sqlite3.c 7.7 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382109383109384109385109386109387109388109389109390109391109392109393109394109395109396109397109398109399109400109401109402109403109404109405109406109407109408109409109410109411109412109413109414109415109416109417109418109419109420109421109422109423109424109425109426109427109428109429109430109431109432109433109434109435109436109437109438109439109440109441109442109443109444109445109446109447109448109449109450109451109452109453109454109455109456109457109458109459109460109461109462109463109464109465109466109467109468109469109470109471109472109473109474109475109476109477109478109479109480109481109482109483109484109485109486109487109488109489109490109491109492109493109494109495109496109497109498109499109500109501109502109503109504109505109506109507109508109509109510109511109512109513109514109515109516109517109518109519109520109521109522109523109524109525109526109527109528109529109530109531109532109533109534109535109536109537109538109539109540109541109542109543109544109545109546109547109548109549109550109551109552109553109554109555109556109557109558109559109560109561109562109563109564109565109566109567109568109569109570109571109572109573109574109575109576109577109578109579109580109581109582109583109584109585109586109587109588109589109590109591109592109593109594109595109596109597109598109599109600109601109602109603109604109605109606109607109608109609109610109611109612109613109614109615109616109617109618109619109620109621109622109623109624109625109626109627109628109629109630109631109632109633109634109635109636109637109638109639109640109641109642109643109644109645109646109647109648109649109650109651109652109653109654109655109656109657109658109659109660109661109662109663109664109665109666109667109668109669109670109671109672109673109674109675109676109677109678109679109680109681109682109683109684109685109686109687109688109689109690109691109692109693109694109695109696109697109698109699109700109701109702109703109704109705109706109707109708109709109710109711109712109713109714109715109716109717109718109719109720109721109722109723109724109725109726109727109728109729109730109731109732109733109734109735109736109737109738109739109740109741109742109743109744109745109746109747109748109749109750109751109752109753109754109755109756109757109758109759109760109761109762109763109764109765109766109767109768109769109770109771109772109773109774109775109776109777109778109779109780109781109782109783109784109785109786109787109788109789109790109791109792109793109794109795109796109797109798109799109800109801109802109803109804109805109806109807109808109809109810109811109812109813109814109815109816109817109818109819109820109821109822109823109824109825109826109827109828109829109830109831109832109833109834109835109836109837109838109839109840109841109842109843109844109845109846109847109848109849109850109851109852109853109854109855109856109857109858109859109860109861109862109863109864109865109866109867109868109869109870109871109872109873109874109875109876109877109878109879109880109881109882109883109884109885109886109887109888109889109890109891109892109893109894109895109896109897109898109899109900109901109902109903109904109905109906109907109908109909109910109911109912109913109914109915109916109917109918109919109920109921109922109923109924109925109926109927109928109929109930109931109932109933109934109935109936109937109938109939109940109941109942109943109944109945109946109947109948109949109950109951109952109953109954109955109956109957109958109959109960109961109962109963109964109965109966109967109968109969109970109971109972109973109974109975109976109977109978109979109980109981109982109983109984109985109986109987109988109989109990109991109992109993109994109995109996109997109998109999110000110001110002110003110004110005110006110007110008110009110010110011110012110013110014110015110016110017110018110019110020110021110022110023110024110025110026110027110028110029110030110031110032110033110034110035110036110037110038110039110040110041110042110043110044110045110046110047110048110049110050110051110052110053110054110055110056110057110058110059110060110061110062110063110064110065110066110067110068110069110070110071110072110073110074110075110076110077110078110079110080110081110082110083110084110085110086110087110088110089110090110091110092110093110094110095110096110097110098110099110100110101110102110103110104110105110106110107110108110109110110110111110112110113110114110115110116110117110118110119110120110121110122110123110124110125110126110127110128110129110130110131110132110133110134110135110136110137110138110139110140110141110142110143110144110145110146110147110148110149110150110151110152110153110154110155110156110157110158110159110160110161110162110163110164110165110166110167110168110169110170110171110172110173110174110175110176110177110178110179110180110181110182110183110184110185110186110187110188110189110190110191110192110193110194110195110196110197110198110199110200110201110202110203110204110205110206110207110208110209110210110211110212110213110214110215110216110217110218110219110220110221110222110223110224110225110226110227110228110229110230110231110232110233110234110235110236110237110238110239110240110241110242110243110244110245110246110247110248110249110250110251110252110253110254110255110256110257110258110259110260110261110262110263110264110265110266110267110268110269110270110271110272110273110274110275110276110277110278110279110280110281110282110283110284110285110286110287110288110289110290110291110292110293110294110295110296110297110298110299110300110301110302110303110304110305110306110307110308110309110310110311110312110313110314110315110316110317110318110319110320110321110322110323110324110325110326110327110328110329110330110331110332110333110334110335110336110337110338110339110340110341110342110343110344110345110346110347110348110349110350110351110352110353110354110355110356110357110358110359110360110361110362110363110364110365110366110367110368110369110370110371110372110373110374110375110376110377110378110379110380110381110382110383110384110385110386110387110388110389110390110391110392110393110394110395110396110397110398110399110400110401110402110403110404110405110406110407110408110409110410110411110412110413110414110415110416110417110418110419110420110421110422110423110424110425110426110427110428110429110430110431110432110433110434110435110436110437110438110439110440110441110442110443110444110445110446110447110448110449110450110451110452110453110454110455110456110457110458110459110460110461110462110463110464110465110466110467110468110469110470110471110472110473110474110475110476110477110478110479110480110481110482110483110484110485110486110487110488110489110490110491110492110493110494110495110496110497110498110499110500110501110502110503110504110505110506110507110508110509110510110511110512110513110514110515110516110517110518110519110520110521110522110523110524110525110526110527110528110529110530110531110532110533110534110535110536110537110538110539110540110541110542110543110544110545110546110547110548110549110550110551110552110553110554110555110556110557110558110559110560110561110562110563110564110565110566110567110568110569110570110571110572110573110574110575110576110577110578110579110580110581110582110583110584110585110586110587110588110589110590110591110592110593110594110595110596110597110598110599110600110601110602110603110604110605110606110607110608110609110610110611110612110613110614110615110616110617110618110619110620110621110622110623110624110625110626110627110628110629110630110631110632110633110634110635110636110637110638110639110640110641110642110643110644110645110646110647110648110649110650110651110652110653110654110655110656110657110658110659110660110661110662110663110664110665110666110667110668110669110670110671110672110673110674110675110676110677110678110679110680110681110682110683110684110685110686110687110688110689110690110691110692110693110694110695110696110697110698110699110700110701110702110703110704110705110706110707110708110709110710110711110712110713110714110715110716110717110718110719110720110721110722110723110724110725110726110727110728110729110730110731110732110733110734110735110736110737110738110739110740110741110742110743110744110745110746110747110748110749110750110751110752110753110754110755110756110757110758110759110760110761110762110763110764110765110766110767110768110769110770110771110772110773110774110775110776110777110778110779110780110781110782110783110784110785110786110787110788110789110790110791110792110793110794110795110796110797110798110799110800110801110802110803110804110805110806110807110808110809110810110811110812110813110814110815110816110817110818110819110820110821110822110823110824110825110826110827110828110829110830110831110832110833110834110835110836110837110838110839110840110841110842110843110844110845110846110847110848110849110850110851110852110853110854110855110856110857110858110859110860110861110862110863110864110865110866110867110868110869110870110871110872110873110874110875110876110877110878110879110880110881110882110883110884110885110886110887110888110889110890110891110892110893110894110895110896110897110898110899110900110901110902110903110904110905110906110907110908110909110910110911110912110913110914110915110916110917110918110919110920110921110922110923110924110925110926110927110928110929110930110931110932110933110934110935110936110937110938110939110940110941110942110943110944110945110946110947110948110949110950110951110952110953110954110955110956110957110958110959110960110961110962110963110964110965110966110967110968110969110970110971110972110973110974110975110976110977110978110979110980110981110982110983110984110985110986110987110988110989110990110991110992110993110994110995110996110997110998110999111000111001111002111003111004111005111006111007111008111009111010111011111012111013111014111015111016111017111018111019111020111021111022111023111024111025111026111027111028111029111030111031111032111033111034111035111036111037111038111039111040111041111042111043111044111045111046111047111048111049111050111051111052111053111054111055111056111057111058111059111060111061111062111063111064111065111066111067111068111069111070111071111072111073111074111075111076111077111078111079111080111081111082111083111084111085111086111087111088111089111090111091111092111093111094111095111096111097111098111099111100111101111102111103111104111105111106111107111108111109111110111111111112111113111114111115111116111117111118111119111120111121111122111123111124111125111126111127111128111129111130111131111132111133111134111135111136111137111138111139111140111141111142111143111144111145111146111147111148111149111150111151111152111153111154111155111156111157111158111159111160111161111162111163111164111165111166111167111168111169111170111171111172111173111174111175111176111177111178111179111180111181111182111183111184111185111186111187111188111189111190111191111192111193111194111195111196111197111198111199111200111201111202111203111204111205111206111207111208111209111210111211111212111213111214111215111216111217111218111219111220111221111222111223111224111225111226111227111228111229111230111231111232111233111234111235111236111237111238111239111240111241111242111243111244111245111246111247111248111249111250111251111252111253111254111255111256111257111258111259111260111261111262111263111264111265111266111267111268111269111270111271111272111273111274111275111276111277111278111279111280111281111282111283111284111285111286111287111288111289111290111291111292111293111294111295111296111297111298111299111300111301111302111303111304111305111306111307111308111309111310111311111312111313111314111315111316111317111318111319111320111321111322111323111324111325111326111327111328111329111330111331111332111333111334111335111336111337111338111339111340111341111342111343111344111345111346111347111348111349111350111351111352111353111354111355111356111357111358111359111360111361111362111363111364111365111366111367111368111369111370111371111372111373111374111375111376111377111378111379111380111381111382111383111384111385111386111387111388111389111390111391111392111393111394111395111396111397111398111399111400111401111402111403111404111405111406111407111408111409111410111411111412111413111414111415111416111417111418111419111420111421111422111423111424111425111426111427111428111429111430111431111432111433111434111435111436111437111438111439111440111441111442111443111444111445111446111447111448111449111450111451111452111453111454111455111456111457111458111459111460111461111462111463111464111465111466111467111468111469111470111471111472111473111474111475111476111477111478111479111480111481111482111483111484111485111486111487111488111489111490111491111492111493111494111495111496111497111498111499111500111501111502111503111504111505111506111507111508111509111510111511111512111513111514111515111516111517111518111519111520111521111522111523111524111525111526111527111528111529111530111531111532111533111534111535111536111537111538111539111540111541111542111543111544111545111546111547111548111549111550111551111552111553111554111555111556111557111558111559111560111561111562111563111564111565111566111567111568111569111570111571111572111573111574111575111576111577111578111579111580111581111582111583111584111585111586111587111588111589111590111591111592111593111594111595111596111597111598111599111600111601111602111603111604111605111606111607111608111609111610111611111612111613111614111615111616111617111618111619111620111621111622111623111624111625111626111627111628111629111630111631111632111633111634111635111636111637111638111639111640111641111642111643111644111645111646111647111648111649111650111651111652111653111654111655111656111657111658111659111660111661111662111663111664111665111666111667111668111669111670111671111672111673111674111675111676111677111678111679111680111681111682111683111684111685111686111687111688111689111690111691111692111693111694111695111696111697111698111699111700111701111702111703111704111705111706111707111708111709111710111711111712111713111714111715111716111717111718111719111720111721111722111723111724111725111726111727111728111729111730111731111732111733111734111735111736111737111738111739111740111741111742111743111744111745111746111747111748111749111750111751111752111753111754111755111756111757111758111759111760111761111762111763111764111765111766111767111768111769111770111771111772111773111774111775111776111777111778111779111780111781111782111783111784111785111786111787111788111789111790111791111792111793111794111795111796111797111798111799111800111801111802111803111804111805111806111807111808111809111810111811111812111813111814111815111816111817111818111819111820111821111822111823111824111825111826111827111828111829111830111831111832111833111834111835111836111837111838111839111840111841111842111843111844111845111846111847111848111849111850111851111852111853111854111855111856111857111858111859111860111861111862111863111864111865111866111867111868111869111870111871111872111873111874111875111876111877111878111879111880111881111882111883111884111885111886111887111888111889111890111891111892111893111894111895111896111897111898111899111900111901111902111903111904111905111906111907111908111909111910111911111912111913111914111915111916111917111918111919111920111921111922111923111924111925111926111927111928111929111930111931111932111933111934111935111936111937111938111939111940111941111942111943111944111945111946111947111948111949111950111951111952111953111954111955111956111957111958111959111960111961111962111963111964111965111966111967111968111969111970111971111972111973111974111975111976111977111978111979111980111981111982111983111984111985111986111987111988111989111990111991111992111993111994111995111996111997111998111999112000112001112002112003112004112005112006112007112008112009112010112011112012112013112014112015112016112017112018112019112020112021112022112023112024112025112026112027112028112029112030112031112032112033112034112035112036112037112038112039112040112041112042112043112044112045112046112047112048112049112050112051112052112053112054112055112056112057112058112059112060112061112062112063112064112065112066112067112068112069112070112071112072112073112074112075112076112077112078112079112080112081112082112083112084112085112086112087112088112089112090112091112092112093112094112095112096112097112098112099112100112101112102112103112104112105112106112107112108112109112110112111112112112113112114112115112116112117112118112119112120112121112122112123112124112125112126112127112128112129112130112131112132112133112134112135112136112137112138112139112140112141112142112143112144112145112146112147112148112149112150112151112152112153112154112155112156112157112158112159112160112161112162112163112164112165112166112167112168112169112170112171112172112173112174112175112176112177112178112179112180112181112182112183112184112185112186112187112188112189112190112191112192112193112194112195112196112197112198112199112200112201112202112203112204112205112206112207112208112209112210112211112212112213112214112215112216112217112218112219112220112221112222112223112224112225112226112227112228112229112230112231112232112233112234112235112236112237112238112239112240112241112242112243112244112245112246112247112248112249112250112251112252112253112254112255112256112257112258112259112260112261112262112263112264112265112266112267112268112269112270112271112272112273112274112275112276112277112278112279112280112281112282112283112284112285112286112287112288112289112290112291112292112293112294112295112296112297112298112299112300112301112302112303112304112305112306112307112308112309112310112311112312112313112314112315112316112317112318112319112320112321112322112323112324112325112326112327112328112329112330112331112332112333112334112335112336112337112338112339112340112341112342112343112344112345112346112347112348112349112350112351112352112353112354112355112356112357112358112359112360112361112362112363112364112365112366112367112368112369112370112371112372112373112374112375112376112377112378112379112380112381112382112383112384112385112386112387112388112389112390112391112392112393112394112395112396112397112398112399112400112401112402112403112404112405112406112407112408112409112410112411112412112413112414112415112416112417112418112419112420112421112422112423112424112425112426112427112428112429112430112431112432112433112434112435112436112437112438112439112440112441112442112443112444112445112446112447112448112449112450112451112452112453112454112455112456112457112458112459112460112461112462112463112464112465112466112467112468112469112470112471112472112473112474112475112476112477112478112479112480112481112482112483112484112485112486112487112488112489112490112491112492112493112494112495112496112497112498112499112500112501112502112503112504112505112506112507112508112509112510112511112512112513112514112515112516112517112518112519112520112521112522112523112524112525112526112527112528112529112530112531112532112533112534112535112536112537112538112539112540112541112542112543112544112545112546112547112548112549112550112551112552112553112554112555112556112557112558112559112560112561112562112563112564112565112566112567112568112569112570112571112572112573112574112575112576112577112578112579112580112581112582112583112584112585112586112587112588112589112590112591112592112593112594112595112596112597112598112599112600112601112602112603112604112605112606112607112608112609112610112611112612112613112614112615112616112617112618112619112620112621112622112623112624112625112626112627112628112629112630112631112632112633112634112635112636112637112638112639112640112641112642112643112644112645112646112647112648112649112650112651112652112653112654112655112656112657112658112659112660112661112662112663112664112665112666112667112668112669112670112671112672112673112674112675112676112677112678112679112680112681112682112683112684112685112686112687112688112689112690112691112692112693112694112695112696112697112698112699112700112701112702112703112704112705112706112707112708112709112710112711112712112713112714112715112716112717112718112719112720112721112722112723112724112725112726112727112728112729112730112731112732112733112734112735112736112737112738112739112740112741112742112743112744112745112746112747112748112749112750112751112752112753112754112755112756112757112758112759112760112761112762112763112764112765112766112767112768112769112770112771112772112773112774112775112776112777112778112779112780112781112782112783112784112785112786112787112788112789112790112791112792112793112794112795112796112797112798112799112800112801112802112803112804112805112806112807112808112809112810112811112812112813112814112815112816112817112818112819112820112821112822112823112824112825112826112827112828112829112830112831112832112833112834112835112836112837112838112839112840112841112842112843112844112845112846112847112848112849112850112851112852112853112854112855112856112857112858112859112860112861112862112863112864112865112866112867112868112869112870112871112872112873112874112875112876112877112878112879112880112881112882112883112884112885112886112887112888112889112890112891112892112893112894112895112896112897112898112899112900112901112902112903112904112905112906112907112908112909112910112911112912112913112914112915112916112917112918112919112920112921112922112923112924112925112926112927112928112929112930112931112932112933112934112935112936112937112938112939112940112941112942112943112944112945112946112947112948112949112950112951112952112953112954112955112956112957112958112959112960112961112962112963112964112965112966112967112968112969112970112971112972112973112974112975112976112977112978112979112980112981112982112983112984112985112986112987112988112989112990112991112992112993112994112995112996112997112998112999113000113001113002113003113004113005113006113007113008113009113010113011113012113013113014113015113016113017113018113019113020113021113022113023113024113025113026113027113028113029113030113031113032113033113034113035113036113037113038113039113040113041113042113043113044113045113046113047113048113049113050113051113052113053113054113055113056113057113058113059113060113061113062113063113064113065113066113067113068113069113070113071113072113073113074113075113076113077113078113079113080113081113082113083113084113085113086113087113088113089113090113091113092113093113094113095113096113097113098113099113100113101113102113103113104113105113106113107113108113109113110113111113112113113113114113115113116113117113118113119113120113121113122113123113124113125113126113127113128113129113130113131113132113133113134113135113136113137113138113139113140113141113142113143113144113145113146113147113148113149113150113151113152113153113154113155113156113157113158113159113160113161113162113163113164113165113166113167113168113169113170113171113172113173113174113175113176113177113178113179113180113181113182113183113184113185113186113187113188113189113190113191113192113193113194113195113196113197113198113199113200113201113202113203113204113205113206113207113208113209113210113211113212113213113214113215113216113217113218113219113220113221113222113223113224113225113226113227113228113229113230113231113232113233113234113235113236113237113238113239113240113241113242113243113244113245113246113247113248113249113250113251113252113253113254113255113256113257113258113259113260113261113262113263113264113265113266113267113268113269113270113271113272113273113274113275113276113277113278113279113280113281113282113283113284113285113286113287113288113289113290113291113292113293113294113295113296113297113298113299113300113301113302113303113304113305113306113307113308113309113310113311113312113313113314113315113316113317113318113319113320113321113322113323113324113325113326113327113328113329113330113331113332113333113334113335113336113337113338113339113340113341113342113343113344113345113346113347113348113349113350113351113352113353113354113355113356113357113358113359113360113361113362113363113364113365113366113367113368113369113370113371113372113373113374113375113376113377113378113379113380113381113382113383113384113385113386113387113388113389113390113391113392113393113394113395113396113397113398113399113400113401113402113403113404113405113406113407113408113409113410113411113412113413113414113415113416113417113418113419113420113421113422113423113424113425113426113427113428113429113430113431113432113433113434113435113436113437113438113439113440113441113442113443113444113445113446113447113448113449113450113451113452113453113454113455113456113457113458113459113460113461113462113463113464113465113466113467113468113469113470113471113472113473113474113475113476113477113478113479113480113481113482113483113484113485113486113487113488113489113490113491113492113493113494113495113496113497113498113499113500113501113502113503113504113505113506113507113508113509113510113511113512113513113514113515113516113517113518113519113520113521113522113523113524113525113526113527113528113529113530113531113532113533113534113535113536113537113538113539113540113541113542113543113544113545113546113547113548113549113550113551113552113553113554113555113556113557113558113559113560113561113562113563113564113565113566113567113568113569113570113571113572113573113574113575113576113577113578113579113580113581113582113583113584113585113586113587113588113589113590113591113592113593113594113595113596113597113598113599113600113601113602113603113604113605113606113607113608113609113610113611113612113613113614113615113616113617113618113619113620113621113622113623113624113625113626113627113628113629113630113631113632113633113634113635113636113637113638113639113640113641113642113643113644113645113646113647113648113649113650113651113652113653113654113655113656113657113658113659113660113661113662113663113664113665113666113667113668113669113670113671113672113673113674113675113676113677113678113679113680113681113682113683113684113685113686113687113688113689113690113691113692113693113694113695113696113697113698113699113700113701113702113703113704113705113706113707113708113709113710113711113712113713113714113715113716113717113718113719113720113721113722113723113724113725113726113727113728113729113730113731113732113733113734113735113736113737113738113739113740113741113742113743113744113745113746113747113748113749113750113751113752113753113754113755113756113757113758113759113760113761113762113763113764113765113766113767113768113769113770113771113772113773113774113775113776113777113778113779113780113781113782113783113784113785113786113787113788113789113790113791113792113793113794113795113796113797113798113799113800113801113802113803113804113805113806113807113808113809113810113811113812113813113814113815113816113817113818113819113820113821113822113823113824113825113826113827113828113829113830113831113832113833113834113835113836113837113838113839113840113841113842113843113844113845113846113847113848113849113850113851113852113853113854113855113856113857113858113859113860113861113862113863113864113865113866113867113868113869113870113871113872113873113874113875113876113877113878113879113880113881113882113883113884113885113886113887113888113889113890113891113892113893113894113895113896113897113898113899113900113901113902113903113904113905113906113907113908113909113910113911113912113913113914113915113916113917113918113919113920113921113922113923113924113925113926113927113928113929113930113931113932113933113934113935113936113937113938113939113940113941113942113943113944113945113946113947113948113949113950113951113952113953113954113955113956113957113958113959113960113961113962113963113964113965113966113967113968113969113970113971113972113973113974113975113976113977113978113979113980113981113982113983113984113985113986113987113988113989113990113991113992113993113994113995113996113997113998113999114000114001114002114003114004114005114006114007114008114009114010114011114012114013114014114015114016114017114018114019114020114021114022114023114024114025114026114027114028114029114030114031114032114033114034114035114036114037114038114039114040114041114042114043114044114045114046114047114048114049114050114051114052114053114054114055114056114057114058114059114060114061114062114063114064114065114066114067114068114069114070114071114072114073114074114075114076114077114078114079114080114081114082114083114084114085114086114087114088114089114090114091114092114093114094114095114096114097114098114099114100114101114102114103114104114105114106114107114108114109114110114111114112114113114114114115114116114117114118114119114120114121114122114123114124114125114126114127114128114129114130114131114132114133114134114135114136114137114138114139114140114141114142114143114144114145114146114147114148114149114150114151114152114153114154114155114156114157114158114159114160114161114162114163114164114165114166114167114168114169114170114171114172114173114174114175114176114177114178114179114180114181114182114183114184114185114186114187114188114189114190114191114192114193114194114195114196114197114198114199114200114201114202114203114204114205114206114207114208114209114210114211114212114213114214114215114216114217114218114219114220114221114222114223114224114225114226114227114228114229114230114231114232114233114234114235114236114237114238114239114240114241114242114243114244114245114246114247114248114249114250114251114252114253114254114255114256114257114258114259114260114261114262114263114264114265114266114267114268114269114270114271114272114273114274114275114276114277114278114279114280114281114282114283114284114285114286114287114288114289114290114291114292114293114294114295114296114297114298114299114300114301114302114303114304114305114306114307114308114309114310114311114312114313114314114315114316114317114318114319114320114321114322114323114324114325114326114327114328114329114330114331114332114333114334114335114336114337114338114339114340114341114342114343114344114345114346114347114348114349114350114351114352114353114354114355114356114357114358114359114360114361114362114363114364114365114366114367114368114369114370114371114372114373114374114375114376114377114378114379114380114381114382114383114384114385114386114387114388114389114390114391114392114393114394114395114396114397114398114399114400114401114402114403114404114405114406114407114408114409114410114411114412114413114414114415114416114417114418114419114420114421114422114423114424114425114426114427114428114429114430114431114432114433114434114435114436114437114438114439114440114441114442114443114444114445114446114447114448114449114450114451114452114453114454114455114456114457114458114459114460114461114462114463114464114465114466114467114468114469114470114471114472114473114474114475114476114477114478114479114480114481114482114483114484114485114486114487114488114489114490114491114492114493114494114495114496114497114498114499114500114501114502114503114504114505114506114507114508114509114510114511114512114513114514114515114516114517114518114519114520114521114522114523114524114525114526114527114528114529114530114531114532114533114534114535114536114537114538114539114540114541114542114543114544114545114546114547114548114549114550114551114552114553114554114555114556114557114558114559114560114561114562114563114564114565114566114567114568114569114570114571114572114573114574114575114576114577114578114579114580114581114582114583114584114585114586114587114588114589114590114591114592114593114594114595114596114597114598114599114600114601114602114603114604114605114606114607114608114609114610114611114612114613114614114615114616114617114618114619114620114621114622114623114624114625114626114627114628114629114630114631114632114633114634114635114636114637114638114639114640114641114642114643114644114645114646114647114648114649114650114651114652114653114654114655114656114657114658114659114660114661114662114663114664114665114666114667114668114669114670114671114672114673114674114675114676114677114678114679114680114681114682114683114684114685114686114687114688114689114690114691114692114693114694114695114696114697114698114699114700114701114702114703114704114705114706114707114708114709114710114711114712114713114714114715114716114717114718114719114720114721114722114723114724114725114726114727114728114729114730114731114732114733114734114735114736114737114738114739114740114741114742114743114744114745114746114747114748114749114750114751114752114753114754114755114756114757114758114759114760114761114762114763114764114765114766114767114768114769114770114771114772114773114774114775114776114777114778114779114780114781114782114783114784114785114786114787114788114789114790114791114792114793114794114795114796114797114798114799114800114801114802114803114804114805114806114807114808114809114810114811114812114813114814114815114816114817114818114819114820114821114822114823114824114825114826114827114828114829114830114831114832114833114834114835114836114837114838114839114840114841114842114843114844114845114846114847114848114849114850114851114852114853114854114855114856114857114858114859114860114861114862114863114864114865114866114867114868114869114870114871114872114873114874114875114876114877114878114879114880114881114882114883114884114885114886114887114888114889114890114891114892114893114894114895114896114897114898114899114900114901114902114903114904114905114906114907114908114909114910114911114912114913114914114915114916114917114918114919114920114921114922114923114924114925114926114927114928114929114930114931114932114933114934114935114936114937114938114939114940114941114942114943114944114945114946114947114948114949114950114951114952114953114954114955114956114957114958114959114960114961114962114963114964114965114966114967114968114969114970114971114972114973114974114975114976114977114978114979114980114981114982114983114984114985114986114987114988114989114990114991114992114993114994114995114996114997114998114999115000115001115002115003115004115005115006115007115008115009115010115011115012115013115014115015115016115017115018115019115020115021115022115023115024115025115026115027115028115029115030115031115032115033115034115035115036115037115038115039115040115041115042115043115044115045115046115047115048115049115050115051115052115053115054115055115056115057115058115059115060115061115062115063115064115065115066115067115068115069115070115071115072115073115074115075115076115077115078115079115080115081115082115083115084115085115086115087115088115089115090115091115092115093115094115095115096115097115098115099115100115101115102115103115104115105115106115107115108115109115110115111115112115113115114115115115116115117115118115119115120115121115122115123115124115125115126115127115128115129115130115131115132115133115134115135115136115137115138115139115140115141115142115143115144115145115146115147115148115149115150115151115152115153115154115155115156115157115158115159115160115161115162115163115164115165115166115167115168115169115170115171115172115173115174115175115176115177115178115179115180115181115182115183115184115185115186115187115188115189115190115191115192115193115194115195115196115197115198115199115200115201115202115203115204115205115206115207115208115209115210115211115212115213115214115215115216115217115218115219115220115221115222115223115224115225115226115227115228115229115230115231115232115233115234115235115236115237115238115239115240115241115242115243115244115245115246115247115248115249115250115251115252115253115254115255115256115257115258115259115260115261115262115263115264115265115266115267115268115269115270115271115272115273115274115275115276115277115278115279115280115281115282115283115284115285115286115287115288115289115290115291115292115293115294115295115296115297115298115299115300115301115302115303115304115305115306115307115308115309115310115311115312115313115314115315115316115317115318115319115320115321115322115323115324115325115326115327115328115329115330115331115332115333115334115335115336115337115338115339115340115341115342115343115344115345115346115347115348115349115350115351115352115353115354115355115356115357115358115359115360115361115362115363115364115365115366115367115368115369115370115371115372115373115374115375115376115377115378115379115380115381115382115383115384115385115386115387115388115389115390115391115392115393115394115395115396115397115398115399115400115401115402115403115404115405115406115407115408115409115410115411115412115413115414115415115416115417115418115419115420115421115422115423115424115425115426115427115428115429115430115431115432115433115434115435115436115437115438115439115440115441115442115443115444115445115446115447115448115449115450115451115452115453115454115455115456115457115458115459115460115461115462115463115464115465115466115467115468115469115470115471115472115473115474115475115476115477115478115479115480115481115482115483115484115485115486115487115488115489115490115491115492115493115494115495115496115497115498115499115500115501115502115503115504115505115506115507115508115509115510115511115512115513115514115515115516115517115518115519115520115521115522115523115524115525115526115527115528115529115530115531115532115533115534115535115536115537115538115539115540115541115542115543115544115545115546115547115548115549115550115551115552115553115554115555115556115557115558115559115560115561115562115563115564115565115566115567115568115569115570115571115572115573115574115575115576115577115578115579115580115581115582115583115584115585115586115587115588115589115590115591115592115593115594115595115596115597115598115599115600115601115602115603115604115605115606115607115608115609115610115611115612115613115614115615115616115617115618115619115620115621115622115623115624115625115626115627115628115629115630115631115632115633115634115635115636115637115638115639115640115641115642115643115644115645115646115647115648115649115650115651115652115653115654115655115656115657115658115659115660115661115662115663115664115665115666115667115668115669115670115671115672115673115674115675115676115677115678115679115680115681115682115683115684115685115686115687115688115689115690115691115692115693115694115695115696115697115698115699115700115701115702115703115704115705115706115707115708115709115710115711115712115713115714115715115716115717115718115719115720115721115722115723115724115725115726115727115728115729115730115731115732115733115734115735115736115737115738115739115740115741115742115743115744115745115746115747115748115749115750115751115752115753115754115755115756115757115758115759115760115761115762115763115764115765115766115767115768115769115770115771115772115773115774115775115776115777115778115779115780115781115782115783115784115785115786115787115788115789115790115791115792115793115794115795115796115797115798115799115800115801115802115803115804115805115806115807115808115809115810115811115812115813115814115815115816115817115818115819115820115821115822115823115824115825115826115827115828115829115830115831115832115833115834115835115836115837115838115839115840115841115842115843115844115845115846115847115848115849115850115851115852115853115854115855115856115857115858115859115860115861115862115863115864115865115866115867115868115869115870115871115872115873115874115875115876115877115878115879115880115881115882115883115884115885115886115887115888115889115890115891115892115893115894115895115896115897115898115899115900115901115902115903115904115905115906115907115908115909115910115911115912115913115914115915115916115917115918115919115920115921115922115923115924115925115926115927115928115929115930115931115932115933115934115935115936115937115938115939115940115941115942115943115944115945115946115947115948115949115950115951115952115953115954115955115956115957115958115959115960115961115962115963115964115965115966115967115968115969115970115971115972115973115974115975115976115977115978115979115980115981115982115983115984115985115986115987115988115989115990115991115992115993115994115995115996115997115998115999116000116001116002116003116004116005116006116007116008116009116010116011116012116013116014116015116016116017116018116019116020116021116022116023116024116025116026116027116028116029116030116031116032116033116034116035116036116037116038116039116040116041116042116043116044116045116046116047116048116049116050116051116052116053116054116055116056116057116058116059116060116061116062116063116064116065116066116067116068116069116070116071116072116073116074116075116076116077116078116079116080116081116082116083116084116085116086116087116088116089116090116091116092116093116094116095116096116097116098116099116100116101116102116103116104116105116106116107116108116109116110116111116112116113116114116115116116116117116118116119116120116121116122116123116124116125116126116127116128116129116130116131116132116133116134116135116136116137116138116139116140116141116142116143116144116145116146116147116148116149116150116151116152116153116154116155116156116157116158116159116160116161116162116163116164116165116166116167116168116169116170116171116172116173116174116175116176116177116178116179116180116181116182116183116184116185116186116187116188116189116190116191116192116193116194116195116196116197116198116199116200116201116202116203116204116205116206116207116208116209116210116211116212116213116214116215116216116217116218116219116220116221116222116223116224116225116226116227116228116229116230116231116232116233116234116235116236116237116238116239116240116241116242116243116244116245116246116247116248116249116250116251116252116253116254116255116256116257116258116259116260116261116262116263116264116265116266116267116268116269116270116271116272116273116274116275116276116277116278116279116280116281116282116283116284116285116286116287116288116289116290116291116292116293116294116295116296116297116298116299116300116301116302116303116304116305116306116307116308116309116310116311116312116313116314116315116316116317116318116319116320116321116322116323116324116325116326116327116328116329116330116331116332116333116334116335116336116337116338116339116340116341116342116343116344116345116346116347116348116349116350116351116352116353116354116355116356116357116358116359116360116361116362116363116364116365116366116367116368116369116370116371116372116373116374116375116376116377116378116379116380116381116382116383116384116385116386116387116388116389116390116391116392116393116394116395116396116397116398116399116400116401116402116403116404116405116406116407116408116409116410116411116412116413116414116415116416116417116418116419116420116421116422116423116424116425116426116427116428116429116430116431116432116433116434116435116436116437116438116439116440116441116442116443116444116445116446116447116448116449116450116451116452116453116454116455116456116457116458116459116460116461116462116463116464116465116466116467116468116469116470116471116472116473116474116475116476116477116478116479116480116481116482116483116484116485116486116487116488116489116490116491116492116493116494116495116496116497116498116499116500116501116502116503116504116505116506116507116508116509116510116511116512116513116514116515116516116517116518116519116520116521116522116523116524116525116526116527116528116529116530116531116532116533116534116535116536116537116538116539116540116541116542116543116544116545116546116547116548116549116550116551116552116553116554116555116556116557116558116559116560116561116562116563116564116565116566116567116568116569116570116571116572116573116574116575116576116577116578116579116580116581116582116583116584116585116586116587116588116589116590116591116592116593116594116595116596116597116598116599116600116601116602116603116604116605116606116607116608116609116610116611116612116613116614116615116616116617116618116619116620116621116622116623116624116625116626116627116628116629116630116631116632116633116634116635116636116637116638116639116640116641116642116643116644116645116646116647116648116649116650116651116652116653116654116655116656116657116658116659116660116661116662116663116664116665116666116667116668116669116670116671116672116673116674116675116676116677116678116679116680116681116682116683116684116685116686116687116688116689116690116691116692116693116694116695116696116697116698116699116700116701116702116703116704116705116706116707116708116709116710116711116712116713116714116715116716116717116718116719116720116721116722116723116724116725116726116727116728116729116730116731116732116733116734116735116736116737116738116739116740116741116742116743116744116745116746116747116748116749116750116751116752116753116754116755116756116757116758116759116760116761116762116763116764116765116766116767116768116769116770116771116772116773116774116775116776116777116778116779116780116781116782116783116784116785116786116787116788116789116790116791116792116793116794116795116796116797116798116799116800116801116802116803116804116805116806116807116808116809116810116811116812116813116814116815116816116817116818116819116820116821116822116823116824116825116826116827116828116829116830116831116832116833116834116835116836116837116838116839116840116841116842116843116844116845116846116847116848116849116850116851116852116853116854116855116856116857116858116859116860116861116862116863116864116865116866116867116868116869116870116871116872116873116874116875116876116877116878116879116880116881116882116883116884116885116886116887116888116889116890116891116892116893116894116895116896116897116898116899116900116901116902116903116904116905116906116907116908116909116910116911116912116913116914116915116916116917116918116919116920116921116922116923116924116925116926116927116928116929116930116931116932116933116934116935116936116937116938116939116940116941116942116943116944116945116946116947116948116949116950116951116952116953116954116955116956116957116958116959116960116961116962116963116964116965116966116967116968116969116970116971116972116973116974116975116976116977116978116979116980116981116982116983116984116985116986116987116988116989116990116991116992116993116994116995116996116997116998116999117000117001117002117003117004117005117006117007117008117009117010117011117012117013117014117015117016117017117018117019117020117021117022117023117024117025117026117027117028117029117030117031117032117033117034117035117036117037117038117039117040117041117042117043117044117045117046117047117048117049117050117051117052117053117054117055117056117057117058117059117060117061117062117063117064117065117066117067117068117069117070117071117072117073117074117075117076117077117078117079117080117081117082117083117084117085117086117087117088117089117090117091117092117093117094117095117096117097117098117099117100117101117102117103117104117105117106117107117108117109117110117111117112117113117114117115117116117117117118117119117120117121117122117123117124117125117126117127117128117129117130117131117132117133117134117135117136117137117138117139117140117141117142117143117144117145117146117147117148117149117150117151117152117153117154117155117156117157117158117159117160117161117162117163117164117165117166117167117168117169117170117171117172117173117174117175117176117177117178117179117180117181117182117183117184117185117186117187117188117189117190117191117192117193117194117195117196117197117198117199117200117201117202117203117204117205117206117207117208117209117210117211117212117213117214117215117216117217117218117219117220117221117222117223117224117225117226117227117228117229117230117231117232117233117234117235117236117237117238117239117240117241117242117243117244117245117246117247117248117249117250117251117252117253117254117255117256117257117258117259117260117261117262117263117264117265117266117267117268117269117270117271117272117273117274117275117276117277117278117279117280117281117282117283117284117285117286117287117288117289117290117291117292117293117294117295117296117297117298117299117300117301117302117303117304117305117306117307117308117309117310117311117312117313117314117315117316117317117318117319117320117321117322117323117324117325117326117327117328117329117330117331117332117333117334117335117336117337117338117339117340117341117342117343117344117345117346117347117348117349117350117351117352117353117354117355117356117357117358117359117360117361117362117363117364117365117366117367117368117369117370117371117372117373117374117375117376117377117378117379117380117381117382117383117384117385117386117387117388117389117390117391117392117393117394117395117396117397117398117399117400117401117402117403117404117405117406117407117408117409117410117411117412117413117414117415117416117417117418117419117420117421117422117423117424117425117426117427117428117429117430117431117432117433117434117435117436117437117438117439117440117441117442117443117444117445117446117447117448117449117450117451117452117453117454117455117456117457117458117459117460117461117462117463117464117465117466117467117468117469117470117471117472117473117474117475117476117477117478117479117480117481117482117483117484117485117486117487117488117489117490117491117492117493117494117495117496117497117498117499117500117501117502117503117504117505117506117507117508117509117510117511117512117513117514117515117516117517117518117519117520117521117522117523117524117525117526117527117528117529117530117531117532117533117534117535117536117537117538117539117540117541117542117543117544117545117546117547117548117549117550117551117552117553117554117555117556117557117558117559117560117561117562117563117564117565117566117567117568117569117570117571117572117573117574117575117576117577117578117579117580117581117582117583117584117585117586117587117588117589117590117591117592117593117594117595117596117597117598117599117600117601117602117603117604117605117606117607117608117609117610117611117612117613117614117615117616117617117618117619117620117621117622117623117624117625117626117627117628117629117630117631117632117633117634117635117636117637117638117639117640117641117642117643117644117645117646117647117648117649117650117651117652117653117654117655117656117657117658117659117660117661117662117663117664117665117666117667117668117669117670117671117672117673117674117675117676117677117678117679117680117681117682117683117684117685117686117687117688117689117690117691117692117693117694117695117696117697117698117699117700117701117702117703117704117705117706117707117708117709117710117711117712117713117714117715117716117717117718117719117720117721117722117723117724117725117726117727117728117729117730117731117732117733117734117735117736117737117738117739117740117741117742117743117744117745117746117747117748117749117750117751117752117753117754117755117756117757117758117759117760117761117762117763117764117765117766117767117768117769117770117771117772117773117774117775117776117777117778117779117780117781117782117783117784117785117786117787117788117789117790117791117792117793117794117795117796117797117798117799117800117801117802117803117804117805117806117807117808117809117810117811117812117813117814117815117816117817117818117819117820117821117822117823117824117825117826117827117828117829117830117831117832117833117834117835117836117837117838117839117840117841117842117843117844117845117846117847117848117849117850117851117852117853117854117855117856117857117858117859117860117861117862117863117864117865117866117867117868117869117870117871117872117873117874117875117876117877117878117879117880117881117882117883117884117885117886117887117888117889117890117891117892117893117894117895117896117897117898117899117900117901117902117903117904117905117906117907117908117909117910117911117912117913117914117915117916117917117918117919117920117921117922117923117924117925117926117927117928117929117930117931117932117933117934117935117936117937117938117939117940117941117942117943117944117945117946117947117948117949117950117951117952117953117954117955117956117957117958117959117960117961117962117963117964117965117966117967117968117969117970117971117972117973117974117975117976117977117978117979117980117981117982117983117984117985117986117987117988117989117990117991117992117993117994117995117996117997117998117999118000118001118002118003118004118005118006118007118008118009118010118011118012118013118014118015118016118017118018118019118020118021118022118023118024118025118026118027118028118029118030118031118032118033118034118035118036118037118038118039118040118041118042118043118044118045118046118047118048118049118050118051118052118053118054118055118056118057118058118059118060118061118062118063118064118065118066118067118068118069118070118071118072118073118074118075118076118077118078118079118080118081118082118083118084118085118086118087118088118089118090118091118092118093118094118095118096118097118098118099118100118101118102118103118104118105118106118107118108118109118110118111118112118113118114118115118116118117118118118119118120118121118122118123118124118125118126118127118128118129118130118131118132118133118134118135118136118137118138118139118140118141118142118143118144118145118146118147118148118149118150118151118152118153118154118155118156118157118158118159118160118161118162118163118164118165118166118167118168118169118170118171118172118173118174118175118176118177118178118179118180118181118182118183118184118185118186118187118188118189118190118191118192118193118194118195118196118197118198118199118200118201118202118203118204118205118206118207118208118209118210118211118212118213118214118215118216118217118218118219118220118221118222118223118224118225118226118227118228118229118230118231118232118233118234118235118236118237118238118239118240118241118242118243118244118245118246118247118248118249118250118251118252118253118254118255118256118257118258118259118260118261118262118263118264118265118266118267118268118269118270118271118272118273118274118275118276118277118278118279118280118281118282118283118284118285118286118287118288118289118290118291118292118293118294118295118296118297118298118299118300118301118302118303118304118305118306118307118308118309118310118311118312118313118314118315118316118317118318118319118320118321118322118323118324118325118326118327118328118329118330118331118332118333118334118335118336118337118338118339118340118341118342118343118344118345118346118347118348118349118350118351118352118353118354118355118356118357118358118359118360118361118362118363118364118365118366118367118368118369118370118371118372118373118374118375118376118377118378118379118380118381118382118383118384118385118386118387118388118389118390118391118392118393118394118395118396118397118398118399118400118401118402118403118404118405118406118407118408118409118410118411118412118413118414118415118416118417118418118419118420118421118422118423118424118425118426118427118428118429118430118431118432118433118434118435118436118437118438118439118440118441118442118443118444118445118446118447118448118449118450118451118452118453118454118455118456118457118458118459118460118461118462118463118464118465118466118467118468118469118470118471118472118473118474118475118476118477118478118479118480118481118482118483118484118485118486118487118488118489118490118491118492118493118494118495118496118497118498118499118500118501118502118503118504118505118506118507118508118509118510118511118512118513118514118515118516118517118518118519118520118521118522118523118524118525118526118527118528118529118530118531118532118533118534118535118536118537118538118539118540118541118542118543118544118545118546118547118548118549118550118551118552118553118554118555118556118557118558118559118560118561118562118563118564118565118566118567118568118569118570118571118572118573118574118575118576118577118578118579118580118581118582118583118584118585118586118587118588118589118590118591118592118593118594118595118596118597118598118599118600118601118602118603118604118605118606118607118608118609118610118611118612118613118614118615118616118617118618118619118620118621118622118623118624118625118626118627118628118629118630118631118632118633118634118635118636118637118638118639118640118641118642118643118644118645118646118647118648118649118650118651118652118653118654118655118656118657118658118659118660118661118662118663118664118665118666118667118668118669118670118671118672118673118674118675118676118677118678118679118680118681118682118683118684118685118686118687118688118689118690118691118692118693118694118695118696118697118698118699118700118701118702118703118704118705118706118707118708118709118710118711118712118713118714118715118716118717118718118719118720118721118722118723118724118725118726118727118728118729118730118731118732118733118734118735118736118737118738118739118740118741118742118743118744118745118746118747118748118749118750118751118752118753118754118755118756118757118758118759118760118761118762118763118764118765118766118767118768118769118770118771118772118773118774118775118776118777118778118779118780118781118782118783118784118785118786118787118788118789118790118791118792118793118794118795118796118797118798118799118800118801118802118803118804118805118806118807118808118809118810118811118812118813118814118815118816118817118818118819118820118821118822118823118824118825118826118827118828118829118830118831118832118833118834118835118836118837118838118839118840118841118842118843118844118845118846118847118848118849118850118851118852118853118854118855118856118857118858118859118860118861118862118863118864118865118866118867118868118869118870118871118872118873118874118875118876118877118878118879118880118881118882118883118884118885118886118887118888118889118890118891118892118893118894118895118896118897118898118899118900118901118902118903118904118905118906118907118908118909118910118911118912118913118914118915118916118917118918118919118920118921118922118923118924118925118926118927118928118929118930118931118932118933118934118935118936118937118938118939118940118941118942118943118944118945118946118947118948118949118950118951118952118953118954118955118956118957118958118959118960118961118962118963118964118965118966118967118968118969118970118971118972118973118974118975118976118977118978118979118980118981118982118983118984118985118986118987118988118989118990118991118992118993118994118995118996118997118998118999119000119001119002119003119004119005119006119007119008119009119010119011119012119013119014119015119016119017119018119019119020119021119022119023119024119025119026119027119028119029119030119031119032119033119034119035119036119037119038119039119040119041119042119043119044119045119046119047119048119049119050119051119052119053119054119055119056119057119058119059119060119061119062119063119064119065119066119067119068119069119070119071119072119073119074119075119076119077119078119079119080119081119082119083119084119085119086119087119088119089119090119091119092119093119094119095119096119097119098119099119100119101119102119103119104119105119106119107119108119109119110119111119112119113119114119115119116119117119118119119119120119121119122119123119124119125119126119127119128119129119130119131119132119133119134119135119136119137119138119139119140119141119142119143119144119145119146119147119148119149119150119151119152119153119154119155119156119157119158119159119160119161119162119163119164119165119166119167119168119169119170119171119172119173119174119175119176119177119178119179119180119181119182119183119184119185119186119187119188119189119190119191119192119193119194119195119196119197119198119199119200119201119202119203119204119205119206119207119208119209119210119211119212119213119214119215119216119217119218119219119220119221119222119223119224119225119226119227119228119229119230119231119232119233119234119235119236119237119238119239119240119241119242119243119244119245119246119247119248119249119250119251119252119253119254119255119256119257119258119259119260119261119262119263119264119265119266119267119268119269119270119271119272119273119274119275119276119277119278119279119280119281119282119283119284119285119286119287119288119289119290119291119292119293119294119295119296119297119298119299119300119301119302119303119304119305119306119307119308119309119310119311119312119313119314119315119316119317119318119319119320119321119322119323119324119325119326119327119328119329119330119331119332119333119334119335119336119337119338119339119340119341119342119343119344119345119346119347119348119349119350119351119352119353119354119355119356119357119358119359119360119361119362119363119364119365119366119367119368119369119370119371119372119373119374119375119376119377119378119379119380119381119382119383119384119385119386119387119388119389119390119391119392119393119394119395119396119397119398119399119400119401119402119403119404119405119406119407119408119409119410119411119412119413119414119415119416119417119418119419119420119421119422119423119424119425119426119427119428119429119430119431119432119433119434119435119436119437119438119439119440119441119442119443119444119445119446119447119448119449119450119451119452119453119454119455119456119457119458119459119460119461119462119463119464119465119466119467119468119469119470119471119472119473119474119475119476119477119478119479119480119481119482119483119484119485119486119487119488119489119490119491119492119493119494119495119496119497119498119499119500119501119502119503119504119505119506119507119508119509119510119511119512119513119514119515119516119517119518119519119520119521119522119523119524119525119526119527119528119529119530119531119532119533119534119535119536119537119538119539119540119541119542119543119544119545119546119547119548119549119550119551119552119553119554119555119556119557119558119559119560119561119562119563119564119565119566119567119568119569119570119571119572119573119574119575119576119577119578119579119580119581119582119583119584119585119586119587119588119589119590119591119592119593119594119595119596119597119598119599119600119601119602119603119604119605119606119607119608119609119610119611119612119613119614119615119616119617119618119619119620119621119622119623119624119625119626119627119628119629119630119631119632119633119634119635119636119637119638119639119640119641119642119643119644119645119646119647119648119649119650119651119652119653119654119655119656119657119658119659119660119661119662119663119664119665119666119667119668119669119670119671119672119673119674119675119676119677119678119679119680119681119682119683119684119685119686119687119688119689119690119691119692119693119694119695119696119697119698119699119700119701119702119703119704119705119706119707119708119709119710119711119712119713119714119715119716119717119718119719119720119721119722119723119724119725119726119727119728119729119730119731119732119733119734119735119736119737119738119739119740119741119742119743119744119745119746119747119748119749119750119751119752119753119754119755119756119757119758119759119760119761119762119763119764119765119766119767119768119769119770119771119772119773119774119775119776119777119778119779119780119781119782119783119784119785119786119787119788119789119790119791119792119793119794119795119796119797119798119799119800119801119802119803119804119805119806119807119808119809119810119811119812119813119814119815119816119817119818119819119820119821119822119823119824119825119826119827119828119829119830119831119832119833119834119835119836119837119838119839119840119841119842119843119844119845119846119847119848119849119850119851119852119853119854119855119856119857119858119859119860119861119862119863119864119865119866119867119868119869119870119871119872119873119874119875119876119877119878119879119880119881119882119883119884119885119886119887119888119889119890119891119892119893119894119895119896119897119898119899119900119901119902119903119904119905119906119907119908119909119910119911119912119913119914119915119916119917119918119919119920119921119922119923119924119925119926119927119928119929119930119931119932119933119934119935119936119937119938119939119940119941119942119943119944119945119946119947119948119949119950119951119952119953119954119955119956119957119958119959119960119961119962119963119964119965119966119967119968119969119970119971119972119973119974119975119976119977119978119979119980119981119982119983119984119985119986119987119988119989119990119991119992119993119994119995119996119997119998119999120000120001120002120003120004120005120006120007120008120009120010120011120012120013120014120015120016120017120018120019120020120021120022120023120024120025120026120027120028120029120030120031120032120033120034120035120036120037120038120039120040120041120042120043120044120045120046120047120048120049120050120051120052120053120054120055120056120057120058120059120060120061120062120063120064120065120066120067120068120069120070120071120072120073120074120075120076120077120078120079120080120081120082120083120084120085120086120087120088120089120090120091120092120093120094120095120096120097120098120099120100120101120102120103120104120105120106120107120108120109120110120111120112120113120114120115120116120117120118120119120120120121120122120123120124120125120126120127120128120129120130120131120132120133120134120135120136120137120138120139120140120141120142120143120144120145120146120147120148120149120150120151120152120153120154120155120156120157120158120159120160120161120162120163120164120165120166120167120168120169120170120171120172120173120174120175120176120177120178120179120180120181120182120183120184120185120186120187120188120189120190120191120192120193120194120195120196120197120198120199120200120201120202120203120204120205120206120207120208120209120210120211120212120213120214120215120216120217120218120219120220120221120222120223120224120225120226120227120228120229120230120231120232120233120234120235120236120237120238120239120240120241120242120243120244120245120246120247120248120249120250120251120252120253120254120255120256120257120258120259120260120261120262120263120264120265120266120267120268120269120270120271120272120273120274120275120276120277120278120279120280120281120282120283120284120285120286120287120288120289120290120291120292120293120294120295120296120297120298120299120300120301120302120303120304120305120306120307120308120309120310120311120312120313120314120315120316120317120318120319120320120321120322120323120324120325120326120327120328120329120330120331120332120333120334120335120336120337120338120339120340120341120342120343120344120345120346120347120348120349120350120351120352120353120354120355120356120357120358120359120360120361120362120363120364120365120366120367120368120369120370120371120372120373120374120375120376120377120378120379120380120381120382120383120384120385120386120387120388120389120390120391120392120393120394120395120396120397120398120399120400120401120402120403120404120405120406120407120408120409120410120411120412120413120414120415120416120417120418120419120420120421120422120423120424120425120426120427120428120429120430120431120432120433120434120435120436120437120438120439120440120441120442120443120444120445120446120447120448120449120450120451120452120453120454120455120456120457120458120459120460120461120462120463120464120465120466120467120468120469120470120471120472120473120474120475120476120477120478120479120480120481120482120483120484120485120486120487120488120489120490120491120492120493120494120495120496120497120498120499120500120501120502120503120504120505120506120507120508120509120510120511120512120513120514120515120516120517120518120519120520120521120522120523120524120525120526120527120528120529120530120531120532120533120534120535120536120537120538120539120540120541120542120543120544120545120546120547120548120549120550120551120552120553120554120555120556120557120558120559120560120561120562120563120564120565120566120567120568120569120570120571120572120573120574120575120576120577120578120579120580120581120582120583120584120585120586120587120588120589120590120591120592120593120594120595120596120597120598120599120600120601120602120603120604120605120606120607120608120609120610120611120612120613120614120615120616120617120618120619120620120621120622120623120624120625120626120627120628120629120630120631120632120633120634120635120636120637120638120639120640120641120642120643120644120645120646120647120648120649120650120651120652120653120654120655120656120657120658120659120660120661120662120663120664120665120666120667120668120669120670120671120672120673120674120675120676120677120678120679120680120681120682120683120684120685120686120687120688120689120690120691120692120693120694120695120696120697120698120699120700120701120702120703120704120705120706120707120708120709120710120711120712120713120714120715120716120717120718120719120720120721120722120723120724120725120726120727120728120729120730120731120732120733120734120735120736120737120738120739120740120741120742120743120744120745120746120747120748120749120750120751120752120753120754120755120756120757120758120759120760120761120762120763120764120765120766120767120768120769120770120771120772120773120774120775120776120777120778120779120780120781120782120783120784120785120786120787120788120789120790120791120792120793120794120795120796120797120798120799120800120801120802120803120804120805120806120807120808120809120810120811120812120813120814120815120816120817120818120819120820120821120822120823120824120825120826120827120828120829120830120831120832120833120834120835120836120837120838120839120840120841120842120843120844120845120846120847120848120849120850120851120852120853120854120855120856120857120858120859120860120861120862120863120864120865120866120867120868120869120870120871120872120873120874120875120876120877120878120879120880120881120882120883120884120885120886120887120888120889120890120891120892120893120894120895120896120897120898120899120900120901120902120903120904120905120906120907120908120909120910120911120912120913120914120915120916120917120918120919120920120921120922120923120924120925120926120927120928120929120930120931120932120933120934120935120936120937120938120939120940120941120942120943120944120945120946120947120948120949120950120951120952120953120954120955120956120957120958120959120960120961120962120963120964120965120966120967120968120969120970120971120972120973120974120975120976120977120978120979120980120981120982120983120984120985120986120987120988120989120990120991120992120993120994120995120996120997120998120999121000121001121002121003121004121005121006121007121008121009121010121011121012121013121014121015121016121017121018121019121020121021121022121023121024121025121026121027121028121029121030121031121032121033121034121035121036121037121038121039121040121041121042121043121044121045121046121047121048121049121050121051121052121053121054121055121056121057121058121059121060121061121062121063121064121065121066121067121068121069121070121071121072121073121074121075121076121077121078121079121080121081121082121083121084121085121086121087121088121089121090121091121092121093121094121095121096121097121098121099121100121101121102121103121104121105121106121107121108121109121110121111121112121113121114121115121116121117121118121119121120121121121122121123121124121125121126121127121128121129121130121131121132121133121134121135121136121137121138121139121140121141121142121143121144121145121146121147121148121149121150121151121152121153121154121155121156121157121158121159121160121161121162121163121164121165121166121167121168121169121170121171121172121173121174121175121176121177121178121179121180121181121182121183121184121185121186121187121188121189121190121191121192121193121194121195121196121197121198121199121200121201121202121203121204121205121206121207121208121209121210121211121212121213121214121215121216121217121218121219121220121221121222121223121224121225121226121227121228121229121230121231121232121233121234121235121236121237121238121239121240121241121242121243121244121245121246121247121248121249121250121251121252121253121254121255121256121257121258121259121260121261121262121263121264121265121266121267121268121269121270121271121272121273121274121275121276121277121278121279121280121281121282121283121284121285121286121287121288121289121290121291121292121293121294121295121296121297121298121299121300121301121302121303121304121305121306121307121308121309121310121311121312121313121314121315121316121317121318121319121320121321121322121323121324121325121326121327121328121329121330121331121332121333121334121335121336121337121338121339121340121341121342121343121344121345121346121347121348121349121350121351121352121353121354121355121356121357121358121359121360121361121362121363121364121365121366121367121368121369121370121371121372121373121374121375121376121377121378121379121380121381121382121383121384121385121386121387121388121389121390121391121392121393121394121395121396121397121398121399121400121401121402121403121404121405121406121407121408121409121410121411121412121413121414121415121416121417121418121419121420121421121422121423121424121425121426121427121428121429121430121431121432121433121434121435121436121437121438121439121440121441121442121443121444121445121446121447121448121449121450121451121452121453121454121455121456121457121458121459121460121461121462121463121464121465121466121467121468121469121470121471121472121473121474121475121476121477121478121479121480121481121482121483121484121485121486121487121488121489121490121491121492121493121494121495121496121497121498121499121500121501121502121503121504121505121506121507121508121509121510121511121512121513121514121515121516121517121518121519121520121521121522121523121524121525121526121527121528121529121530121531121532121533121534121535121536121537121538121539121540121541121542121543121544121545121546121547121548121549121550121551121552121553121554121555121556121557121558121559121560121561121562121563121564121565121566121567121568121569121570121571121572121573121574121575121576121577121578121579121580121581121582121583121584121585121586121587121588121589121590121591121592121593121594121595121596121597121598121599121600121601121602121603121604121605121606121607121608121609121610121611121612121613121614121615121616121617121618121619121620121621121622121623121624121625121626121627121628121629121630121631121632121633121634121635121636121637121638121639121640121641121642121643121644121645121646121647121648121649121650121651121652121653121654121655121656121657121658121659121660121661121662121663121664121665121666121667121668121669121670121671121672121673121674121675121676121677121678121679121680121681121682121683121684121685121686121687121688121689121690121691121692121693121694121695121696121697121698121699121700121701121702121703121704121705121706121707121708121709121710121711121712121713121714121715121716121717121718121719121720121721121722121723121724121725121726121727121728121729121730121731121732121733121734121735121736121737121738121739121740121741121742121743121744121745121746121747121748121749121750121751121752121753121754121755121756121757121758121759121760121761121762121763121764121765121766121767121768121769121770121771121772121773121774121775121776121777121778121779121780121781121782121783121784121785121786121787121788121789121790121791121792121793121794121795121796121797121798121799121800121801121802121803121804121805121806121807121808121809121810121811121812121813121814121815121816121817121818121819121820121821121822121823121824121825121826121827121828121829121830121831121832121833121834121835121836121837121838121839121840121841121842121843121844121845121846121847121848121849121850121851121852121853121854121855121856121857121858121859121860121861121862121863121864121865121866121867121868121869121870121871121872121873121874121875121876121877121878121879121880121881121882121883121884121885121886121887121888121889121890121891121892121893121894121895121896121897121898121899121900121901121902121903121904121905121906121907121908121909121910121911121912121913121914121915121916121917121918121919121920121921121922121923121924121925121926121927121928121929121930121931121932121933121934121935121936121937121938121939121940121941121942121943121944121945121946121947121948121949121950121951121952121953121954121955121956121957121958121959121960121961121962121963121964121965121966121967121968121969121970121971121972121973121974121975121976121977121978121979121980121981121982121983121984121985121986121987121988121989121990121991121992121993121994121995121996121997121998121999122000122001122002122003122004122005122006122007122008122009122010122011122012122013122014122015122016122017122018122019122020122021122022122023122024122025122026122027122028122029122030122031122032122033122034122035122036122037122038122039122040122041122042122043122044122045122046122047122048122049122050122051122052122053122054122055122056122057122058122059122060122061122062122063122064122065122066122067122068122069122070122071122072122073122074122075122076122077122078122079122080122081122082122083122084122085122086122087122088122089122090122091122092122093122094122095122096122097122098122099122100122101122102122103122104122105122106122107122108122109122110122111122112122113122114122115122116122117122118122119122120122121122122122123122124122125122126122127122128122129122130122131122132122133122134122135122136122137122138122139122140122141122142122143122144122145122146122147122148122149122150122151122152122153122154122155122156122157122158122159122160122161122162122163122164122165122166122167122168122169122170122171122172122173122174122175122176122177122178122179122180122181122182122183122184122185122186122187122188122189122190122191122192122193122194122195122196122197122198122199122200122201122202122203122204122205122206122207122208122209122210122211122212122213122214122215122216122217122218122219122220122221122222122223122224122225122226122227122228122229122230122231122232122233122234122235122236122237122238122239122240122241122242122243122244122245122246122247122248122249122250122251122252122253122254122255122256122257122258122259122260122261122262122263122264122265122266122267122268122269122270122271122272122273122274122275122276122277122278122279122280122281122282122283122284122285122286122287122288122289122290122291122292122293122294122295122296122297122298122299122300122301122302122303122304122305122306122307122308122309122310122311122312122313122314122315122316122317122318122319122320122321122322122323122324122325122326122327122328122329122330122331122332122333122334122335122336122337122338122339122340122341122342122343122344122345122346122347122348122349122350122351122352122353122354122355122356122357122358122359122360122361122362122363122364122365122366122367122368122369122370122371122372122373122374122375122376122377122378122379122380122381122382122383122384122385122386122387122388122389122390122391122392122393122394122395122396122397122398122399122400122401122402122403122404122405122406122407122408122409122410122411122412122413122414122415122416122417122418122419122420122421122422122423122424122425122426122427122428122429122430122431122432122433122434122435122436122437122438122439122440122441122442122443122444122445122446122447122448122449122450122451122452122453122454122455122456122457122458122459122460122461122462122463122464122465122466122467122468122469122470122471122472122473122474122475122476122477122478122479122480122481122482122483122484122485122486122487122488122489122490122491122492122493122494122495122496122497122498122499122500122501122502122503122504122505122506122507122508122509122510122511122512122513122514122515122516122517122518122519122520122521122522122523122524122525122526122527122528122529122530122531122532122533122534122535122536122537122538122539122540122541122542122543122544122545122546122547122548122549122550122551122552122553122554122555122556122557122558122559122560122561122562122563122564122565122566122567122568122569122570122571122572122573122574122575122576122577122578122579122580122581122582122583122584122585122586122587122588122589122590122591122592122593122594122595122596122597122598122599122600122601122602122603122604122605122606122607122608122609122610122611122612122613122614122615122616122617122618122619122620122621122622122623122624122625122626122627122628122629122630122631122632122633122634122635122636122637122638122639122640122641122642122643122644122645122646122647122648122649122650122651122652122653122654122655122656122657122658122659122660122661122662122663122664122665122666122667122668122669122670122671122672122673122674122675122676122677122678122679122680122681122682122683122684122685122686122687122688122689122690122691122692122693122694122695122696122697122698122699122700122701122702122703122704122705122706122707122708122709122710122711122712122713122714122715122716122717122718122719122720122721122722122723122724122725122726122727122728122729122730122731122732122733122734122735122736122737122738122739122740122741122742122743122744122745122746122747122748122749122750122751122752122753122754122755122756122757122758122759122760122761122762122763122764122765122766122767122768122769122770122771122772122773122774122775122776122777122778122779122780122781122782122783122784122785122786122787122788122789122790122791122792122793122794122795122796122797122798122799122800122801122802122803122804122805122806122807122808122809122810122811122812122813122814122815122816122817122818122819122820122821122822122823122824122825122826122827122828122829122830122831122832122833122834122835122836122837122838122839122840122841122842122843122844122845122846122847122848122849122850122851122852122853122854122855122856122857122858122859122860122861122862122863122864122865122866122867122868122869122870122871122872122873122874122875122876122877122878122879122880122881122882122883122884122885122886122887122888122889122890122891122892122893122894122895122896122897122898122899122900122901122902122903122904122905122906122907122908122909122910122911122912122913122914122915122916122917122918122919122920122921122922122923122924122925122926122927122928122929122930122931122932122933122934122935122936122937122938122939122940122941122942122943122944122945122946122947122948122949122950122951122952122953122954122955122956122957122958122959122960122961122962122963122964122965122966122967122968122969122970122971122972122973122974122975122976122977122978122979122980122981122982122983122984122985122986122987122988122989122990122991122992122993122994122995122996122997122998122999123000123001123002123003123004123005123006123007123008123009123010123011123012123013123014123015123016123017123018123019123020123021123022123023123024123025123026123027123028123029123030123031123032123033123034123035123036123037123038123039123040123041123042123043123044123045123046123047123048123049123050123051123052123053123054123055123056123057123058123059123060123061123062123063123064123065123066123067123068123069123070123071123072123073123074123075123076123077123078123079123080123081123082123083123084123085123086123087123088123089123090123091123092123093123094123095123096123097123098123099123100123101123102123103123104123105123106123107123108123109123110123111123112123113123114123115123116123117123118123119123120123121123122123123123124123125123126123127123128123129123130123131123132123133123134123135123136123137123138123139123140123141123142123143123144123145123146123147123148123149123150123151123152123153123154123155123156123157123158123159123160123161123162123163123164123165123166123167123168123169123170123171123172123173123174123175123176123177123178123179123180123181123182123183123184123185123186123187123188123189123190123191123192123193123194123195123196123197123198123199123200123201123202123203123204123205123206123207123208123209123210123211123212123213123214123215123216123217123218123219123220123221123222123223123224123225123226123227123228123229123230123231123232123233123234123235123236123237123238123239123240123241123242123243123244123245123246123247123248123249123250123251123252123253123254123255123256123257123258123259123260123261123262123263123264123265123266123267123268123269123270123271123272123273123274123275123276123277123278123279123280123281123282123283123284123285123286123287123288123289123290123291123292123293123294123295123296123297123298123299123300123301123302123303123304123305123306123307123308123309123310123311123312123313123314123315123316123317123318123319123320123321123322123323123324123325123326123327123328123329123330123331123332123333123334123335123336123337123338123339123340123341123342123343123344123345123346123347123348123349123350123351123352123353123354123355123356123357123358123359123360123361123362123363123364123365123366123367123368123369123370123371123372123373123374123375123376123377123378123379123380123381123382123383123384123385123386123387123388123389123390123391123392123393123394123395123396123397123398123399123400123401123402123403123404123405123406123407123408123409123410123411123412123413123414123415123416123417123418123419123420123421123422123423123424123425123426123427123428123429123430123431123432123433123434123435123436123437123438123439123440123441123442123443123444123445123446123447123448123449123450123451123452123453123454123455123456123457123458123459123460123461123462123463123464123465123466123467123468123469123470123471123472123473123474123475123476123477123478123479123480123481123482123483123484123485123486123487123488123489123490123491123492123493123494123495123496123497123498123499123500123501123502123503123504123505123506123507123508123509123510123511123512123513123514123515123516123517123518123519123520123521123522123523123524123525123526123527123528123529123530123531123532123533123534123535123536123537123538123539123540123541123542123543123544123545123546123547123548123549123550123551123552123553123554123555123556123557123558123559123560123561123562123563123564123565123566123567123568123569123570123571123572123573123574123575123576123577123578123579123580123581123582123583123584123585123586123587123588123589123590123591123592123593123594123595123596123597123598123599123600123601123602123603123604123605123606123607123608123609123610123611123612123613123614123615123616123617123618123619123620123621123622123623123624123625123626123627123628123629123630123631123632123633123634123635123636123637123638123639123640123641123642123643123644123645123646123647123648123649123650123651123652123653123654123655123656123657123658123659123660123661123662123663123664123665123666123667123668123669123670123671123672123673123674123675123676123677123678123679123680123681123682123683123684123685123686123687123688123689123690123691123692123693123694123695123696123697123698123699123700123701123702123703123704123705123706123707123708123709123710123711123712123713123714123715123716123717123718123719123720123721123722123723123724123725123726123727123728123729123730123731123732123733123734123735123736123737123738123739123740123741123742123743123744123745123746123747123748123749123750123751123752123753123754123755123756123757123758123759123760123761123762123763123764123765123766123767123768123769123770123771123772123773123774123775123776123777123778123779123780123781123782123783123784123785123786123787123788123789123790123791123792123793123794123795123796123797123798123799123800123801123802123803123804123805123806123807123808123809123810123811123812123813123814123815123816123817123818123819123820123821123822123823123824123825123826123827123828123829123830123831123832123833123834123835123836123837123838123839123840123841123842123843123844123845123846123847123848123849123850123851123852123853123854123855123856123857123858123859123860123861123862123863123864123865123866123867123868123869123870123871123872123873123874123875123876123877123878123879123880123881123882123883123884123885123886123887123888123889123890123891123892123893123894123895123896123897123898123899123900123901123902123903123904123905123906123907123908123909123910123911123912123913123914123915123916123917123918123919123920123921123922123923123924123925123926123927123928123929123930123931123932123933123934123935123936123937123938123939123940123941123942123943123944123945123946123947123948123949123950123951123952123953123954123955123956123957123958123959123960123961123962123963123964123965123966123967123968123969123970123971123972123973123974123975123976123977123978123979123980123981123982123983123984123985123986123987123988123989123990123991123992123993123994123995123996123997123998123999124000124001124002124003124004124005124006124007124008124009124010124011124012124013124014124015124016124017124018124019124020124021124022124023124024124025124026124027124028124029124030124031124032124033124034124035124036124037124038124039124040124041124042124043124044124045124046124047124048124049124050124051124052124053124054124055124056124057124058124059124060124061124062124063124064124065124066124067124068124069124070124071124072124073124074124075124076124077124078124079124080124081124082124083124084124085124086124087124088124089124090124091124092124093124094124095124096124097124098124099124100124101124102124103124104124105124106124107124108124109124110124111124112124113124114124115124116124117124118124119124120124121124122124123124124124125124126124127124128124129124130124131124132124133124134124135124136124137124138124139124140124141124142124143124144124145124146124147124148124149124150124151124152124153124154124155124156124157124158124159124160124161124162124163124164124165124166124167124168124169124170124171124172124173124174124175124176124177124178124179124180124181124182124183124184124185124186124187124188124189124190124191124192124193124194124195124196124197124198124199124200124201124202124203124204124205124206124207124208124209124210124211124212124213124214124215124216124217124218124219124220124221124222124223124224124225124226124227124228124229124230124231124232124233124234124235124236124237124238124239124240124241124242124243124244124245124246124247124248124249124250124251124252124253124254124255124256124257124258124259124260124261124262124263124264124265124266124267124268124269124270124271124272124273124274124275124276124277124278124279124280124281124282124283124284124285124286124287124288124289124290124291124292124293124294124295124296124297124298124299124300124301124302124303124304124305124306124307124308124309124310124311124312124313124314124315124316124317124318124319124320124321124322124323124324124325124326124327124328124329124330124331124332124333124334124335124336124337124338124339124340124341124342124343124344124345124346124347124348124349124350124351124352124353124354124355124356124357124358124359124360124361124362124363124364124365124366124367124368124369124370124371124372124373124374124375124376124377124378124379124380124381124382124383124384124385124386124387124388124389124390124391124392124393124394124395124396124397124398124399124400124401124402124403124404124405124406124407124408124409124410124411124412124413124414124415124416124417124418124419124420124421124422124423124424124425124426124427124428124429124430124431124432124433124434124435124436124437124438124439124440124441124442124443124444124445124446124447124448124449124450124451124452124453124454124455124456124457124458124459124460124461124462124463124464124465124466124467124468124469124470124471124472124473124474124475124476124477124478124479124480124481124482124483124484124485124486124487124488124489124490124491124492124493124494124495124496124497124498124499124500124501124502124503124504124505124506124507124508124509124510124511124512124513124514124515124516124517124518124519124520124521124522124523124524124525124526124527124528124529124530124531124532124533124534124535124536124537124538124539124540124541124542124543124544124545124546124547124548124549124550124551124552124553124554124555124556124557124558124559124560124561124562124563124564124565124566124567124568124569124570124571124572124573124574124575124576124577124578124579124580124581124582124583124584124585124586124587124588124589124590124591124592124593124594124595124596124597124598124599124600124601124602124603124604124605124606124607124608124609124610124611124612124613124614124615124616124617124618124619124620124621124622124623124624124625124626124627124628124629124630124631124632124633124634124635124636124637124638124639124640124641124642124643124644124645124646124647124648124649124650124651124652124653124654124655124656124657124658124659124660124661124662124663124664124665124666124667124668124669124670124671124672124673124674124675124676124677124678124679124680124681124682124683124684124685124686124687124688124689124690124691124692124693124694124695124696124697124698124699124700124701124702124703124704124705124706124707124708124709124710124711124712124713124714124715124716124717124718124719124720124721124722124723124724124725124726124727124728124729124730124731124732124733124734124735124736124737124738124739124740124741124742124743124744124745124746124747124748124749124750124751124752124753124754124755124756124757124758124759124760124761124762124763124764124765124766124767124768124769124770124771124772124773124774124775124776124777124778124779124780124781124782124783124784124785124786124787124788124789124790124791124792124793124794124795124796124797124798124799124800124801124802124803124804124805124806124807124808124809124810124811124812124813124814124815124816124817124818124819124820124821124822124823124824124825124826124827124828124829124830124831124832124833124834124835124836124837124838124839124840124841124842124843124844124845124846124847124848124849124850124851124852124853124854124855124856124857124858124859124860124861124862124863124864124865124866124867124868124869124870124871124872124873124874124875124876124877124878124879124880124881124882124883124884124885124886124887124888124889124890124891124892124893124894124895124896124897124898124899124900124901124902124903124904124905124906124907124908124909124910124911124912124913124914124915124916124917124918124919124920124921124922124923124924124925124926124927124928124929124930124931124932124933124934124935124936124937124938124939124940124941124942124943124944124945124946124947124948124949124950124951124952124953124954124955124956124957124958124959124960124961124962124963124964124965124966124967124968124969124970124971124972124973124974124975124976124977124978124979124980124981124982124983124984124985124986124987124988124989124990124991124992124993124994124995124996124997124998124999125000125001125002125003125004125005125006125007125008125009125010125011125012125013125014125015125016125017125018125019125020125021125022125023125024125025125026125027125028125029125030125031125032125033125034125035125036125037125038125039125040125041125042125043125044125045125046125047125048125049125050125051125052125053125054125055125056125057125058125059125060125061125062125063125064125065125066125067125068125069125070125071125072125073125074125075125076125077125078125079125080125081125082125083125084125085125086125087125088125089125090125091125092125093125094125095125096125097125098125099125100125101125102125103125104125105125106125107125108125109125110125111125112125113125114125115125116125117125118125119125120125121125122125123125124125125125126125127125128125129125130125131125132125133125134125135125136125137125138125139125140125141125142125143125144125145125146125147125148125149125150125151125152125153125154125155125156125157125158125159125160125161125162125163125164125165125166125167125168125169125170125171125172125173125174125175125176125177125178125179125180125181125182125183125184125185125186125187125188125189125190125191125192125193125194125195125196125197125198125199125200125201125202125203125204125205125206125207125208125209125210125211125212125213125214125215125216125217125218125219125220125221125222125223125224125225125226125227125228125229125230125231125232125233125234125235125236125237125238125239125240125241125242125243125244125245125246125247125248125249125250125251125252125253125254125255125256125257125258125259125260125261125262125263125264125265125266125267125268125269125270125271125272125273125274125275125276125277125278125279125280125281125282125283125284125285125286125287125288125289125290125291125292125293125294125295125296125297125298125299125300125301125302125303125304125305125306125307125308125309125310125311125312125313125314125315125316125317125318125319125320125321125322125323125324125325125326125327125328125329125330125331125332125333125334125335125336125337125338125339125340125341125342125343125344125345125346125347125348125349125350125351125352125353125354125355125356125357125358125359125360125361125362125363125364125365125366125367125368125369125370125371125372125373125374125375125376125377125378125379125380125381125382125383125384125385125386125387125388125389125390125391125392125393125394125395125396125397125398125399125400125401125402125403125404125405125406125407125408125409125410125411125412125413125414125415125416125417125418125419125420125421125422125423125424125425125426125427125428125429125430125431125432125433125434125435125436125437125438125439125440125441125442125443125444125445125446125447125448125449125450125451125452125453125454125455125456125457125458125459125460125461125462125463125464125465125466125467125468125469125470125471125472125473125474125475125476125477125478125479125480125481125482125483125484125485125486125487125488125489125490125491125492125493125494125495125496125497125498125499125500125501125502125503125504125505125506125507125508125509125510125511125512125513125514125515125516125517125518125519125520125521125522125523125524125525125526125527125528125529125530125531125532125533125534125535125536125537125538125539125540125541125542125543125544125545125546125547125548125549125550125551125552125553125554125555125556125557125558125559125560125561125562125563125564125565125566125567125568125569125570125571125572125573125574125575125576125577125578125579125580125581125582125583125584125585125586125587125588125589125590125591125592125593125594125595125596125597125598125599125600125601125602125603125604125605125606125607125608125609125610125611125612125613125614125615125616125617125618125619125620125621125622125623125624125625125626125627125628125629125630125631125632125633125634125635125636125637125638125639125640125641125642125643125644125645125646125647125648125649125650125651125652125653125654125655125656125657125658125659125660125661125662125663125664125665125666125667125668125669125670125671125672125673125674125675125676125677125678125679125680125681125682125683125684125685125686125687125688125689125690125691125692125693125694125695125696125697125698125699125700125701125702125703125704125705125706125707125708125709125710125711125712125713125714125715125716125717125718125719125720125721125722125723125724125725125726125727125728125729125730125731125732125733125734125735125736125737125738125739125740125741125742125743125744125745125746125747125748125749125750125751125752125753125754125755125756125757125758125759125760125761125762125763125764125765125766125767125768125769125770125771125772125773125774125775125776125777125778125779125780125781125782125783125784125785125786125787125788125789125790125791125792125793125794125795125796125797125798125799125800125801125802125803125804125805125806125807125808125809125810125811125812125813125814125815125816125817125818125819125820125821125822125823125824125825125826125827125828125829125830125831125832125833125834125835125836125837125838125839125840125841125842125843125844125845125846125847125848125849125850125851125852125853125854125855125856125857125858125859125860125861125862125863125864125865125866125867125868125869125870125871125872125873125874125875125876125877125878125879125880125881125882125883125884125885125886125887125888125889125890125891125892125893125894125895125896125897125898125899125900125901125902125903125904125905125906125907125908125909125910125911125912125913125914125915125916125917125918125919125920125921125922125923125924125925125926125927125928125929125930125931125932125933125934125935125936125937125938125939125940125941125942125943125944125945125946125947125948125949125950125951125952125953125954125955125956125957125958125959125960125961125962125963125964125965125966125967125968125969125970125971125972125973125974125975125976125977125978125979125980125981125982125983125984125985125986125987125988125989125990125991125992125993125994125995125996125997125998125999126000126001126002126003126004126005126006126007126008126009126010126011126012126013126014126015126016126017126018126019126020126021126022126023126024126025126026126027126028126029126030126031126032126033126034126035126036126037126038126039126040126041126042126043126044126045126046126047126048126049126050126051126052126053126054126055126056126057126058126059126060126061126062126063126064126065126066126067126068126069126070126071126072126073126074126075126076126077126078126079126080126081126082126083126084126085126086126087126088126089126090126091126092126093126094126095126096126097126098126099126100126101126102126103126104126105126106126107126108126109126110126111126112126113126114126115126116126117126118126119126120126121126122126123126124126125126126126127126128126129126130126131126132126133126134126135126136126137126138126139126140126141126142126143126144126145126146126147126148126149126150126151126152126153126154126155126156126157126158126159126160126161126162126163126164126165126166126167126168126169126170126171126172126173126174126175126176126177126178126179126180126181126182126183126184126185126186126187126188126189126190126191126192126193126194126195126196126197126198126199126200126201126202126203126204126205126206126207126208126209126210126211126212126213126214126215126216126217126218126219126220126221126222126223126224126225126226126227126228126229126230126231126232126233126234126235126236126237126238126239126240126241126242126243126244126245126246126247126248126249126250126251126252126253126254126255126256126257126258126259126260126261126262126263126264126265126266126267126268126269126270126271126272126273126274126275126276126277126278126279126280126281126282126283126284126285126286126287126288126289126290126291126292126293126294126295126296126297126298126299126300126301126302126303126304126305126306126307126308126309126310126311126312126313126314126315126316126317126318126319126320126321126322126323126324126325126326126327126328126329126330126331126332126333126334126335126336126337126338126339126340126341126342126343126344126345126346126347126348126349126350126351126352126353126354126355126356126357126358126359126360126361126362126363126364126365126366126367126368126369126370126371126372126373126374126375126376126377126378126379126380126381126382126383126384126385126386126387126388126389126390126391126392126393126394126395126396126397126398126399126400126401126402126403126404126405126406126407126408126409126410126411126412126413126414126415126416126417126418126419126420126421126422126423126424126425126426126427126428126429126430126431126432126433126434126435126436126437126438126439126440126441126442126443126444126445126446126447126448126449126450126451126452126453126454126455126456126457126458126459126460126461126462126463126464126465126466126467126468126469126470126471126472126473126474126475126476126477126478126479126480126481126482126483126484126485126486126487126488126489126490126491126492126493126494126495126496126497126498126499126500126501126502126503126504126505126506126507126508126509126510126511126512126513126514126515126516126517126518126519126520126521126522126523126524126525126526126527126528126529126530126531126532126533126534126535126536126537126538126539126540126541126542126543126544126545126546126547126548126549126550126551126552126553126554126555126556126557126558126559126560126561126562126563126564126565126566126567126568126569126570126571126572126573126574126575126576126577126578126579126580126581126582126583126584126585126586126587126588126589126590126591126592126593126594126595126596126597126598126599126600126601126602126603126604126605126606126607126608126609126610126611126612126613126614126615126616126617126618126619126620126621126622126623126624126625126626126627126628126629126630126631126632126633126634126635126636126637126638126639126640126641126642126643126644126645126646126647126648126649126650126651126652126653126654126655126656126657126658126659126660126661126662126663126664126665126666126667126668126669126670126671126672126673126674126675126676126677126678126679126680126681126682126683126684126685126686126687126688126689126690126691126692126693126694126695126696126697126698126699126700126701126702126703126704126705126706126707126708126709126710126711126712126713126714126715126716126717126718126719126720126721126722126723126724126725126726126727126728126729126730126731126732126733126734126735126736126737126738126739126740126741126742126743126744126745126746126747126748126749126750126751126752126753126754126755126756126757126758126759126760126761126762126763126764126765126766126767126768126769126770126771126772126773126774126775126776126777126778126779126780126781126782126783126784126785126786126787126788126789126790126791126792126793126794126795126796126797126798126799126800126801126802126803126804126805126806126807126808126809126810126811126812126813126814126815126816126817126818126819126820126821126822126823126824126825126826126827126828126829126830126831126832126833126834126835126836126837126838126839126840126841126842126843126844126845126846126847126848126849126850126851126852126853126854126855126856126857126858126859126860126861126862126863126864126865126866126867126868126869126870126871126872126873126874126875126876126877126878126879126880126881126882126883126884126885126886126887126888126889126890126891126892126893126894126895126896126897126898126899126900126901126902126903126904126905126906126907126908126909126910126911126912126913126914126915126916126917126918126919126920126921126922126923126924126925126926126927126928126929126930126931126932126933126934126935126936126937126938126939126940126941126942126943126944126945126946126947126948126949126950126951126952126953126954126955126956126957126958126959126960126961126962126963126964126965126966126967126968126969126970126971126972126973126974126975126976126977126978126979126980126981126982126983126984126985126986126987126988126989126990126991126992126993126994126995126996126997126998126999127000127001127002127003127004127005127006127007127008127009127010127011127012127013127014127015127016127017127018127019127020127021127022127023127024127025127026127027127028127029127030127031127032127033127034127035127036127037127038127039127040127041127042127043127044127045127046127047127048127049127050127051127052127053127054127055127056127057127058127059127060127061127062127063127064127065127066127067127068127069127070127071127072127073127074127075127076127077127078127079127080127081127082127083127084127085127086127087127088127089127090127091127092127093127094127095127096127097127098127099127100127101127102127103127104127105127106127107127108127109127110127111127112127113127114127115127116127117127118127119127120127121127122127123127124127125127126127127127128127129127130127131127132127133127134127135127136127137127138127139127140127141127142127143127144127145127146127147127148127149127150127151127152127153127154127155127156127157127158127159127160127161127162127163127164127165127166127167127168127169127170127171127172127173127174127175127176127177127178127179127180127181127182127183127184127185127186127187127188127189127190127191127192127193127194127195127196127197127198127199127200127201127202127203127204127205127206127207127208127209127210127211127212127213127214127215127216127217127218127219127220127221127222127223127224127225127226127227127228127229127230127231127232127233127234127235127236127237127238127239127240127241127242127243127244127245127246127247127248127249127250127251127252127253127254127255127256127257127258127259127260127261127262127263127264127265127266127267127268127269127270127271127272127273127274127275127276127277127278127279127280127281127282127283127284127285127286127287127288127289127290127291127292127293127294127295127296127297127298127299127300127301127302127303127304127305127306127307127308127309127310127311127312127313127314127315127316127317127318127319127320127321127322127323127324127325127326127327127328127329127330127331127332127333127334127335127336127337127338127339127340127341127342127343127344127345127346127347127348127349127350127351127352127353127354127355127356127357127358127359127360127361127362127363127364127365127366127367127368127369127370127371127372127373127374127375127376127377127378127379127380127381127382127383127384127385127386127387127388127389127390127391127392127393127394127395127396127397127398127399127400127401127402127403127404127405127406127407127408127409127410127411127412127413127414127415127416127417127418127419127420127421127422127423127424127425127426127427127428127429127430127431127432127433127434127435127436127437127438127439127440127441127442127443127444127445127446127447127448127449127450127451127452127453127454127455127456127457127458127459127460127461127462127463127464127465127466127467127468127469127470127471127472127473127474127475127476127477127478127479127480127481127482127483127484127485127486127487127488127489127490127491127492127493127494127495127496127497127498127499127500127501127502127503127504127505127506127507127508127509127510127511127512127513127514127515127516127517127518127519127520127521127522127523127524127525127526127527127528127529127530127531127532127533127534127535127536127537127538127539127540127541127542127543127544127545127546127547127548127549127550127551127552127553127554127555127556127557127558127559127560127561127562127563127564127565127566127567127568127569127570127571127572127573127574127575127576127577127578127579127580127581127582127583127584127585127586127587127588127589127590127591127592127593127594127595127596127597127598127599127600127601127602127603127604127605127606127607127608127609127610127611127612127613127614127615127616127617127618127619127620127621127622127623127624127625127626127627127628127629127630127631127632127633127634127635127636127637127638127639127640127641127642127643127644127645127646127647127648127649127650127651127652127653127654127655127656127657127658127659127660127661127662127663127664127665127666127667127668127669127670127671127672127673127674127675127676127677127678127679127680127681127682127683127684127685127686127687127688127689127690127691127692127693127694127695127696127697127698127699127700127701127702127703127704127705127706127707127708127709127710127711127712127713127714127715127716127717127718127719127720127721127722127723127724127725127726127727127728127729127730127731127732127733127734127735127736127737127738127739127740127741127742127743127744127745127746127747127748127749127750127751127752127753127754127755127756127757127758127759127760127761127762127763127764127765127766127767127768127769127770127771127772127773127774127775127776127777127778127779127780127781127782127783127784127785127786127787127788127789127790127791127792127793127794127795127796127797127798127799127800127801127802127803127804127805127806127807127808127809127810127811127812127813127814127815127816127817127818127819127820127821127822127823127824127825127826127827127828127829127830127831127832127833127834127835127836127837127838127839127840127841127842127843127844127845127846127847127848127849127850127851127852127853127854127855127856127857127858127859127860127861127862127863127864127865127866127867127868127869127870127871127872127873127874127875127876127877127878127879127880127881127882127883127884127885127886127887127888127889127890127891127892127893127894127895127896127897127898127899127900127901127902127903127904127905127906127907127908127909127910127911127912127913127914127915127916127917127918127919127920127921127922127923127924127925127926127927127928127929127930127931127932127933127934127935127936127937127938127939127940127941127942127943127944127945127946127947127948127949127950127951127952127953127954127955127956127957127958127959127960127961127962127963127964127965127966127967127968127969127970127971127972127973127974127975127976127977127978127979127980127981127982127983127984127985127986127987127988127989127990127991127992127993127994127995127996127997127998127999128000128001128002128003128004128005128006128007128008128009128010128011128012128013128014128015128016128017128018128019128020128021128022128023128024128025128026128027128028128029128030128031128032128033128034128035128036128037128038128039128040128041128042128043128044128045128046128047128048128049128050128051128052128053128054128055128056128057128058128059128060128061128062128063128064128065128066128067128068128069128070128071128072128073128074128075128076128077128078128079128080128081128082128083128084128085128086128087128088128089128090128091128092128093128094128095128096128097128098128099128100128101128102128103128104128105128106128107128108128109128110128111128112128113128114128115128116128117128118128119128120128121128122128123128124128125128126128127128128128129128130128131128132128133128134128135128136128137128138128139128140128141128142128143128144128145128146128147128148128149128150128151128152128153128154128155128156128157128158128159128160128161128162128163128164128165128166128167128168128169128170128171128172128173128174128175128176128177128178128179128180128181128182128183128184128185128186128187128188128189128190128191128192128193128194128195128196128197128198128199128200128201128202128203128204128205128206128207128208128209128210128211128212128213128214128215128216128217128218128219128220128221128222128223128224128225128226128227128228128229128230128231128232128233128234128235128236128237128238128239128240128241128242128243128244128245128246128247128248128249128250128251128252128253128254128255128256128257128258128259128260128261128262128263128264128265128266128267128268128269128270128271128272128273128274128275128276128277128278128279128280128281128282128283128284128285128286128287128288128289128290128291128292128293128294128295128296128297128298128299128300128301128302128303128304128305128306128307128308128309128310128311128312128313128314128315128316128317128318128319128320128321128322128323128324128325128326128327128328128329128330128331128332128333128334128335128336128337128338128339128340128341128342128343128344128345128346128347128348128349128350128351128352128353128354128355128356128357128358128359128360128361128362128363128364128365128366128367128368128369128370128371128372128373128374128375128376128377128378128379128380128381128382128383128384128385128386128387128388128389128390128391128392128393128394128395128396128397128398128399128400128401128402128403128404128405128406128407128408128409128410128411128412128413128414128415128416128417128418128419128420128421128422128423128424128425128426128427128428128429128430128431128432128433128434128435128436128437128438128439128440128441128442128443128444128445128446128447128448128449128450128451128452128453128454128455128456128457128458128459128460128461128462128463128464128465128466128467128468128469128470128471128472128473128474128475128476128477128478128479128480128481128482128483128484128485128486128487128488128489128490128491128492128493128494128495128496128497128498128499128500128501128502128503128504128505128506128507128508128509128510128511128512128513128514128515128516128517128518128519128520128521128522128523128524128525128526128527128528128529128530128531128532128533128534128535128536128537128538128539128540128541128542128543128544128545128546128547128548128549128550128551128552128553128554128555128556128557128558128559128560128561128562128563128564128565128566128567128568128569128570128571128572128573128574128575128576128577128578128579128580128581128582128583128584128585128586128587128588128589128590128591128592128593128594128595128596128597128598128599128600128601128602128603128604128605128606128607128608128609128610128611128612128613128614128615128616128617128618128619128620128621128622128623128624128625128626128627128628128629128630128631128632128633128634128635128636128637128638128639128640128641128642128643128644128645128646128647128648128649128650128651128652128653128654128655128656128657128658128659128660128661128662128663128664128665128666128667128668128669128670128671128672128673128674128675128676128677128678128679128680128681128682128683128684128685128686128687128688128689128690128691128692128693128694128695128696128697128698128699128700128701128702128703128704128705128706128707128708128709128710128711128712128713128714128715128716128717128718128719128720128721128722128723128724128725128726128727128728128729128730128731128732128733128734128735128736128737128738128739128740128741128742128743128744128745128746128747128748128749128750128751128752128753128754128755128756128757128758128759128760128761128762128763128764128765128766128767128768128769128770128771128772128773128774128775128776128777128778128779128780128781128782128783128784128785128786128787128788128789128790128791128792128793128794128795128796128797128798128799128800128801128802128803128804128805128806128807128808128809128810128811128812128813128814128815128816128817128818128819128820128821128822128823128824128825128826128827128828128829128830128831128832128833128834128835128836128837128838128839128840128841128842128843128844128845128846128847128848128849128850128851128852128853128854128855128856128857128858128859128860128861128862128863128864128865128866128867128868128869128870128871128872128873128874128875128876128877128878128879128880128881128882128883128884128885128886128887128888128889128890128891128892128893128894128895128896128897128898128899128900128901128902128903128904128905128906128907128908128909128910128911128912128913128914128915128916128917128918128919128920128921128922128923128924128925128926128927128928128929128930128931128932128933128934128935128936128937128938128939128940128941128942128943128944128945128946128947128948128949128950128951128952128953128954128955128956128957128958128959128960128961128962128963128964128965128966128967128968128969128970128971128972128973128974128975128976128977128978128979128980128981128982128983128984128985128986128987128988128989128990128991128992128993128994128995128996128997128998128999129000129001129002129003129004129005129006129007129008129009129010129011129012129013129014129015129016129017129018129019129020129021129022129023129024129025129026129027129028129029129030129031129032129033129034129035129036129037129038129039129040129041129042129043129044129045129046129047129048129049129050129051129052129053129054129055129056129057129058129059129060129061129062129063129064129065129066129067129068129069129070129071129072129073129074129075129076129077129078129079129080129081129082129083129084129085129086129087129088129089129090129091129092129093129094129095129096129097129098129099129100129101129102129103129104129105129106129107129108129109129110129111129112129113129114129115129116129117129118129119129120129121129122129123129124129125129126129127129128129129129130129131129132129133129134129135129136129137129138129139129140129141129142129143129144129145129146129147129148129149129150129151129152129153129154129155129156129157129158129159129160129161129162129163129164129165129166129167129168129169129170129171129172129173129174129175129176129177129178129179129180129181129182129183129184129185129186129187129188129189129190129191129192129193129194129195129196129197129198129199129200129201129202129203129204129205129206129207129208129209129210129211129212129213129214129215129216129217129218129219129220129221129222129223129224129225129226129227129228129229129230129231129232129233129234129235129236129237129238129239129240129241129242129243129244129245129246129247129248129249129250129251129252129253129254129255129256129257129258129259129260129261129262129263129264129265129266129267129268129269129270129271129272129273129274129275129276129277129278129279129280129281129282129283129284129285129286129287129288129289129290129291129292129293129294129295129296129297129298129299129300129301129302129303129304129305129306129307129308129309129310129311129312129313129314129315129316129317129318129319129320129321129322129323129324129325129326129327129328129329129330129331129332129333129334129335129336129337129338129339129340129341129342129343129344129345129346129347129348129349129350129351129352129353129354129355129356129357129358129359129360129361129362129363129364129365129366129367129368129369129370129371129372129373129374129375129376129377129378129379129380129381129382129383129384129385129386129387129388129389129390129391129392129393129394129395129396129397129398129399129400129401129402129403129404129405129406129407129408129409129410129411129412129413129414129415129416129417129418129419129420129421129422129423129424129425129426129427129428129429129430129431129432129433129434129435129436129437129438129439129440129441129442129443129444129445129446129447129448129449129450129451129452129453129454129455129456129457129458129459129460129461129462129463129464129465129466129467129468129469129470129471129472129473129474129475129476129477129478129479129480129481129482129483129484129485129486129487129488129489129490129491129492129493129494129495129496129497129498129499129500129501129502129503129504129505129506129507129508129509129510129511129512129513129514129515129516129517129518129519129520129521129522129523129524129525129526129527129528129529129530129531129532129533129534129535129536129537129538129539129540129541129542129543129544129545129546129547129548129549129550129551129552129553129554129555129556129557129558129559129560129561129562129563129564129565129566129567129568129569129570129571129572129573129574129575129576129577129578129579129580129581129582129583129584129585129586129587129588129589129590129591129592129593129594129595129596129597129598129599129600129601129602129603129604129605129606129607129608129609129610129611129612129613129614129615129616129617129618129619129620129621129622129623129624129625129626129627129628129629129630129631129632129633129634129635129636129637129638129639129640129641129642129643129644129645129646129647129648129649129650129651129652129653129654129655129656129657129658129659129660129661129662129663129664129665129666129667129668129669129670129671129672129673129674129675129676129677129678129679129680129681129682129683129684129685129686129687129688129689129690129691129692129693129694129695129696129697129698129699129700129701129702129703129704129705129706129707129708129709129710129711129712129713129714129715129716129717129718129719129720129721129722129723129724129725129726129727129728129729129730129731129732129733129734129735129736129737129738129739129740129741129742129743129744129745129746129747129748129749129750129751129752129753129754129755129756129757129758129759129760129761129762129763129764129765129766129767129768129769129770129771129772129773129774129775129776129777129778129779129780129781129782129783129784129785129786129787129788129789129790129791129792129793129794129795129796129797129798129799129800129801129802129803129804129805129806129807129808129809129810129811129812129813129814129815129816129817129818129819129820129821129822129823129824129825129826129827129828129829129830129831129832129833129834129835129836129837129838129839129840129841129842129843129844129845129846129847129848129849129850129851129852129853129854129855129856129857129858129859129860129861129862129863129864129865129866129867129868129869129870129871129872129873129874129875129876129877129878129879129880129881129882129883129884129885129886129887129888129889129890129891129892129893129894129895129896129897129898129899129900129901129902129903129904129905129906129907129908129909129910129911129912129913129914129915129916129917129918129919129920129921129922129923129924129925129926129927129928129929129930129931129932129933129934129935129936129937129938129939129940129941129942129943129944129945129946129947129948129949129950129951129952129953129954129955129956129957129958129959129960129961129962129963129964129965129966129967129968129969129970129971129972129973129974129975129976129977129978129979129980129981129982129983129984129985129986129987129988129989129990129991129992129993129994129995129996129997129998129999130000130001130002130003130004130005130006130007130008130009130010130011130012130013130014130015130016130017130018130019130020130021130022130023130024130025130026130027130028130029130030130031130032130033130034130035130036130037130038130039130040130041130042130043130044130045130046130047130048130049130050130051130052130053130054130055130056130057130058130059130060130061130062130063130064130065130066130067130068130069130070130071130072130073130074130075130076130077130078130079130080130081130082130083130084130085130086130087130088130089130090130091130092130093130094130095130096130097130098130099130100130101130102130103130104130105130106130107130108130109130110130111130112130113130114130115130116130117130118130119130120130121130122130123130124130125130126130127130128130129130130130131130132130133130134130135130136130137130138130139130140130141130142130143130144130145130146130147130148130149130150130151130152130153130154130155130156130157130158130159130160130161130162130163130164130165130166130167130168130169130170130171130172130173130174130175130176130177130178130179130180130181130182130183130184130185130186130187130188130189130190130191130192130193130194130195130196130197130198130199130200130201130202130203130204130205130206130207130208130209130210130211130212130213130214130215130216130217130218130219130220130221130222130223130224130225130226130227130228130229130230130231130232130233130234130235130236130237130238130239130240130241130242130243130244130245130246130247130248130249130250130251130252130253130254130255130256130257130258130259130260130261130262130263130264130265130266130267130268130269130270130271130272130273130274130275130276130277130278130279130280130281130282130283130284130285130286130287130288130289130290130291130292130293130294130295130296130297130298130299130300130301130302130303130304130305130306130307130308130309130310130311130312130313130314130315130316130317130318130319130320130321130322130323130324130325130326130327130328130329130330130331130332130333130334130335130336130337130338130339130340130341130342130343130344130345130346130347130348130349130350130351130352130353130354130355130356130357130358130359130360130361130362130363130364130365130366130367130368130369130370130371130372130373130374130375130376130377130378130379130380130381130382130383130384130385130386130387130388130389130390130391130392130393130394130395130396130397130398130399130400130401130402130403130404130405130406130407130408130409130410130411130412130413130414130415130416130417130418130419130420130421130422130423130424130425130426130427130428130429130430130431130432130433130434130435130436130437130438130439130440130441130442130443130444130445130446130447130448130449130450130451130452130453130454130455130456130457130458130459130460130461130462130463130464130465130466130467130468130469130470130471130472130473130474130475130476130477130478130479130480130481130482130483130484130485130486130487130488130489130490130491130492130493130494130495130496130497130498130499130500130501130502130503130504130505130506130507130508130509130510130511130512130513130514130515130516130517130518130519130520130521130522130523130524130525130526130527130528130529130530130531130532130533130534130535130536130537130538130539130540130541130542130543130544130545130546130547130548130549130550130551130552130553130554130555130556130557130558130559130560130561130562130563130564130565130566130567130568130569130570130571130572130573130574130575130576130577130578130579130580130581130582130583130584130585130586130587130588130589130590130591130592130593130594130595130596130597130598130599130600130601130602130603130604130605130606130607130608130609130610130611130612130613130614130615130616130617130618130619130620130621130622130623130624130625130626130627130628130629130630130631130632130633130634130635130636130637130638130639130640130641130642130643130644130645130646130647130648130649130650130651130652130653130654130655130656130657130658130659130660130661130662130663130664130665130666130667130668130669130670130671130672130673130674130675130676130677130678130679130680130681130682130683130684130685130686130687130688130689130690130691130692130693130694130695130696130697130698130699130700130701130702130703130704130705130706130707130708130709130710130711130712130713130714130715130716130717130718130719130720130721130722130723130724130725130726130727130728130729130730130731130732130733130734130735130736130737130738130739130740130741130742130743130744130745130746130747130748130749130750130751130752130753130754130755130756130757130758130759130760130761130762130763130764130765130766130767130768130769130770130771130772130773130774130775130776130777130778130779130780130781130782130783130784130785130786130787130788130789130790130791130792130793130794130795130796130797130798130799130800130801130802130803130804130805130806130807130808130809130810130811130812130813130814130815130816130817130818130819130820130821130822130823130824130825130826130827130828130829130830130831130832130833130834130835130836130837130838130839130840130841130842130843130844130845130846130847130848130849130850130851130852130853130854130855130856130857130858130859130860130861130862130863130864130865130866130867130868130869130870130871130872130873130874130875130876130877130878130879130880130881130882130883130884130885130886130887130888130889130890130891130892130893130894130895130896130897130898130899130900130901130902130903130904130905130906130907130908130909130910130911130912130913130914130915130916130917130918130919130920130921130922130923130924130925130926130927130928130929130930130931130932130933130934130935130936130937130938130939130940130941130942130943130944130945130946130947130948130949130950130951130952130953130954130955130956130957130958130959130960130961130962130963130964130965130966130967130968130969130970130971130972130973130974130975130976130977130978130979130980130981130982130983130984130985130986130987130988130989130990130991130992130993130994130995130996130997130998130999131000131001131002131003131004131005131006131007131008131009131010131011131012131013131014131015131016131017131018131019131020131021131022131023131024131025131026131027131028131029131030131031131032131033131034131035131036131037131038131039131040131041131042131043131044131045131046131047131048131049131050131051131052131053131054131055131056131057131058131059131060131061131062131063131064131065131066131067131068131069131070131071131072131073131074131075131076131077131078131079131080131081131082131083131084131085131086131087131088131089131090131091131092131093131094131095131096131097131098131099131100131101131102131103131104131105131106131107131108131109131110131111131112131113131114131115131116131117131118131119131120131121131122131123131124131125131126131127131128131129131130131131131132131133131134131135131136131137131138131139131140131141131142131143131144131145131146131147131148131149131150131151131152131153131154131155131156131157131158131159131160131161131162131163131164131165131166131167131168131169131170131171131172131173131174131175131176131177131178131179131180131181131182131183131184131185131186131187131188131189131190131191131192131193131194131195131196131197131198131199131200131201131202131203131204131205131206131207131208131209131210131211131212131213131214131215131216131217131218131219131220131221131222131223131224131225131226131227131228131229131230131231131232131233131234131235131236131237131238131239131240131241131242131243131244131245131246131247131248131249131250131251131252131253131254131255131256131257131258131259131260131261131262131263131264131265131266131267131268131269131270131271131272131273131274131275131276131277131278131279131280131281131282131283131284131285131286131287131288131289131290131291131292131293131294131295131296131297131298131299131300131301131302131303131304131305131306131307131308131309131310131311131312131313131314131315131316131317131318131319131320131321131322131323131324131325131326131327131328131329131330131331131332131333131334131335131336131337131338131339131340131341131342131343131344131345131346131347131348131349131350131351131352131353131354131355131356131357131358131359131360131361131362131363131364131365131366131367131368131369131370131371131372131373131374131375131376131377131378131379131380131381131382131383131384131385131386131387131388131389131390131391131392131393131394131395131396131397131398131399131400131401131402131403131404131405131406131407131408131409131410131411131412131413131414131415131416131417131418131419131420131421131422131423131424131425131426131427131428131429131430131431131432131433131434131435131436131437131438131439131440131441131442131443131444131445131446131447131448131449131450131451131452131453131454131455131456131457131458131459131460131461131462131463131464131465131466131467131468131469131470131471131472131473131474131475131476131477131478131479131480131481131482131483131484131485131486131487131488131489131490131491131492131493131494131495131496131497131498131499131500131501131502131503131504131505131506131507131508131509131510131511131512131513131514131515131516131517131518131519131520131521131522131523131524131525131526131527131528131529131530131531131532131533131534131535131536131537131538131539131540131541131542131543131544131545131546131547131548131549131550131551131552131553131554131555131556131557131558131559131560131561131562131563131564131565131566131567131568131569131570131571131572131573131574131575131576131577131578131579131580131581131582131583131584131585131586131587131588131589131590131591131592131593131594131595131596131597131598131599131600131601131602131603131604131605131606131607131608131609131610131611131612131613131614131615131616131617131618131619131620131621131622131623131624131625131626131627131628131629131630131631131632131633131634131635131636131637131638131639131640131641131642131643131644131645131646131647131648131649131650131651131652131653131654131655131656131657131658131659131660131661131662131663131664131665131666131667131668131669131670131671131672131673131674131675131676131677131678131679131680131681131682131683131684131685131686131687131688131689131690131691131692131693131694131695131696131697131698131699131700131701131702131703131704131705131706131707131708131709131710131711131712131713131714131715131716131717131718131719131720131721131722131723131724131725131726131727131728131729131730131731131732131733131734131735131736131737131738131739131740131741131742131743131744131745131746131747131748131749131750131751131752131753131754131755131756131757131758131759131760131761131762131763131764131765131766131767131768131769131770131771131772131773131774131775131776131777131778131779131780131781131782131783131784131785131786131787131788131789131790131791131792131793131794131795131796131797131798131799131800131801131802131803131804131805131806131807131808131809131810131811131812131813131814131815131816131817131818131819131820131821131822131823131824131825131826131827131828131829131830131831131832131833131834131835131836131837131838131839131840131841131842131843131844131845131846131847131848131849131850131851131852131853131854131855131856131857131858131859131860131861131862131863131864131865131866131867131868131869131870131871131872131873131874131875131876131877131878131879131880131881131882131883131884131885131886131887131888131889131890131891131892131893131894131895131896131897131898131899131900131901131902131903131904131905131906131907131908131909131910131911131912131913131914131915131916131917131918131919131920131921131922131923131924131925131926131927131928131929131930131931131932131933131934131935131936131937131938131939131940131941131942131943131944131945131946131947131948131949131950131951131952131953131954131955131956131957131958131959131960131961131962131963131964131965131966131967131968131969131970131971131972131973131974131975131976131977131978131979131980131981131982131983131984131985131986131987131988131989131990131991131992131993131994131995131996131997131998131999132000132001132002132003132004132005132006132007132008132009132010132011132012132013132014132015132016132017132018132019132020132021132022132023132024132025132026132027132028132029132030132031132032132033132034132035132036132037132038132039132040132041132042132043132044132045132046132047132048132049132050132051132052132053132054132055132056132057132058132059132060132061132062132063132064132065132066132067132068132069132070132071132072132073132074132075132076132077132078132079132080132081132082132083132084132085132086132087132088132089132090132091132092132093132094132095132096132097132098132099132100132101132102132103132104132105132106132107132108132109132110132111132112132113132114132115132116132117132118132119132120132121132122132123132124132125132126132127132128132129132130132131132132132133132134132135132136132137132138132139132140132141132142132143132144132145132146132147132148132149132150132151132152132153132154132155132156132157132158132159132160132161132162132163132164132165132166132167132168132169132170132171132172132173132174132175132176132177132178132179132180132181132182132183132184132185132186132187132188132189132190132191132192132193132194132195132196132197132198132199132200132201132202132203132204132205132206132207132208132209132210132211132212132213132214132215132216132217132218132219132220132221132222132223132224132225132226132227132228132229132230132231132232132233132234132235132236132237132238132239132240132241132242132243132244132245132246132247132248132249132250132251132252132253132254132255132256132257132258132259132260132261132262132263132264132265132266132267132268132269132270132271132272132273132274132275132276132277132278132279132280132281132282132283132284132285132286132287132288132289132290132291132292132293132294132295132296132297132298132299132300132301132302132303132304132305132306132307132308132309132310132311132312132313132314132315132316132317132318132319132320132321132322132323132324132325132326132327132328132329132330132331132332132333132334132335132336132337132338132339132340132341132342132343132344132345132346132347132348132349132350132351132352132353132354132355132356132357132358132359132360132361132362132363132364132365132366132367132368132369132370132371132372132373132374132375132376132377132378132379132380132381132382132383132384132385132386132387132388132389132390132391132392132393132394132395132396132397132398132399132400132401132402132403132404132405132406132407132408132409132410132411132412132413132414132415132416132417132418132419132420132421132422132423132424132425132426132427132428132429132430132431132432132433132434132435132436132437132438132439132440132441132442132443132444132445132446132447132448132449132450132451132452132453132454132455132456132457132458132459132460132461132462132463132464132465132466132467132468132469132470132471132472132473132474132475132476132477132478132479132480132481132482132483132484132485132486132487132488132489132490132491132492132493132494132495132496132497132498132499132500132501132502132503132504132505132506132507132508132509132510132511132512132513132514132515132516132517132518132519132520132521132522132523132524132525132526132527132528132529132530132531132532132533132534132535132536132537132538132539132540132541132542132543132544132545132546132547132548132549132550132551132552132553132554132555132556132557132558132559132560132561132562132563132564132565132566132567132568132569132570132571132572132573132574132575132576132577132578132579132580132581132582132583132584132585132586132587132588132589132590132591132592132593132594132595132596132597132598132599132600132601132602132603132604132605132606132607132608132609132610132611132612132613132614132615132616132617132618132619132620132621132622132623132624132625132626132627132628132629132630132631132632132633132634132635132636132637132638132639132640132641132642132643132644132645132646132647132648132649132650132651132652132653132654132655132656132657132658132659132660132661132662132663132664132665132666132667132668132669132670132671132672132673132674132675132676132677132678132679132680132681132682132683132684132685132686132687132688132689132690132691132692132693132694132695132696132697132698132699132700132701132702132703132704132705132706132707132708132709132710132711132712132713132714132715132716132717132718132719132720132721132722132723132724132725132726132727132728132729132730132731132732132733132734132735132736132737132738132739132740132741132742132743132744132745132746132747132748132749132750132751132752132753132754132755132756132757132758132759132760132761132762132763132764132765132766132767132768132769132770132771132772132773132774132775132776132777132778132779132780132781132782132783132784132785132786132787132788132789132790132791132792132793132794132795132796132797132798132799132800132801132802132803132804132805132806132807132808132809132810132811132812132813132814132815132816132817132818132819132820132821132822132823132824132825132826132827132828132829132830132831132832132833132834132835132836132837132838132839132840132841132842132843132844132845132846132847132848132849132850132851132852132853132854132855132856132857132858132859132860132861132862132863132864132865132866132867132868132869132870132871132872132873132874132875132876132877132878132879132880132881132882132883132884132885132886132887132888132889132890132891132892132893132894132895132896132897132898132899132900132901132902132903132904132905132906132907132908132909132910132911132912132913132914132915132916132917132918132919132920132921132922132923132924132925132926132927132928132929132930132931132932132933132934132935132936132937132938132939132940132941132942132943132944132945132946132947132948132949132950132951132952132953132954132955132956132957132958132959132960132961132962132963132964132965132966132967132968132969132970132971132972132973132974132975132976132977132978132979132980132981132982132983132984132985132986132987132988132989132990132991132992132993132994132995132996132997132998132999133000133001133002133003133004133005133006133007133008133009133010133011133012133013133014133015133016133017133018133019133020133021133022133023133024133025133026133027133028133029133030133031133032133033133034133035133036133037133038133039133040133041133042133043133044133045133046133047133048133049133050133051133052133053133054133055133056133057133058133059133060133061133062133063133064133065133066133067133068133069133070133071133072133073133074133075133076133077133078133079133080133081133082133083133084133085133086133087133088133089133090133091133092133093133094133095133096133097133098133099133100133101133102133103133104133105133106133107133108133109133110133111133112133113133114133115133116133117133118133119133120133121133122133123133124133125133126133127133128133129133130133131133132133133133134133135133136133137133138133139133140133141133142133143133144133145133146133147133148133149133150133151133152133153133154133155133156133157133158133159133160133161133162133163133164133165133166133167133168133169133170133171133172133173133174133175133176133177133178133179133180133181133182133183133184133185133186133187133188133189133190133191133192133193133194133195133196133197133198133199133200133201133202133203133204133205133206133207133208133209133210133211133212133213133214133215133216133217133218133219133220133221133222133223133224133225133226133227133228133229133230133231133232133233133234133235133236133237133238133239133240133241133242133243133244133245133246133247133248133249133250133251133252133253133254133255133256133257133258133259133260133261133262133263133264133265133266133267133268133269133270133271133272133273133274133275133276133277133278133279133280133281133282133283133284133285133286133287133288133289133290133291133292133293133294133295133296133297133298133299133300133301133302133303133304133305133306133307133308133309133310133311133312133313133314133315133316133317133318133319133320133321133322133323133324133325133326133327133328133329133330133331133332133333133334133335133336133337133338133339133340133341133342133343133344133345133346133347133348133349133350133351133352133353133354133355133356133357133358133359133360133361133362133363133364133365133366133367133368133369133370133371133372133373133374133375133376133377133378133379133380133381133382133383133384133385133386133387133388133389133390133391133392133393133394133395133396133397133398133399133400133401133402133403133404133405133406133407133408133409133410133411133412133413133414133415133416133417133418133419133420133421133422133423133424133425133426133427133428133429133430133431133432133433133434133435133436133437133438133439133440133441133442133443133444133445133446133447133448133449133450133451133452133453133454133455133456133457133458133459133460133461133462133463133464133465133466133467133468133469133470133471133472133473133474133475133476133477133478133479133480133481133482133483133484133485133486133487133488133489133490133491133492133493133494133495133496133497133498133499133500133501133502133503133504133505133506133507133508133509133510133511133512133513133514133515133516133517133518133519133520133521133522133523133524133525133526133527133528133529133530133531133532133533133534133535133536133537133538133539133540133541133542133543133544133545133546133547133548133549133550133551133552133553133554133555133556133557133558133559133560133561133562133563133564133565133566133567133568133569133570133571133572133573133574133575133576133577133578133579133580133581133582133583133584133585133586133587133588133589133590133591133592133593133594133595133596133597133598133599133600133601133602133603133604133605133606133607133608133609133610133611133612133613133614133615133616133617133618133619133620133621133622133623133624133625133626133627133628133629133630133631133632133633133634133635133636133637133638133639133640133641133642133643133644133645133646133647133648133649133650133651133652133653133654133655133656133657133658133659133660133661133662133663133664133665133666133667133668133669133670133671133672133673133674133675133676133677133678133679133680133681133682133683133684133685133686133687133688133689133690133691133692133693133694133695133696133697133698133699133700133701133702133703133704133705133706133707133708133709133710133711133712133713133714133715133716133717133718133719133720133721133722133723133724133725133726133727133728133729133730133731133732133733133734133735133736133737133738133739133740133741133742133743133744133745133746133747133748133749133750133751133752133753133754133755133756133757133758133759133760133761133762133763133764133765133766133767133768133769133770133771133772133773133774133775133776133777133778133779133780133781133782133783133784133785133786133787133788133789133790133791133792133793133794133795133796133797133798133799133800133801133802133803133804133805133806133807133808133809133810133811133812133813133814133815133816133817133818133819133820133821133822133823133824133825133826133827133828133829133830133831133832133833133834133835133836133837133838133839133840133841133842133843133844133845133846133847133848133849133850133851133852133853133854133855133856133857133858133859133860133861133862133863133864133865133866133867133868133869133870133871133872133873133874133875133876133877133878133879133880133881133882133883133884133885133886133887133888133889133890133891133892133893133894133895133896133897133898133899133900133901133902133903133904133905133906133907133908133909133910133911133912133913133914133915133916133917133918133919133920133921133922133923133924133925133926133927133928133929133930133931133932133933133934133935133936133937133938133939133940133941133942133943133944133945133946133947133948133949133950133951133952133953133954133955133956133957133958133959133960133961133962133963133964133965133966133967133968133969133970133971133972133973133974133975133976133977133978133979133980133981133982133983133984133985133986133987133988133989133990133991133992133993133994133995133996133997133998133999134000134001134002134003134004134005134006134007134008134009134010134011134012134013134014134015134016134017134018134019134020134021134022134023134024134025134026134027134028134029134030134031134032134033134034134035134036134037134038134039134040134041134042134043134044134045134046134047134048134049134050134051134052134053134054134055134056134057134058134059134060134061134062134063134064134065134066134067134068134069134070134071134072134073134074134075134076134077134078134079134080134081134082134083134084134085134086134087134088134089134090134091134092134093134094134095134096134097134098134099134100134101134102134103134104134105134106134107134108134109134110134111134112134113134114134115134116134117134118134119134120134121134122134123134124134125134126134127134128134129134130134131134132134133134134134135134136134137134138134139134140134141134142134143134144134145134146134147134148134149134150134151134152134153134154134155134156134157134158134159134160134161134162134163134164134165134166134167134168134169134170134171134172134173134174134175134176134177134178134179134180134181134182134183134184134185134186134187134188134189134190134191134192134193134194134195134196134197134198134199134200134201134202134203134204134205134206134207134208134209134210134211134212134213134214134215134216134217134218134219134220134221134222134223134224134225134226134227134228134229134230134231134232134233134234134235134236134237134238134239134240134241134242134243134244134245134246134247134248134249134250134251134252134253134254134255134256134257134258134259134260134261134262134263134264134265134266134267134268134269134270134271134272134273134274134275134276134277134278134279134280134281134282134283134284134285134286134287134288134289134290134291134292134293134294134295134296134297134298134299134300134301134302134303134304134305134306134307134308134309134310134311134312134313134314134315134316134317134318134319134320134321134322134323134324134325134326134327134328134329134330134331134332134333134334134335134336134337134338134339134340134341134342134343134344134345134346134347134348134349134350134351134352134353134354134355134356134357134358134359134360134361134362134363134364134365134366134367134368134369134370134371134372134373134374134375134376134377134378134379134380134381134382134383134384134385134386134387134388134389134390134391134392134393134394134395134396134397134398134399134400134401134402134403134404134405134406134407134408134409134410134411134412134413134414134415134416134417134418134419134420134421134422134423134424134425134426134427134428134429134430134431134432134433134434134435134436134437134438134439134440134441134442134443134444134445134446134447134448134449134450134451134452134453134454134455134456134457134458134459134460134461134462134463134464134465134466134467134468134469134470134471134472134473134474134475134476134477134478134479134480134481134482134483134484134485134486134487134488134489134490134491134492134493134494134495134496134497134498134499134500134501134502134503134504134505134506134507134508134509134510134511134512134513134514134515134516134517134518134519134520134521134522134523134524134525134526134527134528134529134530134531134532134533134534134535134536134537134538134539134540134541134542134543134544134545134546134547134548134549134550134551134552134553134554134555134556134557134558134559134560134561134562134563134564134565134566134567134568134569134570134571134572134573134574134575134576134577134578134579134580134581134582134583134584134585134586134587134588134589134590134591134592134593134594134595134596134597134598134599134600134601134602134603134604134605134606134607134608134609134610134611134612134613134614134615134616134617134618134619134620134621134622134623134624134625134626134627134628134629134630134631134632134633134634134635134636134637134638134639134640134641134642134643134644134645134646134647134648134649134650134651134652134653134654134655134656134657134658134659134660134661134662134663134664134665134666134667134668134669134670134671134672134673134674134675134676134677134678134679134680134681134682134683134684134685134686134687134688134689134690134691134692134693134694134695134696134697134698134699134700134701134702134703134704134705134706134707134708134709134710134711134712134713134714134715134716134717134718134719134720134721134722134723134724134725134726134727134728134729134730134731134732134733134734134735134736134737134738134739134740134741134742134743134744134745134746134747134748134749134750134751134752134753134754134755134756134757134758134759134760134761134762134763134764134765134766134767134768134769134770134771134772134773134774134775134776134777134778134779134780134781134782134783134784134785134786134787134788134789134790134791134792134793134794134795134796134797134798134799134800134801134802134803134804134805134806134807134808134809134810134811134812134813134814134815134816134817134818134819134820134821134822134823134824134825134826134827134828134829134830134831134832134833134834134835134836134837134838134839134840134841134842134843134844134845134846134847134848134849134850134851134852134853134854134855134856134857134858134859134860134861134862134863134864134865134866134867134868134869134870134871134872134873134874134875134876134877134878134879134880134881134882134883134884134885134886134887134888134889134890134891134892134893134894134895134896134897134898134899134900134901134902134903134904134905134906134907134908134909134910134911134912134913134914134915134916134917134918134919134920134921134922134923134924134925134926134927134928134929134930134931134932134933134934134935134936134937134938134939134940134941134942134943134944134945134946134947134948134949134950134951134952134953134954134955134956134957134958134959134960134961134962134963134964134965134966134967134968134969134970134971134972134973134974134975134976134977134978134979134980134981134982134983134984134985134986134987134988134989134990134991134992134993134994134995134996134997134998134999135000135001135002135003135004135005135006135007135008135009135010135011135012135013135014135015135016135017135018135019135020135021135022135023135024135025135026135027135028135029135030135031135032135033135034135035135036135037135038135039135040135041135042135043135044135045135046135047135048135049135050135051135052135053135054135055135056135057135058135059135060135061135062135063135064135065135066135067135068135069135070135071135072135073135074135075135076135077135078135079135080135081135082135083135084135085135086135087135088135089135090135091135092135093135094135095135096135097135098135099135100135101135102135103135104135105135106135107135108135109135110135111135112135113135114135115135116135117135118135119135120135121135122135123135124135125135126135127135128135129135130135131135132135133135134135135135136135137135138135139135140135141135142135143135144135145135146135147135148135149135150135151135152135153135154135155135156135157135158135159135160135161135162135163135164135165135166135167135168135169135170135171135172135173135174135175135176135177135178135179135180135181135182135183135184135185135186135187135188135189135190135191135192135193135194135195135196135197135198135199135200135201135202135203135204135205135206135207135208135209135210135211135212135213135214135215135216135217135218135219135220135221135222135223135224135225135226135227135228135229135230135231135232135233135234135235135236135237135238135239135240135241135242135243135244135245135246135247135248135249135250135251135252135253135254135255135256135257135258135259135260135261135262135263135264135265135266135267135268135269135270135271135272135273135274135275135276135277135278135279135280135281135282135283135284135285135286135287135288135289135290135291135292135293135294135295135296135297135298135299135300135301135302135303135304135305135306135307135308135309135310135311135312135313135314135315135316135317135318135319135320135321135322135323135324135325135326135327135328135329135330135331135332135333135334135335135336135337135338135339135340135341135342135343135344135345135346135347135348135349135350135351135352135353135354135355135356135357135358135359135360135361135362135363135364135365135366135367135368135369135370135371135372135373135374135375135376135377135378135379135380135381135382135383135384135385135386135387135388135389135390135391135392135393135394135395135396135397135398135399135400135401135402135403135404135405135406135407135408135409135410135411135412135413135414135415135416135417135418135419135420135421135422135423135424135425135426135427135428135429135430135431135432135433135434135435135436135437135438135439135440135441135442135443135444135445135446135447135448135449135450135451135452135453135454135455135456135457135458135459135460135461135462135463135464135465135466135467135468135469135470135471135472135473135474135475135476135477135478135479135480135481135482135483135484135485135486135487135488135489135490135491135492135493135494135495135496135497135498135499135500135501135502135503135504135505135506135507135508135509135510135511135512135513135514135515135516135517135518135519135520135521135522135523135524135525135526135527135528135529135530135531135532135533135534135535135536135537135538135539135540135541135542135543135544135545135546135547135548135549135550135551135552135553135554135555135556135557135558135559135560135561135562135563135564135565135566135567135568135569135570135571135572135573135574135575135576135577135578135579135580135581135582135583135584135585135586135587135588135589135590135591135592135593135594135595135596135597135598135599135600135601135602135603135604135605135606135607135608135609135610135611135612135613135614135615135616135617135618135619135620135621135622135623135624135625135626135627135628135629135630135631135632135633135634135635135636135637135638135639135640135641135642135643135644135645135646135647135648135649135650135651135652135653135654135655135656135657135658135659135660135661135662135663135664135665135666135667135668135669135670135671135672135673135674135675135676135677135678135679135680135681135682135683135684135685135686135687135688135689135690135691135692135693135694135695135696135697135698135699135700135701135702135703135704135705135706135707135708135709135710135711135712135713135714135715135716135717135718135719135720135721135722135723135724135725135726135727135728135729135730135731135732135733135734135735135736135737135738135739135740135741135742135743135744135745135746135747135748135749135750135751135752135753135754135755135756135757135758135759135760135761135762135763135764135765135766135767135768135769135770135771135772135773135774135775135776135777135778135779135780135781135782135783135784135785135786135787135788135789135790135791135792135793135794135795135796135797135798135799135800135801135802135803135804135805135806135807135808135809135810135811135812135813135814135815135816135817135818135819135820135821135822135823135824135825135826135827135828135829135830135831135832135833135834135835135836135837135838135839135840135841135842135843135844135845135846135847135848135849135850135851135852135853135854135855135856135857135858135859135860135861135862135863135864135865135866135867135868135869135870135871135872135873135874135875135876135877135878135879135880135881135882135883135884135885135886135887135888135889135890135891135892135893135894135895135896135897135898135899135900135901135902135903135904135905135906135907135908135909135910135911135912135913135914135915135916135917135918135919135920135921135922135923135924135925135926135927135928135929135930135931135932135933135934135935135936135937135938135939135940135941135942135943135944135945135946135947135948135949135950135951135952135953135954135955135956135957135958135959135960135961135962135963135964135965135966135967135968135969135970135971135972135973135974135975135976135977135978135979135980135981135982135983135984135985135986135987135988135989135990135991135992135993135994135995135996135997135998135999136000136001136002136003136004136005136006136007136008136009136010136011136012136013136014136015136016136017136018136019136020136021136022136023136024136025136026136027136028136029136030136031136032136033136034136035136036136037136038136039136040136041136042136043136044136045136046136047136048136049136050136051136052136053136054136055136056136057136058136059136060136061136062136063136064136065136066136067136068136069136070136071136072136073136074136075136076136077136078136079136080136081136082136083136084136085136086136087136088136089136090136091136092136093136094136095136096136097136098136099136100136101136102136103136104136105136106136107136108136109136110136111136112136113136114136115136116136117136118136119136120136121136122136123136124136125136126136127136128136129136130136131136132136133136134136135136136136137136138136139136140136141136142136143136144136145136146136147136148136149136150136151136152136153136154136155136156136157136158136159136160136161136162136163136164136165136166136167136168136169136170136171136172136173136174136175136176136177136178136179136180136181136182136183136184136185136186136187136188136189136190136191136192136193136194136195136196136197136198136199136200136201136202136203136204136205136206136207136208136209136210136211136212136213136214136215136216136217136218136219136220136221136222136223136224136225136226136227136228136229136230136231136232136233136234136235136236136237136238136239136240136241136242136243136244136245136246136247136248136249136250136251136252136253136254136255136256136257136258136259136260136261136262136263136264136265136266136267136268136269136270136271136272136273136274136275136276136277136278136279136280136281136282136283136284136285136286136287136288136289136290136291136292136293136294136295136296136297136298136299136300136301136302136303136304136305136306136307136308136309136310136311136312136313136314136315136316136317136318136319136320136321136322136323136324136325136326136327136328136329136330136331136332136333136334136335136336136337136338136339136340136341136342136343136344136345136346136347136348136349136350136351136352136353136354136355136356136357136358136359136360136361136362136363136364136365136366136367136368136369136370136371136372136373136374136375136376136377136378136379136380136381136382136383136384136385136386136387136388136389136390136391136392136393136394136395136396136397136398136399136400136401136402136403136404136405136406136407136408136409136410136411136412136413136414136415136416136417136418136419136420136421136422136423136424136425136426136427136428136429136430136431136432136433136434136435136436136437136438136439136440136441136442136443136444136445136446136447136448136449136450136451136452136453136454136455136456136457136458136459136460136461136462136463136464136465136466136467136468136469136470136471136472136473136474136475136476136477136478136479136480136481136482136483136484136485136486136487136488136489136490136491136492136493136494136495136496136497136498136499136500136501136502136503136504136505136506136507136508136509136510136511136512136513136514136515136516136517136518136519136520136521136522136523136524136525136526136527136528136529136530136531136532136533136534136535136536136537136538136539136540136541136542136543136544136545136546136547136548136549136550136551136552136553136554136555136556136557136558136559136560136561136562136563136564136565136566136567136568136569136570136571136572136573136574136575136576136577136578136579136580136581136582136583136584136585136586136587136588136589136590136591136592136593136594136595136596136597136598136599136600136601136602136603136604136605136606136607136608136609136610136611136612136613136614136615136616136617136618136619136620136621136622136623136624136625136626136627136628136629136630136631136632136633136634136635136636136637136638136639136640136641136642136643136644136645136646136647136648136649136650136651136652136653136654136655136656136657136658136659136660136661136662136663136664136665136666136667136668136669136670136671136672136673136674136675136676136677136678136679136680136681136682136683136684136685136686136687136688136689136690136691136692136693136694136695136696136697136698136699136700136701136702136703136704136705136706136707136708136709136710136711136712136713136714136715136716136717136718136719136720136721136722136723136724136725136726136727136728136729136730136731136732136733136734136735136736136737136738136739136740136741136742136743136744136745136746136747136748136749136750136751136752136753136754136755136756136757136758136759136760136761136762136763136764136765136766136767136768136769136770136771136772136773136774136775136776136777136778136779136780136781136782136783136784136785136786136787136788136789136790136791136792136793136794136795136796136797136798136799136800136801136802136803136804136805136806136807136808136809136810136811136812136813136814136815136816136817136818136819136820136821136822136823136824136825136826136827136828136829136830136831136832136833136834136835136836136837136838136839136840136841136842136843136844136845136846136847136848136849136850136851136852136853136854136855136856136857136858136859136860136861136862136863136864136865136866136867136868136869136870136871136872136873136874136875136876136877136878136879136880136881136882136883136884136885136886136887136888136889136890136891136892136893136894136895136896136897136898136899136900136901136902136903136904136905136906136907136908136909136910136911136912136913136914136915136916136917136918136919136920136921136922136923136924136925136926136927136928136929136930136931136932136933136934136935136936136937136938136939136940136941136942136943136944136945136946136947136948136949136950136951136952136953136954136955136956136957136958136959136960136961136962136963136964136965136966136967136968136969136970136971136972136973136974136975136976136977136978136979136980136981136982136983136984136985136986136987136988136989136990136991136992136993136994136995136996136997136998136999137000137001137002137003137004137005137006137007137008137009137010137011137012137013137014137015137016137017137018137019137020137021137022137023137024137025137026137027137028137029137030137031137032137033137034137035137036137037137038137039137040137041137042137043137044137045137046137047137048137049137050137051137052137053137054137055137056137057137058137059137060137061137062137063137064137065137066137067137068137069137070137071137072137073137074137075137076137077137078137079137080137081137082137083137084137085137086137087137088137089137090137091137092137093137094137095137096137097137098137099137100137101137102137103137104137105137106137107137108137109137110137111137112137113137114137115137116137117137118137119137120137121137122137123137124137125137126137127137128137129137130137131137132137133137134137135137136137137137138137139137140137141137142137143137144137145137146137147137148137149137150137151137152137153137154137155137156137157137158137159137160137161137162137163137164137165137166137167137168137169137170137171137172137173137174137175137176137177137178137179137180137181137182137183137184137185137186137187137188137189137190137191137192137193137194137195137196137197137198137199137200137201137202137203137204137205137206137207137208137209137210137211137212137213137214137215137216137217137218137219137220137221137222137223137224137225137226137227137228137229137230137231137232137233137234137235137236137237137238137239137240137241137242137243137244137245137246137247137248137249137250137251137252137253137254137255137256137257137258137259137260137261137262137263137264137265137266137267137268137269137270137271137272137273137274137275137276137277137278137279137280137281137282137283137284137285137286137287137288137289137290137291137292137293137294137295137296137297137298137299137300137301137302137303137304137305137306137307137308137309137310137311137312137313137314137315137316137317137318137319137320137321137322137323137324137325137326137327137328137329137330137331137332137333137334137335137336137337137338137339137340137341137342137343137344137345137346137347137348137349137350137351137352137353137354137355137356137357137358137359137360137361137362137363137364137365137366137367137368137369137370137371137372137373137374137375137376137377137378137379137380137381137382137383137384137385137386137387137388137389137390137391137392137393137394137395137396137397137398137399137400137401137402137403137404137405137406137407137408137409137410137411137412137413137414137415137416137417137418137419137420137421137422137423137424137425137426137427137428137429137430137431137432137433137434137435137436137437137438137439137440137441137442137443137444137445137446137447137448137449137450137451137452137453137454137455137456137457137458137459137460137461137462137463137464137465137466137467137468137469137470137471137472137473137474137475137476137477137478137479137480137481137482137483137484137485137486137487137488137489137490137491137492137493137494137495137496137497137498137499137500137501137502137503137504137505137506137507137508137509137510137511137512137513137514137515137516137517137518137519137520137521137522137523137524137525137526137527137528137529137530137531137532137533137534137535137536137537137538137539137540137541137542137543137544137545137546137547137548137549137550137551137552137553137554137555137556137557137558137559137560137561137562137563137564137565137566137567137568137569137570137571137572137573137574137575137576137577137578137579137580137581137582137583137584137585137586137587137588137589137590137591137592137593137594137595137596137597137598137599137600137601137602137603137604137605137606137607137608137609137610137611137612137613137614137615137616137617137618137619137620137621137622137623137624137625137626137627137628137629137630137631137632137633137634137635137636137637137638137639137640137641137642137643137644137645137646137647137648137649137650137651137652137653137654137655137656137657137658137659137660137661137662137663137664137665137666137667137668137669137670137671137672137673137674137675137676137677137678137679137680137681137682137683137684137685137686137687137688137689137690137691137692137693137694137695137696137697137698137699137700137701137702137703137704137705137706137707137708137709137710137711137712137713137714137715137716137717137718137719137720137721137722137723137724137725137726137727137728137729137730137731137732137733137734137735137736137737137738137739137740137741137742137743137744137745137746137747137748137749137750137751137752137753137754137755137756137757137758137759137760137761137762137763137764137765137766137767137768137769137770137771137772137773137774137775137776137777137778137779137780137781137782137783137784137785137786137787137788137789137790137791137792137793137794137795137796137797137798137799137800137801137802137803137804137805137806137807137808137809137810137811137812137813137814137815137816137817137818137819137820137821137822137823137824137825137826137827137828137829137830137831137832137833137834137835137836137837137838137839137840137841137842137843137844137845137846137847137848137849137850137851137852137853137854137855137856137857137858137859137860137861137862137863137864137865137866137867137868137869137870137871137872137873137874137875137876137877137878137879137880137881137882137883137884137885137886137887137888137889137890137891137892137893137894137895137896137897137898137899137900137901137902137903137904137905137906137907137908137909137910137911137912137913137914137915137916137917137918137919137920137921137922137923137924137925137926137927137928137929137930137931137932137933137934137935137936137937137938137939137940137941137942137943137944137945137946137947137948137949137950137951137952137953137954137955137956137957137958137959137960137961137962137963137964137965137966137967137968137969137970137971137972137973137974137975137976137977137978137979137980137981137982137983137984137985137986137987137988137989137990137991137992137993137994137995137996137997137998137999138000138001138002138003138004138005138006138007138008138009138010138011138012138013138014138015138016138017138018138019138020138021138022138023138024138025138026138027138028138029138030138031138032138033138034138035138036138037138038138039138040138041138042138043138044138045138046138047138048138049138050138051138052138053138054138055138056138057138058138059138060138061138062138063138064138065138066138067138068138069138070138071138072138073138074138075138076138077138078138079138080138081138082138083138084138085138086138087138088138089138090138091138092138093138094138095138096138097138098138099138100138101138102138103138104138105138106138107138108138109138110138111138112138113138114138115138116138117138118138119138120138121138122138123138124138125138126138127138128138129138130138131138132138133138134138135138136138137138138138139138140138141138142138143138144138145138146138147138148138149138150138151138152138153138154138155138156138157138158138159138160138161138162138163138164138165138166138167138168138169138170138171138172138173138174138175138176138177138178138179138180138181138182138183138184138185138186138187138188138189138190138191138192138193138194138195138196138197138198138199138200138201138202138203138204138205138206138207138208138209138210138211138212138213138214138215138216138217138218138219138220138221138222138223138224138225138226138227138228138229138230138231138232138233138234138235138236138237138238138239138240138241138242138243138244138245138246138247138248138249138250138251138252138253138254138255138256138257138258138259138260138261138262138263138264138265138266138267138268138269138270138271138272138273138274138275138276138277138278138279138280138281138282138283138284138285138286138287138288138289138290138291138292138293138294138295138296138297138298138299138300138301138302138303138304138305138306138307138308138309138310138311138312138313138314138315138316138317138318138319138320138321138322138323138324138325138326138327138328138329138330138331138332138333138334138335138336138337138338138339138340138341138342138343138344138345138346138347138348138349138350138351138352138353138354138355138356138357138358138359138360138361138362138363138364138365138366138367138368138369138370138371138372138373138374138375138376138377138378138379138380138381138382138383138384138385138386138387138388138389138390138391138392138393138394138395138396138397138398138399138400138401138402138403138404138405138406138407138408138409138410138411138412138413138414138415138416138417138418138419138420138421138422138423138424138425138426138427138428138429138430138431138432138433138434138435138436138437138438138439138440138441138442138443138444138445138446138447138448138449138450138451138452138453138454138455138456138457138458138459138460138461138462138463138464138465138466138467138468138469138470138471138472138473138474138475138476138477138478138479138480138481138482138483138484138485138486138487138488138489138490138491138492138493138494138495138496138497138498138499138500138501138502138503138504138505138506138507138508138509138510138511138512138513138514138515138516138517138518138519138520138521138522138523138524138525138526138527138528138529138530138531138532138533138534138535138536138537138538138539138540138541138542138543138544138545138546138547138548138549138550138551138552138553138554138555138556138557138558138559138560138561138562138563138564138565138566138567138568138569138570138571138572138573138574138575138576138577138578138579138580138581138582138583138584138585138586138587138588138589138590138591138592138593138594138595138596138597138598138599138600138601138602138603138604138605138606138607138608138609138610138611138612138613138614138615138616138617138618138619138620138621138622138623138624138625138626138627138628138629138630138631138632138633138634138635138636138637138638138639138640138641138642138643138644138645138646138647138648138649138650138651138652138653138654138655138656138657138658138659138660138661138662138663138664138665138666138667138668138669138670138671138672138673138674138675138676138677138678138679138680138681138682138683138684138685138686138687138688138689138690138691138692138693138694138695138696138697138698138699138700138701138702138703138704138705138706138707138708138709138710138711138712138713138714138715138716138717138718138719138720138721138722138723138724138725138726138727138728138729138730138731138732138733138734138735138736138737138738138739138740138741138742138743138744138745138746138747138748138749138750138751138752138753138754138755138756138757138758138759138760138761138762138763138764138765138766138767138768138769138770138771138772138773138774138775138776138777138778138779138780138781138782138783138784138785138786138787138788138789138790138791138792138793138794138795138796138797138798138799138800138801138802138803138804138805138806138807138808138809138810138811138812138813138814138815138816138817138818138819138820138821138822138823138824138825138826138827138828138829138830138831138832138833138834138835138836138837138838138839138840138841138842138843138844138845138846138847138848138849138850138851138852138853138854138855138856138857138858138859138860138861138862138863138864138865138866138867138868138869138870138871138872138873138874138875138876138877138878138879138880138881138882138883138884138885138886138887138888138889138890138891138892138893138894138895138896138897138898138899138900138901138902138903138904138905138906138907138908138909138910138911138912138913138914138915138916138917138918138919138920138921138922138923138924138925138926138927138928138929138930138931138932138933138934138935138936138937138938138939138940138941138942138943138944138945138946138947138948138949138950138951138952138953138954138955138956138957138958138959138960138961138962138963138964138965138966138967138968138969138970138971138972138973138974138975138976138977138978138979138980138981138982138983138984138985138986138987138988138989138990138991138992138993138994138995138996138997138998138999139000139001139002139003139004139005139006139007139008139009139010139011139012139013139014139015139016139017139018139019139020139021139022139023139024139025139026139027139028139029139030139031139032139033139034139035139036139037139038139039139040139041139042139043139044139045139046139047139048139049139050139051139052139053139054139055139056139057139058139059139060139061139062139063139064139065139066139067139068139069139070139071139072139073139074139075139076139077139078139079139080139081139082139083139084139085139086139087139088139089139090139091139092139093139094139095139096139097139098139099139100139101139102139103139104139105139106139107139108139109139110139111139112139113139114139115139116139117139118139119139120139121139122139123139124139125139126139127139128139129139130139131139132139133139134139135139136139137139138139139139140139141139142139143139144139145139146139147139148139149139150139151139152139153139154139155139156139157139158139159139160139161139162139163139164139165139166139167139168139169139170139171139172139173139174139175139176139177139178139179139180139181139182139183139184139185139186139187139188139189139190139191139192139193139194139195139196139197139198139199139200139201139202139203139204139205139206139207139208139209139210139211139212139213139214139215139216139217139218139219139220139221139222139223139224139225139226139227139228139229139230139231139232139233139234139235139236139237139238139239139240139241139242139243139244139245139246139247139248139249139250139251139252139253139254139255139256139257139258139259139260139261139262139263139264139265139266139267139268139269139270139271139272139273139274139275139276139277139278139279139280139281139282139283139284139285139286139287139288139289139290139291139292139293139294139295139296139297139298139299139300139301139302139303139304139305139306139307139308139309139310139311139312139313139314139315139316139317139318139319139320139321139322139323139324139325139326139327139328139329139330139331139332139333139334139335139336139337139338139339139340139341139342139343139344139345139346139347139348139349139350139351139352139353139354139355139356139357139358139359139360139361139362139363139364139365139366139367139368139369139370139371139372139373139374139375139376139377139378139379139380139381139382139383139384139385139386139387139388139389139390139391139392139393139394139395139396139397139398139399139400139401139402139403139404139405139406139407139408139409139410139411139412139413139414139415139416139417139418139419139420139421139422139423139424139425139426139427139428139429139430139431139432139433139434139435139436139437139438139439139440139441139442139443139444139445139446139447139448139449139450139451139452139453139454139455139456139457139458139459139460139461139462139463139464139465139466139467139468139469139470139471139472139473139474139475139476139477139478139479139480139481139482139483139484139485139486139487139488139489139490139491139492139493139494139495139496139497139498139499139500139501139502139503139504139505139506139507139508139509139510139511139512139513139514139515139516139517139518139519139520139521139522139523139524139525139526139527139528139529139530139531139532139533139534139535139536139537139538139539139540139541139542139543139544139545139546139547139548139549139550139551139552139553139554139555139556139557139558139559139560139561139562139563139564139565139566139567139568139569139570139571139572139573139574139575139576139577139578139579139580139581139582139583139584139585139586139587139588139589139590139591139592139593139594139595139596139597139598139599139600139601139602139603139604139605139606139607139608139609139610139611139612139613139614139615139616139617139618139619139620139621139622139623139624139625139626139627139628139629139630139631139632139633139634139635139636139637139638139639139640139641139642139643139644139645139646139647139648139649139650139651139652139653139654139655139656139657139658139659139660139661139662139663139664139665139666139667139668139669139670139671139672139673139674139675139676139677139678139679139680139681139682139683139684139685139686139687139688139689139690139691139692139693139694139695139696139697139698139699139700139701139702139703139704139705139706139707139708139709139710139711139712139713139714139715139716139717139718139719139720139721139722139723139724139725139726139727139728139729139730139731139732139733139734139735139736139737139738139739139740139741139742139743139744139745139746139747139748139749139750139751139752139753139754139755139756139757139758139759139760139761139762139763139764139765139766139767139768139769139770139771139772139773139774139775139776139777139778139779139780139781139782139783139784139785139786139787139788139789139790139791139792139793139794139795139796139797139798139799139800139801139802139803139804139805139806139807139808139809139810139811139812139813139814139815139816139817139818139819139820139821139822139823139824139825139826139827139828139829139830139831139832139833139834139835139836139837139838139839139840139841139842139843139844139845139846139847139848139849139850139851139852139853139854139855139856139857139858139859139860139861139862139863139864139865139866139867139868139869139870139871139872139873139874139875139876139877139878139879139880139881139882139883139884139885139886139887139888139889139890139891139892139893139894139895139896139897139898139899139900139901139902139903139904139905139906139907139908139909139910139911139912139913139914139915139916139917139918139919139920139921139922139923139924139925139926139927139928139929139930139931139932139933139934139935139936139937139938139939139940139941139942139943139944139945139946139947139948139949139950139951139952139953139954139955139956139957139958139959139960139961139962139963139964139965139966139967139968139969139970139971139972139973139974139975139976139977139978139979139980139981139982139983139984139985139986139987139988139989139990139991139992139993139994139995139996139997139998139999140000140001140002140003140004140005140006140007140008140009140010140011140012140013140014140015140016140017140018140019140020140021140022140023140024140025140026140027140028140029140030140031140032140033140034140035140036140037140038140039140040140041140042140043140044140045140046140047140048140049140050140051140052140053140054140055140056140057140058140059140060140061140062140063140064140065140066140067140068140069140070140071140072140073140074140075140076140077140078140079140080140081140082140083140084140085140086140087140088140089140090140091140092140093140094140095140096140097140098140099140100140101140102140103140104140105140106140107140108140109140110140111140112140113140114140115140116140117140118140119140120140121140122140123140124140125140126140127140128140129140130140131140132140133140134140135140136140137140138140139140140140141140142140143140144140145140146140147140148140149140150140151140152140153140154140155140156140157140158140159140160140161140162140163140164140165140166140167140168140169140170140171140172140173140174140175140176140177140178140179140180140181140182140183140184140185140186140187140188140189140190140191140192140193140194140195140196140197140198140199140200140201140202140203140204140205140206140207140208140209140210140211140212140213140214140215140216140217140218140219140220140221140222140223140224140225140226140227140228140229140230140231140232140233140234140235140236140237140238140239140240140241140242140243140244140245140246140247140248140249140250140251140252140253140254140255140256140257140258140259140260140261140262140263140264140265140266140267140268140269140270140271140272140273140274140275140276140277140278140279140280140281140282140283140284140285140286140287140288140289140290140291140292140293140294140295140296140297140298140299140300140301140302140303140304140305140306140307140308140309140310140311140312140313140314140315140316140317140318140319140320140321140322140323140324140325140326140327140328140329140330140331140332140333140334140335140336140337140338140339140340140341140342140343140344140345140346140347140348140349140350140351140352140353140354140355140356140357140358140359140360140361140362140363140364140365140366140367140368140369140370140371140372140373140374140375140376140377140378140379140380140381140382140383140384140385140386140387140388140389140390140391140392140393140394140395140396140397140398140399140400140401140402140403140404140405140406140407140408140409140410140411140412140413140414140415140416140417140418140419140420140421140422140423140424140425140426140427140428140429140430140431140432140433140434140435140436140437140438140439140440140441140442140443140444140445140446140447140448140449140450140451140452140453140454140455140456140457140458140459140460140461140462140463140464140465140466140467140468140469140470140471140472140473140474140475140476140477140478140479140480140481140482140483140484140485140486140487140488140489140490140491140492140493140494140495140496140497140498140499140500140501140502140503140504140505140506140507140508140509140510140511140512140513140514140515140516140517140518140519140520140521140522140523140524140525140526140527140528140529140530140531140532140533140534140535140536140537140538140539140540140541140542140543140544140545140546140547140548140549140550140551140552140553140554140555140556140557140558140559140560140561140562140563140564140565140566140567140568140569140570140571140572140573140574140575140576140577140578140579140580140581140582140583140584140585140586140587140588140589140590140591140592140593140594140595140596140597140598140599140600140601140602140603140604140605140606140607140608140609140610140611140612140613140614140615140616140617140618140619140620140621140622140623140624140625140626140627140628140629140630140631140632140633140634140635140636140637140638140639140640140641140642140643140644140645140646140647140648140649140650140651140652140653140654140655140656140657140658140659140660140661140662140663140664140665140666140667140668140669140670140671140672140673140674140675140676140677140678140679140680140681140682140683140684140685140686140687140688140689140690140691140692140693140694140695140696140697140698140699140700140701140702140703140704140705140706140707140708140709140710140711140712140713140714140715140716140717140718140719140720140721140722140723140724140725140726140727140728140729140730140731140732140733140734140735140736140737140738140739140740140741140742140743140744140745140746140747140748140749140750140751140752140753140754140755140756140757140758140759140760140761140762140763140764140765140766140767140768140769140770140771140772140773140774140775140776140777140778140779140780140781140782140783140784140785140786140787140788140789140790140791140792140793140794140795140796140797140798140799140800140801140802140803140804140805140806140807140808140809140810140811140812140813140814140815140816140817140818140819140820140821140822140823140824140825140826140827140828140829140830140831140832140833140834140835140836140837140838140839140840140841140842140843140844140845140846140847140848140849140850140851140852140853140854140855140856140857140858140859140860140861140862140863140864140865140866140867140868140869140870140871140872140873140874140875140876140877140878140879140880140881140882140883140884140885140886140887140888140889140890140891140892140893140894140895140896140897140898140899140900140901140902140903140904140905140906140907140908140909140910140911140912140913140914140915140916140917140918140919140920140921140922140923140924140925140926140927140928140929140930140931140932140933140934140935140936140937140938140939140940140941140942140943140944140945140946140947140948140949140950140951140952140953140954140955140956140957140958140959140960140961140962140963140964140965140966140967140968140969140970140971140972140973140974140975140976140977140978140979140980140981140982140983140984140985140986140987140988140989140990140991140992140993140994140995140996140997140998140999141000141001141002141003141004141005141006141007141008141009141010141011141012141013141014141015141016141017141018141019141020141021141022141023141024141025141026141027141028141029141030141031141032141033141034141035141036141037141038141039141040141041141042141043141044141045141046141047141048141049141050141051141052141053141054141055141056141057141058141059141060141061141062141063141064141065141066141067141068141069141070141071141072141073141074141075141076141077141078141079141080141081141082141083141084141085141086141087141088141089141090141091141092141093141094141095141096141097141098141099141100141101141102141103141104141105141106141107141108141109141110141111141112141113141114141115141116141117141118141119141120141121141122141123141124141125141126141127141128141129141130141131141132141133141134141135141136141137141138141139141140141141141142141143141144141145141146141147141148141149141150141151141152141153141154141155141156141157141158141159141160141161141162141163141164141165141166141167141168141169141170141171141172141173141174141175141176141177141178141179141180141181141182141183141184141185141186141187141188141189141190141191141192141193141194141195141196141197141198141199141200141201141202141203141204141205141206141207141208141209141210141211141212141213141214141215141216141217141218141219141220141221141222141223141224141225141226141227141228141229141230141231141232141233141234141235141236141237141238141239141240141241141242141243141244141245141246141247141248141249141250141251141252141253141254141255141256141257141258141259141260141261141262141263141264141265141266141267141268141269141270141271141272141273141274141275141276141277141278141279141280141281141282141283141284141285141286141287141288141289141290141291141292141293141294141295141296141297141298141299141300141301141302141303141304141305141306141307141308141309141310141311141312141313141314141315141316141317141318141319141320141321141322141323141324141325141326141327141328141329141330141331141332141333141334141335141336141337141338141339141340141341141342141343141344141345141346141347141348141349141350141351141352141353141354141355141356141357141358141359141360141361141362141363141364141365141366141367141368141369141370141371141372141373141374141375141376141377141378141379141380141381141382141383141384141385141386141387141388141389141390141391141392141393141394141395141396141397141398141399141400141401141402141403141404141405141406141407141408141409141410141411141412141413141414141415141416141417141418141419141420141421141422141423141424141425141426141427141428141429141430141431141432141433141434141435141436141437141438141439141440141441141442141443141444141445141446141447141448141449141450141451141452141453141454141455141456141457141458141459141460141461141462141463141464141465141466141467141468141469141470141471141472141473141474141475141476141477141478141479141480141481141482141483141484141485141486141487141488141489141490141491141492141493141494141495141496141497141498141499141500141501141502141503141504141505141506141507141508141509141510141511141512141513141514141515141516141517141518141519141520141521141522141523141524141525141526141527141528141529141530141531141532141533141534141535141536141537141538141539141540141541141542141543141544141545141546141547141548141549141550141551141552141553141554141555141556141557141558141559141560141561141562141563141564141565141566141567141568141569141570141571141572141573141574141575141576141577141578141579141580141581141582141583141584141585141586141587141588141589141590141591141592141593141594141595141596141597141598141599141600141601141602141603141604141605141606141607141608141609141610141611141612141613141614141615141616141617141618141619141620141621141622141623141624141625141626141627141628141629141630141631141632141633141634141635141636141637141638141639141640141641141642141643141644141645141646141647141648141649141650141651141652141653141654141655141656141657141658141659141660141661141662141663141664141665141666141667141668141669141670141671141672141673141674141675141676141677141678141679141680141681141682141683141684141685141686141687141688141689141690141691141692141693141694141695141696141697141698141699141700141701141702141703141704141705141706141707141708141709141710141711141712141713141714141715141716141717141718141719141720141721141722141723141724141725141726141727141728141729141730141731141732141733141734141735141736141737141738141739141740141741141742141743141744141745141746141747141748141749141750141751141752141753141754141755141756141757141758141759141760141761141762141763141764141765141766141767141768141769141770141771141772141773141774141775141776141777141778141779141780141781141782141783141784141785141786141787141788141789141790141791141792141793141794141795141796141797141798141799141800141801141802141803141804141805141806141807141808141809141810141811141812141813141814141815141816141817141818141819141820141821141822141823141824141825141826141827141828141829141830141831141832141833141834141835141836141837141838141839141840141841141842141843141844141845141846141847141848141849141850141851141852141853141854141855141856141857141858141859141860141861141862141863141864141865141866141867141868141869141870141871141872141873141874141875141876141877141878141879141880141881141882141883141884141885141886141887141888141889141890141891141892141893141894141895141896141897141898141899141900141901141902141903141904141905141906141907141908141909141910141911141912141913141914141915141916141917141918141919141920141921141922141923141924141925141926141927141928141929141930141931141932141933141934141935141936141937141938141939141940141941141942141943141944141945141946141947141948141949141950141951141952141953141954141955141956141957141958141959141960141961141962141963141964141965141966141967141968141969141970141971141972141973141974141975141976141977141978141979141980141981141982141983141984141985141986141987141988141989141990141991141992141993141994141995141996141997141998141999142000142001142002142003142004142005142006142007142008142009142010142011142012142013142014142015142016142017142018142019142020142021142022142023142024142025142026142027142028142029142030142031142032142033142034142035142036142037142038142039142040142041142042142043142044142045142046142047142048142049142050142051142052142053142054142055142056142057142058142059142060142061142062142063142064142065142066142067142068142069142070142071142072142073142074142075142076142077142078142079142080142081142082142083142084142085142086142087142088142089142090142091142092142093142094142095142096142097142098142099142100142101142102142103142104142105142106142107142108142109142110142111142112142113142114142115142116142117142118142119142120142121142122142123142124142125142126142127142128142129142130142131142132142133142134142135142136142137142138142139142140142141142142142143142144142145142146142147142148142149142150142151142152142153142154142155142156142157142158142159142160142161142162142163142164142165142166142167142168142169142170142171142172142173142174142175142176142177142178142179142180142181142182142183142184142185142186142187142188142189142190142191142192142193142194142195142196142197142198142199142200142201142202142203142204142205142206142207142208142209142210142211142212142213142214142215142216142217142218142219142220142221142222142223142224142225142226142227142228142229142230142231142232142233142234142235142236142237142238142239142240142241142242142243142244142245142246142247142248142249142250142251142252142253142254142255142256142257142258142259142260142261142262142263142264142265142266142267142268142269142270142271142272142273142274142275142276142277142278142279142280142281142282142283142284142285142286142287142288142289142290142291142292142293142294142295142296142297142298142299142300142301142302142303142304142305142306142307142308142309142310142311142312142313142314142315142316142317142318142319142320142321142322142323142324142325142326142327142328142329142330142331142332142333142334142335142336142337142338142339142340142341142342142343142344142345142346142347142348142349142350142351142352142353142354142355142356142357142358142359142360142361142362142363142364142365142366142367142368142369142370142371142372142373142374142375142376142377142378142379142380142381142382142383142384142385142386142387142388142389142390142391142392142393142394142395142396142397142398142399142400142401142402142403142404142405142406142407142408142409142410142411142412142413142414142415142416142417142418142419142420142421142422142423142424142425142426142427142428142429142430142431142432142433142434142435142436142437142438142439142440142441142442142443142444142445142446142447142448142449142450142451142452142453142454142455142456142457142458142459142460142461142462142463142464142465142466142467142468142469142470142471142472142473142474142475142476142477142478142479142480142481142482142483142484142485142486142487142488142489142490142491142492142493142494142495142496142497142498142499142500142501142502142503142504142505142506142507142508142509142510142511142512142513142514142515142516142517142518142519142520142521142522142523142524142525142526142527142528142529142530142531142532142533142534142535142536142537142538142539142540142541142542142543142544142545142546142547142548142549142550142551142552142553142554142555142556142557142558142559142560142561142562142563142564142565142566142567142568142569142570142571142572142573142574142575142576142577142578142579142580142581142582142583142584142585142586142587142588142589142590142591142592142593142594142595142596142597142598142599142600142601142602142603142604142605142606142607142608142609142610142611142612142613142614142615142616142617142618142619142620142621142622142623142624142625142626142627142628142629142630142631142632142633142634142635142636142637142638142639142640142641142642142643142644142645142646142647142648142649142650142651142652142653142654142655142656142657142658142659142660142661142662142663142664142665142666142667142668142669142670142671142672142673142674142675142676142677142678142679142680142681142682142683142684142685142686142687142688142689142690142691142692142693142694142695142696142697142698142699142700142701142702142703142704142705142706142707142708142709142710142711142712142713142714142715142716142717142718142719142720142721142722142723142724142725142726142727142728142729142730142731142732142733142734142735142736142737142738142739142740142741142742142743142744142745142746142747142748142749142750142751142752142753142754142755142756142757142758142759142760142761142762142763142764142765142766142767142768142769142770142771142772142773142774142775142776142777142778142779142780142781142782142783142784142785142786142787142788142789142790142791142792142793142794142795142796142797142798142799142800142801142802142803142804142805142806142807142808142809142810142811142812142813142814142815142816142817142818142819142820142821142822142823142824142825142826142827142828142829142830142831142832142833142834142835142836142837142838142839142840142841142842142843142844142845142846142847142848142849142850142851142852142853142854142855142856142857142858142859142860142861142862142863142864142865142866142867142868142869142870142871142872142873142874142875142876142877142878142879142880142881142882142883142884142885142886142887142888142889142890142891142892142893142894142895142896142897142898142899142900142901142902142903142904142905142906142907142908142909142910142911142912142913142914142915142916142917142918142919142920142921142922142923142924142925142926142927142928142929142930142931142932142933142934142935142936142937142938142939142940142941142942142943142944142945142946142947142948142949142950142951142952142953142954142955142956142957142958142959142960142961142962142963142964142965142966142967142968142969142970142971142972142973142974142975142976142977142978142979142980142981142982142983142984142985142986142987142988142989142990142991142992142993142994142995142996142997142998142999143000143001143002143003143004143005143006143007143008143009143010143011143012143013143014143015143016143017143018143019143020143021143022143023143024143025143026143027143028143029143030143031143032143033143034143035143036143037143038143039143040143041143042143043143044143045143046143047143048143049143050143051143052143053143054143055143056143057143058143059143060143061143062143063143064143065143066143067143068143069143070143071143072143073143074143075143076143077143078143079143080143081143082143083143084143085143086143087143088143089143090143091143092143093143094143095143096143097143098143099143100143101143102143103143104143105143106143107143108143109143110143111143112143113143114143115143116143117143118143119143120143121143122143123143124143125143126143127143128143129143130143131143132143133143134143135143136143137143138143139143140143141143142143143143144143145143146143147143148143149143150143151143152143153143154143155143156143157143158143159143160143161143162143163143164143165143166143167143168143169143170143171143172143173143174143175143176143177143178143179143180143181143182143183143184143185143186143187143188143189143190143191143192143193143194143195143196143197143198143199143200143201143202143203143204143205143206143207143208143209143210143211143212143213143214143215143216143217143218143219143220143221143222143223143224143225143226143227143228143229143230143231143232143233143234143235143236143237143238143239143240143241143242143243143244143245143246143247143248143249143250143251143252143253143254143255143256143257143258143259143260143261143262143263143264143265143266143267143268143269143270143271143272143273143274143275143276143277143278143279143280143281143282143283143284143285143286143287143288143289143290143291143292143293143294143295143296143297143298143299143300143301143302143303143304143305143306143307143308143309143310143311143312143313143314143315143316143317143318143319143320143321143322143323143324143325143326143327143328143329143330143331143332143333143334143335143336143337143338143339143340143341143342143343143344143345143346143347143348143349143350143351143352143353143354143355143356143357143358143359143360143361143362143363143364143365143366143367143368143369143370143371143372143373143374143375143376143377143378143379143380143381143382143383143384143385143386143387143388143389143390143391143392143393143394143395143396143397143398143399143400143401143402143403143404143405143406143407143408143409143410143411143412143413143414143415143416143417143418143419143420143421143422143423143424143425143426143427143428143429143430143431143432143433143434143435143436143437143438143439143440143441143442143443143444143445143446143447143448143449143450143451143452143453143454143455143456143457143458143459143460143461143462143463143464143465143466143467143468143469143470143471143472143473143474143475143476143477143478143479143480143481143482143483143484143485143486143487143488143489143490143491143492143493143494143495143496143497143498143499143500143501143502143503143504143505143506143507143508143509143510143511143512143513143514143515143516143517143518143519143520143521143522143523143524143525143526143527143528143529143530143531143532143533143534143535143536143537143538143539143540143541143542143543143544143545143546143547143548143549143550143551143552143553143554143555143556143557143558143559143560143561143562143563143564143565143566143567143568143569143570143571143572143573143574143575143576143577143578143579143580143581143582143583143584143585143586143587143588143589143590143591143592143593143594143595143596143597143598143599143600143601143602143603143604143605143606143607143608143609143610143611143612143613143614143615143616143617143618143619143620143621143622143623143624143625143626143627143628143629143630143631143632143633143634143635143636143637143638143639143640143641143642143643143644143645143646143647143648143649143650143651143652143653143654143655143656143657143658143659143660143661143662143663143664143665143666143667143668143669143670143671143672143673143674143675143676143677143678143679143680143681143682143683143684143685143686143687143688143689143690143691143692143693143694143695143696143697143698143699143700143701143702143703143704143705143706143707143708143709143710143711143712143713143714143715143716143717143718143719143720143721143722143723143724143725143726143727143728143729143730143731143732143733143734143735143736143737143738143739143740143741143742143743143744143745143746143747143748143749143750143751143752143753143754143755143756143757143758143759143760143761143762143763143764143765143766143767143768143769143770143771143772143773143774143775143776143777143778143779143780143781143782143783143784143785143786143787143788143789143790143791143792143793143794143795143796143797143798143799143800143801143802143803143804143805143806143807143808143809143810143811143812143813143814143815143816143817143818143819143820143821143822143823143824143825143826143827143828143829143830143831143832143833143834143835143836143837143838143839143840143841143842143843143844143845143846143847143848143849143850143851143852143853143854143855143856143857143858143859143860143861143862143863143864143865143866143867143868143869143870143871143872143873143874143875143876143877143878143879143880143881143882143883143884143885143886143887143888143889143890143891143892143893143894143895143896143897143898143899143900143901143902143903143904143905143906143907143908143909143910143911143912143913143914143915143916143917143918143919143920143921143922143923143924143925143926143927143928143929143930143931143932143933143934143935143936143937143938143939143940143941143942143943143944143945143946143947143948143949143950143951143952143953143954143955143956143957143958143959143960143961143962143963143964143965143966143967143968143969143970143971143972143973143974143975143976143977143978143979143980143981143982143983143984143985143986143987143988143989143990143991143992143993143994143995143996143997143998143999144000144001144002144003144004144005144006144007144008144009144010144011144012144013144014144015144016144017144018144019144020144021144022144023144024144025144026144027144028144029144030144031144032144033144034144035144036144037144038144039144040144041144042144043144044144045144046144047144048144049144050144051144052144053144054144055144056144057144058144059144060144061144062144063144064144065144066144067144068144069144070144071144072144073144074144075144076144077144078144079144080144081144082144083144084144085144086144087144088144089144090144091144092144093144094144095144096144097144098144099144100144101144102144103144104144105144106144107144108144109144110144111144112144113144114144115144116144117144118144119144120144121144122144123144124144125144126144127144128144129144130144131144132144133144134144135144136144137144138144139144140144141144142144143144144144145144146144147144148144149144150144151144152144153144154144155144156144157144158144159144160144161144162144163144164144165144166144167144168144169144170144171144172144173144174144175144176144177144178144179144180144181144182144183144184144185144186144187144188144189144190144191144192144193144194144195144196144197144198144199144200144201144202144203144204144205144206144207144208144209144210144211144212144213144214144215144216144217144218144219144220144221144222144223144224144225144226144227144228144229144230144231144232144233144234144235144236144237144238144239144240144241144242144243144244144245144246144247144248144249144250144251144252144253144254144255144256144257144258144259144260144261144262144263144264144265144266144267144268144269144270144271144272144273144274144275144276144277144278144279144280144281144282144283144284144285144286144287144288144289144290144291144292144293144294144295144296144297144298144299144300144301144302144303144304144305144306144307144308144309144310144311144312144313144314144315144316144317144318144319144320144321144322144323144324144325144326144327144328144329144330144331144332144333144334144335144336144337144338144339144340144341144342144343144344144345144346144347144348144349144350144351144352144353144354144355144356144357144358144359144360144361144362144363144364144365144366144367144368144369144370144371144372144373144374144375144376144377144378144379144380144381144382144383144384144385144386144387144388144389144390144391144392144393144394144395144396144397144398144399144400144401144402144403144404144405144406144407144408144409144410144411144412144413144414144415144416144417144418144419144420144421144422144423144424144425144426144427144428144429144430144431144432144433144434144435144436144437144438144439144440144441144442144443144444144445144446144447144448144449144450144451144452144453144454144455144456144457144458144459144460144461144462144463144464144465144466144467144468144469144470144471144472144473144474144475144476144477144478144479144480144481144482144483144484144485144486144487144488144489144490144491144492144493144494144495144496144497144498144499144500144501144502144503144504144505144506144507144508144509144510144511144512144513144514144515144516144517144518144519144520144521144522144523144524144525144526144527144528144529144530144531144532144533144534144535144536144537144538144539144540144541144542144543144544144545144546144547144548144549144550144551144552144553144554144555144556144557144558144559144560144561144562144563144564144565144566144567144568144569144570144571144572144573144574144575144576144577144578144579144580144581144582144583144584144585144586144587144588144589144590144591144592144593144594144595144596144597144598144599144600144601144602144603144604144605144606144607144608144609144610144611144612144613144614144615144616144617144618144619144620144621144622144623144624144625144626144627144628144629144630144631144632144633144634144635144636144637144638144639144640144641144642144643144644144645144646144647144648144649144650144651144652144653144654144655144656144657144658144659144660144661144662144663144664144665144666144667144668144669144670144671144672144673144674144675144676144677144678144679144680144681144682144683144684144685144686144687144688144689144690144691144692144693144694144695144696144697144698144699144700144701144702144703144704144705144706144707144708144709144710144711144712144713144714144715144716144717144718144719144720144721144722144723144724144725144726144727144728144729144730144731144732144733144734144735144736144737144738144739144740144741144742144743144744144745144746144747144748144749144750144751144752144753144754144755144756144757144758144759144760144761144762144763144764144765144766144767144768144769144770144771144772144773144774144775144776144777144778144779144780144781144782144783144784144785144786144787144788144789144790144791144792144793144794144795144796144797144798144799144800144801144802144803144804144805144806144807144808144809144810144811144812144813144814144815144816144817144818144819144820144821144822144823144824144825144826144827144828144829144830144831144832144833144834144835144836144837144838144839144840144841144842144843144844144845144846144847144848144849144850144851144852144853144854144855144856144857144858144859144860144861144862144863144864144865144866144867144868144869144870144871144872144873144874144875144876144877144878144879144880144881144882144883144884144885144886144887144888144889144890144891144892144893144894144895144896144897144898144899144900144901144902144903144904144905144906144907144908144909144910144911144912144913144914144915144916144917144918144919144920144921144922144923144924144925144926144927144928144929144930144931144932144933144934144935144936144937144938144939144940144941144942144943144944144945144946144947144948144949144950144951144952144953144954144955144956144957144958144959144960144961144962144963144964144965144966144967144968144969144970144971144972144973144974144975144976144977144978144979144980144981144982144983144984144985144986144987144988144989144990144991144992144993144994144995144996144997144998144999145000145001145002145003145004145005145006145007145008145009145010145011145012145013145014145015145016145017145018145019145020145021145022145023145024145025145026145027145028145029145030145031145032145033145034145035145036145037145038145039145040145041145042145043145044145045145046145047145048145049145050145051145052145053145054145055145056145057145058145059145060145061145062145063145064145065145066145067145068145069145070145071145072145073145074145075145076145077145078145079145080145081145082145083145084145085145086145087145088145089145090145091145092145093145094145095145096145097145098145099145100145101145102145103145104145105145106145107145108145109145110145111145112145113145114145115145116145117145118145119145120145121145122145123145124145125145126145127145128145129145130145131145132145133145134145135145136145137145138145139145140145141145142145143145144145145145146145147145148145149145150145151145152145153145154145155145156145157145158145159145160145161145162145163145164145165145166145167145168145169145170145171145172145173145174145175145176145177145178145179145180145181145182145183145184145185145186145187145188145189145190145191145192145193145194145195145196145197145198145199145200145201145202145203145204145205145206145207145208145209145210145211145212145213145214145215145216145217145218145219145220145221145222145223145224145225145226145227145228145229145230145231145232145233145234145235145236145237145238145239145240145241145242145243145244145245145246145247145248145249145250145251145252145253145254145255145256145257145258145259145260145261145262145263145264145265145266145267145268145269145270145271145272145273145274145275145276145277145278145279145280145281145282145283145284145285145286145287145288145289145290145291145292145293145294145295145296145297145298145299145300145301145302145303145304145305145306145307145308145309145310145311145312145313145314145315145316145317145318145319145320145321145322145323145324145325145326145327145328145329145330145331145332145333145334145335145336145337145338145339145340145341145342145343145344145345145346145347145348145349145350145351145352145353145354145355145356145357145358145359145360145361145362145363145364145365145366145367145368145369145370145371145372145373145374145375145376145377145378145379145380145381145382145383145384145385145386145387145388145389145390145391145392145393145394145395145396145397145398145399145400145401145402145403145404145405145406145407145408145409145410145411145412145413145414145415145416145417145418145419145420145421145422145423145424145425145426145427145428145429145430145431145432145433145434145435145436145437145438145439145440145441145442145443145444145445145446145447145448145449145450145451145452145453145454145455145456145457145458145459145460145461145462145463145464145465145466145467145468145469145470145471145472145473145474145475145476145477145478145479145480145481145482145483145484145485145486145487145488145489145490145491145492145493145494145495145496145497145498145499145500145501145502145503145504145505145506145507145508145509145510145511145512145513145514145515145516145517145518145519145520145521145522145523145524145525145526145527145528145529145530145531145532145533145534145535145536145537145538145539145540145541145542145543145544145545145546145547145548145549145550145551145552145553145554145555145556145557145558145559145560145561145562145563145564145565145566145567145568145569145570145571145572145573145574145575145576145577145578145579145580145581145582145583145584145585145586145587145588145589145590145591145592145593145594145595145596145597145598145599145600145601145602145603145604145605145606145607145608145609145610145611145612145613145614145615145616145617145618145619145620145621145622145623145624145625145626145627145628145629145630145631145632145633145634145635145636145637145638145639145640145641145642145643145644145645145646145647145648145649145650145651145652145653145654145655145656145657145658145659145660145661145662145663145664145665145666145667145668145669145670145671145672145673145674145675145676145677145678145679145680145681145682145683145684145685145686145687145688145689145690145691145692145693145694145695145696145697145698145699145700145701145702145703145704145705145706145707145708145709145710145711145712145713145714145715145716145717145718145719145720145721145722145723145724145725145726145727145728145729145730145731145732145733145734145735145736145737145738145739145740145741145742145743145744145745145746145747145748145749145750145751145752145753145754145755145756145757145758145759145760145761145762145763145764145765145766145767145768145769145770145771145772145773145774145775145776145777145778145779145780145781145782145783145784145785145786145787145788145789145790145791145792145793145794145795145796145797145798145799145800145801145802145803145804145805145806145807145808145809145810145811145812145813145814145815145816145817145818145819145820145821145822145823145824145825145826145827145828145829145830145831145832145833145834145835145836145837145838145839145840145841145842145843145844145845145846145847145848145849145850145851145852145853145854145855145856145857145858145859145860145861145862145863145864145865145866145867145868145869145870145871145872145873145874145875145876145877145878145879145880145881145882145883145884145885145886145887145888145889145890145891145892145893145894145895145896145897145898145899145900145901145902145903145904145905145906145907145908145909145910145911145912145913145914145915145916145917145918145919145920145921145922145923145924145925145926145927145928145929145930145931145932145933145934145935145936145937145938145939145940145941145942145943145944145945145946145947145948145949145950145951145952145953145954145955145956145957145958145959145960145961145962145963145964145965145966145967145968145969145970145971145972145973145974145975145976145977145978145979145980145981145982145983145984145985145986145987145988145989145990145991145992145993145994145995145996145997145998145999146000146001146002146003146004146005146006146007146008146009146010146011146012146013146014146015146016146017146018146019146020146021146022146023146024146025146026146027146028146029146030146031146032146033146034146035146036146037146038146039146040146041146042146043146044146045146046146047146048146049146050146051146052146053146054146055146056146057146058146059146060146061146062146063146064146065146066146067146068146069146070146071146072146073146074146075146076146077146078146079146080146081146082146083146084146085146086146087146088146089146090146091146092146093146094146095146096146097146098146099146100146101146102146103146104146105146106146107146108146109146110146111146112146113146114146115146116146117146118146119146120146121146122146123146124146125146126146127146128146129146130146131146132146133146134146135146136146137146138146139146140146141146142146143146144146145146146146147146148146149146150146151146152146153146154146155146156146157146158146159146160146161146162146163146164146165146166146167146168146169146170146171146172146173146174146175146176146177146178146179146180146181146182146183146184146185146186146187146188146189146190146191146192146193146194146195146196146197146198146199146200146201146202146203146204146205146206146207146208146209146210146211146212146213146214146215146216146217146218146219146220146221146222146223146224146225146226146227146228146229146230146231146232146233146234146235146236146237146238146239146240146241146242146243146244146245146246146247146248146249146250146251146252146253146254146255146256146257146258146259146260146261146262146263146264146265146266146267146268146269146270146271146272146273146274146275146276146277146278146279146280146281146282146283146284146285146286146287146288146289146290146291146292146293146294146295146296146297146298146299146300146301146302146303146304146305146306146307146308146309146310146311146312146313146314146315146316146317146318146319146320146321146322146323146324146325146326146327146328146329146330146331146332146333146334146335146336146337146338146339146340146341146342146343146344146345146346146347146348146349146350146351146352146353146354146355146356146357146358146359146360146361146362146363146364146365146366146367146368146369146370146371146372146373146374146375146376146377146378146379146380146381146382146383146384146385146386146387146388146389146390146391146392146393146394146395146396146397146398146399146400146401146402146403146404146405146406146407146408146409146410146411146412146413146414146415146416146417146418146419146420146421146422146423146424146425146426146427146428146429146430146431146432146433146434146435146436146437146438146439146440146441146442146443146444146445146446146447146448146449146450146451146452146453146454146455146456146457146458146459146460146461146462146463146464146465146466146467146468146469146470146471146472146473146474146475146476146477146478146479146480146481146482146483146484146485146486146487146488146489146490146491146492146493146494146495146496146497146498146499146500146501146502146503146504146505146506146507146508146509146510146511146512146513146514146515146516146517146518146519146520146521146522146523146524146525146526146527146528146529146530146531146532146533146534146535146536146537146538146539146540146541146542146543146544146545146546146547146548146549146550146551146552146553146554146555146556146557146558146559146560146561146562146563146564146565146566146567146568146569146570146571146572146573146574146575146576146577146578146579146580146581146582146583146584146585146586146587146588146589146590146591146592146593146594146595146596146597146598146599146600146601146602146603146604146605146606146607146608146609146610146611146612146613146614146615146616146617146618146619146620146621146622146623146624146625146626146627146628146629146630146631146632146633146634146635146636146637146638146639146640146641146642146643146644146645146646146647146648146649146650146651146652146653146654146655146656146657146658146659146660146661146662146663146664146665146666146667146668146669146670146671146672146673146674146675146676146677146678146679146680146681146682146683146684146685146686146687146688146689146690146691146692146693146694146695146696146697146698146699146700146701146702146703146704146705146706146707146708146709146710146711146712146713146714146715146716146717146718146719146720146721146722146723146724146725146726146727146728146729146730146731146732146733146734146735146736146737146738146739146740146741146742146743146744146745146746146747146748146749146750146751146752146753146754146755146756146757146758146759146760146761146762146763146764146765146766146767146768146769146770146771146772146773146774146775146776146777146778146779146780146781146782146783146784146785146786146787146788146789146790146791146792146793146794146795146796146797146798146799146800146801146802146803146804146805146806146807146808146809146810146811146812146813146814146815146816146817146818146819146820146821146822146823146824146825146826146827146828146829146830146831146832146833146834146835146836146837146838146839146840146841146842146843146844146845146846146847146848146849146850146851146852146853146854146855146856146857146858146859146860146861146862146863146864146865146866146867146868146869146870146871146872146873146874146875146876146877146878146879146880146881146882146883146884146885146886146887146888146889146890146891146892146893146894146895146896146897146898146899146900146901146902146903146904146905146906146907146908146909146910146911146912146913146914146915146916146917146918146919146920146921146922146923146924146925146926146927146928146929146930146931146932146933146934146935146936146937146938146939146940146941146942146943146944146945146946146947146948146949146950146951146952146953146954146955146956146957146958146959146960146961146962146963146964146965146966146967146968146969146970146971146972146973146974146975146976146977146978146979146980146981146982146983146984146985146986146987146988146989146990146991146992146993146994146995146996146997146998146999147000147001147002147003147004147005147006147007147008147009147010147011147012147013147014147015147016147017147018147019147020147021147022147023147024147025147026147027147028147029147030147031147032147033147034147035147036147037147038147039147040147041147042147043147044147045147046147047147048147049147050147051147052147053147054147055147056147057147058147059147060147061147062147063147064147065147066147067147068147069147070147071147072147073147074147075147076147077147078147079147080147081147082147083147084147085147086147087147088147089147090147091147092147093147094147095147096147097147098147099147100147101147102147103147104147105147106147107147108147109147110147111147112147113147114147115147116147117147118147119147120147121147122147123147124147125147126147127147128147129147130147131147132147133147134147135147136147137147138147139147140147141147142147143147144147145147146147147147148147149147150147151147152147153147154147155147156147157147158147159147160147161147162147163147164147165147166147167147168147169147170147171147172147173147174147175147176147177147178147179147180147181147182147183147184147185147186147187147188147189147190147191147192147193147194147195147196147197147198147199147200147201147202147203147204147205147206147207147208147209147210147211147212147213147214147215147216147217147218147219147220147221147222147223147224147225147226147227147228147229147230147231147232147233147234147235147236147237147238147239147240147241147242147243147244147245147246147247147248147249147250147251147252147253147254147255147256147257147258147259147260147261147262147263147264147265147266147267147268147269147270147271147272147273147274147275147276147277147278147279147280147281147282147283147284147285147286147287147288147289147290147291147292147293147294147295147296147297147298147299147300147301147302147303147304147305147306147307147308147309147310147311147312147313147314147315147316147317147318147319147320147321147322147323147324147325147326147327147328147329147330147331147332147333147334147335147336147337147338147339147340147341147342147343147344147345147346147347147348147349147350147351147352147353147354147355147356147357147358147359147360147361147362147363147364147365147366147367147368147369147370147371147372147373147374147375147376147377147378147379147380147381147382147383147384147385147386147387147388147389147390147391147392147393147394147395147396147397147398147399147400147401147402147403147404147405147406147407147408147409147410147411147412147413147414147415147416147417147418147419147420147421147422147423147424147425147426147427147428147429147430147431147432147433147434147435147436147437147438147439147440147441147442147443147444147445147446147447147448147449147450147451147452147453147454147455147456147457147458147459147460147461147462147463147464147465147466147467147468147469147470147471147472147473147474147475147476147477147478147479147480147481147482147483147484147485147486147487147488147489147490147491147492147493147494147495147496147497147498147499147500147501147502147503147504147505147506147507147508147509147510147511147512147513147514147515147516147517147518147519147520147521147522147523147524147525147526147527147528147529147530147531147532147533147534147535147536147537147538147539147540147541147542147543147544147545147546147547147548147549147550147551147552147553147554147555147556147557147558147559147560147561147562147563147564147565147566147567147568147569147570147571147572147573147574147575147576147577147578147579147580147581147582147583147584147585147586147587147588147589147590147591147592147593147594147595147596147597147598147599147600147601147602147603147604147605147606147607147608147609147610147611147612147613147614147615147616147617147618147619147620147621147622147623147624147625147626147627147628147629147630147631147632147633147634147635147636147637147638147639147640147641147642147643147644147645147646147647147648147649147650147651147652147653147654147655147656147657147658147659147660147661147662147663147664147665147666147667147668147669147670147671147672147673147674147675147676147677147678147679147680147681147682147683147684147685147686147687147688147689147690147691147692147693147694147695147696147697147698147699147700147701147702147703147704147705147706147707147708147709147710147711147712147713147714147715147716147717147718147719147720147721147722147723147724147725147726147727147728147729147730147731147732147733147734147735147736147737147738147739147740147741147742147743147744147745147746147747147748147749147750147751147752147753147754147755147756147757147758147759147760147761147762147763147764147765147766147767147768147769147770147771147772147773147774147775147776147777147778147779147780147781147782147783147784147785147786147787147788147789147790147791147792147793147794147795147796147797147798147799147800147801147802147803147804147805147806147807147808147809147810147811147812147813147814147815147816147817147818147819147820147821147822147823147824147825147826147827147828147829147830147831147832147833147834147835147836147837147838147839147840147841147842147843147844147845147846147847147848147849147850147851147852147853147854147855147856147857147858147859147860147861147862147863147864147865147866147867147868147869147870147871147872147873147874147875147876147877147878147879147880147881147882147883147884147885147886147887147888147889147890147891147892147893147894147895147896147897147898147899147900147901147902147903147904147905147906147907147908147909147910147911147912147913147914147915147916147917147918147919147920147921147922147923147924147925147926147927147928147929147930147931147932147933147934147935147936147937147938147939147940147941147942147943147944147945147946147947147948147949147950147951147952147953147954147955147956147957147958147959147960147961147962147963147964147965147966147967147968147969147970147971147972147973147974147975147976147977147978147979147980147981147982147983147984147985147986147987147988147989147990147991147992147993147994147995147996147997147998147999148000148001148002148003148004148005148006148007148008148009148010148011148012148013148014148015148016148017148018148019148020148021148022148023148024148025148026148027148028148029148030148031148032148033148034148035148036148037148038148039148040148041148042148043148044148045148046148047148048148049148050148051148052148053148054148055148056148057148058148059148060148061148062148063148064148065148066148067148068148069148070148071148072148073148074148075148076148077148078148079148080148081148082148083148084148085148086148087148088148089148090148091148092148093148094148095148096148097148098148099148100148101148102148103148104148105148106148107148108148109148110148111148112148113148114148115148116148117148118148119148120148121148122148123148124148125148126148127148128148129148130148131148132148133148134148135148136148137148138148139148140148141148142148143148144148145148146148147148148148149148150148151148152148153148154148155148156148157148158148159148160148161148162148163148164148165148166148167148168148169148170148171148172148173148174148175148176148177148178148179148180148181148182148183148184148185148186148187148188148189148190148191148192148193148194148195148196148197148198148199148200148201148202148203148204148205148206148207148208148209148210148211148212148213148214148215148216148217148218148219148220148221148222148223148224148225148226148227148228148229148230148231148232148233148234148235148236148237148238148239148240148241148242148243148244148245148246148247148248148249148250148251148252148253148254148255148256148257148258148259148260148261148262148263148264148265148266148267148268148269148270148271148272148273148274148275148276148277148278148279148280148281148282148283148284148285148286148287148288148289148290148291148292148293148294148295148296148297148298148299148300148301148302148303148304148305148306148307148308148309148310148311148312148313148314148315148316148317148318148319148320148321148322148323148324148325148326148327148328148329148330148331148332148333148334148335148336148337148338148339148340148341148342148343148344148345148346148347148348148349148350148351148352148353148354148355148356148357148358148359148360148361148362148363148364148365148366148367148368148369148370148371148372148373148374148375148376148377148378148379148380148381148382148383148384148385148386148387148388148389148390148391148392148393148394148395148396148397148398148399148400148401148402148403148404148405148406148407148408148409148410148411148412148413148414148415148416148417148418148419148420148421148422148423148424148425148426148427148428148429148430148431148432148433148434148435148436148437148438148439148440148441148442148443148444148445148446148447148448148449148450148451148452148453148454148455148456148457148458148459148460148461148462148463148464148465148466148467148468148469148470148471148472148473148474148475148476148477148478148479148480148481148482148483148484148485148486148487148488148489148490148491148492148493148494148495148496148497148498148499148500148501148502148503148504148505148506148507148508148509148510148511148512148513148514148515148516148517148518148519148520148521148522148523148524148525148526148527148528148529148530148531148532148533148534148535148536148537148538148539148540148541148542148543148544148545148546148547148548148549148550148551148552148553148554148555148556148557148558148559148560148561148562148563148564148565148566148567148568148569148570148571148572148573148574148575148576148577148578148579148580148581148582148583148584148585148586148587148588148589148590148591148592148593148594148595148596148597148598148599148600148601148602148603148604148605148606148607148608148609148610148611148612148613148614148615148616148617148618148619148620148621148622148623148624148625148626148627148628148629148630148631148632148633148634148635148636148637148638148639148640148641148642148643148644148645148646148647148648148649148650148651148652148653148654148655148656148657148658148659148660148661148662148663148664148665148666148667148668148669148670148671148672148673148674148675148676148677148678148679148680148681148682148683148684148685148686148687148688148689148690148691148692148693148694148695148696148697148698148699148700148701148702148703148704148705148706148707148708148709148710148711148712148713148714148715148716148717148718148719148720148721148722148723148724148725148726148727148728148729148730148731148732148733148734148735148736148737148738148739148740148741148742148743148744148745148746148747148748148749148750148751148752148753148754148755148756148757148758148759148760148761148762148763148764148765148766148767148768148769148770148771148772148773148774148775148776148777148778148779148780148781148782148783148784148785148786148787148788148789148790148791148792148793148794148795148796148797148798148799148800148801148802148803148804148805148806148807148808148809148810148811148812148813148814148815148816148817148818148819148820148821148822148823148824148825148826148827148828148829148830148831148832148833148834148835148836148837148838148839148840148841148842148843148844148845148846148847148848148849148850148851148852148853148854148855148856148857148858148859148860148861148862148863148864148865148866148867148868148869148870148871148872148873148874148875148876148877148878148879148880148881148882148883148884148885148886148887148888148889148890148891148892148893148894148895148896148897148898148899148900148901148902148903148904148905148906148907148908148909148910148911148912148913148914148915148916148917148918148919148920148921148922148923148924148925148926148927148928148929148930148931148932148933148934148935148936148937148938148939148940148941148942148943148944148945148946148947148948148949148950148951148952148953148954148955148956148957148958148959148960148961148962148963148964148965148966148967148968148969148970148971148972148973148974148975148976148977148978148979148980148981148982148983148984148985148986148987148988148989148990148991148992148993148994148995148996148997148998148999149000149001149002149003149004149005149006149007149008149009149010149011149012149013149014149015149016149017149018149019149020149021149022149023149024149025149026149027149028149029149030149031149032149033149034149035149036149037149038149039149040149041149042149043149044149045149046149047149048149049149050149051149052149053149054149055149056149057149058149059149060149061149062149063149064149065149066149067149068149069149070149071149072149073149074149075149076149077149078149079149080149081149082149083149084149085149086149087149088149089149090149091149092149093149094149095149096149097149098149099149100149101149102149103149104149105149106149107149108149109149110149111149112149113149114149115149116149117149118149119149120149121149122149123149124149125149126149127149128149129149130149131149132149133149134149135149136149137149138149139149140149141149142149143149144149145149146149147149148149149149150149151149152149153149154149155149156149157149158149159149160149161149162149163149164149165149166149167149168149169149170149171149172149173149174149175149176149177149178149179149180149181149182149183149184149185149186149187149188149189149190149191149192149193149194149195149196149197149198149199149200149201149202149203149204149205149206149207149208149209149210149211149212149213149214149215149216149217149218149219149220149221149222149223149224149225149226149227149228149229149230149231149232149233149234149235149236149237149238149239149240149241149242149243149244149245149246149247149248149249149250149251149252149253149254149255149256149257149258149259149260149261149262149263149264149265149266149267149268149269149270149271149272149273149274149275149276149277149278149279149280149281149282149283149284149285149286149287149288149289149290149291149292149293149294149295149296149297149298149299149300149301149302149303149304149305149306149307149308149309149310149311149312149313149314149315149316149317149318149319149320149321149322149323149324149325149326149327149328149329149330149331149332149333149334149335149336149337149338149339149340149341149342149343149344149345149346149347149348149349149350149351149352149353149354149355149356149357149358149359149360149361149362149363149364149365149366149367149368149369149370149371149372149373149374149375149376149377149378149379149380149381149382149383149384149385149386149387149388149389149390149391149392149393149394149395149396149397149398149399149400149401149402149403149404149405149406149407149408149409149410149411149412149413149414149415149416149417149418149419149420149421149422149423149424149425149426149427149428149429149430149431149432149433149434149435149436149437149438149439149440149441149442149443149444149445149446149447149448149449149450149451149452149453149454149455149456149457149458149459149460149461149462149463149464149465149466149467149468149469149470149471149472149473149474149475149476149477149478149479149480149481149482149483149484149485149486149487149488149489149490149491149492149493149494149495149496149497149498149499149500149501149502149503149504149505149506149507149508149509149510149511149512149513149514149515149516149517149518149519149520149521149522149523149524149525149526149527149528149529149530149531149532149533149534149535149536149537149538149539149540149541149542149543149544149545149546149547149548149549149550149551149552149553149554149555149556149557149558149559149560149561149562149563149564149565149566149567149568149569149570149571149572149573149574149575149576149577149578149579149580149581149582149583149584149585149586149587149588149589149590149591149592149593149594149595149596149597149598149599149600149601149602149603149604149605149606149607149608149609149610149611149612149613149614149615149616149617149618149619149620149621149622149623149624149625149626149627149628149629149630149631149632149633149634149635149636149637149638149639149640149641149642149643149644149645149646149647149648149649149650149651149652149653149654149655149656149657149658149659149660149661149662149663149664149665149666149667149668149669149670149671149672149673149674149675149676149677149678149679149680149681149682149683149684149685149686149687149688149689149690149691149692149693149694149695149696149697149698149699149700149701149702149703149704149705149706149707149708149709149710149711149712149713149714149715149716149717149718149719149720149721149722149723149724149725149726149727149728149729149730149731149732149733149734149735149736149737149738149739149740149741149742149743149744149745149746149747149748149749149750149751149752149753149754149755149756149757149758149759149760149761149762149763149764149765149766149767149768149769149770149771149772149773149774149775149776149777149778149779149780149781149782149783149784149785149786149787149788149789149790149791149792149793149794149795149796149797149798149799149800149801149802149803149804149805149806149807149808149809149810149811149812149813149814149815149816149817149818149819149820149821149822149823149824149825149826149827149828149829149830149831149832149833149834149835149836149837149838149839149840149841149842149843149844149845149846149847149848149849149850149851149852149853149854149855149856149857149858149859149860149861149862149863149864149865149866149867149868149869149870149871149872149873149874149875149876149877149878149879149880149881149882149883149884149885149886149887149888149889149890149891149892149893149894149895149896149897149898149899149900149901149902149903149904149905149906149907149908149909149910149911149912149913149914149915149916149917149918149919149920149921149922149923149924149925149926149927149928149929149930149931149932149933149934149935149936149937149938149939149940149941149942149943149944149945149946149947149948149949149950149951149952149953149954149955149956149957149958149959149960149961149962149963149964149965149966149967149968149969149970149971149972149973149974149975149976149977149978149979149980149981149982149983149984149985149986149987149988149989149990149991149992149993149994149995149996149997149998149999150000150001150002150003150004150005150006150007150008150009150010150011150012150013150014150015150016150017150018150019150020150021150022150023150024150025150026150027150028150029150030150031150032150033150034150035150036150037150038150039150040150041150042150043150044150045150046150047150048150049150050150051150052150053150054150055150056150057150058150059150060150061150062150063150064150065150066150067150068150069150070150071150072150073150074150075150076150077150078150079150080150081150082150083150084150085150086150087150088150089150090150091150092150093150094150095150096150097150098150099150100150101150102150103150104150105150106150107150108150109150110150111150112150113150114150115150116150117150118150119150120150121150122150123150124150125150126150127150128150129150130150131150132150133150134150135150136150137150138150139150140150141150142150143150144150145150146150147150148150149150150150151150152150153150154150155150156150157150158150159150160150161150162150163150164150165150166150167150168150169150170150171150172150173150174150175150176150177150178150179150180150181150182150183150184150185150186150187150188150189150190150191150192150193150194150195150196150197150198150199150200150201150202150203150204150205150206150207150208150209150210150211150212150213150214150215150216150217150218150219150220150221150222150223150224150225150226150227150228150229150230150231150232150233150234150235150236150237150238150239150240150241150242150243150244150245150246150247150248150249150250150251150252150253150254150255150256150257150258150259150260150261150262150263150264150265150266150267150268150269150270150271150272150273150274150275150276150277150278150279150280150281150282150283150284150285150286150287150288150289150290150291150292150293150294150295150296150297150298150299150300150301150302150303150304150305150306150307150308150309150310150311150312150313150314150315150316150317150318150319150320150321150322150323150324150325150326150327150328150329150330150331150332150333150334150335150336150337150338150339150340150341150342150343150344150345150346150347150348150349150350150351150352150353150354150355150356150357150358150359150360150361150362150363150364150365150366150367150368150369150370150371150372150373150374150375150376150377150378150379150380150381150382150383150384150385150386150387150388150389150390150391150392150393150394150395150396150397150398150399150400150401150402150403150404150405150406150407150408150409150410150411150412150413150414150415150416150417150418150419150420150421150422150423150424150425150426150427150428150429150430150431150432150433150434150435150436150437150438150439150440150441150442150443150444150445150446150447150448150449150450150451150452150453150454150455150456150457150458150459150460150461150462150463150464150465150466150467150468150469150470150471150472150473150474150475150476150477150478150479150480150481150482150483150484150485150486150487150488150489150490150491150492150493150494150495150496150497150498150499150500150501150502150503150504150505150506150507150508150509150510150511150512150513150514150515150516150517150518150519150520150521150522150523150524150525150526150527150528150529150530150531150532150533150534150535150536150537150538150539150540150541150542150543150544150545150546150547150548150549150550150551150552150553150554150555150556150557150558150559150560150561150562150563150564150565150566150567150568150569150570150571150572150573150574150575150576150577150578150579150580150581150582150583150584150585150586150587150588150589150590150591150592150593150594150595150596150597150598150599150600150601150602150603150604150605150606150607150608150609150610150611150612150613150614150615150616150617150618150619150620150621150622150623150624150625150626150627150628150629150630150631150632150633150634150635150636150637150638150639150640150641150642150643150644150645150646150647150648150649150650150651150652150653150654150655150656150657150658150659150660150661150662150663150664150665150666150667150668150669150670150671150672150673150674150675150676150677150678150679150680150681150682150683150684150685150686150687150688150689150690150691150692150693150694150695150696150697150698150699150700150701150702150703150704150705150706150707150708150709150710150711150712150713150714150715150716150717150718150719150720150721150722150723150724150725150726150727150728150729150730150731150732150733150734150735150736150737150738150739150740150741150742150743150744150745150746150747150748150749150750150751150752150753150754150755150756150757150758150759150760150761150762150763150764150765150766150767150768150769150770150771150772150773150774150775150776150777150778150779150780150781150782150783150784150785150786150787150788150789150790150791150792150793150794150795150796150797150798150799150800150801150802150803150804150805150806150807150808150809150810150811150812150813150814150815150816150817150818150819150820150821150822150823150824150825150826150827150828150829150830150831150832150833150834150835150836150837150838150839150840150841150842150843150844150845150846150847150848150849150850150851150852150853150854150855150856150857150858150859150860150861150862150863150864150865150866150867150868150869150870150871150872150873150874150875150876150877150878150879150880150881150882150883150884150885150886150887150888150889150890150891150892150893150894150895150896150897150898150899150900150901150902150903150904150905150906150907150908150909150910150911150912150913150914150915150916150917150918150919150920150921150922150923150924150925150926150927150928150929150930150931150932150933150934150935150936150937150938150939150940150941150942150943150944150945150946150947150948150949150950150951150952150953150954150955150956150957150958150959150960150961150962150963150964150965150966150967150968150969150970150971150972150973150974150975150976150977150978150979150980150981150982150983150984150985150986150987150988150989150990150991150992150993150994150995150996150997150998150999151000151001151002151003151004151005151006151007151008151009151010151011151012151013151014151015151016151017151018151019151020151021151022151023151024151025151026151027151028151029151030151031151032151033151034151035151036151037151038151039151040151041151042151043151044151045151046151047151048151049151050151051151052151053151054151055151056151057151058151059151060151061151062151063151064151065151066151067151068151069151070151071151072151073151074151075151076151077151078151079151080151081151082151083151084151085151086151087151088151089151090151091151092151093151094151095151096151097151098151099151100151101151102151103151104151105151106151107151108151109151110151111151112151113151114151115151116151117151118151119151120151121151122151123151124151125151126151127151128151129151130151131151132151133151134151135151136151137151138151139151140151141151142151143151144151145151146151147151148151149151150151151151152151153151154151155151156151157151158151159151160151161151162151163151164151165151166151167151168151169151170151171151172151173151174151175151176151177151178151179151180151181151182151183151184151185151186151187151188151189151190151191151192151193151194151195151196151197151198151199151200151201151202151203151204151205151206151207151208151209151210151211151212151213151214151215151216151217151218151219151220151221151222151223151224151225151226151227151228151229151230151231151232151233151234151235151236151237151238151239151240151241151242151243151244151245151246151247151248151249151250151251151252151253151254151255151256151257151258151259151260151261151262151263151264151265151266151267151268151269151270151271151272151273151274151275151276151277151278151279151280151281151282151283151284151285151286151287151288151289151290151291151292151293151294151295151296151297151298151299151300151301151302151303151304151305151306151307151308151309151310151311151312151313151314151315151316151317151318151319151320151321151322151323151324151325151326151327151328151329151330151331151332151333151334151335151336151337151338151339151340151341151342151343151344151345151346151347151348151349151350151351151352151353151354151355151356151357151358151359151360151361151362151363151364151365151366151367151368151369151370151371151372151373151374151375151376151377151378151379151380151381151382151383151384151385151386151387151388151389151390151391151392151393151394151395151396151397151398151399151400151401151402151403151404151405151406151407151408151409151410151411151412151413151414151415151416151417151418151419151420151421151422151423151424151425151426151427151428151429151430151431151432151433151434151435151436151437151438151439151440151441151442151443151444151445151446151447151448151449151450151451151452151453151454151455151456151457151458151459151460151461151462151463151464151465151466151467151468151469151470151471151472151473151474151475151476151477151478151479151480151481151482151483151484151485151486151487151488151489151490151491151492151493151494151495151496151497151498151499151500151501151502151503151504151505151506151507151508151509151510151511151512151513151514151515151516151517151518151519151520151521151522151523151524151525151526151527151528151529151530151531151532151533151534151535151536151537151538151539151540151541151542151543151544151545151546151547151548151549151550151551151552151553151554151555151556151557151558151559151560151561151562151563151564151565151566151567151568151569151570151571151572151573151574151575151576151577151578151579151580151581151582151583151584151585151586151587151588151589151590151591151592151593151594151595151596151597151598151599151600151601151602151603151604151605151606151607151608151609151610151611151612151613151614151615151616151617151618151619151620151621151622151623151624151625151626151627151628151629151630151631151632151633151634151635151636151637151638151639151640151641151642151643151644151645151646151647151648151649151650151651151652151653151654151655151656151657151658151659151660151661151662151663151664151665151666151667151668151669151670151671151672151673151674151675151676151677151678151679151680151681151682151683151684151685151686151687151688151689151690151691151692151693151694151695151696151697151698151699151700151701151702151703151704151705151706151707151708151709151710151711151712151713151714151715151716151717151718151719151720151721151722151723151724151725151726151727151728151729151730151731151732151733151734151735151736151737151738151739151740151741151742151743151744151745151746151747151748151749151750151751151752151753151754151755151756151757151758151759151760151761151762151763151764151765151766151767151768151769151770151771151772151773151774151775151776151777151778151779151780151781151782151783151784151785151786151787151788151789151790151791151792151793151794151795151796151797151798151799151800151801151802151803151804151805151806151807151808151809151810151811151812151813151814151815151816151817151818151819151820151821151822151823151824151825151826151827151828151829151830151831151832151833151834151835151836151837151838151839151840151841151842151843151844151845151846151847151848151849151850151851151852151853151854151855151856151857151858151859151860151861151862151863151864151865151866151867151868151869151870151871151872151873151874151875151876151877151878151879151880151881151882151883151884151885151886151887151888151889151890151891151892151893151894151895151896151897151898151899151900151901151902151903151904151905151906151907151908151909151910151911151912151913151914151915151916151917151918151919151920151921151922151923151924151925151926151927151928151929151930151931151932151933151934151935151936151937151938151939151940151941151942151943151944151945151946151947151948151949151950151951151952151953151954151955151956151957151958151959151960151961151962151963151964151965151966151967151968151969151970151971151972151973151974151975151976151977151978151979151980151981151982151983151984151985151986151987151988151989151990151991151992151993151994151995151996151997151998151999152000152001152002152003152004152005152006152007152008152009152010152011152012152013152014152015152016152017152018152019152020152021152022152023152024152025152026152027152028152029152030152031152032152033152034152035152036152037152038152039152040152041152042152043152044152045152046152047152048152049152050152051152052152053152054152055152056152057152058152059152060152061152062152063152064152065152066152067152068152069152070152071152072152073152074152075152076152077152078152079152080152081152082152083152084152085152086152087152088152089152090152091152092152093152094152095152096152097152098152099152100152101152102152103152104152105152106152107152108152109152110152111152112152113152114152115152116152117152118152119152120152121152122152123152124152125152126152127152128152129152130152131152132152133152134152135152136152137152138152139152140152141152142152143152144152145152146152147152148152149152150152151152152152153152154152155152156152157152158152159152160152161152162152163152164152165152166152167152168152169152170152171152172152173152174152175152176152177152178152179152180152181152182152183152184152185152186152187152188152189152190152191152192152193152194152195152196152197152198152199152200152201152202152203152204152205152206152207152208152209152210152211152212152213152214152215152216152217152218152219152220152221152222152223152224152225152226152227152228152229152230152231152232152233152234152235152236152237152238152239152240152241152242152243152244152245152246152247152248152249152250152251152252152253152254152255152256152257152258152259152260152261152262152263152264152265152266152267152268152269152270152271152272152273152274152275152276152277152278152279152280152281152282152283152284152285152286152287152288152289152290152291152292152293152294152295152296152297152298152299152300152301152302152303152304152305152306152307152308152309152310152311152312152313152314152315152316152317152318152319152320152321152322152323152324152325152326152327152328152329152330152331152332152333152334152335152336152337152338152339152340152341152342152343152344152345152346152347152348152349152350152351152352152353152354152355152356152357152358152359152360152361152362152363152364152365152366152367152368152369152370152371152372152373152374152375152376152377152378152379152380152381152382152383152384152385152386152387152388152389152390152391152392152393152394152395152396152397152398152399152400152401152402152403152404152405152406152407152408152409152410152411152412152413152414152415152416152417152418152419152420152421152422152423152424152425152426152427152428152429152430152431152432152433152434152435152436152437152438152439152440152441152442152443152444152445152446152447152448152449152450152451152452152453152454152455152456152457152458152459152460152461152462152463152464152465152466152467152468152469152470152471152472152473152474152475152476152477152478152479152480152481152482152483152484152485152486152487152488152489152490152491152492152493152494152495152496152497152498152499152500152501152502152503152504152505152506152507152508152509152510152511152512152513152514152515152516152517152518152519152520152521152522152523152524152525152526152527152528152529152530152531152532152533152534152535152536152537152538152539152540152541152542152543152544152545152546152547152548152549152550152551152552152553152554152555152556152557152558152559152560152561152562152563152564152565152566152567152568152569152570152571152572152573152574152575152576152577152578152579152580152581152582152583152584152585152586152587152588152589152590152591152592152593152594152595152596152597152598152599152600152601152602152603152604152605152606152607152608152609152610152611152612152613152614152615152616152617152618152619152620152621152622152623152624152625152626152627152628152629152630152631152632152633152634152635152636152637152638152639152640152641152642152643152644152645152646152647152648152649152650152651152652152653152654152655152656152657152658152659152660152661152662152663152664152665152666152667152668152669152670152671152672152673152674152675152676152677152678152679152680152681152682152683152684152685152686152687152688152689152690152691152692152693152694152695152696152697152698152699152700152701152702152703152704152705152706152707152708152709152710152711152712152713152714152715152716152717152718152719152720152721152722152723152724152725152726152727152728152729152730152731152732152733152734152735152736152737152738152739152740152741152742152743152744152745152746152747152748152749152750152751152752152753152754152755152756152757152758152759152760152761152762152763152764152765152766152767152768152769152770152771152772152773152774152775152776152777152778152779152780152781152782152783152784152785152786152787152788152789152790152791152792152793152794152795152796152797152798152799152800152801152802152803152804152805152806152807152808152809152810152811152812152813152814152815152816152817152818152819152820152821152822152823152824152825152826152827152828152829152830152831152832152833152834152835152836152837152838152839152840152841152842152843152844152845152846152847152848152849152850152851152852152853152854152855152856152857152858152859152860152861152862152863152864152865152866152867152868152869152870152871152872152873152874152875152876152877152878152879152880152881152882152883152884152885152886152887152888152889152890152891152892152893152894152895152896152897152898152899152900152901152902152903152904152905152906152907152908152909152910152911152912152913152914152915152916152917152918152919152920152921152922152923152924152925152926152927152928152929152930152931152932152933152934152935152936152937152938152939152940152941152942152943152944152945152946152947152948152949152950152951152952152953152954152955152956152957152958152959152960152961152962152963152964152965152966152967152968152969152970152971152972152973152974152975152976152977152978152979152980152981152982152983152984152985152986152987152988152989152990152991152992152993152994152995152996152997152998152999153000153001153002153003153004153005153006153007153008153009153010153011153012153013153014153015153016153017153018153019153020153021153022153023153024153025153026153027153028153029153030153031153032153033153034153035153036153037153038153039153040153041153042153043153044153045153046153047153048153049153050153051153052153053153054153055153056153057153058153059153060153061153062153063153064153065153066153067153068153069153070153071153072153073153074153075153076153077153078153079153080153081153082153083153084153085153086153087153088153089153090153091153092153093153094153095153096153097153098153099153100153101153102153103153104153105153106153107153108153109153110153111153112153113153114153115153116153117153118153119153120153121153122153123153124153125153126153127153128153129153130153131153132153133153134153135153136153137153138153139153140153141153142153143153144153145153146153147153148153149153150153151153152153153153154153155153156153157153158153159153160153161153162153163153164153165153166153167153168153169153170153171153172153173153174153175153176153177153178153179153180153181153182153183153184153185153186153187153188153189153190153191153192153193153194153195153196153197153198153199153200153201153202153203153204153205153206153207153208153209153210153211153212153213153214153215153216153217153218153219153220153221153222153223153224153225153226153227153228153229153230153231153232153233153234153235153236153237153238153239153240153241153242153243153244153245153246153247153248153249153250153251153252153253153254153255153256153257153258153259153260153261153262153263153264153265153266153267153268153269153270153271153272153273153274153275153276153277153278153279153280153281153282153283153284153285153286153287153288153289153290153291153292153293153294153295153296153297153298153299153300153301153302153303153304153305153306153307153308153309153310153311153312153313153314153315153316153317153318153319153320153321153322153323153324153325153326153327153328153329153330153331153332153333153334153335153336153337153338153339153340153341153342153343153344153345153346153347153348153349153350153351153352153353153354153355153356153357153358153359153360153361153362153363153364153365153366153367153368153369153370153371153372153373153374153375153376153377153378153379153380153381153382153383153384153385153386153387153388153389153390153391153392153393153394153395153396153397153398153399153400153401153402153403153404153405153406153407153408153409153410153411153412153413153414153415153416153417153418153419153420153421153422153423153424153425153426153427153428153429153430153431153432153433153434153435153436153437153438153439153440153441153442153443153444153445153446153447153448153449153450153451153452153453153454153455153456153457153458153459153460153461153462153463153464153465153466153467153468153469153470153471153472153473153474153475153476153477153478153479153480153481153482153483153484153485153486153487153488153489153490153491153492153493153494153495153496153497153498153499153500153501153502153503153504153505153506153507153508153509153510153511153512153513153514153515153516153517153518153519153520153521153522153523153524153525153526153527153528153529153530153531153532153533153534153535153536153537153538153539153540153541153542153543153544153545153546153547153548153549153550153551153552153553153554153555153556153557153558153559153560153561153562153563153564153565153566153567153568153569153570153571153572153573153574153575153576153577153578153579153580153581153582153583153584153585153586153587153588153589153590153591153592153593153594153595153596153597153598153599153600153601153602153603153604153605153606153607153608153609153610153611153612153613153614153615153616153617153618153619153620153621153622153623153624153625153626153627153628153629153630153631153632153633153634153635153636153637153638153639153640153641153642153643153644153645153646153647153648153649153650153651153652153653153654153655153656153657153658153659153660153661153662153663153664153665153666153667153668153669153670153671153672153673153674153675153676153677153678153679153680153681153682153683153684153685153686153687153688153689153690153691153692153693153694153695153696153697153698153699153700153701153702153703153704153705153706153707153708153709153710153711153712153713153714153715153716153717153718153719153720153721153722153723153724153725153726153727153728153729153730153731153732153733153734153735153736153737153738153739153740153741153742153743153744153745153746153747153748153749153750153751153752153753153754153755153756153757153758153759153760153761153762153763153764153765153766153767153768153769153770153771153772153773153774153775153776153777153778153779153780153781153782153783153784153785153786153787153788153789153790153791153792153793153794153795153796153797153798153799153800153801153802153803153804153805153806153807153808153809153810153811153812153813153814153815153816153817153818153819153820153821153822153823153824153825153826153827153828153829153830153831153832153833153834153835153836153837153838153839153840153841153842153843153844153845153846153847153848153849153850153851153852153853153854153855153856153857153858153859153860153861153862153863153864153865153866153867153868153869153870153871153872153873153874153875153876153877153878153879153880153881153882153883153884153885153886153887153888153889153890153891153892153893153894153895153896153897153898153899153900153901153902153903153904153905153906153907153908153909153910153911153912153913153914153915153916153917153918153919153920153921153922153923153924153925153926153927153928153929153930153931153932153933153934153935153936153937153938153939153940153941153942153943153944153945153946153947153948153949153950153951153952153953153954153955153956153957153958153959153960153961153962153963153964153965153966153967153968153969153970153971153972153973153974153975153976153977153978153979153980153981153982153983153984153985153986153987153988153989153990153991153992153993153994153995153996153997153998153999154000154001154002154003154004154005154006154007154008154009154010154011154012154013154014154015154016154017154018154019154020154021154022154023154024154025154026154027154028154029154030154031154032154033154034154035154036154037154038154039154040154041154042154043154044154045154046154047154048154049154050154051154052154053154054154055154056154057154058154059154060154061154062154063154064154065154066154067154068154069154070154071154072154073154074154075154076154077154078154079154080154081154082154083154084154085154086154087154088154089154090154091154092154093154094154095154096154097154098154099154100154101154102154103154104154105154106154107154108154109154110154111154112154113154114154115154116154117154118154119154120154121154122154123154124154125154126154127154128154129154130154131154132154133154134154135154136154137154138154139154140154141154142154143154144154145154146154147154148154149154150154151154152154153154154154155154156154157154158154159154160154161154162154163154164154165154166154167154168154169154170154171154172154173154174154175154176154177154178154179154180154181154182154183154184154185154186154187154188154189154190154191154192154193154194154195154196154197154198154199154200154201154202154203154204154205154206154207154208154209154210154211154212154213154214154215154216154217154218154219154220154221154222154223154224154225154226154227154228154229154230154231154232154233154234154235154236154237154238154239154240154241154242154243154244154245154246154247154248154249154250154251154252154253154254154255154256154257154258154259154260154261154262154263154264154265154266154267154268154269154270154271154272154273154274154275154276154277154278154279154280154281154282154283154284154285154286154287154288154289154290154291154292154293154294154295154296154297154298154299154300154301154302154303154304154305154306154307154308154309154310154311154312154313154314154315154316154317154318154319154320154321154322154323154324154325154326154327154328154329154330154331154332154333154334154335154336154337154338154339154340154341154342154343154344154345154346154347154348154349154350154351154352154353154354154355154356154357154358154359154360154361154362154363154364154365154366154367154368154369154370154371154372154373154374154375154376154377154378154379154380154381154382154383154384154385154386154387154388154389154390154391154392154393154394154395154396154397154398154399154400154401154402154403154404154405154406154407154408154409154410154411154412154413154414154415154416154417154418154419154420154421154422154423154424154425154426154427154428154429154430154431154432154433154434154435154436154437154438154439154440154441154442154443154444154445154446154447154448154449154450154451154452154453154454154455154456154457154458154459154460154461154462154463154464154465154466154467154468154469154470154471154472154473154474154475154476154477154478154479154480154481154482154483154484154485154486154487154488154489154490154491154492154493154494154495154496154497154498154499154500154501154502154503154504154505154506154507154508154509154510154511154512154513154514154515154516154517154518154519154520154521154522154523154524154525154526154527154528154529154530154531154532154533154534154535154536154537154538154539154540154541154542154543154544154545154546154547154548154549154550154551154552154553154554154555154556154557154558154559154560154561154562154563154564154565154566154567154568154569154570154571154572154573154574154575154576154577154578154579154580154581154582154583154584154585154586154587154588154589154590154591154592154593154594154595154596154597154598154599154600154601154602154603154604154605154606154607154608154609154610154611154612154613154614154615154616154617154618154619154620154621154622154623154624154625154626154627154628154629154630154631154632154633154634154635154636154637154638154639154640154641154642154643154644154645154646154647154648154649154650154651154652154653154654154655154656154657154658154659154660154661154662154663154664154665154666154667154668154669154670154671154672154673154674154675154676154677154678154679154680154681154682154683154684154685154686154687154688154689154690154691154692154693154694154695154696154697154698154699154700154701154702154703154704154705154706154707154708154709154710154711154712154713154714154715154716154717154718154719154720154721154722154723154724154725154726154727154728154729154730154731154732154733154734154735154736154737154738154739154740154741154742154743154744154745154746154747154748154749154750154751154752154753154754154755154756154757154758154759154760154761154762154763154764154765154766154767154768154769154770154771154772154773154774154775154776154777154778154779154780154781154782154783154784154785154786154787154788154789154790154791154792154793154794154795154796154797154798154799154800154801154802154803154804154805154806154807154808154809154810154811154812154813154814154815154816154817154818154819154820154821154822154823154824154825154826154827154828154829154830154831154832154833154834154835154836154837154838154839154840154841154842154843154844154845154846154847154848154849154850154851154852154853154854154855154856154857154858154859154860154861154862154863154864154865154866154867154868154869154870154871154872154873154874154875154876154877154878154879154880154881154882154883154884154885154886154887154888154889154890154891154892154893154894154895154896154897154898154899154900154901154902154903154904154905154906154907154908154909154910154911154912154913154914154915154916154917154918154919154920154921154922154923154924154925154926154927154928154929154930154931154932154933154934154935154936154937154938154939154940154941154942154943154944154945154946154947154948154949154950154951154952154953154954154955154956154957154958154959154960154961154962154963154964154965154966154967154968154969154970154971154972154973154974154975154976154977154978154979154980154981154982154983154984154985154986154987154988154989154990154991154992154993154994154995154996154997154998154999155000155001155002155003155004155005155006155007155008155009155010155011155012155013155014155015155016155017155018155019155020155021155022155023155024155025155026155027155028155029155030155031155032155033155034155035155036155037155038155039155040155041155042155043155044155045155046155047155048155049155050155051155052155053155054155055155056155057155058155059155060155061155062155063155064155065155066155067155068155069155070155071155072155073155074155075155076155077155078155079155080155081155082155083155084155085155086155087155088155089155090155091155092155093155094155095155096155097155098155099155100155101155102155103155104155105155106155107155108155109155110155111155112155113155114155115155116155117155118155119155120155121155122155123155124155125155126155127155128155129155130155131155132155133155134155135155136155137155138155139155140155141155142155143155144155145155146155147155148155149155150155151155152155153155154155155155156155157155158155159155160155161155162155163155164155165155166155167155168155169155170155171155172155173155174155175155176155177155178155179155180155181155182155183155184155185155186155187155188155189155190155191155192155193155194155195155196155197155198155199155200155201155202155203155204155205155206155207155208155209155210155211155212155213155214155215155216155217155218155219155220155221155222155223155224155225155226155227155228155229155230155231155232155233155234155235155236155237155238155239155240155241155242155243155244155245155246155247155248155249155250155251155252155253155254155255155256155257155258155259155260155261155262155263155264155265155266155267155268155269155270155271155272155273155274155275155276155277155278155279155280155281155282155283155284155285155286155287155288155289155290155291155292155293155294155295155296155297155298155299155300155301155302155303155304155305155306155307155308155309155310155311155312155313155314155315155316155317155318155319155320155321155322155323155324155325155326155327155328155329155330155331155332155333155334155335155336155337155338155339155340155341155342155343155344155345155346155347155348155349155350155351155352155353155354155355155356155357155358155359155360155361155362155363155364155365155366155367155368155369155370155371155372155373155374155375155376155377155378155379155380155381155382155383155384155385155386155387155388155389155390155391155392155393155394155395155396155397155398155399155400155401155402155403155404155405155406155407155408155409155410155411155412155413155414155415155416155417155418155419155420155421155422155423155424155425155426155427155428155429155430155431155432155433155434155435155436155437155438155439155440155441155442155443155444155445155446155447155448155449155450155451155452155453155454155455155456155457155458155459155460155461155462155463155464155465155466155467155468155469155470155471155472155473155474155475155476155477155478155479155480155481155482155483155484155485155486155487155488155489155490155491155492155493155494155495155496155497155498155499155500155501155502155503155504155505155506155507155508155509155510155511155512155513155514155515155516155517155518155519155520155521155522155523155524155525155526155527155528155529155530155531155532155533155534155535155536155537155538155539155540155541155542155543155544155545155546155547155548155549155550155551155552155553155554155555155556155557155558155559155560155561155562155563155564155565155566155567155568155569155570155571155572155573155574155575155576155577155578155579155580155581155582155583155584155585155586155587155588155589155590155591155592155593155594155595155596155597155598155599155600155601155602155603155604155605155606155607155608155609155610155611155612155613155614155615155616155617155618155619155620155621155622155623155624155625155626155627155628155629155630155631155632155633155634155635155636155637155638155639155640155641155642155643155644155645155646155647155648155649155650155651155652155653155654155655155656155657155658155659155660155661155662155663155664155665155666155667155668155669155670155671155672155673155674155675155676155677155678155679155680155681155682155683155684155685155686155687155688155689155690155691155692155693155694155695155696155697155698155699155700155701155702155703155704155705155706155707155708155709155710155711155712155713155714155715155716155717155718155719155720155721155722155723155724155725155726155727155728155729155730155731155732155733155734155735155736155737155738155739155740155741155742155743155744155745155746155747155748155749155750155751155752155753155754155755155756155757155758155759155760155761155762155763155764155765155766155767155768155769155770155771155772155773155774155775155776155777155778155779155780155781155782155783155784155785155786155787155788155789155790155791155792155793155794155795155796155797155798155799155800155801155802155803155804155805155806155807155808155809155810155811155812155813155814155815155816155817155818155819155820155821155822155823155824155825155826155827155828155829155830155831155832155833155834155835155836155837155838155839155840155841155842155843155844155845155846155847155848155849155850155851155852155853155854155855155856155857155858155859155860155861155862155863155864155865155866155867155868155869155870155871155872155873155874155875155876155877155878155879155880155881155882155883155884155885155886155887155888155889155890155891155892155893155894155895155896155897155898155899155900155901155902155903155904155905155906155907155908155909155910155911155912155913155914155915155916155917155918155919155920155921155922155923155924155925155926155927155928155929155930155931155932155933155934155935155936155937155938155939155940155941155942155943155944155945155946155947155948155949155950155951155952155953155954155955155956155957155958155959155960155961155962155963155964155965155966155967155968155969155970155971155972155973155974155975155976155977155978155979155980155981155982155983155984155985155986155987155988155989155990155991155992155993155994155995155996155997155998155999156000156001156002156003156004156005156006156007156008156009156010156011156012156013156014156015156016156017156018156019156020156021156022156023156024156025156026156027156028156029156030156031156032156033156034156035156036156037156038156039156040156041156042156043156044156045156046156047156048156049156050156051156052156053156054156055156056156057156058156059156060156061156062156063156064156065156066156067156068156069156070156071156072156073156074156075156076156077156078156079156080156081156082156083156084156085156086156087156088156089156090156091156092156093156094156095156096156097156098156099156100156101156102156103156104156105156106156107156108156109156110156111156112156113156114156115156116156117156118156119156120156121156122156123156124156125156126156127156128156129156130156131156132156133156134156135156136156137156138156139156140156141156142156143156144156145156146156147156148156149156150156151156152156153156154156155156156156157156158156159156160156161156162156163156164156165156166156167156168156169156170156171156172156173156174156175156176156177156178156179156180156181156182156183156184156185156186156187156188156189156190156191156192156193156194156195156196156197156198156199156200156201156202156203156204156205156206156207156208156209156210156211156212156213156214156215156216156217156218156219156220156221156222156223156224156225156226156227156228156229156230156231156232156233156234156235156236156237156238156239156240156241156242156243156244156245156246156247156248156249156250156251156252156253156254156255156256156257156258156259156260156261156262156263156264156265156266156267156268156269156270156271156272156273156274156275156276156277156278156279156280156281156282156283156284156285156286156287156288156289156290156291156292156293156294156295156296156297156298156299156300156301156302156303156304156305156306156307156308156309156310156311156312156313156314156315156316156317156318156319156320156321156322156323156324156325156326156327156328156329156330156331156332156333156334156335156336156337156338156339156340156341156342156343156344156345156346156347156348156349156350156351156352156353156354156355156356156357156358156359156360156361156362156363156364156365156366156367156368156369156370156371156372156373156374156375156376156377156378156379156380156381156382156383156384156385156386156387156388156389156390156391156392156393156394156395156396156397156398156399156400156401156402156403156404156405156406156407156408156409156410156411156412156413156414156415156416156417156418156419156420156421156422156423156424156425156426156427156428156429156430156431156432156433156434156435156436156437156438156439156440156441156442156443156444156445156446156447156448156449156450156451156452156453156454156455156456156457156458156459156460156461156462156463156464156465156466156467156468156469156470156471156472156473156474156475156476156477156478156479156480156481156482156483156484156485156486156487156488156489156490156491156492156493156494156495156496156497156498156499156500156501156502156503156504156505156506156507156508156509156510156511156512156513156514156515156516156517156518156519156520156521156522156523156524156525156526156527156528156529156530156531156532156533156534156535156536156537156538156539156540156541156542156543156544156545156546156547156548156549156550156551156552156553156554156555156556156557156558156559156560156561156562156563156564156565156566156567156568156569156570156571156572156573156574156575156576156577156578156579156580156581156582156583156584156585156586156587156588156589156590156591156592156593156594156595156596156597156598156599156600156601156602156603156604156605156606156607156608156609156610156611156612156613156614156615156616156617156618156619156620156621156622156623156624156625156626156627156628156629156630156631156632156633156634156635156636156637156638156639156640156641156642156643156644156645156646156647156648156649156650156651156652156653156654156655156656156657156658156659156660156661156662156663156664156665156666156667156668156669156670156671156672156673156674156675156676156677156678156679156680156681156682156683156684156685156686156687156688156689156690156691156692156693156694156695156696156697156698156699156700156701156702156703156704156705156706156707156708156709156710156711156712156713156714156715156716156717156718156719156720156721156722156723156724156725156726156727156728156729156730156731156732156733156734156735156736156737156738156739156740156741156742156743156744156745156746156747156748156749156750156751156752156753156754156755156756156757156758156759156760156761156762156763156764156765156766156767156768156769156770156771156772156773156774156775156776156777156778156779156780156781156782156783156784156785156786156787156788156789156790156791156792156793156794156795156796156797156798156799156800156801156802156803156804156805156806156807156808156809156810156811156812156813156814156815156816156817156818156819156820156821156822156823156824156825156826156827156828156829156830156831156832156833156834156835156836156837156838156839156840156841156842156843156844156845156846156847156848156849156850156851156852156853156854156855156856156857156858156859156860156861156862156863156864156865156866156867156868156869156870156871156872156873156874156875156876156877156878156879156880156881156882156883156884156885156886156887156888156889156890156891156892156893156894156895156896156897156898156899156900156901156902156903156904156905156906156907156908156909156910156911156912156913156914156915156916156917156918156919156920156921156922156923156924156925156926156927156928156929156930156931156932156933156934156935156936156937156938156939156940156941156942156943156944156945156946156947156948156949156950156951156952156953156954156955156956156957156958156959156960156961156962156963156964156965156966156967156968156969156970156971156972156973156974156975156976156977156978156979156980156981156982156983156984156985156986156987156988156989156990156991156992156993156994156995156996156997156998156999157000157001157002157003157004157005157006157007157008157009157010157011157012157013157014157015157016157017157018157019157020157021157022157023157024157025157026157027157028157029157030157031157032157033157034157035157036157037157038157039157040157041157042157043157044157045157046157047157048157049157050157051157052157053157054157055157056157057157058157059157060157061157062157063157064157065157066157067157068157069157070157071157072157073157074157075157076157077157078157079157080157081157082157083157084157085157086157087157088157089157090157091157092157093157094157095157096157097157098157099157100157101157102157103157104157105157106157107157108157109157110157111157112157113157114157115157116157117157118157119157120157121157122157123157124157125157126157127157128157129157130157131157132157133157134157135157136157137157138157139157140157141157142157143157144157145157146157147157148157149157150157151157152157153157154157155157156157157157158157159157160157161157162157163157164157165157166157167157168157169157170157171157172157173157174157175157176157177157178157179157180157181157182157183157184157185157186157187157188157189157190157191157192157193157194157195157196157197157198157199157200157201157202157203157204157205157206157207157208157209157210157211157212157213157214157215157216157217157218157219157220157221157222157223157224157225157226157227157228157229157230157231157232157233157234157235157236157237157238157239157240157241157242157243157244157245157246157247157248157249157250157251157252157253157254157255157256157257157258157259157260157261157262157263157264157265157266157267157268157269157270157271157272157273157274157275157276157277157278157279157280157281157282157283157284157285157286157287157288157289157290157291157292157293157294157295157296157297157298157299157300157301157302157303157304157305157306157307157308157309157310157311157312157313157314157315157316157317157318157319157320157321157322157323157324157325157326157327157328157329157330157331157332157333157334157335157336157337157338157339157340157341157342157343157344157345157346157347157348157349157350157351157352157353157354157355157356157357157358157359157360157361157362157363157364157365157366157367157368157369157370157371157372157373157374157375157376157377157378157379157380157381157382157383157384157385157386157387157388157389157390157391157392157393157394157395157396157397157398157399157400157401157402157403157404157405157406157407157408157409157410157411157412157413157414157415157416157417157418157419157420157421157422157423157424157425157426157427157428157429157430157431157432157433157434157435157436157437157438157439157440157441157442157443157444157445157446157447157448157449157450157451157452157453157454157455157456157457157458157459157460157461157462157463157464157465157466157467157468157469157470157471157472157473157474157475157476157477157478157479157480157481157482157483157484157485157486157487157488157489157490157491157492157493157494157495157496157497157498157499157500157501157502157503157504157505157506157507157508157509157510157511157512157513157514157515157516157517157518157519157520157521157522157523157524157525157526157527157528157529157530157531157532157533157534157535157536157537157538157539157540157541157542157543157544157545157546157547157548157549157550157551157552157553157554157555157556157557157558157559157560157561157562157563157564157565157566157567157568157569157570157571157572157573157574157575157576157577157578157579157580157581157582157583157584157585157586157587157588157589157590157591157592157593157594157595157596157597157598157599157600157601157602157603157604157605157606157607157608157609157610157611157612157613157614157615157616157617157618157619157620157621157622157623157624157625157626157627157628157629157630157631157632157633157634157635157636157637157638157639157640157641157642157643157644157645157646157647157648157649157650157651157652157653157654157655157656157657157658157659157660157661157662157663157664157665157666157667157668157669157670157671157672157673157674157675157676157677157678157679157680157681157682157683157684157685157686157687157688157689157690157691157692157693157694157695157696157697157698157699157700157701157702157703157704157705157706157707157708157709157710157711157712157713157714157715157716157717157718157719157720157721157722157723157724157725157726157727157728157729157730157731157732157733157734157735157736157737157738157739157740157741157742157743157744157745157746157747157748157749157750157751157752157753157754157755157756157757157758157759157760157761157762157763157764157765157766157767157768157769157770157771157772157773157774157775157776157777157778157779157780157781157782157783157784157785157786157787157788157789157790157791157792157793157794157795157796157797157798157799157800157801157802157803157804157805157806157807157808157809157810157811157812157813157814157815157816157817157818157819157820157821157822157823157824157825157826157827157828157829157830157831157832157833157834157835157836157837157838157839157840157841157842157843157844157845157846157847157848157849157850157851157852157853157854157855157856157857157858157859157860157861157862157863157864157865157866157867157868157869157870157871157872157873157874157875157876157877157878157879157880157881157882157883157884157885157886157887157888157889157890157891157892157893157894157895157896157897157898157899157900157901157902157903157904157905157906157907157908157909157910157911157912157913157914157915157916157917157918157919157920157921157922157923157924157925157926157927157928157929157930157931157932157933157934157935157936157937157938157939157940157941157942157943157944157945157946157947157948157949157950157951157952157953157954157955157956157957157958157959157960157961157962157963157964157965157966157967157968157969157970157971157972157973157974157975157976157977157978157979157980157981157982157983157984157985157986157987157988157989157990157991157992157993157994157995157996157997157998157999158000158001158002158003158004158005158006158007158008158009158010158011158012158013158014158015158016158017158018158019158020158021158022158023158024158025158026158027158028158029158030158031158032158033158034158035158036158037158038158039158040158041158042158043158044158045158046158047158048158049158050158051158052158053158054158055158056158057158058158059158060158061158062158063158064158065158066158067158068158069158070158071158072158073158074158075158076158077158078158079158080158081158082158083158084158085158086158087158088158089158090158091158092158093158094158095158096158097158098158099158100158101158102158103158104158105158106158107158108158109158110158111158112158113158114158115158116158117158118158119158120158121158122158123158124158125158126158127158128158129158130158131158132158133158134158135158136158137158138158139158140158141158142158143158144158145158146158147158148158149158150158151158152158153158154158155158156158157158158158159158160158161158162158163158164158165158166158167158168158169158170158171158172158173158174158175158176158177158178158179158180158181158182158183158184158185158186158187158188158189158190158191158192158193158194158195158196158197158198158199158200158201158202158203158204158205158206158207158208158209158210158211158212158213158214158215158216158217158218158219158220158221158222158223158224158225158226158227158228158229158230158231158232158233158234158235158236158237158238158239158240158241158242158243158244158245158246158247158248158249158250158251158252158253158254158255158256158257158258158259158260158261158262158263158264158265158266158267158268158269158270158271158272158273158274158275158276158277158278158279158280158281158282158283158284158285158286158287158288158289158290158291158292158293158294158295158296158297158298158299158300158301158302158303158304158305158306158307158308158309158310158311158312158313158314158315158316158317158318158319158320158321158322158323158324158325158326158327158328158329158330158331158332158333158334158335158336158337158338158339158340158341158342158343158344158345158346158347158348158349158350158351158352158353158354158355158356158357158358158359158360158361158362158363158364158365158366158367158368158369158370158371158372158373158374158375158376158377158378158379158380158381158382158383158384158385158386158387158388158389158390158391158392158393158394158395158396158397158398158399158400158401158402158403158404158405158406158407158408158409158410158411158412158413158414158415158416158417158418158419158420158421158422158423158424158425158426158427158428158429158430158431158432158433158434158435158436158437158438158439158440158441158442158443158444158445158446158447158448158449158450158451158452158453158454158455158456158457158458158459158460158461158462158463158464158465158466158467158468158469158470158471158472158473158474158475158476158477158478158479158480158481158482158483158484158485158486158487158488158489158490158491158492158493158494158495158496158497158498158499158500158501158502158503158504158505158506158507158508158509158510158511158512158513158514158515158516158517158518158519158520158521158522158523158524158525158526158527158528158529158530158531158532158533158534158535158536158537158538158539158540158541158542158543158544158545158546158547158548158549158550158551158552158553158554158555158556158557158558158559158560158561158562158563158564158565158566158567158568158569158570158571158572158573158574158575158576158577158578158579158580158581158582158583158584158585158586158587158588158589158590158591158592158593158594158595158596158597158598158599158600158601158602158603158604158605158606158607158608158609158610158611158612158613158614158615158616158617158618158619158620158621158622158623158624158625158626158627158628158629158630158631158632158633158634158635158636158637158638158639158640158641158642158643158644158645158646158647158648158649158650158651158652158653158654158655158656158657158658158659158660158661158662158663158664158665158666158667158668158669158670158671158672158673158674158675158676158677158678158679158680158681158682158683158684158685158686158687158688158689158690158691158692158693158694158695158696158697158698158699158700158701158702158703158704158705158706158707158708158709158710158711158712158713158714158715158716158717158718158719158720158721158722158723158724158725158726158727158728158729158730158731158732158733158734158735158736158737158738158739158740158741158742158743158744158745158746158747158748158749158750158751158752158753158754158755158756158757158758158759158760158761158762158763158764158765158766158767158768158769158770158771158772158773158774158775158776158777158778158779158780158781158782158783158784158785158786158787158788158789158790158791158792158793158794158795158796158797158798158799158800158801158802158803158804158805158806158807158808158809158810158811158812158813158814158815158816158817158818158819158820158821158822158823158824158825158826158827158828158829158830158831158832158833158834158835158836158837158838158839158840158841158842158843158844158845158846158847158848158849158850158851158852158853158854158855158856158857158858158859158860158861158862158863158864158865158866158867158868158869158870158871158872158873158874158875158876158877158878158879158880158881158882158883158884158885158886158887158888158889158890158891158892158893158894158895158896158897158898158899158900158901158902158903158904158905158906158907158908158909158910158911158912158913158914158915158916158917158918158919158920158921158922158923158924158925158926158927158928158929158930158931158932158933158934158935158936158937158938158939158940158941158942158943158944158945158946158947158948158949158950158951158952158953158954158955158956158957158958158959158960158961158962158963158964158965158966158967158968158969158970158971158972158973158974158975158976158977158978158979158980158981158982158983158984158985158986158987158988158989158990158991158992158993158994158995158996158997158998158999159000159001159002159003159004159005159006159007159008159009159010159011159012159013159014159015159016159017159018159019159020159021159022159023159024159025159026159027159028159029159030159031159032159033159034159035159036159037159038159039159040159041159042159043159044159045159046159047159048159049159050159051159052159053159054159055159056159057159058159059159060159061159062159063159064159065159066159067159068159069159070159071159072159073159074159075159076159077159078159079159080159081159082159083159084159085159086159087159088159089159090159091159092159093159094159095159096159097159098159099159100159101159102159103159104159105159106159107159108159109159110159111159112159113159114159115159116159117159118159119159120159121159122159123159124159125159126159127159128159129159130159131159132159133159134159135159136159137159138159139159140159141159142159143159144159145159146159147159148159149159150159151159152159153159154159155159156159157159158159159159160159161159162159163159164159165159166159167159168159169159170159171159172159173159174159175159176159177159178159179159180159181159182159183159184159185159186159187159188159189159190159191159192159193159194159195159196159197159198159199159200159201159202159203159204159205159206159207159208159209159210159211159212159213159214159215159216159217159218159219159220159221159222159223159224159225159226159227159228159229159230159231159232159233159234159235159236159237159238159239159240159241159242159243159244159245159246159247159248159249159250159251159252159253159254159255159256159257159258159259159260159261159262159263159264159265159266159267159268159269159270159271159272159273159274159275159276159277159278159279159280159281159282159283159284159285159286159287159288159289159290159291159292159293159294159295159296159297159298159299159300159301159302159303159304159305159306159307159308159309159310159311159312159313159314159315159316159317159318159319159320159321159322159323159324159325159326159327159328159329159330159331159332159333159334159335159336159337159338159339159340159341159342159343159344159345159346159347159348159349159350159351159352159353159354159355159356159357159358159359159360159361159362159363159364159365159366159367159368159369159370159371159372159373159374159375159376159377159378159379159380159381159382159383159384159385159386159387159388159389159390159391159392159393159394159395159396159397159398159399159400159401159402159403159404159405159406159407159408159409159410159411159412159413159414159415159416159417159418159419159420159421159422159423159424159425159426159427159428159429159430159431159432159433159434159435159436159437159438159439159440159441159442159443159444159445159446159447159448159449159450159451159452159453159454159455159456159457159458159459159460159461159462159463159464159465159466159467159468159469159470159471159472159473159474159475159476159477159478159479159480159481159482159483159484159485159486159487159488159489159490159491159492159493159494159495159496159497159498159499159500159501159502159503159504159505159506159507159508159509159510159511159512159513159514159515159516159517159518159519159520159521159522159523159524159525159526159527159528159529159530159531159532159533159534159535159536159537159538159539159540159541159542159543159544159545159546159547159548159549159550159551159552159553159554159555159556159557159558159559159560159561159562159563159564159565159566159567159568159569159570159571159572159573159574159575159576159577159578159579159580159581159582159583159584159585159586159587159588159589159590159591159592159593159594159595159596159597159598159599159600159601159602159603159604159605159606159607159608159609159610159611159612159613159614159615159616159617159618159619159620159621159622159623159624159625159626159627159628159629159630159631159632159633159634159635159636159637159638159639159640159641159642159643159644159645159646159647159648159649159650159651159652159653159654159655159656159657159658159659159660159661159662159663159664159665159666159667159668159669159670159671159672159673159674159675159676159677159678159679159680159681159682159683159684159685159686159687159688159689159690159691159692159693159694159695159696159697159698159699159700159701159702159703159704159705159706159707159708159709159710159711159712159713159714159715159716159717159718159719159720159721159722159723159724159725159726159727159728159729159730159731159732159733159734159735159736159737159738159739159740159741159742159743159744159745159746159747159748159749159750159751159752159753159754159755159756159757159758159759159760159761159762159763159764159765159766159767159768159769159770159771159772159773159774159775159776159777159778159779159780159781159782159783159784159785159786159787159788159789159790159791159792159793159794159795159796159797159798159799159800159801159802159803159804159805159806159807159808159809159810159811159812159813159814159815159816159817159818159819159820159821159822159823159824159825159826159827159828159829159830159831159832159833159834159835159836159837159838159839159840159841159842159843159844159845159846159847159848159849159850159851159852159853159854159855159856159857159858159859159860159861159862159863159864159865159866159867159868159869159870159871159872159873159874159875159876159877159878159879159880159881159882159883159884159885159886159887159888159889159890159891159892159893159894159895159896159897159898159899159900159901159902159903159904159905159906159907159908159909159910159911159912159913159914159915159916159917159918159919159920159921159922159923159924159925159926159927159928159929159930159931159932159933159934159935159936159937159938159939159940159941159942159943159944159945159946159947159948159949159950159951159952159953159954159955159956159957159958159959159960159961159962159963159964159965159966159967159968159969159970159971159972159973159974159975159976159977159978159979159980159981159982159983159984159985159986159987159988159989159990159991159992159993159994159995159996159997159998159999160000160001160002160003160004160005160006160007160008160009160010160011160012160013160014160015160016160017160018160019160020160021160022160023160024160025160026160027160028160029160030160031160032160033160034160035160036160037160038160039160040160041160042160043160044160045160046160047160048160049160050160051160052160053160054160055160056160057160058160059160060160061160062160063160064160065160066160067160068160069160070160071160072160073160074160075160076160077160078160079160080160081160082160083160084160085160086160087160088160089160090160091160092160093160094160095160096160097160098160099160100160101160102160103160104160105160106160107160108160109160110160111160112160113160114160115160116160117160118160119160120160121160122160123160124160125160126160127160128160129160130160131160132160133160134160135160136160137160138160139160140160141160142160143160144160145160146160147160148160149160150160151160152160153160154160155160156160157160158160159160160160161160162160163160164160165160166160167160168160169160170160171160172160173160174160175160176160177160178160179160180160181160182160183160184160185160186160187160188160189160190160191160192160193160194160195160196160197160198160199160200160201160202160203160204160205160206160207160208160209160210160211160212160213160214160215160216160217160218160219160220160221160222160223160224160225160226160227160228160229160230160231160232160233160234160235160236160237160238160239160240160241160242160243160244160245160246160247160248160249160250160251160252160253160254160255160256160257160258160259160260160261160262160263160264160265160266160267160268160269160270160271160272160273160274160275160276160277160278160279160280160281160282160283160284160285160286160287160288160289160290160291160292160293160294160295160296160297160298160299160300160301160302160303160304160305160306160307160308160309160310160311160312160313160314160315160316160317160318160319160320160321160322160323160324160325160326160327160328160329160330160331160332160333160334160335160336160337160338160339160340160341160342160343160344160345160346160347160348160349160350160351160352160353160354160355160356160357160358160359160360160361160362160363160364160365160366160367160368160369160370160371160372160373160374160375160376160377160378160379160380160381160382160383160384160385160386160387160388160389160390160391160392160393160394160395160396160397160398160399160400160401160402160403160404160405160406160407160408160409160410160411160412160413160414160415160416160417160418160419160420160421160422160423160424160425160426160427160428160429160430160431160432160433160434160435160436160437160438160439160440160441160442160443160444160445160446160447160448160449160450160451160452160453160454160455160456160457160458160459160460160461160462160463160464160465160466160467160468160469160470160471160472160473160474160475160476160477160478160479160480160481160482160483160484160485160486160487160488160489160490160491160492160493160494160495160496160497160498160499160500160501160502160503160504160505160506160507160508160509160510160511160512160513160514160515160516160517160518160519160520160521160522160523160524160525160526160527160528160529160530160531160532160533160534160535160536160537160538160539160540160541160542160543160544160545160546160547160548160549160550160551160552160553160554160555160556160557160558160559160560160561160562160563160564160565160566160567160568160569160570160571160572160573160574160575160576160577160578160579160580160581160582160583160584160585160586160587160588160589160590160591160592160593160594160595160596160597160598160599160600160601160602160603160604160605160606160607160608160609160610160611160612160613160614160615160616160617160618160619160620160621160622160623160624160625160626160627160628160629160630160631160632160633160634160635160636160637160638160639160640160641160642160643160644160645160646160647160648160649160650160651160652160653160654160655160656160657160658160659160660160661160662160663160664160665160666160667160668160669160670160671160672160673160674160675160676160677160678160679160680160681160682160683160684160685160686160687160688160689160690160691160692160693160694160695160696160697160698160699160700160701160702160703160704160705160706160707160708160709160710160711160712160713160714160715160716160717160718160719160720160721160722160723160724160725160726160727160728160729160730160731160732160733160734160735160736160737160738160739160740160741160742160743160744160745160746160747160748160749160750160751160752160753160754160755160756160757160758160759160760160761160762160763160764160765160766160767160768160769160770160771160772160773160774160775160776160777160778160779160780160781160782160783160784160785160786160787160788160789160790160791160792160793160794160795160796160797160798160799160800160801160802160803160804160805160806160807160808160809160810160811160812160813160814160815160816160817160818160819160820160821160822160823160824160825160826160827160828160829160830160831160832160833160834160835160836160837160838160839160840160841160842160843160844160845160846160847160848160849160850160851160852160853160854160855160856160857160858160859160860160861160862160863160864160865160866160867160868160869160870160871160872160873160874160875160876160877160878160879160880160881160882160883160884160885160886160887160888160889160890160891160892160893160894160895160896160897160898160899160900160901160902160903160904160905160906160907160908160909160910160911160912160913160914160915160916160917160918160919160920160921160922160923160924160925160926160927160928160929160930160931160932160933160934160935160936160937160938160939160940160941160942160943160944160945160946160947160948160949160950160951160952160953160954160955160956160957160958160959160960160961160962160963160964160965160966160967160968160969160970160971160972160973160974160975160976160977160978160979160980160981160982160983160984160985160986160987160988160989160990160991160992160993160994160995160996160997160998160999161000161001161002161003161004161005161006161007161008161009161010161011161012161013161014161015161016161017161018161019161020161021161022161023161024161025161026161027161028161029161030161031161032161033161034161035161036161037161038161039161040161041161042161043161044161045161046161047161048161049161050161051161052161053161054161055161056161057161058161059161060161061161062161063161064161065161066161067161068161069161070161071161072161073161074161075161076161077161078161079161080161081161082161083161084161085161086161087161088161089161090161091161092161093161094161095161096161097161098161099161100161101161102161103161104161105161106161107161108161109161110161111161112161113161114161115161116161117161118161119161120161121161122161123161124161125161126161127161128161129161130161131161132161133161134161135161136161137161138161139161140161141161142161143161144161145161146161147161148161149161150161151161152161153161154161155161156161157161158161159161160161161161162161163161164161165161166161167161168161169161170161171161172161173161174161175161176161177161178161179161180161181161182161183161184161185161186161187161188161189161190161191161192161193161194161195161196161197161198161199161200161201161202161203161204161205161206161207161208161209161210161211161212161213161214161215161216161217161218161219161220161221161222161223161224161225161226161227161228161229161230161231161232161233161234161235161236161237161238161239161240161241161242161243161244161245161246161247161248161249161250161251161252161253161254161255161256161257161258161259161260161261161262161263161264161265161266161267161268161269161270161271161272161273161274161275161276161277161278161279161280161281161282161283161284161285161286161287161288161289161290161291161292161293161294161295161296161297161298161299161300161301161302161303161304161305161306161307161308161309161310161311161312161313161314161315161316161317161318161319161320161321161322161323161324161325161326161327161328161329161330161331161332161333161334161335161336161337161338161339161340161341161342161343161344161345161346161347161348161349161350161351161352161353161354161355161356161357161358161359161360161361161362161363161364161365161366161367161368161369161370161371161372161373161374161375161376161377161378161379161380161381161382161383161384161385161386161387161388161389161390161391161392161393161394161395161396161397161398161399161400161401161402161403161404161405161406161407161408161409161410161411161412161413161414161415161416161417161418161419161420161421161422161423161424161425161426161427161428161429161430161431161432161433161434161435161436161437161438161439161440161441161442161443161444161445161446161447161448161449161450161451161452161453161454161455161456161457161458161459161460161461161462161463161464161465161466161467161468161469161470161471161472161473161474161475161476161477161478161479161480161481161482161483161484161485161486161487161488161489161490161491161492161493161494161495161496161497161498161499161500161501161502161503161504161505161506161507161508161509161510161511161512161513161514161515161516161517161518161519161520161521161522161523161524161525161526161527161528161529161530161531161532161533161534161535161536161537161538161539161540161541161542161543161544161545161546161547161548161549161550161551161552161553161554161555161556161557161558161559161560161561161562161563161564161565161566161567161568161569161570161571161572161573161574161575161576161577161578161579161580161581161582161583161584161585161586161587161588161589161590161591161592161593161594161595161596161597161598161599161600161601161602161603161604161605161606161607161608161609161610161611161612161613161614161615161616161617161618161619161620161621161622161623161624161625161626161627161628161629161630161631161632161633161634161635161636161637161638161639161640161641161642161643161644161645161646161647161648161649161650161651161652161653161654161655161656161657161658161659161660161661161662161663161664161665161666161667161668161669161670161671161672161673161674161675161676161677161678161679161680161681161682161683161684161685161686161687161688161689161690161691161692161693161694161695161696161697161698161699161700161701161702161703161704161705161706161707161708161709161710161711161712161713161714161715161716161717161718161719161720161721161722161723161724161725161726161727161728161729161730161731161732161733161734161735161736161737161738161739161740161741161742161743161744161745161746161747161748161749161750161751161752161753161754161755161756161757161758161759161760161761161762161763161764161765161766161767161768161769161770161771161772161773161774161775161776161777161778161779161780161781161782161783161784161785161786161787161788161789161790161791161792161793161794161795161796161797161798161799161800161801161802161803161804161805161806161807161808161809161810161811161812161813161814161815161816161817161818161819161820161821161822161823161824161825161826161827161828161829161830161831161832161833161834161835161836161837161838161839161840161841161842161843161844161845161846161847161848161849161850161851161852161853161854161855161856161857161858161859161860161861161862161863161864161865161866161867161868161869161870161871161872161873161874161875161876161877161878161879161880161881161882161883161884161885161886161887161888161889161890161891161892161893161894161895161896161897161898161899161900161901161902161903161904161905161906161907161908161909161910161911161912161913161914161915161916161917161918161919161920161921161922161923161924161925161926161927161928161929161930161931161932161933161934161935161936161937161938161939161940161941161942161943161944161945161946161947161948161949161950161951161952161953161954161955161956161957161958161959161960161961161962161963161964161965161966161967161968161969161970161971161972161973161974161975161976161977161978161979161980161981161982161983161984161985161986161987161988161989161990161991161992161993161994161995161996161997161998161999162000162001162002162003162004162005162006162007162008162009162010162011162012162013162014162015162016162017162018162019162020162021162022162023162024162025162026162027162028162029162030162031162032162033162034162035162036162037162038162039162040162041162042162043162044162045162046162047162048162049162050162051162052162053162054162055162056162057162058162059162060162061162062162063162064162065162066162067162068162069162070162071162072162073162074162075162076162077162078162079162080162081162082162083162084162085162086162087162088162089162090162091162092162093162094162095162096162097162098162099162100162101162102162103162104162105162106162107162108162109162110162111162112162113162114162115162116162117162118162119162120162121162122162123162124162125162126162127162128162129162130162131162132162133162134162135162136162137162138162139162140162141162142162143162144162145162146162147162148162149162150162151162152162153162154162155162156162157162158162159162160162161162162162163162164162165162166162167162168162169162170162171162172162173162174162175162176162177162178162179162180162181162182162183162184162185162186162187162188162189162190162191162192162193162194162195162196162197162198162199162200162201162202162203162204162205162206162207162208162209162210162211162212162213162214162215162216162217162218162219162220162221162222162223162224162225162226162227162228162229162230162231162232162233162234162235162236162237162238162239162240162241162242162243162244162245162246162247162248162249162250162251162252162253162254162255162256162257162258162259162260162261162262162263162264162265162266162267162268162269162270162271162272162273162274162275162276162277162278162279162280162281162282162283162284162285162286162287162288162289162290162291162292162293162294162295162296162297162298162299162300162301162302162303162304162305162306162307162308162309162310162311162312162313162314162315162316162317162318162319162320162321162322162323162324162325162326162327162328162329162330162331162332162333162334162335162336162337162338162339162340162341162342162343162344162345162346162347162348162349162350162351162352162353162354162355162356162357162358162359162360162361162362162363162364162365162366162367162368162369162370162371162372162373162374162375162376162377162378162379162380162381162382162383162384162385162386162387162388162389162390162391162392162393162394162395162396162397162398162399162400162401162402162403162404162405162406162407162408162409162410162411162412162413162414162415162416162417162418162419162420162421162422162423162424162425162426162427162428162429162430162431162432162433162434162435162436162437162438162439162440162441162442162443162444162445162446162447162448162449162450162451162452162453162454162455162456162457162458162459162460162461162462162463162464162465162466162467162468162469162470162471162472162473162474162475162476162477162478162479162480162481162482162483162484162485162486162487162488162489162490162491162492162493162494162495162496162497162498162499162500162501162502162503162504162505162506162507162508162509162510162511162512162513162514162515162516162517162518162519162520162521162522162523162524162525162526162527162528162529162530162531162532162533162534162535162536162537162538162539162540162541162542162543162544162545162546162547162548162549162550162551162552162553162554162555162556162557162558162559162560162561162562162563162564162565162566162567162568162569162570162571162572162573162574162575162576162577162578162579162580162581162582162583162584162585162586162587162588162589162590162591162592162593162594162595162596162597162598162599162600162601162602162603162604162605162606162607162608162609162610162611162612162613162614162615162616162617162618162619162620162621162622162623162624162625162626162627162628162629162630162631162632162633162634162635162636162637162638162639162640162641162642162643162644162645162646162647162648162649162650162651162652162653162654162655162656162657162658162659162660162661162662162663162664162665162666162667162668162669162670162671162672162673162674162675162676162677162678162679162680162681162682162683162684162685162686162687162688162689162690162691162692162693162694162695162696162697162698162699162700162701162702162703162704162705162706162707162708162709162710162711162712162713162714162715162716162717162718162719162720162721162722162723162724162725162726162727162728162729162730162731162732162733162734162735162736162737162738162739162740162741162742162743162744162745162746162747162748162749162750162751162752162753162754162755162756162757162758162759162760162761162762162763162764162765162766162767162768162769162770162771162772162773162774162775162776162777162778162779162780162781162782162783162784162785162786162787162788162789162790162791162792162793162794162795162796162797162798162799162800162801162802162803162804162805162806162807162808162809162810162811162812162813162814162815162816162817162818162819162820162821162822162823162824162825162826162827162828162829162830162831162832162833162834162835162836162837162838162839162840162841162842162843162844162845162846162847162848162849162850162851162852162853162854162855162856162857162858162859162860162861162862162863162864162865162866162867162868162869162870162871162872162873162874162875162876162877162878162879162880162881162882162883162884162885162886162887162888162889162890162891162892162893162894162895162896162897162898162899162900162901162902162903162904162905162906162907162908162909162910162911162912162913162914162915162916162917162918162919162920162921162922162923162924162925162926162927162928162929162930162931162932162933162934162935162936162937162938162939162940162941162942162943162944162945162946162947162948162949162950162951162952162953162954162955162956162957162958162959162960162961162962162963162964162965162966162967162968162969162970162971162972162973162974162975162976162977162978162979162980162981162982162983162984162985162986162987162988162989162990162991162992162993162994162995162996162997162998162999163000163001163002163003163004163005163006163007163008163009163010163011163012163013163014163015163016163017163018163019163020163021163022163023163024163025163026163027163028163029163030163031163032163033163034163035163036163037163038163039163040163041163042163043163044163045163046163047163048163049163050163051163052163053163054163055163056163057163058163059163060163061163062163063163064163065163066163067163068163069163070163071163072163073163074163075163076163077163078163079163080163081163082163083163084163085163086163087163088163089163090163091163092163093163094163095163096163097163098163099163100163101163102163103163104163105163106163107163108163109163110163111163112163113163114163115163116163117163118163119163120163121163122163123163124163125163126163127163128163129163130163131163132163133163134163135163136163137163138163139163140163141163142163143163144163145163146163147163148163149163150163151163152163153163154163155163156163157163158163159163160163161163162163163163164163165163166163167163168163169163170163171163172163173163174163175163176163177163178163179163180163181163182163183163184163185163186163187163188163189163190163191163192163193163194163195163196163197163198163199163200163201163202163203163204163205163206163207163208163209163210163211163212163213163214163215163216163217163218163219163220163221163222163223163224163225163226163227163228163229163230163231163232163233163234163235163236163237163238163239163240163241163242163243163244163245163246163247163248163249163250163251163252163253163254163255163256163257163258163259163260163261163262163263163264163265163266163267163268163269163270163271163272163273163274163275163276163277163278163279163280163281163282163283163284163285163286163287163288163289163290163291163292163293163294163295163296163297163298163299163300163301163302163303163304163305163306163307163308163309163310163311163312163313163314163315163316163317163318163319163320163321163322163323163324163325163326163327163328163329163330163331163332163333163334163335163336163337163338163339163340163341163342163343163344163345163346163347163348163349163350163351163352163353163354163355163356163357163358163359163360163361163362163363163364163365163366163367163368163369163370163371163372163373163374163375163376163377163378163379163380163381163382163383163384163385163386163387163388163389163390163391163392163393163394163395163396163397163398163399163400163401163402163403163404163405163406163407163408163409163410163411163412163413163414163415163416163417163418163419163420163421163422163423163424163425163426163427163428163429163430163431163432163433163434163435163436163437163438163439163440163441163442163443163444163445163446163447163448163449163450163451163452163453163454163455163456163457163458163459163460163461163462163463163464163465163466163467163468163469163470163471163472163473163474163475163476163477163478163479163480163481163482163483163484163485163486163487163488163489163490163491163492163493163494163495163496163497163498163499163500163501163502163503163504163505163506163507163508163509163510163511163512163513163514163515163516163517163518163519163520163521163522163523163524163525163526163527163528163529163530163531163532163533163534163535163536163537163538163539163540163541163542163543163544163545163546163547163548163549163550163551163552163553163554163555163556163557163558163559163560163561163562163563163564163565163566163567163568163569163570163571163572163573163574163575163576163577163578163579163580163581163582163583163584163585163586163587163588163589163590163591163592163593163594163595163596163597163598163599163600163601163602163603163604163605163606163607163608163609163610163611163612163613163614163615163616163617163618163619163620163621163622163623163624163625163626163627163628163629163630163631163632163633163634163635163636163637163638163639163640163641163642163643163644163645163646163647163648163649163650163651163652163653163654163655163656163657163658163659163660163661163662163663163664163665163666163667163668163669163670163671163672163673163674163675163676163677163678163679163680163681163682163683163684163685163686163687163688163689163690163691163692163693163694163695163696163697163698163699163700163701163702163703163704163705163706163707163708163709163710163711163712163713163714163715163716163717163718163719163720163721163722163723163724163725163726163727163728163729163730163731163732163733163734163735163736163737163738163739163740163741163742163743163744163745163746163747163748163749163750163751163752163753163754163755163756163757163758163759163760163761163762163763163764163765163766163767163768163769163770163771163772163773163774163775163776163777163778163779163780163781163782163783163784163785163786163787163788163789163790163791163792163793163794163795163796163797163798163799163800163801163802163803163804163805163806163807163808163809163810163811163812163813163814163815163816163817163818163819163820163821163822163823163824163825163826163827163828163829163830163831163832163833163834163835163836163837163838163839163840163841163842163843163844163845163846163847163848163849163850163851163852163853163854163855163856163857163858163859163860163861163862163863163864163865163866163867163868163869163870163871163872163873163874163875163876163877163878163879163880163881163882163883163884163885163886163887163888163889163890163891163892163893163894163895163896163897163898163899163900163901163902163903163904163905163906163907163908163909163910163911163912163913163914163915163916163917163918163919163920163921163922163923163924163925163926163927163928163929163930163931163932163933163934163935163936163937163938163939163940163941163942163943163944163945163946163947163948163949163950163951163952163953163954163955163956163957163958163959163960163961163962163963163964163965163966163967163968163969163970163971163972163973163974163975163976163977163978163979163980163981163982163983163984163985163986163987163988163989163990163991163992163993163994163995163996163997163998163999164000164001164002164003164004164005164006164007164008164009164010164011164012164013164014164015164016164017164018164019164020164021164022164023164024164025164026164027164028164029164030164031164032164033164034164035164036164037164038164039164040164041164042164043164044164045164046164047164048164049164050164051164052164053164054164055164056164057164058164059164060164061164062164063164064164065164066164067164068164069164070164071164072164073164074164075164076164077164078164079164080164081164082164083164084164085164086164087164088164089164090164091164092164093164094164095164096164097164098164099164100164101164102164103164104164105164106164107164108164109164110164111164112164113164114164115164116164117164118164119164120164121164122164123164124164125164126164127164128164129164130164131164132164133164134164135164136164137164138164139164140164141164142164143164144164145164146164147164148164149164150164151164152164153164154164155164156164157164158164159164160164161164162164163164164164165164166164167164168164169164170164171164172164173164174164175164176164177164178164179164180164181164182164183164184164185164186164187164188164189164190164191164192164193164194164195164196164197164198164199164200164201164202164203164204164205164206164207164208164209164210164211164212164213164214164215164216164217164218164219164220164221164222164223164224164225164226164227164228164229164230164231164232164233164234164235164236164237164238164239164240164241164242164243164244164245164246164247164248164249164250164251164252164253164254164255164256164257164258164259164260164261164262164263164264164265164266164267164268164269164270164271164272164273164274164275164276164277164278164279164280164281164282164283164284164285164286164287164288164289164290164291164292164293164294164295164296164297164298164299164300164301164302164303164304164305164306164307164308164309164310164311164312164313164314164315164316164317164318164319164320164321164322164323164324164325164326164327164328164329164330164331164332164333164334164335164336164337164338164339164340164341164342164343164344164345164346164347164348164349164350164351164352164353164354164355164356164357164358164359164360164361164362164363164364164365164366164367164368164369164370164371164372164373164374164375164376164377164378164379164380164381164382164383164384164385164386164387164388164389164390164391164392164393164394164395164396164397164398164399164400164401164402164403164404164405164406164407164408164409164410164411164412164413164414164415164416164417164418164419164420164421164422164423164424164425164426164427164428164429164430164431164432164433164434164435164436164437164438164439164440164441164442164443164444164445164446164447164448164449164450164451164452164453164454164455164456164457164458164459164460164461164462164463164464164465164466164467164468164469164470164471164472164473164474164475164476164477164478164479164480164481164482164483164484164485164486164487164488164489164490164491164492164493164494164495164496164497164498164499164500164501164502164503164504164505164506164507164508164509164510164511164512164513164514164515164516164517164518164519164520164521164522164523164524164525164526164527164528164529164530164531164532164533164534164535164536164537164538164539164540164541164542164543164544164545164546164547164548164549164550164551164552164553164554164555164556164557164558164559164560164561164562164563164564164565164566164567164568164569164570164571164572164573164574164575164576164577164578164579164580164581164582164583164584164585164586164587164588164589164590164591164592164593164594164595164596164597164598164599164600164601164602164603164604164605164606164607164608164609164610164611164612164613164614164615164616164617164618164619164620164621164622164623164624164625164626164627164628164629164630164631164632164633164634164635164636164637164638164639164640164641164642164643164644164645164646164647164648164649164650164651164652164653164654164655164656164657164658164659164660164661164662164663164664164665164666164667164668164669164670164671164672164673164674164675164676164677164678164679164680164681164682164683164684164685164686164687164688164689164690164691164692164693164694164695164696164697164698164699164700164701164702164703164704164705164706164707164708164709164710164711164712164713164714164715164716164717164718164719164720164721164722164723164724164725164726164727164728164729164730164731164732164733164734164735164736164737164738164739164740164741164742164743164744164745164746164747164748164749164750164751164752164753164754164755164756164757164758164759164760164761164762164763164764164765164766164767164768164769164770164771164772164773164774164775164776164777164778164779164780164781164782164783164784164785164786164787164788164789164790164791164792164793164794164795164796164797164798164799164800164801164802164803164804164805164806164807164808164809164810164811164812164813164814164815164816164817164818164819164820164821164822164823164824164825164826164827164828164829164830164831164832164833164834164835164836164837164838164839164840164841164842164843164844164845164846164847164848164849164850164851164852164853164854164855164856164857164858164859164860164861164862164863164864164865164866164867164868164869164870164871164872164873164874164875164876164877164878164879164880164881164882164883164884164885164886164887164888164889164890164891164892164893164894164895164896164897164898164899164900164901164902164903164904164905164906164907164908164909164910164911164912164913164914164915164916164917164918164919164920164921164922164923164924164925164926164927164928164929164930164931164932164933164934164935164936164937164938164939164940164941164942164943164944164945164946164947164948164949164950164951164952164953164954164955164956164957164958164959164960164961164962164963164964164965164966164967164968164969164970164971164972164973164974164975164976164977164978164979164980164981164982164983164984164985164986164987164988164989164990164991164992164993164994164995164996164997164998164999165000165001165002165003165004165005165006165007165008165009165010165011165012165013165014165015165016165017165018165019165020165021165022165023165024165025165026165027165028165029165030165031165032165033165034165035165036165037165038165039165040165041165042165043165044165045165046165047165048165049165050165051165052165053165054165055165056165057165058165059165060165061165062165063165064165065165066165067165068165069165070165071165072165073165074165075165076165077165078165079165080165081165082165083165084165085165086165087165088165089165090165091165092165093165094165095165096165097165098165099165100165101165102165103165104165105165106165107165108165109165110165111165112165113165114165115165116165117165118165119165120165121165122165123165124165125165126165127165128165129165130165131165132165133165134165135165136165137165138165139165140165141165142165143165144165145165146165147165148165149165150165151165152165153165154165155165156165157165158165159165160165161165162165163165164165165165166165167165168165169165170165171165172165173165174165175165176165177165178165179165180165181165182165183165184165185165186165187165188165189165190165191165192165193165194165195165196165197165198165199165200165201165202165203165204165205165206165207165208165209165210165211165212165213165214165215165216165217165218165219165220165221165222165223165224165225165226165227165228165229165230165231165232165233165234165235165236165237165238165239165240165241165242165243165244165245165246165247165248165249165250165251165252165253165254165255165256165257165258165259165260165261165262165263165264165265165266165267165268165269165270165271165272165273165274165275165276165277165278165279165280165281165282165283165284165285165286165287165288165289165290165291165292165293165294165295165296165297165298165299165300165301165302165303165304165305165306165307165308165309165310165311165312165313165314165315165316165317165318165319165320165321165322165323165324165325165326165327165328165329165330165331165332165333165334165335165336165337165338165339165340165341165342165343165344165345165346165347165348165349165350165351165352165353165354165355165356165357165358165359165360165361165362165363165364165365165366165367165368165369165370165371165372165373165374165375165376165377165378165379165380165381165382165383165384165385165386165387165388165389165390165391165392165393165394165395165396165397165398165399165400165401165402165403165404165405165406165407165408165409165410165411165412165413165414165415165416165417165418165419165420165421165422165423165424165425165426165427165428165429165430165431165432165433165434165435165436165437165438165439165440165441165442165443165444165445165446165447165448165449165450165451165452165453165454165455165456165457165458165459165460165461165462165463165464165465165466165467165468165469165470165471165472165473165474165475165476165477165478165479165480165481165482165483165484165485165486165487165488165489165490165491165492165493165494165495165496165497165498165499165500165501165502165503165504165505165506165507165508165509165510165511165512165513165514165515165516165517165518165519165520165521165522165523165524165525165526165527165528165529165530165531165532165533165534165535165536165537165538165539165540165541165542165543165544165545165546165547165548165549165550165551165552165553165554165555165556165557165558165559165560165561165562165563165564165565165566165567165568165569165570165571165572165573165574165575165576165577165578165579165580165581165582165583165584165585165586165587165588165589165590165591165592165593165594165595165596165597165598165599165600165601165602165603165604165605165606165607165608165609165610165611165612165613165614165615165616165617165618165619165620165621165622165623165624165625165626165627165628165629165630165631165632165633165634165635165636165637165638165639165640165641165642165643165644165645165646165647165648165649165650165651165652165653165654165655165656165657165658165659165660165661165662165663165664165665165666165667165668165669165670165671165672165673165674165675165676165677165678165679165680165681165682165683165684165685165686165687165688165689165690165691165692165693165694165695165696165697165698165699165700165701165702165703165704165705165706165707165708165709165710165711165712165713165714165715165716165717165718165719165720165721165722165723165724165725165726165727165728165729165730165731165732165733165734165735165736165737165738165739165740165741165742165743165744165745165746165747165748165749165750165751165752165753165754165755165756165757165758165759165760165761165762165763165764165765165766165767165768165769165770165771165772165773165774165775165776165777165778165779165780165781165782165783165784165785165786165787165788165789165790165791165792165793165794165795165796165797165798165799165800165801165802165803165804165805165806165807165808165809165810165811165812165813165814165815165816165817165818165819165820165821165822165823165824165825165826165827165828165829165830165831165832165833165834165835165836165837165838165839165840165841165842165843165844165845165846165847165848165849165850165851165852165853165854165855165856165857165858165859165860165861165862165863165864165865165866165867165868165869165870165871165872165873165874165875165876165877165878165879165880165881165882165883165884165885165886165887165888165889165890165891165892165893165894165895165896165897165898165899165900165901165902165903165904165905165906165907165908165909165910165911165912165913165914165915165916165917165918165919165920165921165922165923165924165925165926165927165928165929165930165931165932165933165934165935165936165937165938165939165940165941165942165943165944165945165946165947165948165949165950165951165952165953165954165955165956165957165958165959165960165961165962165963165964165965165966165967165968165969165970165971165972165973165974165975165976165977165978165979165980165981165982165983165984165985165986165987165988165989165990165991165992165993165994165995165996165997165998165999166000166001166002166003166004166005166006166007166008166009166010166011166012166013166014166015166016166017166018166019166020166021166022166023166024166025166026166027166028166029166030166031166032166033166034166035166036166037166038166039166040166041166042166043166044166045166046166047166048166049166050166051166052166053166054166055166056166057166058166059166060166061166062166063166064166065166066166067166068166069166070166071166072166073166074166075166076166077166078166079166080166081166082166083166084166085166086166087166088166089166090166091166092166093166094166095166096166097166098166099166100166101166102166103166104166105166106166107166108166109166110166111166112166113166114166115166116166117166118166119166120166121166122166123166124166125166126166127166128166129166130166131166132166133166134166135166136166137166138166139166140166141166142166143166144166145166146166147166148166149166150166151166152166153166154166155166156166157166158166159166160166161166162166163166164166165166166166167166168166169166170166171166172166173166174166175166176166177166178166179166180166181166182166183166184166185166186166187166188166189166190166191166192166193166194166195166196166197166198166199166200166201166202166203166204166205166206166207166208166209166210166211166212166213166214166215166216166217166218166219166220166221166222166223166224166225166226166227166228166229166230166231166232166233166234166235166236166237166238166239166240166241166242166243166244166245166246166247166248166249166250166251166252166253166254166255166256166257166258166259166260166261166262166263166264166265166266166267166268166269166270166271166272166273166274166275166276166277166278166279166280166281166282166283166284166285166286166287166288166289166290166291166292166293166294166295166296166297166298166299166300166301166302166303166304166305166306166307166308166309166310166311166312166313166314166315166316166317166318166319166320166321166322166323166324166325166326166327166328166329166330166331166332166333166334166335166336166337166338166339166340166341166342166343166344166345166346166347166348166349166350166351166352166353166354166355166356166357166358166359166360166361166362166363166364166365166366166367166368166369166370166371166372166373166374166375166376166377166378166379166380166381166382166383166384166385166386166387166388166389166390166391166392166393166394166395166396166397166398166399166400166401166402166403166404166405166406166407166408166409166410166411166412166413166414166415166416166417166418166419166420166421166422166423166424166425166426166427166428166429166430166431166432166433166434166435166436166437166438166439166440166441166442166443166444166445166446166447166448166449166450166451166452166453166454166455166456166457166458166459166460166461166462166463166464166465166466166467166468166469166470166471166472166473166474166475166476166477166478166479166480166481166482166483166484166485166486166487166488166489166490166491166492166493166494166495166496166497166498166499166500166501166502166503166504166505166506166507166508166509166510166511166512166513166514166515166516166517166518166519166520166521166522166523166524166525166526166527166528166529166530166531166532166533166534166535166536166537166538166539166540166541166542166543166544166545166546166547166548166549166550166551166552166553166554166555166556166557166558166559166560166561166562166563166564166565166566166567166568166569166570166571166572166573166574166575166576166577166578166579166580166581166582166583166584166585166586166587166588166589166590166591166592166593166594166595166596166597166598166599166600166601166602166603166604166605166606166607166608166609166610166611166612166613166614166615166616166617166618166619166620166621166622166623166624166625166626166627166628166629166630166631166632166633166634166635166636166637166638166639166640166641166642166643166644166645166646166647166648166649166650166651166652166653166654166655166656166657166658166659166660166661166662166663166664166665166666166667166668166669166670166671166672166673166674166675166676166677166678166679166680166681166682166683166684166685166686166687166688166689166690166691166692166693166694166695166696166697166698166699166700166701166702166703166704166705166706166707166708166709166710166711166712166713166714166715166716166717166718166719166720166721166722166723166724166725166726166727166728166729166730166731166732166733166734166735166736166737166738166739166740166741166742166743166744166745166746166747166748166749166750166751166752166753166754166755166756166757166758166759166760166761166762166763166764166765166766166767166768166769166770166771166772166773166774166775166776166777166778166779166780166781166782166783166784166785166786166787166788166789166790166791166792166793166794166795166796166797166798166799166800166801166802166803166804166805166806166807166808166809166810166811166812166813166814166815166816166817166818166819166820166821166822166823166824166825166826166827166828166829166830166831166832166833166834166835166836166837166838166839166840166841166842166843166844166845166846166847166848166849166850166851166852166853166854166855166856166857166858166859166860166861166862166863166864166865166866166867166868166869166870166871166872166873166874166875166876166877166878166879166880166881166882166883166884166885166886166887166888166889166890166891166892166893166894166895166896166897166898166899166900166901166902166903166904166905166906166907166908166909166910166911166912166913166914166915166916166917166918166919166920166921166922166923166924166925166926166927166928166929166930166931166932166933166934166935166936166937166938166939166940166941166942166943166944166945166946166947166948166949166950166951166952166953166954166955166956166957166958166959166960166961166962166963166964166965166966166967166968166969166970166971166972166973166974166975166976166977166978166979166980166981166982166983166984166985166986166987166988166989166990166991166992166993166994166995166996166997166998166999167000167001167002167003167004167005167006167007167008167009167010167011167012167013167014167015167016167017167018167019167020167021167022167023167024167025167026167027167028167029167030167031167032167033167034167035167036167037167038167039167040167041167042167043167044167045167046167047167048167049167050167051167052167053167054167055167056167057167058167059167060167061167062167063167064167065167066167067167068167069167070167071167072167073167074167075167076167077167078167079167080167081167082167083167084167085167086167087167088167089167090167091167092167093167094167095167096167097167098167099167100167101167102167103167104167105167106167107167108167109167110167111167112167113167114167115167116167117167118167119167120167121167122167123167124167125167126167127167128167129167130167131167132167133167134167135167136167137167138167139167140167141167142167143167144167145167146167147167148167149167150167151167152167153167154167155167156167157167158167159167160167161167162167163167164167165167166167167167168167169167170167171167172167173167174167175167176167177167178167179167180167181167182167183167184167185167186167187167188167189167190167191167192167193167194167195167196167197167198167199167200167201167202167203167204167205167206167207167208167209167210167211167212167213167214167215167216167217167218167219167220167221167222167223167224167225167226167227167228167229167230167231167232167233167234167235167236167237167238167239167240167241167242167243167244167245167246167247167248167249167250167251167252167253167254167255167256167257167258167259167260167261167262167263167264167265167266167267167268167269167270167271167272167273167274167275167276167277167278167279167280167281167282167283167284167285167286167287167288167289167290167291167292167293167294167295167296167297167298167299167300167301167302167303167304167305167306167307167308167309167310167311167312167313167314167315167316167317167318167319167320167321167322167323167324167325167326167327167328167329167330167331167332167333167334167335167336167337167338167339167340167341167342167343167344167345167346167347167348167349167350167351167352167353167354167355167356167357167358167359167360167361167362167363167364167365167366167367167368167369167370167371167372167373167374167375167376167377167378167379167380167381167382167383167384167385167386167387167388167389167390167391167392167393167394167395167396167397167398167399167400167401167402167403167404167405167406167407167408167409167410167411167412167413167414167415167416167417167418167419167420167421167422167423167424167425167426167427167428167429167430167431167432167433167434167435167436167437167438167439167440167441167442167443167444167445167446167447167448167449167450167451167452167453167454167455167456167457167458167459167460167461167462167463167464167465167466167467167468167469167470167471167472167473167474167475167476167477167478167479167480167481167482167483167484167485167486167487167488167489167490167491167492167493167494167495167496167497167498167499167500167501167502167503167504167505167506167507167508167509167510167511167512167513167514167515167516167517167518167519167520167521167522167523167524167525167526167527167528167529167530167531167532167533167534167535167536167537167538167539167540167541167542167543167544167545167546167547167548167549167550167551167552167553167554167555167556167557167558167559167560167561167562167563167564167565167566167567167568167569167570167571167572167573167574167575167576167577167578167579167580167581167582167583167584167585167586167587167588167589167590167591167592167593167594167595167596167597167598167599167600167601167602167603167604167605167606167607167608167609167610167611167612167613167614167615167616167617167618167619167620167621167622167623167624167625167626167627167628167629167630167631167632167633167634167635167636167637167638167639167640167641167642167643167644167645167646167647167648167649167650167651167652167653167654167655167656167657167658167659167660167661167662167663167664167665167666167667167668167669167670167671167672167673167674167675167676167677167678167679167680167681167682167683167684167685167686167687167688167689167690167691167692167693167694167695167696167697167698167699167700167701167702167703167704167705167706167707167708167709167710167711167712167713167714167715167716167717167718167719167720167721167722167723167724167725167726167727167728167729167730167731167732167733167734167735167736167737167738167739167740167741167742167743167744167745167746167747167748167749167750167751167752167753167754167755167756167757167758167759167760167761167762167763167764167765167766167767167768167769167770167771167772167773167774167775167776167777167778167779167780167781167782167783167784167785167786167787167788167789167790167791167792167793167794167795167796167797167798167799167800167801167802167803167804167805167806167807167808167809167810167811167812167813167814167815167816167817167818167819167820167821167822167823167824167825167826167827167828167829167830167831167832167833167834167835167836167837167838167839167840167841167842167843167844167845167846167847167848167849167850167851167852167853167854167855167856167857167858167859167860167861167862167863167864167865167866167867167868167869167870167871167872167873167874167875167876167877167878167879167880167881167882167883167884167885167886167887167888167889167890167891167892167893167894167895167896167897167898167899167900167901167902167903167904167905167906167907167908167909167910167911167912167913167914167915167916167917167918167919167920167921167922167923167924167925167926167927167928167929167930167931167932167933167934167935167936167937167938167939167940167941167942167943167944167945167946167947167948167949167950167951167952167953167954167955167956167957167958167959167960167961167962167963167964167965167966167967167968167969167970167971167972167973167974167975167976167977167978167979167980167981167982167983167984167985167986167987167988167989167990167991167992167993167994167995167996167997167998167999168000168001168002168003168004168005168006168007168008168009168010168011168012168013168014168015168016168017168018168019168020168021168022168023168024168025168026168027168028168029168030168031168032168033168034168035168036168037168038168039168040168041168042168043168044168045168046168047168048168049168050168051168052168053168054168055168056168057168058168059168060168061168062168063168064168065168066168067168068168069168070168071168072168073168074168075168076168077168078168079168080168081168082168083168084168085168086168087168088168089168090168091168092168093168094168095168096168097168098168099168100168101168102168103168104168105168106168107168108168109168110168111168112168113168114168115168116168117168118168119168120168121168122168123168124168125168126168127168128168129168130168131168132168133168134168135168136168137168138168139168140168141168142168143168144168145168146168147168148168149168150168151168152168153168154168155168156168157168158168159168160168161168162168163168164168165168166168167168168168169168170168171168172168173168174168175168176168177168178168179168180168181168182168183168184168185168186168187168188168189168190168191168192168193168194168195168196168197168198168199168200168201168202168203168204168205168206168207168208168209168210168211168212168213168214168215168216168217168218168219168220168221168222168223168224168225168226168227168228168229168230168231168232168233168234168235168236168237168238168239168240168241168242168243168244168245168246168247168248168249168250168251168252168253168254168255168256168257168258168259168260168261168262168263168264168265168266168267168268168269168270168271168272168273168274168275168276168277168278168279168280168281168282168283168284168285168286168287168288168289168290168291168292168293168294168295168296168297168298168299168300168301168302168303168304168305168306168307168308168309168310168311168312168313168314168315168316168317168318168319168320168321168322168323168324168325168326168327168328168329168330168331168332168333168334168335168336168337168338168339168340168341168342168343168344168345168346168347168348168349168350168351168352168353168354168355168356168357168358168359168360168361168362168363168364168365168366168367168368168369168370168371168372168373168374168375168376168377168378168379168380168381168382168383168384168385168386168387168388168389168390168391168392168393168394168395168396168397168398168399168400168401168402168403168404168405168406168407168408168409168410168411168412168413168414168415168416168417168418168419168420168421168422168423168424168425168426168427168428168429168430168431168432168433168434168435168436168437168438168439168440168441168442168443168444168445168446168447168448168449168450168451168452168453168454168455168456168457168458168459168460168461168462168463168464168465168466168467168468168469168470168471168472168473168474168475168476168477168478168479168480168481168482168483168484168485168486168487168488168489168490168491168492168493168494168495168496168497168498168499168500168501168502168503168504168505168506168507168508168509168510168511168512168513168514168515168516168517168518168519168520168521168522168523168524168525168526168527168528168529168530168531168532168533168534168535168536168537168538168539168540168541168542168543168544168545168546168547168548168549168550168551168552168553168554168555168556168557168558168559168560168561168562168563168564168565168566168567168568168569168570168571168572168573168574168575168576168577168578168579168580168581168582168583168584168585168586168587168588168589168590168591168592168593168594168595168596168597168598168599168600168601168602168603168604168605168606168607168608168609168610168611168612168613168614168615168616168617168618168619168620168621168622168623168624168625168626168627168628168629168630168631168632168633168634168635168636168637168638168639168640168641168642168643168644168645168646168647168648168649168650168651168652168653168654168655168656168657168658168659168660168661168662168663168664168665168666168667168668168669168670168671168672168673168674168675168676168677168678168679168680168681168682168683168684168685168686168687168688168689168690168691168692168693168694168695168696168697168698168699168700168701168702168703168704168705168706168707168708168709168710168711168712168713168714168715168716168717168718168719168720168721168722168723168724168725168726168727168728168729168730168731168732168733168734168735168736168737168738168739168740168741168742168743168744168745168746168747168748168749168750168751168752168753168754168755168756168757168758168759168760168761168762168763168764168765168766168767168768168769168770168771168772168773168774168775168776168777168778168779168780168781168782168783168784168785168786168787168788168789168790168791168792168793168794168795168796168797168798168799168800168801168802168803168804168805168806168807168808168809168810168811168812168813168814168815168816168817168818168819168820168821168822168823168824168825168826168827168828168829168830168831168832168833168834168835168836168837168838168839168840168841168842168843168844168845168846168847168848168849168850168851168852168853168854168855168856168857168858168859168860168861168862168863168864168865168866168867168868168869168870168871168872168873168874168875168876168877168878168879168880168881168882168883168884168885168886168887168888168889168890168891168892168893168894168895168896168897168898168899168900168901168902168903168904168905168906168907168908168909168910168911168912168913168914168915168916168917168918168919168920168921168922168923168924168925168926168927168928168929168930168931168932168933168934168935168936168937168938168939168940168941168942168943168944168945168946168947168948168949168950168951168952168953168954168955168956168957168958168959168960168961168962168963168964168965168966168967168968168969168970168971168972168973168974168975168976168977168978168979168980168981168982168983168984168985168986168987168988168989168990168991168992168993168994168995168996168997168998168999169000169001169002169003169004169005169006169007169008169009169010169011169012169013169014169015169016169017169018169019169020169021169022169023169024169025169026169027169028169029169030169031169032169033169034169035169036169037169038169039169040169041169042169043169044169045169046169047169048169049169050169051169052169053169054169055169056169057169058169059169060169061169062169063169064169065169066169067169068169069169070169071169072169073169074169075169076169077169078169079169080169081169082169083169084169085169086169087169088169089169090169091169092169093169094169095169096169097169098169099169100169101169102169103169104169105169106169107169108169109169110169111169112169113169114169115169116169117169118169119169120169121169122169123169124169125169126169127169128169129169130169131169132169133169134169135169136169137169138169139169140169141169142169143169144169145169146169147169148169149169150169151169152169153169154169155169156169157169158169159169160169161169162169163169164169165169166169167169168169169169170169171169172169173169174169175169176169177169178169179169180169181169182169183169184169185169186169187169188169189169190169191169192169193169194169195169196169197169198169199169200169201169202169203169204169205169206169207169208169209169210169211169212169213169214169215169216169217169218169219169220169221169222169223169224169225169226169227169228169229169230169231169232169233169234169235169236169237169238169239169240169241169242169243169244169245169246169247169248169249169250169251169252169253169254169255169256169257169258169259169260169261169262169263169264169265169266169267169268169269169270169271169272169273169274169275169276169277169278169279169280169281169282169283169284169285169286169287169288169289169290169291169292169293169294169295169296169297169298169299169300169301169302169303169304169305169306169307169308169309169310169311169312169313169314169315169316169317169318169319169320169321169322169323169324169325169326169327169328169329169330169331169332169333169334169335169336169337169338169339169340169341169342169343169344169345169346169347169348169349169350169351169352169353169354169355169356169357169358169359169360169361169362169363169364169365169366169367169368169369169370169371169372169373169374169375169376169377169378169379169380169381169382169383169384169385169386169387169388169389169390169391169392169393169394169395169396169397169398169399169400169401169402169403169404169405169406169407169408169409169410169411169412169413169414169415169416169417169418169419169420169421169422169423169424169425169426169427169428169429169430169431169432169433169434169435169436169437169438169439169440169441169442169443169444169445169446169447169448169449169450169451169452169453169454169455169456169457169458169459169460169461169462169463169464169465169466169467169468169469169470169471169472169473169474169475169476169477169478169479169480169481169482169483169484169485169486169487169488169489169490169491169492169493169494169495169496169497169498169499169500169501169502169503169504169505169506169507169508169509169510169511169512169513169514169515169516169517169518169519169520169521169522169523169524169525169526169527169528169529169530169531169532169533169534169535169536169537169538169539169540169541169542169543169544169545169546169547169548169549169550169551169552169553169554169555169556169557169558169559169560169561169562169563169564169565169566169567169568169569169570169571169572169573169574169575169576169577169578169579169580169581169582169583169584169585169586169587169588169589169590169591169592169593169594169595169596169597169598169599169600169601169602169603169604169605169606169607169608169609169610169611169612169613169614169615169616169617169618169619169620169621169622169623169624169625169626169627169628169629169630169631169632169633169634169635169636169637169638169639169640169641169642169643169644169645169646169647169648169649169650169651169652169653169654169655169656169657169658169659169660169661169662169663169664169665169666169667169668169669169670169671169672169673169674169675169676169677169678169679169680169681169682169683169684169685169686169687169688169689169690169691169692169693169694169695169696169697169698169699169700169701169702169703169704169705169706169707169708169709169710169711169712169713169714169715169716169717169718169719169720169721169722169723169724169725169726169727169728169729169730169731169732169733169734169735169736169737169738169739169740169741169742169743169744169745169746169747169748169749169750169751169752169753169754169755169756169757169758169759169760169761169762169763169764169765169766169767169768169769169770169771169772169773169774169775169776169777169778169779169780169781169782169783169784169785169786169787169788169789169790169791169792169793169794169795169796169797169798169799169800169801169802169803169804169805169806169807169808169809169810169811169812169813169814169815169816169817169818169819169820169821169822169823169824169825169826169827169828169829169830169831169832169833169834169835169836169837169838169839169840169841169842169843169844169845169846169847169848169849169850169851169852169853169854169855169856169857169858169859169860169861169862169863169864169865169866169867169868169869169870169871169872169873169874169875169876169877169878169879169880169881169882169883169884169885169886169887169888169889169890169891169892169893169894169895169896169897169898169899169900169901169902169903169904169905169906169907169908169909169910169911169912169913169914169915169916169917169918169919169920169921169922169923169924169925169926169927169928169929169930169931169932169933169934169935169936169937169938169939169940169941169942169943169944169945169946169947169948169949169950169951169952169953169954169955169956169957169958169959169960169961169962169963169964169965169966169967169968169969169970169971169972169973169974169975169976169977169978169979169980169981169982169983169984169985169986169987169988169989169990169991169992169993169994169995169996169997169998169999170000170001170002170003170004170005170006170007170008170009170010170011170012170013170014170015170016170017170018170019170020170021170022170023170024170025170026170027170028170029170030170031170032170033170034170035170036170037170038170039170040170041170042170043170044170045170046170047170048170049170050170051170052170053170054170055170056170057170058170059170060170061170062170063170064170065170066170067170068170069170070170071170072170073170074170075170076170077170078170079170080170081170082170083170084170085170086170087170088170089170090170091170092170093170094170095170096170097170098170099170100170101170102170103170104170105170106170107170108170109170110170111170112170113170114170115170116170117170118170119170120170121170122170123170124170125170126170127170128170129170130170131170132170133170134170135170136170137170138170139170140170141170142170143170144170145170146170147170148170149170150170151170152170153170154170155170156170157170158170159170160170161170162170163170164170165170166170167170168170169170170170171170172170173170174170175170176170177170178170179170180170181170182170183170184170185170186170187170188170189170190170191170192170193170194170195170196170197170198170199170200170201170202170203170204170205170206170207170208170209170210170211170212170213170214170215170216170217170218170219170220170221170222170223170224170225170226170227170228170229170230170231170232170233170234170235170236170237170238170239170240170241170242170243170244170245170246170247170248170249170250170251170252170253170254170255170256170257170258170259170260170261170262170263170264170265170266170267170268170269170270170271170272170273170274170275170276170277170278170279170280170281170282170283170284170285170286170287170288170289170290170291170292170293170294170295170296170297170298170299170300170301170302170303170304170305170306170307170308170309170310170311170312170313170314170315170316170317170318170319170320170321170322170323170324170325170326170327170328170329170330170331170332170333170334170335170336170337170338170339170340170341170342170343170344170345170346170347170348170349170350170351170352170353170354170355170356170357170358170359170360170361170362170363170364170365170366170367170368170369170370170371170372170373170374170375170376170377170378170379170380170381170382170383170384170385170386170387170388170389170390170391170392170393170394170395170396170397170398170399170400170401170402170403170404170405170406170407170408170409170410170411170412170413170414170415170416170417170418170419170420170421170422170423170424170425170426170427170428170429170430170431170432170433170434170435170436170437170438170439170440170441170442170443170444170445170446170447170448170449170450170451170452170453170454170455170456170457170458170459170460170461170462170463170464170465170466170467170468170469170470170471170472170473170474170475170476170477170478170479170480170481170482170483170484170485170486170487170488170489170490170491170492170493170494170495170496170497170498170499170500170501170502170503170504170505170506170507170508170509170510170511170512170513170514170515170516170517170518170519170520170521170522170523170524170525170526170527170528170529170530170531170532170533170534170535170536170537170538170539170540170541170542170543170544170545170546170547170548170549170550170551170552170553170554170555170556170557170558170559170560170561170562170563170564170565170566170567170568170569170570170571170572170573170574170575170576170577170578170579170580170581170582170583170584170585170586170587170588170589170590170591170592170593170594170595170596170597170598170599170600170601170602170603170604170605170606170607170608170609170610170611170612170613170614170615170616170617170618170619170620170621170622170623170624170625170626170627170628170629170630170631170632170633170634170635170636170637170638170639170640170641170642170643170644170645170646170647170648170649170650170651170652170653170654170655170656170657170658170659170660170661170662170663170664170665170666170667170668170669170670170671170672170673170674170675170676170677170678170679170680170681170682170683170684170685170686170687170688170689170690170691170692170693170694170695170696170697170698170699170700170701170702170703170704170705170706170707170708170709170710170711170712170713170714170715170716170717170718170719170720170721170722170723170724170725170726170727170728170729170730170731170732170733170734170735170736170737170738170739170740170741170742170743170744170745170746170747170748170749170750170751170752170753170754170755170756170757170758170759170760170761170762170763170764170765170766170767170768170769170770170771170772170773170774170775170776170777170778170779170780170781170782170783170784170785170786170787170788170789170790170791170792170793170794170795170796170797170798170799170800170801170802170803170804170805170806170807170808170809170810170811170812170813170814170815170816170817170818170819170820170821170822170823170824170825170826170827170828170829170830170831170832170833170834170835170836170837170838170839170840170841170842170843170844170845170846170847170848170849170850170851170852170853170854170855170856170857170858170859170860170861170862170863170864170865170866170867170868170869170870170871170872170873170874170875170876170877170878170879170880170881170882170883170884170885170886170887170888170889170890170891170892170893170894170895170896170897170898170899170900170901170902170903170904170905170906170907170908170909170910170911170912170913170914170915170916170917170918170919170920170921170922170923170924170925170926170927170928170929170930170931170932170933170934170935170936170937170938170939170940170941170942170943170944170945170946170947170948170949170950170951170952170953170954170955170956170957170958170959170960170961170962170963170964170965170966170967170968170969170970170971170972170973170974170975170976170977170978170979170980170981170982170983170984170985170986170987170988170989170990170991170992170993170994170995170996170997170998170999171000171001171002171003171004171005171006171007171008171009171010171011171012171013171014171015171016171017171018171019171020171021171022171023171024171025171026171027171028171029171030171031171032171033171034171035171036171037171038171039171040171041171042171043171044171045171046171047171048171049171050171051171052171053171054171055171056171057171058171059171060171061171062171063171064171065171066171067171068171069171070171071171072171073171074171075171076171077171078171079171080171081171082171083171084171085171086171087171088171089171090171091171092171093171094171095171096171097171098171099171100171101171102171103171104171105171106171107171108171109171110171111171112171113171114171115171116171117171118171119171120171121171122171123171124171125171126171127171128171129171130171131171132171133171134171135171136171137171138171139171140171141171142171143171144171145171146171147171148171149171150171151171152171153171154171155171156171157171158171159171160171161171162171163171164171165171166171167171168171169171170171171171172171173171174171175171176171177171178171179171180171181171182171183171184171185171186171187171188171189171190171191171192171193171194171195171196171197171198171199171200171201171202171203171204171205171206171207171208171209171210171211171212171213171214171215171216171217171218171219171220171221171222171223171224171225171226171227171228171229171230171231171232171233171234171235171236171237171238171239171240171241171242171243171244171245171246171247171248171249171250171251171252171253171254171255171256171257171258171259171260171261171262171263171264171265171266171267171268171269171270171271171272171273171274171275171276171277171278171279171280171281171282171283171284171285171286171287171288171289171290171291171292171293171294171295171296171297171298171299171300171301171302171303171304171305171306171307171308171309171310171311171312171313171314171315171316171317171318171319171320171321171322171323171324171325171326171327171328171329171330171331171332171333171334171335171336171337171338171339171340171341171342171343171344171345171346171347171348171349171350171351171352171353171354171355171356171357171358171359171360171361171362171363171364171365171366171367171368171369171370171371171372171373171374171375171376171377171378171379171380171381171382171383171384171385171386171387171388171389171390171391171392171393171394171395171396171397171398171399171400171401171402171403171404171405171406171407171408171409171410171411171412171413171414171415171416171417171418171419171420171421171422171423171424171425171426171427171428171429171430171431171432171433171434171435171436171437171438171439171440171441171442171443171444171445171446171447171448171449171450171451171452171453171454171455171456171457171458171459171460171461171462171463171464171465171466171467171468171469171470171471171472171473171474171475171476171477171478171479171480171481171482171483171484171485171486171487171488171489171490171491171492171493171494171495171496171497171498171499171500171501171502171503171504171505171506171507171508171509171510171511171512171513171514171515171516171517171518171519171520171521171522171523171524171525171526171527171528171529171530171531171532171533171534171535171536171537171538171539171540171541171542171543171544171545171546171547171548171549171550171551171552171553171554171555171556171557171558171559171560171561171562171563171564171565171566171567171568171569171570171571171572171573171574171575171576171577171578171579171580171581171582171583171584171585171586171587171588171589171590171591171592171593171594171595171596171597171598171599171600171601171602171603171604171605171606171607171608171609171610171611171612171613171614171615171616171617171618171619171620171621171622171623171624171625171626171627171628171629171630171631171632171633171634171635171636171637171638171639171640171641171642171643171644171645171646171647171648171649171650171651171652171653171654171655171656171657171658171659171660171661171662171663171664171665171666171667171668171669171670171671171672171673171674171675171676171677171678171679171680171681171682171683171684171685171686171687171688171689171690171691171692171693171694171695171696171697171698171699171700171701171702171703171704171705171706171707171708171709171710171711171712171713171714171715171716171717171718171719171720171721171722171723171724171725171726171727171728171729171730171731171732171733171734171735171736171737171738171739171740171741171742171743171744171745171746171747171748171749171750171751171752171753171754171755171756171757171758171759171760171761171762171763171764171765171766171767171768171769171770171771171772171773171774171775171776171777171778171779171780171781171782171783171784171785171786171787171788171789171790171791171792171793171794171795171796171797171798171799171800171801171802171803171804171805171806171807171808171809171810171811171812171813171814171815171816171817171818171819171820171821171822171823171824171825171826171827171828171829171830171831171832171833171834171835171836171837171838171839171840171841171842171843171844171845171846171847171848171849171850171851171852171853171854171855171856171857171858171859171860171861171862171863171864171865171866171867171868171869171870171871171872171873171874171875171876171877171878171879171880171881171882171883171884171885171886171887171888171889171890171891171892171893171894171895171896171897171898171899171900171901171902171903171904171905171906171907171908171909171910171911171912171913171914171915171916171917171918171919171920171921171922171923171924171925171926171927171928171929171930171931171932171933171934171935171936171937171938171939171940171941171942171943171944171945171946171947171948171949171950171951171952171953171954171955171956171957171958171959171960171961171962171963171964171965171966171967171968171969171970171971171972171973171974171975171976171977171978171979171980171981171982171983171984171985171986171987171988171989171990171991171992171993171994171995171996171997171998171999172000172001172002172003172004172005172006172007172008172009172010172011172012172013172014172015172016172017172018172019172020172021172022172023172024172025172026172027172028172029172030172031172032172033172034172035172036172037172038172039172040172041172042172043172044172045172046172047172048172049172050172051172052172053172054172055172056172057172058172059172060172061172062172063172064172065172066172067172068172069172070172071172072172073172074172075172076172077172078172079172080172081172082172083172084172085172086172087172088172089172090172091172092172093172094172095172096172097172098172099172100172101172102172103172104172105172106172107172108172109172110172111172112172113172114172115172116172117172118172119172120172121172122172123172124172125172126172127172128172129172130172131172132172133172134172135172136172137172138172139172140172141172142172143172144172145172146172147172148172149172150172151172152172153172154172155172156172157172158172159172160172161172162172163172164172165172166172167172168172169172170172171172172172173172174172175172176172177172178172179172180172181172182172183172184172185172186172187172188172189172190172191172192172193172194172195172196172197172198172199172200172201172202172203172204172205172206172207172208172209172210172211172212172213172214172215172216172217172218172219172220172221172222172223172224172225172226172227172228172229172230172231172232172233172234172235172236172237172238172239172240172241172242172243172244172245172246172247172248172249172250172251172252172253172254172255172256172257172258172259172260172261172262172263172264172265172266172267172268172269172270172271172272172273172274172275172276172277172278172279172280172281172282172283172284172285172286172287172288172289172290172291172292172293172294172295172296172297172298172299172300172301172302172303172304172305172306172307172308172309172310172311172312172313172314172315172316172317172318172319172320172321172322172323172324172325172326172327172328172329172330172331172332172333172334172335172336172337172338172339172340172341172342172343172344172345172346172347172348172349172350172351172352172353172354172355172356172357172358172359172360172361172362172363172364172365172366172367172368172369172370172371172372172373172374172375172376172377172378172379172380172381172382172383172384172385172386172387172388172389172390172391172392172393172394172395172396172397172398172399172400172401172402172403172404172405172406172407172408172409172410172411172412172413172414172415172416172417172418172419172420172421172422172423172424172425172426172427172428172429172430172431172432172433172434172435172436172437172438172439172440172441172442172443172444172445172446172447172448172449172450172451172452172453172454172455172456172457172458172459172460172461172462172463172464172465172466172467172468172469172470172471172472172473172474172475172476172477172478172479172480172481172482172483172484172485172486172487172488172489172490172491172492172493172494172495172496172497172498172499172500172501172502172503172504172505172506172507172508172509172510172511172512172513172514172515172516172517172518172519172520172521172522172523172524172525172526172527172528172529172530172531172532172533172534172535172536172537172538172539172540172541172542172543172544172545172546172547172548172549172550172551172552172553172554172555172556172557172558172559172560172561172562172563172564172565172566172567172568172569172570172571172572172573172574172575172576172577172578172579172580172581172582172583172584172585172586172587172588172589172590172591172592172593172594172595172596172597172598172599172600172601172602172603172604172605172606172607172608172609172610172611172612172613172614172615172616172617172618172619172620172621172622172623172624172625172626172627172628172629172630172631172632172633172634172635172636172637172638172639172640172641172642172643172644172645172646172647172648172649172650172651172652172653172654172655172656172657172658172659172660172661172662172663172664172665172666172667172668172669172670172671172672172673172674172675172676172677172678172679172680172681172682172683172684172685172686172687172688172689172690172691172692172693172694172695172696172697172698172699172700172701172702172703172704172705172706172707172708172709172710172711172712172713172714172715172716172717172718172719172720172721172722172723172724172725172726172727172728172729172730172731172732172733172734172735172736172737172738172739172740172741172742172743172744172745172746172747172748172749172750172751172752172753172754172755172756172757172758172759172760172761172762172763172764172765172766172767172768172769172770172771172772172773172774172775172776172777172778172779172780172781172782172783172784172785172786172787172788172789172790172791172792172793172794172795172796172797172798172799172800172801172802172803172804172805172806172807172808172809172810172811172812172813172814172815172816172817172818172819172820172821172822172823172824172825172826172827172828172829172830172831172832172833172834172835172836172837172838172839172840172841172842172843172844172845172846172847172848172849172850172851172852172853172854172855172856172857172858172859172860172861172862172863172864172865172866172867172868172869172870172871172872172873172874172875172876172877172878172879172880172881172882172883172884172885172886172887172888172889172890172891172892172893172894172895172896172897172898172899172900172901172902172903172904172905172906172907172908172909172910172911172912172913172914172915172916172917172918172919172920172921172922172923172924172925172926172927172928172929172930172931172932172933172934172935172936172937172938172939172940172941172942172943172944172945172946172947172948172949172950172951172952172953172954172955172956172957172958172959172960172961172962172963172964172965172966172967172968172969172970172971172972172973172974172975172976172977172978172979172980172981172982172983172984172985172986172987172988172989172990172991172992172993172994172995172996172997172998172999173000173001173002173003173004173005173006173007173008173009173010173011173012173013173014173015173016173017173018173019173020173021173022173023173024173025173026173027173028173029173030173031173032173033173034173035173036173037173038173039173040173041173042173043173044173045173046173047173048173049173050173051173052173053173054173055173056173057173058173059173060173061173062173063173064173065173066173067173068173069173070173071173072173073173074173075173076173077173078173079173080173081173082173083173084173085173086173087173088173089173090173091173092173093173094173095173096173097173098173099173100173101173102173103173104173105173106173107173108173109173110173111173112173113173114173115173116173117173118173119173120173121173122173123173124173125173126173127173128173129173130173131173132173133173134173135173136173137173138173139173140173141173142173143173144173145173146173147173148173149173150173151173152173153173154173155173156173157173158173159173160173161173162173163173164173165173166173167173168173169173170173171173172173173173174173175173176173177173178173179173180173181173182173183173184173185173186173187173188173189173190173191173192173193173194173195173196173197173198173199173200173201173202173203173204173205173206173207173208173209173210173211173212173213173214173215173216173217173218173219173220173221173222173223173224173225173226173227173228173229173230173231173232173233173234173235173236173237173238173239173240173241173242173243173244173245173246173247173248173249173250173251173252173253173254173255173256173257173258173259173260173261173262173263173264173265173266173267173268173269173270173271173272173273173274173275173276173277173278173279173280173281173282173283173284173285173286173287173288173289173290173291173292173293173294173295173296173297173298173299173300173301173302173303173304173305173306173307173308173309173310173311173312173313173314173315173316173317173318173319173320173321173322173323173324173325173326173327173328173329173330173331173332173333173334173335173336173337173338173339173340173341173342173343173344173345173346173347173348173349173350173351173352173353173354173355173356173357173358173359173360173361173362173363173364173365173366173367173368173369173370173371173372173373173374173375173376173377173378173379173380173381173382173383173384173385173386173387173388173389173390173391173392173393173394173395173396173397173398173399173400173401173402173403173404173405173406173407173408173409173410173411173412173413173414173415173416173417173418173419173420173421173422173423173424173425173426173427173428173429173430173431173432173433173434173435173436173437173438173439173440173441173442173443173444173445173446173447173448173449173450173451173452173453173454173455173456173457173458173459173460173461173462173463173464173465173466173467173468173469173470173471173472173473173474173475173476173477173478173479173480173481173482173483173484173485173486173487173488173489173490173491173492173493173494173495173496173497173498173499173500173501173502173503173504173505173506173507173508173509173510173511173512173513173514173515173516173517173518173519173520173521173522173523173524173525173526173527173528173529173530173531173532173533173534173535173536173537173538173539173540173541173542173543173544173545173546173547173548173549173550173551173552173553173554173555173556173557173558173559173560173561173562173563173564173565173566173567173568173569173570173571173572173573173574173575173576173577173578173579173580173581173582173583173584173585173586173587173588173589173590173591173592173593173594173595173596173597173598173599173600173601173602173603173604173605173606173607173608173609173610173611173612173613173614173615173616173617173618173619173620173621173622173623173624173625173626173627173628173629173630173631173632173633173634173635173636173637173638173639173640173641173642173643173644173645173646173647173648173649173650173651173652173653173654173655173656173657173658173659173660173661173662173663173664173665173666173667173668173669173670173671173672173673173674173675173676173677173678173679173680173681173682173683173684173685173686173687173688173689173690173691173692173693173694173695173696173697173698173699173700173701173702173703173704173705173706173707173708173709173710173711173712173713173714173715173716173717173718173719173720173721173722173723173724173725173726173727173728173729173730173731173732173733173734173735173736173737173738173739173740173741173742173743173744173745173746173747173748173749173750173751173752173753173754173755173756173757173758173759173760173761173762173763173764173765173766173767173768173769173770173771173772173773173774173775173776173777173778173779173780173781173782173783173784173785173786173787173788173789173790173791173792173793173794173795173796173797173798173799173800173801173802173803173804173805173806173807173808173809173810173811173812173813173814173815173816173817173818173819173820173821173822173823173824173825173826173827173828173829173830173831173832173833173834173835173836173837173838173839173840173841173842173843173844173845173846173847173848173849173850173851173852173853173854173855173856173857173858173859173860173861173862173863173864173865173866173867173868173869173870173871173872173873173874173875173876173877173878173879173880173881173882173883173884173885173886173887173888173889173890173891173892173893173894173895173896173897173898173899173900173901173902173903173904173905173906173907173908173909173910173911173912173913173914173915173916173917173918173919173920173921173922173923173924173925173926173927173928173929173930173931173932173933173934173935173936173937173938173939173940173941173942173943173944173945173946173947173948173949173950173951173952173953173954173955173956173957173958173959173960173961173962173963173964173965173966173967173968173969173970173971173972173973173974173975173976173977173978173979173980173981173982173983173984173985173986173987173988173989173990173991173992173993173994173995173996173997173998173999174000174001174002174003174004174005174006174007174008174009174010174011174012174013174014174015174016174017174018174019174020174021174022174023174024174025174026174027174028174029174030174031174032174033174034174035174036174037174038174039174040174041174042174043174044174045174046174047174048174049174050174051174052174053174054174055174056174057174058174059174060174061174062174063174064174065174066174067174068174069174070174071174072174073174074174075174076174077174078174079174080174081174082174083174084174085174086174087174088174089174090174091174092174093174094174095174096174097174098174099174100174101174102174103174104174105174106174107174108174109174110174111174112174113174114174115174116174117174118174119174120174121174122174123174124174125174126174127174128174129174130174131174132174133174134174135174136174137174138174139174140174141174142174143174144174145174146174147174148174149174150174151174152174153174154174155174156174157174158174159174160174161174162174163174164174165174166174167174168174169174170174171174172174173174174174175174176174177174178174179174180174181174182174183174184174185174186174187174188174189174190174191174192174193174194174195174196174197174198174199174200174201174202174203174204174205174206174207174208174209174210174211174212174213174214174215174216174217174218174219174220174221174222174223174224174225174226174227174228174229174230174231174232174233174234174235174236174237174238174239174240174241174242174243174244174245174246174247174248174249174250174251174252174253174254174255174256174257174258174259174260174261174262174263174264174265174266174267174268174269174270174271174272174273174274174275174276174277174278174279174280174281174282174283174284174285174286174287174288174289174290174291174292174293174294174295174296174297174298174299174300174301174302174303174304174305174306174307174308174309174310174311174312174313174314174315174316174317174318174319174320174321174322174323174324174325174326174327174328174329174330174331174332174333174334174335174336174337174338174339174340174341174342174343174344174345174346174347174348174349174350174351174352174353174354174355174356174357174358174359174360174361174362174363174364174365174366174367174368174369174370174371174372174373174374174375174376174377174378174379174380174381174382174383174384174385174386174387174388174389174390174391174392174393174394174395174396174397174398174399174400174401174402174403174404174405174406174407174408174409174410174411174412174413174414174415174416174417174418174419174420174421174422174423174424174425174426174427174428174429174430174431174432174433174434174435174436174437174438174439174440174441174442174443174444174445174446174447174448174449174450174451174452174453174454174455174456174457174458174459174460174461174462174463174464174465174466174467174468174469174470174471174472174473174474174475174476174477174478174479174480174481174482174483174484174485174486174487174488174489174490174491174492174493174494174495174496174497174498174499174500174501174502174503174504174505174506174507174508174509174510174511174512174513174514174515174516174517174518174519174520174521174522174523174524174525174526174527174528174529174530174531174532174533174534174535174536174537174538174539174540174541174542174543174544174545174546174547174548174549174550174551174552174553174554174555174556174557174558174559174560174561174562174563174564174565174566174567174568174569174570174571174572174573174574174575174576174577174578174579174580174581174582174583174584174585174586174587174588174589174590174591174592174593174594174595174596174597174598174599174600174601174602174603174604174605174606174607174608174609174610174611174612174613174614174615174616174617174618174619174620174621174622174623174624174625174626174627174628174629174630174631174632174633174634174635174636174637174638174639174640174641174642174643174644174645174646174647174648174649174650174651174652174653174654174655174656174657174658174659174660174661174662174663174664174665174666174667174668174669174670174671174672174673174674174675174676174677174678174679174680174681174682174683174684174685174686174687174688174689174690174691174692174693174694174695174696174697174698174699174700174701174702174703174704174705174706174707174708174709174710174711174712174713174714174715174716174717174718174719174720174721174722174723174724174725174726174727174728174729174730174731174732174733174734174735174736174737174738174739174740174741174742174743174744174745174746174747174748174749174750174751174752174753174754174755174756174757174758174759174760174761174762174763174764174765174766174767174768174769174770174771174772174773174774174775174776174777174778174779174780174781174782174783174784174785174786174787174788174789174790174791174792174793174794174795174796174797174798174799174800174801174802174803174804174805174806174807174808174809174810174811174812174813174814174815174816174817174818174819174820174821174822174823174824174825174826174827174828174829174830174831174832174833174834174835174836174837174838174839174840174841174842174843174844174845174846174847174848174849174850174851174852174853174854174855174856174857174858174859174860174861174862174863174864174865174866174867174868174869174870174871174872174873174874174875174876174877174878174879174880174881174882174883174884174885174886174887174888174889174890174891174892174893174894174895174896174897174898174899174900174901174902174903174904174905174906174907174908174909174910174911174912174913174914174915174916174917174918174919174920174921174922174923174924174925174926174927174928174929174930174931174932174933174934174935174936174937174938174939174940174941174942174943174944174945174946174947174948174949174950174951174952174953174954174955174956174957174958174959174960174961174962174963174964174965174966174967174968174969174970174971174972174973174974174975174976174977174978174979174980174981174982174983174984174985174986174987174988174989174990174991174992174993174994174995174996174997174998174999175000175001175002175003175004175005175006175007175008175009175010175011175012175013175014175015175016175017175018175019175020175021175022175023175024175025175026175027175028175029175030175031175032175033175034175035175036175037175038175039175040175041175042175043175044175045175046175047175048175049175050175051175052175053175054175055175056175057175058175059175060175061175062175063175064175065175066175067175068175069175070175071175072175073175074175075175076175077175078175079175080175081175082175083175084175085175086175087175088175089175090175091175092175093175094175095175096175097175098175099175100175101175102175103175104175105175106175107175108175109175110175111175112175113175114175115175116175117175118175119175120175121175122175123175124175125175126175127175128175129175130175131175132175133175134175135175136175137175138175139175140175141175142175143175144175145175146175147175148175149175150175151175152175153175154175155175156175157175158175159175160175161175162175163175164175165175166175167175168175169175170175171175172175173175174175175175176175177175178175179175180175181175182175183175184175185175186175187175188175189175190175191175192175193175194175195175196175197175198175199175200175201175202175203175204175205175206175207175208175209175210175211175212175213175214175215175216175217175218175219175220175221175222175223175224175225175226175227175228175229175230175231175232175233175234175235175236175237175238175239175240175241175242175243175244175245175246175247175248175249175250175251175252175253175254175255175256175257175258175259175260175261175262175263175264175265175266175267175268175269175270175271175272175273175274175275175276175277175278175279175280175281175282175283175284175285175286175287175288175289175290175291175292175293175294175295175296175297175298175299175300175301175302175303175304175305175306175307175308175309175310175311175312175313175314175315175316175317175318175319175320175321175322175323175324175325175326175327175328175329175330175331175332175333175334175335175336175337175338175339175340175341175342175343175344175345175346175347175348175349175350175351175352175353175354175355175356175357175358175359175360175361175362175363175364175365175366175367175368175369175370175371175372175373175374175375175376175377175378175379175380175381175382175383175384175385175386175387175388175389175390175391175392175393175394175395175396175397175398175399175400175401175402175403175404175405175406175407175408175409175410175411175412175413175414175415175416175417175418175419175420175421175422175423175424175425175426175427175428175429175430175431175432175433175434175435175436175437175438175439175440175441175442175443175444175445175446175447175448175449175450175451175452175453175454175455175456175457175458175459175460175461175462175463175464175465175466175467175468175469175470175471175472175473175474175475175476175477175478175479175480175481175482175483175484175485175486175487175488175489175490175491175492175493175494175495175496175497175498175499175500175501175502175503175504175505175506175507175508175509175510175511175512175513175514175515175516175517175518175519175520175521175522175523175524175525175526175527175528175529175530175531175532175533175534175535175536175537175538175539175540175541175542175543175544175545175546175547175548175549175550175551175552175553175554175555175556175557175558175559175560175561175562175563175564175565175566175567175568175569175570175571175572175573175574175575175576175577175578175579175580175581175582175583175584175585175586175587175588175589175590175591175592175593175594175595175596175597175598175599175600175601175602175603175604175605175606175607175608175609175610175611175612175613175614175615175616175617175618175619175620175621175622175623175624175625175626175627175628175629175630175631175632175633175634175635175636175637175638175639175640175641175642175643175644175645175646175647175648175649175650175651175652175653175654175655175656175657175658175659175660175661175662175663175664175665175666175667175668175669175670175671175672175673175674175675175676175677175678175679175680175681175682175683175684175685175686175687175688175689175690175691175692175693175694175695175696175697175698175699175700175701175702175703175704175705175706175707175708175709175710175711175712175713175714175715175716175717175718175719175720175721175722175723175724175725175726175727175728175729175730175731175732175733175734175735175736175737175738175739175740175741175742175743175744175745175746175747175748175749175750175751175752175753175754175755175756175757175758175759175760175761175762175763175764175765175766175767175768175769175770175771175772175773175774175775175776175777175778175779175780175781175782175783175784175785175786175787175788175789175790175791175792175793175794175795175796175797175798175799175800175801175802175803175804175805175806175807175808175809175810175811175812175813175814175815175816175817175818175819175820175821175822175823175824175825175826175827175828175829175830175831175832175833175834175835175836175837175838175839175840175841175842175843175844175845175846175847175848175849175850175851175852175853175854175855175856175857175858175859175860175861175862175863175864175865175866175867175868175869175870175871175872175873175874175875175876175877175878175879175880175881175882175883175884175885175886175887175888175889175890175891175892175893175894175895175896175897175898175899175900175901175902175903175904175905175906175907175908175909175910175911175912175913175914175915175916175917175918175919175920175921175922175923175924175925175926175927175928175929175930175931175932175933175934175935175936175937175938175939175940175941175942175943175944175945175946175947175948175949175950175951175952175953175954175955175956175957175958175959175960175961175962175963175964175965175966175967175968175969175970175971175972175973175974175975175976175977175978175979175980175981175982175983175984175985175986175987175988175989175990175991175992175993175994175995175996175997175998175999176000176001176002176003176004176005176006176007176008176009176010176011176012176013176014176015176016176017176018176019176020176021176022176023176024176025176026176027176028176029176030176031176032176033176034176035176036176037176038176039176040176041176042176043176044176045176046176047176048176049176050176051176052176053176054176055176056176057176058176059176060176061176062176063176064176065176066176067176068176069176070176071176072176073176074176075176076176077176078176079176080176081176082176083176084176085176086176087176088176089176090176091176092176093176094176095176096176097176098176099176100176101176102176103176104176105176106176107176108176109176110176111176112176113176114176115176116176117176118176119176120176121176122176123176124176125176126176127176128176129176130176131176132176133176134176135176136176137176138176139176140176141176142176143176144176145176146176147176148176149176150176151176152176153176154176155176156176157176158176159176160176161176162176163176164176165176166176167176168176169176170176171176172176173176174176175176176176177176178176179176180176181176182176183176184176185176186176187176188176189176190176191176192176193176194176195176196176197176198176199176200176201176202176203176204176205176206176207176208176209176210176211176212176213176214176215176216176217176218176219176220176221176222176223176224176225176226176227176228176229176230176231176232176233176234176235176236176237176238176239176240176241176242176243176244176245176246176247176248176249176250176251176252176253176254176255176256176257176258176259176260176261176262176263176264176265176266176267176268176269176270176271176272176273176274176275176276176277176278176279176280176281176282176283176284176285176286176287176288176289176290176291176292176293176294176295176296176297176298176299176300176301176302176303176304176305176306176307176308176309176310176311176312176313176314176315176316176317176318176319176320176321176322176323176324176325176326176327176328176329176330176331176332176333176334176335176336176337176338176339176340176341176342176343176344176345176346176347176348176349176350176351176352176353176354176355176356176357176358176359176360176361176362176363176364176365176366176367176368176369176370176371176372176373176374176375176376176377176378176379176380176381176382176383176384176385176386176387176388176389176390176391176392176393176394176395176396176397176398176399176400176401176402176403176404176405176406176407176408176409176410176411176412176413176414176415176416176417176418176419176420176421176422176423176424176425176426176427176428176429176430176431176432176433176434176435176436176437176438176439176440176441176442176443176444176445176446176447176448176449176450176451176452176453176454176455176456176457176458176459176460176461176462176463176464176465176466176467176468176469176470176471176472176473176474176475176476176477176478176479176480176481176482176483176484176485176486176487176488176489176490176491176492176493176494176495176496176497176498176499176500176501176502176503176504176505176506176507176508176509176510176511176512176513176514176515176516176517176518176519176520176521176522176523176524176525176526176527176528176529176530176531176532176533176534176535176536176537176538176539176540176541176542176543176544176545176546176547176548176549176550176551176552176553176554176555176556176557176558176559176560176561176562176563176564176565176566176567176568176569176570176571176572176573176574176575176576176577176578176579176580176581176582176583176584176585176586176587176588176589176590176591176592176593176594176595176596176597176598176599176600176601176602176603176604176605176606176607176608176609176610176611176612176613176614176615176616176617176618176619176620176621176622176623176624176625176626176627176628176629176630176631176632176633176634176635176636176637176638176639176640176641176642176643176644176645176646176647176648176649176650176651176652176653176654176655176656176657176658176659176660176661176662176663176664176665176666176667176668176669176670176671176672176673176674176675176676176677176678176679176680176681176682176683176684176685176686176687176688176689176690176691176692176693176694176695176696176697176698176699176700176701176702176703176704176705176706176707176708176709176710176711176712176713176714176715176716176717176718176719176720176721176722176723176724176725176726176727176728176729176730176731176732176733176734176735176736176737176738176739176740176741176742176743176744176745176746176747176748176749176750176751176752176753176754176755176756176757176758176759176760176761176762176763176764176765176766176767176768176769176770176771176772176773176774176775176776176777176778176779176780176781176782176783176784176785176786176787176788176789176790176791176792176793176794176795176796176797176798176799176800176801176802176803176804176805176806176807176808176809176810176811176812176813176814176815176816176817176818176819176820176821176822176823176824176825176826176827176828176829176830176831176832176833176834176835176836176837176838176839176840176841176842176843176844176845176846176847176848176849176850176851176852176853176854176855176856176857176858176859176860176861176862176863176864176865176866176867176868176869176870176871176872176873176874176875176876176877176878176879176880176881176882176883176884176885176886176887176888176889176890176891176892176893176894176895176896176897176898176899176900176901176902176903176904176905176906176907176908176909176910176911176912176913176914176915176916176917176918176919176920176921176922176923176924176925176926176927176928176929176930176931176932176933176934176935176936176937176938176939176940176941176942176943176944176945176946176947176948176949176950176951176952176953176954176955176956176957176958176959176960176961176962176963176964176965176966176967176968176969176970176971176972176973176974176975176976176977176978176979176980176981176982176983176984176985176986176987176988176989176990176991176992176993176994176995176996176997176998176999177000177001177002177003177004177005177006177007177008177009177010177011177012177013177014177015177016177017177018177019177020177021177022177023177024177025177026177027177028177029177030177031177032177033177034177035177036177037177038177039177040177041177042177043177044177045177046177047177048177049177050177051177052177053177054177055177056177057177058177059177060177061177062177063177064177065177066177067177068177069177070177071177072177073177074177075177076177077177078177079177080177081177082177083177084177085177086177087177088177089177090177091177092177093177094177095177096177097177098177099177100177101177102177103177104177105177106177107177108177109177110177111177112177113177114177115177116177117177118177119177120177121177122177123177124177125177126177127177128177129177130177131177132177133177134177135177136177137177138177139177140177141177142177143177144177145177146177147177148177149177150177151177152177153177154177155177156177157177158177159177160177161177162177163177164177165177166177167177168177169177170177171177172177173177174177175177176177177177178177179177180177181177182177183177184177185177186177187177188177189177190177191177192177193177194177195177196177197177198177199177200177201177202177203177204177205177206177207177208177209177210177211177212177213177214177215177216177217177218177219177220177221177222177223177224177225177226177227177228177229177230177231177232177233177234177235177236177237177238177239177240177241177242177243177244177245177246177247177248177249177250177251177252177253177254177255177256177257177258177259177260177261177262177263177264177265177266177267177268177269177270177271177272177273177274177275177276177277177278177279177280177281177282177283177284177285177286177287177288177289177290177291177292177293177294177295177296177297177298177299177300177301177302177303177304177305177306177307177308177309177310177311177312177313177314177315177316177317177318177319177320177321177322177323177324177325177326177327177328177329177330177331177332177333177334177335177336177337177338177339177340177341177342177343177344177345177346177347177348177349177350177351177352177353177354177355177356177357177358177359177360177361177362177363177364177365177366177367177368177369177370177371177372177373177374177375177376177377177378177379177380177381177382177383177384177385177386177387177388177389177390177391177392177393177394177395177396177397177398177399177400177401177402177403177404177405177406177407177408177409177410177411177412177413177414177415177416177417177418177419177420177421177422177423177424177425177426177427177428177429177430177431177432177433177434177435177436177437177438177439177440177441177442177443177444177445177446177447177448177449177450177451177452177453177454177455177456177457177458177459177460177461177462177463177464177465177466177467177468177469177470177471177472177473177474177475177476177477177478177479177480177481177482177483177484177485177486177487177488177489177490177491177492177493177494177495177496177497177498177499177500177501177502177503177504177505177506177507177508177509177510177511177512177513177514177515177516177517177518177519177520177521177522177523177524177525177526177527177528177529177530177531177532177533177534177535177536177537177538177539177540177541177542177543177544177545177546177547177548177549177550177551177552177553177554177555177556177557177558177559177560177561177562177563177564177565177566177567177568177569177570177571177572177573177574177575177576177577177578177579177580177581177582177583177584177585177586177587177588177589177590177591177592177593177594177595177596177597177598177599177600177601177602177603177604177605177606177607177608177609177610177611177612177613177614177615177616177617177618177619177620177621177622177623177624177625177626177627177628177629177630177631177632177633177634177635177636177637177638177639177640177641177642177643177644177645177646177647177648177649177650177651177652177653177654177655177656177657177658177659177660177661177662177663177664177665177666177667177668177669177670177671177672177673177674177675177676177677177678177679177680177681177682177683177684177685177686177687177688177689177690177691177692177693177694177695177696177697177698177699177700177701177702177703177704177705177706177707177708177709177710177711177712177713177714177715177716177717177718177719177720177721177722177723177724177725177726177727177728177729177730177731177732177733177734177735177736177737177738177739177740177741177742177743177744177745177746177747177748177749177750177751177752177753177754177755177756177757177758177759177760177761177762177763177764177765177766177767177768177769177770177771177772177773177774177775177776177777177778177779177780177781177782177783177784177785177786177787177788177789177790177791177792177793177794177795177796177797177798177799177800177801177802177803177804177805177806177807177808177809177810177811177812177813177814177815177816177817177818177819177820177821177822177823177824177825177826177827177828177829177830177831177832177833177834177835177836177837177838177839177840177841177842177843177844177845177846177847177848177849177850177851177852177853177854177855177856177857177858177859177860177861177862177863177864177865177866177867177868177869177870177871177872177873177874177875177876177877177878177879177880177881177882177883177884177885177886177887177888177889177890177891177892177893177894177895177896177897177898177899177900177901177902177903177904177905177906177907177908177909177910177911177912177913177914177915177916177917177918177919177920177921177922177923177924177925177926177927177928177929177930177931177932177933177934177935177936177937177938177939177940177941177942177943177944177945177946177947177948177949177950177951177952177953177954177955177956177957177958177959177960177961177962177963177964177965177966177967177968177969177970177971177972177973177974177975177976177977177978177979177980177981177982177983177984177985177986177987177988177989177990177991177992177993177994177995177996177997177998177999178000178001178002178003178004178005178006178007178008178009178010178011178012178013178014178015178016178017178018178019178020178021178022178023178024178025178026178027178028178029178030178031178032178033178034178035178036178037178038178039178040178041178042178043178044178045178046178047178048178049178050178051178052178053178054178055178056178057178058178059178060178061178062178063178064178065178066178067178068178069178070178071178072178073178074178075178076178077178078178079178080178081178082178083178084178085178086178087178088178089178090178091178092178093178094178095178096178097178098178099178100178101178102178103178104178105178106178107178108178109178110178111178112178113178114178115178116178117178118178119178120178121178122178123178124178125178126178127178128178129178130178131178132178133178134178135178136178137178138178139178140178141178142178143178144178145178146178147178148178149178150178151178152178153178154178155178156178157178158178159178160178161178162178163178164178165178166178167178168178169178170178171178172178173178174178175178176178177178178178179178180178181178182178183178184178185178186178187178188178189178190178191178192178193178194178195178196178197178198178199178200178201178202178203178204178205178206178207178208178209178210178211178212178213178214178215178216178217178218178219178220178221178222178223178224178225178226178227178228178229178230178231178232178233178234178235178236178237178238178239178240178241178242178243178244178245178246178247178248178249178250178251178252178253178254178255178256178257178258178259178260178261178262178263178264178265178266178267178268178269178270178271178272178273178274178275178276178277178278178279178280178281178282178283178284178285178286178287178288178289178290178291178292178293178294178295178296178297178298178299178300178301178302178303178304178305178306178307178308178309178310178311178312178313178314178315178316178317178318178319178320178321178322178323178324178325178326178327178328178329178330178331178332178333178334178335178336178337178338178339178340178341178342178343178344178345178346178347178348178349178350178351178352178353178354178355178356178357178358178359178360178361178362178363178364178365178366178367178368178369178370178371178372178373178374178375178376178377178378178379178380178381178382178383178384178385178386178387178388178389178390178391178392178393178394178395178396178397178398178399178400178401178402178403178404178405178406178407178408178409178410178411178412178413178414178415178416178417178418178419178420178421178422178423178424178425178426178427178428178429178430178431178432178433178434178435178436178437178438178439178440178441178442178443178444178445178446178447178448178449178450178451178452178453178454178455178456178457178458178459178460178461178462178463178464178465178466178467178468178469178470178471178472178473178474178475178476178477178478178479178480178481178482178483178484178485178486178487178488178489178490178491178492178493178494178495178496178497178498178499178500178501178502178503178504178505178506178507178508178509178510178511178512178513178514178515178516178517178518178519178520178521178522178523178524178525178526178527178528178529178530178531178532178533178534178535178536178537178538178539178540178541178542178543178544178545178546178547178548178549178550178551178552178553178554178555178556178557178558178559178560178561178562178563178564178565178566178567178568178569178570178571178572178573178574178575178576178577178578178579178580178581178582178583178584178585178586178587178588178589178590178591178592178593178594178595178596178597178598178599178600178601178602178603178604178605178606178607178608178609178610178611178612178613178614178615178616178617178618178619178620178621178622178623178624178625178626178627178628178629178630178631178632178633178634178635178636178637178638178639178640178641178642178643178644178645178646178647178648178649178650178651178652178653178654178655178656178657178658178659178660178661178662178663178664178665178666178667178668178669178670178671178672178673178674178675178676178677178678178679178680178681178682178683178684178685178686178687178688178689178690178691178692178693178694178695178696178697178698178699178700178701178702178703178704178705178706178707178708178709178710178711178712178713178714178715178716178717178718178719178720178721178722178723178724178725178726178727178728178729178730178731178732178733178734178735178736178737178738178739178740178741178742178743178744178745178746178747178748178749178750178751178752178753178754178755178756178757178758178759178760178761178762178763178764178765178766178767178768178769178770178771178772178773178774178775178776178777178778178779178780178781178782178783178784178785178786178787178788178789178790178791178792178793178794178795178796178797178798178799178800178801178802178803178804178805178806178807178808178809178810178811178812178813178814178815178816178817178818178819178820178821178822178823178824178825178826178827178828178829178830178831178832178833178834178835178836178837178838178839178840178841178842178843178844178845178846178847178848178849178850178851178852178853178854178855178856178857178858178859178860178861178862178863178864178865178866178867178868178869178870178871178872178873178874178875178876178877178878178879178880178881178882178883178884178885178886178887178888178889178890178891178892178893178894178895178896178897178898178899178900178901178902178903178904178905178906178907178908178909178910178911178912178913178914178915178916178917178918178919178920178921178922178923178924178925178926178927178928178929178930178931178932178933178934178935178936178937178938178939178940178941178942178943178944178945178946178947178948178949178950178951178952178953178954178955178956178957178958178959178960178961178962178963178964178965178966178967178968178969178970178971178972178973178974178975178976178977178978178979178980178981178982178983178984178985178986178987178988178989178990178991178992178993178994178995178996178997178998178999179000179001179002179003179004179005179006179007179008179009179010179011179012179013179014179015179016179017179018179019179020179021179022179023179024179025179026179027179028179029179030179031179032179033179034179035179036179037179038179039179040179041179042179043179044179045179046179047179048179049179050179051179052179053179054179055179056179057179058179059179060179061179062179063179064179065179066179067179068179069179070179071179072179073179074179075179076179077179078179079179080179081179082179083179084179085179086179087179088179089179090179091179092179093179094179095179096179097179098179099179100179101179102179103179104179105179106179107179108179109179110179111179112179113179114179115179116179117179118179119179120179121179122179123179124179125179126179127179128179129179130179131179132179133179134179135179136179137179138179139179140179141179142179143179144179145179146179147179148179149179150179151179152179153179154179155179156179157179158179159179160179161179162179163179164179165179166179167179168179169179170179171179172179173179174179175179176179177179178179179179180179181179182179183179184179185179186179187179188179189179190179191179192179193179194179195179196179197179198179199179200179201179202179203179204179205179206179207179208179209179210179211179212179213179214179215179216179217179218179219179220179221179222179223179224179225179226179227179228179229179230179231179232179233179234179235179236179237179238179239179240179241179242179243179244179245179246179247179248179249179250179251179252179253179254179255179256179257179258179259179260179261179262179263179264179265179266179267179268179269179270179271179272179273179274179275179276179277179278179279179280179281179282179283179284179285179286179287179288179289179290179291179292179293179294179295179296179297179298179299179300179301179302179303179304179305179306179307179308179309179310179311179312179313179314179315179316179317179318179319179320179321179322179323179324179325179326179327179328179329179330179331179332179333179334179335179336179337179338179339179340179341179342179343179344179345179346179347179348179349179350179351179352179353179354179355179356179357179358179359179360179361179362179363179364179365179366179367179368179369179370179371179372179373179374179375179376179377179378179379179380179381179382179383179384179385179386179387179388179389179390179391179392179393179394179395179396179397179398179399179400179401179402179403179404179405179406179407179408179409179410179411179412179413179414179415179416179417179418179419179420179421179422179423179424179425179426179427179428179429179430179431179432179433179434179435179436179437179438179439179440179441179442179443179444179445179446179447179448179449179450179451179452179453179454179455179456179457179458179459179460179461179462179463179464179465179466179467179468179469179470179471179472179473179474179475179476179477179478179479179480179481179482179483179484179485179486179487179488179489179490179491179492179493179494179495179496179497179498179499179500179501179502179503179504179505179506179507179508179509179510179511179512179513179514179515179516179517179518179519179520179521179522179523179524179525179526179527179528179529179530179531179532179533179534179535179536179537179538179539179540179541179542179543179544179545179546179547179548179549179550179551179552179553179554179555179556179557179558179559179560179561179562179563179564179565179566179567179568179569179570179571179572179573179574179575179576179577179578179579179580179581179582179583179584179585179586179587179588179589179590179591179592179593179594179595179596179597179598179599179600179601179602179603179604179605179606179607179608179609179610179611179612179613179614179615179616179617179618179619179620179621179622179623179624179625179626179627179628179629179630179631179632179633179634179635179636179637179638179639179640179641179642179643179644179645179646179647179648179649179650179651179652179653179654179655179656179657179658179659179660179661179662179663179664179665179666179667179668179669179670179671179672179673179674179675179676179677179678179679179680179681179682179683179684179685179686179687179688179689179690179691179692179693179694179695179696179697179698179699179700179701179702179703179704179705179706179707179708179709179710179711179712179713179714179715179716179717179718179719179720179721179722179723179724179725179726179727179728179729179730179731179732179733179734179735179736179737179738179739179740179741179742179743179744179745179746179747179748179749179750179751179752179753179754179755179756179757179758179759179760179761179762179763179764179765179766179767179768179769179770179771179772179773179774179775179776179777179778179779179780179781179782179783179784179785179786179787179788179789179790179791179792179793179794179795179796179797179798179799179800179801179802179803179804179805179806179807179808179809179810179811179812179813179814179815179816179817179818179819179820179821179822179823179824179825179826179827179828179829179830179831179832179833179834179835179836179837179838179839179840179841179842179843179844179845179846179847179848179849179850179851179852179853179854179855179856179857179858179859179860179861179862179863179864179865179866179867179868179869179870179871179872179873179874179875179876179877179878179879179880179881179882179883179884179885179886179887179888179889179890179891179892179893179894179895179896179897179898179899179900179901179902179903179904179905179906179907179908179909179910179911179912179913179914179915179916179917179918179919179920179921179922179923179924179925179926179927179928179929179930179931179932179933179934179935179936179937179938179939179940179941179942179943179944179945179946179947179948179949179950179951179952179953179954179955179956179957179958179959179960179961179962179963179964179965179966179967179968179969179970179971179972179973179974179975179976179977179978179979179980179981179982179983179984179985179986179987179988179989179990179991179992179993179994179995179996179997179998179999180000180001180002180003180004180005180006180007180008180009180010180011180012180013180014180015180016180017180018180019180020180021180022180023180024180025180026180027180028180029180030180031180032180033180034180035180036180037180038180039180040180041180042180043180044180045180046180047180048180049180050180051180052180053180054180055180056180057180058180059180060180061180062180063180064180065180066180067180068180069180070180071180072180073180074180075180076180077180078180079180080180081180082180083180084180085180086180087180088180089180090180091180092180093180094180095180096180097180098180099180100180101180102180103180104180105180106180107180108180109180110180111180112180113180114180115180116180117180118180119180120180121180122180123180124180125180126180127180128180129180130180131180132180133180134180135180136180137180138180139180140180141180142180143180144180145180146180147180148180149180150180151180152180153180154180155180156180157180158180159180160180161180162180163180164180165180166180167180168180169180170180171180172180173180174180175180176180177180178180179180180180181180182180183180184180185180186180187180188180189180190180191180192180193180194180195180196180197180198180199180200180201180202180203180204180205180206180207180208180209180210180211180212180213180214180215180216180217180218180219180220180221180222180223180224180225180226180227180228180229180230180231180232180233180234180235180236180237180238180239180240180241180242180243180244180245180246180247180248180249180250180251180252180253180254180255180256180257180258180259180260180261180262180263180264180265180266180267180268180269180270180271180272180273180274180275180276180277180278180279180280180281180282180283180284180285180286180287180288180289180290180291180292180293180294180295180296180297180298180299180300180301180302180303180304180305180306180307180308180309180310180311180312180313180314180315180316180317180318180319180320180321180322180323180324180325180326180327180328180329180330180331180332180333180334180335180336180337180338180339180340180341180342180343180344180345180346180347180348180349180350180351180352180353180354180355180356180357180358180359180360180361180362180363180364180365180366180367180368180369180370180371180372180373180374180375180376180377180378180379180380180381180382180383180384180385180386180387180388180389180390180391180392180393180394180395180396180397180398180399180400180401180402180403180404180405180406180407180408180409180410180411180412180413180414180415180416180417180418180419180420180421180422180423180424180425180426180427180428180429180430180431180432180433180434180435180436180437180438180439180440180441180442180443180444180445180446180447180448180449180450180451180452180453180454180455180456180457180458180459180460180461180462180463180464180465180466180467180468180469180470180471180472180473180474180475180476180477180478180479180480180481180482180483180484180485180486180487180488180489180490180491180492180493180494180495180496180497180498180499180500180501180502180503180504180505180506180507180508180509180510180511180512180513180514180515180516180517180518180519180520180521180522180523180524180525180526180527180528180529180530180531180532180533180534180535180536180537180538180539180540180541180542180543180544180545180546180547180548180549180550180551180552180553180554180555180556180557180558180559180560180561180562180563180564180565180566180567180568180569180570180571180572180573180574180575180576180577180578180579180580180581180582180583180584180585180586180587180588180589180590180591180592180593180594180595180596180597180598180599180600180601180602180603180604180605180606180607180608180609180610180611180612180613180614180615180616180617180618180619180620180621180622180623180624180625180626180627180628180629180630180631180632180633180634180635180636180637180638180639180640180641180642180643180644180645180646180647180648180649180650180651180652180653180654180655180656180657180658180659180660180661180662180663180664180665180666180667180668180669180670180671180672180673180674180675180676180677180678180679180680180681180682180683180684180685180686180687180688180689180690180691180692180693180694180695180696180697180698180699180700180701180702180703180704180705180706180707180708180709180710180711180712180713180714180715180716180717180718180719180720180721180722180723180724180725180726180727180728180729180730180731180732180733180734180735180736180737180738180739180740180741180742180743180744180745180746180747180748180749180750180751180752180753180754180755180756180757180758180759180760180761180762180763180764180765180766180767180768180769180770180771180772180773180774180775180776180777180778180779180780180781180782180783180784180785180786180787180788180789180790180791180792180793180794180795180796180797180798180799180800180801180802180803180804180805180806180807180808180809180810180811180812180813180814180815180816180817180818180819180820180821180822180823180824180825180826180827180828180829180830180831180832180833180834180835180836180837180838180839180840180841180842180843180844180845180846180847180848180849180850180851180852180853180854180855180856180857180858180859180860180861180862180863180864180865180866180867180868180869180870180871180872180873180874180875180876180877180878180879180880180881180882180883180884180885180886180887180888180889180890180891180892180893180894180895180896180897180898180899180900180901180902180903180904180905180906180907180908180909180910180911180912180913180914180915180916180917180918180919180920180921180922180923180924180925180926180927180928180929180930180931180932180933180934180935180936180937180938180939180940180941180942180943180944180945180946180947180948180949180950180951180952180953180954180955180956180957180958180959180960180961180962180963180964180965180966180967180968180969180970180971180972180973180974180975180976180977180978180979180980180981180982180983180984180985180986180987180988180989180990180991180992180993180994180995180996180997180998180999181000181001181002181003181004181005181006181007181008181009181010181011181012181013181014181015181016181017181018181019181020181021181022181023181024181025181026181027181028181029181030181031181032181033181034181035181036181037181038181039181040181041181042181043181044181045181046181047181048181049181050181051181052181053181054181055181056181057181058181059181060181061181062181063181064181065181066181067181068181069181070181071181072181073181074181075181076181077181078181079181080181081181082181083181084181085181086181087181088181089181090181091181092181093181094181095181096181097181098181099181100181101181102181103181104181105181106181107181108181109181110181111181112181113181114181115181116181117181118181119181120181121181122181123181124181125181126181127181128181129181130181131181132181133181134181135181136181137181138181139181140181141181142181143181144181145181146181147181148181149181150181151181152181153181154181155181156181157181158181159181160181161181162181163181164181165181166181167181168181169181170181171181172181173181174181175181176181177181178181179181180181181181182181183181184181185181186181187181188181189181190181191181192181193181194181195181196181197181198181199181200181201181202181203181204181205181206181207181208181209181210181211181212181213181214181215181216181217181218181219181220181221181222181223181224181225181226181227181228181229181230181231181232181233181234181235181236181237181238181239181240181241181242181243181244181245181246181247181248181249181250181251181252181253181254181255181256181257181258181259181260181261181262181263181264181265181266181267181268181269181270181271181272181273181274181275181276181277181278181279181280181281181282181283181284181285181286181287181288181289181290181291181292181293181294181295181296181297181298181299181300181301181302181303181304181305181306181307181308181309181310181311181312181313181314181315181316181317181318181319181320181321181322181323181324181325181326181327181328181329181330181331181332181333181334181335181336181337181338181339181340181341181342181343181344181345181346181347181348181349181350181351181352181353181354181355181356181357181358181359181360181361181362181363181364181365181366181367181368181369181370181371181372181373181374181375181376181377181378181379181380181381181382181383181384181385181386181387181388181389181390181391181392181393181394181395181396181397181398181399181400181401181402181403181404181405181406181407181408181409181410181411181412181413181414181415181416181417181418181419181420181421181422181423181424181425181426181427181428181429181430181431181432181433181434181435181436181437181438181439181440181441181442181443181444181445181446181447181448181449181450181451181452181453181454181455181456181457181458181459181460181461181462181463181464181465181466181467181468181469181470181471181472181473181474181475181476181477181478181479181480181481181482181483181484181485181486181487181488181489181490181491181492181493181494181495181496181497181498181499181500181501181502181503181504181505181506181507181508181509181510181511181512181513181514181515181516181517181518181519181520181521181522181523181524181525181526181527181528181529181530181531181532181533181534181535181536181537181538181539181540181541181542181543181544181545181546181547181548181549181550181551181552181553181554181555181556181557181558181559181560181561181562181563181564181565181566181567181568181569181570181571181572181573181574181575181576181577181578181579181580181581181582181583181584181585181586181587181588181589181590181591181592181593181594181595181596181597181598181599181600181601181602181603181604181605181606181607181608181609181610181611181612181613181614181615181616181617181618181619181620181621181622181623181624181625181626181627181628181629181630181631181632181633181634181635181636181637181638181639181640181641181642181643181644181645181646181647181648181649181650181651181652181653181654181655181656181657181658181659181660181661181662181663181664181665181666181667181668181669181670181671181672181673181674181675181676181677181678181679181680181681181682181683181684181685181686181687181688181689181690181691181692181693181694181695181696181697181698181699181700181701181702181703181704181705181706181707181708181709181710181711181712181713181714181715181716181717181718181719181720181721181722181723181724181725181726181727181728181729181730181731181732181733181734181735181736181737181738181739181740181741181742181743181744181745181746181747181748181749181750181751181752181753181754181755181756181757181758181759181760181761181762181763181764181765181766181767181768181769181770181771181772181773181774181775181776181777181778181779181780181781181782181783181784181785181786181787181788181789181790181791181792181793181794181795181796181797181798181799181800181801181802181803181804181805181806181807181808181809181810181811181812181813181814181815181816181817181818181819181820181821181822181823181824181825181826181827181828181829181830181831181832181833181834181835181836181837181838181839181840181841181842181843181844181845181846181847181848181849181850181851181852181853181854181855181856181857181858181859181860181861181862181863181864181865181866181867181868181869181870181871181872181873181874181875181876181877181878181879181880181881181882181883181884181885181886181887181888181889181890181891181892181893181894181895181896181897181898181899181900181901181902181903181904181905181906181907181908181909181910181911181912181913181914181915181916181917181918181919181920181921181922181923181924181925181926181927181928181929181930181931181932181933181934181935181936181937181938181939181940181941181942181943181944181945181946181947181948181949181950181951181952181953181954181955181956181957181958181959181960181961181962181963181964181965181966181967181968181969181970181971181972181973181974181975181976181977181978181979181980181981181982181983181984181985181986181987181988181989181990181991181992181993181994181995181996181997181998181999182000182001182002182003182004182005182006182007182008182009182010182011182012182013182014182015182016182017182018182019182020182021182022182023182024182025182026182027182028182029182030182031182032182033182034182035182036182037182038182039182040182041182042182043182044182045182046182047182048182049182050182051182052182053182054182055182056182057182058182059182060182061182062182063182064182065182066182067182068182069182070182071182072182073182074182075182076182077182078182079182080182081182082182083182084182085182086182087182088182089182090182091182092182093182094182095182096182097182098182099182100182101182102182103182104182105182106182107182108182109182110182111182112182113182114182115182116182117182118182119182120182121182122182123182124182125182126182127182128182129182130182131182132182133182134182135182136182137182138182139182140182141182142182143182144182145182146182147182148182149182150182151182152182153182154182155182156182157182158182159182160182161182162182163182164182165182166182167182168182169182170182171182172182173182174182175182176182177182178182179182180182181182182182183182184182185182186182187182188182189182190182191182192182193182194182195182196182197182198182199182200182201182202182203182204182205182206182207182208182209182210182211182212182213182214182215182216182217182218182219182220182221182222182223182224182225182226182227182228182229182230182231182232182233182234182235182236182237182238182239182240182241182242182243182244182245182246182247182248182249182250182251182252182253182254182255182256182257182258182259182260182261182262182263182264182265182266182267182268182269182270182271182272182273182274182275182276182277182278182279182280182281182282182283182284182285182286182287182288182289182290182291182292182293182294182295182296182297182298182299182300182301182302182303182304182305182306182307182308182309182310182311182312182313182314182315182316182317182318182319182320182321182322182323182324182325182326182327182328182329182330182331182332182333182334182335182336182337182338182339182340182341182342182343182344182345182346182347182348182349182350182351182352182353182354182355182356182357182358182359182360182361182362182363182364182365182366182367182368182369182370182371182372182373182374182375182376182377182378182379182380182381182382182383182384182385182386182387182388182389182390182391182392182393182394182395182396182397182398182399182400182401182402182403182404182405182406182407182408182409182410182411182412182413182414182415182416182417182418182419182420182421182422182423182424182425182426182427182428182429182430182431182432182433182434182435182436182437182438182439182440182441182442182443182444182445182446182447182448182449182450182451182452182453182454182455182456182457182458182459182460182461182462182463182464182465182466182467182468182469182470182471182472182473182474182475182476182477182478182479182480182481182482182483182484182485182486182487182488182489182490182491182492182493182494182495182496182497182498182499182500182501182502182503182504182505182506182507182508182509182510182511182512182513182514182515182516182517182518182519182520182521182522182523182524182525182526182527182528182529182530182531182532182533182534182535182536182537182538182539182540182541182542182543182544182545182546182547182548182549182550182551182552182553182554182555182556182557182558182559182560182561182562182563182564182565182566182567182568182569182570182571182572182573182574182575182576182577182578182579182580182581182582182583182584182585182586182587182588182589182590182591182592182593182594182595182596182597182598182599182600182601182602182603182604182605182606182607182608182609182610182611182612182613182614182615182616182617182618182619182620182621182622182623182624182625182626182627182628182629182630182631182632182633182634182635182636182637182638182639182640182641182642182643182644182645182646182647182648182649182650182651182652182653182654182655182656182657182658182659182660182661182662182663182664182665182666182667182668182669182670182671182672182673182674182675182676182677182678182679182680182681182682182683182684182685182686182687182688182689182690182691182692182693182694182695182696182697182698182699182700182701182702182703182704182705182706182707182708182709182710182711182712182713182714182715182716182717182718182719182720182721182722182723182724182725182726182727182728182729182730182731182732182733182734182735182736182737182738182739182740182741182742182743182744182745182746182747182748182749182750182751182752182753182754182755182756182757182758182759182760182761182762182763182764182765182766182767182768182769182770182771182772182773182774182775182776182777182778182779182780182781182782182783182784182785182786182787182788182789182790182791182792182793182794182795182796182797182798182799182800182801182802182803182804182805182806182807182808182809182810182811182812182813182814182815182816182817182818182819182820182821182822182823182824182825182826182827182828182829182830182831182832182833182834182835182836182837182838182839182840182841182842182843182844182845182846182847182848182849182850182851182852182853182854182855182856182857182858182859182860182861182862182863182864182865182866182867182868182869182870182871182872182873182874182875182876182877182878182879182880182881182882182883182884182885182886182887182888182889182890182891182892182893182894182895182896182897182898182899182900182901182902182903182904182905182906182907182908182909182910182911182912182913182914182915182916182917182918182919182920182921182922182923182924182925182926182927182928182929182930182931182932182933182934182935182936182937182938182939182940182941182942182943182944182945182946182947182948182949182950182951182952182953182954182955182956182957182958182959182960182961182962182963182964182965182966182967182968182969182970182971182972182973182974182975182976182977182978182979182980182981182982182983182984182985182986182987182988182989182990182991182992182993182994182995182996182997182998182999183000183001183002183003183004183005183006183007183008183009183010183011183012183013183014183015183016183017183018183019183020183021183022183023183024183025183026183027183028183029183030183031183032183033183034183035183036183037183038183039183040183041183042183043183044183045183046183047183048183049183050183051183052183053183054183055183056183057183058183059183060183061183062183063183064183065183066183067183068183069183070183071183072183073183074183075183076183077183078183079183080183081183082183083183084183085183086183087183088183089183090183091183092183093183094183095183096183097183098183099183100183101183102183103183104183105183106183107183108183109183110183111183112183113183114183115183116183117183118183119183120183121183122183123183124183125183126183127183128183129183130183131183132183133183134183135183136183137183138183139183140183141183142183143183144183145183146183147183148183149183150183151183152183153183154183155183156183157183158183159183160183161183162183163183164183165183166183167183168183169183170183171183172183173183174183175183176183177183178183179183180183181183182183183183184183185183186183187183188183189183190183191183192183193183194183195183196183197183198183199183200183201183202183203183204183205183206183207183208183209183210183211183212183213183214183215183216183217183218183219183220183221183222183223183224183225183226183227183228183229183230183231183232183233183234183235183236183237183238183239183240183241183242183243183244183245183246183247183248183249183250183251183252183253183254183255183256183257183258183259183260183261183262183263183264183265183266183267183268183269183270183271183272183273183274183275183276183277183278183279183280183281183282183283183284183285183286183287183288183289183290183291183292183293183294183295183296183297183298183299183300183301183302183303183304183305183306183307183308183309183310183311183312183313183314183315183316183317183318183319183320183321183322183323183324183325183326183327183328183329183330183331183332183333183334183335183336183337183338183339183340183341183342183343183344183345183346183347183348183349183350183351183352183353183354183355183356183357183358183359183360183361183362183363183364183365183366183367183368183369183370183371183372183373183374183375183376183377183378183379183380183381183382183383183384183385183386183387183388183389183390183391183392183393183394183395183396183397183398183399183400183401183402183403183404183405183406183407183408183409183410183411183412183413183414183415183416183417183418183419183420183421183422183423183424183425183426183427183428183429183430183431183432183433183434183435183436183437183438183439183440183441183442183443183444183445183446183447183448183449183450183451183452183453183454183455183456183457183458183459183460183461183462183463183464183465183466183467183468183469183470183471183472183473183474183475183476183477183478183479183480183481183482183483183484183485183486183487183488183489183490183491183492183493183494183495183496183497183498183499183500183501183502183503183504183505183506183507183508183509183510183511183512183513183514183515183516183517183518183519183520183521183522183523183524183525183526183527183528183529183530183531183532183533183534183535183536183537183538183539183540183541183542183543183544183545183546183547183548183549183550183551183552183553183554183555183556183557183558183559183560183561183562183563183564183565183566183567183568183569183570183571183572183573183574183575183576183577183578183579183580183581183582183583183584183585183586183587183588183589183590183591183592183593183594183595183596183597183598183599183600183601183602183603183604183605183606183607183608183609183610183611183612183613183614183615183616183617183618183619183620183621183622183623183624183625183626183627183628183629183630183631183632183633183634183635183636183637183638183639183640183641183642183643183644183645183646183647183648183649183650183651183652183653183654183655183656183657183658183659183660183661183662183663183664183665183666183667183668183669183670183671183672183673183674183675183676183677183678183679183680183681183682183683183684183685183686183687183688183689183690183691183692183693183694183695183696183697183698183699183700183701183702183703183704183705183706183707183708183709183710183711183712183713183714183715183716183717183718183719183720183721183722183723183724183725183726183727183728183729183730183731183732183733183734183735183736183737183738183739183740183741183742183743183744183745183746183747183748183749183750183751183752183753183754183755183756183757183758183759183760183761183762183763183764183765183766183767183768183769183770183771183772183773183774183775183776183777183778183779183780183781183782183783183784183785183786183787183788183789183790183791183792183793183794183795183796183797183798183799183800183801183802183803183804183805183806183807183808183809183810183811183812183813183814183815183816183817183818183819183820183821183822183823183824183825183826183827183828183829183830183831183832183833183834183835183836183837183838183839183840183841183842183843183844183845183846183847183848183849183850183851183852183853183854183855183856183857183858183859183860183861183862183863183864183865183866183867183868183869183870183871183872183873183874183875183876183877183878183879183880183881183882183883183884183885183886183887183888183889183890183891183892183893183894183895183896183897183898183899183900183901183902183903183904183905183906183907183908183909183910183911183912183913183914183915183916183917183918183919183920183921183922183923183924183925183926183927183928183929183930183931183932183933183934183935183936183937183938183939183940183941183942183943183944183945183946183947183948183949183950183951183952183953183954183955183956183957183958183959183960183961183962183963183964183965183966183967183968183969183970183971183972183973183974183975183976183977183978183979183980183981183982183983183984183985183986183987183988183989183990183991183992183993183994183995183996183997183998183999184000184001184002184003184004184005184006184007184008184009184010184011184012184013184014184015184016184017184018184019184020184021184022184023184024184025184026184027184028184029184030184031184032184033184034184035184036184037184038184039184040184041184042184043184044184045184046184047184048184049184050184051184052184053184054184055184056184057184058184059184060184061184062184063184064184065184066184067184068184069184070184071184072184073184074184075184076184077184078184079184080184081184082184083184084184085184086184087184088184089184090184091184092184093184094184095184096184097184098184099184100184101184102184103184104184105184106184107184108184109184110184111184112184113184114184115184116184117184118184119184120184121184122184123184124184125184126184127184128184129184130184131184132184133184134184135184136184137184138184139184140184141184142184143184144184145184146184147184148184149184150184151184152184153184154184155184156184157184158184159184160184161184162184163184164184165184166184167184168184169184170184171184172184173184174184175184176184177184178184179184180184181184182184183184184184185184186184187184188184189184190184191184192184193184194184195184196184197184198184199184200184201184202184203184204184205184206184207184208184209184210184211184212184213184214184215184216184217184218184219184220184221184222184223184224184225184226184227184228184229184230184231184232184233184234184235184236184237184238184239184240184241184242184243184244184245184246184247184248184249184250184251184252184253184254184255184256184257184258184259184260184261184262184263184264184265184266184267184268184269184270184271184272184273184274184275184276184277184278184279184280184281184282184283184284184285184286184287184288184289184290184291184292184293184294184295184296184297184298184299184300184301184302184303184304184305184306184307184308184309184310184311184312184313184314184315184316184317184318184319184320184321184322184323184324184325184326184327184328184329184330184331184332184333184334184335184336184337184338184339184340184341184342184343184344184345184346184347184348184349184350184351184352184353184354184355184356184357184358184359184360184361184362184363184364184365184366184367184368184369184370184371184372184373184374184375184376184377184378184379184380184381184382184383184384184385184386184387184388184389184390184391184392184393184394184395184396184397184398184399184400184401184402184403184404184405184406184407184408184409184410184411184412184413184414184415184416184417184418184419184420184421184422184423184424184425184426184427184428184429184430184431184432184433184434184435184436184437184438184439184440184441184442184443184444184445184446184447184448184449184450184451184452184453184454184455184456184457184458184459184460184461184462184463184464184465184466184467184468184469184470184471184472184473184474184475184476184477184478184479184480184481184482184483184484184485184486184487184488184489184490184491184492184493184494184495184496184497184498184499184500184501184502184503184504184505184506184507184508184509184510184511184512184513184514184515184516184517184518184519184520184521184522184523184524184525184526184527184528184529184530184531184532184533184534184535184536184537184538184539184540184541184542184543184544184545184546184547184548184549184550184551184552184553184554184555184556184557184558184559184560184561184562184563184564184565184566184567184568184569184570184571184572184573184574184575184576184577184578184579184580184581184582184583184584184585184586184587184588184589184590184591184592184593184594184595184596184597184598184599184600184601184602184603184604184605184606184607184608184609184610184611184612184613184614184615184616184617184618184619184620184621184622184623184624184625184626184627184628184629184630184631184632184633184634184635184636184637184638184639184640184641184642184643184644184645184646184647184648184649184650184651184652184653184654184655184656184657184658184659184660184661184662184663184664184665184666184667184668184669184670184671184672184673184674184675184676184677184678184679184680184681184682184683184684184685184686184687184688184689184690184691184692184693184694184695184696184697184698184699184700184701184702184703184704184705184706184707184708184709184710184711184712184713184714184715184716184717184718184719184720184721184722184723184724184725184726184727184728184729184730184731184732184733184734184735184736184737184738184739184740184741184742184743184744184745184746184747184748184749184750184751184752184753184754184755184756184757184758184759184760184761184762184763184764184765184766184767184768184769184770184771184772184773184774184775184776184777184778184779184780184781184782184783184784184785184786184787184788184789184790184791184792184793184794184795184796184797184798184799184800184801184802184803184804184805184806184807184808184809184810184811184812184813184814184815184816184817184818184819184820184821184822184823184824184825184826184827184828184829184830184831184832184833184834184835184836184837184838184839184840184841184842184843184844184845184846184847184848184849184850184851184852184853184854184855184856184857184858184859184860184861184862184863184864184865184866184867184868184869184870184871184872184873184874184875184876184877184878184879184880184881184882184883184884184885184886184887184888184889184890184891184892184893184894184895184896184897184898184899184900184901184902184903184904184905184906184907184908184909184910184911184912184913184914184915184916184917184918184919184920184921184922184923184924184925184926184927184928184929184930184931184932184933184934184935184936184937184938184939184940184941184942184943184944184945184946184947184948184949184950184951184952184953184954184955184956184957184958184959184960184961184962184963184964184965184966184967184968184969184970184971184972184973184974184975184976184977184978184979184980184981184982184983184984184985184986184987184988184989184990184991184992184993184994184995184996184997184998184999185000185001185002185003185004185005185006185007185008185009185010185011185012185013185014185015185016185017185018185019185020185021185022185023185024185025185026185027185028185029185030185031185032185033185034185035185036185037185038185039185040185041185042185043185044185045185046185047185048185049185050185051185052185053185054185055185056185057185058185059185060185061185062185063185064185065185066185067185068185069185070185071185072185073185074185075185076185077185078185079185080185081185082185083185084185085185086185087185088185089185090185091185092185093185094185095185096185097185098185099185100185101185102185103185104185105185106185107185108185109185110185111185112185113185114185115185116185117185118185119185120185121185122185123185124185125185126185127185128185129185130185131185132185133185134185135185136185137185138185139185140185141185142185143185144185145185146185147185148185149185150185151185152185153185154185155185156185157185158185159185160185161185162185163185164185165185166185167185168185169185170185171185172185173185174185175185176185177185178185179185180185181185182185183185184185185185186185187185188185189185190185191185192185193185194185195185196185197185198185199185200185201185202185203185204185205185206185207185208185209185210185211185212185213185214185215185216185217185218185219185220185221185222185223185224185225185226185227185228185229185230185231185232185233185234185235185236185237185238185239185240185241185242185243185244185245185246185247185248185249185250185251185252185253185254185255185256185257185258185259185260185261185262185263185264185265185266185267185268185269185270185271185272185273185274185275185276185277185278185279185280185281185282185283185284185285185286185287185288185289185290185291185292185293185294185295185296185297185298185299185300185301185302185303185304185305185306185307185308185309185310185311185312185313185314185315185316185317185318185319185320185321185322185323185324185325185326185327185328185329185330185331185332185333185334185335185336185337185338185339185340185341185342185343185344185345185346185347185348185349185350185351185352185353185354185355185356185357185358185359185360185361185362185363185364185365185366185367185368185369185370185371185372185373185374185375185376185377185378185379185380185381185382185383185384185385185386185387185388185389185390185391185392185393185394185395185396185397185398185399185400185401185402185403185404185405185406185407185408185409185410185411185412185413185414185415185416185417185418185419185420185421185422185423185424185425185426185427185428185429185430185431185432185433185434185435185436185437185438185439185440185441185442185443185444185445185446185447185448185449185450185451185452185453185454185455185456185457185458185459185460185461185462185463185464185465185466185467185468185469185470185471185472185473185474185475185476185477185478185479185480185481185482185483185484185485185486185487185488185489185490185491185492185493185494185495185496185497185498185499185500185501185502185503185504185505185506185507185508185509185510185511185512185513185514185515185516185517185518185519185520185521185522185523185524185525185526185527185528185529185530185531185532185533185534185535185536185537185538185539185540185541185542185543185544185545185546185547185548185549185550185551185552185553185554185555185556185557185558185559185560185561185562185563185564185565185566185567185568185569185570185571185572185573185574185575185576185577185578185579185580185581185582185583185584185585185586185587185588185589185590185591185592185593185594185595185596185597185598185599185600185601185602185603185604185605185606185607185608185609185610185611185612185613185614185615185616185617185618185619185620185621185622185623185624185625185626185627185628185629185630185631185632185633185634185635185636185637185638185639185640185641185642185643185644185645185646185647185648185649185650185651185652185653185654185655185656185657185658185659185660185661185662185663185664185665185666185667185668185669185670185671185672185673185674185675185676185677185678185679185680185681185682185683185684185685185686185687185688185689185690185691185692185693185694185695185696185697185698185699185700185701185702185703185704185705185706185707185708185709185710185711185712185713185714185715185716185717185718185719185720185721185722185723185724185725185726185727185728185729185730185731185732185733185734185735185736185737185738185739185740185741185742185743185744185745185746185747185748185749185750185751185752185753185754185755185756185757185758185759185760185761185762185763185764185765185766185767185768185769185770185771185772185773185774185775185776185777185778185779185780185781185782185783185784185785185786185787185788185789185790185791185792185793185794185795185796185797185798185799185800185801185802185803185804185805185806185807185808185809185810185811185812185813185814185815185816185817185818185819185820185821185822185823185824185825185826185827185828185829185830185831185832185833185834185835185836185837185838185839185840185841185842185843185844185845185846185847185848185849185850185851185852185853185854185855185856185857185858185859185860185861185862185863185864185865185866185867185868185869185870185871185872185873185874185875185876185877185878185879185880185881185882185883185884185885185886185887185888185889185890185891185892185893185894185895185896185897185898185899185900185901185902185903185904185905185906185907185908185909185910185911185912185913185914185915185916185917185918185919185920185921185922185923185924185925185926185927185928185929185930185931185932185933185934185935185936185937185938185939185940185941185942185943185944185945185946185947185948185949185950185951185952185953185954185955185956185957185958185959185960185961185962185963185964185965185966185967185968185969185970185971185972185973185974185975185976185977185978185979185980185981185982185983185984185985185986185987185988185989185990185991185992185993185994185995185996185997185998185999186000186001186002186003186004186005186006186007186008186009186010186011186012186013186014186015186016186017186018186019186020186021186022186023186024186025186026186027186028186029186030186031186032186033186034186035186036186037186038186039186040186041186042186043186044186045186046186047186048186049186050186051186052186053186054186055186056186057186058186059186060186061186062186063186064186065186066186067186068186069186070186071186072186073186074186075186076186077186078186079186080186081186082186083186084186085186086186087186088186089186090186091186092186093186094186095186096186097186098186099186100186101186102186103186104186105186106186107186108186109186110186111186112186113186114186115186116186117186118186119186120186121186122186123186124186125186126186127186128186129186130186131186132186133186134186135186136186137186138186139186140186141186142186143186144186145186146186147186148186149186150186151186152186153186154186155186156186157186158186159186160186161186162186163186164186165186166186167186168186169186170186171186172186173186174186175186176186177186178186179186180186181186182186183186184186185186186186187186188186189186190186191186192186193186194186195186196186197186198186199186200186201186202186203186204186205186206186207186208186209186210186211186212186213186214186215186216186217186218186219186220186221186222186223186224186225186226186227186228186229186230186231186232186233186234186235186236186237186238186239186240186241186242186243186244186245186246186247186248186249186250186251186252186253186254186255186256186257186258186259186260186261186262186263186264186265186266186267186268186269186270186271186272186273186274186275186276186277186278186279186280186281186282186283186284186285186286186287186288186289186290186291186292186293186294186295186296186297186298186299186300186301186302186303186304186305186306186307186308186309186310186311186312186313186314186315186316186317186318186319186320186321186322186323186324186325186326186327186328186329186330186331186332186333186334186335186336186337186338186339186340186341186342186343186344186345186346186347186348186349186350186351186352186353186354186355186356186357186358186359186360186361186362186363186364186365186366186367186368186369186370186371186372186373186374186375186376186377186378186379186380186381186382186383186384186385186386186387186388186389186390186391186392186393186394186395186396186397186398186399186400186401186402186403186404186405186406186407186408186409186410186411186412186413186414186415186416186417186418186419186420186421186422186423186424186425186426186427186428186429186430186431186432186433186434186435186436186437186438186439186440186441186442186443186444186445186446186447186448186449186450186451186452186453186454186455186456186457186458186459186460186461186462186463186464186465186466186467186468186469186470186471186472186473186474186475186476186477186478186479186480186481186482186483186484186485186486186487186488186489186490186491186492186493186494186495186496186497186498186499186500186501186502186503186504186505186506186507186508186509186510186511186512186513186514186515186516186517186518186519186520186521186522186523186524186525186526186527186528186529186530186531186532186533186534186535186536186537186538186539186540186541186542186543186544186545186546186547186548186549186550186551186552186553186554186555186556186557186558186559186560186561186562186563186564186565186566186567186568186569186570186571186572186573186574186575186576186577186578186579186580186581186582186583186584186585186586186587186588186589186590186591186592186593186594186595186596186597186598186599186600186601186602186603186604186605186606186607186608186609186610186611186612186613186614186615186616186617186618186619186620186621186622186623186624186625186626186627186628186629186630186631186632186633186634186635186636186637186638186639186640186641186642186643186644186645186646186647186648186649186650186651186652186653186654186655186656186657186658186659186660186661186662186663186664186665186666186667186668186669186670186671186672186673186674186675186676186677186678186679186680186681186682186683186684186685186686186687186688186689186690186691186692186693186694186695186696186697186698186699186700186701186702186703186704186705186706186707186708186709186710186711186712186713186714186715186716186717186718186719186720186721186722186723186724186725186726186727186728186729186730186731186732186733186734186735186736186737186738186739186740186741186742186743186744186745186746186747186748186749186750186751186752186753186754186755186756186757186758186759186760186761186762186763186764186765186766186767186768186769186770186771186772186773186774186775186776186777186778186779186780186781186782186783186784186785186786186787186788186789186790186791186792186793186794186795186796186797186798186799186800186801186802186803186804186805186806186807186808186809186810186811186812186813186814186815186816186817186818186819186820186821186822186823186824186825186826186827186828186829186830186831186832186833186834186835186836186837186838186839186840186841186842186843186844186845186846186847186848186849186850186851186852186853186854186855186856186857186858186859186860186861186862186863186864186865186866186867186868186869186870186871186872186873186874186875186876186877186878186879186880186881186882186883186884186885186886186887186888186889186890186891186892186893186894186895186896186897186898186899186900186901186902186903186904186905186906186907186908186909186910186911186912186913186914186915186916186917186918186919186920186921186922186923186924186925186926186927186928186929186930186931186932186933186934186935186936186937186938186939186940186941186942186943186944186945186946186947186948186949186950186951186952186953186954186955186956186957186958186959186960186961186962186963186964186965186966186967186968186969186970186971186972186973186974186975186976186977186978186979186980186981186982186983186984186985186986186987186988186989186990186991186992186993186994186995186996186997186998186999187000187001187002187003187004187005187006187007187008187009187010187011187012187013187014187015187016187017187018187019187020187021187022187023187024187025187026187027187028187029187030187031187032187033187034187035187036187037187038187039187040187041187042187043187044187045187046187047187048187049187050187051187052187053187054187055187056187057187058187059187060187061187062187063187064187065187066187067187068187069187070187071187072187073187074187075187076187077187078187079187080187081187082187083187084187085187086187087187088187089187090187091187092187093187094187095187096187097187098187099187100187101187102187103187104187105187106187107187108187109187110187111187112187113187114187115187116187117187118187119187120187121187122187123187124187125187126187127187128187129187130187131187132187133187134187135187136187137187138187139187140187141187142187143187144187145187146187147187148187149187150187151187152187153187154187155187156187157187158187159187160187161187162187163187164187165187166187167187168187169187170187171187172187173187174187175187176187177187178187179187180187181187182187183187184187185187186187187187188187189187190187191187192187193187194187195187196187197187198187199187200187201187202187203187204187205187206187207187208187209187210187211187212187213187214187215187216187217187218187219187220187221187222187223187224187225187226187227187228187229187230187231187232187233187234187235187236187237187238187239187240187241187242187243187244187245187246187247187248187249187250187251187252187253187254187255187256187257187258187259187260187261187262187263187264187265187266187267187268187269187270187271187272187273187274187275187276187277187278187279187280187281187282187283187284187285187286187287187288187289187290187291187292187293187294187295187296187297187298187299187300187301187302187303187304187305187306187307187308187309187310187311187312187313187314187315187316187317187318187319187320187321187322187323187324187325187326187327187328187329187330187331187332187333187334187335187336187337187338187339187340187341187342187343187344187345187346187347187348187349187350187351187352187353187354187355187356187357187358187359187360187361187362187363187364187365187366187367187368187369187370187371187372187373187374187375187376187377187378187379187380187381187382187383187384187385187386187387187388187389187390187391187392187393187394187395187396187397187398187399187400187401187402187403187404187405187406187407187408187409187410187411187412187413187414187415187416187417187418187419187420187421187422187423187424187425187426187427187428187429187430187431187432187433187434187435187436187437187438187439187440187441187442187443187444187445187446187447187448187449187450187451187452187453187454187455187456187457187458187459187460187461187462187463187464187465187466187467187468187469187470187471187472187473187474187475187476187477187478187479187480187481187482187483187484187485187486187487187488187489187490187491187492187493187494187495187496187497187498187499187500187501187502187503187504187505187506187507187508187509187510187511187512187513187514187515187516187517187518187519187520187521187522187523187524187525187526187527187528187529187530187531187532187533187534187535187536187537187538187539187540187541187542187543187544187545187546187547187548187549187550187551187552187553187554187555187556187557187558187559187560187561187562187563187564187565187566187567187568187569187570187571187572187573187574187575187576187577187578187579187580187581187582187583187584187585187586187587187588187589187590187591187592187593187594187595187596187597187598187599187600187601187602187603187604187605187606187607187608187609187610187611187612187613187614187615187616187617187618187619187620187621187622187623187624187625187626187627187628187629187630187631187632187633187634187635187636187637187638187639187640187641187642187643187644187645187646187647187648187649187650187651187652187653187654187655187656187657187658187659187660187661187662187663187664187665187666187667187668187669187670187671187672187673187674187675187676187677187678187679187680187681187682187683187684187685187686187687187688187689187690187691187692187693187694187695187696187697187698187699187700187701187702187703187704187705187706187707187708187709187710187711187712187713187714187715187716187717187718187719187720187721187722187723187724187725187726187727187728187729187730187731187732187733187734187735187736187737187738187739187740187741187742187743187744187745187746187747187748187749187750187751187752187753187754187755187756187757187758187759187760187761187762187763187764187765187766187767187768187769187770187771187772187773187774187775187776187777187778187779187780187781187782187783187784187785187786187787187788187789187790187791187792187793187794187795187796187797187798187799187800187801187802187803187804187805187806187807187808187809187810187811187812187813187814187815187816187817187818187819187820187821187822187823187824187825187826187827187828187829187830187831187832187833187834187835187836187837187838187839187840187841187842187843187844187845187846187847187848187849187850187851187852187853187854187855187856187857187858187859187860187861187862187863187864187865187866187867187868187869187870187871187872187873187874187875187876187877187878187879187880187881187882187883187884187885187886187887187888187889187890187891187892187893187894187895187896187897187898187899187900187901187902187903187904187905187906187907187908187909187910187911187912187913187914187915187916187917187918187919187920187921187922187923187924187925187926187927187928187929187930187931187932187933187934187935187936187937187938187939187940187941187942187943187944187945187946187947187948187949187950187951187952187953187954187955187956187957187958187959187960187961187962187963187964187965187966187967187968187969187970187971187972187973187974187975187976187977187978187979187980187981187982187983187984187985187986187987187988187989187990187991187992187993187994187995187996187997187998187999188000188001188002188003188004188005188006188007188008188009188010188011188012188013188014188015188016188017188018188019188020188021188022188023188024188025188026188027188028188029188030188031188032188033188034188035188036188037188038188039188040188041188042188043188044188045188046188047188048188049188050188051188052188053188054188055188056188057188058188059188060188061188062188063188064188065188066188067188068188069188070188071188072188073188074188075188076188077188078188079188080188081188082188083188084188085188086188087188088188089188090188091188092188093188094188095188096188097188098188099188100188101188102188103188104188105188106188107188108188109188110188111188112188113188114188115188116188117188118188119188120188121188122188123188124188125188126188127188128188129188130188131188132188133188134188135188136188137188138188139188140188141188142188143188144188145188146188147188148188149188150188151188152188153188154188155188156188157188158188159188160188161188162188163188164188165188166188167188168188169188170188171188172188173188174188175188176188177188178188179188180188181188182188183188184188185188186188187188188188189188190188191188192188193188194188195188196188197188198188199188200188201188202188203188204188205188206188207188208188209188210188211188212188213188214188215188216188217188218188219188220188221188222188223188224188225188226188227188228188229188230188231188232188233188234188235188236188237188238188239188240188241188242188243188244188245188246188247188248188249188250188251188252188253188254188255188256188257188258188259188260188261188262188263188264188265188266188267188268188269188270188271188272188273188274188275188276188277188278188279188280188281188282188283188284188285188286188287188288188289188290188291188292188293188294188295188296188297188298188299188300188301188302188303188304188305188306188307188308188309188310188311188312188313188314188315188316188317188318188319188320188321188322188323188324188325188326188327188328188329188330188331188332188333188334188335188336188337188338188339188340188341188342188343188344188345188346188347188348188349188350188351188352188353188354188355188356188357188358188359188360188361188362188363188364188365188366188367188368188369188370188371188372188373188374188375188376188377188378188379188380188381188382188383188384188385188386188387188388188389188390188391188392188393188394188395188396188397188398188399188400188401188402188403188404188405188406188407188408188409188410188411188412188413188414188415188416188417188418188419188420188421188422188423188424188425188426188427188428188429188430188431188432188433188434188435188436188437188438188439188440188441188442188443188444188445188446188447188448188449188450188451188452188453188454188455188456188457188458188459188460188461188462188463188464188465188466188467188468188469188470188471188472188473188474188475188476188477188478188479188480188481188482188483188484188485188486188487188488188489188490188491188492188493188494188495188496188497188498188499188500188501188502188503188504188505188506188507188508188509188510188511188512188513188514188515188516188517188518188519188520188521188522188523188524188525188526188527188528188529188530188531188532188533188534188535188536188537188538188539188540188541188542188543188544188545188546188547188548188549188550188551188552188553188554188555188556188557188558188559188560188561188562188563188564188565188566188567188568188569188570188571188572188573188574188575188576188577188578188579188580188581188582188583188584188585188586188587188588188589188590188591188592188593188594188595188596188597188598188599188600188601188602188603188604188605188606188607188608188609188610188611188612188613188614188615188616188617188618188619188620188621188622188623188624188625188626188627188628188629188630188631188632188633188634188635188636188637188638188639188640188641188642188643188644188645188646188647188648188649188650188651188652188653188654188655188656188657188658188659188660188661188662188663188664188665188666188667188668188669188670188671188672188673188674188675188676188677188678188679188680188681188682188683188684188685188686188687188688188689188690188691188692188693188694188695188696188697188698188699188700188701188702188703188704188705188706188707188708188709188710188711188712188713188714188715188716188717188718188719188720188721188722188723188724188725188726188727188728188729188730188731188732188733188734188735188736188737188738188739188740188741188742188743188744188745188746188747188748188749188750188751188752188753188754188755188756188757188758188759188760188761188762188763188764188765188766188767188768188769188770188771188772188773188774188775188776188777188778188779188780188781188782188783188784188785188786188787188788188789188790188791188792188793188794188795188796188797188798188799188800188801188802188803188804188805188806188807188808188809188810188811188812188813188814188815188816188817188818188819188820188821188822188823188824188825188826188827188828188829188830188831188832188833188834188835188836188837188838188839188840188841188842188843188844188845188846188847188848188849188850188851188852188853188854188855188856188857188858188859188860188861188862188863188864188865188866188867188868188869188870188871188872188873188874188875188876188877188878188879188880188881188882188883188884188885188886188887188888188889188890188891188892188893188894188895188896188897188898188899188900188901188902188903188904188905188906188907188908188909188910188911188912188913188914188915188916188917188918188919188920188921188922188923188924188925188926188927188928188929188930188931188932188933188934188935188936188937188938188939188940188941188942188943188944188945188946188947188948188949188950188951188952188953188954188955188956188957188958188959188960188961188962188963188964188965188966188967188968188969188970188971188972188973188974188975188976188977188978188979188980188981188982188983188984188985188986188987188988188989188990188991188992188993188994188995188996188997188998188999189000189001189002189003189004189005189006189007189008189009189010189011189012189013189014189015189016189017189018189019189020189021189022189023189024189025189026189027189028189029189030189031189032189033189034189035189036189037189038189039189040189041189042189043189044189045189046189047189048189049189050189051189052189053189054189055189056189057189058189059189060189061189062189063189064189065189066189067189068189069189070189071189072189073189074189075189076189077189078189079189080189081189082189083189084189085189086189087189088189089189090189091189092189093189094189095189096189097189098189099189100189101189102189103189104189105189106189107189108189109189110189111189112189113189114189115189116189117189118189119189120189121189122189123189124189125189126189127189128189129189130189131189132189133189134189135189136189137189138189139189140189141189142189143189144189145189146189147189148189149189150189151189152189153189154189155189156189157189158189159189160189161189162189163189164189165189166189167189168189169189170189171189172189173189174189175189176189177189178189179189180189181189182189183189184189185189186189187189188189189189190189191189192189193189194189195189196189197189198189199189200189201189202189203189204189205189206189207189208189209189210189211189212189213189214189215189216189217189218189219189220189221189222189223189224189225189226189227189228189229189230189231189232189233189234189235189236189237189238189239189240189241189242189243189244189245189246189247189248189249189250189251189252189253189254189255189256189257189258189259189260189261189262189263189264189265189266189267189268189269189270189271189272189273189274189275189276189277189278189279189280189281189282189283189284189285189286189287189288189289189290189291189292189293189294189295189296189297189298189299189300189301189302189303189304189305189306189307189308189309189310189311189312189313189314189315189316189317189318189319189320189321189322189323189324189325189326189327189328189329189330189331189332189333189334189335189336189337189338189339189340189341189342189343189344189345189346189347189348189349189350189351189352189353189354189355189356189357189358189359189360189361189362189363189364189365189366189367189368189369189370189371189372189373189374189375189376189377189378189379189380189381189382189383189384189385189386189387189388189389189390189391189392189393189394189395189396189397189398189399189400189401189402189403189404189405189406189407189408189409189410189411189412189413189414189415189416189417189418189419189420189421189422189423189424189425189426189427189428189429189430189431189432189433189434189435189436189437189438189439189440189441189442189443189444189445189446189447189448189449189450189451189452189453189454189455189456189457189458189459189460189461189462189463189464189465189466189467189468189469189470189471189472189473189474189475189476189477189478189479189480189481189482189483189484189485189486189487189488189489189490189491189492189493189494189495189496189497189498189499189500189501189502189503189504189505189506189507189508189509189510189511189512189513189514189515189516189517189518189519189520189521189522189523189524189525189526189527189528189529189530189531189532189533189534189535189536189537189538189539189540189541189542189543189544189545189546189547189548189549189550189551189552189553189554189555189556189557189558189559189560189561189562189563189564189565189566189567189568189569189570189571189572189573189574189575189576189577189578189579189580189581189582189583189584189585189586189587189588189589189590189591189592189593189594189595189596189597189598189599189600189601189602189603189604189605189606189607189608189609189610189611189612189613189614189615189616189617189618189619189620189621189622189623189624189625189626189627189628189629189630189631189632189633189634189635189636189637189638189639189640189641189642189643189644189645189646189647189648189649189650189651189652189653189654189655189656189657189658189659189660189661189662189663189664189665189666189667189668189669189670189671189672189673189674189675189676189677189678189679189680189681189682189683189684189685189686189687189688189689189690189691189692189693189694189695189696189697189698189699189700189701189702189703189704189705189706189707189708189709189710189711189712189713189714189715189716189717189718189719189720189721189722189723189724189725189726189727189728189729189730189731189732189733189734189735189736189737189738189739189740189741189742189743189744189745189746189747189748189749189750189751189752189753189754189755189756189757189758189759189760189761189762189763189764189765189766189767189768189769189770189771189772189773189774189775189776189777189778189779189780189781189782189783189784189785189786189787189788189789189790189791189792189793189794189795189796189797189798189799189800189801189802189803189804189805189806189807189808189809189810189811189812189813189814189815189816189817189818189819189820189821189822189823189824189825189826189827189828189829189830189831189832189833189834189835189836189837189838189839189840189841189842189843189844189845189846189847189848189849189850189851189852189853189854189855189856189857189858189859189860189861189862189863189864189865189866189867189868189869189870189871189872189873189874189875189876189877189878189879189880189881189882189883189884189885189886189887189888189889189890189891189892189893189894189895189896189897189898189899189900189901189902189903189904189905189906189907189908189909189910189911189912189913189914189915189916189917189918189919189920189921189922189923189924189925189926189927189928189929189930189931189932189933189934189935189936189937189938189939189940189941189942189943189944189945189946189947189948189949189950189951189952189953189954189955189956189957189958189959189960189961189962189963189964189965189966189967189968189969189970189971189972189973189974189975189976189977189978189979189980189981189982189983189984189985189986189987189988189989189990189991189992189993189994189995189996189997189998189999190000190001190002190003190004190005190006190007190008190009190010190011190012190013190014190015190016190017190018190019190020190021190022190023190024190025190026190027190028190029190030190031190032190033190034190035190036190037190038190039190040190041190042190043190044190045190046190047190048190049190050190051190052190053190054190055190056190057190058190059190060190061190062190063190064190065190066190067190068190069190070190071190072190073190074190075190076190077190078190079190080190081190082190083190084190085190086190087190088190089190090190091190092190093190094190095190096190097190098190099190100190101190102190103190104190105190106190107190108190109190110190111190112190113190114190115190116190117190118190119190120190121190122190123190124190125190126190127190128190129190130190131190132190133190134190135190136190137190138190139190140190141190142190143190144190145190146190147190148190149190150190151190152190153190154190155190156190157190158190159190160190161190162190163190164190165190166190167190168190169190170190171190172190173190174190175190176190177190178190179190180190181190182190183190184190185190186190187190188190189190190190191190192190193190194190195190196190197190198190199190200190201190202190203190204190205190206190207190208190209190210190211190212190213190214190215190216190217190218190219190220190221190222190223190224190225190226190227190228190229190230190231190232190233190234190235190236190237190238190239190240190241190242190243190244190245190246190247190248190249190250190251190252190253190254190255190256190257190258190259190260190261190262190263190264190265190266190267190268190269190270190271190272190273190274190275190276190277190278190279190280190281190282190283190284190285190286190287190288190289190290190291190292190293190294190295190296190297190298190299190300190301190302190303190304190305190306190307190308190309190310190311190312190313190314190315190316190317190318190319190320190321190322190323190324190325190326190327190328190329190330190331190332190333190334190335190336190337190338190339190340190341190342190343190344190345190346190347190348190349190350190351190352190353190354190355190356190357190358190359190360190361190362190363190364190365190366190367190368190369190370190371190372190373190374190375190376190377190378190379190380190381190382190383190384190385190386190387190388190389190390190391190392190393190394190395190396190397190398190399190400190401190402190403190404190405190406190407190408190409190410190411190412190413190414190415190416190417190418190419190420190421190422190423190424190425190426190427190428190429190430190431190432190433190434190435190436190437190438190439190440190441190442190443190444190445190446190447190448190449190450190451190452190453190454190455190456190457190458190459190460190461190462190463190464190465190466190467190468190469190470190471190472190473190474190475190476190477190478190479190480190481190482190483190484190485190486190487190488190489190490190491190492190493190494190495190496190497190498190499190500190501190502190503190504190505190506190507190508190509190510190511190512190513190514190515190516190517190518190519190520190521190522190523190524190525190526190527190528190529190530190531190532190533190534190535190536190537190538190539190540190541190542190543190544190545190546190547190548190549190550190551190552190553190554190555190556190557190558190559190560190561190562190563190564190565190566190567190568190569190570190571190572190573190574190575190576190577190578190579190580190581190582190583190584190585190586190587190588190589190590190591190592190593190594190595190596190597190598190599190600190601190602190603190604190605190606190607190608190609190610190611190612190613190614190615190616190617190618190619190620190621190622190623190624190625190626190627190628190629190630190631190632190633190634190635190636190637190638190639190640190641190642190643190644190645190646190647190648190649190650190651190652190653190654190655190656190657190658190659190660190661190662190663190664190665190666190667190668190669190670190671190672190673190674190675190676190677190678190679190680190681190682190683190684190685190686190687190688190689190690190691190692190693190694190695190696190697190698190699190700190701190702190703190704190705190706190707190708190709190710190711190712190713190714190715190716190717190718190719190720190721190722190723190724190725190726190727190728190729190730190731190732190733190734190735190736190737190738190739190740190741190742190743190744190745190746190747190748190749190750190751190752190753190754190755190756190757190758190759190760190761190762190763190764190765190766190767190768190769190770190771190772190773190774190775190776190777190778190779190780190781190782190783190784190785190786190787190788190789190790190791190792190793190794190795190796190797190798190799190800190801190802190803190804190805190806190807190808190809190810190811190812190813190814190815190816190817190818190819190820190821190822190823190824190825190826190827190828190829190830190831190832190833190834190835190836190837190838190839190840190841190842190843190844190845190846190847190848190849190850190851190852190853190854190855190856190857190858190859190860190861190862190863190864190865190866190867190868190869190870190871190872190873190874190875190876190877190878190879190880190881190882190883190884190885190886190887190888190889190890190891190892190893190894190895190896190897190898190899190900190901190902190903190904190905190906190907190908190909190910190911190912190913190914190915190916190917190918190919190920190921190922190923190924190925190926190927190928190929190930190931190932190933190934190935190936190937190938190939190940190941190942190943190944190945190946190947190948190949190950190951190952190953190954190955190956190957190958190959190960190961190962190963190964190965190966190967190968190969190970190971190972190973190974190975190976190977190978190979190980190981190982190983190984190985190986190987190988190989190990190991190992190993190994190995190996190997190998190999191000191001191002191003191004191005191006191007191008191009191010191011191012191013191014191015191016191017191018191019191020191021191022191023191024191025191026191027191028191029191030191031191032191033191034191035191036191037191038191039191040191041191042191043191044191045191046191047191048191049191050191051191052191053191054191055191056191057191058191059191060191061191062191063191064191065191066191067191068191069191070191071191072191073191074191075191076191077191078191079191080191081191082191083191084191085191086191087191088191089191090191091191092191093191094191095191096191097191098191099191100191101191102191103191104191105191106191107191108191109191110191111191112191113191114191115191116191117191118191119191120191121191122191123191124191125191126191127191128191129191130191131191132191133191134191135191136191137191138191139191140191141191142191143191144191145191146191147191148191149191150191151191152191153191154191155191156191157191158191159191160191161191162191163191164191165191166191167191168191169191170191171191172191173191174191175191176191177191178191179191180191181191182191183191184191185191186191187191188191189191190191191191192191193191194191195191196191197191198191199191200191201191202191203191204191205191206191207191208191209191210191211191212191213191214191215191216191217191218191219191220191221191222191223191224191225191226191227191228191229191230191231191232191233191234191235191236191237191238191239191240191241191242191243191244191245191246191247191248191249191250191251191252191253191254191255191256191257191258191259191260191261191262191263191264191265191266191267191268191269191270191271191272191273191274191275191276191277191278191279191280191281191282191283191284191285191286191287191288191289191290191291191292191293191294191295191296191297191298191299191300191301191302191303191304191305191306191307191308191309191310191311191312191313191314191315191316191317191318191319191320191321191322191323191324191325191326191327191328191329191330191331191332191333191334191335191336191337191338191339191340191341191342191343191344191345191346191347191348191349191350191351191352191353191354191355191356191357191358191359191360191361191362191363191364191365191366191367191368191369191370191371191372191373191374191375191376191377191378191379191380191381191382191383191384191385191386191387191388191389191390191391191392191393191394191395191396191397191398191399191400191401191402191403191404191405191406191407191408191409191410191411191412191413191414191415191416191417191418191419191420191421191422191423191424191425191426191427191428191429191430191431191432191433191434191435191436191437191438191439191440191441191442191443191444191445191446191447191448191449191450191451191452191453191454191455191456191457191458191459191460191461191462191463191464191465191466191467191468191469191470191471191472191473191474191475191476191477191478191479191480191481191482191483191484191485191486191487191488191489191490191491191492191493191494191495191496191497191498191499191500191501191502191503191504191505191506191507191508191509191510191511191512191513191514191515191516191517191518191519191520191521191522191523191524191525191526191527191528191529191530191531191532191533191534191535191536191537191538191539191540191541191542191543191544191545191546191547191548191549191550191551191552191553191554191555191556191557191558191559191560191561191562191563191564191565191566191567191568191569191570191571191572191573191574191575191576191577191578191579191580191581191582191583191584191585191586191587191588191589191590191591191592191593191594191595191596191597191598191599191600191601191602191603191604191605191606191607191608191609191610191611191612191613191614191615191616191617191618191619191620191621191622191623191624191625191626191627191628191629191630191631191632191633191634191635191636191637191638191639191640191641191642191643191644191645191646191647191648191649191650191651191652191653191654191655191656191657191658191659191660191661191662191663191664191665191666191667191668191669191670191671191672191673191674191675191676191677191678191679191680191681191682191683191684191685191686191687191688191689191690191691191692191693191694191695191696191697191698191699191700191701191702191703191704191705191706191707191708191709191710191711191712191713191714191715191716191717191718191719191720191721191722191723191724191725191726191727191728191729191730191731191732191733191734191735191736191737191738191739191740191741191742191743191744191745191746191747191748191749191750191751191752191753191754191755191756191757191758191759191760191761191762191763191764191765191766191767191768191769191770191771191772191773191774191775191776191777191778191779191780191781191782191783191784191785191786191787191788191789191790191791191792191793191794191795191796191797191798191799191800191801191802191803191804191805191806191807191808191809191810191811191812191813191814191815191816191817191818191819191820191821191822191823191824191825191826191827191828191829191830191831191832191833191834191835191836191837191838191839191840191841191842191843191844191845191846191847191848191849191850191851191852191853191854191855191856191857191858191859191860191861191862191863191864191865191866191867191868191869191870191871191872191873191874191875191876191877191878191879191880191881191882191883191884191885191886191887191888191889191890191891191892191893191894191895191896191897191898191899191900191901191902191903191904191905191906191907191908191909191910191911191912191913191914191915191916191917191918191919191920191921191922191923191924191925191926191927191928191929191930191931191932191933191934191935191936191937191938191939191940191941191942191943191944191945191946191947191948191949191950191951191952191953191954191955191956191957191958191959191960191961191962191963191964191965191966191967191968191969191970191971191972191973191974191975191976191977191978191979191980191981191982191983191984191985191986191987191988191989191990191991191992191993191994191995191996191997191998191999192000192001192002192003192004192005192006192007192008192009192010192011192012192013192014192015192016192017192018192019192020192021192022192023192024192025192026192027192028192029192030192031192032192033192034192035192036192037192038192039192040192041192042192043192044192045192046192047192048192049192050192051192052192053192054192055192056192057192058192059192060192061192062192063192064192065192066192067192068192069192070192071192072192073192074192075192076192077192078192079192080192081192082192083192084192085192086192087192088192089192090192091192092192093192094192095192096192097192098192099192100192101192102192103192104192105192106192107192108192109192110192111192112192113192114192115192116192117192118192119192120192121192122192123192124192125192126192127192128192129192130192131192132192133192134192135192136192137192138192139192140192141192142192143192144192145192146192147192148192149192150192151192152192153192154192155192156192157192158192159192160192161192162192163192164192165192166192167192168192169192170192171192172192173192174192175192176192177192178192179192180192181192182192183192184192185192186192187192188192189192190192191192192192193192194192195192196192197192198192199192200192201192202192203192204192205192206192207192208192209192210192211192212192213192214192215192216192217192218192219192220192221192222192223192224192225192226192227192228192229192230192231192232192233192234192235192236192237192238192239192240192241192242192243192244192245192246192247192248192249192250192251192252192253192254192255192256192257192258192259192260192261192262192263192264192265192266192267192268192269192270192271192272192273192274192275192276192277192278192279192280192281192282192283192284192285192286192287192288192289192290192291192292192293192294192295192296192297192298192299192300192301192302192303192304192305192306192307192308192309192310192311192312192313192314192315192316192317192318192319192320192321192322192323192324192325192326192327192328192329192330192331192332192333192334192335192336192337192338192339192340192341192342192343192344192345192346192347192348192349192350192351192352192353192354192355192356192357192358192359192360192361192362192363192364192365192366192367192368192369192370192371192372192373192374192375192376192377192378192379192380192381192382192383192384192385192386192387192388192389192390192391192392192393192394192395192396192397192398192399192400192401192402192403192404192405192406192407192408192409192410192411192412192413192414192415192416192417192418192419192420192421192422192423192424192425192426192427192428192429192430192431192432192433192434192435192436192437192438192439192440192441192442192443192444192445192446192447192448192449192450192451192452192453192454192455192456192457192458192459192460192461192462192463192464192465192466192467192468192469192470192471192472192473192474192475192476192477192478192479192480192481192482192483192484192485192486192487192488192489192490192491192492192493192494192495192496192497192498192499192500192501192502192503192504192505192506192507192508192509192510192511192512192513192514192515192516192517192518192519192520192521192522192523192524192525192526192527192528192529192530192531192532192533192534192535192536192537192538192539192540192541192542192543192544192545192546192547192548192549192550192551192552192553192554192555192556192557192558192559192560192561192562192563192564192565192566192567192568192569192570192571192572192573192574192575192576192577192578192579192580192581192582192583192584192585192586192587192588192589192590192591192592192593192594192595192596192597192598192599192600192601192602192603192604192605192606192607192608192609192610192611192612192613192614192615192616192617192618192619192620192621192622192623192624192625192626192627192628192629192630192631192632192633192634192635192636192637192638192639192640192641192642192643192644192645192646192647192648192649192650192651192652192653192654192655192656192657192658192659192660192661192662192663192664192665192666192667192668192669192670192671192672192673192674192675192676192677192678192679192680192681192682192683192684192685192686192687192688192689192690192691192692192693192694192695192696192697192698192699192700192701192702192703192704192705192706192707192708192709192710192711192712192713192714192715192716192717192718192719192720192721192722192723192724192725192726192727192728192729192730192731192732192733192734192735192736192737192738192739192740192741192742192743192744192745192746192747192748192749192750192751192752192753192754192755192756192757192758192759192760192761192762192763192764192765192766192767192768192769192770192771192772192773192774192775192776192777192778192779192780192781192782192783192784192785192786192787192788192789192790192791192792192793192794192795192796192797192798192799192800192801192802192803192804192805192806192807192808192809192810192811192812192813192814192815192816192817192818192819192820192821192822192823192824192825192826192827192828192829192830192831192832192833192834192835192836192837192838192839192840192841192842192843192844192845192846192847192848192849192850192851192852192853192854192855192856192857192858192859192860192861192862192863192864192865192866192867192868192869192870192871192872192873192874192875192876192877192878192879192880192881192882192883192884192885192886192887192888192889192890192891192892192893192894192895192896192897192898192899192900192901192902192903192904192905192906192907192908192909192910192911192912192913192914192915192916192917192918192919192920192921192922192923192924192925192926192927192928192929192930192931192932192933192934192935192936192937192938192939192940192941192942192943192944192945192946192947192948192949192950192951192952192953192954192955192956192957192958192959192960192961192962192963192964192965192966192967192968192969192970192971192972192973192974192975192976192977192978192979192980192981192982192983192984192985192986192987192988192989192990192991192992192993192994192995192996192997192998192999193000193001193002193003193004193005193006193007193008193009193010193011193012193013193014193015193016193017193018193019193020193021193022193023193024193025193026193027193028193029193030193031193032193033193034193035193036193037193038193039193040193041193042193043193044193045193046193047193048193049193050193051193052193053193054193055193056193057193058193059193060193061193062193063193064193065193066193067193068193069193070193071193072193073193074193075193076193077193078193079193080193081193082193083193084193085193086193087193088193089193090193091193092193093193094193095193096193097193098193099193100193101193102193103193104193105193106193107193108193109193110193111193112193113193114193115193116193117193118193119193120193121193122193123193124193125193126193127193128193129193130193131193132193133193134193135193136193137193138193139193140193141193142193143193144193145193146193147193148193149193150193151193152193153193154193155193156193157193158193159193160193161193162193163193164193165193166193167193168193169193170193171193172193173193174193175193176193177193178193179193180193181193182193183193184193185193186193187193188193189193190193191193192193193193194193195193196193197193198193199193200193201193202193203193204193205193206193207193208193209193210193211193212193213193214193215193216193217193218193219193220193221193222193223193224193225193226193227193228193229193230193231193232193233193234193235193236193237193238193239193240193241193242193243193244193245193246193247193248193249193250193251193252193253193254193255193256193257193258193259193260193261193262193263193264193265193266193267193268193269193270193271193272193273193274193275193276193277193278193279193280193281193282193283193284193285193286193287193288193289193290193291193292193293193294193295193296193297193298193299193300193301193302193303193304193305193306193307193308193309193310193311193312193313193314193315193316193317193318193319193320193321193322193323193324193325193326193327193328193329193330193331193332193333193334193335193336193337193338193339193340193341193342193343193344193345193346193347193348193349193350193351193352193353193354193355193356193357193358193359193360193361193362193363193364193365193366193367193368193369193370193371193372193373193374193375193376193377193378193379193380193381193382193383193384193385193386193387193388193389193390193391193392193393193394193395193396193397193398193399193400193401193402193403193404193405193406193407193408193409193410193411193412193413193414193415193416193417193418193419193420193421193422193423193424193425193426193427193428193429193430193431193432193433193434193435193436193437193438193439193440193441193442193443193444193445193446193447193448193449193450193451193452193453193454193455193456193457193458193459193460193461193462193463193464193465193466193467193468193469193470193471193472193473193474193475193476193477193478193479193480193481193482193483193484193485193486193487193488193489193490193491193492193493193494193495193496193497193498193499193500193501193502193503193504193505193506193507193508193509193510193511193512193513193514193515193516193517193518193519193520193521193522193523193524193525193526193527193528193529193530193531193532193533193534193535193536193537193538193539193540193541193542193543193544193545193546193547193548193549193550193551193552193553193554193555193556193557193558193559193560193561193562193563193564193565193566193567193568193569193570193571193572193573193574193575193576193577193578193579193580193581193582193583193584193585193586193587193588193589193590193591193592193593193594193595193596193597193598193599193600193601193602193603193604193605193606193607193608193609193610193611193612193613193614193615193616193617193618193619193620193621193622193623193624193625193626193627193628193629193630193631193632193633193634193635193636193637193638193639193640193641193642193643193644193645193646193647193648193649193650193651193652193653193654193655193656193657193658193659193660193661193662193663193664193665193666193667193668193669193670193671193672193673193674193675193676193677193678193679193680193681193682193683193684193685193686193687193688193689193690193691193692193693193694193695193696193697193698193699193700193701193702193703193704193705193706193707193708193709193710193711193712193713193714193715193716193717193718193719193720193721193722193723193724193725193726193727193728193729193730193731193732193733193734193735193736193737193738193739193740193741193742193743193744193745193746193747193748193749193750193751193752193753193754193755193756193757193758193759193760193761193762193763193764193765193766193767193768193769193770193771193772193773193774193775193776193777193778193779193780193781193782193783193784193785193786193787193788193789193790193791193792193793193794193795193796193797193798193799193800193801193802193803193804193805193806193807193808193809193810193811193812193813193814193815193816193817193818193819193820193821193822193823193824193825193826193827193828193829193830193831193832193833193834193835193836193837193838193839193840193841193842193843193844193845193846193847193848193849193850193851193852193853193854193855193856193857193858193859193860193861193862193863193864193865193866193867193868193869193870193871193872193873193874193875193876193877193878193879193880193881193882193883193884193885193886193887193888193889193890193891193892193893193894193895193896193897193898193899193900193901193902193903193904193905193906193907193908193909193910193911193912193913193914193915193916193917193918193919193920193921193922193923193924193925193926193927193928193929193930193931193932193933193934193935193936193937193938193939193940193941193942193943193944193945193946193947193948193949193950193951193952193953193954193955193956193957193958193959193960193961193962193963193964193965193966193967193968193969193970193971193972193973193974193975193976193977193978193979193980193981193982193983193984193985193986193987193988193989193990193991193992193993193994193995193996193997193998193999194000194001194002194003194004194005194006194007194008194009194010194011194012194013194014194015194016194017194018194019194020194021194022194023194024194025194026194027194028194029194030194031194032194033194034194035194036194037194038194039194040194041194042194043194044194045194046194047194048194049194050194051194052194053194054194055194056194057194058194059194060194061194062194063194064194065194066194067194068194069194070194071194072194073194074194075194076194077194078194079194080194081194082194083194084194085194086194087194088194089194090194091194092194093194094194095194096194097194098194099194100194101194102194103194104194105194106194107194108194109194110194111194112194113194114194115194116194117194118194119194120194121194122194123194124194125194126194127194128194129194130194131194132194133194134194135194136194137194138194139194140194141194142194143194144194145194146194147194148194149194150194151194152194153194154194155194156194157194158194159194160194161194162194163194164194165194166194167194168194169194170194171194172194173194174194175194176194177194178194179194180194181194182194183194184194185194186194187194188194189194190194191194192194193194194194195194196194197194198194199194200194201194202194203194204194205194206194207194208194209194210194211194212194213194214194215194216194217194218194219194220194221194222194223194224194225194226194227194228194229194230194231194232194233194234194235194236194237194238194239194240194241194242194243194244194245194246194247194248194249194250194251194252194253194254194255194256194257194258194259194260194261194262194263194264194265194266194267194268194269194270194271194272194273194274194275194276194277194278194279194280194281194282194283194284194285194286194287194288194289194290194291194292194293194294194295194296194297194298194299194300194301194302194303194304194305194306194307194308194309194310194311194312194313194314194315194316194317194318194319194320194321194322194323194324194325194326194327194328194329194330194331194332194333194334194335194336194337194338194339194340194341194342194343194344194345194346194347194348194349194350194351194352194353194354194355194356194357194358194359194360194361194362194363194364194365194366194367194368194369194370194371194372194373194374194375194376194377194378194379194380194381194382194383194384194385194386194387194388194389194390194391194392194393194394194395194396194397194398194399194400194401194402194403194404194405194406194407194408194409194410194411194412194413194414194415194416194417194418194419194420194421194422194423194424194425194426194427194428194429194430194431194432194433194434194435194436194437194438194439194440194441194442194443194444194445194446194447194448194449194450194451194452194453194454194455194456194457194458194459194460194461194462194463194464194465194466194467194468194469194470194471194472194473194474194475194476194477194478194479194480194481194482194483194484194485194486194487194488194489194490194491194492194493194494194495194496194497194498194499194500194501194502194503194504194505194506194507194508194509194510194511194512194513194514194515194516194517194518194519194520194521194522194523194524194525194526194527194528194529194530194531194532194533194534194535194536194537194538194539194540194541194542194543194544194545194546194547194548194549194550194551194552194553194554194555194556194557194558194559194560194561194562194563194564194565194566194567194568194569194570194571194572194573194574194575194576194577194578194579194580194581194582194583194584194585194586194587194588194589194590194591194592194593194594194595194596194597194598194599194600194601194602194603194604194605194606194607194608194609194610194611194612194613194614194615194616194617194618194619194620194621194622194623194624194625194626194627194628194629194630194631194632194633194634194635194636194637194638194639194640194641194642194643194644194645194646194647194648194649194650194651194652194653194654194655194656194657194658194659194660194661194662194663194664194665194666194667194668194669194670194671194672194673194674194675194676194677194678194679194680194681194682194683194684194685194686194687194688194689194690194691194692194693194694194695194696194697194698194699194700194701194702194703194704194705194706194707194708194709194710194711194712194713194714194715194716194717194718194719194720194721194722194723194724194725194726194727194728194729194730194731194732194733194734194735194736194737194738194739194740194741194742194743194744194745194746194747194748194749194750194751194752194753194754194755194756194757194758194759194760194761194762194763194764194765194766194767194768194769194770194771194772194773194774194775194776194777194778194779194780194781194782194783194784194785194786194787194788194789194790194791194792194793194794194795194796194797194798194799194800194801194802194803194804194805194806194807194808194809194810194811194812194813194814194815194816194817194818194819194820194821194822194823194824194825194826194827194828194829194830194831194832194833194834194835194836194837194838194839194840194841194842194843194844194845194846194847194848194849194850194851194852194853194854194855194856194857194858194859194860194861194862194863194864194865194866194867194868194869194870194871194872194873194874194875194876194877194878194879194880194881194882194883194884194885194886194887194888194889194890194891194892194893194894194895194896194897194898194899194900194901194902194903194904194905194906194907194908194909194910194911194912194913194914194915194916194917194918194919194920194921194922194923194924194925194926194927194928194929194930194931194932194933194934194935194936194937194938194939194940194941194942194943194944194945194946194947194948194949194950194951194952194953194954194955194956194957194958194959194960194961194962194963194964194965194966194967194968194969194970194971194972194973194974194975194976194977194978194979194980194981194982194983194984194985194986194987194988194989194990194991194992194993194994194995194996194997194998194999195000195001195002195003195004195005195006195007195008195009195010195011195012195013195014195015195016195017195018195019195020195021195022195023195024195025195026195027195028195029195030195031195032195033195034195035195036195037195038195039195040195041195042195043195044195045195046195047195048195049195050195051195052195053195054195055195056195057195058195059195060195061195062195063195064195065195066195067195068195069195070195071195072195073195074195075195076195077195078195079195080195081195082195083195084195085195086195087195088195089195090195091195092195093195094195095195096195097195098195099195100195101195102195103195104195105195106195107195108195109195110195111195112195113195114195115195116195117195118195119195120195121195122195123195124195125195126195127195128195129195130195131195132195133195134195135195136195137195138195139195140195141195142195143195144195145195146195147195148195149195150195151195152195153195154195155195156195157195158195159195160195161195162195163195164195165195166195167195168195169195170195171195172195173195174195175195176195177195178195179195180195181195182195183195184195185195186195187195188195189195190195191195192195193195194195195195196195197195198195199195200195201195202195203195204195205195206195207195208195209195210195211195212195213195214195215195216195217195218195219195220195221195222195223195224195225195226195227195228195229195230195231195232195233195234195235195236195237195238195239195240195241195242195243195244195245195246195247195248195249195250195251195252195253195254195255195256195257195258195259195260195261195262195263195264195265195266195267195268195269195270195271195272195273195274195275195276195277195278195279195280195281195282195283195284195285195286195287195288195289195290195291195292195293195294195295195296195297195298195299195300195301195302195303195304195305195306195307195308195309195310195311195312195313195314195315195316195317195318195319195320195321195322195323195324195325195326195327195328195329195330195331195332195333195334195335195336195337195338195339195340195341195342195343195344195345195346195347195348195349195350195351195352195353195354195355195356195357195358195359195360195361195362195363195364195365195366195367195368195369195370195371195372195373195374195375195376195377195378195379195380195381195382195383195384195385195386195387195388195389195390195391195392195393195394195395195396195397195398195399195400195401195402195403195404195405195406195407195408195409195410195411195412195413195414195415195416195417195418195419195420195421195422195423195424195425195426195427195428195429195430195431195432195433195434195435195436195437195438195439195440195441195442195443195444195445195446195447195448195449195450195451195452195453195454195455195456195457195458195459195460195461195462195463195464195465195466195467195468195469195470195471195472195473195474195475195476195477195478195479195480195481195482195483195484195485195486195487195488195489195490195491195492195493195494195495195496195497195498195499195500195501195502195503195504195505195506195507195508195509195510195511195512195513195514195515195516195517195518195519195520195521195522195523195524195525195526195527195528195529195530195531195532195533195534195535195536195537195538195539195540195541195542195543195544195545195546195547195548195549195550195551195552195553195554195555195556195557195558195559195560195561195562195563195564195565195566195567195568195569195570195571195572195573195574195575195576195577195578195579195580195581195582195583195584195585195586195587195588195589195590195591195592195593195594195595195596195597195598195599195600195601195602195603195604195605195606195607195608195609195610195611195612195613195614195615195616195617195618195619195620195621195622195623195624195625195626195627195628195629195630195631195632195633195634195635195636195637195638195639195640195641195642195643195644195645195646195647195648195649195650195651195652195653195654195655195656195657195658195659195660195661195662195663195664195665195666195667195668195669195670195671195672195673195674195675195676195677195678195679195680195681195682195683195684195685195686195687195688195689195690195691195692195693195694195695195696195697195698195699195700195701195702195703195704195705195706195707195708195709195710195711195712195713195714195715195716195717195718195719195720195721195722195723195724195725195726195727195728195729195730195731195732195733195734195735195736195737195738195739195740195741195742195743195744195745195746195747195748195749195750195751195752195753195754195755195756195757195758195759195760195761195762195763195764195765195766195767195768195769195770195771195772195773195774195775195776195777195778195779195780195781195782195783195784195785195786195787195788195789195790195791195792195793195794195795195796195797195798195799195800195801195802195803195804195805195806195807195808195809195810195811195812195813195814195815195816195817195818195819195820195821195822195823195824195825195826195827195828195829195830195831195832195833195834195835195836195837195838195839195840195841195842195843195844195845195846195847195848195849195850195851195852195853195854195855195856195857195858195859195860195861195862195863195864195865195866195867195868195869195870195871195872195873195874195875195876195877195878195879195880195881195882195883195884195885195886195887195888195889195890195891195892195893195894195895195896195897195898195899195900195901195902195903195904195905195906195907195908195909195910195911195912195913195914195915195916195917195918195919195920195921195922195923195924195925195926195927195928195929195930195931195932195933195934195935195936195937195938195939195940195941195942195943195944195945195946195947195948195949195950195951195952195953195954195955195956195957195958195959195960195961195962195963195964195965195966195967195968195969195970195971195972195973195974195975195976195977195978195979195980195981195982195983195984195985195986195987195988195989195990195991195992195993195994195995195996195997195998195999196000196001196002196003196004196005196006196007196008196009196010196011196012196013196014196015196016196017196018196019196020196021196022196023196024196025196026196027196028196029196030196031196032196033196034196035196036196037196038196039196040196041196042196043196044196045196046196047196048196049196050196051196052196053196054196055196056196057196058196059196060196061196062196063196064196065196066196067196068196069196070196071196072196073196074196075196076196077196078196079196080196081196082196083196084196085196086196087196088196089196090196091196092196093196094196095196096196097196098196099196100196101196102196103196104196105196106196107196108196109196110196111196112196113196114196115196116196117196118196119196120196121196122196123196124196125196126196127196128196129196130196131196132196133196134196135196136196137196138196139196140196141196142196143196144196145196146196147196148196149196150196151196152196153196154196155196156196157196158196159196160196161196162196163196164196165196166196167196168196169196170196171196172196173196174196175196176196177196178196179196180196181196182196183196184196185196186196187196188196189196190196191196192196193196194196195196196196197196198196199196200196201196202196203196204196205196206196207196208196209196210196211196212196213196214196215196216196217196218196219196220196221196222196223196224196225196226196227196228196229196230196231196232196233196234196235196236196237196238196239196240196241196242196243196244196245196246196247196248196249196250196251196252196253196254196255196256196257196258196259196260196261196262196263196264196265196266196267196268196269196270196271196272196273196274196275196276196277196278196279196280196281196282196283196284196285196286196287196288196289196290196291196292196293196294196295196296196297196298196299196300196301196302196303196304196305196306196307196308196309196310196311196312196313196314196315196316196317196318196319196320196321196322196323196324196325196326196327196328196329196330196331196332196333196334196335196336196337196338196339196340196341196342196343196344196345196346196347196348196349196350196351196352196353196354196355196356196357196358196359196360196361196362196363196364196365196366196367196368196369196370196371196372196373196374196375196376196377196378196379196380196381196382196383196384196385196386196387196388196389196390196391196392196393196394196395196396196397196398196399196400196401196402196403196404196405196406196407196408196409196410196411196412196413196414196415196416196417196418196419196420196421196422196423196424196425196426196427196428196429196430196431196432196433196434196435196436196437196438196439196440196441196442196443196444196445196446196447196448196449196450196451196452196453196454196455196456196457196458196459196460196461196462196463196464196465196466196467196468196469196470196471196472196473196474196475196476196477196478196479196480196481196482196483196484196485196486196487196488196489196490196491196492196493196494196495196496196497196498196499196500196501196502196503196504196505196506196507196508196509196510196511196512196513196514196515196516196517196518196519196520196521196522196523196524196525196526196527196528196529196530196531196532196533196534196535196536196537196538196539196540196541196542196543196544196545196546196547196548196549196550196551196552196553196554196555196556196557196558196559196560196561196562196563196564196565196566196567196568196569196570196571196572196573196574196575196576196577196578196579196580196581196582196583196584196585196586196587196588196589196590196591196592196593196594196595196596196597196598196599196600196601196602196603196604196605196606196607196608196609196610196611196612196613196614196615196616196617196618196619196620196621196622196623196624196625196626196627196628196629196630196631196632196633196634196635196636196637196638196639196640196641196642196643196644196645196646196647196648196649196650196651196652196653196654196655196656196657196658196659196660196661196662196663196664196665196666196667196668196669196670196671196672196673196674196675196676196677196678196679196680196681196682196683196684196685196686196687196688196689196690196691196692196693196694196695196696196697196698196699196700196701196702196703196704196705196706196707196708196709196710196711196712196713196714196715196716196717196718196719196720196721196722196723196724196725196726196727196728196729196730196731196732196733196734196735196736196737196738196739196740196741196742196743196744196745196746196747196748196749196750196751196752196753196754196755196756196757196758196759196760196761196762196763196764196765196766196767196768196769196770196771196772196773196774196775196776196777196778196779196780196781196782196783196784196785196786196787196788196789196790196791196792196793196794196795196796196797196798196799196800196801196802196803196804196805196806196807196808196809196810196811196812196813196814196815196816196817196818196819196820196821196822196823196824196825196826196827196828196829196830196831196832196833196834196835196836196837196838196839196840196841196842196843196844196845196846196847196848196849196850196851196852196853196854196855196856196857196858196859196860196861196862196863196864196865196866196867196868196869196870196871196872196873196874196875196876196877196878196879196880196881196882196883196884196885196886196887196888196889196890196891196892196893196894196895196896196897196898196899196900196901196902196903196904196905196906196907196908196909196910196911196912196913196914196915196916196917196918196919196920196921196922196923196924196925196926196927196928196929196930196931196932196933196934196935196936196937196938196939196940196941196942196943196944196945196946196947196948196949196950196951196952196953196954196955196956196957196958196959196960196961196962196963196964196965196966196967196968196969196970196971196972196973196974196975196976196977196978196979196980196981196982196983196984196985196986196987196988196989196990196991196992196993196994196995196996196997196998196999197000197001197002197003197004197005197006197007197008197009197010197011197012197013197014197015197016197017197018197019197020197021197022197023197024197025197026197027197028197029197030197031197032197033197034197035197036197037197038197039197040197041197042197043197044197045197046197047197048197049197050197051197052197053197054197055197056197057197058197059197060197061197062197063197064197065197066197067197068197069197070197071197072197073197074197075197076197077197078197079197080197081197082197083197084197085197086197087197088197089197090197091197092197093197094197095197096197097197098197099197100197101197102197103197104197105197106197107197108197109197110197111197112197113197114197115197116197117197118197119197120197121197122197123197124197125197126197127197128197129197130197131197132197133197134197135197136197137197138197139197140197141197142197143197144197145197146197147197148197149197150197151197152197153197154197155197156197157197158197159197160197161197162197163197164197165197166197167197168197169197170197171197172197173197174197175197176197177197178197179197180197181197182197183197184197185197186197187197188197189197190197191197192197193197194197195197196197197197198197199197200197201197202197203197204197205197206197207197208197209197210197211197212197213197214197215197216197217197218197219197220197221197222197223197224197225197226197227197228197229197230197231197232197233197234197235197236197237197238197239197240197241197242197243197244197245197246197247197248197249197250197251197252197253197254197255197256197257197258197259197260197261197262197263197264197265197266197267197268197269197270197271197272197273197274197275197276197277197278197279197280197281197282197283197284197285197286197287197288197289197290197291197292197293197294197295197296197297197298197299197300197301197302197303197304197305197306197307197308197309197310197311197312197313197314197315197316197317197318197319197320197321197322197323197324197325197326197327197328197329197330197331197332197333197334197335197336197337197338197339197340197341197342197343197344197345197346197347197348197349197350197351197352197353197354197355197356197357197358197359197360197361197362197363197364197365197366197367197368197369197370197371197372197373197374197375197376197377197378197379197380197381197382197383197384197385197386197387197388197389197390197391197392197393197394197395197396197397197398197399197400197401197402197403197404197405197406197407197408197409197410197411197412197413197414197415197416197417197418197419197420197421197422197423197424197425197426197427197428197429197430197431197432197433197434197435197436197437197438197439197440197441197442197443197444197445197446197447197448197449197450197451197452197453197454197455197456197457197458197459197460197461197462197463197464197465197466197467197468197469197470197471197472197473197474197475197476197477197478197479197480197481197482197483197484197485197486197487197488197489197490197491197492197493197494197495197496197497197498197499197500197501197502197503197504197505197506197507197508197509197510197511197512197513197514197515197516197517197518197519197520197521197522197523197524197525197526197527197528197529197530197531197532197533197534197535197536197537197538197539197540197541197542197543197544197545197546197547197548197549197550197551197552197553197554197555197556197557197558197559197560197561197562197563197564197565197566197567197568197569197570197571197572197573197574197575197576197577197578197579197580197581197582197583197584197585197586197587197588197589197590197591197592197593197594197595197596197597197598197599197600197601197602197603197604197605197606197607197608197609197610197611197612197613197614197615197616197617197618197619197620197621197622197623197624197625197626197627197628197629197630197631197632197633197634197635197636197637197638197639197640197641197642197643197644197645197646197647197648197649197650197651197652197653197654197655197656197657197658197659197660197661197662197663197664197665197666197667197668197669197670197671197672197673197674197675197676197677197678197679197680197681197682197683197684197685197686197687197688197689197690197691197692197693197694197695197696197697197698197699197700197701197702197703197704197705197706197707197708197709197710197711197712197713197714197715197716197717197718197719197720197721197722197723197724197725197726197727197728197729197730197731197732197733197734197735197736197737197738197739197740197741197742197743197744197745197746197747197748197749197750197751197752197753197754197755197756197757197758197759197760197761197762197763197764197765197766197767197768197769197770197771197772197773197774197775197776197777197778197779197780197781197782197783197784197785197786197787197788197789197790197791197792197793197794197795197796197797197798197799197800197801197802197803197804197805197806197807197808197809197810197811197812197813197814197815197816197817197818197819197820197821197822197823197824197825197826197827197828197829197830197831197832197833197834197835197836197837197838197839197840197841197842197843197844197845197846197847197848197849197850197851197852197853197854197855197856197857197858197859197860197861197862197863197864197865197866197867197868197869197870197871197872197873197874197875197876197877197878197879197880197881197882197883197884197885197886197887197888197889197890197891197892197893197894197895197896197897197898197899197900197901197902197903197904197905197906197907197908197909197910197911197912197913197914197915197916197917197918197919197920197921197922197923197924197925197926197927197928197929197930197931197932197933197934197935197936197937197938197939197940197941197942197943197944197945197946197947197948197949197950197951197952197953197954197955197956197957197958197959197960197961197962197963197964197965197966197967197968197969197970197971197972197973197974197975197976197977197978197979197980197981197982197983197984197985197986197987197988197989197990197991197992197993197994197995197996197997197998197999198000198001198002198003198004198005198006198007198008198009198010198011198012198013198014198015198016198017198018198019198020198021198022198023198024198025198026198027198028198029198030198031198032198033198034198035198036198037198038198039198040198041198042198043198044198045198046198047198048198049198050198051198052198053198054198055198056198057198058198059198060198061198062198063198064198065198066198067198068198069198070198071198072198073198074198075198076198077198078198079198080198081198082198083198084198085198086198087198088198089198090198091198092198093198094198095198096198097198098198099198100198101198102198103198104198105198106198107198108198109198110198111198112198113198114198115198116198117198118198119198120198121198122198123198124198125198126198127198128198129198130198131198132198133198134198135198136198137198138198139198140198141198142198143198144198145198146198147198148198149198150198151198152198153198154198155198156198157198158198159198160198161198162198163198164198165198166198167198168198169198170198171198172198173198174198175198176198177198178198179198180198181198182198183198184198185198186198187198188198189198190198191198192198193198194198195198196198197198198198199198200198201198202198203198204198205198206198207198208198209198210198211198212198213198214198215198216198217198218198219198220198221198222198223198224198225198226198227198228198229198230198231198232198233198234198235198236198237198238198239198240198241198242198243198244198245198246198247198248198249198250198251198252198253198254198255198256198257198258198259198260198261198262198263198264198265198266198267198268198269198270198271198272198273198274198275198276198277198278198279198280198281198282198283198284198285198286198287198288198289198290198291198292198293198294198295198296198297198298198299198300198301198302198303198304198305198306198307198308198309198310198311198312198313198314198315198316198317198318198319198320198321198322198323198324198325198326198327198328198329198330198331198332198333198334198335198336198337198338198339198340198341198342198343198344198345198346198347198348198349198350198351198352198353198354198355198356198357198358198359198360198361198362198363198364198365198366198367198368198369198370198371198372198373198374198375198376198377198378198379198380198381198382198383198384198385198386198387198388198389198390198391198392198393198394198395198396198397198398198399198400198401198402198403198404198405198406198407198408198409198410198411198412198413198414198415198416198417198418198419198420198421198422198423198424198425198426198427198428198429198430198431198432198433198434198435198436198437198438198439198440198441198442198443198444198445198446198447198448198449198450198451198452198453198454198455198456198457198458198459198460198461198462198463198464198465198466198467198468198469198470198471198472198473198474198475198476198477198478198479198480198481198482198483198484198485198486198487198488198489198490198491198492198493198494198495198496198497198498198499198500198501198502198503198504198505198506198507198508198509198510198511198512198513198514198515198516198517198518198519198520198521198522198523198524198525198526198527198528198529198530198531198532198533198534198535198536198537198538198539198540198541198542198543198544198545198546198547198548198549198550198551198552198553198554198555198556198557198558198559198560198561198562198563198564198565198566198567198568198569198570198571198572198573198574198575198576198577198578198579198580198581198582198583198584198585198586198587198588198589198590198591198592198593198594198595198596198597198598198599198600198601198602198603198604198605198606198607198608198609198610198611198612198613198614198615198616198617198618198619198620198621198622198623198624198625198626198627198628198629198630198631198632198633198634198635198636198637198638198639198640198641198642198643198644198645198646198647198648198649198650198651198652198653198654198655198656198657198658198659198660198661198662198663198664198665198666198667198668198669198670198671198672198673198674198675198676198677198678198679198680198681198682198683198684198685198686198687198688198689198690198691198692198693198694198695198696198697198698198699198700198701198702198703198704198705198706198707198708198709198710198711198712198713198714198715198716198717198718198719198720198721198722198723198724198725198726198727198728198729198730198731198732198733198734198735198736198737198738198739198740198741198742198743198744198745198746198747198748198749198750198751198752198753198754198755198756198757198758198759198760198761198762198763198764198765198766198767198768198769198770198771198772198773198774198775198776198777198778198779198780198781198782198783198784198785198786198787198788198789198790198791198792198793198794198795198796198797198798198799198800198801198802198803198804198805198806198807198808198809198810198811198812198813198814198815198816198817198818198819198820198821198822198823198824198825198826198827198828198829198830198831198832198833198834198835198836198837198838198839198840198841198842198843198844198845198846198847198848198849198850198851198852198853198854198855198856198857198858198859198860198861198862198863198864198865198866198867198868198869198870198871198872198873198874198875198876198877198878198879198880198881198882198883198884198885198886198887198888198889198890198891198892198893198894198895198896198897198898198899198900198901198902198903198904198905198906198907198908198909198910198911198912198913198914198915198916198917198918198919198920198921198922198923198924198925198926198927198928198929198930198931198932198933198934198935198936198937198938198939198940198941198942198943198944198945198946198947198948198949198950198951198952198953198954198955198956198957198958198959198960198961198962198963198964198965198966198967198968198969198970198971198972198973198974198975198976198977198978198979198980198981198982198983198984198985198986198987198988198989198990198991198992198993198994198995198996198997198998198999199000199001199002199003199004199005199006199007199008199009199010199011199012199013199014199015199016199017199018199019199020199021199022199023199024199025199026199027199028199029199030199031199032199033199034199035199036199037199038199039199040199041199042199043199044199045199046199047199048199049199050199051199052199053199054199055199056199057199058199059199060199061199062199063199064199065199066199067199068199069199070199071199072199073199074199075199076199077199078199079199080199081199082199083199084199085199086199087199088199089199090199091199092199093199094199095199096199097199098199099199100199101199102199103199104199105199106199107199108199109199110199111199112199113199114199115199116199117199118199119199120199121199122199123199124199125199126199127199128199129199130199131199132199133199134199135199136199137199138199139199140199141199142199143199144199145199146199147199148199149199150199151199152199153199154199155199156199157199158199159199160199161199162199163199164199165199166199167199168199169199170199171199172199173199174199175199176199177199178199179199180199181199182199183199184199185199186199187199188199189199190199191199192199193199194199195199196199197199198199199199200199201199202199203199204199205199206199207199208199209199210199211199212199213199214199215199216199217199218199219199220199221199222199223199224199225199226199227199228199229199230199231199232199233199234199235199236199237199238199239199240199241199242199243199244199245199246199247199248199249199250199251199252199253199254199255199256199257199258199259199260199261199262199263199264199265199266199267199268199269199270199271199272199273199274199275199276199277199278199279199280199281199282199283199284199285199286199287199288199289199290199291199292199293199294199295199296199297199298199299199300199301199302199303199304199305199306199307199308199309199310199311199312199313199314199315199316199317199318199319199320199321199322199323199324199325199326199327199328199329199330199331199332199333199334199335199336199337199338199339199340199341199342199343199344199345199346199347199348199349199350199351199352199353199354199355199356199357199358199359199360199361199362199363199364199365199366199367199368199369199370199371199372199373199374199375199376199377199378199379199380199381199382199383199384199385199386199387199388199389199390199391199392199393199394199395199396199397199398199399199400199401199402199403199404199405199406199407199408199409199410199411199412199413199414199415199416199417199418199419199420199421199422199423199424199425199426199427199428199429199430199431199432199433199434199435199436199437199438199439199440199441199442199443199444199445199446199447199448199449199450199451199452199453199454199455199456199457199458199459199460199461199462199463199464199465199466199467199468199469199470199471199472199473199474199475199476199477199478199479199480199481199482199483199484199485199486199487199488199489199490199491199492199493199494199495199496199497199498199499199500199501199502199503199504199505199506199507199508199509199510199511199512199513199514199515199516199517199518199519199520199521199522199523199524199525199526199527199528199529199530199531199532199533199534199535199536199537199538199539199540199541199542199543199544199545199546199547199548199549199550199551199552199553199554199555199556199557199558199559199560199561199562199563199564199565199566199567199568199569199570199571199572199573199574199575199576199577199578199579199580199581199582199583199584199585199586199587199588199589199590199591199592199593199594199595199596199597199598199599199600199601199602199603199604199605199606199607199608199609199610199611199612199613199614199615199616199617199618199619199620199621199622199623199624199625199626199627199628199629199630199631199632199633199634199635199636199637199638199639199640199641199642199643199644199645199646199647199648199649199650199651199652199653199654199655199656199657199658199659199660199661199662199663199664199665199666199667199668199669199670199671199672199673199674199675199676199677199678199679199680199681199682199683199684199685199686199687199688199689199690199691199692199693199694199695199696199697199698199699199700199701199702199703199704199705199706199707199708199709199710199711199712199713199714199715199716199717199718199719199720199721199722199723199724199725199726199727199728199729199730199731199732199733199734199735199736199737199738199739199740199741199742199743199744199745199746199747199748199749199750199751199752199753199754199755199756199757199758199759199760199761199762199763199764199765199766199767199768199769199770199771199772199773199774199775199776199777199778199779199780199781199782199783199784199785199786199787199788199789199790199791199792199793199794199795199796199797199798199799199800199801199802199803199804199805199806199807199808199809199810199811199812199813199814199815199816199817199818199819199820199821199822199823199824199825199826199827199828199829199830199831199832199833199834199835199836199837199838199839199840199841199842199843199844199845199846199847199848199849199850199851199852199853199854199855199856199857199858199859199860199861199862199863199864199865199866199867199868199869199870199871199872199873199874199875199876199877199878199879199880199881199882199883199884199885199886199887199888199889199890199891199892199893199894199895199896199897199898199899199900199901199902199903199904199905199906199907199908199909199910199911199912199913199914199915199916199917199918199919199920199921199922199923199924199925199926199927199928199929199930199931199932199933199934199935199936199937199938199939199940199941199942199943199944199945199946199947199948199949199950199951199952199953199954199955199956199957199958199959199960199961199962199963199964199965199966199967199968199969199970199971199972199973199974199975199976199977199978199979199980199981199982199983199984199985199986199987199988199989199990199991199992199993199994199995199996199997199998199999200000200001200002200003200004200005200006200007200008200009200010200011200012200013200014200015200016200017200018200019200020200021200022200023200024200025200026200027200028200029200030200031200032200033200034200035200036200037200038200039200040200041200042200043200044200045200046200047200048200049200050200051200052200053200054200055200056200057200058200059200060200061200062200063200064200065200066200067200068200069200070200071200072200073200074200075200076200077200078200079200080200081200082200083200084200085200086200087200088200089200090200091200092200093200094200095200096200097200098200099200100200101200102200103200104200105200106200107200108200109200110200111200112200113200114200115200116200117200118200119200120200121200122200123200124200125200126200127200128200129200130200131200132200133200134200135200136200137200138200139200140200141200142200143200144200145200146200147200148200149200150200151200152200153200154200155200156200157200158200159200160200161200162200163200164200165200166200167200168200169200170200171200172200173200174200175200176200177200178200179200180200181200182200183200184200185200186200187200188200189200190200191200192200193200194200195200196200197200198200199200200200201200202200203200204200205200206200207200208200209200210200211200212200213200214200215200216200217200218200219200220200221200222200223200224200225200226200227200228200229200230200231200232200233200234200235200236200237200238200239200240200241200242200243200244200245200246200247200248200249200250200251200252200253200254200255200256200257200258200259200260200261200262200263200264200265200266200267200268200269200270200271200272200273200274200275200276200277200278200279200280200281200282200283200284200285200286200287200288200289200290200291200292200293200294200295200296200297200298200299200300200301200302200303200304200305200306200307200308200309200310200311200312200313200314200315200316200317200318200319200320200321200322200323200324200325200326200327200328200329200330200331200332200333200334200335200336200337200338200339200340200341200342200343200344200345200346200347200348200349200350200351200352200353200354200355200356200357200358200359200360200361200362200363200364200365200366200367200368200369200370200371200372200373200374200375200376200377200378200379200380200381200382200383200384200385200386200387200388200389200390200391200392200393200394200395200396200397200398200399200400200401200402200403200404200405200406200407200408200409200410200411200412200413200414200415200416200417200418200419200420200421200422200423200424200425200426200427200428200429200430200431200432200433200434200435200436200437200438200439200440200441200442200443200444200445200446200447200448200449200450200451200452200453200454200455200456200457200458200459200460200461200462200463200464200465200466200467200468200469200470200471200472200473200474200475200476200477200478200479200480200481200482200483200484200485200486200487200488200489200490200491200492200493200494200495200496200497200498200499200500200501200502200503200504200505200506200507200508200509200510200511200512200513200514200515200516200517200518200519200520200521200522200523200524200525200526200527200528200529200530200531200532200533200534200535200536200537200538200539200540200541200542200543200544200545200546200547200548200549200550200551200552200553200554200555200556200557200558200559200560200561200562200563200564200565200566200567200568200569200570200571200572200573200574200575200576200577200578200579200580200581200582200583200584200585200586200587200588200589200590200591200592200593200594200595200596200597200598200599200600200601200602200603200604200605200606200607200608200609200610200611200612200613200614200615200616200617200618200619200620200621200622200623200624200625200626200627200628200629200630200631200632200633200634200635200636200637200638200639200640200641200642200643200644200645200646200647200648200649200650200651200652200653200654200655200656200657200658200659200660200661200662200663200664200665200666200667200668200669200670200671200672200673200674200675200676200677200678200679200680200681200682200683200684200685200686200687200688200689200690200691200692200693200694200695200696200697200698200699200700200701200702200703200704200705200706200707200708200709200710200711200712200713200714200715200716200717200718200719200720200721200722200723200724200725200726200727200728200729200730200731200732200733200734200735200736200737200738200739200740200741200742200743200744200745200746200747200748200749200750200751200752200753200754200755200756200757200758200759200760200761200762200763200764200765200766200767200768200769200770200771200772200773200774200775200776200777200778200779200780200781200782200783200784200785200786200787200788200789200790200791200792200793200794200795200796200797200798200799200800200801200802200803200804200805200806200807200808200809200810200811200812200813200814200815200816200817200818200819200820200821200822200823200824200825200826200827200828200829200830200831200832200833200834200835200836200837200838200839200840200841200842200843200844200845200846200847200848200849200850200851200852200853200854200855200856200857200858200859200860200861200862200863200864200865200866200867200868200869200870200871200872200873200874200875200876200877200878200879200880200881200882200883200884200885200886200887200888200889200890200891200892200893200894200895200896200897200898200899200900200901200902200903200904200905200906200907200908200909200910200911200912200913200914200915200916200917200918200919200920200921200922200923200924200925200926200927200928200929200930200931200932200933200934200935200936200937200938200939200940200941200942200943200944200945200946200947200948200949200950200951200952200953200954200955200956200957200958200959200960200961200962200963200964200965200966200967200968200969200970200971200972200973200974200975200976200977200978200979200980200981200982200983200984200985200986200987200988200989200990200991200992200993200994200995200996200997200998200999201000201001201002201003201004201005201006201007201008201009201010201011201012201013201014201015201016201017201018201019201020201021201022201023201024201025201026201027201028201029201030201031201032201033201034201035201036201037201038201039201040201041201042201043201044201045201046201047201048201049201050201051201052201053201054201055201056201057201058201059201060201061201062201063201064201065201066201067201068201069201070201071201072201073201074201075201076201077201078201079201080201081201082201083201084201085201086201087201088201089201090201091201092201093201094201095201096201097201098201099201100201101201102201103201104201105201106201107201108201109201110201111201112201113201114201115201116201117201118201119201120201121201122201123201124201125201126201127201128201129201130201131201132201133201134201135201136201137201138201139201140201141201142201143201144201145201146201147201148201149201150201151201152201153201154201155201156201157201158201159201160201161201162201163201164201165201166201167201168201169201170201171201172201173201174201175201176201177201178201179201180201181201182201183201184201185201186201187201188201189201190201191201192201193201194201195201196201197201198201199201200201201201202201203201204201205201206201207201208201209201210201211201212201213201214201215201216201217201218201219201220201221201222201223201224201225201226201227201228201229201230201231201232201233201234201235201236201237201238201239201240201241201242201243201244201245201246201247201248201249201250201251201252201253201254201255201256201257201258201259201260201261201262201263201264201265201266201267201268201269201270201271201272201273201274201275201276201277201278201279201280201281201282201283201284201285201286201287201288201289201290201291201292201293201294201295201296201297201298201299201300201301201302201303201304201305201306201307201308201309201310201311201312201313201314201315201316201317201318201319201320201321201322201323201324201325201326201327201328201329201330201331201332201333201334201335201336201337201338201339201340201341201342201343201344201345201346201347201348201349201350201351201352201353201354201355201356201357201358201359201360201361201362201363201364201365201366201367201368201369201370201371201372201373201374201375201376201377201378201379201380201381201382201383201384201385201386201387201388201389201390201391201392201393201394201395201396201397201398201399201400201401201402201403201404201405201406201407201408201409201410201411201412201413201414201415201416201417201418201419201420201421201422201423201424201425201426201427201428201429201430201431201432201433201434201435201436201437201438201439201440201441201442201443201444201445201446201447201448201449201450201451201452201453201454201455201456201457201458201459201460201461201462201463201464201465201466201467201468201469201470201471201472201473201474201475201476201477201478201479201480201481201482201483201484201485201486201487201488201489201490201491201492201493201494201495201496201497201498201499201500201501201502201503201504201505201506201507201508201509201510201511201512201513201514201515201516201517201518201519201520201521201522201523201524201525201526201527201528201529201530201531201532201533201534201535201536201537201538201539201540201541201542201543201544201545201546201547201548201549201550201551201552201553201554201555201556201557201558201559201560201561201562201563201564201565201566201567201568201569201570201571201572201573201574201575201576201577201578201579201580201581201582201583201584201585201586201587201588201589201590201591201592201593201594201595201596201597201598201599201600201601201602201603201604201605201606201607201608201609201610201611201612201613201614201615201616201617201618201619201620201621201622201623201624201625201626201627201628201629201630201631201632201633201634201635201636201637201638201639201640201641201642201643201644201645201646201647201648201649201650201651201652201653201654201655201656201657201658201659201660201661201662201663201664201665201666201667201668201669201670201671201672201673201674201675201676201677201678201679201680201681201682201683201684201685201686201687201688201689201690201691201692201693201694201695201696201697201698201699201700201701201702201703201704201705201706201707201708201709201710201711201712201713201714201715201716201717201718201719201720201721201722201723201724201725201726201727201728201729201730201731201732201733201734201735201736201737201738201739201740201741201742201743201744201745201746201747201748201749201750201751201752201753201754201755201756201757201758201759201760201761201762201763201764201765201766201767201768201769201770201771201772201773201774201775201776201777201778201779201780201781201782201783201784201785201786201787201788201789201790201791201792201793201794201795201796201797201798201799201800201801201802201803201804201805201806201807201808201809201810201811201812201813201814201815201816201817201818201819201820201821201822201823201824201825201826201827201828201829201830201831201832201833201834201835201836201837201838201839201840201841201842201843201844201845201846201847201848201849201850201851201852201853201854201855201856201857201858201859201860201861201862201863201864201865201866201867201868201869201870201871201872201873201874201875201876201877201878201879201880201881201882201883201884201885201886201887201888201889201890201891201892201893201894201895201896201897201898201899201900201901201902201903201904201905201906201907201908201909201910201911201912201913201914201915201916201917201918201919201920201921201922201923201924201925201926201927201928201929201930201931201932201933201934201935201936201937201938201939201940201941201942201943201944201945201946201947201948201949201950201951201952201953201954201955201956201957201958201959201960201961201962201963201964201965201966201967201968201969201970201971201972201973201974201975201976201977201978201979201980201981201982201983201984201985201986201987201988201989201990201991201992201993201994201995201996201997201998201999202000202001202002202003202004202005202006202007202008202009202010202011202012202013202014202015202016202017202018202019202020202021202022202023202024202025202026202027202028202029202030202031202032202033202034202035202036202037202038202039202040202041202042202043202044202045202046202047202048202049202050202051202052202053202054202055202056202057202058202059202060202061202062202063202064202065202066202067202068202069202070202071202072202073202074202075202076202077202078202079202080202081202082202083202084202085202086202087202088202089202090202091202092202093202094202095202096202097202098202099202100202101202102202103202104202105202106202107202108202109202110202111202112202113202114202115202116202117202118202119202120202121202122202123202124202125202126202127202128202129202130202131202132202133202134202135202136202137202138202139202140202141202142202143202144202145202146202147202148202149202150202151202152202153202154202155202156202157202158202159202160202161202162202163202164202165202166202167202168202169202170202171202172202173202174202175202176202177202178202179202180202181202182202183202184202185202186202187202188202189202190202191202192202193202194202195202196202197202198202199202200202201202202202203202204202205202206202207202208202209202210202211202212202213202214202215202216202217202218202219202220202221202222202223202224202225202226202227202228202229202230202231202232202233202234202235202236202237202238202239202240202241202242202243202244202245202246202247202248202249202250202251202252202253202254202255202256202257202258202259202260202261202262202263202264202265202266202267202268202269202270202271202272202273202274202275202276202277202278202279202280202281202282202283202284202285202286202287202288202289202290202291202292202293202294202295202296202297202298202299202300202301202302202303202304202305202306202307202308202309202310202311202312202313202314202315202316202317202318202319202320202321202322202323202324202325202326202327202328202329202330202331202332202333202334202335202336202337202338202339202340202341202342202343202344202345202346202347202348202349202350202351202352202353202354202355202356202357202358202359202360202361202362202363202364202365202366202367202368202369202370202371202372202373202374202375202376202377202378202379202380202381202382202383202384202385202386202387202388202389202390202391202392202393202394202395202396202397202398202399202400202401202402202403202404202405202406202407202408202409202410202411202412202413202414202415202416202417202418202419202420202421202422202423202424202425202426202427202428202429202430202431202432202433202434202435202436202437202438202439202440202441202442202443202444202445202446202447202448202449202450202451202452202453202454202455202456202457202458202459202460202461202462202463202464202465202466202467202468202469202470202471202472202473202474202475202476202477202478202479202480202481202482202483202484202485202486202487202488202489202490202491202492202493202494202495202496202497202498202499202500202501202502202503202504202505202506202507202508202509202510202511202512202513202514202515202516202517202518202519202520202521202522202523202524202525202526202527202528202529202530202531202532202533202534202535202536202537202538202539202540202541202542202543202544202545202546202547202548202549202550202551202552202553202554202555202556202557202558202559202560202561202562202563202564202565202566202567202568202569202570202571202572202573202574202575202576202577202578202579202580202581202582202583202584202585202586202587202588202589202590202591202592202593202594202595202596202597202598202599202600202601202602202603202604202605202606202607202608202609202610202611202612202613202614202615202616202617202618202619202620202621202622202623202624202625202626202627202628202629202630202631202632202633202634202635202636202637202638202639202640202641202642202643202644202645202646202647202648202649202650202651202652202653202654202655202656202657202658202659202660202661202662202663202664202665202666202667202668202669202670202671202672202673202674202675202676202677202678202679202680202681202682202683202684202685202686202687202688202689202690202691202692202693202694202695202696202697202698202699202700202701202702202703202704202705202706202707202708202709202710202711202712202713202714202715202716202717202718202719202720202721202722202723202724202725202726202727202728202729202730202731202732202733202734202735202736202737202738202739202740202741202742202743202744202745202746202747202748202749202750202751202752202753202754202755202756202757202758202759202760202761202762202763202764202765202766202767202768202769202770202771202772202773202774202775202776202777202778202779202780202781202782202783202784202785202786202787202788202789202790202791202792202793202794202795202796202797202798202799202800202801202802202803202804202805202806202807202808202809202810202811202812202813202814202815202816202817202818202819202820202821202822202823202824202825202826202827202828202829202830202831202832202833202834202835202836202837202838202839202840202841202842202843202844202845202846202847202848202849202850202851202852202853202854202855202856202857202858202859202860202861202862202863202864202865202866202867202868202869202870202871202872202873202874202875202876202877202878202879202880202881202882202883202884202885202886202887202888202889202890202891202892202893202894202895202896202897202898202899202900202901202902202903202904202905202906202907202908202909202910202911202912202913202914202915202916202917202918202919202920202921202922202923202924202925202926202927202928202929202930202931202932202933202934202935202936202937202938202939202940202941202942202943202944202945202946202947202948202949202950202951202952202953202954202955202956202957202958202959202960202961202962202963202964202965202966202967202968202969202970202971202972202973202974202975202976202977202978202979202980202981202982202983202984202985202986202987202988202989202990202991202992202993202994202995202996202997202998202999203000203001203002203003203004203005203006203007203008203009203010203011203012203013203014203015203016203017203018203019203020203021203022203023203024203025203026203027203028203029203030203031203032203033203034203035203036203037203038203039203040203041203042203043203044203045203046203047203048203049203050203051203052203053203054203055203056203057203058203059203060203061203062203063203064203065203066203067203068203069203070203071203072203073203074203075203076203077203078203079203080203081203082203083203084203085203086203087203088203089203090203091203092203093203094203095203096203097203098203099203100203101203102203103203104203105203106203107203108203109203110203111203112203113203114203115203116203117203118203119203120203121203122203123203124203125203126203127203128203129203130203131203132203133203134203135203136203137203138203139203140203141203142203143203144203145203146203147203148203149203150203151203152203153203154203155203156203157203158203159203160203161203162203163203164203165203166203167203168203169203170203171203172203173203174203175203176203177203178203179203180203181203182203183203184203185203186203187203188203189203190203191203192203193203194203195203196203197203198203199203200203201203202203203203204203205203206203207203208203209203210203211203212203213203214203215203216203217203218203219203220203221203222203223203224203225203226203227203228203229203230203231203232203233203234203235203236203237203238203239203240203241203242203243203244203245203246203247203248203249203250203251203252203253203254203255203256203257203258203259203260203261203262203263203264203265203266203267203268203269203270203271203272203273203274203275203276203277203278203279203280203281203282203283203284203285203286203287203288203289203290203291203292203293203294203295203296203297203298203299203300203301203302203303203304203305203306203307203308203309203310203311203312203313203314203315203316203317203318203319203320203321203322203323203324203325203326203327203328203329203330203331203332203333203334203335203336203337203338203339203340203341203342203343203344203345203346203347203348203349203350203351203352203353203354203355203356203357203358203359203360203361203362203363203364203365203366203367203368203369203370203371203372203373203374203375203376203377203378203379203380203381203382203383203384203385203386203387203388203389203390203391203392203393203394203395203396203397203398203399203400203401203402203403203404203405203406203407203408203409203410203411203412203413203414203415203416203417203418203419203420203421203422203423203424203425203426203427203428203429203430203431203432203433203434203435203436203437203438203439203440203441203442203443203444203445203446203447203448203449203450203451203452203453203454203455203456203457203458203459203460203461203462203463203464203465203466203467203468203469203470203471203472203473203474203475203476203477203478203479203480203481203482203483203484203485203486203487203488203489203490203491203492203493203494203495203496203497203498203499203500203501203502203503203504203505203506203507203508203509203510203511203512203513203514203515203516203517203518203519203520203521203522203523203524203525203526203527203528203529203530203531203532203533203534203535203536203537203538203539203540203541203542203543203544203545203546203547203548203549203550203551203552203553203554203555203556203557203558203559203560203561203562203563203564203565203566203567203568203569203570203571203572203573203574203575203576203577203578203579203580203581203582203583203584203585203586203587203588203589203590203591203592203593203594203595203596203597203598203599203600203601203602203603203604203605203606203607203608203609203610203611203612203613203614203615203616203617203618203619203620203621203622203623203624203625203626203627203628203629203630203631203632203633203634203635203636203637203638203639203640203641203642203643203644203645203646203647203648203649203650203651203652203653203654203655203656203657203658203659203660203661203662203663203664203665203666203667203668203669203670203671203672203673203674203675203676203677203678203679203680203681203682203683203684203685203686203687203688203689203690203691203692203693203694203695203696203697203698203699203700203701203702203703203704203705203706203707203708203709203710203711203712203713203714203715203716203717203718203719203720203721203722203723203724203725203726203727203728203729203730203731203732203733203734203735203736203737203738203739203740203741203742203743203744203745203746203747203748203749203750203751203752203753203754203755203756203757203758203759203760203761203762203763203764203765203766203767203768203769203770203771203772203773203774203775203776203777203778203779203780203781203782203783203784203785203786203787203788203789203790203791203792203793203794203795203796203797203798203799203800203801203802203803203804203805203806203807203808203809203810203811203812203813203814203815203816203817203818203819203820203821203822203823203824203825203826203827203828203829203830203831203832203833203834203835203836203837203838203839203840203841203842203843203844203845203846203847203848203849203850203851203852203853203854203855203856203857203858203859203860203861203862203863203864203865203866203867203868203869203870203871203872203873203874203875203876203877203878203879203880203881203882203883203884203885203886203887203888203889203890203891203892203893203894203895203896203897203898203899203900203901203902203903203904203905203906203907203908203909203910203911203912203913203914203915203916203917203918203919203920203921203922203923203924203925203926203927203928203929203930203931203932203933203934203935203936203937203938203939203940203941203942203943203944203945203946203947203948203949203950203951203952203953203954203955203956203957203958203959203960203961203962203963203964203965203966203967203968203969203970203971203972203973203974203975203976203977203978203979203980203981203982203983203984203985203986203987203988203989203990203991203992203993203994203995203996203997203998203999204000204001204002204003204004204005204006204007204008204009204010204011204012204013204014204015204016204017204018204019204020204021204022204023204024204025204026204027204028204029204030204031204032204033204034204035204036204037204038204039204040204041204042204043204044204045204046204047204048204049204050204051204052204053204054204055204056204057204058204059204060204061204062204063204064204065204066204067204068204069204070204071204072204073204074204075204076204077204078204079204080204081204082204083204084204085204086204087204088204089204090204091204092204093204094204095204096204097204098204099204100204101204102204103204104204105204106204107204108204109204110204111204112204113204114204115204116204117204118204119204120204121204122204123204124204125204126204127204128204129204130204131204132204133204134204135204136204137204138204139204140204141204142204143204144204145204146204147204148204149204150204151204152204153204154204155204156204157204158204159204160204161204162204163204164204165204166204167204168204169204170204171204172204173204174204175204176204177204178204179204180204181204182204183204184204185204186204187204188204189204190204191204192204193204194204195204196204197204198204199204200204201204202204203204204204205204206204207204208204209204210204211204212204213204214204215204216204217204218204219204220204221204222204223204224204225204226204227204228204229204230204231204232204233204234204235204236204237204238204239204240204241204242204243204244204245204246204247204248204249204250204251204252204253204254204255204256204257204258204259204260204261204262204263204264204265204266204267204268204269204270204271204272204273204274204275204276204277204278204279204280204281204282204283204284204285204286204287204288204289204290204291204292204293204294204295204296204297204298204299204300204301204302204303204304204305204306204307204308204309204310204311204312204313204314204315204316204317204318204319204320204321204322204323204324204325204326204327204328204329204330204331204332204333204334204335204336204337204338204339204340204341204342204343204344204345204346204347204348204349204350204351204352204353204354204355204356204357204358204359204360204361204362204363204364204365204366204367204368204369204370204371204372204373204374204375204376204377204378204379204380204381204382204383204384204385204386204387204388204389204390204391204392204393204394204395204396204397204398204399204400204401204402204403204404204405204406204407204408204409204410204411204412204413204414204415204416204417204418204419204420204421204422204423204424204425204426204427204428204429204430204431204432204433204434204435204436204437204438204439204440204441204442204443204444204445204446204447204448204449204450204451204452204453204454204455204456204457204458204459204460204461204462204463204464204465204466204467204468204469204470204471204472204473204474204475204476204477204478204479204480204481204482204483204484204485204486204487204488204489204490204491204492204493204494204495204496204497204498204499204500204501204502204503204504204505204506204507204508204509204510204511204512204513204514204515204516204517204518204519204520204521204522204523204524204525204526204527204528204529204530204531204532204533204534204535204536204537204538204539204540204541204542204543204544204545204546204547204548204549204550204551204552204553204554204555204556204557204558204559204560204561204562204563204564204565204566204567204568204569204570204571204572204573204574204575204576204577204578204579204580204581204582204583204584204585204586204587204588204589204590204591204592204593204594204595204596204597204598204599204600204601204602204603204604204605204606204607204608204609204610204611204612204613204614204615204616204617204618204619204620204621204622204623204624204625204626204627204628204629204630204631204632204633204634204635204636204637204638204639204640204641204642204643204644204645204646204647204648204649204650204651204652204653204654204655204656204657204658204659204660204661204662204663204664204665204666204667204668204669204670204671204672204673204674204675204676204677204678204679204680204681204682204683204684204685204686204687204688204689204690204691204692204693204694204695204696204697204698204699204700204701204702204703204704204705204706204707204708204709204710204711204712204713204714204715204716204717204718204719204720204721204722204723204724204725204726204727204728204729204730204731204732204733204734204735204736204737204738204739204740204741204742204743204744204745204746204747204748204749204750204751204752204753204754204755204756204757204758204759204760204761204762204763204764204765204766204767204768204769204770204771204772204773204774204775204776204777204778204779204780204781204782204783204784204785204786204787204788204789204790204791204792204793204794204795204796204797204798204799204800204801204802204803204804204805204806204807204808204809204810204811204812204813204814204815204816204817204818204819204820204821204822204823204824204825204826204827204828204829204830204831204832204833204834204835204836204837204838204839204840204841204842204843204844204845204846204847204848204849204850204851204852204853204854204855204856204857204858204859204860204861204862204863204864204865204866204867204868204869204870204871204872204873204874204875204876204877204878204879204880204881204882204883204884204885204886204887204888204889204890204891204892204893204894204895204896204897204898204899204900204901204902204903204904204905204906204907204908204909204910204911204912204913204914204915204916204917204918204919204920204921204922204923204924204925204926204927204928204929204930204931204932204933204934204935204936204937204938204939204940204941204942204943204944204945204946204947204948204949204950204951204952204953204954204955204956204957204958204959204960204961204962204963204964204965204966204967204968204969204970204971204972204973204974204975204976204977204978204979204980204981204982204983204984204985204986204987204988204989204990204991204992204993204994204995204996204997204998204999205000205001205002205003205004205005205006205007205008205009205010205011205012205013205014205015205016205017205018205019205020205021205022205023205024205025205026205027205028205029205030205031205032205033205034205035205036205037205038205039205040205041205042205043205044205045205046205047205048205049205050205051205052205053205054205055205056205057205058205059205060205061205062205063205064205065205066205067205068205069205070205071205072205073205074205075205076205077205078205079205080205081205082205083205084205085205086205087205088205089205090205091205092205093205094205095205096205097205098205099205100205101205102205103205104205105205106205107205108205109205110205111205112205113205114205115205116205117205118205119205120205121205122205123205124205125205126205127205128205129205130205131205132205133205134205135205136205137205138205139205140205141205142205143205144205145205146205147205148205149205150205151205152205153205154205155205156205157205158205159205160205161205162205163205164205165205166205167205168205169205170205171205172205173205174205175205176205177205178205179205180205181205182205183205184205185205186205187205188205189205190205191205192205193205194205195205196205197205198205199205200205201205202205203205204205205205206205207205208205209205210205211205212205213205214205215205216205217205218205219205220205221205222205223205224205225205226205227205228205229205230205231205232205233205234205235205236205237205238205239205240205241205242205243205244205245205246205247205248205249205250205251205252205253205254205255205256205257205258205259205260205261205262205263205264205265205266205267205268205269205270205271205272205273205274205275205276205277205278205279205280205281205282205283205284205285205286205287205288205289205290205291205292205293205294205295205296205297205298205299205300205301205302205303205304205305205306205307205308205309205310205311205312205313205314205315205316205317205318205319205320205321205322205323205324205325205326205327205328205329205330205331205332205333205334205335205336205337205338205339205340205341205342205343205344205345205346205347205348205349205350205351205352205353205354205355205356205357205358205359205360205361205362205363205364205365205366205367205368205369205370205371205372205373205374205375205376205377205378205379205380205381205382205383205384205385205386205387205388205389205390205391205392205393205394205395205396205397205398205399205400205401205402205403205404205405205406205407205408205409205410205411205412205413205414205415205416205417205418205419205420205421205422205423205424205425205426205427205428205429205430205431205432205433205434205435205436205437205438205439205440205441205442205443205444205445205446205447205448205449205450205451205452205453205454205455205456205457205458205459205460205461205462205463205464205465205466205467205468205469205470205471205472205473205474205475205476205477205478205479205480205481205482205483205484205485205486205487205488205489205490205491205492205493205494205495205496205497205498205499205500205501205502205503205504205505205506205507205508205509205510205511205512205513205514205515205516205517205518205519205520205521205522205523205524205525205526205527205528205529205530205531205532205533205534205535205536205537205538205539205540205541205542205543205544205545205546205547205548205549205550205551205552205553205554205555205556205557205558205559205560205561205562205563205564205565205566205567205568205569205570205571205572205573205574205575205576205577205578205579205580205581205582205583205584205585205586205587205588205589205590205591205592205593205594205595205596205597205598205599205600205601205602205603205604205605205606205607205608205609205610205611205612205613205614205615205616205617205618205619205620205621205622205623205624205625205626205627205628205629205630205631205632205633205634205635205636205637205638205639205640205641205642205643205644205645205646205647205648205649205650205651205652205653205654205655205656205657205658205659205660205661205662205663205664205665205666205667205668205669205670205671205672205673205674205675205676205677205678205679205680205681205682205683205684205685205686205687205688205689205690205691205692205693205694205695205696205697205698205699205700205701205702205703205704205705205706205707205708205709205710205711205712205713205714205715205716205717205718205719205720205721205722205723205724205725205726205727205728205729205730205731205732205733205734205735205736205737205738205739205740205741205742205743205744205745205746205747205748205749205750205751205752205753205754205755205756205757205758205759205760205761205762205763205764205765205766205767205768205769205770205771205772205773205774205775205776205777205778205779205780205781205782205783205784205785205786205787205788205789205790205791205792205793205794205795205796205797205798205799205800205801205802205803205804205805205806205807205808205809205810205811205812205813205814205815205816205817205818205819205820205821205822205823205824205825205826205827205828205829205830205831205832205833205834205835205836205837205838205839205840205841205842205843205844205845205846205847205848205849205850205851205852205853205854205855205856205857205858205859205860205861205862205863205864205865205866205867205868205869205870205871205872205873205874205875205876205877205878205879205880205881205882205883205884205885205886205887205888205889205890205891205892205893205894205895205896205897205898205899205900205901205902205903205904205905205906205907205908205909205910205911205912205913205914205915205916205917205918205919205920205921205922205923205924205925205926205927205928205929205930205931205932205933205934205935205936205937205938205939205940205941205942205943205944205945205946205947205948205949205950205951205952205953205954205955205956205957205958205959205960205961205962205963205964205965205966205967205968205969205970205971205972205973205974205975205976205977205978205979205980205981205982205983205984205985205986205987205988205989205990205991205992205993205994205995205996205997205998205999206000206001206002206003206004206005206006206007206008206009206010206011206012206013206014206015206016206017206018206019206020206021206022206023206024206025206026206027206028206029206030206031206032206033206034206035206036206037206038206039206040206041206042206043206044206045206046206047206048206049206050206051206052206053206054206055206056206057206058206059206060206061206062206063206064206065206066206067206068206069206070206071206072206073206074206075206076206077206078206079206080206081206082206083206084206085206086206087206088206089206090206091206092206093206094206095206096206097206098206099206100206101206102206103206104206105206106206107206108206109206110206111206112206113206114206115206116206117206118206119206120206121206122206123206124206125206126206127206128206129206130206131206132206133206134206135206136206137206138206139206140206141206142206143206144206145206146206147206148206149206150206151206152206153206154206155206156206157206158206159206160206161206162206163206164206165206166206167206168206169206170206171206172206173206174206175206176206177206178206179206180206181206182206183206184206185206186206187206188206189206190206191206192206193206194206195206196206197206198206199206200206201206202206203206204206205206206206207206208206209206210206211206212206213206214206215206216206217206218206219206220206221206222206223206224206225206226206227206228206229206230206231206232206233206234206235206236206237206238206239206240206241206242206243206244206245206246206247206248206249206250206251206252206253206254206255206256206257206258206259206260206261206262206263206264206265206266206267206268206269206270206271206272206273206274206275206276206277206278206279206280206281206282206283206284206285206286206287206288206289206290206291206292206293206294206295206296206297206298206299206300206301206302206303206304206305206306206307206308206309206310206311206312206313206314206315206316206317206318206319206320206321206322206323206324206325206326206327206328206329206330206331206332206333206334206335206336206337206338206339206340206341206342206343206344206345206346206347206348206349206350206351206352206353206354206355206356206357206358206359206360206361206362206363206364206365206366206367206368206369206370206371206372206373206374206375206376206377206378206379206380206381206382206383206384206385206386206387206388206389206390206391206392206393206394206395206396206397206398206399206400206401206402206403206404206405206406206407206408206409206410206411206412206413206414206415206416206417206418206419206420206421206422206423206424206425206426206427206428206429206430206431206432206433206434206435206436206437206438206439206440206441206442206443206444206445206446206447206448206449206450206451206452206453206454206455206456206457206458206459206460206461206462206463206464206465206466206467206468206469206470206471206472206473206474206475206476206477206478206479206480206481206482206483206484206485206486206487206488206489206490206491206492206493206494206495206496206497206498206499206500206501206502206503206504206505206506206507206508206509206510206511206512206513206514206515206516206517206518206519206520206521206522206523206524206525206526206527206528206529206530206531206532206533206534206535206536206537206538206539206540206541206542206543206544206545206546206547206548206549206550206551206552206553206554206555206556206557206558206559206560206561206562206563206564206565206566206567206568206569206570206571206572206573206574206575206576206577206578206579206580206581206582206583206584206585206586206587206588206589206590206591206592206593206594206595206596206597206598206599206600206601206602206603206604206605206606206607206608206609206610206611206612206613206614206615206616206617206618206619206620206621206622206623206624206625206626206627206628206629206630206631206632206633206634206635206636206637206638206639206640206641206642206643206644206645206646206647206648206649206650206651206652206653206654206655206656206657206658206659206660206661206662206663206664206665206666206667206668206669206670206671206672206673206674206675206676206677206678206679206680206681206682206683206684206685206686206687206688206689206690206691206692206693206694206695206696206697206698206699206700206701206702206703206704206705206706206707206708206709206710206711206712206713206714206715206716206717206718206719206720206721206722206723206724206725206726206727206728206729206730206731206732206733206734206735206736206737206738206739206740206741206742206743206744206745206746206747206748206749206750206751206752206753206754206755206756206757206758206759206760206761206762206763206764206765206766206767206768206769206770206771206772206773206774206775206776206777206778206779206780206781206782206783206784206785206786206787206788206789206790206791206792206793206794206795206796206797206798206799206800206801206802206803206804206805206806206807206808206809206810206811206812206813206814206815206816206817206818206819206820206821206822206823206824206825206826206827206828206829206830206831206832206833206834206835206836206837206838206839206840206841206842206843206844206845206846206847206848206849206850206851206852206853206854206855206856206857206858206859206860206861206862206863206864206865206866206867206868206869206870206871206872206873206874206875206876206877206878206879206880206881206882206883206884206885206886206887206888206889206890206891206892206893206894206895206896206897206898206899206900206901206902206903206904206905206906206907206908206909206910206911206912206913206914206915206916206917206918206919206920206921206922206923206924206925206926206927206928206929206930206931206932206933206934206935206936206937206938206939206940206941206942206943206944206945206946206947206948206949206950206951206952206953206954206955206956206957206958206959206960206961206962206963206964206965206966206967206968206969206970206971206972206973206974206975206976206977206978206979206980206981206982206983206984206985206986206987206988206989206990206991206992206993206994206995206996206997206998206999207000207001207002207003207004207005207006207007207008207009207010207011207012207013207014207015207016207017207018207019207020207021207022207023207024207025207026207027207028207029207030207031207032207033207034207035207036207037207038207039207040207041207042207043207044207045207046207047207048207049207050207051207052207053207054207055207056207057207058207059207060207061207062207063207064207065207066207067207068207069207070207071207072207073207074207075207076207077207078207079207080207081207082207083207084207085207086207087207088207089207090207091207092207093207094207095207096207097207098207099207100207101207102207103207104207105207106207107207108207109207110207111207112207113207114207115207116207117207118207119207120207121207122207123207124207125207126207127207128207129207130207131207132207133207134207135207136207137207138207139207140207141207142207143207144207145207146207147207148207149207150207151207152207153207154207155207156207157207158207159207160207161207162207163207164207165207166207167207168207169207170207171207172207173207174207175207176207177207178207179207180207181207182207183207184207185207186207187207188207189207190207191207192207193207194207195207196207197207198207199207200207201207202207203207204207205207206207207207208207209207210207211207212207213207214207215207216207217207218207219207220207221207222207223207224207225207226207227207228207229207230207231207232207233207234207235207236207237207238207239207240207241207242207243207244207245207246207247207248207249207250207251207252207253207254207255207256207257207258207259207260207261207262207263207264207265207266207267207268207269207270207271207272207273207274207275207276207277207278207279207280207281207282207283207284207285207286207287207288207289207290207291207292207293207294207295207296207297207298207299207300207301207302207303207304207305207306207307207308207309207310207311207312207313207314207315207316207317207318207319207320207321207322207323207324207325207326207327207328207329207330207331207332207333207334207335207336207337207338207339207340207341207342207343207344207345207346207347207348207349207350207351207352207353207354207355207356207357207358207359207360207361207362207363207364207365207366207367207368207369207370207371207372207373207374207375207376207377207378207379207380207381207382207383207384207385207386207387207388207389207390207391207392207393207394207395207396207397207398207399207400207401207402207403207404207405207406207407207408207409207410207411207412207413207414207415207416207417207418207419207420207421207422207423207424207425207426207427207428207429207430207431207432207433207434207435207436207437207438207439207440207441207442207443207444207445207446207447207448207449207450207451207452207453207454207455207456207457207458207459207460207461207462207463207464207465207466207467207468207469207470207471207472207473207474207475207476207477207478207479207480207481207482207483207484207485207486207487207488207489207490207491207492207493207494207495207496207497207498207499207500207501207502207503207504207505207506207507207508207509207510207511207512207513207514207515207516207517207518207519207520207521207522207523207524207525207526207527207528207529207530207531207532207533207534207535207536207537207538207539207540207541207542207543207544207545207546207547207548207549207550207551207552207553207554207555207556207557207558207559207560207561207562207563207564207565207566207567207568207569207570207571207572207573207574207575207576207577207578207579207580207581207582207583207584207585207586207587207588207589207590207591207592207593207594207595207596207597207598207599207600207601207602207603207604207605207606207607207608207609207610207611207612207613207614207615207616207617207618207619207620207621207622207623207624207625207626207627207628207629207630207631207632207633207634207635207636207637207638207639207640207641207642207643207644207645207646207647207648207649207650207651207652207653207654207655207656207657207658207659207660207661207662207663207664207665207666207667207668207669207670207671207672207673207674207675207676207677207678207679207680207681207682207683207684207685207686207687207688207689207690207691207692207693207694207695207696207697207698207699207700207701207702207703207704207705207706207707207708207709207710207711207712207713207714207715207716207717207718207719207720207721207722207723207724207725207726207727207728207729207730207731207732207733207734207735207736207737207738207739207740207741207742207743207744207745207746207747207748207749207750207751207752207753207754207755207756207757207758207759207760207761207762207763207764207765207766207767207768207769207770207771207772207773207774207775207776207777207778207779207780207781207782207783207784207785207786207787207788207789207790207791207792207793207794207795207796207797207798207799207800207801207802207803207804207805207806207807207808207809207810207811207812207813207814207815207816207817207818207819207820207821207822207823207824207825207826207827207828207829207830207831207832207833207834207835207836207837207838207839207840207841207842207843207844207845207846207847207848207849207850207851207852207853207854207855207856207857207858207859207860207861207862207863207864207865207866207867207868207869207870207871207872207873207874207875207876207877207878207879207880207881207882207883207884207885207886207887207888207889207890207891207892207893207894207895207896207897207898207899207900207901207902207903207904207905207906207907207908207909207910207911207912207913207914207915207916207917207918207919207920207921207922207923207924207925207926207927207928207929207930207931207932207933207934207935207936207937207938207939207940207941207942207943207944207945207946207947207948207949207950207951207952207953207954207955207956207957207958207959207960207961207962207963207964207965207966207967207968207969207970207971207972207973207974207975207976207977207978207979207980207981207982207983207984207985207986207987207988207989207990207991207992207993207994207995207996207997207998207999208000208001208002208003208004208005208006208007208008208009208010208011208012208013208014208015208016208017208018208019208020208021208022208023208024208025208026208027208028208029208030208031208032208033208034208035208036208037208038208039208040208041208042208043208044208045208046208047208048208049208050208051208052208053208054208055208056208057208058208059208060208061208062208063208064208065208066208067208068208069208070208071208072208073208074208075208076208077208078208079208080208081208082208083208084208085208086208087208088208089208090208091208092208093208094208095208096208097208098208099208100208101208102208103208104208105208106208107208108208109208110208111208112208113208114208115208116208117208118208119208120208121208122208123208124208125208126208127208128208129208130208131208132208133208134208135208136208137208138208139208140208141208142208143208144208145208146208147208148208149208150208151208152208153208154208155208156208157208158208159208160208161208162208163208164208165208166208167208168208169208170208171208172208173208174208175208176208177208178208179208180208181208182208183208184208185208186208187208188208189208190208191208192208193208194208195208196208197208198208199208200208201208202208203208204208205208206208207208208208209208210208211208212208213208214208215208216208217208218208219208220208221208222208223208224208225208226208227208228208229208230208231208232208233208234208235208236208237208238208239208240208241208242208243208244208245208246208247208248208249208250208251208252208253208254208255208256208257208258208259208260208261208262208263208264208265208266208267208268208269208270208271208272208273208274208275208276208277208278208279208280208281208282208283208284208285208286208287208288208289208290208291208292208293208294208295208296208297208298208299208300208301208302208303208304208305208306208307208308208309208310208311208312208313208314208315208316208317208318208319208320208321208322208323208324208325208326208327208328208329208330208331208332208333208334208335208336208337208338208339208340208341208342208343208344208345208346208347208348208349208350208351208352208353208354208355208356208357208358208359208360208361208362208363208364208365208366208367208368208369208370208371208372208373208374208375208376208377208378208379208380208381208382208383208384208385208386208387208388208389208390208391208392208393208394208395208396208397208398208399208400208401208402208403208404208405208406208407208408208409208410208411208412208413208414208415208416208417208418208419208420208421208422208423208424208425208426208427208428208429208430208431208432208433208434208435208436208437208438208439208440208441208442208443208444208445208446208447208448208449208450208451208452208453208454208455208456208457208458208459208460208461208462208463208464208465208466208467208468208469208470208471208472208473208474208475208476208477208478208479208480208481208482208483208484208485208486208487208488208489208490208491208492208493208494208495208496208497208498208499208500208501208502208503208504208505208506208507208508208509208510208511208512208513208514208515208516208517208518208519208520208521208522208523208524208525208526208527208528208529208530208531208532208533208534208535208536208537208538208539208540208541208542208543208544208545208546208547208548208549208550208551208552208553208554208555208556208557208558208559208560208561208562208563208564208565208566208567208568208569208570208571208572208573208574208575208576208577208578208579208580208581208582208583208584208585208586208587208588208589208590208591208592208593208594208595208596208597208598208599208600208601208602208603208604208605208606208607208608208609208610208611208612208613208614208615208616208617208618208619208620208621208622208623208624208625208626208627208628208629208630208631208632208633208634208635208636208637208638208639208640208641208642208643208644208645208646208647208648208649208650208651208652208653208654208655208656208657208658208659208660208661208662208663208664208665208666208667208668208669208670208671208672208673208674208675208676208677208678208679208680208681208682208683208684208685208686208687208688208689208690208691208692208693208694208695208696208697208698208699208700208701208702208703208704208705208706208707208708208709208710208711208712208713208714208715208716208717208718208719208720208721208722208723208724208725208726208727208728208729208730208731208732208733208734208735208736208737208738208739208740208741208742208743208744208745208746208747208748208749208750208751208752208753208754208755208756208757208758208759208760208761208762208763208764208765208766208767208768208769208770208771208772208773208774208775208776208777208778208779208780208781208782208783208784208785208786208787208788208789208790208791208792208793208794208795208796208797208798208799208800208801208802208803208804208805208806208807208808208809208810208811208812208813208814208815208816208817208818208819208820208821208822208823208824208825208826208827208828208829208830208831208832208833208834208835208836208837208838208839208840208841208842208843208844208845208846208847208848208849208850208851208852208853208854208855208856208857208858208859208860208861208862208863208864208865208866208867208868208869208870208871208872208873208874208875208876208877208878208879208880208881208882208883208884208885208886208887208888208889208890208891208892208893208894208895208896208897208898208899208900208901208902208903208904208905208906208907208908208909208910208911208912208913208914208915208916208917208918208919208920208921208922208923208924208925208926208927208928208929208930208931208932208933208934208935208936208937208938208939208940208941208942208943208944208945208946208947208948208949208950208951208952208953208954208955208956208957208958208959208960208961208962208963208964208965208966208967208968208969208970208971208972208973208974208975208976208977208978208979208980208981208982208983208984208985208986208987208988208989208990208991208992208993208994208995208996208997208998208999209000209001209002209003209004209005209006209007209008209009209010209011209012209013209014209015209016209017209018209019209020209021209022209023209024209025209026209027209028209029209030209031209032209033209034209035209036209037209038209039209040209041209042209043209044209045209046209047209048209049209050209051209052209053209054209055209056209057209058209059209060209061209062209063209064209065209066209067209068209069209070209071209072209073209074209075209076209077209078209079209080209081209082209083209084209085209086209087209088209089209090209091209092209093209094209095209096209097209098209099209100209101209102209103209104209105209106209107209108209109209110209111209112209113209114209115209116209117209118209119209120209121209122209123209124209125209126209127209128209129209130209131209132209133209134209135209136209137209138209139209140209141209142209143209144209145209146209147209148209149209150209151209152209153209154209155209156209157209158209159209160209161209162209163209164209165209166209167209168209169209170209171209172209173209174209175209176209177209178209179209180209181209182209183209184209185209186209187209188209189209190209191209192209193209194209195209196209197209198209199209200209201209202209203209204209205209206209207209208209209209210209211209212209213209214209215209216209217209218209219209220209221209222209223209224209225209226209227209228209229209230209231209232209233209234209235209236209237209238209239209240209241209242209243209244209245209246209247209248209249209250209251209252209253209254209255209256209257209258209259209260209261209262209263209264209265209266209267209268209269209270209271209272209273209274209275209276209277209278209279209280209281209282209283209284209285209286209287209288209289209290209291209292209293209294209295209296209297209298209299209300209301209302209303209304209305209306209307209308209309209310209311209312209313209314209315209316209317209318209319209320209321209322209323209324209325209326209327209328209329209330209331209332209333209334209335209336209337209338209339209340209341209342209343209344209345209346209347209348209349209350209351209352209353209354209355209356209357209358209359209360209361209362209363209364209365209366209367209368209369209370209371209372209373209374209375209376209377209378209379209380209381209382209383209384209385209386209387209388209389209390209391209392209393209394209395209396209397209398209399209400209401209402209403209404209405209406209407209408209409209410209411209412209413209414209415209416209417209418209419209420209421209422209423209424209425209426209427209428209429209430209431209432209433209434209435209436209437209438209439209440209441209442209443209444209445209446209447209448209449209450209451209452209453209454209455209456209457209458209459209460209461209462209463209464209465209466209467209468209469209470209471209472209473209474209475209476209477209478209479209480209481209482209483209484209485209486209487209488209489209490209491209492209493209494209495209496209497209498209499209500209501209502209503209504209505209506209507209508209509209510209511209512209513209514209515209516209517209518209519209520209521209522209523209524209525209526209527209528209529209530209531209532209533209534209535209536209537209538209539209540209541209542209543209544209545209546209547209548209549209550209551209552209553209554209555209556209557209558209559209560209561209562209563209564209565209566209567209568209569209570209571209572209573209574209575209576209577209578209579209580209581209582209583209584209585209586209587209588209589209590209591209592209593209594209595209596209597209598209599209600209601209602209603209604209605209606209607209608209609209610209611209612209613209614209615209616209617209618209619209620209621209622209623209624209625209626209627209628209629209630209631209632209633209634209635209636209637209638209639209640209641209642209643209644209645209646209647209648209649209650209651209652209653209654209655209656209657209658209659209660209661209662209663209664209665209666209667209668209669209670209671209672209673209674209675209676209677209678209679209680209681209682209683209684209685209686209687209688209689209690209691209692209693209694209695209696209697209698209699209700209701209702209703209704209705209706209707209708209709209710209711209712209713209714209715209716209717209718209719209720209721209722209723209724209725209726209727209728209729209730209731209732209733209734209735209736209737209738209739209740209741209742209743209744209745209746209747209748209749209750209751209752209753209754209755209756209757209758209759209760209761209762209763209764209765209766209767209768209769209770209771209772209773209774209775209776209777209778209779209780209781209782209783209784209785209786209787209788209789209790209791209792209793209794209795209796209797209798209799209800209801209802209803209804209805209806209807209808209809209810209811209812209813209814209815209816209817209818209819209820209821209822209823209824209825209826209827209828209829209830209831209832209833209834209835209836209837209838209839209840209841209842209843209844209845209846209847209848209849209850209851209852209853209854209855209856209857209858209859209860209861209862209863209864209865209866209867209868209869209870209871209872209873209874209875209876209877209878209879209880209881209882209883209884209885209886209887209888209889209890209891209892209893209894209895209896209897209898209899209900209901209902209903209904209905209906209907209908209909209910209911209912209913209914209915209916209917209918209919209920209921209922209923209924209925209926209927209928209929209930209931209932209933209934209935209936209937209938209939209940209941209942209943209944209945209946209947209948209949209950209951209952209953209954209955209956209957209958209959209960209961209962209963209964209965209966209967209968209969209970209971209972209973209974209975209976209977209978209979209980209981209982209983209984209985209986209987209988209989209990209991209992209993209994209995209996209997209998209999210000210001210002210003210004210005210006210007210008210009210010210011210012210013210014210015210016210017210018210019210020210021210022210023210024210025210026210027210028210029210030210031210032210033210034210035210036210037210038210039210040210041210042210043210044210045210046210047210048210049210050210051210052210053210054210055210056210057210058210059210060210061210062210063210064210065210066210067210068210069210070210071210072210073210074210075210076210077210078210079210080210081210082210083210084210085210086210087210088210089210090210091210092210093210094210095210096210097210098210099210100210101210102210103210104210105210106210107210108210109210110210111210112210113210114210115210116210117210118210119210120210121210122210123210124210125210126210127210128210129210130210131210132210133210134210135210136210137210138210139210140210141210142210143210144210145210146210147210148210149210150210151210152210153210154210155210156210157210158210159210160210161210162210163210164210165210166210167210168210169210170210171210172210173210174210175210176210177210178210179210180210181210182210183210184210185210186210187210188210189210190210191210192210193210194210195210196210197210198210199210200210201210202210203210204210205210206210207210208210209210210210211210212210213210214210215210216210217210218210219210220210221210222210223210224210225210226210227210228210229210230210231210232210233210234210235210236210237210238210239210240210241210242210243210244210245210246210247210248210249210250210251210252210253210254210255210256210257210258210259210260210261210262210263210264210265210266210267210268210269210270210271210272210273210274210275210276210277210278210279210280210281210282210283210284210285210286210287210288210289210290210291210292210293210294210295210296210297210298210299210300210301210302210303210304210305210306210307210308210309210310210311210312210313210314210315210316210317210318210319210320210321210322210323210324210325210326210327210328210329210330210331210332210333210334210335210336210337210338210339210340210341210342210343210344210345210346210347210348210349210350210351210352210353210354210355210356210357210358210359210360210361210362210363210364210365210366210367210368210369210370210371210372210373210374210375210376210377210378210379210380210381210382210383210384210385210386210387210388210389210390210391210392210393210394210395210396210397210398210399210400210401210402210403210404210405210406210407210408210409210410210411210412210413210414210415210416210417210418210419210420210421210422210423210424210425210426210427210428210429210430210431210432210433210434210435210436210437210438210439210440210441210442210443210444210445210446210447210448210449210450210451210452210453210454210455210456210457210458210459210460210461210462210463210464210465210466210467210468210469210470210471210472210473210474210475210476210477210478210479210480210481210482210483210484210485210486210487210488210489210490210491210492210493210494210495210496210497210498210499210500210501210502210503210504210505210506210507210508210509210510210511210512210513210514210515210516210517210518210519210520210521210522210523210524210525210526210527210528210529210530210531210532210533210534210535210536210537210538210539210540210541210542210543210544210545210546210547210548210549210550210551210552210553210554210555210556210557210558210559210560210561210562210563210564210565210566210567210568210569210570210571210572210573210574210575210576210577210578210579210580210581210582210583210584210585210586210587210588210589210590210591210592210593210594210595210596210597210598210599210600210601210602210603210604210605210606210607210608210609210610210611210612210613210614210615210616210617210618210619210620210621210622210623210624210625210626210627210628210629210630210631210632210633210634210635210636210637210638210639210640210641210642210643210644210645210646210647210648210649210650210651210652210653210654210655210656210657210658210659210660210661210662210663210664210665210666210667210668210669210670210671210672210673210674210675210676210677210678210679210680210681210682210683210684210685210686210687210688210689210690210691210692210693210694210695210696210697210698210699210700210701210702210703210704210705210706210707210708210709210710210711210712210713210714210715210716210717210718210719210720210721210722210723210724210725210726210727210728210729210730210731210732210733210734210735210736210737210738210739210740210741210742210743210744210745210746210747210748210749210750210751210752210753210754210755210756210757210758210759210760210761210762210763210764210765210766210767210768210769210770210771210772210773210774210775210776210777210778210779210780210781210782210783210784210785210786210787210788210789210790210791210792210793210794210795210796210797210798210799210800210801210802210803210804210805210806210807210808210809210810210811210812210813210814210815210816210817210818210819210820210821210822210823210824210825210826210827210828210829210830210831210832210833210834210835210836210837210838210839210840210841210842210843210844210845210846210847210848210849210850210851210852210853210854210855210856210857210858210859210860210861210862210863210864210865210866210867210868210869210870210871210872210873210874210875210876210877210878210879210880210881210882210883210884210885210886210887210888210889210890210891210892210893210894210895210896210897210898210899210900210901210902210903210904210905210906210907210908210909210910210911210912210913210914210915210916210917210918210919210920210921210922210923210924210925210926210927210928210929210930210931210932210933210934210935210936210937210938210939210940210941210942210943210944210945210946210947210948210949210950210951210952210953210954210955210956210957210958210959210960210961210962210963210964210965210966210967210968210969210970210971210972210973210974210975210976210977210978210979210980210981210982210983210984210985210986210987210988210989210990210991210992210993210994210995210996210997210998210999211000211001211002211003211004211005211006211007211008211009211010211011211012211013211014211015211016211017211018211019211020211021211022211023211024211025211026211027211028211029211030211031211032211033211034211035211036211037211038211039211040211041211042211043211044211045211046211047211048211049211050211051211052211053211054211055211056211057211058211059211060211061211062211063211064211065211066211067211068211069211070211071211072211073211074211075211076211077211078211079211080211081211082211083211084211085211086211087211088211089211090211091211092211093211094211095211096211097211098211099211100211101211102211103211104211105211106211107211108211109211110211111211112211113211114211115211116211117211118211119211120211121211122211123211124211125211126211127211128211129211130211131211132211133211134211135211136211137211138211139211140211141211142211143211144211145211146211147211148211149211150211151211152211153211154211155211156211157211158211159211160211161211162211163211164211165211166211167211168211169211170211171211172211173211174211175211176211177211178211179211180211181211182211183211184211185211186211187211188211189211190211191211192211193211194211195211196211197211198211199211200211201211202211203211204211205211206211207211208211209211210211211211212211213211214211215211216211217211218211219211220211221211222211223211224211225211226211227211228211229211230211231211232211233211234211235211236211237211238211239211240211241211242211243211244211245211246211247211248211249211250211251211252211253211254211255211256211257211258211259211260211261211262211263211264211265211266211267211268211269211270211271211272211273211274211275211276211277211278211279211280211281211282211283211284211285211286211287211288211289211290211291211292211293211294211295211296211297211298211299211300211301211302211303211304211305211306211307211308211309211310211311211312211313211314211315211316211317211318211319211320211321211322211323211324211325211326211327211328211329211330211331211332211333211334211335211336211337211338211339211340211341211342211343211344211345211346211347211348211349211350211351211352211353211354211355211356211357211358211359211360211361211362211363211364211365211366211367211368211369211370211371211372211373211374211375211376211377211378211379211380211381211382211383211384211385211386211387211388211389211390211391211392211393211394211395211396211397211398211399211400211401211402211403211404211405211406211407211408211409211410211411211412211413211414211415211416211417211418211419211420211421211422211423211424211425211426211427211428211429211430211431211432211433211434211435211436211437211438211439211440211441211442211443211444211445211446211447211448211449211450211451211452211453211454211455211456211457211458211459211460211461211462211463211464211465211466211467211468211469211470211471211472211473211474211475211476211477211478211479211480211481211482211483211484211485211486211487211488211489211490211491211492211493211494211495211496211497211498211499211500211501211502211503211504211505211506211507211508211509211510211511211512211513211514211515211516211517211518211519211520211521211522211523211524211525211526211527211528211529211530211531211532211533211534211535211536211537211538211539211540211541211542211543211544211545211546211547211548211549211550211551211552211553211554211555211556211557211558211559211560211561211562211563211564211565211566211567211568211569211570211571211572211573211574211575211576211577211578211579211580211581211582211583211584211585211586211587211588211589211590211591211592211593211594211595211596211597211598211599211600211601211602211603211604211605211606211607211608211609211610211611211612211613211614211615211616211617211618211619211620211621211622211623211624211625211626211627211628211629211630211631211632211633211634211635211636211637211638211639211640211641211642211643211644211645211646211647211648211649211650211651211652211653211654211655211656211657211658211659211660211661211662211663211664211665211666211667211668211669211670211671211672211673211674211675211676211677211678211679211680211681211682211683211684211685211686211687211688211689211690211691211692211693211694211695211696211697211698211699211700211701211702211703211704211705211706211707211708211709211710211711211712211713211714211715211716211717211718211719211720211721211722211723211724211725211726211727211728211729211730211731211732211733211734211735211736211737211738211739211740211741211742211743211744211745211746211747211748211749211750211751211752211753211754211755211756211757211758211759211760211761211762211763211764211765211766211767211768211769211770211771211772211773211774211775211776211777211778211779211780211781211782211783211784211785211786211787211788211789211790211791211792211793211794211795211796211797211798211799211800211801211802211803211804211805211806211807211808211809211810211811211812211813211814211815211816211817211818211819211820211821211822211823211824211825211826211827211828211829211830211831211832211833211834211835211836211837211838211839211840211841211842211843211844211845211846211847211848211849211850211851211852211853211854211855211856211857211858211859211860211861211862211863211864211865211866211867211868211869211870211871211872211873211874211875211876211877211878211879211880211881211882211883211884211885211886211887211888211889211890211891211892211893211894211895211896211897211898211899211900211901211902211903211904211905211906211907211908211909211910211911211912211913211914211915211916211917211918211919211920211921211922211923211924211925211926211927211928211929211930211931211932211933211934211935211936211937211938211939211940211941211942211943211944211945211946211947211948211949211950211951211952211953211954211955211956211957211958211959211960211961211962211963211964211965211966211967211968211969211970211971211972211973211974211975211976211977211978211979211980211981211982211983211984211985211986211987211988211989211990211991211992211993211994211995211996211997211998211999212000212001212002212003212004212005212006212007212008212009212010212011212012212013212014212015212016212017212018212019212020212021212022212023212024212025212026212027212028212029212030212031212032212033212034212035212036212037212038212039212040212041212042212043212044212045212046212047212048212049212050212051212052212053212054212055212056212057212058212059212060212061212062212063212064212065212066212067212068212069212070212071212072212073212074212075212076212077212078212079212080212081212082212083212084212085212086212087212088212089212090212091212092212093212094212095212096212097212098212099212100212101212102212103212104212105212106212107212108212109212110212111212112212113212114212115212116212117212118212119212120212121212122212123212124212125212126212127212128212129212130212131212132212133212134212135212136212137212138212139212140212141212142212143212144212145212146212147212148212149212150212151212152212153212154212155212156212157212158212159212160212161212162212163212164212165212166212167212168212169212170212171212172212173212174212175212176212177212178212179212180212181212182212183212184212185212186212187212188212189212190212191212192212193212194212195212196212197212198212199212200212201212202212203212204212205212206212207212208212209212210212211212212212213212214212215212216212217212218212219212220212221212222212223212224212225212226212227212228212229212230212231212232212233212234212235212236212237212238212239212240212241212242212243212244212245212246212247212248212249212250212251212252212253212254212255212256212257212258212259212260212261212262212263212264212265212266212267212268212269212270212271212272212273212274212275212276212277212278212279212280212281212282212283212284212285212286212287212288212289212290212291212292212293212294212295212296212297212298212299212300212301212302212303212304212305212306212307212308212309212310212311212312212313212314212315212316212317212318212319212320212321212322212323212324212325212326212327212328212329212330212331212332212333212334212335212336212337212338212339212340212341212342212343212344212345212346212347212348212349212350212351212352212353212354212355212356212357212358212359212360212361212362212363212364212365212366212367212368212369212370212371212372212373212374212375212376212377212378212379212380212381212382212383212384212385212386212387212388212389212390212391212392212393212394212395212396212397212398212399212400212401212402212403212404212405212406212407212408212409212410212411212412212413212414212415212416212417212418212419212420212421212422212423212424212425212426212427212428212429212430212431212432212433212434212435212436212437212438212439212440212441212442212443212444212445212446212447212448212449212450212451212452212453212454212455212456212457212458212459212460212461212462212463212464212465212466212467212468212469212470212471212472212473212474212475212476212477212478212479212480212481212482212483212484212485212486212487212488212489212490212491212492212493212494212495212496212497212498212499212500212501212502212503212504212505212506212507212508212509212510212511212512212513212514212515212516212517212518212519212520212521212522212523212524212525212526212527212528212529212530212531212532212533212534212535212536212537212538212539212540212541212542212543212544212545212546212547212548212549212550212551212552212553212554212555212556212557212558212559212560212561212562212563212564212565212566212567212568212569212570212571212572212573212574212575212576212577212578212579212580212581212582212583212584212585212586212587212588212589212590212591212592212593212594212595212596212597212598212599212600212601212602212603212604212605212606212607212608212609212610212611212612212613212614212615212616212617212618212619212620212621212622212623212624212625212626212627212628212629212630212631212632212633212634212635212636212637212638212639212640212641212642212643212644212645212646212647212648212649212650212651212652212653212654212655212656212657212658212659212660212661212662212663212664212665212666212667212668212669212670212671212672212673212674212675212676212677212678212679212680212681212682212683212684212685212686212687212688212689212690212691212692212693212694212695212696212697212698212699212700212701212702212703212704212705212706212707212708212709212710212711212712212713212714212715212716212717212718212719212720212721212722212723212724212725212726212727212728212729212730212731212732212733212734212735212736212737212738212739212740212741212742212743212744212745212746212747212748212749212750212751212752212753212754212755212756212757212758212759212760212761212762212763212764212765212766212767212768212769212770212771212772212773212774212775212776212777212778212779212780212781212782212783212784212785212786212787212788212789212790212791212792212793212794212795212796212797212798212799212800212801212802212803212804212805212806212807212808212809212810212811212812212813212814212815212816212817212818212819212820212821212822212823212824212825212826212827212828212829212830212831212832212833212834212835212836212837212838212839212840212841212842212843212844212845212846212847212848212849212850212851212852212853212854212855212856212857212858212859212860212861212862212863212864212865212866212867212868212869212870212871212872212873212874212875212876212877212878212879212880212881212882212883212884212885212886212887212888212889212890212891212892212893212894212895212896212897212898212899212900212901212902212903212904212905212906212907212908212909212910212911212912212913212914212915212916212917212918212919212920212921212922212923212924212925212926212927212928212929212930212931212932212933212934212935212936212937212938212939212940212941212942212943212944212945212946212947212948212949212950212951212952212953212954212955212956212957212958212959212960212961212962212963212964212965212966212967212968212969212970212971212972212973212974212975212976212977212978212979212980212981212982212983212984212985212986212987212988212989212990212991212992212993212994212995212996212997212998212999213000213001213002213003213004213005213006213007213008213009213010213011213012213013213014213015213016213017213018213019213020213021213022213023213024213025213026213027213028213029213030213031213032213033213034213035213036213037213038213039213040213041213042213043213044213045213046213047213048213049213050213051213052213053213054213055213056213057213058213059213060213061213062213063213064213065213066213067213068213069213070213071213072213073213074213075213076213077213078213079213080213081213082213083213084213085213086213087213088213089213090213091213092213093213094213095213096213097213098213099213100213101213102213103213104213105213106213107213108213109213110213111213112213113213114213115213116213117213118213119213120213121213122213123213124213125213126213127213128213129213130213131213132213133213134213135213136213137213138213139213140213141213142213143213144213145213146213147213148213149213150213151213152213153213154213155213156213157213158213159213160213161213162213163213164213165213166213167213168213169213170213171213172213173213174213175213176213177213178213179213180213181213182213183213184213185213186213187213188213189213190213191213192213193213194213195213196213197213198213199213200213201213202213203213204213205213206213207213208213209213210213211213212213213213214213215213216213217213218213219213220213221213222213223213224213225213226213227213228213229213230213231213232213233213234213235213236213237213238213239213240213241213242213243213244213245213246213247213248213249213250213251213252213253213254213255213256213257213258213259213260213261213262213263213264213265213266213267213268213269213270213271213272213273213274213275213276213277213278213279213280213281213282213283213284213285213286213287213288213289213290213291213292213293213294213295213296213297213298213299213300213301213302213303213304213305213306213307213308213309213310213311213312213313213314213315213316213317213318213319213320213321213322213323213324213325213326213327213328213329213330213331213332213333213334213335213336213337213338213339213340213341213342213343213344213345213346213347213348213349213350213351213352213353213354213355213356213357213358213359213360213361213362213363213364213365213366213367213368213369213370213371213372213373213374213375213376213377213378213379213380213381213382213383213384213385213386213387213388213389213390213391213392213393213394213395213396213397213398213399213400213401213402213403213404213405213406213407213408213409213410213411213412213413213414213415213416213417213418213419213420213421213422213423213424213425213426213427213428213429213430213431213432213433213434213435213436213437213438213439213440213441213442213443213444213445213446213447213448213449213450213451213452213453213454213455213456213457213458213459213460213461213462213463213464213465213466213467213468213469213470213471213472213473213474213475213476213477213478213479213480213481213482213483213484213485213486213487213488213489213490213491213492213493213494213495213496213497213498213499213500213501213502213503213504213505213506213507213508213509213510213511213512213513213514213515213516213517213518213519213520213521213522213523213524213525213526213527213528213529213530213531213532213533213534213535213536213537213538213539213540213541213542213543213544213545213546213547213548213549213550213551213552213553213554213555213556213557213558213559213560213561213562213563213564213565213566213567213568213569213570213571213572213573213574213575213576213577213578213579213580213581213582213583213584213585213586213587213588213589213590213591213592213593213594213595213596213597213598213599213600213601213602213603213604213605213606213607213608213609213610213611213612213613213614213615213616213617213618213619213620213621213622213623213624213625213626213627213628213629213630213631213632213633213634213635213636213637213638213639213640213641213642213643213644213645213646213647213648213649213650213651213652213653213654213655213656213657213658213659213660213661213662213663213664213665213666213667213668213669213670213671213672213673213674213675213676213677213678213679213680213681213682213683213684213685213686213687213688213689213690213691213692213693213694213695213696213697213698213699213700213701213702213703213704213705213706213707213708213709213710213711213712213713213714213715213716213717213718213719213720213721213722213723213724213725213726213727213728213729213730213731213732213733213734213735213736213737213738213739213740213741213742213743213744213745213746213747213748213749213750213751213752213753213754213755213756213757213758213759213760213761213762213763213764213765213766213767213768213769213770213771213772213773213774213775213776213777213778213779213780213781213782213783213784213785213786213787213788213789213790213791213792213793213794213795213796213797213798213799213800213801213802213803213804213805213806213807213808213809213810213811213812213813213814213815213816213817213818213819213820213821213822213823213824213825213826213827213828213829213830213831213832213833213834213835213836213837213838213839213840213841213842213843213844213845213846213847213848213849213850213851213852213853213854213855213856213857213858213859213860213861213862213863213864213865213866213867213868213869213870213871213872213873213874213875213876213877213878213879213880213881213882213883213884213885213886213887213888213889213890213891213892213893213894213895213896213897213898213899213900213901213902213903213904213905213906213907213908213909213910213911213912213913213914213915213916213917213918213919213920213921213922213923213924213925213926213927213928213929213930213931213932213933213934213935213936213937213938213939213940213941213942213943213944213945213946213947213948213949213950213951213952213953213954213955213956213957213958213959213960213961213962213963213964213965213966213967213968213969213970213971213972213973213974213975213976213977213978213979213980213981213982213983213984213985213986213987213988213989213990213991213992213993213994213995213996213997213998213999214000214001214002214003214004214005214006214007214008214009214010214011214012214013214014214015214016214017214018214019214020214021214022214023214024214025214026214027214028214029214030214031214032214033214034214035214036214037214038214039214040214041214042214043214044214045214046214047214048214049214050214051214052214053214054214055214056214057214058214059214060214061214062214063214064214065214066214067214068214069214070214071214072214073214074214075214076214077214078214079214080214081214082214083214084214085214086214087214088214089214090214091214092214093214094214095214096214097214098214099214100214101214102214103214104214105214106214107214108214109214110214111214112214113214114214115214116214117214118214119214120214121214122214123214124214125214126214127214128214129214130214131214132214133214134214135214136214137214138214139214140214141214142214143214144214145214146214147214148214149214150214151214152214153214154214155214156214157214158214159214160214161214162214163214164214165214166214167214168214169214170214171214172214173214174214175214176214177214178214179214180214181214182214183214184214185214186214187214188214189214190214191214192214193214194214195214196214197214198214199214200214201214202214203214204214205214206214207214208214209214210214211214212214213214214214215214216214217214218214219214220214221214222214223214224214225214226214227214228214229214230214231214232214233214234214235214236214237214238214239214240214241214242214243214244214245214246214247214248214249214250214251214252214253214254214255214256214257214258214259214260214261214262214263214264214265214266214267214268214269214270214271214272214273214274214275214276214277214278214279214280214281214282214283214284214285214286214287214288214289214290214291214292214293214294214295214296214297214298214299214300214301214302214303214304214305214306214307214308214309214310214311214312214313214314214315214316214317214318214319214320214321214322214323214324214325214326214327214328214329214330214331214332214333214334214335214336214337214338214339214340214341214342214343214344214345214346214347214348214349214350214351214352214353214354214355214356214357214358214359214360214361214362214363214364214365214366214367214368214369214370214371214372214373214374214375214376214377214378214379214380214381214382214383214384214385214386214387214388214389214390214391214392214393214394214395214396214397214398214399214400214401214402214403214404214405214406214407214408214409214410214411214412214413214414214415214416214417214418214419214420214421214422214423214424214425214426214427214428214429214430214431214432214433214434214435214436214437214438214439214440214441214442214443214444214445214446214447214448214449214450214451214452214453214454214455214456214457214458214459214460214461214462214463214464214465214466214467214468214469214470214471214472214473214474214475214476214477214478214479214480214481214482214483214484214485214486214487214488214489214490214491214492214493214494214495214496214497214498214499214500214501214502214503214504214505214506214507214508214509214510214511214512214513214514214515214516214517214518214519214520214521214522214523214524214525214526214527214528214529214530214531214532214533214534214535214536214537214538214539214540214541214542214543214544214545214546214547214548214549214550214551214552214553214554214555214556214557214558214559214560214561214562214563214564214565214566214567214568214569214570214571214572214573214574214575214576214577214578214579214580214581214582214583214584214585214586214587214588214589214590214591214592214593214594214595214596214597214598214599214600214601214602214603214604214605214606214607214608214609214610214611214612214613214614214615214616214617214618214619214620214621214622214623214624214625214626214627214628214629214630214631214632214633214634214635214636214637214638214639214640214641214642214643214644214645214646214647214648214649214650214651214652214653214654214655214656214657214658214659214660214661214662214663214664214665214666214667214668214669214670214671214672214673214674214675214676214677214678214679214680214681214682214683214684214685214686214687214688214689214690214691214692214693214694214695214696214697214698214699214700214701214702214703214704214705214706214707214708214709214710214711214712214713214714214715214716214717214718214719214720214721214722214723214724214725214726214727214728214729214730214731214732214733214734214735214736214737214738214739214740214741214742214743214744214745214746214747214748214749214750214751214752214753214754214755214756214757214758214759214760214761214762214763214764214765214766214767214768214769214770214771214772214773214774214775214776214777214778214779214780214781214782214783214784214785214786214787214788214789214790214791214792214793214794214795214796214797214798214799214800214801214802214803214804214805214806214807214808214809214810214811214812214813214814214815214816214817214818214819214820214821214822214823214824214825214826214827214828214829214830214831214832214833214834214835214836214837214838214839214840214841214842214843214844214845214846214847214848214849214850214851214852214853214854214855214856214857214858214859214860214861214862214863214864214865214866214867214868214869214870214871214872214873214874214875214876214877214878214879214880214881214882214883214884214885214886214887214888214889214890214891214892214893214894214895214896214897214898214899214900214901214902214903214904214905214906214907214908214909214910214911214912214913214914214915214916214917214918214919214920214921214922214923214924214925214926214927214928214929214930214931214932214933214934214935214936214937214938214939214940214941214942214943214944214945214946214947214948214949214950214951214952214953214954214955214956214957214958214959214960214961214962214963214964214965214966214967214968214969214970214971214972214973214974214975214976214977214978214979214980214981214982214983214984214985214986214987214988214989214990214991214992214993214994214995214996214997214998214999215000215001215002215003215004215005215006215007215008215009215010215011215012215013215014215015215016215017215018215019215020215021215022215023215024215025215026215027215028215029215030215031215032215033215034215035215036215037215038215039215040215041215042215043215044215045215046215047215048215049215050215051215052215053215054215055215056215057215058215059215060215061215062215063215064215065215066215067215068215069215070215071215072215073215074215075215076215077215078215079215080215081215082215083215084215085215086215087215088215089215090215091215092215093215094215095215096215097215098215099215100215101215102215103215104215105215106215107215108215109215110215111215112215113215114215115215116215117215118215119215120215121215122215123215124215125215126215127215128215129215130215131215132215133215134215135215136215137215138215139215140215141215142215143215144215145215146215147215148215149215150215151215152215153215154215155215156215157215158215159215160215161215162215163215164215165215166215167215168215169215170215171215172215173215174215175215176215177215178215179215180215181215182215183215184215185215186215187215188215189215190215191215192215193215194215195215196215197215198215199215200215201215202215203215204215205215206215207215208215209215210215211215212215213215214215215215216215217215218215219215220215221215222215223215224215225215226215227215228215229215230215231215232215233215234215235215236215237215238215239215240215241215242215243215244215245215246215247215248215249215250215251215252215253215254215255215256215257215258215259215260215261215262215263215264215265215266215267215268215269215270215271215272215273215274215275215276215277215278215279215280215281215282215283215284215285215286215287215288215289215290215291215292215293215294215295215296215297215298215299215300215301215302215303215304215305215306215307215308215309215310215311215312215313215314215315215316215317215318215319215320215321215322215323215324215325215326215327215328215329215330215331215332215333215334215335215336215337215338215339215340215341215342215343215344215345215346215347215348215349215350215351215352215353215354215355215356215357215358215359215360215361215362215363215364215365215366215367215368215369215370215371215372215373215374215375215376215377215378215379215380215381215382215383215384215385215386215387215388215389215390215391215392215393215394215395215396215397215398215399215400215401215402215403215404215405215406215407215408215409215410215411215412215413215414215415215416215417215418215419215420215421215422215423215424215425215426215427215428215429215430215431215432215433215434215435215436215437215438215439215440215441215442215443215444215445215446215447215448215449215450215451215452215453215454215455215456215457215458215459215460215461215462215463215464215465215466215467215468215469215470215471215472215473215474215475215476215477215478215479215480215481215482215483215484215485215486215487215488215489215490215491215492215493215494215495215496215497215498215499215500215501215502215503215504215505215506215507215508215509215510215511215512215513215514215515215516215517215518215519215520215521215522215523215524215525215526215527215528215529215530215531215532215533215534215535215536215537215538215539215540215541215542215543215544215545215546215547215548215549215550215551215552215553215554215555215556215557215558215559215560215561215562215563215564215565215566215567215568215569215570215571215572215573215574215575215576215577215578215579215580215581215582215583215584215585215586215587215588215589215590215591215592215593215594215595215596215597215598215599215600215601215602215603215604215605215606215607215608215609215610215611215612215613215614215615215616215617215618215619215620215621215622215623215624215625215626215627215628215629215630215631215632215633215634215635215636215637215638215639215640215641215642215643215644215645215646215647215648215649215650215651215652215653215654215655215656215657215658215659215660215661215662215663215664215665215666215667215668215669215670215671215672215673215674215675215676215677215678215679215680215681215682215683215684215685215686215687215688215689215690215691215692215693215694215695215696215697215698215699215700215701215702215703215704215705215706215707215708215709215710215711215712215713215714215715215716215717215718215719215720215721215722215723215724215725215726215727215728215729215730215731215732215733215734215735215736215737215738215739215740215741215742215743215744215745215746215747215748215749215750215751215752215753215754215755215756215757215758215759215760215761215762215763215764215765215766215767215768215769215770215771215772215773215774215775215776215777215778215779215780215781215782215783215784215785215786215787215788215789215790215791215792215793215794215795215796215797215798215799215800215801215802215803215804215805215806215807215808215809215810215811215812215813215814215815215816215817215818215819215820215821215822215823215824215825215826215827215828215829215830215831215832215833215834215835215836215837215838215839215840215841215842215843215844215845215846215847215848215849215850215851215852215853215854215855215856215857215858215859215860215861215862215863215864215865215866215867215868215869215870215871215872215873215874215875215876215877215878215879215880215881215882215883215884215885215886215887215888215889215890215891215892215893215894215895215896215897215898215899215900215901215902215903215904215905215906215907215908215909215910215911215912215913215914215915215916215917215918215919215920215921215922215923215924215925215926215927215928215929215930215931215932215933215934215935215936215937215938215939215940215941215942215943215944215945215946215947215948215949215950215951215952215953215954215955215956215957215958215959215960215961215962215963215964215965215966215967215968215969215970215971215972215973215974215975215976215977215978215979215980215981215982215983215984215985215986215987215988215989215990215991215992215993215994215995215996215997215998215999216000216001216002216003216004216005216006216007216008216009216010216011216012216013216014216015216016216017216018216019216020216021216022216023216024216025216026216027216028216029216030216031216032216033216034216035216036216037216038216039216040216041216042216043216044216045216046216047216048216049216050216051216052216053216054216055216056216057216058216059216060216061216062216063216064216065216066216067216068216069216070216071216072216073216074216075216076216077216078216079216080216081216082216083216084216085216086216087216088216089216090216091216092216093216094216095216096216097216098216099216100216101216102216103216104216105216106216107216108216109216110216111216112216113216114216115216116216117216118216119216120216121216122216123216124216125216126216127216128216129216130216131216132216133216134216135216136216137216138216139216140216141216142216143216144216145216146216147216148216149216150216151216152216153216154216155216156216157216158216159216160216161216162216163216164216165216166216167216168216169216170216171216172216173216174216175216176216177216178216179216180216181216182216183216184216185216186216187216188216189216190216191216192216193216194216195216196216197216198216199216200216201216202216203216204216205216206216207216208216209216210216211216212216213216214216215216216216217216218216219216220216221216222216223216224216225216226216227216228216229216230216231216232216233216234216235216236216237216238216239216240216241216242216243216244216245216246216247216248216249216250216251216252216253216254216255216256216257216258216259216260216261216262216263216264216265216266216267216268216269216270216271216272216273216274216275216276216277216278216279216280216281216282216283216284216285216286216287216288216289216290216291216292216293216294216295216296216297216298216299216300216301216302216303216304216305216306216307216308216309216310216311216312216313216314216315216316216317216318216319216320216321216322216323216324216325216326216327216328216329216330216331216332216333216334216335216336216337216338216339216340216341216342216343216344216345216346216347216348216349216350216351216352216353216354216355216356216357216358216359216360216361216362216363216364216365216366216367216368216369216370216371216372216373216374216375216376216377216378216379216380216381216382216383216384216385216386216387216388216389216390216391216392216393216394216395216396216397216398216399216400216401216402216403216404216405216406216407216408216409216410216411216412216413216414216415216416216417216418216419216420216421216422216423216424216425216426216427216428216429216430216431216432216433216434216435216436216437216438216439216440216441216442216443216444216445216446216447216448216449216450216451216452216453216454216455216456216457216458216459216460216461216462216463216464216465216466216467216468216469216470216471216472216473216474216475216476216477216478216479216480216481216482216483216484216485216486216487216488216489216490216491216492216493216494216495216496216497216498216499216500216501216502216503216504216505216506216507216508216509216510216511216512216513216514216515216516216517216518216519216520216521216522216523216524216525216526216527216528216529216530216531216532216533216534216535216536216537216538216539216540216541216542216543216544216545216546216547216548216549216550216551216552216553216554216555216556216557216558216559216560216561216562216563216564216565216566216567216568216569216570216571216572216573216574216575216576216577216578216579216580216581216582216583216584216585216586216587216588216589216590216591216592216593216594216595216596216597216598216599216600216601216602216603216604216605216606216607216608216609216610216611216612216613216614216615216616216617216618216619216620216621216622216623216624216625216626216627216628216629216630216631216632216633216634216635216636216637216638216639216640216641216642216643216644216645216646216647216648216649216650216651216652216653216654216655216656216657216658216659216660216661216662216663216664216665216666216667216668216669216670216671216672216673216674216675216676216677216678216679216680216681216682216683216684216685216686216687216688216689216690216691216692216693216694216695216696216697216698216699216700216701216702216703216704216705216706216707216708216709216710216711216712216713216714216715216716216717216718216719216720216721216722216723216724216725216726216727216728216729216730216731216732216733216734216735216736216737216738216739216740216741216742216743216744216745216746216747216748216749216750216751216752216753216754216755216756216757216758216759216760216761216762216763216764216765216766216767216768216769216770216771216772216773216774216775216776216777216778216779216780216781216782216783216784216785216786216787216788216789216790216791216792216793216794216795216796216797216798216799216800216801216802216803216804216805216806216807216808216809216810216811216812216813216814216815216816216817216818216819216820216821216822216823216824216825216826216827216828216829216830216831216832216833216834216835216836216837216838216839216840216841216842216843216844216845216846216847216848216849216850216851216852216853216854216855216856216857216858216859216860216861216862216863216864216865216866216867216868216869216870216871216872216873216874216875216876216877216878216879216880216881216882216883216884216885216886216887216888216889216890216891216892216893216894216895216896216897216898216899216900216901216902216903216904216905216906216907216908216909216910216911216912216913216914216915216916216917216918216919216920216921216922216923216924216925216926216927216928216929216930216931216932216933216934216935216936216937216938216939216940216941216942216943216944216945216946216947216948216949216950216951216952216953216954216955216956216957216958216959216960216961216962216963216964216965216966216967216968216969216970216971216972216973216974216975216976216977216978216979216980216981216982216983216984216985216986216987216988216989216990216991216992216993216994216995216996216997216998216999217000217001217002217003217004217005217006217007217008217009217010217011217012217013217014217015217016217017217018217019217020217021217022217023217024217025217026217027217028217029217030217031217032217033217034217035217036217037217038217039217040217041217042217043217044217045217046217047217048217049217050217051217052217053217054217055217056217057217058217059217060217061217062217063217064217065217066217067217068217069217070217071217072217073217074217075217076217077217078217079217080217081217082217083217084217085217086217087217088217089217090217091217092217093217094217095217096217097217098217099217100217101217102217103217104217105217106217107217108217109217110217111217112217113217114217115217116217117217118217119217120217121217122217123217124217125217126217127217128217129217130217131217132217133217134217135217136217137217138217139217140217141217142217143217144217145217146217147217148217149217150217151217152217153217154217155217156217157217158217159217160217161217162217163217164217165217166217167217168217169217170217171217172217173217174217175217176217177217178217179217180217181217182217183217184217185217186217187217188217189217190217191217192217193217194217195217196217197217198217199217200217201217202217203217204217205217206217207217208217209217210217211217212217213217214217215217216217217217218217219217220217221217222217223217224217225217226217227217228217229217230217231217232217233217234217235217236217237217238217239217240217241217242217243217244217245217246217247217248217249217250217251217252217253217254217255217256217257217258217259217260217261217262217263217264217265217266217267217268217269217270217271217272217273217274217275217276217277217278217279217280217281217282217283217284217285217286217287217288217289217290217291217292217293217294217295217296217297217298217299217300217301217302217303217304217305217306217307217308217309217310217311217312217313217314217315217316217317217318217319217320217321217322217323217324217325217326217327217328217329217330217331217332217333217334217335217336217337217338217339217340217341217342217343217344217345217346217347217348217349217350217351217352217353217354217355217356217357217358217359217360217361217362217363217364217365217366217367217368217369217370217371217372217373217374217375217376217377217378217379217380217381217382217383217384217385217386217387217388217389217390217391217392217393217394217395217396217397217398217399217400217401217402217403217404217405217406217407217408217409217410217411217412217413217414217415217416217417217418217419217420217421217422217423217424217425217426217427217428217429217430217431217432217433217434217435217436217437217438217439217440217441217442217443217444217445217446217447217448217449217450217451217452217453217454217455217456217457217458217459217460217461217462217463217464217465217466217467217468217469217470217471217472217473217474217475217476217477217478217479217480217481217482217483217484217485217486217487217488217489217490217491217492217493217494217495217496217497217498217499217500217501217502217503217504217505217506217507217508217509217510217511217512217513217514217515217516217517217518217519217520217521217522217523217524217525217526217527217528217529217530217531217532217533217534217535217536217537217538217539217540217541217542217543217544217545217546217547217548217549217550217551217552217553217554217555217556217557217558217559217560217561217562217563217564217565217566217567217568217569217570217571217572217573217574217575217576217577217578217579217580217581217582217583217584217585217586217587217588217589217590217591217592217593217594217595217596217597217598217599217600217601217602217603217604217605217606217607217608217609217610217611217612217613217614217615217616217617217618217619217620217621217622217623217624217625217626217627217628217629217630217631217632217633217634217635217636217637217638217639217640217641217642217643217644217645217646217647217648217649217650217651217652217653217654217655217656217657217658217659217660217661217662217663217664217665217666217667217668217669217670217671217672217673217674217675217676217677217678217679217680217681217682217683217684217685217686217687217688217689217690217691217692217693217694217695217696217697217698217699217700217701217702217703217704217705217706217707217708217709217710217711217712217713217714217715217716217717217718217719217720217721217722217723217724217725217726217727217728217729217730217731217732217733217734217735217736217737217738217739217740217741217742217743217744217745217746217747217748217749217750217751217752217753217754217755217756217757217758217759217760217761217762217763217764217765217766217767217768217769217770217771217772217773217774217775217776217777217778217779217780217781217782217783217784217785217786217787217788217789217790217791217792217793217794217795217796217797217798217799217800217801217802217803217804217805217806217807217808217809217810217811217812217813217814217815217816217817217818217819217820217821217822217823217824217825217826217827217828217829217830217831217832217833217834217835217836217837217838217839217840217841217842217843217844217845217846217847217848217849217850217851217852217853217854217855217856217857217858217859217860217861217862217863217864217865217866217867217868217869217870217871217872217873217874217875217876217877217878217879217880217881217882217883217884217885217886217887217888217889217890217891217892217893217894217895217896217897217898217899217900217901217902217903217904217905217906217907217908217909217910217911217912217913217914217915217916217917217918217919217920217921217922217923217924217925217926217927217928217929217930217931217932217933217934217935217936217937217938217939217940217941217942217943217944217945217946217947217948217949217950217951217952217953217954217955217956217957217958217959217960217961217962217963217964217965217966217967217968217969217970217971217972217973217974217975217976217977217978217979217980217981217982217983217984217985217986217987217988217989217990217991217992217993217994217995217996217997217998217999218000218001218002218003218004218005218006218007218008218009218010218011218012218013218014218015218016218017218018218019218020218021218022218023218024218025218026218027218028218029218030218031218032218033218034218035218036218037218038218039218040218041218042218043218044218045218046218047218048218049218050218051218052218053218054218055218056218057218058218059218060218061218062218063218064218065218066218067218068218069218070218071218072218073218074218075218076218077218078218079218080218081218082218083218084218085218086218087218088218089218090218091218092218093218094218095218096218097218098218099218100218101218102218103218104218105218106218107218108218109218110218111218112218113218114218115218116218117218118218119218120218121218122218123218124218125218126218127218128218129218130218131218132218133218134218135218136218137218138218139218140218141218142218143218144218145218146218147218148218149218150218151218152218153218154218155218156218157218158218159218160218161218162218163218164218165218166218167218168218169218170218171218172218173218174218175218176218177218178218179218180218181218182218183218184218185218186218187218188218189218190218191218192218193218194218195218196218197218198218199218200218201218202218203218204218205218206218207218208218209218210218211218212218213218214218215218216218217218218218219218220218221218222218223218224218225218226218227218228218229218230218231218232218233218234218235218236218237218238218239218240218241218242218243218244218245218246218247218248218249218250218251218252218253218254218255218256218257218258218259218260218261218262218263218264218265218266218267218268218269218270218271218272218273218274218275218276218277218278218279218280218281218282218283218284218285218286218287218288218289218290218291218292218293218294218295218296218297218298218299218300218301218302218303218304218305218306218307218308218309218310218311218312218313218314218315218316218317218318218319218320218321218322218323218324218325218326218327218328218329218330218331218332218333218334218335218336218337218338218339218340218341218342218343218344218345218346218347218348218349218350218351218352218353218354218355218356218357218358218359218360218361218362218363218364218365218366218367218368218369218370218371218372218373218374218375218376218377218378218379218380218381218382218383218384218385218386218387218388218389218390218391218392218393218394218395218396218397218398218399218400218401218402218403218404218405218406218407218408218409218410218411218412218413218414218415218416218417218418218419218420218421218422218423218424218425218426218427218428218429218430218431218432218433218434218435218436218437218438218439218440218441218442218443218444218445218446218447218448218449218450218451218452218453218454218455218456218457218458218459218460218461218462218463218464218465218466218467218468218469218470218471218472218473218474218475218476218477218478218479218480218481218482218483218484218485218486218487218488218489218490218491218492218493218494218495218496218497218498218499218500218501218502218503218504218505218506218507218508218509218510218511218512218513218514218515218516218517218518218519218520218521218522218523218524218525218526218527218528218529218530218531218532218533218534218535218536218537218538218539218540218541218542218543218544218545218546218547218548218549218550218551218552218553218554218555218556218557218558218559218560218561218562218563218564218565218566218567218568218569218570218571218572218573218574218575218576218577218578218579218580218581218582218583218584218585218586218587218588218589218590218591218592218593218594218595218596218597218598218599218600218601218602218603218604218605218606218607218608218609218610218611218612218613218614218615218616218617218618218619218620218621218622218623218624218625218626218627218628218629218630218631218632218633218634218635218636218637218638218639218640218641218642218643218644218645218646218647218648218649218650218651218652218653218654218655218656218657218658218659218660218661218662218663218664218665218666218667218668218669218670218671218672218673218674218675218676218677218678218679218680218681218682218683218684218685218686218687218688218689218690218691218692218693218694218695218696218697218698218699218700218701218702218703218704218705218706218707218708218709218710218711218712218713218714218715218716218717218718218719218720218721218722218723218724218725218726218727218728218729218730218731218732218733218734218735218736218737218738218739218740218741218742218743218744218745218746218747218748218749218750218751218752218753218754218755218756218757218758218759218760218761218762218763218764218765218766218767218768218769218770218771218772218773218774218775218776218777218778218779218780218781218782218783218784218785218786218787218788218789218790218791218792218793218794218795218796218797218798218799218800218801218802218803218804218805218806218807218808218809218810218811218812218813218814218815218816218817218818218819218820218821218822218823218824218825218826218827218828218829218830218831218832218833218834218835218836218837218838218839218840218841218842218843218844218845218846218847218848218849218850218851218852218853218854218855218856218857218858218859218860218861218862218863218864218865218866218867218868218869218870218871218872218873218874218875218876218877218878218879218880218881218882218883218884218885218886218887218888218889218890218891218892218893218894218895218896218897218898218899218900218901218902218903218904218905218906218907218908218909218910218911218912218913218914218915218916218917218918218919218920218921218922218923218924218925218926218927218928218929218930218931218932218933218934218935218936218937218938218939218940218941218942218943218944218945218946218947218948218949218950218951218952218953218954218955218956218957218958218959218960218961218962218963218964218965218966218967218968218969218970218971218972218973218974218975218976218977218978218979218980218981218982218983218984218985218986218987218988218989218990218991218992218993218994218995218996218997218998218999219000219001219002219003219004219005219006219007219008219009219010219011219012219013219014219015219016219017219018219019219020219021219022219023219024219025219026219027219028219029219030219031219032219033219034219035219036219037219038219039219040219041219042219043219044219045219046219047219048219049219050219051219052219053219054219055219056219057219058219059219060219061219062219063219064219065219066219067219068219069219070219071219072219073219074219075219076219077219078219079219080219081219082219083219084219085219086219087219088219089219090219091219092219093219094219095219096219097219098219099219100219101219102219103219104219105219106219107219108219109219110219111219112219113219114219115219116219117219118219119219120219121219122219123219124219125219126219127219128219129219130219131219132219133219134219135219136219137219138219139219140219141219142219143219144219145219146219147219148219149219150219151219152219153219154219155219156219157219158219159219160219161219162219163219164219165219166219167219168219169219170219171219172219173219174219175219176219177219178219179219180219181219182219183219184219185219186219187219188219189219190219191219192219193219194219195219196219197219198219199219200219201219202219203219204219205219206219207219208219209219210219211219212219213219214219215219216219217219218219219219220219221219222219223219224219225219226219227219228219229219230219231219232219233219234219235219236219237219238219239219240219241219242219243219244219245219246219247219248219249219250219251219252219253219254219255219256219257219258219259219260219261219262219263219264219265219266219267219268219269219270219271219272219273219274219275219276219277219278219279219280219281219282219283219284219285219286219287219288219289219290219291219292219293219294219295219296219297219298219299219300219301219302219303219304219305219306219307219308219309219310219311219312219313219314219315219316219317219318219319219320219321219322219323219324219325219326219327219328219329219330219331219332219333219334219335219336219337219338219339219340219341219342219343219344219345219346219347219348219349219350219351219352219353219354219355219356219357219358219359219360219361219362219363219364219365219366219367219368219369219370219371219372219373219374219375219376219377219378219379219380219381219382219383219384219385219386219387219388219389219390219391219392219393219394219395219396219397219398219399219400219401219402219403219404219405219406219407219408219409219410219411219412219413219414219415219416219417219418219419219420219421219422219423219424219425219426219427219428219429219430219431219432219433219434219435219436219437219438219439219440219441219442219443219444219445219446219447219448219449219450219451219452219453219454219455219456219457219458219459219460219461219462219463219464219465219466219467219468219469219470219471219472219473219474219475219476219477219478219479219480219481219482219483219484219485219486219487219488219489219490219491219492219493219494219495219496219497219498219499219500219501219502219503219504219505219506219507219508219509219510219511219512219513219514219515219516219517219518219519219520219521219522219523219524219525219526219527219528219529219530219531219532219533219534219535219536219537219538219539219540219541219542219543219544219545219546219547219548219549219550219551219552219553219554219555219556219557219558219559219560219561219562219563219564219565219566219567219568219569219570219571219572219573219574219575219576219577219578219579219580219581219582219583219584219585219586219587219588219589219590219591219592219593219594219595219596219597219598219599219600219601219602219603219604219605219606219607219608219609219610219611219612219613219614219615219616219617219618219619219620219621219622219623219624219625219626219627219628219629219630219631219632219633219634219635219636219637219638219639219640219641219642219643219644219645219646219647219648219649219650219651219652219653219654219655219656219657219658219659219660219661219662219663219664219665219666219667219668219669219670219671219672219673219674219675219676219677219678219679219680219681219682219683219684219685219686219687219688219689219690219691219692219693219694219695219696219697219698219699219700219701219702219703219704219705219706219707219708219709219710219711219712219713219714219715219716219717219718219719219720219721219722219723219724219725219726219727219728219729219730219731219732219733219734219735219736219737219738219739219740219741219742219743219744219745219746219747219748219749219750219751219752219753219754219755219756219757219758219759219760219761219762219763219764219765219766219767219768219769219770219771219772219773219774219775219776219777219778219779219780219781219782219783219784219785219786219787219788219789219790219791219792219793219794219795219796219797219798219799219800219801219802219803219804219805219806219807219808219809219810219811219812219813219814219815219816219817219818219819219820219821219822219823219824219825219826219827219828219829219830219831219832219833219834219835219836219837219838219839219840219841219842219843219844219845219846219847219848219849219850219851219852219853219854219855219856219857219858219859219860219861219862219863219864219865219866219867219868219869219870219871219872219873219874219875219876219877219878219879219880219881219882219883219884219885219886219887219888219889219890219891219892219893219894219895219896219897219898219899219900219901219902219903219904219905219906219907219908219909219910219911219912219913219914219915219916219917219918219919219920219921219922219923219924219925219926219927219928219929219930219931219932219933219934219935219936219937219938219939219940219941219942219943219944219945219946219947219948219949219950219951219952219953219954219955219956219957219958219959219960219961219962219963219964219965219966219967219968219969219970219971219972219973219974219975219976219977219978219979219980219981219982219983219984219985219986219987219988219989219990219991219992219993219994219995219996219997219998219999220000220001220002220003220004220005220006220007220008220009220010220011220012220013220014220015220016220017220018220019220020220021220022220023220024220025220026220027220028220029220030220031220032220033220034220035220036220037220038220039220040220041220042220043220044220045220046220047220048220049220050220051220052220053220054220055220056220057220058220059220060220061220062220063220064220065220066220067220068220069220070220071220072220073220074220075220076220077220078220079220080220081220082220083220084220085220086220087220088220089220090220091220092220093220094220095220096220097220098220099220100220101220102220103220104220105220106220107220108220109220110220111220112220113220114220115220116220117220118220119220120220121220122220123220124220125220126220127220128220129220130220131220132220133220134220135220136220137220138220139220140220141220142220143220144220145220146220147220148220149220150220151220152220153220154220155220156220157220158220159220160220161220162220163220164220165220166220167220168220169220170220171220172220173220174220175220176220177220178220179220180220181220182220183220184220185220186220187220188220189220190220191220192220193220194220195220196220197220198220199220200220201220202220203220204220205220206220207220208220209220210220211220212220213220214220215220216220217220218220219220220220221220222220223220224220225220226220227220228220229220230220231220232220233220234220235220236220237220238220239220240220241220242220243220244220245220246220247220248220249220250220251220252220253220254220255220256220257220258220259220260220261220262220263220264220265220266220267220268220269220270220271220272220273220274220275220276220277220278220279220280220281220282220283220284220285220286220287220288220289220290220291220292220293220294220295220296220297220298220299220300220301220302220303220304220305220306220307220308220309220310220311220312220313220314220315220316220317220318220319220320220321220322220323220324220325220326220327220328220329220330220331220332220333220334220335220336220337220338220339220340220341220342220343220344220345220346220347220348220349220350220351220352220353220354220355220356220357220358220359220360220361220362220363220364220365220366220367220368220369220370220371220372220373220374220375220376220377220378220379220380220381220382220383220384220385220386220387220388220389220390220391220392220393220394220395220396220397220398220399220400220401220402220403220404220405220406220407220408220409220410220411220412220413220414220415220416220417220418220419220420220421220422220423220424220425220426220427220428220429220430220431220432220433220434220435220436220437220438220439220440220441220442220443220444220445220446220447220448220449220450220451220452220453220454220455220456220457220458220459220460220461220462220463220464220465220466220467220468220469220470220471220472220473220474220475220476220477220478220479220480220481220482220483220484220485220486220487220488220489220490220491220492220493220494220495220496220497220498220499220500220501220502220503220504220505220506220507220508220509220510220511220512220513220514220515220516220517220518220519220520220521220522220523220524220525220526220527220528220529220530220531220532220533220534220535220536220537220538220539220540220541220542220543220544220545220546220547220548220549220550220551220552220553220554220555220556220557220558220559220560220561220562220563220564220565220566220567220568220569220570220571220572220573220574220575220576220577220578220579220580220581220582220583220584220585220586220587220588220589220590220591220592220593220594220595220596220597220598220599220600220601220602220603220604220605220606220607220608220609220610220611220612220613220614220615220616220617220618220619220620220621220622220623220624220625220626220627220628220629220630220631220632220633220634220635220636220637220638220639220640220641220642220643220644220645220646220647220648220649220650220651220652220653220654220655220656220657220658220659220660220661220662220663220664220665220666220667220668220669220670220671220672220673220674220675220676220677220678220679220680220681220682220683220684220685220686220687220688220689220690220691220692220693220694220695220696220697220698220699220700220701220702220703220704220705220706220707220708220709220710220711220712220713220714220715220716220717220718220719220720220721220722220723220724220725220726220727220728220729220730220731220732220733220734220735220736220737220738220739220740220741220742220743220744220745220746220747220748220749220750220751220752220753220754220755220756220757220758220759220760220761220762220763220764220765220766220767220768220769220770220771220772220773220774220775220776220777220778220779220780220781220782220783220784220785220786220787220788220789220790220791220792220793220794220795220796220797220798220799220800220801220802220803220804220805220806220807220808220809220810220811220812220813220814220815220816220817220818220819220820220821220822220823220824220825220826220827220828220829220830220831220832220833220834220835220836220837220838220839220840220841220842220843220844220845220846220847220848220849220850220851220852220853220854220855220856220857220858220859220860220861220862220863220864220865220866220867220868220869220870220871220872220873220874220875220876220877220878220879220880220881220882220883220884220885220886220887220888220889220890220891220892220893220894220895220896220897220898220899220900220901220902220903220904220905220906220907220908220909220910220911220912220913220914220915220916220917220918220919220920220921220922220923220924220925220926220927220928220929220930220931220932220933220934220935220936220937220938220939220940220941220942220943220944220945220946220947220948220949220950220951220952220953220954220955220956220957220958220959220960220961220962220963220964220965220966220967220968220969220970220971220972220973220974220975220976220977220978220979220980220981220982220983220984220985220986220987220988220989220990220991220992220993220994220995220996220997220998220999221000221001221002221003221004221005221006221007221008221009221010221011221012221013221014221015221016221017221018221019221020221021221022221023221024221025221026221027221028221029221030221031221032221033221034221035221036221037221038221039221040221041221042221043221044221045221046221047221048221049221050221051221052221053221054221055221056221057221058221059221060221061221062221063221064221065221066221067221068221069221070221071221072221073221074221075221076221077221078221079221080221081221082221083221084221085221086221087221088221089221090221091221092221093221094221095221096221097221098221099221100221101221102221103221104221105221106221107221108221109221110221111221112221113221114221115221116221117221118221119221120221121221122221123221124221125221126221127221128221129221130221131221132221133221134221135221136221137221138221139221140221141221142221143221144221145221146221147221148221149221150221151221152221153221154221155221156221157221158221159221160221161221162221163221164221165221166221167221168221169221170221171221172221173221174221175221176221177221178221179221180221181221182221183221184221185221186221187221188221189221190221191221192221193221194221195221196221197221198221199221200221201221202221203221204221205221206221207221208221209221210221211221212221213221214221215221216221217221218221219221220221221221222221223221224221225221226221227221228221229221230221231221232221233221234221235221236221237221238221239221240221241221242221243221244221245221246221247221248221249221250221251221252221253221254221255221256221257221258221259221260221261221262221263221264221265221266221267221268221269221270221271221272221273221274221275221276221277221278221279221280221281221282221283221284221285221286221287221288221289221290221291221292221293221294221295221296221297221298221299221300221301221302221303221304221305221306221307221308221309221310221311221312221313221314221315221316221317221318221319221320221321221322221323221324221325221326221327221328221329221330221331221332221333221334221335221336221337221338221339221340221341221342221343221344221345221346221347221348221349221350221351221352221353221354221355221356221357221358221359221360221361221362221363221364221365221366221367221368221369221370221371221372221373221374221375221376221377221378221379221380221381221382221383221384221385221386221387221388221389221390221391221392221393221394221395221396221397221398221399221400221401221402221403221404221405221406221407221408221409221410221411221412221413221414221415221416221417221418221419221420221421221422221423221424221425221426221427221428221429221430221431221432221433221434221435221436221437221438221439221440221441221442221443221444221445221446221447221448221449221450221451221452221453221454221455221456221457221458221459221460221461221462221463221464221465221466221467221468221469221470221471221472221473221474221475221476221477221478221479221480221481221482221483221484221485221486221487221488221489221490221491221492221493221494221495221496221497221498221499221500221501221502221503221504221505221506221507221508221509221510221511221512221513221514221515221516221517221518221519221520221521221522221523221524221525221526221527221528221529221530221531221532221533221534221535221536221537221538221539221540221541221542221543221544221545221546221547221548221549221550221551221552221553221554221555221556221557221558221559221560221561221562221563221564221565221566221567221568221569221570221571221572221573221574221575221576221577221578221579221580221581221582221583221584221585221586221587221588221589221590221591221592221593221594221595221596221597221598221599221600221601221602221603221604221605221606221607221608221609221610221611221612221613221614221615221616221617221618221619221620221621221622221623221624221625221626221627221628221629221630221631221632221633221634221635221636221637221638221639221640221641221642221643221644221645221646221647221648221649221650221651221652221653221654221655221656221657221658221659221660221661221662221663221664221665221666221667221668221669221670221671221672221673221674221675221676221677221678221679221680221681221682221683221684221685221686221687221688221689221690221691221692221693221694221695221696221697221698221699221700221701221702221703221704221705221706221707221708221709221710221711221712221713221714221715221716221717221718221719221720221721221722221723221724221725221726221727221728221729221730221731221732221733221734221735221736221737221738221739221740221741221742221743221744221745221746221747221748221749221750221751221752221753221754221755221756221757221758221759221760221761221762221763221764221765221766221767221768221769221770221771221772221773221774221775221776221777221778221779221780221781221782221783221784221785221786221787221788221789221790221791221792221793221794221795221796221797221798221799221800221801221802221803221804221805221806221807221808221809221810221811221812221813221814221815221816221817221818221819221820221821221822221823221824221825221826221827221828221829221830221831221832221833221834221835221836221837221838221839221840221841221842221843221844221845221846221847221848221849221850221851221852221853221854221855221856221857221858221859221860221861221862221863221864221865221866221867221868221869221870221871221872221873221874221875221876221877221878221879221880221881221882221883221884221885221886221887221888221889221890221891221892221893221894221895221896221897221898221899221900221901221902221903221904221905221906221907221908221909221910221911221912221913221914221915221916221917221918221919221920221921221922221923221924221925221926221927221928221929221930221931221932221933221934221935221936221937221938221939221940221941221942221943221944221945221946221947221948221949221950221951221952221953221954221955221956221957221958221959221960221961221962221963221964221965221966221967221968221969221970221971221972221973221974221975221976221977221978221979221980221981221982221983221984221985221986221987221988221989221990221991221992221993221994221995221996221997221998221999222000222001222002222003222004222005222006222007222008222009222010222011222012222013222014222015222016222017222018222019222020222021222022222023222024222025222026222027222028222029222030222031222032222033222034222035222036222037222038222039222040222041222042222043222044222045222046222047222048222049222050222051222052222053222054222055222056222057222058222059222060222061222062222063222064222065222066222067222068222069222070222071222072222073222074222075222076222077222078222079222080222081222082222083222084222085222086222087222088222089222090222091222092222093222094222095222096222097222098222099222100222101222102222103222104222105222106222107222108222109222110222111222112222113222114222115222116222117222118222119222120222121222122222123222124222125222126222127222128222129222130222131222132222133222134222135222136222137222138222139222140222141222142222143222144222145222146222147222148222149222150222151222152222153222154222155222156222157222158222159222160222161222162222163222164222165222166222167222168222169222170222171222172222173222174222175222176222177222178222179222180222181222182222183222184222185222186222187222188222189222190222191222192222193222194222195222196222197222198222199222200222201222202222203222204222205222206222207222208222209222210222211222212222213222214222215222216222217222218222219222220222221222222222223222224222225222226222227222228222229222230222231222232222233222234222235222236222237222238222239222240222241222242222243222244222245222246222247222248222249222250222251222252222253222254222255222256222257222258222259222260222261222262222263222264222265222266222267222268222269222270222271222272222273222274222275222276222277222278222279222280222281222282222283222284222285222286222287222288222289222290222291222292222293222294222295222296222297222298222299222300222301222302222303222304222305222306222307222308222309222310222311222312222313222314222315222316222317222318222319222320222321222322222323222324222325222326222327222328222329222330222331222332222333222334222335222336222337222338222339222340222341222342222343222344222345222346222347222348222349222350222351222352222353222354222355222356222357222358222359222360222361222362222363222364222365222366222367222368222369222370222371222372222373222374222375222376222377222378222379222380222381222382222383222384222385222386222387222388222389222390222391222392222393222394222395222396222397222398222399222400222401222402222403222404222405222406222407222408222409222410222411222412222413222414222415222416222417222418222419222420222421222422222423222424222425222426222427222428222429222430222431222432222433222434222435222436222437222438222439222440222441222442222443222444222445222446222447222448222449222450222451222452222453222454222455222456222457222458222459222460222461222462222463222464222465222466222467222468222469222470222471222472222473222474222475222476222477222478222479222480222481222482222483222484222485222486222487222488222489222490222491222492222493222494222495222496222497222498222499222500222501222502222503222504222505222506222507222508222509222510222511222512222513222514222515222516222517222518222519222520222521222522222523222524222525222526222527222528222529222530222531222532222533222534222535222536222537222538222539222540222541222542222543222544222545222546222547222548222549222550222551222552222553222554222555222556222557222558222559222560222561222562222563222564222565222566222567222568222569222570222571222572222573222574222575222576222577222578222579222580222581222582222583222584222585222586222587222588222589222590222591222592222593222594222595222596222597222598222599222600222601222602222603222604222605222606222607222608222609222610222611222612222613222614222615222616222617222618222619222620222621222622222623222624222625222626222627222628222629222630222631222632222633222634222635222636222637222638222639222640222641222642222643222644222645222646222647222648222649222650222651222652222653222654222655222656222657222658222659222660222661222662222663222664222665222666222667222668222669222670222671222672222673222674222675222676222677222678222679222680222681222682222683222684222685222686222687222688222689222690222691222692222693222694222695222696222697222698222699222700222701222702222703222704222705222706222707222708222709222710222711222712222713222714222715222716222717222718222719222720222721222722222723222724222725222726222727222728222729222730222731222732222733222734222735222736222737222738222739222740222741222742222743222744222745222746222747222748222749222750222751222752222753222754222755222756222757222758222759222760222761222762222763222764222765222766222767222768222769222770222771222772222773222774222775222776222777222778222779222780222781222782222783222784222785222786222787222788222789222790222791222792222793222794222795222796222797222798222799222800222801222802222803222804222805222806222807222808222809222810222811222812222813222814222815222816222817222818222819222820222821222822222823222824222825222826222827222828222829222830222831222832222833222834222835222836222837222838222839222840222841222842222843222844222845222846222847222848222849222850222851222852222853222854222855222856222857222858222859222860222861222862222863222864222865222866222867222868222869222870222871222872222873222874222875222876222877222878222879222880222881222882222883222884222885222886222887222888222889222890222891222892222893222894222895222896222897222898222899222900222901222902222903222904222905222906222907222908222909222910222911222912222913222914222915222916222917222918222919222920222921222922222923222924222925222926222927222928222929222930222931222932222933222934222935222936222937222938222939222940222941222942222943222944222945222946222947222948222949222950222951222952222953222954222955222956222957222958222959222960222961222962222963222964222965222966222967222968222969222970222971222972222973222974222975222976222977222978222979222980222981222982222983222984222985222986222987222988222989222990222991222992222993222994222995222996222997222998222999223000223001223002223003223004223005223006223007223008223009223010223011223012223013223014223015223016223017223018223019223020223021223022223023223024223025223026223027223028223029223030223031223032223033223034223035223036223037223038223039223040223041223042223043223044223045223046223047223048223049223050223051223052223053223054223055223056223057223058223059223060223061223062223063223064223065223066223067223068223069223070223071223072223073223074223075223076223077223078223079223080223081223082223083223084223085223086223087223088223089223090223091223092223093223094223095223096223097223098223099223100223101223102223103223104223105223106223107223108223109223110223111223112223113223114223115223116223117223118223119223120223121223122223123223124223125223126223127223128223129223130223131223132223133223134223135223136223137223138223139223140223141223142223143223144223145223146223147223148223149223150223151223152223153223154223155223156223157223158223159223160223161223162223163223164223165223166223167223168223169223170223171223172223173223174223175223176223177223178223179223180223181223182223183223184223185223186223187223188223189223190223191223192223193223194223195223196223197223198223199223200223201223202223203223204223205223206223207223208223209223210223211223212223213223214223215223216223217223218223219223220223221223222223223223224223225223226223227223228223229223230223231223232223233223234223235223236223237223238223239223240223241223242223243223244223245223246223247223248223249223250223251223252223253223254223255223256223257223258223259223260223261223262223263223264223265223266223267223268223269223270223271223272223273223274223275223276223277223278223279223280223281223282223283223284223285223286223287223288223289223290223291223292223293223294223295223296223297223298223299223300223301223302223303223304223305223306223307223308223309223310223311223312223313223314223315223316223317223318223319223320223321223322223323223324223325223326223327223328223329223330223331223332223333223334223335223336223337223338223339223340223341223342223343223344223345223346223347223348223349223350223351223352223353223354223355223356223357223358223359223360223361223362223363223364223365223366223367223368223369223370223371223372223373223374223375223376223377223378223379223380223381223382223383223384223385223386223387223388223389223390223391223392223393223394223395223396223397223398223399223400223401223402223403223404223405223406223407223408223409223410223411223412223413223414223415223416223417223418223419223420223421223422223423223424223425223426223427223428223429223430223431223432223433223434223435223436223437223438223439223440223441223442223443223444223445223446223447223448223449223450223451223452223453223454223455223456223457223458223459223460223461223462223463223464223465223466223467223468223469223470223471223472223473223474223475223476223477223478223479223480223481223482223483223484223485223486223487223488223489223490223491223492223493223494223495223496223497223498223499223500223501223502223503223504223505223506223507223508223509223510223511223512223513223514223515223516223517223518223519223520223521223522223523223524223525223526223527223528223529223530223531223532223533223534223535223536223537223538223539223540223541223542223543223544223545223546223547223548223549223550223551223552223553223554223555223556223557223558223559223560223561223562223563223564223565223566223567223568223569223570223571223572223573223574223575223576223577223578223579223580223581223582223583223584223585223586223587223588223589223590223591223592223593223594223595223596223597223598223599223600223601223602223603223604223605223606223607223608223609223610223611223612223613223614223615223616223617223618223619223620223621223622223623223624223625223626223627223628223629223630223631223632223633223634223635223636223637223638223639223640223641223642223643223644223645223646223647223648223649223650223651223652223653223654223655223656223657223658223659223660223661223662223663223664223665223666223667223668223669223670223671223672223673223674223675223676223677223678223679223680223681223682223683223684223685223686223687223688223689223690223691223692223693223694223695223696223697223698223699223700223701223702223703223704223705223706223707223708223709223710223711223712223713223714223715223716223717223718223719223720223721223722223723223724223725223726223727223728223729223730223731223732223733223734223735223736223737223738223739223740223741223742223743223744223745223746223747223748223749223750223751223752223753223754223755223756223757223758223759223760223761223762223763223764223765223766223767223768223769223770223771223772223773223774223775223776223777223778223779223780223781223782223783223784223785223786223787223788223789223790223791223792223793223794223795223796223797223798223799223800223801223802223803223804223805223806223807223808223809223810223811223812223813223814223815223816223817223818223819223820223821223822223823223824223825223826223827223828223829223830223831223832223833223834223835223836223837223838223839223840223841223842223843223844223845223846223847223848223849223850223851223852223853223854223855223856223857223858223859223860223861223862223863223864223865223866223867223868223869223870223871223872223873223874223875223876223877223878223879223880223881223882223883223884223885223886223887223888223889223890223891223892223893223894223895223896223897223898223899223900223901223902223903223904223905223906223907223908223909223910223911223912223913223914223915223916223917223918223919223920223921223922223923223924223925223926223927223928223929223930223931223932223933223934223935223936223937223938223939223940223941223942223943223944223945223946223947223948223949223950223951223952223953223954223955223956223957223958223959223960223961223962223963223964223965223966223967223968223969223970223971223972223973223974223975223976223977223978223979223980223981223982223983223984223985223986223987223988223989223990223991223992223993223994223995223996223997223998223999224000224001224002224003224004224005224006224007224008224009224010224011224012224013224014224015224016224017224018224019224020224021224022224023224024224025224026224027224028224029224030224031224032224033224034224035224036224037224038224039224040224041224042224043224044224045224046224047224048224049224050224051224052224053224054224055224056224057224058224059224060224061224062224063224064224065224066224067224068224069224070224071224072224073224074224075224076224077224078224079224080224081224082224083224084224085224086224087224088224089224090224091224092224093224094224095224096224097224098224099224100224101224102224103224104224105224106224107224108224109224110224111224112224113224114224115224116224117224118224119224120224121224122224123224124224125224126224127224128224129224130224131224132224133224134224135224136224137224138224139224140224141224142224143224144224145224146224147224148224149224150224151224152224153224154224155224156224157224158224159224160224161224162224163224164224165224166224167224168224169224170224171224172224173224174224175224176224177224178224179224180224181224182224183224184224185224186224187224188224189224190224191224192224193224194224195224196224197224198224199224200224201224202224203224204224205224206224207224208224209224210224211224212224213224214224215224216224217224218224219224220224221224222224223224224224225224226224227224228224229224230224231224232224233224234224235224236224237224238224239224240224241224242224243224244224245224246224247224248224249224250224251224252224253224254224255224256224257224258224259224260224261224262224263224264224265224266224267224268224269224270224271224272224273224274224275224276224277224278224279224280224281224282224283224284224285224286224287224288224289224290224291224292224293224294224295224296224297224298224299224300224301224302224303224304224305224306224307224308224309224310224311224312224313224314224315224316224317224318224319224320224321224322224323224324224325224326224327224328224329224330224331224332224333224334224335224336224337224338224339224340224341224342224343224344224345224346224347224348224349224350224351224352224353224354224355224356224357224358224359224360224361224362224363224364224365224366224367224368224369224370224371224372224373224374224375224376224377224378224379224380224381224382224383224384224385224386224387224388224389224390224391224392224393224394224395224396224397224398224399224400224401224402224403224404224405224406224407224408224409224410224411224412224413224414224415224416224417224418224419224420224421224422224423224424224425224426224427224428224429224430224431224432224433224434224435224436224437224438224439224440224441224442224443224444224445224446224447224448224449224450224451224452224453224454224455224456224457224458224459224460224461224462224463224464224465224466224467224468224469224470224471224472224473224474224475224476224477224478224479224480224481224482224483224484224485224486224487224488224489224490224491224492224493224494224495224496224497224498224499224500224501224502224503224504224505224506224507224508224509224510224511224512224513224514224515224516224517224518224519224520224521224522224523224524224525224526224527224528224529224530224531224532224533224534224535224536224537224538224539224540224541224542224543224544224545224546224547224548224549224550224551224552224553224554224555224556224557224558224559224560224561224562224563224564224565224566224567224568224569224570224571224572224573224574224575224576224577224578224579224580224581224582224583224584224585224586224587224588224589224590224591224592224593224594224595224596224597224598224599224600224601224602224603224604224605224606224607224608224609224610224611224612224613224614224615224616224617224618224619224620224621224622224623224624224625224626224627224628224629224630224631224632224633224634224635224636224637224638224639224640224641224642224643224644224645224646224647224648224649224650224651224652224653224654224655224656224657224658224659224660224661224662224663224664224665224666224667224668224669224670224671224672224673224674224675224676224677224678224679224680224681224682224683224684224685224686224687224688224689224690224691224692224693224694224695224696224697224698224699224700224701224702224703224704224705224706224707224708224709224710224711224712224713224714224715224716224717224718224719224720224721224722224723224724224725224726224727224728224729224730224731224732224733224734224735224736224737224738224739224740224741224742224743224744224745224746224747224748224749224750224751224752224753224754224755224756224757224758224759224760224761224762224763224764224765224766224767224768224769224770224771224772224773224774224775224776224777224778224779224780224781224782224783224784224785224786224787224788224789224790224791224792224793224794224795224796224797224798224799224800224801224802224803224804224805224806224807224808224809224810224811224812224813224814224815224816224817224818224819224820224821224822224823224824224825224826224827224828224829224830224831224832224833224834224835224836224837224838224839224840224841224842224843224844224845224846224847224848224849224850224851224852224853224854224855224856224857224858224859224860224861224862224863224864224865224866224867224868224869224870224871224872224873224874224875224876224877224878224879224880224881224882224883224884224885224886224887224888224889224890224891224892224893224894224895224896224897224898224899224900224901224902224903224904224905224906224907224908224909224910224911224912224913224914224915224916224917224918224919224920224921224922224923224924224925224926224927224928224929224930224931224932224933224934224935224936224937224938224939224940224941224942224943224944224945224946224947224948224949224950224951224952224953224954224955224956224957224958224959224960224961224962224963224964224965224966224967224968224969224970224971224972224973224974224975224976224977224978224979224980224981224982224983224984224985224986224987224988224989224990224991224992224993224994224995224996224997224998224999225000225001225002225003225004225005225006225007225008225009225010225011225012225013225014225015225016225017225018225019225020225021225022225023225024225025225026225027225028225029225030225031225032225033225034225035225036225037225038225039225040225041225042225043225044225045225046225047225048225049225050225051225052225053225054225055225056225057225058225059225060225061225062225063225064225065225066225067225068225069225070225071225072225073225074225075225076225077225078225079225080225081225082225083225084225085225086225087225088225089225090225091225092225093225094225095225096225097225098225099225100225101225102225103225104225105225106225107225108225109225110225111225112225113225114225115225116225117225118225119225120225121225122225123225124225125225126225127225128225129225130225131225132225133225134225135225136225137225138225139225140225141225142225143225144225145225146225147225148225149225150225151225152225153225154225155225156225157225158225159225160225161225162225163225164225165225166225167225168225169225170225171225172225173225174225175225176225177225178225179225180225181225182225183225184225185225186225187225188225189225190225191225192225193225194225195225196225197225198225199225200225201225202225203225204225205225206225207225208225209225210225211225212225213225214225215225216225217225218225219225220225221225222225223225224225225225226225227225228225229225230225231225232225233225234225235225236225237225238225239225240225241225242225243225244225245225246225247225248225249225250225251225252225253225254225255225256225257225258225259225260225261225262225263225264225265225266225267225268225269225270225271225272225273225274225275225276225277225278225279225280225281225282225283225284225285225286225287225288225289225290225291225292225293225294225295225296225297225298225299225300225301225302225303225304225305225306225307225308225309225310225311225312225313225314225315225316225317225318225319225320225321225322225323225324225325225326225327225328225329225330225331225332225333225334225335225336225337225338225339225340225341225342225343225344225345225346225347225348225349225350225351225352225353225354225355225356225357225358225359225360225361225362225363225364225365225366225367225368225369225370225371225372225373225374225375225376225377225378225379225380225381225382225383225384225385225386225387225388225389225390225391225392225393225394225395225396225397225398225399225400225401225402225403225404225405225406225407225408225409225410225411225412225413225414225415225416225417225418225419225420225421225422225423225424225425225426225427225428225429225430225431225432225433225434225435225436225437225438225439225440225441225442225443225444225445225446225447225448225449225450225451225452225453225454225455225456225457225458225459225460225461225462225463225464225465225466225467225468225469225470225471225472225473225474225475225476225477225478225479225480225481225482225483225484225485225486225487225488225489225490225491225492225493225494225495225496225497225498225499225500225501225502225503225504225505225506225507225508225509225510225511225512225513225514225515225516225517225518225519225520225521225522225523225524225525225526225527225528225529225530225531225532225533225534225535225536225537225538225539225540225541225542225543225544225545225546225547225548225549225550225551225552225553225554225555225556225557225558225559225560225561225562225563225564225565225566225567225568225569225570225571225572225573225574225575225576225577225578225579225580225581225582225583225584225585225586225587225588225589225590225591225592225593225594225595225596225597225598225599225600225601225602225603225604225605225606225607225608225609225610225611225612225613225614225615225616225617225618225619225620225621225622225623225624225625225626225627225628225629225630225631225632225633225634225635225636225637225638225639225640225641225642225643225644225645225646225647225648225649225650225651225652225653225654225655225656225657225658225659225660225661225662225663225664225665225666225667225668225669225670225671225672225673225674225675225676225677225678225679225680225681225682225683225684225685225686225687225688225689225690225691225692225693225694225695225696225697225698225699225700225701225702225703225704225705225706225707225708225709225710225711225712225713225714225715225716225717225718225719225720225721225722225723225724225725225726225727225728225729225730225731225732225733225734225735225736225737225738225739225740225741225742225743225744225745225746225747225748225749225750225751225752225753225754225755225756225757225758225759225760225761225762225763225764225765225766225767225768225769225770225771225772225773225774225775225776225777225778225779225780225781225782225783225784225785225786225787225788225789225790225791225792225793225794225795225796225797225798225799225800225801225802225803225804225805225806225807225808225809225810225811225812225813225814225815225816225817225818225819225820225821225822225823225824225825225826225827225828225829225830225831225832225833225834225835225836225837225838225839225840225841225842225843225844225845225846225847225848225849225850225851225852225853225854225855225856225857225858225859225860225861225862225863225864225865225866225867225868225869225870225871225872225873225874225875225876225877225878225879225880225881225882225883225884225885225886225887225888225889225890225891225892225893225894225895225896225897225898225899225900225901225902225903225904225905225906225907225908225909225910225911225912225913225914225915225916225917225918225919225920225921225922225923225924225925225926225927225928225929225930225931225932225933225934225935225936225937225938225939225940225941225942225943225944225945225946225947225948225949225950225951225952225953225954225955225956225957225958225959225960225961225962225963225964225965225966225967225968225969225970225971225972225973225974225975225976225977225978225979225980225981225982225983225984225985225986225987225988225989225990225991225992225993225994225995225996225997225998225999226000226001226002226003226004226005226006226007226008226009226010226011226012226013226014226015226016226017226018226019226020226021226022226023226024226025226026226027226028226029226030226031226032226033226034226035226036226037226038226039226040226041226042226043226044226045226046226047226048226049226050226051226052226053226054226055226056226057226058226059226060226061226062226063226064226065226066226067226068226069226070226071226072226073226074226075226076226077226078226079226080226081226082226083226084226085226086226087226088226089226090226091226092226093226094226095226096226097226098226099226100226101226102226103226104226105226106226107226108226109226110226111226112226113226114226115226116226117226118226119226120226121226122226123226124226125226126226127226128226129226130226131226132226133226134226135226136226137226138226139226140226141226142226143226144226145226146226147226148226149226150226151226152226153226154226155226156226157226158226159226160226161226162226163226164226165226166226167226168226169226170226171226172226173226174226175226176226177226178226179226180226181226182226183226184226185226186226187226188226189226190226191226192226193226194226195226196226197226198226199226200226201226202226203226204226205226206226207226208226209226210226211226212226213226214226215226216226217226218226219226220226221226222226223226224226225226226226227226228226229226230226231226232226233226234226235226236226237226238226239226240226241226242226243226244226245226246226247226248226249226250226251226252226253226254226255226256226257226258226259226260226261226262226263226264226265226266226267226268226269226270226271226272226273226274226275226276226277226278226279226280226281226282226283226284226285226286226287226288226289226290226291226292226293226294226295226296226297226298226299226300226301226302226303226304226305226306226307226308226309226310226311226312226313226314226315226316226317226318226319226320226321226322226323226324226325226326226327226328226329226330226331226332226333226334226335226336226337226338226339226340226341226342226343226344226345226346226347226348226349226350226351226352226353226354226355226356226357226358226359226360226361226362226363226364226365226366226367226368226369226370226371226372226373226374226375226376226377226378226379226380226381226382226383226384226385226386226387226388226389226390226391226392226393226394226395226396226397226398226399226400226401226402226403226404226405226406226407226408226409226410226411226412226413226414226415226416226417226418226419226420226421226422226423226424226425226426226427226428226429226430226431226432226433226434226435226436226437226438226439226440226441226442226443226444226445226446226447226448226449226450226451226452226453226454226455226456226457226458226459226460226461226462226463226464226465226466226467226468226469226470226471226472226473226474226475226476226477226478226479226480226481226482226483226484226485226486226487226488226489226490226491226492226493226494226495226496226497226498226499226500226501226502226503226504226505226506226507226508226509226510226511226512226513226514226515226516226517226518226519226520226521226522226523226524226525226526226527226528226529226530226531226532226533226534226535226536226537226538226539226540226541226542226543226544226545226546226547226548226549226550226551226552226553226554226555226556226557226558226559226560226561226562226563226564226565226566226567226568226569226570226571226572226573226574226575226576226577226578226579226580226581226582226583226584226585226586226587226588226589226590226591226592226593226594226595226596226597226598226599226600226601226602226603226604226605226606226607226608226609226610226611226612226613226614226615226616226617226618226619226620226621226622226623226624226625226626226627226628226629226630226631226632226633226634226635226636226637226638226639226640226641226642226643226644226645226646226647226648226649226650226651226652226653226654226655226656226657226658226659226660226661226662226663226664226665226666226667226668226669226670226671226672226673226674226675226676226677226678226679226680226681226682226683226684226685226686226687226688226689226690226691226692226693226694226695226696226697226698226699226700226701226702226703226704226705226706226707226708226709226710226711226712226713226714226715226716226717226718226719226720226721226722226723226724226725226726226727226728226729226730226731226732226733226734226735226736226737226738226739226740226741226742226743226744226745226746226747226748226749226750226751226752226753226754226755226756226757226758226759226760226761226762226763226764226765226766226767226768226769226770226771226772226773226774226775226776226777226778226779226780226781226782226783226784226785226786226787226788226789226790226791226792226793226794226795226796226797226798226799226800226801226802226803226804226805226806226807226808226809226810226811226812226813226814226815226816226817226818226819226820226821226822226823226824226825226826226827226828226829226830226831226832226833226834226835226836226837226838226839226840226841226842226843226844226845226846226847226848226849226850226851226852226853226854226855226856226857226858226859226860226861226862226863226864226865226866226867226868226869226870226871226872226873226874226875226876226877226878226879226880226881226882226883226884226885226886226887226888226889226890226891226892226893226894226895226896226897226898226899226900226901226902226903226904226905226906226907226908226909226910226911226912226913226914226915226916226917226918226919226920226921226922226923226924226925226926226927226928226929226930226931226932226933226934226935226936226937226938226939226940226941226942226943226944226945226946226947226948226949226950226951226952226953226954226955226956226957226958226959226960226961226962226963226964226965226966226967226968226969226970226971226972226973226974226975226976226977226978226979226980226981226982226983226984226985226986226987226988226989226990226991226992226993226994226995226996226997226998226999227000227001227002227003227004227005227006227007227008227009227010227011227012227013227014227015227016227017227018227019227020227021227022227023227024227025227026227027227028227029227030227031227032227033227034227035227036227037227038227039227040227041227042227043227044227045227046227047227048227049227050227051227052227053227054227055227056227057227058227059227060227061227062227063227064227065227066227067227068227069227070227071227072227073227074227075227076227077227078227079227080227081227082227083227084227085227086227087227088227089227090227091227092227093227094227095227096227097227098227099227100227101227102227103227104227105227106227107227108227109227110227111227112227113227114227115227116227117227118227119227120227121227122227123227124227125227126227127227128227129227130227131227132227133227134227135227136227137227138227139227140227141227142227143227144227145227146227147227148227149227150227151227152227153227154227155227156227157227158227159227160227161227162227163227164227165227166227167227168227169227170227171227172227173227174227175227176227177227178227179227180227181227182227183227184227185227186227187227188227189227190227191227192227193227194227195227196227197227198227199227200227201227202227203227204227205227206227207227208227209227210227211227212227213227214227215227216227217227218227219227220227221227222227223227224227225227226227227227228227229227230227231227232227233227234227235227236227237227238227239227240227241227242227243227244227245227246227247227248227249227250227251227252227253227254227255227256227257227258227259227260227261227262227263227264227265227266227267227268227269227270227271227272227273227274227275227276227277227278227279227280227281227282227283227284227285227286227287227288227289227290227291227292227293227294227295227296227297227298227299227300227301227302227303227304227305227306227307227308227309227310227311227312227313227314227315227316227317227318227319227320227321227322227323227324227325227326227327227328227329227330227331227332227333227334227335227336227337227338227339227340227341227342227343227344227345227346227347227348227349227350227351227352227353227354227355227356227357227358227359227360227361227362227363227364227365227366227367227368227369227370227371227372227373227374227375227376227377227378227379227380227381227382227383227384227385227386227387227388227389227390227391227392227393227394227395227396227397227398227399227400227401227402227403227404227405227406227407227408227409227410227411227412227413227414227415227416227417227418227419227420227421227422227423227424227425227426227427227428227429227430227431227432227433227434227435227436227437227438227439227440227441227442227443227444227445227446227447227448227449227450227451227452227453227454227455227456227457227458227459227460227461227462227463227464227465227466227467227468227469227470227471227472227473227474227475227476227477227478227479227480227481227482227483227484227485227486227487227488227489227490227491227492227493227494227495227496227497227498227499227500227501227502227503227504227505227506227507227508227509227510227511227512227513227514227515227516227517227518227519227520227521227522227523227524227525227526227527227528227529227530227531227532227533227534227535227536227537227538227539227540227541227542227543227544227545227546227547227548227549227550227551227552227553227554227555227556227557227558227559227560227561227562227563227564227565227566227567227568227569227570227571227572227573227574227575227576227577227578227579227580227581227582227583227584227585227586227587227588227589227590227591227592227593227594227595227596227597227598227599227600227601227602227603227604227605227606227607227608227609227610227611227612227613227614227615227616227617227618227619227620227621227622227623227624227625227626227627227628227629227630227631227632227633227634227635227636227637227638227639227640227641227642227643227644227645227646227647227648227649227650227651227652227653227654227655227656227657227658227659227660227661227662227663227664227665227666227667227668227669227670227671227672227673227674227675227676227677227678227679227680227681227682227683227684227685227686227687227688227689227690227691227692227693227694227695227696227697227698227699227700227701227702227703227704227705227706227707227708227709227710227711227712227713227714227715227716227717227718227719227720227721227722227723227724227725227726227727227728227729227730227731227732227733227734227735227736227737227738227739227740227741227742227743227744227745227746227747227748227749227750227751227752227753227754227755227756227757227758227759227760227761227762227763227764227765227766227767227768227769227770227771227772227773227774227775227776227777227778227779227780227781227782227783227784227785227786227787227788227789227790227791227792227793227794227795227796227797227798227799227800227801227802227803227804227805227806227807227808227809227810227811227812227813227814227815227816227817227818227819227820227821227822227823227824227825227826227827227828227829227830227831227832227833227834227835227836227837227838227839227840227841227842227843227844227845227846227847227848227849227850227851227852227853227854227855227856227857227858227859227860227861227862227863227864227865227866227867227868227869227870227871227872227873227874227875227876227877227878227879227880227881227882227883227884227885227886227887227888227889227890227891227892227893227894227895227896227897227898227899227900227901227902227903227904227905227906227907227908227909227910227911227912227913227914227915227916227917227918227919227920227921227922227923227924227925227926227927227928227929227930227931227932227933227934227935227936227937227938227939227940227941227942227943227944227945227946227947227948227949227950227951227952227953227954227955227956227957227958227959227960227961227962227963227964227965227966227967227968227969227970227971227972227973227974227975227976227977227978227979227980227981227982227983227984227985227986227987227988227989227990227991227992227993227994227995227996227997227998227999228000228001228002228003228004228005228006228007228008228009228010228011228012228013228014228015228016228017228018228019228020228021228022228023228024228025228026228027228028228029228030228031228032228033228034228035228036228037228038228039228040228041228042228043228044228045228046228047228048228049228050228051228052228053228054228055228056228057228058228059228060228061228062228063228064228065228066228067228068228069228070228071228072228073228074228075228076228077228078228079228080228081228082228083228084228085228086228087228088228089228090228091228092228093228094228095228096228097228098228099228100228101228102228103228104228105228106228107228108228109228110228111228112228113228114228115228116228117228118228119228120228121228122228123228124228125228126228127228128228129228130228131228132228133228134228135228136228137228138228139228140228141228142228143228144228145228146228147228148228149228150228151228152228153228154228155228156228157228158228159228160228161228162228163228164228165228166228167228168228169228170228171228172228173228174228175228176228177228178228179228180228181228182228183228184228185228186228187228188228189228190228191228192228193228194228195228196228197228198228199228200228201228202228203228204228205228206228207228208228209228210228211228212228213228214228215228216228217228218228219228220228221228222228223228224228225228226228227228228228229228230228231228232228233228234228235228236228237228238228239228240228241228242228243228244228245228246228247228248228249228250228251228252228253228254228255228256228257228258228259228260228261228262228263228264228265228266228267228268228269228270228271228272228273228274228275228276228277228278228279228280228281228282228283228284228285228286228287228288228289228290228291228292228293228294228295228296228297228298228299228300228301228302228303228304228305228306228307228308228309228310228311228312228313228314228315228316228317228318228319228320228321228322228323228324228325228326228327228328228329228330228331228332228333228334228335228336228337228338228339228340228341228342228343228344228345228346228347228348228349228350228351228352228353228354228355228356228357228358228359228360228361228362228363228364228365228366228367228368228369228370228371228372228373228374228375228376228377228378228379228380228381228382228383228384228385228386228387228388228389228390228391228392228393228394228395228396228397228398228399228400228401228402228403228404228405228406228407228408228409228410228411228412228413228414228415228416228417228418228419228420228421228422228423228424228425228426228427228428228429228430228431228432228433228434228435228436228437228438228439228440228441228442228443228444228445228446228447228448228449228450228451228452228453228454228455228456228457228458228459228460228461228462228463228464228465228466228467228468228469228470228471228472228473228474228475228476228477228478228479228480228481228482228483228484228485228486228487228488228489228490228491228492228493228494228495228496228497228498228499228500228501228502228503228504228505228506228507228508228509228510228511228512228513228514228515228516228517228518228519228520228521228522228523228524228525228526228527228528228529228530228531228532228533228534228535228536228537228538228539228540228541228542228543228544228545228546228547228548228549228550228551228552228553228554228555228556228557228558228559228560228561228562228563228564228565228566228567228568228569228570228571228572228573228574228575228576228577228578228579228580228581228582228583228584228585228586228587228588228589228590228591228592228593228594228595228596228597228598228599228600228601228602228603228604228605228606228607228608228609228610228611228612228613228614228615228616228617228618228619228620228621228622228623228624228625228626228627228628228629228630228631228632228633228634228635228636228637228638228639228640228641228642228643228644228645228646228647228648228649228650228651228652228653228654228655228656228657228658228659228660228661228662228663228664228665228666228667228668228669228670228671228672228673228674228675228676228677228678228679228680228681228682228683228684228685228686228687228688228689228690228691228692228693228694228695228696228697228698228699228700228701228702228703228704228705228706228707228708228709228710228711228712228713228714228715228716228717228718228719228720228721228722228723228724228725228726228727228728228729228730228731228732228733228734228735228736228737228738228739228740228741228742228743228744228745228746228747228748228749228750228751228752228753228754228755228756228757228758228759228760228761228762228763228764228765228766228767228768228769228770228771228772228773228774228775228776228777228778228779228780228781228782228783228784228785228786228787228788228789228790228791228792228793228794228795228796228797228798228799228800228801228802228803228804228805228806228807228808228809228810228811228812228813228814228815228816228817228818228819228820228821228822228823228824228825228826228827228828228829228830228831228832228833228834228835228836228837228838228839228840228841228842228843228844228845228846228847228848228849228850228851228852228853228854228855228856228857228858228859228860228861228862228863228864228865228866228867228868228869228870228871228872228873228874228875228876228877228878228879228880228881228882228883228884228885228886228887228888228889228890228891228892228893228894228895228896228897228898228899228900228901228902228903228904228905228906228907228908228909228910228911228912228913228914228915228916228917228918228919228920228921228922228923228924228925228926228927228928228929228930228931228932228933228934228935228936228937228938228939228940228941228942228943228944228945228946228947228948228949228950228951228952228953228954228955228956228957228958228959228960228961228962228963228964228965228966228967228968228969228970228971228972228973228974228975228976228977228978228979228980228981228982228983228984228985228986228987228988228989228990228991228992228993228994228995228996228997228998228999229000229001229002229003229004229005229006229007229008229009229010229011229012229013229014229015229016229017229018229019229020229021229022229023229024229025229026229027229028229029229030229031229032229033229034229035229036229037229038229039229040229041229042229043229044229045229046229047229048229049229050229051229052229053229054229055229056229057229058229059229060229061229062229063229064229065229066229067229068229069229070229071229072229073229074229075229076229077229078229079229080229081229082229083229084229085229086229087229088229089229090229091229092229093229094229095229096229097229098229099229100229101229102229103229104229105229106229107229108229109229110229111229112229113229114229115229116229117229118229119229120229121229122229123229124229125229126229127229128229129229130229131229132229133229134229135229136229137229138229139229140229141229142229143229144229145229146229147229148229149229150229151229152229153229154229155229156229157229158229159229160229161229162229163229164229165229166229167229168229169229170229171229172229173229174229175229176229177229178229179229180229181229182229183229184229185229186229187229188229189229190229191229192229193229194229195229196229197229198229199229200229201229202229203229204229205229206229207229208229209229210229211229212229213229214229215229216229217229218229219229220229221229222229223229224229225229226229227229228229229229230229231229232229233229234229235229236229237229238229239229240229241229242229243229244229245229246229247229248229249229250229251229252229253229254229255229256229257229258229259229260229261229262229263229264229265229266229267229268229269229270229271229272229273229274229275229276229277229278229279229280229281229282229283229284229285229286229287229288229289229290229291229292229293229294229295229296229297229298229299229300229301229302229303229304229305229306229307229308229309229310229311229312229313229314229315229316229317229318229319229320229321229322229323229324229325229326229327229328229329229330229331229332229333229334229335229336229337229338229339229340229341229342229343229344229345229346229347229348229349229350229351229352229353229354229355229356229357229358229359229360229361229362229363229364229365229366229367229368229369229370229371229372229373229374229375229376229377229378229379229380229381229382229383229384229385229386229387229388229389229390229391229392229393229394229395229396229397229398229399229400229401229402229403229404229405229406229407229408229409229410229411229412229413229414229415229416229417229418229419229420229421229422229423229424229425229426229427229428229429229430229431229432229433229434229435229436229437229438229439229440229441229442229443229444229445229446229447229448229449229450229451229452229453229454229455229456229457229458229459229460229461229462229463229464229465229466229467229468229469229470229471229472229473229474229475229476229477229478229479229480229481229482229483229484229485229486229487229488229489229490229491229492229493229494229495229496229497229498229499229500229501229502229503229504229505229506229507229508229509229510229511229512229513229514229515229516229517229518229519229520229521229522229523229524229525229526229527229528229529229530229531229532229533229534229535229536229537229538229539229540229541229542229543229544229545229546229547229548229549229550229551229552229553229554229555229556229557229558229559229560229561229562229563229564229565229566229567229568229569229570229571229572229573229574229575229576229577229578229579229580229581229582229583229584229585229586229587229588229589229590229591229592229593229594229595229596229597229598229599229600229601229602229603229604229605229606229607229608229609229610229611229612229613229614229615229616
  1. /******************************************************************************
  2. ** This file is an amalgamation of many separate C source files from SQLite
  3. ** version 3.32.2. 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 /* IMP: R-16824-07538 */
  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_BYTECODE_VTAB
  216. "ENABLE_BYTECODE_VTAB",
  217. #endif
  218. #if SQLITE_ENABLE_CEROD
  219. "ENABLE_CEROD=" CTIMEOPT_VAL(SQLITE_ENABLE_CEROD),
  220. #endif
  221. #if SQLITE_ENABLE_COLUMN_METADATA
  222. "ENABLE_COLUMN_METADATA",
  223. #endif
  224. #if SQLITE_ENABLE_COLUMN_USED_MASK
  225. "ENABLE_COLUMN_USED_MASK",
  226. #endif
  227. #if SQLITE_ENABLE_COSTMULT
  228. "ENABLE_COSTMULT",
  229. #endif
  230. #if SQLITE_ENABLE_CURSOR_HINTS
  231. "ENABLE_CURSOR_HINTS",
  232. #endif
  233. #if SQLITE_ENABLE_DBSTAT_VTAB
  234. "ENABLE_DBSTAT_VTAB",
  235. #endif
  236. #if SQLITE_ENABLE_EXPENSIVE_ASSERT
  237. "ENABLE_EXPENSIVE_ASSERT",
  238. #endif
  239. #if SQLITE_ENABLE_FTS1
  240. "ENABLE_FTS1",
  241. #endif
  242. #if SQLITE_ENABLE_FTS2
  243. "ENABLE_FTS2",
  244. #endif
  245. #if SQLITE_ENABLE_FTS3
  246. "ENABLE_FTS3",
  247. #endif
  248. #if SQLITE_ENABLE_FTS3_PARENTHESIS
  249. "ENABLE_FTS3_PARENTHESIS",
  250. #endif
  251. #if SQLITE_ENABLE_FTS3_TOKENIZER
  252. "ENABLE_FTS3_TOKENIZER",
  253. #endif
  254. #if SQLITE_ENABLE_FTS4
  255. "ENABLE_FTS4",
  256. #endif
  257. #if SQLITE_ENABLE_FTS5
  258. "ENABLE_FTS5",
  259. #endif
  260. #if SQLITE_ENABLE_GEOPOLY
  261. "ENABLE_GEOPOLY",
  262. #endif
  263. #if SQLITE_ENABLE_HIDDEN_COLUMNS
  264. "ENABLE_HIDDEN_COLUMNS",
  265. #endif
  266. #if SQLITE_ENABLE_ICU
  267. "ENABLE_ICU",
  268. #endif
  269. #if SQLITE_ENABLE_IOTRACE
  270. "ENABLE_IOTRACE",
  271. #endif
  272. #if SQLITE_ENABLE_JSON1
  273. "ENABLE_JSON1",
  274. #endif
  275. #if SQLITE_ENABLE_LOAD_EXTENSION
  276. "ENABLE_LOAD_EXTENSION",
  277. #endif
  278. #ifdef SQLITE_ENABLE_LOCKING_STYLE
  279. "ENABLE_LOCKING_STYLE=" CTIMEOPT_VAL(SQLITE_ENABLE_LOCKING_STYLE),
  280. #endif
  281. #if SQLITE_ENABLE_MEMORY_MANAGEMENT
  282. "ENABLE_MEMORY_MANAGEMENT",
  283. #endif
  284. #if SQLITE_ENABLE_MEMSYS3
  285. "ENABLE_MEMSYS3",
  286. #endif
  287. #if SQLITE_ENABLE_MEMSYS5
  288. "ENABLE_MEMSYS5",
  289. #endif
  290. #if SQLITE_ENABLE_MULTIPLEX
  291. "ENABLE_MULTIPLEX",
  292. #endif
  293. #if SQLITE_ENABLE_NORMALIZE
  294. "ENABLE_NORMALIZE",
  295. #endif
  296. #if SQLITE_ENABLE_NULL_TRIM
  297. "ENABLE_NULL_TRIM",
  298. #endif
  299. #if SQLITE_ENABLE_OVERSIZE_CELL_CHECK
  300. "ENABLE_OVERSIZE_CELL_CHECK",
  301. #endif
  302. #if SQLITE_ENABLE_PREUPDATE_HOOK
  303. "ENABLE_PREUPDATE_HOOK",
  304. #endif
  305. #if SQLITE_ENABLE_QPSG
  306. "ENABLE_QPSG",
  307. #endif
  308. #if SQLITE_ENABLE_RBU
  309. "ENABLE_RBU",
  310. #endif
  311. #if SQLITE_ENABLE_RTREE
  312. "ENABLE_RTREE",
  313. #endif
  314. #if SQLITE_ENABLE_SELECTTRACE
  315. "ENABLE_SELECTTRACE",
  316. #endif
  317. #if SQLITE_ENABLE_SESSION
  318. "ENABLE_SESSION",
  319. #endif
  320. #if SQLITE_ENABLE_SNAPSHOT
  321. "ENABLE_SNAPSHOT",
  322. #endif
  323. #if SQLITE_ENABLE_SORTER_REFERENCES
  324. "ENABLE_SORTER_REFERENCES",
  325. #endif
  326. #if SQLITE_ENABLE_SQLLOG
  327. "ENABLE_SQLLOG",
  328. #endif
  329. #if defined(SQLITE_ENABLE_STAT4)
  330. "ENABLE_STAT4",
  331. #endif
  332. #if SQLITE_ENABLE_STMTVTAB
  333. "ENABLE_STMTVTAB",
  334. #endif
  335. #if SQLITE_ENABLE_STMT_SCANSTATUS
  336. "ENABLE_STMT_SCANSTATUS",
  337. #endif
  338. #if SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
  339. "ENABLE_UNKNOWN_SQL_FUNCTION",
  340. #endif
  341. #if SQLITE_ENABLE_UNLOCK_NOTIFY
  342. "ENABLE_UNLOCK_NOTIFY",
  343. #endif
  344. #if SQLITE_ENABLE_UPDATE_DELETE_LIMIT
  345. "ENABLE_UPDATE_DELETE_LIMIT",
  346. #endif
  347. #if SQLITE_ENABLE_URI_00_ERROR
  348. "ENABLE_URI_00_ERROR",
  349. #endif
  350. #if SQLITE_ENABLE_VFSTRACE
  351. "ENABLE_VFSTRACE",
  352. #endif
  353. #if SQLITE_ENABLE_WHERETRACE
  354. "ENABLE_WHERETRACE",
  355. #endif
  356. #if SQLITE_ENABLE_ZIPVFS
  357. "ENABLE_ZIPVFS",
  358. #endif
  359. #if SQLITE_EXPLAIN_ESTIMATED_ROWS
  360. "EXPLAIN_ESTIMATED_ROWS",
  361. #endif
  362. #if SQLITE_EXTRA_IFNULLROW
  363. "EXTRA_IFNULLROW",
  364. #endif
  365. #ifdef SQLITE_EXTRA_INIT
  366. "EXTRA_INIT=" CTIMEOPT_VAL(SQLITE_EXTRA_INIT),
  367. #endif
  368. #ifdef SQLITE_EXTRA_SHUTDOWN
  369. "EXTRA_SHUTDOWN=" CTIMEOPT_VAL(SQLITE_EXTRA_SHUTDOWN),
  370. #endif
  371. #ifdef SQLITE_FTS3_MAX_EXPR_DEPTH
  372. "FTS3_MAX_EXPR_DEPTH=" CTIMEOPT_VAL(SQLITE_FTS3_MAX_EXPR_DEPTH),
  373. #endif
  374. #if SQLITE_FTS5_ENABLE_TEST_MI
  375. "FTS5_ENABLE_TEST_MI",
  376. #endif
  377. #if SQLITE_FTS5_NO_WITHOUT_ROWID
  378. "FTS5_NO_WITHOUT_ROWID",
  379. #endif
  380. #if HAVE_ISNAN || SQLITE_HAVE_ISNAN
  381. "HAVE_ISNAN",
  382. #endif
  383. #if SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  384. "HOMEGROWN_RECURSIVE_MUTEX",
  385. #endif
  386. #if SQLITE_IGNORE_AFP_LOCK_ERRORS
  387. "IGNORE_AFP_LOCK_ERRORS",
  388. #endif
  389. #if SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  390. "IGNORE_FLOCK_LOCK_ERRORS",
  391. #endif
  392. #if SQLITE_INLINE_MEMCPY
  393. "INLINE_MEMCPY",
  394. #endif
  395. #if SQLITE_INT64_TYPE
  396. "INT64_TYPE",
  397. #endif
  398. #ifdef SQLITE_INTEGRITY_CHECK_ERROR_MAX
  399. "INTEGRITY_CHECK_ERROR_MAX=" CTIMEOPT_VAL(SQLITE_INTEGRITY_CHECK_ERROR_MAX),
  400. #endif
  401. #if SQLITE_LIKE_DOESNT_MATCH_BLOBS
  402. "LIKE_DOESNT_MATCH_BLOBS",
  403. #endif
  404. #if SQLITE_LOCK_TRACE
  405. "LOCK_TRACE",
  406. #endif
  407. #if SQLITE_LOG_CACHE_SPILL
  408. "LOG_CACHE_SPILL",
  409. #endif
  410. #ifdef SQLITE_MALLOC_SOFT_LIMIT
  411. "MALLOC_SOFT_LIMIT=" CTIMEOPT_VAL(SQLITE_MALLOC_SOFT_LIMIT),
  412. #endif
  413. #ifdef SQLITE_MAX_ATTACHED
  414. "MAX_ATTACHED=" CTIMEOPT_VAL(SQLITE_MAX_ATTACHED),
  415. #endif
  416. #ifdef SQLITE_MAX_COLUMN
  417. "MAX_COLUMN=" CTIMEOPT_VAL(SQLITE_MAX_COLUMN),
  418. #endif
  419. #ifdef SQLITE_MAX_COMPOUND_SELECT
  420. "MAX_COMPOUND_SELECT=" CTIMEOPT_VAL(SQLITE_MAX_COMPOUND_SELECT),
  421. #endif
  422. #ifdef SQLITE_MAX_DEFAULT_PAGE_SIZE
  423. "MAX_DEFAULT_PAGE_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_DEFAULT_PAGE_SIZE),
  424. #endif
  425. #ifdef SQLITE_MAX_EXPR_DEPTH
  426. "MAX_EXPR_DEPTH=" CTIMEOPT_VAL(SQLITE_MAX_EXPR_DEPTH),
  427. #endif
  428. #ifdef SQLITE_MAX_FUNCTION_ARG
  429. "MAX_FUNCTION_ARG=" CTIMEOPT_VAL(SQLITE_MAX_FUNCTION_ARG),
  430. #endif
  431. #ifdef SQLITE_MAX_LENGTH
  432. "MAX_LENGTH=" CTIMEOPT_VAL(SQLITE_MAX_LENGTH),
  433. #endif
  434. #ifdef SQLITE_MAX_LIKE_PATTERN_LENGTH
  435. "MAX_LIKE_PATTERN_LENGTH=" CTIMEOPT_VAL(SQLITE_MAX_LIKE_PATTERN_LENGTH),
  436. #endif
  437. #ifdef SQLITE_MAX_MEMORY
  438. "MAX_MEMORY=" CTIMEOPT_VAL(SQLITE_MAX_MEMORY),
  439. #endif
  440. #ifdef SQLITE_MAX_MMAP_SIZE
  441. "MAX_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_MMAP_SIZE),
  442. #endif
  443. #ifdef SQLITE_MAX_MMAP_SIZE_
  444. "MAX_MMAP_SIZE_=" CTIMEOPT_VAL(SQLITE_MAX_MMAP_SIZE_),
  445. #endif
  446. #ifdef SQLITE_MAX_PAGE_COUNT
  447. "MAX_PAGE_COUNT=" CTIMEOPT_VAL(SQLITE_MAX_PAGE_COUNT),
  448. #endif
  449. #ifdef SQLITE_MAX_PAGE_SIZE
  450. "MAX_PAGE_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_PAGE_SIZE),
  451. #endif
  452. #ifdef SQLITE_MAX_SCHEMA_RETRY
  453. "MAX_SCHEMA_RETRY=" CTIMEOPT_VAL(SQLITE_MAX_SCHEMA_RETRY),
  454. #endif
  455. #ifdef SQLITE_MAX_SQL_LENGTH
  456. "MAX_SQL_LENGTH=" CTIMEOPT_VAL(SQLITE_MAX_SQL_LENGTH),
  457. #endif
  458. #ifdef SQLITE_MAX_TRIGGER_DEPTH
  459. "MAX_TRIGGER_DEPTH=" CTIMEOPT_VAL(SQLITE_MAX_TRIGGER_DEPTH),
  460. #endif
  461. #ifdef SQLITE_MAX_VARIABLE_NUMBER
  462. "MAX_VARIABLE_NUMBER=" CTIMEOPT_VAL(SQLITE_MAX_VARIABLE_NUMBER),
  463. #endif
  464. #ifdef SQLITE_MAX_VDBE_OP
  465. "MAX_VDBE_OP=" CTIMEOPT_VAL(SQLITE_MAX_VDBE_OP),
  466. #endif
  467. #ifdef SQLITE_MAX_WORKER_THREADS
  468. "MAX_WORKER_THREADS=" CTIMEOPT_VAL(SQLITE_MAX_WORKER_THREADS),
  469. #endif
  470. #if SQLITE_MEMDEBUG
  471. "MEMDEBUG",
  472. #endif
  473. #if SQLITE_MIXED_ENDIAN_64BIT_FLOAT
  474. "MIXED_ENDIAN_64BIT_FLOAT",
  475. #endif
  476. #if SQLITE_MMAP_READWRITE
  477. "MMAP_READWRITE",
  478. #endif
  479. #if SQLITE_MUTEX_NOOP
  480. "MUTEX_NOOP",
  481. #endif
  482. #if SQLITE_MUTEX_NREF
  483. "MUTEX_NREF",
  484. #endif
  485. #if SQLITE_MUTEX_OMIT
  486. "MUTEX_OMIT",
  487. #endif
  488. #if SQLITE_MUTEX_PTHREADS
  489. "MUTEX_PTHREADS",
  490. #endif
  491. #if SQLITE_MUTEX_W32
  492. "MUTEX_W32",
  493. #endif
  494. #if SQLITE_NEED_ERR_NAME
  495. "NEED_ERR_NAME",
  496. #endif
  497. #if SQLITE_NOINLINE
  498. "NOINLINE",
  499. #endif
  500. #if SQLITE_NO_SYNC
  501. "NO_SYNC",
  502. #endif
  503. #if SQLITE_OMIT_ALTERTABLE
  504. "OMIT_ALTERTABLE",
  505. #endif
  506. #if SQLITE_OMIT_ANALYZE
  507. "OMIT_ANALYZE",
  508. #endif
  509. #if SQLITE_OMIT_ATTACH
  510. "OMIT_ATTACH",
  511. #endif
  512. #if SQLITE_OMIT_AUTHORIZATION
  513. "OMIT_AUTHORIZATION",
  514. #endif
  515. #if SQLITE_OMIT_AUTOINCREMENT
  516. "OMIT_AUTOINCREMENT",
  517. #endif
  518. #if SQLITE_OMIT_AUTOINIT
  519. "OMIT_AUTOINIT",
  520. #endif
  521. #if SQLITE_OMIT_AUTOMATIC_INDEX
  522. "OMIT_AUTOMATIC_INDEX",
  523. #endif
  524. #if SQLITE_OMIT_AUTORESET
  525. "OMIT_AUTORESET",
  526. #endif
  527. #if SQLITE_OMIT_AUTOVACUUM
  528. "OMIT_AUTOVACUUM",
  529. #endif
  530. #if SQLITE_OMIT_BETWEEN_OPTIMIZATION
  531. "OMIT_BETWEEN_OPTIMIZATION",
  532. #endif
  533. #if SQLITE_OMIT_BLOB_LITERAL
  534. "OMIT_BLOB_LITERAL",
  535. #endif
  536. #if SQLITE_OMIT_CAST
  537. "OMIT_CAST",
  538. #endif
  539. #if SQLITE_OMIT_CHECK
  540. "OMIT_CHECK",
  541. #endif
  542. #if SQLITE_OMIT_COMPLETE
  543. "OMIT_COMPLETE",
  544. #endif
  545. #if SQLITE_OMIT_COMPOUND_SELECT
  546. "OMIT_COMPOUND_SELECT",
  547. #endif
  548. #if SQLITE_OMIT_CONFLICT_CLAUSE
  549. "OMIT_CONFLICT_CLAUSE",
  550. #endif
  551. #if SQLITE_OMIT_CTE
  552. "OMIT_CTE",
  553. #endif
  554. #if SQLITE_OMIT_DATETIME_FUNCS
  555. "OMIT_DATETIME_FUNCS",
  556. #endif
  557. #if SQLITE_OMIT_DECLTYPE
  558. "OMIT_DECLTYPE",
  559. #endif
  560. #if SQLITE_OMIT_DEPRECATED
  561. "OMIT_DEPRECATED",
  562. #endif
  563. #if SQLITE_OMIT_DISKIO
  564. "OMIT_DISKIO",
  565. #endif
  566. #if SQLITE_OMIT_EXPLAIN
  567. "OMIT_EXPLAIN",
  568. #endif
  569. #if SQLITE_OMIT_FLAG_PRAGMAS
  570. "OMIT_FLAG_PRAGMAS",
  571. #endif
  572. #if SQLITE_OMIT_FLOATING_POINT
  573. "OMIT_FLOATING_POINT",
  574. #endif
  575. #if SQLITE_OMIT_FOREIGN_KEY
  576. "OMIT_FOREIGN_KEY",
  577. #endif
  578. #if SQLITE_OMIT_GET_TABLE
  579. "OMIT_GET_TABLE",
  580. #endif
  581. #if SQLITE_OMIT_HEX_INTEGER
  582. "OMIT_HEX_INTEGER",
  583. #endif
  584. #if SQLITE_OMIT_INCRBLOB
  585. "OMIT_INCRBLOB",
  586. #endif
  587. #if SQLITE_OMIT_INTEGRITY_CHECK
  588. "OMIT_INTEGRITY_CHECK",
  589. #endif
  590. #if SQLITE_OMIT_LIKE_OPTIMIZATION
  591. "OMIT_LIKE_OPTIMIZATION",
  592. #endif
  593. #if SQLITE_OMIT_LOAD_EXTENSION
  594. "OMIT_LOAD_EXTENSION",
  595. #endif
  596. #if SQLITE_OMIT_LOCALTIME
  597. "OMIT_LOCALTIME",
  598. #endif
  599. #if SQLITE_OMIT_LOOKASIDE
  600. "OMIT_LOOKASIDE",
  601. #endif
  602. #if SQLITE_OMIT_MEMORYDB
  603. "OMIT_MEMORYDB",
  604. #endif
  605. #if SQLITE_OMIT_OR_OPTIMIZATION
  606. "OMIT_OR_OPTIMIZATION",
  607. #endif
  608. #if SQLITE_OMIT_PAGER_PRAGMAS
  609. "OMIT_PAGER_PRAGMAS",
  610. #endif
  611. #if SQLITE_OMIT_PARSER_TRACE
  612. "OMIT_PARSER_TRACE",
  613. #endif
  614. #if SQLITE_OMIT_POPEN
  615. "OMIT_POPEN",
  616. #endif
  617. #if SQLITE_OMIT_PRAGMA
  618. "OMIT_PRAGMA",
  619. #endif
  620. #if SQLITE_OMIT_PROGRESS_CALLBACK
  621. "OMIT_PROGRESS_CALLBACK",
  622. #endif
  623. #if SQLITE_OMIT_QUICKBALANCE
  624. "OMIT_QUICKBALANCE",
  625. #endif
  626. #if SQLITE_OMIT_REINDEX
  627. "OMIT_REINDEX",
  628. #endif
  629. #if SQLITE_OMIT_SCHEMA_PRAGMAS
  630. "OMIT_SCHEMA_PRAGMAS",
  631. #endif
  632. #if SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
  633. "OMIT_SCHEMA_VERSION_PRAGMAS",
  634. #endif
  635. #if SQLITE_OMIT_SHARED_CACHE
  636. "OMIT_SHARED_CACHE",
  637. #endif
  638. #if SQLITE_OMIT_SHUTDOWN_DIRECTORIES
  639. "OMIT_SHUTDOWN_DIRECTORIES",
  640. #endif
  641. #if SQLITE_OMIT_SUBQUERY
  642. "OMIT_SUBQUERY",
  643. #endif
  644. #if SQLITE_OMIT_TCL_VARIABLE
  645. "OMIT_TCL_VARIABLE",
  646. #endif
  647. #if SQLITE_OMIT_TEMPDB
  648. "OMIT_TEMPDB",
  649. #endif
  650. #if SQLITE_OMIT_TEST_CONTROL
  651. "OMIT_TEST_CONTROL",
  652. #endif
  653. #if SQLITE_OMIT_TRACE
  654. "OMIT_TRACE",
  655. #endif
  656. #if SQLITE_OMIT_TRIGGER
  657. "OMIT_TRIGGER",
  658. #endif
  659. #if SQLITE_OMIT_TRUNCATE_OPTIMIZATION
  660. "OMIT_TRUNCATE_OPTIMIZATION",
  661. #endif
  662. #if SQLITE_OMIT_UTF16
  663. "OMIT_UTF16",
  664. #endif
  665. #if SQLITE_OMIT_VACUUM
  666. "OMIT_VACUUM",
  667. #endif
  668. #if SQLITE_OMIT_VIEW
  669. "OMIT_VIEW",
  670. #endif
  671. #if SQLITE_OMIT_VIRTUALTABLE
  672. "OMIT_VIRTUALTABLE",
  673. #endif
  674. #if SQLITE_OMIT_WAL
  675. "OMIT_WAL",
  676. #endif
  677. #if SQLITE_OMIT_WSD
  678. "OMIT_WSD",
  679. #endif
  680. #if SQLITE_OMIT_XFER_OPT
  681. "OMIT_XFER_OPT",
  682. #endif
  683. #if SQLITE_PCACHE_SEPARATE_HEADER
  684. "PCACHE_SEPARATE_HEADER",
  685. #endif
  686. #if SQLITE_PERFORMANCE_TRACE
  687. "PERFORMANCE_TRACE",
  688. #endif
  689. #if SQLITE_POWERSAFE_OVERWRITE
  690. "POWERSAFE_OVERWRITE",
  691. #endif
  692. #if SQLITE_PREFER_PROXY_LOCKING
  693. "PREFER_PROXY_LOCKING",
  694. #endif
  695. #if SQLITE_PROXY_DEBUG
  696. "PROXY_DEBUG",
  697. #endif
  698. #if SQLITE_REVERSE_UNORDERED_SELECTS
  699. "REVERSE_UNORDERED_SELECTS",
  700. #endif
  701. #if SQLITE_RTREE_INT_ONLY
  702. "RTREE_INT_ONLY",
  703. #endif
  704. #if SQLITE_SECURE_DELETE
  705. "SECURE_DELETE",
  706. #endif
  707. #if SQLITE_SMALL_STACK
  708. "SMALL_STACK",
  709. #endif
  710. #ifdef SQLITE_SORTER_PMASZ
  711. "SORTER_PMASZ=" CTIMEOPT_VAL(SQLITE_SORTER_PMASZ),
  712. #endif
  713. #if SQLITE_SOUNDEX
  714. "SOUNDEX",
  715. #endif
  716. #ifdef SQLITE_STAT4_SAMPLES
  717. "STAT4_SAMPLES=" CTIMEOPT_VAL(SQLITE_STAT4_SAMPLES),
  718. #endif
  719. #ifdef SQLITE_STMTJRNL_SPILL
  720. "STMTJRNL_SPILL=" CTIMEOPT_VAL(SQLITE_STMTJRNL_SPILL),
  721. #endif
  722. #if SQLITE_SUBSTR_COMPATIBILITY
  723. "SUBSTR_COMPATIBILITY",
  724. #endif
  725. #if SQLITE_SYSTEM_MALLOC
  726. "SYSTEM_MALLOC",
  727. #endif
  728. #if SQLITE_TCL
  729. "TCL",
  730. #endif
  731. #ifdef SQLITE_TEMP_STORE
  732. "TEMP_STORE=" CTIMEOPT_VAL(SQLITE_TEMP_STORE),
  733. #endif
  734. #if SQLITE_TEST
  735. "TEST",
  736. #endif
  737. #if defined(SQLITE_THREADSAFE)
  738. "THREADSAFE=" CTIMEOPT_VAL(SQLITE_THREADSAFE),
  739. #elif defined(THREADSAFE)
  740. "THREADSAFE=" CTIMEOPT_VAL(THREADSAFE),
  741. #else
  742. "THREADSAFE=1",
  743. #endif
  744. #if SQLITE_UNLINK_AFTER_CLOSE
  745. "UNLINK_AFTER_CLOSE",
  746. #endif
  747. #if SQLITE_UNTESTABLE
  748. "UNTESTABLE",
  749. #endif
  750. #if SQLITE_USER_AUTHENTICATION
  751. "USER_AUTHENTICATION",
  752. #endif
  753. #if SQLITE_USE_ALLOCA
  754. "USE_ALLOCA",
  755. #endif
  756. #if SQLITE_USE_FCNTL_TRACE
  757. "USE_FCNTL_TRACE",
  758. #endif
  759. #if SQLITE_USE_URI
  760. "USE_URI",
  761. #endif
  762. #if SQLITE_VDBE_COVERAGE
  763. "VDBE_COVERAGE",
  764. #endif
  765. #if SQLITE_WIN32_MALLOC
  766. "WIN32_MALLOC",
  767. #endif
  768. #if SQLITE_ZERO_MALLOC
  769. "ZERO_MALLOC",
  770. #endif
  771. /*
  772. ** END CODE GENERATED BY tool/mkctime.tcl
  773. */
  774. };
  775. SQLITE_PRIVATE const char **sqlite3CompileOptions(int *pnOpt){
  776. *pnOpt = sizeof(sqlite3azCompileOpt) / sizeof(sqlite3azCompileOpt[0]);
  777. return (const char**)sqlite3azCompileOpt;
  778. }
  779. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  780. /************** End of ctime.c ***********************************************/
  781. /************** Begin file sqliteInt.h ***************************************/
  782. /*
  783. ** 2001 September 15
  784. **
  785. ** The author disclaims copyright to this source code. In place of
  786. ** a legal notice, here is a blessing:
  787. **
  788. ** May you do good and not evil.
  789. ** May you find forgiveness for yourself and forgive others.
  790. ** May you share freely, never taking more than you give.
  791. **
  792. *************************************************************************
  793. ** Internal interface definitions for SQLite.
  794. **
  795. */
  796. #ifndef SQLITEINT_H
  797. #define SQLITEINT_H
  798. /* Special Comments:
  799. **
  800. ** Some comments have special meaning to the tools that measure test
  801. ** coverage:
  802. **
  803. ** NO_TEST - The branches on this line are not
  804. ** measured by branch coverage. This is
  805. ** used on lines of code that actually
  806. ** implement parts of coverage testing.
  807. **
  808. ** OPTIMIZATION-IF-TRUE - This branch is allowed to alway be false
  809. ** and the correct answer is still obtained,
  810. ** though perhaps more slowly.
  811. **
  812. ** OPTIMIZATION-IF-FALSE - This branch is allowed to alway be true
  813. ** and the correct answer is still obtained,
  814. ** though perhaps more slowly.
  815. **
  816. ** PREVENTS-HARMLESS-OVERREAD - This branch prevents a buffer overread
  817. ** that would be harmless and undetectable
  818. ** if it did occur.
  819. **
  820. ** In all cases, the special comment must be enclosed in the usual
  821. ** slash-asterisk...asterisk-slash comment marks, with no spaces between the
  822. ** asterisks and the comment text.
  823. */
  824. /*
  825. ** Make sure the Tcl calling convention macro is defined. This macro is
  826. ** only used by test code and Tcl integration code.
  827. */
  828. #ifndef SQLITE_TCLAPI
  829. # define SQLITE_TCLAPI
  830. #endif
  831. /*
  832. ** Include the header file used to customize the compiler options for MSVC.
  833. ** This should be done first so that it can successfully prevent spurious
  834. ** compiler warnings due to subsequent content in this file and other files
  835. ** that are included by this file.
  836. */
  837. /************** Include msvc.h in the middle of sqliteInt.h ******************/
  838. /************** Begin file msvc.h ********************************************/
  839. /*
  840. ** 2015 January 12
  841. **
  842. ** The author disclaims copyright to this source code. In place of
  843. ** a legal notice, here is a blessing:
  844. **
  845. ** May you do good and not evil.
  846. ** May you find forgiveness for yourself and forgive others.
  847. ** May you share freely, never taking more than you give.
  848. **
  849. ******************************************************************************
  850. **
  851. ** This file contains code that is specific to MSVC.
  852. */
  853. #ifndef SQLITE_MSVC_H
  854. #define SQLITE_MSVC_H
  855. #if defined(_MSC_VER)
  856. #pragma warning(disable : 4054)
  857. #pragma warning(disable : 4055)
  858. #pragma warning(disable : 4100)
  859. #pragma warning(disable : 4127)
  860. #pragma warning(disable : 4130)
  861. #pragma warning(disable : 4152)
  862. #pragma warning(disable : 4189)
  863. #pragma warning(disable : 4206)
  864. #pragma warning(disable : 4210)
  865. #pragma warning(disable : 4232)
  866. #pragma warning(disable : 4244)
  867. #pragma warning(disable : 4305)
  868. #pragma warning(disable : 4306)
  869. #pragma warning(disable : 4702)
  870. #pragma warning(disable : 4706)
  871. #endif /* defined(_MSC_VER) */
  872. #if defined(_MSC_VER) && !defined(_WIN64)
  873. #undef SQLITE_4_BYTE_ALIGNED_MALLOC
  874. #define SQLITE_4_BYTE_ALIGNED_MALLOC
  875. #endif /* defined(_MSC_VER) && !defined(_WIN64) */
  876. #endif /* SQLITE_MSVC_H */
  877. /************** End of msvc.h ************************************************/
  878. /************** Continuing where we left off in sqliteInt.h ******************/
  879. /*
  880. ** Special setup for VxWorks
  881. */
  882. /************** Include vxworks.h in the middle of sqliteInt.h ***************/
  883. /************** Begin file vxworks.h *****************************************/
  884. /*
  885. ** 2015-03-02
  886. **
  887. ** The author disclaims copyright to this source code. In place of
  888. ** a legal notice, here is a blessing:
  889. **
  890. ** May you do good and not evil.
  891. ** May you find forgiveness for yourself and forgive others.
  892. ** May you share freely, never taking more than you give.
  893. **
  894. ******************************************************************************
  895. **
  896. ** This file contains code that is specific to Wind River's VxWorks
  897. */
  898. #if defined(__RTP__) || defined(_WRS_KERNEL)
  899. /* This is VxWorks. Set up things specially for that OS
  900. */
  901. #include <vxWorks.h>
  902. #include <pthread.h> /* amalgamator: dontcache */
  903. #define OS_VXWORKS 1
  904. #define SQLITE_OS_OTHER 0
  905. #define SQLITE_HOMEGROWN_RECURSIVE_MUTEX 1
  906. #define SQLITE_OMIT_LOAD_EXTENSION 1
  907. #define SQLITE_ENABLE_LOCKING_STYLE 0
  908. #define HAVE_UTIME 1
  909. #else
  910. /* This is not VxWorks. */
  911. #define OS_VXWORKS 0
  912. #define HAVE_FCHOWN 1
  913. #define HAVE_READLINK 1
  914. #define HAVE_LSTAT 1
  915. #endif /* defined(_WRS_KERNEL) */
  916. /************** End of vxworks.h *********************************************/
  917. /************** Continuing where we left off in sqliteInt.h ******************/
  918. /*
  919. ** These #defines should enable >2GB file support on POSIX if the
  920. ** underlying operating system supports it. If the OS lacks
  921. ** large file support, or if the OS is windows, these should be no-ops.
  922. **
  923. ** Ticket #2739: The _LARGEFILE_SOURCE macro must appear before any
  924. ** system #includes. Hence, this block of code must be the very first
  925. ** code in all source files.
  926. **
  927. ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
  928. ** on the compiler command line. This is necessary if you are compiling
  929. ** on a recent machine (ex: Red Hat 7.2) but you want your code to work
  930. ** on an older machine (ex: Red Hat 6.0). If you compile on Red Hat 7.2
  931. ** without this option, LFS is enable. But LFS does not exist in the kernel
  932. ** in Red Hat 6.0, so the code won't work. Hence, for maximum binary
  933. ** portability you should omit LFS.
  934. **
  935. ** The previous paragraph was written in 2005. (This paragraph is written
  936. ** on 2008-11-28.) These days, all Linux kernels support large files, so
  937. ** you should probably leave LFS enabled. But some embedded platforms might
  938. ** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
  939. **
  940. ** Similar is true for Mac OS X. LFS is only supported on Mac OS X 9 and later.
  941. */
  942. #ifndef SQLITE_DISABLE_LFS
  943. # define _LARGE_FILE 1
  944. # ifndef _FILE_OFFSET_BITS
  945. # define _FILE_OFFSET_BITS 64
  946. # endif
  947. # define _LARGEFILE_SOURCE 1
  948. #endif
  949. /* The GCC_VERSION and MSVC_VERSION macros are used to
  950. ** conditionally include optimizations for each of these compilers. A
  951. ** value of 0 means that compiler is not being used. The
  952. ** SQLITE_DISABLE_INTRINSIC macro means do not use any compiler-specific
  953. ** optimizations, and hence set all compiler macros to 0
  954. **
  955. ** There was once also a CLANG_VERSION macro. However, we learn that the
  956. ** version numbers in clang are for "marketing" only and are inconsistent
  957. ** and unreliable. Fortunately, all versions of clang also recognize the
  958. ** gcc version numbers and have reasonable settings for gcc version numbers,
  959. ** so the GCC_VERSION macro will be set to a correct non-zero value even
  960. ** when compiling with clang.
  961. */
  962. #if defined(__GNUC__) && !defined(SQLITE_DISABLE_INTRINSIC)
  963. # define GCC_VERSION (__GNUC__*1000000+__GNUC_MINOR__*1000+__GNUC_PATCHLEVEL__)
  964. #else
  965. # define GCC_VERSION 0
  966. #endif
  967. #if defined(_MSC_VER) && !defined(SQLITE_DISABLE_INTRINSIC)
  968. # define MSVC_VERSION _MSC_VER
  969. #else
  970. # define MSVC_VERSION 0
  971. #endif
  972. /* Needed for various definitions... */
  973. #if defined(__GNUC__) && !defined(_GNU_SOURCE)
  974. # define _GNU_SOURCE
  975. #endif
  976. #if defined(__OpenBSD__) && !defined(_BSD_SOURCE)
  977. # define _BSD_SOURCE
  978. #endif
  979. /*
  980. ** For MinGW, check to see if we can include the header file containing its
  981. ** version information, among other things. Normally, this internal MinGW
  982. ** header file would [only] be included automatically by other MinGW header
  983. ** files; however, the contained version information is now required by this
  984. ** header file to work around binary compatibility issues (see below) and
  985. ** this is the only known way to reliably obtain it. This entire #if block
  986. ** would be completely unnecessary if there was any other way of detecting
  987. ** MinGW via their preprocessor (e.g. if they customized their GCC to define
  988. ** some MinGW-specific macros). When compiling for MinGW, either the
  989. ** _HAVE_MINGW_H or _HAVE__MINGW_H (note the extra underscore) macro must be
  990. ** defined; otherwise, detection of conditions specific to MinGW will be
  991. ** disabled.
  992. */
  993. #if defined(_HAVE_MINGW_H)
  994. # include "mingw.h"
  995. #elif defined(_HAVE__MINGW_H)
  996. # include "_mingw.h"
  997. #endif
  998. /*
  999. ** For MinGW version 4.x (and higher), check to see if the _USE_32BIT_TIME_T
  1000. ** define is required to maintain binary compatibility with the MSVC runtime
  1001. ** library in use (e.g. for Windows XP).
  1002. */
  1003. #if !defined(_USE_32BIT_TIME_T) && !defined(_USE_64BIT_TIME_T) && \
  1004. defined(_WIN32) && !defined(_WIN64) && \
  1005. defined(__MINGW_MAJOR_VERSION) && __MINGW_MAJOR_VERSION >= 4 && \
  1006. defined(__MSVCRT__)
  1007. # define _USE_32BIT_TIME_T
  1008. #endif
  1009. /* The public SQLite interface. The _FILE_OFFSET_BITS macro must appear
  1010. ** first in QNX. Also, the _USE_32BIT_TIME_T macro must appear first for
  1011. ** MinGW.
  1012. */
  1013. /************** Include sqlite3.h in the middle of sqliteInt.h ***************/
  1014. /************** Begin file sqlite3.h *****************************************/
  1015. /*
  1016. ** 2001-09-15
  1017. **
  1018. ** The author disclaims copyright to this source code. In place of
  1019. ** a legal notice, here is a blessing:
  1020. **
  1021. ** May you do good and not evil.
  1022. ** May you find forgiveness for yourself and forgive others.
  1023. ** May you share freely, never taking more than you give.
  1024. **
  1025. *************************************************************************
  1026. ** This header file defines the interface that the SQLite library
  1027. ** presents to client programs. If a C-function, structure, datatype,
  1028. ** or constant definition does not appear in this file, then it is
  1029. ** not a published API of SQLite, is subject to change without
  1030. ** notice, and should not be referenced by programs that use SQLite.
  1031. **
  1032. ** Some of the definitions that are in this file are marked as
  1033. ** "experimental". Experimental interfaces are normally new
  1034. ** features recently added to SQLite. We do not anticipate changes
  1035. ** to experimental interfaces but reserve the right to make minor changes
  1036. ** if experience from use "in the wild" suggest such changes are prudent.
  1037. **
  1038. ** The official C-language API documentation for SQLite is derived
  1039. ** from comments in this file. This file is the authoritative source
  1040. ** on how SQLite interfaces are supposed to operate.
  1041. **
  1042. ** The name of this file under configuration management is "sqlite.h.in".
  1043. ** The makefile makes some minor changes to this file (such as inserting
  1044. ** the version number) and changes its name to "sqlite3.h" as
  1045. ** part of the build process.
  1046. */
  1047. #ifndef SQLITE3_H
  1048. #define SQLITE3_H
  1049. #include <stdarg.h> /* Needed for the definition of va_list */
  1050. /*
  1051. ** Make sure we can call this stuff from C++.
  1052. */
  1053. #if 0
  1054. extern "C" {
  1055. #endif
  1056. /*
  1057. ** Provide the ability to override linkage features of the interface.
  1058. */
  1059. #ifndef SQLITE_EXTERN
  1060. # define SQLITE_EXTERN extern
  1061. #endif
  1062. #ifndef SQLITE_API
  1063. # define SQLITE_API
  1064. #endif
  1065. #ifndef SQLITE_CDECL
  1066. # define SQLITE_CDECL
  1067. #endif
  1068. #ifndef SQLITE_APICALL
  1069. # define SQLITE_APICALL
  1070. #endif
  1071. #ifndef SQLITE_STDCALL
  1072. # define SQLITE_STDCALL SQLITE_APICALL
  1073. #endif
  1074. #ifndef SQLITE_CALLBACK
  1075. # define SQLITE_CALLBACK
  1076. #endif
  1077. #ifndef SQLITE_SYSAPI
  1078. # define SQLITE_SYSAPI
  1079. #endif
  1080. /*
  1081. ** These no-op macros are used in front of interfaces to mark those
  1082. ** interfaces as either deprecated or experimental. New applications
  1083. ** should not use deprecated interfaces - they are supported for backwards
  1084. ** compatibility only. Application writers should be aware that
  1085. ** experimental interfaces are subject to change in point releases.
  1086. **
  1087. ** These macros used to resolve to various kinds of compiler magic that
  1088. ** would generate warning messages when they were used. But that
  1089. ** compiler magic ended up generating such a flurry of bug reports
  1090. ** that we have taken it all out and gone back to using simple
  1091. ** noop macros.
  1092. */
  1093. #define SQLITE_DEPRECATED
  1094. #define SQLITE_EXPERIMENTAL
  1095. /*
  1096. ** Ensure these symbols were not defined by some previous header file.
  1097. */
  1098. #ifdef SQLITE_VERSION
  1099. # undef SQLITE_VERSION
  1100. #endif
  1101. #ifdef SQLITE_VERSION_NUMBER
  1102. # undef SQLITE_VERSION_NUMBER
  1103. #endif
  1104. /*
  1105. ** CAPI3REF: Compile-Time Library Version Numbers
  1106. **
  1107. ** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header
  1108. ** evaluates to a string literal that is the SQLite version in the
  1109. ** format "X.Y.Z" where X is the major version number (always 3 for
  1110. ** SQLite3) and Y is the minor version number and Z is the release number.)^
  1111. ** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer
  1112. ** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same
  1113. ** numbers used in [SQLITE_VERSION].)^
  1114. ** The SQLITE_VERSION_NUMBER for any given release of SQLite will also
  1115. ** be larger than the release from which it is derived. Either Y will
  1116. ** be held constant and Z will be incremented or else Y will be incremented
  1117. ** and Z will be reset to zero.
  1118. **
  1119. ** Since [version 3.6.18] ([dateof:3.6.18]),
  1120. ** SQLite source code has been stored in the
  1121. ** <a href="http://www.fossil-scm.org/">Fossil configuration management
  1122. ** system</a>. ^The SQLITE_SOURCE_ID macro evaluates to
  1123. ** a string which identifies a particular check-in of SQLite
  1124. ** within its configuration management system. ^The SQLITE_SOURCE_ID
  1125. ** string contains the date and time of the check-in (UTC) and a SHA1
  1126. ** or SHA3-256 hash of the entire source tree. If the source code has
  1127. ** been edited in any way since it was last checked in, then the last
  1128. ** four hexadecimal digits of the hash may be modified.
  1129. **
  1130. ** See also: [sqlite3_libversion()],
  1131. ** [sqlite3_libversion_number()], [sqlite3_sourceid()],
  1132. ** [sqlite_version()] and [sqlite_source_id()].
  1133. */
  1134. #define SQLITE_VERSION "3.32.2"
  1135. #define SQLITE_VERSION_NUMBER 3032002
  1136. #define SQLITE_SOURCE_ID "2020-06-04 12:58:43 ec02243ea6ce33b090870ae55ab8aa2534b54d216d45c4aa2fdbb00e86861e8c"
  1137. /*
  1138. ** CAPI3REF: Run-Time Library Version Numbers
  1139. ** KEYWORDS: sqlite3_version sqlite3_sourceid
  1140. **
  1141. ** These interfaces provide the same information as the [SQLITE_VERSION],
  1142. ** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros
  1143. ** but are associated with the library instead of the header file. ^(Cautious
  1144. ** programmers might include assert() statements in their application to
  1145. ** verify that values returned by these interfaces match the macros in
  1146. ** the header, and thus ensure that the application is
  1147. ** compiled with matching library and header files.
  1148. **
  1149. ** <blockquote><pre>
  1150. ** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );
  1151. ** assert( strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,80)==0 );
  1152. ** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );
  1153. ** </pre></blockquote>)^
  1154. **
  1155. ** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION]
  1156. ** macro. ^The sqlite3_libversion() function returns a pointer to the
  1157. ** to the sqlite3_version[] string constant. The sqlite3_libversion()
  1158. ** function is provided for use in DLLs since DLL users usually do not have
  1159. ** direct access to string constants within the DLL. ^The
  1160. ** sqlite3_libversion_number() function returns an integer equal to
  1161. ** [SQLITE_VERSION_NUMBER]. ^(The sqlite3_sourceid() function returns
  1162. ** a pointer to a string constant whose value is the same as the
  1163. ** [SQLITE_SOURCE_ID] C preprocessor macro. Except if SQLite is built
  1164. ** using an edited copy of [the amalgamation], then the last four characters
  1165. ** of the hash might be different from [SQLITE_SOURCE_ID].)^
  1166. **
  1167. ** See also: [sqlite_version()] and [sqlite_source_id()].
  1168. */
  1169. SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
  1170. SQLITE_API const char *sqlite3_libversion(void);
  1171. SQLITE_API const char *sqlite3_sourceid(void);
  1172. SQLITE_API int sqlite3_libversion_number(void);
  1173. /*
  1174. ** CAPI3REF: Run-Time Library Compilation Options Diagnostics
  1175. **
  1176. ** ^The sqlite3_compileoption_used() function returns 0 or 1
  1177. ** indicating whether the specified option was defined at
  1178. ** compile time. ^The SQLITE_ prefix may be omitted from the
  1179. ** option name passed to sqlite3_compileoption_used().
  1180. **
  1181. ** ^The sqlite3_compileoption_get() function allows iterating
  1182. ** over the list of options that were defined at compile time by
  1183. ** returning the N-th compile time option string. ^If N is out of range,
  1184. ** sqlite3_compileoption_get() returns a NULL pointer. ^The SQLITE_
  1185. ** prefix is omitted from any strings returned by
  1186. ** sqlite3_compileoption_get().
  1187. **
  1188. ** ^Support for the diagnostic functions sqlite3_compileoption_used()
  1189. ** and sqlite3_compileoption_get() may be omitted by specifying the
  1190. ** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time.
  1191. **
  1192. ** See also: SQL functions [sqlite_compileoption_used()] and
  1193. ** [sqlite_compileoption_get()] and the [compile_options pragma].
  1194. */
  1195. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  1196. SQLITE_API int sqlite3_compileoption_used(const char *zOptName);
  1197. SQLITE_API const char *sqlite3_compileoption_get(int N);
  1198. #else
  1199. # define sqlite3_compileoption_used(X) 0
  1200. # define sqlite3_compileoption_get(X) ((void*)0)
  1201. #endif
  1202. /*
  1203. ** CAPI3REF: Test To See If The Library Is Threadsafe
  1204. **
  1205. ** ^The sqlite3_threadsafe() function returns zero if and only if
  1206. ** SQLite was compiled with mutexing code omitted due to the
  1207. ** [SQLITE_THREADSAFE] compile-time option being set to 0.
  1208. **
  1209. ** SQLite can be compiled with or without mutexes. When
  1210. ** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes
  1211. ** are enabled and SQLite is threadsafe. When the
  1212. ** [SQLITE_THREADSAFE] macro is 0,
  1213. ** the mutexes are omitted. Without the mutexes, it is not safe
  1214. ** to use SQLite concurrently from more than one thread.
  1215. **
  1216. ** Enabling mutexes incurs a measurable performance penalty.
  1217. ** So if speed is of utmost importance, it makes sense to disable
  1218. ** the mutexes. But for maximum safety, mutexes should be enabled.
  1219. ** ^The default behavior is for mutexes to be enabled.
  1220. **
  1221. ** This interface can be used by an application to make sure that the
  1222. ** version of SQLite that it is linking against was compiled with
  1223. ** the desired setting of the [SQLITE_THREADSAFE] macro.
  1224. **
  1225. ** This interface only reports on the compile-time mutex setting
  1226. ** of the [SQLITE_THREADSAFE] flag. If SQLite is compiled with
  1227. ** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but
  1228. ** can be fully or partially disabled using a call to [sqlite3_config()]
  1229. ** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD],
  1230. ** or [SQLITE_CONFIG_SERIALIZED]. ^(The return value of the
  1231. ** sqlite3_threadsafe() function shows only the compile-time setting of
  1232. ** thread safety, not any run-time changes to that setting made by
  1233. ** sqlite3_config(). In other words, the return value from sqlite3_threadsafe()
  1234. ** is unchanged by calls to sqlite3_config().)^
  1235. **
  1236. ** See the [threading mode] documentation for additional information.
  1237. */
  1238. SQLITE_API int sqlite3_threadsafe(void);
  1239. /*
  1240. ** CAPI3REF: Database Connection Handle
  1241. ** KEYWORDS: {database connection} {database connections}
  1242. **
  1243. ** Each open SQLite database is represented by a pointer to an instance of
  1244. ** the opaque structure named "sqlite3". It is useful to think of an sqlite3
  1245. ** pointer as an object. The [sqlite3_open()], [sqlite3_open16()], and
  1246. ** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()]
  1247. ** and [sqlite3_close_v2()] are its destructors. There are many other
  1248. ** interfaces (such as
  1249. ** [sqlite3_prepare_v2()], [sqlite3_create_function()], and
  1250. ** [sqlite3_busy_timeout()] to name but three) that are methods on an
  1251. ** sqlite3 object.
  1252. */
  1253. typedef struct sqlite3 sqlite3;
  1254. /*
  1255. ** CAPI3REF: 64-Bit Integer Types
  1256. ** KEYWORDS: sqlite_int64 sqlite_uint64
  1257. **
  1258. ** Because there is no cross-platform way to specify 64-bit integer types
  1259. ** SQLite includes typedefs for 64-bit signed and unsigned integers.
  1260. **
  1261. ** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions.
  1262. ** The sqlite_int64 and sqlite_uint64 types are supported for backwards
  1263. ** compatibility only.
  1264. **
  1265. ** ^The sqlite3_int64 and sqlite_int64 types can store integer values
  1266. ** between -9223372036854775808 and +9223372036854775807 inclusive. ^The
  1267. ** sqlite3_uint64 and sqlite_uint64 types can store integer values
  1268. ** between 0 and +18446744073709551615 inclusive.
  1269. */
  1270. #ifdef SQLITE_INT64_TYPE
  1271. typedef SQLITE_INT64_TYPE sqlite_int64;
  1272. # ifdef SQLITE_UINT64_TYPE
  1273. typedef SQLITE_UINT64_TYPE sqlite_uint64;
  1274. # else
  1275. typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
  1276. # endif
  1277. #elif defined(_MSC_VER) || defined(__BORLANDC__)
  1278. typedef __int64 sqlite_int64;
  1279. typedef unsigned __int64 sqlite_uint64;
  1280. #else
  1281. typedef long long int sqlite_int64;
  1282. typedef unsigned long long int sqlite_uint64;
  1283. #endif
  1284. typedef sqlite_int64 sqlite3_int64;
  1285. typedef sqlite_uint64 sqlite3_uint64;
  1286. /*
  1287. ** If compiling for a processor that lacks floating point support,
  1288. ** substitute integer for floating-point.
  1289. */
  1290. #ifdef SQLITE_OMIT_FLOATING_POINT
  1291. # define double sqlite3_int64
  1292. #endif
  1293. /*
  1294. ** CAPI3REF: Closing A Database Connection
  1295. ** DESTRUCTOR: sqlite3
  1296. **
  1297. ** ^The sqlite3_close() and sqlite3_close_v2() routines are destructors
  1298. ** for the [sqlite3] object.
  1299. ** ^Calls to sqlite3_close() and sqlite3_close_v2() return [SQLITE_OK] if
  1300. ** the [sqlite3] object is successfully destroyed and all associated
  1301. ** resources are deallocated.
  1302. **
  1303. ** Ideally, applications should [sqlite3_finalize | finalize] all
  1304. ** [prepared statements], [sqlite3_blob_close | close] all [BLOB handles], and
  1305. ** [sqlite3_backup_finish | finish] all [sqlite3_backup] objects associated
  1306. ** with the [sqlite3] object prior to attempting to close the object.
  1307. ** ^If the database connection is associated with unfinalized prepared
  1308. ** statements, BLOB handlers, and/or unfinished sqlite3_backup objects then
  1309. ** sqlite3_close() will leave the database connection open and return
  1310. ** [SQLITE_BUSY]. ^If sqlite3_close_v2() is called with unfinalized prepared
  1311. ** statements, unclosed BLOB handlers, and/or unfinished sqlite3_backups,
  1312. ** it returns [SQLITE_OK] regardless, but instead of deallocating the database
  1313. ** connection immediately, it marks the database connection as an unusable
  1314. ** "zombie" and makes arrangements to automatically deallocate the database
  1315. ** connection after all prepared statements are finalized, all BLOB handles
  1316. ** are closed, and all backups have finished. The sqlite3_close_v2() interface
  1317. ** is intended for use with host languages that are garbage collected, and
  1318. ** where the order in which destructors are called is arbitrary.
  1319. **
  1320. ** ^If an [sqlite3] object is destroyed while a transaction is open,
  1321. ** the transaction is automatically rolled back.
  1322. **
  1323. ** The C parameter to [sqlite3_close(C)] and [sqlite3_close_v2(C)]
  1324. ** must be either a NULL
  1325. ** pointer or an [sqlite3] object pointer obtained
  1326. ** from [sqlite3_open()], [sqlite3_open16()], or
  1327. ** [sqlite3_open_v2()], and not previously closed.
  1328. ** ^Calling sqlite3_close() or sqlite3_close_v2() with a NULL pointer
  1329. ** argument is a harmless no-op.
  1330. */
  1331. SQLITE_API int sqlite3_close(sqlite3*);
  1332. SQLITE_API int sqlite3_close_v2(sqlite3*);
  1333. /*
  1334. ** The type for a callback function.
  1335. ** This is legacy and deprecated. It is included for historical
  1336. ** compatibility and is not documented.
  1337. */
  1338. typedef int (*sqlite3_callback)(void*,int,char**, char**);
  1339. /*
  1340. ** CAPI3REF: One-Step Query Execution Interface
  1341. ** METHOD: sqlite3
  1342. **
  1343. ** The sqlite3_exec() interface is a convenience wrapper around
  1344. ** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()],
  1345. ** that allows an application to run multiple statements of SQL
  1346. ** without having to use a lot of C code.
  1347. **
  1348. ** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded,
  1349. ** semicolon-separate SQL statements passed into its 2nd argument,
  1350. ** in the context of the [database connection] passed in as its 1st
  1351. ** argument. ^If the callback function of the 3rd argument to
  1352. ** sqlite3_exec() is not NULL, then it is invoked for each result row
  1353. ** coming out of the evaluated SQL statements. ^The 4th argument to
  1354. ** sqlite3_exec() is relayed through to the 1st argument of each
  1355. ** callback invocation. ^If the callback pointer to sqlite3_exec()
  1356. ** is NULL, then no callback is ever invoked and result rows are
  1357. ** ignored.
  1358. **
  1359. ** ^If an error occurs while evaluating the SQL statements passed into
  1360. ** sqlite3_exec(), then execution of the current statement stops and
  1361. ** subsequent statements are skipped. ^If the 5th parameter to sqlite3_exec()
  1362. ** is not NULL then any error message is written into memory obtained
  1363. ** from [sqlite3_malloc()] and passed back through the 5th parameter.
  1364. ** To avoid memory leaks, the application should invoke [sqlite3_free()]
  1365. ** on error message strings returned through the 5th parameter of
  1366. ** sqlite3_exec() after the error message string is no longer needed.
  1367. ** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors
  1368. ** occur, then sqlite3_exec() sets the pointer in its 5th parameter to
  1369. ** NULL before returning.
  1370. **
  1371. ** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec()
  1372. ** routine returns SQLITE_ABORT without invoking the callback again and
  1373. ** without running any subsequent SQL statements.
  1374. **
  1375. ** ^The 2nd argument to the sqlite3_exec() callback function is the
  1376. ** number of columns in the result. ^The 3rd argument to the sqlite3_exec()
  1377. ** callback is an array of pointers to strings obtained as if from
  1378. ** [sqlite3_column_text()], one for each column. ^If an element of a
  1379. ** result row is NULL then the corresponding string pointer for the
  1380. ** sqlite3_exec() callback is a NULL pointer. ^The 4th argument to the
  1381. ** sqlite3_exec() callback is an array of pointers to strings where each
  1382. ** entry represents the name of corresponding result column as obtained
  1383. ** from [sqlite3_column_name()].
  1384. **
  1385. ** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer
  1386. ** to an empty string, or a pointer that contains only whitespace and/or
  1387. ** SQL comments, then no SQL statements are evaluated and the database
  1388. ** is not changed.
  1389. **
  1390. ** Restrictions:
  1391. **
  1392. ** <ul>
  1393. ** <li> The application must ensure that the 1st parameter to sqlite3_exec()
  1394. ** is a valid and open [database connection].
  1395. ** <li> The application must not close the [database connection] specified by
  1396. ** the 1st parameter to sqlite3_exec() while sqlite3_exec() is running.
  1397. ** <li> The application must not modify the SQL statement text passed into
  1398. ** the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running.
  1399. ** </ul>
  1400. */
  1401. SQLITE_API int sqlite3_exec(
  1402. sqlite3*, /* An open database */
  1403. const char *sql, /* SQL to be evaluated */
  1404. int (*callback)(void*,int,char**,char**), /* Callback function */
  1405. void *, /* 1st argument to callback */
  1406. char **errmsg /* Error msg written here */
  1407. );
  1408. /*
  1409. ** CAPI3REF: Result Codes
  1410. ** KEYWORDS: {result code definitions}
  1411. **
  1412. ** Many SQLite functions return an integer result code from the set shown
  1413. ** here in order to indicate success or failure.
  1414. **
  1415. ** New error codes may be added in future versions of SQLite.
  1416. **
  1417. ** See also: [extended result code definitions]
  1418. */
  1419. #define SQLITE_OK 0 /* Successful result */
  1420. /* beginning-of-error-codes */
  1421. #define SQLITE_ERROR 1 /* Generic error */
  1422. #define SQLITE_INTERNAL 2 /* Internal logic error in SQLite */
  1423. #define SQLITE_PERM 3 /* Access permission denied */
  1424. #define SQLITE_ABORT 4 /* Callback routine requested an abort */
  1425. #define SQLITE_BUSY 5 /* The database file is locked */
  1426. #define SQLITE_LOCKED 6 /* A table in the database is locked */
  1427. #define SQLITE_NOMEM 7 /* A malloc() failed */
  1428. #define SQLITE_READONLY 8 /* Attempt to write a readonly database */
  1429. #define SQLITE_INTERRUPT 9 /* Operation terminated by sqlite3_interrupt()*/
  1430. #define SQLITE_IOERR 10 /* Some kind of disk I/O error occurred */
  1431. #define SQLITE_CORRUPT 11 /* The database disk image is malformed */
  1432. #define SQLITE_NOTFOUND 12 /* Unknown opcode in sqlite3_file_control() */
  1433. #define SQLITE_FULL 13 /* Insertion failed because database is full */
  1434. #define SQLITE_CANTOPEN 14 /* Unable to open the database file */
  1435. #define SQLITE_PROTOCOL 15 /* Database lock protocol error */
  1436. #define SQLITE_EMPTY 16 /* Internal use only */
  1437. #define SQLITE_SCHEMA 17 /* The database schema changed */
  1438. #define SQLITE_TOOBIG 18 /* String or BLOB exceeds size limit */
  1439. #define SQLITE_CONSTRAINT 19 /* Abort due to constraint violation */
  1440. #define SQLITE_MISMATCH 20 /* Data type mismatch */
  1441. #define SQLITE_MISUSE 21 /* Library used incorrectly */
  1442. #define SQLITE_NOLFS 22 /* Uses OS features not supported on host */
  1443. #define SQLITE_AUTH 23 /* Authorization denied */
  1444. #define SQLITE_FORMAT 24 /* Not used */
  1445. #define SQLITE_RANGE 25 /* 2nd parameter to sqlite3_bind out of range */
  1446. #define SQLITE_NOTADB 26 /* File opened that is not a database file */
  1447. #define SQLITE_NOTICE 27 /* Notifications from sqlite3_log() */
  1448. #define SQLITE_WARNING 28 /* Warnings from sqlite3_log() */
  1449. #define SQLITE_ROW 100 /* sqlite3_step() has another row ready */
  1450. #define SQLITE_DONE 101 /* sqlite3_step() has finished executing */
  1451. /* end-of-error-codes */
  1452. /*
  1453. ** CAPI3REF: Extended Result Codes
  1454. ** KEYWORDS: {extended result code definitions}
  1455. **
  1456. ** In its default configuration, SQLite API routines return one of 30 integer
  1457. ** [result codes]. However, experience has shown that many of
  1458. ** these result codes are too coarse-grained. They do not provide as
  1459. ** much information about problems as programmers might like. In an effort to
  1460. ** address this, newer versions of SQLite (version 3.3.8 [dateof:3.3.8]
  1461. ** and later) include
  1462. ** support for additional result codes that provide more detailed information
  1463. ** about errors. These [extended result codes] are enabled or disabled
  1464. ** on a per database connection basis using the
  1465. ** [sqlite3_extended_result_codes()] API. Or, the extended code for
  1466. ** the most recent error can be obtained using
  1467. ** [sqlite3_extended_errcode()].
  1468. */
  1469. #define SQLITE_ERROR_MISSING_COLLSEQ (SQLITE_ERROR | (1<<8))
  1470. #define SQLITE_ERROR_RETRY (SQLITE_ERROR | (2<<8))
  1471. #define SQLITE_ERROR_SNAPSHOT (SQLITE_ERROR | (3<<8))
  1472. #define SQLITE_IOERR_READ (SQLITE_IOERR | (1<<8))
  1473. #define SQLITE_IOERR_SHORT_READ (SQLITE_IOERR | (2<<8))
  1474. #define SQLITE_IOERR_WRITE (SQLITE_IOERR | (3<<8))
  1475. #define SQLITE_IOERR_FSYNC (SQLITE_IOERR | (4<<8))
  1476. #define SQLITE_IOERR_DIR_FSYNC (SQLITE_IOERR | (5<<8))
  1477. #define SQLITE_IOERR_TRUNCATE (SQLITE_IOERR | (6<<8))
  1478. #define SQLITE_IOERR_FSTAT (SQLITE_IOERR | (7<<8))
  1479. #define SQLITE_IOERR_UNLOCK (SQLITE_IOERR | (8<<8))
  1480. #define SQLITE_IOERR_RDLOCK (SQLITE_IOERR | (9<<8))
  1481. #define SQLITE_IOERR_DELETE (SQLITE_IOERR | (10<<8))
  1482. #define SQLITE_IOERR_BLOCKED (SQLITE_IOERR | (11<<8))
  1483. #define SQLITE_IOERR_NOMEM (SQLITE_IOERR | (12<<8))
  1484. #define SQLITE_IOERR_ACCESS (SQLITE_IOERR | (13<<8))
  1485. #define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8))
  1486. #define SQLITE_IOERR_LOCK (SQLITE_IOERR | (15<<8))
  1487. #define SQLITE_IOERR_CLOSE (SQLITE_IOERR | (16<<8))
  1488. #define SQLITE_IOERR_DIR_CLOSE (SQLITE_IOERR | (17<<8))
  1489. #define SQLITE_IOERR_SHMOPEN (SQLITE_IOERR | (18<<8))
  1490. #define SQLITE_IOERR_SHMSIZE (SQLITE_IOERR | (19<<8))
  1491. #define SQLITE_IOERR_SHMLOCK (SQLITE_IOERR | (20<<8))
  1492. #define SQLITE_IOERR_SHMMAP (SQLITE_IOERR | (21<<8))
  1493. #define SQLITE_IOERR_SEEK (SQLITE_IOERR | (22<<8))
  1494. #define SQLITE_IOERR_DELETE_NOENT (SQLITE_IOERR | (23<<8))
  1495. #define SQLITE_IOERR_MMAP (SQLITE_IOERR | (24<<8))
  1496. #define SQLITE_IOERR_GETTEMPPATH (SQLITE_IOERR | (25<<8))
  1497. #define SQLITE_IOERR_CONVPATH (SQLITE_IOERR | (26<<8))
  1498. #define SQLITE_IOERR_VNODE (SQLITE_IOERR | (27<<8))
  1499. #define SQLITE_IOERR_AUTH (SQLITE_IOERR | (28<<8))
  1500. #define SQLITE_IOERR_BEGIN_ATOMIC (SQLITE_IOERR | (29<<8))
  1501. #define SQLITE_IOERR_COMMIT_ATOMIC (SQLITE_IOERR | (30<<8))
  1502. #define SQLITE_IOERR_ROLLBACK_ATOMIC (SQLITE_IOERR | (31<<8))
  1503. #define SQLITE_IOERR_DATA (SQLITE_IOERR | (32<<8))
  1504. #define SQLITE_LOCKED_SHAREDCACHE (SQLITE_LOCKED | (1<<8))
  1505. #define SQLITE_LOCKED_VTAB (SQLITE_LOCKED | (2<<8))
  1506. #define SQLITE_BUSY_RECOVERY (SQLITE_BUSY | (1<<8))
  1507. #define SQLITE_BUSY_SNAPSHOT (SQLITE_BUSY | (2<<8))
  1508. #define SQLITE_BUSY_TIMEOUT (SQLITE_BUSY | (3<<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_CANTOPEN_SYMLINK (SQLITE_CANTOPEN | (6<<8))
  1515. #define SQLITE_CORRUPT_VTAB (SQLITE_CORRUPT | (1<<8))
  1516. #define SQLITE_CORRUPT_SEQUENCE (SQLITE_CORRUPT | (2<<8))
  1517. #define SQLITE_CORRUPT_INDEX (SQLITE_CORRUPT | (3<<8))
  1518. #define SQLITE_READONLY_RECOVERY (SQLITE_READONLY | (1<<8))
  1519. #define SQLITE_READONLY_CANTLOCK (SQLITE_READONLY | (2<<8))
  1520. #define SQLITE_READONLY_ROLLBACK (SQLITE_READONLY | (3<<8))
  1521. #define SQLITE_READONLY_DBMOVED (SQLITE_READONLY | (4<<8))
  1522. #define SQLITE_READONLY_CANTINIT (SQLITE_READONLY | (5<<8))
  1523. #define SQLITE_READONLY_DIRECTORY (SQLITE_READONLY | (6<<8))
  1524. #define SQLITE_ABORT_ROLLBACK (SQLITE_ABORT | (2<<8))
  1525. #define SQLITE_CONSTRAINT_CHECK (SQLITE_CONSTRAINT | (1<<8))
  1526. #define SQLITE_CONSTRAINT_COMMITHOOK (SQLITE_CONSTRAINT | (2<<8))
  1527. #define SQLITE_CONSTRAINT_FOREIGNKEY (SQLITE_CONSTRAINT | (3<<8))
  1528. #define SQLITE_CONSTRAINT_FUNCTION (SQLITE_CONSTRAINT | (4<<8))
  1529. #define SQLITE_CONSTRAINT_NOTNULL (SQLITE_CONSTRAINT | (5<<8))
  1530. #define SQLITE_CONSTRAINT_PRIMARYKEY (SQLITE_CONSTRAINT | (6<<8))
  1531. #define SQLITE_CONSTRAINT_TRIGGER (SQLITE_CONSTRAINT | (7<<8))
  1532. #define SQLITE_CONSTRAINT_UNIQUE (SQLITE_CONSTRAINT | (8<<8))
  1533. #define SQLITE_CONSTRAINT_VTAB (SQLITE_CONSTRAINT | (9<<8))
  1534. #define SQLITE_CONSTRAINT_ROWID (SQLITE_CONSTRAINT |(10<<8))
  1535. #define SQLITE_CONSTRAINT_PINNED (SQLITE_CONSTRAINT |(11<<8))
  1536. #define SQLITE_NOTICE_RECOVER_WAL (SQLITE_NOTICE | (1<<8))
  1537. #define SQLITE_NOTICE_RECOVER_ROLLBACK (SQLITE_NOTICE | (2<<8))
  1538. #define SQLITE_WARNING_AUTOINDEX (SQLITE_WARNING | (1<<8))
  1539. #define SQLITE_AUTH_USER (SQLITE_AUTH | (1<<8))
  1540. #define SQLITE_OK_LOAD_PERMANENTLY (SQLITE_OK | (1<<8))
  1541. #define SQLITE_OK_SYMLINK (SQLITE_OK | (2<<8))
  1542. /*
  1543. ** CAPI3REF: Flags For File Open Operations
  1544. **
  1545. ** These bit values are intended for use in the
  1546. ** 3rd parameter to the [sqlite3_open_v2()] interface and
  1547. ** in the 4th parameter to the [sqlite3_vfs.xOpen] method.
  1548. */
  1549. #define SQLITE_OPEN_READONLY 0x00000001 /* Ok for sqlite3_open_v2() */
  1550. #define SQLITE_OPEN_READWRITE 0x00000002 /* Ok for sqlite3_open_v2() */
  1551. #define SQLITE_OPEN_CREATE 0x00000004 /* Ok for sqlite3_open_v2() */
  1552. #define SQLITE_OPEN_DELETEONCLOSE 0x00000008 /* VFS only */
  1553. #define SQLITE_OPEN_EXCLUSIVE 0x00000010 /* VFS only */
  1554. #define SQLITE_OPEN_AUTOPROXY 0x00000020 /* VFS only */
  1555. #define SQLITE_OPEN_URI 0x00000040 /* Ok for sqlite3_open_v2() */
  1556. #define SQLITE_OPEN_MEMORY 0x00000080 /* Ok for sqlite3_open_v2() */
  1557. #define SQLITE_OPEN_MAIN_DB 0x00000100 /* VFS only */
  1558. #define SQLITE_OPEN_TEMP_DB 0x00000200 /* VFS only */
  1559. #define SQLITE_OPEN_TRANSIENT_DB 0x00000400 /* VFS only */
  1560. #define SQLITE_OPEN_MAIN_JOURNAL 0x00000800 /* VFS only */
  1561. #define SQLITE_OPEN_TEMP_JOURNAL 0x00001000 /* VFS only */
  1562. #define SQLITE_OPEN_SUBJOURNAL 0x00002000 /* VFS only */
  1563. #define SQLITE_OPEN_MASTER_JOURNAL 0x00004000 /* VFS only */
  1564. #define SQLITE_OPEN_NOMUTEX 0x00008000 /* Ok for sqlite3_open_v2() */
  1565. #define SQLITE_OPEN_FULLMUTEX 0x00010000 /* Ok for sqlite3_open_v2() */
  1566. #define SQLITE_OPEN_SHAREDCACHE 0x00020000 /* Ok for sqlite3_open_v2() */
  1567. #define SQLITE_OPEN_PRIVATECACHE 0x00040000 /* Ok for sqlite3_open_v2() */
  1568. #define SQLITE_OPEN_WAL 0x00080000 /* VFS only */
  1569. #define SQLITE_OPEN_NOFOLLOW 0x01000000 /* Ok for sqlite3_open_v2() */
  1570. /* Reserved: 0x00F00000 */
  1571. /*
  1572. ** CAPI3REF: Device Characteristics
  1573. **
  1574. ** The xDeviceCharacteristics method of the [sqlite3_io_methods]
  1575. ** object returns an integer which is a vector of these
  1576. ** bit values expressing I/O characteristics of the mass storage
  1577. ** device that holds the file that the [sqlite3_io_methods]
  1578. ** refers to.
  1579. **
  1580. ** The SQLITE_IOCAP_ATOMIC property means that all writes of
  1581. ** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values
  1582. ** mean that writes of blocks that are nnn bytes in size and
  1583. ** are aligned to an address which is an integer multiple of
  1584. ** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means
  1585. ** that when data is appended to a file, the data is appended
  1586. ** first then the size of the file is extended, never the other
  1587. ** way around. The SQLITE_IOCAP_SEQUENTIAL property means that
  1588. ** information is written to disk in the same order as calls
  1589. ** to xWrite(). The SQLITE_IOCAP_POWERSAFE_OVERWRITE property means that
  1590. ** after reboot following a crash or power loss, the only bytes in a
  1591. ** file that were written at the application level might have changed
  1592. ** and that adjacent bytes, even bytes within the same sector are
  1593. ** guaranteed to be unchanged. The SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
  1594. ** flag indicates that a file cannot be deleted when open. The
  1595. ** SQLITE_IOCAP_IMMUTABLE flag indicates that the file is on
  1596. ** read-only media and cannot be changed even by processes with
  1597. ** elevated privileges.
  1598. **
  1599. ** The SQLITE_IOCAP_BATCH_ATOMIC property means that the underlying
  1600. ** filesystem supports doing multiple write operations atomically when those
  1601. ** write operations are bracketed by [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] and
  1602. ** [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE].
  1603. */
  1604. #define SQLITE_IOCAP_ATOMIC 0x00000001
  1605. #define SQLITE_IOCAP_ATOMIC512 0x00000002
  1606. #define SQLITE_IOCAP_ATOMIC1K 0x00000004
  1607. #define SQLITE_IOCAP_ATOMIC2K 0x00000008
  1608. #define SQLITE_IOCAP_ATOMIC4K 0x00000010
  1609. #define SQLITE_IOCAP_ATOMIC8K 0x00000020
  1610. #define SQLITE_IOCAP_ATOMIC16K 0x00000040
  1611. #define SQLITE_IOCAP_ATOMIC32K 0x00000080
  1612. #define SQLITE_IOCAP_ATOMIC64K 0x00000100
  1613. #define SQLITE_IOCAP_SAFE_APPEND 0x00000200
  1614. #define SQLITE_IOCAP_SEQUENTIAL 0x00000400
  1615. #define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN 0x00000800
  1616. #define SQLITE_IOCAP_POWERSAFE_OVERWRITE 0x00001000
  1617. #define SQLITE_IOCAP_IMMUTABLE 0x00002000
  1618. #define SQLITE_IOCAP_BATCH_ATOMIC 0x00004000
  1619. /*
  1620. ** CAPI3REF: File Locking Levels
  1621. **
  1622. ** SQLite uses one of these integer values as the second
  1623. ** argument to calls it makes to the xLock() and xUnlock() methods
  1624. ** of an [sqlite3_io_methods] object.
  1625. */
  1626. #define SQLITE_LOCK_NONE 0
  1627. #define SQLITE_LOCK_SHARED 1
  1628. #define SQLITE_LOCK_RESERVED 2
  1629. #define SQLITE_LOCK_PENDING 3
  1630. #define SQLITE_LOCK_EXCLUSIVE 4
  1631. /*
  1632. ** CAPI3REF: Synchronization Type Flags
  1633. **
  1634. ** When SQLite invokes the xSync() method of an
  1635. ** [sqlite3_io_methods] object it uses a combination of
  1636. ** these integer values as the second argument.
  1637. **
  1638. ** When the SQLITE_SYNC_DATAONLY flag is used, it means that the
  1639. ** sync operation only needs to flush data to mass storage. Inode
  1640. ** information need not be flushed. If the lower four bits of the flag
  1641. ** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics.
  1642. ** If the lower four bits equal SQLITE_SYNC_FULL, that means
  1643. ** to use Mac OS X style fullsync instead of fsync().
  1644. **
  1645. ** Do not confuse the SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags
  1646. ** with the [PRAGMA synchronous]=NORMAL and [PRAGMA synchronous]=FULL
  1647. ** settings. The [synchronous pragma] determines when calls to the
  1648. ** xSync VFS method occur and applies uniformly across all platforms.
  1649. ** The SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags determine how
  1650. ** energetic or rigorous or forceful the sync operations are and
  1651. ** only make a difference on Mac OSX for the default SQLite code.
  1652. ** (Third-party VFS implementations might also make the distinction
  1653. ** between SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL, but among the
  1654. ** operating systems natively supported by SQLite, only Mac OSX
  1655. ** cares about the difference.)
  1656. */
  1657. #define SQLITE_SYNC_NORMAL 0x00002
  1658. #define SQLITE_SYNC_FULL 0x00003
  1659. #define SQLITE_SYNC_DATAONLY 0x00010
  1660. /*
  1661. ** CAPI3REF: OS Interface Open File Handle
  1662. **
  1663. ** An [sqlite3_file] object represents an open file in the
  1664. ** [sqlite3_vfs | OS interface layer]. Individual OS interface
  1665. ** implementations will
  1666. ** want to subclass this object by appending additional fields
  1667. ** for their own use. The pMethods entry is a pointer to an
  1668. ** [sqlite3_io_methods] object that defines methods for performing
  1669. ** I/O operations on the open file.
  1670. */
  1671. typedef struct sqlite3_file sqlite3_file;
  1672. struct sqlite3_file {
  1673. const struct sqlite3_io_methods *pMethods; /* Methods for an open file */
  1674. };
  1675. /*
  1676. ** CAPI3REF: OS Interface File Virtual Methods Object
  1677. **
  1678. ** Every file opened by the [sqlite3_vfs.xOpen] method populates an
  1679. ** [sqlite3_file] object (or, more commonly, a subclass of the
  1680. ** [sqlite3_file] object) with a pointer to an instance of this object.
  1681. ** This object defines the methods used to perform various operations
  1682. ** against the open file represented by the [sqlite3_file] object.
  1683. **
  1684. ** If the [sqlite3_vfs.xOpen] method sets the sqlite3_file.pMethods element
  1685. ** to a non-NULL pointer, then the sqlite3_io_methods.xClose method
  1686. ** may be invoked even if the [sqlite3_vfs.xOpen] reported that it failed. The
  1687. ** only way to prevent a call to xClose following a failed [sqlite3_vfs.xOpen]
  1688. ** is for the [sqlite3_vfs.xOpen] to set the sqlite3_file.pMethods element
  1689. ** to NULL.
  1690. **
  1691. ** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
  1692. ** [SQLITE_SYNC_FULL]. The first choice is the normal fsync().
  1693. ** The second choice is a Mac OS X style fullsync. The [SQLITE_SYNC_DATAONLY]
  1694. ** flag may be ORed in to indicate that only the data of the file
  1695. ** and not its inode needs to be synced.
  1696. **
  1697. ** The integer values to xLock() and xUnlock() are one of
  1698. ** <ul>
  1699. ** <li> [SQLITE_LOCK_NONE],
  1700. ** <li> [SQLITE_LOCK_SHARED],
  1701. ** <li> [SQLITE_LOCK_RESERVED],
  1702. ** <li> [SQLITE_LOCK_PENDING], or
  1703. ** <li> [SQLITE_LOCK_EXCLUSIVE].
  1704. ** </ul>
  1705. ** xLock() increases the lock. xUnlock() decreases the lock.
  1706. ** The xCheckReservedLock() method checks whether any database connection,
  1707. ** either in this process or in some other process, is holding a RESERVED,
  1708. ** PENDING, or EXCLUSIVE lock on the file. It returns true
  1709. ** if such a lock exists and false otherwise.
  1710. **
  1711. ** The xFileControl() method is a generic interface that allows custom
  1712. ** VFS implementations to directly control an open file using the
  1713. ** [sqlite3_file_control()] interface. The second "op" argument is an
  1714. ** integer opcode. The third argument is a generic pointer intended to
  1715. ** point to a structure that may contain arguments or space in which to
  1716. ** write return values. Potential uses for xFileControl() might be
  1717. ** functions to enable blocking locks with timeouts, to change the
  1718. ** locking strategy (for example to use dot-file locks), to inquire
  1719. ** about the status of a lock, or to break stale locks. The SQLite
  1720. ** core reserves all opcodes less than 100 for its own use.
  1721. ** A [file control opcodes | list of opcodes] less than 100 is available.
  1722. ** Applications that define a custom xFileControl method should use opcodes
  1723. ** greater than 100 to avoid conflicts. VFS implementations should
  1724. ** return [SQLITE_NOTFOUND] for file control opcodes that they do not
  1725. ** recognize.
  1726. **
  1727. ** The xSectorSize() method returns the sector size of the
  1728. ** device that underlies the file. The sector size is the
  1729. ** minimum write that can be performed without disturbing
  1730. ** other bytes in the file. The xDeviceCharacteristics()
  1731. ** method returns a bit vector describing behaviors of the
  1732. ** underlying device:
  1733. **
  1734. ** <ul>
  1735. ** <li> [SQLITE_IOCAP_ATOMIC]
  1736. ** <li> [SQLITE_IOCAP_ATOMIC512]
  1737. ** <li> [SQLITE_IOCAP_ATOMIC1K]
  1738. ** <li> [SQLITE_IOCAP_ATOMIC2K]
  1739. ** <li> [SQLITE_IOCAP_ATOMIC4K]
  1740. ** <li> [SQLITE_IOCAP_ATOMIC8K]
  1741. ** <li> [SQLITE_IOCAP_ATOMIC16K]
  1742. ** <li> [SQLITE_IOCAP_ATOMIC32K]
  1743. ** <li> [SQLITE_IOCAP_ATOMIC64K]
  1744. ** <li> [SQLITE_IOCAP_SAFE_APPEND]
  1745. ** <li> [SQLITE_IOCAP_SEQUENTIAL]
  1746. ** <li> [SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN]
  1747. ** <li> [SQLITE_IOCAP_POWERSAFE_OVERWRITE]
  1748. ** <li> [SQLITE_IOCAP_IMMUTABLE]
  1749. ** <li> [SQLITE_IOCAP_BATCH_ATOMIC]
  1750. ** </ul>
  1751. **
  1752. ** The SQLITE_IOCAP_ATOMIC property means that all writes of
  1753. ** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values
  1754. ** mean that writes of blocks that are nnn bytes in size and
  1755. ** are aligned to an address which is an integer multiple of
  1756. ** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means
  1757. ** that when data is appended to a file, the data is appended
  1758. ** first then the size of the file is extended, never the other
  1759. ** way around. The SQLITE_IOCAP_SEQUENTIAL property means that
  1760. ** information is written to disk in the same order as calls
  1761. ** to xWrite().
  1762. **
  1763. ** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill
  1764. ** in the unread portions of the buffer with zeros. A VFS that
  1765. ** fails to zero-fill short reads might seem to work. However,
  1766. ** failure to zero-fill short reads will eventually lead to
  1767. ** database corruption.
  1768. */
  1769. typedef struct sqlite3_io_methods sqlite3_io_methods;
  1770. struct sqlite3_io_methods {
  1771. int iVersion;
  1772. int (*xClose)(sqlite3_file*);
  1773. int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
  1774. int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
  1775. int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
  1776. int (*xSync)(sqlite3_file*, int flags);
  1777. int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
  1778. int (*xLock)(sqlite3_file*, int);
  1779. int (*xUnlock)(sqlite3_file*, int);
  1780. int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);
  1781. int (*xFileControl)(sqlite3_file*, int op, void *pArg);
  1782. int (*xSectorSize)(sqlite3_file*);
  1783. int (*xDeviceCharacteristics)(sqlite3_file*);
  1784. /* Methods above are valid for version 1 */
  1785. int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
  1786. int (*xShmLock)(sqlite3_file*, int offset, int n, int flags);
  1787. void (*xShmBarrier)(sqlite3_file*);
  1788. int (*xShmUnmap)(sqlite3_file*, int deleteFlag);
  1789. /* Methods above are valid for version 2 */
  1790. int (*xFetch)(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp);
  1791. int (*xUnfetch)(sqlite3_file*, sqlite3_int64 iOfst, void *p);
  1792. /* Methods above are valid for version 3 */
  1793. /* Additional methods may be added in future releases */
  1794. };
  1795. /*
  1796. ** CAPI3REF: Standard File Control Opcodes
  1797. ** KEYWORDS: {file control opcodes} {file control opcode}
  1798. **
  1799. ** These integer constants are opcodes for the xFileControl method
  1800. ** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]
  1801. ** interface.
  1802. **
  1803. ** <ul>
  1804. ** <li>[[SQLITE_FCNTL_LOCKSTATE]]
  1805. ** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging. This
  1806. ** opcode causes the xFileControl method to write the current state of
  1807. ** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
  1808. ** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
  1809. ** into an integer that the pArg argument points to. This capability
  1810. ** is used during testing and is only available when the SQLITE_TEST
  1811. ** compile-time option is used.
  1812. **
  1813. ** <li>[[SQLITE_FCNTL_SIZE_HINT]]
  1814. ** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS
  1815. ** layer a hint of how large the database file will grow to be during the
  1816. ** current transaction. This hint is not guaranteed to be accurate but it
  1817. ** is often close. The underlying VFS might choose to preallocate database
  1818. ** file space based on this hint in order to help writes to the database
  1819. ** file run faster.
  1820. **
  1821. ** <li>[[SQLITE_FCNTL_SIZE_LIMIT]]
  1822. ** The [SQLITE_FCNTL_SIZE_LIMIT] opcode is used by in-memory VFS that
  1823. ** implements [sqlite3_deserialize()] to set an upper bound on the size
  1824. ** of the in-memory database. The argument is a pointer to a [sqlite3_int64].
  1825. ** If the integer pointed to is negative, then it is filled in with the
  1826. ** current limit. Otherwise the limit is set to the larger of the value
  1827. ** of the integer pointed to and the current database size. The integer
  1828. ** pointed to is set to the new limit.
  1829. **
  1830. ** <li>[[SQLITE_FCNTL_CHUNK_SIZE]]
  1831. ** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS
  1832. ** extends and truncates the database file in chunks of a size specified
  1833. ** by the user. The fourth argument to [sqlite3_file_control()] should
  1834. ** point to an integer (type int) containing the new chunk-size to use
  1835. ** for the nominated database. Allocating database file space in large
  1836. ** chunks (say 1MB at a time), may reduce file-system fragmentation and
  1837. ** improve performance on some systems.
  1838. **
  1839. ** <li>[[SQLITE_FCNTL_FILE_POINTER]]
  1840. ** The [SQLITE_FCNTL_FILE_POINTER] opcode is used to obtain a pointer
  1841. ** to the [sqlite3_file] object associated with a particular database
  1842. ** connection. See also [SQLITE_FCNTL_JOURNAL_POINTER].
  1843. **
  1844. ** <li>[[SQLITE_FCNTL_JOURNAL_POINTER]]
  1845. ** The [SQLITE_FCNTL_JOURNAL_POINTER] opcode is used to obtain a pointer
  1846. ** to the [sqlite3_file] object associated with the journal file (either
  1847. ** the [rollback journal] or the [write-ahead log]) for a particular database
  1848. ** connection. See also [SQLITE_FCNTL_FILE_POINTER].
  1849. **
  1850. ** <li>[[SQLITE_FCNTL_SYNC_OMITTED]]
  1851. ** No longer in use.
  1852. **
  1853. ** <li>[[SQLITE_FCNTL_SYNC]]
  1854. ** The [SQLITE_FCNTL_SYNC] opcode is generated internally by SQLite and
  1855. ** sent to the VFS immediately before the xSync method is invoked on a
  1856. ** database file descriptor. Or, if the xSync method is not invoked
  1857. ** because the user has configured SQLite with
  1858. ** [PRAGMA synchronous | PRAGMA synchronous=OFF] it is invoked in place
  1859. ** of the xSync method. In most cases, the pointer argument passed with
  1860. ** this file-control is NULL. However, if the database file is being synced
  1861. ** as part of a multi-database commit, the argument points to a nul-terminated
  1862. ** string containing the transactions master-journal file name. VFSes that
  1863. ** do not need this signal should silently ignore this opcode. Applications
  1864. ** should not call [sqlite3_file_control()] with this opcode as doing so may
  1865. ** disrupt the operation of the specialized VFSes that do require it.
  1866. **
  1867. ** <li>[[SQLITE_FCNTL_COMMIT_PHASETWO]]
  1868. ** The [SQLITE_FCNTL_COMMIT_PHASETWO] opcode is generated internally by SQLite
  1869. ** and sent to the VFS after a transaction has been committed immediately
  1870. ** but before the database is unlocked. VFSes that do not need this signal
  1871. ** should silently ignore this opcode. Applications should not call
  1872. ** [sqlite3_file_control()] with this opcode as doing so may disrupt the
  1873. ** operation of the specialized VFSes that do require it.
  1874. **
  1875. ** <li>[[SQLITE_FCNTL_WIN32_AV_RETRY]]
  1876. ** ^The [SQLITE_FCNTL_WIN32_AV_RETRY] opcode is used to configure automatic
  1877. ** retry counts and intervals for certain disk I/O operations for the
  1878. ** windows [VFS] in order to provide robustness in the presence of
  1879. ** anti-virus programs. By default, the windows VFS will retry file read,
  1880. ** file write, and file delete operations up to 10 times, with a delay
  1881. ** of 25 milliseconds before the first retry and with the delay increasing
  1882. ** by an additional 25 milliseconds with each subsequent retry. This
  1883. ** opcode allows these two values (10 retries and 25 milliseconds of delay)
  1884. ** to be adjusted. The values are changed for all database connections
  1885. ** within the same process. The argument is a pointer to an array of two
  1886. ** integers where the first integer is the new retry count and the second
  1887. ** integer is the delay. If either integer is negative, then the setting
  1888. ** is not changed but instead the prior value of that setting is written
  1889. ** into the array entry, allowing the current retry settings to be
  1890. ** interrogated. The zDbName parameter is ignored.
  1891. **
  1892. ** <li>[[SQLITE_FCNTL_PERSIST_WAL]]
  1893. ** ^The [SQLITE_FCNTL_PERSIST_WAL] opcode is used to set or query the
  1894. ** persistent [WAL | Write Ahead Log] setting. By default, the auxiliary
  1895. ** write ahead log ([WAL file]) and shared memory
  1896. ** files used for transaction control
  1897. ** are automatically deleted when the latest connection to the database
  1898. ** closes. Setting persistent WAL mode causes those files to persist after
  1899. ** close. Persisting the files is useful when other processes that do not
  1900. ** have write permission on the directory containing the database file want
  1901. ** to read the database file, as the WAL and shared memory files must exist
  1902. ** in order for the database to be readable. The fourth parameter to
  1903. ** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
  1904. ** That integer is 0 to disable persistent WAL mode or 1 to enable persistent
  1905. ** WAL mode. If the integer is -1, then it is overwritten with the current
  1906. ** WAL persistence setting.
  1907. **
  1908. ** <li>[[SQLITE_FCNTL_POWERSAFE_OVERWRITE]]
  1909. ** ^The [SQLITE_FCNTL_POWERSAFE_OVERWRITE] opcode is used to set or query the
  1910. ** persistent "powersafe-overwrite" or "PSOW" setting. The PSOW setting
  1911. ** determines the [SQLITE_IOCAP_POWERSAFE_OVERWRITE] bit of the
  1912. ** xDeviceCharacteristics methods. The fourth parameter to
  1913. ** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
  1914. ** That integer is 0 to disable zero-damage mode or 1 to enable zero-damage
  1915. ** mode. If the integer is -1, then it is overwritten with the current
  1916. ** zero-damage mode setting.
  1917. **
  1918. ** <li>[[SQLITE_FCNTL_OVERWRITE]]
  1919. ** ^The [SQLITE_FCNTL_OVERWRITE] opcode is invoked by SQLite after opening
  1920. ** a write transaction to indicate that, unless it is rolled back for some
  1921. ** reason, the entire database file will be overwritten by the current
  1922. ** transaction. This is used by VACUUM operations.
  1923. **
  1924. ** <li>[[SQLITE_FCNTL_VFSNAME]]
  1925. ** ^The [SQLITE_FCNTL_VFSNAME] opcode can be used to obtain the names of
  1926. ** all [VFSes] in the VFS stack. The names are of all VFS shims and the
  1927. ** final bottom-level VFS are written into memory obtained from
  1928. ** [sqlite3_malloc()] and the result is stored in the char* variable
  1929. ** that the fourth parameter of [sqlite3_file_control()] points to.
  1930. ** The caller is responsible for freeing the memory when done. As with
  1931. ** all file-control actions, there is no guarantee that this will actually
  1932. ** do anything. Callers should initialize the char* variable to a NULL
  1933. ** pointer in case this file-control is not implemented. This file-control
  1934. ** is intended for diagnostic use only.
  1935. **
  1936. ** <li>[[SQLITE_FCNTL_VFS_POINTER]]
  1937. ** ^The [SQLITE_FCNTL_VFS_POINTER] opcode finds a pointer to the top-level
  1938. ** [VFSes] currently in use. ^(The argument X in
  1939. ** sqlite3_file_control(db,SQLITE_FCNTL_VFS_POINTER,X) must be
  1940. ** of type "[sqlite3_vfs] **". This opcodes will set *X
  1941. ** to a pointer to the top-level VFS.)^
  1942. ** ^When there are multiple VFS shims in the stack, this opcode finds the
  1943. ** upper-most shim only.
  1944. **
  1945. ** <li>[[SQLITE_FCNTL_PRAGMA]]
  1946. ** ^Whenever a [PRAGMA] statement is parsed, an [SQLITE_FCNTL_PRAGMA]
  1947. ** file control is sent to the open [sqlite3_file] object corresponding
  1948. ** to the database file to which the pragma statement refers. ^The argument
  1949. ** to the [SQLITE_FCNTL_PRAGMA] file control is an array of
  1950. ** pointers to strings (char**) in which the second element of the array
  1951. ** is the name of the pragma and the third element is the argument to the
  1952. ** pragma or NULL if the pragma has no argument. ^The handler for an
  1953. ** [SQLITE_FCNTL_PRAGMA] file control can optionally make the first element
  1954. ** of the char** argument point to a string obtained from [sqlite3_mprintf()]
  1955. ** or the equivalent and that string will become the result of the pragma or
  1956. ** the error message if the pragma fails. ^If the
  1957. ** [SQLITE_FCNTL_PRAGMA] file control returns [SQLITE_NOTFOUND], then normal
  1958. ** [PRAGMA] processing continues. ^If the [SQLITE_FCNTL_PRAGMA]
  1959. ** file control returns [SQLITE_OK], then the parser assumes that the
  1960. ** VFS has handled the PRAGMA itself and the parser generates a no-op
  1961. ** prepared statement if result string is NULL, or that returns a copy
  1962. ** of the result string if the string is non-NULL.
  1963. ** ^If the [SQLITE_FCNTL_PRAGMA] file control returns
  1964. ** any result code other than [SQLITE_OK] or [SQLITE_NOTFOUND], that means
  1965. ** that the VFS encountered an error while handling the [PRAGMA] and the
  1966. ** compilation of the PRAGMA fails with an error. ^The [SQLITE_FCNTL_PRAGMA]
  1967. ** file control occurs at the beginning of pragma statement analysis and so
  1968. ** it is able to override built-in [PRAGMA] statements.
  1969. **
  1970. ** <li>[[SQLITE_FCNTL_BUSYHANDLER]]
  1971. ** ^The [SQLITE_FCNTL_BUSYHANDLER]
  1972. ** file-control may be invoked by SQLite on the database file handle
  1973. ** shortly after it is opened in order to provide a custom VFS with access
  1974. ** to the connection's busy-handler callback. The argument is of type (void**)
  1975. ** - an array of two (void *) values. The first (void *) actually points
  1976. ** to a function of type (int (*)(void *)). In order to invoke the connection's
  1977. ** busy-handler, this function should be invoked with the second (void *) in
  1978. ** the array as the only argument. If it returns non-zero, then the operation
  1979. ** should be retried. If it returns zero, the custom VFS should abandon the
  1980. ** current operation.
  1981. **
  1982. ** <li>[[SQLITE_FCNTL_TEMPFILENAME]]
  1983. ** ^Applications can invoke the [SQLITE_FCNTL_TEMPFILENAME] file-control
  1984. ** to have SQLite generate a
  1985. ** temporary filename using the same algorithm that is followed to generate
  1986. ** temporary filenames for TEMP tables and other internal uses. The
  1987. ** argument should be a char** which will be filled with the filename
  1988. ** written into memory obtained from [sqlite3_malloc()]. The caller should
  1989. ** invoke [sqlite3_free()] on the result to avoid a memory leak.
  1990. **
  1991. ** <li>[[SQLITE_FCNTL_MMAP_SIZE]]
  1992. ** The [SQLITE_FCNTL_MMAP_SIZE] file control is used to query or set the
  1993. ** maximum number of bytes that will be used for memory-mapped I/O.
  1994. ** The argument is a pointer to a value of type sqlite3_int64 that
  1995. ** is an advisory maximum number of bytes in the file to memory map. The
  1996. ** pointer is overwritten with the old value. The limit is not changed if
  1997. ** the value originally pointed to is negative, and so the current limit
  1998. ** can be queried by passing in a pointer to a negative number. This
  1999. ** file-control is used internally to implement [PRAGMA mmap_size].
  2000. **
  2001. ** <li>[[SQLITE_FCNTL_TRACE]]
  2002. ** The [SQLITE_FCNTL_TRACE] file control provides advisory information
  2003. ** to the VFS about what the higher layers of the SQLite stack are doing.
  2004. ** This file control is used by some VFS activity tracing [shims].
  2005. ** The argument is a zero-terminated string. Higher layers in the
  2006. ** SQLite stack may generate instances of this file control if
  2007. ** the [SQLITE_USE_FCNTL_TRACE] compile-time option is enabled.
  2008. **
  2009. ** <li>[[SQLITE_FCNTL_HAS_MOVED]]
  2010. ** The [SQLITE_FCNTL_HAS_MOVED] file control interprets its argument as a
  2011. ** pointer to an integer and it writes a boolean into that integer depending
  2012. ** on whether or not the file has been renamed, moved, or deleted since it
  2013. ** was first opened.
  2014. **
  2015. ** <li>[[SQLITE_FCNTL_WIN32_GET_HANDLE]]
  2016. ** The [SQLITE_FCNTL_WIN32_GET_HANDLE] opcode can be used to obtain the
  2017. ** underlying native file handle associated with a file handle. This file
  2018. ** control interprets its argument as a pointer to a native file handle and
  2019. ** writes the resulting value there.
  2020. **
  2021. ** <li>[[SQLITE_FCNTL_WIN32_SET_HANDLE]]
  2022. ** The [SQLITE_FCNTL_WIN32_SET_HANDLE] opcode is used for debugging. This
  2023. ** opcode causes the xFileControl method to swap the file handle with the one
  2024. ** pointed to by the pArg argument. This capability is used during testing
  2025. ** and only needs to be supported when SQLITE_TEST is defined.
  2026. **
  2027. ** <li>[[SQLITE_FCNTL_WAL_BLOCK]]
  2028. ** The [SQLITE_FCNTL_WAL_BLOCK] is a signal to the VFS layer that it might
  2029. ** be advantageous to block on the next WAL lock if the lock is not immediately
  2030. ** available. The WAL subsystem issues this signal during rare
  2031. ** circumstances in order to fix a problem with priority inversion.
  2032. ** Applications should <em>not</em> use this file-control.
  2033. **
  2034. ** <li>[[SQLITE_FCNTL_ZIPVFS]]
  2035. ** The [SQLITE_FCNTL_ZIPVFS] opcode is implemented by zipvfs only. All other
  2036. ** VFS should return SQLITE_NOTFOUND for this opcode.
  2037. **
  2038. ** <li>[[SQLITE_FCNTL_RBU]]
  2039. ** The [SQLITE_FCNTL_RBU] opcode is implemented by the special VFS used by
  2040. ** the RBU extension only. All other VFS should return SQLITE_NOTFOUND for
  2041. ** this opcode.
  2042. **
  2043. ** <li>[[SQLITE_FCNTL_BEGIN_ATOMIC_WRITE]]
  2044. ** If the [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] opcode returns SQLITE_OK, then
  2045. ** the file descriptor is placed in "batch write mode", which
  2046. ** means all subsequent write operations will be deferred and done
  2047. ** atomically at the next [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE]. Systems
  2048. ** that do not support batch atomic writes will return SQLITE_NOTFOUND.
  2049. ** ^Following a successful SQLITE_FCNTL_BEGIN_ATOMIC_WRITE and prior to
  2050. ** the closing [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE] or
  2051. ** [SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE], SQLite will make
  2052. ** no VFS interface calls on the same [sqlite3_file] file descriptor
  2053. ** except for calls to the xWrite method and the xFileControl method
  2054. ** with [SQLITE_FCNTL_SIZE_HINT].
  2055. **
  2056. ** <li>[[SQLITE_FCNTL_COMMIT_ATOMIC_WRITE]]
  2057. ** The [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE] opcode causes all write
  2058. ** operations since the previous successful call to
  2059. ** [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] to be performed atomically.
  2060. ** This file control returns [SQLITE_OK] if and only if the writes were
  2061. ** all performed successfully and have been committed to persistent storage.
  2062. ** ^Regardless of whether or not it is successful, this file control takes
  2063. ** the file descriptor out of batch write mode so that all subsequent
  2064. ** write operations are independent.
  2065. ** ^SQLite will never invoke SQLITE_FCNTL_COMMIT_ATOMIC_WRITE without
  2066. ** a prior successful call to [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE].
  2067. **
  2068. ** <li>[[SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE]]
  2069. ** The [SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE] opcode causes all write
  2070. ** operations since the previous successful call to
  2071. ** [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] to be rolled back.
  2072. ** ^This file control takes the file descriptor out of batch write mode
  2073. ** so that all subsequent write operations are independent.
  2074. ** ^SQLite will never invoke SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE without
  2075. ** a prior successful call to [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE].
  2076. **
  2077. ** <li>[[SQLITE_FCNTL_LOCK_TIMEOUT]]
  2078. ** The [SQLITE_FCNTL_LOCK_TIMEOUT] opcode is used to configure a VFS
  2079. ** to block for up to M milliseconds before failing when attempting to
  2080. ** obtain a file lock using the xLock or xShmLock methods of the VFS.
  2081. ** The parameter is a pointer to a 32-bit signed integer that contains
  2082. ** the value that M is to be set to. Before returning, the 32-bit signed
  2083. ** integer is overwritten with the previous value of M.
  2084. **
  2085. ** <li>[[SQLITE_FCNTL_DATA_VERSION]]
  2086. ** The [SQLITE_FCNTL_DATA_VERSION] opcode is used to detect changes to
  2087. ** a database file. The argument is a pointer to a 32-bit unsigned integer.
  2088. ** The "data version" for the pager is written into the pointer. The
  2089. ** "data version" changes whenever any change occurs to the corresponding
  2090. ** database file, either through SQL statements on the same database
  2091. ** connection or through transactions committed by separate database
  2092. ** connections possibly in other processes. The [sqlite3_total_changes()]
  2093. ** interface can be used to find if any database on the connection has changed,
  2094. ** but that interface responds to changes on TEMP as well as MAIN and does
  2095. ** not provide a mechanism to detect changes to MAIN only. Also, the
  2096. ** [sqlite3_total_changes()] interface responds to internal changes only and
  2097. ** omits changes made by other database connections. The
  2098. ** [PRAGMA data_version] command provides a mechanism to detect changes to
  2099. ** a single attached database that occur due to other database connections,
  2100. ** but omits changes implemented by the database connection on which it is
  2101. ** called. This file control is the only mechanism to detect changes that
  2102. ** happen either internally or externally and that are associated with
  2103. ** a particular attached database.
  2104. **
  2105. ** <li>[[SQLITE_FCNTL_CKPT_START]]
  2106. ** The [SQLITE_FCNTL_CKPT_START] opcode is invoked from within a checkpoint
  2107. ** in wal mode before the client starts to copy pages from the wal
  2108. ** file to the database file.
  2109. **
  2110. ** <li>[[SQLITE_FCNTL_CKPT_DONE]]
  2111. ** The [SQLITE_FCNTL_CKPT_DONE] opcode is invoked from within a checkpoint
  2112. ** in wal mode after the client has finished copying pages from the wal
  2113. ** file to the database file, but before the *-shm file is updated to
  2114. ** record the fact that the pages have been checkpointed.
  2115. ** </ul>
  2116. */
  2117. #define SQLITE_FCNTL_LOCKSTATE 1
  2118. #define SQLITE_FCNTL_GET_LOCKPROXYFILE 2
  2119. #define SQLITE_FCNTL_SET_LOCKPROXYFILE 3
  2120. #define SQLITE_FCNTL_LAST_ERRNO 4
  2121. #define SQLITE_FCNTL_SIZE_HINT 5
  2122. #define SQLITE_FCNTL_CHUNK_SIZE 6
  2123. #define SQLITE_FCNTL_FILE_POINTER 7
  2124. #define SQLITE_FCNTL_SYNC_OMITTED 8
  2125. #define SQLITE_FCNTL_WIN32_AV_RETRY 9
  2126. #define SQLITE_FCNTL_PERSIST_WAL 10
  2127. #define SQLITE_FCNTL_OVERWRITE 11
  2128. #define SQLITE_FCNTL_VFSNAME 12
  2129. #define SQLITE_FCNTL_POWERSAFE_OVERWRITE 13
  2130. #define SQLITE_FCNTL_PRAGMA 14
  2131. #define SQLITE_FCNTL_BUSYHANDLER 15
  2132. #define SQLITE_FCNTL_TEMPFILENAME 16
  2133. #define SQLITE_FCNTL_MMAP_SIZE 18
  2134. #define SQLITE_FCNTL_TRACE 19
  2135. #define SQLITE_FCNTL_HAS_MOVED 20
  2136. #define SQLITE_FCNTL_SYNC 21
  2137. #define SQLITE_FCNTL_COMMIT_PHASETWO 22
  2138. #define SQLITE_FCNTL_WIN32_SET_HANDLE 23
  2139. #define SQLITE_FCNTL_WAL_BLOCK 24
  2140. #define SQLITE_FCNTL_ZIPVFS 25
  2141. #define SQLITE_FCNTL_RBU 26
  2142. #define SQLITE_FCNTL_VFS_POINTER 27
  2143. #define SQLITE_FCNTL_JOURNAL_POINTER 28
  2144. #define SQLITE_FCNTL_WIN32_GET_HANDLE 29
  2145. #define SQLITE_FCNTL_PDB 30
  2146. #define SQLITE_FCNTL_BEGIN_ATOMIC_WRITE 31
  2147. #define SQLITE_FCNTL_COMMIT_ATOMIC_WRITE 32
  2148. #define SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE 33
  2149. #define SQLITE_FCNTL_LOCK_TIMEOUT 34
  2150. #define SQLITE_FCNTL_DATA_VERSION 35
  2151. #define SQLITE_FCNTL_SIZE_LIMIT 36
  2152. #define SQLITE_FCNTL_CKPT_DONE 37
  2153. #define SQLITE_FCNTL_RESERVE_BYTES 38
  2154. #define SQLITE_FCNTL_CKPT_START 39
  2155. /* deprecated names */
  2156. #define SQLITE_GET_LOCKPROXYFILE SQLITE_FCNTL_GET_LOCKPROXYFILE
  2157. #define SQLITE_SET_LOCKPROXYFILE SQLITE_FCNTL_SET_LOCKPROXYFILE
  2158. #define SQLITE_LAST_ERRNO SQLITE_FCNTL_LAST_ERRNO
  2159. /*
  2160. ** CAPI3REF: Mutex Handle
  2161. **
  2162. ** The mutex module within SQLite defines [sqlite3_mutex] to be an
  2163. ** abstract type for a mutex object. The SQLite core never looks
  2164. ** at the internal representation of an [sqlite3_mutex]. It only
  2165. ** deals with pointers to the [sqlite3_mutex] object.
  2166. **
  2167. ** Mutexes are created using [sqlite3_mutex_alloc()].
  2168. */
  2169. typedef struct sqlite3_mutex sqlite3_mutex;
  2170. /*
  2171. ** CAPI3REF: Loadable Extension Thunk
  2172. **
  2173. ** A pointer to the opaque sqlite3_api_routines structure is passed as
  2174. ** the third parameter to entry points of [loadable extensions]. This
  2175. ** structure must be typedefed in order to work around compiler warnings
  2176. ** on some platforms.
  2177. */
  2178. typedef struct sqlite3_api_routines sqlite3_api_routines;
  2179. /*
  2180. ** CAPI3REF: OS Interface Object
  2181. **
  2182. ** An instance of the sqlite3_vfs object defines the interface between
  2183. ** the SQLite core and the underlying operating system. The "vfs"
  2184. ** in the name of the object stands for "virtual file system". See
  2185. ** the [VFS | VFS documentation] for further information.
  2186. **
  2187. ** The VFS interface is sometimes extended by adding new methods onto
  2188. ** the end. Each time such an extension occurs, the iVersion field
  2189. ** is incremented. The iVersion value started out as 1 in
  2190. ** SQLite [version 3.5.0] on [dateof:3.5.0], then increased to 2
  2191. ** with SQLite [version 3.7.0] on [dateof:3.7.0], and then increased
  2192. ** to 3 with SQLite [version 3.7.6] on [dateof:3.7.6]. Additional fields
  2193. ** may be appended to the sqlite3_vfs object and the iVersion value
  2194. ** may increase again in future versions of SQLite.
  2195. ** Note that due to an oversight, the structure
  2196. ** of the sqlite3_vfs object changed in the transition from
  2197. ** SQLite [version 3.5.9] to [version 3.6.0] on [dateof:3.6.0]
  2198. ** and yet the iVersion field was not increased.
  2199. **
  2200. ** The szOsFile field is the size of the subclassed [sqlite3_file]
  2201. ** structure used by this VFS. mxPathname is the maximum length of
  2202. ** a pathname in this VFS.
  2203. **
  2204. ** Registered sqlite3_vfs objects are kept on a linked list formed by
  2205. ** the pNext pointer. The [sqlite3_vfs_register()]
  2206. ** and [sqlite3_vfs_unregister()] interfaces manage this list
  2207. ** in a thread-safe way. The [sqlite3_vfs_find()] interface
  2208. ** searches the list. Neither the application code nor the VFS
  2209. ** implementation should use the pNext pointer.
  2210. **
  2211. ** The pNext field is the only field in the sqlite3_vfs
  2212. ** structure that SQLite will ever modify. SQLite will only access
  2213. ** or modify this field while holding a particular static mutex.
  2214. ** The application should never modify anything within the sqlite3_vfs
  2215. ** object once the object has been registered.
  2216. **
  2217. ** The zName field holds the name of the VFS module. The name must
  2218. ** be unique across all VFS modules.
  2219. **
  2220. ** [[sqlite3_vfs.xOpen]]
  2221. ** ^SQLite guarantees that the zFilename parameter to xOpen
  2222. ** is either a NULL pointer or string obtained
  2223. ** from xFullPathname() with an optional suffix added.
  2224. ** ^If a suffix is added to the zFilename parameter, it will
  2225. ** consist of a single "-" character followed by no more than
  2226. ** 11 alphanumeric and/or "-" characters.
  2227. ** ^SQLite further guarantees that
  2228. ** the string will be valid and unchanged until xClose() is
  2229. ** called. Because of the previous sentence,
  2230. ** the [sqlite3_file] can safely store a pointer to the
  2231. ** filename if it needs to remember the filename for some reason.
  2232. ** If the zFilename parameter to xOpen is a NULL pointer then xOpen
  2233. ** must invent its own temporary name for the file. ^Whenever the
  2234. ** xFilename parameter is NULL it will also be the case that the
  2235. ** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
  2236. **
  2237. ** The flags argument to xOpen() includes all bits set in
  2238. ** the flags argument to [sqlite3_open_v2()]. Or if [sqlite3_open()]
  2239. ** or [sqlite3_open16()] is used, then flags includes at least
  2240. ** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE].
  2241. ** If xOpen() opens a file read-only then it sets *pOutFlags to
  2242. ** include [SQLITE_OPEN_READONLY]. Other bits in *pOutFlags may be set.
  2243. **
  2244. ** ^(SQLite will also add one of the following flags to the xOpen()
  2245. ** call, depending on the object being opened:
  2246. **
  2247. ** <ul>
  2248. ** <li> [SQLITE_OPEN_MAIN_DB]
  2249. ** <li> [SQLITE_OPEN_MAIN_JOURNAL]
  2250. ** <li> [SQLITE_OPEN_TEMP_DB]
  2251. ** <li> [SQLITE_OPEN_TEMP_JOURNAL]
  2252. ** <li> [SQLITE_OPEN_TRANSIENT_DB]
  2253. ** <li> [SQLITE_OPEN_SUBJOURNAL]
  2254. ** <li> [SQLITE_OPEN_MASTER_JOURNAL]
  2255. ** <li> [SQLITE_OPEN_WAL]
  2256. ** </ul>)^
  2257. **
  2258. ** The file I/O implementation can use the object type flags to
  2259. ** change the way it deals with files. For example, an application
  2260. ** that does not care about crash recovery or rollback might make
  2261. ** the open of a journal file a no-op. Writes to this journal would
  2262. ** also be no-ops, and any attempt to read the journal would return
  2263. ** SQLITE_IOERR. Or the implementation might recognize that a database
  2264. ** file will be doing page-aligned sector reads and writes in a random
  2265. ** order and set up its I/O subsystem accordingly.
  2266. **
  2267. ** SQLite might also add one of the following flags to the xOpen method:
  2268. **
  2269. ** <ul>
  2270. ** <li> [SQLITE_OPEN_DELETEONCLOSE]
  2271. ** <li> [SQLITE_OPEN_EXCLUSIVE]
  2272. ** </ul>
  2273. **
  2274. ** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
  2275. ** deleted when it is closed. ^The [SQLITE_OPEN_DELETEONCLOSE]
  2276. ** will be set for TEMP databases and their journals, transient
  2277. ** databases, and subjournals.
  2278. **
  2279. ** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction
  2280. ** with the [SQLITE_OPEN_CREATE] flag, which are both directly
  2281. ** analogous to the O_EXCL and O_CREAT flags of the POSIX open()
  2282. ** API. The SQLITE_OPEN_EXCLUSIVE flag, when paired with the
  2283. ** SQLITE_OPEN_CREATE, is used to indicate that file should always
  2284. ** be created, and that it is an error if it already exists.
  2285. ** It is <i>not</i> used to indicate the file should be opened
  2286. ** for exclusive access.
  2287. **
  2288. ** ^At least szOsFile bytes of memory are allocated by SQLite
  2289. ** to hold the [sqlite3_file] structure passed as the third
  2290. ** argument to xOpen. The xOpen method does not have to
  2291. ** allocate the structure; it should just fill it in. Note that
  2292. ** the xOpen method must set the sqlite3_file.pMethods to either
  2293. ** a valid [sqlite3_io_methods] object or to NULL. xOpen must do
  2294. ** this even if the open fails. SQLite expects that the sqlite3_file.pMethods
  2295. ** element will be valid after xOpen returns regardless of the success
  2296. ** or failure of the xOpen call.
  2297. **
  2298. ** [[sqlite3_vfs.xAccess]]
  2299. ** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
  2300. ** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
  2301. ** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
  2302. ** to test whether a file is at least readable. The SQLITE_ACCESS_READ
  2303. ** flag is never actually used and is not implemented in the built-in
  2304. ** VFSes of SQLite. The file is named by the second argument and can be a
  2305. ** directory. The xAccess method returns [SQLITE_OK] on success or some
  2306. ** non-zero error code if there is an I/O error or if the name of
  2307. ** the file given in the second argument is illegal. If SQLITE_OK
  2308. ** is returned, then non-zero or zero is written into *pResOut to indicate
  2309. ** whether or not the file is accessible.
  2310. **
  2311. ** ^SQLite will always allocate at least mxPathname+1 bytes for the
  2312. ** output buffer xFullPathname. The exact size of the output buffer
  2313. ** is also passed as a parameter to both methods. If the output buffer
  2314. ** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
  2315. ** handled as a fatal error by SQLite, vfs implementations should endeavor
  2316. ** to prevent this by setting mxPathname to a sufficiently large value.
  2317. **
  2318. ** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64()
  2319. ** interfaces are not strictly a part of the filesystem, but they are
  2320. ** included in the VFS structure for completeness.
  2321. ** The xRandomness() function attempts to return nBytes bytes
  2322. ** of good-quality randomness into zOut. The return value is
  2323. ** the actual number of bytes of randomness obtained.
  2324. ** The xSleep() method causes the calling thread to sleep for at
  2325. ** least the number of microseconds given. ^The xCurrentTime()
  2326. ** method returns a Julian Day Number for the current date and time as
  2327. ** a floating point value.
  2328. ** ^The xCurrentTimeInt64() method returns, as an integer, the Julian
  2329. ** Day Number multiplied by 86400000 (the number of milliseconds in
  2330. ** a 24-hour day).
  2331. ** ^SQLite will use the xCurrentTimeInt64() method to get the current
  2332. ** date and time if that method is available (if iVersion is 2 or
  2333. ** greater and the function pointer is not NULL) and will fall back
  2334. ** to xCurrentTime() if xCurrentTimeInt64() is unavailable.
  2335. **
  2336. ** ^The xSetSystemCall(), xGetSystemCall(), and xNestSystemCall() interfaces
  2337. ** are not used by the SQLite core. These optional interfaces are provided
  2338. ** by some VFSes to facilitate testing of the VFS code. By overriding
  2339. ** system calls with functions under its control, a test program can
  2340. ** simulate faults and error conditions that would otherwise be difficult
  2341. ** or impossible to induce. The set of system calls that can be overridden
  2342. ** varies from one VFS to another, and from one version of the same VFS to the
  2343. ** next. Applications that use these interfaces must be prepared for any
  2344. ** or all of these interfaces to be NULL or for their behavior to change
  2345. ** from one release to the next. Applications must not attempt to access
  2346. ** any of these methods if the iVersion of the VFS is less than 3.
  2347. */
  2348. typedef struct sqlite3_vfs sqlite3_vfs;
  2349. typedef void (*sqlite3_syscall_ptr)(void);
  2350. struct sqlite3_vfs {
  2351. int iVersion; /* Structure version number (currently 3) */
  2352. int szOsFile; /* Size of subclassed sqlite3_file */
  2353. int mxPathname; /* Maximum file pathname length */
  2354. sqlite3_vfs *pNext; /* Next registered VFS */
  2355. const char *zName; /* Name of this virtual file system */
  2356. void *pAppData; /* Pointer to application-specific data */
  2357. int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
  2358. int flags, int *pOutFlags);
  2359. int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
  2360. int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);
  2361. int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
  2362. void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
  2363. void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
  2364. void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void);
  2365. void (*xDlClose)(sqlite3_vfs*, void*);
  2366. int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
  2367. int (*xSleep)(sqlite3_vfs*, int microseconds);
  2368. int (*xCurrentTime)(sqlite3_vfs*, double*);
  2369. int (*xGetLastError)(sqlite3_vfs*, int, char *);
  2370. /*
  2371. ** The methods above are in version 1 of the sqlite_vfs object
  2372. ** definition. Those that follow are added in version 2 or later
  2373. */
  2374. int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*);
  2375. /*
  2376. ** The methods above are in versions 1 and 2 of the sqlite_vfs object.
  2377. ** Those below are for version 3 and greater.
  2378. */
  2379. int (*xSetSystemCall)(sqlite3_vfs*, const char *zName, sqlite3_syscall_ptr);
  2380. sqlite3_syscall_ptr (*xGetSystemCall)(sqlite3_vfs*, const char *zName);
  2381. const char *(*xNextSystemCall)(sqlite3_vfs*, const char *zName);
  2382. /*
  2383. ** The methods above are in versions 1 through 3 of the sqlite_vfs object.
  2384. ** New fields may be appended in future versions. The iVersion
  2385. ** value will increment whenever this happens.
  2386. */
  2387. };
  2388. /*
  2389. ** CAPI3REF: Flags for the xAccess VFS method
  2390. **
  2391. ** These integer constants can be used as the third parameter to
  2392. ** the xAccess method of an [sqlite3_vfs] object. They determine
  2393. ** what kind of permissions the xAccess method is looking for.
  2394. ** With SQLITE_ACCESS_EXISTS, the xAccess method
  2395. ** simply checks whether the file exists.
  2396. ** With SQLITE_ACCESS_READWRITE, the xAccess method
  2397. ** checks whether the named directory is both readable and writable
  2398. ** (in other words, if files can be added, removed, and renamed within
  2399. ** the directory).
  2400. ** The SQLITE_ACCESS_READWRITE constant is currently used only by the
  2401. ** [temp_store_directory pragma], though this could change in a future
  2402. ** release of SQLite.
  2403. ** With SQLITE_ACCESS_READ, the xAccess method
  2404. ** checks whether the file is readable. The SQLITE_ACCESS_READ constant is
  2405. ** currently unused, though it might be used in a future release of
  2406. ** SQLite.
  2407. */
  2408. #define SQLITE_ACCESS_EXISTS 0
  2409. #define SQLITE_ACCESS_READWRITE 1 /* Used by PRAGMA temp_store_directory */
  2410. #define SQLITE_ACCESS_READ 2 /* Unused */
  2411. /*
  2412. ** CAPI3REF: Flags for the xShmLock VFS method
  2413. **
  2414. ** These integer constants define the various locking operations
  2415. ** allowed by the xShmLock method of [sqlite3_io_methods]. The
  2416. ** following are the only legal combinations of flags to the
  2417. ** xShmLock method:
  2418. **
  2419. ** <ul>
  2420. ** <li> SQLITE_SHM_LOCK | SQLITE_SHM_SHARED
  2421. ** <li> SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE
  2422. ** <li> SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED
  2423. ** <li> SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE
  2424. ** </ul>
  2425. **
  2426. ** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as
  2427. ** was given on the corresponding lock.
  2428. **
  2429. ** The xShmLock method can transition between unlocked and SHARED or
  2430. ** between unlocked and EXCLUSIVE. It cannot transition between SHARED
  2431. ** and EXCLUSIVE.
  2432. */
  2433. #define SQLITE_SHM_UNLOCK 1
  2434. #define SQLITE_SHM_LOCK 2
  2435. #define SQLITE_SHM_SHARED 4
  2436. #define SQLITE_SHM_EXCLUSIVE 8
  2437. /*
  2438. ** CAPI3REF: Maximum xShmLock index
  2439. **
  2440. ** The xShmLock method on [sqlite3_io_methods] may use values
  2441. ** between 0 and this upper bound as its "offset" argument.
  2442. ** The SQLite core will never attempt to acquire or release a
  2443. ** lock outside of this range
  2444. */
  2445. #define SQLITE_SHM_NLOCK 8
  2446. /*
  2447. ** CAPI3REF: Initialize The SQLite Library
  2448. **
  2449. ** ^The sqlite3_initialize() routine initializes the
  2450. ** SQLite library. ^The sqlite3_shutdown() routine
  2451. ** deallocates any resources that were allocated by sqlite3_initialize().
  2452. ** These routines are designed to aid in process initialization and
  2453. ** shutdown on embedded systems. Workstation applications using
  2454. ** SQLite normally do not need to invoke either of these routines.
  2455. **
  2456. ** A call to sqlite3_initialize() is an "effective" call if it is
  2457. ** the first time sqlite3_initialize() is invoked during the lifetime of
  2458. ** the process, or if it is the first time sqlite3_initialize() is invoked
  2459. ** following a call to sqlite3_shutdown(). ^(Only an effective call
  2460. ** of sqlite3_initialize() does any initialization. All other calls
  2461. ** are harmless no-ops.)^
  2462. **
  2463. ** A call to sqlite3_shutdown() is an "effective" call if it is the first
  2464. ** call to sqlite3_shutdown() since the last sqlite3_initialize(). ^(Only
  2465. ** an effective call to sqlite3_shutdown() does any deinitialization.
  2466. ** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^
  2467. **
  2468. ** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown()
  2469. ** is not. The sqlite3_shutdown() interface must only be called from a
  2470. ** single thread. All open [database connections] must be closed and all
  2471. ** other SQLite resources must be deallocated prior to invoking
  2472. ** sqlite3_shutdown().
  2473. **
  2474. ** Among other things, ^sqlite3_initialize() will invoke
  2475. ** sqlite3_os_init(). Similarly, ^sqlite3_shutdown()
  2476. ** will invoke sqlite3_os_end().
  2477. **
  2478. ** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success.
  2479. ** ^If for some reason, sqlite3_initialize() is unable to initialize
  2480. ** the library (perhaps it is unable to allocate a needed resource such
  2481. ** as a mutex) it returns an [error code] other than [SQLITE_OK].
  2482. **
  2483. ** ^The sqlite3_initialize() routine is called internally by many other
  2484. ** SQLite interfaces so that an application usually does not need to
  2485. ** invoke sqlite3_initialize() directly. For example, [sqlite3_open()]
  2486. ** calls sqlite3_initialize() so the SQLite library will be automatically
  2487. ** initialized when [sqlite3_open()] is called if it has not be initialized
  2488. ** already. ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT]
  2489. ** compile-time option, then the automatic calls to sqlite3_initialize()
  2490. ** are omitted and the application must call sqlite3_initialize() directly
  2491. ** prior to using any other SQLite interface. For maximum portability,
  2492. ** it is recommended that applications always invoke sqlite3_initialize()
  2493. ** directly prior to using any other SQLite interface. Future releases
  2494. ** of SQLite may require this. In other words, the behavior exhibited
  2495. ** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the
  2496. ** default behavior in some future release of SQLite.
  2497. **
  2498. ** The sqlite3_os_init() routine does operating-system specific
  2499. ** initialization of the SQLite library. The sqlite3_os_end()
  2500. ** routine undoes the effect of sqlite3_os_init(). Typical tasks
  2501. ** performed by these routines include allocation or deallocation
  2502. ** of static resources, initialization of global variables,
  2503. ** setting up a default [sqlite3_vfs] module, or setting up
  2504. ** a default configuration using [sqlite3_config()].
  2505. **
  2506. ** The application should never invoke either sqlite3_os_init()
  2507. ** or sqlite3_os_end() directly. The application should only invoke
  2508. ** sqlite3_initialize() and sqlite3_shutdown(). The sqlite3_os_init()
  2509. ** interface is called automatically by sqlite3_initialize() and
  2510. ** sqlite3_os_end() is called by sqlite3_shutdown(). Appropriate
  2511. ** implementations for sqlite3_os_init() and sqlite3_os_end()
  2512. ** are built into SQLite when it is compiled for Unix, Windows, or OS/2.
  2513. ** When [custom builds | built for other platforms]
  2514. ** (using the [SQLITE_OS_OTHER=1] compile-time
  2515. ** option) the application must supply a suitable implementation for
  2516. ** sqlite3_os_init() and sqlite3_os_end(). An application-supplied
  2517. ** implementation of sqlite3_os_init() or sqlite3_os_end()
  2518. ** must return [SQLITE_OK] on success and some other [error code] upon
  2519. ** failure.
  2520. */
  2521. SQLITE_API int sqlite3_initialize(void);
  2522. SQLITE_API int sqlite3_shutdown(void);
  2523. SQLITE_API int sqlite3_os_init(void);
  2524. SQLITE_API int sqlite3_os_end(void);
  2525. /*
  2526. ** CAPI3REF: Configuring The SQLite Library
  2527. **
  2528. ** The sqlite3_config() interface is used to make global configuration
  2529. ** changes to SQLite in order to tune SQLite to the specific needs of
  2530. ** the application. The default configuration is recommended for most
  2531. ** applications and so this routine is usually not necessary. It is
  2532. ** provided to support rare applications with unusual needs.
  2533. **
  2534. ** <b>The sqlite3_config() interface is not threadsafe. The application
  2535. ** must ensure that no other SQLite interfaces are invoked by other
  2536. ** threads while sqlite3_config() is running.</b>
  2537. **
  2538. ** The sqlite3_config() interface
  2539. ** may only be invoked prior to library initialization using
  2540. ** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].
  2541. ** ^If sqlite3_config() is called after [sqlite3_initialize()] and before
  2542. ** [sqlite3_shutdown()] then it will return SQLITE_MISUSE.
  2543. ** Note, however, that ^sqlite3_config() can be called as part of the
  2544. ** implementation of an application-defined [sqlite3_os_init()].
  2545. **
  2546. ** The first argument to sqlite3_config() is an integer
  2547. ** [configuration option] that determines
  2548. ** what property of SQLite is to be configured. Subsequent arguments
  2549. ** vary depending on the [configuration option]
  2550. ** in the first argument.
  2551. **
  2552. ** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK].
  2553. ** ^If the option is unknown or SQLite is unable to set the option
  2554. ** then this routine returns a non-zero [error code].
  2555. */
  2556. SQLITE_API int sqlite3_config(int, ...);
  2557. /*
  2558. ** CAPI3REF: Configure database connections
  2559. ** METHOD: sqlite3
  2560. **
  2561. ** The sqlite3_db_config() interface is used to make configuration
  2562. ** changes to a [database connection]. The interface is similar to
  2563. ** [sqlite3_config()] except that the changes apply to a single
  2564. ** [database connection] (specified in the first argument).
  2565. **
  2566. ** The second argument to sqlite3_db_config(D,V,...) is the
  2567. ** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code
  2568. ** that indicates what aspect of the [database connection] is being configured.
  2569. ** Subsequent arguments vary depending on the configuration verb.
  2570. **
  2571. ** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if
  2572. ** the call is considered successful.
  2573. */
  2574. SQLITE_API int sqlite3_db_config(sqlite3*, int op, ...);
  2575. /*
  2576. ** CAPI3REF: Memory Allocation Routines
  2577. **
  2578. ** An instance of this object defines the interface between SQLite
  2579. ** and low-level memory allocation routines.
  2580. **
  2581. ** This object is used in only one place in the SQLite interface.
  2582. ** A pointer to an instance of this object is the argument to
  2583. ** [sqlite3_config()] when the configuration option is
  2584. ** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC].
  2585. ** By creating an instance of this object
  2586. ** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC])
  2587. ** during configuration, an application can specify an alternative
  2588. ** memory allocation subsystem for SQLite to use for all of its
  2589. ** dynamic memory needs.
  2590. **
  2591. ** Note that SQLite comes with several [built-in memory allocators]
  2592. ** that are perfectly adequate for the overwhelming majority of applications
  2593. ** and that this object is only useful to a tiny minority of applications
  2594. ** with specialized memory allocation requirements. This object is
  2595. ** also used during testing of SQLite in order to specify an alternative
  2596. ** memory allocator that simulates memory out-of-memory conditions in
  2597. ** order to verify that SQLite recovers gracefully from such
  2598. ** conditions.
  2599. **
  2600. ** The xMalloc, xRealloc, and xFree methods must work like the
  2601. ** malloc(), realloc() and free() functions from the standard C library.
  2602. ** ^SQLite guarantees that the second argument to
  2603. ** xRealloc is always a value returned by a prior call to xRoundup.
  2604. **
  2605. ** xSize should return the allocated size of a memory allocation
  2606. ** previously obtained from xMalloc or xRealloc. The allocated size
  2607. ** is always at least as big as the requested size but may be larger.
  2608. **
  2609. ** The xRoundup method returns what would be the allocated size of
  2610. ** a memory allocation given a particular requested size. Most memory
  2611. ** allocators round up memory allocations at least to the next multiple
  2612. ** of 8. Some allocators round up to a larger multiple or to a power of 2.
  2613. ** Every memory allocation request coming in through [sqlite3_malloc()]
  2614. ** or [sqlite3_realloc()] first calls xRoundup. If xRoundup returns 0,
  2615. ** that causes the corresponding memory allocation to fail.
  2616. **
  2617. ** The xInit method initializes the memory allocator. For example,
  2618. ** it might allocate any required mutexes or initialize internal data
  2619. ** structures. The xShutdown method is invoked (indirectly) by
  2620. ** [sqlite3_shutdown()] and should deallocate any resources acquired
  2621. ** by xInit. The pAppData pointer is used as the only parameter to
  2622. ** xInit and xShutdown.
  2623. **
  2624. ** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes
  2625. ** the xInit method, so the xInit method need not be threadsafe. The
  2626. ** xShutdown method is only called from [sqlite3_shutdown()] so it does
  2627. ** not need to be threadsafe either. For all other methods, SQLite
  2628. ** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the
  2629. ** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which
  2630. ** it is by default) and so the methods are automatically serialized.
  2631. ** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other
  2632. ** methods must be threadsafe or else make their own arrangements for
  2633. ** serialization.
  2634. **
  2635. ** SQLite will never invoke xInit() more than once without an intervening
  2636. ** call to xShutdown().
  2637. */
  2638. typedef struct sqlite3_mem_methods sqlite3_mem_methods;
  2639. struct sqlite3_mem_methods {
  2640. void *(*xMalloc)(int); /* Memory allocation function */
  2641. void (*xFree)(void*); /* Free a prior allocation */
  2642. void *(*xRealloc)(void*,int); /* Resize an allocation */
  2643. int (*xSize)(void*); /* Return the size of an allocation */
  2644. int (*xRoundup)(int); /* Round up request size to allocation size */
  2645. int (*xInit)(void*); /* Initialize the memory allocator */
  2646. void (*xShutdown)(void*); /* Deinitialize the memory allocator */
  2647. void *pAppData; /* Argument to xInit() and xShutdown() */
  2648. };
  2649. /*
  2650. ** CAPI3REF: Configuration Options
  2651. ** KEYWORDS: {configuration option}
  2652. **
  2653. ** These constants are the available integer configuration options that
  2654. ** can be passed as the first argument to the [sqlite3_config()] interface.
  2655. **
  2656. ** New configuration options may be added in future releases of SQLite.
  2657. ** Existing configuration options might be discontinued. Applications
  2658. ** should check the return code from [sqlite3_config()] to make sure that
  2659. ** the call worked. The [sqlite3_config()] interface will return a
  2660. ** non-zero [error code] if a discontinued or unsupported configuration option
  2661. ** is invoked.
  2662. **
  2663. ** <dl>
  2664. ** [[SQLITE_CONFIG_SINGLETHREAD]] <dt>SQLITE_CONFIG_SINGLETHREAD</dt>
  2665. ** <dd>There are no arguments to this option. ^This option sets the
  2666. ** [threading mode] to Single-thread. In other words, it disables
  2667. ** all mutexing and puts SQLite into a mode where it can only be used
  2668. ** by a single thread. ^If SQLite is compiled with
  2669. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  2670. ** it is not possible to change the [threading mode] from its default
  2671. ** value of Single-thread and so [sqlite3_config()] will return
  2672. ** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD
  2673. ** configuration option.</dd>
  2674. **
  2675. ** [[SQLITE_CONFIG_MULTITHREAD]] <dt>SQLITE_CONFIG_MULTITHREAD</dt>
  2676. ** <dd>There are no arguments to this option. ^This option sets the
  2677. ** [threading mode] to Multi-thread. In other words, it disables
  2678. ** mutexing on [database connection] and [prepared statement] objects.
  2679. ** The application is responsible for serializing access to
  2680. ** [database connections] and [prepared statements]. But other mutexes
  2681. ** are enabled so that SQLite will be safe to use in a multi-threaded
  2682. ** environment as long as no two threads attempt to use the same
  2683. ** [database connection] at the same time. ^If SQLite is compiled with
  2684. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  2685. ** it is not possible to set the Multi-thread [threading mode] and
  2686. ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
  2687. ** SQLITE_CONFIG_MULTITHREAD configuration option.</dd>
  2688. **
  2689. ** [[SQLITE_CONFIG_SERIALIZED]] <dt>SQLITE_CONFIG_SERIALIZED</dt>
  2690. ** <dd>There are no arguments to this option. ^This option sets the
  2691. ** [threading mode] to Serialized. In other words, this option enables
  2692. ** all mutexes including the recursive
  2693. ** mutexes on [database connection] and [prepared statement] objects.
  2694. ** In this mode (which is the default when SQLite is compiled with
  2695. ** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access
  2696. ** to [database connections] and [prepared statements] so that the
  2697. ** application is free to use the same [database connection] or the
  2698. ** same [prepared statement] in different threads at the same time.
  2699. ** ^If SQLite is compiled with
  2700. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  2701. ** it is not possible to set the Serialized [threading mode] and
  2702. ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
  2703. ** SQLITE_CONFIG_SERIALIZED configuration option.</dd>
  2704. **
  2705. ** [[SQLITE_CONFIG_MALLOC]] <dt>SQLITE_CONFIG_MALLOC</dt>
  2706. ** <dd> ^(The SQLITE_CONFIG_MALLOC option takes a single argument which is
  2707. ** a pointer to an instance of the [sqlite3_mem_methods] structure.
  2708. ** The argument specifies
  2709. ** alternative low-level memory allocation routines to be used in place of
  2710. ** the memory allocation routines built into SQLite.)^ ^SQLite makes
  2711. ** its own private copy of the content of the [sqlite3_mem_methods] structure
  2712. ** before the [sqlite3_config()] call returns.</dd>
  2713. **
  2714. ** [[SQLITE_CONFIG_GETMALLOC]] <dt>SQLITE_CONFIG_GETMALLOC</dt>
  2715. ** <dd> ^(The SQLITE_CONFIG_GETMALLOC option takes a single argument which
  2716. ** is a pointer to an instance of the [sqlite3_mem_methods] structure.
  2717. ** The [sqlite3_mem_methods]
  2718. ** structure is filled with the currently defined memory allocation routines.)^
  2719. ** This option can be used to overload the default memory allocation
  2720. ** routines with a wrapper that simulations memory allocation failure or
  2721. ** tracks memory usage, for example. </dd>
  2722. **
  2723. ** [[SQLITE_CONFIG_SMALL_MALLOC]] <dt>SQLITE_CONFIG_SMALL_MALLOC</dt>
  2724. ** <dd> ^The SQLITE_CONFIG_SMALL_MALLOC option takes single argument of
  2725. ** type int, interpreted as a boolean, which if true provides a hint to
  2726. ** SQLite that it should avoid large memory allocations if possible.
  2727. ** SQLite will run faster if it is free to make large memory allocations,
  2728. ** but some application might prefer to run slower in exchange for
  2729. ** guarantees about memory fragmentation that are possible if large
  2730. ** allocations are avoided. This hint is normally off.
  2731. ** </dd>
  2732. **
  2733. ** [[SQLITE_CONFIG_MEMSTATUS]] <dt>SQLITE_CONFIG_MEMSTATUS</dt>
  2734. ** <dd> ^The SQLITE_CONFIG_MEMSTATUS option takes single argument of type int,
  2735. ** interpreted as a boolean, which enables or disables the collection of
  2736. ** memory allocation statistics. ^(When memory allocation statistics are
  2737. ** disabled, the following SQLite interfaces become non-operational:
  2738. ** <ul>
  2739. ** <li> [sqlite3_hard_heap_limit64()]
  2740. ** <li> [sqlite3_memory_used()]
  2741. ** <li> [sqlite3_memory_highwater()]
  2742. ** <li> [sqlite3_soft_heap_limit64()]
  2743. ** <li> [sqlite3_status64()]
  2744. ** </ul>)^
  2745. ** ^Memory allocation statistics are enabled by default unless SQLite is
  2746. ** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory
  2747. ** allocation statistics are disabled by default.
  2748. ** </dd>
  2749. **
  2750. ** [[SQLITE_CONFIG_SCRATCH]] <dt>SQLITE_CONFIG_SCRATCH</dt>
  2751. ** <dd> The SQLITE_CONFIG_SCRATCH option is no longer used.
  2752. ** </dd>
  2753. **
  2754. ** [[SQLITE_CONFIG_PAGECACHE]] <dt>SQLITE_CONFIG_PAGECACHE</dt>
  2755. ** <dd> ^The SQLITE_CONFIG_PAGECACHE option specifies a memory pool
  2756. ** that SQLite can use for the database page cache with the default page
  2757. ** cache implementation.
  2758. ** This configuration option is a no-op if an application-defined page
  2759. ** cache implementation is loaded using the [SQLITE_CONFIG_PCACHE2].
  2760. ** ^There are three arguments to SQLITE_CONFIG_PAGECACHE: A pointer to
  2761. ** 8-byte aligned memory (pMem), the size of each page cache line (sz),
  2762. ** and the number of cache lines (N).
  2763. ** The sz argument should be the size of the largest database page
  2764. ** (a power of two between 512 and 65536) plus some extra bytes for each
  2765. ** page header. ^The number of extra bytes needed by the page header
  2766. ** can be determined using [SQLITE_CONFIG_PCACHE_HDRSZ].
  2767. ** ^It is harmless, apart from the wasted memory,
  2768. ** for the sz parameter to be larger than necessary. The pMem
  2769. ** argument must be either a NULL pointer or a pointer to an 8-byte
  2770. ** aligned block of memory of at least sz*N bytes, otherwise
  2771. ** subsequent behavior is undefined.
  2772. ** ^When pMem is not NULL, SQLite will strive to use the memory provided
  2773. ** to satisfy page cache needs, falling back to [sqlite3_malloc()] if
  2774. ** a page cache line is larger than sz bytes or if all of the pMem buffer
  2775. ** is exhausted.
  2776. ** ^If pMem is NULL and N is non-zero, then each database connection
  2777. ** does an initial bulk allocation for page cache memory
  2778. ** from [sqlite3_malloc()] sufficient for N cache lines if N is positive or
  2779. ** of -1024*N bytes if N is negative, . ^If additional
  2780. ** page cache memory is needed beyond what is provided by the initial
  2781. ** allocation, then SQLite goes to [sqlite3_malloc()] separately for each
  2782. ** additional cache line. </dd>
  2783. **
  2784. ** [[SQLITE_CONFIG_HEAP]] <dt>SQLITE_CONFIG_HEAP</dt>
  2785. ** <dd> ^The SQLITE_CONFIG_HEAP option specifies a static memory buffer
  2786. ** that SQLite will use for all of its dynamic memory allocation needs
  2787. ** beyond those provided for by [SQLITE_CONFIG_PAGECACHE].
  2788. ** ^The SQLITE_CONFIG_HEAP option is only available if SQLite is compiled
  2789. ** with either [SQLITE_ENABLE_MEMSYS3] or [SQLITE_ENABLE_MEMSYS5] and returns
  2790. ** [SQLITE_ERROR] if invoked otherwise.
  2791. ** ^There are three arguments to SQLITE_CONFIG_HEAP:
  2792. ** An 8-byte aligned pointer to the memory,
  2793. ** the number of bytes in the memory buffer, and the minimum allocation size.
  2794. ** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts
  2795. ** to using its default memory allocator (the system malloc() implementation),
  2796. ** undoing any prior invocation of [SQLITE_CONFIG_MALLOC]. ^If the
  2797. ** memory pointer is not NULL then the alternative memory
  2798. ** allocator is engaged to handle all of SQLites memory allocation needs.
  2799. ** The first pointer (the memory pointer) must be aligned to an 8-byte
  2800. ** boundary or subsequent behavior of SQLite will be undefined.
  2801. ** The minimum allocation size is capped at 2**12. Reasonable values
  2802. ** for the minimum allocation size are 2**5 through 2**8.</dd>
  2803. **
  2804. ** [[SQLITE_CONFIG_MUTEX]] <dt>SQLITE_CONFIG_MUTEX</dt>
  2805. ** <dd> ^(The SQLITE_CONFIG_MUTEX option takes a single argument which is a
  2806. ** pointer to an instance of the [sqlite3_mutex_methods] structure.
  2807. ** The argument specifies alternative low-level mutex routines to be used
  2808. ** in place the mutex routines built into SQLite.)^ ^SQLite makes a copy of
  2809. ** the content of the [sqlite3_mutex_methods] structure before the call to
  2810. ** [sqlite3_config()] returns. ^If SQLite is compiled with
  2811. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  2812. ** the entire mutexing subsystem is omitted from the build and hence calls to
  2813. ** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will
  2814. ** return [SQLITE_ERROR].</dd>
  2815. **
  2816. ** [[SQLITE_CONFIG_GETMUTEX]] <dt>SQLITE_CONFIG_GETMUTEX</dt>
  2817. ** <dd> ^(The SQLITE_CONFIG_GETMUTEX option takes a single argument which
  2818. ** is a pointer to an instance of the [sqlite3_mutex_methods] structure. The
  2819. ** [sqlite3_mutex_methods]
  2820. ** structure is filled with the currently defined mutex routines.)^
  2821. ** This option can be used to overload the default mutex allocation
  2822. ** routines with a wrapper used to track mutex usage for performance
  2823. ** profiling or testing, for example. ^If SQLite is compiled with
  2824. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  2825. ** the entire mutexing subsystem is omitted from the build and hence calls to
  2826. ** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will
  2827. ** return [SQLITE_ERROR].</dd>
  2828. **
  2829. ** [[SQLITE_CONFIG_LOOKASIDE]] <dt>SQLITE_CONFIG_LOOKASIDE</dt>
  2830. ** <dd> ^(The SQLITE_CONFIG_LOOKASIDE option takes two arguments that determine
  2831. ** the default size of lookaside memory on each [database connection].
  2832. ** The first argument is the
  2833. ** size of each lookaside buffer slot and the second is the number of
  2834. ** slots allocated to each database connection.)^ ^(SQLITE_CONFIG_LOOKASIDE
  2835. ** sets the <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE]
  2836. ** option to [sqlite3_db_config()] can be used to change the lookaside
  2837. ** configuration on individual connections.)^ </dd>
  2838. **
  2839. ** [[SQLITE_CONFIG_PCACHE2]] <dt>SQLITE_CONFIG_PCACHE2</dt>
  2840. ** <dd> ^(The SQLITE_CONFIG_PCACHE2 option takes a single argument which is
  2841. ** a pointer to an [sqlite3_pcache_methods2] object. This object specifies
  2842. ** the interface to a custom page cache implementation.)^
  2843. ** ^SQLite makes a copy of the [sqlite3_pcache_methods2] object.</dd>
  2844. **
  2845. ** [[SQLITE_CONFIG_GETPCACHE2]] <dt>SQLITE_CONFIG_GETPCACHE2</dt>
  2846. ** <dd> ^(The SQLITE_CONFIG_GETPCACHE2 option takes a single argument which
  2847. ** is a pointer to an [sqlite3_pcache_methods2] object. SQLite copies of
  2848. ** the current page cache implementation into that object.)^ </dd>
  2849. **
  2850. ** [[SQLITE_CONFIG_LOG]] <dt>SQLITE_CONFIG_LOG</dt>
  2851. ** <dd> The SQLITE_CONFIG_LOG option is used to configure the SQLite
  2852. ** global [error log].
  2853. ** (^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a
  2854. ** function with a call signature of void(*)(void*,int,const char*),
  2855. ** and a pointer to void. ^If the function pointer is not NULL, it is
  2856. ** invoked by [sqlite3_log()] to process each logging event. ^If the
  2857. ** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op.
  2858. ** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is
  2859. ** passed through as the first parameter to the application-defined logger
  2860. ** function whenever that function is invoked. ^The second parameter to
  2861. ** the logger function is a copy of the first parameter to the corresponding
  2862. ** [sqlite3_log()] call and is intended to be a [result code] or an
  2863. ** [extended result code]. ^The third parameter passed to the logger is
  2864. ** log message after formatting via [sqlite3_snprintf()].
  2865. ** The SQLite logging interface is not reentrant; the logger function
  2866. ** supplied by the application must not invoke any SQLite interface.
  2867. ** In a multi-threaded application, the application-defined logger
  2868. ** function must be threadsafe. </dd>
  2869. **
  2870. ** [[SQLITE_CONFIG_URI]] <dt>SQLITE_CONFIG_URI
  2871. ** <dd>^(The SQLITE_CONFIG_URI option takes a single argument of type int.
  2872. ** If non-zero, then URI handling is globally enabled. If the parameter is zero,
  2873. ** then URI handling is globally disabled.)^ ^If URI handling is globally
  2874. ** enabled, all filenames passed to [sqlite3_open()], [sqlite3_open_v2()],
  2875. ** [sqlite3_open16()] or
  2876. ** specified as part of [ATTACH] commands are interpreted as URIs, regardless
  2877. ** of whether or not the [SQLITE_OPEN_URI] flag is set when the database
  2878. ** connection is opened. ^If it is globally disabled, filenames are
  2879. ** only interpreted as URIs if the SQLITE_OPEN_URI flag is set when the
  2880. ** database connection is opened. ^(By default, URI handling is globally
  2881. ** disabled. The default value may be changed by compiling with the
  2882. ** [SQLITE_USE_URI] symbol defined.)^
  2883. **
  2884. ** [[SQLITE_CONFIG_COVERING_INDEX_SCAN]] <dt>SQLITE_CONFIG_COVERING_INDEX_SCAN
  2885. ** <dd>^The SQLITE_CONFIG_COVERING_INDEX_SCAN option takes a single integer
  2886. ** argument which is interpreted as a boolean in order to enable or disable
  2887. ** the use of covering indices for full table scans in the query optimizer.
  2888. ** ^The default setting is determined
  2889. ** by the [SQLITE_ALLOW_COVERING_INDEX_SCAN] compile-time option, or is "on"
  2890. ** if that compile-time option is omitted.
  2891. ** The ability to disable the use of covering indices for full table scans
  2892. ** is because some incorrectly coded legacy applications might malfunction
  2893. ** when the optimization is enabled. Providing the ability to
  2894. ** disable the optimization allows the older, buggy application code to work
  2895. ** without change even with newer versions of SQLite.
  2896. **
  2897. ** [[SQLITE_CONFIG_PCACHE]] [[SQLITE_CONFIG_GETPCACHE]]
  2898. ** <dt>SQLITE_CONFIG_PCACHE and SQLITE_CONFIG_GETPCACHE
  2899. ** <dd> These options are obsolete and should not be used by new code.
  2900. ** They are retained for backwards compatibility but are now no-ops.
  2901. ** </dd>
  2902. **
  2903. ** [[SQLITE_CONFIG_SQLLOG]]
  2904. ** <dt>SQLITE_CONFIG_SQLLOG
  2905. ** <dd>This option is only available if sqlite is compiled with the
  2906. ** [SQLITE_ENABLE_SQLLOG] pre-processor macro defined. The first argument should
  2907. ** be a pointer to a function of type void(*)(void*,sqlite3*,const char*, int).
  2908. ** The second should be of type (void*). The callback is invoked by the library
  2909. ** in three separate circumstances, identified by the value passed as the
  2910. ** fourth parameter. If the fourth parameter is 0, then the database connection
  2911. ** passed as the second argument has just been opened. The third argument
  2912. ** points to a buffer containing the name of the main database file. If the
  2913. ** fourth parameter is 1, then the SQL statement that the third parameter
  2914. ** points to has just been executed. Or, if the fourth parameter is 2, then
  2915. ** the connection being passed as the second parameter is being closed. The
  2916. ** third parameter is passed NULL In this case. An example of using this
  2917. ** configuration option can be seen in the "test_sqllog.c" source file in
  2918. ** the canonical SQLite source tree.</dd>
  2919. **
  2920. ** [[SQLITE_CONFIG_MMAP_SIZE]]
  2921. ** <dt>SQLITE_CONFIG_MMAP_SIZE
  2922. ** <dd>^SQLITE_CONFIG_MMAP_SIZE takes two 64-bit integer (sqlite3_int64) values
  2923. ** that are the default mmap size limit (the default setting for
  2924. ** [PRAGMA mmap_size]) and the maximum allowed mmap size limit.
  2925. ** ^The default setting can be overridden by each database connection using
  2926. ** either the [PRAGMA mmap_size] command, or by using the
  2927. ** [SQLITE_FCNTL_MMAP_SIZE] file control. ^(The maximum allowed mmap size
  2928. ** will be silently truncated if necessary so that it does not exceed the
  2929. ** compile-time maximum mmap size set by the
  2930. ** [SQLITE_MAX_MMAP_SIZE] compile-time option.)^
  2931. ** ^If either argument to this option is negative, then that argument is
  2932. ** changed to its compile-time default.
  2933. **
  2934. ** [[SQLITE_CONFIG_WIN32_HEAPSIZE]]
  2935. ** <dt>SQLITE_CONFIG_WIN32_HEAPSIZE
  2936. ** <dd>^The SQLITE_CONFIG_WIN32_HEAPSIZE option is only available if SQLite is
  2937. ** compiled for Windows with the [SQLITE_WIN32_MALLOC] pre-processor macro
  2938. ** defined. ^SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit unsigned integer value
  2939. ** that specifies the maximum size of the created heap.
  2940. **
  2941. ** [[SQLITE_CONFIG_PCACHE_HDRSZ]]
  2942. ** <dt>SQLITE_CONFIG_PCACHE_HDRSZ
  2943. ** <dd>^The SQLITE_CONFIG_PCACHE_HDRSZ option takes a single parameter which
  2944. ** is a pointer to an integer and writes into that integer the number of extra
  2945. ** bytes per page required for each page in [SQLITE_CONFIG_PAGECACHE].
  2946. ** The amount of extra space required can change depending on the compiler,
  2947. ** target platform, and SQLite version.
  2948. **
  2949. ** [[SQLITE_CONFIG_PMASZ]]
  2950. ** <dt>SQLITE_CONFIG_PMASZ
  2951. ** <dd>^The SQLITE_CONFIG_PMASZ option takes a single parameter which
  2952. ** is an unsigned integer and sets the "Minimum PMA Size" for the multithreaded
  2953. ** sorter to that integer. The default minimum PMA Size is set by the
  2954. ** [SQLITE_SORTER_PMASZ] compile-time option. New threads are launched
  2955. ** to help with sort operations when multithreaded sorting
  2956. ** is enabled (using the [PRAGMA threads] command) and the amount of content
  2957. ** to be sorted exceeds the page size times the minimum of the
  2958. ** [PRAGMA cache_size] setting and this value.
  2959. **
  2960. ** [[SQLITE_CONFIG_STMTJRNL_SPILL]]
  2961. ** <dt>SQLITE_CONFIG_STMTJRNL_SPILL
  2962. ** <dd>^The SQLITE_CONFIG_STMTJRNL_SPILL option takes a single parameter which
  2963. ** becomes the [statement journal] spill-to-disk threshold.
  2964. ** [Statement journals] are held in memory until their size (in bytes)
  2965. ** exceeds this threshold, at which point they are written to disk.
  2966. ** Or if the threshold is -1, statement journals are always held
  2967. ** exclusively in memory.
  2968. ** Since many statement journals never become large, setting the spill
  2969. ** threshold to a value such as 64KiB can greatly reduce the amount of
  2970. ** I/O required to support statement rollback.
  2971. ** The default value for this setting is controlled by the
  2972. ** [SQLITE_STMTJRNL_SPILL] compile-time option.
  2973. **
  2974. ** [[SQLITE_CONFIG_SORTERREF_SIZE]]
  2975. ** <dt>SQLITE_CONFIG_SORTERREF_SIZE
  2976. ** <dd>The SQLITE_CONFIG_SORTERREF_SIZE option accepts a single parameter
  2977. ** of type (int) - the new value of the sorter-reference size threshold.
  2978. ** Usually, when SQLite uses an external sort to order records according
  2979. ** to an ORDER BY clause, all fields required by the caller are present in the
  2980. ** sorted records. However, if SQLite determines based on the declared type
  2981. ** of a table column that its values are likely to be very large - larger
  2982. ** than the configured sorter-reference size threshold - then a reference
  2983. ** is stored in each sorted record and the required column values loaded
  2984. ** from the database as records are returned in sorted order. The default
  2985. ** value for this option is to never use this optimization. Specifying a
  2986. ** negative value for this option restores the default behaviour.
  2987. ** This option is only available if SQLite is compiled with the
  2988. ** [SQLITE_ENABLE_SORTER_REFERENCES] compile-time option.
  2989. **
  2990. ** [[SQLITE_CONFIG_MEMDB_MAXSIZE]]
  2991. ** <dt>SQLITE_CONFIG_MEMDB_MAXSIZE
  2992. ** <dd>The SQLITE_CONFIG_MEMDB_MAXSIZE option accepts a single parameter
  2993. ** [sqlite3_int64] parameter which is the default maximum size for an in-memory
  2994. ** database created using [sqlite3_deserialize()]. This default maximum
  2995. ** size can be adjusted up or down for individual databases using the
  2996. ** [SQLITE_FCNTL_SIZE_LIMIT] [sqlite3_file_control|file-control]. If this
  2997. ** configuration setting is never used, then the default maximum is determined
  2998. ** by the [SQLITE_MEMDB_DEFAULT_MAXSIZE] compile-time option. If that
  2999. ** compile-time option is not set, then the default maximum is 1073741824.
  3000. ** </dl>
  3001. */
  3002. #define SQLITE_CONFIG_SINGLETHREAD 1 /* nil */
  3003. #define SQLITE_CONFIG_MULTITHREAD 2 /* nil */
  3004. #define SQLITE_CONFIG_SERIALIZED 3 /* nil */
  3005. #define SQLITE_CONFIG_MALLOC 4 /* sqlite3_mem_methods* */
  3006. #define SQLITE_CONFIG_GETMALLOC 5 /* sqlite3_mem_methods* */
  3007. #define SQLITE_CONFIG_SCRATCH 6 /* No longer used */
  3008. #define SQLITE_CONFIG_PAGECACHE 7 /* void*, int sz, int N */
  3009. #define SQLITE_CONFIG_HEAP 8 /* void*, int nByte, int min */
  3010. #define SQLITE_CONFIG_MEMSTATUS 9 /* boolean */
  3011. #define SQLITE_CONFIG_MUTEX 10 /* sqlite3_mutex_methods* */
  3012. #define SQLITE_CONFIG_GETMUTEX 11 /* sqlite3_mutex_methods* */
  3013. /* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */
  3014. #define SQLITE_CONFIG_LOOKASIDE 13 /* int int */
  3015. #define SQLITE_CONFIG_PCACHE 14 /* no-op */
  3016. #define SQLITE_CONFIG_GETPCACHE 15 /* no-op */
  3017. #define SQLITE_CONFIG_LOG 16 /* xFunc, void* */
  3018. #define SQLITE_CONFIG_URI 17 /* int */
  3019. #define SQLITE_CONFIG_PCACHE2 18 /* sqlite3_pcache_methods2* */
  3020. #define SQLITE_CONFIG_GETPCACHE2 19 /* sqlite3_pcache_methods2* */
  3021. #define SQLITE_CONFIG_COVERING_INDEX_SCAN 20 /* int */
  3022. #define SQLITE_CONFIG_SQLLOG 21 /* xSqllog, void* */
  3023. #define SQLITE_CONFIG_MMAP_SIZE 22 /* sqlite3_int64, sqlite3_int64 */
  3024. #define SQLITE_CONFIG_WIN32_HEAPSIZE 23 /* int nByte */
  3025. #define SQLITE_CONFIG_PCACHE_HDRSZ 24 /* int *psz */
  3026. #define SQLITE_CONFIG_PMASZ 25 /* unsigned int szPma */
  3027. #define SQLITE_CONFIG_STMTJRNL_SPILL 26 /* int nByte */
  3028. #define SQLITE_CONFIG_SMALL_MALLOC 27 /* boolean */
  3029. #define SQLITE_CONFIG_SORTERREF_SIZE 28 /* int nByte */
  3030. #define SQLITE_CONFIG_MEMDB_MAXSIZE 29 /* sqlite3_int64 */
  3031. /*
  3032. ** CAPI3REF: Database Connection Configuration Options
  3033. **
  3034. ** These constants are the available integer configuration options that
  3035. ** can be passed as the second argument to the [sqlite3_db_config()] interface.
  3036. **
  3037. ** New configuration options may be added in future releases of SQLite.
  3038. ** Existing configuration options might be discontinued. Applications
  3039. ** should check the return code from [sqlite3_db_config()] to make sure that
  3040. ** the call worked. ^The [sqlite3_db_config()] interface will return a
  3041. ** non-zero [error code] if a discontinued or unsupported configuration option
  3042. ** is invoked.
  3043. **
  3044. ** <dl>
  3045. ** [[SQLITE_DBCONFIG_LOOKASIDE]]
  3046. ** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>
  3047. ** <dd> ^This option takes three additional arguments that determine the
  3048. ** [lookaside memory allocator] configuration for the [database connection].
  3049. ** ^The first argument (the third parameter to [sqlite3_db_config()] is a
  3050. ** pointer to a memory buffer to use for lookaside memory.
  3051. ** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb
  3052. ** may be NULL in which case SQLite will allocate the
  3053. ** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the
  3054. ** size of each lookaside buffer slot. ^The third argument is the number of
  3055. ** slots. The size of the buffer in the first argument must be greater than
  3056. ** or equal to the product of the second and third arguments. The buffer
  3057. ** must be aligned to an 8-byte boundary. ^If the second argument to
  3058. ** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally
  3059. ** rounded down to the next smaller multiple of 8. ^(The lookaside memory
  3060. ** configuration for a database connection can only be changed when that
  3061. ** connection is not currently using lookaside memory, or in other words
  3062. ** when the "current value" returned by
  3063. ** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero.
  3064. ** Any attempt to change the lookaside memory configuration when lookaside
  3065. ** memory is in use leaves the configuration unchanged and returns
  3066. ** [SQLITE_BUSY].)^</dd>
  3067. **
  3068. ** [[SQLITE_DBCONFIG_ENABLE_FKEY]]
  3069. ** <dt>SQLITE_DBCONFIG_ENABLE_FKEY</dt>
  3070. ** <dd> ^This option is used to enable or disable the enforcement of
  3071. ** [foreign key constraints]. There should be two additional arguments.
  3072. ** The first argument is an integer which is 0 to disable FK enforcement,
  3073. ** positive to enable FK enforcement or negative to leave FK enforcement
  3074. ** unchanged. The second parameter is a pointer to an integer into which
  3075. ** is written 0 or 1 to indicate whether FK enforcement is off or on
  3076. ** following this call. The second parameter may be a NULL pointer, in
  3077. ** which case the FK enforcement setting is not reported back. </dd>
  3078. **
  3079. ** [[SQLITE_DBCONFIG_ENABLE_TRIGGER]]
  3080. ** <dt>SQLITE_DBCONFIG_ENABLE_TRIGGER</dt>
  3081. ** <dd> ^This option is used to enable or disable [CREATE TRIGGER | triggers].
  3082. ** There should be two additional arguments.
  3083. ** The first argument is an integer which is 0 to disable triggers,
  3084. ** positive to enable triggers or negative to leave the setting unchanged.
  3085. ** The second parameter is a pointer to an integer into which
  3086. ** is written 0 or 1 to indicate whether triggers are disabled or enabled
  3087. ** following this call. The second parameter may be a NULL pointer, in
  3088. ** which case the trigger setting is not reported back. </dd>
  3089. **
  3090. ** [[SQLITE_DBCONFIG_ENABLE_VIEW]]
  3091. ** <dt>SQLITE_DBCONFIG_ENABLE_VIEW</dt>
  3092. ** <dd> ^This option is used to enable or disable [CREATE VIEW | views].
  3093. ** There should be two additional arguments.
  3094. ** The first argument is an integer which is 0 to disable views,
  3095. ** positive to enable views or negative to leave the setting unchanged.
  3096. ** The second parameter is a pointer to an integer into which
  3097. ** is written 0 or 1 to indicate whether views are disabled or enabled
  3098. ** following this call. The second parameter may be a NULL pointer, in
  3099. ** which case the view setting is not reported back. </dd>
  3100. **
  3101. ** [[SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER]]
  3102. ** <dt>SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER</dt>
  3103. ** <dd> ^This option is used to enable or disable the
  3104. ** [fts3_tokenizer()] function which is part of the
  3105. ** [FTS3] full-text search engine extension.
  3106. ** There should be two additional arguments.
  3107. ** The first argument is an integer which is 0 to disable fts3_tokenizer() or
  3108. ** positive to enable fts3_tokenizer() or negative to leave the setting
  3109. ** unchanged.
  3110. ** The second parameter is a pointer to an integer into which
  3111. ** is written 0 or 1 to indicate whether fts3_tokenizer is disabled or enabled
  3112. ** following this call. The second parameter may be a NULL pointer, in
  3113. ** which case the new setting is not reported back. </dd>
  3114. **
  3115. ** [[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION]]
  3116. ** <dt>SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION</dt>
  3117. ** <dd> ^This option is used to enable or disable the [sqlite3_load_extension()]
  3118. ** interface independently of the [load_extension()] SQL function.
  3119. ** The [sqlite3_enable_load_extension()] API enables or disables both the
  3120. ** C-API [sqlite3_load_extension()] and the SQL function [load_extension()].
  3121. ** There should be two additional arguments.
  3122. ** When the first argument to this interface is 1, then only the C-API is
  3123. ** enabled and the SQL function remains disabled. If the first argument to
  3124. ** this interface is 0, then both the C-API and the SQL function are disabled.
  3125. ** If the first argument is -1, then no changes are made to state of either the
  3126. ** C-API or the SQL function.
  3127. ** The second parameter is a pointer to an integer into which
  3128. ** is written 0 or 1 to indicate whether [sqlite3_load_extension()] interface
  3129. ** is disabled or enabled following this call. The second parameter may
  3130. ** be a NULL pointer, in which case the new setting is not reported back.
  3131. ** </dd>
  3132. **
  3133. ** [[SQLITE_DBCONFIG_MAINDBNAME]] <dt>SQLITE_DBCONFIG_MAINDBNAME</dt>
  3134. ** <dd> ^This option is used to change the name of the "main" database
  3135. ** schema. ^The sole argument is a pointer to a constant UTF8 string
  3136. ** which will become the new schema name in place of "main". ^SQLite
  3137. ** does not make a copy of the new main schema name string, so the application
  3138. ** must ensure that the argument passed into this DBCONFIG option is unchanged
  3139. ** until after the database connection closes.
  3140. ** </dd>
  3141. **
  3142. ** [[SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE]]
  3143. ** <dt>SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE</dt>
  3144. ** <dd> Usually, when a database in wal mode is closed or detached from a
  3145. ** database handle, SQLite checks if this will mean that there are now no
  3146. ** connections at all to the database. If so, it performs a checkpoint
  3147. ** operation before closing the connection. This option may be used to
  3148. ** override this behaviour. The first parameter passed to this operation
  3149. ** is an integer - positive to disable checkpoints-on-close, or zero (the
  3150. ** default) to enable them, and negative to leave the setting unchanged.
  3151. ** The second parameter is a pointer to an integer
  3152. ** into which is written 0 or 1 to indicate whether checkpoints-on-close
  3153. ** have been disabled - 0 if they are not disabled, 1 if they are.
  3154. ** </dd>
  3155. **
  3156. ** [[SQLITE_DBCONFIG_ENABLE_QPSG]] <dt>SQLITE_DBCONFIG_ENABLE_QPSG</dt>
  3157. ** <dd>^(The SQLITE_DBCONFIG_ENABLE_QPSG option activates or deactivates
  3158. ** the [query planner stability guarantee] (QPSG). When the QPSG is active,
  3159. ** a single SQL query statement will always use the same algorithm regardless
  3160. ** of values of [bound parameters].)^ The QPSG disables some query optimizations
  3161. ** that look at the values of bound parameters, which can make some queries
  3162. ** slower. But the QPSG has the advantage of more predictable behavior. With
  3163. ** the QPSG active, SQLite will always use the same query plan in the field as
  3164. ** was used during testing in the lab.
  3165. ** The first argument to this setting is an integer which is 0 to disable
  3166. ** the QPSG, positive to enable QPSG, or negative to leave the setting
  3167. ** unchanged. The second parameter is a pointer to an integer into which
  3168. ** is written 0 or 1 to indicate whether the QPSG is disabled or enabled
  3169. ** following this call.
  3170. ** </dd>
  3171. **
  3172. ** [[SQLITE_DBCONFIG_TRIGGER_EQP]] <dt>SQLITE_DBCONFIG_TRIGGER_EQP</dt>
  3173. ** <dd> By default, the output of EXPLAIN QUERY PLAN commands does not
  3174. ** include output for any operations performed by trigger programs. This
  3175. ** option is used to set or clear (the default) a flag that governs this
  3176. ** behavior. The first parameter passed to this operation is an integer -
  3177. ** positive to enable output for trigger programs, or zero to disable it,
  3178. ** or negative to leave the setting unchanged.
  3179. ** The second parameter is a pointer to an integer into which is written
  3180. ** 0 or 1 to indicate whether output-for-triggers has been disabled - 0 if
  3181. ** it is not disabled, 1 if it is.
  3182. ** </dd>
  3183. **
  3184. ** [[SQLITE_DBCONFIG_RESET_DATABASE]] <dt>SQLITE_DBCONFIG_RESET_DATABASE</dt>
  3185. ** <dd> Set the SQLITE_DBCONFIG_RESET_DATABASE flag and then run
  3186. ** [VACUUM] in order to reset a database back to an empty database
  3187. ** with no schema and no content. The following process works even for
  3188. ** a badly corrupted database file:
  3189. ** <ol>
  3190. ** <li> If the database connection is newly opened, make sure it has read the
  3191. ** database schema by preparing then discarding some query against the
  3192. ** database, or calling sqlite3_table_column_metadata(), ignoring any
  3193. ** errors. This step is only necessary if the application desires to keep
  3194. ** the database in WAL mode after the reset if it was in WAL mode before
  3195. ** the reset.
  3196. ** <li> sqlite3_db_config(db, SQLITE_DBCONFIG_RESET_DATABASE, 1, 0);
  3197. ** <li> [sqlite3_exec](db, "[VACUUM]", 0, 0, 0);
  3198. ** <li> sqlite3_db_config(db, SQLITE_DBCONFIG_RESET_DATABASE, 0, 0);
  3199. ** </ol>
  3200. ** Because resetting a database is destructive and irreversible, the
  3201. ** process requires the use of this obscure API and multiple steps to help
  3202. ** ensure that it does not happen by accident.
  3203. **
  3204. ** [[SQLITE_DBCONFIG_DEFENSIVE]] <dt>SQLITE_DBCONFIG_DEFENSIVE</dt>
  3205. ** <dd>The SQLITE_DBCONFIG_DEFENSIVE option activates or deactivates the
  3206. ** "defensive" flag for a database connection. When the defensive
  3207. ** flag is enabled, language features that allow ordinary SQL to
  3208. ** deliberately corrupt the database file are disabled. The disabled
  3209. ** features include but are not limited to the following:
  3210. ** <ul>
  3211. ** <li> The [PRAGMA writable_schema=ON] statement.
  3212. ** <li> The [PRAGMA journal_mode=OFF] statement.
  3213. ** <li> Writes to the [sqlite_dbpage] virtual table.
  3214. ** <li> Direct writes to [shadow tables].
  3215. ** </ul>
  3216. ** </dd>
  3217. **
  3218. ** [[SQLITE_DBCONFIG_WRITABLE_SCHEMA]] <dt>SQLITE_DBCONFIG_WRITABLE_SCHEMA</dt>
  3219. ** <dd>The SQLITE_DBCONFIG_WRITABLE_SCHEMA option activates or deactivates the
  3220. ** "writable_schema" flag. This has the same effect and is logically equivalent
  3221. ** to setting [PRAGMA writable_schema=ON] or [PRAGMA writable_schema=OFF].
  3222. ** The first argument to this setting is an integer which is 0 to disable
  3223. ** the writable_schema, positive to enable writable_schema, or negative to
  3224. ** leave the setting unchanged. The second parameter is a pointer to an
  3225. ** integer into which is written 0 or 1 to indicate whether the writable_schema
  3226. ** is enabled or disabled following this call.
  3227. ** </dd>
  3228. **
  3229. ** [[SQLITE_DBCONFIG_LEGACY_ALTER_TABLE]]
  3230. ** <dt>SQLITE_DBCONFIG_LEGACY_ALTER_TABLE</dt>
  3231. ** <dd>The SQLITE_DBCONFIG_LEGACY_ALTER_TABLE option activates or deactivates
  3232. ** the legacy behavior of the [ALTER TABLE RENAME] command such it
  3233. ** behaves as it did prior to [version 3.24.0] (2018-06-04). See the
  3234. ** "Compatibility Notice" on the [ALTER TABLE RENAME documentation] for
  3235. ** additional information. This feature can also be turned on and off
  3236. ** using the [PRAGMA legacy_alter_table] statement.
  3237. ** </dd>
  3238. **
  3239. ** [[SQLITE_DBCONFIG_DQS_DML]]
  3240. ** <dt>SQLITE_DBCONFIG_DQS_DML</td>
  3241. ** <dd>The SQLITE_DBCONFIG_DQS_DML option activates or deactivates
  3242. ** the legacy [double-quoted string literal] misfeature for DML statements
  3243. ** only, that is DELETE, INSERT, SELECT, and UPDATE statements. The
  3244. ** default value of this setting is determined by the [-DSQLITE_DQS]
  3245. ** compile-time option.
  3246. ** </dd>
  3247. **
  3248. ** [[SQLITE_DBCONFIG_DQS_DDL]]
  3249. ** <dt>SQLITE_DBCONFIG_DQS_DDL</td>
  3250. ** <dd>The SQLITE_DBCONFIG_DQS option activates or deactivates
  3251. ** the legacy [double-quoted string literal] misfeature for DDL statements,
  3252. ** such as CREATE TABLE and CREATE INDEX. The
  3253. ** default value of this setting is determined by the [-DSQLITE_DQS]
  3254. ** compile-time option.
  3255. ** </dd>
  3256. **
  3257. ** [[SQLITE_DBCONFIG_TRUSTED_SCHEMA]]
  3258. ** <dt>SQLITE_DBCONFIG_TRUSTED_SCHEMA</td>
  3259. ** <dd>The SQLITE_DBCONFIG_TRUSTED_SCHEMA option tells SQLite to
  3260. ** assume that database schemas (the contents of the [sqlite_master] tables)
  3261. ** are untainted by malicious content.
  3262. ** When the SQLITE_DBCONFIG_TRUSTED_SCHEMA option is disabled, SQLite
  3263. ** takes additional defensive steps to protect the application from harm
  3264. ** including:
  3265. ** <ul>
  3266. ** <li> Prohibit the use of SQL functions inside triggers, views,
  3267. ** CHECK constraints, DEFAULT clauses, expression indexes,
  3268. ** partial indexes, or generated columns
  3269. ** unless those functions are tagged with [SQLITE_INNOCUOUS].
  3270. ** <li> Prohibit the use of virtual tables inside of triggers or views
  3271. ** unless those virtual tables are tagged with [SQLITE_VTAB_INNOCUOUS].
  3272. ** </ul>
  3273. ** This setting defaults to "on" for legacy compatibility, however
  3274. ** all applications are advised to turn it off if possible. This setting
  3275. ** can also be controlled using the [PRAGMA trusted_schema] statement.
  3276. ** </dd>
  3277. **
  3278. ** [[SQLITE_DBCONFIG_LEGACY_FILE_FORMAT]]
  3279. ** <dt>SQLITE_DBCONFIG_LEGACY_FILE_FORMAT</td>
  3280. ** <dd>The SQLITE_DBCONFIG_LEGACY_FILE_FORMAT option activates or deactivates
  3281. ** the legacy file format flag. When activated, this flag causes all newly
  3282. ** created database file to have a schema format version number (the 4-byte
  3283. ** integer found at offset 44 into the database header) of 1. This in turn
  3284. ** means that the resulting database file will be readable and writable by
  3285. ** any SQLite version back to 3.0.0 ([dateof:3.0.0]). Without this setting,
  3286. ** newly created databases are generally not understandable by SQLite versions
  3287. ** prior to 3.3.0 ([dateof:3.3.0]). As these words are written, there
  3288. ** is now scarcely any need to generated database files that are compatible
  3289. ** all the way back to version 3.0.0, and so this setting is of little
  3290. ** practical use, but is provided so that SQLite can continue to claim the
  3291. ** ability to generate new database files that are compatible with version
  3292. ** 3.0.0.
  3293. ** <p>Note that when the SQLITE_DBCONFIG_LEGACY_FILE_FORMAT setting is on,
  3294. ** the [VACUUM] command will fail with an obscure error when attempting to
  3295. ** process a table with generated columns and a descending index. This is
  3296. ** not considered a bug since SQLite versions 3.3.0 and earlier do not support
  3297. ** either generated columns or decending indexes.
  3298. ** </dd>
  3299. ** </dl>
  3300. */
  3301. #define SQLITE_DBCONFIG_MAINDBNAME 1000 /* const char* */
  3302. #define SQLITE_DBCONFIG_LOOKASIDE 1001 /* void* int int */
  3303. #define SQLITE_DBCONFIG_ENABLE_FKEY 1002 /* int int* */
  3304. #define SQLITE_DBCONFIG_ENABLE_TRIGGER 1003 /* int int* */
  3305. #define SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER 1004 /* int int* */
  3306. #define SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION 1005 /* int int* */
  3307. #define SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE 1006 /* int int* */
  3308. #define SQLITE_DBCONFIG_ENABLE_QPSG 1007 /* int int* */
  3309. #define SQLITE_DBCONFIG_TRIGGER_EQP 1008 /* int int* */
  3310. #define SQLITE_DBCONFIG_RESET_DATABASE 1009 /* int int* */
  3311. #define SQLITE_DBCONFIG_DEFENSIVE 1010 /* int int* */
  3312. #define SQLITE_DBCONFIG_WRITABLE_SCHEMA 1011 /* int int* */
  3313. #define SQLITE_DBCONFIG_LEGACY_ALTER_TABLE 1012 /* int int* */
  3314. #define SQLITE_DBCONFIG_DQS_DML 1013 /* int int* */
  3315. #define SQLITE_DBCONFIG_DQS_DDL 1014 /* int int* */
  3316. #define SQLITE_DBCONFIG_ENABLE_VIEW 1015 /* int int* */
  3317. #define SQLITE_DBCONFIG_LEGACY_FILE_FORMAT 1016 /* int int* */
  3318. #define SQLITE_DBCONFIG_TRUSTED_SCHEMA 1017 /* int int* */
  3319. #define SQLITE_DBCONFIG_MAX 1017 /* Largest DBCONFIG */
  3320. /*
  3321. ** CAPI3REF: Enable Or Disable Extended Result Codes
  3322. ** METHOD: sqlite3
  3323. **
  3324. ** ^The sqlite3_extended_result_codes() routine enables or disables the
  3325. ** [extended result codes] feature of SQLite. ^The extended result
  3326. ** codes are disabled by default for historical compatibility.
  3327. */
  3328. SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff);
  3329. /*
  3330. ** CAPI3REF: Last Insert Rowid
  3331. ** METHOD: sqlite3
  3332. **
  3333. ** ^Each entry in most SQLite tables (except for [WITHOUT ROWID] tables)
  3334. ** has a unique 64-bit signed
  3335. ** integer key called the [ROWID | "rowid"]. ^The rowid is always available
  3336. ** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
  3337. ** names are not also used by explicitly declared columns. ^If
  3338. ** the table has a column of type [INTEGER PRIMARY KEY] then that column
  3339. ** is another alias for the rowid.
  3340. **
  3341. ** ^The sqlite3_last_insert_rowid(D) interface usually returns the [rowid] of
  3342. ** the most recent successful [INSERT] into a rowid table or [virtual table]
  3343. ** on database connection D. ^Inserts into [WITHOUT ROWID] tables are not
  3344. ** recorded. ^If no successful [INSERT]s into rowid tables have ever occurred
  3345. ** on the database connection D, then sqlite3_last_insert_rowid(D) returns
  3346. ** zero.
  3347. **
  3348. ** As well as being set automatically as rows are inserted into database
  3349. ** tables, the value returned by this function may be set explicitly by
  3350. ** [sqlite3_set_last_insert_rowid()]
  3351. **
  3352. ** Some virtual table implementations may INSERT rows into rowid tables as
  3353. ** part of committing a transaction (e.g. to flush data accumulated in memory
  3354. ** to disk). In this case subsequent calls to this function return the rowid
  3355. ** associated with these internal INSERT operations, which leads to
  3356. ** unintuitive results. Virtual table implementations that do write to rowid
  3357. ** tables in this way can avoid this problem by restoring the original
  3358. ** rowid value using [sqlite3_set_last_insert_rowid()] before returning
  3359. ** control to the user.
  3360. **
  3361. ** ^(If an [INSERT] occurs within a trigger then this routine will
  3362. ** return the [rowid] of the inserted row as long as the trigger is
  3363. ** running. Once the trigger program ends, the value returned
  3364. ** by this routine reverts to what it was before the trigger was fired.)^
  3365. **
  3366. ** ^An [INSERT] that fails due to a constraint violation is not a
  3367. ** successful [INSERT] and does not change the value returned by this
  3368. ** routine. ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
  3369. ** and INSERT OR ABORT make no changes to the return value of this
  3370. ** routine when their insertion fails. ^(When INSERT OR REPLACE
  3371. ** encounters a constraint violation, it does not fail. The
  3372. ** INSERT continues to completion after deleting rows that caused
  3373. ** the constraint problem so INSERT OR REPLACE will always change
  3374. ** the return value of this interface.)^
  3375. **
  3376. ** ^For the purposes of this routine, an [INSERT] is considered to
  3377. ** be successful even if it is subsequently rolled back.
  3378. **
  3379. ** This function is accessible to SQL statements via the
  3380. ** [last_insert_rowid() SQL function].
  3381. **
  3382. ** If a separate thread performs a new [INSERT] on the same
  3383. ** database connection while the [sqlite3_last_insert_rowid()]
  3384. ** function is running and thus changes the last insert [rowid],
  3385. ** then the value returned by [sqlite3_last_insert_rowid()] is
  3386. ** unpredictable and might not equal either the old or the new
  3387. ** last insert [rowid].
  3388. */
  3389. SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
  3390. /*
  3391. ** CAPI3REF: Set the Last Insert Rowid value.
  3392. ** METHOD: sqlite3
  3393. **
  3394. ** The sqlite3_set_last_insert_rowid(D, R) method allows the application to
  3395. ** set the value returned by calling sqlite3_last_insert_rowid(D) to R
  3396. ** without inserting a row into the database.
  3397. */
  3398. SQLITE_API void sqlite3_set_last_insert_rowid(sqlite3*,sqlite3_int64);
  3399. /*
  3400. ** CAPI3REF: Count The Number Of Rows Modified
  3401. ** METHOD: sqlite3
  3402. **
  3403. ** ^This function returns the number of rows modified, inserted or
  3404. ** deleted by the most recently completed INSERT, UPDATE or DELETE
  3405. ** statement on the database connection specified by the only parameter.
  3406. ** ^Executing any other type of SQL statement does not modify the value
  3407. ** returned by this function.
  3408. **
  3409. ** ^Only changes made directly by the INSERT, UPDATE or DELETE statement are
  3410. ** considered - auxiliary changes caused by [CREATE TRIGGER | triggers],
  3411. ** [foreign key actions] or [REPLACE] constraint resolution are not counted.
  3412. **
  3413. ** Changes to a view that are intercepted by
  3414. ** [INSTEAD OF trigger | INSTEAD OF triggers] are not counted. ^The value
  3415. ** returned by sqlite3_changes() immediately after an INSERT, UPDATE or
  3416. ** DELETE statement run on a view is always zero. Only changes made to real
  3417. ** tables are counted.
  3418. **
  3419. ** Things are more complicated if the sqlite3_changes() function is
  3420. ** executed while a trigger program is running. This may happen if the
  3421. ** program uses the [changes() SQL function], or if some other callback
  3422. ** function invokes sqlite3_changes() directly. Essentially:
  3423. **
  3424. ** <ul>
  3425. ** <li> ^(Before entering a trigger program the value returned by
  3426. ** sqlite3_changes() function is saved. After the trigger program
  3427. ** has finished, the original value is restored.)^
  3428. **
  3429. ** <li> ^(Within a trigger program each INSERT, UPDATE and DELETE
  3430. ** statement sets the value returned by sqlite3_changes()
  3431. ** upon completion as normal. Of course, this value will not include
  3432. ** any changes performed by sub-triggers, as the sqlite3_changes()
  3433. ** value will be saved and restored after each sub-trigger has run.)^
  3434. ** </ul>
  3435. **
  3436. ** ^This means that if the changes() SQL function (or similar) is used
  3437. ** by the first INSERT, UPDATE or DELETE statement within a trigger, it
  3438. ** returns the value as set when the calling statement began executing.
  3439. ** ^If it is used by the second or subsequent such statement within a trigger
  3440. ** program, the value returned reflects the number of rows modified by the
  3441. ** previous INSERT, UPDATE or DELETE statement within the same trigger.
  3442. **
  3443. ** If a separate thread makes changes on the same database connection
  3444. ** while [sqlite3_changes()] is running then the value returned
  3445. ** is unpredictable and not meaningful.
  3446. **
  3447. ** See also:
  3448. ** <ul>
  3449. ** <li> the [sqlite3_total_changes()] interface
  3450. ** <li> the [count_changes pragma]
  3451. ** <li> the [changes() SQL function]
  3452. ** <li> the [data_version pragma]
  3453. ** </ul>
  3454. */
  3455. SQLITE_API int sqlite3_changes(sqlite3*);
  3456. /*
  3457. ** CAPI3REF: Total Number Of Rows Modified
  3458. ** METHOD: sqlite3
  3459. **
  3460. ** ^This function returns the total number of rows inserted, modified or
  3461. ** deleted by all [INSERT], [UPDATE] or [DELETE] statements completed
  3462. ** since the database connection was opened, including those executed as
  3463. ** part of trigger programs. ^Executing any other type of SQL statement
  3464. ** does not affect the value returned by sqlite3_total_changes().
  3465. **
  3466. ** ^Changes made as part of [foreign key actions] are included in the
  3467. ** count, but those made as part of REPLACE constraint resolution are
  3468. ** not. ^Changes to a view that are intercepted by INSTEAD OF triggers
  3469. ** are not counted.
  3470. **
  3471. ** The [sqlite3_total_changes(D)] interface only reports the number
  3472. ** of rows that changed due to SQL statement run against database
  3473. ** connection D. Any changes by other database connections are ignored.
  3474. ** To detect changes against a database file from other database
  3475. ** connections use the [PRAGMA data_version] command or the
  3476. ** [SQLITE_FCNTL_DATA_VERSION] [file control].
  3477. **
  3478. ** If a separate thread makes changes on the same database connection
  3479. ** while [sqlite3_total_changes()] is running then the value
  3480. ** returned is unpredictable and not meaningful.
  3481. **
  3482. ** See also:
  3483. ** <ul>
  3484. ** <li> the [sqlite3_changes()] interface
  3485. ** <li> the [count_changes pragma]
  3486. ** <li> the [changes() SQL function]
  3487. ** <li> the [data_version pragma]
  3488. ** <li> the [SQLITE_FCNTL_DATA_VERSION] [file control]
  3489. ** </ul>
  3490. */
  3491. SQLITE_API int sqlite3_total_changes(sqlite3*);
  3492. /*
  3493. ** CAPI3REF: Interrupt A Long-Running Query
  3494. ** METHOD: sqlite3
  3495. **
  3496. ** ^This function causes any pending database operation to abort and
  3497. ** return at its earliest opportunity. This routine is typically
  3498. ** called in response to a user action such as pressing "Cancel"
  3499. ** or Ctrl-C where the user wants a long query operation to halt
  3500. ** immediately.
  3501. **
  3502. ** ^It is safe to call this routine from a thread different from the
  3503. ** thread that is currently running the database operation. But it
  3504. ** is not safe to call this routine with a [database connection] that
  3505. ** is closed or might close before sqlite3_interrupt() returns.
  3506. **
  3507. ** ^If an SQL operation is very nearly finished at the time when
  3508. ** sqlite3_interrupt() is called, then it might not have an opportunity
  3509. ** to be interrupted and might continue to completion.
  3510. **
  3511. ** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
  3512. ** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
  3513. ** that is inside an explicit transaction, then the entire transaction
  3514. ** will be rolled back automatically.
  3515. **
  3516. ** ^The sqlite3_interrupt(D) call is in effect until all currently running
  3517. ** SQL statements on [database connection] D complete. ^Any new SQL statements
  3518. ** that are started after the sqlite3_interrupt() call and before the
  3519. ** running statement count reaches zero are interrupted as if they had been
  3520. ** running prior to the sqlite3_interrupt() call. ^New SQL statements
  3521. ** that are started after the running statement count reaches zero are
  3522. ** not effected by the sqlite3_interrupt().
  3523. ** ^A call to sqlite3_interrupt(D) that occurs when there are no running
  3524. ** SQL statements is a no-op and has no effect on SQL statements
  3525. ** that are started after the sqlite3_interrupt() call returns.
  3526. */
  3527. SQLITE_API void sqlite3_interrupt(sqlite3*);
  3528. /*
  3529. ** CAPI3REF: Determine If An SQL Statement Is Complete
  3530. **
  3531. ** These routines are useful during command-line input to determine if the
  3532. ** currently entered text seems to form a complete SQL statement or
  3533. ** if additional input is needed before sending the text into
  3534. ** SQLite for parsing. ^These routines return 1 if the input string
  3535. ** appears to be a complete SQL statement. ^A statement is judged to be
  3536. ** complete if it ends with a semicolon token and is not a prefix of a
  3537. ** well-formed CREATE TRIGGER statement. ^Semicolons that are embedded within
  3538. ** string literals or quoted identifier names or comments are not
  3539. ** independent tokens (they are part of the token in which they are
  3540. ** embedded) and thus do not count as a statement terminator. ^Whitespace
  3541. ** and comments that follow the final semicolon are ignored.
  3542. **
  3543. ** ^These routines return 0 if the statement is incomplete. ^If a
  3544. ** memory allocation fails, then SQLITE_NOMEM is returned.
  3545. **
  3546. ** ^These routines do not parse the SQL statements thus
  3547. ** will not detect syntactically incorrect SQL.
  3548. **
  3549. ** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior
  3550. ** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked
  3551. ** automatically by sqlite3_complete16(). If that initialization fails,
  3552. ** then the return value from sqlite3_complete16() will be non-zero
  3553. ** regardless of whether or not the input SQL is complete.)^
  3554. **
  3555. ** The input to [sqlite3_complete()] must be a zero-terminated
  3556. ** UTF-8 string.
  3557. **
  3558. ** The input to [sqlite3_complete16()] must be a zero-terminated
  3559. ** UTF-16 string in native byte order.
  3560. */
  3561. SQLITE_API int sqlite3_complete(const char *sql);
  3562. SQLITE_API int sqlite3_complete16(const void *sql);
  3563. /*
  3564. ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors
  3565. ** KEYWORDS: {busy-handler callback} {busy handler}
  3566. ** METHOD: sqlite3
  3567. **
  3568. ** ^The sqlite3_busy_handler(D,X,P) routine sets a callback function X
  3569. ** that might be invoked with argument P whenever
  3570. ** an attempt is made to access a database table associated with
  3571. ** [database connection] D when another thread
  3572. ** or process has the table locked.
  3573. ** The sqlite3_busy_handler() interface is used to implement
  3574. ** [sqlite3_busy_timeout()] and [PRAGMA busy_timeout].
  3575. **
  3576. ** ^If the busy callback is NULL, then [SQLITE_BUSY]
  3577. ** is returned immediately upon encountering the lock. ^If the busy callback
  3578. ** is not NULL, then the callback might be invoked with two arguments.
  3579. **
  3580. ** ^The first argument to the busy handler is a copy of the void* pointer which
  3581. ** is the third argument to sqlite3_busy_handler(). ^The second argument to
  3582. ** the busy handler callback is the number of times that the busy handler has
  3583. ** been invoked previously for the same locking event. ^If the
  3584. ** busy callback returns 0, then no additional attempts are made to
  3585. ** access the database and [SQLITE_BUSY] is returned
  3586. ** to the application.
  3587. ** ^If the callback returns non-zero, then another attempt
  3588. ** is made to access the database and the cycle repeats.
  3589. **
  3590. ** The presence of a busy handler does not guarantee that it will be invoked
  3591. ** when there is lock contention. ^If SQLite determines that invoking the busy
  3592. ** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]
  3593. ** to the application instead of invoking the
  3594. ** busy handler.
  3595. ** Consider a scenario where one process is holding a read lock that
  3596. ** it is trying to promote to a reserved lock and
  3597. ** a second process is holding a reserved lock that it is trying
  3598. ** to promote to an exclusive lock. The first process cannot proceed
  3599. ** because it is blocked by the second and the second process cannot
  3600. ** proceed because it is blocked by the first. If both processes
  3601. ** invoke the busy handlers, neither will make any progress. Therefore,
  3602. ** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
  3603. ** will induce the first process to release its read lock and allow
  3604. ** the second process to proceed.
  3605. **
  3606. ** ^The default busy callback is NULL.
  3607. **
  3608. ** ^(There can only be a single busy handler defined for each
  3609. ** [database connection]. Setting a new busy handler clears any
  3610. ** previously set handler.)^ ^Note that calling [sqlite3_busy_timeout()]
  3611. ** or evaluating [PRAGMA busy_timeout=N] will change the
  3612. ** busy handler and thus clear any previously set busy handler.
  3613. **
  3614. ** The busy callback should not take any actions which modify the
  3615. ** database connection that invoked the busy handler. In other words,
  3616. ** the busy handler is not reentrant. Any such actions
  3617. ** result in undefined behavior.
  3618. **
  3619. ** A busy handler must not close the database connection
  3620. ** or [prepared statement] that invoked the busy handler.
  3621. */
  3622. SQLITE_API int sqlite3_busy_handler(sqlite3*,int(*)(void*,int),void*);
  3623. /*
  3624. ** CAPI3REF: Set A Busy Timeout
  3625. ** METHOD: sqlite3
  3626. **
  3627. ** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps
  3628. ** for a specified amount of time when a table is locked. ^The handler
  3629. ** will sleep multiple times until at least "ms" milliseconds of sleeping
  3630. ** have accumulated. ^After at least "ms" milliseconds of sleeping,
  3631. ** the handler returns 0 which causes [sqlite3_step()] to return
  3632. ** [SQLITE_BUSY].
  3633. **
  3634. ** ^Calling this routine with an argument less than or equal to zero
  3635. ** turns off all busy handlers.
  3636. **
  3637. ** ^(There can only be a single busy handler for a particular
  3638. ** [database connection] at any given moment. If another busy handler
  3639. ** was defined (using [sqlite3_busy_handler()]) prior to calling
  3640. ** this routine, that other busy handler is cleared.)^
  3641. **
  3642. ** See also: [PRAGMA busy_timeout]
  3643. */
  3644. SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);
  3645. /*
  3646. ** CAPI3REF: Convenience Routines For Running Queries
  3647. ** METHOD: sqlite3
  3648. **
  3649. ** This is a legacy interface that is preserved for backwards compatibility.
  3650. ** Use of this interface is not recommended.
  3651. **
  3652. ** Definition: A <b>result table</b> is memory data structure created by the
  3653. ** [sqlite3_get_table()] interface. A result table records the
  3654. ** complete query results from one or more queries.
  3655. **
  3656. ** The table conceptually has a number of rows and columns. But
  3657. ** these numbers are not part of the result table itself. These
  3658. ** numbers are obtained separately. Let N be the number of rows
  3659. ** and M be the number of columns.
  3660. **
  3661. ** A result table is an array of pointers to zero-terminated UTF-8 strings.
  3662. ** There are (N+1)*M elements in the array. The first M pointers point
  3663. ** to zero-terminated strings that contain the names of the columns.
  3664. ** The remaining entries all point to query results. NULL values result
  3665. ** in NULL pointers. All other values are in their UTF-8 zero-terminated
  3666. ** string representation as returned by [sqlite3_column_text()].
  3667. **
  3668. ** A result table might consist of one or more memory allocations.
  3669. ** It is not safe to pass a result table directly to [sqlite3_free()].
  3670. ** A result table should be deallocated using [sqlite3_free_table()].
  3671. **
  3672. ** ^(As an example of the result table format, suppose a query result
  3673. ** is as follows:
  3674. **
  3675. ** <blockquote><pre>
  3676. ** Name | Age
  3677. ** -----------------------
  3678. ** Alice | 43
  3679. ** Bob | 28
  3680. ** Cindy | 21
  3681. ** </pre></blockquote>
  3682. **
  3683. ** There are two columns (M==2) and three rows (N==3). Thus the
  3684. ** result table has 8 entries. Suppose the result table is stored
  3685. ** in an array named azResult. Then azResult holds this content:
  3686. **
  3687. ** <blockquote><pre>
  3688. ** azResult&#91;0] = "Name";
  3689. ** azResult&#91;1] = "Age";
  3690. ** azResult&#91;2] = "Alice";
  3691. ** azResult&#91;3] = "43";
  3692. ** azResult&#91;4] = "Bob";
  3693. ** azResult&#91;5] = "28";
  3694. ** azResult&#91;6] = "Cindy";
  3695. ** azResult&#91;7] = "21";
  3696. ** </pre></blockquote>)^
  3697. **
  3698. ** ^The sqlite3_get_table() function evaluates one or more
  3699. ** semicolon-separated SQL statements in the zero-terminated UTF-8
  3700. ** string of its 2nd parameter and returns a result table to the
  3701. ** pointer given in its 3rd parameter.
  3702. **
  3703. ** After the application has finished with the result from sqlite3_get_table(),
  3704. ** it must pass the result table pointer to sqlite3_free_table() in order to
  3705. ** release the memory that was malloced. Because of the way the
  3706. ** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
  3707. ** function must not try to call [sqlite3_free()] directly. Only
  3708. ** [sqlite3_free_table()] is able to release the memory properly and safely.
  3709. **
  3710. ** The sqlite3_get_table() interface is implemented as a wrapper around
  3711. ** [sqlite3_exec()]. The sqlite3_get_table() routine does not have access
  3712. ** to any internal data structures of SQLite. It uses only the public
  3713. ** interface defined here. As a consequence, errors that occur in the
  3714. ** wrapper layer outside of the internal [sqlite3_exec()] call are not
  3715. ** reflected in subsequent calls to [sqlite3_errcode()] or
  3716. ** [sqlite3_errmsg()].
  3717. */
  3718. SQLITE_API int sqlite3_get_table(
  3719. sqlite3 *db, /* An open database */
  3720. const char *zSql, /* SQL to be evaluated */
  3721. char ***pazResult, /* Results of the query */
  3722. int *pnRow, /* Number of result rows written here */
  3723. int *pnColumn, /* Number of result columns written here */
  3724. char **pzErrmsg /* Error msg written here */
  3725. );
  3726. SQLITE_API void sqlite3_free_table(char **result);
  3727. /*
  3728. ** CAPI3REF: Formatted String Printing Functions
  3729. **
  3730. ** These routines are work-alikes of the "printf()" family of functions
  3731. ** from the standard C library.
  3732. ** These routines understand most of the common formatting options from
  3733. ** the standard library printf()
  3734. ** plus some additional non-standard formats ([%q], [%Q], [%w], and [%z]).
  3735. ** See the [built-in printf()] documentation for details.
  3736. **
  3737. ** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
  3738. ** results into memory obtained from [sqlite3_malloc64()].
  3739. ** The strings returned by these two routines should be
  3740. ** released by [sqlite3_free()]. ^Both routines return a
  3741. ** NULL pointer if [sqlite3_malloc64()] is unable to allocate enough
  3742. ** memory to hold the resulting string.
  3743. **
  3744. ** ^(The sqlite3_snprintf() routine is similar to "snprintf()" from
  3745. ** the standard C library. The result is written into the
  3746. ** buffer supplied as the second parameter whose size is given by
  3747. ** the first parameter. Note that the order of the
  3748. ** first two parameters is reversed from snprintf().)^ This is an
  3749. ** historical accident that cannot be fixed without breaking
  3750. ** backwards compatibility. ^(Note also that sqlite3_snprintf()
  3751. ** returns a pointer to its buffer instead of the number of
  3752. ** characters actually written into the buffer.)^ We admit that
  3753. ** the number of characters written would be a more useful return
  3754. ** value but we cannot change the implementation of sqlite3_snprintf()
  3755. ** now without breaking compatibility.
  3756. **
  3757. ** ^As long as the buffer size is greater than zero, sqlite3_snprintf()
  3758. ** guarantees that the buffer is always zero-terminated. ^The first
  3759. ** parameter "n" is the total size of the buffer, including space for
  3760. ** the zero terminator. So the longest string that can be completely
  3761. ** written will be n-1 characters.
  3762. **
  3763. ** ^The sqlite3_vsnprintf() routine is a varargs version of sqlite3_snprintf().
  3764. **
  3765. ** See also: [built-in printf()], [printf() SQL function]
  3766. */
  3767. SQLITE_API char *sqlite3_mprintf(const char*,...);
  3768. SQLITE_API char *sqlite3_vmprintf(const char*, va_list);
  3769. SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...);
  3770. SQLITE_API char *sqlite3_vsnprintf(int,char*,const char*, va_list);
  3771. /*
  3772. ** CAPI3REF: Memory Allocation Subsystem
  3773. **
  3774. ** The SQLite core uses these three routines for all of its own
  3775. ** internal memory allocation needs. "Core" in the previous sentence
  3776. ** does not include operating-system specific [VFS] implementation. The
  3777. ** Windows VFS uses native malloc() and free() for some operations.
  3778. **
  3779. ** ^The sqlite3_malloc() routine returns a pointer to a block
  3780. ** of memory at least N bytes in length, where N is the parameter.
  3781. ** ^If sqlite3_malloc() is unable to obtain sufficient free
  3782. ** memory, it returns a NULL pointer. ^If the parameter N to
  3783. ** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
  3784. ** a NULL pointer.
  3785. **
  3786. ** ^The sqlite3_malloc64(N) routine works just like
  3787. ** sqlite3_malloc(N) except that N is an unsigned 64-bit integer instead
  3788. ** of a signed 32-bit integer.
  3789. **
  3790. ** ^Calling sqlite3_free() with a pointer previously returned
  3791. ** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
  3792. ** that it might be reused. ^The sqlite3_free() routine is
  3793. ** a no-op if is called with a NULL pointer. Passing a NULL pointer
  3794. ** to sqlite3_free() is harmless. After being freed, memory
  3795. ** should neither be read nor written. Even reading previously freed
  3796. ** memory might result in a segmentation fault or other severe error.
  3797. ** Memory corruption, a segmentation fault, or other severe error
  3798. ** might result if sqlite3_free() is called with a non-NULL pointer that
  3799. ** was not obtained from sqlite3_malloc() or sqlite3_realloc().
  3800. **
  3801. ** ^The sqlite3_realloc(X,N) interface attempts to resize a
  3802. ** prior memory allocation X to be at least N bytes.
  3803. ** ^If the X parameter to sqlite3_realloc(X,N)
  3804. ** is a NULL pointer then its behavior is identical to calling
  3805. ** sqlite3_malloc(N).
  3806. ** ^If the N parameter to sqlite3_realloc(X,N) is zero or
  3807. ** negative then the behavior is exactly the same as calling
  3808. ** sqlite3_free(X).
  3809. ** ^sqlite3_realloc(X,N) returns a pointer to a memory allocation
  3810. ** of at least N bytes in size or NULL if insufficient memory is available.
  3811. ** ^If M is the size of the prior allocation, then min(N,M) bytes
  3812. ** of the prior allocation are copied into the beginning of buffer returned
  3813. ** by sqlite3_realloc(X,N) and the prior allocation is freed.
  3814. ** ^If sqlite3_realloc(X,N) returns NULL and N is positive, then the
  3815. ** prior allocation is not freed.
  3816. **
  3817. ** ^The sqlite3_realloc64(X,N) interfaces works the same as
  3818. ** sqlite3_realloc(X,N) except that N is a 64-bit unsigned integer instead
  3819. ** of a 32-bit signed integer.
  3820. **
  3821. ** ^If X is a memory allocation previously obtained from sqlite3_malloc(),
  3822. ** sqlite3_malloc64(), sqlite3_realloc(), or sqlite3_realloc64(), then
  3823. ** sqlite3_msize(X) returns the size of that memory allocation in bytes.
  3824. ** ^The value returned by sqlite3_msize(X) might be larger than the number
  3825. ** of bytes requested when X was allocated. ^If X is a NULL pointer then
  3826. ** sqlite3_msize(X) returns zero. If X points to something that is not
  3827. ** the beginning of memory allocation, or if it points to a formerly
  3828. ** valid memory allocation that has now been freed, then the behavior
  3829. ** of sqlite3_msize(X) is undefined and possibly harmful.
  3830. **
  3831. ** ^The memory returned by sqlite3_malloc(), sqlite3_realloc(),
  3832. ** sqlite3_malloc64(), and sqlite3_realloc64()
  3833. ** is always aligned to at least an 8 byte boundary, or to a
  3834. ** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time
  3835. ** option is used.
  3836. **
  3837. ** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
  3838. ** must be either NULL or else pointers obtained from a prior
  3839. ** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have
  3840. ** not yet been released.
  3841. **
  3842. ** The application must not read or write any part of
  3843. ** a block of memory after it has been released using
  3844. ** [sqlite3_free()] or [sqlite3_realloc()].
  3845. */
  3846. SQLITE_API void *sqlite3_malloc(int);
  3847. SQLITE_API void *sqlite3_malloc64(sqlite3_uint64);
  3848. SQLITE_API void *sqlite3_realloc(void*, int);
  3849. SQLITE_API void *sqlite3_realloc64(void*, sqlite3_uint64);
  3850. SQLITE_API void sqlite3_free(void*);
  3851. SQLITE_API sqlite3_uint64 sqlite3_msize(void*);
  3852. /*
  3853. ** CAPI3REF: Memory Allocator Statistics
  3854. **
  3855. ** SQLite provides these two interfaces for reporting on the status
  3856. ** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]
  3857. ** routines, which form the built-in memory allocation subsystem.
  3858. **
  3859. ** ^The [sqlite3_memory_used()] routine returns the number of bytes
  3860. ** of memory currently outstanding (malloced but not freed).
  3861. ** ^The [sqlite3_memory_highwater()] routine returns the maximum
  3862. ** value of [sqlite3_memory_used()] since the high-water mark
  3863. ** was last reset. ^The values returned by [sqlite3_memory_used()] and
  3864. ** [sqlite3_memory_highwater()] include any overhead
  3865. ** added by SQLite in its implementation of [sqlite3_malloc()],
  3866. ** but not overhead added by the any underlying system library
  3867. ** routines that [sqlite3_malloc()] may call.
  3868. **
  3869. ** ^The memory high-water mark is reset to the current value of
  3870. ** [sqlite3_memory_used()] if and only if the parameter to
  3871. ** [sqlite3_memory_highwater()] is true. ^The value returned
  3872. ** by [sqlite3_memory_highwater(1)] is the high-water mark
  3873. ** prior to the reset.
  3874. */
  3875. SQLITE_API sqlite3_int64 sqlite3_memory_used(void);
  3876. SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag);
  3877. /*
  3878. ** CAPI3REF: Pseudo-Random Number Generator
  3879. **
  3880. ** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
  3881. ** select random [ROWID | ROWIDs] when inserting new records into a table that
  3882. ** already uses the largest possible [ROWID]. The PRNG is also used for
  3883. ** the built-in random() and randomblob() SQL functions. This interface allows
  3884. ** applications to access the same PRNG for other purposes.
  3885. **
  3886. ** ^A call to this routine stores N bytes of randomness into buffer P.
  3887. ** ^The P parameter can be a NULL pointer.
  3888. **
  3889. ** ^If this routine has not been previously called or if the previous
  3890. ** call had N less than one or a NULL pointer for P, then the PRNG is
  3891. ** seeded using randomness obtained from the xRandomness method of
  3892. ** the default [sqlite3_vfs] object.
  3893. ** ^If the previous call to this routine had an N of 1 or more and a
  3894. ** non-NULL P then the pseudo-randomness is generated
  3895. ** internally and without recourse to the [sqlite3_vfs] xRandomness
  3896. ** method.
  3897. */
  3898. SQLITE_API void sqlite3_randomness(int N, void *P);
  3899. /*
  3900. ** CAPI3REF: Compile-Time Authorization Callbacks
  3901. ** METHOD: sqlite3
  3902. ** KEYWORDS: {authorizer callback}
  3903. **
  3904. ** ^This routine registers an authorizer callback with a particular
  3905. ** [database connection], supplied in the first argument.
  3906. ** ^The authorizer callback is invoked as SQL statements are being compiled
  3907. ** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
  3908. ** [sqlite3_prepare_v3()], [sqlite3_prepare16()], [sqlite3_prepare16_v2()],
  3909. ** and [sqlite3_prepare16_v3()]. ^At various
  3910. ** points during the compilation process, as logic is being created
  3911. ** to perform various actions, the authorizer callback is invoked to
  3912. ** see if those actions are allowed. ^The authorizer callback should
  3913. ** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the
  3914. ** specific action but allow the SQL statement to continue to be
  3915. ** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
  3916. ** rejected with an error. ^If the authorizer callback returns
  3917. ** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
  3918. ** then the [sqlite3_prepare_v2()] or equivalent call that triggered
  3919. ** the authorizer will fail with an error message.
  3920. **
  3921. ** When the callback returns [SQLITE_OK], that means the operation
  3922. ** requested is ok. ^When the callback returns [SQLITE_DENY], the
  3923. ** [sqlite3_prepare_v2()] or equivalent call that triggered the
  3924. ** authorizer will fail with an error message explaining that
  3925. ** access is denied.
  3926. **
  3927. ** ^The first parameter to the authorizer callback is a copy of the third
  3928. ** parameter to the sqlite3_set_authorizer() interface. ^The second parameter
  3929. ** to the callback is an integer [SQLITE_COPY | action code] that specifies
  3930. ** the particular action to be authorized. ^The third through sixth parameters
  3931. ** to the callback are either NULL pointers or zero-terminated strings
  3932. ** that contain additional details about the action to be authorized.
  3933. ** Applications must always be prepared to encounter a NULL pointer in any
  3934. ** of the third through the sixth parameters of the authorization callback.
  3935. **
  3936. ** ^If the action code is [SQLITE_READ]
  3937. ** and the callback returns [SQLITE_IGNORE] then the
  3938. ** [prepared statement] statement is constructed to substitute
  3939. ** a NULL value in place of the table column that would have
  3940. ** been read if [SQLITE_OK] had been returned. The [SQLITE_IGNORE]
  3941. ** return can be used to deny an untrusted user access to individual
  3942. ** columns of a table.
  3943. ** ^When a table is referenced by a [SELECT] but no column values are
  3944. ** extracted from that table (for example in a query like
  3945. ** "SELECT count(*) FROM tab") then the [SQLITE_READ] authorizer callback
  3946. ** is invoked once for that table with a column name that is an empty string.
  3947. ** ^If the action code is [SQLITE_DELETE] and the callback returns
  3948. ** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the
  3949. ** [truncate optimization] is disabled and all rows are deleted individually.
  3950. **
  3951. ** An authorizer is used when [sqlite3_prepare | preparing]
  3952. ** SQL statements from an untrusted source, to ensure that the SQL statements
  3953. ** do not try to access data they are not allowed to see, or that they do not
  3954. ** try to execute malicious statements that damage the database. For
  3955. ** example, an application may allow a user to enter arbitrary
  3956. ** SQL queries for evaluation by a database. But the application does
  3957. ** not want the user to be able to make arbitrary changes to the
  3958. ** database. An authorizer could then be put in place while the
  3959. ** user-entered SQL is being [sqlite3_prepare | prepared] that
  3960. ** disallows everything except [SELECT] statements.
  3961. **
  3962. ** Applications that need to process SQL from untrusted sources
  3963. ** might also consider lowering resource limits using [sqlite3_limit()]
  3964. ** and limiting database size using the [max_page_count] [PRAGMA]
  3965. ** in addition to using an authorizer.
  3966. **
  3967. ** ^(Only a single authorizer can be in place on a database connection
  3968. ** at a time. Each call to sqlite3_set_authorizer overrides the
  3969. ** previous call.)^ ^Disable the authorizer by installing a NULL callback.
  3970. ** The authorizer is disabled by default.
  3971. **
  3972. ** The authorizer callback must not do anything that will modify
  3973. ** the database connection that invoked the authorizer callback.
  3974. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
  3975. ** database connections for the meaning of "modify" in this paragraph.
  3976. **
  3977. ** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the
  3978. ** statement might be re-prepared during [sqlite3_step()] due to a
  3979. ** schema change. Hence, the application should ensure that the
  3980. ** correct authorizer callback remains in place during the [sqlite3_step()].
  3981. **
  3982. ** ^Note that the authorizer callback is invoked only during
  3983. ** [sqlite3_prepare()] or its variants. Authorization is not
  3984. ** performed during statement evaluation in [sqlite3_step()], unless
  3985. ** as stated in the previous paragraph, sqlite3_step() invokes
  3986. ** sqlite3_prepare_v2() to reprepare a statement after a schema change.
  3987. */
  3988. SQLITE_API int sqlite3_set_authorizer(
  3989. sqlite3*,
  3990. int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
  3991. void *pUserData
  3992. );
  3993. /*
  3994. ** CAPI3REF: Authorizer Return Codes
  3995. **
  3996. ** The [sqlite3_set_authorizer | authorizer callback function] must
  3997. ** return either [SQLITE_OK] or one of these two constants in order
  3998. ** to signal SQLite whether or not the action is permitted. See the
  3999. ** [sqlite3_set_authorizer | authorizer documentation] for additional
  4000. ** information.
  4001. **
  4002. ** Note that SQLITE_IGNORE is also used as a [conflict resolution mode]
  4003. ** returned from the [sqlite3_vtab_on_conflict()] interface.
  4004. */
  4005. #define SQLITE_DENY 1 /* Abort the SQL statement with an error */
  4006. #define SQLITE_IGNORE 2 /* Don't allow access, but don't generate an error */
  4007. /*
  4008. ** CAPI3REF: Authorizer Action Codes
  4009. **
  4010. ** The [sqlite3_set_authorizer()] interface registers a callback function
  4011. ** that is invoked to authorize certain SQL statement actions. The
  4012. ** second parameter to the callback is an integer code that specifies
  4013. ** what action is being authorized. These are the integer action codes that
  4014. ** the authorizer callback may be passed.
  4015. **
  4016. ** These action code values signify what kind of operation is to be
  4017. ** authorized. The 3rd and 4th parameters to the authorization
  4018. ** callback function will be parameters or NULL depending on which of these
  4019. ** codes is used as the second parameter. ^(The 5th parameter to the
  4020. ** authorizer callback is the name of the database ("main", "temp",
  4021. ** etc.) if applicable.)^ ^The 6th parameter to the authorizer callback
  4022. ** is the name of the inner-most trigger or view that is responsible for
  4023. ** the access attempt or NULL if this access attempt is directly from
  4024. ** top-level SQL code.
  4025. */
  4026. /******************************************* 3rd ************ 4th ***********/
  4027. #define SQLITE_CREATE_INDEX 1 /* Index Name Table Name */
  4028. #define SQLITE_CREATE_TABLE 2 /* Table Name NULL */
  4029. #define SQLITE_CREATE_TEMP_INDEX 3 /* Index Name Table Name */
  4030. #define SQLITE_CREATE_TEMP_TABLE 4 /* Table Name NULL */
  4031. #define SQLITE_CREATE_TEMP_TRIGGER 5 /* Trigger Name Table Name */
  4032. #define SQLITE_CREATE_TEMP_VIEW 6 /* View Name NULL */
  4033. #define SQLITE_CREATE_TRIGGER 7 /* Trigger Name Table Name */
  4034. #define SQLITE_CREATE_VIEW 8 /* View Name NULL */
  4035. #define SQLITE_DELETE 9 /* Table Name NULL */
  4036. #define SQLITE_DROP_INDEX 10 /* Index Name Table Name */
  4037. #define SQLITE_DROP_TABLE 11 /* Table Name NULL */
  4038. #define SQLITE_DROP_TEMP_INDEX 12 /* Index Name Table Name */
  4039. #define SQLITE_DROP_TEMP_TABLE 13 /* Table Name NULL */
  4040. #define SQLITE_DROP_TEMP_TRIGGER 14 /* Trigger Name Table Name */
  4041. #define SQLITE_DROP_TEMP_VIEW 15 /* View Name NULL */
  4042. #define SQLITE_DROP_TRIGGER 16 /* Trigger Name Table Name */
  4043. #define SQLITE_DROP_VIEW 17 /* View Name NULL */
  4044. #define SQLITE_INSERT 18 /* Table Name NULL */
  4045. #define SQLITE_PRAGMA 19 /* Pragma Name 1st arg or NULL */
  4046. #define SQLITE_READ 20 /* Table Name Column Name */
  4047. #define SQLITE_SELECT 21 /* NULL NULL */
  4048. #define SQLITE_TRANSACTION 22 /* Operation NULL */
  4049. #define SQLITE_UPDATE 23 /* Table Name Column Name */
  4050. #define SQLITE_ATTACH 24 /* Filename NULL */
  4051. #define SQLITE_DETACH 25 /* Database Name NULL */
  4052. #define SQLITE_ALTER_TABLE 26 /* Database Name Table Name */
  4053. #define SQLITE_REINDEX 27 /* Index Name NULL */
  4054. #define SQLITE_ANALYZE 28 /* Table Name NULL */
  4055. #define SQLITE_CREATE_VTABLE 29 /* Table Name Module Name */
  4056. #define SQLITE_DROP_VTABLE 30 /* Table Name Module Name */
  4057. #define SQLITE_FUNCTION 31 /* NULL Function Name */
  4058. #define SQLITE_SAVEPOINT 32 /* Operation Savepoint Name */
  4059. #define SQLITE_COPY 0 /* No longer used */
  4060. #define SQLITE_RECURSIVE 33 /* NULL NULL */
  4061. /*
  4062. ** CAPI3REF: Tracing And Profiling Functions
  4063. ** METHOD: sqlite3
  4064. **
  4065. ** These routines are deprecated. Use the [sqlite3_trace_v2()] interface
  4066. ** instead of the routines described here.
  4067. **
  4068. ** These routines register callback functions that can be used for
  4069. ** tracing and profiling the execution of SQL statements.
  4070. **
  4071. ** ^The callback function registered by sqlite3_trace() is invoked at
  4072. ** various times when an SQL statement is being run by [sqlite3_step()].
  4073. ** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the
  4074. ** SQL statement text as the statement first begins executing.
  4075. ** ^(Additional sqlite3_trace() callbacks might occur
  4076. ** as each triggered subprogram is entered. The callbacks for triggers
  4077. ** contain a UTF-8 SQL comment that identifies the trigger.)^
  4078. **
  4079. ** The [SQLITE_TRACE_SIZE_LIMIT] compile-time option can be used to limit
  4080. ** the length of [bound parameter] expansion in the output of sqlite3_trace().
  4081. **
  4082. ** ^The callback function registered by sqlite3_profile() is invoked
  4083. ** as each SQL statement finishes. ^The profile callback contains
  4084. ** the original statement text and an estimate of wall-clock time
  4085. ** of how long that statement took to run. ^The profile callback
  4086. ** time is in units of nanoseconds, however the current implementation
  4087. ** is only capable of millisecond resolution so the six least significant
  4088. ** digits in the time are meaningless. Future versions of SQLite
  4089. ** might provide greater resolution on the profiler callback. Invoking
  4090. ** either [sqlite3_trace()] or [sqlite3_trace_v2()] will cancel the
  4091. ** profile callback.
  4092. */
  4093. SQLITE_API SQLITE_DEPRECATED void *sqlite3_trace(sqlite3*,
  4094. void(*xTrace)(void*,const char*), void*);
  4095. SQLITE_API SQLITE_DEPRECATED void *sqlite3_profile(sqlite3*,
  4096. void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
  4097. /*
  4098. ** CAPI3REF: SQL Trace Event Codes
  4099. ** KEYWORDS: SQLITE_TRACE
  4100. **
  4101. ** These constants identify classes of events that can be monitored
  4102. ** using the [sqlite3_trace_v2()] tracing logic. The M argument
  4103. ** to [sqlite3_trace_v2(D,M,X,P)] is an OR-ed combination of one or more of
  4104. ** the following constants. ^The first argument to the trace callback
  4105. ** is one of the following constants.
  4106. **
  4107. ** New tracing constants may be added in future releases.
  4108. **
  4109. ** ^A trace callback has four arguments: xCallback(T,C,P,X).
  4110. ** ^The T argument is one of the integer type codes above.
  4111. ** ^The C argument is a copy of the context pointer passed in as the
  4112. ** fourth argument to [sqlite3_trace_v2()].
  4113. ** The P and X arguments are pointers whose meanings depend on T.
  4114. **
  4115. ** <dl>
  4116. ** [[SQLITE_TRACE_STMT]] <dt>SQLITE_TRACE_STMT</dt>
  4117. ** <dd>^An SQLITE_TRACE_STMT callback is invoked when a prepared statement
  4118. ** first begins running and possibly at other times during the
  4119. ** execution of the prepared statement, such as at the start of each
  4120. ** trigger subprogram. ^The P argument is a pointer to the
  4121. ** [prepared statement]. ^The X argument is a pointer to a string which
  4122. ** is the unexpanded SQL text of the prepared statement or an SQL comment
  4123. ** that indicates the invocation of a trigger. ^The callback can compute
  4124. ** the same text that would have been returned by the legacy [sqlite3_trace()]
  4125. ** interface by using the X argument when X begins with "--" and invoking
  4126. ** [sqlite3_expanded_sql(P)] otherwise.
  4127. **
  4128. ** [[SQLITE_TRACE_PROFILE]] <dt>SQLITE_TRACE_PROFILE</dt>
  4129. ** <dd>^An SQLITE_TRACE_PROFILE callback provides approximately the same
  4130. ** information as is provided by the [sqlite3_profile()] callback.
  4131. ** ^The P argument is a pointer to the [prepared statement] and the
  4132. ** X argument points to a 64-bit integer which is the estimated of
  4133. ** the number of nanosecond that the prepared statement took to run.
  4134. ** ^The SQLITE_TRACE_PROFILE callback is invoked when the statement finishes.
  4135. **
  4136. ** [[SQLITE_TRACE_ROW]] <dt>SQLITE_TRACE_ROW</dt>
  4137. ** <dd>^An SQLITE_TRACE_ROW callback is invoked whenever a prepared
  4138. ** statement generates a single row of result.
  4139. ** ^The P argument is a pointer to the [prepared statement] and the
  4140. ** X argument is unused.
  4141. **
  4142. ** [[SQLITE_TRACE_CLOSE]] <dt>SQLITE_TRACE_CLOSE</dt>
  4143. ** <dd>^An SQLITE_TRACE_CLOSE callback is invoked when a database
  4144. ** connection closes.
  4145. ** ^The P argument is a pointer to the [database connection] object
  4146. ** and the X argument is unused.
  4147. ** </dl>
  4148. */
  4149. #define SQLITE_TRACE_STMT 0x01
  4150. #define SQLITE_TRACE_PROFILE 0x02
  4151. #define SQLITE_TRACE_ROW 0x04
  4152. #define SQLITE_TRACE_CLOSE 0x08
  4153. /*
  4154. ** CAPI3REF: SQL Trace Hook
  4155. ** METHOD: sqlite3
  4156. **
  4157. ** ^The sqlite3_trace_v2(D,M,X,P) interface registers a trace callback
  4158. ** function X against [database connection] D, using property mask M
  4159. ** and context pointer P. ^If the X callback is
  4160. ** NULL or if the M mask is zero, then tracing is disabled. The
  4161. ** M argument should be the bitwise OR-ed combination of
  4162. ** zero or more [SQLITE_TRACE] constants.
  4163. **
  4164. ** ^Each call to either sqlite3_trace() or sqlite3_trace_v2() overrides
  4165. ** (cancels) any prior calls to sqlite3_trace() or sqlite3_trace_v2().
  4166. **
  4167. ** ^The X callback is invoked whenever any of the events identified by
  4168. ** mask M occur. ^The integer return value from the callback is currently
  4169. ** ignored, though this may change in future releases. Callback
  4170. ** implementations should return zero to ensure future compatibility.
  4171. **
  4172. ** ^A trace callback is invoked with four arguments: callback(T,C,P,X).
  4173. ** ^The T argument is one of the [SQLITE_TRACE]
  4174. ** constants to indicate why the callback was invoked.
  4175. ** ^The C argument is a copy of the context pointer.
  4176. ** The P and X arguments are pointers whose meanings depend on T.
  4177. **
  4178. ** The sqlite3_trace_v2() interface is intended to replace the legacy
  4179. ** interfaces [sqlite3_trace()] and [sqlite3_profile()], both of which
  4180. ** are deprecated.
  4181. */
  4182. SQLITE_API int sqlite3_trace_v2(
  4183. sqlite3*,
  4184. unsigned uMask,
  4185. int(*xCallback)(unsigned,void*,void*,void*),
  4186. void *pCtx
  4187. );
  4188. /*
  4189. ** CAPI3REF: Query Progress Callbacks
  4190. ** METHOD: sqlite3
  4191. **
  4192. ** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback
  4193. ** function X to be invoked periodically during long running calls to
  4194. ** [sqlite3_exec()], [sqlite3_step()] and [sqlite3_get_table()] for
  4195. ** database connection D. An example use for this
  4196. ** interface is to keep a GUI updated during a large query.
  4197. **
  4198. ** ^The parameter P is passed through as the only parameter to the
  4199. ** callback function X. ^The parameter N is the approximate number of
  4200. ** [virtual machine instructions] that are evaluated between successive
  4201. ** invocations of the callback X. ^If N is less than one then the progress
  4202. ** handler is disabled.
  4203. **
  4204. ** ^Only a single progress handler may be defined at one time per
  4205. ** [database connection]; setting a new progress handler cancels the
  4206. ** old one. ^Setting parameter X to NULL disables the progress handler.
  4207. ** ^The progress handler is also disabled by setting N to a value less
  4208. ** than 1.
  4209. **
  4210. ** ^If the progress callback returns non-zero, the operation is
  4211. ** interrupted. This feature can be used to implement a
  4212. ** "Cancel" button on a GUI progress dialog box.
  4213. **
  4214. ** The progress handler callback must not do anything that will modify
  4215. ** the database connection that invoked the progress handler.
  4216. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
  4217. ** database connections for the meaning of "modify" in this paragraph.
  4218. **
  4219. */
  4220. SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
  4221. /*
  4222. ** CAPI3REF: Opening A New Database Connection
  4223. ** CONSTRUCTOR: sqlite3
  4224. **
  4225. ** ^These routines open an SQLite database file as specified by the
  4226. ** filename argument. ^The filename argument is interpreted as UTF-8 for
  4227. ** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
  4228. ** order for sqlite3_open16(). ^(A [database connection] handle is usually
  4229. ** returned in *ppDb, even if an error occurs. The only exception is that
  4230. ** if SQLite is unable to allocate memory to hold the [sqlite3] object,
  4231. ** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]
  4232. ** object.)^ ^(If the database is opened (and/or created) successfully, then
  4233. ** [SQLITE_OK] is returned. Otherwise an [error code] is returned.)^ ^The
  4234. ** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain
  4235. ** an English language description of the error following a failure of any
  4236. ** of the sqlite3_open() routines.
  4237. **
  4238. ** ^The default encoding will be UTF-8 for databases created using
  4239. ** sqlite3_open() or sqlite3_open_v2(). ^The default encoding for databases
  4240. ** created using sqlite3_open16() will be UTF-16 in the native byte order.
  4241. **
  4242. ** Whether or not an error occurs when it is opened, resources
  4243. ** associated with the [database connection] handle should be released by
  4244. ** passing it to [sqlite3_close()] when it is no longer required.
  4245. **
  4246. ** The sqlite3_open_v2() interface works like sqlite3_open()
  4247. ** except that it accepts two additional parameters for additional control
  4248. ** over the new database connection. ^(The flags parameter to
  4249. ** sqlite3_open_v2() must include, at a minimum, one of the following
  4250. ** three flag combinations:)^
  4251. **
  4252. ** <dl>
  4253. ** ^(<dt>[SQLITE_OPEN_READONLY]</dt>
  4254. ** <dd>The database is opened in read-only mode. If the database does not
  4255. ** already exist, an error is returned.</dd>)^
  4256. **
  4257. ** ^(<dt>[SQLITE_OPEN_READWRITE]</dt>
  4258. ** <dd>The database is opened for reading and writing if possible, or reading
  4259. ** only if the file is write protected by the operating system. In either
  4260. ** case the database must already exist, otherwise an error is returned.</dd>)^
  4261. **
  4262. ** ^(<dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt>
  4263. ** <dd>The database is opened for reading and writing, and is created if
  4264. ** it does not already exist. This is the behavior that is always used for
  4265. ** sqlite3_open() and sqlite3_open16().</dd>)^
  4266. ** </dl>
  4267. **
  4268. ** In addition to the required flags, the following optional flags are
  4269. ** also supported:
  4270. **
  4271. ** <dl>
  4272. ** ^(<dt>[SQLITE_OPEN_URI]</dt>
  4273. ** <dd>The filename can be interpreted as a URI if this flag is set.</dd>)^
  4274. **
  4275. ** ^(<dt>[SQLITE_OPEN_MEMORY]</dt>
  4276. ** <dd>The database will be opened as an in-memory database. The database
  4277. ** is named by the "filename" argument for the purposes of cache-sharing,
  4278. ** if shared cache mode is enabled, but the "filename" is otherwise ignored.
  4279. ** </dd>)^
  4280. **
  4281. ** ^(<dt>[SQLITE_OPEN_NOMUTEX]</dt>
  4282. ** <dd>The new database connection will use the "multi-thread"
  4283. ** [threading mode].)^ This means that separate threads are allowed
  4284. ** to use SQLite at the same time, as long as each thread is using
  4285. ** a different [database connection].
  4286. **
  4287. ** ^(<dt>[SQLITE_OPEN_FULLMUTEX]</dt>
  4288. ** <dd>The new database connection will use the "serialized"
  4289. ** [threading mode].)^ This means the multiple threads can safely
  4290. ** attempt to use the same database connection at the same time.
  4291. ** (Mutexes will block any actual concurrency, but in this mode
  4292. ** there is no harm in trying.)
  4293. **
  4294. ** ^(<dt>[SQLITE_OPEN_SHAREDCACHE]</dt>
  4295. ** <dd>The database is opened [shared cache] enabled, overriding
  4296. ** the default shared cache setting provided by
  4297. ** [sqlite3_enable_shared_cache()].)^
  4298. **
  4299. ** ^(<dt>[SQLITE_OPEN_PRIVATECACHE]</dt>
  4300. ** <dd>The database is opened [shared cache] disabled, overriding
  4301. ** the default shared cache setting provided by
  4302. ** [sqlite3_enable_shared_cache()].)^
  4303. **
  4304. ** [[OPEN_NOFOLLOW]] ^(<dt>[SQLITE_OPEN_NOFOLLOW]</dt>
  4305. ** <dd>The database filename is not allowed to be a symbolic link</dd>
  4306. ** </dl>)^
  4307. **
  4308. ** If the 3rd parameter to sqlite3_open_v2() is not one of the
  4309. ** required combinations shown above optionally combined with other
  4310. ** [SQLITE_OPEN_READONLY | SQLITE_OPEN_* bits]
  4311. ** then the behavior is undefined.
  4312. **
  4313. ** ^The fourth parameter to sqlite3_open_v2() is the name of the
  4314. ** [sqlite3_vfs] object that defines the operating system interface that
  4315. ** the new database connection should use. ^If the fourth parameter is
  4316. ** a NULL pointer then the default [sqlite3_vfs] object is used.
  4317. **
  4318. ** ^If the filename is ":memory:", then a private, temporary in-memory database
  4319. ** is created for the connection. ^This in-memory database will vanish when
  4320. ** the database connection is closed. Future versions of SQLite might
  4321. ** make use of additional special filenames that begin with the ":" character.
  4322. ** It is recommended that when a database filename actually does begin with
  4323. ** a ":" character you should prefix the filename with a pathname such as
  4324. ** "./" to avoid ambiguity.
  4325. **
  4326. ** ^If the filename is an empty string, then a private, temporary
  4327. ** on-disk database will be created. ^This private database will be
  4328. ** automatically deleted as soon as the database connection is closed.
  4329. **
  4330. ** [[URI filenames in sqlite3_open()]] <h3>URI Filenames</h3>
  4331. **
  4332. ** ^If [URI filename] interpretation is enabled, and the filename argument
  4333. ** begins with "file:", then the filename is interpreted as a URI. ^URI
  4334. ** filename interpretation is enabled if the [SQLITE_OPEN_URI] flag is
  4335. ** set in the third argument to sqlite3_open_v2(), or if it has
  4336. ** been enabled globally using the [SQLITE_CONFIG_URI] option with the
  4337. ** [sqlite3_config()] method or by the [SQLITE_USE_URI] compile-time option.
  4338. ** URI filename interpretation is turned off
  4339. ** by default, but future releases of SQLite might enable URI filename
  4340. ** interpretation by default. See "[URI filenames]" for additional
  4341. ** information.
  4342. **
  4343. ** URI filenames are parsed according to RFC 3986. ^If the URI contains an
  4344. ** authority, then it must be either an empty string or the string
  4345. ** "localhost". ^If the authority is not an empty string or "localhost", an
  4346. ** error is returned to the caller. ^The fragment component of a URI, if
  4347. ** present, is ignored.
  4348. **
  4349. ** ^SQLite uses the path component of the URI as the name of the disk file
  4350. ** which contains the database. ^If the path begins with a '/' character,
  4351. ** then it is interpreted as an absolute path. ^If the path does not begin
  4352. ** with a '/' (meaning that the authority section is omitted from the URI)
  4353. ** then the path is interpreted as a relative path.
  4354. ** ^(On windows, the first component of an absolute path
  4355. ** is a drive specification (e.g. "C:").)^
  4356. **
  4357. ** [[core URI query parameters]]
  4358. ** The query component of a URI may contain parameters that are interpreted
  4359. ** either by SQLite itself, or by a [VFS | custom VFS implementation].
  4360. ** SQLite and its built-in [VFSes] interpret the
  4361. ** following query parameters:
  4362. **
  4363. ** <ul>
  4364. ** <li> <b>vfs</b>: ^The "vfs" parameter may be used to specify the name of
  4365. ** a VFS object that provides the operating system interface that should
  4366. ** be used to access the database file on disk. ^If this option is set to
  4367. ** an empty string the default VFS object is used. ^Specifying an unknown
  4368. ** VFS is an error. ^If sqlite3_open_v2() is used and the vfs option is
  4369. ** present, then the VFS specified by the option takes precedence over
  4370. ** the value passed as the fourth parameter to sqlite3_open_v2().
  4371. **
  4372. ** <li> <b>mode</b>: ^(The mode parameter may be set to either "ro", "rw",
  4373. ** "rwc", or "memory". Attempting to set it to any other value is
  4374. ** an error)^.
  4375. ** ^If "ro" is specified, then the database is opened for read-only
  4376. ** access, just as if the [SQLITE_OPEN_READONLY] flag had been set in the
  4377. ** third argument to sqlite3_open_v2(). ^If the mode option is set to
  4378. ** "rw", then the database is opened for read-write (but not create)
  4379. ** access, as if SQLITE_OPEN_READWRITE (but not SQLITE_OPEN_CREATE) had
  4380. ** been set. ^Value "rwc" is equivalent to setting both
  4381. ** SQLITE_OPEN_READWRITE and SQLITE_OPEN_CREATE. ^If the mode option is
  4382. ** set to "memory" then a pure [in-memory database] that never reads
  4383. ** or writes from disk is used. ^It is an error to specify a value for
  4384. ** the mode parameter that is less restrictive than that specified by
  4385. ** the flags passed in the third parameter to sqlite3_open_v2().
  4386. **
  4387. ** <li> <b>cache</b>: ^The cache parameter may be set to either "shared" or
  4388. ** "private". ^Setting it to "shared" is equivalent to setting the
  4389. ** SQLITE_OPEN_SHAREDCACHE bit in the flags argument passed to
  4390. ** sqlite3_open_v2(). ^Setting the cache parameter to "private" is
  4391. ** equivalent to setting the SQLITE_OPEN_PRIVATECACHE bit.
  4392. ** ^If sqlite3_open_v2() is used and the "cache" parameter is present in
  4393. ** a URI filename, its value overrides any behavior requested by setting
  4394. ** SQLITE_OPEN_PRIVATECACHE or SQLITE_OPEN_SHAREDCACHE flag.
  4395. **
  4396. ** <li> <b>psow</b>: ^The psow parameter indicates whether or not the
  4397. ** [powersafe overwrite] property does or does not apply to the
  4398. ** storage media on which the database file resides.
  4399. **
  4400. ** <li> <b>nolock</b>: ^The nolock parameter is a boolean query parameter
  4401. ** which if set disables file locking in rollback journal modes. This
  4402. ** is useful for accessing a database on a filesystem that does not
  4403. ** support locking. Caution: Database corruption might result if two
  4404. ** or more processes write to the same database and any one of those
  4405. ** processes uses nolock=1.
  4406. **
  4407. ** <li> <b>immutable</b>: ^The immutable parameter is a boolean query
  4408. ** parameter that indicates that the database file is stored on
  4409. ** read-only media. ^When immutable is set, SQLite assumes that the
  4410. ** database file cannot be changed, even by a process with higher
  4411. ** privilege, and so the database is opened read-only and all locking
  4412. ** and change detection is disabled. Caution: Setting the immutable
  4413. ** property on a database file that does in fact change can result
  4414. ** in incorrect query results and/or [SQLITE_CORRUPT] errors.
  4415. ** See also: [SQLITE_IOCAP_IMMUTABLE].
  4416. **
  4417. ** </ul>
  4418. **
  4419. ** ^Specifying an unknown parameter in the query component of a URI is not an
  4420. ** error. Future versions of SQLite might understand additional query
  4421. ** parameters. See "[query parameters with special meaning to SQLite]" for
  4422. ** additional information.
  4423. **
  4424. ** [[URI filename examples]] <h3>URI filename examples</h3>
  4425. **
  4426. ** <table border="1" align=center cellpadding=5>
  4427. ** <tr><th> URI filenames <th> Results
  4428. ** <tr><td> file:data.db <td>
  4429. ** Open the file "data.db" in the current directory.
  4430. ** <tr><td> file:/home/fred/data.db<br>
  4431. ** file:///home/fred/data.db <br>
  4432. ** file://localhost/home/fred/data.db <br> <td>
  4433. ** Open the database file "/home/fred/data.db".
  4434. ** <tr><td> file://darkstar/home/fred/data.db <td>
  4435. ** An error. "darkstar" is not a recognized authority.
  4436. ** <tr><td style="white-space:nowrap">
  4437. ** file:///C:/Documents%20and%20Settings/fred/Desktop/data.db
  4438. ** <td> Windows only: Open the file "data.db" on fred's desktop on drive
  4439. ** C:. Note that the %20 escaping in this example is not strictly
  4440. ** necessary - space characters can be used literally
  4441. ** in URI filenames.
  4442. ** <tr><td> file:data.db?mode=ro&cache=private <td>
  4443. ** Open file "data.db" in the current directory for read-only access.
  4444. ** Regardless of whether or not shared-cache mode is enabled by
  4445. ** default, use a private cache.
  4446. ** <tr><td> file:/home/fred/data.db?vfs=unix-dotfile <td>
  4447. ** Open file "/home/fred/data.db". Use the special VFS "unix-dotfile"
  4448. ** that uses dot-files in place of posix advisory locking.
  4449. ** <tr><td> file:data.db?mode=readonly <td>
  4450. ** An error. "readonly" is not a valid option for the "mode" parameter.
  4451. ** </table>
  4452. **
  4453. ** ^URI hexadecimal escape sequences (%HH) are supported within the path and
  4454. ** query components of a URI. A hexadecimal escape sequence consists of a
  4455. ** percent sign - "%" - followed by exactly two hexadecimal digits
  4456. ** specifying an octet value. ^Before the path or query components of a
  4457. ** URI filename are interpreted, they are encoded using UTF-8 and all
  4458. ** hexadecimal escape sequences replaced by a single byte containing the
  4459. ** corresponding octet. If this process generates an invalid UTF-8 encoding,
  4460. ** the results are undefined.
  4461. **
  4462. ** <b>Note to Windows users:</b> The encoding used for the filename argument
  4463. ** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever
  4464. ** codepage is currently defined. Filenames containing international
  4465. ** characters must be converted to UTF-8 prior to passing them into
  4466. ** sqlite3_open() or sqlite3_open_v2().
  4467. **
  4468. ** <b>Note to Windows Runtime users:</b> The temporary directory must be set
  4469. ** prior to calling sqlite3_open() or sqlite3_open_v2(). Otherwise, various
  4470. ** features that require the use of temporary files may fail.
  4471. **
  4472. ** See also: [sqlite3_temp_directory]
  4473. */
  4474. SQLITE_API int sqlite3_open(
  4475. const char *filename, /* Database filename (UTF-8) */
  4476. sqlite3 **ppDb /* OUT: SQLite db handle */
  4477. );
  4478. SQLITE_API int sqlite3_open16(
  4479. const void *filename, /* Database filename (UTF-16) */
  4480. sqlite3 **ppDb /* OUT: SQLite db handle */
  4481. );
  4482. SQLITE_API int sqlite3_open_v2(
  4483. const char *filename, /* Database filename (UTF-8) */
  4484. sqlite3 **ppDb, /* OUT: SQLite db handle */
  4485. int flags, /* Flags */
  4486. const char *zVfs /* Name of VFS module to use */
  4487. );
  4488. /*
  4489. ** CAPI3REF: Obtain Values For URI Parameters
  4490. **
  4491. ** These are utility routines, useful to [VFS|custom VFS implementations],
  4492. ** that check if a database file was a URI that contained a specific query
  4493. ** parameter, and if so obtains the value of that query parameter.
  4494. **
  4495. ** The first parameter to these interfaces (hereafter referred to
  4496. ** as F) must be one of:
  4497. ** <ul>
  4498. ** <li> A database filename pointer created by the SQLite core and
  4499. ** passed into the xOpen() method of a VFS implemention, or
  4500. ** <li> A filename obtained from [sqlite3_db_filename()], or
  4501. ** <li> A new filename constructed using [sqlite3_create_filename()].
  4502. ** </ul>
  4503. ** If the F parameter is not one of the above, then the behavior is
  4504. ** undefined and probably undesirable. Older versions of SQLite were
  4505. ** more tolerant of invalid F parameters than newer versions.
  4506. **
  4507. ** If F is a suitable filename (as described in the previous paragraph)
  4508. ** and if P is the name of the query parameter, then
  4509. ** sqlite3_uri_parameter(F,P) returns the value of the P
  4510. ** parameter if it exists or a NULL pointer if P does not appear as a
  4511. ** query parameter on F. If P is a query parameter of F and it
  4512. ** has no explicit value, then sqlite3_uri_parameter(F,P) returns
  4513. ** a pointer to an empty string.
  4514. **
  4515. ** The sqlite3_uri_boolean(F,P,B) routine assumes that P is a boolean
  4516. ** parameter and returns true (1) or false (0) according to the value
  4517. ** of P. The sqlite3_uri_boolean(F,P,B) routine returns true (1) if the
  4518. ** value of query parameter P is one of "yes", "true", or "on" in any
  4519. ** case or if the value begins with a non-zero number. The
  4520. ** sqlite3_uri_boolean(F,P,B) routines returns false (0) if the value of
  4521. ** query parameter P is one of "no", "false", or "off" in any case or
  4522. ** if the value begins with a numeric zero. If P is not a query
  4523. ** parameter on F or if the value of P does not match any of the
  4524. ** above, then sqlite3_uri_boolean(F,P,B) returns (B!=0).
  4525. **
  4526. ** The sqlite3_uri_int64(F,P,D) routine converts the value of P into a
  4527. ** 64-bit signed integer and returns that integer, or D if P does not
  4528. ** exist. If the value of P is something other than an integer, then
  4529. ** zero is returned.
  4530. **
  4531. ** The sqlite3_uri_key(F,N) returns a pointer to the name (not
  4532. ** the value) of the N-th query parameter for filename F, or a NULL
  4533. ** pointer if N is less than zero or greater than the number of query
  4534. ** parameters minus 1. The N value is zero-based so N should be 0 to obtain
  4535. ** the name of the first query parameter, 1 for the second parameter, and
  4536. ** so forth.
  4537. **
  4538. ** If F is a NULL pointer, then sqlite3_uri_parameter(F,P) returns NULL and
  4539. ** sqlite3_uri_boolean(F,P,B) returns B. If F is not a NULL pointer and
  4540. ** is not a database file pathname pointer that the SQLite core passed
  4541. ** into the xOpen VFS method, then the behavior of this routine is undefined
  4542. ** and probably undesirable.
  4543. **
  4544. ** Beginning with SQLite [version 3.31.0] ([dateof:3.31.0]) the input F
  4545. ** parameter can also be the name of a rollback journal file or WAL file
  4546. ** in addition to the main database file. Prior to version 3.31.0, these
  4547. ** routines would only work if F was the name of the main database file.
  4548. ** When the F parameter is the name of the rollback journal or WAL file,
  4549. ** it has access to all the same query parameters as were found on the
  4550. ** main database file.
  4551. **
  4552. ** See the [URI filename] documentation for additional information.
  4553. */
  4554. SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam);
  4555. SQLITE_API int sqlite3_uri_boolean(const char *zFile, const char *zParam, int bDefault);
  4556. SQLITE_API sqlite3_int64 sqlite3_uri_int64(const char*, const char*, sqlite3_int64);
  4557. SQLITE_API const char *sqlite3_uri_key(const char *zFilename, int N);
  4558. /*
  4559. ** CAPI3REF: Translate filenames
  4560. **
  4561. ** These routines are available to [VFS|custom VFS implementations] for
  4562. ** translating filenames between the main database file, the journal file,
  4563. ** and the WAL file.
  4564. **
  4565. ** If F is the name of an sqlite database file, journal file, or WAL file
  4566. ** passed by the SQLite core into the VFS, then sqlite3_filename_database(F)
  4567. ** returns the name of the corresponding database file.
  4568. **
  4569. ** If F is the name of an sqlite database file, journal file, or WAL file
  4570. ** passed by the SQLite core into the VFS, or if F is a database filename
  4571. ** obtained from [sqlite3_db_filename()], then sqlite3_filename_journal(F)
  4572. ** returns the name of the corresponding rollback journal file.
  4573. **
  4574. ** If F is the name of an sqlite database file, journal file, or WAL file
  4575. ** that was passed by the SQLite core into the VFS, or if F is a database
  4576. ** filename obtained from [sqlite3_db_filename()], then
  4577. ** sqlite3_filename_wal(F) returns the name of the corresponding
  4578. ** WAL file.
  4579. **
  4580. ** In all of the above, if F is not the name of a database, journal or WAL
  4581. ** filename passed into the VFS from the SQLite core and F is not the
  4582. ** return value from [sqlite3_db_filename()], then the result is
  4583. ** undefined and is likely a memory access violation.
  4584. */
  4585. SQLITE_API const char *sqlite3_filename_database(const char*);
  4586. SQLITE_API const char *sqlite3_filename_journal(const char*);
  4587. SQLITE_API const char *sqlite3_filename_wal(const char*);
  4588. /*
  4589. ** CAPI3REF: Database File Corresponding To A Journal
  4590. **
  4591. ** ^If X is the name of a rollback or WAL-mode journal file that is
  4592. ** passed into the xOpen method of [sqlite3_vfs], then
  4593. ** sqlite3_database_file_object(X) returns a pointer to the [sqlite3_file]
  4594. ** object that represents the main database file.
  4595. **
  4596. ** This routine is intended for use in custom [VFS] implementations
  4597. ** only. It is not a general-purpose interface.
  4598. ** The argument sqlite3_file_object(X) must be a filename pointer that
  4599. ** has been passed into [sqlite3_vfs].xOpen method where the
  4600. ** flags parameter to xOpen contains one of the bits
  4601. ** [SQLITE_OPEN_MAIN_JOURNAL] or [SQLITE_OPEN_WAL]. Any other use
  4602. ** of this routine results in undefined and probably undesirable
  4603. ** behavior.
  4604. */
  4605. SQLITE_API sqlite3_file *sqlite3_database_file_object(const char*);
  4606. /*
  4607. ** CAPI3REF: Create and Destroy VFS Filenames
  4608. **
  4609. ** These interfces are provided for use by [VFS shim] implementations and
  4610. ** are not useful outside of that context.
  4611. **
  4612. ** The sqlite3_create_filename(D,J,W,N,P) allocates memory to hold a version of
  4613. ** database filename D with corresponding journal file J and WAL file W and
  4614. ** with N URI parameters key/values pairs in the array P. The result from
  4615. ** sqlite3_create_filename(D,J,W,N,P) is a pointer to a database filename that
  4616. ** is safe to pass to routines like:
  4617. ** <ul>
  4618. ** <li> [sqlite3_uri_parameter()],
  4619. ** <li> [sqlite3_uri_boolean()],
  4620. ** <li> [sqlite3_uri_int64()],
  4621. ** <li> [sqlite3_uri_key()],
  4622. ** <li> [sqlite3_filename_database()],
  4623. ** <li> [sqlite3_filename_journal()], or
  4624. ** <li> [sqlite3_filename_wal()].
  4625. ** </ul>
  4626. ** If a memory allocation error occurs, sqlite3_create_filename() might
  4627. ** return a NULL pointer. The memory obtained from sqlite3_create_filename(X)
  4628. ** must be released by a corresponding call to sqlite3_free_filename(Y).
  4629. **
  4630. ** The P parameter in sqlite3_create_filename(D,J,W,N,P) should be an array
  4631. ** of 2*N pointers to strings. Each pair of pointers in this array corresponds
  4632. ** to a key and value for a query parameter. The P parameter may be a NULL
  4633. ** pointer if N is zero. None of the 2*N pointers in the P array may be
  4634. ** NULL pointers and key pointers should not be empty strings.
  4635. ** None of the D, J, or W parameters to sqlite3_create_filename(D,J,W,N,P) may
  4636. ** be NULL pointers, though they can be empty strings.
  4637. **
  4638. ** The sqlite3_free_filename(Y) routine releases a memory allocation
  4639. ** previously obtained from sqlite3_create_filename(). Invoking
  4640. ** sqlite3_free_filename(Y) where Y is a NULL pointer is a harmless no-op.
  4641. **
  4642. ** If the Y parameter to sqlite3_free_filename(Y) is anything other
  4643. ** than a NULL pointer or a pointer previously acquired from
  4644. ** sqlite3_create_filename(), then bad things such as heap
  4645. ** corruption or segfaults may occur. The value Y should be
  4646. ** used again after sqlite3_free_filename(Y) has been called. This means
  4647. ** that if the [sqlite3_vfs.xOpen()] method of a VFS has been called using Y,
  4648. ** then the corresponding [sqlite3_module.xClose() method should also be
  4649. ** invoked prior to calling sqlite3_free_filename(Y).
  4650. */
  4651. SQLITE_API char *sqlite3_create_filename(
  4652. const char *zDatabase,
  4653. const char *zJournal,
  4654. const char *zWal,
  4655. int nParam,
  4656. const char **azParam
  4657. );
  4658. SQLITE_API void sqlite3_free_filename(char*);
  4659. /*
  4660. ** CAPI3REF: Error Codes And Messages
  4661. ** METHOD: sqlite3
  4662. **
  4663. ** ^If the most recent sqlite3_* API call associated with
  4664. ** [database connection] D failed, then the sqlite3_errcode(D) interface
  4665. ** returns the numeric [result code] or [extended result code] for that
  4666. ** API call.
  4667. ** ^The sqlite3_extended_errcode()
  4668. ** interface is the same except that it always returns the
  4669. ** [extended result code] even when extended result codes are
  4670. ** disabled.
  4671. **
  4672. ** The values returned by sqlite3_errcode() and/or
  4673. ** sqlite3_extended_errcode() might change with each API call.
  4674. ** Except, there are some interfaces that are guaranteed to never
  4675. ** change the value of the error code. The error-code preserving
  4676. ** interfaces are:
  4677. **
  4678. ** <ul>
  4679. ** <li> sqlite3_errcode()
  4680. ** <li> sqlite3_extended_errcode()
  4681. ** <li> sqlite3_errmsg()
  4682. ** <li> sqlite3_errmsg16()
  4683. ** </ul>
  4684. **
  4685. ** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
  4686. ** text that describes the error, as either UTF-8 or UTF-16 respectively.
  4687. ** ^(Memory to hold the error message string is managed internally.
  4688. ** The application does not need to worry about freeing the result.
  4689. ** However, the error string might be overwritten or deallocated by
  4690. ** subsequent calls to other SQLite interface functions.)^
  4691. **
  4692. ** ^The sqlite3_errstr() interface returns the English-language text
  4693. ** that describes the [result code], as UTF-8.
  4694. ** ^(Memory to hold the error message string is managed internally
  4695. ** and must not be freed by the application)^.
  4696. **
  4697. ** When the serialized [threading mode] is in use, it might be the
  4698. ** case that a second error occurs on a separate thread in between
  4699. ** the time of the first error and the call to these interfaces.
  4700. ** When that happens, the second error will be reported since these
  4701. ** interfaces always report the most recent result. To avoid
  4702. ** this, each thread can obtain exclusive use of the [database connection] D
  4703. ** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning
  4704. ** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after
  4705. ** all calls to the interfaces listed here are completed.
  4706. **
  4707. ** If an interface fails with SQLITE_MISUSE, that means the interface
  4708. ** was invoked incorrectly by the application. In that case, the
  4709. ** error code and message may or may not be set.
  4710. */
  4711. SQLITE_API int sqlite3_errcode(sqlite3 *db);
  4712. SQLITE_API int sqlite3_extended_errcode(sqlite3 *db);
  4713. SQLITE_API const char *sqlite3_errmsg(sqlite3*);
  4714. SQLITE_API const void *sqlite3_errmsg16(sqlite3*);
  4715. SQLITE_API const char *sqlite3_errstr(int);
  4716. /*
  4717. ** CAPI3REF: Prepared Statement Object
  4718. ** KEYWORDS: {prepared statement} {prepared statements}
  4719. **
  4720. ** An instance of this object represents a single SQL statement that
  4721. ** has been compiled into binary form and is ready to be evaluated.
  4722. **
  4723. ** Think of each SQL statement as a separate computer program. The
  4724. ** original SQL text is source code. A prepared statement object
  4725. ** is the compiled object code. All SQL must be converted into a
  4726. ** prepared statement before it can be run.
  4727. **
  4728. ** The life-cycle of a prepared statement object usually goes like this:
  4729. **
  4730. ** <ol>
  4731. ** <li> Create the prepared statement object using [sqlite3_prepare_v2()].
  4732. ** <li> Bind values to [parameters] using the sqlite3_bind_*()
  4733. ** interfaces.
  4734. ** <li> Run the SQL by calling [sqlite3_step()] one or more times.
  4735. ** <li> Reset the prepared statement using [sqlite3_reset()] then go back
  4736. ** to step 2. Do this zero or more times.
  4737. ** <li> Destroy the object using [sqlite3_finalize()].
  4738. ** </ol>
  4739. */
  4740. typedef struct sqlite3_stmt sqlite3_stmt;
  4741. /*
  4742. ** CAPI3REF: Run-time Limits
  4743. ** METHOD: sqlite3
  4744. **
  4745. ** ^(This interface allows the size of various constructs to be limited
  4746. ** on a connection by connection basis. The first parameter is the
  4747. ** [database connection] whose limit is to be set or queried. The
  4748. ** second parameter is one of the [limit categories] that define a
  4749. ** class of constructs to be size limited. The third parameter is the
  4750. ** new limit for that construct.)^
  4751. **
  4752. ** ^If the new limit is a negative number, the limit is unchanged.
  4753. ** ^(For each limit category SQLITE_LIMIT_<i>NAME</i> there is a
  4754. ** [limits | hard upper bound]
  4755. ** set at compile-time by a C preprocessor macro called
  4756. ** [limits | SQLITE_MAX_<i>NAME</i>].
  4757. ** (The "_LIMIT_" in the name is changed to "_MAX_".))^
  4758. ** ^Attempts to increase a limit above its hard upper bound are
  4759. ** silently truncated to the hard upper bound.
  4760. **
  4761. ** ^Regardless of whether or not the limit was changed, the
  4762. ** [sqlite3_limit()] interface returns the prior value of the limit.
  4763. ** ^Hence, to find the current value of a limit without changing it,
  4764. ** simply invoke this interface with the third parameter set to -1.
  4765. **
  4766. ** Run-time limits are intended for use in applications that manage
  4767. ** both their own internal database and also databases that are controlled
  4768. ** by untrusted external sources. An example application might be a
  4769. ** web browser that has its own databases for storing history and
  4770. ** separate databases controlled by JavaScript applications downloaded
  4771. ** off the Internet. The internal databases can be given the
  4772. ** large, default limits. Databases managed by external sources can
  4773. ** be given much smaller limits designed to prevent a denial of service
  4774. ** attack. Developers might also want to use the [sqlite3_set_authorizer()]
  4775. ** interface to further control untrusted SQL. The size of the database
  4776. ** created by an untrusted script can be contained using the
  4777. ** [max_page_count] [PRAGMA].
  4778. **
  4779. ** New run-time limit categories may be added in future releases.
  4780. */
  4781. SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);
  4782. /*
  4783. ** CAPI3REF: Run-Time Limit Categories
  4784. ** KEYWORDS: {limit category} {*limit categories}
  4785. **
  4786. ** These constants define various performance limits
  4787. ** that can be lowered at run-time using [sqlite3_limit()].
  4788. ** The synopsis of the meanings of the various limits is shown below.
  4789. ** Additional information is available at [limits | Limits in SQLite].
  4790. **
  4791. ** <dl>
  4792. ** [[SQLITE_LIMIT_LENGTH]] ^(<dt>SQLITE_LIMIT_LENGTH</dt>
  4793. ** <dd>The maximum size of any string or BLOB or table row, in bytes.<dd>)^
  4794. **
  4795. ** [[SQLITE_LIMIT_SQL_LENGTH]] ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt>
  4796. ** <dd>The maximum length of an SQL statement, in bytes.</dd>)^
  4797. **
  4798. ** [[SQLITE_LIMIT_COLUMN]] ^(<dt>SQLITE_LIMIT_COLUMN</dt>
  4799. ** <dd>The maximum number of columns in a table definition or in the
  4800. ** result set of a [SELECT] or the maximum number of columns in an index
  4801. ** or in an ORDER BY or GROUP BY clause.</dd>)^
  4802. **
  4803. ** [[SQLITE_LIMIT_EXPR_DEPTH]] ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
  4804. ** <dd>The maximum depth of the parse tree on any expression.</dd>)^
  4805. **
  4806. ** [[SQLITE_LIMIT_COMPOUND_SELECT]] ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
  4807. ** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^
  4808. **
  4809. ** [[SQLITE_LIMIT_VDBE_OP]] ^(<dt>SQLITE_LIMIT_VDBE_OP</dt>
  4810. ** <dd>The maximum number of instructions in a virtual machine program
  4811. ** used to implement an SQL statement. If [sqlite3_prepare_v2()] or
  4812. ** the equivalent tries to allocate space for more than this many opcodes
  4813. ** in a single prepared statement, an SQLITE_NOMEM error is returned.</dd>)^
  4814. **
  4815. ** [[SQLITE_LIMIT_FUNCTION_ARG]] ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
  4816. ** <dd>The maximum number of arguments on a function.</dd>)^
  4817. **
  4818. ** [[SQLITE_LIMIT_ATTACHED]] ^(<dt>SQLITE_LIMIT_ATTACHED</dt>
  4819. ** <dd>The maximum number of [ATTACH | attached databases].)^</dd>
  4820. **
  4821. ** [[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]]
  4822. ** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
  4823. ** <dd>The maximum length of the pattern argument to the [LIKE] or
  4824. ** [GLOB] operators.</dd>)^
  4825. **
  4826. ** [[SQLITE_LIMIT_VARIABLE_NUMBER]]
  4827. ** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
  4828. ** <dd>The maximum index number of any [parameter] in an SQL statement.)^
  4829. **
  4830. ** [[SQLITE_LIMIT_TRIGGER_DEPTH]] ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
  4831. ** <dd>The maximum depth of recursion for triggers.</dd>)^
  4832. **
  4833. ** [[SQLITE_LIMIT_WORKER_THREADS]] ^(<dt>SQLITE_LIMIT_WORKER_THREADS</dt>
  4834. ** <dd>The maximum number of auxiliary worker threads that a single
  4835. ** [prepared statement] may start.</dd>)^
  4836. ** </dl>
  4837. */
  4838. #define SQLITE_LIMIT_LENGTH 0
  4839. #define SQLITE_LIMIT_SQL_LENGTH 1
  4840. #define SQLITE_LIMIT_COLUMN 2
  4841. #define SQLITE_LIMIT_EXPR_DEPTH 3
  4842. #define SQLITE_LIMIT_COMPOUND_SELECT 4
  4843. #define SQLITE_LIMIT_VDBE_OP 5
  4844. #define SQLITE_LIMIT_FUNCTION_ARG 6
  4845. #define SQLITE_LIMIT_ATTACHED 7
  4846. #define SQLITE_LIMIT_LIKE_PATTERN_LENGTH 8
  4847. #define SQLITE_LIMIT_VARIABLE_NUMBER 9
  4848. #define SQLITE_LIMIT_TRIGGER_DEPTH 10
  4849. #define SQLITE_LIMIT_WORKER_THREADS 11
  4850. /*
  4851. ** CAPI3REF: Prepare Flags
  4852. **
  4853. ** These constants define various flags that can be passed into
  4854. ** "prepFlags" parameter of the [sqlite3_prepare_v3()] and
  4855. ** [sqlite3_prepare16_v3()] interfaces.
  4856. **
  4857. ** New flags may be added in future releases of SQLite.
  4858. **
  4859. ** <dl>
  4860. ** [[SQLITE_PREPARE_PERSISTENT]] ^(<dt>SQLITE_PREPARE_PERSISTENT</dt>
  4861. ** <dd>The SQLITE_PREPARE_PERSISTENT flag is a hint to the query planner
  4862. ** that the prepared statement will be retained for a long time and
  4863. ** probably reused many times.)^ ^Without this flag, [sqlite3_prepare_v3()]
  4864. ** and [sqlite3_prepare16_v3()] assume that the prepared statement will
  4865. ** be used just once or at most a few times and then destroyed using
  4866. ** [sqlite3_finalize()] relatively soon. The current implementation acts
  4867. ** on this hint by avoiding the use of [lookaside memory] so as not to
  4868. ** deplete the limited store of lookaside memory. Future versions of
  4869. ** SQLite may act on this hint differently.
  4870. **
  4871. ** [[SQLITE_PREPARE_NORMALIZE]] <dt>SQLITE_PREPARE_NORMALIZE</dt>
  4872. ** <dd>The SQLITE_PREPARE_NORMALIZE flag is a no-op. This flag used
  4873. ** to be required for any prepared statement that wanted to use the
  4874. ** [sqlite3_normalized_sql()] interface. However, the
  4875. ** [sqlite3_normalized_sql()] interface is now available to all
  4876. ** prepared statements, regardless of whether or not they use this
  4877. ** flag.
  4878. **
  4879. ** [[SQLITE_PREPARE_NO_VTAB]] <dt>SQLITE_PREPARE_NO_VTAB</dt>
  4880. ** <dd>The SQLITE_PREPARE_NO_VTAB flag causes the SQL compiler
  4881. ** to return an error (error code SQLITE_ERROR) if the statement uses
  4882. ** any virtual tables.
  4883. ** </dl>
  4884. */
  4885. #define SQLITE_PREPARE_PERSISTENT 0x01
  4886. #define SQLITE_PREPARE_NORMALIZE 0x02
  4887. #define SQLITE_PREPARE_NO_VTAB 0x04
  4888. /*
  4889. ** CAPI3REF: Compiling An SQL Statement
  4890. ** KEYWORDS: {SQL statement compiler}
  4891. ** METHOD: sqlite3
  4892. ** CONSTRUCTOR: sqlite3_stmt
  4893. **
  4894. ** To execute an SQL statement, it must first be compiled into a byte-code
  4895. ** program using one of these routines. Or, in other words, these routines
  4896. ** are constructors for the [prepared statement] object.
  4897. **
  4898. ** The preferred routine to use is [sqlite3_prepare_v2()]. The
  4899. ** [sqlite3_prepare()] interface is legacy and should be avoided.
  4900. ** [sqlite3_prepare_v3()] has an extra "prepFlags" option that is used
  4901. ** for special purposes.
  4902. **
  4903. ** The use of the UTF-8 interfaces is preferred, as SQLite currently
  4904. ** does all parsing using UTF-8. The UTF-16 interfaces are provided
  4905. ** as a convenience. The UTF-16 interfaces work by converting the
  4906. ** input text into UTF-8, then invoking the corresponding UTF-8 interface.
  4907. **
  4908. ** The first argument, "db", is a [database connection] obtained from a
  4909. ** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or
  4910. ** [sqlite3_open16()]. The database connection must not have been closed.
  4911. **
  4912. ** The second argument, "zSql", is the statement to be compiled, encoded
  4913. ** as either UTF-8 or UTF-16. The sqlite3_prepare(), sqlite3_prepare_v2(),
  4914. ** and sqlite3_prepare_v3()
  4915. ** interfaces use UTF-8, and sqlite3_prepare16(), sqlite3_prepare16_v2(),
  4916. ** and sqlite3_prepare16_v3() use UTF-16.
  4917. **
  4918. ** ^If the nByte argument is negative, then zSql is read up to the
  4919. ** first zero terminator. ^If nByte is positive, then it is the
  4920. ** number of bytes read from zSql. ^If nByte is zero, then no prepared
  4921. ** statement is generated.
  4922. ** If the caller knows that the supplied string is nul-terminated, then
  4923. ** there is a small performance advantage to passing an nByte parameter that
  4924. ** is the number of bytes in the input string <i>including</i>
  4925. ** the nul-terminator.
  4926. **
  4927. ** ^If pzTail is not NULL then *pzTail is made to point to the first byte
  4928. ** past the end of the first SQL statement in zSql. These routines only
  4929. ** compile the first statement in zSql, so *pzTail is left pointing to
  4930. ** what remains uncompiled.
  4931. **
  4932. ** ^*ppStmt is left pointing to a compiled [prepared statement] that can be
  4933. ** executed using [sqlite3_step()]. ^If there is an error, *ppStmt is set
  4934. ** to NULL. ^If the input text contains no SQL (if the input is an empty
  4935. ** string or a comment) then *ppStmt is set to NULL.
  4936. ** The calling procedure is responsible for deleting the compiled
  4937. ** SQL statement using [sqlite3_finalize()] after it has finished with it.
  4938. ** ppStmt may not be NULL.
  4939. **
  4940. ** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK];
  4941. ** otherwise an [error code] is returned.
  4942. **
  4943. ** The sqlite3_prepare_v2(), sqlite3_prepare_v3(), sqlite3_prepare16_v2(),
  4944. ** and sqlite3_prepare16_v3() interfaces are recommended for all new programs.
  4945. ** The older interfaces (sqlite3_prepare() and sqlite3_prepare16())
  4946. ** are retained for backwards compatibility, but their use is discouraged.
  4947. ** ^In the "vX" interfaces, the prepared statement
  4948. ** that is returned (the [sqlite3_stmt] object) contains a copy of the
  4949. ** original SQL text. This causes the [sqlite3_step()] interface to
  4950. ** behave differently in three ways:
  4951. **
  4952. ** <ol>
  4953. ** <li>
  4954. ** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
  4955. ** always used to do, [sqlite3_step()] will automatically recompile the SQL
  4956. ** statement and try to run it again. As many as [SQLITE_MAX_SCHEMA_RETRY]
  4957. ** retries will occur before sqlite3_step() gives up and returns an error.
  4958. ** </li>
  4959. **
  4960. ** <li>
  4961. ** ^When an error occurs, [sqlite3_step()] will return one of the detailed
  4962. ** [error codes] or [extended error codes]. ^The legacy behavior was that
  4963. ** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code
  4964. ** and the application would have to make a second call to [sqlite3_reset()]
  4965. ** in order to find the underlying cause of the problem. With the "v2" prepare
  4966. ** interfaces, the underlying reason for the error is returned immediately.
  4967. ** </li>
  4968. **
  4969. ** <li>
  4970. ** ^If the specific value bound to a [parameter | host parameter] in the
  4971. ** WHERE clause might influence the choice of query plan for a statement,
  4972. ** then the statement will be automatically recompiled, as if there had been
  4973. ** a schema change, on the first [sqlite3_step()] call following any change
  4974. ** to the [sqlite3_bind_text | bindings] of that [parameter].
  4975. ** ^The specific value of a WHERE-clause [parameter] might influence the
  4976. ** choice of query plan if the parameter is the left-hand side of a [LIKE]
  4977. ** or [GLOB] operator or if the parameter is compared to an indexed column
  4978. ** and the [SQLITE_ENABLE_STAT4] compile-time option is enabled.
  4979. ** </li>
  4980. ** </ol>
  4981. **
  4982. ** <p>^sqlite3_prepare_v3() differs from sqlite3_prepare_v2() only in having
  4983. ** the extra prepFlags parameter, which is a bit array consisting of zero or
  4984. ** more of the [SQLITE_PREPARE_PERSISTENT|SQLITE_PREPARE_*] flags. ^The
  4985. ** sqlite3_prepare_v2() interface works exactly the same as
  4986. ** sqlite3_prepare_v3() with a zero prepFlags parameter.
  4987. */
  4988. SQLITE_API int sqlite3_prepare(
  4989. sqlite3 *db, /* Database handle */
  4990. const char *zSql, /* SQL statement, UTF-8 encoded */
  4991. int nByte, /* Maximum length of zSql in bytes. */
  4992. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  4993. const char **pzTail /* OUT: Pointer to unused portion of zSql */
  4994. );
  4995. SQLITE_API int sqlite3_prepare_v2(
  4996. sqlite3 *db, /* Database handle */
  4997. const char *zSql, /* SQL statement, UTF-8 encoded */
  4998. int nByte, /* Maximum length of zSql in bytes. */
  4999. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  5000. const char **pzTail /* OUT: Pointer to unused portion of zSql */
  5001. );
  5002. SQLITE_API int sqlite3_prepare_v3(
  5003. sqlite3 *db, /* Database handle */
  5004. const char *zSql, /* SQL statement, UTF-8 encoded */
  5005. int nByte, /* Maximum length of zSql in bytes. */
  5006. unsigned int prepFlags, /* Zero or more SQLITE_PREPARE_ flags */
  5007. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  5008. const char **pzTail /* OUT: Pointer to unused portion of zSql */
  5009. );
  5010. SQLITE_API int sqlite3_prepare16(
  5011. sqlite3 *db, /* Database handle */
  5012. const void *zSql, /* SQL statement, UTF-16 encoded */
  5013. int nByte, /* Maximum length of zSql in bytes. */
  5014. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  5015. const void **pzTail /* OUT: Pointer to unused portion of zSql */
  5016. );
  5017. SQLITE_API int sqlite3_prepare16_v2(
  5018. sqlite3 *db, /* Database handle */
  5019. const void *zSql, /* SQL statement, UTF-16 encoded */
  5020. int nByte, /* Maximum length of zSql in bytes. */
  5021. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  5022. const void **pzTail /* OUT: Pointer to unused portion of zSql */
  5023. );
  5024. SQLITE_API int sqlite3_prepare16_v3(
  5025. sqlite3 *db, /* Database handle */
  5026. const void *zSql, /* SQL statement, UTF-16 encoded */
  5027. int nByte, /* Maximum length of zSql in bytes. */
  5028. unsigned int prepFlags, /* Zero or more SQLITE_PREPARE_ flags */
  5029. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  5030. const void **pzTail /* OUT: Pointer to unused portion of zSql */
  5031. );
  5032. /*
  5033. ** CAPI3REF: Retrieving Statement SQL
  5034. ** METHOD: sqlite3_stmt
  5035. **
  5036. ** ^The sqlite3_sql(P) interface returns a pointer to a copy of the UTF-8
  5037. ** SQL text used to create [prepared statement] P if P was
  5038. ** created by [sqlite3_prepare_v2()], [sqlite3_prepare_v3()],
  5039. ** [sqlite3_prepare16_v2()], or [sqlite3_prepare16_v3()].
  5040. ** ^The sqlite3_expanded_sql(P) interface returns a pointer to a UTF-8
  5041. ** string containing the SQL text of prepared statement P with
  5042. ** [bound parameters] expanded.
  5043. ** ^The sqlite3_normalized_sql(P) interface returns a pointer to a UTF-8
  5044. ** string containing the normalized SQL text of prepared statement P. The
  5045. ** semantics used to normalize a SQL statement are unspecified and subject
  5046. ** to change. At a minimum, literal values will be replaced with suitable
  5047. ** placeholders.
  5048. **
  5049. ** ^(For example, if a prepared statement is created using the SQL
  5050. ** text "SELECT $abc,:xyz" and if parameter $abc is bound to integer 2345
  5051. ** and parameter :xyz is unbound, then sqlite3_sql() will return
  5052. ** the original string, "SELECT $abc,:xyz" but sqlite3_expanded_sql()
  5053. ** will return "SELECT 2345,NULL".)^
  5054. **
  5055. ** ^The sqlite3_expanded_sql() interface returns NULL if insufficient memory
  5056. ** is available to hold the result, or if the result would exceed the
  5057. ** the maximum string length determined by the [SQLITE_LIMIT_LENGTH].
  5058. **
  5059. ** ^The [SQLITE_TRACE_SIZE_LIMIT] compile-time option limits the size of
  5060. ** bound parameter expansions. ^The [SQLITE_OMIT_TRACE] compile-time
  5061. ** option causes sqlite3_expanded_sql() to always return NULL.
  5062. **
  5063. ** ^The strings returned by sqlite3_sql(P) and sqlite3_normalized_sql(P)
  5064. ** are managed by SQLite and are automatically freed when the prepared
  5065. ** statement is finalized.
  5066. ** ^The string returned by sqlite3_expanded_sql(P), on the other hand,
  5067. ** is obtained from [sqlite3_malloc()] and must be free by the application
  5068. ** by passing it to [sqlite3_free()].
  5069. */
  5070. SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt);
  5071. SQLITE_API char *sqlite3_expanded_sql(sqlite3_stmt *pStmt);
  5072. SQLITE_API const char *sqlite3_normalized_sql(sqlite3_stmt *pStmt);
  5073. /*
  5074. ** CAPI3REF: Determine If An SQL Statement Writes The Database
  5075. ** METHOD: sqlite3_stmt
  5076. **
  5077. ** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if
  5078. ** and only if the [prepared statement] X makes no direct changes to
  5079. ** the content of the database file.
  5080. **
  5081. ** Note that [application-defined SQL functions] or
  5082. ** [virtual tables] might change the database indirectly as a side effect.
  5083. ** ^(For example, if an application defines a function "eval()" that
  5084. ** calls [sqlite3_exec()], then the following SQL statement would
  5085. ** change the database file through side-effects:
  5086. **
  5087. ** <blockquote><pre>
  5088. ** SELECT eval('DELETE FROM t1') FROM t2;
  5089. ** </pre></blockquote>
  5090. **
  5091. ** But because the [SELECT] statement does not change the database file
  5092. ** directly, sqlite3_stmt_readonly() would still return true.)^
  5093. **
  5094. ** ^Transaction control statements such as [BEGIN], [COMMIT], [ROLLBACK],
  5095. ** [SAVEPOINT], and [RELEASE] cause sqlite3_stmt_readonly() to return true,
  5096. ** since the statements themselves do not actually modify the database but
  5097. ** rather they control the timing of when other statements modify the
  5098. ** database. ^The [ATTACH] and [DETACH] statements also cause
  5099. ** sqlite3_stmt_readonly() to return true since, while those statements
  5100. ** change the configuration of a database connection, they do not make
  5101. ** changes to the content of the database files on disk.
  5102. ** ^The sqlite3_stmt_readonly() interface returns true for [BEGIN] since
  5103. ** [BEGIN] merely sets internal flags, but the [BEGIN|BEGIN IMMEDIATE] and
  5104. ** [BEGIN|BEGIN EXCLUSIVE] commands do touch the database and so
  5105. ** sqlite3_stmt_readonly() returns false for those commands.
  5106. */
  5107. SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt);
  5108. /*
  5109. ** CAPI3REF: Query The EXPLAIN Setting For A Prepared Statement
  5110. ** METHOD: sqlite3_stmt
  5111. **
  5112. ** ^The sqlite3_stmt_isexplain(S) interface returns 1 if the
  5113. ** prepared statement S is an EXPLAIN statement, or 2 if the
  5114. ** statement S is an EXPLAIN QUERY PLAN.
  5115. ** ^The sqlite3_stmt_isexplain(S) interface returns 0 if S is
  5116. ** an ordinary statement or a NULL pointer.
  5117. */
  5118. SQLITE_API int sqlite3_stmt_isexplain(sqlite3_stmt *pStmt);
  5119. /*
  5120. ** CAPI3REF: Determine If A Prepared Statement Has Been Reset
  5121. ** METHOD: sqlite3_stmt
  5122. **
  5123. ** ^The sqlite3_stmt_busy(S) interface returns true (non-zero) if the
  5124. ** [prepared statement] S has been stepped at least once using
  5125. ** [sqlite3_step(S)] but has neither run to completion (returned
  5126. ** [SQLITE_DONE] from [sqlite3_step(S)]) nor
  5127. ** been reset using [sqlite3_reset(S)]. ^The sqlite3_stmt_busy(S)
  5128. ** interface returns false if S is a NULL pointer. If S is not a
  5129. ** NULL pointer and is not a pointer to a valid [prepared statement]
  5130. ** object, then the behavior is undefined and probably undesirable.
  5131. **
  5132. ** This interface can be used in combination [sqlite3_next_stmt()]
  5133. ** to locate all prepared statements associated with a database
  5134. ** connection that are in need of being reset. This can be used,
  5135. ** for example, in diagnostic routines to search for prepared
  5136. ** statements that are holding a transaction open.
  5137. */
  5138. SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt*);
  5139. /*
  5140. ** CAPI3REF: Dynamically Typed Value Object
  5141. ** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}
  5142. **
  5143. ** SQLite uses the sqlite3_value object to represent all values
  5144. ** that can be stored in a database table. SQLite uses dynamic typing
  5145. ** for the values it stores. ^Values stored in sqlite3_value objects
  5146. ** can be integers, floating point values, strings, BLOBs, or NULL.
  5147. **
  5148. ** An sqlite3_value object may be either "protected" or "unprotected".
  5149. ** Some interfaces require a protected sqlite3_value. Other interfaces
  5150. ** will accept either a protected or an unprotected sqlite3_value.
  5151. ** Every interface that accepts sqlite3_value arguments specifies
  5152. ** whether or not it requires a protected sqlite3_value. The
  5153. ** [sqlite3_value_dup()] interface can be used to construct a new
  5154. ** protected sqlite3_value from an unprotected sqlite3_value.
  5155. **
  5156. ** The terms "protected" and "unprotected" refer to whether or not
  5157. ** a mutex is held. An internal mutex is held for a protected
  5158. ** sqlite3_value object but no mutex is held for an unprotected
  5159. ** sqlite3_value object. If SQLite is compiled to be single-threaded
  5160. ** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)
  5161. ** or if SQLite is run in one of reduced mutex modes
  5162. ** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
  5163. ** then there is no distinction between protected and unprotected
  5164. ** sqlite3_value objects and they can be used interchangeably. However,
  5165. ** for maximum code portability it is recommended that applications
  5166. ** still make the distinction between protected and unprotected
  5167. ** sqlite3_value objects even when not strictly required.
  5168. **
  5169. ** ^The sqlite3_value objects that are passed as parameters into the
  5170. ** implementation of [application-defined SQL functions] are protected.
  5171. ** ^The sqlite3_value object returned by
  5172. ** [sqlite3_column_value()] is unprotected.
  5173. ** Unprotected sqlite3_value objects may only be used as arguments
  5174. ** to [sqlite3_result_value()], [sqlite3_bind_value()], and
  5175. ** [sqlite3_value_dup()].
  5176. ** The [sqlite3_value_blob | sqlite3_value_type()] family of
  5177. ** interfaces require protected sqlite3_value objects.
  5178. */
  5179. typedef struct sqlite3_value sqlite3_value;
  5180. /*
  5181. ** CAPI3REF: SQL Function Context Object
  5182. **
  5183. ** The context in which an SQL function executes is stored in an
  5184. ** sqlite3_context object. ^A pointer to an sqlite3_context object
  5185. ** is always first parameter to [application-defined SQL functions].
  5186. ** The application-defined SQL function implementation will pass this
  5187. ** pointer through into calls to [sqlite3_result_int | sqlite3_result()],
  5188. ** [sqlite3_aggregate_context()], [sqlite3_user_data()],
  5189. ** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],
  5190. ** and/or [sqlite3_set_auxdata()].
  5191. */
  5192. typedef struct sqlite3_context sqlite3_context;
  5193. /*
  5194. ** CAPI3REF: Binding Values To Prepared Statements
  5195. ** KEYWORDS: {host parameter} {host parameters} {host parameter name}
  5196. ** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}
  5197. ** METHOD: sqlite3_stmt
  5198. **
  5199. ** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants,
  5200. ** literals may be replaced by a [parameter] that matches one of following
  5201. ** templates:
  5202. **
  5203. ** <ul>
  5204. ** <li> ?
  5205. ** <li> ?NNN
  5206. ** <li> :VVV
  5207. ** <li> @VVV
  5208. ** <li> $VVV
  5209. ** </ul>
  5210. **
  5211. ** In the templates above, NNN represents an integer literal,
  5212. ** and VVV represents an alphanumeric identifier.)^ ^The values of these
  5213. ** parameters (also called "host parameter names" or "SQL parameters")
  5214. ** can be set using the sqlite3_bind_*() routines defined here.
  5215. **
  5216. ** ^The first argument to the sqlite3_bind_*() routines is always
  5217. ** a pointer to the [sqlite3_stmt] object returned from
  5218. ** [sqlite3_prepare_v2()] or its variants.
  5219. **
  5220. ** ^The second argument is the index of the SQL parameter to be set.
  5221. ** ^The leftmost SQL parameter has an index of 1. ^When the same named
  5222. ** SQL parameter is used more than once, second and subsequent
  5223. ** occurrences have the same index as the first occurrence.
  5224. ** ^The index for named parameters can be looked up using the
  5225. ** [sqlite3_bind_parameter_index()] API if desired. ^The index
  5226. ** for "?NNN" parameters is the value of NNN.
  5227. ** ^The NNN value must be between 1 and the [sqlite3_limit()]
  5228. ** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 32766).
  5229. **
  5230. ** ^The third argument is the value to bind to the parameter.
  5231. ** ^If the third parameter to sqlite3_bind_text() or sqlite3_bind_text16()
  5232. ** or sqlite3_bind_blob() is a NULL pointer then the fourth parameter
  5233. ** is ignored and the end result is the same as sqlite3_bind_null().
  5234. ** ^If the third parameter to sqlite3_bind_text() is not NULL, then
  5235. ** it should be a pointer to well-formed UTF8 text.
  5236. ** ^If the third parameter to sqlite3_bind_text16() is not NULL, then
  5237. ** it should be a pointer to well-formed UTF16 text.
  5238. ** ^If the third parameter to sqlite3_bind_text64() is not NULL, then
  5239. ** it should be a pointer to a well-formed unicode string that is
  5240. ** either UTF8 if the sixth parameter is SQLITE_UTF8, or UTF16
  5241. ** otherwise.
  5242. **
  5243. ** [[byte-order determination rules]] ^The byte-order of
  5244. ** UTF16 input text is determined by the byte-order mark (BOM, U+FEFF)
  5245. ** found in first character, which is removed, or in the absence of a BOM
  5246. ** the byte order is the native byte order of the host
  5247. ** machine for sqlite3_bind_text16() or the byte order specified in
  5248. ** the 6th parameter for sqlite3_bind_text64().)^
  5249. ** ^If UTF16 input text contains invalid unicode
  5250. ** characters, then SQLite might change those invalid characters
  5251. ** into the unicode replacement character: U+FFFD.
  5252. **
  5253. ** ^(In those routines that have a fourth argument, its value is the
  5254. ** number of bytes in the parameter. To be clear: the value is the
  5255. ** number of <u>bytes</u> in the value, not the number of characters.)^
  5256. ** ^If the fourth parameter to sqlite3_bind_text() or sqlite3_bind_text16()
  5257. ** is negative, then the length of the string is
  5258. ** the number of bytes up to the first zero terminator.
  5259. ** If the fourth parameter to sqlite3_bind_blob() is negative, then
  5260. ** the behavior is undefined.
  5261. ** If a non-negative fourth parameter is provided to sqlite3_bind_text()
  5262. ** or sqlite3_bind_text16() or sqlite3_bind_text64() then
  5263. ** that parameter must be the byte offset
  5264. ** where the NUL terminator would occur assuming the string were NUL
  5265. ** terminated. If any NUL characters occurs at byte offsets less than
  5266. ** the value of the fourth parameter then the resulting string value will
  5267. ** contain embedded NULs. The result of expressions involving strings
  5268. ** with embedded NULs is undefined.
  5269. **
  5270. ** ^The fifth argument to the BLOB and string binding interfaces
  5271. ** is a destructor used to dispose of the BLOB or
  5272. ** string after SQLite has finished with it. ^The destructor is called
  5273. ** to dispose of the BLOB or string even if the call to the bind API fails,
  5274. ** except the destructor is not called if the third parameter is a NULL
  5275. ** pointer or the fourth parameter is negative.
  5276. ** ^If the fifth argument is
  5277. ** the special value [SQLITE_STATIC], then SQLite assumes that the
  5278. ** information is in static, unmanaged space and does not need to be freed.
  5279. ** ^If the fifth argument has the value [SQLITE_TRANSIENT], then
  5280. ** SQLite makes its own private copy of the data immediately, before
  5281. ** the sqlite3_bind_*() routine returns.
  5282. **
  5283. ** ^The sixth argument to sqlite3_bind_text64() must be one of
  5284. ** [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE]
  5285. ** to specify the encoding of the text in the third parameter. If
  5286. ** the sixth argument to sqlite3_bind_text64() is not one of the
  5287. ** allowed values shown above, or if the text encoding is different
  5288. ** from the encoding specified by the sixth parameter, then the behavior
  5289. ** is undefined.
  5290. **
  5291. ** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
  5292. ** is filled with zeroes. ^A zeroblob uses a fixed amount of memory
  5293. ** (just an integer to hold its size) while it is being processed.
  5294. ** Zeroblobs are intended to serve as placeholders for BLOBs whose
  5295. ** content is later written using
  5296. ** [sqlite3_blob_open | incremental BLOB I/O] routines.
  5297. ** ^A negative value for the zeroblob results in a zero-length BLOB.
  5298. **
  5299. ** ^The sqlite3_bind_pointer(S,I,P,T,D) routine causes the I-th parameter in
  5300. ** [prepared statement] S to have an SQL value of NULL, but to also be
  5301. ** associated with the pointer P of type T. ^D is either a NULL pointer or
  5302. ** a pointer to a destructor function for P. ^SQLite will invoke the
  5303. ** destructor D with a single argument of P when it is finished using
  5304. ** P. The T parameter should be a static string, preferably a string
  5305. ** literal. The sqlite3_bind_pointer() routine is part of the
  5306. ** [pointer passing interface] added for SQLite 3.20.0.
  5307. **
  5308. ** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer
  5309. ** for the [prepared statement] or with a prepared statement for which
  5310. ** [sqlite3_step()] has been called more recently than [sqlite3_reset()],
  5311. ** then the call will return [SQLITE_MISUSE]. If any sqlite3_bind_()
  5312. ** routine is passed a [prepared statement] that has been finalized, the
  5313. ** result is undefined and probably harmful.
  5314. **
  5315. ** ^Bindings are not cleared by the [sqlite3_reset()] routine.
  5316. ** ^Unbound parameters are interpreted as NULL.
  5317. **
  5318. ** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an
  5319. ** [error code] if anything goes wrong.
  5320. ** ^[SQLITE_TOOBIG] might be returned if the size of a string or BLOB
  5321. ** exceeds limits imposed by [sqlite3_limit]([SQLITE_LIMIT_LENGTH]) or
  5322. ** [SQLITE_MAX_LENGTH].
  5323. ** ^[SQLITE_RANGE] is returned if the parameter
  5324. ** index is out of range. ^[SQLITE_NOMEM] is returned if malloc() fails.
  5325. **
  5326. ** See also: [sqlite3_bind_parameter_count()],
  5327. ** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].
  5328. */
  5329. SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
  5330. SQLITE_API int sqlite3_bind_blob64(sqlite3_stmt*, int, const void*, sqlite3_uint64,
  5331. void(*)(void*));
  5332. SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double);
  5333. SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int);
  5334. SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
  5335. SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int);
  5336. SQLITE_API int sqlite3_bind_text(sqlite3_stmt*,int,const char*,int,void(*)(void*));
  5337. SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
  5338. SQLITE_API int sqlite3_bind_text64(sqlite3_stmt*, int, const char*, sqlite3_uint64,
  5339. void(*)(void*), unsigned char encoding);
  5340. SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
  5341. SQLITE_API int sqlite3_bind_pointer(sqlite3_stmt*, int, void*, const char*,void(*)(void*));
  5342. SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
  5343. SQLITE_API int sqlite3_bind_zeroblob64(sqlite3_stmt*, int, sqlite3_uint64);
  5344. /*
  5345. ** CAPI3REF: Number Of SQL Parameters
  5346. ** METHOD: sqlite3_stmt
  5347. **
  5348. ** ^This routine can be used to find the number of [SQL parameters]
  5349. ** in a [prepared statement]. SQL parameters are tokens of the
  5350. ** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
  5351. ** placeholders for values that are [sqlite3_bind_blob | bound]
  5352. ** to the parameters at a later time.
  5353. **
  5354. ** ^(This routine actually returns the index of the largest (rightmost)
  5355. ** parameter. For all forms except ?NNN, this will correspond to the
  5356. ** number of unique parameters. If parameters of the ?NNN form are used,
  5357. ** there may be gaps in the list.)^
  5358. **
  5359. ** See also: [sqlite3_bind_blob|sqlite3_bind()],
  5360. ** [sqlite3_bind_parameter_name()], and
  5361. ** [sqlite3_bind_parameter_index()].
  5362. */
  5363. SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*);
  5364. /*
  5365. ** CAPI3REF: Name Of A Host Parameter
  5366. ** METHOD: sqlite3_stmt
  5367. **
  5368. ** ^The sqlite3_bind_parameter_name(P,N) interface returns
  5369. ** the name of the N-th [SQL parameter] in the [prepared statement] P.
  5370. ** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"
  5371. ** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"
  5372. ** respectively.
  5373. ** In other words, the initial ":" or "$" or "@" or "?"
  5374. ** is included as part of the name.)^
  5375. ** ^Parameters of the form "?" without a following integer have no name
  5376. ** and are referred to as "nameless" or "anonymous parameters".
  5377. **
  5378. ** ^The first host parameter has an index of 1, not 0.
  5379. **
  5380. ** ^If the value N is out of range or if the N-th parameter is
  5381. ** nameless, then NULL is returned. ^The returned string is
  5382. ** always in UTF-8 encoding even if the named parameter was
  5383. ** originally specified as UTF-16 in [sqlite3_prepare16()],
  5384. ** [sqlite3_prepare16_v2()], or [sqlite3_prepare16_v3()].
  5385. **
  5386. ** See also: [sqlite3_bind_blob|sqlite3_bind()],
  5387. ** [sqlite3_bind_parameter_count()], and
  5388. ** [sqlite3_bind_parameter_index()].
  5389. */
  5390. SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
  5391. /*
  5392. ** CAPI3REF: Index Of A Parameter With A Given Name
  5393. ** METHOD: sqlite3_stmt
  5394. **
  5395. ** ^Return the index of an SQL parameter given its name. ^The
  5396. ** index value returned is suitable for use as the second
  5397. ** parameter to [sqlite3_bind_blob|sqlite3_bind()]. ^A zero
  5398. ** is returned if no matching parameter is found. ^The parameter
  5399. ** name must be given in UTF-8 even if the original statement
  5400. ** was prepared from UTF-16 text using [sqlite3_prepare16_v2()] or
  5401. ** [sqlite3_prepare16_v3()].
  5402. **
  5403. ** See also: [sqlite3_bind_blob|sqlite3_bind()],
  5404. ** [sqlite3_bind_parameter_count()], and
  5405. ** [sqlite3_bind_parameter_name()].
  5406. */
  5407. SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
  5408. /*
  5409. ** CAPI3REF: Reset All Bindings On A Prepared Statement
  5410. ** METHOD: sqlite3_stmt
  5411. **
  5412. ** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset
  5413. ** the [sqlite3_bind_blob | bindings] on a [prepared statement].
  5414. ** ^Use this routine to reset all host parameters to NULL.
  5415. */
  5416. SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*);
  5417. /*
  5418. ** CAPI3REF: Number Of Columns In A Result Set
  5419. ** METHOD: sqlite3_stmt
  5420. **
  5421. ** ^Return the number of columns in the result set returned by the
  5422. ** [prepared statement]. ^If this routine returns 0, that means the
  5423. ** [prepared statement] returns no data (for example an [UPDATE]).
  5424. ** ^However, just because this routine returns a positive number does not
  5425. ** mean that one or more rows of data will be returned. ^A SELECT statement
  5426. ** will always have a positive sqlite3_column_count() but depending on the
  5427. ** WHERE clause constraints and the table content, it might return no rows.
  5428. **
  5429. ** See also: [sqlite3_data_count()]
  5430. */
  5431. SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt);
  5432. /*
  5433. ** CAPI3REF: Column Names In A Result Set
  5434. ** METHOD: sqlite3_stmt
  5435. **
  5436. ** ^These routines return the name assigned to a particular column
  5437. ** in the result set of a [SELECT] statement. ^The sqlite3_column_name()
  5438. ** interface returns a pointer to a zero-terminated UTF-8 string
  5439. ** and sqlite3_column_name16() returns a pointer to a zero-terminated
  5440. ** UTF-16 string. ^The first parameter is the [prepared statement]
  5441. ** that implements the [SELECT] statement. ^The second parameter is the
  5442. ** column number. ^The leftmost column is number 0.
  5443. **
  5444. ** ^The returned string pointer is valid until either the [prepared statement]
  5445. ** is destroyed by [sqlite3_finalize()] or until the statement is automatically
  5446. ** reprepared by the first call to [sqlite3_step()] for a particular run
  5447. ** or until the next call to
  5448. ** sqlite3_column_name() or sqlite3_column_name16() on the same column.
  5449. **
  5450. ** ^If sqlite3_malloc() fails during the processing of either routine
  5451. ** (for example during a conversion from UTF-8 to UTF-16) then a
  5452. ** NULL pointer is returned.
  5453. **
  5454. ** ^The name of a result column is the value of the "AS" clause for
  5455. ** that column, if there is an AS clause. If there is no AS clause
  5456. ** then the name of the column is unspecified and may change from
  5457. ** one release of SQLite to the next.
  5458. */
  5459. SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N);
  5460. SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N);
  5461. /*
  5462. ** CAPI3REF: Source Of Data In A Query Result
  5463. ** METHOD: sqlite3_stmt
  5464. **
  5465. ** ^These routines provide a means to determine the database, table, and
  5466. ** table column that is the origin of a particular result column in
  5467. ** [SELECT] statement.
  5468. ** ^The name of the database or table or column can be returned as
  5469. ** either a UTF-8 or UTF-16 string. ^The _database_ routines return
  5470. ** the database name, the _table_ routines return the table name, and
  5471. ** the origin_ routines return the column name.
  5472. ** ^The returned string is valid until the [prepared statement] is destroyed
  5473. ** using [sqlite3_finalize()] or until the statement is automatically
  5474. ** reprepared by the first call to [sqlite3_step()] for a particular run
  5475. ** or until the same information is requested
  5476. ** again in a different encoding.
  5477. **
  5478. ** ^The names returned are the original un-aliased names of the
  5479. ** database, table, and column.
  5480. **
  5481. ** ^The first argument to these interfaces is a [prepared statement].
  5482. ** ^These functions return information about the Nth result column returned by
  5483. ** the statement, where N is the second function argument.
  5484. ** ^The left-most column is column 0 for these routines.
  5485. **
  5486. ** ^If the Nth column returned by the statement is an expression or
  5487. ** subquery and is not a column value, then all of these functions return
  5488. ** NULL. ^These routines might also return NULL if a memory allocation error
  5489. ** occurs. ^Otherwise, they return the name of the attached database, table,
  5490. ** or column that query result column was extracted from.
  5491. **
  5492. ** ^As with all other SQLite APIs, those whose names end with "16" return
  5493. ** UTF-16 encoded strings and the other functions return UTF-8.
  5494. **
  5495. ** ^These APIs are only available if the library was compiled with the
  5496. ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol.
  5497. **
  5498. ** If two or more threads call one or more
  5499. ** [sqlite3_column_database_name | column metadata interfaces]
  5500. ** for the same [prepared statement] and result column
  5501. ** at the same time then the results are undefined.
  5502. */
  5503. SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int);
  5504. SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int);
  5505. SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int);
  5506. SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int);
  5507. SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int);
  5508. SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);
  5509. /*
  5510. ** CAPI3REF: Declared Datatype Of A Query Result
  5511. ** METHOD: sqlite3_stmt
  5512. **
  5513. ** ^(The first parameter is a [prepared statement].
  5514. ** If this statement is a [SELECT] statement and the Nth column of the
  5515. ** returned result set of that [SELECT] is a table column (not an
  5516. ** expression or subquery) then the declared type of the table
  5517. ** column is returned.)^ ^If the Nth column of the result set is an
  5518. ** expression or subquery, then a NULL pointer is returned.
  5519. ** ^The returned string is always UTF-8 encoded.
  5520. **
  5521. ** ^(For example, given the database schema:
  5522. **
  5523. ** CREATE TABLE t1(c1 VARIANT);
  5524. **
  5525. ** and the following statement to be compiled:
  5526. **
  5527. ** SELECT c1 + 1, c1 FROM t1;
  5528. **
  5529. ** this routine would return the string "VARIANT" for the second result
  5530. ** column (i==1), and a NULL pointer for the first result column (i==0).)^
  5531. **
  5532. ** ^SQLite uses dynamic run-time typing. ^So just because a column
  5533. ** is declared to contain a particular type does not mean that the
  5534. ** data stored in that column is of the declared type. SQLite is
  5535. ** strongly typed, but the typing is dynamic not static. ^Type
  5536. ** is associated with individual values, not with the containers
  5537. ** used to hold those values.
  5538. */
  5539. SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int);
  5540. SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int);
  5541. /*
  5542. ** CAPI3REF: Evaluate An SQL Statement
  5543. ** METHOD: sqlite3_stmt
  5544. **
  5545. ** After a [prepared statement] has been prepared using any of
  5546. ** [sqlite3_prepare_v2()], [sqlite3_prepare_v3()], [sqlite3_prepare16_v2()],
  5547. ** or [sqlite3_prepare16_v3()] or one of the legacy
  5548. ** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function
  5549. ** must be called one or more times to evaluate the statement.
  5550. **
  5551. ** The details of the behavior of the sqlite3_step() interface depend
  5552. ** on whether the statement was prepared using the newer "vX" interfaces
  5553. ** [sqlite3_prepare_v3()], [sqlite3_prepare_v2()], [sqlite3_prepare16_v3()],
  5554. ** [sqlite3_prepare16_v2()] or the older legacy
  5555. ** interfaces [sqlite3_prepare()] and [sqlite3_prepare16()]. The use of the
  5556. ** new "vX" interface is recommended for new applications but the legacy
  5557. ** interface will continue to be supported.
  5558. **
  5559. ** ^In the legacy interface, the return value will be either [SQLITE_BUSY],
  5560. ** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
  5561. ** ^With the "v2" interface, any of the other [result codes] or
  5562. ** [extended result codes] might be returned as well.
  5563. **
  5564. ** ^[SQLITE_BUSY] means that the database engine was unable to acquire the
  5565. ** database locks it needs to do its job. ^If the statement is a [COMMIT]
  5566. ** or occurs outside of an explicit transaction, then you can retry the
  5567. ** statement. If the statement is not a [COMMIT] and occurs within an
  5568. ** explicit transaction then you should rollback the transaction before
  5569. ** continuing.
  5570. **
  5571. ** ^[SQLITE_DONE] means that the statement has finished executing
  5572. ** successfully. sqlite3_step() should not be called again on this virtual
  5573. ** machine without first calling [sqlite3_reset()] to reset the virtual
  5574. ** machine back to its initial state.
  5575. **
  5576. ** ^If the SQL statement being executed returns any data, then [SQLITE_ROW]
  5577. ** is returned each time a new row of data is ready for processing by the
  5578. ** caller. The values may be accessed using the [column access functions].
  5579. ** sqlite3_step() is called again to retrieve the next row of data.
  5580. **
  5581. ** ^[SQLITE_ERROR] means that a run-time error (such as a constraint
  5582. ** violation) has occurred. sqlite3_step() should not be called again on
  5583. ** the VM. More information may be found by calling [sqlite3_errmsg()].
  5584. ** ^With the legacy interface, a more specific error code (for example,
  5585. ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
  5586. ** can be obtained by calling [sqlite3_reset()] on the
  5587. ** [prepared statement]. ^In the "v2" interface,
  5588. ** the more specific error code is returned directly by sqlite3_step().
  5589. **
  5590. ** [SQLITE_MISUSE] means that the this routine was called inappropriately.
  5591. ** Perhaps it was called on a [prepared statement] that has
  5592. ** already been [sqlite3_finalize | finalized] or on one that had
  5593. ** previously returned [SQLITE_ERROR] or [SQLITE_DONE]. Or it could
  5594. ** be the case that the same database connection is being used by two or
  5595. ** more threads at the same moment in time.
  5596. **
  5597. ** For all versions of SQLite up to and including 3.6.23.1, a call to
  5598. ** [sqlite3_reset()] was required after sqlite3_step() returned anything
  5599. ** other than [SQLITE_ROW] before any subsequent invocation of
  5600. ** sqlite3_step(). Failure to reset the prepared statement using
  5601. ** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from
  5602. ** sqlite3_step(). But after [version 3.6.23.1] ([dateof:3.6.23.1],
  5603. ** sqlite3_step() began
  5604. ** calling [sqlite3_reset()] automatically in this circumstance rather
  5605. ** than returning [SQLITE_MISUSE]. This is not considered a compatibility
  5606. ** break because any application that ever receives an SQLITE_MISUSE error
  5607. ** is broken by definition. The [SQLITE_OMIT_AUTORESET] compile-time option
  5608. ** can be used to restore the legacy behavior.
  5609. **
  5610. ** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()
  5611. ** API always returns a generic error code, [SQLITE_ERROR], following any
  5612. ** error other than [SQLITE_BUSY] and [SQLITE_MISUSE]. You must call
  5613. ** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the
  5614. ** specific [error codes] that better describes the error.
  5615. ** We admit that this is a goofy design. The problem has been fixed
  5616. ** with the "v2" interface. If you prepare all of your SQL statements
  5617. ** using [sqlite3_prepare_v3()] or [sqlite3_prepare_v2()]
  5618. ** or [sqlite3_prepare16_v2()] or [sqlite3_prepare16_v3()] instead
  5619. ** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,
  5620. ** then the more specific [error codes] are returned directly
  5621. ** by sqlite3_step(). The use of the "vX" interfaces is recommended.
  5622. */
  5623. SQLITE_API int sqlite3_step(sqlite3_stmt*);
  5624. /*
  5625. ** CAPI3REF: Number of columns in a result set
  5626. ** METHOD: sqlite3_stmt
  5627. **
  5628. ** ^The sqlite3_data_count(P) interface returns the number of columns in the
  5629. ** current row of the result set of [prepared statement] P.
  5630. ** ^If prepared statement P does not have results ready to return
  5631. ** (via calls to the [sqlite3_column_int | sqlite3_column()] family of
  5632. ** interfaces) then sqlite3_data_count(P) returns 0.
  5633. ** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer.
  5634. ** ^The sqlite3_data_count(P) routine returns 0 if the previous call to
  5635. ** [sqlite3_step](P) returned [SQLITE_DONE]. ^The sqlite3_data_count(P)
  5636. ** will return non-zero if previous call to [sqlite3_step](P) returned
  5637. ** [SQLITE_ROW], except in the case of the [PRAGMA incremental_vacuum]
  5638. ** where it always returns zero since each step of that multi-step
  5639. ** pragma returns 0 columns of data.
  5640. **
  5641. ** See also: [sqlite3_column_count()]
  5642. */
  5643. SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
  5644. /*
  5645. ** CAPI3REF: Fundamental Datatypes
  5646. ** KEYWORDS: SQLITE_TEXT
  5647. **
  5648. ** ^(Every value in SQLite has one of five fundamental datatypes:
  5649. **
  5650. ** <ul>
  5651. ** <li> 64-bit signed integer
  5652. ** <li> 64-bit IEEE floating point number
  5653. ** <li> string
  5654. ** <li> BLOB
  5655. ** <li> NULL
  5656. ** </ul>)^
  5657. **
  5658. ** These constants are codes for each of those types.
  5659. **
  5660. ** Note that the SQLITE_TEXT constant was also used in SQLite version 2
  5661. ** for a completely different meaning. Software that links against both
  5662. ** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not
  5663. ** SQLITE_TEXT.
  5664. */
  5665. #define SQLITE_INTEGER 1
  5666. #define SQLITE_FLOAT 2
  5667. #define SQLITE_BLOB 4
  5668. #define SQLITE_NULL 5
  5669. #ifdef SQLITE_TEXT
  5670. # undef SQLITE_TEXT
  5671. #else
  5672. # define SQLITE_TEXT 3
  5673. #endif
  5674. #define SQLITE3_TEXT 3
  5675. /*
  5676. ** CAPI3REF: Result Values From A Query
  5677. ** KEYWORDS: {column access functions}
  5678. ** METHOD: sqlite3_stmt
  5679. **
  5680. ** <b>Summary:</b>
  5681. ** <blockquote><table border=0 cellpadding=0 cellspacing=0>
  5682. ** <tr><td><b>sqlite3_column_blob</b><td>&rarr;<td>BLOB result
  5683. ** <tr><td><b>sqlite3_column_double</b><td>&rarr;<td>REAL result
  5684. ** <tr><td><b>sqlite3_column_int</b><td>&rarr;<td>32-bit INTEGER result
  5685. ** <tr><td><b>sqlite3_column_int64</b><td>&rarr;<td>64-bit INTEGER result
  5686. ** <tr><td><b>sqlite3_column_text</b><td>&rarr;<td>UTF-8 TEXT result
  5687. ** <tr><td><b>sqlite3_column_text16</b><td>&rarr;<td>UTF-16 TEXT result
  5688. ** <tr><td><b>sqlite3_column_value</b><td>&rarr;<td>The result as an
  5689. ** [sqlite3_value|unprotected sqlite3_value] object.
  5690. ** <tr><td>&nbsp;<td>&nbsp;<td>&nbsp;
  5691. ** <tr><td><b>sqlite3_column_bytes</b><td>&rarr;<td>Size of a BLOB
  5692. ** or a UTF-8 TEXT result in bytes
  5693. ** <tr><td><b>sqlite3_column_bytes16&nbsp;&nbsp;</b>
  5694. ** <td>&rarr;&nbsp;&nbsp;<td>Size of UTF-16
  5695. ** TEXT in bytes
  5696. ** <tr><td><b>sqlite3_column_type</b><td>&rarr;<td>Default
  5697. ** datatype of the result
  5698. ** </table></blockquote>
  5699. **
  5700. ** <b>Details:</b>
  5701. **
  5702. ** ^These routines return information about a single column of the current
  5703. ** result row of a query. ^In every case the first argument is a pointer
  5704. ** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]
  5705. ** that was returned from [sqlite3_prepare_v2()] or one of its variants)
  5706. ** and the second argument is the index of the column for which information
  5707. ** should be returned. ^The leftmost column of the result set has the index 0.
  5708. ** ^The number of columns in the result can be determined using
  5709. ** [sqlite3_column_count()].
  5710. **
  5711. ** If the SQL statement does not currently point to a valid row, or if the
  5712. ** column index is out of range, the result is undefined.
  5713. ** These routines may only be called when the most recent call to
  5714. ** [sqlite3_step()] has returned [SQLITE_ROW] and neither
  5715. ** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.
  5716. ** If any of these routines are called after [sqlite3_reset()] or
  5717. ** [sqlite3_finalize()] or after [sqlite3_step()] has returned
  5718. ** something other than [SQLITE_ROW], the results are undefined.
  5719. ** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
  5720. ** are called from a different thread while any of these routines
  5721. ** are pending, then the results are undefined.
  5722. **
  5723. ** The first six interfaces (_blob, _double, _int, _int64, _text, and _text16)
  5724. ** each return the value of a result column in a specific data format. If
  5725. ** the result column is not initially in the requested format (for example,
  5726. ** if the query returns an integer but the sqlite3_column_text() interface
  5727. ** is used to extract the value) then an automatic type conversion is performed.
  5728. **
  5729. ** ^The sqlite3_column_type() routine returns the
  5730. ** [SQLITE_INTEGER | datatype code] for the initial data type
  5731. ** of the result column. ^The returned value is one of [SQLITE_INTEGER],
  5732. ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].
  5733. ** The return value of sqlite3_column_type() can be used to decide which
  5734. ** of the first six interface should be used to extract the column value.
  5735. ** The value returned by sqlite3_column_type() is only meaningful if no
  5736. ** automatic type conversions have occurred for the value in question.
  5737. ** After a type conversion, the result of calling sqlite3_column_type()
  5738. ** is undefined, though harmless. Future
  5739. ** versions of SQLite may change the behavior of sqlite3_column_type()
  5740. ** following a type conversion.
  5741. **
  5742. ** If the result is a BLOB or a TEXT string, then the sqlite3_column_bytes()
  5743. ** or sqlite3_column_bytes16() interfaces can be used to determine the size
  5744. ** of that BLOB or string.
  5745. **
  5746. ** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
  5747. ** routine returns the number of bytes in that BLOB or string.
  5748. ** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts
  5749. ** the string to UTF-8 and then returns the number of bytes.
  5750. ** ^If the result is a numeric value then sqlite3_column_bytes() uses
  5751. ** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
  5752. ** the number of bytes in that string.
  5753. ** ^If the result is NULL, then sqlite3_column_bytes() returns zero.
  5754. **
  5755. ** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16()
  5756. ** routine returns the number of bytes in that BLOB or string.
  5757. ** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts
  5758. ** the string to UTF-16 and then returns the number of bytes.
  5759. ** ^If the result is a numeric value then sqlite3_column_bytes16() uses
  5760. ** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns
  5761. ** the number of bytes in that string.
  5762. ** ^If the result is NULL, then sqlite3_column_bytes16() returns zero.
  5763. **
  5764. ** ^The values returned by [sqlite3_column_bytes()] and
  5765. ** [sqlite3_column_bytes16()] do not include the zero terminators at the end
  5766. ** of the string. ^For clarity: the values returned by
  5767. ** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of
  5768. ** bytes in the string, not the number of characters.
  5769. **
  5770. ** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
  5771. ** even empty strings, are always zero-terminated. ^The return
  5772. ** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer.
  5773. **
  5774. ** <b>Warning:</b> ^The object returned by [sqlite3_column_value()] is an
  5775. ** [unprotected sqlite3_value] object. In a multithreaded environment,
  5776. ** an unprotected sqlite3_value object may only be used safely with
  5777. ** [sqlite3_bind_value()] and [sqlite3_result_value()].
  5778. ** If the [unprotected sqlite3_value] object returned by
  5779. ** [sqlite3_column_value()] is used in any other way, including calls
  5780. ** to routines like [sqlite3_value_int()], [sqlite3_value_text()],
  5781. ** or [sqlite3_value_bytes()], the behavior is not threadsafe.
  5782. ** Hence, the sqlite3_column_value() interface
  5783. ** is normally only useful within the implementation of
  5784. ** [application-defined SQL functions] or [virtual tables], not within
  5785. ** top-level application code.
  5786. **
  5787. ** The these routines may attempt to convert the datatype of the result.
  5788. ** ^For example, if the internal representation is FLOAT and a text result
  5789. ** is requested, [sqlite3_snprintf()] is used internally to perform the
  5790. ** conversion automatically. ^(The following table details the conversions
  5791. ** that are applied:
  5792. **
  5793. ** <blockquote>
  5794. ** <table border="1">
  5795. ** <tr><th> Internal<br>Type <th> Requested<br>Type <th> Conversion
  5796. **
  5797. ** <tr><td> NULL <td> INTEGER <td> Result is 0
  5798. ** <tr><td> NULL <td> FLOAT <td> Result is 0.0
  5799. ** <tr><td> NULL <td> TEXT <td> Result is a NULL pointer
  5800. ** <tr><td> NULL <td> BLOB <td> Result is a NULL pointer
  5801. ** <tr><td> INTEGER <td> FLOAT <td> Convert from integer to float
  5802. ** <tr><td> INTEGER <td> TEXT <td> ASCII rendering of the integer
  5803. ** <tr><td> INTEGER <td> BLOB <td> Same as INTEGER->TEXT
  5804. ** <tr><td> FLOAT <td> INTEGER <td> [CAST] to INTEGER
  5805. ** <tr><td> FLOAT <td> TEXT <td> ASCII rendering of the float
  5806. ** <tr><td> FLOAT <td> BLOB <td> [CAST] to BLOB
  5807. ** <tr><td> TEXT <td> INTEGER <td> [CAST] to INTEGER
  5808. ** <tr><td> TEXT <td> FLOAT <td> [CAST] to REAL
  5809. ** <tr><td> TEXT <td> BLOB <td> No change
  5810. ** <tr><td> BLOB <td> INTEGER <td> [CAST] to INTEGER
  5811. ** <tr><td> BLOB <td> FLOAT <td> [CAST] to REAL
  5812. ** <tr><td> BLOB <td> TEXT <td> Add a zero terminator if needed
  5813. ** </table>
  5814. ** </blockquote>)^
  5815. **
  5816. ** Note that when type conversions occur, pointers returned by prior
  5817. ** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
  5818. ** sqlite3_column_text16() may be invalidated.
  5819. ** Type conversions and pointer invalidations might occur
  5820. ** in the following cases:
  5821. **
  5822. ** <ul>
  5823. ** <li> The initial content is a BLOB and sqlite3_column_text() or
  5824. ** sqlite3_column_text16() is called. A zero-terminator might
  5825. ** need to be added to the string.</li>
  5826. ** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or
  5827. ** sqlite3_column_text16() is called. The content must be converted
  5828. ** to UTF-16.</li>
  5829. ** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
  5830. ** sqlite3_column_text() is called. The content must be converted
  5831. ** to UTF-8.</li>
  5832. ** </ul>
  5833. **
  5834. ** ^Conversions between UTF-16be and UTF-16le are always done in place and do
  5835. ** not invalidate a prior pointer, though of course the content of the buffer
  5836. ** that the prior pointer references will have been modified. Other kinds
  5837. ** of conversion are done in place when it is possible, but sometimes they
  5838. ** are not possible and in those cases prior pointers are invalidated.
  5839. **
  5840. ** The safest policy is to invoke these routines
  5841. ** in one of the following ways:
  5842. **
  5843. ** <ul>
  5844. ** <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
  5845. ** <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
  5846. ** <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
  5847. ** </ul>
  5848. **
  5849. ** In other words, you should call sqlite3_column_text(),
  5850. ** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
  5851. ** into the desired format, then invoke sqlite3_column_bytes() or
  5852. ** sqlite3_column_bytes16() to find the size of the result. Do not mix calls
  5853. ** to sqlite3_column_text() or sqlite3_column_blob() with calls to
  5854. ** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()
  5855. ** with calls to sqlite3_column_bytes().
  5856. **
  5857. ** ^The pointers returned are valid until a type conversion occurs as
  5858. ** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
  5859. ** [sqlite3_finalize()] is called. ^The memory space used to hold strings
  5860. ** and BLOBs is freed automatically. Do not pass the pointers returned
  5861. ** from [sqlite3_column_blob()], [sqlite3_column_text()], etc. into
  5862. ** [sqlite3_free()].
  5863. **
  5864. ** As long as the input parameters are correct, these routines will only
  5865. ** fail if an out-of-memory error occurs during a format conversion.
  5866. ** Only the following subset of interfaces are subject to out-of-memory
  5867. ** errors:
  5868. **
  5869. ** <ul>
  5870. ** <li> sqlite3_column_blob()
  5871. ** <li> sqlite3_column_text()
  5872. ** <li> sqlite3_column_text16()
  5873. ** <li> sqlite3_column_bytes()
  5874. ** <li> sqlite3_column_bytes16()
  5875. ** </ul>
  5876. **
  5877. ** If an out-of-memory error occurs, then the return value from these
  5878. ** routines is the same as if the column had contained an SQL NULL value.
  5879. ** Valid SQL NULL returns can be distinguished from out-of-memory errors
  5880. ** by invoking the [sqlite3_errcode()] immediately after the suspect
  5881. ** return value is obtained and before any
  5882. ** other SQLite interface is called on the same [database connection].
  5883. */
  5884. SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
  5885. SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol);
  5886. SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol);
  5887. SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
  5888. SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
  5889. SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);
  5890. SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);
  5891. SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
  5892. SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
  5893. SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol);
  5894. /*
  5895. ** CAPI3REF: Destroy A Prepared Statement Object
  5896. ** DESTRUCTOR: sqlite3_stmt
  5897. **
  5898. ** ^The sqlite3_finalize() function is called to delete a [prepared statement].
  5899. ** ^If the most recent evaluation of the statement encountered no errors
  5900. ** or if the statement is never been evaluated, then sqlite3_finalize() returns
  5901. ** SQLITE_OK. ^If the most recent evaluation of statement S failed, then
  5902. ** sqlite3_finalize(S) returns the appropriate [error code] or
  5903. ** [extended error code].
  5904. **
  5905. ** ^The sqlite3_finalize(S) routine can be called at any point during
  5906. ** the life cycle of [prepared statement] S:
  5907. ** before statement S is ever evaluated, after
  5908. ** one or more calls to [sqlite3_reset()], or after any call
  5909. ** to [sqlite3_step()] regardless of whether or not the statement has
  5910. ** completed execution.
  5911. **
  5912. ** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op.
  5913. **
  5914. ** The application must finalize every [prepared statement] in order to avoid
  5915. ** resource leaks. It is a grievous error for the application to try to use
  5916. ** a prepared statement after it has been finalized. Any use of a prepared
  5917. ** statement after it has been finalized can result in undefined and
  5918. ** undesirable behavior such as segfaults and heap corruption.
  5919. */
  5920. SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt);
  5921. /*
  5922. ** CAPI3REF: Reset A Prepared Statement Object
  5923. ** METHOD: sqlite3_stmt
  5924. **
  5925. ** The sqlite3_reset() function is called to reset a [prepared statement]
  5926. ** object back to its initial state, ready to be re-executed.
  5927. ** ^Any SQL statement variables that had values bound to them using
  5928. ** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
  5929. ** Use [sqlite3_clear_bindings()] to reset the bindings.
  5930. **
  5931. ** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S
  5932. ** back to the beginning of its program.
  5933. **
  5934. ** ^If the most recent call to [sqlite3_step(S)] for the
  5935. ** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE],
  5936. ** or if [sqlite3_step(S)] has never before been called on S,
  5937. ** then [sqlite3_reset(S)] returns [SQLITE_OK].
  5938. **
  5939. ** ^If the most recent call to [sqlite3_step(S)] for the
  5940. ** [prepared statement] S indicated an error, then
  5941. ** [sqlite3_reset(S)] returns an appropriate [error code].
  5942. **
  5943. ** ^The [sqlite3_reset(S)] interface does not change the values
  5944. ** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.
  5945. */
  5946. SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
  5947. /*
  5948. ** CAPI3REF: Create Or Redefine SQL Functions
  5949. ** KEYWORDS: {function creation routines}
  5950. ** METHOD: sqlite3
  5951. **
  5952. ** ^These functions (collectively known as "function creation routines")
  5953. ** are used to add SQL functions or aggregates or to redefine the behavior
  5954. ** of existing SQL functions or aggregates. The only differences between
  5955. ** the three "sqlite3_create_function*" routines are the text encoding
  5956. ** expected for the second parameter (the name of the function being
  5957. ** created) and the presence or absence of a destructor callback for
  5958. ** the application data pointer. Function sqlite3_create_window_function()
  5959. ** is similar, but allows the user to supply the extra callback functions
  5960. ** needed by [aggregate window functions].
  5961. **
  5962. ** ^The first parameter is the [database connection] to which the SQL
  5963. ** function is to be added. ^If an application uses more than one database
  5964. ** connection then application-defined SQL functions must be added
  5965. ** to each database connection separately.
  5966. **
  5967. ** ^The second parameter is the name of the SQL function to be created or
  5968. ** redefined. ^The length of the name is limited to 255 bytes in a UTF-8
  5969. ** representation, exclusive of the zero-terminator. ^Note that the name
  5970. ** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes.
  5971. ** ^Any attempt to create a function with a longer name
  5972. ** will result in [SQLITE_MISUSE] being returned.
  5973. **
  5974. ** ^The third parameter (nArg)
  5975. ** is the number of arguments that the SQL function or
  5976. ** aggregate takes. ^If this parameter is -1, then the SQL function or
  5977. ** aggregate may take any number of arguments between 0 and the limit
  5978. ** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]). If the third
  5979. ** parameter is less than -1 or greater than 127 then the behavior is
  5980. ** undefined.
  5981. **
  5982. ** ^The fourth parameter, eTextRep, specifies what
  5983. ** [SQLITE_UTF8 | text encoding] this SQL function prefers for
  5984. ** its parameters. The application should set this parameter to
  5985. ** [SQLITE_UTF16LE] if the function implementation invokes
  5986. ** [sqlite3_value_text16le()] on an input, or [SQLITE_UTF16BE] if the
  5987. ** implementation invokes [sqlite3_value_text16be()] on an input, or
  5988. ** [SQLITE_UTF16] if [sqlite3_value_text16()] is used, or [SQLITE_UTF8]
  5989. ** otherwise. ^The same SQL function may be registered multiple times using
  5990. ** different preferred text encodings, with different implementations for
  5991. ** each encoding.
  5992. ** ^When multiple implementations of the same function are available, SQLite
  5993. ** will pick the one that involves the least amount of data conversion.
  5994. **
  5995. ** ^The fourth parameter may optionally be ORed with [SQLITE_DETERMINISTIC]
  5996. ** to signal that the function will always return the same result given
  5997. ** the same inputs within a single SQL statement. Most SQL functions are
  5998. ** deterministic. The built-in [random()] SQL function is an example of a
  5999. ** function that is not deterministic. The SQLite query planner is able to
  6000. ** perform additional optimizations on deterministic functions, so use
  6001. ** of the [SQLITE_DETERMINISTIC] flag is recommended where possible.
  6002. **
  6003. ** ^The fourth parameter may also optionally include the [SQLITE_DIRECTONLY]
  6004. ** flag, which if present prevents the function from being invoked from
  6005. ** within VIEWs, TRIGGERs, CHECK constraints, generated column expressions,
  6006. ** index expressions, or the WHERE clause of partial indexes.
  6007. **
  6008. ** <span style="background-color:#ffff90;">
  6009. ** For best security, the [SQLITE_DIRECTONLY] flag is recommended for
  6010. ** all application-defined SQL functions that do not need to be
  6011. ** used inside of triggers, view, CHECK constraints, or other elements of
  6012. ** the database schema. This flags is especially recommended for SQL
  6013. ** functions that have side effects or reveal internal application state.
  6014. ** Without this flag, an attacker might be able to modify the schema of
  6015. ** a database file to include invocations of the function with parameters
  6016. ** chosen by the attacker, which the application will then execute when
  6017. ** the database file is opened and read.
  6018. ** </span>
  6019. **
  6020. ** ^(The fifth parameter is an arbitrary pointer. The implementation of the
  6021. ** function can gain access to this pointer using [sqlite3_user_data()].)^
  6022. **
  6023. ** ^The sixth, seventh and eighth parameters passed to the three
  6024. ** "sqlite3_create_function*" functions, xFunc, xStep and xFinal, are
  6025. ** pointers to C-language functions that implement the SQL function or
  6026. ** aggregate. ^A scalar SQL function requires an implementation of the xFunc
  6027. ** callback only; NULL pointers must be passed as the xStep and xFinal
  6028. ** parameters. ^An aggregate SQL function requires an implementation of xStep
  6029. ** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing
  6030. ** SQL function or aggregate, pass NULL pointers for all three function
  6031. ** callbacks.
  6032. **
  6033. ** ^The sixth, seventh, eighth and ninth parameters (xStep, xFinal, xValue
  6034. ** and xInverse) passed to sqlite3_create_window_function are pointers to
  6035. ** C-language callbacks that implement the new function. xStep and xFinal
  6036. ** must both be non-NULL. xValue and xInverse may either both be NULL, in
  6037. ** which case a regular aggregate function is created, or must both be
  6038. ** non-NULL, in which case the new function may be used as either an aggregate
  6039. ** or aggregate window function. More details regarding the implementation
  6040. ** of aggregate window functions are
  6041. ** [user-defined window functions|available here].
  6042. **
  6043. ** ^(If the final parameter to sqlite3_create_function_v2() or
  6044. ** sqlite3_create_window_function() is not NULL, then it is destructor for
  6045. ** the application data pointer. The destructor is invoked when the function
  6046. ** is deleted, either by being overloaded or when the database connection
  6047. ** closes.)^ ^The destructor is also invoked if the call to
  6048. ** sqlite3_create_function_v2() fails. ^When the destructor callback is
  6049. ** invoked, it is passed a single argument which is a copy of the application
  6050. ** data pointer which was the fifth parameter to sqlite3_create_function_v2().
  6051. **
  6052. ** ^It is permitted to register multiple implementations of the same
  6053. ** functions with the same name but with either differing numbers of
  6054. ** arguments or differing preferred text encodings. ^SQLite will use
  6055. ** the implementation that most closely matches the way in which the
  6056. ** SQL function is used. ^A function implementation with a non-negative
  6057. ** nArg parameter is a better match than a function implementation with
  6058. ** a negative nArg. ^A function where the preferred text encoding
  6059. ** matches the database encoding is a better
  6060. ** match than a function where the encoding is different.
  6061. ** ^A function where the encoding difference is between UTF16le and UTF16be
  6062. ** is a closer match than a function where the encoding difference is
  6063. ** between UTF8 and UTF16.
  6064. **
  6065. ** ^Built-in functions may be overloaded by new application-defined functions.
  6066. **
  6067. ** ^An application-defined function is permitted to call other
  6068. ** SQLite interfaces. However, such calls must not
  6069. ** close the database connection nor finalize or reset the prepared
  6070. ** statement in which the function is running.
  6071. */
  6072. SQLITE_API int sqlite3_create_function(
  6073. sqlite3 *db,
  6074. const char *zFunctionName,
  6075. int nArg,
  6076. int eTextRep,
  6077. void *pApp,
  6078. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  6079. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  6080. void (*xFinal)(sqlite3_context*)
  6081. );
  6082. SQLITE_API int sqlite3_create_function16(
  6083. sqlite3 *db,
  6084. const void *zFunctionName,
  6085. int nArg,
  6086. int eTextRep,
  6087. void *pApp,
  6088. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  6089. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  6090. void (*xFinal)(sqlite3_context*)
  6091. );
  6092. SQLITE_API int sqlite3_create_function_v2(
  6093. sqlite3 *db,
  6094. const char *zFunctionName,
  6095. int nArg,
  6096. int eTextRep,
  6097. void *pApp,
  6098. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  6099. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  6100. void (*xFinal)(sqlite3_context*),
  6101. void(*xDestroy)(void*)
  6102. );
  6103. SQLITE_API int sqlite3_create_window_function(
  6104. sqlite3 *db,
  6105. const char *zFunctionName,
  6106. int nArg,
  6107. int eTextRep,
  6108. void *pApp,
  6109. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  6110. void (*xFinal)(sqlite3_context*),
  6111. void (*xValue)(sqlite3_context*),
  6112. void (*xInverse)(sqlite3_context*,int,sqlite3_value**),
  6113. void(*xDestroy)(void*)
  6114. );
  6115. /*
  6116. ** CAPI3REF: Text Encodings
  6117. **
  6118. ** These constant define integer codes that represent the various
  6119. ** text encodings supported by SQLite.
  6120. */
  6121. #define SQLITE_UTF8 1 /* IMP: R-37514-35566 */
  6122. #define SQLITE_UTF16LE 2 /* IMP: R-03371-37637 */
  6123. #define SQLITE_UTF16BE 3 /* IMP: R-51971-34154 */
  6124. #define SQLITE_UTF16 4 /* Use native byte order */
  6125. #define SQLITE_ANY 5 /* Deprecated */
  6126. #define SQLITE_UTF16_ALIGNED 8 /* sqlite3_create_collation only */
  6127. /*
  6128. ** CAPI3REF: Function Flags
  6129. **
  6130. ** These constants may be ORed together with the
  6131. ** [SQLITE_UTF8 | preferred text encoding] as the fourth argument
  6132. ** to [sqlite3_create_function()], [sqlite3_create_function16()], or
  6133. ** [sqlite3_create_function_v2()].
  6134. **
  6135. ** <dl>
  6136. ** [[SQLITE_DETERMINISTIC]] <dt>SQLITE_DETERMINISTIC</dt><dd>
  6137. ** The SQLITE_DETERMINISTIC flag means that the new function always gives
  6138. ** the same output when the input parameters are the same.
  6139. ** The [abs|abs() function] is deterministic, for example, but
  6140. ** [randomblob|randomblob()] is not. Functions must
  6141. ** be deterministic in order to be used in certain contexts such as
  6142. ** with the WHERE clause of [partial indexes] or in [generated columns].
  6143. ** SQLite might also optimize deterministic functions by factoring them
  6144. ** out of inner loops.
  6145. ** </dd>
  6146. **
  6147. ** [[SQLITE_DIRECTONLY]] <dt>SQLITE_DIRECTONLY</dt><dd>
  6148. ** The SQLITE_DIRECTONLY flag means that the function may only be invoked
  6149. ** from top-level SQL, and cannot be used in VIEWs or TRIGGERs nor in
  6150. ** schema structures such as [CHECK constraints], [DEFAULT clauses],
  6151. ** [expression indexes], [partial indexes], or [generated columns].
  6152. ** The SQLITE_DIRECTONLY flags is a security feature which is recommended
  6153. ** for all [application-defined SQL functions], and especially for functions
  6154. ** that have side-effects or that could potentially leak sensitive
  6155. ** information.
  6156. ** </dd>
  6157. **
  6158. ** [[SQLITE_INNOCUOUS]] <dt>SQLITE_INNOCUOUS</dt><dd>
  6159. ** The SQLITE_INNOCUOUS flag means that the function is unlikely
  6160. ** to cause problems even if misused. An innocuous function should have
  6161. ** no side effects and should not depend on any values other than its
  6162. ** input parameters. The [abs|abs() function] is an example of an
  6163. ** innocuous function.
  6164. ** The [load_extension() SQL function] is not innocuous because of its
  6165. ** side effects.
  6166. ** <p> SQLITE_INNOCUOUS is similar to SQLITE_DETERMINISTIC, but is not
  6167. ** exactly the same. The [random|random() function] is an example of a
  6168. ** function that is innocuous but not deterministic.
  6169. ** <p>Some heightened security settings
  6170. ** ([SQLITE_DBCONFIG_TRUSTED_SCHEMA] and [PRAGMA trusted_schema=OFF])
  6171. ** disable the use of SQL functions inside views and triggers and in
  6172. ** schema structures such as [CHECK constraints], [DEFAULT clauses],
  6173. ** [expression indexes], [partial indexes], and [generated columns] unless
  6174. ** the function is tagged with SQLITE_INNOCUOUS. Most built-in functions
  6175. ** are innocuous. Developers are advised to avoid using the
  6176. ** SQLITE_INNOCUOUS flag for application-defined functions unless the
  6177. ** function has been carefully audited and found to be free of potentially
  6178. ** security-adverse side-effects and information-leaks.
  6179. ** </dd>
  6180. **
  6181. ** [[SQLITE_SUBTYPE]] <dt>SQLITE_SUBTYPE</dt><dd>
  6182. ** The SQLITE_SUBTYPE flag indicates to SQLite that a function may call
  6183. ** [sqlite3_value_subtype()] to inspect the sub-types of its arguments.
  6184. ** Specifying this flag makes no difference for scalar or aggregate user
  6185. ** functions. However, if it is not specified for a user-defined window
  6186. ** function, then any sub-types belonging to arguments passed to the window
  6187. ** function may be discarded before the window function is called (i.e.
  6188. ** sqlite3_value_subtype() will always return 0).
  6189. ** </dd>
  6190. ** </dl>
  6191. */
  6192. #define SQLITE_DETERMINISTIC 0x000000800
  6193. #define SQLITE_DIRECTONLY 0x000080000
  6194. #define SQLITE_SUBTYPE 0x000100000
  6195. #define SQLITE_INNOCUOUS 0x000200000
  6196. /*
  6197. ** CAPI3REF: Deprecated Functions
  6198. ** DEPRECATED
  6199. **
  6200. ** These functions are [deprecated]. In order to maintain
  6201. ** backwards compatibility with older code, these functions continue
  6202. ** to be supported. However, new applications should avoid
  6203. ** the use of these functions. To encourage programmers to avoid
  6204. ** these functions, we will not explain what they do.
  6205. */
  6206. #ifndef SQLITE_OMIT_DEPRECATED
  6207. SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*);
  6208. SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*);
  6209. SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
  6210. SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void);
  6211. SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void);
  6212. SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),
  6213. void*,sqlite3_int64);
  6214. #endif
  6215. /*
  6216. ** CAPI3REF: Obtaining SQL Values
  6217. ** METHOD: sqlite3_value
  6218. **
  6219. ** <b>Summary:</b>
  6220. ** <blockquote><table border=0 cellpadding=0 cellspacing=0>
  6221. ** <tr><td><b>sqlite3_value_blob</b><td>&rarr;<td>BLOB value
  6222. ** <tr><td><b>sqlite3_value_double</b><td>&rarr;<td>REAL value
  6223. ** <tr><td><b>sqlite3_value_int</b><td>&rarr;<td>32-bit INTEGER value
  6224. ** <tr><td><b>sqlite3_value_int64</b><td>&rarr;<td>64-bit INTEGER value
  6225. ** <tr><td><b>sqlite3_value_pointer</b><td>&rarr;<td>Pointer value
  6226. ** <tr><td><b>sqlite3_value_text</b><td>&rarr;<td>UTF-8 TEXT value
  6227. ** <tr><td><b>sqlite3_value_text16</b><td>&rarr;<td>UTF-16 TEXT value in
  6228. ** the native byteorder
  6229. ** <tr><td><b>sqlite3_value_text16be</b><td>&rarr;<td>UTF-16be TEXT value
  6230. ** <tr><td><b>sqlite3_value_text16le</b><td>&rarr;<td>UTF-16le TEXT value
  6231. ** <tr><td>&nbsp;<td>&nbsp;<td>&nbsp;
  6232. ** <tr><td><b>sqlite3_value_bytes</b><td>&rarr;<td>Size of a BLOB
  6233. ** or a UTF-8 TEXT in bytes
  6234. ** <tr><td><b>sqlite3_value_bytes16&nbsp;&nbsp;</b>
  6235. ** <td>&rarr;&nbsp;&nbsp;<td>Size of UTF-16
  6236. ** TEXT in bytes
  6237. ** <tr><td><b>sqlite3_value_type</b><td>&rarr;<td>Default
  6238. ** datatype of the value
  6239. ** <tr><td><b>sqlite3_value_numeric_type&nbsp;&nbsp;</b>
  6240. ** <td>&rarr;&nbsp;&nbsp;<td>Best numeric datatype of the value
  6241. ** <tr><td><b>sqlite3_value_nochange&nbsp;&nbsp;</b>
  6242. ** <td>&rarr;&nbsp;&nbsp;<td>True if the column is unchanged in an UPDATE
  6243. ** against a virtual table.
  6244. ** <tr><td><b>sqlite3_value_frombind&nbsp;&nbsp;</b>
  6245. ** <td>&rarr;&nbsp;&nbsp;<td>True if value originated from a [bound parameter]
  6246. ** </table></blockquote>
  6247. **
  6248. ** <b>Details:</b>
  6249. **
  6250. ** These routines extract type, size, and content information from
  6251. ** [protected sqlite3_value] objects. Protected sqlite3_value objects
  6252. ** are used to pass parameter information into the functions that
  6253. ** implement [application-defined SQL functions] and [virtual tables].
  6254. **
  6255. ** These routines work only with [protected sqlite3_value] objects.
  6256. ** Any attempt to use these routines on an [unprotected sqlite3_value]
  6257. ** is not threadsafe.
  6258. **
  6259. ** ^These routines work just like the corresponding [column access functions]
  6260. ** except that these routines take a single [protected sqlite3_value] object
  6261. ** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.
  6262. **
  6263. ** ^The sqlite3_value_text16() interface extracts a UTF-16 string
  6264. ** in the native byte-order of the host machine. ^The
  6265. ** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
  6266. ** extract UTF-16 strings as big-endian and little-endian respectively.
  6267. **
  6268. ** ^If [sqlite3_value] object V was initialized
  6269. ** using [sqlite3_bind_pointer(S,I,P,X,D)] or [sqlite3_result_pointer(C,P,X,D)]
  6270. ** and if X and Y are strings that compare equal according to strcmp(X,Y),
  6271. ** then sqlite3_value_pointer(V,Y) will return the pointer P. ^Otherwise,
  6272. ** sqlite3_value_pointer(V,Y) returns a NULL. The sqlite3_bind_pointer()
  6273. ** routine is part of the [pointer passing interface] added for SQLite 3.20.0.
  6274. **
  6275. ** ^(The sqlite3_value_type(V) interface returns the
  6276. ** [SQLITE_INTEGER | datatype code] for the initial datatype of the
  6277. ** [sqlite3_value] object V. The returned value is one of [SQLITE_INTEGER],
  6278. ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].)^
  6279. ** Other interfaces might change the datatype for an sqlite3_value object.
  6280. ** For example, if the datatype is initially SQLITE_INTEGER and
  6281. ** sqlite3_value_text(V) is called to extract a text value for that
  6282. ** integer, then subsequent calls to sqlite3_value_type(V) might return
  6283. ** SQLITE_TEXT. Whether or not a persistent internal datatype conversion
  6284. ** occurs is undefined and may change from one release of SQLite to the next.
  6285. **
  6286. ** ^(The sqlite3_value_numeric_type() interface attempts to apply
  6287. ** numeric affinity to the value. This means that an attempt is
  6288. ** made to convert the value to an integer or floating point. If
  6289. ** such a conversion is possible without loss of information (in other
  6290. ** words, if the value is a string that looks like a number)
  6291. ** then the conversion is performed. Otherwise no conversion occurs.
  6292. ** The [SQLITE_INTEGER | datatype] after conversion is returned.)^
  6293. **
  6294. ** ^Within the [xUpdate] method of a [virtual table], the
  6295. ** sqlite3_value_nochange(X) interface returns true if and only if
  6296. ** the column corresponding to X is unchanged by the UPDATE operation
  6297. ** that the xUpdate method call was invoked to implement and if
  6298. ** and the prior [xColumn] method call that was invoked to extracted
  6299. ** the value for that column returned without setting a result (probably
  6300. ** because it queried [sqlite3_vtab_nochange()] and found that the column
  6301. ** was unchanging). ^Within an [xUpdate] method, any value for which
  6302. ** sqlite3_value_nochange(X) is true will in all other respects appear
  6303. ** to be a NULL value. If sqlite3_value_nochange(X) is invoked anywhere other
  6304. ** than within an [xUpdate] method call for an UPDATE statement, then
  6305. ** the return value is arbitrary and meaningless.
  6306. **
  6307. ** ^The sqlite3_value_frombind(X) interface returns non-zero if the
  6308. ** value X originated from one of the [sqlite3_bind_int|sqlite3_bind()]
  6309. ** interfaces. ^If X comes from an SQL literal value, or a table column,
  6310. ** or an expression, then sqlite3_value_frombind(X) returns zero.
  6311. **
  6312. ** Please pay particular attention to the fact that the pointer returned
  6313. ** from [sqlite3_value_blob()], [sqlite3_value_text()], or
  6314. ** [sqlite3_value_text16()] can be invalidated by a subsequent call to
  6315. ** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
  6316. ** or [sqlite3_value_text16()].
  6317. **
  6318. ** These routines must be called from the same thread as
  6319. ** the SQL function that supplied the [sqlite3_value*] parameters.
  6320. **
  6321. ** As long as the input parameter is correct, these routines can only
  6322. ** fail if an out-of-memory error occurs during a format conversion.
  6323. ** Only the following subset of interfaces are subject to out-of-memory
  6324. ** errors:
  6325. **
  6326. ** <ul>
  6327. ** <li> sqlite3_value_blob()
  6328. ** <li> sqlite3_value_text()
  6329. ** <li> sqlite3_value_text16()
  6330. ** <li> sqlite3_value_text16le()
  6331. ** <li> sqlite3_value_text16be()
  6332. ** <li> sqlite3_value_bytes()
  6333. ** <li> sqlite3_value_bytes16()
  6334. ** </ul>
  6335. **
  6336. ** If an out-of-memory error occurs, then the return value from these
  6337. ** routines is the same as if the column had contained an SQL NULL value.
  6338. ** Valid SQL NULL returns can be distinguished from out-of-memory errors
  6339. ** by invoking the [sqlite3_errcode()] immediately after the suspect
  6340. ** return value is obtained and before any
  6341. ** other SQLite interface is called on the same [database connection].
  6342. */
  6343. SQLITE_API const void *sqlite3_value_blob(sqlite3_value*);
  6344. SQLITE_API double sqlite3_value_double(sqlite3_value*);
  6345. SQLITE_API int sqlite3_value_int(sqlite3_value*);
  6346. SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*);
  6347. SQLITE_API void *sqlite3_value_pointer(sqlite3_value*, const char*);
  6348. SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*);
  6349. SQLITE_API const void *sqlite3_value_text16(sqlite3_value*);
  6350. SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*);
  6351. SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*);
  6352. SQLITE_API int sqlite3_value_bytes(sqlite3_value*);
  6353. SQLITE_API int sqlite3_value_bytes16(sqlite3_value*);
  6354. SQLITE_API int sqlite3_value_type(sqlite3_value*);
  6355. SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*);
  6356. SQLITE_API int sqlite3_value_nochange(sqlite3_value*);
  6357. SQLITE_API int sqlite3_value_frombind(sqlite3_value*);
  6358. /*
  6359. ** CAPI3REF: Finding The Subtype Of SQL Values
  6360. ** METHOD: sqlite3_value
  6361. **
  6362. ** The sqlite3_value_subtype(V) function returns the subtype for
  6363. ** an [application-defined SQL function] argument V. The subtype
  6364. ** information can be used to pass a limited amount of context from
  6365. ** one SQL function to another. Use the [sqlite3_result_subtype()]
  6366. ** routine to set the subtype for the return value of an SQL function.
  6367. */
  6368. SQLITE_API unsigned int sqlite3_value_subtype(sqlite3_value*);
  6369. /*
  6370. ** CAPI3REF: Copy And Free SQL Values
  6371. ** METHOD: sqlite3_value
  6372. **
  6373. ** ^The sqlite3_value_dup(V) interface makes a copy of the [sqlite3_value]
  6374. ** object D and returns a pointer to that copy. ^The [sqlite3_value] returned
  6375. ** is a [protected sqlite3_value] object even if the input is not.
  6376. ** ^The sqlite3_value_dup(V) interface returns NULL if V is NULL or if a
  6377. ** memory allocation fails.
  6378. **
  6379. ** ^The sqlite3_value_free(V) interface frees an [sqlite3_value] object
  6380. ** previously obtained from [sqlite3_value_dup()]. ^If V is a NULL pointer
  6381. ** then sqlite3_value_free(V) is a harmless no-op.
  6382. */
  6383. SQLITE_API sqlite3_value *sqlite3_value_dup(const sqlite3_value*);
  6384. SQLITE_API void sqlite3_value_free(sqlite3_value*);
  6385. /*
  6386. ** CAPI3REF: Obtain Aggregate Function Context
  6387. ** METHOD: sqlite3_context
  6388. **
  6389. ** Implementations of aggregate SQL functions use this
  6390. ** routine to allocate memory for storing their state.
  6391. **
  6392. ** ^The first time the sqlite3_aggregate_context(C,N) routine is called
  6393. ** for a particular aggregate function, SQLite allocates
  6394. ** N bytes of memory, zeroes out that memory, and returns a pointer
  6395. ** to the new memory. ^On second and subsequent calls to
  6396. ** sqlite3_aggregate_context() for the same aggregate function instance,
  6397. ** the same buffer is returned. Sqlite3_aggregate_context() is normally
  6398. ** called once for each invocation of the xStep callback and then one
  6399. ** last time when the xFinal callback is invoked. ^(When no rows match
  6400. ** an aggregate query, the xStep() callback of the aggregate function
  6401. ** implementation is never called and xFinal() is called exactly once.
  6402. ** In those cases, sqlite3_aggregate_context() might be called for the
  6403. ** first time from within xFinal().)^
  6404. **
  6405. ** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer
  6406. ** when first called if N is less than or equal to zero or if a memory
  6407. ** allocate error occurs.
  6408. **
  6409. ** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is
  6410. ** determined by the N parameter on first successful call. Changing the
  6411. ** value of N in any subsequent call to sqlite3_aggregate_context() within
  6412. ** the same aggregate function instance will not resize the memory
  6413. ** allocation.)^ Within the xFinal callback, it is customary to set
  6414. ** N=0 in calls to sqlite3_aggregate_context(C,N) so that no
  6415. ** pointless memory allocations occur.
  6416. **
  6417. ** ^SQLite automatically frees the memory allocated by
  6418. ** sqlite3_aggregate_context() when the aggregate query concludes.
  6419. **
  6420. ** The first parameter must be a copy of the
  6421. ** [sqlite3_context | SQL function context] that is the first parameter
  6422. ** to the xStep or xFinal callback routine that implements the aggregate
  6423. ** function.
  6424. **
  6425. ** This routine must be called from the same thread in which
  6426. ** the aggregate SQL function is running.
  6427. */
  6428. SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);
  6429. /*
  6430. ** CAPI3REF: User Data For Functions
  6431. ** METHOD: sqlite3_context
  6432. **
  6433. ** ^The sqlite3_user_data() interface returns a copy of
  6434. ** the pointer that was the pUserData parameter (the 5th parameter)
  6435. ** of the [sqlite3_create_function()]
  6436. ** and [sqlite3_create_function16()] routines that originally
  6437. ** registered the application defined function.
  6438. **
  6439. ** This routine must be called from the same thread in which
  6440. ** the application-defined function is running.
  6441. */
  6442. SQLITE_API void *sqlite3_user_data(sqlite3_context*);
  6443. /*
  6444. ** CAPI3REF: Database Connection For Functions
  6445. ** METHOD: sqlite3_context
  6446. **
  6447. ** ^The sqlite3_context_db_handle() interface returns a copy of
  6448. ** the pointer to the [database connection] (the 1st parameter)
  6449. ** of the [sqlite3_create_function()]
  6450. ** and [sqlite3_create_function16()] routines that originally
  6451. ** registered the application defined function.
  6452. */
  6453. SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*);
  6454. /*
  6455. ** CAPI3REF: Function Auxiliary Data
  6456. ** METHOD: sqlite3_context
  6457. **
  6458. ** These functions may be used by (non-aggregate) SQL functions to
  6459. ** associate metadata with argument values. If the same value is passed to
  6460. ** multiple invocations of the same SQL function during query execution, under
  6461. ** some circumstances the associated metadata may be preserved. An example
  6462. ** of where this might be useful is in a regular-expression matching
  6463. ** function. The compiled version of the regular expression can be stored as
  6464. ** metadata associated with the pattern string.
  6465. ** Then as long as the pattern string remains the same,
  6466. ** the compiled regular expression can be reused on multiple
  6467. ** invocations of the same function.
  6468. **
  6469. ** ^The sqlite3_get_auxdata(C,N) interface returns a pointer to the metadata
  6470. ** associated by the sqlite3_set_auxdata(C,N,P,X) function with the Nth argument
  6471. ** value to the application-defined function. ^N is zero for the left-most
  6472. ** function argument. ^If there is no metadata
  6473. ** associated with the function argument, the sqlite3_get_auxdata(C,N) interface
  6474. ** returns a NULL pointer.
  6475. **
  6476. ** ^The sqlite3_set_auxdata(C,N,P,X) interface saves P as metadata for the N-th
  6477. ** argument of the application-defined function. ^Subsequent
  6478. ** calls to sqlite3_get_auxdata(C,N) return P from the most recent
  6479. ** sqlite3_set_auxdata(C,N,P,X) call if the metadata is still valid or
  6480. ** NULL if the metadata has been discarded.
  6481. ** ^After each call to sqlite3_set_auxdata(C,N,P,X) where X is not NULL,
  6482. ** SQLite will invoke the destructor function X with parameter P exactly
  6483. ** once, when the metadata is discarded.
  6484. ** SQLite is free to discard the metadata at any time, including: <ul>
  6485. ** <li> ^(when the corresponding function parameter changes)^, or
  6486. ** <li> ^(when [sqlite3_reset()] or [sqlite3_finalize()] is called for the
  6487. ** SQL statement)^, or
  6488. ** <li> ^(when sqlite3_set_auxdata() is invoked again on the same
  6489. ** parameter)^, or
  6490. ** <li> ^(during the original sqlite3_set_auxdata() call when a memory
  6491. ** allocation error occurs.)^ </ul>
  6492. **
  6493. ** Note the last bullet in particular. The destructor X in
  6494. ** sqlite3_set_auxdata(C,N,P,X) might be called immediately, before the
  6495. ** sqlite3_set_auxdata() interface even returns. Hence sqlite3_set_auxdata()
  6496. ** should be called near the end of the function implementation and the
  6497. ** function implementation should not make any use of P after
  6498. ** sqlite3_set_auxdata() has been called.
  6499. **
  6500. ** ^(In practice, metadata is preserved between function calls for
  6501. ** function parameters that are compile-time constants, including literal
  6502. ** values and [parameters] and expressions composed from the same.)^
  6503. **
  6504. ** The value of the N parameter to these interfaces should be non-negative.
  6505. ** Future enhancements may make use of negative N values to define new
  6506. ** kinds of function caching behavior.
  6507. **
  6508. ** These routines must be called from the same thread in which
  6509. ** the SQL function is running.
  6510. */
  6511. SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N);
  6512. SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
  6513. /*
  6514. ** CAPI3REF: Constants Defining Special Destructor Behavior
  6515. **
  6516. ** These are special values for the destructor that is passed in as the
  6517. ** final argument to routines like [sqlite3_result_blob()]. ^If the destructor
  6518. ** argument is SQLITE_STATIC, it means that the content pointer is constant
  6519. ** and will never change. It does not need to be destroyed. ^The
  6520. ** SQLITE_TRANSIENT value means that the content will likely change in
  6521. ** the near future and that SQLite should make its own private copy of
  6522. ** the content before returning.
  6523. **
  6524. ** The typedef is necessary to work around problems in certain
  6525. ** C++ compilers.
  6526. */
  6527. typedef void (*sqlite3_destructor_type)(void*);
  6528. #define SQLITE_STATIC ((sqlite3_destructor_type)0)
  6529. #define SQLITE_TRANSIENT ((sqlite3_destructor_type)-1)
  6530. /*
  6531. ** CAPI3REF: Setting The Result Of An SQL Function
  6532. ** METHOD: sqlite3_context
  6533. **
  6534. ** These routines are used by the xFunc or xFinal callbacks that
  6535. ** implement SQL functions and aggregates. See
  6536. ** [sqlite3_create_function()] and [sqlite3_create_function16()]
  6537. ** for additional information.
  6538. **
  6539. ** These functions work very much like the [parameter binding] family of
  6540. ** functions used to bind values to host parameters in prepared statements.
  6541. ** Refer to the [SQL parameter] documentation for additional information.
  6542. **
  6543. ** ^The sqlite3_result_blob() interface sets the result from
  6544. ** an application-defined function to be the BLOB whose content is pointed
  6545. ** to by the second parameter and which is N bytes long where N is the
  6546. ** third parameter.
  6547. **
  6548. ** ^The sqlite3_result_zeroblob(C,N) and sqlite3_result_zeroblob64(C,N)
  6549. ** interfaces set the result of the application-defined function to be
  6550. ** a BLOB containing all zero bytes and N bytes in size.
  6551. **
  6552. ** ^The sqlite3_result_double() interface sets the result from
  6553. ** an application-defined function to be a floating point value specified
  6554. ** by its 2nd argument.
  6555. **
  6556. ** ^The sqlite3_result_error() and sqlite3_result_error16() functions
  6557. ** cause the implemented SQL function to throw an exception.
  6558. ** ^SQLite uses the string pointed to by the
  6559. ** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
  6560. ** as the text of an error message. ^SQLite interprets the error
  6561. ** message string from sqlite3_result_error() as UTF-8. ^SQLite
  6562. ** interprets the string from sqlite3_result_error16() as UTF-16 using
  6563. ** the same [byte-order determination rules] as [sqlite3_bind_text16()].
  6564. ** ^If the third parameter to sqlite3_result_error()
  6565. ** or sqlite3_result_error16() is negative then SQLite takes as the error
  6566. ** message all text up through the first zero character.
  6567. ** ^If the third parameter to sqlite3_result_error() or
  6568. ** sqlite3_result_error16() is non-negative then SQLite takes that many
  6569. ** bytes (not characters) from the 2nd parameter as the error message.
  6570. ** ^The sqlite3_result_error() and sqlite3_result_error16()
  6571. ** routines make a private copy of the error message text before
  6572. ** they return. Hence, the calling function can deallocate or
  6573. ** modify the text after they return without harm.
  6574. ** ^The sqlite3_result_error_code() function changes the error code
  6575. ** returned by SQLite as a result of an error in a function. ^By default,
  6576. ** the error code is SQLITE_ERROR. ^A subsequent call to sqlite3_result_error()
  6577. ** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.
  6578. **
  6579. ** ^The sqlite3_result_error_toobig() interface causes SQLite to throw an
  6580. ** error indicating that a string or BLOB is too long to represent.
  6581. **
  6582. ** ^The sqlite3_result_error_nomem() interface causes SQLite to throw an
  6583. ** error indicating that a memory allocation failed.
  6584. **
  6585. ** ^The sqlite3_result_int() interface sets the return value
  6586. ** of the application-defined function to be the 32-bit signed integer
  6587. ** value given in the 2nd argument.
  6588. ** ^The sqlite3_result_int64() interface sets the return value
  6589. ** of the application-defined function to be the 64-bit signed integer
  6590. ** value given in the 2nd argument.
  6591. **
  6592. ** ^The sqlite3_result_null() interface sets the return value
  6593. ** of the application-defined function to be NULL.
  6594. **
  6595. ** ^The sqlite3_result_text(), sqlite3_result_text16(),
  6596. ** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
  6597. ** set the return value of the application-defined function to be
  6598. ** a text string which is represented as UTF-8, UTF-16 native byte order,
  6599. ** UTF-16 little endian, or UTF-16 big endian, respectively.
  6600. ** ^The sqlite3_result_text64() interface sets the return value of an
  6601. ** application-defined function to be a text string in an encoding
  6602. ** specified by the fifth (and last) parameter, which must be one
  6603. ** of [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE].
  6604. ** ^SQLite takes the text result from the application from
  6605. ** the 2nd parameter of the sqlite3_result_text* interfaces.
  6606. ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
  6607. ** is negative, then SQLite takes result text from the 2nd parameter
  6608. ** through the first zero character.
  6609. ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
  6610. ** is non-negative, then as many bytes (not characters) of the text
  6611. ** pointed to by the 2nd parameter are taken as the application-defined
  6612. ** function result. If the 3rd parameter is non-negative, then it
  6613. ** must be the byte offset into the string where the NUL terminator would
  6614. ** appear if the string where NUL terminated. If any NUL characters occur
  6615. ** in the string at a byte offset that is less than the value of the 3rd
  6616. ** parameter, then the resulting string will contain embedded NULs and the
  6617. ** result of expressions operating on strings with embedded NULs is undefined.
  6618. ** ^If the 4th parameter to the sqlite3_result_text* interfaces
  6619. ** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
  6620. ** function as the destructor on the text or BLOB result when it has
  6621. ** finished using that result.
  6622. ** ^If the 4th parameter to the sqlite3_result_text* interfaces or to
  6623. ** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite
  6624. ** assumes that the text or BLOB result is in constant space and does not
  6625. ** copy the content of the parameter nor call a destructor on the content
  6626. ** when it has finished using that result.
  6627. ** ^If the 4th parameter to the sqlite3_result_text* interfaces
  6628. ** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
  6629. ** then SQLite makes a copy of the result into space obtained
  6630. ** from [sqlite3_malloc()] before it returns.
  6631. **
  6632. ** ^For the sqlite3_result_text16(), sqlite3_result_text16le(), and
  6633. ** sqlite3_result_text16be() routines, and for sqlite3_result_text64()
  6634. ** when the encoding is not UTF8, if the input UTF16 begins with a
  6635. ** byte-order mark (BOM, U+FEFF) then the BOM is removed from the
  6636. ** string and the rest of the string is interpreted according to the
  6637. ** byte-order specified by the BOM. ^The byte-order specified by
  6638. ** the BOM at the beginning of the text overrides the byte-order
  6639. ** specified by the interface procedure. ^So, for example, if
  6640. ** sqlite3_result_text16le() is invoked with text that begins
  6641. ** with bytes 0xfe, 0xff (a big-endian byte-order mark) then the
  6642. ** first two bytes of input are skipped and the remaining input
  6643. ** is interpreted as UTF16BE text.
  6644. **
  6645. ** ^For UTF16 input text to the sqlite3_result_text16(),
  6646. ** sqlite3_result_text16be(), sqlite3_result_text16le(), and
  6647. ** sqlite3_result_text64() routines, if the text contains invalid
  6648. ** UTF16 characters, the invalid characters might be converted
  6649. ** into the unicode replacement character, U+FFFD.
  6650. **
  6651. ** ^The sqlite3_result_value() interface sets the result of
  6652. ** the application-defined function to be a copy of the
  6653. ** [unprotected sqlite3_value] object specified by the 2nd parameter. ^The
  6654. ** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
  6655. ** so that the [sqlite3_value] specified in the parameter may change or
  6656. ** be deallocated after sqlite3_result_value() returns without harm.
  6657. ** ^A [protected sqlite3_value] object may always be used where an
  6658. ** [unprotected sqlite3_value] object is required, so either
  6659. ** kind of [sqlite3_value] object can be used with this interface.
  6660. **
  6661. ** ^The sqlite3_result_pointer(C,P,T,D) interface sets the result to an
  6662. ** SQL NULL value, just like [sqlite3_result_null(C)], except that it
  6663. ** also associates the host-language pointer P or type T with that
  6664. ** NULL value such that the pointer can be retrieved within an
  6665. ** [application-defined SQL function] using [sqlite3_value_pointer()].
  6666. ** ^If the D parameter is not NULL, then it is a pointer to a destructor
  6667. ** for the P parameter. ^SQLite invokes D with P as its only argument
  6668. ** when SQLite is finished with P. The T parameter should be a static
  6669. ** string and preferably a string literal. The sqlite3_result_pointer()
  6670. ** routine is part of the [pointer passing interface] added for SQLite 3.20.0.
  6671. **
  6672. ** If these routines are called from within the different thread
  6673. ** than the one containing the application-defined function that received
  6674. ** the [sqlite3_context] pointer, the results are undefined.
  6675. */
  6676. SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
  6677. SQLITE_API void sqlite3_result_blob64(sqlite3_context*,const void*,
  6678. sqlite3_uint64,void(*)(void*));
  6679. SQLITE_API void sqlite3_result_double(sqlite3_context*, double);
  6680. SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int);
  6681. SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int);
  6682. SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*);
  6683. SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*);
  6684. SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int);
  6685. SQLITE_API void sqlite3_result_int(sqlite3_context*, int);
  6686. SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
  6687. SQLITE_API void sqlite3_result_null(sqlite3_context*);
  6688. SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
  6689. SQLITE_API void sqlite3_result_text64(sqlite3_context*, const char*,sqlite3_uint64,
  6690. void(*)(void*), unsigned char encoding);
  6691. SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
  6692. SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
  6693. SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
  6694. SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*);
  6695. SQLITE_API void sqlite3_result_pointer(sqlite3_context*, void*,const char*,void(*)(void*));
  6696. SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n);
  6697. SQLITE_API int sqlite3_result_zeroblob64(sqlite3_context*, sqlite3_uint64 n);
  6698. /*
  6699. ** CAPI3REF: Setting The Subtype Of An SQL Function
  6700. ** METHOD: sqlite3_context
  6701. **
  6702. ** The sqlite3_result_subtype(C,T) function causes the subtype of
  6703. ** the result from the [application-defined SQL function] with
  6704. ** [sqlite3_context] C to be the value T. Only the lower 8 bits
  6705. ** of the subtype T are preserved in current versions of SQLite;
  6706. ** higher order bits are discarded.
  6707. ** The number of subtype bytes preserved by SQLite might increase
  6708. ** in future releases of SQLite.
  6709. */
  6710. SQLITE_API void sqlite3_result_subtype(sqlite3_context*,unsigned int);
  6711. /*
  6712. ** CAPI3REF: Define New Collating Sequences
  6713. ** METHOD: sqlite3
  6714. **
  6715. ** ^These functions add, remove, or modify a [collation] associated
  6716. ** with the [database connection] specified as the first argument.
  6717. **
  6718. ** ^The name of the collation is a UTF-8 string
  6719. ** for sqlite3_create_collation() and sqlite3_create_collation_v2()
  6720. ** and a UTF-16 string in native byte order for sqlite3_create_collation16().
  6721. ** ^Collation names that compare equal according to [sqlite3_strnicmp()] are
  6722. ** considered to be the same name.
  6723. **
  6724. ** ^(The third argument (eTextRep) must be one of the constants:
  6725. ** <ul>
  6726. ** <li> [SQLITE_UTF8],
  6727. ** <li> [SQLITE_UTF16LE],
  6728. ** <li> [SQLITE_UTF16BE],
  6729. ** <li> [SQLITE_UTF16], or
  6730. ** <li> [SQLITE_UTF16_ALIGNED].
  6731. ** </ul>)^
  6732. ** ^The eTextRep argument determines the encoding of strings passed
  6733. ** to the collating function callback, xCompare.
  6734. ** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep
  6735. ** force strings to be UTF16 with native byte order.
  6736. ** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin
  6737. ** on an even byte address.
  6738. **
  6739. ** ^The fourth argument, pArg, is an application data pointer that is passed
  6740. ** through as the first argument to the collating function callback.
  6741. **
  6742. ** ^The fifth argument, xCompare, is a pointer to the collating function.
  6743. ** ^Multiple collating functions can be registered using the same name but
  6744. ** with different eTextRep parameters and SQLite will use whichever
  6745. ** function requires the least amount of data transformation.
  6746. ** ^If the xCompare argument is NULL then the collating function is
  6747. ** deleted. ^When all collating functions having the same name are deleted,
  6748. ** that collation is no longer usable.
  6749. **
  6750. ** ^The collating function callback is invoked with a copy of the pArg
  6751. ** application data pointer and with two strings in the encoding specified
  6752. ** by the eTextRep argument. The two integer parameters to the collating
  6753. ** function callback are the length of the two strings, in bytes. The collating
  6754. ** function must return an integer that is negative, zero, or positive
  6755. ** if the first string is less than, equal to, or greater than the second,
  6756. ** respectively. A collating function must always return the same answer
  6757. ** given the same inputs. If two or more collating functions are registered
  6758. ** to the same collation name (using different eTextRep values) then all
  6759. ** must give an equivalent answer when invoked with equivalent strings.
  6760. ** The collating function must obey the following properties for all
  6761. ** strings A, B, and C:
  6762. **
  6763. ** <ol>
  6764. ** <li> If A==B then B==A.
  6765. ** <li> If A==B and B==C then A==C.
  6766. ** <li> If A&lt;B THEN B&gt;A.
  6767. ** <li> If A&lt;B and B&lt;C then A&lt;C.
  6768. ** </ol>
  6769. **
  6770. ** If a collating function fails any of the above constraints and that
  6771. ** collating function is registered and used, then the behavior of SQLite
  6772. ** is undefined.
  6773. **
  6774. ** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation()
  6775. ** with the addition that the xDestroy callback is invoked on pArg when
  6776. ** the collating function is deleted.
  6777. ** ^Collating functions are deleted when they are overridden by later
  6778. ** calls to the collation creation functions or when the
  6779. ** [database connection] is closed using [sqlite3_close()].
  6780. **
  6781. ** ^The xDestroy callback is <u>not</u> called if the
  6782. ** sqlite3_create_collation_v2() function fails. Applications that invoke
  6783. ** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should
  6784. ** check the return code and dispose of the application data pointer
  6785. ** themselves rather than expecting SQLite to deal with it for them.
  6786. ** This is different from every other SQLite interface. The inconsistency
  6787. ** is unfortunate but cannot be changed without breaking backwards
  6788. ** compatibility.
  6789. **
  6790. ** See also: [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].
  6791. */
  6792. SQLITE_API int sqlite3_create_collation(
  6793. sqlite3*,
  6794. const char *zName,
  6795. int eTextRep,
  6796. void *pArg,
  6797. int(*xCompare)(void*,int,const void*,int,const void*)
  6798. );
  6799. SQLITE_API int sqlite3_create_collation_v2(
  6800. sqlite3*,
  6801. const char *zName,
  6802. int eTextRep,
  6803. void *pArg,
  6804. int(*xCompare)(void*,int,const void*,int,const void*),
  6805. void(*xDestroy)(void*)
  6806. );
  6807. SQLITE_API int sqlite3_create_collation16(
  6808. sqlite3*,
  6809. const void *zName,
  6810. int eTextRep,
  6811. void *pArg,
  6812. int(*xCompare)(void*,int,const void*,int,const void*)
  6813. );
  6814. /*
  6815. ** CAPI3REF: Collation Needed Callbacks
  6816. ** METHOD: sqlite3
  6817. **
  6818. ** ^To avoid having to register all collation sequences before a database
  6819. ** can be used, a single callback function may be registered with the
  6820. ** [database connection] to be invoked whenever an undefined collation
  6821. ** sequence is required.
  6822. **
  6823. ** ^If the function is registered using the sqlite3_collation_needed() API,
  6824. ** then it is passed the names of undefined collation sequences as strings
  6825. ** encoded in UTF-8. ^If sqlite3_collation_needed16() is used,
  6826. ** the names are passed as UTF-16 in machine native byte order.
  6827. ** ^A call to either function replaces the existing collation-needed callback.
  6828. **
  6829. ** ^(When the callback is invoked, the first argument passed is a copy
  6830. ** of the second argument to sqlite3_collation_needed() or
  6831. ** sqlite3_collation_needed16(). The second argument is the database
  6832. ** connection. The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE],
  6833. ** or [SQLITE_UTF16LE], indicating the most desirable form of the collation
  6834. ** sequence function required. The fourth parameter is the name of the
  6835. ** required collation sequence.)^
  6836. **
  6837. ** The callback function should register the desired collation using
  6838. ** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
  6839. ** [sqlite3_create_collation_v2()].
  6840. */
  6841. SQLITE_API int sqlite3_collation_needed(
  6842. sqlite3*,
  6843. void*,
  6844. void(*)(void*,sqlite3*,int eTextRep,const char*)
  6845. );
  6846. SQLITE_API int sqlite3_collation_needed16(
  6847. sqlite3*,
  6848. void*,
  6849. void(*)(void*,sqlite3*,int eTextRep,const void*)
  6850. );
  6851. #ifdef SQLITE_ENABLE_CEROD
  6852. /*
  6853. ** Specify the activation key for a CEROD database. Unless
  6854. ** activated, none of the CEROD routines will work.
  6855. */
  6856. SQLITE_API void sqlite3_activate_cerod(
  6857. const char *zPassPhrase /* Activation phrase */
  6858. );
  6859. #endif
  6860. /*
  6861. ** CAPI3REF: Suspend Execution For A Short Time
  6862. **
  6863. ** The sqlite3_sleep() function causes the current thread to suspend execution
  6864. ** for at least a number of milliseconds specified in its parameter.
  6865. **
  6866. ** If the operating system does not support sleep requests with
  6867. ** millisecond time resolution, then the time will be rounded up to
  6868. ** the nearest second. The number of milliseconds of sleep actually
  6869. ** requested from the operating system is returned.
  6870. **
  6871. ** ^SQLite implements this interface by calling the xSleep()
  6872. ** method of the default [sqlite3_vfs] object. If the xSleep() method
  6873. ** of the default VFS is not implemented correctly, or not implemented at
  6874. ** all, then the behavior of sqlite3_sleep() may deviate from the description
  6875. ** in the previous paragraphs.
  6876. */
  6877. SQLITE_API int sqlite3_sleep(int);
  6878. /*
  6879. ** CAPI3REF: Name Of The Folder Holding Temporary Files
  6880. **
  6881. ** ^(If this global variable is made to point to a string which is
  6882. ** the name of a folder (a.k.a. directory), then all temporary files
  6883. ** created by SQLite when using a built-in [sqlite3_vfs | VFS]
  6884. ** will be placed in that directory.)^ ^If this variable
  6885. ** is a NULL pointer, then SQLite performs a search for an appropriate
  6886. ** temporary file directory.
  6887. **
  6888. ** Applications are strongly discouraged from using this global variable.
  6889. ** It is required to set a temporary folder on Windows Runtime (WinRT).
  6890. ** But for all other platforms, it is highly recommended that applications
  6891. ** neither read nor write this variable. This global variable is a relic
  6892. ** that exists for backwards compatibility of legacy applications and should
  6893. ** be avoided in new projects.
  6894. **
  6895. ** It is not safe to read or modify this variable in more than one
  6896. ** thread at a time. It is not safe to read or modify this variable
  6897. ** if a [database connection] is being used at the same time in a separate
  6898. ** thread.
  6899. ** It is intended that this variable be set once
  6900. ** as part of process initialization and before any SQLite interface
  6901. ** routines have been called and that this variable remain unchanged
  6902. ** thereafter.
  6903. **
  6904. ** ^The [temp_store_directory pragma] may modify this variable and cause
  6905. ** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore,
  6906. ** the [temp_store_directory pragma] always assumes that any string
  6907. ** that this variable points to is held in memory obtained from
  6908. ** [sqlite3_malloc] and the pragma may attempt to free that memory
  6909. ** using [sqlite3_free].
  6910. ** Hence, if this variable is modified directly, either it should be
  6911. ** made NULL or made to point to memory obtained from [sqlite3_malloc]
  6912. ** or else the use of the [temp_store_directory pragma] should be avoided.
  6913. ** Except when requested by the [temp_store_directory pragma], SQLite
  6914. ** does not free the memory that sqlite3_temp_directory points to. If
  6915. ** the application wants that memory to be freed, it must do
  6916. ** so itself, taking care to only do so after all [database connection]
  6917. ** objects have been destroyed.
  6918. **
  6919. ** <b>Note to Windows Runtime users:</b> The temporary directory must be set
  6920. ** prior to calling [sqlite3_open] or [sqlite3_open_v2]. Otherwise, various
  6921. ** features that require the use of temporary files may fail. Here is an
  6922. ** example of how to do this using C++ with the Windows Runtime:
  6923. **
  6924. ** <blockquote><pre>
  6925. ** LPCWSTR zPath = Windows::Storage::ApplicationData::Current->
  6926. ** &nbsp; TemporaryFolder->Path->Data();
  6927. ** char zPathBuf&#91;MAX_PATH + 1&#93;;
  6928. ** memset(zPathBuf, 0, sizeof(zPathBuf));
  6929. ** WideCharToMultiByte(CP_UTF8, 0, zPath, -1, zPathBuf, sizeof(zPathBuf),
  6930. ** &nbsp; NULL, NULL);
  6931. ** sqlite3_temp_directory = sqlite3_mprintf("%s", zPathBuf);
  6932. ** </pre></blockquote>
  6933. */
  6934. SQLITE_API char *sqlite3_temp_directory;
  6935. /*
  6936. ** CAPI3REF: Name Of The Folder Holding Database Files
  6937. **
  6938. ** ^(If this global variable is made to point to a string which is
  6939. ** the name of a folder (a.k.a. directory), then all database files
  6940. ** specified with a relative pathname and created or accessed by
  6941. ** SQLite when using a built-in windows [sqlite3_vfs | VFS] will be assumed
  6942. ** to be relative to that directory.)^ ^If this variable is a NULL
  6943. ** pointer, then SQLite assumes that all database files specified
  6944. ** with a relative pathname are relative to the current directory
  6945. ** for the process. Only the windows VFS makes use of this global
  6946. ** variable; it is ignored by the unix VFS.
  6947. **
  6948. ** Changing the value of this variable while a database connection is
  6949. ** open can result in a corrupt database.
  6950. **
  6951. ** It is not safe to read or modify this variable in more than one
  6952. ** thread at a time. It is not safe to read or modify this variable
  6953. ** if a [database connection] is being used at the same time in a separate
  6954. ** thread.
  6955. ** It is intended that this variable be set once
  6956. ** as part of process initialization and before any SQLite interface
  6957. ** routines have been called and that this variable remain unchanged
  6958. ** thereafter.
  6959. **
  6960. ** ^The [data_store_directory pragma] may modify this variable and cause
  6961. ** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore,
  6962. ** the [data_store_directory pragma] always assumes that any string
  6963. ** that this variable points to is held in memory obtained from
  6964. ** [sqlite3_malloc] and the pragma may attempt to free that memory
  6965. ** using [sqlite3_free].
  6966. ** Hence, if this variable is modified directly, either it should be
  6967. ** made NULL or made to point to memory obtained from [sqlite3_malloc]
  6968. ** or else the use of the [data_store_directory pragma] should be avoided.
  6969. */
  6970. SQLITE_API char *sqlite3_data_directory;
  6971. /*
  6972. ** CAPI3REF: Win32 Specific Interface
  6973. **
  6974. ** These interfaces are available only on Windows. The
  6975. ** [sqlite3_win32_set_directory] interface is used to set the value associated
  6976. ** with the [sqlite3_temp_directory] or [sqlite3_data_directory] variable, to
  6977. ** zValue, depending on the value of the type parameter. The zValue parameter
  6978. ** should be NULL to cause the previous value to be freed via [sqlite3_free];
  6979. ** a non-NULL value will be copied into memory obtained from [sqlite3_malloc]
  6980. ** prior to being used. The [sqlite3_win32_set_directory] interface returns
  6981. ** [SQLITE_OK] to indicate success, [SQLITE_ERROR] if the type is unsupported,
  6982. ** or [SQLITE_NOMEM] if memory could not be allocated. The value of the
  6983. ** [sqlite3_data_directory] variable is intended to act as a replacement for
  6984. ** the current directory on the sub-platforms of Win32 where that concept is
  6985. ** not present, e.g. WinRT and UWP. The [sqlite3_win32_set_directory8] and
  6986. ** [sqlite3_win32_set_directory16] interfaces behave exactly the same as the
  6987. ** sqlite3_win32_set_directory interface except the string parameter must be
  6988. ** UTF-8 or UTF-16, respectively.
  6989. */
  6990. SQLITE_API int sqlite3_win32_set_directory(
  6991. unsigned long type, /* Identifier for directory being set or reset */
  6992. void *zValue /* New value for directory being set or reset */
  6993. );
  6994. SQLITE_API int sqlite3_win32_set_directory8(unsigned long type, const char *zValue);
  6995. SQLITE_API int sqlite3_win32_set_directory16(unsigned long type, const void *zValue);
  6996. /*
  6997. ** CAPI3REF: Win32 Directory Types
  6998. **
  6999. ** These macros are only available on Windows. They define the allowed values
  7000. ** for the type argument to the [sqlite3_win32_set_directory] interface.
  7001. */
  7002. #define SQLITE_WIN32_DATA_DIRECTORY_TYPE 1
  7003. #define SQLITE_WIN32_TEMP_DIRECTORY_TYPE 2
  7004. /*
  7005. ** CAPI3REF: Test For Auto-Commit Mode
  7006. ** KEYWORDS: {autocommit mode}
  7007. ** METHOD: sqlite3
  7008. **
  7009. ** ^The sqlite3_get_autocommit() interface returns non-zero or
  7010. ** zero if the given database connection is or is not in autocommit mode,
  7011. ** respectively. ^Autocommit mode is on by default.
  7012. ** ^Autocommit mode is disabled by a [BEGIN] statement.
  7013. ** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].
  7014. **
  7015. ** If certain kinds of errors occur on a statement within a multi-statement
  7016. ** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR],
  7017. ** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
  7018. ** transaction might be rolled back automatically. The only way to
  7019. ** find out whether SQLite automatically rolled back the transaction after
  7020. ** an error is to use this function.
  7021. **
  7022. ** If another thread changes the autocommit status of the database
  7023. ** connection while this routine is running, then the return value
  7024. ** is undefined.
  7025. */
  7026. SQLITE_API int sqlite3_get_autocommit(sqlite3*);
  7027. /*
  7028. ** CAPI3REF: Find The Database Handle Of A Prepared Statement
  7029. ** METHOD: sqlite3_stmt
  7030. **
  7031. ** ^The sqlite3_db_handle interface returns the [database connection] handle
  7032. ** to which a [prepared statement] belongs. ^The [database connection]
  7033. ** returned by sqlite3_db_handle is the same [database connection]
  7034. ** that was the first argument
  7035. ** to the [sqlite3_prepare_v2()] call (or its variants) that was used to
  7036. ** create the statement in the first place.
  7037. */
  7038. SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*);
  7039. /*
  7040. ** CAPI3REF: Return The Filename For A Database Connection
  7041. ** METHOD: sqlite3
  7042. **
  7043. ** ^The sqlite3_db_filename(D,N) interface returns a pointer to the filename
  7044. ** associated with database N of connection D.
  7045. ** ^If there is no attached database N on the database
  7046. ** connection D, or if database N is a temporary or in-memory database, then
  7047. ** this function will return either a NULL pointer or an empty string.
  7048. **
  7049. ** ^The string value returned by this routine is owned and managed by
  7050. ** the database connection. ^The value will be valid until the database N
  7051. ** is [DETACH]-ed or until the database connection closes.
  7052. **
  7053. ** ^The filename returned by this function is the output of the
  7054. ** xFullPathname method of the [VFS]. ^In other words, the filename
  7055. ** will be an absolute pathname, even if the filename used
  7056. ** to open the database originally was a URI or relative pathname.
  7057. **
  7058. ** If the filename pointer returned by this routine is not NULL, then it
  7059. ** can be used as the filename input parameter to these routines:
  7060. ** <ul>
  7061. ** <li> [sqlite3_uri_parameter()]
  7062. ** <li> [sqlite3_uri_boolean()]
  7063. ** <li> [sqlite3_uri_int64()]
  7064. ** <li> [sqlite3_filename_database()]
  7065. ** <li> [sqlite3_filename_journal()]
  7066. ** <li> [sqlite3_filename_wal()]
  7067. ** </ul>
  7068. */
  7069. SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName);
  7070. /*
  7071. ** CAPI3REF: Determine if a database is read-only
  7072. ** METHOD: sqlite3
  7073. **
  7074. ** ^The sqlite3_db_readonly(D,N) interface returns 1 if the database N
  7075. ** of connection D is read-only, 0 if it is read/write, or -1 if N is not
  7076. ** the name of a database on connection D.
  7077. */
  7078. SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName);
  7079. /*
  7080. ** CAPI3REF: Find the next prepared statement
  7081. ** METHOD: sqlite3
  7082. **
  7083. ** ^This interface returns a pointer to the next [prepared statement] after
  7084. ** pStmt associated with the [database connection] pDb. ^If pStmt is NULL
  7085. ** then this interface returns a pointer to the first prepared statement
  7086. ** associated with the database connection pDb. ^If no prepared statement
  7087. ** satisfies the conditions of this routine, it returns NULL.
  7088. **
  7089. ** The [database connection] pointer D in a call to
  7090. ** [sqlite3_next_stmt(D,S)] must refer to an open database
  7091. ** connection and in particular must not be a NULL pointer.
  7092. */
  7093. SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt);
  7094. /*
  7095. ** CAPI3REF: Commit And Rollback Notification Callbacks
  7096. ** METHOD: sqlite3
  7097. **
  7098. ** ^The sqlite3_commit_hook() interface registers a callback
  7099. ** function to be invoked whenever a transaction is [COMMIT | committed].
  7100. ** ^Any callback set by a previous call to sqlite3_commit_hook()
  7101. ** for the same database connection is overridden.
  7102. ** ^The sqlite3_rollback_hook() interface registers a callback
  7103. ** function to be invoked whenever a transaction is [ROLLBACK | rolled back].
  7104. ** ^Any callback set by a previous call to sqlite3_rollback_hook()
  7105. ** for the same database connection is overridden.
  7106. ** ^The pArg argument is passed through to the callback.
  7107. ** ^If the callback on a commit hook function returns non-zero,
  7108. ** then the commit is converted into a rollback.
  7109. **
  7110. ** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions
  7111. ** return the P argument from the previous call of the same function
  7112. ** on the same [database connection] D, or NULL for
  7113. ** the first call for each function on D.
  7114. **
  7115. ** The commit and rollback hook callbacks are not reentrant.
  7116. ** The callback implementation must not do anything that will modify
  7117. ** the database connection that invoked the callback. Any actions
  7118. ** to modify the database connection must be deferred until after the
  7119. ** completion of the [sqlite3_step()] call that triggered the commit
  7120. ** or rollback hook in the first place.
  7121. ** Note that running any other SQL statements, including SELECT statements,
  7122. ** or merely calling [sqlite3_prepare_v2()] and [sqlite3_step()] will modify
  7123. ** the database connections for the meaning of "modify" in this paragraph.
  7124. **
  7125. ** ^Registering a NULL function disables the callback.
  7126. **
  7127. ** ^When the commit hook callback routine returns zero, the [COMMIT]
  7128. ** operation is allowed to continue normally. ^If the commit hook
  7129. ** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK].
  7130. ** ^The rollback hook is invoked on a rollback that results from a commit
  7131. ** hook returning non-zero, just as it would be with any other rollback.
  7132. **
  7133. ** ^For the purposes of this API, a transaction is said to have been
  7134. ** rolled back if an explicit "ROLLBACK" statement is executed, or
  7135. ** an error or constraint causes an implicit rollback to occur.
  7136. ** ^The rollback callback is not invoked if a transaction is
  7137. ** automatically rolled back because the database connection is closed.
  7138. **
  7139. ** See also the [sqlite3_update_hook()] interface.
  7140. */
  7141. SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
  7142. SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
  7143. /*
  7144. ** CAPI3REF: Data Change Notification Callbacks
  7145. ** METHOD: sqlite3
  7146. **
  7147. ** ^The sqlite3_update_hook() interface registers a callback function
  7148. ** with the [database connection] identified by the first argument
  7149. ** to be invoked whenever a row is updated, inserted or deleted in
  7150. ** a [rowid table].
  7151. ** ^Any callback set by a previous call to this function
  7152. ** for the same database connection is overridden.
  7153. **
  7154. ** ^The second argument is a pointer to the function to invoke when a
  7155. ** row is updated, inserted or deleted in a rowid table.
  7156. ** ^The first argument to the callback is a copy of the third argument
  7157. ** to sqlite3_update_hook().
  7158. ** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],
  7159. ** or [SQLITE_UPDATE], depending on the operation that caused the callback
  7160. ** to be invoked.
  7161. ** ^The third and fourth arguments to the callback contain pointers to the
  7162. ** database and table name containing the affected row.
  7163. ** ^The final callback parameter is the [rowid] of the row.
  7164. ** ^In the case of an update, this is the [rowid] after the update takes place.
  7165. **
  7166. ** ^(The update hook is not invoked when internal system tables are
  7167. ** modified (i.e. sqlite_master and sqlite_sequence).)^
  7168. ** ^The update hook is not invoked when [WITHOUT ROWID] tables are modified.
  7169. **
  7170. ** ^In the current implementation, the update hook
  7171. ** is not invoked when conflicting rows are deleted because of an
  7172. ** [ON CONFLICT | ON CONFLICT REPLACE] clause. ^Nor is the update hook
  7173. ** invoked when rows are deleted using the [truncate optimization].
  7174. ** The exceptions defined in this paragraph might change in a future
  7175. ** release of SQLite.
  7176. **
  7177. ** The update hook implementation must not do anything that will modify
  7178. ** the database connection that invoked the update hook. Any actions
  7179. ** to modify the database connection must be deferred until after the
  7180. ** completion of the [sqlite3_step()] call that triggered the update hook.
  7181. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
  7182. ** database connections for the meaning of "modify" in this paragraph.
  7183. **
  7184. ** ^The sqlite3_update_hook(D,C,P) function
  7185. ** returns the P argument from the previous call
  7186. ** on the same [database connection] D, or NULL for
  7187. ** the first call on D.
  7188. **
  7189. ** See also the [sqlite3_commit_hook()], [sqlite3_rollback_hook()],
  7190. ** and [sqlite3_preupdate_hook()] interfaces.
  7191. */
  7192. SQLITE_API void *sqlite3_update_hook(
  7193. sqlite3*,
  7194. void(*)(void *,int ,char const *,char const *,sqlite3_int64),
  7195. void*
  7196. );
  7197. /*
  7198. ** CAPI3REF: Enable Or Disable Shared Pager Cache
  7199. **
  7200. ** ^(This routine enables or disables the sharing of the database cache
  7201. ** and schema data structures between [database connection | connections]
  7202. ** to the same database. Sharing is enabled if the argument is true
  7203. ** and disabled if the argument is false.)^
  7204. **
  7205. ** ^Cache sharing is enabled and disabled for an entire process.
  7206. ** This is a change as of SQLite [version 3.5.0] ([dateof:3.5.0]).
  7207. ** In prior versions of SQLite,
  7208. ** sharing was enabled or disabled for each thread separately.
  7209. **
  7210. ** ^(The cache sharing mode set by this interface effects all subsequent
  7211. ** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
  7212. ** Existing database connections continue to use the sharing mode
  7213. ** that was in effect at the time they were opened.)^
  7214. **
  7215. ** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled
  7216. ** successfully. An [error code] is returned otherwise.)^
  7217. **
  7218. ** ^Shared cache is disabled by default. It is recommended that it stay
  7219. ** that way. In other words, do not use this routine. This interface
  7220. ** continues to be provided for historical compatibility, but its use is
  7221. ** discouraged. Any use of shared cache is discouraged. If shared cache
  7222. ** must be used, it is recommended that shared cache only be enabled for
  7223. ** individual database connections using the [sqlite3_open_v2()] interface
  7224. ** with the [SQLITE_OPEN_SHAREDCACHE] flag.
  7225. **
  7226. ** Note: This method is disabled on MacOS X 10.7 and iOS version 5.0
  7227. ** and will always return SQLITE_MISUSE. On those systems,
  7228. ** shared cache mode should be enabled per-database connection via
  7229. ** [sqlite3_open_v2()] with [SQLITE_OPEN_SHAREDCACHE].
  7230. **
  7231. ** This interface is threadsafe on processors where writing a
  7232. ** 32-bit integer is atomic.
  7233. **
  7234. ** See Also: [SQLite Shared-Cache Mode]
  7235. */
  7236. SQLITE_API int sqlite3_enable_shared_cache(int);
  7237. /*
  7238. ** CAPI3REF: Attempt To Free Heap Memory
  7239. **
  7240. ** ^The sqlite3_release_memory() interface attempts to free N bytes
  7241. ** of heap memory by deallocating non-essential memory allocations
  7242. ** held by the database library. Memory used to cache database
  7243. ** pages to improve performance is an example of non-essential memory.
  7244. ** ^sqlite3_release_memory() returns the number of bytes actually freed,
  7245. ** which might be more or less than the amount requested.
  7246. ** ^The sqlite3_release_memory() routine is a no-op returning zero
  7247. ** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT].
  7248. **
  7249. ** See also: [sqlite3_db_release_memory()]
  7250. */
  7251. SQLITE_API int sqlite3_release_memory(int);
  7252. /*
  7253. ** CAPI3REF: Free Memory Used By A Database Connection
  7254. ** METHOD: sqlite3
  7255. **
  7256. ** ^The sqlite3_db_release_memory(D) interface attempts to free as much heap
  7257. ** memory as possible from database connection D. Unlike the
  7258. ** [sqlite3_release_memory()] interface, this interface is in effect even
  7259. ** when the [SQLITE_ENABLE_MEMORY_MANAGEMENT] compile-time option is
  7260. ** omitted.
  7261. **
  7262. ** See also: [sqlite3_release_memory()]
  7263. */
  7264. SQLITE_API int sqlite3_db_release_memory(sqlite3*);
  7265. /*
  7266. ** CAPI3REF: Impose A Limit On Heap Size
  7267. **
  7268. ** These interfaces impose limits on the amount of heap memory that will be
  7269. ** by all database connections within a single process.
  7270. **
  7271. ** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the
  7272. ** soft limit on the amount of heap memory that may be allocated by SQLite.
  7273. ** ^SQLite strives to keep heap memory utilization below the soft heap
  7274. ** limit by reducing the number of pages held in the page cache
  7275. ** as heap memory usages approaches the limit.
  7276. ** ^The soft heap limit is "soft" because even though SQLite strives to stay
  7277. ** below the limit, it will exceed the limit rather than generate
  7278. ** an [SQLITE_NOMEM] error. In other words, the soft heap limit
  7279. ** is advisory only.
  7280. **
  7281. ** ^The sqlite3_hard_heap_limit64(N) interface sets a hard upper bound of
  7282. ** N bytes on the amount of memory that will be allocated. ^The
  7283. ** sqlite3_hard_heap_limit64(N) interface is similar to
  7284. ** sqlite3_soft_heap_limit64(N) except that memory allocations will fail
  7285. ** when the hard heap limit is reached.
  7286. **
  7287. ** ^The return value from both sqlite3_soft_heap_limit64() and
  7288. ** sqlite3_hard_heap_limit64() is the size of
  7289. ** the heap limit prior to the call, or negative in the case of an
  7290. ** error. ^If the argument N is negative
  7291. ** then no change is made to the heap limit. Hence, the current
  7292. ** size of heap limits can be determined by invoking
  7293. ** sqlite3_soft_heap_limit64(-1) or sqlite3_hard_heap_limit(-1).
  7294. **
  7295. ** ^Setting the heap limits to zero disables the heap limiter mechanism.
  7296. **
  7297. ** ^The soft heap limit may not be greater than the hard heap limit.
  7298. ** ^If the hard heap limit is enabled and if sqlite3_soft_heap_limit(N)
  7299. ** is invoked with a value of N that is greater than the hard heap limit,
  7300. ** the the soft heap limit is set to the value of the hard heap limit.
  7301. ** ^The soft heap limit is automatically enabled whenever the hard heap
  7302. ** limit is enabled. ^When sqlite3_hard_heap_limit64(N) is invoked and
  7303. ** the soft heap limit is outside the range of 1..N, then the soft heap
  7304. ** limit is set to N. ^Invoking sqlite3_soft_heap_limit64(0) when the
  7305. ** hard heap limit is enabled makes the soft heap limit equal to the
  7306. ** hard heap limit.
  7307. **
  7308. ** The memory allocation limits can also be adjusted using
  7309. ** [PRAGMA soft_heap_limit] and [PRAGMA hard_heap_limit].
  7310. **
  7311. ** ^(The heap limits are not enforced in the current implementation
  7312. ** if one or more of following conditions are true:
  7313. **
  7314. ** <ul>
  7315. ** <li> The limit value is set to zero.
  7316. ** <li> Memory accounting is disabled using a combination of the
  7317. ** [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and
  7318. ** the [SQLITE_DEFAULT_MEMSTATUS] compile-time option.
  7319. ** <li> An alternative page cache implementation is specified using
  7320. ** [sqlite3_config]([SQLITE_CONFIG_PCACHE2],...).
  7321. ** <li> The page cache allocates from its own memory pool supplied
  7322. ** by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than
  7323. ** from the heap.
  7324. ** </ul>)^
  7325. **
  7326. ** The circumstances under which SQLite will enforce the heap limits may
  7327. ** changes in future releases of SQLite.
  7328. */
  7329. SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 N);
  7330. SQLITE_API sqlite3_int64 sqlite3_hard_heap_limit64(sqlite3_int64 N);
  7331. /*
  7332. ** CAPI3REF: Deprecated Soft Heap Limit Interface
  7333. ** DEPRECATED
  7334. **
  7335. ** This is a deprecated version of the [sqlite3_soft_heap_limit64()]
  7336. ** interface. This routine is provided for historical compatibility
  7337. ** only. All new applications should use the
  7338. ** [sqlite3_soft_heap_limit64()] interface rather than this one.
  7339. */
  7340. SQLITE_API SQLITE_DEPRECATED void sqlite3_soft_heap_limit(int N);
  7341. /*
  7342. ** CAPI3REF: Extract Metadata About A Column Of A Table
  7343. ** METHOD: sqlite3
  7344. **
  7345. ** ^(The sqlite3_table_column_metadata(X,D,T,C,....) routine returns
  7346. ** information about column C of table T in database D
  7347. ** on [database connection] X.)^ ^The sqlite3_table_column_metadata()
  7348. ** interface returns SQLITE_OK and fills in the non-NULL pointers in
  7349. ** the final five arguments with appropriate values if the specified
  7350. ** column exists. ^The sqlite3_table_column_metadata() interface returns
  7351. ** SQLITE_ERROR if the specified column does not exist.
  7352. ** ^If the column-name parameter to sqlite3_table_column_metadata() is a
  7353. ** NULL pointer, then this routine simply checks for the existence of the
  7354. ** table and returns SQLITE_OK if the table exists and SQLITE_ERROR if it
  7355. ** does not. If the table name parameter T in a call to
  7356. ** sqlite3_table_column_metadata(X,D,T,C,...) is NULL then the result is
  7357. ** undefined behavior.
  7358. **
  7359. ** ^The column is identified by the second, third and fourth parameters to
  7360. ** this function. ^(The second parameter is either the name of the database
  7361. ** (i.e. "main", "temp", or an attached database) containing the specified
  7362. ** table or NULL.)^ ^If it is NULL, then all attached databases are searched
  7363. ** for the table using the same algorithm used by the database engine to
  7364. ** resolve unqualified table references.
  7365. **
  7366. ** ^The third and fourth parameters to this function are the table and column
  7367. ** name of the desired column, respectively.
  7368. **
  7369. ** ^Metadata is returned by writing to the memory locations passed as the 5th
  7370. ** and subsequent parameters to this function. ^Any of these arguments may be
  7371. ** NULL, in which case the corresponding element of metadata is omitted.
  7372. **
  7373. ** ^(<blockquote>
  7374. ** <table border="1">
  7375. ** <tr><th> Parameter <th> Output<br>Type <th> Description
  7376. **
  7377. ** <tr><td> 5th <td> const char* <td> Data type
  7378. ** <tr><td> 6th <td> const char* <td> Name of default collation sequence
  7379. ** <tr><td> 7th <td> int <td> True if column has a NOT NULL constraint
  7380. ** <tr><td> 8th <td> int <td> True if column is part of the PRIMARY KEY
  7381. ** <tr><td> 9th <td> int <td> True if column is [AUTOINCREMENT]
  7382. ** </table>
  7383. ** </blockquote>)^
  7384. **
  7385. ** ^The memory pointed to by the character pointers returned for the
  7386. ** declaration type and collation sequence is valid until the next
  7387. ** call to any SQLite API function.
  7388. **
  7389. ** ^If the specified table is actually a view, an [error code] is returned.
  7390. **
  7391. ** ^If the specified column is "rowid", "oid" or "_rowid_" and the table
  7392. ** is not a [WITHOUT ROWID] table and an
  7393. ** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output
  7394. ** parameters are set for the explicitly declared column. ^(If there is no
  7395. ** [INTEGER PRIMARY KEY] column, then the outputs
  7396. ** for the [rowid] are set as follows:
  7397. **
  7398. ** <pre>
  7399. ** data type: "INTEGER"
  7400. ** collation sequence: "BINARY"
  7401. ** not null: 0
  7402. ** primary key: 1
  7403. ** auto increment: 0
  7404. ** </pre>)^
  7405. **
  7406. ** ^This function causes all database schemas to be read from disk and
  7407. ** parsed, if that has not already been done, and returns an error if
  7408. ** any errors are encountered while loading the schema.
  7409. */
  7410. SQLITE_API int sqlite3_table_column_metadata(
  7411. sqlite3 *db, /* Connection handle */
  7412. const char *zDbName, /* Database name or NULL */
  7413. const char *zTableName, /* Table name */
  7414. const char *zColumnName, /* Column name */
  7415. char const **pzDataType, /* OUTPUT: Declared data type */
  7416. char const **pzCollSeq, /* OUTPUT: Collation sequence name */
  7417. int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */
  7418. int *pPrimaryKey, /* OUTPUT: True if column part of PK */
  7419. int *pAutoinc /* OUTPUT: True if column is auto-increment */
  7420. );
  7421. /*
  7422. ** CAPI3REF: Load An Extension
  7423. ** METHOD: sqlite3
  7424. **
  7425. ** ^This interface loads an SQLite extension library from the named file.
  7426. **
  7427. ** ^The sqlite3_load_extension() interface attempts to load an
  7428. ** [SQLite extension] library contained in the file zFile. If
  7429. ** the file cannot be loaded directly, attempts are made to load
  7430. ** with various operating-system specific extensions added.
  7431. ** So for example, if "samplelib" cannot be loaded, then names like
  7432. ** "samplelib.so" or "samplelib.dylib" or "samplelib.dll" might
  7433. ** be tried also.
  7434. **
  7435. ** ^The entry point is zProc.
  7436. ** ^(zProc may be 0, in which case SQLite will try to come up with an
  7437. ** entry point name on its own. It first tries "sqlite3_extension_init".
  7438. ** If that does not work, it constructs a name "sqlite3_X_init" where the
  7439. ** X is consists of the lower-case equivalent of all ASCII alphabetic
  7440. ** characters in the filename from the last "/" to the first following
  7441. ** "." and omitting any initial "lib".)^
  7442. ** ^The sqlite3_load_extension() interface returns
  7443. ** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
  7444. ** ^If an error occurs and pzErrMsg is not 0, then the
  7445. ** [sqlite3_load_extension()] interface shall attempt to
  7446. ** fill *pzErrMsg with error message text stored in memory
  7447. ** obtained from [sqlite3_malloc()]. The calling function
  7448. ** should free this memory by calling [sqlite3_free()].
  7449. **
  7450. ** ^Extension loading must be enabled using
  7451. ** [sqlite3_enable_load_extension()] or
  7452. ** [sqlite3_db_config](db,[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION],1,NULL)
  7453. ** prior to calling this API,
  7454. ** otherwise an error will be returned.
  7455. **
  7456. ** <b>Security warning:</b> It is recommended that the
  7457. ** [SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION] method be used to enable only this
  7458. ** interface. The use of the [sqlite3_enable_load_extension()] interface
  7459. ** should be avoided. This will keep the SQL function [load_extension()]
  7460. ** disabled and prevent SQL injections from giving attackers
  7461. ** access to extension loading capabilities.
  7462. **
  7463. ** See also the [load_extension() SQL function].
  7464. */
  7465. SQLITE_API int sqlite3_load_extension(
  7466. sqlite3 *db, /* Load the extension into this database connection */
  7467. const char *zFile, /* Name of the shared library containing extension */
  7468. const char *zProc, /* Entry point. Derived from zFile if 0 */
  7469. char **pzErrMsg /* Put error message here if not 0 */
  7470. );
  7471. /*
  7472. ** CAPI3REF: Enable Or Disable Extension Loading
  7473. ** METHOD: sqlite3
  7474. **
  7475. ** ^So as not to open security holes in older applications that are
  7476. ** unprepared to deal with [extension loading], and as a means of disabling
  7477. ** [extension loading] while evaluating user-entered SQL, the following API
  7478. ** is provided to turn the [sqlite3_load_extension()] mechanism on and off.
  7479. **
  7480. ** ^Extension loading is off by default.
  7481. ** ^Call the sqlite3_enable_load_extension() routine with onoff==1
  7482. ** to turn extension loading on and call it with onoff==0 to turn
  7483. ** it back off again.
  7484. **
  7485. ** ^This interface enables or disables both the C-API
  7486. ** [sqlite3_load_extension()] and the SQL function [load_extension()].
  7487. ** ^(Use [sqlite3_db_config](db,[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION],..)
  7488. ** to enable or disable only the C-API.)^
  7489. **
  7490. ** <b>Security warning:</b> It is recommended that extension loading
  7491. ** be enabled using the [SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION] method
  7492. ** rather than this interface, so the [load_extension()] SQL function
  7493. ** remains disabled. This will prevent SQL injections from giving attackers
  7494. ** access to extension loading capabilities.
  7495. */
  7496. SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
  7497. /*
  7498. ** CAPI3REF: Automatically Load Statically Linked Extensions
  7499. **
  7500. ** ^This interface causes the xEntryPoint() function to be invoked for
  7501. ** each new [database connection] that is created. The idea here is that
  7502. ** xEntryPoint() is the entry point for a statically linked [SQLite extension]
  7503. ** that is to be automatically loaded into all new database connections.
  7504. **
  7505. ** ^(Even though the function prototype shows that xEntryPoint() takes
  7506. ** no arguments and returns void, SQLite invokes xEntryPoint() with three
  7507. ** arguments and expects an integer result as if the signature of the
  7508. ** entry point where as follows:
  7509. **
  7510. ** <blockquote><pre>
  7511. ** &nbsp; int xEntryPoint(
  7512. ** &nbsp; sqlite3 *db,
  7513. ** &nbsp; const char **pzErrMsg,
  7514. ** &nbsp; const struct sqlite3_api_routines *pThunk
  7515. ** &nbsp; );
  7516. ** </pre></blockquote>)^
  7517. **
  7518. ** If the xEntryPoint routine encounters an error, it should make *pzErrMsg
  7519. ** point to an appropriate error message (obtained from [sqlite3_mprintf()])
  7520. ** and return an appropriate [error code]. ^SQLite ensures that *pzErrMsg
  7521. ** is NULL before calling the xEntryPoint(). ^SQLite will invoke
  7522. ** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns. ^If any
  7523. ** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()],
  7524. ** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail.
  7525. **
  7526. ** ^Calling sqlite3_auto_extension(X) with an entry point X that is already
  7527. ** on the list of automatic extensions is a harmless no-op. ^No entry point
  7528. ** will be called more than once for each database connection that is opened.
  7529. **
  7530. ** See also: [sqlite3_reset_auto_extension()]
  7531. ** and [sqlite3_cancel_auto_extension()]
  7532. */
  7533. SQLITE_API int sqlite3_auto_extension(void(*xEntryPoint)(void));
  7534. /*
  7535. ** CAPI3REF: Cancel Automatic Extension Loading
  7536. **
  7537. ** ^The [sqlite3_cancel_auto_extension(X)] interface unregisters the
  7538. ** initialization routine X that was registered using a prior call to
  7539. ** [sqlite3_auto_extension(X)]. ^The [sqlite3_cancel_auto_extension(X)]
  7540. ** routine returns 1 if initialization routine X was successfully
  7541. ** unregistered and it returns 0 if X was not on the list of initialization
  7542. ** routines.
  7543. */
  7544. SQLITE_API int sqlite3_cancel_auto_extension(void(*xEntryPoint)(void));
  7545. /*
  7546. ** CAPI3REF: Reset Automatic Extension Loading
  7547. **
  7548. ** ^This interface disables all automatic extensions previously
  7549. ** registered using [sqlite3_auto_extension()].
  7550. */
  7551. SQLITE_API void sqlite3_reset_auto_extension(void);
  7552. /*
  7553. ** The interface to the virtual-table mechanism is currently considered
  7554. ** to be experimental. The interface might change in incompatible ways.
  7555. ** If this is a problem for you, do not use the interface at this time.
  7556. **
  7557. ** When the virtual-table mechanism stabilizes, we will declare the
  7558. ** interface fixed, support it indefinitely, and remove this comment.
  7559. */
  7560. /*
  7561. ** Structures used by the virtual table interface
  7562. */
  7563. typedef struct sqlite3_vtab sqlite3_vtab;
  7564. typedef struct sqlite3_index_info sqlite3_index_info;
  7565. typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
  7566. typedef struct sqlite3_module sqlite3_module;
  7567. /*
  7568. ** CAPI3REF: Virtual Table Object
  7569. ** KEYWORDS: sqlite3_module {virtual table module}
  7570. **
  7571. ** This structure, sometimes called a "virtual table module",
  7572. ** defines the implementation of a [virtual table].
  7573. ** This structure consists mostly of methods for the module.
  7574. **
  7575. ** ^A virtual table module is created by filling in a persistent
  7576. ** instance of this structure and passing a pointer to that instance
  7577. ** to [sqlite3_create_module()] or [sqlite3_create_module_v2()].
  7578. ** ^The registration remains valid until it is replaced by a different
  7579. ** module or until the [database connection] closes. The content
  7580. ** of this structure must not change while it is registered with
  7581. ** any database connection.
  7582. */
  7583. struct sqlite3_module {
  7584. int iVersion;
  7585. int (*xCreate)(sqlite3*, void *pAux,
  7586. int argc, const char *const*argv,
  7587. sqlite3_vtab **ppVTab, char**);
  7588. int (*xConnect)(sqlite3*, void *pAux,
  7589. int argc, const char *const*argv,
  7590. sqlite3_vtab **ppVTab, char**);
  7591. int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
  7592. int (*xDisconnect)(sqlite3_vtab *pVTab);
  7593. int (*xDestroy)(sqlite3_vtab *pVTab);
  7594. int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
  7595. int (*xClose)(sqlite3_vtab_cursor*);
  7596. int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
  7597. int argc, sqlite3_value **argv);
  7598. int (*xNext)(sqlite3_vtab_cursor*);
  7599. int (*xEof)(sqlite3_vtab_cursor*);
  7600. int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
  7601. int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
  7602. int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
  7603. int (*xBegin)(sqlite3_vtab *pVTab);
  7604. int (*xSync)(sqlite3_vtab *pVTab);
  7605. int (*xCommit)(sqlite3_vtab *pVTab);
  7606. int (*xRollback)(sqlite3_vtab *pVTab);
  7607. int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
  7608. void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
  7609. void **ppArg);
  7610. int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
  7611. /* The methods above are in version 1 of the sqlite_module object. Those
  7612. ** below are for version 2 and greater. */
  7613. int (*xSavepoint)(sqlite3_vtab *pVTab, int);
  7614. int (*xRelease)(sqlite3_vtab *pVTab, int);
  7615. int (*xRollbackTo)(sqlite3_vtab *pVTab, int);
  7616. /* The methods above are in versions 1 and 2 of the sqlite_module object.
  7617. ** Those below are for version 3 and greater. */
  7618. int (*xShadowName)(const char*);
  7619. };
  7620. /*
  7621. ** CAPI3REF: Virtual Table Indexing Information
  7622. ** KEYWORDS: sqlite3_index_info
  7623. **
  7624. ** The sqlite3_index_info structure and its substructures is used as part
  7625. ** of the [virtual table] interface to
  7626. ** pass information into and receive the reply from the [xBestIndex]
  7627. ** method of a [virtual table module]. The fields under **Inputs** are the
  7628. ** inputs to xBestIndex and are read-only. xBestIndex inserts its
  7629. ** results into the **Outputs** fields.
  7630. **
  7631. ** ^(The aConstraint[] array records WHERE clause constraints of the form:
  7632. **
  7633. ** <blockquote>column OP expr</blockquote>
  7634. **
  7635. ** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.)^ ^(The particular operator is
  7636. ** stored in aConstraint[].op using one of the
  7637. ** [SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_ values].)^
  7638. ** ^(The index of the column is stored in
  7639. ** aConstraint[].iColumn.)^ ^(aConstraint[].usable is TRUE if the
  7640. ** expr on the right-hand side can be evaluated (and thus the constraint
  7641. ** is usable) and false if it cannot.)^
  7642. **
  7643. ** ^The optimizer automatically inverts terms of the form "expr OP column"
  7644. ** and makes other simplifications to the WHERE clause in an attempt to
  7645. ** get as many WHERE clause terms into the form shown above as possible.
  7646. ** ^The aConstraint[] array only reports WHERE clause terms that are
  7647. ** relevant to the particular virtual table being queried.
  7648. **
  7649. ** ^Information about the ORDER BY clause is stored in aOrderBy[].
  7650. ** ^Each term of aOrderBy records a column of the ORDER BY clause.
  7651. **
  7652. ** The colUsed field indicates which columns of the virtual table may be
  7653. ** required by the current scan. Virtual table columns are numbered from
  7654. ** zero in the order in which they appear within the CREATE TABLE statement
  7655. ** passed to sqlite3_declare_vtab(). For the first 63 columns (columns 0-62),
  7656. ** the corresponding bit is set within the colUsed mask if the column may be
  7657. ** required by SQLite. If the table has at least 64 columns and any column
  7658. ** to the right of the first 63 is required, then bit 63 of colUsed is also
  7659. ** set. In other words, column iCol may be required if the expression
  7660. ** (colUsed & ((sqlite3_uint64)1 << (iCol>=63 ? 63 : iCol))) evaluates to
  7661. ** non-zero.
  7662. **
  7663. ** The [xBestIndex] method must fill aConstraintUsage[] with information
  7664. ** about what parameters to pass to xFilter. ^If argvIndex>0 then
  7665. ** the right-hand side of the corresponding aConstraint[] is evaluated
  7666. ** and becomes the argvIndex-th entry in argv. ^(If aConstraintUsage[].omit
  7667. ** is true, then the constraint is assumed to be fully handled by the
  7668. ** virtual table and might not be checked again by the byte code.)^ ^(The
  7669. ** aConstraintUsage[].omit flag is an optimization hint. When the omit flag
  7670. ** is left in its default setting of false, the constraint will always be
  7671. ** checked separately in byte code. If the omit flag is change to true, then
  7672. ** the constraint may or may not be checked in byte code. In other words,
  7673. ** when the omit flag is true there is no guarantee that the constraint will
  7674. ** not be checked again using byte code.)^
  7675. **
  7676. ** ^The idxNum and idxPtr values are recorded and passed into the
  7677. ** [xFilter] method.
  7678. ** ^[sqlite3_free()] is used to free idxPtr if and only if
  7679. ** needToFreeIdxPtr is true.
  7680. **
  7681. ** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in
  7682. ** the correct order to satisfy the ORDER BY clause so that no separate
  7683. ** sorting step is required.
  7684. **
  7685. ** ^The estimatedCost value is an estimate of the cost of a particular
  7686. ** strategy. A cost of N indicates that the cost of the strategy is similar
  7687. ** to a linear scan of an SQLite table with N rows. A cost of log(N)
  7688. ** indicates that the expense of the operation is similar to that of a
  7689. ** binary search on a unique indexed field of an SQLite table with N rows.
  7690. **
  7691. ** ^The estimatedRows value is an estimate of the number of rows that
  7692. ** will be returned by the strategy.
  7693. **
  7694. ** The xBestIndex method may optionally populate the idxFlags field with a
  7695. ** mask of SQLITE_INDEX_SCAN_* flags. Currently there is only one such flag -
  7696. ** SQLITE_INDEX_SCAN_UNIQUE. If the xBestIndex method sets this flag, SQLite
  7697. ** assumes that the strategy may visit at most one row.
  7698. **
  7699. ** Additionally, if xBestIndex sets the SQLITE_INDEX_SCAN_UNIQUE flag, then
  7700. ** SQLite also assumes that if a call to the xUpdate() method is made as
  7701. ** part of the same statement to delete or update a virtual table row and the
  7702. ** implementation returns SQLITE_CONSTRAINT, then there is no need to rollback
  7703. ** any database changes. In other words, if the xUpdate() returns
  7704. ** SQLITE_CONSTRAINT, the database contents must be exactly as they were
  7705. ** before xUpdate was called. By contrast, if SQLITE_INDEX_SCAN_UNIQUE is not
  7706. ** set and xUpdate returns SQLITE_CONSTRAINT, any database changes made by
  7707. ** the xUpdate method are automatically rolled back by SQLite.
  7708. **
  7709. ** IMPORTANT: The estimatedRows field was added to the sqlite3_index_info
  7710. ** structure for SQLite [version 3.8.2] ([dateof:3.8.2]).
  7711. ** If a virtual table extension is
  7712. ** used with an SQLite version earlier than 3.8.2, the results of attempting
  7713. ** to read or write the estimatedRows field are undefined (but are likely
  7714. ** to include crashing the application). The estimatedRows field should
  7715. ** therefore only be used if [sqlite3_libversion_number()] returns a
  7716. ** value greater than or equal to 3008002. Similarly, the idxFlags field
  7717. ** was added for [version 3.9.0] ([dateof:3.9.0]).
  7718. ** It may therefore only be used if
  7719. ** sqlite3_libversion_number() returns a value greater than or equal to
  7720. ** 3009000.
  7721. */
  7722. struct sqlite3_index_info {
  7723. /* Inputs */
  7724. int nConstraint; /* Number of entries in aConstraint */
  7725. struct sqlite3_index_constraint {
  7726. int iColumn; /* Column constrained. -1 for ROWID */
  7727. unsigned char op; /* Constraint operator */
  7728. unsigned char usable; /* True if this constraint is usable */
  7729. int iTermOffset; /* Used internally - xBestIndex should ignore */
  7730. } *aConstraint; /* Table of WHERE clause constraints */
  7731. int nOrderBy; /* Number of terms in the ORDER BY clause */
  7732. struct sqlite3_index_orderby {
  7733. int iColumn; /* Column number */
  7734. unsigned char desc; /* True for DESC. False for ASC. */
  7735. } *aOrderBy; /* The ORDER BY clause */
  7736. /* Outputs */
  7737. struct sqlite3_index_constraint_usage {
  7738. int argvIndex; /* if >0, constraint is part of argv to xFilter */
  7739. unsigned char omit; /* Do not code a test for this constraint */
  7740. } *aConstraintUsage;
  7741. int idxNum; /* Number used to identify the index */
  7742. char *idxStr; /* String, possibly obtained from sqlite3_malloc */
  7743. int needToFreeIdxStr; /* Free idxStr using sqlite3_free() if true */
  7744. int orderByConsumed; /* True if output is already ordered */
  7745. double estimatedCost; /* Estimated cost of using this index */
  7746. /* Fields below are only available in SQLite 3.8.2 and later */
  7747. sqlite3_int64 estimatedRows; /* Estimated number of rows returned */
  7748. /* Fields below are only available in SQLite 3.9.0 and later */
  7749. int idxFlags; /* Mask of SQLITE_INDEX_SCAN_* flags */
  7750. /* Fields below are only available in SQLite 3.10.0 and later */
  7751. sqlite3_uint64 colUsed; /* Input: Mask of columns used by statement */
  7752. };
  7753. /*
  7754. ** CAPI3REF: Virtual Table Scan Flags
  7755. **
  7756. ** Virtual table implementations are allowed to set the
  7757. ** [sqlite3_index_info].idxFlags field to some combination of
  7758. ** these bits.
  7759. */
  7760. #define SQLITE_INDEX_SCAN_UNIQUE 1 /* Scan visits at most 1 row */
  7761. /*
  7762. ** CAPI3REF: Virtual Table Constraint Operator Codes
  7763. **
  7764. ** These macros define the allowed values for the
  7765. ** [sqlite3_index_info].aConstraint[].op field. Each value represents
  7766. ** an operator that is part of a constraint term in the wHERE clause of
  7767. ** a query that uses a [virtual table].
  7768. */
  7769. #define SQLITE_INDEX_CONSTRAINT_EQ 2
  7770. #define SQLITE_INDEX_CONSTRAINT_GT 4
  7771. #define SQLITE_INDEX_CONSTRAINT_LE 8
  7772. #define SQLITE_INDEX_CONSTRAINT_LT 16
  7773. #define SQLITE_INDEX_CONSTRAINT_GE 32
  7774. #define SQLITE_INDEX_CONSTRAINT_MATCH 64
  7775. #define SQLITE_INDEX_CONSTRAINT_LIKE 65
  7776. #define SQLITE_INDEX_CONSTRAINT_GLOB 66
  7777. #define SQLITE_INDEX_CONSTRAINT_REGEXP 67
  7778. #define SQLITE_INDEX_CONSTRAINT_NE 68
  7779. #define SQLITE_INDEX_CONSTRAINT_ISNOT 69
  7780. #define SQLITE_INDEX_CONSTRAINT_ISNOTNULL 70
  7781. #define SQLITE_INDEX_CONSTRAINT_ISNULL 71
  7782. #define SQLITE_INDEX_CONSTRAINT_IS 72
  7783. #define SQLITE_INDEX_CONSTRAINT_FUNCTION 150
  7784. /*
  7785. ** CAPI3REF: Register A Virtual Table Implementation
  7786. ** METHOD: sqlite3
  7787. **
  7788. ** ^These routines are used to register a new [virtual table module] name.
  7789. ** ^Module names must be registered before
  7790. ** creating a new [virtual table] using the module and before using a
  7791. ** preexisting [virtual table] for the module.
  7792. **
  7793. ** ^The module name is registered on the [database connection] specified
  7794. ** by the first parameter. ^The name of the module is given by the
  7795. ** second parameter. ^The third parameter is a pointer to
  7796. ** the implementation of the [virtual table module]. ^The fourth
  7797. ** parameter is an arbitrary client data pointer that is passed through
  7798. ** into the [xCreate] and [xConnect] methods of the virtual table module
  7799. ** when a new virtual table is be being created or reinitialized.
  7800. **
  7801. ** ^The sqlite3_create_module_v2() interface has a fifth parameter which
  7802. ** is a pointer to a destructor for the pClientData. ^SQLite will
  7803. ** invoke the destructor function (if it is not NULL) when SQLite
  7804. ** no longer needs the pClientData pointer. ^The destructor will also
  7805. ** be invoked if the call to sqlite3_create_module_v2() fails.
  7806. ** ^The sqlite3_create_module()
  7807. ** interface is equivalent to sqlite3_create_module_v2() with a NULL
  7808. ** destructor.
  7809. **
  7810. ** ^If the third parameter (the pointer to the sqlite3_module object) is
  7811. ** NULL then no new module is create and any existing modules with the
  7812. ** same name are dropped.
  7813. **
  7814. ** See also: [sqlite3_drop_modules()]
  7815. */
  7816. SQLITE_API int sqlite3_create_module(
  7817. sqlite3 *db, /* SQLite connection to register module with */
  7818. const char *zName, /* Name of the module */
  7819. const sqlite3_module *p, /* Methods for the module */
  7820. void *pClientData /* Client data for xCreate/xConnect */
  7821. );
  7822. SQLITE_API int sqlite3_create_module_v2(
  7823. sqlite3 *db, /* SQLite connection to register module with */
  7824. const char *zName, /* Name of the module */
  7825. const sqlite3_module *p, /* Methods for the module */
  7826. void *pClientData, /* Client data for xCreate/xConnect */
  7827. void(*xDestroy)(void*) /* Module destructor function */
  7828. );
  7829. /*
  7830. ** CAPI3REF: Remove Unnecessary Virtual Table Implementations
  7831. ** METHOD: sqlite3
  7832. **
  7833. ** ^The sqlite3_drop_modules(D,L) interface removes all virtual
  7834. ** table modules from database connection D except those named on list L.
  7835. ** The L parameter must be either NULL or a pointer to an array of pointers
  7836. ** to strings where the array is terminated by a single NULL pointer.
  7837. ** ^If the L parameter is NULL, then all virtual table modules are removed.
  7838. **
  7839. ** See also: [sqlite3_create_module()]
  7840. */
  7841. SQLITE_API int sqlite3_drop_modules(
  7842. sqlite3 *db, /* Remove modules from this connection */
  7843. const char **azKeep /* Except, do not remove the ones named here */
  7844. );
  7845. /*
  7846. ** CAPI3REF: Virtual Table Instance Object
  7847. ** KEYWORDS: sqlite3_vtab
  7848. **
  7849. ** Every [virtual table module] implementation uses a subclass
  7850. ** of this object to describe a particular instance
  7851. ** of the [virtual table]. Each subclass will
  7852. ** be tailored to the specific needs of the module implementation.
  7853. ** The purpose of this superclass is to define certain fields that are
  7854. ** common to all module implementations.
  7855. **
  7856. ** ^Virtual tables methods can set an error message by assigning a
  7857. ** string obtained from [sqlite3_mprintf()] to zErrMsg. The method should
  7858. ** take care that any prior string is freed by a call to [sqlite3_free()]
  7859. ** prior to assigning a new string to zErrMsg. ^After the error message
  7860. ** is delivered up to the client application, the string will be automatically
  7861. ** freed by sqlite3_free() and the zErrMsg field will be zeroed.
  7862. */
  7863. struct sqlite3_vtab {
  7864. const sqlite3_module *pModule; /* The module for this virtual table */
  7865. int nRef; /* Number of open cursors */
  7866. char *zErrMsg; /* Error message from sqlite3_mprintf() */
  7867. /* Virtual table implementations will typically add additional fields */
  7868. };
  7869. /*
  7870. ** CAPI3REF: Virtual Table Cursor Object
  7871. ** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}
  7872. **
  7873. ** Every [virtual table module] implementation uses a subclass of the
  7874. ** following structure to describe cursors that point into the
  7875. ** [virtual table] and are used
  7876. ** to loop through the virtual table. Cursors are created using the
  7877. ** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed
  7878. ** by the [sqlite3_module.xClose | xClose] method. Cursors are used
  7879. ** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods
  7880. ** of the module. Each module implementation will define
  7881. ** the content of a cursor structure to suit its own needs.
  7882. **
  7883. ** This superclass exists in order to define fields of the cursor that
  7884. ** are common to all implementations.
  7885. */
  7886. struct sqlite3_vtab_cursor {
  7887. sqlite3_vtab *pVtab; /* Virtual table of this cursor */
  7888. /* Virtual table implementations will typically add additional fields */
  7889. };
  7890. /*
  7891. ** CAPI3REF: Declare The Schema Of A Virtual Table
  7892. **
  7893. ** ^The [xCreate] and [xConnect] methods of a
  7894. ** [virtual table module] call this interface
  7895. ** to declare the format (the names and datatypes of the columns) of
  7896. ** the virtual tables they implement.
  7897. */
  7898. SQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zSQL);
  7899. /*
  7900. ** CAPI3REF: Overload A Function For A Virtual Table
  7901. ** METHOD: sqlite3
  7902. **
  7903. ** ^(Virtual tables can provide alternative implementations of functions
  7904. ** using the [xFindFunction] method of the [virtual table module].
  7905. ** But global versions of those functions
  7906. ** must exist in order to be overloaded.)^
  7907. **
  7908. ** ^(This API makes sure a global version of a function with a particular
  7909. ** name and number of parameters exists. If no such function exists
  7910. ** before this API is called, a new function is created.)^ ^The implementation
  7911. ** of the new function always causes an exception to be thrown. So
  7912. ** the new function is not good for anything by itself. Its only
  7913. ** purpose is to be a placeholder function that can be overloaded
  7914. ** by a [virtual table].
  7915. */
  7916. SQLITE_API int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
  7917. /*
  7918. ** The interface to the virtual-table mechanism defined above (back up
  7919. ** to a comment remarkably similar to this one) is currently considered
  7920. ** to be experimental. The interface might change in incompatible ways.
  7921. ** If this is a problem for you, do not use the interface at this time.
  7922. **
  7923. ** When the virtual-table mechanism stabilizes, we will declare the
  7924. ** interface fixed, support it indefinitely, and remove this comment.
  7925. */
  7926. /*
  7927. ** CAPI3REF: A Handle To An Open BLOB
  7928. ** KEYWORDS: {BLOB handle} {BLOB handles}
  7929. **
  7930. ** An instance of this object represents an open BLOB on which
  7931. ** [sqlite3_blob_open | incremental BLOB I/O] can be performed.
  7932. ** ^Objects of this type are created by [sqlite3_blob_open()]
  7933. ** and destroyed by [sqlite3_blob_close()].
  7934. ** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
  7935. ** can be used to read or write small subsections of the BLOB.
  7936. ** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes.
  7937. */
  7938. typedef struct sqlite3_blob sqlite3_blob;
  7939. /*
  7940. ** CAPI3REF: Open A BLOB For Incremental I/O
  7941. ** METHOD: sqlite3
  7942. ** CONSTRUCTOR: sqlite3_blob
  7943. **
  7944. ** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located
  7945. ** in row iRow, column zColumn, table zTable in database zDb;
  7946. ** in other words, the same BLOB that would be selected by:
  7947. **
  7948. ** <pre>
  7949. ** SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
  7950. ** </pre>)^
  7951. **
  7952. ** ^(Parameter zDb is not the filename that contains the database, but
  7953. ** rather the symbolic name of the database. For attached databases, this is
  7954. ** the name that appears after the AS keyword in the [ATTACH] statement.
  7955. ** For the main database file, the database name is "main". For TEMP
  7956. ** tables, the database name is "temp".)^
  7957. **
  7958. ** ^If the flags parameter is non-zero, then the BLOB is opened for read
  7959. ** and write access. ^If the flags parameter is zero, the BLOB is opened for
  7960. ** read-only access.
  7961. **
  7962. ** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is stored
  7963. ** in *ppBlob. Otherwise an [error code] is returned and, unless the error
  7964. ** code is SQLITE_MISUSE, *ppBlob is set to NULL.)^ ^This means that, provided
  7965. ** the API is not misused, it is always safe to call [sqlite3_blob_close()]
  7966. ** on *ppBlob after this function it returns.
  7967. **
  7968. ** This function fails with SQLITE_ERROR if any of the following are true:
  7969. ** <ul>
  7970. ** <li> ^(Database zDb does not exist)^,
  7971. ** <li> ^(Table zTable does not exist within database zDb)^,
  7972. ** <li> ^(Table zTable is a WITHOUT ROWID table)^,
  7973. ** <li> ^(Column zColumn does not exist)^,
  7974. ** <li> ^(Row iRow is not present in the table)^,
  7975. ** <li> ^(The specified column of row iRow contains a value that is not
  7976. ** a TEXT or BLOB value)^,
  7977. ** <li> ^(Column zColumn is part of an index, PRIMARY KEY or UNIQUE
  7978. ** constraint and the blob is being opened for read/write access)^,
  7979. ** <li> ^([foreign key constraints | Foreign key constraints] are enabled,
  7980. ** column zColumn is part of a [child key] definition and the blob is
  7981. ** being opened for read/write access)^.
  7982. ** </ul>
  7983. **
  7984. ** ^Unless it returns SQLITE_MISUSE, this function sets the
  7985. ** [database connection] error code and message accessible via
  7986. ** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions.
  7987. **
  7988. ** A BLOB referenced by sqlite3_blob_open() may be read using the
  7989. ** [sqlite3_blob_read()] interface and modified by using
  7990. ** [sqlite3_blob_write()]. The [BLOB handle] can be moved to a
  7991. ** different row of the same table using the [sqlite3_blob_reopen()]
  7992. ** interface. However, the column, table, or database of a [BLOB handle]
  7993. ** cannot be changed after the [BLOB handle] is opened.
  7994. **
  7995. ** ^(If the row that a BLOB handle points to is modified by an
  7996. ** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects
  7997. ** then the BLOB handle is marked as "expired".
  7998. ** This is true if any column of the row is changed, even a column
  7999. ** other than the one the BLOB handle is open on.)^
  8000. ** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for
  8001. ** an expired BLOB handle fail with a return code of [SQLITE_ABORT].
  8002. ** ^(Changes written into a BLOB prior to the BLOB expiring are not
  8003. ** rolled back by the expiration of the BLOB. Such changes will eventually
  8004. ** commit if the transaction continues to completion.)^
  8005. **
  8006. ** ^Use the [sqlite3_blob_bytes()] interface to determine the size of
  8007. ** the opened blob. ^The size of a blob may not be changed by this
  8008. ** interface. Use the [UPDATE] SQL command to change the size of a
  8009. ** blob.
  8010. **
  8011. ** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces
  8012. ** and the built-in [zeroblob] SQL function may be used to create a
  8013. ** zero-filled blob to read or write using the incremental-blob interface.
  8014. **
  8015. ** To avoid a resource leak, every open [BLOB handle] should eventually
  8016. ** be released by a call to [sqlite3_blob_close()].
  8017. **
  8018. ** See also: [sqlite3_blob_close()],
  8019. ** [sqlite3_blob_reopen()], [sqlite3_blob_read()],
  8020. ** [sqlite3_blob_bytes()], [sqlite3_blob_write()].
  8021. */
  8022. SQLITE_API int sqlite3_blob_open(
  8023. sqlite3*,
  8024. const char *zDb,
  8025. const char *zTable,
  8026. const char *zColumn,
  8027. sqlite3_int64 iRow,
  8028. int flags,
  8029. sqlite3_blob **ppBlob
  8030. );
  8031. /*
  8032. ** CAPI3REF: Move a BLOB Handle to a New Row
  8033. ** METHOD: sqlite3_blob
  8034. **
  8035. ** ^This function is used to move an existing [BLOB handle] so that it points
  8036. ** to a different row of the same database table. ^The new row is identified
  8037. ** by the rowid value passed as the second argument. Only the row can be
  8038. ** changed. ^The database, table and column on which the blob handle is open
  8039. ** remain the same. Moving an existing [BLOB handle] to a new row is
  8040. ** faster than closing the existing handle and opening a new one.
  8041. **
  8042. ** ^(The new row must meet the same criteria as for [sqlite3_blob_open()] -
  8043. ** it must exist and there must be either a blob or text value stored in
  8044. ** the nominated column.)^ ^If the new row is not present in the table, or if
  8045. ** it does not contain a blob or text value, or if another error occurs, an
  8046. ** SQLite error code is returned and the blob handle is considered aborted.
  8047. ** ^All subsequent calls to [sqlite3_blob_read()], [sqlite3_blob_write()] or
  8048. ** [sqlite3_blob_reopen()] on an aborted blob handle immediately return
  8049. ** SQLITE_ABORT. ^Calling [sqlite3_blob_bytes()] on an aborted blob handle
  8050. ** always returns zero.
  8051. **
  8052. ** ^This function sets the database handle error code and message.
  8053. */
  8054. SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64);
  8055. /*
  8056. ** CAPI3REF: Close A BLOB Handle
  8057. ** DESTRUCTOR: sqlite3_blob
  8058. **
  8059. ** ^This function closes an open [BLOB handle]. ^(The BLOB handle is closed
  8060. ** unconditionally. Even if this routine returns an error code, the
  8061. ** handle is still closed.)^
  8062. **
  8063. ** ^If the blob handle being closed was opened for read-write access, and if
  8064. ** the database is in auto-commit mode and there are no other open read-write
  8065. ** blob handles or active write statements, the current transaction is
  8066. ** committed. ^If an error occurs while committing the transaction, an error
  8067. ** code is returned and the transaction rolled back.
  8068. **
  8069. ** Calling this function with an argument that is not a NULL pointer or an
  8070. ** open blob handle results in undefined behaviour. ^Calling this routine
  8071. ** with a null pointer (such as would be returned by a failed call to
  8072. ** [sqlite3_blob_open()]) is a harmless no-op. ^Otherwise, if this function
  8073. ** is passed a valid open blob handle, the values returned by the
  8074. ** sqlite3_errcode() and sqlite3_errmsg() functions are set before returning.
  8075. */
  8076. SQLITE_API int sqlite3_blob_close(sqlite3_blob *);
  8077. /*
  8078. ** CAPI3REF: Return The Size Of An Open BLOB
  8079. ** METHOD: sqlite3_blob
  8080. **
  8081. ** ^Returns the size in bytes of the BLOB accessible via the
  8082. ** successfully opened [BLOB handle] in its only argument. ^The
  8083. ** incremental blob I/O routines can only read or overwriting existing
  8084. ** blob content; they cannot change the size of a blob.
  8085. **
  8086. ** This routine only works on a [BLOB handle] which has been created
  8087. ** by a prior successful call to [sqlite3_blob_open()] and which has not
  8088. ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
  8089. ** to this routine results in undefined and probably undesirable behavior.
  8090. */
  8091. SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *);
  8092. /*
  8093. ** CAPI3REF: Read Data From A BLOB Incrementally
  8094. ** METHOD: sqlite3_blob
  8095. **
  8096. ** ^(This function is used to read data from an open [BLOB handle] into a
  8097. ** caller-supplied buffer. N bytes of data are copied into buffer Z
  8098. ** from the open BLOB, starting at offset iOffset.)^
  8099. **
  8100. ** ^If offset iOffset is less than N bytes from the end of the BLOB,
  8101. ** [SQLITE_ERROR] is returned and no data is read. ^If N or iOffset is
  8102. ** less than zero, [SQLITE_ERROR] is returned and no data is read.
  8103. ** ^The size of the blob (and hence the maximum value of N+iOffset)
  8104. ** can be determined using the [sqlite3_blob_bytes()] interface.
  8105. **
  8106. ** ^An attempt to read from an expired [BLOB handle] fails with an
  8107. ** error code of [SQLITE_ABORT].
  8108. **
  8109. ** ^(On success, sqlite3_blob_read() returns SQLITE_OK.
  8110. ** Otherwise, an [error code] or an [extended error code] is returned.)^
  8111. **
  8112. ** This routine only works on a [BLOB handle] which has been created
  8113. ** by a prior successful call to [sqlite3_blob_open()] and which has not
  8114. ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
  8115. ** to this routine results in undefined and probably undesirable behavior.
  8116. **
  8117. ** See also: [sqlite3_blob_write()].
  8118. */
  8119. SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);
  8120. /*
  8121. ** CAPI3REF: Write Data Into A BLOB Incrementally
  8122. ** METHOD: sqlite3_blob
  8123. **
  8124. ** ^(This function is used to write data into an open [BLOB handle] from a
  8125. ** caller-supplied buffer. N bytes of data are copied from the buffer Z
  8126. ** into the open BLOB, starting at offset iOffset.)^
  8127. **
  8128. ** ^(On success, sqlite3_blob_write() returns SQLITE_OK.
  8129. ** Otherwise, an [error code] or an [extended error code] is returned.)^
  8130. ** ^Unless SQLITE_MISUSE is returned, this function sets the
  8131. ** [database connection] error code and message accessible via
  8132. ** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions.
  8133. **
  8134. ** ^If the [BLOB handle] passed as the first argument was not opened for
  8135. ** writing (the flags parameter to [sqlite3_blob_open()] was zero),
  8136. ** this function returns [SQLITE_READONLY].
  8137. **
  8138. ** This function may only modify the contents of the BLOB; it is
  8139. ** not possible to increase the size of a BLOB using this API.
  8140. ** ^If offset iOffset is less than N bytes from the end of the BLOB,
  8141. ** [SQLITE_ERROR] is returned and no data is written. The size of the
  8142. ** BLOB (and hence the maximum value of N+iOffset) can be determined
  8143. ** using the [sqlite3_blob_bytes()] interface. ^If N or iOffset are less
  8144. ** than zero [SQLITE_ERROR] is returned and no data is written.
  8145. **
  8146. ** ^An attempt to write to an expired [BLOB handle] fails with an
  8147. ** error code of [SQLITE_ABORT]. ^Writes to the BLOB that occurred
  8148. ** before the [BLOB handle] expired are not rolled back by the
  8149. ** expiration of the handle, though of course those changes might
  8150. ** have been overwritten by the statement that expired the BLOB handle
  8151. ** or by other independent statements.
  8152. **
  8153. ** This routine only works on a [BLOB handle] which has been created
  8154. ** by a prior successful call to [sqlite3_blob_open()] and which has not
  8155. ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
  8156. ** to this routine results in undefined and probably undesirable behavior.
  8157. **
  8158. ** See also: [sqlite3_blob_read()].
  8159. */
  8160. SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
  8161. /*
  8162. ** CAPI3REF: Virtual File System Objects
  8163. **
  8164. ** A virtual filesystem (VFS) is an [sqlite3_vfs] object
  8165. ** that SQLite uses to interact
  8166. ** with the underlying operating system. Most SQLite builds come with a
  8167. ** single default VFS that is appropriate for the host computer.
  8168. ** New VFSes can be registered and existing VFSes can be unregistered.
  8169. ** The following interfaces are provided.
  8170. **
  8171. ** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.
  8172. ** ^Names are case sensitive.
  8173. ** ^Names are zero-terminated UTF-8 strings.
  8174. ** ^If there is no match, a NULL pointer is returned.
  8175. ** ^If zVfsName is NULL then the default VFS is returned.
  8176. **
  8177. ** ^New VFSes are registered with sqlite3_vfs_register().
  8178. ** ^Each new VFS becomes the default VFS if the makeDflt flag is set.
  8179. ** ^The same VFS can be registered multiple times without injury.
  8180. ** ^To make an existing VFS into the default VFS, register it again
  8181. ** with the makeDflt flag set. If two different VFSes with the
  8182. ** same name are registered, the behavior is undefined. If a
  8183. ** VFS is registered with a name that is NULL or an empty string,
  8184. ** then the behavior is undefined.
  8185. **
  8186. ** ^Unregister a VFS with the sqlite3_vfs_unregister() interface.
  8187. ** ^(If the default VFS is unregistered, another VFS is chosen as
  8188. ** the default. The choice for the new VFS is arbitrary.)^
  8189. */
  8190. SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName);
  8191. SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
  8192. SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*);
  8193. /*
  8194. ** CAPI3REF: Mutexes
  8195. **
  8196. ** The SQLite core uses these routines for thread
  8197. ** synchronization. Though they are intended for internal
  8198. ** use by SQLite, code that links against SQLite is
  8199. ** permitted to use any of these routines.
  8200. **
  8201. ** The SQLite source code contains multiple implementations
  8202. ** of these mutex routines. An appropriate implementation
  8203. ** is selected automatically at compile-time. The following
  8204. ** implementations are available in the SQLite core:
  8205. **
  8206. ** <ul>
  8207. ** <li> SQLITE_MUTEX_PTHREADS
  8208. ** <li> SQLITE_MUTEX_W32
  8209. ** <li> SQLITE_MUTEX_NOOP
  8210. ** </ul>
  8211. **
  8212. ** The SQLITE_MUTEX_NOOP implementation is a set of routines
  8213. ** that does no real locking and is appropriate for use in
  8214. ** a single-threaded application. The SQLITE_MUTEX_PTHREADS and
  8215. ** SQLITE_MUTEX_W32 implementations are appropriate for use on Unix
  8216. ** and Windows.
  8217. **
  8218. ** If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
  8219. ** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
  8220. ** implementation is included with the library. In this case the
  8221. ** application must supply a custom mutex implementation using the
  8222. ** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function
  8223. ** before calling sqlite3_initialize() or any other public sqlite3_
  8224. ** function that calls sqlite3_initialize().
  8225. **
  8226. ** ^The sqlite3_mutex_alloc() routine allocates a new
  8227. ** mutex and returns a pointer to it. ^The sqlite3_mutex_alloc()
  8228. ** routine returns NULL if it is unable to allocate the requested
  8229. ** mutex. The argument to sqlite3_mutex_alloc() must one of these
  8230. ** integer constants:
  8231. **
  8232. ** <ul>
  8233. ** <li> SQLITE_MUTEX_FAST
  8234. ** <li> SQLITE_MUTEX_RECURSIVE
  8235. ** <li> SQLITE_MUTEX_STATIC_MASTER
  8236. ** <li> SQLITE_MUTEX_STATIC_MEM
  8237. ** <li> SQLITE_MUTEX_STATIC_OPEN
  8238. ** <li> SQLITE_MUTEX_STATIC_PRNG
  8239. ** <li> SQLITE_MUTEX_STATIC_LRU
  8240. ** <li> SQLITE_MUTEX_STATIC_PMEM
  8241. ** <li> SQLITE_MUTEX_STATIC_APP1
  8242. ** <li> SQLITE_MUTEX_STATIC_APP2
  8243. ** <li> SQLITE_MUTEX_STATIC_APP3
  8244. ** <li> SQLITE_MUTEX_STATIC_VFS1
  8245. ** <li> SQLITE_MUTEX_STATIC_VFS2
  8246. ** <li> SQLITE_MUTEX_STATIC_VFS3
  8247. ** </ul>
  8248. **
  8249. ** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE)
  8250. ** cause sqlite3_mutex_alloc() to create
  8251. ** a new mutex. ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
  8252. ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
  8253. ** The mutex implementation does not need to make a distinction
  8254. ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
  8255. ** not want to. SQLite will only request a recursive mutex in
  8256. ** cases where it really needs one. If a faster non-recursive mutex
  8257. ** implementation is available on the host platform, the mutex subsystem
  8258. ** might return such a mutex in response to SQLITE_MUTEX_FAST.
  8259. **
  8260. ** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other
  8261. ** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return
  8262. ** a pointer to a static preexisting mutex. ^Nine static mutexes are
  8263. ** used by the current version of SQLite. Future versions of SQLite
  8264. ** may add additional static mutexes. Static mutexes are for internal
  8265. ** use by SQLite only. Applications that use SQLite mutexes should
  8266. ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
  8267. ** SQLITE_MUTEX_RECURSIVE.
  8268. **
  8269. ** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
  8270. ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
  8271. ** returns a different mutex on every call. ^For the static
  8272. ** mutex types, the same mutex is returned on every call that has
  8273. ** the same type number.
  8274. **
  8275. ** ^The sqlite3_mutex_free() routine deallocates a previously
  8276. ** allocated dynamic mutex. Attempting to deallocate a static
  8277. ** mutex results in undefined behavior.
  8278. **
  8279. ** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  8280. ** to enter a mutex. ^If another thread is already within the mutex,
  8281. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  8282. ** SQLITE_BUSY. ^The sqlite3_mutex_try() interface returns [SQLITE_OK]
  8283. ** upon successful entry. ^(Mutexes created using
  8284. ** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
  8285. ** In such cases, the
  8286. ** mutex must be exited an equal number of times before another thread
  8287. ** can enter.)^ If the same thread tries to enter any mutex other
  8288. ** than an SQLITE_MUTEX_RECURSIVE more than once, the behavior is undefined.
  8289. **
  8290. ** ^(Some systems (for example, Windows 95) do not support the operation
  8291. ** implemented by sqlite3_mutex_try(). On those systems, sqlite3_mutex_try()
  8292. ** will always return SQLITE_BUSY. The SQLite core only ever uses
  8293. ** sqlite3_mutex_try() as an optimization so this is acceptable
  8294. ** behavior.)^
  8295. **
  8296. ** ^The sqlite3_mutex_leave() routine exits a mutex that was
  8297. ** previously entered by the same thread. The behavior
  8298. ** is undefined if the mutex is not currently entered by the
  8299. ** calling thread or is not currently allocated.
  8300. **
  8301. ** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or
  8302. ** sqlite3_mutex_leave() is a NULL pointer, then all three routines
  8303. ** behave as no-ops.
  8304. **
  8305. ** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
  8306. */
  8307. SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int);
  8308. SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*);
  8309. SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*);
  8310. SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*);
  8311. SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*);
  8312. /*
  8313. ** CAPI3REF: Mutex Methods Object
  8314. **
  8315. ** An instance of this structure defines the low-level routines
  8316. ** used to allocate and use mutexes.
  8317. **
  8318. ** Usually, the default mutex implementations provided by SQLite are
  8319. ** sufficient, however the application has the option of substituting a custom
  8320. ** implementation for specialized deployments or systems for which SQLite
  8321. ** does not provide a suitable implementation. In this case, the application
  8322. ** creates and populates an instance of this structure to pass
  8323. ** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option.
  8324. ** Additionally, an instance of this structure can be used as an
  8325. ** output variable when querying the system for the current mutex
  8326. ** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
  8327. **
  8328. ** ^The xMutexInit method defined by this structure is invoked as
  8329. ** part of system initialization by the sqlite3_initialize() function.
  8330. ** ^The xMutexInit routine is called by SQLite exactly once for each
  8331. ** effective call to [sqlite3_initialize()].
  8332. **
  8333. ** ^The xMutexEnd method defined by this structure is invoked as
  8334. ** part of system shutdown by the sqlite3_shutdown() function. The
  8335. ** implementation of this method is expected to release all outstanding
  8336. ** resources obtained by the mutex methods implementation, especially
  8337. ** those obtained by the xMutexInit method. ^The xMutexEnd()
  8338. ** interface is invoked exactly once for each call to [sqlite3_shutdown()].
  8339. **
  8340. ** ^(The remaining seven methods defined by this structure (xMutexAlloc,
  8341. ** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and
  8342. ** xMutexNotheld) implement the following interfaces (respectively):
  8343. **
  8344. ** <ul>
  8345. ** <li> [sqlite3_mutex_alloc()] </li>
  8346. ** <li> [sqlite3_mutex_free()] </li>
  8347. ** <li> [sqlite3_mutex_enter()] </li>
  8348. ** <li> [sqlite3_mutex_try()] </li>
  8349. ** <li> [sqlite3_mutex_leave()] </li>
  8350. ** <li> [sqlite3_mutex_held()] </li>
  8351. ** <li> [sqlite3_mutex_notheld()] </li>
  8352. ** </ul>)^
  8353. **
  8354. ** The only difference is that the public sqlite3_XXX functions enumerated
  8355. ** above silently ignore any invocations that pass a NULL pointer instead
  8356. ** of a valid mutex handle. The implementations of the methods defined
  8357. ** by this structure are not required to handle this case. The results
  8358. ** of passing a NULL pointer instead of a valid mutex handle are undefined
  8359. ** (i.e. it is acceptable to provide an implementation that segfaults if
  8360. ** it is passed a NULL pointer).
  8361. **
  8362. ** The xMutexInit() method must be threadsafe. It must be harmless to
  8363. ** invoke xMutexInit() multiple times within the same process and without
  8364. ** intervening calls to xMutexEnd(). Second and subsequent calls to
  8365. ** xMutexInit() must be no-ops.
  8366. **
  8367. ** xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()]
  8368. ** and its associates). Similarly, xMutexAlloc() must not use SQLite memory
  8369. ** allocation for a static mutex. ^However xMutexAlloc() may use SQLite
  8370. ** memory allocation for a fast or recursive mutex.
  8371. **
  8372. ** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is
  8373. ** called, but only if the prior call to xMutexInit returned SQLITE_OK.
  8374. ** If xMutexInit fails in any way, it is expected to clean up after itself
  8375. ** prior to returning.
  8376. */
  8377. typedef struct sqlite3_mutex_methods sqlite3_mutex_methods;
  8378. struct sqlite3_mutex_methods {
  8379. int (*xMutexInit)(void);
  8380. int (*xMutexEnd)(void);
  8381. sqlite3_mutex *(*xMutexAlloc)(int);
  8382. void (*xMutexFree)(sqlite3_mutex *);
  8383. void (*xMutexEnter)(sqlite3_mutex *);
  8384. int (*xMutexTry)(sqlite3_mutex *);
  8385. void (*xMutexLeave)(sqlite3_mutex *);
  8386. int (*xMutexHeld)(sqlite3_mutex *);
  8387. int (*xMutexNotheld)(sqlite3_mutex *);
  8388. };
  8389. /*
  8390. ** CAPI3REF: Mutex Verification Routines
  8391. **
  8392. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
  8393. ** are intended for use inside assert() statements. The SQLite core
  8394. ** never uses these routines except inside an assert() and applications
  8395. ** are advised to follow the lead of the core. The SQLite core only
  8396. ** provides implementations for these routines when it is compiled
  8397. ** with the SQLITE_DEBUG flag. External mutex implementations
  8398. ** are only required to provide these routines if SQLITE_DEBUG is
  8399. ** defined and if NDEBUG is not defined.
  8400. **
  8401. ** These routines should return true if the mutex in their argument
  8402. ** is held or not held, respectively, by the calling thread.
  8403. **
  8404. ** The implementation is not required to provide versions of these
  8405. ** routines that actually work. If the implementation does not provide working
  8406. ** versions of these routines, it should at least provide stubs that always
  8407. ** return true so that one does not get spurious assertion failures.
  8408. **
  8409. ** If the argument to sqlite3_mutex_held() is a NULL pointer then
  8410. ** the routine should return 1. This seems counter-intuitive since
  8411. ** clearly the mutex cannot be held if it does not exist. But
  8412. ** the reason the mutex does not exist is because the build is not
  8413. ** using mutexes. And we do not want the assert() containing the
  8414. ** call to sqlite3_mutex_held() to fail, so a non-zero return is
  8415. ** the appropriate thing to do. The sqlite3_mutex_notheld()
  8416. ** interface should also return 1 when given a NULL pointer.
  8417. */
  8418. #ifndef NDEBUG
  8419. SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*);
  8420. SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*);
  8421. #endif
  8422. /*
  8423. ** CAPI3REF: Mutex Types
  8424. **
  8425. ** The [sqlite3_mutex_alloc()] interface takes a single argument
  8426. ** which is one of these integer constants.
  8427. **
  8428. ** The set of static mutexes may change from one SQLite release to the
  8429. ** next. Applications that override the built-in mutex logic must be
  8430. ** prepared to accommodate additional static mutexes.
  8431. */
  8432. #define SQLITE_MUTEX_FAST 0
  8433. #define SQLITE_MUTEX_RECURSIVE 1
  8434. #define SQLITE_MUTEX_STATIC_MASTER 2
  8435. #define SQLITE_MUTEX_STATIC_MEM 3 /* sqlite3_malloc() */
  8436. #define SQLITE_MUTEX_STATIC_MEM2 4 /* NOT USED */
  8437. #define SQLITE_MUTEX_STATIC_OPEN 4 /* sqlite3BtreeOpen() */
  8438. #define SQLITE_MUTEX_STATIC_PRNG 5 /* sqlite3_randomness() */
  8439. #define SQLITE_MUTEX_STATIC_LRU 6 /* lru page list */
  8440. #define SQLITE_MUTEX_STATIC_LRU2 7 /* NOT USED */
  8441. #define SQLITE_MUTEX_STATIC_PMEM 7 /* sqlite3PageMalloc() */
  8442. #define SQLITE_MUTEX_STATIC_APP1 8 /* For use by application */
  8443. #define SQLITE_MUTEX_STATIC_APP2 9 /* For use by application */
  8444. #define SQLITE_MUTEX_STATIC_APP3 10 /* For use by application */
  8445. #define SQLITE_MUTEX_STATIC_VFS1 11 /* For use by built-in VFS */
  8446. #define SQLITE_MUTEX_STATIC_VFS2 12 /* For use by extension VFS */
  8447. #define SQLITE_MUTEX_STATIC_VFS3 13 /* For use by application VFS */
  8448. /*
  8449. ** CAPI3REF: Retrieve the mutex for a database connection
  8450. ** METHOD: sqlite3
  8451. **
  8452. ** ^This interface returns a pointer the [sqlite3_mutex] object that
  8453. ** serializes access to the [database connection] given in the argument
  8454. ** when the [threading mode] is Serialized.
  8455. ** ^If the [threading mode] is Single-thread or Multi-thread then this
  8456. ** routine returns a NULL pointer.
  8457. */
  8458. SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*);
  8459. /*
  8460. ** CAPI3REF: Low-Level Control Of Database Files
  8461. ** METHOD: sqlite3
  8462. ** KEYWORDS: {file control}
  8463. **
  8464. ** ^The [sqlite3_file_control()] interface makes a direct call to the
  8465. ** xFileControl method for the [sqlite3_io_methods] object associated
  8466. ** with a particular database identified by the second argument. ^The
  8467. ** name of the database is "main" for the main database or "temp" for the
  8468. ** TEMP database, or the name that appears after the AS keyword for
  8469. ** databases that are added using the [ATTACH] SQL command.
  8470. ** ^A NULL pointer can be used in place of "main" to refer to the
  8471. ** main database file.
  8472. ** ^The third and fourth parameters to this routine
  8473. ** are passed directly through to the second and third parameters of
  8474. ** the xFileControl method. ^The return value of the xFileControl
  8475. ** method becomes the return value of this routine.
  8476. **
  8477. ** A few opcodes for [sqlite3_file_control()] are handled directly
  8478. ** by the SQLite core and never invoke the
  8479. ** sqlite3_io_methods.xFileControl method.
  8480. ** ^The [SQLITE_FCNTL_FILE_POINTER] value for the op parameter causes
  8481. ** a pointer to the underlying [sqlite3_file] object to be written into
  8482. ** the space pointed to by the 4th parameter. The
  8483. ** [SQLITE_FCNTL_JOURNAL_POINTER] works similarly except that it returns
  8484. ** the [sqlite3_file] object associated with the journal file instead of
  8485. ** the main database. The [SQLITE_FCNTL_VFS_POINTER] opcode returns
  8486. ** a pointer to the underlying [sqlite3_vfs] object for the file.
  8487. ** The [SQLITE_FCNTL_DATA_VERSION] returns the data version counter
  8488. ** from the pager.
  8489. **
  8490. ** ^If the second parameter (zDbName) does not match the name of any
  8491. ** open database file, then SQLITE_ERROR is returned. ^This error
  8492. ** code is not remembered and will not be recalled by [sqlite3_errcode()]
  8493. ** or [sqlite3_errmsg()]. The underlying xFileControl method might
  8494. ** also return SQLITE_ERROR. There is no way to distinguish between
  8495. ** an incorrect zDbName and an SQLITE_ERROR return from the underlying
  8496. ** xFileControl method.
  8497. **
  8498. ** See also: [file control opcodes]
  8499. */
  8500. SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
  8501. /*
  8502. ** CAPI3REF: Testing Interface
  8503. **
  8504. ** ^The sqlite3_test_control() interface is used to read out internal
  8505. ** state of SQLite and to inject faults into SQLite for testing
  8506. ** purposes. ^The first parameter is an operation code that determines
  8507. ** the number, meaning, and operation of all subsequent parameters.
  8508. **
  8509. ** This interface is not for use by applications. It exists solely
  8510. ** for verifying the correct operation of the SQLite library. Depending
  8511. ** on how the SQLite library is compiled, this interface might not exist.
  8512. **
  8513. ** The details of the operation codes, their meanings, the parameters
  8514. ** they take, and what they do are all subject to change without notice.
  8515. ** Unlike most of the SQLite API, this function is not guaranteed to
  8516. ** operate consistently from one release to the next.
  8517. */
  8518. SQLITE_API int sqlite3_test_control(int op, ...);
  8519. /*
  8520. ** CAPI3REF: Testing Interface Operation Codes
  8521. **
  8522. ** These constants are the valid operation code parameters used
  8523. ** as the first argument to [sqlite3_test_control()].
  8524. **
  8525. ** These parameters and their meanings are subject to change
  8526. ** without notice. These values are for testing purposes only.
  8527. ** Applications should not use any of these parameters or the
  8528. ** [sqlite3_test_control()] interface.
  8529. */
  8530. #define SQLITE_TESTCTRL_FIRST 5
  8531. #define SQLITE_TESTCTRL_PRNG_SAVE 5
  8532. #define SQLITE_TESTCTRL_PRNG_RESTORE 6
  8533. #define SQLITE_TESTCTRL_PRNG_RESET 7 /* NOT USED */
  8534. #define SQLITE_TESTCTRL_BITVEC_TEST 8
  8535. #define SQLITE_TESTCTRL_FAULT_INSTALL 9
  8536. #define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS 10
  8537. #define SQLITE_TESTCTRL_PENDING_BYTE 11
  8538. #define SQLITE_TESTCTRL_ASSERT 12
  8539. #define SQLITE_TESTCTRL_ALWAYS 13
  8540. #define SQLITE_TESTCTRL_RESERVE 14 /* NOT USED */
  8541. #define SQLITE_TESTCTRL_OPTIMIZATIONS 15
  8542. #define SQLITE_TESTCTRL_ISKEYWORD 16 /* NOT USED */
  8543. #define SQLITE_TESTCTRL_SCRATCHMALLOC 17 /* NOT USED */
  8544. #define SQLITE_TESTCTRL_INTERNAL_FUNCTIONS 17
  8545. #define SQLITE_TESTCTRL_LOCALTIME_FAULT 18
  8546. #define SQLITE_TESTCTRL_EXPLAIN_STMT 19 /* NOT USED */
  8547. #define SQLITE_TESTCTRL_ONCE_RESET_THRESHOLD 19
  8548. #define SQLITE_TESTCTRL_NEVER_CORRUPT 20
  8549. #define SQLITE_TESTCTRL_VDBE_COVERAGE 21
  8550. #define SQLITE_TESTCTRL_BYTEORDER 22
  8551. #define SQLITE_TESTCTRL_ISINIT 23
  8552. #define SQLITE_TESTCTRL_SORTER_MMAP 24
  8553. #define SQLITE_TESTCTRL_IMPOSTER 25
  8554. #define SQLITE_TESTCTRL_PARSER_COVERAGE 26
  8555. #define SQLITE_TESTCTRL_RESULT_INTREAL 27
  8556. #define SQLITE_TESTCTRL_PRNG_SEED 28
  8557. #define SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS 29
  8558. #define SQLITE_TESTCTRL_LAST 29 /* Largest TESTCTRL */
  8559. /*
  8560. ** CAPI3REF: SQL Keyword Checking
  8561. **
  8562. ** These routines provide access to the set of SQL language keywords
  8563. ** recognized by SQLite. Applications can uses these routines to determine
  8564. ** whether or not a specific identifier needs to be escaped (for example,
  8565. ** by enclosing in double-quotes) so as not to confuse the parser.
  8566. **
  8567. ** The sqlite3_keyword_count() interface returns the number of distinct
  8568. ** keywords understood by SQLite.
  8569. **
  8570. ** The sqlite3_keyword_name(N,Z,L) interface finds the N-th keyword and
  8571. ** makes *Z point to that keyword expressed as UTF8 and writes the number
  8572. ** of bytes in the keyword into *L. The string that *Z points to is not
  8573. ** zero-terminated. The sqlite3_keyword_name(N,Z,L) routine returns
  8574. ** SQLITE_OK if N is within bounds and SQLITE_ERROR if not. If either Z
  8575. ** or L are NULL or invalid pointers then calls to
  8576. ** sqlite3_keyword_name(N,Z,L) result in undefined behavior.
  8577. **
  8578. ** The sqlite3_keyword_check(Z,L) interface checks to see whether or not
  8579. ** the L-byte UTF8 identifier that Z points to is a keyword, returning non-zero
  8580. ** if it is and zero if not.
  8581. **
  8582. ** The parser used by SQLite is forgiving. It is often possible to use
  8583. ** a keyword as an identifier as long as such use does not result in a
  8584. ** parsing ambiguity. For example, the statement
  8585. ** "CREATE TABLE BEGIN(REPLACE,PRAGMA,END);" is accepted by SQLite, and
  8586. ** creates a new table named "BEGIN" with three columns named
  8587. ** "REPLACE", "PRAGMA", and "END". Nevertheless, best practice is to avoid
  8588. ** using keywords as identifiers. Common techniques used to avoid keyword
  8589. ** name collisions include:
  8590. ** <ul>
  8591. ** <li> Put all identifier names inside double-quotes. This is the official
  8592. ** SQL way to escape identifier names.
  8593. ** <li> Put identifier names inside &#91;...&#93;. This is not standard SQL,
  8594. ** but it is what SQL Server does and so lots of programmers use this
  8595. ** technique.
  8596. ** <li> Begin every identifier with the letter "Z" as no SQL keywords start
  8597. ** with "Z".
  8598. ** <li> Include a digit somewhere in every identifier name.
  8599. ** </ul>
  8600. **
  8601. ** Note that the number of keywords understood by SQLite can depend on
  8602. ** compile-time options. For example, "VACUUM" is not a keyword if
  8603. ** SQLite is compiled with the [-DSQLITE_OMIT_VACUUM] option. Also,
  8604. ** new keywords may be added to future releases of SQLite.
  8605. */
  8606. SQLITE_API int sqlite3_keyword_count(void);
  8607. SQLITE_API int sqlite3_keyword_name(int,const char**,int*);
  8608. SQLITE_API int sqlite3_keyword_check(const char*,int);
  8609. /*
  8610. ** CAPI3REF: Dynamic String Object
  8611. ** KEYWORDS: {dynamic string}
  8612. **
  8613. ** An instance of the sqlite3_str object contains a dynamically-sized
  8614. ** string under construction.
  8615. **
  8616. ** The lifecycle of an sqlite3_str object is as follows:
  8617. ** <ol>
  8618. ** <li> ^The sqlite3_str object is created using [sqlite3_str_new()].
  8619. ** <li> ^Text is appended to the sqlite3_str object using various
  8620. ** methods, such as [sqlite3_str_appendf()].
  8621. ** <li> ^The sqlite3_str object is destroyed and the string it created
  8622. ** is returned using the [sqlite3_str_finish()] interface.
  8623. ** </ol>
  8624. */
  8625. typedef struct sqlite3_str sqlite3_str;
  8626. /*
  8627. ** CAPI3REF: Create A New Dynamic String Object
  8628. ** CONSTRUCTOR: sqlite3_str
  8629. **
  8630. ** ^The [sqlite3_str_new(D)] interface allocates and initializes
  8631. ** a new [sqlite3_str] object. To avoid memory leaks, the object returned by
  8632. ** [sqlite3_str_new()] must be freed by a subsequent call to
  8633. ** [sqlite3_str_finish(X)].
  8634. **
  8635. ** ^The [sqlite3_str_new(D)] interface always returns a pointer to a
  8636. ** valid [sqlite3_str] object, though in the event of an out-of-memory
  8637. ** error the returned object might be a special singleton that will
  8638. ** silently reject new text, always return SQLITE_NOMEM from
  8639. ** [sqlite3_str_errcode()], always return 0 for
  8640. ** [sqlite3_str_length()], and always return NULL from
  8641. ** [sqlite3_str_finish(X)]. It is always safe to use the value
  8642. ** returned by [sqlite3_str_new(D)] as the sqlite3_str parameter
  8643. ** to any of the other [sqlite3_str] methods.
  8644. **
  8645. ** The D parameter to [sqlite3_str_new(D)] may be NULL. If the
  8646. ** D parameter in [sqlite3_str_new(D)] is not NULL, then the maximum
  8647. ** length of the string contained in the [sqlite3_str] object will be
  8648. ** the value set for [sqlite3_limit](D,[SQLITE_LIMIT_LENGTH]) instead
  8649. ** of [SQLITE_MAX_LENGTH].
  8650. */
  8651. SQLITE_API sqlite3_str *sqlite3_str_new(sqlite3*);
  8652. /*
  8653. ** CAPI3REF: Finalize A Dynamic String
  8654. ** DESTRUCTOR: sqlite3_str
  8655. **
  8656. ** ^The [sqlite3_str_finish(X)] interface destroys the sqlite3_str object X
  8657. ** and returns a pointer to a memory buffer obtained from [sqlite3_malloc64()]
  8658. ** that contains the constructed string. The calling application should
  8659. ** pass the returned value to [sqlite3_free()] to avoid a memory leak.
  8660. ** ^The [sqlite3_str_finish(X)] interface may return a NULL pointer if any
  8661. ** errors were encountered during construction of the string. ^The
  8662. ** [sqlite3_str_finish(X)] interface will also return a NULL pointer if the
  8663. ** string in [sqlite3_str] object X is zero bytes long.
  8664. */
  8665. SQLITE_API char *sqlite3_str_finish(sqlite3_str*);
  8666. /*
  8667. ** CAPI3REF: Add Content To A Dynamic String
  8668. ** METHOD: sqlite3_str
  8669. **
  8670. ** These interfaces add content to an sqlite3_str object previously obtained
  8671. ** from [sqlite3_str_new()].
  8672. **
  8673. ** ^The [sqlite3_str_appendf(X,F,...)] and
  8674. ** [sqlite3_str_vappendf(X,F,V)] interfaces uses the [built-in printf]
  8675. ** functionality of SQLite to append formatted text onto the end of
  8676. ** [sqlite3_str] object X.
  8677. **
  8678. ** ^The [sqlite3_str_append(X,S,N)] method appends exactly N bytes from string S
  8679. ** onto the end of the [sqlite3_str] object X. N must be non-negative.
  8680. ** S must contain at least N non-zero bytes of content. To append a
  8681. ** zero-terminated string in its entirety, use the [sqlite3_str_appendall()]
  8682. ** method instead.
  8683. **
  8684. ** ^The [sqlite3_str_appendall(X,S)] method appends the complete content of
  8685. ** zero-terminated string S onto the end of [sqlite3_str] object X.
  8686. **
  8687. ** ^The [sqlite3_str_appendchar(X,N,C)] method appends N copies of the
  8688. ** single-byte character C onto the end of [sqlite3_str] object X.
  8689. ** ^This method can be used, for example, to add whitespace indentation.
  8690. **
  8691. ** ^The [sqlite3_str_reset(X)] method resets the string under construction
  8692. ** inside [sqlite3_str] object X back to zero bytes in length.
  8693. **
  8694. ** These methods do not return a result code. ^If an error occurs, that fact
  8695. ** is recorded in the [sqlite3_str] object and can be recovered by a
  8696. ** subsequent call to [sqlite3_str_errcode(X)].
  8697. */
  8698. SQLITE_API void sqlite3_str_appendf(sqlite3_str*, const char *zFormat, ...);
  8699. SQLITE_API void sqlite3_str_vappendf(sqlite3_str*, const char *zFormat, va_list);
  8700. SQLITE_API void sqlite3_str_append(sqlite3_str*, const char *zIn, int N);
  8701. SQLITE_API void sqlite3_str_appendall(sqlite3_str*, const char *zIn);
  8702. SQLITE_API void sqlite3_str_appendchar(sqlite3_str*, int N, char C);
  8703. SQLITE_API void sqlite3_str_reset(sqlite3_str*);
  8704. /*
  8705. ** CAPI3REF: Status Of A Dynamic String
  8706. ** METHOD: sqlite3_str
  8707. **
  8708. ** These interfaces return the current status of an [sqlite3_str] object.
  8709. **
  8710. ** ^If any prior errors have occurred while constructing the dynamic string
  8711. ** in sqlite3_str X, then the [sqlite3_str_errcode(X)] method will return
  8712. ** an appropriate error code. ^The [sqlite3_str_errcode(X)] method returns
  8713. ** [SQLITE_NOMEM] following any out-of-memory error, or
  8714. ** [SQLITE_TOOBIG] if the size of the dynamic string exceeds
  8715. ** [SQLITE_MAX_LENGTH], or [SQLITE_OK] if there have been no errors.
  8716. **
  8717. ** ^The [sqlite3_str_length(X)] method returns the current length, in bytes,
  8718. ** of the dynamic string under construction in [sqlite3_str] object X.
  8719. ** ^The length returned by [sqlite3_str_length(X)] does not include the
  8720. ** zero-termination byte.
  8721. **
  8722. ** ^The [sqlite3_str_value(X)] method returns a pointer to the current
  8723. ** content of the dynamic string under construction in X. The value
  8724. ** returned by [sqlite3_str_value(X)] is managed by the sqlite3_str object X
  8725. ** and might be freed or altered by any subsequent method on the same
  8726. ** [sqlite3_str] object. Applications must not used the pointer returned
  8727. ** [sqlite3_str_value(X)] after any subsequent method call on the same
  8728. ** object. ^Applications may change the content of the string returned
  8729. ** by [sqlite3_str_value(X)] as long as they do not write into any bytes
  8730. ** outside the range of 0 to [sqlite3_str_length(X)] and do not read or
  8731. ** write any byte after any subsequent sqlite3_str method call.
  8732. */
  8733. SQLITE_API int sqlite3_str_errcode(sqlite3_str*);
  8734. SQLITE_API int sqlite3_str_length(sqlite3_str*);
  8735. SQLITE_API char *sqlite3_str_value(sqlite3_str*);
  8736. /*
  8737. ** CAPI3REF: SQLite Runtime Status
  8738. **
  8739. ** ^These interfaces are used to retrieve runtime status information
  8740. ** about the performance of SQLite, and optionally to reset various
  8741. ** highwater marks. ^The first argument is an integer code for
  8742. ** the specific parameter to measure. ^(Recognized integer codes
  8743. ** are of the form [status parameters | SQLITE_STATUS_...].)^
  8744. ** ^The current value of the parameter is returned into *pCurrent.
  8745. ** ^The highest recorded value is returned in *pHighwater. ^If the
  8746. ** resetFlag is true, then the highest record value is reset after
  8747. ** *pHighwater is written. ^(Some parameters do not record the highest
  8748. ** value. For those parameters
  8749. ** nothing is written into *pHighwater and the resetFlag is ignored.)^
  8750. ** ^(Other parameters record only the highwater mark and not the current
  8751. ** value. For these latter parameters nothing is written into *pCurrent.)^
  8752. **
  8753. ** ^The sqlite3_status() and sqlite3_status64() routines return
  8754. ** SQLITE_OK on success and a non-zero [error code] on failure.
  8755. **
  8756. ** If either the current value or the highwater mark is too large to
  8757. ** be represented by a 32-bit integer, then the values returned by
  8758. ** sqlite3_status() are undefined.
  8759. **
  8760. ** See also: [sqlite3_db_status()]
  8761. */
  8762. SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);
  8763. SQLITE_API int sqlite3_status64(
  8764. int op,
  8765. sqlite3_int64 *pCurrent,
  8766. sqlite3_int64 *pHighwater,
  8767. int resetFlag
  8768. );
  8769. /*
  8770. ** CAPI3REF: Status Parameters
  8771. ** KEYWORDS: {status parameters}
  8772. **
  8773. ** These integer constants designate various run-time status parameters
  8774. ** that can be returned by [sqlite3_status()].
  8775. **
  8776. ** <dl>
  8777. ** [[SQLITE_STATUS_MEMORY_USED]] ^(<dt>SQLITE_STATUS_MEMORY_USED</dt>
  8778. ** <dd>This parameter is the current amount of memory checked out
  8779. ** using [sqlite3_malloc()], either directly or indirectly. The
  8780. ** figure includes calls made to [sqlite3_malloc()] by the application
  8781. ** and internal memory usage by the SQLite library. Auxiliary page-cache
  8782. ** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in
  8783. ** this parameter. The amount returned is the sum of the allocation
  8784. ** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>)^
  8785. **
  8786. ** [[SQLITE_STATUS_MALLOC_SIZE]] ^(<dt>SQLITE_STATUS_MALLOC_SIZE</dt>
  8787. ** <dd>This parameter records the largest memory allocation request
  8788. ** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their
  8789. ** internal equivalents). Only the value returned in the
  8790. ** *pHighwater parameter to [sqlite3_status()] is of interest.
  8791. ** The value written into the *pCurrent parameter is undefined.</dd>)^
  8792. **
  8793. ** [[SQLITE_STATUS_MALLOC_COUNT]] ^(<dt>SQLITE_STATUS_MALLOC_COUNT</dt>
  8794. ** <dd>This parameter records the number of separate memory allocations
  8795. ** currently checked out.</dd>)^
  8796. **
  8797. ** [[SQLITE_STATUS_PAGECACHE_USED]] ^(<dt>SQLITE_STATUS_PAGECACHE_USED</dt>
  8798. ** <dd>This parameter returns the number of pages used out of the
  8799. ** [pagecache memory allocator] that was configured using
  8800. ** [SQLITE_CONFIG_PAGECACHE]. The
  8801. ** value returned is in pages, not in bytes.</dd>)^
  8802. **
  8803. ** [[SQLITE_STATUS_PAGECACHE_OVERFLOW]]
  8804. ** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
  8805. ** <dd>This parameter returns the number of bytes of page cache
  8806. ** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE]
  8807. ** buffer and where forced to overflow to [sqlite3_malloc()]. The
  8808. ** returned value includes allocations that overflowed because they
  8809. ** where too large (they were larger than the "sz" parameter to
  8810. ** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
  8811. ** no space was left in the page cache.</dd>)^
  8812. **
  8813. ** [[SQLITE_STATUS_PAGECACHE_SIZE]] ^(<dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>
  8814. ** <dd>This parameter records the largest memory allocation request
  8815. ** handed to the [pagecache memory allocator]. Only the value returned in the
  8816. ** *pHighwater parameter to [sqlite3_status()] is of interest.
  8817. ** The value written into the *pCurrent parameter is undefined.</dd>)^
  8818. **
  8819. ** [[SQLITE_STATUS_SCRATCH_USED]] <dt>SQLITE_STATUS_SCRATCH_USED</dt>
  8820. ** <dd>No longer used.</dd>
  8821. **
  8822. ** [[SQLITE_STATUS_SCRATCH_OVERFLOW]] ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
  8823. ** <dd>No longer used.</dd>
  8824. **
  8825. ** [[SQLITE_STATUS_SCRATCH_SIZE]] <dt>SQLITE_STATUS_SCRATCH_SIZE</dt>
  8826. ** <dd>No longer used.</dd>
  8827. **
  8828. ** [[SQLITE_STATUS_PARSER_STACK]] ^(<dt>SQLITE_STATUS_PARSER_STACK</dt>
  8829. ** <dd>The *pHighwater parameter records the deepest parser stack.
  8830. ** The *pCurrent value is undefined. The *pHighwater value is only
  8831. ** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>)^
  8832. ** </dl>
  8833. **
  8834. ** New status parameters may be added from time to time.
  8835. */
  8836. #define SQLITE_STATUS_MEMORY_USED 0
  8837. #define SQLITE_STATUS_PAGECACHE_USED 1
  8838. #define SQLITE_STATUS_PAGECACHE_OVERFLOW 2
  8839. #define SQLITE_STATUS_SCRATCH_USED 3 /* NOT USED */
  8840. #define SQLITE_STATUS_SCRATCH_OVERFLOW 4 /* NOT USED */
  8841. #define SQLITE_STATUS_MALLOC_SIZE 5
  8842. #define SQLITE_STATUS_PARSER_STACK 6
  8843. #define SQLITE_STATUS_PAGECACHE_SIZE 7
  8844. #define SQLITE_STATUS_SCRATCH_SIZE 8 /* NOT USED */
  8845. #define SQLITE_STATUS_MALLOC_COUNT 9
  8846. /*
  8847. ** CAPI3REF: Database Connection Status
  8848. ** METHOD: sqlite3
  8849. **
  8850. ** ^This interface is used to retrieve runtime status information
  8851. ** about a single [database connection]. ^The first argument is the
  8852. ** database connection object to be interrogated. ^The second argument
  8853. ** is an integer constant, taken from the set of
  8854. ** [SQLITE_DBSTATUS options], that
  8855. ** determines the parameter to interrogate. The set of
  8856. ** [SQLITE_DBSTATUS options] is likely
  8857. ** to grow in future releases of SQLite.
  8858. **
  8859. ** ^The current value of the requested parameter is written into *pCur
  8860. ** and the highest instantaneous value is written into *pHiwtr. ^If
  8861. ** the resetFlg is true, then the highest instantaneous value is
  8862. ** reset back down to the current value.
  8863. **
  8864. ** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a
  8865. ** non-zero [error code] on failure.
  8866. **
  8867. ** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
  8868. */
  8869. SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
  8870. /*
  8871. ** CAPI3REF: Status Parameters for database connections
  8872. ** KEYWORDS: {SQLITE_DBSTATUS options}
  8873. **
  8874. ** These constants are the available integer "verbs" that can be passed as
  8875. ** the second argument to the [sqlite3_db_status()] interface.
  8876. **
  8877. ** New verbs may be added in future releases of SQLite. Existing verbs
  8878. ** might be discontinued. Applications should check the return code from
  8879. ** [sqlite3_db_status()] to make sure that the call worked.
  8880. ** The [sqlite3_db_status()] interface will return a non-zero error code
  8881. ** if a discontinued or unsupported verb is invoked.
  8882. **
  8883. ** <dl>
  8884. ** [[SQLITE_DBSTATUS_LOOKASIDE_USED]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>
  8885. ** <dd>This parameter returns the number of lookaside memory slots currently
  8886. ** checked out.</dd>)^
  8887. **
  8888. ** [[SQLITE_DBSTATUS_LOOKASIDE_HIT]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_HIT</dt>
  8889. ** <dd>This parameter returns the number of malloc attempts that were
  8890. ** satisfied using lookaside memory. Only the high-water value is meaningful;
  8891. ** the current value is always zero.)^
  8892. **
  8893. ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE]]
  8894. ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE</dt>
  8895. ** <dd>This parameter returns the number malloc attempts that might have
  8896. ** been satisfied using lookaside memory but failed due to the amount of
  8897. ** memory requested being larger than the lookaside slot size.
  8898. ** Only the high-water value is meaningful;
  8899. ** the current value is always zero.)^
  8900. **
  8901. ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL]]
  8902. ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL</dt>
  8903. ** <dd>This parameter returns the number malloc attempts that might have
  8904. ** been satisfied using lookaside memory but failed due to all lookaside
  8905. ** memory already being in use.
  8906. ** Only the high-water value is meaningful;
  8907. ** the current value is always zero.)^
  8908. **
  8909. ** [[SQLITE_DBSTATUS_CACHE_USED]] ^(<dt>SQLITE_DBSTATUS_CACHE_USED</dt>
  8910. ** <dd>This parameter returns the approximate number of bytes of heap
  8911. ** memory used by all pager caches associated with the database connection.)^
  8912. ** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0.
  8913. **
  8914. ** [[SQLITE_DBSTATUS_CACHE_USED_SHARED]]
  8915. ** ^(<dt>SQLITE_DBSTATUS_CACHE_USED_SHARED</dt>
  8916. ** <dd>This parameter is similar to DBSTATUS_CACHE_USED, except that if a
  8917. ** pager cache is shared between two or more connections the bytes of heap
  8918. ** memory used by that pager cache is divided evenly between the attached
  8919. ** connections.)^ In other words, if none of the pager caches associated
  8920. ** with the database connection are shared, this request returns the same
  8921. ** value as DBSTATUS_CACHE_USED. Or, if one or more or the pager caches are
  8922. ** shared, the value returned by this call will be smaller than that returned
  8923. ** by DBSTATUS_CACHE_USED. ^The highwater mark associated with
  8924. ** SQLITE_DBSTATUS_CACHE_USED_SHARED is always 0.
  8925. **
  8926. ** [[SQLITE_DBSTATUS_SCHEMA_USED]] ^(<dt>SQLITE_DBSTATUS_SCHEMA_USED</dt>
  8927. ** <dd>This parameter returns the approximate number of bytes of heap
  8928. ** memory used to store the schema for all databases associated
  8929. ** with the connection - main, temp, and any [ATTACH]-ed databases.)^
  8930. ** ^The full amount of memory used by the schemas is reported, even if the
  8931. ** schema memory is shared with other database connections due to
  8932. ** [shared cache mode] being enabled.
  8933. ** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0.
  8934. **
  8935. ** [[SQLITE_DBSTATUS_STMT_USED]] ^(<dt>SQLITE_DBSTATUS_STMT_USED</dt>
  8936. ** <dd>This parameter returns the approximate number of bytes of heap
  8937. ** and lookaside memory used by all prepared statements associated with
  8938. ** the database connection.)^
  8939. ** ^The highwater mark associated with SQLITE_DBSTATUS_STMT_USED is always 0.
  8940. ** </dd>
  8941. **
  8942. ** [[SQLITE_DBSTATUS_CACHE_HIT]] ^(<dt>SQLITE_DBSTATUS_CACHE_HIT</dt>
  8943. ** <dd>This parameter returns the number of pager cache hits that have
  8944. ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_HIT
  8945. ** is always 0.
  8946. ** </dd>
  8947. **
  8948. ** [[SQLITE_DBSTATUS_CACHE_MISS]] ^(<dt>SQLITE_DBSTATUS_CACHE_MISS</dt>
  8949. ** <dd>This parameter returns the number of pager cache misses that have
  8950. ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_MISS
  8951. ** is always 0.
  8952. ** </dd>
  8953. **
  8954. ** [[SQLITE_DBSTATUS_CACHE_WRITE]] ^(<dt>SQLITE_DBSTATUS_CACHE_WRITE</dt>
  8955. ** <dd>This parameter returns the number of dirty cache entries that have
  8956. ** been written to disk. Specifically, the number of pages written to the
  8957. ** wal file in wal mode databases, or the number of pages written to the
  8958. ** database file in rollback mode databases. Any pages written as part of
  8959. ** transaction rollback or database recovery operations are not included.
  8960. ** If an IO or other error occurs while writing a page to disk, the effect
  8961. ** on subsequent SQLITE_DBSTATUS_CACHE_WRITE requests is undefined.)^ ^The
  8962. ** highwater mark associated with SQLITE_DBSTATUS_CACHE_WRITE is always 0.
  8963. ** </dd>
  8964. **
  8965. ** [[SQLITE_DBSTATUS_CACHE_SPILL]] ^(<dt>SQLITE_DBSTATUS_CACHE_SPILL</dt>
  8966. ** <dd>This parameter returns the number of dirty cache entries that have
  8967. ** been written to disk in the middle of a transaction due to the page
  8968. ** cache overflowing. Transactions are more efficient if they are written
  8969. ** to disk all at once. When pages spill mid-transaction, that introduces
  8970. ** additional overhead. This parameter can be used help identify
  8971. ** inefficiencies that can be resolved by increasing the cache size.
  8972. ** </dd>
  8973. **
  8974. ** [[SQLITE_DBSTATUS_DEFERRED_FKS]] ^(<dt>SQLITE_DBSTATUS_DEFERRED_FKS</dt>
  8975. ** <dd>This parameter returns zero for the current value if and only if
  8976. ** all foreign key constraints (deferred or immediate) have been
  8977. ** resolved.)^ ^The highwater mark is always 0.
  8978. ** </dd>
  8979. ** </dl>
  8980. */
  8981. #define SQLITE_DBSTATUS_LOOKASIDE_USED 0
  8982. #define SQLITE_DBSTATUS_CACHE_USED 1
  8983. #define SQLITE_DBSTATUS_SCHEMA_USED 2
  8984. #define SQLITE_DBSTATUS_STMT_USED 3
  8985. #define SQLITE_DBSTATUS_LOOKASIDE_HIT 4
  8986. #define SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE 5
  8987. #define SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL 6
  8988. #define SQLITE_DBSTATUS_CACHE_HIT 7
  8989. #define SQLITE_DBSTATUS_CACHE_MISS 8
  8990. #define SQLITE_DBSTATUS_CACHE_WRITE 9
  8991. #define SQLITE_DBSTATUS_DEFERRED_FKS 10
  8992. #define SQLITE_DBSTATUS_CACHE_USED_SHARED 11
  8993. #define SQLITE_DBSTATUS_CACHE_SPILL 12
  8994. #define SQLITE_DBSTATUS_MAX 12 /* Largest defined DBSTATUS */
  8995. /*
  8996. ** CAPI3REF: Prepared Statement Status
  8997. ** METHOD: sqlite3_stmt
  8998. **
  8999. ** ^(Each prepared statement maintains various
  9000. ** [SQLITE_STMTSTATUS counters] that measure the number
  9001. ** of times it has performed specific operations.)^ These counters can
  9002. ** be used to monitor the performance characteristics of the prepared
  9003. ** statements. For example, if the number of table steps greatly exceeds
  9004. ** the number of table searches or result rows, that would tend to indicate
  9005. ** that the prepared statement is using a full table scan rather than
  9006. ** an index.
  9007. **
  9008. ** ^(This interface is used to retrieve and reset counter values from
  9009. ** a [prepared statement]. The first argument is the prepared statement
  9010. ** object to be interrogated. The second argument
  9011. ** is an integer code for a specific [SQLITE_STMTSTATUS counter]
  9012. ** to be interrogated.)^
  9013. ** ^The current value of the requested counter is returned.
  9014. ** ^If the resetFlg is true, then the counter is reset to zero after this
  9015. ** interface call returns.
  9016. **
  9017. ** See also: [sqlite3_status()] and [sqlite3_db_status()].
  9018. */
  9019. SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
  9020. /*
  9021. ** CAPI3REF: Status Parameters for prepared statements
  9022. ** KEYWORDS: {SQLITE_STMTSTATUS counter} {SQLITE_STMTSTATUS counters}
  9023. **
  9024. ** These preprocessor macros define integer codes that name counter
  9025. ** values associated with the [sqlite3_stmt_status()] interface.
  9026. ** The meanings of the various counters are as follows:
  9027. **
  9028. ** <dl>
  9029. ** [[SQLITE_STMTSTATUS_FULLSCAN_STEP]] <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt>
  9030. ** <dd>^This is the number of times that SQLite has stepped forward in
  9031. ** a table as part of a full table scan. Large numbers for this counter
  9032. ** may indicate opportunities for performance improvement through
  9033. ** careful use of indices.</dd>
  9034. **
  9035. ** [[SQLITE_STMTSTATUS_SORT]] <dt>SQLITE_STMTSTATUS_SORT</dt>
  9036. ** <dd>^This is the number of sort operations that have occurred.
  9037. ** A non-zero value in this counter may indicate an opportunity to
  9038. ** improvement performance through careful use of indices.</dd>
  9039. **
  9040. ** [[SQLITE_STMTSTATUS_AUTOINDEX]] <dt>SQLITE_STMTSTATUS_AUTOINDEX</dt>
  9041. ** <dd>^This is the number of rows inserted into transient indices that
  9042. ** were created automatically in order to help joins run faster.
  9043. ** A non-zero value in this counter may indicate an opportunity to
  9044. ** improvement performance by adding permanent indices that do not
  9045. ** need to be reinitialized each time the statement is run.</dd>
  9046. **
  9047. ** [[SQLITE_STMTSTATUS_VM_STEP]] <dt>SQLITE_STMTSTATUS_VM_STEP</dt>
  9048. ** <dd>^This is the number of virtual machine operations executed
  9049. ** by the prepared statement if that number is less than or equal
  9050. ** to 2147483647. The number of virtual machine operations can be
  9051. ** used as a proxy for the total work done by the prepared statement.
  9052. ** If the number of virtual machine operations exceeds 2147483647
  9053. ** then the value returned by this statement status code is undefined.
  9054. **
  9055. ** [[SQLITE_STMTSTATUS_REPREPARE]] <dt>SQLITE_STMTSTATUS_REPREPARE</dt>
  9056. ** <dd>^This is the number of times that the prepare statement has been
  9057. ** automatically regenerated due to schema changes or changes to
  9058. ** [bound parameters] that might affect the query plan.
  9059. **
  9060. ** [[SQLITE_STMTSTATUS_RUN]] <dt>SQLITE_STMTSTATUS_RUN</dt>
  9061. ** <dd>^This is the number of times that the prepared statement has
  9062. ** been run. A single "run" for the purposes of this counter is one
  9063. ** or more calls to [sqlite3_step()] followed by a call to [sqlite3_reset()].
  9064. ** The counter is incremented on the first [sqlite3_step()] call of each
  9065. ** cycle.
  9066. **
  9067. ** [[SQLITE_STMTSTATUS_MEMUSED]] <dt>SQLITE_STMTSTATUS_MEMUSED</dt>
  9068. ** <dd>^This is the approximate number of bytes of heap memory
  9069. ** used to store the prepared statement. ^This value is not actually
  9070. ** a counter, and so the resetFlg parameter to sqlite3_stmt_status()
  9071. ** is ignored when the opcode is SQLITE_STMTSTATUS_MEMUSED.
  9072. ** </dd>
  9073. ** </dl>
  9074. */
  9075. #define SQLITE_STMTSTATUS_FULLSCAN_STEP 1
  9076. #define SQLITE_STMTSTATUS_SORT 2
  9077. #define SQLITE_STMTSTATUS_AUTOINDEX 3
  9078. #define SQLITE_STMTSTATUS_VM_STEP 4
  9079. #define SQLITE_STMTSTATUS_REPREPARE 5
  9080. #define SQLITE_STMTSTATUS_RUN 6
  9081. #define SQLITE_STMTSTATUS_MEMUSED 99
  9082. /*
  9083. ** CAPI3REF: Custom Page Cache Object
  9084. **
  9085. ** The sqlite3_pcache type is opaque. It is implemented by
  9086. ** the pluggable module. The SQLite core has no knowledge of
  9087. ** its size or internal structure and never deals with the
  9088. ** sqlite3_pcache object except by holding and passing pointers
  9089. ** to the object.
  9090. **
  9091. ** See [sqlite3_pcache_methods2] for additional information.
  9092. */
  9093. typedef struct sqlite3_pcache sqlite3_pcache;
  9094. /*
  9095. ** CAPI3REF: Custom Page Cache Object
  9096. **
  9097. ** The sqlite3_pcache_page object represents a single page in the
  9098. ** page cache. The page cache will allocate instances of this
  9099. ** object. Various methods of the page cache use pointers to instances
  9100. ** of this object as parameters or as their return value.
  9101. **
  9102. ** See [sqlite3_pcache_methods2] for additional information.
  9103. */
  9104. typedef struct sqlite3_pcache_page sqlite3_pcache_page;
  9105. struct sqlite3_pcache_page {
  9106. void *pBuf; /* The content of the page */
  9107. void *pExtra; /* Extra information associated with the page */
  9108. };
  9109. /*
  9110. ** CAPI3REF: Application Defined Page Cache.
  9111. ** KEYWORDS: {page cache}
  9112. **
  9113. ** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE2], ...) interface can
  9114. ** register an alternative page cache implementation by passing in an
  9115. ** instance of the sqlite3_pcache_methods2 structure.)^
  9116. ** In many applications, most of the heap memory allocated by
  9117. ** SQLite is used for the page cache.
  9118. ** By implementing a
  9119. ** custom page cache using this API, an application can better control
  9120. ** the amount of memory consumed by SQLite, the way in which
  9121. ** that memory is allocated and released, and the policies used to
  9122. ** determine exactly which parts of a database file are cached and for
  9123. ** how long.
  9124. **
  9125. ** The alternative page cache mechanism is an
  9126. ** extreme measure that is only needed by the most demanding applications.
  9127. ** The built-in page cache is recommended for most uses.
  9128. **
  9129. ** ^(The contents of the sqlite3_pcache_methods2 structure are copied to an
  9130. ** internal buffer by SQLite within the call to [sqlite3_config]. Hence
  9131. ** the application may discard the parameter after the call to
  9132. ** [sqlite3_config()] returns.)^
  9133. **
  9134. ** [[the xInit() page cache method]]
  9135. ** ^(The xInit() method is called once for each effective
  9136. ** call to [sqlite3_initialize()])^
  9137. ** (usually only once during the lifetime of the process). ^(The xInit()
  9138. ** method is passed a copy of the sqlite3_pcache_methods2.pArg value.)^
  9139. ** The intent of the xInit() method is to set up global data structures
  9140. ** required by the custom page cache implementation.
  9141. ** ^(If the xInit() method is NULL, then the
  9142. ** built-in default page cache is used instead of the application defined
  9143. ** page cache.)^
  9144. **
  9145. ** [[the xShutdown() page cache method]]
  9146. ** ^The xShutdown() method is called by [sqlite3_shutdown()].
  9147. ** It can be used to clean up
  9148. ** any outstanding resources before process shutdown, if required.
  9149. ** ^The xShutdown() method may be NULL.
  9150. **
  9151. ** ^SQLite automatically serializes calls to the xInit method,
  9152. ** so the xInit method need not be threadsafe. ^The
  9153. ** xShutdown method is only called from [sqlite3_shutdown()] so it does
  9154. ** not need to be threadsafe either. All other methods must be threadsafe
  9155. ** in multithreaded applications.
  9156. **
  9157. ** ^SQLite will never invoke xInit() more than once without an intervening
  9158. ** call to xShutdown().
  9159. **
  9160. ** [[the xCreate() page cache methods]]
  9161. ** ^SQLite invokes the xCreate() method to construct a new cache instance.
  9162. ** SQLite will typically create one cache instance for each open database file,
  9163. ** though this is not guaranteed. ^The
  9164. ** first parameter, szPage, is the size in bytes of the pages that must
  9165. ** be allocated by the cache. ^szPage will always a power of two. ^The
  9166. ** second parameter szExtra is a number of bytes of extra storage
  9167. ** associated with each page cache entry. ^The szExtra parameter will
  9168. ** a number less than 250. SQLite will use the
  9169. ** extra szExtra bytes on each page to store metadata about the underlying
  9170. ** database page on disk. The value passed into szExtra depends
  9171. ** on the SQLite version, the target platform, and how SQLite was compiled.
  9172. ** ^The third argument to xCreate(), bPurgeable, is true if the cache being
  9173. ** created will be used to cache database pages of a file stored on disk, or
  9174. ** false if it is used for an in-memory database. The cache implementation
  9175. ** does not have to do anything special based with the value of bPurgeable;
  9176. ** it is purely advisory. ^On a cache where bPurgeable is false, SQLite will
  9177. ** never invoke xUnpin() except to deliberately delete a page.
  9178. ** ^In other words, calls to xUnpin() on a cache with bPurgeable set to
  9179. ** false will always have the "discard" flag set to true.
  9180. ** ^Hence, a cache created with bPurgeable false will
  9181. ** never contain any unpinned pages.
  9182. **
  9183. ** [[the xCachesize() page cache method]]
  9184. ** ^(The xCachesize() method may be called at any time by SQLite to set the
  9185. ** suggested maximum cache-size (number of pages stored by) the cache
  9186. ** instance passed as the first argument. This is the value configured using
  9187. ** the SQLite "[PRAGMA cache_size]" command.)^ As with the bPurgeable
  9188. ** parameter, the implementation is not required to do anything with this
  9189. ** value; it is advisory only.
  9190. **
  9191. ** [[the xPagecount() page cache methods]]
  9192. ** The xPagecount() method must return the number of pages currently
  9193. ** stored in the cache, both pinned and unpinned.
  9194. **
  9195. ** [[the xFetch() page cache methods]]
  9196. ** The xFetch() method locates a page in the cache and returns a pointer to
  9197. ** an sqlite3_pcache_page object associated with that page, or a NULL pointer.
  9198. ** The pBuf element of the returned sqlite3_pcache_page object will be a
  9199. ** pointer to a buffer of szPage bytes used to store the content of a
  9200. ** single database page. The pExtra element of sqlite3_pcache_page will be
  9201. ** a pointer to the szExtra bytes of extra storage that SQLite has requested
  9202. ** for each entry in the page cache.
  9203. **
  9204. ** The page to be fetched is determined by the key. ^The minimum key value
  9205. ** is 1. After it has been retrieved using xFetch, the page is considered
  9206. ** to be "pinned".
  9207. **
  9208. ** If the requested page is already in the page cache, then the page cache
  9209. ** implementation must return a pointer to the page buffer with its content
  9210. ** intact. If the requested page is not already in the cache, then the
  9211. ** cache implementation should use the value of the createFlag
  9212. ** parameter to help it determined what action to take:
  9213. **
  9214. ** <table border=1 width=85% align=center>
  9215. ** <tr><th> createFlag <th> Behavior when page is not already in cache
  9216. ** <tr><td> 0 <td> Do not allocate a new page. Return NULL.
  9217. ** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.
  9218. ** Otherwise return NULL.
  9219. ** <tr><td> 2 <td> Make every effort to allocate a new page. Only return
  9220. ** NULL if allocating a new page is effectively impossible.
  9221. ** </table>
  9222. **
  9223. ** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1. SQLite
  9224. ** will only use a createFlag of 2 after a prior call with a createFlag of 1
  9225. ** failed.)^ In between the xFetch() calls, SQLite may
  9226. ** attempt to unpin one or more cache pages by spilling the content of
  9227. ** pinned pages to disk and synching the operating system disk cache.
  9228. **
  9229. ** [[the xUnpin() page cache method]]
  9230. ** ^xUnpin() is called by SQLite with a pointer to a currently pinned page
  9231. ** as its second argument. If the third parameter, discard, is non-zero,
  9232. ** then the page must be evicted from the cache.
  9233. ** ^If the discard parameter is
  9234. ** zero, then the page may be discarded or retained at the discretion of
  9235. ** page cache implementation. ^The page cache implementation
  9236. ** may choose to evict unpinned pages at any time.
  9237. **
  9238. ** The cache must not perform any reference counting. A single
  9239. ** call to xUnpin() unpins the page regardless of the number of prior calls
  9240. ** to xFetch().
  9241. **
  9242. ** [[the xRekey() page cache methods]]
  9243. ** The xRekey() method is used to change the key value associated with the
  9244. ** page passed as the second argument. If the cache
  9245. ** previously contains an entry associated with newKey, it must be
  9246. ** discarded. ^Any prior cache entry associated with newKey is guaranteed not
  9247. ** to be pinned.
  9248. **
  9249. ** When SQLite calls the xTruncate() method, the cache must discard all
  9250. ** existing cache entries with page numbers (keys) greater than or equal
  9251. ** to the value of the iLimit parameter passed to xTruncate(). If any
  9252. ** of these pages are pinned, they are implicitly unpinned, meaning that
  9253. ** they can be safely discarded.
  9254. **
  9255. ** [[the xDestroy() page cache method]]
  9256. ** ^The xDestroy() method is used to delete a cache allocated by xCreate().
  9257. ** All resources associated with the specified cache should be freed. ^After
  9258. ** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*]
  9259. ** handle invalid, and will not use it with any other sqlite3_pcache_methods2
  9260. ** functions.
  9261. **
  9262. ** [[the xShrink() page cache method]]
  9263. ** ^SQLite invokes the xShrink() method when it wants the page cache to
  9264. ** free up as much of heap memory as possible. The page cache implementation
  9265. ** is not obligated to free any memory, but well-behaved implementations should
  9266. ** do their best.
  9267. */
  9268. typedef struct sqlite3_pcache_methods2 sqlite3_pcache_methods2;
  9269. struct sqlite3_pcache_methods2 {
  9270. int iVersion;
  9271. void *pArg;
  9272. int (*xInit)(void*);
  9273. void (*xShutdown)(void*);
  9274. sqlite3_pcache *(*xCreate)(int szPage, int szExtra, int bPurgeable);
  9275. void (*xCachesize)(sqlite3_pcache*, int nCachesize);
  9276. int (*xPagecount)(sqlite3_pcache*);
  9277. sqlite3_pcache_page *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
  9278. void (*xUnpin)(sqlite3_pcache*, sqlite3_pcache_page*, int discard);
  9279. void (*xRekey)(sqlite3_pcache*, sqlite3_pcache_page*,
  9280. unsigned oldKey, unsigned newKey);
  9281. void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
  9282. void (*xDestroy)(sqlite3_pcache*);
  9283. void (*xShrink)(sqlite3_pcache*);
  9284. };
  9285. /*
  9286. ** This is the obsolete pcache_methods object that has now been replaced
  9287. ** by sqlite3_pcache_methods2. This object is not used by SQLite. It is
  9288. ** retained in the header file for backwards compatibility only.
  9289. */
  9290. typedef struct sqlite3_pcache_methods sqlite3_pcache_methods;
  9291. struct sqlite3_pcache_methods {
  9292. void *pArg;
  9293. int (*xInit)(void*);
  9294. void (*xShutdown)(void*);
  9295. sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable);
  9296. void (*xCachesize)(sqlite3_pcache*, int nCachesize);
  9297. int (*xPagecount)(sqlite3_pcache*);
  9298. void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
  9299. void (*xUnpin)(sqlite3_pcache*, void*, int discard);
  9300. void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey);
  9301. void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
  9302. void (*xDestroy)(sqlite3_pcache*);
  9303. };
  9304. /*
  9305. ** CAPI3REF: Online Backup Object
  9306. **
  9307. ** The sqlite3_backup object records state information about an ongoing
  9308. ** online backup operation. ^The sqlite3_backup object is created by
  9309. ** a call to [sqlite3_backup_init()] and is destroyed by a call to
  9310. ** [sqlite3_backup_finish()].
  9311. **
  9312. ** See Also: [Using the SQLite Online Backup API]
  9313. */
  9314. typedef struct sqlite3_backup sqlite3_backup;
  9315. /*
  9316. ** CAPI3REF: Online Backup API.
  9317. **
  9318. ** The backup API copies the content of one database into another.
  9319. ** It is useful either for creating backups of databases or
  9320. ** for copying in-memory databases to or from persistent files.
  9321. **
  9322. ** See Also: [Using the SQLite Online Backup API]
  9323. **
  9324. ** ^SQLite holds a write transaction open on the destination database file
  9325. ** for the duration of the backup operation.
  9326. ** ^The source database is read-locked only while it is being read;
  9327. ** it is not locked continuously for the entire backup operation.
  9328. ** ^Thus, the backup may be performed on a live source database without
  9329. ** preventing other database connections from
  9330. ** reading or writing to the source database while the backup is underway.
  9331. **
  9332. ** ^(To perform a backup operation:
  9333. ** <ol>
  9334. ** <li><b>sqlite3_backup_init()</b> is called once to initialize the
  9335. ** backup,
  9336. ** <li><b>sqlite3_backup_step()</b> is called one or more times to transfer
  9337. ** the data between the two databases, and finally
  9338. ** <li><b>sqlite3_backup_finish()</b> is called to release all resources
  9339. ** associated with the backup operation.
  9340. ** </ol>)^
  9341. ** There should be exactly one call to sqlite3_backup_finish() for each
  9342. ** successful call to sqlite3_backup_init().
  9343. **
  9344. ** [[sqlite3_backup_init()]] <b>sqlite3_backup_init()</b>
  9345. **
  9346. ** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the
  9347. ** [database connection] associated with the destination database
  9348. ** and the database name, respectively.
  9349. ** ^The database name is "main" for the main database, "temp" for the
  9350. ** temporary database, or the name specified after the AS keyword in
  9351. ** an [ATTACH] statement for an attached database.
  9352. ** ^The S and M arguments passed to
  9353. ** sqlite3_backup_init(D,N,S,M) identify the [database connection]
  9354. ** and database name of the source database, respectively.
  9355. ** ^The source and destination [database connections] (parameters S and D)
  9356. ** must be different or else sqlite3_backup_init(D,N,S,M) will fail with
  9357. ** an error.
  9358. **
  9359. ** ^A call to sqlite3_backup_init() will fail, returning NULL, if
  9360. ** there is already a read or read-write transaction open on the
  9361. ** destination database.
  9362. **
  9363. ** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is
  9364. ** returned and an error code and error message are stored in the
  9365. ** destination [database connection] D.
  9366. ** ^The error code and message for the failed call to sqlite3_backup_init()
  9367. ** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or
  9368. ** [sqlite3_errmsg16()] functions.
  9369. ** ^A successful call to sqlite3_backup_init() returns a pointer to an
  9370. ** [sqlite3_backup] object.
  9371. ** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and
  9372. ** sqlite3_backup_finish() functions to perform the specified backup
  9373. ** operation.
  9374. **
  9375. ** [[sqlite3_backup_step()]] <b>sqlite3_backup_step()</b>
  9376. **
  9377. ** ^Function sqlite3_backup_step(B,N) will copy up to N pages between
  9378. ** the source and destination databases specified by [sqlite3_backup] object B.
  9379. ** ^If N is negative, all remaining source pages are copied.
  9380. ** ^If sqlite3_backup_step(B,N) successfully copies N pages and there
  9381. ** are still more pages to be copied, then the function returns [SQLITE_OK].
  9382. ** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages
  9383. ** from source to destination, then it returns [SQLITE_DONE].
  9384. ** ^If an error occurs while running sqlite3_backup_step(B,N),
  9385. ** then an [error code] is returned. ^As well as [SQLITE_OK] and
  9386. ** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY],
  9387. ** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an
  9388. ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code.
  9389. **
  9390. ** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if
  9391. ** <ol>
  9392. ** <li> the destination database was opened read-only, or
  9393. ** <li> the destination database is using write-ahead-log journaling
  9394. ** and the destination and source page sizes differ, or
  9395. ** <li> the destination database is an in-memory database and the
  9396. ** destination and source page sizes differ.
  9397. ** </ol>)^
  9398. **
  9399. ** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then
  9400. ** the [sqlite3_busy_handler | busy-handler function]
  9401. ** is invoked (if one is specified). ^If the
  9402. ** busy-handler returns non-zero before the lock is available, then
  9403. ** [SQLITE_BUSY] is returned to the caller. ^In this case the call to
  9404. ** sqlite3_backup_step() can be retried later. ^If the source
  9405. ** [database connection]
  9406. ** is being used to write to the source database when sqlite3_backup_step()
  9407. ** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this
  9408. ** case the call to sqlite3_backup_step() can be retried later on. ^(If
  9409. ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or
  9410. ** [SQLITE_READONLY] is returned, then
  9411. ** there is no point in retrying the call to sqlite3_backup_step(). These
  9412. ** errors are considered fatal.)^ The application must accept
  9413. ** that the backup operation has failed and pass the backup operation handle
  9414. ** to the sqlite3_backup_finish() to release associated resources.
  9415. **
  9416. ** ^The first call to sqlite3_backup_step() obtains an exclusive lock
  9417. ** on the destination file. ^The exclusive lock is not released until either
  9418. ** sqlite3_backup_finish() is called or the backup operation is complete
  9419. ** and sqlite3_backup_step() returns [SQLITE_DONE]. ^Every call to
  9420. ** sqlite3_backup_step() obtains a [shared lock] on the source database that
  9421. ** lasts for the duration of the sqlite3_backup_step() call.
  9422. ** ^Because the source database is not locked between calls to
  9423. ** sqlite3_backup_step(), the source database may be modified mid-way
  9424. ** through the backup process. ^If the source database is modified by an
  9425. ** external process or via a database connection other than the one being
  9426. ** used by the backup operation, then the backup will be automatically
  9427. ** restarted by the next call to sqlite3_backup_step(). ^If the source
  9428. ** database is modified by the using the same database connection as is used
  9429. ** by the backup operation, then the backup database is automatically
  9430. ** updated at the same time.
  9431. **
  9432. ** [[sqlite3_backup_finish()]] <b>sqlite3_backup_finish()</b>
  9433. **
  9434. ** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the
  9435. ** application wishes to abandon the backup operation, the application
  9436. ** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish().
  9437. ** ^The sqlite3_backup_finish() interfaces releases all
  9438. ** resources associated with the [sqlite3_backup] object.
  9439. ** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any
  9440. ** active write-transaction on the destination database is rolled back.
  9441. ** The [sqlite3_backup] object is invalid
  9442. ** and may not be used following a call to sqlite3_backup_finish().
  9443. **
  9444. ** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no
  9445. ** sqlite3_backup_step() errors occurred, regardless or whether or not
  9446. ** sqlite3_backup_step() completed.
  9447. ** ^If an out-of-memory condition or IO error occurred during any prior
  9448. ** sqlite3_backup_step() call on the same [sqlite3_backup] object, then
  9449. ** sqlite3_backup_finish() returns the corresponding [error code].
  9450. **
  9451. ** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step()
  9452. ** is not a permanent error and does not affect the return value of
  9453. ** sqlite3_backup_finish().
  9454. **
  9455. ** [[sqlite3_backup_remaining()]] [[sqlite3_backup_pagecount()]]
  9456. ** <b>sqlite3_backup_remaining() and sqlite3_backup_pagecount()</b>
  9457. **
  9458. ** ^The sqlite3_backup_remaining() routine returns the number of pages still
  9459. ** to be backed up at the conclusion of the most recent sqlite3_backup_step().
  9460. ** ^The sqlite3_backup_pagecount() routine returns the total number of pages
  9461. ** in the source database at the conclusion of the most recent
  9462. ** sqlite3_backup_step().
  9463. ** ^(The values returned by these functions are only updated by
  9464. ** sqlite3_backup_step(). If the source database is modified in a way that
  9465. ** changes the size of the source database or the number of pages remaining,
  9466. ** those changes are not reflected in the output of sqlite3_backup_pagecount()
  9467. ** and sqlite3_backup_remaining() until after the next
  9468. ** sqlite3_backup_step().)^
  9469. **
  9470. ** <b>Concurrent Usage of Database Handles</b>
  9471. **
  9472. ** ^The source [database connection] may be used by the application for other
  9473. ** purposes while a backup operation is underway or being initialized.
  9474. ** ^If SQLite is compiled and configured to support threadsafe database
  9475. ** connections, then the source database connection may be used concurrently
  9476. ** from within other threads.
  9477. **
  9478. ** However, the application must guarantee that the destination
  9479. ** [database connection] is not passed to any other API (by any thread) after
  9480. ** sqlite3_backup_init() is called and before the corresponding call to
  9481. ** sqlite3_backup_finish(). SQLite does not currently check to see
  9482. ** if the application incorrectly accesses the destination [database connection]
  9483. ** and so no error code is reported, but the operations may malfunction
  9484. ** nevertheless. Use of the destination database connection while a
  9485. ** backup is in progress might also also cause a mutex deadlock.
  9486. **
  9487. ** If running in [shared cache mode], the application must
  9488. ** guarantee that the shared cache used by the destination database
  9489. ** is not accessed while the backup is running. In practice this means
  9490. ** that the application must guarantee that the disk file being
  9491. ** backed up to is not accessed by any connection within the process,
  9492. ** not just the specific connection that was passed to sqlite3_backup_init().
  9493. **
  9494. ** The [sqlite3_backup] object itself is partially threadsafe. Multiple
  9495. ** threads may safely make multiple concurrent calls to sqlite3_backup_step().
  9496. ** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount()
  9497. ** APIs are not strictly speaking threadsafe. If they are invoked at the
  9498. ** same time as another thread is invoking sqlite3_backup_step() it is
  9499. ** possible that they return invalid values.
  9500. */
  9501. SQLITE_API sqlite3_backup *sqlite3_backup_init(
  9502. sqlite3 *pDest, /* Destination database handle */
  9503. const char *zDestName, /* Destination database name */
  9504. sqlite3 *pSource, /* Source database handle */
  9505. const char *zSourceName /* Source database name */
  9506. );
  9507. SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage);
  9508. SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p);
  9509. SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p);
  9510. SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p);
  9511. /*
  9512. ** CAPI3REF: Unlock Notification
  9513. ** METHOD: sqlite3
  9514. **
  9515. ** ^When running in shared-cache mode, a database operation may fail with
  9516. ** an [SQLITE_LOCKED] error if the required locks on the shared-cache or
  9517. ** individual tables within the shared-cache cannot be obtained. See
  9518. ** [SQLite Shared-Cache Mode] for a description of shared-cache locking.
  9519. ** ^This API may be used to register a callback that SQLite will invoke
  9520. ** when the connection currently holding the required lock relinquishes it.
  9521. ** ^This API is only available if the library was compiled with the
  9522. ** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined.
  9523. **
  9524. ** See Also: [Using the SQLite Unlock Notification Feature].
  9525. **
  9526. ** ^Shared-cache locks are released when a database connection concludes
  9527. ** its current transaction, either by committing it or rolling it back.
  9528. **
  9529. ** ^When a connection (known as the blocked connection) fails to obtain a
  9530. ** shared-cache lock and SQLITE_LOCKED is returned to the caller, the
  9531. ** identity of the database connection (the blocking connection) that
  9532. ** has locked the required resource is stored internally. ^After an
  9533. ** application receives an SQLITE_LOCKED error, it may call the
  9534. ** sqlite3_unlock_notify() method with the blocked connection handle as
  9535. ** the first argument to register for a callback that will be invoked
  9536. ** when the blocking connections current transaction is concluded. ^The
  9537. ** callback is invoked from within the [sqlite3_step] or [sqlite3_close]
  9538. ** call that concludes the blocking connection's transaction.
  9539. **
  9540. ** ^(If sqlite3_unlock_notify() is called in a multi-threaded application,
  9541. ** there is a chance that the blocking connection will have already
  9542. ** concluded its transaction by the time sqlite3_unlock_notify() is invoked.
  9543. ** If this happens, then the specified callback is invoked immediately,
  9544. ** from within the call to sqlite3_unlock_notify().)^
  9545. **
  9546. ** ^If the blocked connection is attempting to obtain a write-lock on a
  9547. ** shared-cache table, and more than one other connection currently holds
  9548. ** a read-lock on the same table, then SQLite arbitrarily selects one of
  9549. ** the other connections to use as the blocking connection.
  9550. **
  9551. ** ^(There may be at most one unlock-notify callback registered by a
  9552. ** blocked connection. If sqlite3_unlock_notify() is called when the
  9553. ** blocked connection already has a registered unlock-notify callback,
  9554. ** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is
  9555. ** called with a NULL pointer as its second argument, then any existing
  9556. ** unlock-notify callback is canceled. ^The blocked connections
  9557. ** unlock-notify callback may also be canceled by closing the blocked
  9558. ** connection using [sqlite3_close()].
  9559. **
  9560. ** The unlock-notify callback is not reentrant. If an application invokes
  9561. ** any sqlite3_xxx API functions from within an unlock-notify callback, a
  9562. ** crash or deadlock may be the result.
  9563. **
  9564. ** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always
  9565. ** returns SQLITE_OK.
  9566. **
  9567. ** <b>Callback Invocation Details</b>
  9568. **
  9569. ** When an unlock-notify callback is registered, the application provides a
  9570. ** single void* pointer that is passed to the callback when it is invoked.
  9571. ** However, the signature of the callback function allows SQLite to pass
  9572. ** it an array of void* context pointers. The first argument passed to
  9573. ** an unlock-notify callback is a pointer to an array of void* pointers,
  9574. ** and the second is the number of entries in the array.
  9575. **
  9576. ** When a blocking connection's transaction is concluded, there may be
  9577. ** more than one blocked connection that has registered for an unlock-notify
  9578. ** callback. ^If two or more such blocked connections have specified the
  9579. ** same callback function, then instead of invoking the callback function
  9580. ** multiple times, it is invoked once with the set of void* context pointers
  9581. ** specified by the blocked connections bundled together into an array.
  9582. ** This gives the application an opportunity to prioritize any actions
  9583. ** related to the set of unblocked database connections.
  9584. **
  9585. ** <b>Deadlock Detection</b>
  9586. **
  9587. ** Assuming that after registering for an unlock-notify callback a
  9588. ** database waits for the callback to be issued before taking any further
  9589. ** action (a reasonable assumption), then using this API may cause the
  9590. ** application to deadlock. For example, if connection X is waiting for
  9591. ** connection Y's transaction to be concluded, and similarly connection
  9592. ** Y is waiting on connection X's transaction, then neither connection
  9593. ** will proceed and the system may remain deadlocked indefinitely.
  9594. **
  9595. ** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock
  9596. ** detection. ^If a given call to sqlite3_unlock_notify() would put the
  9597. ** system in a deadlocked state, then SQLITE_LOCKED is returned and no
  9598. ** unlock-notify callback is registered. The system is said to be in
  9599. ** a deadlocked state if connection A has registered for an unlock-notify
  9600. ** callback on the conclusion of connection B's transaction, and connection
  9601. ** B has itself registered for an unlock-notify callback when connection
  9602. ** A's transaction is concluded. ^Indirect deadlock is also detected, so
  9603. ** the system is also considered to be deadlocked if connection B has
  9604. ** registered for an unlock-notify callback on the conclusion of connection
  9605. ** C's transaction, where connection C is waiting on connection A. ^Any
  9606. ** number of levels of indirection are allowed.
  9607. **
  9608. ** <b>The "DROP TABLE" Exception</b>
  9609. **
  9610. ** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost
  9611. ** always appropriate to call sqlite3_unlock_notify(). There is however,
  9612. ** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement,
  9613. ** SQLite checks if there are any currently executing SELECT statements
  9614. ** that belong to the same connection. If there are, SQLITE_LOCKED is
  9615. ** returned. In this case there is no "blocking connection", so invoking
  9616. ** sqlite3_unlock_notify() results in the unlock-notify callback being
  9617. ** invoked immediately. If the application then re-attempts the "DROP TABLE"
  9618. ** or "DROP INDEX" query, an infinite loop might be the result.
  9619. **
  9620. ** One way around this problem is to check the extended error code returned
  9621. ** by an sqlite3_step() call. ^(If there is a blocking connection, then the
  9622. ** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in
  9623. ** the special "DROP TABLE/INDEX" case, the extended error code is just
  9624. ** SQLITE_LOCKED.)^
  9625. */
  9626. SQLITE_API int sqlite3_unlock_notify(
  9627. sqlite3 *pBlocked, /* Waiting connection */
  9628. void (*xNotify)(void **apArg, int nArg), /* Callback function to invoke */
  9629. void *pNotifyArg /* Argument to pass to xNotify */
  9630. );
  9631. /*
  9632. ** CAPI3REF: String Comparison
  9633. **
  9634. ** ^The [sqlite3_stricmp()] and [sqlite3_strnicmp()] APIs allow applications
  9635. ** and extensions to compare the contents of two buffers containing UTF-8
  9636. ** strings in a case-independent fashion, using the same definition of "case
  9637. ** independence" that SQLite uses internally when comparing identifiers.
  9638. */
  9639. SQLITE_API int sqlite3_stricmp(const char *, const char *);
  9640. SQLITE_API int sqlite3_strnicmp(const char *, const char *, int);
  9641. /*
  9642. ** CAPI3REF: String Globbing
  9643. *
  9644. ** ^The [sqlite3_strglob(P,X)] interface returns zero if and only if
  9645. ** string X matches the [GLOB] pattern P.
  9646. ** ^The definition of [GLOB] pattern matching used in
  9647. ** [sqlite3_strglob(P,X)] is the same as for the "X GLOB P" operator in the
  9648. ** SQL dialect understood by SQLite. ^The [sqlite3_strglob(P,X)] function
  9649. ** is case sensitive.
  9650. **
  9651. ** Note that this routine returns zero on a match and non-zero if the strings
  9652. ** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()].
  9653. **
  9654. ** See also: [sqlite3_strlike()].
  9655. */
  9656. SQLITE_API int sqlite3_strglob(const char *zGlob, const char *zStr);
  9657. /*
  9658. ** CAPI3REF: String LIKE Matching
  9659. *
  9660. ** ^The [sqlite3_strlike(P,X,E)] interface returns zero if and only if
  9661. ** string X matches the [LIKE] pattern P with escape character E.
  9662. ** ^The definition of [LIKE] pattern matching used in
  9663. ** [sqlite3_strlike(P,X,E)] is the same as for the "X LIKE P ESCAPE E"
  9664. ** operator in the SQL dialect understood by SQLite. ^For "X LIKE P" without
  9665. ** the ESCAPE clause, set the E parameter of [sqlite3_strlike(P,X,E)] to 0.
  9666. ** ^As with the LIKE operator, the [sqlite3_strlike(P,X,E)] function is case
  9667. ** insensitive - equivalent upper and lower case ASCII characters match
  9668. ** one another.
  9669. **
  9670. ** ^The [sqlite3_strlike(P,X,E)] function matches Unicode characters, though
  9671. ** only ASCII characters are case folded.
  9672. **
  9673. ** Note that this routine returns zero on a match and non-zero if the strings
  9674. ** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()].
  9675. **
  9676. ** See also: [sqlite3_strglob()].
  9677. */
  9678. SQLITE_API int sqlite3_strlike(const char *zGlob, const char *zStr, unsigned int cEsc);
  9679. /*
  9680. ** CAPI3REF: Error Logging Interface
  9681. **
  9682. ** ^The [sqlite3_log()] interface writes a message into the [error log]
  9683. ** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()].
  9684. ** ^If logging is enabled, the zFormat string and subsequent arguments are
  9685. ** used with [sqlite3_snprintf()] to generate the final output string.
  9686. **
  9687. ** The sqlite3_log() interface is intended for use by extensions such as
  9688. ** virtual tables, collating functions, and SQL functions. While there is
  9689. ** nothing to prevent an application from calling sqlite3_log(), doing so
  9690. ** is considered bad form.
  9691. **
  9692. ** The zFormat string must not be NULL.
  9693. **
  9694. ** To avoid deadlocks and other threading problems, the sqlite3_log() routine
  9695. ** will not use dynamically allocated memory. The log message is stored in
  9696. ** a fixed-length buffer on the stack. If the log message is longer than
  9697. ** a few hundred characters, it will be truncated to the length of the
  9698. ** buffer.
  9699. */
  9700. SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...);
  9701. /*
  9702. ** CAPI3REF: Write-Ahead Log Commit Hook
  9703. ** METHOD: sqlite3
  9704. **
  9705. ** ^The [sqlite3_wal_hook()] function is used to register a callback that
  9706. ** is invoked each time data is committed to a database in wal mode.
  9707. **
  9708. ** ^(The callback is invoked by SQLite after the commit has taken place and
  9709. ** the associated write-lock on the database released)^, so the implementation
  9710. ** may read, write or [checkpoint] the database as required.
  9711. **
  9712. ** ^The first parameter passed to the callback function when it is invoked
  9713. ** is a copy of the third parameter passed to sqlite3_wal_hook() when
  9714. ** registering the callback. ^The second is a copy of the database handle.
  9715. ** ^The third parameter is the name of the database that was written to -
  9716. ** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter
  9717. ** is the number of pages currently in the write-ahead log file,
  9718. ** including those that were just committed.
  9719. **
  9720. ** The callback function should normally return [SQLITE_OK]. ^If an error
  9721. ** code is returned, that error will propagate back up through the
  9722. ** SQLite code base to cause the statement that provoked the callback
  9723. ** to report an error, though the commit will have still occurred. If the
  9724. ** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value
  9725. ** that does not correspond to any valid SQLite error code, the results
  9726. ** are undefined.
  9727. **
  9728. ** A single database handle may have at most a single write-ahead log callback
  9729. ** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any
  9730. ** previously registered write-ahead log callback. ^Note that the
  9731. ** [sqlite3_wal_autocheckpoint()] interface and the
  9732. ** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will
  9733. ** overwrite any prior [sqlite3_wal_hook()] settings.
  9734. */
  9735. SQLITE_API void *sqlite3_wal_hook(
  9736. sqlite3*,
  9737. int(*)(void *,sqlite3*,const char*,int),
  9738. void*
  9739. );
  9740. /*
  9741. ** CAPI3REF: Configure an auto-checkpoint
  9742. ** METHOD: sqlite3
  9743. **
  9744. ** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around
  9745. ** [sqlite3_wal_hook()] that causes any database on [database connection] D
  9746. ** to automatically [checkpoint]
  9747. ** after committing a transaction if there are N or
  9748. ** more frames in the [write-ahead log] file. ^Passing zero or
  9749. ** a negative value as the nFrame parameter disables automatic
  9750. ** checkpoints entirely.
  9751. **
  9752. ** ^The callback registered by this function replaces any existing callback
  9753. ** registered using [sqlite3_wal_hook()]. ^Likewise, registering a callback
  9754. ** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism
  9755. ** configured by this function.
  9756. **
  9757. ** ^The [wal_autocheckpoint pragma] can be used to invoke this interface
  9758. ** from SQL.
  9759. **
  9760. ** ^Checkpoints initiated by this mechanism are
  9761. ** [sqlite3_wal_checkpoint_v2|PASSIVE].
  9762. **
  9763. ** ^Every new [database connection] defaults to having the auto-checkpoint
  9764. ** enabled with a threshold of 1000 or [SQLITE_DEFAULT_WAL_AUTOCHECKPOINT]
  9765. ** pages. The use of this interface
  9766. ** is only necessary if the default setting is found to be suboptimal
  9767. ** for a particular application.
  9768. */
  9769. SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int N);
  9770. /*
  9771. ** CAPI3REF: Checkpoint a database
  9772. ** METHOD: sqlite3
  9773. **
  9774. ** ^(The sqlite3_wal_checkpoint(D,X) is equivalent to
  9775. ** [sqlite3_wal_checkpoint_v2](D,X,[SQLITE_CHECKPOINT_PASSIVE],0,0).)^
  9776. **
  9777. ** In brief, sqlite3_wal_checkpoint(D,X) causes the content in the
  9778. ** [write-ahead log] for database X on [database connection] D to be
  9779. ** transferred into the database file and for the write-ahead log to
  9780. ** be reset. See the [checkpointing] documentation for addition
  9781. ** information.
  9782. **
  9783. ** This interface used to be the only way to cause a checkpoint to
  9784. ** occur. But then the newer and more powerful [sqlite3_wal_checkpoint_v2()]
  9785. ** interface was added. This interface is retained for backwards
  9786. ** compatibility and as a convenience for applications that need to manually
  9787. ** start a callback but which do not need the full power (and corresponding
  9788. ** complication) of [sqlite3_wal_checkpoint_v2()].
  9789. */
  9790. SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb);
  9791. /*
  9792. ** CAPI3REF: Checkpoint a database
  9793. ** METHOD: sqlite3
  9794. **
  9795. ** ^(The sqlite3_wal_checkpoint_v2(D,X,M,L,C) interface runs a checkpoint
  9796. ** operation on database X of [database connection] D in mode M. Status
  9797. ** information is written back into integers pointed to by L and C.)^
  9798. ** ^(The M parameter must be a valid [checkpoint mode]:)^
  9799. **
  9800. ** <dl>
  9801. ** <dt>SQLITE_CHECKPOINT_PASSIVE<dd>
  9802. ** ^Checkpoint as many frames as possible without waiting for any database
  9803. ** readers or writers to finish, then sync the database file if all frames
  9804. ** in the log were checkpointed. ^The [busy-handler callback]
  9805. ** is never invoked in the SQLITE_CHECKPOINT_PASSIVE mode.
  9806. ** ^On the other hand, passive mode might leave the checkpoint unfinished
  9807. ** if there are concurrent readers or writers.
  9808. **
  9809. ** <dt>SQLITE_CHECKPOINT_FULL<dd>
  9810. ** ^This mode blocks (it invokes the
  9811. ** [sqlite3_busy_handler|busy-handler callback]) until there is no
  9812. ** database writer and all readers are reading from the most recent database
  9813. ** snapshot. ^It then checkpoints all frames in the log file and syncs the
  9814. ** database file. ^This mode blocks new database writers while it is pending,
  9815. ** but new database readers are allowed to continue unimpeded.
  9816. **
  9817. ** <dt>SQLITE_CHECKPOINT_RESTART<dd>
  9818. ** ^This mode works the same way as SQLITE_CHECKPOINT_FULL with the addition
  9819. ** that after checkpointing the log file it blocks (calls the
  9820. ** [busy-handler callback])
  9821. ** until all readers are reading from the database file only. ^This ensures
  9822. ** that the next writer will restart the log file from the beginning.
  9823. ** ^Like SQLITE_CHECKPOINT_FULL, this mode blocks new
  9824. ** database writer attempts while it is pending, but does not impede readers.
  9825. **
  9826. ** <dt>SQLITE_CHECKPOINT_TRUNCATE<dd>
  9827. ** ^This mode works the same way as SQLITE_CHECKPOINT_RESTART with the
  9828. ** addition that it also truncates the log file to zero bytes just prior
  9829. ** to a successful return.
  9830. ** </dl>
  9831. **
  9832. ** ^If pnLog is not NULL, then *pnLog is set to the total number of frames in
  9833. ** the log file or to -1 if the checkpoint could not run because
  9834. ** of an error or because the database is not in [WAL mode]. ^If pnCkpt is not
  9835. ** NULL,then *pnCkpt is set to the total number of checkpointed frames in the
  9836. ** log file (including any that were already checkpointed before the function
  9837. ** was called) or to -1 if the checkpoint could not run due to an error or
  9838. ** because the database is not in WAL mode. ^Note that upon successful
  9839. ** completion of an SQLITE_CHECKPOINT_TRUNCATE, the log file will have been
  9840. ** truncated to zero bytes and so both *pnLog and *pnCkpt will be set to zero.
  9841. **
  9842. ** ^All calls obtain an exclusive "checkpoint" lock on the database file. ^If
  9843. ** any other process is running a checkpoint operation at the same time, the
  9844. ** lock cannot be obtained and SQLITE_BUSY is returned. ^Even if there is a
  9845. ** busy-handler configured, it will not be invoked in this case.
  9846. **
  9847. ** ^The SQLITE_CHECKPOINT_FULL, RESTART and TRUNCATE modes also obtain the
  9848. ** exclusive "writer" lock on the database file. ^If the writer lock cannot be
  9849. ** obtained immediately, and a busy-handler is configured, it is invoked and
  9850. ** the writer lock retried until either the busy-handler returns 0 or the lock
  9851. ** is successfully obtained. ^The busy-handler is also invoked while waiting for
  9852. ** database readers as described above. ^If the busy-handler returns 0 before
  9853. ** the writer lock is obtained or while waiting for database readers, the
  9854. ** checkpoint operation proceeds from that point in the same way as
  9855. ** SQLITE_CHECKPOINT_PASSIVE - checkpointing as many frames as possible
  9856. ** without blocking any further. ^SQLITE_BUSY is returned in this case.
  9857. **
  9858. ** ^If parameter zDb is NULL or points to a zero length string, then the
  9859. ** specified operation is attempted on all WAL databases [attached] to
  9860. ** [database connection] db. In this case the
  9861. ** values written to output parameters *pnLog and *pnCkpt are undefined. ^If
  9862. ** an SQLITE_BUSY error is encountered when processing one or more of the
  9863. ** attached WAL databases, the operation is still attempted on any remaining
  9864. ** attached databases and SQLITE_BUSY is returned at the end. ^If any other
  9865. ** error occurs while processing an attached database, processing is abandoned
  9866. ** and the error code is returned to the caller immediately. ^If no error
  9867. ** (SQLITE_BUSY or otherwise) is encountered while processing the attached
  9868. ** databases, SQLITE_OK is returned.
  9869. **
  9870. ** ^If database zDb is the name of an attached database that is not in WAL
  9871. ** mode, SQLITE_OK is returned and both *pnLog and *pnCkpt set to -1. ^If
  9872. ** zDb is not NULL (or a zero length string) and is not the name of any
  9873. ** attached database, SQLITE_ERROR is returned to the caller.
  9874. **
  9875. ** ^Unless it returns SQLITE_MISUSE,
  9876. ** the sqlite3_wal_checkpoint_v2() interface
  9877. ** sets the error information that is queried by
  9878. ** [sqlite3_errcode()] and [sqlite3_errmsg()].
  9879. **
  9880. ** ^The [PRAGMA wal_checkpoint] command can be used to invoke this interface
  9881. ** from SQL.
  9882. */
  9883. SQLITE_API int sqlite3_wal_checkpoint_v2(
  9884. sqlite3 *db, /* Database handle */
  9885. const char *zDb, /* Name of attached database (or NULL) */
  9886. int eMode, /* SQLITE_CHECKPOINT_* value */
  9887. int *pnLog, /* OUT: Size of WAL log in frames */
  9888. int *pnCkpt /* OUT: Total number of frames checkpointed */
  9889. );
  9890. /*
  9891. ** CAPI3REF: Checkpoint Mode Values
  9892. ** KEYWORDS: {checkpoint mode}
  9893. **
  9894. ** These constants define all valid values for the "checkpoint mode" passed
  9895. ** as the third parameter to the [sqlite3_wal_checkpoint_v2()] interface.
  9896. ** See the [sqlite3_wal_checkpoint_v2()] documentation for details on the
  9897. ** meaning of each of these checkpoint modes.
  9898. */
  9899. #define SQLITE_CHECKPOINT_PASSIVE 0 /* Do as much as possible w/o blocking */
  9900. #define SQLITE_CHECKPOINT_FULL 1 /* Wait for writers, then checkpoint */
  9901. #define SQLITE_CHECKPOINT_RESTART 2 /* Like FULL but wait for for readers */
  9902. #define SQLITE_CHECKPOINT_TRUNCATE 3 /* Like RESTART but also truncate WAL */
  9903. /*
  9904. ** CAPI3REF: Virtual Table Interface Configuration
  9905. **
  9906. ** This function may be called by either the [xConnect] or [xCreate] method
  9907. ** of a [virtual table] implementation to configure
  9908. ** various facets of the virtual table interface.
  9909. **
  9910. ** If this interface is invoked outside the context of an xConnect or
  9911. ** xCreate virtual table method then the behavior is undefined.
  9912. **
  9913. ** In the call sqlite3_vtab_config(D,C,...) the D parameter is the
  9914. ** [database connection] in which the virtual table is being created and
  9915. ** which is passed in as the first argument to the [xConnect] or [xCreate]
  9916. ** method that is invoking sqlite3_vtab_config(). The C parameter is one
  9917. ** of the [virtual table configuration options]. The presence and meaning
  9918. ** of parameters after C depend on which [virtual table configuration option]
  9919. ** is used.
  9920. */
  9921. SQLITE_API int sqlite3_vtab_config(sqlite3*, int op, ...);
  9922. /*
  9923. ** CAPI3REF: Virtual Table Configuration Options
  9924. ** KEYWORDS: {virtual table configuration options}
  9925. ** KEYWORDS: {virtual table configuration option}
  9926. **
  9927. ** These macros define the various options to the
  9928. ** [sqlite3_vtab_config()] interface that [virtual table] implementations
  9929. ** can use to customize and optimize their behavior.
  9930. **
  9931. ** <dl>
  9932. ** [[SQLITE_VTAB_CONSTRAINT_SUPPORT]]
  9933. ** <dt>SQLITE_VTAB_CONSTRAINT_SUPPORT</dt>
  9934. ** <dd>Calls of the form
  9935. ** [sqlite3_vtab_config](db,SQLITE_VTAB_CONSTRAINT_SUPPORT,X) are supported,
  9936. ** where X is an integer. If X is zero, then the [virtual table] whose
  9937. ** [xCreate] or [xConnect] method invoked [sqlite3_vtab_config()] does not
  9938. ** support constraints. In this configuration (which is the default) if
  9939. ** a call to the [xUpdate] method returns [SQLITE_CONSTRAINT], then the entire
  9940. ** statement is rolled back as if [ON CONFLICT | OR ABORT] had been
  9941. ** specified as part of the users SQL statement, regardless of the actual
  9942. ** ON CONFLICT mode specified.
  9943. **
  9944. ** If X is non-zero, then the virtual table implementation guarantees
  9945. ** that if [xUpdate] returns [SQLITE_CONSTRAINT], it will do so before
  9946. ** any modifications to internal or persistent data structures have been made.
  9947. ** If the [ON CONFLICT] mode is ABORT, FAIL, IGNORE or ROLLBACK, SQLite
  9948. ** is able to roll back a statement or database transaction, and abandon
  9949. ** or continue processing the current SQL statement as appropriate.
  9950. ** If the ON CONFLICT mode is REPLACE and the [xUpdate] method returns
  9951. ** [SQLITE_CONSTRAINT], SQLite handles this as if the ON CONFLICT mode
  9952. ** had been ABORT.
  9953. **
  9954. ** Virtual table implementations that are required to handle OR REPLACE
  9955. ** must do so within the [xUpdate] method. If a call to the
  9956. ** [sqlite3_vtab_on_conflict()] function indicates that the current ON
  9957. ** CONFLICT policy is REPLACE, the virtual table implementation should
  9958. ** silently replace the appropriate rows within the xUpdate callback and
  9959. ** return SQLITE_OK. Or, if this is not possible, it may return
  9960. ** SQLITE_CONSTRAINT, in which case SQLite falls back to OR ABORT
  9961. ** constraint handling.
  9962. ** </dd>
  9963. **
  9964. ** [[SQLITE_VTAB_DIRECTONLY]]<dt>SQLITE_VTAB_DIRECTONLY</dt>
  9965. ** <dd>Calls of the form
  9966. ** [sqlite3_vtab_config](db,SQLITE_VTAB_DIRECTONLY) from within the
  9967. ** the [xConnect] or [xCreate] methods of a [virtual table] implmentation
  9968. ** prohibits that virtual table from being used from within triggers and
  9969. ** views.
  9970. ** </dd>
  9971. **
  9972. ** [[SQLITE_VTAB_INNOCUOUS]]<dt>SQLITE_VTAB_INNOCUOUS</dt>
  9973. ** <dd>Calls of the form
  9974. ** [sqlite3_vtab_config](db,SQLITE_VTAB_INNOCUOUS) from within the
  9975. ** the [xConnect] or [xCreate] methods of a [virtual table] implmentation
  9976. ** identify that virtual table as being safe to use from within triggers
  9977. ** and views. Conceptually, the SQLITE_VTAB_INNOCUOUS tag means that the
  9978. ** virtual table can do no serious harm even if it is controlled by a
  9979. ** malicious hacker. Developers should avoid setting the SQLITE_VTAB_INNOCUOUS
  9980. ** flag unless absolutely necessary.
  9981. ** </dd>
  9982. ** </dl>
  9983. */
  9984. #define SQLITE_VTAB_CONSTRAINT_SUPPORT 1
  9985. #define SQLITE_VTAB_INNOCUOUS 2
  9986. #define SQLITE_VTAB_DIRECTONLY 3
  9987. /*
  9988. ** CAPI3REF: Determine The Virtual Table Conflict Policy
  9989. **
  9990. ** This function may only be called from within a call to the [xUpdate] method
  9991. ** of a [virtual table] implementation for an INSERT or UPDATE operation. ^The
  9992. ** value returned is one of [SQLITE_ROLLBACK], [SQLITE_IGNORE], [SQLITE_FAIL],
  9993. ** [SQLITE_ABORT], or [SQLITE_REPLACE], according to the [ON CONFLICT] mode
  9994. ** of the SQL statement that triggered the call to the [xUpdate] method of the
  9995. ** [virtual table].
  9996. */
  9997. SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *);
  9998. /*
  9999. ** CAPI3REF: Determine If Virtual Table Column Access Is For UPDATE
  10000. **
  10001. ** If the sqlite3_vtab_nochange(X) routine is called within the [xColumn]
  10002. ** method of a [virtual table], then it returns true if and only if the
  10003. ** column is being fetched as part of an UPDATE operation during which the
  10004. ** column value will not change. Applications might use this to substitute
  10005. ** a return value that is less expensive to compute and that the corresponding
  10006. ** [xUpdate] method understands as a "no-change" value.
  10007. **
  10008. ** If the [xColumn] method calls sqlite3_vtab_nochange() and finds that
  10009. ** the column is not changed by the UPDATE statement, then the xColumn
  10010. ** method can optionally return without setting a result, without calling
  10011. ** any of the [sqlite3_result_int|sqlite3_result_xxxxx() interfaces].
  10012. ** In that case, [sqlite3_value_nochange(X)] will return true for the
  10013. ** same column in the [xUpdate] method.
  10014. */
  10015. SQLITE_API int sqlite3_vtab_nochange(sqlite3_context*);
  10016. /*
  10017. ** CAPI3REF: Determine The Collation For a Virtual Table Constraint
  10018. **
  10019. ** This function may only be called from within a call to the [xBestIndex]
  10020. ** method of a [virtual table].
  10021. **
  10022. ** The first argument must be the sqlite3_index_info object that is the
  10023. ** first parameter to the xBestIndex() method. The second argument must be
  10024. ** an index into the aConstraint[] array belonging to the sqlite3_index_info
  10025. ** structure passed to xBestIndex. This function returns a pointer to a buffer
  10026. ** containing the name of the collation sequence for the corresponding
  10027. ** constraint.
  10028. */
  10029. SQLITE_API SQLITE_EXPERIMENTAL const char *sqlite3_vtab_collation(sqlite3_index_info*,int);
  10030. /*
  10031. ** CAPI3REF: Conflict resolution modes
  10032. ** KEYWORDS: {conflict resolution mode}
  10033. **
  10034. ** These constants are returned by [sqlite3_vtab_on_conflict()] to
  10035. ** inform a [virtual table] implementation what the [ON CONFLICT] mode
  10036. ** is for the SQL statement being evaluated.
  10037. **
  10038. ** Note that the [SQLITE_IGNORE] constant is also used as a potential
  10039. ** return value from the [sqlite3_set_authorizer()] callback and that
  10040. ** [SQLITE_ABORT] is also a [result code].
  10041. */
  10042. #define SQLITE_ROLLBACK 1
  10043. /* #define SQLITE_IGNORE 2 // Also used by sqlite3_authorizer() callback */
  10044. #define SQLITE_FAIL 3
  10045. /* #define SQLITE_ABORT 4 // Also an error code */
  10046. #define SQLITE_REPLACE 5
  10047. /*
  10048. ** CAPI3REF: Prepared Statement Scan Status Opcodes
  10049. ** KEYWORDS: {scanstatus options}
  10050. **
  10051. ** The following constants can be used for the T parameter to the
  10052. ** [sqlite3_stmt_scanstatus(S,X,T,V)] interface. Each constant designates a
  10053. ** different metric for sqlite3_stmt_scanstatus() to return.
  10054. **
  10055. ** When the value returned to V is a string, space to hold that string is
  10056. ** managed by the prepared statement S and will be automatically freed when
  10057. ** S is finalized.
  10058. **
  10059. ** <dl>
  10060. ** [[SQLITE_SCANSTAT_NLOOP]] <dt>SQLITE_SCANSTAT_NLOOP</dt>
  10061. ** <dd>^The [sqlite3_int64] variable pointed to by the V parameter will be
  10062. ** set to the total number of times that the X-th loop has run.</dd>
  10063. **
  10064. ** [[SQLITE_SCANSTAT_NVISIT]] <dt>SQLITE_SCANSTAT_NVISIT</dt>
  10065. ** <dd>^The [sqlite3_int64] variable pointed to by the V parameter will be set
  10066. ** to the total number of rows examined by all iterations of the X-th loop.</dd>
  10067. **
  10068. ** [[SQLITE_SCANSTAT_EST]] <dt>SQLITE_SCANSTAT_EST</dt>
  10069. ** <dd>^The "double" variable pointed to by the V parameter will be set to the
  10070. ** query planner's estimate for the average number of rows output from each
  10071. ** iteration of the X-th loop. If the query planner's estimates was accurate,
  10072. ** then this value will approximate the quotient NVISIT/NLOOP and the
  10073. ** product of this value for all prior loops with the same SELECTID will
  10074. ** be the NLOOP value for the current loop.
  10075. **
  10076. ** [[SQLITE_SCANSTAT_NAME]] <dt>SQLITE_SCANSTAT_NAME</dt>
  10077. ** <dd>^The "const char *" variable pointed to by the V parameter will be set
  10078. ** to a zero-terminated UTF-8 string containing the name of the index or table
  10079. ** used for the X-th loop.
  10080. **
  10081. ** [[SQLITE_SCANSTAT_EXPLAIN]] <dt>SQLITE_SCANSTAT_EXPLAIN</dt>
  10082. ** <dd>^The "const char *" variable pointed to by the V parameter will be set
  10083. ** to a zero-terminated UTF-8 string containing the [EXPLAIN QUERY PLAN]
  10084. ** description for the X-th loop.
  10085. **
  10086. ** [[SQLITE_SCANSTAT_SELECTID]] <dt>SQLITE_SCANSTAT_SELECT</dt>
  10087. ** <dd>^The "int" variable pointed to by the V parameter will be set to the
  10088. ** "select-id" for the X-th loop. The select-id identifies which query or
  10089. ** subquery the loop is part of. The main query has a select-id of zero.
  10090. ** The select-id is the same value as is output in the first column
  10091. ** of an [EXPLAIN QUERY PLAN] query.
  10092. ** </dl>
  10093. */
  10094. #define SQLITE_SCANSTAT_NLOOP 0
  10095. #define SQLITE_SCANSTAT_NVISIT 1
  10096. #define SQLITE_SCANSTAT_EST 2
  10097. #define SQLITE_SCANSTAT_NAME 3
  10098. #define SQLITE_SCANSTAT_EXPLAIN 4
  10099. #define SQLITE_SCANSTAT_SELECTID 5
  10100. /*
  10101. ** CAPI3REF: Prepared Statement Scan Status
  10102. ** METHOD: sqlite3_stmt
  10103. **
  10104. ** This interface returns information about the predicted and measured
  10105. ** performance for pStmt. Advanced applications can use this
  10106. ** interface to compare the predicted and the measured performance and
  10107. ** issue warnings and/or rerun [ANALYZE] if discrepancies are found.
  10108. **
  10109. ** Since this interface is expected to be rarely used, it is only
  10110. ** available if SQLite is compiled using the [SQLITE_ENABLE_STMT_SCANSTATUS]
  10111. ** compile-time option.
  10112. **
  10113. ** The "iScanStatusOp" parameter determines which status information to return.
  10114. ** The "iScanStatusOp" must be one of the [scanstatus options] or the behavior
  10115. ** of this interface is undefined.
  10116. ** ^The requested measurement is written into a variable pointed to by
  10117. ** the "pOut" parameter.
  10118. ** Parameter "idx" identifies the specific loop to retrieve statistics for.
  10119. ** Loops are numbered starting from zero. ^If idx is out of range - less than
  10120. ** zero or greater than or equal to the total number of loops used to implement
  10121. ** the statement - a non-zero value is returned and the variable that pOut
  10122. ** points to is unchanged.
  10123. **
  10124. ** ^Statistics might not be available for all loops in all statements. ^In cases
  10125. ** where there exist loops with no available statistics, this function behaves
  10126. ** as if the loop did not exist - it returns non-zero and leave the variable
  10127. ** that pOut points to unchanged.
  10128. **
  10129. ** See also: [sqlite3_stmt_scanstatus_reset()]
  10130. */
  10131. SQLITE_API int sqlite3_stmt_scanstatus(
  10132. sqlite3_stmt *pStmt, /* Prepared statement for which info desired */
  10133. int idx, /* Index of loop to report on */
  10134. int iScanStatusOp, /* Information desired. SQLITE_SCANSTAT_* */
  10135. void *pOut /* Result written here */
  10136. );
  10137. /*
  10138. ** CAPI3REF: Zero Scan-Status Counters
  10139. ** METHOD: sqlite3_stmt
  10140. **
  10141. ** ^Zero all [sqlite3_stmt_scanstatus()] related event counters.
  10142. **
  10143. ** This API is only available if the library is built with pre-processor
  10144. ** symbol [SQLITE_ENABLE_STMT_SCANSTATUS] defined.
  10145. */
  10146. SQLITE_API void sqlite3_stmt_scanstatus_reset(sqlite3_stmt*);
  10147. /*
  10148. ** CAPI3REF: Flush caches to disk mid-transaction
  10149. **
  10150. ** ^If a write-transaction is open on [database connection] D when the
  10151. ** [sqlite3_db_cacheflush(D)] interface invoked, any dirty
  10152. ** pages in the pager-cache that are not currently in use are written out
  10153. ** to disk. A dirty page may be in use if a database cursor created by an
  10154. ** active SQL statement is reading from it, or if it is page 1 of a database
  10155. ** file (page 1 is always "in use"). ^The [sqlite3_db_cacheflush(D)]
  10156. ** interface flushes caches for all schemas - "main", "temp", and
  10157. ** any [attached] databases.
  10158. **
  10159. ** ^If this function needs to obtain extra database locks before dirty pages
  10160. ** can be flushed to disk, it does so. ^If those locks cannot be obtained
  10161. ** immediately and there is a busy-handler callback configured, it is invoked
  10162. ** in the usual manner. ^If the required lock still cannot be obtained, then
  10163. ** the database is skipped and an attempt made to flush any dirty pages
  10164. ** belonging to the next (if any) database. ^If any databases are skipped
  10165. ** because locks cannot be obtained, but no other error occurs, this
  10166. ** function returns SQLITE_BUSY.
  10167. **
  10168. ** ^If any other error occurs while flushing dirty pages to disk (for
  10169. ** example an IO error or out-of-memory condition), then processing is
  10170. ** abandoned and an SQLite [error code] is returned to the caller immediately.
  10171. **
  10172. ** ^Otherwise, if no error occurs, [sqlite3_db_cacheflush()] returns SQLITE_OK.
  10173. **
  10174. ** ^This function does not set the database handle error code or message
  10175. ** returned by the [sqlite3_errcode()] and [sqlite3_errmsg()] functions.
  10176. */
  10177. SQLITE_API int sqlite3_db_cacheflush(sqlite3*);
  10178. /*
  10179. ** CAPI3REF: The pre-update hook.
  10180. **
  10181. ** ^These interfaces are only available if SQLite is compiled using the
  10182. ** [SQLITE_ENABLE_PREUPDATE_HOOK] compile-time option.
  10183. **
  10184. ** ^The [sqlite3_preupdate_hook()] interface registers a callback function
  10185. ** that is invoked prior to each [INSERT], [UPDATE], and [DELETE] operation
  10186. ** on a database table.
  10187. ** ^At most one preupdate hook may be registered at a time on a single
  10188. ** [database connection]; each call to [sqlite3_preupdate_hook()] overrides
  10189. ** the previous setting.
  10190. ** ^The preupdate hook is disabled by invoking [sqlite3_preupdate_hook()]
  10191. ** with a NULL pointer as the second parameter.
  10192. ** ^The third parameter to [sqlite3_preupdate_hook()] is passed through as
  10193. ** the first parameter to callbacks.
  10194. **
  10195. ** ^The preupdate hook only fires for changes to real database tables; the
  10196. ** preupdate hook is not invoked for changes to [virtual tables] or to
  10197. ** system tables like sqlite_master or sqlite_stat1.
  10198. **
  10199. ** ^The second parameter to the preupdate callback is a pointer to
  10200. ** the [database connection] that registered the preupdate hook.
  10201. ** ^The third parameter to the preupdate callback is one of the constants
  10202. ** [SQLITE_INSERT], [SQLITE_DELETE], or [SQLITE_UPDATE] to identify the
  10203. ** kind of update operation that is about to occur.
  10204. ** ^(The fourth parameter to the preupdate callback is the name of the
  10205. ** database within the database connection that is being modified. This
  10206. ** will be "main" for the main database or "temp" for TEMP tables or
  10207. ** the name given after the AS keyword in the [ATTACH] statement for attached
  10208. ** databases.)^
  10209. ** ^The fifth parameter to the preupdate callback is the name of the
  10210. ** table that is being modified.
  10211. **
  10212. ** For an UPDATE or DELETE operation on a [rowid table], the sixth
  10213. ** parameter passed to the preupdate callback is the initial [rowid] of the
  10214. ** row being modified or deleted. For an INSERT operation on a rowid table,
  10215. ** or any operation on a WITHOUT ROWID table, the value of the sixth
  10216. ** parameter is undefined. For an INSERT or UPDATE on a rowid table the
  10217. ** seventh parameter is the final rowid value of the row being inserted
  10218. ** or updated. The value of the seventh parameter passed to the callback
  10219. ** function is not defined for operations on WITHOUT ROWID tables, or for
  10220. ** INSERT operations on rowid tables.
  10221. **
  10222. ** The [sqlite3_preupdate_old()], [sqlite3_preupdate_new()],
  10223. ** [sqlite3_preupdate_count()], and [sqlite3_preupdate_depth()] interfaces
  10224. ** provide additional information about a preupdate event. These routines
  10225. ** may only be called from within a preupdate callback. Invoking any of
  10226. ** these routines from outside of a preupdate callback or with a
  10227. ** [database connection] pointer that is different from the one supplied
  10228. ** to the preupdate callback results in undefined and probably undesirable
  10229. ** behavior.
  10230. **
  10231. ** ^The [sqlite3_preupdate_count(D)] interface returns the number of columns
  10232. ** in the row that is being inserted, updated, or deleted.
  10233. **
  10234. ** ^The [sqlite3_preupdate_old(D,N,P)] interface writes into P a pointer to
  10235. ** a [protected sqlite3_value] that contains the value of the Nth column of
  10236. ** the table row before it is updated. The N parameter must be between 0
  10237. ** and one less than the number of columns or the behavior will be
  10238. ** undefined. This must only be used within SQLITE_UPDATE and SQLITE_DELETE
  10239. ** preupdate callbacks; if it is used by an SQLITE_INSERT callback then the
  10240. ** behavior is undefined. The [sqlite3_value] that P points to
  10241. ** will be destroyed when the preupdate callback returns.
  10242. **
  10243. ** ^The [sqlite3_preupdate_new(D,N,P)] interface writes into P a pointer to
  10244. ** a [protected sqlite3_value] that contains the value of the Nth column of
  10245. ** the table row after it is updated. The N parameter must be between 0
  10246. ** and one less than the number of columns or the behavior will be
  10247. ** undefined. This must only be used within SQLITE_INSERT and SQLITE_UPDATE
  10248. ** preupdate callbacks; if it is used by an SQLITE_DELETE callback then the
  10249. ** behavior is undefined. The [sqlite3_value] that P points to
  10250. ** will be destroyed when the preupdate callback returns.
  10251. **
  10252. ** ^The [sqlite3_preupdate_depth(D)] interface returns 0 if the preupdate
  10253. ** callback was invoked as a result of a direct insert, update, or delete
  10254. ** operation; or 1 for inserts, updates, or deletes invoked by top-level
  10255. ** triggers; or 2 for changes resulting from triggers called by top-level
  10256. ** triggers; and so forth.
  10257. **
  10258. ** See also: [sqlite3_update_hook()]
  10259. */
  10260. #if defined(SQLITE_ENABLE_PREUPDATE_HOOK)
  10261. SQLITE_API void *sqlite3_preupdate_hook(
  10262. sqlite3 *db,
  10263. void(*xPreUpdate)(
  10264. void *pCtx, /* Copy of third arg to preupdate_hook() */
  10265. sqlite3 *db, /* Database handle */
  10266. int op, /* SQLITE_UPDATE, DELETE or INSERT */
  10267. char const *zDb, /* Database name */
  10268. char const *zName, /* Table name */
  10269. sqlite3_int64 iKey1, /* Rowid of row about to be deleted/updated */
  10270. sqlite3_int64 iKey2 /* New rowid value (for a rowid UPDATE) */
  10271. ),
  10272. void*
  10273. );
  10274. SQLITE_API int sqlite3_preupdate_old(sqlite3 *, int, sqlite3_value **);
  10275. SQLITE_API int sqlite3_preupdate_count(sqlite3 *);
  10276. SQLITE_API int sqlite3_preupdate_depth(sqlite3 *);
  10277. SQLITE_API int sqlite3_preupdate_new(sqlite3 *, int, sqlite3_value **);
  10278. #endif
  10279. /*
  10280. ** CAPI3REF: Low-level system error code
  10281. **
  10282. ** ^Attempt to return the underlying operating system error code or error
  10283. ** number that caused the most recent I/O error or failure to open a file.
  10284. ** The return value is OS-dependent. For example, on unix systems, after
  10285. ** [sqlite3_open_v2()] returns [SQLITE_CANTOPEN], this interface could be
  10286. ** called to get back the underlying "errno" that caused the problem, such
  10287. ** as ENOSPC, EAUTH, EISDIR, and so forth.
  10288. */
  10289. SQLITE_API int sqlite3_system_errno(sqlite3*);
  10290. /*
  10291. ** CAPI3REF: Database Snapshot
  10292. ** KEYWORDS: {snapshot} {sqlite3_snapshot}
  10293. **
  10294. ** An instance of the snapshot object records the state of a [WAL mode]
  10295. ** database for some specific point in history.
  10296. **
  10297. ** In [WAL mode], multiple [database connections] that are open on the
  10298. ** same database file can each be reading a different historical version
  10299. ** of the database file. When a [database connection] begins a read
  10300. ** transaction, that connection sees an unchanging copy of the database
  10301. ** as it existed for the point in time when the transaction first started.
  10302. ** Subsequent changes to the database from other connections are not seen
  10303. ** by the reader until a new read transaction is started.
  10304. **
  10305. ** The sqlite3_snapshot object records state information about an historical
  10306. ** version of the database file so that it is possible to later open a new read
  10307. ** transaction that sees that historical version of the database rather than
  10308. ** the most recent version.
  10309. */
  10310. typedef struct sqlite3_snapshot {
  10311. unsigned char hidden[48];
  10312. } sqlite3_snapshot;
  10313. /*
  10314. ** CAPI3REF: Record A Database Snapshot
  10315. ** CONSTRUCTOR: sqlite3_snapshot
  10316. **
  10317. ** ^The [sqlite3_snapshot_get(D,S,P)] interface attempts to make a
  10318. ** new [sqlite3_snapshot] object that records the current state of
  10319. ** schema S in database connection D. ^On success, the
  10320. ** [sqlite3_snapshot_get(D,S,P)] interface writes a pointer to the newly
  10321. ** created [sqlite3_snapshot] object into *P and returns SQLITE_OK.
  10322. ** If there is not already a read-transaction open on schema S when
  10323. ** this function is called, one is opened automatically.
  10324. **
  10325. ** The following must be true for this function to succeed. If any of
  10326. ** the following statements are false when sqlite3_snapshot_get() is
  10327. ** called, SQLITE_ERROR is returned. The final value of *P is undefined
  10328. ** in this case.
  10329. **
  10330. ** <ul>
  10331. ** <li> The database handle must not be in [autocommit mode].
  10332. **
  10333. ** <li> Schema S of [database connection] D must be a [WAL mode] database.
  10334. **
  10335. ** <li> There must not be a write transaction open on schema S of database
  10336. ** connection D.
  10337. **
  10338. ** <li> One or more transactions must have been written to the current wal
  10339. ** file since it was created on disk (by any connection). This means
  10340. ** that a snapshot cannot be taken on a wal mode database with no wal
  10341. ** file immediately after it is first opened. At least one transaction
  10342. ** must be written to it first.
  10343. ** </ul>
  10344. **
  10345. ** This function may also return SQLITE_NOMEM. If it is called with the
  10346. ** database handle in autocommit mode but fails for some other reason,
  10347. ** whether or not a read transaction is opened on schema S is undefined.
  10348. **
  10349. ** The [sqlite3_snapshot] object returned from a successful call to
  10350. ** [sqlite3_snapshot_get()] must be freed using [sqlite3_snapshot_free()]
  10351. ** to avoid a memory leak.
  10352. **
  10353. ** The [sqlite3_snapshot_get()] interface is only available when the
  10354. ** [SQLITE_ENABLE_SNAPSHOT] compile-time option is used.
  10355. */
  10356. SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_get(
  10357. sqlite3 *db,
  10358. const char *zSchema,
  10359. sqlite3_snapshot **ppSnapshot
  10360. );
  10361. /*
  10362. ** CAPI3REF: Start a read transaction on an historical snapshot
  10363. ** METHOD: sqlite3_snapshot
  10364. **
  10365. ** ^The [sqlite3_snapshot_open(D,S,P)] interface either starts a new read
  10366. ** transaction or upgrades an existing one for schema S of
  10367. ** [database connection] D such that the read transaction refers to
  10368. ** historical [snapshot] P, rather than the most recent change to the
  10369. ** database. ^The [sqlite3_snapshot_open()] interface returns SQLITE_OK
  10370. ** on success or an appropriate [error code] if it fails.
  10371. **
  10372. ** ^In order to succeed, the database connection must not be in
  10373. ** [autocommit mode] when [sqlite3_snapshot_open(D,S,P)] is called. If there
  10374. ** is already a read transaction open on schema S, then the database handle
  10375. ** must have no active statements (SELECT statements that have been passed
  10376. ** to sqlite3_step() but not sqlite3_reset() or sqlite3_finalize()).
  10377. ** SQLITE_ERROR is returned if either of these conditions is violated, or
  10378. ** if schema S does not exist, or if the snapshot object is invalid.
  10379. **
  10380. ** ^A call to sqlite3_snapshot_open() will fail to open if the specified
  10381. ** snapshot has been overwritten by a [checkpoint]. In this case
  10382. ** SQLITE_ERROR_SNAPSHOT is returned.
  10383. **
  10384. ** If there is already a read transaction open when this function is
  10385. ** invoked, then the same read transaction remains open (on the same
  10386. ** database snapshot) if SQLITE_ERROR, SQLITE_BUSY or SQLITE_ERROR_SNAPSHOT
  10387. ** is returned. If another error code - for example SQLITE_PROTOCOL or an
  10388. ** SQLITE_IOERR error code - is returned, then the final state of the
  10389. ** read transaction is undefined. If SQLITE_OK is returned, then the
  10390. ** read transaction is now open on database snapshot P.
  10391. **
  10392. ** ^(A call to [sqlite3_snapshot_open(D,S,P)] will fail if the
  10393. ** database connection D does not know that the database file for
  10394. ** schema S is in [WAL mode]. A database connection might not know
  10395. ** that the database file is in [WAL mode] if there has been no prior
  10396. ** I/O on that database connection, or if the database entered [WAL mode]
  10397. ** after the most recent I/O on the database connection.)^
  10398. ** (Hint: Run "[PRAGMA application_id]" against a newly opened
  10399. ** database connection in order to make it ready to use snapshots.)
  10400. **
  10401. ** The [sqlite3_snapshot_open()] interface is only available when the
  10402. ** [SQLITE_ENABLE_SNAPSHOT] compile-time option is used.
  10403. */
  10404. SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_open(
  10405. sqlite3 *db,
  10406. const char *zSchema,
  10407. sqlite3_snapshot *pSnapshot
  10408. );
  10409. /*
  10410. ** CAPI3REF: Destroy a snapshot
  10411. ** DESTRUCTOR: sqlite3_snapshot
  10412. **
  10413. ** ^The [sqlite3_snapshot_free(P)] interface destroys [sqlite3_snapshot] P.
  10414. ** The application must eventually free every [sqlite3_snapshot] object
  10415. ** using this routine to avoid a memory leak.
  10416. **
  10417. ** The [sqlite3_snapshot_free()] interface is only available when the
  10418. ** [SQLITE_ENABLE_SNAPSHOT] compile-time option is used.
  10419. */
  10420. SQLITE_API SQLITE_EXPERIMENTAL void sqlite3_snapshot_free(sqlite3_snapshot*);
  10421. /*
  10422. ** CAPI3REF: Compare the ages of two snapshot handles.
  10423. ** METHOD: sqlite3_snapshot
  10424. **
  10425. ** The sqlite3_snapshot_cmp(P1, P2) interface is used to compare the ages
  10426. ** of two valid snapshot handles.
  10427. **
  10428. ** If the two snapshot handles are not associated with the same database
  10429. ** file, the result of the comparison is undefined.
  10430. **
  10431. ** Additionally, the result of the comparison is only valid if both of the
  10432. ** snapshot handles were obtained by calling sqlite3_snapshot_get() since the
  10433. ** last time the wal file was deleted. The wal file is deleted when the
  10434. ** database is changed back to rollback mode or when the number of database
  10435. ** clients drops to zero. If either snapshot handle was obtained before the
  10436. ** wal file was last deleted, the value returned by this function
  10437. ** is undefined.
  10438. **
  10439. ** Otherwise, this API returns a negative value if P1 refers to an older
  10440. ** snapshot than P2, zero if the two handles refer to the same database
  10441. ** snapshot, and a positive value if P1 is a newer snapshot than P2.
  10442. **
  10443. ** This interface is only available if SQLite is compiled with the
  10444. ** [SQLITE_ENABLE_SNAPSHOT] option.
  10445. */
  10446. SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_cmp(
  10447. sqlite3_snapshot *p1,
  10448. sqlite3_snapshot *p2
  10449. );
  10450. /*
  10451. ** CAPI3REF: Recover snapshots from a wal file
  10452. ** METHOD: sqlite3_snapshot
  10453. **
  10454. ** If a [WAL file] remains on disk after all database connections close
  10455. ** (either through the use of the [SQLITE_FCNTL_PERSIST_WAL] [file control]
  10456. ** or because the last process to have the database opened exited without
  10457. ** calling [sqlite3_close()]) and a new connection is subsequently opened
  10458. ** on that database and [WAL file], the [sqlite3_snapshot_open()] interface
  10459. ** will only be able to open the last transaction added to the WAL file
  10460. ** even though the WAL file contains other valid transactions.
  10461. **
  10462. ** This function attempts to scan the WAL file associated with database zDb
  10463. ** of database handle db and make all valid snapshots available to
  10464. ** sqlite3_snapshot_open(). It is an error if there is already a read
  10465. ** transaction open on the database, or if the database is not a WAL mode
  10466. ** database.
  10467. **
  10468. ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
  10469. **
  10470. ** This interface is only available if SQLite is compiled with the
  10471. ** [SQLITE_ENABLE_SNAPSHOT] option.
  10472. */
  10473. SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_snapshot_recover(sqlite3 *db, const char *zDb);
  10474. /*
  10475. ** CAPI3REF: Serialize a database
  10476. **
  10477. ** The sqlite3_serialize(D,S,P,F) interface returns a pointer to memory
  10478. ** that is a serialization of the S database on [database connection] D.
  10479. ** If P is not a NULL pointer, then the size of the database in bytes
  10480. ** is written into *P.
  10481. **
  10482. ** For an ordinary on-disk database file, the serialization is just a
  10483. ** copy of the disk file. For an in-memory database or a "TEMP" database,
  10484. ** the serialization is the same sequence of bytes which would be written
  10485. ** to disk if that database where backed up to disk.
  10486. **
  10487. ** The usual case is that sqlite3_serialize() copies the serialization of
  10488. ** the database into memory obtained from [sqlite3_malloc64()] and returns
  10489. ** a pointer to that memory. The caller is responsible for freeing the
  10490. ** returned value to avoid a memory leak. However, if the F argument
  10491. ** contains the SQLITE_SERIALIZE_NOCOPY bit, then no memory allocations
  10492. ** are made, and the sqlite3_serialize() function will return a pointer
  10493. ** to the contiguous memory representation of the database that SQLite
  10494. ** is currently using for that database, or NULL if the no such contiguous
  10495. ** memory representation of the database exists. A contiguous memory
  10496. ** representation of the database will usually only exist if there has
  10497. ** been a prior call to [sqlite3_deserialize(D,S,...)] with the same
  10498. ** values of D and S.
  10499. ** The size of the database is written into *P even if the
  10500. ** SQLITE_SERIALIZE_NOCOPY bit is set but no contiguous copy
  10501. ** of the database exists.
  10502. **
  10503. ** A call to sqlite3_serialize(D,S,P,F) might return NULL even if the
  10504. ** SQLITE_SERIALIZE_NOCOPY bit is omitted from argument F if a memory
  10505. ** allocation error occurs.
  10506. **
  10507. ** This interface is only available if SQLite is compiled with the
  10508. ** [SQLITE_ENABLE_DESERIALIZE] option.
  10509. */
  10510. SQLITE_API unsigned char *sqlite3_serialize(
  10511. sqlite3 *db, /* The database connection */
  10512. const char *zSchema, /* Which DB to serialize. ex: "main", "temp", ... */
  10513. sqlite3_int64 *piSize, /* Write size of the DB here, if not NULL */
  10514. unsigned int mFlags /* Zero or more SQLITE_SERIALIZE_* flags */
  10515. );
  10516. /*
  10517. ** CAPI3REF: Flags for sqlite3_serialize
  10518. **
  10519. ** Zero or more of the following constants can be OR-ed together for
  10520. ** the F argument to [sqlite3_serialize(D,S,P,F)].
  10521. **
  10522. ** SQLITE_SERIALIZE_NOCOPY means that [sqlite3_serialize()] will return
  10523. ** a pointer to contiguous in-memory database that it is currently using,
  10524. ** without making a copy of the database. If SQLite is not currently using
  10525. ** a contiguous in-memory database, then this option causes
  10526. ** [sqlite3_serialize()] to return a NULL pointer. SQLite will only be
  10527. ** using a contiguous in-memory database if it has been initialized by a
  10528. ** prior call to [sqlite3_deserialize()].
  10529. */
  10530. #define SQLITE_SERIALIZE_NOCOPY 0x001 /* Do no memory allocations */
  10531. /*
  10532. ** CAPI3REF: Deserialize a database
  10533. **
  10534. ** The sqlite3_deserialize(D,S,P,N,M,F) interface causes the
  10535. ** [database connection] D to disconnect from database S and then
  10536. ** reopen S as an in-memory database based on the serialization contained
  10537. ** in P. The serialized database P is N bytes in size. M is the size of
  10538. ** the buffer P, which might be larger than N. If M is larger than N, and
  10539. ** the SQLITE_DESERIALIZE_READONLY bit is not set in F, then SQLite is
  10540. ** permitted to add content to the in-memory database as long as the total
  10541. ** size does not exceed M bytes.
  10542. **
  10543. ** If the SQLITE_DESERIALIZE_FREEONCLOSE bit is set in F, then SQLite will
  10544. ** invoke sqlite3_free() on the serialization buffer when the database
  10545. ** connection closes. If the SQLITE_DESERIALIZE_RESIZEABLE bit is set, then
  10546. ** SQLite will try to increase the buffer size using sqlite3_realloc64()
  10547. ** if writes on the database cause it to grow larger than M bytes.
  10548. **
  10549. ** The sqlite3_deserialize() interface will fail with SQLITE_BUSY if the
  10550. ** database is currently in a read transaction or is involved in a backup
  10551. ** operation.
  10552. **
  10553. ** If sqlite3_deserialize(D,S,P,N,M,F) fails for any reason and if the
  10554. ** SQLITE_DESERIALIZE_FREEONCLOSE bit is set in argument F, then
  10555. ** [sqlite3_free()] is invoked on argument P prior to returning.
  10556. **
  10557. ** This interface is only available if SQLite is compiled with the
  10558. ** [SQLITE_ENABLE_DESERIALIZE] option.
  10559. */
  10560. SQLITE_API int sqlite3_deserialize(
  10561. sqlite3 *db, /* The database connection */
  10562. const char *zSchema, /* Which DB to reopen with the deserialization */
  10563. unsigned char *pData, /* The serialized database content */
  10564. sqlite3_int64 szDb, /* Number bytes in the deserialization */
  10565. sqlite3_int64 szBuf, /* Total size of buffer pData[] */
  10566. unsigned mFlags /* Zero or more SQLITE_DESERIALIZE_* flags */
  10567. );
  10568. /*
  10569. ** CAPI3REF: Flags for sqlite3_deserialize()
  10570. **
  10571. ** The following are allowed values for 6th argument (the F argument) to
  10572. ** the [sqlite3_deserialize(D,S,P,N,M,F)] interface.
  10573. **
  10574. ** The SQLITE_DESERIALIZE_FREEONCLOSE means that the database serialization
  10575. ** in the P argument is held in memory obtained from [sqlite3_malloc64()]
  10576. ** and that SQLite should take ownership of this memory and automatically
  10577. ** free it when it has finished using it. Without this flag, the caller
  10578. ** is responsible for freeing any dynamically allocated memory.
  10579. **
  10580. ** The SQLITE_DESERIALIZE_RESIZEABLE flag means that SQLite is allowed to
  10581. ** grow the size of the database using calls to [sqlite3_realloc64()]. This
  10582. ** flag should only be used if SQLITE_DESERIALIZE_FREEONCLOSE is also used.
  10583. ** Without this flag, the deserialized database cannot increase in size beyond
  10584. ** the number of bytes specified by the M parameter.
  10585. **
  10586. ** The SQLITE_DESERIALIZE_READONLY flag means that the deserialized database
  10587. ** should be treated as read-only.
  10588. */
  10589. #define SQLITE_DESERIALIZE_FREEONCLOSE 1 /* Call sqlite3_free() on close */
  10590. #define SQLITE_DESERIALIZE_RESIZEABLE 2 /* Resize using sqlite3_realloc64() */
  10591. #define SQLITE_DESERIALIZE_READONLY 4 /* Database is read-only */
  10592. /*
  10593. ** Undo the hack that converts floating point types to integer for
  10594. ** builds on processors without floating point support.
  10595. */
  10596. #ifdef SQLITE_OMIT_FLOATING_POINT
  10597. # undef double
  10598. #endif
  10599. #if 0
  10600. } /* End of the 'extern "C"' block */
  10601. #endif
  10602. #endif /* SQLITE3_H */
  10603. /******** Begin file sqlite3rtree.h *********/
  10604. /*
  10605. ** 2010 August 30
  10606. **
  10607. ** The author disclaims copyright to this source code. In place of
  10608. ** a legal notice, here is a blessing:
  10609. **
  10610. ** May you do good and not evil.
  10611. ** May you find forgiveness for yourself and forgive others.
  10612. ** May you share freely, never taking more than you give.
  10613. **
  10614. *************************************************************************
  10615. */
  10616. #ifndef _SQLITE3RTREE_H_
  10617. #define _SQLITE3RTREE_H_
  10618. #if 0
  10619. extern "C" {
  10620. #endif
  10621. typedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry;
  10622. typedef struct sqlite3_rtree_query_info sqlite3_rtree_query_info;
  10623. /* The double-precision datatype used by RTree depends on the
  10624. ** SQLITE_RTREE_INT_ONLY compile-time option.
  10625. */
  10626. #ifdef SQLITE_RTREE_INT_ONLY
  10627. typedef sqlite3_int64 sqlite3_rtree_dbl;
  10628. #else
  10629. typedef double sqlite3_rtree_dbl;
  10630. #endif
  10631. /*
  10632. ** Register a geometry callback named zGeom that can be used as part of an
  10633. ** R-Tree geometry query as follows:
  10634. **
  10635. ** SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zGeom(... params ...)
  10636. */
  10637. SQLITE_API int sqlite3_rtree_geometry_callback(
  10638. sqlite3 *db,
  10639. const char *zGeom,
  10640. int (*xGeom)(sqlite3_rtree_geometry*, int, sqlite3_rtree_dbl*,int*),
  10641. void *pContext
  10642. );
  10643. /*
  10644. ** A pointer to a structure of the following type is passed as the first
  10645. ** argument to callbacks registered using rtree_geometry_callback().
  10646. */
  10647. struct sqlite3_rtree_geometry {
  10648. void *pContext; /* Copy of pContext passed to s_r_g_c() */
  10649. int nParam; /* Size of array aParam[] */
  10650. sqlite3_rtree_dbl *aParam; /* Parameters passed to SQL geom function */
  10651. void *pUser; /* Callback implementation user data */
  10652. void (*xDelUser)(void *); /* Called by SQLite to clean up pUser */
  10653. };
  10654. /*
  10655. ** Register a 2nd-generation geometry callback named zScore that can be
  10656. ** used as part of an R-Tree geometry query as follows:
  10657. **
  10658. ** SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zQueryFunc(... params ...)
  10659. */
  10660. SQLITE_API int sqlite3_rtree_query_callback(
  10661. sqlite3 *db,
  10662. const char *zQueryFunc,
  10663. int (*xQueryFunc)(sqlite3_rtree_query_info*),
  10664. void *pContext,
  10665. void (*xDestructor)(void*)
  10666. );
  10667. /*
  10668. ** A pointer to a structure of the following type is passed as the
  10669. ** argument to scored geometry callback registered using
  10670. ** sqlite3_rtree_query_callback().
  10671. **
  10672. ** Note that the first 5 fields of this structure are identical to
  10673. ** sqlite3_rtree_geometry. This structure is a subclass of
  10674. ** sqlite3_rtree_geometry.
  10675. */
  10676. struct sqlite3_rtree_query_info {
  10677. void *pContext; /* pContext from when function registered */
  10678. int nParam; /* Number of function parameters */
  10679. sqlite3_rtree_dbl *aParam; /* value of function parameters */
  10680. void *pUser; /* callback can use this, if desired */
  10681. void (*xDelUser)(void*); /* function to free pUser */
  10682. sqlite3_rtree_dbl *aCoord; /* Coordinates of node or entry to check */
  10683. unsigned int *anQueue; /* Number of pending entries in the queue */
  10684. int nCoord; /* Number of coordinates */
  10685. int iLevel; /* Level of current node or entry */
  10686. int mxLevel; /* The largest iLevel value in the tree */
  10687. sqlite3_int64 iRowid; /* Rowid for current entry */
  10688. sqlite3_rtree_dbl rParentScore; /* Score of parent node */
  10689. int eParentWithin; /* Visibility of parent node */
  10690. int eWithin; /* OUT: Visibility */
  10691. sqlite3_rtree_dbl rScore; /* OUT: Write the score here */
  10692. /* The following fields are only available in 3.8.11 and later */
  10693. sqlite3_value **apSqlParam; /* Original SQL values of parameters */
  10694. };
  10695. /*
  10696. ** Allowed values for sqlite3_rtree_query.eWithin and .eParentWithin.
  10697. */
  10698. #define NOT_WITHIN 0 /* Object completely outside of query region */
  10699. #define PARTLY_WITHIN 1 /* Object partially overlaps query region */
  10700. #define FULLY_WITHIN 2 /* Object fully contained within query region */
  10701. #if 0
  10702. } /* end of the 'extern "C"' block */
  10703. #endif
  10704. #endif /* ifndef _SQLITE3RTREE_H_ */
  10705. /******** End of sqlite3rtree.h *********/
  10706. /******** Begin file sqlite3session.h *********/
  10707. #if !defined(__SQLITESESSION_H_) && defined(SQLITE_ENABLE_SESSION)
  10708. #define __SQLITESESSION_H_ 1
  10709. /*
  10710. ** Make sure we can call this stuff from C++.
  10711. */
  10712. #if 0
  10713. extern "C" {
  10714. #endif
  10715. /*
  10716. ** CAPI3REF: Session Object Handle
  10717. **
  10718. ** An instance of this object is a [session] that can be used to
  10719. ** record changes to a database.
  10720. */
  10721. typedef struct sqlite3_session sqlite3_session;
  10722. /*
  10723. ** CAPI3REF: Changeset Iterator Handle
  10724. **
  10725. ** An instance of this object acts as a cursor for iterating
  10726. ** over the elements of a [changeset] or [patchset].
  10727. */
  10728. typedef struct sqlite3_changeset_iter sqlite3_changeset_iter;
  10729. /*
  10730. ** CAPI3REF: Create A New Session Object
  10731. ** CONSTRUCTOR: sqlite3_session
  10732. **
  10733. ** Create a new session object attached to database handle db. If successful,
  10734. ** a pointer to the new object is written to *ppSession and SQLITE_OK is
  10735. ** returned. If an error occurs, *ppSession is set to NULL and an SQLite
  10736. ** error code (e.g. SQLITE_NOMEM) is returned.
  10737. **
  10738. ** It is possible to create multiple session objects attached to a single
  10739. ** database handle.
  10740. **
  10741. ** Session objects created using this function should be deleted using the
  10742. ** [sqlite3session_delete()] function before the database handle that they
  10743. ** are attached to is itself closed. If the database handle is closed before
  10744. ** the session object is deleted, then the results of calling any session
  10745. ** module function, including [sqlite3session_delete()] on the session object
  10746. ** are undefined.
  10747. **
  10748. ** Because the session module uses the [sqlite3_preupdate_hook()] API, it
  10749. ** is not possible for an application to register a pre-update hook on a
  10750. ** database handle that has one or more session objects attached. Nor is
  10751. ** it possible to create a session object attached to a database handle for
  10752. ** which a pre-update hook is already defined. The results of attempting
  10753. ** either of these things are undefined.
  10754. **
  10755. ** The session object will be used to create changesets for tables in
  10756. ** database zDb, where zDb is either "main", or "temp", or the name of an
  10757. ** attached database. It is not an error if database zDb is not attached
  10758. ** to the database when the session object is created.
  10759. */
  10760. SQLITE_API int sqlite3session_create(
  10761. sqlite3 *db, /* Database handle */
  10762. const char *zDb, /* Name of db (e.g. "main") */
  10763. sqlite3_session **ppSession /* OUT: New session object */
  10764. );
  10765. /*
  10766. ** CAPI3REF: Delete A Session Object
  10767. ** DESTRUCTOR: sqlite3_session
  10768. **
  10769. ** Delete a session object previously allocated using
  10770. ** [sqlite3session_create()]. Once a session object has been deleted, the
  10771. ** results of attempting to use pSession with any other session module
  10772. ** function are undefined.
  10773. **
  10774. ** Session objects must be deleted before the database handle to which they
  10775. ** are attached is closed. Refer to the documentation for
  10776. ** [sqlite3session_create()] for details.
  10777. */
  10778. SQLITE_API void sqlite3session_delete(sqlite3_session *pSession);
  10779. /*
  10780. ** CAPI3REF: Enable Or Disable A Session Object
  10781. ** METHOD: sqlite3_session
  10782. **
  10783. ** Enable or disable the recording of changes by a session object. When
  10784. ** enabled, a session object records changes made to the database. When
  10785. ** disabled - it does not. A newly created session object is enabled.
  10786. ** Refer to the documentation for [sqlite3session_changeset()] for further
  10787. ** details regarding how enabling and disabling a session object affects
  10788. ** the eventual changesets.
  10789. **
  10790. ** Passing zero to this function disables the session. Passing a value
  10791. ** greater than zero enables it. Passing a value less than zero is a
  10792. ** no-op, and may be used to query the current state of the session.
  10793. **
  10794. ** The return value indicates the final state of the session object: 0 if
  10795. ** the session is disabled, or 1 if it is enabled.
  10796. */
  10797. SQLITE_API int sqlite3session_enable(sqlite3_session *pSession, int bEnable);
  10798. /*
  10799. ** CAPI3REF: Set Or Clear the Indirect Change Flag
  10800. ** METHOD: sqlite3_session
  10801. **
  10802. ** Each change recorded by a session object is marked as either direct or
  10803. ** indirect. A change is marked as indirect if either:
  10804. **
  10805. ** <ul>
  10806. ** <li> The session object "indirect" flag is set when the change is
  10807. ** made, or
  10808. ** <li> The change is made by an SQL trigger or foreign key action
  10809. ** instead of directly as a result of a users SQL statement.
  10810. ** </ul>
  10811. **
  10812. ** If a single row is affected by more than one operation within a session,
  10813. ** then the change is considered indirect if all operations meet the criteria
  10814. ** for an indirect change above, or direct otherwise.
  10815. **
  10816. ** This function is used to set, clear or query the session object indirect
  10817. ** flag. If the second argument passed to this function is zero, then the
  10818. ** indirect flag is cleared. If it is greater than zero, the indirect flag
  10819. ** is set. Passing a value less than zero does not modify the current value
  10820. ** of the indirect flag, and may be used to query the current state of the
  10821. ** indirect flag for the specified session object.
  10822. **
  10823. ** The return value indicates the final state of the indirect flag: 0 if
  10824. ** it is clear, or 1 if it is set.
  10825. */
  10826. SQLITE_API int sqlite3session_indirect(sqlite3_session *pSession, int bIndirect);
  10827. /*
  10828. ** CAPI3REF: Attach A Table To A Session Object
  10829. ** METHOD: sqlite3_session
  10830. **
  10831. ** If argument zTab is not NULL, then it is the name of a table to attach
  10832. ** to the session object passed as the first argument. All subsequent changes
  10833. ** made to the table while the session object is enabled will be recorded. See
  10834. ** documentation for [sqlite3session_changeset()] for further details.
  10835. **
  10836. ** Or, if argument zTab is NULL, then changes are recorded for all tables
  10837. ** in the database. If additional tables are added to the database (by
  10838. ** executing "CREATE TABLE" statements) after this call is made, changes for
  10839. ** the new tables are also recorded.
  10840. **
  10841. ** Changes can only be recorded for tables that have a PRIMARY KEY explicitly
  10842. ** defined as part of their CREATE TABLE statement. It does not matter if the
  10843. ** PRIMARY KEY is an "INTEGER PRIMARY KEY" (rowid alias) or not. The PRIMARY
  10844. ** KEY may consist of a single column, or may be a composite key.
  10845. **
  10846. ** It is not an error if the named table does not exist in the database. Nor
  10847. ** is it an error if the named table does not have a PRIMARY KEY. However,
  10848. ** no changes will be recorded in either of these scenarios.
  10849. **
  10850. ** Changes are not recorded for individual rows that have NULL values stored
  10851. ** in one or more of their PRIMARY KEY columns.
  10852. **
  10853. ** SQLITE_OK is returned if the call completes without error. Or, if an error
  10854. ** occurs, an SQLite error code (e.g. SQLITE_NOMEM) is returned.
  10855. **
  10856. ** <h3>Special sqlite_stat1 Handling</h3>
  10857. **
  10858. ** As of SQLite version 3.22.0, the "sqlite_stat1" table is an exception to
  10859. ** some of the rules above. In SQLite, the schema of sqlite_stat1 is:
  10860. ** <pre>
  10861. ** &nbsp; CREATE TABLE sqlite_stat1(tbl,idx,stat)
  10862. ** </pre>
  10863. **
  10864. ** Even though sqlite_stat1 does not have a PRIMARY KEY, changes are
  10865. ** recorded for it as if the PRIMARY KEY is (tbl,idx). Additionally, changes
  10866. ** are recorded for rows for which (idx IS NULL) is true. However, for such
  10867. ** rows a zero-length blob (SQL value X'') is stored in the changeset or
  10868. ** patchset instead of a NULL value. This allows such changesets to be
  10869. ** manipulated by legacy implementations of sqlite3changeset_invert(),
  10870. ** concat() and similar.
  10871. **
  10872. ** The sqlite3changeset_apply() function automatically converts the
  10873. ** zero-length blob back to a NULL value when updating the sqlite_stat1
  10874. ** table. However, if the application calls sqlite3changeset_new(),
  10875. ** sqlite3changeset_old() or sqlite3changeset_conflict on a changeset
  10876. ** iterator directly (including on a changeset iterator passed to a
  10877. ** conflict-handler callback) then the X'' value is returned. The application
  10878. ** must translate X'' to NULL itself if required.
  10879. **
  10880. ** Legacy (older than 3.22.0) versions of the sessions module cannot capture
  10881. ** changes made to the sqlite_stat1 table. Legacy versions of the
  10882. ** sqlite3changeset_apply() function silently ignore any modifications to the
  10883. ** sqlite_stat1 table that are part of a changeset or patchset.
  10884. */
  10885. SQLITE_API int sqlite3session_attach(
  10886. sqlite3_session *pSession, /* Session object */
  10887. const char *zTab /* Table name */
  10888. );
  10889. /*
  10890. ** CAPI3REF: Set a table filter on a Session Object.
  10891. ** METHOD: sqlite3_session
  10892. **
  10893. ** The second argument (xFilter) is the "filter callback". For changes to rows
  10894. ** in tables that are not attached to the Session object, the filter is called
  10895. ** to determine whether changes to the table's rows should be tracked or not.
  10896. ** If xFilter returns 0, changes are not tracked. Note that once a table is
  10897. ** attached, xFilter will not be called again.
  10898. */
  10899. SQLITE_API void sqlite3session_table_filter(
  10900. sqlite3_session *pSession, /* Session object */
  10901. int(*xFilter)(
  10902. void *pCtx, /* Copy of third arg to _filter_table() */
  10903. const char *zTab /* Table name */
  10904. ),
  10905. void *pCtx /* First argument passed to xFilter */
  10906. );
  10907. /*
  10908. ** CAPI3REF: Generate A Changeset From A Session Object
  10909. ** METHOD: sqlite3_session
  10910. **
  10911. ** Obtain a changeset containing changes to the tables attached to the
  10912. ** session object passed as the first argument. If successful,
  10913. ** set *ppChangeset to point to a buffer containing the changeset
  10914. ** and *pnChangeset to the size of the changeset in bytes before returning
  10915. ** SQLITE_OK. If an error occurs, set both *ppChangeset and *pnChangeset to
  10916. ** zero and return an SQLite error code.
  10917. **
  10918. ** A changeset consists of zero or more INSERT, UPDATE and/or DELETE changes,
  10919. ** each representing a change to a single row of an attached table. An INSERT
  10920. ** change contains the values of each field of a new database row. A DELETE
  10921. ** contains the original values of each field of a deleted database row. An
  10922. ** UPDATE change contains the original values of each field of an updated
  10923. ** database row along with the updated values for each updated non-primary-key
  10924. ** column. It is not possible for an UPDATE change to represent a change that
  10925. ** modifies the values of primary key columns. If such a change is made, it
  10926. ** is represented in a changeset as a DELETE followed by an INSERT.
  10927. **
  10928. ** Changes are not recorded for rows that have NULL values stored in one or
  10929. ** more of their PRIMARY KEY columns. If such a row is inserted or deleted,
  10930. ** no corresponding change is present in the changesets returned by this
  10931. ** function. If an existing row with one or more NULL values stored in
  10932. ** PRIMARY KEY columns is updated so that all PRIMARY KEY columns are non-NULL,
  10933. ** only an INSERT is appears in the changeset. Similarly, if an existing row
  10934. ** with non-NULL PRIMARY KEY values is updated so that one or more of its
  10935. ** PRIMARY KEY columns are set to NULL, the resulting changeset contains a
  10936. ** DELETE change only.
  10937. **
  10938. ** The contents of a changeset may be traversed using an iterator created
  10939. ** using the [sqlite3changeset_start()] API. A changeset may be applied to
  10940. ** a database with a compatible schema using the [sqlite3changeset_apply()]
  10941. ** API.
  10942. **
  10943. ** Within a changeset generated by this function, all changes related to a
  10944. ** single table are grouped together. In other words, when iterating through
  10945. ** a changeset or when applying a changeset to a database, all changes related
  10946. ** to a single table are processed before moving on to the next table. Tables
  10947. ** are sorted in the same order in which they were attached (or auto-attached)
  10948. ** to the sqlite3_session object. The order in which the changes related to
  10949. ** a single table are stored is undefined.
  10950. **
  10951. ** Following a successful call to this function, it is the responsibility of
  10952. ** the caller to eventually free the buffer that *ppChangeset points to using
  10953. ** [sqlite3_free()].
  10954. **
  10955. ** <h3>Changeset Generation</h3>
  10956. **
  10957. ** Once a table has been attached to a session object, the session object
  10958. ** records the primary key values of all new rows inserted into the table.
  10959. ** It also records the original primary key and other column values of any
  10960. ** deleted or updated rows. For each unique primary key value, data is only
  10961. ** recorded once - the first time a row with said primary key is inserted,
  10962. ** updated or deleted in the lifetime of the session.
  10963. **
  10964. ** There is one exception to the previous paragraph: when a row is inserted,
  10965. ** updated or deleted, if one or more of its primary key columns contain a
  10966. ** NULL value, no record of the change is made.
  10967. **
  10968. ** The session object therefore accumulates two types of records - those
  10969. ** that consist of primary key values only (created when the user inserts
  10970. ** a new record) and those that consist of the primary key values and the
  10971. ** original values of other table columns (created when the users deletes
  10972. ** or updates a record).
  10973. **
  10974. ** When this function is called, the requested changeset is created using
  10975. ** both the accumulated records and the current contents of the database
  10976. ** file. Specifically:
  10977. **
  10978. ** <ul>
  10979. ** <li> For each record generated by an insert, the database is queried
  10980. ** for a row with a matching primary key. If one is found, an INSERT
  10981. ** change is added to the changeset. If no such row is found, no change
  10982. ** is added to the changeset.
  10983. **
  10984. ** <li> For each record generated by an update or delete, the database is
  10985. ** queried for a row with a matching primary key. If such a row is
  10986. ** found and one or more of the non-primary key fields have been
  10987. ** modified from their original values, an UPDATE change is added to
  10988. ** the changeset. Or, if no such row is found in the table, a DELETE
  10989. ** change is added to the changeset. If there is a row with a matching
  10990. ** primary key in the database, but all fields contain their original
  10991. ** values, no change is added to the changeset.
  10992. ** </ul>
  10993. **
  10994. ** This means, amongst other things, that if a row is inserted and then later
  10995. ** deleted while a session object is active, neither the insert nor the delete
  10996. ** will be present in the changeset. Or if a row is deleted and then later a
  10997. ** row with the same primary key values inserted while a session object is
  10998. ** active, the resulting changeset will contain an UPDATE change instead of
  10999. ** a DELETE and an INSERT.
  11000. **
  11001. ** When a session object is disabled (see the [sqlite3session_enable()] API),
  11002. ** it does not accumulate records when rows are inserted, updated or deleted.
  11003. ** This may appear to have some counter-intuitive effects if a single row
  11004. ** is written to more than once during a session. For example, if a row
  11005. ** is inserted while a session object is enabled, then later deleted while
  11006. ** the same session object is disabled, no INSERT record will appear in the
  11007. ** changeset, even though the delete took place while the session was disabled.
  11008. ** Or, if one field of a row is updated while a session is disabled, and
  11009. ** another field of the same row is updated while the session is enabled, the
  11010. ** resulting changeset will contain an UPDATE change that updates both fields.
  11011. */
  11012. SQLITE_API int sqlite3session_changeset(
  11013. sqlite3_session *pSession, /* Session object */
  11014. int *pnChangeset, /* OUT: Size of buffer at *ppChangeset */
  11015. void **ppChangeset /* OUT: Buffer containing changeset */
  11016. );
  11017. /*
  11018. ** CAPI3REF: Load The Difference Between Tables Into A Session
  11019. ** METHOD: sqlite3_session
  11020. **
  11021. ** If it is not already attached to the session object passed as the first
  11022. ** argument, this function attaches table zTbl in the same manner as the
  11023. ** [sqlite3session_attach()] function. If zTbl does not exist, or if it
  11024. ** does not have a primary key, this function is a no-op (but does not return
  11025. ** an error).
  11026. **
  11027. ** Argument zFromDb must be the name of a database ("main", "temp" etc.)
  11028. ** attached to the same database handle as the session object that contains
  11029. ** a table compatible with the table attached to the session by this function.
  11030. ** A table is considered compatible if it:
  11031. **
  11032. ** <ul>
  11033. ** <li> Has the same name,
  11034. ** <li> Has the same set of columns declared in the same order, and
  11035. ** <li> Has the same PRIMARY KEY definition.
  11036. ** </ul>
  11037. **
  11038. ** If the tables are not compatible, SQLITE_SCHEMA is returned. If the tables
  11039. ** are compatible but do not have any PRIMARY KEY columns, it is not an error
  11040. ** but no changes are added to the session object. As with other session
  11041. ** APIs, tables without PRIMARY KEYs are simply ignored.
  11042. **
  11043. ** This function adds a set of changes to the session object that could be
  11044. ** used to update the table in database zFrom (call this the "from-table")
  11045. ** so that its content is the same as the table attached to the session
  11046. ** object (call this the "to-table"). Specifically:
  11047. **
  11048. ** <ul>
  11049. ** <li> For each row (primary key) that exists in the to-table but not in
  11050. ** the from-table, an INSERT record is added to the session object.
  11051. **
  11052. ** <li> For each row (primary key) that exists in the to-table but not in
  11053. ** the from-table, a DELETE record is added to the session object.
  11054. **
  11055. ** <li> For each row (primary key) that exists in both tables, but features
  11056. ** different non-PK values in each, an UPDATE record is added to the
  11057. ** session.
  11058. ** </ul>
  11059. **
  11060. ** To clarify, if this function is called and then a changeset constructed
  11061. ** using [sqlite3session_changeset()], then after applying that changeset to
  11062. ** database zFrom the contents of the two compatible tables would be
  11063. ** identical.
  11064. **
  11065. ** It an error if database zFrom does not exist or does not contain the
  11066. ** required compatible table.
  11067. **
  11068. ** If the operation is successful, SQLITE_OK is returned. Otherwise, an SQLite
  11069. ** error code. In this case, if argument pzErrMsg is not NULL, *pzErrMsg
  11070. ** may be set to point to a buffer containing an English language error
  11071. ** message. It is the responsibility of the caller to free this buffer using
  11072. ** sqlite3_free().
  11073. */
  11074. SQLITE_API int sqlite3session_diff(
  11075. sqlite3_session *pSession,
  11076. const char *zFromDb,
  11077. const char *zTbl,
  11078. char **pzErrMsg
  11079. );
  11080. /*
  11081. ** CAPI3REF: Generate A Patchset From A Session Object
  11082. ** METHOD: sqlite3_session
  11083. **
  11084. ** The differences between a patchset and a changeset are that:
  11085. **
  11086. ** <ul>
  11087. ** <li> DELETE records consist of the primary key fields only. The
  11088. ** original values of other fields are omitted.
  11089. ** <li> The original values of any modified fields are omitted from
  11090. ** UPDATE records.
  11091. ** </ul>
  11092. **
  11093. ** A patchset blob may be used with up to date versions of all
  11094. ** sqlite3changeset_xxx API functions except for sqlite3changeset_invert(),
  11095. ** which returns SQLITE_CORRUPT if it is passed a patchset. Similarly,
  11096. ** attempting to use a patchset blob with old versions of the
  11097. ** sqlite3changeset_xxx APIs also provokes an SQLITE_CORRUPT error.
  11098. **
  11099. ** Because the non-primary key "old.*" fields are omitted, no
  11100. ** SQLITE_CHANGESET_DATA conflicts can be detected or reported if a patchset
  11101. ** is passed to the sqlite3changeset_apply() API. Other conflict types work
  11102. ** in the same way as for changesets.
  11103. **
  11104. ** Changes within a patchset are ordered in the same way as for changesets
  11105. ** generated by the sqlite3session_changeset() function (i.e. all changes for
  11106. ** a single table are grouped together, tables appear in the order in which
  11107. ** they were attached to the session object).
  11108. */
  11109. SQLITE_API int sqlite3session_patchset(
  11110. sqlite3_session *pSession, /* Session object */
  11111. int *pnPatchset, /* OUT: Size of buffer at *ppPatchset */
  11112. void **ppPatchset /* OUT: Buffer containing patchset */
  11113. );
  11114. /*
  11115. ** CAPI3REF: Test if a changeset has recorded any changes.
  11116. **
  11117. ** Return non-zero if no changes to attached tables have been recorded by
  11118. ** the session object passed as the first argument. Otherwise, if one or
  11119. ** more changes have been recorded, return zero.
  11120. **
  11121. ** Even if this function returns zero, it is possible that calling
  11122. ** [sqlite3session_changeset()] on the session handle may still return a
  11123. ** changeset that contains no changes. This can happen when a row in
  11124. ** an attached table is modified and then later on the original values
  11125. ** are restored. However, if this function returns non-zero, then it is
  11126. ** guaranteed that a call to sqlite3session_changeset() will return a
  11127. ** changeset containing zero changes.
  11128. */
  11129. SQLITE_API int sqlite3session_isempty(sqlite3_session *pSession);
  11130. /*
  11131. ** CAPI3REF: Create An Iterator To Traverse A Changeset
  11132. ** CONSTRUCTOR: sqlite3_changeset_iter
  11133. **
  11134. ** Create an iterator used to iterate through the contents of a changeset.
  11135. ** If successful, *pp is set to point to the iterator handle and SQLITE_OK
  11136. ** is returned. Otherwise, if an error occurs, *pp is set to zero and an
  11137. ** SQLite error code is returned.
  11138. **
  11139. ** The following functions can be used to advance and query a changeset
  11140. ** iterator created by this function:
  11141. **
  11142. ** <ul>
  11143. ** <li> [sqlite3changeset_next()]
  11144. ** <li> [sqlite3changeset_op()]
  11145. ** <li> [sqlite3changeset_new()]
  11146. ** <li> [sqlite3changeset_old()]
  11147. ** </ul>
  11148. **
  11149. ** It is the responsibility of the caller to eventually destroy the iterator
  11150. ** by passing it to [sqlite3changeset_finalize()]. The buffer containing the
  11151. ** changeset (pChangeset) must remain valid until after the iterator is
  11152. ** destroyed.
  11153. **
  11154. ** Assuming the changeset blob was created by one of the
  11155. ** [sqlite3session_changeset()], [sqlite3changeset_concat()] or
  11156. ** [sqlite3changeset_invert()] functions, all changes within the changeset
  11157. ** that apply to a single table are grouped together. This means that when
  11158. ** an application iterates through a changeset using an iterator created by
  11159. ** this function, all changes that relate to a single table are visited
  11160. ** consecutively. There is no chance that the iterator will visit a change
  11161. ** the applies to table X, then one for table Y, and then later on visit
  11162. ** another change for table X.
  11163. **
  11164. ** The behavior of sqlite3changeset_start_v2() and its streaming equivalent
  11165. ** may be modified by passing a combination of
  11166. ** [SQLITE_CHANGESETSTART_INVERT | supported flags] as the 4th parameter.
  11167. **
  11168. ** Note that the sqlite3changeset_start_v2() API is still <b>experimental</b>
  11169. ** and therefore subject to change.
  11170. */
  11171. SQLITE_API int sqlite3changeset_start(
  11172. sqlite3_changeset_iter **pp, /* OUT: New changeset iterator handle */
  11173. int nChangeset, /* Size of changeset blob in bytes */
  11174. void *pChangeset /* Pointer to blob containing changeset */
  11175. );
  11176. SQLITE_API int sqlite3changeset_start_v2(
  11177. sqlite3_changeset_iter **pp, /* OUT: New changeset iterator handle */
  11178. int nChangeset, /* Size of changeset blob in bytes */
  11179. void *pChangeset, /* Pointer to blob containing changeset */
  11180. int flags /* SESSION_CHANGESETSTART_* flags */
  11181. );
  11182. /*
  11183. ** CAPI3REF: Flags for sqlite3changeset_start_v2
  11184. **
  11185. ** The following flags may passed via the 4th parameter to
  11186. ** [sqlite3changeset_start_v2] and [sqlite3changeset_start_v2_strm]:
  11187. **
  11188. ** <dt>SQLITE_CHANGESETAPPLY_INVERT <dd>
  11189. ** Invert the changeset while iterating through it. This is equivalent to
  11190. ** inverting a changeset using sqlite3changeset_invert() before applying it.
  11191. ** It is an error to specify this flag with a patchset.
  11192. */
  11193. #define SQLITE_CHANGESETSTART_INVERT 0x0002
  11194. /*
  11195. ** CAPI3REF: Advance A Changeset Iterator
  11196. ** METHOD: sqlite3_changeset_iter
  11197. **
  11198. ** This function may only be used with iterators created by the function
  11199. ** [sqlite3changeset_start()]. If it is called on an iterator passed to
  11200. ** a conflict-handler callback by [sqlite3changeset_apply()], SQLITE_MISUSE
  11201. ** is returned and the call has no effect.
  11202. **
  11203. ** Immediately after an iterator is created by sqlite3changeset_start(), it
  11204. ** does not point to any change in the changeset. Assuming the changeset
  11205. ** is not empty, the first call to this function advances the iterator to
  11206. ** point to the first change in the changeset. Each subsequent call advances
  11207. ** the iterator to point to the next change in the changeset (if any). If
  11208. ** no error occurs and the iterator points to a valid change after a call
  11209. ** to sqlite3changeset_next() has advanced it, SQLITE_ROW is returned.
  11210. ** Otherwise, if all changes in the changeset have already been visited,
  11211. ** SQLITE_DONE is returned.
  11212. **
  11213. ** If an error occurs, an SQLite error code is returned. Possible error
  11214. ** codes include SQLITE_CORRUPT (if the changeset buffer is corrupt) or
  11215. ** SQLITE_NOMEM.
  11216. */
  11217. SQLITE_API int sqlite3changeset_next(sqlite3_changeset_iter *pIter);
  11218. /*
  11219. ** CAPI3REF: Obtain The Current Operation From A Changeset Iterator
  11220. ** METHOD: sqlite3_changeset_iter
  11221. **
  11222. ** The pIter argument passed to this function may either be an iterator
  11223. ** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
  11224. ** created by [sqlite3changeset_start()]. In the latter case, the most recent
  11225. ** call to [sqlite3changeset_next()] must have returned [SQLITE_ROW]. If this
  11226. ** is not the case, this function returns [SQLITE_MISUSE].
  11227. **
  11228. ** If argument pzTab is not NULL, then *pzTab is set to point to a
  11229. ** nul-terminated utf-8 encoded string containing the name of the table
  11230. ** affected by the current change. The buffer remains valid until either
  11231. ** sqlite3changeset_next() is called on the iterator or until the
  11232. ** conflict-handler function returns. If pnCol is not NULL, then *pnCol is
  11233. ** set to the number of columns in the table affected by the change. If
  11234. ** pbIndirect is not NULL, then *pbIndirect is set to true (1) if the change
  11235. ** is an indirect change, or false (0) otherwise. See the documentation for
  11236. ** [sqlite3session_indirect()] for a description of direct and indirect
  11237. ** changes. Finally, if pOp is not NULL, then *pOp is set to one of
  11238. ** [SQLITE_INSERT], [SQLITE_DELETE] or [SQLITE_UPDATE], depending on the
  11239. ** type of change that the iterator currently points to.
  11240. **
  11241. ** If no error occurs, SQLITE_OK is returned. If an error does occur, an
  11242. ** SQLite error code is returned. The values of the output variables may not
  11243. ** be trusted in this case.
  11244. */
  11245. SQLITE_API int sqlite3changeset_op(
  11246. sqlite3_changeset_iter *pIter, /* Iterator object */
  11247. const char **pzTab, /* OUT: Pointer to table name */
  11248. int *pnCol, /* OUT: Number of columns in table */
  11249. int *pOp, /* OUT: SQLITE_INSERT, DELETE or UPDATE */
  11250. int *pbIndirect /* OUT: True for an 'indirect' change */
  11251. );
  11252. /*
  11253. ** CAPI3REF: Obtain The Primary Key Definition Of A Table
  11254. ** METHOD: sqlite3_changeset_iter
  11255. **
  11256. ** For each modified table, a changeset includes the following:
  11257. **
  11258. ** <ul>
  11259. ** <li> The number of columns in the table, and
  11260. ** <li> Which of those columns make up the tables PRIMARY KEY.
  11261. ** </ul>
  11262. **
  11263. ** This function is used to find which columns comprise the PRIMARY KEY of
  11264. ** the table modified by the change that iterator pIter currently points to.
  11265. ** If successful, *pabPK is set to point to an array of nCol entries, where
  11266. ** nCol is the number of columns in the table. Elements of *pabPK are set to
  11267. ** 0x01 if the corresponding column is part of the tables primary key, or
  11268. ** 0x00 if it is not.
  11269. **
  11270. ** If argument pnCol is not NULL, then *pnCol is set to the number of columns
  11271. ** in the table.
  11272. **
  11273. ** If this function is called when the iterator does not point to a valid
  11274. ** entry, SQLITE_MISUSE is returned and the output variables zeroed. Otherwise,
  11275. ** SQLITE_OK is returned and the output variables populated as described
  11276. ** above.
  11277. */
  11278. SQLITE_API int sqlite3changeset_pk(
  11279. sqlite3_changeset_iter *pIter, /* Iterator object */
  11280. unsigned char **pabPK, /* OUT: Array of boolean - true for PK cols */
  11281. int *pnCol /* OUT: Number of entries in output array */
  11282. );
  11283. /*
  11284. ** CAPI3REF: Obtain old.* Values From A Changeset Iterator
  11285. ** METHOD: sqlite3_changeset_iter
  11286. **
  11287. ** The pIter argument passed to this function may either be an iterator
  11288. ** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
  11289. ** created by [sqlite3changeset_start()]. In the latter case, the most recent
  11290. ** call to [sqlite3changeset_next()] must have returned SQLITE_ROW.
  11291. ** Furthermore, it may only be called if the type of change that the iterator
  11292. ** currently points to is either [SQLITE_DELETE] or [SQLITE_UPDATE]. Otherwise,
  11293. ** this function returns [SQLITE_MISUSE] and sets *ppValue to NULL.
  11294. **
  11295. ** Argument iVal must be greater than or equal to 0, and less than the number
  11296. ** of columns in the table affected by the current change. Otherwise,
  11297. ** [SQLITE_RANGE] is returned and *ppValue is set to NULL.
  11298. **
  11299. ** If successful, this function sets *ppValue to point to a protected
  11300. ** sqlite3_value object containing the iVal'th value from the vector of
  11301. ** original row values stored as part of the UPDATE or DELETE change and
  11302. ** returns SQLITE_OK. The name of the function comes from the fact that this
  11303. ** is similar to the "old.*" columns available to update or delete triggers.
  11304. **
  11305. ** If some other error occurs (e.g. an OOM condition), an SQLite error code
  11306. ** is returned and *ppValue is set to NULL.
  11307. */
  11308. SQLITE_API int sqlite3changeset_old(
  11309. sqlite3_changeset_iter *pIter, /* Changeset iterator */
  11310. int iVal, /* Column number */
  11311. sqlite3_value **ppValue /* OUT: Old value (or NULL pointer) */
  11312. );
  11313. /*
  11314. ** CAPI3REF: Obtain new.* Values From A Changeset Iterator
  11315. ** METHOD: sqlite3_changeset_iter
  11316. **
  11317. ** The pIter argument passed to this function may either be an iterator
  11318. ** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
  11319. ** created by [sqlite3changeset_start()]. In the latter case, the most recent
  11320. ** call to [sqlite3changeset_next()] must have returned SQLITE_ROW.
  11321. ** Furthermore, it may only be called if the type of change that the iterator
  11322. ** currently points to is either [SQLITE_UPDATE] or [SQLITE_INSERT]. Otherwise,
  11323. ** this function returns [SQLITE_MISUSE] and sets *ppValue to NULL.
  11324. **
  11325. ** Argument iVal must be greater than or equal to 0, and less than the number
  11326. ** of columns in the table affected by the current change. Otherwise,
  11327. ** [SQLITE_RANGE] is returned and *ppValue is set to NULL.
  11328. **
  11329. ** If successful, this function sets *ppValue to point to a protected
  11330. ** sqlite3_value object containing the iVal'th value from the vector of
  11331. ** new row values stored as part of the UPDATE or INSERT change and
  11332. ** returns SQLITE_OK. If the change is an UPDATE and does not include
  11333. ** a new value for the requested column, *ppValue is set to NULL and
  11334. ** SQLITE_OK returned. The name of the function comes from the fact that
  11335. ** this is similar to the "new.*" columns available to update or delete
  11336. ** triggers.
  11337. **
  11338. ** If some other error occurs (e.g. an OOM condition), an SQLite error code
  11339. ** is returned and *ppValue is set to NULL.
  11340. */
  11341. SQLITE_API int sqlite3changeset_new(
  11342. sqlite3_changeset_iter *pIter, /* Changeset iterator */
  11343. int iVal, /* Column number */
  11344. sqlite3_value **ppValue /* OUT: New value (or NULL pointer) */
  11345. );
  11346. /*
  11347. ** CAPI3REF: Obtain Conflicting Row Values From A Changeset Iterator
  11348. ** METHOD: sqlite3_changeset_iter
  11349. **
  11350. ** This function should only be used with iterator objects passed to a
  11351. ** conflict-handler callback by [sqlite3changeset_apply()] with either
  11352. ** [SQLITE_CHANGESET_DATA] or [SQLITE_CHANGESET_CONFLICT]. If this function
  11353. ** is called on any other iterator, [SQLITE_MISUSE] is returned and *ppValue
  11354. ** is set to NULL.
  11355. **
  11356. ** Argument iVal must be greater than or equal to 0, and less than the number
  11357. ** of columns in the table affected by the current change. Otherwise,
  11358. ** [SQLITE_RANGE] is returned and *ppValue is set to NULL.
  11359. **
  11360. ** If successful, this function sets *ppValue to point to a protected
  11361. ** sqlite3_value object containing the iVal'th value from the
  11362. ** "conflicting row" associated with the current conflict-handler callback
  11363. ** and returns SQLITE_OK.
  11364. **
  11365. ** If some other error occurs (e.g. an OOM condition), an SQLite error code
  11366. ** is returned and *ppValue is set to NULL.
  11367. */
  11368. SQLITE_API int sqlite3changeset_conflict(
  11369. sqlite3_changeset_iter *pIter, /* Changeset iterator */
  11370. int iVal, /* Column number */
  11371. sqlite3_value **ppValue /* OUT: Value from conflicting row */
  11372. );
  11373. /*
  11374. ** CAPI3REF: Determine The Number Of Foreign Key Constraint Violations
  11375. ** METHOD: sqlite3_changeset_iter
  11376. **
  11377. ** This function may only be called with an iterator passed to an
  11378. ** SQLITE_CHANGESET_FOREIGN_KEY conflict handler callback. In this case
  11379. ** it sets the output variable to the total number of known foreign key
  11380. ** violations in the destination database and returns SQLITE_OK.
  11381. **
  11382. ** In all other cases this function returns SQLITE_MISUSE.
  11383. */
  11384. SQLITE_API int sqlite3changeset_fk_conflicts(
  11385. sqlite3_changeset_iter *pIter, /* Changeset iterator */
  11386. int *pnOut /* OUT: Number of FK violations */
  11387. );
  11388. /*
  11389. ** CAPI3REF: Finalize A Changeset Iterator
  11390. ** METHOD: sqlite3_changeset_iter
  11391. **
  11392. ** This function is used to finalize an iterator allocated with
  11393. ** [sqlite3changeset_start()].
  11394. **
  11395. ** This function should only be called on iterators created using the
  11396. ** [sqlite3changeset_start()] function. If an application calls this
  11397. ** function with an iterator passed to a conflict-handler by
  11398. ** [sqlite3changeset_apply()], [SQLITE_MISUSE] is immediately returned and the
  11399. ** call has no effect.
  11400. **
  11401. ** If an error was encountered within a call to an sqlite3changeset_xxx()
  11402. ** function (for example an [SQLITE_CORRUPT] in [sqlite3changeset_next()] or an
  11403. ** [SQLITE_NOMEM] in [sqlite3changeset_new()]) then an error code corresponding
  11404. ** to that error is returned by this function. Otherwise, SQLITE_OK is
  11405. ** returned. This is to allow the following pattern (pseudo-code):
  11406. **
  11407. ** <pre>
  11408. ** sqlite3changeset_start();
  11409. ** while( SQLITE_ROW==sqlite3changeset_next() ){
  11410. ** // Do something with change.
  11411. ** }
  11412. ** rc = sqlite3changeset_finalize();
  11413. ** if( rc!=SQLITE_OK ){
  11414. ** // An error has occurred
  11415. ** }
  11416. ** </pre>
  11417. */
  11418. SQLITE_API int sqlite3changeset_finalize(sqlite3_changeset_iter *pIter);
  11419. /*
  11420. ** CAPI3REF: Invert A Changeset
  11421. **
  11422. ** This function is used to "invert" a changeset object. Applying an inverted
  11423. ** changeset to a database reverses the effects of applying the uninverted
  11424. ** changeset. Specifically:
  11425. **
  11426. ** <ul>
  11427. ** <li> Each DELETE change is changed to an INSERT, and
  11428. ** <li> Each INSERT change is changed to a DELETE, and
  11429. ** <li> For each UPDATE change, the old.* and new.* values are exchanged.
  11430. ** </ul>
  11431. **
  11432. ** This function does not change the order in which changes appear within
  11433. ** the changeset. It merely reverses the sense of each individual change.
  11434. **
  11435. ** If successful, a pointer to a buffer containing the inverted changeset
  11436. ** is stored in *ppOut, the size of the same buffer is stored in *pnOut, and
  11437. ** SQLITE_OK is returned. If an error occurs, both *pnOut and *ppOut are
  11438. ** zeroed and an SQLite error code returned.
  11439. **
  11440. ** It is the responsibility of the caller to eventually call sqlite3_free()
  11441. ** on the *ppOut pointer to free the buffer allocation following a successful
  11442. ** call to this function.
  11443. **
  11444. ** WARNING/TODO: This function currently assumes that the input is a valid
  11445. ** changeset. If it is not, the results are undefined.
  11446. */
  11447. SQLITE_API int sqlite3changeset_invert(
  11448. int nIn, const void *pIn, /* Input changeset */
  11449. int *pnOut, void **ppOut /* OUT: Inverse of input */
  11450. );
  11451. /*
  11452. ** CAPI3REF: Concatenate Two Changeset Objects
  11453. **
  11454. ** This function is used to concatenate two changesets, A and B, into a
  11455. ** single changeset. The result is a changeset equivalent to applying
  11456. ** changeset A followed by changeset B.
  11457. **
  11458. ** This function combines the two input changesets using an
  11459. ** sqlite3_changegroup object. Calling it produces similar results as the
  11460. ** following code fragment:
  11461. **
  11462. ** <pre>
  11463. ** sqlite3_changegroup *pGrp;
  11464. ** rc = sqlite3_changegroup_new(&pGrp);
  11465. ** if( rc==SQLITE_OK ) rc = sqlite3changegroup_add(pGrp, nA, pA);
  11466. ** if( rc==SQLITE_OK ) rc = sqlite3changegroup_add(pGrp, nB, pB);
  11467. ** if( rc==SQLITE_OK ){
  11468. ** rc = sqlite3changegroup_output(pGrp, pnOut, ppOut);
  11469. ** }else{
  11470. ** *ppOut = 0;
  11471. ** *pnOut = 0;
  11472. ** }
  11473. ** </pre>
  11474. **
  11475. ** Refer to the sqlite3_changegroup documentation below for details.
  11476. */
  11477. SQLITE_API int sqlite3changeset_concat(
  11478. int nA, /* Number of bytes in buffer pA */
  11479. void *pA, /* Pointer to buffer containing changeset A */
  11480. int nB, /* Number of bytes in buffer pB */
  11481. void *pB, /* Pointer to buffer containing changeset B */
  11482. int *pnOut, /* OUT: Number of bytes in output changeset */
  11483. void **ppOut /* OUT: Buffer containing output changeset */
  11484. );
  11485. /*
  11486. ** CAPI3REF: Changegroup Handle
  11487. **
  11488. ** A changegroup is an object used to combine two or more
  11489. ** [changesets] or [patchsets]
  11490. */
  11491. typedef struct sqlite3_changegroup sqlite3_changegroup;
  11492. /*
  11493. ** CAPI3REF: Create A New Changegroup Object
  11494. ** CONSTRUCTOR: sqlite3_changegroup
  11495. **
  11496. ** An sqlite3_changegroup object is used to combine two or more changesets
  11497. ** (or patchsets) into a single changeset (or patchset). A single changegroup
  11498. ** object may combine changesets or patchsets, but not both. The output is
  11499. ** always in the same format as the input.
  11500. **
  11501. ** If successful, this function returns SQLITE_OK and populates (*pp) with
  11502. ** a pointer to a new sqlite3_changegroup object before returning. The caller
  11503. ** should eventually free the returned object using a call to
  11504. ** sqlite3changegroup_delete(). If an error occurs, an SQLite error code
  11505. ** (i.e. SQLITE_NOMEM) is returned and *pp is set to NULL.
  11506. **
  11507. ** The usual usage pattern for an sqlite3_changegroup object is as follows:
  11508. **
  11509. ** <ul>
  11510. ** <li> It is created using a call to sqlite3changegroup_new().
  11511. **
  11512. ** <li> Zero or more changesets (or patchsets) are added to the object
  11513. ** by calling sqlite3changegroup_add().
  11514. **
  11515. ** <li> The result of combining all input changesets together is obtained
  11516. ** by the application via a call to sqlite3changegroup_output().
  11517. **
  11518. ** <li> The object is deleted using a call to sqlite3changegroup_delete().
  11519. ** </ul>
  11520. **
  11521. ** Any number of calls to add() and output() may be made between the calls to
  11522. ** new() and delete(), and in any order.
  11523. **
  11524. ** As well as the regular sqlite3changegroup_add() and
  11525. ** sqlite3changegroup_output() functions, also available are the streaming
  11526. ** versions sqlite3changegroup_add_strm() and sqlite3changegroup_output_strm().
  11527. */
  11528. SQLITE_API int sqlite3changegroup_new(sqlite3_changegroup **pp);
  11529. /*
  11530. ** CAPI3REF: Add A Changeset To A Changegroup
  11531. ** METHOD: sqlite3_changegroup
  11532. **
  11533. ** Add all changes within the changeset (or patchset) in buffer pData (size
  11534. ** nData bytes) to the changegroup.
  11535. **
  11536. ** If the buffer contains a patchset, then all prior calls to this function
  11537. ** on the same changegroup object must also have specified patchsets. Or, if
  11538. ** the buffer contains a changeset, so must have the earlier calls to this
  11539. ** function. Otherwise, SQLITE_ERROR is returned and no changes are added
  11540. ** to the changegroup.
  11541. **
  11542. ** Rows within the changeset and changegroup are identified by the values in
  11543. ** their PRIMARY KEY columns. A change in the changeset is considered to
  11544. ** apply to the same row as a change already present in the changegroup if
  11545. ** the two rows have the same primary key.
  11546. **
  11547. ** Changes to rows that do not already appear in the changegroup are
  11548. ** simply copied into it. Or, if both the new changeset and the changegroup
  11549. ** contain changes that apply to a single row, the final contents of the
  11550. ** changegroup depends on the type of each change, as follows:
  11551. **
  11552. ** <table border=1 style="margin-left:8ex;margin-right:8ex">
  11553. ** <tr><th style="white-space:pre">Existing Change </th>
  11554. ** <th style="white-space:pre">New Change </th>
  11555. ** <th>Output Change
  11556. ** <tr><td>INSERT <td>INSERT <td>
  11557. ** The new change is ignored. This case does not occur if the new
  11558. ** changeset was recorded immediately after the changesets already
  11559. ** added to the changegroup.
  11560. ** <tr><td>INSERT <td>UPDATE <td>
  11561. ** The INSERT change remains in the changegroup. The values in the
  11562. ** INSERT change are modified as if the row was inserted by the
  11563. ** existing change and then updated according to the new change.
  11564. ** <tr><td>INSERT <td>DELETE <td>
  11565. ** The existing INSERT is removed from the changegroup. The DELETE is
  11566. ** not added.
  11567. ** <tr><td>UPDATE <td>INSERT <td>
  11568. ** The new change is ignored. This case does not occur if the new
  11569. ** changeset was recorded immediately after the changesets already
  11570. ** added to the changegroup.
  11571. ** <tr><td>UPDATE <td>UPDATE <td>
  11572. ** The existing UPDATE remains within the changegroup. It is amended
  11573. ** so that the accompanying values are as if the row was updated once
  11574. ** by the existing change and then again by the new change.
  11575. ** <tr><td>UPDATE <td>DELETE <td>
  11576. ** The existing UPDATE is replaced by the new DELETE within the
  11577. ** changegroup.
  11578. ** <tr><td>DELETE <td>INSERT <td>
  11579. ** If one or more of the column values in the row inserted by the
  11580. ** new change differ from those in the row deleted by the existing
  11581. ** change, the existing DELETE is replaced by an UPDATE within the
  11582. ** changegroup. Otherwise, if the inserted row is exactly the same
  11583. ** as the deleted row, the existing DELETE is simply discarded.
  11584. ** <tr><td>DELETE <td>UPDATE <td>
  11585. ** The new change is ignored. This case does not occur if the new
  11586. ** changeset was recorded immediately after the changesets already
  11587. ** added to the changegroup.
  11588. ** <tr><td>DELETE <td>DELETE <td>
  11589. ** The new change is ignored. This case does not occur if the new
  11590. ** changeset was recorded immediately after the changesets already
  11591. ** added to the changegroup.
  11592. ** </table>
  11593. **
  11594. ** If the new changeset contains changes to a table that is already present
  11595. ** in the changegroup, then the number of columns and the position of the
  11596. ** primary key columns for the table must be consistent. If this is not the
  11597. ** case, this function fails with SQLITE_SCHEMA. If the input changeset
  11598. ** appears to be corrupt and the corruption is detected, SQLITE_CORRUPT is
  11599. ** returned. Or, if an out-of-memory condition occurs during processing, this
  11600. ** function returns SQLITE_NOMEM. In all cases, if an error occurs the state
  11601. ** of the final contents of the changegroup is undefined.
  11602. **
  11603. ** If no error occurs, SQLITE_OK is returned.
  11604. */
  11605. SQLITE_API int sqlite3changegroup_add(sqlite3_changegroup*, int nData, void *pData);
  11606. /*
  11607. ** CAPI3REF: Obtain A Composite Changeset From A Changegroup
  11608. ** METHOD: sqlite3_changegroup
  11609. **
  11610. ** Obtain a buffer containing a changeset (or patchset) representing the
  11611. ** current contents of the changegroup. If the inputs to the changegroup
  11612. ** were themselves changesets, the output is a changeset. Or, if the
  11613. ** inputs were patchsets, the output is also a patchset.
  11614. **
  11615. ** As with the output of the sqlite3session_changeset() and
  11616. ** sqlite3session_patchset() functions, all changes related to a single
  11617. ** table are grouped together in the output of this function. Tables appear
  11618. ** in the same order as for the very first changeset added to the changegroup.
  11619. ** If the second or subsequent changesets added to the changegroup contain
  11620. ** changes for tables that do not appear in the first changeset, they are
  11621. ** appended onto the end of the output changeset, again in the order in
  11622. ** which they are first encountered.
  11623. **
  11624. ** If an error occurs, an SQLite error code is returned and the output
  11625. ** variables (*pnData) and (*ppData) are set to 0. Otherwise, SQLITE_OK
  11626. ** is returned and the output variables are set to the size of and a
  11627. ** pointer to the output buffer, respectively. In this case it is the
  11628. ** responsibility of the caller to eventually free the buffer using a
  11629. ** call to sqlite3_free().
  11630. */
  11631. SQLITE_API int sqlite3changegroup_output(
  11632. sqlite3_changegroup*,
  11633. int *pnData, /* OUT: Size of output buffer in bytes */
  11634. void **ppData /* OUT: Pointer to output buffer */
  11635. );
  11636. /*
  11637. ** CAPI3REF: Delete A Changegroup Object
  11638. ** DESTRUCTOR: sqlite3_changegroup
  11639. */
  11640. SQLITE_API void sqlite3changegroup_delete(sqlite3_changegroup*);
  11641. /*
  11642. ** CAPI3REF: Apply A Changeset To A Database
  11643. **
  11644. ** Apply a changeset or patchset to a database. These functions attempt to
  11645. ** update the "main" database attached to handle db with the changes found in
  11646. ** the changeset passed via the second and third arguments.
  11647. **
  11648. ** The fourth argument (xFilter) passed to these functions is the "filter
  11649. ** callback". If it is not NULL, then for each table affected by at least one
  11650. ** change in the changeset, the filter callback is invoked with
  11651. ** the table name as the second argument, and a copy of the context pointer
  11652. ** passed as the sixth argument as the first. If the "filter callback"
  11653. ** returns zero, then no attempt is made to apply any changes to the table.
  11654. ** Otherwise, if the return value is non-zero or the xFilter argument to
  11655. ** is NULL, all changes related to the table are attempted.
  11656. **
  11657. ** For each table that is not excluded by the filter callback, this function
  11658. ** tests that the target database contains a compatible table. A table is
  11659. ** considered compatible if all of the following are true:
  11660. **
  11661. ** <ul>
  11662. ** <li> The table has the same name as the name recorded in the
  11663. ** changeset, and
  11664. ** <li> The table has at least as many columns as recorded in the
  11665. ** changeset, and
  11666. ** <li> The table has primary key columns in the same position as
  11667. ** recorded in the changeset.
  11668. ** </ul>
  11669. **
  11670. ** If there is no compatible table, it is not an error, but none of the
  11671. ** changes associated with the table are applied. A warning message is issued
  11672. ** via the sqlite3_log() mechanism with the error code SQLITE_SCHEMA. At most
  11673. ** one such warning is issued for each table in the changeset.
  11674. **
  11675. ** For each change for which there is a compatible table, an attempt is made
  11676. ** to modify the table contents according to the UPDATE, INSERT or DELETE
  11677. ** change. If a change cannot be applied cleanly, the conflict handler
  11678. ** function passed as the fifth argument to sqlite3changeset_apply() may be
  11679. ** invoked. A description of exactly when the conflict handler is invoked for
  11680. ** each type of change is below.
  11681. **
  11682. ** Unlike the xFilter argument, xConflict may not be passed NULL. The results
  11683. ** of passing anything other than a valid function pointer as the xConflict
  11684. ** argument are undefined.
  11685. **
  11686. ** Each time the conflict handler function is invoked, it must return one
  11687. ** of [SQLITE_CHANGESET_OMIT], [SQLITE_CHANGESET_ABORT] or
  11688. ** [SQLITE_CHANGESET_REPLACE]. SQLITE_CHANGESET_REPLACE may only be returned
  11689. ** if the second argument passed to the conflict handler is either
  11690. ** SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT. If the conflict-handler
  11691. ** returns an illegal value, any changes already made are rolled back and
  11692. ** the call to sqlite3changeset_apply() returns SQLITE_MISUSE. Different
  11693. ** actions are taken by sqlite3changeset_apply() depending on the value
  11694. ** returned by each invocation of the conflict-handler function. Refer to
  11695. ** the documentation for the three
  11696. ** [SQLITE_CHANGESET_OMIT|available return values] for details.
  11697. **
  11698. ** <dl>
  11699. ** <dt>DELETE Changes<dd>
  11700. ** For each DELETE change, the function checks if the target database
  11701. ** contains a row with the same primary key value (or values) as the
  11702. ** original row values stored in the changeset. If it does, and the values
  11703. ** stored in all non-primary key columns also match the values stored in
  11704. ** the changeset the row is deleted from the target database.
  11705. **
  11706. ** If a row with matching primary key values is found, but one or more of
  11707. ** the non-primary key fields contains a value different from the original
  11708. ** row value stored in the changeset, the conflict-handler function is
  11709. ** invoked with [SQLITE_CHANGESET_DATA] as the second argument. If the
  11710. ** database table has more columns than are recorded in the changeset,
  11711. ** only the values of those non-primary key fields are compared against
  11712. ** the current database contents - any trailing database table columns
  11713. ** are ignored.
  11714. **
  11715. ** If no row with matching primary key values is found in the database,
  11716. ** the conflict-handler function is invoked with [SQLITE_CHANGESET_NOTFOUND]
  11717. ** passed as the second argument.
  11718. **
  11719. ** If the DELETE operation is attempted, but SQLite returns SQLITE_CONSTRAINT
  11720. ** (which can only happen if a foreign key constraint is violated), the
  11721. ** conflict-handler function is invoked with [SQLITE_CHANGESET_CONSTRAINT]
  11722. ** passed as the second argument. This includes the case where the DELETE
  11723. ** operation is attempted because an earlier call to the conflict handler
  11724. ** function returned [SQLITE_CHANGESET_REPLACE].
  11725. **
  11726. ** <dt>INSERT Changes<dd>
  11727. ** For each INSERT change, an attempt is made to insert the new row into
  11728. ** the database. If the changeset row contains fewer fields than the
  11729. ** database table, the trailing fields are populated with their default
  11730. ** values.
  11731. **
  11732. ** If the attempt to insert the row fails because the database already
  11733. ** contains a row with the same primary key values, the conflict handler
  11734. ** function is invoked with the second argument set to
  11735. ** [SQLITE_CHANGESET_CONFLICT].
  11736. **
  11737. ** If the attempt to insert the row fails because of some other constraint
  11738. ** violation (e.g. NOT NULL or UNIQUE), the conflict handler function is
  11739. ** invoked with the second argument set to [SQLITE_CHANGESET_CONSTRAINT].
  11740. ** This includes the case where the INSERT operation is re-attempted because
  11741. ** an earlier call to the conflict handler function returned
  11742. ** [SQLITE_CHANGESET_REPLACE].
  11743. **
  11744. ** <dt>UPDATE Changes<dd>
  11745. ** For each UPDATE change, the function checks if the target database
  11746. ** contains a row with the same primary key value (or values) as the
  11747. ** original row values stored in the changeset. If it does, and the values
  11748. ** stored in all modified non-primary key columns also match the values
  11749. ** stored in the changeset the row is updated within the target database.
  11750. **
  11751. ** If a row with matching primary key values is found, but one or more of
  11752. ** the modified non-primary key fields contains a value different from an
  11753. ** original row value stored in the changeset, the conflict-handler function
  11754. ** is invoked with [SQLITE_CHANGESET_DATA] as the second argument. Since
  11755. ** UPDATE changes only contain values for non-primary key fields that are
  11756. ** to be modified, only those fields need to match the original values to
  11757. ** avoid the SQLITE_CHANGESET_DATA conflict-handler callback.
  11758. **
  11759. ** If no row with matching primary key values is found in the database,
  11760. ** the conflict-handler function is invoked with [SQLITE_CHANGESET_NOTFOUND]
  11761. ** passed as the second argument.
  11762. **
  11763. ** If the UPDATE operation is attempted, but SQLite returns
  11764. ** SQLITE_CONSTRAINT, the conflict-handler function is invoked with
  11765. ** [SQLITE_CHANGESET_CONSTRAINT] passed as the second argument.
  11766. ** This includes the case where the UPDATE operation is attempted after
  11767. ** an earlier call to the conflict handler function returned
  11768. ** [SQLITE_CHANGESET_REPLACE].
  11769. ** </dl>
  11770. **
  11771. ** It is safe to execute SQL statements, including those that write to the
  11772. ** table that the callback related to, from within the xConflict callback.
  11773. ** This can be used to further customize the application's conflict
  11774. ** resolution strategy.
  11775. **
  11776. ** All changes made by these functions are enclosed in a savepoint transaction.
  11777. ** If any other error (aside from a constraint failure when attempting to
  11778. ** write to the target database) occurs, then the savepoint transaction is
  11779. ** rolled back, restoring the target database to its original state, and an
  11780. ** SQLite error code returned.
  11781. **
  11782. ** If the output parameters (ppRebase) and (pnRebase) are non-NULL and
  11783. ** the input is a changeset (not a patchset), then sqlite3changeset_apply_v2()
  11784. ** may set (*ppRebase) to point to a "rebase" that may be used with the
  11785. ** sqlite3_rebaser APIs buffer before returning. In this case (*pnRebase)
  11786. ** is set to the size of the buffer in bytes. It is the responsibility of the
  11787. ** caller to eventually free any such buffer using sqlite3_free(). The buffer
  11788. ** is only allocated and populated if one or more conflicts were encountered
  11789. ** while applying the patchset. See comments surrounding the sqlite3_rebaser
  11790. ** APIs for further details.
  11791. **
  11792. ** The behavior of sqlite3changeset_apply_v2() and its streaming equivalent
  11793. ** may be modified by passing a combination of
  11794. ** [SQLITE_CHANGESETAPPLY_NOSAVEPOINT | supported flags] as the 9th parameter.
  11795. **
  11796. ** Note that the sqlite3changeset_apply_v2() API is still <b>experimental</b>
  11797. ** and therefore subject to change.
  11798. */
  11799. SQLITE_API int sqlite3changeset_apply(
  11800. sqlite3 *db, /* Apply change to "main" db of this handle */
  11801. int nChangeset, /* Size of changeset in bytes */
  11802. void *pChangeset, /* Changeset blob */
  11803. int(*xFilter)(
  11804. void *pCtx, /* Copy of sixth arg to _apply() */
  11805. const char *zTab /* Table name */
  11806. ),
  11807. int(*xConflict)(
  11808. void *pCtx, /* Copy of sixth arg to _apply() */
  11809. int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
  11810. sqlite3_changeset_iter *p /* Handle describing change and conflict */
  11811. ),
  11812. void *pCtx /* First argument passed to xConflict */
  11813. );
  11814. SQLITE_API int sqlite3changeset_apply_v2(
  11815. sqlite3 *db, /* Apply change to "main" db of this handle */
  11816. int nChangeset, /* Size of changeset in bytes */
  11817. void *pChangeset, /* Changeset blob */
  11818. int(*xFilter)(
  11819. void *pCtx, /* Copy of sixth arg to _apply() */
  11820. const char *zTab /* Table name */
  11821. ),
  11822. int(*xConflict)(
  11823. void *pCtx, /* Copy of sixth arg to _apply() */
  11824. int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
  11825. sqlite3_changeset_iter *p /* Handle describing change and conflict */
  11826. ),
  11827. void *pCtx, /* First argument passed to xConflict */
  11828. void **ppRebase, int *pnRebase, /* OUT: Rebase data */
  11829. int flags /* SESSION_CHANGESETAPPLY_* flags */
  11830. );
  11831. /*
  11832. ** CAPI3REF: Flags for sqlite3changeset_apply_v2
  11833. **
  11834. ** The following flags may passed via the 9th parameter to
  11835. ** [sqlite3changeset_apply_v2] and [sqlite3changeset_apply_v2_strm]:
  11836. **
  11837. ** <dl>
  11838. ** <dt>SQLITE_CHANGESETAPPLY_NOSAVEPOINT <dd>
  11839. ** Usually, the sessions module encloses all operations performed by
  11840. ** a single call to apply_v2() or apply_v2_strm() in a [SAVEPOINT]. The
  11841. ** SAVEPOINT is committed if the changeset or patchset is successfully
  11842. ** applied, or rolled back if an error occurs. Specifying this flag
  11843. ** causes the sessions module to omit this savepoint. In this case, if the
  11844. ** caller has an open transaction or savepoint when apply_v2() is called,
  11845. ** it may revert the partially applied changeset by rolling it back.
  11846. **
  11847. ** <dt>SQLITE_CHANGESETAPPLY_INVERT <dd>
  11848. ** Invert the changeset before applying it. This is equivalent to inverting
  11849. ** a changeset using sqlite3changeset_invert() before applying it. It is
  11850. ** an error to specify this flag with a patchset.
  11851. */
  11852. #define SQLITE_CHANGESETAPPLY_NOSAVEPOINT 0x0001
  11853. #define SQLITE_CHANGESETAPPLY_INVERT 0x0002
  11854. /*
  11855. ** CAPI3REF: Constants Passed To The Conflict Handler
  11856. **
  11857. ** Values that may be passed as the second argument to a conflict-handler.
  11858. **
  11859. ** <dl>
  11860. ** <dt>SQLITE_CHANGESET_DATA<dd>
  11861. ** The conflict handler is invoked with CHANGESET_DATA as the second argument
  11862. ** when processing a DELETE or UPDATE change if a row with the required
  11863. ** PRIMARY KEY fields is present in the database, but one or more other
  11864. ** (non primary-key) fields modified by the update do not contain the
  11865. ** expected "before" values.
  11866. **
  11867. ** The conflicting row, in this case, is the database row with the matching
  11868. ** primary key.
  11869. **
  11870. ** <dt>SQLITE_CHANGESET_NOTFOUND<dd>
  11871. ** The conflict handler is invoked with CHANGESET_NOTFOUND as the second
  11872. ** argument when processing a DELETE or UPDATE change if a row with the
  11873. ** required PRIMARY KEY fields is not present in the database.
  11874. **
  11875. ** There is no conflicting row in this case. The results of invoking the
  11876. ** sqlite3changeset_conflict() API are undefined.
  11877. **
  11878. ** <dt>SQLITE_CHANGESET_CONFLICT<dd>
  11879. ** CHANGESET_CONFLICT is passed as the second argument to the conflict
  11880. ** handler while processing an INSERT change if the operation would result
  11881. ** in duplicate primary key values.
  11882. **
  11883. ** The conflicting row in this case is the database row with the matching
  11884. ** primary key.
  11885. **
  11886. ** <dt>SQLITE_CHANGESET_FOREIGN_KEY<dd>
  11887. ** If foreign key handling is enabled, and applying a changeset leaves the
  11888. ** database in a state containing foreign key violations, the conflict
  11889. ** handler is invoked with CHANGESET_FOREIGN_KEY as the second argument
  11890. ** exactly once before the changeset is committed. If the conflict handler
  11891. ** returns CHANGESET_OMIT, the changes, including those that caused the
  11892. ** foreign key constraint violation, are committed. Or, if it returns
  11893. ** CHANGESET_ABORT, the changeset is rolled back.
  11894. **
  11895. ** No current or conflicting row information is provided. The only function
  11896. ** it is possible to call on the supplied sqlite3_changeset_iter handle
  11897. ** is sqlite3changeset_fk_conflicts().
  11898. **
  11899. ** <dt>SQLITE_CHANGESET_CONSTRAINT<dd>
  11900. ** If any other constraint violation occurs while applying a change (i.e.
  11901. ** a UNIQUE, CHECK or NOT NULL constraint), the conflict handler is
  11902. ** invoked with CHANGESET_CONSTRAINT as the second argument.
  11903. **
  11904. ** There is no conflicting row in this case. The results of invoking the
  11905. ** sqlite3changeset_conflict() API are undefined.
  11906. **
  11907. ** </dl>
  11908. */
  11909. #define SQLITE_CHANGESET_DATA 1
  11910. #define SQLITE_CHANGESET_NOTFOUND 2
  11911. #define SQLITE_CHANGESET_CONFLICT 3
  11912. #define SQLITE_CHANGESET_CONSTRAINT 4
  11913. #define SQLITE_CHANGESET_FOREIGN_KEY 5
  11914. /*
  11915. ** CAPI3REF: Constants Returned By The Conflict Handler
  11916. **
  11917. ** A conflict handler callback must return one of the following three values.
  11918. **
  11919. ** <dl>
  11920. ** <dt>SQLITE_CHANGESET_OMIT<dd>
  11921. ** If a conflict handler returns this value no special action is taken. The
  11922. ** change that caused the conflict is not applied. The session module
  11923. ** continues to the next change in the changeset.
  11924. **
  11925. ** <dt>SQLITE_CHANGESET_REPLACE<dd>
  11926. ** This value may only be returned if the second argument to the conflict
  11927. ** handler was SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT. If this
  11928. ** is not the case, any changes applied so far are rolled back and the
  11929. ** call to sqlite3changeset_apply() returns SQLITE_MISUSE.
  11930. **
  11931. ** If CHANGESET_REPLACE is returned by an SQLITE_CHANGESET_DATA conflict
  11932. ** handler, then the conflicting row is either updated or deleted, depending
  11933. ** on the type of change.
  11934. **
  11935. ** If CHANGESET_REPLACE is returned by an SQLITE_CHANGESET_CONFLICT conflict
  11936. ** handler, then the conflicting row is removed from the database and a
  11937. ** second attempt to apply the change is made. If this second attempt fails,
  11938. ** the original row is restored to the database before continuing.
  11939. **
  11940. ** <dt>SQLITE_CHANGESET_ABORT<dd>
  11941. ** If this value is returned, any changes applied so far are rolled back
  11942. ** and the call to sqlite3changeset_apply() returns SQLITE_ABORT.
  11943. ** </dl>
  11944. */
  11945. #define SQLITE_CHANGESET_OMIT 0
  11946. #define SQLITE_CHANGESET_REPLACE 1
  11947. #define SQLITE_CHANGESET_ABORT 2
  11948. /*
  11949. ** CAPI3REF: Rebasing changesets
  11950. ** EXPERIMENTAL
  11951. **
  11952. ** Suppose there is a site hosting a database in state S0. And that
  11953. ** modifications are made that move that database to state S1 and a
  11954. ** changeset recorded (the "local" changeset). Then, a changeset based
  11955. ** on S0 is received from another site (the "remote" changeset) and
  11956. ** applied to the database. The database is then in state
  11957. ** (S1+"remote"), where the exact state depends on any conflict
  11958. ** resolution decisions (OMIT or REPLACE) made while applying "remote".
  11959. ** Rebasing a changeset is to update it to take those conflict
  11960. ** resolution decisions into account, so that the same conflicts
  11961. ** do not have to be resolved elsewhere in the network.
  11962. **
  11963. ** For example, if both the local and remote changesets contain an
  11964. ** INSERT of the same key on "CREATE TABLE t1(a PRIMARY KEY, b)":
  11965. **
  11966. ** local: INSERT INTO t1 VALUES(1, 'v1');
  11967. ** remote: INSERT INTO t1 VALUES(1, 'v2');
  11968. **
  11969. ** and the conflict resolution is REPLACE, then the INSERT change is
  11970. ** removed from the local changeset (it was overridden). Or, if the
  11971. ** conflict resolution was "OMIT", then the local changeset is modified
  11972. ** to instead contain:
  11973. **
  11974. ** UPDATE t1 SET b = 'v2' WHERE a=1;
  11975. **
  11976. ** Changes within the local changeset are rebased as follows:
  11977. **
  11978. ** <dl>
  11979. ** <dt>Local INSERT<dd>
  11980. ** This may only conflict with a remote INSERT. If the conflict
  11981. ** resolution was OMIT, then add an UPDATE change to the rebased
  11982. ** changeset. Or, if the conflict resolution was REPLACE, add
  11983. ** nothing to the rebased changeset.
  11984. **
  11985. ** <dt>Local DELETE<dd>
  11986. ** This may conflict with a remote UPDATE or DELETE. In both cases the
  11987. ** only possible resolution is OMIT. If the remote operation was a
  11988. ** DELETE, then add no change to the rebased changeset. If the remote
  11989. ** operation was an UPDATE, then the old.* fields of change are updated
  11990. ** to reflect the new.* values in the UPDATE.
  11991. **
  11992. ** <dt>Local UPDATE<dd>
  11993. ** This may conflict with a remote UPDATE or DELETE. If it conflicts
  11994. ** with a DELETE, and the conflict resolution was OMIT, then the update
  11995. ** is changed into an INSERT. Any undefined values in the new.* record
  11996. ** from the update change are filled in using the old.* values from
  11997. ** the conflicting DELETE. Or, if the conflict resolution was REPLACE,
  11998. ** the UPDATE change is simply omitted from the rebased changeset.
  11999. **
  12000. ** If conflict is with a remote UPDATE and the resolution is OMIT, then
  12001. ** the old.* values are rebased using the new.* values in the remote
  12002. ** change. Or, if the resolution is REPLACE, then the change is copied
  12003. ** into the rebased changeset with updates to columns also updated by
  12004. ** the conflicting remote UPDATE removed. If this means no columns would
  12005. ** be updated, the change is omitted.
  12006. ** </dl>
  12007. **
  12008. ** A local change may be rebased against multiple remote changes
  12009. ** simultaneously. If a single key is modified by multiple remote
  12010. ** changesets, they are combined as follows before the local changeset
  12011. ** is rebased:
  12012. **
  12013. ** <ul>
  12014. ** <li> If there has been one or more REPLACE resolutions on a
  12015. ** key, it is rebased according to a REPLACE.
  12016. **
  12017. ** <li> If there have been no REPLACE resolutions on a key, then
  12018. ** the local changeset is rebased according to the most recent
  12019. ** of the OMIT resolutions.
  12020. ** </ul>
  12021. **
  12022. ** Note that conflict resolutions from multiple remote changesets are
  12023. ** combined on a per-field basis, not per-row. This means that in the
  12024. ** case of multiple remote UPDATE operations, some fields of a single
  12025. ** local change may be rebased for REPLACE while others are rebased for
  12026. ** OMIT.
  12027. **
  12028. ** In order to rebase a local changeset, the remote changeset must first
  12029. ** be applied to the local database using sqlite3changeset_apply_v2() and
  12030. ** the buffer of rebase information captured. Then:
  12031. **
  12032. ** <ol>
  12033. ** <li> An sqlite3_rebaser object is created by calling
  12034. ** sqlite3rebaser_create().
  12035. ** <li> The new object is configured with the rebase buffer obtained from
  12036. ** sqlite3changeset_apply_v2() by calling sqlite3rebaser_configure().
  12037. ** If the local changeset is to be rebased against multiple remote
  12038. ** changesets, then sqlite3rebaser_configure() should be called
  12039. ** multiple times, in the same order that the multiple
  12040. ** sqlite3changeset_apply_v2() calls were made.
  12041. ** <li> Each local changeset is rebased by calling sqlite3rebaser_rebase().
  12042. ** <li> The sqlite3_rebaser object is deleted by calling
  12043. ** sqlite3rebaser_delete().
  12044. ** </ol>
  12045. */
  12046. typedef struct sqlite3_rebaser sqlite3_rebaser;
  12047. /*
  12048. ** CAPI3REF: Create a changeset rebaser object.
  12049. ** EXPERIMENTAL
  12050. **
  12051. ** Allocate a new changeset rebaser object. If successful, set (*ppNew) to
  12052. ** point to the new object and return SQLITE_OK. Otherwise, if an error
  12053. ** occurs, return an SQLite error code (e.g. SQLITE_NOMEM) and set (*ppNew)
  12054. ** to NULL.
  12055. */
  12056. SQLITE_API int sqlite3rebaser_create(sqlite3_rebaser **ppNew);
  12057. /*
  12058. ** CAPI3REF: Configure a changeset rebaser object.
  12059. ** EXPERIMENTAL
  12060. **
  12061. ** Configure the changeset rebaser object to rebase changesets according
  12062. ** to the conflict resolutions described by buffer pRebase (size nRebase
  12063. ** bytes), which must have been obtained from a previous call to
  12064. ** sqlite3changeset_apply_v2().
  12065. */
  12066. SQLITE_API int sqlite3rebaser_configure(
  12067. sqlite3_rebaser*,
  12068. int nRebase, const void *pRebase
  12069. );
  12070. /*
  12071. ** CAPI3REF: Rebase a changeset
  12072. ** EXPERIMENTAL
  12073. **
  12074. ** Argument pIn must point to a buffer containing a changeset nIn bytes
  12075. ** in size. This function allocates and populates a buffer with a copy
  12076. ** of the changeset rebased according to the configuration of the
  12077. ** rebaser object passed as the first argument. If successful, (*ppOut)
  12078. ** is set to point to the new buffer containing the rebased changeset and
  12079. ** (*pnOut) to its size in bytes and SQLITE_OK returned. It is the
  12080. ** responsibility of the caller to eventually free the new buffer using
  12081. ** sqlite3_free(). Otherwise, if an error occurs, (*ppOut) and (*pnOut)
  12082. ** are set to zero and an SQLite error code returned.
  12083. */
  12084. SQLITE_API int sqlite3rebaser_rebase(
  12085. sqlite3_rebaser*,
  12086. int nIn, const void *pIn,
  12087. int *pnOut, void **ppOut
  12088. );
  12089. /*
  12090. ** CAPI3REF: Delete a changeset rebaser object.
  12091. ** EXPERIMENTAL
  12092. **
  12093. ** Delete the changeset rebaser object and all associated resources. There
  12094. ** should be one call to this function for each successful invocation
  12095. ** of sqlite3rebaser_create().
  12096. */
  12097. SQLITE_API void sqlite3rebaser_delete(sqlite3_rebaser *p);
  12098. /*
  12099. ** CAPI3REF: Streaming Versions of API functions.
  12100. **
  12101. ** The six streaming API xxx_strm() functions serve similar purposes to the
  12102. ** corresponding non-streaming API functions:
  12103. **
  12104. ** <table border=1 style="margin-left:8ex;margin-right:8ex">
  12105. ** <tr><th>Streaming function<th>Non-streaming equivalent</th>
  12106. ** <tr><td>sqlite3changeset_apply_strm<td>[sqlite3changeset_apply]
  12107. ** <tr><td>sqlite3changeset_apply_strm_v2<td>[sqlite3changeset_apply_v2]
  12108. ** <tr><td>sqlite3changeset_concat_strm<td>[sqlite3changeset_concat]
  12109. ** <tr><td>sqlite3changeset_invert_strm<td>[sqlite3changeset_invert]
  12110. ** <tr><td>sqlite3changeset_start_strm<td>[sqlite3changeset_start]
  12111. ** <tr><td>sqlite3session_changeset_strm<td>[sqlite3session_changeset]
  12112. ** <tr><td>sqlite3session_patchset_strm<td>[sqlite3session_patchset]
  12113. ** </table>
  12114. **
  12115. ** Non-streaming functions that accept changesets (or patchsets) as input
  12116. ** require that the entire changeset be stored in a single buffer in memory.
  12117. ** Similarly, those that return a changeset or patchset do so by returning
  12118. ** a pointer to a single large buffer allocated using sqlite3_malloc().
  12119. ** Normally this is convenient. However, if an application running in a
  12120. ** low-memory environment is required to handle very large changesets, the
  12121. ** large contiguous memory allocations required can become onerous.
  12122. **
  12123. ** In order to avoid this problem, instead of a single large buffer, input
  12124. ** is passed to a streaming API functions by way of a callback function that
  12125. ** the sessions module invokes to incrementally request input data as it is
  12126. ** required. In all cases, a pair of API function parameters such as
  12127. **
  12128. ** <pre>
  12129. ** &nbsp; int nChangeset,
  12130. ** &nbsp; void *pChangeset,
  12131. ** </pre>
  12132. **
  12133. ** Is replaced by:
  12134. **
  12135. ** <pre>
  12136. ** &nbsp; int (*xInput)(void *pIn, void *pData, int *pnData),
  12137. ** &nbsp; void *pIn,
  12138. ** </pre>
  12139. **
  12140. ** Each time the xInput callback is invoked by the sessions module, the first
  12141. ** argument passed is a copy of the supplied pIn context pointer. The second
  12142. ** argument, pData, points to a buffer (*pnData) bytes in size. Assuming no
  12143. ** error occurs the xInput method should copy up to (*pnData) bytes of data
  12144. ** into the buffer and set (*pnData) to the actual number of bytes copied
  12145. ** before returning SQLITE_OK. If the input is completely exhausted, (*pnData)
  12146. ** should be set to zero to indicate this. Or, if an error occurs, an SQLite
  12147. ** error code should be returned. In all cases, if an xInput callback returns
  12148. ** an error, all processing is abandoned and the streaming API function
  12149. ** returns a copy of the error code to the caller.
  12150. **
  12151. ** In the case of sqlite3changeset_start_strm(), the xInput callback may be
  12152. ** invoked by the sessions module at any point during the lifetime of the
  12153. ** iterator. If such an xInput callback returns an error, the iterator enters
  12154. ** an error state, whereby all subsequent calls to iterator functions
  12155. ** immediately fail with the same error code as returned by xInput.
  12156. **
  12157. ** Similarly, streaming API functions that return changesets (or patchsets)
  12158. ** return them in chunks by way of a callback function instead of via a
  12159. ** pointer to a single large buffer. In this case, a pair of parameters such
  12160. ** as:
  12161. **
  12162. ** <pre>
  12163. ** &nbsp; int *pnChangeset,
  12164. ** &nbsp; void **ppChangeset,
  12165. ** </pre>
  12166. **
  12167. ** Is replaced by:
  12168. **
  12169. ** <pre>
  12170. ** &nbsp; int (*xOutput)(void *pOut, const void *pData, int nData),
  12171. ** &nbsp; void *pOut
  12172. ** </pre>
  12173. **
  12174. ** The xOutput callback is invoked zero or more times to return data to
  12175. ** the application. The first parameter passed to each call is a copy of the
  12176. ** pOut pointer supplied by the application. The second parameter, pData,
  12177. ** points to a buffer nData bytes in size containing the chunk of output
  12178. ** data being returned. If the xOutput callback successfully processes the
  12179. ** supplied data, it should return SQLITE_OK to indicate success. Otherwise,
  12180. ** it should return some other SQLite error code. In this case processing
  12181. ** is immediately abandoned and the streaming API function returns a copy
  12182. ** of the xOutput error code to the application.
  12183. **
  12184. ** The sessions module never invokes an xOutput callback with the third
  12185. ** parameter set to a value less than or equal to zero. Other than this,
  12186. ** no guarantees are made as to the size of the chunks of data returned.
  12187. */
  12188. SQLITE_API int sqlite3changeset_apply_strm(
  12189. sqlite3 *db, /* Apply change to "main" db of this handle */
  12190. int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */
  12191. void *pIn, /* First arg for xInput */
  12192. int(*xFilter)(
  12193. void *pCtx, /* Copy of sixth arg to _apply() */
  12194. const char *zTab /* Table name */
  12195. ),
  12196. int(*xConflict)(
  12197. void *pCtx, /* Copy of sixth arg to _apply() */
  12198. int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
  12199. sqlite3_changeset_iter *p /* Handle describing change and conflict */
  12200. ),
  12201. void *pCtx /* First argument passed to xConflict */
  12202. );
  12203. SQLITE_API int sqlite3changeset_apply_v2_strm(
  12204. sqlite3 *db, /* Apply change to "main" db of this handle */
  12205. int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */
  12206. void *pIn, /* First arg for xInput */
  12207. int(*xFilter)(
  12208. void *pCtx, /* Copy of sixth arg to _apply() */
  12209. const char *zTab /* Table name */
  12210. ),
  12211. int(*xConflict)(
  12212. void *pCtx, /* Copy of sixth arg to _apply() */
  12213. int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
  12214. sqlite3_changeset_iter *p /* Handle describing change and conflict */
  12215. ),
  12216. void *pCtx, /* First argument passed to xConflict */
  12217. void **ppRebase, int *pnRebase,
  12218. int flags
  12219. );
  12220. SQLITE_API int sqlite3changeset_concat_strm(
  12221. int (*xInputA)(void *pIn, void *pData, int *pnData),
  12222. void *pInA,
  12223. int (*xInputB)(void *pIn, void *pData, int *pnData),
  12224. void *pInB,
  12225. int (*xOutput)(void *pOut, const void *pData, int nData),
  12226. void *pOut
  12227. );
  12228. SQLITE_API int sqlite3changeset_invert_strm(
  12229. int (*xInput)(void *pIn, void *pData, int *pnData),
  12230. void *pIn,
  12231. int (*xOutput)(void *pOut, const void *pData, int nData),
  12232. void *pOut
  12233. );
  12234. SQLITE_API int sqlite3changeset_start_strm(
  12235. sqlite3_changeset_iter **pp,
  12236. int (*xInput)(void *pIn, void *pData, int *pnData),
  12237. void *pIn
  12238. );
  12239. SQLITE_API int sqlite3changeset_start_v2_strm(
  12240. sqlite3_changeset_iter **pp,
  12241. int (*xInput)(void *pIn, void *pData, int *pnData),
  12242. void *pIn,
  12243. int flags
  12244. );
  12245. SQLITE_API int sqlite3session_changeset_strm(
  12246. sqlite3_session *pSession,
  12247. int (*xOutput)(void *pOut, const void *pData, int nData),
  12248. void *pOut
  12249. );
  12250. SQLITE_API int sqlite3session_patchset_strm(
  12251. sqlite3_session *pSession,
  12252. int (*xOutput)(void *pOut, const void *pData, int nData),
  12253. void *pOut
  12254. );
  12255. SQLITE_API int sqlite3changegroup_add_strm(sqlite3_changegroup*,
  12256. int (*xInput)(void *pIn, void *pData, int *pnData),
  12257. void *pIn
  12258. );
  12259. SQLITE_API int sqlite3changegroup_output_strm(sqlite3_changegroup*,
  12260. int (*xOutput)(void *pOut, const void *pData, int nData),
  12261. void *pOut
  12262. );
  12263. SQLITE_API int sqlite3rebaser_rebase_strm(
  12264. sqlite3_rebaser *pRebaser,
  12265. int (*xInput)(void *pIn, void *pData, int *pnData),
  12266. void *pIn,
  12267. int (*xOutput)(void *pOut, const void *pData, int nData),
  12268. void *pOut
  12269. );
  12270. /*
  12271. ** CAPI3REF: Configure global parameters
  12272. **
  12273. ** The sqlite3session_config() interface is used to make global configuration
  12274. ** changes to the sessions module in order to tune it to the specific needs
  12275. ** of the application.
  12276. **
  12277. ** The sqlite3session_config() interface is not threadsafe. If it is invoked
  12278. ** while any other thread is inside any other sessions method then the
  12279. ** results are undefined. Furthermore, if it is invoked after any sessions
  12280. ** related objects have been created, the results are also undefined.
  12281. **
  12282. ** The first argument to the sqlite3session_config() function must be one
  12283. ** of the SQLITE_SESSION_CONFIG_XXX constants defined below. The
  12284. ** interpretation of the (void*) value passed as the second parameter and
  12285. ** the effect of calling this function depends on the value of the first
  12286. ** parameter.
  12287. **
  12288. ** <dl>
  12289. ** <dt>SQLITE_SESSION_CONFIG_STRMSIZE<dd>
  12290. ** By default, the sessions module streaming interfaces attempt to input
  12291. ** and output data in approximately 1 KiB chunks. This operand may be used
  12292. ** to set and query the value of this configuration setting. The pointer
  12293. ** passed as the second argument must point to a value of type (int).
  12294. ** If this value is greater than 0, it is used as the new streaming data
  12295. ** chunk size for both input and output. Before returning, the (int) value
  12296. ** pointed to by pArg is set to the final value of the streaming interface
  12297. ** chunk size.
  12298. ** </dl>
  12299. **
  12300. ** This function returns SQLITE_OK if successful, or an SQLite error code
  12301. ** otherwise.
  12302. */
  12303. SQLITE_API int sqlite3session_config(int op, void *pArg);
  12304. /*
  12305. ** CAPI3REF: Values for sqlite3session_config().
  12306. */
  12307. #define SQLITE_SESSION_CONFIG_STRMSIZE 1
  12308. /*
  12309. ** Make sure we can call this stuff from C++.
  12310. */
  12311. #if 0
  12312. }
  12313. #endif
  12314. #endif /* !defined(__SQLITESESSION_H_) && defined(SQLITE_ENABLE_SESSION) */
  12315. /******** End of sqlite3session.h *********/
  12316. /******** Begin file fts5.h *********/
  12317. /*
  12318. ** 2014 May 31
  12319. **
  12320. ** The author disclaims copyright to this source code. In place of
  12321. ** a legal notice, here is a blessing:
  12322. **
  12323. ** May you do good and not evil.
  12324. ** May you find forgiveness for yourself and forgive others.
  12325. ** May you share freely, never taking more than you give.
  12326. **
  12327. ******************************************************************************
  12328. **
  12329. ** Interfaces to extend FTS5. Using the interfaces defined in this file,
  12330. ** FTS5 may be extended with:
  12331. **
  12332. ** * custom tokenizers, and
  12333. ** * custom auxiliary functions.
  12334. */
  12335. #ifndef _FTS5_H
  12336. #define _FTS5_H
  12337. #if 0
  12338. extern "C" {
  12339. #endif
  12340. /*************************************************************************
  12341. ** CUSTOM AUXILIARY FUNCTIONS
  12342. **
  12343. ** Virtual table implementations may overload SQL functions by implementing
  12344. ** the sqlite3_module.xFindFunction() method.
  12345. */
  12346. typedef struct Fts5ExtensionApi Fts5ExtensionApi;
  12347. typedef struct Fts5Context Fts5Context;
  12348. typedef struct Fts5PhraseIter Fts5PhraseIter;
  12349. typedef void (*fts5_extension_function)(
  12350. const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
  12351. Fts5Context *pFts, /* First arg to pass to pApi functions */
  12352. sqlite3_context *pCtx, /* Context for returning result/error */
  12353. int nVal, /* Number of values in apVal[] array */
  12354. sqlite3_value **apVal /* Array of trailing arguments */
  12355. );
  12356. struct Fts5PhraseIter {
  12357. const unsigned char *a;
  12358. const unsigned char *b;
  12359. };
  12360. /*
  12361. ** EXTENSION API FUNCTIONS
  12362. **
  12363. ** xUserData(pFts):
  12364. ** Return a copy of the context pointer the extension function was
  12365. ** registered with.
  12366. **
  12367. ** xColumnTotalSize(pFts, iCol, pnToken):
  12368. ** If parameter iCol is less than zero, set output variable *pnToken
  12369. ** to the total number of tokens in the FTS5 table. Or, if iCol is
  12370. ** non-negative but less than the number of columns in the table, return
  12371. ** the total number of tokens in column iCol, considering all rows in
  12372. ** the FTS5 table.
  12373. **
  12374. ** If parameter iCol is greater than or equal to the number of columns
  12375. ** in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
  12376. ** an OOM condition or IO error), an appropriate SQLite error code is
  12377. ** returned.
  12378. **
  12379. ** xColumnCount(pFts):
  12380. ** Return the number of columns in the table.
  12381. **
  12382. ** xColumnSize(pFts, iCol, pnToken):
  12383. ** If parameter iCol is less than zero, set output variable *pnToken
  12384. ** to the total number of tokens in the current row. Or, if iCol is
  12385. ** non-negative but less than the number of columns in the table, set
  12386. ** *pnToken to the number of tokens in column iCol of the current row.
  12387. **
  12388. ** If parameter iCol is greater than or equal to the number of columns
  12389. ** in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
  12390. ** an OOM condition or IO error), an appropriate SQLite error code is
  12391. ** returned.
  12392. **
  12393. ** This function may be quite inefficient if used with an FTS5 table
  12394. ** created with the "columnsize=0" option.
  12395. **
  12396. ** xColumnText:
  12397. ** This function attempts to retrieve the text of column iCol of the
  12398. ** current document. If successful, (*pz) is set to point to a buffer
  12399. ** containing the text in utf-8 encoding, (*pn) is set to the size in bytes
  12400. ** (not characters) of the buffer and SQLITE_OK is returned. Otherwise,
  12401. ** if an error occurs, an SQLite error code is returned and the final values
  12402. ** of (*pz) and (*pn) are undefined.
  12403. **
  12404. ** xPhraseCount:
  12405. ** Returns the number of phrases in the current query expression.
  12406. **
  12407. ** xPhraseSize:
  12408. ** Returns the number of tokens in phrase iPhrase of the query. Phrases
  12409. ** are numbered starting from zero.
  12410. **
  12411. ** xInstCount:
  12412. ** Set *pnInst to the total number of occurrences of all phrases within
  12413. ** the query within the current row. Return SQLITE_OK if successful, or
  12414. ** an error code (i.e. SQLITE_NOMEM) if an error occurs.
  12415. **
  12416. ** This API can be quite slow if used with an FTS5 table created with the
  12417. ** "detail=none" or "detail=column" option. If the FTS5 table is created
  12418. ** with either "detail=none" or "detail=column" and "content=" option
  12419. ** (i.e. if it is a contentless table), then this API always returns 0.
  12420. **
  12421. ** xInst:
  12422. ** Query for the details of phrase match iIdx within the current row.
  12423. ** Phrase matches are numbered starting from zero, so the iIdx argument
  12424. ** should be greater than or equal to zero and smaller than the value
  12425. ** output by xInstCount().
  12426. **
  12427. ** Usually, output parameter *piPhrase is set to the phrase number, *piCol
  12428. ** to the column in which it occurs and *piOff the token offset of the
  12429. ** first token of the phrase. Returns SQLITE_OK if successful, or an error
  12430. ** code (i.e. SQLITE_NOMEM) if an error occurs.
  12431. **
  12432. ** This API can be quite slow if used with an FTS5 table created with the
  12433. ** "detail=none" or "detail=column" option.
  12434. **
  12435. ** xRowid:
  12436. ** Returns the rowid of the current row.
  12437. **
  12438. ** xTokenize:
  12439. ** Tokenize text using the tokenizer belonging to the FTS5 table.
  12440. **
  12441. ** xQueryPhrase(pFts5, iPhrase, pUserData, xCallback):
  12442. ** This API function is used to query the FTS table for phrase iPhrase
  12443. ** of the current query. Specifically, a query equivalent to:
  12444. **
  12445. ** ... FROM ftstable WHERE ftstable MATCH $p ORDER BY rowid
  12446. **
  12447. ** with $p set to a phrase equivalent to the phrase iPhrase of the
  12448. ** current query is executed. Any column filter that applies to
  12449. ** phrase iPhrase of the current query is included in $p. For each
  12450. ** row visited, the callback function passed as the fourth argument
  12451. ** is invoked. The context and API objects passed to the callback
  12452. ** function may be used to access the properties of each matched row.
  12453. ** Invoking Api.xUserData() returns a copy of the pointer passed as
  12454. ** the third argument to pUserData.
  12455. **
  12456. ** If the callback function returns any value other than SQLITE_OK, the
  12457. ** query is abandoned and the xQueryPhrase function returns immediately.
  12458. ** If the returned value is SQLITE_DONE, xQueryPhrase returns SQLITE_OK.
  12459. ** Otherwise, the error code is propagated upwards.
  12460. **
  12461. ** If the query runs to completion without incident, SQLITE_OK is returned.
  12462. ** Or, if some error occurs before the query completes or is aborted by
  12463. ** the callback, an SQLite error code is returned.
  12464. **
  12465. **
  12466. ** xSetAuxdata(pFts5, pAux, xDelete)
  12467. **
  12468. ** Save the pointer passed as the second argument as the extension function's
  12469. ** "auxiliary data". The pointer may then be retrieved by the current or any
  12470. ** future invocation of the same fts5 extension function made as part of
  12471. ** the same MATCH query using the xGetAuxdata() API.
  12472. **
  12473. ** Each extension function is allocated a single auxiliary data slot for
  12474. ** each FTS query (MATCH expression). If the extension function is invoked
  12475. ** more than once for a single FTS query, then all invocations share a
  12476. ** single auxiliary data context.
  12477. **
  12478. ** If there is already an auxiliary data pointer when this function is
  12479. ** invoked, then it is replaced by the new pointer. If an xDelete callback
  12480. ** was specified along with the original pointer, it is invoked at this
  12481. ** point.
  12482. **
  12483. ** The xDelete callback, if one is specified, is also invoked on the
  12484. ** auxiliary data pointer after the FTS5 query has finished.
  12485. **
  12486. ** If an error (e.g. an OOM condition) occurs within this function,
  12487. ** the auxiliary data is set to NULL and an error code returned. If the
  12488. ** xDelete parameter was not NULL, it is invoked on the auxiliary data
  12489. ** pointer before returning.
  12490. **
  12491. **
  12492. ** xGetAuxdata(pFts5, bClear)
  12493. **
  12494. ** Returns the current auxiliary data pointer for the fts5 extension
  12495. ** function. See the xSetAuxdata() method for details.
  12496. **
  12497. ** If the bClear argument is non-zero, then the auxiliary data is cleared
  12498. ** (set to NULL) before this function returns. In this case the xDelete,
  12499. ** if any, is not invoked.
  12500. **
  12501. **
  12502. ** xRowCount(pFts5, pnRow)
  12503. **
  12504. ** This function is used to retrieve the total number of rows in the table.
  12505. ** In other words, the same value that would be returned by:
  12506. **
  12507. ** SELECT count(*) FROM ftstable;
  12508. **
  12509. ** xPhraseFirst()
  12510. ** This function is used, along with type Fts5PhraseIter and the xPhraseNext
  12511. ** method, to iterate through all instances of a single query phrase within
  12512. ** the current row. This is the same information as is accessible via the
  12513. ** xInstCount/xInst APIs. While the xInstCount/xInst APIs are more convenient
  12514. ** to use, this API may be faster under some circumstances. To iterate
  12515. ** through instances of phrase iPhrase, use the following code:
  12516. **
  12517. ** Fts5PhraseIter iter;
  12518. ** int iCol, iOff;
  12519. ** for(pApi->xPhraseFirst(pFts, iPhrase, &iter, &iCol, &iOff);
  12520. ** iCol>=0;
  12521. ** pApi->xPhraseNext(pFts, &iter, &iCol, &iOff)
  12522. ** ){
  12523. ** // An instance of phrase iPhrase at offset iOff of column iCol
  12524. ** }
  12525. **
  12526. ** The Fts5PhraseIter structure is defined above. Applications should not
  12527. ** modify this structure directly - it should only be used as shown above
  12528. ** with the xPhraseFirst() and xPhraseNext() API methods (and by
  12529. ** xPhraseFirstColumn() and xPhraseNextColumn() as illustrated below).
  12530. **
  12531. ** This API can be quite slow if used with an FTS5 table created with the
  12532. ** "detail=none" or "detail=column" option. If the FTS5 table is created
  12533. ** with either "detail=none" or "detail=column" and "content=" option
  12534. ** (i.e. if it is a contentless table), then this API always iterates
  12535. ** through an empty set (all calls to xPhraseFirst() set iCol to -1).
  12536. **
  12537. ** xPhraseNext()
  12538. ** See xPhraseFirst above.
  12539. **
  12540. ** xPhraseFirstColumn()
  12541. ** This function and xPhraseNextColumn() are similar to the xPhraseFirst()
  12542. ** and xPhraseNext() APIs described above. The difference is that instead
  12543. ** of iterating through all instances of a phrase in the current row, these
  12544. ** APIs are used to iterate through the set of columns in the current row
  12545. ** that contain one or more instances of a specified phrase. For example:
  12546. **
  12547. ** Fts5PhraseIter iter;
  12548. ** int iCol;
  12549. ** for(pApi->xPhraseFirstColumn(pFts, iPhrase, &iter, &iCol);
  12550. ** iCol>=0;
  12551. ** pApi->xPhraseNextColumn(pFts, &iter, &iCol)
  12552. ** ){
  12553. ** // Column iCol contains at least one instance of phrase iPhrase
  12554. ** }
  12555. **
  12556. ** This API can be quite slow if used with an FTS5 table created with the
  12557. ** "detail=none" option. If the FTS5 table is created with either
  12558. ** "detail=none" "content=" option (i.e. if it is a contentless table),
  12559. ** then this API always iterates through an empty set (all calls to
  12560. ** xPhraseFirstColumn() set iCol to -1).
  12561. **
  12562. ** The information accessed using this API and its companion
  12563. ** xPhraseFirstColumn() may also be obtained using xPhraseFirst/xPhraseNext
  12564. ** (or xInst/xInstCount). The chief advantage of this API is that it is
  12565. ** significantly more efficient than those alternatives when used with
  12566. ** "detail=column" tables.
  12567. **
  12568. ** xPhraseNextColumn()
  12569. ** See xPhraseFirstColumn above.
  12570. */
  12571. struct Fts5ExtensionApi {
  12572. int iVersion; /* Currently always set to 3 */
  12573. void *(*xUserData)(Fts5Context*);
  12574. int (*xColumnCount)(Fts5Context*);
  12575. int (*xRowCount)(Fts5Context*, sqlite3_int64 *pnRow);
  12576. int (*xColumnTotalSize)(Fts5Context*, int iCol, sqlite3_int64 *pnToken);
  12577. int (*xTokenize)(Fts5Context*,
  12578. const char *pText, int nText, /* Text to tokenize */
  12579. void *pCtx, /* Context passed to xToken() */
  12580. int (*xToken)(void*, int, const char*, int, int, int) /* Callback */
  12581. );
  12582. int (*xPhraseCount)(Fts5Context*);
  12583. int (*xPhraseSize)(Fts5Context*, int iPhrase);
  12584. int (*xInstCount)(Fts5Context*, int *pnInst);
  12585. int (*xInst)(Fts5Context*, int iIdx, int *piPhrase, int *piCol, int *piOff);
  12586. sqlite3_int64 (*xRowid)(Fts5Context*);
  12587. int (*xColumnText)(Fts5Context*, int iCol, const char **pz, int *pn);
  12588. int (*xColumnSize)(Fts5Context*, int iCol, int *pnToken);
  12589. int (*xQueryPhrase)(Fts5Context*, int iPhrase, void *pUserData,
  12590. int(*)(const Fts5ExtensionApi*,Fts5Context*,void*)
  12591. );
  12592. int (*xSetAuxdata)(Fts5Context*, void *pAux, void(*xDelete)(void*));
  12593. void *(*xGetAuxdata)(Fts5Context*, int bClear);
  12594. int (*xPhraseFirst)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*, int*);
  12595. void (*xPhraseNext)(Fts5Context*, Fts5PhraseIter*, int *piCol, int *piOff);
  12596. int (*xPhraseFirstColumn)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*);
  12597. void (*xPhraseNextColumn)(Fts5Context*, Fts5PhraseIter*, int *piCol);
  12598. };
  12599. /*
  12600. ** CUSTOM AUXILIARY FUNCTIONS
  12601. *************************************************************************/
  12602. /*************************************************************************
  12603. ** CUSTOM TOKENIZERS
  12604. **
  12605. ** Applications may also register custom tokenizer types. A tokenizer
  12606. ** is registered by providing fts5 with a populated instance of the
  12607. ** following structure. All structure methods must be defined, setting
  12608. ** any member of the fts5_tokenizer struct to NULL leads to undefined
  12609. ** behaviour. The structure methods are expected to function as follows:
  12610. **
  12611. ** xCreate:
  12612. ** This function is used to allocate and initialize a tokenizer instance.
  12613. ** A tokenizer instance is required to actually tokenize text.
  12614. **
  12615. ** The first argument passed to this function is a copy of the (void*)
  12616. ** pointer provided by the application when the fts5_tokenizer object
  12617. ** was registered with FTS5 (the third argument to xCreateTokenizer()).
  12618. ** The second and third arguments are an array of nul-terminated strings
  12619. ** containing the tokenizer arguments, if any, specified following the
  12620. ** tokenizer name as part of the CREATE VIRTUAL TABLE statement used
  12621. ** to create the FTS5 table.
  12622. **
  12623. ** The final argument is an output variable. If successful, (*ppOut)
  12624. ** should be set to point to the new tokenizer handle and SQLITE_OK
  12625. ** returned. If an error occurs, some value other than SQLITE_OK should
  12626. ** be returned. In this case, fts5 assumes that the final value of *ppOut
  12627. ** is undefined.
  12628. **
  12629. ** xDelete:
  12630. ** This function is invoked to delete a tokenizer handle previously
  12631. ** allocated using xCreate(). Fts5 guarantees that this function will
  12632. ** be invoked exactly once for each successful call to xCreate().
  12633. **
  12634. ** xTokenize:
  12635. ** This function is expected to tokenize the nText byte string indicated
  12636. ** by argument pText. pText may or may not be nul-terminated. The first
  12637. ** argument passed to this function is a pointer to an Fts5Tokenizer object
  12638. ** returned by an earlier call to xCreate().
  12639. **
  12640. ** The second argument indicates the reason that FTS5 is requesting
  12641. ** tokenization of the supplied text. This is always one of the following
  12642. ** four values:
  12643. **
  12644. ** <ul><li> <b>FTS5_TOKENIZE_DOCUMENT</b> - A document is being inserted into
  12645. ** or removed from the FTS table. The tokenizer is being invoked to
  12646. ** determine the set of tokens to add to (or delete from) the
  12647. ** FTS index.
  12648. **
  12649. ** <li> <b>FTS5_TOKENIZE_QUERY</b> - A MATCH query is being executed
  12650. ** against the FTS index. The tokenizer is being called to tokenize
  12651. ** a bareword or quoted string specified as part of the query.
  12652. **
  12653. ** <li> <b>(FTS5_TOKENIZE_QUERY | FTS5_TOKENIZE_PREFIX)</b> - Same as
  12654. ** FTS5_TOKENIZE_QUERY, except that the bareword or quoted string is
  12655. ** followed by a "*" character, indicating that the last token
  12656. ** returned by the tokenizer will be treated as a token prefix.
  12657. **
  12658. ** <li> <b>FTS5_TOKENIZE_AUX</b> - The tokenizer is being invoked to
  12659. ** satisfy an fts5_api.xTokenize() request made by an auxiliary
  12660. ** function. Or an fts5_api.xColumnSize() request made by the same
  12661. ** on a columnsize=0 database.
  12662. ** </ul>
  12663. **
  12664. ** For each token in the input string, the supplied callback xToken() must
  12665. ** be invoked. The first argument to it should be a copy of the pointer
  12666. ** passed as the second argument to xTokenize(). The third and fourth
  12667. ** arguments are a pointer to a buffer containing the token text, and the
  12668. ** size of the token in bytes. The 4th and 5th arguments are the byte offsets
  12669. ** of the first byte of and first byte immediately following the text from
  12670. ** which the token is derived within the input.
  12671. **
  12672. ** The second argument passed to the xToken() callback ("tflags") should
  12673. ** normally be set to 0. The exception is if the tokenizer supports
  12674. ** synonyms. In this case see the discussion below for details.
  12675. **
  12676. ** FTS5 assumes the xToken() callback is invoked for each token in the
  12677. ** order that they occur within the input text.
  12678. **
  12679. ** If an xToken() callback returns any value other than SQLITE_OK, then
  12680. ** the tokenization should be abandoned and the xTokenize() method should
  12681. ** immediately return a copy of the xToken() return value. Or, if the
  12682. ** input buffer is exhausted, xTokenize() should return SQLITE_OK. Finally,
  12683. ** if an error occurs with the xTokenize() implementation itself, it
  12684. ** may abandon the tokenization and return any error code other than
  12685. ** SQLITE_OK or SQLITE_DONE.
  12686. **
  12687. ** SYNONYM SUPPORT
  12688. **
  12689. ** Custom tokenizers may also support synonyms. Consider a case in which a
  12690. ** user wishes to query for a phrase such as "first place". Using the
  12691. ** built-in tokenizers, the FTS5 query 'first + place' will match instances
  12692. ** of "first place" within the document set, but not alternative forms
  12693. ** such as "1st place". In some applications, it would be better to match
  12694. ** all instances of "first place" or "1st place" regardless of which form
  12695. ** the user specified in the MATCH query text.
  12696. **
  12697. ** There are several ways to approach this in FTS5:
  12698. **
  12699. ** <ol><li> By mapping all synonyms to a single token. In this case, using
  12700. ** the above example, this means that the tokenizer returns the
  12701. ** same token for inputs "first" and "1st". Say that token is in
  12702. ** fact "first", so that when the user inserts the document "I won
  12703. ** 1st place" entries are added to the index for tokens "i", "won",
  12704. ** "first" and "place". If the user then queries for '1st + place',
  12705. ** the tokenizer substitutes "first" for "1st" and the query works
  12706. ** as expected.
  12707. **
  12708. ** <li> By querying the index for all synonyms of each query term
  12709. ** separately. In this case, when tokenizing query text, the
  12710. ** tokenizer may provide multiple synonyms for a single term
  12711. ** within the document. FTS5 then queries the index for each
  12712. ** synonym individually. For example, faced with the query:
  12713. **
  12714. ** <codeblock>
  12715. ** ... MATCH 'first place'</codeblock>
  12716. **
  12717. ** the tokenizer offers both "1st" and "first" as synonyms for the
  12718. ** first token in the MATCH query and FTS5 effectively runs a query
  12719. ** similar to:
  12720. **
  12721. ** <codeblock>
  12722. ** ... MATCH '(first OR 1st) place'</codeblock>
  12723. **
  12724. ** except that, for the purposes of auxiliary functions, the query
  12725. ** still appears to contain just two phrases - "(first OR 1st)"
  12726. ** being treated as a single phrase.
  12727. **
  12728. ** <li> By adding multiple synonyms for a single term to the FTS index.
  12729. ** Using this method, when tokenizing document text, the tokenizer
  12730. ** provides multiple synonyms for each token. So that when a
  12731. ** document such as "I won first place" is tokenized, entries are
  12732. ** added to the FTS index for "i", "won", "first", "1st" and
  12733. ** "place".
  12734. **
  12735. ** This way, even if the tokenizer does not provide synonyms
  12736. ** when tokenizing query text (it should not - to do so would be
  12737. ** inefficient), it doesn't matter if the user queries for
  12738. ** 'first + place' or '1st + place', as there are entries in the
  12739. ** FTS index corresponding to both forms of the first token.
  12740. ** </ol>
  12741. **
  12742. ** Whether it is parsing document or query text, any call to xToken that
  12743. ** specifies a <i>tflags</i> argument with the FTS5_TOKEN_COLOCATED bit
  12744. ** is considered to supply a synonym for the previous token. For example,
  12745. ** when parsing the document "I won first place", a tokenizer that supports
  12746. ** synonyms would call xToken() 5 times, as follows:
  12747. **
  12748. ** <codeblock>
  12749. ** xToken(pCtx, 0, "i", 1, 0, 1);
  12750. ** xToken(pCtx, 0, "won", 3, 2, 5);
  12751. ** xToken(pCtx, 0, "first", 5, 6, 11);
  12752. ** xToken(pCtx, FTS5_TOKEN_COLOCATED, "1st", 3, 6, 11);
  12753. ** xToken(pCtx, 0, "place", 5, 12, 17);
  12754. **</codeblock>
  12755. **
  12756. ** It is an error to specify the FTS5_TOKEN_COLOCATED flag the first time
  12757. ** xToken() is called. Multiple synonyms may be specified for a single token
  12758. ** by making multiple calls to xToken(FTS5_TOKEN_COLOCATED) in sequence.
  12759. ** There is no limit to the number of synonyms that may be provided for a
  12760. ** single token.
  12761. **
  12762. ** In many cases, method (1) above is the best approach. It does not add
  12763. ** extra data to the FTS index or require FTS5 to query for multiple terms,
  12764. ** so it is efficient in terms of disk space and query speed. However, it
  12765. ** does not support prefix queries very well. If, as suggested above, the
  12766. ** token "first" is substituted for "1st" by the tokenizer, then the query:
  12767. **
  12768. ** <codeblock>
  12769. ** ... MATCH '1s*'</codeblock>
  12770. **
  12771. ** will not match documents that contain the token "1st" (as the tokenizer
  12772. ** will probably not map "1s" to any prefix of "first").
  12773. **
  12774. ** For full prefix support, method (3) may be preferred. In this case,
  12775. ** because the index contains entries for both "first" and "1st", prefix
  12776. ** queries such as 'fi*' or '1s*' will match correctly. However, because
  12777. ** extra entries are added to the FTS index, this method uses more space
  12778. ** within the database.
  12779. **
  12780. ** Method (2) offers a midpoint between (1) and (3). Using this method,
  12781. ** a query such as '1s*' will match documents that contain the literal
  12782. ** token "1st", but not "first" (assuming the tokenizer is not able to
  12783. ** provide synonyms for prefixes). However, a non-prefix query like '1st'
  12784. ** will match against "1st" and "first". This method does not require
  12785. ** extra disk space, as no extra entries are added to the FTS index.
  12786. ** On the other hand, it may require more CPU cycles to run MATCH queries,
  12787. ** as separate queries of the FTS index are required for each synonym.
  12788. **
  12789. ** When using methods (2) or (3), it is important that the tokenizer only
  12790. ** provide synonyms when tokenizing document text (method (2)) or query
  12791. ** text (method (3)), not both. Doing so will not cause any errors, but is
  12792. ** inefficient.
  12793. */
  12794. typedef struct Fts5Tokenizer Fts5Tokenizer;
  12795. typedef struct fts5_tokenizer fts5_tokenizer;
  12796. struct fts5_tokenizer {
  12797. int (*xCreate)(void*, const char **azArg, int nArg, Fts5Tokenizer **ppOut);
  12798. void (*xDelete)(Fts5Tokenizer*);
  12799. int (*xTokenize)(Fts5Tokenizer*,
  12800. void *pCtx,
  12801. int flags, /* Mask of FTS5_TOKENIZE_* flags */
  12802. const char *pText, int nText,
  12803. int (*xToken)(
  12804. void *pCtx, /* Copy of 2nd argument to xTokenize() */
  12805. int tflags, /* Mask of FTS5_TOKEN_* flags */
  12806. const char *pToken, /* Pointer to buffer containing token */
  12807. int nToken, /* Size of token in bytes */
  12808. int iStart, /* Byte offset of token within input text */
  12809. int iEnd /* Byte offset of end of token within input text */
  12810. )
  12811. );
  12812. };
  12813. /* Flags that may be passed as the third argument to xTokenize() */
  12814. #define FTS5_TOKENIZE_QUERY 0x0001
  12815. #define FTS5_TOKENIZE_PREFIX 0x0002
  12816. #define FTS5_TOKENIZE_DOCUMENT 0x0004
  12817. #define FTS5_TOKENIZE_AUX 0x0008
  12818. /* Flags that may be passed by the tokenizer implementation back to FTS5
  12819. ** as the third argument to the supplied xToken callback. */
  12820. #define FTS5_TOKEN_COLOCATED 0x0001 /* Same position as prev. token */
  12821. /*
  12822. ** END OF CUSTOM TOKENIZERS
  12823. *************************************************************************/
  12824. /*************************************************************************
  12825. ** FTS5 EXTENSION REGISTRATION API
  12826. */
  12827. typedef struct fts5_api fts5_api;
  12828. struct fts5_api {
  12829. int iVersion; /* Currently always set to 2 */
  12830. /* Create a new tokenizer */
  12831. int (*xCreateTokenizer)(
  12832. fts5_api *pApi,
  12833. const char *zName,
  12834. void *pContext,
  12835. fts5_tokenizer *pTokenizer,
  12836. void (*xDestroy)(void*)
  12837. );
  12838. /* Find an existing tokenizer */
  12839. int (*xFindTokenizer)(
  12840. fts5_api *pApi,
  12841. const char *zName,
  12842. void **ppContext,
  12843. fts5_tokenizer *pTokenizer
  12844. );
  12845. /* Create a new auxiliary function */
  12846. int (*xCreateFunction)(
  12847. fts5_api *pApi,
  12848. const char *zName,
  12849. void *pContext,
  12850. fts5_extension_function xFunction,
  12851. void (*xDestroy)(void*)
  12852. );
  12853. };
  12854. /*
  12855. ** END OF REGISTRATION API
  12856. *************************************************************************/
  12857. #if 0
  12858. } /* end of the 'extern "C"' block */
  12859. #endif
  12860. #endif /* _FTS5_H */
  12861. /******** End of fts5.h *********/
  12862. /************** End of sqlite3.h *********************************************/
  12863. /************** Continuing where we left off in sqliteInt.h ******************/
  12864. /*
  12865. ** Include the configuration header output by 'configure' if we're using the
  12866. ** autoconf-based build
  12867. */
  12868. #if defined(_HAVE_SQLITE_CONFIG_H) && !defined(SQLITECONFIG_H)
  12869. /* #include "config.h" */
  12870. #define SQLITECONFIG_H 1
  12871. #endif
  12872. /************** Include sqliteLimit.h in the middle of sqliteInt.h ***********/
  12873. /************** Begin file sqliteLimit.h *************************************/
  12874. /*
  12875. ** 2007 May 7
  12876. **
  12877. ** The author disclaims copyright to this source code. In place of
  12878. ** a legal notice, here is a blessing:
  12879. **
  12880. ** May you do good and not evil.
  12881. ** May you find forgiveness for yourself and forgive others.
  12882. ** May you share freely, never taking more than you give.
  12883. **
  12884. *************************************************************************
  12885. **
  12886. ** This file defines various limits of what SQLite can process.
  12887. */
  12888. /*
  12889. ** The maximum length of a TEXT or BLOB in bytes. This also
  12890. ** limits the size of a row in a table or index.
  12891. **
  12892. ** The hard limit is the ability of a 32-bit signed integer
  12893. ** to count the size: 2^31-1 or 2147483647.
  12894. */
  12895. #ifndef SQLITE_MAX_LENGTH
  12896. # define SQLITE_MAX_LENGTH 1000000000
  12897. #endif
  12898. /*
  12899. ** This is the maximum number of
  12900. **
  12901. ** * Columns in a table
  12902. ** * Columns in an index
  12903. ** * Columns in a view
  12904. ** * Terms in the SET clause of an UPDATE statement
  12905. ** * Terms in the result set of a SELECT statement
  12906. ** * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement.
  12907. ** * Terms in the VALUES clause of an INSERT statement
  12908. **
  12909. ** The hard upper limit here is 32676. Most database people will
  12910. ** tell you that in a well-normalized database, you usually should
  12911. ** not have more than a dozen or so columns in any table. And if
  12912. ** that is the case, there is no point in having more than a few
  12913. ** dozen values in any of the other situations described above.
  12914. */
  12915. #ifndef SQLITE_MAX_COLUMN
  12916. # define SQLITE_MAX_COLUMN 2000
  12917. #endif
  12918. /*
  12919. ** The maximum length of a single SQL statement in bytes.
  12920. **
  12921. ** It used to be the case that setting this value to zero would
  12922. ** turn the limit off. That is no longer true. It is not possible
  12923. ** to turn this limit off.
  12924. */
  12925. #ifndef SQLITE_MAX_SQL_LENGTH
  12926. # define SQLITE_MAX_SQL_LENGTH 1000000000
  12927. #endif
  12928. /*
  12929. ** The maximum depth of an expression tree. This is limited to
  12930. ** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might
  12931. ** want to place more severe limits on the complexity of an
  12932. ** expression.
  12933. **
  12934. ** A value of 0 used to mean that the limit was not enforced.
  12935. ** But that is no longer true. The limit is now strictly enforced
  12936. ** at all times.
  12937. */
  12938. #ifndef SQLITE_MAX_EXPR_DEPTH
  12939. # define SQLITE_MAX_EXPR_DEPTH 1000
  12940. #endif
  12941. /*
  12942. ** The maximum number of terms in a compound SELECT statement.
  12943. ** The code generator for compound SELECT statements does one
  12944. ** level of recursion for each term. A stack overflow can result
  12945. ** if the number of terms is too large. In practice, most SQL
  12946. ** never has more than 3 or 4 terms. Use a value of 0 to disable
  12947. ** any limit on the number of terms in a compount SELECT.
  12948. */
  12949. #ifndef SQLITE_MAX_COMPOUND_SELECT
  12950. # define SQLITE_MAX_COMPOUND_SELECT 500
  12951. #endif
  12952. /*
  12953. ** The maximum number of opcodes in a VDBE program.
  12954. ** Not currently enforced.
  12955. */
  12956. #ifndef SQLITE_MAX_VDBE_OP
  12957. # define SQLITE_MAX_VDBE_OP 250000000
  12958. #endif
  12959. /*
  12960. ** The maximum number of arguments to an SQL function.
  12961. */
  12962. #ifndef SQLITE_MAX_FUNCTION_ARG
  12963. # define SQLITE_MAX_FUNCTION_ARG 127
  12964. #endif
  12965. /*
  12966. ** The suggested maximum number of in-memory pages to use for
  12967. ** the main database table and for temporary tables.
  12968. **
  12969. ** IMPLEMENTATION-OF: R-30185-15359 The default suggested cache size is -2000,
  12970. ** which means the cache size is limited to 2048000 bytes of memory.
  12971. ** IMPLEMENTATION-OF: R-48205-43578 The default suggested cache size can be
  12972. ** altered using the SQLITE_DEFAULT_CACHE_SIZE compile-time options.
  12973. */
  12974. #ifndef SQLITE_DEFAULT_CACHE_SIZE
  12975. # define SQLITE_DEFAULT_CACHE_SIZE -2000
  12976. #endif
  12977. /*
  12978. ** The default number of frames to accumulate in the log file before
  12979. ** checkpointing the database in WAL mode.
  12980. */
  12981. #ifndef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT
  12982. # define SQLITE_DEFAULT_WAL_AUTOCHECKPOINT 1000
  12983. #endif
  12984. /*
  12985. ** The maximum number of attached databases. This must be between 0
  12986. ** and 125. The upper bound of 125 is because the attached databases are
  12987. ** counted using a signed 8-bit integer which has a maximum value of 127
  12988. ** and we have to allow 2 extra counts for the "main" and "temp" databases.
  12989. */
  12990. #ifndef SQLITE_MAX_ATTACHED
  12991. # define SQLITE_MAX_ATTACHED 10
  12992. #endif
  12993. /*
  12994. ** The maximum value of a ?nnn wildcard that the parser will accept.
  12995. ** If the value exceeds 32767 then extra space is required for the Expr
  12996. ** structure. But otherwise, we believe that the number can be as large
  12997. ** as a signed 32-bit integer can hold.
  12998. */
  12999. #ifndef SQLITE_MAX_VARIABLE_NUMBER
  13000. # define SQLITE_MAX_VARIABLE_NUMBER 32766
  13001. #endif
  13002. /* Maximum page size. The upper bound on this value is 65536. This a limit
  13003. ** imposed by the use of 16-bit offsets within each page.
  13004. **
  13005. ** Earlier versions of SQLite allowed the user to change this value at
  13006. ** compile time. This is no longer permitted, on the grounds that it creates
  13007. ** a library that is technically incompatible with an SQLite library
  13008. ** compiled with a different limit. If a process operating on a database
  13009. ** with a page-size of 65536 bytes crashes, then an instance of SQLite
  13010. ** compiled with the default page-size limit will not be able to rollback
  13011. ** the aborted transaction. This could lead to database corruption.
  13012. */
  13013. #ifdef SQLITE_MAX_PAGE_SIZE
  13014. # undef SQLITE_MAX_PAGE_SIZE
  13015. #endif
  13016. #define SQLITE_MAX_PAGE_SIZE 65536
  13017. /*
  13018. ** The default size of a database page.
  13019. */
  13020. #ifndef SQLITE_DEFAULT_PAGE_SIZE
  13021. # define SQLITE_DEFAULT_PAGE_SIZE 4096
  13022. #endif
  13023. #if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
  13024. # undef SQLITE_DEFAULT_PAGE_SIZE
  13025. # define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
  13026. #endif
  13027. /*
  13028. ** Ordinarily, if no value is explicitly provided, SQLite creates databases
  13029. ** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain
  13030. ** device characteristics (sector-size and atomic write() support),
  13031. ** SQLite may choose a larger value. This constant is the maximum value
  13032. ** SQLite will choose on its own.
  13033. */
  13034. #ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE
  13035. # define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192
  13036. #endif
  13037. #if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
  13038. # undef SQLITE_MAX_DEFAULT_PAGE_SIZE
  13039. # define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
  13040. #endif
  13041. /*
  13042. ** Maximum number of pages in one database file.
  13043. **
  13044. ** This is really just the default value for the max_page_count pragma.
  13045. ** This value can be lowered (or raised) at run-time using that the
  13046. ** max_page_count macro.
  13047. */
  13048. #ifndef SQLITE_MAX_PAGE_COUNT
  13049. # define SQLITE_MAX_PAGE_COUNT 1073741823
  13050. #endif
  13051. /*
  13052. ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
  13053. ** operator.
  13054. */
  13055. #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
  13056. # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
  13057. #endif
  13058. /*
  13059. ** Maximum depth of recursion for triggers.
  13060. **
  13061. ** A value of 1 means that a trigger program will not be able to itself
  13062. ** fire any triggers. A value of 0 means that no trigger programs at all
  13063. ** may be executed.
  13064. */
  13065. #ifndef SQLITE_MAX_TRIGGER_DEPTH
  13066. # define SQLITE_MAX_TRIGGER_DEPTH 1000
  13067. #endif
  13068. /************** End of sqliteLimit.h *****************************************/
  13069. /************** Continuing where we left off in sqliteInt.h ******************/
  13070. /* Disable nuisance warnings on Borland compilers */
  13071. #if defined(__BORLANDC__)
  13072. #pragma warn -rch /* unreachable code */
  13073. #pragma warn -ccc /* Condition is always true or false */
  13074. #pragma warn -aus /* Assigned value is never used */
  13075. #pragma warn -csu /* Comparing signed and unsigned */
  13076. #pragma warn -spa /* Suspicious pointer arithmetic */
  13077. #endif
  13078. /*
  13079. ** WAL mode depends on atomic aligned 32-bit loads and stores in a few
  13080. ** places. The following macros try to make this explicit.
  13081. */
  13082. #ifndef __has_feature
  13083. # define __has_feature(x) 0 /* compatibility with non-clang compilers */
  13084. #endif
  13085. #if GCC_VERSION>=4007000 || __has_feature(c_atomic)
  13086. # define AtomicLoad(PTR) __atomic_load_n((PTR),__ATOMIC_RELAXED)
  13087. # define AtomicStore(PTR,VAL) __atomic_store_n((PTR),(VAL),__ATOMIC_RELAXED)
  13088. #else
  13089. # define AtomicLoad(PTR) (*(PTR))
  13090. # define AtomicStore(PTR,VAL) (*(PTR) = (VAL))
  13091. #endif
  13092. /*
  13093. ** Include standard header files as necessary
  13094. */
  13095. #ifdef HAVE_STDINT_H
  13096. #include <stdint.h>
  13097. #endif
  13098. #ifdef HAVE_INTTYPES_H
  13099. #include <inttypes.h>
  13100. #endif
  13101. /*
  13102. ** The following macros are used to cast pointers to integers and
  13103. ** integers to pointers. The way you do this varies from one compiler
  13104. ** to the next, so we have developed the following set of #if statements
  13105. ** to generate appropriate macros for a wide range of compilers.
  13106. **
  13107. ** The correct "ANSI" way to do this is to use the intptr_t type.
  13108. ** Unfortunately, that typedef is not available on all compilers, or
  13109. ** if it is available, it requires an #include of specific headers
  13110. ** that vary from one machine to the next.
  13111. **
  13112. ** Ticket #3860: The llvm-gcc-4.2 compiler from Apple chokes on
  13113. ** the ((void*)&((char*)0)[X]) construct. But MSVC chokes on ((void*)(X)).
  13114. ** So we have to define the macros in different ways depending on the
  13115. ** compiler.
  13116. */
  13117. #if defined(HAVE_STDINT_H) /* Use this case if we have ANSI headers */
  13118. # define SQLITE_INT_TO_PTR(X) ((void*)(intptr_t)(X))
  13119. # define SQLITE_PTR_TO_INT(X) ((int)(intptr_t)(X))
  13120. #elif defined(__PTRDIFF_TYPE__) /* This case should work for GCC */
  13121. # define SQLITE_INT_TO_PTR(X) ((void*)(__PTRDIFF_TYPE__)(X))
  13122. # define SQLITE_PTR_TO_INT(X) ((int)(__PTRDIFF_TYPE__)(X))
  13123. #elif !defined(__GNUC__) /* Works for compilers other than LLVM */
  13124. # define SQLITE_INT_TO_PTR(X) ((void*)&((char*)0)[X])
  13125. # define SQLITE_PTR_TO_INT(X) ((int)(((char*)X)-(char*)0))
  13126. #else /* Generates a warning - but it always works */
  13127. # define SQLITE_INT_TO_PTR(X) ((void*)(X))
  13128. # define SQLITE_PTR_TO_INT(X) ((int)(X))
  13129. #endif
  13130. /*
  13131. ** A macro to hint to the compiler that a function should not be
  13132. ** inlined.
  13133. */
  13134. #if defined(__GNUC__)
  13135. # define SQLITE_NOINLINE __attribute__((noinline))
  13136. #elif defined(_MSC_VER) && _MSC_VER>=1310
  13137. # define SQLITE_NOINLINE __declspec(noinline)
  13138. #else
  13139. # define SQLITE_NOINLINE
  13140. #endif
  13141. /*
  13142. ** Make sure that the compiler intrinsics we desire are enabled when
  13143. ** compiling with an appropriate version of MSVC unless prevented by
  13144. ** the SQLITE_DISABLE_INTRINSIC define.
  13145. */
  13146. #if !defined(SQLITE_DISABLE_INTRINSIC)
  13147. # if defined(_MSC_VER) && _MSC_VER>=1400
  13148. # if !defined(_WIN32_WCE)
  13149. # include <intrin.h>
  13150. # pragma intrinsic(_byteswap_ushort)
  13151. # pragma intrinsic(_byteswap_ulong)
  13152. # pragma intrinsic(_byteswap_uint64)
  13153. # pragma intrinsic(_ReadWriteBarrier)
  13154. # else
  13155. # include <cmnintrin.h>
  13156. # endif
  13157. # endif
  13158. #endif
  13159. /*
  13160. ** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2.
  13161. ** 0 means mutexes are permanently disable and the library is never
  13162. ** threadsafe. 1 means the library is serialized which is the highest
  13163. ** level of threadsafety. 2 means the library is multithreaded - multiple
  13164. ** threads can use SQLite as long as no two threads try to use the same
  13165. ** database connection at the same time.
  13166. **
  13167. ** Older versions of SQLite used an optional THREADSAFE macro.
  13168. ** We support that for legacy.
  13169. **
  13170. ** To ensure that the correct value of "THREADSAFE" is reported when querying
  13171. ** for compile-time options at runtime (e.g. "PRAGMA compile_options"), this
  13172. ** logic is partially replicated in ctime.c. If it is updated here, it should
  13173. ** also be updated there.
  13174. */
  13175. #if !defined(SQLITE_THREADSAFE)
  13176. # if defined(THREADSAFE)
  13177. # define SQLITE_THREADSAFE THREADSAFE
  13178. # else
  13179. # define SQLITE_THREADSAFE 1 /* IMP: R-07272-22309 */
  13180. # endif
  13181. #endif
  13182. /*
  13183. ** Powersafe overwrite is on by default. But can be turned off using
  13184. ** the -DSQLITE_POWERSAFE_OVERWRITE=0 command-line option.
  13185. */
  13186. #ifndef SQLITE_POWERSAFE_OVERWRITE
  13187. # define SQLITE_POWERSAFE_OVERWRITE 1
  13188. #endif
  13189. /*
  13190. ** EVIDENCE-OF: R-25715-37072 Memory allocation statistics are enabled by
  13191. ** default unless SQLite is compiled with SQLITE_DEFAULT_MEMSTATUS=0 in
  13192. ** which case memory allocation statistics are disabled by default.
  13193. */
  13194. #if !defined(SQLITE_DEFAULT_MEMSTATUS)
  13195. # define SQLITE_DEFAULT_MEMSTATUS 1
  13196. #endif
  13197. /*
  13198. ** Exactly one of the following macros must be defined in order to
  13199. ** specify which memory allocation subsystem to use.
  13200. **
  13201. ** SQLITE_SYSTEM_MALLOC // Use normal system malloc()
  13202. ** SQLITE_WIN32_MALLOC // Use Win32 native heap API
  13203. ** SQLITE_ZERO_MALLOC // Use a stub allocator that always fails
  13204. ** SQLITE_MEMDEBUG // Debugging version of system malloc()
  13205. **
  13206. ** On Windows, if the SQLITE_WIN32_MALLOC_VALIDATE macro is defined and the
  13207. ** assert() macro is enabled, each call into the Win32 native heap subsystem
  13208. ** will cause HeapValidate to be called. If heap validation should fail, an
  13209. ** assertion will be triggered.
  13210. **
  13211. ** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
  13212. ** the default.
  13213. */
  13214. #if defined(SQLITE_SYSTEM_MALLOC) \
  13215. + defined(SQLITE_WIN32_MALLOC) \
  13216. + defined(SQLITE_ZERO_MALLOC) \
  13217. + defined(SQLITE_MEMDEBUG)>1
  13218. # error "Two or more of the following compile-time configuration options\
  13219. are defined but at most one is allowed:\
  13220. SQLITE_SYSTEM_MALLOC, SQLITE_WIN32_MALLOC, SQLITE_MEMDEBUG,\
  13221. SQLITE_ZERO_MALLOC"
  13222. #endif
  13223. #if defined(SQLITE_SYSTEM_MALLOC) \
  13224. + defined(SQLITE_WIN32_MALLOC) \
  13225. + defined(SQLITE_ZERO_MALLOC) \
  13226. + defined(SQLITE_MEMDEBUG)==0
  13227. # define SQLITE_SYSTEM_MALLOC 1
  13228. #endif
  13229. /*
  13230. ** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the
  13231. ** sizes of memory allocations below this value where possible.
  13232. */
  13233. #if !defined(SQLITE_MALLOC_SOFT_LIMIT)
  13234. # define SQLITE_MALLOC_SOFT_LIMIT 1024
  13235. #endif
  13236. /*
  13237. ** We need to define _XOPEN_SOURCE as follows in order to enable
  13238. ** recursive mutexes on most Unix systems and fchmod() on OpenBSD.
  13239. ** But _XOPEN_SOURCE define causes problems for Mac OS X, so omit
  13240. ** it.
  13241. */
  13242. #if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__)
  13243. # define _XOPEN_SOURCE 600
  13244. #endif
  13245. /*
  13246. ** NDEBUG and SQLITE_DEBUG are opposites. It should always be true that
  13247. ** defined(NDEBUG)==!defined(SQLITE_DEBUG). If this is not currently true,
  13248. ** make it true by defining or undefining NDEBUG.
  13249. **
  13250. ** Setting NDEBUG makes the code smaller and faster by disabling the
  13251. ** assert() statements in the code. So we want the default action
  13252. ** to be for NDEBUG to be set and NDEBUG to be undefined only if SQLITE_DEBUG
  13253. ** is set. Thus NDEBUG becomes an opt-in rather than an opt-out
  13254. ** feature.
  13255. */
  13256. #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
  13257. # define NDEBUG 1
  13258. #endif
  13259. #if defined(NDEBUG) && defined(SQLITE_DEBUG)
  13260. # undef NDEBUG
  13261. #endif
  13262. /*
  13263. ** Enable SQLITE_ENABLE_EXPLAIN_COMMENTS if SQLITE_DEBUG is turned on.
  13264. */
  13265. #if !defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) && defined(SQLITE_DEBUG)
  13266. # define SQLITE_ENABLE_EXPLAIN_COMMENTS 1
  13267. #endif
  13268. /*
  13269. ** The testcase() macro is used to aid in coverage testing. When
  13270. ** doing coverage testing, the condition inside the argument to
  13271. ** testcase() must be evaluated both true and false in order to
  13272. ** get full branch coverage. The testcase() macro is inserted
  13273. ** to help ensure adequate test coverage in places where simple
  13274. ** condition/decision coverage is inadequate. For example, testcase()
  13275. ** can be used to make sure boundary values are tested. For
  13276. ** bitmask tests, testcase() can be used to make sure each bit
  13277. ** is significant and used at least once. On switch statements
  13278. ** where multiple cases go to the same block of code, testcase()
  13279. ** can insure that all cases are evaluated.
  13280. **
  13281. */
  13282. #ifdef SQLITE_COVERAGE_TEST
  13283. SQLITE_PRIVATE void sqlite3Coverage(int);
  13284. # define testcase(X) if( X ){ sqlite3Coverage(__LINE__); }
  13285. #else
  13286. # define testcase(X)
  13287. #endif
  13288. /*
  13289. ** The TESTONLY macro is used to enclose variable declarations or
  13290. ** other bits of code that are needed to support the arguments
  13291. ** within testcase() and assert() macros.
  13292. */
  13293. #if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)
  13294. # define TESTONLY(X) X
  13295. #else
  13296. # define TESTONLY(X)
  13297. #endif
  13298. /*
  13299. ** Sometimes we need a small amount of code such as a variable initialization
  13300. ** to setup for a later assert() statement. We do not want this code to
  13301. ** appear when assert() is disabled. The following macro is therefore
  13302. ** used to contain that setup code. The "VVA" acronym stands for
  13303. ** "Verification, Validation, and Accreditation". In other words, the
  13304. ** code within VVA_ONLY() will only run during verification processes.
  13305. */
  13306. #ifndef NDEBUG
  13307. # define VVA_ONLY(X) X
  13308. #else
  13309. # define VVA_ONLY(X)
  13310. #endif
  13311. /*
  13312. ** The ALWAYS and NEVER macros surround boolean expressions which
  13313. ** are intended to always be true or false, respectively. Such
  13314. ** expressions could be omitted from the code completely. But they
  13315. ** are included in a few cases in order to enhance the resilience
  13316. ** of SQLite to unexpected behavior - to make the code "self-healing"
  13317. ** or "ductile" rather than being "brittle" and crashing at the first
  13318. ** hint of unplanned behavior.
  13319. **
  13320. ** In other words, ALWAYS and NEVER are added for defensive code.
  13321. **
  13322. ** When doing coverage testing ALWAYS and NEVER are hard-coded to
  13323. ** be true and false so that the unreachable code they specify will
  13324. ** not be counted as untested code.
  13325. */
  13326. #if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_MUTATION_TEST)
  13327. # define ALWAYS(X) (1)
  13328. # define NEVER(X) (0)
  13329. #elif !defined(NDEBUG)
  13330. # define ALWAYS(X) ((X)?1:(assert(0),0))
  13331. # define NEVER(X) ((X)?(assert(0),1):0)
  13332. #else
  13333. # define ALWAYS(X) (X)
  13334. # define NEVER(X) (X)
  13335. #endif
  13336. /*
  13337. ** The harmless(X) macro indicates that expression X is usually false
  13338. ** but can be true without causing any problems, but we don't know of
  13339. ** any way to cause X to be true.
  13340. **
  13341. ** In debugging and testing builds, this macro will abort if X is ever
  13342. ** true. In this way, developers are alerted to a possible test case
  13343. ** that causes X to be true. If a harmless macro ever fails, that is
  13344. ** an opportunity to change the macro into a testcase() and add a new
  13345. ** test case to the test suite.
  13346. **
  13347. ** For normal production builds, harmless(X) is a no-op, since it does
  13348. ** not matter whether expression X is true or false.
  13349. */
  13350. #ifdef SQLITE_DEBUG
  13351. # define harmless(X) assert(!(X));
  13352. #else
  13353. # define harmless(X)
  13354. #endif
  13355. /*
  13356. ** Some conditionals are optimizations only. In other words, if the
  13357. ** conditionals are replaced with a constant 1 (true) or 0 (false) then
  13358. ** the correct answer is still obtained, though perhaps not as quickly.
  13359. **
  13360. ** The following macros mark these optimizations conditionals.
  13361. */
  13362. #if defined(SQLITE_MUTATION_TEST)
  13363. # define OK_IF_ALWAYS_TRUE(X) (1)
  13364. # define OK_IF_ALWAYS_FALSE(X) (0)
  13365. #else
  13366. # define OK_IF_ALWAYS_TRUE(X) (X)
  13367. # define OK_IF_ALWAYS_FALSE(X) (X)
  13368. #endif
  13369. /*
  13370. ** Some malloc failures are only possible if SQLITE_TEST_REALLOC_STRESS is
  13371. ** defined. We need to defend against those failures when testing with
  13372. ** SQLITE_TEST_REALLOC_STRESS, but we don't want the unreachable branches
  13373. ** during a normal build. The following macro can be used to disable tests
  13374. ** that are always false except when SQLITE_TEST_REALLOC_STRESS is set.
  13375. */
  13376. #if defined(SQLITE_TEST_REALLOC_STRESS)
  13377. # define ONLY_IF_REALLOC_STRESS(X) (X)
  13378. #elif !defined(NDEBUG)
  13379. # define ONLY_IF_REALLOC_STRESS(X) ((X)?(assert(0),1):0)
  13380. #else
  13381. # define ONLY_IF_REALLOC_STRESS(X) (0)
  13382. #endif
  13383. /*
  13384. ** Declarations used for tracing the operating system interfaces.
  13385. */
  13386. #if defined(SQLITE_FORCE_OS_TRACE) || defined(SQLITE_TEST) || \
  13387. (defined(SQLITE_DEBUG) && SQLITE_OS_WIN)
  13388. extern int sqlite3OSTrace;
  13389. # define OSTRACE(X) if( sqlite3OSTrace ) sqlite3DebugPrintf X
  13390. # define SQLITE_HAVE_OS_TRACE
  13391. #else
  13392. # define OSTRACE(X)
  13393. # undef SQLITE_HAVE_OS_TRACE
  13394. #endif
  13395. /*
  13396. ** Is the sqlite3ErrName() function needed in the build? Currently,
  13397. ** it is needed by "mutex_w32.c" (when debugging), "os_win.c" (when
  13398. ** OSTRACE is enabled), and by several "test*.c" files (which are
  13399. ** compiled using SQLITE_TEST).
  13400. */
  13401. #if defined(SQLITE_HAVE_OS_TRACE) || defined(SQLITE_TEST) || \
  13402. (defined(SQLITE_DEBUG) && SQLITE_OS_WIN)
  13403. # define SQLITE_NEED_ERR_NAME
  13404. #else
  13405. # undef SQLITE_NEED_ERR_NAME
  13406. #endif
  13407. /*
  13408. ** SQLITE_ENABLE_EXPLAIN_COMMENTS is incompatible with SQLITE_OMIT_EXPLAIN
  13409. */
  13410. #ifdef SQLITE_OMIT_EXPLAIN
  13411. # undef SQLITE_ENABLE_EXPLAIN_COMMENTS
  13412. #endif
  13413. /*
  13414. ** Return true (non-zero) if the input is an integer that is too large
  13415. ** to fit in 32-bits. This macro is used inside of various testcase()
  13416. ** macros to verify that we have tested SQLite for large-file support.
  13417. */
  13418. #define IS_BIG_INT(X) (((X)&~(i64)0xffffffff)!=0)
  13419. /*
  13420. ** The macro unlikely() is a hint that surrounds a boolean
  13421. ** expression that is usually false. Macro likely() surrounds
  13422. ** a boolean expression that is usually true. These hints could,
  13423. ** in theory, be used by the compiler to generate better code, but
  13424. ** currently they are just comments for human readers.
  13425. */
  13426. #define likely(X) (X)
  13427. #define unlikely(X) (X)
  13428. /************** Include hash.h in the middle of sqliteInt.h ******************/
  13429. /************** Begin file hash.h ********************************************/
  13430. /*
  13431. ** 2001 September 22
  13432. **
  13433. ** The author disclaims copyright to this source code. In place of
  13434. ** a legal notice, here is a blessing:
  13435. **
  13436. ** May you do good and not evil.
  13437. ** May you find forgiveness for yourself and forgive others.
  13438. ** May you share freely, never taking more than you give.
  13439. **
  13440. *************************************************************************
  13441. ** This is the header file for the generic hash-table implementation
  13442. ** used in SQLite.
  13443. */
  13444. #ifndef SQLITE_HASH_H
  13445. #define SQLITE_HASH_H
  13446. /* Forward declarations of structures. */
  13447. typedef struct Hash Hash;
  13448. typedef struct HashElem HashElem;
  13449. /* A complete hash table is an instance of the following structure.
  13450. ** The internals of this structure are intended to be opaque -- client
  13451. ** code should not attempt to access or modify the fields of this structure
  13452. ** directly. Change this structure only by using the routines below.
  13453. ** However, some of the "procedures" and "functions" for modifying and
  13454. ** accessing this structure are really macros, so we can't really make
  13455. ** this structure opaque.
  13456. **
  13457. ** All elements of the hash table are on a single doubly-linked list.
  13458. ** Hash.first points to the head of this list.
  13459. **
  13460. ** There are Hash.htsize buckets. Each bucket points to a spot in
  13461. ** the global doubly-linked list. The contents of the bucket are the
  13462. ** element pointed to plus the next _ht.count-1 elements in the list.
  13463. **
  13464. ** Hash.htsize and Hash.ht may be zero. In that case lookup is done
  13465. ** by a linear search of the global list. For small tables, the
  13466. ** Hash.ht table is never allocated because if there are few elements
  13467. ** in the table, it is faster to do a linear search than to manage
  13468. ** the hash table.
  13469. */
  13470. struct Hash {
  13471. unsigned int htsize; /* Number of buckets in the hash table */
  13472. unsigned int count; /* Number of entries in this table */
  13473. HashElem *first; /* The first element of the array */
  13474. struct _ht { /* the hash table */
  13475. unsigned int count; /* Number of entries with this hash */
  13476. HashElem *chain; /* Pointer to first entry with this hash */
  13477. } *ht;
  13478. };
  13479. /* Each element in the hash table is an instance of the following
  13480. ** structure. All elements are stored on a single doubly-linked list.
  13481. **
  13482. ** Again, this structure is intended to be opaque, but it can't really
  13483. ** be opaque because it is used by macros.
  13484. */
  13485. struct HashElem {
  13486. HashElem *next, *prev; /* Next and previous elements in the table */
  13487. void *data; /* Data associated with this element */
  13488. const char *pKey; /* Key associated with this element */
  13489. };
  13490. /*
  13491. ** Access routines. To delete, insert a NULL pointer.
  13492. */
  13493. SQLITE_PRIVATE void sqlite3HashInit(Hash*);
  13494. SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, void *pData);
  13495. SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey);
  13496. SQLITE_PRIVATE void sqlite3HashClear(Hash*);
  13497. /*
  13498. ** Macros for looping over all elements of a hash table. The idiom is
  13499. ** like this:
  13500. **
  13501. ** Hash h;
  13502. ** HashElem *p;
  13503. ** ...
  13504. ** for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
  13505. ** SomeStructure *pData = sqliteHashData(p);
  13506. ** // do something with pData
  13507. ** }
  13508. */
  13509. #define sqliteHashFirst(H) ((H)->first)
  13510. #define sqliteHashNext(E) ((E)->next)
  13511. #define sqliteHashData(E) ((E)->data)
  13512. /* #define sqliteHashKey(E) ((E)->pKey) // NOT USED */
  13513. /* #define sqliteHashKeysize(E) ((E)->nKey) // NOT USED */
  13514. /*
  13515. ** Number of entries in a hash table
  13516. */
  13517. /* #define sqliteHashCount(H) ((H)->count) // NOT USED */
  13518. #endif /* SQLITE_HASH_H */
  13519. /************** End of hash.h ************************************************/
  13520. /************** Continuing where we left off in sqliteInt.h ******************/
  13521. /************** Include parse.h in the middle of sqliteInt.h *****************/
  13522. /************** Begin file parse.h *******************************************/
  13523. #define TK_SEMI 1
  13524. #define TK_EXPLAIN 2
  13525. #define TK_QUERY 3
  13526. #define TK_PLAN 4
  13527. #define TK_BEGIN 5
  13528. #define TK_TRANSACTION 6
  13529. #define TK_DEFERRED 7
  13530. #define TK_IMMEDIATE 8
  13531. #define TK_EXCLUSIVE 9
  13532. #define TK_COMMIT 10
  13533. #define TK_END 11
  13534. #define TK_ROLLBACK 12
  13535. #define TK_SAVEPOINT 13
  13536. #define TK_RELEASE 14
  13537. #define TK_TO 15
  13538. #define TK_TABLE 16
  13539. #define TK_CREATE 17
  13540. #define TK_IF 18
  13541. #define TK_NOT 19
  13542. #define TK_EXISTS 20
  13543. #define TK_TEMP 21
  13544. #define TK_LP 22
  13545. #define TK_RP 23
  13546. #define TK_AS 24
  13547. #define TK_WITHOUT 25
  13548. #define TK_COMMA 26
  13549. #define TK_ABORT 27
  13550. #define TK_ACTION 28
  13551. #define TK_AFTER 29
  13552. #define TK_ANALYZE 30
  13553. #define TK_ASC 31
  13554. #define TK_ATTACH 32
  13555. #define TK_BEFORE 33
  13556. #define TK_BY 34
  13557. #define TK_CASCADE 35
  13558. #define TK_CAST 36
  13559. #define TK_CONFLICT 37
  13560. #define TK_DATABASE 38
  13561. #define TK_DESC 39
  13562. #define TK_DETACH 40
  13563. #define TK_EACH 41
  13564. #define TK_FAIL 42
  13565. #define TK_OR 43
  13566. #define TK_AND 44
  13567. #define TK_IS 45
  13568. #define TK_MATCH 46
  13569. #define TK_LIKE_KW 47
  13570. #define TK_BETWEEN 48
  13571. #define TK_IN 49
  13572. #define TK_ISNULL 50
  13573. #define TK_NOTNULL 51
  13574. #define TK_NE 52
  13575. #define TK_EQ 53
  13576. #define TK_GT 54
  13577. #define TK_LE 55
  13578. #define TK_LT 56
  13579. #define TK_GE 57
  13580. #define TK_ESCAPE 58
  13581. #define TK_ID 59
  13582. #define TK_COLUMNKW 60
  13583. #define TK_DO 61
  13584. #define TK_FOR 62
  13585. #define TK_IGNORE 63
  13586. #define TK_INITIALLY 64
  13587. #define TK_INSTEAD 65
  13588. #define TK_NO 66
  13589. #define TK_KEY 67
  13590. #define TK_OF 68
  13591. #define TK_OFFSET 69
  13592. #define TK_PRAGMA 70
  13593. #define TK_RAISE 71
  13594. #define TK_RECURSIVE 72
  13595. #define TK_REPLACE 73
  13596. #define TK_RESTRICT 74
  13597. #define TK_ROW 75
  13598. #define TK_ROWS 76
  13599. #define TK_TRIGGER 77
  13600. #define TK_VACUUM 78
  13601. #define TK_VIEW 79
  13602. #define TK_VIRTUAL 80
  13603. #define TK_WITH 81
  13604. #define TK_NULLS 82
  13605. #define TK_FIRST 83
  13606. #define TK_LAST 84
  13607. #define TK_CURRENT 85
  13608. #define TK_FOLLOWING 86
  13609. #define TK_PARTITION 87
  13610. #define TK_PRECEDING 88
  13611. #define TK_RANGE 89
  13612. #define TK_UNBOUNDED 90
  13613. #define TK_EXCLUDE 91
  13614. #define TK_GROUPS 92
  13615. #define TK_OTHERS 93
  13616. #define TK_TIES 94
  13617. #define TK_GENERATED 95
  13618. #define TK_ALWAYS 96
  13619. #define TK_REINDEX 97
  13620. #define TK_RENAME 98
  13621. #define TK_CTIME_KW 99
  13622. #define TK_ANY 100
  13623. #define TK_BITAND 101
  13624. #define TK_BITOR 102
  13625. #define TK_LSHIFT 103
  13626. #define TK_RSHIFT 104
  13627. #define TK_PLUS 105
  13628. #define TK_MINUS 106
  13629. #define TK_STAR 107
  13630. #define TK_SLASH 108
  13631. #define TK_REM 109
  13632. #define TK_CONCAT 110
  13633. #define TK_COLLATE 111
  13634. #define TK_BITNOT 112
  13635. #define TK_ON 113
  13636. #define TK_INDEXED 114
  13637. #define TK_STRING 115
  13638. #define TK_JOIN_KW 116
  13639. #define TK_CONSTRAINT 117
  13640. #define TK_DEFAULT 118
  13641. #define TK_NULL 119
  13642. #define TK_PRIMARY 120
  13643. #define TK_UNIQUE 121
  13644. #define TK_CHECK 122
  13645. #define TK_REFERENCES 123
  13646. #define TK_AUTOINCR 124
  13647. #define TK_INSERT 125
  13648. #define TK_DELETE 126
  13649. #define TK_UPDATE 127
  13650. #define TK_SET 128
  13651. #define TK_DEFERRABLE 129
  13652. #define TK_FOREIGN 130
  13653. #define TK_DROP 131
  13654. #define TK_UNION 132
  13655. #define TK_ALL 133
  13656. #define TK_EXCEPT 134
  13657. #define TK_INTERSECT 135
  13658. #define TK_SELECT 136
  13659. #define TK_VALUES 137
  13660. #define TK_DISTINCT 138
  13661. #define TK_DOT 139
  13662. #define TK_FROM 140
  13663. #define TK_JOIN 141
  13664. #define TK_USING 142
  13665. #define TK_ORDER 143
  13666. #define TK_GROUP 144
  13667. #define TK_HAVING 145
  13668. #define TK_LIMIT 146
  13669. #define TK_WHERE 147
  13670. #define TK_INTO 148
  13671. #define TK_NOTHING 149
  13672. #define TK_FLOAT 150
  13673. #define TK_BLOB 151
  13674. #define TK_INTEGER 152
  13675. #define TK_VARIABLE 153
  13676. #define TK_CASE 154
  13677. #define TK_WHEN 155
  13678. #define TK_THEN 156
  13679. #define TK_ELSE 157
  13680. #define TK_INDEX 158
  13681. #define TK_ALTER 159
  13682. #define TK_ADD 160
  13683. #define TK_WINDOW 161
  13684. #define TK_OVER 162
  13685. #define TK_FILTER 163
  13686. #define TK_COLUMN 164
  13687. #define TK_AGG_FUNCTION 165
  13688. #define TK_AGG_COLUMN 166
  13689. #define TK_TRUEFALSE 167
  13690. #define TK_ISNOT 168
  13691. #define TK_FUNCTION 169
  13692. #define TK_UMINUS 170
  13693. #define TK_UPLUS 171
  13694. #define TK_TRUTH 172
  13695. #define TK_REGISTER 173
  13696. #define TK_VECTOR 174
  13697. #define TK_SELECT_COLUMN 175
  13698. #define TK_IF_NULL_ROW 176
  13699. #define TK_ASTERISK 177
  13700. #define TK_SPAN 178
  13701. #define TK_SPACE 179
  13702. #define TK_ILLEGAL 180
  13703. /************** End of parse.h ***********************************************/
  13704. /************** Continuing where we left off in sqliteInt.h ******************/
  13705. #include <stdio.h>
  13706. #include <stdlib.h>
  13707. #include <string.h>
  13708. #include <assert.h>
  13709. #include <stddef.h>
  13710. /*
  13711. ** Use a macro to replace memcpy() if compiled with SQLITE_INLINE_MEMCPY.
  13712. ** This allows better measurements of where memcpy() is used when running
  13713. ** cachegrind. But this macro version of memcpy() is very slow so it
  13714. ** should not be used in production. This is a performance measurement
  13715. ** hack only.
  13716. */
  13717. #ifdef SQLITE_INLINE_MEMCPY
  13718. # define memcpy(D,S,N) {char*xxd=(char*)(D);const char*xxs=(const char*)(S);\
  13719. int xxn=(N);while(xxn-->0)*(xxd++)=*(xxs++);}
  13720. #endif
  13721. /*
  13722. ** If compiling for a processor that lacks floating point support,
  13723. ** substitute integer for floating-point
  13724. */
  13725. #ifdef SQLITE_OMIT_FLOATING_POINT
  13726. # define double sqlite_int64
  13727. # define float sqlite_int64
  13728. # define LONGDOUBLE_TYPE sqlite_int64
  13729. # ifndef SQLITE_BIG_DBL
  13730. # define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)
  13731. # endif
  13732. # define SQLITE_OMIT_DATETIME_FUNCS 1
  13733. # define SQLITE_OMIT_TRACE 1
  13734. # undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
  13735. # undef SQLITE_HAVE_ISNAN
  13736. #endif
  13737. #ifndef SQLITE_BIG_DBL
  13738. # define SQLITE_BIG_DBL (1e99)
  13739. #endif
  13740. /*
  13741. ** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
  13742. ** afterward. Having this macro allows us to cause the C compiler
  13743. ** to omit code used by TEMP tables without messy #ifndef statements.
  13744. */
  13745. #ifdef SQLITE_OMIT_TEMPDB
  13746. #define OMIT_TEMPDB 1
  13747. #else
  13748. #define OMIT_TEMPDB 0
  13749. #endif
  13750. /*
  13751. ** The "file format" number is an integer that is incremented whenever
  13752. ** the VDBE-level file format changes. The following macros define the
  13753. ** the default file format for new databases and the maximum file format
  13754. ** that the library can read.
  13755. */
  13756. #define SQLITE_MAX_FILE_FORMAT 4
  13757. #ifndef SQLITE_DEFAULT_FILE_FORMAT
  13758. # define SQLITE_DEFAULT_FILE_FORMAT 4
  13759. #endif
  13760. /*
  13761. ** Determine whether triggers are recursive by default. This can be
  13762. ** changed at run-time using a pragma.
  13763. */
  13764. #ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS
  13765. # define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0
  13766. #endif
  13767. /*
  13768. ** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
  13769. ** on the command-line
  13770. */
  13771. #ifndef SQLITE_TEMP_STORE
  13772. # define SQLITE_TEMP_STORE 1
  13773. #endif
  13774. /*
  13775. ** If no value has been provided for SQLITE_MAX_WORKER_THREADS, or if
  13776. ** SQLITE_TEMP_STORE is set to 3 (never use temporary files), set it
  13777. ** to zero.
  13778. */
  13779. #if SQLITE_TEMP_STORE==3 || SQLITE_THREADSAFE==0
  13780. # undef SQLITE_MAX_WORKER_THREADS
  13781. # define SQLITE_MAX_WORKER_THREADS 0
  13782. #endif
  13783. #ifndef SQLITE_MAX_WORKER_THREADS
  13784. # define SQLITE_MAX_WORKER_THREADS 8
  13785. #endif
  13786. #ifndef SQLITE_DEFAULT_WORKER_THREADS
  13787. # define SQLITE_DEFAULT_WORKER_THREADS 0
  13788. #endif
  13789. #if SQLITE_DEFAULT_WORKER_THREADS>SQLITE_MAX_WORKER_THREADS
  13790. # undef SQLITE_MAX_WORKER_THREADS
  13791. # define SQLITE_MAX_WORKER_THREADS SQLITE_DEFAULT_WORKER_THREADS
  13792. #endif
  13793. /*
  13794. ** The default initial allocation for the pagecache when using separate
  13795. ** pagecaches for each database connection. A positive number is the
  13796. ** number of pages. A negative number N translations means that a buffer
  13797. ** of -1024*N bytes is allocated and used for as many pages as it will hold.
  13798. **
  13799. ** The default value of "20" was choosen to minimize the run-time of the
  13800. ** speedtest1 test program with options: --shrink-memory --reprepare
  13801. */
  13802. #ifndef SQLITE_DEFAULT_PCACHE_INITSZ
  13803. # define SQLITE_DEFAULT_PCACHE_INITSZ 20
  13804. #endif
  13805. /*
  13806. ** Default value for the SQLITE_CONFIG_SORTERREF_SIZE option.
  13807. */
  13808. #ifndef SQLITE_DEFAULT_SORTERREF_SIZE
  13809. # define SQLITE_DEFAULT_SORTERREF_SIZE 0x7fffffff
  13810. #endif
  13811. /*
  13812. ** The compile-time options SQLITE_MMAP_READWRITE and
  13813. ** SQLITE_ENABLE_BATCH_ATOMIC_WRITE are not compatible with one another.
  13814. ** You must choose one or the other (or neither) but not both.
  13815. */
  13816. #if defined(SQLITE_MMAP_READWRITE) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
  13817. #error Cannot use both SQLITE_MMAP_READWRITE and SQLITE_ENABLE_BATCH_ATOMIC_WRITE
  13818. #endif
  13819. /*
  13820. ** GCC does not define the offsetof() macro so we'll have to do it
  13821. ** ourselves.
  13822. */
  13823. #ifndef offsetof
  13824. #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
  13825. #endif
  13826. /*
  13827. ** Macros to compute minimum and maximum of two numbers.
  13828. */
  13829. #ifndef MIN
  13830. # define MIN(A,B) ((A)<(B)?(A):(B))
  13831. #endif
  13832. #ifndef MAX
  13833. # define MAX(A,B) ((A)>(B)?(A):(B))
  13834. #endif
  13835. /*
  13836. ** Swap two objects of type TYPE.
  13837. */
  13838. #define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
  13839. /*
  13840. ** Check to see if this machine uses EBCDIC. (Yes, believe it or
  13841. ** not, there are still machines out there that use EBCDIC.)
  13842. */
  13843. #if 'A' == '\301'
  13844. # define SQLITE_EBCDIC 1
  13845. #else
  13846. # define SQLITE_ASCII 1
  13847. #endif
  13848. /*
  13849. ** Integers of known sizes. These typedefs might change for architectures
  13850. ** where the sizes very. Preprocessor macros are available so that the
  13851. ** types can be conveniently redefined at compile-type. Like this:
  13852. **
  13853. ** cc '-DUINTPTR_TYPE=long long int' ...
  13854. */
  13855. #ifndef UINT32_TYPE
  13856. # ifdef HAVE_UINT32_T
  13857. # define UINT32_TYPE uint32_t
  13858. # else
  13859. # define UINT32_TYPE unsigned int
  13860. # endif
  13861. #endif
  13862. #ifndef UINT16_TYPE
  13863. # ifdef HAVE_UINT16_T
  13864. # define UINT16_TYPE uint16_t
  13865. # else
  13866. # define UINT16_TYPE unsigned short int
  13867. # endif
  13868. #endif
  13869. #ifndef INT16_TYPE
  13870. # ifdef HAVE_INT16_T
  13871. # define INT16_TYPE int16_t
  13872. # else
  13873. # define INT16_TYPE short int
  13874. # endif
  13875. #endif
  13876. #ifndef UINT8_TYPE
  13877. # ifdef HAVE_UINT8_T
  13878. # define UINT8_TYPE uint8_t
  13879. # else
  13880. # define UINT8_TYPE unsigned char
  13881. # endif
  13882. #endif
  13883. #ifndef INT8_TYPE
  13884. # ifdef HAVE_INT8_T
  13885. # define INT8_TYPE int8_t
  13886. # else
  13887. # define INT8_TYPE signed char
  13888. # endif
  13889. #endif
  13890. #ifndef LONGDOUBLE_TYPE
  13891. # define LONGDOUBLE_TYPE long double
  13892. #endif
  13893. typedef sqlite_int64 i64; /* 8-byte signed integer */
  13894. typedef sqlite_uint64 u64; /* 8-byte unsigned integer */
  13895. typedef UINT32_TYPE u32; /* 4-byte unsigned integer */
  13896. typedef UINT16_TYPE u16; /* 2-byte unsigned integer */
  13897. typedef INT16_TYPE i16; /* 2-byte signed integer */
  13898. typedef UINT8_TYPE u8; /* 1-byte unsigned integer */
  13899. typedef INT8_TYPE i8; /* 1-byte signed integer */
  13900. /*
  13901. ** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value
  13902. ** that can be stored in a u32 without loss of data. The value
  13903. ** is 0x00000000ffffffff. But because of quirks of some compilers, we
  13904. ** have to specify the value in the less intuitive manner shown:
  13905. */
  13906. #define SQLITE_MAX_U32 ((((u64)1)<<32)-1)
  13907. /*
  13908. ** The datatype used to store estimates of the number of rows in a
  13909. ** table or index. This is an unsigned integer type. For 99.9% of
  13910. ** the world, a 32-bit integer is sufficient. But a 64-bit integer
  13911. ** can be used at compile-time if desired.
  13912. */
  13913. #ifdef SQLITE_64BIT_STATS
  13914. typedef u64 tRowcnt; /* 64-bit only if requested at compile-time */
  13915. #else
  13916. typedef u32 tRowcnt; /* 32-bit is the default */
  13917. #endif
  13918. /*
  13919. ** Estimated quantities used for query planning are stored as 16-bit
  13920. ** logarithms. For quantity X, the value stored is 10*log2(X). This
  13921. ** gives a possible range of values of approximately 1.0e986 to 1e-986.
  13922. ** But the allowed values are "grainy". Not every value is representable.
  13923. ** For example, quantities 16 and 17 are both represented by a LogEst
  13924. ** of 40. However, since LogEst quantities are suppose to be estimates,
  13925. ** not exact values, this imprecision is not a problem.
  13926. **
  13927. ** "LogEst" is short for "Logarithmic Estimate".
  13928. **
  13929. ** Examples:
  13930. ** 1 -> 0 20 -> 43 10000 -> 132
  13931. ** 2 -> 10 25 -> 46 25000 -> 146
  13932. ** 3 -> 16 100 -> 66 1000000 -> 199
  13933. ** 4 -> 20 1000 -> 99 1048576 -> 200
  13934. ** 10 -> 33 1024 -> 100 4294967296 -> 320
  13935. **
  13936. ** The LogEst can be negative to indicate fractional values.
  13937. ** Examples:
  13938. **
  13939. ** 0.5 -> -10 0.1 -> -33 0.0625 -> -40
  13940. */
  13941. typedef INT16_TYPE LogEst;
  13942. /*
  13943. ** Set the SQLITE_PTRSIZE macro to the number of bytes in a pointer
  13944. */
  13945. #ifndef SQLITE_PTRSIZE
  13946. # if defined(__SIZEOF_POINTER__)
  13947. # define SQLITE_PTRSIZE __SIZEOF_POINTER__
  13948. # elif defined(i386) || defined(__i386__) || defined(_M_IX86) || \
  13949. defined(_M_ARM) || defined(__arm__) || defined(__x86) || \
  13950. (defined(__TOS_AIX__) && !defined(__64BIT__))
  13951. # define SQLITE_PTRSIZE 4
  13952. # else
  13953. # define SQLITE_PTRSIZE 8
  13954. # endif
  13955. #endif
  13956. /* The uptr type is an unsigned integer large enough to hold a pointer
  13957. */
  13958. #if defined(HAVE_STDINT_H)
  13959. typedef uintptr_t uptr;
  13960. #elif SQLITE_PTRSIZE==4
  13961. typedef u32 uptr;
  13962. #else
  13963. typedef u64 uptr;
  13964. #endif
  13965. /*
  13966. ** The SQLITE_WITHIN(P,S,E) macro checks to see if pointer P points to
  13967. ** something between S (inclusive) and E (exclusive).
  13968. **
  13969. ** In other words, S is a buffer and E is a pointer to the first byte after
  13970. ** the end of buffer S. This macro returns true if P points to something
  13971. ** contained within the buffer S.
  13972. */
  13973. #define SQLITE_WITHIN(P,S,E) (((uptr)(P)>=(uptr)(S))&&((uptr)(P)<(uptr)(E)))
  13974. /*
  13975. ** Macros to determine whether the machine is big or little endian,
  13976. ** and whether or not that determination is run-time or compile-time.
  13977. **
  13978. ** For best performance, an attempt is made to guess at the byte-order
  13979. ** using C-preprocessor macros. If that is unsuccessful, or if
  13980. ** -DSQLITE_BYTEORDER=0 is set, then byte-order is determined
  13981. ** at run-time.
  13982. */
  13983. #ifndef SQLITE_BYTEORDER
  13984. # if defined(i386) || defined(__i386__) || defined(_M_IX86) || \
  13985. defined(__x86_64) || defined(__x86_64__) || defined(_M_X64) || \
  13986. defined(_M_AMD64) || defined(_M_ARM) || defined(__x86) || \
  13987. defined(__ARMEL__) || defined(__AARCH64EL__) || defined(_M_ARM64)
  13988. # define SQLITE_BYTEORDER 1234
  13989. # elif defined(sparc) || defined(__ppc__) || \
  13990. defined(__ARMEB__) || defined(__AARCH64EB__)
  13991. # define SQLITE_BYTEORDER 4321
  13992. # else
  13993. # define SQLITE_BYTEORDER 0
  13994. # endif
  13995. #endif
  13996. #if SQLITE_BYTEORDER==4321
  13997. # define SQLITE_BIGENDIAN 1
  13998. # define SQLITE_LITTLEENDIAN 0
  13999. # define SQLITE_UTF16NATIVE SQLITE_UTF16BE
  14000. #elif SQLITE_BYTEORDER==1234
  14001. # define SQLITE_BIGENDIAN 0
  14002. # define SQLITE_LITTLEENDIAN 1
  14003. # define SQLITE_UTF16NATIVE SQLITE_UTF16LE
  14004. #else
  14005. # ifdef SQLITE_AMALGAMATION
  14006. const int sqlite3one = 1;
  14007. # else
  14008. extern const int sqlite3one;
  14009. # endif
  14010. # define SQLITE_BIGENDIAN (*(char *)(&sqlite3one)==0)
  14011. # define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
  14012. # define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
  14013. #endif
  14014. /*
  14015. ** Constants for the largest and smallest possible 64-bit signed integers.
  14016. ** These macros are designed to work correctly on both 32-bit and 64-bit
  14017. ** compilers.
  14018. */
  14019. #define LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32))
  14020. #define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
  14021. /*
  14022. ** Round up a number to the next larger multiple of 8. This is used
  14023. ** to force 8-byte alignment on 64-bit architectures.
  14024. */
  14025. #define ROUND8(x) (((x)+7)&~7)
  14026. /*
  14027. ** Round down to the nearest multiple of 8
  14028. */
  14029. #define ROUNDDOWN8(x) ((x)&~7)
  14030. /*
  14031. ** Assert that the pointer X is aligned to an 8-byte boundary. This
  14032. ** macro is used only within assert() to verify that the code gets
  14033. ** all alignment restrictions correct.
  14034. **
  14035. ** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the
  14036. ** underlying malloc() implementation might return us 4-byte aligned
  14037. ** pointers. In that case, only verify 4-byte alignment.
  14038. */
  14039. #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
  14040. # define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&3)==0)
  14041. #else
  14042. # define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&7)==0)
  14043. #endif
  14044. /*
  14045. ** Disable MMAP on platforms where it is known to not work
  14046. */
  14047. #if defined(__OpenBSD__) || defined(__QNXNTO__)
  14048. # undef SQLITE_MAX_MMAP_SIZE
  14049. # define SQLITE_MAX_MMAP_SIZE 0
  14050. #endif
  14051. /*
  14052. ** Default maximum size of memory used by memory-mapped I/O in the VFS
  14053. */
  14054. #ifdef __APPLE__
  14055. # include <TargetConditionals.h>
  14056. #endif
  14057. #ifndef SQLITE_MAX_MMAP_SIZE
  14058. # if defined(__linux__) \
  14059. || defined(_WIN32) \
  14060. || (defined(__APPLE__) && defined(__MACH__)) \
  14061. || defined(__sun) \
  14062. || defined(__FreeBSD__) \
  14063. || defined(__DragonFly__)
  14064. # define SQLITE_MAX_MMAP_SIZE 0x7fff0000 /* 2147418112 */
  14065. # else
  14066. # define SQLITE_MAX_MMAP_SIZE 0
  14067. # endif
  14068. #endif
  14069. /*
  14070. ** The default MMAP_SIZE is zero on all platforms. Or, even if a larger
  14071. ** default MMAP_SIZE is specified at compile-time, make sure that it does
  14072. ** not exceed the maximum mmap size.
  14073. */
  14074. #ifndef SQLITE_DEFAULT_MMAP_SIZE
  14075. # define SQLITE_DEFAULT_MMAP_SIZE 0
  14076. #endif
  14077. #if SQLITE_DEFAULT_MMAP_SIZE>SQLITE_MAX_MMAP_SIZE
  14078. # undef SQLITE_DEFAULT_MMAP_SIZE
  14079. # define SQLITE_DEFAULT_MMAP_SIZE SQLITE_MAX_MMAP_SIZE
  14080. #endif
  14081. /*
  14082. ** SELECTTRACE_ENABLED will be either 1 or 0 depending on whether or not
  14083. ** the Select query generator tracing logic is turned on.
  14084. */
  14085. #if defined(SQLITE_ENABLE_SELECTTRACE)
  14086. # define SELECTTRACE_ENABLED 1
  14087. #else
  14088. # define SELECTTRACE_ENABLED 0
  14089. #endif
  14090. /*
  14091. ** An instance of the following structure is used to store the busy-handler
  14092. ** callback for a given sqlite handle.
  14093. **
  14094. ** The sqlite.busyHandler member of the sqlite struct contains the busy
  14095. ** callback for the database handle. Each pager opened via the sqlite
  14096. ** handle is passed a pointer to sqlite.busyHandler. The busy-handler
  14097. ** callback is currently invoked only from within pager.c.
  14098. */
  14099. typedef struct BusyHandler BusyHandler;
  14100. struct BusyHandler {
  14101. int (*xBusyHandler)(void *,int); /* The busy callback */
  14102. void *pBusyArg; /* First arg to busy callback */
  14103. int nBusy; /* Incremented with each busy call */
  14104. };
  14105. /*
  14106. ** Name of the master database table. The master database table
  14107. ** is a special table that holds the names and attributes of all
  14108. ** user tables and indices.
  14109. */
  14110. #define MASTER_NAME "sqlite_master"
  14111. #define TEMP_MASTER_NAME "sqlite_temp_master"
  14112. /*
  14113. ** The root-page of the master database table.
  14114. */
  14115. #define MASTER_ROOT 1
  14116. /*
  14117. ** The name of the schema table.
  14118. */
  14119. #define SCHEMA_TABLE(x) ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
  14120. /*
  14121. ** A convenience macro that returns the number of elements in
  14122. ** an array.
  14123. */
  14124. #define ArraySize(X) ((int)(sizeof(X)/sizeof(X[0])))
  14125. /*
  14126. ** Determine if the argument is a power of two
  14127. */
  14128. #define IsPowerOfTwo(X) (((X)&((X)-1))==0)
  14129. /*
  14130. ** The following value as a destructor means to use sqlite3DbFree().
  14131. ** The sqlite3DbFree() routine requires two parameters instead of the
  14132. ** one parameter that destructors normally want. So we have to introduce
  14133. ** this magic value that the code knows to handle differently. Any
  14134. ** pointer will work here as long as it is distinct from SQLITE_STATIC
  14135. ** and SQLITE_TRANSIENT.
  14136. */
  14137. #define SQLITE_DYNAMIC ((sqlite3_destructor_type)sqlite3MallocSize)
  14138. /*
  14139. ** When SQLITE_OMIT_WSD is defined, it means that the target platform does
  14140. ** not support Writable Static Data (WSD) such as global and static variables.
  14141. ** All variables must either be on the stack or dynamically allocated from
  14142. ** the heap. When WSD is unsupported, the variable declarations scattered
  14143. ** throughout the SQLite code must become constants instead. The SQLITE_WSD
  14144. ** macro is used for this purpose. And instead of referencing the variable
  14145. ** directly, we use its constant as a key to lookup the run-time allocated
  14146. ** buffer that holds real variable. The constant is also the initializer
  14147. ** for the run-time allocated buffer.
  14148. **
  14149. ** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
  14150. ** macros become no-ops and have zero performance impact.
  14151. */
  14152. #ifdef SQLITE_OMIT_WSD
  14153. #define SQLITE_WSD const
  14154. #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
  14155. #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
  14156. SQLITE_API int sqlite3_wsd_init(int N, int J);
  14157. SQLITE_API void *sqlite3_wsd_find(void *K, int L);
  14158. #else
  14159. #define SQLITE_WSD
  14160. #define GLOBAL(t,v) v
  14161. #define sqlite3GlobalConfig sqlite3Config
  14162. #endif
  14163. /*
  14164. ** The following macros are used to suppress compiler warnings and to
  14165. ** make it clear to human readers when a function parameter is deliberately
  14166. ** left unused within the body of a function. This usually happens when
  14167. ** a function is called via a function pointer. For example the
  14168. ** implementation of an SQL aggregate step callback may not use the
  14169. ** parameter indicating the number of arguments passed to the aggregate,
  14170. ** if it knows that this is enforced elsewhere.
  14171. **
  14172. ** When a function parameter is not used at all within the body of a function,
  14173. ** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
  14174. ** However, these macros may also be used to suppress warnings related to
  14175. ** parameters that may or may not be used depending on compilation options.
  14176. ** For example those parameters only used in assert() statements. In these
  14177. ** cases the parameters are named as per the usual conventions.
  14178. */
  14179. #define UNUSED_PARAMETER(x) (void)(x)
  14180. #define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
  14181. /*
  14182. ** Forward references to structures
  14183. */
  14184. typedef struct AggInfo AggInfo;
  14185. typedef struct AuthContext AuthContext;
  14186. typedef struct AutoincInfo AutoincInfo;
  14187. typedef struct Bitvec Bitvec;
  14188. typedef struct CollSeq CollSeq;
  14189. typedef struct Column Column;
  14190. typedef struct Db Db;
  14191. typedef struct Schema Schema;
  14192. typedef struct Expr Expr;
  14193. typedef struct ExprList ExprList;
  14194. typedef struct FKey FKey;
  14195. typedef struct FuncDestructor FuncDestructor;
  14196. typedef struct FuncDef FuncDef;
  14197. typedef struct FuncDefHash FuncDefHash;
  14198. typedef struct IdList IdList;
  14199. typedef struct Index Index;
  14200. typedef struct IndexSample IndexSample;
  14201. typedef struct KeyClass KeyClass;
  14202. typedef struct KeyInfo KeyInfo;
  14203. typedef struct Lookaside Lookaside;
  14204. typedef struct LookasideSlot LookasideSlot;
  14205. typedef struct Module Module;
  14206. typedef struct NameContext NameContext;
  14207. typedef struct Parse Parse;
  14208. typedef struct PreUpdate PreUpdate;
  14209. typedef struct PrintfArguments PrintfArguments;
  14210. typedef struct RenameToken RenameToken;
  14211. typedef struct RowSet RowSet;
  14212. typedef struct Savepoint Savepoint;
  14213. typedef struct Select Select;
  14214. typedef struct SQLiteThread SQLiteThread;
  14215. typedef struct SelectDest SelectDest;
  14216. typedef struct SrcList SrcList;
  14217. typedef struct sqlite3_str StrAccum; /* Internal alias for sqlite3_str */
  14218. typedef struct Table Table;
  14219. typedef struct TableLock TableLock;
  14220. typedef struct Token Token;
  14221. typedef struct TreeView TreeView;
  14222. typedef struct Trigger Trigger;
  14223. typedef struct TriggerPrg TriggerPrg;
  14224. typedef struct TriggerStep TriggerStep;
  14225. typedef struct UnpackedRecord UnpackedRecord;
  14226. typedef struct Upsert Upsert;
  14227. typedef struct VTable VTable;
  14228. typedef struct VtabCtx VtabCtx;
  14229. typedef struct Walker Walker;
  14230. typedef struct WhereInfo WhereInfo;
  14231. typedef struct Window Window;
  14232. typedef struct With With;
  14233. /*
  14234. ** The bitmask datatype defined below is used for various optimizations.
  14235. **
  14236. ** Changing this from a 64-bit to a 32-bit type limits the number of
  14237. ** tables in a join to 32 instead of 64. But it also reduces the size
  14238. ** of the library by 738 bytes on ix86.
  14239. */
  14240. #ifdef SQLITE_BITMASK_TYPE
  14241. typedef SQLITE_BITMASK_TYPE Bitmask;
  14242. #else
  14243. typedef u64 Bitmask;
  14244. #endif
  14245. /*
  14246. ** The number of bits in a Bitmask. "BMS" means "BitMask Size".
  14247. */
  14248. #define BMS ((int)(sizeof(Bitmask)*8))
  14249. /*
  14250. ** A bit in a Bitmask
  14251. */
  14252. #define MASKBIT(n) (((Bitmask)1)<<(n))
  14253. #define MASKBIT64(n) (((u64)1)<<(n))
  14254. #define MASKBIT32(n) (((unsigned int)1)<<(n))
  14255. #define ALLBITS ((Bitmask)-1)
  14256. /* A VList object records a mapping between parameters/variables/wildcards
  14257. ** in the SQL statement (such as $abc, @pqr, or :xyz) and the integer
  14258. ** variable number associated with that parameter. See the format description
  14259. ** on the sqlite3VListAdd() routine for more information. A VList is really
  14260. ** just an array of integers.
  14261. */
  14262. typedef int VList;
  14263. /*
  14264. ** Defer sourcing vdbe.h and btree.h until after the "u8" and
  14265. ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
  14266. ** pointer types (i.e. FuncDef) defined above.
  14267. */
  14268. /************** Include btree.h in the middle of sqliteInt.h *****************/
  14269. /************** Begin file btree.h *******************************************/
  14270. /*
  14271. ** 2001 September 15
  14272. **
  14273. ** The author disclaims copyright to this source code. In place of
  14274. ** a legal notice, here is a blessing:
  14275. **
  14276. ** May you do good and not evil.
  14277. ** May you find forgiveness for yourself and forgive others.
  14278. ** May you share freely, never taking more than you give.
  14279. **
  14280. *************************************************************************
  14281. ** This header file defines the interface that the sqlite B-Tree file
  14282. ** subsystem. See comments in the source code for a detailed description
  14283. ** of what each interface routine does.
  14284. */
  14285. #ifndef SQLITE_BTREE_H
  14286. #define SQLITE_BTREE_H
  14287. /* TODO: This definition is just included so other modules compile. It
  14288. ** needs to be revisited.
  14289. */
  14290. #define SQLITE_N_BTREE_META 16
  14291. /*
  14292. ** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
  14293. ** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
  14294. */
  14295. #ifndef SQLITE_DEFAULT_AUTOVACUUM
  14296. #define SQLITE_DEFAULT_AUTOVACUUM 0
  14297. #endif
  14298. #define BTREE_AUTOVACUUM_NONE 0 /* Do not do auto-vacuum */
  14299. #define BTREE_AUTOVACUUM_FULL 1 /* Do full auto-vacuum */
  14300. #define BTREE_AUTOVACUUM_INCR 2 /* Incremental vacuum */
  14301. /*
  14302. ** Forward declarations of structure
  14303. */
  14304. typedef struct Btree Btree;
  14305. typedef struct BtCursor BtCursor;
  14306. typedef struct BtShared BtShared;
  14307. typedef struct BtreePayload BtreePayload;
  14308. SQLITE_PRIVATE int sqlite3BtreeOpen(
  14309. sqlite3_vfs *pVfs, /* VFS to use with this b-tree */
  14310. const char *zFilename, /* Name of database file to open */
  14311. sqlite3 *db, /* Associated database connection */
  14312. Btree **ppBtree, /* Return open Btree* here */
  14313. int flags, /* Flags */
  14314. int vfsFlags /* Flags passed through to VFS open */
  14315. );
  14316. /* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
  14317. ** following values.
  14318. **
  14319. ** NOTE: These values must match the corresponding PAGER_ values in
  14320. ** pager.h.
  14321. */
  14322. #define BTREE_OMIT_JOURNAL 1 /* Do not create or use a rollback journal */
  14323. #define BTREE_MEMORY 2 /* This is an in-memory DB */
  14324. #define BTREE_SINGLE 4 /* The file contains at most 1 b-tree */
  14325. #define BTREE_UNORDERED 8 /* Use of a hash implementation is OK */
  14326. SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
  14327. SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
  14328. SQLITE_PRIVATE int sqlite3BtreeSetSpillSize(Btree*,int);
  14329. #if SQLITE_MAX_MMAP_SIZE>0
  14330. SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree*,sqlite3_int64);
  14331. #endif
  14332. SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(Btree*,unsigned);
  14333. SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);
  14334. SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
  14335. SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);
  14336. SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree*);
  14337. SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree*,int);
  14338. SQLITE_PRIVATE int sqlite3BtreeGetRequestedReserve(Btree*);
  14339. SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p);
  14340. SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
  14341. SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);
  14342. SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int,int*);
  14343. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
  14344. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*, int);
  14345. SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);
  14346. SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*,int,int);
  14347. SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int);
  14348. SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags);
  14349. SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*);
  14350. SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*);
  14351. SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*);
  14352. SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
  14353. SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree);
  14354. #ifndef SQLITE_OMIT_SHARED_CACHE
  14355. SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock);
  14356. #endif
  14357. SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int);
  14358. SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
  14359. SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
  14360. SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
  14361. SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
  14362. /* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
  14363. ** of the flags shown below.
  14364. **
  14365. ** Every SQLite table must have either BTREE_INTKEY or BTREE_BLOBKEY set.
  14366. ** With BTREE_INTKEY, the table key is a 64-bit integer and arbitrary data
  14367. ** is stored in the leaves. (BTREE_INTKEY is used for SQL tables.) With
  14368. ** BTREE_BLOBKEY, the key is an arbitrary BLOB and no content is stored
  14369. ** anywhere - the key is the content. (BTREE_BLOBKEY is used for SQL
  14370. ** indices.)
  14371. */
  14372. #define BTREE_INTKEY 1 /* Table has only 64-bit signed integer keys */
  14373. #define BTREE_BLOBKEY 2 /* Table has keys only - no data */
  14374. SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
  14375. SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*);
  14376. SQLITE_PRIVATE int sqlite3BtreeClearTableOfCursor(BtCursor*);
  14377. SQLITE_PRIVATE int sqlite3BtreeTripAllCursors(Btree*, int, int);
  14378. SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue);
  14379. SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
  14380. SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p);
  14381. /*
  14382. ** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta
  14383. ** should be one of the following values. The integer values are assigned
  14384. ** to constants so that the offset of the corresponding field in an
  14385. ** SQLite database header may be found using the following formula:
  14386. **
  14387. ** offset = 36 + (idx * 4)
  14388. **
  14389. ** For example, the free-page-count field is located at byte offset 36 of
  14390. ** the database file header. The incr-vacuum-flag field is located at
  14391. ** byte offset 64 (== 36+4*7).
  14392. **
  14393. ** The BTREE_DATA_VERSION value is not really a value stored in the header.
  14394. ** It is a read-only number computed by the pager. But we merge it with
  14395. ** the header value access routines since its access pattern is the same.
  14396. ** Call it a "virtual meta value".
  14397. */
  14398. #define BTREE_FREE_PAGE_COUNT 0
  14399. #define BTREE_SCHEMA_VERSION 1
  14400. #define BTREE_FILE_FORMAT 2
  14401. #define BTREE_DEFAULT_CACHE_SIZE 3
  14402. #define BTREE_LARGEST_ROOT_PAGE 4
  14403. #define BTREE_TEXT_ENCODING 5
  14404. #define BTREE_USER_VERSION 6
  14405. #define BTREE_INCR_VACUUM 7
  14406. #define BTREE_APPLICATION_ID 8
  14407. #define BTREE_DATA_VERSION 15 /* A virtual meta-value */
  14408. /*
  14409. ** Kinds of hints that can be passed into the sqlite3BtreeCursorHint()
  14410. ** interface.
  14411. **
  14412. ** BTREE_HINT_RANGE (arguments: Expr*, Mem*)
  14413. **
  14414. ** The first argument is an Expr* (which is guaranteed to be constant for
  14415. ** the lifetime of the cursor) that defines constraints on which rows
  14416. ** might be fetched with this cursor. The Expr* tree may contain
  14417. ** TK_REGISTER nodes that refer to values stored in the array of registers
  14418. ** passed as the second parameter. In other words, if Expr.op==TK_REGISTER
  14419. ** then the value of the node is the value in Mem[pExpr.iTable]. Any
  14420. ** TK_COLUMN node in the expression tree refers to the Expr.iColumn-th
  14421. ** column of the b-tree of the cursor. The Expr tree will not contain
  14422. ** any function calls nor subqueries nor references to b-trees other than
  14423. ** the cursor being hinted.
  14424. **
  14425. ** The design of the _RANGE hint is aid b-tree implementations that try
  14426. ** to prefetch content from remote machines - to provide those
  14427. ** implementations with limits on what needs to be prefetched and thereby
  14428. ** reduce network bandwidth.
  14429. **
  14430. ** Note that BTREE_HINT_FLAGS with BTREE_BULKLOAD is the only hint used by
  14431. ** standard SQLite. The other hints are provided for extentions that use
  14432. ** the SQLite parser and code generator but substitute their own storage
  14433. ** engine.
  14434. */
  14435. #define BTREE_HINT_RANGE 0 /* Range constraints on queries */
  14436. /*
  14437. ** Values that may be OR'd together to form the argument to the
  14438. ** BTREE_HINT_FLAGS hint for sqlite3BtreeCursorHint():
  14439. **
  14440. ** The BTREE_BULKLOAD flag is set on index cursors when the index is going
  14441. ** to be filled with content that is already in sorted order.
  14442. **
  14443. ** The BTREE_SEEK_EQ flag is set on cursors that will get OP_SeekGE or
  14444. ** OP_SeekLE opcodes for a range search, but where the range of entries
  14445. ** selected will all have the same key. In other words, the cursor will
  14446. ** be used only for equality key searches.
  14447. **
  14448. */
  14449. #define BTREE_BULKLOAD 0x00000001 /* Used to full index in sorted order */
  14450. #define BTREE_SEEK_EQ 0x00000002 /* EQ seeks only - no range seeks */
  14451. /*
  14452. ** Flags passed as the third argument to sqlite3BtreeCursor().
  14453. **
  14454. ** For read-only cursors the wrFlag argument is always zero. For read-write
  14455. ** cursors it may be set to either (BTREE_WRCSR|BTREE_FORDELETE) or just
  14456. ** (BTREE_WRCSR). If the BTREE_FORDELETE bit is set, then the cursor will
  14457. ** only be used by SQLite for the following:
  14458. **
  14459. ** * to seek to and then delete specific entries, and/or
  14460. **
  14461. ** * to read values that will be used to create keys that other
  14462. ** BTREE_FORDELETE cursors will seek to and delete.
  14463. **
  14464. ** The BTREE_FORDELETE flag is an optimization hint. It is not used by
  14465. ** by this, the native b-tree engine of SQLite, but it is available to
  14466. ** alternative storage engines that might be substituted in place of this
  14467. ** b-tree system. For alternative storage engines in which a delete of
  14468. ** the main table row automatically deletes corresponding index rows,
  14469. ** the FORDELETE flag hint allows those alternative storage engines to
  14470. ** skip a lot of work. Namely: FORDELETE cursors may treat all SEEK
  14471. ** and DELETE operations as no-ops, and any READ operation against a
  14472. ** FORDELETE cursor may return a null row: 0x01 0x00.
  14473. */
  14474. #define BTREE_WRCSR 0x00000004 /* read-write cursor */
  14475. #define BTREE_FORDELETE 0x00000008 /* Cursor is for seek/delete only */
  14476. SQLITE_PRIVATE int sqlite3BtreeCursor(
  14477. Btree*, /* BTree containing table to open */
  14478. int iTable, /* Index of root page */
  14479. int wrFlag, /* 1 for writing. 0 for read-only */
  14480. struct KeyInfo*, /* First argument to compare function */
  14481. BtCursor *pCursor /* Space to write cursor structure */
  14482. );
  14483. SQLITE_PRIVATE BtCursor *sqlite3BtreeFakeValidCursor(void);
  14484. SQLITE_PRIVATE int sqlite3BtreeCursorSize(void);
  14485. SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*);
  14486. SQLITE_PRIVATE void sqlite3BtreeCursorHintFlags(BtCursor*, unsigned);
  14487. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  14488. SQLITE_PRIVATE void sqlite3BtreeCursorHint(BtCursor*, int, ...);
  14489. #endif
  14490. SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
  14491. SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
  14492. BtCursor*,
  14493. UnpackedRecord *pUnKey,
  14494. i64 intKey,
  14495. int bias,
  14496. int *pRes
  14497. );
  14498. SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*);
  14499. SQLITE_PRIVATE int sqlite3BtreeCursorRestore(BtCursor*, int*);
  14500. SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*, u8 flags);
  14501. /* Allowed flags for sqlite3BtreeDelete() and sqlite3BtreeInsert() */
  14502. #define BTREE_SAVEPOSITION 0x02 /* Leave cursor pointing at NEXT or PREV */
  14503. #define BTREE_AUXDELETE 0x04 /* not the primary delete operation */
  14504. #define BTREE_APPEND 0x08 /* Insert is likely an append */
  14505. /* An instance of the BtreePayload object describes the content of a single
  14506. ** entry in either an index or table btree.
  14507. **
  14508. ** Index btrees (used for indexes and also WITHOUT ROWID tables) contain
  14509. ** an arbitrary key and no data. These btrees have pKey,nKey set to the
  14510. ** key and the pData,nData,nZero fields are uninitialized. The aMem,nMem
  14511. ** fields give an array of Mem objects that are a decomposition of the key.
  14512. ** The nMem field might be zero, indicating that no decomposition is available.
  14513. **
  14514. ** Table btrees (used for rowid tables) contain an integer rowid used as
  14515. ** the key and passed in the nKey field. The pKey field is zero.
  14516. ** pData,nData hold the content of the new entry. nZero extra zero bytes
  14517. ** are appended to the end of the content when constructing the entry.
  14518. ** The aMem,nMem fields are uninitialized for table btrees.
  14519. **
  14520. ** Field usage summary:
  14521. **
  14522. ** Table BTrees Index Btrees
  14523. **
  14524. ** pKey always NULL encoded key
  14525. ** nKey the ROWID length of pKey
  14526. ** pData data not used
  14527. ** aMem not used decomposed key value
  14528. ** nMem not used entries in aMem
  14529. ** nData length of pData not used
  14530. ** nZero extra zeros after pData not used
  14531. **
  14532. ** This object is used to pass information into sqlite3BtreeInsert(). The
  14533. ** same information used to be passed as five separate parameters. But placing
  14534. ** the information into this object helps to keep the interface more
  14535. ** organized and understandable, and it also helps the resulting code to
  14536. ** run a little faster by using fewer registers for parameter passing.
  14537. */
  14538. struct BtreePayload {
  14539. const void *pKey; /* Key content for indexes. NULL for tables */
  14540. sqlite3_int64 nKey; /* Size of pKey for indexes. PRIMARY KEY for tabs */
  14541. const void *pData; /* Data for tables. */
  14542. sqlite3_value *aMem; /* First of nMem value in the unpacked pKey */
  14543. u16 nMem; /* Number of aMem[] value. Might be zero */
  14544. int nData; /* Size of pData. 0 if none. */
  14545. int nZero; /* Extra zero data appended after pData,nData */
  14546. };
  14547. SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const BtreePayload *pPayload,
  14548. int flags, int seekResult);
  14549. SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
  14550. SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
  14551. SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int flags);
  14552. SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
  14553. SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int flags);
  14554. SQLITE_PRIVATE i64 sqlite3BtreeIntegerKey(BtCursor*);
  14555. SQLITE_PRIVATE void sqlite3BtreeCursorPin(BtCursor*);
  14556. SQLITE_PRIVATE void sqlite3BtreeCursorUnpin(BtCursor*);
  14557. #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
  14558. SQLITE_PRIVATE i64 sqlite3BtreeOffset(BtCursor*);
  14559. #endif
  14560. SQLITE_PRIVATE int sqlite3BtreePayload(BtCursor*, u32 offset, u32 amt, void*);
  14561. SQLITE_PRIVATE const void *sqlite3BtreePayloadFetch(BtCursor*, u32 *pAmt);
  14562. SQLITE_PRIVATE u32 sqlite3BtreePayloadSize(BtCursor*);
  14563. SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeMaxRecordSize(BtCursor*);
  14564. SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(sqlite3*,Btree*,int*aRoot,int nRoot,int,int*);
  14565. SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);
  14566. SQLITE_PRIVATE i64 sqlite3BtreeRowCountEst(BtCursor*);
  14567. #ifndef SQLITE_OMIT_INCRBLOB
  14568. SQLITE_PRIVATE int sqlite3BtreePayloadChecked(BtCursor*, u32 offset, u32 amt, void*);
  14569. SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
  14570. SQLITE_PRIVATE void sqlite3BtreeIncrblobCursor(BtCursor *);
  14571. #endif
  14572. SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *);
  14573. SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBt, int iVersion);
  14574. SQLITE_PRIVATE int sqlite3BtreeCursorHasHint(BtCursor*, unsigned int mask);
  14575. SQLITE_PRIVATE int sqlite3BtreeIsReadonly(Btree *pBt);
  14576. SQLITE_PRIVATE int sqlite3HeaderSizeBtree(void);
  14577. #ifndef NDEBUG
  14578. SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*);
  14579. #endif
  14580. SQLITE_PRIVATE int sqlite3BtreeCursorIsValidNN(BtCursor*);
  14581. SQLITE_PRIVATE int sqlite3BtreeCount(sqlite3*, BtCursor*, i64*);
  14582. #ifdef SQLITE_TEST
  14583. SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
  14584. SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
  14585. #endif
  14586. #ifndef SQLITE_OMIT_WAL
  14587. SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree*, int, int *, int *);
  14588. #endif
  14589. /*
  14590. ** If we are not using shared cache, then there is no need to
  14591. ** use mutexes to access the BtShared structures. So make the
  14592. ** Enter and Leave procedures no-ops.
  14593. */
  14594. #ifndef SQLITE_OMIT_SHARED_CACHE
  14595. SQLITE_PRIVATE void sqlite3BtreeEnter(Btree*);
  14596. SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3*);
  14597. SQLITE_PRIVATE int sqlite3BtreeSharable(Btree*);
  14598. SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor*);
  14599. SQLITE_PRIVATE int sqlite3BtreeConnectionCount(Btree*);
  14600. #else
  14601. # define sqlite3BtreeEnter(X)
  14602. # define sqlite3BtreeEnterAll(X)
  14603. # define sqlite3BtreeSharable(X) 0
  14604. # define sqlite3BtreeEnterCursor(X)
  14605. # define sqlite3BtreeConnectionCount(X) 1
  14606. #endif
  14607. #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
  14608. SQLITE_PRIVATE void sqlite3BtreeLeave(Btree*);
  14609. SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor*);
  14610. SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3*);
  14611. #ifndef NDEBUG
  14612. /* These routines are used inside assert() statements only. */
  14613. SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree*);
  14614. SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3*);
  14615. SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3*,int,Schema*);
  14616. #endif
  14617. #else
  14618. # define sqlite3BtreeLeave(X)
  14619. # define sqlite3BtreeLeaveCursor(X)
  14620. # define sqlite3BtreeLeaveAll(X)
  14621. # define sqlite3BtreeHoldsMutex(X) 1
  14622. # define sqlite3BtreeHoldsAllMutexes(X) 1
  14623. # define sqlite3SchemaMutexHeld(X,Y,Z) 1
  14624. #endif
  14625. #endif /* SQLITE_BTREE_H */
  14626. /************** End of btree.h ***********************************************/
  14627. /************** Continuing where we left off in sqliteInt.h ******************/
  14628. /************** Include vdbe.h in the middle of sqliteInt.h ******************/
  14629. /************** Begin file vdbe.h ********************************************/
  14630. /*
  14631. ** 2001 September 15
  14632. **
  14633. ** The author disclaims copyright to this source code. In place of
  14634. ** a legal notice, here is a blessing:
  14635. **
  14636. ** May you do good and not evil.
  14637. ** May you find forgiveness for yourself and forgive others.
  14638. ** May you share freely, never taking more than you give.
  14639. **
  14640. *************************************************************************
  14641. ** Header file for the Virtual DataBase Engine (VDBE)
  14642. **
  14643. ** This header defines the interface to the virtual database engine
  14644. ** or VDBE. The VDBE implements an abstract machine that runs a
  14645. ** simple program to access and modify the underlying database.
  14646. */
  14647. #ifndef SQLITE_VDBE_H
  14648. #define SQLITE_VDBE_H
  14649. /* #include <stdio.h> */
  14650. /*
  14651. ** A single VDBE is an opaque structure named "Vdbe". Only routines
  14652. ** in the source file sqliteVdbe.c are allowed to see the insides
  14653. ** of this structure.
  14654. */
  14655. typedef struct Vdbe Vdbe;
  14656. /*
  14657. ** The names of the following types declared in vdbeInt.h are required
  14658. ** for the VdbeOp definition.
  14659. */
  14660. typedef struct sqlite3_value Mem;
  14661. typedef struct SubProgram SubProgram;
  14662. /*
  14663. ** A single instruction of the virtual machine has an opcode
  14664. ** and as many as three operands. The instruction is recorded
  14665. ** as an instance of the following structure:
  14666. */
  14667. struct VdbeOp {
  14668. u8 opcode; /* What operation to perform */
  14669. signed char p4type; /* One of the P4_xxx constants for p4 */
  14670. u16 p5; /* Fifth parameter is an unsigned 16-bit integer */
  14671. int p1; /* First operand */
  14672. int p2; /* Second parameter (often the jump destination) */
  14673. int p3; /* The third parameter */
  14674. union p4union { /* fourth parameter */
  14675. int i; /* Integer value if p4type==P4_INT32 */
  14676. void *p; /* Generic pointer */
  14677. char *z; /* Pointer to data for string (char array) types */
  14678. i64 *pI64; /* Used when p4type is P4_INT64 */
  14679. double *pReal; /* Used when p4type is P4_REAL */
  14680. FuncDef *pFunc; /* Used when p4type is P4_FUNCDEF */
  14681. sqlite3_context *pCtx; /* Used when p4type is P4_FUNCCTX */
  14682. CollSeq *pColl; /* Used when p4type is P4_COLLSEQ */
  14683. Mem *pMem; /* Used when p4type is P4_MEM */
  14684. VTable *pVtab; /* Used when p4type is P4_VTAB */
  14685. KeyInfo *pKeyInfo; /* Used when p4type is P4_KEYINFO */
  14686. int *ai; /* Used when p4type is P4_INTARRAY */
  14687. SubProgram *pProgram; /* Used when p4type is P4_SUBPROGRAM */
  14688. Table *pTab; /* Used when p4type is P4_TABLE */
  14689. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  14690. Expr *pExpr; /* Used when p4type is P4_EXPR */
  14691. #endif
  14692. int (*xAdvance)(BtCursor *, int);
  14693. } p4;
  14694. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  14695. char *zComment; /* Comment to improve readability */
  14696. #endif
  14697. #ifdef VDBE_PROFILE
  14698. u32 cnt; /* Number of times this instruction was executed */
  14699. u64 cycles; /* Total time spent executing this instruction */
  14700. #endif
  14701. #ifdef SQLITE_VDBE_COVERAGE
  14702. u32 iSrcLine; /* Source-code line that generated this opcode
  14703. ** with flags in the upper 8 bits */
  14704. #endif
  14705. };
  14706. typedef struct VdbeOp VdbeOp;
  14707. /*
  14708. ** A sub-routine used to implement a trigger program.
  14709. */
  14710. struct SubProgram {
  14711. VdbeOp *aOp; /* Array of opcodes for sub-program */
  14712. int nOp; /* Elements in aOp[] */
  14713. int nMem; /* Number of memory cells required */
  14714. int nCsr; /* Number of cursors required */
  14715. u8 *aOnce; /* Array of OP_Once flags */
  14716. void *token; /* id that may be used to recursive triggers */
  14717. SubProgram *pNext; /* Next sub-program already visited */
  14718. };
  14719. /*
  14720. ** A smaller version of VdbeOp used for the VdbeAddOpList() function because
  14721. ** it takes up less space.
  14722. */
  14723. struct VdbeOpList {
  14724. u8 opcode; /* What operation to perform */
  14725. signed char p1; /* First operand */
  14726. signed char p2; /* Second parameter (often the jump destination) */
  14727. signed char p3; /* Third parameter */
  14728. };
  14729. typedef struct VdbeOpList VdbeOpList;
  14730. /*
  14731. ** Allowed values of VdbeOp.p4type
  14732. */
  14733. #define P4_NOTUSED 0 /* The P4 parameter is not used */
  14734. #define P4_TRANSIENT 0 /* P4 is a pointer to a transient string */
  14735. #define P4_STATIC (-1) /* Pointer to a static string */
  14736. #define P4_COLLSEQ (-2) /* P4 is a pointer to a CollSeq structure */
  14737. #define P4_INT32 (-3) /* P4 is a 32-bit signed integer */
  14738. #define P4_SUBPROGRAM (-4) /* P4 is a pointer to a SubProgram structure */
  14739. #define P4_ADVANCE (-5) /* P4 is a pointer to BtreeNext() or BtreePrev() */
  14740. #define P4_TABLE (-6) /* P4 is a pointer to a Table structure */
  14741. /* Above do not own any resources. Must free those below */
  14742. #define P4_FREE_IF_LE (-7)
  14743. #define P4_DYNAMIC (-7) /* Pointer to memory from sqliteMalloc() */
  14744. #define P4_FUNCDEF (-8) /* P4 is a pointer to a FuncDef structure */
  14745. #define P4_KEYINFO (-9) /* P4 is a pointer to a KeyInfo structure */
  14746. #define P4_EXPR (-10) /* P4 is a pointer to an Expr tree */
  14747. #define P4_MEM (-11) /* P4 is a pointer to a Mem* structure */
  14748. #define P4_VTAB (-12) /* P4 is a pointer to an sqlite3_vtab structure */
  14749. #define P4_REAL (-13) /* P4 is a 64-bit floating point value */
  14750. #define P4_INT64 (-14) /* P4 is a 64-bit signed integer */
  14751. #define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */
  14752. #define P4_FUNCCTX (-16) /* P4 is a pointer to an sqlite3_context object */
  14753. #define P4_DYNBLOB (-17) /* Pointer to memory from sqliteMalloc() */
  14754. /* Error message codes for OP_Halt */
  14755. #define P5_ConstraintNotNull 1
  14756. #define P5_ConstraintUnique 2
  14757. #define P5_ConstraintCheck 3
  14758. #define P5_ConstraintFK 4
  14759. /*
  14760. ** The Vdbe.aColName array contains 5n Mem structures, where n is the
  14761. ** number of columns of data returned by the statement.
  14762. */
  14763. #define COLNAME_NAME 0
  14764. #define COLNAME_DECLTYPE 1
  14765. #define COLNAME_DATABASE 2
  14766. #define COLNAME_TABLE 3
  14767. #define COLNAME_COLUMN 4
  14768. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  14769. # define COLNAME_N 5 /* Number of COLNAME_xxx symbols */
  14770. #else
  14771. # ifdef SQLITE_OMIT_DECLTYPE
  14772. # define COLNAME_N 1 /* Store only the name */
  14773. # else
  14774. # define COLNAME_N 2 /* Store the name and decltype */
  14775. # endif
  14776. #endif
  14777. /*
  14778. ** The following macro converts a label returned by sqlite3VdbeMakeLabel()
  14779. ** into an index into the Parse.aLabel[] array that contains the resolved
  14780. ** address of that label.
  14781. */
  14782. #define ADDR(X) (~(X))
  14783. /*
  14784. ** The makefile scans the vdbe.c source file and creates the "opcodes.h"
  14785. ** header file that defines a number for each opcode used by the VDBE.
  14786. */
  14787. /************** Include opcodes.h in the middle of vdbe.h ********************/
  14788. /************** Begin file opcodes.h *****************************************/
  14789. /* Automatically generated. Do not edit */
  14790. /* See the tool/mkopcodeh.tcl script for details */
  14791. #define OP_Savepoint 0
  14792. #define OP_AutoCommit 1
  14793. #define OP_Transaction 2
  14794. #define OP_SorterNext 3 /* jump */
  14795. #define OP_Prev 4 /* jump */
  14796. #define OP_Next 5 /* jump */
  14797. #define OP_Checkpoint 6
  14798. #define OP_JournalMode 7
  14799. #define OP_Vacuum 8
  14800. #define OP_VFilter 9 /* jump, synopsis: iplan=r[P3] zplan='P4' */
  14801. #define OP_VUpdate 10 /* synopsis: data=r[P3@P2] */
  14802. #define OP_Goto 11 /* jump */
  14803. #define OP_Gosub 12 /* jump */
  14804. #define OP_InitCoroutine 13 /* jump */
  14805. #define OP_Yield 14 /* jump */
  14806. #define OP_MustBeInt 15 /* jump */
  14807. #define OP_Jump 16 /* jump */
  14808. #define OP_Once 17 /* jump */
  14809. #define OP_If 18 /* jump */
  14810. #define OP_Not 19 /* same as TK_NOT, synopsis: r[P2]= !r[P1] */
  14811. #define OP_IfNot 20 /* jump */
  14812. #define OP_IfNullRow 21 /* jump, synopsis: if P1.nullRow then r[P3]=NULL, goto P2 */
  14813. #define OP_SeekLT 22 /* jump, synopsis: key=r[P3@P4] */
  14814. #define OP_SeekLE 23 /* jump, synopsis: key=r[P3@P4] */
  14815. #define OP_SeekGE 24 /* jump, synopsis: key=r[P3@P4] */
  14816. #define OP_SeekGT 25 /* jump, synopsis: key=r[P3@P4] */
  14817. #define OP_IfNotOpen 26 /* jump, synopsis: if( !csr[P1] ) goto P2 */
  14818. #define OP_IfNoHope 27 /* jump, synopsis: key=r[P3@P4] */
  14819. #define OP_NoConflict 28 /* jump, synopsis: key=r[P3@P4] */
  14820. #define OP_NotFound 29 /* jump, synopsis: key=r[P3@P4] */
  14821. #define OP_Found 30 /* jump, synopsis: key=r[P3@P4] */
  14822. #define OP_SeekRowid 31 /* jump, synopsis: intkey=r[P3] */
  14823. #define OP_NotExists 32 /* jump, synopsis: intkey=r[P3] */
  14824. #define OP_Last 33 /* jump */
  14825. #define OP_IfSmaller 34 /* jump */
  14826. #define OP_SorterSort 35 /* jump */
  14827. #define OP_Sort 36 /* jump */
  14828. #define OP_Rewind 37 /* jump */
  14829. #define OP_IdxLE 38 /* jump, synopsis: key=r[P3@P4] */
  14830. #define OP_IdxGT 39 /* jump, synopsis: key=r[P3@P4] */
  14831. #define OP_IdxLT 40 /* jump, synopsis: key=r[P3@P4] */
  14832. #define OP_IdxGE 41 /* jump, synopsis: key=r[P3@P4] */
  14833. #define OP_RowSetRead 42 /* jump, synopsis: r[P3]=rowset(P1) */
  14834. #define OP_Or 43 /* same as TK_OR, synopsis: r[P3]=(r[P1] || r[P2]) */
  14835. #define OP_And 44 /* same as TK_AND, synopsis: r[P3]=(r[P1] && r[P2]) */
  14836. #define OP_RowSetTest 45 /* jump, synopsis: if r[P3] in rowset(P1) goto P2 */
  14837. #define OP_Program 46 /* jump */
  14838. #define OP_FkIfZero 47 /* jump, synopsis: if fkctr[P1]==0 goto P2 */
  14839. #define OP_IfPos 48 /* jump, synopsis: if r[P1]>0 then r[P1]-=P3, goto P2 */
  14840. #define OP_IfNotZero 49 /* jump, synopsis: if r[P1]!=0 then r[P1]--, goto P2 */
  14841. #define OP_IsNull 50 /* jump, same as TK_ISNULL, synopsis: if r[P1]==NULL goto P2 */
  14842. #define OP_NotNull 51 /* jump, same as TK_NOTNULL, synopsis: if r[P1]!=NULL goto P2 */
  14843. #define OP_Ne 52 /* jump, same as TK_NE, synopsis: IF r[P3]!=r[P1] */
  14844. #define OP_Eq 53 /* jump, same as TK_EQ, synopsis: IF r[P3]==r[P1] */
  14845. #define OP_Gt 54 /* jump, same as TK_GT, synopsis: IF r[P3]>r[P1] */
  14846. #define OP_Le 55 /* jump, same as TK_LE, synopsis: IF r[P3]<=r[P1] */
  14847. #define OP_Lt 56 /* jump, same as TK_LT, synopsis: IF r[P3]<r[P1] */
  14848. #define OP_Ge 57 /* jump, same as TK_GE, synopsis: IF r[P3]>=r[P1] */
  14849. #define OP_ElseNotEq 58 /* jump, same as TK_ESCAPE */
  14850. #define OP_DecrJumpZero 59 /* jump, synopsis: if (--r[P1])==0 goto P2 */
  14851. #define OP_IncrVacuum 60 /* jump */
  14852. #define OP_VNext 61 /* jump */
  14853. #define OP_Init 62 /* jump, synopsis: Start at P2 */
  14854. #define OP_PureFunc 63 /* synopsis: r[P3]=func(r[P2@NP]) */
  14855. #define OP_Function 64 /* synopsis: r[P3]=func(r[P2@NP]) */
  14856. #define OP_Return 65
  14857. #define OP_EndCoroutine 66
  14858. #define OP_HaltIfNull 67 /* synopsis: if r[P3]=null halt */
  14859. #define OP_Halt 68
  14860. #define OP_Integer 69 /* synopsis: r[P2]=P1 */
  14861. #define OP_Int64 70 /* synopsis: r[P2]=P4 */
  14862. #define OP_String 71 /* synopsis: r[P2]='P4' (len=P1) */
  14863. #define OP_Null 72 /* synopsis: r[P2..P3]=NULL */
  14864. #define OP_SoftNull 73 /* synopsis: r[P1]=NULL */
  14865. #define OP_Blob 74 /* synopsis: r[P2]=P4 (len=P1) */
  14866. #define OP_Variable 75 /* synopsis: r[P2]=parameter(P1,P4) */
  14867. #define OP_Move 76 /* synopsis: r[P2@P3]=r[P1@P3] */
  14868. #define OP_Copy 77 /* synopsis: r[P2@P3+1]=r[P1@P3+1] */
  14869. #define OP_SCopy 78 /* synopsis: r[P2]=r[P1] */
  14870. #define OP_IntCopy 79 /* synopsis: r[P2]=r[P1] */
  14871. #define OP_ResultRow 80 /* synopsis: output=r[P1@P2] */
  14872. #define OP_CollSeq 81
  14873. #define OP_AddImm 82 /* synopsis: r[P1]=r[P1]+P2 */
  14874. #define OP_RealAffinity 83
  14875. #define OP_Cast 84 /* synopsis: affinity(r[P1]) */
  14876. #define OP_Permutation 85
  14877. #define OP_Compare 86 /* synopsis: r[P1@P3] <-> r[P2@P3] */
  14878. #define OP_IsTrue 87 /* synopsis: r[P2] = coalesce(r[P1]==TRUE,P3) ^ P4 */
  14879. #define OP_Offset 88 /* synopsis: r[P3] = sqlite_offset(P1) */
  14880. #define OP_Column 89 /* synopsis: r[P3]=PX */
  14881. #define OP_Affinity 90 /* synopsis: affinity(r[P1@P2]) */
  14882. #define OP_MakeRecord 91 /* synopsis: r[P3]=mkrec(r[P1@P2]) */
  14883. #define OP_Count 92 /* synopsis: r[P2]=count() */
  14884. #define OP_ReadCookie 93
  14885. #define OP_SetCookie 94
  14886. #define OP_ReopenIdx 95 /* synopsis: root=P2 iDb=P3 */
  14887. #define OP_OpenRead 96 /* synopsis: root=P2 iDb=P3 */
  14888. #define OP_OpenWrite 97 /* synopsis: root=P2 iDb=P3 */
  14889. #define OP_OpenDup 98
  14890. #define OP_OpenAutoindex 99 /* synopsis: nColumn=P2 */
  14891. #define OP_OpenEphemeral 100 /* synopsis: nColumn=P2 */
  14892. #define OP_BitAnd 101 /* same as TK_BITAND, synopsis: r[P3]=r[P1]&r[P2] */
  14893. #define OP_BitOr 102 /* same as TK_BITOR, synopsis: r[P3]=r[P1]|r[P2] */
  14894. #define OP_ShiftLeft 103 /* same as TK_LSHIFT, synopsis: r[P3]=r[P2]<<r[P1] */
  14895. #define OP_ShiftRight 104 /* same as TK_RSHIFT, synopsis: r[P3]=r[P2]>>r[P1] */
  14896. #define OP_Add 105 /* same as TK_PLUS, synopsis: r[P3]=r[P1]+r[P2] */
  14897. #define OP_Subtract 106 /* same as TK_MINUS, synopsis: r[P3]=r[P2]-r[P1] */
  14898. #define OP_Multiply 107 /* same as TK_STAR, synopsis: r[P3]=r[P1]*r[P2] */
  14899. #define OP_Divide 108 /* same as TK_SLASH, synopsis: r[P3]=r[P2]/r[P1] */
  14900. #define OP_Remainder 109 /* same as TK_REM, synopsis: r[P3]=r[P2]%r[P1] */
  14901. #define OP_Concat 110 /* same as TK_CONCAT, synopsis: r[P3]=r[P2]+r[P1] */
  14902. #define OP_SorterOpen 111
  14903. #define OP_BitNot 112 /* same as TK_BITNOT, synopsis: r[P2]= ~r[P1] */
  14904. #define OP_SequenceTest 113 /* synopsis: if( cursor[P1].ctr++ ) pc = P2 */
  14905. #define OP_OpenPseudo 114 /* synopsis: P3 columns in r[P2] */
  14906. #define OP_String8 115 /* same as TK_STRING, synopsis: r[P2]='P4' */
  14907. #define OP_Close 116
  14908. #define OP_ColumnsUsed 117
  14909. #define OP_SeekHit 118 /* synopsis: seekHit=P2 */
  14910. #define OP_Sequence 119 /* synopsis: r[P2]=cursor[P1].ctr++ */
  14911. #define OP_NewRowid 120 /* synopsis: r[P2]=rowid */
  14912. #define OP_Insert 121 /* synopsis: intkey=r[P3] data=r[P2] */
  14913. #define OP_Delete 122
  14914. #define OP_ResetCount 123
  14915. #define OP_SorterCompare 124 /* synopsis: if key(P1)!=trim(r[P3],P4) goto P2 */
  14916. #define OP_SorterData 125 /* synopsis: r[P2]=data */
  14917. #define OP_RowData 126 /* synopsis: r[P2]=data */
  14918. #define OP_Rowid 127 /* synopsis: r[P2]=rowid */
  14919. #define OP_NullRow 128
  14920. #define OP_SeekEnd 129
  14921. #define OP_IdxInsert 130 /* synopsis: key=r[P2] */
  14922. #define OP_SorterInsert 131 /* synopsis: key=r[P2] */
  14923. #define OP_IdxDelete 132 /* synopsis: key=r[P2@P3] */
  14924. #define OP_DeferredSeek 133 /* synopsis: Move P3 to P1.rowid if needed */
  14925. #define OP_IdxRowid 134 /* synopsis: r[P2]=rowid */
  14926. #define OP_FinishSeek 135
  14927. #define OP_Destroy 136
  14928. #define OP_Clear 137
  14929. #define OP_ResetSorter 138
  14930. #define OP_CreateBtree 139 /* synopsis: r[P2]=root iDb=P1 flags=P3 */
  14931. #define OP_SqlExec 140
  14932. #define OP_ParseSchema 141
  14933. #define OP_LoadAnalysis 142
  14934. #define OP_DropTable 143
  14935. #define OP_DropIndex 144
  14936. #define OP_DropTrigger 145
  14937. #define OP_IntegrityCk 146
  14938. #define OP_RowSetAdd 147 /* synopsis: rowset(P1)=r[P2] */
  14939. #define OP_Param 148
  14940. #define OP_FkCounter 149 /* synopsis: fkctr[P1]+=P2 */
  14941. #define OP_Real 150 /* same as TK_FLOAT, synopsis: r[P2]=P4 */
  14942. #define OP_MemMax 151 /* synopsis: r[P1]=max(r[P1],r[P2]) */
  14943. #define OP_OffsetLimit 152 /* synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1) */
  14944. #define OP_AggInverse 153 /* synopsis: accum=r[P3] inverse(r[P2@P5]) */
  14945. #define OP_AggStep 154 /* synopsis: accum=r[P3] step(r[P2@P5]) */
  14946. #define OP_AggStep1 155 /* synopsis: accum=r[P3] step(r[P2@P5]) */
  14947. #define OP_AggValue 156 /* synopsis: r[P3]=value N=P2 */
  14948. #define OP_AggFinal 157 /* synopsis: accum=r[P1] N=P2 */
  14949. #define OP_Expire 158
  14950. #define OP_CursorLock 159
  14951. #define OP_CursorUnlock 160
  14952. #define OP_TableLock 161 /* synopsis: iDb=P1 root=P2 write=P3 */
  14953. #define OP_VBegin 162
  14954. #define OP_VCreate 163
  14955. #define OP_VDestroy 164
  14956. #define OP_VOpen 165
  14957. #define OP_VColumn 166 /* synopsis: r[P3]=vcolumn(P2) */
  14958. #define OP_VRename 167
  14959. #define OP_Pagecount 168
  14960. #define OP_MaxPgcnt 169
  14961. #define OP_Trace 170
  14962. #define OP_CursorHint 171
  14963. #define OP_ReleaseReg 172 /* synopsis: release r[P1@P2] mask P3 */
  14964. #define OP_Noop 173
  14965. #define OP_Explain 174
  14966. #define OP_Abortable 175
  14967. /* Properties such as "out2" or "jump" that are specified in
  14968. ** comments following the "case" for each opcode in the vdbe.c
  14969. ** are encoded into bitvectors as follows:
  14970. */
  14971. #define OPFLG_JUMP 0x01 /* jump: P2 holds jmp target */
  14972. #define OPFLG_IN1 0x02 /* in1: P1 is an input */
  14973. #define OPFLG_IN2 0x04 /* in2: P2 is an input */
  14974. #define OPFLG_IN3 0x08 /* in3: P3 is an input */
  14975. #define OPFLG_OUT2 0x10 /* out2: P2 is an output */
  14976. #define OPFLG_OUT3 0x20 /* out3: P3 is an output */
  14977. #define OPFLG_INITIALIZER {\
  14978. /* 0 */ 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x00, 0x10,\
  14979. /* 8 */ 0x00, 0x01, 0x00, 0x01, 0x01, 0x01, 0x03, 0x03,\
  14980. /* 16 */ 0x01, 0x01, 0x03, 0x12, 0x03, 0x01, 0x09, 0x09,\
  14981. /* 24 */ 0x09, 0x09, 0x01, 0x09, 0x09, 0x09, 0x09, 0x09,\
  14982. /* 32 */ 0x09, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,\
  14983. /* 40 */ 0x01, 0x01, 0x23, 0x26, 0x26, 0x0b, 0x01, 0x01,\
  14984. /* 48 */ 0x03, 0x03, 0x03, 0x03, 0x0b, 0x0b, 0x0b, 0x0b,\
  14985. /* 56 */ 0x0b, 0x0b, 0x01, 0x03, 0x01, 0x01, 0x01, 0x00,\
  14986. /* 64 */ 0x00, 0x02, 0x02, 0x08, 0x00, 0x10, 0x10, 0x10,\
  14987. /* 72 */ 0x10, 0x00, 0x10, 0x10, 0x00, 0x00, 0x10, 0x10,\
  14988. /* 80 */ 0x00, 0x00, 0x02, 0x02, 0x02, 0x00, 0x00, 0x12,\
  14989. /* 88 */ 0x20, 0x00, 0x00, 0x00, 0x10, 0x10, 0x00, 0x00,\
  14990. /* 96 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x26, 0x26, 0x26,\
  14991. /* 104 */ 0x26, 0x26, 0x26, 0x26, 0x26, 0x26, 0x26, 0x00,\
  14992. /* 112 */ 0x12, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x10,\
  14993. /* 120 */ 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10,\
  14994. /* 128 */ 0x00, 0x00, 0x04, 0x04, 0x00, 0x00, 0x10, 0x00,\
  14995. /* 136 */ 0x10, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00,\
  14996. /* 144 */ 0x00, 0x00, 0x00, 0x06, 0x10, 0x00, 0x10, 0x04,\
  14997. /* 152 */ 0x1a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
  14998. /* 160 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
  14999. /* 168 */ 0x10, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
  15000. }
  15001. /* The sqlite3P2Values() routine is able to run faster if it knows
  15002. ** the value of the largest JUMP opcode. The smaller the maximum
  15003. ** JUMP opcode the better, so the mkopcodeh.tcl script that
  15004. ** generated this include file strives to group all JUMP opcodes
  15005. ** together near the beginning of the list.
  15006. */
  15007. #define SQLITE_MX_JUMP_OPCODE 62 /* Maximum JUMP opcode */
  15008. /************** End of opcodes.h *********************************************/
  15009. /************** Continuing where we left off in vdbe.h ***********************/
  15010. /*
  15011. ** Additional non-public SQLITE_PREPARE_* flags
  15012. */
  15013. #define SQLITE_PREPARE_SAVESQL 0x80 /* Preserve SQL text */
  15014. #define SQLITE_PREPARE_MASK 0x0f /* Mask of public flags */
  15015. /*
  15016. ** Prototypes for the VDBE interface. See comments on the implementation
  15017. ** for a description of what each of these routines does.
  15018. */
  15019. SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(Parse*);
  15020. SQLITE_PRIVATE Parse *sqlite3VdbeParser(Vdbe*);
  15021. SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int);
  15022. SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);
  15023. SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
  15024. SQLITE_PRIVATE int sqlite3VdbeGoto(Vdbe*,int);
  15025. SQLITE_PRIVATE int sqlite3VdbeLoadString(Vdbe*,int,const char*);
  15026. SQLITE_PRIVATE void sqlite3VdbeMultiLoad(Vdbe*,int,const char*,...);
  15027. SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
  15028. SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
  15029. SQLITE_PRIVATE int sqlite3VdbeAddOp4Dup8(Vdbe*,int,int,int,int,const u8*,int);
  15030. SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int);
  15031. SQLITE_PRIVATE int sqlite3VdbeAddFunctionCall(Parse*,int,int,int,int,const FuncDef*,int);
  15032. SQLITE_PRIVATE void sqlite3VdbeEndCoroutine(Vdbe*,int);
  15033. #if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS)
  15034. SQLITE_PRIVATE void sqlite3VdbeVerifyNoMallocRequired(Vdbe *p, int N);
  15035. SQLITE_PRIVATE void sqlite3VdbeVerifyNoResultRow(Vdbe *p);
  15036. #else
  15037. # define sqlite3VdbeVerifyNoMallocRequired(A,B)
  15038. # define sqlite3VdbeVerifyNoResultRow(A)
  15039. #endif
  15040. #if defined(SQLITE_DEBUG)
  15041. SQLITE_PRIVATE void sqlite3VdbeVerifyAbortable(Vdbe *p, int);
  15042. #else
  15043. # define sqlite3VdbeVerifyAbortable(A,B)
  15044. #endif
  15045. SQLITE_PRIVATE VdbeOp *sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp,int iLineno);
  15046. #ifndef SQLITE_OMIT_EXPLAIN
  15047. SQLITE_PRIVATE void sqlite3VdbeExplain(Parse*,u8,const char*,...);
  15048. SQLITE_PRIVATE void sqlite3VdbeExplainPop(Parse*);
  15049. SQLITE_PRIVATE int sqlite3VdbeExplainParent(Parse*);
  15050. # define ExplainQueryPlan(P) sqlite3VdbeExplain P
  15051. # define ExplainQueryPlanPop(P) sqlite3VdbeExplainPop(P)
  15052. # define ExplainQueryPlanParent(P) sqlite3VdbeExplainParent(P)
  15053. #else
  15054. # define ExplainQueryPlan(P)
  15055. # define ExplainQueryPlanPop(P)
  15056. # define ExplainQueryPlanParent(P) 0
  15057. # define sqlite3ExplainBreakpoint(A,B) /*no-op*/
  15058. #endif
  15059. #if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_EXPLAIN)
  15060. SQLITE_PRIVATE void sqlite3ExplainBreakpoint(const char*,const char*);
  15061. #else
  15062. # define sqlite3ExplainBreakpoint(A,B) /*no-op*/
  15063. #endif
  15064. SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe*,int,char*);
  15065. SQLITE_PRIVATE void sqlite3VdbeChangeOpcode(Vdbe*, int addr, u8);
  15066. SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, int addr, int P1);
  15067. SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, int addr, int P2);
  15068. SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, int addr, int P3);
  15069. SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u16 P5);
  15070. SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
  15071. SQLITE_PRIVATE void sqlite3VdbeJumpHereOrPopInst(Vdbe*, int addr);
  15072. SQLITE_PRIVATE int sqlite3VdbeChangeToNoop(Vdbe*, int addr);
  15073. SQLITE_PRIVATE int sqlite3VdbeDeletePriorOpcode(Vdbe*, u8 op);
  15074. #ifdef SQLITE_DEBUG
  15075. SQLITE_PRIVATE void sqlite3VdbeReleaseRegisters(Parse*,int addr, int n, u32 mask, int);
  15076. #else
  15077. # define sqlite3VdbeReleaseRegisters(P,A,N,M,F)
  15078. #endif
  15079. SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
  15080. SQLITE_PRIVATE void sqlite3VdbeAppendP4(Vdbe*, void *pP4, int p4type);
  15081. SQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse*, Index*);
  15082. SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);
  15083. SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
  15084. SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Parse*);
  15085. SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe*);
  15086. SQLITE_PRIVATE void sqlite3VdbeReusable(Vdbe*);
  15087. SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
  15088. SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3*,Vdbe*);
  15089. SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,Parse*);
  15090. SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
  15091. SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
  15092. SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);
  15093. #ifdef SQLITE_DEBUG
  15094. SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *, int);
  15095. #endif
  15096. SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);
  15097. SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe*);
  15098. SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*);
  15099. SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);
  15100. SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));
  15101. SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);
  15102. SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);
  15103. SQLITE_PRIVATE u8 sqlite3VdbePrepareFlags(Vdbe*);
  15104. SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, u8);
  15105. #ifdef SQLITE_ENABLE_NORMALIZE
  15106. SQLITE_PRIVATE void sqlite3VdbeAddDblquoteStr(sqlite3*,Vdbe*,const char*);
  15107. SQLITE_PRIVATE int sqlite3VdbeUsesDoubleQuotedString(Vdbe*,const char*);
  15108. #endif
  15109. SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);
  15110. SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*);
  15111. SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe*, int, u8);
  15112. SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int);
  15113. #ifndef SQLITE_OMIT_TRACE
  15114. SQLITE_PRIVATE char *sqlite3VdbeExpandSql(Vdbe*, const char*);
  15115. #endif
  15116. SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
  15117. SQLITE_PRIVATE int sqlite3BlobCompare(const Mem*, const Mem*);
  15118. SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,UnpackedRecord*);
  15119. SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);
  15120. SQLITE_PRIVATE int sqlite3VdbeRecordCompareWithSkip(int, const void *, UnpackedRecord *, int);
  15121. SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(KeyInfo*);
  15122. typedef int (*RecordCompare)(int,const void*,UnpackedRecord*);
  15123. SQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord*);
  15124. SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram *);
  15125. SQLITE_PRIVATE int sqlite3VdbeHasSubProgram(Vdbe*);
  15126. SQLITE_PRIVATE int sqlite3NotPureFunc(sqlite3_context*);
  15127. #ifdef SQLITE_ENABLE_BYTECODE_VTAB
  15128. SQLITE_PRIVATE int sqlite3VdbeBytecodeVtabInit(sqlite3*);
  15129. #endif
  15130. /* Use SQLITE_ENABLE_COMMENTS to enable generation of extra comments on
  15131. ** each VDBE opcode.
  15132. **
  15133. ** Use the SQLITE_ENABLE_MODULE_COMMENTS macro to see some extra no-op
  15134. ** comments in VDBE programs that show key decision points in the code
  15135. ** generator.
  15136. */
  15137. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  15138. SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe*, const char*, ...);
  15139. # define VdbeComment(X) sqlite3VdbeComment X
  15140. SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
  15141. # define VdbeNoopComment(X) sqlite3VdbeNoopComment X
  15142. # ifdef SQLITE_ENABLE_MODULE_COMMENTS
  15143. # define VdbeModuleComment(X) sqlite3VdbeNoopComment X
  15144. # else
  15145. # define VdbeModuleComment(X)
  15146. # endif
  15147. #else
  15148. # define VdbeComment(X)
  15149. # define VdbeNoopComment(X)
  15150. # define VdbeModuleComment(X)
  15151. #endif
  15152. /*
  15153. ** The VdbeCoverage macros are used to set a coverage testing point
  15154. ** for VDBE branch instructions. The coverage testing points are line
  15155. ** numbers in the sqlite3.c source file. VDBE branch coverage testing
  15156. ** only works with an amalagmation build. That's ok since a VDBE branch
  15157. ** coverage build designed for testing the test suite only. No application
  15158. ** should ever ship with VDBE branch coverage measuring turned on.
  15159. **
  15160. ** VdbeCoverage(v) // Mark the previously coded instruction
  15161. ** // as a branch
  15162. **
  15163. ** VdbeCoverageIf(v, conditional) // Mark previous if conditional true
  15164. **
  15165. ** VdbeCoverageAlwaysTaken(v) // Previous branch is always taken
  15166. **
  15167. ** VdbeCoverageNeverTaken(v) // Previous branch is never taken
  15168. **
  15169. ** VdbeCoverageNeverNull(v) // Previous three-way branch is only
  15170. ** // taken on the first two ways. The
  15171. ** // NULL option is not possible
  15172. **
  15173. ** VdbeCoverageEqNe(v) // Previous OP_Jump is only interested
  15174. ** // in distingishing equal and not-equal.
  15175. **
  15176. ** Every VDBE branch operation must be tagged with one of the macros above.
  15177. ** If not, then when "make test" is run with -DSQLITE_VDBE_COVERAGE and
  15178. ** -DSQLITE_DEBUG then an ALWAYS() will fail in the vdbeTakeBranch()
  15179. ** routine in vdbe.c, alerting the developer to the missed tag.
  15180. **
  15181. ** During testing, the test application will invoke
  15182. ** sqlite3_test_control(SQLITE_TESTCTRL_VDBE_COVERAGE,...) to set a callback
  15183. ** routine that is invoked as each bytecode branch is taken. The callback
  15184. ** contains the sqlite3.c source line number ov the VdbeCoverage macro and
  15185. ** flags to indicate whether or not the branch was taken. The test application
  15186. ** is responsible for keeping track of this and reporting byte-code branches
  15187. ** that are never taken.
  15188. **
  15189. ** See the VdbeBranchTaken() macro and vdbeTakeBranch() function in the
  15190. ** vdbe.c source file for additional information.
  15191. */
  15192. #ifdef SQLITE_VDBE_COVERAGE
  15193. SQLITE_PRIVATE void sqlite3VdbeSetLineNumber(Vdbe*,int);
  15194. # define VdbeCoverage(v) sqlite3VdbeSetLineNumber(v,__LINE__)
  15195. # define VdbeCoverageIf(v,x) if(x)sqlite3VdbeSetLineNumber(v,__LINE__)
  15196. # define VdbeCoverageAlwaysTaken(v) \
  15197. sqlite3VdbeSetLineNumber(v,__LINE__|0x5000000);
  15198. # define VdbeCoverageNeverTaken(v) \
  15199. sqlite3VdbeSetLineNumber(v,__LINE__|0x6000000);
  15200. # define VdbeCoverageNeverNull(v) \
  15201. sqlite3VdbeSetLineNumber(v,__LINE__|0x4000000);
  15202. # define VdbeCoverageNeverNullIf(v,x) \
  15203. if(x)sqlite3VdbeSetLineNumber(v,__LINE__|0x4000000);
  15204. # define VdbeCoverageEqNe(v) \
  15205. sqlite3VdbeSetLineNumber(v,__LINE__|0x8000000);
  15206. # define VDBE_OFFSET_LINENO(x) (__LINE__+x)
  15207. #else
  15208. # define VdbeCoverage(v)
  15209. # define VdbeCoverageIf(v,x)
  15210. # define VdbeCoverageAlwaysTaken(v)
  15211. # define VdbeCoverageNeverTaken(v)
  15212. # define VdbeCoverageNeverNull(v)
  15213. # define VdbeCoverageNeverNullIf(v,x)
  15214. # define VdbeCoverageEqNe(v)
  15215. # define VDBE_OFFSET_LINENO(x) 0
  15216. #endif
  15217. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  15218. SQLITE_PRIVATE void sqlite3VdbeScanStatus(Vdbe*, int, int, int, LogEst, const char*);
  15219. #else
  15220. # define sqlite3VdbeScanStatus(a,b,c,d,e)
  15221. #endif
  15222. #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
  15223. SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, VdbeOp*);
  15224. #endif
  15225. #endif /* SQLITE_VDBE_H */
  15226. /************** End of vdbe.h ************************************************/
  15227. /************** Continuing where we left off in sqliteInt.h ******************/
  15228. /************** Include pager.h in the middle of sqliteInt.h *****************/
  15229. /************** Begin file pager.h *******************************************/
  15230. /*
  15231. ** 2001 September 15
  15232. **
  15233. ** The author disclaims copyright to this source code. In place of
  15234. ** a legal notice, here is a blessing:
  15235. **
  15236. ** May you do good and not evil.
  15237. ** May you find forgiveness for yourself and forgive others.
  15238. ** May you share freely, never taking more than you give.
  15239. **
  15240. *************************************************************************
  15241. ** This header file defines the interface that the sqlite page cache
  15242. ** subsystem. The page cache subsystem reads and writes a file a page
  15243. ** at a time and provides a journal for rollback.
  15244. */
  15245. #ifndef SQLITE_PAGER_H
  15246. #define SQLITE_PAGER_H
  15247. /*
  15248. ** Default maximum size for persistent journal files. A negative
  15249. ** value means no limit. This value may be overridden using the
  15250. ** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit".
  15251. */
  15252. #ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
  15253. #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
  15254. #endif
  15255. /*
  15256. ** The type used to represent a page number. The first page in a file
  15257. ** is called page 1. 0 is used to represent "not a page".
  15258. */
  15259. typedef u32 Pgno;
  15260. /*
  15261. ** Each open file is managed by a separate instance of the "Pager" structure.
  15262. */
  15263. typedef struct Pager Pager;
  15264. /*
  15265. ** Handle type for pages.
  15266. */
  15267. typedef struct PgHdr DbPage;
  15268. /*
  15269. ** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
  15270. ** reserved for working around a windows/posix incompatibility). It is
  15271. ** used in the journal to signify that the remainder of the journal file
  15272. ** is devoted to storing a master journal name - there are no more pages to
  15273. ** roll back. See comments for function writeMasterJournal() in pager.c
  15274. ** for details.
  15275. */
  15276. #define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))
  15277. /*
  15278. ** Allowed values for the flags parameter to sqlite3PagerOpen().
  15279. **
  15280. ** NOTE: These values must match the corresponding BTREE_ values in btree.h.
  15281. */
  15282. #define PAGER_OMIT_JOURNAL 0x0001 /* Do not use a rollback journal */
  15283. #define PAGER_MEMORY 0x0002 /* In-memory database */
  15284. /*
  15285. ** Valid values for the second argument to sqlite3PagerLockingMode().
  15286. */
  15287. #define PAGER_LOCKINGMODE_QUERY -1
  15288. #define PAGER_LOCKINGMODE_NORMAL 0
  15289. #define PAGER_LOCKINGMODE_EXCLUSIVE 1
  15290. /*
  15291. ** Numeric constants that encode the journalmode.
  15292. **
  15293. ** The numeric values encoded here (other than PAGER_JOURNALMODE_QUERY)
  15294. ** are exposed in the API via the "PRAGMA journal_mode" command and
  15295. ** therefore cannot be changed without a compatibility break.
  15296. */
  15297. #define PAGER_JOURNALMODE_QUERY (-1) /* Query the value of journalmode */
  15298. #define PAGER_JOURNALMODE_DELETE 0 /* Commit by deleting journal file */
  15299. #define PAGER_JOURNALMODE_PERSIST 1 /* Commit by zeroing journal header */
  15300. #define PAGER_JOURNALMODE_OFF 2 /* Journal omitted. */
  15301. #define PAGER_JOURNALMODE_TRUNCATE 3 /* Commit by truncating journal */
  15302. #define PAGER_JOURNALMODE_MEMORY 4 /* In-memory journal file */
  15303. #define PAGER_JOURNALMODE_WAL 5 /* Use write-ahead logging */
  15304. /*
  15305. ** Flags that make up the mask passed to sqlite3PagerGet().
  15306. */
  15307. #define PAGER_GET_NOCONTENT 0x01 /* Do not load data from disk */
  15308. #define PAGER_GET_READONLY 0x02 /* Read-only page is acceptable */
  15309. /*
  15310. ** Flags for sqlite3PagerSetFlags()
  15311. **
  15312. ** Value constraints (enforced via assert()):
  15313. ** PAGER_FULLFSYNC == SQLITE_FullFSync
  15314. ** PAGER_CKPT_FULLFSYNC == SQLITE_CkptFullFSync
  15315. ** PAGER_CACHE_SPILL == SQLITE_CacheSpill
  15316. */
  15317. #define PAGER_SYNCHRONOUS_OFF 0x01 /* PRAGMA synchronous=OFF */
  15318. #define PAGER_SYNCHRONOUS_NORMAL 0x02 /* PRAGMA synchronous=NORMAL */
  15319. #define PAGER_SYNCHRONOUS_FULL 0x03 /* PRAGMA synchronous=FULL */
  15320. #define PAGER_SYNCHRONOUS_EXTRA 0x04 /* PRAGMA synchronous=EXTRA */
  15321. #define PAGER_SYNCHRONOUS_MASK 0x07 /* Mask for four values above */
  15322. #define PAGER_FULLFSYNC 0x08 /* PRAGMA fullfsync=ON */
  15323. #define PAGER_CKPT_FULLFSYNC 0x10 /* PRAGMA checkpoint_fullfsync=ON */
  15324. #define PAGER_CACHESPILL 0x20 /* PRAGMA cache_spill=ON */
  15325. #define PAGER_FLAGS_MASK 0x38 /* All above except SYNCHRONOUS */
  15326. /*
  15327. ** The remainder of this file contains the declarations of the functions
  15328. ** that make up the Pager sub-system API. See source code comments for
  15329. ** a detailed description of each routine.
  15330. */
  15331. /* Open and close a Pager connection. */
  15332. SQLITE_PRIVATE int sqlite3PagerOpen(
  15333. sqlite3_vfs*,
  15334. Pager **ppPager,
  15335. const char*,
  15336. int,
  15337. int,
  15338. int,
  15339. void(*)(DbPage*)
  15340. );
  15341. SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager, sqlite3*);
  15342. SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
  15343. /* Functions used to configure a Pager object. */
  15344. SQLITE_PRIVATE void sqlite3PagerSetBusyHandler(Pager*, int(*)(void *), void *);
  15345. SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u32*, int);
  15346. SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);
  15347. SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
  15348. SQLITE_PRIVATE int sqlite3PagerSetSpillsize(Pager*, int);
  15349. SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *, sqlite3_int64);
  15350. SQLITE_PRIVATE void sqlite3PagerShrink(Pager*);
  15351. SQLITE_PRIVATE void sqlite3PagerSetFlags(Pager*,unsigned);
  15352. SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
  15353. SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *, int);
  15354. SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager*);
  15355. SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager*);
  15356. SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
  15357. SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*);
  15358. SQLITE_PRIVATE int sqlite3PagerFlush(Pager*);
  15359. /* Functions used to obtain and release page references. */
  15360. SQLITE_PRIVATE int sqlite3PagerGet(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
  15361. SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
  15362. SQLITE_PRIVATE void sqlite3PagerRef(DbPage*);
  15363. SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*);
  15364. SQLITE_PRIVATE void sqlite3PagerUnrefNotNull(DbPage*);
  15365. SQLITE_PRIVATE void sqlite3PagerUnrefPageOne(DbPage*);
  15366. /* Operations on page references. */
  15367. SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
  15368. SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*);
  15369. SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);
  15370. SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*);
  15371. SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *);
  15372. SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *);
  15373. /* Functions used to manage pager transactions and savepoints. */
  15374. SQLITE_PRIVATE void sqlite3PagerPagecount(Pager*, int*);
  15375. SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int);
  15376. SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int);
  15377. SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager*);
  15378. SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zMaster);
  15379. SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
  15380. SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
  15381. SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n);
  15382. SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);
  15383. SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager);
  15384. #ifndef SQLITE_OMIT_WAL
  15385. SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, sqlite3*, int, int*, int*);
  15386. SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager);
  15387. SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager);
  15388. SQLITE_PRIVATE int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen);
  15389. SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager, sqlite3*);
  15390. # ifdef SQLITE_ENABLE_SNAPSHOT
  15391. SQLITE_PRIVATE int sqlite3PagerSnapshotGet(Pager*, sqlite3_snapshot **ppSnapshot);
  15392. SQLITE_PRIVATE int sqlite3PagerSnapshotOpen(Pager*, sqlite3_snapshot *pSnapshot);
  15393. SQLITE_PRIVATE int sqlite3PagerSnapshotRecover(Pager *pPager);
  15394. SQLITE_PRIVATE int sqlite3PagerSnapshotCheck(Pager *pPager, sqlite3_snapshot *pSnapshot);
  15395. SQLITE_PRIVATE void sqlite3PagerSnapshotUnlock(Pager *pPager);
  15396. # endif
  15397. #endif
  15398. #if !defined(SQLITE_OMIT_WAL) && defined(SQLITE_ENABLE_SETLK_TIMEOUT)
  15399. SQLITE_PRIVATE int sqlite3PagerWalWriteLock(Pager*, int);
  15400. SQLITE_PRIVATE void sqlite3PagerWalDb(Pager*, sqlite3*);
  15401. #else
  15402. # define sqlite3PagerWalWriteLock(y,z) SQLITE_OK
  15403. # define sqlite3PagerWalDb(x,y)
  15404. #endif
  15405. #ifdef SQLITE_DIRECT_OVERFLOW_READ
  15406. SQLITE_PRIVATE int sqlite3PagerDirectReadOk(Pager *pPager, Pgno pgno);
  15407. #endif
  15408. #ifdef SQLITE_ENABLE_ZIPVFS
  15409. SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager);
  15410. #endif
  15411. /* Functions used to query pager state and configuration. */
  15412. SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*);
  15413. SQLITE_PRIVATE u32 sqlite3PagerDataVersion(Pager*);
  15414. #ifdef SQLITE_DEBUG
  15415. SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*);
  15416. #endif
  15417. SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager*);
  15418. SQLITE_PRIVATE const char *sqlite3PagerFilename(const Pager*, int);
  15419. SQLITE_PRIVATE sqlite3_vfs *sqlite3PagerVfs(Pager*);
  15420. SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
  15421. SQLITE_PRIVATE sqlite3_file *sqlite3PagerJrnlFile(Pager*);
  15422. SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
  15423. SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
  15424. SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*);
  15425. SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *, int, int, int *);
  15426. SQLITE_PRIVATE void sqlite3PagerClearCache(Pager*);
  15427. SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *);
  15428. /* Functions used to truncate the database file. */
  15429. SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno);
  15430. SQLITE_PRIVATE void sqlite3PagerRekey(DbPage*, Pgno, u16);
  15431. /* Functions to support testing and debugging. */
  15432. #if !defined(NDEBUG) || defined(SQLITE_TEST)
  15433. SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage*);
  15434. SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage*);
  15435. #endif
  15436. #ifdef SQLITE_TEST
  15437. SQLITE_PRIVATE int *sqlite3PagerStats(Pager*);
  15438. SQLITE_PRIVATE void sqlite3PagerRefdump(Pager*);
  15439. void disable_simulated_io_errors(void);
  15440. void enable_simulated_io_errors(void);
  15441. #else
  15442. # define disable_simulated_io_errors()
  15443. # define enable_simulated_io_errors()
  15444. #endif
  15445. #endif /* SQLITE_PAGER_H */
  15446. /************** End of pager.h ***********************************************/
  15447. /************** Continuing where we left off in sqliteInt.h ******************/
  15448. /************** Include pcache.h in the middle of sqliteInt.h ****************/
  15449. /************** Begin file pcache.h ******************************************/
  15450. /*
  15451. ** 2008 August 05
  15452. **
  15453. ** The author disclaims copyright to this source code. In place of
  15454. ** a legal notice, here is a blessing:
  15455. **
  15456. ** May you do good and not evil.
  15457. ** May you find forgiveness for yourself and forgive others.
  15458. ** May you share freely, never taking more than you give.
  15459. **
  15460. *************************************************************************
  15461. ** This header file defines the interface that the sqlite page cache
  15462. ** subsystem.
  15463. */
  15464. #ifndef _PCACHE_H_
  15465. typedef struct PgHdr PgHdr;
  15466. typedef struct PCache PCache;
  15467. /*
  15468. ** Every page in the cache is controlled by an instance of the following
  15469. ** structure.
  15470. */
  15471. struct PgHdr {
  15472. sqlite3_pcache_page *pPage; /* Pcache object page handle */
  15473. void *pData; /* Page data */
  15474. void *pExtra; /* Extra content */
  15475. PCache *pCache; /* PRIVATE: Cache that owns this page */
  15476. PgHdr *pDirty; /* Transient list of dirty sorted by pgno */
  15477. Pager *pPager; /* The pager this page is part of */
  15478. Pgno pgno; /* Page number for this page */
  15479. #ifdef SQLITE_CHECK_PAGES
  15480. u32 pageHash; /* Hash of page content */
  15481. #endif
  15482. u16 flags; /* PGHDR flags defined below */
  15483. /**********************************************************************
  15484. ** Elements above, except pCache, are public. All that follow are
  15485. ** private to pcache.c and should not be accessed by other modules.
  15486. ** pCache is grouped with the public elements for efficiency.
  15487. */
  15488. i16 nRef; /* Number of users of this page */
  15489. PgHdr *pDirtyNext; /* Next element in list of dirty pages */
  15490. PgHdr *pDirtyPrev; /* Previous element in list of dirty pages */
  15491. /* NB: pDirtyNext and pDirtyPrev are undefined if the
  15492. ** PgHdr object is not dirty */
  15493. };
  15494. /* Bit values for PgHdr.flags */
  15495. #define PGHDR_CLEAN 0x001 /* Page not on the PCache.pDirty list */
  15496. #define PGHDR_DIRTY 0x002 /* Page is on the PCache.pDirty list */
  15497. #define PGHDR_WRITEABLE 0x004 /* Journaled and ready to modify */
  15498. #define PGHDR_NEED_SYNC 0x008 /* Fsync the rollback journal before
  15499. ** writing this page to the database */
  15500. #define PGHDR_DONT_WRITE 0x010 /* Do not write content to disk */
  15501. #define PGHDR_MMAP 0x020 /* This is an mmap page object */
  15502. #define PGHDR_WAL_APPEND 0x040 /* Appended to wal file */
  15503. /* Initialize and shutdown the page cache subsystem */
  15504. SQLITE_PRIVATE int sqlite3PcacheInitialize(void);
  15505. SQLITE_PRIVATE void sqlite3PcacheShutdown(void);
  15506. /* Page cache buffer management:
  15507. ** These routines implement SQLITE_CONFIG_PAGECACHE.
  15508. */
  15509. SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n);
  15510. /* Create a new pager cache.
  15511. ** Under memory stress, invoke xStress to try to make pages clean.
  15512. ** Only clean and unpinned pages can be reclaimed.
  15513. */
  15514. SQLITE_PRIVATE int sqlite3PcacheOpen(
  15515. int szPage, /* Size of every page */
  15516. int szExtra, /* Extra space associated with each page */
  15517. int bPurgeable, /* True if pages are on backing store */
  15518. int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */
  15519. void *pStress, /* Argument to xStress */
  15520. PCache *pToInit /* Preallocated space for the PCache */
  15521. );
  15522. /* Modify the page-size after the cache has been created. */
  15523. SQLITE_PRIVATE int sqlite3PcacheSetPageSize(PCache *, int);
  15524. /* Return the size in bytes of a PCache object. Used to preallocate
  15525. ** storage space.
  15526. */
  15527. SQLITE_PRIVATE int sqlite3PcacheSize(void);
  15528. /* One release per successful fetch. Page is pinned until released.
  15529. ** Reference counted.
  15530. */
  15531. SQLITE_PRIVATE sqlite3_pcache_page *sqlite3PcacheFetch(PCache*, Pgno, int createFlag);
  15532. SQLITE_PRIVATE int sqlite3PcacheFetchStress(PCache*, Pgno, sqlite3_pcache_page**);
  15533. SQLITE_PRIVATE PgHdr *sqlite3PcacheFetchFinish(PCache*, Pgno, sqlite3_pcache_page *pPage);
  15534. SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*);
  15535. SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*); /* Remove page from cache */
  15536. SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*); /* Make sure page is marked dirty */
  15537. SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*); /* Mark a single page as clean */
  15538. SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*); /* Mark all dirty list pages as clean */
  15539. SQLITE_PRIVATE void sqlite3PcacheClearWritable(PCache*);
  15540. /* Change a page number. Used by incr-vacuum. */
  15541. SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno);
  15542. /* Remove all pages with pgno>x. Reset the cache if x==0 */
  15543. SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x);
  15544. /* Get a list of all dirty pages in the cache, sorted by page number */
  15545. SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*);
  15546. /* Reset and close the cache object */
  15547. SQLITE_PRIVATE void sqlite3PcacheClose(PCache*);
  15548. /* Clear flags from pages of the page cache */
  15549. SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *);
  15550. /* Discard the contents of the cache */
  15551. SQLITE_PRIVATE void sqlite3PcacheClear(PCache*);
  15552. /* Return the total number of outstanding page references */
  15553. SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*);
  15554. /* Increment the reference count of an existing page */
  15555. SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*);
  15556. SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*);
  15557. /* Return the total number of pages stored in the cache */
  15558. SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*);
  15559. #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
  15560. /* Iterate through all dirty pages currently stored in the cache. This
  15561. ** interface is only available if SQLITE_CHECK_PAGES is defined when the
  15562. ** library is built.
  15563. */
  15564. SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
  15565. #endif
  15566. #if defined(SQLITE_DEBUG)
  15567. /* Check invariants on a PgHdr object */
  15568. SQLITE_PRIVATE int sqlite3PcachePageSanity(PgHdr*);
  15569. #endif
  15570. /* Set and get the suggested cache-size for the specified pager-cache.
  15571. **
  15572. ** If no global maximum is configured, then the system attempts to limit
  15573. ** the total number of pages cached by purgeable pager-caches to the sum
  15574. ** of the suggested cache-sizes.
  15575. */
  15576. SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int);
  15577. #ifdef SQLITE_TEST
  15578. SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *);
  15579. #endif
  15580. /* Set or get the suggested spill-size for the specified pager-cache.
  15581. **
  15582. ** The spill-size is the minimum number of pages in cache before the cache
  15583. ** will attempt to spill dirty pages by calling xStress.
  15584. */
  15585. SQLITE_PRIVATE int sqlite3PcacheSetSpillsize(PCache *, int);
  15586. /* Free up as much memory as possible from the page cache */
  15587. SQLITE_PRIVATE void sqlite3PcacheShrink(PCache*);
  15588. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  15589. /* Try to return memory used by the pcache module to the main memory heap */
  15590. SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int);
  15591. #endif
  15592. #ifdef SQLITE_TEST
  15593. SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*);
  15594. #endif
  15595. SQLITE_PRIVATE void sqlite3PCacheSetDefault(void);
  15596. /* Return the header size */
  15597. SQLITE_PRIVATE int sqlite3HeaderSizePcache(void);
  15598. SQLITE_PRIVATE int sqlite3HeaderSizePcache1(void);
  15599. /* Number of dirty pages as a percentage of the configured cache size */
  15600. SQLITE_PRIVATE int sqlite3PCachePercentDirty(PCache*);
  15601. #ifdef SQLITE_DIRECT_OVERFLOW_READ
  15602. SQLITE_PRIVATE int sqlite3PCacheIsDirty(PCache *pCache);
  15603. #endif
  15604. #endif /* _PCACHE_H_ */
  15605. /************** End of pcache.h **********************************************/
  15606. /************** Continuing where we left off in sqliteInt.h ******************/
  15607. /************** Include os.h in the middle of sqliteInt.h ********************/
  15608. /************** Begin file os.h **********************************************/
  15609. /*
  15610. ** 2001 September 16
  15611. **
  15612. ** The author disclaims copyright to this source code. In place of
  15613. ** a legal notice, here is a blessing:
  15614. **
  15615. ** May you do good and not evil.
  15616. ** May you find forgiveness for yourself and forgive others.
  15617. ** May you share freely, never taking more than you give.
  15618. **
  15619. ******************************************************************************
  15620. **
  15621. ** This header file (together with is companion C source-code file
  15622. ** "os.c") attempt to abstract the underlying operating system so that
  15623. ** the SQLite library will work on both POSIX and windows systems.
  15624. **
  15625. ** This header file is #include-ed by sqliteInt.h and thus ends up
  15626. ** being included by every source file.
  15627. */
  15628. #ifndef _SQLITE_OS_H_
  15629. #define _SQLITE_OS_H_
  15630. /*
  15631. ** Attempt to automatically detect the operating system and setup the
  15632. ** necessary pre-processor macros for it.
  15633. */
  15634. /************** Include os_setup.h in the middle of os.h *********************/
  15635. /************** Begin file os_setup.h ****************************************/
  15636. /*
  15637. ** 2013 November 25
  15638. **
  15639. ** The author disclaims copyright to this source code. In place of
  15640. ** a legal notice, here is a blessing:
  15641. **
  15642. ** May you do good and not evil.
  15643. ** May you find forgiveness for yourself and forgive others.
  15644. ** May you share freely, never taking more than you give.
  15645. **
  15646. ******************************************************************************
  15647. **
  15648. ** This file contains pre-processor directives related to operating system
  15649. ** detection and/or setup.
  15650. */
  15651. #ifndef SQLITE_OS_SETUP_H
  15652. #define SQLITE_OS_SETUP_H
  15653. /*
  15654. ** Figure out if we are dealing with Unix, Windows, or some other operating
  15655. ** system.
  15656. **
  15657. ** After the following block of preprocess macros, all of SQLITE_OS_UNIX,
  15658. ** SQLITE_OS_WIN, and SQLITE_OS_OTHER will defined to either 1 or 0. One of
  15659. ** the three will be 1. The other two will be 0.
  15660. */
  15661. #if defined(SQLITE_OS_OTHER)
  15662. # if SQLITE_OS_OTHER==1
  15663. # undef SQLITE_OS_UNIX
  15664. # define SQLITE_OS_UNIX 0
  15665. # undef SQLITE_OS_WIN
  15666. # define SQLITE_OS_WIN 0
  15667. # else
  15668. # undef SQLITE_OS_OTHER
  15669. # endif
  15670. #endif
  15671. #if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER)
  15672. # define SQLITE_OS_OTHER 0
  15673. # ifndef SQLITE_OS_WIN
  15674. # if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || \
  15675. defined(__MINGW32__) || defined(__BORLANDC__)
  15676. # define SQLITE_OS_WIN 1
  15677. # define SQLITE_OS_UNIX 0
  15678. # else
  15679. # define SQLITE_OS_WIN 0
  15680. # define SQLITE_OS_UNIX 1
  15681. # endif
  15682. # else
  15683. # define SQLITE_OS_UNIX 0
  15684. # endif
  15685. #else
  15686. # ifndef SQLITE_OS_WIN
  15687. # define SQLITE_OS_WIN 0
  15688. # endif
  15689. #endif
  15690. #endif /* SQLITE_OS_SETUP_H */
  15691. /************** End of os_setup.h ********************************************/
  15692. /************** Continuing where we left off in os.h *************************/
  15693. /* If the SET_FULLSYNC macro is not defined above, then make it
  15694. ** a no-op
  15695. */
  15696. #ifndef SET_FULLSYNC
  15697. # define SET_FULLSYNC(x,y)
  15698. #endif
  15699. /*
  15700. ** The default size of a disk sector
  15701. */
  15702. #ifndef SQLITE_DEFAULT_SECTOR_SIZE
  15703. # define SQLITE_DEFAULT_SECTOR_SIZE 4096
  15704. #endif
  15705. /*
  15706. ** Temporary files are named starting with this prefix followed by 16 random
  15707. ** alphanumeric characters, and no file extension. They are stored in the
  15708. ** OS's standard temporary file directory, and are deleted prior to exit.
  15709. ** If sqlite is being embedded in another program, you may wish to change the
  15710. ** prefix to reflect your program's name, so that if your program exits
  15711. ** prematurely, old temporary files can be easily identified. This can be done
  15712. ** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
  15713. **
  15714. ** 2006-10-31: The default prefix used to be "sqlite_". But then
  15715. ** Mcafee started using SQLite in their anti-virus product and it
  15716. ** started putting files with the "sqlite" name in the c:/temp folder.
  15717. ** This annoyed many windows users. Those users would then do a
  15718. ** Google search for "sqlite", find the telephone numbers of the
  15719. ** developers and call to wake them up at night and complain.
  15720. ** For this reason, the default name prefix is changed to be "sqlite"
  15721. ** spelled backwards. So the temp files are still identified, but
  15722. ** anybody smart enough to figure out the code is also likely smart
  15723. ** enough to know that calling the developer will not help get rid
  15724. ** of the file.
  15725. */
  15726. #ifndef SQLITE_TEMP_FILE_PREFIX
  15727. # define SQLITE_TEMP_FILE_PREFIX "etilqs_"
  15728. #endif
  15729. /*
  15730. ** The following values may be passed as the second argument to
  15731. ** sqlite3OsLock(). The various locks exhibit the following semantics:
  15732. **
  15733. ** SHARED: Any number of processes may hold a SHARED lock simultaneously.
  15734. ** RESERVED: A single process may hold a RESERVED lock on a file at
  15735. ** any time. Other processes may hold and obtain new SHARED locks.
  15736. ** PENDING: A single process may hold a PENDING lock on a file at
  15737. ** any one time. Existing SHARED locks may persist, but no new
  15738. ** SHARED locks may be obtained by other processes.
  15739. ** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
  15740. **
  15741. ** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
  15742. ** process that requests an EXCLUSIVE lock may actually obtain a PENDING
  15743. ** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
  15744. ** sqlite3OsLock().
  15745. */
  15746. #define NO_LOCK 0
  15747. #define SHARED_LOCK 1
  15748. #define RESERVED_LOCK 2
  15749. #define PENDING_LOCK 3
  15750. #define EXCLUSIVE_LOCK 4
  15751. /*
  15752. ** File Locking Notes: (Mostly about windows but also some info for Unix)
  15753. **
  15754. ** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
  15755. ** those functions are not available. So we use only LockFile() and
  15756. ** UnlockFile().
  15757. **
  15758. ** LockFile() prevents not just writing but also reading by other processes.
  15759. ** A SHARED_LOCK is obtained by locking a single randomly-chosen
  15760. ** byte out of a specific range of bytes. The lock byte is obtained at
  15761. ** random so two separate readers can probably access the file at the
  15762. ** same time, unless they are unlucky and choose the same lock byte.
  15763. ** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
  15764. ** There can only be one writer. A RESERVED_LOCK is obtained by locking
  15765. ** a single byte of the file that is designated as the reserved lock byte.
  15766. ** A PENDING_LOCK is obtained by locking a designated byte different from
  15767. ** the RESERVED_LOCK byte.
  15768. **
  15769. ** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
  15770. ** which means we can use reader/writer locks. When reader/writer locks
  15771. ** are used, the lock is placed on the same range of bytes that is used
  15772. ** for probabilistic locking in Win95/98/ME. Hence, the locking scheme
  15773. ** will support two or more Win95 readers or two or more WinNT readers.
  15774. ** But a single Win95 reader will lock out all WinNT readers and a single
  15775. ** WinNT reader will lock out all other Win95 readers.
  15776. **
  15777. ** The following #defines specify the range of bytes used for locking.
  15778. ** SHARED_SIZE is the number of bytes available in the pool from which
  15779. ** a random byte is selected for a shared lock. The pool of bytes for
  15780. ** shared locks begins at SHARED_FIRST.
  15781. **
  15782. ** The same locking strategy and
  15783. ** byte ranges are used for Unix. This leaves open the possibility of having
  15784. ** clients on win95, winNT, and unix all talking to the same shared file
  15785. ** and all locking correctly. To do so would require that samba (or whatever
  15786. ** tool is being used for file sharing) implements locks correctly between
  15787. ** windows and unix. I'm guessing that isn't likely to happen, but by
  15788. ** using the same locking range we are at least open to the possibility.
  15789. **
  15790. ** Locking in windows is manditory. For this reason, we cannot store
  15791. ** actual data in the bytes used for locking. The pager never allocates
  15792. ** the pages involved in locking therefore. SHARED_SIZE is selected so
  15793. ** that all locks will fit on a single page even at the minimum page size.
  15794. ** PENDING_BYTE defines the beginning of the locks. By default PENDING_BYTE
  15795. ** is set high so that we don't have to allocate an unused page except
  15796. ** for very large databases. But one should test the page skipping logic
  15797. ** by setting PENDING_BYTE low and running the entire regression suite.
  15798. **
  15799. ** Changing the value of PENDING_BYTE results in a subtly incompatible
  15800. ** file format. Depending on how it is changed, you might not notice
  15801. ** the incompatibility right away, even running a full regression test.
  15802. ** The default location of PENDING_BYTE is the first byte past the
  15803. ** 1GB boundary.
  15804. **
  15805. */
  15806. #ifdef SQLITE_OMIT_WSD
  15807. # define PENDING_BYTE (0x40000000)
  15808. #else
  15809. # define PENDING_BYTE sqlite3PendingByte
  15810. #endif
  15811. #define RESERVED_BYTE (PENDING_BYTE+1)
  15812. #define SHARED_FIRST (PENDING_BYTE+2)
  15813. #define SHARED_SIZE 510
  15814. /*
  15815. ** Wrapper around OS specific sqlite3_os_init() function.
  15816. */
  15817. SQLITE_PRIVATE int sqlite3OsInit(void);
  15818. /*
  15819. ** Functions for accessing sqlite3_file methods
  15820. */
  15821. SQLITE_PRIVATE void sqlite3OsClose(sqlite3_file*);
  15822. SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
  15823. SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
  15824. SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
  15825. SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
  15826. SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
  15827. SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);
  15828. SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);
  15829. SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);
  15830. SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);
  15831. SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file*,int,void*);
  15832. #define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0
  15833. SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
  15834. SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
  15835. #ifndef SQLITE_OMIT_WAL
  15836. SQLITE_PRIVATE int sqlite3OsShmMap(sqlite3_file *,int,int,int,void volatile **);
  15837. SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int, int, int);
  15838. SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id);
  15839. SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int);
  15840. #endif /* SQLITE_OMIT_WAL */
  15841. SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64, int, void **);
  15842. SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *, i64, void *);
  15843. /*
  15844. ** Functions for accessing sqlite3_vfs methods
  15845. */
  15846. SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
  15847. SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
  15848. SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);
  15849. SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
  15850. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  15851. SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
  15852. SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
  15853. SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void);
  15854. SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
  15855. #endif /* SQLITE_OMIT_LOAD_EXTENSION */
  15856. SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
  15857. SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
  15858. SQLITE_PRIVATE int sqlite3OsGetLastError(sqlite3_vfs*);
  15859. SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64*);
  15860. /*
  15861. ** Convenience functions for opening and closing files using
  15862. ** sqlite3_malloc() to obtain space for the file-handle structure.
  15863. */
  15864. SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
  15865. SQLITE_PRIVATE void sqlite3OsCloseFree(sqlite3_file *);
  15866. #endif /* _SQLITE_OS_H_ */
  15867. /************** End of os.h **************************************************/
  15868. /************** Continuing where we left off in sqliteInt.h ******************/
  15869. /************** Include mutex.h in the middle of sqliteInt.h *****************/
  15870. /************** Begin file mutex.h *******************************************/
  15871. /*
  15872. ** 2007 August 28
  15873. **
  15874. ** The author disclaims copyright to this source code. In place of
  15875. ** a legal notice, here is a blessing:
  15876. **
  15877. ** May you do good and not evil.
  15878. ** May you find forgiveness for yourself and forgive others.
  15879. ** May you share freely, never taking more than you give.
  15880. **
  15881. *************************************************************************
  15882. **
  15883. ** This file contains the common header for all mutex implementations.
  15884. ** The sqliteInt.h header #includes this file so that it is available
  15885. ** to all source files. We break it out in an effort to keep the code
  15886. ** better organized.
  15887. **
  15888. ** NOTE: source files should *not* #include this header file directly.
  15889. ** Source files should #include the sqliteInt.h file and let that file
  15890. ** include this one indirectly.
  15891. */
  15892. /*
  15893. ** Figure out what version of the code to use. The choices are
  15894. **
  15895. ** SQLITE_MUTEX_OMIT No mutex logic. Not even stubs. The
  15896. ** mutexes implementation cannot be overridden
  15897. ** at start-time.
  15898. **
  15899. ** SQLITE_MUTEX_NOOP For single-threaded applications. No
  15900. ** mutual exclusion is provided. But this
  15901. ** implementation can be overridden at
  15902. ** start-time.
  15903. **
  15904. ** SQLITE_MUTEX_PTHREADS For multi-threaded applications on Unix.
  15905. **
  15906. ** SQLITE_MUTEX_W32 For multi-threaded applications on Win32.
  15907. */
  15908. #if !SQLITE_THREADSAFE
  15909. # define SQLITE_MUTEX_OMIT
  15910. #endif
  15911. #if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP)
  15912. # if SQLITE_OS_UNIX
  15913. # define SQLITE_MUTEX_PTHREADS
  15914. # elif SQLITE_OS_WIN
  15915. # define SQLITE_MUTEX_W32
  15916. # else
  15917. # define SQLITE_MUTEX_NOOP
  15918. # endif
  15919. #endif
  15920. #ifdef SQLITE_MUTEX_OMIT
  15921. /*
  15922. ** If this is a no-op implementation, implement everything as macros.
  15923. */
  15924. #define sqlite3_mutex_alloc(X) ((sqlite3_mutex*)8)
  15925. #define sqlite3_mutex_free(X)
  15926. #define sqlite3_mutex_enter(X)
  15927. #define sqlite3_mutex_try(X) SQLITE_OK
  15928. #define sqlite3_mutex_leave(X)
  15929. #define sqlite3_mutex_held(X) ((void)(X),1)
  15930. #define sqlite3_mutex_notheld(X) ((void)(X),1)
  15931. #define sqlite3MutexAlloc(X) ((sqlite3_mutex*)8)
  15932. #define sqlite3MutexInit() SQLITE_OK
  15933. #define sqlite3MutexEnd()
  15934. #define MUTEX_LOGIC(X)
  15935. #else
  15936. #define MUTEX_LOGIC(X) X
  15937. SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*);
  15938. #endif /* defined(SQLITE_MUTEX_OMIT) */
  15939. /************** End of mutex.h ***********************************************/
  15940. /************** Continuing where we left off in sqliteInt.h ******************/
  15941. /* The SQLITE_EXTRA_DURABLE compile-time option used to set the default
  15942. ** synchronous setting to EXTRA. It is no longer supported.
  15943. */
  15944. #ifdef SQLITE_EXTRA_DURABLE
  15945. # warning Use SQLITE_DEFAULT_SYNCHRONOUS=3 instead of SQLITE_EXTRA_DURABLE
  15946. # define SQLITE_DEFAULT_SYNCHRONOUS 3
  15947. #endif
  15948. /*
  15949. ** Default synchronous levels.
  15950. **
  15951. ** Note that (for historcal reasons) the PAGER_SYNCHRONOUS_* macros differ
  15952. ** from the SQLITE_DEFAULT_SYNCHRONOUS value by 1.
  15953. **
  15954. ** PAGER_SYNCHRONOUS DEFAULT_SYNCHRONOUS
  15955. ** OFF 1 0
  15956. ** NORMAL 2 1
  15957. ** FULL 3 2
  15958. ** EXTRA 4 3
  15959. **
  15960. ** The "PRAGMA synchronous" statement also uses the zero-based numbers.
  15961. ** In other words, the zero-based numbers are used for all external interfaces
  15962. ** and the one-based values are used internally.
  15963. */
  15964. #ifndef SQLITE_DEFAULT_SYNCHRONOUS
  15965. # define SQLITE_DEFAULT_SYNCHRONOUS 2
  15966. #endif
  15967. #ifndef SQLITE_DEFAULT_WAL_SYNCHRONOUS
  15968. # define SQLITE_DEFAULT_WAL_SYNCHRONOUS SQLITE_DEFAULT_SYNCHRONOUS
  15969. #endif
  15970. /*
  15971. ** Each database file to be accessed by the system is an instance
  15972. ** of the following structure. There are normally two of these structures
  15973. ** in the sqlite.aDb[] array. aDb[0] is the main database file and
  15974. ** aDb[1] is the database file used to hold temporary tables. Additional
  15975. ** databases may be attached.
  15976. */
  15977. struct Db {
  15978. char *zDbSName; /* Name of this database. (schema name, not filename) */
  15979. Btree *pBt; /* The B*Tree structure for this database file */
  15980. u8 safety_level; /* How aggressive at syncing data to disk */
  15981. u8 bSyncSet; /* True if "PRAGMA synchronous=N" has been run */
  15982. Schema *pSchema; /* Pointer to database schema (possibly shared) */
  15983. };
  15984. /*
  15985. ** An instance of the following structure stores a database schema.
  15986. **
  15987. ** Most Schema objects are associated with a Btree. The exception is
  15988. ** the Schema for the TEMP databaes (sqlite3.aDb[1]) which is free-standing.
  15989. ** In shared cache mode, a single Schema object can be shared by multiple
  15990. ** Btrees that refer to the same underlying BtShared object.
  15991. **
  15992. ** Schema objects are automatically deallocated when the last Btree that
  15993. ** references them is destroyed. The TEMP Schema is manually freed by
  15994. ** sqlite3_close().
  15995. *
  15996. ** A thread must be holding a mutex on the corresponding Btree in order
  15997. ** to access Schema content. This implies that the thread must also be
  15998. ** holding a mutex on the sqlite3 connection pointer that owns the Btree.
  15999. ** For a TEMP Schema, only the connection mutex is required.
  16000. */
  16001. struct Schema {
  16002. int schema_cookie; /* Database schema version number for this file */
  16003. int iGeneration; /* Generation counter. Incremented with each change */
  16004. Hash tblHash; /* All tables indexed by name */
  16005. Hash idxHash; /* All (named) indices indexed by name */
  16006. Hash trigHash; /* All triggers indexed by name */
  16007. Hash fkeyHash; /* All foreign keys by referenced table name */
  16008. Table *pSeqTab; /* The sqlite_sequence table used by AUTOINCREMENT */
  16009. u8 file_format; /* Schema format version for this file */
  16010. u8 enc; /* Text encoding used by this database */
  16011. u16 schemaFlags; /* Flags associated with this schema */
  16012. int cache_size; /* Number of pages to use in the cache */
  16013. };
  16014. /*
  16015. ** These macros can be used to test, set, or clear bits in the
  16016. ** Db.pSchema->flags field.
  16017. */
  16018. #define DbHasProperty(D,I,P) (((D)->aDb[I].pSchema->schemaFlags&(P))==(P))
  16019. #define DbHasAnyProperty(D,I,P) (((D)->aDb[I].pSchema->schemaFlags&(P))!=0)
  16020. #define DbSetProperty(D,I,P) (D)->aDb[I].pSchema->schemaFlags|=(P)
  16021. #define DbClearProperty(D,I,P) (D)->aDb[I].pSchema->schemaFlags&=~(P)
  16022. /*
  16023. ** Allowed values for the DB.pSchema->flags field.
  16024. **
  16025. ** The DB_SchemaLoaded flag is set after the database schema has been
  16026. ** read into internal hash tables.
  16027. **
  16028. ** DB_UnresetViews means that one or more views have column names that
  16029. ** have been filled out. If the schema changes, these column names might
  16030. ** changes and so the view will need to be reset.
  16031. */
  16032. #define DB_SchemaLoaded 0x0001 /* The schema has been loaded */
  16033. #define DB_UnresetViews 0x0002 /* Some views have defined column names */
  16034. #define DB_ResetWanted 0x0008 /* Reset the schema when nSchemaLock==0 */
  16035. /*
  16036. ** The number of different kinds of things that can be limited
  16037. ** using the sqlite3_limit() interface.
  16038. */
  16039. #define SQLITE_N_LIMIT (SQLITE_LIMIT_WORKER_THREADS+1)
  16040. /*
  16041. ** Lookaside malloc is a set of fixed-size buffers that can be used
  16042. ** to satisfy small transient memory allocation requests for objects
  16043. ** associated with a particular database connection. The use of
  16044. ** lookaside malloc provides a significant performance enhancement
  16045. ** (approx 10%) by avoiding numerous malloc/free requests while parsing
  16046. ** SQL statements.
  16047. **
  16048. ** The Lookaside structure holds configuration information about the
  16049. ** lookaside malloc subsystem. Each available memory allocation in
  16050. ** the lookaside subsystem is stored on a linked list of LookasideSlot
  16051. ** objects.
  16052. **
  16053. ** Lookaside allocations are only allowed for objects that are associated
  16054. ** with a particular database connection. Hence, schema information cannot
  16055. ** be stored in lookaside because in shared cache mode the schema information
  16056. ** is shared by multiple database connections. Therefore, while parsing
  16057. ** schema information, the Lookaside.bEnabled flag is cleared so that
  16058. ** lookaside allocations are not used to construct the schema objects.
  16059. **
  16060. ** New lookaside allocations are only allowed if bDisable==0. When
  16061. ** bDisable is greater than zero, sz is set to zero which effectively
  16062. ** disables lookaside without adding a new test for the bDisable flag
  16063. ** in a performance-critical path. sz should be set by to szTrue whenever
  16064. ** bDisable changes back to zero.
  16065. **
  16066. ** Lookaside buffers are initially held on the pInit list. As they are
  16067. ** used and freed, they are added back to the pFree list. New allocations
  16068. ** come off of pFree first, then pInit as a fallback. This dual-list
  16069. ** allows use to compute a high-water mark - the maximum number of allocations
  16070. ** outstanding at any point in the past - by subtracting the number of
  16071. ** allocations on the pInit list from the total number of allocations.
  16072. **
  16073. ** Enhancement on 2019-12-12: Two-size-lookaside
  16074. ** The default lookaside configuration is 100 slots of 1200 bytes each.
  16075. ** The larger slot sizes are important for performance, but they waste
  16076. ** a lot of space, as most lookaside allocations are less than 128 bytes.
  16077. ** The two-size-lookaside enhancement breaks up the lookaside allocation
  16078. ** into two pools: One of 128-byte slots and the other of the default size
  16079. ** (1200-byte) slots. Allocations are filled from the small-pool first,
  16080. ** failing over to the full-size pool if that does not work. Thus more
  16081. ** lookaside slots are available while also using less memory.
  16082. ** This enhancement can be omitted by compiling with
  16083. ** SQLITE_OMIT_TWOSIZE_LOOKASIDE.
  16084. */
  16085. struct Lookaside {
  16086. u32 bDisable; /* Only operate the lookaside when zero */
  16087. u16 sz; /* Size of each buffer in bytes */
  16088. u16 szTrue; /* True value of sz, even if disabled */
  16089. u8 bMalloced; /* True if pStart obtained from sqlite3_malloc() */
  16090. u32 nSlot; /* Number of lookaside slots allocated */
  16091. u32 anStat[3]; /* 0: hits. 1: size misses. 2: full misses */
  16092. LookasideSlot *pInit; /* List of buffers not previously used */
  16093. LookasideSlot *pFree; /* List of available buffers */
  16094. #ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE
  16095. LookasideSlot *pSmallInit; /* List of small buffers not prediously used */
  16096. LookasideSlot *pSmallFree; /* List of available small buffers */
  16097. void *pMiddle; /* First byte past end of full-size buffers and
  16098. ** the first byte of LOOKASIDE_SMALL buffers */
  16099. #endif /* SQLITE_OMIT_TWOSIZE_LOOKASIDE */
  16100. void *pStart; /* First byte of available memory space */
  16101. void *pEnd; /* First byte past end of available space */
  16102. };
  16103. struct LookasideSlot {
  16104. LookasideSlot *pNext; /* Next buffer in the list of free buffers */
  16105. };
  16106. #define DisableLookaside db->lookaside.bDisable++;db->lookaside.sz=0
  16107. #define EnableLookaside db->lookaside.bDisable--;\
  16108. db->lookaside.sz=db->lookaside.bDisable?0:db->lookaside.szTrue
  16109. /* Size of the smaller allocations in two-size lookside */
  16110. #ifdef SQLITE_OMIT_TWOSIZE_LOOKASIDE
  16111. # define LOOKASIDE_SMALL 0
  16112. #else
  16113. # define LOOKASIDE_SMALL 128
  16114. #endif
  16115. /*
  16116. ** A hash table for built-in function definitions. (Application-defined
  16117. ** functions use a regular table table from hash.h.)
  16118. **
  16119. ** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
  16120. ** Collisions are on the FuncDef.u.pHash chain. Use the SQLITE_FUNC_HASH()
  16121. ** macro to compute a hash on the function name.
  16122. */
  16123. #define SQLITE_FUNC_HASH_SZ 23
  16124. struct FuncDefHash {
  16125. FuncDef *a[SQLITE_FUNC_HASH_SZ]; /* Hash table for functions */
  16126. };
  16127. #define SQLITE_FUNC_HASH(C,L) (((C)+(L))%SQLITE_FUNC_HASH_SZ)
  16128. #ifdef SQLITE_USER_AUTHENTICATION
  16129. /*
  16130. ** Information held in the "sqlite3" database connection object and used
  16131. ** to manage user authentication.
  16132. */
  16133. typedef struct sqlite3_userauth sqlite3_userauth;
  16134. struct sqlite3_userauth {
  16135. u8 authLevel; /* Current authentication level */
  16136. int nAuthPW; /* Size of the zAuthPW in bytes */
  16137. char *zAuthPW; /* Password used to authenticate */
  16138. char *zAuthUser; /* User name used to authenticate */
  16139. };
  16140. /* Allowed values for sqlite3_userauth.authLevel */
  16141. #define UAUTH_Unknown 0 /* Authentication not yet checked */
  16142. #define UAUTH_Fail 1 /* User authentication failed */
  16143. #define UAUTH_User 2 /* Authenticated as a normal user */
  16144. #define UAUTH_Admin 3 /* Authenticated as an administrator */
  16145. /* Functions used only by user authorization logic */
  16146. SQLITE_PRIVATE int sqlite3UserAuthTable(const char*);
  16147. SQLITE_PRIVATE int sqlite3UserAuthCheckLogin(sqlite3*,const char*,u8*);
  16148. SQLITE_PRIVATE void sqlite3UserAuthInit(sqlite3*);
  16149. SQLITE_PRIVATE void sqlite3CryptFunc(sqlite3_context*,int,sqlite3_value**);
  16150. #endif /* SQLITE_USER_AUTHENTICATION */
  16151. /*
  16152. ** typedef for the authorization callback function.
  16153. */
  16154. #ifdef SQLITE_USER_AUTHENTICATION
  16155. typedef int (*sqlite3_xauth)(void*,int,const char*,const char*,const char*,
  16156. const char*, const char*);
  16157. #else
  16158. typedef int (*sqlite3_xauth)(void*,int,const char*,const char*,const char*,
  16159. const char*);
  16160. #endif
  16161. #ifndef SQLITE_OMIT_DEPRECATED
  16162. /* This is an extra SQLITE_TRACE macro that indicates "legacy" tracing
  16163. ** in the style of sqlite3_trace()
  16164. */
  16165. #define SQLITE_TRACE_LEGACY 0x40 /* Use the legacy xTrace */
  16166. #define SQLITE_TRACE_XPROFILE 0x80 /* Use the legacy xProfile */
  16167. #else
  16168. #define SQLITE_TRACE_LEGACY 0
  16169. #define SQLITE_TRACE_XPROFILE 0
  16170. #endif /* SQLITE_OMIT_DEPRECATED */
  16171. #define SQLITE_TRACE_NONLEGACY_MASK 0x0f /* Normal flags */
  16172. /*
  16173. ** Each database connection is an instance of the following structure.
  16174. */
  16175. struct sqlite3 {
  16176. sqlite3_vfs *pVfs; /* OS Interface */
  16177. struct Vdbe *pVdbe; /* List of active virtual machines */
  16178. CollSeq *pDfltColl; /* BINARY collseq for the database encoding */
  16179. sqlite3_mutex *mutex; /* Connection mutex */
  16180. Db *aDb; /* All backends */
  16181. int nDb; /* Number of backends currently in use */
  16182. u32 mDbFlags; /* flags recording internal state */
  16183. u64 flags; /* flags settable by pragmas. See below */
  16184. i64 lastRowid; /* ROWID of most recent insert (see above) */
  16185. i64 szMmap; /* Default mmap_size setting */
  16186. u32 nSchemaLock; /* Do not reset the schema when non-zero */
  16187. unsigned int openFlags; /* Flags passed to sqlite3_vfs.xOpen() */
  16188. int errCode; /* Most recent error code (SQLITE_*) */
  16189. int errMask; /* & result codes with this before returning */
  16190. int iSysErrno; /* Errno value from last system error */
  16191. u16 dbOptFlags; /* Flags to enable/disable optimizations */
  16192. u8 enc; /* Text encoding */
  16193. u8 autoCommit; /* The auto-commit flag. */
  16194. u8 temp_store; /* 1: file 2: memory 0: default */
  16195. u8 mallocFailed; /* True if we have seen a malloc failure */
  16196. u8 bBenignMalloc; /* Do not require OOMs if true */
  16197. u8 dfltLockMode; /* Default locking-mode for attached dbs */
  16198. signed char nextAutovac; /* Autovac setting after VACUUM if >=0 */
  16199. u8 suppressErr; /* Do not issue error messages if true */
  16200. u8 vtabOnConflict; /* Value to return for s3_vtab_on_conflict() */
  16201. u8 isTransactionSavepoint; /* True if the outermost savepoint is a TS */
  16202. u8 mTrace; /* zero or more SQLITE_TRACE flags */
  16203. u8 noSharedCache; /* True if no shared-cache backends */
  16204. u8 nSqlExec; /* Number of pending OP_SqlExec opcodes */
  16205. int nextPagesize; /* Pagesize after VACUUM if >0 */
  16206. u32 magic; /* Magic number for detect library misuse */
  16207. int nChange; /* Value returned by sqlite3_changes() */
  16208. int nTotalChange; /* Value returned by sqlite3_total_changes() */
  16209. int aLimit[SQLITE_N_LIMIT]; /* Limits */
  16210. int nMaxSorterMmap; /* Maximum size of regions mapped by sorter */
  16211. struct sqlite3InitInfo { /* Information used during initialization */
  16212. int newTnum; /* Rootpage of table being initialized */
  16213. u8 iDb; /* Which db file is being initialized */
  16214. u8 busy; /* TRUE if currently initializing */
  16215. unsigned orphanTrigger : 1; /* Last statement is orphaned TEMP trigger */
  16216. unsigned imposterTable : 1; /* Building an imposter table */
  16217. unsigned reopenMemdb : 1; /* ATTACH is really a reopen using MemDB */
  16218. char **azInit; /* "type", "name", and "tbl_name" columns */
  16219. } init;
  16220. int nVdbeActive; /* Number of VDBEs currently running */
  16221. int nVdbeRead; /* Number of active VDBEs that read or write */
  16222. int nVdbeWrite; /* Number of active VDBEs that read and write */
  16223. int nVdbeExec; /* Number of nested calls to VdbeExec() */
  16224. int nVDestroy; /* Number of active OP_VDestroy operations */
  16225. int nExtension; /* Number of loaded extensions */
  16226. void **aExtension; /* Array of shared library handles */
  16227. int (*xTrace)(u32,void*,void*,void*); /* Trace function */
  16228. void *pTraceArg; /* Argument to the trace function */
  16229. #ifndef SQLITE_OMIT_DEPRECATED
  16230. void (*xProfile)(void*,const char*,u64); /* Profiling function */
  16231. void *pProfileArg; /* Argument to profile function */
  16232. #endif
  16233. void *pCommitArg; /* Argument to xCommitCallback() */
  16234. int (*xCommitCallback)(void*); /* Invoked at every commit. */
  16235. void *pRollbackArg; /* Argument to xRollbackCallback() */
  16236. void (*xRollbackCallback)(void*); /* Invoked at every commit. */
  16237. void *pUpdateArg;
  16238. void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
  16239. Parse *pParse; /* Current parse */
  16240. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  16241. void *pPreUpdateArg; /* First argument to xPreUpdateCallback */
  16242. void (*xPreUpdateCallback)( /* Registered using sqlite3_preupdate_hook() */
  16243. void*,sqlite3*,int,char const*,char const*,sqlite3_int64,sqlite3_int64
  16244. );
  16245. PreUpdate *pPreUpdate; /* Context for active pre-update callback */
  16246. #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
  16247. #ifndef SQLITE_OMIT_WAL
  16248. int (*xWalCallback)(void *, sqlite3 *, const char *, int);
  16249. void *pWalArg;
  16250. #endif
  16251. void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
  16252. void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
  16253. void *pCollNeededArg;
  16254. sqlite3_value *pErr; /* Most recent error message */
  16255. union {
  16256. volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
  16257. double notUsed1; /* Spacer */
  16258. } u1;
  16259. Lookaside lookaside; /* Lookaside malloc configuration */
  16260. #ifndef SQLITE_OMIT_AUTHORIZATION
  16261. sqlite3_xauth xAuth; /* Access authorization function */
  16262. void *pAuthArg; /* 1st argument to the access auth function */
  16263. #endif
  16264. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  16265. int (*xProgress)(void *); /* The progress callback */
  16266. void *pProgressArg; /* Argument to the progress callback */
  16267. unsigned nProgressOps; /* Number of opcodes for progress callback */
  16268. #endif
  16269. #ifndef SQLITE_OMIT_VIRTUALTABLE
  16270. int nVTrans; /* Allocated size of aVTrans */
  16271. Hash aModule; /* populated by sqlite3_create_module() */
  16272. VtabCtx *pVtabCtx; /* Context for active vtab connect/create */
  16273. VTable **aVTrans; /* Virtual tables with open transactions */
  16274. VTable *pDisconnect; /* Disconnect these in next sqlite3_prepare() */
  16275. #endif
  16276. Hash aFunc; /* Hash table of connection functions */
  16277. Hash aCollSeq; /* All collating sequences */
  16278. BusyHandler busyHandler; /* Busy callback */
  16279. Db aDbStatic[2]; /* Static space for the 2 default backends */
  16280. Savepoint *pSavepoint; /* List of active savepoints */
  16281. int nAnalysisLimit; /* Number of index rows to ANALYZE */
  16282. int busyTimeout; /* Busy handler timeout, in msec */
  16283. int nSavepoint; /* Number of non-transaction savepoints */
  16284. int nStatement; /* Number of nested statement-transactions */
  16285. i64 nDeferredCons; /* Net deferred constraints this transaction. */
  16286. i64 nDeferredImmCons; /* Net deferred immediate constraints */
  16287. int *pnBytesFreed; /* If not NULL, increment this in DbFree() */
  16288. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  16289. /* The following variables are all protected by the STATIC_MASTER
  16290. ** mutex, not by sqlite3.mutex. They are used by code in notify.c.
  16291. **
  16292. ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
  16293. ** unlock so that it can proceed.
  16294. **
  16295. ** When X.pBlockingConnection==Y, that means that something that X tried
  16296. ** tried to do recently failed with an SQLITE_LOCKED error due to locks
  16297. ** held by Y.
  16298. */
  16299. sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */
  16300. sqlite3 *pUnlockConnection; /* Connection to watch for unlock */
  16301. void *pUnlockArg; /* Argument to xUnlockNotify */
  16302. void (*xUnlockNotify)(void **, int); /* Unlock notify callback */
  16303. sqlite3 *pNextBlocked; /* Next in list of all blocked connections */
  16304. #endif
  16305. #ifdef SQLITE_USER_AUTHENTICATION
  16306. sqlite3_userauth auth; /* User authentication information */
  16307. #endif
  16308. };
  16309. /*
  16310. ** A macro to discover the encoding of a database.
  16311. */
  16312. #define SCHEMA_ENC(db) ((db)->aDb[0].pSchema->enc)
  16313. #define ENC(db) ((db)->enc)
  16314. /*
  16315. ** A u64 constant where the lower 32 bits are all zeros. Only the
  16316. ** upper 32 bits are included in the argument. Necessary because some
  16317. ** C-compilers still do not accept LL integer literals.
  16318. */
  16319. #define HI(X) ((u64)(X)<<32)
  16320. /*
  16321. ** Possible values for the sqlite3.flags.
  16322. **
  16323. ** Value constraints (enforced via assert()):
  16324. ** SQLITE_FullFSync == PAGER_FULLFSYNC
  16325. ** SQLITE_CkptFullFSync == PAGER_CKPT_FULLFSYNC
  16326. ** SQLITE_CacheSpill == PAGER_CACHE_SPILL
  16327. */
  16328. #define SQLITE_WriteSchema 0x00000001 /* OK to update SQLITE_MASTER */
  16329. #define SQLITE_LegacyFileFmt 0x00000002 /* Create new databases in format 1 */
  16330. #define SQLITE_FullColNames 0x00000004 /* Show full column names on SELECT */
  16331. #define SQLITE_FullFSync 0x00000008 /* Use full fsync on the backend */
  16332. #define SQLITE_CkptFullFSync 0x00000010 /* Use full fsync for checkpoint */
  16333. #define SQLITE_CacheSpill 0x00000020 /* OK to spill pager cache */
  16334. #define SQLITE_ShortColNames 0x00000040 /* Show short columns names */
  16335. #define SQLITE_TrustedSchema 0x00000080 /* Allow unsafe functions and
  16336. ** vtabs in the schema definition */
  16337. #define SQLITE_NullCallback 0x00000100 /* Invoke the callback once if the */
  16338. /* result set is empty */
  16339. #define SQLITE_IgnoreChecks 0x00000200 /* Do not enforce check constraints */
  16340. #define SQLITE_ReadUncommit 0x00000400 /* READ UNCOMMITTED in shared-cache */
  16341. #define SQLITE_NoCkptOnClose 0x00000800 /* No checkpoint on close()/DETACH */
  16342. #define SQLITE_ReverseOrder 0x00001000 /* Reverse unordered SELECTs */
  16343. #define SQLITE_RecTriggers 0x00002000 /* Enable recursive triggers */
  16344. #define SQLITE_ForeignKeys 0x00004000 /* Enforce foreign key constraints */
  16345. #define SQLITE_AutoIndex 0x00008000 /* Enable automatic indexes */
  16346. #define SQLITE_LoadExtension 0x00010000 /* Enable load_extension */
  16347. #define SQLITE_LoadExtFunc 0x00020000 /* Enable load_extension() SQL func */
  16348. #define SQLITE_EnableTrigger 0x00040000 /* True to enable triggers */
  16349. #define SQLITE_DeferFKs 0x00080000 /* Defer all FK constraints */
  16350. #define SQLITE_QueryOnly 0x00100000 /* Disable database changes */
  16351. #define SQLITE_CellSizeCk 0x00200000 /* Check btree cell sizes on load */
  16352. #define SQLITE_Fts3Tokenizer 0x00400000 /* Enable fts3_tokenizer(2) */
  16353. #define SQLITE_EnableQPSG 0x00800000 /* Query Planner Stability Guarantee*/
  16354. #define SQLITE_TriggerEQP 0x01000000 /* Show trigger EXPLAIN QUERY PLAN */
  16355. #define SQLITE_ResetDatabase 0x02000000 /* Reset the database */
  16356. #define SQLITE_LegacyAlter 0x04000000 /* Legacy ALTER TABLE behaviour */
  16357. #define SQLITE_NoSchemaError 0x08000000 /* Do not report schema parse errors*/
  16358. #define SQLITE_Defensive 0x10000000 /* Input SQL is likely hostile */
  16359. #define SQLITE_DqsDDL 0x20000000 /* dbl-quoted strings allowed in DDL*/
  16360. #define SQLITE_DqsDML 0x40000000 /* dbl-quoted strings allowed in DML*/
  16361. #define SQLITE_EnableView 0x80000000 /* Enable the use of views */
  16362. #define SQLITE_CountRows HI(0x00001) /* Count rows changed by INSERT, */
  16363. /* DELETE, or UPDATE and return */
  16364. /* the count using a callback. */
  16365. /* Flags used only if debugging */
  16366. #ifdef SQLITE_DEBUG
  16367. #define SQLITE_SqlTrace HI(0x0100000) /* Debug print SQL as it executes */
  16368. #define SQLITE_VdbeListing HI(0x0200000) /* Debug listings of VDBE progs */
  16369. #define SQLITE_VdbeTrace HI(0x0400000) /* True to trace VDBE execution */
  16370. #define SQLITE_VdbeAddopTrace HI(0x0800000) /* Trace sqlite3VdbeAddOp() calls */
  16371. #define SQLITE_VdbeEQP HI(0x1000000) /* Debug EXPLAIN QUERY PLAN */
  16372. #define SQLITE_ParserTrace HI(0x2000000) /* PRAGMA parser_trace=ON */
  16373. #endif
  16374. /*
  16375. ** Allowed values for sqlite3.mDbFlags
  16376. */
  16377. #define DBFLAG_SchemaChange 0x0001 /* Uncommitted Hash table changes */
  16378. #define DBFLAG_PreferBuiltin 0x0002 /* Preference to built-in funcs */
  16379. #define DBFLAG_Vacuum 0x0004 /* Currently in a VACUUM */
  16380. #define DBFLAG_VacuumInto 0x0008 /* Currently running VACUUM INTO */
  16381. #define DBFLAG_SchemaKnownOk 0x0010 /* Schema is known to be valid */
  16382. #define DBFLAG_InternalFunc 0x0020 /* Allow use of internal functions */
  16383. #define DBFLAG_EncodingFixed 0x0040 /* No longer possible to change enc. */
  16384. /*
  16385. ** Bits of the sqlite3.dbOptFlags field that are used by the
  16386. ** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface to
  16387. ** selectively disable various optimizations.
  16388. */
  16389. #define SQLITE_QueryFlattener 0x0001 /* Query flattening */
  16390. #define SQLITE_WindowFunc 0x0002 /* Use xInverse for window functions */
  16391. #define SQLITE_GroupByOrder 0x0004 /* GROUPBY cover of ORDERBY */
  16392. #define SQLITE_FactorOutConst 0x0008 /* Constant factoring */
  16393. #define SQLITE_DistinctOpt 0x0010 /* DISTINCT using indexes */
  16394. #define SQLITE_CoverIdxScan 0x0020 /* Covering index scans */
  16395. #define SQLITE_OrderByIdxJoin 0x0040 /* ORDER BY of joins via index */
  16396. #define SQLITE_Transitive 0x0080 /* Transitive constraints */
  16397. #define SQLITE_OmitNoopJoin 0x0100 /* Omit unused tables in joins */
  16398. #define SQLITE_CountOfView 0x0200 /* The count-of-view optimization */
  16399. #define SQLITE_CursorHints 0x0400 /* Add OP_CursorHint opcodes */
  16400. #define SQLITE_Stat4 0x0800 /* Use STAT4 data */
  16401. /* TH3 expects the Stat4 ^^^^^^ value to be 0x0800. Don't change it */
  16402. #define SQLITE_PushDown 0x1000 /* The push-down optimization */
  16403. #define SQLITE_SimplifyJoin 0x2000 /* Convert LEFT JOIN to JOIN */
  16404. #define SQLITE_SkipScan 0x4000 /* Skip-scans */
  16405. #define SQLITE_PropagateConst 0x8000 /* The constant propagation opt */
  16406. #define SQLITE_AllOpts 0xffff /* All optimizations */
  16407. /*
  16408. ** Macros for testing whether or not optimizations are enabled or disabled.
  16409. */
  16410. #define OptimizationDisabled(db, mask) (((db)->dbOptFlags&(mask))!=0)
  16411. #define OptimizationEnabled(db, mask) (((db)->dbOptFlags&(mask))==0)
  16412. /*
  16413. ** Return true if it OK to factor constant expressions into the initialization
  16414. ** code. The argument is a Parse object for the code generator.
  16415. */
  16416. #define ConstFactorOk(P) ((P)->okConstFactor)
  16417. /*
  16418. ** Possible values for the sqlite.magic field.
  16419. ** The numbers are obtained at random and have no special meaning, other
  16420. ** than being distinct from one another.
  16421. */
  16422. #define SQLITE_MAGIC_OPEN 0xa029a697 /* Database is open */
  16423. #define SQLITE_MAGIC_CLOSED 0x9f3c2d33 /* Database is closed */
  16424. #define SQLITE_MAGIC_SICK 0x4b771290 /* Error and awaiting close */
  16425. #define SQLITE_MAGIC_BUSY 0xf03b7906 /* Database currently in use */
  16426. #define SQLITE_MAGIC_ERROR 0xb5357930 /* An SQLITE_MISUSE error occurred */
  16427. #define SQLITE_MAGIC_ZOMBIE 0x64cffc7f /* Close with last statement close */
  16428. /*
  16429. ** Each SQL function is defined by an instance of the following
  16430. ** structure. For global built-in functions (ex: substr(), max(), count())
  16431. ** a pointer to this structure is held in the sqlite3BuiltinFunctions object.
  16432. ** For per-connection application-defined functions, a pointer to this
  16433. ** structure is held in the db->aHash hash table.
  16434. **
  16435. ** The u.pHash field is used by the global built-ins. The u.pDestructor
  16436. ** field is used by per-connection app-def functions.
  16437. */
  16438. struct FuncDef {
  16439. i8 nArg; /* Number of arguments. -1 means unlimited */
  16440. u32 funcFlags; /* Some combination of SQLITE_FUNC_* */
  16441. void *pUserData; /* User data parameter */
  16442. FuncDef *pNext; /* Next function with same name */
  16443. void (*xSFunc)(sqlite3_context*,int,sqlite3_value**); /* func or agg-step */
  16444. void (*xFinalize)(sqlite3_context*); /* Agg finalizer */
  16445. void (*xValue)(sqlite3_context*); /* Current agg value */
  16446. void (*xInverse)(sqlite3_context*,int,sqlite3_value**); /* inverse agg-step */
  16447. const char *zName; /* SQL name of the function. */
  16448. union {
  16449. FuncDef *pHash; /* Next with a different name but the same hash */
  16450. FuncDestructor *pDestructor; /* Reference counted destructor function */
  16451. } u;
  16452. };
  16453. /*
  16454. ** This structure encapsulates a user-function destructor callback (as
  16455. ** configured using create_function_v2()) and a reference counter. When
  16456. ** create_function_v2() is called to create a function with a destructor,
  16457. ** a single object of this type is allocated. FuncDestructor.nRef is set to
  16458. ** the number of FuncDef objects created (either 1 or 3, depending on whether
  16459. ** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor
  16460. ** member of each of the new FuncDef objects is set to point to the allocated
  16461. ** FuncDestructor.
  16462. **
  16463. ** Thereafter, when one of the FuncDef objects is deleted, the reference
  16464. ** count on this object is decremented. When it reaches 0, the destructor
  16465. ** is invoked and the FuncDestructor structure freed.
  16466. */
  16467. struct FuncDestructor {
  16468. int nRef;
  16469. void (*xDestroy)(void *);
  16470. void *pUserData;
  16471. };
  16472. /*
  16473. ** Possible values for FuncDef.flags. Note that the _LENGTH and _TYPEOF
  16474. ** values must correspond to OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG. And
  16475. ** SQLITE_FUNC_CONSTANT must be the same as SQLITE_DETERMINISTIC. There
  16476. ** are assert() statements in the code to verify this.
  16477. **
  16478. ** Value constraints (enforced via assert()):
  16479. ** SQLITE_FUNC_MINMAX == NC_MinMaxAgg == SF_MinMaxAgg
  16480. ** SQLITE_FUNC_LENGTH == OPFLAG_LENGTHARG
  16481. ** SQLITE_FUNC_TYPEOF == OPFLAG_TYPEOFARG
  16482. ** SQLITE_FUNC_CONSTANT == SQLITE_DETERMINISTIC from the API
  16483. ** SQLITE_FUNC_DIRECT == SQLITE_DIRECTONLY from the API
  16484. ** SQLITE_FUNC_UNSAFE == SQLITE_INNOCUOUS
  16485. ** SQLITE_FUNC_ENCMASK depends on SQLITE_UTF* macros in the API
  16486. */
  16487. #define SQLITE_FUNC_ENCMASK 0x0003 /* SQLITE_UTF8, SQLITE_UTF16BE or UTF16LE */
  16488. #define SQLITE_FUNC_LIKE 0x0004 /* Candidate for the LIKE optimization */
  16489. #define SQLITE_FUNC_CASE 0x0008 /* Case-sensitive LIKE-type function */
  16490. #define SQLITE_FUNC_EPHEM 0x0010 /* Ephemeral. Delete with VDBE */
  16491. #define SQLITE_FUNC_NEEDCOLL 0x0020 /* sqlite3GetFuncCollSeq() might be called*/
  16492. #define SQLITE_FUNC_LENGTH 0x0040 /* Built-in length() function */
  16493. #define SQLITE_FUNC_TYPEOF 0x0080 /* Built-in typeof() function */
  16494. #define SQLITE_FUNC_COUNT 0x0100 /* Built-in count(*) aggregate */
  16495. /* 0x0200 -- available for reuse */
  16496. #define SQLITE_FUNC_UNLIKELY 0x0400 /* Built-in unlikely() function */
  16497. #define SQLITE_FUNC_CONSTANT 0x0800 /* Constant inputs give a constant output */
  16498. #define SQLITE_FUNC_MINMAX 0x1000 /* True for min() and max() aggregates */
  16499. #define SQLITE_FUNC_SLOCHNG 0x2000 /* "Slow Change". Value constant during a
  16500. ** single query - might change over time */
  16501. #define SQLITE_FUNC_TEST 0x4000 /* Built-in testing functions */
  16502. #define SQLITE_FUNC_OFFSET 0x8000 /* Built-in sqlite_offset() function */
  16503. #define SQLITE_FUNC_WINDOW 0x00010000 /* Built-in window-only function */
  16504. #define SQLITE_FUNC_INTERNAL 0x00040000 /* For use by NestedParse() only */
  16505. #define SQLITE_FUNC_DIRECT 0x00080000 /* Not for use in TRIGGERs or VIEWs */
  16506. #define SQLITE_FUNC_SUBTYPE 0x00100000 /* Result likely to have sub-type */
  16507. #define SQLITE_FUNC_UNSAFE 0x00200000 /* Function has side effects */
  16508. #define SQLITE_FUNC_INLINE 0x00400000 /* Functions implemented in-line */
  16509. /* Identifier numbers for each in-line function */
  16510. #define INLINEFUNC_coalesce 0
  16511. #define INLINEFUNC_implies_nonnull_row 1
  16512. #define INLINEFUNC_expr_implies_expr 2
  16513. #define INLINEFUNC_expr_compare 3
  16514. #define INLINEFUNC_affinity 4
  16515. #define INLINEFUNC_iif 5
  16516. #define INLINEFUNC_unlikely 99 /* Default case */
  16517. /*
  16518. ** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
  16519. ** used to create the initializers for the FuncDef structures.
  16520. **
  16521. ** FUNCTION(zName, nArg, iArg, bNC, xFunc)
  16522. ** Used to create a scalar function definition of a function zName
  16523. ** implemented by C function xFunc that accepts nArg arguments. The
  16524. ** value passed as iArg is cast to a (void*) and made available
  16525. ** as the user-data (sqlite3_user_data()) for the function. If
  16526. ** argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set.
  16527. **
  16528. ** VFUNCTION(zName, nArg, iArg, bNC, xFunc)
  16529. ** Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag.
  16530. **
  16531. ** SFUNCTION(zName, nArg, iArg, bNC, xFunc)
  16532. ** Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag and
  16533. ** adds the SQLITE_DIRECTONLY flag.
  16534. **
  16535. ** INLINE_FUNC(zName, nArg, iFuncId, mFlags)
  16536. ** zName is the name of a function that is implemented by in-line
  16537. ** byte code rather than by the usual callbacks. The iFuncId
  16538. ** parameter determines the function id. The mFlags parameter is
  16539. ** optional SQLITE_FUNC_ flags for this function.
  16540. **
  16541. ** TEST_FUNC(zName, nArg, iFuncId, mFlags)
  16542. ** zName is the name of a test-only function implemented by in-line
  16543. ** byte code rather than by the usual callbacks. The iFuncId
  16544. ** parameter determines the function id. The mFlags parameter is
  16545. ** optional SQLITE_FUNC_ flags for this function.
  16546. **
  16547. ** DFUNCTION(zName, nArg, iArg, bNC, xFunc)
  16548. ** Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag and
  16549. ** adds the SQLITE_FUNC_SLOCHNG flag. Used for date & time functions
  16550. ** and functions like sqlite_version() that can change, but not during
  16551. ** a single query. The iArg is ignored. The user-data is always set
  16552. ** to a NULL pointer. The bNC parameter is not used.
  16553. **
  16554. ** PURE_DATE(zName, nArg, iArg, bNC, xFunc)
  16555. ** Used for "pure" date/time functions, this macro is like DFUNCTION
  16556. ** except that it does set the SQLITE_FUNC_CONSTANT flags. iArg is
  16557. ** ignored and the user-data for these functions is set to an
  16558. ** arbitrary non-NULL pointer. The bNC parameter is not used.
  16559. **
  16560. ** AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
  16561. ** Used to create an aggregate function definition implemented by
  16562. ** the C functions xStep and xFinal. The first four parameters
  16563. ** are interpreted in the same way as the first 4 parameters to
  16564. ** FUNCTION().
  16565. **
  16566. ** WFUNCTION(zName, nArg, iArg, xStep, xFinal, xValue, xInverse)
  16567. ** Used to create an aggregate function definition implemented by
  16568. ** the C functions xStep and xFinal. The first four parameters
  16569. ** are interpreted in the same way as the first 4 parameters to
  16570. ** FUNCTION().
  16571. **
  16572. ** LIKEFUNC(zName, nArg, pArg, flags)
  16573. ** Used to create a scalar function definition of a function zName
  16574. ** that accepts nArg arguments and is implemented by a call to C
  16575. ** function likeFunc. Argument pArg is cast to a (void *) and made
  16576. ** available as the function user-data (sqlite3_user_data()). The
  16577. ** FuncDef.flags variable is set to the value passed as the flags
  16578. ** parameter.
  16579. */
  16580. #define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
  16581. {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
  16582. SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, 0, #zName, {0} }
  16583. #define VFUNCTION(zName, nArg, iArg, bNC, xFunc) \
  16584. {nArg, SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
  16585. SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, 0, #zName, {0} }
  16586. #define SFUNCTION(zName, nArg, iArg, bNC, xFunc) \
  16587. {nArg, SQLITE_UTF8|SQLITE_DIRECTONLY|SQLITE_FUNC_UNSAFE, \
  16588. SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, 0, #zName, {0} }
  16589. #define INLINE_FUNC(zName, nArg, iArg, mFlags) \
  16590. {nArg, SQLITE_UTF8|SQLITE_FUNC_INLINE|SQLITE_FUNC_CONSTANT|(mFlags), \
  16591. SQLITE_INT_TO_PTR(iArg), 0, noopFunc, 0, 0, 0, #zName, {0} }
  16592. #define TEST_FUNC(zName, nArg, iArg, mFlags) \
  16593. {nArg, SQLITE_UTF8|SQLITE_FUNC_INTERNAL|SQLITE_FUNC_TEST| \
  16594. SQLITE_FUNC_INLINE|SQLITE_FUNC_CONSTANT|(mFlags), \
  16595. SQLITE_INT_TO_PTR(iArg), 0, noopFunc, 0, 0, 0, #zName, {0} }
  16596. #define DFUNCTION(zName, nArg, iArg, bNC, xFunc) \
  16597. {nArg, SQLITE_FUNC_SLOCHNG|SQLITE_UTF8, \
  16598. 0, 0, xFunc, 0, 0, 0, #zName, {0} }
  16599. #define PURE_DATE(zName, nArg, iArg, bNC, xFunc) \
  16600. {nArg, SQLITE_FUNC_SLOCHNG|SQLITE_UTF8|SQLITE_FUNC_CONSTANT, \
  16601. (void*)&sqlite3Config, 0, xFunc, 0, 0, 0, #zName, {0} }
  16602. #define FUNCTION2(zName, nArg, iArg, bNC, xFunc, extraFlags) \
  16603. {nArg,SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL)|extraFlags,\
  16604. SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, 0, #zName, {0} }
  16605. #define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
  16606. {nArg, SQLITE_FUNC_SLOCHNG|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
  16607. pArg, 0, xFunc, 0, 0, 0, #zName, }
  16608. #define LIKEFUNC(zName, nArg, arg, flags) \
  16609. {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|flags, \
  16610. (void *)arg, 0, likeFunc, 0, 0, 0, #zName, {0} }
  16611. #define WAGGREGATE(zName, nArg, arg, nc, xStep, xFinal, xValue, xInverse, f) \
  16612. {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL)|f, \
  16613. SQLITE_INT_TO_PTR(arg), 0, xStep,xFinal,xValue,xInverse,#zName, {0}}
  16614. #define INTERNAL_FUNCTION(zName, nArg, xFunc) \
  16615. {nArg, SQLITE_FUNC_INTERNAL|SQLITE_UTF8|SQLITE_FUNC_CONSTANT, \
  16616. 0, 0, xFunc, 0, 0, 0, #zName, {0} }
  16617. /*
  16618. ** All current savepoints are stored in a linked list starting at
  16619. ** sqlite3.pSavepoint. The first element in the list is the most recently
  16620. ** opened savepoint. Savepoints are added to the list by the vdbe
  16621. ** OP_Savepoint instruction.
  16622. */
  16623. struct Savepoint {
  16624. char *zName; /* Savepoint name (nul-terminated) */
  16625. i64 nDeferredCons; /* Number of deferred fk violations */
  16626. i64 nDeferredImmCons; /* Number of deferred imm fk. */
  16627. Savepoint *pNext; /* Parent savepoint (if any) */
  16628. };
  16629. /*
  16630. ** The following are used as the second parameter to sqlite3Savepoint(),
  16631. ** and as the P1 argument to the OP_Savepoint instruction.
  16632. */
  16633. #define SAVEPOINT_BEGIN 0
  16634. #define SAVEPOINT_RELEASE 1
  16635. #define SAVEPOINT_ROLLBACK 2
  16636. /*
  16637. ** Each SQLite module (virtual table definition) is defined by an
  16638. ** instance of the following structure, stored in the sqlite3.aModule
  16639. ** hash table.
  16640. */
  16641. struct Module {
  16642. const sqlite3_module *pModule; /* Callback pointers */
  16643. const char *zName; /* Name passed to create_module() */
  16644. int nRefModule; /* Number of pointers to this object */
  16645. void *pAux; /* pAux passed to create_module() */
  16646. void (*xDestroy)(void *); /* Module destructor function */
  16647. Table *pEpoTab; /* Eponymous table for this module */
  16648. };
  16649. /*
  16650. ** Information about each column of an SQL table is held in an instance
  16651. ** of the Column structure, in the Table.aCol[] array.
  16652. **
  16653. ** Definitions:
  16654. **
  16655. ** "table column index" This is the index of the column in the
  16656. ** Table.aCol[] array, and also the index of
  16657. ** the column in the original CREATE TABLE stmt.
  16658. **
  16659. ** "storage column index" This is the index of the column in the
  16660. ** record BLOB generated by the OP_MakeRecord
  16661. ** opcode. The storage column index is less than
  16662. ** or equal to the table column index. It is
  16663. ** equal if and only if there are no VIRTUAL
  16664. ** columns to the left.
  16665. */
  16666. struct Column {
  16667. char *zName; /* Name of this column, \000, then the type */
  16668. Expr *pDflt; /* Default value or GENERATED ALWAYS AS value */
  16669. char *zColl; /* Collating sequence. If NULL, use the default */
  16670. u8 notNull; /* An OE_ code for handling a NOT NULL constraint */
  16671. char affinity; /* One of the SQLITE_AFF_... values */
  16672. u8 szEst; /* Estimated size of value in this column. sizeof(INT)==1 */
  16673. u8 hName; /* Column name hash for faster lookup */
  16674. u16 colFlags; /* Boolean properties. See COLFLAG_ defines below */
  16675. };
  16676. /* Allowed values for Column.colFlags:
  16677. */
  16678. #define COLFLAG_PRIMKEY 0x0001 /* Column is part of the primary key */
  16679. #define COLFLAG_HIDDEN 0x0002 /* A hidden column in a virtual table */
  16680. #define COLFLAG_HASTYPE 0x0004 /* Type name follows column name */
  16681. #define COLFLAG_UNIQUE 0x0008 /* Column def contains "UNIQUE" or "PK" */
  16682. #define COLFLAG_SORTERREF 0x0010 /* Use sorter-refs with this column */
  16683. #define COLFLAG_VIRTUAL 0x0020 /* GENERATED ALWAYS AS ... VIRTUAL */
  16684. #define COLFLAG_STORED 0x0040 /* GENERATED ALWAYS AS ... STORED */
  16685. #define COLFLAG_NOTAVAIL 0x0080 /* STORED column not yet calculated */
  16686. #define COLFLAG_BUSY 0x0100 /* Blocks recursion on GENERATED columns */
  16687. #define COLFLAG_GENERATED 0x0060 /* Combo: _STORED, _VIRTUAL */
  16688. #define COLFLAG_NOINSERT 0x0062 /* Combo: _HIDDEN, _STORED, _VIRTUAL */
  16689. /*
  16690. ** A "Collating Sequence" is defined by an instance of the following
  16691. ** structure. Conceptually, a collating sequence consists of a name and
  16692. ** a comparison routine that defines the order of that sequence.
  16693. **
  16694. ** If CollSeq.xCmp is NULL, it means that the
  16695. ** collating sequence is undefined. Indices built on an undefined
  16696. ** collating sequence may not be read or written.
  16697. */
  16698. struct CollSeq {
  16699. char *zName; /* Name of the collating sequence, UTF-8 encoded */
  16700. u8 enc; /* Text encoding handled by xCmp() */
  16701. void *pUser; /* First argument to xCmp() */
  16702. int (*xCmp)(void*,int, const void*, int, const void*);
  16703. void (*xDel)(void*); /* Destructor for pUser */
  16704. };
  16705. /*
  16706. ** A sort order can be either ASC or DESC.
  16707. */
  16708. #define SQLITE_SO_ASC 0 /* Sort in ascending order */
  16709. #define SQLITE_SO_DESC 1 /* Sort in ascending order */
  16710. #define SQLITE_SO_UNDEFINED -1 /* No sort order specified */
  16711. /*
  16712. ** Column affinity types.
  16713. **
  16714. ** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
  16715. ** 't' for SQLITE_AFF_TEXT. But we can save a little space and improve
  16716. ** the speed a little by numbering the values consecutively.
  16717. **
  16718. ** But rather than start with 0 or 1, we begin with 'A'. That way,
  16719. ** when multiple affinity types are concatenated into a string and
  16720. ** used as the P4 operand, they will be more readable.
  16721. **
  16722. ** Note also that the numeric types are grouped together so that testing
  16723. ** for a numeric type is a single comparison. And the BLOB type is first.
  16724. */
  16725. #define SQLITE_AFF_NONE 0x40 /* '@' */
  16726. #define SQLITE_AFF_BLOB 0x41 /* 'A' */
  16727. #define SQLITE_AFF_TEXT 0x42 /* 'B' */
  16728. #define SQLITE_AFF_NUMERIC 0x43 /* 'C' */
  16729. #define SQLITE_AFF_INTEGER 0x44 /* 'D' */
  16730. #define SQLITE_AFF_REAL 0x45 /* 'E' */
  16731. #define sqlite3IsNumericAffinity(X) ((X)>=SQLITE_AFF_NUMERIC)
  16732. /*
  16733. ** The SQLITE_AFF_MASK values masks off the significant bits of an
  16734. ** affinity value.
  16735. */
  16736. #define SQLITE_AFF_MASK 0x47
  16737. /*
  16738. ** Additional bit values that can be ORed with an affinity without
  16739. ** changing the affinity.
  16740. **
  16741. ** The SQLITE_NOTNULL flag is a combination of NULLEQ and JUMPIFNULL.
  16742. ** It causes an assert() to fire if either operand to a comparison
  16743. ** operator is NULL. It is added to certain comparison operators to
  16744. ** prove that the operands are always NOT NULL.
  16745. */
  16746. #define SQLITE_KEEPNULL 0x08 /* Used by vector == or <> */
  16747. #define SQLITE_JUMPIFNULL 0x10 /* jumps if either operand is NULL */
  16748. #define SQLITE_STOREP2 0x20 /* Store result in reg[P2] rather than jump */
  16749. #define SQLITE_NULLEQ 0x80 /* NULL=NULL */
  16750. #define SQLITE_NOTNULL 0x90 /* Assert that operands are never NULL */
  16751. /*
  16752. ** An object of this type is created for each virtual table present in
  16753. ** the database schema.
  16754. **
  16755. ** If the database schema is shared, then there is one instance of this
  16756. ** structure for each database connection (sqlite3*) that uses the shared
  16757. ** schema. This is because each database connection requires its own unique
  16758. ** instance of the sqlite3_vtab* handle used to access the virtual table
  16759. ** implementation. sqlite3_vtab* handles can not be shared between
  16760. ** database connections, even when the rest of the in-memory database
  16761. ** schema is shared, as the implementation often stores the database
  16762. ** connection handle passed to it via the xConnect() or xCreate() method
  16763. ** during initialization internally. This database connection handle may
  16764. ** then be used by the virtual table implementation to access real tables
  16765. ** within the database. So that they appear as part of the callers
  16766. ** transaction, these accesses need to be made via the same database
  16767. ** connection as that used to execute SQL operations on the virtual table.
  16768. **
  16769. ** All VTable objects that correspond to a single table in a shared
  16770. ** database schema are initially stored in a linked-list pointed to by
  16771. ** the Table.pVTable member variable of the corresponding Table object.
  16772. ** When an sqlite3_prepare() operation is required to access the virtual
  16773. ** table, it searches the list for the VTable that corresponds to the
  16774. ** database connection doing the preparing so as to use the correct
  16775. ** sqlite3_vtab* handle in the compiled query.
  16776. **
  16777. ** When an in-memory Table object is deleted (for example when the
  16778. ** schema is being reloaded for some reason), the VTable objects are not
  16779. ** deleted and the sqlite3_vtab* handles are not xDisconnect()ed
  16780. ** immediately. Instead, they are moved from the Table.pVTable list to
  16781. ** another linked list headed by the sqlite3.pDisconnect member of the
  16782. ** corresponding sqlite3 structure. They are then deleted/xDisconnected
  16783. ** next time a statement is prepared using said sqlite3*. This is done
  16784. ** to avoid deadlock issues involving multiple sqlite3.mutex mutexes.
  16785. ** Refer to comments above function sqlite3VtabUnlockList() for an
  16786. ** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect
  16787. ** list without holding the corresponding sqlite3.mutex mutex.
  16788. **
  16789. ** The memory for objects of this type is always allocated by
  16790. ** sqlite3DbMalloc(), using the connection handle stored in VTable.db as
  16791. ** the first argument.
  16792. */
  16793. struct VTable {
  16794. sqlite3 *db; /* Database connection associated with this table */
  16795. Module *pMod; /* Pointer to module implementation */
  16796. sqlite3_vtab *pVtab; /* Pointer to vtab instance */
  16797. int nRef; /* Number of pointers to this structure */
  16798. u8 bConstraint; /* True if constraints are supported */
  16799. u8 eVtabRisk; /* Riskiness of allowing hacker access */
  16800. int iSavepoint; /* Depth of the SAVEPOINT stack */
  16801. VTable *pNext; /* Next in linked list (see above) */
  16802. };
  16803. /* Allowed values for VTable.eVtabRisk
  16804. */
  16805. #define SQLITE_VTABRISK_Low 0
  16806. #define SQLITE_VTABRISK_Normal 1
  16807. #define SQLITE_VTABRISK_High 2
  16808. /*
  16809. ** The schema for each SQL table and view is represented in memory
  16810. ** by an instance of the following structure.
  16811. */
  16812. struct Table {
  16813. char *zName; /* Name of the table or view */
  16814. Column *aCol; /* Information about each column */
  16815. Index *pIndex; /* List of SQL indexes on this table. */
  16816. Select *pSelect; /* NULL for tables. Points to definition if a view. */
  16817. FKey *pFKey; /* Linked list of all foreign keys in this table */
  16818. char *zColAff; /* String defining the affinity of each column */
  16819. ExprList *pCheck; /* All CHECK constraints */
  16820. /* ... also used as column name list in a VIEW */
  16821. int tnum; /* Root BTree page for this table */
  16822. u32 nTabRef; /* Number of pointers to this Table */
  16823. u32 tabFlags; /* Mask of TF_* values */
  16824. i16 iPKey; /* If not negative, use aCol[iPKey] as the rowid */
  16825. i16 nCol; /* Number of columns in this table */
  16826. i16 nNVCol; /* Number of columns that are not VIRTUAL */
  16827. LogEst nRowLogEst; /* Estimated rows in table - from sqlite_stat1 table */
  16828. LogEst szTabRow; /* Estimated size of each table row in bytes */
  16829. #ifdef SQLITE_ENABLE_COSTMULT
  16830. LogEst costMult; /* Cost multiplier for using this table */
  16831. #endif
  16832. u8 keyConf; /* What to do in case of uniqueness conflict on iPKey */
  16833. #ifndef SQLITE_OMIT_ALTERTABLE
  16834. int addColOffset; /* Offset in CREATE TABLE stmt to add a new column */
  16835. #endif
  16836. #ifndef SQLITE_OMIT_VIRTUALTABLE
  16837. int nModuleArg; /* Number of arguments to the module */
  16838. char **azModuleArg; /* 0: module 1: schema 2: vtab name 3...: args */
  16839. VTable *pVTable; /* List of VTable objects. */
  16840. #endif
  16841. Trigger *pTrigger; /* List of triggers stored in pSchema */
  16842. Schema *pSchema; /* Schema that contains this table */
  16843. Table *pNextZombie; /* Next on the Parse.pZombieTab list */
  16844. };
  16845. /*
  16846. ** Allowed values for Table.tabFlags.
  16847. **
  16848. ** TF_OOOHidden applies to tables or view that have hidden columns that are
  16849. ** followed by non-hidden columns. Example: "CREATE VIRTUAL TABLE x USING
  16850. ** vtab1(a HIDDEN, b);". Since "b" is a non-hidden column but "a" is hidden,
  16851. ** the TF_OOOHidden attribute would apply in this case. Such tables require
  16852. ** special handling during INSERT processing. The "OOO" means "Out Of Order".
  16853. **
  16854. ** Constraints:
  16855. **
  16856. ** TF_HasVirtual == COLFLAG_Virtual
  16857. ** TF_HasStored == COLFLAG_Stored
  16858. */
  16859. #define TF_Readonly 0x0001 /* Read-only system table */
  16860. #define TF_Ephemeral 0x0002 /* An ephemeral table */
  16861. #define TF_HasPrimaryKey 0x0004 /* Table has a primary key */
  16862. #define TF_Autoincrement 0x0008 /* Integer primary key is autoincrement */
  16863. #define TF_HasStat1 0x0010 /* nRowLogEst set from sqlite_stat1 */
  16864. #define TF_HasVirtual 0x0020 /* Has one or more VIRTUAL columns */
  16865. #define TF_HasStored 0x0040 /* Has one or more STORED columns */
  16866. #define TF_HasGenerated 0x0060 /* Combo: HasVirtual + HasStored */
  16867. #define TF_WithoutRowid 0x0080 /* No rowid. PRIMARY KEY is the key */
  16868. #define TF_StatsUsed 0x0100 /* Query planner decisions affected by
  16869. ** Index.aiRowLogEst[] values */
  16870. #define TF_NoVisibleRowid 0x0200 /* No user-visible "rowid" column */
  16871. #define TF_OOOHidden 0x0400 /* Out-of-Order hidden columns */
  16872. #define TF_HasNotNull 0x0800 /* Contains NOT NULL constraints */
  16873. #define TF_Shadow 0x1000 /* True for a shadow table */
  16874. /*
  16875. ** Test to see whether or not a table is a virtual table. This is
  16876. ** done as a macro so that it will be optimized out when virtual
  16877. ** table support is omitted from the build.
  16878. */
  16879. #ifndef SQLITE_OMIT_VIRTUALTABLE
  16880. # define IsVirtual(X) ((X)->nModuleArg)
  16881. # define ExprIsVtab(X) \
  16882. ((X)->op==TK_COLUMN && (X)->y.pTab!=0 && (X)->y.pTab->nModuleArg)
  16883. #else
  16884. # define IsVirtual(X) 0
  16885. # define ExprIsVtab(X) 0
  16886. #endif
  16887. /*
  16888. ** Macros to determine if a column is hidden. IsOrdinaryHiddenColumn()
  16889. ** only works for non-virtual tables (ordinary tables and views) and is
  16890. ** always false unless SQLITE_ENABLE_HIDDEN_COLUMNS is defined. The
  16891. ** IsHiddenColumn() macro is general purpose.
  16892. */
  16893. #if defined(SQLITE_ENABLE_HIDDEN_COLUMNS)
  16894. # define IsHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
  16895. # define IsOrdinaryHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
  16896. #elif !defined(SQLITE_OMIT_VIRTUALTABLE)
  16897. # define IsHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
  16898. # define IsOrdinaryHiddenColumn(X) 0
  16899. #else
  16900. # define IsHiddenColumn(X) 0
  16901. # define IsOrdinaryHiddenColumn(X) 0
  16902. #endif
  16903. /* Does the table have a rowid */
  16904. #define HasRowid(X) (((X)->tabFlags & TF_WithoutRowid)==0)
  16905. #define VisibleRowid(X) (((X)->tabFlags & TF_NoVisibleRowid)==0)
  16906. /*
  16907. ** Each foreign key constraint is an instance of the following structure.
  16908. **
  16909. ** A foreign key is associated with two tables. The "from" table is
  16910. ** the table that contains the REFERENCES clause that creates the foreign
  16911. ** key. The "to" table is the table that is named in the REFERENCES clause.
  16912. ** Consider this example:
  16913. **
  16914. ** CREATE TABLE ex1(
  16915. ** a INTEGER PRIMARY KEY,
  16916. ** b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
  16917. ** );
  16918. **
  16919. ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
  16920. ** Equivalent names:
  16921. **
  16922. ** from-table == child-table
  16923. ** to-table == parent-table
  16924. **
  16925. ** Each REFERENCES clause generates an instance of the following structure
  16926. ** which is attached to the from-table. The to-table need not exist when
  16927. ** the from-table is created. The existence of the to-table is not checked.
  16928. **
  16929. ** The list of all parents for child Table X is held at X.pFKey.
  16930. **
  16931. ** A list of all children for a table named Z (which might not even exist)
  16932. ** is held in Schema.fkeyHash with a hash key of Z.
  16933. */
  16934. struct FKey {
  16935. Table *pFrom; /* Table containing the REFERENCES clause (aka: Child) */
  16936. FKey *pNextFrom; /* Next FKey with the same in pFrom. Next parent of pFrom */
  16937. char *zTo; /* Name of table that the key points to (aka: Parent) */
  16938. FKey *pNextTo; /* Next with the same zTo. Next child of zTo. */
  16939. FKey *pPrevTo; /* Previous with the same zTo */
  16940. int nCol; /* Number of columns in this key */
  16941. /* EV: R-30323-21917 */
  16942. u8 isDeferred; /* True if constraint checking is deferred till COMMIT */
  16943. u8 aAction[2]; /* ON DELETE and ON UPDATE actions, respectively */
  16944. Trigger *apTrigger[2];/* Triggers for aAction[] actions */
  16945. struct sColMap { /* Mapping of columns in pFrom to columns in zTo */
  16946. int iFrom; /* Index of column in pFrom */
  16947. char *zCol; /* Name of column in zTo. If NULL use PRIMARY KEY */
  16948. } aCol[1]; /* One entry for each of nCol columns */
  16949. };
  16950. /*
  16951. ** SQLite supports many different ways to resolve a constraint
  16952. ** error. ROLLBACK processing means that a constraint violation
  16953. ** causes the operation in process to fail and for the current transaction
  16954. ** to be rolled back. ABORT processing means the operation in process
  16955. ** fails and any prior changes from that one operation are backed out,
  16956. ** but the transaction is not rolled back. FAIL processing means that
  16957. ** the operation in progress stops and returns an error code. But prior
  16958. ** changes due to the same operation are not backed out and no rollback
  16959. ** occurs. IGNORE means that the particular row that caused the constraint
  16960. ** error is not inserted or updated. Processing continues and no error
  16961. ** is returned. REPLACE means that preexisting database rows that caused
  16962. ** a UNIQUE constraint violation are removed so that the new insert or
  16963. ** update can proceed. Processing continues and no error is reported.
  16964. **
  16965. ** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
  16966. ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
  16967. ** same as ROLLBACK for DEFERRED keys. SETNULL means that the foreign
  16968. ** key is set to NULL. CASCADE means that a DELETE or UPDATE of the
  16969. ** referenced table row is propagated into the row that holds the
  16970. ** foreign key.
  16971. **
  16972. ** The following symbolic values are used to record which type
  16973. ** of action to take.
  16974. */
  16975. #define OE_None 0 /* There is no constraint to check */
  16976. #define OE_Rollback 1 /* Fail the operation and rollback the transaction */
  16977. #define OE_Abort 2 /* Back out changes but do no rollback transaction */
  16978. #define OE_Fail 3 /* Stop the operation but leave all prior changes */
  16979. #define OE_Ignore 4 /* Ignore the error. Do not do the INSERT or UPDATE */
  16980. #define OE_Replace 5 /* Delete existing record, then do INSERT or UPDATE */
  16981. #define OE_Update 6 /* Process as a DO UPDATE in an upsert */
  16982. #define OE_Restrict 7 /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
  16983. #define OE_SetNull 8 /* Set the foreign key value to NULL */
  16984. #define OE_SetDflt 9 /* Set the foreign key value to its default */
  16985. #define OE_Cascade 10 /* Cascade the changes */
  16986. #define OE_Default 11 /* Do whatever the default action is */
  16987. /*
  16988. ** An instance of the following structure is passed as the first
  16989. ** argument to sqlite3VdbeKeyCompare and is used to control the
  16990. ** comparison of the two index keys.
  16991. **
  16992. ** Note that aSortOrder[] and aColl[] have nField+1 slots. There
  16993. ** are nField slots for the columns of an index then one extra slot
  16994. ** for the rowid at the end.
  16995. */
  16996. struct KeyInfo {
  16997. u32 nRef; /* Number of references to this KeyInfo object */
  16998. u8 enc; /* Text encoding - one of the SQLITE_UTF* values */
  16999. u16 nKeyField; /* Number of key columns in the index */
  17000. u16 nAllField; /* Total columns, including key plus others */
  17001. sqlite3 *db; /* The database connection */
  17002. u8 *aSortFlags; /* Sort order for each column. */
  17003. CollSeq *aColl[1]; /* Collating sequence for each term of the key */
  17004. };
  17005. /*
  17006. ** Allowed bit values for entries in the KeyInfo.aSortFlags[] array.
  17007. */
  17008. #define KEYINFO_ORDER_DESC 0x01 /* DESC sort order */
  17009. #define KEYINFO_ORDER_BIGNULL 0x02 /* NULL is larger than any other value */
  17010. /*
  17011. ** This object holds a record which has been parsed out into individual
  17012. ** fields, for the purposes of doing a comparison.
  17013. **
  17014. ** A record is an object that contains one or more fields of data.
  17015. ** Records are used to store the content of a table row and to store
  17016. ** the key of an index. A blob encoding of a record is created by
  17017. ** the OP_MakeRecord opcode of the VDBE and is disassembled by the
  17018. ** OP_Column opcode.
  17019. **
  17020. ** An instance of this object serves as a "key" for doing a search on
  17021. ** an index b+tree. The goal of the search is to find the entry that
  17022. ** is closed to the key described by this object. This object might hold
  17023. ** just a prefix of the key. The number of fields is given by
  17024. ** pKeyInfo->nField.
  17025. **
  17026. ** The r1 and r2 fields are the values to return if this key is less than
  17027. ** or greater than a key in the btree, respectively. These are normally
  17028. ** -1 and +1 respectively, but might be inverted to +1 and -1 if the b-tree
  17029. ** is in DESC order.
  17030. **
  17031. ** The key comparison functions actually return default_rc when they find
  17032. ** an equals comparison. default_rc can be -1, 0, or +1. If there are
  17033. ** multiple entries in the b-tree with the same key (when only looking
  17034. ** at the first pKeyInfo->nFields,) then default_rc can be set to -1 to
  17035. ** cause the search to find the last match, or +1 to cause the search to
  17036. ** find the first match.
  17037. **
  17038. ** The key comparison functions will set eqSeen to true if they ever
  17039. ** get and equal results when comparing this structure to a b-tree record.
  17040. ** When default_rc!=0, the search might end up on the record immediately
  17041. ** before the first match or immediately after the last match. The
  17042. ** eqSeen field will indicate whether or not an exact match exists in the
  17043. ** b-tree.
  17044. */
  17045. struct UnpackedRecord {
  17046. KeyInfo *pKeyInfo; /* Collation and sort-order information */
  17047. Mem *aMem; /* Values */
  17048. u16 nField; /* Number of entries in apMem[] */
  17049. i8 default_rc; /* Comparison result if keys are equal */
  17050. u8 errCode; /* Error detected by xRecordCompare (CORRUPT or NOMEM) */
  17051. i8 r1; /* Value to return if (lhs < rhs) */
  17052. i8 r2; /* Value to return if (lhs > rhs) */
  17053. u8 eqSeen; /* True if an equality comparison has been seen */
  17054. };
  17055. /*
  17056. ** Each SQL index is represented in memory by an
  17057. ** instance of the following structure.
  17058. **
  17059. ** The columns of the table that are to be indexed are described
  17060. ** by the aiColumn[] field of this structure. For example, suppose
  17061. ** we have the following table and index:
  17062. **
  17063. ** CREATE TABLE Ex1(c1 int, c2 int, c3 text);
  17064. ** CREATE INDEX Ex2 ON Ex1(c3,c1);
  17065. **
  17066. ** In the Table structure describing Ex1, nCol==3 because there are
  17067. ** three columns in the table. In the Index structure describing
  17068. ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
  17069. ** The value of aiColumn is {2, 0}. aiColumn[0]==2 because the
  17070. ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
  17071. ** The second column to be indexed (c1) has an index of 0 in
  17072. ** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
  17073. **
  17074. ** The Index.onError field determines whether or not the indexed columns
  17075. ** must be unique and what to do if they are not. When Index.onError=OE_None,
  17076. ** it means this is not a unique index. Otherwise it is a unique index
  17077. ** and the value of Index.onError indicate the which conflict resolution
  17078. ** algorithm to employ whenever an attempt is made to insert a non-unique
  17079. ** element.
  17080. **
  17081. ** While parsing a CREATE TABLE or CREATE INDEX statement in order to
  17082. ** generate VDBE code (as opposed to parsing one read from an sqlite_master
  17083. ** table as part of parsing an existing database schema), transient instances
  17084. ** of this structure may be created. In this case the Index.tnum variable is
  17085. ** used to store the address of a VDBE instruction, not a database page
  17086. ** number (it cannot - the database page is not allocated until the VDBE
  17087. ** program is executed). See convertToWithoutRowidTable() for details.
  17088. */
  17089. struct Index {
  17090. char *zName; /* Name of this index */
  17091. i16 *aiColumn; /* Which columns are used by this index. 1st is 0 */
  17092. LogEst *aiRowLogEst; /* From ANALYZE: Est. rows selected by each column */
  17093. Table *pTable; /* The SQL table being indexed */
  17094. char *zColAff; /* String defining the affinity of each column */
  17095. Index *pNext; /* The next index associated with the same table */
  17096. Schema *pSchema; /* Schema containing this index */
  17097. u8 *aSortOrder; /* for each column: True==DESC, False==ASC */
  17098. const char **azColl; /* Array of collation sequence names for index */
  17099. Expr *pPartIdxWhere; /* WHERE clause for partial indices */
  17100. ExprList *aColExpr; /* Column expressions */
  17101. int tnum; /* DB Page containing root of this index */
  17102. LogEst szIdxRow; /* Estimated average row size in bytes */
  17103. u16 nKeyCol; /* Number of columns forming the key */
  17104. u16 nColumn; /* Number of columns stored in the index */
  17105. u8 onError; /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
  17106. unsigned idxType:2; /* 0:Normal 1:UNIQUE, 2:PRIMARY KEY, 3:IPK */
  17107. unsigned bUnordered:1; /* Use this index for == or IN queries only */
  17108. unsigned uniqNotNull:1; /* True if UNIQUE and NOT NULL for all columns */
  17109. unsigned isResized:1; /* True if resizeIndexObject() has been called */
  17110. unsigned isCovering:1; /* True if this is a covering index */
  17111. unsigned noSkipScan:1; /* Do not try to use skip-scan if true */
  17112. unsigned hasStat1:1; /* aiRowLogEst values come from sqlite_stat1 */
  17113. unsigned bNoQuery:1; /* Do not use this index to optimize queries */
  17114. unsigned bAscKeyBug:1; /* True if the bba7b69f9849b5bf bug applies */
  17115. unsigned bHasVCol:1; /* Index references one or more VIRTUAL columns */
  17116. #ifdef SQLITE_ENABLE_STAT4
  17117. int nSample; /* Number of elements in aSample[] */
  17118. int nSampleCol; /* Size of IndexSample.anEq[] and so on */
  17119. tRowcnt *aAvgEq; /* Average nEq values for keys not in aSample */
  17120. IndexSample *aSample; /* Samples of the left-most key */
  17121. tRowcnt *aiRowEst; /* Non-logarithmic stat1 data for this index */
  17122. tRowcnt nRowEst0; /* Non-logarithmic number of rows in the index */
  17123. #endif
  17124. Bitmask colNotIdxed; /* 0 for unindexed columns in pTab */
  17125. };
  17126. /*
  17127. ** Allowed values for Index.idxType
  17128. */
  17129. #define SQLITE_IDXTYPE_APPDEF 0 /* Created using CREATE INDEX */
  17130. #define SQLITE_IDXTYPE_UNIQUE 1 /* Implements a UNIQUE constraint */
  17131. #define SQLITE_IDXTYPE_PRIMARYKEY 2 /* Is the PRIMARY KEY for the table */
  17132. #define SQLITE_IDXTYPE_IPK 3 /* INTEGER PRIMARY KEY index */
  17133. /* Return true if index X is a PRIMARY KEY index */
  17134. #define IsPrimaryKeyIndex(X) ((X)->idxType==SQLITE_IDXTYPE_PRIMARYKEY)
  17135. /* Return true if index X is a UNIQUE index */
  17136. #define IsUniqueIndex(X) ((X)->onError!=OE_None)
  17137. /* The Index.aiColumn[] values are normally positive integer. But
  17138. ** there are some negative values that have special meaning:
  17139. */
  17140. #define XN_ROWID (-1) /* Indexed column is the rowid */
  17141. #define XN_EXPR (-2) /* Indexed column is an expression */
  17142. /*
  17143. ** Each sample stored in the sqlite_stat4 table is represented in memory
  17144. ** using a structure of this type. See documentation at the top of the
  17145. ** analyze.c source file for additional information.
  17146. */
  17147. struct IndexSample {
  17148. void *p; /* Pointer to sampled record */
  17149. int n; /* Size of record in bytes */
  17150. tRowcnt *anEq; /* Est. number of rows where the key equals this sample */
  17151. tRowcnt *anLt; /* Est. number of rows where key is less than this sample */
  17152. tRowcnt *anDLt; /* Est. number of distinct keys less than this sample */
  17153. };
  17154. /*
  17155. ** Possible values to use within the flags argument to sqlite3GetToken().
  17156. */
  17157. #define SQLITE_TOKEN_QUOTED 0x1 /* Token is a quoted identifier. */
  17158. #define SQLITE_TOKEN_KEYWORD 0x2 /* Token is a keyword. */
  17159. /*
  17160. ** Each token coming out of the lexer is an instance of
  17161. ** this structure. Tokens are also used as part of an expression.
  17162. **
  17163. ** The memory that "z" points to is owned by other objects. Take care
  17164. ** that the owner of the "z" string does not deallocate the string before
  17165. ** the Token goes out of scope! Very often, the "z" points to some place
  17166. ** in the middle of the Parse.zSql text. But it might also point to a
  17167. ** static string.
  17168. */
  17169. struct Token {
  17170. const char *z; /* Text of the token. Not NULL-terminated! */
  17171. unsigned int n; /* Number of characters in this token */
  17172. };
  17173. /*
  17174. ** An instance of this structure contains information needed to generate
  17175. ** code for a SELECT that contains aggregate functions.
  17176. **
  17177. ** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
  17178. ** pointer to this structure. The Expr.iAgg field is the index in
  17179. ** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
  17180. ** code for that node.
  17181. **
  17182. ** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
  17183. ** original Select structure that describes the SELECT statement. These
  17184. ** fields do not need to be freed when deallocating the AggInfo structure.
  17185. */
  17186. struct AggInfo {
  17187. u8 directMode; /* Direct rendering mode means take data directly
  17188. ** from source tables rather than from accumulators */
  17189. u8 useSortingIdx; /* In direct mode, reference the sorting index rather
  17190. ** than the source table */
  17191. int sortingIdx; /* Cursor number of the sorting index */
  17192. int sortingIdxPTab; /* Cursor number of pseudo-table */
  17193. int nSortingColumn; /* Number of columns in the sorting index */
  17194. int mnReg, mxReg; /* Range of registers allocated for aCol and aFunc */
  17195. ExprList *pGroupBy; /* The group by clause */
  17196. struct AggInfo_col { /* For each column used in source tables */
  17197. Table *pTab; /* Source table */
  17198. int iTable; /* Cursor number of the source table */
  17199. int iColumn; /* Column number within the source table */
  17200. int iSorterColumn; /* Column number in the sorting index */
  17201. int iMem; /* Memory location that acts as accumulator */
  17202. Expr *pExpr; /* The original expression */
  17203. } *aCol;
  17204. int nColumn; /* Number of used entries in aCol[] */
  17205. int nAccumulator; /* Number of columns that show through to the output.
  17206. ** Additional columns are used only as parameters to
  17207. ** aggregate functions */
  17208. struct AggInfo_func { /* For each aggregate function */
  17209. Expr *pExpr; /* Expression encoding the function */
  17210. FuncDef *pFunc; /* The aggregate function implementation */
  17211. int iMem; /* Memory location that acts as accumulator */
  17212. int iDistinct; /* Ephemeral table used to enforce DISTINCT */
  17213. } *aFunc;
  17214. int nFunc; /* Number of entries in aFunc[] */
  17215. };
  17216. /*
  17217. ** The datatype ynVar is a signed integer, either 16-bit or 32-bit.
  17218. ** Usually it is 16-bits. But if SQLITE_MAX_VARIABLE_NUMBER is greater
  17219. ** than 32767 we have to make it 32-bit. 16-bit is preferred because
  17220. ** it uses less memory in the Expr object, which is a big memory user
  17221. ** in systems with lots of prepared statements. And few applications
  17222. ** need more than about 10 or 20 variables. But some extreme users want
  17223. ** to have prepared statements with over 32766 variables, and for them
  17224. ** the option is available (at compile-time).
  17225. */
  17226. #if SQLITE_MAX_VARIABLE_NUMBER<32767
  17227. typedef i16 ynVar;
  17228. #else
  17229. typedef int ynVar;
  17230. #endif
  17231. /*
  17232. ** Each node of an expression in the parse tree is an instance
  17233. ** of this structure.
  17234. **
  17235. ** Expr.op is the opcode. The integer parser token codes are reused
  17236. ** as opcodes here. For example, the parser defines TK_GE to be an integer
  17237. ** code representing the ">=" operator. This same integer code is reused
  17238. ** to represent the greater-than-or-equal-to operator in the expression
  17239. ** tree.
  17240. **
  17241. ** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB,
  17242. ** or TK_STRING), then Expr.token contains the text of the SQL literal. If
  17243. ** the expression is a variable (TK_VARIABLE), then Expr.token contains the
  17244. ** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
  17245. ** then Expr.token contains the name of the function.
  17246. **
  17247. ** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
  17248. ** binary operator. Either or both may be NULL.
  17249. **
  17250. ** Expr.x.pList is a list of arguments if the expression is an SQL function,
  17251. ** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
  17252. ** Expr.x.pSelect is used if the expression is a sub-select or an expression of
  17253. ** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the
  17254. ** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is
  17255. ** valid.
  17256. **
  17257. ** An expression of the form ID or ID.ID refers to a column in a table.
  17258. ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
  17259. ** the integer cursor number of a VDBE cursor pointing to that table and
  17260. ** Expr.iColumn is the column number for the specific column. If the
  17261. ** expression is used as a result in an aggregate SELECT, then the
  17262. ** value is also stored in the Expr.iAgg column in the aggregate so that
  17263. ** it can be accessed after all aggregates are computed.
  17264. **
  17265. ** If the expression is an unbound variable marker (a question mark
  17266. ** character '?' in the original SQL) then the Expr.iTable holds the index
  17267. ** number for that variable.
  17268. **
  17269. ** If the expression is a subquery then Expr.iColumn holds an integer
  17270. ** register number containing the result of the subquery. If the
  17271. ** subquery gives a constant result, then iTable is -1. If the subquery
  17272. ** gives a different answer at different times during statement processing
  17273. ** then iTable is the address of a subroutine that computes the subquery.
  17274. **
  17275. ** If the Expr is of type OP_Column, and the table it is selecting from
  17276. ** is a disk table or the "old.*" pseudo-table, then pTab points to the
  17277. ** corresponding table definition.
  17278. **
  17279. ** ALLOCATION NOTES:
  17280. **
  17281. ** Expr objects can use a lot of memory space in database schema. To
  17282. ** help reduce memory requirements, sometimes an Expr object will be
  17283. ** truncated. And to reduce the number of memory allocations, sometimes
  17284. ** two or more Expr objects will be stored in a single memory allocation,
  17285. ** together with Expr.zToken strings.
  17286. **
  17287. ** If the EP_Reduced and EP_TokenOnly flags are set when
  17288. ** an Expr object is truncated. When EP_Reduced is set, then all
  17289. ** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees
  17290. ** are contained within the same memory allocation. Note, however, that
  17291. ** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately
  17292. ** allocated, regardless of whether or not EP_Reduced is set.
  17293. */
  17294. struct Expr {
  17295. u8 op; /* Operation performed by this node */
  17296. char affExpr; /* affinity, or RAISE type */
  17297. u8 op2; /* TK_REGISTER/TK_TRUTH: original value of Expr.op
  17298. ** TK_COLUMN: the value of p5 for OP_Column
  17299. ** TK_AGG_FUNCTION: nesting depth
  17300. ** TK_FUNCTION: NC_SelfRef flag if needs OP_PureFunc */
  17301. #ifdef SQLITE_DEBUG
  17302. u8 vvaFlags; /* Verification flags. */
  17303. #endif
  17304. u32 flags; /* Various flags. EP_* See below */
  17305. union {
  17306. char *zToken; /* Token value. Zero terminated and dequoted */
  17307. int iValue; /* Non-negative integer value if EP_IntValue */
  17308. } u;
  17309. /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
  17310. ** space is allocated for the fields below this point. An attempt to
  17311. ** access them will result in a segfault or malfunction.
  17312. *********************************************************************/
  17313. Expr *pLeft; /* Left subnode */
  17314. Expr *pRight; /* Right subnode */
  17315. union {
  17316. ExprList *pList; /* op = IN, EXISTS, SELECT, CASE, FUNCTION, BETWEEN */
  17317. Select *pSelect; /* EP_xIsSelect and op = IN, EXISTS, SELECT */
  17318. } x;
  17319. /* If the EP_Reduced flag is set in the Expr.flags mask, then no
  17320. ** space is allocated for the fields below this point. An attempt to
  17321. ** access them will result in a segfault or malfunction.
  17322. *********************************************************************/
  17323. #if SQLITE_MAX_EXPR_DEPTH>0
  17324. int nHeight; /* Height of the tree headed by this node */
  17325. #endif
  17326. int iTable; /* TK_COLUMN: cursor number of table holding column
  17327. ** TK_REGISTER: register number
  17328. ** TK_TRIGGER: 1 -> new, 0 -> old
  17329. ** EP_Unlikely: 134217728 times likelihood
  17330. ** TK_IN: ephemerial table holding RHS
  17331. ** TK_SELECT_COLUMN: Number of columns on the LHS
  17332. ** TK_SELECT: 1st register of result vector */
  17333. ynVar iColumn; /* TK_COLUMN: column index. -1 for rowid.
  17334. ** TK_VARIABLE: variable number (always >= 1).
  17335. ** TK_SELECT_COLUMN: column of the result vector */
  17336. i16 iAgg; /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
  17337. i16 iRightJoinTable; /* If EP_FromJoin, the right table of the join */
  17338. AggInfo *pAggInfo; /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
  17339. union {
  17340. Table *pTab; /* TK_COLUMN: Table containing column. Can be NULL
  17341. ** for a column of an index on an expression */
  17342. Window *pWin; /* EP_WinFunc: Window/Filter defn for a function */
  17343. struct { /* TK_IN, TK_SELECT, and TK_EXISTS */
  17344. int iAddr; /* Subroutine entry address */
  17345. int regReturn; /* Register used to hold return address */
  17346. } sub;
  17347. } y;
  17348. };
  17349. /*
  17350. ** The following are the meanings of bits in the Expr.flags field.
  17351. ** Value restrictions:
  17352. **
  17353. ** EP_Agg == NC_HasAgg == SF_HasAgg
  17354. ** EP_Win == NC_HasWin
  17355. */
  17356. #define EP_FromJoin 0x000001 /* Originates in ON/USING clause of outer join */
  17357. #define EP_Distinct 0x000002 /* Aggregate function with DISTINCT keyword */
  17358. #define EP_HasFunc 0x000004 /* Contains one or more functions of any kind */
  17359. #define EP_FixedCol 0x000008 /* TK_Column with a known fixed value */
  17360. #define EP_Agg 0x000010 /* Contains one or more aggregate functions */
  17361. #define EP_VarSelect 0x000020 /* pSelect is correlated, not constant */
  17362. #define EP_DblQuoted 0x000040 /* token.z was originally in "..." */
  17363. #define EP_InfixFunc 0x000080 /* True for an infix function: LIKE, GLOB, etc */
  17364. #define EP_Collate 0x000100 /* Tree contains a TK_COLLATE operator */
  17365. #define EP_Commuted 0x000200 /* Comparison operator has been commuted */
  17366. #define EP_IntValue 0x000400 /* Integer value contained in u.iValue */
  17367. #define EP_xIsSelect 0x000800 /* x.pSelect is valid (otherwise x.pList is) */
  17368. #define EP_Skip 0x001000 /* Operator does not contribute to affinity */
  17369. #define EP_Reduced 0x002000 /* Expr struct EXPR_REDUCEDSIZE bytes only */
  17370. #define EP_TokenOnly 0x004000 /* Expr struct EXPR_TOKENONLYSIZE bytes only */
  17371. #define EP_Win 0x008000 /* Contains window functions */
  17372. #define EP_MemToken 0x010000 /* Need to sqlite3DbFree() Expr.zToken */
  17373. /* 0x020000 // available for reuse */
  17374. #define EP_Unlikely 0x040000 /* unlikely() or likelihood() function */
  17375. #define EP_ConstFunc 0x080000 /* A SQLITE_FUNC_CONSTANT or _SLOCHNG function */
  17376. #define EP_CanBeNull 0x100000 /* Can be null despite NOT NULL constraint */
  17377. #define EP_Subquery 0x200000 /* Tree contains a TK_SELECT operator */
  17378. #define EP_Alias 0x400000 /* Is an alias for a result set column */
  17379. #define EP_Leaf 0x800000 /* Expr.pLeft, .pRight, .u.pSelect all NULL */
  17380. #define EP_WinFunc 0x1000000 /* TK_FUNCTION with Expr.y.pWin set */
  17381. #define EP_Subrtn 0x2000000 /* Uses Expr.y.sub. TK_IN, _SELECT, or _EXISTS */
  17382. #define EP_Quoted 0x4000000 /* TK_ID was originally quoted */
  17383. #define EP_Static 0x8000000 /* Held in memory not obtained from malloc() */
  17384. #define EP_IsTrue 0x10000000 /* Always has boolean value of TRUE */
  17385. #define EP_IsFalse 0x20000000 /* Always has boolean value of FALSE */
  17386. #define EP_FromDDL 0x40000000 /* Originates from sqlite_master */
  17387. /* 0x80000000 // Available */
  17388. /*
  17389. ** The EP_Propagate mask is a set of properties that automatically propagate
  17390. ** upwards into parent nodes.
  17391. */
  17392. #define EP_Propagate (EP_Collate|EP_Subquery|EP_HasFunc)
  17393. /*
  17394. ** These macros can be used to test, set, or clear bits in the
  17395. ** Expr.flags field.
  17396. */
  17397. #define ExprHasProperty(E,P) (((E)->flags&(P))!=0)
  17398. #define ExprHasAllProperty(E,P) (((E)->flags&(P))==(P))
  17399. #define ExprSetProperty(E,P) (E)->flags|=(P)
  17400. #define ExprClearProperty(E,P) (E)->flags&=~(P)
  17401. #define ExprAlwaysTrue(E) (((E)->flags&(EP_FromJoin|EP_IsTrue))==EP_IsTrue)
  17402. #define ExprAlwaysFalse(E) (((E)->flags&(EP_FromJoin|EP_IsFalse))==EP_IsFalse)
  17403. /* Flags for use with Expr.vvaFlags
  17404. */
  17405. #define EP_NoReduce 0x01 /* Cannot EXPRDUP_REDUCE this Expr */
  17406. #define EP_Immutable 0x02 /* Do not change this Expr node */
  17407. /* The ExprSetVVAProperty() macro is used for Verification, Validation,
  17408. ** and Accreditation only. It works like ExprSetProperty() during VVA
  17409. ** processes but is a no-op for delivery.
  17410. */
  17411. #ifdef SQLITE_DEBUG
  17412. # define ExprSetVVAProperty(E,P) (E)->vvaFlags|=(P)
  17413. # define ExprHasVVAProperty(E,P) (((E)->vvaFlags&(P))!=0)
  17414. # define ExprClearVVAProperties(E) (E)->vvaFlags = 0
  17415. #else
  17416. # define ExprSetVVAProperty(E,P)
  17417. # define ExprHasVVAProperty(E,P) 0
  17418. # define ExprClearVVAProperties(E)
  17419. #endif
  17420. /*
  17421. ** Macros to determine the number of bytes required by a normal Expr
  17422. ** struct, an Expr struct with the EP_Reduced flag set in Expr.flags
  17423. ** and an Expr struct with the EP_TokenOnly flag set.
  17424. */
  17425. #define EXPR_FULLSIZE sizeof(Expr) /* Full size */
  17426. #define EXPR_REDUCEDSIZE offsetof(Expr,iTable) /* Common features */
  17427. #define EXPR_TOKENONLYSIZE offsetof(Expr,pLeft) /* Fewer features */
  17428. /*
  17429. ** Flags passed to the sqlite3ExprDup() function. See the header comment
  17430. ** above sqlite3ExprDup() for details.
  17431. */
  17432. #define EXPRDUP_REDUCE 0x0001 /* Used reduced-size Expr nodes */
  17433. /*
  17434. ** True if the expression passed as an argument was a function with
  17435. ** an OVER() clause (a window function).
  17436. */
  17437. #ifdef SQLITE_OMIT_WINDOWFUNC
  17438. # define IsWindowFunc(p) 0
  17439. #else
  17440. # define IsWindowFunc(p) ( \
  17441. ExprHasProperty((p), EP_WinFunc) && p->y.pWin->eFrmType!=TK_FILTER \
  17442. )
  17443. #endif
  17444. /*
  17445. ** A list of expressions. Each expression may optionally have a
  17446. ** name. An expr/name combination can be used in several ways, such
  17447. ** as the list of "expr AS ID" fields following a "SELECT" or in the
  17448. ** list of "ID = expr" items in an UPDATE. A list of expressions can
  17449. ** also be used as the argument to a function, in which case the a.zName
  17450. ** field is not used.
  17451. **
  17452. ** In order to try to keep memory usage down, the Expr.a.zEName field
  17453. ** is used for multiple purposes:
  17454. **
  17455. ** eEName Usage
  17456. ** ---------- -------------------------
  17457. ** ENAME_NAME (1) the AS of result set column
  17458. ** (2) COLUMN= of an UPDATE
  17459. **
  17460. ** ENAME_TAB DB.TABLE.NAME used to resolve names
  17461. ** of subqueries
  17462. **
  17463. ** ENAME_SPAN Text of the original result set
  17464. ** expression.
  17465. */
  17466. struct ExprList {
  17467. int nExpr; /* Number of expressions on the list */
  17468. struct ExprList_item { /* For each expression in the list */
  17469. Expr *pExpr; /* The parse tree for this expression */
  17470. char *zEName; /* Token associated with this expression */
  17471. u8 sortFlags; /* Mask of KEYINFO_ORDER_* flags */
  17472. unsigned eEName :2; /* Meaning of zEName */
  17473. unsigned done :1; /* A flag to indicate when processing is finished */
  17474. unsigned reusable :1; /* Constant expression is reusable */
  17475. unsigned bSorterRef :1; /* Defer evaluation until after sorting */
  17476. unsigned bNulls: 1; /* True if explicit "NULLS FIRST/LAST" */
  17477. union {
  17478. struct {
  17479. u16 iOrderByCol; /* For ORDER BY, column number in result set */
  17480. u16 iAlias; /* Index into Parse.aAlias[] for zName */
  17481. } x;
  17482. int iConstExprReg; /* Register in which Expr value is cached */
  17483. } u;
  17484. } a[1]; /* One slot for each expression in the list */
  17485. };
  17486. /*
  17487. ** Allowed values for Expr.a.eEName
  17488. */
  17489. #define ENAME_NAME 0 /* The AS clause of a result set */
  17490. #define ENAME_SPAN 1 /* Complete text of the result set expression */
  17491. #define ENAME_TAB 2 /* "DB.TABLE.NAME" for the result set */
  17492. /*
  17493. ** An instance of this structure can hold a simple list of identifiers,
  17494. ** such as the list "a,b,c" in the following statements:
  17495. **
  17496. ** INSERT INTO t(a,b,c) VALUES ...;
  17497. ** CREATE INDEX idx ON t(a,b,c);
  17498. ** CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
  17499. **
  17500. ** The IdList.a.idx field is used when the IdList represents the list of
  17501. ** column names after a table name in an INSERT statement. In the statement
  17502. **
  17503. ** INSERT INTO t(a,b,c) ...
  17504. **
  17505. ** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
  17506. */
  17507. struct IdList {
  17508. struct IdList_item {
  17509. char *zName; /* Name of the identifier */
  17510. int idx; /* Index in some Table.aCol[] of a column named zName */
  17511. } *a;
  17512. int nId; /* Number of identifiers on the list */
  17513. };
  17514. /*
  17515. ** The following structure describes the FROM clause of a SELECT statement.
  17516. ** Each table or subquery in the FROM clause is a separate element of
  17517. ** the SrcList.a[] array.
  17518. **
  17519. ** With the addition of multiple database support, the following structure
  17520. ** can also be used to describe a particular table such as the table that
  17521. ** is modified by an INSERT, DELETE, or UPDATE statement. In standard SQL,
  17522. ** such a table must be a simple name: ID. But in SQLite, the table can
  17523. ** now be identified by a database name, a dot, then the table name: ID.ID.
  17524. **
  17525. ** The jointype starts out showing the join type between the current table
  17526. ** and the next table on the list. The parser builds the list this way.
  17527. ** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
  17528. ** jointype expresses the join between the table and the previous table.
  17529. **
  17530. ** In the colUsed field, the high-order bit (bit 63) is set if the table
  17531. ** contains more than 63 columns and the 64-th or later column is used.
  17532. */
  17533. struct SrcList {
  17534. int nSrc; /* Number of tables or subqueries in the FROM clause */
  17535. u32 nAlloc; /* Number of entries allocated in a[] below */
  17536. struct SrcList_item {
  17537. Schema *pSchema; /* Schema to which this item is fixed */
  17538. char *zDatabase; /* Name of database holding this table */
  17539. char *zName; /* Name of the table */
  17540. char *zAlias; /* The "B" part of a "A AS B" phrase. zName is the "A" */
  17541. Table *pTab; /* An SQL table corresponding to zName */
  17542. Select *pSelect; /* A SELECT statement used in place of a table name */
  17543. int addrFillSub; /* Address of subroutine to manifest a subquery */
  17544. int regReturn; /* Register holding return address of addrFillSub */
  17545. int regResult; /* Registers holding results of a co-routine */
  17546. struct {
  17547. u8 jointype; /* Type of join between this table and the previous */
  17548. unsigned notIndexed :1; /* True if there is a NOT INDEXED clause */
  17549. unsigned isIndexedBy :1; /* True if there is an INDEXED BY clause */
  17550. unsigned isTabFunc :1; /* True if table-valued-function syntax */
  17551. unsigned isCorrelated :1; /* True if sub-query is correlated */
  17552. unsigned viaCoroutine :1; /* Implemented as a co-routine */
  17553. unsigned isRecursive :1; /* True for recursive reference in WITH */
  17554. unsigned fromDDL :1; /* Comes from sqlite_master */
  17555. } fg;
  17556. int iCursor; /* The VDBE cursor number used to access this table */
  17557. Expr *pOn; /* The ON clause of a join */
  17558. IdList *pUsing; /* The USING clause of a join */
  17559. Bitmask colUsed; /* Bit N (1<<N) set if column N of pTab is used */
  17560. union {
  17561. char *zIndexedBy; /* Identifier from "INDEXED BY <zIndex>" clause */
  17562. ExprList *pFuncArg; /* Arguments to table-valued-function */
  17563. } u1;
  17564. Index *pIBIndex; /* Index structure corresponding to u1.zIndexedBy */
  17565. } a[1]; /* One entry for each identifier on the list */
  17566. };
  17567. /*
  17568. ** Permitted values of the SrcList.a.jointype field
  17569. */
  17570. #define JT_INNER 0x0001 /* Any kind of inner or cross join */
  17571. #define JT_CROSS 0x0002 /* Explicit use of the CROSS keyword */
  17572. #define JT_NATURAL 0x0004 /* True for a "natural" join */
  17573. #define JT_LEFT 0x0008 /* Left outer join */
  17574. #define JT_RIGHT 0x0010 /* Right outer join */
  17575. #define JT_OUTER 0x0020 /* The "OUTER" keyword is present */
  17576. #define JT_ERROR 0x0040 /* unknown or unsupported join type */
  17577. /*
  17578. ** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
  17579. ** and the WhereInfo.wctrlFlags member.
  17580. **
  17581. ** Value constraints (enforced via assert()):
  17582. ** WHERE_USE_LIMIT == SF_FixedLimit
  17583. */
  17584. #define WHERE_ORDERBY_NORMAL 0x0000 /* No-op */
  17585. #define WHERE_ORDERBY_MIN 0x0001 /* ORDER BY processing for min() func */
  17586. #define WHERE_ORDERBY_MAX 0x0002 /* ORDER BY processing for max() func */
  17587. #define WHERE_ONEPASS_DESIRED 0x0004 /* Want to do one-pass UPDATE/DELETE */
  17588. #define WHERE_ONEPASS_MULTIROW 0x0008 /* ONEPASS is ok with multiple rows */
  17589. #define WHERE_DUPLICATES_OK 0x0010 /* Ok to return a row more than once */
  17590. #define WHERE_OR_SUBCLAUSE 0x0020 /* Processing a sub-WHERE as part of
  17591. ** the OR optimization */
  17592. #define WHERE_GROUPBY 0x0040 /* pOrderBy is really a GROUP BY */
  17593. #define WHERE_DISTINCTBY 0x0080 /* pOrderby is really a DISTINCT clause */
  17594. #define WHERE_WANT_DISTINCT 0x0100 /* All output needs to be distinct */
  17595. #define WHERE_SORTBYGROUP 0x0200 /* Support sqlite3WhereIsSorted() */
  17596. #define WHERE_SEEK_TABLE 0x0400 /* Do not defer seeks on main table */
  17597. #define WHERE_ORDERBY_LIMIT 0x0800 /* ORDERBY+LIMIT on the inner loop */
  17598. #define WHERE_SEEK_UNIQ_TABLE 0x1000 /* Do not defer seeks if unique */
  17599. /* 0x2000 not currently used */
  17600. #define WHERE_USE_LIMIT 0x4000 /* Use the LIMIT in cost estimates */
  17601. /* 0x8000 not currently used */
  17602. /* Allowed return values from sqlite3WhereIsDistinct()
  17603. */
  17604. #define WHERE_DISTINCT_NOOP 0 /* DISTINCT keyword not used */
  17605. #define WHERE_DISTINCT_UNIQUE 1 /* No duplicates */
  17606. #define WHERE_DISTINCT_ORDERED 2 /* All duplicates are adjacent */
  17607. #define WHERE_DISTINCT_UNORDERED 3 /* Duplicates are scattered */
  17608. /*
  17609. ** A NameContext defines a context in which to resolve table and column
  17610. ** names. The context consists of a list of tables (the pSrcList) field and
  17611. ** a list of named expression (pEList). The named expression list may
  17612. ** be NULL. The pSrc corresponds to the FROM clause of a SELECT or
  17613. ** to the table being operated on by INSERT, UPDATE, or DELETE. The
  17614. ** pEList corresponds to the result set of a SELECT and is NULL for
  17615. ** other statements.
  17616. **
  17617. ** NameContexts can be nested. When resolving names, the inner-most
  17618. ** context is searched first. If no match is found, the next outer
  17619. ** context is checked. If there is still no match, the next context
  17620. ** is checked. This process continues until either a match is found
  17621. ** or all contexts are check. When a match is found, the nRef member of
  17622. ** the context containing the match is incremented.
  17623. **
  17624. ** Each subquery gets a new NameContext. The pNext field points to the
  17625. ** NameContext in the parent query. Thus the process of scanning the
  17626. ** NameContext list corresponds to searching through successively outer
  17627. ** subqueries looking for a match.
  17628. */
  17629. struct NameContext {
  17630. Parse *pParse; /* The parser */
  17631. SrcList *pSrcList; /* One or more tables used to resolve names */
  17632. union {
  17633. ExprList *pEList; /* Optional list of result-set columns */
  17634. AggInfo *pAggInfo; /* Information about aggregates at this level */
  17635. Upsert *pUpsert; /* ON CONFLICT clause information from an upsert */
  17636. } uNC;
  17637. NameContext *pNext; /* Next outer name context. NULL for outermost */
  17638. int nRef; /* Number of names resolved by this context */
  17639. int nErr; /* Number of errors encountered while resolving names */
  17640. int ncFlags; /* Zero or more NC_* flags defined below */
  17641. Select *pWinSelect; /* SELECT statement for any window functions */
  17642. };
  17643. /*
  17644. ** Allowed values for the NameContext, ncFlags field.
  17645. **
  17646. ** Value constraints (all checked via assert()):
  17647. ** NC_HasAgg == SF_HasAgg == EP_Agg
  17648. ** NC_MinMaxAgg == SF_MinMaxAgg == SQLITE_FUNC_MINMAX
  17649. ** NC_HasWin == EP_Win
  17650. **
  17651. */
  17652. #define NC_AllowAgg 0x00001 /* Aggregate functions are allowed here */
  17653. #define NC_PartIdx 0x00002 /* True if resolving a partial index WHERE */
  17654. #define NC_IsCheck 0x00004 /* True if resolving a CHECK constraint */
  17655. #define NC_GenCol 0x00008 /* True for a GENERATED ALWAYS AS clause */
  17656. #define NC_HasAgg 0x00010 /* One or more aggregate functions seen */
  17657. #define NC_IdxExpr 0x00020 /* True if resolving columns of CREATE INDEX */
  17658. #define NC_SelfRef 0x0002e /* Combo: PartIdx, isCheck, GenCol, and IdxExpr */
  17659. #define NC_VarSelect 0x00040 /* A correlated subquery has been seen */
  17660. #define NC_UEList 0x00080 /* True if uNC.pEList is used */
  17661. #define NC_UAggInfo 0x00100 /* True if uNC.pAggInfo is used */
  17662. #define NC_UUpsert 0x00200 /* True if uNC.pUpsert is used */
  17663. #define NC_MinMaxAgg 0x01000 /* min/max aggregates seen. See note above */
  17664. #define NC_Complex 0x02000 /* True if a function or subquery seen */
  17665. #define NC_AllowWin 0x04000 /* Window functions are allowed here */
  17666. #define NC_HasWin 0x08000 /* One or more window functions seen */
  17667. #define NC_IsDDL 0x10000 /* Resolving names in a CREATE statement */
  17668. #define NC_InAggFunc 0x20000 /* True if analyzing arguments to an agg func */
  17669. #define NC_FromDDL 0x40000 /* SQL text comes from sqlite_master */
  17670. /*
  17671. ** An instance of the following object describes a single ON CONFLICT
  17672. ** clause in an upsert.
  17673. **
  17674. ** The pUpsertTarget field is only set if the ON CONFLICT clause includes
  17675. ** conflict-target clause. (In "ON CONFLICT(a,b)" the "(a,b)" is the
  17676. ** conflict-target clause.) The pUpsertTargetWhere is the optional
  17677. ** WHERE clause used to identify partial unique indexes.
  17678. **
  17679. ** pUpsertSet is the list of column=expr terms of the UPDATE statement.
  17680. ** The pUpsertSet field is NULL for a ON CONFLICT DO NOTHING. The
  17681. ** pUpsertWhere is the WHERE clause for the UPDATE and is NULL if the
  17682. ** WHERE clause is omitted.
  17683. */
  17684. struct Upsert {
  17685. ExprList *pUpsertTarget; /* Optional description of conflicting index */
  17686. Expr *pUpsertTargetWhere; /* WHERE clause for partial index targets */
  17687. ExprList *pUpsertSet; /* The SET clause from an ON CONFLICT UPDATE */
  17688. Expr *pUpsertWhere; /* WHERE clause for the ON CONFLICT UPDATE */
  17689. /* The fields above comprise the parse tree for the upsert clause.
  17690. ** The fields below are used to transfer information from the INSERT
  17691. ** processing down into the UPDATE processing while generating code.
  17692. ** Upsert owns the memory allocated above, but not the memory below. */
  17693. Index *pUpsertIdx; /* Constraint that pUpsertTarget identifies */
  17694. SrcList *pUpsertSrc; /* Table to be updated */
  17695. int regData; /* First register holding array of VALUES */
  17696. int iDataCur; /* Index of the data cursor */
  17697. int iIdxCur; /* Index of the first index cursor */
  17698. };
  17699. /*
  17700. ** An instance of the following structure contains all information
  17701. ** needed to generate code for a single SELECT statement.
  17702. **
  17703. ** See the header comment on the computeLimitRegisters() routine for a
  17704. ** detailed description of the meaning of the iLimit and iOffset fields.
  17705. **
  17706. ** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
  17707. ** These addresses must be stored so that we can go back and fill in
  17708. ** the P4_KEYINFO and P2 parameters later. Neither the KeyInfo nor
  17709. ** the number of columns in P2 can be computed at the same time
  17710. ** as the OP_OpenEphm instruction is coded because not
  17711. ** enough information about the compound query is known at that point.
  17712. ** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
  17713. ** for the result set. The KeyInfo for addrOpenEphm[2] contains collating
  17714. ** sequences for the ORDER BY clause.
  17715. */
  17716. struct Select {
  17717. u8 op; /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
  17718. LogEst nSelectRow; /* Estimated number of result rows */
  17719. u32 selFlags; /* Various SF_* values */
  17720. int iLimit, iOffset; /* Memory registers holding LIMIT & OFFSET counters */
  17721. u32 selId; /* Unique identifier number for this SELECT */
  17722. int addrOpenEphm[2]; /* OP_OpenEphem opcodes related to this select */
  17723. ExprList *pEList; /* The fields of the result */
  17724. SrcList *pSrc; /* The FROM clause */
  17725. Expr *pWhere; /* The WHERE clause */
  17726. ExprList *pGroupBy; /* The GROUP BY clause */
  17727. Expr *pHaving; /* The HAVING clause */
  17728. ExprList *pOrderBy; /* The ORDER BY clause */
  17729. Select *pPrior; /* Prior select in a compound select statement */
  17730. Select *pNext; /* Next select to the left in a compound */
  17731. Expr *pLimit; /* LIMIT expression. NULL means not used. */
  17732. With *pWith; /* WITH clause attached to this select. Or NULL. */
  17733. #ifndef SQLITE_OMIT_WINDOWFUNC
  17734. Window *pWin; /* List of window functions */
  17735. Window *pWinDefn; /* List of named window definitions */
  17736. #endif
  17737. };
  17738. /*
  17739. ** Allowed values for Select.selFlags. The "SF" prefix stands for
  17740. ** "Select Flag".
  17741. **
  17742. ** Value constraints (all checked via assert())
  17743. ** SF_HasAgg == NC_HasAgg
  17744. ** SF_MinMaxAgg == NC_MinMaxAgg == SQLITE_FUNC_MINMAX
  17745. ** SF_FixedLimit == WHERE_USE_LIMIT
  17746. */
  17747. #define SF_Distinct 0x0000001 /* Output should be DISTINCT */
  17748. #define SF_All 0x0000002 /* Includes the ALL keyword */
  17749. #define SF_Resolved 0x0000004 /* Identifiers have been resolved */
  17750. #define SF_Aggregate 0x0000008 /* Contains agg functions or a GROUP BY */
  17751. #define SF_HasAgg 0x0000010 /* Contains aggregate functions */
  17752. #define SF_UsesEphemeral 0x0000020 /* Uses the OpenEphemeral opcode */
  17753. #define SF_Expanded 0x0000040 /* sqlite3SelectExpand() called on this */
  17754. #define SF_HasTypeInfo 0x0000080 /* FROM subqueries have Table metadata */
  17755. #define SF_Compound 0x0000100 /* Part of a compound query */
  17756. #define SF_Values 0x0000200 /* Synthesized from VALUES clause */
  17757. #define SF_MultiValue 0x0000400 /* Single VALUES term with multiple rows */
  17758. #define SF_NestedFrom 0x0000800 /* Part of a parenthesized FROM clause */
  17759. #define SF_MinMaxAgg 0x0001000 /* Aggregate containing min() or max() */
  17760. #define SF_Recursive 0x0002000 /* The recursive part of a recursive CTE */
  17761. #define SF_FixedLimit 0x0004000 /* nSelectRow set by a constant LIMIT */
  17762. #define SF_MaybeConvert 0x0008000 /* Need convertCompoundSelectToSubquery() */
  17763. #define SF_Converted 0x0010000 /* By convertCompoundSelectToSubquery() */
  17764. #define SF_IncludeHidden 0x0020000 /* Include hidden columns in output */
  17765. #define SF_ComplexResult 0x0040000 /* Result contains subquery or function */
  17766. #define SF_WhereBegin 0x0080000 /* Really a WhereBegin() call. Debug Only */
  17767. #define SF_WinRewrite 0x0100000 /* Window function rewrite accomplished */
  17768. #define SF_View 0x0200000 /* SELECT statement is a view */
  17769. /*
  17770. ** The results of a SELECT can be distributed in several ways, as defined
  17771. ** by one of the following macros. The "SRT" prefix means "SELECT Result
  17772. ** Type".
  17773. **
  17774. ** SRT_Union Store results as a key in a temporary index
  17775. ** identified by pDest->iSDParm.
  17776. **
  17777. ** SRT_Except Remove results from the temporary index pDest->iSDParm.
  17778. **
  17779. ** SRT_Exists Store a 1 in memory cell pDest->iSDParm if the result
  17780. ** set is not empty.
  17781. **
  17782. ** SRT_Discard Throw the results away. This is used by SELECT
  17783. ** statements within triggers whose only purpose is
  17784. ** the side-effects of functions.
  17785. **
  17786. ** All of the above are free to ignore their ORDER BY clause. Those that
  17787. ** follow must honor the ORDER BY clause.
  17788. **
  17789. ** SRT_Output Generate a row of output (using the OP_ResultRow
  17790. ** opcode) for each row in the result set.
  17791. **
  17792. ** SRT_Mem Only valid if the result is a single column.
  17793. ** Store the first column of the first result row
  17794. ** in register pDest->iSDParm then abandon the rest
  17795. ** of the query. This destination implies "LIMIT 1".
  17796. **
  17797. ** SRT_Set The result must be a single column. Store each
  17798. ** row of result as the key in table pDest->iSDParm.
  17799. ** Apply the affinity pDest->affSdst before storing
  17800. ** results. Used to implement "IN (SELECT ...)".
  17801. **
  17802. ** SRT_EphemTab Create an temporary table pDest->iSDParm and store
  17803. ** the result there. The cursor is left open after
  17804. ** returning. This is like SRT_Table except that
  17805. ** this destination uses OP_OpenEphemeral to create
  17806. ** the table first.
  17807. **
  17808. ** SRT_Coroutine Generate a co-routine that returns a new row of
  17809. ** results each time it is invoked. The entry point
  17810. ** of the co-routine is stored in register pDest->iSDParm
  17811. ** and the result row is stored in pDest->nDest registers
  17812. ** starting with pDest->iSdst.
  17813. **
  17814. ** SRT_Table Store results in temporary table pDest->iSDParm.
  17815. ** SRT_Fifo This is like SRT_EphemTab except that the table
  17816. ** is assumed to already be open. SRT_Fifo has
  17817. ** the additional property of being able to ignore
  17818. ** the ORDER BY clause.
  17819. **
  17820. ** SRT_DistFifo Store results in a temporary table pDest->iSDParm.
  17821. ** But also use temporary table pDest->iSDParm+1 as
  17822. ** a record of all prior results and ignore any duplicate
  17823. ** rows. Name means: "Distinct Fifo".
  17824. **
  17825. ** SRT_Queue Store results in priority queue pDest->iSDParm (really
  17826. ** an index). Append a sequence number so that all entries
  17827. ** are distinct.
  17828. **
  17829. ** SRT_DistQueue Store results in priority queue pDest->iSDParm only if
  17830. ** the same record has never been stored before. The
  17831. ** index at pDest->iSDParm+1 hold all prior stores.
  17832. */
  17833. #define SRT_Union 1 /* Store result as keys in an index */
  17834. #define SRT_Except 2 /* Remove result from a UNION index */
  17835. #define SRT_Exists 3 /* Store 1 if the result is not empty */
  17836. #define SRT_Discard 4 /* Do not save the results anywhere */
  17837. #define SRT_Fifo 5 /* Store result as data with an automatic rowid */
  17838. #define SRT_DistFifo 6 /* Like SRT_Fifo, but unique results only */
  17839. #define SRT_Queue 7 /* Store result in an queue */
  17840. #define SRT_DistQueue 8 /* Like SRT_Queue, but unique results only */
  17841. /* The ORDER BY clause is ignored for all of the above */
  17842. #define IgnorableOrderby(X) ((X->eDest)<=SRT_DistQueue)
  17843. #define SRT_Output 9 /* Output each row of result */
  17844. #define SRT_Mem 10 /* Store result in a memory cell */
  17845. #define SRT_Set 11 /* Store results as keys in an index */
  17846. #define SRT_EphemTab 12 /* Create transient tab and store like SRT_Table */
  17847. #define SRT_Coroutine 13 /* Generate a single row of result */
  17848. #define SRT_Table 14 /* Store result as data with an automatic rowid */
  17849. /*
  17850. ** An instance of this object describes where to put of the results of
  17851. ** a SELECT statement.
  17852. */
  17853. struct SelectDest {
  17854. u8 eDest; /* How to dispose of the results. On of SRT_* above. */
  17855. int iSDParm; /* A parameter used by the eDest disposal method */
  17856. int iSdst; /* Base register where results are written */
  17857. int nSdst; /* Number of registers allocated */
  17858. char *zAffSdst; /* Affinity used when eDest==SRT_Set */
  17859. ExprList *pOrderBy; /* Key columns for SRT_Queue and SRT_DistQueue */
  17860. };
  17861. /*
  17862. ** During code generation of statements that do inserts into AUTOINCREMENT
  17863. ** tables, the following information is attached to the Table.u.autoInc.p
  17864. ** pointer of each autoincrement table to record some side information that
  17865. ** the code generator needs. We have to keep per-table autoincrement
  17866. ** information in case inserts are done within triggers. Triggers do not
  17867. ** normally coordinate their activities, but we do need to coordinate the
  17868. ** loading and saving of autoincrement information.
  17869. */
  17870. struct AutoincInfo {
  17871. AutoincInfo *pNext; /* Next info block in a list of them all */
  17872. Table *pTab; /* Table this info block refers to */
  17873. int iDb; /* Index in sqlite3.aDb[] of database holding pTab */
  17874. int regCtr; /* Memory register holding the rowid counter */
  17875. };
  17876. /*
  17877. ** At least one instance of the following structure is created for each
  17878. ** trigger that may be fired while parsing an INSERT, UPDATE or DELETE
  17879. ** statement. All such objects are stored in the linked list headed at
  17880. ** Parse.pTriggerPrg and deleted once statement compilation has been
  17881. ** completed.
  17882. **
  17883. ** A Vdbe sub-program that implements the body and WHEN clause of trigger
  17884. ** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of
  17885. ** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.
  17886. ** The Parse.pTriggerPrg list never contains two entries with the same
  17887. ** values for both pTrigger and orconf.
  17888. **
  17889. ** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns
  17890. ** accessed (or set to 0 for triggers fired as a result of INSERT
  17891. ** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to
  17892. ** a mask of new.* columns used by the program.
  17893. */
  17894. struct TriggerPrg {
  17895. Trigger *pTrigger; /* Trigger this program was coded from */
  17896. TriggerPrg *pNext; /* Next entry in Parse.pTriggerPrg list */
  17897. SubProgram *pProgram; /* Program implementing pTrigger/orconf */
  17898. int orconf; /* Default ON CONFLICT policy */
  17899. u32 aColmask[2]; /* Masks of old.*, new.* columns accessed */
  17900. };
  17901. /*
  17902. ** The yDbMask datatype for the bitmask of all attached databases.
  17903. */
  17904. #if SQLITE_MAX_ATTACHED>30
  17905. typedef unsigned char yDbMask[(SQLITE_MAX_ATTACHED+9)/8];
  17906. # define DbMaskTest(M,I) (((M)[(I)/8]&(1<<((I)&7)))!=0)
  17907. # define DbMaskZero(M) memset((M),0,sizeof(M))
  17908. # define DbMaskSet(M,I) (M)[(I)/8]|=(1<<((I)&7))
  17909. # define DbMaskAllZero(M) sqlite3DbMaskAllZero(M)
  17910. # define DbMaskNonZero(M) (sqlite3DbMaskAllZero(M)==0)
  17911. #else
  17912. typedef unsigned int yDbMask;
  17913. # define DbMaskTest(M,I) (((M)&(((yDbMask)1)<<(I)))!=0)
  17914. # define DbMaskZero(M) (M)=0
  17915. # define DbMaskSet(M,I) (M)|=(((yDbMask)1)<<(I))
  17916. # define DbMaskAllZero(M) (M)==0
  17917. # define DbMaskNonZero(M) (M)!=0
  17918. #endif
  17919. /*
  17920. ** An SQL parser context. A copy of this structure is passed through
  17921. ** the parser and down into all the parser action routine in order to
  17922. ** carry around information that is global to the entire parse.
  17923. **
  17924. ** The structure is divided into two parts. When the parser and code
  17925. ** generate call themselves recursively, the first part of the structure
  17926. ** is constant but the second part is reset at the beginning and end of
  17927. ** each recursion.
  17928. **
  17929. ** The nTableLock and aTableLock variables are only used if the shared-cache
  17930. ** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
  17931. ** used to store the set of table-locks required by the statement being
  17932. ** compiled. Function sqlite3TableLock() is used to add entries to the
  17933. ** list.
  17934. */
  17935. struct Parse {
  17936. sqlite3 *db; /* The main database structure */
  17937. char *zErrMsg; /* An error message */
  17938. Vdbe *pVdbe; /* An engine for executing database bytecode */
  17939. int rc; /* Return code from execution */
  17940. u8 colNamesSet; /* TRUE after OP_ColumnName has been issued to pVdbe */
  17941. u8 checkSchema; /* Causes schema cookie check after an error */
  17942. u8 nested; /* Number of nested calls to the parser/code generator */
  17943. u8 nTempReg; /* Number of temporary registers in aTempReg[] */
  17944. u8 isMultiWrite; /* True if statement may modify/insert multiple rows */
  17945. u8 mayAbort; /* True if statement may throw an ABORT exception */
  17946. u8 hasCompound; /* Need to invoke convertCompoundSelectToSubquery() */
  17947. u8 okConstFactor; /* OK to factor out constants */
  17948. u8 disableLookaside; /* Number of times lookaside has been disabled */
  17949. u8 disableVtab; /* Disable all virtual tables for this parse */
  17950. int nRangeReg; /* Size of the temporary register block */
  17951. int iRangeReg; /* First register in temporary register block */
  17952. int nErr; /* Number of errors seen */
  17953. int nTab; /* Number of previously allocated VDBE cursors */
  17954. int nMem; /* Number of memory cells used so far */
  17955. int szOpAlloc; /* Bytes of memory space allocated for Vdbe.aOp[] */
  17956. int iSelfTab; /* Table associated with an index on expr, or negative
  17957. ** of the base register during check-constraint eval */
  17958. int nLabel; /* The *negative* of the number of labels used */
  17959. int nLabelAlloc; /* Number of slots in aLabel */
  17960. int *aLabel; /* Space to hold the labels */
  17961. ExprList *pConstExpr;/* Constant expressions */
  17962. Token constraintName;/* Name of the constraint currently being parsed */
  17963. yDbMask writeMask; /* Start a write transaction on these databases */
  17964. yDbMask cookieMask; /* Bitmask of schema verified databases */
  17965. int regRowid; /* Register holding rowid of CREATE TABLE entry */
  17966. int regRoot; /* Register holding root page number for new objects */
  17967. int nMaxArg; /* Max args passed to user function by sub-program */
  17968. int nSelect; /* Number of SELECT stmts. Counter for Select.selId */
  17969. #ifndef SQLITE_OMIT_SHARED_CACHE
  17970. int nTableLock; /* Number of locks in aTableLock */
  17971. TableLock *aTableLock; /* Required table locks for shared-cache mode */
  17972. #endif
  17973. AutoincInfo *pAinc; /* Information about AUTOINCREMENT counters */
  17974. Parse *pToplevel; /* Parse structure for main program (or NULL) */
  17975. Table *pTriggerTab; /* Table triggers are being coded for */
  17976. Parse *pParentParse; /* Parent parser if this parser is nested */
  17977. int addrCrTab; /* Address of OP_CreateBtree opcode on CREATE TABLE */
  17978. u32 nQueryLoop; /* Est number of iterations of a query (10*log2(N)) */
  17979. u32 oldmask; /* Mask of old.* columns referenced */
  17980. u32 newmask; /* Mask of new.* columns referenced */
  17981. u8 eTriggerOp; /* TK_UPDATE, TK_INSERT or TK_DELETE */
  17982. u8 eOrconf; /* Default ON CONFLICT policy for trigger steps */
  17983. u8 disableTriggers; /* True to disable triggers */
  17984. /**************************************************************************
  17985. ** Fields above must be initialized to zero. The fields that follow,
  17986. ** down to the beginning of the recursive section, do not need to be
  17987. ** initialized as they will be set before being used. The boundary is
  17988. ** determined by offsetof(Parse,aTempReg).
  17989. **************************************************************************/
  17990. int aTempReg[8]; /* Holding area for temporary registers */
  17991. Token sNameToken; /* Token with unqualified schema object name */
  17992. /************************************************************************
  17993. ** Above is constant between recursions. Below is reset before and after
  17994. ** each recursion. The boundary between these two regions is determined
  17995. ** using offsetof(Parse,sLastToken) so the sLastToken field must be the
  17996. ** first field in the recursive region.
  17997. ************************************************************************/
  17998. Token sLastToken; /* The last token parsed */
  17999. ynVar nVar; /* Number of '?' variables seen in the SQL so far */
  18000. u8 iPkSortOrder; /* ASC or DESC for INTEGER PRIMARY KEY */
  18001. u8 explain; /* True if the EXPLAIN flag is found on the query */
  18002. #if !(defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_OMIT_ALTERTABLE))
  18003. u8 eParseMode; /* PARSE_MODE_XXX constant */
  18004. #endif
  18005. #ifndef SQLITE_OMIT_VIRTUALTABLE
  18006. int nVtabLock; /* Number of virtual tables to lock */
  18007. #endif
  18008. int nHeight; /* Expression tree height of current sub-select */
  18009. #ifndef SQLITE_OMIT_EXPLAIN
  18010. int addrExplain; /* Address of current OP_Explain opcode */
  18011. #endif
  18012. VList *pVList; /* Mapping between variable names and numbers */
  18013. Vdbe *pReprepare; /* VM being reprepared (sqlite3Reprepare()) */
  18014. const char *zTail; /* All SQL text past the last semicolon parsed */
  18015. Table *pNewTable; /* A table being constructed by CREATE TABLE */
  18016. Index *pNewIndex; /* An index being constructed by CREATE INDEX.
  18017. ** Also used to hold redundant UNIQUE constraints
  18018. ** during a RENAME COLUMN */
  18019. Trigger *pNewTrigger; /* Trigger under construct by a CREATE TRIGGER */
  18020. const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
  18021. #ifndef SQLITE_OMIT_VIRTUALTABLE
  18022. Token sArg; /* Complete text of a module argument */
  18023. Table **apVtabLock; /* Pointer to virtual tables needing locking */
  18024. #endif
  18025. Table *pZombieTab; /* List of Table objects to delete after code gen */
  18026. TriggerPrg *pTriggerPrg; /* Linked list of coded triggers */
  18027. With *pWith; /* Current WITH clause, or NULL */
  18028. With *pWithToFree; /* Free this WITH object at the end of the parse */
  18029. #ifndef SQLITE_OMIT_ALTERTABLE
  18030. RenameToken *pRename; /* Tokens subject to renaming by ALTER TABLE */
  18031. #endif
  18032. };
  18033. #define PARSE_MODE_NORMAL 0
  18034. #define PARSE_MODE_DECLARE_VTAB 1
  18035. #define PARSE_MODE_RENAME 2
  18036. #define PARSE_MODE_UNMAP 3
  18037. /*
  18038. ** Sizes and pointers of various parts of the Parse object.
  18039. */
  18040. #define PARSE_HDR_SZ offsetof(Parse,aTempReg) /* Recursive part w/o aColCache*/
  18041. #define PARSE_RECURSE_SZ offsetof(Parse,sLastToken) /* Recursive part */
  18042. #define PARSE_TAIL_SZ (sizeof(Parse)-PARSE_RECURSE_SZ) /* Non-recursive part */
  18043. #define PARSE_TAIL(X) (((char*)(X))+PARSE_RECURSE_SZ) /* Pointer to tail */
  18044. /*
  18045. ** Return true if currently inside an sqlite3_declare_vtab() call.
  18046. */
  18047. #ifdef SQLITE_OMIT_VIRTUALTABLE
  18048. #define IN_DECLARE_VTAB 0
  18049. #else
  18050. #define IN_DECLARE_VTAB (pParse->eParseMode==PARSE_MODE_DECLARE_VTAB)
  18051. #endif
  18052. #if defined(SQLITE_OMIT_ALTERTABLE)
  18053. #define IN_RENAME_OBJECT 0
  18054. #else
  18055. #define IN_RENAME_OBJECT (pParse->eParseMode>=PARSE_MODE_RENAME)
  18056. #endif
  18057. #if defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_OMIT_ALTERTABLE)
  18058. #define IN_SPECIAL_PARSE 0
  18059. #else
  18060. #define IN_SPECIAL_PARSE (pParse->eParseMode!=PARSE_MODE_NORMAL)
  18061. #endif
  18062. /*
  18063. ** An instance of the following structure can be declared on a stack and used
  18064. ** to save the Parse.zAuthContext value so that it can be restored later.
  18065. */
  18066. struct AuthContext {
  18067. const char *zAuthContext; /* Put saved Parse.zAuthContext here */
  18068. Parse *pParse; /* The Parse structure */
  18069. };
  18070. /*
  18071. ** Bitfield flags for P5 value in various opcodes.
  18072. **
  18073. ** Value constraints (enforced via assert()):
  18074. ** OPFLAG_LENGTHARG == SQLITE_FUNC_LENGTH
  18075. ** OPFLAG_TYPEOFARG == SQLITE_FUNC_TYPEOF
  18076. ** OPFLAG_BULKCSR == BTREE_BULKLOAD
  18077. ** OPFLAG_SEEKEQ == BTREE_SEEK_EQ
  18078. ** OPFLAG_FORDELETE == BTREE_FORDELETE
  18079. ** OPFLAG_SAVEPOSITION == BTREE_SAVEPOSITION
  18080. ** OPFLAG_AUXDELETE == BTREE_AUXDELETE
  18081. */
  18082. #define OPFLAG_NCHANGE 0x01 /* OP_Insert: Set to update db->nChange */
  18083. /* Also used in P2 (not P5) of OP_Delete */
  18084. #define OPFLAG_NOCHNG 0x01 /* OP_VColumn nochange for UPDATE */
  18085. #define OPFLAG_EPHEM 0x01 /* OP_Column: Ephemeral output is ok */
  18086. #define OPFLAG_LASTROWID 0x20 /* Set to update db->lastRowid */
  18087. #define OPFLAG_ISUPDATE 0x04 /* This OP_Insert is an sql UPDATE */
  18088. #define OPFLAG_APPEND 0x08 /* This is likely to be an append */
  18089. #define OPFLAG_USESEEKRESULT 0x10 /* Try to avoid a seek in BtreeInsert() */
  18090. #define OPFLAG_ISNOOP 0x40 /* OP_Delete does pre-update-hook only */
  18091. #define OPFLAG_LENGTHARG 0x40 /* OP_Column only used for length() */
  18092. #define OPFLAG_TYPEOFARG 0x80 /* OP_Column only used for typeof() */
  18093. #define OPFLAG_BULKCSR 0x01 /* OP_Open** used to open bulk cursor */
  18094. #define OPFLAG_SEEKEQ 0x02 /* OP_Open** cursor uses EQ seek only */
  18095. #define OPFLAG_FORDELETE 0x08 /* OP_Open should use BTREE_FORDELETE */
  18096. #define OPFLAG_P2ISREG 0x10 /* P2 to OP_Open** is a register number */
  18097. #define OPFLAG_PERMUTE 0x01 /* OP_Compare: use the permutation */
  18098. #define OPFLAG_SAVEPOSITION 0x02 /* OP_Delete/Insert: save cursor pos */
  18099. #define OPFLAG_AUXDELETE 0x04 /* OP_Delete: index in a DELETE op */
  18100. #define OPFLAG_NOCHNG_MAGIC 0x6d /* OP_MakeRecord: serialtype 10 is ok */
  18101. /*
  18102. * Each trigger present in the database schema is stored as an instance of
  18103. * struct Trigger.
  18104. *
  18105. * Pointers to instances of struct Trigger are stored in two ways.
  18106. * 1. In the "trigHash" hash table (part of the sqlite3* that represents the
  18107. * database). This allows Trigger structures to be retrieved by name.
  18108. * 2. All triggers associated with a single table form a linked list, using the
  18109. * pNext member of struct Trigger. A pointer to the first element of the
  18110. * linked list is stored as the "pTrigger" member of the associated
  18111. * struct Table.
  18112. *
  18113. * The "step_list" member points to the first element of a linked list
  18114. * containing the SQL statements specified as the trigger program.
  18115. */
  18116. struct Trigger {
  18117. char *zName; /* The name of the trigger */
  18118. char *table; /* The table or view to which the trigger applies */
  18119. u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT */
  18120. u8 tr_tm; /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
  18121. Expr *pWhen; /* The WHEN clause of the expression (may be NULL) */
  18122. IdList *pColumns; /* If this is an UPDATE OF <column-list> trigger,
  18123. the <column-list> is stored here */
  18124. Schema *pSchema; /* Schema containing the trigger */
  18125. Schema *pTabSchema; /* Schema containing the table */
  18126. TriggerStep *step_list; /* Link list of trigger program steps */
  18127. Trigger *pNext; /* Next trigger associated with the table */
  18128. };
  18129. /*
  18130. ** A trigger is either a BEFORE or an AFTER trigger. The following constants
  18131. ** determine which.
  18132. **
  18133. ** If there are multiple triggers, you might of some BEFORE and some AFTER.
  18134. ** In that cases, the constants below can be ORed together.
  18135. */
  18136. #define TRIGGER_BEFORE 1
  18137. #define TRIGGER_AFTER 2
  18138. /*
  18139. * An instance of struct TriggerStep is used to store a single SQL statement
  18140. * that is a part of a trigger-program.
  18141. *
  18142. * Instances of struct TriggerStep are stored in a singly linked list (linked
  18143. * using the "pNext" member) referenced by the "step_list" member of the
  18144. * associated struct Trigger instance. The first element of the linked list is
  18145. * the first step of the trigger-program.
  18146. *
  18147. * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
  18148. * "SELECT" statement. The meanings of the other members is determined by the
  18149. * value of "op" as follows:
  18150. *
  18151. * (op == TK_INSERT)
  18152. * orconf -> stores the ON CONFLICT algorithm
  18153. * pSelect -> If this is an INSERT INTO ... SELECT ... statement, then
  18154. * this stores a pointer to the SELECT statement. Otherwise NULL.
  18155. * zTarget -> Dequoted name of the table to insert into.
  18156. * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
  18157. * this stores values to be inserted. Otherwise NULL.
  18158. * pIdList -> If this is an INSERT INTO ... (<column-names>) VALUES ...
  18159. * statement, then this stores the column-names to be
  18160. * inserted into.
  18161. *
  18162. * (op == TK_DELETE)
  18163. * zTarget -> Dequoted name of the table to delete from.
  18164. * pWhere -> The WHERE clause of the DELETE statement if one is specified.
  18165. * Otherwise NULL.
  18166. *
  18167. * (op == TK_UPDATE)
  18168. * zTarget -> Dequoted name of the table to update.
  18169. * pWhere -> The WHERE clause of the UPDATE statement if one is specified.
  18170. * Otherwise NULL.
  18171. * pExprList -> A list of the columns to update and the expressions to update
  18172. * them to. See sqlite3Update() documentation of "pChanges"
  18173. * argument.
  18174. *
  18175. */
  18176. struct TriggerStep {
  18177. u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
  18178. u8 orconf; /* OE_Rollback etc. */
  18179. Trigger *pTrig; /* The trigger that this step is a part of */
  18180. Select *pSelect; /* SELECT statement or RHS of INSERT INTO SELECT ... */
  18181. char *zTarget; /* Target table for DELETE, UPDATE, INSERT */
  18182. Expr *pWhere; /* The WHERE clause for DELETE or UPDATE steps */
  18183. ExprList *pExprList; /* SET clause for UPDATE */
  18184. IdList *pIdList; /* Column names for INSERT */
  18185. Upsert *pUpsert; /* Upsert clauses on an INSERT */
  18186. char *zSpan; /* Original SQL text of this command */
  18187. TriggerStep *pNext; /* Next in the link-list */
  18188. TriggerStep *pLast; /* Last element in link-list. Valid for 1st elem only */
  18189. };
  18190. /*
  18191. ** The following structure contains information used by the sqliteFix...
  18192. ** routines as they walk the parse tree to make database references
  18193. ** explicit.
  18194. */
  18195. typedef struct DbFixer DbFixer;
  18196. struct DbFixer {
  18197. Parse *pParse; /* The parsing context. Error messages written here */
  18198. Schema *pSchema; /* Fix items to this schema */
  18199. u8 bTemp; /* True for TEMP schema entries */
  18200. const char *zDb; /* Make sure all objects are contained in this database */
  18201. const char *zType; /* Type of the container - used for error messages */
  18202. const Token *pName; /* Name of the container - used for error messages */
  18203. };
  18204. /*
  18205. ** An objected used to accumulate the text of a string where we
  18206. ** do not necessarily know how big the string will be in the end.
  18207. */
  18208. struct sqlite3_str {
  18209. sqlite3 *db; /* Optional database for lookaside. Can be NULL */
  18210. char *zText; /* The string collected so far */
  18211. u32 nAlloc; /* Amount of space allocated in zText */
  18212. u32 mxAlloc; /* Maximum allowed allocation. 0 for no malloc usage */
  18213. u32 nChar; /* Length of the string so far */
  18214. u8 accError; /* SQLITE_NOMEM or SQLITE_TOOBIG */
  18215. u8 printfFlags; /* SQLITE_PRINTF flags below */
  18216. };
  18217. #define SQLITE_PRINTF_INTERNAL 0x01 /* Internal-use-only converters allowed */
  18218. #define SQLITE_PRINTF_SQLFUNC 0x02 /* SQL function arguments to VXPrintf */
  18219. #define SQLITE_PRINTF_MALLOCED 0x04 /* True if xText is allocated space */
  18220. #define isMalloced(X) (((X)->printfFlags & SQLITE_PRINTF_MALLOCED)!=0)
  18221. /*
  18222. ** A pointer to this structure is used to communicate information
  18223. ** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
  18224. */
  18225. typedef struct {
  18226. sqlite3 *db; /* The database being initialized */
  18227. char **pzErrMsg; /* Error message stored here */
  18228. int iDb; /* 0 for main database. 1 for TEMP, 2.. for ATTACHed */
  18229. int rc; /* Result code stored here */
  18230. u32 mInitFlags; /* Flags controlling error messages */
  18231. u32 nInitRow; /* Number of rows processed */
  18232. } InitData;
  18233. /*
  18234. ** Allowed values for mInitFlags
  18235. */
  18236. #define INITFLAG_AlterTable 0x0001 /* This is a reparse after ALTER TABLE */
  18237. /*
  18238. ** Structure containing global configuration data for the SQLite library.
  18239. **
  18240. ** This structure also contains some state information.
  18241. */
  18242. struct Sqlite3Config {
  18243. int bMemstat; /* True to enable memory status */
  18244. u8 bCoreMutex; /* True to enable core mutexing */
  18245. u8 bFullMutex; /* True to enable full mutexing */
  18246. u8 bOpenUri; /* True to interpret filenames as URIs */
  18247. u8 bUseCis; /* Use covering indices for full-scans */
  18248. u8 bSmallMalloc; /* Avoid large memory allocations if true */
  18249. u8 bExtraSchemaChecks; /* Verify type,name,tbl_name in schema */
  18250. int mxStrlen; /* Maximum string length */
  18251. int neverCorrupt; /* Database is always well-formed */
  18252. int szLookaside; /* Default lookaside buffer size */
  18253. int nLookaside; /* Default lookaside buffer count */
  18254. int nStmtSpill; /* Stmt-journal spill-to-disk threshold */
  18255. sqlite3_mem_methods m; /* Low-level memory allocation interface */
  18256. sqlite3_mutex_methods mutex; /* Low-level mutex interface */
  18257. sqlite3_pcache_methods2 pcache2; /* Low-level page-cache interface */
  18258. void *pHeap; /* Heap storage space */
  18259. int nHeap; /* Size of pHeap[] */
  18260. int mnReq, mxReq; /* Min and max heap requests sizes */
  18261. sqlite3_int64 szMmap; /* mmap() space per open file */
  18262. sqlite3_int64 mxMmap; /* Maximum value for szMmap */
  18263. void *pPage; /* Page cache memory */
  18264. int szPage; /* Size of each page in pPage[] */
  18265. int nPage; /* Number of pages in pPage[] */
  18266. int mxParserStack; /* maximum depth of the parser stack */
  18267. int sharedCacheEnabled; /* true if shared-cache mode enabled */
  18268. u32 szPma; /* Maximum Sorter PMA size */
  18269. /* The above might be initialized to non-zero. The following need to always
  18270. ** initially be zero, however. */
  18271. int isInit; /* True after initialization has finished */
  18272. int inProgress; /* True while initialization in progress */
  18273. int isMutexInit; /* True after mutexes are initialized */
  18274. int isMallocInit; /* True after malloc is initialized */
  18275. int isPCacheInit; /* True after malloc is initialized */
  18276. int nRefInitMutex; /* Number of users of pInitMutex */
  18277. sqlite3_mutex *pInitMutex; /* Mutex used by sqlite3_initialize() */
  18278. void (*xLog)(void*,int,const char*); /* Function for logging */
  18279. void *pLogArg; /* First argument to xLog() */
  18280. #ifdef SQLITE_ENABLE_SQLLOG
  18281. void(*xSqllog)(void*,sqlite3*,const char*, int);
  18282. void *pSqllogArg;
  18283. #endif
  18284. #ifdef SQLITE_VDBE_COVERAGE
  18285. /* The following callback (if not NULL) is invoked on every VDBE branch
  18286. ** operation. Set the callback using SQLITE_TESTCTRL_VDBE_COVERAGE.
  18287. */
  18288. void (*xVdbeBranch)(void*,unsigned iSrcLine,u8 eThis,u8 eMx); /* Callback */
  18289. void *pVdbeBranchArg; /* 1st argument */
  18290. #endif
  18291. #ifdef SQLITE_ENABLE_DESERIALIZE
  18292. sqlite3_int64 mxMemdbSize; /* Default max memdb size */
  18293. #endif
  18294. #ifndef SQLITE_UNTESTABLE
  18295. int (*xTestCallback)(int); /* Invoked by sqlite3FaultSim() */
  18296. #endif
  18297. int bLocaltimeFault; /* True to fail localtime() calls */
  18298. int iOnceResetThreshold; /* When to reset OP_Once counters */
  18299. u32 szSorterRef; /* Min size in bytes to use sorter-refs */
  18300. unsigned int iPrngSeed; /* Alternative fixed seed for the PRNG */
  18301. };
  18302. /*
  18303. ** This macro is used inside of assert() statements to indicate that
  18304. ** the assert is only valid on a well-formed database. Instead of:
  18305. **
  18306. ** assert( X );
  18307. **
  18308. ** One writes:
  18309. **
  18310. ** assert( X || CORRUPT_DB );
  18311. **
  18312. ** CORRUPT_DB is true during normal operation. CORRUPT_DB does not indicate
  18313. ** that the database is definitely corrupt, only that it might be corrupt.
  18314. ** For most test cases, CORRUPT_DB is set to false using a special
  18315. ** sqlite3_test_control(). This enables assert() statements to prove
  18316. ** things that are always true for well-formed databases.
  18317. */
  18318. #define CORRUPT_DB (sqlite3Config.neverCorrupt==0)
  18319. /*
  18320. ** Context pointer passed down through the tree-walk.
  18321. */
  18322. struct Walker {
  18323. Parse *pParse; /* Parser context. */
  18324. int (*xExprCallback)(Walker*, Expr*); /* Callback for expressions */
  18325. int (*xSelectCallback)(Walker*,Select*); /* Callback for SELECTs */
  18326. void (*xSelectCallback2)(Walker*,Select*);/* Second callback for SELECTs */
  18327. int walkerDepth; /* Number of subqueries */
  18328. u16 eCode; /* A small processing code */
  18329. union { /* Extra data for callback */
  18330. NameContext *pNC; /* Naming context */
  18331. int n; /* A counter */
  18332. int iCur; /* A cursor number */
  18333. SrcList *pSrcList; /* FROM clause */
  18334. struct SrcCount *pSrcCount; /* Counting column references */
  18335. struct CCurHint *pCCurHint; /* Used by codeCursorHint() */
  18336. int *aiCol; /* array of column indexes */
  18337. struct IdxCover *pIdxCover; /* Check for index coverage */
  18338. struct IdxExprTrans *pIdxTrans; /* Convert idxed expr to column */
  18339. ExprList *pGroupBy; /* GROUP BY clause */
  18340. Select *pSelect; /* HAVING to WHERE clause ctx */
  18341. struct WindowRewrite *pRewrite; /* Window rewrite context */
  18342. struct WhereConst *pConst; /* WHERE clause constants */
  18343. struct RenameCtx *pRename; /* RENAME COLUMN context */
  18344. struct Table *pTab; /* Table of generated column */
  18345. struct SrcList_item *pSrcItem; /* A single FROM clause item */
  18346. } u;
  18347. };
  18348. /* Forward declarations */
  18349. SQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*);
  18350. SQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*);
  18351. SQLITE_PRIVATE int sqlite3WalkSelect(Walker*, Select*);
  18352. SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker*, Select*);
  18353. SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*);
  18354. SQLITE_PRIVATE int sqlite3ExprWalkNoop(Walker*, Expr*);
  18355. SQLITE_PRIVATE int sqlite3SelectWalkNoop(Walker*, Select*);
  18356. SQLITE_PRIVATE int sqlite3SelectWalkFail(Walker*, Select*);
  18357. SQLITE_PRIVATE int sqlite3WalkerDepthIncrease(Walker*,Select*);
  18358. SQLITE_PRIVATE void sqlite3WalkerDepthDecrease(Walker*,Select*);
  18359. #ifdef SQLITE_DEBUG
  18360. SQLITE_PRIVATE void sqlite3SelectWalkAssert2(Walker*, Select*);
  18361. #endif
  18362. /*
  18363. ** Return code from the parse-tree walking primitives and their
  18364. ** callbacks.
  18365. */
  18366. #define WRC_Continue 0 /* Continue down into children */
  18367. #define WRC_Prune 1 /* Omit children but continue walking siblings */
  18368. #define WRC_Abort 2 /* Abandon the tree walk */
  18369. /*
  18370. ** An instance of this structure represents a set of one or more CTEs
  18371. ** (common table expressions) created by a single WITH clause.
  18372. */
  18373. struct With {
  18374. int nCte; /* Number of CTEs in the WITH clause */
  18375. With *pOuter; /* Containing WITH clause, or NULL */
  18376. struct Cte { /* For each CTE in the WITH clause.... */
  18377. char *zName; /* Name of this CTE */
  18378. ExprList *pCols; /* List of explicit column names, or NULL */
  18379. Select *pSelect; /* The definition of this CTE */
  18380. const char *zCteErr; /* Error message for circular references */
  18381. } a[1];
  18382. };
  18383. #ifdef SQLITE_DEBUG
  18384. /*
  18385. ** An instance of the TreeView object is used for printing the content of
  18386. ** data structures on sqlite3DebugPrintf() using a tree-like view.
  18387. */
  18388. struct TreeView {
  18389. int iLevel; /* Which level of the tree we are on */
  18390. u8 bLine[100]; /* Draw vertical in column i if bLine[i] is true */
  18391. };
  18392. #endif /* SQLITE_DEBUG */
  18393. /*
  18394. ** This object is used in various ways, most (but not all) related to window
  18395. ** functions.
  18396. **
  18397. ** (1) A single instance of this structure is attached to the
  18398. ** the Expr.y.pWin field for each window function in an expression tree.
  18399. ** This object holds the information contained in the OVER clause,
  18400. ** plus additional fields used during code generation.
  18401. **
  18402. ** (2) All window functions in a single SELECT form a linked-list
  18403. ** attached to Select.pWin. The Window.pFunc and Window.pExpr
  18404. ** fields point back to the expression that is the window function.
  18405. **
  18406. ** (3) The terms of the WINDOW clause of a SELECT are instances of this
  18407. ** object on a linked list attached to Select.pWinDefn.
  18408. **
  18409. ** (4) For an aggregate function with a FILTER clause, an instance
  18410. ** of this object is stored in Expr.y.pWin with eFrmType set to
  18411. ** TK_FILTER. In this case the only field used is Window.pFilter.
  18412. **
  18413. ** The uses (1) and (2) are really the same Window object that just happens
  18414. ** to be accessible in two different ways. Use case (3) are separate objects.
  18415. */
  18416. struct Window {
  18417. char *zName; /* Name of window (may be NULL) */
  18418. char *zBase; /* Name of base window for chaining (may be NULL) */
  18419. ExprList *pPartition; /* PARTITION BY clause */
  18420. ExprList *pOrderBy; /* ORDER BY clause */
  18421. u8 eFrmType; /* TK_RANGE, TK_GROUPS, TK_ROWS, or 0 */
  18422. u8 eStart; /* UNBOUNDED, CURRENT, PRECEDING or FOLLOWING */
  18423. u8 eEnd; /* UNBOUNDED, CURRENT, PRECEDING or FOLLOWING */
  18424. u8 bImplicitFrame; /* True if frame was implicitly specified */
  18425. u8 eExclude; /* TK_NO, TK_CURRENT, TK_TIES, TK_GROUP, or 0 */
  18426. Expr *pStart; /* Expression for "<expr> PRECEDING" */
  18427. Expr *pEnd; /* Expression for "<expr> FOLLOWING" */
  18428. Window **ppThis; /* Pointer to this object in Select.pWin list */
  18429. Window *pNextWin; /* Next window function belonging to this SELECT */
  18430. Expr *pFilter; /* The FILTER expression */
  18431. FuncDef *pFunc; /* The function */
  18432. int iEphCsr; /* Partition buffer or Peer buffer */
  18433. int regAccum; /* Accumulator */
  18434. int regResult; /* Interim result */
  18435. int csrApp; /* Function cursor (used by min/max) */
  18436. int regApp; /* Function register (also used by min/max) */
  18437. int regPart; /* Array of registers for PARTITION BY values */
  18438. Expr *pOwner; /* Expression object this window is attached to */
  18439. int nBufferCol; /* Number of columns in buffer table */
  18440. int iArgCol; /* Offset of first argument for this function */
  18441. int regOne; /* Register containing constant value 1 */
  18442. int regStartRowid;
  18443. int regEndRowid;
  18444. u8 bExprArgs; /* Defer evaluation of window function arguments
  18445. ** due to the SQLITE_SUBTYPE flag */
  18446. };
  18447. #ifndef SQLITE_OMIT_WINDOWFUNC
  18448. SQLITE_PRIVATE void sqlite3WindowDelete(sqlite3*, Window*);
  18449. SQLITE_PRIVATE void sqlite3WindowUnlinkFromSelect(Window*);
  18450. SQLITE_PRIVATE void sqlite3WindowListDelete(sqlite3 *db, Window *p);
  18451. SQLITE_PRIVATE Window *sqlite3WindowAlloc(Parse*, int, int, Expr*, int , Expr*, u8);
  18452. SQLITE_PRIVATE void sqlite3WindowAttach(Parse*, Expr*, Window*);
  18453. SQLITE_PRIVATE void sqlite3WindowLink(Select *pSel, Window *pWin);
  18454. SQLITE_PRIVATE int sqlite3WindowCompare(Parse*, Window*, Window*, int);
  18455. SQLITE_PRIVATE void sqlite3WindowCodeInit(Parse*, Select*);
  18456. SQLITE_PRIVATE void sqlite3WindowCodeStep(Parse*, Select*, WhereInfo*, int, int);
  18457. SQLITE_PRIVATE int sqlite3WindowRewrite(Parse*, Select*);
  18458. SQLITE_PRIVATE int sqlite3ExpandSubquery(Parse*, struct SrcList_item*);
  18459. SQLITE_PRIVATE void sqlite3WindowUpdate(Parse*, Window*, Window*, FuncDef*);
  18460. SQLITE_PRIVATE Window *sqlite3WindowDup(sqlite3 *db, Expr *pOwner, Window *p);
  18461. SQLITE_PRIVATE Window *sqlite3WindowListDup(sqlite3 *db, Window *p);
  18462. SQLITE_PRIVATE void sqlite3WindowFunctions(void);
  18463. SQLITE_PRIVATE void sqlite3WindowChain(Parse*, Window*, Window*);
  18464. SQLITE_PRIVATE Window *sqlite3WindowAssemble(Parse*, Window*, ExprList*, ExprList*, Token*);
  18465. #else
  18466. # define sqlite3WindowDelete(a,b)
  18467. # define sqlite3WindowFunctions()
  18468. # define sqlite3WindowAttach(a,b,c)
  18469. #endif
  18470. /*
  18471. ** Assuming zIn points to the first byte of a UTF-8 character,
  18472. ** advance zIn to point to the first byte of the next UTF-8 character.
  18473. */
  18474. #define SQLITE_SKIP_UTF8(zIn) { \
  18475. if( (*(zIn++))>=0xc0 ){ \
  18476. while( (*zIn & 0xc0)==0x80 ){ zIn++; } \
  18477. } \
  18478. }
  18479. /*
  18480. ** The SQLITE_*_BKPT macros are substitutes for the error codes with
  18481. ** the same name but without the _BKPT suffix. These macros invoke
  18482. ** routines that report the line-number on which the error originated
  18483. ** using sqlite3_log(). The routines also provide a convenient place
  18484. ** to set a debugger breakpoint.
  18485. */
  18486. SQLITE_PRIVATE int sqlite3ReportError(int iErr, int lineno, const char *zType);
  18487. SQLITE_PRIVATE int sqlite3CorruptError(int);
  18488. SQLITE_PRIVATE int sqlite3MisuseError(int);
  18489. SQLITE_PRIVATE int sqlite3CantopenError(int);
  18490. #define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__)
  18491. #define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__)
  18492. #define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__)
  18493. #ifdef SQLITE_DEBUG
  18494. SQLITE_PRIVATE int sqlite3NomemError(int);
  18495. SQLITE_PRIVATE int sqlite3IoerrnomemError(int);
  18496. # define SQLITE_NOMEM_BKPT sqlite3NomemError(__LINE__)
  18497. # define SQLITE_IOERR_NOMEM_BKPT sqlite3IoerrnomemError(__LINE__)
  18498. #else
  18499. # define SQLITE_NOMEM_BKPT SQLITE_NOMEM
  18500. # define SQLITE_IOERR_NOMEM_BKPT SQLITE_IOERR_NOMEM
  18501. #endif
  18502. #if defined(SQLITE_DEBUG) || defined(SQLITE_ENABLE_CORRUPT_PGNO)
  18503. SQLITE_PRIVATE int sqlite3CorruptPgnoError(int,Pgno);
  18504. # define SQLITE_CORRUPT_PGNO(P) sqlite3CorruptPgnoError(__LINE__,(P))
  18505. #else
  18506. # define SQLITE_CORRUPT_PGNO(P) sqlite3CorruptError(__LINE__)
  18507. #endif
  18508. /*
  18509. ** FTS3 and FTS4 both require virtual table support
  18510. */
  18511. #if defined(SQLITE_OMIT_VIRTUALTABLE)
  18512. # undef SQLITE_ENABLE_FTS3
  18513. # undef SQLITE_ENABLE_FTS4
  18514. #endif
  18515. /*
  18516. ** FTS4 is really an extension for FTS3. It is enabled using the
  18517. ** SQLITE_ENABLE_FTS3 macro. But to avoid confusion we also call
  18518. ** the SQLITE_ENABLE_FTS4 macro to serve as an alias for SQLITE_ENABLE_FTS3.
  18519. */
  18520. #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
  18521. # define SQLITE_ENABLE_FTS3 1
  18522. #endif
  18523. /*
  18524. ** The ctype.h header is needed for non-ASCII systems. It is also
  18525. ** needed by FTS3 when FTS3 is included in the amalgamation.
  18526. */
  18527. #if !defined(SQLITE_ASCII) || \
  18528. (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION))
  18529. # include <ctype.h>
  18530. #endif
  18531. /*
  18532. ** The following macros mimic the standard library functions toupper(),
  18533. ** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
  18534. ** sqlite versions only work for ASCII characters, regardless of locale.
  18535. */
  18536. #ifdef SQLITE_ASCII
  18537. # define sqlite3Toupper(x) ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
  18538. # define sqlite3Isspace(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
  18539. # define sqlite3Isalnum(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
  18540. # define sqlite3Isalpha(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
  18541. # define sqlite3Isdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
  18542. # define sqlite3Isxdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
  18543. # define sqlite3Tolower(x) (sqlite3UpperToLower[(unsigned char)(x)])
  18544. # define sqlite3Isquote(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x80)
  18545. #else
  18546. # define sqlite3Toupper(x) toupper((unsigned char)(x))
  18547. # define sqlite3Isspace(x) isspace((unsigned char)(x))
  18548. # define sqlite3Isalnum(x) isalnum((unsigned char)(x))
  18549. # define sqlite3Isalpha(x) isalpha((unsigned char)(x))
  18550. # define sqlite3Isdigit(x) isdigit((unsigned char)(x))
  18551. # define sqlite3Isxdigit(x) isxdigit((unsigned char)(x))
  18552. # define sqlite3Tolower(x) tolower((unsigned char)(x))
  18553. # define sqlite3Isquote(x) ((x)=='"'||(x)=='\''||(x)=='['||(x)=='`')
  18554. #endif
  18555. SQLITE_PRIVATE int sqlite3IsIdChar(u8);
  18556. /*
  18557. ** Internal function prototypes
  18558. */
  18559. SQLITE_PRIVATE int sqlite3StrICmp(const char*,const char*);
  18560. SQLITE_PRIVATE int sqlite3Strlen30(const char*);
  18561. #define sqlite3Strlen30NN(C) (strlen(C)&0x3fffffff)
  18562. SQLITE_PRIVATE char *sqlite3ColumnType(Column*,char*);
  18563. #define sqlite3StrNICmp sqlite3_strnicmp
  18564. SQLITE_PRIVATE int sqlite3MallocInit(void);
  18565. SQLITE_PRIVATE void sqlite3MallocEnd(void);
  18566. SQLITE_PRIVATE void *sqlite3Malloc(u64);
  18567. SQLITE_PRIVATE void *sqlite3MallocZero(u64);
  18568. SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, u64);
  18569. SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, u64);
  18570. SQLITE_PRIVATE void *sqlite3DbMallocRawNN(sqlite3*, u64);
  18571. SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);
  18572. SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, u64);
  18573. SQLITE_PRIVATE char *sqlite3DbSpanDup(sqlite3*,const char*,const char*);
  18574. SQLITE_PRIVATE void *sqlite3Realloc(void*, u64);
  18575. SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, u64);
  18576. SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, u64);
  18577. SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*);
  18578. SQLITE_PRIVATE void sqlite3DbFreeNN(sqlite3*, void*);
  18579. SQLITE_PRIVATE int sqlite3MallocSize(void*);
  18580. SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, void*);
  18581. SQLITE_PRIVATE void *sqlite3PageMalloc(int);
  18582. SQLITE_PRIVATE void sqlite3PageFree(void*);
  18583. SQLITE_PRIVATE void sqlite3MemSetDefault(void);
  18584. #ifndef SQLITE_UNTESTABLE
  18585. SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
  18586. #endif
  18587. SQLITE_PRIVATE int sqlite3HeapNearlyFull(void);
  18588. /*
  18589. ** On systems with ample stack space and that support alloca(), make
  18590. ** use of alloca() to obtain space for large automatic objects. By default,
  18591. ** obtain space from malloc().
  18592. **
  18593. ** The alloca() routine never returns NULL. This will cause code paths
  18594. ** that deal with sqlite3StackAlloc() failures to be unreachable.
  18595. */
  18596. #ifdef SQLITE_USE_ALLOCA
  18597. # define sqlite3StackAllocRaw(D,N) alloca(N)
  18598. # define sqlite3StackAllocZero(D,N) memset(alloca(N), 0, N)
  18599. # define sqlite3StackFree(D,P)
  18600. #else
  18601. # define sqlite3StackAllocRaw(D,N) sqlite3DbMallocRaw(D,N)
  18602. # define sqlite3StackAllocZero(D,N) sqlite3DbMallocZero(D,N)
  18603. # define sqlite3StackFree(D,P) sqlite3DbFree(D,P)
  18604. #endif
  18605. /* Do not allow both MEMSYS5 and MEMSYS3 to be defined together. If they
  18606. ** are, disable MEMSYS3
  18607. */
  18608. #ifdef SQLITE_ENABLE_MEMSYS5
  18609. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
  18610. #undef SQLITE_ENABLE_MEMSYS3
  18611. #endif
  18612. #ifdef SQLITE_ENABLE_MEMSYS3
  18613. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
  18614. #endif
  18615. #ifndef SQLITE_MUTEX_OMIT
  18616. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void);
  18617. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void);
  18618. SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int);
  18619. SQLITE_PRIVATE int sqlite3MutexInit(void);
  18620. SQLITE_PRIVATE int sqlite3MutexEnd(void);
  18621. #endif
  18622. #if !defined(SQLITE_MUTEX_OMIT) && !defined(SQLITE_MUTEX_NOOP)
  18623. SQLITE_PRIVATE void sqlite3MemoryBarrier(void);
  18624. #else
  18625. # define sqlite3MemoryBarrier()
  18626. #endif
  18627. SQLITE_PRIVATE sqlite3_int64 sqlite3StatusValue(int);
  18628. SQLITE_PRIVATE void sqlite3StatusUp(int, int);
  18629. SQLITE_PRIVATE void sqlite3StatusDown(int, int);
  18630. SQLITE_PRIVATE void sqlite3StatusHighwater(int, int);
  18631. SQLITE_PRIVATE int sqlite3LookasideUsed(sqlite3*,int*);
  18632. /* Access to mutexes used by sqlite3_status() */
  18633. SQLITE_PRIVATE sqlite3_mutex *sqlite3Pcache1Mutex(void);
  18634. SQLITE_PRIVATE sqlite3_mutex *sqlite3MallocMutex(void);
  18635. #if defined(SQLITE_ENABLE_MULTITHREADED_CHECKS) && !defined(SQLITE_MUTEX_OMIT)
  18636. SQLITE_PRIVATE void sqlite3MutexWarnOnContention(sqlite3_mutex*);
  18637. #else
  18638. # define sqlite3MutexWarnOnContention(x)
  18639. #endif
  18640. #ifndef SQLITE_OMIT_FLOATING_POINT
  18641. # define EXP754 (((u64)0x7ff)<<52)
  18642. # define MAN754 ((((u64)1)<<52)-1)
  18643. # define IsNaN(X) (((X)&EXP754)==EXP754 && ((X)&MAN754)!=0)
  18644. SQLITE_PRIVATE int sqlite3IsNaN(double);
  18645. #else
  18646. # define IsNaN(X) 0
  18647. # define sqlite3IsNaN(X) 0
  18648. #endif
  18649. /*
  18650. ** An instance of the following structure holds information about SQL
  18651. ** functions arguments that are the parameters to the printf() function.
  18652. */
  18653. struct PrintfArguments {
  18654. int nArg; /* Total number of arguments */
  18655. int nUsed; /* Number of arguments used so far */
  18656. sqlite3_value **apArg; /* The argument values */
  18657. };
  18658. SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);
  18659. SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
  18660. #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
  18661. SQLITE_PRIVATE void sqlite3DebugPrintf(const char*, ...);
  18662. #endif
  18663. #if defined(SQLITE_TEST)
  18664. SQLITE_PRIVATE void *sqlite3TestTextToPtr(const char*);
  18665. #endif
  18666. #if defined(SQLITE_DEBUG)
  18667. SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView*, const Expr*, u8);
  18668. SQLITE_PRIVATE void sqlite3TreeViewBareExprList(TreeView*, const ExprList*, const char*);
  18669. SQLITE_PRIVATE void sqlite3TreeViewExprList(TreeView*, const ExprList*, u8, const char*);
  18670. SQLITE_PRIVATE void sqlite3TreeViewSrcList(TreeView*, const SrcList*);
  18671. SQLITE_PRIVATE void sqlite3TreeViewSelect(TreeView*, const Select*, u8);
  18672. SQLITE_PRIVATE void sqlite3TreeViewWith(TreeView*, const With*, u8);
  18673. #ifndef SQLITE_OMIT_WINDOWFUNC
  18674. SQLITE_PRIVATE void sqlite3TreeViewWindow(TreeView*, const Window*, u8);
  18675. SQLITE_PRIVATE void sqlite3TreeViewWinFunc(TreeView*, const Window*, u8);
  18676. #endif
  18677. #endif
  18678. SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*);
  18679. SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
  18680. SQLITE_PRIVATE int sqlite3ErrorToParser(sqlite3*,int);
  18681. SQLITE_PRIVATE void sqlite3Dequote(char*);
  18682. SQLITE_PRIVATE void sqlite3DequoteExpr(Expr*);
  18683. SQLITE_PRIVATE void sqlite3TokenInit(Token*,char*);
  18684. SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
  18685. SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
  18686. SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
  18687. SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
  18688. SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
  18689. SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);
  18690. SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);
  18691. SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse*);
  18692. #ifdef SQLITE_DEBUG
  18693. SQLITE_PRIVATE int sqlite3NoTempsInRange(Parse*,int,int);
  18694. #endif
  18695. SQLITE_PRIVATE Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);
  18696. SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*);
  18697. SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);
  18698. SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*);
  18699. SQLITE_PRIVATE void sqlite3PExprAddSelect(Parse*, Expr*, Select*);
  18700. SQLITE_PRIVATE Expr *sqlite3ExprAnd(Parse*,Expr*, Expr*);
  18701. SQLITE_PRIVATE Expr *sqlite3ExprSimplifiedAndOr(Expr*);
  18702. SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*, int);
  18703. SQLITE_PRIVATE void sqlite3ExprFunctionUsable(Parse*,Expr*,FuncDef*);
  18704. SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*, u32);
  18705. SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
  18706. SQLITE_PRIVATE void sqlite3ExprUnmapAndDelete(Parse*, Expr*);
  18707. SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
  18708. SQLITE_PRIVATE ExprList *sqlite3ExprListAppendVector(Parse*,ExprList*,IdList*,Expr*);
  18709. SQLITE_PRIVATE void sqlite3ExprListSetSortOrder(ExprList*,int,int);
  18710. SQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,Token*,int);
  18711. SQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse*,ExprList*,const char*,const char*);
  18712. SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*);
  18713. SQLITE_PRIVATE u32 sqlite3ExprListFlags(const ExprList*);
  18714. SQLITE_PRIVATE int sqlite3IndexHasDuplicateRootPage(Index*);
  18715. SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
  18716. SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
  18717. SQLITE_PRIVATE int sqlite3InitOne(sqlite3*, int, char**, u32);
  18718. SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
  18719. #ifndef SQLITE_OMIT_VIRTUALTABLE
  18720. SQLITE_PRIVATE Module *sqlite3PragmaVtabRegister(sqlite3*,const char *zName);
  18721. #endif
  18722. SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3*);
  18723. SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3*,int);
  18724. SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3*);
  18725. SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
  18726. SQLITE_PRIVATE void sqlite3DeleteColumnNames(sqlite3*,Table*);
  18727. SQLITE_PRIVATE int sqlite3ColumnsFromExprList(Parse*,ExprList*,i16*,Column**);
  18728. SQLITE_PRIVATE void sqlite3SelectAddColumnTypeAndCollation(Parse*,Table*,Select*,char);
  18729. SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*,char);
  18730. SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int);
  18731. SQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table*);
  18732. SQLITE_PRIVATE i16 sqlite3TableColumnToIndex(Index*, i16);
  18733. #ifdef SQLITE_OMIT_GENERATED_COLUMNS
  18734. # define sqlite3TableColumnToStorage(T,X) (X) /* No-op pass-through */
  18735. # define sqlite3StorageColumnToTable(T,X) (X) /* No-op pass-through */
  18736. #else
  18737. SQLITE_PRIVATE i16 sqlite3TableColumnToStorage(Table*, i16);
  18738. SQLITE_PRIVATE i16 sqlite3StorageColumnToTable(Table*, i16);
  18739. #endif
  18740. SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
  18741. #if SQLITE_ENABLE_HIDDEN_COLUMNS
  18742. SQLITE_PRIVATE void sqlite3ColumnPropertiesFromName(Table*, Column*);
  18743. #else
  18744. # define sqlite3ColumnPropertiesFromName(T,C) /* no-op */
  18745. #endif
  18746. SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*,Token*);
  18747. SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
  18748. SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
  18749. SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*);
  18750. SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,Expr*,const char*,const char*);
  18751. SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);
  18752. SQLITE_PRIVATE void sqlite3AddGenerated(Parse*,Expr*,Token*);
  18753. SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,u8,Select*);
  18754. SQLITE_PRIVATE int sqlite3ParseUri(const char*,const char*,unsigned int*,
  18755. sqlite3_vfs**,char**,char **);
  18756. #define sqlite3CodecQueryParameters(A,B,C) 0
  18757. SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3*,const char*);
  18758. #ifdef SQLITE_UNTESTABLE
  18759. # define sqlite3FaultSim(X) SQLITE_OK
  18760. #else
  18761. SQLITE_PRIVATE int sqlite3FaultSim(int);
  18762. #endif
  18763. SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32);
  18764. SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32);
  18765. SQLITE_PRIVATE int sqlite3BitvecTestNotNull(Bitvec*, u32);
  18766. SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32);
  18767. SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32, void*);
  18768. SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*);
  18769. SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec*);
  18770. #ifndef SQLITE_UNTESTABLE
  18771. SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);
  18772. #endif
  18773. SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*);
  18774. SQLITE_PRIVATE void sqlite3RowSetDelete(void*);
  18775. SQLITE_PRIVATE void sqlite3RowSetClear(void*);
  18776. SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64);
  18777. SQLITE_PRIVATE int sqlite3RowSetTest(RowSet*, int iBatch, i64);
  18778. SQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*);
  18779. SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,ExprList*,Select*,int,int);
  18780. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
  18781. SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse*,Table*);
  18782. #else
  18783. # define sqlite3ViewGetColumnNames(A,B) 0
  18784. #endif
  18785. #if SQLITE_MAX_ATTACHED>30
  18786. SQLITE_PRIVATE int sqlite3DbMaskAllZero(yDbMask);
  18787. #endif
  18788. SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
  18789. SQLITE_PRIVATE void sqlite3CodeDropTable(Parse*, Table*, int, int);
  18790. SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3*, Table*);
  18791. SQLITE_PRIVATE void sqlite3FreeIndex(sqlite3*, Index*);
  18792. #ifndef SQLITE_OMIT_AUTOINCREMENT
  18793. SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse);
  18794. SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse);
  18795. #else
  18796. # define sqlite3AutoincrementBegin(X)
  18797. # define sqlite3AutoincrementEnd(X)
  18798. #endif
  18799. SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, Select*, IdList*, int, Upsert*);
  18800. #ifndef SQLITE_OMIT_GENERATED_COLUMNS
  18801. SQLITE_PRIVATE void sqlite3ComputeGeneratedColumns(Parse*, int, Table*);
  18802. #endif
  18803. SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int*,int*);
  18804. SQLITE_PRIVATE IdList *sqlite3IdListAppend(Parse*, IdList*, Token*);
  18805. SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);
  18806. SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(Parse*, SrcList*, int, int);
  18807. SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(Parse*, SrcList*, Token*, Token*);
  18808. SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
  18809. Token*, Select*, Expr*, IdList*);
  18810. SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
  18811. SQLITE_PRIVATE void sqlite3SrcListFuncArgs(Parse*, SrcList*, ExprList*);
  18812. SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);
  18813. SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*);
  18814. SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
  18815. SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);
  18816. SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);
  18817. SQLITE_PRIVATE Index *sqlite3AllocateIndexObject(sqlite3*,i16,int,char**);
  18818. SQLITE_PRIVATE void sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
  18819. Expr*, int, int, u8);
  18820. SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
  18821. SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);
  18822. SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
  18823. Expr*,ExprList*,u32,Expr*);
  18824. SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);
  18825. SQLITE_PRIVATE void sqlite3SelectReset(Parse*, Select*);
  18826. SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
  18827. SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int);
  18828. SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
  18829. #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
  18830. SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse*,SrcList*,Expr*,ExprList*,Expr*,char*);
  18831. #endif
  18832. SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*, ExprList*, Expr*);
  18833. SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*,Expr*,int,ExprList*,Expr*,
  18834. Upsert*);
  18835. SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*,SrcList*,Expr*,ExprList*,ExprList*,u16,int);
  18836. SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
  18837. SQLITE_PRIVATE LogEst sqlite3WhereOutputRowCount(WhereInfo*);
  18838. SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo*);
  18839. SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo*);
  18840. SQLITE_PRIVATE int sqlite3WhereOrderByLimitOptLabel(WhereInfo*);
  18841. SQLITE_PRIVATE int sqlite3WhereIsSorted(WhereInfo*);
  18842. SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo*);
  18843. SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo*);
  18844. SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo*, int*);
  18845. #define ONEPASS_OFF 0 /* Use of ONEPASS not allowed */
  18846. #define ONEPASS_SINGLE 1 /* ONEPASS valid for a single row update */
  18847. #define ONEPASS_MULTI 2 /* ONEPASS is valid for multiple rows */
  18848. SQLITE_PRIVATE int sqlite3WhereUsesDeferredSeek(WhereInfo*);
  18849. SQLITE_PRIVATE void sqlite3ExprCodeLoadIndexColumn(Parse*, Index*, int, int, int);
  18850. SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int, u8);
  18851. SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int);
  18852. SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
  18853. SQLITE_PRIVATE void sqlite3ExprCode(Parse*, Expr*, int);
  18854. #ifndef SQLITE_OMIT_GENERATED_COLUMNS
  18855. SQLITE_PRIVATE void sqlite3ExprCodeGeneratedColumn(Parse*, Column*, int);
  18856. #endif
  18857. SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse*, Expr*, int);
  18858. SQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse*, Expr*, int);
  18859. SQLITE_PRIVATE int sqlite3ExprCodeRunJustOnce(Parse*, Expr*, int);
  18860. SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
  18861. SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
  18862. SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int, u8);
  18863. #define SQLITE_ECEL_DUP 0x01 /* Deep, not shallow copies */
  18864. #define SQLITE_ECEL_FACTOR 0x02 /* Factor out constant terms */
  18865. #define SQLITE_ECEL_REF 0x04 /* Use ExprList.u.x.iOrderByCol */
  18866. #define SQLITE_ECEL_OMITREF 0x08 /* Omit if ExprList.u.x.iOrderByCol */
  18867. SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
  18868. SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
  18869. SQLITE_PRIVATE void sqlite3ExprIfFalseDup(Parse*, Expr*, int, int);
  18870. SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);
  18871. #define LOCATE_VIEW 0x01
  18872. #define LOCATE_NOERR 0x02
  18873. SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,u32 flags,const char*, const char*);
  18874. SQLITE_PRIVATE Table *sqlite3LocateTableItem(Parse*,u32 flags,struct SrcList_item *);
  18875. SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
  18876. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
  18877. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
  18878. SQLITE_PRIVATE void sqlite3Vacuum(Parse*,Token*,Expr*);
  18879. SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*, int, sqlite3_value*);
  18880. SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*);
  18881. SQLITE_PRIVATE int sqlite3ExprCompare(Parse*,Expr*, Expr*, int);
  18882. SQLITE_PRIVATE int sqlite3ExprCompareSkip(Expr*, Expr*, int);
  18883. SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList*, ExprList*, int);
  18884. SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Parse*,Expr*, Expr*, int);
  18885. SQLITE_PRIVATE int sqlite3ExprImpliesNonNullRow(Expr*,int);
  18886. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
  18887. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
  18888. SQLITE_PRIVATE int sqlite3ExprCoveredByIndex(Expr*, int iCur, Index *pIdx);
  18889. SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr*, SrcList*);
  18890. SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);
  18891. #ifndef SQLITE_UNTESTABLE
  18892. SQLITE_PRIVATE void sqlite3PrngSaveState(void);
  18893. SQLITE_PRIVATE void sqlite3PrngRestoreState(void);
  18894. #endif
  18895. SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*,int);
  18896. SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int);
  18897. SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse*, const char *zDb);
  18898. SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int);
  18899. SQLITE_PRIVATE void sqlite3EndTransaction(Parse*,int);
  18900. SQLITE_PRIVATE void sqlite3Savepoint(Parse*, int, Token*);
  18901. SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *);
  18902. SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3*);
  18903. SQLITE_PRIVATE u32 sqlite3IsTrueOrFalse(const char*);
  18904. SQLITE_PRIVATE int sqlite3ExprIdToTrueFalse(Expr*);
  18905. SQLITE_PRIVATE int sqlite3ExprTruthValue(const Expr*);
  18906. SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);
  18907. SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);
  18908. SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*, u8);
  18909. SQLITE_PRIVATE int sqlite3ExprIsConstantOrGroupBy(Parse*, Expr*, ExprList*);
  18910. SQLITE_PRIVATE int sqlite3ExprIsTableConstant(Expr*,int);
  18911. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  18912. SQLITE_PRIVATE int sqlite3ExprContainsSubquery(Expr*);
  18913. #endif
  18914. SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*);
  18915. SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*);
  18916. SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
  18917. SQLITE_PRIVATE int sqlite3IsRowid(const char*);
  18918. SQLITE_PRIVATE void sqlite3GenerateRowDelete(
  18919. Parse*,Table*,Trigger*,int,int,int,i16,u8,u8,u8,int);
  18920. SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int, int*, int);
  18921. SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int, int*,Index*,int);
  18922. SQLITE_PRIVATE void sqlite3ResolvePartIdxLabel(Parse*,int);
  18923. SQLITE_PRIVATE int sqlite3ExprReferencesUpdatedColumn(Expr*,int*,int);
  18924. SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int*,int,int,int,int,
  18925. u8,u8,int,int*,int*,Upsert*);
  18926. #ifdef SQLITE_ENABLE_NULL_TRIM
  18927. SQLITE_PRIVATE void sqlite3SetMakeRecordP5(Vdbe*,Table*);
  18928. #else
  18929. # define sqlite3SetMakeRecordP5(A,B)
  18930. #endif
  18931. SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*,Table*,int,int,int,int*,int,int,int);
  18932. SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, u8, int, u8*, int*, int*);
  18933. SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);
  18934. SQLITE_PRIVATE void sqlite3MultiWrite(Parse*);
  18935. SQLITE_PRIVATE void sqlite3MayAbort(Parse*);
  18936. SQLITE_PRIVATE void sqlite3HaltConstraint(Parse*, int, int, char*, i8, u8);
  18937. SQLITE_PRIVATE void sqlite3UniqueConstraint(Parse*, int, Index*);
  18938. SQLITE_PRIVATE void sqlite3RowidConstraint(Parse*, int, Table*);
  18939. SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*,int);
  18940. SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int);
  18941. SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int);
  18942. SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*);
  18943. SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*,int);
  18944. SQLITE_PRIVATE FuncDef *sqlite3FunctionSearch(int,const char*);
  18945. SQLITE_PRIVATE void sqlite3InsertBuiltinFuncs(FuncDef*,int);
  18946. SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,u8,u8);
  18947. SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void);
  18948. SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void);
  18949. SQLITE_PRIVATE void sqlite3RegisterPerConnectionBuiltinFunctions(sqlite3*);
  18950. SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);
  18951. SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);
  18952. SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);
  18953. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  18954. SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, ExprList*,Expr*,int);
  18955. #endif
  18956. #ifndef SQLITE_OMIT_TRIGGER
  18957. SQLITE_PRIVATE void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
  18958. Expr*,int, int);
  18959. SQLITE_PRIVATE void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
  18960. SQLITE_PRIVATE void sqlite3DropTrigger(Parse*, SrcList*, int);
  18961. SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse*, Trigger*);
  18962. SQLITE_PRIVATE Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);
  18963. SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *, Table *);
  18964. SQLITE_PRIVATE void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,
  18965. int, int, int);
  18966. SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int);
  18967. void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
  18968. SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
  18969. SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*,
  18970. const char*,const char*);
  18971. SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(Parse*,Token*, IdList*,
  18972. Select*,u8,Upsert*,
  18973. const char*,const char*);
  18974. SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(Parse*,Token*,ExprList*, Expr*, u8,
  18975. const char*,const char*);
  18976. SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(Parse*,Token*, Expr*,
  18977. const char*,const char*);
  18978. SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3*, Trigger*);
  18979. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
  18980. SQLITE_PRIVATE u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int);
  18981. # define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
  18982. # define sqlite3IsToplevel(p) ((p)->pToplevel==0)
  18983. #else
  18984. # define sqlite3TriggersExist(B,C,D,E,F) 0
  18985. # define sqlite3DeleteTrigger(A,B)
  18986. # define sqlite3DropTriggerPtr(A,B)
  18987. # define sqlite3UnlinkAndDeleteTrigger(A,B,C)
  18988. # define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I)
  18989. # define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F)
  18990. # define sqlite3TriggerList(X, Y) 0
  18991. # define sqlite3ParseToplevel(p) p
  18992. # define sqlite3IsToplevel(p) 1
  18993. # define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0
  18994. #endif
  18995. SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);
  18996. SQLITE_PRIVATE void sqlite3SetJoinExpr(Expr*,int);
  18997. SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
  18998. SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);
  18999. #ifndef SQLITE_OMIT_AUTHORIZATION
  19000. SQLITE_PRIVATE void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
  19001. SQLITE_PRIVATE int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
  19002. SQLITE_PRIVATE void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
  19003. SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext*);
  19004. SQLITE_PRIVATE int sqlite3AuthReadCol(Parse*, const char *, const char *, int);
  19005. #else
  19006. # define sqlite3AuthRead(a,b,c,d)
  19007. # define sqlite3AuthCheck(a,b,c,d,e) SQLITE_OK
  19008. # define sqlite3AuthContextPush(a,b,c)
  19009. # define sqlite3AuthContextPop(a) ((void)(a))
  19010. #endif
  19011. SQLITE_PRIVATE int sqlite3DbIsNamed(sqlite3 *db, int iDb, const char *zName);
  19012. SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
  19013. SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
  19014. SQLITE_PRIVATE void sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
  19015. SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
  19016. SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
  19017. SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
  19018. SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
  19019. SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
  19020. SQLITE_PRIVATE int sqlite3RealSameAsInt(double,sqlite3_int64);
  19021. SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*, int, u8);
  19022. SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
  19023. SQLITE_PRIVATE int sqlite3Atoi(const char*);
  19024. #ifndef SQLITE_OMIT_UTF16
  19025. SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
  19026. #endif
  19027. SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
  19028. SQLITE_PRIVATE u32 sqlite3Utf8Read(const u8**);
  19029. SQLITE_PRIVATE LogEst sqlite3LogEst(u64);
  19030. SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst,LogEst);
  19031. #ifndef SQLITE_OMIT_VIRTUALTABLE
  19032. SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double);
  19033. #endif
  19034. #if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \
  19035. defined(SQLITE_ENABLE_STAT4) || \
  19036. defined(SQLITE_EXPLAIN_ESTIMATED_ROWS)
  19037. SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst);
  19038. #endif
  19039. SQLITE_PRIVATE VList *sqlite3VListAdd(sqlite3*,VList*,const char*,int,int);
  19040. SQLITE_PRIVATE const char *sqlite3VListNumToName(VList*,int);
  19041. SQLITE_PRIVATE int sqlite3VListNameToNum(VList*,const char*,int);
  19042. /*
  19043. ** Routines to read and write variable-length integers. These used to
  19044. ** be defined locally, but now we use the varint routines in the util.c
  19045. ** file.
  19046. */
  19047. SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64);
  19048. SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *);
  19049. SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *);
  19050. SQLITE_PRIVATE int sqlite3VarintLen(u64 v);
  19051. /*
  19052. ** The common case is for a varint to be a single byte. They following
  19053. ** macros handle the common case without a procedure call, but then call
  19054. ** the procedure for larger varints.
  19055. */
  19056. #define getVarint32(A,B) \
  19057. (u8)((*(A)<(u8)0x80)?((B)=(u32)*(A)),1:sqlite3GetVarint32((A),(u32 *)&(B)))
  19058. #define getVarint32NR(A,B) \
  19059. B=(u32)*(A);if(B>=0x80)sqlite3GetVarint32((A),(u32*)&(B))
  19060. #define putVarint32(A,B) \
  19061. (u8)(((u32)(B)<(u32)0x80)?(*(A)=(unsigned char)(B)),1:\
  19062. sqlite3PutVarint((A),(B)))
  19063. #define getVarint sqlite3GetVarint
  19064. #define putVarint sqlite3PutVarint
  19065. SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(sqlite3*, Index*);
  19066. SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe*, Table*, int);
  19067. SQLITE_PRIVATE char sqlite3CompareAffinity(const Expr *pExpr, char aff2);
  19068. SQLITE_PRIVATE int sqlite3IndexAffinityOk(const Expr *pExpr, char idx_affinity);
  19069. SQLITE_PRIVATE char sqlite3TableColumnAffinity(Table*,int);
  19070. SQLITE_PRIVATE char sqlite3ExprAffinity(const Expr *pExpr);
  19071. SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*, int, u8);
  19072. SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char*, i64*);
  19073. SQLITE_PRIVATE void sqlite3ErrorWithMsg(sqlite3*, int, const char*,...);
  19074. SQLITE_PRIVATE void sqlite3Error(sqlite3*,int);
  19075. SQLITE_PRIVATE void sqlite3SystemError(sqlite3*,int);
  19076. SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
  19077. SQLITE_PRIVATE u8 sqlite3HexToInt(int h);
  19078. SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
  19079. #if defined(SQLITE_NEED_ERR_NAME)
  19080. SQLITE_PRIVATE const char *sqlite3ErrName(int);
  19081. #endif
  19082. #ifdef SQLITE_ENABLE_DESERIALIZE
  19083. SQLITE_PRIVATE int sqlite3MemdbInit(void);
  19084. #endif
  19085. SQLITE_PRIVATE const char *sqlite3ErrStr(int);
  19086. SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);
  19087. SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);
  19088. SQLITE_PRIVATE int sqlite3IsBinary(const CollSeq*);
  19089. SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);
  19090. SQLITE_PRIVATE void sqlite3SetTextEncoding(sqlite3 *db, u8);
  19091. SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, const Expr *pExpr);
  19092. SQLITE_PRIVATE CollSeq *sqlite3ExprNNCollSeq(Parse *pParse, const Expr *pExpr);
  19093. SQLITE_PRIVATE int sqlite3ExprCollSeqMatch(Parse*,const Expr*,const Expr*);
  19094. SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(Parse *pParse, Expr*, const Token*, int);
  19095. SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse*,Expr*,const char*);
  19096. SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr*);
  19097. SQLITE_PRIVATE Expr *sqlite3ExprSkipCollateAndLikely(Expr*);
  19098. SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
  19099. SQLITE_PRIVATE int sqlite3WritableSchema(sqlite3*);
  19100. SQLITE_PRIVATE int sqlite3CheckObjectName(Parse*, const char*,const char*,const char*);
  19101. SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);
  19102. SQLITE_PRIVATE int sqlite3AddInt64(i64*,i64);
  19103. SQLITE_PRIVATE int sqlite3SubInt64(i64*,i64);
  19104. SQLITE_PRIVATE int sqlite3MulInt64(i64*,i64);
  19105. SQLITE_PRIVATE int sqlite3AbsInt32(int);
  19106. #ifdef SQLITE_ENABLE_8_3_NAMES
  19107. SQLITE_PRIVATE void sqlite3FileSuffix3(const char*, char*);
  19108. #else
  19109. # define sqlite3FileSuffix3(X,Y)
  19110. #endif
  19111. SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z,u8);
  19112. SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);
  19113. SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);
  19114. SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8,
  19115. void(*)(void*));
  19116. SQLITE_PRIVATE void sqlite3ValueSetNull(sqlite3_value*);
  19117. SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);
  19118. #ifndef SQLITE_UNTESTABLE
  19119. SQLITE_PRIVATE void sqlite3ResultIntReal(sqlite3_context*);
  19120. #endif
  19121. SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);
  19122. #ifndef SQLITE_OMIT_UTF16
  19123. SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8);
  19124. #endif
  19125. SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
  19126. SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
  19127. #ifndef SQLITE_AMALGAMATION
  19128. SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[];
  19129. SQLITE_PRIVATE const char sqlite3StrBINARY[];
  19130. SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
  19131. SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];
  19132. SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
  19133. SQLITE_PRIVATE FuncDefHash sqlite3BuiltinFunctions;
  19134. #ifndef SQLITE_OMIT_WSD
  19135. SQLITE_PRIVATE int sqlite3PendingByte;
  19136. #endif
  19137. #endif
  19138. #ifdef VDBE_PROFILE
  19139. SQLITE_PRIVATE sqlite3_uint64 sqlite3NProfileCnt;
  19140. #endif
  19141. SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3*, int, int, int);
  19142. SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
  19143. SQLITE_PRIVATE void sqlite3AlterFunctions(void);
  19144. SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
  19145. SQLITE_PRIVATE void sqlite3AlterRenameColumn(Parse*, SrcList*, Token*, Token*);
  19146. SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
  19147. SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
  19148. SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*, int);
  19149. SQLITE_PRIVATE void sqlite3CodeRhsOfIN(Parse*, Expr*, int);
  19150. SQLITE_PRIVATE int sqlite3CodeSubselect(Parse*, Expr*);
  19151. SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);
  19152. SQLITE_PRIVATE void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p);
  19153. SQLITE_PRIVATE int sqlite3MatchEName(
  19154. const struct ExprList_item*,
  19155. const char*,
  19156. const char*,
  19157. const char*
  19158. );
  19159. SQLITE_PRIVATE Bitmask sqlite3ExprColUsed(Expr*);
  19160. SQLITE_PRIVATE u8 sqlite3StrIHash(const char*);
  19161. SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*);
  19162. SQLITE_PRIVATE int sqlite3ResolveExprListNames(NameContext*, ExprList*);
  19163. SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
  19164. SQLITE_PRIVATE int sqlite3ResolveSelfReference(Parse*,Table*,int,Expr*,ExprList*);
  19165. SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
  19166. SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int, int);
  19167. SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);
  19168. SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
  19169. SQLITE_PRIVATE void *sqlite3RenameTokenMap(Parse*, void*, Token*);
  19170. SQLITE_PRIVATE void sqlite3RenameTokenRemap(Parse*, void *pTo, void *pFrom);
  19171. SQLITE_PRIVATE void sqlite3RenameExprUnmap(Parse*, Expr*);
  19172. SQLITE_PRIVATE void sqlite3RenameExprlistUnmap(Parse*, ExprList*);
  19173. SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(Parse*, u8, CollSeq *, const char*);
  19174. SQLITE_PRIVATE char sqlite3AffinityType(const char*, Column*);
  19175. SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);
  19176. SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*);
  19177. SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
  19178. SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *);
  19179. SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
  19180. SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3*,Index*);
  19181. SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);
  19182. SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);
  19183. SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
  19184. SQLITE_PRIVATE void sqlite3SchemaClear(void *);
  19185. SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
  19186. SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
  19187. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3*,int,int);
  19188. SQLITE_PRIVATE void sqlite3KeyInfoUnref(KeyInfo*);
  19189. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoRef(KeyInfo*);
  19190. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoOfIndex(Parse*, Index*);
  19191. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoFromExprList(Parse*, ExprList*, int, int);
  19192. SQLITE_PRIVATE int sqlite3HasExplicitNulls(Parse*, ExprList*);
  19193. #ifdef SQLITE_DEBUG
  19194. SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo*);
  19195. #endif
  19196. SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *,
  19197. void (*)(sqlite3_context*,int,sqlite3_value **),
  19198. void (*)(sqlite3_context*,int,sqlite3_value **),
  19199. void (*)(sqlite3_context*),
  19200. void (*)(sqlite3_context*),
  19201. void (*)(sqlite3_context*,int,sqlite3_value **),
  19202. FuncDestructor *pDestructor
  19203. );
  19204. SQLITE_PRIVATE void sqlite3NoopDestructor(void*);
  19205. SQLITE_PRIVATE void sqlite3OomFault(sqlite3*);
  19206. SQLITE_PRIVATE void sqlite3OomClear(sqlite3*);
  19207. SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
  19208. SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
  19209. SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, sqlite3*, char*, int, int);
  19210. SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
  19211. SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);
  19212. SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);
  19213. SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *);
  19214. SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);
  19215. #ifndef SQLITE_OMIT_SUBQUERY
  19216. SQLITE_PRIVATE int sqlite3ExprCheckIN(Parse*, Expr*);
  19217. #else
  19218. # define sqlite3ExprCheckIN(x,y) SQLITE_OK
  19219. #endif
  19220. #ifdef SQLITE_ENABLE_STAT4
  19221. SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(
  19222. Parse*,Index*,UnpackedRecord**,Expr*,int,int,int*);
  19223. SQLITE_PRIVATE int sqlite3Stat4ValueFromExpr(Parse*, Expr*, u8, sqlite3_value**);
  19224. SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord*);
  19225. SQLITE_PRIVATE int sqlite3Stat4Column(sqlite3*, const void*, int, int, sqlite3_value**);
  19226. SQLITE_PRIVATE char sqlite3IndexColumnAffinity(sqlite3*, Index*, int);
  19227. #endif
  19228. /*
  19229. ** The interface to the LEMON-generated parser
  19230. */
  19231. #ifndef SQLITE_AMALGAMATION
  19232. SQLITE_PRIVATE void *sqlite3ParserAlloc(void*(*)(u64), Parse*);
  19233. SQLITE_PRIVATE void sqlite3ParserFree(void*, void(*)(void*));
  19234. #endif
  19235. SQLITE_PRIVATE void sqlite3Parser(void*, int, Token);
  19236. SQLITE_PRIVATE int sqlite3ParserFallback(int);
  19237. #ifdef YYTRACKMAXSTACKDEPTH
  19238. SQLITE_PRIVATE int sqlite3ParserStackPeak(void*);
  19239. #endif
  19240. SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3*);
  19241. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  19242. SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3*);
  19243. #else
  19244. # define sqlite3CloseExtensions(X)
  19245. #endif
  19246. #ifndef SQLITE_OMIT_SHARED_CACHE
  19247. SQLITE_PRIVATE void sqlite3TableLock(Parse *, int, int, u8, const char *);
  19248. #else
  19249. #define sqlite3TableLock(v,w,x,y,z)
  19250. #endif
  19251. #ifdef SQLITE_TEST
  19252. SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char*);
  19253. #endif
  19254. #ifdef SQLITE_OMIT_VIRTUALTABLE
  19255. # define sqlite3VtabClear(Y)
  19256. # define sqlite3VtabSync(X,Y) SQLITE_OK
  19257. # define sqlite3VtabRollback(X)
  19258. # define sqlite3VtabCommit(X)
  19259. # define sqlite3VtabInSync(db) 0
  19260. # define sqlite3VtabLock(X)
  19261. # define sqlite3VtabUnlock(X)
  19262. # define sqlite3VtabModuleUnref(D,X)
  19263. # define sqlite3VtabUnlockList(X)
  19264. # define sqlite3VtabSavepoint(X, Y, Z) SQLITE_OK
  19265. # define sqlite3GetVTable(X,Y) ((VTable*)0)
  19266. #else
  19267. SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table*);
  19268. SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p);
  19269. SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, Vdbe*);
  19270. SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db);
  19271. SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db);
  19272. SQLITE_PRIVATE void sqlite3VtabLock(VTable *);
  19273. SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *);
  19274. SQLITE_PRIVATE void sqlite3VtabModuleUnref(sqlite3*,Module*);
  19275. SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3*);
  19276. SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *, int, int);
  19277. SQLITE_PRIVATE void sqlite3VtabImportErrmsg(Vdbe*, sqlite3_vtab*);
  19278. SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3*, Table*);
  19279. SQLITE_PRIVATE Module *sqlite3VtabCreateModule(
  19280. sqlite3*,
  19281. const char*,
  19282. const sqlite3_module*,
  19283. void*,
  19284. void(*)(void*)
  19285. );
  19286. # define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
  19287. #endif
  19288. SQLITE_PRIVATE int sqlite3ReadOnlyShadowTables(sqlite3 *db);
  19289. #ifndef SQLITE_OMIT_VIRTUALTABLE
  19290. SQLITE_PRIVATE int sqlite3ShadowTableName(sqlite3 *db, const char *zName);
  19291. SQLITE_PRIVATE int sqlite3IsShadowTableOf(sqlite3*,Table*,const char*);
  19292. #else
  19293. # define sqlite3ShadowTableName(A,B) 0
  19294. # define sqlite3IsShadowTableOf(A,B,C) 0
  19295. #endif
  19296. SQLITE_PRIVATE int sqlite3VtabEponymousTableInit(Parse*,Module*);
  19297. SQLITE_PRIVATE void sqlite3VtabEponymousTableClear(sqlite3*,Module*);
  19298. SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*);
  19299. SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*, int);
  19300. SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*);
  19301. SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);
  19302. SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
  19303. SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
  19304. SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
  19305. SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
  19306. SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *);
  19307. SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
  19308. SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context*);
  19309. SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
  19310. SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
  19311. SQLITE_PRIVATE void sqlite3ParserReset(Parse*);
  19312. #ifdef SQLITE_ENABLE_NORMALIZE
  19313. SQLITE_PRIVATE char *sqlite3Normalize(Vdbe*, const char*);
  19314. #endif
  19315. SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
  19316. SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
  19317. SQLITE_PRIVATE CollSeq *sqlite3ExprCompareCollSeq(Parse*,const Expr*);
  19318. SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, const Expr*, const Expr*);
  19319. SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*);
  19320. SQLITE_PRIVATE const char *sqlite3JournalModename(int);
  19321. #ifndef SQLITE_OMIT_WAL
  19322. SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3*, int, int, int*, int*);
  19323. SQLITE_PRIVATE int sqlite3WalDefaultHook(void*,sqlite3*,const char*,int);
  19324. #endif
  19325. #ifndef SQLITE_OMIT_CTE
  19326. SQLITE_PRIVATE With *sqlite3WithAdd(Parse*,With*,Token*,ExprList*,Select*);
  19327. SQLITE_PRIVATE void sqlite3WithDelete(sqlite3*,With*);
  19328. SQLITE_PRIVATE void sqlite3WithPush(Parse*, With*, u8);
  19329. #else
  19330. #define sqlite3WithPush(x,y,z)
  19331. #define sqlite3WithDelete(x,y)
  19332. #endif
  19333. #ifndef SQLITE_OMIT_UPSERT
  19334. SQLITE_PRIVATE Upsert *sqlite3UpsertNew(sqlite3*,ExprList*,Expr*,ExprList*,Expr*);
  19335. SQLITE_PRIVATE void sqlite3UpsertDelete(sqlite3*,Upsert*);
  19336. SQLITE_PRIVATE Upsert *sqlite3UpsertDup(sqlite3*,Upsert*);
  19337. SQLITE_PRIVATE int sqlite3UpsertAnalyzeTarget(Parse*,SrcList*,Upsert*);
  19338. SQLITE_PRIVATE void sqlite3UpsertDoUpdate(Parse*,Upsert*,Table*,Index*,int);
  19339. #else
  19340. #define sqlite3UpsertNew(v,w,x,y,z) ((Upsert*)0)
  19341. #define sqlite3UpsertDelete(x,y)
  19342. #define sqlite3UpsertDup(x,y) ((Upsert*)0)
  19343. #endif
  19344. /* Declarations for functions in fkey.c. All of these are replaced by
  19345. ** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
  19346. ** key functionality is available. If OMIT_TRIGGER is defined but
  19347. ** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
  19348. ** this case foreign keys are parsed, but no other functionality is
  19349. ** provided (enforcement of FK constraints requires the triggers sub-system).
  19350. */
  19351. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  19352. SQLITE_PRIVATE void sqlite3FkCheck(Parse*, Table*, int, int, int*, int);
  19353. SQLITE_PRIVATE void sqlite3FkDropTable(Parse*, SrcList *, Table*);
  19354. SQLITE_PRIVATE void sqlite3FkActions(Parse*, Table*, ExprList*, int, int*, int);
  19355. SQLITE_PRIVATE int sqlite3FkRequired(Parse*, Table*, int*, int);
  19356. SQLITE_PRIVATE u32 sqlite3FkOldmask(Parse*, Table*);
  19357. SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *);
  19358. #else
  19359. #define sqlite3FkActions(a,b,c,d,e,f)
  19360. #define sqlite3FkCheck(a,b,c,d,e,f)
  19361. #define sqlite3FkDropTable(a,b,c)
  19362. #define sqlite3FkOldmask(a,b) 0
  19363. #define sqlite3FkRequired(a,b,c,d) 0
  19364. #define sqlite3FkReferences(a) 0
  19365. #endif
  19366. #ifndef SQLITE_OMIT_FOREIGN_KEY
  19367. SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *, Table*);
  19368. SQLITE_PRIVATE int sqlite3FkLocateIndex(Parse*,Table*,FKey*,Index**,int**);
  19369. #else
  19370. #define sqlite3FkDelete(a,b)
  19371. #define sqlite3FkLocateIndex(a,b,c,d,e)
  19372. #endif
  19373. /*
  19374. ** Available fault injectors. Should be numbered beginning with 0.
  19375. */
  19376. #define SQLITE_FAULTINJECTOR_MALLOC 0
  19377. #define SQLITE_FAULTINJECTOR_COUNT 1
  19378. /*
  19379. ** The interface to the code in fault.c used for identifying "benign"
  19380. ** malloc failures. This is only present if SQLITE_UNTESTABLE
  19381. ** is not defined.
  19382. */
  19383. #ifndef SQLITE_UNTESTABLE
  19384. SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void);
  19385. SQLITE_PRIVATE void sqlite3EndBenignMalloc(void);
  19386. #else
  19387. #define sqlite3BeginBenignMalloc()
  19388. #define sqlite3EndBenignMalloc()
  19389. #endif
  19390. /*
  19391. ** Allowed return values from sqlite3FindInIndex()
  19392. */
  19393. #define IN_INDEX_ROWID 1 /* Search the rowid of the table */
  19394. #define IN_INDEX_EPH 2 /* Search an ephemeral b-tree */
  19395. #define IN_INDEX_INDEX_ASC 3 /* Existing index ASCENDING */
  19396. #define IN_INDEX_INDEX_DESC 4 /* Existing index DESCENDING */
  19397. #define IN_INDEX_NOOP 5 /* No table available. Use comparisons */
  19398. /*
  19399. ** Allowed flags for the 3rd parameter to sqlite3FindInIndex().
  19400. */
  19401. #define IN_INDEX_NOOP_OK 0x0001 /* OK to return IN_INDEX_NOOP */
  19402. #define IN_INDEX_MEMBERSHIP 0x0002 /* IN operator used for membership test */
  19403. #define IN_INDEX_LOOP 0x0004 /* IN operator used as a loop */
  19404. SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, u32, int*, int*, int*);
  19405. SQLITE_PRIVATE int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
  19406. SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *);
  19407. #if defined(SQLITE_ENABLE_ATOMIC_WRITE) \
  19408. || defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
  19409. SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *);
  19410. #endif
  19411. SQLITE_PRIVATE int sqlite3JournalIsInMemory(sqlite3_file *p);
  19412. SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *);
  19413. SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p);
  19414. #if SQLITE_MAX_EXPR_DEPTH>0
  19415. SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *);
  19416. SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse*, int);
  19417. #else
  19418. #define sqlite3SelectExprHeight(x) 0
  19419. #define sqlite3ExprCheckHeight(x,y)
  19420. #endif
  19421. SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);
  19422. SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);
  19423. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  19424. SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *);
  19425. SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db);
  19426. SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db);
  19427. #else
  19428. #define sqlite3ConnectionBlocked(x,y)
  19429. #define sqlite3ConnectionUnlocked(x)
  19430. #define sqlite3ConnectionClosed(x)
  19431. #endif
  19432. #ifdef SQLITE_DEBUG
  19433. SQLITE_PRIVATE void sqlite3ParserTrace(FILE*, char *);
  19434. #endif
  19435. #if defined(YYCOVERAGE)
  19436. SQLITE_PRIVATE int sqlite3ParserCoverage(FILE*);
  19437. #endif
  19438. /*
  19439. ** If the SQLITE_ENABLE IOTRACE exists then the global variable
  19440. ** sqlite3IoTrace is a pointer to a printf-like routine used to
  19441. ** print I/O tracing messages.
  19442. */
  19443. #ifdef SQLITE_ENABLE_IOTRACE
  19444. # define IOTRACE(A) if( sqlite3IoTrace ){ sqlite3IoTrace A; }
  19445. SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe*);
  19446. SQLITE_API SQLITE_EXTERN void (SQLITE_CDECL *sqlite3IoTrace)(const char*,...);
  19447. #else
  19448. # define IOTRACE(A)
  19449. # define sqlite3VdbeIOTraceSql(X)
  19450. #endif
  19451. /*
  19452. ** These routines are available for the mem2.c debugging memory allocator
  19453. ** only. They are used to verify that different "types" of memory
  19454. ** allocations are properly tracked by the system.
  19455. **
  19456. ** sqlite3MemdebugSetType() sets the "type" of an allocation to one of
  19457. ** the MEMTYPE_* macros defined below. The type must be a bitmask with
  19458. ** a single bit set.
  19459. **
  19460. ** sqlite3MemdebugHasType() returns true if any of the bits in its second
  19461. ** argument match the type set by the previous sqlite3MemdebugSetType().
  19462. ** sqlite3MemdebugHasType() is intended for use inside assert() statements.
  19463. **
  19464. ** sqlite3MemdebugNoType() returns true if none of the bits in its second
  19465. ** argument match the type set by the previous sqlite3MemdebugSetType().
  19466. **
  19467. ** Perhaps the most important point is the difference between MEMTYPE_HEAP
  19468. ** and MEMTYPE_LOOKASIDE. If an allocation is MEMTYPE_LOOKASIDE, that means
  19469. ** it might have been allocated by lookaside, except the allocation was
  19470. ** too large or lookaside was already full. It is important to verify
  19471. ** that allocations that might have been satisfied by lookaside are not
  19472. ** passed back to non-lookaside free() routines. Asserts such as the
  19473. ** example above are placed on the non-lookaside free() routines to verify
  19474. ** this constraint.
  19475. **
  19476. ** All of this is no-op for a production build. It only comes into
  19477. ** play when the SQLITE_MEMDEBUG compile-time option is used.
  19478. */
  19479. #ifdef SQLITE_MEMDEBUG
  19480. SQLITE_PRIVATE void sqlite3MemdebugSetType(void*,u8);
  19481. SQLITE_PRIVATE int sqlite3MemdebugHasType(void*,u8);
  19482. SQLITE_PRIVATE int sqlite3MemdebugNoType(void*,u8);
  19483. #else
  19484. # define sqlite3MemdebugSetType(X,Y) /* no-op */
  19485. # define sqlite3MemdebugHasType(X,Y) 1
  19486. # define sqlite3MemdebugNoType(X,Y) 1
  19487. #endif
  19488. #define MEMTYPE_HEAP 0x01 /* General heap allocations */
  19489. #define MEMTYPE_LOOKASIDE 0x02 /* Heap that might have been lookaside */
  19490. #define MEMTYPE_PCACHE 0x04 /* Page cache allocations */
  19491. /*
  19492. ** Threading interface
  19493. */
  19494. #if SQLITE_MAX_WORKER_THREADS>0
  19495. SQLITE_PRIVATE int sqlite3ThreadCreate(SQLiteThread**,void*(*)(void*),void*);
  19496. SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread*, void**);
  19497. #endif
  19498. #if defined(SQLITE_ENABLE_DBPAGE_VTAB) || defined(SQLITE_TEST)
  19499. SQLITE_PRIVATE int sqlite3DbpageRegister(sqlite3*);
  19500. #endif
  19501. #if defined(SQLITE_ENABLE_DBSTAT_VTAB) || defined(SQLITE_TEST)
  19502. SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3*);
  19503. #endif
  19504. SQLITE_PRIVATE int sqlite3ExprVectorSize(Expr *pExpr);
  19505. SQLITE_PRIVATE int sqlite3ExprIsVector(Expr *pExpr);
  19506. SQLITE_PRIVATE Expr *sqlite3VectorFieldSubexpr(Expr*, int);
  19507. SQLITE_PRIVATE Expr *sqlite3ExprForVectorField(Parse*,Expr*,int);
  19508. SQLITE_PRIVATE void sqlite3VectorErrorMsg(Parse*, Expr*);
  19509. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  19510. SQLITE_PRIVATE const char **sqlite3CompileOptions(int *pnOpt);
  19511. #endif
  19512. #endif /* SQLITEINT_H */
  19513. /************** End of sqliteInt.h *******************************************/
  19514. /************** Begin file global.c ******************************************/
  19515. /*
  19516. ** 2008 June 13
  19517. **
  19518. ** The author disclaims copyright to this source code. In place of
  19519. ** a legal notice, here is a blessing:
  19520. **
  19521. ** May you do good and not evil.
  19522. ** May you find forgiveness for yourself and forgive others.
  19523. ** May you share freely, never taking more than you give.
  19524. **
  19525. *************************************************************************
  19526. **
  19527. ** This file contains definitions of global variables and constants.
  19528. */
  19529. /* #include "sqliteInt.h" */
  19530. /* An array to map all upper-case characters into their corresponding
  19531. ** lower-case character.
  19532. **
  19533. ** SQLite only considers US-ASCII (or EBCDIC) characters. We do not
  19534. ** handle case conversions for the UTF character set since the tables
  19535. ** involved are nearly as big or bigger than SQLite itself.
  19536. */
  19537. SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
  19538. #ifdef SQLITE_ASCII
  19539. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
  19540. 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
  19541. 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
  19542. 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
  19543. 104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
  19544. 122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
  19545. 108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
  19546. 126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
  19547. 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
  19548. 162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
  19549. 180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
  19550. 198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
  19551. 216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
  19552. 234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
  19553. 252,253,254,255
  19554. #endif
  19555. #ifdef SQLITE_EBCDIC
  19556. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, /* 0x */
  19557. 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
  19558. 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
  19559. 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
  19560. 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
  19561. 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
  19562. 96, 97, 98, 99,100,101,102,103,104,105,106,107,108,109,110,111, /* 6x */
  19563. 112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127, /* 7x */
  19564. 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
  19565. 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159, /* 9x */
  19566. 160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
  19567. 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
  19568. 192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
  19569. 208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
  19570. 224,225,162,163,164,165,166,167,168,169,234,235,236,237,238,239, /* Ex */
  19571. 240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255, /* Fx */
  19572. #endif
  19573. };
  19574. /*
  19575. ** The following 256 byte lookup table is used to support SQLites built-in
  19576. ** equivalents to the following standard library functions:
  19577. **
  19578. ** isspace() 0x01
  19579. ** isalpha() 0x02
  19580. ** isdigit() 0x04
  19581. ** isalnum() 0x06
  19582. ** isxdigit() 0x08
  19583. ** toupper() 0x20
  19584. ** SQLite identifier character 0x40
  19585. ** Quote character 0x80
  19586. **
  19587. ** Bit 0x20 is set if the mapped character requires translation to upper
  19588. ** case. i.e. if the character is a lower-case ASCII character.
  19589. ** If x is a lower-case ASCII character, then its upper-case equivalent
  19590. ** is (x - 0x20). Therefore toupper() can be implemented as:
  19591. **
  19592. ** (x & ~(map[x]&0x20))
  19593. **
  19594. ** The equivalent of tolower() is implemented using the sqlite3UpperToLower[]
  19595. ** array. tolower() is used more often than toupper() by SQLite.
  19596. **
  19597. ** Bit 0x40 is set if the character is non-alphanumeric and can be used in an
  19598. ** SQLite identifier. Identifiers are alphanumerics, "_", "$", and any
  19599. ** non-ASCII UTF character. Hence the test for whether or not a character is
  19600. ** part of an identifier is 0x46.
  19601. */
  19602. SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
  19603. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 00..07 ........ */
  19604. 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, /* 08..0f ........ */
  19605. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 10..17 ........ */
  19606. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 18..1f ........ */
  19607. 0x01, 0x00, 0x80, 0x00, 0x40, 0x00, 0x00, 0x80, /* 20..27 !"#$%&' */
  19608. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 28..2f ()*+,-./ */
  19609. 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, /* 30..37 01234567 */
  19610. 0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 38..3f 89:;<=>? */
  19611. 0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02, /* 40..47 @ABCDEFG */
  19612. 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 48..4f HIJKLMNO */
  19613. 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 50..57 PQRSTUVW */
  19614. 0x02, 0x02, 0x02, 0x80, 0x00, 0x00, 0x00, 0x40, /* 58..5f XYZ[\]^_ */
  19615. 0x80, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22, /* 60..67 `abcdefg */
  19616. 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 68..6f hijklmno */
  19617. 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 70..77 pqrstuvw */
  19618. 0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00, /* 78..7f xyz{|}~. */
  19619. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 80..87 ........ */
  19620. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 88..8f ........ */
  19621. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 90..97 ........ */
  19622. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 98..9f ........ */
  19623. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* a0..a7 ........ */
  19624. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* a8..af ........ */
  19625. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* b0..b7 ........ */
  19626. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* b8..bf ........ */
  19627. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* c0..c7 ........ */
  19628. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* c8..cf ........ */
  19629. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* d0..d7 ........ */
  19630. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* d8..df ........ */
  19631. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* e0..e7 ........ */
  19632. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* e8..ef ........ */
  19633. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* f0..f7 ........ */
  19634. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40 /* f8..ff ........ */
  19635. };
  19636. /* EVIDENCE-OF: R-02982-34736 In order to maintain full backwards
  19637. ** compatibility for legacy applications, the URI filename capability is
  19638. ** disabled by default.
  19639. **
  19640. ** EVIDENCE-OF: R-38799-08373 URI filenames can be enabled or disabled
  19641. ** using the SQLITE_USE_URI=1 or SQLITE_USE_URI=0 compile-time options.
  19642. **
  19643. ** EVIDENCE-OF: R-43642-56306 By default, URI handling is globally
  19644. ** disabled. The default value may be changed by compiling with the
  19645. ** SQLITE_USE_URI symbol defined.
  19646. */
  19647. #ifndef SQLITE_USE_URI
  19648. # define SQLITE_USE_URI 0
  19649. #endif
  19650. /* EVIDENCE-OF: R-38720-18127 The default setting is determined by the
  19651. ** SQLITE_ALLOW_COVERING_INDEX_SCAN compile-time option, or is "on" if
  19652. ** that compile-time option is omitted.
  19653. */
  19654. #if !defined(SQLITE_ALLOW_COVERING_INDEX_SCAN)
  19655. # define SQLITE_ALLOW_COVERING_INDEX_SCAN 1
  19656. #else
  19657. # if !SQLITE_ALLOW_COVERING_INDEX_SCAN
  19658. # error "Compile-time disabling of covering index scan using the\
  19659. -DSQLITE_ALLOW_COVERING_INDEX_SCAN=0 option is deprecated.\
  19660. Contact SQLite developers if this is a problem for you, and\
  19661. delete this #error macro to continue with your build."
  19662. # endif
  19663. #endif
  19664. /* The minimum PMA size is set to this value multiplied by the database
  19665. ** page size in bytes.
  19666. */
  19667. #ifndef SQLITE_SORTER_PMASZ
  19668. # define SQLITE_SORTER_PMASZ 250
  19669. #endif
  19670. /* Statement journals spill to disk when their size exceeds the following
  19671. ** threshold (in bytes). 0 means that statement journals are created and
  19672. ** written to disk immediately (the default behavior for SQLite versions
  19673. ** before 3.12.0). -1 means always keep the entire statement journal in
  19674. ** memory. (The statement journal is also always held entirely in memory
  19675. ** if journal_mode=MEMORY or if temp_store=MEMORY, regardless of this
  19676. ** setting.)
  19677. */
  19678. #ifndef SQLITE_STMTJRNL_SPILL
  19679. # define SQLITE_STMTJRNL_SPILL (64*1024)
  19680. #endif
  19681. /*
  19682. ** The default lookaside-configuration, the format "SZ,N". SZ is the
  19683. ** number of bytes in each lookaside slot (should be a multiple of 8)
  19684. ** and N is the number of slots. The lookaside-configuration can be
  19685. ** changed as start-time using sqlite3_config(SQLITE_CONFIG_LOOKASIDE)
  19686. ** or at run-time for an individual database connection using
  19687. ** sqlite3_db_config(db, SQLITE_DBCONFIG_LOOKASIDE);
  19688. **
  19689. ** With the two-size-lookaside enhancement, less lookaside is required.
  19690. ** The default configuration of 1200,40 actually provides 30 1200-byte slots
  19691. ** and 93 128-byte slots, which is more lookaside than is available
  19692. ** using the older 1200,100 configuration without two-size-lookaside.
  19693. */
  19694. #ifndef SQLITE_DEFAULT_LOOKASIDE
  19695. # ifdef SQLITE_OMIT_TWOSIZE_LOOKASIDE
  19696. # define SQLITE_DEFAULT_LOOKASIDE 1200,100 /* 120KB of memory */
  19697. # else
  19698. # define SQLITE_DEFAULT_LOOKASIDE 1200,40 /* 48KB of memory */
  19699. # endif
  19700. #endif
  19701. /* The default maximum size of an in-memory database created using
  19702. ** sqlite3_deserialize()
  19703. */
  19704. #ifndef SQLITE_MEMDB_DEFAULT_MAXSIZE
  19705. # define SQLITE_MEMDB_DEFAULT_MAXSIZE 1073741824
  19706. #endif
  19707. /*
  19708. ** The following singleton contains the global configuration for
  19709. ** the SQLite library.
  19710. */
  19711. SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = {
  19712. SQLITE_DEFAULT_MEMSTATUS, /* bMemstat */
  19713. 1, /* bCoreMutex */
  19714. SQLITE_THREADSAFE==1, /* bFullMutex */
  19715. SQLITE_USE_URI, /* bOpenUri */
  19716. SQLITE_ALLOW_COVERING_INDEX_SCAN, /* bUseCis */
  19717. 0, /* bSmallMalloc */
  19718. 1, /* bExtraSchemaChecks */
  19719. 0x7ffffffe, /* mxStrlen */
  19720. 0, /* neverCorrupt */
  19721. SQLITE_DEFAULT_LOOKASIDE, /* szLookaside, nLookaside */
  19722. SQLITE_STMTJRNL_SPILL, /* nStmtSpill */
  19723. {0,0,0,0,0,0,0,0}, /* m */
  19724. {0,0,0,0,0,0,0,0,0}, /* mutex */
  19725. {0,0,0,0,0,0,0,0,0,0,0,0,0},/* pcache2 */
  19726. (void*)0, /* pHeap */
  19727. 0, /* nHeap */
  19728. 0, 0, /* mnHeap, mxHeap */
  19729. SQLITE_DEFAULT_MMAP_SIZE, /* szMmap */
  19730. SQLITE_MAX_MMAP_SIZE, /* mxMmap */
  19731. (void*)0, /* pPage */
  19732. 0, /* szPage */
  19733. SQLITE_DEFAULT_PCACHE_INITSZ, /* nPage */
  19734. 0, /* mxParserStack */
  19735. 0, /* sharedCacheEnabled */
  19736. SQLITE_SORTER_PMASZ, /* szPma */
  19737. /* All the rest should always be initialized to zero */
  19738. 0, /* isInit */
  19739. 0, /* inProgress */
  19740. 0, /* isMutexInit */
  19741. 0, /* isMallocInit */
  19742. 0, /* isPCacheInit */
  19743. 0, /* nRefInitMutex */
  19744. 0, /* pInitMutex */
  19745. 0, /* xLog */
  19746. 0, /* pLogArg */
  19747. #ifdef SQLITE_ENABLE_SQLLOG
  19748. 0, /* xSqllog */
  19749. 0, /* pSqllogArg */
  19750. #endif
  19751. #ifdef SQLITE_VDBE_COVERAGE
  19752. 0, /* xVdbeBranch */
  19753. 0, /* pVbeBranchArg */
  19754. #endif
  19755. #ifdef SQLITE_ENABLE_DESERIALIZE
  19756. SQLITE_MEMDB_DEFAULT_MAXSIZE, /* mxMemdbSize */
  19757. #endif
  19758. #ifndef SQLITE_UNTESTABLE
  19759. 0, /* xTestCallback */
  19760. #endif
  19761. 0, /* bLocaltimeFault */
  19762. 0x7ffffffe, /* iOnceResetThreshold */
  19763. SQLITE_DEFAULT_SORTERREF_SIZE, /* szSorterRef */
  19764. 0, /* iPrngSeed */
  19765. };
  19766. /*
  19767. ** Hash table for global functions - functions common to all
  19768. ** database connections. After initialization, this table is
  19769. ** read-only.
  19770. */
  19771. SQLITE_PRIVATE FuncDefHash sqlite3BuiltinFunctions;
  19772. #ifdef VDBE_PROFILE
  19773. /*
  19774. ** The following performance counter can be used in place of
  19775. ** sqlite3Hwtime() for profiling. This is a no-op on standard builds.
  19776. */
  19777. SQLITE_PRIVATE sqlite3_uint64 sqlite3NProfileCnt = 0;
  19778. #endif
  19779. /*
  19780. ** The value of the "pending" byte must be 0x40000000 (1 byte past the
  19781. ** 1-gibabyte boundary) in a compatible database. SQLite never uses
  19782. ** the database page that contains the pending byte. It never attempts
  19783. ** to read or write that page. The pending byte page is set aside
  19784. ** for use by the VFS layers as space for managing file locks.
  19785. **
  19786. ** During testing, it is often desirable to move the pending byte to
  19787. ** a different position in the file. This allows code that has to
  19788. ** deal with the pending byte to run on files that are much smaller
  19789. ** than 1 GiB. The sqlite3_test_control() interface can be used to
  19790. ** move the pending byte.
  19791. **
  19792. ** IMPORTANT: Changing the pending byte to any value other than
  19793. ** 0x40000000 results in an incompatible database file format!
  19794. ** Changing the pending byte during operation will result in undefined
  19795. ** and incorrect behavior.
  19796. */
  19797. #ifndef SQLITE_OMIT_WSD
  19798. SQLITE_PRIVATE int sqlite3PendingByte = 0x40000000;
  19799. #endif
  19800. /* #include "opcodes.h" */
  19801. /*
  19802. ** Properties of opcodes. The OPFLG_INITIALIZER macro is
  19803. ** created by mkopcodeh.awk during compilation. Data is obtained
  19804. ** from the comments following the "case OP_xxxx:" statements in
  19805. ** the vdbe.c file.
  19806. */
  19807. SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER;
  19808. /*
  19809. ** Name of the default collating sequence
  19810. */
  19811. SQLITE_PRIVATE const char sqlite3StrBINARY[] = "BINARY";
  19812. /************** End of global.c **********************************************/
  19813. /************** Begin file status.c ******************************************/
  19814. /*
  19815. ** 2008 June 18
  19816. **
  19817. ** The author disclaims copyright to this source code. In place of
  19818. ** a legal notice, here is a blessing:
  19819. **
  19820. ** May you do good and not evil.
  19821. ** May you find forgiveness for yourself and forgive others.
  19822. ** May you share freely, never taking more than you give.
  19823. **
  19824. *************************************************************************
  19825. **
  19826. ** This module implements the sqlite3_status() interface and related
  19827. ** functionality.
  19828. */
  19829. /* #include "sqliteInt.h" */
  19830. /************** Include vdbeInt.h in the middle of status.c ******************/
  19831. /************** Begin file vdbeInt.h *****************************************/
  19832. /*
  19833. ** 2003 September 6
  19834. **
  19835. ** The author disclaims copyright to this source code. In place of
  19836. ** a legal notice, here is a blessing:
  19837. **
  19838. ** May you do good and not evil.
  19839. ** May you find forgiveness for yourself and forgive others.
  19840. ** May you share freely, never taking more than you give.
  19841. **
  19842. *************************************************************************
  19843. ** This is the header file for information that is private to the
  19844. ** VDBE. This information used to all be at the top of the single
  19845. ** source code file "vdbe.c". When that file became too big (over
  19846. ** 6000 lines long) it was split up into several smaller files and
  19847. ** this header information was factored out.
  19848. */
  19849. #ifndef SQLITE_VDBEINT_H
  19850. #define SQLITE_VDBEINT_H
  19851. /*
  19852. ** The maximum number of times that a statement will try to reparse
  19853. ** itself before giving up and returning SQLITE_SCHEMA.
  19854. */
  19855. #ifndef SQLITE_MAX_SCHEMA_RETRY
  19856. # define SQLITE_MAX_SCHEMA_RETRY 50
  19857. #endif
  19858. /*
  19859. ** VDBE_DISPLAY_P4 is true or false depending on whether or not the
  19860. ** "explain" P4 display logic is enabled.
  19861. */
  19862. #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
  19863. || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG) \
  19864. || defined(SQLITE_ENABLE_BYTECODE_VTAB)
  19865. # define VDBE_DISPLAY_P4 1
  19866. #else
  19867. # define VDBE_DISPLAY_P4 0
  19868. #endif
  19869. /*
  19870. ** SQL is translated into a sequence of instructions to be
  19871. ** executed by a virtual machine. Each instruction is an instance
  19872. ** of the following structure.
  19873. */
  19874. typedef struct VdbeOp Op;
  19875. /*
  19876. ** Boolean values
  19877. */
  19878. typedef unsigned Bool;
  19879. /* Opaque type used by code in vdbesort.c */
  19880. typedef struct VdbeSorter VdbeSorter;
  19881. /* Elements of the linked list at Vdbe.pAuxData */
  19882. typedef struct AuxData AuxData;
  19883. /* Types of VDBE cursors */
  19884. #define CURTYPE_BTREE 0
  19885. #define CURTYPE_SORTER 1
  19886. #define CURTYPE_VTAB 2
  19887. #define CURTYPE_PSEUDO 3
  19888. /*
  19889. ** A VdbeCursor is an superclass (a wrapper) for various cursor objects:
  19890. **
  19891. ** * A b-tree cursor
  19892. ** - In the main database or in an ephemeral database
  19893. ** - On either an index or a table
  19894. ** * A sorter
  19895. ** * A virtual table
  19896. ** * A one-row "pseudotable" stored in a single register
  19897. */
  19898. typedef struct VdbeCursor VdbeCursor;
  19899. struct VdbeCursor {
  19900. u8 eCurType; /* One of the CURTYPE_* values above */
  19901. i8 iDb; /* Index of cursor database in db->aDb[] (or -1) */
  19902. u8 nullRow; /* True if pointing to a row with no data */
  19903. u8 deferredMoveto; /* A call to sqlite3BtreeMoveto() is needed */
  19904. u8 isTable; /* True for rowid tables. False for indexes */
  19905. #ifdef SQLITE_DEBUG
  19906. u8 seekOp; /* Most recent seek operation on this cursor */
  19907. u8 wrFlag; /* The wrFlag argument to sqlite3BtreeCursor() */
  19908. #endif
  19909. Bool isEphemeral:1; /* True for an ephemeral table */
  19910. Bool useRandomRowid:1; /* Generate new record numbers semi-randomly */
  19911. Bool isOrdered:1; /* True if the table is not BTREE_UNORDERED */
  19912. Bool seekHit:1; /* See the OP_SeekHit and OP_IfNoHope opcodes */
  19913. Btree *pBtx; /* Separate file holding temporary table */
  19914. i64 seqCount; /* Sequence counter */
  19915. int *aAltMap; /* Mapping from table to index column numbers */
  19916. /* Cached OP_Column parse information is only valid if cacheStatus matches
  19917. ** Vdbe.cacheCtr. Vdbe.cacheCtr will never take on the value of
  19918. ** CACHE_STALE (0) and so setting cacheStatus=CACHE_STALE guarantees that
  19919. ** the cache is out of date. */
  19920. u32 cacheStatus; /* Cache is valid if this matches Vdbe.cacheCtr */
  19921. int seekResult; /* Result of previous sqlite3BtreeMoveto() or 0
  19922. ** if there have been no prior seeks on the cursor. */
  19923. /* seekResult does not distinguish between "no seeks have ever occurred
  19924. ** on this cursor" and "the most recent seek was an exact match".
  19925. ** For CURTYPE_PSEUDO, seekResult is the register holding the record */
  19926. /* When a new VdbeCursor is allocated, only the fields above are zeroed.
  19927. ** The fields that follow are uninitialized, and must be individually
  19928. ** initialized prior to first use. */
  19929. VdbeCursor *pAltCursor; /* Associated index cursor from which to read */
  19930. union {
  19931. BtCursor *pCursor; /* CURTYPE_BTREE or _PSEUDO. Btree cursor */
  19932. sqlite3_vtab_cursor *pVCur; /* CURTYPE_VTAB. Vtab cursor */
  19933. VdbeSorter *pSorter; /* CURTYPE_SORTER. Sorter object */
  19934. } uc;
  19935. KeyInfo *pKeyInfo; /* Info about index keys needed by index cursors */
  19936. u32 iHdrOffset; /* Offset to next unparsed byte of the header */
  19937. Pgno pgnoRoot; /* Root page of the open btree cursor */
  19938. i16 nField; /* Number of fields in the header */
  19939. u16 nHdrParsed; /* Number of header fields parsed so far */
  19940. i64 movetoTarget; /* Argument to the deferred sqlite3BtreeMoveto() */
  19941. u32 *aOffset; /* Pointer to aType[nField] */
  19942. const u8 *aRow; /* Data for the current row, if all on one page */
  19943. u32 payloadSize; /* Total number of bytes in the record */
  19944. u32 szRow; /* Byte available in aRow */
  19945. #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
  19946. u64 maskUsed; /* Mask of columns used by this cursor */
  19947. #endif
  19948. /* 2*nField extra array elements allocated for aType[], beyond the one
  19949. ** static element declared in the structure. nField total array slots for
  19950. ** aType[] and nField+1 array slots for aOffset[] */
  19951. u32 aType[1]; /* Type values record decode. MUST BE LAST */
  19952. };
  19953. /*
  19954. ** A value for VdbeCursor.cacheStatus that means the cache is always invalid.
  19955. */
  19956. #define CACHE_STALE 0
  19957. /*
  19958. ** When a sub-program is executed (OP_Program), a structure of this type
  19959. ** is allocated to store the current value of the program counter, as
  19960. ** well as the current memory cell array and various other frame specific
  19961. ** values stored in the Vdbe struct. When the sub-program is finished,
  19962. ** these values are copied back to the Vdbe from the VdbeFrame structure,
  19963. ** restoring the state of the VM to as it was before the sub-program
  19964. ** began executing.
  19965. **
  19966. ** The memory for a VdbeFrame object is allocated and managed by a memory
  19967. ** cell in the parent (calling) frame. When the memory cell is deleted or
  19968. ** overwritten, the VdbeFrame object is not freed immediately. Instead, it
  19969. ** is linked into the Vdbe.pDelFrame list. The contents of the Vdbe.pDelFrame
  19970. ** list is deleted when the VM is reset in VdbeHalt(). The reason for doing
  19971. ** this instead of deleting the VdbeFrame immediately is to avoid recursive
  19972. ** calls to sqlite3VdbeMemRelease() when the memory cells belonging to the
  19973. ** child frame are released.
  19974. **
  19975. ** The currently executing frame is stored in Vdbe.pFrame. Vdbe.pFrame is
  19976. ** set to NULL if the currently executing frame is the main program.
  19977. */
  19978. typedef struct VdbeFrame VdbeFrame;
  19979. struct VdbeFrame {
  19980. Vdbe *v; /* VM this frame belongs to */
  19981. VdbeFrame *pParent; /* Parent of this frame, or NULL if parent is main */
  19982. Op *aOp; /* Program instructions for parent frame */
  19983. i64 *anExec; /* Event counters from parent frame */
  19984. Mem *aMem; /* Array of memory cells for parent frame */
  19985. VdbeCursor **apCsr; /* Array of Vdbe cursors for parent frame */
  19986. u8 *aOnce; /* Bitmask used by OP_Once */
  19987. void *token; /* Copy of SubProgram.token */
  19988. i64 lastRowid; /* Last insert rowid (sqlite3.lastRowid) */
  19989. AuxData *pAuxData; /* Linked list of auxdata allocations */
  19990. #if SQLITE_DEBUG
  19991. u32 iFrameMagic; /* magic number for sanity checking */
  19992. #endif
  19993. int nCursor; /* Number of entries in apCsr */
  19994. int pc; /* Program Counter in parent (calling) frame */
  19995. int nOp; /* Size of aOp array */
  19996. int nMem; /* Number of entries in aMem */
  19997. int nChildMem; /* Number of memory cells for child frame */
  19998. int nChildCsr; /* Number of cursors for child frame */
  19999. int nChange; /* Statement changes (Vdbe.nChange) */
  20000. int nDbChange; /* Value of db->nChange */
  20001. };
  20002. /* Magic number for sanity checking on VdbeFrame objects */
  20003. #define SQLITE_FRAME_MAGIC 0x879fb71e
  20004. /*
  20005. ** Return a pointer to the array of registers allocated for use
  20006. ** by a VdbeFrame.
  20007. */
  20008. #define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))])
  20009. /*
  20010. ** Internally, the vdbe manipulates nearly all SQL values as Mem
  20011. ** structures. Each Mem struct may cache multiple representations (string,
  20012. ** integer etc.) of the same value.
  20013. */
  20014. struct sqlite3_value {
  20015. union MemValue {
  20016. double r; /* Real value used when MEM_Real is set in flags */
  20017. i64 i; /* Integer value used when MEM_Int is set in flags */
  20018. int nZero; /* Extra zero bytes when MEM_Zero and MEM_Blob set */
  20019. const char *zPType; /* Pointer type when MEM_Term|MEM_Subtype|MEM_Null */
  20020. FuncDef *pDef; /* Used only when flags==MEM_Agg */
  20021. } u;
  20022. u16 flags; /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
  20023. u8 enc; /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
  20024. u8 eSubtype; /* Subtype for this value */
  20025. int n; /* Number of characters in string value, excluding '\0' */
  20026. char *z; /* String or BLOB value */
  20027. /* ShallowCopy only needs to copy the information above */
  20028. char *zMalloc; /* Space to hold MEM_Str or MEM_Blob if szMalloc>0 */
  20029. int szMalloc; /* Size of the zMalloc allocation */
  20030. u32 uTemp; /* Transient storage for serial_type in OP_MakeRecord */
  20031. sqlite3 *db; /* The associated database connection */
  20032. void (*xDel)(void*);/* Destructor for Mem.z - only valid if MEM_Dyn */
  20033. #ifdef SQLITE_DEBUG
  20034. Mem *pScopyFrom; /* This Mem is a shallow copy of pScopyFrom */
  20035. u16 mScopyFlags; /* flags value immediately after the shallow copy */
  20036. #endif
  20037. };
  20038. /*
  20039. ** Size of struct Mem not including the Mem.zMalloc member or anything that
  20040. ** follows.
  20041. */
  20042. #define MEMCELLSIZE offsetof(Mem,zMalloc)
  20043. /* One or more of the following flags are set to indicate the validOK
  20044. ** representations of the value stored in the Mem struct.
  20045. **
  20046. ** If the MEM_Null flag is set, then the value is an SQL NULL value.
  20047. ** For a pointer type created using sqlite3_bind_pointer() or
  20048. ** sqlite3_result_pointer() the MEM_Term and MEM_Subtype flags are also set.
  20049. **
  20050. ** If the MEM_Str flag is set then Mem.z points at a string representation.
  20051. ** Usually this is encoded in the same unicode encoding as the main
  20052. ** database (see below for exceptions). If the MEM_Term flag is also
  20053. ** set, then the string is nul terminated. The MEM_Int and MEM_Real
  20054. ** flags may coexist with the MEM_Str flag.
  20055. */
  20056. #define MEM_Null 0x0001 /* Value is NULL (or a pointer) */
  20057. #define MEM_Str 0x0002 /* Value is a string */
  20058. #define MEM_Int 0x0004 /* Value is an integer */
  20059. #define MEM_Real 0x0008 /* Value is a real number */
  20060. #define MEM_Blob 0x0010 /* Value is a BLOB */
  20061. #define MEM_IntReal 0x0020 /* MEM_Int that stringifies like MEM_Real */
  20062. #define MEM_AffMask 0x003f /* Mask of affinity bits */
  20063. #define MEM_FromBind 0x0040 /* Value originates from sqlite3_bind() */
  20064. #define MEM_Undefined 0x0080 /* Value is undefined */
  20065. #define MEM_Cleared 0x0100 /* NULL set by OP_Null, not from data */
  20066. #define MEM_TypeMask 0xc1bf /* Mask of type bits */
  20067. /* Whenever Mem contains a valid string or blob representation, one of
  20068. ** the following flags must be set to determine the memory management
  20069. ** policy for Mem.z. The MEM_Term flag tells us whether or not the
  20070. ** string is \000 or \u0000 terminated
  20071. */
  20072. #define MEM_Term 0x0200 /* String in Mem.z is zero terminated */
  20073. #define MEM_Dyn 0x0400 /* Need to call Mem.xDel() on Mem.z */
  20074. #define MEM_Static 0x0800 /* Mem.z points to a static string */
  20075. #define MEM_Ephem 0x1000 /* Mem.z points to an ephemeral string */
  20076. #define MEM_Agg 0x2000 /* Mem.z points to an agg function context */
  20077. #define MEM_Zero 0x4000 /* Mem.i contains count of 0s appended to blob */
  20078. #define MEM_Subtype 0x8000 /* Mem.eSubtype is valid */
  20079. #ifdef SQLITE_OMIT_INCRBLOB
  20080. #undef MEM_Zero
  20081. #define MEM_Zero 0x0000
  20082. #endif
  20083. /* Return TRUE if Mem X contains dynamically allocated content - anything
  20084. ** that needs to be deallocated to avoid a leak.
  20085. */
  20086. #define VdbeMemDynamic(X) \
  20087. (((X)->flags&(MEM_Agg|MEM_Dyn))!=0)
  20088. /*
  20089. ** Clear any existing type flags from a Mem and replace them with f
  20090. */
  20091. #define MemSetTypeFlag(p, f) \
  20092. ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
  20093. /*
  20094. ** True if Mem X is a NULL-nochng type.
  20095. */
  20096. #define MemNullNochng(X) \
  20097. (((X)->flags&MEM_TypeMask)==(MEM_Null|MEM_Zero) \
  20098. && (X)->n==0 && (X)->u.nZero==0)
  20099. /*
  20100. ** Return true if a memory cell is not marked as invalid. This macro
  20101. ** is for use inside assert() statements only.
  20102. */
  20103. #ifdef SQLITE_DEBUG
  20104. #define memIsValid(M) ((M)->flags & MEM_Undefined)==0
  20105. #endif
  20106. /*
  20107. ** Each auxiliary data pointer stored by a user defined function
  20108. ** implementation calling sqlite3_set_auxdata() is stored in an instance
  20109. ** of this structure. All such structures associated with a single VM
  20110. ** are stored in a linked list headed at Vdbe.pAuxData. All are destroyed
  20111. ** when the VM is halted (if not before).
  20112. */
  20113. struct AuxData {
  20114. int iAuxOp; /* Instruction number of OP_Function opcode */
  20115. int iAuxArg; /* Index of function argument. */
  20116. void *pAux; /* Aux data pointer */
  20117. void (*xDeleteAux)(void*); /* Destructor for the aux data */
  20118. AuxData *pNextAux; /* Next element in list */
  20119. };
  20120. /*
  20121. ** The "context" argument for an installable function. A pointer to an
  20122. ** instance of this structure is the first argument to the routines used
  20123. ** implement the SQL functions.
  20124. **
  20125. ** There is a typedef for this structure in sqlite.h. So all routines,
  20126. ** even the public interface to SQLite, can use a pointer to this structure.
  20127. ** But this file is the only place where the internal details of this
  20128. ** structure are known.
  20129. **
  20130. ** This structure is defined inside of vdbeInt.h because it uses substructures
  20131. ** (Mem) which are only defined there.
  20132. */
  20133. struct sqlite3_context {
  20134. Mem *pOut; /* The return value is stored here */
  20135. FuncDef *pFunc; /* Pointer to function information */
  20136. Mem *pMem; /* Memory cell used to store aggregate context */
  20137. Vdbe *pVdbe; /* The VM that owns this context */
  20138. int iOp; /* Instruction number of OP_Function */
  20139. int isError; /* Error code returned by the function. */
  20140. u8 skipFlag; /* Skip accumulator loading if true */
  20141. u8 argc; /* Number of arguments */
  20142. sqlite3_value *argv[1]; /* Argument set */
  20143. };
  20144. /* A bitfield type for use inside of structures. Always follow with :N where
  20145. ** N is the number of bits.
  20146. */
  20147. typedef unsigned bft; /* Bit Field Type */
  20148. /* The ScanStatus object holds a single value for the
  20149. ** sqlite3_stmt_scanstatus() interface.
  20150. */
  20151. typedef struct ScanStatus ScanStatus;
  20152. struct ScanStatus {
  20153. int addrExplain; /* OP_Explain for loop */
  20154. int addrLoop; /* Address of "loops" counter */
  20155. int addrVisit; /* Address of "rows visited" counter */
  20156. int iSelectID; /* The "Select-ID" for this loop */
  20157. LogEst nEst; /* Estimated output rows per loop */
  20158. char *zName; /* Name of table or index */
  20159. };
  20160. /* The DblquoteStr object holds the text of a double-quoted
  20161. ** string for a prepared statement. A linked list of these objects
  20162. ** is constructed during statement parsing and is held on Vdbe.pDblStr.
  20163. ** When computing a normalized SQL statement for an SQL statement, that
  20164. ** list is consulted for each double-quoted identifier to see if the
  20165. ** identifier should really be a string literal.
  20166. */
  20167. typedef struct DblquoteStr DblquoteStr;
  20168. struct DblquoteStr {
  20169. DblquoteStr *pNextStr; /* Next string literal in the list */
  20170. char z[8]; /* Dequoted value for the string */
  20171. };
  20172. /*
  20173. ** An instance of the virtual machine. This structure contains the complete
  20174. ** state of the virtual machine.
  20175. **
  20176. ** The "sqlite3_stmt" structure pointer that is returned by sqlite3_prepare()
  20177. ** is really a pointer to an instance of this structure.
  20178. */
  20179. struct Vdbe {
  20180. sqlite3 *db; /* The database connection that owns this statement */
  20181. Vdbe *pPrev,*pNext; /* Linked list of VDBEs with the same Vdbe.db */
  20182. Parse *pParse; /* Parsing context used to create this Vdbe */
  20183. ynVar nVar; /* Number of entries in aVar[] */
  20184. u32 magic; /* Magic number for sanity checking */
  20185. int nMem; /* Number of memory locations currently allocated */
  20186. int nCursor; /* Number of slots in apCsr[] */
  20187. u32 cacheCtr; /* VdbeCursor row cache generation counter */
  20188. int pc; /* The program counter */
  20189. int rc; /* Value to return */
  20190. int nChange; /* Number of db changes made since last reset */
  20191. int iStatement; /* Statement number (or 0 if has no opened stmt) */
  20192. i64 iCurrentTime; /* Value of julianday('now') for this statement */
  20193. i64 nFkConstraint; /* Number of imm. FK constraints this VM */
  20194. i64 nStmtDefCons; /* Number of def. constraints when stmt started */
  20195. i64 nStmtDefImmCons; /* Number of def. imm constraints when stmt started */
  20196. Mem *aMem; /* The memory locations */
  20197. Mem **apArg; /* Arguments to currently executing user function */
  20198. VdbeCursor **apCsr; /* One element of this array for each open cursor */
  20199. Mem *aVar; /* Values for the OP_Variable opcode. */
  20200. /* When allocating a new Vdbe object, all of the fields below should be
  20201. ** initialized to zero or NULL */
  20202. Op *aOp; /* Space to hold the virtual machine's program */
  20203. int nOp; /* Number of instructions in the program */
  20204. int nOpAlloc; /* Slots allocated for aOp[] */
  20205. Mem *aColName; /* Column names to return */
  20206. Mem *pResultSet; /* Pointer to an array of results */
  20207. char *zErrMsg; /* Error message written here */
  20208. VList *pVList; /* Name of variables */
  20209. #ifndef SQLITE_OMIT_TRACE
  20210. i64 startTime; /* Time when query started - used for profiling */
  20211. #endif
  20212. #ifdef SQLITE_DEBUG
  20213. int rcApp; /* errcode set by sqlite3_result_error_code() */
  20214. u32 nWrite; /* Number of write operations that have occurred */
  20215. #endif
  20216. u16 nResColumn; /* Number of columns in one row of the result set */
  20217. u8 errorAction; /* Recovery action to do in case of an error */
  20218. u8 minWriteFileFormat; /* Minimum file format for writable database files */
  20219. u8 prepFlags; /* SQLITE_PREPARE_* flags */
  20220. u8 doingRerun; /* True if rerunning after an auto-reprepare */
  20221. bft expired:2; /* 1: recompile VM immediately 2: when convenient */
  20222. bft explain:2; /* True if EXPLAIN present on SQL command */
  20223. bft changeCntOn:1; /* True to update the change-counter */
  20224. bft runOnlyOnce:1; /* Automatically expire on reset */
  20225. bft usesStmtJournal:1; /* True if uses a statement journal */
  20226. bft readOnly:1; /* True for statements that do not write */
  20227. bft bIsReader:1; /* True for statements that read */
  20228. yDbMask btreeMask; /* Bitmask of db->aDb[] entries referenced */
  20229. yDbMask lockMask; /* Subset of btreeMask that requires a lock */
  20230. u32 aCounter[7]; /* Counters used by sqlite3_stmt_status() */
  20231. char *zSql; /* Text of the SQL statement that generated this */
  20232. #ifdef SQLITE_ENABLE_NORMALIZE
  20233. char *zNormSql; /* Normalization of the associated SQL statement */
  20234. DblquoteStr *pDblStr; /* List of double-quoted string literals */
  20235. #endif
  20236. void *pFree; /* Free this when deleting the vdbe */
  20237. VdbeFrame *pFrame; /* Parent frame */
  20238. VdbeFrame *pDelFrame; /* List of frame objects to free on VM reset */
  20239. int nFrame; /* Number of frames in pFrame list */
  20240. u32 expmask; /* Binding to these vars invalidates VM */
  20241. SubProgram *pProgram; /* Linked list of all sub-programs used by VM */
  20242. AuxData *pAuxData; /* Linked list of auxdata allocations */
  20243. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  20244. i64 *anExec; /* Number of times each op has been executed */
  20245. int nScan; /* Entries in aScan[] */
  20246. ScanStatus *aScan; /* Scan definitions for sqlite3_stmt_scanstatus() */
  20247. #endif
  20248. };
  20249. /*
  20250. ** The following are allowed values for Vdbe.magic
  20251. */
  20252. #define VDBE_MAGIC_INIT 0x16bceaa5 /* Building a VDBE program */
  20253. #define VDBE_MAGIC_RUN 0x2df20da3 /* VDBE is ready to execute */
  20254. #define VDBE_MAGIC_HALT 0x319c2973 /* VDBE has completed execution */
  20255. #define VDBE_MAGIC_RESET 0x48fa9f76 /* Reset and ready to run again */
  20256. #define VDBE_MAGIC_DEAD 0x5606c3c8 /* The VDBE has been deallocated */
  20257. /*
  20258. ** Structure used to store the context required by the
  20259. ** sqlite3_preupdate_*() API functions.
  20260. */
  20261. struct PreUpdate {
  20262. Vdbe *v;
  20263. VdbeCursor *pCsr; /* Cursor to read old values from */
  20264. int op; /* One of SQLITE_INSERT, UPDATE, DELETE */
  20265. u8 *aRecord; /* old.* database record */
  20266. KeyInfo keyinfo;
  20267. UnpackedRecord *pUnpacked; /* Unpacked version of aRecord[] */
  20268. UnpackedRecord *pNewUnpacked; /* Unpacked version of new.* record */
  20269. int iNewReg; /* Register for new.* values */
  20270. i64 iKey1; /* First key value passed to hook */
  20271. i64 iKey2; /* Second key value passed to hook */
  20272. Mem *aNew; /* Array of new.* values */
  20273. Table *pTab; /* Schema object being upated */
  20274. Index *pPk; /* PK index if pTab is WITHOUT ROWID */
  20275. };
  20276. /*
  20277. ** Function prototypes
  20278. */
  20279. SQLITE_PRIVATE void sqlite3VdbeError(Vdbe*, const char *, ...);
  20280. SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*);
  20281. void sqliteVdbePopStack(Vdbe*,int);
  20282. SQLITE_PRIVATE int SQLITE_NOINLINE sqlite3VdbeFinishMoveto(VdbeCursor*);
  20283. SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor**, int*);
  20284. SQLITE_PRIVATE int sqlite3VdbeCursorRestore(VdbeCursor*);
  20285. SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32);
  20286. SQLITE_PRIVATE u8 sqlite3VdbeOneByteSerialTypeLen(u8);
  20287. SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(unsigned char*, Mem*, u32);
  20288. SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
  20289. SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(sqlite3*, AuxData**, int, int);
  20290. int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
  20291. SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(sqlite3*,VdbeCursor*,UnpackedRecord*,int*);
  20292. SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3*, BtCursor*, i64*);
  20293. SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);
  20294. #if !defined(SQLITE_OMIT_EXPLAIN) || defined(SQLITE_ENABLE_BYTECODE_VTAB)
  20295. SQLITE_PRIVATE int sqlite3VdbeNextOpcode(Vdbe*,Mem*,int,int*,int*,Op**);
  20296. SQLITE_PRIVATE char *sqlite3VdbeDisplayP4(sqlite3*,Op*);
  20297. #endif
  20298. #if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS)
  20299. SQLITE_PRIVATE char *sqlite3VdbeDisplayComment(sqlite3*,const Op*,const char*);
  20300. #endif
  20301. #if !defined(SQLITE_OMIT_EXPLAIN)
  20302. SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);
  20303. #endif
  20304. SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);
  20305. SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int);
  20306. SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*);
  20307. SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);
  20308. SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
  20309. SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*);
  20310. SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);
  20311. SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
  20312. SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);
  20313. #ifdef SQLITE_OMIT_FLOATING_POINT
  20314. # define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64
  20315. #else
  20316. SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem*, double);
  20317. #endif
  20318. SQLITE_PRIVATE void sqlite3VdbeMemSetPointer(Mem*, void*, const char*, void(*)(void*));
  20319. SQLITE_PRIVATE void sqlite3VdbeMemInit(Mem*,sqlite3*,u16);
  20320. SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*);
  20321. SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int);
  20322. #ifdef SQLITE_DEBUG
  20323. SQLITE_PRIVATE int sqlite3VdbeMemIsRowSet(const Mem*);
  20324. #endif
  20325. SQLITE_PRIVATE int sqlite3VdbeMemSetRowSet(Mem*);
  20326. SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*);
  20327. SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, u8, u8);
  20328. SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*);
  20329. SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*);
  20330. SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*);
  20331. SQLITE_PRIVATE int sqlite3VdbeBooleanValue(Mem*, int ifNull);
  20332. SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*);
  20333. SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*);
  20334. SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*);
  20335. SQLITE_PRIVATE int sqlite3VdbeMemCast(Mem*,u8,u8);
  20336. SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,u32,u32,Mem*);
  20337. SQLITE_PRIVATE int sqlite3VdbeMemFromBtreeZeroOffset(BtCursor*,u32,Mem*);
  20338. SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);
  20339. SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
  20340. #ifndef SQLITE_OMIT_WINDOWFUNC
  20341. SQLITE_PRIVATE int sqlite3VdbeMemAggValue(Mem*, Mem*, FuncDef*);
  20342. #endif
  20343. #if !defined(SQLITE_OMIT_EXPLAIN) || defined(SQLITE_ENABLE_BYTECODE_VTAB)
  20344. SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
  20345. #endif
  20346. SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
  20347. SQLITE_PRIVATE int sqlite3VdbeMemClearAndResize(Mem *pMem, int n);
  20348. SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int);
  20349. #ifdef SQLITE_DEBUG
  20350. SQLITE_PRIVATE int sqlite3VdbeFrameIsValid(VdbeFrame*);
  20351. #endif
  20352. SQLITE_PRIVATE void sqlite3VdbeFrameMemDel(void*); /* Destructor on Mem */
  20353. SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame*); /* Actually deletes the Frame */
  20354. SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *);
  20355. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  20356. SQLITE_PRIVATE void sqlite3VdbePreUpdateHook(Vdbe*,VdbeCursor*,int,const char*,Table*,i64,int);
  20357. #endif
  20358. SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p);
  20359. SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *, int, VdbeCursor *);
  20360. SQLITE_PRIVATE void sqlite3VdbeSorterReset(sqlite3 *, VdbeSorter *);
  20361. SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *, VdbeCursor *);
  20362. SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *, Mem *);
  20363. SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *, const VdbeCursor *);
  20364. SQLITE_PRIVATE int sqlite3VdbeSorterRewind(const VdbeCursor *, int *);
  20365. SQLITE_PRIVATE int sqlite3VdbeSorterWrite(const VdbeCursor *, Mem *);
  20366. SQLITE_PRIVATE int sqlite3VdbeSorterCompare(const VdbeCursor *, Mem *, int, int *);
  20367. #ifdef SQLITE_DEBUG
  20368. SQLITE_PRIVATE void sqlite3VdbeIncrWriteCounter(Vdbe*, VdbeCursor*);
  20369. SQLITE_PRIVATE void sqlite3VdbeAssertAbortable(Vdbe*);
  20370. #else
  20371. # define sqlite3VdbeIncrWriteCounter(V,C)
  20372. # define sqlite3VdbeAssertAbortable(V)
  20373. #endif
  20374. #if !defined(SQLITE_OMIT_SHARED_CACHE)
  20375. SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe*);
  20376. #else
  20377. # define sqlite3VdbeEnter(X)
  20378. #endif
  20379. #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
  20380. SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe*);
  20381. #else
  20382. # define sqlite3VdbeLeave(X)
  20383. #endif
  20384. #ifdef SQLITE_DEBUG
  20385. SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe*,Mem*);
  20386. SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem*);
  20387. #endif
  20388. #ifndef SQLITE_OMIT_FOREIGN_KEY
  20389. SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int);
  20390. #else
  20391. # define sqlite3VdbeCheckFk(p,i) 0
  20392. #endif
  20393. #ifdef SQLITE_DEBUG
  20394. SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe*);
  20395. SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, StrAccum *pStr);
  20396. #endif
  20397. #ifndef SQLITE_OMIT_UTF16
  20398. SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8);
  20399. SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem);
  20400. #endif
  20401. #ifndef SQLITE_OMIT_INCRBLOB
  20402. SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *);
  20403. #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
  20404. #else
  20405. #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
  20406. #define ExpandBlob(P) SQLITE_OK
  20407. #endif
  20408. #endif /* !defined(SQLITE_VDBEINT_H) */
  20409. /************** End of vdbeInt.h *********************************************/
  20410. /************** Continuing where we left off in status.c *********************/
  20411. /*
  20412. ** Variables in which to record status information.
  20413. */
  20414. #if SQLITE_PTRSIZE>4
  20415. typedef sqlite3_int64 sqlite3StatValueType;
  20416. #else
  20417. typedef u32 sqlite3StatValueType;
  20418. #endif
  20419. typedef struct sqlite3StatType sqlite3StatType;
  20420. static SQLITE_WSD struct sqlite3StatType {
  20421. sqlite3StatValueType nowValue[10]; /* Current value */
  20422. sqlite3StatValueType mxValue[10]; /* Maximum value */
  20423. } sqlite3Stat = { {0,}, {0,} };
  20424. /*
  20425. ** Elements of sqlite3Stat[] are protected by either the memory allocator
  20426. ** mutex, or by the pcache1 mutex. The following array determines which.
  20427. */
  20428. static const char statMutex[] = {
  20429. 0, /* SQLITE_STATUS_MEMORY_USED */
  20430. 1, /* SQLITE_STATUS_PAGECACHE_USED */
  20431. 1, /* SQLITE_STATUS_PAGECACHE_OVERFLOW */
  20432. 0, /* SQLITE_STATUS_SCRATCH_USED */
  20433. 0, /* SQLITE_STATUS_SCRATCH_OVERFLOW */
  20434. 0, /* SQLITE_STATUS_MALLOC_SIZE */
  20435. 0, /* SQLITE_STATUS_PARSER_STACK */
  20436. 1, /* SQLITE_STATUS_PAGECACHE_SIZE */
  20437. 0, /* SQLITE_STATUS_SCRATCH_SIZE */
  20438. 0, /* SQLITE_STATUS_MALLOC_COUNT */
  20439. };
  20440. /* The "wsdStat" macro will resolve to the status information
  20441. ** state vector. If writable static data is unsupported on the target,
  20442. ** we have to locate the state vector at run-time. In the more common
  20443. ** case where writable static data is supported, wsdStat can refer directly
  20444. ** to the "sqlite3Stat" state vector declared above.
  20445. */
  20446. #ifdef SQLITE_OMIT_WSD
  20447. # define wsdStatInit sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)
  20448. # define wsdStat x[0]
  20449. #else
  20450. # define wsdStatInit
  20451. # define wsdStat sqlite3Stat
  20452. #endif
  20453. /*
  20454. ** Return the current value of a status parameter. The caller must
  20455. ** be holding the appropriate mutex.
  20456. */
  20457. SQLITE_PRIVATE sqlite3_int64 sqlite3StatusValue(int op){
  20458. wsdStatInit;
  20459. assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
  20460. assert( op>=0 && op<ArraySize(statMutex) );
  20461. assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
  20462. : sqlite3MallocMutex()) );
  20463. return wsdStat.nowValue[op];
  20464. }
  20465. /*
  20466. ** Add N to the value of a status record. The caller must hold the
  20467. ** appropriate mutex. (Locking is checked by assert()).
  20468. **
  20469. ** The StatusUp() routine can accept positive or negative values for N.
  20470. ** The value of N is added to the current status value and the high-water
  20471. ** mark is adjusted if necessary.
  20472. **
  20473. ** The StatusDown() routine lowers the current value by N. The highwater
  20474. ** mark is unchanged. N must be non-negative for StatusDown().
  20475. */
  20476. SQLITE_PRIVATE void sqlite3StatusUp(int op, int N){
  20477. wsdStatInit;
  20478. assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
  20479. assert( op>=0 && op<ArraySize(statMutex) );
  20480. assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
  20481. : sqlite3MallocMutex()) );
  20482. wsdStat.nowValue[op] += N;
  20483. if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
  20484. wsdStat.mxValue[op] = wsdStat.nowValue[op];
  20485. }
  20486. }
  20487. SQLITE_PRIVATE void sqlite3StatusDown(int op, int N){
  20488. wsdStatInit;
  20489. assert( N>=0 );
  20490. assert( op>=0 && op<ArraySize(statMutex) );
  20491. assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
  20492. : sqlite3MallocMutex()) );
  20493. assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
  20494. wsdStat.nowValue[op] -= N;
  20495. }
  20496. /*
  20497. ** Adjust the highwater mark if necessary.
  20498. ** The caller must hold the appropriate mutex.
  20499. */
  20500. SQLITE_PRIVATE void sqlite3StatusHighwater(int op, int X){
  20501. sqlite3StatValueType newValue;
  20502. wsdStatInit;
  20503. assert( X>=0 );
  20504. newValue = (sqlite3StatValueType)X;
  20505. assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
  20506. assert( op>=0 && op<ArraySize(statMutex) );
  20507. assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
  20508. : sqlite3MallocMutex()) );
  20509. assert( op==SQLITE_STATUS_MALLOC_SIZE
  20510. || op==SQLITE_STATUS_PAGECACHE_SIZE
  20511. || op==SQLITE_STATUS_PARSER_STACK );
  20512. if( newValue>wsdStat.mxValue[op] ){
  20513. wsdStat.mxValue[op] = newValue;
  20514. }
  20515. }
  20516. /*
  20517. ** Query status information.
  20518. */
  20519. SQLITE_API int sqlite3_status64(
  20520. int op,
  20521. sqlite3_int64 *pCurrent,
  20522. sqlite3_int64 *pHighwater,
  20523. int resetFlag
  20524. ){
  20525. sqlite3_mutex *pMutex;
  20526. wsdStatInit;
  20527. if( op<0 || op>=ArraySize(wsdStat.nowValue) ){
  20528. return SQLITE_MISUSE_BKPT;
  20529. }
  20530. #ifdef SQLITE_ENABLE_API_ARMOR
  20531. if( pCurrent==0 || pHighwater==0 ) return SQLITE_MISUSE_BKPT;
  20532. #endif
  20533. pMutex = statMutex[op] ? sqlite3Pcache1Mutex() : sqlite3MallocMutex();
  20534. sqlite3_mutex_enter(pMutex);
  20535. *pCurrent = wsdStat.nowValue[op];
  20536. *pHighwater = wsdStat.mxValue[op];
  20537. if( resetFlag ){
  20538. wsdStat.mxValue[op] = wsdStat.nowValue[op];
  20539. }
  20540. sqlite3_mutex_leave(pMutex);
  20541. (void)pMutex; /* Prevent warning when SQLITE_THREADSAFE=0 */
  20542. return SQLITE_OK;
  20543. }
  20544. SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
  20545. sqlite3_int64 iCur = 0, iHwtr = 0;
  20546. int rc;
  20547. #ifdef SQLITE_ENABLE_API_ARMOR
  20548. if( pCurrent==0 || pHighwater==0 ) return SQLITE_MISUSE_BKPT;
  20549. #endif
  20550. rc = sqlite3_status64(op, &iCur, &iHwtr, resetFlag);
  20551. if( rc==0 ){
  20552. *pCurrent = (int)iCur;
  20553. *pHighwater = (int)iHwtr;
  20554. }
  20555. return rc;
  20556. }
  20557. /*
  20558. ** Return the number of LookasideSlot elements on the linked list
  20559. */
  20560. static u32 countLookasideSlots(LookasideSlot *p){
  20561. u32 cnt = 0;
  20562. while( p ){
  20563. p = p->pNext;
  20564. cnt++;
  20565. }
  20566. return cnt;
  20567. }
  20568. /*
  20569. ** Count the number of slots of lookaside memory that are outstanding
  20570. */
  20571. SQLITE_PRIVATE int sqlite3LookasideUsed(sqlite3 *db, int *pHighwater){
  20572. u32 nInit = countLookasideSlots(db->lookaside.pInit);
  20573. u32 nFree = countLookasideSlots(db->lookaside.pFree);
  20574. #ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE
  20575. nInit += countLookasideSlots(db->lookaside.pSmallInit);
  20576. nFree += countLookasideSlots(db->lookaside.pSmallFree);
  20577. #endif /* SQLITE_OMIT_TWOSIZE_LOOKASIDE */
  20578. if( pHighwater ) *pHighwater = db->lookaside.nSlot - nInit;
  20579. return db->lookaside.nSlot - (nInit+nFree);
  20580. }
  20581. /*
  20582. ** Query status information for a single database connection
  20583. */
  20584. SQLITE_API int sqlite3_db_status(
  20585. sqlite3 *db, /* The database connection whose status is desired */
  20586. int op, /* Status verb */
  20587. int *pCurrent, /* Write current value here */
  20588. int *pHighwater, /* Write high-water mark here */
  20589. int resetFlag /* Reset high-water mark if true */
  20590. ){
  20591. int rc = SQLITE_OK; /* Return code */
  20592. #ifdef SQLITE_ENABLE_API_ARMOR
  20593. if( !sqlite3SafetyCheckOk(db) || pCurrent==0|| pHighwater==0 ){
  20594. return SQLITE_MISUSE_BKPT;
  20595. }
  20596. #endif
  20597. sqlite3_mutex_enter(db->mutex);
  20598. switch( op ){
  20599. case SQLITE_DBSTATUS_LOOKASIDE_USED: {
  20600. *pCurrent = sqlite3LookasideUsed(db, pHighwater);
  20601. if( resetFlag ){
  20602. LookasideSlot *p = db->lookaside.pFree;
  20603. if( p ){
  20604. while( p->pNext ) p = p->pNext;
  20605. p->pNext = db->lookaside.pInit;
  20606. db->lookaside.pInit = db->lookaside.pFree;
  20607. db->lookaside.pFree = 0;
  20608. }
  20609. #ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE
  20610. p = db->lookaside.pSmallFree;
  20611. if( p ){
  20612. while( p->pNext ) p = p->pNext;
  20613. p->pNext = db->lookaside.pSmallInit;
  20614. db->lookaside.pSmallInit = db->lookaside.pSmallFree;
  20615. db->lookaside.pSmallFree = 0;
  20616. }
  20617. #endif
  20618. }
  20619. break;
  20620. }
  20621. case SQLITE_DBSTATUS_LOOKASIDE_HIT:
  20622. case SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE:
  20623. case SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL: {
  20624. testcase( op==SQLITE_DBSTATUS_LOOKASIDE_HIT );
  20625. testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE );
  20626. testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL );
  20627. assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)>=0 );
  20628. assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)<3 );
  20629. *pCurrent = 0;
  20630. *pHighwater = db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT];
  20631. if( resetFlag ){
  20632. db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT] = 0;
  20633. }
  20634. break;
  20635. }
  20636. /*
  20637. ** Return an approximation for the amount of memory currently used
  20638. ** by all pagers associated with the given database connection. The
  20639. ** highwater mark is meaningless and is returned as zero.
  20640. */
  20641. case SQLITE_DBSTATUS_CACHE_USED_SHARED:
  20642. case SQLITE_DBSTATUS_CACHE_USED: {
  20643. int totalUsed = 0;
  20644. int i;
  20645. sqlite3BtreeEnterAll(db);
  20646. for(i=0; i<db->nDb; i++){
  20647. Btree *pBt = db->aDb[i].pBt;
  20648. if( pBt ){
  20649. Pager *pPager = sqlite3BtreePager(pBt);
  20650. int nByte = sqlite3PagerMemUsed(pPager);
  20651. if( op==SQLITE_DBSTATUS_CACHE_USED_SHARED ){
  20652. nByte = nByte / sqlite3BtreeConnectionCount(pBt);
  20653. }
  20654. totalUsed += nByte;
  20655. }
  20656. }
  20657. sqlite3BtreeLeaveAll(db);
  20658. *pCurrent = totalUsed;
  20659. *pHighwater = 0;
  20660. break;
  20661. }
  20662. /*
  20663. ** *pCurrent gets an accurate estimate of the amount of memory used
  20664. ** to store the schema for all databases (main, temp, and any ATTACHed
  20665. ** databases. *pHighwater is set to zero.
  20666. */
  20667. case SQLITE_DBSTATUS_SCHEMA_USED: {
  20668. int i; /* Used to iterate through schemas */
  20669. int nByte = 0; /* Used to accumulate return value */
  20670. sqlite3BtreeEnterAll(db);
  20671. db->pnBytesFreed = &nByte;
  20672. for(i=0; i<db->nDb; i++){
  20673. Schema *pSchema = db->aDb[i].pSchema;
  20674. if( ALWAYS(pSchema!=0) ){
  20675. HashElem *p;
  20676. nByte += sqlite3GlobalConfig.m.xRoundup(sizeof(HashElem)) * (
  20677. pSchema->tblHash.count
  20678. + pSchema->trigHash.count
  20679. + pSchema->idxHash.count
  20680. + pSchema->fkeyHash.count
  20681. );
  20682. nByte += sqlite3_msize(pSchema->tblHash.ht);
  20683. nByte += sqlite3_msize(pSchema->trigHash.ht);
  20684. nByte += sqlite3_msize(pSchema->idxHash.ht);
  20685. nByte += sqlite3_msize(pSchema->fkeyHash.ht);
  20686. for(p=sqliteHashFirst(&pSchema->trigHash); p; p=sqliteHashNext(p)){
  20687. sqlite3DeleteTrigger(db, (Trigger*)sqliteHashData(p));
  20688. }
  20689. for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
  20690. sqlite3DeleteTable(db, (Table *)sqliteHashData(p));
  20691. }
  20692. }
  20693. }
  20694. db->pnBytesFreed = 0;
  20695. sqlite3BtreeLeaveAll(db);
  20696. *pHighwater = 0;
  20697. *pCurrent = nByte;
  20698. break;
  20699. }
  20700. /*
  20701. ** *pCurrent gets an accurate estimate of the amount of memory used
  20702. ** to store all prepared statements.
  20703. ** *pHighwater is set to zero.
  20704. */
  20705. case SQLITE_DBSTATUS_STMT_USED: {
  20706. struct Vdbe *pVdbe; /* Used to iterate through VMs */
  20707. int nByte = 0; /* Used to accumulate return value */
  20708. db->pnBytesFreed = &nByte;
  20709. for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){
  20710. sqlite3VdbeClearObject(db, pVdbe);
  20711. sqlite3DbFree(db, pVdbe);
  20712. }
  20713. db->pnBytesFreed = 0;
  20714. *pHighwater = 0; /* IMP: R-64479-57858 */
  20715. *pCurrent = nByte;
  20716. break;
  20717. }
  20718. /*
  20719. ** Set *pCurrent to the total cache hits or misses encountered by all
  20720. ** pagers the database handle is connected to. *pHighwater is always set
  20721. ** to zero.
  20722. */
  20723. case SQLITE_DBSTATUS_CACHE_SPILL:
  20724. op = SQLITE_DBSTATUS_CACHE_WRITE+1;
  20725. /* Fall through into the next case */
  20726. case SQLITE_DBSTATUS_CACHE_HIT:
  20727. case SQLITE_DBSTATUS_CACHE_MISS:
  20728. case SQLITE_DBSTATUS_CACHE_WRITE:{
  20729. int i;
  20730. int nRet = 0;
  20731. assert( SQLITE_DBSTATUS_CACHE_MISS==SQLITE_DBSTATUS_CACHE_HIT+1 );
  20732. assert( SQLITE_DBSTATUS_CACHE_WRITE==SQLITE_DBSTATUS_CACHE_HIT+2 );
  20733. for(i=0; i<db->nDb; i++){
  20734. if( db->aDb[i].pBt ){
  20735. Pager *pPager = sqlite3BtreePager(db->aDb[i].pBt);
  20736. sqlite3PagerCacheStat(pPager, op, resetFlag, &nRet);
  20737. }
  20738. }
  20739. *pHighwater = 0; /* IMP: R-42420-56072 */
  20740. /* IMP: R-54100-20147 */
  20741. /* IMP: R-29431-39229 */
  20742. *pCurrent = nRet;
  20743. break;
  20744. }
  20745. /* Set *pCurrent to non-zero if there are unresolved deferred foreign
  20746. ** key constraints. Set *pCurrent to zero if all foreign key constraints
  20747. ** have been satisfied. The *pHighwater is always set to zero.
  20748. */
  20749. case SQLITE_DBSTATUS_DEFERRED_FKS: {
  20750. *pHighwater = 0; /* IMP: R-11967-56545 */
  20751. *pCurrent = db->nDeferredImmCons>0 || db->nDeferredCons>0;
  20752. break;
  20753. }
  20754. default: {
  20755. rc = SQLITE_ERROR;
  20756. }
  20757. }
  20758. sqlite3_mutex_leave(db->mutex);
  20759. return rc;
  20760. }
  20761. /************** End of status.c **********************************************/
  20762. /************** Begin file date.c ********************************************/
  20763. /*
  20764. ** 2003 October 31
  20765. **
  20766. ** The author disclaims copyright to this source code. In place of
  20767. ** a legal notice, here is a blessing:
  20768. **
  20769. ** May you do good and not evil.
  20770. ** May you find forgiveness for yourself and forgive others.
  20771. ** May you share freely, never taking more than you give.
  20772. **
  20773. *************************************************************************
  20774. ** This file contains the C functions that implement date and time
  20775. ** functions for SQLite.
  20776. **
  20777. ** There is only one exported symbol in this file - the function
  20778. ** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
  20779. ** All other code has file scope.
  20780. **
  20781. ** SQLite processes all times and dates as julian day numbers. The
  20782. ** dates and times are stored as the number of days since noon
  20783. ** in Greenwich on November 24, 4714 B.C. according to the Gregorian
  20784. ** calendar system.
  20785. **
  20786. ** 1970-01-01 00:00:00 is JD 2440587.5
  20787. ** 2000-01-01 00:00:00 is JD 2451544.5
  20788. **
  20789. ** This implementation requires years to be expressed as a 4-digit number
  20790. ** which means that only dates between 0000-01-01 and 9999-12-31 can
  20791. ** be represented, even though julian day numbers allow a much wider
  20792. ** range of dates.
  20793. **
  20794. ** The Gregorian calendar system is used for all dates and times,
  20795. ** even those that predate the Gregorian calendar. Historians usually
  20796. ** use the julian calendar for dates prior to 1582-10-15 and for some
  20797. ** dates afterwards, depending on locale. Beware of this difference.
  20798. **
  20799. ** The conversion algorithms are implemented based on descriptions
  20800. ** in the following text:
  20801. **
  20802. ** Jean Meeus
  20803. ** Astronomical Algorithms, 2nd Edition, 1998
  20804. ** ISBN 0-943396-61-1
  20805. ** Willmann-Bell, Inc
  20806. ** Richmond, Virginia (USA)
  20807. */
  20808. /* #include "sqliteInt.h" */
  20809. /* #include <stdlib.h> */
  20810. /* #include <assert.h> */
  20811. #include <time.h>
  20812. #ifndef SQLITE_OMIT_DATETIME_FUNCS
  20813. /*
  20814. ** The MSVC CRT on Windows CE may not have a localtime() function.
  20815. ** So declare a substitute. The substitute function itself is
  20816. ** defined in "os_win.c".
  20817. */
  20818. #if !defined(SQLITE_OMIT_LOCALTIME) && defined(_WIN32_WCE) && \
  20819. (!defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API)
  20820. struct tm *__cdecl localtime(const time_t *);
  20821. #endif
  20822. /*
  20823. ** A structure for holding a single date and time.
  20824. */
  20825. typedef struct DateTime DateTime;
  20826. struct DateTime {
  20827. sqlite3_int64 iJD; /* The julian day number times 86400000 */
  20828. int Y, M, D; /* Year, month, and day */
  20829. int h, m; /* Hour and minutes */
  20830. int tz; /* Timezone offset in minutes */
  20831. double s; /* Seconds */
  20832. char validJD; /* True (1) if iJD is valid */
  20833. char rawS; /* Raw numeric value stored in s */
  20834. char validYMD; /* True (1) if Y,M,D are valid */
  20835. char validHMS; /* True (1) if h,m,s are valid */
  20836. char validTZ; /* True (1) if tz is valid */
  20837. char tzSet; /* Timezone was set explicitly */
  20838. char isError; /* An overflow has occurred */
  20839. };
  20840. /*
  20841. ** Convert zDate into one or more integers according to the conversion
  20842. ** specifier zFormat.
  20843. **
  20844. ** zFormat[] contains 4 characters for each integer converted, except for
  20845. ** the last integer which is specified by three characters. The meaning
  20846. ** of a four-character format specifiers ABCD is:
  20847. **
  20848. ** A: number of digits to convert. Always "2" or "4".
  20849. ** B: minimum value. Always "0" or "1".
  20850. ** C: maximum value, decoded as:
  20851. ** a: 12
  20852. ** b: 14
  20853. ** c: 24
  20854. ** d: 31
  20855. ** e: 59
  20856. ** f: 9999
  20857. ** D: the separator character, or \000 to indicate this is the
  20858. ** last number to convert.
  20859. **
  20860. ** Example: To translate an ISO-8601 date YYYY-MM-DD, the format would
  20861. ** be "40f-21a-20c". The "40f-" indicates the 4-digit year followed by "-".
  20862. ** The "21a-" indicates the 2-digit month followed by "-". The "20c" indicates
  20863. ** the 2-digit day which is the last integer in the set.
  20864. **
  20865. ** The function returns the number of successful conversions.
  20866. */
  20867. static int getDigits(const char *zDate, const char *zFormat, ...){
  20868. /* The aMx[] array translates the 3rd character of each format
  20869. ** spec into a max size: a b c d e f */
  20870. static const u16 aMx[] = { 12, 14, 24, 31, 59, 9999 };
  20871. va_list ap;
  20872. int cnt = 0;
  20873. char nextC;
  20874. va_start(ap, zFormat);
  20875. do{
  20876. char N = zFormat[0] - '0';
  20877. char min = zFormat[1] - '0';
  20878. int val = 0;
  20879. u16 max;
  20880. assert( zFormat[2]>='a' && zFormat[2]<='f' );
  20881. max = aMx[zFormat[2] - 'a'];
  20882. nextC = zFormat[3];
  20883. val = 0;
  20884. while( N-- ){
  20885. if( !sqlite3Isdigit(*zDate) ){
  20886. goto end_getDigits;
  20887. }
  20888. val = val*10 + *zDate - '0';
  20889. zDate++;
  20890. }
  20891. if( val<(int)min || val>(int)max || (nextC!=0 && nextC!=*zDate) ){
  20892. goto end_getDigits;
  20893. }
  20894. *va_arg(ap,int*) = val;
  20895. zDate++;
  20896. cnt++;
  20897. zFormat += 4;
  20898. }while( nextC );
  20899. end_getDigits:
  20900. va_end(ap);
  20901. return cnt;
  20902. }
  20903. /*
  20904. ** Parse a timezone extension on the end of a date-time.
  20905. ** The extension is of the form:
  20906. **
  20907. ** (+/-)HH:MM
  20908. **
  20909. ** Or the "zulu" notation:
  20910. **
  20911. ** Z
  20912. **
  20913. ** If the parse is successful, write the number of minutes
  20914. ** of change in p->tz and return 0. If a parser error occurs,
  20915. ** return non-zero.
  20916. **
  20917. ** A missing specifier is not considered an error.
  20918. */
  20919. static int parseTimezone(const char *zDate, DateTime *p){
  20920. int sgn = 0;
  20921. int nHr, nMn;
  20922. int c;
  20923. while( sqlite3Isspace(*zDate) ){ zDate++; }
  20924. p->tz = 0;
  20925. c = *zDate;
  20926. if( c=='-' ){
  20927. sgn = -1;
  20928. }else if( c=='+' ){
  20929. sgn = +1;
  20930. }else if( c=='Z' || c=='z' ){
  20931. zDate++;
  20932. goto zulu_time;
  20933. }else{
  20934. return c!=0;
  20935. }
  20936. zDate++;
  20937. if( getDigits(zDate, "20b:20e", &nHr, &nMn)!=2 ){
  20938. return 1;
  20939. }
  20940. zDate += 5;
  20941. p->tz = sgn*(nMn + nHr*60);
  20942. zulu_time:
  20943. while( sqlite3Isspace(*zDate) ){ zDate++; }
  20944. p->tzSet = 1;
  20945. return *zDate!=0;
  20946. }
  20947. /*
  20948. ** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
  20949. ** The HH, MM, and SS must each be exactly 2 digits. The
  20950. ** fractional seconds FFFF can be one or more digits.
  20951. **
  20952. ** Return 1 if there is a parsing error and 0 on success.
  20953. */
  20954. static int parseHhMmSs(const char *zDate, DateTime *p){
  20955. int h, m, s;
  20956. double ms = 0.0;
  20957. if( getDigits(zDate, "20c:20e", &h, &m)!=2 ){
  20958. return 1;
  20959. }
  20960. zDate += 5;
  20961. if( *zDate==':' ){
  20962. zDate++;
  20963. if( getDigits(zDate, "20e", &s)!=1 ){
  20964. return 1;
  20965. }
  20966. zDate += 2;
  20967. if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){
  20968. double rScale = 1.0;
  20969. zDate++;
  20970. while( sqlite3Isdigit(*zDate) ){
  20971. ms = ms*10.0 + *zDate - '0';
  20972. rScale *= 10.0;
  20973. zDate++;
  20974. }
  20975. ms /= rScale;
  20976. }
  20977. }else{
  20978. s = 0;
  20979. }
  20980. p->validJD = 0;
  20981. p->rawS = 0;
  20982. p->validHMS = 1;
  20983. p->h = h;
  20984. p->m = m;
  20985. p->s = s + ms;
  20986. if( parseTimezone(zDate, p) ) return 1;
  20987. p->validTZ = (p->tz!=0)?1:0;
  20988. return 0;
  20989. }
  20990. /*
  20991. ** Put the DateTime object into its error state.
  20992. */
  20993. static void datetimeError(DateTime *p){
  20994. memset(p, 0, sizeof(*p));
  20995. p->isError = 1;
  20996. }
  20997. /*
  20998. ** Convert from YYYY-MM-DD HH:MM:SS to julian day. We always assume
  20999. ** that the YYYY-MM-DD is according to the Gregorian calendar.
  21000. **
  21001. ** Reference: Meeus page 61
  21002. */
  21003. static void computeJD(DateTime *p){
  21004. int Y, M, D, A, B, X1, X2;
  21005. if( p->validJD ) return;
  21006. if( p->validYMD ){
  21007. Y = p->Y;
  21008. M = p->M;
  21009. D = p->D;
  21010. }else{
  21011. Y = 2000; /* If no YMD specified, assume 2000-Jan-01 */
  21012. M = 1;
  21013. D = 1;
  21014. }
  21015. if( Y<-4713 || Y>9999 || p->rawS ){
  21016. datetimeError(p);
  21017. return;
  21018. }
  21019. if( M<=2 ){
  21020. Y--;
  21021. M += 12;
  21022. }
  21023. A = Y/100;
  21024. B = 2 - A + (A/4);
  21025. X1 = 36525*(Y+4716)/100;
  21026. X2 = 306001*(M+1)/10000;
  21027. p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
  21028. p->validJD = 1;
  21029. if( p->validHMS ){
  21030. p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000);
  21031. if( p->validTZ ){
  21032. p->iJD -= p->tz*60000;
  21033. p->validYMD = 0;
  21034. p->validHMS = 0;
  21035. p->validTZ = 0;
  21036. }
  21037. }
  21038. }
  21039. /*
  21040. ** Parse dates of the form
  21041. **
  21042. ** YYYY-MM-DD HH:MM:SS.FFF
  21043. ** YYYY-MM-DD HH:MM:SS
  21044. ** YYYY-MM-DD HH:MM
  21045. ** YYYY-MM-DD
  21046. **
  21047. ** Write the result into the DateTime structure and return 0
  21048. ** on success and 1 if the input string is not a well-formed
  21049. ** date.
  21050. */
  21051. static int parseYyyyMmDd(const char *zDate, DateTime *p){
  21052. int Y, M, D, neg;
  21053. if( zDate[0]=='-' ){
  21054. zDate++;
  21055. neg = 1;
  21056. }else{
  21057. neg = 0;
  21058. }
  21059. if( getDigits(zDate, "40f-21a-21d", &Y, &M, &D)!=3 ){
  21060. return 1;
  21061. }
  21062. zDate += 10;
  21063. while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
  21064. if( parseHhMmSs(zDate, p)==0 ){
  21065. /* We got the time */
  21066. }else if( *zDate==0 ){
  21067. p->validHMS = 0;
  21068. }else{
  21069. return 1;
  21070. }
  21071. p->validJD = 0;
  21072. p->validYMD = 1;
  21073. p->Y = neg ? -Y : Y;
  21074. p->M = M;
  21075. p->D = D;
  21076. if( p->validTZ ){
  21077. computeJD(p);
  21078. }
  21079. return 0;
  21080. }
  21081. /*
  21082. ** Set the time to the current time reported by the VFS.
  21083. **
  21084. ** Return the number of errors.
  21085. */
  21086. static int setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
  21087. p->iJD = sqlite3StmtCurrentTime(context);
  21088. if( p->iJD>0 ){
  21089. p->validJD = 1;
  21090. return 0;
  21091. }else{
  21092. return 1;
  21093. }
  21094. }
  21095. /*
  21096. ** Input "r" is a numeric quantity which might be a julian day number,
  21097. ** or the number of seconds since 1970. If the value if r is within
  21098. ** range of a julian day number, install it as such and set validJD.
  21099. ** If the value is a valid unix timestamp, put it in p->s and set p->rawS.
  21100. */
  21101. static void setRawDateNumber(DateTime *p, double r){
  21102. p->s = r;
  21103. p->rawS = 1;
  21104. if( r>=0.0 && r<5373484.5 ){
  21105. p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
  21106. p->validJD = 1;
  21107. }
  21108. }
  21109. /*
  21110. ** Attempt to parse the given string into a julian day number. Return
  21111. ** the number of errors.
  21112. **
  21113. ** The following are acceptable forms for the input string:
  21114. **
  21115. ** YYYY-MM-DD HH:MM:SS.FFF +/-HH:MM
  21116. ** DDDD.DD
  21117. ** now
  21118. **
  21119. ** In the first form, the +/-HH:MM is always optional. The fractional
  21120. ** seconds extension (the ".FFF") is optional. The seconds portion
  21121. ** (":SS.FFF") is option. The year and date can be omitted as long
  21122. ** as there is a time string. The time string can be omitted as long
  21123. ** as there is a year and date.
  21124. */
  21125. static int parseDateOrTime(
  21126. sqlite3_context *context,
  21127. const char *zDate,
  21128. DateTime *p
  21129. ){
  21130. double r;
  21131. if( parseYyyyMmDd(zDate,p)==0 ){
  21132. return 0;
  21133. }else if( parseHhMmSs(zDate, p)==0 ){
  21134. return 0;
  21135. }else if( sqlite3StrICmp(zDate,"now")==0 && sqlite3NotPureFunc(context) ){
  21136. return setDateTimeToCurrent(context, p);
  21137. }else if( sqlite3AtoF(zDate, &r, sqlite3Strlen30(zDate), SQLITE_UTF8)>0 ){
  21138. setRawDateNumber(p, r);
  21139. return 0;
  21140. }
  21141. return 1;
  21142. }
  21143. /* The julian day number for 9999-12-31 23:59:59.999 is 5373484.4999999.
  21144. ** Multiplying this by 86400000 gives 464269060799999 as the maximum value
  21145. ** for DateTime.iJD.
  21146. **
  21147. ** But some older compilers (ex: gcc 4.2.1 on older Macs) cannot deal with
  21148. ** such a large integer literal, so we have to encode it.
  21149. */
  21150. #define INT_464269060799999 ((((i64)0x1a640)<<32)|0x1072fdff)
  21151. /*
  21152. ** Return TRUE if the given julian day number is within range.
  21153. **
  21154. ** The input is the JulianDay times 86400000.
  21155. */
  21156. static int validJulianDay(sqlite3_int64 iJD){
  21157. return iJD>=0 && iJD<=INT_464269060799999;
  21158. }
  21159. /*
  21160. ** Compute the Year, Month, and Day from the julian day number.
  21161. */
  21162. static void computeYMD(DateTime *p){
  21163. int Z, A, B, C, D, E, X1;
  21164. if( p->validYMD ) return;
  21165. if( !p->validJD ){
  21166. p->Y = 2000;
  21167. p->M = 1;
  21168. p->D = 1;
  21169. }else if( !validJulianDay(p->iJD) ){
  21170. datetimeError(p);
  21171. return;
  21172. }else{
  21173. Z = (int)((p->iJD + 43200000)/86400000);
  21174. A = (int)((Z - 1867216.25)/36524.25);
  21175. A = Z + 1 + A - (A/4);
  21176. B = A + 1524;
  21177. C = (int)((B - 122.1)/365.25);
  21178. D = (36525*(C&32767))/100;
  21179. E = (int)((B-D)/30.6001);
  21180. X1 = (int)(30.6001*E);
  21181. p->D = B - D - X1;
  21182. p->M = E<14 ? E-1 : E-13;
  21183. p->Y = p->M>2 ? C - 4716 : C - 4715;
  21184. }
  21185. p->validYMD = 1;
  21186. }
  21187. /*
  21188. ** Compute the Hour, Minute, and Seconds from the julian day number.
  21189. */
  21190. static void computeHMS(DateTime *p){
  21191. int s;
  21192. if( p->validHMS ) return;
  21193. computeJD(p);
  21194. s = (int)((p->iJD + 43200000) % 86400000);
  21195. p->s = s/1000.0;
  21196. s = (int)p->s;
  21197. p->s -= s;
  21198. p->h = s/3600;
  21199. s -= p->h*3600;
  21200. p->m = s/60;
  21201. p->s += s - p->m*60;
  21202. p->rawS = 0;
  21203. p->validHMS = 1;
  21204. }
  21205. /*
  21206. ** Compute both YMD and HMS
  21207. */
  21208. static void computeYMD_HMS(DateTime *p){
  21209. computeYMD(p);
  21210. computeHMS(p);
  21211. }
  21212. /*
  21213. ** Clear the YMD and HMS and the TZ
  21214. */
  21215. static void clearYMD_HMS_TZ(DateTime *p){
  21216. p->validYMD = 0;
  21217. p->validHMS = 0;
  21218. p->validTZ = 0;
  21219. }
  21220. #ifndef SQLITE_OMIT_LOCALTIME
  21221. /*
  21222. ** On recent Windows platforms, the localtime_s() function is available
  21223. ** as part of the "Secure CRT". It is essentially equivalent to
  21224. ** localtime_r() available under most POSIX platforms, except that the
  21225. ** order of the parameters is reversed.
  21226. **
  21227. ** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
  21228. **
  21229. ** If the user has not indicated to use localtime_r() or localtime_s()
  21230. ** already, check for an MSVC build environment that provides
  21231. ** localtime_s().
  21232. */
  21233. #if !HAVE_LOCALTIME_R && !HAVE_LOCALTIME_S \
  21234. && defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
  21235. #undef HAVE_LOCALTIME_S
  21236. #define HAVE_LOCALTIME_S 1
  21237. #endif
  21238. /*
  21239. ** The following routine implements the rough equivalent of localtime_r()
  21240. ** using whatever operating-system specific localtime facility that
  21241. ** is available. This routine returns 0 on success and
  21242. ** non-zero on any kind of error.
  21243. **
  21244. ** If the sqlite3GlobalConfig.bLocaltimeFault variable is true then this
  21245. ** routine will always fail.
  21246. **
  21247. ** EVIDENCE-OF: R-62172-00036 In this implementation, the standard C
  21248. ** library function localtime_r() is used to assist in the calculation of
  21249. ** local time.
  21250. */
  21251. static int osLocaltime(time_t *t, struct tm *pTm){
  21252. int rc;
  21253. #if !HAVE_LOCALTIME_R && !HAVE_LOCALTIME_S
  21254. struct tm *pX;
  21255. #if SQLITE_THREADSAFE>0
  21256. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  21257. #endif
  21258. sqlite3_mutex_enter(mutex);
  21259. pX = localtime(t);
  21260. #ifndef SQLITE_UNTESTABLE
  21261. if( sqlite3GlobalConfig.bLocaltimeFault ) pX = 0;
  21262. #endif
  21263. if( pX ) *pTm = *pX;
  21264. sqlite3_mutex_leave(mutex);
  21265. rc = pX==0;
  21266. #else
  21267. #ifndef SQLITE_UNTESTABLE
  21268. if( sqlite3GlobalConfig.bLocaltimeFault ) return 1;
  21269. #endif
  21270. #if HAVE_LOCALTIME_R
  21271. rc = localtime_r(t, pTm)==0;
  21272. #else
  21273. rc = localtime_s(pTm, t);
  21274. #endif /* HAVE_LOCALTIME_R */
  21275. #endif /* HAVE_LOCALTIME_R || HAVE_LOCALTIME_S */
  21276. return rc;
  21277. }
  21278. #endif /* SQLITE_OMIT_LOCALTIME */
  21279. #ifndef SQLITE_OMIT_LOCALTIME
  21280. /*
  21281. ** Compute the difference (in milliseconds) between localtime and UTC
  21282. ** (a.k.a. GMT) for the time value p where p is in UTC. If no error occurs,
  21283. ** return this value and set *pRc to SQLITE_OK.
  21284. **
  21285. ** Or, if an error does occur, set *pRc to SQLITE_ERROR. The returned value
  21286. ** is undefined in this case.
  21287. */
  21288. static sqlite3_int64 localtimeOffset(
  21289. DateTime *p, /* Date at which to calculate offset */
  21290. sqlite3_context *pCtx, /* Write error here if one occurs */
  21291. int *pRc /* OUT: Error code. SQLITE_OK or ERROR */
  21292. ){
  21293. DateTime x, y;
  21294. time_t t;
  21295. struct tm sLocal;
  21296. /* Initialize the contents of sLocal to avoid a compiler warning. */
  21297. memset(&sLocal, 0, sizeof(sLocal));
  21298. x = *p;
  21299. computeYMD_HMS(&x);
  21300. if( x.Y<1971 || x.Y>=2038 ){
  21301. /* EVIDENCE-OF: R-55269-29598 The localtime_r() C function normally only
  21302. ** works for years between 1970 and 2037. For dates outside this range,
  21303. ** SQLite attempts to map the year into an equivalent year within this
  21304. ** range, do the calculation, then map the year back.
  21305. */
  21306. x.Y = 2000;
  21307. x.M = 1;
  21308. x.D = 1;
  21309. x.h = 0;
  21310. x.m = 0;
  21311. x.s = 0.0;
  21312. } else {
  21313. int s = (int)(x.s + 0.5);
  21314. x.s = s;
  21315. }
  21316. x.tz = 0;
  21317. x.validJD = 0;
  21318. computeJD(&x);
  21319. t = (time_t)(x.iJD/1000 - 21086676*(i64)10000);
  21320. if( osLocaltime(&t, &sLocal) ){
  21321. sqlite3_result_error(pCtx, "local time unavailable", -1);
  21322. *pRc = SQLITE_ERROR;
  21323. return 0;
  21324. }
  21325. y.Y = sLocal.tm_year + 1900;
  21326. y.M = sLocal.tm_mon + 1;
  21327. y.D = sLocal.tm_mday;
  21328. y.h = sLocal.tm_hour;
  21329. y.m = sLocal.tm_min;
  21330. y.s = sLocal.tm_sec;
  21331. y.validYMD = 1;
  21332. y.validHMS = 1;
  21333. y.validJD = 0;
  21334. y.rawS = 0;
  21335. y.validTZ = 0;
  21336. y.isError = 0;
  21337. computeJD(&y);
  21338. *pRc = SQLITE_OK;
  21339. return y.iJD - x.iJD;
  21340. }
  21341. #endif /* SQLITE_OMIT_LOCALTIME */
  21342. /*
  21343. ** The following table defines various date transformations of the form
  21344. **
  21345. ** 'NNN days'
  21346. **
  21347. ** Where NNN is an arbitrary floating-point number and "days" can be one
  21348. ** of several units of time.
  21349. */
  21350. static const struct {
  21351. u8 eType; /* Transformation type code */
  21352. u8 nName; /* Length of th name */
  21353. char *zName; /* Name of the transformation */
  21354. double rLimit; /* Maximum NNN value for this transform */
  21355. double rXform; /* Constant used for this transform */
  21356. } aXformType[] = {
  21357. { 0, 6, "second", 464269060800.0, 1000.0 },
  21358. { 0, 6, "minute", 7737817680.0, 60000.0 },
  21359. { 0, 4, "hour", 128963628.0, 3600000.0 },
  21360. { 0, 3, "day", 5373485.0, 86400000.0 },
  21361. { 1, 5, "month", 176546.0, 2592000000.0 },
  21362. { 2, 4, "year", 14713.0, 31536000000.0 },
  21363. };
  21364. /*
  21365. ** Process a modifier to a date-time stamp. The modifiers are
  21366. ** as follows:
  21367. **
  21368. ** NNN days
  21369. ** NNN hours
  21370. ** NNN minutes
  21371. ** NNN.NNNN seconds
  21372. ** NNN months
  21373. ** NNN years
  21374. ** start of month
  21375. ** start of year
  21376. ** start of week
  21377. ** start of day
  21378. ** weekday N
  21379. ** unixepoch
  21380. ** localtime
  21381. ** utc
  21382. **
  21383. ** Return 0 on success and 1 if there is any kind of error. If the error
  21384. ** is in a system call (i.e. localtime()), then an error message is written
  21385. ** to context pCtx. If the error is an unrecognized modifier, no error is
  21386. ** written to pCtx.
  21387. */
  21388. static int parseModifier(
  21389. sqlite3_context *pCtx, /* Function context */
  21390. const char *z, /* The text of the modifier */
  21391. int n, /* Length of zMod in bytes */
  21392. DateTime *p /* The date/time value to be modified */
  21393. ){
  21394. int rc = 1;
  21395. double r;
  21396. switch(sqlite3UpperToLower[(u8)z[0]] ){
  21397. #ifndef SQLITE_OMIT_LOCALTIME
  21398. case 'l': {
  21399. /* localtime
  21400. **
  21401. ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
  21402. ** show local time.
  21403. */
  21404. if( sqlite3_stricmp(z, "localtime")==0 && sqlite3NotPureFunc(pCtx) ){
  21405. computeJD(p);
  21406. p->iJD += localtimeOffset(p, pCtx, &rc);
  21407. clearYMD_HMS_TZ(p);
  21408. }
  21409. break;
  21410. }
  21411. #endif
  21412. case 'u': {
  21413. /*
  21414. ** unixepoch
  21415. **
  21416. ** Treat the current value of p->s as the number of
  21417. ** seconds since 1970. Convert to a real julian day number.
  21418. */
  21419. if( sqlite3_stricmp(z, "unixepoch")==0 && p->rawS ){
  21420. r = p->s*1000.0 + 210866760000000.0;
  21421. if( r>=0.0 && r<464269060800000.0 ){
  21422. clearYMD_HMS_TZ(p);
  21423. p->iJD = (sqlite3_int64)(r + 0.5);
  21424. p->validJD = 1;
  21425. p->rawS = 0;
  21426. rc = 0;
  21427. }
  21428. }
  21429. #ifndef SQLITE_OMIT_LOCALTIME
  21430. else if( sqlite3_stricmp(z, "utc")==0 && sqlite3NotPureFunc(pCtx) ){
  21431. if( p->tzSet==0 ){
  21432. sqlite3_int64 c1;
  21433. computeJD(p);
  21434. c1 = localtimeOffset(p, pCtx, &rc);
  21435. if( rc==SQLITE_OK ){
  21436. p->iJD -= c1;
  21437. clearYMD_HMS_TZ(p);
  21438. p->iJD += c1 - localtimeOffset(p, pCtx, &rc);
  21439. }
  21440. p->tzSet = 1;
  21441. }else{
  21442. rc = SQLITE_OK;
  21443. }
  21444. }
  21445. #endif
  21446. break;
  21447. }
  21448. case 'w': {
  21449. /*
  21450. ** weekday N
  21451. **
  21452. ** Move the date to the same time on the next occurrence of
  21453. ** weekday N where 0==Sunday, 1==Monday, and so forth. If the
  21454. ** date is already on the appropriate weekday, this is a no-op.
  21455. */
  21456. if( sqlite3_strnicmp(z, "weekday ", 8)==0
  21457. && sqlite3AtoF(&z[8], &r, sqlite3Strlen30(&z[8]), SQLITE_UTF8)>0
  21458. && (n=(int)r)==r && n>=0 && r<7 ){
  21459. sqlite3_int64 Z;
  21460. computeYMD_HMS(p);
  21461. p->validTZ = 0;
  21462. p->validJD = 0;
  21463. computeJD(p);
  21464. Z = ((p->iJD + 129600000)/86400000) % 7;
  21465. if( Z>n ) Z -= 7;
  21466. p->iJD += (n - Z)*86400000;
  21467. clearYMD_HMS_TZ(p);
  21468. rc = 0;
  21469. }
  21470. break;
  21471. }
  21472. case 's': {
  21473. /*
  21474. ** start of TTTTT
  21475. **
  21476. ** Move the date backwards to the beginning of the current day,
  21477. ** or month or year.
  21478. */
  21479. if( sqlite3_strnicmp(z, "start of ", 9)!=0 ) break;
  21480. if( !p->validJD && !p->validYMD && !p->validHMS ) break;
  21481. z += 9;
  21482. computeYMD(p);
  21483. p->validHMS = 1;
  21484. p->h = p->m = 0;
  21485. p->s = 0.0;
  21486. p->rawS = 0;
  21487. p->validTZ = 0;
  21488. p->validJD = 0;
  21489. if( sqlite3_stricmp(z,"month")==0 ){
  21490. p->D = 1;
  21491. rc = 0;
  21492. }else if( sqlite3_stricmp(z,"year")==0 ){
  21493. p->M = 1;
  21494. p->D = 1;
  21495. rc = 0;
  21496. }else if( sqlite3_stricmp(z,"day")==0 ){
  21497. rc = 0;
  21498. }
  21499. break;
  21500. }
  21501. case '+':
  21502. case '-':
  21503. case '0':
  21504. case '1':
  21505. case '2':
  21506. case '3':
  21507. case '4':
  21508. case '5':
  21509. case '6':
  21510. case '7':
  21511. case '8':
  21512. case '9': {
  21513. double rRounder;
  21514. int i;
  21515. for(n=1; z[n] && z[n]!=':' && !sqlite3Isspace(z[n]); n++){}
  21516. if( sqlite3AtoF(z, &r, n, SQLITE_UTF8)<=0 ){
  21517. rc = 1;
  21518. break;
  21519. }
  21520. if( z[n]==':' ){
  21521. /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
  21522. ** specified number of hours, minutes, seconds, and fractional seconds
  21523. ** to the time. The ".FFF" may be omitted. The ":SS.FFF" may be
  21524. ** omitted.
  21525. */
  21526. const char *z2 = z;
  21527. DateTime tx;
  21528. sqlite3_int64 day;
  21529. if( !sqlite3Isdigit(*z2) ) z2++;
  21530. memset(&tx, 0, sizeof(tx));
  21531. if( parseHhMmSs(z2, &tx) ) break;
  21532. computeJD(&tx);
  21533. tx.iJD -= 43200000;
  21534. day = tx.iJD/86400000;
  21535. tx.iJD -= day*86400000;
  21536. if( z[0]=='-' ) tx.iJD = -tx.iJD;
  21537. computeJD(p);
  21538. clearYMD_HMS_TZ(p);
  21539. p->iJD += tx.iJD;
  21540. rc = 0;
  21541. break;
  21542. }
  21543. /* If control reaches this point, it means the transformation is
  21544. ** one of the forms like "+NNN days". */
  21545. z += n;
  21546. while( sqlite3Isspace(*z) ) z++;
  21547. n = sqlite3Strlen30(z);
  21548. if( n>10 || n<3 ) break;
  21549. if( sqlite3UpperToLower[(u8)z[n-1]]=='s' ) n--;
  21550. computeJD(p);
  21551. rc = 1;
  21552. rRounder = r<0 ? -0.5 : +0.5;
  21553. for(i=0; i<ArraySize(aXformType); i++){
  21554. if( aXformType[i].nName==n
  21555. && sqlite3_strnicmp(aXformType[i].zName, z, n)==0
  21556. && r>-aXformType[i].rLimit && r<aXformType[i].rLimit
  21557. ){
  21558. switch( aXformType[i].eType ){
  21559. case 1: { /* Special processing to add months */
  21560. int x;
  21561. computeYMD_HMS(p);
  21562. p->M += (int)r;
  21563. x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
  21564. p->Y += x;
  21565. p->M -= x*12;
  21566. p->validJD = 0;
  21567. r -= (int)r;
  21568. break;
  21569. }
  21570. case 2: { /* Special processing to add years */
  21571. int y = (int)r;
  21572. computeYMD_HMS(p);
  21573. p->Y += y;
  21574. p->validJD = 0;
  21575. r -= (int)r;
  21576. break;
  21577. }
  21578. }
  21579. computeJD(p);
  21580. p->iJD += (sqlite3_int64)(r*aXformType[i].rXform + rRounder);
  21581. rc = 0;
  21582. break;
  21583. }
  21584. }
  21585. clearYMD_HMS_TZ(p);
  21586. break;
  21587. }
  21588. default: {
  21589. break;
  21590. }
  21591. }
  21592. return rc;
  21593. }
  21594. /*
  21595. ** Process time function arguments. argv[0] is a date-time stamp.
  21596. ** argv[1] and following are modifiers. Parse them all and write
  21597. ** the resulting time into the DateTime structure p. Return 0
  21598. ** on success and 1 if there are any errors.
  21599. **
  21600. ** If there are zero parameters (if even argv[0] is undefined)
  21601. ** then assume a default value of "now" for argv[0].
  21602. */
  21603. static int isDate(
  21604. sqlite3_context *context,
  21605. int argc,
  21606. sqlite3_value **argv,
  21607. DateTime *p
  21608. ){
  21609. int i, n;
  21610. const unsigned char *z;
  21611. int eType;
  21612. memset(p, 0, sizeof(*p));
  21613. if( argc==0 ){
  21614. return setDateTimeToCurrent(context, p);
  21615. }
  21616. if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
  21617. || eType==SQLITE_INTEGER ){
  21618. setRawDateNumber(p, sqlite3_value_double(argv[0]));
  21619. }else{
  21620. z = sqlite3_value_text(argv[0]);
  21621. if( !z || parseDateOrTime(context, (char*)z, p) ){
  21622. return 1;
  21623. }
  21624. }
  21625. for(i=1; i<argc; i++){
  21626. z = sqlite3_value_text(argv[i]);
  21627. n = sqlite3_value_bytes(argv[i]);
  21628. if( z==0 || parseModifier(context, (char*)z, n, p) ) return 1;
  21629. }
  21630. computeJD(p);
  21631. if( p->isError || !validJulianDay(p->iJD) ) return 1;
  21632. return 0;
  21633. }
  21634. /*
  21635. ** The following routines implement the various date and time functions
  21636. ** of SQLite.
  21637. */
  21638. /*
  21639. ** julianday( TIMESTRING, MOD, MOD, ...)
  21640. **
  21641. ** Return the julian day number of the date specified in the arguments
  21642. */
  21643. static void juliandayFunc(
  21644. sqlite3_context *context,
  21645. int argc,
  21646. sqlite3_value **argv
  21647. ){
  21648. DateTime x;
  21649. if( isDate(context, argc, argv, &x)==0 ){
  21650. computeJD(&x);
  21651. sqlite3_result_double(context, x.iJD/86400000.0);
  21652. }
  21653. }
  21654. /*
  21655. ** datetime( TIMESTRING, MOD, MOD, ...)
  21656. **
  21657. ** Return YYYY-MM-DD HH:MM:SS
  21658. */
  21659. static void datetimeFunc(
  21660. sqlite3_context *context,
  21661. int argc,
  21662. sqlite3_value **argv
  21663. ){
  21664. DateTime x;
  21665. if( isDate(context, argc, argv, &x)==0 ){
  21666. char zBuf[100];
  21667. computeYMD_HMS(&x);
  21668. sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
  21669. x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
  21670. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  21671. }
  21672. }
  21673. /*
  21674. ** time( TIMESTRING, MOD, MOD, ...)
  21675. **
  21676. ** Return HH:MM:SS
  21677. */
  21678. static void timeFunc(
  21679. sqlite3_context *context,
  21680. int argc,
  21681. sqlite3_value **argv
  21682. ){
  21683. DateTime x;
  21684. if( isDate(context, argc, argv, &x)==0 ){
  21685. char zBuf[100];
  21686. computeHMS(&x);
  21687. sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
  21688. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  21689. }
  21690. }
  21691. /*
  21692. ** date( TIMESTRING, MOD, MOD, ...)
  21693. **
  21694. ** Return YYYY-MM-DD
  21695. */
  21696. static void dateFunc(
  21697. sqlite3_context *context,
  21698. int argc,
  21699. sqlite3_value **argv
  21700. ){
  21701. DateTime x;
  21702. if( isDate(context, argc, argv, &x)==0 ){
  21703. char zBuf[100];
  21704. computeYMD(&x);
  21705. sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
  21706. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  21707. }
  21708. }
  21709. /*
  21710. ** strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
  21711. **
  21712. ** Return a string described by FORMAT. Conversions as follows:
  21713. **
  21714. ** %d day of month
  21715. ** %f ** fractional seconds SS.SSS
  21716. ** %H hour 00-24
  21717. ** %j day of year 000-366
  21718. ** %J ** julian day number
  21719. ** %m month 01-12
  21720. ** %M minute 00-59
  21721. ** %s seconds since 1970-01-01
  21722. ** %S seconds 00-59
  21723. ** %w day of week 0-6 sunday==0
  21724. ** %W week of year 00-53
  21725. ** %Y year 0000-9999
  21726. ** %% %
  21727. */
  21728. static void strftimeFunc(
  21729. sqlite3_context *context,
  21730. int argc,
  21731. sqlite3_value **argv
  21732. ){
  21733. DateTime x;
  21734. u64 n;
  21735. size_t i,j;
  21736. char *z;
  21737. sqlite3 *db;
  21738. const char *zFmt;
  21739. char zBuf[100];
  21740. if( argc==0 ) return;
  21741. zFmt = (const char*)sqlite3_value_text(argv[0]);
  21742. if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
  21743. db = sqlite3_context_db_handle(context);
  21744. for(i=0, n=1; zFmt[i]; i++, n++){
  21745. if( zFmt[i]=='%' ){
  21746. switch( zFmt[i+1] ){
  21747. case 'd':
  21748. case 'H':
  21749. case 'm':
  21750. case 'M':
  21751. case 'S':
  21752. case 'W':
  21753. n++;
  21754. /* fall thru */
  21755. case 'w':
  21756. case '%':
  21757. break;
  21758. case 'f':
  21759. n += 8;
  21760. break;
  21761. case 'j':
  21762. n += 3;
  21763. break;
  21764. case 'Y':
  21765. n += 8;
  21766. break;
  21767. case 's':
  21768. case 'J':
  21769. n += 50;
  21770. break;
  21771. default:
  21772. return; /* ERROR. return a NULL */
  21773. }
  21774. i++;
  21775. }
  21776. }
  21777. testcase( n==sizeof(zBuf)-1 );
  21778. testcase( n==sizeof(zBuf) );
  21779. testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
  21780. testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );
  21781. if( n<sizeof(zBuf) ){
  21782. z = zBuf;
  21783. }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
  21784. sqlite3_result_error_toobig(context);
  21785. return;
  21786. }else{
  21787. z = sqlite3DbMallocRawNN(db, (int)n);
  21788. if( z==0 ){
  21789. sqlite3_result_error_nomem(context);
  21790. return;
  21791. }
  21792. }
  21793. computeJD(&x);
  21794. computeYMD_HMS(&x);
  21795. for(i=j=0; zFmt[i]; i++){
  21796. if( zFmt[i]!='%' ){
  21797. z[j++] = zFmt[i];
  21798. }else{
  21799. i++;
  21800. switch( zFmt[i] ){
  21801. case 'd': sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
  21802. case 'f': {
  21803. double s = x.s;
  21804. if( s>59.999 ) s = 59.999;
  21805. sqlite3_snprintf(7, &z[j],"%06.3f", s);
  21806. j += sqlite3Strlen30(&z[j]);
  21807. break;
  21808. }
  21809. case 'H': sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
  21810. case 'W': /* Fall thru */
  21811. case 'j': {
  21812. int nDay; /* Number of days since 1st day of year */
  21813. DateTime y = x;
  21814. y.validJD = 0;
  21815. y.M = 1;
  21816. y.D = 1;
  21817. computeJD(&y);
  21818. nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
  21819. if( zFmt[i]=='W' ){
  21820. int wd; /* 0=Monday, 1=Tuesday, ... 6=Sunday */
  21821. wd = (int)(((x.iJD+43200000)/86400000)%7);
  21822. sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
  21823. j += 2;
  21824. }else{
  21825. sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
  21826. j += 3;
  21827. }
  21828. break;
  21829. }
  21830. case 'J': {
  21831. sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
  21832. j+=sqlite3Strlen30(&z[j]);
  21833. break;
  21834. }
  21835. case 'm': sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
  21836. case 'M': sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
  21837. case 's': {
  21838. sqlite3_snprintf(30,&z[j],"%lld",
  21839. (i64)(x.iJD/1000 - 21086676*(i64)10000));
  21840. j += sqlite3Strlen30(&z[j]);
  21841. break;
  21842. }
  21843. case 'S': sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
  21844. case 'w': {
  21845. z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
  21846. break;
  21847. }
  21848. case 'Y': {
  21849. sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]);
  21850. break;
  21851. }
  21852. default: z[j++] = '%'; break;
  21853. }
  21854. }
  21855. }
  21856. z[j] = 0;
  21857. sqlite3_result_text(context, z, -1,
  21858. z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
  21859. }
  21860. /*
  21861. ** current_time()
  21862. **
  21863. ** This function returns the same value as time('now').
  21864. */
  21865. static void ctimeFunc(
  21866. sqlite3_context *context,
  21867. int NotUsed,
  21868. sqlite3_value **NotUsed2
  21869. ){
  21870. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  21871. timeFunc(context, 0, 0);
  21872. }
  21873. /*
  21874. ** current_date()
  21875. **
  21876. ** This function returns the same value as date('now').
  21877. */
  21878. static void cdateFunc(
  21879. sqlite3_context *context,
  21880. int NotUsed,
  21881. sqlite3_value **NotUsed2
  21882. ){
  21883. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  21884. dateFunc(context, 0, 0);
  21885. }
  21886. /*
  21887. ** current_timestamp()
  21888. **
  21889. ** This function returns the same value as datetime('now').
  21890. */
  21891. static void ctimestampFunc(
  21892. sqlite3_context *context,
  21893. int NotUsed,
  21894. sqlite3_value **NotUsed2
  21895. ){
  21896. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  21897. datetimeFunc(context, 0, 0);
  21898. }
  21899. #endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
  21900. #ifdef SQLITE_OMIT_DATETIME_FUNCS
  21901. /*
  21902. ** If the library is compiled to omit the full-scale date and time
  21903. ** handling (to get a smaller binary), the following minimal version
  21904. ** of the functions current_time(), current_date() and current_timestamp()
  21905. ** are included instead. This is to support column declarations that
  21906. ** include "DEFAULT CURRENT_TIME" etc.
  21907. **
  21908. ** This function uses the C-library functions time(), gmtime()
  21909. ** and strftime(). The format string to pass to strftime() is supplied
  21910. ** as the user-data for the function.
  21911. */
  21912. static void currentTimeFunc(
  21913. sqlite3_context *context,
  21914. int argc,
  21915. sqlite3_value **argv
  21916. ){
  21917. time_t t;
  21918. char *zFormat = (char *)sqlite3_user_data(context);
  21919. sqlite3_int64 iT;
  21920. struct tm *pTm;
  21921. struct tm sNow;
  21922. char zBuf[20];
  21923. UNUSED_PARAMETER(argc);
  21924. UNUSED_PARAMETER(argv);
  21925. iT = sqlite3StmtCurrentTime(context);
  21926. if( iT<=0 ) return;
  21927. t = iT/1000 - 10000*(sqlite3_int64)21086676;
  21928. #if HAVE_GMTIME_R
  21929. pTm = gmtime_r(&t, &sNow);
  21930. #else
  21931. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  21932. pTm = gmtime(&t);
  21933. if( pTm ) memcpy(&sNow, pTm, sizeof(sNow));
  21934. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  21935. #endif
  21936. if( pTm ){
  21937. strftime(zBuf, 20, zFormat, &sNow);
  21938. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  21939. }
  21940. }
  21941. #endif
  21942. /*
  21943. ** This function registered all of the above C functions as SQL
  21944. ** functions. This should be the only routine in this file with
  21945. ** external linkage.
  21946. */
  21947. SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){
  21948. static FuncDef aDateTimeFuncs[] = {
  21949. #ifndef SQLITE_OMIT_DATETIME_FUNCS
  21950. PURE_DATE(julianday, -1, 0, 0, juliandayFunc ),
  21951. PURE_DATE(date, -1, 0, 0, dateFunc ),
  21952. PURE_DATE(time, -1, 0, 0, timeFunc ),
  21953. PURE_DATE(datetime, -1, 0, 0, datetimeFunc ),
  21954. PURE_DATE(strftime, -1, 0, 0, strftimeFunc ),
  21955. DFUNCTION(current_time, 0, 0, 0, ctimeFunc ),
  21956. DFUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
  21957. DFUNCTION(current_date, 0, 0, 0, cdateFunc ),
  21958. #else
  21959. STR_FUNCTION(current_time, 0, "%H:%M:%S", 0, currentTimeFunc),
  21960. STR_FUNCTION(current_date, 0, "%Y-%m-%d", 0, currentTimeFunc),
  21961. STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
  21962. #endif
  21963. };
  21964. sqlite3InsertBuiltinFuncs(aDateTimeFuncs, ArraySize(aDateTimeFuncs));
  21965. }
  21966. /************** End of date.c ************************************************/
  21967. /************** Begin file os.c **********************************************/
  21968. /*
  21969. ** 2005 November 29
  21970. **
  21971. ** The author disclaims copyright to this source code. In place of
  21972. ** a legal notice, here is a blessing:
  21973. **
  21974. ** May you do good and not evil.
  21975. ** May you find forgiveness for yourself and forgive others.
  21976. ** May you share freely, never taking more than you give.
  21977. **
  21978. ******************************************************************************
  21979. **
  21980. ** This file contains OS interface code that is common to all
  21981. ** architectures.
  21982. */
  21983. /* #include "sqliteInt.h" */
  21984. /*
  21985. ** If we compile with the SQLITE_TEST macro set, then the following block
  21986. ** of code will give us the ability to simulate a disk I/O error. This
  21987. ** is used for testing the I/O recovery logic.
  21988. */
  21989. #if defined(SQLITE_TEST)
  21990. SQLITE_API int sqlite3_io_error_hit = 0; /* Total number of I/O Errors */
  21991. SQLITE_API int sqlite3_io_error_hardhit = 0; /* Number of non-benign errors */
  21992. SQLITE_API int sqlite3_io_error_pending = 0; /* Count down to first I/O error */
  21993. SQLITE_API int sqlite3_io_error_persist = 0; /* True if I/O errors persist */
  21994. SQLITE_API int sqlite3_io_error_benign = 0; /* True if errors are benign */
  21995. SQLITE_API int sqlite3_diskfull_pending = 0;
  21996. SQLITE_API int sqlite3_diskfull = 0;
  21997. #endif /* defined(SQLITE_TEST) */
  21998. /*
  21999. ** When testing, also keep a count of the number of open files.
  22000. */
  22001. #if defined(SQLITE_TEST)
  22002. SQLITE_API int sqlite3_open_file_count = 0;
  22003. #endif /* defined(SQLITE_TEST) */
  22004. /*
  22005. ** The default SQLite sqlite3_vfs implementations do not allocate
  22006. ** memory (actually, os_unix.c allocates a small amount of memory
  22007. ** from within OsOpen()), but some third-party implementations may.
  22008. ** So we test the effects of a malloc() failing and the sqlite3OsXXX()
  22009. ** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
  22010. **
  22011. ** The following functions are instrumented for malloc() failure
  22012. ** testing:
  22013. **
  22014. ** sqlite3OsRead()
  22015. ** sqlite3OsWrite()
  22016. ** sqlite3OsSync()
  22017. ** sqlite3OsFileSize()
  22018. ** sqlite3OsLock()
  22019. ** sqlite3OsCheckReservedLock()
  22020. ** sqlite3OsFileControl()
  22021. ** sqlite3OsShmMap()
  22022. ** sqlite3OsOpen()
  22023. ** sqlite3OsDelete()
  22024. ** sqlite3OsAccess()
  22025. ** sqlite3OsFullPathname()
  22026. **
  22027. */
  22028. #if defined(SQLITE_TEST)
  22029. SQLITE_API int sqlite3_memdebug_vfs_oom_test = 1;
  22030. #define DO_OS_MALLOC_TEST(x) \
  22031. if (sqlite3_memdebug_vfs_oom_test && (!x || !sqlite3JournalIsInMemory(x))) { \
  22032. void *pTstAlloc = sqlite3Malloc(10); \
  22033. if (!pTstAlloc) return SQLITE_IOERR_NOMEM_BKPT; \
  22034. sqlite3_free(pTstAlloc); \
  22035. }
  22036. #else
  22037. #define DO_OS_MALLOC_TEST(x)
  22038. #endif
  22039. /*
  22040. ** The following routines are convenience wrappers around methods
  22041. ** of the sqlite3_file object. This is mostly just syntactic sugar. All
  22042. ** of this would be completely automatic if SQLite were coded using
  22043. ** C++ instead of plain old C.
  22044. */
  22045. SQLITE_PRIVATE void sqlite3OsClose(sqlite3_file *pId){
  22046. if( pId->pMethods ){
  22047. pId->pMethods->xClose(pId);
  22048. pId->pMethods = 0;
  22049. }
  22050. }
  22051. SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
  22052. DO_OS_MALLOC_TEST(id);
  22053. return id->pMethods->xRead(id, pBuf, amt, offset);
  22054. }
  22055. SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
  22056. DO_OS_MALLOC_TEST(id);
  22057. return id->pMethods->xWrite(id, pBuf, amt, offset);
  22058. }
  22059. SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
  22060. return id->pMethods->xTruncate(id, size);
  22061. }
  22062. SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
  22063. DO_OS_MALLOC_TEST(id);
  22064. return flags ? id->pMethods->xSync(id, flags) : SQLITE_OK;
  22065. }
  22066. SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
  22067. DO_OS_MALLOC_TEST(id);
  22068. return id->pMethods->xFileSize(id, pSize);
  22069. }
  22070. SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
  22071. DO_OS_MALLOC_TEST(id);
  22072. return id->pMethods->xLock(id, lockType);
  22073. }
  22074. SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
  22075. return id->pMethods->xUnlock(id, lockType);
  22076. }
  22077. SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
  22078. DO_OS_MALLOC_TEST(id);
  22079. return id->pMethods->xCheckReservedLock(id, pResOut);
  22080. }
  22081. /*
  22082. ** Use sqlite3OsFileControl() when we are doing something that might fail
  22083. ** and we need to know about the failures. Use sqlite3OsFileControlHint()
  22084. ** when simply tossing information over the wall to the VFS and we do not
  22085. ** really care if the VFS receives and understands the information since it
  22086. ** is only a hint and can be safely ignored. The sqlite3OsFileControlHint()
  22087. ** routine has no return value since the return value would be meaningless.
  22088. */
  22089. SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
  22090. if( id->pMethods==0 ) return SQLITE_NOTFOUND;
  22091. #ifdef SQLITE_TEST
  22092. if( op!=SQLITE_FCNTL_COMMIT_PHASETWO
  22093. && op!=SQLITE_FCNTL_LOCK_TIMEOUT
  22094. ){
  22095. /* Faults are not injected into COMMIT_PHASETWO because, assuming SQLite
  22096. ** is using a regular VFS, it is called after the corresponding
  22097. ** transaction has been committed. Injecting a fault at this point
  22098. ** confuses the test scripts - the COMMIT comand returns SQLITE_NOMEM
  22099. ** but the transaction is committed anyway.
  22100. **
  22101. ** The core must call OsFileControl() though, not OsFileControlHint(),
  22102. ** as if a custom VFS (e.g. zipvfs) returns an error here, it probably
  22103. ** means the commit really has failed and an error should be returned
  22104. ** to the user. */
  22105. DO_OS_MALLOC_TEST(id);
  22106. }
  22107. #endif
  22108. return id->pMethods->xFileControl(id, op, pArg);
  22109. }
  22110. SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file *id, int op, void *pArg){
  22111. if( id->pMethods ) (void)id->pMethods->xFileControl(id, op, pArg);
  22112. }
  22113. SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
  22114. int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
  22115. return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
  22116. }
  22117. SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
  22118. return id->pMethods->xDeviceCharacteristics(id);
  22119. }
  22120. #ifndef SQLITE_OMIT_WAL
  22121. SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int offset, int n, int flags){
  22122. return id->pMethods->xShmLock(id, offset, n, flags);
  22123. }
  22124. SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id){
  22125. id->pMethods->xShmBarrier(id);
  22126. }
  22127. SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int deleteFlag){
  22128. return id->pMethods->xShmUnmap(id, deleteFlag);
  22129. }
  22130. SQLITE_PRIVATE int sqlite3OsShmMap(
  22131. sqlite3_file *id, /* Database file handle */
  22132. int iPage,
  22133. int pgsz,
  22134. int bExtend, /* True to extend file if necessary */
  22135. void volatile **pp /* OUT: Pointer to mapping */
  22136. ){
  22137. DO_OS_MALLOC_TEST(id);
  22138. return id->pMethods->xShmMap(id, iPage, pgsz, bExtend, pp);
  22139. }
  22140. #endif /* SQLITE_OMIT_WAL */
  22141. #if SQLITE_MAX_MMAP_SIZE>0
  22142. /* The real implementation of xFetch and xUnfetch */
  22143. SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
  22144. DO_OS_MALLOC_TEST(id);
  22145. return id->pMethods->xFetch(id, iOff, iAmt, pp);
  22146. }
  22147. SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
  22148. return id->pMethods->xUnfetch(id, iOff, p);
  22149. }
  22150. #else
  22151. /* No-op stubs to use when memory-mapped I/O is disabled */
  22152. SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
  22153. *pp = 0;
  22154. return SQLITE_OK;
  22155. }
  22156. SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
  22157. return SQLITE_OK;
  22158. }
  22159. #endif
  22160. /*
  22161. ** The next group of routines are convenience wrappers around the
  22162. ** VFS methods.
  22163. */
  22164. SQLITE_PRIVATE int sqlite3OsOpen(
  22165. sqlite3_vfs *pVfs,
  22166. const char *zPath,
  22167. sqlite3_file *pFile,
  22168. int flags,
  22169. int *pFlagsOut
  22170. ){
  22171. int rc;
  22172. DO_OS_MALLOC_TEST(0);
  22173. /* 0x87f7f is a mask of SQLITE_OPEN_ flags that are valid to be passed
  22174. ** down into the VFS layer. Some SQLITE_OPEN_ flags (for example,
  22175. ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before
  22176. ** reaching the VFS. */
  22177. rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x1087f7f, pFlagsOut);
  22178. assert( rc==SQLITE_OK || pFile->pMethods==0 );
  22179. return rc;
  22180. }
  22181. SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
  22182. DO_OS_MALLOC_TEST(0);
  22183. assert( dirSync==0 || dirSync==1 );
  22184. return pVfs->xDelete(pVfs, zPath, dirSync);
  22185. }
  22186. SQLITE_PRIVATE int sqlite3OsAccess(
  22187. sqlite3_vfs *pVfs,
  22188. const char *zPath,
  22189. int flags,
  22190. int *pResOut
  22191. ){
  22192. DO_OS_MALLOC_TEST(0);
  22193. return pVfs->xAccess(pVfs, zPath, flags, pResOut);
  22194. }
  22195. SQLITE_PRIVATE int sqlite3OsFullPathname(
  22196. sqlite3_vfs *pVfs,
  22197. const char *zPath,
  22198. int nPathOut,
  22199. char *zPathOut
  22200. ){
  22201. DO_OS_MALLOC_TEST(0);
  22202. zPathOut[0] = 0;
  22203. return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
  22204. }
  22205. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  22206. SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
  22207. return pVfs->xDlOpen(pVfs, zPath);
  22208. }
  22209. SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
  22210. pVfs->xDlError(pVfs, nByte, zBufOut);
  22211. }
  22212. SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){
  22213. return pVfs->xDlSym(pVfs, pHdle, zSym);
  22214. }
  22215. SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
  22216. pVfs->xDlClose(pVfs, pHandle);
  22217. }
  22218. #endif /* SQLITE_OMIT_LOAD_EXTENSION */
  22219. SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
  22220. if( sqlite3Config.iPrngSeed ){
  22221. memset(zBufOut, 0, nByte);
  22222. if( ALWAYS(nByte>(signed)sizeof(unsigned)) ) nByte = sizeof(unsigned int);
  22223. memcpy(zBufOut, &sqlite3Config.iPrngSeed, nByte);
  22224. return SQLITE_OK;
  22225. }else{
  22226. return pVfs->xRandomness(pVfs, nByte, zBufOut);
  22227. }
  22228. }
  22229. SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
  22230. return pVfs->xSleep(pVfs, nMicro);
  22231. }
  22232. SQLITE_PRIVATE int sqlite3OsGetLastError(sqlite3_vfs *pVfs){
  22233. return pVfs->xGetLastError ? pVfs->xGetLastError(pVfs, 0, 0) : 0;
  22234. }
  22235. SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){
  22236. int rc;
  22237. /* IMPLEMENTATION-OF: R-49045-42493 SQLite will use the xCurrentTimeInt64()
  22238. ** method to get the current date and time if that method is available
  22239. ** (if iVersion is 2 or greater and the function pointer is not NULL) and
  22240. ** will fall back to xCurrentTime() if xCurrentTimeInt64() is
  22241. ** unavailable.
  22242. */
  22243. if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
  22244. rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut);
  22245. }else{
  22246. double r;
  22247. rc = pVfs->xCurrentTime(pVfs, &r);
  22248. *pTimeOut = (sqlite3_int64)(r*86400000.0);
  22249. }
  22250. return rc;
  22251. }
  22252. SQLITE_PRIVATE int sqlite3OsOpenMalloc(
  22253. sqlite3_vfs *pVfs,
  22254. const char *zFile,
  22255. sqlite3_file **ppFile,
  22256. int flags,
  22257. int *pOutFlags
  22258. ){
  22259. int rc;
  22260. sqlite3_file *pFile;
  22261. pFile = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile);
  22262. if( pFile ){
  22263. rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
  22264. if( rc!=SQLITE_OK ){
  22265. sqlite3_free(pFile);
  22266. }else{
  22267. *ppFile = pFile;
  22268. }
  22269. }else{
  22270. rc = SQLITE_NOMEM_BKPT;
  22271. }
  22272. return rc;
  22273. }
  22274. SQLITE_PRIVATE void sqlite3OsCloseFree(sqlite3_file *pFile){
  22275. assert( pFile );
  22276. sqlite3OsClose(pFile);
  22277. sqlite3_free(pFile);
  22278. }
  22279. /*
  22280. ** This function is a wrapper around the OS specific implementation of
  22281. ** sqlite3_os_init(). The purpose of the wrapper is to provide the
  22282. ** ability to simulate a malloc failure, so that the handling of an
  22283. ** error in sqlite3_os_init() by the upper layers can be tested.
  22284. */
  22285. SQLITE_PRIVATE int sqlite3OsInit(void){
  22286. void *p = sqlite3_malloc(10);
  22287. if( p==0 ) return SQLITE_NOMEM_BKPT;
  22288. sqlite3_free(p);
  22289. return sqlite3_os_init();
  22290. }
  22291. /*
  22292. ** The list of all registered VFS implementations.
  22293. */
  22294. static sqlite3_vfs * SQLITE_WSD vfsList = 0;
  22295. #define vfsList GLOBAL(sqlite3_vfs *, vfsList)
  22296. /*
  22297. ** Locate a VFS by name. If no name is given, simply return the
  22298. ** first VFS on the list.
  22299. */
  22300. SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){
  22301. sqlite3_vfs *pVfs = 0;
  22302. #if SQLITE_THREADSAFE
  22303. sqlite3_mutex *mutex;
  22304. #endif
  22305. #ifndef SQLITE_OMIT_AUTOINIT
  22306. int rc = sqlite3_initialize();
  22307. if( rc ) return 0;
  22308. #endif
  22309. #if SQLITE_THREADSAFE
  22310. mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  22311. #endif
  22312. sqlite3_mutex_enter(mutex);
  22313. for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
  22314. if( zVfs==0 ) break;
  22315. if( strcmp(zVfs, pVfs->zName)==0 ) break;
  22316. }
  22317. sqlite3_mutex_leave(mutex);
  22318. return pVfs;
  22319. }
  22320. /*
  22321. ** Unlink a VFS from the linked list
  22322. */
  22323. static void vfsUnlink(sqlite3_vfs *pVfs){
  22324. assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) );
  22325. if( pVfs==0 ){
  22326. /* No-op */
  22327. }else if( vfsList==pVfs ){
  22328. vfsList = pVfs->pNext;
  22329. }else if( vfsList ){
  22330. sqlite3_vfs *p = vfsList;
  22331. while( p->pNext && p->pNext!=pVfs ){
  22332. p = p->pNext;
  22333. }
  22334. if( p->pNext==pVfs ){
  22335. p->pNext = pVfs->pNext;
  22336. }
  22337. }
  22338. }
  22339. /*
  22340. ** Register a VFS with the system. It is harmless to register the same
  22341. ** VFS multiple times. The new VFS becomes the default if makeDflt is
  22342. ** true.
  22343. */
  22344. SQLITE_API int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
  22345. MUTEX_LOGIC(sqlite3_mutex *mutex;)
  22346. #ifndef SQLITE_OMIT_AUTOINIT
  22347. int rc = sqlite3_initialize();
  22348. if( rc ) return rc;
  22349. #endif
  22350. #ifdef SQLITE_ENABLE_API_ARMOR
  22351. if( pVfs==0 ) return SQLITE_MISUSE_BKPT;
  22352. #endif
  22353. MUTEX_LOGIC( mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
  22354. sqlite3_mutex_enter(mutex);
  22355. vfsUnlink(pVfs);
  22356. if( makeDflt || vfsList==0 ){
  22357. pVfs->pNext = vfsList;
  22358. vfsList = pVfs;
  22359. }else{
  22360. pVfs->pNext = vfsList->pNext;
  22361. vfsList->pNext = pVfs;
  22362. }
  22363. assert(vfsList);
  22364. sqlite3_mutex_leave(mutex);
  22365. return SQLITE_OK;
  22366. }
  22367. /*
  22368. ** Unregister a VFS so that it is no longer accessible.
  22369. */
  22370. SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
  22371. MUTEX_LOGIC(sqlite3_mutex *mutex;)
  22372. #ifndef SQLITE_OMIT_AUTOINIT
  22373. int rc = sqlite3_initialize();
  22374. if( rc ) return rc;
  22375. #endif
  22376. MUTEX_LOGIC( mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
  22377. sqlite3_mutex_enter(mutex);
  22378. vfsUnlink(pVfs);
  22379. sqlite3_mutex_leave(mutex);
  22380. return SQLITE_OK;
  22381. }
  22382. /************** End of os.c **************************************************/
  22383. /************** Begin file fault.c *******************************************/
  22384. /*
  22385. ** 2008 Jan 22
  22386. **
  22387. ** The author disclaims copyright to this source code. In place of
  22388. ** a legal notice, here is a blessing:
  22389. **
  22390. ** May you do good and not evil.
  22391. ** May you find forgiveness for yourself and forgive others.
  22392. ** May you share freely, never taking more than you give.
  22393. **
  22394. *************************************************************************
  22395. **
  22396. ** This file contains code to support the concept of "benign"
  22397. ** malloc failures (when the xMalloc() or xRealloc() method of the
  22398. ** sqlite3_mem_methods structure fails to allocate a block of memory
  22399. ** and returns 0).
  22400. **
  22401. ** Most malloc failures are non-benign. After they occur, SQLite
  22402. ** abandons the current operation and returns an error code (usually
  22403. ** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
  22404. ** fatal. For example, if a malloc fails while resizing a hash table, this
  22405. ** is completely recoverable simply by not carrying out the resize. The
  22406. ** hash table will continue to function normally. So a malloc failure
  22407. ** during a hash table resize is a benign fault.
  22408. */
  22409. /* #include "sqliteInt.h" */
  22410. #ifndef SQLITE_UNTESTABLE
  22411. /*
  22412. ** Global variables.
  22413. */
  22414. typedef struct BenignMallocHooks BenignMallocHooks;
  22415. static SQLITE_WSD struct BenignMallocHooks {
  22416. void (*xBenignBegin)(void);
  22417. void (*xBenignEnd)(void);
  22418. } sqlite3Hooks = { 0, 0 };
  22419. /* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
  22420. ** structure. If writable static data is unsupported on the target,
  22421. ** we have to locate the state vector at run-time. In the more common
  22422. ** case where writable static data is supported, wsdHooks can refer directly
  22423. ** to the "sqlite3Hooks" state vector declared above.
  22424. */
  22425. #ifdef SQLITE_OMIT_WSD
  22426. # define wsdHooksInit \
  22427. BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)
  22428. # define wsdHooks x[0]
  22429. #else
  22430. # define wsdHooksInit
  22431. # define wsdHooks sqlite3Hooks
  22432. #endif
  22433. /*
  22434. ** Register hooks to call when sqlite3BeginBenignMalloc() and
  22435. ** sqlite3EndBenignMalloc() are called, respectively.
  22436. */
  22437. SQLITE_PRIVATE void sqlite3BenignMallocHooks(
  22438. void (*xBenignBegin)(void),
  22439. void (*xBenignEnd)(void)
  22440. ){
  22441. wsdHooksInit;
  22442. wsdHooks.xBenignBegin = xBenignBegin;
  22443. wsdHooks.xBenignEnd = xBenignEnd;
  22444. }
  22445. /*
  22446. ** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that
  22447. ** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()
  22448. ** indicates that subsequent malloc failures are non-benign.
  22449. */
  22450. SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){
  22451. wsdHooksInit;
  22452. if( wsdHooks.xBenignBegin ){
  22453. wsdHooks.xBenignBegin();
  22454. }
  22455. }
  22456. SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){
  22457. wsdHooksInit;
  22458. if( wsdHooks.xBenignEnd ){
  22459. wsdHooks.xBenignEnd();
  22460. }
  22461. }
  22462. #endif /* #ifndef SQLITE_UNTESTABLE */
  22463. /************** End of fault.c ***********************************************/
  22464. /************** Begin file mem0.c ********************************************/
  22465. /*
  22466. ** 2008 October 28
  22467. **
  22468. ** The author disclaims copyright to this source code. In place of
  22469. ** a legal notice, here is a blessing:
  22470. **
  22471. ** May you do good and not evil.
  22472. ** May you find forgiveness for yourself and forgive others.
  22473. ** May you share freely, never taking more than you give.
  22474. **
  22475. *************************************************************************
  22476. **
  22477. ** This file contains a no-op memory allocation drivers for use when
  22478. ** SQLITE_ZERO_MALLOC is defined. The allocation drivers implemented
  22479. ** here always fail. SQLite will not operate with these drivers. These
  22480. ** are merely placeholders. Real drivers must be substituted using
  22481. ** sqlite3_config() before SQLite will operate.
  22482. */
  22483. /* #include "sqliteInt.h" */
  22484. /*
  22485. ** This version of the memory allocator is the default. It is
  22486. ** used when no other memory allocator is specified using compile-time
  22487. ** macros.
  22488. */
  22489. #ifdef SQLITE_ZERO_MALLOC
  22490. /*
  22491. ** No-op versions of all memory allocation routines
  22492. */
  22493. static void *sqlite3MemMalloc(int nByte){ return 0; }
  22494. static void sqlite3MemFree(void *pPrior){ return; }
  22495. static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; }
  22496. static int sqlite3MemSize(void *pPrior){ return 0; }
  22497. static int sqlite3MemRoundup(int n){ return n; }
  22498. static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; }
  22499. static void sqlite3MemShutdown(void *NotUsed){ return; }
  22500. /*
  22501. ** This routine is the only routine in this file with external linkage.
  22502. **
  22503. ** Populate the low-level memory allocation function pointers in
  22504. ** sqlite3GlobalConfig.m with pointers to the routines in this file.
  22505. */
  22506. SQLITE_PRIVATE void sqlite3MemSetDefault(void){
  22507. static const sqlite3_mem_methods defaultMethods = {
  22508. sqlite3MemMalloc,
  22509. sqlite3MemFree,
  22510. sqlite3MemRealloc,
  22511. sqlite3MemSize,
  22512. sqlite3MemRoundup,
  22513. sqlite3MemInit,
  22514. sqlite3MemShutdown,
  22515. 0
  22516. };
  22517. sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
  22518. }
  22519. #endif /* SQLITE_ZERO_MALLOC */
  22520. /************** End of mem0.c ************************************************/
  22521. /************** Begin file mem1.c ********************************************/
  22522. /*
  22523. ** 2007 August 14
  22524. **
  22525. ** The author disclaims copyright to this source code. In place of
  22526. ** a legal notice, here is a blessing:
  22527. **
  22528. ** May you do good and not evil.
  22529. ** May you find forgiveness for yourself and forgive others.
  22530. ** May you share freely, never taking more than you give.
  22531. **
  22532. *************************************************************************
  22533. **
  22534. ** This file contains low-level memory allocation drivers for when
  22535. ** SQLite will use the standard C-library malloc/realloc/free interface
  22536. ** to obtain the memory it needs.
  22537. **
  22538. ** This file contains implementations of the low-level memory allocation
  22539. ** routines specified in the sqlite3_mem_methods object. The content of
  22540. ** this file is only used if SQLITE_SYSTEM_MALLOC is defined. The
  22541. ** SQLITE_SYSTEM_MALLOC macro is defined automatically if neither the
  22542. ** SQLITE_MEMDEBUG nor the SQLITE_WIN32_MALLOC macros are defined. The
  22543. ** default configuration is to use memory allocation routines in this
  22544. ** file.
  22545. **
  22546. ** C-preprocessor macro summary:
  22547. **
  22548. ** HAVE_MALLOC_USABLE_SIZE The configure script sets this symbol if
  22549. ** the malloc_usable_size() interface exists
  22550. ** on the target platform. Or, this symbol
  22551. ** can be set manually, if desired.
  22552. ** If an equivalent interface exists by
  22553. ** a different name, using a separate -D
  22554. ** option to rename it.
  22555. **
  22556. ** SQLITE_WITHOUT_ZONEMALLOC Some older macs lack support for the zone
  22557. ** memory allocator. Set this symbol to enable
  22558. ** building on older macs.
  22559. **
  22560. ** SQLITE_WITHOUT_MSIZE Set this symbol to disable the use of
  22561. ** _msize() on windows systems. This might
  22562. ** be necessary when compiling for Delphi,
  22563. ** for example.
  22564. */
  22565. /* #include "sqliteInt.h" */
  22566. /*
  22567. ** This version of the memory allocator is the default. It is
  22568. ** used when no other memory allocator is specified using compile-time
  22569. ** macros.
  22570. */
  22571. #ifdef SQLITE_SYSTEM_MALLOC
  22572. #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
  22573. /*
  22574. ** Use the zone allocator available on apple products unless the
  22575. ** SQLITE_WITHOUT_ZONEMALLOC symbol is defined.
  22576. */
  22577. #include <sys/sysctl.h>
  22578. #include <malloc/malloc.h>
  22579. #ifdef SQLITE_MIGHT_BE_SINGLE_CORE
  22580. #include <libkern/OSAtomic.h>
  22581. #endif /* SQLITE_MIGHT_BE_SINGLE_CORE */
  22582. static malloc_zone_t* _sqliteZone_;
  22583. #define SQLITE_MALLOC(x) malloc_zone_malloc(_sqliteZone_, (x))
  22584. #define SQLITE_FREE(x) malloc_zone_free(_sqliteZone_, (x));
  22585. #define SQLITE_REALLOC(x,y) malloc_zone_realloc(_sqliteZone_, (x), (y))
  22586. #define SQLITE_MALLOCSIZE(x) \
  22587. (_sqliteZone_ ? _sqliteZone_->size(_sqliteZone_,x) : malloc_size(x))
  22588. #else /* if not __APPLE__ */
  22589. /*
  22590. ** Use standard C library malloc and free on non-Apple systems.
  22591. ** Also used by Apple systems if SQLITE_WITHOUT_ZONEMALLOC is defined.
  22592. */
  22593. #define SQLITE_MALLOC(x) malloc(x)
  22594. #define SQLITE_FREE(x) free(x)
  22595. #define SQLITE_REALLOC(x,y) realloc((x),(y))
  22596. /*
  22597. ** The malloc.h header file is needed for malloc_usable_size() function
  22598. ** on some systems (e.g. Linux).
  22599. */
  22600. #if HAVE_MALLOC_H && HAVE_MALLOC_USABLE_SIZE
  22601. # define SQLITE_USE_MALLOC_H 1
  22602. # define SQLITE_USE_MALLOC_USABLE_SIZE 1
  22603. /*
  22604. ** The MSVCRT has malloc_usable_size(), but it is called _msize(). The
  22605. ** use of _msize() is automatic, but can be disabled by compiling with
  22606. ** -DSQLITE_WITHOUT_MSIZE. Using the _msize() function also requires
  22607. ** the malloc.h header file.
  22608. */
  22609. #elif defined(_MSC_VER) && !defined(SQLITE_WITHOUT_MSIZE)
  22610. # define SQLITE_USE_MALLOC_H
  22611. # define SQLITE_USE_MSIZE
  22612. #endif
  22613. /*
  22614. ** Include the malloc.h header file, if necessary. Also set define macro
  22615. ** SQLITE_MALLOCSIZE to the appropriate function name, which is _msize()
  22616. ** for MSVC and malloc_usable_size() for most other systems (e.g. Linux).
  22617. ** The memory size function can always be overridden manually by defining
  22618. ** the macro SQLITE_MALLOCSIZE to the desired function name.
  22619. */
  22620. #if defined(SQLITE_USE_MALLOC_H)
  22621. # include <malloc.h>
  22622. # if defined(SQLITE_USE_MALLOC_USABLE_SIZE)
  22623. # if !defined(SQLITE_MALLOCSIZE)
  22624. # define SQLITE_MALLOCSIZE(x) malloc_usable_size(x)
  22625. # endif
  22626. # elif defined(SQLITE_USE_MSIZE)
  22627. # if !defined(SQLITE_MALLOCSIZE)
  22628. # define SQLITE_MALLOCSIZE _msize
  22629. # endif
  22630. # endif
  22631. #endif /* defined(SQLITE_USE_MALLOC_H) */
  22632. #endif /* __APPLE__ or not __APPLE__ */
  22633. /*
  22634. ** Like malloc(), but remember the size of the allocation
  22635. ** so that we can find it later using sqlite3MemSize().
  22636. **
  22637. ** For this low-level routine, we are guaranteed that nByte>0 because
  22638. ** cases of nByte<=0 will be intercepted and dealt with by higher level
  22639. ** routines.
  22640. */
  22641. static void *sqlite3MemMalloc(int nByte){
  22642. #ifdef SQLITE_MALLOCSIZE
  22643. void *p;
  22644. testcase( ROUND8(nByte)==nByte );
  22645. p = SQLITE_MALLOC( nByte );
  22646. if( p==0 ){
  22647. testcase( sqlite3GlobalConfig.xLog!=0 );
  22648. sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
  22649. }
  22650. return p;
  22651. #else
  22652. sqlite3_int64 *p;
  22653. assert( nByte>0 );
  22654. testcase( ROUND8(nByte)!=nByte );
  22655. p = SQLITE_MALLOC( nByte+8 );
  22656. if( p ){
  22657. p[0] = nByte;
  22658. p++;
  22659. }else{
  22660. testcase( sqlite3GlobalConfig.xLog!=0 );
  22661. sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
  22662. }
  22663. return (void *)p;
  22664. #endif
  22665. }
  22666. /*
  22667. ** Like free() but works for allocations obtained from sqlite3MemMalloc()
  22668. ** or sqlite3MemRealloc().
  22669. **
  22670. ** For this low-level routine, we already know that pPrior!=0 since
  22671. ** cases where pPrior==0 will have been intecepted and dealt with
  22672. ** by higher-level routines.
  22673. */
  22674. static void sqlite3MemFree(void *pPrior){
  22675. #ifdef SQLITE_MALLOCSIZE
  22676. SQLITE_FREE(pPrior);
  22677. #else
  22678. sqlite3_int64 *p = (sqlite3_int64*)pPrior;
  22679. assert( pPrior!=0 );
  22680. p--;
  22681. SQLITE_FREE(p);
  22682. #endif
  22683. }
  22684. /*
  22685. ** Report the allocated size of a prior return from xMalloc()
  22686. ** or xRealloc().
  22687. */
  22688. static int sqlite3MemSize(void *pPrior){
  22689. #ifdef SQLITE_MALLOCSIZE
  22690. assert( pPrior!=0 );
  22691. return (int)SQLITE_MALLOCSIZE(pPrior);
  22692. #else
  22693. sqlite3_int64 *p;
  22694. assert( pPrior!=0 );
  22695. p = (sqlite3_int64*)pPrior;
  22696. p--;
  22697. return (int)p[0];
  22698. #endif
  22699. }
  22700. /*
  22701. ** Like realloc(). Resize an allocation previously obtained from
  22702. ** sqlite3MemMalloc().
  22703. **
  22704. ** For this low-level interface, we know that pPrior!=0. Cases where
  22705. ** pPrior==0 while have been intercepted by higher-level routine and
  22706. ** redirected to xMalloc. Similarly, we know that nByte>0 because
  22707. ** cases where nByte<=0 will have been intercepted by higher-level
  22708. ** routines and redirected to xFree.
  22709. */
  22710. static void *sqlite3MemRealloc(void *pPrior, int nByte){
  22711. #ifdef SQLITE_MALLOCSIZE
  22712. void *p = SQLITE_REALLOC(pPrior, nByte);
  22713. if( p==0 ){
  22714. testcase( sqlite3GlobalConfig.xLog!=0 );
  22715. sqlite3_log(SQLITE_NOMEM,
  22716. "failed memory resize %u to %u bytes",
  22717. SQLITE_MALLOCSIZE(pPrior), nByte);
  22718. }
  22719. return p;
  22720. #else
  22721. sqlite3_int64 *p = (sqlite3_int64*)pPrior;
  22722. assert( pPrior!=0 && nByte>0 );
  22723. assert( nByte==ROUND8(nByte) ); /* EV: R-46199-30249 */
  22724. p--;
  22725. p = SQLITE_REALLOC(p, nByte+8 );
  22726. if( p ){
  22727. p[0] = nByte;
  22728. p++;
  22729. }else{
  22730. testcase( sqlite3GlobalConfig.xLog!=0 );
  22731. sqlite3_log(SQLITE_NOMEM,
  22732. "failed memory resize %u to %u bytes",
  22733. sqlite3MemSize(pPrior), nByte);
  22734. }
  22735. return (void*)p;
  22736. #endif
  22737. }
  22738. /*
  22739. ** Round up a request size to the next valid allocation size.
  22740. */
  22741. static int sqlite3MemRoundup(int n){
  22742. return ROUND8(n);
  22743. }
  22744. /*
  22745. ** Initialize this module.
  22746. */
  22747. static int sqlite3MemInit(void *NotUsed){
  22748. #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
  22749. int cpuCount;
  22750. size_t len;
  22751. if( _sqliteZone_ ){
  22752. return SQLITE_OK;
  22753. }
  22754. len = sizeof(cpuCount);
  22755. /* One usually wants to use hw.acctivecpu for MT decisions, but not here */
  22756. sysctlbyname("hw.ncpu", &cpuCount, &len, NULL, 0);
  22757. if( cpuCount>1 ){
  22758. /* defer MT decisions to system malloc */
  22759. _sqliteZone_ = malloc_default_zone();
  22760. }else{
  22761. /* only 1 core, use our own zone to contention over global locks,
  22762. ** e.g. we have our own dedicated locks */
  22763. _sqliteZone_ = malloc_create_zone(4096, 0);
  22764. malloc_set_zone_name(_sqliteZone_, "Sqlite_Heap");
  22765. }
  22766. #endif /* defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC) */
  22767. UNUSED_PARAMETER(NotUsed);
  22768. return SQLITE_OK;
  22769. }
  22770. /*
  22771. ** Deinitialize this module.
  22772. */
  22773. static void sqlite3MemShutdown(void *NotUsed){
  22774. UNUSED_PARAMETER(NotUsed);
  22775. return;
  22776. }
  22777. /*
  22778. ** This routine is the only routine in this file with external linkage.
  22779. **
  22780. ** Populate the low-level memory allocation function pointers in
  22781. ** sqlite3GlobalConfig.m with pointers to the routines in this file.
  22782. */
  22783. SQLITE_PRIVATE void sqlite3MemSetDefault(void){
  22784. static const sqlite3_mem_methods defaultMethods = {
  22785. sqlite3MemMalloc,
  22786. sqlite3MemFree,
  22787. sqlite3MemRealloc,
  22788. sqlite3MemSize,
  22789. sqlite3MemRoundup,
  22790. sqlite3MemInit,
  22791. sqlite3MemShutdown,
  22792. 0
  22793. };
  22794. sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
  22795. }
  22796. #endif /* SQLITE_SYSTEM_MALLOC */
  22797. /************** End of mem1.c ************************************************/
  22798. /************** Begin file mem2.c ********************************************/
  22799. /*
  22800. ** 2007 August 15
  22801. **
  22802. ** The author disclaims copyright to this source code. In place of
  22803. ** a legal notice, here is a blessing:
  22804. **
  22805. ** May you do good and not evil.
  22806. ** May you find forgiveness for yourself and forgive others.
  22807. ** May you share freely, never taking more than you give.
  22808. **
  22809. *************************************************************************
  22810. **
  22811. ** This file contains low-level memory allocation drivers for when
  22812. ** SQLite will use the standard C-library malloc/realloc/free interface
  22813. ** to obtain the memory it needs while adding lots of additional debugging
  22814. ** information to each allocation in order to help detect and fix memory
  22815. ** leaks and memory usage errors.
  22816. **
  22817. ** This file contains implementations of the low-level memory allocation
  22818. ** routines specified in the sqlite3_mem_methods object.
  22819. */
  22820. /* #include "sqliteInt.h" */
  22821. /*
  22822. ** This version of the memory allocator is used only if the
  22823. ** SQLITE_MEMDEBUG macro is defined
  22824. */
  22825. #ifdef SQLITE_MEMDEBUG
  22826. /*
  22827. ** The backtrace functionality is only available with GLIBC
  22828. */
  22829. #ifdef __GLIBC__
  22830. extern int backtrace(void**,int);
  22831. extern void backtrace_symbols_fd(void*const*,int,int);
  22832. #else
  22833. # define backtrace(A,B) 1
  22834. # define backtrace_symbols_fd(A,B,C)
  22835. #endif
  22836. /* #include <stdio.h> */
  22837. /*
  22838. ** Each memory allocation looks like this:
  22839. **
  22840. ** ------------------------------------------------------------------------
  22841. ** | Title | backtrace pointers | MemBlockHdr | allocation | EndGuard |
  22842. ** ------------------------------------------------------------------------
  22843. **
  22844. ** The application code sees only a pointer to the allocation. We have
  22845. ** to back up from the allocation pointer to find the MemBlockHdr. The
  22846. ** MemBlockHdr tells us the size of the allocation and the number of
  22847. ** backtrace pointers. There is also a guard word at the end of the
  22848. ** MemBlockHdr.
  22849. */
  22850. struct MemBlockHdr {
  22851. i64 iSize; /* Size of this allocation */
  22852. struct MemBlockHdr *pNext, *pPrev; /* Linked list of all unfreed memory */
  22853. char nBacktrace; /* Number of backtraces on this alloc */
  22854. char nBacktraceSlots; /* Available backtrace slots */
  22855. u8 nTitle; /* Bytes of title; includes '\0' */
  22856. u8 eType; /* Allocation type code */
  22857. int iForeGuard; /* Guard word for sanity */
  22858. };
  22859. /*
  22860. ** Guard words
  22861. */
  22862. #define FOREGUARD 0x80F5E153
  22863. #define REARGUARD 0xE4676B53
  22864. /*
  22865. ** Number of malloc size increments to track.
  22866. */
  22867. #define NCSIZE 1000
  22868. /*
  22869. ** All of the static variables used by this module are collected
  22870. ** into a single structure named "mem". This is to keep the
  22871. ** static variables organized and to reduce namespace pollution
  22872. ** when this module is combined with other in the amalgamation.
  22873. */
  22874. static struct {
  22875. /*
  22876. ** Mutex to control access to the memory allocation subsystem.
  22877. */
  22878. sqlite3_mutex *mutex;
  22879. /*
  22880. ** Head and tail of a linked list of all outstanding allocations
  22881. */
  22882. struct MemBlockHdr *pFirst;
  22883. struct MemBlockHdr *pLast;
  22884. /*
  22885. ** The number of levels of backtrace to save in new allocations.
  22886. */
  22887. int nBacktrace;
  22888. void (*xBacktrace)(int, int, void **);
  22889. /*
  22890. ** Title text to insert in front of each block
  22891. */
  22892. int nTitle; /* Bytes of zTitle to save. Includes '\0' and padding */
  22893. char zTitle[100]; /* The title text */
  22894. /*
  22895. ** sqlite3MallocDisallow() increments the following counter.
  22896. ** sqlite3MallocAllow() decrements it.
  22897. */
  22898. int disallow; /* Do not allow memory allocation */
  22899. /*
  22900. ** Gather statistics on the sizes of memory allocations.
  22901. ** nAlloc[i] is the number of allocation attempts of i*8
  22902. ** bytes. i==NCSIZE is the number of allocation attempts for
  22903. ** sizes more than NCSIZE*8 bytes.
  22904. */
  22905. int nAlloc[NCSIZE]; /* Total number of allocations */
  22906. int nCurrent[NCSIZE]; /* Current number of allocations */
  22907. int mxCurrent[NCSIZE]; /* Highwater mark for nCurrent */
  22908. } mem;
  22909. /*
  22910. ** Adjust memory usage statistics
  22911. */
  22912. static void adjustStats(int iSize, int increment){
  22913. int i = ROUND8(iSize)/8;
  22914. if( i>NCSIZE-1 ){
  22915. i = NCSIZE - 1;
  22916. }
  22917. if( increment>0 ){
  22918. mem.nAlloc[i]++;
  22919. mem.nCurrent[i]++;
  22920. if( mem.nCurrent[i]>mem.mxCurrent[i] ){
  22921. mem.mxCurrent[i] = mem.nCurrent[i];
  22922. }
  22923. }else{
  22924. mem.nCurrent[i]--;
  22925. assert( mem.nCurrent[i]>=0 );
  22926. }
  22927. }
  22928. /*
  22929. ** Given an allocation, find the MemBlockHdr for that allocation.
  22930. **
  22931. ** This routine checks the guards at either end of the allocation and
  22932. ** if they are incorrect it asserts.
  22933. */
  22934. static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
  22935. struct MemBlockHdr *p;
  22936. int *pInt;
  22937. u8 *pU8;
  22938. int nReserve;
  22939. p = (struct MemBlockHdr*)pAllocation;
  22940. p--;
  22941. assert( p->iForeGuard==(int)FOREGUARD );
  22942. nReserve = ROUND8(p->iSize);
  22943. pInt = (int*)pAllocation;
  22944. pU8 = (u8*)pAllocation;
  22945. assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD );
  22946. /* This checks any of the "extra" bytes allocated due
  22947. ** to rounding up to an 8 byte boundary to ensure
  22948. ** they haven't been overwritten.
  22949. */
  22950. while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
  22951. return p;
  22952. }
  22953. /*
  22954. ** Return the number of bytes currently allocated at address p.
  22955. */
  22956. static int sqlite3MemSize(void *p){
  22957. struct MemBlockHdr *pHdr;
  22958. if( !p ){
  22959. return 0;
  22960. }
  22961. pHdr = sqlite3MemsysGetHeader(p);
  22962. return (int)pHdr->iSize;
  22963. }
  22964. /*
  22965. ** Initialize the memory allocation subsystem.
  22966. */
  22967. static int sqlite3MemInit(void *NotUsed){
  22968. UNUSED_PARAMETER(NotUsed);
  22969. assert( (sizeof(struct MemBlockHdr)&7) == 0 );
  22970. if( !sqlite3GlobalConfig.bMemstat ){
  22971. /* If memory status is enabled, then the malloc.c wrapper will already
  22972. ** hold the STATIC_MEM mutex when the routines here are invoked. */
  22973. mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  22974. }
  22975. return SQLITE_OK;
  22976. }
  22977. /*
  22978. ** Deinitialize the memory allocation subsystem.
  22979. */
  22980. static void sqlite3MemShutdown(void *NotUsed){
  22981. UNUSED_PARAMETER(NotUsed);
  22982. mem.mutex = 0;
  22983. }
  22984. /*
  22985. ** Round up a request size to the next valid allocation size.
  22986. */
  22987. static int sqlite3MemRoundup(int n){
  22988. return ROUND8(n);
  22989. }
  22990. /*
  22991. ** Fill a buffer with pseudo-random bytes. This is used to preset
  22992. ** the content of a new memory allocation to unpredictable values and
  22993. ** to clear the content of a freed allocation to unpredictable values.
  22994. */
  22995. static void randomFill(char *pBuf, int nByte){
  22996. unsigned int x, y, r;
  22997. x = SQLITE_PTR_TO_INT(pBuf);
  22998. y = nByte | 1;
  22999. while( nByte >= 4 ){
  23000. x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);
  23001. y = y*1103515245 + 12345;
  23002. r = x ^ y;
  23003. *(int*)pBuf = r;
  23004. pBuf += 4;
  23005. nByte -= 4;
  23006. }
  23007. while( nByte-- > 0 ){
  23008. x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);
  23009. y = y*1103515245 + 12345;
  23010. r = x ^ y;
  23011. *(pBuf++) = r & 0xff;
  23012. }
  23013. }
  23014. /*
  23015. ** Allocate nByte bytes of memory.
  23016. */
  23017. static void *sqlite3MemMalloc(int nByte){
  23018. struct MemBlockHdr *pHdr;
  23019. void **pBt;
  23020. char *z;
  23021. int *pInt;
  23022. void *p = 0;
  23023. int totalSize;
  23024. int nReserve;
  23025. sqlite3_mutex_enter(mem.mutex);
  23026. assert( mem.disallow==0 );
  23027. nReserve = ROUND8(nByte);
  23028. totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
  23029. mem.nBacktrace*sizeof(void*) + mem.nTitle;
  23030. p = malloc(totalSize);
  23031. if( p ){
  23032. z = p;
  23033. pBt = (void**)&z[mem.nTitle];
  23034. pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
  23035. pHdr->pNext = 0;
  23036. pHdr->pPrev = mem.pLast;
  23037. if( mem.pLast ){
  23038. mem.pLast->pNext = pHdr;
  23039. }else{
  23040. mem.pFirst = pHdr;
  23041. }
  23042. mem.pLast = pHdr;
  23043. pHdr->iForeGuard = FOREGUARD;
  23044. pHdr->eType = MEMTYPE_HEAP;
  23045. pHdr->nBacktraceSlots = mem.nBacktrace;
  23046. pHdr->nTitle = mem.nTitle;
  23047. if( mem.nBacktrace ){
  23048. void *aAddr[40];
  23049. pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
  23050. memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
  23051. assert(pBt[0]);
  23052. if( mem.xBacktrace ){
  23053. mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
  23054. }
  23055. }else{
  23056. pHdr->nBacktrace = 0;
  23057. }
  23058. if( mem.nTitle ){
  23059. memcpy(z, mem.zTitle, mem.nTitle);
  23060. }
  23061. pHdr->iSize = nByte;
  23062. adjustStats(nByte, +1);
  23063. pInt = (int*)&pHdr[1];
  23064. pInt[nReserve/sizeof(int)] = REARGUARD;
  23065. randomFill((char*)pInt, nByte);
  23066. memset(((char*)pInt)+nByte, 0x65, nReserve-nByte);
  23067. p = (void*)pInt;
  23068. }
  23069. sqlite3_mutex_leave(mem.mutex);
  23070. return p;
  23071. }
  23072. /*
  23073. ** Free memory.
  23074. */
  23075. static void sqlite3MemFree(void *pPrior){
  23076. struct MemBlockHdr *pHdr;
  23077. void **pBt;
  23078. char *z;
  23079. assert( sqlite3GlobalConfig.bMemstat || sqlite3GlobalConfig.bCoreMutex==0
  23080. || mem.mutex!=0 );
  23081. pHdr = sqlite3MemsysGetHeader(pPrior);
  23082. pBt = (void**)pHdr;
  23083. pBt -= pHdr->nBacktraceSlots;
  23084. sqlite3_mutex_enter(mem.mutex);
  23085. if( pHdr->pPrev ){
  23086. assert( pHdr->pPrev->pNext==pHdr );
  23087. pHdr->pPrev->pNext = pHdr->pNext;
  23088. }else{
  23089. assert( mem.pFirst==pHdr );
  23090. mem.pFirst = pHdr->pNext;
  23091. }
  23092. if( pHdr->pNext ){
  23093. assert( pHdr->pNext->pPrev==pHdr );
  23094. pHdr->pNext->pPrev = pHdr->pPrev;
  23095. }else{
  23096. assert( mem.pLast==pHdr );
  23097. mem.pLast = pHdr->pPrev;
  23098. }
  23099. z = (char*)pBt;
  23100. z -= pHdr->nTitle;
  23101. adjustStats((int)pHdr->iSize, -1);
  23102. randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
  23103. (int)pHdr->iSize + sizeof(int) + pHdr->nTitle);
  23104. free(z);
  23105. sqlite3_mutex_leave(mem.mutex);
  23106. }
  23107. /*
  23108. ** Change the size of an existing memory allocation.
  23109. **
  23110. ** For this debugging implementation, we *always* make a copy of the
  23111. ** allocation into a new place in memory. In this way, if the
  23112. ** higher level code is using pointer to the old allocation, it is
  23113. ** much more likely to break and we are much more liking to find
  23114. ** the error.
  23115. */
  23116. static void *sqlite3MemRealloc(void *pPrior, int nByte){
  23117. struct MemBlockHdr *pOldHdr;
  23118. void *pNew;
  23119. assert( mem.disallow==0 );
  23120. assert( (nByte & 7)==0 ); /* EV: R-46199-30249 */
  23121. pOldHdr = sqlite3MemsysGetHeader(pPrior);
  23122. pNew = sqlite3MemMalloc(nByte);
  23123. if( pNew ){
  23124. memcpy(pNew, pPrior, (int)(nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize));
  23125. if( nByte>pOldHdr->iSize ){
  23126. randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - (int)pOldHdr->iSize);
  23127. }
  23128. sqlite3MemFree(pPrior);
  23129. }
  23130. return pNew;
  23131. }
  23132. /*
  23133. ** Populate the low-level memory allocation function pointers in
  23134. ** sqlite3GlobalConfig.m with pointers to the routines in this file.
  23135. */
  23136. SQLITE_PRIVATE void sqlite3MemSetDefault(void){
  23137. static const sqlite3_mem_methods defaultMethods = {
  23138. sqlite3MemMalloc,
  23139. sqlite3MemFree,
  23140. sqlite3MemRealloc,
  23141. sqlite3MemSize,
  23142. sqlite3MemRoundup,
  23143. sqlite3MemInit,
  23144. sqlite3MemShutdown,
  23145. 0
  23146. };
  23147. sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
  23148. }
  23149. /*
  23150. ** Set the "type" of an allocation.
  23151. */
  23152. SQLITE_PRIVATE void sqlite3MemdebugSetType(void *p, u8 eType){
  23153. if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
  23154. struct MemBlockHdr *pHdr;
  23155. pHdr = sqlite3MemsysGetHeader(p);
  23156. assert( pHdr->iForeGuard==FOREGUARD );
  23157. pHdr->eType = eType;
  23158. }
  23159. }
  23160. /*
  23161. ** Return TRUE if the mask of type in eType matches the type of the
  23162. ** allocation p. Also return true if p==NULL.
  23163. **
  23164. ** This routine is designed for use within an assert() statement, to
  23165. ** verify the type of an allocation. For example:
  23166. **
  23167. ** assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
  23168. */
  23169. SQLITE_PRIVATE int sqlite3MemdebugHasType(void *p, u8 eType){
  23170. int rc = 1;
  23171. if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
  23172. struct MemBlockHdr *pHdr;
  23173. pHdr = sqlite3MemsysGetHeader(p);
  23174. assert( pHdr->iForeGuard==FOREGUARD ); /* Allocation is valid */
  23175. if( (pHdr->eType&eType)==0 ){
  23176. rc = 0;
  23177. }
  23178. }
  23179. return rc;
  23180. }
  23181. /*
  23182. ** Return TRUE if the mask of type in eType matches no bits of the type of the
  23183. ** allocation p. Also return true if p==NULL.
  23184. **
  23185. ** This routine is designed for use within an assert() statement, to
  23186. ** verify the type of an allocation. For example:
  23187. **
  23188. ** assert( sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
  23189. */
  23190. SQLITE_PRIVATE int sqlite3MemdebugNoType(void *p, u8 eType){
  23191. int rc = 1;
  23192. if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
  23193. struct MemBlockHdr *pHdr;
  23194. pHdr = sqlite3MemsysGetHeader(p);
  23195. assert( pHdr->iForeGuard==FOREGUARD ); /* Allocation is valid */
  23196. if( (pHdr->eType&eType)!=0 ){
  23197. rc = 0;
  23198. }
  23199. }
  23200. return rc;
  23201. }
  23202. /*
  23203. ** Set the number of backtrace levels kept for each allocation.
  23204. ** A value of zero turns off backtracing. The number is always rounded
  23205. ** up to a multiple of 2.
  23206. */
  23207. SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){
  23208. if( depth<0 ){ depth = 0; }
  23209. if( depth>20 ){ depth = 20; }
  23210. depth = (depth+1)&0xfe;
  23211. mem.nBacktrace = depth;
  23212. }
  23213. SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
  23214. mem.xBacktrace = xBacktrace;
  23215. }
  23216. /*
  23217. ** Set the title string for subsequent allocations.
  23218. */
  23219. SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){
  23220. unsigned int n = sqlite3Strlen30(zTitle) + 1;
  23221. sqlite3_mutex_enter(mem.mutex);
  23222. if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
  23223. memcpy(mem.zTitle, zTitle, n);
  23224. mem.zTitle[n] = 0;
  23225. mem.nTitle = ROUND8(n);
  23226. sqlite3_mutex_leave(mem.mutex);
  23227. }
  23228. SQLITE_PRIVATE void sqlite3MemdebugSync(){
  23229. struct MemBlockHdr *pHdr;
  23230. for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
  23231. void **pBt = (void**)pHdr;
  23232. pBt -= pHdr->nBacktraceSlots;
  23233. mem.xBacktrace((int)pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
  23234. }
  23235. }
  23236. /*
  23237. ** Open the file indicated and write a log of all unfreed memory
  23238. ** allocations into that log.
  23239. */
  23240. SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
  23241. FILE *out;
  23242. struct MemBlockHdr *pHdr;
  23243. void **pBt;
  23244. int i;
  23245. out = fopen(zFilename, "w");
  23246. if( out==0 ){
  23247. fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
  23248. zFilename);
  23249. return;
  23250. }
  23251. for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
  23252. char *z = (char*)pHdr;
  23253. z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
  23254. fprintf(out, "**** %lld bytes at %p from %s ****\n",
  23255. pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
  23256. if( pHdr->nBacktrace ){
  23257. fflush(out);
  23258. pBt = (void**)pHdr;
  23259. pBt -= pHdr->nBacktraceSlots;
  23260. backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
  23261. fprintf(out, "\n");
  23262. }
  23263. }
  23264. fprintf(out, "COUNTS:\n");
  23265. for(i=0; i<NCSIZE-1; i++){
  23266. if( mem.nAlloc[i] ){
  23267. fprintf(out, " %5d: %10d %10d %10d\n",
  23268. i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
  23269. }
  23270. }
  23271. if( mem.nAlloc[NCSIZE-1] ){
  23272. fprintf(out, " %5d: %10d %10d %10d\n",
  23273. NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
  23274. mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
  23275. }
  23276. fclose(out);
  23277. }
  23278. /*
  23279. ** Return the number of times sqlite3MemMalloc() has been called.
  23280. */
  23281. SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
  23282. int i;
  23283. int nTotal = 0;
  23284. for(i=0; i<NCSIZE; i++){
  23285. nTotal += mem.nAlloc[i];
  23286. }
  23287. return nTotal;
  23288. }
  23289. #endif /* SQLITE_MEMDEBUG */
  23290. /************** End of mem2.c ************************************************/
  23291. /************** Begin file mem3.c ********************************************/
  23292. /*
  23293. ** 2007 October 14
  23294. **
  23295. ** The author disclaims copyright to this source code. In place of
  23296. ** a legal notice, here is a blessing:
  23297. **
  23298. ** May you do good and not evil.
  23299. ** May you find forgiveness for yourself and forgive others.
  23300. ** May you share freely, never taking more than you give.
  23301. **
  23302. *************************************************************************
  23303. ** This file contains the C functions that implement a memory
  23304. ** allocation subsystem for use by SQLite.
  23305. **
  23306. ** This version of the memory allocation subsystem omits all
  23307. ** use of malloc(). The SQLite user supplies a block of memory
  23308. ** before calling sqlite3_initialize() from which allocations
  23309. ** are made and returned by the xMalloc() and xRealloc()
  23310. ** implementations. Once sqlite3_initialize() has been called,
  23311. ** the amount of memory available to SQLite is fixed and cannot
  23312. ** be changed.
  23313. **
  23314. ** This version of the memory allocation subsystem is included
  23315. ** in the build only if SQLITE_ENABLE_MEMSYS3 is defined.
  23316. */
  23317. /* #include "sqliteInt.h" */
  23318. /*
  23319. ** This version of the memory allocator is only built into the library
  23320. ** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not
  23321. ** mean that the library will use a memory-pool by default, just that
  23322. ** it is available. The mempool allocator is activated by calling
  23323. ** sqlite3_config().
  23324. */
  23325. #ifdef SQLITE_ENABLE_MEMSYS3
  23326. /*
  23327. ** Maximum size (in Mem3Blocks) of a "small" chunk.
  23328. */
  23329. #define MX_SMALL 10
  23330. /*
  23331. ** Number of freelist hash slots
  23332. */
  23333. #define N_HASH 61
  23334. /*
  23335. ** A memory allocation (also called a "chunk") consists of two or
  23336. ** more blocks where each block is 8 bytes. The first 8 bytes are
  23337. ** a header that is not returned to the user.
  23338. **
  23339. ** A chunk is two or more blocks that is either checked out or
  23340. ** free. The first block has format u.hdr. u.hdr.size4x is 4 times the
  23341. ** size of the allocation in blocks if the allocation is free.
  23342. ** The u.hdr.size4x&1 bit is true if the chunk is checked out and
  23343. ** false if the chunk is on the freelist. The u.hdr.size4x&2 bit
  23344. ** is true if the previous chunk is checked out and false if the
  23345. ** previous chunk is free. The u.hdr.prevSize field is the size of
  23346. ** the previous chunk in blocks if the previous chunk is on the
  23347. ** freelist. If the previous chunk is checked out, then
  23348. ** u.hdr.prevSize can be part of the data for that chunk and should
  23349. ** not be read or written.
  23350. **
  23351. ** We often identify a chunk by its index in mem3.aPool[]. When
  23352. ** this is done, the chunk index refers to the second block of
  23353. ** the chunk. In this way, the first chunk has an index of 1.
  23354. ** A chunk index of 0 means "no such chunk" and is the equivalent
  23355. ** of a NULL pointer.
  23356. **
  23357. ** The second block of free chunks is of the form u.list. The
  23358. ** two fields form a double-linked list of chunks of related sizes.
  23359. ** Pointers to the head of the list are stored in mem3.aiSmall[]
  23360. ** for smaller chunks and mem3.aiHash[] for larger chunks.
  23361. **
  23362. ** The second block of a chunk is user data if the chunk is checked
  23363. ** out. If a chunk is checked out, the user data may extend into
  23364. ** the u.hdr.prevSize value of the following chunk.
  23365. */
  23366. typedef struct Mem3Block Mem3Block;
  23367. struct Mem3Block {
  23368. union {
  23369. struct {
  23370. u32 prevSize; /* Size of previous chunk in Mem3Block elements */
  23371. u32 size4x; /* 4x the size of current chunk in Mem3Block elements */
  23372. } hdr;
  23373. struct {
  23374. u32 next; /* Index in mem3.aPool[] of next free chunk */
  23375. u32 prev; /* Index in mem3.aPool[] of previous free chunk */
  23376. } list;
  23377. } u;
  23378. };
  23379. /*
  23380. ** All of the static variables used by this module are collected
  23381. ** into a single structure named "mem3". This is to keep the
  23382. ** static variables organized and to reduce namespace pollution
  23383. ** when this module is combined with other in the amalgamation.
  23384. */
  23385. static SQLITE_WSD struct Mem3Global {
  23386. /*
  23387. ** Memory available for allocation. nPool is the size of the array
  23388. ** (in Mem3Blocks) pointed to by aPool less 2.
  23389. */
  23390. u32 nPool;
  23391. Mem3Block *aPool;
  23392. /*
  23393. ** True if we are evaluating an out-of-memory callback.
  23394. */
  23395. int alarmBusy;
  23396. /*
  23397. ** Mutex to control access to the memory allocation subsystem.
  23398. */
  23399. sqlite3_mutex *mutex;
  23400. /*
  23401. ** The minimum amount of free space that we have seen.
  23402. */
  23403. u32 mnMaster;
  23404. /*
  23405. ** iMaster is the index of the master chunk. Most new allocations
  23406. ** occur off of this chunk. szMaster is the size (in Mem3Blocks)
  23407. ** of the current master. iMaster is 0 if there is not master chunk.
  23408. ** The master chunk is not in either the aiHash[] or aiSmall[].
  23409. */
  23410. u32 iMaster;
  23411. u32 szMaster;
  23412. /*
  23413. ** Array of lists of free blocks according to the block size
  23414. ** for smaller chunks, or a hash on the block size for larger
  23415. ** chunks.
  23416. */
  23417. u32 aiSmall[MX_SMALL-1]; /* For sizes 2 through MX_SMALL, inclusive */
  23418. u32 aiHash[N_HASH]; /* For sizes MX_SMALL+1 and larger */
  23419. } mem3 = { 97535575 };
  23420. #define mem3 GLOBAL(struct Mem3Global, mem3)
  23421. /*
  23422. ** Unlink the chunk at mem3.aPool[i] from list it is currently
  23423. ** on. *pRoot is the list that i is a member of.
  23424. */
  23425. static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
  23426. u32 next = mem3.aPool[i].u.list.next;
  23427. u32 prev = mem3.aPool[i].u.list.prev;
  23428. assert( sqlite3_mutex_held(mem3.mutex) );
  23429. if( prev==0 ){
  23430. *pRoot = next;
  23431. }else{
  23432. mem3.aPool[prev].u.list.next = next;
  23433. }
  23434. if( next ){
  23435. mem3.aPool[next].u.list.prev = prev;
  23436. }
  23437. mem3.aPool[i].u.list.next = 0;
  23438. mem3.aPool[i].u.list.prev = 0;
  23439. }
  23440. /*
  23441. ** Unlink the chunk at index i from
  23442. ** whatever list is currently a member of.
  23443. */
  23444. static void memsys3Unlink(u32 i){
  23445. u32 size, hash;
  23446. assert( sqlite3_mutex_held(mem3.mutex) );
  23447. assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
  23448. assert( i>=1 );
  23449. size = mem3.aPool[i-1].u.hdr.size4x/4;
  23450. assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
  23451. assert( size>=2 );
  23452. if( size <= MX_SMALL ){
  23453. memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
  23454. }else{
  23455. hash = size % N_HASH;
  23456. memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
  23457. }
  23458. }
  23459. /*
  23460. ** Link the chunk at mem3.aPool[i] so that is on the list rooted
  23461. ** at *pRoot.
  23462. */
  23463. static void memsys3LinkIntoList(u32 i, u32 *pRoot){
  23464. assert( sqlite3_mutex_held(mem3.mutex) );
  23465. mem3.aPool[i].u.list.next = *pRoot;
  23466. mem3.aPool[i].u.list.prev = 0;
  23467. if( *pRoot ){
  23468. mem3.aPool[*pRoot].u.list.prev = i;
  23469. }
  23470. *pRoot = i;
  23471. }
  23472. /*
  23473. ** Link the chunk at index i into either the appropriate
  23474. ** small chunk list, or into the large chunk hash table.
  23475. */
  23476. static void memsys3Link(u32 i){
  23477. u32 size, hash;
  23478. assert( sqlite3_mutex_held(mem3.mutex) );
  23479. assert( i>=1 );
  23480. assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
  23481. size = mem3.aPool[i-1].u.hdr.size4x/4;
  23482. assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
  23483. assert( size>=2 );
  23484. if( size <= MX_SMALL ){
  23485. memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
  23486. }else{
  23487. hash = size % N_HASH;
  23488. memsys3LinkIntoList(i, &mem3.aiHash[hash]);
  23489. }
  23490. }
  23491. /*
  23492. ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
  23493. ** will already be held (obtained by code in malloc.c) if
  23494. ** sqlite3GlobalConfig.bMemStat is true.
  23495. */
  23496. static void memsys3Enter(void){
  23497. if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){
  23498. mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  23499. }
  23500. sqlite3_mutex_enter(mem3.mutex);
  23501. }
  23502. static void memsys3Leave(void){
  23503. sqlite3_mutex_leave(mem3.mutex);
  23504. }
  23505. /*
  23506. ** Called when we are unable to satisfy an allocation of nBytes.
  23507. */
  23508. static void memsys3OutOfMemory(int nByte){
  23509. if( !mem3.alarmBusy ){
  23510. mem3.alarmBusy = 1;
  23511. assert( sqlite3_mutex_held(mem3.mutex) );
  23512. sqlite3_mutex_leave(mem3.mutex);
  23513. sqlite3_release_memory(nByte);
  23514. sqlite3_mutex_enter(mem3.mutex);
  23515. mem3.alarmBusy = 0;
  23516. }
  23517. }
  23518. /*
  23519. ** Chunk i is a free chunk that has been unlinked. Adjust its
  23520. ** size parameters for check-out and return a pointer to the
  23521. ** user portion of the chunk.
  23522. */
  23523. static void *memsys3Checkout(u32 i, u32 nBlock){
  23524. u32 x;
  23525. assert( sqlite3_mutex_held(mem3.mutex) );
  23526. assert( i>=1 );
  23527. assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
  23528. assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
  23529. x = mem3.aPool[i-1].u.hdr.size4x;
  23530. mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
  23531. mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
  23532. mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
  23533. return &mem3.aPool[i];
  23534. }
  23535. /*
  23536. ** Carve a piece off of the end of the mem3.iMaster free chunk.
  23537. ** Return a pointer to the new allocation. Or, if the master chunk
  23538. ** is not large enough, return 0.
  23539. */
  23540. static void *memsys3FromMaster(u32 nBlock){
  23541. assert( sqlite3_mutex_held(mem3.mutex) );
  23542. assert( mem3.szMaster>=nBlock );
  23543. if( nBlock>=mem3.szMaster-1 ){
  23544. /* Use the entire master */
  23545. void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);
  23546. mem3.iMaster = 0;
  23547. mem3.szMaster = 0;
  23548. mem3.mnMaster = 0;
  23549. return p;
  23550. }else{
  23551. /* Split the master block. Return the tail. */
  23552. u32 newi, x;
  23553. newi = mem3.iMaster + mem3.szMaster - nBlock;
  23554. assert( newi > mem3.iMaster+1 );
  23555. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;
  23556. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;
  23557. mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
  23558. mem3.szMaster -= nBlock;
  23559. mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;
  23560. x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
  23561. mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
  23562. if( mem3.szMaster < mem3.mnMaster ){
  23563. mem3.mnMaster = mem3.szMaster;
  23564. }
  23565. return (void*)&mem3.aPool[newi];
  23566. }
  23567. }
  23568. /*
  23569. ** *pRoot is the head of a list of free chunks of the same size
  23570. ** or same size hash. In other words, *pRoot is an entry in either
  23571. ** mem3.aiSmall[] or mem3.aiHash[].
  23572. **
  23573. ** This routine examines all entries on the given list and tries
  23574. ** to coalesce each entries with adjacent free chunks.
  23575. **
  23576. ** If it sees a chunk that is larger than mem3.iMaster, it replaces
  23577. ** the current mem3.iMaster with the new larger chunk. In order for
  23578. ** this mem3.iMaster replacement to work, the master chunk must be
  23579. ** linked into the hash tables. That is not the normal state of
  23580. ** affairs, of course. The calling routine must link the master
  23581. ** chunk before invoking this routine, then must unlink the (possibly
  23582. ** changed) master chunk once this routine has finished.
  23583. */
  23584. static void memsys3Merge(u32 *pRoot){
  23585. u32 iNext, prev, size, i, x;
  23586. assert( sqlite3_mutex_held(mem3.mutex) );
  23587. for(i=*pRoot; i>0; i=iNext){
  23588. iNext = mem3.aPool[i].u.list.next;
  23589. size = mem3.aPool[i-1].u.hdr.size4x;
  23590. assert( (size&1)==0 );
  23591. if( (size&2)==0 ){
  23592. memsys3UnlinkFromList(i, pRoot);
  23593. assert( i > mem3.aPool[i-1].u.hdr.prevSize );
  23594. prev = i - mem3.aPool[i-1].u.hdr.prevSize;
  23595. if( prev==iNext ){
  23596. iNext = mem3.aPool[prev].u.list.next;
  23597. }
  23598. memsys3Unlink(prev);
  23599. size = i + size/4 - prev;
  23600. x = mem3.aPool[prev-1].u.hdr.size4x & 2;
  23601. mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
  23602. mem3.aPool[prev+size-1].u.hdr.prevSize = size;
  23603. memsys3Link(prev);
  23604. i = prev;
  23605. }else{
  23606. size /= 4;
  23607. }
  23608. if( size>mem3.szMaster ){
  23609. mem3.iMaster = i;
  23610. mem3.szMaster = size;
  23611. }
  23612. }
  23613. }
  23614. /*
  23615. ** Return a block of memory of at least nBytes in size.
  23616. ** Return NULL if unable.
  23617. **
  23618. ** This function assumes that the necessary mutexes, if any, are
  23619. ** already held by the caller. Hence "Unsafe".
  23620. */
  23621. static void *memsys3MallocUnsafe(int nByte){
  23622. u32 i;
  23623. u32 nBlock;
  23624. u32 toFree;
  23625. assert( sqlite3_mutex_held(mem3.mutex) );
  23626. assert( sizeof(Mem3Block)==8 );
  23627. if( nByte<=12 ){
  23628. nBlock = 2;
  23629. }else{
  23630. nBlock = (nByte + 11)/8;
  23631. }
  23632. assert( nBlock>=2 );
  23633. /* STEP 1:
  23634. ** Look for an entry of the correct size in either the small
  23635. ** chunk table or in the large chunk hash table. This is
  23636. ** successful most of the time (about 9 times out of 10).
  23637. */
  23638. if( nBlock <= MX_SMALL ){
  23639. i = mem3.aiSmall[nBlock-2];
  23640. if( i>0 ){
  23641. memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
  23642. return memsys3Checkout(i, nBlock);
  23643. }
  23644. }else{
  23645. int hash = nBlock % N_HASH;
  23646. for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
  23647. if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
  23648. memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
  23649. return memsys3Checkout(i, nBlock);
  23650. }
  23651. }
  23652. }
  23653. /* STEP 2:
  23654. ** Try to satisfy the allocation by carving a piece off of the end
  23655. ** of the master chunk. This step usually works if step 1 fails.
  23656. */
  23657. if( mem3.szMaster>=nBlock ){
  23658. return memsys3FromMaster(nBlock);
  23659. }
  23660. /* STEP 3:
  23661. ** Loop through the entire memory pool. Coalesce adjacent free
  23662. ** chunks. Recompute the master chunk as the largest free chunk.
  23663. ** Then try again to satisfy the allocation by carving a piece off
  23664. ** of the end of the master chunk. This step happens very
  23665. ** rarely (we hope!)
  23666. */
  23667. for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
  23668. memsys3OutOfMemory(toFree);
  23669. if( mem3.iMaster ){
  23670. memsys3Link(mem3.iMaster);
  23671. mem3.iMaster = 0;
  23672. mem3.szMaster = 0;
  23673. }
  23674. for(i=0; i<N_HASH; i++){
  23675. memsys3Merge(&mem3.aiHash[i]);
  23676. }
  23677. for(i=0; i<MX_SMALL-1; i++){
  23678. memsys3Merge(&mem3.aiSmall[i]);
  23679. }
  23680. if( mem3.szMaster ){
  23681. memsys3Unlink(mem3.iMaster);
  23682. if( mem3.szMaster>=nBlock ){
  23683. return memsys3FromMaster(nBlock);
  23684. }
  23685. }
  23686. }
  23687. /* If none of the above worked, then we fail. */
  23688. return 0;
  23689. }
  23690. /*
  23691. ** Free an outstanding memory allocation.
  23692. **
  23693. ** This function assumes that the necessary mutexes, if any, are
  23694. ** already held by the caller. Hence "Unsafe".
  23695. */
  23696. static void memsys3FreeUnsafe(void *pOld){
  23697. Mem3Block *p = (Mem3Block*)pOld;
  23698. int i;
  23699. u32 size, x;
  23700. assert( sqlite3_mutex_held(mem3.mutex) );
  23701. assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
  23702. i = p - mem3.aPool;
  23703. assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
  23704. size = mem3.aPool[i-1].u.hdr.size4x/4;
  23705. assert( i+size<=mem3.nPool+1 );
  23706. mem3.aPool[i-1].u.hdr.size4x &= ~1;
  23707. mem3.aPool[i+size-1].u.hdr.prevSize = size;
  23708. mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
  23709. memsys3Link(i);
  23710. /* Try to expand the master using the newly freed chunk */
  23711. if( mem3.iMaster ){
  23712. while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){
  23713. size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;
  23714. mem3.iMaster -= size;
  23715. mem3.szMaster += size;
  23716. memsys3Unlink(mem3.iMaster);
  23717. x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
  23718. mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
  23719. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
  23720. }
  23721. x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
  23722. while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){
  23723. memsys3Unlink(mem3.iMaster+mem3.szMaster);
  23724. mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;
  23725. mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
  23726. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
  23727. }
  23728. }
  23729. }
  23730. /*
  23731. ** Return the size of an outstanding allocation, in bytes. The
  23732. ** size returned omits the 8-byte header overhead. This only
  23733. ** works for chunks that are currently checked out.
  23734. */
  23735. static int memsys3Size(void *p){
  23736. Mem3Block *pBlock;
  23737. assert( p!=0 );
  23738. pBlock = (Mem3Block*)p;
  23739. assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
  23740. return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
  23741. }
  23742. /*
  23743. ** Round up a request size to the next valid allocation size.
  23744. */
  23745. static int memsys3Roundup(int n){
  23746. if( n<=12 ){
  23747. return 12;
  23748. }else{
  23749. return ((n+11)&~7) - 4;
  23750. }
  23751. }
  23752. /*
  23753. ** Allocate nBytes of memory.
  23754. */
  23755. static void *memsys3Malloc(int nBytes){
  23756. sqlite3_int64 *p;
  23757. assert( nBytes>0 ); /* malloc.c filters out 0 byte requests */
  23758. memsys3Enter();
  23759. p = memsys3MallocUnsafe(nBytes);
  23760. memsys3Leave();
  23761. return (void*)p;
  23762. }
  23763. /*
  23764. ** Free memory.
  23765. */
  23766. static void memsys3Free(void *pPrior){
  23767. assert( pPrior );
  23768. memsys3Enter();
  23769. memsys3FreeUnsafe(pPrior);
  23770. memsys3Leave();
  23771. }
  23772. /*
  23773. ** Change the size of an existing memory allocation
  23774. */
  23775. static void *memsys3Realloc(void *pPrior, int nBytes){
  23776. int nOld;
  23777. void *p;
  23778. if( pPrior==0 ){
  23779. return sqlite3_malloc(nBytes);
  23780. }
  23781. if( nBytes<=0 ){
  23782. sqlite3_free(pPrior);
  23783. return 0;
  23784. }
  23785. nOld = memsys3Size(pPrior);
  23786. if( nBytes<=nOld && nBytes>=nOld-128 ){
  23787. return pPrior;
  23788. }
  23789. memsys3Enter();
  23790. p = memsys3MallocUnsafe(nBytes);
  23791. if( p ){
  23792. if( nOld<nBytes ){
  23793. memcpy(p, pPrior, nOld);
  23794. }else{
  23795. memcpy(p, pPrior, nBytes);
  23796. }
  23797. memsys3FreeUnsafe(pPrior);
  23798. }
  23799. memsys3Leave();
  23800. return p;
  23801. }
  23802. /*
  23803. ** Initialize this module.
  23804. */
  23805. static int memsys3Init(void *NotUsed){
  23806. UNUSED_PARAMETER(NotUsed);
  23807. if( !sqlite3GlobalConfig.pHeap ){
  23808. return SQLITE_ERROR;
  23809. }
  23810. /* Store a pointer to the memory block in global structure mem3. */
  23811. assert( sizeof(Mem3Block)==8 );
  23812. mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap;
  23813. mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;
  23814. /* Initialize the master block. */
  23815. mem3.szMaster = mem3.nPool;
  23816. mem3.mnMaster = mem3.szMaster;
  23817. mem3.iMaster = 1;
  23818. mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2;
  23819. mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
  23820. mem3.aPool[mem3.nPool].u.hdr.size4x = 1;
  23821. return SQLITE_OK;
  23822. }
  23823. /*
  23824. ** Deinitialize this module.
  23825. */
  23826. static void memsys3Shutdown(void *NotUsed){
  23827. UNUSED_PARAMETER(NotUsed);
  23828. mem3.mutex = 0;
  23829. return;
  23830. }
  23831. /*
  23832. ** Open the file indicated and write a log of all unfreed memory
  23833. ** allocations into that log.
  23834. */
  23835. SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
  23836. #ifdef SQLITE_DEBUG
  23837. FILE *out;
  23838. u32 i, j;
  23839. u32 size;
  23840. if( zFilename==0 || zFilename[0]==0 ){
  23841. out = stdout;
  23842. }else{
  23843. out = fopen(zFilename, "w");
  23844. if( out==0 ){
  23845. fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
  23846. zFilename);
  23847. return;
  23848. }
  23849. }
  23850. memsys3Enter();
  23851. fprintf(out, "CHUNKS:\n");
  23852. for(i=1; i<=mem3.nPool; i+=size/4){
  23853. size = mem3.aPool[i-1].u.hdr.size4x;
  23854. if( size/4<=1 ){
  23855. fprintf(out, "%p size error\n", &mem3.aPool[i]);
  23856. assert( 0 );
  23857. break;
  23858. }
  23859. if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
  23860. fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]);
  23861. assert( 0 );
  23862. break;
  23863. }
  23864. if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
  23865. fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
  23866. assert( 0 );
  23867. break;
  23868. }
  23869. if( size&1 ){
  23870. fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
  23871. }else{
  23872. fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
  23873. i==mem3.iMaster ? " **master**" : "");
  23874. }
  23875. }
  23876. for(i=0; i<MX_SMALL-1; i++){
  23877. if( mem3.aiSmall[i]==0 ) continue;
  23878. fprintf(out, "small(%2d):", i);
  23879. for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){
  23880. fprintf(out, " %p(%d)", &mem3.aPool[j],
  23881. (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
  23882. }
  23883. fprintf(out, "\n");
  23884. }
  23885. for(i=0; i<N_HASH; i++){
  23886. if( mem3.aiHash[i]==0 ) continue;
  23887. fprintf(out, "hash(%2d):", i);
  23888. for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){
  23889. fprintf(out, " %p(%d)", &mem3.aPool[j],
  23890. (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
  23891. }
  23892. fprintf(out, "\n");
  23893. }
  23894. fprintf(out, "master=%d\n", mem3.iMaster);
  23895. fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8);
  23896. fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8);
  23897. sqlite3_mutex_leave(mem3.mutex);
  23898. if( out==stdout ){
  23899. fflush(stdout);
  23900. }else{
  23901. fclose(out);
  23902. }
  23903. #else
  23904. UNUSED_PARAMETER(zFilename);
  23905. #endif
  23906. }
  23907. /*
  23908. ** This routine is the only routine in this file with external
  23909. ** linkage.
  23910. **
  23911. ** Populate the low-level memory allocation function pointers in
  23912. ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
  23913. ** arguments specify the block of memory to manage.
  23914. **
  23915. ** This routine is only called by sqlite3_config(), and therefore
  23916. ** is not required to be threadsafe (it is not).
  23917. */
  23918. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){
  23919. static const sqlite3_mem_methods mempoolMethods = {
  23920. memsys3Malloc,
  23921. memsys3Free,
  23922. memsys3Realloc,
  23923. memsys3Size,
  23924. memsys3Roundup,
  23925. memsys3Init,
  23926. memsys3Shutdown,
  23927. 0
  23928. };
  23929. return &mempoolMethods;
  23930. }
  23931. #endif /* SQLITE_ENABLE_MEMSYS3 */
  23932. /************** End of mem3.c ************************************************/
  23933. /************** Begin file mem5.c ********************************************/
  23934. /*
  23935. ** 2007 October 14
  23936. **
  23937. ** The author disclaims copyright to this source code. In place of
  23938. ** a legal notice, here is a blessing:
  23939. **
  23940. ** May you do good and not evil.
  23941. ** May you find forgiveness for yourself and forgive others.
  23942. ** May you share freely, never taking more than you give.
  23943. **
  23944. *************************************************************************
  23945. ** This file contains the C functions that implement a memory
  23946. ** allocation subsystem for use by SQLite.
  23947. **
  23948. ** This version of the memory allocation subsystem omits all
  23949. ** use of malloc(). The application gives SQLite a block of memory
  23950. ** before calling sqlite3_initialize() from which allocations
  23951. ** are made and returned by the xMalloc() and xRealloc()
  23952. ** implementations. Once sqlite3_initialize() has been called,
  23953. ** the amount of memory available to SQLite is fixed and cannot
  23954. ** be changed.
  23955. **
  23956. ** This version of the memory allocation subsystem is included
  23957. ** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
  23958. **
  23959. ** This memory allocator uses the following algorithm:
  23960. **
  23961. ** 1. All memory allocation sizes are rounded up to a power of 2.
  23962. **
  23963. ** 2. If two adjacent free blocks are the halves of a larger block,
  23964. ** then the two blocks are coalesced into the single larger block.
  23965. **
  23966. ** 3. New memory is allocated from the first available free block.
  23967. **
  23968. ** This algorithm is described in: J. M. Robson. "Bounds for Some Functions
  23969. ** Concerning Dynamic Storage Allocation". Journal of the Association for
  23970. ** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.
  23971. **
  23972. ** Let n be the size of the largest allocation divided by the minimum
  23973. ** allocation size (after rounding all sizes up to a power of 2.) Let M
  23974. ** be the maximum amount of memory ever outstanding at one time. Let
  23975. ** N be the total amount of memory available for allocation. Robson
  23976. ** proved that this memory allocator will never breakdown due to
  23977. ** fragmentation as long as the following constraint holds:
  23978. **
  23979. ** N >= M*(1 + log2(n)/2) - n + 1
  23980. **
  23981. ** The sqlite3_status() logic tracks the maximum values of n and M so
  23982. ** that an application can, at any time, verify this constraint.
  23983. */
  23984. /* #include "sqliteInt.h" */
  23985. /*
  23986. ** This version of the memory allocator is used only when
  23987. ** SQLITE_ENABLE_MEMSYS5 is defined.
  23988. */
  23989. #ifdef SQLITE_ENABLE_MEMSYS5
  23990. /*
  23991. ** A minimum allocation is an instance of the following structure.
  23992. ** Larger allocations are an array of these structures where the
  23993. ** size of the array is a power of 2.
  23994. **
  23995. ** The size of this object must be a power of two. That fact is
  23996. ** verified in memsys5Init().
  23997. */
  23998. typedef struct Mem5Link Mem5Link;
  23999. struct Mem5Link {
  24000. int next; /* Index of next free chunk */
  24001. int prev; /* Index of previous free chunk */
  24002. };
  24003. /*
  24004. ** Maximum size of any allocation is ((1<<LOGMAX)*mem5.szAtom). Since
  24005. ** mem5.szAtom is always at least 8 and 32-bit integers are used,
  24006. ** it is not actually possible to reach this limit.
  24007. */
  24008. #define LOGMAX 30
  24009. /*
  24010. ** Masks used for mem5.aCtrl[] elements.
  24011. */
  24012. #define CTRL_LOGSIZE 0x1f /* Log2 Size of this block */
  24013. #define CTRL_FREE 0x20 /* True if not checked out */
  24014. /*
  24015. ** All of the static variables used by this module are collected
  24016. ** into a single structure named "mem5". This is to keep the
  24017. ** static variables organized and to reduce namespace pollution
  24018. ** when this module is combined with other in the amalgamation.
  24019. */
  24020. static SQLITE_WSD struct Mem5Global {
  24021. /*
  24022. ** Memory available for allocation
  24023. */
  24024. int szAtom; /* Smallest possible allocation in bytes */
  24025. int nBlock; /* Number of szAtom sized blocks in zPool */
  24026. u8 *zPool; /* Memory available to be allocated */
  24027. /*
  24028. ** Mutex to control access to the memory allocation subsystem.
  24029. */
  24030. sqlite3_mutex *mutex;
  24031. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  24032. /*
  24033. ** Performance statistics
  24034. */
  24035. u64 nAlloc; /* Total number of calls to malloc */
  24036. u64 totalAlloc; /* Total of all malloc calls - includes internal frag */
  24037. u64 totalExcess; /* Total internal fragmentation */
  24038. u32 currentOut; /* Current checkout, including internal fragmentation */
  24039. u32 currentCount; /* Current number of distinct checkouts */
  24040. u32 maxOut; /* Maximum instantaneous currentOut */
  24041. u32 maxCount; /* Maximum instantaneous currentCount */
  24042. u32 maxRequest; /* Largest allocation (exclusive of internal frag) */
  24043. #endif
  24044. /*
  24045. ** Lists of free blocks. aiFreelist[0] is a list of free blocks of
  24046. ** size mem5.szAtom. aiFreelist[1] holds blocks of size szAtom*2.
  24047. ** aiFreelist[2] holds free blocks of size szAtom*4. And so forth.
  24048. */
  24049. int aiFreelist[LOGMAX+1];
  24050. /*
  24051. ** Space for tracking which blocks are checked out and the size
  24052. ** of each block. One byte per block.
  24053. */
  24054. u8 *aCtrl;
  24055. } mem5;
  24056. /*
  24057. ** Access the static variable through a macro for SQLITE_OMIT_WSD.
  24058. */
  24059. #define mem5 GLOBAL(struct Mem5Global, mem5)
  24060. /*
  24061. ** Assuming mem5.zPool is divided up into an array of Mem5Link
  24062. ** structures, return a pointer to the idx-th such link.
  24063. */
  24064. #define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.szAtom]))
  24065. /*
  24066. ** Unlink the chunk at mem5.aPool[i] from list it is currently
  24067. ** on. It should be found on mem5.aiFreelist[iLogsize].
  24068. */
  24069. static void memsys5Unlink(int i, int iLogsize){
  24070. int next, prev;
  24071. assert( i>=0 && i<mem5.nBlock );
  24072. assert( iLogsize>=0 && iLogsize<=LOGMAX );
  24073. assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
  24074. next = MEM5LINK(i)->next;
  24075. prev = MEM5LINK(i)->prev;
  24076. if( prev<0 ){
  24077. mem5.aiFreelist[iLogsize] = next;
  24078. }else{
  24079. MEM5LINK(prev)->next = next;
  24080. }
  24081. if( next>=0 ){
  24082. MEM5LINK(next)->prev = prev;
  24083. }
  24084. }
  24085. /*
  24086. ** Link the chunk at mem5.aPool[i] so that is on the iLogsize
  24087. ** free list.
  24088. */
  24089. static void memsys5Link(int i, int iLogsize){
  24090. int x;
  24091. assert( sqlite3_mutex_held(mem5.mutex) );
  24092. assert( i>=0 && i<mem5.nBlock );
  24093. assert( iLogsize>=0 && iLogsize<=LOGMAX );
  24094. assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
  24095. x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
  24096. MEM5LINK(i)->prev = -1;
  24097. if( x>=0 ){
  24098. assert( x<mem5.nBlock );
  24099. MEM5LINK(x)->prev = i;
  24100. }
  24101. mem5.aiFreelist[iLogsize] = i;
  24102. }
  24103. /*
  24104. ** Obtain or release the mutex needed to access global data structures.
  24105. */
  24106. static void memsys5Enter(void){
  24107. sqlite3_mutex_enter(mem5.mutex);
  24108. }
  24109. static void memsys5Leave(void){
  24110. sqlite3_mutex_leave(mem5.mutex);
  24111. }
  24112. /*
  24113. ** Return the size of an outstanding allocation, in bytes.
  24114. ** This only works for chunks that are currently checked out.
  24115. */
  24116. static int memsys5Size(void *p){
  24117. int iSize, i;
  24118. assert( p!=0 );
  24119. i = (int)(((u8 *)p-mem5.zPool)/mem5.szAtom);
  24120. assert( i>=0 && i<mem5.nBlock );
  24121. iSize = mem5.szAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
  24122. return iSize;
  24123. }
  24124. /*
  24125. ** Return a block of memory of at least nBytes in size.
  24126. ** Return NULL if unable. Return NULL if nBytes==0.
  24127. **
  24128. ** The caller guarantees that nByte is positive.
  24129. **
  24130. ** The caller has obtained a mutex prior to invoking this
  24131. ** routine so there is never any chance that two or more
  24132. ** threads can be in this routine at the same time.
  24133. */
  24134. static void *memsys5MallocUnsafe(int nByte){
  24135. int i; /* Index of a mem5.aPool[] slot */
  24136. int iBin; /* Index into mem5.aiFreelist[] */
  24137. int iFullSz; /* Size of allocation rounded up to power of 2 */
  24138. int iLogsize; /* Log2 of iFullSz/POW2_MIN */
  24139. /* nByte must be a positive */
  24140. assert( nByte>0 );
  24141. /* No more than 1GiB per allocation */
  24142. if( nByte > 0x40000000 ) return 0;
  24143. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  24144. /* Keep track of the maximum allocation request. Even unfulfilled
  24145. ** requests are counted */
  24146. if( (u32)nByte>mem5.maxRequest ){
  24147. mem5.maxRequest = nByte;
  24148. }
  24149. #endif
  24150. /* Round nByte up to the next valid power of two */
  24151. for(iFullSz=mem5.szAtom,iLogsize=0; iFullSz<nByte; iFullSz*=2,iLogsize++){}
  24152. /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
  24153. ** block. If not, then split a block of the next larger power of
  24154. ** two in order to create a new free block of size iLogsize.
  24155. */
  24156. for(iBin=iLogsize; iBin<=LOGMAX && mem5.aiFreelist[iBin]<0; iBin++){}
  24157. if( iBin>LOGMAX ){
  24158. testcase( sqlite3GlobalConfig.xLog!=0 );
  24159. sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes", nByte);
  24160. return 0;
  24161. }
  24162. i = mem5.aiFreelist[iBin];
  24163. memsys5Unlink(i, iBin);
  24164. while( iBin>iLogsize ){
  24165. int newSize;
  24166. iBin--;
  24167. newSize = 1 << iBin;
  24168. mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
  24169. memsys5Link(i+newSize, iBin);
  24170. }
  24171. mem5.aCtrl[i] = iLogsize;
  24172. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  24173. /* Update allocator performance statistics. */
  24174. mem5.nAlloc++;
  24175. mem5.totalAlloc += iFullSz;
  24176. mem5.totalExcess += iFullSz - nByte;
  24177. mem5.currentCount++;
  24178. mem5.currentOut += iFullSz;
  24179. if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
  24180. if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
  24181. #endif
  24182. #ifdef SQLITE_DEBUG
  24183. /* Make sure the allocated memory does not assume that it is set to zero
  24184. ** or retains a value from a previous allocation */
  24185. memset(&mem5.zPool[i*mem5.szAtom], 0xAA, iFullSz);
  24186. #endif
  24187. /* Return a pointer to the allocated memory. */
  24188. return (void*)&mem5.zPool[i*mem5.szAtom];
  24189. }
  24190. /*
  24191. ** Free an outstanding memory allocation.
  24192. */
  24193. static void memsys5FreeUnsafe(void *pOld){
  24194. u32 size, iLogsize;
  24195. int iBlock;
  24196. /* Set iBlock to the index of the block pointed to by pOld in
  24197. ** the array of mem5.szAtom byte blocks pointed to by mem5.zPool.
  24198. */
  24199. iBlock = (int)(((u8 *)pOld-mem5.zPool)/mem5.szAtom);
  24200. /* Check that the pointer pOld points to a valid, non-free block. */
  24201. assert( iBlock>=0 && iBlock<mem5.nBlock );
  24202. assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 );
  24203. assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
  24204. iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
  24205. size = 1<<iLogsize;
  24206. assert( iBlock+size-1<(u32)mem5.nBlock );
  24207. mem5.aCtrl[iBlock] |= CTRL_FREE;
  24208. mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
  24209. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  24210. assert( mem5.currentCount>0 );
  24211. assert( mem5.currentOut>=(size*mem5.szAtom) );
  24212. mem5.currentCount--;
  24213. mem5.currentOut -= size*mem5.szAtom;
  24214. assert( mem5.currentOut>0 || mem5.currentCount==0 );
  24215. assert( mem5.currentCount>0 || mem5.currentOut==0 );
  24216. #endif
  24217. mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
  24218. while( ALWAYS(iLogsize<LOGMAX) ){
  24219. int iBuddy;
  24220. if( (iBlock>>iLogsize) & 1 ){
  24221. iBuddy = iBlock - size;
  24222. assert( iBuddy>=0 );
  24223. }else{
  24224. iBuddy = iBlock + size;
  24225. if( iBuddy>=mem5.nBlock ) break;
  24226. }
  24227. if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
  24228. memsys5Unlink(iBuddy, iLogsize);
  24229. iLogsize++;
  24230. if( iBuddy<iBlock ){
  24231. mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
  24232. mem5.aCtrl[iBlock] = 0;
  24233. iBlock = iBuddy;
  24234. }else{
  24235. mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
  24236. mem5.aCtrl[iBuddy] = 0;
  24237. }
  24238. size *= 2;
  24239. }
  24240. #ifdef SQLITE_DEBUG
  24241. /* Overwrite freed memory with the 0x55 bit pattern to verify that it is
  24242. ** not used after being freed */
  24243. memset(&mem5.zPool[iBlock*mem5.szAtom], 0x55, size);
  24244. #endif
  24245. memsys5Link(iBlock, iLogsize);
  24246. }
  24247. /*
  24248. ** Allocate nBytes of memory.
  24249. */
  24250. static void *memsys5Malloc(int nBytes){
  24251. sqlite3_int64 *p = 0;
  24252. if( nBytes>0 ){
  24253. memsys5Enter();
  24254. p = memsys5MallocUnsafe(nBytes);
  24255. memsys5Leave();
  24256. }
  24257. return (void*)p;
  24258. }
  24259. /*
  24260. ** Free memory.
  24261. **
  24262. ** The outer layer memory allocator prevents this routine from
  24263. ** being called with pPrior==0.
  24264. */
  24265. static void memsys5Free(void *pPrior){
  24266. assert( pPrior!=0 );
  24267. memsys5Enter();
  24268. memsys5FreeUnsafe(pPrior);
  24269. memsys5Leave();
  24270. }
  24271. /*
  24272. ** Change the size of an existing memory allocation.
  24273. **
  24274. ** The outer layer memory allocator prevents this routine from
  24275. ** being called with pPrior==0.
  24276. **
  24277. ** nBytes is always a value obtained from a prior call to
  24278. ** memsys5Round(). Hence nBytes is always a non-negative power
  24279. ** of two. If nBytes==0 that means that an oversize allocation
  24280. ** (an allocation larger than 0x40000000) was requested and this
  24281. ** routine should return 0 without freeing pPrior.
  24282. */
  24283. static void *memsys5Realloc(void *pPrior, int nBytes){
  24284. int nOld;
  24285. void *p;
  24286. assert( pPrior!=0 );
  24287. assert( (nBytes&(nBytes-1))==0 ); /* EV: R-46199-30249 */
  24288. assert( nBytes>=0 );
  24289. if( nBytes==0 ){
  24290. return 0;
  24291. }
  24292. nOld = memsys5Size(pPrior);
  24293. if( nBytes<=nOld ){
  24294. return pPrior;
  24295. }
  24296. p = memsys5Malloc(nBytes);
  24297. if( p ){
  24298. memcpy(p, pPrior, nOld);
  24299. memsys5Free(pPrior);
  24300. }
  24301. return p;
  24302. }
  24303. /*
  24304. ** Round up a request size to the next valid allocation size. If
  24305. ** the allocation is too large to be handled by this allocation system,
  24306. ** return 0.
  24307. **
  24308. ** All allocations must be a power of two and must be expressed by a
  24309. ** 32-bit signed integer. Hence the largest allocation is 0x40000000
  24310. ** or 1073741824 bytes.
  24311. */
  24312. static int memsys5Roundup(int n){
  24313. int iFullSz;
  24314. if( n > 0x40000000 ) return 0;
  24315. for(iFullSz=mem5.szAtom; iFullSz<n; iFullSz *= 2);
  24316. return iFullSz;
  24317. }
  24318. /*
  24319. ** Return the ceiling of the logarithm base 2 of iValue.
  24320. **
  24321. ** Examples: memsys5Log(1) -> 0
  24322. ** memsys5Log(2) -> 1
  24323. ** memsys5Log(4) -> 2
  24324. ** memsys5Log(5) -> 3
  24325. ** memsys5Log(8) -> 3
  24326. ** memsys5Log(9) -> 4
  24327. */
  24328. static int memsys5Log(int iValue){
  24329. int iLog;
  24330. for(iLog=0; (iLog<(int)((sizeof(int)*8)-1)) && (1<<iLog)<iValue; iLog++);
  24331. return iLog;
  24332. }
  24333. /*
  24334. ** Initialize the memory allocator.
  24335. **
  24336. ** This routine is not threadsafe. The caller must be holding a mutex
  24337. ** to prevent multiple threads from entering at the same time.
  24338. */
  24339. static int memsys5Init(void *NotUsed){
  24340. int ii; /* Loop counter */
  24341. int nByte; /* Number of bytes of memory available to this allocator */
  24342. u8 *zByte; /* Memory usable by this allocator */
  24343. int nMinLog; /* Log base 2 of minimum allocation size in bytes */
  24344. int iOffset; /* An offset into mem5.aCtrl[] */
  24345. UNUSED_PARAMETER(NotUsed);
  24346. /* For the purposes of this routine, disable the mutex */
  24347. mem5.mutex = 0;
  24348. /* The size of a Mem5Link object must be a power of two. Verify that
  24349. ** this is case.
  24350. */
  24351. assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 );
  24352. nByte = sqlite3GlobalConfig.nHeap;
  24353. zByte = (u8*)sqlite3GlobalConfig.pHeap;
  24354. assert( zByte!=0 ); /* sqlite3_config() does not allow otherwise */
  24355. /* boundaries on sqlite3GlobalConfig.mnReq are enforced in sqlite3_config() */
  24356. nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);
  24357. mem5.szAtom = (1<<nMinLog);
  24358. while( (int)sizeof(Mem5Link)>mem5.szAtom ){
  24359. mem5.szAtom = mem5.szAtom << 1;
  24360. }
  24361. mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8)));
  24362. mem5.zPool = zByte;
  24363. mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom];
  24364. for(ii=0; ii<=LOGMAX; ii++){
  24365. mem5.aiFreelist[ii] = -1;
  24366. }
  24367. iOffset = 0;
  24368. for(ii=LOGMAX; ii>=0; ii--){
  24369. int nAlloc = (1<<ii);
  24370. if( (iOffset+nAlloc)<=mem5.nBlock ){
  24371. mem5.aCtrl[iOffset] = ii | CTRL_FREE;
  24372. memsys5Link(iOffset, ii);
  24373. iOffset += nAlloc;
  24374. }
  24375. assert((iOffset+nAlloc)>mem5.nBlock);
  24376. }
  24377. /* If a mutex is required for normal operation, allocate one */
  24378. if( sqlite3GlobalConfig.bMemstat==0 ){
  24379. mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  24380. }
  24381. return SQLITE_OK;
  24382. }
  24383. /*
  24384. ** Deinitialize this module.
  24385. */
  24386. static void memsys5Shutdown(void *NotUsed){
  24387. UNUSED_PARAMETER(NotUsed);
  24388. mem5.mutex = 0;
  24389. return;
  24390. }
  24391. #ifdef SQLITE_TEST
  24392. /*
  24393. ** Open the file indicated and write a log of all unfreed memory
  24394. ** allocations into that log.
  24395. */
  24396. SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){
  24397. FILE *out;
  24398. int i, j, n;
  24399. int nMinLog;
  24400. if( zFilename==0 || zFilename[0]==0 ){
  24401. out = stdout;
  24402. }else{
  24403. out = fopen(zFilename, "w");
  24404. if( out==0 ){
  24405. fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
  24406. zFilename);
  24407. return;
  24408. }
  24409. }
  24410. memsys5Enter();
  24411. nMinLog = memsys5Log(mem5.szAtom);
  24412. for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
  24413. for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
  24414. fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n);
  24415. }
  24416. fprintf(out, "mem5.nAlloc = %llu\n", mem5.nAlloc);
  24417. fprintf(out, "mem5.totalAlloc = %llu\n", mem5.totalAlloc);
  24418. fprintf(out, "mem5.totalExcess = %llu\n", mem5.totalExcess);
  24419. fprintf(out, "mem5.currentOut = %u\n", mem5.currentOut);
  24420. fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
  24421. fprintf(out, "mem5.maxOut = %u\n", mem5.maxOut);
  24422. fprintf(out, "mem5.maxCount = %u\n", mem5.maxCount);
  24423. fprintf(out, "mem5.maxRequest = %u\n", mem5.maxRequest);
  24424. memsys5Leave();
  24425. if( out==stdout ){
  24426. fflush(stdout);
  24427. }else{
  24428. fclose(out);
  24429. }
  24430. }
  24431. #endif
  24432. /*
  24433. ** This routine is the only routine in this file with external
  24434. ** linkage. It returns a pointer to a static sqlite3_mem_methods
  24435. ** struct populated with the memsys5 methods.
  24436. */
  24437. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
  24438. static const sqlite3_mem_methods memsys5Methods = {
  24439. memsys5Malloc,
  24440. memsys5Free,
  24441. memsys5Realloc,
  24442. memsys5Size,
  24443. memsys5Roundup,
  24444. memsys5Init,
  24445. memsys5Shutdown,
  24446. 0
  24447. };
  24448. return &memsys5Methods;
  24449. }
  24450. #endif /* SQLITE_ENABLE_MEMSYS5 */
  24451. /************** End of mem5.c ************************************************/
  24452. /************** Begin file mutex.c *******************************************/
  24453. /*
  24454. ** 2007 August 14
  24455. **
  24456. ** The author disclaims copyright to this source code. In place of
  24457. ** a legal notice, here is a blessing:
  24458. **
  24459. ** May you do good and not evil.
  24460. ** May you find forgiveness for yourself and forgive others.
  24461. ** May you share freely, never taking more than you give.
  24462. **
  24463. *************************************************************************
  24464. ** This file contains the C functions that implement mutexes.
  24465. **
  24466. ** This file contains code that is common across all mutex implementations.
  24467. */
  24468. /* #include "sqliteInt.h" */
  24469. #if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT)
  24470. /*
  24471. ** For debugging purposes, record when the mutex subsystem is initialized
  24472. ** and uninitialized so that we can assert() if there is an attempt to
  24473. ** allocate a mutex while the system is uninitialized.
  24474. */
  24475. static SQLITE_WSD int mutexIsInit = 0;
  24476. #endif /* SQLITE_DEBUG && !defined(SQLITE_MUTEX_OMIT) */
  24477. #ifndef SQLITE_MUTEX_OMIT
  24478. #ifdef SQLITE_ENABLE_MULTITHREADED_CHECKS
  24479. /*
  24480. ** This block (enclosed by SQLITE_ENABLE_MULTITHREADED_CHECKS) contains
  24481. ** the implementation of a wrapper around the system default mutex
  24482. ** implementation (sqlite3DefaultMutex()).
  24483. **
  24484. ** Most calls are passed directly through to the underlying default
  24485. ** mutex implementation. Except, if a mutex is configured by calling
  24486. ** sqlite3MutexWarnOnContention() on it, then if contention is ever
  24487. ** encountered within xMutexEnter() a warning is emitted via sqlite3_log().
  24488. **
  24489. ** This type of mutex is used as the database handle mutex when testing
  24490. ** apps that usually use SQLITE_CONFIG_MULTITHREAD mode.
  24491. */
  24492. /*
  24493. ** Type for all mutexes used when SQLITE_ENABLE_MULTITHREADED_CHECKS
  24494. ** is defined. Variable CheckMutex.mutex is a pointer to the real mutex
  24495. ** allocated by the system mutex implementation. Variable iType is usually set
  24496. ** to the type of mutex requested - SQLITE_MUTEX_RECURSIVE, SQLITE_MUTEX_FAST
  24497. ** or one of the static mutex identifiers. Or, if this is a recursive mutex
  24498. ** that has been configured using sqlite3MutexWarnOnContention(), it is
  24499. ** set to SQLITE_MUTEX_WARNONCONTENTION.
  24500. */
  24501. typedef struct CheckMutex CheckMutex;
  24502. struct CheckMutex {
  24503. int iType;
  24504. sqlite3_mutex *mutex;
  24505. };
  24506. #define SQLITE_MUTEX_WARNONCONTENTION (-1)
  24507. /*
  24508. ** Pointer to real mutex methods object used by the CheckMutex
  24509. ** implementation. Set by checkMutexInit().
  24510. */
  24511. static SQLITE_WSD const sqlite3_mutex_methods *pGlobalMutexMethods;
  24512. #ifdef SQLITE_DEBUG
  24513. static int checkMutexHeld(sqlite3_mutex *p){
  24514. return pGlobalMutexMethods->xMutexHeld(((CheckMutex*)p)->mutex);
  24515. }
  24516. static int checkMutexNotheld(sqlite3_mutex *p){
  24517. return pGlobalMutexMethods->xMutexNotheld(((CheckMutex*)p)->mutex);
  24518. }
  24519. #endif
  24520. /*
  24521. ** Initialize and deinitialize the mutex subsystem.
  24522. */
  24523. static int checkMutexInit(void){
  24524. pGlobalMutexMethods = sqlite3DefaultMutex();
  24525. return SQLITE_OK;
  24526. }
  24527. static int checkMutexEnd(void){
  24528. pGlobalMutexMethods = 0;
  24529. return SQLITE_OK;
  24530. }
  24531. /*
  24532. ** Allocate a mutex.
  24533. */
  24534. static sqlite3_mutex *checkMutexAlloc(int iType){
  24535. static CheckMutex staticMutexes[] = {
  24536. {2, 0}, {3, 0}, {4, 0}, {5, 0},
  24537. {6, 0}, {7, 0}, {8, 0}, {9, 0},
  24538. {10, 0}, {11, 0}, {12, 0}, {13, 0}
  24539. };
  24540. CheckMutex *p = 0;
  24541. assert( SQLITE_MUTEX_RECURSIVE==1 && SQLITE_MUTEX_FAST==0 );
  24542. if( iType<2 ){
  24543. p = sqlite3MallocZero(sizeof(CheckMutex));
  24544. if( p==0 ) return 0;
  24545. p->iType = iType;
  24546. }else{
  24547. #ifdef SQLITE_ENABLE_API_ARMOR
  24548. if( iType-2>=ArraySize(staticMutexes) ){
  24549. (void)SQLITE_MISUSE_BKPT;
  24550. return 0;
  24551. }
  24552. #endif
  24553. p = &staticMutexes[iType-2];
  24554. }
  24555. if( p->mutex==0 ){
  24556. p->mutex = pGlobalMutexMethods->xMutexAlloc(iType);
  24557. if( p->mutex==0 ){
  24558. if( iType<2 ){
  24559. sqlite3_free(p);
  24560. }
  24561. p = 0;
  24562. }
  24563. }
  24564. return (sqlite3_mutex*)p;
  24565. }
  24566. /*
  24567. ** Free a mutex.
  24568. */
  24569. static void checkMutexFree(sqlite3_mutex *p){
  24570. assert( SQLITE_MUTEX_RECURSIVE<2 );
  24571. assert( SQLITE_MUTEX_FAST<2 );
  24572. assert( SQLITE_MUTEX_WARNONCONTENTION<2 );
  24573. #if SQLITE_ENABLE_API_ARMOR
  24574. if( ((CheckMutex*)p)->iType<2 )
  24575. #endif
  24576. {
  24577. CheckMutex *pCheck = (CheckMutex*)p;
  24578. pGlobalMutexMethods->xMutexFree(pCheck->mutex);
  24579. sqlite3_free(pCheck);
  24580. }
  24581. #ifdef SQLITE_ENABLE_API_ARMOR
  24582. else{
  24583. (void)SQLITE_MISUSE_BKPT;
  24584. }
  24585. #endif
  24586. }
  24587. /*
  24588. ** Enter the mutex.
  24589. */
  24590. static void checkMutexEnter(sqlite3_mutex *p){
  24591. CheckMutex *pCheck = (CheckMutex*)p;
  24592. if( pCheck->iType==SQLITE_MUTEX_WARNONCONTENTION ){
  24593. if( SQLITE_OK==pGlobalMutexMethods->xMutexTry(pCheck->mutex) ){
  24594. return;
  24595. }
  24596. sqlite3_log(SQLITE_MISUSE,
  24597. "illegal multi-threaded access to database connection"
  24598. );
  24599. }
  24600. pGlobalMutexMethods->xMutexEnter(pCheck->mutex);
  24601. }
  24602. /*
  24603. ** Enter the mutex (do not block).
  24604. */
  24605. static int checkMutexTry(sqlite3_mutex *p){
  24606. CheckMutex *pCheck = (CheckMutex*)p;
  24607. return pGlobalMutexMethods->xMutexTry(pCheck->mutex);
  24608. }
  24609. /*
  24610. ** Leave the mutex.
  24611. */
  24612. static void checkMutexLeave(sqlite3_mutex *p){
  24613. CheckMutex *pCheck = (CheckMutex*)p;
  24614. pGlobalMutexMethods->xMutexLeave(pCheck->mutex);
  24615. }
  24616. sqlite3_mutex_methods const *multiThreadedCheckMutex(void){
  24617. static const sqlite3_mutex_methods sMutex = {
  24618. checkMutexInit,
  24619. checkMutexEnd,
  24620. checkMutexAlloc,
  24621. checkMutexFree,
  24622. checkMutexEnter,
  24623. checkMutexTry,
  24624. checkMutexLeave,
  24625. #ifdef SQLITE_DEBUG
  24626. checkMutexHeld,
  24627. checkMutexNotheld
  24628. #else
  24629. 0,
  24630. 0
  24631. #endif
  24632. };
  24633. return &sMutex;
  24634. }
  24635. /*
  24636. ** Mark the SQLITE_MUTEX_RECURSIVE mutex passed as the only argument as
  24637. ** one on which there should be no contention.
  24638. */
  24639. SQLITE_PRIVATE void sqlite3MutexWarnOnContention(sqlite3_mutex *p){
  24640. if( sqlite3GlobalConfig.mutex.xMutexAlloc==checkMutexAlloc ){
  24641. CheckMutex *pCheck = (CheckMutex*)p;
  24642. assert( pCheck->iType==SQLITE_MUTEX_RECURSIVE );
  24643. pCheck->iType = SQLITE_MUTEX_WARNONCONTENTION;
  24644. }
  24645. }
  24646. #endif /* ifdef SQLITE_ENABLE_MULTITHREADED_CHECKS */
  24647. /*
  24648. ** Initialize the mutex system.
  24649. */
  24650. SQLITE_PRIVATE int sqlite3MutexInit(void){
  24651. int rc = SQLITE_OK;
  24652. if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
  24653. /* If the xMutexAlloc method has not been set, then the user did not
  24654. ** install a mutex implementation via sqlite3_config() prior to
  24655. ** sqlite3_initialize() being called. This block copies pointers to
  24656. ** the default implementation into the sqlite3GlobalConfig structure.
  24657. */
  24658. sqlite3_mutex_methods const *pFrom;
  24659. sqlite3_mutex_methods *pTo = &sqlite3GlobalConfig.mutex;
  24660. if( sqlite3GlobalConfig.bCoreMutex ){
  24661. #ifdef SQLITE_ENABLE_MULTITHREADED_CHECKS
  24662. pFrom = multiThreadedCheckMutex();
  24663. #else
  24664. pFrom = sqlite3DefaultMutex();
  24665. #endif
  24666. }else{
  24667. pFrom = sqlite3NoopMutex();
  24668. }
  24669. pTo->xMutexInit = pFrom->xMutexInit;
  24670. pTo->xMutexEnd = pFrom->xMutexEnd;
  24671. pTo->xMutexFree = pFrom->xMutexFree;
  24672. pTo->xMutexEnter = pFrom->xMutexEnter;
  24673. pTo->xMutexTry = pFrom->xMutexTry;
  24674. pTo->xMutexLeave = pFrom->xMutexLeave;
  24675. pTo->xMutexHeld = pFrom->xMutexHeld;
  24676. pTo->xMutexNotheld = pFrom->xMutexNotheld;
  24677. sqlite3MemoryBarrier();
  24678. pTo->xMutexAlloc = pFrom->xMutexAlloc;
  24679. }
  24680. assert( sqlite3GlobalConfig.mutex.xMutexInit );
  24681. rc = sqlite3GlobalConfig.mutex.xMutexInit();
  24682. #ifdef SQLITE_DEBUG
  24683. GLOBAL(int, mutexIsInit) = 1;
  24684. #endif
  24685. sqlite3MemoryBarrier();
  24686. return rc;
  24687. }
  24688. /*
  24689. ** Shutdown the mutex system. This call frees resources allocated by
  24690. ** sqlite3MutexInit().
  24691. */
  24692. SQLITE_PRIVATE int sqlite3MutexEnd(void){
  24693. int rc = SQLITE_OK;
  24694. if( sqlite3GlobalConfig.mutex.xMutexEnd ){
  24695. rc = sqlite3GlobalConfig.mutex.xMutexEnd();
  24696. }
  24697. #ifdef SQLITE_DEBUG
  24698. GLOBAL(int, mutexIsInit) = 0;
  24699. #endif
  24700. return rc;
  24701. }
  24702. /*
  24703. ** Retrieve a pointer to a static mutex or allocate a new dynamic one.
  24704. */
  24705. SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int id){
  24706. #ifndef SQLITE_OMIT_AUTOINIT
  24707. if( id<=SQLITE_MUTEX_RECURSIVE && sqlite3_initialize() ) return 0;
  24708. if( id>SQLITE_MUTEX_RECURSIVE && sqlite3MutexInit() ) return 0;
  24709. #endif
  24710. assert( sqlite3GlobalConfig.mutex.xMutexAlloc );
  24711. return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
  24712. }
  24713. SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){
  24714. if( !sqlite3GlobalConfig.bCoreMutex ){
  24715. return 0;
  24716. }
  24717. assert( GLOBAL(int, mutexIsInit) );
  24718. assert( sqlite3GlobalConfig.mutex.xMutexAlloc );
  24719. return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
  24720. }
  24721. /*
  24722. ** Free a dynamic mutex.
  24723. */
  24724. SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){
  24725. if( p ){
  24726. assert( sqlite3GlobalConfig.mutex.xMutexFree );
  24727. sqlite3GlobalConfig.mutex.xMutexFree(p);
  24728. }
  24729. }
  24730. /*
  24731. ** Obtain the mutex p. If some other thread already has the mutex, block
  24732. ** until it can be obtained.
  24733. */
  24734. SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){
  24735. if( p ){
  24736. assert( sqlite3GlobalConfig.mutex.xMutexEnter );
  24737. sqlite3GlobalConfig.mutex.xMutexEnter(p);
  24738. }
  24739. }
  24740. /*
  24741. ** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
  24742. ** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
  24743. */
  24744. SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){
  24745. int rc = SQLITE_OK;
  24746. if( p ){
  24747. assert( sqlite3GlobalConfig.mutex.xMutexTry );
  24748. return sqlite3GlobalConfig.mutex.xMutexTry(p);
  24749. }
  24750. return rc;
  24751. }
  24752. /*
  24753. ** The sqlite3_mutex_leave() routine exits a mutex that was previously
  24754. ** entered by the same thread. The behavior is undefined if the mutex
  24755. ** is not currently entered. If a NULL pointer is passed as an argument
  24756. ** this function is a no-op.
  24757. */
  24758. SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){
  24759. if( p ){
  24760. assert( sqlite3GlobalConfig.mutex.xMutexLeave );
  24761. sqlite3GlobalConfig.mutex.xMutexLeave(p);
  24762. }
  24763. }
  24764. #ifndef NDEBUG
  24765. /*
  24766. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  24767. ** intended for use inside assert() statements.
  24768. */
  24769. SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){
  24770. assert( p==0 || sqlite3GlobalConfig.mutex.xMutexHeld );
  24771. return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);
  24772. }
  24773. SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){
  24774. assert( p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld );
  24775. return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);
  24776. }
  24777. #endif
  24778. #endif /* !defined(SQLITE_MUTEX_OMIT) */
  24779. /************** End of mutex.c ***********************************************/
  24780. /************** Begin file mutex_noop.c **************************************/
  24781. /*
  24782. ** 2008 October 07
  24783. **
  24784. ** The author disclaims copyright to this source code. In place of
  24785. ** a legal notice, here is a blessing:
  24786. **
  24787. ** May you do good and not evil.
  24788. ** May you find forgiveness for yourself and forgive others.
  24789. ** May you share freely, never taking more than you give.
  24790. **
  24791. *************************************************************************
  24792. ** This file contains the C functions that implement mutexes.
  24793. **
  24794. ** This implementation in this file does not provide any mutual
  24795. ** exclusion and is thus suitable for use only in applications
  24796. ** that use SQLite in a single thread. The routines defined
  24797. ** here are place-holders. Applications can substitute working
  24798. ** mutex routines at start-time using the
  24799. **
  24800. ** sqlite3_config(SQLITE_CONFIG_MUTEX,...)
  24801. **
  24802. ** interface.
  24803. **
  24804. ** If compiled with SQLITE_DEBUG, then additional logic is inserted
  24805. ** that does error checking on mutexes to make sure they are being
  24806. ** called correctly.
  24807. */
  24808. /* #include "sqliteInt.h" */
  24809. #ifndef SQLITE_MUTEX_OMIT
  24810. #ifndef SQLITE_DEBUG
  24811. /*
  24812. ** Stub routines for all mutex methods.
  24813. **
  24814. ** This routines provide no mutual exclusion or error checking.
  24815. */
  24816. static int noopMutexInit(void){ return SQLITE_OK; }
  24817. static int noopMutexEnd(void){ return SQLITE_OK; }
  24818. static sqlite3_mutex *noopMutexAlloc(int id){
  24819. UNUSED_PARAMETER(id);
  24820. return (sqlite3_mutex*)8;
  24821. }
  24822. static void noopMutexFree(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
  24823. static void noopMutexEnter(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
  24824. static int noopMutexTry(sqlite3_mutex *p){
  24825. UNUSED_PARAMETER(p);
  24826. return SQLITE_OK;
  24827. }
  24828. static void noopMutexLeave(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
  24829. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
  24830. static const sqlite3_mutex_methods sMutex = {
  24831. noopMutexInit,
  24832. noopMutexEnd,
  24833. noopMutexAlloc,
  24834. noopMutexFree,
  24835. noopMutexEnter,
  24836. noopMutexTry,
  24837. noopMutexLeave,
  24838. 0,
  24839. 0,
  24840. };
  24841. return &sMutex;
  24842. }
  24843. #endif /* !SQLITE_DEBUG */
  24844. #ifdef SQLITE_DEBUG
  24845. /*
  24846. ** In this implementation, error checking is provided for testing
  24847. ** and debugging purposes. The mutexes still do not provide any
  24848. ** mutual exclusion.
  24849. */
  24850. /*
  24851. ** The mutex object
  24852. */
  24853. typedef struct sqlite3_debug_mutex {
  24854. int id; /* The mutex type */
  24855. int cnt; /* Number of entries without a matching leave */
  24856. } sqlite3_debug_mutex;
  24857. /*
  24858. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  24859. ** intended for use inside assert() statements.
  24860. */
  24861. static int debugMutexHeld(sqlite3_mutex *pX){
  24862. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  24863. return p==0 || p->cnt>0;
  24864. }
  24865. static int debugMutexNotheld(sqlite3_mutex *pX){
  24866. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  24867. return p==0 || p->cnt==0;
  24868. }
  24869. /*
  24870. ** Initialize and deinitialize the mutex subsystem.
  24871. */
  24872. static int debugMutexInit(void){ return SQLITE_OK; }
  24873. static int debugMutexEnd(void){ return SQLITE_OK; }
  24874. /*
  24875. ** The sqlite3_mutex_alloc() routine allocates a new
  24876. ** mutex and returns a pointer to it. If it returns NULL
  24877. ** that means that a mutex could not be allocated.
  24878. */
  24879. static sqlite3_mutex *debugMutexAlloc(int id){
  24880. static sqlite3_debug_mutex aStatic[SQLITE_MUTEX_STATIC_VFS3 - 1];
  24881. sqlite3_debug_mutex *pNew = 0;
  24882. switch( id ){
  24883. case SQLITE_MUTEX_FAST:
  24884. case SQLITE_MUTEX_RECURSIVE: {
  24885. pNew = sqlite3Malloc(sizeof(*pNew));
  24886. if( pNew ){
  24887. pNew->id = id;
  24888. pNew->cnt = 0;
  24889. }
  24890. break;
  24891. }
  24892. default: {
  24893. #ifdef SQLITE_ENABLE_API_ARMOR
  24894. if( id-2<0 || id-2>=ArraySize(aStatic) ){
  24895. (void)SQLITE_MISUSE_BKPT;
  24896. return 0;
  24897. }
  24898. #endif
  24899. pNew = &aStatic[id-2];
  24900. pNew->id = id;
  24901. break;
  24902. }
  24903. }
  24904. return (sqlite3_mutex*)pNew;
  24905. }
  24906. /*
  24907. ** This routine deallocates a previously allocated mutex.
  24908. */
  24909. static void debugMutexFree(sqlite3_mutex *pX){
  24910. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  24911. assert( p->cnt==0 );
  24912. if( p->id==SQLITE_MUTEX_RECURSIVE || p->id==SQLITE_MUTEX_FAST ){
  24913. sqlite3_free(p);
  24914. }else{
  24915. #ifdef SQLITE_ENABLE_API_ARMOR
  24916. (void)SQLITE_MISUSE_BKPT;
  24917. #endif
  24918. }
  24919. }
  24920. /*
  24921. ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  24922. ** to enter a mutex. If another thread is already within the mutex,
  24923. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  24924. ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
  24925. ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
  24926. ** be entered multiple times by the same thread. In such cases the,
  24927. ** mutex must be exited an equal number of times before another thread
  24928. ** can enter. If the same thread tries to enter any other kind of mutex
  24929. ** more than once, the behavior is undefined.
  24930. */
  24931. static void debugMutexEnter(sqlite3_mutex *pX){
  24932. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  24933. assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
  24934. p->cnt++;
  24935. }
  24936. static int debugMutexTry(sqlite3_mutex *pX){
  24937. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  24938. assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
  24939. p->cnt++;
  24940. return SQLITE_OK;
  24941. }
  24942. /*
  24943. ** The sqlite3_mutex_leave() routine exits a mutex that was
  24944. ** previously entered by the same thread. The behavior
  24945. ** is undefined if the mutex is not currently entered or
  24946. ** is not currently allocated. SQLite will never do either.
  24947. */
  24948. static void debugMutexLeave(sqlite3_mutex *pX){
  24949. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  24950. assert( debugMutexHeld(pX) );
  24951. p->cnt--;
  24952. assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
  24953. }
  24954. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
  24955. static const sqlite3_mutex_methods sMutex = {
  24956. debugMutexInit,
  24957. debugMutexEnd,
  24958. debugMutexAlloc,
  24959. debugMutexFree,
  24960. debugMutexEnter,
  24961. debugMutexTry,
  24962. debugMutexLeave,
  24963. debugMutexHeld,
  24964. debugMutexNotheld
  24965. };
  24966. return &sMutex;
  24967. }
  24968. #endif /* SQLITE_DEBUG */
  24969. /*
  24970. ** If compiled with SQLITE_MUTEX_NOOP, then the no-op mutex implementation
  24971. ** is used regardless of the run-time threadsafety setting.
  24972. */
  24973. #ifdef SQLITE_MUTEX_NOOP
  24974. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
  24975. return sqlite3NoopMutex();
  24976. }
  24977. #endif /* defined(SQLITE_MUTEX_NOOP) */
  24978. #endif /* !defined(SQLITE_MUTEX_OMIT) */
  24979. /************** End of mutex_noop.c ******************************************/
  24980. /************** Begin file mutex_unix.c **************************************/
  24981. /*
  24982. ** 2007 August 28
  24983. **
  24984. ** The author disclaims copyright to this source code. In place of
  24985. ** a legal notice, here is a blessing:
  24986. **
  24987. ** May you do good and not evil.
  24988. ** May you find forgiveness for yourself and forgive others.
  24989. ** May you share freely, never taking more than you give.
  24990. **
  24991. *************************************************************************
  24992. ** This file contains the C functions that implement mutexes for pthreads
  24993. */
  24994. /* #include "sqliteInt.h" */
  24995. /*
  24996. ** The code in this file is only used if we are compiling threadsafe
  24997. ** under unix with pthreads.
  24998. **
  24999. ** Note that this implementation requires a version of pthreads that
  25000. ** supports recursive mutexes.
  25001. */
  25002. #ifdef SQLITE_MUTEX_PTHREADS
  25003. #include <pthread.h>
  25004. /*
  25005. ** The sqlite3_mutex.id, sqlite3_mutex.nRef, and sqlite3_mutex.owner fields
  25006. ** are necessary under two condidtions: (1) Debug builds and (2) using
  25007. ** home-grown mutexes. Encapsulate these conditions into a single #define.
  25008. */
  25009. #if defined(SQLITE_DEBUG) || defined(SQLITE_HOMEGROWN_RECURSIVE_MUTEX)
  25010. # define SQLITE_MUTEX_NREF 1
  25011. #else
  25012. # define SQLITE_MUTEX_NREF 0
  25013. #endif
  25014. /*
  25015. ** Each recursive mutex is an instance of the following structure.
  25016. */
  25017. struct sqlite3_mutex {
  25018. pthread_mutex_t mutex; /* Mutex controlling the lock */
  25019. #if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR)
  25020. int id; /* Mutex type */
  25021. #endif
  25022. #if SQLITE_MUTEX_NREF
  25023. volatile int nRef; /* Number of entrances */
  25024. volatile pthread_t owner; /* Thread that is within this mutex */
  25025. int trace; /* True to trace changes */
  25026. #endif
  25027. };
  25028. #if SQLITE_MUTEX_NREF
  25029. # define SQLITE3_MUTEX_INITIALIZER(id) \
  25030. {PTHREAD_MUTEX_INITIALIZER,id,0,(pthread_t)0,0}
  25031. #elif defined(SQLITE_ENABLE_API_ARMOR)
  25032. # define SQLITE3_MUTEX_INITIALIZER(id) { PTHREAD_MUTEX_INITIALIZER, id }
  25033. #else
  25034. #define SQLITE3_MUTEX_INITIALIZER(id) { PTHREAD_MUTEX_INITIALIZER }
  25035. #endif
  25036. /*
  25037. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  25038. ** intended for use only inside assert() statements. On some platforms,
  25039. ** there might be race conditions that can cause these routines to
  25040. ** deliver incorrect results. In particular, if pthread_equal() is
  25041. ** not an atomic operation, then these routines might delivery
  25042. ** incorrect results. On most platforms, pthread_equal() is a
  25043. ** comparison of two integers and is therefore atomic. But we are
  25044. ** told that HPUX is not such a platform. If so, then these routines
  25045. ** will not always work correctly on HPUX.
  25046. **
  25047. ** On those platforms where pthread_equal() is not atomic, SQLite
  25048. ** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
  25049. ** make sure no assert() statements are evaluated and hence these
  25050. ** routines are never called.
  25051. */
  25052. #if !defined(NDEBUG) || defined(SQLITE_DEBUG)
  25053. static int pthreadMutexHeld(sqlite3_mutex *p){
  25054. return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
  25055. }
  25056. static int pthreadMutexNotheld(sqlite3_mutex *p){
  25057. return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
  25058. }
  25059. #endif
  25060. /*
  25061. ** Try to provide a memory barrier operation, needed for initialization
  25062. ** and also for the implementation of xShmBarrier in the VFS in cases
  25063. ** where SQLite is compiled without mutexes.
  25064. */
  25065. SQLITE_PRIVATE void sqlite3MemoryBarrier(void){
  25066. #if defined(SQLITE_MEMORY_BARRIER)
  25067. SQLITE_MEMORY_BARRIER;
  25068. #elif defined(__GNUC__) && GCC_VERSION>=4001000
  25069. __sync_synchronize();
  25070. #endif
  25071. }
  25072. /*
  25073. ** Initialize and deinitialize the mutex subsystem.
  25074. */
  25075. static int pthreadMutexInit(void){ return SQLITE_OK; }
  25076. static int pthreadMutexEnd(void){ return SQLITE_OK; }
  25077. /*
  25078. ** The sqlite3_mutex_alloc() routine allocates a new
  25079. ** mutex and returns a pointer to it. If it returns NULL
  25080. ** that means that a mutex could not be allocated. SQLite
  25081. ** will unwind its stack and return an error. The argument
  25082. ** to sqlite3_mutex_alloc() is one of these integer constants:
  25083. **
  25084. ** <ul>
  25085. ** <li> SQLITE_MUTEX_FAST
  25086. ** <li> SQLITE_MUTEX_RECURSIVE
  25087. ** <li> SQLITE_MUTEX_STATIC_MASTER
  25088. ** <li> SQLITE_MUTEX_STATIC_MEM
  25089. ** <li> SQLITE_MUTEX_STATIC_OPEN
  25090. ** <li> SQLITE_MUTEX_STATIC_PRNG
  25091. ** <li> SQLITE_MUTEX_STATIC_LRU
  25092. ** <li> SQLITE_MUTEX_STATIC_PMEM
  25093. ** <li> SQLITE_MUTEX_STATIC_APP1
  25094. ** <li> SQLITE_MUTEX_STATIC_APP2
  25095. ** <li> SQLITE_MUTEX_STATIC_APP3
  25096. ** <li> SQLITE_MUTEX_STATIC_VFS1
  25097. ** <li> SQLITE_MUTEX_STATIC_VFS2
  25098. ** <li> SQLITE_MUTEX_STATIC_VFS3
  25099. ** </ul>
  25100. **
  25101. ** The first two constants cause sqlite3_mutex_alloc() to create
  25102. ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
  25103. ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
  25104. ** The mutex implementation does not need to make a distinction
  25105. ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
  25106. ** not want to. But SQLite will only request a recursive mutex in
  25107. ** cases where it really needs one. If a faster non-recursive mutex
  25108. ** implementation is available on the host platform, the mutex subsystem
  25109. ** might return such a mutex in response to SQLITE_MUTEX_FAST.
  25110. **
  25111. ** The other allowed parameters to sqlite3_mutex_alloc() each return
  25112. ** a pointer to a static preexisting mutex. Six static mutexes are
  25113. ** used by the current version of SQLite. Future versions of SQLite
  25114. ** may add additional static mutexes. Static mutexes are for internal
  25115. ** use by SQLite only. Applications that use SQLite mutexes should
  25116. ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
  25117. ** SQLITE_MUTEX_RECURSIVE.
  25118. **
  25119. ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
  25120. ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
  25121. ** returns a different mutex on every call. But for the static
  25122. ** mutex types, the same mutex is returned on every call that has
  25123. ** the same type number.
  25124. */
  25125. static sqlite3_mutex *pthreadMutexAlloc(int iType){
  25126. static sqlite3_mutex staticMutexes[] = {
  25127. SQLITE3_MUTEX_INITIALIZER(2),
  25128. SQLITE3_MUTEX_INITIALIZER(3),
  25129. SQLITE3_MUTEX_INITIALIZER(4),
  25130. SQLITE3_MUTEX_INITIALIZER(5),
  25131. SQLITE3_MUTEX_INITIALIZER(6),
  25132. SQLITE3_MUTEX_INITIALIZER(7),
  25133. SQLITE3_MUTEX_INITIALIZER(8),
  25134. SQLITE3_MUTEX_INITIALIZER(9),
  25135. SQLITE3_MUTEX_INITIALIZER(10),
  25136. SQLITE3_MUTEX_INITIALIZER(11),
  25137. SQLITE3_MUTEX_INITIALIZER(12),
  25138. SQLITE3_MUTEX_INITIALIZER(13)
  25139. };
  25140. sqlite3_mutex *p;
  25141. switch( iType ){
  25142. case SQLITE_MUTEX_RECURSIVE: {
  25143. p = sqlite3MallocZero( sizeof(*p) );
  25144. if( p ){
  25145. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  25146. /* If recursive mutexes are not available, we will have to
  25147. ** build our own. See below. */
  25148. pthread_mutex_init(&p->mutex, 0);
  25149. #else
  25150. /* Use a recursive mutex if it is available */
  25151. pthread_mutexattr_t recursiveAttr;
  25152. pthread_mutexattr_init(&recursiveAttr);
  25153. pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
  25154. pthread_mutex_init(&p->mutex, &recursiveAttr);
  25155. pthread_mutexattr_destroy(&recursiveAttr);
  25156. #endif
  25157. #if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR)
  25158. p->id = SQLITE_MUTEX_RECURSIVE;
  25159. #endif
  25160. }
  25161. break;
  25162. }
  25163. case SQLITE_MUTEX_FAST: {
  25164. p = sqlite3MallocZero( sizeof(*p) );
  25165. if( p ){
  25166. pthread_mutex_init(&p->mutex, 0);
  25167. #if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR)
  25168. p->id = SQLITE_MUTEX_FAST;
  25169. #endif
  25170. }
  25171. break;
  25172. }
  25173. default: {
  25174. #ifdef SQLITE_ENABLE_API_ARMOR
  25175. if( iType-2<0 || iType-2>=ArraySize(staticMutexes) ){
  25176. (void)SQLITE_MISUSE_BKPT;
  25177. return 0;
  25178. }
  25179. #endif
  25180. p = &staticMutexes[iType-2];
  25181. break;
  25182. }
  25183. }
  25184. #if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR)
  25185. assert( p==0 || p->id==iType );
  25186. #endif
  25187. return p;
  25188. }
  25189. /*
  25190. ** This routine deallocates a previously
  25191. ** allocated mutex. SQLite is careful to deallocate every
  25192. ** mutex that it allocates.
  25193. */
  25194. static void pthreadMutexFree(sqlite3_mutex *p){
  25195. assert( p->nRef==0 );
  25196. #if SQLITE_ENABLE_API_ARMOR
  25197. if( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE )
  25198. #endif
  25199. {
  25200. pthread_mutex_destroy(&p->mutex);
  25201. sqlite3_free(p);
  25202. }
  25203. #ifdef SQLITE_ENABLE_API_ARMOR
  25204. else{
  25205. (void)SQLITE_MISUSE_BKPT;
  25206. }
  25207. #endif
  25208. }
  25209. /*
  25210. ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  25211. ** to enter a mutex. If another thread is already within the mutex,
  25212. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  25213. ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
  25214. ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
  25215. ** be entered multiple times by the same thread. In such cases the,
  25216. ** mutex must be exited an equal number of times before another thread
  25217. ** can enter. If the same thread tries to enter any other kind of mutex
  25218. ** more than once, the behavior is undefined.
  25219. */
  25220. static void pthreadMutexEnter(sqlite3_mutex *p){
  25221. assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
  25222. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  25223. /* If recursive mutexes are not available, then we have to grow
  25224. ** our own. This implementation assumes that pthread_equal()
  25225. ** is atomic - that it cannot be deceived into thinking self
  25226. ** and p->owner are equal if p->owner changes between two values
  25227. ** that are not equal to self while the comparison is taking place.
  25228. ** This implementation also assumes a coherent cache - that
  25229. ** separate processes cannot read different values from the same
  25230. ** address at the same time. If either of these two conditions
  25231. ** are not met, then the mutexes will fail and problems will result.
  25232. */
  25233. {
  25234. pthread_t self = pthread_self();
  25235. if( p->nRef>0 && pthread_equal(p->owner, self) ){
  25236. p->nRef++;
  25237. }else{
  25238. pthread_mutex_lock(&p->mutex);
  25239. assert( p->nRef==0 );
  25240. p->owner = self;
  25241. p->nRef = 1;
  25242. }
  25243. }
  25244. #else
  25245. /* Use the built-in recursive mutexes if they are available.
  25246. */
  25247. pthread_mutex_lock(&p->mutex);
  25248. #if SQLITE_MUTEX_NREF
  25249. assert( p->nRef>0 || p->owner==0 );
  25250. p->owner = pthread_self();
  25251. p->nRef++;
  25252. #endif
  25253. #endif
  25254. #ifdef SQLITE_DEBUG
  25255. if( p->trace ){
  25256. printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  25257. }
  25258. #endif
  25259. }
  25260. static int pthreadMutexTry(sqlite3_mutex *p){
  25261. int rc;
  25262. assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
  25263. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  25264. /* If recursive mutexes are not available, then we have to grow
  25265. ** our own. This implementation assumes that pthread_equal()
  25266. ** is atomic - that it cannot be deceived into thinking self
  25267. ** and p->owner are equal if p->owner changes between two values
  25268. ** that are not equal to self while the comparison is taking place.
  25269. ** This implementation also assumes a coherent cache - that
  25270. ** separate processes cannot read different values from the same
  25271. ** address at the same time. If either of these two conditions
  25272. ** are not met, then the mutexes will fail and problems will result.
  25273. */
  25274. {
  25275. pthread_t self = pthread_self();
  25276. if( p->nRef>0 && pthread_equal(p->owner, self) ){
  25277. p->nRef++;
  25278. rc = SQLITE_OK;
  25279. }else if( pthread_mutex_trylock(&p->mutex)==0 ){
  25280. assert( p->nRef==0 );
  25281. p->owner = self;
  25282. p->nRef = 1;
  25283. rc = SQLITE_OK;
  25284. }else{
  25285. rc = SQLITE_BUSY;
  25286. }
  25287. }
  25288. #else
  25289. /* Use the built-in recursive mutexes if they are available.
  25290. */
  25291. if( pthread_mutex_trylock(&p->mutex)==0 ){
  25292. #if SQLITE_MUTEX_NREF
  25293. p->owner = pthread_self();
  25294. p->nRef++;
  25295. #endif
  25296. rc = SQLITE_OK;
  25297. }else{
  25298. rc = SQLITE_BUSY;
  25299. }
  25300. #endif
  25301. #ifdef SQLITE_DEBUG
  25302. if( rc==SQLITE_OK && p->trace ){
  25303. printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  25304. }
  25305. #endif
  25306. return rc;
  25307. }
  25308. /*
  25309. ** The sqlite3_mutex_leave() routine exits a mutex that was
  25310. ** previously entered by the same thread. The behavior
  25311. ** is undefined if the mutex is not currently entered or
  25312. ** is not currently allocated. SQLite will never do either.
  25313. */
  25314. static void pthreadMutexLeave(sqlite3_mutex *p){
  25315. assert( pthreadMutexHeld(p) );
  25316. #if SQLITE_MUTEX_NREF
  25317. p->nRef--;
  25318. if( p->nRef==0 ) p->owner = 0;
  25319. #endif
  25320. assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
  25321. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  25322. if( p->nRef==0 ){
  25323. pthread_mutex_unlock(&p->mutex);
  25324. }
  25325. #else
  25326. pthread_mutex_unlock(&p->mutex);
  25327. #endif
  25328. #ifdef SQLITE_DEBUG
  25329. if( p->trace ){
  25330. printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  25331. }
  25332. #endif
  25333. }
  25334. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
  25335. static const sqlite3_mutex_methods sMutex = {
  25336. pthreadMutexInit,
  25337. pthreadMutexEnd,
  25338. pthreadMutexAlloc,
  25339. pthreadMutexFree,
  25340. pthreadMutexEnter,
  25341. pthreadMutexTry,
  25342. pthreadMutexLeave,
  25343. #ifdef SQLITE_DEBUG
  25344. pthreadMutexHeld,
  25345. pthreadMutexNotheld
  25346. #else
  25347. 0,
  25348. 0
  25349. #endif
  25350. };
  25351. return &sMutex;
  25352. }
  25353. #endif /* SQLITE_MUTEX_PTHREADS */
  25354. /************** End of mutex_unix.c ******************************************/
  25355. /************** Begin file mutex_w32.c ***************************************/
  25356. /*
  25357. ** 2007 August 14
  25358. **
  25359. ** The author disclaims copyright to this source code. In place of
  25360. ** a legal notice, here is a blessing:
  25361. **
  25362. ** May you do good and not evil.
  25363. ** May you find forgiveness for yourself and forgive others.
  25364. ** May you share freely, never taking more than you give.
  25365. **
  25366. *************************************************************************
  25367. ** This file contains the C functions that implement mutexes for Win32.
  25368. */
  25369. /* #include "sqliteInt.h" */
  25370. #if SQLITE_OS_WIN
  25371. /*
  25372. ** Include code that is common to all os_*.c files
  25373. */
  25374. /************** Include os_common.h in the middle of mutex_w32.c *************/
  25375. /************** Begin file os_common.h ***************************************/
  25376. /*
  25377. ** 2004 May 22
  25378. **
  25379. ** The author disclaims copyright to this source code. In place of
  25380. ** a legal notice, here is a blessing:
  25381. **
  25382. ** May you do good and not evil.
  25383. ** May you find forgiveness for yourself and forgive others.
  25384. ** May you share freely, never taking more than you give.
  25385. **
  25386. ******************************************************************************
  25387. **
  25388. ** This file contains macros and a little bit of code that is common to
  25389. ** all of the platform-specific files (os_*.c) and is #included into those
  25390. ** files.
  25391. **
  25392. ** This file should be #included by the os_*.c files only. It is not a
  25393. ** general purpose header file.
  25394. */
  25395. #ifndef _OS_COMMON_H_
  25396. #define _OS_COMMON_H_
  25397. /*
  25398. ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
  25399. ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
  25400. ** switch. The following code should catch this problem at compile-time.
  25401. */
  25402. #ifdef MEMORY_DEBUG
  25403. # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
  25404. #endif
  25405. /*
  25406. ** Macros for performance tracing. Normally turned off. Only works
  25407. ** on i486 hardware.
  25408. */
  25409. #ifdef SQLITE_PERFORMANCE_TRACE
  25410. /*
  25411. ** hwtime.h contains inline assembler code for implementing
  25412. ** high-performance timing routines.
  25413. */
  25414. /************** Include hwtime.h in the middle of os_common.h ****************/
  25415. /************** Begin file hwtime.h ******************************************/
  25416. /*
  25417. ** 2008 May 27
  25418. **
  25419. ** The author disclaims copyright to this source code. In place of
  25420. ** a legal notice, here is a blessing:
  25421. **
  25422. ** May you do good and not evil.
  25423. ** May you find forgiveness for yourself and forgive others.
  25424. ** May you share freely, never taking more than you give.
  25425. **
  25426. ******************************************************************************
  25427. **
  25428. ** This file contains inline asm code for retrieving "high-performance"
  25429. ** counters for x86 and x86_64 class CPUs.
  25430. */
  25431. #ifndef SQLITE_HWTIME_H
  25432. #define SQLITE_HWTIME_H
  25433. /*
  25434. ** The following routine only works on pentium-class (or newer) processors.
  25435. ** It uses the RDTSC opcode to read the cycle count value out of the
  25436. ** processor and returns that value. This can be used for high-res
  25437. ** profiling.
  25438. */
  25439. #if !defined(__STRICT_ANSI__) && \
  25440. (defined(__GNUC__) || defined(_MSC_VER)) && \
  25441. (defined(i386) || defined(__i386__) || defined(_M_IX86))
  25442. #if defined(__GNUC__)
  25443. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  25444. unsigned int lo, hi;
  25445. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  25446. return (sqlite_uint64)hi << 32 | lo;
  25447. }
  25448. #elif defined(_MSC_VER)
  25449. __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
  25450. __asm {
  25451. rdtsc
  25452. ret ; return value at EDX:EAX
  25453. }
  25454. }
  25455. #endif
  25456. #elif !defined(__STRICT_ANSI__) && (defined(__GNUC__) && defined(__x86_64__))
  25457. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  25458. unsigned long val;
  25459. __asm__ __volatile__ ("rdtsc" : "=A" (val));
  25460. return val;
  25461. }
  25462. #elif !defined(__STRICT_ANSI__) && (defined(__GNUC__) && defined(__ppc__))
  25463. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  25464. unsigned long long retval;
  25465. unsigned long junk;
  25466. __asm__ __volatile__ ("\n\
  25467. 1: mftbu %1\n\
  25468. mftb %L0\n\
  25469. mftbu %0\n\
  25470. cmpw %0,%1\n\
  25471. bne 1b"
  25472. : "=r" (retval), "=r" (junk));
  25473. return retval;
  25474. }
  25475. #else
  25476. /*
  25477. ** asm() is needed for hardware timing support. Without asm(),
  25478. ** disable the sqlite3Hwtime() routine.
  25479. **
  25480. ** sqlite3Hwtime() is only used for some obscure debugging
  25481. ** and analysis configurations, not in any deliverable, so this
  25482. ** should not be a great loss.
  25483. */
  25484. SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
  25485. #endif
  25486. #endif /* !defined(SQLITE_HWTIME_H) */
  25487. /************** End of hwtime.h **********************************************/
  25488. /************** Continuing where we left off in os_common.h ******************/
  25489. static sqlite_uint64 g_start;
  25490. static sqlite_uint64 g_elapsed;
  25491. #define TIMER_START g_start=sqlite3Hwtime()
  25492. #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
  25493. #define TIMER_ELAPSED g_elapsed
  25494. #else
  25495. #define TIMER_START
  25496. #define TIMER_END
  25497. #define TIMER_ELAPSED ((sqlite_uint64)0)
  25498. #endif
  25499. /*
  25500. ** If we compile with the SQLITE_TEST macro set, then the following block
  25501. ** of code will give us the ability to simulate a disk I/O error. This
  25502. ** is used for testing the I/O recovery logic.
  25503. */
  25504. #if defined(SQLITE_TEST)
  25505. SQLITE_API extern int sqlite3_io_error_hit;
  25506. SQLITE_API extern int sqlite3_io_error_hardhit;
  25507. SQLITE_API extern int sqlite3_io_error_pending;
  25508. SQLITE_API extern int sqlite3_io_error_persist;
  25509. SQLITE_API extern int sqlite3_io_error_benign;
  25510. SQLITE_API extern int sqlite3_diskfull_pending;
  25511. SQLITE_API extern int sqlite3_diskfull;
  25512. #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
  25513. #define SimulateIOError(CODE) \
  25514. if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
  25515. || sqlite3_io_error_pending-- == 1 ) \
  25516. { local_ioerr(); CODE; }
  25517. static void local_ioerr(){
  25518. IOTRACE(("IOERR\n"));
  25519. sqlite3_io_error_hit++;
  25520. if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
  25521. }
  25522. #define SimulateDiskfullError(CODE) \
  25523. if( sqlite3_diskfull_pending ){ \
  25524. if( sqlite3_diskfull_pending == 1 ){ \
  25525. local_ioerr(); \
  25526. sqlite3_diskfull = 1; \
  25527. sqlite3_io_error_hit = 1; \
  25528. CODE; \
  25529. }else{ \
  25530. sqlite3_diskfull_pending--; \
  25531. } \
  25532. }
  25533. #else
  25534. #define SimulateIOErrorBenign(X)
  25535. #define SimulateIOError(A)
  25536. #define SimulateDiskfullError(A)
  25537. #endif /* defined(SQLITE_TEST) */
  25538. /*
  25539. ** When testing, keep a count of the number of open files.
  25540. */
  25541. #if defined(SQLITE_TEST)
  25542. SQLITE_API extern int sqlite3_open_file_count;
  25543. #define OpenCounter(X) sqlite3_open_file_count+=(X)
  25544. #else
  25545. #define OpenCounter(X)
  25546. #endif /* defined(SQLITE_TEST) */
  25547. #endif /* !defined(_OS_COMMON_H_) */
  25548. /************** End of os_common.h *******************************************/
  25549. /************** Continuing where we left off in mutex_w32.c ******************/
  25550. /*
  25551. ** Include the header file for the Windows VFS.
  25552. */
  25553. /************** Include os_win.h in the middle of mutex_w32.c ****************/
  25554. /************** Begin file os_win.h ******************************************/
  25555. /*
  25556. ** 2013 November 25
  25557. **
  25558. ** The author disclaims copyright to this source code. In place of
  25559. ** a legal notice, here is a blessing:
  25560. **
  25561. ** May you do good and not evil.
  25562. ** May you find forgiveness for yourself and forgive others.
  25563. ** May you share freely, never taking more than you give.
  25564. **
  25565. ******************************************************************************
  25566. **
  25567. ** This file contains code that is specific to Windows.
  25568. */
  25569. #ifndef SQLITE_OS_WIN_H
  25570. #define SQLITE_OS_WIN_H
  25571. /*
  25572. ** Include the primary Windows SDK header file.
  25573. */
  25574. #include "windows.h"
  25575. #ifdef __CYGWIN__
  25576. # include <sys/cygwin.h>
  25577. # include <errno.h> /* amalgamator: dontcache */
  25578. #endif
  25579. /*
  25580. ** Determine if we are dealing with Windows NT.
  25581. **
  25582. ** We ought to be able to determine if we are compiling for Windows 9x or
  25583. ** Windows NT using the _WIN32_WINNT macro as follows:
  25584. **
  25585. ** #if defined(_WIN32_WINNT)
  25586. ** # define SQLITE_OS_WINNT 1
  25587. ** #else
  25588. ** # define SQLITE_OS_WINNT 0
  25589. ** #endif
  25590. **
  25591. ** However, Visual Studio 2005 does not set _WIN32_WINNT by default, as
  25592. ** it ought to, so the above test does not work. We'll just assume that
  25593. ** everything is Windows NT unless the programmer explicitly says otherwise
  25594. ** by setting SQLITE_OS_WINNT to 0.
  25595. */
  25596. #if SQLITE_OS_WIN && !defined(SQLITE_OS_WINNT)
  25597. # define SQLITE_OS_WINNT 1
  25598. #endif
  25599. /*
  25600. ** Determine if we are dealing with Windows CE - which has a much reduced
  25601. ** API.
  25602. */
  25603. #if defined(_WIN32_WCE)
  25604. # define SQLITE_OS_WINCE 1
  25605. #else
  25606. # define SQLITE_OS_WINCE 0
  25607. #endif
  25608. /*
  25609. ** Determine if we are dealing with WinRT, which provides only a subset of
  25610. ** the full Win32 API.
  25611. */
  25612. #if !defined(SQLITE_OS_WINRT)
  25613. # define SQLITE_OS_WINRT 0
  25614. #endif
  25615. /*
  25616. ** For WinCE, some API function parameters do not appear to be declared as
  25617. ** volatile.
  25618. */
  25619. #if SQLITE_OS_WINCE
  25620. # define SQLITE_WIN32_VOLATILE
  25621. #else
  25622. # define SQLITE_WIN32_VOLATILE volatile
  25623. #endif
  25624. /*
  25625. ** For some Windows sub-platforms, the _beginthreadex() / _endthreadex()
  25626. ** functions are not available (e.g. those not using MSVC, Cygwin, etc).
  25627. */
  25628. #if SQLITE_OS_WIN && !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && \
  25629. SQLITE_THREADSAFE>0 && !defined(__CYGWIN__)
  25630. # define SQLITE_OS_WIN_THREADS 1
  25631. #else
  25632. # define SQLITE_OS_WIN_THREADS 0
  25633. #endif
  25634. #endif /* SQLITE_OS_WIN_H */
  25635. /************** End of os_win.h **********************************************/
  25636. /************** Continuing where we left off in mutex_w32.c ******************/
  25637. #endif
  25638. /*
  25639. ** The code in this file is only used if we are compiling multithreaded
  25640. ** on a Win32 system.
  25641. */
  25642. #ifdef SQLITE_MUTEX_W32
  25643. /*
  25644. ** Each recursive mutex is an instance of the following structure.
  25645. */
  25646. struct sqlite3_mutex {
  25647. CRITICAL_SECTION mutex; /* Mutex controlling the lock */
  25648. int id; /* Mutex type */
  25649. #ifdef SQLITE_DEBUG
  25650. volatile int nRef; /* Number of enterances */
  25651. volatile DWORD owner; /* Thread holding this mutex */
  25652. volatile LONG trace; /* True to trace changes */
  25653. #endif
  25654. };
  25655. /*
  25656. ** These are the initializer values used when declaring a "static" mutex
  25657. ** on Win32. It should be noted that all mutexes require initialization
  25658. ** on the Win32 platform.
  25659. */
  25660. #define SQLITE_W32_MUTEX_INITIALIZER { 0 }
  25661. #ifdef SQLITE_DEBUG
  25662. #define SQLITE3_MUTEX_INITIALIZER(id) { SQLITE_W32_MUTEX_INITIALIZER, id, \
  25663. 0L, (DWORD)0, 0 }
  25664. #else
  25665. #define SQLITE3_MUTEX_INITIALIZER(id) { SQLITE_W32_MUTEX_INITIALIZER, id }
  25666. #endif
  25667. #ifdef SQLITE_DEBUG
  25668. /*
  25669. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  25670. ** intended for use only inside assert() statements.
  25671. */
  25672. static int winMutexHeld(sqlite3_mutex *p){
  25673. return p->nRef!=0 && p->owner==GetCurrentThreadId();
  25674. }
  25675. static int winMutexNotheld2(sqlite3_mutex *p, DWORD tid){
  25676. return p->nRef==0 || p->owner!=tid;
  25677. }
  25678. static int winMutexNotheld(sqlite3_mutex *p){
  25679. DWORD tid = GetCurrentThreadId();
  25680. return winMutexNotheld2(p, tid);
  25681. }
  25682. #endif
  25683. /*
  25684. ** Try to provide a memory barrier operation, needed for initialization
  25685. ** and also for the xShmBarrier method of the VFS in cases when SQLite is
  25686. ** compiled without mutexes (SQLITE_THREADSAFE=0).
  25687. */
  25688. SQLITE_PRIVATE void sqlite3MemoryBarrier(void){
  25689. #if defined(SQLITE_MEMORY_BARRIER)
  25690. SQLITE_MEMORY_BARRIER;
  25691. #elif defined(__GNUC__)
  25692. __sync_synchronize();
  25693. #elif MSVC_VERSION>=1300
  25694. _ReadWriteBarrier();
  25695. #elif defined(MemoryBarrier)
  25696. MemoryBarrier();
  25697. #endif
  25698. }
  25699. /*
  25700. ** Initialize and deinitialize the mutex subsystem.
  25701. */
  25702. static sqlite3_mutex winMutex_staticMutexes[] = {
  25703. SQLITE3_MUTEX_INITIALIZER(2),
  25704. SQLITE3_MUTEX_INITIALIZER(3),
  25705. SQLITE3_MUTEX_INITIALIZER(4),
  25706. SQLITE3_MUTEX_INITIALIZER(5),
  25707. SQLITE3_MUTEX_INITIALIZER(6),
  25708. SQLITE3_MUTEX_INITIALIZER(7),
  25709. SQLITE3_MUTEX_INITIALIZER(8),
  25710. SQLITE3_MUTEX_INITIALIZER(9),
  25711. SQLITE3_MUTEX_INITIALIZER(10),
  25712. SQLITE3_MUTEX_INITIALIZER(11),
  25713. SQLITE3_MUTEX_INITIALIZER(12),
  25714. SQLITE3_MUTEX_INITIALIZER(13)
  25715. };
  25716. static int winMutex_isInit = 0;
  25717. static int winMutex_isNt = -1; /* <0 means "need to query" */
  25718. /* As the winMutexInit() and winMutexEnd() functions are called as part
  25719. ** of the sqlite3_initialize() and sqlite3_shutdown() processing, the
  25720. ** "interlocked" magic used here is probably not strictly necessary.
  25721. */
  25722. static LONG SQLITE_WIN32_VOLATILE winMutex_lock = 0;
  25723. SQLITE_API int sqlite3_win32_is_nt(void); /* os_win.c */
  25724. SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds); /* os_win.c */
  25725. static int winMutexInit(void){
  25726. /* The first to increment to 1 does actual initialization */
  25727. if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ){
  25728. int i;
  25729. for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
  25730. #if SQLITE_OS_WINRT
  25731. InitializeCriticalSectionEx(&winMutex_staticMutexes[i].mutex, 0, 0);
  25732. #else
  25733. InitializeCriticalSection(&winMutex_staticMutexes[i].mutex);
  25734. #endif
  25735. }
  25736. winMutex_isInit = 1;
  25737. }else{
  25738. /* Another thread is (in the process of) initializing the static
  25739. ** mutexes */
  25740. while( !winMutex_isInit ){
  25741. sqlite3_win32_sleep(1);
  25742. }
  25743. }
  25744. return SQLITE_OK;
  25745. }
  25746. static int winMutexEnd(void){
  25747. /* The first to decrement to 0 does actual shutdown
  25748. ** (which should be the last to shutdown.) */
  25749. if( InterlockedCompareExchange(&winMutex_lock, 0, 1)==1 ){
  25750. if( winMutex_isInit==1 ){
  25751. int i;
  25752. for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
  25753. DeleteCriticalSection(&winMutex_staticMutexes[i].mutex);
  25754. }
  25755. winMutex_isInit = 0;
  25756. }
  25757. }
  25758. return SQLITE_OK;
  25759. }
  25760. /*
  25761. ** The sqlite3_mutex_alloc() routine allocates a new
  25762. ** mutex and returns a pointer to it. If it returns NULL
  25763. ** that means that a mutex could not be allocated. SQLite
  25764. ** will unwind its stack and return an error. The argument
  25765. ** to sqlite3_mutex_alloc() is one of these integer constants:
  25766. **
  25767. ** <ul>
  25768. ** <li> SQLITE_MUTEX_FAST
  25769. ** <li> SQLITE_MUTEX_RECURSIVE
  25770. ** <li> SQLITE_MUTEX_STATIC_MASTER
  25771. ** <li> SQLITE_MUTEX_STATIC_MEM
  25772. ** <li> SQLITE_MUTEX_STATIC_OPEN
  25773. ** <li> SQLITE_MUTEX_STATIC_PRNG
  25774. ** <li> SQLITE_MUTEX_STATIC_LRU
  25775. ** <li> SQLITE_MUTEX_STATIC_PMEM
  25776. ** <li> SQLITE_MUTEX_STATIC_APP1
  25777. ** <li> SQLITE_MUTEX_STATIC_APP2
  25778. ** <li> SQLITE_MUTEX_STATIC_APP3
  25779. ** <li> SQLITE_MUTEX_STATIC_VFS1
  25780. ** <li> SQLITE_MUTEX_STATIC_VFS2
  25781. ** <li> SQLITE_MUTEX_STATIC_VFS3
  25782. ** </ul>
  25783. **
  25784. ** The first two constants cause sqlite3_mutex_alloc() to create
  25785. ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
  25786. ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
  25787. ** The mutex implementation does not need to make a distinction
  25788. ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
  25789. ** not want to. But SQLite will only request a recursive mutex in
  25790. ** cases where it really needs one. If a faster non-recursive mutex
  25791. ** implementation is available on the host platform, the mutex subsystem
  25792. ** might return such a mutex in response to SQLITE_MUTEX_FAST.
  25793. **
  25794. ** The other allowed parameters to sqlite3_mutex_alloc() each return
  25795. ** a pointer to a static preexisting mutex. Six static mutexes are
  25796. ** used by the current version of SQLite. Future versions of SQLite
  25797. ** may add additional static mutexes. Static mutexes are for internal
  25798. ** use by SQLite only. Applications that use SQLite mutexes should
  25799. ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
  25800. ** SQLITE_MUTEX_RECURSIVE.
  25801. **
  25802. ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
  25803. ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
  25804. ** returns a different mutex on every call. But for the static
  25805. ** mutex types, the same mutex is returned on every call that has
  25806. ** the same type number.
  25807. */
  25808. static sqlite3_mutex *winMutexAlloc(int iType){
  25809. sqlite3_mutex *p;
  25810. switch( iType ){
  25811. case SQLITE_MUTEX_FAST:
  25812. case SQLITE_MUTEX_RECURSIVE: {
  25813. p = sqlite3MallocZero( sizeof(*p) );
  25814. if( p ){
  25815. p->id = iType;
  25816. #ifdef SQLITE_DEBUG
  25817. #ifdef SQLITE_WIN32_MUTEX_TRACE_DYNAMIC
  25818. p->trace = 1;
  25819. #endif
  25820. #endif
  25821. #if SQLITE_OS_WINRT
  25822. InitializeCriticalSectionEx(&p->mutex, 0, 0);
  25823. #else
  25824. InitializeCriticalSection(&p->mutex);
  25825. #endif
  25826. }
  25827. break;
  25828. }
  25829. default: {
  25830. #ifdef SQLITE_ENABLE_API_ARMOR
  25831. if( iType-2<0 || iType-2>=ArraySize(winMutex_staticMutexes) ){
  25832. (void)SQLITE_MISUSE_BKPT;
  25833. return 0;
  25834. }
  25835. #endif
  25836. p = &winMutex_staticMutexes[iType-2];
  25837. #ifdef SQLITE_DEBUG
  25838. #ifdef SQLITE_WIN32_MUTEX_TRACE_STATIC
  25839. InterlockedCompareExchange(&p->trace, 1, 0);
  25840. #endif
  25841. #endif
  25842. break;
  25843. }
  25844. }
  25845. assert( p==0 || p->id==iType );
  25846. return p;
  25847. }
  25848. /*
  25849. ** This routine deallocates a previously
  25850. ** allocated mutex. SQLite is careful to deallocate every
  25851. ** mutex that it allocates.
  25852. */
  25853. static void winMutexFree(sqlite3_mutex *p){
  25854. assert( p );
  25855. assert( p->nRef==0 && p->owner==0 );
  25856. if( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE ){
  25857. DeleteCriticalSection(&p->mutex);
  25858. sqlite3_free(p);
  25859. }else{
  25860. #ifdef SQLITE_ENABLE_API_ARMOR
  25861. (void)SQLITE_MISUSE_BKPT;
  25862. #endif
  25863. }
  25864. }
  25865. /*
  25866. ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  25867. ** to enter a mutex. If another thread is already within the mutex,
  25868. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  25869. ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
  25870. ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
  25871. ** be entered multiple times by the same thread. In such cases the,
  25872. ** mutex must be exited an equal number of times before another thread
  25873. ** can enter. If the same thread tries to enter any other kind of mutex
  25874. ** more than once, the behavior is undefined.
  25875. */
  25876. static void winMutexEnter(sqlite3_mutex *p){
  25877. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  25878. DWORD tid = GetCurrentThreadId();
  25879. #endif
  25880. #ifdef SQLITE_DEBUG
  25881. assert( p );
  25882. assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
  25883. #else
  25884. assert( p );
  25885. #endif
  25886. assert( winMutex_isInit==1 );
  25887. EnterCriticalSection(&p->mutex);
  25888. #ifdef SQLITE_DEBUG
  25889. assert( p->nRef>0 || p->owner==0 );
  25890. p->owner = tid;
  25891. p->nRef++;
  25892. if( p->trace ){
  25893. OSTRACE(("ENTER-MUTEX tid=%lu, mutex(%d)=%p (%d), nRef=%d\n",
  25894. tid, p->id, p, p->trace, p->nRef));
  25895. }
  25896. #endif
  25897. }
  25898. static int winMutexTry(sqlite3_mutex *p){
  25899. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  25900. DWORD tid = GetCurrentThreadId();
  25901. #endif
  25902. int rc = SQLITE_BUSY;
  25903. assert( p );
  25904. assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
  25905. /*
  25906. ** The sqlite3_mutex_try() routine is very rarely used, and when it
  25907. ** is used it is merely an optimization. So it is OK for it to always
  25908. ** fail.
  25909. **
  25910. ** The TryEnterCriticalSection() interface is only available on WinNT.
  25911. ** And some windows compilers complain if you try to use it without
  25912. ** first doing some #defines that prevent SQLite from building on Win98.
  25913. ** For that reason, we will omit this optimization for now. See
  25914. ** ticket #2685.
  25915. */
  25916. #if defined(_WIN32_WINNT) && _WIN32_WINNT >= 0x0400
  25917. assert( winMutex_isInit==1 );
  25918. assert( winMutex_isNt>=-1 && winMutex_isNt<=1 );
  25919. if( winMutex_isNt<0 ){
  25920. winMutex_isNt = sqlite3_win32_is_nt();
  25921. }
  25922. assert( winMutex_isNt==0 || winMutex_isNt==1 );
  25923. if( winMutex_isNt && TryEnterCriticalSection(&p->mutex) ){
  25924. #ifdef SQLITE_DEBUG
  25925. p->owner = tid;
  25926. p->nRef++;
  25927. #endif
  25928. rc = SQLITE_OK;
  25929. }
  25930. #else
  25931. UNUSED_PARAMETER(p);
  25932. #endif
  25933. #ifdef SQLITE_DEBUG
  25934. if( p->trace ){
  25935. OSTRACE(("TRY-MUTEX tid=%lu, mutex(%d)=%p (%d), owner=%lu, nRef=%d, rc=%s\n",
  25936. tid, p->id, p, p->trace, p->owner, p->nRef, sqlite3ErrName(rc)));
  25937. }
  25938. #endif
  25939. return rc;
  25940. }
  25941. /*
  25942. ** The sqlite3_mutex_leave() routine exits a mutex that was
  25943. ** previously entered by the same thread. The behavior
  25944. ** is undefined if the mutex is not currently entered or
  25945. ** is not currently allocated. SQLite will never do either.
  25946. */
  25947. static void winMutexLeave(sqlite3_mutex *p){
  25948. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  25949. DWORD tid = GetCurrentThreadId();
  25950. #endif
  25951. assert( p );
  25952. #ifdef SQLITE_DEBUG
  25953. assert( p->nRef>0 );
  25954. assert( p->owner==tid );
  25955. p->nRef--;
  25956. if( p->nRef==0 ) p->owner = 0;
  25957. assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
  25958. #endif
  25959. assert( winMutex_isInit==1 );
  25960. LeaveCriticalSection(&p->mutex);
  25961. #ifdef SQLITE_DEBUG
  25962. if( p->trace ){
  25963. OSTRACE(("LEAVE-MUTEX tid=%lu, mutex(%d)=%p (%d), nRef=%d\n",
  25964. tid, p->id, p, p->trace, p->nRef));
  25965. }
  25966. #endif
  25967. }
  25968. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
  25969. static const sqlite3_mutex_methods sMutex = {
  25970. winMutexInit,
  25971. winMutexEnd,
  25972. winMutexAlloc,
  25973. winMutexFree,
  25974. winMutexEnter,
  25975. winMutexTry,
  25976. winMutexLeave,
  25977. #ifdef SQLITE_DEBUG
  25978. winMutexHeld,
  25979. winMutexNotheld
  25980. #else
  25981. 0,
  25982. 0
  25983. #endif
  25984. };
  25985. return &sMutex;
  25986. }
  25987. #endif /* SQLITE_MUTEX_W32 */
  25988. /************** End of mutex_w32.c *******************************************/
  25989. /************** Begin file malloc.c ******************************************/
  25990. /*
  25991. ** 2001 September 15
  25992. **
  25993. ** The author disclaims copyright to this source code. In place of
  25994. ** a legal notice, here is a blessing:
  25995. **
  25996. ** May you do good and not evil.
  25997. ** May you find forgiveness for yourself and forgive others.
  25998. ** May you share freely, never taking more than you give.
  25999. **
  26000. *************************************************************************
  26001. **
  26002. ** Memory allocation functions used throughout sqlite.
  26003. */
  26004. /* #include "sqliteInt.h" */
  26005. /* #include <stdarg.h> */
  26006. /*
  26007. ** Attempt to release up to n bytes of non-essential memory currently
  26008. ** held by SQLite. An example of non-essential memory is memory used to
  26009. ** cache database pages that are not currently in use.
  26010. */
  26011. SQLITE_API int sqlite3_release_memory(int n){
  26012. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  26013. return sqlite3PcacheReleaseMemory(n);
  26014. #else
  26015. /* IMPLEMENTATION-OF: R-34391-24921 The sqlite3_release_memory() routine
  26016. ** is a no-op returning zero if SQLite is not compiled with
  26017. ** SQLITE_ENABLE_MEMORY_MANAGEMENT. */
  26018. UNUSED_PARAMETER(n);
  26019. return 0;
  26020. #endif
  26021. }
  26022. /*
  26023. ** Default value of the hard heap limit. 0 means "no limit".
  26024. */
  26025. #ifndef SQLITE_MAX_MEMORY
  26026. # define SQLITE_MAX_MEMORY 0
  26027. #endif
  26028. /*
  26029. ** State information local to the memory allocation subsystem.
  26030. */
  26031. static SQLITE_WSD struct Mem0Global {
  26032. sqlite3_mutex *mutex; /* Mutex to serialize access */
  26033. sqlite3_int64 alarmThreshold; /* The soft heap limit */
  26034. sqlite3_int64 hardLimit; /* The hard upper bound on memory */
  26035. /*
  26036. ** True if heap is nearly "full" where "full" is defined by the
  26037. ** sqlite3_soft_heap_limit() setting.
  26038. */
  26039. int nearlyFull;
  26040. } mem0 = { 0, SQLITE_MAX_MEMORY, SQLITE_MAX_MEMORY, 0 };
  26041. #define mem0 GLOBAL(struct Mem0Global, mem0)
  26042. /*
  26043. ** Return the memory allocator mutex. sqlite3_status() needs it.
  26044. */
  26045. SQLITE_PRIVATE sqlite3_mutex *sqlite3MallocMutex(void){
  26046. return mem0.mutex;
  26047. }
  26048. #ifndef SQLITE_OMIT_DEPRECATED
  26049. /*
  26050. ** Deprecated external interface. It used to set an alarm callback
  26051. ** that was invoked when memory usage grew too large. Now it is a
  26052. ** no-op.
  26053. */
  26054. SQLITE_API int sqlite3_memory_alarm(
  26055. void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
  26056. void *pArg,
  26057. sqlite3_int64 iThreshold
  26058. ){
  26059. (void)xCallback;
  26060. (void)pArg;
  26061. (void)iThreshold;
  26062. return SQLITE_OK;
  26063. }
  26064. #endif
  26065. /*
  26066. ** Set the soft heap-size limit for the library. An argument of
  26067. ** zero disables the limit. A negative argument is a no-op used to
  26068. ** obtain the return value.
  26069. **
  26070. ** The return value is the value of the heap limit just before this
  26071. ** interface was called.
  26072. **
  26073. ** If the hard heap limit is enabled, then the soft heap limit cannot
  26074. ** be disabled nor raised above the hard heap limit.
  26075. */
  26076. SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 n){
  26077. sqlite3_int64 priorLimit;
  26078. sqlite3_int64 excess;
  26079. sqlite3_int64 nUsed;
  26080. #ifndef SQLITE_OMIT_AUTOINIT
  26081. int rc = sqlite3_initialize();
  26082. if( rc ) return -1;
  26083. #endif
  26084. sqlite3_mutex_enter(mem0.mutex);
  26085. priorLimit = mem0.alarmThreshold;
  26086. if( n<0 ){
  26087. sqlite3_mutex_leave(mem0.mutex);
  26088. return priorLimit;
  26089. }
  26090. if( mem0.hardLimit>0 && (n>mem0.hardLimit || n==0) ){
  26091. n = mem0.hardLimit;
  26092. }
  26093. mem0.alarmThreshold = n;
  26094. nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
  26095. AtomicStore(&mem0.nearlyFull, n>0 && n<=nUsed);
  26096. sqlite3_mutex_leave(mem0.mutex);
  26097. excess = sqlite3_memory_used() - n;
  26098. if( excess>0 ) sqlite3_release_memory((int)(excess & 0x7fffffff));
  26099. return priorLimit;
  26100. }
  26101. SQLITE_API void sqlite3_soft_heap_limit(int n){
  26102. if( n<0 ) n = 0;
  26103. sqlite3_soft_heap_limit64(n);
  26104. }
  26105. /*
  26106. ** Set the hard heap-size limit for the library. An argument of zero
  26107. ** disables the hard heap limit. A negative argument is a no-op used
  26108. ** to obtain the return value without affecting the hard heap limit.
  26109. **
  26110. ** The return value is the value of the hard heap limit just prior to
  26111. ** calling this interface.
  26112. **
  26113. ** Setting the hard heap limit will also activate the soft heap limit
  26114. ** and constrain the soft heap limit to be no more than the hard heap
  26115. ** limit.
  26116. */
  26117. SQLITE_API sqlite3_int64 sqlite3_hard_heap_limit64(sqlite3_int64 n){
  26118. sqlite3_int64 priorLimit;
  26119. #ifndef SQLITE_OMIT_AUTOINIT
  26120. int rc = sqlite3_initialize();
  26121. if( rc ) return -1;
  26122. #endif
  26123. sqlite3_mutex_enter(mem0.mutex);
  26124. priorLimit = mem0.hardLimit;
  26125. if( n>=0 ){
  26126. mem0.hardLimit = n;
  26127. if( n<mem0.alarmThreshold || mem0.alarmThreshold==0 ){
  26128. mem0.alarmThreshold = n;
  26129. }
  26130. }
  26131. sqlite3_mutex_leave(mem0.mutex);
  26132. return priorLimit;
  26133. }
  26134. /*
  26135. ** Initialize the memory allocation subsystem.
  26136. */
  26137. SQLITE_PRIVATE int sqlite3MallocInit(void){
  26138. int rc;
  26139. if( sqlite3GlobalConfig.m.xMalloc==0 ){
  26140. sqlite3MemSetDefault();
  26141. }
  26142. memset(&mem0, 0, sizeof(mem0));
  26143. mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  26144. if( sqlite3GlobalConfig.pPage==0 || sqlite3GlobalConfig.szPage<512
  26145. || sqlite3GlobalConfig.nPage<=0 ){
  26146. sqlite3GlobalConfig.pPage = 0;
  26147. sqlite3GlobalConfig.szPage = 0;
  26148. }
  26149. rc = sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
  26150. if( rc!=SQLITE_OK ) memset(&mem0, 0, sizeof(mem0));
  26151. return rc;
  26152. }
  26153. /*
  26154. ** Return true if the heap is currently under memory pressure - in other
  26155. ** words if the amount of heap used is close to the limit set by
  26156. ** sqlite3_soft_heap_limit().
  26157. */
  26158. SQLITE_PRIVATE int sqlite3HeapNearlyFull(void){
  26159. return AtomicLoad(&mem0.nearlyFull);
  26160. }
  26161. /*
  26162. ** Deinitialize the memory allocation subsystem.
  26163. */
  26164. SQLITE_PRIVATE void sqlite3MallocEnd(void){
  26165. if( sqlite3GlobalConfig.m.xShutdown ){
  26166. sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
  26167. }
  26168. memset(&mem0, 0, sizeof(mem0));
  26169. }
  26170. /*
  26171. ** Return the amount of memory currently checked out.
  26172. */
  26173. SQLITE_API sqlite3_int64 sqlite3_memory_used(void){
  26174. sqlite3_int64 res, mx;
  26175. sqlite3_status64(SQLITE_STATUS_MEMORY_USED, &res, &mx, 0);
  26176. return res;
  26177. }
  26178. /*
  26179. ** Return the maximum amount of memory that has ever been
  26180. ** checked out since either the beginning of this process
  26181. ** or since the most recent reset.
  26182. */
  26183. SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
  26184. sqlite3_int64 res, mx;
  26185. sqlite3_status64(SQLITE_STATUS_MEMORY_USED, &res, &mx, resetFlag);
  26186. return mx;
  26187. }
  26188. /*
  26189. ** Trigger the alarm
  26190. */
  26191. static void sqlite3MallocAlarm(int nByte){
  26192. if( mem0.alarmThreshold<=0 ) return;
  26193. sqlite3_mutex_leave(mem0.mutex);
  26194. sqlite3_release_memory(nByte);
  26195. sqlite3_mutex_enter(mem0.mutex);
  26196. }
  26197. /*
  26198. ** Do a memory allocation with statistics and alarms. Assume the
  26199. ** lock is already held.
  26200. */
  26201. static void mallocWithAlarm(int n, void **pp){
  26202. void *p;
  26203. int nFull;
  26204. assert( sqlite3_mutex_held(mem0.mutex) );
  26205. assert( n>0 );
  26206. /* In Firefox (circa 2017-02-08), xRoundup() is remapped to an internal
  26207. ** implementation of malloc_good_size(), which must be called in debug
  26208. ** mode and specifically when the DMD "Dark Matter Detector" is enabled
  26209. ** or else a crash results. Hence, do not attempt to optimize out the
  26210. ** following xRoundup() call. */
  26211. nFull = sqlite3GlobalConfig.m.xRoundup(n);
  26212. sqlite3StatusHighwater(SQLITE_STATUS_MALLOC_SIZE, n);
  26213. if( mem0.alarmThreshold>0 ){
  26214. sqlite3_int64 nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
  26215. if( nUsed >= mem0.alarmThreshold - nFull ){
  26216. AtomicStore(&mem0.nearlyFull, 1);
  26217. sqlite3MallocAlarm(nFull);
  26218. if( mem0.hardLimit ){
  26219. nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
  26220. if( nUsed >= mem0.hardLimit - nFull ){
  26221. *pp = 0;
  26222. return;
  26223. }
  26224. }
  26225. }else{
  26226. AtomicStore(&mem0.nearlyFull, 0);
  26227. }
  26228. }
  26229. p = sqlite3GlobalConfig.m.xMalloc(nFull);
  26230. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  26231. if( p==0 && mem0.alarmThreshold>0 ){
  26232. sqlite3MallocAlarm(nFull);
  26233. p = sqlite3GlobalConfig.m.xMalloc(nFull);
  26234. }
  26235. #endif
  26236. if( p ){
  26237. nFull = sqlite3MallocSize(p);
  26238. sqlite3StatusUp(SQLITE_STATUS_MEMORY_USED, nFull);
  26239. sqlite3StatusUp(SQLITE_STATUS_MALLOC_COUNT, 1);
  26240. }
  26241. *pp = p;
  26242. }
  26243. /*
  26244. ** Allocate memory. This routine is like sqlite3_malloc() except that it
  26245. ** assumes the memory subsystem has already been initialized.
  26246. */
  26247. SQLITE_PRIVATE void *sqlite3Malloc(u64 n){
  26248. void *p;
  26249. if( n==0 || n>=0x7fffff00 ){
  26250. /* A memory allocation of a number of bytes which is near the maximum
  26251. ** signed integer value might cause an integer overflow inside of the
  26252. ** xMalloc(). Hence we limit the maximum size to 0x7fffff00, giving
  26253. ** 255 bytes of overhead. SQLite itself will never use anything near
  26254. ** this amount. The only way to reach the limit is with sqlite3_malloc() */
  26255. p = 0;
  26256. }else if( sqlite3GlobalConfig.bMemstat ){
  26257. sqlite3_mutex_enter(mem0.mutex);
  26258. mallocWithAlarm((int)n, &p);
  26259. sqlite3_mutex_leave(mem0.mutex);
  26260. }else{
  26261. p = sqlite3GlobalConfig.m.xMalloc((int)n);
  26262. }
  26263. assert( EIGHT_BYTE_ALIGNMENT(p) ); /* IMP: R-11148-40995 */
  26264. return p;
  26265. }
  26266. /*
  26267. ** This version of the memory allocation is for use by the application.
  26268. ** First make sure the memory subsystem is initialized, then do the
  26269. ** allocation.
  26270. */
  26271. SQLITE_API void *sqlite3_malloc(int n){
  26272. #ifndef SQLITE_OMIT_AUTOINIT
  26273. if( sqlite3_initialize() ) return 0;
  26274. #endif
  26275. return n<=0 ? 0 : sqlite3Malloc(n);
  26276. }
  26277. SQLITE_API void *sqlite3_malloc64(sqlite3_uint64 n){
  26278. #ifndef SQLITE_OMIT_AUTOINIT
  26279. if( sqlite3_initialize() ) return 0;
  26280. #endif
  26281. return sqlite3Malloc(n);
  26282. }
  26283. /*
  26284. ** TRUE if p is a lookaside memory allocation from db
  26285. */
  26286. #ifndef SQLITE_OMIT_LOOKASIDE
  26287. static int isLookaside(sqlite3 *db, void *p){
  26288. return SQLITE_WITHIN(p, db->lookaside.pStart, db->lookaside.pEnd);
  26289. }
  26290. #else
  26291. #define isLookaside(A,B) 0
  26292. #endif
  26293. /*
  26294. ** Return the size of a memory allocation previously obtained from
  26295. ** sqlite3Malloc() or sqlite3_malloc().
  26296. */
  26297. SQLITE_PRIVATE int sqlite3MallocSize(void *p){
  26298. assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
  26299. return sqlite3GlobalConfig.m.xSize(p);
  26300. }
  26301. static int lookasideMallocSize(sqlite3 *db, void *p){
  26302. #ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE
  26303. return p<db->lookaside.pMiddle ? db->lookaside.szTrue : LOOKASIDE_SMALL;
  26304. #else
  26305. return db->lookaside.szTrue;
  26306. #endif
  26307. }
  26308. SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){
  26309. assert( p!=0 );
  26310. #ifdef SQLITE_DEBUG
  26311. if( db==0 || !isLookaside(db,p) ){
  26312. if( db==0 ){
  26313. assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
  26314. assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
  26315. }else{
  26316. assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
  26317. assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
  26318. }
  26319. }
  26320. #endif
  26321. if( db ){
  26322. if( ((uptr)p)<(uptr)(db->lookaside.pEnd) ){
  26323. #ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE
  26324. if( ((uptr)p)>=(uptr)(db->lookaside.pMiddle) ){
  26325. assert( sqlite3_mutex_held(db->mutex) );
  26326. return LOOKASIDE_SMALL;
  26327. }
  26328. #endif
  26329. if( ((uptr)p)>=(uptr)(db->lookaside.pStart) ){
  26330. assert( sqlite3_mutex_held(db->mutex) );
  26331. return db->lookaside.szTrue;
  26332. }
  26333. }
  26334. }
  26335. return sqlite3GlobalConfig.m.xSize(p);
  26336. }
  26337. SQLITE_API sqlite3_uint64 sqlite3_msize(void *p){
  26338. assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
  26339. assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
  26340. return p ? sqlite3GlobalConfig.m.xSize(p) : 0;
  26341. }
  26342. /*
  26343. ** Free memory previously obtained from sqlite3Malloc().
  26344. */
  26345. SQLITE_API void sqlite3_free(void *p){
  26346. if( p==0 ) return; /* IMP: R-49053-54554 */
  26347. assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
  26348. assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
  26349. if( sqlite3GlobalConfig.bMemstat ){
  26350. sqlite3_mutex_enter(mem0.mutex);
  26351. sqlite3StatusDown(SQLITE_STATUS_MEMORY_USED, sqlite3MallocSize(p));
  26352. sqlite3StatusDown(SQLITE_STATUS_MALLOC_COUNT, 1);
  26353. sqlite3GlobalConfig.m.xFree(p);
  26354. sqlite3_mutex_leave(mem0.mutex);
  26355. }else{
  26356. sqlite3GlobalConfig.m.xFree(p);
  26357. }
  26358. }
  26359. /*
  26360. ** Add the size of memory allocation "p" to the count in
  26361. ** *db->pnBytesFreed.
  26362. */
  26363. static SQLITE_NOINLINE void measureAllocationSize(sqlite3 *db, void *p){
  26364. *db->pnBytesFreed += sqlite3DbMallocSize(db,p);
  26365. }
  26366. /*
  26367. ** Free memory that might be associated with a particular database
  26368. ** connection. Calling sqlite3DbFree(D,X) for X==0 is a harmless no-op.
  26369. ** The sqlite3DbFreeNN(D,X) version requires that X be non-NULL.
  26370. */
  26371. SQLITE_PRIVATE void sqlite3DbFreeNN(sqlite3 *db, void *p){
  26372. assert( db==0 || sqlite3_mutex_held(db->mutex) );
  26373. assert( p!=0 );
  26374. if( db ){
  26375. if( db->pnBytesFreed ){
  26376. measureAllocationSize(db, p);
  26377. return;
  26378. }
  26379. if( ((uptr)p)<(uptr)(db->lookaside.pEnd) ){
  26380. #ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE
  26381. if( ((uptr)p)>=(uptr)(db->lookaside.pMiddle) ){
  26382. LookasideSlot *pBuf = (LookasideSlot*)p;
  26383. #ifdef SQLITE_DEBUG
  26384. memset(p, 0xaa, LOOKASIDE_SMALL); /* Trash freed content */
  26385. #endif
  26386. pBuf->pNext = db->lookaside.pSmallFree;
  26387. db->lookaside.pSmallFree = pBuf;
  26388. return;
  26389. }
  26390. #endif /* SQLITE_OMIT_TWOSIZE_LOOKASIDE */
  26391. if( ((uptr)p)>=(uptr)(db->lookaside.pStart) ){
  26392. LookasideSlot *pBuf = (LookasideSlot*)p;
  26393. #ifdef SQLITE_DEBUG
  26394. memset(p, 0xaa, db->lookaside.szTrue); /* Trash freed content */
  26395. #endif
  26396. pBuf->pNext = db->lookaside.pFree;
  26397. db->lookaside.pFree = pBuf;
  26398. return;
  26399. }
  26400. }
  26401. }
  26402. assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
  26403. assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
  26404. assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
  26405. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  26406. sqlite3_free(p);
  26407. }
  26408. SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){
  26409. assert( db==0 || sqlite3_mutex_held(db->mutex) );
  26410. if( p ) sqlite3DbFreeNN(db, p);
  26411. }
  26412. /*
  26413. ** Change the size of an existing memory allocation
  26414. */
  26415. SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, u64 nBytes){
  26416. int nOld, nNew, nDiff;
  26417. void *pNew;
  26418. assert( sqlite3MemdebugHasType(pOld, MEMTYPE_HEAP) );
  26419. assert( sqlite3MemdebugNoType(pOld, (u8)~MEMTYPE_HEAP) );
  26420. if( pOld==0 ){
  26421. return sqlite3Malloc(nBytes); /* IMP: R-04300-56712 */
  26422. }
  26423. if( nBytes==0 ){
  26424. sqlite3_free(pOld); /* IMP: R-26507-47431 */
  26425. return 0;
  26426. }
  26427. if( nBytes>=0x7fffff00 ){
  26428. /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
  26429. return 0;
  26430. }
  26431. nOld = sqlite3MallocSize(pOld);
  26432. /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second
  26433. ** argument to xRealloc is always a value returned by a prior call to
  26434. ** xRoundup. */
  26435. nNew = sqlite3GlobalConfig.m.xRoundup((int)nBytes);
  26436. if( nOld==nNew ){
  26437. pNew = pOld;
  26438. }else if( sqlite3GlobalConfig.bMemstat ){
  26439. sqlite3_mutex_enter(mem0.mutex);
  26440. sqlite3StatusHighwater(SQLITE_STATUS_MALLOC_SIZE, (int)nBytes);
  26441. nDiff = nNew - nOld;
  26442. if( nDiff>0 && sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED) >=
  26443. mem0.alarmThreshold-nDiff ){
  26444. sqlite3MallocAlarm(nDiff);
  26445. }
  26446. pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
  26447. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  26448. if( pNew==0 && mem0.alarmThreshold>0 ){
  26449. sqlite3MallocAlarm((int)nBytes);
  26450. pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
  26451. }
  26452. #endif
  26453. if( pNew ){
  26454. nNew = sqlite3MallocSize(pNew);
  26455. sqlite3StatusUp(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
  26456. }
  26457. sqlite3_mutex_leave(mem0.mutex);
  26458. }else{
  26459. pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
  26460. }
  26461. assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-11148-40995 */
  26462. return pNew;
  26463. }
  26464. /*
  26465. ** The public interface to sqlite3Realloc. Make sure that the memory
  26466. ** subsystem is initialized prior to invoking sqliteRealloc.
  26467. */
  26468. SQLITE_API void *sqlite3_realloc(void *pOld, int n){
  26469. #ifndef SQLITE_OMIT_AUTOINIT
  26470. if( sqlite3_initialize() ) return 0;
  26471. #endif
  26472. if( n<0 ) n = 0; /* IMP: R-26507-47431 */
  26473. return sqlite3Realloc(pOld, n);
  26474. }
  26475. SQLITE_API void *sqlite3_realloc64(void *pOld, sqlite3_uint64 n){
  26476. #ifndef SQLITE_OMIT_AUTOINIT
  26477. if( sqlite3_initialize() ) return 0;
  26478. #endif
  26479. return sqlite3Realloc(pOld, n);
  26480. }
  26481. /*
  26482. ** Allocate and zero memory.
  26483. */
  26484. SQLITE_PRIVATE void *sqlite3MallocZero(u64 n){
  26485. void *p = sqlite3Malloc(n);
  26486. if( p ){
  26487. memset(p, 0, (size_t)n);
  26488. }
  26489. return p;
  26490. }
  26491. /*
  26492. ** Allocate and zero memory. If the allocation fails, make
  26493. ** the mallocFailed flag in the connection pointer.
  26494. */
  26495. SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, u64 n){
  26496. void *p;
  26497. testcase( db==0 );
  26498. p = sqlite3DbMallocRaw(db, n);
  26499. if( p ) memset(p, 0, (size_t)n);
  26500. return p;
  26501. }
  26502. /* Finish the work of sqlite3DbMallocRawNN for the unusual and
  26503. ** slower case when the allocation cannot be fulfilled using lookaside.
  26504. */
  26505. static SQLITE_NOINLINE void *dbMallocRawFinish(sqlite3 *db, u64 n){
  26506. void *p;
  26507. assert( db!=0 );
  26508. p = sqlite3Malloc(n);
  26509. if( !p ) sqlite3OomFault(db);
  26510. sqlite3MemdebugSetType(p,
  26511. (db->lookaside.bDisable==0) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP);
  26512. return p;
  26513. }
  26514. /*
  26515. ** Allocate memory, either lookaside (if possible) or heap.
  26516. ** If the allocation fails, set the mallocFailed flag in
  26517. ** the connection pointer.
  26518. **
  26519. ** If db!=0 and db->mallocFailed is true (indicating a prior malloc
  26520. ** failure on the same database connection) then always return 0.
  26521. ** Hence for a particular database connection, once malloc starts
  26522. ** failing, it fails consistently until mallocFailed is reset.
  26523. ** This is an important assumption. There are many places in the
  26524. ** code that do things like this:
  26525. **
  26526. ** int *a = (int*)sqlite3DbMallocRaw(db, 100);
  26527. ** int *b = (int*)sqlite3DbMallocRaw(db, 200);
  26528. ** if( b ) a[10] = 9;
  26529. **
  26530. ** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
  26531. ** that all prior mallocs (ex: "a") worked too.
  26532. **
  26533. ** The sqlite3MallocRawNN() variant guarantees that the "db" parameter is
  26534. ** not a NULL pointer.
  26535. */
  26536. SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, u64 n){
  26537. void *p;
  26538. if( db ) return sqlite3DbMallocRawNN(db, n);
  26539. p = sqlite3Malloc(n);
  26540. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  26541. return p;
  26542. }
  26543. SQLITE_PRIVATE void *sqlite3DbMallocRawNN(sqlite3 *db, u64 n){
  26544. #ifndef SQLITE_OMIT_LOOKASIDE
  26545. LookasideSlot *pBuf;
  26546. assert( db!=0 );
  26547. assert( sqlite3_mutex_held(db->mutex) );
  26548. assert( db->pnBytesFreed==0 );
  26549. if( n>db->lookaside.sz ){
  26550. if( !db->lookaside.bDisable ){
  26551. db->lookaside.anStat[1]++;
  26552. }else if( db->mallocFailed ){
  26553. return 0;
  26554. }
  26555. return dbMallocRawFinish(db, n);
  26556. }
  26557. #ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE
  26558. if( n<=LOOKASIDE_SMALL ){
  26559. if( (pBuf = db->lookaside.pSmallFree)!=0 ){
  26560. db->lookaside.pSmallFree = pBuf->pNext;
  26561. db->lookaside.anStat[0]++;
  26562. return (void*)pBuf;
  26563. }else if( (pBuf = db->lookaside.pSmallInit)!=0 ){
  26564. db->lookaside.pSmallInit = pBuf->pNext;
  26565. db->lookaside.anStat[0]++;
  26566. return (void*)pBuf;
  26567. }
  26568. }
  26569. #endif
  26570. if( (pBuf = db->lookaside.pFree)!=0 ){
  26571. db->lookaside.pFree = pBuf->pNext;
  26572. db->lookaside.anStat[0]++;
  26573. return (void*)pBuf;
  26574. }else if( (pBuf = db->lookaside.pInit)!=0 ){
  26575. db->lookaside.pInit = pBuf->pNext;
  26576. db->lookaside.anStat[0]++;
  26577. return (void*)pBuf;
  26578. }else{
  26579. db->lookaside.anStat[2]++;
  26580. }
  26581. #else
  26582. assert( db!=0 );
  26583. assert( sqlite3_mutex_held(db->mutex) );
  26584. assert( db->pnBytesFreed==0 );
  26585. if( db->mallocFailed ){
  26586. return 0;
  26587. }
  26588. #endif
  26589. return dbMallocRawFinish(db, n);
  26590. }
  26591. /* Forward declaration */
  26592. static SQLITE_NOINLINE void *dbReallocFinish(sqlite3 *db, void *p, u64 n);
  26593. /*
  26594. ** Resize the block of memory pointed to by p to n bytes. If the
  26595. ** resize fails, set the mallocFailed flag in the connection object.
  26596. */
  26597. SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, u64 n){
  26598. assert( db!=0 );
  26599. if( p==0 ) return sqlite3DbMallocRawNN(db, n);
  26600. assert( sqlite3_mutex_held(db->mutex) );
  26601. if( ((uptr)p)<(uptr)db->lookaside.pEnd ){
  26602. #ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE
  26603. if( ((uptr)p)>=(uptr)db->lookaside.pMiddle ){
  26604. if( n<=LOOKASIDE_SMALL ) return p;
  26605. }else
  26606. #endif
  26607. if( ((uptr)p)>=(uptr)db->lookaside.pStart ){
  26608. if( n<=db->lookaside.szTrue ) return p;
  26609. }
  26610. }
  26611. return dbReallocFinish(db, p, n);
  26612. }
  26613. static SQLITE_NOINLINE void *dbReallocFinish(sqlite3 *db, void *p, u64 n){
  26614. void *pNew = 0;
  26615. assert( db!=0 );
  26616. assert( p!=0 );
  26617. if( db->mallocFailed==0 ){
  26618. if( isLookaside(db, p) ){
  26619. pNew = sqlite3DbMallocRawNN(db, n);
  26620. if( pNew ){
  26621. memcpy(pNew, p, lookasideMallocSize(db, p));
  26622. sqlite3DbFree(db, p);
  26623. }
  26624. }else{
  26625. assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
  26626. assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
  26627. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  26628. pNew = sqlite3Realloc(p, n);
  26629. if( !pNew ){
  26630. sqlite3OomFault(db);
  26631. }
  26632. sqlite3MemdebugSetType(pNew,
  26633. (db->lookaside.bDisable==0 ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
  26634. }
  26635. }
  26636. return pNew;
  26637. }
  26638. /*
  26639. ** Attempt to reallocate p. If the reallocation fails, then free p
  26640. ** and set the mallocFailed flag in the database connection.
  26641. */
  26642. SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, u64 n){
  26643. void *pNew;
  26644. pNew = sqlite3DbRealloc(db, p, n);
  26645. if( !pNew ){
  26646. sqlite3DbFree(db, p);
  26647. }
  26648. return pNew;
  26649. }
  26650. /*
  26651. ** Make a copy of a string in memory obtained from sqliteMalloc(). These
  26652. ** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
  26653. ** is because when memory debugging is turned on, these two functions are
  26654. ** called via macros that record the current file and line number in the
  26655. ** ThreadData structure.
  26656. */
  26657. SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){
  26658. char *zNew;
  26659. size_t n;
  26660. if( z==0 ){
  26661. return 0;
  26662. }
  26663. n = strlen(z) + 1;
  26664. zNew = sqlite3DbMallocRaw(db, n);
  26665. if( zNew ){
  26666. memcpy(zNew, z, n);
  26667. }
  26668. return zNew;
  26669. }
  26670. SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, u64 n){
  26671. char *zNew;
  26672. assert( db!=0 );
  26673. if( z==0 ){
  26674. return 0;
  26675. }
  26676. assert( (n&0x7fffffff)==n );
  26677. zNew = sqlite3DbMallocRawNN(db, n+1);
  26678. if( zNew ){
  26679. memcpy(zNew, z, (size_t)n);
  26680. zNew[n] = 0;
  26681. }
  26682. return zNew;
  26683. }
  26684. /*
  26685. ** The text between zStart and zEnd represents a phrase within a larger
  26686. ** SQL statement. Make a copy of this phrase in space obtained form
  26687. ** sqlite3DbMalloc(). Omit leading and trailing whitespace.
  26688. */
  26689. SQLITE_PRIVATE char *sqlite3DbSpanDup(sqlite3 *db, const char *zStart, const char *zEnd){
  26690. int n;
  26691. while( sqlite3Isspace(zStart[0]) ) zStart++;
  26692. n = (int)(zEnd - zStart);
  26693. while( ALWAYS(n>0) && sqlite3Isspace(zStart[n-1]) ) n--;
  26694. return sqlite3DbStrNDup(db, zStart, n);
  26695. }
  26696. /*
  26697. ** Free any prior content in *pz and replace it with a copy of zNew.
  26698. */
  26699. SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zNew){
  26700. sqlite3DbFree(db, *pz);
  26701. *pz = sqlite3DbStrDup(db, zNew);
  26702. }
  26703. /*
  26704. ** Call this routine to record the fact that an OOM (out-of-memory) error
  26705. ** has happened. This routine will set db->mallocFailed, and also
  26706. ** temporarily disable the lookaside memory allocator and interrupt
  26707. ** any running VDBEs.
  26708. */
  26709. SQLITE_PRIVATE void sqlite3OomFault(sqlite3 *db){
  26710. if( db->mallocFailed==0 && db->bBenignMalloc==0 ){
  26711. db->mallocFailed = 1;
  26712. if( db->nVdbeExec>0 ){
  26713. AtomicStore(&db->u1.isInterrupted, 1);
  26714. }
  26715. DisableLookaside;
  26716. if( db->pParse ){
  26717. db->pParse->rc = SQLITE_NOMEM_BKPT;
  26718. }
  26719. }
  26720. }
  26721. /*
  26722. ** This routine reactivates the memory allocator and clears the
  26723. ** db->mallocFailed flag as necessary.
  26724. **
  26725. ** The memory allocator is not restarted if there are running
  26726. ** VDBEs.
  26727. */
  26728. SQLITE_PRIVATE void sqlite3OomClear(sqlite3 *db){
  26729. if( db->mallocFailed && db->nVdbeExec==0 ){
  26730. db->mallocFailed = 0;
  26731. AtomicStore(&db->u1.isInterrupted, 0);
  26732. assert( db->lookaside.bDisable>0 );
  26733. EnableLookaside;
  26734. }
  26735. }
  26736. /*
  26737. ** Take actions at the end of an API call to indicate an OOM error
  26738. */
  26739. static SQLITE_NOINLINE int apiOomError(sqlite3 *db){
  26740. sqlite3OomClear(db);
  26741. sqlite3Error(db, SQLITE_NOMEM);
  26742. return SQLITE_NOMEM_BKPT;
  26743. }
  26744. /*
  26745. ** This function must be called before exiting any API function (i.e.
  26746. ** returning control to the user) that has called sqlite3_malloc or
  26747. ** sqlite3_realloc.
  26748. **
  26749. ** The returned value is normally a copy of the second argument to this
  26750. ** function. However, if a malloc() failure has occurred since the previous
  26751. ** invocation SQLITE_NOMEM is returned instead.
  26752. **
  26753. ** If an OOM as occurred, then the connection error-code (the value
  26754. ** returned by sqlite3_errcode()) is set to SQLITE_NOMEM.
  26755. */
  26756. SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
  26757. /* If the db handle must hold the connection handle mutex here.
  26758. ** Otherwise the read (and possible write) of db->mallocFailed
  26759. ** is unsafe, as is the call to sqlite3Error().
  26760. */
  26761. assert( db!=0 );
  26762. assert( sqlite3_mutex_held(db->mutex) );
  26763. if( db->mallocFailed || rc==SQLITE_IOERR_NOMEM ){
  26764. return apiOomError(db);
  26765. }
  26766. return rc & db->errMask;
  26767. }
  26768. /************** End of malloc.c **********************************************/
  26769. /************** Begin file printf.c ******************************************/
  26770. /*
  26771. ** The "printf" code that follows dates from the 1980's. It is in
  26772. ** the public domain.
  26773. **
  26774. **************************************************************************
  26775. **
  26776. ** This file contains code for a set of "printf"-like routines. These
  26777. ** routines format strings much like the printf() from the standard C
  26778. ** library, though the implementation here has enhancements to support
  26779. ** SQLite.
  26780. */
  26781. /* #include "sqliteInt.h" */
  26782. /*
  26783. ** Conversion types fall into various categories as defined by the
  26784. ** following enumeration.
  26785. */
  26786. #define etRADIX 0 /* non-decimal integer types. %x %o */
  26787. #define etFLOAT 1 /* Floating point. %f */
  26788. #define etEXP 2 /* Exponentional notation. %e and %E */
  26789. #define etGENERIC 3 /* Floating or exponential, depending on exponent. %g */
  26790. #define etSIZE 4 /* Return number of characters processed so far. %n */
  26791. #define etSTRING 5 /* Strings. %s */
  26792. #define etDYNSTRING 6 /* Dynamically allocated strings. %z */
  26793. #define etPERCENT 7 /* Percent symbol. %% */
  26794. #define etCHARX 8 /* Characters. %c */
  26795. /* The rest are extensions, not normally found in printf() */
  26796. #define etSQLESCAPE 9 /* Strings with '\'' doubled. %q */
  26797. #define etSQLESCAPE2 10 /* Strings with '\'' doubled and enclosed in '',
  26798. NULL pointers replaced by SQL NULL. %Q */
  26799. #define etTOKEN 11 /* a pointer to a Token structure */
  26800. #define etSRCLIST 12 /* a pointer to a SrcList */
  26801. #define etPOINTER 13 /* The %p conversion */
  26802. #define etSQLESCAPE3 14 /* %w -> Strings with '\"' doubled */
  26803. #define etORDINAL 15 /* %r -> 1st, 2nd, 3rd, 4th, etc. English only */
  26804. #define etDECIMAL 16 /* %d or %u, but not %x, %o */
  26805. #define etINVALID 17 /* Any unrecognized conversion type */
  26806. /*
  26807. ** An "etByte" is an 8-bit unsigned value.
  26808. */
  26809. typedef unsigned char etByte;
  26810. /*
  26811. ** Each builtin conversion character (ex: the 'd' in "%d") is described
  26812. ** by an instance of the following structure
  26813. */
  26814. typedef struct et_info { /* Information about each format field */
  26815. char fmttype; /* The format field code letter */
  26816. etByte base; /* The base for radix conversion */
  26817. etByte flags; /* One or more of FLAG_ constants below */
  26818. etByte type; /* Conversion paradigm */
  26819. etByte charset; /* Offset into aDigits[] of the digits string */
  26820. etByte prefix; /* Offset into aPrefix[] of the prefix string */
  26821. } et_info;
  26822. /*
  26823. ** Allowed values for et_info.flags
  26824. */
  26825. #define FLAG_SIGNED 1 /* True if the value to convert is signed */
  26826. #define FLAG_STRING 4 /* Allow infinite precision */
  26827. /*
  26828. ** The following table is searched linearly, so it is good to put the
  26829. ** most frequently used conversion types first.
  26830. */
  26831. static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
  26832. static const char aPrefix[] = "-x0\000X0";
  26833. static const et_info fmtinfo[] = {
  26834. { 'd', 10, 1, etDECIMAL, 0, 0 },
  26835. { 's', 0, 4, etSTRING, 0, 0 },
  26836. { 'g', 0, 1, etGENERIC, 30, 0 },
  26837. { 'z', 0, 4, etDYNSTRING, 0, 0 },
  26838. { 'q', 0, 4, etSQLESCAPE, 0, 0 },
  26839. { 'Q', 0, 4, etSQLESCAPE2, 0, 0 },
  26840. { 'w', 0, 4, etSQLESCAPE3, 0, 0 },
  26841. { 'c', 0, 0, etCHARX, 0, 0 },
  26842. { 'o', 8, 0, etRADIX, 0, 2 },
  26843. { 'u', 10, 0, etDECIMAL, 0, 0 },
  26844. { 'x', 16, 0, etRADIX, 16, 1 },
  26845. { 'X', 16, 0, etRADIX, 0, 4 },
  26846. #ifndef SQLITE_OMIT_FLOATING_POINT
  26847. { 'f', 0, 1, etFLOAT, 0, 0 },
  26848. { 'e', 0, 1, etEXP, 30, 0 },
  26849. { 'E', 0, 1, etEXP, 14, 0 },
  26850. { 'G', 0, 1, etGENERIC, 14, 0 },
  26851. #endif
  26852. { 'i', 10, 1, etDECIMAL, 0, 0 },
  26853. { 'n', 0, 0, etSIZE, 0, 0 },
  26854. { '%', 0, 0, etPERCENT, 0, 0 },
  26855. { 'p', 16, 0, etPOINTER, 0, 1 },
  26856. /* All the rest are undocumented and are for internal use only */
  26857. { 'T', 0, 0, etTOKEN, 0, 0 },
  26858. { 'S', 0, 0, etSRCLIST, 0, 0 },
  26859. { 'r', 10, 1, etORDINAL, 0, 0 },
  26860. };
  26861. /* Floating point constants used for rounding */
  26862. static const double arRound[] = {
  26863. 5.0e-01, 5.0e-02, 5.0e-03, 5.0e-04, 5.0e-05,
  26864. 5.0e-06, 5.0e-07, 5.0e-08, 5.0e-09, 5.0e-10,
  26865. };
  26866. /*
  26867. ** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
  26868. ** conversions will work.
  26869. */
  26870. #ifndef SQLITE_OMIT_FLOATING_POINT
  26871. /*
  26872. ** "*val" is a double such that 0.1 <= *val < 10.0
  26873. ** Return the ascii code for the leading digit of *val, then
  26874. ** multiply "*val" by 10.0 to renormalize.
  26875. **
  26876. ** Example:
  26877. ** input: *val = 3.14159
  26878. ** output: *val = 1.4159 function return = '3'
  26879. **
  26880. ** The counter *cnt is incremented each time. After counter exceeds
  26881. ** 16 (the number of significant digits in a 64-bit float) '0' is
  26882. ** always returned.
  26883. */
  26884. static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
  26885. int digit;
  26886. LONGDOUBLE_TYPE d;
  26887. if( (*cnt)<=0 ) return '0';
  26888. (*cnt)--;
  26889. digit = (int)*val;
  26890. d = digit;
  26891. digit += '0';
  26892. *val = (*val - d)*10.0;
  26893. return (char)digit;
  26894. }
  26895. #endif /* SQLITE_OMIT_FLOATING_POINT */
  26896. /*
  26897. ** Set the StrAccum object to an error mode.
  26898. */
  26899. static void setStrAccumError(StrAccum *p, u8 eError){
  26900. assert( eError==SQLITE_NOMEM || eError==SQLITE_TOOBIG );
  26901. p->accError = eError;
  26902. if( p->mxAlloc ) sqlite3_str_reset(p);
  26903. if( eError==SQLITE_TOOBIG ) sqlite3ErrorToParser(p->db, eError);
  26904. }
  26905. /*
  26906. ** Extra argument values from a PrintfArguments object
  26907. */
  26908. static sqlite3_int64 getIntArg(PrintfArguments *p){
  26909. if( p->nArg<=p->nUsed ) return 0;
  26910. return sqlite3_value_int64(p->apArg[p->nUsed++]);
  26911. }
  26912. static double getDoubleArg(PrintfArguments *p){
  26913. if( p->nArg<=p->nUsed ) return 0.0;
  26914. return sqlite3_value_double(p->apArg[p->nUsed++]);
  26915. }
  26916. static char *getTextArg(PrintfArguments *p){
  26917. if( p->nArg<=p->nUsed ) return 0;
  26918. return (char*)sqlite3_value_text(p->apArg[p->nUsed++]);
  26919. }
  26920. /*
  26921. ** Allocate memory for a temporary buffer needed for printf rendering.
  26922. **
  26923. ** If the requested size of the temp buffer is larger than the size
  26924. ** of the output buffer in pAccum, then cause an SQLITE_TOOBIG error.
  26925. ** Do the size check before the memory allocation to prevent rogue
  26926. ** SQL from requesting large allocations using the precision or width
  26927. ** field of the printf() function.
  26928. */
  26929. static char *printfTempBuf(sqlite3_str *pAccum, sqlite3_int64 n){
  26930. char *z;
  26931. if( pAccum->accError ) return 0;
  26932. if( n>pAccum->nAlloc && n>pAccum->mxAlloc ){
  26933. setStrAccumError(pAccum, SQLITE_TOOBIG);
  26934. return 0;
  26935. }
  26936. z = sqlite3DbMallocRaw(pAccum->db, n);
  26937. if( z==0 ){
  26938. setStrAccumError(pAccum, SQLITE_NOMEM);
  26939. }
  26940. return z;
  26941. }
  26942. /*
  26943. ** On machines with a small stack size, you can redefine the
  26944. ** SQLITE_PRINT_BUF_SIZE to be something smaller, if desired.
  26945. */
  26946. #ifndef SQLITE_PRINT_BUF_SIZE
  26947. # define SQLITE_PRINT_BUF_SIZE 70
  26948. #endif
  26949. #define etBUFSIZE SQLITE_PRINT_BUF_SIZE /* Size of the output buffer */
  26950. /*
  26951. ** Hard limit on the precision of floating-point conversions.
  26952. */
  26953. #ifndef SQLITE_PRINTF_PRECISION_LIMIT
  26954. # define SQLITE_FP_PRECISION_LIMIT 100000000
  26955. #endif
  26956. /*
  26957. ** Render a string given by "fmt" into the StrAccum object.
  26958. */
  26959. SQLITE_API void sqlite3_str_vappendf(
  26960. sqlite3_str *pAccum, /* Accumulate results here */
  26961. const char *fmt, /* Format string */
  26962. va_list ap /* arguments */
  26963. ){
  26964. int c; /* Next character in the format string */
  26965. char *bufpt; /* Pointer to the conversion buffer */
  26966. int precision; /* Precision of the current field */
  26967. int length; /* Length of the field */
  26968. int idx; /* A general purpose loop counter */
  26969. int width; /* Width of the current field */
  26970. etByte flag_leftjustify; /* True if "-" flag is present */
  26971. etByte flag_prefix; /* '+' or ' ' or 0 for prefix */
  26972. etByte flag_alternateform; /* True if "#" flag is present */
  26973. etByte flag_altform2; /* True if "!" flag is present */
  26974. etByte flag_zeropad; /* True if field width constant starts with zero */
  26975. etByte flag_long; /* 1 for the "l" flag, 2 for "ll", 0 by default */
  26976. etByte done; /* Loop termination flag */
  26977. etByte cThousand; /* Thousands separator for %d and %u */
  26978. etByte xtype = etINVALID; /* Conversion paradigm */
  26979. u8 bArgList; /* True for SQLITE_PRINTF_SQLFUNC */
  26980. char prefix; /* Prefix character. "+" or "-" or " " or '\0'. */
  26981. sqlite_uint64 longvalue; /* Value for integer types */
  26982. LONGDOUBLE_TYPE realvalue; /* Value for real types */
  26983. const et_info *infop; /* Pointer to the appropriate info structure */
  26984. char *zOut; /* Rendering buffer */
  26985. int nOut; /* Size of the rendering buffer */
  26986. char *zExtra = 0; /* Malloced memory used by some conversion */
  26987. #ifndef SQLITE_OMIT_FLOATING_POINT
  26988. int exp, e2; /* exponent of real numbers */
  26989. int nsd; /* Number of significant digits returned */
  26990. double rounder; /* Used for rounding floating point values */
  26991. etByte flag_dp; /* True if decimal point should be shown */
  26992. etByte flag_rtz; /* True if trailing zeros should be removed */
  26993. #endif
  26994. PrintfArguments *pArgList = 0; /* Arguments for SQLITE_PRINTF_SQLFUNC */
  26995. char buf[etBUFSIZE]; /* Conversion buffer */
  26996. /* pAccum never starts out with an empty buffer that was obtained from
  26997. ** malloc(). This precondition is required by the mprintf("%z...")
  26998. ** optimization. */
  26999. assert( pAccum->nChar>0 || (pAccum->printfFlags&SQLITE_PRINTF_MALLOCED)==0 );
  27000. bufpt = 0;
  27001. if( (pAccum->printfFlags & SQLITE_PRINTF_SQLFUNC)!=0 ){
  27002. pArgList = va_arg(ap, PrintfArguments*);
  27003. bArgList = 1;
  27004. }else{
  27005. bArgList = 0;
  27006. }
  27007. for(; (c=(*fmt))!=0; ++fmt){
  27008. if( c!='%' ){
  27009. bufpt = (char *)fmt;
  27010. #if HAVE_STRCHRNUL
  27011. fmt = strchrnul(fmt, '%');
  27012. #else
  27013. do{ fmt++; }while( *fmt && *fmt != '%' );
  27014. #endif
  27015. sqlite3_str_append(pAccum, bufpt, (int)(fmt - bufpt));
  27016. if( *fmt==0 ) break;
  27017. }
  27018. if( (c=(*++fmt))==0 ){
  27019. sqlite3_str_append(pAccum, "%", 1);
  27020. break;
  27021. }
  27022. /* Find out what flags are present */
  27023. flag_leftjustify = flag_prefix = cThousand =
  27024. flag_alternateform = flag_altform2 = flag_zeropad = 0;
  27025. done = 0;
  27026. width = 0;
  27027. flag_long = 0;
  27028. precision = -1;
  27029. do{
  27030. switch( c ){
  27031. case '-': flag_leftjustify = 1; break;
  27032. case '+': flag_prefix = '+'; break;
  27033. case ' ': flag_prefix = ' '; break;
  27034. case '#': flag_alternateform = 1; break;
  27035. case '!': flag_altform2 = 1; break;
  27036. case '0': flag_zeropad = 1; break;
  27037. case ',': cThousand = ','; break;
  27038. default: done = 1; break;
  27039. case 'l': {
  27040. flag_long = 1;
  27041. c = *++fmt;
  27042. if( c=='l' ){
  27043. c = *++fmt;
  27044. flag_long = 2;
  27045. }
  27046. done = 1;
  27047. break;
  27048. }
  27049. case '1': case '2': case '3': case '4': case '5':
  27050. case '6': case '7': case '8': case '9': {
  27051. unsigned wx = c - '0';
  27052. while( (c = *++fmt)>='0' && c<='9' ){
  27053. wx = wx*10 + c - '0';
  27054. }
  27055. testcase( wx>0x7fffffff );
  27056. width = wx & 0x7fffffff;
  27057. #ifdef SQLITE_PRINTF_PRECISION_LIMIT
  27058. if( width>SQLITE_PRINTF_PRECISION_LIMIT ){
  27059. width = SQLITE_PRINTF_PRECISION_LIMIT;
  27060. }
  27061. #endif
  27062. if( c!='.' && c!='l' ){
  27063. done = 1;
  27064. }else{
  27065. fmt--;
  27066. }
  27067. break;
  27068. }
  27069. case '*': {
  27070. if( bArgList ){
  27071. width = (int)getIntArg(pArgList);
  27072. }else{
  27073. width = va_arg(ap,int);
  27074. }
  27075. if( width<0 ){
  27076. flag_leftjustify = 1;
  27077. width = width >= -2147483647 ? -width : 0;
  27078. }
  27079. #ifdef SQLITE_PRINTF_PRECISION_LIMIT
  27080. if( width>SQLITE_PRINTF_PRECISION_LIMIT ){
  27081. width = SQLITE_PRINTF_PRECISION_LIMIT;
  27082. }
  27083. #endif
  27084. if( (c = fmt[1])!='.' && c!='l' ){
  27085. c = *++fmt;
  27086. done = 1;
  27087. }
  27088. break;
  27089. }
  27090. case '.': {
  27091. c = *++fmt;
  27092. if( c=='*' ){
  27093. if( bArgList ){
  27094. precision = (int)getIntArg(pArgList);
  27095. }else{
  27096. precision = va_arg(ap,int);
  27097. }
  27098. if( precision<0 ){
  27099. precision = precision >= -2147483647 ? -precision : -1;
  27100. }
  27101. c = *++fmt;
  27102. }else{
  27103. unsigned px = 0;
  27104. while( c>='0' && c<='9' ){
  27105. px = px*10 + c - '0';
  27106. c = *++fmt;
  27107. }
  27108. testcase( px>0x7fffffff );
  27109. precision = px & 0x7fffffff;
  27110. }
  27111. #ifdef SQLITE_PRINTF_PRECISION_LIMIT
  27112. if( precision>SQLITE_PRINTF_PRECISION_LIMIT ){
  27113. precision = SQLITE_PRINTF_PRECISION_LIMIT;
  27114. }
  27115. #endif
  27116. if( c=='l' ){
  27117. --fmt;
  27118. }else{
  27119. done = 1;
  27120. }
  27121. break;
  27122. }
  27123. }
  27124. }while( !done && (c=(*++fmt))!=0 );
  27125. /* Fetch the info entry for the field */
  27126. infop = &fmtinfo[0];
  27127. xtype = etINVALID;
  27128. for(idx=0; idx<ArraySize(fmtinfo); idx++){
  27129. if( c==fmtinfo[idx].fmttype ){
  27130. infop = &fmtinfo[idx];
  27131. xtype = infop->type;
  27132. break;
  27133. }
  27134. }
  27135. /*
  27136. ** At this point, variables are initialized as follows:
  27137. **
  27138. ** flag_alternateform TRUE if a '#' is present.
  27139. ** flag_altform2 TRUE if a '!' is present.
  27140. ** flag_prefix '+' or ' ' or zero
  27141. ** flag_leftjustify TRUE if a '-' is present or if the
  27142. ** field width was negative.
  27143. ** flag_zeropad TRUE if the width began with 0.
  27144. ** flag_long 1 for "l", 2 for "ll"
  27145. ** width The specified field width. This is
  27146. ** always non-negative. Zero is the default.
  27147. ** precision The specified precision. The default
  27148. ** is -1.
  27149. ** xtype The class of the conversion.
  27150. ** infop Pointer to the appropriate info struct.
  27151. */
  27152. assert( width>=0 );
  27153. assert( precision>=(-1) );
  27154. switch( xtype ){
  27155. case etPOINTER:
  27156. flag_long = sizeof(char*)==sizeof(i64) ? 2 :
  27157. sizeof(char*)==sizeof(long int) ? 1 : 0;
  27158. /* Fall through into the next case */
  27159. case etORDINAL:
  27160. case etRADIX:
  27161. cThousand = 0;
  27162. /* Fall through into the next case */
  27163. case etDECIMAL:
  27164. if( infop->flags & FLAG_SIGNED ){
  27165. i64 v;
  27166. if( bArgList ){
  27167. v = getIntArg(pArgList);
  27168. }else if( flag_long ){
  27169. if( flag_long==2 ){
  27170. v = va_arg(ap,i64) ;
  27171. }else{
  27172. v = va_arg(ap,long int);
  27173. }
  27174. }else{
  27175. v = va_arg(ap,int);
  27176. }
  27177. if( v<0 ){
  27178. if( v==SMALLEST_INT64 ){
  27179. longvalue = ((u64)1)<<63;
  27180. }else{
  27181. longvalue = -v;
  27182. }
  27183. prefix = '-';
  27184. }else{
  27185. longvalue = v;
  27186. prefix = flag_prefix;
  27187. }
  27188. }else{
  27189. if( bArgList ){
  27190. longvalue = (u64)getIntArg(pArgList);
  27191. }else if( flag_long ){
  27192. if( flag_long==2 ){
  27193. longvalue = va_arg(ap,u64);
  27194. }else{
  27195. longvalue = va_arg(ap,unsigned long int);
  27196. }
  27197. }else{
  27198. longvalue = va_arg(ap,unsigned int);
  27199. }
  27200. prefix = 0;
  27201. }
  27202. if( longvalue==0 ) flag_alternateform = 0;
  27203. if( flag_zeropad && precision<width-(prefix!=0) ){
  27204. precision = width-(prefix!=0);
  27205. }
  27206. if( precision<etBUFSIZE-10-etBUFSIZE/3 ){
  27207. nOut = etBUFSIZE;
  27208. zOut = buf;
  27209. }else{
  27210. u64 n;
  27211. n = (u64)precision + 10;
  27212. if( cThousand ) n += precision/3;
  27213. zOut = zExtra = printfTempBuf(pAccum, n);
  27214. if( zOut==0 ) return;
  27215. nOut = (int)n;
  27216. }
  27217. bufpt = &zOut[nOut-1];
  27218. if( xtype==etORDINAL ){
  27219. static const char zOrd[] = "thstndrd";
  27220. int x = (int)(longvalue % 10);
  27221. if( x>=4 || (longvalue/10)%10==1 ){
  27222. x = 0;
  27223. }
  27224. *(--bufpt) = zOrd[x*2+1];
  27225. *(--bufpt) = zOrd[x*2];
  27226. }
  27227. {
  27228. const char *cset = &aDigits[infop->charset];
  27229. u8 base = infop->base;
  27230. do{ /* Convert to ascii */
  27231. *(--bufpt) = cset[longvalue%base];
  27232. longvalue = longvalue/base;
  27233. }while( longvalue>0 );
  27234. }
  27235. length = (int)(&zOut[nOut-1]-bufpt);
  27236. while( precision>length ){
  27237. *(--bufpt) = '0'; /* Zero pad */
  27238. length++;
  27239. }
  27240. if( cThousand ){
  27241. int nn = (length - 1)/3; /* Number of "," to insert */
  27242. int ix = (length - 1)%3 + 1;
  27243. bufpt -= nn;
  27244. for(idx=0; nn>0; idx++){
  27245. bufpt[idx] = bufpt[idx+nn];
  27246. ix--;
  27247. if( ix==0 ){
  27248. bufpt[++idx] = cThousand;
  27249. nn--;
  27250. ix = 3;
  27251. }
  27252. }
  27253. }
  27254. if( prefix ) *(--bufpt) = prefix; /* Add sign */
  27255. if( flag_alternateform && infop->prefix ){ /* Add "0" or "0x" */
  27256. const char *pre;
  27257. char x;
  27258. pre = &aPrefix[infop->prefix];
  27259. for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
  27260. }
  27261. length = (int)(&zOut[nOut-1]-bufpt);
  27262. break;
  27263. case etFLOAT:
  27264. case etEXP:
  27265. case etGENERIC:
  27266. if( bArgList ){
  27267. realvalue = getDoubleArg(pArgList);
  27268. }else{
  27269. realvalue = va_arg(ap,double);
  27270. }
  27271. #ifdef SQLITE_OMIT_FLOATING_POINT
  27272. length = 0;
  27273. #else
  27274. if( precision<0 ) precision = 6; /* Set default precision */
  27275. #ifdef SQLITE_FP_PRECISION_LIMIT
  27276. if( precision>SQLITE_FP_PRECISION_LIMIT ){
  27277. precision = SQLITE_FP_PRECISION_LIMIT;
  27278. }
  27279. #endif
  27280. if( realvalue<0.0 ){
  27281. realvalue = -realvalue;
  27282. prefix = '-';
  27283. }else{
  27284. prefix = flag_prefix;
  27285. }
  27286. if( xtype==etGENERIC && precision>0 ) precision--;
  27287. testcase( precision>0xfff );
  27288. idx = precision & 0xfff;
  27289. rounder = arRound[idx%10];
  27290. while( idx>=10 ){ rounder *= 1.0e-10; idx -= 10; }
  27291. if( xtype==etFLOAT ){
  27292. double rx = (double)realvalue;
  27293. sqlite3_uint64 u;
  27294. int ex;
  27295. memcpy(&u, &rx, sizeof(u));
  27296. ex = -1023 + (int)((u>>52)&0x7ff);
  27297. if( precision+(ex/3) < 15 ) rounder += realvalue*3e-16;
  27298. realvalue += rounder;
  27299. }
  27300. /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
  27301. exp = 0;
  27302. if( sqlite3IsNaN((double)realvalue) ){
  27303. bufpt = "NaN";
  27304. length = 3;
  27305. break;
  27306. }
  27307. if( realvalue>0.0 ){
  27308. LONGDOUBLE_TYPE scale = 1.0;
  27309. while( realvalue>=1e100*scale && exp<=350 ){ scale *= 1e100;exp+=100;}
  27310. while( realvalue>=1e10*scale && exp<=350 ){ scale *= 1e10; exp+=10; }
  27311. while( realvalue>=10.0*scale && exp<=350 ){ scale *= 10.0; exp++; }
  27312. realvalue /= scale;
  27313. while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
  27314. while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
  27315. if( exp>350 ){
  27316. bufpt = buf;
  27317. buf[0] = prefix;
  27318. memcpy(buf+(prefix!=0),"Inf",4);
  27319. length = 3+(prefix!=0);
  27320. break;
  27321. }
  27322. }
  27323. bufpt = buf;
  27324. /*
  27325. ** If the field type is etGENERIC, then convert to either etEXP
  27326. ** or etFLOAT, as appropriate.
  27327. */
  27328. if( xtype!=etFLOAT ){
  27329. realvalue += rounder;
  27330. if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
  27331. }
  27332. if( xtype==etGENERIC ){
  27333. flag_rtz = !flag_alternateform;
  27334. if( exp<-4 || exp>precision ){
  27335. xtype = etEXP;
  27336. }else{
  27337. precision = precision - exp;
  27338. xtype = etFLOAT;
  27339. }
  27340. }else{
  27341. flag_rtz = flag_altform2;
  27342. }
  27343. if( xtype==etEXP ){
  27344. e2 = 0;
  27345. }else{
  27346. e2 = exp;
  27347. }
  27348. {
  27349. i64 szBufNeeded; /* Size of a temporary buffer needed */
  27350. szBufNeeded = MAX(e2,0)+(i64)precision+(i64)width+15;
  27351. if( szBufNeeded > etBUFSIZE ){
  27352. bufpt = zExtra = printfTempBuf(pAccum, szBufNeeded);
  27353. if( bufpt==0 ) return;
  27354. }
  27355. }
  27356. zOut = bufpt;
  27357. nsd = 16 + flag_altform2*10;
  27358. flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
  27359. /* The sign in front of the number */
  27360. if( prefix ){
  27361. *(bufpt++) = prefix;
  27362. }
  27363. /* Digits prior to the decimal point */
  27364. if( e2<0 ){
  27365. *(bufpt++) = '0';
  27366. }else{
  27367. for(; e2>=0; e2--){
  27368. *(bufpt++) = et_getdigit(&realvalue,&nsd);
  27369. }
  27370. }
  27371. /* The decimal point */
  27372. if( flag_dp ){
  27373. *(bufpt++) = '.';
  27374. }
  27375. /* "0" digits after the decimal point but before the first
  27376. ** significant digit of the number */
  27377. for(e2++; e2<0; precision--, e2++){
  27378. assert( precision>0 );
  27379. *(bufpt++) = '0';
  27380. }
  27381. /* Significant digits after the decimal point */
  27382. while( (precision--)>0 ){
  27383. *(bufpt++) = et_getdigit(&realvalue,&nsd);
  27384. }
  27385. /* Remove trailing zeros and the "." if no digits follow the "." */
  27386. if( flag_rtz && flag_dp ){
  27387. while( bufpt[-1]=='0' ) *(--bufpt) = 0;
  27388. assert( bufpt>zOut );
  27389. if( bufpt[-1]=='.' ){
  27390. if( flag_altform2 ){
  27391. *(bufpt++) = '0';
  27392. }else{
  27393. *(--bufpt) = 0;
  27394. }
  27395. }
  27396. }
  27397. /* Add the "eNNN" suffix */
  27398. if( xtype==etEXP ){
  27399. *(bufpt++) = aDigits[infop->charset];
  27400. if( exp<0 ){
  27401. *(bufpt++) = '-'; exp = -exp;
  27402. }else{
  27403. *(bufpt++) = '+';
  27404. }
  27405. if( exp>=100 ){
  27406. *(bufpt++) = (char)((exp/100)+'0'); /* 100's digit */
  27407. exp %= 100;
  27408. }
  27409. *(bufpt++) = (char)(exp/10+'0'); /* 10's digit */
  27410. *(bufpt++) = (char)(exp%10+'0'); /* 1's digit */
  27411. }
  27412. *bufpt = 0;
  27413. /* The converted number is in buf[] and zero terminated. Output it.
  27414. ** Note that the number is in the usual order, not reversed as with
  27415. ** integer conversions. */
  27416. length = (int)(bufpt-zOut);
  27417. bufpt = zOut;
  27418. /* Special case: Add leading zeros if the flag_zeropad flag is
  27419. ** set and we are not left justified */
  27420. if( flag_zeropad && !flag_leftjustify && length < width){
  27421. int i;
  27422. int nPad = width - length;
  27423. for(i=width; i>=nPad; i--){
  27424. bufpt[i] = bufpt[i-nPad];
  27425. }
  27426. i = prefix!=0;
  27427. while( nPad-- ) bufpt[i++] = '0';
  27428. length = width;
  27429. }
  27430. #endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */
  27431. break;
  27432. case etSIZE:
  27433. if( !bArgList ){
  27434. *(va_arg(ap,int*)) = pAccum->nChar;
  27435. }
  27436. length = width = 0;
  27437. break;
  27438. case etPERCENT:
  27439. buf[0] = '%';
  27440. bufpt = buf;
  27441. length = 1;
  27442. break;
  27443. case etCHARX:
  27444. if( bArgList ){
  27445. bufpt = getTextArg(pArgList);
  27446. length = 1;
  27447. if( bufpt ){
  27448. buf[0] = c = *(bufpt++);
  27449. if( (c&0xc0)==0xc0 ){
  27450. while( length<4 && (bufpt[0]&0xc0)==0x80 ){
  27451. buf[length++] = *(bufpt++);
  27452. }
  27453. }
  27454. }else{
  27455. buf[0] = 0;
  27456. }
  27457. }else{
  27458. unsigned int ch = va_arg(ap,unsigned int);
  27459. if( ch<0x00080 ){
  27460. buf[0] = ch & 0xff;
  27461. length = 1;
  27462. }else if( ch<0x00800 ){
  27463. buf[0] = 0xc0 + (u8)((ch>>6)&0x1f);
  27464. buf[1] = 0x80 + (u8)(ch & 0x3f);
  27465. length = 2;
  27466. }else if( ch<0x10000 ){
  27467. buf[0] = 0xe0 + (u8)((ch>>12)&0x0f);
  27468. buf[1] = 0x80 + (u8)((ch>>6) & 0x3f);
  27469. buf[2] = 0x80 + (u8)(ch & 0x3f);
  27470. length = 3;
  27471. }else{
  27472. buf[0] = 0xf0 + (u8)((ch>>18) & 0x07);
  27473. buf[1] = 0x80 + (u8)((ch>>12) & 0x3f);
  27474. buf[2] = 0x80 + (u8)((ch>>6) & 0x3f);
  27475. buf[3] = 0x80 + (u8)(ch & 0x3f);
  27476. length = 4;
  27477. }
  27478. }
  27479. if( precision>1 ){
  27480. width -= precision-1;
  27481. if( width>1 && !flag_leftjustify ){
  27482. sqlite3_str_appendchar(pAccum, width-1, ' ');
  27483. width = 0;
  27484. }
  27485. while( precision-- > 1 ){
  27486. sqlite3_str_append(pAccum, buf, length);
  27487. }
  27488. }
  27489. bufpt = buf;
  27490. flag_altform2 = 1;
  27491. goto adjust_width_for_utf8;
  27492. case etSTRING:
  27493. case etDYNSTRING:
  27494. if( bArgList ){
  27495. bufpt = getTextArg(pArgList);
  27496. xtype = etSTRING;
  27497. }else{
  27498. bufpt = va_arg(ap,char*);
  27499. }
  27500. if( bufpt==0 ){
  27501. bufpt = "";
  27502. }else if( xtype==etDYNSTRING ){
  27503. if( pAccum->nChar==0
  27504. && pAccum->mxAlloc
  27505. && width==0
  27506. && precision<0
  27507. && pAccum->accError==0
  27508. ){
  27509. /* Special optimization for sqlite3_mprintf("%z..."):
  27510. ** Extend an existing memory allocation rather than creating
  27511. ** a new one. */
  27512. assert( (pAccum->printfFlags&SQLITE_PRINTF_MALLOCED)==0 );
  27513. pAccum->zText = bufpt;
  27514. pAccum->nAlloc = sqlite3DbMallocSize(pAccum->db, bufpt);
  27515. pAccum->nChar = 0x7fffffff & (int)strlen(bufpt);
  27516. pAccum->printfFlags |= SQLITE_PRINTF_MALLOCED;
  27517. length = 0;
  27518. break;
  27519. }
  27520. zExtra = bufpt;
  27521. }
  27522. if( precision>=0 ){
  27523. if( flag_altform2 ){
  27524. /* Set length to the number of bytes needed in order to display
  27525. ** precision characters */
  27526. unsigned char *z = (unsigned char*)bufpt;
  27527. while( precision-- > 0 && z[0] ){
  27528. SQLITE_SKIP_UTF8(z);
  27529. }
  27530. length = (int)(z - (unsigned char*)bufpt);
  27531. }else{
  27532. for(length=0; length<precision && bufpt[length]; length++){}
  27533. }
  27534. }else{
  27535. length = 0x7fffffff & (int)strlen(bufpt);
  27536. }
  27537. adjust_width_for_utf8:
  27538. if( flag_altform2 && width>0 ){
  27539. /* Adjust width to account for extra bytes in UTF-8 characters */
  27540. int ii = length - 1;
  27541. while( ii>=0 ) if( (bufpt[ii--] & 0xc0)==0x80 ) width++;
  27542. }
  27543. break;
  27544. case etSQLESCAPE: /* %q: Escape ' characters */
  27545. case etSQLESCAPE2: /* %Q: Escape ' and enclose in '...' */
  27546. case etSQLESCAPE3: { /* %w: Escape " characters */
  27547. int i, j, k, n, isnull;
  27548. int needQuote;
  27549. char ch;
  27550. char q = ((xtype==etSQLESCAPE3)?'"':'\''); /* Quote character */
  27551. char *escarg;
  27552. if( bArgList ){
  27553. escarg = getTextArg(pArgList);
  27554. }else{
  27555. escarg = va_arg(ap,char*);
  27556. }
  27557. isnull = escarg==0;
  27558. if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
  27559. /* For %q, %Q, and %w, the precision is the number of bytes (or
  27560. ** characters if the ! flags is present) to use from the input.
  27561. ** Because of the extra quoting characters inserted, the number
  27562. ** of output characters may be larger than the precision.
  27563. */
  27564. k = precision;
  27565. for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
  27566. if( ch==q ) n++;
  27567. if( flag_altform2 && (ch&0xc0)==0xc0 ){
  27568. while( (escarg[i+1]&0xc0)==0x80 ){ i++; }
  27569. }
  27570. }
  27571. needQuote = !isnull && xtype==etSQLESCAPE2;
  27572. n += i + 3;
  27573. if( n>etBUFSIZE ){
  27574. bufpt = zExtra = printfTempBuf(pAccum, n);
  27575. if( bufpt==0 ) return;
  27576. }else{
  27577. bufpt = buf;
  27578. }
  27579. j = 0;
  27580. if( needQuote ) bufpt[j++] = q;
  27581. k = i;
  27582. for(i=0; i<k; i++){
  27583. bufpt[j++] = ch = escarg[i];
  27584. if( ch==q ) bufpt[j++] = ch;
  27585. }
  27586. if( needQuote ) bufpt[j++] = q;
  27587. bufpt[j] = 0;
  27588. length = j;
  27589. goto adjust_width_for_utf8;
  27590. }
  27591. case etTOKEN: {
  27592. Token *pToken;
  27593. if( (pAccum->printfFlags & SQLITE_PRINTF_INTERNAL)==0 ) return;
  27594. pToken = va_arg(ap, Token*);
  27595. assert( bArgList==0 );
  27596. if( pToken && pToken->n ){
  27597. sqlite3_str_append(pAccum, (const char*)pToken->z, pToken->n);
  27598. }
  27599. length = width = 0;
  27600. break;
  27601. }
  27602. case etSRCLIST: {
  27603. SrcList *pSrc;
  27604. int k;
  27605. struct SrcList_item *pItem;
  27606. if( (pAccum->printfFlags & SQLITE_PRINTF_INTERNAL)==0 ) return;
  27607. pSrc = va_arg(ap, SrcList*);
  27608. k = va_arg(ap, int);
  27609. pItem = &pSrc->a[k];
  27610. assert( bArgList==0 );
  27611. assert( k>=0 && k<pSrc->nSrc );
  27612. if( pItem->zDatabase ){
  27613. sqlite3_str_appendall(pAccum, pItem->zDatabase);
  27614. sqlite3_str_append(pAccum, ".", 1);
  27615. }
  27616. sqlite3_str_appendall(pAccum, pItem->zName);
  27617. length = width = 0;
  27618. break;
  27619. }
  27620. default: {
  27621. assert( xtype==etINVALID );
  27622. return;
  27623. }
  27624. }/* End switch over the format type */
  27625. /*
  27626. ** The text of the conversion is pointed to by "bufpt" and is
  27627. ** "length" characters long. The field width is "width". Do
  27628. ** the output. Both length and width are in bytes, not characters,
  27629. ** at this point. If the "!" flag was present on string conversions
  27630. ** indicating that width and precision should be expressed in characters,
  27631. ** then the values have been translated prior to reaching this point.
  27632. */
  27633. width -= length;
  27634. if( width>0 ){
  27635. if( !flag_leftjustify ) sqlite3_str_appendchar(pAccum, width, ' ');
  27636. sqlite3_str_append(pAccum, bufpt, length);
  27637. if( flag_leftjustify ) sqlite3_str_appendchar(pAccum, width, ' ');
  27638. }else{
  27639. sqlite3_str_append(pAccum, bufpt, length);
  27640. }
  27641. if( zExtra ){
  27642. sqlite3DbFree(pAccum->db, zExtra);
  27643. zExtra = 0;
  27644. }
  27645. }/* End for loop over the format string */
  27646. } /* End of function */
  27647. /*
  27648. ** Enlarge the memory allocation on a StrAccum object so that it is
  27649. ** able to accept at least N more bytes of text.
  27650. **
  27651. ** Return the number of bytes of text that StrAccum is able to accept
  27652. ** after the attempted enlargement. The value returned might be zero.
  27653. */
  27654. static int sqlite3StrAccumEnlarge(StrAccum *p, int N){
  27655. char *zNew;
  27656. assert( p->nChar+(i64)N >= p->nAlloc ); /* Only called if really needed */
  27657. if( p->accError ){
  27658. testcase(p->accError==SQLITE_TOOBIG);
  27659. testcase(p->accError==SQLITE_NOMEM);
  27660. return 0;
  27661. }
  27662. if( p->mxAlloc==0 ){
  27663. setStrAccumError(p, SQLITE_TOOBIG);
  27664. return p->nAlloc - p->nChar - 1;
  27665. }else{
  27666. char *zOld = isMalloced(p) ? p->zText : 0;
  27667. i64 szNew = p->nChar;
  27668. szNew += N + 1;
  27669. if( szNew+p->nChar<=p->mxAlloc ){
  27670. /* Force exponential buffer size growth as long as it does not overflow,
  27671. ** to avoid having to call this routine too often */
  27672. szNew += p->nChar;
  27673. }
  27674. if( szNew > p->mxAlloc ){
  27675. sqlite3_str_reset(p);
  27676. setStrAccumError(p, SQLITE_TOOBIG);
  27677. return 0;
  27678. }else{
  27679. p->nAlloc = (int)szNew;
  27680. }
  27681. if( p->db ){
  27682. zNew = sqlite3DbRealloc(p->db, zOld, p->nAlloc);
  27683. }else{
  27684. zNew = sqlite3Realloc(zOld, p->nAlloc);
  27685. }
  27686. if( zNew ){
  27687. assert( p->zText!=0 || p->nChar==0 );
  27688. if( !isMalloced(p) && p->nChar>0 ) memcpy(zNew, p->zText, p->nChar);
  27689. p->zText = zNew;
  27690. p->nAlloc = sqlite3DbMallocSize(p->db, zNew);
  27691. p->printfFlags |= SQLITE_PRINTF_MALLOCED;
  27692. }else{
  27693. sqlite3_str_reset(p);
  27694. setStrAccumError(p, SQLITE_NOMEM);
  27695. return 0;
  27696. }
  27697. }
  27698. return N;
  27699. }
  27700. /*
  27701. ** Append N copies of character c to the given string buffer.
  27702. */
  27703. SQLITE_API void sqlite3_str_appendchar(sqlite3_str *p, int N, char c){
  27704. testcase( p->nChar + (i64)N > 0x7fffffff );
  27705. if( p->nChar+(i64)N >= p->nAlloc && (N = sqlite3StrAccumEnlarge(p, N))<=0 ){
  27706. return;
  27707. }
  27708. while( (N--)>0 ) p->zText[p->nChar++] = c;
  27709. }
  27710. /*
  27711. ** The StrAccum "p" is not large enough to accept N new bytes of z[].
  27712. ** So enlarge if first, then do the append.
  27713. **
  27714. ** This is a helper routine to sqlite3_str_append() that does special-case
  27715. ** work (enlarging the buffer) using tail recursion, so that the
  27716. ** sqlite3_str_append() routine can use fast calling semantics.
  27717. */
  27718. static void SQLITE_NOINLINE enlargeAndAppend(StrAccum *p, const char *z, int N){
  27719. N = sqlite3StrAccumEnlarge(p, N);
  27720. if( N>0 ){
  27721. memcpy(&p->zText[p->nChar], z, N);
  27722. p->nChar += N;
  27723. }
  27724. }
  27725. /*
  27726. ** Append N bytes of text from z to the StrAccum object. Increase the
  27727. ** size of the memory allocation for StrAccum if necessary.
  27728. */
  27729. SQLITE_API void sqlite3_str_append(sqlite3_str *p, const char *z, int N){
  27730. assert( z!=0 || N==0 );
  27731. assert( p->zText!=0 || p->nChar==0 || p->accError );
  27732. assert( N>=0 );
  27733. assert( p->accError==0 || p->nAlloc==0 || p->mxAlloc==0 );
  27734. if( p->nChar+N >= p->nAlloc ){
  27735. enlargeAndAppend(p,z,N);
  27736. }else if( N ){
  27737. assert( p->zText );
  27738. p->nChar += N;
  27739. memcpy(&p->zText[p->nChar-N], z, N);
  27740. }
  27741. }
  27742. /*
  27743. ** Append the complete text of zero-terminated string z[] to the p string.
  27744. */
  27745. SQLITE_API void sqlite3_str_appendall(sqlite3_str *p, const char *z){
  27746. sqlite3_str_append(p, z, sqlite3Strlen30(z));
  27747. }
  27748. /*
  27749. ** Finish off a string by making sure it is zero-terminated.
  27750. ** Return a pointer to the resulting string. Return a NULL
  27751. ** pointer if any kind of error was encountered.
  27752. */
  27753. static SQLITE_NOINLINE char *strAccumFinishRealloc(StrAccum *p){
  27754. char *zText;
  27755. assert( p->mxAlloc>0 && !isMalloced(p) );
  27756. zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
  27757. if( zText ){
  27758. memcpy(zText, p->zText, p->nChar+1);
  27759. p->printfFlags |= SQLITE_PRINTF_MALLOCED;
  27760. }else{
  27761. setStrAccumError(p, SQLITE_NOMEM);
  27762. }
  27763. p->zText = zText;
  27764. return zText;
  27765. }
  27766. SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){
  27767. if( p->zText ){
  27768. p->zText[p->nChar] = 0;
  27769. if( p->mxAlloc>0 && !isMalloced(p) ){
  27770. return strAccumFinishRealloc(p);
  27771. }
  27772. }
  27773. return p->zText;
  27774. }
  27775. /*
  27776. ** This singleton is an sqlite3_str object that is returned if
  27777. ** sqlite3_malloc() fails to provide space for a real one. This
  27778. ** sqlite3_str object accepts no new text and always returns
  27779. ** an SQLITE_NOMEM error.
  27780. */
  27781. static sqlite3_str sqlite3OomStr = {
  27782. 0, 0, 0, 0, 0, SQLITE_NOMEM, 0
  27783. };
  27784. /* Finalize a string created using sqlite3_str_new().
  27785. */
  27786. SQLITE_API char *sqlite3_str_finish(sqlite3_str *p){
  27787. char *z;
  27788. if( p!=0 && p!=&sqlite3OomStr ){
  27789. z = sqlite3StrAccumFinish(p);
  27790. sqlite3_free(p);
  27791. }else{
  27792. z = 0;
  27793. }
  27794. return z;
  27795. }
  27796. /* Return any error code associated with p */
  27797. SQLITE_API int sqlite3_str_errcode(sqlite3_str *p){
  27798. return p ? p->accError : SQLITE_NOMEM;
  27799. }
  27800. /* Return the current length of p in bytes */
  27801. SQLITE_API int sqlite3_str_length(sqlite3_str *p){
  27802. return p ? p->nChar : 0;
  27803. }
  27804. /* Return the current value for p */
  27805. SQLITE_API char *sqlite3_str_value(sqlite3_str *p){
  27806. if( p==0 || p->nChar==0 ) return 0;
  27807. p->zText[p->nChar] = 0;
  27808. return p->zText;
  27809. }
  27810. /*
  27811. ** Reset an StrAccum string. Reclaim all malloced memory.
  27812. */
  27813. SQLITE_API void sqlite3_str_reset(StrAccum *p){
  27814. if( isMalloced(p) ){
  27815. sqlite3DbFree(p->db, p->zText);
  27816. p->printfFlags &= ~SQLITE_PRINTF_MALLOCED;
  27817. }
  27818. p->nAlloc = 0;
  27819. p->nChar = 0;
  27820. p->zText = 0;
  27821. }
  27822. /*
  27823. ** Initialize a string accumulator.
  27824. **
  27825. ** p: The accumulator to be initialized.
  27826. ** db: Pointer to a database connection. May be NULL. Lookaside
  27827. ** memory is used if not NULL. db->mallocFailed is set appropriately
  27828. ** when not NULL.
  27829. ** zBase: An initial buffer. May be NULL in which case the initial buffer
  27830. ** is malloced.
  27831. ** n: Size of zBase in bytes. If total space requirements never exceed
  27832. ** n then no memory allocations ever occur.
  27833. ** mx: Maximum number of bytes to accumulate. If mx==0 then no memory
  27834. ** allocations will ever occur.
  27835. */
  27836. SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, sqlite3 *db, char *zBase, int n, int mx){
  27837. p->zText = zBase;
  27838. p->db = db;
  27839. p->nAlloc = n;
  27840. p->mxAlloc = mx;
  27841. p->nChar = 0;
  27842. p->accError = 0;
  27843. p->printfFlags = 0;
  27844. }
  27845. /* Allocate and initialize a new dynamic string object */
  27846. SQLITE_API sqlite3_str *sqlite3_str_new(sqlite3 *db){
  27847. sqlite3_str *p = sqlite3_malloc64(sizeof(*p));
  27848. if( p ){
  27849. sqlite3StrAccumInit(p, 0, 0, 0,
  27850. db ? db->aLimit[SQLITE_LIMIT_LENGTH] : SQLITE_MAX_LENGTH);
  27851. }else{
  27852. p = &sqlite3OomStr;
  27853. }
  27854. return p;
  27855. }
  27856. /*
  27857. ** Print into memory obtained from sqliteMalloc(). Use the internal
  27858. ** %-conversion extensions.
  27859. */
  27860. SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
  27861. char *z;
  27862. char zBase[SQLITE_PRINT_BUF_SIZE];
  27863. StrAccum acc;
  27864. assert( db!=0 );
  27865. sqlite3StrAccumInit(&acc, db, zBase, sizeof(zBase),
  27866. db->aLimit[SQLITE_LIMIT_LENGTH]);
  27867. acc.printfFlags = SQLITE_PRINTF_INTERNAL;
  27868. sqlite3_str_vappendf(&acc, zFormat, ap);
  27869. z = sqlite3StrAccumFinish(&acc);
  27870. if( acc.accError==SQLITE_NOMEM ){
  27871. sqlite3OomFault(db);
  27872. }
  27873. return z;
  27874. }
  27875. /*
  27876. ** Print into memory obtained from sqliteMalloc(). Use the internal
  27877. ** %-conversion extensions.
  27878. */
  27879. SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
  27880. va_list ap;
  27881. char *z;
  27882. va_start(ap, zFormat);
  27883. z = sqlite3VMPrintf(db, zFormat, ap);
  27884. va_end(ap);
  27885. return z;
  27886. }
  27887. /*
  27888. ** Print into memory obtained from sqlite3_malloc(). Omit the internal
  27889. ** %-conversion extensions.
  27890. */
  27891. SQLITE_API char *sqlite3_vmprintf(const char *zFormat, va_list ap){
  27892. char *z;
  27893. char zBase[SQLITE_PRINT_BUF_SIZE];
  27894. StrAccum acc;
  27895. #ifdef SQLITE_ENABLE_API_ARMOR
  27896. if( zFormat==0 ){
  27897. (void)SQLITE_MISUSE_BKPT;
  27898. return 0;
  27899. }
  27900. #endif
  27901. #ifndef SQLITE_OMIT_AUTOINIT
  27902. if( sqlite3_initialize() ) return 0;
  27903. #endif
  27904. sqlite3StrAccumInit(&acc, 0, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
  27905. sqlite3_str_vappendf(&acc, zFormat, ap);
  27906. z = sqlite3StrAccumFinish(&acc);
  27907. return z;
  27908. }
  27909. /*
  27910. ** Print into memory obtained from sqlite3_malloc()(). Omit the internal
  27911. ** %-conversion extensions.
  27912. */
  27913. SQLITE_API char *sqlite3_mprintf(const char *zFormat, ...){
  27914. va_list ap;
  27915. char *z;
  27916. #ifndef SQLITE_OMIT_AUTOINIT
  27917. if( sqlite3_initialize() ) return 0;
  27918. #endif
  27919. va_start(ap, zFormat);
  27920. z = sqlite3_vmprintf(zFormat, ap);
  27921. va_end(ap);
  27922. return z;
  27923. }
  27924. /*
  27925. ** sqlite3_snprintf() works like snprintf() except that it ignores the
  27926. ** current locale settings. This is important for SQLite because we
  27927. ** are not able to use a "," as the decimal point in place of "." as
  27928. ** specified by some locales.
  27929. **
  27930. ** Oops: The first two arguments of sqlite3_snprintf() are backwards
  27931. ** from the snprintf() standard. Unfortunately, it is too late to change
  27932. ** this without breaking compatibility, so we just have to live with the
  27933. ** mistake.
  27934. **
  27935. ** sqlite3_vsnprintf() is the varargs version.
  27936. */
  27937. SQLITE_API char *sqlite3_vsnprintf(int n, char *zBuf, const char *zFormat, va_list ap){
  27938. StrAccum acc;
  27939. if( n<=0 ) return zBuf;
  27940. #ifdef SQLITE_ENABLE_API_ARMOR
  27941. if( zBuf==0 || zFormat==0 ) {
  27942. (void)SQLITE_MISUSE_BKPT;
  27943. if( zBuf ) zBuf[0] = 0;
  27944. return zBuf;
  27945. }
  27946. #endif
  27947. sqlite3StrAccumInit(&acc, 0, zBuf, n, 0);
  27948. sqlite3_str_vappendf(&acc, zFormat, ap);
  27949. zBuf[acc.nChar] = 0;
  27950. return zBuf;
  27951. }
  27952. SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
  27953. char *z;
  27954. va_list ap;
  27955. va_start(ap,zFormat);
  27956. z = sqlite3_vsnprintf(n, zBuf, zFormat, ap);
  27957. va_end(ap);
  27958. return z;
  27959. }
  27960. /*
  27961. ** This is the routine that actually formats the sqlite3_log() message.
  27962. ** We house it in a separate routine from sqlite3_log() to avoid using
  27963. ** stack space on small-stack systems when logging is disabled.
  27964. **
  27965. ** sqlite3_log() must render into a static buffer. It cannot dynamically
  27966. ** allocate memory because it might be called while the memory allocator
  27967. ** mutex is held.
  27968. **
  27969. ** sqlite3_str_vappendf() might ask for *temporary* memory allocations for
  27970. ** certain format characters (%q) or for very large precisions or widths.
  27971. ** Care must be taken that any sqlite3_log() calls that occur while the
  27972. ** memory mutex is held do not use these mechanisms.
  27973. */
  27974. static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
  27975. StrAccum acc; /* String accumulator */
  27976. char zMsg[SQLITE_PRINT_BUF_SIZE*3]; /* Complete log message */
  27977. sqlite3StrAccumInit(&acc, 0, zMsg, sizeof(zMsg), 0);
  27978. sqlite3_str_vappendf(&acc, zFormat, ap);
  27979. sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,
  27980. sqlite3StrAccumFinish(&acc));
  27981. }
  27982. /*
  27983. ** Format and write a message to the log if logging is enabled.
  27984. */
  27985. SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...){
  27986. va_list ap; /* Vararg list */
  27987. if( sqlite3GlobalConfig.xLog ){
  27988. va_start(ap, zFormat);
  27989. renderLogMsg(iErrCode, zFormat, ap);
  27990. va_end(ap);
  27991. }
  27992. }
  27993. #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
  27994. /*
  27995. ** A version of printf() that understands %lld. Used for debugging.
  27996. ** The printf() built into some versions of windows does not understand %lld
  27997. ** and segfaults if you give it a long long int.
  27998. */
  27999. SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
  28000. va_list ap;
  28001. StrAccum acc;
  28002. char zBuf[SQLITE_PRINT_BUF_SIZE*10];
  28003. sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
  28004. va_start(ap,zFormat);
  28005. sqlite3_str_vappendf(&acc, zFormat, ap);
  28006. va_end(ap);
  28007. sqlite3StrAccumFinish(&acc);
  28008. #ifdef SQLITE_OS_TRACE_PROC
  28009. {
  28010. extern void SQLITE_OS_TRACE_PROC(const char *zBuf, int nBuf);
  28011. SQLITE_OS_TRACE_PROC(zBuf, sizeof(zBuf));
  28012. }
  28013. #else
  28014. fprintf(stdout,"%s", zBuf);
  28015. fflush(stdout);
  28016. #endif
  28017. }
  28018. #endif
  28019. /*
  28020. ** variable-argument wrapper around sqlite3_str_vappendf(). The bFlags argument
  28021. ** can contain the bit SQLITE_PRINTF_INTERNAL enable internal formats.
  28022. */
  28023. SQLITE_API void sqlite3_str_appendf(StrAccum *p, const char *zFormat, ...){
  28024. va_list ap;
  28025. va_start(ap,zFormat);
  28026. sqlite3_str_vappendf(p, zFormat, ap);
  28027. va_end(ap);
  28028. }
  28029. /************** End of printf.c **********************************************/
  28030. /************** Begin file treeview.c ****************************************/
  28031. /*
  28032. ** 2015-06-08
  28033. **
  28034. ** The author disclaims copyright to this source code. In place of
  28035. ** a legal notice, here is a blessing:
  28036. **
  28037. ** May you do good and not evil.
  28038. ** May you find forgiveness for yourself and forgive others.
  28039. ** May you share freely, never taking more than you give.
  28040. **
  28041. *************************************************************************
  28042. **
  28043. ** This file contains C code to implement the TreeView debugging routines.
  28044. ** These routines print a parse tree to standard output for debugging and
  28045. ** analysis.
  28046. **
  28047. ** The interfaces in this file is only available when compiling
  28048. ** with SQLITE_DEBUG.
  28049. */
  28050. /* #include "sqliteInt.h" */
  28051. #ifdef SQLITE_DEBUG
  28052. /*
  28053. ** Add a new subitem to the tree. The moreToFollow flag indicates that this
  28054. ** is not the last item in the tree.
  28055. */
  28056. static TreeView *sqlite3TreeViewPush(TreeView *p, u8 moreToFollow){
  28057. if( p==0 ){
  28058. p = sqlite3_malloc64( sizeof(*p) );
  28059. if( p==0 ) return 0;
  28060. memset(p, 0, sizeof(*p));
  28061. }else{
  28062. p->iLevel++;
  28063. }
  28064. assert( moreToFollow==0 || moreToFollow==1 );
  28065. if( p->iLevel<sizeof(p->bLine) ) p->bLine[p->iLevel] = moreToFollow;
  28066. return p;
  28067. }
  28068. /*
  28069. ** Finished with one layer of the tree
  28070. */
  28071. static void sqlite3TreeViewPop(TreeView *p){
  28072. if( p==0 ) return;
  28073. p->iLevel--;
  28074. if( p->iLevel<0 ) sqlite3_free(p);
  28075. }
  28076. /*
  28077. ** Generate a single line of output for the tree, with a prefix that contains
  28078. ** all the appropriate tree lines
  28079. */
  28080. static void sqlite3TreeViewLine(TreeView *p, const char *zFormat, ...){
  28081. va_list ap;
  28082. int i;
  28083. StrAccum acc;
  28084. char zBuf[500];
  28085. sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
  28086. if( p ){
  28087. for(i=0; i<p->iLevel && i<sizeof(p->bLine)-1; i++){
  28088. sqlite3_str_append(&acc, p->bLine[i] ? "| " : " ", 4);
  28089. }
  28090. sqlite3_str_append(&acc, p->bLine[i] ? "|-- " : "'-- ", 4);
  28091. }
  28092. if( zFormat!=0 ){
  28093. va_start(ap, zFormat);
  28094. sqlite3_str_vappendf(&acc, zFormat, ap);
  28095. va_end(ap);
  28096. assert( acc.nChar>0 || acc.accError );
  28097. sqlite3_str_append(&acc, "\n", 1);
  28098. }
  28099. sqlite3StrAccumFinish(&acc);
  28100. fprintf(stdout,"%s", zBuf);
  28101. fflush(stdout);
  28102. }
  28103. /*
  28104. ** Shorthand for starting a new tree item that consists of a single label
  28105. */
  28106. static void sqlite3TreeViewItem(TreeView *p, const char *zLabel,u8 moreFollows){
  28107. p = sqlite3TreeViewPush(p, moreFollows);
  28108. sqlite3TreeViewLine(p, "%s", zLabel);
  28109. }
  28110. /*
  28111. ** Generate a human-readable description of a WITH clause.
  28112. */
  28113. SQLITE_PRIVATE void sqlite3TreeViewWith(TreeView *pView, const With *pWith, u8 moreToFollow){
  28114. int i;
  28115. if( pWith==0 ) return;
  28116. if( pWith->nCte==0 ) return;
  28117. if( pWith->pOuter ){
  28118. sqlite3TreeViewLine(pView, "WITH (0x%p, pOuter=0x%p)",pWith,pWith->pOuter);
  28119. }else{
  28120. sqlite3TreeViewLine(pView, "WITH (0x%p)", pWith);
  28121. }
  28122. if( pWith->nCte>0 ){
  28123. pView = sqlite3TreeViewPush(pView, 1);
  28124. for(i=0; i<pWith->nCte; i++){
  28125. StrAccum x;
  28126. char zLine[1000];
  28127. const struct Cte *pCte = &pWith->a[i];
  28128. sqlite3StrAccumInit(&x, 0, zLine, sizeof(zLine), 0);
  28129. sqlite3_str_appendf(&x, "%s", pCte->zName);
  28130. if( pCte->pCols && pCte->pCols->nExpr>0 ){
  28131. char cSep = '(';
  28132. int j;
  28133. for(j=0; j<pCte->pCols->nExpr; j++){
  28134. sqlite3_str_appendf(&x, "%c%s", cSep, pCte->pCols->a[j].zEName);
  28135. cSep = ',';
  28136. }
  28137. sqlite3_str_appendf(&x, ")");
  28138. }
  28139. sqlite3_str_appendf(&x, " AS");
  28140. sqlite3StrAccumFinish(&x);
  28141. sqlite3TreeViewItem(pView, zLine, i<pWith->nCte-1);
  28142. sqlite3TreeViewSelect(pView, pCte->pSelect, 0);
  28143. sqlite3TreeViewPop(pView);
  28144. }
  28145. sqlite3TreeViewPop(pView);
  28146. }
  28147. }
  28148. /*
  28149. ** Generate a human-readable description of a SrcList object.
  28150. */
  28151. SQLITE_PRIVATE void sqlite3TreeViewSrcList(TreeView *pView, const SrcList *pSrc){
  28152. int i;
  28153. for(i=0; i<pSrc->nSrc; i++){
  28154. const struct SrcList_item *pItem = &pSrc->a[i];
  28155. StrAccum x;
  28156. char zLine[100];
  28157. sqlite3StrAccumInit(&x, 0, zLine, sizeof(zLine), 0);
  28158. sqlite3_str_appendf(&x, "{%d:*}", pItem->iCursor);
  28159. if( pItem->zDatabase ){
  28160. sqlite3_str_appendf(&x, " %s.%s", pItem->zDatabase, pItem->zName);
  28161. }else if( pItem->zName ){
  28162. sqlite3_str_appendf(&x, " %s", pItem->zName);
  28163. }
  28164. if( pItem->pTab ){
  28165. sqlite3_str_appendf(&x, " tab=%Q nCol=%d ptr=%p used=%llx",
  28166. pItem->pTab->zName, pItem->pTab->nCol, pItem->pTab, pItem->colUsed);
  28167. }
  28168. if( pItem->zAlias ){
  28169. sqlite3_str_appendf(&x, " (AS %s)", pItem->zAlias);
  28170. }
  28171. if( pItem->fg.jointype & JT_LEFT ){
  28172. sqlite3_str_appendf(&x, " LEFT-JOIN");
  28173. }
  28174. if( pItem->fg.fromDDL ){
  28175. sqlite3_str_appendf(&x, " DDL");
  28176. }
  28177. sqlite3StrAccumFinish(&x);
  28178. sqlite3TreeViewItem(pView, zLine, i<pSrc->nSrc-1);
  28179. if( pItem->pSelect ){
  28180. sqlite3TreeViewSelect(pView, pItem->pSelect, 0);
  28181. }
  28182. if( pItem->fg.isTabFunc ){
  28183. sqlite3TreeViewExprList(pView, pItem->u1.pFuncArg, 0, "func-args:");
  28184. }
  28185. sqlite3TreeViewPop(pView);
  28186. }
  28187. }
  28188. /*
  28189. ** Generate a human-readable description of a Select object.
  28190. */
  28191. SQLITE_PRIVATE void sqlite3TreeViewSelect(TreeView *pView, const Select *p, u8 moreToFollow){
  28192. int n = 0;
  28193. int cnt = 0;
  28194. if( p==0 ){
  28195. sqlite3TreeViewLine(pView, "nil-SELECT");
  28196. return;
  28197. }
  28198. pView = sqlite3TreeViewPush(pView, moreToFollow);
  28199. if( p->pWith ){
  28200. sqlite3TreeViewWith(pView, p->pWith, 1);
  28201. cnt = 1;
  28202. sqlite3TreeViewPush(pView, 1);
  28203. }
  28204. do{
  28205. if( p->selFlags & SF_WhereBegin ){
  28206. sqlite3TreeViewLine(pView, "sqlite3WhereBegin()");
  28207. }else{
  28208. sqlite3TreeViewLine(pView,
  28209. "SELECT%s%s (%u/%p) selFlags=0x%x nSelectRow=%d",
  28210. ((p->selFlags & SF_Distinct) ? " DISTINCT" : ""),
  28211. ((p->selFlags & SF_Aggregate) ? " agg_flag" : ""),
  28212. p->selId, p, p->selFlags,
  28213. (int)p->nSelectRow
  28214. );
  28215. }
  28216. if( cnt++ ) sqlite3TreeViewPop(pView);
  28217. if( p->pPrior ){
  28218. n = 1000;
  28219. }else{
  28220. n = 0;
  28221. if( p->pSrc && p->pSrc->nSrc ) n++;
  28222. if( p->pWhere ) n++;
  28223. if( p->pGroupBy ) n++;
  28224. if( p->pHaving ) n++;
  28225. if( p->pOrderBy ) n++;
  28226. if( p->pLimit ) n++;
  28227. #ifndef SQLITE_OMIT_WINDOWFUNC
  28228. if( p->pWin ) n++;
  28229. if( p->pWinDefn ) n++;
  28230. #endif
  28231. }
  28232. if( p->pEList ){
  28233. sqlite3TreeViewExprList(pView, p->pEList, n>0, "result-set");
  28234. }
  28235. n--;
  28236. #ifndef SQLITE_OMIT_WINDOWFUNC
  28237. if( p->pWin ){
  28238. Window *pX;
  28239. pView = sqlite3TreeViewPush(pView, (n--)>0);
  28240. sqlite3TreeViewLine(pView, "window-functions");
  28241. for(pX=p->pWin; pX; pX=pX->pNextWin){
  28242. sqlite3TreeViewWinFunc(pView, pX, pX->pNextWin!=0);
  28243. }
  28244. sqlite3TreeViewPop(pView);
  28245. }
  28246. #endif
  28247. if( p->pSrc && p->pSrc->nSrc ){
  28248. pView = sqlite3TreeViewPush(pView, (n--)>0);
  28249. sqlite3TreeViewLine(pView, "FROM");
  28250. sqlite3TreeViewSrcList(pView, p->pSrc);
  28251. sqlite3TreeViewPop(pView);
  28252. }
  28253. if( p->pWhere ){
  28254. sqlite3TreeViewItem(pView, "WHERE", (n--)>0);
  28255. sqlite3TreeViewExpr(pView, p->pWhere, 0);
  28256. sqlite3TreeViewPop(pView);
  28257. }
  28258. if( p->pGroupBy ){
  28259. sqlite3TreeViewExprList(pView, p->pGroupBy, (n--)>0, "GROUPBY");
  28260. }
  28261. if( p->pHaving ){
  28262. sqlite3TreeViewItem(pView, "HAVING", (n--)>0);
  28263. sqlite3TreeViewExpr(pView, p->pHaving, 0);
  28264. sqlite3TreeViewPop(pView);
  28265. }
  28266. #ifndef SQLITE_OMIT_WINDOWFUNC
  28267. if( p->pWinDefn ){
  28268. Window *pX;
  28269. sqlite3TreeViewItem(pView, "WINDOW", (n--)>0);
  28270. for(pX=p->pWinDefn; pX; pX=pX->pNextWin){
  28271. sqlite3TreeViewWindow(pView, pX, pX->pNextWin!=0);
  28272. }
  28273. sqlite3TreeViewPop(pView);
  28274. }
  28275. #endif
  28276. if( p->pOrderBy ){
  28277. sqlite3TreeViewExprList(pView, p->pOrderBy, (n--)>0, "ORDERBY");
  28278. }
  28279. if( p->pLimit ){
  28280. sqlite3TreeViewItem(pView, "LIMIT", (n--)>0);
  28281. sqlite3TreeViewExpr(pView, p->pLimit->pLeft, p->pLimit->pRight!=0);
  28282. if( p->pLimit->pRight ){
  28283. sqlite3TreeViewItem(pView, "OFFSET", (n--)>0);
  28284. sqlite3TreeViewExpr(pView, p->pLimit->pRight, 0);
  28285. sqlite3TreeViewPop(pView);
  28286. }
  28287. sqlite3TreeViewPop(pView);
  28288. }
  28289. if( p->pPrior ){
  28290. const char *zOp = "UNION";
  28291. switch( p->op ){
  28292. case TK_ALL: zOp = "UNION ALL"; break;
  28293. case TK_INTERSECT: zOp = "INTERSECT"; break;
  28294. case TK_EXCEPT: zOp = "EXCEPT"; break;
  28295. }
  28296. sqlite3TreeViewItem(pView, zOp, 1);
  28297. }
  28298. p = p->pPrior;
  28299. }while( p!=0 );
  28300. sqlite3TreeViewPop(pView);
  28301. }
  28302. #ifndef SQLITE_OMIT_WINDOWFUNC
  28303. /*
  28304. ** Generate a description of starting or stopping bounds
  28305. */
  28306. SQLITE_PRIVATE void sqlite3TreeViewBound(
  28307. TreeView *pView, /* View context */
  28308. u8 eBound, /* UNBOUNDED, CURRENT, PRECEDING, FOLLOWING */
  28309. Expr *pExpr, /* Value for PRECEDING or FOLLOWING */
  28310. u8 moreToFollow /* True if more to follow */
  28311. ){
  28312. switch( eBound ){
  28313. case TK_UNBOUNDED: {
  28314. sqlite3TreeViewItem(pView, "UNBOUNDED", moreToFollow);
  28315. sqlite3TreeViewPop(pView);
  28316. break;
  28317. }
  28318. case TK_CURRENT: {
  28319. sqlite3TreeViewItem(pView, "CURRENT", moreToFollow);
  28320. sqlite3TreeViewPop(pView);
  28321. break;
  28322. }
  28323. case TK_PRECEDING: {
  28324. sqlite3TreeViewItem(pView, "PRECEDING", moreToFollow);
  28325. sqlite3TreeViewExpr(pView, pExpr, 0);
  28326. sqlite3TreeViewPop(pView);
  28327. break;
  28328. }
  28329. case TK_FOLLOWING: {
  28330. sqlite3TreeViewItem(pView, "FOLLOWING", moreToFollow);
  28331. sqlite3TreeViewExpr(pView, pExpr, 0);
  28332. sqlite3TreeViewPop(pView);
  28333. break;
  28334. }
  28335. }
  28336. }
  28337. #endif /* SQLITE_OMIT_WINDOWFUNC */
  28338. #ifndef SQLITE_OMIT_WINDOWFUNC
  28339. /*
  28340. ** Generate a human-readable explanation for a Window object
  28341. */
  28342. SQLITE_PRIVATE void sqlite3TreeViewWindow(TreeView *pView, const Window *pWin, u8 more){
  28343. int nElement = 0;
  28344. if( pWin->pFilter ){
  28345. sqlite3TreeViewItem(pView, "FILTER", 1);
  28346. sqlite3TreeViewExpr(pView, pWin->pFilter, 0);
  28347. sqlite3TreeViewPop(pView);
  28348. }
  28349. pView = sqlite3TreeViewPush(pView, more);
  28350. if( pWin->zName ){
  28351. sqlite3TreeViewLine(pView, "OVER %s (%p)", pWin->zName, pWin);
  28352. }else{
  28353. sqlite3TreeViewLine(pView, "OVER (%p)", pWin);
  28354. }
  28355. if( pWin->zBase ) nElement++;
  28356. if( pWin->pOrderBy ) nElement++;
  28357. if( pWin->eFrmType ) nElement++;
  28358. if( pWin->eExclude ) nElement++;
  28359. if( pWin->zBase ){
  28360. sqlite3TreeViewPush(pView, (--nElement)>0);
  28361. sqlite3TreeViewLine(pView, "window: %s", pWin->zBase);
  28362. sqlite3TreeViewPop(pView);
  28363. }
  28364. if( pWin->pPartition ){
  28365. sqlite3TreeViewExprList(pView, pWin->pPartition, nElement>0,"PARTITION-BY");
  28366. }
  28367. if( pWin->pOrderBy ){
  28368. sqlite3TreeViewExprList(pView, pWin->pOrderBy, (--nElement)>0, "ORDER-BY");
  28369. }
  28370. if( pWin->eFrmType ){
  28371. char zBuf[30];
  28372. const char *zFrmType = "ROWS";
  28373. if( pWin->eFrmType==TK_RANGE ) zFrmType = "RANGE";
  28374. if( pWin->eFrmType==TK_GROUPS ) zFrmType = "GROUPS";
  28375. sqlite3_snprintf(sizeof(zBuf),zBuf,"%s%s",zFrmType,
  28376. pWin->bImplicitFrame ? " (implied)" : "");
  28377. sqlite3TreeViewItem(pView, zBuf, (--nElement)>0);
  28378. sqlite3TreeViewBound(pView, pWin->eStart, pWin->pStart, 1);
  28379. sqlite3TreeViewBound(pView, pWin->eEnd, pWin->pEnd, 0);
  28380. sqlite3TreeViewPop(pView);
  28381. }
  28382. if( pWin->eExclude ){
  28383. char zBuf[30];
  28384. const char *zExclude;
  28385. switch( pWin->eExclude ){
  28386. case TK_NO: zExclude = "NO OTHERS"; break;
  28387. case TK_CURRENT: zExclude = "CURRENT ROW"; break;
  28388. case TK_GROUP: zExclude = "GROUP"; break;
  28389. case TK_TIES: zExclude = "TIES"; break;
  28390. default:
  28391. sqlite3_snprintf(sizeof(zBuf),zBuf,"invalid(%d)", pWin->eExclude);
  28392. zExclude = zBuf;
  28393. break;
  28394. }
  28395. sqlite3TreeViewPush(pView, 0);
  28396. sqlite3TreeViewLine(pView, "EXCLUDE %s", zExclude);
  28397. sqlite3TreeViewPop(pView);
  28398. }
  28399. sqlite3TreeViewPop(pView);
  28400. }
  28401. #endif /* SQLITE_OMIT_WINDOWFUNC */
  28402. #ifndef SQLITE_OMIT_WINDOWFUNC
  28403. /*
  28404. ** Generate a human-readable explanation for a Window Function object
  28405. */
  28406. SQLITE_PRIVATE void sqlite3TreeViewWinFunc(TreeView *pView, const Window *pWin, u8 more){
  28407. pView = sqlite3TreeViewPush(pView, more);
  28408. sqlite3TreeViewLine(pView, "WINFUNC %s(%d)",
  28409. pWin->pFunc->zName, pWin->pFunc->nArg);
  28410. sqlite3TreeViewWindow(pView, pWin, 0);
  28411. sqlite3TreeViewPop(pView);
  28412. }
  28413. #endif /* SQLITE_OMIT_WINDOWFUNC */
  28414. /*
  28415. ** Generate a human-readable explanation of an expression tree.
  28416. */
  28417. SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView *pView, const Expr *pExpr, u8 moreToFollow){
  28418. const char *zBinOp = 0; /* Binary operator */
  28419. const char *zUniOp = 0; /* Unary operator */
  28420. char zFlgs[200];
  28421. pView = sqlite3TreeViewPush(pView, moreToFollow);
  28422. if( pExpr==0 ){
  28423. sqlite3TreeViewLine(pView, "nil");
  28424. sqlite3TreeViewPop(pView);
  28425. return;
  28426. }
  28427. if( pExpr->flags || pExpr->affExpr || pExpr->vvaFlags ){
  28428. StrAccum x;
  28429. sqlite3StrAccumInit(&x, 0, zFlgs, sizeof(zFlgs), 0);
  28430. sqlite3_str_appendf(&x, " fg.af=%x.%c",
  28431. pExpr->flags, pExpr->affExpr ? pExpr->affExpr : 'n');
  28432. if( ExprHasProperty(pExpr, EP_FromJoin) ){
  28433. sqlite3_str_appendf(&x, " iRJT=%d", pExpr->iRightJoinTable);
  28434. }
  28435. if( ExprHasProperty(pExpr, EP_FromDDL) ){
  28436. sqlite3_str_appendf(&x, " DDL");
  28437. }
  28438. if( ExprHasVVAProperty(pExpr, EP_Immutable) ){
  28439. sqlite3_str_appendf(&x, " IMMUTABLE");
  28440. }
  28441. sqlite3StrAccumFinish(&x);
  28442. }else{
  28443. zFlgs[0] = 0;
  28444. }
  28445. switch( pExpr->op ){
  28446. case TK_AGG_COLUMN: {
  28447. sqlite3TreeViewLine(pView, "AGG{%d:%d}%s",
  28448. pExpr->iTable, pExpr->iColumn, zFlgs);
  28449. break;
  28450. }
  28451. case TK_COLUMN: {
  28452. if( pExpr->iTable<0 ){
  28453. /* This only happens when coding check constraints */
  28454. char zOp2[16];
  28455. if( pExpr->op2 ){
  28456. sqlite3_snprintf(sizeof(zOp2),zOp2," op2=0x%02x",pExpr->op2);
  28457. }else{
  28458. zOp2[0] = 0;
  28459. }
  28460. sqlite3TreeViewLine(pView, "COLUMN(%d)%s%s",
  28461. pExpr->iColumn, zFlgs, zOp2);
  28462. }else{
  28463. sqlite3TreeViewLine(pView, "{%d:%d} pTab=%p%s",
  28464. pExpr->iTable, pExpr->iColumn,
  28465. pExpr->y.pTab, zFlgs);
  28466. }
  28467. if( ExprHasProperty(pExpr, EP_FixedCol) ){
  28468. sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
  28469. }
  28470. break;
  28471. }
  28472. case TK_INTEGER: {
  28473. if( pExpr->flags & EP_IntValue ){
  28474. sqlite3TreeViewLine(pView, "%d", pExpr->u.iValue);
  28475. }else{
  28476. sqlite3TreeViewLine(pView, "%s", pExpr->u.zToken);
  28477. }
  28478. break;
  28479. }
  28480. #ifndef SQLITE_OMIT_FLOATING_POINT
  28481. case TK_FLOAT: {
  28482. sqlite3TreeViewLine(pView,"%s", pExpr->u.zToken);
  28483. break;
  28484. }
  28485. #endif
  28486. case TK_STRING: {
  28487. sqlite3TreeViewLine(pView,"%Q", pExpr->u.zToken);
  28488. break;
  28489. }
  28490. case TK_NULL: {
  28491. sqlite3TreeViewLine(pView,"NULL");
  28492. break;
  28493. }
  28494. case TK_TRUEFALSE: {
  28495. sqlite3TreeViewLine(pView,
  28496. sqlite3ExprTruthValue(pExpr) ? "TRUE" : "FALSE");
  28497. break;
  28498. }
  28499. #ifndef SQLITE_OMIT_BLOB_LITERAL
  28500. case TK_BLOB: {
  28501. sqlite3TreeViewLine(pView,"%s", pExpr->u.zToken);
  28502. break;
  28503. }
  28504. #endif
  28505. case TK_VARIABLE: {
  28506. sqlite3TreeViewLine(pView,"VARIABLE(%s,%d)",
  28507. pExpr->u.zToken, pExpr->iColumn);
  28508. break;
  28509. }
  28510. case TK_REGISTER: {
  28511. sqlite3TreeViewLine(pView,"REGISTER(%d)", pExpr->iTable);
  28512. break;
  28513. }
  28514. case TK_ID: {
  28515. sqlite3TreeViewLine(pView,"ID \"%w\"", pExpr->u.zToken);
  28516. break;
  28517. }
  28518. #ifndef SQLITE_OMIT_CAST
  28519. case TK_CAST: {
  28520. /* Expressions of the form: CAST(pLeft AS token) */
  28521. sqlite3TreeViewLine(pView,"CAST %Q", pExpr->u.zToken);
  28522. sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
  28523. break;
  28524. }
  28525. #endif /* SQLITE_OMIT_CAST */
  28526. case TK_LT: zBinOp = "LT"; break;
  28527. case TK_LE: zBinOp = "LE"; break;
  28528. case TK_GT: zBinOp = "GT"; break;
  28529. case TK_GE: zBinOp = "GE"; break;
  28530. case TK_NE: zBinOp = "NE"; break;
  28531. case TK_EQ: zBinOp = "EQ"; break;
  28532. case TK_IS: zBinOp = "IS"; break;
  28533. case TK_ISNOT: zBinOp = "ISNOT"; break;
  28534. case TK_AND: zBinOp = "AND"; break;
  28535. case TK_OR: zBinOp = "OR"; break;
  28536. case TK_PLUS: zBinOp = "ADD"; break;
  28537. case TK_STAR: zBinOp = "MUL"; break;
  28538. case TK_MINUS: zBinOp = "SUB"; break;
  28539. case TK_REM: zBinOp = "REM"; break;
  28540. case TK_BITAND: zBinOp = "BITAND"; break;
  28541. case TK_BITOR: zBinOp = "BITOR"; break;
  28542. case TK_SLASH: zBinOp = "DIV"; break;
  28543. case TK_LSHIFT: zBinOp = "LSHIFT"; break;
  28544. case TK_RSHIFT: zBinOp = "RSHIFT"; break;
  28545. case TK_CONCAT: zBinOp = "CONCAT"; break;
  28546. case TK_DOT: zBinOp = "DOT"; break;
  28547. case TK_LIMIT: zBinOp = "LIMIT"; break;
  28548. case TK_UMINUS: zUniOp = "UMINUS"; break;
  28549. case TK_UPLUS: zUniOp = "UPLUS"; break;
  28550. case TK_BITNOT: zUniOp = "BITNOT"; break;
  28551. case TK_NOT: zUniOp = "NOT"; break;
  28552. case TK_ISNULL: zUniOp = "ISNULL"; break;
  28553. case TK_NOTNULL: zUniOp = "NOTNULL"; break;
  28554. case TK_TRUTH: {
  28555. int x;
  28556. const char *azOp[] = {
  28557. "IS-FALSE", "IS-TRUE", "IS-NOT-FALSE", "IS-NOT-TRUE"
  28558. };
  28559. assert( pExpr->op2==TK_IS || pExpr->op2==TK_ISNOT );
  28560. assert( pExpr->pRight );
  28561. assert( sqlite3ExprSkipCollate(pExpr->pRight)->op==TK_TRUEFALSE );
  28562. x = (pExpr->op2==TK_ISNOT)*2 + sqlite3ExprTruthValue(pExpr->pRight);
  28563. zUniOp = azOp[x];
  28564. break;
  28565. }
  28566. case TK_SPAN: {
  28567. sqlite3TreeViewLine(pView, "SPAN %Q", pExpr->u.zToken);
  28568. sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
  28569. break;
  28570. }
  28571. case TK_COLLATE: {
  28572. /* COLLATE operators without the EP_Collate flag are intended to
  28573. ** emulate collation associated with a table column. These show
  28574. ** up in the treeview output as "SOFT-COLLATE". Explicit COLLATE
  28575. ** operators that appear in the original SQL always have the
  28576. ** EP_Collate bit set and appear in treeview output as just "COLLATE" */
  28577. sqlite3TreeViewLine(pView, "%sCOLLATE %Q%s",
  28578. !ExprHasProperty(pExpr, EP_Collate) ? "SOFT-" : "",
  28579. pExpr->u.zToken, zFlgs);
  28580. sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
  28581. break;
  28582. }
  28583. case TK_AGG_FUNCTION:
  28584. case TK_FUNCTION: {
  28585. ExprList *pFarg; /* List of function arguments */
  28586. Window *pWin;
  28587. if( ExprHasProperty(pExpr, EP_TokenOnly) ){
  28588. pFarg = 0;
  28589. pWin = 0;
  28590. }else{
  28591. pFarg = pExpr->x.pList;
  28592. #ifndef SQLITE_OMIT_WINDOWFUNC
  28593. pWin = ExprHasProperty(pExpr, EP_WinFunc) ? pExpr->y.pWin : 0;
  28594. #else
  28595. pWin = 0;
  28596. #endif
  28597. }
  28598. if( pExpr->op==TK_AGG_FUNCTION ){
  28599. sqlite3TreeViewLine(pView, "AGG_FUNCTION%d %Q%s iAgg=%d agg=%p",
  28600. pExpr->op2, pExpr->u.zToken, zFlgs,
  28601. pExpr->iAgg, pExpr->pAggInfo);
  28602. }else if( pExpr->op2!=0 ){
  28603. const char *zOp2;
  28604. char zBuf[8];
  28605. sqlite3_snprintf(sizeof(zBuf),zBuf,"0x%02x",pExpr->op2);
  28606. zOp2 = zBuf;
  28607. if( pExpr->op2==NC_IsCheck ) zOp2 = "NC_IsCheck";
  28608. if( pExpr->op2==NC_IdxExpr ) zOp2 = "NC_IdxExpr";
  28609. if( pExpr->op2==NC_PartIdx ) zOp2 = "NC_PartIdx";
  28610. if( pExpr->op2==NC_GenCol ) zOp2 = "NC_GenCol";
  28611. sqlite3TreeViewLine(pView, "FUNCTION %Q%s op2=%s",
  28612. pExpr->u.zToken, zFlgs, zOp2);
  28613. }else{
  28614. sqlite3TreeViewLine(pView, "FUNCTION %Q%s", pExpr->u.zToken, zFlgs);
  28615. }
  28616. if( pFarg ){
  28617. sqlite3TreeViewExprList(pView, pFarg, pWin!=0, 0);
  28618. }
  28619. #ifndef SQLITE_OMIT_WINDOWFUNC
  28620. if( pWin ){
  28621. sqlite3TreeViewWindow(pView, pWin, 0);
  28622. }
  28623. #endif
  28624. break;
  28625. }
  28626. #ifndef SQLITE_OMIT_SUBQUERY
  28627. case TK_EXISTS: {
  28628. sqlite3TreeViewLine(pView, "EXISTS-expr flags=0x%x", pExpr->flags);
  28629. sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
  28630. break;
  28631. }
  28632. case TK_SELECT: {
  28633. sqlite3TreeViewLine(pView, "SELECT-expr flags=0x%x", pExpr->flags);
  28634. sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
  28635. break;
  28636. }
  28637. case TK_IN: {
  28638. sqlite3TreeViewLine(pView, "IN flags=0x%x", pExpr->flags);
  28639. sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
  28640. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  28641. sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
  28642. }else{
  28643. sqlite3TreeViewExprList(pView, pExpr->x.pList, 0, 0);
  28644. }
  28645. break;
  28646. }
  28647. #endif /* SQLITE_OMIT_SUBQUERY */
  28648. /*
  28649. ** x BETWEEN y AND z
  28650. **
  28651. ** This is equivalent to
  28652. **
  28653. ** x>=y AND x<=z
  28654. **
  28655. ** X is stored in pExpr->pLeft.
  28656. ** Y is stored in pExpr->pList->a[0].pExpr.
  28657. ** Z is stored in pExpr->pList->a[1].pExpr.
  28658. */
  28659. case TK_BETWEEN: {
  28660. Expr *pX = pExpr->pLeft;
  28661. Expr *pY = pExpr->x.pList->a[0].pExpr;
  28662. Expr *pZ = pExpr->x.pList->a[1].pExpr;
  28663. sqlite3TreeViewLine(pView, "BETWEEN");
  28664. sqlite3TreeViewExpr(pView, pX, 1);
  28665. sqlite3TreeViewExpr(pView, pY, 1);
  28666. sqlite3TreeViewExpr(pView, pZ, 0);
  28667. break;
  28668. }
  28669. case TK_TRIGGER: {
  28670. /* If the opcode is TK_TRIGGER, then the expression is a reference
  28671. ** to a column in the new.* or old.* pseudo-tables available to
  28672. ** trigger programs. In this case Expr.iTable is set to 1 for the
  28673. ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
  28674. ** is set to the column of the pseudo-table to read, or to -1 to
  28675. ** read the rowid field.
  28676. */
  28677. sqlite3TreeViewLine(pView, "%s(%d)",
  28678. pExpr->iTable ? "NEW" : "OLD", pExpr->iColumn);
  28679. break;
  28680. }
  28681. case TK_CASE: {
  28682. sqlite3TreeViewLine(pView, "CASE");
  28683. sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
  28684. sqlite3TreeViewExprList(pView, pExpr->x.pList, 0, 0);
  28685. break;
  28686. }
  28687. #ifndef SQLITE_OMIT_TRIGGER
  28688. case TK_RAISE: {
  28689. const char *zType = "unk";
  28690. switch( pExpr->affExpr ){
  28691. case OE_Rollback: zType = "rollback"; break;
  28692. case OE_Abort: zType = "abort"; break;
  28693. case OE_Fail: zType = "fail"; break;
  28694. case OE_Ignore: zType = "ignore"; break;
  28695. }
  28696. sqlite3TreeViewLine(pView, "RAISE %s(%Q)", zType, pExpr->u.zToken);
  28697. break;
  28698. }
  28699. #endif
  28700. case TK_MATCH: {
  28701. sqlite3TreeViewLine(pView, "MATCH {%d:%d}%s",
  28702. pExpr->iTable, pExpr->iColumn, zFlgs);
  28703. sqlite3TreeViewExpr(pView, pExpr->pRight, 0);
  28704. break;
  28705. }
  28706. case TK_VECTOR: {
  28707. char *z = sqlite3_mprintf("VECTOR%s",zFlgs);
  28708. sqlite3TreeViewBareExprList(pView, pExpr->x.pList, z);
  28709. sqlite3_free(z);
  28710. break;
  28711. }
  28712. case TK_SELECT_COLUMN: {
  28713. sqlite3TreeViewLine(pView, "SELECT-COLUMN %d", pExpr->iColumn);
  28714. sqlite3TreeViewSelect(pView, pExpr->pLeft->x.pSelect, 0);
  28715. break;
  28716. }
  28717. case TK_IF_NULL_ROW: {
  28718. sqlite3TreeViewLine(pView, "IF-NULL-ROW %d", pExpr->iTable);
  28719. sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
  28720. break;
  28721. }
  28722. default: {
  28723. sqlite3TreeViewLine(pView, "op=%d", pExpr->op);
  28724. break;
  28725. }
  28726. }
  28727. if( zBinOp ){
  28728. sqlite3TreeViewLine(pView, "%s%s", zBinOp, zFlgs);
  28729. sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
  28730. sqlite3TreeViewExpr(pView, pExpr->pRight, 0);
  28731. }else if( zUniOp ){
  28732. sqlite3TreeViewLine(pView, "%s%s", zUniOp, zFlgs);
  28733. sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
  28734. }
  28735. sqlite3TreeViewPop(pView);
  28736. }
  28737. /*
  28738. ** Generate a human-readable explanation of an expression list.
  28739. */
  28740. SQLITE_PRIVATE void sqlite3TreeViewBareExprList(
  28741. TreeView *pView,
  28742. const ExprList *pList,
  28743. const char *zLabel
  28744. ){
  28745. if( zLabel==0 || zLabel[0]==0 ) zLabel = "LIST";
  28746. if( pList==0 ){
  28747. sqlite3TreeViewLine(pView, "%s (empty)", zLabel);
  28748. }else{
  28749. int i;
  28750. sqlite3TreeViewLine(pView, "%s", zLabel);
  28751. for(i=0; i<pList->nExpr; i++){
  28752. int j = pList->a[i].u.x.iOrderByCol;
  28753. char *zName = pList->a[i].zEName;
  28754. int moreToFollow = i<pList->nExpr - 1;
  28755. if( pList->a[i].eEName!=ENAME_NAME ) zName = 0;
  28756. if( j || zName ){
  28757. sqlite3TreeViewPush(pView, moreToFollow);
  28758. moreToFollow = 0;
  28759. sqlite3TreeViewLine(pView, 0);
  28760. if( zName ){
  28761. fprintf(stdout, "AS %s ", zName);
  28762. }
  28763. if( j ){
  28764. fprintf(stdout, "iOrderByCol=%d", j);
  28765. }
  28766. fprintf(stdout, "\n");
  28767. fflush(stdout);
  28768. }
  28769. sqlite3TreeViewExpr(pView, pList->a[i].pExpr, moreToFollow);
  28770. if( j || zName ){
  28771. sqlite3TreeViewPop(pView);
  28772. }
  28773. }
  28774. }
  28775. }
  28776. SQLITE_PRIVATE void sqlite3TreeViewExprList(
  28777. TreeView *pView,
  28778. const ExprList *pList,
  28779. u8 moreToFollow,
  28780. const char *zLabel
  28781. ){
  28782. pView = sqlite3TreeViewPush(pView, moreToFollow);
  28783. sqlite3TreeViewBareExprList(pView, pList, zLabel);
  28784. sqlite3TreeViewPop(pView);
  28785. }
  28786. #endif /* SQLITE_DEBUG */
  28787. /************** End of treeview.c ********************************************/
  28788. /************** Begin file random.c ******************************************/
  28789. /*
  28790. ** 2001 September 15
  28791. **
  28792. ** The author disclaims copyright to this source code. In place of
  28793. ** a legal notice, here is a blessing:
  28794. **
  28795. ** May you do good and not evil.
  28796. ** May you find forgiveness for yourself and forgive others.
  28797. ** May you share freely, never taking more than you give.
  28798. **
  28799. *************************************************************************
  28800. ** This file contains code to implement a pseudo-random number
  28801. ** generator (PRNG) for SQLite.
  28802. **
  28803. ** Random numbers are used by some of the database backends in order
  28804. ** to generate random integer keys for tables or random filenames.
  28805. */
  28806. /* #include "sqliteInt.h" */
  28807. /* All threads share a single random number generator.
  28808. ** This structure is the current state of the generator.
  28809. */
  28810. static SQLITE_WSD struct sqlite3PrngType {
  28811. unsigned char isInit; /* True if initialized */
  28812. unsigned char i, j; /* State variables */
  28813. unsigned char s[256]; /* State variables */
  28814. } sqlite3Prng;
  28815. /*
  28816. ** Return N random bytes.
  28817. */
  28818. SQLITE_API void sqlite3_randomness(int N, void *pBuf){
  28819. unsigned char t;
  28820. unsigned char *zBuf = pBuf;
  28821. /* The "wsdPrng" macro will resolve to the pseudo-random number generator
  28822. ** state vector. If writable static data is unsupported on the target,
  28823. ** we have to locate the state vector at run-time. In the more common
  28824. ** case where writable static data is supported, wsdPrng can refer directly
  28825. ** to the "sqlite3Prng" state vector declared above.
  28826. */
  28827. #ifdef SQLITE_OMIT_WSD
  28828. struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng);
  28829. # define wsdPrng p[0]
  28830. #else
  28831. # define wsdPrng sqlite3Prng
  28832. #endif
  28833. #if SQLITE_THREADSAFE
  28834. sqlite3_mutex *mutex;
  28835. #endif
  28836. #ifndef SQLITE_OMIT_AUTOINIT
  28837. if( sqlite3_initialize() ) return;
  28838. #endif
  28839. #if SQLITE_THREADSAFE
  28840. mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);
  28841. #endif
  28842. sqlite3_mutex_enter(mutex);
  28843. if( N<=0 || pBuf==0 ){
  28844. wsdPrng.isInit = 0;
  28845. sqlite3_mutex_leave(mutex);
  28846. return;
  28847. }
  28848. /* Initialize the state of the random number generator once,
  28849. ** the first time this routine is called. The seed value does
  28850. ** not need to contain a lot of randomness since we are not
  28851. ** trying to do secure encryption or anything like that...
  28852. **
  28853. ** Nothing in this file or anywhere else in SQLite does any kind of
  28854. ** encryption. The RC4 algorithm is being used as a PRNG (pseudo-random
  28855. ** number generator) not as an encryption device.
  28856. */
  28857. if( !wsdPrng.isInit ){
  28858. int i;
  28859. char k[256];
  28860. wsdPrng.j = 0;
  28861. wsdPrng.i = 0;
  28862. sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k);
  28863. for(i=0; i<256; i++){
  28864. wsdPrng.s[i] = (u8)i;
  28865. }
  28866. for(i=0; i<256; i++){
  28867. wsdPrng.j += wsdPrng.s[i] + k[i];
  28868. t = wsdPrng.s[wsdPrng.j];
  28869. wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];
  28870. wsdPrng.s[i] = t;
  28871. }
  28872. wsdPrng.isInit = 1;
  28873. }
  28874. assert( N>0 );
  28875. do{
  28876. wsdPrng.i++;
  28877. t = wsdPrng.s[wsdPrng.i];
  28878. wsdPrng.j += t;
  28879. wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j];
  28880. wsdPrng.s[wsdPrng.j] = t;
  28881. t += wsdPrng.s[wsdPrng.i];
  28882. *(zBuf++) = wsdPrng.s[t];
  28883. }while( --N );
  28884. sqlite3_mutex_leave(mutex);
  28885. }
  28886. #ifndef SQLITE_UNTESTABLE
  28887. /*
  28888. ** For testing purposes, we sometimes want to preserve the state of
  28889. ** PRNG and restore the PRNG to its saved state at a later time, or
  28890. ** to reset the PRNG to its initial state. These routines accomplish
  28891. ** those tasks.
  28892. **
  28893. ** The sqlite3_test_control() interface calls these routines to
  28894. ** control the PRNG.
  28895. */
  28896. static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng;
  28897. SQLITE_PRIVATE void sqlite3PrngSaveState(void){
  28898. memcpy(
  28899. &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
  28900. &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
  28901. sizeof(sqlite3Prng)
  28902. );
  28903. }
  28904. SQLITE_PRIVATE void sqlite3PrngRestoreState(void){
  28905. memcpy(
  28906. &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
  28907. &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
  28908. sizeof(sqlite3Prng)
  28909. );
  28910. }
  28911. #endif /* SQLITE_UNTESTABLE */
  28912. /************** End of random.c **********************************************/
  28913. /************** Begin file threads.c *****************************************/
  28914. /*
  28915. ** 2012 July 21
  28916. **
  28917. ** The author disclaims copyright to this source code. In place of
  28918. ** a legal notice, here is a blessing:
  28919. **
  28920. ** May you do good and not evil.
  28921. ** May you find forgiveness for yourself and forgive others.
  28922. ** May you share freely, never taking more than you give.
  28923. **
  28924. ******************************************************************************
  28925. **
  28926. ** This file presents a simple cross-platform threading interface for
  28927. ** use internally by SQLite.
  28928. **
  28929. ** A "thread" can be created using sqlite3ThreadCreate(). This thread
  28930. ** runs independently of its creator until it is joined using
  28931. ** sqlite3ThreadJoin(), at which point it terminates.
  28932. **
  28933. ** Threads do not have to be real. It could be that the work of the
  28934. ** "thread" is done by the main thread at either the sqlite3ThreadCreate()
  28935. ** or sqlite3ThreadJoin() call. This is, in fact, what happens in
  28936. ** single threaded systems. Nothing in SQLite requires multiple threads.
  28937. ** This interface exists so that applications that want to take advantage
  28938. ** of multiple cores can do so, while also allowing applications to stay
  28939. ** single-threaded if desired.
  28940. */
  28941. /* #include "sqliteInt.h" */
  28942. #if SQLITE_OS_WIN
  28943. /* # include "os_win.h" */
  28944. #endif
  28945. #if SQLITE_MAX_WORKER_THREADS>0
  28946. /********************************* Unix Pthreads ****************************/
  28947. #if SQLITE_OS_UNIX && defined(SQLITE_MUTEX_PTHREADS) && SQLITE_THREADSAFE>0
  28948. #define SQLITE_THREADS_IMPLEMENTED 1 /* Prevent the single-thread code below */
  28949. /* #include <pthread.h> */
  28950. /* A running thread */
  28951. struct SQLiteThread {
  28952. pthread_t tid; /* Thread ID */
  28953. int done; /* Set to true when thread finishes */
  28954. void *pOut; /* Result returned by the thread */
  28955. void *(*xTask)(void*); /* The thread routine */
  28956. void *pIn; /* Argument to the thread */
  28957. };
  28958. /* Create a new thread */
  28959. SQLITE_PRIVATE int sqlite3ThreadCreate(
  28960. SQLiteThread **ppThread, /* OUT: Write the thread object here */
  28961. void *(*xTask)(void*), /* Routine to run in a separate thread */
  28962. void *pIn /* Argument passed into xTask() */
  28963. ){
  28964. SQLiteThread *p;
  28965. int rc;
  28966. assert( ppThread!=0 );
  28967. assert( xTask!=0 );
  28968. /* This routine is never used in single-threaded mode */
  28969. assert( sqlite3GlobalConfig.bCoreMutex!=0 );
  28970. *ppThread = 0;
  28971. p = sqlite3Malloc(sizeof(*p));
  28972. if( p==0 ) return SQLITE_NOMEM_BKPT;
  28973. memset(p, 0, sizeof(*p));
  28974. p->xTask = xTask;
  28975. p->pIn = pIn;
  28976. /* If the SQLITE_TESTCTRL_FAULT_INSTALL callback is registered to a
  28977. ** function that returns SQLITE_ERROR when passed the argument 200, that
  28978. ** forces worker threads to run sequentially and deterministically
  28979. ** for testing purposes. */
  28980. if( sqlite3FaultSim(200) ){
  28981. rc = 1;
  28982. }else{
  28983. rc = pthread_create(&p->tid, 0, xTask, pIn);
  28984. }
  28985. if( rc ){
  28986. p->done = 1;
  28987. p->pOut = xTask(pIn);
  28988. }
  28989. *ppThread = p;
  28990. return SQLITE_OK;
  28991. }
  28992. /* Get the results of the thread */
  28993. SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
  28994. int rc;
  28995. assert( ppOut!=0 );
  28996. if( NEVER(p==0) ) return SQLITE_NOMEM_BKPT;
  28997. if( p->done ){
  28998. *ppOut = p->pOut;
  28999. rc = SQLITE_OK;
  29000. }else{
  29001. rc = pthread_join(p->tid, ppOut) ? SQLITE_ERROR : SQLITE_OK;
  29002. }
  29003. sqlite3_free(p);
  29004. return rc;
  29005. }
  29006. #endif /* SQLITE_OS_UNIX && defined(SQLITE_MUTEX_PTHREADS) */
  29007. /******************************** End Unix Pthreads *************************/
  29008. /********************************* Win32 Threads ****************************/
  29009. #if SQLITE_OS_WIN_THREADS
  29010. #define SQLITE_THREADS_IMPLEMENTED 1 /* Prevent the single-thread code below */
  29011. #include <process.h>
  29012. /* A running thread */
  29013. struct SQLiteThread {
  29014. void *tid; /* The thread handle */
  29015. unsigned id; /* The thread identifier */
  29016. void *(*xTask)(void*); /* The routine to run as a thread */
  29017. void *pIn; /* Argument to xTask */
  29018. void *pResult; /* Result of xTask */
  29019. };
  29020. /* Thread procedure Win32 compatibility shim */
  29021. static unsigned __stdcall sqlite3ThreadProc(
  29022. void *pArg /* IN: Pointer to the SQLiteThread structure */
  29023. ){
  29024. SQLiteThread *p = (SQLiteThread *)pArg;
  29025. assert( p!=0 );
  29026. #if 0
  29027. /*
  29028. ** This assert appears to trigger spuriously on certain
  29029. ** versions of Windows, possibly due to _beginthreadex()
  29030. ** and/or CreateThread() not fully setting their thread
  29031. ** ID parameter before starting the thread.
  29032. */
  29033. assert( p->id==GetCurrentThreadId() );
  29034. #endif
  29035. assert( p->xTask!=0 );
  29036. p->pResult = p->xTask(p->pIn);
  29037. _endthreadex(0);
  29038. return 0; /* NOT REACHED */
  29039. }
  29040. /* Create a new thread */
  29041. SQLITE_PRIVATE int sqlite3ThreadCreate(
  29042. SQLiteThread **ppThread, /* OUT: Write the thread object here */
  29043. void *(*xTask)(void*), /* Routine to run in a separate thread */
  29044. void *pIn /* Argument passed into xTask() */
  29045. ){
  29046. SQLiteThread *p;
  29047. assert( ppThread!=0 );
  29048. assert( xTask!=0 );
  29049. *ppThread = 0;
  29050. p = sqlite3Malloc(sizeof(*p));
  29051. if( p==0 ) return SQLITE_NOMEM_BKPT;
  29052. /* If the SQLITE_TESTCTRL_FAULT_INSTALL callback is registered to a
  29053. ** function that returns SQLITE_ERROR when passed the argument 200, that
  29054. ** forces worker threads to run sequentially and deterministically
  29055. ** (via the sqlite3FaultSim() term of the conditional) for testing
  29056. ** purposes. */
  29057. if( sqlite3GlobalConfig.bCoreMutex==0 || sqlite3FaultSim(200) ){
  29058. memset(p, 0, sizeof(*p));
  29059. }else{
  29060. p->xTask = xTask;
  29061. p->pIn = pIn;
  29062. p->tid = (void*)_beginthreadex(0, 0, sqlite3ThreadProc, p, 0, &p->id);
  29063. if( p->tid==0 ){
  29064. memset(p, 0, sizeof(*p));
  29065. }
  29066. }
  29067. if( p->xTask==0 ){
  29068. p->id = GetCurrentThreadId();
  29069. p->pResult = xTask(pIn);
  29070. }
  29071. *ppThread = p;
  29072. return SQLITE_OK;
  29073. }
  29074. SQLITE_PRIVATE DWORD sqlite3Win32Wait(HANDLE hObject); /* os_win.c */
  29075. /* Get the results of the thread */
  29076. SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
  29077. DWORD rc;
  29078. BOOL bRc;
  29079. assert( ppOut!=0 );
  29080. if( NEVER(p==0) ) return SQLITE_NOMEM_BKPT;
  29081. if( p->xTask==0 ){
  29082. /* assert( p->id==GetCurrentThreadId() ); */
  29083. rc = WAIT_OBJECT_0;
  29084. assert( p->tid==0 );
  29085. }else{
  29086. assert( p->id!=0 && p->id!=GetCurrentThreadId() );
  29087. rc = sqlite3Win32Wait((HANDLE)p->tid);
  29088. assert( rc!=WAIT_IO_COMPLETION );
  29089. bRc = CloseHandle((HANDLE)p->tid);
  29090. assert( bRc );
  29091. }
  29092. if( rc==WAIT_OBJECT_0 ) *ppOut = p->pResult;
  29093. sqlite3_free(p);
  29094. return (rc==WAIT_OBJECT_0) ? SQLITE_OK : SQLITE_ERROR;
  29095. }
  29096. #endif /* SQLITE_OS_WIN_THREADS */
  29097. /******************************** End Win32 Threads *************************/
  29098. /********************************* Single-Threaded **************************/
  29099. #ifndef SQLITE_THREADS_IMPLEMENTED
  29100. /*
  29101. ** This implementation does not actually create a new thread. It does the
  29102. ** work of the thread in the main thread, when either the thread is created
  29103. ** or when it is joined
  29104. */
  29105. /* A running thread */
  29106. struct SQLiteThread {
  29107. void *(*xTask)(void*); /* The routine to run as a thread */
  29108. void *pIn; /* Argument to xTask */
  29109. void *pResult; /* Result of xTask */
  29110. };
  29111. /* Create a new thread */
  29112. SQLITE_PRIVATE int sqlite3ThreadCreate(
  29113. SQLiteThread **ppThread, /* OUT: Write the thread object here */
  29114. void *(*xTask)(void*), /* Routine to run in a separate thread */
  29115. void *pIn /* Argument passed into xTask() */
  29116. ){
  29117. SQLiteThread *p;
  29118. assert( ppThread!=0 );
  29119. assert( xTask!=0 );
  29120. *ppThread = 0;
  29121. p = sqlite3Malloc(sizeof(*p));
  29122. if( p==0 ) return SQLITE_NOMEM_BKPT;
  29123. if( (SQLITE_PTR_TO_INT(p)/17)&1 ){
  29124. p->xTask = xTask;
  29125. p->pIn = pIn;
  29126. }else{
  29127. p->xTask = 0;
  29128. p->pResult = xTask(pIn);
  29129. }
  29130. *ppThread = p;
  29131. return SQLITE_OK;
  29132. }
  29133. /* Get the results of the thread */
  29134. SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
  29135. assert( ppOut!=0 );
  29136. if( NEVER(p==0) ) return SQLITE_NOMEM_BKPT;
  29137. if( p->xTask ){
  29138. *ppOut = p->xTask(p->pIn);
  29139. }else{
  29140. *ppOut = p->pResult;
  29141. }
  29142. sqlite3_free(p);
  29143. #if defined(SQLITE_TEST)
  29144. {
  29145. void *pTstAlloc = sqlite3Malloc(10);
  29146. if (!pTstAlloc) return SQLITE_NOMEM_BKPT;
  29147. sqlite3_free(pTstAlloc);
  29148. }
  29149. #endif
  29150. return SQLITE_OK;
  29151. }
  29152. #endif /* !defined(SQLITE_THREADS_IMPLEMENTED) */
  29153. /****************************** End Single-Threaded *************************/
  29154. #endif /* SQLITE_MAX_WORKER_THREADS>0 */
  29155. /************** End of threads.c *********************************************/
  29156. /************** Begin file utf.c *********************************************/
  29157. /*
  29158. ** 2004 April 13
  29159. **
  29160. ** The author disclaims copyright to this source code. In place of
  29161. ** a legal notice, here is a blessing:
  29162. **
  29163. ** May you do good and not evil.
  29164. ** May you find forgiveness for yourself and forgive others.
  29165. ** May you share freely, never taking more than you give.
  29166. **
  29167. *************************************************************************
  29168. ** This file contains routines used to translate between UTF-8,
  29169. ** UTF-16, UTF-16BE, and UTF-16LE.
  29170. **
  29171. ** Notes on UTF-8:
  29172. **
  29173. ** Byte-0 Byte-1 Byte-2 Byte-3 Value
  29174. ** 0xxxxxxx 00000000 00000000 0xxxxxxx
  29175. ** 110yyyyy 10xxxxxx 00000000 00000yyy yyxxxxxx
  29176. ** 1110zzzz 10yyyyyy 10xxxxxx 00000000 zzzzyyyy yyxxxxxx
  29177. ** 11110uuu 10uuzzzz 10yyyyyy 10xxxxxx 000uuuuu zzzzyyyy yyxxxxxx
  29178. **
  29179. **
  29180. ** Notes on UTF-16: (with wwww+1==uuuuu)
  29181. **
  29182. ** Word-0 Word-1 Value
  29183. ** 110110ww wwzzzzyy 110111yy yyxxxxxx 000uuuuu zzzzyyyy yyxxxxxx
  29184. ** zzzzyyyy yyxxxxxx 00000000 zzzzyyyy yyxxxxxx
  29185. **
  29186. **
  29187. ** BOM or Byte Order Mark:
  29188. ** 0xff 0xfe little-endian utf-16 follows
  29189. ** 0xfe 0xff big-endian utf-16 follows
  29190. **
  29191. */
  29192. /* #include "sqliteInt.h" */
  29193. /* #include <assert.h> */
  29194. /* #include "vdbeInt.h" */
  29195. #if !defined(SQLITE_AMALGAMATION) && SQLITE_BYTEORDER==0
  29196. /*
  29197. ** The following constant value is used by the SQLITE_BIGENDIAN and
  29198. ** SQLITE_LITTLEENDIAN macros.
  29199. */
  29200. SQLITE_PRIVATE const int sqlite3one = 1;
  29201. #endif /* SQLITE_AMALGAMATION && SQLITE_BYTEORDER==0 */
  29202. /*
  29203. ** This lookup table is used to help decode the first byte of
  29204. ** a multi-byte UTF8 character.
  29205. */
  29206. static const unsigned char sqlite3Utf8Trans1[] = {
  29207. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  29208. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  29209. 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
  29210. 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
  29211. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  29212. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  29213. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  29214. 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
  29215. };
  29216. #define WRITE_UTF8(zOut, c) { \
  29217. if( c<0x00080 ){ \
  29218. *zOut++ = (u8)(c&0xFF); \
  29219. } \
  29220. else if( c<0x00800 ){ \
  29221. *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); \
  29222. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  29223. } \
  29224. else if( c<0x10000 ){ \
  29225. *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); \
  29226. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
  29227. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  29228. }else{ \
  29229. *zOut++ = 0xF0 + (u8)((c>>18) & 0x07); \
  29230. *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); \
  29231. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
  29232. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  29233. } \
  29234. }
  29235. #define WRITE_UTF16LE(zOut, c) { \
  29236. if( c<=0xFFFF ){ \
  29237. *zOut++ = (u8)(c&0x00FF); \
  29238. *zOut++ = (u8)((c>>8)&0x00FF); \
  29239. }else{ \
  29240. *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \
  29241. *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \
  29242. *zOut++ = (u8)(c&0x00FF); \
  29243. *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \
  29244. } \
  29245. }
  29246. #define WRITE_UTF16BE(zOut, c) { \
  29247. if( c<=0xFFFF ){ \
  29248. *zOut++ = (u8)((c>>8)&0x00FF); \
  29249. *zOut++ = (u8)(c&0x00FF); \
  29250. }else{ \
  29251. *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \
  29252. *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \
  29253. *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \
  29254. *zOut++ = (u8)(c&0x00FF); \
  29255. } \
  29256. }
  29257. /*
  29258. ** Translate a single UTF-8 character. Return the unicode value.
  29259. **
  29260. ** During translation, assume that the byte that zTerm points
  29261. ** is a 0x00.
  29262. **
  29263. ** Write a pointer to the next unread byte back into *pzNext.
  29264. **
  29265. ** Notes On Invalid UTF-8:
  29266. **
  29267. ** * This routine never allows a 7-bit character (0x00 through 0x7f) to
  29268. ** be encoded as a multi-byte character. Any multi-byte character that
  29269. ** attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
  29270. **
  29271. ** * This routine never allows a UTF16 surrogate value to be encoded.
  29272. ** If a multi-byte character attempts to encode a value between
  29273. ** 0xd800 and 0xe000 then it is rendered as 0xfffd.
  29274. **
  29275. ** * Bytes in the range of 0x80 through 0xbf which occur as the first
  29276. ** byte of a character are interpreted as single-byte characters
  29277. ** and rendered as themselves even though they are technically
  29278. ** invalid characters.
  29279. **
  29280. ** * This routine accepts over-length UTF8 encodings
  29281. ** for unicode values 0x80 and greater. It does not change over-length
  29282. ** encodings to 0xfffd as some systems recommend.
  29283. */
  29284. #define READ_UTF8(zIn, zTerm, c) \
  29285. c = *(zIn++); \
  29286. if( c>=0xc0 ){ \
  29287. c = sqlite3Utf8Trans1[c-0xc0]; \
  29288. while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \
  29289. c = (c<<6) + (0x3f & *(zIn++)); \
  29290. } \
  29291. if( c<0x80 \
  29292. || (c&0xFFFFF800)==0xD800 \
  29293. || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \
  29294. }
  29295. SQLITE_PRIVATE u32 sqlite3Utf8Read(
  29296. const unsigned char **pz /* Pointer to string from which to read char */
  29297. ){
  29298. unsigned int c;
  29299. /* Same as READ_UTF8() above but without the zTerm parameter.
  29300. ** For this routine, we assume the UTF8 string is always zero-terminated.
  29301. */
  29302. c = *((*pz)++);
  29303. if( c>=0xc0 ){
  29304. c = sqlite3Utf8Trans1[c-0xc0];
  29305. while( (*(*pz) & 0xc0)==0x80 ){
  29306. c = (c<<6) + (0x3f & *((*pz)++));
  29307. }
  29308. if( c<0x80
  29309. || (c&0xFFFFF800)==0xD800
  29310. || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; }
  29311. }
  29312. return c;
  29313. }
  29314. /*
  29315. ** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
  29316. ** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
  29317. */
  29318. /* #define TRANSLATE_TRACE 1 */
  29319. #ifndef SQLITE_OMIT_UTF16
  29320. /*
  29321. ** This routine transforms the internal text encoding used by pMem to
  29322. ** desiredEnc. It is an error if the string is already of the desired
  29323. ** encoding, or if *pMem does not contain a string value.
  29324. */
  29325. SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
  29326. sqlite3_int64 len; /* Maximum length of output string in bytes */
  29327. unsigned char *zOut; /* Output buffer */
  29328. unsigned char *zIn; /* Input iterator */
  29329. unsigned char *zTerm; /* End of input */
  29330. unsigned char *z; /* Output iterator */
  29331. unsigned int c;
  29332. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  29333. assert( pMem->flags&MEM_Str );
  29334. assert( pMem->enc!=desiredEnc );
  29335. assert( pMem->enc!=0 );
  29336. assert( pMem->n>=0 );
  29337. #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
  29338. {
  29339. StrAccum acc;
  29340. char zBuf[1000];
  29341. sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
  29342. sqlite3VdbeMemPrettyPrint(pMem, &acc);
  29343. fprintf(stderr, "INPUT: %s\n", sqlite3StrAccumFinish(&acc));
  29344. }
  29345. #endif
  29346. /* If the translation is between UTF-16 little and big endian, then
  29347. ** all that is required is to swap the byte order. This case is handled
  29348. ** differently from the others.
  29349. */
  29350. if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
  29351. u8 temp;
  29352. int rc;
  29353. rc = sqlite3VdbeMemMakeWriteable(pMem);
  29354. if( rc!=SQLITE_OK ){
  29355. assert( rc==SQLITE_NOMEM );
  29356. return SQLITE_NOMEM_BKPT;
  29357. }
  29358. zIn = (u8*)pMem->z;
  29359. zTerm = &zIn[pMem->n&~1];
  29360. while( zIn<zTerm ){
  29361. temp = *zIn;
  29362. *zIn = *(zIn+1);
  29363. zIn++;
  29364. *zIn++ = temp;
  29365. }
  29366. pMem->enc = desiredEnc;
  29367. goto translate_out;
  29368. }
  29369. /* Set len to the maximum number of bytes required in the output buffer. */
  29370. if( desiredEnc==SQLITE_UTF8 ){
  29371. /* When converting from UTF-16, the maximum growth results from
  29372. ** translating a 2-byte character to a 4-byte UTF-8 character.
  29373. ** A single byte is required for the output string
  29374. ** nul-terminator.
  29375. */
  29376. pMem->n &= ~1;
  29377. len = 2 * (sqlite3_int64)pMem->n + 1;
  29378. }else{
  29379. /* When converting from UTF-8 to UTF-16 the maximum growth is caused
  29380. ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
  29381. ** character. Two bytes are required in the output buffer for the
  29382. ** nul-terminator.
  29383. */
  29384. len = 2 * (sqlite3_int64)pMem->n + 2;
  29385. }
  29386. /* Set zIn to point at the start of the input buffer and zTerm to point 1
  29387. ** byte past the end.
  29388. **
  29389. ** Variable zOut is set to point at the output buffer, space obtained
  29390. ** from sqlite3_malloc().
  29391. */
  29392. zIn = (u8*)pMem->z;
  29393. zTerm = &zIn[pMem->n];
  29394. zOut = sqlite3DbMallocRaw(pMem->db, len);
  29395. if( !zOut ){
  29396. return SQLITE_NOMEM_BKPT;
  29397. }
  29398. z = zOut;
  29399. if( pMem->enc==SQLITE_UTF8 ){
  29400. if( desiredEnc==SQLITE_UTF16LE ){
  29401. /* UTF-8 -> UTF-16 Little-endian */
  29402. while( zIn<zTerm ){
  29403. READ_UTF8(zIn, zTerm, c);
  29404. WRITE_UTF16LE(z, c);
  29405. }
  29406. }else{
  29407. assert( desiredEnc==SQLITE_UTF16BE );
  29408. /* UTF-8 -> UTF-16 Big-endian */
  29409. while( zIn<zTerm ){
  29410. READ_UTF8(zIn, zTerm, c);
  29411. WRITE_UTF16BE(z, c);
  29412. }
  29413. }
  29414. pMem->n = (int)(z - zOut);
  29415. *z++ = 0;
  29416. }else{
  29417. assert( desiredEnc==SQLITE_UTF8 );
  29418. if( pMem->enc==SQLITE_UTF16LE ){
  29419. /* UTF-16 Little-endian -> UTF-8 */
  29420. while( zIn<zTerm ){
  29421. c = *(zIn++);
  29422. c += (*(zIn++))<<8;
  29423. if( c>=0xd800 && c<0xe000 ){
  29424. #ifdef SQLITE_REPLACE_INVALID_UTF
  29425. if( c>=0xdc00 || zIn>=zTerm ){
  29426. c = 0xfffd;
  29427. }else{
  29428. int c2 = *(zIn++);
  29429. c2 += (*(zIn++))<<8;
  29430. if( c2<0xdc00 || c2>=0xe000 ){
  29431. zIn -= 2;
  29432. c = 0xfffd;
  29433. }else{
  29434. c = ((c&0x3ff)<<10) + (c2&0x3ff) + 0x10000;
  29435. }
  29436. }
  29437. #else
  29438. if( zIn<zTerm ){
  29439. int c2 = (*zIn++);
  29440. c2 += ((*zIn++)<<8);
  29441. c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);
  29442. }
  29443. #endif
  29444. }
  29445. WRITE_UTF8(z, c);
  29446. }
  29447. }else{
  29448. /* UTF-16 Big-endian -> UTF-8 */
  29449. while( zIn<zTerm ){
  29450. c = (*(zIn++))<<8;
  29451. c += *(zIn++);
  29452. if( c>=0xd800 && c<0xe000 ){
  29453. #ifdef SQLITE_REPLACE_INVALID_UTF
  29454. if( c>=0xdc00 || zIn>=zTerm ){
  29455. c = 0xfffd;
  29456. }else{
  29457. int c2 = (*(zIn++))<<8;
  29458. c2 += *(zIn++);
  29459. if( c2<0xdc00 || c2>=0xe000 ){
  29460. zIn -= 2;
  29461. c = 0xfffd;
  29462. }else{
  29463. c = ((c&0x3ff)<<10) + (c2&0x3ff) + 0x10000;
  29464. }
  29465. }
  29466. #else
  29467. if( zIn<zTerm ){
  29468. int c2 = ((*zIn++)<<8);
  29469. c2 += (*zIn++);
  29470. c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);
  29471. }
  29472. #endif
  29473. }
  29474. WRITE_UTF8(z, c);
  29475. }
  29476. }
  29477. pMem->n = (int)(z - zOut);
  29478. }
  29479. *z = 0;
  29480. assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
  29481. c = pMem->flags;
  29482. sqlite3VdbeMemRelease(pMem);
  29483. pMem->flags = MEM_Str|MEM_Term|(c&(MEM_AffMask|MEM_Subtype));
  29484. pMem->enc = desiredEnc;
  29485. pMem->z = (char*)zOut;
  29486. pMem->zMalloc = pMem->z;
  29487. pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->z);
  29488. translate_out:
  29489. #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
  29490. {
  29491. StrAccum acc;
  29492. char zBuf[1000];
  29493. sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
  29494. sqlite3VdbeMemPrettyPrint(pMem, &acc);
  29495. fprintf(stderr, "OUTPUT: %s\n", sqlite3StrAccumFinish(&acc));
  29496. }
  29497. #endif
  29498. return SQLITE_OK;
  29499. }
  29500. #endif /* SQLITE_OMIT_UTF16 */
  29501. #ifndef SQLITE_OMIT_UTF16
  29502. /*
  29503. ** This routine checks for a byte-order mark at the beginning of the
  29504. ** UTF-16 string stored in *pMem. If one is present, it is removed and
  29505. ** the encoding of the Mem adjusted. This routine does not do any
  29506. ** byte-swapping, it just sets Mem.enc appropriately.
  29507. **
  29508. ** The allocation (static, dynamic etc.) and encoding of the Mem may be
  29509. ** changed by this function.
  29510. */
  29511. SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){
  29512. int rc = SQLITE_OK;
  29513. u8 bom = 0;
  29514. assert( pMem->n>=0 );
  29515. if( pMem->n>1 ){
  29516. u8 b1 = *(u8 *)pMem->z;
  29517. u8 b2 = *(((u8 *)pMem->z) + 1);
  29518. if( b1==0xFE && b2==0xFF ){
  29519. bom = SQLITE_UTF16BE;
  29520. }
  29521. if( b1==0xFF && b2==0xFE ){
  29522. bom = SQLITE_UTF16LE;
  29523. }
  29524. }
  29525. if( bom ){
  29526. rc = sqlite3VdbeMemMakeWriteable(pMem);
  29527. if( rc==SQLITE_OK ){
  29528. pMem->n -= 2;
  29529. memmove(pMem->z, &pMem->z[2], pMem->n);
  29530. pMem->z[pMem->n] = '\0';
  29531. pMem->z[pMem->n+1] = '\0';
  29532. pMem->flags |= MEM_Term;
  29533. pMem->enc = bom;
  29534. }
  29535. }
  29536. return rc;
  29537. }
  29538. #endif /* SQLITE_OMIT_UTF16 */
  29539. /*
  29540. ** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
  29541. ** return the number of unicode characters in pZ up to (but not including)
  29542. ** the first 0x00 byte. If nByte is not less than zero, return the
  29543. ** number of unicode characters in the first nByte of pZ (or up to
  29544. ** the first 0x00, whichever comes first).
  29545. */
  29546. SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){
  29547. int r = 0;
  29548. const u8 *z = (const u8*)zIn;
  29549. const u8 *zTerm;
  29550. if( nByte>=0 ){
  29551. zTerm = &z[nByte];
  29552. }else{
  29553. zTerm = (const u8*)(-1);
  29554. }
  29555. assert( z<=zTerm );
  29556. while( *z!=0 && z<zTerm ){
  29557. SQLITE_SKIP_UTF8(z);
  29558. r++;
  29559. }
  29560. return r;
  29561. }
  29562. /* This test function is not currently used by the automated test-suite.
  29563. ** Hence it is only available in debug builds.
  29564. */
  29565. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  29566. /*
  29567. ** Translate UTF-8 to UTF-8.
  29568. **
  29569. ** This has the effect of making sure that the string is well-formed
  29570. ** UTF-8. Miscoded characters are removed.
  29571. **
  29572. ** The translation is done in-place and aborted if the output
  29573. ** overruns the input.
  29574. */
  29575. SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){
  29576. unsigned char *zOut = zIn;
  29577. unsigned char *zStart = zIn;
  29578. u32 c;
  29579. while( zIn[0] && zOut<=zIn ){
  29580. c = sqlite3Utf8Read((const u8**)&zIn);
  29581. if( c!=0xfffd ){
  29582. WRITE_UTF8(zOut, c);
  29583. }
  29584. }
  29585. *zOut = 0;
  29586. return (int)(zOut - zStart);
  29587. }
  29588. #endif
  29589. #ifndef SQLITE_OMIT_UTF16
  29590. /*
  29591. ** Convert a UTF-16 string in the native encoding into a UTF-8 string.
  29592. ** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
  29593. ** be freed by the calling function.
  29594. **
  29595. ** NULL is returned if there is an allocation error.
  29596. */
  29597. SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte, u8 enc){
  29598. Mem m;
  29599. memset(&m, 0, sizeof(m));
  29600. m.db = db;
  29601. sqlite3VdbeMemSetStr(&m, z, nByte, enc, SQLITE_STATIC);
  29602. sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
  29603. if( db->mallocFailed ){
  29604. sqlite3VdbeMemRelease(&m);
  29605. m.z = 0;
  29606. }
  29607. assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
  29608. assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
  29609. assert( m.z || db->mallocFailed );
  29610. return m.z;
  29611. }
  29612. /*
  29613. ** zIn is a UTF-16 encoded unicode string at least nChar characters long.
  29614. ** Return the number of bytes in the first nChar unicode characters
  29615. ** in pZ. nChar must be non-negative.
  29616. */
  29617. SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){
  29618. int c;
  29619. unsigned char const *z = zIn;
  29620. int n = 0;
  29621. if( SQLITE_UTF16NATIVE==SQLITE_UTF16LE ) z++;
  29622. while( n<nChar ){
  29623. c = z[0];
  29624. z += 2;
  29625. if( c>=0xd8 && c<0xdc && z[0]>=0xdc && z[0]<0xe0 ) z += 2;
  29626. n++;
  29627. }
  29628. return (int)(z-(unsigned char const *)zIn)
  29629. - (SQLITE_UTF16NATIVE==SQLITE_UTF16LE);
  29630. }
  29631. #if defined(SQLITE_TEST)
  29632. /*
  29633. ** This routine is called from the TCL test function "translate_selftest".
  29634. ** It checks that the primitives for serializing and deserializing
  29635. ** characters in each encoding are inverses of each other.
  29636. */
  29637. SQLITE_PRIVATE void sqlite3UtfSelfTest(void){
  29638. unsigned int i, t;
  29639. unsigned char zBuf[20];
  29640. unsigned char *z;
  29641. int n;
  29642. unsigned int c;
  29643. for(i=0; i<0x00110000; i++){
  29644. z = zBuf;
  29645. WRITE_UTF8(z, i);
  29646. n = (int)(z-zBuf);
  29647. assert( n>0 && n<=4 );
  29648. z[0] = 0;
  29649. z = zBuf;
  29650. c = sqlite3Utf8Read((const u8**)&z);
  29651. t = i;
  29652. if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
  29653. if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
  29654. assert( c==t );
  29655. assert( (z-zBuf)==n );
  29656. }
  29657. }
  29658. #endif /* SQLITE_TEST */
  29659. #endif /* SQLITE_OMIT_UTF16 */
  29660. /************** End of utf.c *************************************************/
  29661. /************** Begin file util.c ********************************************/
  29662. /*
  29663. ** 2001 September 15
  29664. **
  29665. ** The author disclaims copyright to this source code. In place of
  29666. ** a legal notice, here is a blessing:
  29667. **
  29668. ** May you do good and not evil.
  29669. ** May you find forgiveness for yourself and forgive others.
  29670. ** May you share freely, never taking more than you give.
  29671. **
  29672. *************************************************************************
  29673. ** Utility functions used throughout sqlite.
  29674. **
  29675. ** This file contains functions for allocating memory, comparing
  29676. ** strings, and stuff like that.
  29677. **
  29678. */
  29679. /* #include "sqliteInt.h" */
  29680. /* #include <stdarg.h> */
  29681. #ifndef SQLITE_OMIT_FLOATING_POINT
  29682. #include <math.h>
  29683. #endif
  29684. /*
  29685. ** Routine needed to support the testcase() macro.
  29686. */
  29687. #ifdef SQLITE_COVERAGE_TEST
  29688. SQLITE_PRIVATE void sqlite3Coverage(int x){
  29689. static unsigned dummy = 0;
  29690. dummy += (unsigned)x;
  29691. }
  29692. #endif
  29693. /*
  29694. ** Calls to sqlite3FaultSim() are used to simulate a failure during testing,
  29695. ** or to bypass normal error detection during testing in order to let
  29696. ** execute proceed futher downstream.
  29697. **
  29698. ** In deployment, sqlite3FaultSim() *always* return SQLITE_OK (0). The
  29699. ** sqlite3FaultSim() function only returns non-zero during testing.
  29700. **
  29701. ** During testing, if the test harness has set a fault-sim callback using
  29702. ** a call to sqlite3_test_control(SQLITE_TESTCTRL_FAULT_INSTALL), then
  29703. ** each call to sqlite3FaultSim() is relayed to that application-supplied
  29704. ** callback and the integer return value form the application-supplied
  29705. ** callback is returned by sqlite3FaultSim().
  29706. **
  29707. ** The integer argument to sqlite3FaultSim() is a code to identify which
  29708. ** sqlite3FaultSim() instance is being invoked. Each call to sqlite3FaultSim()
  29709. ** should have a unique code. To prevent legacy testing applications from
  29710. ** breaking, the codes should not be changed or reused.
  29711. */
  29712. #ifndef SQLITE_UNTESTABLE
  29713. SQLITE_PRIVATE int sqlite3FaultSim(int iTest){
  29714. int (*xCallback)(int) = sqlite3GlobalConfig.xTestCallback;
  29715. return xCallback ? xCallback(iTest) : SQLITE_OK;
  29716. }
  29717. #endif
  29718. #ifndef SQLITE_OMIT_FLOATING_POINT
  29719. /*
  29720. ** Return true if the floating point value is Not a Number (NaN).
  29721. */
  29722. SQLITE_PRIVATE int sqlite3IsNaN(double x){
  29723. u64 y;
  29724. memcpy(&y,&x,sizeof(y));
  29725. return IsNaN(y);
  29726. }
  29727. #endif /* SQLITE_OMIT_FLOATING_POINT */
  29728. /*
  29729. ** Compute a string length that is limited to what can be stored in
  29730. ** lower 30 bits of a 32-bit signed integer.
  29731. **
  29732. ** The value returned will never be negative. Nor will it ever be greater
  29733. ** than the actual length of the string. For very long strings (greater
  29734. ** than 1GiB) the value returned might be less than the true string length.
  29735. */
  29736. SQLITE_PRIVATE int sqlite3Strlen30(const char *z){
  29737. if( z==0 ) return 0;
  29738. return 0x3fffffff & (int)strlen(z);
  29739. }
  29740. /*
  29741. ** Return the declared type of a column. Or return zDflt if the column
  29742. ** has no declared type.
  29743. **
  29744. ** The column type is an extra string stored after the zero-terminator on
  29745. ** the column name if and only if the COLFLAG_HASTYPE flag is set.
  29746. */
  29747. SQLITE_PRIVATE char *sqlite3ColumnType(Column *pCol, char *zDflt){
  29748. if( (pCol->colFlags & COLFLAG_HASTYPE)==0 ) return zDflt;
  29749. return pCol->zName + strlen(pCol->zName) + 1;
  29750. }
  29751. /*
  29752. ** Helper function for sqlite3Error() - called rarely. Broken out into
  29753. ** a separate routine to avoid unnecessary register saves on entry to
  29754. ** sqlite3Error().
  29755. */
  29756. static SQLITE_NOINLINE void sqlite3ErrorFinish(sqlite3 *db, int err_code){
  29757. if( db->pErr ) sqlite3ValueSetNull(db->pErr);
  29758. sqlite3SystemError(db, err_code);
  29759. }
  29760. /*
  29761. ** Set the current error code to err_code and clear any prior error message.
  29762. ** Also set iSysErrno (by calling sqlite3System) if the err_code indicates
  29763. ** that would be appropriate.
  29764. */
  29765. SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code){
  29766. assert( db!=0 );
  29767. db->errCode = err_code;
  29768. if( err_code || db->pErr ) sqlite3ErrorFinish(db, err_code);
  29769. }
  29770. /*
  29771. ** Load the sqlite3.iSysErrno field if that is an appropriate thing
  29772. ** to do based on the SQLite error code in rc.
  29773. */
  29774. SQLITE_PRIVATE void sqlite3SystemError(sqlite3 *db, int rc){
  29775. if( rc==SQLITE_IOERR_NOMEM ) return;
  29776. rc &= 0xff;
  29777. if( rc==SQLITE_CANTOPEN || rc==SQLITE_IOERR ){
  29778. db->iSysErrno = sqlite3OsGetLastError(db->pVfs);
  29779. }
  29780. }
  29781. /*
  29782. ** Set the most recent error code and error string for the sqlite
  29783. ** handle "db". The error code is set to "err_code".
  29784. **
  29785. ** If it is not NULL, string zFormat specifies the format of the
  29786. ** error string in the style of the printf functions: The following
  29787. ** format characters are allowed:
  29788. **
  29789. ** %s Insert a string
  29790. ** %z A string that should be freed after use
  29791. ** %d Insert an integer
  29792. ** %T Insert a token
  29793. ** %S Insert the first element of a SrcList
  29794. **
  29795. ** zFormat and any string tokens that follow it are assumed to be
  29796. ** encoded in UTF-8.
  29797. **
  29798. ** To clear the most recent error for sqlite handle "db", sqlite3Error
  29799. ** should be called with err_code set to SQLITE_OK and zFormat set
  29800. ** to NULL.
  29801. */
  29802. SQLITE_PRIVATE void sqlite3ErrorWithMsg(sqlite3 *db, int err_code, const char *zFormat, ...){
  29803. assert( db!=0 );
  29804. db->errCode = err_code;
  29805. sqlite3SystemError(db, err_code);
  29806. if( zFormat==0 ){
  29807. sqlite3Error(db, err_code);
  29808. }else if( db->pErr || (db->pErr = sqlite3ValueNew(db))!=0 ){
  29809. char *z;
  29810. va_list ap;
  29811. va_start(ap, zFormat);
  29812. z = sqlite3VMPrintf(db, zFormat, ap);
  29813. va_end(ap);
  29814. sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
  29815. }
  29816. }
  29817. /*
  29818. ** Add an error message to pParse->zErrMsg and increment pParse->nErr.
  29819. ** The following formatting characters are allowed:
  29820. **
  29821. ** %s Insert a string
  29822. ** %z A string that should be freed after use
  29823. ** %d Insert an integer
  29824. ** %T Insert a token
  29825. ** %S Insert the first element of a SrcList
  29826. **
  29827. ** This function should be used to report any error that occurs while
  29828. ** compiling an SQL statement (i.e. within sqlite3_prepare()). The
  29829. ** last thing the sqlite3_prepare() function does is copy the error
  29830. ** stored by this function into the database handle using sqlite3Error().
  29831. ** Functions sqlite3Error() or sqlite3ErrorWithMsg() should be used
  29832. ** during statement execution (sqlite3_step() etc.).
  29833. */
  29834. SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
  29835. char *zMsg;
  29836. va_list ap;
  29837. sqlite3 *db = pParse->db;
  29838. va_start(ap, zFormat);
  29839. zMsg = sqlite3VMPrintf(db, zFormat, ap);
  29840. va_end(ap);
  29841. if( db->suppressErr ){
  29842. sqlite3DbFree(db, zMsg);
  29843. }else{
  29844. pParse->nErr++;
  29845. sqlite3DbFree(db, pParse->zErrMsg);
  29846. pParse->zErrMsg = zMsg;
  29847. pParse->rc = SQLITE_ERROR;
  29848. pParse->pWith = 0;
  29849. }
  29850. }
  29851. /*
  29852. ** If database connection db is currently parsing SQL, then transfer
  29853. ** error code errCode to that parser if the parser has not already
  29854. ** encountered some other kind of error.
  29855. */
  29856. SQLITE_PRIVATE int sqlite3ErrorToParser(sqlite3 *db, int errCode){
  29857. Parse *pParse;
  29858. if( db==0 || (pParse = db->pParse)==0 ) return errCode;
  29859. pParse->rc = errCode;
  29860. pParse->nErr++;
  29861. return errCode;
  29862. }
  29863. /*
  29864. ** Convert an SQL-style quoted string into a normal string by removing
  29865. ** the quote characters. The conversion is done in-place. If the
  29866. ** input does not begin with a quote character, then this routine
  29867. ** is a no-op.
  29868. **
  29869. ** The input string must be zero-terminated. A new zero-terminator
  29870. ** is added to the dequoted string.
  29871. **
  29872. ** The return value is -1 if no dequoting occurs or the length of the
  29873. ** dequoted string, exclusive of the zero terminator, if dequoting does
  29874. ** occur.
  29875. **
  29876. ** 2002-02-14: This routine is extended to remove MS-Access style
  29877. ** brackets from around identifiers. For example: "[a-b-c]" becomes
  29878. ** "a-b-c".
  29879. */
  29880. SQLITE_PRIVATE void sqlite3Dequote(char *z){
  29881. char quote;
  29882. int i, j;
  29883. if( z==0 ) return;
  29884. quote = z[0];
  29885. if( !sqlite3Isquote(quote) ) return;
  29886. if( quote=='[' ) quote = ']';
  29887. for(i=1, j=0;; i++){
  29888. assert( z[i] );
  29889. if( z[i]==quote ){
  29890. if( z[i+1]==quote ){
  29891. z[j++] = quote;
  29892. i++;
  29893. }else{
  29894. break;
  29895. }
  29896. }else{
  29897. z[j++] = z[i];
  29898. }
  29899. }
  29900. z[j] = 0;
  29901. }
  29902. SQLITE_PRIVATE void sqlite3DequoteExpr(Expr *p){
  29903. assert( sqlite3Isquote(p->u.zToken[0]) );
  29904. p->flags |= p->u.zToken[0]=='"' ? EP_Quoted|EP_DblQuoted : EP_Quoted;
  29905. sqlite3Dequote(p->u.zToken);
  29906. }
  29907. /*
  29908. ** Generate a Token object from a string
  29909. */
  29910. SQLITE_PRIVATE void sqlite3TokenInit(Token *p, char *z){
  29911. p->z = z;
  29912. p->n = sqlite3Strlen30(z);
  29913. }
  29914. /* Convenient short-hand */
  29915. #define UpperToLower sqlite3UpperToLower
  29916. /*
  29917. ** Some systems have stricmp(). Others have strcasecmp(). Because
  29918. ** there is no consistency, we will define our own.
  29919. **
  29920. ** IMPLEMENTATION-OF: R-30243-02494 The sqlite3_stricmp() and
  29921. ** sqlite3_strnicmp() APIs allow applications and extensions to compare
  29922. ** the contents of two buffers containing UTF-8 strings in a
  29923. ** case-independent fashion, using the same definition of "case
  29924. ** independence" that SQLite uses internally when comparing identifiers.
  29925. */
  29926. SQLITE_API int sqlite3_stricmp(const char *zLeft, const char *zRight){
  29927. if( zLeft==0 ){
  29928. return zRight ? -1 : 0;
  29929. }else if( zRight==0 ){
  29930. return 1;
  29931. }
  29932. return sqlite3StrICmp(zLeft, zRight);
  29933. }
  29934. SQLITE_PRIVATE int sqlite3StrICmp(const char *zLeft, const char *zRight){
  29935. unsigned char *a, *b;
  29936. int c, x;
  29937. a = (unsigned char *)zLeft;
  29938. b = (unsigned char *)zRight;
  29939. for(;;){
  29940. c = *a;
  29941. x = *b;
  29942. if( c==x ){
  29943. if( c==0 ) break;
  29944. }else{
  29945. c = (int)UpperToLower[c] - (int)UpperToLower[x];
  29946. if( c ) break;
  29947. }
  29948. a++;
  29949. b++;
  29950. }
  29951. return c;
  29952. }
  29953. SQLITE_API int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
  29954. register unsigned char *a, *b;
  29955. if( zLeft==0 ){
  29956. return zRight ? -1 : 0;
  29957. }else if( zRight==0 ){
  29958. return 1;
  29959. }
  29960. a = (unsigned char *)zLeft;
  29961. b = (unsigned char *)zRight;
  29962. while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
  29963. return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
  29964. }
  29965. /*
  29966. ** Compute an 8-bit hash on a string that is insensitive to case differences
  29967. */
  29968. SQLITE_PRIVATE u8 sqlite3StrIHash(const char *z){
  29969. u8 h = 0;
  29970. if( z==0 ) return 0;
  29971. while( z[0] ){
  29972. h += UpperToLower[(unsigned char)z[0]];
  29973. z++;
  29974. }
  29975. return h;
  29976. }
  29977. /*
  29978. ** Compute 10 to the E-th power. Examples: E==1 results in 10.
  29979. ** E==2 results in 100. E==50 results in 1.0e50.
  29980. **
  29981. ** This routine only works for values of E between 1 and 341.
  29982. */
  29983. static LONGDOUBLE_TYPE sqlite3Pow10(int E){
  29984. #if defined(_MSC_VER)
  29985. static const LONGDOUBLE_TYPE x[] = {
  29986. 1.0e+001L,
  29987. 1.0e+002L,
  29988. 1.0e+004L,
  29989. 1.0e+008L,
  29990. 1.0e+016L,
  29991. 1.0e+032L,
  29992. 1.0e+064L,
  29993. 1.0e+128L,
  29994. 1.0e+256L
  29995. };
  29996. LONGDOUBLE_TYPE r = 1.0;
  29997. int i;
  29998. assert( E>=0 && E<=307 );
  29999. for(i=0; E!=0; i++, E >>=1){
  30000. if( E & 1 ) r *= x[i];
  30001. }
  30002. return r;
  30003. #else
  30004. LONGDOUBLE_TYPE x = 10.0;
  30005. LONGDOUBLE_TYPE r = 1.0;
  30006. while(1){
  30007. if( E & 1 ) r *= x;
  30008. E >>= 1;
  30009. if( E==0 ) break;
  30010. x *= x;
  30011. }
  30012. return r;
  30013. #endif
  30014. }
  30015. /*
  30016. ** The string z[] is an text representation of a real number.
  30017. ** Convert this string to a double and write it into *pResult.
  30018. **
  30019. ** The string z[] is length bytes in length (bytes, not characters) and
  30020. ** uses the encoding enc. The string is not necessarily zero-terminated.
  30021. **
  30022. ** Return TRUE if the result is a valid real number (or integer) and FALSE
  30023. ** if the string is empty or contains extraneous text. More specifically
  30024. ** return
  30025. ** 1 => The input string is a pure integer
  30026. ** 2 or more => The input has a decimal point or eNNN clause
  30027. ** 0 or less => The input string is not a valid number
  30028. ** -1 => Not a valid number, but has a valid prefix which
  30029. ** includes a decimal point and/or an eNNN clause
  30030. **
  30031. ** Valid numbers are in one of these formats:
  30032. **
  30033. ** [+-]digits[E[+-]digits]
  30034. ** [+-]digits.[digits][E[+-]digits]
  30035. ** [+-].digits[E[+-]digits]
  30036. **
  30037. ** Leading and trailing whitespace is ignored for the purpose of determining
  30038. ** validity.
  30039. **
  30040. ** If some prefix of the input string is a valid number, this routine
  30041. ** returns FALSE but it still converts the prefix and writes the result
  30042. ** into *pResult.
  30043. */
  30044. #if defined(_MSC_VER)
  30045. #pragma warning(disable : 4756)
  30046. #endif
  30047. SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){
  30048. #ifndef SQLITE_OMIT_FLOATING_POINT
  30049. int incr;
  30050. const char *zEnd;
  30051. /* sign * significand * (10 ^ (esign * exponent)) */
  30052. int sign = 1; /* sign of significand */
  30053. i64 s = 0; /* significand */
  30054. int d = 0; /* adjust exponent for shifting decimal point */
  30055. int esign = 1; /* sign of exponent */
  30056. int e = 0; /* exponent */
  30057. int eValid = 1; /* True exponent is either not used or is well-formed */
  30058. double result;
  30059. int nDigit = 0; /* Number of digits processed */
  30060. int eType = 1; /* 1: pure integer, 2+: fractional -1 or less: bad UTF16 */
  30061. assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
  30062. *pResult = 0.0; /* Default return value, in case of an error */
  30063. if( length==0 ) return 0;
  30064. if( enc==SQLITE_UTF8 ){
  30065. incr = 1;
  30066. zEnd = z + length;
  30067. }else{
  30068. int i;
  30069. incr = 2;
  30070. length &= ~1;
  30071. assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
  30072. testcase( enc==SQLITE_UTF16LE );
  30073. testcase( enc==SQLITE_UTF16BE );
  30074. for(i=3-enc; i<length && z[i]==0; i+=2){}
  30075. if( i<length ) eType = -100;
  30076. zEnd = &z[i^1];
  30077. z += (enc&1);
  30078. }
  30079. /* skip leading spaces */
  30080. while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
  30081. if( z>=zEnd ) return 0;
  30082. /* get sign of significand */
  30083. if( *z=='-' ){
  30084. sign = -1;
  30085. z+=incr;
  30086. }else if( *z=='+' ){
  30087. z+=incr;
  30088. }
  30089. /* copy max significant digits to significand */
  30090. while( z<zEnd && sqlite3Isdigit(*z) ){
  30091. s = s*10 + (*z - '0');
  30092. z+=incr; nDigit++;
  30093. if( s>=((LARGEST_INT64-9)/10) ){
  30094. /* skip non-significant significand digits
  30095. ** (increase exponent by d to shift decimal left) */
  30096. while( z<zEnd && sqlite3Isdigit(*z) ){ z+=incr; d++; }
  30097. }
  30098. }
  30099. if( z>=zEnd ) goto do_atof_calc;
  30100. /* if decimal point is present */
  30101. if( *z=='.' ){
  30102. z+=incr;
  30103. eType++;
  30104. /* copy digits from after decimal to significand
  30105. ** (decrease exponent by d to shift decimal right) */
  30106. while( z<zEnd && sqlite3Isdigit(*z) ){
  30107. if( s<((LARGEST_INT64-9)/10) ){
  30108. s = s*10 + (*z - '0');
  30109. d--;
  30110. nDigit++;
  30111. }
  30112. z+=incr;
  30113. }
  30114. }
  30115. if( z>=zEnd ) goto do_atof_calc;
  30116. /* if exponent is present */
  30117. if( *z=='e' || *z=='E' ){
  30118. z+=incr;
  30119. eValid = 0;
  30120. eType++;
  30121. /* This branch is needed to avoid a (harmless) buffer overread. The
  30122. ** special comment alerts the mutation tester that the correct answer
  30123. ** is obtained even if the branch is omitted */
  30124. if( z>=zEnd ) goto do_atof_calc; /*PREVENTS-HARMLESS-OVERREAD*/
  30125. /* get sign of exponent */
  30126. if( *z=='-' ){
  30127. esign = -1;
  30128. z+=incr;
  30129. }else if( *z=='+' ){
  30130. z+=incr;
  30131. }
  30132. /* copy digits to exponent */
  30133. while( z<zEnd && sqlite3Isdigit(*z) ){
  30134. e = e<10000 ? (e*10 + (*z - '0')) : 10000;
  30135. z+=incr;
  30136. eValid = 1;
  30137. }
  30138. }
  30139. /* skip trailing spaces */
  30140. while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
  30141. do_atof_calc:
  30142. /* adjust exponent by d, and update sign */
  30143. e = (e*esign) + d;
  30144. if( e<0 ) {
  30145. esign = -1;
  30146. e *= -1;
  30147. } else {
  30148. esign = 1;
  30149. }
  30150. if( s==0 ) {
  30151. /* In the IEEE 754 standard, zero is signed. */
  30152. result = sign<0 ? -(double)0 : (double)0;
  30153. } else {
  30154. /* Attempt to reduce exponent.
  30155. **
  30156. ** Branches that are not required for the correct answer but which only
  30157. ** help to obtain the correct answer faster are marked with special
  30158. ** comments, as a hint to the mutation tester.
  30159. */
  30160. while( e>0 ){ /*OPTIMIZATION-IF-TRUE*/
  30161. if( esign>0 ){
  30162. if( s>=(LARGEST_INT64/10) ) break; /*OPTIMIZATION-IF-FALSE*/
  30163. s *= 10;
  30164. }else{
  30165. if( s%10!=0 ) break; /*OPTIMIZATION-IF-FALSE*/
  30166. s /= 10;
  30167. }
  30168. e--;
  30169. }
  30170. /* adjust the sign of significand */
  30171. s = sign<0 ? -s : s;
  30172. if( e==0 ){ /*OPTIMIZATION-IF-TRUE*/
  30173. result = (double)s;
  30174. }else{
  30175. /* attempt to handle extremely small/large numbers better */
  30176. if( e>307 ){ /*OPTIMIZATION-IF-TRUE*/
  30177. if( e<342 ){ /*OPTIMIZATION-IF-TRUE*/
  30178. LONGDOUBLE_TYPE scale = sqlite3Pow10(e-308);
  30179. if( esign<0 ){
  30180. result = s / scale;
  30181. result /= 1.0e+308;
  30182. }else{
  30183. result = s * scale;
  30184. result *= 1.0e+308;
  30185. }
  30186. }else{ assert( e>=342 );
  30187. if( esign<0 ){
  30188. result = 0.0*s;
  30189. }else{
  30190. #ifdef INFINITY
  30191. result = INFINITY*s;
  30192. #else
  30193. result = 1e308*1e308*s; /* Infinity */
  30194. #endif
  30195. }
  30196. }
  30197. }else{
  30198. LONGDOUBLE_TYPE scale = sqlite3Pow10(e);
  30199. if( esign<0 ){
  30200. result = s / scale;
  30201. }else{
  30202. result = s * scale;
  30203. }
  30204. }
  30205. }
  30206. }
  30207. /* store the result */
  30208. *pResult = result;
  30209. /* return true if number and no extra non-whitespace chracters after */
  30210. if( z==zEnd && nDigit>0 && eValid && eType>0 ){
  30211. return eType;
  30212. }else if( eType>=2 && (eType==3 || eValid) && nDigit>0 ){
  30213. return -1;
  30214. }else{
  30215. return 0;
  30216. }
  30217. #else
  30218. return !sqlite3Atoi64(z, pResult, length, enc);
  30219. #endif /* SQLITE_OMIT_FLOATING_POINT */
  30220. }
  30221. #if defined(_MSC_VER)
  30222. #pragma warning(default : 4756)
  30223. #endif
  30224. /*
  30225. ** Compare the 19-character string zNum against the text representation
  30226. ** value 2^63: 9223372036854775808. Return negative, zero, or positive
  30227. ** if zNum is less than, equal to, or greater than the string.
  30228. ** Note that zNum must contain exactly 19 characters.
  30229. **
  30230. ** Unlike memcmp() this routine is guaranteed to return the difference
  30231. ** in the values of the last digit if the only difference is in the
  30232. ** last digit. So, for example,
  30233. **
  30234. ** compare2pow63("9223372036854775800", 1)
  30235. **
  30236. ** will return -8.
  30237. */
  30238. static int compare2pow63(const char *zNum, int incr){
  30239. int c = 0;
  30240. int i;
  30241. /* 012345678901234567 */
  30242. const char *pow63 = "922337203685477580";
  30243. for(i=0; c==0 && i<18; i++){
  30244. c = (zNum[i*incr]-pow63[i])*10;
  30245. }
  30246. if( c==0 ){
  30247. c = zNum[18*incr] - '8';
  30248. testcase( c==(-1) );
  30249. testcase( c==0 );
  30250. testcase( c==(+1) );
  30251. }
  30252. return c;
  30253. }
  30254. /*
  30255. ** Convert zNum to a 64-bit signed integer. zNum must be decimal. This
  30256. ** routine does *not* accept hexadecimal notation.
  30257. **
  30258. ** Returns:
  30259. **
  30260. ** -1 Not even a prefix of the input text looks like an integer
  30261. ** 0 Successful transformation. Fits in a 64-bit signed integer.
  30262. ** 1 Excess non-space text after the integer value
  30263. ** 2 Integer too large for a 64-bit signed integer or is malformed
  30264. ** 3 Special case of 9223372036854775808
  30265. **
  30266. ** length is the number of bytes in the string (bytes, not characters).
  30267. ** The string is not necessarily zero-terminated. The encoding is
  30268. ** given by enc.
  30269. */
  30270. SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc){
  30271. int incr;
  30272. u64 u = 0;
  30273. int neg = 0; /* assume positive */
  30274. int i;
  30275. int c = 0;
  30276. int nonNum = 0; /* True if input contains UTF16 with high byte non-zero */
  30277. int rc; /* Baseline return code */
  30278. const char *zStart;
  30279. const char *zEnd = zNum + length;
  30280. assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
  30281. if( enc==SQLITE_UTF8 ){
  30282. incr = 1;
  30283. }else{
  30284. incr = 2;
  30285. assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
  30286. for(i=3-enc; i<length && zNum[i]==0; i+=2){}
  30287. nonNum = i<length;
  30288. zEnd = &zNum[i^1];
  30289. zNum += (enc&1);
  30290. }
  30291. while( zNum<zEnd && sqlite3Isspace(*zNum) ) zNum+=incr;
  30292. if( zNum<zEnd ){
  30293. if( *zNum=='-' ){
  30294. neg = 1;
  30295. zNum+=incr;
  30296. }else if( *zNum=='+' ){
  30297. zNum+=incr;
  30298. }
  30299. }
  30300. zStart = zNum;
  30301. while( zNum<zEnd && zNum[0]=='0' ){ zNum+=incr; } /* Skip leading zeros. */
  30302. for(i=0; &zNum[i]<zEnd && (c=zNum[i])>='0' && c<='9'; i+=incr){
  30303. u = u*10 + c - '0';
  30304. }
  30305. testcase( i==18*incr );
  30306. testcase( i==19*incr );
  30307. testcase( i==20*incr );
  30308. if( u>LARGEST_INT64 ){
  30309. /* This test and assignment is needed only to suppress UB warnings
  30310. ** from clang and -fsanitize=undefined. This test and assignment make
  30311. ** the code a little larger and slower, and no harm comes from omitting
  30312. ** them, but we must appaise the undefined-behavior pharisees. */
  30313. *pNum = neg ? SMALLEST_INT64 : LARGEST_INT64;
  30314. }else if( neg ){
  30315. *pNum = -(i64)u;
  30316. }else{
  30317. *pNum = (i64)u;
  30318. }
  30319. rc = 0;
  30320. if( i==0 && zStart==zNum ){ /* No digits */
  30321. rc = -1;
  30322. }else if( nonNum ){ /* UTF16 with high-order bytes non-zero */
  30323. rc = 1;
  30324. }else if( &zNum[i]<zEnd ){ /* Extra bytes at the end */
  30325. int jj = i;
  30326. do{
  30327. if( !sqlite3Isspace(zNum[jj]) ){
  30328. rc = 1; /* Extra non-space text after the integer */
  30329. break;
  30330. }
  30331. jj += incr;
  30332. }while( &zNum[jj]<zEnd );
  30333. }
  30334. if( i<19*incr ){
  30335. /* Less than 19 digits, so we know that it fits in 64 bits */
  30336. assert( u<=LARGEST_INT64 );
  30337. return rc;
  30338. }else{
  30339. /* zNum is a 19-digit numbers. Compare it against 9223372036854775808. */
  30340. c = i>19*incr ? 1 : compare2pow63(zNum, incr);
  30341. if( c<0 ){
  30342. /* zNum is less than 9223372036854775808 so it fits */
  30343. assert( u<=LARGEST_INT64 );
  30344. return rc;
  30345. }else{
  30346. *pNum = neg ? SMALLEST_INT64 : LARGEST_INT64;
  30347. if( c>0 ){
  30348. /* zNum is greater than 9223372036854775808 so it overflows */
  30349. return 2;
  30350. }else{
  30351. /* zNum is exactly 9223372036854775808. Fits if negative. The
  30352. ** special case 2 overflow if positive */
  30353. assert( u-1==LARGEST_INT64 );
  30354. return neg ? rc : 3;
  30355. }
  30356. }
  30357. }
  30358. }
  30359. /*
  30360. ** Transform a UTF-8 integer literal, in either decimal or hexadecimal,
  30361. ** into a 64-bit signed integer. This routine accepts hexadecimal literals,
  30362. ** whereas sqlite3Atoi64() does not.
  30363. **
  30364. ** Returns:
  30365. **
  30366. ** 0 Successful transformation. Fits in a 64-bit signed integer.
  30367. ** 1 Excess text after the integer value
  30368. ** 2 Integer too large for a 64-bit signed integer or is malformed
  30369. ** 3 Special case of 9223372036854775808
  30370. */
  30371. SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char *z, i64 *pOut){
  30372. #ifndef SQLITE_OMIT_HEX_INTEGER
  30373. if( z[0]=='0'
  30374. && (z[1]=='x' || z[1]=='X')
  30375. ){
  30376. u64 u = 0;
  30377. int i, k;
  30378. for(i=2; z[i]=='0'; i++){}
  30379. for(k=i; sqlite3Isxdigit(z[k]); k++){
  30380. u = u*16 + sqlite3HexToInt(z[k]);
  30381. }
  30382. memcpy(pOut, &u, 8);
  30383. return (z[k]==0 && k-i<=16) ? 0 : 2;
  30384. }else
  30385. #endif /* SQLITE_OMIT_HEX_INTEGER */
  30386. {
  30387. return sqlite3Atoi64(z, pOut, sqlite3Strlen30(z), SQLITE_UTF8);
  30388. }
  30389. }
  30390. /*
  30391. ** If zNum represents an integer that will fit in 32-bits, then set
  30392. ** *pValue to that integer and return true. Otherwise return false.
  30393. **
  30394. ** This routine accepts both decimal and hexadecimal notation for integers.
  30395. **
  30396. ** Any non-numeric characters that following zNum are ignored.
  30397. ** This is different from sqlite3Atoi64() which requires the
  30398. ** input number to be zero-terminated.
  30399. */
  30400. SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){
  30401. sqlite_int64 v = 0;
  30402. int i, c;
  30403. int neg = 0;
  30404. if( zNum[0]=='-' ){
  30405. neg = 1;
  30406. zNum++;
  30407. }else if( zNum[0]=='+' ){
  30408. zNum++;
  30409. }
  30410. #ifndef SQLITE_OMIT_HEX_INTEGER
  30411. else if( zNum[0]=='0'
  30412. && (zNum[1]=='x' || zNum[1]=='X')
  30413. && sqlite3Isxdigit(zNum[2])
  30414. ){
  30415. u32 u = 0;
  30416. zNum += 2;
  30417. while( zNum[0]=='0' ) zNum++;
  30418. for(i=0; sqlite3Isxdigit(zNum[i]) && i<8; i++){
  30419. u = u*16 + sqlite3HexToInt(zNum[i]);
  30420. }
  30421. if( (u&0x80000000)==0 && sqlite3Isxdigit(zNum[i])==0 ){
  30422. memcpy(pValue, &u, 4);
  30423. return 1;
  30424. }else{
  30425. return 0;
  30426. }
  30427. }
  30428. #endif
  30429. if( !sqlite3Isdigit(zNum[0]) ) return 0;
  30430. while( zNum[0]=='0' ) zNum++;
  30431. for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
  30432. v = v*10 + c;
  30433. }
  30434. /* The longest decimal representation of a 32 bit integer is 10 digits:
  30435. **
  30436. ** 1234567890
  30437. ** 2^31 -> 2147483648
  30438. */
  30439. testcase( i==10 );
  30440. if( i>10 ){
  30441. return 0;
  30442. }
  30443. testcase( v-neg==2147483647 );
  30444. if( v-neg>2147483647 ){
  30445. return 0;
  30446. }
  30447. if( neg ){
  30448. v = -v;
  30449. }
  30450. *pValue = (int)v;
  30451. return 1;
  30452. }
  30453. /*
  30454. ** Return a 32-bit integer value extracted from a string. If the
  30455. ** string is not an integer, just return 0.
  30456. */
  30457. SQLITE_PRIVATE int sqlite3Atoi(const char *z){
  30458. int x = 0;
  30459. if( z ) sqlite3GetInt32(z, &x);
  30460. return x;
  30461. }
  30462. /*
  30463. ** The variable-length integer encoding is as follows:
  30464. **
  30465. ** KEY:
  30466. ** A = 0xxxxxxx 7 bits of data and one flag bit
  30467. ** B = 1xxxxxxx 7 bits of data and one flag bit
  30468. ** C = xxxxxxxx 8 bits of data
  30469. **
  30470. ** 7 bits - A
  30471. ** 14 bits - BA
  30472. ** 21 bits - BBA
  30473. ** 28 bits - BBBA
  30474. ** 35 bits - BBBBA
  30475. ** 42 bits - BBBBBA
  30476. ** 49 bits - BBBBBBA
  30477. ** 56 bits - BBBBBBBA
  30478. ** 64 bits - BBBBBBBBC
  30479. */
  30480. /*
  30481. ** Write a 64-bit variable-length integer to memory starting at p[0].
  30482. ** The length of data write will be between 1 and 9 bytes. The number
  30483. ** of bytes written is returned.
  30484. **
  30485. ** A variable-length integer consists of the lower 7 bits of each byte
  30486. ** for all bytes that have the 8th bit set and one byte with the 8th
  30487. ** bit clear. Except, if we get to the 9th byte, it stores the full
  30488. ** 8 bits and is the last byte.
  30489. */
  30490. static int SQLITE_NOINLINE putVarint64(unsigned char *p, u64 v){
  30491. int i, j, n;
  30492. u8 buf[10];
  30493. if( v & (((u64)0xff000000)<<32) ){
  30494. p[8] = (u8)v;
  30495. v >>= 8;
  30496. for(i=7; i>=0; i--){
  30497. p[i] = (u8)((v & 0x7f) | 0x80);
  30498. v >>= 7;
  30499. }
  30500. return 9;
  30501. }
  30502. n = 0;
  30503. do{
  30504. buf[n++] = (u8)((v & 0x7f) | 0x80);
  30505. v >>= 7;
  30506. }while( v!=0 );
  30507. buf[0] &= 0x7f;
  30508. assert( n<=9 );
  30509. for(i=0, j=n-1; j>=0; j--, i++){
  30510. p[i] = buf[j];
  30511. }
  30512. return n;
  30513. }
  30514. SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){
  30515. if( v<=0x7f ){
  30516. p[0] = v&0x7f;
  30517. return 1;
  30518. }
  30519. if( v<=0x3fff ){
  30520. p[0] = ((v>>7)&0x7f)|0x80;
  30521. p[1] = v&0x7f;
  30522. return 2;
  30523. }
  30524. return putVarint64(p,v);
  30525. }
  30526. /*
  30527. ** Bitmasks used by sqlite3GetVarint(). These precomputed constants
  30528. ** are defined here rather than simply putting the constant expressions
  30529. ** inline in order to work around bugs in the RVT compiler.
  30530. **
  30531. ** SLOT_2_0 A mask for (0x7f<<14) | 0x7f
  30532. **
  30533. ** SLOT_4_2_0 A mask for (0x7f<<28) | SLOT_2_0
  30534. */
  30535. #define SLOT_2_0 0x001fc07f
  30536. #define SLOT_4_2_0 0xf01fc07f
  30537. /*
  30538. ** Read a 64-bit variable-length integer from memory starting at p[0].
  30539. ** Return the number of bytes read. The value is stored in *v.
  30540. */
  30541. SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
  30542. u32 a,b,s;
  30543. if( ((signed char*)p)[0]>=0 ){
  30544. *v = *p;
  30545. return 1;
  30546. }
  30547. if( ((signed char*)p)[1]>=0 ){
  30548. *v = ((u32)(p[0]&0x7f)<<7) | p[1];
  30549. return 2;
  30550. }
  30551. /* Verify that constants are precomputed correctly */
  30552. assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
  30553. assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
  30554. a = ((u32)p[0])<<14;
  30555. b = p[1];
  30556. p += 2;
  30557. a |= *p;
  30558. /* a: p0<<14 | p2 (unmasked) */
  30559. if (!(a&0x80))
  30560. {
  30561. a &= SLOT_2_0;
  30562. b &= 0x7f;
  30563. b = b<<7;
  30564. a |= b;
  30565. *v = a;
  30566. return 3;
  30567. }
  30568. /* CSE1 from below */
  30569. a &= SLOT_2_0;
  30570. p++;
  30571. b = b<<14;
  30572. b |= *p;
  30573. /* b: p1<<14 | p3 (unmasked) */
  30574. if (!(b&0x80))
  30575. {
  30576. b &= SLOT_2_0;
  30577. /* moved CSE1 up */
  30578. /* a &= (0x7f<<14)|(0x7f); */
  30579. a = a<<7;
  30580. a |= b;
  30581. *v = a;
  30582. return 4;
  30583. }
  30584. /* a: p0<<14 | p2 (masked) */
  30585. /* b: p1<<14 | p3 (unmasked) */
  30586. /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  30587. /* moved CSE1 up */
  30588. /* a &= (0x7f<<14)|(0x7f); */
  30589. b &= SLOT_2_0;
  30590. s = a;
  30591. /* s: p0<<14 | p2 (masked) */
  30592. p++;
  30593. a = a<<14;
  30594. a |= *p;
  30595. /* a: p0<<28 | p2<<14 | p4 (unmasked) */
  30596. if (!(a&0x80))
  30597. {
  30598. /* we can skip these cause they were (effectively) done above
  30599. ** while calculating s */
  30600. /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
  30601. /* b &= (0x7f<<14)|(0x7f); */
  30602. b = b<<7;
  30603. a |= b;
  30604. s = s>>18;
  30605. *v = ((u64)s)<<32 | a;
  30606. return 5;
  30607. }
  30608. /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  30609. s = s<<7;
  30610. s |= b;
  30611. /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  30612. p++;
  30613. b = b<<14;
  30614. b |= *p;
  30615. /* b: p1<<28 | p3<<14 | p5 (unmasked) */
  30616. if (!(b&0x80))
  30617. {
  30618. /* we can skip this cause it was (effectively) done above in calc'ing s */
  30619. /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
  30620. a &= SLOT_2_0;
  30621. a = a<<7;
  30622. a |= b;
  30623. s = s>>18;
  30624. *v = ((u64)s)<<32 | a;
  30625. return 6;
  30626. }
  30627. p++;
  30628. a = a<<14;
  30629. a |= *p;
  30630. /* a: p2<<28 | p4<<14 | p6 (unmasked) */
  30631. if (!(a&0x80))
  30632. {
  30633. a &= SLOT_4_2_0;
  30634. b &= SLOT_2_0;
  30635. b = b<<7;
  30636. a |= b;
  30637. s = s>>11;
  30638. *v = ((u64)s)<<32 | a;
  30639. return 7;
  30640. }
  30641. /* CSE2 from below */
  30642. a &= SLOT_2_0;
  30643. p++;
  30644. b = b<<14;
  30645. b |= *p;
  30646. /* b: p3<<28 | p5<<14 | p7 (unmasked) */
  30647. if (!(b&0x80))
  30648. {
  30649. b &= SLOT_4_2_0;
  30650. /* moved CSE2 up */
  30651. /* a &= (0x7f<<14)|(0x7f); */
  30652. a = a<<7;
  30653. a |= b;
  30654. s = s>>4;
  30655. *v = ((u64)s)<<32 | a;
  30656. return 8;
  30657. }
  30658. p++;
  30659. a = a<<15;
  30660. a |= *p;
  30661. /* a: p4<<29 | p6<<15 | p8 (unmasked) */
  30662. /* moved CSE2 up */
  30663. /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
  30664. b &= SLOT_2_0;
  30665. b = b<<8;
  30666. a |= b;
  30667. s = s<<4;
  30668. b = p[-4];
  30669. b &= 0x7f;
  30670. b = b>>3;
  30671. s |= b;
  30672. *v = ((u64)s)<<32 | a;
  30673. return 9;
  30674. }
  30675. /*
  30676. ** Read a 32-bit variable-length integer from memory starting at p[0].
  30677. ** Return the number of bytes read. The value is stored in *v.
  30678. **
  30679. ** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
  30680. ** integer, then set *v to 0xffffffff.
  30681. **
  30682. ** A MACRO version, getVarint32, is provided which inlines the
  30683. ** single-byte case. All code should use the MACRO version as
  30684. ** this function assumes the single-byte case has already been handled.
  30685. */
  30686. SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
  30687. u32 a,b;
  30688. /* The 1-byte case. Overwhelmingly the most common. Handled inline
  30689. ** by the getVarin32() macro */
  30690. a = *p;
  30691. /* a: p0 (unmasked) */
  30692. #ifndef getVarint32
  30693. if (!(a&0x80))
  30694. {
  30695. /* Values between 0 and 127 */
  30696. *v = a;
  30697. return 1;
  30698. }
  30699. #endif
  30700. /* The 2-byte case */
  30701. p++;
  30702. b = *p;
  30703. /* b: p1 (unmasked) */
  30704. if (!(b&0x80))
  30705. {
  30706. /* Values between 128 and 16383 */
  30707. a &= 0x7f;
  30708. a = a<<7;
  30709. *v = a | b;
  30710. return 2;
  30711. }
  30712. /* The 3-byte case */
  30713. p++;
  30714. a = a<<14;
  30715. a |= *p;
  30716. /* a: p0<<14 | p2 (unmasked) */
  30717. if (!(a&0x80))
  30718. {
  30719. /* Values between 16384 and 2097151 */
  30720. a &= (0x7f<<14)|(0x7f);
  30721. b &= 0x7f;
  30722. b = b<<7;
  30723. *v = a | b;
  30724. return 3;
  30725. }
  30726. /* A 32-bit varint is used to store size information in btrees.
  30727. ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
  30728. ** A 3-byte varint is sufficient, for example, to record the size
  30729. ** of a 1048569-byte BLOB or string.
  30730. **
  30731. ** We only unroll the first 1-, 2-, and 3- byte cases. The very
  30732. ** rare larger cases can be handled by the slower 64-bit varint
  30733. ** routine.
  30734. */
  30735. #if 1
  30736. {
  30737. u64 v64;
  30738. u8 n;
  30739. p -= 2;
  30740. n = sqlite3GetVarint(p, &v64);
  30741. assert( n>3 && n<=9 );
  30742. if( (v64 & SQLITE_MAX_U32)!=v64 ){
  30743. *v = 0xffffffff;
  30744. }else{
  30745. *v = (u32)v64;
  30746. }
  30747. return n;
  30748. }
  30749. #else
  30750. /* For following code (kept for historical record only) shows an
  30751. ** unrolling for the 3- and 4-byte varint cases. This code is
  30752. ** slightly faster, but it is also larger and much harder to test.
  30753. */
  30754. p++;
  30755. b = b<<14;
  30756. b |= *p;
  30757. /* b: p1<<14 | p3 (unmasked) */
  30758. if (!(b&0x80))
  30759. {
  30760. /* Values between 2097152 and 268435455 */
  30761. b &= (0x7f<<14)|(0x7f);
  30762. a &= (0x7f<<14)|(0x7f);
  30763. a = a<<7;
  30764. *v = a | b;
  30765. return 4;
  30766. }
  30767. p++;
  30768. a = a<<14;
  30769. a |= *p;
  30770. /* a: p0<<28 | p2<<14 | p4 (unmasked) */
  30771. if (!(a&0x80))
  30772. {
  30773. /* Values between 268435456 and 34359738367 */
  30774. a &= SLOT_4_2_0;
  30775. b &= SLOT_4_2_0;
  30776. b = b<<7;
  30777. *v = a | b;
  30778. return 5;
  30779. }
  30780. /* We can only reach this point when reading a corrupt database
  30781. ** file. In that case we are not in any hurry. Use the (relatively
  30782. ** slow) general-purpose sqlite3GetVarint() routine to extract the
  30783. ** value. */
  30784. {
  30785. u64 v64;
  30786. u8 n;
  30787. p -= 4;
  30788. n = sqlite3GetVarint(p, &v64);
  30789. assert( n>5 && n<=9 );
  30790. *v = (u32)v64;
  30791. return n;
  30792. }
  30793. #endif
  30794. }
  30795. /*
  30796. ** Return the number of bytes that will be needed to store the given
  30797. ** 64-bit integer.
  30798. */
  30799. SQLITE_PRIVATE int sqlite3VarintLen(u64 v){
  30800. int i;
  30801. for(i=1; (v >>= 7)!=0; i++){ assert( i<10 ); }
  30802. return i;
  30803. }
  30804. /*
  30805. ** Read or write a four-byte big-endian integer value.
  30806. */
  30807. SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){
  30808. #if SQLITE_BYTEORDER==4321
  30809. u32 x;
  30810. memcpy(&x,p,4);
  30811. return x;
  30812. #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
  30813. u32 x;
  30814. memcpy(&x,p,4);
  30815. return __builtin_bswap32(x);
  30816. #elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
  30817. u32 x;
  30818. memcpy(&x,p,4);
  30819. return _byteswap_ulong(x);
  30820. #else
  30821. testcase( p[0]&0x80 );
  30822. return ((unsigned)p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
  30823. #endif
  30824. }
  30825. SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){
  30826. #if SQLITE_BYTEORDER==4321
  30827. memcpy(p,&v,4);
  30828. #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
  30829. u32 x = __builtin_bswap32(v);
  30830. memcpy(p,&x,4);
  30831. #elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
  30832. u32 x = _byteswap_ulong(v);
  30833. memcpy(p,&x,4);
  30834. #else
  30835. p[0] = (u8)(v>>24);
  30836. p[1] = (u8)(v>>16);
  30837. p[2] = (u8)(v>>8);
  30838. p[3] = (u8)v;
  30839. #endif
  30840. }
  30841. /*
  30842. ** Translate a single byte of Hex into an integer.
  30843. ** This routine only works if h really is a valid hexadecimal
  30844. ** character: 0..9a..fA..F
  30845. */
  30846. SQLITE_PRIVATE u8 sqlite3HexToInt(int h){
  30847. assert( (h>='0' && h<='9') || (h>='a' && h<='f') || (h>='A' && h<='F') );
  30848. #ifdef SQLITE_ASCII
  30849. h += 9*(1&(h>>6));
  30850. #endif
  30851. #ifdef SQLITE_EBCDIC
  30852. h += 9*(1&~(h>>4));
  30853. #endif
  30854. return (u8)(h & 0xf);
  30855. }
  30856. #if !defined(SQLITE_OMIT_BLOB_LITERAL)
  30857. /*
  30858. ** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
  30859. ** value. Return a pointer to its binary value. Space to hold the
  30860. ** binary value has been obtained from malloc and must be freed by
  30861. ** the calling routine.
  30862. */
  30863. SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
  30864. char *zBlob;
  30865. int i;
  30866. zBlob = (char *)sqlite3DbMallocRawNN(db, n/2 + 1);
  30867. n--;
  30868. if( zBlob ){
  30869. for(i=0; i<n; i+=2){
  30870. zBlob[i/2] = (sqlite3HexToInt(z[i])<<4) | sqlite3HexToInt(z[i+1]);
  30871. }
  30872. zBlob[i/2] = 0;
  30873. }
  30874. return zBlob;
  30875. }
  30876. #endif /* !SQLITE_OMIT_BLOB_LITERAL */
  30877. /*
  30878. ** Log an error that is an API call on a connection pointer that should
  30879. ** not have been used. The "type" of connection pointer is given as the
  30880. ** argument. The zType is a word like "NULL" or "closed" or "invalid".
  30881. */
  30882. static void logBadConnection(const char *zType){
  30883. sqlite3_log(SQLITE_MISUSE,
  30884. "API call with %s database connection pointer",
  30885. zType
  30886. );
  30887. }
  30888. /*
  30889. ** Check to make sure we have a valid db pointer. This test is not
  30890. ** foolproof but it does provide some measure of protection against
  30891. ** misuse of the interface such as passing in db pointers that are
  30892. ** NULL or which have been previously closed. If this routine returns
  30893. ** 1 it means that the db pointer is valid and 0 if it should not be
  30894. ** dereferenced for any reason. The calling function should invoke
  30895. ** SQLITE_MISUSE immediately.
  30896. **
  30897. ** sqlite3SafetyCheckOk() requires that the db pointer be valid for
  30898. ** use. sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
  30899. ** open properly and is not fit for general use but which can be
  30900. ** used as an argument to sqlite3_errmsg() or sqlite3_close().
  30901. */
  30902. SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){
  30903. u32 magic;
  30904. if( db==0 ){
  30905. logBadConnection("NULL");
  30906. return 0;
  30907. }
  30908. magic = db->magic;
  30909. if( magic!=SQLITE_MAGIC_OPEN ){
  30910. if( sqlite3SafetyCheckSickOrOk(db) ){
  30911. testcase( sqlite3GlobalConfig.xLog!=0 );
  30912. logBadConnection("unopened");
  30913. }
  30914. return 0;
  30915. }else{
  30916. return 1;
  30917. }
  30918. }
  30919. SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
  30920. u32 magic;
  30921. magic = db->magic;
  30922. if( magic!=SQLITE_MAGIC_SICK &&
  30923. magic!=SQLITE_MAGIC_OPEN &&
  30924. magic!=SQLITE_MAGIC_BUSY ){
  30925. testcase( sqlite3GlobalConfig.xLog!=0 );
  30926. logBadConnection("invalid");
  30927. return 0;
  30928. }else{
  30929. return 1;
  30930. }
  30931. }
  30932. /*
  30933. ** Attempt to add, substract, or multiply the 64-bit signed value iB against
  30934. ** the other 64-bit signed integer at *pA and store the result in *pA.
  30935. ** Return 0 on success. Or if the operation would have resulted in an
  30936. ** overflow, leave *pA unchanged and return 1.
  30937. */
  30938. SQLITE_PRIVATE int sqlite3AddInt64(i64 *pA, i64 iB){
  30939. #if GCC_VERSION>=5004000 && !defined(__INTEL_COMPILER)
  30940. return __builtin_add_overflow(*pA, iB, pA);
  30941. #else
  30942. i64 iA = *pA;
  30943. testcase( iA==0 ); testcase( iA==1 );
  30944. testcase( iB==-1 ); testcase( iB==0 );
  30945. if( iB>=0 ){
  30946. testcase( iA>0 && LARGEST_INT64 - iA == iB );
  30947. testcase( iA>0 && LARGEST_INT64 - iA == iB - 1 );
  30948. if( iA>0 && LARGEST_INT64 - iA < iB ) return 1;
  30949. }else{
  30950. testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 1 );
  30951. testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 2 );
  30952. if( iA<0 && -(iA + LARGEST_INT64) > iB + 1 ) return 1;
  30953. }
  30954. *pA += iB;
  30955. return 0;
  30956. #endif
  30957. }
  30958. SQLITE_PRIVATE int sqlite3SubInt64(i64 *pA, i64 iB){
  30959. #if GCC_VERSION>=5004000 && !defined(__INTEL_COMPILER)
  30960. return __builtin_sub_overflow(*pA, iB, pA);
  30961. #else
  30962. testcase( iB==SMALLEST_INT64+1 );
  30963. if( iB==SMALLEST_INT64 ){
  30964. testcase( (*pA)==(-1) ); testcase( (*pA)==0 );
  30965. if( (*pA)>=0 ) return 1;
  30966. *pA -= iB;
  30967. return 0;
  30968. }else{
  30969. return sqlite3AddInt64(pA, -iB);
  30970. }
  30971. #endif
  30972. }
  30973. SQLITE_PRIVATE int sqlite3MulInt64(i64 *pA, i64 iB){
  30974. #if GCC_VERSION>=5004000 && !defined(__INTEL_COMPILER)
  30975. return __builtin_mul_overflow(*pA, iB, pA);
  30976. #else
  30977. i64 iA = *pA;
  30978. if( iB>0 ){
  30979. if( iA>LARGEST_INT64/iB ) return 1;
  30980. if( iA<SMALLEST_INT64/iB ) return 1;
  30981. }else if( iB<0 ){
  30982. if( iA>0 ){
  30983. if( iB<SMALLEST_INT64/iA ) return 1;
  30984. }else if( iA<0 ){
  30985. if( iB==SMALLEST_INT64 ) return 1;
  30986. if( iA==SMALLEST_INT64 ) return 1;
  30987. if( -iA>LARGEST_INT64/-iB ) return 1;
  30988. }
  30989. }
  30990. *pA = iA*iB;
  30991. return 0;
  30992. #endif
  30993. }
  30994. /*
  30995. ** Compute the absolute value of a 32-bit signed integer, of possible. Or
  30996. ** if the integer has a value of -2147483648, return +2147483647
  30997. */
  30998. SQLITE_PRIVATE int sqlite3AbsInt32(int x){
  30999. if( x>=0 ) return x;
  31000. if( x==(int)0x80000000 ) return 0x7fffffff;
  31001. return -x;
  31002. }
  31003. #ifdef SQLITE_ENABLE_8_3_NAMES
  31004. /*
  31005. ** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
  31006. ** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
  31007. ** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
  31008. ** three characters, then shorten the suffix on z[] to be the last three
  31009. ** characters of the original suffix.
  31010. **
  31011. ** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
  31012. ** do the suffix shortening regardless of URI parameter.
  31013. **
  31014. ** Examples:
  31015. **
  31016. ** test.db-journal => test.nal
  31017. ** test.db-wal => test.wal
  31018. ** test.db-shm => test.shm
  31019. ** test.db-mj7f3319fa => test.9fa
  31020. */
  31021. SQLITE_PRIVATE void sqlite3FileSuffix3(const char *zBaseFilename, char *z){
  31022. #if SQLITE_ENABLE_8_3_NAMES<2
  31023. if( sqlite3_uri_boolean(zBaseFilename, "8_3_names", 0) )
  31024. #endif
  31025. {
  31026. int i, sz;
  31027. sz = sqlite3Strlen30(z);
  31028. for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
  31029. if( z[i]=='.' && ALWAYS(sz>i+4) ) memmove(&z[i+1], &z[sz-3], 4);
  31030. }
  31031. }
  31032. #endif
  31033. /*
  31034. ** Find (an approximate) sum of two LogEst values. This computation is
  31035. ** not a simple "+" operator because LogEst is stored as a logarithmic
  31036. ** value.
  31037. **
  31038. */
  31039. SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst a, LogEst b){
  31040. static const unsigned char x[] = {
  31041. 10, 10, /* 0,1 */
  31042. 9, 9, /* 2,3 */
  31043. 8, 8, /* 4,5 */
  31044. 7, 7, 7, /* 6,7,8 */
  31045. 6, 6, 6, /* 9,10,11 */
  31046. 5, 5, 5, /* 12-14 */
  31047. 4, 4, 4, 4, /* 15-18 */
  31048. 3, 3, 3, 3, 3, 3, /* 19-24 */
  31049. 2, 2, 2, 2, 2, 2, 2, /* 25-31 */
  31050. };
  31051. if( a>=b ){
  31052. if( a>b+49 ) return a;
  31053. if( a>b+31 ) return a+1;
  31054. return a+x[a-b];
  31055. }else{
  31056. if( b>a+49 ) return b;
  31057. if( b>a+31 ) return b+1;
  31058. return b+x[b-a];
  31059. }
  31060. }
  31061. /*
  31062. ** Convert an integer into a LogEst. In other words, compute an
  31063. ** approximation for 10*log2(x).
  31064. */
  31065. SQLITE_PRIVATE LogEst sqlite3LogEst(u64 x){
  31066. static LogEst a[] = { 0, 2, 3, 5, 6, 7, 8, 9 };
  31067. LogEst y = 40;
  31068. if( x<8 ){
  31069. if( x<2 ) return 0;
  31070. while( x<8 ){ y -= 10; x <<= 1; }
  31071. }else{
  31072. #if GCC_VERSION>=5004000
  31073. int i = 60 - __builtin_clzll(x);
  31074. y += i*10;
  31075. x >>= i;
  31076. #else
  31077. while( x>255 ){ y += 40; x >>= 4; } /*OPTIMIZATION-IF-TRUE*/
  31078. while( x>15 ){ y += 10; x >>= 1; }
  31079. #endif
  31080. }
  31081. return a[x&7] + y - 10;
  31082. }
  31083. #ifndef SQLITE_OMIT_VIRTUALTABLE
  31084. /*
  31085. ** Convert a double into a LogEst
  31086. ** In other words, compute an approximation for 10*log2(x).
  31087. */
  31088. SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double x){
  31089. u64 a;
  31090. LogEst e;
  31091. assert( sizeof(x)==8 && sizeof(a)==8 );
  31092. if( x<=1 ) return 0;
  31093. if( x<=2000000000 ) return sqlite3LogEst((u64)x);
  31094. memcpy(&a, &x, 8);
  31095. e = (a>>52) - 1022;
  31096. return e*10;
  31097. }
  31098. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  31099. #if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \
  31100. defined(SQLITE_ENABLE_STAT4) || \
  31101. defined(SQLITE_EXPLAIN_ESTIMATED_ROWS)
  31102. /*
  31103. ** Convert a LogEst into an integer.
  31104. **
  31105. ** Note that this routine is only used when one or more of various
  31106. ** non-standard compile-time options is enabled.
  31107. */
  31108. SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst x){
  31109. u64 n;
  31110. n = x%10;
  31111. x /= 10;
  31112. if( n>=5 ) n -= 2;
  31113. else if( n>=1 ) n -= 1;
  31114. #if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \
  31115. defined(SQLITE_EXPLAIN_ESTIMATED_ROWS)
  31116. if( x>60 ) return (u64)LARGEST_INT64;
  31117. #else
  31118. /* If only SQLITE_ENABLE_STAT4 is on, then the largest input
  31119. ** possible to this routine is 310, resulting in a maximum x of 31 */
  31120. assert( x<=60 );
  31121. #endif
  31122. return x>=3 ? (n+8)<<(x-3) : (n+8)>>(3-x);
  31123. }
  31124. #endif /* defined SCANSTAT or STAT4 or ESTIMATED_ROWS */
  31125. /*
  31126. ** Add a new name/number pair to a VList. This might require that the
  31127. ** VList object be reallocated, so return the new VList. If an OOM
  31128. ** error occurs, the original VList returned and the
  31129. ** db->mallocFailed flag is set.
  31130. **
  31131. ** A VList is really just an array of integers. To destroy a VList,
  31132. ** simply pass it to sqlite3DbFree().
  31133. **
  31134. ** The first integer is the number of integers allocated for the whole
  31135. ** VList. The second integer is the number of integers actually used.
  31136. ** Each name/number pair is encoded by subsequent groups of 3 or more
  31137. ** integers.
  31138. **
  31139. ** Each name/number pair starts with two integers which are the numeric
  31140. ** value for the pair and the size of the name/number pair, respectively.
  31141. ** The text name overlays one or more following integers. The text name
  31142. ** is always zero-terminated.
  31143. **
  31144. ** Conceptually:
  31145. **
  31146. ** struct VList {
  31147. ** int nAlloc; // Number of allocated slots
  31148. ** int nUsed; // Number of used slots
  31149. ** struct VListEntry {
  31150. ** int iValue; // Value for this entry
  31151. ** int nSlot; // Slots used by this entry
  31152. ** // ... variable name goes here
  31153. ** } a[0];
  31154. ** }
  31155. **
  31156. ** During code generation, pointers to the variable names within the
  31157. ** VList are taken. When that happens, nAlloc is set to zero as an
  31158. ** indication that the VList may never again be enlarged, since the
  31159. ** accompanying realloc() would invalidate the pointers.
  31160. */
  31161. SQLITE_PRIVATE VList *sqlite3VListAdd(
  31162. sqlite3 *db, /* The database connection used for malloc() */
  31163. VList *pIn, /* The input VList. Might be NULL */
  31164. const char *zName, /* Name of symbol to add */
  31165. int nName, /* Bytes of text in zName */
  31166. int iVal /* Value to associate with zName */
  31167. ){
  31168. int nInt; /* number of sizeof(int) objects needed for zName */
  31169. char *z; /* Pointer to where zName will be stored */
  31170. int i; /* Index in pIn[] where zName is stored */
  31171. nInt = nName/4 + 3;
  31172. assert( pIn==0 || pIn[0]>=3 ); /* Verify ok to add new elements */
  31173. if( pIn==0 || pIn[1]+nInt > pIn[0] ){
  31174. /* Enlarge the allocation */
  31175. sqlite3_int64 nAlloc = (pIn ? 2*(sqlite3_int64)pIn[0] : 10) + nInt;
  31176. VList *pOut = sqlite3DbRealloc(db, pIn, nAlloc*sizeof(int));
  31177. if( pOut==0 ) return pIn;
  31178. if( pIn==0 ) pOut[1] = 2;
  31179. pIn = pOut;
  31180. pIn[0] = nAlloc;
  31181. }
  31182. i = pIn[1];
  31183. pIn[i] = iVal;
  31184. pIn[i+1] = nInt;
  31185. z = (char*)&pIn[i+2];
  31186. pIn[1] = i+nInt;
  31187. assert( pIn[1]<=pIn[0] );
  31188. memcpy(z, zName, nName);
  31189. z[nName] = 0;
  31190. return pIn;
  31191. }
  31192. /*
  31193. ** Return a pointer to the name of a variable in the given VList that
  31194. ** has the value iVal. Or return a NULL if there is no such variable in
  31195. ** the list
  31196. */
  31197. SQLITE_PRIVATE const char *sqlite3VListNumToName(VList *pIn, int iVal){
  31198. int i, mx;
  31199. if( pIn==0 ) return 0;
  31200. mx = pIn[1];
  31201. i = 2;
  31202. do{
  31203. if( pIn[i]==iVal ) return (char*)&pIn[i+2];
  31204. i += pIn[i+1];
  31205. }while( i<mx );
  31206. return 0;
  31207. }
  31208. /*
  31209. ** Return the number of the variable named zName, if it is in VList.
  31210. ** or return 0 if there is no such variable.
  31211. */
  31212. SQLITE_PRIVATE int sqlite3VListNameToNum(VList *pIn, const char *zName, int nName){
  31213. int i, mx;
  31214. if( pIn==0 ) return 0;
  31215. mx = pIn[1];
  31216. i = 2;
  31217. do{
  31218. const char *z = (const char*)&pIn[i+2];
  31219. if( strncmp(z,zName,nName)==0 && z[nName]==0 ) return pIn[i];
  31220. i += pIn[i+1];
  31221. }while( i<mx );
  31222. return 0;
  31223. }
  31224. /************** End of util.c ************************************************/
  31225. /************** Begin file hash.c ********************************************/
  31226. /*
  31227. ** 2001 September 22
  31228. **
  31229. ** The author disclaims copyright to this source code. In place of
  31230. ** a legal notice, here is a blessing:
  31231. **
  31232. ** May you do good and not evil.
  31233. ** May you find forgiveness for yourself and forgive others.
  31234. ** May you share freely, never taking more than you give.
  31235. **
  31236. *************************************************************************
  31237. ** This is the implementation of generic hash-tables
  31238. ** used in SQLite.
  31239. */
  31240. /* #include "sqliteInt.h" */
  31241. /* #include <assert.h> */
  31242. /* Turn bulk memory into a hash table object by initializing the
  31243. ** fields of the Hash structure.
  31244. **
  31245. ** "pNew" is a pointer to the hash table that is to be initialized.
  31246. */
  31247. SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew){
  31248. assert( pNew!=0 );
  31249. pNew->first = 0;
  31250. pNew->count = 0;
  31251. pNew->htsize = 0;
  31252. pNew->ht = 0;
  31253. }
  31254. /* Remove all entries from a hash table. Reclaim all memory.
  31255. ** Call this routine to delete a hash table or to reset a hash table
  31256. ** to the empty state.
  31257. */
  31258. SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){
  31259. HashElem *elem; /* For looping over all elements of the table */
  31260. assert( pH!=0 );
  31261. elem = pH->first;
  31262. pH->first = 0;
  31263. sqlite3_free(pH->ht);
  31264. pH->ht = 0;
  31265. pH->htsize = 0;
  31266. while( elem ){
  31267. HashElem *next_elem = elem->next;
  31268. sqlite3_free(elem);
  31269. elem = next_elem;
  31270. }
  31271. pH->count = 0;
  31272. }
  31273. /*
  31274. ** The hashing function.
  31275. */
  31276. static unsigned int strHash(const char *z){
  31277. unsigned int h = 0;
  31278. unsigned char c;
  31279. while( (c = (unsigned char)*z++)!=0 ){ /*OPTIMIZATION-IF-TRUE*/
  31280. /* Knuth multiplicative hashing. (Sorting & Searching, p. 510).
  31281. ** 0x9e3779b1 is 2654435761 which is the closest prime number to
  31282. ** (2**32)*golden_ratio, where golden_ratio = (sqrt(5) - 1)/2. */
  31283. h += sqlite3UpperToLower[c];
  31284. h *= 0x9e3779b1;
  31285. }
  31286. return h;
  31287. }
  31288. /* Link pNew element into the hash table pH. If pEntry!=0 then also
  31289. ** insert pNew into the pEntry hash bucket.
  31290. */
  31291. static void insertElement(
  31292. Hash *pH, /* The complete hash table */
  31293. struct _ht *pEntry, /* The entry into which pNew is inserted */
  31294. HashElem *pNew /* The element to be inserted */
  31295. ){
  31296. HashElem *pHead; /* First element already in pEntry */
  31297. if( pEntry ){
  31298. pHead = pEntry->count ? pEntry->chain : 0;
  31299. pEntry->count++;
  31300. pEntry->chain = pNew;
  31301. }else{
  31302. pHead = 0;
  31303. }
  31304. if( pHead ){
  31305. pNew->next = pHead;
  31306. pNew->prev = pHead->prev;
  31307. if( pHead->prev ){ pHead->prev->next = pNew; }
  31308. else { pH->first = pNew; }
  31309. pHead->prev = pNew;
  31310. }else{
  31311. pNew->next = pH->first;
  31312. if( pH->first ){ pH->first->prev = pNew; }
  31313. pNew->prev = 0;
  31314. pH->first = pNew;
  31315. }
  31316. }
  31317. /* Resize the hash table so that it cantains "new_size" buckets.
  31318. **
  31319. ** The hash table might fail to resize if sqlite3_malloc() fails or
  31320. ** if the new size is the same as the prior size.
  31321. ** Return TRUE if the resize occurs and false if not.
  31322. */
  31323. static int rehash(Hash *pH, unsigned int new_size){
  31324. struct _ht *new_ht; /* The new hash table */
  31325. HashElem *elem, *next_elem; /* For looping over existing elements */
  31326. #if SQLITE_MALLOC_SOFT_LIMIT>0
  31327. if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
  31328. new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
  31329. }
  31330. if( new_size==pH->htsize ) return 0;
  31331. #endif
  31332. /* The inability to allocates space for a larger hash table is
  31333. ** a performance hit but it is not a fatal error. So mark the
  31334. ** allocation as a benign. Use sqlite3Malloc()/memset(0) instead of
  31335. ** sqlite3MallocZero() to make the allocation, as sqlite3MallocZero()
  31336. ** only zeroes the requested number of bytes whereas this module will
  31337. ** use the actual amount of space allocated for the hash table (which
  31338. ** may be larger than the requested amount).
  31339. */
  31340. sqlite3BeginBenignMalloc();
  31341. new_ht = (struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) );
  31342. sqlite3EndBenignMalloc();
  31343. if( new_ht==0 ) return 0;
  31344. sqlite3_free(pH->ht);
  31345. pH->ht = new_ht;
  31346. pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht);
  31347. memset(new_ht, 0, new_size*sizeof(struct _ht));
  31348. for(elem=pH->first, pH->first=0; elem; elem = next_elem){
  31349. unsigned int h = strHash(elem->pKey) % new_size;
  31350. next_elem = elem->next;
  31351. insertElement(pH, &new_ht[h], elem);
  31352. }
  31353. return 1;
  31354. }
  31355. /* This function (for internal use only) locates an element in an
  31356. ** hash table that matches the given key. If no element is found,
  31357. ** a pointer to a static null element with HashElem.data==0 is returned.
  31358. ** If pH is not NULL, then the hash for this key is written to *pH.
  31359. */
  31360. static HashElem *findElementWithHash(
  31361. const Hash *pH, /* The pH to be searched */
  31362. const char *pKey, /* The key we are searching for */
  31363. unsigned int *pHash /* Write the hash value here */
  31364. ){
  31365. HashElem *elem; /* Used to loop thru the element list */
  31366. unsigned int count; /* Number of elements left to test */
  31367. unsigned int h; /* The computed hash */
  31368. static HashElem nullElement = { 0, 0, 0, 0 };
  31369. if( pH->ht ){ /*OPTIMIZATION-IF-TRUE*/
  31370. struct _ht *pEntry;
  31371. h = strHash(pKey) % pH->htsize;
  31372. pEntry = &pH->ht[h];
  31373. elem = pEntry->chain;
  31374. count = pEntry->count;
  31375. }else{
  31376. h = 0;
  31377. elem = pH->first;
  31378. count = pH->count;
  31379. }
  31380. if( pHash ) *pHash = h;
  31381. while( count-- ){
  31382. assert( elem!=0 );
  31383. if( sqlite3StrICmp(elem->pKey,pKey)==0 ){
  31384. return elem;
  31385. }
  31386. elem = elem->next;
  31387. }
  31388. return &nullElement;
  31389. }
  31390. /* Remove a single entry from the hash table given a pointer to that
  31391. ** element and a hash on the element's key.
  31392. */
  31393. static void removeElementGivenHash(
  31394. Hash *pH, /* The pH containing "elem" */
  31395. HashElem* elem, /* The element to be removed from the pH */
  31396. unsigned int h /* Hash value for the element */
  31397. ){
  31398. struct _ht *pEntry;
  31399. if( elem->prev ){
  31400. elem->prev->next = elem->next;
  31401. }else{
  31402. pH->first = elem->next;
  31403. }
  31404. if( elem->next ){
  31405. elem->next->prev = elem->prev;
  31406. }
  31407. if( pH->ht ){
  31408. pEntry = &pH->ht[h];
  31409. if( pEntry->chain==elem ){
  31410. pEntry->chain = elem->next;
  31411. }
  31412. assert( pEntry->count>0 );
  31413. pEntry->count--;
  31414. }
  31415. sqlite3_free( elem );
  31416. pH->count--;
  31417. if( pH->count==0 ){
  31418. assert( pH->first==0 );
  31419. assert( pH->count==0 );
  31420. sqlite3HashClear(pH);
  31421. }
  31422. }
  31423. /* Attempt to locate an element of the hash table pH with a key
  31424. ** that matches pKey. Return the data for this element if it is
  31425. ** found, or NULL if there is no match.
  31426. */
  31427. SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const char *pKey){
  31428. assert( pH!=0 );
  31429. assert( pKey!=0 );
  31430. return findElementWithHash(pH, pKey, 0)->data;
  31431. }
  31432. /* Insert an element into the hash table pH. The key is pKey
  31433. ** and the data is "data".
  31434. **
  31435. ** If no element exists with a matching key, then a new
  31436. ** element is created and NULL is returned.
  31437. **
  31438. ** If another element already exists with the same key, then the
  31439. ** new data replaces the old data and the old data is returned.
  31440. ** The key is not copied in this instance. If a malloc fails, then
  31441. ** the new data is returned and the hash table is unchanged.
  31442. **
  31443. ** If the "data" parameter to this function is NULL, then the
  31444. ** element corresponding to "key" is removed from the hash table.
  31445. */
  31446. SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, void *data){
  31447. unsigned int h; /* the hash of the key modulo hash table size */
  31448. HashElem *elem; /* Used to loop thru the element list */
  31449. HashElem *new_elem; /* New element added to the pH */
  31450. assert( pH!=0 );
  31451. assert( pKey!=0 );
  31452. elem = findElementWithHash(pH,pKey,&h);
  31453. if( elem->data ){
  31454. void *old_data = elem->data;
  31455. if( data==0 ){
  31456. removeElementGivenHash(pH,elem,h);
  31457. }else{
  31458. elem->data = data;
  31459. elem->pKey = pKey;
  31460. }
  31461. return old_data;
  31462. }
  31463. if( data==0 ) return 0;
  31464. new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );
  31465. if( new_elem==0 ) return data;
  31466. new_elem->pKey = pKey;
  31467. new_elem->data = data;
  31468. pH->count++;
  31469. if( pH->count>=10 && pH->count > 2*pH->htsize ){
  31470. if( rehash(pH, pH->count*2) ){
  31471. assert( pH->htsize>0 );
  31472. h = strHash(pKey) % pH->htsize;
  31473. }
  31474. }
  31475. insertElement(pH, pH->ht ? &pH->ht[h] : 0, new_elem);
  31476. return 0;
  31477. }
  31478. /************** End of hash.c ************************************************/
  31479. /************** Begin file opcodes.c *****************************************/
  31480. /* Automatically generated. Do not edit */
  31481. /* See the tool/mkopcodec.tcl script for details. */
  31482. #if !defined(SQLITE_OMIT_EXPLAIN) \
  31483. || defined(VDBE_PROFILE) \
  31484. || defined(SQLITE_DEBUG)
  31485. #if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) || defined(SQLITE_DEBUG)
  31486. # define OpHelp(X) "\0" X
  31487. #else
  31488. # define OpHelp(X)
  31489. #endif
  31490. SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
  31491. static const char *const azName[] = {
  31492. /* 0 */ "Savepoint" OpHelp(""),
  31493. /* 1 */ "AutoCommit" OpHelp(""),
  31494. /* 2 */ "Transaction" OpHelp(""),
  31495. /* 3 */ "SorterNext" OpHelp(""),
  31496. /* 4 */ "Prev" OpHelp(""),
  31497. /* 5 */ "Next" OpHelp(""),
  31498. /* 6 */ "Checkpoint" OpHelp(""),
  31499. /* 7 */ "JournalMode" OpHelp(""),
  31500. /* 8 */ "Vacuum" OpHelp(""),
  31501. /* 9 */ "VFilter" OpHelp("iplan=r[P3] zplan='P4'"),
  31502. /* 10 */ "VUpdate" OpHelp("data=r[P3@P2]"),
  31503. /* 11 */ "Goto" OpHelp(""),
  31504. /* 12 */ "Gosub" OpHelp(""),
  31505. /* 13 */ "InitCoroutine" OpHelp(""),
  31506. /* 14 */ "Yield" OpHelp(""),
  31507. /* 15 */ "MustBeInt" OpHelp(""),
  31508. /* 16 */ "Jump" OpHelp(""),
  31509. /* 17 */ "Once" OpHelp(""),
  31510. /* 18 */ "If" OpHelp(""),
  31511. /* 19 */ "Not" OpHelp("r[P2]= !r[P1]"),
  31512. /* 20 */ "IfNot" OpHelp(""),
  31513. /* 21 */ "IfNullRow" OpHelp("if P1.nullRow then r[P3]=NULL, goto P2"),
  31514. /* 22 */ "SeekLT" OpHelp("key=r[P3@P4]"),
  31515. /* 23 */ "SeekLE" OpHelp("key=r[P3@P4]"),
  31516. /* 24 */ "SeekGE" OpHelp("key=r[P3@P4]"),
  31517. /* 25 */ "SeekGT" OpHelp("key=r[P3@P4]"),
  31518. /* 26 */ "IfNotOpen" OpHelp("if( !csr[P1] ) goto P2"),
  31519. /* 27 */ "IfNoHope" OpHelp("key=r[P3@P4]"),
  31520. /* 28 */ "NoConflict" OpHelp("key=r[P3@P4]"),
  31521. /* 29 */ "NotFound" OpHelp("key=r[P3@P4]"),
  31522. /* 30 */ "Found" OpHelp("key=r[P3@P4]"),
  31523. /* 31 */ "SeekRowid" OpHelp("intkey=r[P3]"),
  31524. /* 32 */ "NotExists" OpHelp("intkey=r[P3]"),
  31525. /* 33 */ "Last" OpHelp(""),
  31526. /* 34 */ "IfSmaller" OpHelp(""),
  31527. /* 35 */ "SorterSort" OpHelp(""),
  31528. /* 36 */ "Sort" OpHelp(""),
  31529. /* 37 */ "Rewind" OpHelp(""),
  31530. /* 38 */ "IdxLE" OpHelp("key=r[P3@P4]"),
  31531. /* 39 */ "IdxGT" OpHelp("key=r[P3@P4]"),
  31532. /* 40 */ "IdxLT" OpHelp("key=r[P3@P4]"),
  31533. /* 41 */ "IdxGE" OpHelp("key=r[P3@P4]"),
  31534. /* 42 */ "RowSetRead" OpHelp("r[P3]=rowset(P1)"),
  31535. /* 43 */ "Or" OpHelp("r[P3]=(r[P1] || r[P2])"),
  31536. /* 44 */ "And" OpHelp("r[P3]=(r[P1] && r[P2])"),
  31537. /* 45 */ "RowSetTest" OpHelp("if r[P3] in rowset(P1) goto P2"),
  31538. /* 46 */ "Program" OpHelp(""),
  31539. /* 47 */ "FkIfZero" OpHelp("if fkctr[P1]==0 goto P2"),
  31540. /* 48 */ "IfPos" OpHelp("if r[P1]>0 then r[P1]-=P3, goto P2"),
  31541. /* 49 */ "IfNotZero" OpHelp("if r[P1]!=0 then r[P1]--, goto P2"),
  31542. /* 50 */ "IsNull" OpHelp("if r[P1]==NULL goto P2"),
  31543. /* 51 */ "NotNull" OpHelp("if r[P1]!=NULL goto P2"),
  31544. /* 52 */ "Ne" OpHelp("IF r[P3]!=r[P1]"),
  31545. /* 53 */ "Eq" OpHelp("IF r[P3]==r[P1]"),
  31546. /* 54 */ "Gt" OpHelp("IF r[P3]>r[P1]"),
  31547. /* 55 */ "Le" OpHelp("IF r[P3]<=r[P1]"),
  31548. /* 56 */ "Lt" OpHelp("IF r[P3]<r[P1]"),
  31549. /* 57 */ "Ge" OpHelp("IF r[P3]>=r[P1]"),
  31550. /* 58 */ "ElseNotEq" OpHelp(""),
  31551. /* 59 */ "DecrJumpZero" OpHelp("if (--r[P1])==0 goto P2"),
  31552. /* 60 */ "IncrVacuum" OpHelp(""),
  31553. /* 61 */ "VNext" OpHelp(""),
  31554. /* 62 */ "Init" OpHelp("Start at P2"),
  31555. /* 63 */ "PureFunc" OpHelp("r[P3]=func(r[P2@NP])"),
  31556. /* 64 */ "Function" OpHelp("r[P3]=func(r[P2@NP])"),
  31557. /* 65 */ "Return" OpHelp(""),
  31558. /* 66 */ "EndCoroutine" OpHelp(""),
  31559. /* 67 */ "HaltIfNull" OpHelp("if r[P3]=null halt"),
  31560. /* 68 */ "Halt" OpHelp(""),
  31561. /* 69 */ "Integer" OpHelp("r[P2]=P1"),
  31562. /* 70 */ "Int64" OpHelp("r[P2]=P4"),
  31563. /* 71 */ "String" OpHelp("r[P2]='P4' (len=P1)"),
  31564. /* 72 */ "Null" OpHelp("r[P2..P3]=NULL"),
  31565. /* 73 */ "SoftNull" OpHelp("r[P1]=NULL"),
  31566. /* 74 */ "Blob" OpHelp("r[P2]=P4 (len=P1)"),
  31567. /* 75 */ "Variable" OpHelp("r[P2]=parameter(P1,P4)"),
  31568. /* 76 */ "Move" OpHelp("r[P2@P3]=r[P1@P3]"),
  31569. /* 77 */ "Copy" OpHelp("r[P2@P3+1]=r[P1@P3+1]"),
  31570. /* 78 */ "SCopy" OpHelp("r[P2]=r[P1]"),
  31571. /* 79 */ "IntCopy" OpHelp("r[P2]=r[P1]"),
  31572. /* 80 */ "ResultRow" OpHelp("output=r[P1@P2]"),
  31573. /* 81 */ "CollSeq" OpHelp(""),
  31574. /* 82 */ "AddImm" OpHelp("r[P1]=r[P1]+P2"),
  31575. /* 83 */ "RealAffinity" OpHelp(""),
  31576. /* 84 */ "Cast" OpHelp("affinity(r[P1])"),
  31577. /* 85 */ "Permutation" OpHelp(""),
  31578. /* 86 */ "Compare" OpHelp("r[P1@P3] <-> r[P2@P3]"),
  31579. /* 87 */ "IsTrue" OpHelp("r[P2] = coalesce(r[P1]==TRUE,P3) ^ P4"),
  31580. /* 88 */ "Offset" OpHelp("r[P3] = sqlite_offset(P1)"),
  31581. /* 89 */ "Column" OpHelp("r[P3]=PX"),
  31582. /* 90 */ "Affinity" OpHelp("affinity(r[P1@P2])"),
  31583. /* 91 */ "MakeRecord" OpHelp("r[P3]=mkrec(r[P1@P2])"),
  31584. /* 92 */ "Count" OpHelp("r[P2]=count()"),
  31585. /* 93 */ "ReadCookie" OpHelp(""),
  31586. /* 94 */ "SetCookie" OpHelp(""),
  31587. /* 95 */ "ReopenIdx" OpHelp("root=P2 iDb=P3"),
  31588. /* 96 */ "OpenRead" OpHelp("root=P2 iDb=P3"),
  31589. /* 97 */ "OpenWrite" OpHelp("root=P2 iDb=P3"),
  31590. /* 98 */ "OpenDup" OpHelp(""),
  31591. /* 99 */ "OpenAutoindex" OpHelp("nColumn=P2"),
  31592. /* 100 */ "OpenEphemeral" OpHelp("nColumn=P2"),
  31593. /* 101 */ "BitAnd" OpHelp("r[P3]=r[P1]&r[P2]"),
  31594. /* 102 */ "BitOr" OpHelp("r[P3]=r[P1]|r[P2]"),
  31595. /* 103 */ "ShiftLeft" OpHelp("r[P3]=r[P2]<<r[P1]"),
  31596. /* 104 */ "ShiftRight" OpHelp("r[P3]=r[P2]>>r[P1]"),
  31597. /* 105 */ "Add" OpHelp("r[P3]=r[P1]+r[P2]"),
  31598. /* 106 */ "Subtract" OpHelp("r[P3]=r[P2]-r[P1]"),
  31599. /* 107 */ "Multiply" OpHelp("r[P3]=r[P1]*r[P2]"),
  31600. /* 108 */ "Divide" OpHelp("r[P3]=r[P2]/r[P1]"),
  31601. /* 109 */ "Remainder" OpHelp("r[P3]=r[P2]%r[P1]"),
  31602. /* 110 */ "Concat" OpHelp("r[P3]=r[P2]+r[P1]"),
  31603. /* 111 */ "SorterOpen" OpHelp(""),
  31604. /* 112 */ "BitNot" OpHelp("r[P2]= ~r[P1]"),
  31605. /* 113 */ "SequenceTest" OpHelp("if( cursor[P1].ctr++ ) pc = P2"),
  31606. /* 114 */ "OpenPseudo" OpHelp("P3 columns in r[P2]"),
  31607. /* 115 */ "String8" OpHelp("r[P2]='P4'"),
  31608. /* 116 */ "Close" OpHelp(""),
  31609. /* 117 */ "ColumnsUsed" OpHelp(""),
  31610. /* 118 */ "SeekHit" OpHelp("seekHit=P2"),
  31611. /* 119 */ "Sequence" OpHelp("r[P2]=cursor[P1].ctr++"),
  31612. /* 120 */ "NewRowid" OpHelp("r[P2]=rowid"),
  31613. /* 121 */ "Insert" OpHelp("intkey=r[P3] data=r[P2]"),
  31614. /* 122 */ "Delete" OpHelp(""),
  31615. /* 123 */ "ResetCount" OpHelp(""),
  31616. /* 124 */ "SorterCompare" OpHelp("if key(P1)!=trim(r[P3],P4) goto P2"),
  31617. /* 125 */ "SorterData" OpHelp("r[P2]=data"),
  31618. /* 126 */ "RowData" OpHelp("r[P2]=data"),
  31619. /* 127 */ "Rowid" OpHelp("r[P2]=rowid"),
  31620. /* 128 */ "NullRow" OpHelp(""),
  31621. /* 129 */ "SeekEnd" OpHelp(""),
  31622. /* 130 */ "IdxInsert" OpHelp("key=r[P2]"),
  31623. /* 131 */ "SorterInsert" OpHelp("key=r[P2]"),
  31624. /* 132 */ "IdxDelete" OpHelp("key=r[P2@P3]"),
  31625. /* 133 */ "DeferredSeek" OpHelp("Move P3 to P1.rowid if needed"),
  31626. /* 134 */ "IdxRowid" OpHelp("r[P2]=rowid"),
  31627. /* 135 */ "FinishSeek" OpHelp(""),
  31628. /* 136 */ "Destroy" OpHelp(""),
  31629. /* 137 */ "Clear" OpHelp(""),
  31630. /* 138 */ "ResetSorter" OpHelp(""),
  31631. /* 139 */ "CreateBtree" OpHelp("r[P2]=root iDb=P1 flags=P3"),
  31632. /* 140 */ "SqlExec" OpHelp(""),
  31633. /* 141 */ "ParseSchema" OpHelp(""),
  31634. /* 142 */ "LoadAnalysis" OpHelp(""),
  31635. /* 143 */ "DropTable" OpHelp(""),
  31636. /* 144 */ "DropIndex" OpHelp(""),
  31637. /* 145 */ "DropTrigger" OpHelp(""),
  31638. /* 146 */ "IntegrityCk" OpHelp(""),
  31639. /* 147 */ "RowSetAdd" OpHelp("rowset(P1)=r[P2]"),
  31640. /* 148 */ "Param" OpHelp(""),
  31641. /* 149 */ "FkCounter" OpHelp("fkctr[P1]+=P2"),
  31642. /* 150 */ "Real" OpHelp("r[P2]=P4"),
  31643. /* 151 */ "MemMax" OpHelp("r[P1]=max(r[P1],r[P2])"),
  31644. /* 152 */ "OffsetLimit" OpHelp("if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1)"),
  31645. /* 153 */ "AggInverse" OpHelp("accum=r[P3] inverse(r[P2@P5])"),
  31646. /* 154 */ "AggStep" OpHelp("accum=r[P3] step(r[P2@P5])"),
  31647. /* 155 */ "AggStep1" OpHelp("accum=r[P3] step(r[P2@P5])"),
  31648. /* 156 */ "AggValue" OpHelp("r[P3]=value N=P2"),
  31649. /* 157 */ "AggFinal" OpHelp("accum=r[P1] N=P2"),
  31650. /* 158 */ "Expire" OpHelp(""),
  31651. /* 159 */ "CursorLock" OpHelp(""),
  31652. /* 160 */ "CursorUnlock" OpHelp(""),
  31653. /* 161 */ "TableLock" OpHelp("iDb=P1 root=P2 write=P3"),
  31654. /* 162 */ "VBegin" OpHelp(""),
  31655. /* 163 */ "VCreate" OpHelp(""),
  31656. /* 164 */ "VDestroy" OpHelp(""),
  31657. /* 165 */ "VOpen" OpHelp(""),
  31658. /* 166 */ "VColumn" OpHelp("r[P3]=vcolumn(P2)"),
  31659. /* 167 */ "VRename" OpHelp(""),
  31660. /* 168 */ "Pagecount" OpHelp(""),
  31661. /* 169 */ "MaxPgcnt" OpHelp(""),
  31662. /* 170 */ "Trace" OpHelp(""),
  31663. /* 171 */ "CursorHint" OpHelp(""),
  31664. /* 172 */ "ReleaseReg" OpHelp("release r[P1@P2] mask P3"),
  31665. /* 173 */ "Noop" OpHelp(""),
  31666. /* 174 */ "Explain" OpHelp(""),
  31667. /* 175 */ "Abortable" OpHelp(""),
  31668. };
  31669. return azName[i];
  31670. }
  31671. #endif
  31672. /************** End of opcodes.c *********************************************/
  31673. /************** Begin file os_unix.c *****************************************/
  31674. /*
  31675. ** 2004 May 22
  31676. **
  31677. ** The author disclaims copyright to this source code. In place of
  31678. ** a legal notice, here is a blessing:
  31679. **
  31680. ** May you do good and not evil.
  31681. ** May you find forgiveness for yourself and forgive others.
  31682. ** May you share freely, never taking more than you give.
  31683. **
  31684. ******************************************************************************
  31685. **
  31686. ** This file contains the VFS implementation for unix-like operating systems
  31687. ** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
  31688. **
  31689. ** There are actually several different VFS implementations in this file.
  31690. ** The differences are in the way that file locking is done. The default
  31691. ** implementation uses Posix Advisory Locks. Alternative implementations
  31692. ** use flock(), dot-files, various proprietary locking schemas, or simply
  31693. ** skip locking all together.
  31694. **
  31695. ** This source file is organized into divisions where the logic for various
  31696. ** subfunctions is contained within the appropriate division. PLEASE
  31697. ** KEEP THE STRUCTURE OF THIS FILE INTACT. New code should be placed
  31698. ** in the correct division and should be clearly labeled.
  31699. **
  31700. ** The layout of divisions is as follows:
  31701. **
  31702. ** * General-purpose declarations and utility functions.
  31703. ** * Unique file ID logic used by VxWorks.
  31704. ** * Various locking primitive implementations (all except proxy locking):
  31705. ** + for Posix Advisory Locks
  31706. ** + for no-op locks
  31707. ** + for dot-file locks
  31708. ** + for flock() locking
  31709. ** + for named semaphore locks (VxWorks only)
  31710. ** + for AFP filesystem locks (MacOSX only)
  31711. ** * sqlite3_file methods not associated with locking.
  31712. ** * Definitions of sqlite3_io_methods objects for all locking
  31713. ** methods plus "finder" functions for each locking method.
  31714. ** * sqlite3_vfs method implementations.
  31715. ** * Locking primitives for the proxy uber-locking-method. (MacOSX only)
  31716. ** * Definitions of sqlite3_vfs objects for all locking methods
  31717. ** plus implementations of sqlite3_os_init() and sqlite3_os_end().
  31718. */
  31719. /* #include "sqliteInt.h" */
  31720. #if SQLITE_OS_UNIX /* This file is used on unix only */
  31721. /*
  31722. ** There are various methods for file locking used for concurrency
  31723. ** control:
  31724. **
  31725. ** 1. POSIX locking (the default),
  31726. ** 2. No locking,
  31727. ** 3. Dot-file locking,
  31728. ** 4. flock() locking,
  31729. ** 5. AFP locking (OSX only),
  31730. ** 6. Named POSIX semaphores (VXWorks only),
  31731. ** 7. proxy locking. (OSX only)
  31732. **
  31733. ** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
  31734. ** is defined to 1. The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
  31735. ** selection of the appropriate locking style based on the filesystem
  31736. ** where the database is located.
  31737. */
  31738. #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
  31739. # if defined(__APPLE__)
  31740. # define SQLITE_ENABLE_LOCKING_STYLE 1
  31741. # else
  31742. # define SQLITE_ENABLE_LOCKING_STYLE 0
  31743. # endif
  31744. #endif
  31745. /* Use pread() and pwrite() if they are available */
  31746. #if defined(__APPLE__)
  31747. # define HAVE_PREAD 1
  31748. # define HAVE_PWRITE 1
  31749. #endif
  31750. #if defined(HAVE_PREAD64) && defined(HAVE_PWRITE64)
  31751. # undef USE_PREAD
  31752. # define USE_PREAD64 1
  31753. #elif defined(HAVE_PREAD) && defined(HAVE_PWRITE)
  31754. # undef USE_PREAD64
  31755. # define USE_PREAD 1
  31756. #endif
  31757. /*
  31758. ** standard include files.
  31759. */
  31760. #include <sys/types.h>
  31761. #include <sys/stat.h>
  31762. #include <fcntl.h>
  31763. #include <sys/ioctl.h>
  31764. #include <unistd.h>
  31765. /* #include <time.h> */
  31766. #include <sys/time.h>
  31767. #include <errno.h>
  31768. #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
  31769. # include <sys/mman.h>
  31770. #endif
  31771. #if SQLITE_ENABLE_LOCKING_STYLE
  31772. /* # include <sys/ioctl.h> */
  31773. # include <sys/file.h>
  31774. # include <sys/param.h>
  31775. #endif /* SQLITE_ENABLE_LOCKING_STYLE */
  31776. /*
  31777. ** Try to determine if gethostuuid() is available based on standard
  31778. ** macros. This might sometimes compute the wrong value for some
  31779. ** obscure platforms. For those cases, simply compile with one of
  31780. ** the following:
  31781. **
  31782. ** -DHAVE_GETHOSTUUID=0
  31783. ** -DHAVE_GETHOSTUUID=1
  31784. **
  31785. ** None if this matters except when building on Apple products with
  31786. ** -DSQLITE_ENABLE_LOCKING_STYLE.
  31787. */
  31788. #ifndef HAVE_GETHOSTUUID
  31789. # define HAVE_GETHOSTUUID 0
  31790. # if defined(__APPLE__) && ((__MAC_OS_X_VERSION_MIN_REQUIRED > 1050) || \
  31791. (__IPHONE_OS_VERSION_MIN_REQUIRED > 2000))
  31792. # if (!defined(TARGET_OS_EMBEDDED) || (TARGET_OS_EMBEDDED==0)) \
  31793. && (!defined(TARGET_IPHONE_SIMULATOR) || (TARGET_IPHONE_SIMULATOR==0))
  31794. # undef HAVE_GETHOSTUUID
  31795. # define HAVE_GETHOSTUUID 1
  31796. # else
  31797. # warning "gethostuuid() is disabled."
  31798. # endif
  31799. # endif
  31800. #endif
  31801. #if OS_VXWORKS
  31802. /* # include <sys/ioctl.h> */
  31803. # include <semaphore.h>
  31804. # include <limits.h>
  31805. #endif /* OS_VXWORKS */
  31806. #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
  31807. # include <sys/mount.h>
  31808. #endif
  31809. #ifdef HAVE_UTIME
  31810. # include <utime.h>
  31811. #endif
  31812. /*
  31813. ** Allowed values of unixFile.fsFlags
  31814. */
  31815. #define SQLITE_FSFLAGS_IS_MSDOS 0x1
  31816. /*
  31817. ** If we are to be thread-safe, include the pthreads header.
  31818. */
  31819. #if SQLITE_THREADSAFE
  31820. /* # include <pthread.h> */
  31821. #endif
  31822. /*
  31823. ** Default permissions when creating a new file
  31824. */
  31825. #ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
  31826. # define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
  31827. #endif
  31828. /*
  31829. ** Default permissions when creating auto proxy dir
  31830. */
  31831. #ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
  31832. # define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
  31833. #endif
  31834. /*
  31835. ** Maximum supported path-length.
  31836. */
  31837. #define MAX_PATHNAME 512
  31838. /*
  31839. ** Maximum supported symbolic links
  31840. */
  31841. #define SQLITE_MAX_SYMLINKS 100
  31842. /* Always cast the getpid() return type for compatibility with
  31843. ** kernel modules in VxWorks. */
  31844. #define osGetpid(X) (pid_t)getpid()
  31845. /*
  31846. ** Only set the lastErrno if the error code is a real error and not
  31847. ** a normal expected return code of SQLITE_BUSY or SQLITE_OK
  31848. */
  31849. #define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
  31850. /* Forward references */
  31851. typedef struct unixShm unixShm; /* Connection shared memory */
  31852. typedef struct unixShmNode unixShmNode; /* Shared memory instance */
  31853. typedef struct unixInodeInfo unixInodeInfo; /* An i-node */
  31854. typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */
  31855. /*
  31856. ** Sometimes, after a file handle is closed by SQLite, the file descriptor
  31857. ** cannot be closed immediately. In these cases, instances of the following
  31858. ** structure are used to store the file descriptor while waiting for an
  31859. ** opportunity to either close or reuse it.
  31860. */
  31861. struct UnixUnusedFd {
  31862. int fd; /* File descriptor to close */
  31863. int flags; /* Flags this file descriptor was opened with */
  31864. UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
  31865. };
  31866. /*
  31867. ** The unixFile structure is subclass of sqlite3_file specific to the unix
  31868. ** VFS implementations.
  31869. */
  31870. typedef struct unixFile unixFile;
  31871. struct unixFile {
  31872. sqlite3_io_methods const *pMethod; /* Always the first entry */
  31873. sqlite3_vfs *pVfs; /* The VFS that created this unixFile */
  31874. unixInodeInfo *pInode; /* Info about locks on this inode */
  31875. int h; /* The file descriptor */
  31876. unsigned char eFileLock; /* The type of lock held on this fd */
  31877. unsigned short int ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */
  31878. int lastErrno; /* The unix errno from last I/O error */
  31879. void *lockingContext; /* Locking style specific state */
  31880. UnixUnusedFd *pPreallocatedUnused; /* Pre-allocated UnixUnusedFd */
  31881. const char *zPath; /* Name of the file */
  31882. unixShm *pShm; /* Shared memory segment information */
  31883. int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
  31884. #if SQLITE_MAX_MMAP_SIZE>0
  31885. int nFetchOut; /* Number of outstanding xFetch refs */
  31886. sqlite3_int64 mmapSize; /* Usable size of mapping at pMapRegion */
  31887. sqlite3_int64 mmapSizeActual; /* Actual size of mapping at pMapRegion */
  31888. sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */
  31889. void *pMapRegion; /* Memory mapped region */
  31890. #endif
  31891. int sectorSize; /* Device sector size */
  31892. int deviceCharacteristics; /* Precomputed device characteristics */
  31893. #if SQLITE_ENABLE_LOCKING_STYLE
  31894. int openFlags; /* The flags specified at open() */
  31895. #endif
  31896. #if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
  31897. unsigned fsFlags; /* cached details from statfs() */
  31898. #endif
  31899. #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
  31900. unsigned iBusyTimeout; /* Wait this many millisec on locks */
  31901. #endif
  31902. #if OS_VXWORKS
  31903. struct vxworksFileId *pId; /* Unique file ID */
  31904. #endif
  31905. #ifdef SQLITE_DEBUG
  31906. /* The next group of variables are used to track whether or not the
  31907. ** transaction counter in bytes 24-27 of database files are updated
  31908. ** whenever any part of the database changes. An assertion fault will
  31909. ** occur if a file is updated without also updating the transaction
  31910. ** counter. This test is made to avoid new problems similar to the
  31911. ** one described by ticket #3584.
  31912. */
  31913. unsigned char transCntrChng; /* True if the transaction counter changed */
  31914. unsigned char dbUpdate; /* True if any part of database file changed */
  31915. unsigned char inNormalWrite; /* True if in a normal write operation */
  31916. #endif
  31917. #ifdef SQLITE_TEST
  31918. /* In test mode, increase the size of this structure a bit so that
  31919. ** it is larger than the struct CrashFile defined in test6.c.
  31920. */
  31921. char aPadding[32];
  31922. #endif
  31923. };
  31924. /* This variable holds the process id (pid) from when the xRandomness()
  31925. ** method was called. If xOpen() is called from a different process id,
  31926. ** indicating that a fork() has occurred, the PRNG will be reset.
  31927. */
  31928. static pid_t randomnessPid = 0;
  31929. /*
  31930. ** Allowed values for the unixFile.ctrlFlags bitmask:
  31931. */
  31932. #define UNIXFILE_EXCL 0x01 /* Connections from one process only */
  31933. #define UNIXFILE_RDONLY 0x02 /* Connection is read only */
  31934. #define UNIXFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
  31935. #ifndef SQLITE_DISABLE_DIRSYNC
  31936. # define UNIXFILE_DIRSYNC 0x08 /* Directory sync needed */
  31937. #else
  31938. # define UNIXFILE_DIRSYNC 0x00
  31939. #endif
  31940. #define UNIXFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
  31941. #define UNIXFILE_DELETE 0x20 /* Delete on close */
  31942. #define UNIXFILE_URI 0x40 /* Filename might have query parameters */
  31943. #define UNIXFILE_NOLOCK 0x80 /* Do no file locking */
  31944. /*
  31945. ** Include code that is common to all os_*.c files
  31946. */
  31947. /************** Include os_common.h in the middle of os_unix.c ***************/
  31948. /************** Begin file os_common.h ***************************************/
  31949. /*
  31950. ** 2004 May 22
  31951. **
  31952. ** The author disclaims copyright to this source code. In place of
  31953. ** a legal notice, here is a blessing:
  31954. **
  31955. ** May you do good and not evil.
  31956. ** May you find forgiveness for yourself and forgive others.
  31957. ** May you share freely, never taking more than you give.
  31958. **
  31959. ******************************************************************************
  31960. **
  31961. ** This file contains macros and a little bit of code that is common to
  31962. ** all of the platform-specific files (os_*.c) and is #included into those
  31963. ** files.
  31964. **
  31965. ** This file should be #included by the os_*.c files only. It is not a
  31966. ** general purpose header file.
  31967. */
  31968. #ifndef _OS_COMMON_H_
  31969. #define _OS_COMMON_H_
  31970. /*
  31971. ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
  31972. ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
  31973. ** switch. The following code should catch this problem at compile-time.
  31974. */
  31975. #ifdef MEMORY_DEBUG
  31976. # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
  31977. #endif
  31978. /*
  31979. ** Macros for performance tracing. Normally turned off. Only works
  31980. ** on i486 hardware.
  31981. */
  31982. #ifdef SQLITE_PERFORMANCE_TRACE
  31983. /*
  31984. ** hwtime.h contains inline assembler code for implementing
  31985. ** high-performance timing routines.
  31986. */
  31987. /************** Include hwtime.h in the middle of os_common.h ****************/
  31988. /************** Begin file hwtime.h ******************************************/
  31989. /*
  31990. ** 2008 May 27
  31991. **
  31992. ** The author disclaims copyright to this source code. In place of
  31993. ** a legal notice, here is a blessing:
  31994. **
  31995. ** May you do good and not evil.
  31996. ** May you find forgiveness for yourself and forgive others.
  31997. ** May you share freely, never taking more than you give.
  31998. **
  31999. ******************************************************************************
  32000. **
  32001. ** This file contains inline asm code for retrieving "high-performance"
  32002. ** counters for x86 and x86_64 class CPUs.
  32003. */
  32004. #ifndef SQLITE_HWTIME_H
  32005. #define SQLITE_HWTIME_H
  32006. /*
  32007. ** The following routine only works on pentium-class (or newer) processors.
  32008. ** It uses the RDTSC opcode to read the cycle count value out of the
  32009. ** processor and returns that value. This can be used for high-res
  32010. ** profiling.
  32011. */
  32012. #if !defined(__STRICT_ANSI__) && \
  32013. (defined(__GNUC__) || defined(_MSC_VER)) && \
  32014. (defined(i386) || defined(__i386__) || defined(_M_IX86))
  32015. #if defined(__GNUC__)
  32016. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  32017. unsigned int lo, hi;
  32018. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  32019. return (sqlite_uint64)hi << 32 | lo;
  32020. }
  32021. #elif defined(_MSC_VER)
  32022. __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
  32023. __asm {
  32024. rdtsc
  32025. ret ; return value at EDX:EAX
  32026. }
  32027. }
  32028. #endif
  32029. #elif !defined(__STRICT_ANSI__) && (defined(__GNUC__) && defined(__x86_64__))
  32030. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  32031. unsigned long val;
  32032. __asm__ __volatile__ ("rdtsc" : "=A" (val));
  32033. return val;
  32034. }
  32035. #elif !defined(__STRICT_ANSI__) && (defined(__GNUC__) && defined(__ppc__))
  32036. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  32037. unsigned long long retval;
  32038. unsigned long junk;
  32039. __asm__ __volatile__ ("\n\
  32040. 1: mftbu %1\n\
  32041. mftb %L0\n\
  32042. mftbu %0\n\
  32043. cmpw %0,%1\n\
  32044. bne 1b"
  32045. : "=r" (retval), "=r" (junk));
  32046. return retval;
  32047. }
  32048. #else
  32049. /*
  32050. ** asm() is needed for hardware timing support. Without asm(),
  32051. ** disable the sqlite3Hwtime() routine.
  32052. **
  32053. ** sqlite3Hwtime() is only used for some obscure debugging
  32054. ** and analysis configurations, not in any deliverable, so this
  32055. ** should not be a great loss.
  32056. */
  32057. SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
  32058. #endif
  32059. #endif /* !defined(SQLITE_HWTIME_H) */
  32060. /************** End of hwtime.h **********************************************/
  32061. /************** Continuing where we left off in os_common.h ******************/
  32062. static sqlite_uint64 g_start;
  32063. static sqlite_uint64 g_elapsed;
  32064. #define TIMER_START g_start=sqlite3Hwtime()
  32065. #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
  32066. #define TIMER_ELAPSED g_elapsed
  32067. #else
  32068. #define TIMER_START
  32069. #define TIMER_END
  32070. #define TIMER_ELAPSED ((sqlite_uint64)0)
  32071. #endif
  32072. /*
  32073. ** If we compile with the SQLITE_TEST macro set, then the following block
  32074. ** of code will give us the ability to simulate a disk I/O error. This
  32075. ** is used for testing the I/O recovery logic.
  32076. */
  32077. #if defined(SQLITE_TEST)
  32078. SQLITE_API extern int sqlite3_io_error_hit;
  32079. SQLITE_API extern int sqlite3_io_error_hardhit;
  32080. SQLITE_API extern int sqlite3_io_error_pending;
  32081. SQLITE_API extern int sqlite3_io_error_persist;
  32082. SQLITE_API extern int sqlite3_io_error_benign;
  32083. SQLITE_API extern int sqlite3_diskfull_pending;
  32084. SQLITE_API extern int sqlite3_diskfull;
  32085. #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
  32086. #define SimulateIOError(CODE) \
  32087. if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
  32088. || sqlite3_io_error_pending-- == 1 ) \
  32089. { local_ioerr(); CODE; }
  32090. static void local_ioerr(){
  32091. IOTRACE(("IOERR\n"));
  32092. sqlite3_io_error_hit++;
  32093. if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
  32094. }
  32095. #define SimulateDiskfullError(CODE) \
  32096. if( sqlite3_diskfull_pending ){ \
  32097. if( sqlite3_diskfull_pending == 1 ){ \
  32098. local_ioerr(); \
  32099. sqlite3_diskfull = 1; \
  32100. sqlite3_io_error_hit = 1; \
  32101. CODE; \
  32102. }else{ \
  32103. sqlite3_diskfull_pending--; \
  32104. } \
  32105. }
  32106. #else
  32107. #define SimulateIOErrorBenign(X)
  32108. #define SimulateIOError(A)
  32109. #define SimulateDiskfullError(A)
  32110. #endif /* defined(SQLITE_TEST) */
  32111. /*
  32112. ** When testing, keep a count of the number of open files.
  32113. */
  32114. #if defined(SQLITE_TEST)
  32115. SQLITE_API extern int sqlite3_open_file_count;
  32116. #define OpenCounter(X) sqlite3_open_file_count+=(X)
  32117. #else
  32118. #define OpenCounter(X)
  32119. #endif /* defined(SQLITE_TEST) */
  32120. #endif /* !defined(_OS_COMMON_H_) */
  32121. /************** End of os_common.h *******************************************/
  32122. /************** Continuing where we left off in os_unix.c ********************/
  32123. /*
  32124. ** Define various macros that are missing from some systems.
  32125. */
  32126. #ifndef O_LARGEFILE
  32127. # define O_LARGEFILE 0
  32128. #endif
  32129. #ifdef SQLITE_DISABLE_LFS
  32130. # undef O_LARGEFILE
  32131. # define O_LARGEFILE 0
  32132. #endif
  32133. #ifndef O_NOFOLLOW
  32134. # define O_NOFOLLOW 0
  32135. #endif
  32136. #ifndef O_BINARY
  32137. # define O_BINARY 0
  32138. #endif
  32139. /*
  32140. ** The threadid macro resolves to the thread-id or to 0. Used for
  32141. ** testing and debugging only.
  32142. */
  32143. #if SQLITE_THREADSAFE
  32144. #define threadid pthread_self()
  32145. #else
  32146. #define threadid 0
  32147. #endif
  32148. /*
  32149. ** HAVE_MREMAP defaults to true on Linux and false everywhere else.
  32150. */
  32151. #if !defined(HAVE_MREMAP)
  32152. # if defined(__linux__) && defined(_GNU_SOURCE)
  32153. # define HAVE_MREMAP 1
  32154. # else
  32155. # define HAVE_MREMAP 0
  32156. # endif
  32157. #endif
  32158. /*
  32159. ** Explicitly call the 64-bit version of lseek() on Android. Otherwise, lseek()
  32160. ** is the 32-bit version, even if _FILE_OFFSET_BITS=64 is defined.
  32161. */
  32162. #ifdef __ANDROID__
  32163. # define lseek lseek64
  32164. #endif
  32165. #ifdef __linux__
  32166. /*
  32167. ** Linux-specific IOCTL magic numbers used for controlling F2FS
  32168. */
  32169. #define F2FS_IOCTL_MAGIC 0xf5
  32170. #define F2FS_IOC_START_ATOMIC_WRITE _IO(F2FS_IOCTL_MAGIC, 1)
  32171. #define F2FS_IOC_COMMIT_ATOMIC_WRITE _IO(F2FS_IOCTL_MAGIC, 2)
  32172. #define F2FS_IOC_START_VOLATILE_WRITE _IO(F2FS_IOCTL_MAGIC, 3)
  32173. #define F2FS_IOC_ABORT_VOLATILE_WRITE _IO(F2FS_IOCTL_MAGIC, 5)
  32174. #define F2FS_IOC_GET_FEATURES _IOR(F2FS_IOCTL_MAGIC, 12, u32)
  32175. #define F2FS_FEATURE_ATOMIC_WRITE 0x0004
  32176. #endif /* __linux__ */
  32177. /*
  32178. ** Different Unix systems declare open() in different ways. Same use
  32179. ** open(const char*,int,mode_t). Others use open(const char*,int,...).
  32180. ** The difference is important when using a pointer to the function.
  32181. **
  32182. ** The safest way to deal with the problem is to always use this wrapper
  32183. ** which always has the same well-defined interface.
  32184. */
  32185. static int posixOpen(const char *zFile, int flags, int mode){
  32186. return open(zFile, flags, mode);
  32187. }
  32188. /* Forward reference */
  32189. static int openDirectory(const char*, int*);
  32190. static int unixGetpagesize(void);
  32191. /*
  32192. ** Many system calls are accessed through pointer-to-functions so that
  32193. ** they may be overridden at runtime to facilitate fault injection during
  32194. ** testing and sandboxing. The following array holds the names and pointers
  32195. ** to all overrideable system calls.
  32196. */
  32197. static struct unix_syscall {
  32198. const char *zName; /* Name of the system call */
  32199. sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
  32200. sqlite3_syscall_ptr pDefault; /* Default value */
  32201. } aSyscall[] = {
  32202. { "open", (sqlite3_syscall_ptr)posixOpen, 0 },
  32203. #define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
  32204. { "close", (sqlite3_syscall_ptr)close, 0 },
  32205. #define osClose ((int(*)(int))aSyscall[1].pCurrent)
  32206. { "access", (sqlite3_syscall_ptr)access, 0 },
  32207. #define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
  32208. { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
  32209. #define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
  32210. { "stat", (sqlite3_syscall_ptr)stat, 0 },
  32211. #define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
  32212. /*
  32213. ** The DJGPP compiler environment looks mostly like Unix, but it
  32214. ** lacks the fcntl() system call. So redefine fcntl() to be something
  32215. ** that always succeeds. This means that locking does not occur under
  32216. ** DJGPP. But it is DOS - what did you expect?
  32217. */
  32218. #ifdef __DJGPP__
  32219. { "fstat", 0, 0 },
  32220. #define osFstat(a,b,c) 0
  32221. #else
  32222. { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
  32223. #define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
  32224. #endif
  32225. { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
  32226. #define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
  32227. { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
  32228. #define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
  32229. { "read", (sqlite3_syscall_ptr)read, 0 },
  32230. #define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
  32231. #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
  32232. { "pread", (sqlite3_syscall_ptr)pread, 0 },
  32233. #else
  32234. { "pread", (sqlite3_syscall_ptr)0, 0 },
  32235. #endif
  32236. #define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
  32237. #if defined(USE_PREAD64)
  32238. { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
  32239. #else
  32240. { "pread64", (sqlite3_syscall_ptr)0, 0 },
  32241. #endif
  32242. #define osPread64 ((ssize_t(*)(int,void*,size_t,off64_t))aSyscall[10].pCurrent)
  32243. { "write", (sqlite3_syscall_ptr)write, 0 },
  32244. #define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
  32245. #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
  32246. { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
  32247. #else
  32248. { "pwrite", (sqlite3_syscall_ptr)0, 0 },
  32249. #endif
  32250. #define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
  32251. aSyscall[12].pCurrent)
  32252. #if defined(USE_PREAD64)
  32253. { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
  32254. #else
  32255. { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
  32256. #endif
  32257. #define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off64_t))\
  32258. aSyscall[13].pCurrent)
  32259. { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
  32260. #define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
  32261. #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
  32262. { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
  32263. #else
  32264. { "fallocate", (sqlite3_syscall_ptr)0, 0 },
  32265. #endif
  32266. #define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
  32267. { "unlink", (sqlite3_syscall_ptr)unlink, 0 },
  32268. #define osUnlink ((int(*)(const char*))aSyscall[16].pCurrent)
  32269. { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 },
  32270. #define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
  32271. { "mkdir", (sqlite3_syscall_ptr)mkdir, 0 },
  32272. #define osMkdir ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
  32273. { "rmdir", (sqlite3_syscall_ptr)rmdir, 0 },
  32274. #define osRmdir ((int(*)(const char*))aSyscall[19].pCurrent)
  32275. #if defined(HAVE_FCHOWN)
  32276. { "fchown", (sqlite3_syscall_ptr)fchown, 0 },
  32277. #else
  32278. { "fchown", (sqlite3_syscall_ptr)0, 0 },
  32279. #endif
  32280. #define osFchown ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
  32281. #if defined(HAVE_FCHOWN)
  32282. { "geteuid", (sqlite3_syscall_ptr)geteuid, 0 },
  32283. #else
  32284. { "geteuid", (sqlite3_syscall_ptr)0, 0 },
  32285. #endif
  32286. #define osGeteuid ((uid_t(*)(void))aSyscall[21].pCurrent)
  32287. #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
  32288. { "mmap", (sqlite3_syscall_ptr)mmap, 0 },
  32289. #else
  32290. { "mmap", (sqlite3_syscall_ptr)0, 0 },
  32291. #endif
  32292. #define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[22].pCurrent)
  32293. #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
  32294. { "munmap", (sqlite3_syscall_ptr)munmap, 0 },
  32295. #else
  32296. { "munmap", (sqlite3_syscall_ptr)0, 0 },
  32297. #endif
  32298. #define osMunmap ((int(*)(void*,size_t))aSyscall[23].pCurrent)
  32299. #if HAVE_MREMAP && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
  32300. { "mremap", (sqlite3_syscall_ptr)mremap, 0 },
  32301. #else
  32302. { "mremap", (sqlite3_syscall_ptr)0, 0 },
  32303. #endif
  32304. #define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[24].pCurrent)
  32305. #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
  32306. { "getpagesize", (sqlite3_syscall_ptr)unixGetpagesize, 0 },
  32307. #else
  32308. { "getpagesize", (sqlite3_syscall_ptr)0, 0 },
  32309. #endif
  32310. #define osGetpagesize ((int(*)(void))aSyscall[25].pCurrent)
  32311. #if defined(HAVE_READLINK)
  32312. { "readlink", (sqlite3_syscall_ptr)readlink, 0 },
  32313. #else
  32314. { "readlink", (sqlite3_syscall_ptr)0, 0 },
  32315. #endif
  32316. #define osReadlink ((ssize_t(*)(const char*,char*,size_t))aSyscall[26].pCurrent)
  32317. #if defined(HAVE_LSTAT)
  32318. { "lstat", (sqlite3_syscall_ptr)lstat, 0 },
  32319. #else
  32320. { "lstat", (sqlite3_syscall_ptr)0, 0 },
  32321. #endif
  32322. #define osLstat ((int(*)(const char*,struct stat*))aSyscall[27].pCurrent)
  32323. #if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
  32324. # ifdef __ANDROID__
  32325. { "ioctl", (sqlite3_syscall_ptr)(int(*)(int, int, ...))ioctl, 0 },
  32326. #define osIoctl ((int(*)(int,int,...))aSyscall[28].pCurrent)
  32327. # else
  32328. { "ioctl", (sqlite3_syscall_ptr)ioctl, 0 },
  32329. #define osIoctl ((int(*)(int,unsigned long,...))aSyscall[28].pCurrent)
  32330. # endif
  32331. #else
  32332. { "ioctl", (sqlite3_syscall_ptr)0, 0 },
  32333. #endif
  32334. }; /* End of the overrideable system calls */
  32335. /*
  32336. ** On some systems, calls to fchown() will trigger a message in a security
  32337. ** log if they come from non-root processes. So avoid calling fchown() if
  32338. ** we are not running as root.
  32339. */
  32340. static int robustFchown(int fd, uid_t uid, gid_t gid){
  32341. #if defined(HAVE_FCHOWN)
  32342. return osGeteuid() ? 0 : osFchown(fd,uid,gid);
  32343. #else
  32344. return 0;
  32345. #endif
  32346. }
  32347. /*
  32348. ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
  32349. ** "unix" VFSes. Return SQLITE_OK opon successfully updating the
  32350. ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
  32351. ** system call named zName.
  32352. */
  32353. static int unixSetSystemCall(
  32354. sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
  32355. const char *zName, /* Name of system call to override */
  32356. sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
  32357. ){
  32358. unsigned int i;
  32359. int rc = SQLITE_NOTFOUND;
  32360. UNUSED_PARAMETER(pNotUsed);
  32361. if( zName==0 ){
  32362. /* If no zName is given, restore all system calls to their default
  32363. ** settings and return NULL
  32364. */
  32365. rc = SQLITE_OK;
  32366. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  32367. if( aSyscall[i].pDefault ){
  32368. aSyscall[i].pCurrent = aSyscall[i].pDefault;
  32369. }
  32370. }
  32371. }else{
  32372. /* If zName is specified, operate on only the one system call
  32373. ** specified.
  32374. */
  32375. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  32376. if( strcmp(zName, aSyscall[i].zName)==0 ){
  32377. if( aSyscall[i].pDefault==0 ){
  32378. aSyscall[i].pDefault = aSyscall[i].pCurrent;
  32379. }
  32380. rc = SQLITE_OK;
  32381. if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
  32382. aSyscall[i].pCurrent = pNewFunc;
  32383. break;
  32384. }
  32385. }
  32386. }
  32387. return rc;
  32388. }
  32389. /*
  32390. ** Return the value of a system call. Return NULL if zName is not a
  32391. ** recognized system call name. NULL is also returned if the system call
  32392. ** is currently undefined.
  32393. */
  32394. static sqlite3_syscall_ptr unixGetSystemCall(
  32395. sqlite3_vfs *pNotUsed,
  32396. const char *zName
  32397. ){
  32398. unsigned int i;
  32399. UNUSED_PARAMETER(pNotUsed);
  32400. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  32401. if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
  32402. }
  32403. return 0;
  32404. }
  32405. /*
  32406. ** Return the name of the first system call after zName. If zName==NULL
  32407. ** then return the name of the first system call. Return NULL if zName
  32408. ** is the last system call or if zName is not the name of a valid
  32409. ** system call.
  32410. */
  32411. static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
  32412. int i = -1;
  32413. UNUSED_PARAMETER(p);
  32414. if( zName ){
  32415. for(i=0; i<ArraySize(aSyscall)-1; i++){
  32416. if( strcmp(zName, aSyscall[i].zName)==0 ) break;
  32417. }
  32418. }
  32419. for(i++; i<ArraySize(aSyscall); i++){
  32420. if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
  32421. }
  32422. return 0;
  32423. }
  32424. /*
  32425. ** Do not accept any file descriptor less than this value, in order to avoid
  32426. ** opening database file using file descriptors that are commonly used for
  32427. ** standard input, output, and error.
  32428. */
  32429. #ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR
  32430. # define SQLITE_MINIMUM_FILE_DESCRIPTOR 3
  32431. #endif
  32432. /*
  32433. ** Invoke open(). Do so multiple times, until it either succeeds or
  32434. ** fails for some reason other than EINTR.
  32435. **
  32436. ** If the file creation mode "m" is 0 then set it to the default for
  32437. ** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
  32438. ** 0644) as modified by the system umask. If m is not 0, then
  32439. ** make the file creation mode be exactly m ignoring the umask.
  32440. **
  32441. ** The m parameter will be non-zero only when creating -wal, -journal,
  32442. ** and -shm files. We want those files to have *exactly* the same
  32443. ** permissions as their original database, unadulterated by the umask.
  32444. ** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
  32445. ** transaction crashes and leaves behind hot journals, then any
  32446. ** process that is able to write to the database will also be able to
  32447. ** recover the hot journals.
  32448. */
  32449. static int robust_open(const char *z, int f, mode_t m){
  32450. int fd;
  32451. mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
  32452. while(1){
  32453. #if defined(O_CLOEXEC)
  32454. fd = osOpen(z,f|O_CLOEXEC,m2);
  32455. #else
  32456. fd = osOpen(z,f,m2);
  32457. #endif
  32458. if( fd<0 ){
  32459. if( errno==EINTR ) continue;
  32460. break;
  32461. }
  32462. if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break;
  32463. osClose(fd);
  32464. sqlite3_log(SQLITE_WARNING,
  32465. "attempt to open \"%s\" as file descriptor %d", z, fd);
  32466. fd = -1;
  32467. if( osOpen("/dev/null", O_RDONLY, m)<0 ) break;
  32468. }
  32469. if( fd>=0 ){
  32470. if( m!=0 ){
  32471. struct stat statbuf;
  32472. if( osFstat(fd, &statbuf)==0
  32473. && statbuf.st_size==0
  32474. && (statbuf.st_mode&0777)!=m
  32475. ){
  32476. osFchmod(fd, m);
  32477. }
  32478. }
  32479. #if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
  32480. osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
  32481. #endif
  32482. }
  32483. return fd;
  32484. }
  32485. /*
  32486. ** Helper functions to obtain and relinquish the global mutex. The
  32487. ** global mutex is used to protect the unixInodeInfo and
  32488. ** vxworksFileId objects used by this file, all of which may be
  32489. ** shared by multiple threads.
  32490. **
  32491. ** Function unixMutexHeld() is used to assert() that the global mutex
  32492. ** is held when required. This function is only used as part of assert()
  32493. ** statements. e.g.
  32494. **
  32495. ** unixEnterMutex()
  32496. ** assert( unixMutexHeld() );
  32497. ** unixEnterLeave()
  32498. **
  32499. ** To prevent deadlock, the global unixBigLock must must be acquired
  32500. ** before the unixInodeInfo.pLockMutex mutex, if both are held. It is
  32501. ** OK to get the pLockMutex without holding unixBigLock first, but if
  32502. ** that happens, the unixBigLock mutex must not be acquired until after
  32503. ** pLockMutex is released.
  32504. **
  32505. ** OK: enter(unixBigLock), enter(pLockInfo)
  32506. ** OK: enter(unixBigLock)
  32507. ** OK: enter(pLockInfo)
  32508. ** ERROR: enter(pLockInfo), enter(unixBigLock)
  32509. */
  32510. static sqlite3_mutex *unixBigLock = 0;
  32511. static void unixEnterMutex(void){
  32512. assert( sqlite3_mutex_notheld(unixBigLock) ); /* Not a recursive mutex */
  32513. sqlite3_mutex_enter(unixBigLock);
  32514. }
  32515. static void unixLeaveMutex(void){
  32516. assert( sqlite3_mutex_held(unixBigLock) );
  32517. sqlite3_mutex_leave(unixBigLock);
  32518. }
  32519. #ifdef SQLITE_DEBUG
  32520. static int unixMutexHeld(void) {
  32521. return sqlite3_mutex_held(unixBigLock);
  32522. }
  32523. #endif
  32524. #ifdef SQLITE_HAVE_OS_TRACE
  32525. /*
  32526. ** Helper function for printing out trace information from debugging
  32527. ** binaries. This returns the string representation of the supplied
  32528. ** integer lock-type.
  32529. */
  32530. static const char *azFileLock(int eFileLock){
  32531. switch( eFileLock ){
  32532. case NO_LOCK: return "NONE";
  32533. case SHARED_LOCK: return "SHARED";
  32534. case RESERVED_LOCK: return "RESERVED";
  32535. case PENDING_LOCK: return "PENDING";
  32536. case EXCLUSIVE_LOCK: return "EXCLUSIVE";
  32537. }
  32538. return "ERROR";
  32539. }
  32540. #endif
  32541. #ifdef SQLITE_LOCK_TRACE
  32542. /*
  32543. ** Print out information about all locking operations.
  32544. **
  32545. ** This routine is used for troubleshooting locks on multithreaded
  32546. ** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
  32547. ** command-line option on the compiler. This code is normally
  32548. ** turned off.
  32549. */
  32550. static int lockTrace(int fd, int op, struct flock *p){
  32551. char *zOpName, *zType;
  32552. int s;
  32553. int savedErrno;
  32554. if( op==F_GETLK ){
  32555. zOpName = "GETLK";
  32556. }else if( op==F_SETLK ){
  32557. zOpName = "SETLK";
  32558. }else{
  32559. s = osFcntl(fd, op, p);
  32560. sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
  32561. return s;
  32562. }
  32563. if( p->l_type==F_RDLCK ){
  32564. zType = "RDLCK";
  32565. }else if( p->l_type==F_WRLCK ){
  32566. zType = "WRLCK";
  32567. }else if( p->l_type==F_UNLCK ){
  32568. zType = "UNLCK";
  32569. }else{
  32570. assert( 0 );
  32571. }
  32572. assert( p->l_whence==SEEK_SET );
  32573. s = osFcntl(fd, op, p);
  32574. savedErrno = errno;
  32575. sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
  32576. threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
  32577. (int)p->l_pid, s);
  32578. if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
  32579. struct flock l2;
  32580. l2 = *p;
  32581. osFcntl(fd, F_GETLK, &l2);
  32582. if( l2.l_type==F_RDLCK ){
  32583. zType = "RDLCK";
  32584. }else if( l2.l_type==F_WRLCK ){
  32585. zType = "WRLCK";
  32586. }else if( l2.l_type==F_UNLCK ){
  32587. zType = "UNLCK";
  32588. }else{
  32589. assert( 0 );
  32590. }
  32591. sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
  32592. zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
  32593. }
  32594. errno = savedErrno;
  32595. return s;
  32596. }
  32597. #undef osFcntl
  32598. #define osFcntl lockTrace
  32599. #endif /* SQLITE_LOCK_TRACE */
  32600. /*
  32601. ** Retry ftruncate() calls that fail due to EINTR
  32602. **
  32603. ** All calls to ftruncate() within this file should be made through
  32604. ** this wrapper. On the Android platform, bypassing the logic below
  32605. ** could lead to a corrupt database.
  32606. */
  32607. static int robust_ftruncate(int h, sqlite3_int64 sz){
  32608. int rc;
  32609. #ifdef __ANDROID__
  32610. /* On Android, ftruncate() always uses 32-bit offsets, even if
  32611. ** _FILE_OFFSET_BITS=64 is defined. This means it is unsafe to attempt to
  32612. ** truncate a file to any size larger than 2GiB. Silently ignore any
  32613. ** such attempts. */
  32614. if( sz>(sqlite3_int64)0x7FFFFFFF ){
  32615. rc = SQLITE_OK;
  32616. }else
  32617. #endif
  32618. do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
  32619. return rc;
  32620. }
  32621. /*
  32622. ** This routine translates a standard POSIX errno code into something
  32623. ** useful to the clients of the sqlite3 functions. Specifically, it is
  32624. ** intended to translate a variety of "try again" errors into SQLITE_BUSY
  32625. ** and a variety of "please close the file descriptor NOW" errors into
  32626. ** SQLITE_IOERR
  32627. **
  32628. ** Errors during initialization of locks, or file system support for locks,
  32629. ** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
  32630. */
  32631. static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
  32632. assert( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
  32633. (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
  32634. (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
  32635. (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) );
  32636. switch (posixError) {
  32637. case EACCES:
  32638. case EAGAIN:
  32639. case ETIMEDOUT:
  32640. case EBUSY:
  32641. case EINTR:
  32642. case ENOLCK:
  32643. /* random NFS retry error, unless during file system support
  32644. * introspection, in which it actually means what it says */
  32645. return SQLITE_BUSY;
  32646. case EPERM:
  32647. return SQLITE_PERM;
  32648. default:
  32649. return sqliteIOErr;
  32650. }
  32651. }
  32652. /******************************************************************************
  32653. ****************** Begin Unique File ID Utility Used By VxWorks ***************
  32654. **
  32655. ** On most versions of unix, we can get a unique ID for a file by concatenating
  32656. ** the device number and the inode number. But this does not work on VxWorks.
  32657. ** On VxWorks, a unique file id must be based on the canonical filename.
  32658. **
  32659. ** A pointer to an instance of the following structure can be used as a
  32660. ** unique file ID in VxWorks. Each instance of this structure contains
  32661. ** a copy of the canonical filename. There is also a reference count.
  32662. ** The structure is reclaimed when the number of pointers to it drops to
  32663. ** zero.
  32664. **
  32665. ** There are never very many files open at one time and lookups are not
  32666. ** a performance-critical path, so it is sufficient to put these
  32667. ** structures on a linked list.
  32668. */
  32669. struct vxworksFileId {
  32670. struct vxworksFileId *pNext; /* Next in a list of them all */
  32671. int nRef; /* Number of references to this one */
  32672. int nName; /* Length of the zCanonicalName[] string */
  32673. char *zCanonicalName; /* Canonical filename */
  32674. };
  32675. #if OS_VXWORKS
  32676. /*
  32677. ** All unique filenames are held on a linked list headed by this
  32678. ** variable:
  32679. */
  32680. static struct vxworksFileId *vxworksFileList = 0;
  32681. /*
  32682. ** Simplify a filename into its canonical form
  32683. ** by making the following changes:
  32684. **
  32685. ** * removing any trailing and duplicate /
  32686. ** * convert /./ into just /
  32687. ** * convert /A/../ where A is any simple name into just /
  32688. **
  32689. ** Changes are made in-place. Return the new name length.
  32690. **
  32691. ** The original filename is in z[0..n-1]. Return the number of
  32692. ** characters in the simplified name.
  32693. */
  32694. static int vxworksSimplifyName(char *z, int n){
  32695. int i, j;
  32696. while( n>1 && z[n-1]=='/' ){ n--; }
  32697. for(i=j=0; i<n; i++){
  32698. if( z[i]=='/' ){
  32699. if( z[i+1]=='/' ) continue;
  32700. if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
  32701. i += 1;
  32702. continue;
  32703. }
  32704. if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
  32705. while( j>0 && z[j-1]!='/' ){ j--; }
  32706. if( j>0 ){ j--; }
  32707. i += 2;
  32708. continue;
  32709. }
  32710. }
  32711. z[j++] = z[i];
  32712. }
  32713. z[j] = 0;
  32714. return j;
  32715. }
  32716. /*
  32717. ** Find a unique file ID for the given absolute pathname. Return
  32718. ** a pointer to the vxworksFileId object. This pointer is the unique
  32719. ** file ID.
  32720. **
  32721. ** The nRef field of the vxworksFileId object is incremented before
  32722. ** the object is returned. A new vxworksFileId object is created
  32723. ** and added to the global list if necessary.
  32724. **
  32725. ** If a memory allocation error occurs, return NULL.
  32726. */
  32727. static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
  32728. struct vxworksFileId *pNew; /* search key and new file ID */
  32729. struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
  32730. int n; /* Length of zAbsoluteName string */
  32731. assert( zAbsoluteName[0]=='/' );
  32732. n = (int)strlen(zAbsoluteName);
  32733. pNew = sqlite3_malloc64( sizeof(*pNew) + (n+1) );
  32734. if( pNew==0 ) return 0;
  32735. pNew->zCanonicalName = (char*)&pNew[1];
  32736. memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
  32737. n = vxworksSimplifyName(pNew->zCanonicalName, n);
  32738. /* Search for an existing entry that matching the canonical name.
  32739. ** If found, increment the reference count and return a pointer to
  32740. ** the existing file ID.
  32741. */
  32742. unixEnterMutex();
  32743. for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
  32744. if( pCandidate->nName==n
  32745. && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
  32746. ){
  32747. sqlite3_free(pNew);
  32748. pCandidate->nRef++;
  32749. unixLeaveMutex();
  32750. return pCandidate;
  32751. }
  32752. }
  32753. /* No match was found. We will make a new file ID */
  32754. pNew->nRef = 1;
  32755. pNew->nName = n;
  32756. pNew->pNext = vxworksFileList;
  32757. vxworksFileList = pNew;
  32758. unixLeaveMutex();
  32759. return pNew;
  32760. }
  32761. /*
  32762. ** Decrement the reference count on a vxworksFileId object. Free
  32763. ** the object when the reference count reaches zero.
  32764. */
  32765. static void vxworksReleaseFileId(struct vxworksFileId *pId){
  32766. unixEnterMutex();
  32767. assert( pId->nRef>0 );
  32768. pId->nRef--;
  32769. if( pId->nRef==0 ){
  32770. struct vxworksFileId **pp;
  32771. for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
  32772. assert( *pp==pId );
  32773. *pp = pId->pNext;
  32774. sqlite3_free(pId);
  32775. }
  32776. unixLeaveMutex();
  32777. }
  32778. #endif /* OS_VXWORKS */
  32779. /*************** End of Unique File ID Utility Used By VxWorks ****************
  32780. ******************************************************************************/
  32781. /******************************************************************************
  32782. *************************** Posix Advisory Locking ****************************
  32783. **
  32784. ** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
  32785. ** section 6.5.2.2 lines 483 through 490 specify that when a process
  32786. ** sets or clears a lock, that operation overrides any prior locks set
  32787. ** by the same process. It does not explicitly say so, but this implies
  32788. ** that it overrides locks set by the same process using a different
  32789. ** file descriptor. Consider this test case:
  32790. **
  32791. ** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
  32792. ** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
  32793. **
  32794. ** Suppose ./file1 and ./file2 are really the same file (because
  32795. ** one is a hard or symbolic link to the other) then if you set
  32796. ** an exclusive lock on fd1, then try to get an exclusive lock
  32797. ** on fd2, it works. I would have expected the second lock to
  32798. ** fail since there was already a lock on the file due to fd1.
  32799. ** But not so. Since both locks came from the same process, the
  32800. ** second overrides the first, even though they were on different
  32801. ** file descriptors opened on different file names.
  32802. **
  32803. ** This means that we cannot use POSIX locks to synchronize file access
  32804. ** among competing threads of the same process. POSIX locks will work fine
  32805. ** to synchronize access for threads in separate processes, but not
  32806. ** threads within the same process.
  32807. **
  32808. ** To work around the problem, SQLite has to manage file locks internally
  32809. ** on its own. Whenever a new database is opened, we have to find the
  32810. ** specific inode of the database file (the inode is determined by the
  32811. ** st_dev and st_ino fields of the stat structure that fstat() fills in)
  32812. ** and check for locks already existing on that inode. When locks are
  32813. ** created or removed, we have to look at our own internal record of the
  32814. ** locks to see if another thread has previously set a lock on that same
  32815. ** inode.
  32816. **
  32817. ** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
  32818. ** For VxWorks, we have to use the alternative unique ID system based on
  32819. ** canonical filename and implemented in the previous division.)
  32820. **
  32821. ** The sqlite3_file structure for POSIX is no longer just an integer file
  32822. ** descriptor. It is now a structure that holds the integer file
  32823. ** descriptor and a pointer to a structure that describes the internal
  32824. ** locks on the corresponding inode. There is one locking structure
  32825. ** per inode, so if the same inode is opened twice, both unixFile structures
  32826. ** point to the same locking structure. The locking structure keeps
  32827. ** a reference count (so we will know when to delete it) and a "cnt"
  32828. ** field that tells us its internal lock status. cnt==0 means the
  32829. ** file is unlocked. cnt==-1 means the file has an exclusive lock.
  32830. ** cnt>0 means there are cnt shared locks on the file.
  32831. **
  32832. ** Any attempt to lock or unlock a file first checks the locking
  32833. ** structure. The fcntl() system call is only invoked to set a
  32834. ** POSIX lock if the internal lock structure transitions between
  32835. ** a locked and an unlocked state.
  32836. **
  32837. ** But wait: there are yet more problems with POSIX advisory locks.
  32838. **
  32839. ** If you close a file descriptor that points to a file that has locks,
  32840. ** all locks on that file that are owned by the current process are
  32841. ** released. To work around this problem, each unixInodeInfo object
  32842. ** maintains a count of the number of pending locks on tha inode.
  32843. ** When an attempt is made to close an unixFile, if there are
  32844. ** other unixFile open on the same inode that are holding locks, the call
  32845. ** to close() the file descriptor is deferred until all of the locks clear.
  32846. ** The unixInodeInfo structure keeps a list of file descriptors that need to
  32847. ** be closed and that list is walked (and cleared) when the last lock
  32848. ** clears.
  32849. **
  32850. ** Yet another problem: LinuxThreads do not play well with posix locks.
  32851. **
  32852. ** Many older versions of linux use the LinuxThreads library which is
  32853. ** not posix compliant. Under LinuxThreads, a lock created by thread
  32854. ** A cannot be modified or overridden by a different thread B.
  32855. ** Only thread A can modify the lock. Locking behavior is correct
  32856. ** if the appliation uses the newer Native Posix Thread Library (NPTL)
  32857. ** on linux - with NPTL a lock created by thread A can override locks
  32858. ** in thread B. But there is no way to know at compile-time which
  32859. ** threading library is being used. So there is no way to know at
  32860. ** compile-time whether or not thread A can override locks on thread B.
  32861. ** One has to do a run-time check to discover the behavior of the
  32862. ** current process.
  32863. **
  32864. ** SQLite used to support LinuxThreads. But support for LinuxThreads
  32865. ** was dropped beginning with version 3.7.0. SQLite will still work with
  32866. ** LinuxThreads provided that (1) there is no more than one connection
  32867. ** per database file in the same process and (2) database connections
  32868. ** do not move across threads.
  32869. */
  32870. /*
  32871. ** An instance of the following structure serves as the key used
  32872. ** to locate a particular unixInodeInfo object.
  32873. */
  32874. struct unixFileId {
  32875. dev_t dev; /* Device number */
  32876. #if OS_VXWORKS
  32877. struct vxworksFileId *pId; /* Unique file ID for vxworks. */
  32878. #else
  32879. /* We are told that some versions of Android contain a bug that
  32880. ** sizes ino_t at only 32-bits instead of 64-bits. (See
  32881. ** https://android-review.googlesource.com/#/c/115351/3/dist/sqlite3.c)
  32882. ** To work around this, always allocate 64-bits for the inode number.
  32883. ** On small machines that only have 32-bit inodes, this wastes 4 bytes,
  32884. ** but that should not be a big deal. */
  32885. /* WAS: ino_t ino; */
  32886. u64 ino; /* Inode number */
  32887. #endif
  32888. };
  32889. /*
  32890. ** An instance of the following structure is allocated for each open
  32891. ** inode.
  32892. **
  32893. ** A single inode can have multiple file descriptors, so each unixFile
  32894. ** structure contains a pointer to an instance of this object and this
  32895. ** object keeps a count of the number of unixFile pointing to it.
  32896. **
  32897. ** Mutex rules:
  32898. **
  32899. ** (1) Only the pLockMutex mutex must be held in order to read or write
  32900. ** any of the locking fields:
  32901. ** nShared, nLock, eFileLock, bProcessLock, pUnused
  32902. **
  32903. ** (2) When nRef>0, then the following fields are unchanging and can
  32904. ** be read (but not written) without holding any mutex:
  32905. ** fileId, pLockMutex
  32906. **
  32907. ** (3) With the exceptions above, all the fields may only be read
  32908. ** or written while holding the global unixBigLock mutex.
  32909. **
  32910. ** Deadlock prevention: The global unixBigLock mutex may not
  32911. ** be acquired while holding the pLockMutex mutex. If both unixBigLock
  32912. ** and pLockMutex are needed, then unixBigLock must be acquired first.
  32913. */
  32914. struct unixInodeInfo {
  32915. struct unixFileId fileId; /* The lookup key */
  32916. sqlite3_mutex *pLockMutex; /* Hold this mutex for... */
  32917. int nShared; /* Number of SHARED locks held */
  32918. int nLock; /* Number of outstanding file locks */
  32919. unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
  32920. unsigned char bProcessLock; /* An exclusive process lock is held */
  32921. UnixUnusedFd *pUnused; /* Unused file descriptors to close */
  32922. int nRef; /* Number of pointers to this structure */
  32923. unixShmNode *pShmNode; /* Shared memory associated with this inode */
  32924. unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
  32925. unixInodeInfo *pPrev; /* .... doubly linked */
  32926. #if SQLITE_ENABLE_LOCKING_STYLE
  32927. unsigned long long sharedByte; /* for AFP simulated shared lock */
  32928. #endif
  32929. #if OS_VXWORKS
  32930. sem_t *pSem; /* Named POSIX semaphore */
  32931. char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
  32932. #endif
  32933. };
  32934. /*
  32935. ** A lists of all unixInodeInfo objects.
  32936. **
  32937. ** Must hold unixBigLock in order to read or write this variable.
  32938. */
  32939. static unixInodeInfo *inodeList = 0; /* All unixInodeInfo objects */
  32940. #ifdef SQLITE_DEBUG
  32941. /*
  32942. ** True if the inode mutex (on the unixFile.pFileMutex field) is held, or not.
  32943. ** This routine is used only within assert() to help verify correct mutex
  32944. ** usage.
  32945. */
  32946. int unixFileMutexHeld(unixFile *pFile){
  32947. assert( pFile->pInode );
  32948. return sqlite3_mutex_held(pFile->pInode->pLockMutex);
  32949. }
  32950. int unixFileMutexNotheld(unixFile *pFile){
  32951. assert( pFile->pInode );
  32952. return sqlite3_mutex_notheld(pFile->pInode->pLockMutex);
  32953. }
  32954. #endif
  32955. /*
  32956. **
  32957. ** This function - unixLogErrorAtLine(), is only ever called via the macro
  32958. ** unixLogError().
  32959. **
  32960. ** It is invoked after an error occurs in an OS function and errno has been
  32961. ** set. It logs a message using sqlite3_log() containing the current value of
  32962. ** errno and, if possible, the human-readable equivalent from strerror() or
  32963. ** strerror_r().
  32964. **
  32965. ** The first argument passed to the macro should be the error code that
  32966. ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
  32967. ** The two subsequent arguments should be the name of the OS function that
  32968. ** failed (e.g. "unlink", "open") and the associated file-system path,
  32969. ** if any.
  32970. */
  32971. #define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
  32972. static int unixLogErrorAtLine(
  32973. int errcode, /* SQLite error code */
  32974. const char *zFunc, /* Name of OS function that failed */
  32975. const char *zPath, /* File path associated with error */
  32976. int iLine /* Source line number where error occurred */
  32977. ){
  32978. char *zErr; /* Message from strerror() or equivalent */
  32979. int iErrno = errno; /* Saved syscall error number */
  32980. /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
  32981. ** the strerror() function to obtain the human-readable error message
  32982. ** equivalent to errno. Otherwise, use strerror_r().
  32983. */
  32984. #if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
  32985. char aErr[80];
  32986. memset(aErr, 0, sizeof(aErr));
  32987. zErr = aErr;
  32988. /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
  32989. ** assume that the system provides the GNU version of strerror_r() that
  32990. ** returns a pointer to a buffer containing the error message. That pointer
  32991. ** may point to aErr[], or it may point to some static storage somewhere.
  32992. ** Otherwise, assume that the system provides the POSIX version of
  32993. ** strerror_r(), which always writes an error message into aErr[].
  32994. **
  32995. ** If the code incorrectly assumes that it is the POSIX version that is
  32996. ** available, the error message will often be an empty string. Not a
  32997. ** huge problem. Incorrectly concluding that the GNU version is available
  32998. ** could lead to a segfault though.
  32999. */
  33000. #if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
  33001. zErr =
  33002. # endif
  33003. strerror_r(iErrno, aErr, sizeof(aErr)-1);
  33004. #elif SQLITE_THREADSAFE
  33005. /* This is a threadsafe build, but strerror_r() is not available. */
  33006. zErr = "";
  33007. #else
  33008. /* Non-threadsafe build, use strerror(). */
  33009. zErr = strerror(iErrno);
  33010. #endif
  33011. if( zPath==0 ) zPath = "";
  33012. sqlite3_log(errcode,
  33013. "os_unix.c:%d: (%d) %s(%s) - %s",
  33014. iLine, iErrno, zFunc, zPath, zErr
  33015. );
  33016. return errcode;
  33017. }
  33018. /*
  33019. ** Close a file descriptor.
  33020. **
  33021. ** We assume that close() almost always works, since it is only in a
  33022. ** very sick application or on a very sick platform that it might fail.
  33023. ** If it does fail, simply leak the file descriptor, but do log the
  33024. ** error.
  33025. **
  33026. ** Note that it is not safe to retry close() after EINTR since the
  33027. ** file descriptor might have already been reused by another thread.
  33028. ** So we don't even try to recover from an EINTR. Just log the error
  33029. ** and move on.
  33030. */
  33031. static void robust_close(unixFile *pFile, int h, int lineno){
  33032. if( osClose(h) ){
  33033. unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
  33034. pFile ? pFile->zPath : 0, lineno);
  33035. }
  33036. }
  33037. /*
  33038. ** Set the pFile->lastErrno. Do this in a subroutine as that provides
  33039. ** a convenient place to set a breakpoint.
  33040. */
  33041. static void storeLastErrno(unixFile *pFile, int error){
  33042. pFile->lastErrno = error;
  33043. }
  33044. /*
  33045. ** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
  33046. */
  33047. static void closePendingFds(unixFile *pFile){
  33048. unixInodeInfo *pInode = pFile->pInode;
  33049. UnixUnusedFd *p;
  33050. UnixUnusedFd *pNext;
  33051. assert( unixFileMutexHeld(pFile) );
  33052. for(p=pInode->pUnused; p; p=pNext){
  33053. pNext = p->pNext;
  33054. robust_close(pFile, p->fd, __LINE__);
  33055. sqlite3_free(p);
  33056. }
  33057. pInode->pUnused = 0;
  33058. }
  33059. /*
  33060. ** Release a unixInodeInfo structure previously allocated by findInodeInfo().
  33061. **
  33062. ** The global mutex must be held when this routine is called, but the mutex
  33063. ** on the inode being deleted must NOT be held.
  33064. */
  33065. static void releaseInodeInfo(unixFile *pFile){
  33066. unixInodeInfo *pInode = pFile->pInode;
  33067. assert( unixMutexHeld() );
  33068. assert( unixFileMutexNotheld(pFile) );
  33069. if( ALWAYS(pInode) ){
  33070. pInode->nRef--;
  33071. if( pInode->nRef==0 ){
  33072. assert( pInode->pShmNode==0 );
  33073. sqlite3_mutex_enter(pInode->pLockMutex);
  33074. closePendingFds(pFile);
  33075. sqlite3_mutex_leave(pInode->pLockMutex);
  33076. if( pInode->pPrev ){
  33077. assert( pInode->pPrev->pNext==pInode );
  33078. pInode->pPrev->pNext = pInode->pNext;
  33079. }else{
  33080. assert( inodeList==pInode );
  33081. inodeList = pInode->pNext;
  33082. }
  33083. if( pInode->pNext ){
  33084. assert( pInode->pNext->pPrev==pInode );
  33085. pInode->pNext->pPrev = pInode->pPrev;
  33086. }
  33087. sqlite3_mutex_free(pInode->pLockMutex);
  33088. sqlite3_free(pInode);
  33089. }
  33090. }
  33091. }
  33092. /*
  33093. ** Given a file descriptor, locate the unixInodeInfo object that
  33094. ** describes that file descriptor. Create a new one if necessary. The
  33095. ** return value might be uninitialized if an error occurs.
  33096. **
  33097. ** The global mutex must held when calling this routine.
  33098. **
  33099. ** Return an appropriate error code.
  33100. */
  33101. static int findInodeInfo(
  33102. unixFile *pFile, /* Unix file with file desc used in the key */
  33103. unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
  33104. ){
  33105. int rc; /* System call return code */
  33106. int fd; /* The file descriptor for pFile */
  33107. struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
  33108. struct stat statbuf; /* Low-level file information */
  33109. unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
  33110. assert( unixMutexHeld() );
  33111. /* Get low-level information about the file that we can used to
  33112. ** create a unique name for the file.
  33113. */
  33114. fd = pFile->h;
  33115. rc = osFstat(fd, &statbuf);
  33116. if( rc!=0 ){
  33117. storeLastErrno(pFile, errno);
  33118. #if defined(EOVERFLOW) && defined(SQLITE_DISABLE_LFS)
  33119. if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
  33120. #endif
  33121. return SQLITE_IOERR;
  33122. }
  33123. #ifdef __APPLE__
  33124. /* On OS X on an msdos filesystem, the inode number is reported
  33125. ** incorrectly for zero-size files. See ticket #3260. To work
  33126. ** around this problem (we consider it a bug in OS X, not SQLite)
  33127. ** we always increase the file size to 1 by writing a single byte
  33128. ** prior to accessing the inode number. The one byte written is
  33129. ** an ASCII 'S' character which also happens to be the first byte
  33130. ** in the header of every SQLite database. In this way, if there
  33131. ** is a race condition such that another thread has already populated
  33132. ** the first page of the database, no damage is done.
  33133. */
  33134. if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
  33135. do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
  33136. if( rc!=1 ){
  33137. storeLastErrno(pFile, errno);
  33138. return SQLITE_IOERR;
  33139. }
  33140. rc = osFstat(fd, &statbuf);
  33141. if( rc!=0 ){
  33142. storeLastErrno(pFile, errno);
  33143. return SQLITE_IOERR;
  33144. }
  33145. }
  33146. #endif
  33147. memset(&fileId, 0, sizeof(fileId));
  33148. fileId.dev = statbuf.st_dev;
  33149. #if OS_VXWORKS
  33150. fileId.pId = pFile->pId;
  33151. #else
  33152. fileId.ino = (u64)statbuf.st_ino;
  33153. #endif
  33154. assert( unixMutexHeld() );
  33155. pInode = inodeList;
  33156. while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
  33157. pInode = pInode->pNext;
  33158. }
  33159. if( pInode==0 ){
  33160. pInode = sqlite3_malloc64( sizeof(*pInode) );
  33161. if( pInode==0 ){
  33162. return SQLITE_NOMEM_BKPT;
  33163. }
  33164. memset(pInode, 0, sizeof(*pInode));
  33165. memcpy(&pInode->fileId, &fileId, sizeof(fileId));
  33166. if( sqlite3GlobalConfig.bCoreMutex ){
  33167. pInode->pLockMutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
  33168. if( pInode->pLockMutex==0 ){
  33169. sqlite3_free(pInode);
  33170. return SQLITE_NOMEM_BKPT;
  33171. }
  33172. }
  33173. pInode->nRef = 1;
  33174. assert( unixMutexHeld() );
  33175. pInode->pNext = inodeList;
  33176. pInode->pPrev = 0;
  33177. if( inodeList ) inodeList->pPrev = pInode;
  33178. inodeList = pInode;
  33179. }else{
  33180. pInode->nRef++;
  33181. }
  33182. *ppInode = pInode;
  33183. return SQLITE_OK;
  33184. }
  33185. /*
  33186. ** Return TRUE if pFile has been renamed or unlinked since it was first opened.
  33187. */
  33188. static int fileHasMoved(unixFile *pFile){
  33189. #if OS_VXWORKS
  33190. return pFile->pInode!=0 && pFile->pId!=pFile->pInode->fileId.pId;
  33191. #else
  33192. struct stat buf;
  33193. return pFile->pInode!=0 &&
  33194. (osStat(pFile->zPath, &buf)!=0
  33195. || (u64)buf.st_ino!=pFile->pInode->fileId.ino);
  33196. #endif
  33197. }
  33198. /*
  33199. ** Check a unixFile that is a database. Verify the following:
  33200. **
  33201. ** (1) There is exactly one hard link on the file
  33202. ** (2) The file is not a symbolic link
  33203. ** (3) The file has not been renamed or unlinked
  33204. **
  33205. ** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
  33206. */
  33207. static void verifyDbFile(unixFile *pFile){
  33208. struct stat buf;
  33209. int rc;
  33210. /* These verifications occurs for the main database only */
  33211. if( pFile->ctrlFlags & UNIXFILE_NOLOCK ) return;
  33212. rc = osFstat(pFile->h, &buf);
  33213. if( rc!=0 ){
  33214. sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
  33215. return;
  33216. }
  33217. if( buf.st_nlink==0 ){
  33218. sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
  33219. return;
  33220. }
  33221. if( buf.st_nlink>1 ){
  33222. sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
  33223. return;
  33224. }
  33225. if( fileHasMoved(pFile) ){
  33226. sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
  33227. return;
  33228. }
  33229. }
  33230. /*
  33231. ** This routine checks if there is a RESERVED lock held on the specified
  33232. ** file by this or any other process. If such a lock is held, set *pResOut
  33233. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  33234. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  33235. */
  33236. static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
  33237. int rc = SQLITE_OK;
  33238. int reserved = 0;
  33239. unixFile *pFile = (unixFile*)id;
  33240. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  33241. assert( pFile );
  33242. assert( pFile->eFileLock<=SHARED_LOCK );
  33243. sqlite3_mutex_enter(pFile->pInode->pLockMutex);
  33244. /* Check if a thread in this process holds such a lock */
  33245. if( pFile->pInode->eFileLock>SHARED_LOCK ){
  33246. reserved = 1;
  33247. }
  33248. /* Otherwise see if some other process holds it.
  33249. */
  33250. #ifndef __DJGPP__
  33251. if( !reserved && !pFile->pInode->bProcessLock ){
  33252. struct flock lock;
  33253. lock.l_whence = SEEK_SET;
  33254. lock.l_start = RESERVED_BYTE;
  33255. lock.l_len = 1;
  33256. lock.l_type = F_WRLCK;
  33257. if( osFcntl(pFile->h, F_GETLK, &lock) ){
  33258. rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
  33259. storeLastErrno(pFile, errno);
  33260. } else if( lock.l_type!=F_UNLCK ){
  33261. reserved = 1;
  33262. }
  33263. }
  33264. #endif
  33265. sqlite3_mutex_leave(pFile->pInode->pLockMutex);
  33266. OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
  33267. *pResOut = reserved;
  33268. return rc;
  33269. }
  33270. /*
  33271. ** Set a posix-advisory-lock.
  33272. **
  33273. ** There are two versions of this routine. If compiled with
  33274. ** SQLITE_ENABLE_SETLK_TIMEOUT then the routine has an extra parameter
  33275. ** which is a pointer to a unixFile. If the unixFile->iBusyTimeout
  33276. ** value is set, then it is the number of milliseconds to wait before
  33277. ** failing the lock. The iBusyTimeout value is always reset back to
  33278. ** zero on each call.
  33279. **
  33280. ** If SQLITE_ENABLE_SETLK_TIMEOUT is not defined, then do a non-blocking
  33281. ** attempt to set the lock.
  33282. */
  33283. #ifndef SQLITE_ENABLE_SETLK_TIMEOUT
  33284. # define osSetPosixAdvisoryLock(h,x,t) osFcntl(h,F_SETLK,x)
  33285. #else
  33286. static int osSetPosixAdvisoryLock(
  33287. int h, /* The file descriptor on which to take the lock */
  33288. struct flock *pLock, /* The description of the lock */
  33289. unixFile *pFile /* Structure holding timeout value */
  33290. ){
  33291. int tm = pFile->iBusyTimeout;
  33292. int rc = osFcntl(h,F_SETLK,pLock);
  33293. while( rc<0 && tm>0 ){
  33294. /* On systems that support some kind of blocking file lock with a timeout,
  33295. ** make appropriate changes here to invoke that blocking file lock. On
  33296. ** generic posix, however, there is no such API. So we simply try the
  33297. ** lock once every millisecond until either the timeout expires, or until
  33298. ** the lock is obtained. */
  33299. usleep(1000);
  33300. rc = osFcntl(h,F_SETLK,pLock);
  33301. tm--;
  33302. }
  33303. return rc;
  33304. }
  33305. #endif /* SQLITE_ENABLE_SETLK_TIMEOUT */
  33306. /*
  33307. ** Attempt to set a system-lock on the file pFile. The lock is
  33308. ** described by pLock.
  33309. **
  33310. ** If the pFile was opened read/write from unix-excl, then the only lock
  33311. ** ever obtained is an exclusive lock, and it is obtained exactly once
  33312. ** the first time any lock is attempted. All subsequent system locking
  33313. ** operations become no-ops. Locking operations still happen internally,
  33314. ** in order to coordinate access between separate database connections
  33315. ** within this process, but all of that is handled in memory and the
  33316. ** operating system does not participate.
  33317. **
  33318. ** This function is a pass-through to fcntl(F_SETLK) if pFile is using
  33319. ** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
  33320. ** and is read-only.
  33321. **
  33322. ** Zero is returned if the call completes successfully, or -1 if a call
  33323. ** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
  33324. */
  33325. static int unixFileLock(unixFile *pFile, struct flock *pLock){
  33326. int rc;
  33327. unixInodeInfo *pInode = pFile->pInode;
  33328. assert( pInode!=0 );
  33329. assert( sqlite3_mutex_held(pInode->pLockMutex) );
  33330. if( (pFile->ctrlFlags & (UNIXFILE_EXCL|UNIXFILE_RDONLY))==UNIXFILE_EXCL ){
  33331. if( pInode->bProcessLock==0 ){
  33332. struct flock lock;
  33333. assert( pInode->nLock==0 );
  33334. lock.l_whence = SEEK_SET;
  33335. lock.l_start = SHARED_FIRST;
  33336. lock.l_len = SHARED_SIZE;
  33337. lock.l_type = F_WRLCK;
  33338. rc = osSetPosixAdvisoryLock(pFile->h, &lock, pFile);
  33339. if( rc<0 ) return rc;
  33340. pInode->bProcessLock = 1;
  33341. pInode->nLock++;
  33342. }else{
  33343. rc = 0;
  33344. }
  33345. }else{
  33346. rc = osSetPosixAdvisoryLock(pFile->h, pLock, pFile);
  33347. }
  33348. return rc;
  33349. }
  33350. /*
  33351. ** Lock the file with the lock specified by parameter eFileLock - one
  33352. ** of the following:
  33353. **
  33354. ** (1) SHARED_LOCK
  33355. ** (2) RESERVED_LOCK
  33356. ** (3) PENDING_LOCK
  33357. ** (4) EXCLUSIVE_LOCK
  33358. **
  33359. ** Sometimes when requesting one lock state, additional lock states
  33360. ** are inserted in between. The locking might fail on one of the later
  33361. ** transitions leaving the lock state different from what it started but
  33362. ** still short of its goal. The following chart shows the allowed
  33363. ** transitions and the inserted intermediate states:
  33364. **
  33365. ** UNLOCKED -> SHARED
  33366. ** SHARED -> RESERVED
  33367. ** SHARED -> (PENDING) -> EXCLUSIVE
  33368. ** RESERVED -> (PENDING) -> EXCLUSIVE
  33369. ** PENDING -> EXCLUSIVE
  33370. **
  33371. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  33372. ** routine to lower a locking level.
  33373. */
  33374. static int unixLock(sqlite3_file *id, int eFileLock){
  33375. /* The following describes the implementation of the various locks and
  33376. ** lock transitions in terms of the POSIX advisory shared and exclusive
  33377. ** lock primitives (called read-locks and write-locks below, to avoid
  33378. ** confusion with SQLite lock names). The algorithms are complicated
  33379. ** slightly in order to be compatible with Windows95 systems simultaneously
  33380. ** accessing the same database file, in case that is ever required.
  33381. **
  33382. ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
  33383. ** byte', each single bytes at well known offsets, and the 'shared byte
  33384. ** range', a range of 510 bytes at a well known offset.
  33385. **
  33386. ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
  33387. ** byte'. If this is successful, 'shared byte range' is read-locked
  33388. ** and the lock on the 'pending byte' released. (Legacy note: When
  33389. ** SQLite was first developed, Windows95 systems were still very common,
  33390. ** and Widnows95 lacks a shared-lock capability. So on Windows95, a
  33391. ** single randomly selected by from the 'shared byte range' is locked.
  33392. ** Windows95 is now pretty much extinct, but this work-around for the
  33393. ** lack of shared-locks on Windows95 lives on, for backwards
  33394. ** compatibility.)
  33395. **
  33396. ** A process may only obtain a RESERVED lock after it has a SHARED lock.
  33397. ** A RESERVED lock is implemented by grabbing a write-lock on the
  33398. ** 'reserved byte'.
  33399. **
  33400. ** A process may only obtain a PENDING lock after it has obtained a
  33401. ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
  33402. ** on the 'pending byte'. This ensures that no new SHARED locks can be
  33403. ** obtained, but existing SHARED locks are allowed to persist. A process
  33404. ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
  33405. ** This property is used by the algorithm for rolling back a journal file
  33406. ** after a crash.
  33407. **
  33408. ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
  33409. ** implemented by obtaining a write-lock on the entire 'shared byte
  33410. ** range'. Since all other locks require a read-lock on one of the bytes
  33411. ** within this range, this ensures that no other locks are held on the
  33412. ** database.
  33413. */
  33414. int rc = SQLITE_OK;
  33415. unixFile *pFile = (unixFile*)id;
  33416. unixInodeInfo *pInode;
  33417. struct flock lock;
  33418. int tErrno = 0;
  33419. assert( pFile );
  33420. OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
  33421. azFileLock(eFileLock), azFileLock(pFile->eFileLock),
  33422. azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared,
  33423. osGetpid(0)));
  33424. /* If there is already a lock of this type or more restrictive on the
  33425. ** unixFile, do nothing. Don't use the end_lock: exit path, as
  33426. ** unixEnterMutex() hasn't been called yet.
  33427. */
  33428. if( pFile->eFileLock>=eFileLock ){
  33429. OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
  33430. azFileLock(eFileLock)));
  33431. return SQLITE_OK;
  33432. }
  33433. /* Make sure the locking sequence is correct.
  33434. ** (1) We never move from unlocked to anything higher than shared lock.
  33435. ** (2) SQLite never explicitly requests a pendig lock.
  33436. ** (3) A shared lock is always held when a reserve lock is requested.
  33437. */
  33438. assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
  33439. assert( eFileLock!=PENDING_LOCK );
  33440. assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
  33441. /* This mutex is needed because pFile->pInode is shared across threads
  33442. */
  33443. pInode = pFile->pInode;
  33444. sqlite3_mutex_enter(pInode->pLockMutex);
  33445. /* If some thread using this PID has a lock via a different unixFile*
  33446. ** handle that precludes the requested lock, return BUSY.
  33447. */
  33448. if( (pFile->eFileLock!=pInode->eFileLock &&
  33449. (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
  33450. ){
  33451. rc = SQLITE_BUSY;
  33452. goto end_lock;
  33453. }
  33454. /* If a SHARED lock is requested, and some thread using this PID already
  33455. ** has a SHARED or RESERVED lock, then increment reference counts and
  33456. ** return SQLITE_OK.
  33457. */
  33458. if( eFileLock==SHARED_LOCK &&
  33459. (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
  33460. assert( eFileLock==SHARED_LOCK );
  33461. assert( pFile->eFileLock==0 );
  33462. assert( pInode->nShared>0 );
  33463. pFile->eFileLock = SHARED_LOCK;
  33464. pInode->nShared++;
  33465. pInode->nLock++;
  33466. goto end_lock;
  33467. }
  33468. /* A PENDING lock is needed before acquiring a SHARED lock and before
  33469. ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
  33470. ** be released.
  33471. */
  33472. lock.l_len = 1L;
  33473. lock.l_whence = SEEK_SET;
  33474. if( eFileLock==SHARED_LOCK
  33475. || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
  33476. ){
  33477. lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
  33478. lock.l_start = PENDING_BYTE;
  33479. if( unixFileLock(pFile, &lock) ){
  33480. tErrno = errno;
  33481. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  33482. if( rc!=SQLITE_BUSY ){
  33483. storeLastErrno(pFile, tErrno);
  33484. }
  33485. goto end_lock;
  33486. }
  33487. }
  33488. /* If control gets to this point, then actually go ahead and make
  33489. ** operating system calls for the specified lock.
  33490. */
  33491. if( eFileLock==SHARED_LOCK ){
  33492. assert( pInode->nShared==0 );
  33493. assert( pInode->eFileLock==0 );
  33494. assert( rc==SQLITE_OK );
  33495. /* Now get the read-lock */
  33496. lock.l_start = SHARED_FIRST;
  33497. lock.l_len = SHARED_SIZE;
  33498. if( unixFileLock(pFile, &lock) ){
  33499. tErrno = errno;
  33500. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  33501. }
  33502. /* Drop the temporary PENDING lock */
  33503. lock.l_start = PENDING_BYTE;
  33504. lock.l_len = 1L;
  33505. lock.l_type = F_UNLCK;
  33506. if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
  33507. /* This could happen with a network mount */
  33508. tErrno = errno;
  33509. rc = SQLITE_IOERR_UNLOCK;
  33510. }
  33511. if( rc ){
  33512. if( rc!=SQLITE_BUSY ){
  33513. storeLastErrno(pFile, tErrno);
  33514. }
  33515. goto end_lock;
  33516. }else{
  33517. pFile->eFileLock = SHARED_LOCK;
  33518. pInode->nLock++;
  33519. pInode->nShared = 1;
  33520. }
  33521. }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
  33522. /* We are trying for an exclusive lock but another thread in this
  33523. ** same process is still holding a shared lock. */
  33524. rc = SQLITE_BUSY;
  33525. }else{
  33526. /* The request was for a RESERVED or EXCLUSIVE lock. It is
  33527. ** assumed that there is a SHARED or greater lock on the file
  33528. ** already.
  33529. */
  33530. assert( 0!=pFile->eFileLock );
  33531. lock.l_type = F_WRLCK;
  33532. assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
  33533. if( eFileLock==RESERVED_LOCK ){
  33534. lock.l_start = RESERVED_BYTE;
  33535. lock.l_len = 1L;
  33536. }else{
  33537. lock.l_start = SHARED_FIRST;
  33538. lock.l_len = SHARED_SIZE;
  33539. }
  33540. if( unixFileLock(pFile, &lock) ){
  33541. tErrno = errno;
  33542. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  33543. if( rc!=SQLITE_BUSY ){
  33544. storeLastErrno(pFile, tErrno);
  33545. }
  33546. }
  33547. }
  33548. #ifdef SQLITE_DEBUG
  33549. /* Set up the transaction-counter change checking flags when
  33550. ** transitioning from a SHARED to a RESERVED lock. The change
  33551. ** from SHARED to RESERVED marks the beginning of a normal
  33552. ** write operation (not a hot journal rollback).
  33553. */
  33554. if( rc==SQLITE_OK
  33555. && pFile->eFileLock<=SHARED_LOCK
  33556. && eFileLock==RESERVED_LOCK
  33557. ){
  33558. pFile->transCntrChng = 0;
  33559. pFile->dbUpdate = 0;
  33560. pFile->inNormalWrite = 1;
  33561. }
  33562. #endif
  33563. if( rc==SQLITE_OK ){
  33564. pFile->eFileLock = eFileLock;
  33565. pInode->eFileLock = eFileLock;
  33566. }else if( eFileLock==EXCLUSIVE_LOCK ){
  33567. pFile->eFileLock = PENDING_LOCK;
  33568. pInode->eFileLock = PENDING_LOCK;
  33569. }
  33570. end_lock:
  33571. sqlite3_mutex_leave(pInode->pLockMutex);
  33572. OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
  33573. rc==SQLITE_OK ? "ok" : "failed"));
  33574. return rc;
  33575. }
  33576. /*
  33577. ** Add the file descriptor used by file handle pFile to the corresponding
  33578. ** pUnused list.
  33579. */
  33580. static void setPendingFd(unixFile *pFile){
  33581. unixInodeInfo *pInode = pFile->pInode;
  33582. UnixUnusedFd *p = pFile->pPreallocatedUnused;
  33583. assert( unixFileMutexHeld(pFile) );
  33584. p->pNext = pInode->pUnused;
  33585. pInode->pUnused = p;
  33586. pFile->h = -1;
  33587. pFile->pPreallocatedUnused = 0;
  33588. }
  33589. /*
  33590. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  33591. ** must be either NO_LOCK or SHARED_LOCK.
  33592. **
  33593. ** If the locking level of the file descriptor is already at or below
  33594. ** the requested locking level, this routine is a no-op.
  33595. **
  33596. ** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
  33597. ** the byte range is divided into 2 parts and the first part is unlocked then
  33598. ** set to a read lock, then the other part is simply unlocked. This works
  33599. ** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
  33600. ** remove the write lock on a region when a read lock is set.
  33601. */
  33602. static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
  33603. unixFile *pFile = (unixFile*)id;
  33604. unixInodeInfo *pInode;
  33605. struct flock lock;
  33606. int rc = SQLITE_OK;
  33607. assert( pFile );
  33608. OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
  33609. pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
  33610. osGetpid(0)));
  33611. assert( eFileLock<=SHARED_LOCK );
  33612. if( pFile->eFileLock<=eFileLock ){
  33613. return SQLITE_OK;
  33614. }
  33615. pInode = pFile->pInode;
  33616. sqlite3_mutex_enter(pInode->pLockMutex);
  33617. assert( pInode->nShared!=0 );
  33618. if( pFile->eFileLock>SHARED_LOCK ){
  33619. assert( pInode->eFileLock==pFile->eFileLock );
  33620. #ifdef SQLITE_DEBUG
  33621. /* When reducing a lock such that other processes can start
  33622. ** reading the database file again, make sure that the
  33623. ** transaction counter was updated if any part of the database
  33624. ** file changed. If the transaction counter is not updated,
  33625. ** other connections to the same file might not realize that
  33626. ** the file has changed and hence might not know to flush their
  33627. ** cache. The use of a stale cache can lead to database corruption.
  33628. */
  33629. pFile->inNormalWrite = 0;
  33630. #endif
  33631. /* downgrading to a shared lock on NFS involves clearing the write lock
  33632. ** before establishing the readlock - to avoid a race condition we downgrade
  33633. ** the lock in 2 blocks, so that part of the range will be covered by a
  33634. ** write lock until the rest is covered by a read lock:
  33635. ** 1: [WWWWW]
  33636. ** 2: [....W]
  33637. ** 3: [RRRRW]
  33638. ** 4: [RRRR.]
  33639. */
  33640. if( eFileLock==SHARED_LOCK ){
  33641. #if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
  33642. (void)handleNFSUnlock;
  33643. assert( handleNFSUnlock==0 );
  33644. #endif
  33645. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  33646. if( handleNFSUnlock ){
  33647. int tErrno; /* Error code from system call errors */
  33648. off_t divSize = SHARED_SIZE - 1;
  33649. lock.l_type = F_UNLCK;
  33650. lock.l_whence = SEEK_SET;
  33651. lock.l_start = SHARED_FIRST;
  33652. lock.l_len = divSize;
  33653. if( unixFileLock(pFile, &lock)==(-1) ){
  33654. tErrno = errno;
  33655. rc = SQLITE_IOERR_UNLOCK;
  33656. storeLastErrno(pFile, tErrno);
  33657. goto end_unlock;
  33658. }
  33659. lock.l_type = F_RDLCK;
  33660. lock.l_whence = SEEK_SET;
  33661. lock.l_start = SHARED_FIRST;
  33662. lock.l_len = divSize;
  33663. if( unixFileLock(pFile, &lock)==(-1) ){
  33664. tErrno = errno;
  33665. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
  33666. if( IS_LOCK_ERROR(rc) ){
  33667. storeLastErrno(pFile, tErrno);
  33668. }
  33669. goto end_unlock;
  33670. }
  33671. lock.l_type = F_UNLCK;
  33672. lock.l_whence = SEEK_SET;
  33673. lock.l_start = SHARED_FIRST+divSize;
  33674. lock.l_len = SHARED_SIZE-divSize;
  33675. if( unixFileLock(pFile, &lock)==(-1) ){
  33676. tErrno = errno;
  33677. rc = SQLITE_IOERR_UNLOCK;
  33678. storeLastErrno(pFile, tErrno);
  33679. goto end_unlock;
  33680. }
  33681. }else
  33682. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  33683. {
  33684. lock.l_type = F_RDLCK;
  33685. lock.l_whence = SEEK_SET;
  33686. lock.l_start = SHARED_FIRST;
  33687. lock.l_len = SHARED_SIZE;
  33688. if( unixFileLock(pFile, &lock) ){
  33689. /* In theory, the call to unixFileLock() cannot fail because another
  33690. ** process is holding an incompatible lock. If it does, this
  33691. ** indicates that the other process is not following the locking
  33692. ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
  33693. ** SQLITE_BUSY would confuse the upper layer (in practice it causes
  33694. ** an assert to fail). */
  33695. rc = SQLITE_IOERR_RDLOCK;
  33696. storeLastErrno(pFile, errno);
  33697. goto end_unlock;
  33698. }
  33699. }
  33700. }
  33701. lock.l_type = F_UNLCK;
  33702. lock.l_whence = SEEK_SET;
  33703. lock.l_start = PENDING_BYTE;
  33704. lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
  33705. if( unixFileLock(pFile, &lock)==0 ){
  33706. pInode->eFileLock = SHARED_LOCK;
  33707. }else{
  33708. rc = SQLITE_IOERR_UNLOCK;
  33709. storeLastErrno(pFile, errno);
  33710. goto end_unlock;
  33711. }
  33712. }
  33713. if( eFileLock==NO_LOCK ){
  33714. /* Decrement the shared lock counter. Release the lock using an
  33715. ** OS call only when all threads in this same process have released
  33716. ** the lock.
  33717. */
  33718. pInode->nShared--;
  33719. if( pInode->nShared==0 ){
  33720. lock.l_type = F_UNLCK;
  33721. lock.l_whence = SEEK_SET;
  33722. lock.l_start = lock.l_len = 0L;
  33723. if( unixFileLock(pFile, &lock)==0 ){
  33724. pInode->eFileLock = NO_LOCK;
  33725. }else{
  33726. rc = SQLITE_IOERR_UNLOCK;
  33727. storeLastErrno(pFile, errno);
  33728. pInode->eFileLock = NO_LOCK;
  33729. pFile->eFileLock = NO_LOCK;
  33730. }
  33731. }
  33732. /* Decrement the count of locks against this same file. When the
  33733. ** count reaches zero, close any other file descriptors whose close
  33734. ** was deferred because of outstanding locks.
  33735. */
  33736. pInode->nLock--;
  33737. assert( pInode->nLock>=0 );
  33738. if( pInode->nLock==0 ) closePendingFds(pFile);
  33739. }
  33740. end_unlock:
  33741. sqlite3_mutex_leave(pInode->pLockMutex);
  33742. if( rc==SQLITE_OK ){
  33743. pFile->eFileLock = eFileLock;
  33744. }
  33745. return rc;
  33746. }
  33747. /*
  33748. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  33749. ** must be either NO_LOCK or SHARED_LOCK.
  33750. **
  33751. ** If the locking level of the file descriptor is already at or below
  33752. ** the requested locking level, this routine is a no-op.
  33753. */
  33754. static int unixUnlock(sqlite3_file *id, int eFileLock){
  33755. #if SQLITE_MAX_MMAP_SIZE>0
  33756. assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
  33757. #endif
  33758. return posixUnlock(id, eFileLock, 0);
  33759. }
  33760. #if SQLITE_MAX_MMAP_SIZE>0
  33761. static int unixMapfile(unixFile *pFd, i64 nByte);
  33762. static void unixUnmapfile(unixFile *pFd);
  33763. #endif
  33764. /*
  33765. ** This function performs the parts of the "close file" operation
  33766. ** common to all locking schemes. It closes the directory and file
  33767. ** handles, if they are valid, and sets all fields of the unixFile
  33768. ** structure to 0.
  33769. **
  33770. ** It is *not* necessary to hold the mutex when this routine is called,
  33771. ** even on VxWorks. A mutex will be acquired on VxWorks by the
  33772. ** vxworksReleaseFileId() routine.
  33773. */
  33774. static int closeUnixFile(sqlite3_file *id){
  33775. unixFile *pFile = (unixFile*)id;
  33776. #if SQLITE_MAX_MMAP_SIZE>0
  33777. unixUnmapfile(pFile);
  33778. #endif
  33779. if( pFile->h>=0 ){
  33780. robust_close(pFile, pFile->h, __LINE__);
  33781. pFile->h = -1;
  33782. }
  33783. #if OS_VXWORKS
  33784. if( pFile->pId ){
  33785. if( pFile->ctrlFlags & UNIXFILE_DELETE ){
  33786. osUnlink(pFile->pId->zCanonicalName);
  33787. }
  33788. vxworksReleaseFileId(pFile->pId);
  33789. pFile->pId = 0;
  33790. }
  33791. #endif
  33792. #ifdef SQLITE_UNLINK_AFTER_CLOSE
  33793. if( pFile->ctrlFlags & UNIXFILE_DELETE ){
  33794. osUnlink(pFile->zPath);
  33795. sqlite3_free(*(char**)&pFile->zPath);
  33796. pFile->zPath = 0;
  33797. }
  33798. #endif
  33799. OSTRACE(("CLOSE %-3d\n", pFile->h));
  33800. OpenCounter(-1);
  33801. sqlite3_free(pFile->pPreallocatedUnused);
  33802. memset(pFile, 0, sizeof(unixFile));
  33803. return SQLITE_OK;
  33804. }
  33805. /*
  33806. ** Close a file.
  33807. */
  33808. static int unixClose(sqlite3_file *id){
  33809. int rc = SQLITE_OK;
  33810. unixFile *pFile = (unixFile *)id;
  33811. unixInodeInfo *pInode = pFile->pInode;
  33812. assert( pInode!=0 );
  33813. verifyDbFile(pFile);
  33814. unixUnlock(id, NO_LOCK);
  33815. assert( unixFileMutexNotheld(pFile) );
  33816. unixEnterMutex();
  33817. /* unixFile.pInode is always valid here. Otherwise, a different close
  33818. ** routine (e.g. nolockClose()) would be called instead.
  33819. */
  33820. assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
  33821. sqlite3_mutex_enter(pInode->pLockMutex);
  33822. if( pInode->nLock ){
  33823. /* If there are outstanding locks, do not actually close the file just
  33824. ** yet because that would clear those locks. Instead, add the file
  33825. ** descriptor to pInode->pUnused list. It will be automatically closed
  33826. ** when the last lock is cleared.
  33827. */
  33828. setPendingFd(pFile);
  33829. }
  33830. sqlite3_mutex_leave(pInode->pLockMutex);
  33831. releaseInodeInfo(pFile);
  33832. rc = closeUnixFile(id);
  33833. unixLeaveMutex();
  33834. return rc;
  33835. }
  33836. /************** End of the posix advisory lock implementation *****************
  33837. ******************************************************************************/
  33838. /******************************************************************************
  33839. ****************************** No-op Locking **********************************
  33840. **
  33841. ** Of the various locking implementations available, this is by far the
  33842. ** simplest: locking is ignored. No attempt is made to lock the database
  33843. ** file for reading or writing.
  33844. **
  33845. ** This locking mode is appropriate for use on read-only databases
  33846. ** (ex: databases that are burned into CD-ROM, for example.) It can
  33847. ** also be used if the application employs some external mechanism to
  33848. ** prevent simultaneous access of the same database by two or more
  33849. ** database connections. But there is a serious risk of database
  33850. ** corruption if this locking mode is used in situations where multiple
  33851. ** database connections are accessing the same database file at the same
  33852. ** time and one or more of those connections are writing.
  33853. */
  33854. static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
  33855. UNUSED_PARAMETER(NotUsed);
  33856. *pResOut = 0;
  33857. return SQLITE_OK;
  33858. }
  33859. static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
  33860. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  33861. return SQLITE_OK;
  33862. }
  33863. static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
  33864. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  33865. return SQLITE_OK;
  33866. }
  33867. /*
  33868. ** Close the file.
  33869. */
  33870. static int nolockClose(sqlite3_file *id) {
  33871. return closeUnixFile(id);
  33872. }
  33873. /******************* End of the no-op lock implementation *********************
  33874. ******************************************************************************/
  33875. /******************************************************************************
  33876. ************************* Begin dot-file Locking ******************************
  33877. **
  33878. ** The dotfile locking implementation uses the existence of separate lock
  33879. ** files (really a directory) to control access to the database. This works
  33880. ** on just about every filesystem imaginable. But there are serious downsides:
  33881. **
  33882. ** (1) There is zero concurrency. A single reader blocks all other
  33883. ** connections from reading or writing the database.
  33884. **
  33885. ** (2) An application crash or power loss can leave stale lock files
  33886. ** sitting around that need to be cleared manually.
  33887. **
  33888. ** Nevertheless, a dotlock is an appropriate locking mode for use if no
  33889. ** other locking strategy is available.
  33890. **
  33891. ** Dotfile locking works by creating a subdirectory in the same directory as
  33892. ** the database and with the same name but with a ".lock" extension added.
  33893. ** The existence of a lock directory implies an EXCLUSIVE lock. All other
  33894. ** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
  33895. */
  33896. /*
  33897. ** The file suffix added to the data base filename in order to create the
  33898. ** lock directory.
  33899. */
  33900. #define DOTLOCK_SUFFIX ".lock"
  33901. /*
  33902. ** This routine checks if there is a RESERVED lock held on the specified
  33903. ** file by this or any other process. If such a lock is held, set *pResOut
  33904. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  33905. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  33906. **
  33907. ** In dotfile locking, either a lock exists or it does not. So in this
  33908. ** variation of CheckReservedLock(), *pResOut is set to true if any lock
  33909. ** is held on the file and false if the file is unlocked.
  33910. */
  33911. static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
  33912. int rc = SQLITE_OK;
  33913. int reserved = 0;
  33914. unixFile *pFile = (unixFile*)id;
  33915. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  33916. assert( pFile );
  33917. reserved = osAccess((const char*)pFile->lockingContext, 0)==0;
  33918. OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
  33919. *pResOut = reserved;
  33920. return rc;
  33921. }
  33922. /*
  33923. ** Lock the file with the lock specified by parameter eFileLock - one
  33924. ** of the following:
  33925. **
  33926. ** (1) SHARED_LOCK
  33927. ** (2) RESERVED_LOCK
  33928. ** (3) PENDING_LOCK
  33929. ** (4) EXCLUSIVE_LOCK
  33930. **
  33931. ** Sometimes when requesting one lock state, additional lock states
  33932. ** are inserted in between. The locking might fail on one of the later
  33933. ** transitions leaving the lock state different from what it started but
  33934. ** still short of its goal. The following chart shows the allowed
  33935. ** transitions and the inserted intermediate states:
  33936. **
  33937. ** UNLOCKED -> SHARED
  33938. ** SHARED -> RESERVED
  33939. ** SHARED -> (PENDING) -> EXCLUSIVE
  33940. ** RESERVED -> (PENDING) -> EXCLUSIVE
  33941. ** PENDING -> EXCLUSIVE
  33942. **
  33943. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  33944. ** routine to lower a locking level.
  33945. **
  33946. ** With dotfile locking, we really only support state (4): EXCLUSIVE.
  33947. ** But we track the other locking levels internally.
  33948. */
  33949. static int dotlockLock(sqlite3_file *id, int eFileLock) {
  33950. unixFile *pFile = (unixFile*)id;
  33951. char *zLockFile = (char *)pFile->lockingContext;
  33952. int rc = SQLITE_OK;
  33953. /* If we have any lock, then the lock file already exists. All we have
  33954. ** to do is adjust our internal record of the lock level.
  33955. */
  33956. if( pFile->eFileLock > NO_LOCK ){
  33957. pFile->eFileLock = eFileLock;
  33958. /* Always update the timestamp on the old file */
  33959. #ifdef HAVE_UTIME
  33960. utime(zLockFile, NULL);
  33961. #else
  33962. utimes(zLockFile, NULL);
  33963. #endif
  33964. return SQLITE_OK;
  33965. }
  33966. /* grab an exclusive lock */
  33967. rc = osMkdir(zLockFile, 0777);
  33968. if( rc<0 ){
  33969. /* failed to open/create the lock directory */
  33970. int tErrno = errno;
  33971. if( EEXIST == tErrno ){
  33972. rc = SQLITE_BUSY;
  33973. } else {
  33974. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  33975. if( rc!=SQLITE_BUSY ){
  33976. storeLastErrno(pFile, tErrno);
  33977. }
  33978. }
  33979. return rc;
  33980. }
  33981. /* got it, set the type and return ok */
  33982. pFile->eFileLock = eFileLock;
  33983. return rc;
  33984. }
  33985. /*
  33986. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  33987. ** must be either NO_LOCK or SHARED_LOCK.
  33988. **
  33989. ** If the locking level of the file descriptor is already at or below
  33990. ** the requested locking level, this routine is a no-op.
  33991. **
  33992. ** When the locking level reaches NO_LOCK, delete the lock file.
  33993. */
  33994. static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
  33995. unixFile *pFile = (unixFile*)id;
  33996. char *zLockFile = (char *)pFile->lockingContext;
  33997. int rc;
  33998. assert( pFile );
  33999. OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
  34000. pFile->eFileLock, osGetpid(0)));
  34001. assert( eFileLock<=SHARED_LOCK );
  34002. /* no-op if possible */
  34003. if( pFile->eFileLock==eFileLock ){
  34004. return SQLITE_OK;
  34005. }
  34006. /* To downgrade to shared, simply update our internal notion of the
  34007. ** lock state. No need to mess with the file on disk.
  34008. */
  34009. if( eFileLock==SHARED_LOCK ){
  34010. pFile->eFileLock = SHARED_LOCK;
  34011. return SQLITE_OK;
  34012. }
  34013. /* To fully unlock the database, delete the lock file */
  34014. assert( eFileLock==NO_LOCK );
  34015. rc = osRmdir(zLockFile);
  34016. if( rc<0 ){
  34017. int tErrno = errno;
  34018. if( tErrno==ENOENT ){
  34019. rc = SQLITE_OK;
  34020. }else{
  34021. rc = SQLITE_IOERR_UNLOCK;
  34022. storeLastErrno(pFile, tErrno);
  34023. }
  34024. return rc;
  34025. }
  34026. pFile->eFileLock = NO_LOCK;
  34027. return SQLITE_OK;
  34028. }
  34029. /*
  34030. ** Close a file. Make sure the lock has been released before closing.
  34031. */
  34032. static int dotlockClose(sqlite3_file *id) {
  34033. unixFile *pFile = (unixFile*)id;
  34034. assert( id!=0 );
  34035. dotlockUnlock(id, NO_LOCK);
  34036. sqlite3_free(pFile->lockingContext);
  34037. return closeUnixFile(id);
  34038. }
  34039. /****************** End of the dot-file lock implementation *******************
  34040. ******************************************************************************/
  34041. /******************************************************************************
  34042. ************************** Begin flock Locking ********************************
  34043. **
  34044. ** Use the flock() system call to do file locking.
  34045. **
  34046. ** flock() locking is like dot-file locking in that the various
  34047. ** fine-grain locking levels supported by SQLite are collapsed into
  34048. ** a single exclusive lock. In other words, SHARED, RESERVED, and
  34049. ** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
  34050. ** still works when you do this, but concurrency is reduced since
  34051. ** only a single process can be reading the database at a time.
  34052. **
  34053. ** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off
  34054. */
  34055. #if SQLITE_ENABLE_LOCKING_STYLE
  34056. /*
  34057. ** Retry flock() calls that fail with EINTR
  34058. */
  34059. #ifdef EINTR
  34060. static int robust_flock(int fd, int op){
  34061. int rc;
  34062. do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
  34063. return rc;
  34064. }
  34065. #else
  34066. # define robust_flock(a,b) flock(a,b)
  34067. #endif
  34068. /*
  34069. ** This routine checks if there is a RESERVED lock held on the specified
  34070. ** file by this or any other process. If such a lock is held, set *pResOut
  34071. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  34072. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  34073. */
  34074. static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
  34075. int rc = SQLITE_OK;
  34076. int reserved = 0;
  34077. unixFile *pFile = (unixFile*)id;
  34078. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  34079. assert( pFile );
  34080. /* Check if a thread in this process holds such a lock */
  34081. if( pFile->eFileLock>SHARED_LOCK ){
  34082. reserved = 1;
  34083. }
  34084. /* Otherwise see if some other process holds it. */
  34085. if( !reserved ){
  34086. /* attempt to get the lock */
  34087. int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
  34088. if( !lrc ){
  34089. /* got the lock, unlock it */
  34090. lrc = robust_flock(pFile->h, LOCK_UN);
  34091. if ( lrc ) {
  34092. int tErrno = errno;
  34093. /* unlock failed with an error */
  34094. lrc = SQLITE_IOERR_UNLOCK;
  34095. storeLastErrno(pFile, tErrno);
  34096. rc = lrc;
  34097. }
  34098. } else {
  34099. int tErrno = errno;
  34100. reserved = 1;
  34101. /* someone else might have it reserved */
  34102. lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  34103. if( IS_LOCK_ERROR(lrc) ){
  34104. storeLastErrno(pFile, tErrno);
  34105. rc = lrc;
  34106. }
  34107. }
  34108. }
  34109. OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
  34110. #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  34111. if( (rc & 0xff) == SQLITE_IOERR ){
  34112. rc = SQLITE_OK;
  34113. reserved=1;
  34114. }
  34115. #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
  34116. *pResOut = reserved;
  34117. return rc;
  34118. }
  34119. /*
  34120. ** Lock the file with the lock specified by parameter eFileLock - one
  34121. ** of the following:
  34122. **
  34123. ** (1) SHARED_LOCK
  34124. ** (2) RESERVED_LOCK
  34125. ** (3) PENDING_LOCK
  34126. ** (4) EXCLUSIVE_LOCK
  34127. **
  34128. ** Sometimes when requesting one lock state, additional lock states
  34129. ** are inserted in between. The locking might fail on one of the later
  34130. ** transitions leaving the lock state different from what it started but
  34131. ** still short of its goal. The following chart shows the allowed
  34132. ** transitions and the inserted intermediate states:
  34133. **
  34134. ** UNLOCKED -> SHARED
  34135. ** SHARED -> RESERVED
  34136. ** SHARED -> (PENDING) -> EXCLUSIVE
  34137. ** RESERVED -> (PENDING) -> EXCLUSIVE
  34138. ** PENDING -> EXCLUSIVE
  34139. **
  34140. ** flock() only really support EXCLUSIVE locks. We track intermediate
  34141. ** lock states in the sqlite3_file structure, but all locks SHARED or
  34142. ** above are really EXCLUSIVE locks and exclude all other processes from
  34143. ** access the file.
  34144. **
  34145. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  34146. ** routine to lower a locking level.
  34147. */
  34148. static int flockLock(sqlite3_file *id, int eFileLock) {
  34149. int rc = SQLITE_OK;
  34150. unixFile *pFile = (unixFile*)id;
  34151. assert( pFile );
  34152. /* if we already have a lock, it is exclusive.
  34153. ** Just adjust level and punt on outta here. */
  34154. if (pFile->eFileLock > NO_LOCK) {
  34155. pFile->eFileLock = eFileLock;
  34156. return SQLITE_OK;
  34157. }
  34158. /* grab an exclusive lock */
  34159. if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
  34160. int tErrno = errno;
  34161. /* didn't get, must be busy */
  34162. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  34163. if( IS_LOCK_ERROR(rc) ){
  34164. storeLastErrno(pFile, tErrno);
  34165. }
  34166. } else {
  34167. /* got it, set the type and return ok */
  34168. pFile->eFileLock = eFileLock;
  34169. }
  34170. OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
  34171. rc==SQLITE_OK ? "ok" : "failed"));
  34172. #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  34173. if( (rc & 0xff) == SQLITE_IOERR ){
  34174. rc = SQLITE_BUSY;
  34175. }
  34176. #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
  34177. return rc;
  34178. }
  34179. /*
  34180. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  34181. ** must be either NO_LOCK or SHARED_LOCK.
  34182. **
  34183. ** If the locking level of the file descriptor is already at or below
  34184. ** the requested locking level, this routine is a no-op.
  34185. */
  34186. static int flockUnlock(sqlite3_file *id, int eFileLock) {
  34187. unixFile *pFile = (unixFile*)id;
  34188. assert( pFile );
  34189. OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
  34190. pFile->eFileLock, osGetpid(0)));
  34191. assert( eFileLock<=SHARED_LOCK );
  34192. /* no-op if possible */
  34193. if( pFile->eFileLock==eFileLock ){
  34194. return SQLITE_OK;
  34195. }
  34196. /* shared can just be set because we always have an exclusive */
  34197. if (eFileLock==SHARED_LOCK) {
  34198. pFile->eFileLock = eFileLock;
  34199. return SQLITE_OK;
  34200. }
  34201. /* no, really, unlock. */
  34202. if( robust_flock(pFile->h, LOCK_UN) ){
  34203. #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  34204. return SQLITE_OK;
  34205. #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
  34206. return SQLITE_IOERR_UNLOCK;
  34207. }else{
  34208. pFile->eFileLock = NO_LOCK;
  34209. return SQLITE_OK;
  34210. }
  34211. }
  34212. /*
  34213. ** Close a file.
  34214. */
  34215. static int flockClose(sqlite3_file *id) {
  34216. assert( id!=0 );
  34217. flockUnlock(id, NO_LOCK);
  34218. return closeUnixFile(id);
  34219. }
  34220. #endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
  34221. /******************* End of the flock lock implementation *********************
  34222. ******************************************************************************/
  34223. /******************************************************************************
  34224. ************************ Begin Named Semaphore Locking ************************
  34225. **
  34226. ** Named semaphore locking is only supported on VxWorks.
  34227. **
  34228. ** Semaphore locking is like dot-lock and flock in that it really only
  34229. ** supports EXCLUSIVE locking. Only a single process can read or write
  34230. ** the database file at a time. This reduces potential concurrency, but
  34231. ** makes the lock implementation much easier.
  34232. */
  34233. #if OS_VXWORKS
  34234. /*
  34235. ** This routine checks if there is a RESERVED lock held on the specified
  34236. ** file by this or any other process. If such a lock is held, set *pResOut
  34237. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  34238. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  34239. */
  34240. static int semXCheckReservedLock(sqlite3_file *id, int *pResOut) {
  34241. int rc = SQLITE_OK;
  34242. int reserved = 0;
  34243. unixFile *pFile = (unixFile*)id;
  34244. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  34245. assert( pFile );
  34246. /* Check if a thread in this process holds such a lock */
  34247. if( pFile->eFileLock>SHARED_LOCK ){
  34248. reserved = 1;
  34249. }
  34250. /* Otherwise see if some other process holds it. */
  34251. if( !reserved ){
  34252. sem_t *pSem = pFile->pInode->pSem;
  34253. if( sem_trywait(pSem)==-1 ){
  34254. int tErrno = errno;
  34255. if( EAGAIN != tErrno ){
  34256. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
  34257. storeLastErrno(pFile, tErrno);
  34258. } else {
  34259. /* someone else has the lock when we are in NO_LOCK */
  34260. reserved = (pFile->eFileLock < SHARED_LOCK);
  34261. }
  34262. }else{
  34263. /* we could have it if we want it */
  34264. sem_post(pSem);
  34265. }
  34266. }
  34267. OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
  34268. *pResOut = reserved;
  34269. return rc;
  34270. }
  34271. /*
  34272. ** Lock the file with the lock specified by parameter eFileLock - one
  34273. ** of the following:
  34274. **
  34275. ** (1) SHARED_LOCK
  34276. ** (2) RESERVED_LOCK
  34277. ** (3) PENDING_LOCK
  34278. ** (4) EXCLUSIVE_LOCK
  34279. **
  34280. ** Sometimes when requesting one lock state, additional lock states
  34281. ** are inserted in between. The locking might fail on one of the later
  34282. ** transitions leaving the lock state different from what it started but
  34283. ** still short of its goal. The following chart shows the allowed
  34284. ** transitions and the inserted intermediate states:
  34285. **
  34286. ** UNLOCKED -> SHARED
  34287. ** SHARED -> RESERVED
  34288. ** SHARED -> (PENDING) -> EXCLUSIVE
  34289. ** RESERVED -> (PENDING) -> EXCLUSIVE
  34290. ** PENDING -> EXCLUSIVE
  34291. **
  34292. ** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
  34293. ** lock states in the sqlite3_file structure, but all locks SHARED or
  34294. ** above are really EXCLUSIVE locks and exclude all other processes from
  34295. ** access the file.
  34296. **
  34297. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  34298. ** routine to lower a locking level.
  34299. */
  34300. static int semXLock(sqlite3_file *id, int eFileLock) {
  34301. unixFile *pFile = (unixFile*)id;
  34302. sem_t *pSem = pFile->pInode->pSem;
  34303. int rc = SQLITE_OK;
  34304. /* if we already have a lock, it is exclusive.
  34305. ** Just adjust level and punt on outta here. */
  34306. if (pFile->eFileLock > NO_LOCK) {
  34307. pFile->eFileLock = eFileLock;
  34308. rc = SQLITE_OK;
  34309. goto sem_end_lock;
  34310. }
  34311. /* lock semaphore now but bail out when already locked. */
  34312. if( sem_trywait(pSem)==-1 ){
  34313. rc = SQLITE_BUSY;
  34314. goto sem_end_lock;
  34315. }
  34316. /* got it, set the type and return ok */
  34317. pFile->eFileLock = eFileLock;
  34318. sem_end_lock:
  34319. return rc;
  34320. }
  34321. /*
  34322. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  34323. ** must be either NO_LOCK or SHARED_LOCK.
  34324. **
  34325. ** If the locking level of the file descriptor is already at or below
  34326. ** the requested locking level, this routine is a no-op.
  34327. */
  34328. static int semXUnlock(sqlite3_file *id, int eFileLock) {
  34329. unixFile *pFile = (unixFile*)id;
  34330. sem_t *pSem = pFile->pInode->pSem;
  34331. assert( pFile );
  34332. assert( pSem );
  34333. OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
  34334. pFile->eFileLock, osGetpid(0)));
  34335. assert( eFileLock<=SHARED_LOCK );
  34336. /* no-op if possible */
  34337. if( pFile->eFileLock==eFileLock ){
  34338. return SQLITE_OK;
  34339. }
  34340. /* shared can just be set because we always have an exclusive */
  34341. if (eFileLock==SHARED_LOCK) {
  34342. pFile->eFileLock = eFileLock;
  34343. return SQLITE_OK;
  34344. }
  34345. /* no, really unlock. */
  34346. if ( sem_post(pSem)==-1 ) {
  34347. int rc, tErrno = errno;
  34348. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
  34349. if( IS_LOCK_ERROR(rc) ){
  34350. storeLastErrno(pFile, tErrno);
  34351. }
  34352. return rc;
  34353. }
  34354. pFile->eFileLock = NO_LOCK;
  34355. return SQLITE_OK;
  34356. }
  34357. /*
  34358. ** Close a file.
  34359. */
  34360. static int semXClose(sqlite3_file *id) {
  34361. if( id ){
  34362. unixFile *pFile = (unixFile*)id;
  34363. semXUnlock(id, NO_LOCK);
  34364. assert( pFile );
  34365. assert( unixFileMutexNotheld(pFile) );
  34366. unixEnterMutex();
  34367. releaseInodeInfo(pFile);
  34368. unixLeaveMutex();
  34369. closeUnixFile(id);
  34370. }
  34371. return SQLITE_OK;
  34372. }
  34373. #endif /* OS_VXWORKS */
  34374. /*
  34375. ** Named semaphore locking is only available on VxWorks.
  34376. **
  34377. *************** End of the named semaphore lock implementation ****************
  34378. ******************************************************************************/
  34379. /******************************************************************************
  34380. *************************** Begin AFP Locking *********************************
  34381. **
  34382. ** AFP is the Apple Filing Protocol. AFP is a network filesystem found
  34383. ** on Apple Macintosh computers - both OS9 and OSX.
  34384. **
  34385. ** Third-party implementations of AFP are available. But this code here
  34386. ** only works on OSX.
  34387. */
  34388. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  34389. /*
  34390. ** The afpLockingContext structure contains all afp lock specific state
  34391. */
  34392. typedef struct afpLockingContext afpLockingContext;
  34393. struct afpLockingContext {
  34394. int reserved;
  34395. const char *dbPath; /* Name of the open file */
  34396. };
  34397. struct ByteRangeLockPB2
  34398. {
  34399. unsigned long long offset; /* offset to first byte to lock */
  34400. unsigned long long length; /* nbr of bytes to lock */
  34401. unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
  34402. unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
  34403. unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
  34404. int fd; /* file desc to assoc this lock with */
  34405. };
  34406. #define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
  34407. /*
  34408. ** This is a utility for setting or clearing a bit-range lock on an
  34409. ** AFP filesystem.
  34410. **
  34411. ** Return SQLITE_OK on success, SQLITE_BUSY on failure.
  34412. */
  34413. static int afpSetLock(
  34414. const char *path, /* Name of the file to be locked or unlocked */
  34415. unixFile *pFile, /* Open file descriptor on path */
  34416. unsigned long long offset, /* First byte to be locked */
  34417. unsigned long long length, /* Number of bytes to lock */
  34418. int setLockFlag /* True to set lock. False to clear lock */
  34419. ){
  34420. struct ByteRangeLockPB2 pb;
  34421. int err;
  34422. pb.unLockFlag = setLockFlag ? 0 : 1;
  34423. pb.startEndFlag = 0;
  34424. pb.offset = offset;
  34425. pb.length = length;
  34426. pb.fd = pFile->h;
  34427. OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
  34428. (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
  34429. offset, length));
  34430. err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
  34431. if ( err==-1 ) {
  34432. int rc;
  34433. int tErrno = errno;
  34434. OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
  34435. path, tErrno, strerror(tErrno)));
  34436. #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
  34437. rc = SQLITE_BUSY;
  34438. #else
  34439. rc = sqliteErrorFromPosixError(tErrno,
  34440. setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
  34441. #endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
  34442. if( IS_LOCK_ERROR(rc) ){
  34443. storeLastErrno(pFile, tErrno);
  34444. }
  34445. return rc;
  34446. } else {
  34447. return SQLITE_OK;
  34448. }
  34449. }
  34450. /*
  34451. ** This routine checks if there is a RESERVED lock held on the specified
  34452. ** file by this or any other process. If such a lock is held, set *pResOut
  34453. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  34454. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  34455. */
  34456. static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
  34457. int rc = SQLITE_OK;
  34458. int reserved = 0;
  34459. unixFile *pFile = (unixFile*)id;
  34460. afpLockingContext *context;
  34461. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  34462. assert( pFile );
  34463. context = (afpLockingContext *) pFile->lockingContext;
  34464. if( context->reserved ){
  34465. *pResOut = 1;
  34466. return SQLITE_OK;
  34467. }
  34468. sqlite3_mutex_enter(pFile->pInode->pLockMutex);
  34469. /* Check if a thread in this process holds such a lock */
  34470. if( pFile->pInode->eFileLock>SHARED_LOCK ){
  34471. reserved = 1;
  34472. }
  34473. /* Otherwise see if some other process holds it.
  34474. */
  34475. if( !reserved ){
  34476. /* lock the RESERVED byte */
  34477. int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
  34478. if( SQLITE_OK==lrc ){
  34479. /* if we succeeded in taking the reserved lock, unlock it to restore
  34480. ** the original state */
  34481. lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
  34482. } else {
  34483. /* if we failed to get the lock then someone else must have it */
  34484. reserved = 1;
  34485. }
  34486. if( IS_LOCK_ERROR(lrc) ){
  34487. rc=lrc;
  34488. }
  34489. }
  34490. sqlite3_mutex_leave(pFile->pInode->pLockMutex);
  34491. OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
  34492. *pResOut = reserved;
  34493. return rc;
  34494. }
  34495. /*
  34496. ** Lock the file with the lock specified by parameter eFileLock - one
  34497. ** of the following:
  34498. **
  34499. ** (1) SHARED_LOCK
  34500. ** (2) RESERVED_LOCK
  34501. ** (3) PENDING_LOCK
  34502. ** (4) EXCLUSIVE_LOCK
  34503. **
  34504. ** Sometimes when requesting one lock state, additional lock states
  34505. ** are inserted in between. The locking might fail on one of the later
  34506. ** transitions leaving the lock state different from what it started but
  34507. ** still short of its goal. The following chart shows the allowed
  34508. ** transitions and the inserted intermediate states:
  34509. **
  34510. ** UNLOCKED -> SHARED
  34511. ** SHARED -> RESERVED
  34512. ** SHARED -> (PENDING) -> EXCLUSIVE
  34513. ** RESERVED -> (PENDING) -> EXCLUSIVE
  34514. ** PENDING -> EXCLUSIVE
  34515. **
  34516. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  34517. ** routine to lower a locking level.
  34518. */
  34519. static int afpLock(sqlite3_file *id, int eFileLock){
  34520. int rc = SQLITE_OK;
  34521. unixFile *pFile = (unixFile*)id;
  34522. unixInodeInfo *pInode = pFile->pInode;
  34523. afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
  34524. assert( pFile );
  34525. OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
  34526. azFileLock(eFileLock), azFileLock(pFile->eFileLock),
  34527. azFileLock(pInode->eFileLock), pInode->nShared , osGetpid(0)));
  34528. /* If there is already a lock of this type or more restrictive on the
  34529. ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
  34530. ** unixEnterMutex() hasn't been called yet.
  34531. */
  34532. if( pFile->eFileLock>=eFileLock ){
  34533. OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
  34534. azFileLock(eFileLock)));
  34535. return SQLITE_OK;
  34536. }
  34537. /* Make sure the locking sequence is correct
  34538. ** (1) We never move from unlocked to anything higher than shared lock.
  34539. ** (2) SQLite never explicitly requests a pendig lock.
  34540. ** (3) A shared lock is always held when a reserve lock is requested.
  34541. */
  34542. assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
  34543. assert( eFileLock!=PENDING_LOCK );
  34544. assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
  34545. /* This mutex is needed because pFile->pInode is shared across threads
  34546. */
  34547. pInode = pFile->pInode;
  34548. sqlite3_mutex_enter(pInode->pLockMutex);
  34549. /* If some thread using this PID has a lock via a different unixFile*
  34550. ** handle that precludes the requested lock, return BUSY.
  34551. */
  34552. if( (pFile->eFileLock!=pInode->eFileLock &&
  34553. (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
  34554. ){
  34555. rc = SQLITE_BUSY;
  34556. goto afp_end_lock;
  34557. }
  34558. /* If a SHARED lock is requested, and some thread using this PID already
  34559. ** has a SHARED or RESERVED lock, then increment reference counts and
  34560. ** return SQLITE_OK.
  34561. */
  34562. if( eFileLock==SHARED_LOCK &&
  34563. (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
  34564. assert( eFileLock==SHARED_LOCK );
  34565. assert( pFile->eFileLock==0 );
  34566. assert( pInode->nShared>0 );
  34567. pFile->eFileLock = SHARED_LOCK;
  34568. pInode->nShared++;
  34569. pInode->nLock++;
  34570. goto afp_end_lock;
  34571. }
  34572. /* A PENDING lock is needed before acquiring a SHARED lock and before
  34573. ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
  34574. ** be released.
  34575. */
  34576. if( eFileLock==SHARED_LOCK
  34577. || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
  34578. ){
  34579. int failed;
  34580. failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
  34581. if (failed) {
  34582. rc = failed;
  34583. goto afp_end_lock;
  34584. }
  34585. }
  34586. /* If control gets to this point, then actually go ahead and make
  34587. ** operating system calls for the specified lock.
  34588. */
  34589. if( eFileLock==SHARED_LOCK ){
  34590. int lrc1, lrc2, lrc1Errno = 0;
  34591. long lk, mask;
  34592. assert( pInode->nShared==0 );
  34593. assert( pInode->eFileLock==0 );
  34594. mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
  34595. /* Now get the read-lock SHARED_LOCK */
  34596. /* note that the quality of the randomness doesn't matter that much */
  34597. lk = random();
  34598. pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
  34599. lrc1 = afpSetLock(context->dbPath, pFile,
  34600. SHARED_FIRST+pInode->sharedByte, 1, 1);
  34601. if( IS_LOCK_ERROR(lrc1) ){
  34602. lrc1Errno = pFile->lastErrno;
  34603. }
  34604. /* Drop the temporary PENDING lock */
  34605. lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
  34606. if( IS_LOCK_ERROR(lrc1) ) {
  34607. storeLastErrno(pFile, lrc1Errno);
  34608. rc = lrc1;
  34609. goto afp_end_lock;
  34610. } else if( IS_LOCK_ERROR(lrc2) ){
  34611. rc = lrc2;
  34612. goto afp_end_lock;
  34613. } else if( lrc1 != SQLITE_OK ) {
  34614. rc = lrc1;
  34615. } else {
  34616. pFile->eFileLock = SHARED_LOCK;
  34617. pInode->nLock++;
  34618. pInode->nShared = 1;
  34619. }
  34620. }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
  34621. /* We are trying for an exclusive lock but another thread in this
  34622. ** same process is still holding a shared lock. */
  34623. rc = SQLITE_BUSY;
  34624. }else{
  34625. /* The request was for a RESERVED or EXCLUSIVE lock. It is
  34626. ** assumed that there is a SHARED or greater lock on the file
  34627. ** already.
  34628. */
  34629. int failed = 0;
  34630. assert( 0!=pFile->eFileLock );
  34631. if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
  34632. /* Acquire a RESERVED lock */
  34633. failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
  34634. if( !failed ){
  34635. context->reserved = 1;
  34636. }
  34637. }
  34638. if (!failed && eFileLock == EXCLUSIVE_LOCK) {
  34639. /* Acquire an EXCLUSIVE lock */
  34640. /* Remove the shared lock before trying the range. we'll need to
  34641. ** reestablish the shared lock if we can't get the afpUnlock
  34642. */
  34643. if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
  34644. pInode->sharedByte, 1, 0)) ){
  34645. int failed2 = SQLITE_OK;
  34646. /* now attemmpt to get the exclusive lock range */
  34647. failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
  34648. SHARED_SIZE, 1);
  34649. if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
  34650. SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
  34651. /* Can't reestablish the shared lock. Sqlite can't deal, this is
  34652. ** a critical I/O error
  34653. */
  34654. rc = ((failed & 0xff) == SQLITE_IOERR) ? failed2 :
  34655. SQLITE_IOERR_LOCK;
  34656. goto afp_end_lock;
  34657. }
  34658. }else{
  34659. rc = failed;
  34660. }
  34661. }
  34662. if( failed ){
  34663. rc = failed;
  34664. }
  34665. }
  34666. if( rc==SQLITE_OK ){
  34667. pFile->eFileLock = eFileLock;
  34668. pInode->eFileLock = eFileLock;
  34669. }else if( eFileLock==EXCLUSIVE_LOCK ){
  34670. pFile->eFileLock = PENDING_LOCK;
  34671. pInode->eFileLock = PENDING_LOCK;
  34672. }
  34673. afp_end_lock:
  34674. sqlite3_mutex_leave(pInode->pLockMutex);
  34675. OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
  34676. rc==SQLITE_OK ? "ok" : "failed"));
  34677. return rc;
  34678. }
  34679. /*
  34680. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  34681. ** must be either NO_LOCK or SHARED_LOCK.
  34682. **
  34683. ** If the locking level of the file descriptor is already at or below
  34684. ** the requested locking level, this routine is a no-op.
  34685. */
  34686. static int afpUnlock(sqlite3_file *id, int eFileLock) {
  34687. int rc = SQLITE_OK;
  34688. unixFile *pFile = (unixFile*)id;
  34689. unixInodeInfo *pInode;
  34690. afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
  34691. int skipShared = 0;
  34692. #ifdef SQLITE_TEST
  34693. int h = pFile->h;
  34694. #endif
  34695. assert( pFile );
  34696. OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
  34697. pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
  34698. osGetpid(0)));
  34699. assert( eFileLock<=SHARED_LOCK );
  34700. if( pFile->eFileLock<=eFileLock ){
  34701. return SQLITE_OK;
  34702. }
  34703. pInode = pFile->pInode;
  34704. sqlite3_mutex_enter(pInode->pLockMutex);
  34705. assert( pInode->nShared!=0 );
  34706. if( pFile->eFileLock>SHARED_LOCK ){
  34707. assert( pInode->eFileLock==pFile->eFileLock );
  34708. SimulateIOErrorBenign(1);
  34709. SimulateIOError( h=(-1) )
  34710. SimulateIOErrorBenign(0);
  34711. #ifdef SQLITE_DEBUG
  34712. /* When reducing a lock such that other processes can start
  34713. ** reading the database file again, make sure that the
  34714. ** transaction counter was updated if any part of the database
  34715. ** file changed. If the transaction counter is not updated,
  34716. ** other connections to the same file might not realize that
  34717. ** the file has changed and hence might not know to flush their
  34718. ** cache. The use of a stale cache can lead to database corruption.
  34719. */
  34720. assert( pFile->inNormalWrite==0
  34721. || pFile->dbUpdate==0
  34722. || pFile->transCntrChng==1 );
  34723. pFile->inNormalWrite = 0;
  34724. #endif
  34725. if( pFile->eFileLock==EXCLUSIVE_LOCK ){
  34726. rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
  34727. if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
  34728. /* only re-establish the shared lock if necessary */
  34729. int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
  34730. rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
  34731. } else {
  34732. skipShared = 1;
  34733. }
  34734. }
  34735. if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
  34736. rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
  34737. }
  34738. if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
  34739. rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
  34740. if( !rc ){
  34741. context->reserved = 0;
  34742. }
  34743. }
  34744. if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
  34745. pInode->eFileLock = SHARED_LOCK;
  34746. }
  34747. }
  34748. if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
  34749. /* Decrement the shared lock counter. Release the lock using an
  34750. ** OS call only when all threads in this same process have released
  34751. ** the lock.
  34752. */
  34753. unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
  34754. pInode->nShared--;
  34755. if( pInode->nShared==0 ){
  34756. SimulateIOErrorBenign(1);
  34757. SimulateIOError( h=(-1) )
  34758. SimulateIOErrorBenign(0);
  34759. if( !skipShared ){
  34760. rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
  34761. }
  34762. if( !rc ){
  34763. pInode->eFileLock = NO_LOCK;
  34764. pFile->eFileLock = NO_LOCK;
  34765. }
  34766. }
  34767. if( rc==SQLITE_OK ){
  34768. pInode->nLock--;
  34769. assert( pInode->nLock>=0 );
  34770. if( pInode->nLock==0 ) closePendingFds(pFile);
  34771. }
  34772. }
  34773. sqlite3_mutex_leave(pInode->pLockMutex);
  34774. if( rc==SQLITE_OK ){
  34775. pFile->eFileLock = eFileLock;
  34776. }
  34777. return rc;
  34778. }
  34779. /*
  34780. ** Close a file & cleanup AFP specific locking context
  34781. */
  34782. static int afpClose(sqlite3_file *id) {
  34783. int rc = SQLITE_OK;
  34784. unixFile *pFile = (unixFile*)id;
  34785. assert( id!=0 );
  34786. afpUnlock(id, NO_LOCK);
  34787. assert( unixFileMutexNotheld(pFile) );
  34788. unixEnterMutex();
  34789. if( pFile->pInode ){
  34790. unixInodeInfo *pInode = pFile->pInode;
  34791. sqlite3_mutex_enter(pInode->pLockMutex);
  34792. if( pInode->nLock ){
  34793. /* If there are outstanding locks, do not actually close the file just
  34794. ** yet because that would clear those locks. Instead, add the file
  34795. ** descriptor to pInode->aPending. It will be automatically closed when
  34796. ** the last lock is cleared.
  34797. */
  34798. setPendingFd(pFile);
  34799. }
  34800. sqlite3_mutex_leave(pInode->pLockMutex);
  34801. }
  34802. releaseInodeInfo(pFile);
  34803. sqlite3_free(pFile->lockingContext);
  34804. rc = closeUnixFile(id);
  34805. unixLeaveMutex();
  34806. return rc;
  34807. }
  34808. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  34809. /*
  34810. ** The code above is the AFP lock implementation. The code is specific
  34811. ** to MacOSX and does not work on other unix platforms. No alternative
  34812. ** is available. If you don't compile for a mac, then the "unix-afp"
  34813. ** VFS is not available.
  34814. **
  34815. ********************* End of the AFP lock implementation **********************
  34816. ******************************************************************************/
  34817. /******************************************************************************
  34818. *************************** Begin NFS Locking ********************************/
  34819. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  34820. /*
  34821. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  34822. ** must be either NO_LOCK or SHARED_LOCK.
  34823. **
  34824. ** If the locking level of the file descriptor is already at or below
  34825. ** the requested locking level, this routine is a no-op.
  34826. */
  34827. static int nfsUnlock(sqlite3_file *id, int eFileLock){
  34828. return posixUnlock(id, eFileLock, 1);
  34829. }
  34830. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  34831. /*
  34832. ** The code above is the NFS lock implementation. The code is specific
  34833. ** to MacOSX and does not work on other unix platforms. No alternative
  34834. ** is available.
  34835. **
  34836. ********************* End of the NFS lock implementation **********************
  34837. ******************************************************************************/
  34838. /******************************************************************************
  34839. **************** Non-locking sqlite3_file methods *****************************
  34840. **
  34841. ** The next division contains implementations for all methods of the
  34842. ** sqlite3_file object other than the locking methods. The locking
  34843. ** methods were defined in divisions above (one locking method per
  34844. ** division). Those methods that are common to all locking modes
  34845. ** are gather together into this division.
  34846. */
  34847. /*
  34848. ** Seek to the offset passed as the second argument, then read cnt
  34849. ** bytes into pBuf. Return the number of bytes actually read.
  34850. **
  34851. ** NB: If you define USE_PREAD or USE_PREAD64, then it might also
  34852. ** be necessary to define _XOPEN_SOURCE to be 500. This varies from
  34853. ** one system to another. Since SQLite does not define USE_PREAD
  34854. ** in any form by default, we will not attempt to define _XOPEN_SOURCE.
  34855. ** See tickets #2741 and #2681.
  34856. **
  34857. ** To avoid stomping the errno value on a failed read the lastErrno value
  34858. ** is set before returning.
  34859. */
  34860. static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
  34861. int got;
  34862. int prior = 0;
  34863. #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
  34864. i64 newOffset;
  34865. #endif
  34866. TIMER_START;
  34867. assert( cnt==(cnt&0x1ffff) );
  34868. assert( id->h>2 );
  34869. do{
  34870. #if defined(USE_PREAD)
  34871. got = osPread(id->h, pBuf, cnt, offset);
  34872. SimulateIOError( got = -1 );
  34873. #elif defined(USE_PREAD64)
  34874. got = osPread64(id->h, pBuf, cnt, offset);
  34875. SimulateIOError( got = -1 );
  34876. #else
  34877. newOffset = lseek(id->h, offset, SEEK_SET);
  34878. SimulateIOError( newOffset = -1 );
  34879. if( newOffset<0 ){
  34880. storeLastErrno((unixFile*)id, errno);
  34881. return -1;
  34882. }
  34883. got = osRead(id->h, pBuf, cnt);
  34884. #endif
  34885. if( got==cnt ) break;
  34886. if( got<0 ){
  34887. if( errno==EINTR ){ got = 1; continue; }
  34888. prior = 0;
  34889. storeLastErrno((unixFile*)id, errno);
  34890. break;
  34891. }else if( got>0 ){
  34892. cnt -= got;
  34893. offset += got;
  34894. prior += got;
  34895. pBuf = (void*)(got + (char*)pBuf);
  34896. }
  34897. }while( got>0 );
  34898. TIMER_END;
  34899. OSTRACE(("READ %-3d %5d %7lld %llu\n",
  34900. id->h, got+prior, offset-prior, TIMER_ELAPSED));
  34901. return got+prior;
  34902. }
  34903. /*
  34904. ** Read data from a file into a buffer. Return SQLITE_OK if all
  34905. ** bytes were read successfully and SQLITE_IOERR if anything goes
  34906. ** wrong.
  34907. */
  34908. static int unixRead(
  34909. sqlite3_file *id,
  34910. void *pBuf,
  34911. int amt,
  34912. sqlite3_int64 offset
  34913. ){
  34914. unixFile *pFile = (unixFile *)id;
  34915. int got;
  34916. assert( id );
  34917. assert( offset>=0 );
  34918. assert( amt>0 );
  34919. /* If this is a database file (not a journal, master-journal or temp
  34920. ** file), the bytes in the locking range should never be read or written. */
  34921. #if 0
  34922. assert( pFile->pPreallocatedUnused==0
  34923. || offset>=PENDING_BYTE+512
  34924. || offset+amt<=PENDING_BYTE
  34925. );
  34926. #endif
  34927. #if SQLITE_MAX_MMAP_SIZE>0
  34928. /* Deal with as much of this read request as possible by transfering
  34929. ** data from the memory mapping using memcpy(). */
  34930. if( offset<pFile->mmapSize ){
  34931. if( offset+amt <= pFile->mmapSize ){
  34932. memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
  34933. return SQLITE_OK;
  34934. }else{
  34935. int nCopy = pFile->mmapSize - offset;
  34936. memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
  34937. pBuf = &((u8 *)pBuf)[nCopy];
  34938. amt -= nCopy;
  34939. offset += nCopy;
  34940. }
  34941. }
  34942. #endif
  34943. got = seekAndRead(pFile, offset, pBuf, amt);
  34944. if( got==amt ){
  34945. return SQLITE_OK;
  34946. }else if( got<0 ){
  34947. /* lastErrno set by seekAndRead */
  34948. return SQLITE_IOERR_READ;
  34949. }else{
  34950. storeLastErrno(pFile, 0); /* not a system error */
  34951. /* Unread parts of the buffer must be zero-filled */
  34952. memset(&((char*)pBuf)[got], 0, amt-got);
  34953. return SQLITE_IOERR_SHORT_READ;
  34954. }
  34955. }
  34956. /*
  34957. ** Attempt to seek the file-descriptor passed as the first argument to
  34958. ** absolute offset iOff, then attempt to write nBuf bytes of data from
  34959. ** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
  34960. ** return the actual number of bytes written (which may be less than
  34961. ** nBuf).
  34962. */
  34963. static int seekAndWriteFd(
  34964. int fd, /* File descriptor to write to */
  34965. i64 iOff, /* File offset to begin writing at */
  34966. const void *pBuf, /* Copy data from this buffer to the file */
  34967. int nBuf, /* Size of buffer pBuf in bytes */
  34968. int *piErrno /* OUT: Error number if error occurs */
  34969. ){
  34970. int rc = 0; /* Value returned by system call */
  34971. assert( nBuf==(nBuf&0x1ffff) );
  34972. assert( fd>2 );
  34973. assert( piErrno!=0 );
  34974. nBuf &= 0x1ffff;
  34975. TIMER_START;
  34976. #if defined(USE_PREAD)
  34977. do{ rc = (int)osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
  34978. #elif defined(USE_PREAD64)
  34979. do{ rc = (int)osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
  34980. #else
  34981. do{
  34982. i64 iSeek = lseek(fd, iOff, SEEK_SET);
  34983. SimulateIOError( iSeek = -1 );
  34984. if( iSeek<0 ){
  34985. rc = -1;
  34986. break;
  34987. }
  34988. rc = osWrite(fd, pBuf, nBuf);
  34989. }while( rc<0 && errno==EINTR );
  34990. #endif
  34991. TIMER_END;
  34992. OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
  34993. if( rc<0 ) *piErrno = errno;
  34994. return rc;
  34995. }
  34996. /*
  34997. ** Seek to the offset in id->offset then read cnt bytes into pBuf.
  34998. ** Return the number of bytes actually read. Update the offset.
  34999. **
  35000. ** To avoid stomping the errno value on a failed write the lastErrno value
  35001. ** is set before returning.
  35002. */
  35003. static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
  35004. return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
  35005. }
  35006. /*
  35007. ** Write data from a buffer into a file. Return SQLITE_OK on success
  35008. ** or some other error code on failure.
  35009. */
  35010. static int unixWrite(
  35011. sqlite3_file *id,
  35012. const void *pBuf,
  35013. int amt,
  35014. sqlite3_int64 offset
  35015. ){
  35016. unixFile *pFile = (unixFile*)id;
  35017. int wrote = 0;
  35018. assert( id );
  35019. assert( amt>0 );
  35020. /* If this is a database file (not a journal, master-journal or temp
  35021. ** file), the bytes in the locking range should never be read or written. */
  35022. #if 0
  35023. assert( pFile->pPreallocatedUnused==0
  35024. || offset>=PENDING_BYTE+512
  35025. || offset+amt<=PENDING_BYTE
  35026. );
  35027. #endif
  35028. #ifdef SQLITE_DEBUG
  35029. /* If we are doing a normal write to a database file (as opposed to
  35030. ** doing a hot-journal rollback or a write to some file other than a
  35031. ** normal database file) then record the fact that the database
  35032. ** has changed. If the transaction counter is modified, record that
  35033. ** fact too.
  35034. */
  35035. if( pFile->inNormalWrite ){
  35036. pFile->dbUpdate = 1; /* The database has been modified */
  35037. if( offset<=24 && offset+amt>=27 ){
  35038. int rc;
  35039. char oldCntr[4];
  35040. SimulateIOErrorBenign(1);
  35041. rc = seekAndRead(pFile, 24, oldCntr, 4);
  35042. SimulateIOErrorBenign(0);
  35043. if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
  35044. pFile->transCntrChng = 1; /* The transaction counter has changed */
  35045. }
  35046. }
  35047. }
  35048. #endif
  35049. #if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0
  35050. /* Deal with as much of this write request as possible by transfering
  35051. ** data from the memory mapping using memcpy(). */
  35052. if( offset<pFile->mmapSize ){
  35053. if( offset+amt <= pFile->mmapSize ){
  35054. memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
  35055. return SQLITE_OK;
  35056. }else{
  35057. int nCopy = pFile->mmapSize - offset;
  35058. memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
  35059. pBuf = &((u8 *)pBuf)[nCopy];
  35060. amt -= nCopy;
  35061. offset += nCopy;
  35062. }
  35063. }
  35064. #endif
  35065. while( (wrote = seekAndWrite(pFile, offset, pBuf, amt))<amt && wrote>0 ){
  35066. amt -= wrote;
  35067. offset += wrote;
  35068. pBuf = &((char*)pBuf)[wrote];
  35069. }
  35070. SimulateIOError(( wrote=(-1), amt=1 ));
  35071. SimulateDiskfullError(( wrote=0, amt=1 ));
  35072. if( amt>wrote ){
  35073. if( wrote<0 && pFile->lastErrno!=ENOSPC ){
  35074. /* lastErrno set by seekAndWrite */
  35075. return SQLITE_IOERR_WRITE;
  35076. }else{
  35077. storeLastErrno(pFile, 0); /* not a system error */
  35078. return SQLITE_FULL;
  35079. }
  35080. }
  35081. return SQLITE_OK;
  35082. }
  35083. #ifdef SQLITE_TEST
  35084. /*
  35085. ** Count the number of fullsyncs and normal syncs. This is used to test
  35086. ** that syncs and fullsyncs are occurring at the right times.
  35087. */
  35088. SQLITE_API int sqlite3_sync_count = 0;
  35089. SQLITE_API int sqlite3_fullsync_count = 0;
  35090. #endif
  35091. /*
  35092. ** We do not trust systems to provide a working fdatasync(). Some do.
  35093. ** Others do no. To be safe, we will stick with the (slightly slower)
  35094. ** fsync(). If you know that your system does support fdatasync() correctly,
  35095. ** then simply compile with -Dfdatasync=fdatasync or -DHAVE_FDATASYNC
  35096. */
  35097. #if !defined(fdatasync) && !HAVE_FDATASYNC
  35098. # define fdatasync fsync
  35099. #endif
  35100. /*
  35101. ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
  35102. ** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
  35103. ** only available on Mac OS X. But that could change.
  35104. */
  35105. #ifdef F_FULLFSYNC
  35106. # define HAVE_FULLFSYNC 1
  35107. #else
  35108. # define HAVE_FULLFSYNC 0
  35109. #endif
  35110. /*
  35111. ** The fsync() system call does not work as advertised on many
  35112. ** unix systems. The following procedure is an attempt to make
  35113. ** it work better.
  35114. **
  35115. ** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
  35116. ** for testing when we want to run through the test suite quickly.
  35117. ** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
  35118. ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
  35119. ** or power failure will likely corrupt the database file.
  35120. **
  35121. ** SQLite sets the dataOnly flag if the size of the file is unchanged.
  35122. ** The idea behind dataOnly is that it should only write the file content
  35123. ** to disk, not the inode. We only set dataOnly if the file size is
  35124. ** unchanged since the file size is part of the inode. However,
  35125. ** Ted Ts'o tells us that fdatasync() will also write the inode if the
  35126. ** file size has changed. The only real difference between fdatasync()
  35127. ** and fsync(), Ted tells us, is that fdatasync() will not flush the
  35128. ** inode if the mtime or owner or other inode attributes have changed.
  35129. ** We only care about the file size, not the other file attributes, so
  35130. ** as far as SQLite is concerned, an fdatasync() is always adequate.
  35131. ** So, we always use fdatasync() if it is available, regardless of
  35132. ** the value of the dataOnly flag.
  35133. */
  35134. static int full_fsync(int fd, int fullSync, int dataOnly){
  35135. int rc;
  35136. /* The following "ifdef/elif/else/" block has the same structure as
  35137. ** the one below. It is replicated here solely to avoid cluttering
  35138. ** up the real code with the UNUSED_PARAMETER() macros.
  35139. */
  35140. #ifdef SQLITE_NO_SYNC
  35141. UNUSED_PARAMETER(fd);
  35142. UNUSED_PARAMETER(fullSync);
  35143. UNUSED_PARAMETER(dataOnly);
  35144. #elif HAVE_FULLFSYNC
  35145. UNUSED_PARAMETER(dataOnly);
  35146. #else
  35147. UNUSED_PARAMETER(fullSync);
  35148. UNUSED_PARAMETER(dataOnly);
  35149. #endif
  35150. /* Record the number of times that we do a normal fsync() and
  35151. ** FULLSYNC. This is used during testing to verify that this procedure
  35152. ** gets called with the correct arguments.
  35153. */
  35154. #ifdef SQLITE_TEST
  35155. if( fullSync ) sqlite3_fullsync_count++;
  35156. sqlite3_sync_count++;
  35157. #endif
  35158. /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
  35159. ** no-op. But go ahead and call fstat() to validate the file
  35160. ** descriptor as we need a method to provoke a failure during
  35161. ** coverate testing.
  35162. */
  35163. #ifdef SQLITE_NO_SYNC
  35164. {
  35165. struct stat buf;
  35166. rc = osFstat(fd, &buf);
  35167. }
  35168. #elif HAVE_FULLFSYNC
  35169. if( fullSync ){
  35170. rc = osFcntl(fd, F_FULLFSYNC, 0);
  35171. }else{
  35172. rc = 1;
  35173. }
  35174. /* If the FULLFSYNC failed, fall back to attempting an fsync().
  35175. ** It shouldn't be possible for fullfsync to fail on the local
  35176. ** file system (on OSX), so failure indicates that FULLFSYNC
  35177. ** isn't supported for this file system. So, attempt an fsync
  35178. ** and (for now) ignore the overhead of a superfluous fcntl call.
  35179. ** It'd be better to detect fullfsync support once and avoid
  35180. ** the fcntl call every time sync is called.
  35181. */
  35182. if( rc ) rc = fsync(fd);
  35183. #elif defined(__APPLE__)
  35184. /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
  35185. ** so currently we default to the macro that redefines fdatasync to fsync
  35186. */
  35187. rc = fsync(fd);
  35188. #else
  35189. rc = fdatasync(fd);
  35190. #if OS_VXWORKS
  35191. if( rc==-1 && errno==ENOTSUP ){
  35192. rc = fsync(fd);
  35193. }
  35194. #endif /* OS_VXWORKS */
  35195. #endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
  35196. if( OS_VXWORKS && rc!= -1 ){
  35197. rc = 0;
  35198. }
  35199. return rc;
  35200. }
  35201. /*
  35202. ** Open a file descriptor to the directory containing file zFilename.
  35203. ** If successful, *pFd is set to the opened file descriptor and
  35204. ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
  35205. ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
  35206. ** value.
  35207. **
  35208. ** The directory file descriptor is used for only one thing - to
  35209. ** fsync() a directory to make sure file creation and deletion events
  35210. ** are flushed to disk. Such fsyncs are not needed on newer
  35211. ** journaling filesystems, but are required on older filesystems.
  35212. **
  35213. ** This routine can be overridden using the xSetSysCall interface.
  35214. ** The ability to override this routine was added in support of the
  35215. ** chromium sandbox. Opening a directory is a security risk (we are
  35216. ** told) so making it overrideable allows the chromium sandbox to
  35217. ** replace this routine with a harmless no-op. To make this routine
  35218. ** a no-op, replace it with a stub that returns SQLITE_OK but leaves
  35219. ** *pFd set to a negative number.
  35220. **
  35221. ** If SQLITE_OK is returned, the caller is responsible for closing
  35222. ** the file descriptor *pFd using close().
  35223. */
  35224. static int openDirectory(const char *zFilename, int *pFd){
  35225. int ii;
  35226. int fd = -1;
  35227. char zDirname[MAX_PATHNAME+1];
  35228. sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
  35229. for(ii=(int)strlen(zDirname); ii>0 && zDirname[ii]!='/'; ii--);
  35230. if( ii>0 ){
  35231. zDirname[ii] = '\0';
  35232. }else{
  35233. if( zDirname[0]!='/' ) zDirname[0] = '.';
  35234. zDirname[1] = 0;
  35235. }
  35236. fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
  35237. if( fd>=0 ){
  35238. OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
  35239. }
  35240. *pFd = fd;
  35241. if( fd>=0 ) return SQLITE_OK;
  35242. return unixLogError(SQLITE_CANTOPEN_BKPT, "openDirectory", zDirname);
  35243. }
  35244. /*
  35245. ** Make sure all writes to a particular file are committed to disk.
  35246. **
  35247. ** If dataOnly==0 then both the file itself and its metadata (file
  35248. ** size, access time, etc) are synced. If dataOnly!=0 then only the
  35249. ** file data is synced.
  35250. **
  35251. ** Under Unix, also make sure that the directory entry for the file
  35252. ** has been created by fsync-ing the directory that contains the file.
  35253. ** If we do not do this and we encounter a power failure, the directory
  35254. ** entry for the journal might not exist after we reboot. The next
  35255. ** SQLite to access the file will not know that the journal exists (because
  35256. ** the directory entry for the journal was never created) and the transaction
  35257. ** will not roll back - possibly leading to database corruption.
  35258. */
  35259. static int unixSync(sqlite3_file *id, int flags){
  35260. int rc;
  35261. unixFile *pFile = (unixFile*)id;
  35262. int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
  35263. int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
  35264. /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
  35265. assert((flags&0x0F)==SQLITE_SYNC_NORMAL
  35266. || (flags&0x0F)==SQLITE_SYNC_FULL
  35267. );
  35268. /* Unix cannot, but some systems may return SQLITE_FULL from here. This
  35269. ** line is to test that doing so does not cause any problems.
  35270. */
  35271. SimulateDiskfullError( return SQLITE_FULL );
  35272. assert( pFile );
  35273. OSTRACE(("SYNC %-3d\n", pFile->h));
  35274. rc = full_fsync(pFile->h, isFullsync, isDataOnly);
  35275. SimulateIOError( rc=1 );
  35276. if( rc ){
  35277. storeLastErrno(pFile, errno);
  35278. return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
  35279. }
  35280. /* Also fsync the directory containing the file if the DIRSYNC flag
  35281. ** is set. This is a one-time occurrence. Many systems (examples: AIX)
  35282. ** are unable to fsync a directory, so ignore errors on the fsync.
  35283. */
  35284. if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
  35285. int dirfd;
  35286. OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
  35287. HAVE_FULLFSYNC, isFullsync));
  35288. rc = osOpenDirectory(pFile->zPath, &dirfd);
  35289. if( rc==SQLITE_OK ){
  35290. full_fsync(dirfd, 0, 0);
  35291. robust_close(pFile, dirfd, __LINE__);
  35292. }else{
  35293. assert( rc==SQLITE_CANTOPEN );
  35294. rc = SQLITE_OK;
  35295. }
  35296. pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
  35297. }
  35298. return rc;
  35299. }
  35300. /*
  35301. ** Truncate an open file to a specified size
  35302. */
  35303. static int unixTruncate(sqlite3_file *id, i64 nByte){
  35304. unixFile *pFile = (unixFile *)id;
  35305. int rc;
  35306. assert( pFile );
  35307. SimulateIOError( return SQLITE_IOERR_TRUNCATE );
  35308. /* If the user has configured a chunk-size for this file, truncate the
  35309. ** file so that it consists of an integer number of chunks (i.e. the
  35310. ** actual file size after the operation may be larger than the requested
  35311. ** size).
  35312. */
  35313. if( pFile->szChunk>0 ){
  35314. nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
  35315. }
  35316. rc = robust_ftruncate(pFile->h, nByte);
  35317. if( rc ){
  35318. storeLastErrno(pFile, errno);
  35319. return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
  35320. }else{
  35321. #ifdef SQLITE_DEBUG
  35322. /* If we are doing a normal write to a database file (as opposed to
  35323. ** doing a hot-journal rollback or a write to some file other than a
  35324. ** normal database file) and we truncate the file to zero length,
  35325. ** that effectively updates the change counter. This might happen
  35326. ** when restoring a database using the backup API from a zero-length
  35327. ** source.
  35328. */
  35329. if( pFile->inNormalWrite && nByte==0 ){
  35330. pFile->transCntrChng = 1;
  35331. }
  35332. #endif
  35333. #if SQLITE_MAX_MMAP_SIZE>0
  35334. /* If the file was just truncated to a size smaller than the currently
  35335. ** mapped region, reduce the effective mapping size as well. SQLite will
  35336. ** use read() and write() to access data beyond this point from now on.
  35337. */
  35338. if( nByte<pFile->mmapSize ){
  35339. pFile->mmapSize = nByte;
  35340. }
  35341. #endif
  35342. return SQLITE_OK;
  35343. }
  35344. }
  35345. /*
  35346. ** Determine the current size of a file in bytes
  35347. */
  35348. static int unixFileSize(sqlite3_file *id, i64 *pSize){
  35349. int rc;
  35350. struct stat buf;
  35351. assert( id );
  35352. rc = osFstat(((unixFile*)id)->h, &buf);
  35353. SimulateIOError( rc=1 );
  35354. if( rc!=0 ){
  35355. storeLastErrno((unixFile*)id, errno);
  35356. return SQLITE_IOERR_FSTAT;
  35357. }
  35358. *pSize = buf.st_size;
  35359. /* When opening a zero-size database, the findInodeInfo() procedure
  35360. ** writes a single byte into that file in order to work around a bug
  35361. ** in the OS-X msdos filesystem. In order to avoid problems with upper
  35362. ** layers, we need to report this file size as zero even though it is
  35363. ** really 1. Ticket #3260.
  35364. */
  35365. if( *pSize==1 ) *pSize = 0;
  35366. return SQLITE_OK;
  35367. }
  35368. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  35369. /*
  35370. ** Handler for proxy-locking file-control verbs. Defined below in the
  35371. ** proxying locking division.
  35372. */
  35373. static int proxyFileControl(sqlite3_file*,int,void*);
  35374. #endif
  35375. /*
  35376. ** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
  35377. ** file-control operation. Enlarge the database to nBytes in size
  35378. ** (rounded up to the next chunk-size). If the database is already
  35379. ** nBytes or larger, this routine is a no-op.
  35380. */
  35381. static int fcntlSizeHint(unixFile *pFile, i64 nByte){
  35382. if( pFile->szChunk>0 ){
  35383. i64 nSize; /* Required file size */
  35384. struct stat buf; /* Used to hold return values of fstat() */
  35385. if( osFstat(pFile->h, &buf) ){
  35386. return SQLITE_IOERR_FSTAT;
  35387. }
  35388. nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
  35389. if( nSize>(i64)buf.st_size ){
  35390. #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
  35391. /* The code below is handling the return value of osFallocate()
  35392. ** correctly. posix_fallocate() is defined to "returns zero on success,
  35393. ** or an error number on failure". See the manpage for details. */
  35394. int err;
  35395. do{
  35396. err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
  35397. }while( err==EINTR );
  35398. if( err && err!=EINVAL ) return SQLITE_IOERR_WRITE;
  35399. #else
  35400. /* If the OS does not have posix_fallocate(), fake it. Write a
  35401. ** single byte to the last byte in each block that falls entirely
  35402. ** within the extended region. Then, if required, a single byte
  35403. ** at offset (nSize-1), to set the size of the file correctly.
  35404. ** This is a similar technique to that used by glibc on systems
  35405. ** that do not have a real fallocate() call.
  35406. */
  35407. int nBlk = buf.st_blksize; /* File-system block size */
  35408. int nWrite = 0; /* Number of bytes written by seekAndWrite */
  35409. i64 iWrite; /* Next offset to write to */
  35410. iWrite = (buf.st_size/nBlk)*nBlk + nBlk - 1;
  35411. assert( iWrite>=buf.st_size );
  35412. assert( ((iWrite+1)%nBlk)==0 );
  35413. for(/*no-op*/; iWrite<nSize+nBlk-1; iWrite+=nBlk ){
  35414. if( iWrite>=nSize ) iWrite = nSize - 1;
  35415. nWrite = seekAndWrite(pFile, iWrite, "", 1);
  35416. if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
  35417. }
  35418. #endif
  35419. }
  35420. }
  35421. #if SQLITE_MAX_MMAP_SIZE>0
  35422. if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
  35423. int rc;
  35424. if( pFile->szChunk<=0 ){
  35425. if( robust_ftruncate(pFile->h, nByte) ){
  35426. storeLastErrno(pFile, errno);
  35427. return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
  35428. }
  35429. }
  35430. rc = unixMapfile(pFile, nByte);
  35431. return rc;
  35432. }
  35433. #endif
  35434. return SQLITE_OK;
  35435. }
  35436. /*
  35437. ** If *pArg is initially negative then this is a query. Set *pArg to
  35438. ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
  35439. **
  35440. ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
  35441. */
  35442. static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
  35443. if( *pArg<0 ){
  35444. *pArg = (pFile->ctrlFlags & mask)!=0;
  35445. }else if( (*pArg)==0 ){
  35446. pFile->ctrlFlags &= ~mask;
  35447. }else{
  35448. pFile->ctrlFlags |= mask;
  35449. }
  35450. }
  35451. /* Forward declaration */
  35452. static int unixGetTempname(int nBuf, char *zBuf);
  35453. /*
  35454. ** Information and control of an open file handle.
  35455. */
  35456. static int unixFileControl(sqlite3_file *id, int op, void *pArg){
  35457. unixFile *pFile = (unixFile*)id;
  35458. switch( op ){
  35459. #if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
  35460. case SQLITE_FCNTL_BEGIN_ATOMIC_WRITE: {
  35461. int rc = osIoctl(pFile->h, F2FS_IOC_START_ATOMIC_WRITE);
  35462. return rc ? SQLITE_IOERR_BEGIN_ATOMIC : SQLITE_OK;
  35463. }
  35464. case SQLITE_FCNTL_COMMIT_ATOMIC_WRITE: {
  35465. int rc = osIoctl(pFile->h, F2FS_IOC_COMMIT_ATOMIC_WRITE);
  35466. return rc ? SQLITE_IOERR_COMMIT_ATOMIC : SQLITE_OK;
  35467. }
  35468. case SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE: {
  35469. int rc = osIoctl(pFile->h, F2FS_IOC_ABORT_VOLATILE_WRITE);
  35470. return rc ? SQLITE_IOERR_ROLLBACK_ATOMIC : SQLITE_OK;
  35471. }
  35472. #endif /* __linux__ && SQLITE_ENABLE_BATCH_ATOMIC_WRITE */
  35473. case SQLITE_FCNTL_LOCKSTATE: {
  35474. *(int*)pArg = pFile->eFileLock;
  35475. return SQLITE_OK;
  35476. }
  35477. case SQLITE_FCNTL_LAST_ERRNO: {
  35478. *(int*)pArg = pFile->lastErrno;
  35479. return SQLITE_OK;
  35480. }
  35481. case SQLITE_FCNTL_CHUNK_SIZE: {
  35482. pFile->szChunk = *(int *)pArg;
  35483. return SQLITE_OK;
  35484. }
  35485. case SQLITE_FCNTL_SIZE_HINT: {
  35486. int rc;
  35487. SimulateIOErrorBenign(1);
  35488. rc = fcntlSizeHint(pFile, *(i64 *)pArg);
  35489. SimulateIOErrorBenign(0);
  35490. return rc;
  35491. }
  35492. case SQLITE_FCNTL_PERSIST_WAL: {
  35493. unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
  35494. return SQLITE_OK;
  35495. }
  35496. case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
  35497. unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
  35498. return SQLITE_OK;
  35499. }
  35500. case SQLITE_FCNTL_VFSNAME: {
  35501. *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
  35502. return SQLITE_OK;
  35503. }
  35504. case SQLITE_FCNTL_TEMPFILENAME: {
  35505. char *zTFile = sqlite3_malloc64( pFile->pVfs->mxPathname );
  35506. if( zTFile ){
  35507. unixGetTempname(pFile->pVfs->mxPathname, zTFile);
  35508. *(char**)pArg = zTFile;
  35509. }
  35510. return SQLITE_OK;
  35511. }
  35512. case SQLITE_FCNTL_HAS_MOVED: {
  35513. *(int*)pArg = fileHasMoved(pFile);
  35514. return SQLITE_OK;
  35515. }
  35516. #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
  35517. case SQLITE_FCNTL_LOCK_TIMEOUT: {
  35518. int iOld = pFile->iBusyTimeout;
  35519. pFile->iBusyTimeout = *(int*)pArg;
  35520. *(int*)pArg = iOld;
  35521. return SQLITE_OK;
  35522. }
  35523. #endif
  35524. #if SQLITE_MAX_MMAP_SIZE>0
  35525. case SQLITE_FCNTL_MMAP_SIZE: {
  35526. i64 newLimit = *(i64*)pArg;
  35527. int rc = SQLITE_OK;
  35528. if( newLimit>sqlite3GlobalConfig.mxMmap ){
  35529. newLimit = sqlite3GlobalConfig.mxMmap;
  35530. }
  35531. /* The value of newLimit may be eventually cast to (size_t) and passed
  35532. ** to mmap(). Restrict its value to 2GB if (size_t) is not at least a
  35533. ** 64-bit type. */
  35534. if( newLimit>0 && sizeof(size_t)<8 ){
  35535. newLimit = (newLimit & 0x7FFFFFFF);
  35536. }
  35537. *(i64*)pArg = pFile->mmapSizeMax;
  35538. if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
  35539. pFile->mmapSizeMax = newLimit;
  35540. if( pFile->mmapSize>0 ){
  35541. unixUnmapfile(pFile);
  35542. rc = unixMapfile(pFile, -1);
  35543. }
  35544. }
  35545. return rc;
  35546. }
  35547. #endif
  35548. #ifdef SQLITE_DEBUG
  35549. /* The pager calls this method to signal that it has done
  35550. ** a rollback and that the database is therefore unchanged and
  35551. ** it hence it is OK for the transaction change counter to be
  35552. ** unchanged.
  35553. */
  35554. case SQLITE_FCNTL_DB_UNCHANGED: {
  35555. ((unixFile*)id)->dbUpdate = 0;
  35556. return SQLITE_OK;
  35557. }
  35558. #endif
  35559. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  35560. case SQLITE_FCNTL_SET_LOCKPROXYFILE:
  35561. case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
  35562. return proxyFileControl(id,op,pArg);
  35563. }
  35564. #endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
  35565. }
  35566. return SQLITE_NOTFOUND;
  35567. }
  35568. /*
  35569. ** If pFd->sectorSize is non-zero when this function is called, it is a
  35570. ** no-op. Otherwise, the values of pFd->sectorSize and
  35571. ** pFd->deviceCharacteristics are set according to the file-system
  35572. ** characteristics.
  35573. **
  35574. ** There are two versions of this function. One for QNX and one for all
  35575. ** other systems.
  35576. */
  35577. #ifndef __QNXNTO__
  35578. static void setDeviceCharacteristics(unixFile *pFd){
  35579. assert( pFd->deviceCharacteristics==0 || pFd->sectorSize!=0 );
  35580. if( pFd->sectorSize==0 ){
  35581. #if defined(__linux__) && defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
  35582. int res;
  35583. u32 f = 0;
  35584. /* Check for support for F2FS atomic batch writes. */
  35585. res = osIoctl(pFd->h, F2FS_IOC_GET_FEATURES, &f);
  35586. if( res==0 && (f & F2FS_FEATURE_ATOMIC_WRITE) ){
  35587. pFd->deviceCharacteristics = SQLITE_IOCAP_BATCH_ATOMIC;
  35588. }
  35589. #endif /* __linux__ && SQLITE_ENABLE_BATCH_ATOMIC_WRITE */
  35590. /* Set the POWERSAFE_OVERWRITE flag if requested. */
  35591. if( pFd->ctrlFlags & UNIXFILE_PSOW ){
  35592. pFd->deviceCharacteristics |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
  35593. }
  35594. pFd->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
  35595. }
  35596. }
  35597. #else
  35598. #include <sys/dcmd_blk.h>
  35599. #include <sys/statvfs.h>
  35600. static void setDeviceCharacteristics(unixFile *pFile){
  35601. if( pFile->sectorSize == 0 ){
  35602. struct statvfs fsInfo;
  35603. /* Set defaults for non-supported filesystems */
  35604. pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
  35605. pFile->deviceCharacteristics = 0;
  35606. if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
  35607. return;
  35608. }
  35609. if( !strcmp(fsInfo.f_basetype, "tmp") ) {
  35610. pFile->sectorSize = fsInfo.f_bsize;
  35611. pFile->deviceCharacteristics =
  35612. SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */
  35613. SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
  35614. ** the write succeeds */
  35615. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  35616. ** so it is ordered */
  35617. 0;
  35618. }else if( strstr(fsInfo.f_basetype, "etfs") ){
  35619. pFile->sectorSize = fsInfo.f_bsize;
  35620. pFile->deviceCharacteristics =
  35621. /* etfs cluster size writes are atomic */
  35622. (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
  35623. SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
  35624. ** the write succeeds */
  35625. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  35626. ** so it is ordered */
  35627. 0;
  35628. }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
  35629. pFile->sectorSize = fsInfo.f_bsize;
  35630. pFile->deviceCharacteristics =
  35631. SQLITE_IOCAP_ATOMIC | /* All filesystem writes are atomic */
  35632. SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
  35633. ** the write succeeds */
  35634. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  35635. ** so it is ordered */
  35636. 0;
  35637. }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
  35638. pFile->sectorSize = fsInfo.f_bsize;
  35639. pFile->deviceCharacteristics =
  35640. /* full bitset of atomics from max sector size and smaller */
  35641. ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
  35642. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  35643. ** so it is ordered */
  35644. 0;
  35645. }else if( strstr(fsInfo.f_basetype, "dos") ){
  35646. pFile->sectorSize = fsInfo.f_bsize;
  35647. pFile->deviceCharacteristics =
  35648. /* full bitset of atomics from max sector size and smaller */
  35649. ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
  35650. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  35651. ** so it is ordered */
  35652. 0;
  35653. }else{
  35654. pFile->deviceCharacteristics =
  35655. SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */
  35656. SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
  35657. ** the write succeeds */
  35658. 0;
  35659. }
  35660. }
  35661. /* Last chance verification. If the sector size isn't a multiple of 512
  35662. ** then it isn't valid.*/
  35663. if( pFile->sectorSize % 512 != 0 ){
  35664. pFile->deviceCharacteristics = 0;
  35665. pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
  35666. }
  35667. }
  35668. #endif
  35669. /*
  35670. ** Return the sector size in bytes of the underlying block device for
  35671. ** the specified file. This is almost always 512 bytes, but may be
  35672. ** larger for some devices.
  35673. **
  35674. ** SQLite code assumes this function cannot fail. It also assumes that
  35675. ** if two files are created in the same file-system directory (i.e.
  35676. ** a database and its journal file) that the sector size will be the
  35677. ** same for both.
  35678. */
  35679. static int unixSectorSize(sqlite3_file *id){
  35680. unixFile *pFd = (unixFile*)id;
  35681. setDeviceCharacteristics(pFd);
  35682. return pFd->sectorSize;
  35683. }
  35684. /*
  35685. ** Return the device characteristics for the file.
  35686. **
  35687. ** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
  35688. ** However, that choice is controversial since technically the underlying
  35689. ** file system does not always provide powersafe overwrites. (In other
  35690. ** words, after a power-loss event, parts of the file that were never
  35691. ** written might end up being altered.) However, non-PSOW behavior is very,
  35692. ** very rare. And asserting PSOW makes a large reduction in the amount
  35693. ** of required I/O for journaling, since a lot of padding is eliminated.
  35694. ** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
  35695. ** available to turn it off and URI query parameter available to turn it off.
  35696. */
  35697. static int unixDeviceCharacteristics(sqlite3_file *id){
  35698. unixFile *pFd = (unixFile*)id;
  35699. setDeviceCharacteristics(pFd);
  35700. return pFd->deviceCharacteristics;
  35701. }
  35702. #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
  35703. /*
  35704. ** Return the system page size.
  35705. **
  35706. ** This function should not be called directly by other code in this file.
  35707. ** Instead, it should be called via macro osGetpagesize().
  35708. */
  35709. static int unixGetpagesize(void){
  35710. #if OS_VXWORKS
  35711. return 1024;
  35712. #elif defined(_BSD_SOURCE)
  35713. return getpagesize();
  35714. #else
  35715. return (int)sysconf(_SC_PAGESIZE);
  35716. #endif
  35717. }
  35718. #endif /* !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 */
  35719. #ifndef SQLITE_OMIT_WAL
  35720. /*
  35721. ** Object used to represent an shared memory buffer.
  35722. **
  35723. ** When multiple threads all reference the same wal-index, each thread
  35724. ** has its own unixShm object, but they all point to a single instance
  35725. ** of this unixShmNode object. In other words, each wal-index is opened
  35726. ** only once per process.
  35727. **
  35728. ** Each unixShmNode object is connected to a single unixInodeInfo object.
  35729. ** We could coalesce this object into unixInodeInfo, but that would mean
  35730. ** every open file that does not use shared memory (in other words, most
  35731. ** open files) would have to carry around this extra information. So
  35732. ** the unixInodeInfo object contains a pointer to this unixShmNode object
  35733. ** and the unixShmNode object is created only when needed.
  35734. **
  35735. ** unixMutexHeld() must be true when creating or destroying
  35736. ** this object or while reading or writing the following fields:
  35737. **
  35738. ** nRef
  35739. **
  35740. ** The following fields are read-only after the object is created:
  35741. **
  35742. ** hShm
  35743. ** zFilename
  35744. **
  35745. ** Either unixShmNode.pShmMutex must be held or unixShmNode.nRef==0 and
  35746. ** unixMutexHeld() is true when reading or writing any other field
  35747. ** in this structure.
  35748. */
  35749. struct unixShmNode {
  35750. unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
  35751. sqlite3_mutex *pShmMutex; /* Mutex to access this object */
  35752. char *zFilename; /* Name of the mmapped file */
  35753. int hShm; /* Open file descriptor */
  35754. int szRegion; /* Size of shared-memory regions */
  35755. u16 nRegion; /* Size of array apRegion */
  35756. u8 isReadonly; /* True if read-only */
  35757. u8 isUnlocked; /* True if no DMS lock held */
  35758. char **apRegion; /* Array of mapped shared-memory regions */
  35759. int nRef; /* Number of unixShm objects pointing to this */
  35760. unixShm *pFirst; /* All unixShm objects pointing to this */
  35761. #ifdef SQLITE_DEBUG
  35762. u8 exclMask; /* Mask of exclusive locks held */
  35763. u8 sharedMask; /* Mask of shared locks held */
  35764. u8 nextShmId; /* Next available unixShm.id value */
  35765. #endif
  35766. };
  35767. /*
  35768. ** Structure used internally by this VFS to record the state of an
  35769. ** open shared memory connection.
  35770. **
  35771. ** The following fields are initialized when this object is created and
  35772. ** are read-only thereafter:
  35773. **
  35774. ** unixShm.pShmNode
  35775. ** unixShm.id
  35776. **
  35777. ** All other fields are read/write. The unixShm.pShmNode->pShmMutex must
  35778. ** be held while accessing any read/write fields.
  35779. */
  35780. struct unixShm {
  35781. unixShmNode *pShmNode; /* The underlying unixShmNode object */
  35782. unixShm *pNext; /* Next unixShm with the same unixShmNode */
  35783. u8 hasMutex; /* True if holding the unixShmNode->pShmMutex */
  35784. u8 id; /* Id of this connection within its unixShmNode */
  35785. u16 sharedMask; /* Mask of shared locks held */
  35786. u16 exclMask; /* Mask of exclusive locks held */
  35787. };
  35788. /*
  35789. ** Constants used for locking
  35790. */
  35791. #define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
  35792. #define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
  35793. /*
  35794. ** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
  35795. **
  35796. ** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
  35797. ** otherwise.
  35798. */
  35799. static int unixShmSystemLock(
  35800. unixFile *pFile, /* Open connection to the WAL file */
  35801. int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
  35802. int ofst, /* First byte of the locking range */
  35803. int n /* Number of bytes to lock */
  35804. ){
  35805. unixShmNode *pShmNode; /* Apply locks to this open shared-memory segment */
  35806. struct flock f; /* The posix advisory locking structure */
  35807. int rc = SQLITE_OK; /* Result code form fcntl() */
  35808. /* Access to the unixShmNode object is serialized by the caller */
  35809. pShmNode = pFile->pInode->pShmNode;
  35810. assert( pShmNode->nRef==0 || sqlite3_mutex_held(pShmNode->pShmMutex) );
  35811. assert( pShmNode->nRef>0 || unixMutexHeld() );
  35812. /* Shared locks never span more than one byte */
  35813. assert( n==1 || lockType!=F_RDLCK );
  35814. /* Locks are within range */
  35815. assert( n>=1 && n<=SQLITE_SHM_NLOCK );
  35816. if( pShmNode->hShm>=0 ){
  35817. int res;
  35818. /* Initialize the locking parameters */
  35819. f.l_type = lockType;
  35820. f.l_whence = SEEK_SET;
  35821. f.l_start = ofst;
  35822. f.l_len = n;
  35823. res = osSetPosixAdvisoryLock(pShmNode->hShm, &f, pFile);
  35824. if( res==-1 ){
  35825. #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
  35826. rc = (pFile->iBusyTimeout ? SQLITE_BUSY_TIMEOUT : SQLITE_BUSY);
  35827. #else
  35828. rc = SQLITE_BUSY;
  35829. #endif
  35830. }
  35831. }
  35832. /* Update the global lock state and do debug tracing */
  35833. #ifdef SQLITE_DEBUG
  35834. { u16 mask;
  35835. OSTRACE(("SHM-LOCK "));
  35836. mask = ofst>31 ? 0xffff : (1<<(ofst+n)) - (1<<ofst);
  35837. if( rc==SQLITE_OK ){
  35838. if( lockType==F_UNLCK ){
  35839. OSTRACE(("unlock %d ok", ofst));
  35840. pShmNode->exclMask &= ~mask;
  35841. pShmNode->sharedMask &= ~mask;
  35842. }else if( lockType==F_RDLCK ){
  35843. OSTRACE(("read-lock %d ok", ofst));
  35844. pShmNode->exclMask &= ~mask;
  35845. pShmNode->sharedMask |= mask;
  35846. }else{
  35847. assert( lockType==F_WRLCK );
  35848. OSTRACE(("write-lock %d ok", ofst));
  35849. pShmNode->exclMask |= mask;
  35850. pShmNode->sharedMask &= ~mask;
  35851. }
  35852. }else{
  35853. if( lockType==F_UNLCK ){
  35854. OSTRACE(("unlock %d failed", ofst));
  35855. }else if( lockType==F_RDLCK ){
  35856. OSTRACE(("read-lock failed"));
  35857. }else{
  35858. assert( lockType==F_WRLCK );
  35859. OSTRACE(("write-lock %d failed", ofst));
  35860. }
  35861. }
  35862. OSTRACE((" - afterwards %03x,%03x\n",
  35863. pShmNode->sharedMask, pShmNode->exclMask));
  35864. }
  35865. #endif
  35866. return rc;
  35867. }
  35868. /*
  35869. ** Return the minimum number of 32KB shm regions that should be mapped at
  35870. ** a time, assuming that each mapping must be an integer multiple of the
  35871. ** current system page-size.
  35872. **
  35873. ** Usually, this is 1. The exception seems to be systems that are configured
  35874. ** to use 64KB pages - in this case each mapping must cover at least two
  35875. ** shm regions.
  35876. */
  35877. static int unixShmRegionPerMap(void){
  35878. int shmsz = 32*1024; /* SHM region size */
  35879. int pgsz = osGetpagesize(); /* System page size */
  35880. assert( ((pgsz-1)&pgsz)==0 ); /* Page size must be a power of 2 */
  35881. if( pgsz<shmsz ) return 1;
  35882. return pgsz/shmsz;
  35883. }
  35884. /*
  35885. ** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
  35886. **
  35887. ** This is not a VFS shared-memory method; it is a utility function called
  35888. ** by VFS shared-memory methods.
  35889. */
  35890. static void unixShmPurge(unixFile *pFd){
  35891. unixShmNode *p = pFd->pInode->pShmNode;
  35892. assert( unixMutexHeld() );
  35893. if( p && ALWAYS(p->nRef==0) ){
  35894. int nShmPerMap = unixShmRegionPerMap();
  35895. int i;
  35896. assert( p->pInode==pFd->pInode );
  35897. sqlite3_mutex_free(p->pShmMutex);
  35898. for(i=0; i<p->nRegion; i+=nShmPerMap){
  35899. if( p->hShm>=0 ){
  35900. osMunmap(p->apRegion[i], p->szRegion);
  35901. }else{
  35902. sqlite3_free(p->apRegion[i]);
  35903. }
  35904. }
  35905. sqlite3_free(p->apRegion);
  35906. if( p->hShm>=0 ){
  35907. robust_close(pFd, p->hShm, __LINE__);
  35908. p->hShm = -1;
  35909. }
  35910. p->pInode->pShmNode = 0;
  35911. sqlite3_free(p);
  35912. }
  35913. }
  35914. /*
  35915. ** The DMS lock has not yet been taken on shm file pShmNode. Attempt to
  35916. ** take it now. Return SQLITE_OK if successful, or an SQLite error
  35917. ** code otherwise.
  35918. **
  35919. ** If the DMS cannot be locked because this is a readonly_shm=1
  35920. ** connection and no other process already holds a lock, return
  35921. ** SQLITE_READONLY_CANTINIT and set pShmNode->isUnlocked=1.
  35922. */
  35923. static int unixLockSharedMemory(unixFile *pDbFd, unixShmNode *pShmNode){
  35924. struct flock lock;
  35925. int rc = SQLITE_OK;
  35926. /* Use F_GETLK to determine the locks other processes are holding
  35927. ** on the DMS byte. If it indicates that another process is holding
  35928. ** a SHARED lock, then this process may also take a SHARED lock
  35929. ** and proceed with opening the *-shm file.
  35930. **
  35931. ** Or, if no other process is holding any lock, then this process
  35932. ** is the first to open it. In this case take an EXCLUSIVE lock on the
  35933. ** DMS byte and truncate the *-shm file to zero bytes in size. Then
  35934. ** downgrade to a SHARED lock on the DMS byte.
  35935. **
  35936. ** If another process is holding an EXCLUSIVE lock on the DMS byte,
  35937. ** return SQLITE_BUSY to the caller (it will try again). An earlier
  35938. ** version of this code attempted the SHARED lock at this point. But
  35939. ** this introduced a subtle race condition: if the process holding
  35940. ** EXCLUSIVE failed just before truncating the *-shm file, then this
  35941. ** process might open and use the *-shm file without truncating it.
  35942. ** And if the *-shm file has been corrupted by a power failure or
  35943. ** system crash, the database itself may also become corrupt. */
  35944. lock.l_whence = SEEK_SET;
  35945. lock.l_start = UNIX_SHM_DMS;
  35946. lock.l_len = 1;
  35947. lock.l_type = F_WRLCK;
  35948. if( osFcntl(pShmNode->hShm, F_GETLK, &lock)!=0 ) {
  35949. rc = SQLITE_IOERR_LOCK;
  35950. }else if( lock.l_type==F_UNLCK ){
  35951. if( pShmNode->isReadonly ){
  35952. pShmNode->isUnlocked = 1;
  35953. rc = SQLITE_READONLY_CANTINIT;
  35954. }else{
  35955. rc = unixShmSystemLock(pDbFd, F_WRLCK, UNIX_SHM_DMS, 1);
  35956. /* The first connection to attach must truncate the -shm file. We
  35957. ** truncate to 3 bytes (an arbitrary small number, less than the
  35958. ** -shm header size) rather than 0 as a system debugging aid, to
  35959. ** help detect if a -shm file truncation is legitimate or is the work
  35960. ** or a rogue process. */
  35961. if( rc==SQLITE_OK && robust_ftruncate(pShmNode->hShm, 3) ){
  35962. rc = unixLogError(SQLITE_IOERR_SHMOPEN,"ftruncate",pShmNode->zFilename);
  35963. }
  35964. }
  35965. }else if( lock.l_type==F_WRLCK ){
  35966. rc = SQLITE_BUSY;
  35967. }
  35968. if( rc==SQLITE_OK ){
  35969. assert( lock.l_type==F_UNLCK || lock.l_type==F_RDLCK );
  35970. rc = unixShmSystemLock(pDbFd, F_RDLCK, UNIX_SHM_DMS, 1);
  35971. }
  35972. return rc;
  35973. }
  35974. /*
  35975. ** Open a shared-memory area associated with open database file pDbFd.
  35976. ** This particular implementation uses mmapped files.
  35977. **
  35978. ** The file used to implement shared-memory is in the same directory
  35979. ** as the open database file and has the same name as the open database
  35980. ** file with the "-shm" suffix added. For example, if the database file
  35981. ** is "/home/user1/config.db" then the file that is created and mmapped
  35982. ** for shared memory will be called "/home/user1/config.db-shm".
  35983. **
  35984. ** Another approach to is to use files in /dev/shm or /dev/tmp or an
  35985. ** some other tmpfs mount. But if a file in a different directory
  35986. ** from the database file is used, then differing access permissions
  35987. ** or a chroot() might cause two different processes on the same
  35988. ** database to end up using different files for shared memory -
  35989. ** meaning that their memory would not really be shared - resulting
  35990. ** in database corruption. Nevertheless, this tmpfs file usage
  35991. ** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
  35992. ** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
  35993. ** option results in an incompatible build of SQLite; builds of SQLite
  35994. ** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
  35995. ** same database file at the same time, database corruption will likely
  35996. ** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
  35997. ** "unsupported" and may go away in a future SQLite release.
  35998. **
  35999. ** When opening a new shared-memory file, if no other instances of that
  36000. ** file are currently open, in this process or in other processes, then
  36001. ** the file must be truncated to zero length or have its header cleared.
  36002. **
  36003. ** If the original database file (pDbFd) is using the "unix-excl" VFS
  36004. ** that means that an exclusive lock is held on the database file and
  36005. ** that no other processes are able to read or write the database. In
  36006. ** that case, we do not really need shared memory. No shared memory
  36007. ** file is created. The shared memory will be simulated with heap memory.
  36008. */
  36009. static int unixOpenSharedMemory(unixFile *pDbFd){
  36010. struct unixShm *p = 0; /* The connection to be opened */
  36011. struct unixShmNode *pShmNode; /* The underlying mmapped file */
  36012. int rc = SQLITE_OK; /* Result code */
  36013. unixInodeInfo *pInode; /* The inode of fd */
  36014. char *zShm; /* Name of the file used for SHM */
  36015. int nShmFilename; /* Size of the SHM filename in bytes */
  36016. /* Allocate space for the new unixShm object. */
  36017. p = sqlite3_malloc64( sizeof(*p) );
  36018. if( p==0 ) return SQLITE_NOMEM_BKPT;
  36019. memset(p, 0, sizeof(*p));
  36020. assert( pDbFd->pShm==0 );
  36021. /* Check to see if a unixShmNode object already exists. Reuse an existing
  36022. ** one if present. Create a new one if necessary.
  36023. */
  36024. assert( unixFileMutexNotheld(pDbFd) );
  36025. unixEnterMutex();
  36026. pInode = pDbFd->pInode;
  36027. pShmNode = pInode->pShmNode;
  36028. if( pShmNode==0 ){
  36029. struct stat sStat; /* fstat() info for database file */
  36030. #ifndef SQLITE_SHM_DIRECTORY
  36031. const char *zBasePath = pDbFd->zPath;
  36032. #endif
  36033. /* Call fstat() to figure out the permissions on the database file. If
  36034. ** a new *-shm file is created, an attempt will be made to create it
  36035. ** with the same permissions.
  36036. */
  36037. if( osFstat(pDbFd->h, &sStat) ){
  36038. rc = SQLITE_IOERR_FSTAT;
  36039. goto shm_open_err;
  36040. }
  36041. #ifdef SQLITE_SHM_DIRECTORY
  36042. nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
  36043. #else
  36044. nShmFilename = 6 + (int)strlen(zBasePath);
  36045. #endif
  36046. pShmNode = sqlite3_malloc64( sizeof(*pShmNode) + nShmFilename );
  36047. if( pShmNode==0 ){
  36048. rc = SQLITE_NOMEM_BKPT;
  36049. goto shm_open_err;
  36050. }
  36051. memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
  36052. zShm = pShmNode->zFilename = (char*)&pShmNode[1];
  36053. #ifdef SQLITE_SHM_DIRECTORY
  36054. sqlite3_snprintf(nShmFilename, zShm,
  36055. SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
  36056. (u32)sStat.st_ino, (u32)sStat.st_dev);
  36057. #else
  36058. sqlite3_snprintf(nShmFilename, zShm, "%s-shm", zBasePath);
  36059. sqlite3FileSuffix3(pDbFd->zPath, zShm);
  36060. #endif
  36061. pShmNode->hShm = -1;
  36062. pDbFd->pInode->pShmNode = pShmNode;
  36063. pShmNode->pInode = pDbFd->pInode;
  36064. if( sqlite3GlobalConfig.bCoreMutex ){
  36065. pShmNode->pShmMutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
  36066. if( pShmNode->pShmMutex==0 ){
  36067. rc = SQLITE_NOMEM_BKPT;
  36068. goto shm_open_err;
  36069. }
  36070. }
  36071. if( pInode->bProcessLock==0 ){
  36072. if( 0==sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
  36073. pShmNode->hShm = robust_open(zShm, O_RDWR|O_CREAT|O_NOFOLLOW,
  36074. (sStat.st_mode&0777));
  36075. }
  36076. if( pShmNode->hShm<0 ){
  36077. pShmNode->hShm = robust_open(zShm, O_RDONLY|O_NOFOLLOW,
  36078. (sStat.st_mode&0777));
  36079. if( pShmNode->hShm<0 ){
  36080. rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShm);
  36081. goto shm_open_err;
  36082. }
  36083. pShmNode->isReadonly = 1;
  36084. }
  36085. /* If this process is running as root, make sure that the SHM file
  36086. ** is owned by the same user that owns the original database. Otherwise,
  36087. ** the original owner will not be able to connect.
  36088. */
  36089. robustFchown(pShmNode->hShm, sStat.st_uid, sStat.st_gid);
  36090. rc = unixLockSharedMemory(pDbFd, pShmNode);
  36091. if( rc!=SQLITE_OK && rc!=SQLITE_READONLY_CANTINIT ) goto shm_open_err;
  36092. }
  36093. }
  36094. /* Make the new connection a child of the unixShmNode */
  36095. p->pShmNode = pShmNode;
  36096. #ifdef SQLITE_DEBUG
  36097. p->id = pShmNode->nextShmId++;
  36098. #endif
  36099. pShmNode->nRef++;
  36100. pDbFd->pShm = p;
  36101. unixLeaveMutex();
  36102. /* The reference count on pShmNode has already been incremented under
  36103. ** the cover of the unixEnterMutex() mutex and the pointer from the
  36104. ** new (struct unixShm) object to the pShmNode has been set. All that is
  36105. ** left to do is to link the new object into the linked list starting
  36106. ** at pShmNode->pFirst. This must be done while holding the
  36107. ** pShmNode->pShmMutex.
  36108. */
  36109. sqlite3_mutex_enter(pShmNode->pShmMutex);
  36110. p->pNext = pShmNode->pFirst;
  36111. pShmNode->pFirst = p;
  36112. sqlite3_mutex_leave(pShmNode->pShmMutex);
  36113. return rc;
  36114. /* Jump here on any error */
  36115. shm_open_err:
  36116. unixShmPurge(pDbFd); /* This call frees pShmNode if required */
  36117. sqlite3_free(p);
  36118. unixLeaveMutex();
  36119. return rc;
  36120. }
  36121. /*
  36122. ** This function is called to obtain a pointer to region iRegion of the
  36123. ** shared-memory associated with the database file fd. Shared-memory regions
  36124. ** are numbered starting from zero. Each shared-memory region is szRegion
  36125. ** bytes in size.
  36126. **
  36127. ** If an error occurs, an error code is returned and *pp is set to NULL.
  36128. **
  36129. ** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
  36130. ** region has not been allocated (by any client, including one running in a
  36131. ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
  36132. ** bExtend is non-zero and the requested shared-memory region has not yet
  36133. ** been allocated, it is allocated by this function.
  36134. **
  36135. ** If the shared-memory region has already been allocated or is allocated by
  36136. ** this call as described above, then it is mapped into this processes
  36137. ** address space (if it is not already), *pp is set to point to the mapped
  36138. ** memory and SQLITE_OK returned.
  36139. */
  36140. static int unixShmMap(
  36141. sqlite3_file *fd, /* Handle open on database file */
  36142. int iRegion, /* Region to retrieve */
  36143. int szRegion, /* Size of regions */
  36144. int bExtend, /* True to extend file if necessary */
  36145. void volatile **pp /* OUT: Mapped memory */
  36146. ){
  36147. unixFile *pDbFd = (unixFile*)fd;
  36148. unixShm *p;
  36149. unixShmNode *pShmNode;
  36150. int rc = SQLITE_OK;
  36151. int nShmPerMap = unixShmRegionPerMap();
  36152. int nReqRegion;
  36153. /* If the shared-memory file has not yet been opened, open it now. */
  36154. if( pDbFd->pShm==0 ){
  36155. rc = unixOpenSharedMemory(pDbFd);
  36156. if( rc!=SQLITE_OK ) return rc;
  36157. }
  36158. p = pDbFd->pShm;
  36159. pShmNode = p->pShmNode;
  36160. sqlite3_mutex_enter(pShmNode->pShmMutex);
  36161. if( pShmNode->isUnlocked ){
  36162. rc = unixLockSharedMemory(pDbFd, pShmNode);
  36163. if( rc!=SQLITE_OK ) goto shmpage_out;
  36164. pShmNode->isUnlocked = 0;
  36165. }
  36166. assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
  36167. assert( pShmNode->pInode==pDbFd->pInode );
  36168. assert( pShmNode->hShm>=0 || pDbFd->pInode->bProcessLock==1 );
  36169. assert( pShmNode->hShm<0 || pDbFd->pInode->bProcessLock==0 );
  36170. /* Minimum number of regions required to be mapped. */
  36171. nReqRegion = ((iRegion+nShmPerMap) / nShmPerMap) * nShmPerMap;
  36172. if( pShmNode->nRegion<nReqRegion ){
  36173. char **apNew; /* New apRegion[] array */
  36174. int nByte = nReqRegion*szRegion; /* Minimum required file size */
  36175. struct stat sStat; /* Used by fstat() */
  36176. pShmNode->szRegion = szRegion;
  36177. if( pShmNode->hShm>=0 ){
  36178. /* The requested region is not mapped into this processes address space.
  36179. ** Check to see if it has been allocated (i.e. if the wal-index file is
  36180. ** large enough to contain the requested region).
  36181. */
  36182. if( osFstat(pShmNode->hShm, &sStat) ){
  36183. rc = SQLITE_IOERR_SHMSIZE;
  36184. goto shmpage_out;
  36185. }
  36186. if( sStat.st_size<nByte ){
  36187. /* The requested memory region does not exist. If bExtend is set to
  36188. ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
  36189. */
  36190. if( !bExtend ){
  36191. goto shmpage_out;
  36192. }
  36193. /* Alternatively, if bExtend is true, extend the file. Do this by
  36194. ** writing a single byte to the end of each (OS) page being
  36195. ** allocated or extended. Technically, we need only write to the
  36196. ** last page in order to extend the file. But writing to all new
  36197. ** pages forces the OS to allocate them immediately, which reduces
  36198. ** the chances of SIGBUS while accessing the mapped region later on.
  36199. */
  36200. else{
  36201. static const int pgsz = 4096;
  36202. int iPg;
  36203. /* Write to the last byte of each newly allocated or extended page */
  36204. assert( (nByte % pgsz)==0 );
  36205. for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
  36206. int x = 0;
  36207. if( seekAndWriteFd(pShmNode->hShm, iPg*pgsz + pgsz-1,"",1,&x)!=1 ){
  36208. const char *zFile = pShmNode->zFilename;
  36209. rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
  36210. goto shmpage_out;
  36211. }
  36212. }
  36213. }
  36214. }
  36215. }
  36216. /* Map the requested memory region into this processes address space. */
  36217. apNew = (char **)sqlite3_realloc(
  36218. pShmNode->apRegion, nReqRegion*sizeof(char *)
  36219. );
  36220. if( !apNew ){
  36221. rc = SQLITE_IOERR_NOMEM_BKPT;
  36222. goto shmpage_out;
  36223. }
  36224. pShmNode->apRegion = apNew;
  36225. while( pShmNode->nRegion<nReqRegion ){
  36226. int nMap = szRegion*nShmPerMap;
  36227. int i;
  36228. void *pMem;
  36229. if( pShmNode->hShm>=0 ){
  36230. pMem = osMmap(0, nMap,
  36231. pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
  36232. MAP_SHARED, pShmNode->hShm, szRegion*(i64)pShmNode->nRegion
  36233. );
  36234. if( pMem==MAP_FAILED ){
  36235. rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
  36236. goto shmpage_out;
  36237. }
  36238. }else{
  36239. pMem = sqlite3_malloc64(nMap);
  36240. if( pMem==0 ){
  36241. rc = SQLITE_NOMEM_BKPT;
  36242. goto shmpage_out;
  36243. }
  36244. memset(pMem, 0, nMap);
  36245. }
  36246. for(i=0; i<nShmPerMap; i++){
  36247. pShmNode->apRegion[pShmNode->nRegion+i] = &((char*)pMem)[szRegion*i];
  36248. }
  36249. pShmNode->nRegion += nShmPerMap;
  36250. }
  36251. }
  36252. shmpage_out:
  36253. if( pShmNode->nRegion>iRegion ){
  36254. *pp = pShmNode->apRegion[iRegion];
  36255. }else{
  36256. *pp = 0;
  36257. }
  36258. if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
  36259. sqlite3_mutex_leave(pShmNode->pShmMutex);
  36260. return rc;
  36261. }
  36262. /*
  36263. ** Change the lock state for a shared-memory segment.
  36264. **
  36265. ** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
  36266. ** different here than in posix. In xShmLock(), one can go from unlocked
  36267. ** to shared and back or from unlocked to exclusive and back. But one may
  36268. ** not go from shared to exclusive or from exclusive to shared.
  36269. */
  36270. static int unixShmLock(
  36271. sqlite3_file *fd, /* Database file holding the shared memory */
  36272. int ofst, /* First lock to acquire or release */
  36273. int n, /* Number of locks to acquire or release */
  36274. int flags /* What to do with the lock */
  36275. ){
  36276. unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
  36277. unixShm *p = pDbFd->pShm; /* The shared memory being locked */
  36278. unixShm *pX; /* For looping over all siblings */
  36279. unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
  36280. int rc = SQLITE_OK; /* Result code */
  36281. u16 mask; /* Mask of locks to take or release */
  36282. assert( pShmNode==pDbFd->pInode->pShmNode );
  36283. assert( pShmNode->pInode==pDbFd->pInode );
  36284. assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
  36285. assert( n>=1 );
  36286. assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
  36287. || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
  36288. || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
  36289. || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
  36290. assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
  36291. assert( pShmNode->hShm>=0 || pDbFd->pInode->bProcessLock==1 );
  36292. assert( pShmNode->hShm<0 || pDbFd->pInode->bProcessLock==0 );
  36293. /* Check that, if this to be a blocking lock, no locks that occur later
  36294. ** in the following list than the lock being obtained are already held:
  36295. **
  36296. ** 1. Checkpointer lock (ofst==1).
  36297. ** 2. Write lock (ofst==0).
  36298. ** 3. Read locks (ofst>=3 && ofst<SQLITE_SHM_NLOCK).
  36299. **
  36300. ** In other words, if this is a blocking lock, none of the locks that
  36301. ** occur later in the above list than the lock being obtained may be
  36302. ** held. */
  36303. #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
  36304. assert( (flags & SQLITE_SHM_UNLOCK) || pDbFd->iBusyTimeout==0 || (
  36305. (ofst!=2) /* not RECOVER */
  36306. && (ofst!=1 || (p->exclMask|p->sharedMask)==0)
  36307. && (ofst!=0 || (p->exclMask|p->sharedMask)<3)
  36308. && (ofst<3 || (p->exclMask|p->sharedMask)<(1<<ofst))
  36309. ));
  36310. #endif
  36311. mask = (1<<(ofst+n)) - (1<<ofst);
  36312. assert( n>1 || mask==(1<<ofst) );
  36313. sqlite3_mutex_enter(pShmNode->pShmMutex);
  36314. if( flags & SQLITE_SHM_UNLOCK ){
  36315. u16 allMask = 0; /* Mask of locks held by siblings */
  36316. /* See if any siblings hold this same lock */
  36317. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  36318. if( pX==p ) continue;
  36319. assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
  36320. allMask |= pX->sharedMask;
  36321. }
  36322. /* Unlock the system-level locks */
  36323. if( (mask & allMask)==0 ){
  36324. rc = unixShmSystemLock(pDbFd, F_UNLCK, ofst+UNIX_SHM_BASE, n);
  36325. }else{
  36326. rc = SQLITE_OK;
  36327. }
  36328. /* Undo the local locks */
  36329. if( rc==SQLITE_OK ){
  36330. p->exclMask &= ~mask;
  36331. p->sharedMask &= ~mask;
  36332. }
  36333. }else if( flags & SQLITE_SHM_SHARED ){
  36334. u16 allShared = 0; /* Union of locks held by connections other than "p" */
  36335. /* Find out which shared locks are already held by sibling connections.
  36336. ** If any sibling already holds an exclusive lock, go ahead and return
  36337. ** SQLITE_BUSY.
  36338. */
  36339. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  36340. if( (pX->exclMask & mask)!=0 ){
  36341. rc = SQLITE_BUSY;
  36342. break;
  36343. }
  36344. allShared |= pX->sharedMask;
  36345. }
  36346. /* Get shared locks at the system level, if necessary */
  36347. if( rc==SQLITE_OK ){
  36348. if( (allShared & mask)==0 ){
  36349. rc = unixShmSystemLock(pDbFd, F_RDLCK, ofst+UNIX_SHM_BASE, n);
  36350. }else{
  36351. rc = SQLITE_OK;
  36352. }
  36353. }
  36354. /* Get the local shared locks */
  36355. if( rc==SQLITE_OK ){
  36356. p->sharedMask |= mask;
  36357. }
  36358. }else{
  36359. /* Make sure no sibling connections hold locks that will block this
  36360. ** lock. If any do, return SQLITE_BUSY right away.
  36361. */
  36362. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  36363. if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
  36364. rc = SQLITE_BUSY;
  36365. break;
  36366. }
  36367. }
  36368. /* Get the exclusive locks at the system level. Then if successful
  36369. ** also mark the local connection as being locked.
  36370. */
  36371. if( rc==SQLITE_OK ){
  36372. rc = unixShmSystemLock(pDbFd, F_WRLCK, ofst+UNIX_SHM_BASE, n);
  36373. if( rc==SQLITE_OK ){
  36374. assert( (p->sharedMask & mask)==0 );
  36375. p->exclMask |= mask;
  36376. }
  36377. }
  36378. }
  36379. sqlite3_mutex_leave(pShmNode->pShmMutex);
  36380. OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
  36381. p->id, osGetpid(0), p->sharedMask, p->exclMask));
  36382. return rc;
  36383. }
  36384. /*
  36385. ** Implement a memory barrier or memory fence on shared memory.
  36386. **
  36387. ** All loads and stores begun before the barrier must complete before
  36388. ** any load or store begun after the barrier.
  36389. */
  36390. static void unixShmBarrier(
  36391. sqlite3_file *fd /* Database file holding the shared memory */
  36392. ){
  36393. UNUSED_PARAMETER(fd);
  36394. sqlite3MemoryBarrier(); /* compiler-defined memory barrier */
  36395. assert( fd->pMethods->xLock==nolockLock
  36396. || unixFileMutexNotheld((unixFile*)fd)
  36397. );
  36398. unixEnterMutex(); /* Also mutex, for redundancy */
  36399. unixLeaveMutex();
  36400. }
  36401. /*
  36402. ** Close a connection to shared-memory. Delete the underlying
  36403. ** storage if deleteFlag is true.
  36404. **
  36405. ** If there is no shared memory associated with the connection then this
  36406. ** routine is a harmless no-op.
  36407. */
  36408. static int unixShmUnmap(
  36409. sqlite3_file *fd, /* The underlying database file */
  36410. int deleteFlag /* Delete shared-memory if true */
  36411. ){
  36412. unixShm *p; /* The connection to be closed */
  36413. unixShmNode *pShmNode; /* The underlying shared-memory file */
  36414. unixShm **pp; /* For looping over sibling connections */
  36415. unixFile *pDbFd; /* The underlying database file */
  36416. pDbFd = (unixFile*)fd;
  36417. p = pDbFd->pShm;
  36418. if( p==0 ) return SQLITE_OK;
  36419. pShmNode = p->pShmNode;
  36420. assert( pShmNode==pDbFd->pInode->pShmNode );
  36421. assert( pShmNode->pInode==pDbFd->pInode );
  36422. /* Remove connection p from the set of connections associated
  36423. ** with pShmNode */
  36424. sqlite3_mutex_enter(pShmNode->pShmMutex);
  36425. for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
  36426. *pp = p->pNext;
  36427. /* Free the connection p */
  36428. sqlite3_free(p);
  36429. pDbFd->pShm = 0;
  36430. sqlite3_mutex_leave(pShmNode->pShmMutex);
  36431. /* If pShmNode->nRef has reached 0, then close the underlying
  36432. ** shared-memory file, too */
  36433. assert( unixFileMutexNotheld(pDbFd) );
  36434. unixEnterMutex();
  36435. assert( pShmNode->nRef>0 );
  36436. pShmNode->nRef--;
  36437. if( pShmNode->nRef==0 ){
  36438. if( deleteFlag && pShmNode->hShm>=0 ){
  36439. osUnlink(pShmNode->zFilename);
  36440. }
  36441. unixShmPurge(pDbFd);
  36442. }
  36443. unixLeaveMutex();
  36444. return SQLITE_OK;
  36445. }
  36446. #else
  36447. # define unixShmMap 0
  36448. # define unixShmLock 0
  36449. # define unixShmBarrier 0
  36450. # define unixShmUnmap 0
  36451. #endif /* #ifndef SQLITE_OMIT_WAL */
  36452. #if SQLITE_MAX_MMAP_SIZE>0
  36453. /*
  36454. ** If it is currently memory mapped, unmap file pFd.
  36455. */
  36456. static void unixUnmapfile(unixFile *pFd){
  36457. assert( pFd->nFetchOut==0 );
  36458. if( pFd->pMapRegion ){
  36459. osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
  36460. pFd->pMapRegion = 0;
  36461. pFd->mmapSize = 0;
  36462. pFd->mmapSizeActual = 0;
  36463. }
  36464. }
  36465. /*
  36466. ** Attempt to set the size of the memory mapping maintained by file
  36467. ** descriptor pFd to nNew bytes. Any existing mapping is discarded.
  36468. **
  36469. ** If successful, this function sets the following variables:
  36470. **
  36471. ** unixFile.pMapRegion
  36472. ** unixFile.mmapSize
  36473. ** unixFile.mmapSizeActual
  36474. **
  36475. ** If unsuccessful, an error message is logged via sqlite3_log() and
  36476. ** the three variables above are zeroed. In this case SQLite should
  36477. ** continue accessing the database using the xRead() and xWrite()
  36478. ** methods.
  36479. */
  36480. static void unixRemapfile(
  36481. unixFile *pFd, /* File descriptor object */
  36482. i64 nNew /* Required mapping size */
  36483. ){
  36484. const char *zErr = "mmap";
  36485. int h = pFd->h; /* File descriptor open on db file */
  36486. u8 *pOrig = (u8 *)pFd->pMapRegion; /* Pointer to current file mapping */
  36487. i64 nOrig = pFd->mmapSizeActual; /* Size of pOrig region in bytes */
  36488. u8 *pNew = 0; /* Location of new mapping */
  36489. int flags = PROT_READ; /* Flags to pass to mmap() */
  36490. assert( pFd->nFetchOut==0 );
  36491. assert( nNew>pFd->mmapSize );
  36492. assert( nNew<=pFd->mmapSizeMax );
  36493. assert( nNew>0 );
  36494. assert( pFd->mmapSizeActual>=pFd->mmapSize );
  36495. assert( MAP_FAILED!=0 );
  36496. #ifdef SQLITE_MMAP_READWRITE
  36497. if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
  36498. #endif
  36499. if( pOrig ){
  36500. #if HAVE_MREMAP
  36501. i64 nReuse = pFd->mmapSize;
  36502. #else
  36503. const int szSyspage = osGetpagesize();
  36504. i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
  36505. #endif
  36506. u8 *pReq = &pOrig[nReuse];
  36507. /* Unmap any pages of the existing mapping that cannot be reused. */
  36508. if( nReuse!=nOrig ){
  36509. osMunmap(pReq, nOrig-nReuse);
  36510. }
  36511. #if HAVE_MREMAP
  36512. pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
  36513. zErr = "mremap";
  36514. #else
  36515. pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
  36516. if( pNew!=MAP_FAILED ){
  36517. if( pNew!=pReq ){
  36518. osMunmap(pNew, nNew - nReuse);
  36519. pNew = 0;
  36520. }else{
  36521. pNew = pOrig;
  36522. }
  36523. }
  36524. #endif
  36525. /* The attempt to extend the existing mapping failed. Free it. */
  36526. if( pNew==MAP_FAILED || pNew==0 ){
  36527. osMunmap(pOrig, nReuse);
  36528. }
  36529. }
  36530. /* If pNew is still NULL, try to create an entirely new mapping. */
  36531. if( pNew==0 ){
  36532. pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
  36533. }
  36534. if( pNew==MAP_FAILED ){
  36535. pNew = 0;
  36536. nNew = 0;
  36537. unixLogError(SQLITE_OK, zErr, pFd->zPath);
  36538. /* If the mmap() above failed, assume that all subsequent mmap() calls
  36539. ** will probably fail too. Fall back to using xRead/xWrite exclusively
  36540. ** in this case. */
  36541. pFd->mmapSizeMax = 0;
  36542. }
  36543. pFd->pMapRegion = (void *)pNew;
  36544. pFd->mmapSize = pFd->mmapSizeActual = nNew;
  36545. }
  36546. /*
  36547. ** Memory map or remap the file opened by file-descriptor pFd (if the file
  36548. ** is already mapped, the existing mapping is replaced by the new). Or, if
  36549. ** there already exists a mapping for this file, and there are still
  36550. ** outstanding xFetch() references to it, this function is a no-op.
  36551. **
  36552. ** If parameter nByte is non-negative, then it is the requested size of
  36553. ** the mapping to create. Otherwise, if nByte is less than zero, then the
  36554. ** requested size is the size of the file on disk. The actual size of the
  36555. ** created mapping is either the requested size or the value configured
  36556. ** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
  36557. **
  36558. ** SQLITE_OK is returned if no error occurs (even if the mapping is not
  36559. ** recreated as a result of outstanding references) or an SQLite error
  36560. ** code otherwise.
  36561. */
  36562. static int unixMapfile(unixFile *pFd, i64 nMap){
  36563. assert( nMap>=0 || pFd->nFetchOut==0 );
  36564. assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
  36565. if( pFd->nFetchOut>0 ) return SQLITE_OK;
  36566. if( nMap<0 ){
  36567. struct stat statbuf; /* Low-level file information */
  36568. if( osFstat(pFd->h, &statbuf) ){
  36569. return SQLITE_IOERR_FSTAT;
  36570. }
  36571. nMap = statbuf.st_size;
  36572. }
  36573. if( nMap>pFd->mmapSizeMax ){
  36574. nMap = pFd->mmapSizeMax;
  36575. }
  36576. assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
  36577. if( nMap!=pFd->mmapSize ){
  36578. unixRemapfile(pFd, nMap);
  36579. }
  36580. return SQLITE_OK;
  36581. }
  36582. #endif /* SQLITE_MAX_MMAP_SIZE>0 */
  36583. /*
  36584. ** If possible, return a pointer to a mapping of file fd starting at offset
  36585. ** iOff. The mapping must be valid for at least nAmt bytes.
  36586. **
  36587. ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
  36588. ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
  36589. ** Finally, if an error does occur, return an SQLite error code. The final
  36590. ** value of *pp is undefined in this case.
  36591. **
  36592. ** If this function does return a pointer, the caller must eventually
  36593. ** release the reference by calling unixUnfetch().
  36594. */
  36595. static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
  36596. #if SQLITE_MAX_MMAP_SIZE>0
  36597. unixFile *pFd = (unixFile *)fd; /* The underlying database file */
  36598. #endif
  36599. *pp = 0;
  36600. #if SQLITE_MAX_MMAP_SIZE>0
  36601. if( pFd->mmapSizeMax>0 ){
  36602. if( pFd->pMapRegion==0 ){
  36603. int rc = unixMapfile(pFd, -1);
  36604. if( rc!=SQLITE_OK ) return rc;
  36605. }
  36606. if( pFd->mmapSize >= iOff+nAmt ){
  36607. *pp = &((u8 *)pFd->pMapRegion)[iOff];
  36608. pFd->nFetchOut++;
  36609. }
  36610. }
  36611. #endif
  36612. return SQLITE_OK;
  36613. }
  36614. /*
  36615. ** If the third argument is non-NULL, then this function releases a
  36616. ** reference obtained by an earlier call to unixFetch(). The second
  36617. ** argument passed to this function must be the same as the corresponding
  36618. ** argument that was passed to the unixFetch() invocation.
  36619. **
  36620. ** Or, if the third argument is NULL, then this function is being called
  36621. ** to inform the VFS layer that, according to POSIX, any existing mapping
  36622. ** may now be invalid and should be unmapped.
  36623. */
  36624. static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
  36625. #if SQLITE_MAX_MMAP_SIZE>0
  36626. unixFile *pFd = (unixFile *)fd; /* The underlying database file */
  36627. UNUSED_PARAMETER(iOff);
  36628. /* If p==0 (unmap the entire file) then there must be no outstanding
  36629. ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
  36630. ** then there must be at least one outstanding. */
  36631. assert( (p==0)==(pFd->nFetchOut==0) );
  36632. /* If p!=0, it must match the iOff value. */
  36633. assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
  36634. if( p ){
  36635. pFd->nFetchOut--;
  36636. }else{
  36637. unixUnmapfile(pFd);
  36638. }
  36639. assert( pFd->nFetchOut>=0 );
  36640. #else
  36641. UNUSED_PARAMETER(fd);
  36642. UNUSED_PARAMETER(p);
  36643. UNUSED_PARAMETER(iOff);
  36644. #endif
  36645. return SQLITE_OK;
  36646. }
  36647. /*
  36648. ** Here ends the implementation of all sqlite3_file methods.
  36649. **
  36650. ********************** End sqlite3_file Methods *******************************
  36651. ******************************************************************************/
  36652. /*
  36653. ** This division contains definitions of sqlite3_io_methods objects that
  36654. ** implement various file locking strategies. It also contains definitions
  36655. ** of "finder" functions. A finder-function is used to locate the appropriate
  36656. ** sqlite3_io_methods object for a particular database file. The pAppData
  36657. ** field of the sqlite3_vfs VFS objects are initialized to be pointers to
  36658. ** the correct finder-function for that VFS.
  36659. **
  36660. ** Most finder functions return a pointer to a fixed sqlite3_io_methods
  36661. ** object. The only interesting finder-function is autolockIoFinder, which
  36662. ** looks at the filesystem type and tries to guess the best locking
  36663. ** strategy from that.
  36664. **
  36665. ** For finder-function F, two objects are created:
  36666. **
  36667. ** (1) The real finder-function named "FImpt()".
  36668. **
  36669. ** (2) A constant pointer to this function named just "F".
  36670. **
  36671. **
  36672. ** A pointer to the F pointer is used as the pAppData value for VFS
  36673. ** objects. We have to do this instead of letting pAppData point
  36674. ** directly at the finder-function since C90 rules prevent a void*
  36675. ** from be cast into a function pointer.
  36676. **
  36677. **
  36678. ** Each instance of this macro generates two objects:
  36679. **
  36680. ** * A constant sqlite3_io_methods object call METHOD that has locking
  36681. ** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
  36682. **
  36683. ** * An I/O method finder function called FINDER that returns a pointer
  36684. ** to the METHOD object in the previous bullet.
  36685. */
  36686. #define IOMETHODS(FINDER,METHOD,VERSION,CLOSE,LOCK,UNLOCK,CKLOCK,SHMMAP) \
  36687. static const sqlite3_io_methods METHOD = { \
  36688. VERSION, /* iVersion */ \
  36689. CLOSE, /* xClose */ \
  36690. unixRead, /* xRead */ \
  36691. unixWrite, /* xWrite */ \
  36692. unixTruncate, /* xTruncate */ \
  36693. unixSync, /* xSync */ \
  36694. unixFileSize, /* xFileSize */ \
  36695. LOCK, /* xLock */ \
  36696. UNLOCK, /* xUnlock */ \
  36697. CKLOCK, /* xCheckReservedLock */ \
  36698. unixFileControl, /* xFileControl */ \
  36699. unixSectorSize, /* xSectorSize */ \
  36700. unixDeviceCharacteristics, /* xDeviceCapabilities */ \
  36701. SHMMAP, /* xShmMap */ \
  36702. unixShmLock, /* xShmLock */ \
  36703. unixShmBarrier, /* xShmBarrier */ \
  36704. unixShmUnmap, /* xShmUnmap */ \
  36705. unixFetch, /* xFetch */ \
  36706. unixUnfetch, /* xUnfetch */ \
  36707. }; \
  36708. static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
  36709. UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
  36710. return &METHOD; \
  36711. } \
  36712. static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
  36713. = FINDER##Impl;
  36714. /*
  36715. ** Here are all of the sqlite3_io_methods objects for each of the
  36716. ** locking strategies. Functions that return pointers to these methods
  36717. ** are also created.
  36718. */
  36719. IOMETHODS(
  36720. posixIoFinder, /* Finder function name */
  36721. posixIoMethods, /* sqlite3_io_methods object name */
  36722. 3, /* shared memory and mmap are enabled */
  36723. unixClose, /* xClose method */
  36724. unixLock, /* xLock method */
  36725. unixUnlock, /* xUnlock method */
  36726. unixCheckReservedLock, /* xCheckReservedLock method */
  36727. unixShmMap /* xShmMap method */
  36728. )
  36729. IOMETHODS(
  36730. nolockIoFinder, /* Finder function name */
  36731. nolockIoMethods, /* sqlite3_io_methods object name */
  36732. 3, /* shared memory and mmap are enabled */
  36733. nolockClose, /* xClose method */
  36734. nolockLock, /* xLock method */
  36735. nolockUnlock, /* xUnlock method */
  36736. nolockCheckReservedLock, /* xCheckReservedLock method */
  36737. 0 /* xShmMap method */
  36738. )
  36739. IOMETHODS(
  36740. dotlockIoFinder, /* Finder function name */
  36741. dotlockIoMethods, /* sqlite3_io_methods object name */
  36742. 1, /* shared memory is disabled */
  36743. dotlockClose, /* xClose method */
  36744. dotlockLock, /* xLock method */
  36745. dotlockUnlock, /* xUnlock method */
  36746. dotlockCheckReservedLock, /* xCheckReservedLock method */
  36747. 0 /* xShmMap method */
  36748. )
  36749. #if SQLITE_ENABLE_LOCKING_STYLE
  36750. IOMETHODS(
  36751. flockIoFinder, /* Finder function name */
  36752. flockIoMethods, /* sqlite3_io_methods object name */
  36753. 1, /* shared memory is disabled */
  36754. flockClose, /* xClose method */
  36755. flockLock, /* xLock method */
  36756. flockUnlock, /* xUnlock method */
  36757. flockCheckReservedLock, /* xCheckReservedLock method */
  36758. 0 /* xShmMap method */
  36759. )
  36760. #endif
  36761. #if OS_VXWORKS
  36762. IOMETHODS(
  36763. semIoFinder, /* Finder function name */
  36764. semIoMethods, /* sqlite3_io_methods object name */
  36765. 1, /* shared memory is disabled */
  36766. semXClose, /* xClose method */
  36767. semXLock, /* xLock method */
  36768. semXUnlock, /* xUnlock method */
  36769. semXCheckReservedLock, /* xCheckReservedLock method */
  36770. 0 /* xShmMap method */
  36771. )
  36772. #endif
  36773. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  36774. IOMETHODS(
  36775. afpIoFinder, /* Finder function name */
  36776. afpIoMethods, /* sqlite3_io_methods object name */
  36777. 1, /* shared memory is disabled */
  36778. afpClose, /* xClose method */
  36779. afpLock, /* xLock method */
  36780. afpUnlock, /* xUnlock method */
  36781. afpCheckReservedLock, /* xCheckReservedLock method */
  36782. 0 /* xShmMap method */
  36783. )
  36784. #endif
  36785. /*
  36786. ** The proxy locking method is a "super-method" in the sense that it
  36787. ** opens secondary file descriptors for the conch and lock files and
  36788. ** it uses proxy, dot-file, AFP, and flock() locking methods on those
  36789. ** secondary files. For this reason, the division that implements
  36790. ** proxy locking is located much further down in the file. But we need
  36791. ** to go ahead and define the sqlite3_io_methods and finder function
  36792. ** for proxy locking here. So we forward declare the I/O methods.
  36793. */
  36794. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  36795. static int proxyClose(sqlite3_file*);
  36796. static int proxyLock(sqlite3_file*, int);
  36797. static int proxyUnlock(sqlite3_file*, int);
  36798. static int proxyCheckReservedLock(sqlite3_file*, int*);
  36799. IOMETHODS(
  36800. proxyIoFinder, /* Finder function name */
  36801. proxyIoMethods, /* sqlite3_io_methods object name */
  36802. 1, /* shared memory is disabled */
  36803. proxyClose, /* xClose method */
  36804. proxyLock, /* xLock method */
  36805. proxyUnlock, /* xUnlock method */
  36806. proxyCheckReservedLock, /* xCheckReservedLock method */
  36807. 0 /* xShmMap method */
  36808. )
  36809. #endif
  36810. /* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
  36811. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  36812. IOMETHODS(
  36813. nfsIoFinder, /* Finder function name */
  36814. nfsIoMethods, /* sqlite3_io_methods object name */
  36815. 1, /* shared memory is disabled */
  36816. unixClose, /* xClose method */
  36817. unixLock, /* xLock method */
  36818. nfsUnlock, /* xUnlock method */
  36819. unixCheckReservedLock, /* xCheckReservedLock method */
  36820. 0 /* xShmMap method */
  36821. )
  36822. #endif
  36823. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  36824. /*
  36825. ** This "finder" function attempts to determine the best locking strategy
  36826. ** for the database file "filePath". It then returns the sqlite3_io_methods
  36827. ** object that implements that strategy.
  36828. **
  36829. ** This is for MacOSX only.
  36830. */
  36831. static const sqlite3_io_methods *autolockIoFinderImpl(
  36832. const char *filePath, /* name of the database file */
  36833. unixFile *pNew /* open file object for the database file */
  36834. ){
  36835. static const struct Mapping {
  36836. const char *zFilesystem; /* Filesystem type name */
  36837. const sqlite3_io_methods *pMethods; /* Appropriate locking method */
  36838. } aMap[] = {
  36839. { "hfs", &posixIoMethods },
  36840. { "ufs", &posixIoMethods },
  36841. { "afpfs", &afpIoMethods },
  36842. { "smbfs", &afpIoMethods },
  36843. { "webdav", &nolockIoMethods },
  36844. { 0, 0 }
  36845. };
  36846. int i;
  36847. struct statfs fsInfo;
  36848. struct flock lockInfo;
  36849. if( !filePath ){
  36850. /* If filePath==NULL that means we are dealing with a transient file
  36851. ** that does not need to be locked. */
  36852. return &nolockIoMethods;
  36853. }
  36854. if( statfs(filePath, &fsInfo) != -1 ){
  36855. if( fsInfo.f_flags & MNT_RDONLY ){
  36856. return &nolockIoMethods;
  36857. }
  36858. for(i=0; aMap[i].zFilesystem; i++){
  36859. if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
  36860. return aMap[i].pMethods;
  36861. }
  36862. }
  36863. }
  36864. /* Default case. Handles, amongst others, "nfs".
  36865. ** Test byte-range lock using fcntl(). If the call succeeds,
  36866. ** assume that the file-system supports POSIX style locks.
  36867. */
  36868. lockInfo.l_len = 1;
  36869. lockInfo.l_start = 0;
  36870. lockInfo.l_whence = SEEK_SET;
  36871. lockInfo.l_type = F_RDLCK;
  36872. if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
  36873. if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
  36874. return &nfsIoMethods;
  36875. } else {
  36876. return &posixIoMethods;
  36877. }
  36878. }else{
  36879. return &dotlockIoMethods;
  36880. }
  36881. }
  36882. static const sqlite3_io_methods
  36883. *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
  36884. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  36885. #if OS_VXWORKS
  36886. /*
  36887. ** This "finder" function for VxWorks checks to see if posix advisory
  36888. ** locking works. If it does, then that is what is used. If it does not
  36889. ** work, then fallback to named semaphore locking.
  36890. */
  36891. static const sqlite3_io_methods *vxworksIoFinderImpl(
  36892. const char *filePath, /* name of the database file */
  36893. unixFile *pNew /* the open file object */
  36894. ){
  36895. struct flock lockInfo;
  36896. if( !filePath ){
  36897. /* If filePath==NULL that means we are dealing with a transient file
  36898. ** that does not need to be locked. */
  36899. return &nolockIoMethods;
  36900. }
  36901. /* Test if fcntl() is supported and use POSIX style locks.
  36902. ** Otherwise fall back to the named semaphore method.
  36903. */
  36904. lockInfo.l_len = 1;
  36905. lockInfo.l_start = 0;
  36906. lockInfo.l_whence = SEEK_SET;
  36907. lockInfo.l_type = F_RDLCK;
  36908. if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
  36909. return &posixIoMethods;
  36910. }else{
  36911. return &semIoMethods;
  36912. }
  36913. }
  36914. static const sqlite3_io_methods
  36915. *(*const vxworksIoFinder)(const char*,unixFile*) = vxworksIoFinderImpl;
  36916. #endif /* OS_VXWORKS */
  36917. /*
  36918. ** An abstract type for a pointer to an IO method finder function:
  36919. */
  36920. typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
  36921. /****************************************************************************
  36922. **************************** sqlite3_vfs methods ****************************
  36923. **
  36924. ** This division contains the implementation of methods on the
  36925. ** sqlite3_vfs object.
  36926. */
  36927. /*
  36928. ** Initialize the contents of the unixFile structure pointed to by pId.
  36929. */
  36930. static int fillInUnixFile(
  36931. sqlite3_vfs *pVfs, /* Pointer to vfs object */
  36932. int h, /* Open file descriptor of file being opened */
  36933. sqlite3_file *pId, /* Write to the unixFile structure here */
  36934. const char *zFilename, /* Name of the file being opened */
  36935. int ctrlFlags /* Zero or more UNIXFILE_* values */
  36936. ){
  36937. const sqlite3_io_methods *pLockingStyle;
  36938. unixFile *pNew = (unixFile *)pId;
  36939. int rc = SQLITE_OK;
  36940. assert( pNew->pInode==NULL );
  36941. /* No locking occurs in temporary files */
  36942. assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
  36943. OSTRACE(("OPEN %-3d %s\n", h, zFilename));
  36944. pNew->h = h;
  36945. pNew->pVfs = pVfs;
  36946. pNew->zPath = zFilename;
  36947. pNew->ctrlFlags = (u8)ctrlFlags;
  36948. #if SQLITE_MAX_MMAP_SIZE>0
  36949. pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
  36950. #endif
  36951. if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
  36952. "psow", SQLITE_POWERSAFE_OVERWRITE) ){
  36953. pNew->ctrlFlags |= UNIXFILE_PSOW;
  36954. }
  36955. if( strcmp(pVfs->zName,"unix-excl")==0 ){
  36956. pNew->ctrlFlags |= UNIXFILE_EXCL;
  36957. }
  36958. #if OS_VXWORKS
  36959. pNew->pId = vxworksFindFileId(zFilename);
  36960. if( pNew->pId==0 ){
  36961. ctrlFlags |= UNIXFILE_NOLOCK;
  36962. rc = SQLITE_NOMEM_BKPT;
  36963. }
  36964. #endif
  36965. if( ctrlFlags & UNIXFILE_NOLOCK ){
  36966. pLockingStyle = &nolockIoMethods;
  36967. }else{
  36968. pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
  36969. #if SQLITE_ENABLE_LOCKING_STYLE
  36970. /* Cache zFilename in the locking context (AFP and dotlock override) for
  36971. ** proxyLock activation is possible (remote proxy is based on db name)
  36972. ** zFilename remains valid until file is closed, to support */
  36973. pNew->lockingContext = (void*)zFilename;
  36974. #endif
  36975. }
  36976. if( pLockingStyle == &posixIoMethods
  36977. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  36978. || pLockingStyle == &nfsIoMethods
  36979. #endif
  36980. ){
  36981. unixEnterMutex();
  36982. rc = findInodeInfo(pNew, &pNew->pInode);
  36983. if( rc!=SQLITE_OK ){
  36984. /* If an error occurred in findInodeInfo(), close the file descriptor
  36985. ** immediately, before releasing the mutex. findInodeInfo() may fail
  36986. ** in two scenarios:
  36987. **
  36988. ** (a) A call to fstat() failed.
  36989. ** (b) A malloc failed.
  36990. **
  36991. ** Scenario (b) may only occur if the process is holding no other
  36992. ** file descriptors open on the same file. If there were other file
  36993. ** descriptors on this file, then no malloc would be required by
  36994. ** findInodeInfo(). If this is the case, it is quite safe to close
  36995. ** handle h - as it is guaranteed that no posix locks will be released
  36996. ** by doing so.
  36997. **
  36998. ** If scenario (a) caused the error then things are not so safe. The
  36999. ** implicit assumption here is that if fstat() fails, things are in
  37000. ** such bad shape that dropping a lock or two doesn't matter much.
  37001. */
  37002. robust_close(pNew, h, __LINE__);
  37003. h = -1;
  37004. }
  37005. unixLeaveMutex();
  37006. }
  37007. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  37008. else if( pLockingStyle == &afpIoMethods ){
  37009. /* AFP locking uses the file path so it needs to be included in
  37010. ** the afpLockingContext.
  37011. */
  37012. afpLockingContext *pCtx;
  37013. pNew->lockingContext = pCtx = sqlite3_malloc64( sizeof(*pCtx) );
  37014. if( pCtx==0 ){
  37015. rc = SQLITE_NOMEM_BKPT;
  37016. }else{
  37017. /* NB: zFilename exists and remains valid until the file is closed
  37018. ** according to requirement F11141. So we do not need to make a
  37019. ** copy of the filename. */
  37020. pCtx->dbPath = zFilename;
  37021. pCtx->reserved = 0;
  37022. srandomdev();
  37023. unixEnterMutex();
  37024. rc = findInodeInfo(pNew, &pNew->pInode);
  37025. if( rc!=SQLITE_OK ){
  37026. sqlite3_free(pNew->lockingContext);
  37027. robust_close(pNew, h, __LINE__);
  37028. h = -1;
  37029. }
  37030. unixLeaveMutex();
  37031. }
  37032. }
  37033. #endif
  37034. else if( pLockingStyle == &dotlockIoMethods ){
  37035. /* Dotfile locking uses the file path so it needs to be included in
  37036. ** the dotlockLockingContext
  37037. */
  37038. char *zLockFile;
  37039. int nFilename;
  37040. assert( zFilename!=0 );
  37041. nFilename = (int)strlen(zFilename) + 6;
  37042. zLockFile = (char *)sqlite3_malloc64(nFilename);
  37043. if( zLockFile==0 ){
  37044. rc = SQLITE_NOMEM_BKPT;
  37045. }else{
  37046. sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
  37047. }
  37048. pNew->lockingContext = zLockFile;
  37049. }
  37050. #if OS_VXWORKS
  37051. else if( pLockingStyle == &semIoMethods ){
  37052. /* Named semaphore locking uses the file path so it needs to be
  37053. ** included in the semLockingContext
  37054. */
  37055. unixEnterMutex();
  37056. rc = findInodeInfo(pNew, &pNew->pInode);
  37057. if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
  37058. char *zSemName = pNew->pInode->aSemName;
  37059. int n;
  37060. sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
  37061. pNew->pId->zCanonicalName);
  37062. for( n=1; zSemName[n]; n++ )
  37063. if( zSemName[n]=='/' ) zSemName[n] = '_';
  37064. pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
  37065. if( pNew->pInode->pSem == SEM_FAILED ){
  37066. rc = SQLITE_NOMEM_BKPT;
  37067. pNew->pInode->aSemName[0] = '\0';
  37068. }
  37069. }
  37070. unixLeaveMutex();
  37071. }
  37072. #endif
  37073. storeLastErrno(pNew, 0);
  37074. #if OS_VXWORKS
  37075. if( rc!=SQLITE_OK ){
  37076. if( h>=0 ) robust_close(pNew, h, __LINE__);
  37077. h = -1;
  37078. osUnlink(zFilename);
  37079. pNew->ctrlFlags |= UNIXFILE_DELETE;
  37080. }
  37081. #endif
  37082. if( rc!=SQLITE_OK ){
  37083. if( h>=0 ) robust_close(pNew, h, __LINE__);
  37084. }else{
  37085. pNew->pMethod = pLockingStyle;
  37086. OpenCounter(+1);
  37087. verifyDbFile(pNew);
  37088. }
  37089. return rc;
  37090. }
  37091. /*
  37092. ** Return the name of a directory in which to put temporary files.
  37093. ** If no suitable temporary file directory can be found, return NULL.
  37094. */
  37095. static const char *unixTempFileDir(void){
  37096. static const char *azDirs[] = {
  37097. 0,
  37098. 0,
  37099. "/var/tmp",
  37100. "/usr/tmp",
  37101. "/tmp",
  37102. "."
  37103. };
  37104. unsigned int i = 0;
  37105. struct stat buf;
  37106. const char *zDir = sqlite3_temp_directory;
  37107. if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
  37108. if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
  37109. while(1){
  37110. if( zDir!=0
  37111. && osStat(zDir, &buf)==0
  37112. && S_ISDIR(buf.st_mode)
  37113. && osAccess(zDir, 03)==0
  37114. ){
  37115. return zDir;
  37116. }
  37117. if( i>=sizeof(azDirs)/sizeof(azDirs[0]) ) break;
  37118. zDir = azDirs[i++];
  37119. }
  37120. return 0;
  37121. }
  37122. /*
  37123. ** Create a temporary file name in zBuf. zBuf must be allocated
  37124. ** by the calling process and must be big enough to hold at least
  37125. ** pVfs->mxPathname bytes.
  37126. */
  37127. static int unixGetTempname(int nBuf, char *zBuf){
  37128. const char *zDir;
  37129. int iLimit = 0;
  37130. /* It's odd to simulate an io-error here, but really this is just
  37131. ** using the io-error infrastructure to test that SQLite handles this
  37132. ** function failing.
  37133. */
  37134. zBuf[0] = 0;
  37135. SimulateIOError( return SQLITE_IOERR );
  37136. zDir = unixTempFileDir();
  37137. if( zDir==0 ) return SQLITE_IOERR_GETTEMPPATH;
  37138. do{
  37139. u64 r;
  37140. sqlite3_randomness(sizeof(r), &r);
  37141. assert( nBuf>2 );
  37142. zBuf[nBuf-2] = 0;
  37143. sqlite3_snprintf(nBuf, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX"%llx%c",
  37144. zDir, r, 0);
  37145. if( zBuf[nBuf-2]!=0 || (iLimit++)>10 ) return SQLITE_ERROR;
  37146. }while( osAccess(zBuf,0)==0 );
  37147. return SQLITE_OK;
  37148. }
  37149. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  37150. /*
  37151. ** Routine to transform a unixFile into a proxy-locking unixFile.
  37152. ** Implementation in the proxy-lock division, but used by unixOpen()
  37153. ** if SQLITE_PREFER_PROXY_LOCKING is defined.
  37154. */
  37155. static int proxyTransformUnixFile(unixFile*, const char*);
  37156. #endif
  37157. /*
  37158. ** Search for an unused file descriptor that was opened on the database
  37159. ** file (not a journal or master-journal file) identified by pathname
  37160. ** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
  37161. ** argument to this function.
  37162. **
  37163. ** Such a file descriptor may exist if a database connection was closed
  37164. ** but the associated file descriptor could not be closed because some
  37165. ** other file descriptor open on the same file is holding a file-lock.
  37166. ** Refer to comments in the unixClose() function and the lengthy comment
  37167. ** describing "Posix Advisory Locking" at the start of this file for
  37168. ** further details. Also, ticket #4018.
  37169. **
  37170. ** If a suitable file descriptor is found, then it is returned. If no
  37171. ** such file descriptor is located, -1 is returned.
  37172. */
  37173. static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
  37174. UnixUnusedFd *pUnused = 0;
  37175. /* Do not search for an unused file descriptor on vxworks. Not because
  37176. ** vxworks would not benefit from the change (it might, we're not sure),
  37177. ** but because no way to test it is currently available. It is better
  37178. ** not to risk breaking vxworks support for the sake of such an obscure
  37179. ** feature. */
  37180. #if !OS_VXWORKS
  37181. struct stat sStat; /* Results of stat() call */
  37182. unixEnterMutex();
  37183. /* A stat() call may fail for various reasons. If this happens, it is
  37184. ** almost certain that an open() call on the same path will also fail.
  37185. ** For this reason, if an error occurs in the stat() call here, it is
  37186. ** ignored and -1 is returned. The caller will try to open a new file
  37187. ** descriptor on the same path, fail, and return an error to SQLite.
  37188. **
  37189. ** Even if a subsequent open() call does succeed, the consequences of
  37190. ** not searching for a reusable file descriptor are not dire. */
  37191. if( inodeList!=0 && 0==osStat(zPath, &sStat) ){
  37192. unixInodeInfo *pInode;
  37193. pInode = inodeList;
  37194. while( pInode && (pInode->fileId.dev!=sStat.st_dev
  37195. || pInode->fileId.ino!=(u64)sStat.st_ino) ){
  37196. pInode = pInode->pNext;
  37197. }
  37198. if( pInode ){
  37199. UnixUnusedFd **pp;
  37200. assert( sqlite3_mutex_notheld(pInode->pLockMutex) );
  37201. sqlite3_mutex_enter(pInode->pLockMutex);
  37202. flags &= (SQLITE_OPEN_READONLY|SQLITE_OPEN_READWRITE);
  37203. for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
  37204. pUnused = *pp;
  37205. if( pUnused ){
  37206. *pp = pUnused->pNext;
  37207. }
  37208. sqlite3_mutex_leave(pInode->pLockMutex);
  37209. }
  37210. }
  37211. unixLeaveMutex();
  37212. #endif /* if !OS_VXWORKS */
  37213. return pUnused;
  37214. }
  37215. /*
  37216. ** Find the mode, uid and gid of file zFile.
  37217. */
  37218. static int getFileMode(
  37219. const char *zFile, /* File name */
  37220. mode_t *pMode, /* OUT: Permissions of zFile */
  37221. uid_t *pUid, /* OUT: uid of zFile. */
  37222. gid_t *pGid /* OUT: gid of zFile. */
  37223. ){
  37224. struct stat sStat; /* Output of stat() on database file */
  37225. int rc = SQLITE_OK;
  37226. if( 0==osStat(zFile, &sStat) ){
  37227. *pMode = sStat.st_mode & 0777;
  37228. *pUid = sStat.st_uid;
  37229. *pGid = sStat.st_gid;
  37230. }else{
  37231. rc = SQLITE_IOERR_FSTAT;
  37232. }
  37233. return rc;
  37234. }
  37235. /*
  37236. ** This function is called by unixOpen() to determine the unix permissions
  37237. ** to create new files with. If no error occurs, then SQLITE_OK is returned
  37238. ** and a value suitable for passing as the third argument to open(2) is
  37239. ** written to *pMode. If an IO error occurs, an SQLite error code is
  37240. ** returned and the value of *pMode is not modified.
  37241. **
  37242. ** In most cases, this routine sets *pMode to 0, which will become
  37243. ** an indication to robust_open() to create the file using
  37244. ** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
  37245. ** But if the file being opened is a WAL or regular journal file, then
  37246. ** this function queries the file-system for the permissions on the
  37247. ** corresponding database file and sets *pMode to this value. Whenever
  37248. ** possible, WAL and journal files are created using the same permissions
  37249. ** as the associated database file.
  37250. **
  37251. ** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
  37252. ** original filename is unavailable. But 8_3_NAMES is only used for
  37253. ** FAT filesystems and permissions do not matter there, so just use
  37254. ** the default permissions. In 8_3_NAMES mode, leave *pMode set to zero.
  37255. */
  37256. static int findCreateFileMode(
  37257. const char *zPath, /* Path of file (possibly) being created */
  37258. int flags, /* Flags passed as 4th argument to xOpen() */
  37259. mode_t *pMode, /* OUT: Permissions to open file with */
  37260. uid_t *pUid, /* OUT: uid to set on the file */
  37261. gid_t *pGid /* OUT: gid to set on the file */
  37262. ){
  37263. int rc = SQLITE_OK; /* Return Code */
  37264. *pMode = 0;
  37265. *pUid = 0;
  37266. *pGid = 0;
  37267. if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
  37268. char zDb[MAX_PATHNAME+1]; /* Database file path */
  37269. int nDb; /* Number of valid bytes in zDb */
  37270. /* zPath is a path to a WAL or journal file. The following block derives
  37271. ** the path to the associated database file from zPath. This block handles
  37272. ** the following naming conventions:
  37273. **
  37274. ** "<path to db>-journal"
  37275. ** "<path to db>-wal"
  37276. ** "<path to db>-journalNN"
  37277. ** "<path to db>-walNN"
  37278. **
  37279. ** where NN is a decimal number. The NN naming schemes are
  37280. ** used by the test_multiplex.c module.
  37281. */
  37282. nDb = sqlite3Strlen30(zPath) - 1;
  37283. while( zPath[nDb]!='-' ){
  37284. /* In normal operation, the journal file name will always contain
  37285. ** a '-' character. However in 8+3 filename mode, or if a corrupt
  37286. ** rollback journal specifies a master journal with a goofy name, then
  37287. ** the '-' might be missing. */
  37288. if( nDb==0 || zPath[nDb]=='.' ) return SQLITE_OK;
  37289. nDb--;
  37290. }
  37291. memcpy(zDb, zPath, nDb);
  37292. zDb[nDb] = '\0';
  37293. rc = getFileMode(zDb, pMode, pUid, pGid);
  37294. }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
  37295. *pMode = 0600;
  37296. }else if( flags & SQLITE_OPEN_URI ){
  37297. /* If this is a main database file and the file was opened using a URI
  37298. ** filename, check for the "modeof" parameter. If present, interpret
  37299. ** its value as a filename and try to copy the mode, uid and gid from
  37300. ** that file. */
  37301. const char *z = sqlite3_uri_parameter(zPath, "modeof");
  37302. if( z ){
  37303. rc = getFileMode(z, pMode, pUid, pGid);
  37304. }
  37305. }
  37306. return rc;
  37307. }
  37308. /*
  37309. ** Open the file zPath.
  37310. **
  37311. ** Previously, the SQLite OS layer used three functions in place of this
  37312. ** one:
  37313. **
  37314. ** sqlite3OsOpenReadWrite();
  37315. ** sqlite3OsOpenReadOnly();
  37316. ** sqlite3OsOpenExclusive();
  37317. **
  37318. ** These calls correspond to the following combinations of flags:
  37319. **
  37320. ** ReadWrite() -> (READWRITE | CREATE)
  37321. ** ReadOnly() -> (READONLY)
  37322. ** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
  37323. **
  37324. ** The old OpenExclusive() accepted a boolean argument - "delFlag". If
  37325. ** true, the file was configured to be automatically deleted when the
  37326. ** file handle closed. To achieve the same effect using this new
  37327. ** interface, add the DELETEONCLOSE flag to those specified above for
  37328. ** OpenExclusive().
  37329. */
  37330. static int unixOpen(
  37331. sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
  37332. const char *zPath, /* Pathname of file to be opened */
  37333. sqlite3_file *pFile, /* The file descriptor to be filled in */
  37334. int flags, /* Input flags to control the opening */
  37335. int *pOutFlags /* Output flags returned to SQLite core */
  37336. ){
  37337. unixFile *p = (unixFile *)pFile;
  37338. int fd = -1; /* File descriptor returned by open() */
  37339. int openFlags = 0; /* Flags to pass to open() */
  37340. int eType = flags&0x0FFF00; /* Type of file to open */
  37341. int noLock; /* True to omit locking primitives */
  37342. int rc = SQLITE_OK; /* Function Return Code */
  37343. int ctrlFlags = 0; /* UNIXFILE_* flags */
  37344. int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
  37345. int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
  37346. int isCreate = (flags & SQLITE_OPEN_CREATE);
  37347. int isReadonly = (flags & SQLITE_OPEN_READONLY);
  37348. int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
  37349. #if SQLITE_ENABLE_LOCKING_STYLE
  37350. int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
  37351. #endif
  37352. #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
  37353. struct statfs fsInfo;
  37354. #endif
  37355. /* If creating a master or main-file journal, this function will open
  37356. ** a file-descriptor on the directory too. The first time unixSync()
  37357. ** is called the directory file descriptor will be fsync()ed and close()d.
  37358. */
  37359. int isNewJrnl = (isCreate && (
  37360. eType==SQLITE_OPEN_MASTER_JOURNAL
  37361. || eType==SQLITE_OPEN_MAIN_JOURNAL
  37362. || eType==SQLITE_OPEN_WAL
  37363. ));
  37364. /* If argument zPath is a NULL pointer, this function is required to open
  37365. ** a temporary file. Use this buffer to store the file name in.
  37366. */
  37367. char zTmpname[MAX_PATHNAME+2];
  37368. const char *zName = zPath;
  37369. /* Check the following statements are true:
  37370. **
  37371. ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
  37372. ** (b) if CREATE is set, then READWRITE must also be set, and
  37373. ** (c) if EXCLUSIVE is set, then CREATE must also be set.
  37374. ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
  37375. */
  37376. assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
  37377. assert(isCreate==0 || isReadWrite);
  37378. assert(isExclusive==0 || isCreate);
  37379. assert(isDelete==0 || isCreate);
  37380. /* The main DB, main journal, WAL file and master journal are never
  37381. ** automatically deleted. Nor are they ever temporary files. */
  37382. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
  37383. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
  37384. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
  37385. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
  37386. /* Assert that the upper layer has set one of the "file-type" flags. */
  37387. assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
  37388. || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
  37389. || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
  37390. || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
  37391. );
  37392. /* Detect a pid change and reset the PRNG. There is a race condition
  37393. ** here such that two or more threads all trying to open databases at
  37394. ** the same instant might all reset the PRNG. But multiple resets
  37395. ** are harmless.
  37396. */
  37397. if( randomnessPid!=osGetpid(0) ){
  37398. randomnessPid = osGetpid(0);
  37399. sqlite3_randomness(0,0);
  37400. }
  37401. memset(p, 0, sizeof(unixFile));
  37402. if( eType==SQLITE_OPEN_MAIN_DB ){
  37403. UnixUnusedFd *pUnused;
  37404. pUnused = findReusableFd(zName, flags);
  37405. if( pUnused ){
  37406. fd = pUnused->fd;
  37407. }else{
  37408. pUnused = sqlite3_malloc64(sizeof(*pUnused));
  37409. if( !pUnused ){
  37410. return SQLITE_NOMEM_BKPT;
  37411. }
  37412. }
  37413. p->pPreallocatedUnused = pUnused;
  37414. /* Database filenames are double-zero terminated if they are not
  37415. ** URIs with parameters. Hence, they can always be passed into
  37416. ** sqlite3_uri_parameter(). */
  37417. assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
  37418. }else if( !zName ){
  37419. /* If zName is NULL, the upper layer is requesting a temp file. */
  37420. assert(isDelete && !isNewJrnl);
  37421. rc = unixGetTempname(pVfs->mxPathname, zTmpname);
  37422. if( rc!=SQLITE_OK ){
  37423. return rc;
  37424. }
  37425. zName = zTmpname;
  37426. /* Generated temporary filenames are always double-zero terminated
  37427. ** for use by sqlite3_uri_parameter(). */
  37428. assert( zName[strlen(zName)+1]==0 );
  37429. }
  37430. /* Determine the value of the flags parameter passed to POSIX function
  37431. ** open(). These must be calculated even if open() is not called, as
  37432. ** they may be stored as part of the file handle and used by the
  37433. ** 'conch file' locking functions later on. */
  37434. if( isReadonly ) openFlags |= O_RDONLY;
  37435. if( isReadWrite ) openFlags |= O_RDWR;
  37436. if( isCreate ) openFlags |= O_CREAT;
  37437. if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
  37438. openFlags |= (O_LARGEFILE|O_BINARY|O_NOFOLLOW);
  37439. if( fd<0 ){
  37440. mode_t openMode; /* Permissions to create file with */
  37441. uid_t uid; /* Userid for the file */
  37442. gid_t gid; /* Groupid for the file */
  37443. rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
  37444. if( rc!=SQLITE_OK ){
  37445. assert( !p->pPreallocatedUnused );
  37446. assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
  37447. return rc;
  37448. }
  37449. fd = robust_open(zName, openFlags, openMode);
  37450. OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
  37451. assert( !isExclusive || (openFlags & O_CREAT)!=0 );
  37452. if( fd<0 ){
  37453. if( isNewJrnl && errno==EACCES && osAccess(zName, F_OK) ){
  37454. /* If unable to create a journal because the directory is not
  37455. ** writable, change the error code to indicate that. */
  37456. rc = SQLITE_READONLY_DIRECTORY;
  37457. }else if( errno!=EISDIR && isReadWrite ){
  37458. /* Failed to open the file for read/write access. Try read-only. */
  37459. flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
  37460. openFlags &= ~(O_RDWR|O_CREAT);
  37461. flags |= SQLITE_OPEN_READONLY;
  37462. openFlags |= O_RDONLY;
  37463. isReadonly = 1;
  37464. fd = robust_open(zName, openFlags, openMode);
  37465. }
  37466. }
  37467. if( fd<0 ){
  37468. int rc2 = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
  37469. if( rc==SQLITE_OK ) rc = rc2;
  37470. goto open_finished;
  37471. }
  37472. /* The owner of the rollback journal or WAL file should always be the
  37473. ** same as the owner of the database file. Try to ensure that this is
  37474. ** the case. The chown() system call will be a no-op if the current
  37475. ** process lacks root privileges, be we should at least try. Without
  37476. ** this step, if a root process opens a database file, it can leave
  37477. ** behinds a journal/WAL that is owned by root and hence make the
  37478. ** database inaccessible to unprivileged processes.
  37479. **
  37480. ** If openMode==0, then that means uid and gid are not set correctly
  37481. ** (probably because SQLite is configured to use 8+3 filename mode) and
  37482. ** in that case we do not want to attempt the chown().
  37483. */
  37484. if( openMode && (flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL))!=0 ){
  37485. robustFchown(fd, uid, gid);
  37486. }
  37487. }
  37488. assert( fd>=0 );
  37489. if( pOutFlags ){
  37490. *pOutFlags = flags;
  37491. }
  37492. if( p->pPreallocatedUnused ){
  37493. p->pPreallocatedUnused->fd = fd;
  37494. p->pPreallocatedUnused->flags =
  37495. flags & (SQLITE_OPEN_READONLY|SQLITE_OPEN_READWRITE);
  37496. }
  37497. if( isDelete ){
  37498. #if OS_VXWORKS
  37499. zPath = zName;
  37500. #elif defined(SQLITE_UNLINK_AFTER_CLOSE)
  37501. zPath = sqlite3_mprintf("%s", zName);
  37502. if( zPath==0 ){
  37503. robust_close(p, fd, __LINE__);
  37504. return SQLITE_NOMEM_BKPT;
  37505. }
  37506. #else
  37507. osUnlink(zName);
  37508. #endif
  37509. }
  37510. #if SQLITE_ENABLE_LOCKING_STYLE
  37511. else{
  37512. p->openFlags = openFlags;
  37513. }
  37514. #endif
  37515. #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
  37516. if( fstatfs(fd, &fsInfo) == -1 ){
  37517. storeLastErrno(p, errno);
  37518. robust_close(p, fd, __LINE__);
  37519. return SQLITE_IOERR_ACCESS;
  37520. }
  37521. if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
  37522. ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
  37523. }
  37524. if (0 == strncmp("exfat", fsInfo.f_fstypename, 5)) {
  37525. ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
  37526. }
  37527. #endif
  37528. /* Set up appropriate ctrlFlags */
  37529. if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
  37530. if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
  37531. noLock = eType!=SQLITE_OPEN_MAIN_DB;
  37532. if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
  37533. if( isNewJrnl ) ctrlFlags |= UNIXFILE_DIRSYNC;
  37534. if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
  37535. #if SQLITE_ENABLE_LOCKING_STYLE
  37536. #if SQLITE_PREFER_PROXY_LOCKING
  37537. isAutoProxy = 1;
  37538. #endif
  37539. if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
  37540. char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
  37541. int useProxy = 0;
  37542. /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
  37543. ** never use proxy, NULL means use proxy for non-local files only. */
  37544. if( envforce!=NULL ){
  37545. useProxy = atoi(envforce)>0;
  37546. }else{
  37547. useProxy = !(fsInfo.f_flags&MNT_LOCAL);
  37548. }
  37549. if( useProxy ){
  37550. rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
  37551. if( rc==SQLITE_OK ){
  37552. rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
  37553. if( rc!=SQLITE_OK ){
  37554. /* Use unixClose to clean up the resources added in fillInUnixFile
  37555. ** and clear all the structure's references. Specifically,
  37556. ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
  37557. */
  37558. unixClose(pFile);
  37559. return rc;
  37560. }
  37561. }
  37562. goto open_finished;
  37563. }
  37564. }
  37565. #endif
  37566. assert( zPath==0 || zPath[0]=='/'
  37567. || eType==SQLITE_OPEN_MASTER_JOURNAL || eType==SQLITE_OPEN_MAIN_JOURNAL
  37568. );
  37569. rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
  37570. open_finished:
  37571. if( rc!=SQLITE_OK ){
  37572. sqlite3_free(p->pPreallocatedUnused);
  37573. }
  37574. return rc;
  37575. }
  37576. /*
  37577. ** Delete the file at zPath. If the dirSync argument is true, fsync()
  37578. ** the directory after deleting the file.
  37579. */
  37580. static int unixDelete(
  37581. sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
  37582. const char *zPath, /* Name of file to be deleted */
  37583. int dirSync /* If true, fsync() directory after deleting file */
  37584. ){
  37585. int rc = SQLITE_OK;
  37586. UNUSED_PARAMETER(NotUsed);
  37587. SimulateIOError(return SQLITE_IOERR_DELETE);
  37588. if( osUnlink(zPath)==(-1) ){
  37589. if( errno==ENOENT
  37590. #if OS_VXWORKS
  37591. || osAccess(zPath,0)!=0
  37592. #endif
  37593. ){
  37594. rc = SQLITE_IOERR_DELETE_NOENT;
  37595. }else{
  37596. rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
  37597. }
  37598. return rc;
  37599. }
  37600. #ifndef SQLITE_DISABLE_DIRSYNC
  37601. if( (dirSync & 1)!=0 ){
  37602. int fd;
  37603. rc = osOpenDirectory(zPath, &fd);
  37604. if( rc==SQLITE_OK ){
  37605. if( full_fsync(fd,0,0) ){
  37606. rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
  37607. }
  37608. robust_close(0, fd, __LINE__);
  37609. }else{
  37610. assert( rc==SQLITE_CANTOPEN );
  37611. rc = SQLITE_OK;
  37612. }
  37613. }
  37614. #endif
  37615. return rc;
  37616. }
  37617. /*
  37618. ** Test the existence of or access permissions of file zPath. The
  37619. ** test performed depends on the value of flags:
  37620. **
  37621. ** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
  37622. ** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
  37623. ** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
  37624. **
  37625. ** Otherwise return 0.
  37626. */
  37627. static int unixAccess(
  37628. sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
  37629. const char *zPath, /* Path of the file to examine */
  37630. int flags, /* What do we want to learn about the zPath file? */
  37631. int *pResOut /* Write result boolean here */
  37632. ){
  37633. UNUSED_PARAMETER(NotUsed);
  37634. SimulateIOError( return SQLITE_IOERR_ACCESS; );
  37635. assert( pResOut!=0 );
  37636. /* The spec says there are three possible values for flags. But only
  37637. ** two of them are actually used */
  37638. assert( flags==SQLITE_ACCESS_EXISTS || flags==SQLITE_ACCESS_READWRITE );
  37639. if( flags==SQLITE_ACCESS_EXISTS ){
  37640. struct stat buf;
  37641. *pResOut = 0==osStat(zPath, &buf) &&
  37642. (!S_ISREG(buf.st_mode) || buf.st_size>0);
  37643. }else{
  37644. *pResOut = osAccess(zPath, W_OK|R_OK)==0;
  37645. }
  37646. return SQLITE_OK;
  37647. }
  37648. /*
  37649. **
  37650. */
  37651. static int mkFullPathname(
  37652. const char *zPath, /* Input path */
  37653. char *zOut, /* Output buffer */
  37654. int nOut /* Allocated size of buffer zOut */
  37655. ){
  37656. int nPath = sqlite3Strlen30(zPath);
  37657. int iOff = 0;
  37658. if( zPath[0]!='/' ){
  37659. if( osGetcwd(zOut, nOut-2)==0 ){
  37660. return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
  37661. }
  37662. iOff = sqlite3Strlen30(zOut);
  37663. zOut[iOff++] = '/';
  37664. }
  37665. if( (iOff+nPath+1)>nOut ){
  37666. /* SQLite assumes that xFullPathname() nul-terminates the output buffer
  37667. ** even if it returns an error. */
  37668. zOut[iOff] = '\0';
  37669. return SQLITE_CANTOPEN_BKPT;
  37670. }
  37671. sqlite3_snprintf(nOut-iOff, &zOut[iOff], "%s", zPath);
  37672. return SQLITE_OK;
  37673. }
  37674. /*
  37675. ** Turn a relative pathname into a full pathname. The relative path
  37676. ** is stored as a nul-terminated string in the buffer pointed to by
  37677. ** zPath.
  37678. **
  37679. ** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
  37680. ** (in this case, MAX_PATHNAME bytes). The full-path is written to
  37681. ** this buffer before returning.
  37682. */
  37683. static int unixFullPathname(
  37684. sqlite3_vfs *pVfs, /* Pointer to vfs object */
  37685. const char *zPath, /* Possibly relative input path */
  37686. int nOut, /* Size of output buffer in bytes */
  37687. char *zOut /* Output buffer */
  37688. ){
  37689. #if !defined(HAVE_READLINK) || !defined(HAVE_LSTAT)
  37690. return mkFullPathname(zPath, zOut, nOut);
  37691. #else
  37692. int rc = SQLITE_OK;
  37693. int nByte;
  37694. int nLink = 0; /* Number of symbolic links followed so far */
  37695. const char *zIn = zPath; /* Input path for each iteration of loop */
  37696. char *zDel = 0;
  37697. assert( pVfs->mxPathname==MAX_PATHNAME );
  37698. UNUSED_PARAMETER(pVfs);
  37699. /* It's odd to simulate an io-error here, but really this is just
  37700. ** using the io-error infrastructure to test that SQLite handles this
  37701. ** function failing. This function could fail if, for example, the
  37702. ** current working directory has been unlinked.
  37703. */
  37704. SimulateIOError( return SQLITE_ERROR );
  37705. do {
  37706. /* Call stat() on path zIn. Set bLink to true if the path is a symbolic
  37707. ** link, or false otherwise. */
  37708. int bLink = 0;
  37709. struct stat buf;
  37710. if( osLstat(zIn, &buf)!=0 ){
  37711. if( errno!=ENOENT ){
  37712. rc = unixLogError(SQLITE_CANTOPEN_BKPT, "lstat", zIn);
  37713. }
  37714. }else{
  37715. bLink = S_ISLNK(buf.st_mode);
  37716. }
  37717. if( bLink ){
  37718. nLink++;
  37719. if( zDel==0 ){
  37720. zDel = sqlite3_malloc(nOut);
  37721. if( zDel==0 ) rc = SQLITE_NOMEM_BKPT;
  37722. }else if( nLink>=SQLITE_MAX_SYMLINKS ){
  37723. rc = SQLITE_CANTOPEN_BKPT;
  37724. }
  37725. if( rc==SQLITE_OK ){
  37726. nByte = osReadlink(zIn, zDel, nOut-1);
  37727. if( nByte<0 ){
  37728. rc = unixLogError(SQLITE_CANTOPEN_BKPT, "readlink", zIn);
  37729. }else{
  37730. if( zDel[0]!='/' ){
  37731. int n;
  37732. for(n = sqlite3Strlen30(zIn); n>0 && zIn[n-1]!='/'; n--);
  37733. if( nByte+n+1>nOut ){
  37734. rc = SQLITE_CANTOPEN_BKPT;
  37735. }else{
  37736. memmove(&zDel[n], zDel, nByte+1);
  37737. memcpy(zDel, zIn, n);
  37738. nByte += n;
  37739. }
  37740. }
  37741. zDel[nByte] = '\0';
  37742. }
  37743. }
  37744. zIn = zDel;
  37745. }
  37746. assert( rc!=SQLITE_OK || zIn!=zOut || zIn[0]=='/' );
  37747. if( rc==SQLITE_OK && zIn!=zOut ){
  37748. rc = mkFullPathname(zIn, zOut, nOut);
  37749. }
  37750. if( bLink==0 ) break;
  37751. zIn = zOut;
  37752. }while( rc==SQLITE_OK );
  37753. sqlite3_free(zDel);
  37754. if( rc==SQLITE_OK && nLink ) rc = SQLITE_OK_SYMLINK;
  37755. return rc;
  37756. #endif /* HAVE_READLINK && HAVE_LSTAT */
  37757. }
  37758. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  37759. /*
  37760. ** Interfaces for opening a shared library, finding entry points
  37761. ** within the shared library, and closing the shared library.
  37762. */
  37763. #include <dlfcn.h>
  37764. static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
  37765. UNUSED_PARAMETER(NotUsed);
  37766. return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
  37767. }
  37768. /*
  37769. ** SQLite calls this function immediately after a call to unixDlSym() or
  37770. ** unixDlOpen() fails (returns a null pointer). If a more detailed error
  37771. ** message is available, it is written to zBufOut. If no error message
  37772. ** is available, zBufOut is left unmodified and SQLite uses a default
  37773. ** error message.
  37774. */
  37775. static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
  37776. const char *zErr;
  37777. UNUSED_PARAMETER(NotUsed);
  37778. unixEnterMutex();
  37779. zErr = dlerror();
  37780. if( zErr ){
  37781. sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
  37782. }
  37783. unixLeaveMutex();
  37784. }
  37785. static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
  37786. /*
  37787. ** GCC with -pedantic-errors says that C90 does not allow a void* to be
  37788. ** cast into a pointer to a function. And yet the library dlsym() routine
  37789. ** returns a void* which is really a pointer to a function. So how do we
  37790. ** use dlsym() with -pedantic-errors?
  37791. **
  37792. ** Variable x below is defined to be a pointer to a function taking
  37793. ** parameters void* and const char* and returning a pointer to a function.
  37794. ** We initialize x by assigning it a pointer to the dlsym() function.
  37795. ** (That assignment requires a cast.) Then we call the function that
  37796. ** x points to.
  37797. **
  37798. ** This work-around is unlikely to work correctly on any system where
  37799. ** you really cannot cast a function pointer into void*. But then, on the
  37800. ** other hand, dlsym() will not work on such a system either, so we have
  37801. ** not really lost anything.
  37802. */
  37803. void (*(*x)(void*,const char*))(void);
  37804. UNUSED_PARAMETER(NotUsed);
  37805. x = (void(*(*)(void*,const char*))(void))dlsym;
  37806. return (*x)(p, zSym);
  37807. }
  37808. static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
  37809. UNUSED_PARAMETER(NotUsed);
  37810. dlclose(pHandle);
  37811. }
  37812. #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
  37813. #define unixDlOpen 0
  37814. #define unixDlError 0
  37815. #define unixDlSym 0
  37816. #define unixDlClose 0
  37817. #endif
  37818. /*
  37819. ** Write nBuf bytes of random data to the supplied buffer zBuf.
  37820. */
  37821. static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
  37822. UNUSED_PARAMETER(NotUsed);
  37823. assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
  37824. /* We have to initialize zBuf to prevent valgrind from reporting
  37825. ** errors. The reports issued by valgrind are incorrect - we would
  37826. ** prefer that the randomness be increased by making use of the
  37827. ** uninitialized space in zBuf - but valgrind errors tend to worry
  37828. ** some users. Rather than argue, it seems easier just to initialize
  37829. ** the whole array and silence valgrind, even if that means less randomness
  37830. ** in the random seed.
  37831. **
  37832. ** When testing, initializing zBuf[] to zero is all we do. That means
  37833. ** that we always use the same random number sequence. This makes the
  37834. ** tests repeatable.
  37835. */
  37836. memset(zBuf, 0, nBuf);
  37837. randomnessPid = osGetpid(0);
  37838. #if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
  37839. {
  37840. int fd, got;
  37841. fd = robust_open("/dev/urandom", O_RDONLY, 0);
  37842. if( fd<0 ){
  37843. time_t t;
  37844. time(&t);
  37845. memcpy(zBuf, &t, sizeof(t));
  37846. memcpy(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid));
  37847. assert( sizeof(t)+sizeof(randomnessPid)<=(size_t)nBuf );
  37848. nBuf = sizeof(t) + sizeof(randomnessPid);
  37849. }else{
  37850. do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
  37851. robust_close(0, fd, __LINE__);
  37852. }
  37853. }
  37854. #endif
  37855. return nBuf;
  37856. }
  37857. /*
  37858. ** Sleep for a little while. Return the amount of time slept.
  37859. ** The argument is the number of microseconds we want to sleep.
  37860. ** The return value is the number of microseconds of sleep actually
  37861. ** requested from the underlying operating system, a number which
  37862. ** might be greater than or equal to the argument, but not less
  37863. ** than the argument.
  37864. */
  37865. static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
  37866. #if OS_VXWORKS
  37867. struct timespec sp;
  37868. sp.tv_sec = microseconds / 1000000;
  37869. sp.tv_nsec = (microseconds % 1000000) * 1000;
  37870. nanosleep(&sp, NULL);
  37871. UNUSED_PARAMETER(NotUsed);
  37872. return microseconds;
  37873. #elif defined(HAVE_USLEEP) && HAVE_USLEEP
  37874. usleep(microseconds);
  37875. UNUSED_PARAMETER(NotUsed);
  37876. return microseconds;
  37877. #else
  37878. int seconds = (microseconds+999999)/1000000;
  37879. sleep(seconds);
  37880. UNUSED_PARAMETER(NotUsed);
  37881. return seconds*1000000;
  37882. #endif
  37883. }
  37884. /*
  37885. ** The following variable, if set to a non-zero value, is interpreted as
  37886. ** the number of seconds since 1970 and is used to set the result of
  37887. ** sqlite3OsCurrentTime() during testing.
  37888. */
  37889. #ifdef SQLITE_TEST
  37890. SQLITE_API int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
  37891. #endif
  37892. /*
  37893. ** Find the current time (in Universal Coordinated Time). Write into *piNow
  37894. ** the current time and date as a Julian Day number times 86_400_000. In
  37895. ** other words, write into *piNow the number of milliseconds since the Julian
  37896. ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
  37897. ** proleptic Gregorian calendar.
  37898. **
  37899. ** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
  37900. ** cannot be found.
  37901. */
  37902. static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
  37903. static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
  37904. int rc = SQLITE_OK;
  37905. #if defined(NO_GETTOD)
  37906. time_t t;
  37907. time(&t);
  37908. *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
  37909. #elif OS_VXWORKS
  37910. struct timespec sNow;
  37911. clock_gettime(CLOCK_REALTIME, &sNow);
  37912. *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
  37913. #else
  37914. struct timeval sNow;
  37915. (void)gettimeofday(&sNow, 0); /* Cannot fail given valid arguments */
  37916. *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
  37917. #endif
  37918. #ifdef SQLITE_TEST
  37919. if( sqlite3_current_time ){
  37920. *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
  37921. }
  37922. #endif
  37923. UNUSED_PARAMETER(NotUsed);
  37924. return rc;
  37925. }
  37926. #ifndef SQLITE_OMIT_DEPRECATED
  37927. /*
  37928. ** Find the current time (in Universal Coordinated Time). Write the
  37929. ** current time and date as a Julian Day number into *prNow and
  37930. ** return 0. Return 1 if the time and date cannot be found.
  37931. */
  37932. static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
  37933. sqlite3_int64 i = 0;
  37934. int rc;
  37935. UNUSED_PARAMETER(NotUsed);
  37936. rc = unixCurrentTimeInt64(0, &i);
  37937. *prNow = i/86400000.0;
  37938. return rc;
  37939. }
  37940. #else
  37941. # define unixCurrentTime 0
  37942. #endif
  37943. /*
  37944. ** The xGetLastError() method is designed to return a better
  37945. ** low-level error message when operating-system problems come up
  37946. ** during SQLite operation. Only the integer return code is currently
  37947. ** used.
  37948. */
  37949. static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
  37950. UNUSED_PARAMETER(NotUsed);
  37951. UNUSED_PARAMETER(NotUsed2);
  37952. UNUSED_PARAMETER(NotUsed3);
  37953. return errno;
  37954. }
  37955. /*
  37956. ************************ End of sqlite3_vfs methods ***************************
  37957. ******************************************************************************/
  37958. /******************************************************************************
  37959. ************************** Begin Proxy Locking ********************************
  37960. **
  37961. ** Proxy locking is a "uber-locking-method" in this sense: It uses the
  37962. ** other locking methods on secondary lock files. Proxy locking is a
  37963. ** meta-layer over top of the primitive locking implemented above. For
  37964. ** this reason, the division that implements of proxy locking is deferred
  37965. ** until late in the file (here) after all of the other I/O methods have
  37966. ** been defined - so that the primitive locking methods are available
  37967. ** as services to help with the implementation of proxy locking.
  37968. **
  37969. ****
  37970. **
  37971. ** The default locking schemes in SQLite use byte-range locks on the
  37972. ** database file to coordinate safe, concurrent access by multiple readers
  37973. ** and writers [http://sqlite.org/lockingv3.html]. The five file locking
  37974. ** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
  37975. ** as POSIX read & write locks over fixed set of locations (via fsctl),
  37976. ** on AFP and SMB only exclusive byte-range locks are available via fsctl
  37977. ** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
  37978. ** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
  37979. ** address in the shared range is taken for a SHARED lock, the entire
  37980. ** shared range is taken for an EXCLUSIVE lock):
  37981. **
  37982. ** PENDING_BYTE 0x40000000
  37983. ** RESERVED_BYTE 0x40000001
  37984. ** SHARED_RANGE 0x40000002 -> 0x40000200
  37985. **
  37986. ** This works well on the local file system, but shows a nearly 100x
  37987. ** slowdown in read performance on AFP because the AFP client disables
  37988. ** the read cache when byte-range locks are present. Enabling the read
  37989. ** cache exposes a cache coherency problem that is present on all OS X
  37990. ** supported network file systems. NFS and AFP both observe the
  37991. ** close-to-open semantics for ensuring cache coherency
  37992. ** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
  37993. ** address the requirements for concurrent database access by multiple
  37994. ** readers and writers
  37995. ** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
  37996. **
  37997. ** To address the performance and cache coherency issues, proxy file locking
  37998. ** changes the way database access is controlled by limiting access to a
  37999. ** single host at a time and moving file locks off of the database file
  38000. ** and onto a proxy file on the local file system.
  38001. **
  38002. **
  38003. ** Using proxy locks
  38004. ** -----------------
  38005. **
  38006. ** C APIs
  38007. **
  38008. ** sqlite3_file_control(db, dbname, SQLITE_FCNTL_SET_LOCKPROXYFILE,
  38009. ** <proxy_path> | ":auto:");
  38010. ** sqlite3_file_control(db, dbname, SQLITE_FCNTL_GET_LOCKPROXYFILE,
  38011. ** &<proxy_path>);
  38012. **
  38013. **
  38014. ** SQL pragmas
  38015. **
  38016. ** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
  38017. ** PRAGMA [database.]lock_proxy_file
  38018. **
  38019. ** Specifying ":auto:" means that if there is a conch file with a matching
  38020. ** host ID in it, the proxy path in the conch file will be used, otherwise
  38021. ** a proxy path based on the user's temp dir
  38022. ** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
  38023. ** actual proxy file name is generated from the name and path of the
  38024. ** database file. For example:
  38025. **
  38026. ** For database path "/Users/me/foo.db"
  38027. ** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
  38028. **
  38029. ** Once a lock proxy is configured for a database connection, it can not
  38030. ** be removed, however it may be switched to a different proxy path via
  38031. ** the above APIs (assuming the conch file is not being held by another
  38032. ** connection or process).
  38033. **
  38034. **
  38035. ** How proxy locking works
  38036. ** -----------------------
  38037. **
  38038. ** Proxy file locking relies primarily on two new supporting files:
  38039. **
  38040. ** * conch file to limit access to the database file to a single host
  38041. ** at a time
  38042. **
  38043. ** * proxy file to act as a proxy for the advisory locks normally
  38044. ** taken on the database
  38045. **
  38046. ** The conch file - to use a proxy file, sqlite must first "hold the conch"
  38047. ** by taking an sqlite-style shared lock on the conch file, reading the
  38048. ** contents and comparing the host's unique host ID (see below) and lock
  38049. ** proxy path against the values stored in the conch. The conch file is
  38050. ** stored in the same directory as the database file and the file name
  38051. ** is patterned after the database file name as ".<databasename>-conch".
  38052. ** If the conch file does not exist, or its contents do not match the
  38053. ** host ID and/or proxy path, then the lock is escalated to an exclusive
  38054. ** lock and the conch file contents is updated with the host ID and proxy
  38055. ** path and the lock is downgraded to a shared lock again. If the conch
  38056. ** is held by another process (with a shared lock), the exclusive lock
  38057. ** will fail and SQLITE_BUSY is returned.
  38058. **
  38059. ** The proxy file - a single-byte file used for all advisory file locks
  38060. ** normally taken on the database file. This allows for safe sharing
  38061. ** of the database file for multiple readers and writers on the same
  38062. ** host (the conch ensures that they all use the same local lock file).
  38063. **
  38064. ** Requesting the lock proxy does not immediately take the conch, it is
  38065. ** only taken when the first request to lock database file is made.
  38066. ** This matches the semantics of the traditional locking behavior, where
  38067. ** opening a connection to a database file does not take a lock on it.
  38068. ** The shared lock and an open file descriptor are maintained until
  38069. ** the connection to the database is closed.
  38070. **
  38071. ** The proxy file and the lock file are never deleted so they only need
  38072. ** to be created the first time they are used.
  38073. **
  38074. ** Configuration options
  38075. ** ---------------------
  38076. **
  38077. ** SQLITE_PREFER_PROXY_LOCKING
  38078. **
  38079. ** Database files accessed on non-local file systems are
  38080. ** automatically configured for proxy locking, lock files are
  38081. ** named automatically using the same logic as
  38082. ** PRAGMA lock_proxy_file=":auto:"
  38083. **
  38084. ** SQLITE_PROXY_DEBUG
  38085. **
  38086. ** Enables the logging of error messages during host id file
  38087. ** retrieval and creation
  38088. **
  38089. ** LOCKPROXYDIR
  38090. **
  38091. ** Overrides the default directory used for lock proxy files that
  38092. ** are named automatically via the ":auto:" setting
  38093. **
  38094. ** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
  38095. **
  38096. ** Permissions to use when creating a directory for storing the
  38097. ** lock proxy files, only used when LOCKPROXYDIR is not set.
  38098. **
  38099. **
  38100. ** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
  38101. ** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
  38102. ** force proxy locking to be used for every database file opened, and 0
  38103. ** will force automatic proxy locking to be disabled for all database
  38104. ** files (explicitly calling the SQLITE_FCNTL_SET_LOCKPROXYFILE pragma or
  38105. ** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
  38106. */
  38107. /*
  38108. ** Proxy locking is only available on MacOSX
  38109. */
  38110. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  38111. /*
  38112. ** The proxyLockingContext has the path and file structures for the remote
  38113. ** and local proxy files in it
  38114. */
  38115. typedef struct proxyLockingContext proxyLockingContext;
  38116. struct proxyLockingContext {
  38117. unixFile *conchFile; /* Open conch file */
  38118. char *conchFilePath; /* Name of the conch file */
  38119. unixFile *lockProxy; /* Open proxy lock file */
  38120. char *lockProxyPath; /* Name of the proxy lock file */
  38121. char *dbPath; /* Name of the open file */
  38122. int conchHeld; /* 1 if the conch is held, -1 if lockless */
  38123. int nFails; /* Number of conch taking failures */
  38124. void *oldLockingContext; /* Original lockingcontext to restore on close */
  38125. sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
  38126. };
  38127. /*
  38128. ** The proxy lock file path for the database at dbPath is written into lPath,
  38129. ** which must point to valid, writable memory large enough for a maxLen length
  38130. ** file path.
  38131. */
  38132. static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
  38133. int len;
  38134. int dbLen;
  38135. int i;
  38136. #ifdef LOCKPROXYDIR
  38137. len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
  38138. #else
  38139. # ifdef _CS_DARWIN_USER_TEMP_DIR
  38140. {
  38141. if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
  38142. OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
  38143. lPath, errno, osGetpid(0)));
  38144. return SQLITE_IOERR_LOCK;
  38145. }
  38146. len = strlcat(lPath, "sqliteplocks", maxLen);
  38147. }
  38148. # else
  38149. len = strlcpy(lPath, "/tmp/", maxLen);
  38150. # endif
  38151. #endif
  38152. if( lPath[len-1]!='/' ){
  38153. len = strlcat(lPath, "/", maxLen);
  38154. }
  38155. /* transform the db path to a unique cache name */
  38156. dbLen = (int)strlen(dbPath);
  38157. for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
  38158. char c = dbPath[i];
  38159. lPath[i+len] = (c=='/')?'_':c;
  38160. }
  38161. lPath[i+len]='\0';
  38162. strlcat(lPath, ":auto:", maxLen);
  38163. OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, osGetpid(0)));
  38164. return SQLITE_OK;
  38165. }
  38166. /*
  38167. ** Creates the lock file and any missing directories in lockPath
  38168. */
  38169. static int proxyCreateLockPath(const char *lockPath){
  38170. int i, len;
  38171. char buf[MAXPATHLEN];
  38172. int start = 0;
  38173. assert(lockPath!=NULL);
  38174. /* try to create all the intermediate directories */
  38175. len = (int)strlen(lockPath);
  38176. buf[0] = lockPath[0];
  38177. for( i=1; i<len; i++ ){
  38178. if( lockPath[i] == '/' && (i - start > 0) ){
  38179. /* only mkdir if leaf dir != "." or "/" or ".." */
  38180. if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
  38181. || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
  38182. buf[i]='\0';
  38183. if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
  38184. int err=errno;
  38185. if( err!=EEXIST ) {
  38186. OSTRACE(("CREATELOCKPATH FAILED creating %s, "
  38187. "'%s' proxy lock path=%s pid=%d\n",
  38188. buf, strerror(err), lockPath, osGetpid(0)));
  38189. return err;
  38190. }
  38191. }
  38192. }
  38193. start=i+1;
  38194. }
  38195. buf[i] = lockPath[i];
  38196. }
  38197. OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n",lockPath,osGetpid(0)));
  38198. return 0;
  38199. }
  38200. /*
  38201. ** Create a new VFS file descriptor (stored in memory obtained from
  38202. ** sqlite3_malloc) and open the file named "path" in the file descriptor.
  38203. **
  38204. ** The caller is responsible not only for closing the file descriptor
  38205. ** but also for freeing the memory associated with the file descriptor.
  38206. */
  38207. static int proxyCreateUnixFile(
  38208. const char *path, /* path for the new unixFile */
  38209. unixFile **ppFile, /* unixFile created and returned by ref */
  38210. int islockfile /* if non zero missing dirs will be created */
  38211. ) {
  38212. int fd = -1;
  38213. unixFile *pNew;
  38214. int rc = SQLITE_OK;
  38215. int openFlags = O_RDWR | O_CREAT | O_NOFOLLOW;
  38216. sqlite3_vfs dummyVfs;
  38217. int terrno = 0;
  38218. UnixUnusedFd *pUnused = NULL;
  38219. /* 1. first try to open/create the file
  38220. ** 2. if that fails, and this is a lock file (not-conch), try creating
  38221. ** the parent directories and then try again.
  38222. ** 3. if that fails, try to open the file read-only
  38223. ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
  38224. */
  38225. pUnused = findReusableFd(path, openFlags);
  38226. if( pUnused ){
  38227. fd = pUnused->fd;
  38228. }else{
  38229. pUnused = sqlite3_malloc64(sizeof(*pUnused));
  38230. if( !pUnused ){
  38231. return SQLITE_NOMEM_BKPT;
  38232. }
  38233. }
  38234. if( fd<0 ){
  38235. fd = robust_open(path, openFlags, 0);
  38236. terrno = errno;
  38237. if( fd<0 && errno==ENOENT && islockfile ){
  38238. if( proxyCreateLockPath(path) == SQLITE_OK ){
  38239. fd = robust_open(path, openFlags, 0);
  38240. }
  38241. }
  38242. }
  38243. if( fd<0 ){
  38244. openFlags = O_RDONLY | O_NOFOLLOW;
  38245. fd = robust_open(path, openFlags, 0);
  38246. terrno = errno;
  38247. }
  38248. if( fd<0 ){
  38249. if( islockfile ){
  38250. return SQLITE_BUSY;
  38251. }
  38252. switch (terrno) {
  38253. case EACCES:
  38254. return SQLITE_PERM;
  38255. case EIO:
  38256. return SQLITE_IOERR_LOCK; /* even though it is the conch */
  38257. default:
  38258. return SQLITE_CANTOPEN_BKPT;
  38259. }
  38260. }
  38261. pNew = (unixFile *)sqlite3_malloc64(sizeof(*pNew));
  38262. if( pNew==NULL ){
  38263. rc = SQLITE_NOMEM_BKPT;
  38264. goto end_create_proxy;
  38265. }
  38266. memset(pNew, 0, sizeof(unixFile));
  38267. pNew->openFlags = openFlags;
  38268. memset(&dummyVfs, 0, sizeof(dummyVfs));
  38269. dummyVfs.pAppData = (void*)&autolockIoFinder;
  38270. dummyVfs.zName = "dummy";
  38271. pUnused->fd = fd;
  38272. pUnused->flags = openFlags;
  38273. pNew->pPreallocatedUnused = pUnused;
  38274. rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
  38275. if( rc==SQLITE_OK ){
  38276. *ppFile = pNew;
  38277. return SQLITE_OK;
  38278. }
  38279. end_create_proxy:
  38280. robust_close(pNew, fd, __LINE__);
  38281. sqlite3_free(pNew);
  38282. sqlite3_free(pUnused);
  38283. return rc;
  38284. }
  38285. #ifdef SQLITE_TEST
  38286. /* simulate multiple hosts by creating unique hostid file paths */
  38287. SQLITE_API int sqlite3_hostid_num = 0;
  38288. #endif
  38289. #define PROXY_HOSTIDLEN 16 /* conch file host id length */
  38290. #if HAVE_GETHOSTUUID
  38291. /* Not always defined in the headers as it ought to be */
  38292. extern int gethostuuid(uuid_t id, const struct timespec *wait);
  38293. #endif
  38294. /* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
  38295. ** bytes of writable memory.
  38296. */
  38297. static int proxyGetHostID(unsigned char *pHostID, int *pError){
  38298. assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
  38299. memset(pHostID, 0, PROXY_HOSTIDLEN);
  38300. #if HAVE_GETHOSTUUID
  38301. {
  38302. struct timespec timeout = {1, 0}; /* 1 sec timeout */
  38303. if( gethostuuid(pHostID, &timeout) ){
  38304. int err = errno;
  38305. if( pError ){
  38306. *pError = err;
  38307. }
  38308. return SQLITE_IOERR;
  38309. }
  38310. }
  38311. #else
  38312. UNUSED_PARAMETER(pError);
  38313. #endif
  38314. #ifdef SQLITE_TEST
  38315. /* simulate multiple hosts by creating unique hostid file paths */
  38316. if( sqlite3_hostid_num != 0){
  38317. pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
  38318. }
  38319. #endif
  38320. return SQLITE_OK;
  38321. }
  38322. /* The conch file contains the header, host id and lock file path
  38323. */
  38324. #define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
  38325. #define PROXY_HEADERLEN 1 /* conch file header length */
  38326. #define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
  38327. #define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
  38328. /*
  38329. ** Takes an open conch file, copies the contents to a new path and then moves
  38330. ** it back. The newly created file's file descriptor is assigned to the
  38331. ** conch file structure and finally the original conch file descriptor is
  38332. ** closed. Returns zero if successful.
  38333. */
  38334. static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
  38335. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  38336. unixFile *conchFile = pCtx->conchFile;
  38337. char tPath[MAXPATHLEN];
  38338. char buf[PROXY_MAXCONCHLEN];
  38339. char *cPath = pCtx->conchFilePath;
  38340. size_t readLen = 0;
  38341. size_t pathLen = 0;
  38342. char errmsg[64] = "";
  38343. int fd = -1;
  38344. int rc = -1;
  38345. UNUSED_PARAMETER(myHostID);
  38346. /* create a new path by replace the trailing '-conch' with '-break' */
  38347. pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
  38348. if( pathLen>MAXPATHLEN || pathLen<6 ||
  38349. (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
  38350. sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
  38351. goto end_breaklock;
  38352. }
  38353. /* read the conch content */
  38354. readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
  38355. if( readLen<PROXY_PATHINDEX ){
  38356. sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
  38357. goto end_breaklock;
  38358. }
  38359. /* write it out to the temporary break file */
  38360. fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL|O_NOFOLLOW), 0);
  38361. if( fd<0 ){
  38362. sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
  38363. goto end_breaklock;
  38364. }
  38365. if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
  38366. sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
  38367. goto end_breaklock;
  38368. }
  38369. if( rename(tPath, cPath) ){
  38370. sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
  38371. goto end_breaklock;
  38372. }
  38373. rc = 0;
  38374. fprintf(stderr, "broke stale lock on %s\n", cPath);
  38375. robust_close(pFile, conchFile->h, __LINE__);
  38376. conchFile->h = fd;
  38377. conchFile->openFlags = O_RDWR | O_CREAT;
  38378. end_breaklock:
  38379. if( rc ){
  38380. if( fd>=0 ){
  38381. osUnlink(tPath);
  38382. robust_close(pFile, fd, __LINE__);
  38383. }
  38384. fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
  38385. }
  38386. return rc;
  38387. }
  38388. /* Take the requested lock on the conch file and break a stale lock if the
  38389. ** host id matches.
  38390. */
  38391. static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
  38392. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  38393. unixFile *conchFile = pCtx->conchFile;
  38394. int rc = SQLITE_OK;
  38395. int nTries = 0;
  38396. struct timespec conchModTime;
  38397. memset(&conchModTime, 0, sizeof(conchModTime));
  38398. do {
  38399. rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
  38400. nTries ++;
  38401. if( rc==SQLITE_BUSY ){
  38402. /* If the lock failed (busy):
  38403. * 1st try: get the mod time of the conch, wait 0.5s and try again.
  38404. * 2nd try: fail if the mod time changed or host id is different, wait
  38405. * 10 sec and try again
  38406. * 3rd try: break the lock unless the mod time has changed.
  38407. */
  38408. struct stat buf;
  38409. if( osFstat(conchFile->h, &buf) ){
  38410. storeLastErrno(pFile, errno);
  38411. return SQLITE_IOERR_LOCK;
  38412. }
  38413. if( nTries==1 ){
  38414. conchModTime = buf.st_mtimespec;
  38415. usleep(500000); /* wait 0.5 sec and try the lock again*/
  38416. continue;
  38417. }
  38418. assert( nTries>1 );
  38419. if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
  38420. conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
  38421. return SQLITE_BUSY;
  38422. }
  38423. if( nTries==2 ){
  38424. char tBuf[PROXY_MAXCONCHLEN];
  38425. int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
  38426. if( len<0 ){
  38427. storeLastErrno(pFile, errno);
  38428. return SQLITE_IOERR_LOCK;
  38429. }
  38430. if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
  38431. /* don't break the lock if the host id doesn't match */
  38432. if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
  38433. return SQLITE_BUSY;
  38434. }
  38435. }else{
  38436. /* don't break the lock on short read or a version mismatch */
  38437. return SQLITE_BUSY;
  38438. }
  38439. usleep(10000000); /* wait 10 sec and try the lock again */
  38440. continue;
  38441. }
  38442. assert( nTries==3 );
  38443. if( 0==proxyBreakConchLock(pFile, myHostID) ){
  38444. rc = SQLITE_OK;
  38445. if( lockType==EXCLUSIVE_LOCK ){
  38446. rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
  38447. }
  38448. if( !rc ){
  38449. rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
  38450. }
  38451. }
  38452. }
  38453. } while( rc==SQLITE_BUSY && nTries<3 );
  38454. return rc;
  38455. }
  38456. /* Takes the conch by taking a shared lock and read the contents conch, if
  38457. ** lockPath is non-NULL, the host ID and lock file path must match. A NULL
  38458. ** lockPath means that the lockPath in the conch file will be used if the
  38459. ** host IDs match, or a new lock path will be generated automatically
  38460. ** and written to the conch file.
  38461. */
  38462. static int proxyTakeConch(unixFile *pFile){
  38463. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  38464. if( pCtx->conchHeld!=0 ){
  38465. return SQLITE_OK;
  38466. }else{
  38467. unixFile *conchFile = pCtx->conchFile;
  38468. uuid_t myHostID;
  38469. int pError = 0;
  38470. char readBuf[PROXY_MAXCONCHLEN];
  38471. char lockPath[MAXPATHLEN];
  38472. char *tempLockPath = NULL;
  38473. int rc = SQLITE_OK;
  38474. int createConch = 0;
  38475. int hostIdMatch = 0;
  38476. int readLen = 0;
  38477. int tryOldLockPath = 0;
  38478. int forceNewLockPath = 0;
  38479. OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
  38480. (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
  38481. osGetpid(0)));
  38482. rc = proxyGetHostID(myHostID, &pError);
  38483. if( (rc&0xff)==SQLITE_IOERR ){
  38484. storeLastErrno(pFile, pError);
  38485. goto end_takeconch;
  38486. }
  38487. rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
  38488. if( rc!=SQLITE_OK ){
  38489. goto end_takeconch;
  38490. }
  38491. /* read the existing conch file */
  38492. readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
  38493. if( readLen<0 ){
  38494. /* I/O error: lastErrno set by seekAndRead */
  38495. storeLastErrno(pFile, conchFile->lastErrno);
  38496. rc = SQLITE_IOERR_READ;
  38497. goto end_takeconch;
  38498. }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
  38499. readBuf[0]!=(char)PROXY_CONCHVERSION ){
  38500. /* a short read or version format mismatch means we need to create a new
  38501. ** conch file.
  38502. */
  38503. createConch = 1;
  38504. }
  38505. /* if the host id matches and the lock path already exists in the conch
  38506. ** we'll try to use the path there, if we can't open that path, we'll
  38507. ** retry with a new auto-generated path
  38508. */
  38509. do { /* in case we need to try again for an :auto: named lock file */
  38510. if( !createConch && !forceNewLockPath ){
  38511. hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
  38512. PROXY_HOSTIDLEN);
  38513. /* if the conch has data compare the contents */
  38514. if( !pCtx->lockProxyPath ){
  38515. /* for auto-named local lock file, just check the host ID and we'll
  38516. ** use the local lock file path that's already in there
  38517. */
  38518. if( hostIdMatch ){
  38519. size_t pathLen = (readLen - PROXY_PATHINDEX);
  38520. if( pathLen>=MAXPATHLEN ){
  38521. pathLen=MAXPATHLEN-1;
  38522. }
  38523. memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
  38524. lockPath[pathLen] = 0;
  38525. tempLockPath = lockPath;
  38526. tryOldLockPath = 1;
  38527. /* create a copy of the lock path if the conch is taken */
  38528. goto end_takeconch;
  38529. }
  38530. }else if( hostIdMatch
  38531. && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
  38532. readLen-PROXY_PATHINDEX)
  38533. ){
  38534. /* conch host and lock path match */
  38535. goto end_takeconch;
  38536. }
  38537. }
  38538. /* if the conch isn't writable and doesn't match, we can't take it */
  38539. if( (conchFile->openFlags&O_RDWR) == 0 ){
  38540. rc = SQLITE_BUSY;
  38541. goto end_takeconch;
  38542. }
  38543. /* either the conch didn't match or we need to create a new one */
  38544. if( !pCtx->lockProxyPath ){
  38545. proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
  38546. tempLockPath = lockPath;
  38547. /* create a copy of the lock path _only_ if the conch is taken */
  38548. }
  38549. /* update conch with host and path (this will fail if other process
  38550. ** has a shared lock already), if the host id matches, use the big
  38551. ** stick.
  38552. */
  38553. futimes(conchFile->h, NULL);
  38554. if( hostIdMatch && !createConch ){
  38555. if( conchFile->pInode && conchFile->pInode->nShared>1 ){
  38556. /* We are trying for an exclusive lock but another thread in this
  38557. ** same process is still holding a shared lock. */
  38558. rc = SQLITE_BUSY;
  38559. } else {
  38560. rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
  38561. }
  38562. }else{
  38563. rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
  38564. }
  38565. if( rc==SQLITE_OK ){
  38566. char writeBuffer[PROXY_MAXCONCHLEN];
  38567. int writeSize = 0;
  38568. writeBuffer[0] = (char)PROXY_CONCHVERSION;
  38569. memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
  38570. if( pCtx->lockProxyPath!=NULL ){
  38571. strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath,
  38572. MAXPATHLEN);
  38573. }else{
  38574. strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
  38575. }
  38576. writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
  38577. robust_ftruncate(conchFile->h, writeSize);
  38578. rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
  38579. full_fsync(conchFile->h,0,0);
  38580. /* If we created a new conch file (not just updated the contents of a
  38581. ** valid conch file), try to match the permissions of the database
  38582. */
  38583. if( rc==SQLITE_OK && createConch ){
  38584. struct stat buf;
  38585. int err = osFstat(pFile->h, &buf);
  38586. if( err==0 ){
  38587. mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
  38588. S_IROTH|S_IWOTH);
  38589. /* try to match the database file R/W permissions, ignore failure */
  38590. #ifndef SQLITE_PROXY_DEBUG
  38591. osFchmod(conchFile->h, cmode);
  38592. #else
  38593. do{
  38594. rc = osFchmod(conchFile->h, cmode);
  38595. }while( rc==(-1) && errno==EINTR );
  38596. if( rc!=0 ){
  38597. int code = errno;
  38598. fprintf(stderr, "fchmod %o FAILED with %d %s\n",
  38599. cmode, code, strerror(code));
  38600. } else {
  38601. fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
  38602. }
  38603. }else{
  38604. int code = errno;
  38605. fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
  38606. err, code, strerror(code));
  38607. #endif
  38608. }
  38609. }
  38610. }
  38611. conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
  38612. end_takeconch:
  38613. OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
  38614. if( rc==SQLITE_OK && pFile->openFlags ){
  38615. int fd;
  38616. if( pFile->h>=0 ){
  38617. robust_close(pFile, pFile->h, __LINE__);
  38618. }
  38619. pFile->h = -1;
  38620. fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
  38621. OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
  38622. if( fd>=0 ){
  38623. pFile->h = fd;
  38624. }else{
  38625. rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
  38626. during locking */
  38627. }
  38628. }
  38629. if( rc==SQLITE_OK && !pCtx->lockProxy ){
  38630. char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
  38631. rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
  38632. if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
  38633. /* we couldn't create the proxy lock file with the old lock file path
  38634. ** so try again via auto-naming
  38635. */
  38636. forceNewLockPath = 1;
  38637. tryOldLockPath = 0;
  38638. continue; /* go back to the do {} while start point, try again */
  38639. }
  38640. }
  38641. if( rc==SQLITE_OK ){
  38642. /* Need to make a copy of path if we extracted the value
  38643. ** from the conch file or the path was allocated on the stack
  38644. */
  38645. if( tempLockPath ){
  38646. pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
  38647. if( !pCtx->lockProxyPath ){
  38648. rc = SQLITE_NOMEM_BKPT;
  38649. }
  38650. }
  38651. }
  38652. if( rc==SQLITE_OK ){
  38653. pCtx->conchHeld = 1;
  38654. if( pCtx->lockProxy->pMethod == &afpIoMethods ){
  38655. afpLockingContext *afpCtx;
  38656. afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
  38657. afpCtx->dbPath = pCtx->lockProxyPath;
  38658. }
  38659. } else {
  38660. conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
  38661. }
  38662. OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
  38663. rc==SQLITE_OK?"ok":"failed"));
  38664. return rc;
  38665. } while (1); /* in case we need to retry the :auto: lock file -
  38666. ** we should never get here except via the 'continue' call. */
  38667. }
  38668. }
  38669. /*
  38670. ** If pFile holds a lock on a conch file, then release that lock.
  38671. */
  38672. static int proxyReleaseConch(unixFile *pFile){
  38673. int rc = SQLITE_OK; /* Subroutine return code */
  38674. proxyLockingContext *pCtx; /* The locking context for the proxy lock */
  38675. unixFile *conchFile; /* Name of the conch file */
  38676. pCtx = (proxyLockingContext *)pFile->lockingContext;
  38677. conchFile = pCtx->conchFile;
  38678. OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
  38679. (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
  38680. osGetpid(0)));
  38681. if( pCtx->conchHeld>0 ){
  38682. rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
  38683. }
  38684. pCtx->conchHeld = 0;
  38685. OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
  38686. (rc==SQLITE_OK ? "ok" : "failed")));
  38687. return rc;
  38688. }
  38689. /*
  38690. ** Given the name of a database file, compute the name of its conch file.
  38691. ** Store the conch filename in memory obtained from sqlite3_malloc64().
  38692. ** Make *pConchPath point to the new name. Return SQLITE_OK on success
  38693. ** or SQLITE_NOMEM if unable to obtain memory.
  38694. **
  38695. ** The caller is responsible for ensuring that the allocated memory
  38696. ** space is eventually freed.
  38697. **
  38698. ** *pConchPath is set to NULL if a memory allocation error occurs.
  38699. */
  38700. static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
  38701. int i; /* Loop counter */
  38702. int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
  38703. char *conchPath; /* buffer in which to construct conch name */
  38704. /* Allocate space for the conch filename and initialize the name to
  38705. ** the name of the original database file. */
  38706. *pConchPath = conchPath = (char *)sqlite3_malloc64(len + 8);
  38707. if( conchPath==0 ){
  38708. return SQLITE_NOMEM_BKPT;
  38709. }
  38710. memcpy(conchPath, dbPath, len+1);
  38711. /* now insert a "." before the last / character */
  38712. for( i=(len-1); i>=0; i-- ){
  38713. if( conchPath[i]=='/' ){
  38714. i++;
  38715. break;
  38716. }
  38717. }
  38718. conchPath[i]='.';
  38719. while ( i<len ){
  38720. conchPath[i+1]=dbPath[i];
  38721. i++;
  38722. }
  38723. /* append the "-conch" suffix to the file */
  38724. memcpy(&conchPath[i+1], "-conch", 7);
  38725. assert( (int)strlen(conchPath) == len+7 );
  38726. return SQLITE_OK;
  38727. }
  38728. /* Takes a fully configured proxy locking-style unix file and switches
  38729. ** the local lock file path
  38730. */
  38731. static int switchLockProxyPath(unixFile *pFile, const char *path) {
  38732. proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
  38733. char *oldPath = pCtx->lockProxyPath;
  38734. int rc = SQLITE_OK;
  38735. if( pFile->eFileLock!=NO_LOCK ){
  38736. return SQLITE_BUSY;
  38737. }
  38738. /* nothing to do if the path is NULL, :auto: or matches the existing path */
  38739. if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
  38740. (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
  38741. return SQLITE_OK;
  38742. }else{
  38743. unixFile *lockProxy = pCtx->lockProxy;
  38744. pCtx->lockProxy=NULL;
  38745. pCtx->conchHeld = 0;
  38746. if( lockProxy!=NULL ){
  38747. rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
  38748. if( rc ) return rc;
  38749. sqlite3_free(lockProxy);
  38750. }
  38751. sqlite3_free(oldPath);
  38752. pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
  38753. }
  38754. return rc;
  38755. }
  38756. /*
  38757. ** pFile is a file that has been opened by a prior xOpen call. dbPath
  38758. ** is a string buffer at least MAXPATHLEN+1 characters in size.
  38759. **
  38760. ** This routine find the filename associated with pFile and writes it
  38761. ** int dbPath.
  38762. */
  38763. static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
  38764. #if defined(__APPLE__)
  38765. if( pFile->pMethod == &afpIoMethods ){
  38766. /* afp style keeps a reference to the db path in the filePath field
  38767. ** of the struct */
  38768. assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
  38769. strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath,
  38770. MAXPATHLEN);
  38771. } else
  38772. #endif
  38773. if( pFile->pMethod == &dotlockIoMethods ){
  38774. /* dot lock style uses the locking context to store the dot lock
  38775. ** file path */
  38776. int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
  38777. memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
  38778. }else{
  38779. /* all other styles use the locking context to store the db file path */
  38780. assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
  38781. strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
  38782. }
  38783. return SQLITE_OK;
  38784. }
  38785. /*
  38786. ** Takes an already filled in unix file and alters it so all file locking
  38787. ** will be performed on the local proxy lock file. The following fields
  38788. ** are preserved in the locking context so that they can be restored and
  38789. ** the unix structure properly cleaned up at close time:
  38790. ** ->lockingContext
  38791. ** ->pMethod
  38792. */
  38793. static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
  38794. proxyLockingContext *pCtx;
  38795. char dbPath[MAXPATHLEN+1]; /* Name of the database file */
  38796. char *lockPath=NULL;
  38797. int rc = SQLITE_OK;
  38798. if( pFile->eFileLock!=NO_LOCK ){
  38799. return SQLITE_BUSY;
  38800. }
  38801. proxyGetDbPathForUnixFile(pFile, dbPath);
  38802. if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
  38803. lockPath=NULL;
  38804. }else{
  38805. lockPath=(char *)path;
  38806. }
  38807. OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
  38808. (lockPath ? lockPath : ":auto:"), osGetpid(0)));
  38809. pCtx = sqlite3_malloc64( sizeof(*pCtx) );
  38810. if( pCtx==0 ){
  38811. return SQLITE_NOMEM_BKPT;
  38812. }
  38813. memset(pCtx, 0, sizeof(*pCtx));
  38814. rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
  38815. if( rc==SQLITE_OK ){
  38816. rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
  38817. if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
  38818. /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
  38819. ** (c) the file system is read-only, then enable no-locking access.
  38820. ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
  38821. ** that openFlags will have only one of O_RDONLY or O_RDWR.
  38822. */
  38823. struct statfs fsInfo;
  38824. struct stat conchInfo;
  38825. int goLockless = 0;
  38826. if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
  38827. int err = errno;
  38828. if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
  38829. goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
  38830. }
  38831. }
  38832. if( goLockless ){
  38833. pCtx->conchHeld = -1; /* read only FS/ lockless */
  38834. rc = SQLITE_OK;
  38835. }
  38836. }
  38837. }
  38838. if( rc==SQLITE_OK && lockPath ){
  38839. pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
  38840. }
  38841. if( rc==SQLITE_OK ){
  38842. pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
  38843. if( pCtx->dbPath==NULL ){
  38844. rc = SQLITE_NOMEM_BKPT;
  38845. }
  38846. }
  38847. if( rc==SQLITE_OK ){
  38848. /* all memory is allocated, proxys are created and assigned,
  38849. ** switch the locking context and pMethod then return.
  38850. */
  38851. pCtx->oldLockingContext = pFile->lockingContext;
  38852. pFile->lockingContext = pCtx;
  38853. pCtx->pOldMethod = pFile->pMethod;
  38854. pFile->pMethod = &proxyIoMethods;
  38855. }else{
  38856. if( pCtx->conchFile ){
  38857. pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
  38858. sqlite3_free(pCtx->conchFile);
  38859. }
  38860. sqlite3DbFree(0, pCtx->lockProxyPath);
  38861. sqlite3_free(pCtx->conchFilePath);
  38862. sqlite3_free(pCtx);
  38863. }
  38864. OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
  38865. (rc==SQLITE_OK ? "ok" : "failed")));
  38866. return rc;
  38867. }
  38868. /*
  38869. ** This routine handles sqlite3_file_control() calls that are specific
  38870. ** to proxy locking.
  38871. */
  38872. static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
  38873. switch( op ){
  38874. case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
  38875. unixFile *pFile = (unixFile*)id;
  38876. if( pFile->pMethod == &proxyIoMethods ){
  38877. proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
  38878. proxyTakeConch(pFile);
  38879. if( pCtx->lockProxyPath ){
  38880. *(const char **)pArg = pCtx->lockProxyPath;
  38881. }else{
  38882. *(const char **)pArg = ":auto: (not held)";
  38883. }
  38884. } else {
  38885. *(const char **)pArg = NULL;
  38886. }
  38887. return SQLITE_OK;
  38888. }
  38889. case SQLITE_FCNTL_SET_LOCKPROXYFILE: {
  38890. unixFile *pFile = (unixFile*)id;
  38891. int rc = SQLITE_OK;
  38892. int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
  38893. if( pArg==NULL || (const char *)pArg==0 ){
  38894. if( isProxyStyle ){
  38895. /* turn off proxy locking - not supported. If support is added for
  38896. ** switching proxy locking mode off then it will need to fail if
  38897. ** the journal mode is WAL mode.
  38898. */
  38899. rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
  38900. }else{
  38901. /* turn off proxy locking - already off - NOOP */
  38902. rc = SQLITE_OK;
  38903. }
  38904. }else{
  38905. const char *proxyPath = (const char *)pArg;
  38906. if( isProxyStyle ){
  38907. proxyLockingContext *pCtx =
  38908. (proxyLockingContext*)pFile->lockingContext;
  38909. if( !strcmp(pArg, ":auto:")
  38910. || (pCtx->lockProxyPath &&
  38911. !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
  38912. ){
  38913. rc = SQLITE_OK;
  38914. }else{
  38915. rc = switchLockProxyPath(pFile, proxyPath);
  38916. }
  38917. }else{
  38918. /* turn on proxy file locking */
  38919. rc = proxyTransformUnixFile(pFile, proxyPath);
  38920. }
  38921. }
  38922. return rc;
  38923. }
  38924. default: {
  38925. assert( 0 ); /* The call assures that only valid opcodes are sent */
  38926. }
  38927. }
  38928. /*NOTREACHED*/ assert(0);
  38929. return SQLITE_ERROR;
  38930. }
  38931. /*
  38932. ** Within this division (the proxying locking implementation) the procedures
  38933. ** above this point are all utilities. The lock-related methods of the
  38934. ** proxy-locking sqlite3_io_method object follow.
  38935. */
  38936. /*
  38937. ** This routine checks if there is a RESERVED lock held on the specified
  38938. ** file by this or any other process. If such a lock is held, set *pResOut
  38939. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  38940. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  38941. */
  38942. static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
  38943. unixFile *pFile = (unixFile*)id;
  38944. int rc = proxyTakeConch(pFile);
  38945. if( rc==SQLITE_OK ){
  38946. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  38947. if( pCtx->conchHeld>0 ){
  38948. unixFile *proxy = pCtx->lockProxy;
  38949. return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
  38950. }else{ /* conchHeld < 0 is lockless */
  38951. pResOut=0;
  38952. }
  38953. }
  38954. return rc;
  38955. }
  38956. /*
  38957. ** Lock the file with the lock specified by parameter eFileLock - one
  38958. ** of the following:
  38959. **
  38960. ** (1) SHARED_LOCK
  38961. ** (2) RESERVED_LOCK
  38962. ** (3) PENDING_LOCK
  38963. ** (4) EXCLUSIVE_LOCK
  38964. **
  38965. ** Sometimes when requesting one lock state, additional lock states
  38966. ** are inserted in between. The locking might fail on one of the later
  38967. ** transitions leaving the lock state different from what it started but
  38968. ** still short of its goal. The following chart shows the allowed
  38969. ** transitions and the inserted intermediate states:
  38970. **
  38971. ** UNLOCKED -> SHARED
  38972. ** SHARED -> RESERVED
  38973. ** SHARED -> (PENDING) -> EXCLUSIVE
  38974. ** RESERVED -> (PENDING) -> EXCLUSIVE
  38975. ** PENDING -> EXCLUSIVE
  38976. **
  38977. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  38978. ** routine to lower a locking level.
  38979. */
  38980. static int proxyLock(sqlite3_file *id, int eFileLock) {
  38981. unixFile *pFile = (unixFile*)id;
  38982. int rc = proxyTakeConch(pFile);
  38983. if( rc==SQLITE_OK ){
  38984. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  38985. if( pCtx->conchHeld>0 ){
  38986. unixFile *proxy = pCtx->lockProxy;
  38987. rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
  38988. pFile->eFileLock = proxy->eFileLock;
  38989. }else{
  38990. /* conchHeld < 0 is lockless */
  38991. }
  38992. }
  38993. return rc;
  38994. }
  38995. /*
  38996. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  38997. ** must be either NO_LOCK or SHARED_LOCK.
  38998. **
  38999. ** If the locking level of the file descriptor is already at or below
  39000. ** the requested locking level, this routine is a no-op.
  39001. */
  39002. static int proxyUnlock(sqlite3_file *id, int eFileLock) {
  39003. unixFile *pFile = (unixFile*)id;
  39004. int rc = proxyTakeConch(pFile);
  39005. if( rc==SQLITE_OK ){
  39006. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  39007. if( pCtx->conchHeld>0 ){
  39008. unixFile *proxy = pCtx->lockProxy;
  39009. rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
  39010. pFile->eFileLock = proxy->eFileLock;
  39011. }else{
  39012. /* conchHeld < 0 is lockless */
  39013. }
  39014. }
  39015. return rc;
  39016. }
  39017. /*
  39018. ** Close a file that uses proxy locks.
  39019. */
  39020. static int proxyClose(sqlite3_file *id) {
  39021. if( ALWAYS(id) ){
  39022. unixFile *pFile = (unixFile*)id;
  39023. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  39024. unixFile *lockProxy = pCtx->lockProxy;
  39025. unixFile *conchFile = pCtx->conchFile;
  39026. int rc = SQLITE_OK;
  39027. if( lockProxy ){
  39028. rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
  39029. if( rc ) return rc;
  39030. rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
  39031. if( rc ) return rc;
  39032. sqlite3_free(lockProxy);
  39033. pCtx->lockProxy = 0;
  39034. }
  39035. if( conchFile ){
  39036. if( pCtx->conchHeld ){
  39037. rc = proxyReleaseConch(pFile);
  39038. if( rc ) return rc;
  39039. }
  39040. rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
  39041. if( rc ) return rc;
  39042. sqlite3_free(conchFile);
  39043. }
  39044. sqlite3DbFree(0, pCtx->lockProxyPath);
  39045. sqlite3_free(pCtx->conchFilePath);
  39046. sqlite3DbFree(0, pCtx->dbPath);
  39047. /* restore the original locking context and pMethod then close it */
  39048. pFile->lockingContext = pCtx->oldLockingContext;
  39049. pFile->pMethod = pCtx->pOldMethod;
  39050. sqlite3_free(pCtx);
  39051. return pFile->pMethod->xClose(id);
  39052. }
  39053. return SQLITE_OK;
  39054. }
  39055. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  39056. /*
  39057. ** The proxy locking style is intended for use with AFP filesystems.
  39058. ** And since AFP is only supported on MacOSX, the proxy locking is also
  39059. ** restricted to MacOSX.
  39060. **
  39061. **
  39062. ******************* End of the proxy lock implementation **********************
  39063. ******************************************************************************/
  39064. /*
  39065. ** Initialize the operating system interface.
  39066. **
  39067. ** This routine registers all VFS implementations for unix-like operating
  39068. ** systems. This routine, and the sqlite3_os_end() routine that follows,
  39069. ** should be the only routines in this file that are visible from other
  39070. ** files.
  39071. **
  39072. ** This routine is called once during SQLite initialization and by a
  39073. ** single thread. The memory allocation and mutex subsystems have not
  39074. ** necessarily been initialized when this routine is called, and so they
  39075. ** should not be used.
  39076. */
  39077. SQLITE_API int sqlite3_os_init(void){
  39078. /*
  39079. ** The following macro defines an initializer for an sqlite3_vfs object.
  39080. ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
  39081. ** to the "finder" function. (pAppData is a pointer to a pointer because
  39082. ** silly C90 rules prohibit a void* from being cast to a function pointer
  39083. ** and so we have to go through the intermediate pointer to avoid problems
  39084. ** when compiling with -pedantic-errors on GCC.)
  39085. **
  39086. ** The FINDER parameter to this macro is the name of the pointer to the
  39087. ** finder-function. The finder-function returns a pointer to the
  39088. ** sqlite_io_methods object that implements the desired locking
  39089. ** behaviors. See the division above that contains the IOMETHODS
  39090. ** macro for addition information on finder-functions.
  39091. **
  39092. ** Most finders simply return a pointer to a fixed sqlite3_io_methods
  39093. ** object. But the "autolockIoFinder" available on MacOSX does a little
  39094. ** more than that; it looks at the filesystem type that hosts the
  39095. ** database file and tries to choose an locking method appropriate for
  39096. ** that filesystem time.
  39097. */
  39098. #define UNIXVFS(VFSNAME, FINDER) { \
  39099. 3, /* iVersion */ \
  39100. sizeof(unixFile), /* szOsFile */ \
  39101. MAX_PATHNAME, /* mxPathname */ \
  39102. 0, /* pNext */ \
  39103. VFSNAME, /* zName */ \
  39104. (void*)&FINDER, /* pAppData */ \
  39105. unixOpen, /* xOpen */ \
  39106. unixDelete, /* xDelete */ \
  39107. unixAccess, /* xAccess */ \
  39108. unixFullPathname, /* xFullPathname */ \
  39109. unixDlOpen, /* xDlOpen */ \
  39110. unixDlError, /* xDlError */ \
  39111. unixDlSym, /* xDlSym */ \
  39112. unixDlClose, /* xDlClose */ \
  39113. unixRandomness, /* xRandomness */ \
  39114. unixSleep, /* xSleep */ \
  39115. unixCurrentTime, /* xCurrentTime */ \
  39116. unixGetLastError, /* xGetLastError */ \
  39117. unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
  39118. unixSetSystemCall, /* xSetSystemCall */ \
  39119. unixGetSystemCall, /* xGetSystemCall */ \
  39120. unixNextSystemCall, /* xNextSystemCall */ \
  39121. }
  39122. /*
  39123. ** All default VFSes for unix are contained in the following array.
  39124. **
  39125. ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
  39126. ** by the SQLite core when the VFS is registered. So the following
  39127. ** array cannot be const.
  39128. */
  39129. static sqlite3_vfs aVfs[] = {
  39130. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  39131. UNIXVFS("unix", autolockIoFinder ),
  39132. #elif OS_VXWORKS
  39133. UNIXVFS("unix", vxworksIoFinder ),
  39134. #else
  39135. UNIXVFS("unix", posixIoFinder ),
  39136. #endif
  39137. UNIXVFS("unix-none", nolockIoFinder ),
  39138. UNIXVFS("unix-dotfile", dotlockIoFinder ),
  39139. UNIXVFS("unix-excl", posixIoFinder ),
  39140. #if OS_VXWORKS
  39141. UNIXVFS("unix-namedsem", semIoFinder ),
  39142. #endif
  39143. #if SQLITE_ENABLE_LOCKING_STYLE || OS_VXWORKS
  39144. UNIXVFS("unix-posix", posixIoFinder ),
  39145. #endif
  39146. #if SQLITE_ENABLE_LOCKING_STYLE
  39147. UNIXVFS("unix-flock", flockIoFinder ),
  39148. #endif
  39149. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  39150. UNIXVFS("unix-afp", afpIoFinder ),
  39151. UNIXVFS("unix-nfs", nfsIoFinder ),
  39152. UNIXVFS("unix-proxy", proxyIoFinder ),
  39153. #endif
  39154. };
  39155. unsigned int i; /* Loop counter */
  39156. /* Double-check that the aSyscall[] array has been constructed
  39157. ** correctly. See ticket [bb3a86e890c8e96ab] */
  39158. assert( ArraySize(aSyscall)==29 );
  39159. /* Register all VFSes defined in the aVfs[] array */
  39160. for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
  39161. sqlite3_vfs_register(&aVfs[i], i==0);
  39162. }
  39163. unixBigLock = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1);
  39164. return SQLITE_OK;
  39165. }
  39166. /*
  39167. ** Shutdown the operating system interface.
  39168. **
  39169. ** Some operating systems might need to do some cleanup in this routine,
  39170. ** to release dynamically allocated objects. But not on unix.
  39171. ** This routine is a no-op for unix.
  39172. */
  39173. SQLITE_API int sqlite3_os_end(void){
  39174. unixBigLock = 0;
  39175. return SQLITE_OK;
  39176. }
  39177. #endif /* SQLITE_OS_UNIX */
  39178. /************** End of os_unix.c *********************************************/
  39179. /************** Begin file os_win.c ******************************************/
  39180. /*
  39181. ** 2004 May 22
  39182. **
  39183. ** The author disclaims copyright to this source code. In place of
  39184. ** a legal notice, here is a blessing:
  39185. **
  39186. ** May you do good and not evil.
  39187. ** May you find forgiveness for yourself and forgive others.
  39188. ** May you share freely, never taking more than you give.
  39189. **
  39190. ******************************************************************************
  39191. **
  39192. ** This file contains code that is specific to Windows.
  39193. */
  39194. /* #include "sqliteInt.h" */
  39195. #if SQLITE_OS_WIN /* This file is used for Windows only */
  39196. /*
  39197. ** Include code that is common to all os_*.c files
  39198. */
  39199. /************** Include os_common.h in the middle of os_win.c ****************/
  39200. /************** Begin file os_common.h ***************************************/
  39201. /*
  39202. ** 2004 May 22
  39203. **
  39204. ** The author disclaims copyright to this source code. In place of
  39205. ** a legal notice, here is a blessing:
  39206. **
  39207. ** May you do good and not evil.
  39208. ** May you find forgiveness for yourself and forgive others.
  39209. ** May you share freely, never taking more than you give.
  39210. **
  39211. ******************************************************************************
  39212. **
  39213. ** This file contains macros and a little bit of code that is common to
  39214. ** all of the platform-specific files (os_*.c) and is #included into those
  39215. ** files.
  39216. **
  39217. ** This file should be #included by the os_*.c files only. It is not a
  39218. ** general purpose header file.
  39219. */
  39220. #ifndef _OS_COMMON_H_
  39221. #define _OS_COMMON_H_
  39222. /*
  39223. ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
  39224. ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
  39225. ** switch. The following code should catch this problem at compile-time.
  39226. */
  39227. #ifdef MEMORY_DEBUG
  39228. # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
  39229. #endif
  39230. /*
  39231. ** Macros for performance tracing. Normally turned off. Only works
  39232. ** on i486 hardware.
  39233. */
  39234. #ifdef SQLITE_PERFORMANCE_TRACE
  39235. /*
  39236. ** hwtime.h contains inline assembler code for implementing
  39237. ** high-performance timing routines.
  39238. */
  39239. /************** Include hwtime.h in the middle of os_common.h ****************/
  39240. /************** Begin file hwtime.h ******************************************/
  39241. /*
  39242. ** 2008 May 27
  39243. **
  39244. ** The author disclaims copyright to this source code. In place of
  39245. ** a legal notice, here is a blessing:
  39246. **
  39247. ** May you do good and not evil.
  39248. ** May you find forgiveness for yourself and forgive others.
  39249. ** May you share freely, never taking more than you give.
  39250. **
  39251. ******************************************************************************
  39252. **
  39253. ** This file contains inline asm code for retrieving "high-performance"
  39254. ** counters for x86 and x86_64 class CPUs.
  39255. */
  39256. #ifndef SQLITE_HWTIME_H
  39257. #define SQLITE_HWTIME_H
  39258. /*
  39259. ** The following routine only works on pentium-class (or newer) processors.
  39260. ** It uses the RDTSC opcode to read the cycle count value out of the
  39261. ** processor and returns that value. This can be used for high-res
  39262. ** profiling.
  39263. */
  39264. #if !defined(__STRICT_ANSI__) && \
  39265. (defined(__GNUC__) || defined(_MSC_VER)) && \
  39266. (defined(i386) || defined(__i386__) || defined(_M_IX86))
  39267. #if defined(__GNUC__)
  39268. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  39269. unsigned int lo, hi;
  39270. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  39271. return (sqlite_uint64)hi << 32 | lo;
  39272. }
  39273. #elif defined(_MSC_VER)
  39274. __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
  39275. __asm {
  39276. rdtsc
  39277. ret ; return value at EDX:EAX
  39278. }
  39279. }
  39280. #endif
  39281. #elif !defined(__STRICT_ANSI__) && (defined(__GNUC__) && defined(__x86_64__))
  39282. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  39283. unsigned long val;
  39284. __asm__ __volatile__ ("rdtsc" : "=A" (val));
  39285. return val;
  39286. }
  39287. #elif !defined(__STRICT_ANSI__) && (defined(__GNUC__) && defined(__ppc__))
  39288. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  39289. unsigned long long retval;
  39290. unsigned long junk;
  39291. __asm__ __volatile__ ("\n\
  39292. 1: mftbu %1\n\
  39293. mftb %L0\n\
  39294. mftbu %0\n\
  39295. cmpw %0,%1\n\
  39296. bne 1b"
  39297. : "=r" (retval), "=r" (junk));
  39298. return retval;
  39299. }
  39300. #else
  39301. /*
  39302. ** asm() is needed for hardware timing support. Without asm(),
  39303. ** disable the sqlite3Hwtime() routine.
  39304. **
  39305. ** sqlite3Hwtime() is only used for some obscure debugging
  39306. ** and analysis configurations, not in any deliverable, so this
  39307. ** should not be a great loss.
  39308. */
  39309. SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
  39310. #endif
  39311. #endif /* !defined(SQLITE_HWTIME_H) */
  39312. /************** End of hwtime.h **********************************************/
  39313. /************** Continuing where we left off in os_common.h ******************/
  39314. static sqlite_uint64 g_start;
  39315. static sqlite_uint64 g_elapsed;
  39316. #define TIMER_START g_start=sqlite3Hwtime()
  39317. #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
  39318. #define TIMER_ELAPSED g_elapsed
  39319. #else
  39320. #define TIMER_START
  39321. #define TIMER_END
  39322. #define TIMER_ELAPSED ((sqlite_uint64)0)
  39323. #endif
  39324. /*
  39325. ** If we compile with the SQLITE_TEST macro set, then the following block
  39326. ** of code will give us the ability to simulate a disk I/O error. This
  39327. ** is used for testing the I/O recovery logic.
  39328. */
  39329. #if defined(SQLITE_TEST)
  39330. SQLITE_API extern int sqlite3_io_error_hit;
  39331. SQLITE_API extern int sqlite3_io_error_hardhit;
  39332. SQLITE_API extern int sqlite3_io_error_pending;
  39333. SQLITE_API extern int sqlite3_io_error_persist;
  39334. SQLITE_API extern int sqlite3_io_error_benign;
  39335. SQLITE_API extern int sqlite3_diskfull_pending;
  39336. SQLITE_API extern int sqlite3_diskfull;
  39337. #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
  39338. #define SimulateIOError(CODE) \
  39339. if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
  39340. || sqlite3_io_error_pending-- == 1 ) \
  39341. { local_ioerr(); CODE; }
  39342. static void local_ioerr(){
  39343. IOTRACE(("IOERR\n"));
  39344. sqlite3_io_error_hit++;
  39345. if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
  39346. }
  39347. #define SimulateDiskfullError(CODE) \
  39348. if( sqlite3_diskfull_pending ){ \
  39349. if( sqlite3_diskfull_pending == 1 ){ \
  39350. local_ioerr(); \
  39351. sqlite3_diskfull = 1; \
  39352. sqlite3_io_error_hit = 1; \
  39353. CODE; \
  39354. }else{ \
  39355. sqlite3_diskfull_pending--; \
  39356. } \
  39357. }
  39358. #else
  39359. #define SimulateIOErrorBenign(X)
  39360. #define SimulateIOError(A)
  39361. #define SimulateDiskfullError(A)
  39362. #endif /* defined(SQLITE_TEST) */
  39363. /*
  39364. ** When testing, keep a count of the number of open files.
  39365. */
  39366. #if defined(SQLITE_TEST)
  39367. SQLITE_API extern int sqlite3_open_file_count;
  39368. #define OpenCounter(X) sqlite3_open_file_count+=(X)
  39369. #else
  39370. #define OpenCounter(X)
  39371. #endif /* defined(SQLITE_TEST) */
  39372. #endif /* !defined(_OS_COMMON_H_) */
  39373. /************** End of os_common.h *******************************************/
  39374. /************** Continuing where we left off in os_win.c *********************/
  39375. /*
  39376. ** Include the header file for the Windows VFS.
  39377. */
  39378. /* #include "os_win.h" */
  39379. /*
  39380. ** Compiling and using WAL mode requires several APIs that are only
  39381. ** available in Windows platforms based on the NT kernel.
  39382. */
  39383. #if !SQLITE_OS_WINNT && !defined(SQLITE_OMIT_WAL)
  39384. # error "WAL mode requires support from the Windows NT kernel, compile\
  39385. with SQLITE_OMIT_WAL."
  39386. #endif
  39387. #if !SQLITE_OS_WINNT && SQLITE_MAX_MMAP_SIZE>0
  39388. # error "Memory mapped files require support from the Windows NT kernel,\
  39389. compile with SQLITE_MAX_MMAP_SIZE=0."
  39390. #endif
  39391. /*
  39392. ** Are most of the Win32 ANSI APIs available (i.e. with certain exceptions
  39393. ** based on the sub-platform)?
  39394. */
  39395. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(SQLITE_WIN32_NO_ANSI)
  39396. # define SQLITE_WIN32_HAS_ANSI
  39397. #endif
  39398. /*
  39399. ** Are most of the Win32 Unicode APIs available (i.e. with certain exceptions
  39400. ** based on the sub-platform)?
  39401. */
  39402. #if (SQLITE_OS_WINCE || SQLITE_OS_WINNT || SQLITE_OS_WINRT) && \
  39403. !defined(SQLITE_WIN32_NO_WIDE)
  39404. # define SQLITE_WIN32_HAS_WIDE
  39405. #endif
  39406. /*
  39407. ** Make sure at least one set of Win32 APIs is available.
  39408. */
  39409. #if !defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_WIN32_HAS_WIDE)
  39410. # error "At least one of SQLITE_WIN32_HAS_ANSI and SQLITE_WIN32_HAS_WIDE\
  39411. must be defined."
  39412. #endif
  39413. /*
  39414. ** Define the required Windows SDK version constants if they are not
  39415. ** already available.
  39416. */
  39417. #ifndef NTDDI_WIN8
  39418. # define NTDDI_WIN8 0x06020000
  39419. #endif
  39420. #ifndef NTDDI_WINBLUE
  39421. # define NTDDI_WINBLUE 0x06030000
  39422. #endif
  39423. #ifndef NTDDI_WINTHRESHOLD
  39424. # define NTDDI_WINTHRESHOLD 0x06040000
  39425. #endif
  39426. /*
  39427. ** Check to see if the GetVersionEx[AW] functions are deprecated on the
  39428. ** target system. GetVersionEx was first deprecated in Win8.1.
  39429. */
  39430. #ifndef SQLITE_WIN32_GETVERSIONEX
  39431. # if defined(NTDDI_VERSION) && NTDDI_VERSION >= NTDDI_WINBLUE
  39432. # define SQLITE_WIN32_GETVERSIONEX 0 /* GetVersionEx() is deprecated */
  39433. # else
  39434. # define SQLITE_WIN32_GETVERSIONEX 1 /* GetVersionEx() is current */
  39435. # endif
  39436. #endif
  39437. /*
  39438. ** Check to see if the CreateFileMappingA function is supported on the
  39439. ** target system. It is unavailable when using "mincore.lib" on Win10.
  39440. ** When compiling for Windows 10, always assume "mincore.lib" is in use.
  39441. */
  39442. #ifndef SQLITE_WIN32_CREATEFILEMAPPINGA
  39443. # if defined(NTDDI_VERSION) && NTDDI_VERSION >= NTDDI_WINTHRESHOLD
  39444. # define SQLITE_WIN32_CREATEFILEMAPPINGA 0
  39445. # else
  39446. # define SQLITE_WIN32_CREATEFILEMAPPINGA 1
  39447. # endif
  39448. #endif
  39449. /*
  39450. ** This constant should already be defined (in the "WinDef.h" SDK file).
  39451. */
  39452. #ifndef MAX_PATH
  39453. # define MAX_PATH (260)
  39454. #endif
  39455. /*
  39456. ** Maximum pathname length (in chars) for Win32. This should normally be
  39457. ** MAX_PATH.
  39458. */
  39459. #ifndef SQLITE_WIN32_MAX_PATH_CHARS
  39460. # define SQLITE_WIN32_MAX_PATH_CHARS (MAX_PATH)
  39461. #endif
  39462. /*
  39463. ** This constant should already be defined (in the "WinNT.h" SDK file).
  39464. */
  39465. #ifndef UNICODE_STRING_MAX_CHARS
  39466. # define UNICODE_STRING_MAX_CHARS (32767)
  39467. #endif
  39468. /*
  39469. ** Maximum pathname length (in chars) for WinNT. This should normally be
  39470. ** UNICODE_STRING_MAX_CHARS.
  39471. */
  39472. #ifndef SQLITE_WINNT_MAX_PATH_CHARS
  39473. # define SQLITE_WINNT_MAX_PATH_CHARS (UNICODE_STRING_MAX_CHARS)
  39474. #endif
  39475. /*
  39476. ** Maximum pathname length (in bytes) for Win32. The MAX_PATH macro is in
  39477. ** characters, so we allocate 4 bytes per character assuming worst-case of
  39478. ** 4-bytes-per-character for UTF8.
  39479. */
  39480. #ifndef SQLITE_WIN32_MAX_PATH_BYTES
  39481. # define SQLITE_WIN32_MAX_PATH_BYTES (SQLITE_WIN32_MAX_PATH_CHARS*4)
  39482. #endif
  39483. /*
  39484. ** Maximum pathname length (in bytes) for WinNT. This should normally be
  39485. ** UNICODE_STRING_MAX_CHARS * sizeof(WCHAR).
  39486. */
  39487. #ifndef SQLITE_WINNT_MAX_PATH_BYTES
  39488. # define SQLITE_WINNT_MAX_PATH_BYTES \
  39489. (sizeof(WCHAR) * SQLITE_WINNT_MAX_PATH_CHARS)
  39490. #endif
  39491. /*
  39492. ** Maximum error message length (in chars) for WinRT.
  39493. */
  39494. #ifndef SQLITE_WIN32_MAX_ERRMSG_CHARS
  39495. # define SQLITE_WIN32_MAX_ERRMSG_CHARS (1024)
  39496. #endif
  39497. /*
  39498. ** Returns non-zero if the character should be treated as a directory
  39499. ** separator.
  39500. */
  39501. #ifndef winIsDirSep
  39502. # define winIsDirSep(a) (((a) == '/') || ((a) == '\\'))
  39503. #endif
  39504. /*
  39505. ** This macro is used when a local variable is set to a value that is
  39506. ** [sometimes] not used by the code (e.g. via conditional compilation).
  39507. */
  39508. #ifndef UNUSED_VARIABLE_VALUE
  39509. # define UNUSED_VARIABLE_VALUE(x) (void)(x)
  39510. #endif
  39511. /*
  39512. ** Returns the character that should be used as the directory separator.
  39513. */
  39514. #ifndef winGetDirSep
  39515. # define winGetDirSep() '\\'
  39516. #endif
  39517. /*
  39518. ** Do we need to manually define the Win32 file mapping APIs for use with WAL
  39519. ** mode or memory mapped files (e.g. these APIs are available in the Windows
  39520. ** CE SDK; however, they are not present in the header file)?
  39521. */
  39522. #if SQLITE_WIN32_FILEMAPPING_API && \
  39523. (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
  39524. /*
  39525. ** Two of the file mapping APIs are different under WinRT. Figure out which
  39526. ** set we need.
  39527. */
  39528. #if SQLITE_OS_WINRT
  39529. WINBASEAPI HANDLE WINAPI CreateFileMappingFromApp(HANDLE, \
  39530. LPSECURITY_ATTRIBUTES, ULONG, ULONG64, LPCWSTR);
  39531. WINBASEAPI LPVOID WINAPI MapViewOfFileFromApp(HANDLE, ULONG, ULONG64, SIZE_T);
  39532. #else
  39533. #if defined(SQLITE_WIN32_HAS_ANSI)
  39534. WINBASEAPI HANDLE WINAPI CreateFileMappingA(HANDLE, LPSECURITY_ATTRIBUTES, \
  39535. DWORD, DWORD, DWORD, LPCSTR);
  39536. #endif /* defined(SQLITE_WIN32_HAS_ANSI) */
  39537. #if defined(SQLITE_WIN32_HAS_WIDE)
  39538. WINBASEAPI HANDLE WINAPI CreateFileMappingW(HANDLE, LPSECURITY_ATTRIBUTES, \
  39539. DWORD, DWORD, DWORD, LPCWSTR);
  39540. #endif /* defined(SQLITE_WIN32_HAS_WIDE) */
  39541. WINBASEAPI LPVOID WINAPI MapViewOfFile(HANDLE, DWORD, DWORD, DWORD, SIZE_T);
  39542. #endif /* SQLITE_OS_WINRT */
  39543. /*
  39544. ** These file mapping APIs are common to both Win32 and WinRT.
  39545. */
  39546. WINBASEAPI BOOL WINAPI FlushViewOfFile(LPCVOID, SIZE_T);
  39547. WINBASEAPI BOOL WINAPI UnmapViewOfFile(LPCVOID);
  39548. #endif /* SQLITE_WIN32_FILEMAPPING_API */
  39549. /*
  39550. ** Some Microsoft compilers lack this definition.
  39551. */
  39552. #ifndef INVALID_FILE_ATTRIBUTES
  39553. # define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
  39554. #endif
  39555. #ifndef FILE_FLAG_MASK
  39556. # define FILE_FLAG_MASK (0xFF3C0000)
  39557. #endif
  39558. #ifndef FILE_ATTRIBUTE_MASK
  39559. # define FILE_ATTRIBUTE_MASK (0x0003FFF7)
  39560. #endif
  39561. #ifndef SQLITE_OMIT_WAL
  39562. /* Forward references to structures used for WAL */
  39563. typedef struct winShm winShm; /* A connection to shared-memory */
  39564. typedef struct winShmNode winShmNode; /* A region of shared-memory */
  39565. #endif
  39566. /*
  39567. ** WinCE lacks native support for file locking so we have to fake it
  39568. ** with some code of our own.
  39569. */
  39570. #if SQLITE_OS_WINCE
  39571. typedef struct winceLock {
  39572. int nReaders; /* Number of reader locks obtained */
  39573. BOOL bPending; /* Indicates a pending lock has been obtained */
  39574. BOOL bReserved; /* Indicates a reserved lock has been obtained */
  39575. BOOL bExclusive; /* Indicates an exclusive lock has been obtained */
  39576. } winceLock;
  39577. #endif
  39578. /*
  39579. ** The winFile structure is a subclass of sqlite3_file* specific to the win32
  39580. ** portability layer.
  39581. */
  39582. typedef struct winFile winFile;
  39583. struct winFile {
  39584. const sqlite3_io_methods *pMethod; /*** Must be first ***/
  39585. sqlite3_vfs *pVfs; /* The VFS used to open this file */
  39586. HANDLE h; /* Handle for accessing the file */
  39587. u8 locktype; /* Type of lock currently held on this file */
  39588. short sharedLockByte; /* Randomly chosen byte used as a shared lock */
  39589. u8 ctrlFlags; /* Flags. See WINFILE_* below */
  39590. DWORD lastErrno; /* The Windows errno from the last I/O error */
  39591. #ifndef SQLITE_OMIT_WAL
  39592. winShm *pShm; /* Instance of shared memory on this file */
  39593. #endif
  39594. const char *zPath; /* Full pathname of this file */
  39595. int szChunk; /* Chunk size configured by FCNTL_CHUNK_SIZE */
  39596. #if SQLITE_OS_WINCE
  39597. LPWSTR zDeleteOnClose; /* Name of file to delete when closing */
  39598. HANDLE hMutex; /* Mutex used to control access to shared lock */
  39599. HANDLE hShared; /* Shared memory segment used for locking */
  39600. winceLock local; /* Locks obtained by this instance of winFile */
  39601. winceLock *shared; /* Global shared lock memory for the file */
  39602. #endif
  39603. #if SQLITE_MAX_MMAP_SIZE>0
  39604. int nFetchOut; /* Number of outstanding xFetch references */
  39605. HANDLE hMap; /* Handle for accessing memory mapping */
  39606. void *pMapRegion; /* Area memory mapped */
  39607. sqlite3_int64 mmapSize; /* Size of mapped region */
  39608. sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */
  39609. #endif
  39610. };
  39611. /*
  39612. ** The winVfsAppData structure is used for the pAppData member for all of the
  39613. ** Win32 VFS variants.
  39614. */
  39615. typedef struct winVfsAppData winVfsAppData;
  39616. struct winVfsAppData {
  39617. const sqlite3_io_methods *pMethod; /* The file I/O methods to use. */
  39618. void *pAppData; /* The extra pAppData, if any. */
  39619. BOOL bNoLock; /* Non-zero if locking is disabled. */
  39620. };
  39621. /*
  39622. ** Allowed values for winFile.ctrlFlags
  39623. */
  39624. #define WINFILE_RDONLY 0x02 /* Connection is read only */
  39625. #define WINFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
  39626. #define WINFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
  39627. /*
  39628. * The size of the buffer used by sqlite3_win32_write_debug().
  39629. */
  39630. #ifndef SQLITE_WIN32_DBG_BUF_SIZE
  39631. # define SQLITE_WIN32_DBG_BUF_SIZE ((int)(4096-sizeof(DWORD)))
  39632. #endif
  39633. /*
  39634. * If compiled with SQLITE_WIN32_MALLOC on Windows, we will use the
  39635. * various Win32 API heap functions instead of our own.
  39636. */
  39637. #ifdef SQLITE_WIN32_MALLOC
  39638. /*
  39639. * If this is non-zero, an isolated heap will be created by the native Win32
  39640. * allocator subsystem; otherwise, the default process heap will be used. This
  39641. * setting has no effect when compiling for WinRT. By default, this is enabled
  39642. * and an isolated heap will be created to store all allocated data.
  39643. *
  39644. ******************************************************************************
  39645. * WARNING: It is important to note that when this setting is non-zero and the
  39646. * winMemShutdown function is called (e.g. by the sqlite3_shutdown
  39647. * function), all data that was allocated using the isolated heap will
  39648. * be freed immediately and any attempt to access any of that freed
  39649. * data will almost certainly result in an immediate access violation.
  39650. ******************************************************************************
  39651. */
  39652. #ifndef SQLITE_WIN32_HEAP_CREATE
  39653. # define SQLITE_WIN32_HEAP_CREATE (TRUE)
  39654. #endif
  39655. /*
  39656. * This is the maximum possible initial size of the Win32-specific heap, in
  39657. * bytes.
  39658. */
  39659. #ifndef SQLITE_WIN32_HEAP_MAX_INIT_SIZE
  39660. # define SQLITE_WIN32_HEAP_MAX_INIT_SIZE (4294967295U)
  39661. #endif
  39662. /*
  39663. * This is the extra space for the initial size of the Win32-specific heap,
  39664. * in bytes. This value may be zero.
  39665. */
  39666. #ifndef SQLITE_WIN32_HEAP_INIT_EXTRA
  39667. # define SQLITE_WIN32_HEAP_INIT_EXTRA (4194304)
  39668. #endif
  39669. /*
  39670. * Calculate the maximum legal cache size, in pages, based on the maximum
  39671. * possible initial heap size and the default page size, setting aside the
  39672. * needed extra space.
  39673. */
  39674. #ifndef SQLITE_WIN32_MAX_CACHE_SIZE
  39675. # define SQLITE_WIN32_MAX_CACHE_SIZE (((SQLITE_WIN32_HEAP_MAX_INIT_SIZE) - \
  39676. (SQLITE_WIN32_HEAP_INIT_EXTRA)) / \
  39677. (SQLITE_DEFAULT_PAGE_SIZE))
  39678. #endif
  39679. /*
  39680. * This is cache size used in the calculation of the initial size of the
  39681. * Win32-specific heap. It cannot be negative.
  39682. */
  39683. #ifndef SQLITE_WIN32_CACHE_SIZE
  39684. # if SQLITE_DEFAULT_CACHE_SIZE>=0
  39685. # define SQLITE_WIN32_CACHE_SIZE (SQLITE_DEFAULT_CACHE_SIZE)
  39686. # else
  39687. # define SQLITE_WIN32_CACHE_SIZE (-(SQLITE_DEFAULT_CACHE_SIZE))
  39688. # endif
  39689. #endif
  39690. /*
  39691. * Make sure that the calculated cache size, in pages, cannot cause the
  39692. * initial size of the Win32-specific heap to exceed the maximum amount
  39693. * of memory that can be specified in the call to HeapCreate.
  39694. */
  39695. #if SQLITE_WIN32_CACHE_SIZE>SQLITE_WIN32_MAX_CACHE_SIZE
  39696. # undef SQLITE_WIN32_CACHE_SIZE
  39697. # define SQLITE_WIN32_CACHE_SIZE (2000)
  39698. #endif
  39699. /*
  39700. * The initial size of the Win32-specific heap. This value may be zero.
  39701. */
  39702. #ifndef SQLITE_WIN32_HEAP_INIT_SIZE
  39703. # define SQLITE_WIN32_HEAP_INIT_SIZE ((SQLITE_WIN32_CACHE_SIZE) * \
  39704. (SQLITE_DEFAULT_PAGE_SIZE) + \
  39705. (SQLITE_WIN32_HEAP_INIT_EXTRA))
  39706. #endif
  39707. /*
  39708. * The maximum size of the Win32-specific heap. This value may be zero.
  39709. */
  39710. #ifndef SQLITE_WIN32_HEAP_MAX_SIZE
  39711. # define SQLITE_WIN32_HEAP_MAX_SIZE (0)
  39712. #endif
  39713. /*
  39714. * The extra flags to use in calls to the Win32 heap APIs. This value may be
  39715. * zero for the default behavior.
  39716. */
  39717. #ifndef SQLITE_WIN32_HEAP_FLAGS
  39718. # define SQLITE_WIN32_HEAP_FLAGS (0)
  39719. #endif
  39720. /*
  39721. ** The winMemData structure stores information required by the Win32-specific
  39722. ** sqlite3_mem_methods implementation.
  39723. */
  39724. typedef struct winMemData winMemData;
  39725. struct winMemData {
  39726. #ifndef NDEBUG
  39727. u32 magic1; /* Magic number to detect structure corruption. */
  39728. #endif
  39729. HANDLE hHeap; /* The handle to our heap. */
  39730. BOOL bOwned; /* Do we own the heap (i.e. destroy it on shutdown)? */
  39731. #ifndef NDEBUG
  39732. u32 magic2; /* Magic number to detect structure corruption. */
  39733. #endif
  39734. };
  39735. #ifndef NDEBUG
  39736. #define WINMEM_MAGIC1 0x42b2830b
  39737. #define WINMEM_MAGIC2 0xbd4d7cf4
  39738. #endif
  39739. static struct winMemData win_mem_data = {
  39740. #ifndef NDEBUG
  39741. WINMEM_MAGIC1,
  39742. #endif
  39743. NULL, FALSE
  39744. #ifndef NDEBUG
  39745. ,WINMEM_MAGIC2
  39746. #endif
  39747. };
  39748. #ifndef NDEBUG
  39749. #define winMemAssertMagic1() assert( win_mem_data.magic1==WINMEM_MAGIC1 )
  39750. #define winMemAssertMagic2() assert( win_mem_data.magic2==WINMEM_MAGIC2 )
  39751. #define winMemAssertMagic() winMemAssertMagic1(); winMemAssertMagic2();
  39752. #else
  39753. #define winMemAssertMagic()
  39754. #endif
  39755. #define winMemGetDataPtr() &win_mem_data
  39756. #define winMemGetHeap() win_mem_data.hHeap
  39757. #define winMemGetOwned() win_mem_data.bOwned
  39758. static void *winMemMalloc(int nBytes);
  39759. static void winMemFree(void *pPrior);
  39760. static void *winMemRealloc(void *pPrior, int nBytes);
  39761. static int winMemSize(void *p);
  39762. static int winMemRoundup(int n);
  39763. static int winMemInit(void *pAppData);
  39764. static void winMemShutdown(void *pAppData);
  39765. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void);
  39766. #endif /* SQLITE_WIN32_MALLOC */
  39767. /*
  39768. ** The following variable is (normally) set once and never changes
  39769. ** thereafter. It records whether the operating system is Win9x
  39770. ** or WinNT.
  39771. **
  39772. ** 0: Operating system unknown.
  39773. ** 1: Operating system is Win9x.
  39774. ** 2: Operating system is WinNT.
  39775. **
  39776. ** In order to facilitate testing on a WinNT system, the test fixture
  39777. ** can manually set this value to 1 to emulate Win98 behavior.
  39778. */
  39779. #ifdef SQLITE_TEST
  39780. SQLITE_API LONG SQLITE_WIN32_VOLATILE sqlite3_os_type = 0;
  39781. #else
  39782. static LONG SQLITE_WIN32_VOLATILE sqlite3_os_type = 0;
  39783. #endif
  39784. #ifndef SYSCALL
  39785. # define SYSCALL sqlite3_syscall_ptr
  39786. #endif
  39787. /*
  39788. ** This function is not available on Windows CE or WinRT.
  39789. */
  39790. #if SQLITE_OS_WINCE || SQLITE_OS_WINRT
  39791. # define osAreFileApisANSI() 1
  39792. #endif
  39793. /*
  39794. ** Many system calls are accessed through pointer-to-functions so that
  39795. ** they may be overridden at runtime to facilitate fault injection during
  39796. ** testing and sandboxing. The following array holds the names and pointers
  39797. ** to all overrideable system calls.
  39798. */
  39799. static struct win_syscall {
  39800. const char *zName; /* Name of the system call */
  39801. sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
  39802. sqlite3_syscall_ptr pDefault; /* Default value */
  39803. } aSyscall[] = {
  39804. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  39805. { "AreFileApisANSI", (SYSCALL)AreFileApisANSI, 0 },
  39806. #else
  39807. { "AreFileApisANSI", (SYSCALL)0, 0 },
  39808. #endif
  39809. #ifndef osAreFileApisANSI
  39810. #define osAreFileApisANSI ((BOOL(WINAPI*)(VOID))aSyscall[0].pCurrent)
  39811. #endif
  39812. #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
  39813. { "CharLowerW", (SYSCALL)CharLowerW, 0 },
  39814. #else
  39815. { "CharLowerW", (SYSCALL)0, 0 },
  39816. #endif
  39817. #define osCharLowerW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[1].pCurrent)
  39818. #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
  39819. { "CharUpperW", (SYSCALL)CharUpperW, 0 },
  39820. #else
  39821. { "CharUpperW", (SYSCALL)0, 0 },
  39822. #endif
  39823. #define osCharUpperW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[2].pCurrent)
  39824. { "CloseHandle", (SYSCALL)CloseHandle, 0 },
  39825. #define osCloseHandle ((BOOL(WINAPI*)(HANDLE))aSyscall[3].pCurrent)
  39826. #if defined(SQLITE_WIN32_HAS_ANSI)
  39827. { "CreateFileA", (SYSCALL)CreateFileA, 0 },
  39828. #else
  39829. { "CreateFileA", (SYSCALL)0, 0 },
  39830. #endif
  39831. #define osCreateFileA ((HANDLE(WINAPI*)(LPCSTR,DWORD,DWORD, \
  39832. LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[4].pCurrent)
  39833. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  39834. { "CreateFileW", (SYSCALL)CreateFileW, 0 },
  39835. #else
  39836. { "CreateFileW", (SYSCALL)0, 0 },
  39837. #endif
  39838. #define osCreateFileW ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD, \
  39839. LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[5].pCurrent)
  39840. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_ANSI) && \
  39841. (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0) && \
  39842. SQLITE_WIN32_CREATEFILEMAPPINGA
  39843. { "CreateFileMappingA", (SYSCALL)CreateFileMappingA, 0 },
  39844. #else
  39845. { "CreateFileMappingA", (SYSCALL)0, 0 },
  39846. #endif
  39847. #define osCreateFileMappingA ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
  39848. DWORD,DWORD,DWORD,LPCSTR))aSyscall[6].pCurrent)
  39849. #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
  39850. (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0))
  39851. { "CreateFileMappingW", (SYSCALL)CreateFileMappingW, 0 },
  39852. #else
  39853. { "CreateFileMappingW", (SYSCALL)0, 0 },
  39854. #endif
  39855. #define osCreateFileMappingW ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
  39856. DWORD,DWORD,DWORD,LPCWSTR))aSyscall[7].pCurrent)
  39857. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  39858. { "CreateMutexW", (SYSCALL)CreateMutexW, 0 },
  39859. #else
  39860. { "CreateMutexW", (SYSCALL)0, 0 },
  39861. #endif
  39862. #define osCreateMutexW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,BOOL, \
  39863. LPCWSTR))aSyscall[8].pCurrent)
  39864. #if defined(SQLITE_WIN32_HAS_ANSI)
  39865. { "DeleteFileA", (SYSCALL)DeleteFileA, 0 },
  39866. #else
  39867. { "DeleteFileA", (SYSCALL)0, 0 },
  39868. #endif
  39869. #define osDeleteFileA ((BOOL(WINAPI*)(LPCSTR))aSyscall[9].pCurrent)
  39870. #if defined(SQLITE_WIN32_HAS_WIDE)
  39871. { "DeleteFileW", (SYSCALL)DeleteFileW, 0 },
  39872. #else
  39873. { "DeleteFileW", (SYSCALL)0, 0 },
  39874. #endif
  39875. #define osDeleteFileW ((BOOL(WINAPI*)(LPCWSTR))aSyscall[10].pCurrent)
  39876. #if SQLITE_OS_WINCE
  39877. { "FileTimeToLocalFileTime", (SYSCALL)FileTimeToLocalFileTime, 0 },
  39878. #else
  39879. { "FileTimeToLocalFileTime", (SYSCALL)0, 0 },
  39880. #endif
  39881. #define osFileTimeToLocalFileTime ((BOOL(WINAPI*)(CONST FILETIME*, \
  39882. LPFILETIME))aSyscall[11].pCurrent)
  39883. #if SQLITE_OS_WINCE
  39884. { "FileTimeToSystemTime", (SYSCALL)FileTimeToSystemTime, 0 },
  39885. #else
  39886. { "FileTimeToSystemTime", (SYSCALL)0, 0 },
  39887. #endif
  39888. #define osFileTimeToSystemTime ((BOOL(WINAPI*)(CONST FILETIME*, \
  39889. LPSYSTEMTIME))aSyscall[12].pCurrent)
  39890. { "FlushFileBuffers", (SYSCALL)FlushFileBuffers, 0 },
  39891. #define osFlushFileBuffers ((BOOL(WINAPI*)(HANDLE))aSyscall[13].pCurrent)
  39892. #if defined(SQLITE_WIN32_HAS_ANSI)
  39893. { "FormatMessageA", (SYSCALL)FormatMessageA, 0 },
  39894. #else
  39895. { "FormatMessageA", (SYSCALL)0, 0 },
  39896. #endif
  39897. #define osFormatMessageA ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPSTR, \
  39898. DWORD,va_list*))aSyscall[14].pCurrent)
  39899. #if defined(SQLITE_WIN32_HAS_WIDE)
  39900. { "FormatMessageW", (SYSCALL)FormatMessageW, 0 },
  39901. #else
  39902. { "FormatMessageW", (SYSCALL)0, 0 },
  39903. #endif
  39904. #define osFormatMessageW ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPWSTR, \
  39905. DWORD,va_list*))aSyscall[15].pCurrent)
  39906. #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
  39907. { "FreeLibrary", (SYSCALL)FreeLibrary, 0 },
  39908. #else
  39909. { "FreeLibrary", (SYSCALL)0, 0 },
  39910. #endif
  39911. #define osFreeLibrary ((BOOL(WINAPI*)(HMODULE))aSyscall[16].pCurrent)
  39912. { "GetCurrentProcessId", (SYSCALL)GetCurrentProcessId, 0 },
  39913. #define osGetCurrentProcessId ((DWORD(WINAPI*)(VOID))aSyscall[17].pCurrent)
  39914. #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
  39915. { "GetDiskFreeSpaceA", (SYSCALL)GetDiskFreeSpaceA, 0 },
  39916. #else
  39917. { "GetDiskFreeSpaceA", (SYSCALL)0, 0 },
  39918. #endif
  39919. #define osGetDiskFreeSpaceA ((BOOL(WINAPI*)(LPCSTR,LPDWORD,LPDWORD,LPDWORD, \
  39920. LPDWORD))aSyscall[18].pCurrent)
  39921. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  39922. { "GetDiskFreeSpaceW", (SYSCALL)GetDiskFreeSpaceW, 0 },
  39923. #else
  39924. { "GetDiskFreeSpaceW", (SYSCALL)0, 0 },
  39925. #endif
  39926. #define osGetDiskFreeSpaceW ((BOOL(WINAPI*)(LPCWSTR,LPDWORD,LPDWORD,LPDWORD, \
  39927. LPDWORD))aSyscall[19].pCurrent)
  39928. #if defined(SQLITE_WIN32_HAS_ANSI)
  39929. { "GetFileAttributesA", (SYSCALL)GetFileAttributesA, 0 },
  39930. #else
  39931. { "GetFileAttributesA", (SYSCALL)0, 0 },
  39932. #endif
  39933. #define osGetFileAttributesA ((DWORD(WINAPI*)(LPCSTR))aSyscall[20].pCurrent)
  39934. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  39935. { "GetFileAttributesW", (SYSCALL)GetFileAttributesW, 0 },
  39936. #else
  39937. { "GetFileAttributesW", (SYSCALL)0, 0 },
  39938. #endif
  39939. #define osGetFileAttributesW ((DWORD(WINAPI*)(LPCWSTR))aSyscall[21].pCurrent)
  39940. #if defined(SQLITE_WIN32_HAS_WIDE)
  39941. { "GetFileAttributesExW", (SYSCALL)GetFileAttributesExW, 0 },
  39942. #else
  39943. { "GetFileAttributesExW", (SYSCALL)0, 0 },
  39944. #endif
  39945. #define osGetFileAttributesExW ((BOOL(WINAPI*)(LPCWSTR,GET_FILEEX_INFO_LEVELS, \
  39946. LPVOID))aSyscall[22].pCurrent)
  39947. #if !SQLITE_OS_WINRT
  39948. { "GetFileSize", (SYSCALL)GetFileSize, 0 },
  39949. #else
  39950. { "GetFileSize", (SYSCALL)0, 0 },
  39951. #endif
  39952. #define osGetFileSize ((DWORD(WINAPI*)(HANDLE,LPDWORD))aSyscall[23].pCurrent)
  39953. #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
  39954. { "GetFullPathNameA", (SYSCALL)GetFullPathNameA, 0 },
  39955. #else
  39956. { "GetFullPathNameA", (SYSCALL)0, 0 },
  39957. #endif
  39958. #define osGetFullPathNameA ((DWORD(WINAPI*)(LPCSTR,DWORD,LPSTR, \
  39959. LPSTR*))aSyscall[24].pCurrent)
  39960. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  39961. { "GetFullPathNameW", (SYSCALL)GetFullPathNameW, 0 },
  39962. #else
  39963. { "GetFullPathNameW", (SYSCALL)0, 0 },
  39964. #endif
  39965. #define osGetFullPathNameW ((DWORD(WINAPI*)(LPCWSTR,DWORD,LPWSTR, \
  39966. LPWSTR*))aSyscall[25].pCurrent)
  39967. { "GetLastError", (SYSCALL)GetLastError, 0 },
  39968. #define osGetLastError ((DWORD(WINAPI*)(VOID))aSyscall[26].pCurrent)
  39969. #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
  39970. #if SQLITE_OS_WINCE
  39971. /* The GetProcAddressA() routine is only available on Windows CE. */
  39972. { "GetProcAddressA", (SYSCALL)GetProcAddressA, 0 },
  39973. #else
  39974. /* All other Windows platforms expect GetProcAddress() to take
  39975. ** an ANSI string regardless of the _UNICODE setting */
  39976. { "GetProcAddressA", (SYSCALL)GetProcAddress, 0 },
  39977. #endif
  39978. #else
  39979. { "GetProcAddressA", (SYSCALL)0, 0 },
  39980. #endif
  39981. #define osGetProcAddressA ((FARPROC(WINAPI*)(HMODULE, \
  39982. LPCSTR))aSyscall[27].pCurrent)
  39983. #if !SQLITE_OS_WINRT
  39984. { "GetSystemInfo", (SYSCALL)GetSystemInfo, 0 },
  39985. #else
  39986. { "GetSystemInfo", (SYSCALL)0, 0 },
  39987. #endif
  39988. #define osGetSystemInfo ((VOID(WINAPI*)(LPSYSTEM_INFO))aSyscall[28].pCurrent)
  39989. { "GetSystemTime", (SYSCALL)GetSystemTime, 0 },
  39990. #define osGetSystemTime ((VOID(WINAPI*)(LPSYSTEMTIME))aSyscall[29].pCurrent)
  39991. #if !SQLITE_OS_WINCE
  39992. { "GetSystemTimeAsFileTime", (SYSCALL)GetSystemTimeAsFileTime, 0 },
  39993. #else
  39994. { "GetSystemTimeAsFileTime", (SYSCALL)0, 0 },
  39995. #endif
  39996. #define osGetSystemTimeAsFileTime ((VOID(WINAPI*)( \
  39997. LPFILETIME))aSyscall[30].pCurrent)
  39998. #if defined(SQLITE_WIN32_HAS_ANSI)
  39999. { "GetTempPathA", (SYSCALL)GetTempPathA, 0 },
  40000. #else
  40001. { "GetTempPathA", (SYSCALL)0, 0 },
  40002. #endif
  40003. #define osGetTempPathA ((DWORD(WINAPI*)(DWORD,LPSTR))aSyscall[31].pCurrent)
  40004. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  40005. { "GetTempPathW", (SYSCALL)GetTempPathW, 0 },
  40006. #else
  40007. { "GetTempPathW", (SYSCALL)0, 0 },
  40008. #endif
  40009. #define osGetTempPathW ((DWORD(WINAPI*)(DWORD,LPWSTR))aSyscall[32].pCurrent)
  40010. #if !SQLITE_OS_WINRT
  40011. { "GetTickCount", (SYSCALL)GetTickCount, 0 },
  40012. #else
  40013. { "GetTickCount", (SYSCALL)0, 0 },
  40014. #endif
  40015. #define osGetTickCount ((DWORD(WINAPI*)(VOID))aSyscall[33].pCurrent)
  40016. #if defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_GETVERSIONEX
  40017. { "GetVersionExA", (SYSCALL)GetVersionExA, 0 },
  40018. #else
  40019. { "GetVersionExA", (SYSCALL)0, 0 },
  40020. #endif
  40021. #define osGetVersionExA ((BOOL(WINAPI*)( \
  40022. LPOSVERSIONINFOA))aSyscall[34].pCurrent)
  40023. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
  40024. SQLITE_WIN32_GETVERSIONEX
  40025. { "GetVersionExW", (SYSCALL)GetVersionExW, 0 },
  40026. #else
  40027. { "GetVersionExW", (SYSCALL)0, 0 },
  40028. #endif
  40029. #define osGetVersionExW ((BOOL(WINAPI*)( \
  40030. LPOSVERSIONINFOW))aSyscall[35].pCurrent)
  40031. { "HeapAlloc", (SYSCALL)HeapAlloc, 0 },
  40032. #define osHeapAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD, \
  40033. SIZE_T))aSyscall[36].pCurrent)
  40034. #if !SQLITE_OS_WINRT
  40035. { "HeapCreate", (SYSCALL)HeapCreate, 0 },
  40036. #else
  40037. { "HeapCreate", (SYSCALL)0, 0 },
  40038. #endif
  40039. #define osHeapCreate ((HANDLE(WINAPI*)(DWORD,SIZE_T, \
  40040. SIZE_T))aSyscall[37].pCurrent)
  40041. #if !SQLITE_OS_WINRT
  40042. { "HeapDestroy", (SYSCALL)HeapDestroy, 0 },
  40043. #else
  40044. { "HeapDestroy", (SYSCALL)0, 0 },
  40045. #endif
  40046. #define osHeapDestroy ((BOOL(WINAPI*)(HANDLE))aSyscall[38].pCurrent)
  40047. { "HeapFree", (SYSCALL)HeapFree, 0 },
  40048. #define osHeapFree ((BOOL(WINAPI*)(HANDLE,DWORD,LPVOID))aSyscall[39].pCurrent)
  40049. { "HeapReAlloc", (SYSCALL)HeapReAlloc, 0 },
  40050. #define osHeapReAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD,LPVOID, \
  40051. SIZE_T))aSyscall[40].pCurrent)
  40052. { "HeapSize", (SYSCALL)HeapSize, 0 },
  40053. #define osHeapSize ((SIZE_T(WINAPI*)(HANDLE,DWORD, \
  40054. LPCVOID))aSyscall[41].pCurrent)
  40055. #if !SQLITE_OS_WINRT
  40056. { "HeapValidate", (SYSCALL)HeapValidate, 0 },
  40057. #else
  40058. { "HeapValidate", (SYSCALL)0, 0 },
  40059. #endif
  40060. #define osHeapValidate ((BOOL(WINAPI*)(HANDLE,DWORD, \
  40061. LPCVOID))aSyscall[42].pCurrent)
  40062. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  40063. { "HeapCompact", (SYSCALL)HeapCompact, 0 },
  40064. #else
  40065. { "HeapCompact", (SYSCALL)0, 0 },
  40066. #endif
  40067. #define osHeapCompact ((UINT(WINAPI*)(HANDLE,DWORD))aSyscall[43].pCurrent)
  40068. #if defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
  40069. { "LoadLibraryA", (SYSCALL)LoadLibraryA, 0 },
  40070. #else
  40071. { "LoadLibraryA", (SYSCALL)0, 0 },
  40072. #endif
  40073. #define osLoadLibraryA ((HMODULE(WINAPI*)(LPCSTR))aSyscall[44].pCurrent)
  40074. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
  40075. !defined(SQLITE_OMIT_LOAD_EXTENSION)
  40076. { "LoadLibraryW", (SYSCALL)LoadLibraryW, 0 },
  40077. #else
  40078. { "LoadLibraryW", (SYSCALL)0, 0 },
  40079. #endif
  40080. #define osLoadLibraryW ((HMODULE(WINAPI*)(LPCWSTR))aSyscall[45].pCurrent)
  40081. #if !SQLITE_OS_WINRT
  40082. { "LocalFree", (SYSCALL)LocalFree, 0 },
  40083. #else
  40084. { "LocalFree", (SYSCALL)0, 0 },
  40085. #endif
  40086. #define osLocalFree ((HLOCAL(WINAPI*)(HLOCAL))aSyscall[46].pCurrent)
  40087. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  40088. { "LockFile", (SYSCALL)LockFile, 0 },
  40089. #else
  40090. { "LockFile", (SYSCALL)0, 0 },
  40091. #endif
  40092. #ifndef osLockFile
  40093. #define osLockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
  40094. DWORD))aSyscall[47].pCurrent)
  40095. #endif
  40096. #if !SQLITE_OS_WINCE
  40097. { "LockFileEx", (SYSCALL)LockFileEx, 0 },
  40098. #else
  40099. { "LockFileEx", (SYSCALL)0, 0 },
  40100. #endif
  40101. #ifndef osLockFileEx
  40102. #define osLockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD,DWORD, \
  40103. LPOVERLAPPED))aSyscall[48].pCurrent)
  40104. #endif
  40105. #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && \
  40106. (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0))
  40107. { "MapViewOfFile", (SYSCALL)MapViewOfFile, 0 },
  40108. #else
  40109. { "MapViewOfFile", (SYSCALL)0, 0 },
  40110. #endif
  40111. #define osMapViewOfFile ((LPVOID(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
  40112. SIZE_T))aSyscall[49].pCurrent)
  40113. { "MultiByteToWideChar", (SYSCALL)MultiByteToWideChar, 0 },
  40114. #define osMultiByteToWideChar ((int(WINAPI*)(UINT,DWORD,LPCSTR,int,LPWSTR, \
  40115. int))aSyscall[50].pCurrent)
  40116. { "QueryPerformanceCounter", (SYSCALL)QueryPerformanceCounter, 0 },
  40117. #define osQueryPerformanceCounter ((BOOL(WINAPI*)( \
  40118. LARGE_INTEGER*))aSyscall[51].pCurrent)
  40119. { "ReadFile", (SYSCALL)ReadFile, 0 },
  40120. #define osReadFile ((BOOL(WINAPI*)(HANDLE,LPVOID,DWORD,LPDWORD, \
  40121. LPOVERLAPPED))aSyscall[52].pCurrent)
  40122. { "SetEndOfFile", (SYSCALL)SetEndOfFile, 0 },
  40123. #define osSetEndOfFile ((BOOL(WINAPI*)(HANDLE))aSyscall[53].pCurrent)
  40124. #if !SQLITE_OS_WINRT
  40125. { "SetFilePointer", (SYSCALL)SetFilePointer, 0 },
  40126. #else
  40127. { "SetFilePointer", (SYSCALL)0, 0 },
  40128. #endif
  40129. #define osSetFilePointer ((DWORD(WINAPI*)(HANDLE,LONG,PLONG, \
  40130. DWORD))aSyscall[54].pCurrent)
  40131. #if !SQLITE_OS_WINRT
  40132. { "Sleep", (SYSCALL)Sleep, 0 },
  40133. #else
  40134. { "Sleep", (SYSCALL)0, 0 },
  40135. #endif
  40136. #define osSleep ((VOID(WINAPI*)(DWORD))aSyscall[55].pCurrent)
  40137. { "SystemTimeToFileTime", (SYSCALL)SystemTimeToFileTime, 0 },
  40138. #define osSystemTimeToFileTime ((BOOL(WINAPI*)(CONST SYSTEMTIME*, \
  40139. LPFILETIME))aSyscall[56].pCurrent)
  40140. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  40141. { "UnlockFile", (SYSCALL)UnlockFile, 0 },
  40142. #else
  40143. { "UnlockFile", (SYSCALL)0, 0 },
  40144. #endif
  40145. #ifndef osUnlockFile
  40146. #define osUnlockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
  40147. DWORD))aSyscall[57].pCurrent)
  40148. #endif
  40149. #if !SQLITE_OS_WINCE
  40150. { "UnlockFileEx", (SYSCALL)UnlockFileEx, 0 },
  40151. #else
  40152. { "UnlockFileEx", (SYSCALL)0, 0 },
  40153. #endif
  40154. #define osUnlockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
  40155. LPOVERLAPPED))aSyscall[58].pCurrent)
  40156. #if SQLITE_OS_WINCE || !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
  40157. { "UnmapViewOfFile", (SYSCALL)UnmapViewOfFile, 0 },
  40158. #else
  40159. { "UnmapViewOfFile", (SYSCALL)0, 0 },
  40160. #endif
  40161. #define osUnmapViewOfFile ((BOOL(WINAPI*)(LPCVOID))aSyscall[59].pCurrent)
  40162. { "WideCharToMultiByte", (SYSCALL)WideCharToMultiByte, 0 },
  40163. #define osWideCharToMultiByte ((int(WINAPI*)(UINT,DWORD,LPCWSTR,int,LPSTR,int, \
  40164. LPCSTR,LPBOOL))aSyscall[60].pCurrent)
  40165. { "WriteFile", (SYSCALL)WriteFile, 0 },
  40166. #define osWriteFile ((BOOL(WINAPI*)(HANDLE,LPCVOID,DWORD,LPDWORD, \
  40167. LPOVERLAPPED))aSyscall[61].pCurrent)
  40168. #if SQLITE_OS_WINRT
  40169. { "CreateEventExW", (SYSCALL)CreateEventExW, 0 },
  40170. #else
  40171. { "CreateEventExW", (SYSCALL)0, 0 },
  40172. #endif
  40173. #define osCreateEventExW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,LPCWSTR, \
  40174. DWORD,DWORD))aSyscall[62].pCurrent)
  40175. #if !SQLITE_OS_WINRT
  40176. { "WaitForSingleObject", (SYSCALL)WaitForSingleObject, 0 },
  40177. #else
  40178. { "WaitForSingleObject", (SYSCALL)0, 0 },
  40179. #endif
  40180. #define osWaitForSingleObject ((DWORD(WINAPI*)(HANDLE, \
  40181. DWORD))aSyscall[63].pCurrent)
  40182. #if !SQLITE_OS_WINCE
  40183. { "WaitForSingleObjectEx", (SYSCALL)WaitForSingleObjectEx, 0 },
  40184. #else
  40185. { "WaitForSingleObjectEx", (SYSCALL)0, 0 },
  40186. #endif
  40187. #define osWaitForSingleObjectEx ((DWORD(WINAPI*)(HANDLE,DWORD, \
  40188. BOOL))aSyscall[64].pCurrent)
  40189. #if SQLITE_OS_WINRT
  40190. { "SetFilePointerEx", (SYSCALL)SetFilePointerEx, 0 },
  40191. #else
  40192. { "SetFilePointerEx", (SYSCALL)0, 0 },
  40193. #endif
  40194. #define osSetFilePointerEx ((BOOL(WINAPI*)(HANDLE,LARGE_INTEGER, \
  40195. PLARGE_INTEGER,DWORD))aSyscall[65].pCurrent)
  40196. #if SQLITE_OS_WINRT
  40197. { "GetFileInformationByHandleEx", (SYSCALL)GetFileInformationByHandleEx, 0 },
  40198. #else
  40199. { "GetFileInformationByHandleEx", (SYSCALL)0, 0 },
  40200. #endif
  40201. #define osGetFileInformationByHandleEx ((BOOL(WINAPI*)(HANDLE, \
  40202. FILE_INFO_BY_HANDLE_CLASS,LPVOID,DWORD))aSyscall[66].pCurrent)
  40203. #if SQLITE_OS_WINRT && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
  40204. { "MapViewOfFileFromApp", (SYSCALL)MapViewOfFileFromApp, 0 },
  40205. #else
  40206. { "MapViewOfFileFromApp", (SYSCALL)0, 0 },
  40207. #endif
  40208. #define osMapViewOfFileFromApp ((LPVOID(WINAPI*)(HANDLE,ULONG,ULONG64, \
  40209. SIZE_T))aSyscall[67].pCurrent)
  40210. #if SQLITE_OS_WINRT
  40211. { "CreateFile2", (SYSCALL)CreateFile2, 0 },
  40212. #else
  40213. { "CreateFile2", (SYSCALL)0, 0 },
  40214. #endif
  40215. #define osCreateFile2 ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD,DWORD, \
  40216. LPCREATEFILE2_EXTENDED_PARAMETERS))aSyscall[68].pCurrent)
  40217. #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_LOAD_EXTENSION)
  40218. { "LoadPackagedLibrary", (SYSCALL)LoadPackagedLibrary, 0 },
  40219. #else
  40220. { "LoadPackagedLibrary", (SYSCALL)0, 0 },
  40221. #endif
  40222. #define osLoadPackagedLibrary ((HMODULE(WINAPI*)(LPCWSTR, \
  40223. DWORD))aSyscall[69].pCurrent)
  40224. #if SQLITE_OS_WINRT
  40225. { "GetTickCount64", (SYSCALL)GetTickCount64, 0 },
  40226. #else
  40227. { "GetTickCount64", (SYSCALL)0, 0 },
  40228. #endif
  40229. #define osGetTickCount64 ((ULONGLONG(WINAPI*)(VOID))aSyscall[70].pCurrent)
  40230. #if SQLITE_OS_WINRT
  40231. { "GetNativeSystemInfo", (SYSCALL)GetNativeSystemInfo, 0 },
  40232. #else
  40233. { "GetNativeSystemInfo", (SYSCALL)0, 0 },
  40234. #endif
  40235. #define osGetNativeSystemInfo ((VOID(WINAPI*)( \
  40236. LPSYSTEM_INFO))aSyscall[71].pCurrent)
  40237. #if defined(SQLITE_WIN32_HAS_ANSI)
  40238. { "OutputDebugStringA", (SYSCALL)OutputDebugStringA, 0 },
  40239. #else
  40240. { "OutputDebugStringA", (SYSCALL)0, 0 },
  40241. #endif
  40242. #define osOutputDebugStringA ((VOID(WINAPI*)(LPCSTR))aSyscall[72].pCurrent)
  40243. #if defined(SQLITE_WIN32_HAS_WIDE)
  40244. { "OutputDebugStringW", (SYSCALL)OutputDebugStringW, 0 },
  40245. #else
  40246. { "OutputDebugStringW", (SYSCALL)0, 0 },
  40247. #endif
  40248. #define osOutputDebugStringW ((VOID(WINAPI*)(LPCWSTR))aSyscall[73].pCurrent)
  40249. { "GetProcessHeap", (SYSCALL)GetProcessHeap, 0 },
  40250. #define osGetProcessHeap ((HANDLE(WINAPI*)(VOID))aSyscall[74].pCurrent)
  40251. #if SQLITE_OS_WINRT && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
  40252. { "CreateFileMappingFromApp", (SYSCALL)CreateFileMappingFromApp, 0 },
  40253. #else
  40254. { "CreateFileMappingFromApp", (SYSCALL)0, 0 },
  40255. #endif
  40256. #define osCreateFileMappingFromApp ((HANDLE(WINAPI*)(HANDLE, \
  40257. LPSECURITY_ATTRIBUTES,ULONG,ULONG64,LPCWSTR))aSyscall[75].pCurrent)
  40258. /*
  40259. ** NOTE: On some sub-platforms, the InterlockedCompareExchange "function"
  40260. ** is really just a macro that uses a compiler intrinsic (e.g. x64).
  40261. ** So do not try to make this is into a redefinable interface.
  40262. */
  40263. #if defined(InterlockedCompareExchange)
  40264. { "InterlockedCompareExchange", (SYSCALL)0, 0 },
  40265. #define osInterlockedCompareExchange InterlockedCompareExchange
  40266. #else
  40267. { "InterlockedCompareExchange", (SYSCALL)InterlockedCompareExchange, 0 },
  40268. #define osInterlockedCompareExchange ((LONG(WINAPI*)(LONG \
  40269. SQLITE_WIN32_VOLATILE*, LONG,LONG))aSyscall[76].pCurrent)
  40270. #endif /* defined(InterlockedCompareExchange) */
  40271. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
  40272. { "UuidCreate", (SYSCALL)UuidCreate, 0 },
  40273. #else
  40274. { "UuidCreate", (SYSCALL)0, 0 },
  40275. #endif
  40276. #define osUuidCreate ((RPC_STATUS(RPC_ENTRY*)(UUID*))aSyscall[77].pCurrent)
  40277. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
  40278. { "UuidCreateSequential", (SYSCALL)UuidCreateSequential, 0 },
  40279. #else
  40280. { "UuidCreateSequential", (SYSCALL)0, 0 },
  40281. #endif
  40282. #define osUuidCreateSequential \
  40283. ((RPC_STATUS(RPC_ENTRY*)(UUID*))aSyscall[78].pCurrent)
  40284. #if !defined(SQLITE_NO_SYNC) && SQLITE_MAX_MMAP_SIZE>0
  40285. { "FlushViewOfFile", (SYSCALL)FlushViewOfFile, 0 },
  40286. #else
  40287. { "FlushViewOfFile", (SYSCALL)0, 0 },
  40288. #endif
  40289. #define osFlushViewOfFile \
  40290. ((BOOL(WINAPI*)(LPCVOID,SIZE_T))aSyscall[79].pCurrent)
  40291. }; /* End of the overrideable system calls */
  40292. /*
  40293. ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
  40294. ** "win32" VFSes. Return SQLITE_OK opon successfully updating the
  40295. ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
  40296. ** system call named zName.
  40297. */
  40298. static int winSetSystemCall(
  40299. sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
  40300. const char *zName, /* Name of system call to override */
  40301. sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
  40302. ){
  40303. unsigned int i;
  40304. int rc = SQLITE_NOTFOUND;
  40305. UNUSED_PARAMETER(pNotUsed);
  40306. if( zName==0 ){
  40307. /* If no zName is given, restore all system calls to their default
  40308. ** settings and return NULL
  40309. */
  40310. rc = SQLITE_OK;
  40311. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  40312. if( aSyscall[i].pDefault ){
  40313. aSyscall[i].pCurrent = aSyscall[i].pDefault;
  40314. }
  40315. }
  40316. }else{
  40317. /* If zName is specified, operate on only the one system call
  40318. ** specified.
  40319. */
  40320. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  40321. if( strcmp(zName, aSyscall[i].zName)==0 ){
  40322. if( aSyscall[i].pDefault==0 ){
  40323. aSyscall[i].pDefault = aSyscall[i].pCurrent;
  40324. }
  40325. rc = SQLITE_OK;
  40326. if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
  40327. aSyscall[i].pCurrent = pNewFunc;
  40328. break;
  40329. }
  40330. }
  40331. }
  40332. return rc;
  40333. }
  40334. /*
  40335. ** Return the value of a system call. Return NULL if zName is not a
  40336. ** recognized system call name. NULL is also returned if the system call
  40337. ** is currently undefined.
  40338. */
  40339. static sqlite3_syscall_ptr winGetSystemCall(
  40340. sqlite3_vfs *pNotUsed,
  40341. const char *zName
  40342. ){
  40343. unsigned int i;
  40344. UNUSED_PARAMETER(pNotUsed);
  40345. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  40346. if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
  40347. }
  40348. return 0;
  40349. }
  40350. /*
  40351. ** Return the name of the first system call after zName. If zName==NULL
  40352. ** then return the name of the first system call. Return NULL if zName
  40353. ** is the last system call or if zName is not the name of a valid
  40354. ** system call.
  40355. */
  40356. static const char *winNextSystemCall(sqlite3_vfs *p, const char *zName){
  40357. int i = -1;
  40358. UNUSED_PARAMETER(p);
  40359. if( zName ){
  40360. for(i=0; i<ArraySize(aSyscall)-1; i++){
  40361. if( strcmp(zName, aSyscall[i].zName)==0 ) break;
  40362. }
  40363. }
  40364. for(i++; i<ArraySize(aSyscall); i++){
  40365. if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
  40366. }
  40367. return 0;
  40368. }
  40369. #ifdef SQLITE_WIN32_MALLOC
  40370. /*
  40371. ** If a Win32 native heap has been configured, this function will attempt to
  40372. ** compact it. Upon success, SQLITE_OK will be returned. Upon failure, one
  40373. ** of SQLITE_NOMEM, SQLITE_ERROR, or SQLITE_NOTFOUND will be returned. The
  40374. ** "pnLargest" argument, if non-zero, will be used to return the size of the
  40375. ** largest committed free block in the heap, in bytes.
  40376. */
  40377. SQLITE_API int sqlite3_win32_compact_heap(LPUINT pnLargest){
  40378. int rc = SQLITE_OK;
  40379. UINT nLargest = 0;
  40380. HANDLE hHeap;
  40381. winMemAssertMagic();
  40382. hHeap = winMemGetHeap();
  40383. assert( hHeap!=0 );
  40384. assert( hHeap!=INVALID_HANDLE_VALUE );
  40385. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  40386. assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
  40387. #endif
  40388. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  40389. if( (nLargest=osHeapCompact(hHeap, SQLITE_WIN32_HEAP_FLAGS))==0 ){
  40390. DWORD lastErrno = osGetLastError();
  40391. if( lastErrno==NO_ERROR ){
  40392. sqlite3_log(SQLITE_NOMEM, "failed to HeapCompact (no space), heap=%p",
  40393. (void*)hHeap);
  40394. rc = SQLITE_NOMEM_BKPT;
  40395. }else{
  40396. sqlite3_log(SQLITE_ERROR, "failed to HeapCompact (%lu), heap=%p",
  40397. osGetLastError(), (void*)hHeap);
  40398. rc = SQLITE_ERROR;
  40399. }
  40400. }
  40401. #else
  40402. sqlite3_log(SQLITE_NOTFOUND, "failed to HeapCompact, heap=%p",
  40403. (void*)hHeap);
  40404. rc = SQLITE_NOTFOUND;
  40405. #endif
  40406. if( pnLargest ) *pnLargest = nLargest;
  40407. return rc;
  40408. }
  40409. /*
  40410. ** If a Win32 native heap has been configured, this function will attempt to
  40411. ** destroy and recreate it. If the Win32 native heap is not isolated and/or
  40412. ** the sqlite3_memory_used() function does not return zero, SQLITE_BUSY will
  40413. ** be returned and no changes will be made to the Win32 native heap.
  40414. */
  40415. SQLITE_API int sqlite3_win32_reset_heap(){
  40416. int rc;
  40417. MUTEX_LOGIC( sqlite3_mutex *pMaster; ) /* The main static mutex */
  40418. MUTEX_LOGIC( sqlite3_mutex *pMem; ) /* The memsys static mutex */
  40419. MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
  40420. MUTEX_LOGIC( pMem = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM); )
  40421. sqlite3_mutex_enter(pMaster);
  40422. sqlite3_mutex_enter(pMem);
  40423. winMemAssertMagic();
  40424. if( winMemGetHeap()!=NULL && winMemGetOwned() && sqlite3_memory_used()==0 ){
  40425. /*
  40426. ** At this point, there should be no outstanding memory allocations on
  40427. ** the heap. Also, since both the master and memsys locks are currently
  40428. ** being held by us, no other function (i.e. from another thread) should
  40429. ** be able to even access the heap. Attempt to destroy and recreate our
  40430. ** isolated Win32 native heap now.
  40431. */
  40432. assert( winMemGetHeap()!=NULL );
  40433. assert( winMemGetOwned() );
  40434. assert( sqlite3_memory_used()==0 );
  40435. winMemShutdown(winMemGetDataPtr());
  40436. assert( winMemGetHeap()==NULL );
  40437. assert( !winMemGetOwned() );
  40438. assert( sqlite3_memory_used()==0 );
  40439. rc = winMemInit(winMemGetDataPtr());
  40440. assert( rc!=SQLITE_OK || winMemGetHeap()!=NULL );
  40441. assert( rc!=SQLITE_OK || winMemGetOwned() );
  40442. assert( rc!=SQLITE_OK || sqlite3_memory_used()==0 );
  40443. }else{
  40444. /*
  40445. ** The Win32 native heap cannot be modified because it may be in use.
  40446. */
  40447. rc = SQLITE_BUSY;
  40448. }
  40449. sqlite3_mutex_leave(pMem);
  40450. sqlite3_mutex_leave(pMaster);
  40451. return rc;
  40452. }
  40453. #endif /* SQLITE_WIN32_MALLOC */
  40454. /*
  40455. ** This function outputs the specified (ANSI) string to the Win32 debugger
  40456. ** (if available).
  40457. */
  40458. SQLITE_API void sqlite3_win32_write_debug(const char *zBuf, int nBuf){
  40459. char zDbgBuf[SQLITE_WIN32_DBG_BUF_SIZE];
  40460. int nMin = MIN(nBuf, (SQLITE_WIN32_DBG_BUF_SIZE - 1)); /* may be negative. */
  40461. if( nMin<-1 ) nMin = -1; /* all negative values become -1. */
  40462. assert( nMin==-1 || nMin==0 || nMin<SQLITE_WIN32_DBG_BUF_SIZE );
  40463. #ifdef SQLITE_ENABLE_API_ARMOR
  40464. if( !zBuf ){
  40465. (void)SQLITE_MISUSE_BKPT;
  40466. return;
  40467. }
  40468. #endif
  40469. #if defined(SQLITE_WIN32_HAS_ANSI)
  40470. if( nMin>0 ){
  40471. memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
  40472. memcpy(zDbgBuf, zBuf, nMin);
  40473. osOutputDebugStringA(zDbgBuf);
  40474. }else{
  40475. osOutputDebugStringA(zBuf);
  40476. }
  40477. #elif defined(SQLITE_WIN32_HAS_WIDE)
  40478. memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
  40479. if ( osMultiByteToWideChar(
  40480. osAreFileApisANSI() ? CP_ACP : CP_OEMCP, 0, zBuf,
  40481. nMin, (LPWSTR)zDbgBuf, SQLITE_WIN32_DBG_BUF_SIZE/sizeof(WCHAR))<=0 ){
  40482. return;
  40483. }
  40484. osOutputDebugStringW((LPCWSTR)zDbgBuf);
  40485. #else
  40486. if( nMin>0 ){
  40487. memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
  40488. memcpy(zDbgBuf, zBuf, nMin);
  40489. fprintf(stderr, "%s", zDbgBuf);
  40490. }else{
  40491. fprintf(stderr, "%s", zBuf);
  40492. }
  40493. #endif
  40494. }
  40495. /*
  40496. ** The following routine suspends the current thread for at least ms
  40497. ** milliseconds. This is equivalent to the Win32 Sleep() interface.
  40498. */
  40499. #if SQLITE_OS_WINRT
  40500. static HANDLE sleepObj = NULL;
  40501. #endif
  40502. SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds){
  40503. #if SQLITE_OS_WINRT
  40504. if ( sleepObj==NULL ){
  40505. sleepObj = osCreateEventExW(NULL, NULL, CREATE_EVENT_MANUAL_RESET,
  40506. SYNCHRONIZE);
  40507. }
  40508. assert( sleepObj!=NULL );
  40509. osWaitForSingleObjectEx(sleepObj, milliseconds, FALSE);
  40510. #else
  40511. osSleep(milliseconds);
  40512. #endif
  40513. }
  40514. #if SQLITE_MAX_WORKER_THREADS>0 && !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && \
  40515. SQLITE_THREADSAFE>0
  40516. SQLITE_PRIVATE DWORD sqlite3Win32Wait(HANDLE hObject){
  40517. DWORD rc;
  40518. while( (rc = osWaitForSingleObjectEx(hObject, INFINITE,
  40519. TRUE))==WAIT_IO_COMPLETION ){}
  40520. return rc;
  40521. }
  40522. #endif
  40523. /*
  40524. ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
  40525. ** or WinCE. Return false (zero) for Win95, Win98, or WinME.
  40526. **
  40527. ** Here is an interesting observation: Win95, Win98, and WinME lack
  40528. ** the LockFileEx() API. But we can still statically link against that
  40529. ** API as long as we don't call it when running Win95/98/ME. A call to
  40530. ** this routine is used to determine if the host is Win95/98/ME or
  40531. ** WinNT/2K/XP so that we will know whether or not we can safely call
  40532. ** the LockFileEx() API.
  40533. */
  40534. #if !SQLITE_WIN32_GETVERSIONEX
  40535. # define osIsNT() (1)
  40536. #elif SQLITE_OS_WINCE || SQLITE_OS_WINRT || !defined(SQLITE_WIN32_HAS_ANSI)
  40537. # define osIsNT() (1)
  40538. #elif !defined(SQLITE_WIN32_HAS_WIDE)
  40539. # define osIsNT() (0)
  40540. #else
  40541. # define osIsNT() ((sqlite3_os_type==2) || sqlite3_win32_is_nt())
  40542. #endif
  40543. /*
  40544. ** This function determines if the machine is running a version of Windows
  40545. ** based on the NT kernel.
  40546. */
  40547. SQLITE_API int sqlite3_win32_is_nt(void){
  40548. #if SQLITE_OS_WINRT
  40549. /*
  40550. ** NOTE: The WinRT sub-platform is always assumed to be based on the NT
  40551. ** kernel.
  40552. */
  40553. return 1;
  40554. #elif SQLITE_WIN32_GETVERSIONEX
  40555. if( osInterlockedCompareExchange(&sqlite3_os_type, 0, 0)==0 ){
  40556. #if defined(SQLITE_WIN32_HAS_ANSI)
  40557. OSVERSIONINFOA sInfo;
  40558. sInfo.dwOSVersionInfoSize = sizeof(sInfo);
  40559. osGetVersionExA(&sInfo);
  40560. osInterlockedCompareExchange(&sqlite3_os_type,
  40561. (sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) ? 2 : 1, 0);
  40562. #elif defined(SQLITE_WIN32_HAS_WIDE)
  40563. OSVERSIONINFOW sInfo;
  40564. sInfo.dwOSVersionInfoSize = sizeof(sInfo);
  40565. osGetVersionExW(&sInfo);
  40566. osInterlockedCompareExchange(&sqlite3_os_type,
  40567. (sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) ? 2 : 1, 0);
  40568. #endif
  40569. }
  40570. return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2;
  40571. #elif SQLITE_TEST
  40572. return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2;
  40573. #else
  40574. /*
  40575. ** NOTE: All sub-platforms where the GetVersionEx[AW] functions are
  40576. ** deprecated are always assumed to be based on the NT kernel.
  40577. */
  40578. return 1;
  40579. #endif
  40580. }
  40581. #ifdef SQLITE_WIN32_MALLOC
  40582. /*
  40583. ** Allocate nBytes of memory.
  40584. */
  40585. static void *winMemMalloc(int nBytes){
  40586. HANDLE hHeap;
  40587. void *p;
  40588. winMemAssertMagic();
  40589. hHeap = winMemGetHeap();
  40590. assert( hHeap!=0 );
  40591. assert( hHeap!=INVALID_HANDLE_VALUE );
  40592. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  40593. assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
  40594. #endif
  40595. assert( nBytes>=0 );
  40596. p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
  40597. if( !p ){
  40598. sqlite3_log(SQLITE_NOMEM, "failed to HeapAlloc %u bytes (%lu), heap=%p",
  40599. nBytes, osGetLastError(), (void*)hHeap);
  40600. }
  40601. return p;
  40602. }
  40603. /*
  40604. ** Free memory.
  40605. */
  40606. static void winMemFree(void *pPrior){
  40607. HANDLE hHeap;
  40608. winMemAssertMagic();
  40609. hHeap = winMemGetHeap();
  40610. assert( hHeap!=0 );
  40611. assert( hHeap!=INVALID_HANDLE_VALUE );
  40612. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  40613. assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
  40614. #endif
  40615. if( !pPrior ) return; /* Passing NULL to HeapFree is undefined. */
  40616. if( !osHeapFree(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) ){
  40617. sqlite3_log(SQLITE_NOMEM, "failed to HeapFree block %p (%lu), heap=%p",
  40618. pPrior, osGetLastError(), (void*)hHeap);
  40619. }
  40620. }
  40621. /*
  40622. ** Change the size of an existing memory allocation
  40623. */
  40624. static void *winMemRealloc(void *pPrior, int nBytes){
  40625. HANDLE hHeap;
  40626. void *p;
  40627. winMemAssertMagic();
  40628. hHeap = winMemGetHeap();
  40629. assert( hHeap!=0 );
  40630. assert( hHeap!=INVALID_HANDLE_VALUE );
  40631. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  40632. assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
  40633. #endif
  40634. assert( nBytes>=0 );
  40635. if( !pPrior ){
  40636. p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
  40637. }else{
  40638. p = osHeapReAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior, (SIZE_T)nBytes);
  40639. }
  40640. if( !p ){
  40641. sqlite3_log(SQLITE_NOMEM, "failed to %s %u bytes (%lu), heap=%p",
  40642. pPrior ? "HeapReAlloc" : "HeapAlloc", nBytes, osGetLastError(),
  40643. (void*)hHeap);
  40644. }
  40645. return p;
  40646. }
  40647. /*
  40648. ** Return the size of an outstanding allocation, in bytes.
  40649. */
  40650. static int winMemSize(void *p){
  40651. HANDLE hHeap;
  40652. SIZE_T n;
  40653. winMemAssertMagic();
  40654. hHeap = winMemGetHeap();
  40655. assert( hHeap!=0 );
  40656. assert( hHeap!=INVALID_HANDLE_VALUE );
  40657. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  40658. assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, p) );
  40659. #endif
  40660. if( !p ) return 0;
  40661. n = osHeapSize(hHeap, SQLITE_WIN32_HEAP_FLAGS, p);
  40662. if( n==(SIZE_T)-1 ){
  40663. sqlite3_log(SQLITE_NOMEM, "failed to HeapSize block %p (%lu), heap=%p",
  40664. p, osGetLastError(), (void*)hHeap);
  40665. return 0;
  40666. }
  40667. return (int)n;
  40668. }
  40669. /*
  40670. ** Round up a request size to the next valid allocation size.
  40671. */
  40672. static int winMemRoundup(int n){
  40673. return n;
  40674. }
  40675. /*
  40676. ** Initialize this module.
  40677. */
  40678. static int winMemInit(void *pAppData){
  40679. winMemData *pWinMemData = (winMemData *)pAppData;
  40680. if( !pWinMemData ) return SQLITE_ERROR;
  40681. assert( pWinMemData->magic1==WINMEM_MAGIC1 );
  40682. assert( pWinMemData->magic2==WINMEM_MAGIC2 );
  40683. #if !SQLITE_OS_WINRT && SQLITE_WIN32_HEAP_CREATE
  40684. if( !pWinMemData->hHeap ){
  40685. DWORD dwInitialSize = SQLITE_WIN32_HEAP_INIT_SIZE;
  40686. DWORD dwMaximumSize = (DWORD)sqlite3GlobalConfig.nHeap;
  40687. if( dwMaximumSize==0 ){
  40688. dwMaximumSize = SQLITE_WIN32_HEAP_MAX_SIZE;
  40689. }else if( dwInitialSize>dwMaximumSize ){
  40690. dwInitialSize = dwMaximumSize;
  40691. }
  40692. pWinMemData->hHeap = osHeapCreate(SQLITE_WIN32_HEAP_FLAGS,
  40693. dwInitialSize, dwMaximumSize);
  40694. if( !pWinMemData->hHeap ){
  40695. sqlite3_log(SQLITE_NOMEM,
  40696. "failed to HeapCreate (%lu), flags=%u, initSize=%lu, maxSize=%lu",
  40697. osGetLastError(), SQLITE_WIN32_HEAP_FLAGS, dwInitialSize,
  40698. dwMaximumSize);
  40699. return SQLITE_NOMEM_BKPT;
  40700. }
  40701. pWinMemData->bOwned = TRUE;
  40702. assert( pWinMemData->bOwned );
  40703. }
  40704. #else
  40705. pWinMemData->hHeap = osGetProcessHeap();
  40706. if( !pWinMemData->hHeap ){
  40707. sqlite3_log(SQLITE_NOMEM,
  40708. "failed to GetProcessHeap (%lu)", osGetLastError());
  40709. return SQLITE_NOMEM_BKPT;
  40710. }
  40711. pWinMemData->bOwned = FALSE;
  40712. assert( !pWinMemData->bOwned );
  40713. #endif
  40714. assert( pWinMemData->hHeap!=0 );
  40715. assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
  40716. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  40717. assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
  40718. #endif
  40719. return SQLITE_OK;
  40720. }
  40721. /*
  40722. ** Deinitialize this module.
  40723. */
  40724. static void winMemShutdown(void *pAppData){
  40725. winMemData *pWinMemData = (winMemData *)pAppData;
  40726. if( !pWinMemData ) return;
  40727. assert( pWinMemData->magic1==WINMEM_MAGIC1 );
  40728. assert( pWinMemData->magic2==WINMEM_MAGIC2 );
  40729. if( pWinMemData->hHeap ){
  40730. assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
  40731. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  40732. assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
  40733. #endif
  40734. if( pWinMemData->bOwned ){
  40735. if( !osHeapDestroy(pWinMemData->hHeap) ){
  40736. sqlite3_log(SQLITE_NOMEM, "failed to HeapDestroy (%lu), heap=%p",
  40737. osGetLastError(), (void*)pWinMemData->hHeap);
  40738. }
  40739. pWinMemData->bOwned = FALSE;
  40740. }
  40741. pWinMemData->hHeap = NULL;
  40742. }
  40743. }
  40744. /*
  40745. ** Populate the low-level memory allocation function pointers in
  40746. ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
  40747. ** arguments specify the block of memory to manage.
  40748. **
  40749. ** This routine is only called by sqlite3_config(), and therefore
  40750. ** is not required to be threadsafe (it is not).
  40751. */
  40752. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void){
  40753. static const sqlite3_mem_methods winMemMethods = {
  40754. winMemMalloc,
  40755. winMemFree,
  40756. winMemRealloc,
  40757. winMemSize,
  40758. winMemRoundup,
  40759. winMemInit,
  40760. winMemShutdown,
  40761. &win_mem_data
  40762. };
  40763. return &winMemMethods;
  40764. }
  40765. SQLITE_PRIVATE void sqlite3MemSetDefault(void){
  40766. sqlite3_config(SQLITE_CONFIG_MALLOC, sqlite3MemGetWin32());
  40767. }
  40768. #endif /* SQLITE_WIN32_MALLOC */
  40769. /*
  40770. ** Convert a UTF-8 string to Microsoft Unicode.
  40771. **
  40772. ** Space to hold the returned string is obtained from sqlite3_malloc().
  40773. */
  40774. static LPWSTR winUtf8ToUnicode(const char *zText){
  40775. int nChar;
  40776. LPWSTR zWideText;
  40777. nChar = osMultiByteToWideChar(CP_UTF8, 0, zText, -1, NULL, 0);
  40778. if( nChar==0 ){
  40779. return 0;
  40780. }
  40781. zWideText = sqlite3MallocZero( nChar*sizeof(WCHAR) );
  40782. if( zWideText==0 ){
  40783. return 0;
  40784. }
  40785. nChar = osMultiByteToWideChar(CP_UTF8, 0, zText, -1, zWideText,
  40786. nChar);
  40787. if( nChar==0 ){
  40788. sqlite3_free(zWideText);
  40789. zWideText = 0;
  40790. }
  40791. return zWideText;
  40792. }
  40793. /*
  40794. ** Convert a Microsoft Unicode string to UTF-8.
  40795. **
  40796. ** Space to hold the returned string is obtained from sqlite3_malloc().
  40797. */
  40798. static char *winUnicodeToUtf8(LPCWSTR zWideText){
  40799. int nByte;
  40800. char *zText;
  40801. nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideText, -1, 0, 0, 0, 0);
  40802. if( nByte == 0 ){
  40803. return 0;
  40804. }
  40805. zText = sqlite3MallocZero( nByte );
  40806. if( zText==0 ){
  40807. return 0;
  40808. }
  40809. nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideText, -1, zText, nByte,
  40810. 0, 0);
  40811. if( nByte == 0 ){
  40812. sqlite3_free(zText);
  40813. zText = 0;
  40814. }
  40815. return zText;
  40816. }
  40817. /*
  40818. ** Convert an ANSI string to Microsoft Unicode, using the ANSI or OEM
  40819. ** code page.
  40820. **
  40821. ** Space to hold the returned string is obtained from sqlite3_malloc().
  40822. */
  40823. static LPWSTR winMbcsToUnicode(const char *zText, int useAnsi){
  40824. int nByte;
  40825. LPWSTR zMbcsText;
  40826. int codepage = useAnsi ? CP_ACP : CP_OEMCP;
  40827. nByte = osMultiByteToWideChar(codepage, 0, zText, -1, NULL,
  40828. 0)*sizeof(WCHAR);
  40829. if( nByte==0 ){
  40830. return 0;
  40831. }
  40832. zMbcsText = sqlite3MallocZero( nByte*sizeof(WCHAR) );
  40833. if( zMbcsText==0 ){
  40834. return 0;
  40835. }
  40836. nByte = osMultiByteToWideChar(codepage, 0, zText, -1, zMbcsText,
  40837. nByte);
  40838. if( nByte==0 ){
  40839. sqlite3_free(zMbcsText);
  40840. zMbcsText = 0;
  40841. }
  40842. return zMbcsText;
  40843. }
  40844. /*
  40845. ** Convert a Microsoft Unicode string to a multi-byte character string,
  40846. ** using the ANSI or OEM code page.
  40847. **
  40848. ** Space to hold the returned string is obtained from sqlite3_malloc().
  40849. */
  40850. static char *winUnicodeToMbcs(LPCWSTR zWideText, int useAnsi){
  40851. int nByte;
  40852. char *zText;
  40853. int codepage = useAnsi ? CP_ACP : CP_OEMCP;
  40854. nByte = osWideCharToMultiByte(codepage, 0, zWideText, -1, 0, 0, 0, 0);
  40855. if( nByte == 0 ){
  40856. return 0;
  40857. }
  40858. zText = sqlite3MallocZero( nByte );
  40859. if( zText==0 ){
  40860. return 0;
  40861. }
  40862. nByte = osWideCharToMultiByte(codepage, 0, zWideText, -1, zText,
  40863. nByte, 0, 0);
  40864. if( nByte == 0 ){
  40865. sqlite3_free(zText);
  40866. zText = 0;
  40867. }
  40868. return zText;
  40869. }
  40870. /*
  40871. ** Convert a multi-byte character string to UTF-8.
  40872. **
  40873. ** Space to hold the returned string is obtained from sqlite3_malloc().
  40874. */
  40875. static char *winMbcsToUtf8(const char *zText, int useAnsi){
  40876. char *zTextUtf8;
  40877. LPWSTR zTmpWide;
  40878. zTmpWide = winMbcsToUnicode(zText, useAnsi);
  40879. if( zTmpWide==0 ){
  40880. return 0;
  40881. }
  40882. zTextUtf8 = winUnicodeToUtf8(zTmpWide);
  40883. sqlite3_free(zTmpWide);
  40884. return zTextUtf8;
  40885. }
  40886. /*
  40887. ** Convert a UTF-8 string to a multi-byte character string.
  40888. **
  40889. ** Space to hold the returned string is obtained from sqlite3_malloc().
  40890. */
  40891. static char *winUtf8ToMbcs(const char *zText, int useAnsi){
  40892. char *zTextMbcs;
  40893. LPWSTR zTmpWide;
  40894. zTmpWide = winUtf8ToUnicode(zText);
  40895. if( zTmpWide==0 ){
  40896. return 0;
  40897. }
  40898. zTextMbcs = winUnicodeToMbcs(zTmpWide, useAnsi);
  40899. sqlite3_free(zTmpWide);
  40900. return zTextMbcs;
  40901. }
  40902. /*
  40903. ** This is a public wrapper for the winUtf8ToUnicode() function.
  40904. */
  40905. SQLITE_API LPWSTR sqlite3_win32_utf8_to_unicode(const char *zText){
  40906. #ifdef SQLITE_ENABLE_API_ARMOR
  40907. if( !zText ){
  40908. (void)SQLITE_MISUSE_BKPT;
  40909. return 0;
  40910. }
  40911. #endif
  40912. #ifndef SQLITE_OMIT_AUTOINIT
  40913. if( sqlite3_initialize() ) return 0;
  40914. #endif
  40915. return winUtf8ToUnicode(zText);
  40916. }
  40917. /*
  40918. ** This is a public wrapper for the winUnicodeToUtf8() function.
  40919. */
  40920. SQLITE_API char *sqlite3_win32_unicode_to_utf8(LPCWSTR zWideText){
  40921. #ifdef SQLITE_ENABLE_API_ARMOR
  40922. if( !zWideText ){
  40923. (void)SQLITE_MISUSE_BKPT;
  40924. return 0;
  40925. }
  40926. #endif
  40927. #ifndef SQLITE_OMIT_AUTOINIT
  40928. if( sqlite3_initialize() ) return 0;
  40929. #endif
  40930. return winUnicodeToUtf8(zWideText);
  40931. }
  40932. /*
  40933. ** This is a public wrapper for the winMbcsToUtf8() function.
  40934. */
  40935. SQLITE_API char *sqlite3_win32_mbcs_to_utf8(const char *zText){
  40936. #ifdef SQLITE_ENABLE_API_ARMOR
  40937. if( !zText ){
  40938. (void)SQLITE_MISUSE_BKPT;
  40939. return 0;
  40940. }
  40941. #endif
  40942. #ifndef SQLITE_OMIT_AUTOINIT
  40943. if( sqlite3_initialize() ) return 0;
  40944. #endif
  40945. return winMbcsToUtf8(zText, osAreFileApisANSI());
  40946. }
  40947. /*
  40948. ** This is a public wrapper for the winMbcsToUtf8() function.
  40949. */
  40950. SQLITE_API char *sqlite3_win32_mbcs_to_utf8_v2(const char *zText, int useAnsi){
  40951. #ifdef SQLITE_ENABLE_API_ARMOR
  40952. if( !zText ){
  40953. (void)SQLITE_MISUSE_BKPT;
  40954. return 0;
  40955. }
  40956. #endif
  40957. #ifndef SQLITE_OMIT_AUTOINIT
  40958. if( sqlite3_initialize() ) return 0;
  40959. #endif
  40960. return winMbcsToUtf8(zText, useAnsi);
  40961. }
  40962. /*
  40963. ** This is a public wrapper for the winUtf8ToMbcs() function.
  40964. */
  40965. SQLITE_API char *sqlite3_win32_utf8_to_mbcs(const char *zText){
  40966. #ifdef SQLITE_ENABLE_API_ARMOR
  40967. if( !zText ){
  40968. (void)SQLITE_MISUSE_BKPT;
  40969. return 0;
  40970. }
  40971. #endif
  40972. #ifndef SQLITE_OMIT_AUTOINIT
  40973. if( sqlite3_initialize() ) return 0;
  40974. #endif
  40975. return winUtf8ToMbcs(zText, osAreFileApisANSI());
  40976. }
  40977. /*
  40978. ** This is a public wrapper for the winUtf8ToMbcs() function.
  40979. */
  40980. SQLITE_API char *sqlite3_win32_utf8_to_mbcs_v2(const char *zText, int useAnsi){
  40981. #ifdef SQLITE_ENABLE_API_ARMOR
  40982. if( !zText ){
  40983. (void)SQLITE_MISUSE_BKPT;
  40984. return 0;
  40985. }
  40986. #endif
  40987. #ifndef SQLITE_OMIT_AUTOINIT
  40988. if( sqlite3_initialize() ) return 0;
  40989. #endif
  40990. return winUtf8ToMbcs(zText, useAnsi);
  40991. }
  40992. /*
  40993. ** This function is the same as sqlite3_win32_set_directory (below); however,
  40994. ** it accepts a UTF-8 string.
  40995. */
  40996. SQLITE_API int sqlite3_win32_set_directory8(
  40997. unsigned long type, /* Identifier for directory being set or reset */
  40998. const char *zValue /* New value for directory being set or reset */
  40999. ){
  41000. char **ppDirectory = 0;
  41001. #ifndef SQLITE_OMIT_AUTOINIT
  41002. int rc = sqlite3_initialize();
  41003. if( rc ) return rc;
  41004. #endif
  41005. if( type==SQLITE_WIN32_DATA_DIRECTORY_TYPE ){
  41006. ppDirectory = &sqlite3_data_directory;
  41007. }else if( type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE ){
  41008. ppDirectory = &sqlite3_temp_directory;
  41009. }
  41010. assert( !ppDirectory || type==SQLITE_WIN32_DATA_DIRECTORY_TYPE
  41011. || type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE
  41012. );
  41013. assert( !ppDirectory || sqlite3MemdebugHasType(*ppDirectory, MEMTYPE_HEAP) );
  41014. if( ppDirectory ){
  41015. char *zCopy = 0;
  41016. if( zValue && zValue[0] ){
  41017. zCopy = sqlite3_mprintf("%s", zValue);
  41018. if ( zCopy==0 ){
  41019. return SQLITE_NOMEM_BKPT;
  41020. }
  41021. }
  41022. sqlite3_free(*ppDirectory);
  41023. *ppDirectory = zCopy;
  41024. return SQLITE_OK;
  41025. }
  41026. return SQLITE_ERROR;
  41027. }
  41028. /*
  41029. ** This function is the same as sqlite3_win32_set_directory (below); however,
  41030. ** it accepts a UTF-16 string.
  41031. */
  41032. SQLITE_API int sqlite3_win32_set_directory16(
  41033. unsigned long type, /* Identifier for directory being set or reset */
  41034. const void *zValue /* New value for directory being set or reset */
  41035. ){
  41036. int rc;
  41037. char *zUtf8 = 0;
  41038. if( zValue ){
  41039. zUtf8 = sqlite3_win32_unicode_to_utf8(zValue);
  41040. if( zUtf8==0 ) return SQLITE_NOMEM_BKPT;
  41041. }
  41042. rc = sqlite3_win32_set_directory8(type, zUtf8);
  41043. if( zUtf8 ) sqlite3_free(zUtf8);
  41044. return rc;
  41045. }
  41046. /*
  41047. ** This function sets the data directory or the temporary directory based on
  41048. ** the provided arguments. The type argument must be 1 in order to set the
  41049. ** data directory or 2 in order to set the temporary directory. The zValue
  41050. ** argument is the name of the directory to use. The return value will be
  41051. ** SQLITE_OK if successful.
  41052. */
  41053. SQLITE_API int sqlite3_win32_set_directory(
  41054. unsigned long type, /* Identifier for directory being set or reset */
  41055. void *zValue /* New value for directory being set or reset */
  41056. ){
  41057. return sqlite3_win32_set_directory16(type, zValue);
  41058. }
  41059. /*
  41060. ** The return value of winGetLastErrorMsg
  41061. ** is zero if the error message fits in the buffer, or non-zero
  41062. ** otherwise (if the message was truncated).
  41063. */
  41064. static int winGetLastErrorMsg(DWORD lastErrno, int nBuf, char *zBuf){
  41065. /* FormatMessage returns 0 on failure. Otherwise it
  41066. ** returns the number of TCHARs written to the output
  41067. ** buffer, excluding the terminating null char.
  41068. */
  41069. DWORD dwLen = 0;
  41070. char *zOut = 0;
  41071. if( osIsNT() ){
  41072. #if SQLITE_OS_WINRT
  41073. WCHAR zTempWide[SQLITE_WIN32_MAX_ERRMSG_CHARS+1];
  41074. dwLen = osFormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
  41075. FORMAT_MESSAGE_IGNORE_INSERTS,
  41076. NULL,
  41077. lastErrno,
  41078. 0,
  41079. zTempWide,
  41080. SQLITE_WIN32_MAX_ERRMSG_CHARS,
  41081. 0);
  41082. #else
  41083. LPWSTR zTempWide = NULL;
  41084. dwLen = osFormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
  41085. FORMAT_MESSAGE_FROM_SYSTEM |
  41086. FORMAT_MESSAGE_IGNORE_INSERTS,
  41087. NULL,
  41088. lastErrno,
  41089. 0,
  41090. (LPWSTR) &zTempWide,
  41091. 0,
  41092. 0);
  41093. #endif
  41094. if( dwLen > 0 ){
  41095. /* allocate a buffer and convert to UTF8 */
  41096. sqlite3BeginBenignMalloc();
  41097. zOut = winUnicodeToUtf8(zTempWide);
  41098. sqlite3EndBenignMalloc();
  41099. #if !SQLITE_OS_WINRT
  41100. /* free the system buffer allocated by FormatMessage */
  41101. osLocalFree(zTempWide);
  41102. #endif
  41103. }
  41104. }
  41105. #ifdef SQLITE_WIN32_HAS_ANSI
  41106. else{
  41107. char *zTemp = NULL;
  41108. dwLen = osFormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
  41109. FORMAT_MESSAGE_FROM_SYSTEM |
  41110. FORMAT_MESSAGE_IGNORE_INSERTS,
  41111. NULL,
  41112. lastErrno,
  41113. 0,
  41114. (LPSTR) &zTemp,
  41115. 0,
  41116. 0);
  41117. if( dwLen > 0 ){
  41118. /* allocate a buffer and convert to UTF8 */
  41119. sqlite3BeginBenignMalloc();
  41120. zOut = winMbcsToUtf8(zTemp, osAreFileApisANSI());
  41121. sqlite3EndBenignMalloc();
  41122. /* free the system buffer allocated by FormatMessage */
  41123. osLocalFree(zTemp);
  41124. }
  41125. }
  41126. #endif
  41127. if( 0 == dwLen ){
  41128. sqlite3_snprintf(nBuf, zBuf, "OsError 0x%lx (%lu)", lastErrno, lastErrno);
  41129. }else{
  41130. /* copy a maximum of nBuf chars to output buffer */
  41131. sqlite3_snprintf(nBuf, zBuf, "%s", zOut);
  41132. /* free the UTF8 buffer */
  41133. sqlite3_free(zOut);
  41134. }
  41135. return 0;
  41136. }
  41137. /*
  41138. **
  41139. ** This function - winLogErrorAtLine() - is only ever called via the macro
  41140. ** winLogError().
  41141. **
  41142. ** This routine is invoked after an error occurs in an OS function.
  41143. ** It logs a message using sqlite3_log() containing the current value of
  41144. ** error code and, if possible, the human-readable equivalent from
  41145. ** FormatMessage.
  41146. **
  41147. ** The first argument passed to the macro should be the error code that
  41148. ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
  41149. ** The two subsequent arguments should be the name of the OS function that
  41150. ** failed and the associated file-system path, if any.
  41151. */
  41152. #define winLogError(a,b,c,d) winLogErrorAtLine(a,b,c,d,__LINE__)
  41153. static int winLogErrorAtLine(
  41154. int errcode, /* SQLite error code */
  41155. DWORD lastErrno, /* Win32 last error */
  41156. const char *zFunc, /* Name of OS function that failed */
  41157. const char *zPath, /* File path associated with error */
  41158. int iLine /* Source line number where error occurred */
  41159. ){
  41160. char zMsg[500]; /* Human readable error text */
  41161. int i; /* Loop counter */
  41162. zMsg[0] = 0;
  41163. winGetLastErrorMsg(lastErrno, sizeof(zMsg), zMsg);
  41164. assert( errcode!=SQLITE_OK );
  41165. if( zPath==0 ) zPath = "";
  41166. for(i=0; zMsg[i] && zMsg[i]!='\r' && zMsg[i]!='\n'; i++){}
  41167. zMsg[i] = 0;
  41168. sqlite3_log(errcode,
  41169. "os_win.c:%d: (%lu) %s(%s) - %s",
  41170. iLine, lastErrno, zFunc, zPath, zMsg
  41171. );
  41172. return errcode;
  41173. }
  41174. /*
  41175. ** The number of times that a ReadFile(), WriteFile(), and DeleteFile()
  41176. ** will be retried following a locking error - probably caused by
  41177. ** antivirus software. Also the initial delay before the first retry.
  41178. ** The delay increases linearly with each retry.
  41179. */
  41180. #ifndef SQLITE_WIN32_IOERR_RETRY
  41181. # define SQLITE_WIN32_IOERR_RETRY 10
  41182. #endif
  41183. #ifndef SQLITE_WIN32_IOERR_RETRY_DELAY
  41184. # define SQLITE_WIN32_IOERR_RETRY_DELAY 25
  41185. #endif
  41186. static int winIoerrRetry = SQLITE_WIN32_IOERR_RETRY;
  41187. static int winIoerrRetryDelay = SQLITE_WIN32_IOERR_RETRY_DELAY;
  41188. /*
  41189. ** The "winIoerrCanRetry1" macro is used to determine if a particular I/O
  41190. ** error code obtained via GetLastError() is eligible to be retried. It
  41191. ** must accept the error code DWORD as its only argument and should return
  41192. ** non-zero if the error code is transient in nature and the operation
  41193. ** responsible for generating the original error might succeed upon being
  41194. ** retried. The argument to this macro should be a variable.
  41195. **
  41196. ** Additionally, a macro named "winIoerrCanRetry2" may be defined. If it
  41197. ** is defined, it will be consulted only when the macro "winIoerrCanRetry1"
  41198. ** returns zero. The "winIoerrCanRetry2" macro is completely optional and
  41199. ** may be used to include additional error codes in the set that should
  41200. ** result in the failing I/O operation being retried by the caller. If
  41201. ** defined, the "winIoerrCanRetry2" macro must exhibit external semantics
  41202. ** identical to those of the "winIoerrCanRetry1" macro.
  41203. */
  41204. #if !defined(winIoerrCanRetry1)
  41205. #define winIoerrCanRetry1(a) (((a)==ERROR_ACCESS_DENIED) || \
  41206. ((a)==ERROR_SHARING_VIOLATION) || \
  41207. ((a)==ERROR_LOCK_VIOLATION) || \
  41208. ((a)==ERROR_DEV_NOT_EXIST) || \
  41209. ((a)==ERROR_NETNAME_DELETED) || \
  41210. ((a)==ERROR_SEM_TIMEOUT) || \
  41211. ((a)==ERROR_NETWORK_UNREACHABLE))
  41212. #endif
  41213. /*
  41214. ** If a ReadFile() or WriteFile() error occurs, invoke this routine
  41215. ** to see if it should be retried. Return TRUE to retry. Return FALSE
  41216. ** to give up with an error.
  41217. */
  41218. static int winRetryIoerr(int *pnRetry, DWORD *pError){
  41219. DWORD e = osGetLastError();
  41220. if( *pnRetry>=winIoerrRetry ){
  41221. if( pError ){
  41222. *pError = e;
  41223. }
  41224. return 0;
  41225. }
  41226. if( winIoerrCanRetry1(e) ){
  41227. sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry));
  41228. ++*pnRetry;
  41229. return 1;
  41230. }
  41231. #if defined(winIoerrCanRetry2)
  41232. else if( winIoerrCanRetry2(e) ){
  41233. sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry));
  41234. ++*pnRetry;
  41235. return 1;
  41236. }
  41237. #endif
  41238. if( pError ){
  41239. *pError = e;
  41240. }
  41241. return 0;
  41242. }
  41243. /*
  41244. ** Log a I/O error retry episode.
  41245. */
  41246. static void winLogIoerr(int nRetry, int lineno){
  41247. if( nRetry ){
  41248. sqlite3_log(SQLITE_NOTICE,
  41249. "delayed %dms for lock/sharing conflict at line %d",
  41250. winIoerrRetryDelay*nRetry*(nRetry+1)/2, lineno
  41251. );
  41252. }
  41253. }
  41254. /*
  41255. ** This #if does not rely on the SQLITE_OS_WINCE define because the
  41256. ** corresponding section in "date.c" cannot use it.
  41257. */
  41258. #if !defined(SQLITE_OMIT_LOCALTIME) && defined(_WIN32_WCE) && \
  41259. (!defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API)
  41260. /*
  41261. ** The MSVC CRT on Windows CE may not have a localtime() function.
  41262. ** So define a substitute.
  41263. */
  41264. /* # include <time.h> */
  41265. struct tm *__cdecl localtime(const time_t *t)
  41266. {
  41267. static struct tm y;
  41268. FILETIME uTm, lTm;
  41269. SYSTEMTIME pTm;
  41270. sqlite3_int64 t64;
  41271. t64 = *t;
  41272. t64 = (t64 + 11644473600)*10000000;
  41273. uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF);
  41274. uTm.dwHighDateTime= (DWORD)(t64 >> 32);
  41275. osFileTimeToLocalFileTime(&uTm,&lTm);
  41276. osFileTimeToSystemTime(&lTm,&pTm);
  41277. y.tm_year = pTm.wYear - 1900;
  41278. y.tm_mon = pTm.wMonth - 1;
  41279. y.tm_wday = pTm.wDayOfWeek;
  41280. y.tm_mday = pTm.wDay;
  41281. y.tm_hour = pTm.wHour;
  41282. y.tm_min = pTm.wMinute;
  41283. y.tm_sec = pTm.wSecond;
  41284. return &y;
  41285. }
  41286. #endif
  41287. #if SQLITE_OS_WINCE
  41288. /*************************************************************************
  41289. ** This section contains code for WinCE only.
  41290. */
  41291. #define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
  41292. /*
  41293. ** Acquire a lock on the handle h
  41294. */
  41295. static void winceMutexAcquire(HANDLE h){
  41296. DWORD dwErr;
  41297. do {
  41298. dwErr = osWaitForSingleObject(h, INFINITE);
  41299. } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
  41300. }
  41301. /*
  41302. ** Release a lock acquired by winceMutexAcquire()
  41303. */
  41304. #define winceMutexRelease(h) ReleaseMutex(h)
  41305. /*
  41306. ** Create the mutex and shared memory used for locking in the file
  41307. ** descriptor pFile
  41308. */
  41309. static int winceCreateLock(const char *zFilename, winFile *pFile){
  41310. LPWSTR zTok;
  41311. LPWSTR zName;
  41312. DWORD lastErrno;
  41313. BOOL bLogged = FALSE;
  41314. BOOL bInit = TRUE;
  41315. zName = winUtf8ToUnicode(zFilename);
  41316. if( zName==0 ){
  41317. /* out of memory */
  41318. return SQLITE_IOERR_NOMEM_BKPT;
  41319. }
  41320. /* Initialize the local lockdata */
  41321. memset(&pFile->local, 0, sizeof(pFile->local));
  41322. /* Replace the backslashes from the filename and lowercase it
  41323. ** to derive a mutex name. */
  41324. zTok = osCharLowerW(zName);
  41325. for (;*zTok;zTok++){
  41326. if (*zTok == '\\') *zTok = '_';
  41327. }
  41328. /* Create/open the named mutex */
  41329. pFile->hMutex = osCreateMutexW(NULL, FALSE, zName);
  41330. if (!pFile->hMutex){
  41331. pFile->lastErrno = osGetLastError();
  41332. sqlite3_free(zName);
  41333. return winLogError(SQLITE_IOERR, pFile->lastErrno,
  41334. "winceCreateLock1", zFilename);
  41335. }
  41336. /* Acquire the mutex before continuing */
  41337. winceMutexAcquire(pFile->hMutex);
  41338. /* Since the names of named mutexes, semaphores, file mappings etc are
  41339. ** case-sensitive, take advantage of that by uppercasing the mutex name
  41340. ** and using that as the shared filemapping name.
  41341. */
  41342. osCharUpperW(zName);
  41343. pFile->hShared = osCreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
  41344. PAGE_READWRITE, 0, sizeof(winceLock),
  41345. zName);
  41346. /* Set a flag that indicates we're the first to create the memory so it
  41347. ** must be zero-initialized */
  41348. lastErrno = osGetLastError();
  41349. if (lastErrno == ERROR_ALREADY_EXISTS){
  41350. bInit = FALSE;
  41351. }
  41352. sqlite3_free(zName);
  41353. /* If we succeeded in making the shared memory handle, map it. */
  41354. if( pFile->hShared ){
  41355. pFile->shared = (winceLock*)osMapViewOfFile(pFile->hShared,
  41356. FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
  41357. /* If mapping failed, close the shared memory handle and erase it */
  41358. if( !pFile->shared ){
  41359. pFile->lastErrno = osGetLastError();
  41360. winLogError(SQLITE_IOERR, pFile->lastErrno,
  41361. "winceCreateLock2", zFilename);
  41362. bLogged = TRUE;
  41363. osCloseHandle(pFile->hShared);
  41364. pFile->hShared = NULL;
  41365. }
  41366. }
  41367. /* If shared memory could not be created, then close the mutex and fail */
  41368. if( pFile->hShared==NULL ){
  41369. if( !bLogged ){
  41370. pFile->lastErrno = lastErrno;
  41371. winLogError(SQLITE_IOERR, pFile->lastErrno,
  41372. "winceCreateLock3", zFilename);
  41373. bLogged = TRUE;
  41374. }
  41375. winceMutexRelease(pFile->hMutex);
  41376. osCloseHandle(pFile->hMutex);
  41377. pFile->hMutex = NULL;
  41378. return SQLITE_IOERR;
  41379. }
  41380. /* Initialize the shared memory if we're supposed to */
  41381. if( bInit ){
  41382. memset(pFile->shared, 0, sizeof(winceLock));
  41383. }
  41384. winceMutexRelease(pFile->hMutex);
  41385. return SQLITE_OK;
  41386. }
  41387. /*
  41388. ** Destroy the part of winFile that deals with wince locks
  41389. */
  41390. static void winceDestroyLock(winFile *pFile){
  41391. if (pFile->hMutex){
  41392. /* Acquire the mutex */
  41393. winceMutexAcquire(pFile->hMutex);
  41394. /* The following blocks should probably assert in debug mode, but they
  41395. are to cleanup in case any locks remained open */
  41396. if (pFile->local.nReaders){
  41397. pFile->shared->nReaders --;
  41398. }
  41399. if (pFile->local.bReserved){
  41400. pFile->shared->bReserved = FALSE;
  41401. }
  41402. if (pFile->local.bPending){
  41403. pFile->shared->bPending = FALSE;
  41404. }
  41405. if (pFile->local.bExclusive){
  41406. pFile->shared->bExclusive = FALSE;
  41407. }
  41408. /* De-reference and close our copy of the shared memory handle */
  41409. osUnmapViewOfFile(pFile->shared);
  41410. osCloseHandle(pFile->hShared);
  41411. /* Done with the mutex */
  41412. winceMutexRelease(pFile->hMutex);
  41413. osCloseHandle(pFile->hMutex);
  41414. pFile->hMutex = NULL;
  41415. }
  41416. }
  41417. /*
  41418. ** An implementation of the LockFile() API of Windows for CE
  41419. */
  41420. static BOOL winceLockFile(
  41421. LPHANDLE phFile,
  41422. DWORD dwFileOffsetLow,
  41423. DWORD dwFileOffsetHigh,
  41424. DWORD nNumberOfBytesToLockLow,
  41425. DWORD nNumberOfBytesToLockHigh
  41426. ){
  41427. winFile *pFile = HANDLE_TO_WINFILE(phFile);
  41428. BOOL bReturn = FALSE;
  41429. UNUSED_PARAMETER(dwFileOffsetHigh);
  41430. UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
  41431. if (!pFile->hMutex) return TRUE;
  41432. winceMutexAcquire(pFile->hMutex);
  41433. /* Wanting an exclusive lock? */
  41434. if (dwFileOffsetLow == (DWORD)SHARED_FIRST
  41435. && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
  41436. if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
  41437. pFile->shared->bExclusive = TRUE;
  41438. pFile->local.bExclusive = TRUE;
  41439. bReturn = TRUE;
  41440. }
  41441. }
  41442. /* Want a read-only lock? */
  41443. else if (dwFileOffsetLow == (DWORD)SHARED_FIRST &&
  41444. nNumberOfBytesToLockLow == 1){
  41445. if (pFile->shared->bExclusive == 0){
  41446. pFile->local.nReaders ++;
  41447. if (pFile->local.nReaders == 1){
  41448. pFile->shared->nReaders ++;
  41449. }
  41450. bReturn = TRUE;
  41451. }
  41452. }
  41453. /* Want a pending lock? */
  41454. else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
  41455. && nNumberOfBytesToLockLow == 1){
  41456. /* If no pending lock has been acquired, then acquire it */
  41457. if (pFile->shared->bPending == 0) {
  41458. pFile->shared->bPending = TRUE;
  41459. pFile->local.bPending = TRUE;
  41460. bReturn = TRUE;
  41461. }
  41462. }
  41463. /* Want a reserved lock? */
  41464. else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
  41465. && nNumberOfBytesToLockLow == 1){
  41466. if (pFile->shared->bReserved == 0) {
  41467. pFile->shared->bReserved = TRUE;
  41468. pFile->local.bReserved = TRUE;
  41469. bReturn = TRUE;
  41470. }
  41471. }
  41472. winceMutexRelease(pFile->hMutex);
  41473. return bReturn;
  41474. }
  41475. /*
  41476. ** An implementation of the UnlockFile API of Windows for CE
  41477. */
  41478. static BOOL winceUnlockFile(
  41479. LPHANDLE phFile,
  41480. DWORD dwFileOffsetLow,
  41481. DWORD dwFileOffsetHigh,
  41482. DWORD nNumberOfBytesToUnlockLow,
  41483. DWORD nNumberOfBytesToUnlockHigh
  41484. ){
  41485. winFile *pFile = HANDLE_TO_WINFILE(phFile);
  41486. BOOL bReturn = FALSE;
  41487. UNUSED_PARAMETER(dwFileOffsetHigh);
  41488. UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh);
  41489. if (!pFile->hMutex) return TRUE;
  41490. winceMutexAcquire(pFile->hMutex);
  41491. /* Releasing a reader lock or an exclusive lock */
  41492. if (dwFileOffsetLow == (DWORD)SHARED_FIRST){
  41493. /* Did we have an exclusive lock? */
  41494. if (pFile->local.bExclusive){
  41495. assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE);
  41496. pFile->local.bExclusive = FALSE;
  41497. pFile->shared->bExclusive = FALSE;
  41498. bReturn = TRUE;
  41499. }
  41500. /* Did we just have a reader lock? */
  41501. else if (pFile->local.nReaders){
  41502. assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE
  41503. || nNumberOfBytesToUnlockLow == 1);
  41504. pFile->local.nReaders --;
  41505. if (pFile->local.nReaders == 0)
  41506. {
  41507. pFile->shared->nReaders --;
  41508. }
  41509. bReturn = TRUE;
  41510. }
  41511. }
  41512. /* Releasing a pending lock */
  41513. else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
  41514. && nNumberOfBytesToUnlockLow == 1){
  41515. if (pFile->local.bPending){
  41516. pFile->local.bPending = FALSE;
  41517. pFile->shared->bPending = FALSE;
  41518. bReturn = TRUE;
  41519. }
  41520. }
  41521. /* Releasing a reserved lock */
  41522. else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
  41523. && nNumberOfBytesToUnlockLow == 1){
  41524. if (pFile->local.bReserved) {
  41525. pFile->local.bReserved = FALSE;
  41526. pFile->shared->bReserved = FALSE;
  41527. bReturn = TRUE;
  41528. }
  41529. }
  41530. winceMutexRelease(pFile->hMutex);
  41531. return bReturn;
  41532. }
  41533. /*
  41534. ** End of the special code for wince
  41535. *****************************************************************************/
  41536. #endif /* SQLITE_OS_WINCE */
  41537. /*
  41538. ** Lock a file region.
  41539. */
  41540. static BOOL winLockFile(
  41541. LPHANDLE phFile,
  41542. DWORD flags,
  41543. DWORD offsetLow,
  41544. DWORD offsetHigh,
  41545. DWORD numBytesLow,
  41546. DWORD numBytesHigh
  41547. ){
  41548. #if SQLITE_OS_WINCE
  41549. /*
  41550. ** NOTE: Windows CE is handled differently here due its lack of the Win32
  41551. ** API LockFile.
  41552. */
  41553. return winceLockFile(phFile, offsetLow, offsetHigh,
  41554. numBytesLow, numBytesHigh);
  41555. #else
  41556. if( osIsNT() ){
  41557. OVERLAPPED ovlp;
  41558. memset(&ovlp, 0, sizeof(OVERLAPPED));
  41559. ovlp.Offset = offsetLow;
  41560. ovlp.OffsetHigh = offsetHigh;
  41561. return osLockFileEx(*phFile, flags, 0, numBytesLow, numBytesHigh, &ovlp);
  41562. }else{
  41563. return osLockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
  41564. numBytesHigh);
  41565. }
  41566. #endif
  41567. }
  41568. /*
  41569. ** Unlock a file region.
  41570. */
  41571. static BOOL winUnlockFile(
  41572. LPHANDLE phFile,
  41573. DWORD offsetLow,
  41574. DWORD offsetHigh,
  41575. DWORD numBytesLow,
  41576. DWORD numBytesHigh
  41577. ){
  41578. #if SQLITE_OS_WINCE
  41579. /*
  41580. ** NOTE: Windows CE is handled differently here due its lack of the Win32
  41581. ** API UnlockFile.
  41582. */
  41583. return winceUnlockFile(phFile, offsetLow, offsetHigh,
  41584. numBytesLow, numBytesHigh);
  41585. #else
  41586. if( osIsNT() ){
  41587. OVERLAPPED ovlp;
  41588. memset(&ovlp, 0, sizeof(OVERLAPPED));
  41589. ovlp.Offset = offsetLow;
  41590. ovlp.OffsetHigh = offsetHigh;
  41591. return osUnlockFileEx(*phFile, 0, numBytesLow, numBytesHigh, &ovlp);
  41592. }else{
  41593. return osUnlockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
  41594. numBytesHigh);
  41595. }
  41596. #endif
  41597. }
  41598. /*****************************************************************************
  41599. ** The next group of routines implement the I/O methods specified
  41600. ** by the sqlite3_io_methods object.
  41601. ******************************************************************************/
  41602. /*
  41603. ** Some Microsoft compilers lack this definition.
  41604. */
  41605. #ifndef INVALID_SET_FILE_POINTER
  41606. # define INVALID_SET_FILE_POINTER ((DWORD)-1)
  41607. #endif
  41608. /*
  41609. ** Move the current position of the file handle passed as the first
  41610. ** argument to offset iOffset within the file. If successful, return 0.
  41611. ** Otherwise, set pFile->lastErrno and return non-zero.
  41612. */
  41613. static int winSeekFile(winFile *pFile, sqlite3_int64 iOffset){
  41614. #if !SQLITE_OS_WINRT
  41615. LONG upperBits; /* Most sig. 32 bits of new offset */
  41616. LONG lowerBits; /* Least sig. 32 bits of new offset */
  41617. DWORD dwRet; /* Value returned by SetFilePointer() */
  41618. DWORD lastErrno; /* Value returned by GetLastError() */
  41619. OSTRACE(("SEEK file=%p, offset=%lld\n", pFile->h, iOffset));
  41620. upperBits = (LONG)((iOffset>>32) & 0x7fffffff);
  41621. lowerBits = (LONG)(iOffset & 0xffffffff);
  41622. /* API oddity: If successful, SetFilePointer() returns a dword
  41623. ** containing the lower 32-bits of the new file-offset. Or, if it fails,
  41624. ** it returns INVALID_SET_FILE_POINTER. However according to MSDN,
  41625. ** INVALID_SET_FILE_POINTER may also be a valid new offset. So to determine
  41626. ** whether an error has actually occurred, it is also necessary to call
  41627. ** GetLastError().
  41628. */
  41629. dwRet = osSetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
  41630. if( (dwRet==INVALID_SET_FILE_POINTER
  41631. && ((lastErrno = osGetLastError())!=NO_ERROR)) ){
  41632. pFile->lastErrno = lastErrno;
  41633. winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
  41634. "winSeekFile", pFile->zPath);
  41635. OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
  41636. return 1;
  41637. }
  41638. OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
  41639. return 0;
  41640. #else
  41641. /*
  41642. ** Same as above, except that this implementation works for WinRT.
  41643. */
  41644. LARGE_INTEGER x; /* The new offset */
  41645. BOOL bRet; /* Value returned by SetFilePointerEx() */
  41646. x.QuadPart = iOffset;
  41647. bRet = osSetFilePointerEx(pFile->h, x, 0, FILE_BEGIN);
  41648. if(!bRet){
  41649. pFile->lastErrno = osGetLastError();
  41650. winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
  41651. "winSeekFile", pFile->zPath);
  41652. OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
  41653. return 1;
  41654. }
  41655. OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
  41656. return 0;
  41657. #endif
  41658. }
  41659. #if SQLITE_MAX_MMAP_SIZE>0
  41660. /* Forward references to VFS helper methods used for memory mapped files */
  41661. static int winMapfile(winFile*, sqlite3_int64);
  41662. static int winUnmapfile(winFile*);
  41663. #endif
  41664. /*
  41665. ** Close a file.
  41666. **
  41667. ** It is reported that an attempt to close a handle might sometimes
  41668. ** fail. This is a very unreasonable result, but Windows is notorious
  41669. ** for being unreasonable so I do not doubt that it might happen. If
  41670. ** the close fails, we pause for 100 milliseconds and try again. As
  41671. ** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
  41672. ** giving up and returning an error.
  41673. */
  41674. #define MX_CLOSE_ATTEMPT 3
  41675. static int winClose(sqlite3_file *id){
  41676. int rc, cnt = 0;
  41677. winFile *pFile = (winFile*)id;
  41678. assert( id!=0 );
  41679. #ifndef SQLITE_OMIT_WAL
  41680. assert( pFile->pShm==0 );
  41681. #endif
  41682. assert( pFile->h!=NULL && pFile->h!=INVALID_HANDLE_VALUE );
  41683. OSTRACE(("CLOSE pid=%lu, pFile=%p, file=%p\n",
  41684. osGetCurrentProcessId(), pFile, pFile->h));
  41685. #if SQLITE_MAX_MMAP_SIZE>0
  41686. winUnmapfile(pFile);
  41687. #endif
  41688. do{
  41689. rc = osCloseHandle(pFile->h);
  41690. /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */
  41691. }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (sqlite3_win32_sleep(100), 1) );
  41692. #if SQLITE_OS_WINCE
  41693. #define WINCE_DELETION_ATTEMPTS 3
  41694. {
  41695. winVfsAppData *pAppData = (winVfsAppData*)pFile->pVfs->pAppData;
  41696. if( pAppData==NULL || !pAppData->bNoLock ){
  41697. winceDestroyLock(pFile);
  41698. }
  41699. }
  41700. if( pFile->zDeleteOnClose ){
  41701. int cnt = 0;
  41702. while(
  41703. osDeleteFileW(pFile->zDeleteOnClose)==0
  41704. && osGetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff
  41705. && cnt++ < WINCE_DELETION_ATTEMPTS
  41706. ){
  41707. sqlite3_win32_sleep(100); /* Wait a little before trying again */
  41708. }
  41709. sqlite3_free(pFile->zDeleteOnClose);
  41710. }
  41711. #endif
  41712. if( rc ){
  41713. pFile->h = NULL;
  41714. }
  41715. OpenCounter(-1);
  41716. OSTRACE(("CLOSE pid=%lu, pFile=%p, file=%p, rc=%s\n",
  41717. osGetCurrentProcessId(), pFile, pFile->h, rc ? "ok" : "failed"));
  41718. return rc ? SQLITE_OK
  41719. : winLogError(SQLITE_IOERR_CLOSE, osGetLastError(),
  41720. "winClose", pFile->zPath);
  41721. }
  41722. /*
  41723. ** Read data from a file into a buffer. Return SQLITE_OK if all
  41724. ** bytes were read successfully and SQLITE_IOERR if anything goes
  41725. ** wrong.
  41726. */
  41727. static int winRead(
  41728. sqlite3_file *id, /* File to read from */
  41729. void *pBuf, /* Write content into this buffer */
  41730. int amt, /* Number of bytes to read */
  41731. sqlite3_int64 offset /* Begin reading at this offset */
  41732. ){
  41733. #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
  41734. OVERLAPPED overlapped; /* The offset for ReadFile. */
  41735. #endif
  41736. winFile *pFile = (winFile*)id; /* file handle */
  41737. DWORD nRead; /* Number of bytes actually read from file */
  41738. int nRetry = 0; /* Number of retrys */
  41739. assert( id!=0 );
  41740. assert( amt>0 );
  41741. assert( offset>=0 );
  41742. SimulateIOError(return SQLITE_IOERR_READ);
  41743. OSTRACE(("READ pid=%lu, pFile=%p, file=%p, buffer=%p, amount=%d, "
  41744. "offset=%lld, lock=%d\n", osGetCurrentProcessId(), pFile,
  41745. pFile->h, pBuf, amt, offset, pFile->locktype));
  41746. #if SQLITE_MAX_MMAP_SIZE>0
  41747. /* Deal with as much of this read request as possible by transfering
  41748. ** data from the memory mapping using memcpy(). */
  41749. if( offset<pFile->mmapSize ){
  41750. if( offset+amt <= pFile->mmapSize ){
  41751. memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
  41752. OSTRACE(("READ-MMAP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
  41753. osGetCurrentProcessId(), pFile, pFile->h));
  41754. return SQLITE_OK;
  41755. }else{
  41756. int nCopy = (int)(pFile->mmapSize - offset);
  41757. memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
  41758. pBuf = &((u8 *)pBuf)[nCopy];
  41759. amt -= nCopy;
  41760. offset += nCopy;
  41761. }
  41762. }
  41763. #endif
  41764. #if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
  41765. if( winSeekFile(pFile, offset) ){
  41766. OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_FULL\n",
  41767. osGetCurrentProcessId(), pFile, pFile->h));
  41768. return SQLITE_FULL;
  41769. }
  41770. while( !osReadFile(pFile->h, pBuf, amt, &nRead, 0) ){
  41771. #else
  41772. memset(&overlapped, 0, sizeof(OVERLAPPED));
  41773. overlapped.Offset = (LONG)(offset & 0xffffffff);
  41774. overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
  41775. while( !osReadFile(pFile->h, pBuf, amt, &nRead, &overlapped) &&
  41776. osGetLastError()!=ERROR_HANDLE_EOF ){
  41777. #endif
  41778. DWORD lastErrno;
  41779. if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
  41780. pFile->lastErrno = lastErrno;
  41781. OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_READ\n",
  41782. osGetCurrentProcessId(), pFile, pFile->h));
  41783. return winLogError(SQLITE_IOERR_READ, pFile->lastErrno,
  41784. "winRead", pFile->zPath);
  41785. }
  41786. winLogIoerr(nRetry, __LINE__);
  41787. if( nRead<(DWORD)amt ){
  41788. /* Unread parts of the buffer must be zero-filled */
  41789. memset(&((char*)pBuf)[nRead], 0, amt-nRead);
  41790. OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_SHORT_READ\n",
  41791. osGetCurrentProcessId(), pFile, pFile->h));
  41792. return SQLITE_IOERR_SHORT_READ;
  41793. }
  41794. OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
  41795. osGetCurrentProcessId(), pFile, pFile->h));
  41796. return SQLITE_OK;
  41797. }
  41798. /*
  41799. ** Write data from a buffer into a file. Return SQLITE_OK on success
  41800. ** or some other error code on failure.
  41801. */
  41802. static int winWrite(
  41803. sqlite3_file *id, /* File to write into */
  41804. const void *pBuf, /* The bytes to be written */
  41805. int amt, /* Number of bytes to write */
  41806. sqlite3_int64 offset /* Offset into the file to begin writing at */
  41807. ){
  41808. int rc = 0; /* True if error has occurred, else false */
  41809. winFile *pFile = (winFile*)id; /* File handle */
  41810. int nRetry = 0; /* Number of retries */
  41811. assert( amt>0 );
  41812. assert( pFile );
  41813. SimulateIOError(return SQLITE_IOERR_WRITE);
  41814. SimulateDiskfullError(return SQLITE_FULL);
  41815. OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, buffer=%p, amount=%d, "
  41816. "offset=%lld, lock=%d\n", osGetCurrentProcessId(), pFile,
  41817. pFile->h, pBuf, amt, offset, pFile->locktype));
  41818. #if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0
  41819. /* Deal with as much of this write request as possible by transfering
  41820. ** data from the memory mapping using memcpy(). */
  41821. if( offset<pFile->mmapSize ){
  41822. if( offset+amt <= pFile->mmapSize ){
  41823. memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
  41824. OSTRACE(("WRITE-MMAP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
  41825. osGetCurrentProcessId(), pFile, pFile->h));
  41826. return SQLITE_OK;
  41827. }else{
  41828. int nCopy = (int)(pFile->mmapSize - offset);
  41829. memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
  41830. pBuf = &((u8 *)pBuf)[nCopy];
  41831. amt -= nCopy;
  41832. offset += nCopy;
  41833. }
  41834. }
  41835. #endif
  41836. #if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
  41837. rc = winSeekFile(pFile, offset);
  41838. if( rc==0 ){
  41839. #else
  41840. {
  41841. #endif
  41842. #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
  41843. OVERLAPPED overlapped; /* The offset for WriteFile. */
  41844. #endif
  41845. u8 *aRem = (u8 *)pBuf; /* Data yet to be written */
  41846. int nRem = amt; /* Number of bytes yet to be written */
  41847. DWORD nWrite; /* Bytes written by each WriteFile() call */
  41848. DWORD lastErrno = NO_ERROR; /* Value returned by GetLastError() */
  41849. #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
  41850. memset(&overlapped, 0, sizeof(OVERLAPPED));
  41851. overlapped.Offset = (LONG)(offset & 0xffffffff);
  41852. overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
  41853. #endif
  41854. while( nRem>0 ){
  41855. #if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
  41856. if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, 0) ){
  41857. #else
  41858. if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, &overlapped) ){
  41859. #endif
  41860. if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
  41861. break;
  41862. }
  41863. assert( nWrite==0 || nWrite<=(DWORD)nRem );
  41864. if( nWrite==0 || nWrite>(DWORD)nRem ){
  41865. lastErrno = osGetLastError();
  41866. break;
  41867. }
  41868. #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
  41869. offset += nWrite;
  41870. overlapped.Offset = (LONG)(offset & 0xffffffff);
  41871. overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
  41872. #endif
  41873. aRem += nWrite;
  41874. nRem -= nWrite;
  41875. }
  41876. if( nRem>0 ){
  41877. pFile->lastErrno = lastErrno;
  41878. rc = 1;
  41879. }
  41880. }
  41881. if( rc ){
  41882. if( ( pFile->lastErrno==ERROR_HANDLE_DISK_FULL )
  41883. || ( pFile->lastErrno==ERROR_DISK_FULL )){
  41884. OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_FULL\n",
  41885. osGetCurrentProcessId(), pFile, pFile->h));
  41886. return winLogError(SQLITE_FULL, pFile->lastErrno,
  41887. "winWrite1", pFile->zPath);
  41888. }
  41889. OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_WRITE\n",
  41890. osGetCurrentProcessId(), pFile, pFile->h));
  41891. return winLogError(SQLITE_IOERR_WRITE, pFile->lastErrno,
  41892. "winWrite2", pFile->zPath);
  41893. }else{
  41894. winLogIoerr(nRetry, __LINE__);
  41895. }
  41896. OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
  41897. osGetCurrentProcessId(), pFile, pFile->h));
  41898. return SQLITE_OK;
  41899. }
  41900. /*
  41901. ** Truncate an open file to a specified size
  41902. */
  41903. static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
  41904. winFile *pFile = (winFile*)id; /* File handle object */
  41905. int rc = SQLITE_OK; /* Return code for this function */
  41906. DWORD lastErrno;
  41907. #if SQLITE_MAX_MMAP_SIZE>0
  41908. sqlite3_int64 oldMmapSize;
  41909. if( pFile->nFetchOut>0 ){
  41910. /* File truncation is a no-op if there are outstanding memory mapped
  41911. ** pages. This is because truncating the file means temporarily unmapping
  41912. ** the file, and that might delete memory out from under existing cursors.
  41913. **
  41914. ** This can result in incremental vacuum not truncating the file,
  41915. ** if there is an active read cursor when the incremental vacuum occurs.
  41916. ** No real harm comes of this - the database file is not corrupted,
  41917. ** though some folks might complain that the file is bigger than it
  41918. ** needs to be.
  41919. **
  41920. ** The only feasible work-around is to defer the truncation until after
  41921. ** all references to memory-mapped content are closed. That is doable,
  41922. ** but involves adding a few branches in the common write code path which
  41923. ** could slow down normal operations slightly. Hence, we have decided for
  41924. ** now to simply make trancations a no-op if there are pending reads. We
  41925. ** can maybe revisit this decision in the future.
  41926. */
  41927. return SQLITE_OK;
  41928. }
  41929. #endif
  41930. assert( pFile );
  41931. SimulateIOError(return SQLITE_IOERR_TRUNCATE);
  41932. OSTRACE(("TRUNCATE pid=%lu, pFile=%p, file=%p, size=%lld, lock=%d\n",
  41933. osGetCurrentProcessId(), pFile, pFile->h, nByte, pFile->locktype));
  41934. /* If the user has configured a chunk-size for this file, truncate the
  41935. ** file so that it consists of an integer number of chunks (i.e. the
  41936. ** actual file size after the operation may be larger than the requested
  41937. ** size).
  41938. */
  41939. if( pFile->szChunk>0 ){
  41940. nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
  41941. }
  41942. #if SQLITE_MAX_MMAP_SIZE>0
  41943. if( pFile->pMapRegion ){
  41944. oldMmapSize = pFile->mmapSize;
  41945. }else{
  41946. oldMmapSize = 0;
  41947. }
  41948. winUnmapfile(pFile);
  41949. #endif
  41950. /* SetEndOfFile() returns non-zero when successful, or zero when it fails. */
  41951. if( winSeekFile(pFile, nByte) ){
  41952. rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
  41953. "winTruncate1", pFile->zPath);
  41954. }else if( 0==osSetEndOfFile(pFile->h) &&
  41955. ((lastErrno = osGetLastError())!=ERROR_USER_MAPPED_FILE) ){
  41956. pFile->lastErrno = lastErrno;
  41957. rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
  41958. "winTruncate2", pFile->zPath);
  41959. }
  41960. #if SQLITE_MAX_MMAP_SIZE>0
  41961. if( rc==SQLITE_OK && oldMmapSize>0 ){
  41962. if( oldMmapSize>nByte ){
  41963. winMapfile(pFile, -1);
  41964. }else{
  41965. winMapfile(pFile, oldMmapSize);
  41966. }
  41967. }
  41968. #endif
  41969. OSTRACE(("TRUNCATE pid=%lu, pFile=%p, file=%p, rc=%s\n",
  41970. osGetCurrentProcessId(), pFile, pFile->h, sqlite3ErrName(rc)));
  41971. return rc;
  41972. }
  41973. #ifdef SQLITE_TEST
  41974. /*
  41975. ** Count the number of fullsyncs and normal syncs. This is used to test
  41976. ** that syncs and fullsyncs are occuring at the right times.
  41977. */
  41978. SQLITE_API int sqlite3_sync_count = 0;
  41979. SQLITE_API int sqlite3_fullsync_count = 0;
  41980. #endif
  41981. /*
  41982. ** Make sure all writes to a particular file are committed to disk.
  41983. */
  41984. static int winSync(sqlite3_file *id, int flags){
  41985. #ifndef SQLITE_NO_SYNC
  41986. /*
  41987. ** Used only when SQLITE_NO_SYNC is not defined.
  41988. */
  41989. BOOL rc;
  41990. #endif
  41991. #if !defined(NDEBUG) || !defined(SQLITE_NO_SYNC) || \
  41992. defined(SQLITE_HAVE_OS_TRACE)
  41993. /*
  41994. ** Used when SQLITE_NO_SYNC is not defined and by the assert() and/or
  41995. ** OSTRACE() macros.
  41996. */
  41997. winFile *pFile = (winFile*)id;
  41998. #else
  41999. UNUSED_PARAMETER(id);
  42000. #endif
  42001. assert( pFile );
  42002. /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
  42003. assert((flags&0x0F)==SQLITE_SYNC_NORMAL
  42004. || (flags&0x0F)==SQLITE_SYNC_FULL
  42005. );
  42006. /* Unix cannot, but some systems may return SQLITE_FULL from here. This
  42007. ** line is to test that doing so does not cause any problems.
  42008. */
  42009. SimulateDiskfullError( return SQLITE_FULL );
  42010. OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, flags=%x, lock=%d\n",
  42011. osGetCurrentProcessId(), pFile, pFile->h, flags,
  42012. pFile->locktype));
  42013. #ifndef SQLITE_TEST
  42014. UNUSED_PARAMETER(flags);
  42015. #else
  42016. if( (flags&0x0F)==SQLITE_SYNC_FULL ){
  42017. sqlite3_fullsync_count++;
  42018. }
  42019. sqlite3_sync_count++;
  42020. #endif
  42021. /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
  42022. ** no-op
  42023. */
  42024. #ifdef SQLITE_NO_SYNC
  42025. OSTRACE(("SYNC-NOP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
  42026. osGetCurrentProcessId(), pFile, pFile->h));
  42027. return SQLITE_OK;
  42028. #else
  42029. #if SQLITE_MAX_MMAP_SIZE>0
  42030. if( pFile->pMapRegion ){
  42031. if( osFlushViewOfFile(pFile->pMapRegion, 0) ){
  42032. OSTRACE(("SYNC-MMAP pid=%lu, pFile=%p, pMapRegion=%p, "
  42033. "rc=SQLITE_OK\n", osGetCurrentProcessId(),
  42034. pFile, pFile->pMapRegion));
  42035. }else{
  42036. pFile->lastErrno = osGetLastError();
  42037. OSTRACE(("SYNC-MMAP pid=%lu, pFile=%p, pMapRegion=%p, "
  42038. "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(),
  42039. pFile, pFile->pMapRegion));
  42040. return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
  42041. "winSync1", pFile->zPath);
  42042. }
  42043. }
  42044. #endif
  42045. rc = osFlushFileBuffers(pFile->h);
  42046. SimulateIOError( rc=FALSE );
  42047. if( rc ){
  42048. OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
  42049. osGetCurrentProcessId(), pFile, pFile->h));
  42050. return SQLITE_OK;
  42051. }else{
  42052. pFile->lastErrno = osGetLastError();
  42053. OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_FSYNC\n",
  42054. osGetCurrentProcessId(), pFile, pFile->h));
  42055. return winLogError(SQLITE_IOERR_FSYNC, pFile->lastErrno,
  42056. "winSync2", pFile->zPath);
  42057. }
  42058. #endif
  42059. }
  42060. /*
  42061. ** Determine the current size of a file in bytes
  42062. */
  42063. static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
  42064. winFile *pFile = (winFile*)id;
  42065. int rc = SQLITE_OK;
  42066. assert( id!=0 );
  42067. assert( pSize!=0 );
  42068. SimulateIOError(return SQLITE_IOERR_FSTAT);
  42069. OSTRACE(("SIZE file=%p, pSize=%p\n", pFile->h, pSize));
  42070. #if SQLITE_OS_WINRT
  42071. {
  42072. FILE_STANDARD_INFO info;
  42073. if( osGetFileInformationByHandleEx(pFile->h, FileStandardInfo,
  42074. &info, sizeof(info)) ){
  42075. *pSize = info.EndOfFile.QuadPart;
  42076. }else{
  42077. pFile->lastErrno = osGetLastError();
  42078. rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
  42079. "winFileSize", pFile->zPath);
  42080. }
  42081. }
  42082. #else
  42083. {
  42084. DWORD upperBits;
  42085. DWORD lowerBits;
  42086. DWORD lastErrno;
  42087. lowerBits = osGetFileSize(pFile->h, &upperBits);
  42088. *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
  42089. if( (lowerBits == INVALID_FILE_SIZE)
  42090. && ((lastErrno = osGetLastError())!=NO_ERROR) ){
  42091. pFile->lastErrno = lastErrno;
  42092. rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
  42093. "winFileSize", pFile->zPath);
  42094. }
  42095. }
  42096. #endif
  42097. OSTRACE(("SIZE file=%p, pSize=%p, *pSize=%lld, rc=%s\n",
  42098. pFile->h, pSize, *pSize, sqlite3ErrName(rc)));
  42099. return rc;
  42100. }
  42101. /*
  42102. ** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
  42103. */
  42104. #ifndef LOCKFILE_FAIL_IMMEDIATELY
  42105. # define LOCKFILE_FAIL_IMMEDIATELY 1
  42106. #endif
  42107. #ifndef LOCKFILE_EXCLUSIVE_LOCK
  42108. # define LOCKFILE_EXCLUSIVE_LOCK 2
  42109. #endif
  42110. /*
  42111. ** Historically, SQLite has used both the LockFile and LockFileEx functions.
  42112. ** When the LockFile function was used, it was always expected to fail
  42113. ** immediately if the lock could not be obtained. Also, it always expected to
  42114. ** obtain an exclusive lock. These flags are used with the LockFileEx function
  42115. ** and reflect those expectations; therefore, they should not be changed.
  42116. */
  42117. #ifndef SQLITE_LOCKFILE_FLAGS
  42118. # define SQLITE_LOCKFILE_FLAGS (LOCKFILE_FAIL_IMMEDIATELY | \
  42119. LOCKFILE_EXCLUSIVE_LOCK)
  42120. #endif
  42121. /*
  42122. ** Currently, SQLite never calls the LockFileEx function without wanting the
  42123. ** call to fail immediately if the lock cannot be obtained.
  42124. */
  42125. #ifndef SQLITE_LOCKFILEEX_FLAGS
  42126. # define SQLITE_LOCKFILEEX_FLAGS (LOCKFILE_FAIL_IMMEDIATELY)
  42127. #endif
  42128. /*
  42129. ** Acquire a reader lock.
  42130. ** Different API routines are called depending on whether or not this
  42131. ** is Win9x or WinNT.
  42132. */
  42133. static int winGetReadLock(winFile *pFile){
  42134. int res;
  42135. OSTRACE(("READ-LOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
  42136. if( osIsNT() ){
  42137. #if SQLITE_OS_WINCE
  42138. /*
  42139. ** NOTE: Windows CE is handled differently here due its lack of the Win32
  42140. ** API LockFileEx.
  42141. */
  42142. res = winceLockFile(&pFile->h, SHARED_FIRST, 0, 1, 0);
  42143. #else
  42144. res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS, SHARED_FIRST, 0,
  42145. SHARED_SIZE, 0);
  42146. #endif
  42147. }
  42148. #ifdef SQLITE_WIN32_HAS_ANSI
  42149. else{
  42150. int lk;
  42151. sqlite3_randomness(sizeof(lk), &lk);
  42152. pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
  42153. res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
  42154. SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
  42155. }
  42156. #endif
  42157. if( res == 0 ){
  42158. pFile->lastErrno = osGetLastError();
  42159. /* No need to log a failure to lock */
  42160. }
  42161. OSTRACE(("READ-LOCK file=%p, result=%d\n", pFile->h, res));
  42162. return res;
  42163. }
  42164. /*
  42165. ** Undo a readlock
  42166. */
  42167. static int winUnlockReadLock(winFile *pFile){
  42168. int res;
  42169. DWORD lastErrno;
  42170. OSTRACE(("READ-UNLOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
  42171. if( osIsNT() ){
  42172. res = winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
  42173. }
  42174. #ifdef SQLITE_WIN32_HAS_ANSI
  42175. else{
  42176. res = winUnlockFile(&pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
  42177. }
  42178. #endif
  42179. if( res==0 && ((lastErrno = osGetLastError())!=ERROR_NOT_LOCKED) ){
  42180. pFile->lastErrno = lastErrno;
  42181. winLogError(SQLITE_IOERR_UNLOCK, pFile->lastErrno,
  42182. "winUnlockReadLock", pFile->zPath);
  42183. }
  42184. OSTRACE(("READ-UNLOCK file=%p, result=%d\n", pFile->h, res));
  42185. return res;
  42186. }
  42187. /*
  42188. ** Lock the file with the lock specified by parameter locktype - one
  42189. ** of the following:
  42190. **
  42191. ** (1) SHARED_LOCK
  42192. ** (2) RESERVED_LOCK
  42193. ** (3) PENDING_LOCK
  42194. ** (4) EXCLUSIVE_LOCK
  42195. **
  42196. ** Sometimes when requesting one lock state, additional lock states
  42197. ** are inserted in between. The locking might fail on one of the later
  42198. ** transitions leaving the lock state different from what it started but
  42199. ** still short of its goal. The following chart shows the allowed
  42200. ** transitions and the inserted intermediate states:
  42201. **
  42202. ** UNLOCKED -> SHARED
  42203. ** SHARED -> RESERVED
  42204. ** SHARED -> (PENDING) -> EXCLUSIVE
  42205. ** RESERVED -> (PENDING) -> EXCLUSIVE
  42206. ** PENDING -> EXCLUSIVE
  42207. **
  42208. ** This routine will only increase a lock. The winUnlock() routine
  42209. ** erases all locks at once and returns us immediately to locking level 0.
  42210. ** It is not possible to lower the locking level one step at a time. You
  42211. ** must go straight to locking level 0.
  42212. */
  42213. static int winLock(sqlite3_file *id, int locktype){
  42214. int rc = SQLITE_OK; /* Return code from subroutines */
  42215. int res = 1; /* Result of a Windows lock call */
  42216. int newLocktype; /* Set pFile->locktype to this value before exiting */
  42217. int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
  42218. winFile *pFile = (winFile*)id;
  42219. DWORD lastErrno = NO_ERROR;
  42220. assert( id!=0 );
  42221. OSTRACE(("LOCK file=%p, oldLock=%d(%d), newLock=%d\n",
  42222. pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
  42223. /* If there is already a lock of this type or more restrictive on the
  42224. ** OsFile, do nothing. Don't use the end_lock: exit path, as
  42225. ** sqlite3OsEnterMutex() hasn't been called yet.
  42226. */
  42227. if( pFile->locktype>=locktype ){
  42228. OSTRACE(("LOCK-HELD file=%p, rc=SQLITE_OK\n", pFile->h));
  42229. return SQLITE_OK;
  42230. }
  42231. /* Do not allow any kind of write-lock on a read-only database
  42232. */
  42233. if( (pFile->ctrlFlags & WINFILE_RDONLY)!=0 && locktype>=RESERVED_LOCK ){
  42234. return SQLITE_IOERR_LOCK;
  42235. }
  42236. /* Make sure the locking sequence is correct
  42237. */
  42238. assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
  42239. assert( locktype!=PENDING_LOCK );
  42240. assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
  42241. /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
  42242. ** a SHARED lock. If we are acquiring a SHARED lock, the acquisition of
  42243. ** the PENDING_LOCK byte is temporary.
  42244. */
  42245. newLocktype = pFile->locktype;
  42246. if( pFile->locktype==NO_LOCK
  42247. || (locktype==EXCLUSIVE_LOCK && pFile->locktype<=RESERVED_LOCK)
  42248. ){
  42249. int cnt = 3;
  42250. while( cnt-->0 && (res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
  42251. PENDING_BYTE, 0, 1, 0))==0 ){
  42252. /* Try 3 times to get the pending lock. This is needed to work
  42253. ** around problems caused by indexing and/or anti-virus software on
  42254. ** Windows systems.
  42255. ** If you are using this code as a model for alternative VFSes, do not
  42256. ** copy this retry logic. It is a hack intended for Windows only.
  42257. */
  42258. lastErrno = osGetLastError();
  42259. OSTRACE(("LOCK-PENDING-FAIL file=%p, count=%d, result=%d\n",
  42260. pFile->h, cnt, res));
  42261. if( lastErrno==ERROR_INVALID_HANDLE ){
  42262. pFile->lastErrno = lastErrno;
  42263. rc = SQLITE_IOERR_LOCK;
  42264. OSTRACE(("LOCK-FAIL file=%p, count=%d, rc=%s\n",
  42265. pFile->h, cnt, sqlite3ErrName(rc)));
  42266. return rc;
  42267. }
  42268. if( cnt ) sqlite3_win32_sleep(1);
  42269. }
  42270. gotPendingLock = res;
  42271. if( !res ){
  42272. lastErrno = osGetLastError();
  42273. }
  42274. }
  42275. /* Acquire a shared lock
  42276. */
  42277. if( locktype==SHARED_LOCK && res ){
  42278. assert( pFile->locktype==NO_LOCK );
  42279. res = winGetReadLock(pFile);
  42280. if( res ){
  42281. newLocktype = SHARED_LOCK;
  42282. }else{
  42283. lastErrno = osGetLastError();
  42284. }
  42285. }
  42286. /* Acquire a RESERVED lock
  42287. */
  42288. if( locktype==RESERVED_LOCK && res ){
  42289. assert( pFile->locktype==SHARED_LOCK );
  42290. res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, RESERVED_BYTE, 0, 1, 0);
  42291. if( res ){
  42292. newLocktype = RESERVED_LOCK;
  42293. }else{
  42294. lastErrno = osGetLastError();
  42295. }
  42296. }
  42297. /* Acquire a PENDING lock
  42298. */
  42299. if( locktype==EXCLUSIVE_LOCK && res ){
  42300. newLocktype = PENDING_LOCK;
  42301. gotPendingLock = 0;
  42302. }
  42303. /* Acquire an EXCLUSIVE lock
  42304. */
  42305. if( locktype==EXCLUSIVE_LOCK && res ){
  42306. assert( pFile->locktype>=SHARED_LOCK );
  42307. res = winUnlockReadLock(pFile);
  42308. res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, SHARED_FIRST, 0,
  42309. SHARED_SIZE, 0);
  42310. if( res ){
  42311. newLocktype = EXCLUSIVE_LOCK;
  42312. }else{
  42313. lastErrno = osGetLastError();
  42314. winGetReadLock(pFile);
  42315. }
  42316. }
  42317. /* If we are holding a PENDING lock that ought to be released, then
  42318. ** release it now.
  42319. */
  42320. if( gotPendingLock && locktype==SHARED_LOCK ){
  42321. winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
  42322. }
  42323. /* Update the state of the lock has held in the file descriptor then
  42324. ** return the appropriate result code.
  42325. */
  42326. if( res ){
  42327. rc = SQLITE_OK;
  42328. }else{
  42329. pFile->lastErrno = lastErrno;
  42330. rc = SQLITE_BUSY;
  42331. OSTRACE(("LOCK-FAIL file=%p, wanted=%d, got=%d\n",
  42332. pFile->h, locktype, newLocktype));
  42333. }
  42334. pFile->locktype = (u8)newLocktype;
  42335. OSTRACE(("LOCK file=%p, lock=%d, rc=%s\n",
  42336. pFile->h, pFile->locktype, sqlite3ErrName(rc)));
  42337. return rc;
  42338. }
  42339. /*
  42340. ** This routine checks if there is a RESERVED lock held on the specified
  42341. ** file by this or any other process. If such a lock is held, return
  42342. ** non-zero, otherwise zero.
  42343. */
  42344. static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
  42345. int res;
  42346. winFile *pFile = (winFile*)id;
  42347. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  42348. OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p\n", pFile->h, pResOut));
  42349. assert( id!=0 );
  42350. if( pFile->locktype>=RESERVED_LOCK ){
  42351. res = 1;
  42352. OSTRACE(("TEST-WR-LOCK file=%p, result=%d (local)\n", pFile->h, res));
  42353. }else{
  42354. res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS,RESERVED_BYTE,0,1,0);
  42355. if( res ){
  42356. winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
  42357. }
  42358. res = !res;
  42359. OSTRACE(("TEST-WR-LOCK file=%p, result=%d (remote)\n", pFile->h, res));
  42360. }
  42361. *pResOut = res;
  42362. OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
  42363. pFile->h, pResOut, *pResOut));
  42364. return SQLITE_OK;
  42365. }
  42366. /*
  42367. ** Lower the locking level on file descriptor id to locktype. locktype
  42368. ** must be either NO_LOCK or SHARED_LOCK.
  42369. **
  42370. ** If the locking level of the file descriptor is already at or below
  42371. ** the requested locking level, this routine is a no-op.
  42372. **
  42373. ** It is not possible for this routine to fail if the second argument
  42374. ** is NO_LOCK. If the second argument is SHARED_LOCK then this routine
  42375. ** might return SQLITE_IOERR;
  42376. */
  42377. static int winUnlock(sqlite3_file *id, int locktype){
  42378. int type;
  42379. winFile *pFile = (winFile*)id;
  42380. int rc = SQLITE_OK;
  42381. assert( pFile!=0 );
  42382. assert( locktype<=SHARED_LOCK );
  42383. OSTRACE(("UNLOCK file=%p, oldLock=%d(%d), newLock=%d\n",
  42384. pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
  42385. type = pFile->locktype;
  42386. if( type>=EXCLUSIVE_LOCK ){
  42387. winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
  42388. if( locktype==SHARED_LOCK && !winGetReadLock(pFile) ){
  42389. /* This should never happen. We should always be able to
  42390. ** reacquire the read lock */
  42391. rc = winLogError(SQLITE_IOERR_UNLOCK, osGetLastError(),
  42392. "winUnlock", pFile->zPath);
  42393. }
  42394. }
  42395. if( type>=RESERVED_LOCK ){
  42396. winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
  42397. }
  42398. if( locktype==NO_LOCK && type>=SHARED_LOCK ){
  42399. winUnlockReadLock(pFile);
  42400. }
  42401. if( type>=PENDING_LOCK ){
  42402. winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
  42403. }
  42404. pFile->locktype = (u8)locktype;
  42405. OSTRACE(("UNLOCK file=%p, lock=%d, rc=%s\n",
  42406. pFile->h, pFile->locktype, sqlite3ErrName(rc)));
  42407. return rc;
  42408. }
  42409. /******************************************************************************
  42410. ****************************** No-op Locking **********************************
  42411. **
  42412. ** Of the various locking implementations available, this is by far the
  42413. ** simplest: locking is ignored. No attempt is made to lock the database
  42414. ** file for reading or writing.
  42415. **
  42416. ** This locking mode is appropriate for use on read-only databases
  42417. ** (ex: databases that are burned into CD-ROM, for example.) It can
  42418. ** also be used if the application employs some external mechanism to
  42419. ** prevent simultaneous access of the same database by two or more
  42420. ** database connections. But there is a serious risk of database
  42421. ** corruption if this locking mode is used in situations where multiple
  42422. ** database connections are accessing the same database file at the same
  42423. ** time and one or more of those connections are writing.
  42424. */
  42425. static int winNolockLock(sqlite3_file *id, int locktype){
  42426. UNUSED_PARAMETER(id);
  42427. UNUSED_PARAMETER(locktype);
  42428. return SQLITE_OK;
  42429. }
  42430. static int winNolockCheckReservedLock(sqlite3_file *id, int *pResOut){
  42431. UNUSED_PARAMETER(id);
  42432. UNUSED_PARAMETER(pResOut);
  42433. return SQLITE_OK;
  42434. }
  42435. static int winNolockUnlock(sqlite3_file *id, int locktype){
  42436. UNUSED_PARAMETER(id);
  42437. UNUSED_PARAMETER(locktype);
  42438. return SQLITE_OK;
  42439. }
  42440. /******************* End of the no-op lock implementation *********************
  42441. ******************************************************************************/
  42442. /*
  42443. ** If *pArg is initially negative then this is a query. Set *pArg to
  42444. ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
  42445. **
  42446. ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
  42447. */
  42448. static void winModeBit(winFile *pFile, unsigned char mask, int *pArg){
  42449. if( *pArg<0 ){
  42450. *pArg = (pFile->ctrlFlags & mask)!=0;
  42451. }else if( (*pArg)==0 ){
  42452. pFile->ctrlFlags &= ~mask;
  42453. }else{
  42454. pFile->ctrlFlags |= mask;
  42455. }
  42456. }
  42457. /* Forward references to VFS helper methods used for temporary files */
  42458. static int winGetTempname(sqlite3_vfs *, char **);
  42459. static int winIsDir(const void *);
  42460. static BOOL winIsLongPathPrefix(const char *);
  42461. static BOOL winIsDriveLetterAndColon(const char *);
  42462. /*
  42463. ** Control and query of the open file handle.
  42464. */
  42465. static int winFileControl(sqlite3_file *id, int op, void *pArg){
  42466. winFile *pFile = (winFile*)id;
  42467. OSTRACE(("FCNTL file=%p, op=%d, pArg=%p\n", pFile->h, op, pArg));
  42468. switch( op ){
  42469. case SQLITE_FCNTL_LOCKSTATE: {
  42470. *(int*)pArg = pFile->locktype;
  42471. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  42472. return SQLITE_OK;
  42473. }
  42474. case SQLITE_FCNTL_LAST_ERRNO: {
  42475. *(int*)pArg = (int)pFile->lastErrno;
  42476. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  42477. return SQLITE_OK;
  42478. }
  42479. case SQLITE_FCNTL_CHUNK_SIZE: {
  42480. pFile->szChunk = *(int *)pArg;
  42481. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  42482. return SQLITE_OK;
  42483. }
  42484. case SQLITE_FCNTL_SIZE_HINT: {
  42485. if( pFile->szChunk>0 ){
  42486. sqlite3_int64 oldSz;
  42487. int rc = winFileSize(id, &oldSz);
  42488. if( rc==SQLITE_OK ){
  42489. sqlite3_int64 newSz = *(sqlite3_int64*)pArg;
  42490. if( newSz>oldSz ){
  42491. SimulateIOErrorBenign(1);
  42492. rc = winTruncate(id, newSz);
  42493. SimulateIOErrorBenign(0);
  42494. }
  42495. }
  42496. OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
  42497. return rc;
  42498. }
  42499. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  42500. return SQLITE_OK;
  42501. }
  42502. case SQLITE_FCNTL_PERSIST_WAL: {
  42503. winModeBit(pFile, WINFILE_PERSIST_WAL, (int*)pArg);
  42504. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  42505. return SQLITE_OK;
  42506. }
  42507. case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
  42508. winModeBit(pFile, WINFILE_PSOW, (int*)pArg);
  42509. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  42510. return SQLITE_OK;
  42511. }
  42512. case SQLITE_FCNTL_VFSNAME: {
  42513. *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
  42514. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  42515. return SQLITE_OK;
  42516. }
  42517. case SQLITE_FCNTL_WIN32_AV_RETRY: {
  42518. int *a = (int*)pArg;
  42519. if( a[0]>0 ){
  42520. winIoerrRetry = a[0];
  42521. }else{
  42522. a[0] = winIoerrRetry;
  42523. }
  42524. if( a[1]>0 ){
  42525. winIoerrRetryDelay = a[1];
  42526. }else{
  42527. a[1] = winIoerrRetryDelay;
  42528. }
  42529. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  42530. return SQLITE_OK;
  42531. }
  42532. case SQLITE_FCNTL_WIN32_GET_HANDLE: {
  42533. LPHANDLE phFile = (LPHANDLE)pArg;
  42534. *phFile = pFile->h;
  42535. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  42536. return SQLITE_OK;
  42537. }
  42538. #ifdef SQLITE_TEST
  42539. case SQLITE_FCNTL_WIN32_SET_HANDLE: {
  42540. LPHANDLE phFile = (LPHANDLE)pArg;
  42541. HANDLE hOldFile = pFile->h;
  42542. pFile->h = *phFile;
  42543. *phFile = hOldFile;
  42544. OSTRACE(("FCNTL oldFile=%p, newFile=%p, rc=SQLITE_OK\n",
  42545. hOldFile, pFile->h));
  42546. return SQLITE_OK;
  42547. }
  42548. #endif
  42549. case SQLITE_FCNTL_TEMPFILENAME: {
  42550. char *zTFile = 0;
  42551. int rc = winGetTempname(pFile->pVfs, &zTFile);
  42552. if( rc==SQLITE_OK ){
  42553. *(char**)pArg = zTFile;
  42554. }
  42555. OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
  42556. return rc;
  42557. }
  42558. #if SQLITE_MAX_MMAP_SIZE>0
  42559. case SQLITE_FCNTL_MMAP_SIZE: {
  42560. i64 newLimit = *(i64*)pArg;
  42561. int rc = SQLITE_OK;
  42562. if( newLimit>sqlite3GlobalConfig.mxMmap ){
  42563. newLimit = sqlite3GlobalConfig.mxMmap;
  42564. }
  42565. /* The value of newLimit may be eventually cast to (SIZE_T) and passed
  42566. ** to MapViewOfFile(). Restrict its value to 2GB if (SIZE_T) is not at
  42567. ** least a 64-bit type. */
  42568. if( newLimit>0 && sizeof(SIZE_T)<8 ){
  42569. newLimit = (newLimit & 0x7FFFFFFF);
  42570. }
  42571. *(i64*)pArg = pFile->mmapSizeMax;
  42572. if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
  42573. pFile->mmapSizeMax = newLimit;
  42574. if( pFile->mmapSize>0 ){
  42575. winUnmapfile(pFile);
  42576. rc = winMapfile(pFile, -1);
  42577. }
  42578. }
  42579. OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
  42580. return rc;
  42581. }
  42582. #endif
  42583. }
  42584. OSTRACE(("FCNTL file=%p, rc=SQLITE_NOTFOUND\n", pFile->h));
  42585. return SQLITE_NOTFOUND;
  42586. }
  42587. /*
  42588. ** Return the sector size in bytes of the underlying block device for
  42589. ** the specified file. This is almost always 512 bytes, but may be
  42590. ** larger for some devices.
  42591. **
  42592. ** SQLite code assumes this function cannot fail. It also assumes that
  42593. ** if two files are created in the same file-system directory (i.e.
  42594. ** a database and its journal file) that the sector size will be the
  42595. ** same for both.
  42596. */
  42597. static int winSectorSize(sqlite3_file *id){
  42598. (void)id;
  42599. return SQLITE_DEFAULT_SECTOR_SIZE;
  42600. }
  42601. /*
  42602. ** Return a vector of device characteristics.
  42603. */
  42604. static int winDeviceCharacteristics(sqlite3_file *id){
  42605. winFile *p = (winFile*)id;
  42606. return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN |
  42607. ((p->ctrlFlags & WINFILE_PSOW)?SQLITE_IOCAP_POWERSAFE_OVERWRITE:0);
  42608. }
  42609. /*
  42610. ** Windows will only let you create file view mappings
  42611. ** on allocation size granularity boundaries.
  42612. ** During sqlite3_os_init() we do a GetSystemInfo()
  42613. ** to get the granularity size.
  42614. */
  42615. static SYSTEM_INFO winSysInfo;
  42616. #ifndef SQLITE_OMIT_WAL
  42617. /*
  42618. ** Helper functions to obtain and relinquish the global mutex. The
  42619. ** global mutex is used to protect the winLockInfo objects used by
  42620. ** this file, all of which may be shared by multiple threads.
  42621. **
  42622. ** Function winShmMutexHeld() is used to assert() that the global mutex
  42623. ** is held when required. This function is only used as part of assert()
  42624. ** statements. e.g.
  42625. **
  42626. ** winShmEnterMutex()
  42627. ** assert( winShmMutexHeld() );
  42628. ** winShmLeaveMutex()
  42629. */
  42630. static sqlite3_mutex *winBigLock = 0;
  42631. static void winShmEnterMutex(void){
  42632. sqlite3_mutex_enter(winBigLock);
  42633. }
  42634. static void winShmLeaveMutex(void){
  42635. sqlite3_mutex_leave(winBigLock);
  42636. }
  42637. #ifndef NDEBUG
  42638. static int winShmMutexHeld(void) {
  42639. return sqlite3_mutex_held(winBigLock);
  42640. }
  42641. #endif
  42642. /*
  42643. ** Object used to represent a single file opened and mmapped to provide
  42644. ** shared memory. When multiple threads all reference the same
  42645. ** log-summary, each thread has its own winFile object, but they all
  42646. ** point to a single instance of this object. In other words, each
  42647. ** log-summary is opened only once per process.
  42648. **
  42649. ** winShmMutexHeld() must be true when creating or destroying
  42650. ** this object or while reading or writing the following fields:
  42651. **
  42652. ** nRef
  42653. ** pNext
  42654. **
  42655. ** The following fields are read-only after the object is created:
  42656. **
  42657. ** fid
  42658. ** zFilename
  42659. **
  42660. ** Either winShmNode.mutex must be held or winShmNode.nRef==0 and
  42661. ** winShmMutexHeld() is true when reading or writing any other field
  42662. ** in this structure.
  42663. **
  42664. */
  42665. struct winShmNode {
  42666. sqlite3_mutex *mutex; /* Mutex to access this object */
  42667. char *zFilename; /* Name of the file */
  42668. winFile hFile; /* File handle from winOpen */
  42669. int szRegion; /* Size of shared-memory regions */
  42670. int nRegion; /* Size of array apRegion */
  42671. u8 isReadonly; /* True if read-only */
  42672. u8 isUnlocked; /* True if no DMS lock held */
  42673. struct ShmRegion {
  42674. HANDLE hMap; /* File handle from CreateFileMapping */
  42675. void *pMap;
  42676. } *aRegion;
  42677. DWORD lastErrno; /* The Windows errno from the last I/O error */
  42678. int nRef; /* Number of winShm objects pointing to this */
  42679. winShm *pFirst; /* All winShm objects pointing to this */
  42680. winShmNode *pNext; /* Next in list of all winShmNode objects */
  42681. #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
  42682. u8 nextShmId; /* Next available winShm.id value */
  42683. #endif
  42684. };
  42685. /*
  42686. ** A global array of all winShmNode objects.
  42687. **
  42688. ** The winShmMutexHeld() must be true while reading or writing this list.
  42689. */
  42690. static winShmNode *winShmNodeList = 0;
  42691. /*
  42692. ** Structure used internally by this VFS to record the state of an
  42693. ** open shared memory connection.
  42694. **
  42695. ** The following fields are initialized when this object is created and
  42696. ** are read-only thereafter:
  42697. **
  42698. ** winShm.pShmNode
  42699. ** winShm.id
  42700. **
  42701. ** All other fields are read/write. The winShm.pShmNode->mutex must be held
  42702. ** while accessing any read/write fields.
  42703. */
  42704. struct winShm {
  42705. winShmNode *pShmNode; /* The underlying winShmNode object */
  42706. winShm *pNext; /* Next winShm with the same winShmNode */
  42707. u8 hasMutex; /* True if holding the winShmNode mutex */
  42708. u16 sharedMask; /* Mask of shared locks held */
  42709. u16 exclMask; /* Mask of exclusive locks held */
  42710. #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
  42711. u8 id; /* Id of this connection with its winShmNode */
  42712. #endif
  42713. };
  42714. /*
  42715. ** Constants used for locking
  42716. */
  42717. #define WIN_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
  42718. #define WIN_SHM_DMS (WIN_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
  42719. /*
  42720. ** Apply advisory locks for all n bytes beginning at ofst.
  42721. */
  42722. #define WINSHM_UNLCK 1
  42723. #define WINSHM_RDLCK 2
  42724. #define WINSHM_WRLCK 3
  42725. static int winShmSystemLock(
  42726. winShmNode *pFile, /* Apply locks to this open shared-memory segment */
  42727. int lockType, /* WINSHM_UNLCK, WINSHM_RDLCK, or WINSHM_WRLCK */
  42728. int ofst, /* Offset to first byte to be locked/unlocked */
  42729. int nByte /* Number of bytes to lock or unlock */
  42730. ){
  42731. int rc = 0; /* Result code form Lock/UnlockFileEx() */
  42732. /* Access to the winShmNode object is serialized by the caller */
  42733. assert( pFile->nRef==0 || sqlite3_mutex_held(pFile->mutex) );
  42734. OSTRACE(("SHM-LOCK file=%p, lock=%d, offset=%d, size=%d\n",
  42735. pFile->hFile.h, lockType, ofst, nByte));
  42736. /* Release/Acquire the system-level lock */
  42737. if( lockType==WINSHM_UNLCK ){
  42738. rc = winUnlockFile(&pFile->hFile.h, ofst, 0, nByte, 0);
  42739. }else{
  42740. /* Initialize the locking parameters */
  42741. DWORD dwFlags = LOCKFILE_FAIL_IMMEDIATELY;
  42742. if( lockType == WINSHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;
  42743. rc = winLockFile(&pFile->hFile.h, dwFlags, ofst, 0, nByte, 0);
  42744. }
  42745. if( rc!= 0 ){
  42746. rc = SQLITE_OK;
  42747. }else{
  42748. pFile->lastErrno = osGetLastError();
  42749. rc = SQLITE_BUSY;
  42750. }
  42751. OSTRACE(("SHM-LOCK file=%p, func=%s, errno=%lu, rc=%s\n",
  42752. pFile->hFile.h, (lockType == WINSHM_UNLCK) ? "winUnlockFile" :
  42753. "winLockFile", pFile->lastErrno, sqlite3ErrName(rc)));
  42754. return rc;
  42755. }
  42756. /* Forward references to VFS methods */
  42757. static int winOpen(sqlite3_vfs*,const char*,sqlite3_file*,int,int*);
  42758. static int winDelete(sqlite3_vfs *,const char*,int);
  42759. /*
  42760. ** Purge the winShmNodeList list of all entries with winShmNode.nRef==0.
  42761. **
  42762. ** This is not a VFS shared-memory method; it is a utility function called
  42763. ** by VFS shared-memory methods.
  42764. */
  42765. static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){
  42766. winShmNode **pp;
  42767. winShmNode *p;
  42768. assert( winShmMutexHeld() );
  42769. OSTRACE(("SHM-PURGE pid=%lu, deleteFlag=%d\n",
  42770. osGetCurrentProcessId(), deleteFlag));
  42771. pp = &winShmNodeList;
  42772. while( (p = *pp)!=0 ){
  42773. if( p->nRef==0 ){
  42774. int i;
  42775. if( p->mutex ){ sqlite3_mutex_free(p->mutex); }
  42776. for(i=0; i<p->nRegion; i++){
  42777. BOOL bRc = osUnmapViewOfFile(p->aRegion[i].pMap);
  42778. OSTRACE(("SHM-PURGE-UNMAP pid=%lu, region=%d, rc=%s\n",
  42779. osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
  42780. UNUSED_VARIABLE_VALUE(bRc);
  42781. bRc = osCloseHandle(p->aRegion[i].hMap);
  42782. OSTRACE(("SHM-PURGE-CLOSE pid=%lu, region=%d, rc=%s\n",
  42783. osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
  42784. UNUSED_VARIABLE_VALUE(bRc);
  42785. }
  42786. if( p->hFile.h!=NULL && p->hFile.h!=INVALID_HANDLE_VALUE ){
  42787. SimulateIOErrorBenign(1);
  42788. winClose((sqlite3_file *)&p->hFile);
  42789. SimulateIOErrorBenign(0);
  42790. }
  42791. if( deleteFlag ){
  42792. SimulateIOErrorBenign(1);
  42793. sqlite3BeginBenignMalloc();
  42794. winDelete(pVfs, p->zFilename, 0);
  42795. sqlite3EndBenignMalloc();
  42796. SimulateIOErrorBenign(0);
  42797. }
  42798. *pp = p->pNext;
  42799. sqlite3_free(p->aRegion);
  42800. sqlite3_free(p);
  42801. }else{
  42802. pp = &p->pNext;
  42803. }
  42804. }
  42805. }
  42806. /*
  42807. ** The DMS lock has not yet been taken on shm file pShmNode. Attempt to
  42808. ** take it now. Return SQLITE_OK if successful, or an SQLite error
  42809. ** code otherwise.
  42810. **
  42811. ** If the DMS cannot be locked because this is a readonly_shm=1
  42812. ** connection and no other process already holds a lock, return
  42813. ** SQLITE_READONLY_CANTINIT and set pShmNode->isUnlocked=1.
  42814. */
  42815. static int winLockSharedMemory(winShmNode *pShmNode){
  42816. int rc = winShmSystemLock(pShmNode, WINSHM_WRLCK, WIN_SHM_DMS, 1);
  42817. if( rc==SQLITE_OK ){
  42818. if( pShmNode->isReadonly ){
  42819. pShmNode->isUnlocked = 1;
  42820. winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1);
  42821. return SQLITE_READONLY_CANTINIT;
  42822. }else if( winTruncate((sqlite3_file*)&pShmNode->hFile, 0) ){
  42823. winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1);
  42824. return winLogError(SQLITE_IOERR_SHMOPEN, osGetLastError(),
  42825. "winLockSharedMemory", pShmNode->zFilename);
  42826. }
  42827. }
  42828. if( rc==SQLITE_OK ){
  42829. winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1);
  42830. }
  42831. return winShmSystemLock(pShmNode, WINSHM_RDLCK, WIN_SHM_DMS, 1);
  42832. }
  42833. /*
  42834. ** Open the shared-memory area associated with database file pDbFd.
  42835. **
  42836. ** When opening a new shared-memory file, if no other instances of that
  42837. ** file are currently open, in this process or in other processes, then
  42838. ** the file must be truncated to zero length or have its header cleared.
  42839. */
  42840. static int winOpenSharedMemory(winFile *pDbFd){
  42841. struct winShm *p; /* The connection to be opened */
  42842. winShmNode *pShmNode = 0; /* The underlying mmapped file */
  42843. int rc = SQLITE_OK; /* Result code */
  42844. winShmNode *pNew; /* Newly allocated winShmNode */
  42845. int nName; /* Size of zName in bytes */
  42846. assert( pDbFd->pShm==0 ); /* Not previously opened */
  42847. /* Allocate space for the new sqlite3_shm object. Also speculatively
  42848. ** allocate space for a new winShmNode and filename.
  42849. */
  42850. p = sqlite3MallocZero( sizeof(*p) );
  42851. if( p==0 ) return SQLITE_IOERR_NOMEM_BKPT;
  42852. nName = sqlite3Strlen30(pDbFd->zPath);
  42853. pNew = sqlite3MallocZero( sizeof(*pShmNode) + nName + 17 );
  42854. if( pNew==0 ){
  42855. sqlite3_free(p);
  42856. return SQLITE_IOERR_NOMEM_BKPT;
  42857. }
  42858. pNew->zFilename = (char*)&pNew[1];
  42859. sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath);
  42860. sqlite3FileSuffix3(pDbFd->zPath, pNew->zFilename);
  42861. /* Look to see if there is an existing winShmNode that can be used.
  42862. ** If no matching winShmNode currently exists, create a new one.
  42863. */
  42864. winShmEnterMutex();
  42865. for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){
  42866. /* TBD need to come up with better match here. Perhaps
  42867. ** use FILE_ID_BOTH_DIR_INFO Structure.
  42868. */
  42869. if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break;
  42870. }
  42871. if( pShmNode ){
  42872. sqlite3_free(pNew);
  42873. }else{
  42874. int inFlags = SQLITE_OPEN_WAL;
  42875. int outFlags = 0;
  42876. pShmNode = pNew;
  42877. pNew = 0;
  42878. ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE;
  42879. pShmNode->pNext = winShmNodeList;
  42880. winShmNodeList = pShmNode;
  42881. if( sqlite3GlobalConfig.bCoreMutex ){
  42882. pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
  42883. if( pShmNode->mutex==0 ){
  42884. rc = SQLITE_IOERR_NOMEM_BKPT;
  42885. goto shm_open_err;
  42886. }
  42887. }
  42888. if( 0==sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
  42889. inFlags |= SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE;
  42890. }else{
  42891. inFlags |= SQLITE_OPEN_READONLY;
  42892. }
  42893. rc = winOpen(pDbFd->pVfs, pShmNode->zFilename,
  42894. (sqlite3_file*)&pShmNode->hFile,
  42895. inFlags, &outFlags);
  42896. if( rc!=SQLITE_OK ){
  42897. rc = winLogError(rc, osGetLastError(), "winOpenShm",
  42898. pShmNode->zFilename);
  42899. goto shm_open_err;
  42900. }
  42901. if( outFlags==SQLITE_OPEN_READONLY ) pShmNode->isReadonly = 1;
  42902. rc = winLockSharedMemory(pShmNode);
  42903. if( rc!=SQLITE_OK && rc!=SQLITE_READONLY_CANTINIT ) goto shm_open_err;
  42904. }
  42905. /* Make the new connection a child of the winShmNode */
  42906. p->pShmNode = pShmNode;
  42907. #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
  42908. p->id = pShmNode->nextShmId++;
  42909. #endif
  42910. pShmNode->nRef++;
  42911. pDbFd->pShm = p;
  42912. winShmLeaveMutex();
  42913. /* The reference count on pShmNode has already been incremented under
  42914. ** the cover of the winShmEnterMutex() mutex and the pointer from the
  42915. ** new (struct winShm) object to the pShmNode has been set. All that is
  42916. ** left to do is to link the new object into the linked list starting
  42917. ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
  42918. ** mutex.
  42919. */
  42920. sqlite3_mutex_enter(pShmNode->mutex);
  42921. p->pNext = pShmNode->pFirst;
  42922. pShmNode->pFirst = p;
  42923. sqlite3_mutex_leave(pShmNode->mutex);
  42924. return rc;
  42925. /* Jump here on any error */
  42926. shm_open_err:
  42927. winShmSystemLock(pShmNode, WINSHM_UNLCK, WIN_SHM_DMS, 1);
  42928. winShmPurge(pDbFd->pVfs, 0); /* This call frees pShmNode if required */
  42929. sqlite3_free(p);
  42930. sqlite3_free(pNew);
  42931. winShmLeaveMutex();
  42932. return rc;
  42933. }
  42934. /*
  42935. ** Close a connection to shared-memory. Delete the underlying
  42936. ** storage if deleteFlag is true.
  42937. */
  42938. static int winShmUnmap(
  42939. sqlite3_file *fd, /* Database holding shared memory */
  42940. int deleteFlag /* Delete after closing if true */
  42941. ){
  42942. winFile *pDbFd; /* Database holding shared-memory */
  42943. winShm *p; /* The connection to be closed */
  42944. winShmNode *pShmNode; /* The underlying shared-memory file */
  42945. winShm **pp; /* For looping over sibling connections */
  42946. pDbFd = (winFile*)fd;
  42947. p = pDbFd->pShm;
  42948. if( p==0 ) return SQLITE_OK;
  42949. pShmNode = p->pShmNode;
  42950. /* Remove connection p from the set of connections associated
  42951. ** with pShmNode */
  42952. sqlite3_mutex_enter(pShmNode->mutex);
  42953. for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
  42954. *pp = p->pNext;
  42955. /* Free the connection p */
  42956. sqlite3_free(p);
  42957. pDbFd->pShm = 0;
  42958. sqlite3_mutex_leave(pShmNode->mutex);
  42959. /* If pShmNode->nRef has reached 0, then close the underlying
  42960. ** shared-memory file, too */
  42961. winShmEnterMutex();
  42962. assert( pShmNode->nRef>0 );
  42963. pShmNode->nRef--;
  42964. if( pShmNode->nRef==0 ){
  42965. winShmPurge(pDbFd->pVfs, deleteFlag);
  42966. }
  42967. winShmLeaveMutex();
  42968. return SQLITE_OK;
  42969. }
  42970. /*
  42971. ** Change the lock state for a shared-memory segment.
  42972. */
  42973. static int winShmLock(
  42974. sqlite3_file *fd, /* Database file holding the shared memory */
  42975. int ofst, /* First lock to acquire or release */
  42976. int n, /* Number of locks to acquire or release */
  42977. int flags /* What to do with the lock */
  42978. ){
  42979. winFile *pDbFd = (winFile*)fd; /* Connection holding shared memory */
  42980. winShm *p = pDbFd->pShm; /* The shared memory being locked */
  42981. winShm *pX; /* For looping over all siblings */
  42982. winShmNode *pShmNode = p->pShmNode;
  42983. int rc = SQLITE_OK; /* Result code */
  42984. u16 mask; /* Mask of locks to take or release */
  42985. assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
  42986. assert( n>=1 );
  42987. assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
  42988. || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
  42989. || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
  42990. || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
  42991. assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
  42992. mask = (u16)((1U<<(ofst+n)) - (1U<<ofst));
  42993. assert( n>1 || mask==(1<<ofst) );
  42994. sqlite3_mutex_enter(pShmNode->mutex);
  42995. if( flags & SQLITE_SHM_UNLOCK ){
  42996. u16 allMask = 0; /* Mask of locks held by siblings */
  42997. /* See if any siblings hold this same lock */
  42998. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  42999. if( pX==p ) continue;
  43000. assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
  43001. allMask |= pX->sharedMask;
  43002. }
  43003. /* Unlock the system-level locks */
  43004. if( (mask & allMask)==0 ){
  43005. rc = winShmSystemLock(pShmNode, WINSHM_UNLCK, ofst+WIN_SHM_BASE, n);
  43006. }else{
  43007. rc = SQLITE_OK;
  43008. }
  43009. /* Undo the local locks */
  43010. if( rc==SQLITE_OK ){
  43011. p->exclMask &= ~mask;
  43012. p->sharedMask &= ~mask;
  43013. }
  43014. }else if( flags & SQLITE_SHM_SHARED ){
  43015. u16 allShared = 0; /* Union of locks held by connections other than "p" */
  43016. /* Find out which shared locks are already held by sibling connections.
  43017. ** If any sibling already holds an exclusive lock, go ahead and return
  43018. ** SQLITE_BUSY.
  43019. */
  43020. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  43021. if( (pX->exclMask & mask)!=0 ){
  43022. rc = SQLITE_BUSY;
  43023. break;
  43024. }
  43025. allShared |= pX->sharedMask;
  43026. }
  43027. /* Get shared locks at the system level, if necessary */
  43028. if( rc==SQLITE_OK ){
  43029. if( (allShared & mask)==0 ){
  43030. rc = winShmSystemLock(pShmNode, WINSHM_RDLCK, ofst+WIN_SHM_BASE, n);
  43031. }else{
  43032. rc = SQLITE_OK;
  43033. }
  43034. }
  43035. /* Get the local shared locks */
  43036. if( rc==SQLITE_OK ){
  43037. p->sharedMask |= mask;
  43038. }
  43039. }else{
  43040. /* Make sure no sibling connections hold locks that will block this
  43041. ** lock. If any do, return SQLITE_BUSY right away.
  43042. */
  43043. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  43044. if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
  43045. rc = SQLITE_BUSY;
  43046. break;
  43047. }
  43048. }
  43049. /* Get the exclusive locks at the system level. Then if successful
  43050. ** also mark the local connection as being locked.
  43051. */
  43052. if( rc==SQLITE_OK ){
  43053. rc = winShmSystemLock(pShmNode, WINSHM_WRLCK, ofst+WIN_SHM_BASE, n);
  43054. if( rc==SQLITE_OK ){
  43055. assert( (p->sharedMask & mask)==0 );
  43056. p->exclMask |= mask;
  43057. }
  43058. }
  43059. }
  43060. sqlite3_mutex_leave(pShmNode->mutex);
  43061. OSTRACE(("SHM-LOCK pid=%lu, id=%d, sharedMask=%03x, exclMask=%03x, rc=%s\n",
  43062. osGetCurrentProcessId(), p->id, p->sharedMask, p->exclMask,
  43063. sqlite3ErrName(rc)));
  43064. return rc;
  43065. }
  43066. /*
  43067. ** Implement a memory barrier or memory fence on shared memory.
  43068. **
  43069. ** All loads and stores begun before the barrier must complete before
  43070. ** any load or store begun after the barrier.
  43071. */
  43072. static void winShmBarrier(
  43073. sqlite3_file *fd /* Database holding the shared memory */
  43074. ){
  43075. UNUSED_PARAMETER(fd);
  43076. sqlite3MemoryBarrier(); /* compiler-defined memory barrier */
  43077. winShmEnterMutex(); /* Also mutex, for redundancy */
  43078. winShmLeaveMutex();
  43079. }
  43080. /*
  43081. ** This function is called to obtain a pointer to region iRegion of the
  43082. ** shared-memory associated with the database file fd. Shared-memory regions
  43083. ** are numbered starting from zero. Each shared-memory region is szRegion
  43084. ** bytes in size.
  43085. **
  43086. ** If an error occurs, an error code is returned and *pp is set to NULL.
  43087. **
  43088. ** Otherwise, if the isWrite parameter is 0 and the requested shared-memory
  43089. ** region has not been allocated (by any client, including one running in a
  43090. ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
  43091. ** isWrite is non-zero and the requested shared-memory region has not yet
  43092. ** been allocated, it is allocated by this function.
  43093. **
  43094. ** If the shared-memory region has already been allocated or is allocated by
  43095. ** this call as described above, then it is mapped into this processes
  43096. ** address space (if it is not already), *pp is set to point to the mapped
  43097. ** memory and SQLITE_OK returned.
  43098. */
  43099. static int winShmMap(
  43100. sqlite3_file *fd, /* Handle open on database file */
  43101. int iRegion, /* Region to retrieve */
  43102. int szRegion, /* Size of regions */
  43103. int isWrite, /* True to extend file if necessary */
  43104. void volatile **pp /* OUT: Mapped memory */
  43105. ){
  43106. winFile *pDbFd = (winFile*)fd;
  43107. winShm *pShm = pDbFd->pShm;
  43108. winShmNode *pShmNode;
  43109. DWORD protect = PAGE_READWRITE;
  43110. DWORD flags = FILE_MAP_WRITE | FILE_MAP_READ;
  43111. int rc = SQLITE_OK;
  43112. if( !pShm ){
  43113. rc = winOpenSharedMemory(pDbFd);
  43114. if( rc!=SQLITE_OK ) return rc;
  43115. pShm = pDbFd->pShm;
  43116. assert( pShm!=0 );
  43117. }
  43118. pShmNode = pShm->pShmNode;
  43119. sqlite3_mutex_enter(pShmNode->mutex);
  43120. if( pShmNode->isUnlocked ){
  43121. rc = winLockSharedMemory(pShmNode);
  43122. if( rc!=SQLITE_OK ) goto shmpage_out;
  43123. pShmNode->isUnlocked = 0;
  43124. }
  43125. assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
  43126. if( pShmNode->nRegion<=iRegion ){
  43127. struct ShmRegion *apNew; /* New aRegion[] array */
  43128. int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
  43129. sqlite3_int64 sz; /* Current size of wal-index file */
  43130. pShmNode->szRegion = szRegion;
  43131. /* The requested region is not mapped into this processes address space.
  43132. ** Check to see if it has been allocated (i.e. if the wal-index file is
  43133. ** large enough to contain the requested region).
  43134. */
  43135. rc = winFileSize((sqlite3_file *)&pShmNode->hFile, &sz);
  43136. if( rc!=SQLITE_OK ){
  43137. rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
  43138. "winShmMap1", pDbFd->zPath);
  43139. goto shmpage_out;
  43140. }
  43141. if( sz<nByte ){
  43142. /* The requested memory region does not exist. If isWrite is set to
  43143. ** zero, exit early. *pp will be set to NULL and SQLITE_OK returned.
  43144. **
  43145. ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate
  43146. ** the requested memory region.
  43147. */
  43148. if( !isWrite ) goto shmpage_out;
  43149. rc = winTruncate((sqlite3_file *)&pShmNode->hFile, nByte);
  43150. if( rc!=SQLITE_OK ){
  43151. rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
  43152. "winShmMap2", pDbFd->zPath);
  43153. goto shmpage_out;
  43154. }
  43155. }
  43156. /* Map the requested memory region into this processes address space. */
  43157. apNew = (struct ShmRegion *)sqlite3_realloc64(
  43158. pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0])
  43159. );
  43160. if( !apNew ){
  43161. rc = SQLITE_IOERR_NOMEM_BKPT;
  43162. goto shmpage_out;
  43163. }
  43164. pShmNode->aRegion = apNew;
  43165. if( pShmNode->isReadonly ){
  43166. protect = PAGE_READONLY;
  43167. flags = FILE_MAP_READ;
  43168. }
  43169. while( pShmNode->nRegion<=iRegion ){
  43170. HANDLE hMap = NULL; /* file-mapping handle */
  43171. void *pMap = 0; /* Mapped memory region */
  43172. #if SQLITE_OS_WINRT
  43173. hMap = osCreateFileMappingFromApp(pShmNode->hFile.h,
  43174. NULL, protect, nByte, NULL
  43175. );
  43176. #elif defined(SQLITE_WIN32_HAS_WIDE)
  43177. hMap = osCreateFileMappingW(pShmNode->hFile.h,
  43178. NULL, protect, 0, nByte, NULL
  43179. );
  43180. #elif defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_CREATEFILEMAPPINGA
  43181. hMap = osCreateFileMappingA(pShmNode->hFile.h,
  43182. NULL, protect, 0, nByte, NULL
  43183. );
  43184. #endif
  43185. OSTRACE(("SHM-MAP-CREATE pid=%lu, region=%d, size=%d, rc=%s\n",
  43186. osGetCurrentProcessId(), pShmNode->nRegion, nByte,
  43187. hMap ? "ok" : "failed"));
  43188. if( hMap ){
  43189. int iOffset = pShmNode->nRegion*szRegion;
  43190. int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
  43191. #if SQLITE_OS_WINRT
  43192. pMap = osMapViewOfFileFromApp(hMap, flags,
  43193. iOffset - iOffsetShift, szRegion + iOffsetShift
  43194. );
  43195. #else
  43196. pMap = osMapViewOfFile(hMap, flags,
  43197. 0, iOffset - iOffsetShift, szRegion + iOffsetShift
  43198. );
  43199. #endif
  43200. OSTRACE(("SHM-MAP-MAP pid=%lu, region=%d, offset=%d, size=%d, rc=%s\n",
  43201. osGetCurrentProcessId(), pShmNode->nRegion, iOffset,
  43202. szRegion, pMap ? "ok" : "failed"));
  43203. }
  43204. if( !pMap ){
  43205. pShmNode->lastErrno = osGetLastError();
  43206. rc = winLogError(SQLITE_IOERR_SHMMAP, pShmNode->lastErrno,
  43207. "winShmMap3", pDbFd->zPath);
  43208. if( hMap ) osCloseHandle(hMap);
  43209. goto shmpage_out;
  43210. }
  43211. pShmNode->aRegion[pShmNode->nRegion].pMap = pMap;
  43212. pShmNode->aRegion[pShmNode->nRegion].hMap = hMap;
  43213. pShmNode->nRegion++;
  43214. }
  43215. }
  43216. shmpage_out:
  43217. if( pShmNode->nRegion>iRegion ){
  43218. int iOffset = iRegion*szRegion;
  43219. int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
  43220. char *p = (char *)pShmNode->aRegion[iRegion].pMap;
  43221. *pp = (void *)&p[iOffsetShift];
  43222. }else{
  43223. *pp = 0;
  43224. }
  43225. if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
  43226. sqlite3_mutex_leave(pShmNode->mutex);
  43227. return rc;
  43228. }
  43229. #else
  43230. # define winShmMap 0
  43231. # define winShmLock 0
  43232. # define winShmBarrier 0
  43233. # define winShmUnmap 0
  43234. #endif /* #ifndef SQLITE_OMIT_WAL */
  43235. /*
  43236. ** Cleans up the mapped region of the specified file, if any.
  43237. */
  43238. #if SQLITE_MAX_MMAP_SIZE>0
  43239. static int winUnmapfile(winFile *pFile){
  43240. assert( pFile!=0 );
  43241. OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, pMapRegion=%p, "
  43242. "mmapSize=%lld, mmapSizeMax=%lld\n",
  43243. osGetCurrentProcessId(), pFile, pFile->hMap, pFile->pMapRegion,
  43244. pFile->mmapSize, pFile->mmapSizeMax));
  43245. if( pFile->pMapRegion ){
  43246. if( !osUnmapViewOfFile(pFile->pMapRegion) ){
  43247. pFile->lastErrno = osGetLastError();
  43248. OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, pMapRegion=%p, "
  43249. "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(), pFile,
  43250. pFile->pMapRegion));
  43251. return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
  43252. "winUnmapfile1", pFile->zPath);
  43253. }
  43254. pFile->pMapRegion = 0;
  43255. pFile->mmapSize = 0;
  43256. }
  43257. if( pFile->hMap!=NULL ){
  43258. if( !osCloseHandle(pFile->hMap) ){
  43259. pFile->lastErrno = osGetLastError();
  43260. OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, rc=SQLITE_IOERR_MMAP\n",
  43261. osGetCurrentProcessId(), pFile, pFile->hMap));
  43262. return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
  43263. "winUnmapfile2", pFile->zPath);
  43264. }
  43265. pFile->hMap = NULL;
  43266. }
  43267. OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
  43268. osGetCurrentProcessId(), pFile));
  43269. return SQLITE_OK;
  43270. }
  43271. /*
  43272. ** Memory map or remap the file opened by file-descriptor pFd (if the file
  43273. ** is already mapped, the existing mapping is replaced by the new). Or, if
  43274. ** there already exists a mapping for this file, and there are still
  43275. ** outstanding xFetch() references to it, this function is a no-op.
  43276. **
  43277. ** If parameter nByte is non-negative, then it is the requested size of
  43278. ** the mapping to create. Otherwise, if nByte is less than zero, then the
  43279. ** requested size is the size of the file on disk. The actual size of the
  43280. ** created mapping is either the requested size or the value configured
  43281. ** using SQLITE_FCNTL_MMAP_SIZE, whichever is smaller.
  43282. **
  43283. ** SQLITE_OK is returned if no error occurs (even if the mapping is not
  43284. ** recreated as a result of outstanding references) or an SQLite error
  43285. ** code otherwise.
  43286. */
  43287. static int winMapfile(winFile *pFd, sqlite3_int64 nByte){
  43288. sqlite3_int64 nMap = nByte;
  43289. int rc;
  43290. assert( nMap>=0 || pFd->nFetchOut==0 );
  43291. OSTRACE(("MAP-FILE pid=%lu, pFile=%p, size=%lld\n",
  43292. osGetCurrentProcessId(), pFd, nByte));
  43293. if( pFd->nFetchOut>0 ) return SQLITE_OK;
  43294. if( nMap<0 ){
  43295. rc = winFileSize((sqlite3_file*)pFd, &nMap);
  43296. if( rc ){
  43297. OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_IOERR_FSTAT\n",
  43298. osGetCurrentProcessId(), pFd));
  43299. return SQLITE_IOERR_FSTAT;
  43300. }
  43301. }
  43302. if( nMap>pFd->mmapSizeMax ){
  43303. nMap = pFd->mmapSizeMax;
  43304. }
  43305. nMap &= ~(sqlite3_int64)(winSysInfo.dwPageSize - 1);
  43306. if( nMap==0 && pFd->mmapSize>0 ){
  43307. winUnmapfile(pFd);
  43308. }
  43309. if( nMap!=pFd->mmapSize ){
  43310. void *pNew = 0;
  43311. DWORD protect = PAGE_READONLY;
  43312. DWORD flags = FILE_MAP_READ;
  43313. winUnmapfile(pFd);
  43314. #ifdef SQLITE_MMAP_READWRITE
  43315. if( (pFd->ctrlFlags & WINFILE_RDONLY)==0 ){
  43316. protect = PAGE_READWRITE;
  43317. flags |= FILE_MAP_WRITE;
  43318. }
  43319. #endif
  43320. #if SQLITE_OS_WINRT
  43321. pFd->hMap = osCreateFileMappingFromApp(pFd->h, NULL, protect, nMap, NULL);
  43322. #elif defined(SQLITE_WIN32_HAS_WIDE)
  43323. pFd->hMap = osCreateFileMappingW(pFd->h, NULL, protect,
  43324. (DWORD)((nMap>>32) & 0xffffffff),
  43325. (DWORD)(nMap & 0xffffffff), NULL);
  43326. #elif defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_CREATEFILEMAPPINGA
  43327. pFd->hMap = osCreateFileMappingA(pFd->h, NULL, protect,
  43328. (DWORD)((nMap>>32) & 0xffffffff),
  43329. (DWORD)(nMap & 0xffffffff), NULL);
  43330. #endif
  43331. if( pFd->hMap==NULL ){
  43332. pFd->lastErrno = osGetLastError();
  43333. rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
  43334. "winMapfile1", pFd->zPath);
  43335. /* Log the error, but continue normal operation using xRead/xWrite */
  43336. OSTRACE(("MAP-FILE-CREATE pid=%lu, pFile=%p, rc=%s\n",
  43337. osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
  43338. return SQLITE_OK;
  43339. }
  43340. assert( (nMap % winSysInfo.dwPageSize)==0 );
  43341. assert( sizeof(SIZE_T)==sizeof(sqlite3_int64) || nMap<=0xffffffff );
  43342. #if SQLITE_OS_WINRT
  43343. pNew = osMapViewOfFileFromApp(pFd->hMap, flags, 0, (SIZE_T)nMap);
  43344. #else
  43345. pNew = osMapViewOfFile(pFd->hMap, flags, 0, 0, (SIZE_T)nMap);
  43346. #endif
  43347. if( pNew==NULL ){
  43348. osCloseHandle(pFd->hMap);
  43349. pFd->hMap = NULL;
  43350. pFd->lastErrno = osGetLastError();
  43351. rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
  43352. "winMapfile2", pFd->zPath);
  43353. /* Log the error, but continue normal operation using xRead/xWrite */
  43354. OSTRACE(("MAP-FILE-MAP pid=%lu, pFile=%p, rc=%s\n",
  43355. osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
  43356. return SQLITE_OK;
  43357. }
  43358. pFd->pMapRegion = pNew;
  43359. pFd->mmapSize = nMap;
  43360. }
  43361. OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
  43362. osGetCurrentProcessId(), pFd));
  43363. return SQLITE_OK;
  43364. }
  43365. #endif /* SQLITE_MAX_MMAP_SIZE>0 */
  43366. /*
  43367. ** If possible, return a pointer to a mapping of file fd starting at offset
  43368. ** iOff. The mapping must be valid for at least nAmt bytes.
  43369. **
  43370. ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
  43371. ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
  43372. ** Finally, if an error does occur, return an SQLite error code. The final
  43373. ** value of *pp is undefined in this case.
  43374. **
  43375. ** If this function does return a pointer, the caller must eventually
  43376. ** release the reference by calling winUnfetch().
  43377. */
  43378. static int winFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
  43379. #if SQLITE_MAX_MMAP_SIZE>0
  43380. winFile *pFd = (winFile*)fd; /* The underlying database file */
  43381. #endif
  43382. *pp = 0;
  43383. OSTRACE(("FETCH pid=%lu, pFile=%p, offset=%lld, amount=%d, pp=%p\n",
  43384. osGetCurrentProcessId(), fd, iOff, nAmt, pp));
  43385. #if SQLITE_MAX_MMAP_SIZE>0
  43386. if( pFd->mmapSizeMax>0 ){
  43387. if( pFd->pMapRegion==0 ){
  43388. int rc = winMapfile(pFd, -1);
  43389. if( rc!=SQLITE_OK ){
  43390. OSTRACE(("FETCH pid=%lu, pFile=%p, rc=%s\n",
  43391. osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
  43392. return rc;
  43393. }
  43394. }
  43395. if( pFd->mmapSize >= iOff+nAmt ){
  43396. assert( pFd->pMapRegion!=0 );
  43397. *pp = &((u8 *)pFd->pMapRegion)[iOff];
  43398. pFd->nFetchOut++;
  43399. }
  43400. }
  43401. #endif
  43402. OSTRACE(("FETCH pid=%lu, pFile=%p, pp=%p, *pp=%p, rc=SQLITE_OK\n",
  43403. osGetCurrentProcessId(), fd, pp, *pp));
  43404. return SQLITE_OK;
  43405. }
  43406. /*
  43407. ** If the third argument is non-NULL, then this function releases a
  43408. ** reference obtained by an earlier call to winFetch(). The second
  43409. ** argument passed to this function must be the same as the corresponding
  43410. ** argument that was passed to the winFetch() invocation.
  43411. **
  43412. ** Or, if the third argument is NULL, then this function is being called
  43413. ** to inform the VFS layer that, according to POSIX, any existing mapping
  43414. ** may now be invalid and should be unmapped.
  43415. */
  43416. static int winUnfetch(sqlite3_file *fd, i64 iOff, void *p){
  43417. #if SQLITE_MAX_MMAP_SIZE>0
  43418. winFile *pFd = (winFile*)fd; /* The underlying database file */
  43419. /* If p==0 (unmap the entire file) then there must be no outstanding
  43420. ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
  43421. ** then there must be at least one outstanding. */
  43422. assert( (p==0)==(pFd->nFetchOut==0) );
  43423. /* If p!=0, it must match the iOff value. */
  43424. assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
  43425. OSTRACE(("UNFETCH pid=%lu, pFile=%p, offset=%lld, p=%p\n",
  43426. osGetCurrentProcessId(), pFd, iOff, p));
  43427. if( p ){
  43428. pFd->nFetchOut--;
  43429. }else{
  43430. /* FIXME: If Windows truly always prevents truncating or deleting a
  43431. ** file while a mapping is held, then the following winUnmapfile() call
  43432. ** is unnecessary can be omitted - potentially improving
  43433. ** performance. */
  43434. winUnmapfile(pFd);
  43435. }
  43436. assert( pFd->nFetchOut>=0 );
  43437. #endif
  43438. OSTRACE(("UNFETCH pid=%lu, pFile=%p, rc=SQLITE_OK\n",
  43439. osGetCurrentProcessId(), fd));
  43440. return SQLITE_OK;
  43441. }
  43442. /*
  43443. ** Here ends the implementation of all sqlite3_file methods.
  43444. **
  43445. ********************** End sqlite3_file Methods *******************************
  43446. ******************************************************************************/
  43447. /*
  43448. ** This vector defines all the methods that can operate on an
  43449. ** sqlite3_file for win32.
  43450. */
  43451. static const sqlite3_io_methods winIoMethod = {
  43452. 3, /* iVersion */
  43453. winClose, /* xClose */
  43454. winRead, /* xRead */
  43455. winWrite, /* xWrite */
  43456. winTruncate, /* xTruncate */
  43457. winSync, /* xSync */
  43458. winFileSize, /* xFileSize */
  43459. winLock, /* xLock */
  43460. winUnlock, /* xUnlock */
  43461. winCheckReservedLock, /* xCheckReservedLock */
  43462. winFileControl, /* xFileControl */
  43463. winSectorSize, /* xSectorSize */
  43464. winDeviceCharacteristics, /* xDeviceCharacteristics */
  43465. winShmMap, /* xShmMap */
  43466. winShmLock, /* xShmLock */
  43467. winShmBarrier, /* xShmBarrier */
  43468. winShmUnmap, /* xShmUnmap */
  43469. winFetch, /* xFetch */
  43470. winUnfetch /* xUnfetch */
  43471. };
  43472. /*
  43473. ** This vector defines all the methods that can operate on an
  43474. ** sqlite3_file for win32 without performing any locking.
  43475. */
  43476. static const sqlite3_io_methods winIoNolockMethod = {
  43477. 3, /* iVersion */
  43478. winClose, /* xClose */
  43479. winRead, /* xRead */
  43480. winWrite, /* xWrite */
  43481. winTruncate, /* xTruncate */
  43482. winSync, /* xSync */
  43483. winFileSize, /* xFileSize */
  43484. winNolockLock, /* xLock */
  43485. winNolockUnlock, /* xUnlock */
  43486. winNolockCheckReservedLock, /* xCheckReservedLock */
  43487. winFileControl, /* xFileControl */
  43488. winSectorSize, /* xSectorSize */
  43489. winDeviceCharacteristics, /* xDeviceCharacteristics */
  43490. winShmMap, /* xShmMap */
  43491. winShmLock, /* xShmLock */
  43492. winShmBarrier, /* xShmBarrier */
  43493. winShmUnmap, /* xShmUnmap */
  43494. winFetch, /* xFetch */
  43495. winUnfetch /* xUnfetch */
  43496. };
  43497. static winVfsAppData winAppData = {
  43498. &winIoMethod, /* pMethod */
  43499. 0, /* pAppData */
  43500. 0 /* bNoLock */
  43501. };
  43502. static winVfsAppData winNolockAppData = {
  43503. &winIoNolockMethod, /* pMethod */
  43504. 0, /* pAppData */
  43505. 1 /* bNoLock */
  43506. };
  43507. /****************************************************************************
  43508. **************************** sqlite3_vfs methods ****************************
  43509. **
  43510. ** This division contains the implementation of methods on the
  43511. ** sqlite3_vfs object.
  43512. */
  43513. #if defined(__CYGWIN__)
  43514. /*
  43515. ** Convert a filename from whatever the underlying operating system
  43516. ** supports for filenames into UTF-8. Space to hold the result is
  43517. ** obtained from malloc and must be freed by the calling function.
  43518. */
  43519. static char *winConvertToUtf8Filename(const void *zFilename){
  43520. char *zConverted = 0;
  43521. if( osIsNT() ){
  43522. zConverted = winUnicodeToUtf8(zFilename);
  43523. }
  43524. #ifdef SQLITE_WIN32_HAS_ANSI
  43525. else{
  43526. zConverted = winMbcsToUtf8(zFilename, osAreFileApisANSI());
  43527. }
  43528. #endif
  43529. /* caller will handle out of memory */
  43530. return zConverted;
  43531. }
  43532. #endif
  43533. /*
  43534. ** Convert a UTF-8 filename into whatever form the underlying
  43535. ** operating system wants filenames in. Space to hold the result
  43536. ** is obtained from malloc and must be freed by the calling
  43537. ** function.
  43538. */
  43539. static void *winConvertFromUtf8Filename(const char *zFilename){
  43540. void *zConverted = 0;
  43541. if( osIsNT() ){
  43542. zConverted = winUtf8ToUnicode(zFilename);
  43543. }
  43544. #ifdef SQLITE_WIN32_HAS_ANSI
  43545. else{
  43546. zConverted = winUtf8ToMbcs(zFilename, osAreFileApisANSI());
  43547. }
  43548. #endif
  43549. /* caller will handle out of memory */
  43550. return zConverted;
  43551. }
  43552. /*
  43553. ** This function returns non-zero if the specified UTF-8 string buffer
  43554. ** ends with a directory separator character or one was successfully
  43555. ** added to it.
  43556. */
  43557. static int winMakeEndInDirSep(int nBuf, char *zBuf){
  43558. if( zBuf ){
  43559. int nLen = sqlite3Strlen30(zBuf);
  43560. if( nLen>0 ){
  43561. if( winIsDirSep(zBuf[nLen-1]) ){
  43562. return 1;
  43563. }else if( nLen+1<nBuf ){
  43564. zBuf[nLen] = winGetDirSep();
  43565. zBuf[nLen+1] = '\0';
  43566. return 1;
  43567. }
  43568. }
  43569. }
  43570. return 0;
  43571. }
  43572. /*
  43573. ** Create a temporary file name and store the resulting pointer into pzBuf.
  43574. ** The pointer returned in pzBuf must be freed via sqlite3_free().
  43575. */
  43576. static int winGetTempname(sqlite3_vfs *pVfs, char **pzBuf){
  43577. static char zChars[] =
  43578. "abcdefghijklmnopqrstuvwxyz"
  43579. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  43580. "0123456789";
  43581. size_t i, j;
  43582. int nPre = sqlite3Strlen30(SQLITE_TEMP_FILE_PREFIX);
  43583. int nMax, nBuf, nDir, nLen;
  43584. char *zBuf;
  43585. /* It's odd to simulate an io-error here, but really this is just
  43586. ** using the io-error infrastructure to test that SQLite handles this
  43587. ** function failing.
  43588. */
  43589. SimulateIOError( return SQLITE_IOERR );
  43590. /* Allocate a temporary buffer to store the fully qualified file
  43591. ** name for the temporary file. If this fails, we cannot continue.
  43592. */
  43593. nMax = pVfs->mxPathname; nBuf = nMax + 2;
  43594. zBuf = sqlite3MallocZero( nBuf );
  43595. if( !zBuf ){
  43596. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  43597. return SQLITE_IOERR_NOMEM_BKPT;
  43598. }
  43599. /* Figure out the effective temporary directory. First, check if one
  43600. ** has been explicitly set by the application; otherwise, use the one
  43601. ** configured by the operating system.
  43602. */
  43603. nDir = nMax - (nPre + 15);
  43604. assert( nDir>0 );
  43605. if( sqlite3_temp_directory ){
  43606. int nDirLen = sqlite3Strlen30(sqlite3_temp_directory);
  43607. if( nDirLen>0 ){
  43608. if( !winIsDirSep(sqlite3_temp_directory[nDirLen-1]) ){
  43609. nDirLen++;
  43610. }
  43611. if( nDirLen>nDir ){
  43612. sqlite3_free(zBuf);
  43613. OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
  43614. return winLogError(SQLITE_ERROR, 0, "winGetTempname1", 0);
  43615. }
  43616. sqlite3_snprintf(nMax, zBuf, "%s", sqlite3_temp_directory);
  43617. }
  43618. }
  43619. #if defined(__CYGWIN__)
  43620. else{
  43621. static const char *azDirs[] = {
  43622. 0, /* getenv("SQLITE_TMPDIR") */
  43623. 0, /* getenv("TMPDIR") */
  43624. 0, /* getenv("TMP") */
  43625. 0, /* getenv("TEMP") */
  43626. 0, /* getenv("USERPROFILE") */
  43627. "/var/tmp",
  43628. "/usr/tmp",
  43629. "/tmp",
  43630. ".",
  43631. 0 /* List terminator */
  43632. };
  43633. unsigned int i;
  43634. const char *zDir = 0;
  43635. if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
  43636. if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
  43637. if( !azDirs[2] ) azDirs[2] = getenv("TMP");
  43638. if( !azDirs[3] ) azDirs[3] = getenv("TEMP");
  43639. if( !azDirs[4] ) azDirs[4] = getenv("USERPROFILE");
  43640. for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
  43641. void *zConverted;
  43642. if( zDir==0 ) continue;
  43643. /* If the path starts with a drive letter followed by the colon
  43644. ** character, assume it is already a native Win32 path; otherwise,
  43645. ** it must be converted to a native Win32 path via the Cygwin API
  43646. ** prior to using it.
  43647. */
  43648. if( winIsDriveLetterAndColon(zDir) ){
  43649. zConverted = winConvertFromUtf8Filename(zDir);
  43650. if( !zConverted ){
  43651. sqlite3_free(zBuf);
  43652. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  43653. return SQLITE_IOERR_NOMEM_BKPT;
  43654. }
  43655. if( winIsDir(zConverted) ){
  43656. sqlite3_snprintf(nMax, zBuf, "%s", zDir);
  43657. sqlite3_free(zConverted);
  43658. break;
  43659. }
  43660. sqlite3_free(zConverted);
  43661. }else{
  43662. zConverted = sqlite3MallocZero( nMax+1 );
  43663. if( !zConverted ){
  43664. sqlite3_free(zBuf);
  43665. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  43666. return SQLITE_IOERR_NOMEM_BKPT;
  43667. }
  43668. if( cygwin_conv_path(
  43669. osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A, zDir,
  43670. zConverted, nMax+1)<0 ){
  43671. sqlite3_free(zConverted);
  43672. sqlite3_free(zBuf);
  43673. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_CONVPATH\n"));
  43674. return winLogError(SQLITE_IOERR_CONVPATH, (DWORD)errno,
  43675. "winGetTempname2", zDir);
  43676. }
  43677. if( winIsDir(zConverted) ){
  43678. /* At this point, we know the candidate directory exists and should
  43679. ** be used. However, we may need to convert the string containing
  43680. ** its name into UTF-8 (i.e. if it is UTF-16 right now).
  43681. */
  43682. char *zUtf8 = winConvertToUtf8Filename(zConverted);
  43683. if( !zUtf8 ){
  43684. sqlite3_free(zConverted);
  43685. sqlite3_free(zBuf);
  43686. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  43687. return SQLITE_IOERR_NOMEM_BKPT;
  43688. }
  43689. sqlite3_snprintf(nMax, zBuf, "%s", zUtf8);
  43690. sqlite3_free(zUtf8);
  43691. sqlite3_free(zConverted);
  43692. break;
  43693. }
  43694. sqlite3_free(zConverted);
  43695. }
  43696. }
  43697. }
  43698. #elif !SQLITE_OS_WINRT && !defined(__CYGWIN__)
  43699. else if( osIsNT() ){
  43700. char *zMulti;
  43701. LPWSTR zWidePath = sqlite3MallocZero( nMax*sizeof(WCHAR) );
  43702. if( !zWidePath ){
  43703. sqlite3_free(zBuf);
  43704. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  43705. return SQLITE_IOERR_NOMEM_BKPT;
  43706. }
  43707. if( osGetTempPathW(nMax, zWidePath)==0 ){
  43708. sqlite3_free(zWidePath);
  43709. sqlite3_free(zBuf);
  43710. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
  43711. return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
  43712. "winGetTempname2", 0);
  43713. }
  43714. zMulti = winUnicodeToUtf8(zWidePath);
  43715. if( zMulti ){
  43716. sqlite3_snprintf(nMax, zBuf, "%s", zMulti);
  43717. sqlite3_free(zMulti);
  43718. sqlite3_free(zWidePath);
  43719. }else{
  43720. sqlite3_free(zWidePath);
  43721. sqlite3_free(zBuf);
  43722. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  43723. return SQLITE_IOERR_NOMEM_BKPT;
  43724. }
  43725. }
  43726. #ifdef SQLITE_WIN32_HAS_ANSI
  43727. else{
  43728. char *zUtf8;
  43729. char *zMbcsPath = sqlite3MallocZero( nMax );
  43730. if( !zMbcsPath ){
  43731. sqlite3_free(zBuf);
  43732. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  43733. return SQLITE_IOERR_NOMEM_BKPT;
  43734. }
  43735. if( osGetTempPathA(nMax, zMbcsPath)==0 ){
  43736. sqlite3_free(zBuf);
  43737. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
  43738. return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
  43739. "winGetTempname3", 0);
  43740. }
  43741. zUtf8 = winMbcsToUtf8(zMbcsPath, osAreFileApisANSI());
  43742. if( zUtf8 ){
  43743. sqlite3_snprintf(nMax, zBuf, "%s", zUtf8);
  43744. sqlite3_free(zUtf8);
  43745. }else{
  43746. sqlite3_free(zBuf);
  43747. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  43748. return SQLITE_IOERR_NOMEM_BKPT;
  43749. }
  43750. }
  43751. #endif /* SQLITE_WIN32_HAS_ANSI */
  43752. #endif /* !SQLITE_OS_WINRT */
  43753. /*
  43754. ** Check to make sure the temporary directory ends with an appropriate
  43755. ** separator. If it does not and there is not enough space left to add
  43756. ** one, fail.
  43757. */
  43758. if( !winMakeEndInDirSep(nDir+1, zBuf) ){
  43759. sqlite3_free(zBuf);
  43760. OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
  43761. return winLogError(SQLITE_ERROR, 0, "winGetTempname4", 0);
  43762. }
  43763. /*
  43764. ** Check that the output buffer is large enough for the temporary file
  43765. ** name in the following format:
  43766. **
  43767. ** "<temporary_directory>/etilqs_XXXXXXXXXXXXXXX\0\0"
  43768. **
  43769. ** If not, return SQLITE_ERROR. The number 17 is used here in order to
  43770. ** account for the space used by the 15 character random suffix and the
  43771. ** two trailing NUL characters. The final directory separator character
  43772. ** has already added if it was not already present.
  43773. */
  43774. nLen = sqlite3Strlen30(zBuf);
  43775. if( (nLen + nPre + 17) > nBuf ){
  43776. sqlite3_free(zBuf);
  43777. OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
  43778. return winLogError(SQLITE_ERROR, 0, "winGetTempname5", 0);
  43779. }
  43780. sqlite3_snprintf(nBuf-16-nLen, zBuf+nLen, SQLITE_TEMP_FILE_PREFIX);
  43781. j = sqlite3Strlen30(zBuf);
  43782. sqlite3_randomness(15, &zBuf[j]);
  43783. for(i=0; i<15; i++, j++){
  43784. zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
  43785. }
  43786. zBuf[j] = 0;
  43787. zBuf[j+1] = 0;
  43788. *pzBuf = zBuf;
  43789. OSTRACE(("TEMP-FILENAME name=%s, rc=SQLITE_OK\n", zBuf));
  43790. return SQLITE_OK;
  43791. }
  43792. /*
  43793. ** Return TRUE if the named file is really a directory. Return false if
  43794. ** it is something other than a directory, or if there is any kind of memory
  43795. ** allocation failure.
  43796. */
  43797. static int winIsDir(const void *zConverted){
  43798. DWORD attr;
  43799. int rc = 0;
  43800. DWORD lastErrno;
  43801. if( osIsNT() ){
  43802. int cnt = 0;
  43803. WIN32_FILE_ATTRIBUTE_DATA sAttrData;
  43804. memset(&sAttrData, 0, sizeof(sAttrData));
  43805. while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
  43806. GetFileExInfoStandard,
  43807. &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
  43808. if( !rc ){
  43809. return 0; /* Invalid name? */
  43810. }
  43811. attr = sAttrData.dwFileAttributes;
  43812. #if SQLITE_OS_WINCE==0
  43813. }else{
  43814. attr = osGetFileAttributesA((char*)zConverted);
  43815. #endif
  43816. }
  43817. return (attr!=INVALID_FILE_ATTRIBUTES) && (attr&FILE_ATTRIBUTE_DIRECTORY);
  43818. }
  43819. /* forward reference */
  43820. static int winAccess(
  43821. sqlite3_vfs *pVfs, /* Not used on win32 */
  43822. const char *zFilename, /* Name of file to check */
  43823. int flags, /* Type of test to make on this file */
  43824. int *pResOut /* OUT: Result */
  43825. );
  43826. /*
  43827. ** Open a file.
  43828. */
  43829. static int winOpen(
  43830. sqlite3_vfs *pVfs, /* Used to get maximum path length and AppData */
  43831. const char *zName, /* Name of the file (UTF-8) */
  43832. sqlite3_file *id, /* Write the SQLite file handle here */
  43833. int flags, /* Open mode flags */
  43834. int *pOutFlags /* Status return flags */
  43835. ){
  43836. HANDLE h;
  43837. DWORD lastErrno = 0;
  43838. DWORD dwDesiredAccess;
  43839. DWORD dwShareMode;
  43840. DWORD dwCreationDisposition;
  43841. DWORD dwFlagsAndAttributes = 0;
  43842. #if SQLITE_OS_WINCE
  43843. int isTemp = 0;
  43844. #endif
  43845. winVfsAppData *pAppData;
  43846. winFile *pFile = (winFile*)id;
  43847. void *zConverted; /* Filename in OS encoding */
  43848. const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */
  43849. int cnt = 0;
  43850. /* If argument zPath is a NULL pointer, this function is required to open
  43851. ** a temporary file. Use this buffer to store the file name in.
  43852. */
  43853. char *zTmpname = 0; /* For temporary filename, if necessary. */
  43854. int rc = SQLITE_OK; /* Function Return Code */
  43855. #if !defined(NDEBUG) || SQLITE_OS_WINCE
  43856. int eType = flags&0xFFFFFF00; /* Type of file to open */
  43857. #endif
  43858. int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
  43859. int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
  43860. int isCreate = (flags & SQLITE_OPEN_CREATE);
  43861. int isReadonly = (flags & SQLITE_OPEN_READONLY);
  43862. int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
  43863. #ifndef NDEBUG
  43864. int isOpenJournal = (isCreate && (
  43865. eType==SQLITE_OPEN_MASTER_JOURNAL
  43866. || eType==SQLITE_OPEN_MAIN_JOURNAL
  43867. || eType==SQLITE_OPEN_WAL
  43868. ));
  43869. #endif
  43870. OSTRACE(("OPEN name=%s, pFile=%p, flags=%x, pOutFlags=%p\n",
  43871. zUtf8Name, id, flags, pOutFlags));
  43872. /* Check the following statements are true:
  43873. **
  43874. ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
  43875. ** (b) if CREATE is set, then READWRITE must also be set, and
  43876. ** (c) if EXCLUSIVE is set, then CREATE must also be set.
  43877. ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
  43878. */
  43879. assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
  43880. assert(isCreate==0 || isReadWrite);
  43881. assert(isExclusive==0 || isCreate);
  43882. assert(isDelete==0 || isCreate);
  43883. /* The main DB, main journal, WAL file and master journal are never
  43884. ** automatically deleted. Nor are they ever temporary files. */
  43885. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
  43886. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
  43887. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
  43888. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
  43889. /* Assert that the upper layer has set one of the "file-type" flags. */
  43890. assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
  43891. || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
  43892. || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
  43893. || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
  43894. );
  43895. assert( pFile!=0 );
  43896. memset(pFile, 0, sizeof(winFile));
  43897. pFile->h = INVALID_HANDLE_VALUE;
  43898. #if SQLITE_OS_WINRT
  43899. if( !zUtf8Name && !sqlite3_temp_directory ){
  43900. sqlite3_log(SQLITE_ERROR,
  43901. "sqlite3_temp_directory variable should be set for WinRT");
  43902. }
  43903. #endif
  43904. /* If the second argument to this function is NULL, generate a
  43905. ** temporary file name to use
  43906. */
  43907. if( !zUtf8Name ){
  43908. assert( isDelete && !isOpenJournal );
  43909. rc = winGetTempname(pVfs, &zTmpname);
  43910. if( rc!=SQLITE_OK ){
  43911. OSTRACE(("OPEN name=%s, rc=%s", zUtf8Name, sqlite3ErrName(rc)));
  43912. return rc;
  43913. }
  43914. zUtf8Name = zTmpname;
  43915. }
  43916. /* Database filenames are double-zero terminated if they are not
  43917. ** URIs with parameters. Hence, they can always be passed into
  43918. ** sqlite3_uri_parameter().
  43919. */
  43920. assert( (eType!=SQLITE_OPEN_MAIN_DB) || (flags & SQLITE_OPEN_URI) ||
  43921. zUtf8Name[sqlite3Strlen30(zUtf8Name)+1]==0 );
  43922. /* Convert the filename to the system encoding. */
  43923. zConverted = winConvertFromUtf8Filename(zUtf8Name);
  43924. if( zConverted==0 ){
  43925. sqlite3_free(zTmpname);
  43926. OSTRACE(("OPEN name=%s, rc=SQLITE_IOERR_NOMEM", zUtf8Name));
  43927. return SQLITE_IOERR_NOMEM_BKPT;
  43928. }
  43929. if( winIsDir(zConverted) ){
  43930. sqlite3_free(zConverted);
  43931. sqlite3_free(zTmpname);
  43932. OSTRACE(("OPEN name=%s, rc=SQLITE_CANTOPEN_ISDIR", zUtf8Name));
  43933. return SQLITE_CANTOPEN_ISDIR;
  43934. }
  43935. if( isReadWrite ){
  43936. dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
  43937. }else{
  43938. dwDesiredAccess = GENERIC_READ;
  43939. }
  43940. /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is
  43941. ** created. SQLite doesn't use it to indicate "exclusive access"
  43942. ** as it is usually understood.
  43943. */
  43944. if( isExclusive ){
  43945. /* Creates a new file, only if it does not already exist. */
  43946. /* If the file exists, it fails. */
  43947. dwCreationDisposition = CREATE_NEW;
  43948. }else if( isCreate ){
  43949. /* Open existing file, or create if it doesn't exist */
  43950. dwCreationDisposition = OPEN_ALWAYS;
  43951. }else{
  43952. /* Opens a file, only if it exists. */
  43953. dwCreationDisposition = OPEN_EXISTING;
  43954. }
  43955. dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
  43956. if( isDelete ){
  43957. #if SQLITE_OS_WINCE
  43958. dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
  43959. isTemp = 1;
  43960. #else
  43961. dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
  43962. | FILE_ATTRIBUTE_HIDDEN
  43963. | FILE_FLAG_DELETE_ON_CLOSE;
  43964. #endif
  43965. }else{
  43966. dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
  43967. }
  43968. /* Reports from the internet are that performance is always
  43969. ** better if FILE_FLAG_RANDOM_ACCESS is used. Ticket #2699. */
  43970. #if SQLITE_OS_WINCE
  43971. dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
  43972. #endif
  43973. if( osIsNT() ){
  43974. #if SQLITE_OS_WINRT
  43975. CREATEFILE2_EXTENDED_PARAMETERS extendedParameters;
  43976. extendedParameters.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
  43977. extendedParameters.dwFileAttributes =
  43978. dwFlagsAndAttributes & FILE_ATTRIBUTE_MASK;
  43979. extendedParameters.dwFileFlags = dwFlagsAndAttributes & FILE_FLAG_MASK;
  43980. extendedParameters.dwSecurityQosFlags = SECURITY_ANONYMOUS;
  43981. extendedParameters.lpSecurityAttributes = NULL;
  43982. extendedParameters.hTemplateFile = NULL;
  43983. do{
  43984. h = osCreateFile2((LPCWSTR)zConverted,
  43985. dwDesiredAccess,
  43986. dwShareMode,
  43987. dwCreationDisposition,
  43988. &extendedParameters);
  43989. if( h!=INVALID_HANDLE_VALUE ) break;
  43990. if( isReadWrite ){
  43991. int rc2, isRO = 0;
  43992. sqlite3BeginBenignMalloc();
  43993. rc2 = winAccess(pVfs, zName, SQLITE_ACCESS_READ, &isRO);
  43994. sqlite3EndBenignMalloc();
  43995. if( rc2==SQLITE_OK && isRO ) break;
  43996. }
  43997. }while( winRetryIoerr(&cnt, &lastErrno) );
  43998. #else
  43999. do{
  44000. h = osCreateFileW((LPCWSTR)zConverted,
  44001. dwDesiredAccess,
  44002. dwShareMode, NULL,
  44003. dwCreationDisposition,
  44004. dwFlagsAndAttributes,
  44005. NULL);
  44006. if( h!=INVALID_HANDLE_VALUE ) break;
  44007. if( isReadWrite ){
  44008. int rc2, isRO = 0;
  44009. sqlite3BeginBenignMalloc();
  44010. rc2 = winAccess(pVfs, zName, SQLITE_ACCESS_READ, &isRO);
  44011. sqlite3EndBenignMalloc();
  44012. if( rc2==SQLITE_OK && isRO ) break;
  44013. }
  44014. }while( winRetryIoerr(&cnt, &lastErrno) );
  44015. #endif
  44016. }
  44017. #ifdef SQLITE_WIN32_HAS_ANSI
  44018. else{
  44019. do{
  44020. h = osCreateFileA((LPCSTR)zConverted,
  44021. dwDesiredAccess,
  44022. dwShareMode, NULL,
  44023. dwCreationDisposition,
  44024. dwFlagsAndAttributes,
  44025. NULL);
  44026. if( h!=INVALID_HANDLE_VALUE ) break;
  44027. if( isReadWrite ){
  44028. int rc2, isRO = 0;
  44029. sqlite3BeginBenignMalloc();
  44030. rc2 = winAccess(pVfs, zName, SQLITE_ACCESS_READ, &isRO);
  44031. sqlite3EndBenignMalloc();
  44032. if( rc2==SQLITE_OK && isRO ) break;
  44033. }
  44034. }while( winRetryIoerr(&cnt, &lastErrno) );
  44035. }
  44036. #endif
  44037. winLogIoerr(cnt, __LINE__);
  44038. OSTRACE(("OPEN file=%p, name=%s, access=%lx, rc=%s\n", h, zUtf8Name,
  44039. dwDesiredAccess, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
  44040. if( h==INVALID_HANDLE_VALUE ){
  44041. sqlite3_free(zConverted);
  44042. sqlite3_free(zTmpname);
  44043. if( isReadWrite && !isExclusive ){
  44044. return winOpen(pVfs, zName, id,
  44045. ((flags|SQLITE_OPEN_READONLY) &
  44046. ~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)),
  44047. pOutFlags);
  44048. }else{
  44049. pFile->lastErrno = lastErrno;
  44050. winLogError(SQLITE_CANTOPEN, pFile->lastErrno, "winOpen", zUtf8Name);
  44051. return SQLITE_CANTOPEN_BKPT;
  44052. }
  44053. }
  44054. if( pOutFlags ){
  44055. if( isReadWrite ){
  44056. *pOutFlags = SQLITE_OPEN_READWRITE;
  44057. }else{
  44058. *pOutFlags = SQLITE_OPEN_READONLY;
  44059. }
  44060. }
  44061. OSTRACE(("OPEN file=%p, name=%s, access=%lx, pOutFlags=%p, *pOutFlags=%d, "
  44062. "rc=%s\n", h, zUtf8Name, dwDesiredAccess, pOutFlags, pOutFlags ?
  44063. *pOutFlags : 0, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
  44064. pAppData = (winVfsAppData*)pVfs->pAppData;
  44065. #if SQLITE_OS_WINCE
  44066. {
  44067. if( isReadWrite && eType==SQLITE_OPEN_MAIN_DB
  44068. && ((pAppData==NULL) || !pAppData->bNoLock)
  44069. && (rc = winceCreateLock(zName, pFile))!=SQLITE_OK
  44070. ){
  44071. osCloseHandle(h);
  44072. sqlite3_free(zConverted);
  44073. sqlite3_free(zTmpname);
  44074. OSTRACE(("OPEN-CE-LOCK name=%s, rc=%s\n", zName, sqlite3ErrName(rc)));
  44075. return rc;
  44076. }
  44077. }
  44078. if( isTemp ){
  44079. pFile->zDeleteOnClose = zConverted;
  44080. }else
  44081. #endif
  44082. {
  44083. sqlite3_free(zConverted);
  44084. }
  44085. sqlite3_free(zTmpname);
  44086. pFile->pMethod = pAppData ? pAppData->pMethod : &winIoMethod;
  44087. pFile->pVfs = pVfs;
  44088. pFile->h = h;
  44089. if( isReadonly ){
  44090. pFile->ctrlFlags |= WINFILE_RDONLY;
  44091. }
  44092. if( (flags & SQLITE_OPEN_MAIN_DB)
  44093. && sqlite3_uri_boolean(zName, "psow", SQLITE_POWERSAFE_OVERWRITE)
  44094. ){
  44095. pFile->ctrlFlags |= WINFILE_PSOW;
  44096. }
  44097. pFile->lastErrno = NO_ERROR;
  44098. pFile->zPath = zName;
  44099. #if SQLITE_MAX_MMAP_SIZE>0
  44100. pFile->hMap = NULL;
  44101. pFile->pMapRegion = 0;
  44102. pFile->mmapSize = 0;
  44103. pFile->mmapSizeMax = sqlite3GlobalConfig.szMmap;
  44104. #endif
  44105. OpenCounter(+1);
  44106. return rc;
  44107. }
  44108. /*
  44109. ** Delete the named file.
  44110. **
  44111. ** Note that Windows does not allow a file to be deleted if some other
  44112. ** process has it open. Sometimes a virus scanner or indexing program
  44113. ** will open a journal file shortly after it is created in order to do
  44114. ** whatever it does. While this other process is holding the
  44115. ** file open, we will be unable to delete it. To work around this
  44116. ** problem, we delay 100 milliseconds and try to delete again. Up
  44117. ** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
  44118. ** up and returning an error.
  44119. */
  44120. static int winDelete(
  44121. sqlite3_vfs *pVfs, /* Not used on win32 */
  44122. const char *zFilename, /* Name of file to delete */
  44123. int syncDir /* Not used on win32 */
  44124. ){
  44125. int cnt = 0;
  44126. int rc;
  44127. DWORD attr;
  44128. DWORD lastErrno = 0;
  44129. void *zConverted;
  44130. UNUSED_PARAMETER(pVfs);
  44131. UNUSED_PARAMETER(syncDir);
  44132. SimulateIOError(return SQLITE_IOERR_DELETE);
  44133. OSTRACE(("DELETE name=%s, syncDir=%d\n", zFilename, syncDir));
  44134. zConverted = winConvertFromUtf8Filename(zFilename);
  44135. if( zConverted==0 ){
  44136. OSTRACE(("DELETE name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
  44137. return SQLITE_IOERR_NOMEM_BKPT;
  44138. }
  44139. if( osIsNT() ){
  44140. do {
  44141. #if SQLITE_OS_WINRT
  44142. WIN32_FILE_ATTRIBUTE_DATA sAttrData;
  44143. memset(&sAttrData, 0, sizeof(sAttrData));
  44144. if ( osGetFileAttributesExW(zConverted, GetFileExInfoStandard,
  44145. &sAttrData) ){
  44146. attr = sAttrData.dwFileAttributes;
  44147. }else{
  44148. lastErrno = osGetLastError();
  44149. if( lastErrno==ERROR_FILE_NOT_FOUND
  44150. || lastErrno==ERROR_PATH_NOT_FOUND ){
  44151. rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
  44152. }else{
  44153. rc = SQLITE_ERROR;
  44154. }
  44155. break;
  44156. }
  44157. #else
  44158. attr = osGetFileAttributesW(zConverted);
  44159. #endif
  44160. if ( attr==INVALID_FILE_ATTRIBUTES ){
  44161. lastErrno = osGetLastError();
  44162. if( lastErrno==ERROR_FILE_NOT_FOUND
  44163. || lastErrno==ERROR_PATH_NOT_FOUND ){
  44164. rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
  44165. }else{
  44166. rc = SQLITE_ERROR;
  44167. }
  44168. break;
  44169. }
  44170. if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
  44171. rc = SQLITE_ERROR; /* Files only. */
  44172. break;
  44173. }
  44174. if ( osDeleteFileW(zConverted) ){
  44175. rc = SQLITE_OK; /* Deleted OK. */
  44176. break;
  44177. }
  44178. if ( !winRetryIoerr(&cnt, &lastErrno) ){
  44179. rc = SQLITE_ERROR; /* No more retries. */
  44180. break;
  44181. }
  44182. } while(1);
  44183. }
  44184. #ifdef SQLITE_WIN32_HAS_ANSI
  44185. else{
  44186. do {
  44187. attr = osGetFileAttributesA(zConverted);
  44188. if ( attr==INVALID_FILE_ATTRIBUTES ){
  44189. lastErrno = osGetLastError();
  44190. if( lastErrno==ERROR_FILE_NOT_FOUND
  44191. || lastErrno==ERROR_PATH_NOT_FOUND ){
  44192. rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
  44193. }else{
  44194. rc = SQLITE_ERROR;
  44195. }
  44196. break;
  44197. }
  44198. if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
  44199. rc = SQLITE_ERROR; /* Files only. */
  44200. break;
  44201. }
  44202. if ( osDeleteFileA(zConverted) ){
  44203. rc = SQLITE_OK; /* Deleted OK. */
  44204. break;
  44205. }
  44206. if ( !winRetryIoerr(&cnt, &lastErrno) ){
  44207. rc = SQLITE_ERROR; /* No more retries. */
  44208. break;
  44209. }
  44210. } while(1);
  44211. }
  44212. #endif
  44213. if( rc && rc!=SQLITE_IOERR_DELETE_NOENT ){
  44214. rc = winLogError(SQLITE_IOERR_DELETE, lastErrno, "winDelete", zFilename);
  44215. }else{
  44216. winLogIoerr(cnt, __LINE__);
  44217. }
  44218. sqlite3_free(zConverted);
  44219. OSTRACE(("DELETE name=%s, rc=%s\n", zFilename, sqlite3ErrName(rc)));
  44220. return rc;
  44221. }
  44222. /*
  44223. ** Check the existence and status of a file.
  44224. */
  44225. static int winAccess(
  44226. sqlite3_vfs *pVfs, /* Not used on win32 */
  44227. const char *zFilename, /* Name of file to check */
  44228. int flags, /* Type of test to make on this file */
  44229. int *pResOut /* OUT: Result */
  44230. ){
  44231. DWORD attr;
  44232. int rc = 0;
  44233. DWORD lastErrno = 0;
  44234. void *zConverted;
  44235. UNUSED_PARAMETER(pVfs);
  44236. SimulateIOError( return SQLITE_IOERR_ACCESS; );
  44237. OSTRACE(("ACCESS name=%s, flags=%x, pResOut=%p\n",
  44238. zFilename, flags, pResOut));
  44239. zConverted = winConvertFromUtf8Filename(zFilename);
  44240. if( zConverted==0 ){
  44241. OSTRACE(("ACCESS name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
  44242. return SQLITE_IOERR_NOMEM_BKPT;
  44243. }
  44244. if( osIsNT() ){
  44245. int cnt = 0;
  44246. WIN32_FILE_ATTRIBUTE_DATA sAttrData;
  44247. memset(&sAttrData, 0, sizeof(sAttrData));
  44248. while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
  44249. GetFileExInfoStandard,
  44250. &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
  44251. if( rc ){
  44252. /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
  44253. ** as if it does not exist.
  44254. */
  44255. if( flags==SQLITE_ACCESS_EXISTS
  44256. && sAttrData.nFileSizeHigh==0
  44257. && sAttrData.nFileSizeLow==0 ){
  44258. attr = INVALID_FILE_ATTRIBUTES;
  44259. }else{
  44260. attr = sAttrData.dwFileAttributes;
  44261. }
  44262. }else{
  44263. winLogIoerr(cnt, __LINE__);
  44264. if( lastErrno!=ERROR_FILE_NOT_FOUND && lastErrno!=ERROR_PATH_NOT_FOUND ){
  44265. sqlite3_free(zConverted);
  44266. return winLogError(SQLITE_IOERR_ACCESS, lastErrno, "winAccess",
  44267. zFilename);
  44268. }else{
  44269. attr = INVALID_FILE_ATTRIBUTES;
  44270. }
  44271. }
  44272. }
  44273. #ifdef SQLITE_WIN32_HAS_ANSI
  44274. else{
  44275. attr = osGetFileAttributesA((char*)zConverted);
  44276. }
  44277. #endif
  44278. sqlite3_free(zConverted);
  44279. switch( flags ){
  44280. case SQLITE_ACCESS_READ:
  44281. case SQLITE_ACCESS_EXISTS:
  44282. rc = attr!=INVALID_FILE_ATTRIBUTES;
  44283. break;
  44284. case SQLITE_ACCESS_READWRITE:
  44285. rc = attr!=INVALID_FILE_ATTRIBUTES &&
  44286. (attr & FILE_ATTRIBUTE_READONLY)==0;
  44287. break;
  44288. default:
  44289. assert(!"Invalid flags argument");
  44290. }
  44291. *pResOut = rc;
  44292. OSTRACE(("ACCESS name=%s, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
  44293. zFilename, pResOut, *pResOut));
  44294. return SQLITE_OK;
  44295. }
  44296. /*
  44297. ** Returns non-zero if the specified path name starts with the "long path"
  44298. ** prefix.
  44299. */
  44300. static BOOL winIsLongPathPrefix(
  44301. const char *zPathname
  44302. ){
  44303. return ( zPathname[0]=='\\' && zPathname[1]=='\\'
  44304. && zPathname[2]=='?' && zPathname[3]=='\\' );
  44305. }
  44306. /*
  44307. ** Returns non-zero if the specified path name starts with a drive letter
  44308. ** followed by a colon character.
  44309. */
  44310. static BOOL winIsDriveLetterAndColon(
  44311. const char *zPathname
  44312. ){
  44313. return ( sqlite3Isalpha(zPathname[0]) && zPathname[1]==':' );
  44314. }
  44315. /*
  44316. ** Returns non-zero if the specified path name should be used verbatim. If
  44317. ** non-zero is returned from this function, the calling function must simply
  44318. ** use the provided path name verbatim -OR- resolve it into a full path name
  44319. ** using the GetFullPathName Win32 API function (if available).
  44320. */
  44321. static BOOL winIsVerbatimPathname(
  44322. const char *zPathname
  44323. ){
  44324. /*
  44325. ** If the path name starts with a forward slash or a backslash, it is either
  44326. ** a legal UNC name, a volume relative path, or an absolute path name in the
  44327. ** "Unix" format on Windows. There is no easy way to differentiate between
  44328. ** the final two cases; therefore, we return the safer return value of TRUE
  44329. ** so that callers of this function will simply use it verbatim.
  44330. */
  44331. if ( winIsDirSep(zPathname[0]) ){
  44332. return TRUE;
  44333. }
  44334. /*
  44335. ** If the path name starts with a letter and a colon it is either a volume
  44336. ** relative path or an absolute path. Callers of this function must not
  44337. ** attempt to treat it as a relative path name (i.e. they should simply use
  44338. ** it verbatim).
  44339. */
  44340. if ( winIsDriveLetterAndColon(zPathname) ){
  44341. return TRUE;
  44342. }
  44343. /*
  44344. ** If we get to this point, the path name should almost certainly be a purely
  44345. ** relative one (i.e. not a UNC name, not absolute, and not volume relative).
  44346. */
  44347. return FALSE;
  44348. }
  44349. /*
  44350. ** Turn a relative pathname into a full pathname. Write the full
  44351. ** pathname into zOut[]. zOut[] will be at least pVfs->mxPathname
  44352. ** bytes in size.
  44353. */
  44354. static int winFullPathname(
  44355. sqlite3_vfs *pVfs, /* Pointer to vfs object */
  44356. const char *zRelative, /* Possibly relative input path */
  44357. int nFull, /* Size of output buffer in bytes */
  44358. char *zFull /* Output buffer */
  44359. ){
  44360. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__)
  44361. DWORD nByte;
  44362. void *zConverted;
  44363. char *zOut;
  44364. #endif
  44365. /* If this path name begins with "/X:" or "\\?\", where "X" is any
  44366. ** alphabetic character, discard the initial "/" from the pathname.
  44367. */
  44368. if( zRelative[0]=='/' && (winIsDriveLetterAndColon(zRelative+1)
  44369. || winIsLongPathPrefix(zRelative+1)) ){
  44370. zRelative++;
  44371. }
  44372. #if defined(__CYGWIN__)
  44373. SimulateIOError( return SQLITE_ERROR );
  44374. UNUSED_PARAMETER(nFull);
  44375. assert( nFull>=pVfs->mxPathname );
  44376. if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
  44377. /*
  44378. ** NOTE: We are dealing with a relative path name and the data
  44379. ** directory has been set. Therefore, use it as the basis
  44380. ** for converting the relative path name to an absolute
  44381. ** one by prepending the data directory and a slash.
  44382. */
  44383. char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
  44384. if( !zOut ){
  44385. return SQLITE_IOERR_NOMEM_BKPT;
  44386. }
  44387. if( cygwin_conv_path(
  44388. (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A) |
  44389. CCP_RELATIVE, zRelative, zOut, pVfs->mxPathname+1)<0 ){
  44390. sqlite3_free(zOut);
  44391. return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
  44392. "winFullPathname1", zRelative);
  44393. }else{
  44394. char *zUtf8 = winConvertToUtf8Filename(zOut);
  44395. if( !zUtf8 ){
  44396. sqlite3_free(zOut);
  44397. return SQLITE_IOERR_NOMEM_BKPT;
  44398. }
  44399. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
  44400. sqlite3_data_directory, winGetDirSep(), zUtf8);
  44401. sqlite3_free(zUtf8);
  44402. sqlite3_free(zOut);
  44403. }
  44404. }else{
  44405. char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
  44406. if( !zOut ){
  44407. return SQLITE_IOERR_NOMEM_BKPT;
  44408. }
  44409. if( cygwin_conv_path(
  44410. (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A),
  44411. zRelative, zOut, pVfs->mxPathname+1)<0 ){
  44412. sqlite3_free(zOut);
  44413. return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
  44414. "winFullPathname2", zRelative);
  44415. }else{
  44416. char *zUtf8 = winConvertToUtf8Filename(zOut);
  44417. if( !zUtf8 ){
  44418. sqlite3_free(zOut);
  44419. return SQLITE_IOERR_NOMEM_BKPT;
  44420. }
  44421. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zUtf8);
  44422. sqlite3_free(zUtf8);
  44423. sqlite3_free(zOut);
  44424. }
  44425. }
  44426. return SQLITE_OK;
  44427. #endif
  44428. #if (SQLITE_OS_WINCE || SQLITE_OS_WINRT) && !defined(__CYGWIN__)
  44429. SimulateIOError( return SQLITE_ERROR );
  44430. /* WinCE has no concept of a relative pathname, or so I am told. */
  44431. /* WinRT has no way to convert a relative path to an absolute one. */
  44432. if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
  44433. /*
  44434. ** NOTE: We are dealing with a relative path name and the data
  44435. ** directory has been set. Therefore, use it as the basis
  44436. ** for converting the relative path name to an absolute
  44437. ** one by prepending the data directory and a backslash.
  44438. */
  44439. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
  44440. sqlite3_data_directory, winGetDirSep(), zRelative);
  44441. }else{
  44442. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zRelative);
  44443. }
  44444. return SQLITE_OK;
  44445. #endif
  44446. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__)
  44447. /* It's odd to simulate an io-error here, but really this is just
  44448. ** using the io-error infrastructure to test that SQLite handles this
  44449. ** function failing. This function could fail if, for example, the
  44450. ** current working directory has been unlinked.
  44451. */
  44452. SimulateIOError( return SQLITE_ERROR );
  44453. if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
  44454. /*
  44455. ** NOTE: We are dealing with a relative path name and the data
  44456. ** directory has been set. Therefore, use it as the basis
  44457. ** for converting the relative path name to an absolute
  44458. ** one by prepending the data directory and a backslash.
  44459. */
  44460. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
  44461. sqlite3_data_directory, winGetDirSep(), zRelative);
  44462. return SQLITE_OK;
  44463. }
  44464. zConverted = winConvertFromUtf8Filename(zRelative);
  44465. if( zConverted==0 ){
  44466. return SQLITE_IOERR_NOMEM_BKPT;
  44467. }
  44468. if( osIsNT() ){
  44469. LPWSTR zTemp;
  44470. nByte = osGetFullPathNameW((LPCWSTR)zConverted, 0, 0, 0);
  44471. if( nByte==0 ){
  44472. sqlite3_free(zConverted);
  44473. return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
  44474. "winFullPathname1", zRelative);
  44475. }
  44476. nByte += 3;
  44477. zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
  44478. if( zTemp==0 ){
  44479. sqlite3_free(zConverted);
  44480. return SQLITE_IOERR_NOMEM_BKPT;
  44481. }
  44482. nByte = osGetFullPathNameW((LPCWSTR)zConverted, nByte, zTemp, 0);
  44483. if( nByte==0 ){
  44484. sqlite3_free(zConverted);
  44485. sqlite3_free(zTemp);
  44486. return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
  44487. "winFullPathname2", zRelative);
  44488. }
  44489. sqlite3_free(zConverted);
  44490. zOut = winUnicodeToUtf8(zTemp);
  44491. sqlite3_free(zTemp);
  44492. }
  44493. #ifdef SQLITE_WIN32_HAS_ANSI
  44494. else{
  44495. char *zTemp;
  44496. nByte = osGetFullPathNameA((char*)zConverted, 0, 0, 0);
  44497. if( nByte==0 ){
  44498. sqlite3_free(zConverted);
  44499. return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
  44500. "winFullPathname3", zRelative);
  44501. }
  44502. nByte += 3;
  44503. zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
  44504. if( zTemp==0 ){
  44505. sqlite3_free(zConverted);
  44506. return SQLITE_IOERR_NOMEM_BKPT;
  44507. }
  44508. nByte = osGetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
  44509. if( nByte==0 ){
  44510. sqlite3_free(zConverted);
  44511. sqlite3_free(zTemp);
  44512. return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
  44513. "winFullPathname4", zRelative);
  44514. }
  44515. sqlite3_free(zConverted);
  44516. zOut = winMbcsToUtf8(zTemp, osAreFileApisANSI());
  44517. sqlite3_free(zTemp);
  44518. }
  44519. #endif
  44520. if( zOut ){
  44521. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zOut);
  44522. sqlite3_free(zOut);
  44523. return SQLITE_OK;
  44524. }else{
  44525. return SQLITE_IOERR_NOMEM_BKPT;
  44526. }
  44527. #endif
  44528. }
  44529. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  44530. /*
  44531. ** Interfaces for opening a shared library, finding entry points
  44532. ** within the shared library, and closing the shared library.
  44533. */
  44534. static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
  44535. HANDLE h;
  44536. #if defined(__CYGWIN__)
  44537. int nFull = pVfs->mxPathname+1;
  44538. char *zFull = sqlite3MallocZero( nFull );
  44539. void *zConverted = 0;
  44540. if( zFull==0 ){
  44541. OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
  44542. return 0;
  44543. }
  44544. if( winFullPathname(pVfs, zFilename, nFull, zFull)!=SQLITE_OK ){
  44545. sqlite3_free(zFull);
  44546. OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
  44547. return 0;
  44548. }
  44549. zConverted = winConvertFromUtf8Filename(zFull);
  44550. sqlite3_free(zFull);
  44551. #else
  44552. void *zConverted = winConvertFromUtf8Filename(zFilename);
  44553. UNUSED_PARAMETER(pVfs);
  44554. #endif
  44555. if( zConverted==0 ){
  44556. OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
  44557. return 0;
  44558. }
  44559. if( osIsNT() ){
  44560. #if SQLITE_OS_WINRT
  44561. h = osLoadPackagedLibrary((LPCWSTR)zConverted, 0);
  44562. #else
  44563. h = osLoadLibraryW((LPCWSTR)zConverted);
  44564. #endif
  44565. }
  44566. #ifdef SQLITE_WIN32_HAS_ANSI
  44567. else{
  44568. h = osLoadLibraryA((char*)zConverted);
  44569. }
  44570. #endif
  44571. OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)h));
  44572. sqlite3_free(zConverted);
  44573. return (void*)h;
  44574. }
  44575. static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
  44576. UNUSED_PARAMETER(pVfs);
  44577. winGetLastErrorMsg(osGetLastError(), nBuf, zBufOut);
  44578. }
  44579. static void (*winDlSym(sqlite3_vfs *pVfs,void *pH,const char *zSym))(void){
  44580. FARPROC proc;
  44581. UNUSED_PARAMETER(pVfs);
  44582. proc = osGetProcAddressA((HANDLE)pH, zSym);
  44583. OSTRACE(("DLSYM handle=%p, symbol=%s, address=%p\n",
  44584. (void*)pH, zSym, (void*)proc));
  44585. return (void(*)(void))proc;
  44586. }
  44587. static void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
  44588. UNUSED_PARAMETER(pVfs);
  44589. osFreeLibrary((HANDLE)pHandle);
  44590. OSTRACE(("DLCLOSE handle=%p\n", (void*)pHandle));
  44591. }
  44592. #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
  44593. #define winDlOpen 0
  44594. #define winDlError 0
  44595. #define winDlSym 0
  44596. #define winDlClose 0
  44597. #endif
  44598. /* State information for the randomness gatherer. */
  44599. typedef struct EntropyGatherer EntropyGatherer;
  44600. struct EntropyGatherer {
  44601. unsigned char *a; /* Gather entropy into this buffer */
  44602. int na; /* Size of a[] in bytes */
  44603. int i; /* XOR next input into a[i] */
  44604. int nXor; /* Number of XOR operations done */
  44605. };
  44606. #if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
  44607. /* Mix sz bytes of entropy into p. */
  44608. static void xorMemory(EntropyGatherer *p, unsigned char *x, int sz){
  44609. int j, k;
  44610. for(j=0, k=p->i; j<sz; j++){
  44611. p->a[k++] ^= x[j];
  44612. if( k>=p->na ) k = 0;
  44613. }
  44614. p->i = k;
  44615. p->nXor += sz;
  44616. }
  44617. #endif /* !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS) */
  44618. /*
  44619. ** Write up to nBuf bytes of randomness into zBuf.
  44620. */
  44621. static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
  44622. #if defined(SQLITE_TEST) || defined(SQLITE_OMIT_RANDOMNESS)
  44623. UNUSED_PARAMETER(pVfs);
  44624. memset(zBuf, 0, nBuf);
  44625. return nBuf;
  44626. #else
  44627. EntropyGatherer e;
  44628. UNUSED_PARAMETER(pVfs);
  44629. memset(zBuf, 0, nBuf);
  44630. e.a = (unsigned char*)zBuf;
  44631. e.na = nBuf;
  44632. e.nXor = 0;
  44633. e.i = 0;
  44634. {
  44635. SYSTEMTIME x;
  44636. osGetSystemTime(&x);
  44637. xorMemory(&e, (unsigned char*)&x, sizeof(SYSTEMTIME));
  44638. }
  44639. {
  44640. DWORD pid = osGetCurrentProcessId();
  44641. xorMemory(&e, (unsigned char*)&pid, sizeof(DWORD));
  44642. }
  44643. #if SQLITE_OS_WINRT
  44644. {
  44645. ULONGLONG cnt = osGetTickCount64();
  44646. xorMemory(&e, (unsigned char*)&cnt, sizeof(ULONGLONG));
  44647. }
  44648. #else
  44649. {
  44650. DWORD cnt = osGetTickCount();
  44651. xorMemory(&e, (unsigned char*)&cnt, sizeof(DWORD));
  44652. }
  44653. #endif /* SQLITE_OS_WINRT */
  44654. {
  44655. LARGE_INTEGER i;
  44656. osQueryPerformanceCounter(&i);
  44657. xorMemory(&e, (unsigned char*)&i, sizeof(LARGE_INTEGER));
  44658. }
  44659. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
  44660. {
  44661. UUID id;
  44662. memset(&id, 0, sizeof(UUID));
  44663. osUuidCreate(&id);
  44664. xorMemory(&e, (unsigned char*)&id, sizeof(UUID));
  44665. memset(&id, 0, sizeof(UUID));
  44666. osUuidCreateSequential(&id);
  44667. xorMemory(&e, (unsigned char*)&id, sizeof(UUID));
  44668. }
  44669. #endif /* !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID */
  44670. return e.nXor>nBuf ? nBuf : e.nXor;
  44671. #endif /* defined(SQLITE_TEST) || defined(SQLITE_OMIT_RANDOMNESS) */
  44672. }
  44673. /*
  44674. ** Sleep for a little while. Return the amount of time slept.
  44675. */
  44676. static int winSleep(sqlite3_vfs *pVfs, int microsec){
  44677. sqlite3_win32_sleep((microsec+999)/1000);
  44678. UNUSED_PARAMETER(pVfs);
  44679. return ((microsec+999)/1000)*1000;
  44680. }
  44681. /*
  44682. ** The following variable, if set to a non-zero value, is interpreted as
  44683. ** the number of seconds since 1970 and is used to set the result of
  44684. ** sqlite3OsCurrentTime() during testing.
  44685. */
  44686. #ifdef SQLITE_TEST
  44687. SQLITE_API int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
  44688. #endif
  44689. /*
  44690. ** Find the current time (in Universal Coordinated Time). Write into *piNow
  44691. ** the current time and date as a Julian Day number times 86_400_000. In
  44692. ** other words, write into *piNow the number of milliseconds since the Julian
  44693. ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
  44694. ** proleptic Gregorian calendar.
  44695. **
  44696. ** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
  44697. ** cannot be found.
  44698. */
  44699. static int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
  44700. /* FILETIME structure is a 64-bit value representing the number of
  44701. 100-nanosecond intervals since January 1, 1601 (= JD 2305813.5).
  44702. */
  44703. FILETIME ft;
  44704. static const sqlite3_int64 winFiletimeEpoch = 23058135*(sqlite3_int64)8640000;
  44705. #ifdef SQLITE_TEST
  44706. static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
  44707. #endif
  44708. /* 2^32 - to avoid use of LL and warnings in gcc */
  44709. static const sqlite3_int64 max32BitValue =
  44710. (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 +
  44711. (sqlite3_int64)294967296;
  44712. #if SQLITE_OS_WINCE
  44713. SYSTEMTIME time;
  44714. osGetSystemTime(&time);
  44715. /* if SystemTimeToFileTime() fails, it returns zero. */
  44716. if (!osSystemTimeToFileTime(&time,&ft)){
  44717. return SQLITE_ERROR;
  44718. }
  44719. #else
  44720. osGetSystemTimeAsFileTime( &ft );
  44721. #endif
  44722. *piNow = winFiletimeEpoch +
  44723. ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) +
  44724. (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000;
  44725. #ifdef SQLITE_TEST
  44726. if( sqlite3_current_time ){
  44727. *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
  44728. }
  44729. #endif
  44730. UNUSED_PARAMETER(pVfs);
  44731. return SQLITE_OK;
  44732. }
  44733. /*
  44734. ** Find the current time (in Universal Coordinated Time). Write the
  44735. ** current time and date as a Julian Day number into *prNow and
  44736. ** return 0. Return 1 if the time and date cannot be found.
  44737. */
  44738. static int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
  44739. int rc;
  44740. sqlite3_int64 i;
  44741. rc = winCurrentTimeInt64(pVfs, &i);
  44742. if( !rc ){
  44743. *prNow = i/86400000.0;
  44744. }
  44745. return rc;
  44746. }
  44747. /*
  44748. ** The idea is that this function works like a combination of
  44749. ** GetLastError() and FormatMessage() on Windows (or errno and
  44750. ** strerror_r() on Unix). After an error is returned by an OS
  44751. ** function, SQLite calls this function with zBuf pointing to
  44752. ** a buffer of nBuf bytes. The OS layer should populate the
  44753. ** buffer with a nul-terminated UTF-8 encoded error message
  44754. ** describing the last IO error to have occurred within the calling
  44755. ** thread.
  44756. **
  44757. ** If the error message is too large for the supplied buffer,
  44758. ** it should be truncated. The return value of xGetLastError
  44759. ** is zero if the error message fits in the buffer, or non-zero
  44760. ** otherwise (if the message was truncated). If non-zero is returned,
  44761. ** then it is not necessary to include the nul-terminator character
  44762. ** in the output buffer.
  44763. **
  44764. ** Not supplying an error message will have no adverse effect
  44765. ** on SQLite. It is fine to have an implementation that never
  44766. ** returns an error message:
  44767. **
  44768. ** int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
  44769. ** assert(zBuf[0]=='\0');
  44770. ** return 0;
  44771. ** }
  44772. **
  44773. ** However if an error message is supplied, it will be incorporated
  44774. ** by sqlite into the error message available to the user using
  44775. ** sqlite3_errmsg(), possibly making IO errors easier to debug.
  44776. */
  44777. static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
  44778. DWORD e = osGetLastError();
  44779. UNUSED_PARAMETER(pVfs);
  44780. if( nBuf>0 ) winGetLastErrorMsg(e, nBuf, zBuf);
  44781. return e;
  44782. }
  44783. /*
  44784. ** Initialize and deinitialize the operating system interface.
  44785. */
  44786. SQLITE_API int sqlite3_os_init(void){
  44787. static sqlite3_vfs winVfs = {
  44788. 3, /* iVersion */
  44789. sizeof(winFile), /* szOsFile */
  44790. SQLITE_WIN32_MAX_PATH_BYTES, /* mxPathname */
  44791. 0, /* pNext */
  44792. "win32", /* zName */
  44793. &winAppData, /* pAppData */
  44794. winOpen, /* xOpen */
  44795. winDelete, /* xDelete */
  44796. winAccess, /* xAccess */
  44797. winFullPathname, /* xFullPathname */
  44798. winDlOpen, /* xDlOpen */
  44799. winDlError, /* xDlError */
  44800. winDlSym, /* xDlSym */
  44801. winDlClose, /* xDlClose */
  44802. winRandomness, /* xRandomness */
  44803. winSleep, /* xSleep */
  44804. winCurrentTime, /* xCurrentTime */
  44805. winGetLastError, /* xGetLastError */
  44806. winCurrentTimeInt64, /* xCurrentTimeInt64 */
  44807. winSetSystemCall, /* xSetSystemCall */
  44808. winGetSystemCall, /* xGetSystemCall */
  44809. winNextSystemCall, /* xNextSystemCall */
  44810. };
  44811. #if defined(SQLITE_WIN32_HAS_WIDE)
  44812. static sqlite3_vfs winLongPathVfs = {
  44813. 3, /* iVersion */
  44814. sizeof(winFile), /* szOsFile */
  44815. SQLITE_WINNT_MAX_PATH_BYTES, /* mxPathname */
  44816. 0, /* pNext */
  44817. "win32-longpath", /* zName */
  44818. &winAppData, /* pAppData */
  44819. winOpen, /* xOpen */
  44820. winDelete, /* xDelete */
  44821. winAccess, /* xAccess */
  44822. winFullPathname, /* xFullPathname */
  44823. winDlOpen, /* xDlOpen */
  44824. winDlError, /* xDlError */
  44825. winDlSym, /* xDlSym */
  44826. winDlClose, /* xDlClose */
  44827. winRandomness, /* xRandomness */
  44828. winSleep, /* xSleep */
  44829. winCurrentTime, /* xCurrentTime */
  44830. winGetLastError, /* xGetLastError */
  44831. winCurrentTimeInt64, /* xCurrentTimeInt64 */
  44832. winSetSystemCall, /* xSetSystemCall */
  44833. winGetSystemCall, /* xGetSystemCall */
  44834. winNextSystemCall, /* xNextSystemCall */
  44835. };
  44836. #endif
  44837. static sqlite3_vfs winNolockVfs = {
  44838. 3, /* iVersion */
  44839. sizeof(winFile), /* szOsFile */
  44840. SQLITE_WIN32_MAX_PATH_BYTES, /* mxPathname */
  44841. 0, /* pNext */
  44842. "win32-none", /* zName */
  44843. &winNolockAppData, /* pAppData */
  44844. winOpen, /* xOpen */
  44845. winDelete, /* xDelete */
  44846. winAccess, /* xAccess */
  44847. winFullPathname, /* xFullPathname */
  44848. winDlOpen, /* xDlOpen */
  44849. winDlError, /* xDlError */
  44850. winDlSym, /* xDlSym */
  44851. winDlClose, /* xDlClose */
  44852. winRandomness, /* xRandomness */
  44853. winSleep, /* xSleep */
  44854. winCurrentTime, /* xCurrentTime */
  44855. winGetLastError, /* xGetLastError */
  44856. winCurrentTimeInt64, /* xCurrentTimeInt64 */
  44857. winSetSystemCall, /* xSetSystemCall */
  44858. winGetSystemCall, /* xGetSystemCall */
  44859. winNextSystemCall, /* xNextSystemCall */
  44860. };
  44861. #if defined(SQLITE_WIN32_HAS_WIDE)
  44862. static sqlite3_vfs winLongPathNolockVfs = {
  44863. 3, /* iVersion */
  44864. sizeof(winFile), /* szOsFile */
  44865. SQLITE_WINNT_MAX_PATH_BYTES, /* mxPathname */
  44866. 0, /* pNext */
  44867. "win32-longpath-none", /* zName */
  44868. &winNolockAppData, /* pAppData */
  44869. winOpen, /* xOpen */
  44870. winDelete, /* xDelete */
  44871. winAccess, /* xAccess */
  44872. winFullPathname, /* xFullPathname */
  44873. winDlOpen, /* xDlOpen */
  44874. winDlError, /* xDlError */
  44875. winDlSym, /* xDlSym */
  44876. winDlClose, /* xDlClose */
  44877. winRandomness, /* xRandomness */
  44878. winSleep, /* xSleep */
  44879. winCurrentTime, /* xCurrentTime */
  44880. winGetLastError, /* xGetLastError */
  44881. winCurrentTimeInt64, /* xCurrentTimeInt64 */
  44882. winSetSystemCall, /* xSetSystemCall */
  44883. winGetSystemCall, /* xGetSystemCall */
  44884. winNextSystemCall, /* xNextSystemCall */
  44885. };
  44886. #endif
  44887. /* Double-check that the aSyscall[] array has been constructed
  44888. ** correctly. See ticket [bb3a86e890c8e96ab] */
  44889. assert( ArraySize(aSyscall)==80 );
  44890. /* get memory map allocation granularity */
  44891. memset(&winSysInfo, 0, sizeof(SYSTEM_INFO));
  44892. #if SQLITE_OS_WINRT
  44893. osGetNativeSystemInfo(&winSysInfo);
  44894. #else
  44895. osGetSystemInfo(&winSysInfo);
  44896. #endif
  44897. assert( winSysInfo.dwAllocationGranularity>0 );
  44898. assert( winSysInfo.dwPageSize>0 );
  44899. sqlite3_vfs_register(&winVfs, 1);
  44900. #if defined(SQLITE_WIN32_HAS_WIDE)
  44901. sqlite3_vfs_register(&winLongPathVfs, 0);
  44902. #endif
  44903. sqlite3_vfs_register(&winNolockVfs, 0);
  44904. #if defined(SQLITE_WIN32_HAS_WIDE)
  44905. sqlite3_vfs_register(&winLongPathNolockVfs, 0);
  44906. #endif
  44907. #ifndef SQLITE_OMIT_WAL
  44908. winBigLock = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1);
  44909. #endif
  44910. return SQLITE_OK;
  44911. }
  44912. SQLITE_API int sqlite3_os_end(void){
  44913. #if SQLITE_OS_WINRT
  44914. if( sleepObj!=NULL ){
  44915. osCloseHandle(sleepObj);
  44916. sleepObj = NULL;
  44917. }
  44918. #endif
  44919. #ifndef SQLITE_OMIT_WAL
  44920. winBigLock = 0;
  44921. #endif
  44922. return SQLITE_OK;
  44923. }
  44924. #endif /* SQLITE_OS_WIN */
  44925. /************** End of os_win.c **********************************************/
  44926. /************** Begin file memdb.c *******************************************/
  44927. /*
  44928. ** 2016-09-07
  44929. **
  44930. ** The author disclaims copyright to this source code. In place of
  44931. ** a legal notice, here is a blessing:
  44932. **
  44933. ** May you do good and not evil.
  44934. ** May you find forgiveness for yourself and forgive others.
  44935. ** May you share freely, never taking more than you give.
  44936. **
  44937. ******************************************************************************
  44938. **
  44939. ** This file implements an in-memory VFS. A database is held as a contiguous
  44940. ** block of memory.
  44941. **
  44942. ** This file also implements interface sqlite3_serialize() and
  44943. ** sqlite3_deserialize().
  44944. */
  44945. /* #include "sqliteInt.h" */
  44946. #ifdef SQLITE_ENABLE_DESERIALIZE
  44947. /*
  44948. ** Forward declaration of objects used by this utility
  44949. */
  44950. typedef struct sqlite3_vfs MemVfs;
  44951. typedef struct MemFile MemFile;
  44952. /* Access to a lower-level VFS that (might) implement dynamic loading,
  44953. ** access to randomness, etc.
  44954. */
  44955. #define ORIGVFS(p) ((sqlite3_vfs*)((p)->pAppData))
  44956. /* An open file */
  44957. struct MemFile {
  44958. sqlite3_file base; /* IO methods */
  44959. sqlite3_int64 sz; /* Size of the file */
  44960. sqlite3_int64 szAlloc; /* Space allocated to aData */
  44961. sqlite3_int64 szMax; /* Maximum allowed size of the file */
  44962. unsigned char *aData; /* content of the file */
  44963. int nMmap; /* Number of memory mapped pages */
  44964. unsigned mFlags; /* Flags */
  44965. int eLock; /* Most recent lock against this file */
  44966. };
  44967. /*
  44968. ** Methods for MemFile
  44969. */
  44970. static int memdbClose(sqlite3_file*);
  44971. static int memdbRead(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
  44972. static int memdbWrite(sqlite3_file*,const void*,int iAmt, sqlite3_int64 iOfst);
  44973. static int memdbTruncate(sqlite3_file*, sqlite3_int64 size);
  44974. static int memdbSync(sqlite3_file*, int flags);
  44975. static int memdbFileSize(sqlite3_file*, sqlite3_int64 *pSize);
  44976. static int memdbLock(sqlite3_file*, int);
  44977. /* static int memdbCheckReservedLock(sqlite3_file*, int *pResOut);// not used */
  44978. static int memdbFileControl(sqlite3_file*, int op, void *pArg);
  44979. /* static int memdbSectorSize(sqlite3_file*); // not used */
  44980. static int memdbDeviceCharacteristics(sqlite3_file*);
  44981. static int memdbFetch(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp);
  44982. static int memdbUnfetch(sqlite3_file*, sqlite3_int64 iOfst, void *p);
  44983. /*
  44984. ** Methods for MemVfs
  44985. */
  44986. static int memdbOpen(sqlite3_vfs*, const char *, sqlite3_file*, int , int *);
  44987. /* static int memdbDelete(sqlite3_vfs*, const char *zName, int syncDir); */
  44988. static int memdbAccess(sqlite3_vfs*, const char *zName, int flags, int *);
  44989. static int memdbFullPathname(sqlite3_vfs*, const char *zName, int, char *zOut);
  44990. static void *memdbDlOpen(sqlite3_vfs*, const char *zFilename);
  44991. static void memdbDlError(sqlite3_vfs*, int nByte, char *zErrMsg);
  44992. static void (*memdbDlSym(sqlite3_vfs *pVfs, void *p, const char*zSym))(void);
  44993. static void memdbDlClose(sqlite3_vfs*, void*);
  44994. static int memdbRandomness(sqlite3_vfs*, int nByte, char *zOut);
  44995. static int memdbSleep(sqlite3_vfs*, int microseconds);
  44996. /* static int memdbCurrentTime(sqlite3_vfs*, double*); */
  44997. static int memdbGetLastError(sqlite3_vfs*, int, char *);
  44998. static int memdbCurrentTimeInt64(sqlite3_vfs*, sqlite3_int64*);
  44999. static sqlite3_vfs memdb_vfs = {
  45000. 2, /* iVersion */
  45001. 0, /* szOsFile (set when registered) */
  45002. 1024, /* mxPathname */
  45003. 0, /* pNext */
  45004. "memdb", /* zName */
  45005. 0, /* pAppData (set when registered) */
  45006. memdbOpen, /* xOpen */
  45007. 0, /* memdbDelete, */ /* xDelete */
  45008. memdbAccess, /* xAccess */
  45009. memdbFullPathname, /* xFullPathname */
  45010. memdbDlOpen, /* xDlOpen */
  45011. memdbDlError, /* xDlError */
  45012. memdbDlSym, /* xDlSym */
  45013. memdbDlClose, /* xDlClose */
  45014. memdbRandomness, /* xRandomness */
  45015. memdbSleep, /* xSleep */
  45016. 0, /* memdbCurrentTime, */ /* xCurrentTime */
  45017. memdbGetLastError, /* xGetLastError */
  45018. memdbCurrentTimeInt64 /* xCurrentTimeInt64 */
  45019. };
  45020. static const sqlite3_io_methods memdb_io_methods = {
  45021. 3, /* iVersion */
  45022. memdbClose, /* xClose */
  45023. memdbRead, /* xRead */
  45024. memdbWrite, /* xWrite */
  45025. memdbTruncate, /* xTruncate */
  45026. memdbSync, /* xSync */
  45027. memdbFileSize, /* xFileSize */
  45028. memdbLock, /* xLock */
  45029. memdbLock, /* xUnlock - same as xLock in this case */
  45030. 0, /* memdbCheckReservedLock, */ /* xCheckReservedLock */
  45031. memdbFileControl, /* xFileControl */
  45032. 0, /* memdbSectorSize,*/ /* xSectorSize */
  45033. memdbDeviceCharacteristics, /* xDeviceCharacteristics */
  45034. 0, /* xShmMap */
  45035. 0, /* xShmLock */
  45036. 0, /* xShmBarrier */
  45037. 0, /* xShmUnmap */
  45038. memdbFetch, /* xFetch */
  45039. memdbUnfetch /* xUnfetch */
  45040. };
  45041. /*
  45042. ** Close an memdb-file.
  45043. **
  45044. ** The pData pointer is owned by the application, so there is nothing
  45045. ** to free.
  45046. */
  45047. static int memdbClose(sqlite3_file *pFile){
  45048. MemFile *p = (MemFile *)pFile;
  45049. if( p->mFlags & SQLITE_DESERIALIZE_FREEONCLOSE ) sqlite3_free(p->aData);
  45050. return SQLITE_OK;
  45051. }
  45052. /*
  45053. ** Read data from an memdb-file.
  45054. */
  45055. static int memdbRead(
  45056. sqlite3_file *pFile,
  45057. void *zBuf,
  45058. int iAmt,
  45059. sqlite_int64 iOfst
  45060. ){
  45061. MemFile *p = (MemFile *)pFile;
  45062. if( iOfst+iAmt>p->sz ){
  45063. memset(zBuf, 0, iAmt);
  45064. if( iOfst<p->sz ) memcpy(zBuf, p->aData+iOfst, p->sz - iOfst);
  45065. return SQLITE_IOERR_SHORT_READ;
  45066. }
  45067. memcpy(zBuf, p->aData+iOfst, iAmt);
  45068. return SQLITE_OK;
  45069. }
  45070. /*
  45071. ** Try to enlarge the memory allocation to hold at least sz bytes
  45072. */
  45073. static int memdbEnlarge(MemFile *p, sqlite3_int64 newSz){
  45074. unsigned char *pNew;
  45075. if( (p->mFlags & SQLITE_DESERIALIZE_RESIZEABLE)==0 || p->nMmap>0 ){
  45076. return SQLITE_FULL;
  45077. }
  45078. if( newSz>p->szMax ){
  45079. return SQLITE_FULL;
  45080. }
  45081. newSz *= 2;
  45082. if( newSz>p->szMax ) newSz = p->szMax;
  45083. pNew = sqlite3Realloc(p->aData, newSz);
  45084. if( pNew==0 ) return SQLITE_NOMEM;
  45085. p->aData = pNew;
  45086. p->szAlloc = newSz;
  45087. return SQLITE_OK;
  45088. }
  45089. /*
  45090. ** Write data to an memdb-file.
  45091. */
  45092. static int memdbWrite(
  45093. sqlite3_file *pFile,
  45094. const void *z,
  45095. int iAmt,
  45096. sqlite_int64 iOfst
  45097. ){
  45098. MemFile *p = (MemFile *)pFile;
  45099. if( NEVER(p->mFlags & SQLITE_DESERIALIZE_READONLY) ) return SQLITE_READONLY;
  45100. if( iOfst+iAmt>p->sz ){
  45101. int rc;
  45102. if( iOfst+iAmt>p->szAlloc
  45103. && (rc = memdbEnlarge(p, iOfst+iAmt))!=SQLITE_OK
  45104. ){
  45105. return rc;
  45106. }
  45107. if( iOfst>p->sz ) memset(p->aData+p->sz, 0, iOfst-p->sz);
  45108. p->sz = iOfst+iAmt;
  45109. }
  45110. memcpy(p->aData+iOfst, z, iAmt);
  45111. return SQLITE_OK;
  45112. }
  45113. /*
  45114. ** Truncate an memdb-file.
  45115. **
  45116. ** In rollback mode (which is always the case for memdb, as it does not
  45117. ** support WAL mode) the truncate() method is only used to reduce
  45118. ** the size of a file, never to increase the size.
  45119. */
  45120. static int memdbTruncate(sqlite3_file *pFile, sqlite_int64 size){
  45121. MemFile *p = (MemFile *)pFile;
  45122. if( NEVER(size>p->sz) ) return SQLITE_FULL;
  45123. p->sz = size;
  45124. return SQLITE_OK;
  45125. }
  45126. /*
  45127. ** Sync an memdb-file.
  45128. */
  45129. static int memdbSync(sqlite3_file *pFile, int flags){
  45130. return SQLITE_OK;
  45131. }
  45132. /*
  45133. ** Return the current file-size of an memdb-file.
  45134. */
  45135. static int memdbFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){
  45136. MemFile *p = (MemFile *)pFile;
  45137. *pSize = p->sz;
  45138. return SQLITE_OK;
  45139. }
  45140. /*
  45141. ** Lock an memdb-file.
  45142. */
  45143. static int memdbLock(sqlite3_file *pFile, int eLock){
  45144. MemFile *p = (MemFile *)pFile;
  45145. if( eLock>SQLITE_LOCK_SHARED
  45146. && (p->mFlags & SQLITE_DESERIALIZE_READONLY)!=0
  45147. ){
  45148. return SQLITE_READONLY;
  45149. }
  45150. p->eLock = eLock;
  45151. return SQLITE_OK;
  45152. }
  45153. #if 0 /* Never used because memdbAccess() always returns false */
  45154. /*
  45155. ** Check if another file-handle holds a RESERVED lock on an memdb-file.
  45156. */
  45157. static int memdbCheckReservedLock(sqlite3_file *pFile, int *pResOut){
  45158. *pResOut = 0;
  45159. return SQLITE_OK;
  45160. }
  45161. #endif
  45162. /*
  45163. ** File control method. For custom operations on an memdb-file.
  45164. */
  45165. static int memdbFileControl(sqlite3_file *pFile, int op, void *pArg){
  45166. MemFile *p = (MemFile *)pFile;
  45167. int rc = SQLITE_NOTFOUND;
  45168. if( op==SQLITE_FCNTL_VFSNAME ){
  45169. *(char**)pArg = sqlite3_mprintf("memdb(%p,%lld)", p->aData, p->sz);
  45170. rc = SQLITE_OK;
  45171. }
  45172. if( op==SQLITE_FCNTL_SIZE_LIMIT ){
  45173. sqlite3_int64 iLimit = *(sqlite3_int64*)pArg;
  45174. if( iLimit<p->sz ){
  45175. if( iLimit<0 ){
  45176. iLimit = p->szMax;
  45177. }else{
  45178. iLimit = p->sz;
  45179. }
  45180. }
  45181. p->szMax = iLimit;
  45182. *(sqlite3_int64*)pArg = iLimit;
  45183. rc = SQLITE_OK;
  45184. }
  45185. return rc;
  45186. }
  45187. #if 0 /* Not used because of SQLITE_IOCAP_POWERSAFE_OVERWRITE */
  45188. /*
  45189. ** Return the sector-size in bytes for an memdb-file.
  45190. */
  45191. static int memdbSectorSize(sqlite3_file *pFile){
  45192. return 1024;
  45193. }
  45194. #endif
  45195. /*
  45196. ** Return the device characteristic flags supported by an memdb-file.
  45197. */
  45198. static int memdbDeviceCharacteristics(sqlite3_file *pFile){
  45199. return SQLITE_IOCAP_ATOMIC |
  45200. SQLITE_IOCAP_POWERSAFE_OVERWRITE |
  45201. SQLITE_IOCAP_SAFE_APPEND |
  45202. SQLITE_IOCAP_SEQUENTIAL;
  45203. }
  45204. /* Fetch a page of a memory-mapped file */
  45205. static int memdbFetch(
  45206. sqlite3_file *pFile,
  45207. sqlite3_int64 iOfst,
  45208. int iAmt,
  45209. void **pp
  45210. ){
  45211. MemFile *p = (MemFile *)pFile;
  45212. if( iOfst+iAmt>p->sz ){
  45213. *pp = 0;
  45214. }else{
  45215. p->nMmap++;
  45216. *pp = (void*)(p->aData + iOfst);
  45217. }
  45218. return SQLITE_OK;
  45219. }
  45220. /* Release a memory-mapped page */
  45221. static int memdbUnfetch(sqlite3_file *pFile, sqlite3_int64 iOfst, void *pPage){
  45222. MemFile *p = (MemFile *)pFile;
  45223. p->nMmap--;
  45224. return SQLITE_OK;
  45225. }
  45226. /*
  45227. ** Open an mem file handle.
  45228. */
  45229. static int memdbOpen(
  45230. sqlite3_vfs *pVfs,
  45231. const char *zName,
  45232. sqlite3_file *pFile,
  45233. int flags,
  45234. int *pOutFlags
  45235. ){
  45236. MemFile *p = (MemFile*)pFile;
  45237. if( (flags & SQLITE_OPEN_MAIN_DB)==0 ){
  45238. return ORIGVFS(pVfs)->xOpen(ORIGVFS(pVfs), zName, pFile, flags, pOutFlags);
  45239. }
  45240. memset(p, 0, sizeof(*p));
  45241. p->mFlags = SQLITE_DESERIALIZE_RESIZEABLE | SQLITE_DESERIALIZE_FREEONCLOSE;
  45242. assert( pOutFlags!=0 ); /* True because flags==SQLITE_OPEN_MAIN_DB */
  45243. *pOutFlags = flags | SQLITE_OPEN_MEMORY;
  45244. p->base.pMethods = &memdb_io_methods;
  45245. p->szMax = sqlite3GlobalConfig.mxMemdbSize;
  45246. return SQLITE_OK;
  45247. }
  45248. #if 0 /* Only used to delete rollback journals, master journals, and WAL
  45249. ** files, none of which exist in memdb. So this routine is never used */
  45250. /*
  45251. ** Delete the file located at zPath. If the dirSync argument is true,
  45252. ** ensure the file-system modifications are synced to disk before
  45253. ** returning.
  45254. */
  45255. static int memdbDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
  45256. return SQLITE_IOERR_DELETE;
  45257. }
  45258. #endif
  45259. /*
  45260. ** Test for access permissions. Return true if the requested permission
  45261. ** is available, or false otherwise.
  45262. **
  45263. ** With memdb, no files ever exist on disk. So always return false.
  45264. */
  45265. static int memdbAccess(
  45266. sqlite3_vfs *pVfs,
  45267. const char *zPath,
  45268. int flags,
  45269. int *pResOut
  45270. ){
  45271. *pResOut = 0;
  45272. return SQLITE_OK;
  45273. }
  45274. /*
  45275. ** Populate buffer zOut with the full canonical pathname corresponding
  45276. ** to the pathname in zPath. zOut is guaranteed to point to a buffer
  45277. ** of at least (INST_MAX_PATHNAME+1) bytes.
  45278. */
  45279. static int memdbFullPathname(
  45280. sqlite3_vfs *pVfs,
  45281. const char *zPath,
  45282. int nOut,
  45283. char *zOut
  45284. ){
  45285. sqlite3_snprintf(nOut, zOut, "%s", zPath);
  45286. return SQLITE_OK;
  45287. }
  45288. /*
  45289. ** Open the dynamic library located at zPath and return a handle.
  45290. */
  45291. static void *memdbDlOpen(sqlite3_vfs *pVfs, const char *zPath){
  45292. return ORIGVFS(pVfs)->xDlOpen(ORIGVFS(pVfs), zPath);
  45293. }
  45294. /*
  45295. ** Populate the buffer zErrMsg (size nByte bytes) with a human readable
  45296. ** utf-8 string describing the most recent error encountered associated
  45297. ** with dynamic libraries.
  45298. */
  45299. static void memdbDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){
  45300. ORIGVFS(pVfs)->xDlError(ORIGVFS(pVfs), nByte, zErrMsg);
  45301. }
  45302. /*
  45303. ** Return a pointer to the symbol zSymbol in the dynamic library pHandle.
  45304. */
  45305. static void (*memdbDlSym(sqlite3_vfs *pVfs, void *p, const char *zSym))(void){
  45306. return ORIGVFS(pVfs)->xDlSym(ORIGVFS(pVfs), p, zSym);
  45307. }
  45308. /*
  45309. ** Close the dynamic library handle pHandle.
  45310. */
  45311. static void memdbDlClose(sqlite3_vfs *pVfs, void *pHandle){
  45312. ORIGVFS(pVfs)->xDlClose(ORIGVFS(pVfs), pHandle);
  45313. }
  45314. /*
  45315. ** Populate the buffer pointed to by zBufOut with nByte bytes of
  45316. ** random data.
  45317. */
  45318. static int memdbRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
  45319. return ORIGVFS(pVfs)->xRandomness(ORIGVFS(pVfs), nByte, zBufOut);
  45320. }
  45321. /*
  45322. ** Sleep for nMicro microseconds. Return the number of microseconds
  45323. ** actually slept.
  45324. */
  45325. static int memdbSleep(sqlite3_vfs *pVfs, int nMicro){
  45326. return ORIGVFS(pVfs)->xSleep(ORIGVFS(pVfs), nMicro);
  45327. }
  45328. #if 0 /* Never used. Modern cores only call xCurrentTimeInt64() */
  45329. /*
  45330. ** Return the current time as a Julian Day number in *pTimeOut.
  45331. */
  45332. static int memdbCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){
  45333. return ORIGVFS(pVfs)->xCurrentTime(ORIGVFS(pVfs), pTimeOut);
  45334. }
  45335. #endif
  45336. static int memdbGetLastError(sqlite3_vfs *pVfs, int a, char *b){
  45337. return ORIGVFS(pVfs)->xGetLastError(ORIGVFS(pVfs), a, b);
  45338. }
  45339. static int memdbCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *p){
  45340. return ORIGVFS(pVfs)->xCurrentTimeInt64(ORIGVFS(pVfs), p);
  45341. }
  45342. /*
  45343. ** Translate a database connection pointer and schema name into a
  45344. ** MemFile pointer.
  45345. */
  45346. static MemFile *memdbFromDbSchema(sqlite3 *db, const char *zSchema){
  45347. MemFile *p = 0;
  45348. int rc = sqlite3_file_control(db, zSchema, SQLITE_FCNTL_FILE_POINTER, &p);
  45349. if( rc ) return 0;
  45350. if( p->base.pMethods!=&memdb_io_methods ) return 0;
  45351. return p;
  45352. }
  45353. /*
  45354. ** Return the serialization of a database
  45355. */
  45356. SQLITE_API unsigned char *sqlite3_serialize(
  45357. sqlite3 *db, /* The database connection */
  45358. const char *zSchema, /* Which database within the connection */
  45359. sqlite3_int64 *piSize, /* Write size here, if not NULL */
  45360. unsigned int mFlags /* Maybe SQLITE_SERIALIZE_NOCOPY */
  45361. ){
  45362. MemFile *p;
  45363. int iDb;
  45364. Btree *pBt;
  45365. sqlite3_int64 sz;
  45366. int szPage = 0;
  45367. sqlite3_stmt *pStmt = 0;
  45368. unsigned char *pOut;
  45369. char *zSql;
  45370. int rc;
  45371. #ifdef SQLITE_ENABLE_API_ARMOR
  45372. if( !sqlite3SafetyCheckOk(db) ){
  45373. (void)SQLITE_MISUSE_BKPT;
  45374. return 0;
  45375. }
  45376. #endif
  45377. if( zSchema==0 ) zSchema = db->aDb[0].zDbSName;
  45378. p = memdbFromDbSchema(db, zSchema);
  45379. iDb = sqlite3FindDbName(db, zSchema);
  45380. if( piSize ) *piSize = -1;
  45381. if( iDb<0 ) return 0;
  45382. if( p ){
  45383. if( piSize ) *piSize = p->sz;
  45384. if( mFlags & SQLITE_SERIALIZE_NOCOPY ){
  45385. pOut = p->aData;
  45386. }else{
  45387. pOut = sqlite3_malloc64( p->sz );
  45388. if( pOut ) memcpy(pOut, p->aData, p->sz);
  45389. }
  45390. return pOut;
  45391. }
  45392. pBt = db->aDb[iDb].pBt;
  45393. if( pBt==0 ) return 0;
  45394. szPage = sqlite3BtreeGetPageSize(pBt);
  45395. zSql = sqlite3_mprintf("PRAGMA \"%w\".page_count", zSchema);
  45396. rc = zSql ? sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0) : SQLITE_NOMEM;
  45397. sqlite3_free(zSql);
  45398. if( rc ) return 0;
  45399. rc = sqlite3_step(pStmt);
  45400. if( rc!=SQLITE_ROW ){
  45401. pOut = 0;
  45402. }else{
  45403. sz = sqlite3_column_int64(pStmt, 0)*szPage;
  45404. if( piSize ) *piSize = sz;
  45405. if( mFlags & SQLITE_SERIALIZE_NOCOPY ){
  45406. pOut = 0;
  45407. }else{
  45408. pOut = sqlite3_malloc64( sz );
  45409. if( pOut ){
  45410. int nPage = sqlite3_column_int(pStmt, 0);
  45411. Pager *pPager = sqlite3BtreePager(pBt);
  45412. int pgno;
  45413. for(pgno=1; pgno<=nPage; pgno++){
  45414. DbPage *pPage = 0;
  45415. unsigned char *pTo = pOut + szPage*(sqlite3_int64)(pgno-1);
  45416. rc = sqlite3PagerGet(pPager, pgno, (DbPage**)&pPage, 0);
  45417. if( rc==SQLITE_OK ){
  45418. memcpy(pTo, sqlite3PagerGetData(pPage), szPage);
  45419. }else{
  45420. memset(pTo, 0, szPage);
  45421. }
  45422. sqlite3PagerUnref(pPage);
  45423. }
  45424. }
  45425. }
  45426. }
  45427. sqlite3_finalize(pStmt);
  45428. return pOut;
  45429. }
  45430. /* Convert zSchema to a MemDB and initialize its content.
  45431. */
  45432. SQLITE_API int sqlite3_deserialize(
  45433. sqlite3 *db, /* The database connection */
  45434. const char *zSchema, /* Which DB to reopen with the deserialization */
  45435. unsigned char *pData, /* The serialized database content */
  45436. sqlite3_int64 szDb, /* Number bytes in the deserialization */
  45437. sqlite3_int64 szBuf, /* Total size of buffer pData[] */
  45438. unsigned mFlags /* Zero or more SQLITE_DESERIALIZE_* flags */
  45439. ){
  45440. MemFile *p;
  45441. char *zSql;
  45442. sqlite3_stmt *pStmt = 0;
  45443. int rc;
  45444. int iDb;
  45445. #ifdef SQLITE_ENABLE_API_ARMOR
  45446. if( !sqlite3SafetyCheckOk(db) ){
  45447. return SQLITE_MISUSE_BKPT;
  45448. }
  45449. if( szDb<0 ) return SQLITE_MISUSE_BKPT;
  45450. if( szBuf<0 ) return SQLITE_MISUSE_BKPT;
  45451. #endif
  45452. sqlite3_mutex_enter(db->mutex);
  45453. if( zSchema==0 ) zSchema = db->aDb[0].zDbSName;
  45454. iDb = sqlite3FindDbName(db, zSchema);
  45455. if( iDb<0 ){
  45456. rc = SQLITE_ERROR;
  45457. goto end_deserialize;
  45458. }
  45459. zSql = sqlite3_mprintf("ATTACH x AS %Q", zSchema);
  45460. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  45461. sqlite3_free(zSql);
  45462. if( rc ) goto end_deserialize;
  45463. db->init.iDb = (u8)iDb;
  45464. db->init.reopenMemdb = 1;
  45465. rc = sqlite3_step(pStmt);
  45466. db->init.reopenMemdb = 0;
  45467. if( rc!=SQLITE_DONE ){
  45468. rc = SQLITE_ERROR;
  45469. goto end_deserialize;
  45470. }
  45471. p = memdbFromDbSchema(db, zSchema);
  45472. if( p==0 ){
  45473. rc = SQLITE_ERROR;
  45474. }else{
  45475. p->aData = pData;
  45476. p->sz = szDb;
  45477. p->szAlloc = szBuf;
  45478. p->szMax = szBuf;
  45479. if( p->szMax<sqlite3GlobalConfig.mxMemdbSize ){
  45480. p->szMax = sqlite3GlobalConfig.mxMemdbSize;
  45481. }
  45482. p->mFlags = mFlags;
  45483. rc = SQLITE_OK;
  45484. }
  45485. end_deserialize:
  45486. sqlite3_finalize(pStmt);
  45487. sqlite3_mutex_leave(db->mutex);
  45488. return rc;
  45489. }
  45490. /*
  45491. ** This routine is called when the extension is loaded.
  45492. ** Register the new VFS.
  45493. */
  45494. SQLITE_PRIVATE int sqlite3MemdbInit(void){
  45495. sqlite3_vfs *pLower = sqlite3_vfs_find(0);
  45496. int sz = pLower->szOsFile;
  45497. memdb_vfs.pAppData = pLower;
  45498. /* The following conditional can only be true when compiled for
  45499. ** Windows x86 and SQLITE_MAX_MMAP_SIZE=0. We always leave
  45500. ** it in, to be safe, but it is marked as NO_TEST since there
  45501. ** is no way to reach it under most builds. */
  45502. if( sz<sizeof(MemFile) ) sz = sizeof(MemFile); /*NO_TEST*/
  45503. memdb_vfs.szOsFile = sz;
  45504. return sqlite3_vfs_register(&memdb_vfs, 0);
  45505. }
  45506. #endif /* SQLITE_ENABLE_DESERIALIZE */
  45507. /************** End of memdb.c ***********************************************/
  45508. /************** Begin file bitvec.c ******************************************/
  45509. /*
  45510. ** 2008 February 16
  45511. **
  45512. ** The author disclaims copyright to this source code. In place of
  45513. ** a legal notice, here is a blessing:
  45514. **
  45515. ** May you do good and not evil.
  45516. ** May you find forgiveness for yourself and forgive others.
  45517. ** May you share freely, never taking more than you give.
  45518. **
  45519. *************************************************************************
  45520. ** This file implements an object that represents a fixed-length
  45521. ** bitmap. Bits are numbered starting with 1.
  45522. **
  45523. ** A bitmap is used to record which pages of a database file have been
  45524. ** journalled during a transaction, or which pages have the "dont-write"
  45525. ** property. Usually only a few pages are meet either condition.
  45526. ** So the bitmap is usually sparse and has low cardinality.
  45527. ** But sometimes (for example when during a DROP of a large table) most
  45528. ** or all of the pages in a database can get journalled. In those cases,
  45529. ** the bitmap becomes dense with high cardinality. The algorithm needs
  45530. ** to handle both cases well.
  45531. **
  45532. ** The size of the bitmap is fixed when the object is created.
  45533. **
  45534. ** All bits are clear when the bitmap is created. Individual bits
  45535. ** may be set or cleared one at a time.
  45536. **
  45537. ** Test operations are about 100 times more common that set operations.
  45538. ** Clear operations are exceedingly rare. There are usually between
  45539. ** 5 and 500 set operations per Bitvec object, though the number of sets can
  45540. ** sometimes grow into tens of thousands or larger. The size of the
  45541. ** Bitvec object is the number of pages in the database file at the
  45542. ** start of a transaction, and is thus usually less than a few thousand,
  45543. ** but can be as large as 2 billion for a really big database.
  45544. */
  45545. /* #include "sqliteInt.h" */
  45546. /* Size of the Bitvec structure in bytes. */
  45547. #define BITVEC_SZ 512
  45548. /* Round the union size down to the nearest pointer boundary, since that's how
  45549. ** it will be aligned within the Bitvec struct. */
  45550. #define BITVEC_USIZE \
  45551. (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))
  45552. /* Type of the array "element" for the bitmap representation.
  45553. ** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE.
  45554. ** Setting this to the "natural word" size of your CPU may improve
  45555. ** performance. */
  45556. #define BITVEC_TELEM u8
  45557. /* Size, in bits, of the bitmap element. */
  45558. #define BITVEC_SZELEM 8
  45559. /* Number of elements in a bitmap array. */
  45560. #define BITVEC_NELEM (BITVEC_USIZE/sizeof(BITVEC_TELEM))
  45561. /* Number of bits in the bitmap array. */
  45562. #define BITVEC_NBIT (BITVEC_NELEM*BITVEC_SZELEM)
  45563. /* Number of u32 values in hash table. */
  45564. #define BITVEC_NINT (BITVEC_USIZE/sizeof(u32))
  45565. /* Maximum number of entries in hash table before
  45566. ** sub-dividing and re-hashing. */
  45567. #define BITVEC_MXHASH (BITVEC_NINT/2)
  45568. /* Hashing function for the aHash representation.
  45569. ** Empirical testing showed that the *37 multiplier
  45570. ** (an arbitrary prime)in the hash function provided
  45571. ** no fewer collisions than the no-op *1. */
  45572. #define BITVEC_HASH(X) (((X)*1)%BITVEC_NINT)
  45573. #define BITVEC_NPTR (BITVEC_USIZE/sizeof(Bitvec *))
  45574. /*
  45575. ** A bitmap is an instance of the following structure.
  45576. **
  45577. ** This bitmap records the existence of zero or more bits
  45578. ** with values between 1 and iSize, inclusive.
  45579. **
  45580. ** There are three possible representations of the bitmap.
  45581. ** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
  45582. ** bitmap. The least significant bit is bit 1.
  45583. **
  45584. ** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
  45585. ** a hash table that will hold up to BITVEC_MXHASH distinct values.
  45586. **
  45587. ** Otherwise, the value i is redirected into one of BITVEC_NPTR
  45588. ** sub-bitmaps pointed to by Bitvec.u.apSub[]. Each subbitmap
  45589. ** handles up to iDivisor separate values of i. apSub[0] holds
  45590. ** values between 1 and iDivisor. apSub[1] holds values between
  45591. ** iDivisor+1 and 2*iDivisor. apSub[N] holds values between
  45592. ** N*iDivisor+1 and (N+1)*iDivisor. Each subbitmap is normalized
  45593. ** to hold deal with values between 1 and iDivisor.
  45594. */
  45595. struct Bitvec {
  45596. u32 iSize; /* Maximum bit index. Max iSize is 4,294,967,296. */
  45597. u32 nSet; /* Number of bits that are set - only valid for aHash
  45598. ** element. Max is BITVEC_NINT. For BITVEC_SZ of 512,
  45599. ** this would be 125. */
  45600. u32 iDivisor; /* Number of bits handled by each apSub[] entry. */
  45601. /* Should >=0 for apSub element. */
  45602. /* Max iDivisor is max(u32) / BITVEC_NPTR + 1. */
  45603. /* For a BITVEC_SZ of 512, this would be 34,359,739. */
  45604. union {
  45605. BITVEC_TELEM aBitmap[BITVEC_NELEM]; /* Bitmap representation */
  45606. u32 aHash[BITVEC_NINT]; /* Hash table representation */
  45607. Bitvec *apSub[BITVEC_NPTR]; /* Recursive representation */
  45608. } u;
  45609. };
  45610. /*
  45611. ** Create a new bitmap object able to handle bits between 0 and iSize,
  45612. ** inclusive. Return a pointer to the new object. Return NULL if
  45613. ** malloc fails.
  45614. */
  45615. SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){
  45616. Bitvec *p;
  45617. assert( sizeof(*p)==BITVEC_SZ );
  45618. p = sqlite3MallocZero( sizeof(*p) );
  45619. if( p ){
  45620. p->iSize = iSize;
  45621. }
  45622. return p;
  45623. }
  45624. /*
  45625. ** Check to see if the i-th bit is set. Return true or false.
  45626. ** If p is NULL (if the bitmap has not been created) or if
  45627. ** i is out of range, then return false.
  45628. */
  45629. SQLITE_PRIVATE int sqlite3BitvecTestNotNull(Bitvec *p, u32 i){
  45630. assert( p!=0 );
  45631. i--;
  45632. if( i>=p->iSize ) return 0;
  45633. while( p->iDivisor ){
  45634. u32 bin = i/p->iDivisor;
  45635. i = i%p->iDivisor;
  45636. p = p->u.apSub[bin];
  45637. if (!p) {
  45638. return 0;
  45639. }
  45640. }
  45641. if( p->iSize<=BITVEC_NBIT ){
  45642. return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0;
  45643. } else{
  45644. u32 h = BITVEC_HASH(i++);
  45645. while( p->u.aHash[h] ){
  45646. if( p->u.aHash[h]==i ) return 1;
  45647. h = (h+1) % BITVEC_NINT;
  45648. }
  45649. return 0;
  45650. }
  45651. }
  45652. SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){
  45653. return p!=0 && sqlite3BitvecTestNotNull(p,i);
  45654. }
  45655. /*
  45656. ** Set the i-th bit. Return 0 on success and an error code if
  45657. ** anything goes wrong.
  45658. **
  45659. ** This routine might cause sub-bitmaps to be allocated. Failing
  45660. ** to get the memory needed to hold the sub-bitmap is the only
  45661. ** that can go wrong with an insert, assuming p and i are valid.
  45662. **
  45663. ** The calling function must ensure that p is a valid Bitvec object
  45664. ** and that the value for "i" is within range of the Bitvec object.
  45665. ** Otherwise the behavior is undefined.
  45666. */
  45667. SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){
  45668. u32 h;
  45669. if( p==0 ) return SQLITE_OK;
  45670. assert( i>0 );
  45671. assert( i<=p->iSize );
  45672. i--;
  45673. while((p->iSize > BITVEC_NBIT) && p->iDivisor) {
  45674. u32 bin = i/p->iDivisor;
  45675. i = i%p->iDivisor;
  45676. if( p->u.apSub[bin]==0 ){
  45677. p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
  45678. if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM_BKPT;
  45679. }
  45680. p = p->u.apSub[bin];
  45681. }
  45682. if( p->iSize<=BITVEC_NBIT ){
  45683. p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1));
  45684. return SQLITE_OK;
  45685. }
  45686. h = BITVEC_HASH(i++);
  45687. /* if there wasn't a hash collision, and this doesn't */
  45688. /* completely fill the hash, then just add it without */
  45689. /* worring about sub-dividing and re-hashing. */
  45690. if( !p->u.aHash[h] ){
  45691. if (p->nSet<(BITVEC_NINT-1)) {
  45692. goto bitvec_set_end;
  45693. } else {
  45694. goto bitvec_set_rehash;
  45695. }
  45696. }
  45697. /* there was a collision, check to see if it's already */
  45698. /* in hash, if not, try to find a spot for it */
  45699. do {
  45700. if( p->u.aHash[h]==i ) return SQLITE_OK;
  45701. h++;
  45702. if( h>=BITVEC_NINT ) h = 0;
  45703. } while( p->u.aHash[h] );
  45704. /* we didn't find it in the hash. h points to the first */
  45705. /* available free spot. check to see if this is going to */
  45706. /* make our hash too "full". */
  45707. bitvec_set_rehash:
  45708. if( p->nSet>=BITVEC_MXHASH ){
  45709. unsigned int j;
  45710. int rc;
  45711. u32 *aiValues = sqlite3StackAllocRaw(0, sizeof(p->u.aHash));
  45712. if( aiValues==0 ){
  45713. return SQLITE_NOMEM_BKPT;
  45714. }else{
  45715. memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
  45716. memset(p->u.apSub, 0, sizeof(p->u.apSub));
  45717. p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
  45718. rc = sqlite3BitvecSet(p, i);
  45719. for(j=0; j<BITVEC_NINT; j++){
  45720. if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);
  45721. }
  45722. sqlite3StackFree(0, aiValues);
  45723. return rc;
  45724. }
  45725. }
  45726. bitvec_set_end:
  45727. p->nSet++;
  45728. p->u.aHash[h] = i;
  45729. return SQLITE_OK;
  45730. }
  45731. /*
  45732. ** Clear the i-th bit.
  45733. **
  45734. ** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage
  45735. ** that BitvecClear can use to rebuilt its hash table.
  45736. */
  45737. SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){
  45738. if( p==0 ) return;
  45739. assert( i>0 );
  45740. i--;
  45741. while( p->iDivisor ){
  45742. u32 bin = i/p->iDivisor;
  45743. i = i%p->iDivisor;
  45744. p = p->u.apSub[bin];
  45745. if (!p) {
  45746. return;
  45747. }
  45748. }
  45749. if( p->iSize<=BITVEC_NBIT ){
  45750. p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1)));
  45751. }else{
  45752. unsigned int j;
  45753. u32 *aiValues = pBuf;
  45754. memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
  45755. memset(p->u.aHash, 0, sizeof(p->u.aHash));
  45756. p->nSet = 0;
  45757. for(j=0; j<BITVEC_NINT; j++){
  45758. if( aiValues[j] && aiValues[j]!=(i+1) ){
  45759. u32 h = BITVEC_HASH(aiValues[j]-1);
  45760. p->nSet++;
  45761. while( p->u.aHash[h] ){
  45762. h++;
  45763. if( h>=BITVEC_NINT ) h = 0;
  45764. }
  45765. p->u.aHash[h] = aiValues[j];
  45766. }
  45767. }
  45768. }
  45769. }
  45770. /*
  45771. ** Destroy a bitmap object. Reclaim all memory used.
  45772. */
  45773. SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){
  45774. if( p==0 ) return;
  45775. if( p->iDivisor ){
  45776. unsigned int i;
  45777. for(i=0; i<BITVEC_NPTR; i++){
  45778. sqlite3BitvecDestroy(p->u.apSub[i]);
  45779. }
  45780. }
  45781. sqlite3_free(p);
  45782. }
  45783. /*
  45784. ** Return the value of the iSize parameter specified when Bitvec *p
  45785. ** was created.
  45786. */
  45787. SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){
  45788. return p->iSize;
  45789. }
  45790. #ifndef SQLITE_UNTESTABLE
  45791. /*
  45792. ** Let V[] be an array of unsigned characters sufficient to hold
  45793. ** up to N bits. Let I be an integer between 0 and N. 0<=I<N.
  45794. ** Then the following macros can be used to set, clear, or test
  45795. ** individual bits within V.
  45796. */
  45797. #define SETBIT(V,I) V[I>>3] |= (1<<(I&7))
  45798. #define CLEARBIT(V,I) V[I>>3] &= ~(1<<(I&7))
  45799. #define TESTBIT(V,I) (V[I>>3]&(1<<(I&7)))!=0
  45800. /*
  45801. ** This routine runs an extensive test of the Bitvec code.
  45802. **
  45803. ** The input is an array of integers that acts as a program
  45804. ** to test the Bitvec. The integers are opcodes followed
  45805. ** by 0, 1, or 3 operands, depending on the opcode. Another
  45806. ** opcode follows immediately after the last operand.
  45807. **
  45808. ** There are 6 opcodes numbered from 0 through 5. 0 is the
  45809. ** "halt" opcode and causes the test to end.
  45810. **
  45811. ** 0 Halt and return the number of errors
  45812. ** 1 N S X Set N bits beginning with S and incrementing by X
  45813. ** 2 N S X Clear N bits beginning with S and incrementing by X
  45814. ** 3 N Set N randomly chosen bits
  45815. ** 4 N Clear N randomly chosen bits
  45816. ** 5 N S X Set N bits from S increment X in array only, not in bitvec
  45817. **
  45818. ** The opcodes 1 through 4 perform set and clear operations are performed
  45819. ** on both a Bitvec object and on a linear array of bits obtained from malloc.
  45820. ** Opcode 5 works on the linear array only, not on the Bitvec.
  45821. ** Opcode 5 is used to deliberately induce a fault in order to
  45822. ** confirm that error detection works.
  45823. **
  45824. ** At the conclusion of the test the linear array is compared
  45825. ** against the Bitvec object. If there are any differences,
  45826. ** an error is returned. If they are the same, zero is returned.
  45827. **
  45828. ** If a memory allocation error occurs, return -1.
  45829. */
  45830. SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){
  45831. Bitvec *pBitvec = 0;
  45832. unsigned char *pV = 0;
  45833. int rc = -1;
  45834. int i, nx, pc, op;
  45835. void *pTmpSpace;
  45836. /* Allocate the Bitvec to be tested and a linear array of
  45837. ** bits to act as the reference */
  45838. pBitvec = sqlite3BitvecCreate( sz );
  45839. pV = sqlite3MallocZero( (sz+7)/8 + 1 );
  45840. pTmpSpace = sqlite3_malloc64(BITVEC_SZ);
  45841. if( pBitvec==0 || pV==0 || pTmpSpace==0 ) goto bitvec_end;
  45842. /* NULL pBitvec tests */
  45843. sqlite3BitvecSet(0, 1);
  45844. sqlite3BitvecClear(0, 1, pTmpSpace);
  45845. /* Run the program */
  45846. pc = 0;
  45847. while( (op = aOp[pc])!=0 ){
  45848. switch( op ){
  45849. case 1:
  45850. case 2:
  45851. case 5: {
  45852. nx = 4;
  45853. i = aOp[pc+2] - 1;
  45854. aOp[pc+2] += aOp[pc+3];
  45855. break;
  45856. }
  45857. case 3:
  45858. case 4:
  45859. default: {
  45860. nx = 2;
  45861. sqlite3_randomness(sizeof(i), &i);
  45862. break;
  45863. }
  45864. }
  45865. if( (--aOp[pc+1]) > 0 ) nx = 0;
  45866. pc += nx;
  45867. i = (i & 0x7fffffff)%sz;
  45868. if( (op & 1)!=0 ){
  45869. SETBIT(pV, (i+1));
  45870. if( op!=5 ){
  45871. if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;
  45872. }
  45873. }else{
  45874. CLEARBIT(pV, (i+1));
  45875. sqlite3BitvecClear(pBitvec, i+1, pTmpSpace);
  45876. }
  45877. }
  45878. /* Test to make sure the linear array exactly matches the
  45879. ** Bitvec object. Start with the assumption that they do
  45880. ** match (rc==0). Change rc to non-zero if a discrepancy
  45881. ** is found.
  45882. */
  45883. rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)
  45884. + sqlite3BitvecTest(pBitvec, 0)
  45885. + (sqlite3BitvecSize(pBitvec) - sz);
  45886. for(i=1; i<=sz; i++){
  45887. if( (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){
  45888. rc = i;
  45889. break;
  45890. }
  45891. }
  45892. /* Free allocated structure */
  45893. bitvec_end:
  45894. sqlite3_free(pTmpSpace);
  45895. sqlite3_free(pV);
  45896. sqlite3BitvecDestroy(pBitvec);
  45897. return rc;
  45898. }
  45899. #endif /* SQLITE_UNTESTABLE */
  45900. /************** End of bitvec.c **********************************************/
  45901. /************** Begin file pcache.c ******************************************/
  45902. /*
  45903. ** 2008 August 05
  45904. **
  45905. ** The author disclaims copyright to this source code. In place of
  45906. ** a legal notice, here is a blessing:
  45907. **
  45908. ** May you do good and not evil.
  45909. ** May you find forgiveness for yourself and forgive others.
  45910. ** May you share freely, never taking more than you give.
  45911. **
  45912. *************************************************************************
  45913. ** This file implements that page cache.
  45914. */
  45915. /* #include "sqliteInt.h" */
  45916. /*
  45917. ** A complete page cache is an instance of this structure. Every
  45918. ** entry in the cache holds a single page of the database file. The
  45919. ** btree layer only operates on the cached copy of the database pages.
  45920. **
  45921. ** A page cache entry is "clean" if it exactly matches what is currently
  45922. ** on disk. A page is "dirty" if it has been modified and needs to be
  45923. ** persisted to disk.
  45924. **
  45925. ** pDirty, pDirtyTail, pSynced:
  45926. ** All dirty pages are linked into the doubly linked list using
  45927. ** PgHdr.pDirtyNext and pDirtyPrev. The list is maintained in LRU order
  45928. ** such that p was added to the list more recently than p->pDirtyNext.
  45929. ** PCache.pDirty points to the first (newest) element in the list and
  45930. ** pDirtyTail to the last (oldest).
  45931. **
  45932. ** The PCache.pSynced variable is used to optimize searching for a dirty
  45933. ** page to eject from the cache mid-transaction. It is better to eject
  45934. ** a page that does not require a journal sync than one that does.
  45935. ** Therefore, pSynced is maintained so that it *almost* always points
  45936. ** to either the oldest page in the pDirty/pDirtyTail list that has a
  45937. ** clear PGHDR_NEED_SYNC flag or to a page that is older than this one
  45938. ** (so that the right page to eject can be found by following pDirtyPrev
  45939. ** pointers).
  45940. */
  45941. struct PCache {
  45942. PgHdr *pDirty, *pDirtyTail; /* List of dirty pages in LRU order */
  45943. PgHdr *pSynced; /* Last synced page in dirty page list */
  45944. int nRefSum; /* Sum of ref counts over all pages */
  45945. int szCache; /* Configured cache size */
  45946. int szSpill; /* Size before spilling occurs */
  45947. int szPage; /* Size of every page in this cache */
  45948. int szExtra; /* Size of extra space for each page */
  45949. u8 bPurgeable; /* True if pages are on backing store */
  45950. u8 eCreate; /* eCreate value for for xFetch() */
  45951. int (*xStress)(void*,PgHdr*); /* Call to try make a page clean */
  45952. void *pStress; /* Argument to xStress */
  45953. sqlite3_pcache *pCache; /* Pluggable cache module */
  45954. };
  45955. /********************************** Test and Debug Logic **********************/
  45956. /*
  45957. ** Debug tracing macros. Enable by by changing the "0" to "1" and
  45958. ** recompiling.
  45959. **
  45960. ** When sqlite3PcacheTrace is 1, single line trace messages are issued.
  45961. ** When sqlite3PcacheTrace is 2, a dump of the pcache showing all cache entries
  45962. ** is displayed for many operations, resulting in a lot of output.
  45963. */
  45964. #if defined(SQLITE_DEBUG) && 0
  45965. int sqlite3PcacheTrace = 2; /* 0: off 1: simple 2: cache dumps */
  45966. int sqlite3PcacheMxDump = 9999; /* Max cache entries for pcacheDump() */
  45967. # define pcacheTrace(X) if(sqlite3PcacheTrace){sqlite3DebugPrintf X;}
  45968. void pcacheDump(PCache *pCache){
  45969. int N;
  45970. int i, j;
  45971. sqlite3_pcache_page *pLower;
  45972. PgHdr *pPg;
  45973. unsigned char *a;
  45974. if( sqlite3PcacheTrace<2 ) return;
  45975. if( pCache->pCache==0 ) return;
  45976. N = sqlite3PcachePagecount(pCache);
  45977. if( N>sqlite3PcacheMxDump ) N = sqlite3PcacheMxDump;
  45978. for(i=1; i<=N; i++){
  45979. pLower = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, i, 0);
  45980. if( pLower==0 ) continue;
  45981. pPg = (PgHdr*)pLower->pExtra;
  45982. printf("%3d: nRef %2d flgs %02x data ", i, pPg->nRef, pPg->flags);
  45983. a = (unsigned char *)pLower->pBuf;
  45984. for(j=0; j<12; j++) printf("%02x", a[j]);
  45985. printf("\n");
  45986. if( pPg->pPage==0 ){
  45987. sqlite3GlobalConfig.pcache2.xUnpin(pCache->pCache, pLower, 0);
  45988. }
  45989. }
  45990. }
  45991. #else
  45992. # define pcacheTrace(X)
  45993. # define pcacheDump(X)
  45994. #endif
  45995. /*
  45996. ** Check invariants on a PgHdr entry. Return true if everything is OK.
  45997. ** Return false if any invariant is violated.
  45998. **
  45999. ** This routine is for use inside of assert() statements only. For
  46000. ** example:
  46001. **
  46002. ** assert( sqlite3PcachePageSanity(pPg) );
  46003. */
  46004. #ifdef SQLITE_DEBUG
  46005. SQLITE_PRIVATE int sqlite3PcachePageSanity(PgHdr *pPg){
  46006. PCache *pCache;
  46007. assert( pPg!=0 );
  46008. assert( pPg->pgno>0 || pPg->pPager==0 ); /* Page number is 1 or more */
  46009. pCache = pPg->pCache;
  46010. assert( pCache!=0 ); /* Every page has an associated PCache */
  46011. if( pPg->flags & PGHDR_CLEAN ){
  46012. assert( (pPg->flags & PGHDR_DIRTY)==0 );/* Cannot be both CLEAN and DIRTY */
  46013. assert( pCache->pDirty!=pPg ); /* CLEAN pages not on dirty list */
  46014. assert( pCache->pDirtyTail!=pPg );
  46015. }
  46016. /* WRITEABLE pages must also be DIRTY */
  46017. if( pPg->flags & PGHDR_WRITEABLE ){
  46018. assert( pPg->flags & PGHDR_DIRTY ); /* WRITEABLE implies DIRTY */
  46019. }
  46020. /* NEED_SYNC can be set independently of WRITEABLE. This can happen,
  46021. ** for example, when using the sqlite3PagerDontWrite() optimization:
  46022. ** (1) Page X is journalled, and gets WRITEABLE and NEED_SEEK.
  46023. ** (2) Page X moved to freelist, WRITEABLE is cleared
  46024. ** (3) Page X reused, WRITEABLE is set again
  46025. ** If NEED_SYNC had been cleared in step 2, then it would not be reset
  46026. ** in step 3, and page might be written into the database without first
  46027. ** syncing the rollback journal, which might cause corruption on a power
  46028. ** loss.
  46029. **
  46030. ** Another example is when the database page size is smaller than the
  46031. ** disk sector size. When any page of a sector is journalled, all pages
  46032. ** in that sector are marked NEED_SYNC even if they are still CLEAN, just
  46033. ** in case they are later modified, since all pages in the same sector
  46034. ** must be journalled and synced before any of those pages can be safely
  46035. ** written.
  46036. */
  46037. return 1;
  46038. }
  46039. #endif /* SQLITE_DEBUG */
  46040. /********************************** Linked List Management ********************/
  46041. /* Allowed values for second argument to pcacheManageDirtyList() */
  46042. #define PCACHE_DIRTYLIST_REMOVE 1 /* Remove pPage from dirty list */
  46043. #define PCACHE_DIRTYLIST_ADD 2 /* Add pPage to the dirty list */
  46044. #define PCACHE_DIRTYLIST_FRONT 3 /* Move pPage to the front of the list */
  46045. /*
  46046. ** Manage pPage's participation on the dirty list. Bits of the addRemove
  46047. ** argument determines what operation to do. The 0x01 bit means first
  46048. ** remove pPage from the dirty list. The 0x02 means add pPage back to
  46049. ** the dirty list. Doing both moves pPage to the front of the dirty list.
  46050. */
  46051. static void pcacheManageDirtyList(PgHdr *pPage, u8 addRemove){
  46052. PCache *p = pPage->pCache;
  46053. pcacheTrace(("%p.DIRTYLIST.%s %d\n", p,
  46054. addRemove==1 ? "REMOVE" : addRemove==2 ? "ADD" : "FRONT",
  46055. pPage->pgno));
  46056. if( addRemove & PCACHE_DIRTYLIST_REMOVE ){
  46057. assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
  46058. assert( pPage->pDirtyPrev || pPage==p->pDirty );
  46059. /* Update the PCache1.pSynced variable if necessary. */
  46060. if( p->pSynced==pPage ){
  46061. p->pSynced = pPage->pDirtyPrev;
  46062. }
  46063. if( pPage->pDirtyNext ){
  46064. pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
  46065. }else{
  46066. assert( pPage==p->pDirtyTail );
  46067. p->pDirtyTail = pPage->pDirtyPrev;
  46068. }
  46069. if( pPage->pDirtyPrev ){
  46070. pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
  46071. }else{
  46072. /* If there are now no dirty pages in the cache, set eCreate to 2.
  46073. ** This is an optimization that allows sqlite3PcacheFetch() to skip
  46074. ** searching for a dirty page to eject from the cache when it might
  46075. ** otherwise have to. */
  46076. assert( pPage==p->pDirty );
  46077. p->pDirty = pPage->pDirtyNext;
  46078. assert( p->bPurgeable || p->eCreate==2 );
  46079. if( p->pDirty==0 ){ /*OPTIMIZATION-IF-TRUE*/
  46080. assert( p->bPurgeable==0 || p->eCreate==1 );
  46081. p->eCreate = 2;
  46082. }
  46083. }
  46084. }
  46085. if( addRemove & PCACHE_DIRTYLIST_ADD ){
  46086. pPage->pDirtyPrev = 0;
  46087. pPage->pDirtyNext = p->pDirty;
  46088. if( pPage->pDirtyNext ){
  46089. assert( pPage->pDirtyNext->pDirtyPrev==0 );
  46090. pPage->pDirtyNext->pDirtyPrev = pPage;
  46091. }else{
  46092. p->pDirtyTail = pPage;
  46093. if( p->bPurgeable ){
  46094. assert( p->eCreate==2 );
  46095. p->eCreate = 1;
  46096. }
  46097. }
  46098. p->pDirty = pPage;
  46099. /* If pSynced is NULL and this page has a clear NEED_SYNC flag, set
  46100. ** pSynced to point to it. Checking the NEED_SYNC flag is an
  46101. ** optimization, as if pSynced points to a page with the NEED_SYNC
  46102. ** flag set sqlite3PcacheFetchStress() searches through all newer
  46103. ** entries of the dirty-list for a page with NEED_SYNC clear anyway. */
  46104. if( !p->pSynced
  46105. && 0==(pPage->flags&PGHDR_NEED_SYNC) /*OPTIMIZATION-IF-FALSE*/
  46106. ){
  46107. p->pSynced = pPage;
  46108. }
  46109. }
  46110. pcacheDump(p);
  46111. }
  46112. /*
  46113. ** Wrapper around the pluggable caches xUnpin method. If the cache is
  46114. ** being used for an in-memory database, this function is a no-op.
  46115. */
  46116. static void pcacheUnpin(PgHdr *p){
  46117. if( p->pCache->bPurgeable ){
  46118. pcacheTrace(("%p.UNPIN %d\n", p->pCache, p->pgno));
  46119. sqlite3GlobalConfig.pcache2.xUnpin(p->pCache->pCache, p->pPage, 0);
  46120. pcacheDump(p->pCache);
  46121. }
  46122. }
  46123. /*
  46124. ** Compute the number of pages of cache requested. p->szCache is the
  46125. ** cache size requested by the "PRAGMA cache_size" statement.
  46126. */
  46127. static int numberOfCachePages(PCache *p){
  46128. if( p->szCache>=0 ){
  46129. /* IMPLEMENTATION-OF: R-42059-47211 If the argument N is positive then the
  46130. ** suggested cache size is set to N. */
  46131. return p->szCache;
  46132. }else{
  46133. /* IMPLEMANTATION-OF: R-59858-46238 If the argument N is negative, then the
  46134. ** number of cache pages is adjusted to be a number of pages that would
  46135. ** use approximately abs(N*1024) bytes of memory based on the current
  46136. ** page size. */
  46137. return (int)((-1024*(i64)p->szCache)/(p->szPage+p->szExtra));
  46138. }
  46139. }
  46140. /*************************************************** General Interfaces ******
  46141. **
  46142. ** Initialize and shutdown the page cache subsystem. Neither of these
  46143. ** functions are threadsafe.
  46144. */
  46145. SQLITE_PRIVATE int sqlite3PcacheInitialize(void){
  46146. if( sqlite3GlobalConfig.pcache2.xInit==0 ){
  46147. /* IMPLEMENTATION-OF: R-26801-64137 If the xInit() method is NULL, then the
  46148. ** built-in default page cache is used instead of the application defined
  46149. ** page cache. */
  46150. sqlite3PCacheSetDefault();
  46151. assert( sqlite3GlobalConfig.pcache2.xInit!=0 );
  46152. }
  46153. return sqlite3GlobalConfig.pcache2.xInit(sqlite3GlobalConfig.pcache2.pArg);
  46154. }
  46155. SQLITE_PRIVATE void sqlite3PcacheShutdown(void){
  46156. if( sqlite3GlobalConfig.pcache2.xShutdown ){
  46157. /* IMPLEMENTATION-OF: R-26000-56589 The xShutdown() method may be NULL. */
  46158. sqlite3GlobalConfig.pcache2.xShutdown(sqlite3GlobalConfig.pcache2.pArg);
  46159. }
  46160. }
  46161. /*
  46162. ** Return the size in bytes of a PCache object.
  46163. */
  46164. SQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); }
  46165. /*
  46166. ** Create a new PCache object. Storage space to hold the object
  46167. ** has already been allocated and is passed in as the p pointer.
  46168. ** The caller discovers how much space needs to be allocated by
  46169. ** calling sqlite3PcacheSize().
  46170. **
  46171. ** szExtra is some extra space allocated for each page. The first
  46172. ** 8 bytes of the extra space will be zeroed as the page is allocated,
  46173. ** but remaining content will be uninitialized. Though it is opaque
  46174. ** to this module, the extra space really ends up being the MemPage
  46175. ** structure in the pager.
  46176. */
  46177. SQLITE_PRIVATE int sqlite3PcacheOpen(
  46178. int szPage, /* Size of every page */
  46179. int szExtra, /* Extra space associated with each page */
  46180. int bPurgeable, /* True if pages are on backing store */
  46181. int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
  46182. void *pStress, /* Argument to xStress */
  46183. PCache *p /* Preallocated space for the PCache */
  46184. ){
  46185. memset(p, 0, sizeof(PCache));
  46186. p->szPage = 1;
  46187. p->szExtra = szExtra;
  46188. assert( szExtra>=8 ); /* First 8 bytes will be zeroed */
  46189. p->bPurgeable = bPurgeable;
  46190. p->eCreate = 2;
  46191. p->xStress = xStress;
  46192. p->pStress = pStress;
  46193. p->szCache = 100;
  46194. p->szSpill = 1;
  46195. pcacheTrace(("%p.OPEN szPage %d bPurgeable %d\n",p,szPage,bPurgeable));
  46196. return sqlite3PcacheSetPageSize(p, szPage);
  46197. }
  46198. /*
  46199. ** Change the page size for PCache object. The caller must ensure that there
  46200. ** are no outstanding page references when this function is called.
  46201. */
  46202. SQLITE_PRIVATE int sqlite3PcacheSetPageSize(PCache *pCache, int szPage){
  46203. assert( pCache->nRefSum==0 && pCache->pDirty==0 );
  46204. if( pCache->szPage ){
  46205. sqlite3_pcache *pNew;
  46206. pNew = sqlite3GlobalConfig.pcache2.xCreate(
  46207. szPage, pCache->szExtra + ROUND8(sizeof(PgHdr)),
  46208. pCache->bPurgeable
  46209. );
  46210. if( pNew==0 ) return SQLITE_NOMEM_BKPT;
  46211. sqlite3GlobalConfig.pcache2.xCachesize(pNew, numberOfCachePages(pCache));
  46212. if( pCache->pCache ){
  46213. sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
  46214. }
  46215. pCache->pCache = pNew;
  46216. pCache->szPage = szPage;
  46217. pcacheTrace(("%p.PAGESIZE %d\n",pCache,szPage));
  46218. }
  46219. return SQLITE_OK;
  46220. }
  46221. /*
  46222. ** Try to obtain a page from the cache.
  46223. **
  46224. ** This routine returns a pointer to an sqlite3_pcache_page object if
  46225. ** such an object is already in cache, or if a new one is created.
  46226. ** This routine returns a NULL pointer if the object was not in cache
  46227. ** and could not be created.
  46228. **
  46229. ** The createFlags should be 0 to check for existing pages and should
  46230. ** be 3 (not 1, but 3) to try to create a new page.
  46231. **
  46232. ** If the createFlag is 0, then NULL is always returned if the page
  46233. ** is not already in the cache. If createFlag is 1, then a new page
  46234. ** is created only if that can be done without spilling dirty pages
  46235. ** and without exceeding the cache size limit.
  46236. **
  46237. ** The caller needs to invoke sqlite3PcacheFetchFinish() to properly
  46238. ** initialize the sqlite3_pcache_page object and convert it into a
  46239. ** PgHdr object. The sqlite3PcacheFetch() and sqlite3PcacheFetchFinish()
  46240. ** routines are split this way for performance reasons. When separated
  46241. ** they can both (usually) operate without having to push values to
  46242. ** the stack on entry and pop them back off on exit, which saves a
  46243. ** lot of pushing and popping.
  46244. */
  46245. SQLITE_PRIVATE sqlite3_pcache_page *sqlite3PcacheFetch(
  46246. PCache *pCache, /* Obtain the page from this cache */
  46247. Pgno pgno, /* Page number to obtain */
  46248. int createFlag /* If true, create page if it does not exist already */
  46249. ){
  46250. int eCreate;
  46251. sqlite3_pcache_page *pRes;
  46252. assert( pCache!=0 );
  46253. assert( pCache->pCache!=0 );
  46254. assert( createFlag==3 || createFlag==0 );
  46255. assert( pCache->eCreate==((pCache->bPurgeable && pCache->pDirty) ? 1 : 2) );
  46256. /* eCreate defines what to do if the page does not exist.
  46257. ** 0 Do not allocate a new page. (createFlag==0)
  46258. ** 1 Allocate a new page if doing so is inexpensive.
  46259. ** (createFlag==1 AND bPurgeable AND pDirty)
  46260. ** 2 Allocate a new page even it doing so is difficult.
  46261. ** (createFlag==1 AND !(bPurgeable AND pDirty)
  46262. */
  46263. eCreate = createFlag & pCache->eCreate;
  46264. assert( eCreate==0 || eCreate==1 || eCreate==2 );
  46265. assert( createFlag==0 || pCache->eCreate==eCreate );
  46266. assert( createFlag==0 || eCreate==1+(!pCache->bPurgeable||!pCache->pDirty) );
  46267. pRes = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, eCreate);
  46268. pcacheTrace(("%p.FETCH %d%s (result: %p)\n",pCache,pgno,
  46269. createFlag?" create":"",pRes));
  46270. return pRes;
  46271. }
  46272. /*
  46273. ** If the sqlite3PcacheFetch() routine is unable to allocate a new
  46274. ** page because no clean pages are available for reuse and the cache
  46275. ** size limit has been reached, then this routine can be invoked to
  46276. ** try harder to allocate a page. This routine might invoke the stress
  46277. ** callback to spill dirty pages to the journal. It will then try to
  46278. ** allocate the new page and will only fail to allocate a new page on
  46279. ** an OOM error.
  46280. **
  46281. ** This routine should be invoked only after sqlite3PcacheFetch() fails.
  46282. */
  46283. SQLITE_PRIVATE int sqlite3PcacheFetchStress(
  46284. PCache *pCache, /* Obtain the page from this cache */
  46285. Pgno pgno, /* Page number to obtain */
  46286. sqlite3_pcache_page **ppPage /* Write result here */
  46287. ){
  46288. PgHdr *pPg;
  46289. if( pCache->eCreate==2 ) return 0;
  46290. if( sqlite3PcachePagecount(pCache)>pCache->szSpill ){
  46291. /* Find a dirty page to write-out and recycle. First try to find a
  46292. ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
  46293. ** cleared), but if that is not possible settle for any other
  46294. ** unreferenced dirty page.
  46295. **
  46296. ** If the LRU page in the dirty list that has a clear PGHDR_NEED_SYNC
  46297. ** flag is currently referenced, then the following may leave pSynced
  46298. ** set incorrectly (pointing to other than the LRU page with NEED_SYNC
  46299. ** cleared). This is Ok, as pSynced is just an optimization. */
  46300. for(pPg=pCache->pSynced;
  46301. pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC));
  46302. pPg=pPg->pDirtyPrev
  46303. );
  46304. pCache->pSynced = pPg;
  46305. if( !pPg ){
  46306. for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);
  46307. }
  46308. if( pPg ){
  46309. int rc;
  46310. #ifdef SQLITE_LOG_CACHE_SPILL
  46311. sqlite3_log(SQLITE_FULL,
  46312. "spill page %d making room for %d - cache used: %d/%d",
  46313. pPg->pgno, pgno,
  46314. sqlite3GlobalConfig.pcache2.xPagecount(pCache->pCache),
  46315. numberOfCachePages(pCache));
  46316. #endif
  46317. pcacheTrace(("%p.SPILL %d\n",pCache,pPg->pgno));
  46318. rc = pCache->xStress(pCache->pStress, pPg);
  46319. pcacheDump(pCache);
  46320. if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
  46321. return rc;
  46322. }
  46323. }
  46324. }
  46325. *ppPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, 2);
  46326. return *ppPage==0 ? SQLITE_NOMEM_BKPT : SQLITE_OK;
  46327. }
  46328. /*
  46329. ** This is a helper routine for sqlite3PcacheFetchFinish()
  46330. **
  46331. ** In the uncommon case where the page being fetched has not been
  46332. ** initialized, this routine is invoked to do the initialization.
  46333. ** This routine is broken out into a separate function since it
  46334. ** requires extra stack manipulation that can be avoided in the common
  46335. ** case.
  46336. */
  46337. static SQLITE_NOINLINE PgHdr *pcacheFetchFinishWithInit(
  46338. PCache *pCache, /* Obtain the page from this cache */
  46339. Pgno pgno, /* Page number obtained */
  46340. sqlite3_pcache_page *pPage /* Page obtained by prior PcacheFetch() call */
  46341. ){
  46342. PgHdr *pPgHdr;
  46343. assert( pPage!=0 );
  46344. pPgHdr = (PgHdr*)pPage->pExtra;
  46345. assert( pPgHdr->pPage==0 );
  46346. memset(&pPgHdr->pDirty, 0, sizeof(PgHdr) - offsetof(PgHdr,pDirty));
  46347. pPgHdr->pPage = pPage;
  46348. pPgHdr->pData = pPage->pBuf;
  46349. pPgHdr->pExtra = (void *)&pPgHdr[1];
  46350. memset(pPgHdr->pExtra, 0, 8);
  46351. pPgHdr->pCache = pCache;
  46352. pPgHdr->pgno = pgno;
  46353. pPgHdr->flags = PGHDR_CLEAN;
  46354. return sqlite3PcacheFetchFinish(pCache,pgno,pPage);
  46355. }
  46356. /*
  46357. ** This routine converts the sqlite3_pcache_page object returned by
  46358. ** sqlite3PcacheFetch() into an initialized PgHdr object. This routine
  46359. ** must be called after sqlite3PcacheFetch() in order to get a usable
  46360. ** result.
  46361. */
  46362. SQLITE_PRIVATE PgHdr *sqlite3PcacheFetchFinish(
  46363. PCache *pCache, /* Obtain the page from this cache */
  46364. Pgno pgno, /* Page number obtained */
  46365. sqlite3_pcache_page *pPage /* Page obtained by prior PcacheFetch() call */
  46366. ){
  46367. PgHdr *pPgHdr;
  46368. assert( pPage!=0 );
  46369. pPgHdr = (PgHdr *)pPage->pExtra;
  46370. if( !pPgHdr->pPage ){
  46371. return pcacheFetchFinishWithInit(pCache, pgno, pPage);
  46372. }
  46373. pCache->nRefSum++;
  46374. pPgHdr->nRef++;
  46375. assert( sqlite3PcachePageSanity(pPgHdr) );
  46376. return pPgHdr;
  46377. }
  46378. /*
  46379. ** Decrement the reference count on a page. If the page is clean and the
  46380. ** reference count drops to 0, then it is made eligible for recycling.
  46381. */
  46382. SQLITE_PRIVATE void SQLITE_NOINLINE sqlite3PcacheRelease(PgHdr *p){
  46383. assert( p->nRef>0 );
  46384. p->pCache->nRefSum--;
  46385. if( (--p->nRef)==0 ){
  46386. if( p->flags&PGHDR_CLEAN ){
  46387. pcacheUnpin(p);
  46388. }else{
  46389. pcacheManageDirtyList(p, PCACHE_DIRTYLIST_FRONT);
  46390. }
  46391. }
  46392. }
  46393. /*
  46394. ** Increase the reference count of a supplied page by 1.
  46395. */
  46396. SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){
  46397. assert(p->nRef>0);
  46398. assert( sqlite3PcachePageSanity(p) );
  46399. p->nRef++;
  46400. p->pCache->nRefSum++;
  46401. }
  46402. /*
  46403. ** Drop a page from the cache. There must be exactly one reference to the
  46404. ** page. This function deletes that reference, so after it returns the
  46405. ** page pointed to by p is invalid.
  46406. */
  46407. SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){
  46408. assert( p->nRef==1 );
  46409. assert( sqlite3PcachePageSanity(p) );
  46410. if( p->flags&PGHDR_DIRTY ){
  46411. pcacheManageDirtyList(p, PCACHE_DIRTYLIST_REMOVE);
  46412. }
  46413. p->pCache->nRefSum--;
  46414. sqlite3GlobalConfig.pcache2.xUnpin(p->pCache->pCache, p->pPage, 1);
  46415. }
  46416. /*
  46417. ** Make sure the page is marked as dirty. If it isn't dirty already,
  46418. ** make it so.
  46419. */
  46420. SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){
  46421. assert( p->nRef>0 );
  46422. assert( sqlite3PcachePageSanity(p) );
  46423. if( p->flags & (PGHDR_CLEAN|PGHDR_DONT_WRITE) ){ /*OPTIMIZATION-IF-FALSE*/
  46424. p->flags &= ~PGHDR_DONT_WRITE;
  46425. if( p->flags & PGHDR_CLEAN ){
  46426. p->flags ^= (PGHDR_DIRTY|PGHDR_CLEAN);
  46427. pcacheTrace(("%p.DIRTY %d\n",p->pCache,p->pgno));
  46428. assert( (p->flags & (PGHDR_DIRTY|PGHDR_CLEAN))==PGHDR_DIRTY );
  46429. pcacheManageDirtyList(p, PCACHE_DIRTYLIST_ADD);
  46430. }
  46431. assert( sqlite3PcachePageSanity(p) );
  46432. }
  46433. }
  46434. /*
  46435. ** Make sure the page is marked as clean. If it isn't clean already,
  46436. ** make it so.
  46437. */
  46438. SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){
  46439. assert( sqlite3PcachePageSanity(p) );
  46440. assert( (p->flags & PGHDR_DIRTY)!=0 );
  46441. assert( (p->flags & PGHDR_CLEAN)==0 );
  46442. pcacheManageDirtyList(p, PCACHE_DIRTYLIST_REMOVE);
  46443. p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC|PGHDR_WRITEABLE);
  46444. p->flags |= PGHDR_CLEAN;
  46445. pcacheTrace(("%p.CLEAN %d\n",p->pCache,p->pgno));
  46446. assert( sqlite3PcachePageSanity(p) );
  46447. if( p->nRef==0 ){
  46448. pcacheUnpin(p);
  46449. }
  46450. }
  46451. /*
  46452. ** Make every page in the cache clean.
  46453. */
  46454. SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){
  46455. PgHdr *p;
  46456. pcacheTrace(("%p.CLEAN-ALL\n",pCache));
  46457. while( (p = pCache->pDirty)!=0 ){
  46458. sqlite3PcacheMakeClean(p);
  46459. }
  46460. }
  46461. /*
  46462. ** Clear the PGHDR_NEED_SYNC and PGHDR_WRITEABLE flag from all dirty pages.
  46463. */
  46464. SQLITE_PRIVATE void sqlite3PcacheClearWritable(PCache *pCache){
  46465. PgHdr *p;
  46466. pcacheTrace(("%p.CLEAR-WRITEABLE\n",pCache));
  46467. for(p=pCache->pDirty; p; p=p->pDirtyNext){
  46468. p->flags &= ~(PGHDR_NEED_SYNC|PGHDR_WRITEABLE);
  46469. }
  46470. pCache->pSynced = pCache->pDirtyTail;
  46471. }
  46472. /*
  46473. ** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
  46474. */
  46475. SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){
  46476. PgHdr *p;
  46477. for(p=pCache->pDirty; p; p=p->pDirtyNext){
  46478. p->flags &= ~PGHDR_NEED_SYNC;
  46479. }
  46480. pCache->pSynced = pCache->pDirtyTail;
  46481. }
  46482. /*
  46483. ** Change the page number of page p to newPgno.
  46484. */
  46485. SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
  46486. PCache *pCache = p->pCache;
  46487. assert( p->nRef>0 );
  46488. assert( newPgno>0 );
  46489. assert( sqlite3PcachePageSanity(p) );
  46490. pcacheTrace(("%p.MOVE %d -> %d\n",pCache,p->pgno,newPgno));
  46491. sqlite3GlobalConfig.pcache2.xRekey(pCache->pCache, p->pPage, p->pgno,newPgno);
  46492. p->pgno = newPgno;
  46493. if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
  46494. pcacheManageDirtyList(p, PCACHE_DIRTYLIST_FRONT);
  46495. }
  46496. }
  46497. /*
  46498. ** Drop every cache entry whose page number is greater than "pgno". The
  46499. ** caller must ensure that there are no outstanding references to any pages
  46500. ** other than page 1 with a page number greater than pgno.
  46501. **
  46502. ** If there is a reference to page 1 and the pgno parameter passed to this
  46503. ** function is 0, then the data area associated with page 1 is zeroed, but
  46504. ** the page object is not dropped.
  46505. */
  46506. SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){
  46507. if( pCache->pCache ){
  46508. PgHdr *p;
  46509. PgHdr *pNext;
  46510. pcacheTrace(("%p.TRUNCATE %d\n",pCache,pgno));
  46511. for(p=pCache->pDirty; p; p=pNext){
  46512. pNext = p->pDirtyNext;
  46513. /* This routine never gets call with a positive pgno except right
  46514. ** after sqlite3PcacheCleanAll(). So if there are dirty pages,
  46515. ** it must be that pgno==0.
  46516. */
  46517. assert( p->pgno>0 );
  46518. if( p->pgno>pgno ){
  46519. assert( p->flags&PGHDR_DIRTY );
  46520. sqlite3PcacheMakeClean(p);
  46521. }
  46522. }
  46523. if( pgno==0 && pCache->nRefSum ){
  46524. sqlite3_pcache_page *pPage1;
  46525. pPage1 = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache,1,0);
  46526. if( ALWAYS(pPage1) ){ /* Page 1 is always available in cache, because
  46527. ** pCache->nRefSum>0 */
  46528. memset(pPage1->pBuf, 0, pCache->szPage);
  46529. pgno = 1;
  46530. }
  46531. }
  46532. sqlite3GlobalConfig.pcache2.xTruncate(pCache->pCache, pgno+1);
  46533. }
  46534. }
  46535. /*
  46536. ** Close a cache.
  46537. */
  46538. SQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){
  46539. assert( pCache->pCache!=0 );
  46540. pcacheTrace(("%p.CLOSE\n",pCache));
  46541. sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
  46542. }
  46543. /*
  46544. ** Discard the contents of the cache.
  46545. */
  46546. SQLITE_PRIVATE void sqlite3PcacheClear(PCache *pCache){
  46547. sqlite3PcacheTruncate(pCache, 0);
  46548. }
  46549. /*
  46550. ** Merge two lists of pages connected by pDirty and in pgno order.
  46551. ** Do not bother fixing the pDirtyPrev pointers.
  46552. */
  46553. static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){
  46554. PgHdr result, *pTail;
  46555. pTail = &result;
  46556. assert( pA!=0 && pB!=0 );
  46557. for(;;){
  46558. if( pA->pgno<pB->pgno ){
  46559. pTail->pDirty = pA;
  46560. pTail = pA;
  46561. pA = pA->pDirty;
  46562. if( pA==0 ){
  46563. pTail->pDirty = pB;
  46564. break;
  46565. }
  46566. }else{
  46567. pTail->pDirty = pB;
  46568. pTail = pB;
  46569. pB = pB->pDirty;
  46570. if( pB==0 ){
  46571. pTail->pDirty = pA;
  46572. break;
  46573. }
  46574. }
  46575. }
  46576. return result.pDirty;
  46577. }
  46578. /*
  46579. ** Sort the list of pages in accending order by pgno. Pages are
  46580. ** connected by pDirty pointers. The pDirtyPrev pointers are
  46581. ** corrupted by this sort.
  46582. **
  46583. ** Since there cannot be more than 2^31 distinct pages in a database,
  46584. ** there cannot be more than 31 buckets required by the merge sorter.
  46585. ** One extra bucket is added to catch overflow in case something
  46586. ** ever changes to make the previous sentence incorrect.
  46587. */
  46588. #define N_SORT_BUCKET 32
  46589. static PgHdr *pcacheSortDirtyList(PgHdr *pIn){
  46590. PgHdr *a[N_SORT_BUCKET], *p;
  46591. int i;
  46592. memset(a, 0, sizeof(a));
  46593. while( pIn ){
  46594. p = pIn;
  46595. pIn = p->pDirty;
  46596. p->pDirty = 0;
  46597. for(i=0; ALWAYS(i<N_SORT_BUCKET-1); i++){
  46598. if( a[i]==0 ){
  46599. a[i] = p;
  46600. break;
  46601. }else{
  46602. p = pcacheMergeDirtyList(a[i], p);
  46603. a[i] = 0;
  46604. }
  46605. }
  46606. if( NEVER(i==N_SORT_BUCKET-1) ){
  46607. /* To get here, there need to be 2^(N_SORT_BUCKET) elements in
  46608. ** the input list. But that is impossible.
  46609. */
  46610. a[i] = pcacheMergeDirtyList(a[i], p);
  46611. }
  46612. }
  46613. p = a[0];
  46614. for(i=1; i<N_SORT_BUCKET; i++){
  46615. if( a[i]==0 ) continue;
  46616. p = p ? pcacheMergeDirtyList(p, a[i]) : a[i];
  46617. }
  46618. return p;
  46619. }
  46620. /*
  46621. ** Return a list of all dirty pages in the cache, sorted by page number.
  46622. */
  46623. SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache *pCache){
  46624. PgHdr *p;
  46625. for(p=pCache->pDirty; p; p=p->pDirtyNext){
  46626. p->pDirty = p->pDirtyNext;
  46627. }
  46628. return pcacheSortDirtyList(pCache->pDirty);
  46629. }
  46630. /*
  46631. ** Return the total number of references to all pages held by the cache.
  46632. **
  46633. ** This is not the total number of pages referenced, but the sum of the
  46634. ** reference count for all pages.
  46635. */
  46636. SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache *pCache){
  46637. return pCache->nRefSum;
  46638. }
  46639. /*
  46640. ** Return the number of references to the page supplied as an argument.
  46641. */
  46642. SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr *p){
  46643. return p->nRef;
  46644. }
  46645. /*
  46646. ** Return the total number of pages in the cache.
  46647. */
  46648. SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){
  46649. assert( pCache->pCache!=0 );
  46650. return sqlite3GlobalConfig.pcache2.xPagecount(pCache->pCache);
  46651. }
  46652. #ifdef SQLITE_TEST
  46653. /*
  46654. ** Get the suggested cache-size value.
  46655. */
  46656. SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){
  46657. return numberOfCachePages(pCache);
  46658. }
  46659. #endif
  46660. /*
  46661. ** Set the suggested cache-size value.
  46662. */
  46663. SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){
  46664. assert( pCache->pCache!=0 );
  46665. pCache->szCache = mxPage;
  46666. sqlite3GlobalConfig.pcache2.xCachesize(pCache->pCache,
  46667. numberOfCachePages(pCache));
  46668. }
  46669. /*
  46670. ** Set the suggested cache-spill value. Make no changes if if the
  46671. ** argument is zero. Return the effective cache-spill size, which will
  46672. ** be the larger of the szSpill and szCache.
  46673. */
  46674. SQLITE_PRIVATE int sqlite3PcacheSetSpillsize(PCache *p, int mxPage){
  46675. int res;
  46676. assert( p->pCache!=0 );
  46677. if( mxPage ){
  46678. if( mxPage<0 ){
  46679. mxPage = (int)((-1024*(i64)mxPage)/(p->szPage+p->szExtra));
  46680. }
  46681. p->szSpill = mxPage;
  46682. }
  46683. res = numberOfCachePages(p);
  46684. if( res<p->szSpill ) res = p->szSpill;
  46685. return res;
  46686. }
  46687. /*
  46688. ** Free up as much memory as possible from the page cache.
  46689. */
  46690. SQLITE_PRIVATE void sqlite3PcacheShrink(PCache *pCache){
  46691. assert( pCache->pCache!=0 );
  46692. sqlite3GlobalConfig.pcache2.xShrink(pCache->pCache);
  46693. }
  46694. /*
  46695. ** Return the size of the header added by this middleware layer
  46696. ** in the page-cache hierarchy.
  46697. */
  46698. SQLITE_PRIVATE int sqlite3HeaderSizePcache(void){ return ROUND8(sizeof(PgHdr)); }
  46699. /*
  46700. ** Return the number of dirty pages currently in the cache, as a percentage
  46701. ** of the configured cache size.
  46702. */
  46703. SQLITE_PRIVATE int sqlite3PCachePercentDirty(PCache *pCache){
  46704. PgHdr *pDirty;
  46705. int nDirty = 0;
  46706. int nCache = numberOfCachePages(pCache);
  46707. for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext) nDirty++;
  46708. return nCache ? (int)(((i64)nDirty * 100) / nCache) : 0;
  46709. }
  46710. #ifdef SQLITE_DIRECT_OVERFLOW_READ
  46711. /*
  46712. ** Return true if there are one or more dirty pages in the cache. Else false.
  46713. */
  46714. SQLITE_PRIVATE int sqlite3PCacheIsDirty(PCache *pCache){
  46715. return (pCache->pDirty!=0);
  46716. }
  46717. #endif
  46718. #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
  46719. /*
  46720. ** For all dirty pages currently in the cache, invoke the specified
  46721. ** callback. This is only used if the SQLITE_CHECK_PAGES macro is
  46722. ** defined.
  46723. */
  46724. SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){
  46725. PgHdr *pDirty;
  46726. for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){
  46727. xIter(pDirty);
  46728. }
  46729. }
  46730. #endif
  46731. /************** End of pcache.c **********************************************/
  46732. /************** Begin file pcache1.c *****************************************/
  46733. /*
  46734. ** 2008 November 05
  46735. **
  46736. ** The author disclaims copyright to this source code. In place of
  46737. ** a legal notice, here is a blessing:
  46738. **
  46739. ** May you do good and not evil.
  46740. ** May you find forgiveness for yourself and forgive others.
  46741. ** May you share freely, never taking more than you give.
  46742. **
  46743. *************************************************************************
  46744. **
  46745. ** This file implements the default page cache implementation (the
  46746. ** sqlite3_pcache interface). It also contains part of the implementation
  46747. ** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.
  46748. ** If the default page cache implementation is overridden, then neither of
  46749. ** these two features are available.
  46750. **
  46751. ** A Page cache line looks like this:
  46752. **
  46753. ** -------------------------------------------------------------
  46754. ** | database page content | PgHdr1 | MemPage | PgHdr |
  46755. ** -------------------------------------------------------------
  46756. **
  46757. ** The database page content is up front (so that buffer overreads tend to
  46758. ** flow harmlessly into the PgHdr1, MemPage, and PgHdr extensions). MemPage
  46759. ** is the extension added by the btree.c module containing information such
  46760. ** as the database page number and how that database page is used. PgHdr
  46761. ** is added by the pcache.c layer and contains information used to keep track
  46762. ** of which pages are "dirty". PgHdr1 is an extension added by this
  46763. ** module (pcache1.c). The PgHdr1 header is a subclass of sqlite3_pcache_page.
  46764. ** PgHdr1 contains information needed to look up a page by its page number.
  46765. ** The superclass sqlite3_pcache_page.pBuf points to the start of the
  46766. ** database page content and sqlite3_pcache_page.pExtra points to PgHdr.
  46767. **
  46768. ** The size of the extension (MemPage+PgHdr+PgHdr1) can be determined at
  46769. ** runtime using sqlite3_config(SQLITE_CONFIG_PCACHE_HDRSZ, &size). The
  46770. ** sizes of the extensions sum to 272 bytes on x64 for 3.8.10, but this
  46771. ** size can vary according to architecture, compile-time options, and
  46772. ** SQLite library version number.
  46773. **
  46774. ** If SQLITE_PCACHE_SEPARATE_HEADER is defined, then the extension is obtained
  46775. ** using a separate memory allocation from the database page content. This
  46776. ** seeks to overcome the "clownshoe" problem (also called "internal
  46777. ** fragmentation" in academic literature) of allocating a few bytes more
  46778. ** than a power of two with the memory allocator rounding up to the next
  46779. ** power of two, and leaving the rounded-up space unused.
  46780. **
  46781. ** This module tracks pointers to PgHdr1 objects. Only pcache.c communicates
  46782. ** with this module. Information is passed back and forth as PgHdr1 pointers.
  46783. **
  46784. ** The pcache.c and pager.c modules deal pointers to PgHdr objects.
  46785. ** The btree.c module deals with pointers to MemPage objects.
  46786. **
  46787. ** SOURCE OF PAGE CACHE MEMORY:
  46788. **
  46789. ** Memory for a page might come from any of three sources:
  46790. **
  46791. ** (1) The general-purpose memory allocator - sqlite3Malloc()
  46792. ** (2) Global page-cache memory provided using sqlite3_config() with
  46793. ** SQLITE_CONFIG_PAGECACHE.
  46794. ** (3) PCache-local bulk allocation.
  46795. **
  46796. ** The third case is a chunk of heap memory (defaulting to 100 pages worth)
  46797. ** that is allocated when the page cache is created. The size of the local
  46798. ** bulk allocation can be adjusted using
  46799. **
  46800. ** sqlite3_config(SQLITE_CONFIG_PAGECACHE, (void*)0, 0, N).
  46801. **
  46802. ** If N is positive, then N pages worth of memory are allocated using a single
  46803. ** sqlite3Malloc() call and that memory is used for the first N pages allocated.
  46804. ** Or if N is negative, then -1024*N bytes of memory are allocated and used
  46805. ** for as many pages as can be accomodated.
  46806. **
  46807. ** Only one of (2) or (3) can be used. Once the memory available to (2) or
  46808. ** (3) is exhausted, subsequent allocations fail over to the general-purpose
  46809. ** memory allocator (1).
  46810. **
  46811. ** Earlier versions of SQLite used only methods (1) and (2). But experiments
  46812. ** show that method (3) with N==100 provides about a 5% performance boost for
  46813. ** common workloads.
  46814. */
  46815. /* #include "sqliteInt.h" */
  46816. typedef struct PCache1 PCache1;
  46817. typedef struct PgHdr1 PgHdr1;
  46818. typedef struct PgFreeslot PgFreeslot;
  46819. typedef struct PGroup PGroup;
  46820. /*
  46821. ** Each cache entry is represented by an instance of the following
  46822. ** structure. Unless SQLITE_PCACHE_SEPARATE_HEADER is defined, a buffer of
  46823. ** PgHdr1.pCache->szPage bytes is allocated directly before this structure
  46824. ** in memory.
  46825. **
  46826. ** Note: Variables isBulkLocal and isAnchor were once type "u8". That works,
  46827. ** but causes a 2-byte gap in the structure for most architectures (since
  46828. ** pointers must be either 4 or 8-byte aligned). As this structure is located
  46829. ** in memory directly after the associated page data, if the database is
  46830. ** corrupt, code at the b-tree layer may overread the page buffer and
  46831. ** read part of this structure before the corruption is detected. This
  46832. ** can cause a valgrind error if the unitialized gap is accessed. Using u16
  46833. ** ensures there is no such gap, and therefore no bytes of unitialized memory
  46834. ** in the structure.
  46835. */
  46836. struct PgHdr1 {
  46837. sqlite3_pcache_page page; /* Base class. Must be first. pBuf & pExtra */
  46838. unsigned int iKey; /* Key value (page number) */
  46839. u16 isBulkLocal; /* This page from bulk local storage */
  46840. u16 isAnchor; /* This is the PGroup.lru element */
  46841. PgHdr1 *pNext; /* Next in hash table chain */
  46842. PCache1 *pCache; /* Cache that currently owns this page */
  46843. PgHdr1 *pLruNext; /* Next in LRU list of unpinned pages */
  46844. PgHdr1 *pLruPrev; /* Previous in LRU list of unpinned pages */
  46845. /* NB: pLruPrev is only valid if pLruNext!=0 */
  46846. };
  46847. /*
  46848. ** A page is pinned if it is not on the LRU list. To be "pinned" means
  46849. ** that the page is in active use and must not be deallocated.
  46850. */
  46851. #define PAGE_IS_PINNED(p) ((p)->pLruNext==0)
  46852. #define PAGE_IS_UNPINNED(p) ((p)->pLruNext!=0)
  46853. /* Each page cache (or PCache) belongs to a PGroup. A PGroup is a set
  46854. ** of one or more PCaches that are able to recycle each other's unpinned
  46855. ** pages when they are under memory pressure. A PGroup is an instance of
  46856. ** the following object.
  46857. **
  46858. ** This page cache implementation works in one of two modes:
  46859. **
  46860. ** (1) Every PCache is the sole member of its own PGroup. There is
  46861. ** one PGroup per PCache.
  46862. **
  46863. ** (2) There is a single global PGroup that all PCaches are a member
  46864. ** of.
  46865. **
  46866. ** Mode 1 uses more memory (since PCache instances are not able to rob
  46867. ** unused pages from other PCaches) but it also operates without a mutex,
  46868. ** and is therefore often faster. Mode 2 requires a mutex in order to be
  46869. ** threadsafe, but recycles pages more efficiently.
  46870. **
  46871. ** For mode (1), PGroup.mutex is NULL. For mode (2) there is only a single
  46872. ** PGroup which is the pcache1.grp global variable and its mutex is
  46873. ** SQLITE_MUTEX_STATIC_LRU.
  46874. */
  46875. struct PGroup {
  46876. sqlite3_mutex *mutex; /* MUTEX_STATIC_LRU or NULL */
  46877. unsigned int nMaxPage; /* Sum of nMax for purgeable caches */
  46878. unsigned int nMinPage; /* Sum of nMin for purgeable caches */
  46879. unsigned int mxPinned; /* nMaxpage + 10 - nMinPage */
  46880. unsigned int nPurgeable; /* Number of purgeable pages allocated */
  46881. PgHdr1 lru; /* The beginning and end of the LRU list */
  46882. };
  46883. /* Each page cache is an instance of the following object. Every
  46884. ** open database file (including each in-memory database and each
  46885. ** temporary or transient database) has a single page cache which
  46886. ** is an instance of this object.
  46887. **
  46888. ** Pointers to structures of this type are cast and returned as
  46889. ** opaque sqlite3_pcache* handles.
  46890. */
  46891. struct PCache1 {
  46892. /* Cache configuration parameters. Page size (szPage) and the purgeable
  46893. ** flag (bPurgeable) and the pnPurgeable pointer are all set when the
  46894. ** cache is created and are never changed thereafter. nMax may be
  46895. ** modified at any time by a call to the pcache1Cachesize() method.
  46896. ** The PGroup mutex must be held when accessing nMax.
  46897. */
  46898. PGroup *pGroup; /* PGroup this cache belongs to */
  46899. unsigned int *pnPurgeable; /* Pointer to pGroup->nPurgeable */
  46900. int szPage; /* Size of database content section */
  46901. int szExtra; /* sizeof(MemPage)+sizeof(PgHdr) */
  46902. int szAlloc; /* Total size of one pcache line */
  46903. int bPurgeable; /* True if cache is purgeable */
  46904. unsigned int nMin; /* Minimum number of pages reserved */
  46905. unsigned int nMax; /* Configured "cache_size" value */
  46906. unsigned int n90pct; /* nMax*9/10 */
  46907. unsigned int iMaxKey; /* Largest key seen since xTruncate() */
  46908. unsigned int nPurgeableDummy; /* pnPurgeable points here when not used*/
  46909. /* Hash table of all pages. The following variables may only be accessed
  46910. ** when the accessor is holding the PGroup mutex.
  46911. */
  46912. unsigned int nRecyclable; /* Number of pages in the LRU list */
  46913. unsigned int nPage; /* Total number of pages in apHash */
  46914. unsigned int nHash; /* Number of slots in apHash[] */
  46915. PgHdr1 **apHash; /* Hash table for fast lookup by key */
  46916. PgHdr1 *pFree; /* List of unused pcache-local pages */
  46917. void *pBulk; /* Bulk memory used by pcache-local */
  46918. };
  46919. /*
  46920. ** Free slots in the allocator used to divide up the global page cache
  46921. ** buffer provided using the SQLITE_CONFIG_PAGECACHE mechanism.
  46922. */
  46923. struct PgFreeslot {
  46924. PgFreeslot *pNext; /* Next free slot */
  46925. };
  46926. /*
  46927. ** Global data used by this cache.
  46928. */
  46929. static SQLITE_WSD struct PCacheGlobal {
  46930. PGroup grp; /* The global PGroup for mode (2) */
  46931. /* Variables related to SQLITE_CONFIG_PAGECACHE settings. The
  46932. ** szSlot, nSlot, pStart, pEnd, nReserve, and isInit values are all
  46933. ** fixed at sqlite3_initialize() time and do not require mutex protection.
  46934. ** The nFreeSlot and pFree values do require mutex protection.
  46935. */
  46936. int isInit; /* True if initialized */
  46937. int separateCache; /* Use a new PGroup for each PCache */
  46938. int nInitPage; /* Initial bulk allocation size */
  46939. int szSlot; /* Size of each free slot */
  46940. int nSlot; /* The number of pcache slots */
  46941. int nReserve; /* Try to keep nFreeSlot above this */
  46942. void *pStart, *pEnd; /* Bounds of global page cache memory */
  46943. /* Above requires no mutex. Use mutex below for variable that follow. */
  46944. sqlite3_mutex *mutex; /* Mutex for accessing the following: */
  46945. PgFreeslot *pFree; /* Free page blocks */
  46946. int nFreeSlot; /* Number of unused pcache slots */
  46947. /* The following value requires a mutex to change. We skip the mutex on
  46948. ** reading because (1) most platforms read a 32-bit integer atomically and
  46949. ** (2) even if an incorrect value is read, no great harm is done since this
  46950. ** is really just an optimization. */
  46951. int bUnderPressure; /* True if low on PAGECACHE memory */
  46952. } pcache1_g;
  46953. /*
  46954. ** All code in this file should access the global structure above via the
  46955. ** alias "pcache1". This ensures that the WSD emulation is used when
  46956. ** compiling for systems that do not support real WSD.
  46957. */
  46958. #define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))
  46959. /*
  46960. ** Macros to enter and leave the PCache LRU mutex.
  46961. */
  46962. #if !defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) || SQLITE_THREADSAFE==0
  46963. # define pcache1EnterMutex(X) assert((X)->mutex==0)
  46964. # define pcache1LeaveMutex(X) assert((X)->mutex==0)
  46965. # define PCACHE1_MIGHT_USE_GROUP_MUTEX 0
  46966. #else
  46967. # define pcache1EnterMutex(X) sqlite3_mutex_enter((X)->mutex)
  46968. # define pcache1LeaveMutex(X) sqlite3_mutex_leave((X)->mutex)
  46969. # define PCACHE1_MIGHT_USE_GROUP_MUTEX 1
  46970. #endif
  46971. /******************************************************************************/
  46972. /******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/
  46973. /*
  46974. ** This function is called during initialization if a static buffer is
  46975. ** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE
  46976. ** verb to sqlite3_config(). Parameter pBuf points to an allocation large
  46977. ** enough to contain 'n' buffers of 'sz' bytes each.
  46978. **
  46979. ** This routine is called from sqlite3_initialize() and so it is guaranteed
  46980. ** to be serialized already. There is no need for further mutexing.
  46981. */
  46982. SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
  46983. if( pcache1.isInit ){
  46984. PgFreeslot *p;
  46985. if( pBuf==0 ) sz = n = 0;
  46986. if( n==0 ) sz = 0;
  46987. sz = ROUNDDOWN8(sz);
  46988. pcache1.szSlot = sz;
  46989. pcache1.nSlot = pcache1.nFreeSlot = n;
  46990. pcache1.nReserve = n>90 ? 10 : (n/10 + 1);
  46991. pcache1.pStart = pBuf;
  46992. pcache1.pFree = 0;
  46993. pcache1.bUnderPressure = 0;
  46994. while( n-- ){
  46995. p = (PgFreeslot*)pBuf;
  46996. p->pNext = pcache1.pFree;
  46997. pcache1.pFree = p;
  46998. pBuf = (void*)&((char*)pBuf)[sz];
  46999. }
  47000. pcache1.pEnd = pBuf;
  47001. }
  47002. }
  47003. /*
  47004. ** Try to initialize the pCache->pFree and pCache->pBulk fields. Return
  47005. ** true if pCache->pFree ends up containing one or more free pages.
  47006. */
  47007. static int pcache1InitBulk(PCache1 *pCache){
  47008. i64 szBulk;
  47009. char *zBulk;
  47010. if( pcache1.nInitPage==0 ) return 0;
  47011. /* Do not bother with a bulk allocation if the cache size very small */
  47012. if( pCache->nMax<3 ) return 0;
  47013. sqlite3BeginBenignMalloc();
  47014. if( pcache1.nInitPage>0 ){
  47015. szBulk = pCache->szAlloc * (i64)pcache1.nInitPage;
  47016. }else{
  47017. szBulk = -1024 * (i64)pcache1.nInitPage;
  47018. }
  47019. if( szBulk > pCache->szAlloc*(i64)pCache->nMax ){
  47020. szBulk = pCache->szAlloc*(i64)pCache->nMax;
  47021. }
  47022. zBulk = pCache->pBulk = sqlite3Malloc( szBulk );
  47023. sqlite3EndBenignMalloc();
  47024. if( zBulk ){
  47025. int nBulk = sqlite3MallocSize(zBulk)/pCache->szAlloc;
  47026. do{
  47027. PgHdr1 *pX = (PgHdr1*)&zBulk[pCache->szPage];
  47028. pX->page.pBuf = zBulk;
  47029. pX->page.pExtra = &pX[1];
  47030. pX->isBulkLocal = 1;
  47031. pX->isAnchor = 0;
  47032. pX->pNext = pCache->pFree;
  47033. pX->pLruPrev = 0; /* Initializing this saves a valgrind error */
  47034. pCache->pFree = pX;
  47035. zBulk += pCache->szAlloc;
  47036. }while( --nBulk );
  47037. }
  47038. return pCache->pFree!=0;
  47039. }
  47040. /*
  47041. ** Malloc function used within this file to allocate space from the buffer
  47042. ** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no
  47043. ** such buffer exists or there is no space left in it, this function falls
  47044. ** back to sqlite3Malloc().
  47045. **
  47046. ** Multiple threads can run this routine at the same time. Global variables
  47047. ** in pcache1 need to be protected via mutex.
  47048. */
  47049. static void *pcache1Alloc(int nByte){
  47050. void *p = 0;
  47051. assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
  47052. if( nByte<=pcache1.szSlot ){
  47053. sqlite3_mutex_enter(pcache1.mutex);
  47054. p = (PgHdr1 *)pcache1.pFree;
  47055. if( p ){
  47056. pcache1.pFree = pcache1.pFree->pNext;
  47057. pcache1.nFreeSlot--;
  47058. pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
  47059. assert( pcache1.nFreeSlot>=0 );
  47060. sqlite3StatusHighwater(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
  47061. sqlite3StatusUp(SQLITE_STATUS_PAGECACHE_USED, 1);
  47062. }
  47063. sqlite3_mutex_leave(pcache1.mutex);
  47064. }
  47065. if( p==0 ){
  47066. /* Memory is not available in the SQLITE_CONFIG_PAGECACHE pool. Get
  47067. ** it from sqlite3Malloc instead.
  47068. */
  47069. p = sqlite3Malloc(nByte);
  47070. #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
  47071. if( p ){
  47072. int sz = sqlite3MallocSize(p);
  47073. sqlite3_mutex_enter(pcache1.mutex);
  47074. sqlite3StatusHighwater(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
  47075. sqlite3StatusUp(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
  47076. sqlite3_mutex_leave(pcache1.mutex);
  47077. }
  47078. #endif
  47079. sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
  47080. }
  47081. return p;
  47082. }
  47083. /*
  47084. ** Free an allocated buffer obtained from pcache1Alloc().
  47085. */
  47086. static void pcache1Free(void *p){
  47087. if( p==0 ) return;
  47088. if( SQLITE_WITHIN(p, pcache1.pStart, pcache1.pEnd) ){
  47089. PgFreeslot *pSlot;
  47090. sqlite3_mutex_enter(pcache1.mutex);
  47091. sqlite3StatusDown(SQLITE_STATUS_PAGECACHE_USED, 1);
  47092. pSlot = (PgFreeslot*)p;
  47093. pSlot->pNext = pcache1.pFree;
  47094. pcache1.pFree = pSlot;
  47095. pcache1.nFreeSlot++;
  47096. pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
  47097. assert( pcache1.nFreeSlot<=pcache1.nSlot );
  47098. sqlite3_mutex_leave(pcache1.mutex);
  47099. }else{
  47100. assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
  47101. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  47102. #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
  47103. {
  47104. int nFreed = 0;
  47105. nFreed = sqlite3MallocSize(p);
  47106. sqlite3_mutex_enter(pcache1.mutex);
  47107. sqlite3StatusDown(SQLITE_STATUS_PAGECACHE_OVERFLOW, nFreed);
  47108. sqlite3_mutex_leave(pcache1.mutex);
  47109. }
  47110. #endif
  47111. sqlite3_free(p);
  47112. }
  47113. }
  47114. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  47115. /*
  47116. ** Return the size of a pcache allocation
  47117. */
  47118. static int pcache1MemSize(void *p){
  47119. if( p>=pcache1.pStart && p<pcache1.pEnd ){
  47120. return pcache1.szSlot;
  47121. }else{
  47122. int iSize;
  47123. assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
  47124. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  47125. iSize = sqlite3MallocSize(p);
  47126. sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
  47127. return iSize;
  47128. }
  47129. }
  47130. #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
  47131. /*
  47132. ** Allocate a new page object initially associated with cache pCache.
  47133. */
  47134. static PgHdr1 *pcache1AllocPage(PCache1 *pCache, int benignMalloc){
  47135. PgHdr1 *p = 0;
  47136. void *pPg;
  47137. assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
  47138. if( pCache->pFree || (pCache->nPage==0 && pcache1InitBulk(pCache)) ){
  47139. assert( pCache->pFree!=0 );
  47140. p = pCache->pFree;
  47141. pCache->pFree = p->pNext;
  47142. p->pNext = 0;
  47143. }else{
  47144. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  47145. /* The group mutex must be released before pcache1Alloc() is called. This
  47146. ** is because it might call sqlite3_release_memory(), which assumes that
  47147. ** this mutex is not held. */
  47148. assert( pcache1.separateCache==0 );
  47149. assert( pCache->pGroup==&pcache1.grp );
  47150. pcache1LeaveMutex(pCache->pGroup);
  47151. #endif
  47152. if( benignMalloc ){ sqlite3BeginBenignMalloc(); }
  47153. #ifdef SQLITE_PCACHE_SEPARATE_HEADER
  47154. pPg = pcache1Alloc(pCache->szPage);
  47155. p = sqlite3Malloc(sizeof(PgHdr1) + pCache->szExtra);
  47156. if( !pPg || !p ){
  47157. pcache1Free(pPg);
  47158. sqlite3_free(p);
  47159. pPg = 0;
  47160. }
  47161. #else
  47162. pPg = pcache1Alloc(pCache->szAlloc);
  47163. #endif
  47164. if( benignMalloc ){ sqlite3EndBenignMalloc(); }
  47165. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  47166. pcache1EnterMutex(pCache->pGroup);
  47167. #endif
  47168. if( pPg==0 ) return 0;
  47169. #ifndef SQLITE_PCACHE_SEPARATE_HEADER
  47170. p = (PgHdr1 *)&((u8 *)pPg)[pCache->szPage];
  47171. #endif
  47172. p->page.pBuf = pPg;
  47173. p->page.pExtra = &p[1];
  47174. p->isBulkLocal = 0;
  47175. p->isAnchor = 0;
  47176. }
  47177. (*pCache->pnPurgeable)++;
  47178. return p;
  47179. }
  47180. /*
  47181. ** Free a page object allocated by pcache1AllocPage().
  47182. */
  47183. static void pcache1FreePage(PgHdr1 *p){
  47184. PCache1 *pCache;
  47185. assert( p!=0 );
  47186. pCache = p->pCache;
  47187. assert( sqlite3_mutex_held(p->pCache->pGroup->mutex) );
  47188. if( p->isBulkLocal ){
  47189. p->pNext = pCache->pFree;
  47190. pCache->pFree = p;
  47191. }else{
  47192. pcache1Free(p->page.pBuf);
  47193. #ifdef SQLITE_PCACHE_SEPARATE_HEADER
  47194. sqlite3_free(p);
  47195. #endif
  47196. }
  47197. (*pCache->pnPurgeable)--;
  47198. }
  47199. /*
  47200. ** Malloc function used by SQLite to obtain space from the buffer configured
  47201. ** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer
  47202. ** exists, this function falls back to sqlite3Malloc().
  47203. */
  47204. SQLITE_PRIVATE void *sqlite3PageMalloc(int sz){
  47205. assert( sz<=65536+8 ); /* These allocations are never very large */
  47206. return pcache1Alloc(sz);
  47207. }
  47208. /*
  47209. ** Free an allocated buffer obtained from sqlite3PageMalloc().
  47210. */
  47211. SQLITE_PRIVATE void sqlite3PageFree(void *p){
  47212. pcache1Free(p);
  47213. }
  47214. /*
  47215. ** Return true if it desirable to avoid allocating a new page cache
  47216. ** entry.
  47217. **
  47218. ** If memory was allocated specifically to the page cache using
  47219. ** SQLITE_CONFIG_PAGECACHE but that memory has all been used, then
  47220. ** it is desirable to avoid allocating a new page cache entry because
  47221. ** presumably SQLITE_CONFIG_PAGECACHE was suppose to be sufficient
  47222. ** for all page cache needs and we should not need to spill the
  47223. ** allocation onto the heap.
  47224. **
  47225. ** Or, the heap is used for all page cache memory but the heap is
  47226. ** under memory pressure, then again it is desirable to avoid
  47227. ** allocating a new page cache entry in order to avoid stressing
  47228. ** the heap even further.
  47229. */
  47230. static int pcache1UnderMemoryPressure(PCache1 *pCache){
  47231. if( pcache1.nSlot && (pCache->szPage+pCache->szExtra)<=pcache1.szSlot ){
  47232. return pcache1.bUnderPressure;
  47233. }else{
  47234. return sqlite3HeapNearlyFull();
  47235. }
  47236. }
  47237. /******************************************************************************/
  47238. /******** General Implementation Functions ************************************/
  47239. /*
  47240. ** This function is used to resize the hash table used by the cache passed
  47241. ** as the first argument.
  47242. **
  47243. ** The PCache mutex must be held when this function is called.
  47244. */
  47245. static void pcache1ResizeHash(PCache1 *p){
  47246. PgHdr1 **apNew;
  47247. unsigned int nNew;
  47248. unsigned int i;
  47249. assert( sqlite3_mutex_held(p->pGroup->mutex) );
  47250. nNew = p->nHash*2;
  47251. if( nNew<256 ){
  47252. nNew = 256;
  47253. }
  47254. pcache1LeaveMutex(p->pGroup);
  47255. if( p->nHash ){ sqlite3BeginBenignMalloc(); }
  47256. apNew = (PgHdr1 **)sqlite3MallocZero(sizeof(PgHdr1 *)*nNew);
  47257. if( p->nHash ){ sqlite3EndBenignMalloc(); }
  47258. pcache1EnterMutex(p->pGroup);
  47259. if( apNew ){
  47260. for(i=0; i<p->nHash; i++){
  47261. PgHdr1 *pPage;
  47262. PgHdr1 *pNext = p->apHash[i];
  47263. while( (pPage = pNext)!=0 ){
  47264. unsigned int h = pPage->iKey % nNew;
  47265. pNext = pPage->pNext;
  47266. pPage->pNext = apNew[h];
  47267. apNew[h] = pPage;
  47268. }
  47269. }
  47270. sqlite3_free(p->apHash);
  47271. p->apHash = apNew;
  47272. p->nHash = nNew;
  47273. }
  47274. }
  47275. /*
  47276. ** This function is used internally to remove the page pPage from the
  47277. ** PGroup LRU list, if is part of it. If pPage is not part of the PGroup
  47278. ** LRU list, then this function is a no-op.
  47279. **
  47280. ** The PGroup mutex must be held when this function is called.
  47281. */
  47282. static PgHdr1 *pcache1PinPage(PgHdr1 *pPage){
  47283. assert( pPage!=0 );
  47284. assert( PAGE_IS_UNPINNED(pPage) );
  47285. assert( pPage->pLruNext );
  47286. assert( pPage->pLruPrev );
  47287. assert( sqlite3_mutex_held(pPage->pCache->pGroup->mutex) );
  47288. pPage->pLruPrev->pLruNext = pPage->pLruNext;
  47289. pPage->pLruNext->pLruPrev = pPage->pLruPrev;
  47290. pPage->pLruNext = 0;
  47291. /* pPage->pLruPrev = 0;
  47292. ** No need to clear pLruPrev as it is never accessed if pLruNext is 0 */
  47293. assert( pPage->isAnchor==0 );
  47294. assert( pPage->pCache->pGroup->lru.isAnchor==1 );
  47295. pPage->pCache->nRecyclable--;
  47296. return pPage;
  47297. }
  47298. /*
  47299. ** Remove the page supplied as an argument from the hash table
  47300. ** (PCache1.apHash structure) that it is currently stored in.
  47301. ** Also free the page if freePage is true.
  47302. **
  47303. ** The PGroup mutex must be held when this function is called.
  47304. */
  47305. static void pcache1RemoveFromHash(PgHdr1 *pPage, int freeFlag){
  47306. unsigned int h;
  47307. PCache1 *pCache = pPage->pCache;
  47308. PgHdr1 **pp;
  47309. assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
  47310. h = pPage->iKey % pCache->nHash;
  47311. for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
  47312. *pp = (*pp)->pNext;
  47313. pCache->nPage--;
  47314. if( freeFlag ) pcache1FreePage(pPage);
  47315. }
  47316. /*
  47317. ** If there are currently more than nMaxPage pages allocated, try
  47318. ** to recycle pages to reduce the number allocated to nMaxPage.
  47319. */
  47320. static void pcache1EnforceMaxPage(PCache1 *pCache){
  47321. PGroup *pGroup = pCache->pGroup;
  47322. PgHdr1 *p;
  47323. assert( sqlite3_mutex_held(pGroup->mutex) );
  47324. while( pGroup->nPurgeable>pGroup->nMaxPage
  47325. && (p=pGroup->lru.pLruPrev)->isAnchor==0
  47326. ){
  47327. assert( p->pCache->pGroup==pGroup );
  47328. assert( PAGE_IS_UNPINNED(p) );
  47329. pcache1PinPage(p);
  47330. pcache1RemoveFromHash(p, 1);
  47331. }
  47332. if( pCache->nPage==0 && pCache->pBulk ){
  47333. sqlite3_free(pCache->pBulk);
  47334. pCache->pBulk = pCache->pFree = 0;
  47335. }
  47336. }
  47337. /*
  47338. ** Discard all pages from cache pCache with a page number (key value)
  47339. ** greater than or equal to iLimit. Any pinned pages that meet this
  47340. ** criteria are unpinned before they are discarded.
  47341. **
  47342. ** The PCache mutex must be held when this function is called.
  47343. */
  47344. static void pcache1TruncateUnsafe(
  47345. PCache1 *pCache, /* The cache to truncate */
  47346. unsigned int iLimit /* Drop pages with this pgno or larger */
  47347. ){
  47348. TESTONLY( int nPage = 0; ) /* To assert pCache->nPage is correct */
  47349. unsigned int h, iStop;
  47350. assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
  47351. assert( pCache->iMaxKey >= iLimit );
  47352. assert( pCache->nHash > 0 );
  47353. if( pCache->iMaxKey - iLimit < pCache->nHash ){
  47354. /* If we are just shaving the last few pages off the end of the
  47355. ** cache, then there is no point in scanning the entire hash table.
  47356. ** Only scan those hash slots that might contain pages that need to
  47357. ** be removed. */
  47358. h = iLimit % pCache->nHash;
  47359. iStop = pCache->iMaxKey % pCache->nHash;
  47360. TESTONLY( nPage = -10; ) /* Disable the pCache->nPage validity check */
  47361. }else{
  47362. /* This is the general case where many pages are being removed.
  47363. ** It is necessary to scan the entire hash table */
  47364. h = pCache->nHash/2;
  47365. iStop = h - 1;
  47366. }
  47367. for(;;){
  47368. PgHdr1 **pp;
  47369. PgHdr1 *pPage;
  47370. assert( h<pCache->nHash );
  47371. pp = &pCache->apHash[h];
  47372. while( (pPage = *pp)!=0 ){
  47373. if( pPage->iKey>=iLimit ){
  47374. pCache->nPage--;
  47375. *pp = pPage->pNext;
  47376. if( PAGE_IS_UNPINNED(pPage) ) pcache1PinPage(pPage);
  47377. pcache1FreePage(pPage);
  47378. }else{
  47379. pp = &pPage->pNext;
  47380. TESTONLY( if( nPage>=0 ) nPage++; )
  47381. }
  47382. }
  47383. if( h==iStop ) break;
  47384. h = (h+1) % pCache->nHash;
  47385. }
  47386. assert( nPage<0 || pCache->nPage==(unsigned)nPage );
  47387. }
  47388. /******************************************************************************/
  47389. /******** sqlite3_pcache Methods **********************************************/
  47390. /*
  47391. ** Implementation of the sqlite3_pcache.xInit method.
  47392. */
  47393. static int pcache1Init(void *NotUsed){
  47394. UNUSED_PARAMETER(NotUsed);
  47395. assert( pcache1.isInit==0 );
  47396. memset(&pcache1, 0, sizeof(pcache1));
  47397. /*
  47398. ** The pcache1.separateCache variable is true if each PCache has its own
  47399. ** private PGroup (mode-1). pcache1.separateCache is false if the single
  47400. ** PGroup in pcache1.grp is used for all page caches (mode-2).
  47401. **
  47402. ** * Always use a unified cache (mode-2) if ENABLE_MEMORY_MANAGEMENT
  47403. **
  47404. ** * Use a unified cache in single-threaded applications that have
  47405. ** configured a start-time buffer for use as page-cache memory using
  47406. ** sqlite3_config(SQLITE_CONFIG_PAGECACHE, pBuf, sz, N) with non-NULL
  47407. ** pBuf argument.
  47408. **
  47409. ** * Otherwise use separate caches (mode-1)
  47410. */
  47411. #if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT)
  47412. pcache1.separateCache = 0;
  47413. #elif SQLITE_THREADSAFE
  47414. pcache1.separateCache = sqlite3GlobalConfig.pPage==0
  47415. || sqlite3GlobalConfig.bCoreMutex>0;
  47416. #else
  47417. pcache1.separateCache = sqlite3GlobalConfig.pPage==0;
  47418. #endif
  47419. #if SQLITE_THREADSAFE
  47420. if( sqlite3GlobalConfig.bCoreMutex ){
  47421. pcache1.grp.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_LRU);
  47422. pcache1.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PMEM);
  47423. }
  47424. #endif
  47425. if( pcache1.separateCache
  47426. && sqlite3GlobalConfig.nPage!=0
  47427. && sqlite3GlobalConfig.pPage==0
  47428. ){
  47429. pcache1.nInitPage = sqlite3GlobalConfig.nPage;
  47430. }else{
  47431. pcache1.nInitPage = 0;
  47432. }
  47433. pcache1.grp.mxPinned = 10;
  47434. pcache1.isInit = 1;
  47435. return SQLITE_OK;
  47436. }
  47437. /*
  47438. ** Implementation of the sqlite3_pcache.xShutdown method.
  47439. ** Note that the static mutex allocated in xInit does
  47440. ** not need to be freed.
  47441. */
  47442. static void pcache1Shutdown(void *NotUsed){
  47443. UNUSED_PARAMETER(NotUsed);
  47444. assert( pcache1.isInit!=0 );
  47445. memset(&pcache1, 0, sizeof(pcache1));
  47446. }
  47447. /* forward declaration */
  47448. static void pcache1Destroy(sqlite3_pcache *p);
  47449. /*
  47450. ** Implementation of the sqlite3_pcache.xCreate method.
  47451. **
  47452. ** Allocate a new cache.
  47453. */
  47454. static sqlite3_pcache *pcache1Create(int szPage, int szExtra, int bPurgeable){
  47455. PCache1 *pCache; /* The newly created page cache */
  47456. PGroup *pGroup; /* The group the new page cache will belong to */
  47457. int sz; /* Bytes of memory required to allocate the new cache */
  47458. assert( (szPage & (szPage-1))==0 && szPage>=512 && szPage<=65536 );
  47459. assert( szExtra < 300 );
  47460. sz = sizeof(PCache1) + sizeof(PGroup)*pcache1.separateCache;
  47461. pCache = (PCache1 *)sqlite3MallocZero(sz);
  47462. if( pCache ){
  47463. if( pcache1.separateCache ){
  47464. pGroup = (PGroup*)&pCache[1];
  47465. pGroup->mxPinned = 10;
  47466. }else{
  47467. pGroup = &pcache1.grp;
  47468. }
  47469. pcache1EnterMutex(pGroup);
  47470. if( pGroup->lru.isAnchor==0 ){
  47471. pGroup->lru.isAnchor = 1;
  47472. pGroup->lru.pLruPrev = pGroup->lru.pLruNext = &pGroup->lru;
  47473. }
  47474. pCache->pGroup = pGroup;
  47475. pCache->szPage = szPage;
  47476. pCache->szExtra = szExtra;
  47477. pCache->szAlloc = szPage + szExtra + ROUND8(sizeof(PgHdr1));
  47478. pCache->bPurgeable = (bPurgeable ? 1 : 0);
  47479. pcache1ResizeHash(pCache);
  47480. if( bPurgeable ){
  47481. pCache->nMin = 10;
  47482. pGroup->nMinPage += pCache->nMin;
  47483. pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
  47484. pCache->pnPurgeable = &pGroup->nPurgeable;
  47485. }else{
  47486. pCache->pnPurgeable = &pCache->nPurgeableDummy;
  47487. }
  47488. pcache1LeaveMutex(pGroup);
  47489. if( pCache->nHash==0 ){
  47490. pcache1Destroy((sqlite3_pcache*)pCache);
  47491. pCache = 0;
  47492. }
  47493. }
  47494. return (sqlite3_pcache *)pCache;
  47495. }
  47496. /*
  47497. ** Implementation of the sqlite3_pcache.xCachesize method.
  47498. **
  47499. ** Configure the cache_size limit for a cache.
  47500. */
  47501. static void pcache1Cachesize(sqlite3_pcache *p, int nMax){
  47502. PCache1 *pCache = (PCache1 *)p;
  47503. if( pCache->bPurgeable ){
  47504. PGroup *pGroup = pCache->pGroup;
  47505. pcache1EnterMutex(pGroup);
  47506. pGroup->nMaxPage += (nMax - pCache->nMax);
  47507. pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
  47508. pCache->nMax = nMax;
  47509. pCache->n90pct = pCache->nMax*9/10;
  47510. pcache1EnforceMaxPage(pCache);
  47511. pcache1LeaveMutex(pGroup);
  47512. }
  47513. }
  47514. /*
  47515. ** Implementation of the sqlite3_pcache.xShrink method.
  47516. **
  47517. ** Free up as much memory as possible.
  47518. */
  47519. static void pcache1Shrink(sqlite3_pcache *p){
  47520. PCache1 *pCache = (PCache1*)p;
  47521. if( pCache->bPurgeable ){
  47522. PGroup *pGroup = pCache->pGroup;
  47523. int savedMaxPage;
  47524. pcache1EnterMutex(pGroup);
  47525. savedMaxPage = pGroup->nMaxPage;
  47526. pGroup->nMaxPage = 0;
  47527. pcache1EnforceMaxPage(pCache);
  47528. pGroup->nMaxPage = savedMaxPage;
  47529. pcache1LeaveMutex(pGroup);
  47530. }
  47531. }
  47532. /*
  47533. ** Implementation of the sqlite3_pcache.xPagecount method.
  47534. */
  47535. static int pcache1Pagecount(sqlite3_pcache *p){
  47536. int n;
  47537. PCache1 *pCache = (PCache1*)p;
  47538. pcache1EnterMutex(pCache->pGroup);
  47539. n = pCache->nPage;
  47540. pcache1LeaveMutex(pCache->pGroup);
  47541. return n;
  47542. }
  47543. /*
  47544. ** Implement steps 3, 4, and 5 of the pcache1Fetch() algorithm described
  47545. ** in the header of the pcache1Fetch() procedure.
  47546. **
  47547. ** This steps are broken out into a separate procedure because they are
  47548. ** usually not needed, and by avoiding the stack initialization required
  47549. ** for these steps, the main pcache1Fetch() procedure can run faster.
  47550. */
  47551. static SQLITE_NOINLINE PgHdr1 *pcache1FetchStage2(
  47552. PCache1 *pCache,
  47553. unsigned int iKey,
  47554. int createFlag
  47555. ){
  47556. unsigned int nPinned;
  47557. PGroup *pGroup = pCache->pGroup;
  47558. PgHdr1 *pPage = 0;
  47559. /* Step 3: Abort if createFlag is 1 but the cache is nearly full */
  47560. assert( pCache->nPage >= pCache->nRecyclable );
  47561. nPinned = pCache->nPage - pCache->nRecyclable;
  47562. assert( pGroup->mxPinned == pGroup->nMaxPage + 10 - pGroup->nMinPage );
  47563. assert( pCache->n90pct == pCache->nMax*9/10 );
  47564. if( createFlag==1 && (
  47565. nPinned>=pGroup->mxPinned
  47566. || nPinned>=pCache->n90pct
  47567. || (pcache1UnderMemoryPressure(pCache) && pCache->nRecyclable<nPinned)
  47568. )){
  47569. return 0;
  47570. }
  47571. if( pCache->nPage>=pCache->nHash ) pcache1ResizeHash(pCache);
  47572. assert( pCache->nHash>0 && pCache->apHash );
  47573. /* Step 4. Try to recycle a page. */
  47574. if( pCache->bPurgeable
  47575. && !pGroup->lru.pLruPrev->isAnchor
  47576. && ((pCache->nPage+1>=pCache->nMax) || pcache1UnderMemoryPressure(pCache))
  47577. ){
  47578. PCache1 *pOther;
  47579. pPage = pGroup->lru.pLruPrev;
  47580. assert( PAGE_IS_UNPINNED(pPage) );
  47581. pcache1RemoveFromHash(pPage, 0);
  47582. pcache1PinPage(pPage);
  47583. pOther = pPage->pCache;
  47584. if( pOther->szAlloc != pCache->szAlloc ){
  47585. pcache1FreePage(pPage);
  47586. pPage = 0;
  47587. }else{
  47588. pGroup->nPurgeable -= (pOther->bPurgeable - pCache->bPurgeable);
  47589. }
  47590. }
  47591. /* Step 5. If a usable page buffer has still not been found,
  47592. ** attempt to allocate a new one.
  47593. */
  47594. if( !pPage ){
  47595. pPage = pcache1AllocPage(pCache, createFlag==1);
  47596. }
  47597. if( pPage ){
  47598. unsigned int h = iKey % pCache->nHash;
  47599. pCache->nPage++;
  47600. pPage->iKey = iKey;
  47601. pPage->pNext = pCache->apHash[h];
  47602. pPage->pCache = pCache;
  47603. pPage->pLruNext = 0;
  47604. /* pPage->pLruPrev = 0;
  47605. ** No need to clear pLruPrev since it is not accessed when pLruNext==0 */
  47606. *(void **)pPage->page.pExtra = 0;
  47607. pCache->apHash[h] = pPage;
  47608. if( iKey>pCache->iMaxKey ){
  47609. pCache->iMaxKey = iKey;
  47610. }
  47611. }
  47612. return pPage;
  47613. }
  47614. /*
  47615. ** Implementation of the sqlite3_pcache.xFetch method.
  47616. **
  47617. ** Fetch a page by key value.
  47618. **
  47619. ** Whether or not a new page may be allocated by this function depends on
  47620. ** the value of the createFlag argument. 0 means do not allocate a new
  47621. ** page. 1 means allocate a new page if space is easily available. 2
  47622. ** means to try really hard to allocate a new page.
  47623. **
  47624. ** For a non-purgeable cache (a cache used as the storage for an in-memory
  47625. ** database) there is really no difference between createFlag 1 and 2. So
  47626. ** the calling function (pcache.c) will never have a createFlag of 1 on
  47627. ** a non-purgeable cache.
  47628. **
  47629. ** There are three different approaches to obtaining space for a page,
  47630. ** depending on the value of parameter createFlag (which may be 0, 1 or 2).
  47631. **
  47632. ** 1. Regardless of the value of createFlag, the cache is searched for a
  47633. ** copy of the requested page. If one is found, it is returned.
  47634. **
  47635. ** 2. If createFlag==0 and the page is not already in the cache, NULL is
  47636. ** returned.
  47637. **
  47638. ** 3. If createFlag is 1, and the page is not already in the cache, then
  47639. ** return NULL (do not allocate a new page) if any of the following
  47640. ** conditions are true:
  47641. **
  47642. ** (a) the number of pages pinned by the cache is greater than
  47643. ** PCache1.nMax, or
  47644. **
  47645. ** (b) the number of pages pinned by the cache is greater than
  47646. ** the sum of nMax for all purgeable caches, less the sum of
  47647. ** nMin for all other purgeable caches, or
  47648. **
  47649. ** 4. If none of the first three conditions apply and the cache is marked
  47650. ** as purgeable, and if one of the following is true:
  47651. **
  47652. ** (a) The number of pages allocated for the cache is already
  47653. ** PCache1.nMax, or
  47654. **
  47655. ** (b) The number of pages allocated for all purgeable caches is
  47656. ** already equal to or greater than the sum of nMax for all
  47657. ** purgeable caches,
  47658. **
  47659. ** (c) The system is under memory pressure and wants to avoid
  47660. ** unnecessary pages cache entry allocations
  47661. **
  47662. ** then attempt to recycle a page from the LRU list. If it is the right
  47663. ** size, return the recycled buffer. Otherwise, free the buffer and
  47664. ** proceed to step 5.
  47665. **
  47666. ** 5. Otherwise, allocate and return a new page buffer.
  47667. **
  47668. ** There are two versions of this routine. pcache1FetchWithMutex() is
  47669. ** the general case. pcache1FetchNoMutex() is a faster implementation for
  47670. ** the common case where pGroup->mutex is NULL. The pcache1Fetch() wrapper
  47671. ** invokes the appropriate routine.
  47672. */
  47673. static PgHdr1 *pcache1FetchNoMutex(
  47674. sqlite3_pcache *p,
  47675. unsigned int iKey,
  47676. int createFlag
  47677. ){
  47678. PCache1 *pCache = (PCache1 *)p;
  47679. PgHdr1 *pPage = 0;
  47680. /* Step 1: Search the hash table for an existing entry. */
  47681. pPage = pCache->apHash[iKey % pCache->nHash];
  47682. while( pPage && pPage->iKey!=iKey ){ pPage = pPage->pNext; }
  47683. /* Step 2: If the page was found in the hash table, then return it.
  47684. ** If the page was not in the hash table and createFlag is 0, abort.
  47685. ** Otherwise (page not in hash and createFlag!=0) continue with
  47686. ** subsequent steps to try to create the page. */
  47687. if( pPage ){
  47688. if( PAGE_IS_UNPINNED(pPage) ){
  47689. return pcache1PinPage(pPage);
  47690. }else{
  47691. return pPage;
  47692. }
  47693. }else if( createFlag ){
  47694. /* Steps 3, 4, and 5 implemented by this subroutine */
  47695. return pcache1FetchStage2(pCache, iKey, createFlag);
  47696. }else{
  47697. return 0;
  47698. }
  47699. }
  47700. #if PCACHE1_MIGHT_USE_GROUP_MUTEX
  47701. static PgHdr1 *pcache1FetchWithMutex(
  47702. sqlite3_pcache *p,
  47703. unsigned int iKey,
  47704. int createFlag
  47705. ){
  47706. PCache1 *pCache = (PCache1 *)p;
  47707. PgHdr1 *pPage;
  47708. pcache1EnterMutex(pCache->pGroup);
  47709. pPage = pcache1FetchNoMutex(p, iKey, createFlag);
  47710. assert( pPage==0 || pCache->iMaxKey>=iKey );
  47711. pcache1LeaveMutex(pCache->pGroup);
  47712. return pPage;
  47713. }
  47714. #endif
  47715. static sqlite3_pcache_page *pcache1Fetch(
  47716. sqlite3_pcache *p,
  47717. unsigned int iKey,
  47718. int createFlag
  47719. ){
  47720. #if PCACHE1_MIGHT_USE_GROUP_MUTEX || defined(SQLITE_DEBUG)
  47721. PCache1 *pCache = (PCache1 *)p;
  47722. #endif
  47723. assert( offsetof(PgHdr1,page)==0 );
  47724. assert( pCache->bPurgeable || createFlag!=1 );
  47725. assert( pCache->bPurgeable || pCache->nMin==0 );
  47726. assert( pCache->bPurgeable==0 || pCache->nMin==10 );
  47727. assert( pCache->nMin==0 || pCache->bPurgeable );
  47728. assert( pCache->nHash>0 );
  47729. #if PCACHE1_MIGHT_USE_GROUP_MUTEX
  47730. if( pCache->pGroup->mutex ){
  47731. return (sqlite3_pcache_page*)pcache1FetchWithMutex(p, iKey, createFlag);
  47732. }else
  47733. #endif
  47734. {
  47735. return (sqlite3_pcache_page*)pcache1FetchNoMutex(p, iKey, createFlag);
  47736. }
  47737. }
  47738. /*
  47739. ** Implementation of the sqlite3_pcache.xUnpin method.
  47740. **
  47741. ** Mark a page as unpinned (eligible for asynchronous recycling).
  47742. */
  47743. static void pcache1Unpin(
  47744. sqlite3_pcache *p,
  47745. sqlite3_pcache_page *pPg,
  47746. int reuseUnlikely
  47747. ){
  47748. PCache1 *pCache = (PCache1 *)p;
  47749. PgHdr1 *pPage = (PgHdr1 *)pPg;
  47750. PGroup *pGroup = pCache->pGroup;
  47751. assert( pPage->pCache==pCache );
  47752. pcache1EnterMutex(pGroup);
  47753. /* It is an error to call this function if the page is already
  47754. ** part of the PGroup LRU list.
  47755. */
  47756. assert( pPage->pLruNext==0 );
  47757. assert( PAGE_IS_PINNED(pPage) );
  47758. if( reuseUnlikely || pGroup->nPurgeable>pGroup->nMaxPage ){
  47759. pcache1RemoveFromHash(pPage, 1);
  47760. }else{
  47761. /* Add the page to the PGroup LRU list. */
  47762. PgHdr1 **ppFirst = &pGroup->lru.pLruNext;
  47763. pPage->pLruPrev = &pGroup->lru;
  47764. (pPage->pLruNext = *ppFirst)->pLruPrev = pPage;
  47765. *ppFirst = pPage;
  47766. pCache->nRecyclable++;
  47767. }
  47768. pcache1LeaveMutex(pCache->pGroup);
  47769. }
  47770. /*
  47771. ** Implementation of the sqlite3_pcache.xRekey method.
  47772. */
  47773. static void pcache1Rekey(
  47774. sqlite3_pcache *p,
  47775. sqlite3_pcache_page *pPg,
  47776. unsigned int iOld,
  47777. unsigned int iNew
  47778. ){
  47779. PCache1 *pCache = (PCache1 *)p;
  47780. PgHdr1 *pPage = (PgHdr1 *)pPg;
  47781. PgHdr1 **pp;
  47782. unsigned int h;
  47783. assert( pPage->iKey==iOld );
  47784. assert( pPage->pCache==pCache );
  47785. pcache1EnterMutex(pCache->pGroup);
  47786. h = iOld%pCache->nHash;
  47787. pp = &pCache->apHash[h];
  47788. while( (*pp)!=pPage ){
  47789. pp = &(*pp)->pNext;
  47790. }
  47791. *pp = pPage->pNext;
  47792. h = iNew%pCache->nHash;
  47793. pPage->iKey = iNew;
  47794. pPage->pNext = pCache->apHash[h];
  47795. pCache->apHash[h] = pPage;
  47796. if( iNew>pCache->iMaxKey ){
  47797. pCache->iMaxKey = iNew;
  47798. }
  47799. pcache1LeaveMutex(pCache->pGroup);
  47800. }
  47801. /*
  47802. ** Implementation of the sqlite3_pcache.xTruncate method.
  47803. **
  47804. ** Discard all unpinned pages in the cache with a page number equal to
  47805. ** or greater than parameter iLimit. Any pinned pages with a page number
  47806. ** equal to or greater than iLimit are implicitly unpinned.
  47807. */
  47808. static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){
  47809. PCache1 *pCache = (PCache1 *)p;
  47810. pcache1EnterMutex(pCache->pGroup);
  47811. if( iLimit<=pCache->iMaxKey ){
  47812. pcache1TruncateUnsafe(pCache, iLimit);
  47813. pCache->iMaxKey = iLimit-1;
  47814. }
  47815. pcache1LeaveMutex(pCache->pGroup);
  47816. }
  47817. /*
  47818. ** Implementation of the sqlite3_pcache.xDestroy method.
  47819. **
  47820. ** Destroy a cache allocated using pcache1Create().
  47821. */
  47822. static void pcache1Destroy(sqlite3_pcache *p){
  47823. PCache1 *pCache = (PCache1 *)p;
  47824. PGroup *pGroup = pCache->pGroup;
  47825. assert( pCache->bPurgeable || (pCache->nMax==0 && pCache->nMin==0) );
  47826. pcache1EnterMutex(pGroup);
  47827. if( pCache->nPage ) pcache1TruncateUnsafe(pCache, 0);
  47828. assert( pGroup->nMaxPage >= pCache->nMax );
  47829. pGroup->nMaxPage -= pCache->nMax;
  47830. assert( pGroup->nMinPage >= pCache->nMin );
  47831. pGroup->nMinPage -= pCache->nMin;
  47832. pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
  47833. pcache1EnforceMaxPage(pCache);
  47834. pcache1LeaveMutex(pGroup);
  47835. sqlite3_free(pCache->pBulk);
  47836. sqlite3_free(pCache->apHash);
  47837. sqlite3_free(pCache);
  47838. }
  47839. /*
  47840. ** This function is called during initialization (sqlite3_initialize()) to
  47841. ** install the default pluggable cache module, assuming the user has not
  47842. ** already provided an alternative.
  47843. */
  47844. SQLITE_PRIVATE void sqlite3PCacheSetDefault(void){
  47845. static const sqlite3_pcache_methods2 defaultMethods = {
  47846. 1, /* iVersion */
  47847. 0, /* pArg */
  47848. pcache1Init, /* xInit */
  47849. pcache1Shutdown, /* xShutdown */
  47850. pcache1Create, /* xCreate */
  47851. pcache1Cachesize, /* xCachesize */
  47852. pcache1Pagecount, /* xPagecount */
  47853. pcache1Fetch, /* xFetch */
  47854. pcache1Unpin, /* xUnpin */
  47855. pcache1Rekey, /* xRekey */
  47856. pcache1Truncate, /* xTruncate */
  47857. pcache1Destroy, /* xDestroy */
  47858. pcache1Shrink /* xShrink */
  47859. };
  47860. sqlite3_config(SQLITE_CONFIG_PCACHE2, &defaultMethods);
  47861. }
  47862. /*
  47863. ** Return the size of the header on each page of this PCACHE implementation.
  47864. */
  47865. SQLITE_PRIVATE int sqlite3HeaderSizePcache1(void){ return ROUND8(sizeof(PgHdr1)); }
  47866. /*
  47867. ** Return the global mutex used by this PCACHE implementation. The
  47868. ** sqlite3_status() routine needs access to this mutex.
  47869. */
  47870. SQLITE_PRIVATE sqlite3_mutex *sqlite3Pcache1Mutex(void){
  47871. return pcache1.mutex;
  47872. }
  47873. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  47874. /*
  47875. ** This function is called to free superfluous dynamically allocated memory
  47876. ** held by the pager system. Memory in use by any SQLite pager allocated
  47877. ** by the current thread may be sqlite3_free()ed.
  47878. **
  47879. ** nReq is the number of bytes of memory required. Once this much has
  47880. ** been released, the function returns. The return value is the total number
  47881. ** of bytes of memory released.
  47882. */
  47883. SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){
  47884. int nFree = 0;
  47885. assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
  47886. assert( sqlite3_mutex_notheld(pcache1.mutex) );
  47887. if( sqlite3GlobalConfig.pPage==0 ){
  47888. PgHdr1 *p;
  47889. pcache1EnterMutex(&pcache1.grp);
  47890. while( (nReq<0 || nFree<nReq)
  47891. && (p=pcache1.grp.lru.pLruPrev)!=0
  47892. && p->isAnchor==0
  47893. ){
  47894. nFree += pcache1MemSize(p->page.pBuf);
  47895. #ifdef SQLITE_PCACHE_SEPARATE_HEADER
  47896. nFree += sqlite3MemSize(p);
  47897. #endif
  47898. assert( PAGE_IS_UNPINNED(p) );
  47899. pcache1PinPage(p);
  47900. pcache1RemoveFromHash(p, 1);
  47901. }
  47902. pcache1LeaveMutex(&pcache1.grp);
  47903. }
  47904. return nFree;
  47905. }
  47906. #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
  47907. #ifdef SQLITE_TEST
  47908. /*
  47909. ** This function is used by test procedures to inspect the internal state
  47910. ** of the global cache.
  47911. */
  47912. SQLITE_PRIVATE void sqlite3PcacheStats(
  47913. int *pnCurrent, /* OUT: Total number of pages cached */
  47914. int *pnMax, /* OUT: Global maximum cache size */
  47915. int *pnMin, /* OUT: Sum of PCache1.nMin for purgeable caches */
  47916. int *pnRecyclable /* OUT: Total number of pages available for recycling */
  47917. ){
  47918. PgHdr1 *p;
  47919. int nRecyclable = 0;
  47920. for(p=pcache1.grp.lru.pLruNext; p && !p->isAnchor; p=p->pLruNext){
  47921. assert( PAGE_IS_UNPINNED(p) );
  47922. nRecyclable++;
  47923. }
  47924. *pnCurrent = pcache1.grp.nPurgeable;
  47925. *pnMax = (int)pcache1.grp.nMaxPage;
  47926. *pnMin = (int)pcache1.grp.nMinPage;
  47927. *pnRecyclable = nRecyclable;
  47928. }
  47929. #endif
  47930. /************** End of pcache1.c *********************************************/
  47931. /************** Begin file rowset.c ******************************************/
  47932. /*
  47933. ** 2008 December 3
  47934. **
  47935. ** The author disclaims copyright to this source code. In place of
  47936. ** a legal notice, here is a blessing:
  47937. **
  47938. ** May you do good and not evil.
  47939. ** May you find forgiveness for yourself and forgive others.
  47940. ** May you share freely, never taking more than you give.
  47941. **
  47942. *************************************************************************
  47943. **
  47944. ** This module implements an object we call a "RowSet".
  47945. **
  47946. ** The RowSet object is a collection of rowids. Rowids
  47947. ** are inserted into the RowSet in an arbitrary order. Inserts
  47948. ** can be intermixed with tests to see if a given rowid has been
  47949. ** previously inserted into the RowSet.
  47950. **
  47951. ** After all inserts are finished, it is possible to extract the
  47952. ** elements of the RowSet in sorted order. Once this extraction
  47953. ** process has started, no new elements may be inserted.
  47954. **
  47955. ** Hence, the primitive operations for a RowSet are:
  47956. **
  47957. ** CREATE
  47958. ** INSERT
  47959. ** TEST
  47960. ** SMALLEST
  47961. ** DESTROY
  47962. **
  47963. ** The CREATE and DESTROY primitives are the constructor and destructor,
  47964. ** obviously. The INSERT primitive adds a new element to the RowSet.
  47965. ** TEST checks to see if an element is already in the RowSet. SMALLEST
  47966. ** extracts the least value from the RowSet.
  47967. **
  47968. ** The INSERT primitive might allocate additional memory. Memory is
  47969. ** allocated in chunks so most INSERTs do no allocation. There is an
  47970. ** upper bound on the size of allocated memory. No memory is freed
  47971. ** until DESTROY.
  47972. **
  47973. ** The TEST primitive includes a "batch" number. The TEST primitive
  47974. ** will only see elements that were inserted before the last change
  47975. ** in the batch number. In other words, if an INSERT occurs between
  47976. ** two TESTs where the TESTs have the same batch nubmer, then the
  47977. ** value added by the INSERT will not be visible to the second TEST.
  47978. ** The initial batch number is zero, so if the very first TEST contains
  47979. ** a non-zero batch number, it will see all prior INSERTs.
  47980. **
  47981. ** No INSERTs may occurs after a SMALLEST. An assertion will fail if
  47982. ** that is attempted.
  47983. **
  47984. ** The cost of an INSERT is roughly constant. (Sometimes new memory
  47985. ** has to be allocated on an INSERT.) The cost of a TEST with a new
  47986. ** batch number is O(NlogN) where N is the number of elements in the RowSet.
  47987. ** The cost of a TEST using the same batch number is O(logN). The cost
  47988. ** of the first SMALLEST is O(NlogN). Second and subsequent SMALLEST
  47989. ** primitives are constant time. The cost of DESTROY is O(N).
  47990. **
  47991. ** TEST and SMALLEST may not be used by the same RowSet. This used to
  47992. ** be possible, but the feature was not used, so it was removed in order
  47993. ** to simplify the code.
  47994. */
  47995. /* #include "sqliteInt.h" */
  47996. /*
  47997. ** Target size for allocation chunks.
  47998. */
  47999. #define ROWSET_ALLOCATION_SIZE 1024
  48000. /*
  48001. ** The number of rowset entries per allocation chunk.
  48002. */
  48003. #define ROWSET_ENTRY_PER_CHUNK \
  48004. ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry))
  48005. /*
  48006. ** Each entry in a RowSet is an instance of the following object.
  48007. **
  48008. ** This same object is reused to store a linked list of trees of RowSetEntry
  48009. ** objects. In that alternative use, pRight points to the next entry
  48010. ** in the list, pLeft points to the tree, and v is unused. The
  48011. ** RowSet.pForest value points to the head of this forest list.
  48012. */
  48013. struct RowSetEntry {
  48014. i64 v; /* ROWID value for this entry */
  48015. struct RowSetEntry *pRight; /* Right subtree (larger entries) or list */
  48016. struct RowSetEntry *pLeft; /* Left subtree (smaller entries) */
  48017. };
  48018. /*
  48019. ** RowSetEntry objects are allocated in large chunks (instances of the
  48020. ** following structure) to reduce memory allocation overhead. The
  48021. ** chunks are kept on a linked list so that they can be deallocated
  48022. ** when the RowSet is destroyed.
  48023. */
  48024. struct RowSetChunk {
  48025. struct RowSetChunk *pNextChunk; /* Next chunk on list of them all */
  48026. struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */
  48027. };
  48028. /*
  48029. ** A RowSet in an instance of the following structure.
  48030. **
  48031. ** A typedef of this structure if found in sqliteInt.h.
  48032. */
  48033. struct RowSet {
  48034. struct RowSetChunk *pChunk; /* List of all chunk allocations */
  48035. sqlite3 *db; /* The database connection */
  48036. struct RowSetEntry *pEntry; /* List of entries using pRight */
  48037. struct RowSetEntry *pLast; /* Last entry on the pEntry list */
  48038. struct RowSetEntry *pFresh; /* Source of new entry objects */
  48039. struct RowSetEntry *pForest; /* List of binary trees of entries */
  48040. u16 nFresh; /* Number of objects on pFresh */
  48041. u16 rsFlags; /* Various flags */
  48042. int iBatch; /* Current insert batch */
  48043. };
  48044. /*
  48045. ** Allowed values for RowSet.rsFlags
  48046. */
  48047. #define ROWSET_SORTED 0x01 /* True if RowSet.pEntry is sorted */
  48048. #define ROWSET_NEXT 0x02 /* True if sqlite3RowSetNext() has been called */
  48049. /*
  48050. ** Allocate a RowSet object. Return NULL if a memory allocation
  48051. ** error occurs.
  48052. */
  48053. SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3 *db){
  48054. RowSet *p = sqlite3DbMallocRawNN(db, sizeof(*p));
  48055. if( p ){
  48056. int N = sqlite3DbMallocSize(db, p);
  48057. p->pChunk = 0;
  48058. p->db = db;
  48059. p->pEntry = 0;
  48060. p->pLast = 0;
  48061. p->pForest = 0;
  48062. p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p);
  48063. p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry));
  48064. p->rsFlags = ROWSET_SORTED;
  48065. p->iBatch = 0;
  48066. }
  48067. return p;
  48068. }
  48069. /*
  48070. ** Deallocate all chunks from a RowSet. This frees all memory that
  48071. ** the RowSet has allocated over its lifetime. This routine is
  48072. ** the destructor for the RowSet.
  48073. */
  48074. SQLITE_PRIVATE void sqlite3RowSetClear(void *pArg){
  48075. RowSet *p = (RowSet*)pArg;
  48076. struct RowSetChunk *pChunk, *pNextChunk;
  48077. for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
  48078. pNextChunk = pChunk->pNextChunk;
  48079. sqlite3DbFree(p->db, pChunk);
  48080. }
  48081. p->pChunk = 0;
  48082. p->nFresh = 0;
  48083. p->pEntry = 0;
  48084. p->pLast = 0;
  48085. p->pForest = 0;
  48086. p->rsFlags = ROWSET_SORTED;
  48087. }
  48088. /*
  48089. ** Deallocate all chunks from a RowSet. This frees all memory that
  48090. ** the RowSet has allocated over its lifetime. This routine is
  48091. ** the destructor for the RowSet.
  48092. */
  48093. SQLITE_PRIVATE void sqlite3RowSetDelete(void *pArg){
  48094. sqlite3RowSetClear(pArg);
  48095. sqlite3DbFree(((RowSet*)pArg)->db, pArg);
  48096. }
  48097. /*
  48098. ** Allocate a new RowSetEntry object that is associated with the
  48099. ** given RowSet. Return a pointer to the new and completely uninitialized
  48100. ** object.
  48101. **
  48102. ** In an OOM situation, the RowSet.db->mallocFailed flag is set and this
  48103. ** routine returns NULL.
  48104. */
  48105. static struct RowSetEntry *rowSetEntryAlloc(RowSet *p){
  48106. assert( p!=0 );
  48107. if( p->nFresh==0 ){ /*OPTIMIZATION-IF-FALSE*/
  48108. /* We could allocate a fresh RowSetEntry each time one is needed, but it
  48109. ** is more efficient to pull a preallocated entry from the pool */
  48110. struct RowSetChunk *pNew;
  48111. pNew = sqlite3DbMallocRawNN(p->db, sizeof(*pNew));
  48112. if( pNew==0 ){
  48113. return 0;
  48114. }
  48115. pNew->pNextChunk = p->pChunk;
  48116. p->pChunk = pNew;
  48117. p->pFresh = pNew->aEntry;
  48118. p->nFresh = ROWSET_ENTRY_PER_CHUNK;
  48119. }
  48120. p->nFresh--;
  48121. return p->pFresh++;
  48122. }
  48123. /*
  48124. ** Insert a new value into a RowSet.
  48125. **
  48126. ** The mallocFailed flag of the database connection is set if a
  48127. ** memory allocation fails.
  48128. */
  48129. SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){
  48130. struct RowSetEntry *pEntry; /* The new entry */
  48131. struct RowSetEntry *pLast; /* The last prior entry */
  48132. /* This routine is never called after sqlite3RowSetNext() */
  48133. assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
  48134. pEntry = rowSetEntryAlloc(p);
  48135. if( pEntry==0 ) return;
  48136. pEntry->v = rowid;
  48137. pEntry->pRight = 0;
  48138. pLast = p->pLast;
  48139. if( pLast ){
  48140. if( rowid<=pLast->v ){ /*OPTIMIZATION-IF-FALSE*/
  48141. /* Avoid unnecessary sorts by preserving the ROWSET_SORTED flags
  48142. ** where possible */
  48143. p->rsFlags &= ~ROWSET_SORTED;
  48144. }
  48145. pLast->pRight = pEntry;
  48146. }else{
  48147. p->pEntry = pEntry;
  48148. }
  48149. p->pLast = pEntry;
  48150. }
  48151. /*
  48152. ** Merge two lists of RowSetEntry objects. Remove duplicates.
  48153. **
  48154. ** The input lists are connected via pRight pointers and are
  48155. ** assumed to each already be in sorted order.
  48156. */
  48157. static struct RowSetEntry *rowSetEntryMerge(
  48158. struct RowSetEntry *pA, /* First sorted list to be merged */
  48159. struct RowSetEntry *pB /* Second sorted list to be merged */
  48160. ){
  48161. struct RowSetEntry head;
  48162. struct RowSetEntry *pTail;
  48163. pTail = &head;
  48164. assert( pA!=0 && pB!=0 );
  48165. for(;;){
  48166. assert( pA->pRight==0 || pA->v<=pA->pRight->v );
  48167. assert( pB->pRight==0 || pB->v<=pB->pRight->v );
  48168. if( pA->v<=pB->v ){
  48169. if( pA->v<pB->v ) pTail = pTail->pRight = pA;
  48170. pA = pA->pRight;
  48171. if( pA==0 ){
  48172. pTail->pRight = pB;
  48173. break;
  48174. }
  48175. }else{
  48176. pTail = pTail->pRight = pB;
  48177. pB = pB->pRight;
  48178. if( pB==0 ){
  48179. pTail->pRight = pA;
  48180. break;
  48181. }
  48182. }
  48183. }
  48184. return head.pRight;
  48185. }
  48186. /*
  48187. ** Sort all elements on the list of RowSetEntry objects into order of
  48188. ** increasing v.
  48189. */
  48190. static struct RowSetEntry *rowSetEntrySort(struct RowSetEntry *pIn){
  48191. unsigned int i;
  48192. struct RowSetEntry *pNext, *aBucket[40];
  48193. memset(aBucket, 0, sizeof(aBucket));
  48194. while( pIn ){
  48195. pNext = pIn->pRight;
  48196. pIn->pRight = 0;
  48197. for(i=0; aBucket[i]; i++){
  48198. pIn = rowSetEntryMerge(aBucket[i], pIn);
  48199. aBucket[i] = 0;
  48200. }
  48201. aBucket[i] = pIn;
  48202. pIn = pNext;
  48203. }
  48204. pIn = aBucket[0];
  48205. for(i=1; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){
  48206. if( aBucket[i]==0 ) continue;
  48207. pIn = pIn ? rowSetEntryMerge(pIn, aBucket[i]) : aBucket[i];
  48208. }
  48209. return pIn;
  48210. }
  48211. /*
  48212. ** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects.
  48213. ** Convert this tree into a linked list connected by the pRight pointers
  48214. ** and return pointers to the first and last elements of the new list.
  48215. */
  48216. static void rowSetTreeToList(
  48217. struct RowSetEntry *pIn, /* Root of the input tree */
  48218. struct RowSetEntry **ppFirst, /* Write head of the output list here */
  48219. struct RowSetEntry **ppLast /* Write tail of the output list here */
  48220. ){
  48221. assert( pIn!=0 );
  48222. if( pIn->pLeft ){
  48223. struct RowSetEntry *p;
  48224. rowSetTreeToList(pIn->pLeft, ppFirst, &p);
  48225. p->pRight = pIn;
  48226. }else{
  48227. *ppFirst = pIn;
  48228. }
  48229. if( pIn->pRight ){
  48230. rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast);
  48231. }else{
  48232. *ppLast = pIn;
  48233. }
  48234. assert( (*ppLast)->pRight==0 );
  48235. }
  48236. /*
  48237. ** Convert a sorted list of elements (connected by pRight) into a binary
  48238. ** tree with depth of iDepth. A depth of 1 means the tree contains a single
  48239. ** node taken from the head of *ppList. A depth of 2 means a tree with
  48240. ** three nodes. And so forth.
  48241. **
  48242. ** Use as many entries from the input list as required and update the
  48243. ** *ppList to point to the unused elements of the list. If the input
  48244. ** list contains too few elements, then construct an incomplete tree
  48245. ** and leave *ppList set to NULL.
  48246. **
  48247. ** Return a pointer to the root of the constructed binary tree.
  48248. */
  48249. static struct RowSetEntry *rowSetNDeepTree(
  48250. struct RowSetEntry **ppList,
  48251. int iDepth
  48252. ){
  48253. struct RowSetEntry *p; /* Root of the new tree */
  48254. struct RowSetEntry *pLeft; /* Left subtree */
  48255. if( *ppList==0 ){ /*OPTIMIZATION-IF-TRUE*/
  48256. /* Prevent unnecessary deep recursion when we run out of entries */
  48257. return 0;
  48258. }
  48259. if( iDepth>1 ){ /*OPTIMIZATION-IF-TRUE*/
  48260. /* This branch causes a *balanced* tree to be generated. A valid tree
  48261. ** is still generated without this branch, but the tree is wildly
  48262. ** unbalanced and inefficient. */
  48263. pLeft = rowSetNDeepTree(ppList, iDepth-1);
  48264. p = *ppList;
  48265. if( p==0 ){ /*OPTIMIZATION-IF-FALSE*/
  48266. /* It is safe to always return here, but the resulting tree
  48267. ** would be unbalanced */
  48268. return pLeft;
  48269. }
  48270. p->pLeft = pLeft;
  48271. *ppList = p->pRight;
  48272. p->pRight = rowSetNDeepTree(ppList, iDepth-1);
  48273. }else{
  48274. p = *ppList;
  48275. *ppList = p->pRight;
  48276. p->pLeft = p->pRight = 0;
  48277. }
  48278. return p;
  48279. }
  48280. /*
  48281. ** Convert a sorted list of elements into a binary tree. Make the tree
  48282. ** as deep as it needs to be in order to contain the entire list.
  48283. */
  48284. static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){
  48285. int iDepth; /* Depth of the tree so far */
  48286. struct RowSetEntry *p; /* Current tree root */
  48287. struct RowSetEntry *pLeft; /* Left subtree */
  48288. assert( pList!=0 );
  48289. p = pList;
  48290. pList = p->pRight;
  48291. p->pLeft = p->pRight = 0;
  48292. for(iDepth=1; pList; iDepth++){
  48293. pLeft = p;
  48294. p = pList;
  48295. pList = p->pRight;
  48296. p->pLeft = pLeft;
  48297. p->pRight = rowSetNDeepTree(&pList, iDepth);
  48298. }
  48299. return p;
  48300. }
  48301. /*
  48302. ** Extract the smallest element from the RowSet.
  48303. ** Write the element into *pRowid. Return 1 on success. Return
  48304. ** 0 if the RowSet is already empty.
  48305. **
  48306. ** After this routine has been called, the sqlite3RowSetInsert()
  48307. ** routine may not be called again.
  48308. **
  48309. ** This routine may not be called after sqlite3RowSetTest() has
  48310. ** been used. Older versions of RowSet allowed that, but as the
  48311. ** capability was not used by the code generator, it was removed
  48312. ** for code economy.
  48313. */
  48314. SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){
  48315. assert( p!=0 );
  48316. assert( p->pForest==0 ); /* Cannot be used with sqlite3RowSetText() */
  48317. /* Merge the forest into a single sorted list on first call */
  48318. if( (p->rsFlags & ROWSET_NEXT)==0 ){ /*OPTIMIZATION-IF-FALSE*/
  48319. if( (p->rsFlags & ROWSET_SORTED)==0 ){ /*OPTIMIZATION-IF-FALSE*/
  48320. p->pEntry = rowSetEntrySort(p->pEntry);
  48321. }
  48322. p->rsFlags |= ROWSET_SORTED|ROWSET_NEXT;
  48323. }
  48324. /* Return the next entry on the list */
  48325. if( p->pEntry ){
  48326. *pRowid = p->pEntry->v;
  48327. p->pEntry = p->pEntry->pRight;
  48328. if( p->pEntry==0 ){ /*OPTIMIZATION-IF-TRUE*/
  48329. /* Free memory immediately, rather than waiting on sqlite3_finalize() */
  48330. sqlite3RowSetClear(p);
  48331. }
  48332. return 1;
  48333. }else{
  48334. return 0;
  48335. }
  48336. }
  48337. /*
  48338. ** Check to see if element iRowid was inserted into the rowset as
  48339. ** part of any insert batch prior to iBatch. Return 1 or 0.
  48340. **
  48341. ** If this is the first test of a new batch and if there exist entries
  48342. ** on pRowSet->pEntry, then sort those entries into the forest at
  48343. ** pRowSet->pForest so that they can be tested.
  48344. */
  48345. SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, int iBatch, sqlite3_int64 iRowid){
  48346. struct RowSetEntry *p, *pTree;
  48347. /* This routine is never called after sqlite3RowSetNext() */
  48348. assert( pRowSet!=0 && (pRowSet->rsFlags & ROWSET_NEXT)==0 );
  48349. /* Sort entries into the forest on the first test of a new batch.
  48350. ** To save unnecessary work, only do this when the batch number changes.
  48351. */
  48352. if( iBatch!=pRowSet->iBatch ){ /*OPTIMIZATION-IF-FALSE*/
  48353. p = pRowSet->pEntry;
  48354. if( p ){
  48355. struct RowSetEntry **ppPrevTree = &pRowSet->pForest;
  48356. if( (pRowSet->rsFlags & ROWSET_SORTED)==0 ){ /*OPTIMIZATION-IF-FALSE*/
  48357. /* Only sort the current set of entries if they need it */
  48358. p = rowSetEntrySort(p);
  48359. }
  48360. for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
  48361. ppPrevTree = &pTree->pRight;
  48362. if( pTree->pLeft==0 ){
  48363. pTree->pLeft = rowSetListToTree(p);
  48364. break;
  48365. }else{
  48366. struct RowSetEntry *pAux, *pTail;
  48367. rowSetTreeToList(pTree->pLeft, &pAux, &pTail);
  48368. pTree->pLeft = 0;
  48369. p = rowSetEntryMerge(pAux, p);
  48370. }
  48371. }
  48372. if( pTree==0 ){
  48373. *ppPrevTree = pTree = rowSetEntryAlloc(pRowSet);
  48374. if( pTree ){
  48375. pTree->v = 0;
  48376. pTree->pRight = 0;
  48377. pTree->pLeft = rowSetListToTree(p);
  48378. }
  48379. }
  48380. pRowSet->pEntry = 0;
  48381. pRowSet->pLast = 0;
  48382. pRowSet->rsFlags |= ROWSET_SORTED;
  48383. }
  48384. pRowSet->iBatch = iBatch;
  48385. }
  48386. /* Test to see if the iRowid value appears anywhere in the forest.
  48387. ** Return 1 if it does and 0 if not.
  48388. */
  48389. for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
  48390. p = pTree->pLeft;
  48391. while( p ){
  48392. if( p->v<iRowid ){
  48393. p = p->pRight;
  48394. }else if( p->v>iRowid ){
  48395. p = p->pLeft;
  48396. }else{
  48397. return 1;
  48398. }
  48399. }
  48400. }
  48401. return 0;
  48402. }
  48403. /************** End of rowset.c **********************************************/
  48404. /************** Begin file pager.c *******************************************/
  48405. /*
  48406. ** 2001 September 15
  48407. **
  48408. ** The author disclaims copyright to this source code. In place of
  48409. ** a legal notice, here is a blessing:
  48410. **
  48411. ** May you do good and not evil.
  48412. ** May you find forgiveness for yourself and forgive others.
  48413. ** May you share freely, never taking more than you give.
  48414. **
  48415. *************************************************************************
  48416. ** This is the implementation of the page cache subsystem or "pager".
  48417. **
  48418. ** The pager is used to access a database disk file. It implements
  48419. ** atomic commit and rollback through the use of a journal file that
  48420. ** is separate from the database file. The pager also implements file
  48421. ** locking to prevent two processes from writing the same database
  48422. ** file simultaneously, or one process from reading the database while
  48423. ** another is writing.
  48424. */
  48425. #ifndef SQLITE_OMIT_DISKIO
  48426. /* #include "sqliteInt.h" */
  48427. /************** Include wal.h in the middle of pager.c ***********************/
  48428. /************** Begin file wal.h *********************************************/
  48429. /*
  48430. ** 2010 February 1
  48431. **
  48432. ** The author disclaims copyright to this source code. In place of
  48433. ** a legal notice, here is a blessing:
  48434. **
  48435. ** May you do good and not evil.
  48436. ** May you find forgiveness for yourself and forgive others.
  48437. ** May you share freely, never taking more than you give.
  48438. **
  48439. *************************************************************************
  48440. ** This header file defines the interface to the write-ahead logging
  48441. ** system. Refer to the comments below and the header comment attached to
  48442. ** the implementation of each function in log.c for further details.
  48443. */
  48444. #ifndef SQLITE_WAL_H
  48445. #define SQLITE_WAL_H
  48446. /* #include "sqliteInt.h" */
  48447. /* Macros for extracting appropriate sync flags for either transaction
  48448. ** commits (WAL_SYNC_FLAGS(X)) or for checkpoint ops (CKPT_SYNC_FLAGS(X)):
  48449. */
  48450. #define WAL_SYNC_FLAGS(X) ((X)&0x03)
  48451. #define CKPT_SYNC_FLAGS(X) (((X)>>2)&0x03)
  48452. #ifdef SQLITE_OMIT_WAL
  48453. # define sqlite3WalOpen(x,y,z) 0
  48454. # define sqlite3WalLimit(x,y)
  48455. # define sqlite3WalClose(v,w,x,y,z) 0
  48456. # define sqlite3WalBeginReadTransaction(y,z) 0
  48457. # define sqlite3WalEndReadTransaction(z)
  48458. # define sqlite3WalDbsize(y) 0
  48459. # define sqlite3WalBeginWriteTransaction(y) 0
  48460. # define sqlite3WalEndWriteTransaction(x) 0
  48461. # define sqlite3WalUndo(x,y,z) 0
  48462. # define sqlite3WalSavepoint(y,z)
  48463. # define sqlite3WalSavepointUndo(y,z) 0
  48464. # define sqlite3WalFrames(u,v,w,x,y,z) 0
  48465. # define sqlite3WalCheckpoint(q,r,s,t,u,v,w,x,y,z) 0
  48466. # define sqlite3WalCallback(z) 0
  48467. # define sqlite3WalExclusiveMode(y,z) 0
  48468. # define sqlite3WalHeapMemory(z) 0
  48469. # define sqlite3WalFramesize(z) 0
  48470. # define sqlite3WalFindFrame(x,y,z) 0
  48471. # define sqlite3WalFile(x) 0
  48472. #else
  48473. #define WAL_SAVEPOINT_NDATA 4
  48474. /* Connection to a write-ahead log (WAL) file.
  48475. ** There is one object of this type for each pager.
  48476. */
  48477. typedef struct Wal Wal;
  48478. /* Open and close a connection to a write-ahead log. */
  48479. SQLITE_PRIVATE int sqlite3WalOpen(sqlite3_vfs*, sqlite3_file*, const char *, int, i64, Wal**);
  48480. SQLITE_PRIVATE int sqlite3WalClose(Wal *pWal, sqlite3*, int sync_flags, int, u8 *);
  48481. /* Set the limiting size of a WAL file. */
  48482. SQLITE_PRIVATE void sqlite3WalLimit(Wal*, i64);
  48483. /* Used by readers to open (lock) and close (unlock) a snapshot. A
  48484. ** snapshot is like a read-transaction. It is the state of the database
  48485. ** at an instant in time. sqlite3WalOpenSnapshot gets a read lock and
  48486. ** preserves the current state even if the other threads or processes
  48487. ** write to or checkpoint the WAL. sqlite3WalCloseSnapshot() closes the
  48488. ** transaction and releases the lock.
  48489. */
  48490. SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *);
  48491. SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal);
  48492. /* Read a page from the write-ahead log, if it is present. */
  48493. SQLITE_PRIVATE int sqlite3WalFindFrame(Wal *, Pgno, u32 *);
  48494. SQLITE_PRIVATE int sqlite3WalReadFrame(Wal *, u32, int, u8 *);
  48495. /* If the WAL is not empty, return the size of the database. */
  48496. SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal);
  48497. /* Obtain or release the WRITER lock. */
  48498. SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal);
  48499. SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal);
  48500. /* Undo any frames written (but not committed) to the log */
  48501. SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx);
  48502. /* Return an integer that records the current (uncommitted) write
  48503. ** position in the WAL */
  48504. SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData);
  48505. /* Move the write position of the WAL back to iFrame. Called in
  48506. ** response to a ROLLBACK TO command. */
  48507. SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData);
  48508. /* Write a frame or frames to the log. */
  48509. SQLITE_PRIVATE int sqlite3WalFrames(Wal *pWal, int, PgHdr *, Pgno, int, int);
  48510. /* Copy pages from the log to the database file */
  48511. SQLITE_PRIVATE int sqlite3WalCheckpoint(
  48512. Wal *pWal, /* Write-ahead log connection */
  48513. sqlite3 *db, /* Check this handle's interrupt flag */
  48514. int eMode, /* One of PASSIVE, FULL and RESTART */
  48515. int (*xBusy)(void*), /* Function to call when busy */
  48516. void *pBusyArg, /* Context argument for xBusyHandler */
  48517. int sync_flags, /* Flags to sync db file with (or 0) */
  48518. int nBuf, /* Size of buffer nBuf */
  48519. u8 *zBuf, /* Temporary buffer to use */
  48520. int *pnLog, /* OUT: Number of frames in WAL */
  48521. int *pnCkpt /* OUT: Number of backfilled frames in WAL */
  48522. );
  48523. /* Return the value to pass to a sqlite3_wal_hook callback, the
  48524. ** number of frames in the WAL at the point of the last commit since
  48525. ** sqlite3WalCallback() was called. If no commits have occurred since
  48526. ** the last call, then return 0.
  48527. */
  48528. SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal);
  48529. /* Tell the wal layer that an EXCLUSIVE lock has been obtained (or released)
  48530. ** by the pager layer on the database file.
  48531. */
  48532. SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op);
  48533. /* Return true if the argument is non-NULL and the WAL module is using
  48534. ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
  48535. ** WAL module is using shared-memory, return false.
  48536. */
  48537. SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal);
  48538. #ifdef SQLITE_ENABLE_SNAPSHOT
  48539. SQLITE_PRIVATE int sqlite3WalSnapshotGet(Wal *pWal, sqlite3_snapshot **ppSnapshot);
  48540. SQLITE_PRIVATE void sqlite3WalSnapshotOpen(Wal *pWal, sqlite3_snapshot *pSnapshot);
  48541. SQLITE_PRIVATE int sqlite3WalSnapshotRecover(Wal *pWal);
  48542. SQLITE_PRIVATE int sqlite3WalSnapshotCheck(Wal *pWal, sqlite3_snapshot *pSnapshot);
  48543. SQLITE_PRIVATE void sqlite3WalSnapshotUnlock(Wal *pWal);
  48544. #endif
  48545. #ifdef SQLITE_ENABLE_ZIPVFS
  48546. /* If the WAL file is not empty, return the number of bytes of content
  48547. ** stored in each frame (i.e. the db page-size when the WAL was created).
  48548. */
  48549. SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal);
  48550. #endif
  48551. /* Return the sqlite3_file object for the WAL file */
  48552. SQLITE_PRIVATE sqlite3_file *sqlite3WalFile(Wal *pWal);
  48553. #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
  48554. SQLITE_PRIVATE int sqlite3WalWriteLock(Wal *pWal, int bLock);
  48555. SQLITE_PRIVATE void sqlite3WalDb(Wal *pWal, sqlite3 *db);
  48556. #endif
  48557. #endif /* ifndef SQLITE_OMIT_WAL */
  48558. #endif /* SQLITE_WAL_H */
  48559. /************** End of wal.h *************************************************/
  48560. /************** Continuing where we left off in pager.c **********************/
  48561. /******************* NOTES ON THE DESIGN OF THE PAGER ************************
  48562. **
  48563. ** This comment block describes invariants that hold when using a rollback
  48564. ** journal. These invariants do not apply for journal_mode=WAL,
  48565. ** journal_mode=MEMORY, or journal_mode=OFF.
  48566. **
  48567. ** Within this comment block, a page is deemed to have been synced
  48568. ** automatically as soon as it is written when PRAGMA synchronous=OFF.
  48569. ** Otherwise, the page is not synced until the xSync method of the VFS
  48570. ** is called successfully on the file containing the page.
  48571. **
  48572. ** Definition: A page of the database file is said to be "overwriteable" if
  48573. ** one or more of the following are true about the page:
  48574. **
  48575. ** (a) The original content of the page as it was at the beginning of
  48576. ** the transaction has been written into the rollback journal and
  48577. ** synced.
  48578. **
  48579. ** (b) The page was a freelist leaf page at the start of the transaction.
  48580. **
  48581. ** (c) The page number is greater than the largest page that existed in
  48582. ** the database file at the start of the transaction.
  48583. **
  48584. ** (1) A page of the database file is never overwritten unless one of the
  48585. ** following are true:
  48586. **
  48587. ** (a) The page and all other pages on the same sector are overwriteable.
  48588. **
  48589. ** (b) The atomic page write optimization is enabled, and the entire
  48590. ** transaction other than the update of the transaction sequence
  48591. ** number consists of a single page change.
  48592. **
  48593. ** (2) The content of a page written into the rollback journal exactly matches
  48594. ** both the content in the database when the rollback journal was written
  48595. ** and the content in the database at the beginning of the current
  48596. ** transaction.
  48597. **
  48598. ** (3) Writes to the database file are an integer multiple of the page size
  48599. ** in length and are aligned on a page boundary.
  48600. **
  48601. ** (4) Reads from the database file are either aligned on a page boundary and
  48602. ** an integer multiple of the page size in length or are taken from the
  48603. ** first 100 bytes of the database file.
  48604. **
  48605. ** (5) All writes to the database file are synced prior to the rollback journal
  48606. ** being deleted, truncated, or zeroed.
  48607. **
  48608. ** (6) If a master journal file is used, then all writes to the database file
  48609. ** are synced prior to the master journal being deleted.
  48610. **
  48611. ** Definition: Two databases (or the same database at two points it time)
  48612. ** are said to be "logically equivalent" if they give the same answer to
  48613. ** all queries. Note in particular the content of freelist leaf
  48614. ** pages can be changed arbitrarily without affecting the logical equivalence
  48615. ** of the database.
  48616. **
  48617. ** (7) At any time, if any subset, including the empty set and the total set,
  48618. ** of the unsynced changes to a rollback journal are removed and the
  48619. ** journal is rolled back, the resulting database file will be logically
  48620. ** equivalent to the database file at the beginning of the transaction.
  48621. **
  48622. ** (8) When a transaction is rolled back, the xTruncate method of the VFS
  48623. ** is called to restore the database file to the same size it was at
  48624. ** the beginning of the transaction. (In some VFSes, the xTruncate
  48625. ** method is a no-op, but that does not change the fact the SQLite will
  48626. ** invoke it.)
  48627. **
  48628. ** (9) Whenever the database file is modified, at least one bit in the range
  48629. ** of bytes from 24 through 39 inclusive will be changed prior to releasing
  48630. ** the EXCLUSIVE lock, thus signaling other connections on the same
  48631. ** database to flush their caches.
  48632. **
  48633. ** (10) The pattern of bits in bytes 24 through 39 shall not repeat in less
  48634. ** than one billion transactions.
  48635. **
  48636. ** (11) A database file is well-formed at the beginning and at the conclusion
  48637. ** of every transaction.
  48638. **
  48639. ** (12) An EXCLUSIVE lock is held on the database file when writing to
  48640. ** the database file.
  48641. **
  48642. ** (13) A SHARED lock is held on the database file while reading any
  48643. ** content out of the database file.
  48644. **
  48645. ******************************************************************************/
  48646. /*
  48647. ** Macros for troubleshooting. Normally turned off
  48648. */
  48649. #if 0
  48650. int sqlite3PagerTrace=1; /* True to enable tracing */
  48651. #define sqlite3DebugPrintf printf
  48652. #define PAGERTRACE(X) if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; }
  48653. #else
  48654. #define PAGERTRACE(X)
  48655. #endif
  48656. /*
  48657. ** The following two macros are used within the PAGERTRACE() macros above
  48658. ** to print out file-descriptors.
  48659. **
  48660. ** PAGERID() takes a pointer to a Pager struct as its argument. The
  48661. ** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
  48662. ** struct as its argument.
  48663. */
  48664. #define PAGERID(p) (SQLITE_PTR_TO_INT(p->fd))
  48665. #define FILEHANDLEID(fd) (SQLITE_PTR_TO_INT(fd))
  48666. /*
  48667. ** The Pager.eState variable stores the current 'state' of a pager. A
  48668. ** pager may be in any one of the seven states shown in the following
  48669. ** state diagram.
  48670. **
  48671. ** OPEN <------+------+
  48672. ** | | |
  48673. ** V | |
  48674. ** +---------> READER-------+ |
  48675. ** | | |
  48676. ** | V |
  48677. ** |<-------WRITER_LOCKED------> ERROR
  48678. ** | | ^
  48679. ** | V |
  48680. ** |<------WRITER_CACHEMOD-------->|
  48681. ** | | |
  48682. ** | V |
  48683. ** |<-------WRITER_DBMOD---------->|
  48684. ** | | |
  48685. ** | V |
  48686. ** +<------WRITER_FINISHED-------->+
  48687. **
  48688. **
  48689. ** List of state transitions and the C [function] that performs each:
  48690. **
  48691. ** OPEN -> READER [sqlite3PagerSharedLock]
  48692. ** READER -> OPEN [pager_unlock]
  48693. **
  48694. ** READER -> WRITER_LOCKED [sqlite3PagerBegin]
  48695. ** WRITER_LOCKED -> WRITER_CACHEMOD [pager_open_journal]
  48696. ** WRITER_CACHEMOD -> WRITER_DBMOD [syncJournal]
  48697. ** WRITER_DBMOD -> WRITER_FINISHED [sqlite3PagerCommitPhaseOne]
  48698. ** WRITER_*** -> READER [pager_end_transaction]
  48699. **
  48700. ** WRITER_*** -> ERROR [pager_error]
  48701. ** ERROR -> OPEN [pager_unlock]
  48702. **
  48703. **
  48704. ** OPEN:
  48705. **
  48706. ** The pager starts up in this state. Nothing is guaranteed in this
  48707. ** state - the file may or may not be locked and the database size is
  48708. ** unknown. The database may not be read or written.
  48709. **
  48710. ** * No read or write transaction is active.
  48711. ** * Any lock, or no lock at all, may be held on the database file.
  48712. ** * The dbSize, dbOrigSize and dbFileSize variables may not be trusted.
  48713. **
  48714. ** READER:
  48715. **
  48716. ** In this state all the requirements for reading the database in
  48717. ** rollback (non-WAL) mode are met. Unless the pager is (or recently
  48718. ** was) in exclusive-locking mode, a user-level read transaction is
  48719. ** open. The database size is known in this state.
  48720. **
  48721. ** A connection running with locking_mode=normal enters this state when
  48722. ** it opens a read-transaction on the database and returns to state
  48723. ** OPEN after the read-transaction is completed. However a connection
  48724. ** running in locking_mode=exclusive (including temp databases) remains in
  48725. ** this state even after the read-transaction is closed. The only way
  48726. ** a locking_mode=exclusive connection can transition from READER to OPEN
  48727. ** is via the ERROR state (see below).
  48728. **
  48729. ** * A read transaction may be active (but a write-transaction cannot).
  48730. ** * A SHARED or greater lock is held on the database file.
  48731. ** * The dbSize variable may be trusted (even if a user-level read
  48732. ** transaction is not active). The dbOrigSize and dbFileSize variables
  48733. ** may not be trusted at this point.
  48734. ** * If the database is a WAL database, then the WAL connection is open.
  48735. ** * Even if a read-transaction is not open, it is guaranteed that
  48736. ** there is no hot-journal in the file-system.
  48737. **
  48738. ** WRITER_LOCKED:
  48739. **
  48740. ** The pager moves to this state from READER when a write-transaction
  48741. ** is first opened on the database. In WRITER_LOCKED state, all locks
  48742. ** required to start a write-transaction are held, but no actual
  48743. ** modifications to the cache or database have taken place.
  48744. **
  48745. ** In rollback mode, a RESERVED or (if the transaction was opened with
  48746. ** BEGIN EXCLUSIVE) EXCLUSIVE lock is obtained on the database file when
  48747. ** moving to this state, but the journal file is not written to or opened
  48748. ** to in this state. If the transaction is committed or rolled back while
  48749. ** in WRITER_LOCKED state, all that is required is to unlock the database
  48750. ** file.
  48751. **
  48752. ** IN WAL mode, WalBeginWriteTransaction() is called to lock the log file.
  48753. ** If the connection is running with locking_mode=exclusive, an attempt
  48754. ** is made to obtain an EXCLUSIVE lock on the database file.
  48755. **
  48756. ** * A write transaction is active.
  48757. ** * If the connection is open in rollback-mode, a RESERVED or greater
  48758. ** lock is held on the database file.
  48759. ** * If the connection is open in WAL-mode, a WAL write transaction
  48760. ** is open (i.e. sqlite3WalBeginWriteTransaction() has been successfully
  48761. ** called).
  48762. ** * The dbSize, dbOrigSize and dbFileSize variables are all valid.
  48763. ** * The contents of the pager cache have not been modified.
  48764. ** * The journal file may or may not be open.
  48765. ** * Nothing (not even the first header) has been written to the journal.
  48766. **
  48767. ** WRITER_CACHEMOD:
  48768. **
  48769. ** A pager moves from WRITER_LOCKED state to this state when a page is
  48770. ** first modified by the upper layer. In rollback mode the journal file
  48771. ** is opened (if it is not already open) and a header written to the
  48772. ** start of it. The database file on disk has not been modified.
  48773. **
  48774. ** * A write transaction is active.
  48775. ** * A RESERVED or greater lock is held on the database file.
  48776. ** * The journal file is open and the first header has been written
  48777. ** to it, but the header has not been synced to disk.
  48778. ** * The contents of the page cache have been modified.
  48779. **
  48780. ** WRITER_DBMOD:
  48781. **
  48782. ** The pager transitions from WRITER_CACHEMOD into WRITER_DBMOD state
  48783. ** when it modifies the contents of the database file. WAL connections
  48784. ** never enter this state (since they do not modify the database file,
  48785. ** just the log file).
  48786. **
  48787. ** * A write transaction is active.
  48788. ** * An EXCLUSIVE or greater lock is held on the database file.
  48789. ** * The journal file is open and the first header has been written
  48790. ** and synced to disk.
  48791. ** * The contents of the page cache have been modified (and possibly
  48792. ** written to disk).
  48793. **
  48794. ** WRITER_FINISHED:
  48795. **
  48796. ** It is not possible for a WAL connection to enter this state.
  48797. **
  48798. ** A rollback-mode pager changes to WRITER_FINISHED state from WRITER_DBMOD
  48799. ** state after the entire transaction has been successfully written into the
  48800. ** database file. In this state the transaction may be committed simply
  48801. ** by finalizing the journal file. Once in WRITER_FINISHED state, it is
  48802. ** not possible to modify the database further. At this point, the upper
  48803. ** layer must either commit or rollback the transaction.
  48804. **
  48805. ** * A write transaction is active.
  48806. ** * An EXCLUSIVE or greater lock is held on the database file.
  48807. ** * All writing and syncing of journal and database data has finished.
  48808. ** If no error occurred, all that remains is to finalize the journal to
  48809. ** commit the transaction. If an error did occur, the caller will need
  48810. ** to rollback the transaction.
  48811. **
  48812. ** ERROR:
  48813. **
  48814. ** The ERROR state is entered when an IO or disk-full error (including
  48815. ** SQLITE_IOERR_NOMEM) occurs at a point in the code that makes it
  48816. ** difficult to be sure that the in-memory pager state (cache contents,
  48817. ** db size etc.) are consistent with the contents of the file-system.
  48818. **
  48819. ** Temporary pager files may enter the ERROR state, but in-memory pagers
  48820. ** cannot.
  48821. **
  48822. ** For example, if an IO error occurs while performing a rollback,
  48823. ** the contents of the page-cache may be left in an inconsistent state.
  48824. ** At this point it would be dangerous to change back to READER state
  48825. ** (as usually happens after a rollback). Any subsequent readers might
  48826. ** report database corruption (due to the inconsistent cache), and if
  48827. ** they upgrade to writers, they may inadvertently corrupt the database
  48828. ** file. To avoid this hazard, the pager switches into the ERROR state
  48829. ** instead of READER following such an error.
  48830. **
  48831. ** Once it has entered the ERROR state, any attempt to use the pager
  48832. ** to read or write data returns an error. Eventually, once all
  48833. ** outstanding transactions have been abandoned, the pager is able to
  48834. ** transition back to OPEN state, discarding the contents of the
  48835. ** page-cache and any other in-memory state at the same time. Everything
  48836. ** is reloaded from disk (and, if necessary, hot-journal rollback peformed)
  48837. ** when a read-transaction is next opened on the pager (transitioning
  48838. ** the pager into READER state). At that point the system has recovered
  48839. ** from the error.
  48840. **
  48841. ** Specifically, the pager jumps into the ERROR state if:
  48842. **
  48843. ** 1. An error occurs while attempting a rollback. This happens in
  48844. ** function sqlite3PagerRollback().
  48845. **
  48846. ** 2. An error occurs while attempting to finalize a journal file
  48847. ** following a commit in function sqlite3PagerCommitPhaseTwo().
  48848. **
  48849. ** 3. An error occurs while attempting to write to the journal or
  48850. ** database file in function pagerStress() in order to free up
  48851. ** memory.
  48852. **
  48853. ** In other cases, the error is returned to the b-tree layer. The b-tree
  48854. ** layer then attempts a rollback operation. If the error condition
  48855. ** persists, the pager enters the ERROR state via condition (1) above.
  48856. **
  48857. ** Condition (3) is necessary because it can be triggered by a read-only
  48858. ** statement executed within a transaction. In this case, if the error
  48859. ** code were simply returned to the user, the b-tree layer would not
  48860. ** automatically attempt a rollback, as it assumes that an error in a
  48861. ** read-only statement cannot leave the pager in an internally inconsistent
  48862. ** state.
  48863. **
  48864. ** * The Pager.errCode variable is set to something other than SQLITE_OK.
  48865. ** * There are one or more outstanding references to pages (after the
  48866. ** last reference is dropped the pager should move back to OPEN state).
  48867. ** * The pager is not an in-memory pager.
  48868. **
  48869. **
  48870. ** Notes:
  48871. **
  48872. ** * A pager is never in WRITER_DBMOD or WRITER_FINISHED state if the
  48873. ** connection is open in WAL mode. A WAL connection is always in one
  48874. ** of the first four states.
  48875. **
  48876. ** * Normally, a connection open in exclusive mode is never in PAGER_OPEN
  48877. ** state. There are two exceptions: immediately after exclusive-mode has
  48878. ** been turned on (and before any read or write transactions are
  48879. ** executed), and when the pager is leaving the "error state".
  48880. **
  48881. ** * See also: assert_pager_state().
  48882. */
  48883. #define PAGER_OPEN 0
  48884. #define PAGER_READER 1
  48885. #define PAGER_WRITER_LOCKED 2
  48886. #define PAGER_WRITER_CACHEMOD 3
  48887. #define PAGER_WRITER_DBMOD 4
  48888. #define PAGER_WRITER_FINISHED 5
  48889. #define PAGER_ERROR 6
  48890. /*
  48891. ** The Pager.eLock variable is almost always set to one of the
  48892. ** following locking-states, according to the lock currently held on
  48893. ** the database file: NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
  48894. ** This variable is kept up to date as locks are taken and released by
  48895. ** the pagerLockDb() and pagerUnlockDb() wrappers.
  48896. **
  48897. ** If the VFS xLock() or xUnlock() returns an error other than SQLITE_BUSY
  48898. ** (i.e. one of the SQLITE_IOERR subtypes), it is not clear whether or not
  48899. ** the operation was successful. In these circumstances pagerLockDb() and
  48900. ** pagerUnlockDb() take a conservative approach - eLock is always updated
  48901. ** when unlocking the file, and only updated when locking the file if the
  48902. ** VFS call is successful. This way, the Pager.eLock variable may be set
  48903. ** to a less exclusive (lower) value than the lock that is actually held
  48904. ** at the system level, but it is never set to a more exclusive value.
  48905. **
  48906. ** This is usually safe. If an xUnlock fails or appears to fail, there may
  48907. ** be a few redundant xLock() calls or a lock may be held for longer than
  48908. ** required, but nothing really goes wrong.
  48909. **
  48910. ** The exception is when the database file is unlocked as the pager moves
  48911. ** from ERROR to OPEN state. At this point there may be a hot-journal file
  48912. ** in the file-system that needs to be rolled back (as part of an OPEN->SHARED
  48913. ** transition, by the same pager or any other). If the call to xUnlock()
  48914. ** fails at this point and the pager is left holding an EXCLUSIVE lock, this
  48915. ** can confuse the call to xCheckReservedLock() call made later as part
  48916. ** of hot-journal detection.
  48917. **
  48918. ** xCheckReservedLock() is defined as returning true "if there is a RESERVED
  48919. ** lock held by this process or any others". So xCheckReservedLock may
  48920. ** return true because the caller itself is holding an EXCLUSIVE lock (but
  48921. ** doesn't know it because of a previous error in xUnlock). If this happens
  48922. ** a hot-journal may be mistaken for a journal being created by an active
  48923. ** transaction in another process, causing SQLite to read from the database
  48924. ** without rolling it back.
  48925. **
  48926. ** To work around this, if a call to xUnlock() fails when unlocking the
  48927. ** database in the ERROR state, Pager.eLock is set to UNKNOWN_LOCK. It
  48928. ** is only changed back to a real locking state after a successful call
  48929. ** to xLock(EXCLUSIVE). Also, the code to do the OPEN->SHARED state transition
  48930. ** omits the check for a hot-journal if Pager.eLock is set to UNKNOWN_LOCK
  48931. ** lock. Instead, it assumes a hot-journal exists and obtains an EXCLUSIVE
  48932. ** lock on the database file before attempting to roll it back. See function
  48933. ** PagerSharedLock() for more detail.
  48934. **
  48935. ** Pager.eLock may only be set to UNKNOWN_LOCK when the pager is in
  48936. ** PAGER_OPEN state.
  48937. */
  48938. #define UNKNOWN_LOCK (EXCLUSIVE_LOCK+1)
  48939. /*
  48940. ** The maximum allowed sector size. 64KiB. If the xSectorsize() method
  48941. ** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.
  48942. ** This could conceivably cause corruption following a power failure on
  48943. ** such a system. This is currently an undocumented limit.
  48944. */
  48945. #define MAX_SECTOR_SIZE 0x10000
  48946. /*
  48947. ** An instance of the following structure is allocated for each active
  48948. ** savepoint and statement transaction in the system. All such structures
  48949. ** are stored in the Pager.aSavepoint[] array, which is allocated and
  48950. ** resized using sqlite3Realloc().
  48951. **
  48952. ** When a savepoint is created, the PagerSavepoint.iHdrOffset field is
  48953. ** set to 0. If a journal-header is written into the main journal while
  48954. ** the savepoint is active, then iHdrOffset is set to the byte offset
  48955. ** immediately following the last journal record written into the main
  48956. ** journal before the journal-header. This is required during savepoint
  48957. ** rollback (see pagerPlaybackSavepoint()).
  48958. */
  48959. typedef struct PagerSavepoint PagerSavepoint;
  48960. struct PagerSavepoint {
  48961. i64 iOffset; /* Starting offset in main journal */
  48962. i64 iHdrOffset; /* See above */
  48963. Bitvec *pInSavepoint; /* Set of pages in this savepoint */
  48964. Pgno nOrig; /* Original number of pages in file */
  48965. Pgno iSubRec; /* Index of first record in sub-journal */
  48966. #ifndef SQLITE_OMIT_WAL
  48967. u32 aWalData[WAL_SAVEPOINT_NDATA]; /* WAL savepoint context */
  48968. #endif
  48969. };
  48970. /*
  48971. ** Bits of the Pager.doNotSpill flag. See further description below.
  48972. */
  48973. #define SPILLFLAG_OFF 0x01 /* Never spill cache. Set via pragma */
  48974. #define SPILLFLAG_ROLLBACK 0x02 /* Current rolling back, so do not spill */
  48975. #define SPILLFLAG_NOSYNC 0x04 /* Spill is ok, but do not sync */
  48976. /*
  48977. ** An open page cache is an instance of struct Pager. A description of
  48978. ** some of the more important member variables follows:
  48979. **
  48980. ** eState
  48981. **
  48982. ** The current 'state' of the pager object. See the comment and state
  48983. ** diagram above for a description of the pager state.
  48984. **
  48985. ** eLock
  48986. **
  48987. ** For a real on-disk database, the current lock held on the database file -
  48988. ** NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
  48989. **
  48990. ** For a temporary or in-memory database (neither of which require any
  48991. ** locks), this variable is always set to EXCLUSIVE_LOCK. Since such
  48992. ** databases always have Pager.exclusiveMode==1, this tricks the pager
  48993. ** logic into thinking that it already has all the locks it will ever
  48994. ** need (and no reason to release them).
  48995. **
  48996. ** In some (obscure) circumstances, this variable may also be set to
  48997. ** UNKNOWN_LOCK. See the comment above the #define of UNKNOWN_LOCK for
  48998. ** details.
  48999. **
  49000. ** changeCountDone
  49001. **
  49002. ** This boolean variable is used to make sure that the change-counter
  49003. ** (the 4-byte header field at byte offset 24 of the database file) is
  49004. ** not updated more often than necessary.
  49005. **
  49006. ** It is set to true when the change-counter field is updated, which
  49007. ** can only happen if an exclusive lock is held on the database file.
  49008. ** It is cleared (set to false) whenever an exclusive lock is
  49009. ** relinquished on the database file. Each time a transaction is committed,
  49010. ** The changeCountDone flag is inspected. If it is true, the work of
  49011. ** updating the change-counter is omitted for the current transaction.
  49012. **
  49013. ** This mechanism means that when running in exclusive mode, a connection
  49014. ** need only update the change-counter once, for the first transaction
  49015. ** committed.
  49016. **
  49017. ** setMaster
  49018. **
  49019. ** When PagerCommitPhaseOne() is called to commit a transaction, it may
  49020. ** (or may not) specify a master-journal name to be written into the
  49021. ** journal file before it is synced to disk.
  49022. **
  49023. ** Whether or not a journal file contains a master-journal pointer affects
  49024. ** the way in which the journal file is finalized after the transaction is
  49025. ** committed or rolled back when running in "journal_mode=PERSIST" mode.
  49026. ** If a journal file does not contain a master-journal pointer, it is
  49027. ** finalized by overwriting the first journal header with zeroes. If
  49028. ** it does contain a master-journal pointer the journal file is finalized
  49029. ** by truncating it to zero bytes, just as if the connection were
  49030. ** running in "journal_mode=truncate" mode.
  49031. **
  49032. ** Journal files that contain master journal pointers cannot be finalized
  49033. ** simply by overwriting the first journal-header with zeroes, as the
  49034. ** master journal pointer could interfere with hot-journal rollback of any
  49035. ** subsequently interrupted transaction that reuses the journal file.
  49036. **
  49037. ** The flag is cleared as soon as the journal file is finalized (either
  49038. ** by PagerCommitPhaseTwo or PagerRollback). If an IO error prevents the
  49039. ** journal file from being successfully finalized, the setMaster flag
  49040. ** is cleared anyway (and the pager will move to ERROR state).
  49041. **
  49042. ** doNotSpill
  49043. **
  49044. ** This variables control the behavior of cache-spills (calls made by
  49045. ** the pcache module to the pagerStress() routine to write cached data
  49046. ** to the file-system in order to free up memory).
  49047. **
  49048. ** When bits SPILLFLAG_OFF or SPILLFLAG_ROLLBACK of doNotSpill are set,
  49049. ** writing to the database from pagerStress() is disabled altogether.
  49050. ** The SPILLFLAG_ROLLBACK case is done in a very obscure case that
  49051. ** comes up during savepoint rollback that requires the pcache module
  49052. ** to allocate a new page to prevent the journal file from being written
  49053. ** while it is being traversed by code in pager_playback(). The SPILLFLAG_OFF
  49054. ** case is a user preference.
  49055. **
  49056. ** If the SPILLFLAG_NOSYNC bit is set, writing to the database from
  49057. ** pagerStress() is permitted, but syncing the journal file is not.
  49058. ** This flag is set by sqlite3PagerWrite() when the file-system sector-size
  49059. ** is larger than the database page-size in order to prevent a journal sync
  49060. ** from happening in between the journalling of two pages on the same sector.
  49061. **
  49062. ** subjInMemory
  49063. **
  49064. ** This is a boolean variable. If true, then any required sub-journal
  49065. ** is opened as an in-memory journal file. If false, then in-memory
  49066. ** sub-journals are only used for in-memory pager files.
  49067. **
  49068. ** This variable is updated by the upper layer each time a new
  49069. ** write-transaction is opened.
  49070. **
  49071. ** dbSize, dbOrigSize, dbFileSize
  49072. **
  49073. ** Variable dbSize is set to the number of pages in the database file.
  49074. ** It is valid in PAGER_READER and higher states (all states except for
  49075. ** OPEN and ERROR).
  49076. **
  49077. ** dbSize is set based on the size of the database file, which may be
  49078. ** larger than the size of the database (the value stored at offset
  49079. ** 28 of the database header by the btree). If the size of the file
  49080. ** is not an integer multiple of the page-size, the value stored in
  49081. ** dbSize is rounded down (i.e. a 5KB file with 2K page-size has dbSize==2).
  49082. ** Except, any file that is greater than 0 bytes in size is considered
  49083. ** to have at least one page. (i.e. a 1KB file with 2K page-size leads
  49084. ** to dbSize==1).
  49085. **
  49086. ** During a write-transaction, if pages with page-numbers greater than
  49087. ** dbSize are modified in the cache, dbSize is updated accordingly.
  49088. ** Similarly, if the database is truncated using PagerTruncateImage(),
  49089. ** dbSize is updated.
  49090. **
  49091. ** Variables dbOrigSize and dbFileSize are valid in states
  49092. ** PAGER_WRITER_LOCKED and higher. dbOrigSize is a copy of the dbSize
  49093. ** variable at the start of the transaction. It is used during rollback,
  49094. ** and to determine whether or not pages need to be journalled before
  49095. ** being modified.
  49096. **
  49097. ** Throughout a write-transaction, dbFileSize contains the size of
  49098. ** the file on disk in pages. It is set to a copy of dbSize when the
  49099. ** write-transaction is first opened, and updated when VFS calls are made
  49100. ** to write or truncate the database file on disk.
  49101. **
  49102. ** The only reason the dbFileSize variable is required is to suppress
  49103. ** unnecessary calls to xTruncate() after committing a transaction. If,
  49104. ** when a transaction is committed, the dbFileSize variable indicates
  49105. ** that the database file is larger than the database image (Pager.dbSize),
  49106. ** pager_truncate() is called. The pager_truncate() call uses xFilesize()
  49107. ** to measure the database file on disk, and then truncates it if required.
  49108. ** dbFileSize is not used when rolling back a transaction. In this case
  49109. ** pager_truncate() is called unconditionally (which means there may be
  49110. ** a call to xFilesize() that is not strictly required). In either case,
  49111. ** pager_truncate() may cause the file to become smaller or larger.
  49112. **
  49113. ** dbHintSize
  49114. **
  49115. ** The dbHintSize variable is used to limit the number of calls made to
  49116. ** the VFS xFileControl(FCNTL_SIZE_HINT) method.
  49117. **
  49118. ** dbHintSize is set to a copy of the dbSize variable when a
  49119. ** write-transaction is opened (at the same time as dbFileSize and
  49120. ** dbOrigSize). If the xFileControl(FCNTL_SIZE_HINT) method is called,
  49121. ** dbHintSize is increased to the number of pages that correspond to the
  49122. ** size-hint passed to the method call. See pager_write_pagelist() for
  49123. ** details.
  49124. **
  49125. ** errCode
  49126. **
  49127. ** The Pager.errCode variable is only ever used in PAGER_ERROR state. It
  49128. ** is set to zero in all other states. In PAGER_ERROR state, Pager.errCode
  49129. ** is always set to SQLITE_FULL, SQLITE_IOERR or one of the SQLITE_IOERR_XXX
  49130. ** sub-codes.
  49131. **
  49132. ** syncFlags, walSyncFlags
  49133. **
  49134. ** syncFlags is either SQLITE_SYNC_NORMAL (0x02) or SQLITE_SYNC_FULL (0x03).
  49135. ** syncFlags is used for rollback mode. walSyncFlags is used for WAL mode
  49136. ** and contains the flags used to sync the checkpoint operations in the
  49137. ** lower two bits, and sync flags used for transaction commits in the WAL
  49138. ** file in bits 0x04 and 0x08. In other words, to get the correct sync flags
  49139. ** for checkpoint operations, use (walSyncFlags&0x03) and to get the correct
  49140. ** sync flags for transaction commit, use ((walSyncFlags>>2)&0x03). Note
  49141. ** that with synchronous=NORMAL in WAL mode, transaction commit is not synced
  49142. ** meaning that the 0x04 and 0x08 bits are both zero.
  49143. */
  49144. struct Pager {
  49145. sqlite3_vfs *pVfs; /* OS functions to use for IO */
  49146. u8 exclusiveMode; /* Boolean. True if locking_mode==EXCLUSIVE */
  49147. u8 journalMode; /* One of the PAGER_JOURNALMODE_* values */
  49148. u8 useJournal; /* Use a rollback journal on this file */
  49149. u8 noSync; /* Do not sync the journal if true */
  49150. u8 fullSync; /* Do extra syncs of the journal for robustness */
  49151. u8 extraSync; /* sync directory after journal delete */
  49152. u8 syncFlags; /* SYNC_NORMAL or SYNC_FULL otherwise */
  49153. u8 walSyncFlags; /* See description above */
  49154. u8 tempFile; /* zFilename is a temporary or immutable file */
  49155. u8 noLock; /* Do not lock (except in WAL mode) */
  49156. u8 readOnly; /* True for a read-only database */
  49157. u8 memDb; /* True to inhibit all file I/O */
  49158. /**************************************************************************
  49159. ** The following block contains those class members that change during
  49160. ** routine operation. Class members not in this block are either fixed
  49161. ** when the pager is first created or else only change when there is a
  49162. ** significant mode change (such as changing the page_size, locking_mode,
  49163. ** or the journal_mode). From another view, these class members describe
  49164. ** the "state" of the pager, while other class members describe the
  49165. ** "configuration" of the pager.
  49166. */
  49167. u8 eState; /* Pager state (OPEN, READER, WRITER_LOCKED..) */
  49168. u8 eLock; /* Current lock held on database file */
  49169. u8 changeCountDone; /* Set after incrementing the change-counter */
  49170. u8 setMaster; /* True if a m-j name has been written to jrnl */
  49171. u8 doNotSpill; /* Do not spill the cache when non-zero */
  49172. u8 subjInMemory; /* True to use in-memory sub-journals */
  49173. u8 bUseFetch; /* True to use xFetch() */
  49174. u8 hasHeldSharedLock; /* True if a shared lock has ever been held */
  49175. Pgno dbSize; /* Number of pages in the database */
  49176. Pgno dbOrigSize; /* dbSize before the current transaction */
  49177. Pgno dbFileSize; /* Number of pages in the database file */
  49178. Pgno dbHintSize; /* Value passed to FCNTL_SIZE_HINT call */
  49179. int errCode; /* One of several kinds of errors */
  49180. int nRec; /* Pages journalled since last j-header written */
  49181. u32 cksumInit; /* Quasi-random value added to every checksum */
  49182. u32 nSubRec; /* Number of records written to sub-journal */
  49183. Bitvec *pInJournal; /* One bit for each page in the database file */
  49184. sqlite3_file *fd; /* File descriptor for database */
  49185. sqlite3_file *jfd; /* File descriptor for main journal */
  49186. sqlite3_file *sjfd; /* File descriptor for sub-journal */
  49187. i64 journalOff; /* Current write offset in the journal file */
  49188. i64 journalHdr; /* Byte offset to previous journal header */
  49189. sqlite3_backup *pBackup; /* Pointer to list of ongoing backup processes */
  49190. PagerSavepoint *aSavepoint; /* Array of active savepoints */
  49191. int nSavepoint; /* Number of elements in aSavepoint[] */
  49192. u32 iDataVersion; /* Changes whenever database content changes */
  49193. char dbFileVers[16]; /* Changes whenever database file changes */
  49194. int nMmapOut; /* Number of mmap pages currently outstanding */
  49195. sqlite3_int64 szMmap; /* Desired maximum mmap size */
  49196. PgHdr *pMmapFreelist; /* List of free mmap page headers (pDirty) */
  49197. /*
  49198. ** End of the routinely-changing class members
  49199. ***************************************************************************/
  49200. u16 nExtra; /* Add this many bytes to each in-memory page */
  49201. i16 nReserve; /* Number of unused bytes at end of each page */
  49202. u32 vfsFlags; /* Flags for sqlite3_vfs.xOpen() */
  49203. u32 sectorSize; /* Assumed sector size during rollback */
  49204. int pageSize; /* Number of bytes in a page */
  49205. Pgno mxPgno; /* Maximum allowed size of the database */
  49206. i64 journalSizeLimit; /* Size limit for persistent journal files */
  49207. char *zFilename; /* Name of the database file */
  49208. char *zJournal; /* Name of the journal file */
  49209. int (*xBusyHandler)(void*); /* Function to call when busy */
  49210. void *pBusyHandlerArg; /* Context argument for xBusyHandler */
  49211. int aStat[4]; /* Total cache hits, misses, writes, spills */
  49212. #ifdef SQLITE_TEST
  49213. int nRead; /* Database pages read */
  49214. #endif
  49215. void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
  49216. int (*xGet)(Pager*,Pgno,DbPage**,int); /* Routine to fetch a patch */
  49217. char *pTmpSpace; /* Pager.pageSize bytes of space for tmp use */
  49218. PCache *pPCache; /* Pointer to page cache object */
  49219. #ifndef SQLITE_OMIT_WAL
  49220. Wal *pWal; /* Write-ahead log used by "journal_mode=wal" */
  49221. char *zWal; /* File name for write-ahead log */
  49222. #endif
  49223. };
  49224. /*
  49225. ** Indexes for use with Pager.aStat[]. The Pager.aStat[] array contains
  49226. ** the values accessed by passing SQLITE_DBSTATUS_CACHE_HIT, CACHE_MISS
  49227. ** or CACHE_WRITE to sqlite3_db_status().
  49228. */
  49229. #define PAGER_STAT_HIT 0
  49230. #define PAGER_STAT_MISS 1
  49231. #define PAGER_STAT_WRITE 2
  49232. #define PAGER_STAT_SPILL 3
  49233. /*
  49234. ** The following global variables hold counters used for
  49235. ** testing purposes only. These variables do not exist in
  49236. ** a non-testing build. These variables are not thread-safe.
  49237. */
  49238. #ifdef SQLITE_TEST
  49239. SQLITE_API int sqlite3_pager_readdb_count = 0; /* Number of full pages read from DB */
  49240. SQLITE_API int sqlite3_pager_writedb_count = 0; /* Number of full pages written to DB */
  49241. SQLITE_API int sqlite3_pager_writej_count = 0; /* Number of pages written to journal */
  49242. # define PAGER_INCR(v) v++
  49243. #else
  49244. # define PAGER_INCR(v)
  49245. #endif
  49246. /*
  49247. ** Journal files begin with the following magic string. The data
  49248. ** was obtained from /dev/random. It is used only as a sanity check.
  49249. **
  49250. ** Since version 2.8.0, the journal format contains additional sanity
  49251. ** checking information. If the power fails while the journal is being
  49252. ** written, semi-random garbage data might appear in the journal
  49253. ** file after power is restored. If an attempt is then made
  49254. ** to roll the journal back, the database could be corrupted. The additional
  49255. ** sanity checking data is an attempt to discover the garbage in the
  49256. ** journal and ignore it.
  49257. **
  49258. ** The sanity checking information for the new journal format consists
  49259. ** of a 32-bit checksum on each page of data. The checksum covers both
  49260. ** the page number and the pPager->pageSize bytes of data for the page.
  49261. ** This cksum is initialized to a 32-bit random value that appears in the
  49262. ** journal file right after the header. The random initializer is important,
  49263. ** because garbage data that appears at the end of a journal is likely
  49264. ** data that was once in other files that have now been deleted. If the
  49265. ** garbage data came from an obsolete journal file, the checksums might
  49266. ** be correct. But by initializing the checksum to random value which
  49267. ** is different for every journal, we minimize that risk.
  49268. */
  49269. static const unsigned char aJournalMagic[] = {
  49270. 0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
  49271. };
  49272. /*
  49273. ** The size of the of each page record in the journal is given by
  49274. ** the following macro.
  49275. */
  49276. #define JOURNAL_PG_SZ(pPager) ((pPager->pageSize) + 8)
  49277. /*
  49278. ** The journal header size for this pager. This is usually the same
  49279. ** size as a single disk sector. See also setSectorSize().
  49280. */
  49281. #define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
  49282. /*
  49283. ** The macro MEMDB is true if we are dealing with an in-memory database.
  49284. ** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
  49285. ** the value of MEMDB will be a constant and the compiler will optimize
  49286. ** out code that would never execute.
  49287. */
  49288. #ifdef SQLITE_OMIT_MEMORYDB
  49289. # define MEMDB 0
  49290. #else
  49291. # define MEMDB pPager->memDb
  49292. #endif
  49293. /*
  49294. ** The macro USEFETCH is true if we are allowed to use the xFetch and xUnfetch
  49295. ** interfaces to access the database using memory-mapped I/O.
  49296. */
  49297. #if SQLITE_MAX_MMAP_SIZE>0
  49298. # define USEFETCH(x) ((x)->bUseFetch)
  49299. #else
  49300. # define USEFETCH(x) 0
  49301. #endif
  49302. /*
  49303. ** The maximum legal page number is (2^31 - 1).
  49304. */
  49305. #define PAGER_MAX_PGNO 2147483647
  49306. /*
  49307. ** The argument to this macro is a file descriptor (type sqlite3_file*).
  49308. ** Return 0 if it is not open, or non-zero (but not 1) if it is.
  49309. **
  49310. ** This is so that expressions can be written as:
  49311. **
  49312. ** if( isOpen(pPager->jfd) ){ ...
  49313. **
  49314. ** instead of
  49315. **
  49316. ** if( pPager->jfd->pMethods ){ ...
  49317. */
  49318. #define isOpen(pFd) ((pFd)->pMethods!=0)
  49319. #ifdef SQLITE_DIRECT_OVERFLOW_READ
  49320. /*
  49321. ** Return true if page pgno can be read directly from the database file
  49322. ** by the b-tree layer. This is the case if:
  49323. **
  49324. ** * the database file is open,
  49325. ** * there are no dirty pages in the cache, and
  49326. ** * the desired page is not currently in the wal file.
  49327. */
  49328. SQLITE_PRIVATE int sqlite3PagerDirectReadOk(Pager *pPager, Pgno pgno){
  49329. if( pPager->fd->pMethods==0 ) return 0;
  49330. if( sqlite3PCacheIsDirty(pPager->pPCache) ) return 0;
  49331. #ifndef SQLITE_OMIT_WAL
  49332. if( pPager->pWal ){
  49333. u32 iRead = 0;
  49334. int rc;
  49335. rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iRead);
  49336. return (rc==SQLITE_OK && iRead==0);
  49337. }
  49338. #endif
  49339. return 1;
  49340. }
  49341. #endif
  49342. #ifndef SQLITE_OMIT_WAL
  49343. # define pagerUseWal(x) ((x)->pWal!=0)
  49344. #else
  49345. # define pagerUseWal(x) 0
  49346. # define pagerRollbackWal(x) 0
  49347. # define pagerWalFrames(v,w,x,y) 0
  49348. # define pagerOpenWalIfPresent(z) SQLITE_OK
  49349. # define pagerBeginReadTransaction(z) SQLITE_OK
  49350. #endif
  49351. #ifndef NDEBUG
  49352. /*
  49353. ** Usage:
  49354. **
  49355. ** assert( assert_pager_state(pPager) );
  49356. **
  49357. ** This function runs many asserts to try to find inconsistencies in
  49358. ** the internal state of the Pager object.
  49359. */
  49360. static int assert_pager_state(Pager *p){
  49361. Pager *pPager = p;
  49362. /* State must be valid. */
  49363. assert( p->eState==PAGER_OPEN
  49364. || p->eState==PAGER_READER
  49365. || p->eState==PAGER_WRITER_LOCKED
  49366. || p->eState==PAGER_WRITER_CACHEMOD
  49367. || p->eState==PAGER_WRITER_DBMOD
  49368. || p->eState==PAGER_WRITER_FINISHED
  49369. || p->eState==PAGER_ERROR
  49370. );
  49371. /* Regardless of the current state, a temp-file connection always behaves
  49372. ** as if it has an exclusive lock on the database file. It never updates
  49373. ** the change-counter field, so the changeCountDone flag is always set.
  49374. */
  49375. assert( p->tempFile==0 || p->eLock==EXCLUSIVE_LOCK );
  49376. assert( p->tempFile==0 || pPager->changeCountDone );
  49377. /* If the useJournal flag is clear, the journal-mode must be "OFF".
  49378. ** And if the journal-mode is "OFF", the journal file must not be open.
  49379. */
  49380. assert( p->journalMode==PAGER_JOURNALMODE_OFF || p->useJournal );
  49381. assert( p->journalMode!=PAGER_JOURNALMODE_OFF || !isOpen(p->jfd) );
  49382. /* Check that MEMDB implies noSync. And an in-memory journal. Since
  49383. ** this means an in-memory pager performs no IO at all, it cannot encounter
  49384. ** either SQLITE_IOERR or SQLITE_FULL during rollback or while finalizing
  49385. ** a journal file. (although the in-memory journal implementation may
  49386. ** return SQLITE_IOERR_NOMEM while the journal file is being written). It
  49387. ** is therefore not possible for an in-memory pager to enter the ERROR
  49388. ** state.
  49389. */
  49390. if( MEMDB ){
  49391. assert( !isOpen(p->fd) );
  49392. assert( p->noSync );
  49393. assert( p->journalMode==PAGER_JOURNALMODE_OFF
  49394. || p->journalMode==PAGER_JOURNALMODE_MEMORY
  49395. );
  49396. assert( p->eState!=PAGER_ERROR && p->eState!=PAGER_OPEN );
  49397. assert( pagerUseWal(p)==0 );
  49398. }
  49399. /* If changeCountDone is set, a RESERVED lock or greater must be held
  49400. ** on the file.
  49401. */
  49402. assert( pPager->changeCountDone==0 || pPager->eLock>=RESERVED_LOCK );
  49403. assert( p->eLock!=PENDING_LOCK );
  49404. switch( p->eState ){
  49405. case PAGER_OPEN:
  49406. assert( !MEMDB );
  49407. assert( pPager->errCode==SQLITE_OK );
  49408. assert( sqlite3PcacheRefCount(pPager->pPCache)==0 || pPager->tempFile );
  49409. break;
  49410. case PAGER_READER:
  49411. assert( pPager->errCode==SQLITE_OK );
  49412. assert( p->eLock!=UNKNOWN_LOCK );
  49413. assert( p->eLock>=SHARED_LOCK );
  49414. break;
  49415. case PAGER_WRITER_LOCKED:
  49416. assert( p->eLock!=UNKNOWN_LOCK );
  49417. assert( pPager->errCode==SQLITE_OK );
  49418. if( !pagerUseWal(pPager) ){
  49419. assert( p->eLock>=RESERVED_LOCK );
  49420. }
  49421. assert( pPager->dbSize==pPager->dbOrigSize );
  49422. assert( pPager->dbOrigSize==pPager->dbFileSize );
  49423. assert( pPager->dbOrigSize==pPager->dbHintSize );
  49424. assert( pPager->setMaster==0 );
  49425. break;
  49426. case PAGER_WRITER_CACHEMOD:
  49427. assert( p->eLock!=UNKNOWN_LOCK );
  49428. assert( pPager->errCode==SQLITE_OK );
  49429. if( !pagerUseWal(pPager) ){
  49430. /* It is possible that if journal_mode=wal here that neither the
  49431. ** journal file nor the WAL file are open. This happens during
  49432. ** a rollback transaction that switches from journal_mode=off
  49433. ** to journal_mode=wal.
  49434. */
  49435. assert( p->eLock>=RESERVED_LOCK );
  49436. assert( isOpen(p->jfd)
  49437. || p->journalMode==PAGER_JOURNALMODE_OFF
  49438. || p->journalMode==PAGER_JOURNALMODE_WAL
  49439. );
  49440. }
  49441. assert( pPager->dbOrigSize==pPager->dbFileSize );
  49442. assert( pPager->dbOrigSize==pPager->dbHintSize );
  49443. break;
  49444. case PAGER_WRITER_DBMOD:
  49445. assert( p->eLock==EXCLUSIVE_LOCK );
  49446. assert( pPager->errCode==SQLITE_OK );
  49447. assert( !pagerUseWal(pPager) );
  49448. assert( p->eLock>=EXCLUSIVE_LOCK );
  49449. assert( isOpen(p->jfd)
  49450. || p->journalMode==PAGER_JOURNALMODE_OFF
  49451. || p->journalMode==PAGER_JOURNALMODE_WAL
  49452. || (sqlite3OsDeviceCharacteristics(p->fd)&SQLITE_IOCAP_BATCH_ATOMIC)
  49453. );
  49454. assert( pPager->dbOrigSize<=pPager->dbHintSize );
  49455. break;
  49456. case PAGER_WRITER_FINISHED:
  49457. assert( p->eLock==EXCLUSIVE_LOCK );
  49458. assert( pPager->errCode==SQLITE_OK );
  49459. assert( !pagerUseWal(pPager) );
  49460. assert( isOpen(p->jfd)
  49461. || p->journalMode==PAGER_JOURNALMODE_OFF
  49462. || p->journalMode==PAGER_JOURNALMODE_WAL
  49463. || (sqlite3OsDeviceCharacteristics(p->fd)&SQLITE_IOCAP_BATCH_ATOMIC)
  49464. );
  49465. break;
  49466. case PAGER_ERROR:
  49467. /* There must be at least one outstanding reference to the pager if
  49468. ** in ERROR state. Otherwise the pager should have already dropped
  49469. ** back to OPEN state.
  49470. */
  49471. assert( pPager->errCode!=SQLITE_OK );
  49472. assert( sqlite3PcacheRefCount(pPager->pPCache)>0 || pPager->tempFile );
  49473. break;
  49474. }
  49475. return 1;
  49476. }
  49477. #endif /* ifndef NDEBUG */
  49478. #ifdef SQLITE_DEBUG
  49479. /*
  49480. ** Return a pointer to a human readable string in a static buffer
  49481. ** containing the state of the Pager object passed as an argument. This
  49482. ** is intended to be used within debuggers. For example, as an alternative
  49483. ** to "print *pPager" in gdb:
  49484. **
  49485. ** (gdb) printf "%s", print_pager_state(pPager)
  49486. **
  49487. ** This routine has external linkage in order to suppress compiler warnings
  49488. ** about an unused function. It is enclosed within SQLITE_DEBUG and so does
  49489. ** not appear in normal builds.
  49490. */
  49491. char *print_pager_state(Pager *p){
  49492. static char zRet[1024];
  49493. sqlite3_snprintf(1024, zRet,
  49494. "Filename: %s\n"
  49495. "State: %s errCode=%d\n"
  49496. "Lock: %s\n"
  49497. "Locking mode: locking_mode=%s\n"
  49498. "Journal mode: journal_mode=%s\n"
  49499. "Backing store: tempFile=%d memDb=%d useJournal=%d\n"
  49500. "Journal: journalOff=%lld journalHdr=%lld\n"
  49501. "Size: dbsize=%d dbOrigSize=%d dbFileSize=%d\n"
  49502. , p->zFilename
  49503. , p->eState==PAGER_OPEN ? "OPEN" :
  49504. p->eState==PAGER_READER ? "READER" :
  49505. p->eState==PAGER_WRITER_LOCKED ? "WRITER_LOCKED" :
  49506. p->eState==PAGER_WRITER_CACHEMOD ? "WRITER_CACHEMOD" :
  49507. p->eState==PAGER_WRITER_DBMOD ? "WRITER_DBMOD" :
  49508. p->eState==PAGER_WRITER_FINISHED ? "WRITER_FINISHED" :
  49509. p->eState==PAGER_ERROR ? "ERROR" : "?error?"
  49510. , (int)p->errCode
  49511. , p->eLock==NO_LOCK ? "NO_LOCK" :
  49512. p->eLock==RESERVED_LOCK ? "RESERVED" :
  49513. p->eLock==EXCLUSIVE_LOCK ? "EXCLUSIVE" :
  49514. p->eLock==SHARED_LOCK ? "SHARED" :
  49515. p->eLock==UNKNOWN_LOCK ? "UNKNOWN" : "?error?"
  49516. , p->exclusiveMode ? "exclusive" : "normal"
  49517. , p->journalMode==PAGER_JOURNALMODE_MEMORY ? "memory" :
  49518. p->journalMode==PAGER_JOURNALMODE_OFF ? "off" :
  49519. p->journalMode==PAGER_JOURNALMODE_DELETE ? "delete" :
  49520. p->journalMode==PAGER_JOURNALMODE_PERSIST ? "persist" :
  49521. p->journalMode==PAGER_JOURNALMODE_TRUNCATE ? "truncate" :
  49522. p->journalMode==PAGER_JOURNALMODE_WAL ? "wal" : "?error?"
  49523. , (int)p->tempFile, (int)p->memDb, (int)p->useJournal
  49524. , p->journalOff, p->journalHdr
  49525. , (int)p->dbSize, (int)p->dbOrigSize, (int)p->dbFileSize
  49526. );
  49527. return zRet;
  49528. }
  49529. #endif
  49530. /* Forward references to the various page getters */
  49531. static int getPageNormal(Pager*,Pgno,DbPage**,int);
  49532. static int getPageError(Pager*,Pgno,DbPage**,int);
  49533. #if SQLITE_MAX_MMAP_SIZE>0
  49534. static int getPageMMap(Pager*,Pgno,DbPage**,int);
  49535. #endif
  49536. /*
  49537. ** Set the Pager.xGet method for the appropriate routine used to fetch
  49538. ** content from the pager.
  49539. */
  49540. static void setGetterMethod(Pager *pPager){
  49541. if( pPager->errCode ){
  49542. pPager->xGet = getPageError;
  49543. #if SQLITE_MAX_MMAP_SIZE>0
  49544. }else if( USEFETCH(pPager) ){
  49545. pPager->xGet = getPageMMap;
  49546. #endif /* SQLITE_MAX_MMAP_SIZE>0 */
  49547. }else{
  49548. pPager->xGet = getPageNormal;
  49549. }
  49550. }
  49551. /*
  49552. ** Return true if it is necessary to write page *pPg into the sub-journal.
  49553. ** A page needs to be written into the sub-journal if there exists one
  49554. ** or more open savepoints for which:
  49555. **
  49556. ** * The page-number is less than or equal to PagerSavepoint.nOrig, and
  49557. ** * The bit corresponding to the page-number is not set in
  49558. ** PagerSavepoint.pInSavepoint.
  49559. */
  49560. static int subjRequiresPage(PgHdr *pPg){
  49561. Pager *pPager = pPg->pPager;
  49562. PagerSavepoint *p;
  49563. Pgno pgno = pPg->pgno;
  49564. int i;
  49565. for(i=0; i<pPager->nSavepoint; i++){
  49566. p = &pPager->aSavepoint[i];
  49567. if( p->nOrig>=pgno && 0==sqlite3BitvecTestNotNull(p->pInSavepoint, pgno) ){
  49568. return 1;
  49569. }
  49570. }
  49571. return 0;
  49572. }
  49573. #ifdef SQLITE_DEBUG
  49574. /*
  49575. ** Return true if the page is already in the journal file.
  49576. */
  49577. static int pageInJournal(Pager *pPager, PgHdr *pPg){
  49578. return sqlite3BitvecTest(pPager->pInJournal, pPg->pgno);
  49579. }
  49580. #endif
  49581. /*
  49582. ** Read a 32-bit integer from the given file descriptor. Store the integer
  49583. ** that is read in *pRes. Return SQLITE_OK if everything worked, or an
  49584. ** error code is something goes wrong.
  49585. **
  49586. ** All values are stored on disk as big-endian.
  49587. */
  49588. static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
  49589. unsigned char ac[4];
  49590. int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
  49591. if( rc==SQLITE_OK ){
  49592. *pRes = sqlite3Get4byte(ac);
  49593. }
  49594. return rc;
  49595. }
  49596. /*
  49597. ** Write a 32-bit integer into a string buffer in big-endian byte order.
  49598. */
  49599. #define put32bits(A,B) sqlite3Put4byte((u8*)A,B)
  49600. /*
  49601. ** Write a 32-bit integer into the given file descriptor. Return SQLITE_OK
  49602. ** on success or an error code is something goes wrong.
  49603. */
  49604. static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
  49605. char ac[4];
  49606. put32bits(ac, val);
  49607. return sqlite3OsWrite(fd, ac, 4, offset);
  49608. }
  49609. /*
  49610. ** Unlock the database file to level eLock, which must be either NO_LOCK
  49611. ** or SHARED_LOCK. Regardless of whether or not the call to xUnlock()
  49612. ** succeeds, set the Pager.eLock variable to match the (attempted) new lock.
  49613. **
  49614. ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
  49615. ** called, do not modify it. See the comment above the #define of
  49616. ** UNKNOWN_LOCK for an explanation of this.
  49617. */
  49618. static int pagerUnlockDb(Pager *pPager, int eLock){
  49619. int rc = SQLITE_OK;
  49620. assert( !pPager->exclusiveMode || pPager->eLock==eLock );
  49621. assert( eLock==NO_LOCK || eLock==SHARED_LOCK );
  49622. assert( eLock!=NO_LOCK || pagerUseWal(pPager)==0 );
  49623. if( isOpen(pPager->fd) ){
  49624. assert( pPager->eLock>=eLock );
  49625. rc = pPager->noLock ? SQLITE_OK : sqlite3OsUnlock(pPager->fd, eLock);
  49626. if( pPager->eLock!=UNKNOWN_LOCK ){
  49627. pPager->eLock = (u8)eLock;
  49628. }
  49629. IOTRACE(("UNLOCK %p %d\n", pPager, eLock))
  49630. }
  49631. pPager->changeCountDone = pPager->tempFile; /* ticket fb3b3024ea238d5c */
  49632. return rc;
  49633. }
  49634. /*
  49635. ** Lock the database file to level eLock, which must be either SHARED_LOCK,
  49636. ** RESERVED_LOCK or EXCLUSIVE_LOCK. If the caller is successful, set the
  49637. ** Pager.eLock variable to the new locking state.
  49638. **
  49639. ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
  49640. ** called, do not modify it unless the new locking state is EXCLUSIVE_LOCK.
  49641. ** See the comment above the #define of UNKNOWN_LOCK for an explanation
  49642. ** of this.
  49643. */
  49644. static int pagerLockDb(Pager *pPager, int eLock){
  49645. int rc = SQLITE_OK;
  49646. assert( eLock==SHARED_LOCK || eLock==RESERVED_LOCK || eLock==EXCLUSIVE_LOCK );
  49647. if( pPager->eLock<eLock || pPager->eLock==UNKNOWN_LOCK ){
  49648. rc = pPager->noLock ? SQLITE_OK : sqlite3OsLock(pPager->fd, eLock);
  49649. if( rc==SQLITE_OK && (pPager->eLock!=UNKNOWN_LOCK||eLock==EXCLUSIVE_LOCK) ){
  49650. pPager->eLock = (u8)eLock;
  49651. IOTRACE(("LOCK %p %d\n", pPager, eLock))
  49652. }
  49653. }
  49654. return rc;
  49655. }
  49656. /*
  49657. ** This function determines whether or not the atomic-write or
  49658. ** atomic-batch-write optimizations can be used with this pager. The
  49659. ** atomic-write optimization can be used if:
  49660. **
  49661. ** (a) the value returned by OsDeviceCharacteristics() indicates that
  49662. ** a database page may be written atomically, and
  49663. ** (b) the value returned by OsSectorSize() is less than or equal
  49664. ** to the page size.
  49665. **
  49666. ** If it can be used, then the value returned is the size of the journal
  49667. ** file when it contains rollback data for exactly one page.
  49668. **
  49669. ** The atomic-batch-write optimization can be used if OsDeviceCharacteristics()
  49670. ** returns a value with the SQLITE_IOCAP_BATCH_ATOMIC bit set. -1 is
  49671. ** returned in this case.
  49672. **
  49673. ** If neither optimization can be used, 0 is returned.
  49674. */
  49675. static int jrnlBufferSize(Pager *pPager){
  49676. assert( !MEMDB );
  49677. #if defined(SQLITE_ENABLE_ATOMIC_WRITE) \
  49678. || defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
  49679. int dc; /* Device characteristics */
  49680. assert( isOpen(pPager->fd) );
  49681. dc = sqlite3OsDeviceCharacteristics(pPager->fd);
  49682. #else
  49683. UNUSED_PARAMETER(pPager);
  49684. #endif
  49685. #ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE
  49686. if( pPager->dbSize>0 && (dc&SQLITE_IOCAP_BATCH_ATOMIC) ){
  49687. return -1;
  49688. }
  49689. #endif
  49690. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  49691. {
  49692. int nSector = pPager->sectorSize;
  49693. int szPage = pPager->pageSize;
  49694. assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
  49695. assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
  49696. if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){
  49697. return 0;
  49698. }
  49699. }
  49700. return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
  49701. #endif
  49702. return 0;
  49703. }
  49704. /*
  49705. ** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
  49706. ** on the cache using a hash function. This is used for testing
  49707. ** and debugging only.
  49708. */
  49709. #ifdef SQLITE_CHECK_PAGES
  49710. /*
  49711. ** Return a 32-bit hash of the page data for pPage.
  49712. */
  49713. static u32 pager_datahash(int nByte, unsigned char *pData){
  49714. u32 hash = 0;
  49715. int i;
  49716. for(i=0; i<nByte; i++){
  49717. hash = (hash*1039) + pData[i];
  49718. }
  49719. return hash;
  49720. }
  49721. static u32 pager_pagehash(PgHdr *pPage){
  49722. return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
  49723. }
  49724. static void pager_set_pagehash(PgHdr *pPage){
  49725. pPage->pageHash = pager_pagehash(pPage);
  49726. }
  49727. /*
  49728. ** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
  49729. ** is defined, and NDEBUG is not defined, an assert() statement checks
  49730. ** that the page is either dirty or still matches the calculated page-hash.
  49731. */
  49732. #define CHECK_PAGE(x) checkPage(x)
  49733. static void checkPage(PgHdr *pPg){
  49734. Pager *pPager = pPg->pPager;
  49735. assert( pPager->eState!=PAGER_ERROR );
  49736. assert( (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
  49737. }
  49738. #else
  49739. #define pager_datahash(X,Y) 0
  49740. #define pager_pagehash(X) 0
  49741. #define pager_set_pagehash(X)
  49742. #define CHECK_PAGE(x)
  49743. #endif /* SQLITE_CHECK_PAGES */
  49744. /*
  49745. ** When this is called the journal file for pager pPager must be open.
  49746. ** This function attempts to read a master journal file name from the
  49747. ** end of the file and, if successful, copies it into memory supplied
  49748. ** by the caller. See comments above writeMasterJournal() for the format
  49749. ** used to store a master journal file name at the end of a journal file.
  49750. **
  49751. ** zMaster must point to a buffer of at least nMaster bytes allocated by
  49752. ** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
  49753. ** enough space to write the master journal name). If the master journal
  49754. ** name in the journal is longer than nMaster bytes (including a
  49755. ** nul-terminator), then this is handled as if no master journal name
  49756. ** were present in the journal.
  49757. **
  49758. ** If a master journal file name is present at the end of the journal
  49759. ** file, then it is copied into the buffer pointed to by zMaster. A
  49760. ** nul-terminator byte is appended to the buffer following the master
  49761. ** journal file name.
  49762. **
  49763. ** If it is determined that no master journal file name is present
  49764. ** zMaster[0] is set to 0 and SQLITE_OK returned.
  49765. **
  49766. ** If an error occurs while reading from the journal file, an SQLite
  49767. ** error code is returned.
  49768. */
  49769. static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){
  49770. int rc; /* Return code */
  49771. u32 len; /* Length in bytes of master journal name */
  49772. i64 szJ; /* Total size in bytes of journal file pJrnl */
  49773. u32 cksum; /* MJ checksum value read from journal */
  49774. u32 u; /* Unsigned loop counter */
  49775. unsigned char aMagic[8]; /* A buffer to hold the magic header */
  49776. zMaster[0] = '\0';
  49777. if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ))
  49778. || szJ<16
  49779. || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
  49780. || len>=nMaster
  49781. || len>szJ-16
  49782. || len==0
  49783. || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
  49784. || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
  49785. || memcmp(aMagic, aJournalMagic, 8)
  49786. || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len))
  49787. ){
  49788. return rc;
  49789. }
  49790. /* See if the checksum matches the master journal name */
  49791. for(u=0; u<len; u++){
  49792. cksum -= zMaster[u];
  49793. }
  49794. if( cksum ){
  49795. /* If the checksum doesn't add up, then one or more of the disk sectors
  49796. ** containing the master journal filename is corrupted. This means
  49797. ** definitely roll back, so just return SQLITE_OK and report a (nul)
  49798. ** master-journal filename.
  49799. */
  49800. len = 0;
  49801. }
  49802. zMaster[len] = '\0';
  49803. zMaster[len+1] = '\0';
  49804. return SQLITE_OK;
  49805. }
  49806. /*
  49807. ** Return the offset of the sector boundary at or immediately
  49808. ** following the value in pPager->journalOff, assuming a sector
  49809. ** size of pPager->sectorSize bytes.
  49810. **
  49811. ** i.e for a sector size of 512:
  49812. **
  49813. ** Pager.journalOff Return value
  49814. ** ---------------------------------------
  49815. ** 0 0
  49816. ** 512 512
  49817. ** 100 512
  49818. ** 2000 2048
  49819. **
  49820. */
  49821. static i64 journalHdrOffset(Pager *pPager){
  49822. i64 offset = 0;
  49823. i64 c = pPager->journalOff;
  49824. if( c ){
  49825. offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
  49826. }
  49827. assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
  49828. assert( offset>=c );
  49829. assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
  49830. return offset;
  49831. }
  49832. /*
  49833. ** The journal file must be open when this function is called.
  49834. **
  49835. ** This function is a no-op if the journal file has not been written to
  49836. ** within the current transaction (i.e. if Pager.journalOff==0).
  49837. **
  49838. ** If doTruncate is non-zero or the Pager.journalSizeLimit variable is
  49839. ** set to 0, then truncate the journal file to zero bytes in size. Otherwise,
  49840. ** zero the 28-byte header at the start of the journal file. In either case,
  49841. ** if the pager is not in no-sync mode, sync the journal file immediately
  49842. ** after writing or truncating it.
  49843. **
  49844. ** If Pager.journalSizeLimit is set to a positive, non-zero value, and
  49845. ** following the truncation or zeroing described above the size of the
  49846. ** journal file in bytes is larger than this value, then truncate the
  49847. ** journal file to Pager.journalSizeLimit bytes. The journal file does
  49848. ** not need to be synced following this operation.
  49849. **
  49850. ** If an IO error occurs, abandon processing and return the IO error code.
  49851. ** Otherwise, return SQLITE_OK.
  49852. */
  49853. static int zeroJournalHdr(Pager *pPager, int doTruncate){
  49854. int rc = SQLITE_OK; /* Return code */
  49855. assert( isOpen(pPager->jfd) );
  49856. assert( !sqlite3JournalIsInMemory(pPager->jfd) );
  49857. if( pPager->journalOff ){
  49858. const i64 iLimit = pPager->journalSizeLimit; /* Local cache of jsl */
  49859. IOTRACE(("JZEROHDR %p\n", pPager))
  49860. if( doTruncate || iLimit==0 ){
  49861. rc = sqlite3OsTruncate(pPager->jfd, 0);
  49862. }else{
  49863. static const char zeroHdr[28] = {0};
  49864. rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
  49865. }
  49866. if( rc==SQLITE_OK && !pPager->noSync ){
  49867. rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->syncFlags);
  49868. }
  49869. /* At this point the transaction is committed but the write lock
  49870. ** is still held on the file. If there is a size limit configured for
  49871. ** the persistent journal and the journal file currently consumes more
  49872. ** space than that limit allows for, truncate it now. There is no need
  49873. ** to sync the file following this operation.
  49874. */
  49875. if( rc==SQLITE_OK && iLimit>0 ){
  49876. i64 sz;
  49877. rc = sqlite3OsFileSize(pPager->jfd, &sz);
  49878. if( rc==SQLITE_OK && sz>iLimit ){
  49879. rc = sqlite3OsTruncate(pPager->jfd, iLimit);
  49880. }
  49881. }
  49882. }
  49883. return rc;
  49884. }
  49885. /*
  49886. ** The journal file must be open when this routine is called. A journal
  49887. ** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
  49888. ** current location.
  49889. **
  49890. ** The format for the journal header is as follows:
  49891. ** - 8 bytes: Magic identifying journal format.
  49892. ** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
  49893. ** - 4 bytes: Random number used for page hash.
  49894. ** - 4 bytes: Initial database page count.
  49895. ** - 4 bytes: Sector size used by the process that wrote this journal.
  49896. ** - 4 bytes: Database page size.
  49897. **
  49898. ** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
  49899. */
  49900. static int writeJournalHdr(Pager *pPager){
  49901. int rc = SQLITE_OK; /* Return code */
  49902. char *zHeader = pPager->pTmpSpace; /* Temporary space used to build header */
  49903. u32 nHeader = (u32)pPager->pageSize;/* Size of buffer pointed to by zHeader */
  49904. u32 nWrite; /* Bytes of header sector written */
  49905. int ii; /* Loop counter */
  49906. assert( isOpen(pPager->jfd) ); /* Journal file must be open. */
  49907. if( nHeader>JOURNAL_HDR_SZ(pPager) ){
  49908. nHeader = JOURNAL_HDR_SZ(pPager);
  49909. }
  49910. /* If there are active savepoints and any of them were created
  49911. ** since the most recent journal header was written, update the
  49912. ** PagerSavepoint.iHdrOffset fields now.
  49913. */
  49914. for(ii=0; ii<pPager->nSavepoint; ii++){
  49915. if( pPager->aSavepoint[ii].iHdrOffset==0 ){
  49916. pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;
  49917. }
  49918. }
  49919. pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);
  49920. /*
  49921. ** Write the nRec Field - the number of page records that follow this
  49922. ** journal header. Normally, zero is written to this value at this time.
  49923. ** After the records are added to the journal (and the journal synced,
  49924. ** if in full-sync mode), the zero is overwritten with the true number
  49925. ** of records (see syncJournal()).
  49926. **
  49927. ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
  49928. ** reading the journal this value tells SQLite to assume that the
  49929. ** rest of the journal file contains valid page records. This assumption
  49930. ** is dangerous, as if a failure occurred whilst writing to the journal
  49931. ** file it may contain some garbage data. There are two scenarios
  49932. ** where this risk can be ignored:
  49933. **
  49934. ** * When the pager is in no-sync mode. Corruption can follow a
  49935. ** power failure in this case anyway.
  49936. **
  49937. ** * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
  49938. ** that garbage data is never appended to the journal file.
  49939. */
  49940. assert( isOpen(pPager->fd) || pPager->noSync );
  49941. if( pPager->noSync || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
  49942. || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND)
  49943. ){
  49944. memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
  49945. put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
  49946. }else{
  49947. memset(zHeader, 0, sizeof(aJournalMagic)+4);
  49948. }
  49949. /* The random check-hash initializer */
  49950. sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
  49951. put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
  49952. /* The initial database size */
  49953. put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
  49954. /* The assumed sector size for this process */
  49955. put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
  49956. /* The page size */
  49957. put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
  49958. /* Initializing the tail of the buffer is not necessary. Everything
  49959. ** works find if the following memset() is omitted. But initializing
  49960. ** the memory prevents valgrind from complaining, so we are willing to
  49961. ** take the performance hit.
  49962. */
  49963. memset(&zHeader[sizeof(aJournalMagic)+20], 0,
  49964. nHeader-(sizeof(aJournalMagic)+20));
  49965. /* In theory, it is only necessary to write the 28 bytes that the
  49966. ** journal header consumes to the journal file here. Then increment the
  49967. ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next
  49968. ** record is written to the following sector (leaving a gap in the file
  49969. ** that will be implicitly filled in by the OS).
  49970. **
  49971. ** However it has been discovered that on some systems this pattern can
  49972. ** be significantly slower than contiguously writing data to the file,
  49973. ** even if that means explicitly writing data to the block of
  49974. ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what
  49975. ** is done.
  49976. **
  49977. ** The loop is required here in case the sector-size is larger than the
  49978. ** database page size. Since the zHeader buffer is only Pager.pageSize
  49979. ** bytes in size, more than one call to sqlite3OsWrite() may be required
  49980. ** to populate the entire journal header sector.
  49981. */
  49982. for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
  49983. IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
  49984. rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
  49985. assert( pPager->journalHdr <= pPager->journalOff );
  49986. pPager->journalOff += nHeader;
  49987. }
  49988. return rc;
  49989. }
  49990. /*
  49991. ** The journal file must be open when this is called. A journal header file
  49992. ** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
  49993. ** file. The current location in the journal file is given by
  49994. ** pPager->journalOff. See comments above function writeJournalHdr() for
  49995. ** a description of the journal header format.
  49996. **
  49997. ** If the header is read successfully, *pNRec is set to the number of
  49998. ** page records following this header and *pDbSize is set to the size of the
  49999. ** database before the transaction began, in pages. Also, pPager->cksumInit
  50000. ** is set to the value read from the journal header. SQLITE_OK is returned
  50001. ** in this case.
  50002. **
  50003. ** If the journal header file appears to be corrupted, SQLITE_DONE is
  50004. ** returned and *pNRec and *PDbSize are undefined. If JOURNAL_HDR_SZ bytes
  50005. ** cannot be read from the journal file an error code is returned.
  50006. */
  50007. static int readJournalHdr(
  50008. Pager *pPager, /* Pager object */
  50009. int isHot,
  50010. i64 journalSize, /* Size of the open journal file in bytes */
  50011. u32 *pNRec, /* OUT: Value read from the nRec field */
  50012. u32 *pDbSize /* OUT: Value of original database size field */
  50013. ){
  50014. int rc; /* Return code */
  50015. unsigned char aMagic[8]; /* A buffer to hold the magic header */
  50016. i64 iHdrOff; /* Offset of journal header being read */
  50017. assert( isOpen(pPager->jfd) ); /* Journal file must be open. */
  50018. /* Advance Pager.journalOff to the start of the next sector. If the
  50019. ** journal file is too small for there to be a header stored at this
  50020. ** point, return SQLITE_DONE.
  50021. */
  50022. pPager->journalOff = journalHdrOffset(pPager);
  50023. if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
  50024. return SQLITE_DONE;
  50025. }
  50026. iHdrOff = pPager->journalOff;
  50027. /* Read in the first 8 bytes of the journal header. If they do not match
  50028. ** the magic string found at the start of each journal header, return
  50029. ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise,
  50030. ** proceed.
  50031. */
  50032. if( isHot || iHdrOff!=pPager->journalHdr ){
  50033. rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff);
  50034. if( rc ){
  50035. return rc;
  50036. }
  50037. if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
  50038. return SQLITE_DONE;
  50039. }
  50040. }
  50041. /* Read the first three 32-bit fields of the journal header: The nRec
  50042. ** field, the checksum-initializer and the database size at the start
  50043. ** of the transaction. Return an error code if anything goes wrong.
  50044. */
  50045. if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec))
  50046. || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit))
  50047. || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize))
  50048. ){
  50049. return rc;
  50050. }
  50051. if( pPager->journalOff==0 ){
  50052. u32 iPageSize; /* Page-size field of journal header */
  50053. u32 iSectorSize; /* Sector-size field of journal header */
  50054. /* Read the page-size and sector-size journal header fields. */
  50055. if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))
  50056. || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize))
  50057. ){
  50058. return rc;
  50059. }
  50060. /* Versions of SQLite prior to 3.5.8 set the page-size field of the
  50061. ** journal header to zero. In this case, assume that the Pager.pageSize
  50062. ** variable is already set to the correct page size.
  50063. */
  50064. if( iPageSize==0 ){
  50065. iPageSize = pPager->pageSize;
  50066. }
  50067. /* Check that the values read from the page-size and sector-size fields
  50068. ** are within range. To be 'in range', both values need to be a power
  50069. ** of two greater than or equal to 512 or 32, and not greater than their
  50070. ** respective compile time maximum limits.
  50071. */
  50072. if( iPageSize<512 || iSectorSize<32
  50073. || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE
  50074. || ((iPageSize-1)&iPageSize)!=0 || ((iSectorSize-1)&iSectorSize)!=0
  50075. ){
  50076. /* If the either the page-size or sector-size in the journal-header is
  50077. ** invalid, then the process that wrote the journal-header must have
  50078. ** crashed before the header was synced. In this case stop reading
  50079. ** the journal file here.
  50080. */
  50081. return SQLITE_DONE;
  50082. }
  50083. /* Update the page-size to match the value read from the journal.
  50084. ** Use a testcase() macro to make sure that malloc failure within
  50085. ** PagerSetPagesize() is tested.
  50086. */
  50087. rc = sqlite3PagerSetPagesize(pPager, &iPageSize, -1);
  50088. testcase( rc!=SQLITE_OK );
  50089. /* Update the assumed sector-size to match the value used by
  50090. ** the process that created this journal. If this journal was
  50091. ** created by a process other than this one, then this routine
  50092. ** is being called from within pager_playback(). The local value
  50093. ** of Pager.sectorSize is restored at the end of that routine.
  50094. */
  50095. pPager->sectorSize = iSectorSize;
  50096. }
  50097. pPager->journalOff += JOURNAL_HDR_SZ(pPager);
  50098. return rc;
  50099. }
  50100. /*
  50101. ** Write the supplied master journal name into the journal file for pager
  50102. ** pPager at the current location. The master journal name must be the last
  50103. ** thing written to a journal file. If the pager is in full-sync mode, the
  50104. ** journal file descriptor is advanced to the next sector boundary before
  50105. ** anything is written. The format is:
  50106. **
  50107. ** + 4 bytes: PAGER_MJ_PGNO.
  50108. ** + N bytes: Master journal filename in utf-8.
  50109. ** + 4 bytes: N (length of master journal name in bytes, no nul-terminator).
  50110. ** + 4 bytes: Master journal name checksum.
  50111. ** + 8 bytes: aJournalMagic[].
  50112. **
  50113. ** The master journal page checksum is the sum of the bytes in the master
  50114. ** journal name, where each byte is interpreted as a signed 8-bit integer.
  50115. **
  50116. ** If zMaster is a NULL pointer (occurs for a single database transaction),
  50117. ** this call is a no-op.
  50118. */
  50119. static int writeMasterJournal(Pager *pPager, const char *zMaster){
  50120. int rc; /* Return code */
  50121. int nMaster; /* Length of string zMaster */
  50122. i64 iHdrOff; /* Offset of header in journal file */
  50123. i64 jrnlSize; /* Size of journal file on disk */
  50124. u32 cksum = 0; /* Checksum of string zMaster */
  50125. assert( pPager->setMaster==0 );
  50126. assert( !pagerUseWal(pPager) );
  50127. if( !zMaster
  50128. || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
  50129. || !isOpen(pPager->jfd)
  50130. ){
  50131. return SQLITE_OK;
  50132. }
  50133. pPager->setMaster = 1;
  50134. assert( pPager->journalHdr <= pPager->journalOff );
  50135. /* Calculate the length in bytes and the checksum of zMaster */
  50136. for(nMaster=0; zMaster[nMaster]; nMaster++){
  50137. cksum += zMaster[nMaster];
  50138. }
  50139. /* If in full-sync mode, advance to the next disk sector before writing
  50140. ** the master journal name. This is in case the previous page written to
  50141. ** the journal has already been synced.
  50142. */
  50143. if( pPager->fullSync ){
  50144. pPager->journalOff = journalHdrOffset(pPager);
  50145. }
  50146. iHdrOff = pPager->journalOff;
  50147. /* Write the master journal data to the end of the journal file. If
  50148. ** an error occurs, return the error code to the caller.
  50149. */
  50150. if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager))))
  50151. || (0 != (rc = sqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4)))
  50152. || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster)))
  50153. || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum)))
  50154. || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8,
  50155. iHdrOff+4+nMaster+8)))
  50156. ){
  50157. return rc;
  50158. }
  50159. pPager->journalOff += (nMaster+20);
  50160. /* If the pager is in peristent-journal mode, then the physical
  50161. ** journal-file may extend past the end of the master-journal name
  50162. ** and 8 bytes of magic data just written to the file. This is
  50163. ** dangerous because the code to rollback a hot-journal file
  50164. ** will not be able to find the master-journal name to determine
  50165. ** whether or not the journal is hot.
  50166. **
  50167. ** Easiest thing to do in this scenario is to truncate the journal
  50168. ** file to the required size.
  50169. */
  50170. if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))
  50171. && jrnlSize>pPager->journalOff
  50172. ){
  50173. rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff);
  50174. }
  50175. return rc;
  50176. }
  50177. /*
  50178. ** Discard the entire contents of the in-memory page-cache.
  50179. */
  50180. static void pager_reset(Pager *pPager){
  50181. pPager->iDataVersion++;
  50182. sqlite3BackupRestart(pPager->pBackup);
  50183. sqlite3PcacheClear(pPager->pPCache);
  50184. }
  50185. /*
  50186. ** Return the pPager->iDataVersion value
  50187. */
  50188. SQLITE_PRIVATE u32 sqlite3PagerDataVersion(Pager *pPager){
  50189. return pPager->iDataVersion;
  50190. }
  50191. /*
  50192. ** Free all structures in the Pager.aSavepoint[] array and set both
  50193. ** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
  50194. ** if it is open and the pager is not in exclusive mode.
  50195. */
  50196. static void releaseAllSavepoints(Pager *pPager){
  50197. int ii; /* Iterator for looping through Pager.aSavepoint */
  50198. for(ii=0; ii<pPager->nSavepoint; ii++){
  50199. sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
  50200. }
  50201. if( !pPager->exclusiveMode || sqlite3JournalIsInMemory(pPager->sjfd) ){
  50202. sqlite3OsClose(pPager->sjfd);
  50203. }
  50204. sqlite3_free(pPager->aSavepoint);
  50205. pPager->aSavepoint = 0;
  50206. pPager->nSavepoint = 0;
  50207. pPager->nSubRec = 0;
  50208. }
  50209. /*
  50210. ** Set the bit number pgno in the PagerSavepoint.pInSavepoint
  50211. ** bitvecs of all open savepoints. Return SQLITE_OK if successful
  50212. ** or SQLITE_NOMEM if a malloc failure occurs.
  50213. */
  50214. static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){
  50215. int ii; /* Loop counter */
  50216. int rc = SQLITE_OK; /* Result code */
  50217. for(ii=0; ii<pPager->nSavepoint; ii++){
  50218. PagerSavepoint *p = &pPager->aSavepoint[ii];
  50219. if( pgno<=p->nOrig ){
  50220. rc |= sqlite3BitvecSet(p->pInSavepoint, pgno);
  50221. testcase( rc==SQLITE_NOMEM );
  50222. assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
  50223. }
  50224. }
  50225. return rc;
  50226. }
  50227. /*
  50228. ** This function is a no-op if the pager is in exclusive mode and not
  50229. ** in the ERROR state. Otherwise, it switches the pager to PAGER_OPEN
  50230. ** state.
  50231. **
  50232. ** If the pager is not in exclusive-access mode, the database file is
  50233. ** completely unlocked. If the file is unlocked and the file-system does
  50234. ** not exhibit the UNDELETABLE_WHEN_OPEN property, the journal file is
  50235. ** closed (if it is open).
  50236. **
  50237. ** If the pager is in ERROR state when this function is called, the
  50238. ** contents of the pager cache are discarded before switching back to
  50239. ** the OPEN state. Regardless of whether the pager is in exclusive-mode
  50240. ** or not, any journal file left in the file-system will be treated
  50241. ** as a hot-journal and rolled back the next time a read-transaction
  50242. ** is opened (by this or by any other connection).
  50243. */
  50244. static void pager_unlock(Pager *pPager){
  50245. assert( pPager->eState==PAGER_READER
  50246. || pPager->eState==PAGER_OPEN
  50247. || pPager->eState==PAGER_ERROR
  50248. );
  50249. sqlite3BitvecDestroy(pPager->pInJournal);
  50250. pPager->pInJournal = 0;
  50251. releaseAllSavepoints(pPager);
  50252. if( pagerUseWal(pPager) ){
  50253. assert( !isOpen(pPager->jfd) );
  50254. sqlite3WalEndReadTransaction(pPager->pWal);
  50255. pPager->eState = PAGER_OPEN;
  50256. }else if( !pPager->exclusiveMode ){
  50257. int rc; /* Error code returned by pagerUnlockDb() */
  50258. int iDc = isOpen(pPager->fd)?sqlite3OsDeviceCharacteristics(pPager->fd):0;
  50259. /* If the operating system support deletion of open files, then
  50260. ** close the journal file when dropping the database lock. Otherwise
  50261. ** another connection with journal_mode=delete might delete the file
  50262. ** out from under us.
  50263. */
  50264. assert( (PAGER_JOURNALMODE_MEMORY & 5)!=1 );
  50265. assert( (PAGER_JOURNALMODE_OFF & 5)!=1 );
  50266. assert( (PAGER_JOURNALMODE_WAL & 5)!=1 );
  50267. assert( (PAGER_JOURNALMODE_DELETE & 5)!=1 );
  50268. assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
  50269. assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
  50270. if( 0==(iDc & SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN)
  50271. || 1!=(pPager->journalMode & 5)
  50272. ){
  50273. sqlite3OsClose(pPager->jfd);
  50274. }
  50275. /* If the pager is in the ERROR state and the call to unlock the database
  50276. ** file fails, set the current lock to UNKNOWN_LOCK. See the comment
  50277. ** above the #define for UNKNOWN_LOCK for an explanation of why this
  50278. ** is necessary.
  50279. */
  50280. rc = pagerUnlockDb(pPager, NO_LOCK);
  50281. if( rc!=SQLITE_OK && pPager->eState==PAGER_ERROR ){
  50282. pPager->eLock = UNKNOWN_LOCK;
  50283. }
  50284. /* The pager state may be changed from PAGER_ERROR to PAGER_OPEN here
  50285. ** without clearing the error code. This is intentional - the error
  50286. ** code is cleared and the cache reset in the block below.
  50287. */
  50288. assert( pPager->errCode || pPager->eState!=PAGER_ERROR );
  50289. pPager->eState = PAGER_OPEN;
  50290. }
  50291. /* If Pager.errCode is set, the contents of the pager cache cannot be
  50292. ** trusted. Now that there are no outstanding references to the pager,
  50293. ** it can safely move back to PAGER_OPEN state. This happens in both
  50294. ** normal and exclusive-locking mode.
  50295. */
  50296. assert( pPager->errCode==SQLITE_OK || !MEMDB );
  50297. if( pPager->errCode ){
  50298. if( pPager->tempFile==0 ){
  50299. pager_reset(pPager);
  50300. pPager->changeCountDone = 0;
  50301. pPager->eState = PAGER_OPEN;
  50302. }else{
  50303. pPager->eState = (isOpen(pPager->jfd) ? PAGER_OPEN : PAGER_READER);
  50304. }
  50305. if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
  50306. pPager->errCode = SQLITE_OK;
  50307. setGetterMethod(pPager);
  50308. }
  50309. pPager->journalOff = 0;
  50310. pPager->journalHdr = 0;
  50311. pPager->setMaster = 0;
  50312. }
  50313. /*
  50314. ** This function is called whenever an IOERR or FULL error that requires
  50315. ** the pager to transition into the ERROR state may ahve occurred.
  50316. ** The first argument is a pointer to the pager structure, the second
  50317. ** the error-code about to be returned by a pager API function. The
  50318. ** value returned is a copy of the second argument to this function.
  50319. **
  50320. ** If the second argument is SQLITE_FULL, SQLITE_IOERR or one of the
  50321. ** IOERR sub-codes, the pager enters the ERROR state and the error code
  50322. ** is stored in Pager.errCode. While the pager remains in the ERROR state,
  50323. ** all major API calls on the Pager will immediately return Pager.errCode.
  50324. **
  50325. ** The ERROR state indicates that the contents of the pager-cache
  50326. ** cannot be trusted. This state can be cleared by completely discarding
  50327. ** the contents of the pager-cache. If a transaction was active when
  50328. ** the persistent error occurred, then the rollback journal may need
  50329. ** to be replayed to restore the contents of the database file (as if
  50330. ** it were a hot-journal).
  50331. */
  50332. static int pager_error(Pager *pPager, int rc){
  50333. int rc2 = rc & 0xff;
  50334. assert( rc==SQLITE_OK || !MEMDB );
  50335. assert(
  50336. pPager->errCode==SQLITE_FULL ||
  50337. pPager->errCode==SQLITE_OK ||
  50338. (pPager->errCode & 0xff)==SQLITE_IOERR
  50339. );
  50340. if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){
  50341. pPager->errCode = rc;
  50342. pPager->eState = PAGER_ERROR;
  50343. setGetterMethod(pPager);
  50344. }
  50345. return rc;
  50346. }
  50347. static int pager_truncate(Pager *pPager, Pgno nPage);
  50348. /*
  50349. ** The write transaction open on pPager is being committed (bCommit==1)
  50350. ** or rolled back (bCommit==0).
  50351. **
  50352. ** Return TRUE if and only if all dirty pages should be flushed to disk.
  50353. **
  50354. ** Rules:
  50355. **
  50356. ** * For non-TEMP databases, always sync to disk. This is necessary
  50357. ** for transactions to be durable.
  50358. **
  50359. ** * Sync TEMP database only on a COMMIT (not a ROLLBACK) when the backing
  50360. ** file has been created already (via a spill on pagerStress()) and
  50361. ** when the number of dirty pages in memory exceeds 25% of the total
  50362. ** cache size.
  50363. */
  50364. static int pagerFlushOnCommit(Pager *pPager, int bCommit){
  50365. if( pPager->tempFile==0 ) return 1;
  50366. if( !bCommit ) return 0;
  50367. if( !isOpen(pPager->fd) ) return 0;
  50368. return (sqlite3PCachePercentDirty(pPager->pPCache)>=25);
  50369. }
  50370. /*
  50371. ** This routine ends a transaction. A transaction is usually ended by
  50372. ** either a COMMIT or a ROLLBACK operation. This routine may be called
  50373. ** after rollback of a hot-journal, or if an error occurs while opening
  50374. ** the journal file or writing the very first journal-header of a
  50375. ** database transaction.
  50376. **
  50377. ** This routine is never called in PAGER_ERROR state. If it is called
  50378. ** in PAGER_NONE or PAGER_SHARED state and the lock held is less
  50379. ** exclusive than a RESERVED lock, it is a no-op.
  50380. **
  50381. ** Otherwise, any active savepoints are released.
  50382. **
  50383. ** If the journal file is open, then it is "finalized". Once a journal
  50384. ** file has been finalized it is not possible to use it to roll back a
  50385. ** transaction. Nor will it be considered to be a hot-journal by this
  50386. ** or any other database connection. Exactly how a journal is finalized
  50387. ** depends on whether or not the pager is running in exclusive mode and
  50388. ** the current journal-mode (Pager.journalMode value), as follows:
  50389. **
  50390. ** journalMode==MEMORY
  50391. ** Journal file descriptor is simply closed. This destroys an
  50392. ** in-memory journal.
  50393. **
  50394. ** journalMode==TRUNCATE
  50395. ** Journal file is truncated to zero bytes in size.
  50396. **
  50397. ** journalMode==PERSIST
  50398. ** The first 28 bytes of the journal file are zeroed. This invalidates
  50399. ** the first journal header in the file, and hence the entire journal
  50400. ** file. An invalid journal file cannot be rolled back.
  50401. **
  50402. ** journalMode==DELETE
  50403. ** The journal file is closed and deleted using sqlite3OsDelete().
  50404. **
  50405. ** If the pager is running in exclusive mode, this method of finalizing
  50406. ** the journal file is never used. Instead, if the journalMode is
  50407. ** DELETE and the pager is in exclusive mode, the method described under
  50408. ** journalMode==PERSIST is used instead.
  50409. **
  50410. ** After the journal is finalized, the pager moves to PAGER_READER state.
  50411. ** If running in non-exclusive rollback mode, the lock on the file is
  50412. ** downgraded to a SHARED_LOCK.
  50413. **
  50414. ** SQLITE_OK is returned if no error occurs. If an error occurs during
  50415. ** any of the IO operations to finalize the journal file or unlock the
  50416. ** database then the IO error code is returned to the user. If the
  50417. ** operation to finalize the journal file fails, then the code still
  50418. ** tries to unlock the database file if not in exclusive mode. If the
  50419. ** unlock operation fails as well, then the first error code related
  50420. ** to the first error encountered (the journal finalization one) is
  50421. ** returned.
  50422. */
  50423. static int pager_end_transaction(Pager *pPager, int hasMaster, int bCommit){
  50424. int rc = SQLITE_OK; /* Error code from journal finalization operation */
  50425. int rc2 = SQLITE_OK; /* Error code from db file unlock operation */
  50426. /* Do nothing if the pager does not have an open write transaction
  50427. ** or at least a RESERVED lock. This function may be called when there
  50428. ** is no write-transaction active but a RESERVED or greater lock is
  50429. ** held under two circumstances:
  50430. **
  50431. ** 1. After a successful hot-journal rollback, it is called with
  50432. ** eState==PAGER_NONE and eLock==EXCLUSIVE_LOCK.
  50433. **
  50434. ** 2. If a connection with locking_mode=exclusive holding an EXCLUSIVE
  50435. ** lock switches back to locking_mode=normal and then executes a
  50436. ** read-transaction, this function is called with eState==PAGER_READER
  50437. ** and eLock==EXCLUSIVE_LOCK when the read-transaction is closed.
  50438. */
  50439. assert( assert_pager_state(pPager) );
  50440. assert( pPager->eState!=PAGER_ERROR );
  50441. if( pPager->eState<PAGER_WRITER_LOCKED && pPager->eLock<RESERVED_LOCK ){
  50442. return SQLITE_OK;
  50443. }
  50444. releaseAllSavepoints(pPager);
  50445. assert( isOpen(pPager->jfd) || pPager->pInJournal==0
  50446. || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_BATCH_ATOMIC)
  50447. );
  50448. if( isOpen(pPager->jfd) ){
  50449. assert( !pagerUseWal(pPager) );
  50450. /* Finalize the journal file. */
  50451. if( sqlite3JournalIsInMemory(pPager->jfd) ){
  50452. /* assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ); */
  50453. sqlite3OsClose(pPager->jfd);
  50454. }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
  50455. if( pPager->journalOff==0 ){
  50456. rc = SQLITE_OK;
  50457. }else{
  50458. rc = sqlite3OsTruncate(pPager->jfd, 0);
  50459. if( rc==SQLITE_OK && pPager->fullSync ){
  50460. /* Make sure the new file size is written into the inode right away.
  50461. ** Otherwise the journal might resurrect following a power loss and
  50462. ** cause the last transaction to roll back. See
  50463. ** https://bugzilla.mozilla.org/show_bug.cgi?id=1072773
  50464. */
  50465. rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
  50466. }
  50467. }
  50468. pPager->journalOff = 0;
  50469. }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST
  50470. || (pPager->exclusiveMode && pPager->journalMode!=PAGER_JOURNALMODE_WAL)
  50471. ){
  50472. rc = zeroJournalHdr(pPager, hasMaster||pPager->tempFile);
  50473. pPager->journalOff = 0;
  50474. }else{
  50475. /* This branch may be executed with Pager.journalMode==MEMORY if
  50476. ** a hot-journal was just rolled back. In this case the journal
  50477. ** file should be closed and deleted. If this connection writes to
  50478. ** the database file, it will do so using an in-memory journal.
  50479. */
  50480. int bDelete = !pPager->tempFile;
  50481. assert( sqlite3JournalIsInMemory(pPager->jfd)==0 );
  50482. assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE
  50483. || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
  50484. || pPager->journalMode==PAGER_JOURNALMODE_WAL
  50485. );
  50486. sqlite3OsClose(pPager->jfd);
  50487. if( bDelete ){
  50488. rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, pPager->extraSync);
  50489. }
  50490. }
  50491. }
  50492. #ifdef SQLITE_CHECK_PAGES
  50493. sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
  50494. if( pPager->dbSize==0 && sqlite3PcacheRefCount(pPager->pPCache)>0 ){
  50495. PgHdr *p = sqlite3PagerLookup(pPager, 1);
  50496. if( p ){
  50497. p->pageHash = 0;
  50498. sqlite3PagerUnrefNotNull(p);
  50499. }
  50500. }
  50501. #endif
  50502. sqlite3BitvecDestroy(pPager->pInJournal);
  50503. pPager->pInJournal = 0;
  50504. pPager->nRec = 0;
  50505. if( rc==SQLITE_OK ){
  50506. if( MEMDB || pagerFlushOnCommit(pPager, bCommit) ){
  50507. sqlite3PcacheCleanAll(pPager->pPCache);
  50508. }else{
  50509. sqlite3PcacheClearWritable(pPager->pPCache);
  50510. }
  50511. sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
  50512. }
  50513. if( pagerUseWal(pPager) ){
  50514. /* Drop the WAL write-lock, if any. Also, if the connection was in
  50515. ** locking_mode=exclusive mode but is no longer, drop the EXCLUSIVE
  50516. ** lock held on the database file.
  50517. */
  50518. rc2 = sqlite3WalEndWriteTransaction(pPager->pWal);
  50519. assert( rc2==SQLITE_OK );
  50520. }else if( rc==SQLITE_OK && bCommit && pPager->dbFileSize>pPager->dbSize ){
  50521. /* This branch is taken when committing a transaction in rollback-journal
  50522. ** mode if the database file on disk is larger than the database image.
  50523. ** At this point the journal has been finalized and the transaction
  50524. ** successfully committed, but the EXCLUSIVE lock is still held on the
  50525. ** file. So it is safe to truncate the database file to its minimum
  50526. ** required size. */
  50527. assert( pPager->eLock==EXCLUSIVE_LOCK );
  50528. rc = pager_truncate(pPager, pPager->dbSize);
  50529. }
  50530. if( rc==SQLITE_OK && bCommit ){
  50531. rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_COMMIT_PHASETWO, 0);
  50532. if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
  50533. }
  50534. if( !pPager->exclusiveMode
  50535. && (!pagerUseWal(pPager) || sqlite3WalExclusiveMode(pPager->pWal, 0))
  50536. ){
  50537. rc2 = pagerUnlockDb(pPager, SHARED_LOCK);
  50538. }
  50539. pPager->eState = PAGER_READER;
  50540. pPager->setMaster = 0;
  50541. return (rc==SQLITE_OK?rc2:rc);
  50542. }
  50543. /*
  50544. ** Execute a rollback if a transaction is active and unlock the
  50545. ** database file.
  50546. **
  50547. ** If the pager has already entered the ERROR state, do not attempt
  50548. ** the rollback at this time. Instead, pager_unlock() is called. The
  50549. ** call to pager_unlock() will discard all in-memory pages, unlock
  50550. ** the database file and move the pager back to OPEN state. If this
  50551. ** means that there is a hot-journal left in the file-system, the next
  50552. ** connection to obtain a shared lock on the pager (which may be this one)
  50553. ** will roll it back.
  50554. **
  50555. ** If the pager has not already entered the ERROR state, but an IO or
  50556. ** malloc error occurs during a rollback, then this will itself cause
  50557. ** the pager to enter the ERROR state. Which will be cleared by the
  50558. ** call to pager_unlock(), as described above.
  50559. */
  50560. static void pagerUnlockAndRollback(Pager *pPager){
  50561. if( pPager->eState!=PAGER_ERROR && pPager->eState!=PAGER_OPEN ){
  50562. assert( assert_pager_state(pPager) );
  50563. if( pPager->eState>=PAGER_WRITER_LOCKED ){
  50564. sqlite3BeginBenignMalloc();
  50565. sqlite3PagerRollback(pPager);
  50566. sqlite3EndBenignMalloc();
  50567. }else if( !pPager->exclusiveMode ){
  50568. assert( pPager->eState==PAGER_READER );
  50569. pager_end_transaction(pPager, 0, 0);
  50570. }
  50571. }
  50572. pager_unlock(pPager);
  50573. }
  50574. /*
  50575. ** Parameter aData must point to a buffer of pPager->pageSize bytes
  50576. ** of data. Compute and return a checksum based ont the contents of the
  50577. ** page of data and the current value of pPager->cksumInit.
  50578. **
  50579. ** This is not a real checksum. It is really just the sum of the
  50580. ** random initial value (pPager->cksumInit) and every 200th byte
  50581. ** of the page data, starting with byte offset (pPager->pageSize%200).
  50582. ** Each byte is interpreted as an 8-bit unsigned integer.
  50583. **
  50584. ** Changing the formula used to compute this checksum results in an
  50585. ** incompatible journal file format.
  50586. **
  50587. ** If journal corruption occurs due to a power failure, the most likely
  50588. ** scenario is that one end or the other of the record will be changed.
  50589. ** It is much less likely that the two ends of the journal record will be
  50590. ** correct and the middle be corrupt. Thus, this "checksum" scheme,
  50591. ** though fast and simple, catches the mostly likely kind of corruption.
  50592. */
  50593. static u32 pager_cksum(Pager *pPager, const u8 *aData){
  50594. u32 cksum = pPager->cksumInit; /* Checksum value to return */
  50595. int i = pPager->pageSize-200; /* Loop counter */
  50596. while( i>0 ){
  50597. cksum += aData[i];
  50598. i -= 200;
  50599. }
  50600. return cksum;
  50601. }
  50602. /*
  50603. ** Read a single page from either the journal file (if isMainJrnl==1) or
  50604. ** from the sub-journal (if isMainJrnl==0) and playback that page.
  50605. ** The page begins at offset *pOffset into the file. The *pOffset
  50606. ** value is increased to the start of the next page in the journal.
  50607. **
  50608. ** The main rollback journal uses checksums - the statement journal does
  50609. ** not.
  50610. **
  50611. ** If the page number of the page record read from the (sub-)journal file
  50612. ** is greater than the current value of Pager.dbSize, then playback is
  50613. ** skipped and SQLITE_OK is returned.
  50614. **
  50615. ** If pDone is not NULL, then it is a record of pages that have already
  50616. ** been played back. If the page at *pOffset has already been played back
  50617. ** (if the corresponding pDone bit is set) then skip the playback.
  50618. ** Make sure the pDone bit corresponding to the *pOffset page is set
  50619. ** prior to returning.
  50620. **
  50621. ** If the page record is successfully read from the (sub-)journal file
  50622. ** and played back, then SQLITE_OK is returned. If an IO error occurs
  50623. ** while reading the record from the (sub-)journal file or while writing
  50624. ** to the database file, then the IO error code is returned. If data
  50625. ** is successfully read from the (sub-)journal file but appears to be
  50626. ** corrupted, SQLITE_DONE is returned. Data is considered corrupted in
  50627. ** two circumstances:
  50628. **
  50629. ** * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or
  50630. ** * If the record is being rolled back from the main journal file
  50631. ** and the checksum field does not match the record content.
  50632. **
  50633. ** Neither of these two scenarios are possible during a savepoint rollback.
  50634. **
  50635. ** If this is a savepoint rollback, then memory may have to be dynamically
  50636. ** allocated by this function. If this is the case and an allocation fails,
  50637. ** SQLITE_NOMEM is returned.
  50638. */
  50639. static int pager_playback_one_page(
  50640. Pager *pPager, /* The pager being played back */
  50641. i64 *pOffset, /* Offset of record to playback */
  50642. Bitvec *pDone, /* Bitvec of pages already played back */
  50643. int isMainJrnl, /* 1 -> main journal. 0 -> sub-journal. */
  50644. int isSavepnt /* True for a savepoint rollback */
  50645. ){
  50646. int rc;
  50647. PgHdr *pPg; /* An existing page in the cache */
  50648. Pgno pgno; /* The page number of a page in journal */
  50649. u32 cksum; /* Checksum used for sanity checking */
  50650. char *aData; /* Temporary storage for the page */
  50651. sqlite3_file *jfd; /* The file descriptor for the journal file */
  50652. int isSynced; /* True if journal page is synced */
  50653. assert( (isMainJrnl&~1)==0 ); /* isMainJrnl is 0 or 1 */
  50654. assert( (isSavepnt&~1)==0 ); /* isSavepnt is 0 or 1 */
  50655. assert( isMainJrnl || pDone ); /* pDone always used on sub-journals */
  50656. assert( isSavepnt || pDone==0 ); /* pDone never used on non-savepoint */
  50657. aData = pPager->pTmpSpace;
  50658. assert( aData ); /* Temp storage must have already been allocated */
  50659. assert( pagerUseWal(pPager)==0 || (!isMainJrnl && isSavepnt) );
  50660. /* Either the state is greater than PAGER_WRITER_CACHEMOD (a transaction
  50661. ** or savepoint rollback done at the request of the caller) or this is
  50662. ** a hot-journal rollback. If it is a hot-journal rollback, the pager
  50663. ** is in state OPEN and holds an EXCLUSIVE lock. Hot-journal rollback
  50664. ** only reads from the main journal, not the sub-journal.
  50665. */
  50666. assert( pPager->eState>=PAGER_WRITER_CACHEMOD
  50667. || (pPager->eState==PAGER_OPEN && pPager->eLock==EXCLUSIVE_LOCK)
  50668. );
  50669. assert( pPager->eState>=PAGER_WRITER_CACHEMOD || isMainJrnl );
  50670. /* Read the page number and page data from the journal or sub-journal
  50671. ** file. Return an error code to the caller if an IO error occurs.
  50672. */
  50673. jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;
  50674. rc = read32bits(jfd, *pOffset, &pgno);
  50675. if( rc!=SQLITE_OK ) return rc;
  50676. rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4);
  50677. if( rc!=SQLITE_OK ) return rc;
  50678. *pOffset += pPager->pageSize + 4 + isMainJrnl*4;
  50679. /* Sanity checking on the page. This is more important that I originally
  50680. ** thought. If a power failure occurs while the journal is being written,
  50681. ** it could cause invalid data to be written into the journal. We need to
  50682. ** detect this invalid data (with high probability) and ignore it.
  50683. */
  50684. if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
  50685. assert( !isSavepnt );
  50686. return SQLITE_DONE;
  50687. }
  50688. if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){
  50689. return SQLITE_OK;
  50690. }
  50691. if( isMainJrnl ){
  50692. rc = read32bits(jfd, (*pOffset)-4, &cksum);
  50693. if( rc ) return rc;
  50694. if( !isSavepnt && pager_cksum(pPager, (u8*)aData)!=cksum ){
  50695. return SQLITE_DONE;
  50696. }
  50697. }
  50698. /* If this page has already been played back before during the current
  50699. ** rollback, then don't bother to play it back again.
  50700. */
  50701. if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){
  50702. return rc;
  50703. }
  50704. /* When playing back page 1, restore the nReserve setting
  50705. */
  50706. if( pgno==1 && pPager->nReserve!=((u8*)aData)[20] ){
  50707. pPager->nReserve = ((u8*)aData)[20];
  50708. }
  50709. /* If the pager is in CACHEMOD state, then there must be a copy of this
  50710. ** page in the pager cache. In this case just update the pager cache,
  50711. ** not the database file. The page is left marked dirty in this case.
  50712. **
  50713. ** An exception to the above rule: If the database is in no-sync mode
  50714. ** and a page is moved during an incremental vacuum then the page may
  50715. ** not be in the pager cache. Later: if a malloc() or IO error occurs
  50716. ** during a Movepage() call, then the page may not be in the cache
  50717. ** either. So the condition described in the above paragraph is not
  50718. ** assert()able.
  50719. **
  50720. ** If in WRITER_DBMOD, WRITER_FINISHED or OPEN state, then we update the
  50721. ** pager cache if it exists and the main file. The page is then marked
  50722. ** not dirty. Since this code is only executed in PAGER_OPEN state for
  50723. ** a hot-journal rollback, it is guaranteed that the page-cache is empty
  50724. ** if the pager is in OPEN state.
  50725. **
  50726. ** Ticket #1171: The statement journal might contain page content that is
  50727. ** different from the page content at the start of the transaction.
  50728. ** This occurs when a page is changed prior to the start of a statement
  50729. ** then changed again within the statement. When rolling back such a
  50730. ** statement we must not write to the original database unless we know
  50731. ** for certain that original page contents are synced into the main rollback
  50732. ** journal. Otherwise, a power loss might leave modified data in the
  50733. ** database file without an entry in the rollback journal that can
  50734. ** restore the database to its original form. Two conditions must be
  50735. ** met before writing to the database files. (1) the database must be
  50736. ** locked. (2) we know that the original page content is fully synced
  50737. ** in the main journal either because the page is not in cache or else
  50738. ** the page is marked as needSync==0.
  50739. **
  50740. ** 2008-04-14: When attempting to vacuum a corrupt database file, it
  50741. ** is possible to fail a statement on a database that does not yet exist.
  50742. ** Do not attempt to write if database file has never been opened.
  50743. */
  50744. if( pagerUseWal(pPager) ){
  50745. pPg = 0;
  50746. }else{
  50747. pPg = sqlite3PagerLookup(pPager, pgno);
  50748. }
  50749. assert( pPg || !MEMDB );
  50750. assert( pPager->eState!=PAGER_OPEN || pPg==0 || pPager->tempFile );
  50751. PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
  50752. PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),
  50753. (isMainJrnl?"main-journal":"sub-journal")
  50754. ));
  50755. if( isMainJrnl ){
  50756. isSynced = pPager->noSync || (*pOffset <= pPager->journalHdr);
  50757. }else{
  50758. isSynced = (pPg==0 || 0==(pPg->flags & PGHDR_NEED_SYNC));
  50759. }
  50760. if( isOpen(pPager->fd)
  50761. && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
  50762. && isSynced
  50763. ){
  50764. i64 ofst = (pgno-1)*(i64)pPager->pageSize;
  50765. testcase( !isSavepnt && pPg!=0 && (pPg->flags&PGHDR_NEED_SYNC)!=0 );
  50766. assert( !pagerUseWal(pPager) );
  50767. /* Write the data read from the journal back into the database file.
  50768. ** This is usually safe even for an encrypted database - as the data
  50769. ** was encrypted before it was written to the journal file. The exception
  50770. ** is if the data was just read from an in-memory sub-journal. In that
  50771. ** case it must be encrypted here before it is copied into the database
  50772. ** file. */
  50773. rc = sqlite3OsWrite(pPager->fd, (u8 *)aData, pPager->pageSize, ofst);
  50774. if( pgno>pPager->dbFileSize ){
  50775. pPager->dbFileSize = pgno;
  50776. }
  50777. if( pPager->pBackup ){
  50778. sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
  50779. }
  50780. }else if( !isMainJrnl && pPg==0 ){
  50781. /* If this is a rollback of a savepoint and data was not written to
  50782. ** the database and the page is not in-memory, there is a potential
  50783. ** problem. When the page is next fetched by the b-tree layer, it
  50784. ** will be read from the database file, which may or may not be
  50785. ** current.
  50786. **
  50787. ** There are a couple of different ways this can happen. All are quite
  50788. ** obscure. When running in synchronous mode, this can only happen
  50789. ** if the page is on the free-list at the start of the transaction, then
  50790. ** populated, then moved using sqlite3PagerMovepage().
  50791. **
  50792. ** The solution is to add an in-memory page to the cache containing
  50793. ** the data just read from the sub-journal. Mark the page as dirty
  50794. ** and if the pager requires a journal-sync, then mark the page as
  50795. ** requiring a journal-sync before it is written.
  50796. */
  50797. assert( isSavepnt );
  50798. assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)==0 );
  50799. pPager->doNotSpill |= SPILLFLAG_ROLLBACK;
  50800. rc = sqlite3PagerGet(pPager, pgno, &pPg, 1);
  50801. assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)!=0 );
  50802. pPager->doNotSpill &= ~SPILLFLAG_ROLLBACK;
  50803. if( rc!=SQLITE_OK ) return rc;
  50804. sqlite3PcacheMakeDirty(pPg);
  50805. }
  50806. if( pPg ){
  50807. /* No page should ever be explicitly rolled back that is in use, except
  50808. ** for page 1 which is held in use in order to keep the lock on the
  50809. ** database active. However such a page may be rolled back as a result
  50810. ** of an internal error resulting in an automatic call to
  50811. ** sqlite3PagerRollback().
  50812. */
  50813. void *pData;
  50814. pData = pPg->pData;
  50815. memcpy(pData, (u8*)aData, pPager->pageSize);
  50816. pPager->xReiniter(pPg);
  50817. /* It used to be that sqlite3PcacheMakeClean(pPg) was called here. But
  50818. ** that call was dangerous and had no detectable benefit since the cache
  50819. ** is normally cleaned by sqlite3PcacheCleanAll() after rollback and so
  50820. ** has been removed. */
  50821. pager_set_pagehash(pPg);
  50822. /* If this was page 1, then restore the value of Pager.dbFileVers.
  50823. ** Do this before any decoding. */
  50824. if( pgno==1 ){
  50825. memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
  50826. }
  50827. sqlite3PcacheRelease(pPg);
  50828. }
  50829. return rc;
  50830. }
  50831. /*
  50832. ** Parameter zMaster is the name of a master journal file. A single journal
  50833. ** file that referred to the master journal file has just been rolled back.
  50834. ** This routine checks if it is possible to delete the master journal file,
  50835. ** and does so if it is.
  50836. **
  50837. ** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not
  50838. ** available for use within this function.
  50839. **
  50840. ** When a master journal file is created, it is populated with the names
  50841. ** of all of its child journals, one after another, formatted as utf-8
  50842. ** encoded text. The end of each child journal file is marked with a
  50843. ** nul-terminator byte (0x00). i.e. the entire contents of a master journal
  50844. ** file for a transaction involving two databases might be:
  50845. **
  50846. ** "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00"
  50847. **
  50848. ** A master journal file may only be deleted once all of its child
  50849. ** journals have been rolled back.
  50850. **
  50851. ** This function reads the contents of the master-journal file into
  50852. ** memory and loops through each of the child journal names. For
  50853. ** each child journal, it checks if:
  50854. **
  50855. ** * if the child journal exists, and if so
  50856. ** * if the child journal contains a reference to master journal
  50857. ** file zMaster
  50858. **
  50859. ** If a child journal can be found that matches both of the criteria
  50860. ** above, this function returns without doing anything. Otherwise, if
  50861. ** no such child journal can be found, file zMaster is deleted from
  50862. ** the file-system using sqlite3OsDelete().
  50863. **
  50864. ** If an IO error within this function, an error code is returned. This
  50865. ** function allocates memory by calling sqlite3Malloc(). If an allocation
  50866. ** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors
  50867. ** occur, SQLITE_OK is returned.
  50868. **
  50869. ** TODO: This function allocates a single block of memory to load
  50870. ** the entire contents of the master journal file. This could be
  50871. ** a couple of kilobytes or so - potentially larger than the page
  50872. ** size.
  50873. */
  50874. static int pager_delmaster(Pager *pPager, const char *zMaster){
  50875. sqlite3_vfs *pVfs = pPager->pVfs;
  50876. int rc; /* Return code */
  50877. sqlite3_file *pMaster; /* Malloc'd master-journal file descriptor */
  50878. sqlite3_file *pJournal; /* Malloc'd child-journal file descriptor */
  50879. char *zMasterJournal = 0; /* Contents of master journal file */
  50880. i64 nMasterJournal; /* Size of master journal file */
  50881. char *zJournal; /* Pointer to one journal within MJ file */
  50882. char *zMasterPtr; /* Space to hold MJ filename from a journal file */
  50883. int nMasterPtr; /* Amount of space allocated to zMasterPtr[] */
  50884. /* Allocate space for both the pJournal and pMaster file descriptors.
  50885. ** If successful, open the master journal file for reading.
  50886. */
  50887. pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);
  50888. pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
  50889. if( !pMaster ){
  50890. rc = SQLITE_NOMEM_BKPT;
  50891. }else{
  50892. const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
  50893. rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
  50894. }
  50895. if( rc!=SQLITE_OK ) goto delmaster_out;
  50896. /* Load the entire master journal file into space obtained from
  50897. ** sqlite3_malloc() and pointed to by zMasterJournal. Also obtain
  50898. ** sufficient space (in zMasterPtr) to hold the names of master
  50899. ** journal files extracted from regular rollback-journals.
  50900. */
  50901. rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
  50902. if( rc!=SQLITE_OK ) goto delmaster_out;
  50903. nMasterPtr = pVfs->mxPathname+1;
  50904. zMasterJournal = sqlite3Malloc(nMasterJournal + nMasterPtr + 2);
  50905. if( !zMasterJournal ){
  50906. rc = SQLITE_NOMEM_BKPT;
  50907. goto delmaster_out;
  50908. }
  50909. zMasterPtr = &zMasterJournal[nMasterJournal+2];
  50910. rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0);
  50911. if( rc!=SQLITE_OK ) goto delmaster_out;
  50912. zMasterJournal[nMasterJournal] = 0;
  50913. zMasterJournal[nMasterJournal+1] = 0;
  50914. zJournal = zMasterJournal;
  50915. while( (zJournal-zMasterJournal)<nMasterJournal ){
  50916. int exists;
  50917. rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
  50918. if( rc!=SQLITE_OK ){
  50919. goto delmaster_out;
  50920. }
  50921. if( exists ){
  50922. /* One of the journals pointed to by the master journal exists.
  50923. ** Open it and check if it points at the master journal. If
  50924. ** so, return without deleting the master journal file.
  50925. ** NB: zJournal is really a MAIN_JOURNAL. But call it a
  50926. ** MASTER_JOURNAL here so that the VFS will not send the zJournal
  50927. ** name into sqlite3_database_file_object().
  50928. */
  50929. int c;
  50930. int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
  50931. rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
  50932. if( rc!=SQLITE_OK ){
  50933. goto delmaster_out;
  50934. }
  50935. rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
  50936. sqlite3OsClose(pJournal);
  50937. if( rc!=SQLITE_OK ){
  50938. goto delmaster_out;
  50939. }
  50940. c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
  50941. if( c ){
  50942. /* We have a match. Do not delete the master journal file. */
  50943. goto delmaster_out;
  50944. }
  50945. }
  50946. zJournal += (sqlite3Strlen30(zJournal)+1);
  50947. }
  50948. sqlite3OsClose(pMaster);
  50949. rc = sqlite3OsDelete(pVfs, zMaster, 0);
  50950. delmaster_out:
  50951. sqlite3_free(zMasterJournal);
  50952. if( pMaster ){
  50953. sqlite3OsClose(pMaster);
  50954. assert( !isOpen(pJournal) );
  50955. sqlite3_free(pMaster);
  50956. }
  50957. return rc;
  50958. }
  50959. /*
  50960. ** This function is used to change the actual size of the database
  50961. ** file in the file-system. This only happens when committing a transaction,
  50962. ** or rolling back a transaction (including rolling back a hot-journal).
  50963. **
  50964. ** If the main database file is not open, or the pager is not in either
  50965. ** DBMOD or OPEN state, this function is a no-op. Otherwise, the size
  50966. ** of the file is changed to nPage pages (nPage*pPager->pageSize bytes).
  50967. ** If the file on disk is currently larger than nPage pages, then use the VFS
  50968. ** xTruncate() method to truncate it.
  50969. **
  50970. ** Or, it might be the case that the file on disk is smaller than
  50971. ** nPage pages. Some operating system implementations can get confused if
  50972. ** you try to truncate a file to some size that is larger than it
  50973. ** currently is, so detect this case and write a single zero byte to
  50974. ** the end of the new file instead.
  50975. **
  50976. ** If successful, return SQLITE_OK. If an IO error occurs while modifying
  50977. ** the database file, return the error code to the caller.
  50978. */
  50979. static int pager_truncate(Pager *pPager, Pgno nPage){
  50980. int rc = SQLITE_OK;
  50981. assert( pPager->eState!=PAGER_ERROR );
  50982. assert( pPager->eState!=PAGER_READER );
  50983. if( isOpen(pPager->fd)
  50984. && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
  50985. ){
  50986. i64 currentSize, newSize;
  50987. int szPage = pPager->pageSize;
  50988. assert( pPager->eLock==EXCLUSIVE_LOCK );
  50989. /* TODO: Is it safe to use Pager.dbFileSize here? */
  50990. rc = sqlite3OsFileSize(pPager->fd, &currentSize);
  50991. newSize = szPage*(i64)nPage;
  50992. if( rc==SQLITE_OK && currentSize!=newSize ){
  50993. if( currentSize>newSize ){
  50994. rc = sqlite3OsTruncate(pPager->fd, newSize);
  50995. }else if( (currentSize+szPage)<=newSize ){
  50996. char *pTmp = pPager->pTmpSpace;
  50997. memset(pTmp, 0, szPage);
  50998. testcase( (newSize-szPage) == currentSize );
  50999. testcase( (newSize-szPage) > currentSize );
  51000. rc = sqlite3OsWrite(pPager->fd, pTmp, szPage, newSize-szPage);
  51001. }
  51002. if( rc==SQLITE_OK ){
  51003. pPager->dbFileSize = nPage;
  51004. }
  51005. }
  51006. }
  51007. return rc;
  51008. }
  51009. /*
  51010. ** Return a sanitized version of the sector-size of OS file pFile. The
  51011. ** return value is guaranteed to lie between 32 and MAX_SECTOR_SIZE.
  51012. */
  51013. SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *pFile){
  51014. int iRet = sqlite3OsSectorSize(pFile);
  51015. if( iRet<32 ){
  51016. iRet = 512;
  51017. }else if( iRet>MAX_SECTOR_SIZE ){
  51018. assert( MAX_SECTOR_SIZE>=512 );
  51019. iRet = MAX_SECTOR_SIZE;
  51020. }
  51021. return iRet;
  51022. }
  51023. /*
  51024. ** Set the value of the Pager.sectorSize variable for the given
  51025. ** pager based on the value returned by the xSectorSize method
  51026. ** of the open database file. The sector size will be used
  51027. ** to determine the size and alignment of journal header and
  51028. ** master journal pointers within created journal files.
  51029. **
  51030. ** For temporary files the effective sector size is always 512 bytes.
  51031. **
  51032. ** Otherwise, for non-temporary files, the effective sector size is
  51033. ** the value returned by the xSectorSize() method rounded up to 32 if
  51034. ** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it
  51035. ** is greater than MAX_SECTOR_SIZE.
  51036. **
  51037. ** If the file has the SQLITE_IOCAP_POWERSAFE_OVERWRITE property, then set
  51038. ** the effective sector size to its minimum value (512). The purpose of
  51039. ** pPager->sectorSize is to define the "blast radius" of bytes that
  51040. ** might change if a crash occurs while writing to a single byte in
  51041. ** that range. But with POWERSAFE_OVERWRITE, the blast radius is zero
  51042. ** (that is what POWERSAFE_OVERWRITE means), so we minimize the sector
  51043. ** size. For backwards compatibility of the rollback journal file format,
  51044. ** we cannot reduce the effective sector size below 512.
  51045. */
  51046. static void setSectorSize(Pager *pPager){
  51047. assert( isOpen(pPager->fd) || pPager->tempFile );
  51048. if( pPager->tempFile
  51049. || (sqlite3OsDeviceCharacteristics(pPager->fd) &
  51050. SQLITE_IOCAP_POWERSAFE_OVERWRITE)!=0
  51051. ){
  51052. /* Sector size doesn't matter for temporary files. Also, the file
  51053. ** may not have been opened yet, in which case the OsSectorSize()
  51054. ** call will segfault. */
  51055. pPager->sectorSize = 512;
  51056. }else{
  51057. pPager->sectorSize = sqlite3SectorSize(pPager->fd);
  51058. }
  51059. }
  51060. /*
  51061. ** Playback the journal and thus restore the database file to
  51062. ** the state it was in before we started making changes.
  51063. **
  51064. ** The journal file format is as follows:
  51065. **
  51066. ** (1) 8 byte prefix. A copy of aJournalMagic[].
  51067. ** (2) 4 byte big-endian integer which is the number of valid page records
  51068. ** in the journal. If this value is 0xffffffff, then compute the
  51069. ** number of page records from the journal size.
  51070. ** (3) 4 byte big-endian integer which is the initial value for the
  51071. ** sanity checksum.
  51072. ** (4) 4 byte integer which is the number of pages to truncate the
  51073. ** database to during a rollback.
  51074. ** (5) 4 byte big-endian integer which is the sector size. The header
  51075. ** is this many bytes in size.
  51076. ** (6) 4 byte big-endian integer which is the page size.
  51077. ** (7) zero padding out to the next sector size.
  51078. ** (8) Zero or more pages instances, each as follows:
  51079. ** + 4 byte page number.
  51080. ** + pPager->pageSize bytes of data.
  51081. ** + 4 byte checksum
  51082. **
  51083. ** When we speak of the journal header, we mean the first 7 items above.
  51084. ** Each entry in the journal is an instance of the 8th item.
  51085. **
  51086. ** Call the value from the second bullet "nRec". nRec is the number of
  51087. ** valid page entries in the journal. In most cases, you can compute the
  51088. ** value of nRec from the size of the journal file. But if a power
  51089. ** failure occurred while the journal was being written, it could be the
  51090. ** case that the size of the journal file had already been increased but
  51091. ** the extra entries had not yet made it safely to disk. In such a case,
  51092. ** the value of nRec computed from the file size would be too large. For
  51093. ** that reason, we always use the nRec value in the header.
  51094. **
  51095. ** If the nRec value is 0xffffffff it means that nRec should be computed
  51096. ** from the file size. This value is used when the user selects the
  51097. ** no-sync option for the journal. A power failure could lead to corruption
  51098. ** in this case. But for things like temporary table (which will be
  51099. ** deleted when the power is restored) we don't care.
  51100. **
  51101. ** If the file opened as the journal file is not a well-formed
  51102. ** journal file then all pages up to the first corrupted page are rolled
  51103. ** back (or no pages if the journal header is corrupted). The journal file
  51104. ** is then deleted and SQLITE_OK returned, just as if no corruption had
  51105. ** been encountered.
  51106. **
  51107. ** If an I/O or malloc() error occurs, the journal-file is not deleted
  51108. ** and an error code is returned.
  51109. **
  51110. ** The isHot parameter indicates that we are trying to rollback a journal
  51111. ** that might be a hot journal. Or, it could be that the journal is
  51112. ** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE.
  51113. ** If the journal really is hot, reset the pager cache prior rolling
  51114. ** back any content. If the journal is merely persistent, no reset is
  51115. ** needed.
  51116. */
  51117. static int pager_playback(Pager *pPager, int isHot){
  51118. sqlite3_vfs *pVfs = pPager->pVfs;
  51119. i64 szJ; /* Size of the journal file in bytes */
  51120. u32 nRec; /* Number of Records in the journal */
  51121. u32 u; /* Unsigned loop counter */
  51122. Pgno mxPg = 0; /* Size of the original file in pages */
  51123. int rc; /* Result code of a subroutine */
  51124. int res = 1; /* Value returned by sqlite3OsAccess() */
  51125. char *zMaster = 0; /* Name of master journal file if any */
  51126. int needPagerReset; /* True to reset page prior to first page rollback */
  51127. int nPlayback = 0; /* Total number of pages restored from journal */
  51128. u32 savedPageSize = pPager->pageSize;
  51129. /* Figure out how many records are in the journal. Abort early if
  51130. ** the journal is empty.
  51131. */
  51132. assert( isOpen(pPager->jfd) );
  51133. rc = sqlite3OsFileSize(pPager->jfd, &szJ);
  51134. if( rc!=SQLITE_OK ){
  51135. goto end_playback;
  51136. }
  51137. /* Read the master journal name from the journal, if it is present.
  51138. ** If a master journal file name is specified, but the file is not
  51139. ** present on disk, then the journal is not hot and does not need to be
  51140. ** played back.
  51141. **
  51142. ** TODO: Technically the following is an error because it assumes that
  51143. ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that
  51144. ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,
  51145. ** mxPathname is 512, which is the same as the minimum allowable value
  51146. ** for pageSize.
  51147. */
  51148. zMaster = pPager->pTmpSpace;
  51149. rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
  51150. if( rc==SQLITE_OK && zMaster[0] ){
  51151. rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
  51152. }
  51153. zMaster = 0;
  51154. if( rc!=SQLITE_OK || !res ){
  51155. goto end_playback;
  51156. }
  51157. pPager->journalOff = 0;
  51158. needPagerReset = isHot;
  51159. /* This loop terminates either when a readJournalHdr() or
  51160. ** pager_playback_one_page() call returns SQLITE_DONE or an IO error
  51161. ** occurs.
  51162. */
  51163. while( 1 ){
  51164. /* Read the next journal header from the journal file. If there are
  51165. ** not enough bytes left in the journal file for a complete header, or
  51166. ** it is corrupted, then a process must have failed while writing it.
  51167. ** This indicates nothing more needs to be rolled back.
  51168. */
  51169. rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg);
  51170. if( rc!=SQLITE_OK ){
  51171. if( rc==SQLITE_DONE ){
  51172. rc = SQLITE_OK;
  51173. }
  51174. goto end_playback;
  51175. }
  51176. /* If nRec is 0xffffffff, then this journal was created by a process
  51177. ** working in no-sync mode. This means that the rest of the journal
  51178. ** file consists of pages, there are no more journal headers. Compute
  51179. ** the value of nRec based on this assumption.
  51180. */
  51181. if( nRec==0xffffffff ){
  51182. assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
  51183. nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager));
  51184. }
  51185. /* If nRec is 0 and this rollback is of a transaction created by this
  51186. ** process and if this is the final header in the journal, then it means
  51187. ** that this part of the journal was being filled but has not yet been
  51188. ** synced to disk. Compute the number of pages based on the remaining
  51189. ** size of the file.
  51190. **
  51191. ** The third term of the test was added to fix ticket #2565.
  51192. ** When rolling back a hot journal, nRec==0 always means that the next
  51193. ** chunk of the journal contains zero pages to be rolled back. But
  51194. ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in
  51195. ** the journal, it means that the journal might contain additional
  51196. ** pages that need to be rolled back and that the number of pages
  51197. ** should be computed based on the journal file size.
  51198. */
  51199. if( nRec==0 && !isHot &&
  51200. pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
  51201. nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));
  51202. }
  51203. /* If this is the first header read from the journal, truncate the
  51204. ** database file back to its original size.
  51205. */
  51206. if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
  51207. rc = pager_truncate(pPager, mxPg);
  51208. if( rc!=SQLITE_OK ){
  51209. goto end_playback;
  51210. }
  51211. pPager->dbSize = mxPg;
  51212. }
  51213. /* Copy original pages out of the journal and back into the
  51214. ** database file and/or page cache.
  51215. */
  51216. for(u=0; u<nRec; u++){
  51217. if( needPagerReset ){
  51218. pager_reset(pPager);
  51219. needPagerReset = 0;
  51220. }
  51221. rc = pager_playback_one_page(pPager,&pPager->journalOff,0,1,0);
  51222. if( rc==SQLITE_OK ){
  51223. nPlayback++;
  51224. }else{
  51225. if( rc==SQLITE_DONE ){
  51226. pPager->journalOff = szJ;
  51227. break;
  51228. }else if( rc==SQLITE_IOERR_SHORT_READ ){
  51229. /* If the journal has been truncated, simply stop reading and
  51230. ** processing the journal. This might happen if the journal was
  51231. ** not completely written and synced prior to a crash. In that
  51232. ** case, the database should have never been written in the
  51233. ** first place so it is OK to simply abandon the rollback. */
  51234. rc = SQLITE_OK;
  51235. goto end_playback;
  51236. }else{
  51237. /* If we are unable to rollback, quit and return the error
  51238. ** code. This will cause the pager to enter the error state
  51239. ** so that no further harm will be done. Perhaps the next
  51240. ** process to come along will be able to rollback the database.
  51241. */
  51242. goto end_playback;
  51243. }
  51244. }
  51245. }
  51246. }
  51247. /*NOTREACHED*/
  51248. assert( 0 );
  51249. end_playback:
  51250. if( rc==SQLITE_OK ){
  51251. rc = sqlite3PagerSetPagesize(pPager, &savedPageSize, -1);
  51252. }
  51253. /* Following a rollback, the database file should be back in its original
  51254. ** state prior to the start of the transaction, so invoke the
  51255. ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the
  51256. ** assertion that the transaction counter was modified.
  51257. */
  51258. #ifdef SQLITE_DEBUG
  51259. sqlite3OsFileControlHint(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0);
  51260. #endif
  51261. /* If this playback is happening automatically as a result of an IO or
  51262. ** malloc error that occurred after the change-counter was updated but
  51263. ** before the transaction was committed, then the change-counter
  51264. ** modification may just have been reverted. If this happens in exclusive
  51265. ** mode, then subsequent transactions performed by the connection will not
  51266. ** update the change-counter at all. This may lead to cache inconsistency
  51267. ** problems for other processes at some point in the future. So, just
  51268. ** in case this has happened, clear the changeCountDone flag now.
  51269. */
  51270. pPager->changeCountDone = pPager->tempFile;
  51271. if( rc==SQLITE_OK ){
  51272. zMaster = pPager->pTmpSpace;
  51273. rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
  51274. testcase( rc!=SQLITE_OK );
  51275. }
  51276. if( rc==SQLITE_OK
  51277. && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
  51278. ){
  51279. rc = sqlite3PagerSync(pPager, 0);
  51280. }
  51281. if( rc==SQLITE_OK ){
  51282. rc = pager_end_transaction(pPager, zMaster[0]!='\0', 0);
  51283. testcase( rc!=SQLITE_OK );
  51284. }
  51285. if( rc==SQLITE_OK && zMaster[0] && res ){
  51286. /* If there was a master journal and this routine will return success,
  51287. ** see if it is possible to delete the master journal.
  51288. */
  51289. rc = pager_delmaster(pPager, zMaster);
  51290. testcase( rc!=SQLITE_OK );
  51291. }
  51292. if( isHot && nPlayback ){
  51293. sqlite3_log(SQLITE_NOTICE_RECOVER_ROLLBACK, "recovered %d pages from %s",
  51294. nPlayback, pPager->zJournal);
  51295. }
  51296. /* The Pager.sectorSize variable may have been updated while rolling
  51297. ** back a journal created by a process with a different sector size
  51298. ** value. Reset it to the correct value for this process.
  51299. */
  51300. setSectorSize(pPager);
  51301. return rc;
  51302. }
  51303. /*
  51304. ** Read the content for page pPg out of the database file (or out of
  51305. ** the WAL if that is where the most recent copy if found) into
  51306. ** pPg->pData. A shared lock or greater must be held on the database
  51307. ** file before this function is called.
  51308. **
  51309. ** If page 1 is read, then the value of Pager.dbFileVers[] is set to
  51310. ** the value read from the database file.
  51311. **
  51312. ** If an IO error occurs, then the IO error is returned to the caller.
  51313. ** Otherwise, SQLITE_OK is returned.
  51314. */
  51315. static int readDbPage(PgHdr *pPg){
  51316. Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */
  51317. int rc = SQLITE_OK; /* Return code */
  51318. #ifndef SQLITE_OMIT_WAL
  51319. u32 iFrame = 0; /* Frame of WAL containing pgno */
  51320. assert( pPager->eState>=PAGER_READER && !MEMDB );
  51321. assert( isOpen(pPager->fd) );
  51322. if( pagerUseWal(pPager) ){
  51323. rc = sqlite3WalFindFrame(pPager->pWal, pPg->pgno, &iFrame);
  51324. if( rc ) return rc;
  51325. }
  51326. if( iFrame ){
  51327. rc = sqlite3WalReadFrame(pPager->pWal, iFrame,pPager->pageSize,pPg->pData);
  51328. }else
  51329. #endif
  51330. {
  51331. i64 iOffset = (pPg->pgno-1)*(i64)pPager->pageSize;
  51332. rc = sqlite3OsRead(pPager->fd, pPg->pData, pPager->pageSize, iOffset);
  51333. if( rc==SQLITE_IOERR_SHORT_READ ){
  51334. rc = SQLITE_OK;
  51335. }
  51336. }
  51337. if( pPg->pgno==1 ){
  51338. if( rc ){
  51339. /* If the read is unsuccessful, set the dbFileVers[] to something
  51340. ** that will never be a valid file version. dbFileVers[] is a copy
  51341. ** of bytes 24..39 of the database. Bytes 28..31 should always be
  51342. ** zero or the size of the database in page. Bytes 32..35 and 35..39
  51343. ** should be page numbers which are never 0xffffffff. So filling
  51344. ** pPager->dbFileVers[] with all 0xff bytes should suffice.
  51345. **
  51346. ** For an encrypted database, the situation is more complex: bytes
  51347. ** 24..39 of the database are white noise. But the probability of
  51348. ** white noise equaling 16 bytes of 0xff is vanishingly small so
  51349. ** we should still be ok.
  51350. */
  51351. memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers));
  51352. }else{
  51353. u8 *dbFileVers = &((u8*)pPg->pData)[24];
  51354. memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
  51355. }
  51356. }
  51357. PAGER_INCR(sqlite3_pager_readdb_count);
  51358. PAGER_INCR(pPager->nRead);
  51359. IOTRACE(("PGIN %p %d\n", pPager, pPg->pgno));
  51360. PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
  51361. PAGERID(pPager), pPg->pgno, pager_pagehash(pPg)));
  51362. return rc;
  51363. }
  51364. /*
  51365. ** Update the value of the change-counter at offsets 24 and 92 in
  51366. ** the header and the sqlite version number at offset 96.
  51367. **
  51368. ** This is an unconditional update. See also the pager_incr_changecounter()
  51369. ** routine which only updates the change-counter if the update is actually
  51370. ** needed, as determined by the pPager->changeCountDone state variable.
  51371. */
  51372. static void pager_write_changecounter(PgHdr *pPg){
  51373. u32 change_counter;
  51374. /* Increment the value just read and write it back to byte 24. */
  51375. change_counter = sqlite3Get4byte((u8*)pPg->pPager->dbFileVers)+1;
  51376. put32bits(((char*)pPg->pData)+24, change_counter);
  51377. /* Also store the SQLite version number in bytes 96..99 and in
  51378. ** bytes 92..95 store the change counter for which the version number
  51379. ** is valid. */
  51380. put32bits(((char*)pPg->pData)+92, change_counter);
  51381. put32bits(((char*)pPg->pData)+96, SQLITE_VERSION_NUMBER);
  51382. }
  51383. #ifndef SQLITE_OMIT_WAL
  51384. /*
  51385. ** This function is invoked once for each page that has already been
  51386. ** written into the log file when a WAL transaction is rolled back.
  51387. ** Parameter iPg is the page number of said page. The pCtx argument
  51388. ** is actually a pointer to the Pager structure.
  51389. **
  51390. ** If page iPg is present in the cache, and has no outstanding references,
  51391. ** it is discarded. Otherwise, if there are one or more outstanding
  51392. ** references, the page content is reloaded from the database. If the
  51393. ** attempt to reload content from the database is required and fails,
  51394. ** return an SQLite error code. Otherwise, SQLITE_OK.
  51395. */
  51396. static int pagerUndoCallback(void *pCtx, Pgno iPg){
  51397. int rc = SQLITE_OK;
  51398. Pager *pPager = (Pager *)pCtx;
  51399. PgHdr *pPg;
  51400. assert( pagerUseWal(pPager) );
  51401. pPg = sqlite3PagerLookup(pPager, iPg);
  51402. if( pPg ){
  51403. if( sqlite3PcachePageRefcount(pPg)==1 ){
  51404. sqlite3PcacheDrop(pPg);
  51405. }else{
  51406. rc = readDbPage(pPg);
  51407. if( rc==SQLITE_OK ){
  51408. pPager->xReiniter(pPg);
  51409. }
  51410. sqlite3PagerUnrefNotNull(pPg);
  51411. }
  51412. }
  51413. /* Normally, if a transaction is rolled back, any backup processes are
  51414. ** updated as data is copied out of the rollback journal and into the
  51415. ** database. This is not generally possible with a WAL database, as
  51416. ** rollback involves simply truncating the log file. Therefore, if one
  51417. ** or more frames have already been written to the log (and therefore
  51418. ** also copied into the backup databases) as part of this transaction,
  51419. ** the backups must be restarted.
  51420. */
  51421. sqlite3BackupRestart(pPager->pBackup);
  51422. return rc;
  51423. }
  51424. /*
  51425. ** This function is called to rollback a transaction on a WAL database.
  51426. */
  51427. static int pagerRollbackWal(Pager *pPager){
  51428. int rc; /* Return Code */
  51429. PgHdr *pList; /* List of dirty pages to revert */
  51430. /* For all pages in the cache that are currently dirty or have already
  51431. ** been written (but not committed) to the log file, do one of the
  51432. ** following:
  51433. **
  51434. ** + Discard the cached page (if refcount==0), or
  51435. ** + Reload page content from the database (if refcount>0).
  51436. */
  51437. pPager->dbSize = pPager->dbOrigSize;
  51438. rc = sqlite3WalUndo(pPager->pWal, pagerUndoCallback, (void *)pPager);
  51439. pList = sqlite3PcacheDirtyList(pPager->pPCache);
  51440. while( pList && rc==SQLITE_OK ){
  51441. PgHdr *pNext = pList->pDirty;
  51442. rc = pagerUndoCallback((void *)pPager, pList->pgno);
  51443. pList = pNext;
  51444. }
  51445. return rc;
  51446. }
  51447. /*
  51448. ** This function is a wrapper around sqlite3WalFrames(). As well as logging
  51449. ** the contents of the list of pages headed by pList (connected by pDirty),
  51450. ** this function notifies any active backup processes that the pages have
  51451. ** changed.
  51452. **
  51453. ** The list of pages passed into this routine is always sorted by page number.
  51454. ** Hence, if page 1 appears anywhere on the list, it will be the first page.
  51455. */
  51456. static int pagerWalFrames(
  51457. Pager *pPager, /* Pager object */
  51458. PgHdr *pList, /* List of frames to log */
  51459. Pgno nTruncate, /* Database size after this commit */
  51460. int isCommit /* True if this is a commit */
  51461. ){
  51462. int rc; /* Return code */
  51463. int nList; /* Number of pages in pList */
  51464. PgHdr *p; /* For looping over pages */
  51465. assert( pPager->pWal );
  51466. assert( pList );
  51467. #ifdef SQLITE_DEBUG
  51468. /* Verify that the page list is in accending order */
  51469. for(p=pList; p && p->pDirty; p=p->pDirty){
  51470. assert( p->pgno < p->pDirty->pgno );
  51471. }
  51472. #endif
  51473. assert( pList->pDirty==0 || isCommit );
  51474. if( isCommit ){
  51475. /* If a WAL transaction is being committed, there is no point in writing
  51476. ** any pages with page numbers greater than nTruncate into the WAL file.
  51477. ** They will never be read by any client. So remove them from the pDirty
  51478. ** list here. */
  51479. PgHdr **ppNext = &pList;
  51480. nList = 0;
  51481. for(p=pList; (*ppNext = p)!=0; p=p->pDirty){
  51482. if( p->pgno<=nTruncate ){
  51483. ppNext = &p->pDirty;
  51484. nList++;
  51485. }
  51486. }
  51487. assert( pList );
  51488. }else{
  51489. nList = 1;
  51490. }
  51491. pPager->aStat[PAGER_STAT_WRITE] += nList;
  51492. if( pList->pgno==1 ) pager_write_changecounter(pList);
  51493. rc = sqlite3WalFrames(pPager->pWal,
  51494. pPager->pageSize, pList, nTruncate, isCommit, pPager->walSyncFlags
  51495. );
  51496. if( rc==SQLITE_OK && pPager->pBackup ){
  51497. for(p=pList; p; p=p->pDirty){
  51498. sqlite3BackupUpdate(pPager->pBackup, p->pgno, (u8 *)p->pData);
  51499. }
  51500. }
  51501. #ifdef SQLITE_CHECK_PAGES
  51502. pList = sqlite3PcacheDirtyList(pPager->pPCache);
  51503. for(p=pList; p; p=p->pDirty){
  51504. pager_set_pagehash(p);
  51505. }
  51506. #endif
  51507. return rc;
  51508. }
  51509. /*
  51510. ** Begin a read transaction on the WAL.
  51511. **
  51512. ** This routine used to be called "pagerOpenSnapshot()" because it essentially
  51513. ** makes a snapshot of the database at the current point in time and preserves
  51514. ** that snapshot for use by the reader in spite of concurrently changes by
  51515. ** other writers or checkpointers.
  51516. */
  51517. static int pagerBeginReadTransaction(Pager *pPager){
  51518. int rc; /* Return code */
  51519. int changed = 0; /* True if cache must be reset */
  51520. assert( pagerUseWal(pPager) );
  51521. assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
  51522. /* sqlite3WalEndReadTransaction() was not called for the previous
  51523. ** transaction in locking_mode=EXCLUSIVE. So call it now. If we
  51524. ** are in locking_mode=NORMAL and EndRead() was previously called,
  51525. ** the duplicate call is harmless.
  51526. */
  51527. sqlite3WalEndReadTransaction(pPager->pWal);
  51528. rc = sqlite3WalBeginReadTransaction(pPager->pWal, &changed);
  51529. if( rc!=SQLITE_OK || changed ){
  51530. pager_reset(pPager);
  51531. if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
  51532. }
  51533. return rc;
  51534. }
  51535. #endif
  51536. /*
  51537. ** This function is called as part of the transition from PAGER_OPEN
  51538. ** to PAGER_READER state to determine the size of the database file
  51539. ** in pages (assuming the page size currently stored in Pager.pageSize).
  51540. **
  51541. ** If no error occurs, SQLITE_OK is returned and the size of the database
  51542. ** in pages is stored in *pnPage. Otherwise, an error code (perhaps
  51543. ** SQLITE_IOERR_FSTAT) is returned and *pnPage is left unmodified.
  51544. */
  51545. static int pagerPagecount(Pager *pPager, Pgno *pnPage){
  51546. Pgno nPage; /* Value to return via *pnPage */
  51547. /* Query the WAL sub-system for the database size. The WalDbsize()
  51548. ** function returns zero if the WAL is not open (i.e. Pager.pWal==0), or
  51549. ** if the database size is not available. The database size is not
  51550. ** available from the WAL sub-system if the log file is empty or
  51551. ** contains no valid committed transactions.
  51552. */
  51553. assert( pPager->eState==PAGER_OPEN );
  51554. assert( pPager->eLock>=SHARED_LOCK );
  51555. assert( isOpen(pPager->fd) );
  51556. assert( pPager->tempFile==0 );
  51557. nPage = sqlite3WalDbsize(pPager->pWal);
  51558. /* If the number of pages in the database is not available from the
  51559. ** WAL sub-system, determine the page count based on the size of
  51560. ** the database file. If the size of the database file is not an
  51561. ** integer multiple of the page-size, round up the result.
  51562. */
  51563. if( nPage==0 && ALWAYS(isOpen(pPager->fd)) ){
  51564. i64 n = 0; /* Size of db file in bytes */
  51565. int rc = sqlite3OsFileSize(pPager->fd, &n);
  51566. if( rc!=SQLITE_OK ){
  51567. return rc;
  51568. }
  51569. nPage = (Pgno)((n+pPager->pageSize-1) / pPager->pageSize);
  51570. }
  51571. /* If the current number of pages in the file is greater than the
  51572. ** configured maximum pager number, increase the allowed limit so
  51573. ** that the file can be read.
  51574. */
  51575. if( nPage>pPager->mxPgno ){
  51576. pPager->mxPgno = (Pgno)nPage;
  51577. }
  51578. *pnPage = nPage;
  51579. return SQLITE_OK;
  51580. }
  51581. #ifndef SQLITE_OMIT_WAL
  51582. /*
  51583. ** Check if the *-wal file that corresponds to the database opened by pPager
  51584. ** exists if the database is not empy, or verify that the *-wal file does
  51585. ** not exist (by deleting it) if the database file is empty.
  51586. **
  51587. ** If the database is not empty and the *-wal file exists, open the pager
  51588. ** in WAL mode. If the database is empty or if no *-wal file exists and
  51589. ** if no error occurs, make sure Pager.journalMode is not set to
  51590. ** PAGER_JOURNALMODE_WAL.
  51591. **
  51592. ** Return SQLITE_OK or an error code.
  51593. **
  51594. ** The caller must hold a SHARED lock on the database file to call this
  51595. ** function. Because an EXCLUSIVE lock on the db file is required to delete
  51596. ** a WAL on a none-empty database, this ensures there is no race condition
  51597. ** between the xAccess() below and an xDelete() being executed by some
  51598. ** other connection.
  51599. */
  51600. static int pagerOpenWalIfPresent(Pager *pPager){
  51601. int rc = SQLITE_OK;
  51602. assert( pPager->eState==PAGER_OPEN );
  51603. assert( pPager->eLock>=SHARED_LOCK );
  51604. if( !pPager->tempFile ){
  51605. int isWal; /* True if WAL file exists */
  51606. rc = sqlite3OsAccess(
  51607. pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &isWal
  51608. );
  51609. if( rc==SQLITE_OK ){
  51610. if( isWal ){
  51611. Pgno nPage; /* Size of the database file */
  51612. rc = pagerPagecount(pPager, &nPage);
  51613. if( rc ) return rc;
  51614. if( nPage==0 ){
  51615. rc = sqlite3OsDelete(pPager->pVfs, pPager->zWal, 0);
  51616. }else{
  51617. testcase( sqlite3PcachePagecount(pPager->pPCache)==0 );
  51618. rc = sqlite3PagerOpenWal(pPager, 0);
  51619. }
  51620. }else if( pPager->journalMode==PAGER_JOURNALMODE_WAL ){
  51621. pPager->journalMode = PAGER_JOURNALMODE_DELETE;
  51622. }
  51623. }
  51624. }
  51625. return rc;
  51626. }
  51627. #endif
  51628. /*
  51629. ** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
  51630. ** the entire master journal file. The case pSavepoint==NULL occurs when
  51631. ** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction
  51632. ** savepoint.
  51633. **
  51634. ** When pSavepoint is not NULL (meaning a non-transaction savepoint is
  51635. ** being rolled back), then the rollback consists of up to three stages,
  51636. ** performed in the order specified:
  51637. **
  51638. ** * Pages are played back from the main journal starting at byte
  51639. ** offset PagerSavepoint.iOffset and continuing to
  51640. ** PagerSavepoint.iHdrOffset, or to the end of the main journal
  51641. ** file if PagerSavepoint.iHdrOffset is zero.
  51642. **
  51643. ** * If PagerSavepoint.iHdrOffset is not zero, then pages are played
  51644. ** back starting from the journal header immediately following
  51645. ** PagerSavepoint.iHdrOffset to the end of the main journal file.
  51646. **
  51647. ** * Pages are then played back from the sub-journal file, starting
  51648. ** with the PagerSavepoint.iSubRec and continuing to the end of
  51649. ** the journal file.
  51650. **
  51651. ** Throughout the rollback process, each time a page is rolled back, the
  51652. ** corresponding bit is set in a bitvec structure (variable pDone in the
  51653. ** implementation below). This is used to ensure that a page is only
  51654. ** rolled back the first time it is encountered in either journal.
  51655. **
  51656. ** If pSavepoint is NULL, then pages are only played back from the main
  51657. ** journal file. There is no need for a bitvec in this case.
  51658. **
  51659. ** In either case, before playback commences the Pager.dbSize variable
  51660. ** is reset to the value that it held at the start of the savepoint
  51661. ** (or transaction). No page with a page-number greater than this value
  51662. ** is played back. If one is encountered it is simply skipped.
  51663. */
  51664. static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
  51665. i64 szJ; /* Effective size of the main journal */
  51666. i64 iHdrOff; /* End of first segment of main-journal records */
  51667. int rc = SQLITE_OK; /* Return code */
  51668. Bitvec *pDone = 0; /* Bitvec to ensure pages played back only once */
  51669. assert( pPager->eState!=PAGER_ERROR );
  51670. assert( pPager->eState>=PAGER_WRITER_LOCKED );
  51671. /* Allocate a bitvec to use to store the set of pages rolled back */
  51672. if( pSavepoint ){
  51673. pDone = sqlite3BitvecCreate(pSavepoint->nOrig);
  51674. if( !pDone ){
  51675. return SQLITE_NOMEM_BKPT;
  51676. }
  51677. }
  51678. /* Set the database size back to the value it was before the savepoint
  51679. ** being reverted was opened.
  51680. */
  51681. pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
  51682. pPager->changeCountDone = pPager->tempFile;
  51683. if( !pSavepoint && pagerUseWal(pPager) ){
  51684. return pagerRollbackWal(pPager);
  51685. }
  51686. /* Use pPager->journalOff as the effective size of the main rollback
  51687. ** journal. The actual file might be larger than this in
  51688. ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST. But anything
  51689. ** past pPager->journalOff is off-limits to us.
  51690. */
  51691. szJ = pPager->journalOff;
  51692. assert( pagerUseWal(pPager)==0 || szJ==0 );
  51693. /* Begin by rolling back records from the main journal starting at
  51694. ** PagerSavepoint.iOffset and continuing to the next journal header.
  51695. ** There might be records in the main journal that have a page number
  51696. ** greater than the current database size (pPager->dbSize) but those
  51697. ** will be skipped automatically. Pages are added to pDone as they
  51698. ** are played back.
  51699. */
  51700. if( pSavepoint && !pagerUseWal(pPager) ){
  51701. iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
  51702. pPager->journalOff = pSavepoint->iOffset;
  51703. while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){
  51704. rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
  51705. }
  51706. assert( rc!=SQLITE_DONE );
  51707. }else{
  51708. pPager->journalOff = 0;
  51709. }
  51710. /* Continue rolling back records out of the main journal starting at
  51711. ** the first journal header seen and continuing until the effective end
  51712. ** of the main journal file. Continue to skip out-of-range pages and
  51713. ** continue adding pages rolled back to pDone.
  51714. */
  51715. while( rc==SQLITE_OK && pPager->journalOff<szJ ){
  51716. u32 ii; /* Loop counter */
  51717. u32 nJRec = 0; /* Number of Journal Records */
  51718. u32 dummy;
  51719. rc = readJournalHdr(pPager, 0, szJ, &nJRec, &dummy);
  51720. assert( rc!=SQLITE_DONE );
  51721. /*
  51722. ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff"
  51723. ** test is related to ticket #2565. See the discussion in the
  51724. ** pager_playback() function for additional information.
  51725. */
  51726. if( nJRec==0
  51727. && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
  51728. ){
  51729. nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
  51730. }
  51731. for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
  51732. rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
  51733. }
  51734. assert( rc!=SQLITE_DONE );
  51735. }
  51736. assert( rc!=SQLITE_OK || pPager->journalOff>=szJ );
  51737. /* Finally, rollback pages from the sub-journal. Page that were
  51738. ** previously rolled back out of the main journal (and are hence in pDone)
  51739. ** will be skipped. Out-of-range pages are also skipped.
  51740. */
  51741. if( pSavepoint ){
  51742. u32 ii; /* Loop counter */
  51743. i64 offset = (i64)pSavepoint->iSubRec*(4+pPager->pageSize);
  51744. if( pagerUseWal(pPager) ){
  51745. rc = sqlite3WalSavepointUndo(pPager->pWal, pSavepoint->aWalData);
  51746. }
  51747. for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){
  51748. assert( offset==(i64)ii*(4+pPager->pageSize) );
  51749. rc = pager_playback_one_page(pPager, &offset, pDone, 0, 1);
  51750. }
  51751. assert( rc!=SQLITE_DONE );
  51752. }
  51753. sqlite3BitvecDestroy(pDone);
  51754. if( rc==SQLITE_OK ){
  51755. pPager->journalOff = szJ;
  51756. }
  51757. return rc;
  51758. }
  51759. /*
  51760. ** Change the maximum number of in-memory pages that are allowed
  51761. ** before attempting to recycle clean and unused pages.
  51762. */
  51763. SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
  51764. sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
  51765. }
  51766. /*
  51767. ** Change the maximum number of in-memory pages that are allowed
  51768. ** before attempting to spill pages to journal.
  51769. */
  51770. SQLITE_PRIVATE int sqlite3PagerSetSpillsize(Pager *pPager, int mxPage){
  51771. return sqlite3PcacheSetSpillsize(pPager->pPCache, mxPage);
  51772. }
  51773. /*
  51774. ** Invoke SQLITE_FCNTL_MMAP_SIZE based on the current value of szMmap.
  51775. */
  51776. static void pagerFixMaplimit(Pager *pPager){
  51777. #if SQLITE_MAX_MMAP_SIZE>0
  51778. sqlite3_file *fd = pPager->fd;
  51779. if( isOpen(fd) && fd->pMethods->iVersion>=3 ){
  51780. sqlite3_int64 sz;
  51781. sz = pPager->szMmap;
  51782. pPager->bUseFetch = (sz>0);
  51783. setGetterMethod(pPager);
  51784. sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_MMAP_SIZE, &sz);
  51785. }
  51786. #endif
  51787. }
  51788. /*
  51789. ** Change the maximum size of any memory mapping made of the database file.
  51790. */
  51791. SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *pPager, sqlite3_int64 szMmap){
  51792. pPager->szMmap = szMmap;
  51793. pagerFixMaplimit(pPager);
  51794. }
  51795. /*
  51796. ** Free as much memory as possible from the pager.
  51797. */
  51798. SQLITE_PRIVATE void sqlite3PagerShrink(Pager *pPager){
  51799. sqlite3PcacheShrink(pPager->pPCache);
  51800. }
  51801. /*
  51802. ** Adjust settings of the pager to those specified in the pgFlags parameter.
  51803. **
  51804. ** The "level" in pgFlags & PAGER_SYNCHRONOUS_MASK sets the robustness
  51805. ** of the database to damage due to OS crashes or power failures by
  51806. ** changing the number of syncs()s when writing the journals.
  51807. ** There are four levels:
  51808. **
  51809. ** OFF sqlite3OsSync() is never called. This is the default
  51810. ** for temporary and transient files.
  51811. **
  51812. ** NORMAL The journal is synced once before writes begin on the
  51813. ** database. This is normally adequate protection, but
  51814. ** it is theoretically possible, though very unlikely,
  51815. ** that an inopertune power failure could leave the journal
  51816. ** in a state which would cause damage to the database
  51817. ** when it is rolled back.
  51818. **
  51819. ** FULL The journal is synced twice before writes begin on the
  51820. ** database (with some additional information - the nRec field
  51821. ** of the journal header - being written in between the two
  51822. ** syncs). If we assume that writing a
  51823. ** single disk sector is atomic, then this mode provides
  51824. ** assurance that the journal will not be corrupted to the
  51825. ** point of causing damage to the database during rollback.
  51826. **
  51827. ** EXTRA This is like FULL except that is also syncs the directory
  51828. ** that contains the rollback journal after the rollback
  51829. ** journal is unlinked.
  51830. **
  51831. ** The above is for a rollback-journal mode. For WAL mode, OFF continues
  51832. ** to mean that no syncs ever occur. NORMAL means that the WAL is synced
  51833. ** prior to the start of checkpoint and that the database file is synced
  51834. ** at the conclusion of the checkpoint if the entire content of the WAL
  51835. ** was written back into the database. But no sync operations occur for
  51836. ** an ordinary commit in NORMAL mode with WAL. FULL means that the WAL
  51837. ** file is synced following each commit operation, in addition to the
  51838. ** syncs associated with NORMAL. There is no difference between FULL
  51839. ** and EXTRA for WAL mode.
  51840. **
  51841. ** Do not confuse synchronous=FULL with SQLITE_SYNC_FULL. The
  51842. ** SQLITE_SYNC_FULL macro means to use the MacOSX-style full-fsync
  51843. ** using fcntl(F_FULLFSYNC). SQLITE_SYNC_NORMAL means to do an
  51844. ** ordinary fsync() call. There is no difference between SQLITE_SYNC_FULL
  51845. ** and SQLITE_SYNC_NORMAL on platforms other than MacOSX. But the
  51846. ** synchronous=FULL versus synchronous=NORMAL setting determines when
  51847. ** the xSync primitive is called and is relevant to all platforms.
  51848. **
  51849. ** Numeric values associated with these states are OFF==1, NORMAL=2,
  51850. ** and FULL=3.
  51851. */
  51852. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  51853. SQLITE_PRIVATE void sqlite3PagerSetFlags(
  51854. Pager *pPager, /* The pager to set safety level for */
  51855. unsigned pgFlags /* Various flags */
  51856. ){
  51857. unsigned level = pgFlags & PAGER_SYNCHRONOUS_MASK;
  51858. if( pPager->tempFile ){
  51859. pPager->noSync = 1;
  51860. pPager->fullSync = 0;
  51861. pPager->extraSync = 0;
  51862. }else{
  51863. pPager->noSync = level==PAGER_SYNCHRONOUS_OFF ?1:0;
  51864. pPager->fullSync = level>=PAGER_SYNCHRONOUS_FULL ?1:0;
  51865. pPager->extraSync = level==PAGER_SYNCHRONOUS_EXTRA ?1:0;
  51866. }
  51867. if( pPager->noSync ){
  51868. pPager->syncFlags = 0;
  51869. }else if( pgFlags & PAGER_FULLFSYNC ){
  51870. pPager->syncFlags = SQLITE_SYNC_FULL;
  51871. }else{
  51872. pPager->syncFlags = SQLITE_SYNC_NORMAL;
  51873. }
  51874. pPager->walSyncFlags = (pPager->syncFlags<<2);
  51875. if( pPager->fullSync ){
  51876. pPager->walSyncFlags |= pPager->syncFlags;
  51877. }
  51878. if( (pgFlags & PAGER_CKPT_FULLFSYNC) && !pPager->noSync ){
  51879. pPager->walSyncFlags |= (SQLITE_SYNC_FULL<<2);
  51880. }
  51881. if( pgFlags & PAGER_CACHESPILL ){
  51882. pPager->doNotSpill &= ~SPILLFLAG_OFF;
  51883. }else{
  51884. pPager->doNotSpill |= SPILLFLAG_OFF;
  51885. }
  51886. }
  51887. #endif
  51888. /*
  51889. ** The following global variable is incremented whenever the library
  51890. ** attempts to open a temporary file. This information is used for
  51891. ** testing and analysis only.
  51892. */
  51893. #ifdef SQLITE_TEST
  51894. SQLITE_API int sqlite3_opentemp_count = 0;
  51895. #endif
  51896. /*
  51897. ** Open a temporary file.
  51898. **
  51899. ** Write the file descriptor into *pFile. Return SQLITE_OK on success
  51900. ** or some other error code if we fail. The OS will automatically
  51901. ** delete the temporary file when it is closed.
  51902. **
  51903. ** The flags passed to the VFS layer xOpen() call are those specified
  51904. ** by parameter vfsFlags ORed with the following:
  51905. **
  51906. ** SQLITE_OPEN_READWRITE
  51907. ** SQLITE_OPEN_CREATE
  51908. ** SQLITE_OPEN_EXCLUSIVE
  51909. ** SQLITE_OPEN_DELETEONCLOSE
  51910. */
  51911. static int pagerOpentemp(
  51912. Pager *pPager, /* The pager object */
  51913. sqlite3_file *pFile, /* Write the file descriptor here */
  51914. int vfsFlags /* Flags passed through to the VFS */
  51915. ){
  51916. int rc; /* Return code */
  51917. #ifdef SQLITE_TEST
  51918. sqlite3_opentemp_count++; /* Used for testing and analysis only */
  51919. #endif
  51920. vfsFlags |= SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
  51921. SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
  51922. rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
  51923. assert( rc!=SQLITE_OK || isOpen(pFile) );
  51924. return rc;
  51925. }
  51926. /*
  51927. ** Set the busy handler function.
  51928. **
  51929. ** The pager invokes the busy-handler if sqlite3OsLock() returns
  51930. ** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock,
  51931. ** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE
  51932. ** lock. It does *not* invoke the busy handler when upgrading from
  51933. ** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE
  51934. ** (which occurs during hot-journal rollback). Summary:
  51935. **
  51936. ** Transition | Invokes xBusyHandler
  51937. ** --------------------------------------------------------
  51938. ** NO_LOCK -> SHARED_LOCK | Yes
  51939. ** SHARED_LOCK -> RESERVED_LOCK | No
  51940. ** SHARED_LOCK -> EXCLUSIVE_LOCK | No
  51941. ** RESERVED_LOCK -> EXCLUSIVE_LOCK | Yes
  51942. **
  51943. ** If the busy-handler callback returns non-zero, the lock is
  51944. ** retried. If it returns zero, then the SQLITE_BUSY error is
  51945. ** returned to the caller of the pager API function.
  51946. */
  51947. SQLITE_PRIVATE void sqlite3PagerSetBusyHandler(
  51948. Pager *pPager, /* Pager object */
  51949. int (*xBusyHandler)(void *), /* Pointer to busy-handler function */
  51950. void *pBusyHandlerArg /* Argument to pass to xBusyHandler */
  51951. ){
  51952. void **ap;
  51953. pPager->xBusyHandler = xBusyHandler;
  51954. pPager->pBusyHandlerArg = pBusyHandlerArg;
  51955. ap = (void **)&pPager->xBusyHandler;
  51956. assert( ((int(*)(void *))(ap[0]))==xBusyHandler );
  51957. assert( ap[1]==pBusyHandlerArg );
  51958. sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_BUSYHANDLER, (void *)ap);
  51959. }
  51960. /*
  51961. ** Change the page size used by the Pager object. The new page size
  51962. ** is passed in *pPageSize.
  51963. **
  51964. ** If the pager is in the error state when this function is called, it
  51965. ** is a no-op. The value returned is the error state error code (i.e.
  51966. ** one of SQLITE_IOERR, an SQLITE_IOERR_xxx sub-code or SQLITE_FULL).
  51967. **
  51968. ** Otherwise, if all of the following are true:
  51969. **
  51970. ** * the new page size (value of *pPageSize) is valid (a power
  51971. ** of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and
  51972. **
  51973. ** * there are no outstanding page references, and
  51974. **
  51975. ** * the database is either not an in-memory database or it is
  51976. ** an in-memory database that currently consists of zero pages.
  51977. **
  51978. ** then the pager object page size is set to *pPageSize.
  51979. **
  51980. ** If the page size is changed, then this function uses sqlite3PagerMalloc()
  51981. ** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt
  51982. ** fails, SQLITE_NOMEM is returned and the page size remains unchanged.
  51983. ** In all other cases, SQLITE_OK is returned.
  51984. **
  51985. ** If the page size is not changed, either because one of the enumerated
  51986. ** conditions above is not true, the pager was in error state when this
  51987. ** function was called, or because the memory allocation attempt failed,
  51988. ** then *pPageSize is set to the old, retained page size before returning.
  51989. */
  51990. SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u32 *pPageSize, int nReserve){
  51991. int rc = SQLITE_OK;
  51992. /* It is not possible to do a full assert_pager_state() here, as this
  51993. ** function may be called from within PagerOpen(), before the state
  51994. ** of the Pager object is internally consistent.
  51995. **
  51996. ** At one point this function returned an error if the pager was in
  51997. ** PAGER_ERROR state. But since PAGER_ERROR state guarantees that
  51998. ** there is at least one outstanding page reference, this function
  51999. ** is a no-op for that case anyhow.
  52000. */
  52001. u32 pageSize = *pPageSize;
  52002. assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
  52003. if( (pPager->memDb==0 || pPager->dbSize==0)
  52004. && sqlite3PcacheRefCount(pPager->pPCache)==0
  52005. && pageSize && pageSize!=(u32)pPager->pageSize
  52006. ){
  52007. char *pNew = NULL; /* New temp space */
  52008. i64 nByte = 0;
  52009. if( pPager->eState>PAGER_OPEN && isOpen(pPager->fd) ){
  52010. rc = sqlite3OsFileSize(pPager->fd, &nByte);
  52011. }
  52012. if( rc==SQLITE_OK ){
  52013. /* 8 bytes of zeroed overrun space is sufficient so that the b-tree
  52014. * cell header parser will never run off the end of the allocation */
  52015. pNew = (char *)sqlite3PageMalloc(pageSize+8);
  52016. if( !pNew ){
  52017. rc = SQLITE_NOMEM_BKPT;
  52018. }else{
  52019. memset(pNew+pageSize, 0, 8);
  52020. }
  52021. }
  52022. if( rc==SQLITE_OK ){
  52023. pager_reset(pPager);
  52024. rc = sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
  52025. }
  52026. if( rc==SQLITE_OK ){
  52027. sqlite3PageFree(pPager->pTmpSpace);
  52028. pPager->pTmpSpace = pNew;
  52029. pPager->dbSize = (Pgno)((nByte+pageSize-1)/pageSize);
  52030. pPager->pageSize = pageSize;
  52031. }else{
  52032. sqlite3PageFree(pNew);
  52033. }
  52034. }
  52035. *pPageSize = pPager->pageSize;
  52036. if( rc==SQLITE_OK ){
  52037. if( nReserve<0 ) nReserve = pPager->nReserve;
  52038. assert( nReserve>=0 && nReserve<1000 );
  52039. pPager->nReserve = (i16)nReserve;
  52040. pagerFixMaplimit(pPager);
  52041. }
  52042. return rc;
  52043. }
  52044. /*
  52045. ** Return a pointer to the "temporary page" buffer held internally
  52046. ** by the pager. This is a buffer that is big enough to hold the
  52047. ** entire content of a database page. This buffer is used internally
  52048. ** during rollback and will be overwritten whenever a rollback
  52049. ** occurs. But other modules are free to use it too, as long as
  52050. ** no rollbacks are happening.
  52051. */
  52052. SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){
  52053. return pPager->pTmpSpace;
  52054. }
  52055. /*
  52056. ** Attempt to set the maximum database page count if mxPage is positive.
  52057. ** Make no changes if mxPage is zero or negative. And never reduce the
  52058. ** maximum page count below the current size of the database.
  52059. **
  52060. ** Regardless of mxPage, return the current maximum page count.
  52061. */
  52062. SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
  52063. if( mxPage>0 ){
  52064. pPager->mxPgno = mxPage;
  52065. }
  52066. assert( pPager->eState!=PAGER_OPEN ); /* Called only by OP_MaxPgcnt */
  52067. /* assert( pPager->mxPgno>=pPager->dbSize ); */
  52068. /* OP_MaxPgcnt ensures that the parameter passed to this function is not
  52069. ** less than the total number of valid pages in the database. But this
  52070. ** may be less than Pager.dbSize, and so the assert() above is not valid */
  52071. return pPager->mxPgno;
  52072. }
  52073. /*
  52074. ** The following set of routines are used to disable the simulated
  52075. ** I/O error mechanism. These routines are used to avoid simulated
  52076. ** errors in places where we do not care about errors.
  52077. **
  52078. ** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
  52079. ** and generate no code.
  52080. */
  52081. #ifdef SQLITE_TEST
  52082. SQLITE_API extern int sqlite3_io_error_pending;
  52083. SQLITE_API extern int sqlite3_io_error_hit;
  52084. static int saved_cnt;
  52085. void disable_simulated_io_errors(void){
  52086. saved_cnt = sqlite3_io_error_pending;
  52087. sqlite3_io_error_pending = -1;
  52088. }
  52089. void enable_simulated_io_errors(void){
  52090. sqlite3_io_error_pending = saved_cnt;
  52091. }
  52092. #else
  52093. # define disable_simulated_io_errors()
  52094. # define enable_simulated_io_errors()
  52095. #endif
  52096. /*
  52097. ** Read the first N bytes from the beginning of the file into memory
  52098. ** that pDest points to.
  52099. **
  52100. ** If the pager was opened on a transient file (zFilename==""), or
  52101. ** opened on a file less than N bytes in size, the output buffer is
  52102. ** zeroed and SQLITE_OK returned. The rationale for this is that this
  52103. ** function is used to read database headers, and a new transient or
  52104. ** zero sized database has a header than consists entirely of zeroes.
  52105. **
  52106. ** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered,
  52107. ** the error code is returned to the caller and the contents of the
  52108. ** output buffer undefined.
  52109. */
  52110. SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
  52111. int rc = SQLITE_OK;
  52112. memset(pDest, 0, N);
  52113. assert( isOpen(pPager->fd) || pPager->tempFile );
  52114. /* This routine is only called by btree immediately after creating
  52115. ** the Pager object. There has not been an opportunity to transition
  52116. ** to WAL mode yet.
  52117. */
  52118. assert( !pagerUseWal(pPager) );
  52119. if( isOpen(pPager->fd) ){
  52120. IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
  52121. rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
  52122. if( rc==SQLITE_IOERR_SHORT_READ ){
  52123. rc = SQLITE_OK;
  52124. }
  52125. }
  52126. return rc;
  52127. }
  52128. /*
  52129. ** This function may only be called when a read-transaction is open on
  52130. ** the pager. It returns the total number of pages in the database.
  52131. **
  52132. ** However, if the file is between 1 and <page-size> bytes in size, then
  52133. ** this is considered a 1 page file.
  52134. */
  52135. SQLITE_PRIVATE void sqlite3PagerPagecount(Pager *pPager, int *pnPage){
  52136. assert( pPager->eState>=PAGER_READER );
  52137. assert( pPager->eState!=PAGER_WRITER_FINISHED );
  52138. *pnPage = (int)pPager->dbSize;
  52139. }
  52140. /*
  52141. ** Try to obtain a lock of type locktype on the database file. If
  52142. ** a similar or greater lock is already held, this function is a no-op
  52143. ** (returning SQLITE_OK immediately).
  52144. **
  52145. ** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke
  52146. ** the busy callback if the lock is currently not available. Repeat
  52147. ** until the busy callback returns false or until the attempt to
  52148. ** obtain the lock succeeds.
  52149. **
  52150. ** Return SQLITE_OK on success and an error code if we cannot obtain
  52151. ** the lock. If the lock is obtained successfully, set the Pager.state
  52152. ** variable to locktype before returning.
  52153. */
  52154. static int pager_wait_on_lock(Pager *pPager, int locktype){
  52155. int rc; /* Return code */
  52156. /* Check that this is either a no-op (because the requested lock is
  52157. ** already held), or one of the transitions that the busy-handler
  52158. ** may be invoked during, according to the comment above
  52159. ** sqlite3PagerSetBusyhandler().
  52160. */
  52161. assert( (pPager->eLock>=locktype)
  52162. || (pPager->eLock==NO_LOCK && locktype==SHARED_LOCK)
  52163. || (pPager->eLock==RESERVED_LOCK && locktype==EXCLUSIVE_LOCK)
  52164. );
  52165. do {
  52166. rc = pagerLockDb(pPager, locktype);
  52167. }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
  52168. return rc;
  52169. }
  52170. /*
  52171. ** Function assertTruncateConstraint(pPager) checks that one of the
  52172. ** following is true for all dirty pages currently in the page-cache:
  52173. **
  52174. ** a) The page number is less than or equal to the size of the
  52175. ** current database image, in pages, OR
  52176. **
  52177. ** b) if the page content were written at this time, it would not
  52178. ** be necessary to write the current content out to the sub-journal
  52179. ** (as determined by function subjRequiresPage()).
  52180. **
  52181. ** If the condition asserted by this function were not true, and the
  52182. ** dirty page were to be discarded from the cache via the pagerStress()
  52183. ** routine, pagerStress() would not write the current page content to
  52184. ** the database file. If a savepoint transaction were rolled back after
  52185. ** this happened, the correct behavior would be to restore the current
  52186. ** content of the page. However, since this content is not present in either
  52187. ** the database file or the portion of the rollback journal and
  52188. ** sub-journal rolled back the content could not be restored and the
  52189. ** database image would become corrupt. It is therefore fortunate that
  52190. ** this circumstance cannot arise.
  52191. */
  52192. #if defined(SQLITE_DEBUG)
  52193. static void assertTruncateConstraintCb(PgHdr *pPg){
  52194. assert( pPg->flags&PGHDR_DIRTY );
  52195. assert( !subjRequiresPage(pPg) || pPg->pgno<=pPg->pPager->dbSize );
  52196. }
  52197. static void assertTruncateConstraint(Pager *pPager){
  52198. sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb);
  52199. }
  52200. #else
  52201. # define assertTruncateConstraint(pPager)
  52202. #endif
  52203. /*
  52204. ** Truncate the in-memory database file image to nPage pages. This
  52205. ** function does not actually modify the database file on disk. It
  52206. ** just sets the internal state of the pager object so that the
  52207. ** truncation will be done when the current transaction is committed.
  52208. **
  52209. ** This function is only called right before committing a transaction.
  52210. ** Once this function has been called, the transaction must either be
  52211. ** rolled back or committed. It is not safe to call this function and
  52212. ** then continue writing to the database.
  52213. */
  52214. SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){
  52215. assert( pPager->dbSize>=nPage );
  52216. assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
  52217. pPager->dbSize = nPage;
  52218. /* At one point the code here called assertTruncateConstraint() to
  52219. ** ensure that all pages being truncated away by this operation are,
  52220. ** if one or more savepoints are open, present in the savepoint
  52221. ** journal so that they can be restored if the savepoint is rolled
  52222. ** back. This is no longer necessary as this function is now only
  52223. ** called right before committing a transaction. So although the
  52224. ** Pager object may still have open savepoints (Pager.nSavepoint!=0),
  52225. ** they cannot be rolled back. So the assertTruncateConstraint() call
  52226. ** is no longer correct. */
  52227. }
  52228. /*
  52229. ** This function is called before attempting a hot-journal rollback. It
  52230. ** syncs the journal file to disk, then sets pPager->journalHdr to the
  52231. ** size of the journal file so that the pager_playback() routine knows
  52232. ** that the entire journal file has been synced.
  52233. **
  52234. ** Syncing a hot-journal to disk before attempting to roll it back ensures
  52235. ** that if a power-failure occurs during the rollback, the process that
  52236. ** attempts rollback following system recovery sees the same journal
  52237. ** content as this process.
  52238. **
  52239. ** If everything goes as planned, SQLITE_OK is returned. Otherwise,
  52240. ** an SQLite error code.
  52241. */
  52242. static int pagerSyncHotJournal(Pager *pPager){
  52243. int rc = SQLITE_OK;
  52244. if( !pPager->noSync ){
  52245. rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_NORMAL);
  52246. }
  52247. if( rc==SQLITE_OK ){
  52248. rc = sqlite3OsFileSize(pPager->jfd, &pPager->journalHdr);
  52249. }
  52250. return rc;
  52251. }
  52252. #if SQLITE_MAX_MMAP_SIZE>0
  52253. /*
  52254. ** Obtain a reference to a memory mapped page object for page number pgno.
  52255. ** The new object will use the pointer pData, obtained from xFetch().
  52256. ** If successful, set *ppPage to point to the new page reference
  52257. ** and return SQLITE_OK. Otherwise, return an SQLite error code and set
  52258. ** *ppPage to zero.
  52259. **
  52260. ** Page references obtained by calling this function should be released
  52261. ** by calling pagerReleaseMapPage().
  52262. */
  52263. static int pagerAcquireMapPage(
  52264. Pager *pPager, /* Pager object */
  52265. Pgno pgno, /* Page number */
  52266. void *pData, /* xFetch()'d data for this page */
  52267. PgHdr **ppPage /* OUT: Acquired page object */
  52268. ){
  52269. PgHdr *p; /* Memory mapped page to return */
  52270. if( pPager->pMmapFreelist ){
  52271. *ppPage = p = pPager->pMmapFreelist;
  52272. pPager->pMmapFreelist = p->pDirty;
  52273. p->pDirty = 0;
  52274. assert( pPager->nExtra>=8 );
  52275. memset(p->pExtra, 0, 8);
  52276. }else{
  52277. *ppPage = p = (PgHdr *)sqlite3MallocZero(sizeof(PgHdr) + pPager->nExtra);
  52278. if( p==0 ){
  52279. sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1) * pPager->pageSize, pData);
  52280. return SQLITE_NOMEM_BKPT;
  52281. }
  52282. p->pExtra = (void *)&p[1];
  52283. p->flags = PGHDR_MMAP;
  52284. p->nRef = 1;
  52285. p->pPager = pPager;
  52286. }
  52287. assert( p->pExtra==(void *)&p[1] );
  52288. assert( p->pPage==0 );
  52289. assert( p->flags==PGHDR_MMAP );
  52290. assert( p->pPager==pPager );
  52291. assert( p->nRef==1 );
  52292. p->pgno = pgno;
  52293. p->pData = pData;
  52294. pPager->nMmapOut++;
  52295. return SQLITE_OK;
  52296. }
  52297. #endif
  52298. /*
  52299. ** Release a reference to page pPg. pPg must have been returned by an
  52300. ** earlier call to pagerAcquireMapPage().
  52301. */
  52302. static void pagerReleaseMapPage(PgHdr *pPg){
  52303. Pager *pPager = pPg->pPager;
  52304. pPager->nMmapOut--;
  52305. pPg->pDirty = pPager->pMmapFreelist;
  52306. pPager->pMmapFreelist = pPg;
  52307. assert( pPager->fd->pMethods->iVersion>=3 );
  52308. sqlite3OsUnfetch(pPager->fd, (i64)(pPg->pgno-1)*pPager->pageSize, pPg->pData);
  52309. }
  52310. /*
  52311. ** Free all PgHdr objects stored in the Pager.pMmapFreelist list.
  52312. */
  52313. static void pagerFreeMapHdrs(Pager *pPager){
  52314. PgHdr *p;
  52315. PgHdr *pNext;
  52316. for(p=pPager->pMmapFreelist; p; p=pNext){
  52317. pNext = p->pDirty;
  52318. sqlite3_free(p);
  52319. }
  52320. }
  52321. /* Verify that the database file has not be deleted or renamed out from
  52322. ** under the pager. Return SQLITE_OK if the database is still where it ought
  52323. ** to be on disk. Return non-zero (SQLITE_READONLY_DBMOVED or some other error
  52324. ** code from sqlite3OsAccess()) if the database has gone missing.
  52325. */
  52326. static int databaseIsUnmoved(Pager *pPager){
  52327. int bHasMoved = 0;
  52328. int rc;
  52329. if( pPager->tempFile ) return SQLITE_OK;
  52330. if( pPager->dbSize==0 ) return SQLITE_OK;
  52331. assert( pPager->zFilename && pPager->zFilename[0] );
  52332. rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_HAS_MOVED, &bHasMoved);
  52333. if( rc==SQLITE_NOTFOUND ){
  52334. /* If the HAS_MOVED file-control is unimplemented, assume that the file
  52335. ** has not been moved. That is the historical behavior of SQLite: prior to
  52336. ** version 3.8.3, it never checked */
  52337. rc = SQLITE_OK;
  52338. }else if( rc==SQLITE_OK && bHasMoved ){
  52339. rc = SQLITE_READONLY_DBMOVED;
  52340. }
  52341. return rc;
  52342. }
  52343. /*
  52344. ** Shutdown the page cache. Free all memory and close all files.
  52345. **
  52346. ** If a transaction was in progress when this routine is called, that
  52347. ** transaction is rolled back. All outstanding pages are invalidated
  52348. ** and their memory is freed. Any attempt to use a page associated
  52349. ** with this page cache after this function returns will likely
  52350. ** result in a coredump.
  52351. **
  52352. ** This function always succeeds. If a transaction is active an attempt
  52353. ** is made to roll it back. If an error occurs during the rollback
  52354. ** a hot journal may be left in the filesystem but no error is returned
  52355. ** to the caller.
  52356. */
  52357. SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager, sqlite3 *db){
  52358. u8 *pTmp = (u8*)pPager->pTmpSpace;
  52359. assert( db || pagerUseWal(pPager)==0 );
  52360. assert( assert_pager_state(pPager) );
  52361. disable_simulated_io_errors();
  52362. sqlite3BeginBenignMalloc();
  52363. pagerFreeMapHdrs(pPager);
  52364. /* pPager->errCode = 0; */
  52365. pPager->exclusiveMode = 0;
  52366. #ifndef SQLITE_OMIT_WAL
  52367. {
  52368. u8 *a = 0;
  52369. assert( db || pPager->pWal==0 );
  52370. if( db && 0==(db->flags & SQLITE_NoCkptOnClose)
  52371. && SQLITE_OK==databaseIsUnmoved(pPager)
  52372. ){
  52373. a = pTmp;
  52374. }
  52375. sqlite3WalClose(pPager->pWal, db, pPager->walSyncFlags, pPager->pageSize,a);
  52376. pPager->pWal = 0;
  52377. }
  52378. #endif
  52379. pager_reset(pPager);
  52380. if( MEMDB ){
  52381. pager_unlock(pPager);
  52382. }else{
  52383. /* If it is open, sync the journal file before calling UnlockAndRollback.
  52384. ** If this is not done, then an unsynced portion of the open journal
  52385. ** file may be played back into the database. If a power failure occurs
  52386. ** while this is happening, the database could become corrupt.
  52387. **
  52388. ** If an error occurs while trying to sync the journal, shift the pager
  52389. ** into the ERROR state. This causes UnlockAndRollback to unlock the
  52390. ** database and close the journal file without attempting to roll it
  52391. ** back or finalize it. The next database user will have to do hot-journal
  52392. ** rollback before accessing the database file.
  52393. */
  52394. if( isOpen(pPager->jfd) ){
  52395. pager_error(pPager, pagerSyncHotJournal(pPager));
  52396. }
  52397. pagerUnlockAndRollback(pPager);
  52398. }
  52399. sqlite3EndBenignMalloc();
  52400. enable_simulated_io_errors();
  52401. PAGERTRACE(("CLOSE %d\n", PAGERID(pPager)));
  52402. IOTRACE(("CLOSE %p\n", pPager))
  52403. sqlite3OsClose(pPager->jfd);
  52404. sqlite3OsClose(pPager->fd);
  52405. sqlite3PageFree(pTmp);
  52406. sqlite3PcacheClose(pPager->pPCache);
  52407. assert( !pPager->aSavepoint && !pPager->pInJournal );
  52408. assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) );
  52409. sqlite3_free(pPager);
  52410. return SQLITE_OK;
  52411. }
  52412. #if !defined(NDEBUG) || defined(SQLITE_TEST)
  52413. /*
  52414. ** Return the page number for page pPg.
  52415. */
  52416. SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *pPg){
  52417. return pPg->pgno;
  52418. }
  52419. #endif
  52420. /*
  52421. ** Increment the reference count for page pPg.
  52422. */
  52423. SQLITE_PRIVATE void sqlite3PagerRef(DbPage *pPg){
  52424. sqlite3PcacheRef(pPg);
  52425. }
  52426. /*
  52427. ** Sync the journal. In other words, make sure all the pages that have
  52428. ** been written to the journal have actually reached the surface of the
  52429. ** disk and can be restored in the event of a hot-journal rollback.
  52430. **
  52431. ** If the Pager.noSync flag is set, then this function is a no-op.
  52432. ** Otherwise, the actions required depend on the journal-mode and the
  52433. ** device characteristics of the file-system, as follows:
  52434. **
  52435. ** * If the journal file is an in-memory journal file, no action need
  52436. ** be taken.
  52437. **
  52438. ** * Otherwise, if the device does not support the SAFE_APPEND property,
  52439. ** then the nRec field of the most recently written journal header
  52440. ** is updated to contain the number of journal records that have
  52441. ** been written following it. If the pager is operating in full-sync
  52442. ** mode, then the journal file is synced before this field is updated.
  52443. **
  52444. ** * If the device does not support the SEQUENTIAL property, then
  52445. ** journal file is synced.
  52446. **
  52447. ** Or, in pseudo-code:
  52448. **
  52449. ** if( NOT <in-memory journal> ){
  52450. ** if( NOT SAFE_APPEND ){
  52451. ** if( <full-sync mode> ) xSync(<journal file>);
  52452. ** <update nRec field>
  52453. ** }
  52454. ** if( NOT SEQUENTIAL ) xSync(<journal file>);
  52455. ** }
  52456. **
  52457. ** If successful, this routine clears the PGHDR_NEED_SYNC flag of every
  52458. ** page currently held in memory before returning SQLITE_OK. If an IO
  52459. ** error is encountered, then the IO error code is returned to the caller.
  52460. */
  52461. static int syncJournal(Pager *pPager, int newHdr){
  52462. int rc; /* Return code */
  52463. assert( pPager->eState==PAGER_WRITER_CACHEMOD
  52464. || pPager->eState==PAGER_WRITER_DBMOD
  52465. );
  52466. assert( assert_pager_state(pPager) );
  52467. assert( !pagerUseWal(pPager) );
  52468. rc = sqlite3PagerExclusiveLock(pPager);
  52469. if( rc!=SQLITE_OK ) return rc;
  52470. if( !pPager->noSync ){
  52471. assert( !pPager->tempFile );
  52472. if( isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
  52473. const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
  52474. assert( isOpen(pPager->jfd) );
  52475. if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
  52476. /* This block deals with an obscure problem. If the last connection
  52477. ** that wrote to this database was operating in persistent-journal
  52478. ** mode, then the journal file may at this point actually be larger
  52479. ** than Pager.journalOff bytes. If the next thing in the journal
  52480. ** file happens to be a journal-header (written as part of the
  52481. ** previous connection's transaction), and a crash or power-failure
  52482. ** occurs after nRec is updated but before this connection writes
  52483. ** anything else to the journal file (or commits/rolls back its
  52484. ** transaction), then SQLite may become confused when doing the
  52485. ** hot-journal rollback following recovery. It may roll back all
  52486. ** of this connections data, then proceed to rolling back the old,
  52487. ** out-of-date data that follows it. Database corruption.
  52488. **
  52489. ** To work around this, if the journal file does appear to contain
  52490. ** a valid header following Pager.journalOff, then write a 0x00
  52491. ** byte to the start of it to prevent it from being recognized.
  52492. **
  52493. ** Variable iNextHdrOffset is set to the offset at which this
  52494. ** problematic header will occur, if it exists. aMagic is used
  52495. ** as a temporary buffer to inspect the first couple of bytes of
  52496. ** the potential journal header.
  52497. */
  52498. i64 iNextHdrOffset;
  52499. u8 aMagic[8];
  52500. u8 zHeader[sizeof(aJournalMagic)+4];
  52501. memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
  52502. put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec);
  52503. iNextHdrOffset = journalHdrOffset(pPager);
  52504. rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);
  52505. if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){
  52506. static const u8 zerobyte = 0;
  52507. rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset);
  52508. }
  52509. if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
  52510. return rc;
  52511. }
  52512. /* Write the nRec value into the journal file header. If in
  52513. ** full-synchronous mode, sync the journal first. This ensures that
  52514. ** all data has really hit the disk before nRec is updated to mark
  52515. ** it as a candidate for rollback.
  52516. **
  52517. ** This is not required if the persistent media supports the
  52518. ** SAFE_APPEND property. Because in this case it is not possible
  52519. ** for garbage data to be appended to the file, the nRec field
  52520. ** is populated with 0xFFFFFFFF when the journal header is written
  52521. ** and never needs to be updated.
  52522. */
  52523. if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
  52524. PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
  52525. IOTRACE(("JSYNC %p\n", pPager))
  52526. rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
  52527. if( rc!=SQLITE_OK ) return rc;
  52528. }
  52529. IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr));
  52530. rc = sqlite3OsWrite(
  52531. pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr
  52532. );
  52533. if( rc!=SQLITE_OK ) return rc;
  52534. }
  52535. if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
  52536. PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
  52537. IOTRACE(("JSYNC %p\n", pPager))
  52538. rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags|
  52539. (pPager->syncFlags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
  52540. );
  52541. if( rc!=SQLITE_OK ) return rc;
  52542. }
  52543. pPager->journalHdr = pPager->journalOff;
  52544. if( newHdr && 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
  52545. pPager->nRec = 0;
  52546. rc = writeJournalHdr(pPager);
  52547. if( rc!=SQLITE_OK ) return rc;
  52548. }
  52549. }else{
  52550. pPager->journalHdr = pPager->journalOff;
  52551. }
  52552. }
  52553. /* Unless the pager is in noSync mode, the journal file was just
  52554. ** successfully synced. Either way, clear the PGHDR_NEED_SYNC flag on
  52555. ** all pages.
  52556. */
  52557. sqlite3PcacheClearSyncFlags(pPager->pPCache);
  52558. pPager->eState = PAGER_WRITER_DBMOD;
  52559. assert( assert_pager_state(pPager) );
  52560. return SQLITE_OK;
  52561. }
  52562. /*
  52563. ** The argument is the first in a linked list of dirty pages connected
  52564. ** by the PgHdr.pDirty pointer. This function writes each one of the
  52565. ** in-memory pages in the list to the database file. The argument may
  52566. ** be NULL, representing an empty list. In this case this function is
  52567. ** a no-op.
  52568. **
  52569. ** The pager must hold at least a RESERVED lock when this function
  52570. ** is called. Before writing anything to the database file, this lock
  52571. ** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained,
  52572. ** SQLITE_BUSY is returned and no data is written to the database file.
  52573. **
  52574. ** If the pager is a temp-file pager and the actual file-system file
  52575. ** is not yet open, it is created and opened before any data is
  52576. ** written out.
  52577. **
  52578. ** Once the lock has been upgraded and, if necessary, the file opened,
  52579. ** the pages are written out to the database file in list order. Writing
  52580. ** a page is skipped if it meets either of the following criteria:
  52581. **
  52582. ** * The page number is greater than Pager.dbSize, or
  52583. ** * The PGHDR_DONT_WRITE flag is set on the page.
  52584. **
  52585. ** If writing out a page causes the database file to grow, Pager.dbFileSize
  52586. ** is updated accordingly. If page 1 is written out, then the value cached
  52587. ** in Pager.dbFileVers[] is updated to match the new value stored in
  52588. ** the database file.
  52589. **
  52590. ** If everything is successful, SQLITE_OK is returned. If an IO error
  52591. ** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot
  52592. ** be obtained, SQLITE_BUSY is returned.
  52593. */
  52594. static int pager_write_pagelist(Pager *pPager, PgHdr *pList){
  52595. int rc = SQLITE_OK; /* Return code */
  52596. /* This function is only called for rollback pagers in WRITER_DBMOD state. */
  52597. assert( !pagerUseWal(pPager) );
  52598. assert( pPager->tempFile || pPager->eState==PAGER_WRITER_DBMOD );
  52599. assert( pPager->eLock==EXCLUSIVE_LOCK );
  52600. assert( isOpen(pPager->fd) || pList->pDirty==0 );
  52601. /* If the file is a temp-file has not yet been opened, open it now. It
  52602. ** is not possible for rc to be other than SQLITE_OK if this branch
  52603. ** is taken, as pager_wait_on_lock() is a no-op for temp-files.
  52604. */
  52605. if( !isOpen(pPager->fd) ){
  52606. assert( pPager->tempFile && rc==SQLITE_OK );
  52607. rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
  52608. }
  52609. /* Before the first write, give the VFS a hint of what the final
  52610. ** file size will be.
  52611. */
  52612. assert( rc!=SQLITE_OK || isOpen(pPager->fd) );
  52613. if( rc==SQLITE_OK
  52614. && pPager->dbHintSize<pPager->dbSize
  52615. && (pList->pDirty || pList->pgno>pPager->dbHintSize)
  52616. ){
  52617. sqlite3_int64 szFile = pPager->pageSize * (sqlite3_int64)pPager->dbSize;
  52618. sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &szFile);
  52619. pPager->dbHintSize = pPager->dbSize;
  52620. }
  52621. while( rc==SQLITE_OK && pList ){
  52622. Pgno pgno = pList->pgno;
  52623. /* If there are dirty pages in the page cache with page numbers greater
  52624. ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to
  52625. ** make the file smaller (presumably by auto-vacuum code). Do not write
  52626. ** any such pages to the file.
  52627. **
  52628. ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag
  52629. ** set (set by sqlite3PagerDontWrite()).
  52630. */
  52631. if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
  52632. i64 offset = (pgno-1)*(i64)pPager->pageSize; /* Offset to write */
  52633. char *pData; /* Data to write */
  52634. assert( (pList->flags&PGHDR_NEED_SYNC)==0 );
  52635. if( pList->pgno==1 ) pager_write_changecounter(pList);
  52636. pData = pList->pData;
  52637. /* Write out the page data. */
  52638. rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
  52639. /* If page 1 was just written, update Pager.dbFileVers to match
  52640. ** the value now stored in the database file. If writing this
  52641. ** page caused the database file to grow, update dbFileSize.
  52642. */
  52643. if( pgno==1 ){
  52644. memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
  52645. }
  52646. if( pgno>pPager->dbFileSize ){
  52647. pPager->dbFileSize = pgno;
  52648. }
  52649. pPager->aStat[PAGER_STAT_WRITE]++;
  52650. /* Update any backup objects copying the contents of this pager. */
  52651. sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData);
  52652. PAGERTRACE(("STORE %d page %d hash(%08x)\n",
  52653. PAGERID(pPager), pgno, pager_pagehash(pList)));
  52654. IOTRACE(("PGOUT %p %d\n", pPager, pgno));
  52655. PAGER_INCR(sqlite3_pager_writedb_count);
  52656. }else{
  52657. PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno));
  52658. }
  52659. pager_set_pagehash(pList);
  52660. pList = pList->pDirty;
  52661. }
  52662. return rc;
  52663. }
  52664. /*
  52665. ** Ensure that the sub-journal file is open. If it is already open, this
  52666. ** function is a no-op.
  52667. **
  52668. ** SQLITE_OK is returned if everything goes according to plan. An
  52669. ** SQLITE_IOERR_XXX error code is returned if a call to sqlite3OsOpen()
  52670. ** fails.
  52671. */
  52672. static int openSubJournal(Pager *pPager){
  52673. int rc = SQLITE_OK;
  52674. if( !isOpen(pPager->sjfd) ){
  52675. const int flags = SQLITE_OPEN_SUBJOURNAL | SQLITE_OPEN_READWRITE
  52676. | SQLITE_OPEN_CREATE | SQLITE_OPEN_EXCLUSIVE
  52677. | SQLITE_OPEN_DELETEONCLOSE;
  52678. int nStmtSpill = sqlite3Config.nStmtSpill;
  52679. if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){
  52680. nStmtSpill = -1;
  52681. }
  52682. rc = sqlite3JournalOpen(pPager->pVfs, 0, pPager->sjfd, flags, nStmtSpill);
  52683. }
  52684. return rc;
  52685. }
  52686. /*
  52687. ** Append a record of the current state of page pPg to the sub-journal.
  52688. **
  52689. ** If successful, set the bit corresponding to pPg->pgno in the bitvecs
  52690. ** for all open savepoints before returning.
  52691. **
  52692. ** This function returns SQLITE_OK if everything is successful, an IO
  52693. ** error code if the attempt to write to the sub-journal fails, or
  52694. ** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint
  52695. ** bitvec.
  52696. */
  52697. static int subjournalPage(PgHdr *pPg){
  52698. int rc = SQLITE_OK;
  52699. Pager *pPager = pPg->pPager;
  52700. if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
  52701. /* Open the sub-journal, if it has not already been opened */
  52702. assert( pPager->useJournal );
  52703. assert( isOpen(pPager->jfd) || pagerUseWal(pPager) );
  52704. assert( isOpen(pPager->sjfd) || pPager->nSubRec==0 );
  52705. assert( pagerUseWal(pPager)
  52706. || pageInJournal(pPager, pPg)
  52707. || pPg->pgno>pPager->dbOrigSize
  52708. );
  52709. rc = openSubJournal(pPager);
  52710. /* If the sub-journal was opened successfully (or was already open),
  52711. ** write the journal record into the file. */
  52712. if( rc==SQLITE_OK ){
  52713. void *pData = pPg->pData;
  52714. i64 offset = (i64)pPager->nSubRec*(4+pPager->pageSize);
  52715. char *pData2;
  52716. pData2 = pData;
  52717. PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
  52718. rc = write32bits(pPager->sjfd, offset, pPg->pgno);
  52719. if( rc==SQLITE_OK ){
  52720. rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
  52721. }
  52722. }
  52723. }
  52724. if( rc==SQLITE_OK ){
  52725. pPager->nSubRec++;
  52726. assert( pPager->nSavepoint>0 );
  52727. rc = addToSavepointBitvecs(pPager, pPg->pgno);
  52728. }
  52729. return rc;
  52730. }
  52731. static int subjournalPageIfRequired(PgHdr *pPg){
  52732. if( subjRequiresPage(pPg) ){
  52733. return subjournalPage(pPg);
  52734. }else{
  52735. return SQLITE_OK;
  52736. }
  52737. }
  52738. /*
  52739. ** This function is called by the pcache layer when it has reached some
  52740. ** soft memory limit. The first argument is a pointer to a Pager object
  52741. ** (cast as a void*). The pager is always 'purgeable' (not an in-memory
  52742. ** database). The second argument is a reference to a page that is
  52743. ** currently dirty but has no outstanding references. The page
  52744. ** is always associated with the Pager object passed as the first
  52745. ** argument.
  52746. **
  52747. ** The job of this function is to make pPg clean by writing its contents
  52748. ** out to the database file, if possible. This may involve syncing the
  52749. ** journal file.
  52750. **
  52751. ** If successful, sqlite3PcacheMakeClean() is called on the page and
  52752. ** SQLITE_OK returned. If an IO error occurs while trying to make the
  52753. ** page clean, the IO error code is returned. If the page cannot be
  52754. ** made clean for some other reason, but no error occurs, then SQLITE_OK
  52755. ** is returned by sqlite3PcacheMakeClean() is not called.
  52756. */
  52757. static int pagerStress(void *p, PgHdr *pPg){
  52758. Pager *pPager = (Pager *)p;
  52759. int rc = SQLITE_OK;
  52760. assert( pPg->pPager==pPager );
  52761. assert( pPg->flags&PGHDR_DIRTY );
  52762. /* The doNotSpill NOSYNC bit is set during times when doing a sync of
  52763. ** journal (and adding a new header) is not allowed. This occurs
  52764. ** during calls to sqlite3PagerWrite() while trying to journal multiple
  52765. ** pages belonging to the same sector.
  52766. **
  52767. ** The doNotSpill ROLLBACK and OFF bits inhibits all cache spilling
  52768. ** regardless of whether or not a sync is required. This is set during
  52769. ** a rollback or by user request, respectively.
  52770. **
  52771. ** Spilling is also prohibited when in an error state since that could
  52772. ** lead to database corruption. In the current implementation it
  52773. ** is impossible for sqlite3PcacheFetch() to be called with createFlag==3
  52774. ** while in the error state, hence it is impossible for this routine to
  52775. ** be called in the error state. Nevertheless, we include a NEVER()
  52776. ** test for the error state as a safeguard against future changes.
  52777. */
  52778. if( NEVER(pPager->errCode) ) return SQLITE_OK;
  52779. testcase( pPager->doNotSpill & SPILLFLAG_ROLLBACK );
  52780. testcase( pPager->doNotSpill & SPILLFLAG_OFF );
  52781. testcase( pPager->doNotSpill & SPILLFLAG_NOSYNC );
  52782. if( pPager->doNotSpill
  52783. && ((pPager->doNotSpill & (SPILLFLAG_ROLLBACK|SPILLFLAG_OFF))!=0
  52784. || (pPg->flags & PGHDR_NEED_SYNC)!=0)
  52785. ){
  52786. return SQLITE_OK;
  52787. }
  52788. pPager->aStat[PAGER_STAT_SPILL]++;
  52789. pPg->pDirty = 0;
  52790. if( pagerUseWal(pPager) ){
  52791. /* Write a single frame for this page to the log. */
  52792. rc = subjournalPageIfRequired(pPg);
  52793. if( rc==SQLITE_OK ){
  52794. rc = pagerWalFrames(pPager, pPg, 0, 0);
  52795. }
  52796. }else{
  52797. #ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE
  52798. if( pPager->tempFile==0 ){
  52799. rc = sqlite3JournalCreate(pPager->jfd);
  52800. if( rc!=SQLITE_OK ) return pager_error(pPager, rc);
  52801. }
  52802. #endif
  52803. /* Sync the journal file if required. */
  52804. if( pPg->flags&PGHDR_NEED_SYNC
  52805. || pPager->eState==PAGER_WRITER_CACHEMOD
  52806. ){
  52807. rc = syncJournal(pPager, 1);
  52808. }
  52809. /* Write the contents of the page out to the database file. */
  52810. if( rc==SQLITE_OK ){
  52811. assert( (pPg->flags&PGHDR_NEED_SYNC)==0 );
  52812. rc = pager_write_pagelist(pPager, pPg);
  52813. }
  52814. }
  52815. /* Mark the page as clean. */
  52816. if( rc==SQLITE_OK ){
  52817. PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno));
  52818. sqlite3PcacheMakeClean(pPg);
  52819. }
  52820. return pager_error(pPager, rc);
  52821. }
  52822. /*
  52823. ** Flush all unreferenced dirty pages to disk.
  52824. */
  52825. SQLITE_PRIVATE int sqlite3PagerFlush(Pager *pPager){
  52826. int rc = pPager->errCode;
  52827. if( !MEMDB ){
  52828. PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
  52829. assert( assert_pager_state(pPager) );
  52830. while( rc==SQLITE_OK && pList ){
  52831. PgHdr *pNext = pList->pDirty;
  52832. if( pList->nRef==0 ){
  52833. rc = pagerStress((void*)pPager, pList);
  52834. }
  52835. pList = pNext;
  52836. }
  52837. }
  52838. return rc;
  52839. }
  52840. /*
  52841. ** Allocate and initialize a new Pager object and put a pointer to it
  52842. ** in *ppPager. The pager should eventually be freed by passing it
  52843. ** to sqlite3PagerClose().
  52844. **
  52845. ** The zFilename argument is the path to the database file to open.
  52846. ** If zFilename is NULL then a randomly-named temporary file is created
  52847. ** and used as the file to be cached. Temporary files are be deleted
  52848. ** automatically when they are closed. If zFilename is ":memory:" then
  52849. ** all information is held in cache. It is never written to disk.
  52850. ** This can be used to implement an in-memory database.
  52851. **
  52852. ** The nExtra parameter specifies the number of bytes of space allocated
  52853. ** along with each page reference. This space is available to the user
  52854. ** via the sqlite3PagerGetExtra() API. When a new page is allocated, the
  52855. ** first 8 bytes of this space are zeroed but the remainder is uninitialized.
  52856. ** (The extra space is used by btree as the MemPage object.)
  52857. **
  52858. ** The flags argument is used to specify properties that affect the
  52859. ** operation of the pager. It should be passed some bitwise combination
  52860. ** of the PAGER_* flags.
  52861. **
  52862. ** The vfsFlags parameter is a bitmask to pass to the flags parameter
  52863. ** of the xOpen() method of the supplied VFS when opening files.
  52864. **
  52865. ** If the pager object is allocated and the specified file opened
  52866. ** successfully, SQLITE_OK is returned and *ppPager set to point to
  52867. ** the new pager object. If an error occurs, *ppPager is set to NULL
  52868. ** and error code returned. This function may return SQLITE_NOMEM
  52869. ** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or
  52870. ** various SQLITE_IO_XXX errors.
  52871. */
  52872. SQLITE_PRIVATE int sqlite3PagerOpen(
  52873. sqlite3_vfs *pVfs, /* The virtual file system to use */
  52874. Pager **ppPager, /* OUT: Return the Pager structure here */
  52875. const char *zFilename, /* Name of the database file to open */
  52876. int nExtra, /* Extra bytes append to each in-memory page */
  52877. int flags, /* flags controlling this file */
  52878. int vfsFlags, /* flags passed through to sqlite3_vfs.xOpen() */
  52879. void (*xReinit)(DbPage*) /* Function to reinitialize pages */
  52880. ){
  52881. u8 *pPtr;
  52882. Pager *pPager = 0; /* Pager object to allocate and return */
  52883. int rc = SQLITE_OK; /* Return code */
  52884. int tempFile = 0; /* True for temp files (incl. in-memory files) */
  52885. int memDb = 0; /* True if this is an in-memory file */
  52886. #ifdef SQLITE_ENABLE_DESERIALIZE
  52887. int memJM = 0; /* Memory journal mode */
  52888. #else
  52889. # define memJM 0
  52890. #endif
  52891. int readOnly = 0; /* True if this is a read-only file */
  52892. int journalFileSize; /* Bytes to allocate for each journal fd */
  52893. char *zPathname = 0; /* Full path to database file */
  52894. int nPathname = 0; /* Number of bytes in zPathname */
  52895. int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */
  52896. int pcacheSize = sqlite3PcacheSize(); /* Bytes to allocate for PCache */
  52897. u32 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE; /* Default page size */
  52898. const char *zUri = 0; /* URI args to copy */
  52899. int nUriByte = 1; /* Number of bytes of URI args at *zUri */
  52900. int nUri = 0; /* Number of URI parameters */
  52901. /* Figure out how much space is required for each journal file-handle
  52902. ** (there are two of them, the main journal and the sub-journal). */
  52903. journalFileSize = ROUND8(sqlite3JournalSize(pVfs));
  52904. /* Set the output variable to NULL in case an error occurs. */
  52905. *ppPager = 0;
  52906. #ifndef SQLITE_OMIT_MEMORYDB
  52907. if( flags & PAGER_MEMORY ){
  52908. memDb = 1;
  52909. if( zFilename && zFilename[0] ){
  52910. zPathname = sqlite3DbStrDup(0, zFilename);
  52911. if( zPathname==0 ) return SQLITE_NOMEM_BKPT;
  52912. nPathname = sqlite3Strlen30(zPathname);
  52913. zFilename = 0;
  52914. }
  52915. }
  52916. #endif
  52917. /* Compute and store the full pathname in an allocated buffer pointed
  52918. ** to by zPathname, length nPathname. Or, if this is a temporary file,
  52919. ** leave both nPathname and zPathname set to 0.
  52920. */
  52921. if( zFilename && zFilename[0] ){
  52922. const char *z;
  52923. nPathname = pVfs->mxPathname+1;
  52924. zPathname = sqlite3DbMallocRaw(0, nPathname*2);
  52925. if( zPathname==0 ){
  52926. return SQLITE_NOMEM_BKPT;
  52927. }
  52928. zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
  52929. rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
  52930. if( rc!=SQLITE_OK ){
  52931. if( rc==SQLITE_OK_SYMLINK ){
  52932. if( vfsFlags & SQLITE_OPEN_NOFOLLOW ){
  52933. rc = SQLITE_CANTOPEN_SYMLINK;
  52934. }else{
  52935. rc = SQLITE_OK;
  52936. }
  52937. }
  52938. }
  52939. nPathname = sqlite3Strlen30(zPathname);
  52940. z = zUri = &zFilename[sqlite3Strlen30(zFilename)+1];
  52941. while( *z ){
  52942. z += strlen(z)+1;
  52943. z += strlen(z)+1;
  52944. nUri++;
  52945. }
  52946. nUriByte = (int)(&z[1] - zUri);
  52947. assert( nUriByte>=1 );
  52948. if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){
  52949. /* This branch is taken when the journal path required by
  52950. ** the database being opened will be more than pVfs->mxPathname
  52951. ** bytes in length. This means the database cannot be opened,
  52952. ** as it will not be possible to open the journal file or even
  52953. ** check for a hot-journal before reading.
  52954. */
  52955. rc = SQLITE_CANTOPEN_BKPT;
  52956. }
  52957. if( rc!=SQLITE_OK ){
  52958. sqlite3DbFree(0, zPathname);
  52959. return rc;
  52960. }
  52961. }
  52962. /* Allocate memory for the Pager structure, PCache object, the
  52963. ** three file descriptors, the database file name and the journal
  52964. ** file name. The layout in memory is as follows:
  52965. **
  52966. ** Pager object (sizeof(Pager) bytes)
  52967. ** PCache object (sqlite3PcacheSize() bytes)
  52968. ** Database file handle (pVfs->szOsFile bytes)
  52969. ** Sub-journal file handle (journalFileSize bytes)
  52970. ** Main journal file handle (journalFileSize bytes)
  52971. ** Ptr back to the Pager (sizeof(Pager*) bytes)
  52972. ** \0\0\0\0 database prefix (4 bytes)
  52973. ** Database file name (nPathname+1 bytes)
  52974. ** URI query parameters (nUriByte bytes)
  52975. ** Journal filename (nPathname+8+1 bytes)
  52976. ** WAL filename (nPathname+4+1 bytes)
  52977. ** \0\0\0 terminator (3 bytes)
  52978. **
  52979. ** Some 3rd-party software, over which we have no control, depends on
  52980. ** the specific order of the filenames and the \0 separators between them
  52981. ** so that it can (for example) find the database filename given the WAL
  52982. ** filename without using the sqlite3_filename_database() API. This is a
  52983. ** misuse of SQLite and a bug in the 3rd-party software, but the 3rd-party
  52984. ** software is in widespread use, so we try to avoid changing the filename
  52985. ** order and formatting if possible. In particular, the details of the
  52986. ** filename format expected by 3rd-party software should be as follows:
  52987. **
  52988. ** - Main Database Path
  52989. ** - \0
  52990. ** - Multiple URI components consisting of:
  52991. ** - Key
  52992. ** - \0
  52993. ** - Value
  52994. ** - \0
  52995. ** - \0
  52996. ** - Journal Path
  52997. ** - \0
  52998. ** - WAL Path (zWALName)
  52999. ** - \0
  53000. **
  53001. ** The sqlite3_create_filename() interface and the databaseFilename() utility
  53002. ** that is used by sqlite3_filename_database() and kin also depend on the
  53003. ** specific formatting and order of the various filenames, so if the format
  53004. ** changes here, be sure to change it there as well.
  53005. */
  53006. pPtr = (u8 *)sqlite3MallocZero(
  53007. ROUND8(sizeof(*pPager)) + /* Pager structure */
  53008. ROUND8(pcacheSize) + /* PCache object */
  53009. ROUND8(pVfs->szOsFile) + /* The main db file */
  53010. journalFileSize * 2 + /* The two journal files */
  53011. sizeof(pPager) + /* Space to hold a pointer */
  53012. 4 + /* Database prefix */
  53013. nPathname + 1 + /* database filename */
  53014. nUriByte + /* query parameters */
  53015. nPathname + 8 + 1 + /* Journal filename */
  53016. #ifndef SQLITE_OMIT_WAL
  53017. nPathname + 4 + 1 + /* WAL filename */
  53018. #endif
  53019. 3 /* Terminator */
  53020. );
  53021. assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) );
  53022. if( !pPtr ){
  53023. sqlite3DbFree(0, zPathname);
  53024. return SQLITE_NOMEM_BKPT;
  53025. }
  53026. pPager = (Pager*)pPtr; pPtr += ROUND8(sizeof(*pPager));
  53027. pPager->pPCache = (PCache*)pPtr; pPtr += ROUND8(pcacheSize);
  53028. pPager->fd = (sqlite3_file*)pPtr; pPtr += ROUND8(pVfs->szOsFile);
  53029. pPager->sjfd = (sqlite3_file*)pPtr; pPtr += journalFileSize;
  53030. pPager->jfd = (sqlite3_file*)pPtr; pPtr += journalFileSize;
  53031. assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );
  53032. memcpy(pPtr, &pPager, sizeof(pPager)); pPtr += sizeof(pPager);
  53033. /* Fill in the Pager.zFilename and pPager.zQueryParam fields */
  53034. pPtr += 4; /* Skip zero prefix */
  53035. pPager->zFilename = (char*)pPtr;
  53036. if( nPathname>0 ){
  53037. memcpy(pPtr, zPathname, nPathname); pPtr += nPathname + 1;
  53038. if( zUri ){
  53039. memcpy(pPtr, zUri, nUriByte); pPtr += nUriByte;
  53040. }else{
  53041. pPtr++;
  53042. }
  53043. }
  53044. /* Fill in Pager.zJournal */
  53045. if( nPathname>0 ){
  53046. pPager->zJournal = (char*)pPtr;
  53047. memcpy(pPtr, zPathname, nPathname); pPtr += nPathname;
  53048. memcpy(pPtr, "-journal",8); pPtr += 8 + 1;
  53049. #ifdef SQLITE_ENABLE_8_3_NAMES
  53050. sqlite3FileSuffix3(zFilename,pPager->zJournal);
  53051. pPtr = (u8*)(pPager->zJournal + sqlite3Strlen30(pPager->zJournal)+1);
  53052. #endif
  53053. }else{
  53054. pPager->zJournal = 0;
  53055. }
  53056. #ifndef SQLITE_OMIT_WAL
  53057. /* Fill in Pager.zWal */
  53058. if( nPathname>0 ){
  53059. pPager->zWal = (char*)pPtr;
  53060. memcpy(pPtr, zPathname, nPathname); pPtr += nPathname;
  53061. memcpy(pPtr, "-wal", 4); pPtr += 4 + 1;
  53062. #ifdef SQLITE_ENABLE_8_3_NAMES
  53063. sqlite3FileSuffix3(zFilename, pPager->zWal);
  53064. pPtr = (u8*)(pPager->zWal + sqlite3Strlen30(pPager->zWal)+1);
  53065. #endif
  53066. }else{
  53067. pPager->zWal = 0;
  53068. }
  53069. #endif
  53070. if( nPathname ) sqlite3DbFree(0, zPathname);
  53071. pPager->pVfs = pVfs;
  53072. pPager->vfsFlags = vfsFlags;
  53073. /* Open the pager file.
  53074. */
  53075. if( zFilename && zFilename[0] ){
  53076. int fout = 0; /* VFS flags returned by xOpen() */
  53077. rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
  53078. assert( !memDb );
  53079. #ifdef SQLITE_ENABLE_DESERIALIZE
  53080. memJM = (fout&SQLITE_OPEN_MEMORY)!=0;
  53081. #endif
  53082. readOnly = (fout&SQLITE_OPEN_READONLY)!=0;
  53083. /* If the file was successfully opened for read/write access,
  53084. ** choose a default page size in case we have to create the
  53085. ** database file. The default page size is the maximum of:
  53086. **
  53087. ** + SQLITE_DEFAULT_PAGE_SIZE,
  53088. ** + The value returned by sqlite3OsSectorSize()
  53089. ** + The largest page size that can be written atomically.
  53090. */
  53091. if( rc==SQLITE_OK ){
  53092. int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
  53093. if( !readOnly ){
  53094. setSectorSize(pPager);
  53095. assert(SQLITE_DEFAULT_PAGE_SIZE<=SQLITE_MAX_DEFAULT_PAGE_SIZE);
  53096. if( szPageDflt<pPager->sectorSize ){
  53097. if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
  53098. szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
  53099. }else{
  53100. szPageDflt = (u32)pPager->sectorSize;
  53101. }
  53102. }
  53103. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  53104. {
  53105. int ii;
  53106. assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
  53107. assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
  53108. assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
  53109. for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
  53110. if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){
  53111. szPageDflt = ii;
  53112. }
  53113. }
  53114. }
  53115. #endif
  53116. }
  53117. pPager->noLock = sqlite3_uri_boolean(pPager->zFilename, "nolock", 0);
  53118. if( (iDc & SQLITE_IOCAP_IMMUTABLE)!=0
  53119. || sqlite3_uri_boolean(pPager->zFilename, "immutable", 0) ){
  53120. vfsFlags |= SQLITE_OPEN_READONLY;
  53121. goto act_like_temp_file;
  53122. }
  53123. }
  53124. }else{
  53125. /* If a temporary file is requested, it is not opened immediately.
  53126. ** In this case we accept the default page size and delay actually
  53127. ** opening the file until the first call to OsWrite().
  53128. **
  53129. ** This branch is also run for an in-memory database. An in-memory
  53130. ** database is the same as a temp-file that is never written out to
  53131. ** disk and uses an in-memory rollback journal.
  53132. **
  53133. ** This branch also runs for files marked as immutable.
  53134. */
  53135. act_like_temp_file:
  53136. tempFile = 1;
  53137. pPager->eState = PAGER_READER; /* Pretend we already have a lock */
  53138. pPager->eLock = EXCLUSIVE_LOCK; /* Pretend we are in EXCLUSIVE mode */
  53139. pPager->noLock = 1; /* Do no locking */
  53140. readOnly = (vfsFlags&SQLITE_OPEN_READONLY);
  53141. }
  53142. /* The following call to PagerSetPagesize() serves to set the value of
  53143. ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer.
  53144. */
  53145. if( rc==SQLITE_OK ){
  53146. assert( pPager->memDb==0 );
  53147. rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1);
  53148. testcase( rc!=SQLITE_OK );
  53149. }
  53150. /* Initialize the PCache object. */
  53151. if( rc==SQLITE_OK ){
  53152. nExtra = ROUND8(nExtra);
  53153. assert( nExtra>=8 && nExtra<1000 );
  53154. rc = sqlite3PcacheOpen(szPageDflt, nExtra, !memDb,
  53155. !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);
  53156. }
  53157. /* If an error occurred above, free the Pager structure and close the file.
  53158. */
  53159. if( rc!=SQLITE_OK ){
  53160. sqlite3OsClose(pPager->fd);
  53161. sqlite3PageFree(pPager->pTmpSpace);
  53162. sqlite3_free(pPager);
  53163. return rc;
  53164. }
  53165. PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename));
  53166. IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
  53167. pPager->useJournal = (u8)useJournal;
  53168. /* pPager->stmtOpen = 0; */
  53169. /* pPager->stmtInUse = 0; */
  53170. /* pPager->nRef = 0; */
  53171. /* pPager->stmtSize = 0; */
  53172. /* pPager->stmtJSize = 0; */
  53173. /* pPager->nPage = 0; */
  53174. pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
  53175. /* pPager->state = PAGER_UNLOCK; */
  53176. /* pPager->errMask = 0; */
  53177. pPager->tempFile = (u8)tempFile;
  53178. assert( tempFile==PAGER_LOCKINGMODE_NORMAL
  53179. || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
  53180. assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
  53181. pPager->exclusiveMode = (u8)tempFile;
  53182. pPager->changeCountDone = pPager->tempFile;
  53183. pPager->memDb = (u8)memDb;
  53184. pPager->readOnly = (u8)readOnly;
  53185. assert( useJournal || pPager->tempFile );
  53186. pPager->noSync = pPager->tempFile;
  53187. if( pPager->noSync ){
  53188. assert( pPager->fullSync==0 );
  53189. assert( pPager->extraSync==0 );
  53190. assert( pPager->syncFlags==0 );
  53191. assert( pPager->walSyncFlags==0 );
  53192. }else{
  53193. pPager->fullSync = 1;
  53194. pPager->extraSync = 0;
  53195. pPager->syncFlags = SQLITE_SYNC_NORMAL;
  53196. pPager->walSyncFlags = SQLITE_SYNC_NORMAL | (SQLITE_SYNC_NORMAL<<2);
  53197. }
  53198. /* pPager->pFirst = 0; */
  53199. /* pPager->pFirstSynced = 0; */
  53200. /* pPager->pLast = 0; */
  53201. pPager->nExtra = (u16)nExtra;
  53202. pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
  53203. assert( isOpen(pPager->fd) || tempFile );
  53204. setSectorSize(pPager);
  53205. if( !useJournal ){
  53206. pPager->journalMode = PAGER_JOURNALMODE_OFF;
  53207. }else if( memDb || memJM ){
  53208. pPager->journalMode = PAGER_JOURNALMODE_MEMORY;
  53209. }
  53210. /* pPager->xBusyHandler = 0; */
  53211. /* pPager->pBusyHandlerArg = 0; */
  53212. pPager->xReiniter = xReinit;
  53213. setGetterMethod(pPager);
  53214. /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
  53215. /* pPager->szMmap = SQLITE_DEFAULT_MMAP_SIZE // will be set by btree.c */
  53216. *ppPager = pPager;
  53217. return SQLITE_OK;
  53218. }
  53219. /*
  53220. ** Return the sqlite3_file for the main database given the name
  53221. ** of the corresonding WAL or Journal name as passed into
  53222. ** xOpen.
  53223. */
  53224. SQLITE_API sqlite3_file *sqlite3_database_file_object(const char *zName){
  53225. Pager *pPager;
  53226. while( zName[-1]!=0 || zName[-2]!=0 || zName[-3]!=0 || zName[-4]!=0 ){
  53227. zName--;
  53228. }
  53229. pPager = *(Pager**)(zName - 4 - sizeof(Pager*));
  53230. return pPager->fd;
  53231. }
  53232. /*
  53233. ** This function is called after transitioning from PAGER_UNLOCK to
  53234. ** PAGER_SHARED state. It tests if there is a hot journal present in
  53235. ** the file-system for the given pager. A hot journal is one that
  53236. ** needs to be played back. According to this function, a hot-journal
  53237. ** file exists if the following criteria are met:
  53238. **
  53239. ** * The journal file exists in the file system, and
  53240. ** * No process holds a RESERVED or greater lock on the database file, and
  53241. ** * The database file itself is greater than 0 bytes in size, and
  53242. ** * The first byte of the journal file exists and is not 0x00.
  53243. **
  53244. ** If the current size of the database file is 0 but a journal file
  53245. ** exists, that is probably an old journal left over from a prior
  53246. ** database with the same name. In this case the journal file is
  53247. ** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK
  53248. ** is returned.
  53249. **
  53250. ** This routine does not check if there is a master journal filename
  53251. ** at the end of the file. If there is, and that master journal file
  53252. ** does not exist, then the journal file is not really hot. In this
  53253. ** case this routine will return a false-positive. The pager_playback()
  53254. ** routine will discover that the journal file is not really hot and
  53255. ** will not roll it back.
  53256. **
  53257. ** If a hot-journal file is found to exist, *pExists is set to 1 and
  53258. ** SQLITE_OK returned. If no hot-journal file is present, *pExists is
  53259. ** set to 0 and SQLITE_OK returned. If an IO error occurs while trying
  53260. ** to determine whether or not a hot-journal file exists, the IO error
  53261. ** code is returned and the value of *pExists is undefined.
  53262. */
  53263. static int hasHotJournal(Pager *pPager, int *pExists){
  53264. sqlite3_vfs * const pVfs = pPager->pVfs;
  53265. int rc = SQLITE_OK; /* Return code */
  53266. int exists = 1; /* True if a journal file is present */
  53267. int jrnlOpen = !!isOpen(pPager->jfd);
  53268. assert( pPager->useJournal );
  53269. assert( isOpen(pPager->fd) );
  53270. assert( pPager->eState==PAGER_OPEN );
  53271. assert( jrnlOpen==0 || ( sqlite3OsDeviceCharacteristics(pPager->jfd) &
  53272. SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
  53273. ));
  53274. *pExists = 0;
  53275. if( !jrnlOpen ){
  53276. rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
  53277. }
  53278. if( rc==SQLITE_OK && exists ){
  53279. int locked = 0; /* True if some process holds a RESERVED lock */
  53280. /* Race condition here: Another process might have been holding the
  53281. ** the RESERVED lock and have a journal open at the sqlite3OsAccess()
  53282. ** call above, but then delete the journal and drop the lock before
  53283. ** we get to the following sqlite3OsCheckReservedLock() call. If that
  53284. ** is the case, this routine might think there is a hot journal when
  53285. ** in fact there is none. This results in a false-positive which will
  53286. ** be dealt with by the playback routine. Ticket #3883.
  53287. */
  53288. rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
  53289. if( rc==SQLITE_OK && !locked ){
  53290. Pgno nPage; /* Number of pages in database file */
  53291. assert( pPager->tempFile==0 );
  53292. rc = pagerPagecount(pPager, &nPage);
  53293. if( rc==SQLITE_OK ){
  53294. /* If the database is zero pages in size, that means that either (1) the
  53295. ** journal is a remnant from a prior database with the same name where
  53296. ** the database file but not the journal was deleted, or (2) the initial
  53297. ** transaction that populates a new database is being rolled back.
  53298. ** In either case, the journal file can be deleted. However, take care
  53299. ** not to delete the journal file if it is already open due to
  53300. ** journal_mode=PERSIST.
  53301. */
  53302. if( nPage==0 && !jrnlOpen ){
  53303. sqlite3BeginBenignMalloc();
  53304. if( pagerLockDb(pPager, RESERVED_LOCK)==SQLITE_OK ){
  53305. sqlite3OsDelete(pVfs, pPager->zJournal, 0);
  53306. if( !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
  53307. }
  53308. sqlite3EndBenignMalloc();
  53309. }else{
  53310. /* The journal file exists and no other connection has a reserved
  53311. ** or greater lock on the database file. Now check that there is
  53312. ** at least one non-zero bytes at the start of the journal file.
  53313. ** If there is, then we consider this journal to be hot. If not,
  53314. ** it can be ignored.
  53315. */
  53316. if( !jrnlOpen ){
  53317. int f = SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL;
  53318. rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f);
  53319. }
  53320. if( rc==SQLITE_OK ){
  53321. u8 first = 0;
  53322. rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0);
  53323. if( rc==SQLITE_IOERR_SHORT_READ ){
  53324. rc = SQLITE_OK;
  53325. }
  53326. if( !jrnlOpen ){
  53327. sqlite3OsClose(pPager->jfd);
  53328. }
  53329. *pExists = (first!=0);
  53330. }else if( rc==SQLITE_CANTOPEN ){
  53331. /* If we cannot open the rollback journal file in order to see if
  53332. ** it has a zero header, that might be due to an I/O error, or
  53333. ** it might be due to the race condition described above and in
  53334. ** ticket #3883. Either way, assume that the journal is hot.
  53335. ** This might be a false positive. But if it is, then the
  53336. ** automatic journal playback and recovery mechanism will deal
  53337. ** with it under an EXCLUSIVE lock where we do not need to
  53338. ** worry so much with race conditions.
  53339. */
  53340. *pExists = 1;
  53341. rc = SQLITE_OK;
  53342. }
  53343. }
  53344. }
  53345. }
  53346. }
  53347. return rc;
  53348. }
  53349. /*
  53350. ** This function is called to obtain a shared lock on the database file.
  53351. ** It is illegal to call sqlite3PagerGet() until after this function
  53352. ** has been successfully called. If a shared-lock is already held when
  53353. ** this function is called, it is a no-op.
  53354. **
  53355. ** The following operations are also performed by this function.
  53356. **
  53357. ** 1) If the pager is currently in PAGER_OPEN state (no lock held
  53358. ** on the database file), then an attempt is made to obtain a
  53359. ** SHARED lock on the database file. Immediately after obtaining
  53360. ** the SHARED lock, the file-system is checked for a hot-journal,
  53361. ** which is played back if present. Following any hot-journal
  53362. ** rollback, the contents of the cache are validated by checking
  53363. ** the 'change-counter' field of the database file header and
  53364. ** discarded if they are found to be invalid.
  53365. **
  53366. ** 2) If the pager is running in exclusive-mode, and there are currently
  53367. ** no outstanding references to any pages, and is in the error state,
  53368. ** then an attempt is made to clear the error state by discarding
  53369. ** the contents of the page cache and rolling back any open journal
  53370. ** file.
  53371. **
  53372. ** If everything is successful, SQLITE_OK is returned. If an IO error
  53373. ** occurs while locking the database, checking for a hot-journal file or
  53374. ** rolling back a journal file, the IO error code is returned.
  53375. */
  53376. SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){
  53377. int rc = SQLITE_OK; /* Return code */
  53378. /* This routine is only called from b-tree and only when there are no
  53379. ** outstanding pages. This implies that the pager state should either
  53380. ** be OPEN or READER. READER is only possible if the pager is or was in
  53381. ** exclusive access mode. */
  53382. assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
  53383. assert( assert_pager_state(pPager) );
  53384. assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
  53385. assert( pPager->errCode==SQLITE_OK );
  53386. if( !pagerUseWal(pPager) && pPager->eState==PAGER_OPEN ){
  53387. int bHotJournal = 1; /* True if there exists a hot journal-file */
  53388. assert( !MEMDB );
  53389. assert( pPager->tempFile==0 || pPager->eLock==EXCLUSIVE_LOCK );
  53390. rc = pager_wait_on_lock(pPager, SHARED_LOCK);
  53391. if( rc!=SQLITE_OK ){
  53392. assert( pPager->eLock==NO_LOCK || pPager->eLock==UNKNOWN_LOCK );
  53393. goto failed;
  53394. }
  53395. /* If a journal file exists, and there is no RESERVED lock on the
  53396. ** database file, then it either needs to be played back or deleted.
  53397. */
  53398. if( pPager->eLock<=SHARED_LOCK ){
  53399. rc = hasHotJournal(pPager, &bHotJournal);
  53400. }
  53401. if( rc!=SQLITE_OK ){
  53402. goto failed;
  53403. }
  53404. if( bHotJournal ){
  53405. if( pPager->readOnly ){
  53406. rc = SQLITE_READONLY_ROLLBACK;
  53407. goto failed;
  53408. }
  53409. /* Get an EXCLUSIVE lock on the database file. At this point it is
  53410. ** important that a RESERVED lock is not obtained on the way to the
  53411. ** EXCLUSIVE lock. If it were, another process might open the
  53412. ** database file, detect the RESERVED lock, and conclude that the
  53413. ** database is safe to read while this process is still rolling the
  53414. ** hot-journal back.
  53415. **
  53416. ** Because the intermediate RESERVED lock is not requested, any
  53417. ** other process attempting to access the database file will get to
  53418. ** this point in the code and fail to obtain its own EXCLUSIVE lock
  53419. ** on the database file.
  53420. **
  53421. ** Unless the pager is in locking_mode=exclusive mode, the lock is
  53422. ** downgraded to SHARED_LOCK before this function returns.
  53423. */
  53424. rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
  53425. if( rc!=SQLITE_OK ){
  53426. goto failed;
  53427. }
  53428. /* If it is not already open and the file exists on disk, open the
  53429. ** journal for read/write access. Write access is required because
  53430. ** in exclusive-access mode the file descriptor will be kept open
  53431. ** and possibly used for a transaction later on. Also, write-access
  53432. ** is usually required to finalize the journal in journal_mode=persist
  53433. ** mode (and also for journal_mode=truncate on some systems).
  53434. **
  53435. ** If the journal does not exist, it usually means that some
  53436. ** other connection managed to get in and roll it back before
  53437. ** this connection obtained the exclusive lock above. Or, it
  53438. ** may mean that the pager was in the error-state when this
  53439. ** function was called and the journal file does not exist.
  53440. */
  53441. if( !isOpen(pPager->jfd) ){
  53442. sqlite3_vfs * const pVfs = pPager->pVfs;
  53443. int bExists; /* True if journal file exists */
  53444. rc = sqlite3OsAccess(
  53445. pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &bExists);
  53446. if( rc==SQLITE_OK && bExists ){
  53447. int fout = 0;
  53448. int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
  53449. assert( !pPager->tempFile );
  53450. rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
  53451. assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
  53452. if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){
  53453. rc = SQLITE_CANTOPEN_BKPT;
  53454. sqlite3OsClose(pPager->jfd);
  53455. }
  53456. }
  53457. }
  53458. /* Playback and delete the journal. Drop the database write
  53459. ** lock and reacquire the read lock. Purge the cache before
  53460. ** playing back the hot-journal so that we don't end up with
  53461. ** an inconsistent cache. Sync the hot journal before playing
  53462. ** it back since the process that crashed and left the hot journal
  53463. ** probably did not sync it and we are required to always sync
  53464. ** the journal before playing it back.
  53465. */
  53466. if( isOpen(pPager->jfd) ){
  53467. assert( rc==SQLITE_OK );
  53468. rc = pagerSyncHotJournal(pPager);
  53469. if( rc==SQLITE_OK ){
  53470. rc = pager_playback(pPager, !pPager->tempFile);
  53471. pPager->eState = PAGER_OPEN;
  53472. }
  53473. }else if( !pPager->exclusiveMode ){
  53474. pagerUnlockDb(pPager, SHARED_LOCK);
  53475. }
  53476. if( rc!=SQLITE_OK ){
  53477. /* This branch is taken if an error occurs while trying to open
  53478. ** or roll back a hot-journal while holding an EXCLUSIVE lock. The
  53479. ** pager_unlock() routine will be called before returning to unlock
  53480. ** the file. If the unlock attempt fails, then Pager.eLock must be
  53481. ** set to UNKNOWN_LOCK (see the comment above the #define for
  53482. ** UNKNOWN_LOCK above for an explanation).
  53483. **
  53484. ** In order to get pager_unlock() to do this, set Pager.eState to
  53485. ** PAGER_ERROR now. This is not actually counted as a transition
  53486. ** to ERROR state in the state diagram at the top of this file,
  53487. ** since we know that the same call to pager_unlock() will very
  53488. ** shortly transition the pager object to the OPEN state. Calling
  53489. ** assert_pager_state() would fail now, as it should not be possible
  53490. ** to be in ERROR state when there are zero outstanding page
  53491. ** references.
  53492. */
  53493. pager_error(pPager, rc);
  53494. goto failed;
  53495. }
  53496. assert( pPager->eState==PAGER_OPEN );
  53497. assert( (pPager->eLock==SHARED_LOCK)
  53498. || (pPager->exclusiveMode && pPager->eLock>SHARED_LOCK)
  53499. );
  53500. }
  53501. if( !pPager->tempFile && pPager->hasHeldSharedLock ){
  53502. /* The shared-lock has just been acquired then check to
  53503. ** see if the database has been modified. If the database has changed,
  53504. ** flush the cache. The hasHeldSharedLock flag prevents this from
  53505. ** occurring on the very first access to a file, in order to save a
  53506. ** single unnecessary sqlite3OsRead() call at the start-up.
  53507. **
  53508. ** Database changes are detected by looking at 15 bytes beginning
  53509. ** at offset 24 into the file. The first 4 of these 16 bytes are
  53510. ** a 32-bit counter that is incremented with each change. The
  53511. ** other bytes change randomly with each file change when
  53512. ** a codec is in use.
  53513. **
  53514. ** There is a vanishingly small chance that a change will not be
  53515. ** detected. The chance of an undetected change is so small that
  53516. ** it can be neglected.
  53517. */
  53518. char dbFileVers[sizeof(pPager->dbFileVers)];
  53519. IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
  53520. rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
  53521. if( rc!=SQLITE_OK ){
  53522. if( rc!=SQLITE_IOERR_SHORT_READ ){
  53523. goto failed;
  53524. }
  53525. memset(dbFileVers, 0, sizeof(dbFileVers));
  53526. }
  53527. if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
  53528. pager_reset(pPager);
  53529. /* Unmap the database file. It is possible that external processes
  53530. ** may have truncated the database file and then extended it back
  53531. ** to its original size while this process was not holding a lock.
  53532. ** In this case there may exist a Pager.pMap mapping that appears
  53533. ** to be the right size but is not actually valid. Avoid this
  53534. ** possibility by unmapping the db here. */
  53535. if( USEFETCH(pPager) ){
  53536. sqlite3OsUnfetch(pPager->fd, 0, 0);
  53537. }
  53538. }
  53539. }
  53540. /* If there is a WAL file in the file-system, open this database in WAL
  53541. ** mode. Otherwise, the following function call is a no-op.
  53542. */
  53543. rc = pagerOpenWalIfPresent(pPager);
  53544. #ifndef SQLITE_OMIT_WAL
  53545. assert( pPager->pWal==0 || rc==SQLITE_OK );
  53546. #endif
  53547. }
  53548. if( pagerUseWal(pPager) ){
  53549. assert( rc==SQLITE_OK );
  53550. rc = pagerBeginReadTransaction(pPager);
  53551. }
  53552. if( pPager->tempFile==0 && pPager->eState==PAGER_OPEN && rc==SQLITE_OK ){
  53553. rc = pagerPagecount(pPager, &pPager->dbSize);
  53554. }
  53555. failed:
  53556. if( rc!=SQLITE_OK ){
  53557. assert( !MEMDB );
  53558. pager_unlock(pPager);
  53559. assert( pPager->eState==PAGER_OPEN );
  53560. }else{
  53561. pPager->eState = PAGER_READER;
  53562. pPager->hasHeldSharedLock = 1;
  53563. }
  53564. return rc;
  53565. }
  53566. /*
  53567. ** If the reference count has reached zero, rollback any active
  53568. ** transaction and unlock the pager.
  53569. **
  53570. ** Except, in locking_mode=EXCLUSIVE when there is nothing to in
  53571. ** the rollback journal, the unlock is not performed and there is
  53572. ** nothing to rollback, so this routine is a no-op.
  53573. */
  53574. static void pagerUnlockIfUnused(Pager *pPager){
  53575. if( sqlite3PcacheRefCount(pPager->pPCache)==0 ){
  53576. assert( pPager->nMmapOut==0 ); /* because page1 is never memory mapped */
  53577. pagerUnlockAndRollback(pPager);
  53578. }
  53579. }
  53580. /*
  53581. ** The page getter methods each try to acquire a reference to a
  53582. ** page with page number pgno. If the requested reference is
  53583. ** successfully obtained, it is copied to *ppPage and SQLITE_OK returned.
  53584. **
  53585. ** There are different implementations of the getter method depending
  53586. ** on the current state of the pager.
  53587. **
  53588. ** getPageNormal() -- The normal getter
  53589. ** getPageError() -- Used if the pager is in an error state
  53590. ** getPageMmap() -- Used if memory-mapped I/O is enabled
  53591. **
  53592. ** If the requested page is already in the cache, it is returned.
  53593. ** Otherwise, a new page object is allocated and populated with data
  53594. ** read from the database file. In some cases, the pcache module may
  53595. ** choose not to allocate a new page object and may reuse an existing
  53596. ** object with no outstanding references.
  53597. **
  53598. ** The extra data appended to a page is always initialized to zeros the
  53599. ** first time a page is loaded into memory. If the page requested is
  53600. ** already in the cache when this function is called, then the extra
  53601. ** data is left as it was when the page object was last used.
  53602. **
  53603. ** If the database image is smaller than the requested page or if
  53604. ** the flags parameter contains the PAGER_GET_NOCONTENT bit and the
  53605. ** requested page is not already stored in the cache, then no
  53606. ** actual disk read occurs. In this case the memory image of the
  53607. ** page is initialized to all zeros.
  53608. **
  53609. ** If PAGER_GET_NOCONTENT is true, it means that we do not care about
  53610. ** the contents of the page. This occurs in two scenarios:
  53611. **
  53612. ** a) When reading a free-list leaf page from the database, and
  53613. **
  53614. ** b) When a savepoint is being rolled back and we need to load
  53615. ** a new page into the cache to be filled with the data read
  53616. ** from the savepoint journal.
  53617. **
  53618. ** If PAGER_GET_NOCONTENT is true, then the data returned is zeroed instead
  53619. ** of being read from the database. Additionally, the bits corresponding
  53620. ** to pgno in Pager.pInJournal (bitvec of pages already written to the
  53621. ** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open
  53622. ** savepoints are set. This means if the page is made writable at any
  53623. ** point in the future, using a call to sqlite3PagerWrite(), its contents
  53624. ** will not be journaled. This saves IO.
  53625. **
  53626. ** The acquisition might fail for several reasons. In all cases,
  53627. ** an appropriate error code is returned and *ppPage is set to NULL.
  53628. **
  53629. ** See also sqlite3PagerLookup(). Both this routine and Lookup() attempt
  53630. ** to find a page in the in-memory cache first. If the page is not already
  53631. ** in memory, this routine goes to disk to read it in whereas Lookup()
  53632. ** just returns 0. This routine acquires a read-lock the first time it
  53633. ** has to go to disk, and could also playback an old journal if necessary.
  53634. ** Since Lookup() never goes to disk, it never has to deal with locks
  53635. ** or journal files.
  53636. */
  53637. static int getPageNormal(
  53638. Pager *pPager, /* The pager open on the database file */
  53639. Pgno pgno, /* Page number to fetch */
  53640. DbPage **ppPage, /* Write a pointer to the page here */
  53641. int flags /* PAGER_GET_XXX flags */
  53642. ){
  53643. int rc = SQLITE_OK;
  53644. PgHdr *pPg;
  53645. u8 noContent; /* True if PAGER_GET_NOCONTENT is set */
  53646. sqlite3_pcache_page *pBase;
  53647. assert( pPager->errCode==SQLITE_OK );
  53648. assert( pPager->eState>=PAGER_READER );
  53649. assert( assert_pager_state(pPager) );
  53650. assert( pPager->hasHeldSharedLock==1 );
  53651. if( pgno==0 ) return SQLITE_CORRUPT_BKPT;
  53652. pBase = sqlite3PcacheFetch(pPager->pPCache, pgno, 3);
  53653. if( pBase==0 ){
  53654. pPg = 0;
  53655. rc = sqlite3PcacheFetchStress(pPager->pPCache, pgno, &pBase);
  53656. if( rc!=SQLITE_OK ) goto pager_acquire_err;
  53657. if( pBase==0 ){
  53658. rc = SQLITE_NOMEM_BKPT;
  53659. goto pager_acquire_err;
  53660. }
  53661. }
  53662. pPg = *ppPage = sqlite3PcacheFetchFinish(pPager->pPCache, pgno, pBase);
  53663. assert( pPg==(*ppPage) );
  53664. assert( pPg->pgno==pgno );
  53665. assert( pPg->pPager==pPager || pPg->pPager==0 );
  53666. noContent = (flags & PAGER_GET_NOCONTENT)!=0;
  53667. if( pPg->pPager && !noContent ){
  53668. /* In this case the pcache already contains an initialized copy of
  53669. ** the page. Return without further ado. */
  53670. assert( pgno<=PAGER_MAX_PGNO && pgno!=PAGER_MJ_PGNO(pPager) );
  53671. pPager->aStat[PAGER_STAT_HIT]++;
  53672. return SQLITE_OK;
  53673. }else{
  53674. /* The pager cache has created a new page. Its content needs to
  53675. ** be initialized. But first some error checks:
  53676. **
  53677. ** (1) The maximum page number is 2^31
  53678. ** (2) Never try to fetch the locking page
  53679. */
  53680. if( pgno>PAGER_MAX_PGNO || pgno==PAGER_MJ_PGNO(pPager) ){
  53681. rc = SQLITE_CORRUPT_BKPT;
  53682. goto pager_acquire_err;
  53683. }
  53684. pPg->pPager = pPager;
  53685. assert( !isOpen(pPager->fd) || !MEMDB );
  53686. if( !isOpen(pPager->fd) || pPager->dbSize<pgno || noContent ){
  53687. if( pgno>pPager->mxPgno ){
  53688. rc = SQLITE_FULL;
  53689. goto pager_acquire_err;
  53690. }
  53691. if( noContent ){
  53692. /* Failure to set the bits in the InJournal bit-vectors is benign.
  53693. ** It merely means that we might do some extra work to journal a
  53694. ** page that does not need to be journaled. Nevertheless, be sure
  53695. ** to test the case where a malloc error occurs while trying to set
  53696. ** a bit in a bit vector.
  53697. */
  53698. sqlite3BeginBenignMalloc();
  53699. if( pgno<=pPager->dbOrigSize ){
  53700. TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno);
  53701. testcase( rc==SQLITE_NOMEM );
  53702. }
  53703. TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno);
  53704. testcase( rc==SQLITE_NOMEM );
  53705. sqlite3EndBenignMalloc();
  53706. }
  53707. memset(pPg->pData, 0, pPager->pageSize);
  53708. IOTRACE(("ZERO %p %d\n", pPager, pgno));
  53709. }else{
  53710. assert( pPg->pPager==pPager );
  53711. pPager->aStat[PAGER_STAT_MISS]++;
  53712. rc = readDbPage(pPg);
  53713. if( rc!=SQLITE_OK ){
  53714. goto pager_acquire_err;
  53715. }
  53716. }
  53717. pager_set_pagehash(pPg);
  53718. }
  53719. return SQLITE_OK;
  53720. pager_acquire_err:
  53721. assert( rc!=SQLITE_OK );
  53722. if( pPg ){
  53723. sqlite3PcacheDrop(pPg);
  53724. }
  53725. pagerUnlockIfUnused(pPager);
  53726. *ppPage = 0;
  53727. return rc;
  53728. }
  53729. #if SQLITE_MAX_MMAP_SIZE>0
  53730. /* The page getter for when memory-mapped I/O is enabled */
  53731. static int getPageMMap(
  53732. Pager *pPager, /* The pager open on the database file */
  53733. Pgno pgno, /* Page number to fetch */
  53734. DbPage **ppPage, /* Write a pointer to the page here */
  53735. int flags /* PAGER_GET_XXX flags */
  53736. ){
  53737. int rc = SQLITE_OK;
  53738. PgHdr *pPg = 0;
  53739. u32 iFrame = 0; /* Frame to read from WAL file */
  53740. /* It is acceptable to use a read-only (mmap) page for any page except
  53741. ** page 1 if there is no write-transaction open or the ACQUIRE_READONLY
  53742. ** flag was specified by the caller. And so long as the db is not a
  53743. ** temporary or in-memory database. */
  53744. const int bMmapOk = (pgno>1
  53745. && (pPager->eState==PAGER_READER || (flags & PAGER_GET_READONLY))
  53746. );
  53747. assert( USEFETCH(pPager) );
  53748. /* Optimization note: Adding the "pgno<=1" term before "pgno==0" here
  53749. ** allows the compiler optimizer to reuse the results of the "pgno>1"
  53750. ** test in the previous statement, and avoid testing pgno==0 in the
  53751. ** common case where pgno is large. */
  53752. if( pgno<=1 && pgno==0 ){
  53753. return SQLITE_CORRUPT_BKPT;
  53754. }
  53755. assert( pPager->eState>=PAGER_READER );
  53756. assert( assert_pager_state(pPager) );
  53757. assert( pPager->hasHeldSharedLock==1 );
  53758. assert( pPager->errCode==SQLITE_OK );
  53759. if( bMmapOk && pagerUseWal(pPager) ){
  53760. rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame);
  53761. if( rc!=SQLITE_OK ){
  53762. *ppPage = 0;
  53763. return rc;
  53764. }
  53765. }
  53766. if( bMmapOk && iFrame==0 ){
  53767. void *pData = 0;
  53768. rc = sqlite3OsFetch(pPager->fd,
  53769. (i64)(pgno-1) * pPager->pageSize, pPager->pageSize, &pData
  53770. );
  53771. if( rc==SQLITE_OK && pData ){
  53772. if( pPager->eState>PAGER_READER || pPager->tempFile ){
  53773. pPg = sqlite3PagerLookup(pPager, pgno);
  53774. }
  53775. if( pPg==0 ){
  53776. rc = pagerAcquireMapPage(pPager, pgno, pData, &pPg);
  53777. }else{
  53778. sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1)*pPager->pageSize, pData);
  53779. }
  53780. if( pPg ){
  53781. assert( rc==SQLITE_OK );
  53782. *ppPage = pPg;
  53783. return SQLITE_OK;
  53784. }
  53785. }
  53786. if( rc!=SQLITE_OK ){
  53787. *ppPage = 0;
  53788. return rc;
  53789. }
  53790. }
  53791. return getPageNormal(pPager, pgno, ppPage, flags);
  53792. }
  53793. #endif /* SQLITE_MAX_MMAP_SIZE>0 */
  53794. /* The page getter method for when the pager is an error state */
  53795. static int getPageError(
  53796. Pager *pPager, /* The pager open on the database file */
  53797. Pgno pgno, /* Page number to fetch */
  53798. DbPage **ppPage, /* Write a pointer to the page here */
  53799. int flags /* PAGER_GET_XXX flags */
  53800. ){
  53801. UNUSED_PARAMETER(pgno);
  53802. UNUSED_PARAMETER(flags);
  53803. assert( pPager->errCode!=SQLITE_OK );
  53804. *ppPage = 0;
  53805. return pPager->errCode;
  53806. }
  53807. /* Dispatch all page fetch requests to the appropriate getter method.
  53808. */
  53809. SQLITE_PRIVATE int sqlite3PagerGet(
  53810. Pager *pPager, /* The pager open on the database file */
  53811. Pgno pgno, /* Page number to fetch */
  53812. DbPage **ppPage, /* Write a pointer to the page here */
  53813. int flags /* PAGER_GET_XXX flags */
  53814. ){
  53815. return pPager->xGet(pPager, pgno, ppPage, flags);
  53816. }
  53817. /*
  53818. ** Acquire a page if it is already in the in-memory cache. Do
  53819. ** not read the page from disk. Return a pointer to the page,
  53820. ** or 0 if the page is not in cache.
  53821. **
  53822. ** See also sqlite3PagerGet(). The difference between this routine
  53823. ** and sqlite3PagerGet() is that _get() will go to the disk and read
  53824. ** in the page if the page is not already in cache. This routine
  53825. ** returns NULL if the page is not in cache or if a disk I/O error
  53826. ** has ever happened.
  53827. */
  53828. SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
  53829. sqlite3_pcache_page *pPage;
  53830. assert( pPager!=0 );
  53831. assert( pgno!=0 );
  53832. assert( pPager->pPCache!=0 );
  53833. pPage = sqlite3PcacheFetch(pPager->pPCache, pgno, 0);
  53834. assert( pPage==0 || pPager->hasHeldSharedLock );
  53835. if( pPage==0 ) return 0;
  53836. return sqlite3PcacheFetchFinish(pPager->pPCache, pgno, pPage);
  53837. }
  53838. /*
  53839. ** Release a page reference.
  53840. **
  53841. ** The sqlite3PagerUnref() and sqlite3PagerUnrefNotNull() may only be
  53842. ** used if we know that the page being released is not the last page.
  53843. ** The btree layer always holds page1 open until the end, so these first
  53844. ** to routines can be used to release any page other than BtShared.pPage1.
  53845. **
  53846. ** Use sqlite3PagerUnrefPageOne() to release page1. This latter routine
  53847. ** checks the total number of outstanding pages and if the number of
  53848. ** pages reaches zero it drops the database lock.
  53849. */
  53850. SQLITE_PRIVATE void sqlite3PagerUnrefNotNull(DbPage *pPg){
  53851. TESTONLY( Pager *pPager = pPg->pPager; )
  53852. assert( pPg!=0 );
  53853. if( pPg->flags & PGHDR_MMAP ){
  53854. assert( pPg->pgno!=1 ); /* Page1 is never memory mapped */
  53855. pagerReleaseMapPage(pPg);
  53856. }else{
  53857. sqlite3PcacheRelease(pPg);
  53858. }
  53859. /* Do not use this routine to release the last reference to page1 */
  53860. assert( sqlite3PcacheRefCount(pPager->pPCache)>0 );
  53861. }
  53862. SQLITE_PRIVATE void sqlite3PagerUnref(DbPage *pPg){
  53863. if( pPg ) sqlite3PagerUnrefNotNull(pPg);
  53864. }
  53865. SQLITE_PRIVATE void sqlite3PagerUnrefPageOne(DbPage *pPg){
  53866. Pager *pPager;
  53867. assert( pPg!=0 );
  53868. assert( pPg->pgno==1 );
  53869. assert( (pPg->flags & PGHDR_MMAP)==0 ); /* Page1 is never memory mapped */
  53870. pPager = pPg->pPager;
  53871. sqlite3PcacheRelease(pPg);
  53872. pagerUnlockIfUnused(pPager);
  53873. }
  53874. /*
  53875. ** This function is called at the start of every write transaction.
  53876. ** There must already be a RESERVED or EXCLUSIVE lock on the database
  53877. ** file when this routine is called.
  53878. **
  53879. ** Open the journal file for pager pPager and write a journal header
  53880. ** to the start of it. If there are active savepoints, open the sub-journal
  53881. ** as well. This function is only used when the journal file is being
  53882. ** opened to write a rollback log for a transaction. It is not used
  53883. ** when opening a hot journal file to roll it back.
  53884. **
  53885. ** If the journal file is already open (as it may be in exclusive mode),
  53886. ** then this function just writes a journal header to the start of the
  53887. ** already open file.
  53888. **
  53889. ** Whether or not the journal file is opened by this function, the
  53890. ** Pager.pInJournal bitvec structure is allocated.
  53891. **
  53892. ** Return SQLITE_OK if everything is successful. Otherwise, return
  53893. ** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or
  53894. ** an IO error code if opening or writing the journal file fails.
  53895. */
  53896. static int pager_open_journal(Pager *pPager){
  53897. int rc = SQLITE_OK; /* Return code */
  53898. sqlite3_vfs * const pVfs = pPager->pVfs; /* Local cache of vfs pointer */
  53899. assert( pPager->eState==PAGER_WRITER_LOCKED );
  53900. assert( assert_pager_state(pPager) );
  53901. assert( pPager->pInJournal==0 );
  53902. /* If already in the error state, this function is a no-op. But on
  53903. ** the other hand, this routine is never called if we are already in
  53904. ** an error state. */
  53905. if( NEVER(pPager->errCode) ) return pPager->errCode;
  53906. if( !pagerUseWal(pPager) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
  53907. pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
  53908. if( pPager->pInJournal==0 ){
  53909. return SQLITE_NOMEM_BKPT;
  53910. }
  53911. /* Open the journal file if it is not already open. */
  53912. if( !isOpen(pPager->jfd) ){
  53913. if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
  53914. sqlite3MemJournalOpen(pPager->jfd);
  53915. }else{
  53916. int flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE;
  53917. int nSpill;
  53918. if( pPager->tempFile ){
  53919. flags |= (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL);
  53920. nSpill = sqlite3Config.nStmtSpill;
  53921. }else{
  53922. flags |= SQLITE_OPEN_MAIN_JOURNAL;
  53923. nSpill = jrnlBufferSize(pPager);
  53924. }
  53925. /* Verify that the database still has the same name as it did when
  53926. ** it was originally opened. */
  53927. rc = databaseIsUnmoved(pPager);
  53928. if( rc==SQLITE_OK ){
  53929. rc = sqlite3JournalOpen (
  53930. pVfs, pPager->zJournal, pPager->jfd, flags, nSpill
  53931. );
  53932. }
  53933. }
  53934. assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
  53935. }
  53936. /* Write the first journal header to the journal file and open
  53937. ** the sub-journal if necessary.
  53938. */
  53939. if( rc==SQLITE_OK ){
  53940. /* TODO: Check if all of these are really required. */
  53941. pPager->nRec = 0;
  53942. pPager->journalOff = 0;
  53943. pPager->setMaster = 0;
  53944. pPager->journalHdr = 0;
  53945. rc = writeJournalHdr(pPager);
  53946. }
  53947. }
  53948. if( rc!=SQLITE_OK ){
  53949. sqlite3BitvecDestroy(pPager->pInJournal);
  53950. pPager->pInJournal = 0;
  53951. }else{
  53952. assert( pPager->eState==PAGER_WRITER_LOCKED );
  53953. pPager->eState = PAGER_WRITER_CACHEMOD;
  53954. }
  53955. return rc;
  53956. }
  53957. /*
  53958. ** Begin a write-transaction on the specified pager object. If a
  53959. ** write-transaction has already been opened, this function is a no-op.
  53960. **
  53961. ** If the exFlag argument is false, then acquire at least a RESERVED
  53962. ** lock on the database file. If exFlag is true, then acquire at least
  53963. ** an EXCLUSIVE lock. If such a lock is already held, no locking
  53964. ** functions need be called.
  53965. **
  53966. ** If the subjInMemory argument is non-zero, then any sub-journal opened
  53967. ** within this transaction will be opened as an in-memory file. This
  53968. ** has no effect if the sub-journal is already opened (as it may be when
  53969. ** running in exclusive mode) or if the transaction does not require a
  53970. ** sub-journal. If the subjInMemory argument is zero, then any required
  53971. ** sub-journal is implemented in-memory if pPager is an in-memory database,
  53972. ** or using a temporary file otherwise.
  53973. */
  53974. SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){
  53975. int rc = SQLITE_OK;
  53976. if( pPager->errCode ) return pPager->errCode;
  53977. assert( pPager->eState>=PAGER_READER && pPager->eState<PAGER_ERROR );
  53978. pPager->subjInMemory = (u8)subjInMemory;
  53979. if( ALWAYS(pPager->eState==PAGER_READER) ){
  53980. assert( pPager->pInJournal==0 );
  53981. if( pagerUseWal(pPager) ){
  53982. /* If the pager is configured to use locking_mode=exclusive, and an
  53983. ** exclusive lock on the database is not already held, obtain it now.
  53984. */
  53985. if( pPager->exclusiveMode && sqlite3WalExclusiveMode(pPager->pWal, -1) ){
  53986. rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
  53987. if( rc!=SQLITE_OK ){
  53988. return rc;
  53989. }
  53990. (void)sqlite3WalExclusiveMode(pPager->pWal, 1);
  53991. }
  53992. /* Grab the write lock on the log file. If successful, upgrade to
  53993. ** PAGER_RESERVED state. Otherwise, return an error code to the caller.
  53994. ** The busy-handler is not invoked if another connection already
  53995. ** holds the write-lock. If possible, the upper layer will call it.
  53996. */
  53997. rc = sqlite3WalBeginWriteTransaction(pPager->pWal);
  53998. }else{
  53999. /* Obtain a RESERVED lock on the database file. If the exFlag parameter
  54000. ** is true, then immediately upgrade this to an EXCLUSIVE lock. The
  54001. ** busy-handler callback can be used when upgrading to the EXCLUSIVE
  54002. ** lock, but not when obtaining the RESERVED lock.
  54003. */
  54004. rc = pagerLockDb(pPager, RESERVED_LOCK);
  54005. if( rc==SQLITE_OK && exFlag ){
  54006. rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
  54007. }
  54008. }
  54009. if( rc==SQLITE_OK ){
  54010. /* Change to WRITER_LOCKED state.
  54011. **
  54012. ** WAL mode sets Pager.eState to PAGER_WRITER_LOCKED or CACHEMOD
  54013. ** when it has an open transaction, but never to DBMOD or FINISHED.
  54014. ** This is because in those states the code to roll back savepoint
  54015. ** transactions may copy data from the sub-journal into the database
  54016. ** file as well as into the page cache. Which would be incorrect in
  54017. ** WAL mode.
  54018. */
  54019. pPager->eState = PAGER_WRITER_LOCKED;
  54020. pPager->dbHintSize = pPager->dbSize;
  54021. pPager->dbFileSize = pPager->dbSize;
  54022. pPager->dbOrigSize = pPager->dbSize;
  54023. pPager->journalOff = 0;
  54024. }
  54025. assert( rc==SQLITE_OK || pPager->eState==PAGER_READER );
  54026. assert( rc!=SQLITE_OK || pPager->eState==PAGER_WRITER_LOCKED );
  54027. assert( assert_pager_state(pPager) );
  54028. }
  54029. PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager)));
  54030. return rc;
  54031. }
  54032. /*
  54033. ** Write page pPg onto the end of the rollback journal.
  54034. */
  54035. static SQLITE_NOINLINE int pagerAddPageToRollbackJournal(PgHdr *pPg){
  54036. Pager *pPager = pPg->pPager;
  54037. int rc;
  54038. u32 cksum;
  54039. char *pData2;
  54040. i64 iOff = pPager->journalOff;
  54041. /* We should never write to the journal file the page that
  54042. ** contains the database locks. The following assert verifies
  54043. ** that we do not. */
  54044. assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
  54045. assert( pPager->journalHdr<=pPager->journalOff );
  54046. pData2 = pPg->pData;
  54047. cksum = pager_cksum(pPager, (u8*)pData2);
  54048. /* Even if an IO or diskfull error occurs while journalling the
  54049. ** page in the block above, set the need-sync flag for the page.
  54050. ** Otherwise, when the transaction is rolled back, the logic in
  54051. ** playback_one_page() will think that the page needs to be restored
  54052. ** in the database file. And if an IO error occurs while doing so,
  54053. ** then corruption may follow.
  54054. */
  54055. pPg->flags |= PGHDR_NEED_SYNC;
  54056. rc = write32bits(pPager->jfd, iOff, pPg->pgno);
  54057. if( rc!=SQLITE_OK ) return rc;
  54058. rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize, iOff+4);
  54059. if( rc!=SQLITE_OK ) return rc;
  54060. rc = write32bits(pPager->jfd, iOff+pPager->pageSize+4, cksum);
  54061. if( rc!=SQLITE_OK ) return rc;
  54062. IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno,
  54063. pPager->journalOff, pPager->pageSize));
  54064. PAGER_INCR(sqlite3_pager_writej_count);
  54065. PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n",
  54066. PAGERID(pPager), pPg->pgno,
  54067. ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));
  54068. pPager->journalOff += 8 + pPager->pageSize;
  54069. pPager->nRec++;
  54070. assert( pPager->pInJournal!=0 );
  54071. rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
  54072. testcase( rc==SQLITE_NOMEM );
  54073. assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
  54074. rc |= addToSavepointBitvecs(pPager, pPg->pgno);
  54075. assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
  54076. return rc;
  54077. }
  54078. /*
  54079. ** Mark a single data page as writeable. The page is written into the
  54080. ** main journal or sub-journal as required. If the page is written into
  54081. ** one of the journals, the corresponding bit is set in the
  54082. ** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs
  54083. ** of any open savepoints as appropriate.
  54084. */
  54085. static int pager_write(PgHdr *pPg){
  54086. Pager *pPager = pPg->pPager;
  54087. int rc = SQLITE_OK;
  54088. /* This routine is not called unless a write-transaction has already
  54089. ** been started. The journal file may or may not be open at this point.
  54090. ** It is never called in the ERROR state.
  54091. */
  54092. assert( pPager->eState==PAGER_WRITER_LOCKED
  54093. || pPager->eState==PAGER_WRITER_CACHEMOD
  54094. || pPager->eState==PAGER_WRITER_DBMOD
  54095. );
  54096. assert( assert_pager_state(pPager) );
  54097. assert( pPager->errCode==0 );
  54098. assert( pPager->readOnly==0 );
  54099. CHECK_PAGE(pPg);
  54100. /* The journal file needs to be opened. Higher level routines have already
  54101. ** obtained the necessary locks to begin the write-transaction, but the
  54102. ** rollback journal might not yet be open. Open it now if this is the case.
  54103. **
  54104. ** This is done before calling sqlite3PcacheMakeDirty() on the page.
  54105. ** Otherwise, if it were done after calling sqlite3PcacheMakeDirty(), then
  54106. ** an error might occur and the pager would end up in WRITER_LOCKED state
  54107. ** with pages marked as dirty in the cache.
  54108. */
  54109. if( pPager->eState==PAGER_WRITER_LOCKED ){
  54110. rc = pager_open_journal(pPager);
  54111. if( rc!=SQLITE_OK ) return rc;
  54112. }
  54113. assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
  54114. assert( assert_pager_state(pPager) );
  54115. /* Mark the page that is about to be modified as dirty. */
  54116. sqlite3PcacheMakeDirty(pPg);
  54117. /* If a rollback journal is in use, them make sure the page that is about
  54118. ** to change is in the rollback journal, or if the page is a new page off
  54119. ** then end of the file, make sure it is marked as PGHDR_NEED_SYNC.
  54120. */
  54121. assert( (pPager->pInJournal!=0) == isOpen(pPager->jfd) );
  54122. if( pPager->pInJournal!=0
  54123. && sqlite3BitvecTestNotNull(pPager->pInJournal, pPg->pgno)==0
  54124. ){
  54125. assert( pagerUseWal(pPager)==0 );
  54126. if( pPg->pgno<=pPager->dbOrigSize ){
  54127. rc = pagerAddPageToRollbackJournal(pPg);
  54128. if( rc!=SQLITE_OK ){
  54129. return rc;
  54130. }
  54131. }else{
  54132. if( pPager->eState!=PAGER_WRITER_DBMOD ){
  54133. pPg->flags |= PGHDR_NEED_SYNC;
  54134. }
  54135. PAGERTRACE(("APPEND %d page %d needSync=%d\n",
  54136. PAGERID(pPager), pPg->pgno,
  54137. ((pPg->flags&PGHDR_NEED_SYNC)?1:0)));
  54138. }
  54139. }
  54140. /* The PGHDR_DIRTY bit is set above when the page was added to the dirty-list
  54141. ** and before writing the page into the rollback journal. Wait until now,
  54142. ** after the page has been successfully journalled, before setting the
  54143. ** PGHDR_WRITEABLE bit that indicates that the page can be safely modified.
  54144. */
  54145. pPg->flags |= PGHDR_WRITEABLE;
  54146. /* If the statement journal is open and the page is not in it,
  54147. ** then write the page into the statement journal.
  54148. */
  54149. if( pPager->nSavepoint>0 ){
  54150. rc = subjournalPageIfRequired(pPg);
  54151. }
  54152. /* Update the database size and return. */
  54153. if( pPager->dbSize<pPg->pgno ){
  54154. pPager->dbSize = pPg->pgno;
  54155. }
  54156. return rc;
  54157. }
  54158. /*
  54159. ** This is a variant of sqlite3PagerWrite() that runs when the sector size
  54160. ** is larger than the page size. SQLite makes the (reasonable) assumption that
  54161. ** all bytes of a sector are written together by hardware. Hence, all bytes of
  54162. ** a sector need to be journalled in case of a power loss in the middle of
  54163. ** a write.
  54164. **
  54165. ** Usually, the sector size is less than or equal to the page size, in which
  54166. ** case pages can be individually written. This routine only runs in the
  54167. ** exceptional case where the page size is smaller than the sector size.
  54168. */
  54169. static SQLITE_NOINLINE int pagerWriteLargeSector(PgHdr *pPg){
  54170. int rc = SQLITE_OK; /* Return code */
  54171. Pgno nPageCount; /* Total number of pages in database file */
  54172. Pgno pg1; /* First page of the sector pPg is located on. */
  54173. int nPage = 0; /* Number of pages starting at pg1 to journal */
  54174. int ii; /* Loop counter */
  54175. int needSync = 0; /* True if any page has PGHDR_NEED_SYNC */
  54176. Pager *pPager = pPg->pPager; /* The pager that owns pPg */
  54177. Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
  54178. /* Set the doNotSpill NOSYNC bit to 1. This is because we cannot allow
  54179. ** a journal header to be written between the pages journaled by
  54180. ** this function.
  54181. */
  54182. assert( !MEMDB );
  54183. assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)==0 );
  54184. pPager->doNotSpill |= SPILLFLAG_NOSYNC;
  54185. /* This trick assumes that both the page-size and sector-size are
  54186. ** an integer power of 2. It sets variable pg1 to the identifier
  54187. ** of the first page of the sector pPg is located on.
  54188. */
  54189. pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
  54190. nPageCount = pPager->dbSize;
  54191. if( pPg->pgno>nPageCount ){
  54192. nPage = (pPg->pgno - pg1)+1;
  54193. }else if( (pg1+nPagePerSector-1)>nPageCount ){
  54194. nPage = nPageCount+1-pg1;
  54195. }else{
  54196. nPage = nPagePerSector;
  54197. }
  54198. assert(nPage>0);
  54199. assert(pg1<=pPg->pgno);
  54200. assert((pg1+nPage)>pPg->pgno);
  54201. for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
  54202. Pgno pg = pg1+ii;
  54203. PgHdr *pPage;
  54204. if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
  54205. if( pg!=PAGER_MJ_PGNO(pPager) ){
  54206. rc = sqlite3PagerGet(pPager, pg, &pPage, 0);
  54207. if( rc==SQLITE_OK ){
  54208. rc = pager_write(pPage);
  54209. if( pPage->flags&PGHDR_NEED_SYNC ){
  54210. needSync = 1;
  54211. }
  54212. sqlite3PagerUnrefNotNull(pPage);
  54213. }
  54214. }
  54215. }else if( (pPage = sqlite3PagerLookup(pPager, pg))!=0 ){
  54216. if( pPage->flags&PGHDR_NEED_SYNC ){
  54217. needSync = 1;
  54218. }
  54219. sqlite3PagerUnrefNotNull(pPage);
  54220. }
  54221. }
  54222. /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages
  54223. ** starting at pg1, then it needs to be set for all of them. Because
  54224. ** writing to any of these nPage pages may damage the others, the
  54225. ** journal file must contain sync()ed copies of all of them
  54226. ** before any of them can be written out to the database file.
  54227. */
  54228. if( rc==SQLITE_OK && needSync ){
  54229. assert( !MEMDB );
  54230. for(ii=0; ii<nPage; ii++){
  54231. PgHdr *pPage = sqlite3PagerLookup(pPager, pg1+ii);
  54232. if( pPage ){
  54233. pPage->flags |= PGHDR_NEED_SYNC;
  54234. sqlite3PagerUnrefNotNull(pPage);
  54235. }
  54236. }
  54237. }
  54238. assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)!=0 );
  54239. pPager->doNotSpill &= ~SPILLFLAG_NOSYNC;
  54240. return rc;
  54241. }
  54242. /*
  54243. ** Mark a data page as writeable. This routine must be called before
  54244. ** making changes to a page. The caller must check the return value
  54245. ** of this function and be careful not to change any page data unless
  54246. ** this routine returns SQLITE_OK.
  54247. **
  54248. ** The difference between this function and pager_write() is that this
  54249. ** function also deals with the special case where 2 or more pages
  54250. ** fit on a single disk sector. In this case all co-resident pages
  54251. ** must have been written to the journal file before returning.
  54252. **
  54253. ** If an error occurs, SQLITE_NOMEM or an IO error code is returned
  54254. ** as appropriate. Otherwise, SQLITE_OK.
  54255. */
  54256. SQLITE_PRIVATE int sqlite3PagerWrite(PgHdr *pPg){
  54257. Pager *pPager = pPg->pPager;
  54258. assert( (pPg->flags & PGHDR_MMAP)==0 );
  54259. assert( pPager->eState>=PAGER_WRITER_LOCKED );
  54260. assert( assert_pager_state(pPager) );
  54261. if( (pPg->flags & PGHDR_WRITEABLE)!=0 && pPager->dbSize>=pPg->pgno ){
  54262. if( pPager->nSavepoint ) return subjournalPageIfRequired(pPg);
  54263. return SQLITE_OK;
  54264. }else if( pPager->errCode ){
  54265. return pPager->errCode;
  54266. }else if( pPager->sectorSize > (u32)pPager->pageSize ){
  54267. assert( pPager->tempFile==0 );
  54268. return pagerWriteLargeSector(pPg);
  54269. }else{
  54270. return pager_write(pPg);
  54271. }
  54272. }
  54273. /*
  54274. ** Return TRUE if the page given in the argument was previously passed
  54275. ** to sqlite3PagerWrite(). In other words, return TRUE if it is ok
  54276. ** to change the content of the page.
  54277. */
  54278. #ifndef NDEBUG
  54279. SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){
  54280. return pPg->flags & PGHDR_WRITEABLE;
  54281. }
  54282. #endif
  54283. /*
  54284. ** A call to this routine tells the pager that it is not necessary to
  54285. ** write the information on page pPg back to the disk, even though
  54286. ** that page might be marked as dirty. This happens, for example, when
  54287. ** the page has been added as a leaf of the freelist and so its
  54288. ** content no longer matters.
  54289. **
  54290. ** The overlying software layer calls this routine when all of the data
  54291. ** on the given page is unused. The pager marks the page as clean so
  54292. ** that it does not get written to disk.
  54293. **
  54294. ** Tests show that this optimization can quadruple the speed of large
  54295. ** DELETE operations.
  54296. **
  54297. ** This optimization cannot be used with a temp-file, as the page may
  54298. ** have been dirty at the start of the transaction. In that case, if
  54299. ** memory pressure forces page pPg out of the cache, the data does need
  54300. ** to be written out to disk so that it may be read back in if the
  54301. ** current transaction is rolled back.
  54302. */
  54303. SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){
  54304. Pager *pPager = pPg->pPager;
  54305. if( !pPager->tempFile && (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
  54306. PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
  54307. IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
  54308. pPg->flags |= PGHDR_DONT_WRITE;
  54309. pPg->flags &= ~PGHDR_WRITEABLE;
  54310. testcase( pPg->flags & PGHDR_NEED_SYNC );
  54311. pager_set_pagehash(pPg);
  54312. }
  54313. }
  54314. /*
  54315. ** This routine is called to increment the value of the database file
  54316. ** change-counter, stored as a 4-byte big-endian integer starting at
  54317. ** byte offset 24 of the pager file. The secondary change counter at
  54318. ** 92 is also updated, as is the SQLite version number at offset 96.
  54319. **
  54320. ** But this only happens if the pPager->changeCountDone flag is false.
  54321. ** To avoid excess churning of page 1, the update only happens once.
  54322. ** See also the pager_write_changecounter() routine that does an
  54323. ** unconditional update of the change counters.
  54324. **
  54325. ** If the isDirectMode flag is zero, then this is done by calling
  54326. ** sqlite3PagerWrite() on page 1, then modifying the contents of the
  54327. ** page data. In this case the file will be updated when the current
  54328. ** transaction is committed.
  54329. **
  54330. ** The isDirectMode flag may only be non-zero if the library was compiled
  54331. ** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case,
  54332. ** if isDirect is non-zero, then the database file is updated directly
  54333. ** by writing an updated version of page 1 using a call to the
  54334. ** sqlite3OsWrite() function.
  54335. */
  54336. static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
  54337. int rc = SQLITE_OK;
  54338. assert( pPager->eState==PAGER_WRITER_CACHEMOD
  54339. || pPager->eState==PAGER_WRITER_DBMOD
  54340. );
  54341. assert( assert_pager_state(pPager) );
  54342. /* Declare and initialize constant integer 'isDirect'. If the
  54343. ** atomic-write optimization is enabled in this build, then isDirect
  54344. ** is initialized to the value passed as the isDirectMode parameter
  54345. ** to this function. Otherwise, it is always set to zero.
  54346. **
  54347. ** The idea is that if the atomic-write optimization is not
  54348. ** enabled at compile time, the compiler can omit the tests of
  54349. ** 'isDirect' below, as well as the block enclosed in the
  54350. ** "if( isDirect )" condition.
  54351. */
  54352. #ifndef SQLITE_ENABLE_ATOMIC_WRITE
  54353. # define DIRECT_MODE 0
  54354. assert( isDirectMode==0 );
  54355. UNUSED_PARAMETER(isDirectMode);
  54356. #else
  54357. # define DIRECT_MODE isDirectMode
  54358. #endif
  54359. if( !pPager->changeCountDone && ALWAYS(pPager->dbSize>0) ){
  54360. PgHdr *pPgHdr; /* Reference to page 1 */
  54361. assert( !pPager->tempFile && isOpen(pPager->fd) );
  54362. /* Open page 1 of the file for writing. */
  54363. rc = sqlite3PagerGet(pPager, 1, &pPgHdr, 0);
  54364. assert( pPgHdr==0 || rc==SQLITE_OK );
  54365. /* If page one was fetched successfully, and this function is not
  54366. ** operating in direct-mode, make page 1 writable. When not in
  54367. ** direct mode, page 1 is always held in cache and hence the PagerGet()
  54368. ** above is always successful - hence the ALWAYS on rc==SQLITE_OK.
  54369. */
  54370. if( !DIRECT_MODE && ALWAYS(rc==SQLITE_OK) ){
  54371. rc = sqlite3PagerWrite(pPgHdr);
  54372. }
  54373. if( rc==SQLITE_OK ){
  54374. /* Actually do the update of the change counter */
  54375. pager_write_changecounter(pPgHdr);
  54376. /* If running in direct mode, write the contents of page 1 to the file. */
  54377. if( DIRECT_MODE ){
  54378. const void *zBuf;
  54379. assert( pPager->dbFileSize>0 );
  54380. zBuf = pPgHdr->pData;
  54381. if( rc==SQLITE_OK ){
  54382. rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
  54383. pPager->aStat[PAGER_STAT_WRITE]++;
  54384. }
  54385. if( rc==SQLITE_OK ){
  54386. /* Update the pager's copy of the change-counter. Otherwise, the
  54387. ** next time a read transaction is opened the cache will be
  54388. ** flushed (as the change-counter values will not match). */
  54389. const void *pCopy = (const void *)&((const char *)zBuf)[24];
  54390. memcpy(&pPager->dbFileVers, pCopy, sizeof(pPager->dbFileVers));
  54391. pPager->changeCountDone = 1;
  54392. }
  54393. }else{
  54394. pPager->changeCountDone = 1;
  54395. }
  54396. }
  54397. /* Release the page reference. */
  54398. sqlite3PagerUnref(pPgHdr);
  54399. }
  54400. return rc;
  54401. }
  54402. /*
  54403. ** Sync the database file to disk. This is a no-op for in-memory databases
  54404. ** or pages with the Pager.noSync flag set.
  54405. **
  54406. ** If successful, or if called on a pager for which it is a no-op, this
  54407. ** function returns SQLITE_OK. Otherwise, an IO error code is returned.
  54408. */
  54409. SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zMaster){
  54410. int rc = SQLITE_OK;
  54411. void *pArg = (void*)zMaster;
  54412. rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SYNC, pArg);
  54413. if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
  54414. if( rc==SQLITE_OK && !pPager->noSync ){
  54415. assert( !MEMDB );
  54416. rc = sqlite3OsSync(pPager->fd, pPager->syncFlags);
  54417. }
  54418. return rc;
  54419. }
  54420. /*
  54421. ** This function may only be called while a write-transaction is active in
  54422. ** rollback. If the connection is in WAL mode, this call is a no-op.
  54423. ** Otherwise, if the connection does not already have an EXCLUSIVE lock on
  54424. ** the database file, an attempt is made to obtain one.
  54425. **
  54426. ** If the EXCLUSIVE lock is already held or the attempt to obtain it is
  54427. ** successful, or the connection is in WAL mode, SQLITE_OK is returned.
  54428. ** Otherwise, either SQLITE_BUSY or an SQLITE_IOERR_XXX error code is
  54429. ** returned.
  54430. */
  54431. SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager *pPager){
  54432. int rc = pPager->errCode;
  54433. assert( assert_pager_state(pPager) );
  54434. if( rc==SQLITE_OK ){
  54435. assert( pPager->eState==PAGER_WRITER_CACHEMOD
  54436. || pPager->eState==PAGER_WRITER_DBMOD
  54437. || pPager->eState==PAGER_WRITER_LOCKED
  54438. );
  54439. assert( assert_pager_state(pPager) );
  54440. if( 0==pagerUseWal(pPager) ){
  54441. rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
  54442. }
  54443. }
  54444. return rc;
  54445. }
  54446. /*
  54447. ** Sync the database file for the pager pPager. zMaster points to the name
  54448. ** of a master journal file that should be written into the individual
  54449. ** journal file. zMaster may be NULL, which is interpreted as no master
  54450. ** journal (a single database transaction).
  54451. **
  54452. ** This routine ensures that:
  54453. **
  54454. ** * The database file change-counter is updated,
  54455. ** * the journal is synced (unless the atomic-write optimization is used),
  54456. ** * all dirty pages are written to the database file,
  54457. ** * the database file is truncated (if required), and
  54458. ** * the database file synced.
  54459. **
  54460. ** The only thing that remains to commit the transaction is to finalize
  54461. ** (delete, truncate or zero the first part of) the journal file (or
  54462. ** delete the master journal file if specified).
  54463. **
  54464. ** Note that if zMaster==NULL, this does not overwrite a previous value
  54465. ** passed to an sqlite3PagerCommitPhaseOne() call.
  54466. **
  54467. ** If the final parameter - noSync - is true, then the database file itself
  54468. ** is not synced. The caller must call sqlite3PagerSync() directly to
  54469. ** sync the database file before calling CommitPhaseTwo() to delete the
  54470. ** journal file in this case.
  54471. */
  54472. SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
  54473. Pager *pPager, /* Pager object */
  54474. const char *zMaster, /* If not NULL, the master journal name */
  54475. int noSync /* True to omit the xSync on the db file */
  54476. ){
  54477. int rc = SQLITE_OK; /* Return code */
  54478. assert( pPager->eState==PAGER_WRITER_LOCKED
  54479. || pPager->eState==PAGER_WRITER_CACHEMOD
  54480. || pPager->eState==PAGER_WRITER_DBMOD
  54481. || pPager->eState==PAGER_ERROR
  54482. );
  54483. assert( assert_pager_state(pPager) );
  54484. /* If a prior error occurred, report that error again. */
  54485. if( NEVER(pPager->errCode) ) return pPager->errCode;
  54486. /* Provide the ability to easily simulate an I/O error during testing */
  54487. if( sqlite3FaultSim(400) ) return SQLITE_IOERR;
  54488. PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n",
  54489. pPager->zFilename, zMaster, pPager->dbSize));
  54490. /* If no database changes have been made, return early. */
  54491. if( pPager->eState<PAGER_WRITER_CACHEMOD ) return SQLITE_OK;
  54492. assert( MEMDB==0 || pPager->tempFile );
  54493. assert( isOpen(pPager->fd) || pPager->tempFile );
  54494. if( 0==pagerFlushOnCommit(pPager, 1) ){
  54495. /* If this is an in-memory db, or no pages have been written to, or this
  54496. ** function has already been called, it is mostly a no-op. However, any
  54497. ** backup in progress needs to be restarted. */
  54498. sqlite3BackupRestart(pPager->pBackup);
  54499. }else{
  54500. PgHdr *pList;
  54501. if( pagerUseWal(pPager) ){
  54502. PgHdr *pPageOne = 0;
  54503. pList = sqlite3PcacheDirtyList(pPager->pPCache);
  54504. if( pList==0 ){
  54505. /* Must have at least one page for the WAL commit flag.
  54506. ** Ticket [2d1a5c67dfc2363e44f29d9bbd57f] 2011-05-18 */
  54507. rc = sqlite3PagerGet(pPager, 1, &pPageOne, 0);
  54508. pList = pPageOne;
  54509. pList->pDirty = 0;
  54510. }
  54511. assert( rc==SQLITE_OK );
  54512. if( ALWAYS(pList) ){
  54513. rc = pagerWalFrames(pPager, pList, pPager->dbSize, 1);
  54514. }
  54515. sqlite3PagerUnref(pPageOne);
  54516. if( rc==SQLITE_OK ){
  54517. sqlite3PcacheCleanAll(pPager->pPCache);
  54518. }
  54519. }else{
  54520. /* The bBatch boolean is true if the batch-atomic-write commit method
  54521. ** should be used. No rollback journal is created if batch-atomic-write
  54522. ** is enabled.
  54523. */
  54524. #ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE
  54525. sqlite3_file *fd = pPager->fd;
  54526. int bBatch = zMaster==0 /* An SQLITE_IOCAP_BATCH_ATOMIC commit */
  54527. && (sqlite3OsDeviceCharacteristics(fd) & SQLITE_IOCAP_BATCH_ATOMIC)
  54528. && !pPager->noSync
  54529. && sqlite3JournalIsInMemory(pPager->jfd);
  54530. #else
  54531. # define bBatch 0
  54532. #endif
  54533. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  54534. /* The following block updates the change-counter. Exactly how it
  54535. ** does this depends on whether or not the atomic-update optimization
  54536. ** was enabled at compile time, and if this transaction meets the
  54537. ** runtime criteria to use the operation:
  54538. **
  54539. ** * The file-system supports the atomic-write property for
  54540. ** blocks of size page-size, and
  54541. ** * This commit is not part of a multi-file transaction, and
  54542. ** * Exactly one page has been modified and store in the journal file.
  54543. **
  54544. ** If the optimization was not enabled at compile time, then the
  54545. ** pager_incr_changecounter() function is called to update the change
  54546. ** counter in 'indirect-mode'. If the optimization is compiled in but
  54547. ** is not applicable to this transaction, call sqlite3JournalCreate()
  54548. ** to make sure the journal file has actually been created, then call
  54549. ** pager_incr_changecounter() to update the change-counter in indirect
  54550. ** mode.
  54551. **
  54552. ** Otherwise, if the optimization is both enabled and applicable,
  54553. ** then call pager_incr_changecounter() to update the change-counter
  54554. ** in 'direct' mode. In this case the journal file will never be
  54555. ** created for this transaction.
  54556. */
  54557. if( bBatch==0 ){
  54558. PgHdr *pPg;
  54559. assert( isOpen(pPager->jfd)
  54560. || pPager->journalMode==PAGER_JOURNALMODE_OFF
  54561. || pPager->journalMode==PAGER_JOURNALMODE_WAL
  54562. );
  54563. if( !zMaster && isOpen(pPager->jfd)
  54564. && pPager->journalOff==jrnlBufferSize(pPager)
  54565. && pPager->dbSize>=pPager->dbOrigSize
  54566. && (!(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)
  54567. ){
  54568. /* Update the db file change counter via the direct-write method. The
  54569. ** following call will modify the in-memory representation of page 1
  54570. ** to include the updated change counter and then write page 1
  54571. ** directly to the database file. Because of the atomic-write
  54572. ** property of the host file-system, this is safe.
  54573. */
  54574. rc = pager_incr_changecounter(pPager, 1);
  54575. }else{
  54576. rc = sqlite3JournalCreate(pPager->jfd);
  54577. if( rc==SQLITE_OK ){
  54578. rc = pager_incr_changecounter(pPager, 0);
  54579. }
  54580. }
  54581. }
  54582. #else /* SQLITE_ENABLE_ATOMIC_WRITE */
  54583. #ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE
  54584. if( zMaster ){
  54585. rc = sqlite3JournalCreate(pPager->jfd);
  54586. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  54587. assert( bBatch==0 );
  54588. }
  54589. #endif
  54590. rc = pager_incr_changecounter(pPager, 0);
  54591. #endif /* !SQLITE_ENABLE_ATOMIC_WRITE */
  54592. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  54593. /* Write the master journal name into the journal file. If a master
  54594. ** journal file name has already been written to the journal file,
  54595. ** or if zMaster is NULL (no master journal), then this call is a no-op.
  54596. */
  54597. rc = writeMasterJournal(pPager, zMaster);
  54598. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  54599. /* Sync the journal file and write all dirty pages to the database.
  54600. ** If the atomic-update optimization is being used, this sync will not
  54601. ** create the journal file or perform any real IO.
  54602. **
  54603. ** Because the change-counter page was just modified, unless the
  54604. ** atomic-update optimization is used it is almost certain that the
  54605. ** journal requires a sync here. However, in locking_mode=exclusive
  54606. ** on a system under memory pressure it is just possible that this is
  54607. ** not the case. In this case it is likely enough that the redundant
  54608. ** xSync() call will be changed to a no-op by the OS anyhow.
  54609. */
  54610. rc = syncJournal(pPager, 0);
  54611. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  54612. pList = sqlite3PcacheDirtyList(pPager->pPCache);
  54613. #ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE
  54614. if( bBatch ){
  54615. rc = sqlite3OsFileControl(fd, SQLITE_FCNTL_BEGIN_ATOMIC_WRITE, 0);
  54616. if( rc==SQLITE_OK ){
  54617. rc = pager_write_pagelist(pPager, pList);
  54618. if( rc==SQLITE_OK ){
  54619. rc = sqlite3OsFileControl(fd, SQLITE_FCNTL_COMMIT_ATOMIC_WRITE, 0);
  54620. }
  54621. if( rc!=SQLITE_OK ){
  54622. sqlite3OsFileControlHint(fd, SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE, 0);
  54623. }
  54624. }
  54625. if( (rc&0xFF)==SQLITE_IOERR && rc!=SQLITE_IOERR_NOMEM ){
  54626. rc = sqlite3JournalCreate(pPager->jfd);
  54627. if( rc!=SQLITE_OK ){
  54628. sqlite3OsClose(pPager->jfd);
  54629. goto commit_phase_one_exit;
  54630. }
  54631. bBatch = 0;
  54632. }else{
  54633. sqlite3OsClose(pPager->jfd);
  54634. }
  54635. }
  54636. #endif /* SQLITE_ENABLE_BATCH_ATOMIC_WRITE */
  54637. if( bBatch==0 ){
  54638. rc = pager_write_pagelist(pPager, pList);
  54639. }
  54640. if( rc!=SQLITE_OK ){
  54641. assert( rc!=SQLITE_IOERR_BLOCKED );
  54642. goto commit_phase_one_exit;
  54643. }
  54644. sqlite3PcacheCleanAll(pPager->pPCache);
  54645. /* If the file on disk is smaller than the database image, use
  54646. ** pager_truncate to grow the file here. This can happen if the database
  54647. ** image was extended as part of the current transaction and then the
  54648. ** last page in the db image moved to the free-list. In this case the
  54649. ** last page is never written out to disk, leaving the database file
  54650. ** undersized. Fix this now if it is the case. */
  54651. if( pPager->dbSize>pPager->dbFileSize ){
  54652. Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager));
  54653. assert( pPager->eState==PAGER_WRITER_DBMOD );
  54654. rc = pager_truncate(pPager, nNew);
  54655. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  54656. }
  54657. /* Finally, sync the database file. */
  54658. if( !noSync ){
  54659. rc = sqlite3PagerSync(pPager, zMaster);
  54660. }
  54661. IOTRACE(("DBSYNC %p\n", pPager))
  54662. }
  54663. }
  54664. commit_phase_one_exit:
  54665. if( rc==SQLITE_OK && !pagerUseWal(pPager) ){
  54666. pPager->eState = PAGER_WRITER_FINISHED;
  54667. }
  54668. return rc;
  54669. }
  54670. /*
  54671. ** When this function is called, the database file has been completely
  54672. ** updated to reflect the changes made by the current transaction and
  54673. ** synced to disk. The journal file still exists in the file-system
  54674. ** though, and if a failure occurs at this point it will eventually
  54675. ** be used as a hot-journal and the current transaction rolled back.
  54676. **
  54677. ** This function finalizes the journal file, either by deleting,
  54678. ** truncating or partially zeroing it, so that it cannot be used
  54679. ** for hot-journal rollback. Once this is done the transaction is
  54680. ** irrevocably committed.
  54681. **
  54682. ** If an error occurs, an IO error code is returned and the pager
  54683. ** moves into the error state. Otherwise, SQLITE_OK is returned.
  54684. */
  54685. SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
  54686. int rc = SQLITE_OK; /* Return code */
  54687. /* This routine should not be called if a prior error has occurred.
  54688. ** But if (due to a coding error elsewhere in the system) it does get
  54689. ** called, just return the same error code without doing anything. */
  54690. if( NEVER(pPager->errCode) ) return pPager->errCode;
  54691. pPager->iDataVersion++;
  54692. assert( pPager->eState==PAGER_WRITER_LOCKED
  54693. || pPager->eState==PAGER_WRITER_FINISHED
  54694. || (pagerUseWal(pPager) && pPager->eState==PAGER_WRITER_CACHEMOD)
  54695. );
  54696. assert( assert_pager_state(pPager) );
  54697. /* An optimization. If the database was not actually modified during
  54698. ** this transaction, the pager is running in exclusive-mode and is
  54699. ** using persistent journals, then this function is a no-op.
  54700. **
  54701. ** The start of the journal file currently contains a single journal
  54702. ** header with the nRec field set to 0. If such a journal is used as
  54703. ** a hot-journal during hot-journal rollback, 0 changes will be made
  54704. ** to the database file. So there is no need to zero the journal
  54705. ** header. Since the pager is in exclusive mode, there is no need
  54706. ** to drop any locks either.
  54707. */
  54708. if( pPager->eState==PAGER_WRITER_LOCKED
  54709. && pPager->exclusiveMode
  54710. && pPager->journalMode==PAGER_JOURNALMODE_PERSIST
  54711. ){
  54712. assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) || !pPager->journalOff );
  54713. pPager->eState = PAGER_READER;
  54714. return SQLITE_OK;
  54715. }
  54716. PAGERTRACE(("COMMIT %d\n", PAGERID(pPager)));
  54717. rc = pager_end_transaction(pPager, pPager->setMaster, 1);
  54718. return pager_error(pPager, rc);
  54719. }
  54720. /*
  54721. ** If a write transaction is open, then all changes made within the
  54722. ** transaction are reverted and the current write-transaction is closed.
  54723. ** The pager falls back to PAGER_READER state if successful, or PAGER_ERROR
  54724. ** state if an error occurs.
  54725. **
  54726. ** If the pager is already in PAGER_ERROR state when this function is called,
  54727. ** it returns Pager.errCode immediately. No work is performed in this case.
  54728. **
  54729. ** Otherwise, in rollback mode, this function performs two functions:
  54730. **
  54731. ** 1) It rolls back the journal file, restoring all database file and
  54732. ** in-memory cache pages to the state they were in when the transaction
  54733. ** was opened, and
  54734. **
  54735. ** 2) It finalizes the journal file, so that it is not used for hot
  54736. ** rollback at any point in the future.
  54737. **
  54738. ** Finalization of the journal file (task 2) is only performed if the
  54739. ** rollback is successful.
  54740. **
  54741. ** In WAL mode, all cache-entries containing data modified within the
  54742. ** current transaction are either expelled from the cache or reverted to
  54743. ** their pre-transaction state by re-reading data from the database or
  54744. ** WAL files. The WAL transaction is then closed.
  54745. */
  54746. SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
  54747. int rc = SQLITE_OK; /* Return code */
  54748. PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager)));
  54749. /* PagerRollback() is a no-op if called in READER or OPEN state. If
  54750. ** the pager is already in the ERROR state, the rollback is not
  54751. ** attempted here. Instead, the error code is returned to the caller.
  54752. */
  54753. assert( assert_pager_state(pPager) );
  54754. if( pPager->eState==PAGER_ERROR ) return pPager->errCode;
  54755. if( pPager->eState<=PAGER_READER ) return SQLITE_OK;
  54756. if( pagerUseWal(pPager) ){
  54757. int rc2;
  54758. rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK, -1);
  54759. rc2 = pager_end_transaction(pPager, pPager->setMaster, 0);
  54760. if( rc==SQLITE_OK ) rc = rc2;
  54761. }else if( !isOpen(pPager->jfd) || pPager->eState==PAGER_WRITER_LOCKED ){
  54762. int eState = pPager->eState;
  54763. rc = pager_end_transaction(pPager, 0, 0);
  54764. if( !MEMDB && eState>PAGER_WRITER_LOCKED ){
  54765. /* This can happen using journal_mode=off. Move the pager to the error
  54766. ** state to indicate that the contents of the cache may not be trusted.
  54767. ** Any active readers will get SQLITE_ABORT.
  54768. */
  54769. pPager->errCode = SQLITE_ABORT;
  54770. pPager->eState = PAGER_ERROR;
  54771. setGetterMethod(pPager);
  54772. return rc;
  54773. }
  54774. }else{
  54775. rc = pager_playback(pPager, 0);
  54776. }
  54777. assert( pPager->eState==PAGER_READER || rc!=SQLITE_OK );
  54778. assert( rc==SQLITE_OK || rc==SQLITE_FULL || rc==SQLITE_CORRUPT
  54779. || rc==SQLITE_NOMEM || (rc&0xFF)==SQLITE_IOERR
  54780. || rc==SQLITE_CANTOPEN
  54781. );
  54782. /* If an error occurs during a ROLLBACK, we can no longer trust the pager
  54783. ** cache. So call pager_error() on the way out to make any error persistent.
  54784. */
  54785. return pager_error(pPager, rc);
  54786. }
  54787. /*
  54788. ** Return TRUE if the database file is opened read-only. Return FALSE
  54789. ** if the database is (in theory) writable.
  54790. */
  54791. SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager *pPager){
  54792. return pPager->readOnly;
  54793. }
  54794. #ifdef SQLITE_DEBUG
  54795. /*
  54796. ** Return the sum of the reference counts for all pages held by pPager.
  54797. */
  54798. SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){
  54799. return sqlite3PcacheRefCount(pPager->pPCache);
  54800. }
  54801. #endif
  54802. /*
  54803. ** Return the approximate number of bytes of memory currently
  54804. ** used by the pager and its associated cache.
  54805. */
  54806. SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager *pPager){
  54807. int perPageSize = pPager->pageSize + pPager->nExtra + sizeof(PgHdr)
  54808. + 5*sizeof(void*);
  54809. return perPageSize*sqlite3PcachePagecount(pPager->pPCache)
  54810. + sqlite3MallocSize(pPager)
  54811. + pPager->pageSize;
  54812. }
  54813. /*
  54814. ** Return the number of references to the specified page.
  54815. */
  54816. SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *pPage){
  54817. return sqlite3PcachePageRefcount(pPage);
  54818. }
  54819. #ifdef SQLITE_TEST
  54820. /*
  54821. ** This routine is used for testing and analysis only.
  54822. */
  54823. SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){
  54824. static int a[11];
  54825. a[0] = sqlite3PcacheRefCount(pPager->pPCache);
  54826. a[1] = sqlite3PcachePagecount(pPager->pPCache);
  54827. a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
  54828. a[3] = pPager->eState==PAGER_OPEN ? -1 : (int) pPager->dbSize;
  54829. a[4] = pPager->eState;
  54830. a[5] = pPager->errCode;
  54831. a[6] = pPager->aStat[PAGER_STAT_HIT];
  54832. a[7] = pPager->aStat[PAGER_STAT_MISS];
  54833. a[8] = 0; /* Used to be pPager->nOvfl */
  54834. a[9] = pPager->nRead;
  54835. a[10] = pPager->aStat[PAGER_STAT_WRITE];
  54836. return a;
  54837. }
  54838. #endif
  54839. /*
  54840. ** Parameter eStat must be one of SQLITE_DBSTATUS_CACHE_HIT, _MISS, _WRITE,
  54841. ** or _WRITE+1. The SQLITE_DBSTATUS_CACHE_WRITE+1 case is a translation
  54842. ** of SQLITE_DBSTATUS_CACHE_SPILL. The _SPILL case is not contiguous because
  54843. ** it was added later.
  54844. **
  54845. ** Before returning, *pnVal is incremented by the
  54846. ** current cache hit or miss count, according to the value of eStat. If the
  54847. ** reset parameter is non-zero, the cache hit or miss count is zeroed before
  54848. ** returning.
  54849. */
  54850. SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *pPager, int eStat, int reset, int *pnVal){
  54851. assert( eStat==SQLITE_DBSTATUS_CACHE_HIT
  54852. || eStat==SQLITE_DBSTATUS_CACHE_MISS
  54853. || eStat==SQLITE_DBSTATUS_CACHE_WRITE
  54854. || eStat==SQLITE_DBSTATUS_CACHE_WRITE+1
  54855. );
  54856. assert( SQLITE_DBSTATUS_CACHE_HIT+1==SQLITE_DBSTATUS_CACHE_MISS );
  54857. assert( SQLITE_DBSTATUS_CACHE_HIT+2==SQLITE_DBSTATUS_CACHE_WRITE );
  54858. assert( PAGER_STAT_HIT==0 && PAGER_STAT_MISS==1
  54859. && PAGER_STAT_WRITE==2 && PAGER_STAT_SPILL==3 );
  54860. eStat -= SQLITE_DBSTATUS_CACHE_HIT;
  54861. *pnVal += pPager->aStat[eStat];
  54862. if( reset ){
  54863. pPager->aStat[eStat] = 0;
  54864. }
  54865. }
  54866. /*
  54867. ** Return true if this is an in-memory or temp-file backed pager.
  54868. */
  54869. SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){
  54870. return pPager->tempFile;
  54871. }
  54872. /*
  54873. ** Check that there are at least nSavepoint savepoints open. If there are
  54874. ** currently less than nSavepoints open, then open one or more savepoints
  54875. ** to make up the difference. If the number of savepoints is already
  54876. ** equal to nSavepoint, then this function is a no-op.
  54877. **
  54878. ** If a memory allocation fails, SQLITE_NOMEM is returned. If an error
  54879. ** occurs while opening the sub-journal file, then an IO error code is
  54880. ** returned. Otherwise, SQLITE_OK.
  54881. */
  54882. static SQLITE_NOINLINE int pagerOpenSavepoint(Pager *pPager, int nSavepoint){
  54883. int rc = SQLITE_OK; /* Return code */
  54884. int nCurrent = pPager->nSavepoint; /* Current number of savepoints */
  54885. int ii; /* Iterator variable */
  54886. PagerSavepoint *aNew; /* New Pager.aSavepoint array */
  54887. assert( pPager->eState>=PAGER_WRITER_LOCKED );
  54888. assert( assert_pager_state(pPager) );
  54889. assert( nSavepoint>nCurrent && pPager->useJournal );
  54890. /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM
  54891. ** if the allocation fails. Otherwise, zero the new portion in case a
  54892. ** malloc failure occurs while populating it in the for(...) loop below.
  54893. */
  54894. aNew = (PagerSavepoint *)sqlite3Realloc(
  54895. pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint
  54896. );
  54897. if( !aNew ){
  54898. return SQLITE_NOMEM_BKPT;
  54899. }
  54900. memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));
  54901. pPager->aSavepoint = aNew;
  54902. /* Populate the PagerSavepoint structures just allocated. */
  54903. for(ii=nCurrent; ii<nSavepoint; ii++){
  54904. aNew[ii].nOrig = pPager->dbSize;
  54905. if( isOpen(pPager->jfd) && pPager->journalOff>0 ){
  54906. aNew[ii].iOffset = pPager->journalOff;
  54907. }else{
  54908. aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);
  54909. }
  54910. aNew[ii].iSubRec = pPager->nSubRec;
  54911. aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize);
  54912. if( !aNew[ii].pInSavepoint ){
  54913. return SQLITE_NOMEM_BKPT;
  54914. }
  54915. if( pagerUseWal(pPager) ){
  54916. sqlite3WalSavepoint(pPager->pWal, aNew[ii].aWalData);
  54917. }
  54918. pPager->nSavepoint = ii+1;
  54919. }
  54920. assert( pPager->nSavepoint==nSavepoint );
  54921. assertTruncateConstraint(pPager);
  54922. return rc;
  54923. }
  54924. SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){
  54925. assert( pPager->eState>=PAGER_WRITER_LOCKED );
  54926. assert( assert_pager_state(pPager) );
  54927. if( nSavepoint>pPager->nSavepoint && pPager->useJournal ){
  54928. return pagerOpenSavepoint(pPager, nSavepoint);
  54929. }else{
  54930. return SQLITE_OK;
  54931. }
  54932. }
  54933. /*
  54934. ** This function is called to rollback or release (commit) a savepoint.
  54935. ** The savepoint to release or rollback need not be the most recently
  54936. ** created savepoint.
  54937. **
  54938. ** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.
  54939. ** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with
  54940. ** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes
  54941. ** that have occurred since the specified savepoint was created.
  54942. **
  54943. ** The savepoint to rollback or release is identified by parameter
  54944. ** iSavepoint. A value of 0 means to operate on the outermost savepoint
  54945. ** (the first created). A value of (Pager.nSavepoint-1) means operate
  54946. ** on the most recently created savepoint. If iSavepoint is greater than
  54947. ** (Pager.nSavepoint-1), then this function is a no-op.
  54948. **
  54949. ** If a negative value is passed to this function, then the current
  54950. ** transaction is rolled back. This is different to calling
  54951. ** sqlite3PagerRollback() because this function does not terminate
  54952. ** the transaction or unlock the database, it just restores the
  54953. ** contents of the database to its original state.
  54954. **
  54955. ** In any case, all savepoints with an index greater than iSavepoint
  54956. ** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE),
  54957. ** then savepoint iSavepoint is also destroyed.
  54958. **
  54959. ** This function may return SQLITE_NOMEM if a memory allocation fails,
  54960. ** or an IO error code if an IO error occurs while rolling back a
  54961. ** savepoint. If no errors occur, SQLITE_OK is returned.
  54962. */
  54963. SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
  54964. int rc = pPager->errCode;
  54965. #ifdef SQLITE_ENABLE_ZIPVFS
  54966. if( op==SAVEPOINT_RELEASE ) rc = SQLITE_OK;
  54967. #endif
  54968. assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
  54969. assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK );
  54970. if( rc==SQLITE_OK && iSavepoint<pPager->nSavepoint ){
  54971. int ii; /* Iterator variable */
  54972. int nNew; /* Number of remaining savepoints after this op. */
  54973. /* Figure out how many savepoints will still be active after this
  54974. ** operation. Store this value in nNew. Then free resources associated
  54975. ** with any savepoints that are destroyed by this operation.
  54976. */
  54977. nNew = iSavepoint + (( op==SAVEPOINT_RELEASE ) ? 0 : 1);
  54978. for(ii=nNew; ii<pPager->nSavepoint; ii++){
  54979. sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
  54980. }
  54981. pPager->nSavepoint = nNew;
  54982. /* If this is a release of the outermost savepoint, truncate
  54983. ** the sub-journal to zero bytes in size. */
  54984. if( op==SAVEPOINT_RELEASE ){
  54985. if( nNew==0 && isOpen(pPager->sjfd) ){
  54986. /* Only truncate if it is an in-memory sub-journal. */
  54987. if( sqlite3JournalIsInMemory(pPager->sjfd) ){
  54988. rc = sqlite3OsTruncate(pPager->sjfd, 0);
  54989. assert( rc==SQLITE_OK );
  54990. }
  54991. pPager->nSubRec = 0;
  54992. }
  54993. }
  54994. /* Else this is a rollback operation, playback the specified savepoint.
  54995. ** If this is a temp-file, it is possible that the journal file has
  54996. ** not yet been opened. In this case there have been no changes to
  54997. ** the database file, so the playback operation can be skipped.
  54998. */
  54999. else if( pagerUseWal(pPager) || isOpen(pPager->jfd) ){
  55000. PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
  55001. rc = pagerPlaybackSavepoint(pPager, pSavepoint);
  55002. assert(rc!=SQLITE_DONE);
  55003. }
  55004. #ifdef SQLITE_ENABLE_ZIPVFS
  55005. /* If the cache has been modified but the savepoint cannot be rolled
  55006. ** back journal_mode=off, put the pager in the error state. This way,
  55007. ** if the VFS used by this pager includes ZipVFS, the entire transaction
  55008. ** can be rolled back at the ZipVFS level. */
  55009. else if(
  55010. pPager->journalMode==PAGER_JOURNALMODE_OFF
  55011. && pPager->eState>=PAGER_WRITER_CACHEMOD
  55012. ){
  55013. pPager->errCode = SQLITE_ABORT;
  55014. pPager->eState = PAGER_ERROR;
  55015. setGetterMethod(pPager);
  55016. }
  55017. #endif
  55018. }
  55019. return rc;
  55020. }
  55021. /*
  55022. ** Return the full pathname of the database file.
  55023. **
  55024. ** Except, if the pager is in-memory only, then return an empty string if
  55025. ** nullIfMemDb is true. This routine is called with nullIfMemDb==1 when
  55026. ** used to report the filename to the user, for compatibility with legacy
  55027. ** behavior. But when the Btree needs to know the filename for matching to
  55028. ** shared cache, it uses nullIfMemDb==0 so that in-memory databases can
  55029. ** participate in shared-cache.
  55030. **
  55031. ** The return value to this routine is always safe to use with
  55032. ** sqlite3_uri_parameter() and sqlite3_filename_database() and friends.
  55033. */
  55034. SQLITE_PRIVATE const char *sqlite3PagerFilename(const Pager *pPager, int nullIfMemDb){
  55035. static const char zFake[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };
  55036. return (nullIfMemDb && pPager->memDb) ? &zFake[4] : pPager->zFilename;
  55037. }
  55038. /*
  55039. ** Return the VFS structure for the pager.
  55040. */
  55041. SQLITE_PRIVATE sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
  55042. return pPager->pVfs;
  55043. }
  55044. /*
  55045. ** Return the file handle for the database file associated
  55046. ** with the pager. This might return NULL if the file has
  55047. ** not yet been opened.
  55048. */
  55049. SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){
  55050. return pPager->fd;
  55051. }
  55052. /*
  55053. ** Return the file handle for the journal file (if it exists).
  55054. ** This will be either the rollback journal or the WAL file.
  55055. */
  55056. SQLITE_PRIVATE sqlite3_file *sqlite3PagerJrnlFile(Pager *pPager){
  55057. #if SQLITE_OMIT_WAL
  55058. return pPager->jfd;
  55059. #else
  55060. return pPager->pWal ? sqlite3WalFile(pPager->pWal) : pPager->jfd;
  55061. #endif
  55062. }
  55063. /*
  55064. ** Return the full pathname of the journal file.
  55065. */
  55066. SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){
  55067. return pPager->zJournal;
  55068. }
  55069. #ifndef SQLITE_OMIT_AUTOVACUUM
  55070. /*
  55071. ** Move the page pPg to location pgno in the file.
  55072. **
  55073. ** There must be no references to the page previously located at
  55074. ** pgno (which we call pPgOld) though that page is allowed to be
  55075. ** in cache. If the page previously located at pgno is not already
  55076. ** in the rollback journal, it is not put there by by this routine.
  55077. **
  55078. ** References to the page pPg remain valid. Updating any
  55079. ** meta-data associated with pPg (i.e. data stored in the nExtra bytes
  55080. ** allocated along with the page) is the responsibility of the caller.
  55081. **
  55082. ** A transaction must be active when this routine is called. It used to be
  55083. ** required that a statement transaction was not active, but this restriction
  55084. ** has been removed (CREATE INDEX needs to move a page when a statement
  55085. ** transaction is active).
  55086. **
  55087. ** If the fourth argument, isCommit, is non-zero, then this page is being
  55088. ** moved as part of a database reorganization just before the transaction
  55089. ** is being committed. In this case, it is guaranteed that the database page
  55090. ** pPg refers to will not be written to again within this transaction.
  55091. **
  55092. ** This function may return SQLITE_NOMEM or an IO error code if an error
  55093. ** occurs. Otherwise, it returns SQLITE_OK.
  55094. */
  55095. SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
  55096. PgHdr *pPgOld; /* The page being overwritten. */
  55097. Pgno needSyncPgno = 0; /* Old value of pPg->pgno, if sync is required */
  55098. int rc; /* Return code */
  55099. Pgno origPgno; /* The original page number */
  55100. assert( pPg->nRef>0 );
  55101. assert( pPager->eState==PAGER_WRITER_CACHEMOD
  55102. || pPager->eState==PAGER_WRITER_DBMOD
  55103. );
  55104. assert( assert_pager_state(pPager) );
  55105. /* In order to be able to rollback, an in-memory database must journal
  55106. ** the page we are moving from.
  55107. */
  55108. assert( pPager->tempFile || !MEMDB );
  55109. if( pPager->tempFile ){
  55110. rc = sqlite3PagerWrite(pPg);
  55111. if( rc ) return rc;
  55112. }
  55113. /* If the page being moved is dirty and has not been saved by the latest
  55114. ** savepoint, then save the current contents of the page into the
  55115. ** sub-journal now. This is required to handle the following scenario:
  55116. **
  55117. ** BEGIN;
  55118. ** <journal page X, then modify it in memory>
  55119. ** SAVEPOINT one;
  55120. ** <Move page X to location Y>
  55121. ** ROLLBACK TO one;
  55122. **
  55123. ** If page X were not written to the sub-journal here, it would not
  55124. ** be possible to restore its contents when the "ROLLBACK TO one"
  55125. ** statement were is processed.
  55126. **
  55127. ** subjournalPage() may need to allocate space to store pPg->pgno into
  55128. ** one or more savepoint bitvecs. This is the reason this function
  55129. ** may return SQLITE_NOMEM.
  55130. */
  55131. if( (pPg->flags & PGHDR_DIRTY)!=0
  55132. && SQLITE_OK!=(rc = subjournalPageIfRequired(pPg))
  55133. ){
  55134. return rc;
  55135. }
  55136. PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n",
  55137. PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));
  55138. IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
  55139. /* If the journal needs to be sync()ed before page pPg->pgno can
  55140. ** be written to, store pPg->pgno in local variable needSyncPgno.
  55141. **
  55142. ** If the isCommit flag is set, there is no need to remember that
  55143. ** the journal needs to be sync()ed before database page pPg->pgno
  55144. ** can be written to. The caller has already promised not to write to it.
  55145. */
  55146. if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
  55147. needSyncPgno = pPg->pgno;
  55148. assert( pPager->journalMode==PAGER_JOURNALMODE_OFF ||
  55149. pageInJournal(pPager, pPg) || pPg->pgno>pPager->dbOrigSize );
  55150. assert( pPg->flags&PGHDR_DIRTY );
  55151. }
  55152. /* If the cache contains a page with page-number pgno, remove it
  55153. ** from its hash chain. Also, if the PGHDR_NEED_SYNC flag was set for
  55154. ** page pgno before the 'move' operation, it needs to be retained
  55155. ** for the page moved there.
  55156. */
  55157. pPg->flags &= ~PGHDR_NEED_SYNC;
  55158. pPgOld = sqlite3PagerLookup(pPager, pgno);
  55159. assert( !pPgOld || pPgOld->nRef==1 || CORRUPT_DB );
  55160. if( pPgOld ){
  55161. if( pPgOld->nRef>1 ){
  55162. sqlite3PagerUnrefNotNull(pPgOld);
  55163. return SQLITE_CORRUPT_BKPT;
  55164. }
  55165. pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
  55166. if( pPager->tempFile ){
  55167. /* Do not discard pages from an in-memory database since we might
  55168. ** need to rollback later. Just move the page out of the way. */
  55169. sqlite3PcacheMove(pPgOld, pPager->dbSize+1);
  55170. }else{
  55171. sqlite3PcacheDrop(pPgOld);
  55172. }
  55173. }
  55174. origPgno = pPg->pgno;
  55175. sqlite3PcacheMove(pPg, pgno);
  55176. sqlite3PcacheMakeDirty(pPg);
  55177. /* For an in-memory database, make sure the original page continues
  55178. ** to exist, in case the transaction needs to roll back. Use pPgOld
  55179. ** as the original page since it has already been allocated.
  55180. */
  55181. if( pPager->tempFile && pPgOld ){
  55182. sqlite3PcacheMove(pPgOld, origPgno);
  55183. sqlite3PagerUnrefNotNull(pPgOld);
  55184. }
  55185. if( needSyncPgno ){
  55186. /* If needSyncPgno is non-zero, then the journal file needs to be
  55187. ** sync()ed before any data is written to database file page needSyncPgno.
  55188. ** Currently, no such page exists in the page-cache and the
  55189. ** "is journaled" bitvec flag has been set. This needs to be remedied by
  55190. ** loading the page into the pager-cache and setting the PGHDR_NEED_SYNC
  55191. ** flag.
  55192. **
  55193. ** If the attempt to load the page into the page-cache fails, (due
  55194. ** to a malloc() or IO failure), clear the bit in the pInJournal[]
  55195. ** array. Otherwise, if the page is loaded and written again in
  55196. ** this transaction, it may be written to the database file before
  55197. ** it is synced into the journal file. This way, it may end up in
  55198. ** the journal file twice, but that is not a problem.
  55199. */
  55200. PgHdr *pPgHdr;
  55201. rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr, 0);
  55202. if( rc!=SQLITE_OK ){
  55203. if( needSyncPgno<=pPager->dbOrigSize ){
  55204. assert( pPager->pTmpSpace!=0 );
  55205. sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace);
  55206. }
  55207. return rc;
  55208. }
  55209. pPgHdr->flags |= PGHDR_NEED_SYNC;
  55210. sqlite3PcacheMakeDirty(pPgHdr);
  55211. sqlite3PagerUnrefNotNull(pPgHdr);
  55212. }
  55213. return SQLITE_OK;
  55214. }
  55215. #endif
  55216. /*
  55217. ** The page handle passed as the first argument refers to a dirty page
  55218. ** with a page number other than iNew. This function changes the page's
  55219. ** page number to iNew and sets the value of the PgHdr.flags field to
  55220. ** the value passed as the third parameter.
  55221. */
  55222. SQLITE_PRIVATE void sqlite3PagerRekey(DbPage *pPg, Pgno iNew, u16 flags){
  55223. assert( pPg->pgno!=iNew );
  55224. pPg->flags = flags;
  55225. sqlite3PcacheMove(pPg, iNew);
  55226. }
  55227. /*
  55228. ** Return a pointer to the data for the specified page.
  55229. */
  55230. SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){
  55231. assert( pPg->nRef>0 || pPg->pPager->memDb );
  55232. return pPg->pData;
  55233. }
  55234. /*
  55235. ** Return a pointer to the Pager.nExtra bytes of "extra" space
  55236. ** allocated along with the specified page.
  55237. */
  55238. SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){
  55239. return pPg->pExtra;
  55240. }
  55241. /*
  55242. ** Get/set the locking-mode for this pager. Parameter eMode must be one
  55243. ** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or
  55244. ** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
  55245. ** the locking-mode is set to the value specified.
  55246. **
  55247. ** The returned value is either PAGER_LOCKINGMODE_NORMAL or
  55248. ** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
  55249. ** locking-mode.
  55250. */
  55251. SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){
  55252. assert( eMode==PAGER_LOCKINGMODE_QUERY
  55253. || eMode==PAGER_LOCKINGMODE_NORMAL
  55254. || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
  55255. assert( PAGER_LOCKINGMODE_QUERY<0 );
  55256. assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
  55257. assert( pPager->exclusiveMode || 0==sqlite3WalHeapMemory(pPager->pWal) );
  55258. if( eMode>=0 && !pPager->tempFile && !sqlite3WalHeapMemory(pPager->pWal) ){
  55259. pPager->exclusiveMode = (u8)eMode;
  55260. }
  55261. return (int)pPager->exclusiveMode;
  55262. }
  55263. /*
  55264. ** Set the journal-mode for this pager. Parameter eMode must be one of:
  55265. **
  55266. ** PAGER_JOURNALMODE_DELETE
  55267. ** PAGER_JOURNALMODE_TRUNCATE
  55268. ** PAGER_JOURNALMODE_PERSIST
  55269. ** PAGER_JOURNALMODE_OFF
  55270. ** PAGER_JOURNALMODE_MEMORY
  55271. ** PAGER_JOURNALMODE_WAL
  55272. **
  55273. ** The journalmode is set to the value specified if the change is allowed.
  55274. ** The change may be disallowed for the following reasons:
  55275. **
  55276. ** * An in-memory database can only have its journal_mode set to _OFF
  55277. ** or _MEMORY.
  55278. **
  55279. ** * Temporary databases cannot have _WAL journalmode.
  55280. **
  55281. ** The returned indicate the current (possibly updated) journal-mode.
  55282. */
  55283. SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *pPager, int eMode){
  55284. u8 eOld = pPager->journalMode; /* Prior journalmode */
  55285. /* The eMode parameter is always valid */
  55286. assert( eMode==PAGER_JOURNALMODE_DELETE
  55287. || eMode==PAGER_JOURNALMODE_TRUNCATE
  55288. || eMode==PAGER_JOURNALMODE_PERSIST
  55289. || eMode==PAGER_JOURNALMODE_OFF
  55290. || eMode==PAGER_JOURNALMODE_WAL
  55291. || eMode==PAGER_JOURNALMODE_MEMORY );
  55292. /* This routine is only called from the OP_JournalMode opcode, and
  55293. ** the logic there will never allow a temporary file to be changed
  55294. ** to WAL mode.
  55295. */
  55296. assert( pPager->tempFile==0 || eMode!=PAGER_JOURNALMODE_WAL );
  55297. /* Do allow the journalmode of an in-memory database to be set to
  55298. ** anything other than MEMORY or OFF
  55299. */
  55300. if( MEMDB ){
  55301. assert( eOld==PAGER_JOURNALMODE_MEMORY || eOld==PAGER_JOURNALMODE_OFF );
  55302. if( eMode!=PAGER_JOURNALMODE_MEMORY && eMode!=PAGER_JOURNALMODE_OFF ){
  55303. eMode = eOld;
  55304. }
  55305. }
  55306. if( eMode!=eOld ){
  55307. /* Change the journal mode. */
  55308. assert( pPager->eState!=PAGER_ERROR );
  55309. pPager->journalMode = (u8)eMode;
  55310. /* When transistioning from TRUNCATE or PERSIST to any other journal
  55311. ** mode except WAL, unless the pager is in locking_mode=exclusive mode,
  55312. ** delete the journal file.
  55313. */
  55314. assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
  55315. assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
  55316. assert( (PAGER_JOURNALMODE_DELETE & 5)==0 );
  55317. assert( (PAGER_JOURNALMODE_MEMORY & 5)==4 );
  55318. assert( (PAGER_JOURNALMODE_OFF & 5)==0 );
  55319. assert( (PAGER_JOURNALMODE_WAL & 5)==5 );
  55320. assert( isOpen(pPager->fd) || pPager->exclusiveMode );
  55321. if( !pPager->exclusiveMode && (eOld & 5)==1 && (eMode & 1)==0 ){
  55322. /* In this case we would like to delete the journal file. If it is
  55323. ** not possible, then that is not a problem. Deleting the journal file
  55324. ** here is an optimization only.
  55325. **
  55326. ** Before deleting the journal file, obtain a RESERVED lock on the
  55327. ** database file. This ensures that the journal file is not deleted
  55328. ** while it is in use by some other client.
  55329. */
  55330. sqlite3OsClose(pPager->jfd);
  55331. if( pPager->eLock>=RESERVED_LOCK ){
  55332. sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
  55333. }else{
  55334. int rc = SQLITE_OK;
  55335. int state = pPager->eState;
  55336. assert( state==PAGER_OPEN || state==PAGER_READER );
  55337. if( state==PAGER_OPEN ){
  55338. rc = sqlite3PagerSharedLock(pPager);
  55339. }
  55340. if( pPager->eState==PAGER_READER ){
  55341. assert( rc==SQLITE_OK );
  55342. rc = pagerLockDb(pPager, RESERVED_LOCK);
  55343. }
  55344. if( rc==SQLITE_OK ){
  55345. sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
  55346. }
  55347. if( rc==SQLITE_OK && state==PAGER_READER ){
  55348. pagerUnlockDb(pPager, SHARED_LOCK);
  55349. }else if( state==PAGER_OPEN ){
  55350. pager_unlock(pPager);
  55351. }
  55352. assert( state==pPager->eState );
  55353. }
  55354. }else if( eMode==PAGER_JOURNALMODE_OFF ){
  55355. sqlite3OsClose(pPager->jfd);
  55356. }
  55357. }
  55358. /* Return the new journal mode */
  55359. return (int)pPager->journalMode;
  55360. }
  55361. /*
  55362. ** Return the current journal mode.
  55363. */
  55364. SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager *pPager){
  55365. return (int)pPager->journalMode;
  55366. }
  55367. /*
  55368. ** Return TRUE if the pager is in a state where it is OK to change the
  55369. ** journalmode. Journalmode changes can only happen when the database
  55370. ** is unmodified.
  55371. */
  55372. SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager *pPager){
  55373. assert( assert_pager_state(pPager) );
  55374. if( pPager->eState>=PAGER_WRITER_CACHEMOD ) return 0;
  55375. if( NEVER(isOpen(pPager->jfd) && pPager->journalOff>0) ) return 0;
  55376. return 1;
  55377. }
  55378. /*
  55379. ** Get/set the size-limit used for persistent journal files.
  55380. **
  55381. ** Setting the size limit to -1 means no limit is enforced.
  55382. ** An attempt to set a limit smaller than -1 is a no-op.
  55383. */
  55384. SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){
  55385. if( iLimit>=-1 ){
  55386. pPager->journalSizeLimit = iLimit;
  55387. sqlite3WalLimit(pPager->pWal, iLimit);
  55388. }
  55389. return pPager->journalSizeLimit;
  55390. }
  55391. /*
  55392. ** Return a pointer to the pPager->pBackup variable. The backup module
  55393. ** in backup.c maintains the content of this variable. This module
  55394. ** uses it opaquely as an argument to sqlite3BackupRestart() and
  55395. ** sqlite3BackupUpdate() only.
  55396. */
  55397. SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){
  55398. return &pPager->pBackup;
  55399. }
  55400. #ifndef SQLITE_OMIT_VACUUM
  55401. /*
  55402. ** Unless this is an in-memory or temporary database, clear the pager cache.
  55403. */
  55404. SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *pPager){
  55405. assert( MEMDB==0 || pPager->tempFile );
  55406. if( pPager->tempFile==0 ) pager_reset(pPager);
  55407. }
  55408. #endif
  55409. #ifndef SQLITE_OMIT_WAL
  55410. /*
  55411. ** This function is called when the user invokes "PRAGMA wal_checkpoint",
  55412. ** "PRAGMA wal_blocking_checkpoint" or calls the sqlite3_wal_checkpoint()
  55413. ** or wal_blocking_checkpoint() API functions.
  55414. **
  55415. ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
  55416. */
  55417. SQLITE_PRIVATE int sqlite3PagerCheckpoint(
  55418. Pager *pPager, /* Checkpoint on this pager */
  55419. sqlite3 *db, /* Db handle used to check for interrupts */
  55420. int eMode, /* Type of checkpoint */
  55421. int *pnLog, /* OUT: Final number of frames in log */
  55422. int *pnCkpt /* OUT: Final number of checkpointed frames */
  55423. ){
  55424. int rc = SQLITE_OK;
  55425. if( pPager->pWal ){
  55426. rc = sqlite3WalCheckpoint(pPager->pWal, db, eMode,
  55427. (eMode==SQLITE_CHECKPOINT_PASSIVE ? 0 : pPager->xBusyHandler),
  55428. pPager->pBusyHandlerArg,
  55429. pPager->walSyncFlags, pPager->pageSize, (u8 *)pPager->pTmpSpace,
  55430. pnLog, pnCkpt
  55431. );
  55432. }
  55433. return rc;
  55434. }
  55435. SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager){
  55436. return sqlite3WalCallback(pPager->pWal);
  55437. }
  55438. /*
  55439. ** Return true if the underlying VFS for the given pager supports the
  55440. ** primitives necessary for write-ahead logging.
  55441. */
  55442. SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager){
  55443. const sqlite3_io_methods *pMethods = pPager->fd->pMethods;
  55444. if( pPager->noLock ) return 0;
  55445. return pPager->exclusiveMode || (pMethods->iVersion>=2 && pMethods->xShmMap);
  55446. }
  55447. /*
  55448. ** Attempt to take an exclusive lock on the database file. If a PENDING lock
  55449. ** is obtained instead, immediately release it.
  55450. */
  55451. static int pagerExclusiveLock(Pager *pPager){
  55452. int rc; /* Return code */
  55453. assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
  55454. rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
  55455. if( rc!=SQLITE_OK ){
  55456. /* If the attempt to grab the exclusive lock failed, release the
  55457. ** pending lock that may have been obtained instead. */
  55458. pagerUnlockDb(pPager, SHARED_LOCK);
  55459. }
  55460. return rc;
  55461. }
  55462. /*
  55463. ** Call sqlite3WalOpen() to open the WAL handle. If the pager is in
  55464. ** exclusive-locking mode when this function is called, take an EXCLUSIVE
  55465. ** lock on the database file and use heap-memory to store the wal-index
  55466. ** in. Otherwise, use the normal shared-memory.
  55467. */
  55468. static int pagerOpenWal(Pager *pPager){
  55469. int rc = SQLITE_OK;
  55470. assert( pPager->pWal==0 && pPager->tempFile==0 );
  55471. assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
  55472. /* If the pager is already in exclusive-mode, the WAL module will use
  55473. ** heap-memory for the wal-index instead of the VFS shared-memory
  55474. ** implementation. Take the exclusive lock now, before opening the WAL
  55475. ** file, to make sure this is safe.
  55476. */
  55477. if( pPager->exclusiveMode ){
  55478. rc = pagerExclusiveLock(pPager);
  55479. }
  55480. /* Open the connection to the log file. If this operation fails,
  55481. ** (e.g. due to malloc() failure), return an error code.
  55482. */
  55483. if( rc==SQLITE_OK ){
  55484. rc = sqlite3WalOpen(pPager->pVfs,
  55485. pPager->fd, pPager->zWal, pPager->exclusiveMode,
  55486. pPager->journalSizeLimit, &pPager->pWal
  55487. );
  55488. }
  55489. pagerFixMaplimit(pPager);
  55490. return rc;
  55491. }
  55492. /*
  55493. ** The caller must be holding a SHARED lock on the database file to call
  55494. ** this function.
  55495. **
  55496. ** If the pager passed as the first argument is open on a real database
  55497. ** file (not a temp file or an in-memory database), and the WAL file
  55498. ** is not already open, make an attempt to open it now. If successful,
  55499. ** return SQLITE_OK. If an error occurs or the VFS used by the pager does
  55500. ** not support the xShmXXX() methods, return an error code. *pbOpen is
  55501. ** not modified in either case.
  55502. **
  55503. ** If the pager is open on a temp-file (or in-memory database), or if
  55504. ** the WAL file is already open, set *pbOpen to 1 and return SQLITE_OK
  55505. ** without doing anything.
  55506. */
  55507. SQLITE_PRIVATE int sqlite3PagerOpenWal(
  55508. Pager *pPager, /* Pager object */
  55509. int *pbOpen /* OUT: Set to true if call is a no-op */
  55510. ){
  55511. int rc = SQLITE_OK; /* Return code */
  55512. assert( assert_pager_state(pPager) );
  55513. assert( pPager->eState==PAGER_OPEN || pbOpen );
  55514. assert( pPager->eState==PAGER_READER || !pbOpen );
  55515. assert( pbOpen==0 || *pbOpen==0 );
  55516. assert( pbOpen!=0 || (!pPager->tempFile && !pPager->pWal) );
  55517. if( !pPager->tempFile && !pPager->pWal ){
  55518. if( !sqlite3PagerWalSupported(pPager) ) return SQLITE_CANTOPEN;
  55519. /* Close any rollback journal previously open */
  55520. sqlite3OsClose(pPager->jfd);
  55521. rc = pagerOpenWal(pPager);
  55522. if( rc==SQLITE_OK ){
  55523. pPager->journalMode = PAGER_JOURNALMODE_WAL;
  55524. pPager->eState = PAGER_OPEN;
  55525. }
  55526. }else{
  55527. *pbOpen = 1;
  55528. }
  55529. return rc;
  55530. }
  55531. /*
  55532. ** This function is called to close the connection to the log file prior
  55533. ** to switching from WAL to rollback mode.
  55534. **
  55535. ** Before closing the log file, this function attempts to take an
  55536. ** EXCLUSIVE lock on the database file. If this cannot be obtained, an
  55537. ** error (SQLITE_BUSY) is returned and the log connection is not closed.
  55538. ** If successful, the EXCLUSIVE lock is not released before returning.
  55539. */
  55540. SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager, sqlite3 *db){
  55541. int rc = SQLITE_OK;
  55542. assert( pPager->journalMode==PAGER_JOURNALMODE_WAL );
  55543. /* If the log file is not already open, but does exist in the file-system,
  55544. ** it may need to be checkpointed before the connection can switch to
  55545. ** rollback mode. Open it now so this can happen.
  55546. */
  55547. if( !pPager->pWal ){
  55548. int logexists = 0;
  55549. rc = pagerLockDb(pPager, SHARED_LOCK);
  55550. if( rc==SQLITE_OK ){
  55551. rc = sqlite3OsAccess(
  55552. pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &logexists
  55553. );
  55554. }
  55555. if( rc==SQLITE_OK && logexists ){
  55556. rc = pagerOpenWal(pPager);
  55557. }
  55558. }
  55559. /* Checkpoint and close the log. Because an EXCLUSIVE lock is held on
  55560. ** the database file, the log and log-summary files will be deleted.
  55561. */
  55562. if( rc==SQLITE_OK && pPager->pWal ){
  55563. rc = pagerExclusiveLock(pPager);
  55564. if( rc==SQLITE_OK ){
  55565. rc = sqlite3WalClose(pPager->pWal, db, pPager->walSyncFlags,
  55566. pPager->pageSize, (u8*)pPager->pTmpSpace);
  55567. pPager->pWal = 0;
  55568. pagerFixMaplimit(pPager);
  55569. if( rc && !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
  55570. }
  55571. }
  55572. return rc;
  55573. }
  55574. #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
  55575. /*
  55576. ** If pager pPager is a wal-mode database not in exclusive locking mode,
  55577. ** invoke the sqlite3WalWriteLock() function on the associated Wal object
  55578. ** with the same db and bLock parameters as were passed to this function.
  55579. ** Return an SQLite error code if an error occurs, or SQLITE_OK otherwise.
  55580. */
  55581. SQLITE_PRIVATE int sqlite3PagerWalWriteLock(Pager *pPager, int bLock){
  55582. int rc = SQLITE_OK;
  55583. if( pagerUseWal(pPager) && pPager->exclusiveMode==0 ){
  55584. rc = sqlite3WalWriteLock(pPager->pWal, bLock);
  55585. }
  55586. return rc;
  55587. }
  55588. /*
  55589. ** Set the database handle used by the wal layer to determine if
  55590. ** blocking locks are required.
  55591. */
  55592. SQLITE_PRIVATE void sqlite3PagerWalDb(Pager *pPager, sqlite3 *db){
  55593. if( pagerUseWal(pPager) ){
  55594. sqlite3WalDb(pPager->pWal, db);
  55595. }
  55596. }
  55597. #endif
  55598. #ifdef SQLITE_ENABLE_SNAPSHOT
  55599. /*
  55600. ** If this is a WAL database, obtain a snapshot handle for the snapshot
  55601. ** currently open. Otherwise, return an error.
  55602. */
  55603. SQLITE_PRIVATE int sqlite3PagerSnapshotGet(Pager *pPager, sqlite3_snapshot **ppSnapshot){
  55604. int rc = SQLITE_ERROR;
  55605. if( pPager->pWal ){
  55606. rc = sqlite3WalSnapshotGet(pPager->pWal, ppSnapshot);
  55607. }
  55608. return rc;
  55609. }
  55610. /*
  55611. ** If this is a WAL database, store a pointer to pSnapshot. Next time a
  55612. ** read transaction is opened, attempt to read from the snapshot it
  55613. ** identifies. If this is not a WAL database, return an error.
  55614. */
  55615. SQLITE_PRIVATE int sqlite3PagerSnapshotOpen(
  55616. Pager *pPager,
  55617. sqlite3_snapshot *pSnapshot
  55618. ){
  55619. int rc = SQLITE_OK;
  55620. if( pPager->pWal ){
  55621. sqlite3WalSnapshotOpen(pPager->pWal, pSnapshot);
  55622. }else{
  55623. rc = SQLITE_ERROR;
  55624. }
  55625. return rc;
  55626. }
  55627. /*
  55628. ** If this is a WAL database, call sqlite3WalSnapshotRecover(). If this
  55629. ** is not a WAL database, return an error.
  55630. */
  55631. SQLITE_PRIVATE int sqlite3PagerSnapshotRecover(Pager *pPager){
  55632. int rc;
  55633. if( pPager->pWal ){
  55634. rc = sqlite3WalSnapshotRecover(pPager->pWal);
  55635. }else{
  55636. rc = SQLITE_ERROR;
  55637. }
  55638. return rc;
  55639. }
  55640. /*
  55641. ** The caller currently has a read transaction open on the database.
  55642. ** If this is not a WAL database, SQLITE_ERROR is returned. Otherwise,
  55643. ** this function takes a SHARED lock on the CHECKPOINTER slot and then
  55644. ** checks if the snapshot passed as the second argument is still
  55645. ** available. If so, SQLITE_OK is returned.
  55646. **
  55647. ** If the snapshot is not available, SQLITE_ERROR is returned. Or, if
  55648. ** the CHECKPOINTER lock cannot be obtained, SQLITE_BUSY. If any error
  55649. ** occurs (any value other than SQLITE_OK is returned), the CHECKPOINTER
  55650. ** lock is released before returning.
  55651. */
  55652. SQLITE_PRIVATE int sqlite3PagerSnapshotCheck(Pager *pPager, sqlite3_snapshot *pSnapshot){
  55653. int rc;
  55654. if( pPager->pWal ){
  55655. rc = sqlite3WalSnapshotCheck(pPager->pWal, pSnapshot);
  55656. }else{
  55657. rc = SQLITE_ERROR;
  55658. }
  55659. return rc;
  55660. }
  55661. /*
  55662. ** Release a lock obtained by an earlier successful call to
  55663. ** sqlite3PagerSnapshotCheck().
  55664. */
  55665. SQLITE_PRIVATE void sqlite3PagerSnapshotUnlock(Pager *pPager){
  55666. assert( pPager->pWal );
  55667. sqlite3WalSnapshotUnlock(pPager->pWal);
  55668. }
  55669. #endif /* SQLITE_ENABLE_SNAPSHOT */
  55670. #endif /* !SQLITE_OMIT_WAL */
  55671. #ifdef SQLITE_ENABLE_ZIPVFS
  55672. /*
  55673. ** A read-lock must be held on the pager when this function is called. If
  55674. ** the pager is in WAL mode and the WAL file currently contains one or more
  55675. ** frames, return the size in bytes of the page images stored within the
  55676. ** WAL frames. Otherwise, if this is not a WAL database or the WAL file
  55677. ** is empty, return 0.
  55678. */
  55679. SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager){
  55680. assert( pPager->eState>=PAGER_READER );
  55681. return sqlite3WalFramesize(pPager->pWal);
  55682. }
  55683. #endif
  55684. #endif /* SQLITE_OMIT_DISKIO */
  55685. /************** End of pager.c ***********************************************/
  55686. /************** Begin file wal.c *********************************************/
  55687. /*
  55688. ** 2010 February 1
  55689. **
  55690. ** The author disclaims copyright to this source code. In place of
  55691. ** a legal notice, here is a blessing:
  55692. **
  55693. ** May you do good and not evil.
  55694. ** May you find forgiveness for yourself and forgive others.
  55695. ** May you share freely, never taking more than you give.
  55696. **
  55697. *************************************************************************
  55698. **
  55699. ** This file contains the implementation of a write-ahead log (WAL) used in
  55700. ** "journal_mode=WAL" mode.
  55701. **
  55702. ** WRITE-AHEAD LOG (WAL) FILE FORMAT
  55703. **
  55704. ** A WAL file consists of a header followed by zero or more "frames".
  55705. ** Each frame records the revised content of a single page from the
  55706. ** database file. All changes to the database are recorded by writing
  55707. ** frames into the WAL. Transactions commit when a frame is written that
  55708. ** contains a commit marker. A single WAL can and usually does record
  55709. ** multiple transactions. Periodically, the content of the WAL is
  55710. ** transferred back into the database file in an operation called a
  55711. ** "checkpoint".
  55712. **
  55713. ** A single WAL file can be used multiple times. In other words, the
  55714. ** WAL can fill up with frames and then be checkpointed and then new
  55715. ** frames can overwrite the old ones. A WAL always grows from beginning
  55716. ** toward the end. Checksums and counters attached to each frame are
  55717. ** used to determine which frames within the WAL are valid and which
  55718. ** are leftovers from prior checkpoints.
  55719. **
  55720. ** The WAL header is 32 bytes in size and consists of the following eight
  55721. ** big-endian 32-bit unsigned integer values:
  55722. **
  55723. ** 0: Magic number. 0x377f0682 or 0x377f0683
  55724. ** 4: File format version. Currently 3007000
  55725. ** 8: Database page size. Example: 1024
  55726. ** 12: Checkpoint sequence number
  55727. ** 16: Salt-1, random integer incremented with each checkpoint
  55728. ** 20: Salt-2, a different random integer changing with each ckpt
  55729. ** 24: Checksum-1 (first part of checksum for first 24 bytes of header).
  55730. ** 28: Checksum-2 (second part of checksum for first 24 bytes of header).
  55731. **
  55732. ** Immediately following the wal-header are zero or more frames. Each
  55733. ** frame consists of a 24-byte frame-header followed by a <page-size> bytes
  55734. ** of page data. The frame-header is six big-endian 32-bit unsigned
  55735. ** integer values, as follows:
  55736. **
  55737. ** 0: Page number.
  55738. ** 4: For commit records, the size of the database image in pages
  55739. ** after the commit. For all other records, zero.
  55740. ** 8: Salt-1 (copied from the header)
  55741. ** 12: Salt-2 (copied from the header)
  55742. ** 16: Checksum-1.
  55743. ** 20: Checksum-2.
  55744. **
  55745. ** A frame is considered valid if and only if the following conditions are
  55746. ** true:
  55747. **
  55748. ** (1) The salt-1 and salt-2 values in the frame-header match
  55749. ** salt values in the wal-header
  55750. **
  55751. ** (2) The checksum values in the final 8 bytes of the frame-header
  55752. ** exactly match the checksum computed consecutively on the
  55753. ** WAL header and the first 8 bytes and the content of all frames
  55754. ** up to and including the current frame.
  55755. **
  55756. ** The checksum is computed using 32-bit big-endian integers if the
  55757. ** magic number in the first 4 bytes of the WAL is 0x377f0683 and it
  55758. ** is computed using little-endian if the magic number is 0x377f0682.
  55759. ** The checksum values are always stored in the frame header in a
  55760. ** big-endian format regardless of which byte order is used to compute
  55761. ** the checksum. The checksum is computed by interpreting the input as
  55762. ** an even number of unsigned 32-bit integers: x[0] through x[N]. The
  55763. ** algorithm used for the checksum is as follows:
  55764. **
  55765. ** for i from 0 to n-1 step 2:
  55766. ** s0 += x[i] + s1;
  55767. ** s1 += x[i+1] + s0;
  55768. ** endfor
  55769. **
  55770. ** Note that s0 and s1 are both weighted checksums using fibonacci weights
  55771. ** in reverse order (the largest fibonacci weight occurs on the first element
  55772. ** of the sequence being summed.) The s1 value spans all 32-bit
  55773. ** terms of the sequence whereas s0 omits the final term.
  55774. **
  55775. ** On a checkpoint, the WAL is first VFS.xSync-ed, then valid content of the
  55776. ** WAL is transferred into the database, then the database is VFS.xSync-ed.
  55777. ** The VFS.xSync operations serve as write barriers - all writes launched
  55778. ** before the xSync must complete before any write that launches after the
  55779. ** xSync begins.
  55780. **
  55781. ** After each checkpoint, the salt-1 value is incremented and the salt-2
  55782. ** value is randomized. This prevents old and new frames in the WAL from
  55783. ** being considered valid at the same time and being checkpointing together
  55784. ** following a crash.
  55785. **
  55786. ** READER ALGORITHM
  55787. **
  55788. ** To read a page from the database (call it page number P), a reader
  55789. ** first checks the WAL to see if it contains page P. If so, then the
  55790. ** last valid instance of page P that is a followed by a commit frame
  55791. ** or is a commit frame itself becomes the value read. If the WAL
  55792. ** contains no copies of page P that are valid and which are a commit
  55793. ** frame or are followed by a commit frame, then page P is read from
  55794. ** the database file.
  55795. **
  55796. ** To start a read transaction, the reader records the index of the last
  55797. ** valid frame in the WAL. The reader uses this recorded "mxFrame" value
  55798. ** for all subsequent read operations. New transactions can be appended
  55799. ** to the WAL, but as long as the reader uses its original mxFrame value
  55800. ** and ignores the newly appended content, it will see a consistent snapshot
  55801. ** of the database from a single point in time. This technique allows
  55802. ** multiple concurrent readers to view different versions of the database
  55803. ** content simultaneously.
  55804. **
  55805. ** The reader algorithm in the previous paragraphs works correctly, but
  55806. ** because frames for page P can appear anywhere within the WAL, the
  55807. ** reader has to scan the entire WAL looking for page P frames. If the
  55808. ** WAL is large (multiple megabytes is typical) that scan can be slow,
  55809. ** and read performance suffers. To overcome this problem, a separate
  55810. ** data structure called the wal-index is maintained to expedite the
  55811. ** search for frames of a particular page.
  55812. **
  55813. ** WAL-INDEX FORMAT
  55814. **
  55815. ** Conceptually, the wal-index is shared memory, though VFS implementations
  55816. ** might choose to implement the wal-index using a mmapped file. Because
  55817. ** the wal-index is shared memory, SQLite does not support journal_mode=WAL
  55818. ** on a network filesystem. All users of the database must be able to
  55819. ** share memory.
  55820. **
  55821. ** In the default unix and windows implementation, the wal-index is a mmapped
  55822. ** file whose name is the database name with a "-shm" suffix added. For that
  55823. ** reason, the wal-index is sometimes called the "shm" file.
  55824. **
  55825. ** The wal-index is transient. After a crash, the wal-index can (and should
  55826. ** be) reconstructed from the original WAL file. In fact, the VFS is required
  55827. ** to either truncate or zero the header of the wal-index when the last
  55828. ** connection to it closes. Because the wal-index is transient, it can
  55829. ** use an architecture-specific format; it does not have to be cross-platform.
  55830. ** Hence, unlike the database and WAL file formats which store all values
  55831. ** as big endian, the wal-index can store multi-byte values in the native
  55832. ** byte order of the host computer.
  55833. **
  55834. ** The purpose of the wal-index is to answer this question quickly: Given
  55835. ** a page number P and a maximum frame index M, return the index of the
  55836. ** last frame in the wal before frame M for page P in the WAL, or return
  55837. ** NULL if there are no frames for page P in the WAL prior to M.
  55838. **
  55839. ** The wal-index consists of a header region, followed by an one or
  55840. ** more index blocks.
  55841. **
  55842. ** The wal-index header contains the total number of frames within the WAL
  55843. ** in the mxFrame field.
  55844. **
  55845. ** Each index block except for the first contains information on
  55846. ** HASHTABLE_NPAGE frames. The first index block contains information on
  55847. ** HASHTABLE_NPAGE_ONE frames. The values of HASHTABLE_NPAGE_ONE and
  55848. ** HASHTABLE_NPAGE are selected so that together the wal-index header and
  55849. ** first index block are the same size as all other index blocks in the
  55850. ** wal-index.
  55851. **
  55852. ** Each index block contains two sections, a page-mapping that contains the
  55853. ** database page number associated with each wal frame, and a hash-table
  55854. ** that allows readers to query an index block for a specific page number.
  55855. ** The page-mapping is an array of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE
  55856. ** for the first index block) 32-bit page numbers. The first entry in the
  55857. ** first index-block contains the database page number corresponding to the
  55858. ** first frame in the WAL file. The first entry in the second index block
  55859. ** in the WAL file corresponds to the (HASHTABLE_NPAGE_ONE+1)th frame in
  55860. ** the log, and so on.
  55861. **
  55862. ** The last index block in a wal-index usually contains less than the full
  55863. ** complement of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE) page-numbers,
  55864. ** depending on the contents of the WAL file. This does not change the
  55865. ** allocated size of the page-mapping array - the page-mapping array merely
  55866. ** contains unused entries.
  55867. **
  55868. ** Even without using the hash table, the last frame for page P
  55869. ** can be found by scanning the page-mapping sections of each index block
  55870. ** starting with the last index block and moving toward the first, and
  55871. ** within each index block, starting at the end and moving toward the
  55872. ** beginning. The first entry that equals P corresponds to the frame
  55873. ** holding the content for that page.
  55874. **
  55875. ** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers.
  55876. ** HASHTABLE_NSLOT = 2*HASHTABLE_NPAGE, and there is one entry in the
  55877. ** hash table for each page number in the mapping section, so the hash
  55878. ** table is never more than half full. The expected number of collisions
  55879. ** prior to finding a match is 1. Each entry of the hash table is an
  55880. ** 1-based index of an entry in the mapping section of the same
  55881. ** index block. Let K be the 1-based index of the largest entry in
  55882. ** the mapping section. (For index blocks other than the last, K will
  55883. ** always be exactly HASHTABLE_NPAGE (4096) and for the last index block
  55884. ** K will be (mxFrame%HASHTABLE_NPAGE).) Unused slots of the hash table
  55885. ** contain a value of 0.
  55886. **
  55887. ** To look for page P in the hash table, first compute a hash iKey on
  55888. ** P as follows:
  55889. **
  55890. ** iKey = (P * 383) % HASHTABLE_NSLOT
  55891. **
  55892. ** Then start scanning entries of the hash table, starting with iKey
  55893. ** (wrapping around to the beginning when the end of the hash table is
  55894. ** reached) until an unused hash slot is found. Let the first unused slot
  55895. ** be at index iUnused. (iUnused might be less than iKey if there was
  55896. ** wrap-around.) Because the hash table is never more than half full,
  55897. ** the search is guaranteed to eventually hit an unused entry. Let
  55898. ** iMax be the value between iKey and iUnused, closest to iUnused,
  55899. ** where aHash[iMax]==P. If there is no iMax entry (if there exists
  55900. ** no hash slot such that aHash[i]==p) then page P is not in the
  55901. ** current index block. Otherwise the iMax-th mapping entry of the
  55902. ** current index block corresponds to the last entry that references
  55903. ** page P.
  55904. **
  55905. ** A hash search begins with the last index block and moves toward the
  55906. ** first index block, looking for entries corresponding to page P. On
  55907. ** average, only two or three slots in each index block need to be
  55908. ** examined in order to either find the last entry for page P, or to
  55909. ** establish that no such entry exists in the block. Each index block
  55910. ** holds over 4000 entries. So two or three index blocks are sufficient
  55911. ** to cover a typical 10 megabyte WAL file, assuming 1K pages. 8 or 10
  55912. ** comparisons (on average) suffice to either locate a frame in the
  55913. ** WAL or to establish that the frame does not exist in the WAL. This
  55914. ** is much faster than scanning the entire 10MB WAL.
  55915. **
  55916. ** Note that entries are added in order of increasing K. Hence, one
  55917. ** reader might be using some value K0 and a second reader that started
  55918. ** at a later time (after additional transactions were added to the WAL
  55919. ** and to the wal-index) might be using a different value K1, where K1>K0.
  55920. ** Both readers can use the same hash table and mapping section to get
  55921. ** the correct result. There may be entries in the hash table with
  55922. ** K>K0 but to the first reader, those entries will appear to be unused
  55923. ** slots in the hash table and so the first reader will get an answer as
  55924. ** if no values greater than K0 had ever been inserted into the hash table
  55925. ** in the first place - which is what reader one wants. Meanwhile, the
  55926. ** second reader using K1 will see additional values that were inserted
  55927. ** later, which is exactly what reader two wants.
  55928. **
  55929. ** When a rollback occurs, the value of K is decreased. Hash table entries
  55930. ** that correspond to frames greater than the new K value are removed
  55931. ** from the hash table at this point.
  55932. */
  55933. #ifndef SQLITE_OMIT_WAL
  55934. /* #include "wal.h" */
  55935. /*
  55936. ** Trace output macros
  55937. */
  55938. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  55939. SQLITE_PRIVATE int sqlite3WalTrace = 0;
  55940. # define WALTRACE(X) if(sqlite3WalTrace) sqlite3DebugPrintf X
  55941. #else
  55942. # define WALTRACE(X)
  55943. #endif
  55944. /*
  55945. ** The maximum (and only) versions of the wal and wal-index formats
  55946. ** that may be interpreted by this version of SQLite.
  55947. **
  55948. ** If a client begins recovering a WAL file and finds that (a) the checksum
  55949. ** values in the wal-header are correct and (b) the version field is not
  55950. ** WAL_MAX_VERSION, recovery fails and SQLite returns SQLITE_CANTOPEN.
  55951. **
  55952. ** Similarly, if a client successfully reads a wal-index header (i.e. the
  55953. ** checksum test is successful) and finds that the version field is not
  55954. ** WALINDEX_MAX_VERSION, then no read-transaction is opened and SQLite
  55955. ** returns SQLITE_CANTOPEN.
  55956. */
  55957. #define WAL_MAX_VERSION 3007000
  55958. #define WALINDEX_MAX_VERSION 3007000
  55959. /*
  55960. ** Index numbers for various locking bytes. WAL_NREADER is the number
  55961. ** of available reader locks and should be at least 3. The default
  55962. ** is SQLITE_SHM_NLOCK==8 and WAL_NREADER==5.
  55963. **
  55964. ** Technically, the various VFSes are free to implement these locks however
  55965. ** they see fit. However, compatibility is encouraged so that VFSes can
  55966. ** interoperate. The standard implemention used on both unix and windows
  55967. ** is for the index number to indicate a byte offset into the
  55968. ** WalCkptInfo.aLock[] array in the wal-index header. In other words, all
  55969. ** locks are on the shm file. The WALINDEX_LOCK_OFFSET constant (which
  55970. ** should be 120) is the location in the shm file for the first locking
  55971. ** byte.
  55972. */
  55973. #define WAL_WRITE_LOCK 0
  55974. #define WAL_ALL_BUT_WRITE 1
  55975. #define WAL_CKPT_LOCK 1
  55976. #define WAL_RECOVER_LOCK 2
  55977. #define WAL_READ_LOCK(I) (3+(I))
  55978. #define WAL_NREADER (SQLITE_SHM_NLOCK-3)
  55979. /* Object declarations */
  55980. typedef struct WalIndexHdr WalIndexHdr;
  55981. typedef struct WalIterator WalIterator;
  55982. typedef struct WalCkptInfo WalCkptInfo;
  55983. /*
  55984. ** The following object holds a copy of the wal-index header content.
  55985. **
  55986. ** The actual header in the wal-index consists of two copies of this
  55987. ** object followed by one instance of the WalCkptInfo object.
  55988. ** For all versions of SQLite through 3.10.0 and probably beyond,
  55989. ** the locking bytes (WalCkptInfo.aLock) start at offset 120 and
  55990. ** the total header size is 136 bytes.
  55991. **
  55992. ** The szPage value can be any power of 2 between 512 and 32768, inclusive.
  55993. ** Or it can be 1 to represent a 65536-byte page. The latter case was
  55994. ** added in 3.7.1 when support for 64K pages was added.
  55995. */
  55996. struct WalIndexHdr {
  55997. u32 iVersion; /* Wal-index version */
  55998. u32 unused; /* Unused (padding) field */
  55999. u32 iChange; /* Counter incremented each transaction */
  56000. u8 isInit; /* 1 when initialized */
  56001. u8 bigEndCksum; /* True if checksums in WAL are big-endian */
  56002. u16 szPage; /* Database page size in bytes. 1==64K */
  56003. u32 mxFrame; /* Index of last valid frame in the WAL */
  56004. u32 nPage; /* Size of database in pages */
  56005. u32 aFrameCksum[2]; /* Checksum of last frame in log */
  56006. u32 aSalt[2]; /* Two salt values copied from WAL header */
  56007. u32 aCksum[2]; /* Checksum over all prior fields */
  56008. };
  56009. /*
  56010. ** A copy of the following object occurs in the wal-index immediately
  56011. ** following the second copy of the WalIndexHdr. This object stores
  56012. ** information used by checkpoint.
  56013. **
  56014. ** nBackfill is the number of frames in the WAL that have been written
  56015. ** back into the database. (We call the act of moving content from WAL to
  56016. ** database "backfilling".) The nBackfill number is never greater than
  56017. ** WalIndexHdr.mxFrame. nBackfill can only be increased by threads
  56018. ** holding the WAL_CKPT_LOCK lock (which includes a recovery thread).
  56019. ** However, a WAL_WRITE_LOCK thread can move the value of nBackfill from
  56020. ** mxFrame back to zero when the WAL is reset.
  56021. **
  56022. ** nBackfillAttempted is the largest value of nBackfill that a checkpoint
  56023. ** has attempted to achieve. Normally nBackfill==nBackfillAtempted, however
  56024. ** the nBackfillAttempted is set before any backfilling is done and the
  56025. ** nBackfill is only set after all backfilling completes. So if a checkpoint
  56026. ** crashes, nBackfillAttempted might be larger than nBackfill. The
  56027. ** WalIndexHdr.mxFrame must never be less than nBackfillAttempted.
  56028. **
  56029. ** The aLock[] field is a set of bytes used for locking. These bytes should
  56030. ** never be read or written.
  56031. **
  56032. ** There is one entry in aReadMark[] for each reader lock. If a reader
  56033. ** holds read-lock K, then the value in aReadMark[K] is no greater than
  56034. ** the mxFrame for that reader. The value READMARK_NOT_USED (0xffffffff)
  56035. ** for any aReadMark[] means that entry is unused. aReadMark[0] is
  56036. ** a special case; its value is never used and it exists as a place-holder
  56037. ** to avoid having to offset aReadMark[] indexs by one. Readers holding
  56038. ** WAL_READ_LOCK(0) always ignore the entire WAL and read all content
  56039. ** directly from the database.
  56040. **
  56041. ** The value of aReadMark[K] may only be changed by a thread that
  56042. ** is holding an exclusive lock on WAL_READ_LOCK(K). Thus, the value of
  56043. ** aReadMark[K] cannot changed while there is a reader is using that mark
  56044. ** since the reader will be holding a shared lock on WAL_READ_LOCK(K).
  56045. **
  56046. ** The checkpointer may only transfer frames from WAL to database where
  56047. ** the frame numbers are less than or equal to every aReadMark[] that is
  56048. ** in use (that is, every aReadMark[j] for which there is a corresponding
  56049. ** WAL_READ_LOCK(j)). New readers (usually) pick the aReadMark[] with the
  56050. ** largest value and will increase an unused aReadMark[] to mxFrame if there
  56051. ** is not already an aReadMark[] equal to mxFrame. The exception to the
  56052. ** previous sentence is when nBackfill equals mxFrame (meaning that everything
  56053. ** in the WAL has been backfilled into the database) then new readers
  56054. ** will choose aReadMark[0] which has value 0 and hence such reader will
  56055. ** get all their all content directly from the database file and ignore
  56056. ** the WAL.
  56057. **
  56058. ** Writers normally append new frames to the end of the WAL. However,
  56059. ** if nBackfill equals mxFrame (meaning that all WAL content has been
  56060. ** written back into the database) and if no readers are using the WAL
  56061. ** (in other words, if there are no WAL_READ_LOCK(i) where i>0) then
  56062. ** the writer will first "reset" the WAL back to the beginning and start
  56063. ** writing new content beginning at frame 1.
  56064. **
  56065. ** We assume that 32-bit loads are atomic and so no locks are needed in
  56066. ** order to read from any aReadMark[] entries.
  56067. */
  56068. struct WalCkptInfo {
  56069. u32 nBackfill; /* Number of WAL frames backfilled into DB */
  56070. u32 aReadMark[WAL_NREADER]; /* Reader marks */
  56071. u8 aLock[SQLITE_SHM_NLOCK]; /* Reserved space for locks */
  56072. u32 nBackfillAttempted; /* WAL frames perhaps written, or maybe not */
  56073. u32 notUsed0; /* Available for future enhancements */
  56074. };
  56075. #define READMARK_NOT_USED 0xffffffff
  56076. /* A block of WALINDEX_LOCK_RESERVED bytes beginning at
  56077. ** WALINDEX_LOCK_OFFSET is reserved for locks. Since some systems
  56078. ** only support mandatory file-locks, we do not read or write data
  56079. ** from the region of the file on which locks are applied.
  56080. */
  56081. #define WALINDEX_LOCK_OFFSET (sizeof(WalIndexHdr)*2+offsetof(WalCkptInfo,aLock))
  56082. #define WALINDEX_HDR_SIZE (sizeof(WalIndexHdr)*2+sizeof(WalCkptInfo))
  56083. /* Size of header before each frame in wal */
  56084. #define WAL_FRAME_HDRSIZE 24
  56085. /* Size of write ahead log header, including checksum. */
  56086. #define WAL_HDRSIZE 32
  56087. /* WAL magic value. Either this value, or the same value with the least
  56088. ** significant bit also set (WAL_MAGIC | 0x00000001) is stored in 32-bit
  56089. ** big-endian format in the first 4 bytes of a WAL file.
  56090. **
  56091. ** If the LSB is set, then the checksums for each frame within the WAL
  56092. ** file are calculated by treating all data as an array of 32-bit
  56093. ** big-endian words. Otherwise, they are calculated by interpreting
  56094. ** all data as 32-bit little-endian words.
  56095. */
  56096. #define WAL_MAGIC 0x377f0682
  56097. /*
  56098. ** Return the offset of frame iFrame in the write-ahead log file,
  56099. ** assuming a database page size of szPage bytes. The offset returned
  56100. ** is to the start of the write-ahead log frame-header.
  56101. */
  56102. #define walFrameOffset(iFrame, szPage) ( \
  56103. WAL_HDRSIZE + ((iFrame)-1)*(i64)((szPage)+WAL_FRAME_HDRSIZE) \
  56104. )
  56105. /*
  56106. ** An open write-ahead log file is represented by an instance of the
  56107. ** following object.
  56108. */
  56109. struct Wal {
  56110. sqlite3_vfs *pVfs; /* The VFS used to create pDbFd */
  56111. sqlite3_file *pDbFd; /* File handle for the database file */
  56112. sqlite3_file *pWalFd; /* File handle for WAL file */
  56113. u32 iCallback; /* Value to pass to log callback (or 0) */
  56114. i64 mxWalSize; /* Truncate WAL to this size upon reset */
  56115. int nWiData; /* Size of array apWiData */
  56116. int szFirstBlock; /* Size of first block written to WAL file */
  56117. volatile u32 **apWiData; /* Pointer to wal-index content in memory */
  56118. u32 szPage; /* Database page size */
  56119. i16 readLock; /* Which read lock is being held. -1 for none */
  56120. u8 syncFlags; /* Flags to use to sync header writes */
  56121. u8 exclusiveMode; /* Non-zero if connection is in exclusive mode */
  56122. u8 writeLock; /* True if in a write transaction */
  56123. u8 ckptLock; /* True if holding a checkpoint lock */
  56124. u8 readOnly; /* WAL_RDWR, WAL_RDONLY, or WAL_SHM_RDONLY */
  56125. u8 truncateOnCommit; /* True to truncate WAL file on commit */
  56126. u8 syncHeader; /* Fsync the WAL header if true */
  56127. u8 padToSectorBoundary; /* Pad transactions out to the next sector */
  56128. u8 bShmUnreliable; /* SHM content is read-only and unreliable */
  56129. WalIndexHdr hdr; /* Wal-index header for current transaction */
  56130. u32 minFrame; /* Ignore wal frames before this one */
  56131. u32 iReCksum; /* On commit, recalculate checksums from here */
  56132. const char *zWalName; /* Name of WAL file */
  56133. u32 nCkpt; /* Checkpoint sequence counter in the wal-header */
  56134. #ifdef SQLITE_DEBUG
  56135. u8 lockError; /* True if a locking error has occurred */
  56136. #endif
  56137. #ifdef SQLITE_ENABLE_SNAPSHOT
  56138. WalIndexHdr *pSnapshot; /* Start transaction here if not NULL */
  56139. #endif
  56140. #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
  56141. sqlite3 *db;
  56142. #endif
  56143. };
  56144. /*
  56145. ** Candidate values for Wal.exclusiveMode.
  56146. */
  56147. #define WAL_NORMAL_MODE 0
  56148. #define WAL_EXCLUSIVE_MODE 1
  56149. #define WAL_HEAPMEMORY_MODE 2
  56150. /*
  56151. ** Possible values for WAL.readOnly
  56152. */
  56153. #define WAL_RDWR 0 /* Normal read/write connection */
  56154. #define WAL_RDONLY 1 /* The WAL file is readonly */
  56155. #define WAL_SHM_RDONLY 2 /* The SHM file is readonly */
  56156. /*
  56157. ** Each page of the wal-index mapping contains a hash-table made up of
  56158. ** an array of HASHTABLE_NSLOT elements of the following type.
  56159. */
  56160. typedef u16 ht_slot;
  56161. /*
  56162. ** This structure is used to implement an iterator that loops through
  56163. ** all frames in the WAL in database page order. Where two or more frames
  56164. ** correspond to the same database page, the iterator visits only the
  56165. ** frame most recently written to the WAL (in other words, the frame with
  56166. ** the largest index).
  56167. **
  56168. ** The internals of this structure are only accessed by:
  56169. **
  56170. ** walIteratorInit() - Create a new iterator,
  56171. ** walIteratorNext() - Step an iterator,
  56172. ** walIteratorFree() - Free an iterator.
  56173. **
  56174. ** This functionality is used by the checkpoint code (see walCheckpoint()).
  56175. */
  56176. struct WalIterator {
  56177. int iPrior; /* Last result returned from the iterator */
  56178. int nSegment; /* Number of entries in aSegment[] */
  56179. struct WalSegment {
  56180. int iNext; /* Next slot in aIndex[] not yet returned */
  56181. ht_slot *aIndex; /* i0, i1, i2... such that aPgno[iN] ascend */
  56182. u32 *aPgno; /* Array of page numbers. */
  56183. int nEntry; /* Nr. of entries in aPgno[] and aIndex[] */
  56184. int iZero; /* Frame number associated with aPgno[0] */
  56185. } aSegment[1]; /* One for every 32KB page in the wal-index */
  56186. };
  56187. /*
  56188. ** Define the parameters of the hash tables in the wal-index file. There
  56189. ** is a hash-table following every HASHTABLE_NPAGE page numbers in the
  56190. ** wal-index.
  56191. **
  56192. ** Changing any of these constants will alter the wal-index format and
  56193. ** create incompatibilities.
  56194. */
  56195. #define HASHTABLE_NPAGE 4096 /* Must be power of 2 */
  56196. #define HASHTABLE_HASH_1 383 /* Should be prime */
  56197. #define HASHTABLE_NSLOT (HASHTABLE_NPAGE*2) /* Must be a power of 2 */
  56198. /*
  56199. ** The block of page numbers associated with the first hash-table in a
  56200. ** wal-index is smaller than usual. This is so that there is a complete
  56201. ** hash-table on each aligned 32KB page of the wal-index.
  56202. */
  56203. #define HASHTABLE_NPAGE_ONE (HASHTABLE_NPAGE - (WALINDEX_HDR_SIZE/sizeof(u32)))
  56204. /* The wal-index is divided into pages of WALINDEX_PGSZ bytes each. */
  56205. #define WALINDEX_PGSZ ( \
  56206. sizeof(ht_slot)*HASHTABLE_NSLOT + HASHTABLE_NPAGE*sizeof(u32) \
  56207. )
  56208. /*
  56209. ** Obtain a pointer to the iPage'th page of the wal-index. The wal-index
  56210. ** is broken into pages of WALINDEX_PGSZ bytes. Wal-index pages are
  56211. ** numbered from zero.
  56212. **
  56213. ** If the wal-index is currently smaller the iPage pages then the size
  56214. ** of the wal-index might be increased, but only if it is safe to do
  56215. ** so. It is safe to enlarge the wal-index if pWal->writeLock is true
  56216. ** or pWal->exclusiveMode==WAL_HEAPMEMORY_MODE.
  56217. **
  56218. ** If this call is successful, *ppPage is set to point to the wal-index
  56219. ** page and SQLITE_OK is returned. If an error (an OOM or VFS error) occurs,
  56220. ** then an SQLite error code is returned and *ppPage is set to 0.
  56221. */
  56222. static SQLITE_NOINLINE int walIndexPageRealloc(
  56223. Wal *pWal, /* The WAL context */
  56224. int iPage, /* The page we seek */
  56225. volatile u32 **ppPage /* Write the page pointer here */
  56226. ){
  56227. int rc = SQLITE_OK;
  56228. /* Enlarge the pWal->apWiData[] array if required */
  56229. if( pWal->nWiData<=iPage ){
  56230. sqlite3_int64 nByte = sizeof(u32*)*(iPage+1);
  56231. volatile u32 **apNew;
  56232. apNew = (volatile u32 **)sqlite3Realloc((void *)pWal->apWiData, nByte);
  56233. if( !apNew ){
  56234. *ppPage = 0;
  56235. return SQLITE_NOMEM_BKPT;
  56236. }
  56237. memset((void*)&apNew[pWal->nWiData], 0,
  56238. sizeof(u32*)*(iPage+1-pWal->nWiData));
  56239. pWal->apWiData = apNew;
  56240. pWal->nWiData = iPage+1;
  56241. }
  56242. /* Request a pointer to the required page from the VFS */
  56243. assert( pWal->apWiData[iPage]==0 );
  56244. if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
  56245. pWal->apWiData[iPage] = (u32 volatile *)sqlite3MallocZero(WALINDEX_PGSZ);
  56246. if( !pWal->apWiData[iPage] ) rc = SQLITE_NOMEM_BKPT;
  56247. }else{
  56248. rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ,
  56249. pWal->writeLock, (void volatile **)&pWal->apWiData[iPage]
  56250. );
  56251. assert( pWal->apWiData[iPage]!=0 || rc!=SQLITE_OK || pWal->writeLock==0 );
  56252. testcase( pWal->apWiData[iPage]==0 && rc==SQLITE_OK );
  56253. if( (rc&0xff)==SQLITE_READONLY ){
  56254. pWal->readOnly |= WAL_SHM_RDONLY;
  56255. if( rc==SQLITE_READONLY ){
  56256. rc = SQLITE_OK;
  56257. }
  56258. }
  56259. }
  56260. *ppPage = pWal->apWiData[iPage];
  56261. assert( iPage==0 || *ppPage || rc!=SQLITE_OK );
  56262. return rc;
  56263. }
  56264. static int walIndexPage(
  56265. Wal *pWal, /* The WAL context */
  56266. int iPage, /* The page we seek */
  56267. volatile u32 **ppPage /* Write the page pointer here */
  56268. ){
  56269. if( pWal->nWiData<=iPage || (*ppPage = pWal->apWiData[iPage])==0 ){
  56270. return walIndexPageRealloc(pWal, iPage, ppPage);
  56271. }
  56272. return SQLITE_OK;
  56273. }
  56274. /*
  56275. ** Return a pointer to the WalCkptInfo structure in the wal-index.
  56276. */
  56277. static volatile WalCkptInfo *walCkptInfo(Wal *pWal){
  56278. assert( pWal->nWiData>0 && pWal->apWiData[0] );
  56279. return (volatile WalCkptInfo*)&(pWal->apWiData[0][sizeof(WalIndexHdr)/2]);
  56280. }
  56281. /*
  56282. ** Return a pointer to the WalIndexHdr structure in the wal-index.
  56283. */
  56284. static volatile WalIndexHdr *walIndexHdr(Wal *pWal){
  56285. assert( pWal->nWiData>0 && pWal->apWiData[0] );
  56286. return (volatile WalIndexHdr*)pWal->apWiData[0];
  56287. }
  56288. /*
  56289. ** The argument to this macro must be of type u32. On a little-endian
  56290. ** architecture, it returns the u32 value that results from interpreting
  56291. ** the 4 bytes as a big-endian value. On a big-endian architecture, it
  56292. ** returns the value that would be produced by interpreting the 4 bytes
  56293. ** of the input value as a little-endian integer.
  56294. */
  56295. #define BYTESWAP32(x) ( \
  56296. (((x)&0x000000FF)<<24) + (((x)&0x0000FF00)<<8) \
  56297. + (((x)&0x00FF0000)>>8) + (((x)&0xFF000000)>>24) \
  56298. )
  56299. /*
  56300. ** Generate or extend an 8 byte checksum based on the data in
  56301. ** array aByte[] and the initial values of aIn[0] and aIn[1] (or
  56302. ** initial values of 0 and 0 if aIn==NULL).
  56303. **
  56304. ** The checksum is written back into aOut[] before returning.
  56305. **
  56306. ** nByte must be a positive multiple of 8.
  56307. */
  56308. static void walChecksumBytes(
  56309. int nativeCksum, /* True for native byte-order, false for non-native */
  56310. u8 *a, /* Content to be checksummed */
  56311. int nByte, /* Bytes of content in a[]. Must be a multiple of 8. */
  56312. const u32 *aIn, /* Initial checksum value input */
  56313. u32 *aOut /* OUT: Final checksum value output */
  56314. ){
  56315. u32 s1, s2;
  56316. u32 *aData = (u32 *)a;
  56317. u32 *aEnd = (u32 *)&a[nByte];
  56318. if( aIn ){
  56319. s1 = aIn[0];
  56320. s2 = aIn[1];
  56321. }else{
  56322. s1 = s2 = 0;
  56323. }
  56324. assert( nByte>=8 );
  56325. assert( (nByte&0x00000007)==0 );
  56326. assert( nByte<=65536 );
  56327. if( nativeCksum ){
  56328. do {
  56329. s1 += *aData++ + s2;
  56330. s2 += *aData++ + s1;
  56331. }while( aData<aEnd );
  56332. }else{
  56333. do {
  56334. s1 += BYTESWAP32(aData[0]) + s2;
  56335. s2 += BYTESWAP32(aData[1]) + s1;
  56336. aData += 2;
  56337. }while( aData<aEnd );
  56338. }
  56339. aOut[0] = s1;
  56340. aOut[1] = s2;
  56341. }
  56342. /*
  56343. ** If there is the possibility of concurrent access to the SHM file
  56344. ** from multiple threads and/or processes, then do a memory barrier.
  56345. */
  56346. static void walShmBarrier(Wal *pWal){
  56347. if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
  56348. sqlite3OsShmBarrier(pWal->pDbFd);
  56349. }
  56350. }
  56351. /*
  56352. ** Add the SQLITE_NO_TSAN as part of the return-type of a function
  56353. ** definition as a hint that the function contains constructs that
  56354. ** might give false-positive TSAN warnings.
  56355. **
  56356. ** See tag-20200519-1.
  56357. */
  56358. #if defined(__clang__) && !defined(SQLITE_NO_TSAN)
  56359. # define SQLITE_NO_TSAN __attribute__((no_sanitize_thread))
  56360. #else
  56361. # define SQLITE_NO_TSAN
  56362. #endif
  56363. /*
  56364. ** Write the header information in pWal->hdr into the wal-index.
  56365. **
  56366. ** The checksum on pWal->hdr is updated before it is written.
  56367. */
  56368. static SQLITE_NO_TSAN void walIndexWriteHdr(Wal *pWal){
  56369. volatile WalIndexHdr *aHdr = walIndexHdr(pWal);
  56370. const int nCksum = offsetof(WalIndexHdr, aCksum);
  56371. assert( pWal->writeLock );
  56372. pWal->hdr.isInit = 1;
  56373. pWal->hdr.iVersion = WALINDEX_MAX_VERSION;
  56374. walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum);
  56375. /* Possible TSAN false-positive. See tag-20200519-1 */
  56376. memcpy((void*)&aHdr[1], (const void*)&pWal->hdr, sizeof(WalIndexHdr));
  56377. walShmBarrier(pWal);
  56378. memcpy((void*)&aHdr[0], (const void*)&pWal->hdr, sizeof(WalIndexHdr));
  56379. }
  56380. /*
  56381. ** This function encodes a single frame header and writes it to a buffer
  56382. ** supplied by the caller. A frame-header is made up of a series of
  56383. ** 4-byte big-endian integers, as follows:
  56384. **
  56385. ** 0: Page number.
  56386. ** 4: For commit records, the size of the database image in pages
  56387. ** after the commit. For all other records, zero.
  56388. ** 8: Salt-1 (copied from the wal-header)
  56389. ** 12: Salt-2 (copied from the wal-header)
  56390. ** 16: Checksum-1.
  56391. ** 20: Checksum-2.
  56392. */
  56393. static void walEncodeFrame(
  56394. Wal *pWal, /* The write-ahead log */
  56395. u32 iPage, /* Database page number for frame */
  56396. u32 nTruncate, /* New db size (or 0 for non-commit frames) */
  56397. u8 *aData, /* Pointer to page data */
  56398. u8 *aFrame /* OUT: Write encoded frame here */
  56399. ){
  56400. int nativeCksum; /* True for native byte-order checksums */
  56401. u32 *aCksum = pWal->hdr.aFrameCksum;
  56402. assert( WAL_FRAME_HDRSIZE==24 );
  56403. sqlite3Put4byte(&aFrame[0], iPage);
  56404. sqlite3Put4byte(&aFrame[4], nTruncate);
  56405. if( pWal->iReCksum==0 ){
  56406. memcpy(&aFrame[8], pWal->hdr.aSalt, 8);
  56407. nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
  56408. walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
  56409. walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
  56410. sqlite3Put4byte(&aFrame[16], aCksum[0]);
  56411. sqlite3Put4byte(&aFrame[20], aCksum[1]);
  56412. }else{
  56413. memset(&aFrame[8], 0, 16);
  56414. }
  56415. }
  56416. /*
  56417. ** Check to see if the frame with header in aFrame[] and content
  56418. ** in aData[] is valid. If it is a valid frame, fill *piPage and
  56419. ** *pnTruncate and return true. Return if the frame is not valid.
  56420. */
  56421. static int walDecodeFrame(
  56422. Wal *pWal, /* The write-ahead log */
  56423. u32 *piPage, /* OUT: Database page number for frame */
  56424. u32 *pnTruncate, /* OUT: New db size (or 0 if not commit) */
  56425. u8 *aData, /* Pointer to page data (for checksum) */
  56426. u8 *aFrame /* Frame data */
  56427. ){
  56428. int nativeCksum; /* True for native byte-order checksums */
  56429. u32 *aCksum = pWal->hdr.aFrameCksum;
  56430. u32 pgno; /* Page number of the frame */
  56431. assert( WAL_FRAME_HDRSIZE==24 );
  56432. /* A frame is only valid if the salt values in the frame-header
  56433. ** match the salt values in the wal-header.
  56434. */
  56435. if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){
  56436. return 0;
  56437. }
  56438. /* A frame is only valid if the page number is creater than zero.
  56439. */
  56440. pgno = sqlite3Get4byte(&aFrame[0]);
  56441. if( pgno==0 ){
  56442. return 0;
  56443. }
  56444. /* A frame is only valid if a checksum of the WAL header,
  56445. ** all prior frams, the first 16 bytes of this frame-header,
  56446. ** and the frame-data matches the checksum in the last 8
  56447. ** bytes of this frame-header.
  56448. */
  56449. nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
  56450. walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
  56451. walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
  56452. if( aCksum[0]!=sqlite3Get4byte(&aFrame[16])
  56453. || aCksum[1]!=sqlite3Get4byte(&aFrame[20])
  56454. ){
  56455. /* Checksum failed. */
  56456. return 0;
  56457. }
  56458. /* If we reach this point, the frame is valid. Return the page number
  56459. ** and the new database size.
  56460. */
  56461. *piPage = pgno;
  56462. *pnTruncate = sqlite3Get4byte(&aFrame[4]);
  56463. return 1;
  56464. }
  56465. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  56466. /*
  56467. ** Names of locks. This routine is used to provide debugging output and is not
  56468. ** a part of an ordinary build.
  56469. */
  56470. static const char *walLockName(int lockIdx){
  56471. if( lockIdx==WAL_WRITE_LOCK ){
  56472. return "WRITE-LOCK";
  56473. }else if( lockIdx==WAL_CKPT_LOCK ){
  56474. return "CKPT-LOCK";
  56475. }else if( lockIdx==WAL_RECOVER_LOCK ){
  56476. return "RECOVER-LOCK";
  56477. }else{
  56478. static char zName[15];
  56479. sqlite3_snprintf(sizeof(zName), zName, "READ-LOCK[%d]",
  56480. lockIdx-WAL_READ_LOCK(0));
  56481. return zName;
  56482. }
  56483. }
  56484. #endif /*defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
  56485. /*
  56486. ** Set or release locks on the WAL. Locks are either shared or exclusive.
  56487. ** A lock cannot be moved directly between shared and exclusive - it must go
  56488. ** through the unlocked state first.
  56489. **
  56490. ** In locking_mode=EXCLUSIVE, all of these routines become no-ops.
  56491. */
  56492. static int walLockShared(Wal *pWal, int lockIdx){
  56493. int rc;
  56494. if( pWal->exclusiveMode ) return SQLITE_OK;
  56495. rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
  56496. SQLITE_SHM_LOCK | SQLITE_SHM_SHARED);
  56497. WALTRACE(("WAL%p: acquire SHARED-%s %s\n", pWal,
  56498. walLockName(lockIdx), rc ? "failed" : "ok"));
  56499. VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && (rc&0xFF)!=SQLITE_BUSY); )
  56500. return rc;
  56501. }
  56502. static void walUnlockShared(Wal *pWal, int lockIdx){
  56503. if( pWal->exclusiveMode ) return;
  56504. (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
  56505. SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED);
  56506. WALTRACE(("WAL%p: release SHARED-%s\n", pWal, walLockName(lockIdx)));
  56507. }
  56508. static int walLockExclusive(Wal *pWal, int lockIdx, int n){
  56509. int rc;
  56510. if( pWal->exclusiveMode ) return SQLITE_OK;
  56511. rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
  56512. SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE);
  56513. WALTRACE(("WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\n", pWal,
  56514. walLockName(lockIdx), n, rc ? "failed" : "ok"));
  56515. VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && (rc&0xFF)!=SQLITE_BUSY); )
  56516. return rc;
  56517. }
  56518. static void walUnlockExclusive(Wal *pWal, int lockIdx, int n){
  56519. if( pWal->exclusiveMode ) return;
  56520. (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
  56521. SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE);
  56522. WALTRACE(("WAL%p: release EXCLUSIVE-%s cnt=%d\n", pWal,
  56523. walLockName(lockIdx), n));
  56524. }
  56525. /*
  56526. ** Compute a hash on a page number. The resulting hash value must land
  56527. ** between 0 and (HASHTABLE_NSLOT-1). The walHashNext() function advances
  56528. ** the hash to the next value in the event of a collision.
  56529. */
  56530. static int walHash(u32 iPage){
  56531. assert( iPage>0 );
  56532. assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 );
  56533. return (iPage*HASHTABLE_HASH_1) & (HASHTABLE_NSLOT-1);
  56534. }
  56535. static int walNextHash(int iPriorHash){
  56536. return (iPriorHash+1)&(HASHTABLE_NSLOT-1);
  56537. }
  56538. /*
  56539. ** An instance of the WalHashLoc object is used to describe the location
  56540. ** of a page hash table in the wal-index. This becomes the return value
  56541. ** from walHashGet().
  56542. */
  56543. typedef struct WalHashLoc WalHashLoc;
  56544. struct WalHashLoc {
  56545. volatile ht_slot *aHash; /* Start of the wal-index hash table */
  56546. volatile u32 *aPgno; /* aPgno[1] is the page of first frame indexed */
  56547. u32 iZero; /* One less than the frame number of first indexed*/
  56548. };
  56549. /*
  56550. ** Return pointers to the hash table and page number array stored on
  56551. ** page iHash of the wal-index. The wal-index is broken into 32KB pages
  56552. ** numbered starting from 0.
  56553. **
  56554. ** Set output variable pLoc->aHash to point to the start of the hash table
  56555. ** in the wal-index file. Set pLoc->iZero to one less than the frame
  56556. ** number of the first frame indexed by this hash table. If a
  56557. ** slot in the hash table is set to N, it refers to frame number
  56558. ** (pLoc->iZero+N) in the log.
  56559. **
  56560. ** Finally, set pLoc->aPgno so that pLoc->aPgno[1] is the page number of the
  56561. ** first frame indexed by the hash table, frame (pLoc->iZero+1).
  56562. */
  56563. static int walHashGet(
  56564. Wal *pWal, /* WAL handle */
  56565. int iHash, /* Find the iHash'th table */
  56566. WalHashLoc *pLoc /* OUT: Hash table location */
  56567. ){
  56568. int rc; /* Return code */
  56569. rc = walIndexPage(pWal, iHash, &pLoc->aPgno);
  56570. assert( rc==SQLITE_OK || iHash>0 );
  56571. if( rc==SQLITE_OK ){
  56572. pLoc->aHash = (volatile ht_slot *)&pLoc->aPgno[HASHTABLE_NPAGE];
  56573. if( iHash==0 ){
  56574. pLoc->aPgno = &pLoc->aPgno[WALINDEX_HDR_SIZE/sizeof(u32)];
  56575. pLoc->iZero = 0;
  56576. }else{
  56577. pLoc->iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE;
  56578. }
  56579. pLoc->aPgno = &pLoc->aPgno[-1];
  56580. }
  56581. return rc;
  56582. }
  56583. /*
  56584. ** Return the number of the wal-index page that contains the hash-table
  56585. ** and page-number array that contain entries corresponding to WAL frame
  56586. ** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages
  56587. ** are numbered starting from 0.
  56588. */
  56589. static int walFramePage(u32 iFrame){
  56590. int iHash = (iFrame+HASHTABLE_NPAGE-HASHTABLE_NPAGE_ONE-1) / HASHTABLE_NPAGE;
  56591. assert( (iHash==0 || iFrame>HASHTABLE_NPAGE_ONE)
  56592. && (iHash>=1 || iFrame<=HASHTABLE_NPAGE_ONE)
  56593. && (iHash<=1 || iFrame>(HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE))
  56594. && (iHash>=2 || iFrame<=HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE)
  56595. && (iHash<=2 || iFrame>(HASHTABLE_NPAGE_ONE+2*HASHTABLE_NPAGE))
  56596. );
  56597. return iHash;
  56598. }
  56599. /*
  56600. ** Return the page number associated with frame iFrame in this WAL.
  56601. */
  56602. static u32 walFramePgno(Wal *pWal, u32 iFrame){
  56603. int iHash = walFramePage(iFrame);
  56604. if( iHash==0 ){
  56605. return pWal->apWiData[0][WALINDEX_HDR_SIZE/sizeof(u32) + iFrame - 1];
  56606. }
  56607. return pWal->apWiData[iHash][(iFrame-1-HASHTABLE_NPAGE_ONE)%HASHTABLE_NPAGE];
  56608. }
  56609. /*
  56610. ** Remove entries from the hash table that point to WAL slots greater
  56611. ** than pWal->hdr.mxFrame.
  56612. **
  56613. ** This function is called whenever pWal->hdr.mxFrame is decreased due
  56614. ** to a rollback or savepoint.
  56615. **
  56616. ** At most only the hash table containing pWal->hdr.mxFrame needs to be
  56617. ** updated. Any later hash tables will be automatically cleared when
  56618. ** pWal->hdr.mxFrame advances to the point where those hash tables are
  56619. ** actually needed.
  56620. */
  56621. static void walCleanupHash(Wal *pWal){
  56622. WalHashLoc sLoc; /* Hash table location */
  56623. int iLimit = 0; /* Zero values greater than this */
  56624. int nByte; /* Number of bytes to zero in aPgno[] */
  56625. int i; /* Used to iterate through aHash[] */
  56626. int rc; /* Return code form walHashGet() */
  56627. assert( pWal->writeLock );
  56628. testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE-1 );
  56629. testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE );
  56630. testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE+1 );
  56631. if( pWal->hdr.mxFrame==0 ) return;
  56632. /* Obtain pointers to the hash-table and page-number array containing
  56633. ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed
  56634. ** that the page said hash-table and array reside on is already mapped.(1)
  56635. */
  56636. assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) );
  56637. assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] );
  56638. rc = walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &sLoc);
  56639. if( NEVER(rc) ) return; /* Defense-in-depth, in case (1) above is wrong */
  56640. /* Zero all hash-table entries that correspond to frame numbers greater
  56641. ** than pWal->hdr.mxFrame.
  56642. */
  56643. iLimit = pWal->hdr.mxFrame - sLoc.iZero;
  56644. assert( iLimit>0 );
  56645. for(i=0; i<HASHTABLE_NSLOT; i++){
  56646. if( sLoc.aHash[i]>iLimit ){
  56647. sLoc.aHash[i] = 0;
  56648. }
  56649. }
  56650. /* Zero the entries in the aPgno array that correspond to frames with
  56651. ** frame numbers greater than pWal->hdr.mxFrame.
  56652. */
  56653. nByte = (int)((char *)sLoc.aHash - (char *)&sLoc.aPgno[iLimit+1]);
  56654. memset((void *)&sLoc.aPgno[iLimit+1], 0, nByte);
  56655. #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
  56656. /* Verify that the every entry in the mapping region is still reachable
  56657. ** via the hash table even after the cleanup.
  56658. */
  56659. if( iLimit ){
  56660. int j; /* Loop counter */
  56661. int iKey; /* Hash key */
  56662. for(j=1; j<=iLimit; j++){
  56663. for(iKey=walHash(sLoc.aPgno[j]);sLoc.aHash[iKey];iKey=walNextHash(iKey)){
  56664. if( sLoc.aHash[iKey]==j ) break;
  56665. }
  56666. assert( sLoc.aHash[iKey]==j );
  56667. }
  56668. }
  56669. #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
  56670. }
  56671. /*
  56672. ** Set an entry in the wal-index that will map database page number
  56673. ** pPage into WAL frame iFrame.
  56674. */
  56675. static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){
  56676. int rc; /* Return code */
  56677. WalHashLoc sLoc; /* Wal-index hash table location */
  56678. rc = walHashGet(pWal, walFramePage(iFrame), &sLoc);
  56679. /* Assuming the wal-index file was successfully mapped, populate the
  56680. ** page number array and hash table entry.
  56681. */
  56682. if( rc==SQLITE_OK ){
  56683. int iKey; /* Hash table key */
  56684. int idx; /* Value to write to hash-table slot */
  56685. int nCollide; /* Number of hash collisions */
  56686. idx = iFrame - sLoc.iZero;
  56687. assert( idx <= HASHTABLE_NSLOT/2 + 1 );
  56688. /* If this is the first entry to be added to this hash-table, zero the
  56689. ** entire hash table and aPgno[] array before proceeding.
  56690. */
  56691. if( idx==1 ){
  56692. int nByte = (int)((u8 *)&sLoc.aHash[HASHTABLE_NSLOT]
  56693. - (u8 *)&sLoc.aPgno[1]);
  56694. memset((void*)&sLoc.aPgno[1], 0, nByte);
  56695. }
  56696. /* If the entry in aPgno[] is already set, then the previous writer
  56697. ** must have exited unexpectedly in the middle of a transaction (after
  56698. ** writing one or more dirty pages to the WAL to free up memory).
  56699. ** Remove the remnants of that writers uncommitted transaction from
  56700. ** the hash-table before writing any new entries.
  56701. */
  56702. if( sLoc.aPgno[idx] ){
  56703. walCleanupHash(pWal);
  56704. assert( !sLoc.aPgno[idx] );
  56705. }
  56706. /* Write the aPgno[] array entry and the hash-table slot. */
  56707. nCollide = idx;
  56708. for(iKey=walHash(iPage); sLoc.aHash[iKey]; iKey=walNextHash(iKey)){
  56709. if( (nCollide--)==0 ) return SQLITE_CORRUPT_BKPT;
  56710. }
  56711. sLoc.aPgno[idx] = iPage;
  56712. sLoc.aHash[iKey] = (ht_slot)idx;
  56713. #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
  56714. /* Verify that the number of entries in the hash table exactly equals
  56715. ** the number of entries in the mapping region.
  56716. */
  56717. {
  56718. int i; /* Loop counter */
  56719. int nEntry = 0; /* Number of entries in the hash table */
  56720. for(i=0; i<HASHTABLE_NSLOT; i++){ if( sLoc.aHash[i] ) nEntry++; }
  56721. assert( nEntry==idx );
  56722. }
  56723. /* Verify that the every entry in the mapping region is reachable
  56724. ** via the hash table. This turns out to be a really, really expensive
  56725. ** thing to check, so only do this occasionally - not on every
  56726. ** iteration.
  56727. */
  56728. if( (idx&0x3ff)==0 ){
  56729. int i; /* Loop counter */
  56730. for(i=1; i<=idx; i++){
  56731. for(iKey=walHash(sLoc.aPgno[i]);
  56732. sLoc.aHash[iKey];
  56733. iKey=walNextHash(iKey)){
  56734. if( sLoc.aHash[iKey]==i ) break;
  56735. }
  56736. assert( sLoc.aHash[iKey]==i );
  56737. }
  56738. }
  56739. #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
  56740. }
  56741. return rc;
  56742. }
  56743. /*
  56744. ** Recover the wal-index by reading the write-ahead log file.
  56745. **
  56746. ** This routine first tries to establish an exclusive lock on the
  56747. ** wal-index to prevent other threads/processes from doing anything
  56748. ** with the WAL or wal-index while recovery is running. The
  56749. ** WAL_RECOVER_LOCK is also held so that other threads will know
  56750. ** that this thread is running recovery. If unable to establish
  56751. ** the necessary locks, this routine returns SQLITE_BUSY.
  56752. */
  56753. static int walIndexRecover(Wal *pWal){
  56754. int rc; /* Return Code */
  56755. i64 nSize; /* Size of log file */
  56756. u32 aFrameCksum[2] = {0, 0};
  56757. int iLock; /* Lock offset to lock for checkpoint */
  56758. /* Obtain an exclusive lock on all byte in the locking range not already
  56759. ** locked by the caller. The caller is guaranteed to have locked the
  56760. ** WAL_WRITE_LOCK byte, and may have also locked the WAL_CKPT_LOCK byte.
  56761. ** If successful, the same bytes that are locked here are unlocked before
  56762. ** this function returns.
  56763. */
  56764. assert( pWal->ckptLock==1 || pWal->ckptLock==0 );
  56765. assert( WAL_ALL_BUT_WRITE==WAL_WRITE_LOCK+1 );
  56766. assert( WAL_CKPT_LOCK==WAL_ALL_BUT_WRITE );
  56767. assert( pWal->writeLock );
  56768. iLock = WAL_ALL_BUT_WRITE + pWal->ckptLock;
  56769. rc = walLockExclusive(pWal, iLock, WAL_READ_LOCK(0)-iLock);
  56770. if( rc==SQLITE_OK ){
  56771. rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
  56772. if( rc!=SQLITE_OK ){
  56773. walUnlockExclusive(pWal, iLock, WAL_READ_LOCK(0)-iLock);
  56774. }
  56775. }
  56776. if( rc ){
  56777. return rc;
  56778. }
  56779. WALTRACE(("WAL%p: recovery begin...\n", pWal));
  56780. memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
  56781. rc = sqlite3OsFileSize(pWal->pWalFd, &nSize);
  56782. if( rc!=SQLITE_OK ){
  56783. goto recovery_error;
  56784. }
  56785. if( nSize>WAL_HDRSIZE ){
  56786. u8 aBuf[WAL_HDRSIZE]; /* Buffer to load WAL header into */
  56787. u8 *aFrame = 0; /* Malloc'd buffer to load entire frame */
  56788. int szFrame; /* Number of bytes in buffer aFrame[] */
  56789. u8 *aData; /* Pointer to data part of aFrame buffer */
  56790. int iFrame; /* Index of last frame read */
  56791. i64 iOffset; /* Next offset to read from log file */
  56792. int szPage; /* Page size according to the log */
  56793. u32 magic; /* Magic value read from WAL header */
  56794. u32 version; /* Magic value read from WAL header */
  56795. int isValid; /* True if this frame is valid */
  56796. /* Read in the WAL header. */
  56797. rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
  56798. if( rc!=SQLITE_OK ){
  56799. goto recovery_error;
  56800. }
  56801. /* If the database page size is not a power of two, or is greater than
  56802. ** SQLITE_MAX_PAGE_SIZE, conclude that the WAL file contains no valid
  56803. ** data. Similarly, if the 'magic' value is invalid, ignore the whole
  56804. ** WAL file.
  56805. */
  56806. magic = sqlite3Get4byte(&aBuf[0]);
  56807. szPage = sqlite3Get4byte(&aBuf[8]);
  56808. if( (magic&0xFFFFFFFE)!=WAL_MAGIC
  56809. || szPage&(szPage-1)
  56810. || szPage>SQLITE_MAX_PAGE_SIZE
  56811. || szPage<512
  56812. ){
  56813. goto finished;
  56814. }
  56815. pWal->hdr.bigEndCksum = (u8)(magic&0x00000001);
  56816. pWal->szPage = szPage;
  56817. pWal->nCkpt = sqlite3Get4byte(&aBuf[12]);
  56818. memcpy(&pWal->hdr.aSalt, &aBuf[16], 8);
  56819. /* Verify that the WAL header checksum is correct */
  56820. walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN,
  56821. aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum
  56822. );
  56823. if( pWal->hdr.aFrameCksum[0]!=sqlite3Get4byte(&aBuf[24])
  56824. || pWal->hdr.aFrameCksum[1]!=sqlite3Get4byte(&aBuf[28])
  56825. ){
  56826. goto finished;
  56827. }
  56828. /* Verify that the version number on the WAL format is one that
  56829. ** are able to understand */
  56830. version = sqlite3Get4byte(&aBuf[4]);
  56831. if( version!=WAL_MAX_VERSION ){
  56832. rc = SQLITE_CANTOPEN_BKPT;
  56833. goto finished;
  56834. }
  56835. /* Malloc a buffer to read frames into. */
  56836. szFrame = szPage + WAL_FRAME_HDRSIZE;
  56837. aFrame = (u8 *)sqlite3_malloc64(szFrame);
  56838. if( !aFrame ){
  56839. rc = SQLITE_NOMEM_BKPT;
  56840. goto recovery_error;
  56841. }
  56842. aData = &aFrame[WAL_FRAME_HDRSIZE];
  56843. /* Read all frames from the log file. */
  56844. iFrame = 0;
  56845. for(iOffset=WAL_HDRSIZE; (iOffset+szFrame)<=nSize; iOffset+=szFrame){
  56846. u32 pgno; /* Database page number for frame */
  56847. u32 nTruncate; /* dbsize field from frame header */
  56848. /* Read and decode the next log frame. */
  56849. iFrame++;
  56850. rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
  56851. if( rc!=SQLITE_OK ) break;
  56852. isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame);
  56853. if( !isValid ) break;
  56854. rc = walIndexAppend(pWal, iFrame, pgno);
  56855. if( rc!=SQLITE_OK ) break;
  56856. /* If nTruncate is non-zero, this is a commit record. */
  56857. if( nTruncate ){
  56858. pWal->hdr.mxFrame = iFrame;
  56859. pWal->hdr.nPage = nTruncate;
  56860. pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
  56861. testcase( szPage<=32768 );
  56862. testcase( szPage>=65536 );
  56863. aFrameCksum[0] = pWal->hdr.aFrameCksum[0];
  56864. aFrameCksum[1] = pWal->hdr.aFrameCksum[1];
  56865. }
  56866. }
  56867. sqlite3_free(aFrame);
  56868. }
  56869. finished:
  56870. if( rc==SQLITE_OK ){
  56871. volatile WalCkptInfo *pInfo;
  56872. int i;
  56873. pWal->hdr.aFrameCksum[0] = aFrameCksum[0];
  56874. pWal->hdr.aFrameCksum[1] = aFrameCksum[1];
  56875. walIndexWriteHdr(pWal);
  56876. /* Reset the checkpoint-header. This is safe because this thread is
  56877. ** currently holding locks that exclude all other readers, writers and
  56878. ** checkpointers.
  56879. */
  56880. pInfo = walCkptInfo(pWal);
  56881. pInfo->nBackfill = 0;
  56882. pInfo->nBackfillAttempted = pWal->hdr.mxFrame;
  56883. pInfo->aReadMark[0] = 0;
  56884. for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
  56885. if( pWal->hdr.mxFrame ) pInfo->aReadMark[1] = pWal->hdr.mxFrame;
  56886. /* If more than one frame was recovered from the log file, report an
  56887. ** event via sqlite3_log(). This is to help with identifying performance
  56888. ** problems caused by applications routinely shutting down without
  56889. ** checkpointing the log file.
  56890. */
  56891. if( pWal->hdr.nPage ){
  56892. sqlite3_log(SQLITE_NOTICE_RECOVER_WAL,
  56893. "recovered %d frames from WAL file %s",
  56894. pWal->hdr.mxFrame, pWal->zWalName
  56895. );
  56896. }
  56897. }
  56898. recovery_error:
  56899. WALTRACE(("WAL%p: recovery %s\n", pWal, rc ? "failed" : "ok"));
  56900. walUnlockExclusive(pWal, iLock, WAL_READ_LOCK(0)-iLock);
  56901. walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
  56902. return rc;
  56903. }
  56904. /*
  56905. ** Close an open wal-index.
  56906. */
  56907. static void walIndexClose(Wal *pWal, int isDelete){
  56908. if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE || pWal->bShmUnreliable ){
  56909. int i;
  56910. for(i=0; i<pWal->nWiData; i++){
  56911. sqlite3_free((void *)pWal->apWiData[i]);
  56912. pWal->apWiData[i] = 0;
  56913. }
  56914. }
  56915. if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
  56916. sqlite3OsShmUnmap(pWal->pDbFd, isDelete);
  56917. }
  56918. }
  56919. /*
  56920. ** Open a connection to the WAL file zWalName. The database file must
  56921. ** already be opened on connection pDbFd. The buffer that zWalName points
  56922. ** to must remain valid for the lifetime of the returned Wal* handle.
  56923. **
  56924. ** A SHARED lock should be held on the database file when this function
  56925. ** is called. The purpose of this SHARED lock is to prevent any other
  56926. ** client from unlinking the WAL or wal-index file. If another process
  56927. ** were to do this just after this client opened one of these files, the
  56928. ** system would be badly broken.
  56929. **
  56930. ** If the log file is successfully opened, SQLITE_OK is returned and
  56931. ** *ppWal is set to point to a new WAL handle. If an error occurs,
  56932. ** an SQLite error code is returned and *ppWal is left unmodified.
  56933. */
  56934. SQLITE_PRIVATE int sqlite3WalOpen(
  56935. sqlite3_vfs *pVfs, /* vfs module to open wal and wal-index */
  56936. sqlite3_file *pDbFd, /* The open database file */
  56937. const char *zWalName, /* Name of the WAL file */
  56938. int bNoShm, /* True to run in heap-memory mode */
  56939. i64 mxWalSize, /* Truncate WAL to this size on reset */
  56940. Wal **ppWal /* OUT: Allocated Wal handle */
  56941. ){
  56942. int rc; /* Return Code */
  56943. Wal *pRet; /* Object to allocate and return */
  56944. int flags; /* Flags passed to OsOpen() */
  56945. assert( zWalName && zWalName[0] );
  56946. assert( pDbFd );
  56947. /* In the amalgamation, the os_unix.c and os_win.c source files come before
  56948. ** this source file. Verify that the #defines of the locking byte offsets
  56949. ** in os_unix.c and os_win.c agree with the WALINDEX_LOCK_OFFSET value.
  56950. ** For that matter, if the lock offset ever changes from its initial design
  56951. ** value of 120, we need to know that so there is an assert() to check it.
  56952. */
  56953. assert( 120==WALINDEX_LOCK_OFFSET );
  56954. assert( 136==WALINDEX_HDR_SIZE );
  56955. #ifdef WIN_SHM_BASE
  56956. assert( WIN_SHM_BASE==WALINDEX_LOCK_OFFSET );
  56957. #endif
  56958. #ifdef UNIX_SHM_BASE
  56959. assert( UNIX_SHM_BASE==WALINDEX_LOCK_OFFSET );
  56960. #endif
  56961. /* Allocate an instance of struct Wal to return. */
  56962. *ppWal = 0;
  56963. pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile);
  56964. if( !pRet ){
  56965. return SQLITE_NOMEM_BKPT;
  56966. }
  56967. pRet->pVfs = pVfs;
  56968. pRet->pWalFd = (sqlite3_file *)&pRet[1];
  56969. pRet->pDbFd = pDbFd;
  56970. pRet->readLock = -1;
  56971. pRet->mxWalSize = mxWalSize;
  56972. pRet->zWalName = zWalName;
  56973. pRet->syncHeader = 1;
  56974. pRet->padToSectorBoundary = 1;
  56975. pRet->exclusiveMode = (bNoShm ? WAL_HEAPMEMORY_MODE: WAL_NORMAL_MODE);
  56976. /* Open file handle on the write-ahead log file. */
  56977. flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_WAL);
  56978. rc = sqlite3OsOpen(pVfs, zWalName, pRet->pWalFd, flags, &flags);
  56979. if( rc==SQLITE_OK && flags&SQLITE_OPEN_READONLY ){
  56980. pRet->readOnly = WAL_RDONLY;
  56981. }
  56982. if( rc!=SQLITE_OK ){
  56983. walIndexClose(pRet, 0);
  56984. sqlite3OsClose(pRet->pWalFd);
  56985. sqlite3_free(pRet);
  56986. }else{
  56987. int iDC = sqlite3OsDeviceCharacteristics(pDbFd);
  56988. if( iDC & SQLITE_IOCAP_SEQUENTIAL ){ pRet->syncHeader = 0; }
  56989. if( iDC & SQLITE_IOCAP_POWERSAFE_OVERWRITE ){
  56990. pRet->padToSectorBoundary = 0;
  56991. }
  56992. *ppWal = pRet;
  56993. WALTRACE(("WAL%d: opened\n", pRet));
  56994. }
  56995. return rc;
  56996. }
  56997. /*
  56998. ** Change the size to which the WAL file is trucated on each reset.
  56999. */
  57000. SQLITE_PRIVATE void sqlite3WalLimit(Wal *pWal, i64 iLimit){
  57001. if( pWal ) pWal->mxWalSize = iLimit;
  57002. }
  57003. /*
  57004. ** Find the smallest page number out of all pages held in the WAL that
  57005. ** has not been returned by any prior invocation of this method on the
  57006. ** same WalIterator object. Write into *piFrame the frame index where
  57007. ** that page was last written into the WAL. Write into *piPage the page
  57008. ** number.
  57009. **
  57010. ** Return 0 on success. If there are no pages in the WAL with a page
  57011. ** number larger than *piPage, then return 1.
  57012. */
  57013. static int walIteratorNext(
  57014. WalIterator *p, /* Iterator */
  57015. u32 *piPage, /* OUT: The page number of the next page */
  57016. u32 *piFrame /* OUT: Wal frame index of next page */
  57017. ){
  57018. u32 iMin; /* Result pgno must be greater than iMin */
  57019. u32 iRet = 0xFFFFFFFF; /* 0xffffffff is never a valid page number */
  57020. int i; /* For looping through segments */
  57021. iMin = p->iPrior;
  57022. assert( iMin<0xffffffff );
  57023. for(i=p->nSegment-1; i>=0; i--){
  57024. struct WalSegment *pSegment = &p->aSegment[i];
  57025. while( pSegment->iNext<pSegment->nEntry ){
  57026. u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]];
  57027. if( iPg>iMin ){
  57028. if( iPg<iRet ){
  57029. iRet = iPg;
  57030. *piFrame = pSegment->iZero + pSegment->aIndex[pSegment->iNext];
  57031. }
  57032. break;
  57033. }
  57034. pSegment->iNext++;
  57035. }
  57036. }
  57037. *piPage = p->iPrior = iRet;
  57038. return (iRet==0xFFFFFFFF);
  57039. }
  57040. /*
  57041. ** This function merges two sorted lists into a single sorted list.
  57042. **
  57043. ** aLeft[] and aRight[] are arrays of indices. The sort key is
  57044. ** aContent[aLeft[]] and aContent[aRight[]]. Upon entry, the following
  57045. ** is guaranteed for all J<K:
  57046. **
  57047. ** aContent[aLeft[J]] < aContent[aLeft[K]]
  57048. ** aContent[aRight[J]] < aContent[aRight[K]]
  57049. **
  57050. ** This routine overwrites aRight[] with a new (probably longer) sequence
  57051. ** of indices such that the aRight[] contains every index that appears in
  57052. ** either aLeft[] or the old aRight[] and such that the second condition
  57053. ** above is still met.
  57054. **
  57055. ** The aContent[aLeft[X]] values will be unique for all X. And the
  57056. ** aContent[aRight[X]] values will be unique too. But there might be
  57057. ** one or more combinations of X and Y such that
  57058. **
  57059. ** aLeft[X]!=aRight[Y] && aContent[aLeft[X]] == aContent[aRight[Y]]
  57060. **
  57061. ** When that happens, omit the aLeft[X] and use the aRight[Y] index.
  57062. */
  57063. static void walMerge(
  57064. const u32 *aContent, /* Pages in wal - keys for the sort */
  57065. ht_slot *aLeft, /* IN: Left hand input list */
  57066. int nLeft, /* IN: Elements in array *paLeft */
  57067. ht_slot **paRight, /* IN/OUT: Right hand input list */
  57068. int *pnRight, /* IN/OUT: Elements in *paRight */
  57069. ht_slot *aTmp /* Temporary buffer */
  57070. ){
  57071. int iLeft = 0; /* Current index in aLeft */
  57072. int iRight = 0; /* Current index in aRight */
  57073. int iOut = 0; /* Current index in output buffer */
  57074. int nRight = *pnRight;
  57075. ht_slot *aRight = *paRight;
  57076. assert( nLeft>0 && nRight>0 );
  57077. while( iRight<nRight || iLeft<nLeft ){
  57078. ht_slot logpage;
  57079. Pgno dbpage;
  57080. if( (iLeft<nLeft)
  57081. && (iRight>=nRight || aContent[aLeft[iLeft]]<aContent[aRight[iRight]])
  57082. ){
  57083. logpage = aLeft[iLeft++];
  57084. }else{
  57085. logpage = aRight[iRight++];
  57086. }
  57087. dbpage = aContent[logpage];
  57088. aTmp[iOut++] = logpage;
  57089. if( iLeft<nLeft && aContent[aLeft[iLeft]]==dbpage ) iLeft++;
  57090. assert( iLeft>=nLeft || aContent[aLeft[iLeft]]>dbpage );
  57091. assert( iRight>=nRight || aContent[aRight[iRight]]>dbpage );
  57092. }
  57093. *paRight = aLeft;
  57094. *pnRight = iOut;
  57095. memcpy(aLeft, aTmp, sizeof(aTmp[0])*iOut);
  57096. }
  57097. /*
  57098. ** Sort the elements in list aList using aContent[] as the sort key.
  57099. ** Remove elements with duplicate keys, preferring to keep the
  57100. ** larger aList[] values.
  57101. **
  57102. ** The aList[] entries are indices into aContent[]. The values in
  57103. ** aList[] are to be sorted so that for all J<K:
  57104. **
  57105. ** aContent[aList[J]] < aContent[aList[K]]
  57106. **
  57107. ** For any X and Y such that
  57108. **
  57109. ** aContent[aList[X]] == aContent[aList[Y]]
  57110. **
  57111. ** Keep the larger of the two values aList[X] and aList[Y] and discard
  57112. ** the smaller.
  57113. */
  57114. static void walMergesort(
  57115. const u32 *aContent, /* Pages in wal */
  57116. ht_slot *aBuffer, /* Buffer of at least *pnList items to use */
  57117. ht_slot *aList, /* IN/OUT: List to sort */
  57118. int *pnList /* IN/OUT: Number of elements in aList[] */
  57119. ){
  57120. struct Sublist {
  57121. int nList; /* Number of elements in aList */
  57122. ht_slot *aList; /* Pointer to sub-list content */
  57123. };
  57124. const int nList = *pnList; /* Size of input list */
  57125. int nMerge = 0; /* Number of elements in list aMerge */
  57126. ht_slot *aMerge = 0; /* List to be merged */
  57127. int iList; /* Index into input list */
  57128. u32 iSub = 0; /* Index into aSub array */
  57129. struct Sublist aSub[13]; /* Array of sub-lists */
  57130. memset(aSub, 0, sizeof(aSub));
  57131. assert( nList<=HASHTABLE_NPAGE && nList>0 );
  57132. assert( HASHTABLE_NPAGE==(1<<(ArraySize(aSub)-1)) );
  57133. for(iList=0; iList<nList; iList++){
  57134. nMerge = 1;
  57135. aMerge = &aList[iList];
  57136. for(iSub=0; iList & (1<<iSub); iSub++){
  57137. struct Sublist *p;
  57138. assert( iSub<ArraySize(aSub) );
  57139. p = &aSub[iSub];
  57140. assert( p->aList && p->nList<=(1<<iSub) );
  57141. assert( p->aList==&aList[iList&~((2<<iSub)-1)] );
  57142. walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
  57143. }
  57144. aSub[iSub].aList = aMerge;
  57145. aSub[iSub].nList = nMerge;
  57146. }
  57147. for(iSub++; iSub<ArraySize(aSub); iSub++){
  57148. if( nList & (1<<iSub) ){
  57149. struct Sublist *p;
  57150. assert( iSub<ArraySize(aSub) );
  57151. p = &aSub[iSub];
  57152. assert( p->nList<=(1<<iSub) );
  57153. assert( p->aList==&aList[nList&~((2<<iSub)-1)] );
  57154. walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
  57155. }
  57156. }
  57157. assert( aMerge==aList );
  57158. *pnList = nMerge;
  57159. #ifdef SQLITE_DEBUG
  57160. {
  57161. int i;
  57162. for(i=1; i<*pnList; i++){
  57163. assert( aContent[aList[i]] > aContent[aList[i-1]] );
  57164. }
  57165. }
  57166. #endif
  57167. }
  57168. /*
  57169. ** Free an iterator allocated by walIteratorInit().
  57170. */
  57171. static void walIteratorFree(WalIterator *p){
  57172. sqlite3_free(p);
  57173. }
  57174. /*
  57175. ** Construct a WalInterator object that can be used to loop over all
  57176. ** pages in the WAL following frame nBackfill in ascending order. Frames
  57177. ** nBackfill or earlier may be included - excluding them is an optimization
  57178. ** only. The caller must hold the checkpoint lock.
  57179. **
  57180. ** On success, make *pp point to the newly allocated WalInterator object
  57181. ** return SQLITE_OK. Otherwise, return an error code. If this routine
  57182. ** returns an error, the value of *pp is undefined.
  57183. **
  57184. ** The calling routine should invoke walIteratorFree() to destroy the
  57185. ** WalIterator object when it has finished with it.
  57186. */
  57187. static int walIteratorInit(Wal *pWal, u32 nBackfill, WalIterator **pp){
  57188. WalIterator *p; /* Return value */
  57189. int nSegment; /* Number of segments to merge */
  57190. u32 iLast; /* Last frame in log */
  57191. sqlite3_int64 nByte; /* Number of bytes to allocate */
  57192. int i; /* Iterator variable */
  57193. ht_slot *aTmp; /* Temp space used by merge-sort */
  57194. int rc = SQLITE_OK; /* Return Code */
  57195. /* This routine only runs while holding the checkpoint lock. And
  57196. ** it only runs if there is actually content in the log (mxFrame>0).
  57197. */
  57198. assert( pWal->ckptLock && pWal->hdr.mxFrame>0 );
  57199. iLast = pWal->hdr.mxFrame;
  57200. /* Allocate space for the WalIterator object. */
  57201. nSegment = walFramePage(iLast) + 1;
  57202. nByte = sizeof(WalIterator)
  57203. + (nSegment-1)*sizeof(struct WalSegment)
  57204. + iLast*sizeof(ht_slot);
  57205. p = (WalIterator *)sqlite3_malloc64(nByte);
  57206. if( !p ){
  57207. return SQLITE_NOMEM_BKPT;
  57208. }
  57209. memset(p, 0, nByte);
  57210. p->nSegment = nSegment;
  57211. /* Allocate temporary space used by the merge-sort routine. This block
  57212. ** of memory will be freed before this function returns.
  57213. */
  57214. aTmp = (ht_slot *)sqlite3_malloc64(
  57215. sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast)
  57216. );
  57217. if( !aTmp ){
  57218. rc = SQLITE_NOMEM_BKPT;
  57219. }
  57220. for(i=walFramePage(nBackfill+1); rc==SQLITE_OK && i<nSegment; i++){
  57221. WalHashLoc sLoc;
  57222. rc = walHashGet(pWal, i, &sLoc);
  57223. if( rc==SQLITE_OK ){
  57224. int j; /* Counter variable */
  57225. int nEntry; /* Number of entries in this segment */
  57226. ht_slot *aIndex; /* Sorted index for this segment */
  57227. sLoc.aPgno++;
  57228. if( (i+1)==nSegment ){
  57229. nEntry = (int)(iLast - sLoc.iZero);
  57230. }else{
  57231. nEntry = (int)((u32*)sLoc.aHash - (u32*)sLoc.aPgno);
  57232. }
  57233. aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[sLoc.iZero];
  57234. sLoc.iZero++;
  57235. for(j=0; j<nEntry; j++){
  57236. aIndex[j] = (ht_slot)j;
  57237. }
  57238. walMergesort((u32 *)sLoc.aPgno, aTmp, aIndex, &nEntry);
  57239. p->aSegment[i].iZero = sLoc.iZero;
  57240. p->aSegment[i].nEntry = nEntry;
  57241. p->aSegment[i].aIndex = aIndex;
  57242. p->aSegment[i].aPgno = (u32 *)sLoc.aPgno;
  57243. }
  57244. }
  57245. sqlite3_free(aTmp);
  57246. if( rc!=SQLITE_OK ){
  57247. walIteratorFree(p);
  57248. p = 0;
  57249. }
  57250. *pp = p;
  57251. return rc;
  57252. }
  57253. #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
  57254. /*
  57255. ** Attempt to enable blocking locks. Blocking locks are enabled only if (a)
  57256. ** they are supported by the VFS, and (b) the database handle is configured
  57257. ** with a busy-timeout. Return 1 if blocking locks are successfully enabled,
  57258. ** or 0 otherwise.
  57259. */
  57260. static int walEnableBlocking(Wal *pWal){
  57261. int res = 0;
  57262. if( pWal->db ){
  57263. int tmout = pWal->db->busyTimeout;
  57264. if( tmout ){
  57265. int rc;
  57266. rc = sqlite3OsFileControl(
  57267. pWal->pDbFd, SQLITE_FCNTL_LOCK_TIMEOUT, (void*)&tmout
  57268. );
  57269. res = (rc==SQLITE_OK);
  57270. }
  57271. }
  57272. return res;
  57273. }
  57274. /*
  57275. ** Disable blocking locks.
  57276. */
  57277. static void walDisableBlocking(Wal *pWal){
  57278. int tmout = 0;
  57279. sqlite3OsFileControl(pWal->pDbFd, SQLITE_FCNTL_LOCK_TIMEOUT, (void*)&tmout);
  57280. }
  57281. /*
  57282. ** If parameter bLock is true, attempt to enable blocking locks, take
  57283. ** the WRITER lock, and then disable blocking locks. If blocking locks
  57284. ** cannot be enabled, no attempt to obtain the WRITER lock is made. Return
  57285. ** an SQLite error code if an error occurs, or SQLITE_OK otherwise. It is not
  57286. ** an error if blocking locks can not be enabled.
  57287. **
  57288. ** If the bLock parameter is false and the WRITER lock is held, release it.
  57289. */
  57290. SQLITE_PRIVATE int sqlite3WalWriteLock(Wal *pWal, int bLock){
  57291. int rc = SQLITE_OK;
  57292. assert( pWal->readLock<0 || bLock==0 );
  57293. if( bLock ){
  57294. assert( pWal->db );
  57295. if( walEnableBlocking(pWal) ){
  57296. rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);
  57297. if( rc==SQLITE_OK ){
  57298. pWal->writeLock = 1;
  57299. }
  57300. walDisableBlocking(pWal);
  57301. }
  57302. }else if( pWal->writeLock ){
  57303. walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
  57304. pWal->writeLock = 0;
  57305. }
  57306. return rc;
  57307. }
  57308. /*
  57309. ** Set the database handle used to determine if blocking locks are required.
  57310. */
  57311. SQLITE_PRIVATE void sqlite3WalDb(Wal *pWal, sqlite3 *db){
  57312. pWal->db = db;
  57313. }
  57314. /*
  57315. ** Take an exclusive WRITE lock. Blocking if so configured.
  57316. */
  57317. static int walLockWriter(Wal *pWal){
  57318. int rc;
  57319. walEnableBlocking(pWal);
  57320. rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);
  57321. walDisableBlocking(pWal);
  57322. return rc;
  57323. }
  57324. #else
  57325. # define walEnableBlocking(x) 0
  57326. # define walDisableBlocking(x)
  57327. # define walLockWriter(pWal) walLockExclusive((pWal), WAL_WRITE_LOCK, 1)
  57328. # define sqlite3WalDb(pWal, db)
  57329. #endif /* ifdef SQLITE_ENABLE_SETLK_TIMEOUT */
  57330. /*
  57331. ** Attempt to obtain the exclusive WAL lock defined by parameters lockIdx and
  57332. ** n. If the attempt fails and parameter xBusy is not NULL, then it is a
  57333. ** busy-handler function. Invoke it and retry the lock until either the
  57334. ** lock is successfully obtained or the busy-handler returns 0.
  57335. */
  57336. static int walBusyLock(
  57337. Wal *pWal, /* WAL connection */
  57338. int (*xBusy)(void*), /* Function to call when busy */
  57339. void *pBusyArg, /* Context argument for xBusyHandler */
  57340. int lockIdx, /* Offset of first byte to lock */
  57341. int n /* Number of bytes to lock */
  57342. ){
  57343. int rc;
  57344. do {
  57345. rc = walLockExclusive(pWal, lockIdx, n);
  57346. }while( xBusy && rc==SQLITE_BUSY && xBusy(pBusyArg) );
  57347. #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
  57348. if( rc==SQLITE_BUSY_TIMEOUT ){
  57349. walDisableBlocking(pWal);
  57350. rc = SQLITE_BUSY;
  57351. }
  57352. #endif
  57353. return rc;
  57354. }
  57355. /*
  57356. ** The cache of the wal-index header must be valid to call this function.
  57357. ** Return the page-size in bytes used by the database.
  57358. */
  57359. static int walPagesize(Wal *pWal){
  57360. return (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
  57361. }
  57362. /*
  57363. ** The following is guaranteed when this function is called:
  57364. **
  57365. ** a) the WRITER lock is held,
  57366. ** b) the entire log file has been checkpointed, and
  57367. ** c) any existing readers are reading exclusively from the database
  57368. ** file - there are no readers that may attempt to read a frame from
  57369. ** the log file.
  57370. **
  57371. ** This function updates the shared-memory structures so that the next
  57372. ** client to write to the database (which may be this one) does so by
  57373. ** writing frames into the start of the log file.
  57374. **
  57375. ** The value of parameter salt1 is used as the aSalt[1] value in the
  57376. ** new wal-index header. It should be passed a pseudo-random value (i.e.
  57377. ** one obtained from sqlite3_randomness()).
  57378. */
  57379. static void walRestartHdr(Wal *pWal, u32 salt1){
  57380. volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
  57381. int i; /* Loop counter */
  57382. u32 *aSalt = pWal->hdr.aSalt; /* Big-endian salt values */
  57383. pWal->nCkpt++;
  57384. pWal->hdr.mxFrame = 0;
  57385. sqlite3Put4byte((u8*)&aSalt[0], 1 + sqlite3Get4byte((u8*)&aSalt[0]));
  57386. memcpy(&pWal->hdr.aSalt[1], &salt1, 4);
  57387. walIndexWriteHdr(pWal);
  57388. AtomicStore(&pInfo->nBackfill, 0);
  57389. pInfo->nBackfillAttempted = 0;
  57390. pInfo->aReadMark[1] = 0;
  57391. for(i=2; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
  57392. assert( pInfo->aReadMark[0]==0 );
  57393. }
  57394. /*
  57395. ** Copy as much content as we can from the WAL back into the database file
  57396. ** in response to an sqlite3_wal_checkpoint() request or the equivalent.
  57397. **
  57398. ** The amount of information copies from WAL to database might be limited
  57399. ** by active readers. This routine will never overwrite a database page
  57400. ** that a concurrent reader might be using.
  57401. **
  57402. ** All I/O barrier operations (a.k.a fsyncs) occur in this routine when
  57403. ** SQLite is in WAL-mode in synchronous=NORMAL. That means that if
  57404. ** checkpoints are always run by a background thread or background
  57405. ** process, foreground threads will never block on a lengthy fsync call.
  57406. **
  57407. ** Fsync is called on the WAL before writing content out of the WAL and
  57408. ** into the database. This ensures that if the new content is persistent
  57409. ** in the WAL and can be recovered following a power-loss or hard reset.
  57410. **
  57411. ** Fsync is also called on the database file if (and only if) the entire
  57412. ** WAL content is copied into the database file. This second fsync makes
  57413. ** it safe to delete the WAL since the new content will persist in the
  57414. ** database file.
  57415. **
  57416. ** This routine uses and updates the nBackfill field of the wal-index header.
  57417. ** This is the only routine that will increase the value of nBackfill.
  57418. ** (A WAL reset or recovery will revert nBackfill to zero, but not increase
  57419. ** its value.)
  57420. **
  57421. ** The caller must be holding sufficient locks to ensure that no other
  57422. ** checkpoint is running (in any other thread or process) at the same
  57423. ** time.
  57424. */
  57425. static int walCheckpoint(
  57426. Wal *pWal, /* Wal connection */
  57427. sqlite3 *db, /* Check for interrupts on this handle */
  57428. int eMode, /* One of PASSIVE, FULL or RESTART */
  57429. int (*xBusy)(void*), /* Function to call when busy */
  57430. void *pBusyArg, /* Context argument for xBusyHandler */
  57431. int sync_flags, /* Flags for OsSync() (or 0) */
  57432. u8 *zBuf /* Temporary buffer to use */
  57433. ){
  57434. int rc = SQLITE_OK; /* Return code */
  57435. int szPage; /* Database page-size */
  57436. WalIterator *pIter = 0; /* Wal iterator context */
  57437. u32 iDbpage = 0; /* Next database page to write */
  57438. u32 iFrame = 0; /* Wal frame containing data for iDbpage */
  57439. u32 mxSafeFrame; /* Max frame that can be backfilled */
  57440. u32 mxPage; /* Max database page to write */
  57441. int i; /* Loop counter */
  57442. volatile WalCkptInfo *pInfo; /* The checkpoint status information */
  57443. szPage = walPagesize(pWal);
  57444. testcase( szPage<=32768 );
  57445. testcase( szPage>=65536 );
  57446. pInfo = walCkptInfo(pWal);
  57447. if( pInfo->nBackfill<pWal->hdr.mxFrame ){
  57448. /* EVIDENCE-OF: R-62920-47450 The busy-handler callback is never invoked
  57449. ** in the SQLITE_CHECKPOINT_PASSIVE mode. */
  57450. assert( eMode!=SQLITE_CHECKPOINT_PASSIVE || xBusy==0 );
  57451. /* Compute in mxSafeFrame the index of the last frame of the WAL that is
  57452. ** safe to write into the database. Frames beyond mxSafeFrame might
  57453. ** overwrite database pages that are in use by active readers and thus
  57454. ** cannot be backfilled from the WAL.
  57455. */
  57456. mxSafeFrame = pWal->hdr.mxFrame;
  57457. mxPage = pWal->hdr.nPage;
  57458. for(i=1; i<WAL_NREADER; i++){
  57459. u32 y = AtomicLoad(pInfo->aReadMark+i);
  57460. if( mxSafeFrame>y ){
  57461. assert( y<=pWal->hdr.mxFrame );
  57462. rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(i), 1);
  57463. if( rc==SQLITE_OK ){
  57464. u32 iMark = (i==1 ? mxSafeFrame : READMARK_NOT_USED);
  57465. AtomicStore(pInfo->aReadMark+i, iMark);
  57466. walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
  57467. }else if( rc==SQLITE_BUSY ){
  57468. mxSafeFrame = y;
  57469. xBusy = 0;
  57470. }else{
  57471. goto walcheckpoint_out;
  57472. }
  57473. }
  57474. }
  57475. /* Allocate the iterator */
  57476. if( pInfo->nBackfill<mxSafeFrame ){
  57477. rc = walIteratorInit(pWal, pInfo->nBackfill, &pIter);
  57478. assert( rc==SQLITE_OK || pIter==0 );
  57479. }
  57480. if( pIter
  57481. && (rc = walBusyLock(pWal,xBusy,pBusyArg,WAL_READ_LOCK(0),1))==SQLITE_OK
  57482. ){
  57483. u32 nBackfill = pInfo->nBackfill;
  57484. pInfo->nBackfillAttempted = mxSafeFrame;
  57485. /* Sync the WAL to disk */
  57486. rc = sqlite3OsSync(pWal->pWalFd, CKPT_SYNC_FLAGS(sync_flags));
  57487. /* If the database may grow as a result of this checkpoint, hint
  57488. ** about the eventual size of the db file to the VFS layer.
  57489. */
  57490. if( rc==SQLITE_OK ){
  57491. i64 nReq = ((i64)mxPage * szPage);
  57492. i64 nSize; /* Current size of database file */
  57493. sqlite3OsFileControl(pWal->pDbFd, SQLITE_FCNTL_CKPT_START, 0);
  57494. rc = sqlite3OsFileSize(pWal->pDbFd, &nSize);
  57495. if( rc==SQLITE_OK && nSize<nReq ){
  57496. sqlite3OsFileControlHint(pWal->pDbFd, SQLITE_FCNTL_SIZE_HINT, &nReq);
  57497. }
  57498. }
  57499. /* Iterate through the contents of the WAL, copying data to the db file */
  57500. while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){
  57501. i64 iOffset;
  57502. assert( walFramePgno(pWal, iFrame)==iDbpage );
  57503. if( AtomicLoad(&db->u1.isInterrupted) ){
  57504. rc = db->mallocFailed ? SQLITE_NOMEM_BKPT : SQLITE_INTERRUPT;
  57505. break;
  57506. }
  57507. if( iFrame<=nBackfill || iFrame>mxSafeFrame || iDbpage>mxPage ){
  57508. continue;
  57509. }
  57510. iOffset = walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE;
  57511. /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL file */
  57512. rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset);
  57513. if( rc!=SQLITE_OK ) break;
  57514. iOffset = (iDbpage-1)*(i64)szPage;
  57515. testcase( IS_BIG_INT(iOffset) );
  57516. rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset);
  57517. if( rc!=SQLITE_OK ) break;
  57518. }
  57519. sqlite3OsFileControl(pWal->pDbFd, SQLITE_FCNTL_CKPT_DONE, 0);
  57520. /* If work was actually accomplished... */
  57521. if( rc==SQLITE_OK ){
  57522. if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){
  57523. i64 szDb = pWal->hdr.nPage*(i64)szPage;
  57524. testcase( IS_BIG_INT(szDb) );
  57525. rc = sqlite3OsTruncate(pWal->pDbFd, szDb);
  57526. if( rc==SQLITE_OK ){
  57527. rc = sqlite3OsSync(pWal->pDbFd, CKPT_SYNC_FLAGS(sync_flags));
  57528. }
  57529. }
  57530. if( rc==SQLITE_OK ){
  57531. AtomicStore(&pInfo->nBackfill, mxSafeFrame);
  57532. }
  57533. }
  57534. /* Release the reader lock held while backfilling */
  57535. walUnlockExclusive(pWal, WAL_READ_LOCK(0), 1);
  57536. }
  57537. if( rc==SQLITE_BUSY ){
  57538. /* Reset the return code so as not to report a checkpoint failure
  57539. ** just because there are active readers. */
  57540. rc = SQLITE_OK;
  57541. }
  57542. }
  57543. /* If this is an SQLITE_CHECKPOINT_RESTART or TRUNCATE operation, and the
  57544. ** entire wal file has been copied into the database file, then block
  57545. ** until all readers have finished using the wal file. This ensures that
  57546. ** the next process to write to the database restarts the wal file.
  57547. */
  57548. if( rc==SQLITE_OK && eMode!=SQLITE_CHECKPOINT_PASSIVE ){
  57549. assert( pWal->writeLock );
  57550. if( pInfo->nBackfill<pWal->hdr.mxFrame ){
  57551. rc = SQLITE_BUSY;
  57552. }else if( eMode>=SQLITE_CHECKPOINT_RESTART ){
  57553. u32 salt1;
  57554. sqlite3_randomness(4, &salt1);
  57555. assert( pInfo->nBackfill==pWal->hdr.mxFrame );
  57556. rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(1), WAL_NREADER-1);
  57557. if( rc==SQLITE_OK ){
  57558. if( eMode==SQLITE_CHECKPOINT_TRUNCATE ){
  57559. /* IMPLEMENTATION-OF: R-44699-57140 This mode works the same way as
  57560. ** SQLITE_CHECKPOINT_RESTART with the addition that it also
  57561. ** truncates the log file to zero bytes just prior to a
  57562. ** successful return.
  57563. **
  57564. ** In theory, it might be safe to do this without updating the
  57565. ** wal-index header in shared memory, as all subsequent reader or
  57566. ** writer clients should see that the entire log file has been
  57567. ** checkpointed and behave accordingly. This seems unsafe though,
  57568. ** as it would leave the system in a state where the contents of
  57569. ** the wal-index header do not match the contents of the
  57570. ** file-system. To avoid this, update the wal-index header to
  57571. ** indicate that the log file contains zero valid frames. */
  57572. walRestartHdr(pWal, salt1);
  57573. rc = sqlite3OsTruncate(pWal->pWalFd, 0);
  57574. }
  57575. walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
  57576. }
  57577. }
  57578. }
  57579. walcheckpoint_out:
  57580. walIteratorFree(pIter);
  57581. return rc;
  57582. }
  57583. /*
  57584. ** If the WAL file is currently larger than nMax bytes in size, truncate
  57585. ** it to exactly nMax bytes. If an error occurs while doing so, ignore it.
  57586. */
  57587. static void walLimitSize(Wal *pWal, i64 nMax){
  57588. i64 sz;
  57589. int rx;
  57590. sqlite3BeginBenignMalloc();
  57591. rx = sqlite3OsFileSize(pWal->pWalFd, &sz);
  57592. if( rx==SQLITE_OK && (sz > nMax ) ){
  57593. rx = sqlite3OsTruncate(pWal->pWalFd, nMax);
  57594. }
  57595. sqlite3EndBenignMalloc();
  57596. if( rx ){
  57597. sqlite3_log(rx, "cannot limit WAL size: %s", pWal->zWalName);
  57598. }
  57599. }
  57600. /*
  57601. ** Close a connection to a log file.
  57602. */
  57603. SQLITE_PRIVATE int sqlite3WalClose(
  57604. Wal *pWal, /* Wal to close */
  57605. sqlite3 *db, /* For interrupt flag */
  57606. int sync_flags, /* Flags to pass to OsSync() (or 0) */
  57607. int nBuf,
  57608. u8 *zBuf /* Buffer of at least nBuf bytes */
  57609. ){
  57610. int rc = SQLITE_OK;
  57611. if( pWal ){
  57612. int isDelete = 0; /* True to unlink wal and wal-index files */
  57613. /* If an EXCLUSIVE lock can be obtained on the database file (using the
  57614. ** ordinary, rollback-mode locking methods, this guarantees that the
  57615. ** connection associated with this log file is the only connection to
  57616. ** the database. In this case checkpoint the database and unlink both
  57617. ** the wal and wal-index files.
  57618. **
  57619. ** The EXCLUSIVE lock is not released before returning.
  57620. */
  57621. if( zBuf!=0
  57622. && SQLITE_OK==(rc = sqlite3OsLock(pWal->pDbFd, SQLITE_LOCK_EXCLUSIVE))
  57623. ){
  57624. if( pWal->exclusiveMode==WAL_NORMAL_MODE ){
  57625. pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
  57626. }
  57627. rc = sqlite3WalCheckpoint(pWal, db,
  57628. SQLITE_CHECKPOINT_PASSIVE, 0, 0, sync_flags, nBuf, zBuf, 0, 0
  57629. );
  57630. if( rc==SQLITE_OK ){
  57631. int bPersist = -1;
  57632. sqlite3OsFileControlHint(
  57633. pWal->pDbFd, SQLITE_FCNTL_PERSIST_WAL, &bPersist
  57634. );
  57635. if( bPersist!=1 ){
  57636. /* Try to delete the WAL file if the checkpoint completed and
  57637. ** fsyned (rc==SQLITE_OK) and if we are not in persistent-wal
  57638. ** mode (!bPersist) */
  57639. isDelete = 1;
  57640. }else if( pWal->mxWalSize>=0 ){
  57641. /* Try to truncate the WAL file to zero bytes if the checkpoint
  57642. ** completed and fsynced (rc==SQLITE_OK) and we are in persistent
  57643. ** WAL mode (bPersist) and if the PRAGMA journal_size_limit is a
  57644. ** non-negative value (pWal->mxWalSize>=0). Note that we truncate
  57645. ** to zero bytes as truncating to the journal_size_limit might
  57646. ** leave a corrupt WAL file on disk. */
  57647. walLimitSize(pWal, 0);
  57648. }
  57649. }
  57650. }
  57651. walIndexClose(pWal, isDelete);
  57652. sqlite3OsClose(pWal->pWalFd);
  57653. if( isDelete ){
  57654. sqlite3BeginBenignMalloc();
  57655. sqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0);
  57656. sqlite3EndBenignMalloc();
  57657. }
  57658. WALTRACE(("WAL%p: closed\n", pWal));
  57659. sqlite3_free((void *)pWal->apWiData);
  57660. sqlite3_free(pWal);
  57661. }
  57662. return rc;
  57663. }
  57664. /*
  57665. ** Try to read the wal-index header. Return 0 on success and 1 if
  57666. ** there is a problem.
  57667. **
  57668. ** The wal-index is in shared memory. Another thread or process might
  57669. ** be writing the header at the same time this procedure is trying to
  57670. ** read it, which might result in inconsistency. A dirty read is detected
  57671. ** by verifying that both copies of the header are the same and also by
  57672. ** a checksum on the header.
  57673. **
  57674. ** If and only if the read is consistent and the header is different from
  57675. ** pWal->hdr, then pWal->hdr is updated to the content of the new header
  57676. ** and *pChanged is set to 1.
  57677. **
  57678. ** If the checksum cannot be verified return non-zero. If the header
  57679. ** is read successfully and the checksum verified, return zero.
  57680. */
  57681. static SQLITE_NO_TSAN int walIndexTryHdr(Wal *pWal, int *pChanged){
  57682. u32 aCksum[2]; /* Checksum on the header content */
  57683. WalIndexHdr h1, h2; /* Two copies of the header content */
  57684. WalIndexHdr volatile *aHdr; /* Header in shared memory */
  57685. /* The first page of the wal-index must be mapped at this point. */
  57686. assert( pWal->nWiData>0 && pWal->apWiData[0] );
  57687. /* Read the header. This might happen concurrently with a write to the
  57688. ** same area of shared memory on a different CPU in a SMP,
  57689. ** meaning it is possible that an inconsistent snapshot is read
  57690. ** from the file. If this happens, return non-zero.
  57691. **
  57692. ** tag-20200519-1:
  57693. ** There are two copies of the header at the beginning of the wal-index.
  57694. ** When reading, read [0] first then [1]. Writes are in the reverse order.
  57695. ** Memory barriers are used to prevent the compiler or the hardware from
  57696. ** reordering the reads and writes. TSAN and similar tools can sometimes
  57697. ** give false-positive warnings about these accesses because the tools do not
  57698. ** account for the double-read and the memory barrier. The use of mutexes
  57699. ** here would be problematic as the memory being accessed is potentially
  57700. ** shared among multiple processes and not all mutex implementions work
  57701. ** reliably in that environment.
  57702. */
  57703. aHdr = walIndexHdr(pWal);
  57704. memcpy(&h1, (void *)&aHdr[0], sizeof(h1)); /* Possible TSAN false-positive */
  57705. walShmBarrier(pWal);
  57706. memcpy(&h2, (void *)&aHdr[1], sizeof(h2));
  57707. if( memcmp(&h1, &h2, sizeof(h1))!=0 ){
  57708. return 1; /* Dirty read */
  57709. }
  57710. if( h1.isInit==0 ){
  57711. return 1; /* Malformed header - probably all zeros */
  57712. }
  57713. walChecksumBytes(1, (u8*)&h1, sizeof(h1)-sizeof(h1.aCksum), 0, aCksum);
  57714. if( aCksum[0]!=h1.aCksum[0] || aCksum[1]!=h1.aCksum[1] ){
  57715. return 1; /* Checksum does not match */
  57716. }
  57717. if( memcmp(&pWal->hdr, &h1, sizeof(WalIndexHdr)) ){
  57718. *pChanged = 1;
  57719. memcpy(&pWal->hdr, &h1, sizeof(WalIndexHdr));
  57720. pWal->szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
  57721. testcase( pWal->szPage<=32768 );
  57722. testcase( pWal->szPage>=65536 );
  57723. }
  57724. /* The header was successfully read. Return zero. */
  57725. return 0;
  57726. }
  57727. /*
  57728. ** This is the value that walTryBeginRead returns when it needs to
  57729. ** be retried.
  57730. */
  57731. #define WAL_RETRY (-1)
  57732. /*
  57733. ** Read the wal-index header from the wal-index and into pWal->hdr.
  57734. ** If the wal-header appears to be corrupt, try to reconstruct the
  57735. ** wal-index from the WAL before returning.
  57736. **
  57737. ** Set *pChanged to 1 if the wal-index header value in pWal->hdr is
  57738. ** changed by this operation. If pWal->hdr is unchanged, set *pChanged
  57739. ** to 0.
  57740. **
  57741. ** If the wal-index header is successfully read, return SQLITE_OK.
  57742. ** Otherwise an SQLite error code.
  57743. */
  57744. static int walIndexReadHdr(Wal *pWal, int *pChanged){
  57745. int rc; /* Return code */
  57746. int badHdr; /* True if a header read failed */
  57747. volatile u32 *page0; /* Chunk of wal-index containing header */
  57748. /* Ensure that page 0 of the wal-index (the page that contains the
  57749. ** wal-index header) is mapped. Return early if an error occurs here.
  57750. */
  57751. assert( pChanged );
  57752. rc = walIndexPage(pWal, 0, &page0);
  57753. if( rc!=SQLITE_OK ){
  57754. assert( rc!=SQLITE_READONLY ); /* READONLY changed to OK in walIndexPage */
  57755. if( rc==SQLITE_READONLY_CANTINIT ){
  57756. /* The SQLITE_READONLY_CANTINIT return means that the shared-memory
  57757. ** was openable but is not writable, and this thread is unable to
  57758. ** confirm that another write-capable connection has the shared-memory
  57759. ** open, and hence the content of the shared-memory is unreliable,
  57760. ** since the shared-memory might be inconsistent with the WAL file
  57761. ** and there is no writer on hand to fix it. */
  57762. assert( page0==0 );
  57763. assert( pWal->writeLock==0 );
  57764. assert( pWal->readOnly & WAL_SHM_RDONLY );
  57765. pWal->bShmUnreliable = 1;
  57766. pWal->exclusiveMode = WAL_HEAPMEMORY_MODE;
  57767. *pChanged = 1;
  57768. }else{
  57769. return rc; /* Any other non-OK return is just an error */
  57770. }
  57771. }else{
  57772. /* page0 can be NULL if the SHM is zero bytes in size and pWal->writeLock
  57773. ** is zero, which prevents the SHM from growing */
  57774. testcase( page0!=0 );
  57775. }
  57776. assert( page0!=0 || pWal->writeLock==0 );
  57777. /* If the first page of the wal-index has been mapped, try to read the
  57778. ** wal-index header immediately, without holding any lock. This usually
  57779. ** works, but may fail if the wal-index header is corrupt or currently
  57780. ** being modified by another thread or process.
  57781. */
  57782. badHdr = (page0 ? walIndexTryHdr(pWal, pChanged) : 1);
  57783. /* If the first attempt failed, it might have been due to a race
  57784. ** with a writer. So get a WRITE lock and try again.
  57785. */
  57786. if( badHdr ){
  57787. if( pWal->bShmUnreliable==0 && (pWal->readOnly & WAL_SHM_RDONLY) ){
  57788. if( SQLITE_OK==(rc = walLockShared(pWal, WAL_WRITE_LOCK)) ){
  57789. walUnlockShared(pWal, WAL_WRITE_LOCK);
  57790. rc = SQLITE_READONLY_RECOVERY;
  57791. }
  57792. }else{
  57793. int bWriteLock = pWal->writeLock;
  57794. if( bWriteLock || SQLITE_OK==(rc = walLockWriter(pWal)) ){
  57795. pWal->writeLock = 1;
  57796. if( SQLITE_OK==(rc = walIndexPage(pWal, 0, &page0)) ){
  57797. badHdr = walIndexTryHdr(pWal, pChanged);
  57798. if( badHdr ){
  57799. /* If the wal-index header is still malformed even while holding
  57800. ** a WRITE lock, it can only mean that the header is corrupted and
  57801. ** needs to be reconstructed. So run recovery to do exactly that.
  57802. */
  57803. rc = walIndexRecover(pWal);
  57804. *pChanged = 1;
  57805. }
  57806. }
  57807. if( bWriteLock==0 ){
  57808. pWal->writeLock = 0;
  57809. walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
  57810. }
  57811. }
  57812. }
  57813. }
  57814. /* If the header is read successfully, check the version number to make
  57815. ** sure the wal-index was not constructed with some future format that
  57816. ** this version of SQLite cannot understand.
  57817. */
  57818. if( badHdr==0 && pWal->hdr.iVersion!=WALINDEX_MAX_VERSION ){
  57819. rc = SQLITE_CANTOPEN_BKPT;
  57820. }
  57821. if( pWal->bShmUnreliable ){
  57822. if( rc!=SQLITE_OK ){
  57823. walIndexClose(pWal, 0);
  57824. pWal->bShmUnreliable = 0;
  57825. assert( pWal->nWiData>0 && pWal->apWiData[0]==0 );
  57826. /* walIndexRecover() might have returned SHORT_READ if a concurrent
  57827. ** writer truncated the WAL out from under it. If that happens, it
  57828. ** indicates that a writer has fixed the SHM file for us, so retry */
  57829. if( rc==SQLITE_IOERR_SHORT_READ ) rc = WAL_RETRY;
  57830. }
  57831. pWal->exclusiveMode = WAL_NORMAL_MODE;
  57832. }
  57833. return rc;
  57834. }
  57835. /*
  57836. ** Open a transaction in a connection where the shared-memory is read-only
  57837. ** and where we cannot verify that there is a separate write-capable connection
  57838. ** on hand to keep the shared-memory up-to-date with the WAL file.
  57839. **
  57840. ** This can happen, for example, when the shared-memory is implemented by
  57841. ** memory-mapping a *-shm file, where a prior writer has shut down and
  57842. ** left the *-shm file on disk, and now the present connection is trying
  57843. ** to use that database but lacks write permission on the *-shm file.
  57844. ** Other scenarios are also possible, depending on the VFS implementation.
  57845. **
  57846. ** Precondition:
  57847. **
  57848. ** The *-wal file has been read and an appropriate wal-index has been
  57849. ** constructed in pWal->apWiData[] using heap memory instead of shared
  57850. ** memory.
  57851. **
  57852. ** If this function returns SQLITE_OK, then the read transaction has
  57853. ** been successfully opened. In this case output variable (*pChanged)
  57854. ** is set to true before returning if the caller should discard the
  57855. ** contents of the page cache before proceeding. Or, if it returns
  57856. ** WAL_RETRY, then the heap memory wal-index has been discarded and
  57857. ** the caller should retry opening the read transaction from the
  57858. ** beginning (including attempting to map the *-shm file).
  57859. **
  57860. ** If an error occurs, an SQLite error code is returned.
  57861. */
  57862. static int walBeginShmUnreliable(Wal *pWal, int *pChanged){
  57863. i64 szWal; /* Size of wal file on disk in bytes */
  57864. i64 iOffset; /* Current offset when reading wal file */
  57865. u8 aBuf[WAL_HDRSIZE]; /* Buffer to load WAL header into */
  57866. u8 *aFrame = 0; /* Malloc'd buffer to load entire frame */
  57867. int szFrame; /* Number of bytes in buffer aFrame[] */
  57868. u8 *aData; /* Pointer to data part of aFrame buffer */
  57869. volatile void *pDummy; /* Dummy argument for xShmMap */
  57870. int rc; /* Return code */
  57871. u32 aSaveCksum[2]; /* Saved copy of pWal->hdr.aFrameCksum */
  57872. assert( pWal->bShmUnreliable );
  57873. assert( pWal->readOnly & WAL_SHM_RDONLY );
  57874. assert( pWal->nWiData>0 && pWal->apWiData[0] );
  57875. /* Take WAL_READ_LOCK(0). This has the effect of preventing any
  57876. ** writers from running a checkpoint, but does not stop them
  57877. ** from running recovery. */
  57878. rc = walLockShared(pWal, WAL_READ_LOCK(0));
  57879. if( rc!=SQLITE_OK ){
  57880. if( rc==SQLITE_BUSY ) rc = WAL_RETRY;
  57881. goto begin_unreliable_shm_out;
  57882. }
  57883. pWal->readLock = 0;
  57884. /* Check to see if a separate writer has attached to the shared-memory area,
  57885. ** thus making the shared-memory "reliable" again. Do this by invoking
  57886. ** the xShmMap() routine of the VFS and looking to see if the return
  57887. ** is SQLITE_READONLY instead of SQLITE_READONLY_CANTINIT.
  57888. **
  57889. ** If the shared-memory is now "reliable" return WAL_RETRY, which will
  57890. ** cause the heap-memory WAL-index to be discarded and the actual
  57891. ** shared memory to be used in its place.
  57892. **
  57893. ** This step is important because, even though this connection is holding
  57894. ** the WAL_READ_LOCK(0) which prevents a checkpoint, a writer might
  57895. ** have already checkpointed the WAL file and, while the current
  57896. ** is active, wrap the WAL and start overwriting frames that this
  57897. ** process wants to use.
  57898. **
  57899. ** Once sqlite3OsShmMap() has been called for an sqlite3_file and has
  57900. ** returned any SQLITE_READONLY value, it must return only SQLITE_READONLY
  57901. ** or SQLITE_READONLY_CANTINIT or some error for all subsequent invocations,
  57902. ** even if some external agent does a "chmod" to make the shared-memory
  57903. ** writable by us, until sqlite3OsShmUnmap() has been called.
  57904. ** This is a requirement on the VFS implementation.
  57905. */
  57906. rc = sqlite3OsShmMap(pWal->pDbFd, 0, WALINDEX_PGSZ, 0, &pDummy);
  57907. assert( rc!=SQLITE_OK ); /* SQLITE_OK not possible for read-only connection */
  57908. if( rc!=SQLITE_READONLY_CANTINIT ){
  57909. rc = (rc==SQLITE_READONLY ? WAL_RETRY : rc);
  57910. goto begin_unreliable_shm_out;
  57911. }
  57912. /* We reach this point only if the real shared-memory is still unreliable.
  57913. ** Assume the in-memory WAL-index substitute is correct and load it
  57914. ** into pWal->hdr.
  57915. */
  57916. memcpy(&pWal->hdr, (void*)walIndexHdr(pWal), sizeof(WalIndexHdr));
  57917. /* Make sure some writer hasn't come in and changed the WAL file out
  57918. ** from under us, then disconnected, while we were not looking.
  57919. */
  57920. rc = sqlite3OsFileSize(pWal->pWalFd, &szWal);
  57921. if( rc!=SQLITE_OK ){
  57922. goto begin_unreliable_shm_out;
  57923. }
  57924. if( szWal<WAL_HDRSIZE ){
  57925. /* If the wal file is too small to contain a wal-header and the
  57926. ** wal-index header has mxFrame==0, then it must be safe to proceed
  57927. ** reading the database file only. However, the page cache cannot
  57928. ** be trusted, as a read/write connection may have connected, written
  57929. ** the db, run a checkpoint, truncated the wal file and disconnected
  57930. ** since this client's last read transaction. */
  57931. *pChanged = 1;
  57932. rc = (pWal->hdr.mxFrame==0 ? SQLITE_OK : WAL_RETRY);
  57933. goto begin_unreliable_shm_out;
  57934. }
  57935. /* Check the salt keys at the start of the wal file still match. */
  57936. rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
  57937. if( rc!=SQLITE_OK ){
  57938. goto begin_unreliable_shm_out;
  57939. }
  57940. if( memcmp(&pWal->hdr.aSalt, &aBuf[16], 8) ){
  57941. /* Some writer has wrapped the WAL file while we were not looking.
  57942. ** Return WAL_RETRY which will cause the in-memory WAL-index to be
  57943. ** rebuilt. */
  57944. rc = WAL_RETRY;
  57945. goto begin_unreliable_shm_out;
  57946. }
  57947. /* Allocate a buffer to read frames into */
  57948. szFrame = pWal->hdr.szPage + WAL_FRAME_HDRSIZE;
  57949. aFrame = (u8 *)sqlite3_malloc64(szFrame);
  57950. if( aFrame==0 ){
  57951. rc = SQLITE_NOMEM_BKPT;
  57952. goto begin_unreliable_shm_out;
  57953. }
  57954. aData = &aFrame[WAL_FRAME_HDRSIZE];
  57955. /* Check to see if a complete transaction has been appended to the
  57956. ** wal file since the heap-memory wal-index was created. If so, the
  57957. ** heap-memory wal-index is discarded and WAL_RETRY returned to
  57958. ** the caller. */
  57959. aSaveCksum[0] = pWal->hdr.aFrameCksum[0];
  57960. aSaveCksum[1] = pWal->hdr.aFrameCksum[1];
  57961. for(iOffset=walFrameOffset(pWal->hdr.mxFrame+1, pWal->hdr.szPage);
  57962. iOffset+szFrame<=szWal;
  57963. iOffset+=szFrame
  57964. ){
  57965. u32 pgno; /* Database page number for frame */
  57966. u32 nTruncate; /* dbsize field from frame header */
  57967. /* Read and decode the next log frame. */
  57968. rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
  57969. if( rc!=SQLITE_OK ) break;
  57970. if( !walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame) ) break;
  57971. /* If nTruncate is non-zero, then a complete transaction has been
  57972. ** appended to this wal file. Set rc to WAL_RETRY and break out of
  57973. ** the loop. */
  57974. if( nTruncate ){
  57975. rc = WAL_RETRY;
  57976. break;
  57977. }
  57978. }
  57979. pWal->hdr.aFrameCksum[0] = aSaveCksum[0];
  57980. pWal->hdr.aFrameCksum[1] = aSaveCksum[1];
  57981. begin_unreliable_shm_out:
  57982. sqlite3_free(aFrame);
  57983. if( rc!=SQLITE_OK ){
  57984. int i;
  57985. for(i=0; i<pWal->nWiData; i++){
  57986. sqlite3_free((void*)pWal->apWiData[i]);
  57987. pWal->apWiData[i] = 0;
  57988. }
  57989. pWal->bShmUnreliable = 0;
  57990. sqlite3WalEndReadTransaction(pWal);
  57991. *pChanged = 1;
  57992. }
  57993. return rc;
  57994. }
  57995. /*
  57996. ** Attempt to start a read transaction. This might fail due to a race or
  57997. ** other transient condition. When that happens, it returns WAL_RETRY to
  57998. ** indicate to the caller that it is safe to retry immediately.
  57999. **
  58000. ** On success return SQLITE_OK. On a permanent failure (such an
  58001. ** I/O error or an SQLITE_BUSY because another process is running
  58002. ** recovery) return a positive error code.
  58003. **
  58004. ** The useWal parameter is true to force the use of the WAL and disable
  58005. ** the case where the WAL is bypassed because it has been completely
  58006. ** checkpointed. If useWal==0 then this routine calls walIndexReadHdr()
  58007. ** to make a copy of the wal-index header into pWal->hdr. If the
  58008. ** wal-index header has changed, *pChanged is set to 1 (as an indication
  58009. ** to the caller that the local page cache is obsolete and needs to be
  58010. ** flushed.) When useWal==1, the wal-index header is assumed to already
  58011. ** be loaded and the pChanged parameter is unused.
  58012. **
  58013. ** The caller must set the cnt parameter to the number of prior calls to
  58014. ** this routine during the current read attempt that returned WAL_RETRY.
  58015. ** This routine will start taking more aggressive measures to clear the
  58016. ** race conditions after multiple WAL_RETRY returns, and after an excessive
  58017. ** number of errors will ultimately return SQLITE_PROTOCOL. The
  58018. ** SQLITE_PROTOCOL return indicates that some other process has gone rogue
  58019. ** and is not honoring the locking protocol. There is a vanishingly small
  58020. ** chance that SQLITE_PROTOCOL could be returned because of a run of really
  58021. ** bad luck when there is lots of contention for the wal-index, but that
  58022. ** possibility is so small that it can be safely neglected, we believe.
  58023. **
  58024. ** On success, this routine obtains a read lock on
  58025. ** WAL_READ_LOCK(pWal->readLock). The pWal->readLock integer is
  58026. ** in the range 0 <= pWal->readLock < WAL_NREADER. If pWal->readLock==(-1)
  58027. ** that means the Wal does not hold any read lock. The reader must not
  58028. ** access any database page that is modified by a WAL frame up to and
  58029. ** including frame number aReadMark[pWal->readLock]. The reader will
  58030. ** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0
  58031. ** Or if pWal->readLock==0, then the reader will ignore the WAL
  58032. ** completely and get all content directly from the database file.
  58033. ** If the useWal parameter is 1 then the WAL will never be ignored and
  58034. ** this routine will always set pWal->readLock>0 on success.
  58035. ** When the read transaction is completed, the caller must release the
  58036. ** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1.
  58037. **
  58038. ** This routine uses the nBackfill and aReadMark[] fields of the header
  58039. ** to select a particular WAL_READ_LOCK() that strives to let the
  58040. ** checkpoint process do as much work as possible. This routine might
  58041. ** update values of the aReadMark[] array in the header, but if it does
  58042. ** so it takes care to hold an exclusive lock on the corresponding
  58043. ** WAL_READ_LOCK() while changing values.
  58044. */
  58045. static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){
  58046. volatile WalCkptInfo *pInfo; /* Checkpoint information in wal-index */
  58047. u32 mxReadMark; /* Largest aReadMark[] value */
  58048. int mxI; /* Index of largest aReadMark[] value */
  58049. int i; /* Loop counter */
  58050. int rc = SQLITE_OK; /* Return code */
  58051. u32 mxFrame; /* Wal frame to lock to */
  58052. assert( pWal->readLock<0 ); /* Not currently locked */
  58053. /* useWal may only be set for read/write connections */
  58054. assert( (pWal->readOnly & WAL_SHM_RDONLY)==0 || useWal==0 );
  58055. /* Take steps to avoid spinning forever if there is a protocol error.
  58056. **
  58057. ** Circumstances that cause a RETRY should only last for the briefest
  58058. ** instances of time. No I/O or other system calls are done while the
  58059. ** locks are held, so the locks should not be held for very long. But
  58060. ** if we are unlucky, another process that is holding a lock might get
  58061. ** paged out or take a page-fault that is time-consuming to resolve,
  58062. ** during the few nanoseconds that it is holding the lock. In that case,
  58063. ** it might take longer than normal for the lock to free.
  58064. **
  58065. ** After 5 RETRYs, we begin calling sqlite3OsSleep(). The first few
  58066. ** calls to sqlite3OsSleep() have a delay of 1 microsecond. Really this
  58067. ** is more of a scheduler yield than an actual delay. But on the 10th
  58068. ** an subsequent retries, the delays start becoming longer and longer,
  58069. ** so that on the 100th (and last) RETRY we delay for 323 milliseconds.
  58070. ** The total delay time before giving up is less than 10 seconds.
  58071. */
  58072. if( cnt>5 ){
  58073. int nDelay = 1; /* Pause time in microseconds */
  58074. if( cnt>100 ){
  58075. VVA_ONLY( pWal->lockError = 1; )
  58076. return SQLITE_PROTOCOL;
  58077. }
  58078. if( cnt>=10 ) nDelay = (cnt-9)*(cnt-9)*39;
  58079. sqlite3OsSleep(pWal->pVfs, nDelay);
  58080. }
  58081. if( !useWal ){
  58082. assert( rc==SQLITE_OK );
  58083. if( pWal->bShmUnreliable==0 ){
  58084. rc = walIndexReadHdr(pWal, pChanged);
  58085. }
  58086. if( rc==SQLITE_BUSY ){
  58087. /* If there is not a recovery running in another thread or process
  58088. ** then convert BUSY errors to WAL_RETRY. If recovery is known to
  58089. ** be running, convert BUSY to BUSY_RECOVERY. There is a race here
  58090. ** which might cause WAL_RETRY to be returned even if BUSY_RECOVERY
  58091. ** would be technically correct. But the race is benign since with
  58092. ** WAL_RETRY this routine will be called again and will probably be
  58093. ** right on the second iteration.
  58094. */
  58095. if( pWal->apWiData[0]==0 ){
  58096. /* This branch is taken when the xShmMap() method returns SQLITE_BUSY.
  58097. ** We assume this is a transient condition, so return WAL_RETRY. The
  58098. ** xShmMap() implementation used by the default unix and win32 VFS
  58099. ** modules may return SQLITE_BUSY due to a race condition in the
  58100. ** code that determines whether or not the shared-memory region
  58101. ** must be zeroed before the requested page is returned.
  58102. */
  58103. rc = WAL_RETRY;
  58104. }else if( SQLITE_OK==(rc = walLockShared(pWal, WAL_RECOVER_LOCK)) ){
  58105. walUnlockShared(pWal, WAL_RECOVER_LOCK);
  58106. rc = WAL_RETRY;
  58107. }else if( rc==SQLITE_BUSY ){
  58108. rc = SQLITE_BUSY_RECOVERY;
  58109. }
  58110. }
  58111. if( rc!=SQLITE_OK ){
  58112. return rc;
  58113. }
  58114. else if( pWal->bShmUnreliable ){
  58115. return walBeginShmUnreliable(pWal, pChanged);
  58116. }
  58117. }
  58118. assert( pWal->nWiData>0 );
  58119. assert( pWal->apWiData[0]!=0 );
  58120. pInfo = walCkptInfo(pWal);
  58121. if( !useWal && AtomicLoad(&pInfo->nBackfill)==pWal->hdr.mxFrame
  58122. #ifdef SQLITE_ENABLE_SNAPSHOT
  58123. && (pWal->pSnapshot==0 || pWal->hdr.mxFrame==0)
  58124. #endif
  58125. ){
  58126. /* The WAL has been completely backfilled (or it is empty).
  58127. ** and can be safely ignored.
  58128. */
  58129. rc = walLockShared(pWal, WAL_READ_LOCK(0));
  58130. walShmBarrier(pWal);
  58131. if( rc==SQLITE_OK ){
  58132. if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){
  58133. /* It is not safe to allow the reader to continue here if frames
  58134. ** may have been appended to the log before READ_LOCK(0) was obtained.
  58135. ** When holding READ_LOCK(0), the reader ignores the entire log file,
  58136. ** which implies that the database file contains a trustworthy
  58137. ** snapshot. Since holding READ_LOCK(0) prevents a checkpoint from
  58138. ** happening, this is usually correct.
  58139. **
  58140. ** However, if frames have been appended to the log (or if the log
  58141. ** is wrapped and written for that matter) before the READ_LOCK(0)
  58142. ** is obtained, that is not necessarily true. A checkpointer may
  58143. ** have started to backfill the appended frames but crashed before
  58144. ** it finished. Leaving a corrupt image in the database file.
  58145. */
  58146. walUnlockShared(pWal, WAL_READ_LOCK(0));
  58147. return WAL_RETRY;
  58148. }
  58149. pWal->readLock = 0;
  58150. return SQLITE_OK;
  58151. }else if( rc!=SQLITE_BUSY ){
  58152. return rc;
  58153. }
  58154. }
  58155. /* If we get this far, it means that the reader will want to use
  58156. ** the WAL to get at content from recent commits. The job now is
  58157. ** to select one of the aReadMark[] entries that is closest to
  58158. ** but not exceeding pWal->hdr.mxFrame and lock that entry.
  58159. */
  58160. mxReadMark = 0;
  58161. mxI = 0;
  58162. mxFrame = pWal->hdr.mxFrame;
  58163. #ifdef SQLITE_ENABLE_SNAPSHOT
  58164. if( pWal->pSnapshot && pWal->pSnapshot->mxFrame<mxFrame ){
  58165. mxFrame = pWal->pSnapshot->mxFrame;
  58166. }
  58167. #endif
  58168. for(i=1; i<WAL_NREADER; i++){
  58169. u32 thisMark = AtomicLoad(pInfo->aReadMark+i);
  58170. if( mxReadMark<=thisMark && thisMark<=mxFrame ){
  58171. assert( thisMark!=READMARK_NOT_USED );
  58172. mxReadMark = thisMark;
  58173. mxI = i;
  58174. }
  58175. }
  58176. if( (pWal->readOnly & WAL_SHM_RDONLY)==0
  58177. && (mxReadMark<mxFrame || mxI==0)
  58178. ){
  58179. for(i=1; i<WAL_NREADER; i++){
  58180. rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
  58181. if( rc==SQLITE_OK ){
  58182. AtomicStore(pInfo->aReadMark+i,mxFrame);
  58183. mxReadMark = mxFrame;
  58184. mxI = i;
  58185. walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
  58186. break;
  58187. }else if( rc!=SQLITE_BUSY ){
  58188. return rc;
  58189. }
  58190. }
  58191. }
  58192. if( mxI==0 ){
  58193. assert( rc==SQLITE_BUSY || (pWal->readOnly & WAL_SHM_RDONLY)!=0 );
  58194. return rc==SQLITE_BUSY ? WAL_RETRY : SQLITE_READONLY_CANTINIT;
  58195. }
  58196. rc = walLockShared(pWal, WAL_READ_LOCK(mxI));
  58197. if( rc ){
  58198. return rc==SQLITE_BUSY ? WAL_RETRY : rc;
  58199. }
  58200. /* Now that the read-lock has been obtained, check that neither the
  58201. ** value in the aReadMark[] array or the contents of the wal-index
  58202. ** header have changed.
  58203. **
  58204. ** It is necessary to check that the wal-index header did not change
  58205. ** between the time it was read and when the shared-lock was obtained
  58206. ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility
  58207. ** that the log file may have been wrapped by a writer, or that frames
  58208. ** that occur later in the log than pWal->hdr.mxFrame may have been
  58209. ** copied into the database by a checkpointer. If either of these things
  58210. ** happened, then reading the database with the current value of
  58211. ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry
  58212. ** instead.
  58213. **
  58214. ** Before checking that the live wal-index header has not changed
  58215. ** since it was read, set Wal.minFrame to the first frame in the wal
  58216. ** file that has not yet been checkpointed. This client will not need
  58217. ** to read any frames earlier than minFrame from the wal file - they
  58218. ** can be safely read directly from the database file.
  58219. **
  58220. ** Because a ShmBarrier() call is made between taking the copy of
  58221. ** nBackfill and checking that the wal-header in shared-memory still
  58222. ** matches the one cached in pWal->hdr, it is guaranteed that the
  58223. ** checkpointer that set nBackfill was not working with a wal-index
  58224. ** header newer than that cached in pWal->hdr. If it were, that could
  58225. ** cause a problem. The checkpointer could omit to checkpoint
  58226. ** a version of page X that lies before pWal->minFrame (call that version
  58227. ** A) on the basis that there is a newer version (version B) of the same
  58228. ** page later in the wal file. But if version B happens to like past
  58229. ** frame pWal->hdr.mxFrame - then the client would incorrectly assume
  58230. ** that it can read version A from the database file. However, since
  58231. ** we can guarantee that the checkpointer that set nBackfill could not
  58232. ** see any pages past pWal->hdr.mxFrame, this problem does not come up.
  58233. */
  58234. pWal->minFrame = AtomicLoad(&pInfo->nBackfill)+1;
  58235. walShmBarrier(pWal);
  58236. if( AtomicLoad(pInfo->aReadMark+mxI)!=mxReadMark
  58237. || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr))
  58238. ){
  58239. walUnlockShared(pWal, WAL_READ_LOCK(mxI));
  58240. return WAL_RETRY;
  58241. }else{
  58242. assert( mxReadMark<=pWal->hdr.mxFrame );
  58243. pWal->readLock = (i16)mxI;
  58244. }
  58245. return rc;
  58246. }
  58247. #ifdef SQLITE_ENABLE_SNAPSHOT
  58248. /*
  58249. ** Attempt to reduce the value of the WalCkptInfo.nBackfillAttempted
  58250. ** variable so that older snapshots can be accessed. To do this, loop
  58251. ** through all wal frames from nBackfillAttempted to (nBackfill+1),
  58252. ** comparing their content to the corresponding page with the database
  58253. ** file, if any. Set nBackfillAttempted to the frame number of the
  58254. ** first frame for which the wal file content matches the db file.
  58255. **
  58256. ** This is only really safe if the file-system is such that any page
  58257. ** writes made by earlier checkpointers were atomic operations, which
  58258. ** is not always true. It is also possible that nBackfillAttempted
  58259. ** may be left set to a value larger than expected, if a wal frame
  58260. ** contains content that duplicate of an earlier version of the same
  58261. ** page.
  58262. **
  58263. ** SQLITE_OK is returned if successful, or an SQLite error code if an
  58264. ** error occurs. It is not an error if nBackfillAttempted cannot be
  58265. ** decreased at all.
  58266. */
  58267. SQLITE_PRIVATE int sqlite3WalSnapshotRecover(Wal *pWal){
  58268. int rc;
  58269. assert( pWal->readLock>=0 );
  58270. rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
  58271. if( rc==SQLITE_OK ){
  58272. volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
  58273. int szPage = (int)pWal->szPage;
  58274. i64 szDb; /* Size of db file in bytes */
  58275. rc = sqlite3OsFileSize(pWal->pDbFd, &szDb);
  58276. if( rc==SQLITE_OK ){
  58277. void *pBuf1 = sqlite3_malloc(szPage);
  58278. void *pBuf2 = sqlite3_malloc(szPage);
  58279. if( pBuf1==0 || pBuf2==0 ){
  58280. rc = SQLITE_NOMEM;
  58281. }else{
  58282. u32 i = pInfo->nBackfillAttempted;
  58283. for(i=pInfo->nBackfillAttempted; i>AtomicLoad(&pInfo->nBackfill); i--){
  58284. WalHashLoc sLoc; /* Hash table location */
  58285. u32 pgno; /* Page number in db file */
  58286. i64 iDbOff; /* Offset of db file entry */
  58287. i64 iWalOff; /* Offset of wal file entry */
  58288. rc = walHashGet(pWal, walFramePage(i), &sLoc);
  58289. if( rc!=SQLITE_OK ) break;
  58290. pgno = sLoc.aPgno[i-sLoc.iZero];
  58291. iDbOff = (i64)(pgno-1) * szPage;
  58292. if( iDbOff+szPage<=szDb ){
  58293. iWalOff = walFrameOffset(i, szPage) + WAL_FRAME_HDRSIZE;
  58294. rc = sqlite3OsRead(pWal->pWalFd, pBuf1, szPage, iWalOff);
  58295. if( rc==SQLITE_OK ){
  58296. rc = sqlite3OsRead(pWal->pDbFd, pBuf2, szPage, iDbOff);
  58297. }
  58298. if( rc!=SQLITE_OK || 0==memcmp(pBuf1, pBuf2, szPage) ){
  58299. break;
  58300. }
  58301. }
  58302. pInfo->nBackfillAttempted = i-1;
  58303. }
  58304. }
  58305. sqlite3_free(pBuf1);
  58306. sqlite3_free(pBuf2);
  58307. }
  58308. walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
  58309. }
  58310. return rc;
  58311. }
  58312. #endif /* SQLITE_ENABLE_SNAPSHOT */
  58313. /*
  58314. ** Begin a read transaction on the database.
  58315. **
  58316. ** This routine used to be called sqlite3OpenSnapshot() and with good reason:
  58317. ** it takes a snapshot of the state of the WAL and wal-index for the current
  58318. ** instant in time. The current thread will continue to use this snapshot.
  58319. ** Other threads might append new content to the WAL and wal-index but
  58320. ** that extra content is ignored by the current thread.
  58321. **
  58322. ** If the database contents have changes since the previous read
  58323. ** transaction, then *pChanged is set to 1 before returning. The
  58324. ** Pager layer will use this to know that its cache is stale and
  58325. ** needs to be flushed.
  58326. */
  58327. SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){
  58328. int rc; /* Return code */
  58329. int cnt = 0; /* Number of TryBeginRead attempts */
  58330. #ifdef SQLITE_ENABLE_SNAPSHOT
  58331. int bChanged = 0;
  58332. WalIndexHdr *pSnapshot = pWal->pSnapshot;
  58333. #endif
  58334. assert( pWal->ckptLock==0 );
  58335. #ifdef SQLITE_ENABLE_SNAPSHOT
  58336. if( pSnapshot ){
  58337. if( memcmp(pSnapshot, &pWal->hdr, sizeof(WalIndexHdr))!=0 ){
  58338. bChanged = 1;
  58339. }
  58340. /* It is possible that there is a checkpointer thread running
  58341. ** concurrent with this code. If this is the case, it may be that the
  58342. ** checkpointer has already determined that it will checkpoint
  58343. ** snapshot X, where X is later in the wal file than pSnapshot, but
  58344. ** has not yet set the pInfo->nBackfillAttempted variable to indicate
  58345. ** its intent. To avoid the race condition this leads to, ensure that
  58346. ** there is no checkpointer process by taking a shared CKPT lock
  58347. ** before checking pInfo->nBackfillAttempted. */
  58348. (void)walEnableBlocking(pWal);
  58349. rc = walLockShared(pWal, WAL_CKPT_LOCK);
  58350. walDisableBlocking(pWal);
  58351. if( rc!=SQLITE_OK ){
  58352. return rc;
  58353. }
  58354. pWal->ckptLock = 1;
  58355. }
  58356. #endif
  58357. do{
  58358. rc = walTryBeginRead(pWal, pChanged, 0, ++cnt);
  58359. }while( rc==WAL_RETRY );
  58360. testcase( (rc&0xff)==SQLITE_BUSY );
  58361. testcase( (rc&0xff)==SQLITE_IOERR );
  58362. testcase( rc==SQLITE_PROTOCOL );
  58363. testcase( rc==SQLITE_OK );
  58364. #ifdef SQLITE_ENABLE_SNAPSHOT
  58365. if( rc==SQLITE_OK ){
  58366. if( pSnapshot && memcmp(pSnapshot, &pWal->hdr, sizeof(WalIndexHdr))!=0 ){
  58367. /* At this point the client has a lock on an aReadMark[] slot holding
  58368. ** a value equal to or smaller than pSnapshot->mxFrame, but pWal->hdr
  58369. ** is populated with the wal-index header corresponding to the head
  58370. ** of the wal file. Verify that pSnapshot is still valid before
  58371. ** continuing. Reasons why pSnapshot might no longer be valid:
  58372. **
  58373. ** (1) The WAL file has been reset since the snapshot was taken.
  58374. ** In this case, the salt will have changed.
  58375. **
  58376. ** (2) A checkpoint as been attempted that wrote frames past
  58377. ** pSnapshot->mxFrame into the database file. Note that the
  58378. ** checkpoint need not have completed for this to cause problems.
  58379. */
  58380. volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
  58381. assert( pWal->readLock>0 || pWal->hdr.mxFrame==0 );
  58382. assert( pInfo->aReadMark[pWal->readLock]<=pSnapshot->mxFrame );
  58383. /* Check that the wal file has not been wrapped. Assuming that it has
  58384. ** not, also check that no checkpointer has attempted to checkpoint any
  58385. ** frames beyond pSnapshot->mxFrame. If either of these conditions are
  58386. ** true, return SQLITE_ERROR_SNAPSHOT. Otherwise, overwrite pWal->hdr
  58387. ** with *pSnapshot and set *pChanged as appropriate for opening the
  58388. ** snapshot. */
  58389. if( !memcmp(pSnapshot->aSalt, pWal->hdr.aSalt, sizeof(pWal->hdr.aSalt))
  58390. && pSnapshot->mxFrame>=pInfo->nBackfillAttempted
  58391. ){
  58392. assert( pWal->readLock>0 );
  58393. memcpy(&pWal->hdr, pSnapshot, sizeof(WalIndexHdr));
  58394. *pChanged = bChanged;
  58395. }else{
  58396. rc = SQLITE_ERROR_SNAPSHOT;
  58397. }
  58398. /* A client using a non-current snapshot may not ignore any frames
  58399. ** from the start of the wal file. This is because, for a system
  58400. ** where (minFrame < iSnapshot < maxFrame), a checkpointer may
  58401. ** have omitted to checkpoint a frame earlier than minFrame in
  58402. ** the file because there exists a frame after iSnapshot that
  58403. ** is the same database page. */
  58404. pWal->minFrame = 1;
  58405. if( rc!=SQLITE_OK ){
  58406. sqlite3WalEndReadTransaction(pWal);
  58407. }
  58408. }
  58409. }
  58410. /* Release the shared CKPT lock obtained above. */
  58411. if( pWal->ckptLock ){
  58412. assert( pSnapshot );
  58413. walUnlockShared(pWal, WAL_CKPT_LOCK);
  58414. pWal->ckptLock = 0;
  58415. }
  58416. #endif
  58417. return rc;
  58418. }
  58419. /*
  58420. ** Finish with a read transaction. All this does is release the
  58421. ** read-lock.
  58422. */
  58423. SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal){
  58424. sqlite3WalEndWriteTransaction(pWal);
  58425. if( pWal->readLock>=0 ){
  58426. walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
  58427. pWal->readLock = -1;
  58428. }
  58429. }
  58430. /*
  58431. ** Search the wal file for page pgno. If found, set *piRead to the frame that
  58432. ** contains the page. Otherwise, if pgno is not in the wal file, set *piRead
  58433. ** to zero.
  58434. **
  58435. ** Return SQLITE_OK if successful, or an error code if an error occurs. If an
  58436. ** error does occur, the final value of *piRead is undefined.
  58437. */
  58438. SQLITE_PRIVATE int sqlite3WalFindFrame(
  58439. Wal *pWal, /* WAL handle */
  58440. Pgno pgno, /* Database page number to read data for */
  58441. u32 *piRead /* OUT: Frame number (or zero) */
  58442. ){
  58443. u32 iRead = 0; /* If !=0, WAL frame to return data from */
  58444. u32 iLast = pWal->hdr.mxFrame; /* Last page in WAL for this reader */
  58445. int iHash; /* Used to loop through N hash tables */
  58446. int iMinHash;
  58447. /* This routine is only be called from within a read transaction. */
  58448. assert( pWal->readLock>=0 || pWal->lockError );
  58449. /* If the "last page" field of the wal-index header snapshot is 0, then
  58450. ** no data will be read from the wal under any circumstances. Return early
  58451. ** in this case as an optimization. Likewise, if pWal->readLock==0,
  58452. ** then the WAL is ignored by the reader so return early, as if the
  58453. ** WAL were empty.
  58454. */
  58455. if( iLast==0 || (pWal->readLock==0 && pWal->bShmUnreliable==0) ){
  58456. *piRead = 0;
  58457. return SQLITE_OK;
  58458. }
  58459. /* Search the hash table or tables for an entry matching page number
  58460. ** pgno. Each iteration of the following for() loop searches one
  58461. ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames).
  58462. **
  58463. ** This code might run concurrently to the code in walIndexAppend()
  58464. ** that adds entries to the wal-index (and possibly to this hash
  58465. ** table). This means the value just read from the hash
  58466. ** slot (aHash[iKey]) may have been added before or after the
  58467. ** current read transaction was opened. Values added after the
  58468. ** read transaction was opened may have been written incorrectly -
  58469. ** i.e. these slots may contain garbage data. However, we assume
  58470. ** that any slots written before the current read transaction was
  58471. ** opened remain unmodified.
  58472. **
  58473. ** For the reasons above, the if(...) condition featured in the inner
  58474. ** loop of the following block is more stringent that would be required
  58475. ** if we had exclusive access to the hash-table:
  58476. **
  58477. ** (aPgno[iFrame]==pgno):
  58478. ** This condition filters out normal hash-table collisions.
  58479. **
  58480. ** (iFrame<=iLast):
  58481. ** This condition filters out entries that were added to the hash
  58482. ** table after the current read-transaction had started.
  58483. */
  58484. iMinHash = walFramePage(pWal->minFrame);
  58485. for(iHash=walFramePage(iLast); iHash>=iMinHash; iHash--){
  58486. WalHashLoc sLoc; /* Hash table location */
  58487. int iKey; /* Hash slot index */
  58488. int nCollide; /* Number of hash collisions remaining */
  58489. int rc; /* Error code */
  58490. u32 iH;
  58491. rc = walHashGet(pWal, iHash, &sLoc);
  58492. if( rc!=SQLITE_OK ){
  58493. return rc;
  58494. }
  58495. nCollide = HASHTABLE_NSLOT;
  58496. iKey = walHash(pgno);
  58497. while( (iH = AtomicLoad(&sLoc.aHash[iKey]))!=0 ){
  58498. u32 iFrame = iH + sLoc.iZero;
  58499. if( iFrame<=iLast && iFrame>=pWal->minFrame && sLoc.aPgno[iH]==pgno ){
  58500. assert( iFrame>iRead || CORRUPT_DB );
  58501. iRead = iFrame;
  58502. }
  58503. if( (nCollide--)==0 ){
  58504. return SQLITE_CORRUPT_BKPT;
  58505. }
  58506. iKey = walNextHash(iKey);
  58507. }
  58508. if( iRead ) break;
  58509. }
  58510. #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
  58511. /* If expensive assert() statements are available, do a linear search
  58512. ** of the wal-index file content. Make sure the results agree with the
  58513. ** result obtained using the hash indexes above. */
  58514. {
  58515. u32 iRead2 = 0;
  58516. u32 iTest;
  58517. assert( pWal->bShmUnreliable || pWal->minFrame>0 );
  58518. for(iTest=iLast; iTest>=pWal->minFrame && iTest>0; iTest--){
  58519. if( walFramePgno(pWal, iTest)==pgno ){
  58520. iRead2 = iTest;
  58521. break;
  58522. }
  58523. }
  58524. assert( iRead==iRead2 );
  58525. }
  58526. #endif
  58527. *piRead = iRead;
  58528. return SQLITE_OK;
  58529. }
  58530. /*
  58531. ** Read the contents of frame iRead from the wal file into buffer pOut
  58532. ** (which is nOut bytes in size). Return SQLITE_OK if successful, or an
  58533. ** error code otherwise.
  58534. */
  58535. SQLITE_PRIVATE int sqlite3WalReadFrame(
  58536. Wal *pWal, /* WAL handle */
  58537. u32 iRead, /* Frame to read */
  58538. int nOut, /* Size of buffer pOut in bytes */
  58539. u8 *pOut /* Buffer to write page data to */
  58540. ){
  58541. int sz;
  58542. i64 iOffset;
  58543. sz = pWal->hdr.szPage;
  58544. sz = (sz&0xfe00) + ((sz&0x0001)<<16);
  58545. testcase( sz<=32768 );
  58546. testcase( sz>=65536 );
  58547. iOffset = walFrameOffset(iRead, sz) + WAL_FRAME_HDRSIZE;
  58548. /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
  58549. return sqlite3OsRead(pWal->pWalFd, pOut, (nOut>sz ? sz : nOut), iOffset);
  58550. }
  58551. /*
  58552. ** Return the size of the database in pages (or zero, if unknown).
  58553. */
  58554. SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal){
  58555. if( pWal && ALWAYS(pWal->readLock>=0) ){
  58556. return pWal->hdr.nPage;
  58557. }
  58558. return 0;
  58559. }
  58560. /*
  58561. ** This function starts a write transaction on the WAL.
  58562. **
  58563. ** A read transaction must have already been started by a prior call
  58564. ** to sqlite3WalBeginReadTransaction().
  58565. **
  58566. ** If another thread or process has written into the database since
  58567. ** the read transaction was started, then it is not possible for this
  58568. ** thread to write as doing so would cause a fork. So this routine
  58569. ** returns SQLITE_BUSY in that case and no write transaction is started.
  58570. **
  58571. ** There can only be a single writer active at a time.
  58572. */
  58573. SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal){
  58574. int rc;
  58575. #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
  58576. /* If the write-lock is already held, then it was obtained before the
  58577. ** read-transaction was even opened, making this call a no-op.
  58578. ** Return early. */
  58579. if( pWal->writeLock ){
  58580. assert( !memcmp(&pWal->hdr,(void *)walIndexHdr(pWal),sizeof(WalIndexHdr)) );
  58581. return SQLITE_OK;
  58582. }
  58583. #endif
  58584. /* Cannot start a write transaction without first holding a read
  58585. ** transaction. */
  58586. assert( pWal->readLock>=0 );
  58587. assert( pWal->writeLock==0 && pWal->iReCksum==0 );
  58588. if( pWal->readOnly ){
  58589. return SQLITE_READONLY;
  58590. }
  58591. /* Only one writer allowed at a time. Get the write lock. Return
  58592. ** SQLITE_BUSY if unable.
  58593. */
  58594. rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);
  58595. if( rc ){
  58596. return rc;
  58597. }
  58598. pWal->writeLock = 1;
  58599. /* If another connection has written to the database file since the
  58600. ** time the read transaction on this connection was started, then
  58601. ** the write is disallowed.
  58602. */
  58603. if( memcmp(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr))!=0 ){
  58604. walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
  58605. pWal->writeLock = 0;
  58606. rc = SQLITE_BUSY_SNAPSHOT;
  58607. }
  58608. return rc;
  58609. }
  58610. /*
  58611. ** End a write transaction. The commit has already been done. This
  58612. ** routine merely releases the lock.
  58613. */
  58614. SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal){
  58615. if( pWal->writeLock ){
  58616. walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
  58617. pWal->writeLock = 0;
  58618. pWal->iReCksum = 0;
  58619. pWal->truncateOnCommit = 0;
  58620. }
  58621. return SQLITE_OK;
  58622. }
  58623. /*
  58624. ** If any data has been written (but not committed) to the log file, this
  58625. ** function moves the write-pointer back to the start of the transaction.
  58626. **
  58627. ** Additionally, the callback function is invoked for each frame written
  58628. ** to the WAL since the start of the transaction. If the callback returns
  58629. ** other than SQLITE_OK, it is not invoked again and the error code is
  58630. ** returned to the caller.
  58631. **
  58632. ** Otherwise, if the callback function does not return an error, this
  58633. ** function returns SQLITE_OK.
  58634. */
  58635. SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){
  58636. int rc = SQLITE_OK;
  58637. if( ALWAYS(pWal->writeLock) ){
  58638. Pgno iMax = pWal->hdr.mxFrame;
  58639. Pgno iFrame;
  58640. /* Restore the clients cache of the wal-index header to the state it
  58641. ** was in before the client began writing to the database.
  58642. */
  58643. memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr));
  58644. for(iFrame=pWal->hdr.mxFrame+1;
  58645. ALWAYS(rc==SQLITE_OK) && iFrame<=iMax;
  58646. iFrame++
  58647. ){
  58648. /* This call cannot fail. Unless the page for which the page number
  58649. ** is passed as the second argument is (a) in the cache and
  58650. ** (b) has an outstanding reference, then xUndo is either a no-op
  58651. ** (if (a) is false) or simply expels the page from the cache (if (b)
  58652. ** is false).
  58653. **
  58654. ** If the upper layer is doing a rollback, it is guaranteed that there
  58655. ** are no outstanding references to any page other than page 1. And
  58656. ** page 1 is never written to the log until the transaction is
  58657. ** committed. As a result, the call to xUndo may not fail.
  58658. */
  58659. assert( walFramePgno(pWal, iFrame)!=1 );
  58660. rc = xUndo(pUndoCtx, walFramePgno(pWal, iFrame));
  58661. }
  58662. if( iMax!=pWal->hdr.mxFrame ) walCleanupHash(pWal);
  58663. }
  58664. return rc;
  58665. }
  58666. /*
  58667. ** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32
  58668. ** values. This function populates the array with values required to
  58669. ** "rollback" the write position of the WAL handle back to the current
  58670. ** point in the event of a savepoint rollback (via WalSavepointUndo()).
  58671. */
  58672. SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){
  58673. assert( pWal->writeLock );
  58674. aWalData[0] = pWal->hdr.mxFrame;
  58675. aWalData[1] = pWal->hdr.aFrameCksum[0];
  58676. aWalData[2] = pWal->hdr.aFrameCksum[1];
  58677. aWalData[3] = pWal->nCkpt;
  58678. }
  58679. /*
  58680. ** Move the write position of the WAL back to the point identified by
  58681. ** the values in the aWalData[] array. aWalData must point to an array
  58682. ** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated
  58683. ** by a call to WalSavepoint().
  58684. */
  58685. SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){
  58686. int rc = SQLITE_OK;
  58687. assert( pWal->writeLock );
  58688. assert( aWalData[3]!=pWal->nCkpt || aWalData[0]<=pWal->hdr.mxFrame );
  58689. if( aWalData[3]!=pWal->nCkpt ){
  58690. /* This savepoint was opened immediately after the write-transaction
  58691. ** was started. Right after that, the writer decided to wrap around
  58692. ** to the start of the log. Update the savepoint values to match.
  58693. */
  58694. aWalData[0] = 0;
  58695. aWalData[3] = pWal->nCkpt;
  58696. }
  58697. if( aWalData[0]<pWal->hdr.mxFrame ){
  58698. pWal->hdr.mxFrame = aWalData[0];
  58699. pWal->hdr.aFrameCksum[0] = aWalData[1];
  58700. pWal->hdr.aFrameCksum[1] = aWalData[2];
  58701. walCleanupHash(pWal);
  58702. }
  58703. return rc;
  58704. }
  58705. /*
  58706. ** This function is called just before writing a set of frames to the log
  58707. ** file (see sqlite3WalFrames()). It checks to see if, instead of appending
  58708. ** to the current log file, it is possible to overwrite the start of the
  58709. ** existing log file with the new frames (i.e. "reset" the log). If so,
  58710. ** it sets pWal->hdr.mxFrame to 0. Otherwise, pWal->hdr.mxFrame is left
  58711. ** unchanged.
  58712. **
  58713. ** SQLITE_OK is returned if no error is encountered (regardless of whether
  58714. ** or not pWal->hdr.mxFrame is modified). An SQLite error code is returned
  58715. ** if an error occurs.
  58716. */
  58717. static int walRestartLog(Wal *pWal){
  58718. int rc = SQLITE_OK;
  58719. int cnt;
  58720. if( pWal->readLock==0 ){
  58721. volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
  58722. assert( pInfo->nBackfill==pWal->hdr.mxFrame );
  58723. if( pInfo->nBackfill>0 ){
  58724. u32 salt1;
  58725. sqlite3_randomness(4, &salt1);
  58726. rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
  58727. if( rc==SQLITE_OK ){
  58728. /* If all readers are using WAL_READ_LOCK(0) (in other words if no
  58729. ** readers are currently using the WAL), then the transactions
  58730. ** frames will overwrite the start of the existing log. Update the
  58731. ** wal-index header to reflect this.
  58732. **
  58733. ** In theory it would be Ok to update the cache of the header only
  58734. ** at this point. But updating the actual wal-index header is also
  58735. ** safe and means there is no special case for sqlite3WalUndo()
  58736. ** to handle if this transaction is rolled back. */
  58737. walRestartHdr(pWal, salt1);
  58738. walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
  58739. }else if( rc!=SQLITE_BUSY ){
  58740. return rc;
  58741. }
  58742. }
  58743. walUnlockShared(pWal, WAL_READ_LOCK(0));
  58744. pWal->readLock = -1;
  58745. cnt = 0;
  58746. do{
  58747. int notUsed;
  58748. rc = walTryBeginRead(pWal, &notUsed, 1, ++cnt);
  58749. }while( rc==WAL_RETRY );
  58750. assert( (rc&0xff)!=SQLITE_BUSY ); /* BUSY not possible when useWal==1 */
  58751. testcase( (rc&0xff)==SQLITE_IOERR );
  58752. testcase( rc==SQLITE_PROTOCOL );
  58753. testcase( rc==SQLITE_OK );
  58754. }
  58755. return rc;
  58756. }
  58757. /*
  58758. ** Information about the current state of the WAL file and where
  58759. ** the next fsync should occur - passed from sqlite3WalFrames() into
  58760. ** walWriteToLog().
  58761. */
  58762. typedef struct WalWriter {
  58763. Wal *pWal; /* The complete WAL information */
  58764. sqlite3_file *pFd; /* The WAL file to which we write */
  58765. sqlite3_int64 iSyncPoint; /* Fsync at this offset */
  58766. int syncFlags; /* Flags for the fsync */
  58767. int szPage; /* Size of one page */
  58768. } WalWriter;
  58769. /*
  58770. ** Write iAmt bytes of content into the WAL file beginning at iOffset.
  58771. ** Do a sync when crossing the p->iSyncPoint boundary.
  58772. **
  58773. ** In other words, if iSyncPoint is in between iOffset and iOffset+iAmt,
  58774. ** first write the part before iSyncPoint, then sync, then write the
  58775. ** rest.
  58776. */
  58777. static int walWriteToLog(
  58778. WalWriter *p, /* WAL to write to */
  58779. void *pContent, /* Content to be written */
  58780. int iAmt, /* Number of bytes to write */
  58781. sqlite3_int64 iOffset /* Start writing at this offset */
  58782. ){
  58783. int rc;
  58784. if( iOffset<p->iSyncPoint && iOffset+iAmt>=p->iSyncPoint ){
  58785. int iFirstAmt = (int)(p->iSyncPoint - iOffset);
  58786. rc = sqlite3OsWrite(p->pFd, pContent, iFirstAmt, iOffset);
  58787. if( rc ) return rc;
  58788. iOffset += iFirstAmt;
  58789. iAmt -= iFirstAmt;
  58790. pContent = (void*)(iFirstAmt + (char*)pContent);
  58791. assert( WAL_SYNC_FLAGS(p->syncFlags)!=0 );
  58792. rc = sqlite3OsSync(p->pFd, WAL_SYNC_FLAGS(p->syncFlags));
  58793. if( iAmt==0 || rc ) return rc;
  58794. }
  58795. rc = sqlite3OsWrite(p->pFd, pContent, iAmt, iOffset);
  58796. return rc;
  58797. }
  58798. /*
  58799. ** Write out a single frame of the WAL
  58800. */
  58801. static int walWriteOneFrame(
  58802. WalWriter *p, /* Where to write the frame */
  58803. PgHdr *pPage, /* The page of the frame to be written */
  58804. int nTruncate, /* The commit flag. Usually 0. >0 for commit */
  58805. sqlite3_int64 iOffset /* Byte offset at which to write */
  58806. ){
  58807. int rc; /* Result code from subfunctions */
  58808. void *pData; /* Data actually written */
  58809. u8 aFrame[WAL_FRAME_HDRSIZE]; /* Buffer to assemble frame-header in */
  58810. pData = pPage->pData;
  58811. walEncodeFrame(p->pWal, pPage->pgno, nTruncate, pData, aFrame);
  58812. rc = walWriteToLog(p, aFrame, sizeof(aFrame), iOffset);
  58813. if( rc ) return rc;
  58814. /* Write the page data */
  58815. rc = walWriteToLog(p, pData, p->szPage, iOffset+sizeof(aFrame));
  58816. return rc;
  58817. }
  58818. /*
  58819. ** This function is called as part of committing a transaction within which
  58820. ** one or more frames have been overwritten. It updates the checksums for
  58821. ** all frames written to the wal file by the current transaction starting
  58822. ** with the earliest to have been overwritten.
  58823. **
  58824. ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
  58825. */
  58826. static int walRewriteChecksums(Wal *pWal, u32 iLast){
  58827. const int szPage = pWal->szPage;/* Database page size */
  58828. int rc = SQLITE_OK; /* Return code */
  58829. u8 *aBuf; /* Buffer to load data from wal file into */
  58830. u8 aFrame[WAL_FRAME_HDRSIZE]; /* Buffer to assemble frame-headers in */
  58831. u32 iRead; /* Next frame to read from wal file */
  58832. i64 iCksumOff;
  58833. aBuf = sqlite3_malloc(szPage + WAL_FRAME_HDRSIZE);
  58834. if( aBuf==0 ) return SQLITE_NOMEM_BKPT;
  58835. /* Find the checksum values to use as input for the recalculating the
  58836. ** first checksum. If the first frame is frame 1 (implying that the current
  58837. ** transaction restarted the wal file), these values must be read from the
  58838. ** wal-file header. Otherwise, read them from the frame header of the
  58839. ** previous frame. */
  58840. assert( pWal->iReCksum>0 );
  58841. if( pWal->iReCksum==1 ){
  58842. iCksumOff = 24;
  58843. }else{
  58844. iCksumOff = walFrameOffset(pWal->iReCksum-1, szPage) + 16;
  58845. }
  58846. rc = sqlite3OsRead(pWal->pWalFd, aBuf, sizeof(u32)*2, iCksumOff);
  58847. pWal->hdr.aFrameCksum[0] = sqlite3Get4byte(aBuf);
  58848. pWal->hdr.aFrameCksum[1] = sqlite3Get4byte(&aBuf[sizeof(u32)]);
  58849. iRead = pWal->iReCksum;
  58850. pWal->iReCksum = 0;
  58851. for(; rc==SQLITE_OK && iRead<=iLast; iRead++){
  58852. i64 iOff = walFrameOffset(iRead, szPage);
  58853. rc = sqlite3OsRead(pWal->pWalFd, aBuf, szPage+WAL_FRAME_HDRSIZE, iOff);
  58854. if( rc==SQLITE_OK ){
  58855. u32 iPgno, nDbSize;
  58856. iPgno = sqlite3Get4byte(aBuf);
  58857. nDbSize = sqlite3Get4byte(&aBuf[4]);
  58858. walEncodeFrame(pWal, iPgno, nDbSize, &aBuf[WAL_FRAME_HDRSIZE], aFrame);
  58859. rc = sqlite3OsWrite(pWal->pWalFd, aFrame, sizeof(aFrame), iOff);
  58860. }
  58861. }
  58862. sqlite3_free(aBuf);
  58863. return rc;
  58864. }
  58865. /*
  58866. ** Write a set of frames to the log. The caller must hold the write-lock
  58867. ** on the log file (obtained using sqlite3WalBeginWriteTransaction()).
  58868. */
  58869. SQLITE_PRIVATE int sqlite3WalFrames(
  58870. Wal *pWal, /* Wal handle to write to */
  58871. int szPage, /* Database page-size in bytes */
  58872. PgHdr *pList, /* List of dirty pages to write */
  58873. Pgno nTruncate, /* Database size after this commit */
  58874. int isCommit, /* True if this is a commit */
  58875. int sync_flags /* Flags to pass to OsSync() (or 0) */
  58876. ){
  58877. int rc; /* Used to catch return codes */
  58878. u32 iFrame; /* Next frame address */
  58879. PgHdr *p; /* Iterator to run through pList with. */
  58880. PgHdr *pLast = 0; /* Last frame in list */
  58881. int nExtra = 0; /* Number of extra copies of last page */
  58882. int szFrame; /* The size of a single frame */
  58883. i64 iOffset; /* Next byte to write in WAL file */
  58884. WalWriter w; /* The writer */
  58885. u32 iFirst = 0; /* First frame that may be overwritten */
  58886. WalIndexHdr *pLive; /* Pointer to shared header */
  58887. assert( pList );
  58888. assert( pWal->writeLock );
  58889. /* If this frame set completes a transaction, then nTruncate>0. If
  58890. ** nTruncate==0 then this frame set does not complete the transaction. */
  58891. assert( (isCommit!=0)==(nTruncate!=0) );
  58892. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  58893. { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){}
  58894. WALTRACE(("WAL%p: frame write begin. %d frames. mxFrame=%d. %s\n",
  58895. pWal, cnt, pWal->hdr.mxFrame, isCommit ? "Commit" : "Spill"));
  58896. }
  58897. #endif
  58898. pLive = (WalIndexHdr*)walIndexHdr(pWal);
  58899. if( memcmp(&pWal->hdr, (void *)pLive, sizeof(WalIndexHdr))!=0 ){
  58900. iFirst = pLive->mxFrame+1;
  58901. }
  58902. /* See if it is possible to write these frames into the start of the
  58903. ** log file, instead of appending to it at pWal->hdr.mxFrame.
  58904. */
  58905. if( SQLITE_OK!=(rc = walRestartLog(pWal)) ){
  58906. return rc;
  58907. }
  58908. /* If this is the first frame written into the log, write the WAL
  58909. ** header to the start of the WAL file. See comments at the top of
  58910. ** this source file for a description of the WAL header format.
  58911. */
  58912. iFrame = pWal->hdr.mxFrame;
  58913. if( iFrame==0 ){
  58914. u8 aWalHdr[WAL_HDRSIZE]; /* Buffer to assemble wal-header in */
  58915. u32 aCksum[2]; /* Checksum for wal-header */
  58916. sqlite3Put4byte(&aWalHdr[0], (WAL_MAGIC | SQLITE_BIGENDIAN));
  58917. sqlite3Put4byte(&aWalHdr[4], WAL_MAX_VERSION);
  58918. sqlite3Put4byte(&aWalHdr[8], szPage);
  58919. sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt);
  58920. if( pWal->nCkpt==0 ) sqlite3_randomness(8, pWal->hdr.aSalt);
  58921. memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8);
  58922. walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum);
  58923. sqlite3Put4byte(&aWalHdr[24], aCksum[0]);
  58924. sqlite3Put4byte(&aWalHdr[28], aCksum[1]);
  58925. pWal->szPage = szPage;
  58926. pWal->hdr.bigEndCksum = SQLITE_BIGENDIAN;
  58927. pWal->hdr.aFrameCksum[0] = aCksum[0];
  58928. pWal->hdr.aFrameCksum[1] = aCksum[1];
  58929. pWal->truncateOnCommit = 1;
  58930. rc = sqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0);
  58931. WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok"));
  58932. if( rc!=SQLITE_OK ){
  58933. return rc;
  58934. }
  58935. /* Sync the header (unless SQLITE_IOCAP_SEQUENTIAL is true or unless
  58936. ** all syncing is turned off by PRAGMA synchronous=OFF). Otherwise
  58937. ** an out-of-order write following a WAL restart could result in
  58938. ** database corruption. See the ticket:
  58939. **
  58940. ** https://sqlite.org/src/info/ff5be73dee
  58941. */
  58942. if( pWal->syncHeader ){
  58943. rc = sqlite3OsSync(pWal->pWalFd, CKPT_SYNC_FLAGS(sync_flags));
  58944. if( rc ) return rc;
  58945. }
  58946. }
  58947. assert( (int)pWal->szPage==szPage );
  58948. /* Setup information needed to write frames into the WAL */
  58949. w.pWal = pWal;
  58950. w.pFd = pWal->pWalFd;
  58951. w.iSyncPoint = 0;
  58952. w.syncFlags = sync_flags;
  58953. w.szPage = szPage;
  58954. iOffset = walFrameOffset(iFrame+1, szPage);
  58955. szFrame = szPage + WAL_FRAME_HDRSIZE;
  58956. /* Write all frames into the log file exactly once */
  58957. for(p=pList; p; p=p->pDirty){
  58958. int nDbSize; /* 0 normally. Positive == commit flag */
  58959. /* Check if this page has already been written into the wal file by
  58960. ** the current transaction. If so, overwrite the existing frame and
  58961. ** set Wal.writeLock to WAL_WRITELOCK_RECKSUM - indicating that
  58962. ** checksums must be recomputed when the transaction is committed. */
  58963. if( iFirst && (p->pDirty || isCommit==0) ){
  58964. u32 iWrite = 0;
  58965. VVA_ONLY(rc =) sqlite3WalFindFrame(pWal, p->pgno, &iWrite);
  58966. assert( rc==SQLITE_OK || iWrite==0 );
  58967. if( iWrite>=iFirst ){
  58968. i64 iOff = walFrameOffset(iWrite, szPage) + WAL_FRAME_HDRSIZE;
  58969. void *pData;
  58970. if( pWal->iReCksum==0 || iWrite<pWal->iReCksum ){
  58971. pWal->iReCksum = iWrite;
  58972. }
  58973. pData = p->pData;
  58974. rc = sqlite3OsWrite(pWal->pWalFd, pData, szPage, iOff);
  58975. if( rc ) return rc;
  58976. p->flags &= ~PGHDR_WAL_APPEND;
  58977. continue;
  58978. }
  58979. }
  58980. iFrame++;
  58981. assert( iOffset==walFrameOffset(iFrame, szPage) );
  58982. nDbSize = (isCommit && p->pDirty==0) ? nTruncate : 0;
  58983. rc = walWriteOneFrame(&w, p, nDbSize, iOffset);
  58984. if( rc ) return rc;
  58985. pLast = p;
  58986. iOffset += szFrame;
  58987. p->flags |= PGHDR_WAL_APPEND;
  58988. }
  58989. /* Recalculate checksums within the wal file if required. */
  58990. if( isCommit && pWal->iReCksum ){
  58991. rc = walRewriteChecksums(pWal, iFrame);
  58992. if( rc ) return rc;
  58993. }
  58994. /* If this is the end of a transaction, then we might need to pad
  58995. ** the transaction and/or sync the WAL file.
  58996. **
  58997. ** Padding and syncing only occur if this set of frames complete a
  58998. ** transaction and if PRAGMA synchronous=FULL. If synchronous==NORMAL
  58999. ** or synchronous==OFF, then no padding or syncing are needed.
  59000. **
  59001. ** If SQLITE_IOCAP_POWERSAFE_OVERWRITE is defined, then padding is not
  59002. ** needed and only the sync is done. If padding is needed, then the
  59003. ** final frame is repeated (with its commit mark) until the next sector
  59004. ** boundary is crossed. Only the part of the WAL prior to the last
  59005. ** sector boundary is synced; the part of the last frame that extends
  59006. ** past the sector boundary is written after the sync.
  59007. */
  59008. if( isCommit && WAL_SYNC_FLAGS(sync_flags)!=0 ){
  59009. int bSync = 1;
  59010. if( pWal->padToSectorBoundary ){
  59011. int sectorSize = sqlite3SectorSize(pWal->pWalFd);
  59012. w.iSyncPoint = ((iOffset+sectorSize-1)/sectorSize)*sectorSize;
  59013. bSync = (w.iSyncPoint==iOffset);
  59014. testcase( bSync );
  59015. while( iOffset<w.iSyncPoint ){
  59016. rc = walWriteOneFrame(&w, pLast, nTruncate, iOffset);
  59017. if( rc ) return rc;
  59018. iOffset += szFrame;
  59019. nExtra++;
  59020. assert( pLast!=0 );
  59021. }
  59022. }
  59023. if( bSync ){
  59024. assert( rc==SQLITE_OK );
  59025. rc = sqlite3OsSync(w.pFd, WAL_SYNC_FLAGS(sync_flags));
  59026. }
  59027. }
  59028. /* If this frame set completes the first transaction in the WAL and
  59029. ** if PRAGMA journal_size_limit is set, then truncate the WAL to the
  59030. ** journal size limit, if possible.
  59031. */
  59032. if( isCommit && pWal->truncateOnCommit && pWal->mxWalSize>=0 ){
  59033. i64 sz = pWal->mxWalSize;
  59034. if( walFrameOffset(iFrame+nExtra+1, szPage)>pWal->mxWalSize ){
  59035. sz = walFrameOffset(iFrame+nExtra+1, szPage);
  59036. }
  59037. walLimitSize(pWal, sz);
  59038. pWal->truncateOnCommit = 0;
  59039. }
  59040. /* Append data to the wal-index. It is not necessary to lock the
  59041. ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index
  59042. ** guarantees that there are no other writers, and no data that may
  59043. ** be in use by existing readers is being overwritten.
  59044. */
  59045. iFrame = pWal->hdr.mxFrame;
  59046. for(p=pList; p && rc==SQLITE_OK; p=p->pDirty){
  59047. if( (p->flags & PGHDR_WAL_APPEND)==0 ) continue;
  59048. iFrame++;
  59049. rc = walIndexAppend(pWal, iFrame, p->pgno);
  59050. }
  59051. assert( pLast!=0 || nExtra==0 );
  59052. while( rc==SQLITE_OK && nExtra>0 ){
  59053. iFrame++;
  59054. nExtra--;
  59055. rc = walIndexAppend(pWal, iFrame, pLast->pgno);
  59056. }
  59057. if( rc==SQLITE_OK ){
  59058. /* Update the private copy of the header. */
  59059. pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
  59060. testcase( szPage<=32768 );
  59061. testcase( szPage>=65536 );
  59062. pWal->hdr.mxFrame = iFrame;
  59063. if( isCommit ){
  59064. pWal->hdr.iChange++;
  59065. pWal->hdr.nPage = nTruncate;
  59066. }
  59067. /* If this is a commit, update the wal-index header too. */
  59068. if( isCommit ){
  59069. walIndexWriteHdr(pWal);
  59070. pWal->iCallback = iFrame;
  59071. }
  59072. }
  59073. WALTRACE(("WAL%p: frame write %s\n", pWal, rc ? "failed" : "ok"));
  59074. return rc;
  59075. }
  59076. /*
  59077. ** This routine is called to implement sqlite3_wal_checkpoint() and
  59078. ** related interfaces.
  59079. **
  59080. ** Obtain a CHECKPOINT lock and then backfill as much information as
  59081. ** we can from WAL into the database.
  59082. **
  59083. ** If parameter xBusy is not NULL, it is a pointer to a busy-handler
  59084. ** callback. In this case this function runs a blocking checkpoint.
  59085. */
  59086. SQLITE_PRIVATE int sqlite3WalCheckpoint(
  59087. Wal *pWal, /* Wal connection */
  59088. sqlite3 *db, /* Check this handle's interrupt flag */
  59089. int eMode, /* PASSIVE, FULL, RESTART, or TRUNCATE */
  59090. int (*xBusy)(void*), /* Function to call when busy */
  59091. void *pBusyArg, /* Context argument for xBusyHandler */
  59092. int sync_flags, /* Flags to sync db file with (or 0) */
  59093. int nBuf, /* Size of temporary buffer */
  59094. u8 *zBuf, /* Temporary buffer to use */
  59095. int *pnLog, /* OUT: Number of frames in WAL */
  59096. int *pnCkpt /* OUT: Number of backfilled frames in WAL */
  59097. ){
  59098. int rc; /* Return code */
  59099. int isChanged = 0; /* True if a new wal-index header is loaded */
  59100. int eMode2 = eMode; /* Mode to pass to walCheckpoint() */
  59101. int (*xBusy2)(void*) = xBusy; /* Busy handler for eMode2 */
  59102. assert( pWal->ckptLock==0 );
  59103. assert( pWal->writeLock==0 );
  59104. /* EVIDENCE-OF: R-62920-47450 The busy-handler callback is never invoked
  59105. ** in the SQLITE_CHECKPOINT_PASSIVE mode. */
  59106. assert( eMode!=SQLITE_CHECKPOINT_PASSIVE || xBusy==0 );
  59107. if( pWal->readOnly ) return SQLITE_READONLY;
  59108. WALTRACE(("WAL%p: checkpoint begins\n", pWal));
  59109. /* Enable blocking locks, if possible. If blocking locks are successfully
  59110. ** enabled, set xBusy2=0 so that the busy-handler is never invoked. */
  59111. sqlite3WalDb(pWal, db);
  59112. (void)walEnableBlocking(pWal);
  59113. /* IMPLEMENTATION-OF: R-62028-47212 All calls obtain an exclusive
  59114. ** "checkpoint" lock on the database file.
  59115. ** EVIDENCE-OF: R-10421-19736 If any other process is running a
  59116. ** checkpoint operation at the same time, the lock cannot be obtained and
  59117. ** SQLITE_BUSY is returned.
  59118. ** EVIDENCE-OF: R-53820-33897 Even if there is a busy-handler configured,
  59119. ** it will not be invoked in this case.
  59120. */
  59121. rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
  59122. testcase( rc==SQLITE_BUSY );
  59123. testcase( rc!=SQLITE_OK && xBusy2!=0 );
  59124. if( rc==SQLITE_OK ){
  59125. pWal->ckptLock = 1;
  59126. /* IMPLEMENTATION-OF: R-59782-36818 The SQLITE_CHECKPOINT_FULL, RESTART and
  59127. ** TRUNCATE modes also obtain the exclusive "writer" lock on the database
  59128. ** file.
  59129. **
  59130. ** EVIDENCE-OF: R-60642-04082 If the writer lock cannot be obtained
  59131. ** immediately, and a busy-handler is configured, it is invoked and the
  59132. ** writer lock retried until either the busy-handler returns 0 or the
  59133. ** lock is successfully obtained.
  59134. */
  59135. if( eMode!=SQLITE_CHECKPOINT_PASSIVE ){
  59136. rc = walBusyLock(pWal, xBusy2, pBusyArg, WAL_WRITE_LOCK, 1);
  59137. if( rc==SQLITE_OK ){
  59138. pWal->writeLock = 1;
  59139. }else if( rc==SQLITE_BUSY ){
  59140. eMode2 = SQLITE_CHECKPOINT_PASSIVE;
  59141. xBusy2 = 0;
  59142. rc = SQLITE_OK;
  59143. }
  59144. }
  59145. }
  59146. /* Read the wal-index header. */
  59147. if( rc==SQLITE_OK ){
  59148. walDisableBlocking(pWal);
  59149. rc = walIndexReadHdr(pWal, &isChanged);
  59150. (void)walEnableBlocking(pWal);
  59151. if( isChanged && pWal->pDbFd->pMethods->iVersion>=3 ){
  59152. sqlite3OsUnfetch(pWal->pDbFd, 0, 0);
  59153. }
  59154. }
  59155. /* Copy data from the log to the database file. */
  59156. if( rc==SQLITE_OK ){
  59157. if( pWal->hdr.mxFrame && walPagesize(pWal)!=nBuf ){
  59158. rc = SQLITE_CORRUPT_BKPT;
  59159. }else{
  59160. rc = walCheckpoint(pWal, db, eMode2, xBusy2, pBusyArg, sync_flags, zBuf);
  59161. }
  59162. /* If no error occurred, set the output variables. */
  59163. if( rc==SQLITE_OK || rc==SQLITE_BUSY ){
  59164. if( pnLog ) *pnLog = (int)pWal->hdr.mxFrame;
  59165. if( pnCkpt ) *pnCkpt = (int)(walCkptInfo(pWal)->nBackfill);
  59166. }
  59167. }
  59168. if( isChanged ){
  59169. /* If a new wal-index header was loaded before the checkpoint was
  59170. ** performed, then the pager-cache associated with pWal is now
  59171. ** out of date. So zero the cached wal-index header to ensure that
  59172. ** next time the pager opens a snapshot on this database it knows that
  59173. ** the cache needs to be reset.
  59174. */
  59175. memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
  59176. }
  59177. walDisableBlocking(pWal);
  59178. sqlite3WalDb(pWal, 0);
  59179. /* Release the locks. */
  59180. sqlite3WalEndWriteTransaction(pWal);
  59181. if( pWal->ckptLock ){
  59182. walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
  59183. pWal->ckptLock = 0;
  59184. }
  59185. WALTRACE(("WAL%p: checkpoint %s\n", pWal, rc ? "failed" : "ok"));
  59186. #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
  59187. if( rc==SQLITE_BUSY_TIMEOUT ) rc = SQLITE_BUSY;
  59188. #endif
  59189. return (rc==SQLITE_OK && eMode!=eMode2 ? SQLITE_BUSY : rc);
  59190. }
  59191. /* Return the value to pass to a sqlite3_wal_hook callback, the
  59192. ** number of frames in the WAL at the point of the last commit since
  59193. ** sqlite3WalCallback() was called. If no commits have occurred since
  59194. ** the last call, then return 0.
  59195. */
  59196. SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal){
  59197. u32 ret = 0;
  59198. if( pWal ){
  59199. ret = pWal->iCallback;
  59200. pWal->iCallback = 0;
  59201. }
  59202. return (int)ret;
  59203. }
  59204. /*
  59205. ** This function is called to change the WAL subsystem into or out
  59206. ** of locking_mode=EXCLUSIVE.
  59207. **
  59208. ** If op is zero, then attempt to change from locking_mode=EXCLUSIVE
  59209. ** into locking_mode=NORMAL. This means that we must acquire a lock
  59210. ** on the pWal->readLock byte. If the WAL is already in locking_mode=NORMAL
  59211. ** or if the acquisition of the lock fails, then return 0. If the
  59212. ** transition out of exclusive-mode is successful, return 1. This
  59213. ** operation must occur while the pager is still holding the exclusive
  59214. ** lock on the main database file.
  59215. **
  59216. ** If op is one, then change from locking_mode=NORMAL into
  59217. ** locking_mode=EXCLUSIVE. This means that the pWal->readLock must
  59218. ** be released. Return 1 if the transition is made and 0 if the
  59219. ** WAL is already in exclusive-locking mode - meaning that this
  59220. ** routine is a no-op. The pager must already hold the exclusive lock
  59221. ** on the main database file before invoking this operation.
  59222. **
  59223. ** If op is negative, then do a dry-run of the op==1 case but do
  59224. ** not actually change anything. The pager uses this to see if it
  59225. ** should acquire the database exclusive lock prior to invoking
  59226. ** the op==1 case.
  59227. */
  59228. SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op){
  59229. int rc;
  59230. assert( pWal->writeLock==0 );
  59231. assert( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE || op==-1 );
  59232. /* pWal->readLock is usually set, but might be -1 if there was a
  59233. ** prior error while attempting to acquire are read-lock. This cannot
  59234. ** happen if the connection is actually in exclusive mode (as no xShmLock
  59235. ** locks are taken in this case). Nor should the pager attempt to
  59236. ** upgrade to exclusive-mode following such an error.
  59237. */
  59238. assert( pWal->readLock>=0 || pWal->lockError );
  59239. assert( pWal->readLock>=0 || (op<=0 && pWal->exclusiveMode==0) );
  59240. if( op==0 ){
  59241. if( pWal->exclusiveMode!=WAL_NORMAL_MODE ){
  59242. pWal->exclusiveMode = WAL_NORMAL_MODE;
  59243. if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLITE_OK ){
  59244. pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
  59245. }
  59246. rc = pWal->exclusiveMode==WAL_NORMAL_MODE;
  59247. }else{
  59248. /* Already in locking_mode=NORMAL */
  59249. rc = 0;
  59250. }
  59251. }else if( op>0 ){
  59252. assert( pWal->exclusiveMode==WAL_NORMAL_MODE );
  59253. assert( pWal->readLock>=0 );
  59254. walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
  59255. pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
  59256. rc = 1;
  59257. }else{
  59258. rc = pWal->exclusiveMode==WAL_NORMAL_MODE;
  59259. }
  59260. return rc;
  59261. }
  59262. /*
  59263. ** Return true if the argument is non-NULL and the WAL module is using
  59264. ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
  59265. ** WAL module is using shared-memory, return false.
  59266. */
  59267. SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal){
  59268. return (pWal && pWal->exclusiveMode==WAL_HEAPMEMORY_MODE );
  59269. }
  59270. #ifdef SQLITE_ENABLE_SNAPSHOT
  59271. /* Create a snapshot object. The content of a snapshot is opaque to
  59272. ** every other subsystem, so the WAL module can put whatever it needs
  59273. ** in the object.
  59274. */
  59275. SQLITE_PRIVATE int sqlite3WalSnapshotGet(Wal *pWal, sqlite3_snapshot **ppSnapshot){
  59276. int rc = SQLITE_OK;
  59277. WalIndexHdr *pRet;
  59278. static const u32 aZero[4] = { 0, 0, 0, 0 };
  59279. assert( pWal->readLock>=0 && pWal->writeLock==0 );
  59280. if( memcmp(&pWal->hdr.aFrameCksum[0],aZero,16)==0 ){
  59281. *ppSnapshot = 0;
  59282. return SQLITE_ERROR;
  59283. }
  59284. pRet = (WalIndexHdr*)sqlite3_malloc(sizeof(WalIndexHdr));
  59285. if( pRet==0 ){
  59286. rc = SQLITE_NOMEM_BKPT;
  59287. }else{
  59288. memcpy(pRet, &pWal->hdr, sizeof(WalIndexHdr));
  59289. *ppSnapshot = (sqlite3_snapshot*)pRet;
  59290. }
  59291. return rc;
  59292. }
  59293. /* Try to open on pSnapshot when the next read-transaction starts
  59294. */
  59295. SQLITE_PRIVATE void sqlite3WalSnapshotOpen(
  59296. Wal *pWal,
  59297. sqlite3_snapshot *pSnapshot
  59298. ){
  59299. pWal->pSnapshot = (WalIndexHdr*)pSnapshot;
  59300. }
  59301. /*
  59302. ** Return a +ve value if snapshot p1 is newer than p2. A -ve value if
  59303. ** p1 is older than p2 and zero if p1 and p2 are the same snapshot.
  59304. */
  59305. SQLITE_API int sqlite3_snapshot_cmp(sqlite3_snapshot *p1, sqlite3_snapshot *p2){
  59306. WalIndexHdr *pHdr1 = (WalIndexHdr*)p1;
  59307. WalIndexHdr *pHdr2 = (WalIndexHdr*)p2;
  59308. /* aSalt[0] is a copy of the value stored in the wal file header. It
  59309. ** is incremented each time the wal file is restarted. */
  59310. if( pHdr1->aSalt[0]<pHdr2->aSalt[0] ) return -1;
  59311. if( pHdr1->aSalt[0]>pHdr2->aSalt[0] ) return +1;
  59312. if( pHdr1->mxFrame<pHdr2->mxFrame ) return -1;
  59313. if( pHdr1->mxFrame>pHdr2->mxFrame ) return +1;
  59314. return 0;
  59315. }
  59316. /*
  59317. ** The caller currently has a read transaction open on the database.
  59318. ** This function takes a SHARED lock on the CHECKPOINTER slot and then
  59319. ** checks if the snapshot passed as the second argument is still
  59320. ** available. If so, SQLITE_OK is returned.
  59321. **
  59322. ** If the snapshot is not available, SQLITE_ERROR is returned. Or, if
  59323. ** the CHECKPOINTER lock cannot be obtained, SQLITE_BUSY. If any error
  59324. ** occurs (any value other than SQLITE_OK is returned), the CHECKPOINTER
  59325. ** lock is released before returning.
  59326. */
  59327. SQLITE_PRIVATE int sqlite3WalSnapshotCheck(Wal *pWal, sqlite3_snapshot *pSnapshot){
  59328. int rc;
  59329. rc = walLockShared(pWal, WAL_CKPT_LOCK);
  59330. if( rc==SQLITE_OK ){
  59331. WalIndexHdr *pNew = (WalIndexHdr*)pSnapshot;
  59332. if( memcmp(pNew->aSalt, pWal->hdr.aSalt, sizeof(pWal->hdr.aSalt))
  59333. || pNew->mxFrame<walCkptInfo(pWal)->nBackfillAttempted
  59334. ){
  59335. rc = SQLITE_ERROR_SNAPSHOT;
  59336. walUnlockShared(pWal, WAL_CKPT_LOCK);
  59337. }
  59338. }
  59339. return rc;
  59340. }
  59341. /*
  59342. ** Release a lock obtained by an earlier successful call to
  59343. ** sqlite3WalSnapshotCheck().
  59344. */
  59345. SQLITE_PRIVATE void sqlite3WalSnapshotUnlock(Wal *pWal){
  59346. assert( pWal );
  59347. walUnlockShared(pWal, WAL_CKPT_LOCK);
  59348. }
  59349. #endif /* SQLITE_ENABLE_SNAPSHOT */
  59350. #ifdef SQLITE_ENABLE_ZIPVFS
  59351. /*
  59352. ** If the argument is not NULL, it points to a Wal object that holds a
  59353. ** read-lock. This function returns the database page-size if it is known,
  59354. ** or zero if it is not (or if pWal is NULL).
  59355. */
  59356. SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal){
  59357. assert( pWal==0 || pWal->readLock>=0 );
  59358. return (pWal ? pWal->szPage : 0);
  59359. }
  59360. #endif
  59361. /* Return the sqlite3_file object for the WAL file
  59362. */
  59363. SQLITE_PRIVATE sqlite3_file *sqlite3WalFile(Wal *pWal){
  59364. return pWal->pWalFd;
  59365. }
  59366. #endif /* #ifndef SQLITE_OMIT_WAL */
  59367. /************** End of wal.c *************************************************/
  59368. /************** Begin file btmutex.c *****************************************/
  59369. /*
  59370. ** 2007 August 27
  59371. **
  59372. ** The author disclaims copyright to this source code. In place of
  59373. ** a legal notice, here is a blessing:
  59374. **
  59375. ** May you do good and not evil.
  59376. ** May you find forgiveness for yourself and forgive others.
  59377. ** May you share freely, never taking more than you give.
  59378. **
  59379. *************************************************************************
  59380. **
  59381. ** This file contains code used to implement mutexes on Btree objects.
  59382. ** This code really belongs in btree.c. But btree.c is getting too
  59383. ** big and we want to break it down some. This packaged seemed like
  59384. ** a good breakout.
  59385. */
  59386. /************** Include btreeInt.h in the middle of btmutex.c ****************/
  59387. /************** Begin file btreeInt.h ****************************************/
  59388. /*
  59389. ** 2004 April 6
  59390. **
  59391. ** The author disclaims copyright to this source code. In place of
  59392. ** a legal notice, here is a blessing:
  59393. **
  59394. ** May you do good and not evil.
  59395. ** May you find forgiveness for yourself and forgive others.
  59396. ** May you share freely, never taking more than you give.
  59397. **
  59398. *************************************************************************
  59399. ** This file implements an external (disk-based) database using BTrees.
  59400. ** For a detailed discussion of BTrees, refer to
  59401. **
  59402. ** Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
  59403. ** "Sorting And Searching", pages 473-480. Addison-Wesley
  59404. ** Publishing Company, Reading, Massachusetts.
  59405. **
  59406. ** The basic idea is that each page of the file contains N database
  59407. ** entries and N+1 pointers to subpages.
  59408. **
  59409. ** ----------------------------------------------------------------
  59410. ** | Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
  59411. ** ----------------------------------------------------------------
  59412. **
  59413. ** All of the keys on the page that Ptr(0) points to have values less
  59414. ** than Key(0). All of the keys on page Ptr(1) and its subpages have
  59415. ** values greater than Key(0) and less than Key(1). All of the keys
  59416. ** on Ptr(N) and its subpages have values greater than Key(N-1). And
  59417. ** so forth.
  59418. **
  59419. ** Finding a particular key requires reading O(log(M)) pages from the
  59420. ** disk where M is the number of entries in the tree.
  59421. **
  59422. ** In this implementation, a single file can hold one or more separate
  59423. ** BTrees. Each BTree is identified by the index of its root page. The
  59424. ** key and data for any entry are combined to form the "payload". A
  59425. ** fixed amount of payload can be carried directly on the database
  59426. ** page. If the payload is larger than the preset amount then surplus
  59427. ** bytes are stored on overflow pages. The payload for an entry
  59428. ** and the preceding pointer are combined to form a "Cell". Each
  59429. ** page has a small header which contains the Ptr(N) pointer and other
  59430. ** information such as the size of key and data.
  59431. **
  59432. ** FORMAT DETAILS
  59433. **
  59434. ** The file is divided into pages. The first page is called page 1,
  59435. ** the second is page 2, and so forth. A page number of zero indicates
  59436. ** "no such page". The page size can be any power of 2 between 512 and 65536.
  59437. ** Each page can be either a btree page, a freelist page, an overflow
  59438. ** page, or a pointer-map page.
  59439. **
  59440. ** The first page is always a btree page. The first 100 bytes of the first
  59441. ** page contain a special header (the "file header") that describes the file.
  59442. ** The format of the file header is as follows:
  59443. **
  59444. ** OFFSET SIZE DESCRIPTION
  59445. ** 0 16 Header string: "SQLite format 3\000"
  59446. ** 16 2 Page size in bytes. (1 means 65536)
  59447. ** 18 1 File format write version
  59448. ** 19 1 File format read version
  59449. ** 20 1 Bytes of unused space at the end of each page
  59450. ** 21 1 Max embedded payload fraction (must be 64)
  59451. ** 22 1 Min embedded payload fraction (must be 32)
  59452. ** 23 1 Min leaf payload fraction (must be 32)
  59453. ** 24 4 File change counter
  59454. ** 28 4 Reserved for future use
  59455. ** 32 4 First freelist page
  59456. ** 36 4 Number of freelist pages in the file
  59457. ** 40 60 15 4-byte meta values passed to higher layers
  59458. **
  59459. ** 40 4 Schema cookie
  59460. ** 44 4 File format of schema layer
  59461. ** 48 4 Size of page cache
  59462. ** 52 4 Largest root-page (auto/incr_vacuum)
  59463. ** 56 4 1=UTF-8 2=UTF16le 3=UTF16be
  59464. ** 60 4 User version
  59465. ** 64 4 Incremental vacuum mode
  59466. ** 68 4 Application-ID
  59467. ** 72 20 unused
  59468. ** 92 4 The version-valid-for number
  59469. ** 96 4 SQLITE_VERSION_NUMBER
  59470. **
  59471. ** All of the integer values are big-endian (most significant byte first).
  59472. **
  59473. ** The file change counter is incremented when the database is changed
  59474. ** This counter allows other processes to know when the file has changed
  59475. ** and thus when they need to flush their cache.
  59476. **
  59477. ** The max embedded payload fraction is the amount of the total usable
  59478. ** space in a page that can be consumed by a single cell for standard
  59479. ** B-tree (non-LEAFDATA) tables. A value of 255 means 100%. The default
  59480. ** is to limit the maximum cell size so that at least 4 cells will fit
  59481. ** on one page. Thus the default max embedded payload fraction is 64.
  59482. **
  59483. ** If the payload for a cell is larger than the max payload, then extra
  59484. ** payload is spilled to overflow pages. Once an overflow page is allocated,
  59485. ** as many bytes as possible are moved into the overflow pages without letting
  59486. ** the cell size drop below the min embedded payload fraction.
  59487. **
  59488. ** The min leaf payload fraction is like the min embedded payload fraction
  59489. ** except that it applies to leaf nodes in a LEAFDATA tree. The maximum
  59490. ** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
  59491. ** not specified in the header.
  59492. **
  59493. ** Each btree pages is divided into three sections: The header, the
  59494. ** cell pointer array, and the cell content area. Page 1 also has a 100-byte
  59495. ** file header that occurs before the page header.
  59496. **
  59497. ** |----------------|
  59498. ** | file header | 100 bytes. Page 1 only.
  59499. ** |----------------|
  59500. ** | page header | 8 bytes for leaves. 12 bytes for interior nodes
  59501. ** |----------------|
  59502. ** | cell pointer | | 2 bytes per cell. Sorted order.
  59503. ** | array | | Grows downward
  59504. ** | | v
  59505. ** |----------------|
  59506. ** | unallocated |
  59507. ** | space |
  59508. ** |----------------| ^ Grows upwards
  59509. ** | cell content | | Arbitrary order interspersed with freeblocks.
  59510. ** | area | | and free space fragments.
  59511. ** |----------------|
  59512. **
  59513. ** The page headers looks like this:
  59514. **
  59515. ** OFFSET SIZE DESCRIPTION
  59516. ** 0 1 Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
  59517. ** 1 2 byte offset to the first freeblock
  59518. ** 3 2 number of cells on this page
  59519. ** 5 2 first byte of the cell content area
  59520. ** 7 1 number of fragmented free bytes
  59521. ** 8 4 Right child (the Ptr(N) value). Omitted on leaves.
  59522. **
  59523. ** The flags define the format of this btree page. The leaf flag means that
  59524. ** this page has no children. The zerodata flag means that this page carries
  59525. ** only keys and no data. The intkey flag means that the key is an integer
  59526. ** which is stored in the key size entry of the cell header rather than in
  59527. ** the payload area.
  59528. **
  59529. ** The cell pointer array begins on the first byte after the page header.
  59530. ** The cell pointer array contains zero or more 2-byte numbers which are
  59531. ** offsets from the beginning of the page to the cell content in the cell
  59532. ** content area. The cell pointers occur in sorted order. The system strives
  59533. ** to keep free space after the last cell pointer so that new cells can
  59534. ** be easily added without having to defragment the page.
  59535. **
  59536. ** Cell content is stored at the very end of the page and grows toward the
  59537. ** beginning of the page.
  59538. **
  59539. ** Unused space within the cell content area is collected into a linked list of
  59540. ** freeblocks. Each freeblock is at least 4 bytes in size. The byte offset
  59541. ** to the first freeblock is given in the header. Freeblocks occur in
  59542. ** increasing order. Because a freeblock must be at least 4 bytes in size,
  59543. ** any group of 3 or fewer unused bytes in the cell content area cannot
  59544. ** exist on the freeblock chain. A group of 3 or fewer free bytes is called
  59545. ** a fragment. The total number of bytes in all fragments is recorded.
  59546. ** in the page header at offset 7.
  59547. **
  59548. ** SIZE DESCRIPTION
  59549. ** 2 Byte offset of the next freeblock
  59550. ** 2 Bytes in this freeblock
  59551. **
  59552. ** Cells are of variable length. Cells are stored in the cell content area at
  59553. ** the end of the page. Pointers to the cells are in the cell pointer array
  59554. ** that immediately follows the page header. Cells is not necessarily
  59555. ** contiguous or in order, but cell pointers are contiguous and in order.
  59556. **
  59557. ** Cell content makes use of variable length integers. A variable
  59558. ** length integer is 1 to 9 bytes where the lower 7 bits of each
  59559. ** byte are used. The integer consists of all bytes that have bit 8 set and
  59560. ** the first byte with bit 8 clear. The most significant byte of the integer
  59561. ** appears first. A variable-length integer may not be more than 9 bytes long.
  59562. ** As a special case, all 8 bytes of the 9th byte are used as data. This
  59563. ** allows a 64-bit integer to be encoded in 9 bytes.
  59564. **
  59565. ** 0x00 becomes 0x00000000
  59566. ** 0x7f becomes 0x0000007f
  59567. ** 0x81 0x00 becomes 0x00000080
  59568. ** 0x82 0x00 becomes 0x00000100
  59569. ** 0x80 0x7f becomes 0x0000007f
  59570. ** 0x8a 0x91 0xd1 0xac 0x78 becomes 0x12345678
  59571. ** 0x81 0x81 0x81 0x81 0x01 becomes 0x10204081
  59572. **
  59573. ** Variable length integers are used for rowids and to hold the number of
  59574. ** bytes of key and data in a btree cell.
  59575. **
  59576. ** The content of a cell looks like this:
  59577. **
  59578. ** SIZE DESCRIPTION
  59579. ** 4 Page number of the left child. Omitted if leaf flag is set.
  59580. ** var Number of bytes of data. Omitted if the zerodata flag is set.
  59581. ** var Number of bytes of key. Or the key itself if intkey flag is set.
  59582. ** * Payload
  59583. ** 4 First page of the overflow chain. Omitted if no overflow
  59584. **
  59585. ** Overflow pages form a linked list. Each page except the last is completely
  59586. ** filled with data (pagesize - 4 bytes). The last page can have as little
  59587. ** as 1 byte of data.
  59588. **
  59589. ** SIZE DESCRIPTION
  59590. ** 4 Page number of next overflow page
  59591. ** * Data
  59592. **
  59593. ** Freelist pages come in two subtypes: trunk pages and leaf pages. The
  59594. ** file header points to the first in a linked list of trunk page. Each trunk
  59595. ** page points to multiple leaf pages. The content of a leaf page is
  59596. ** unspecified. A trunk page looks like this:
  59597. **
  59598. ** SIZE DESCRIPTION
  59599. ** 4 Page number of next trunk page
  59600. ** 4 Number of leaf pointers on this page
  59601. ** * zero or more pages numbers of leaves
  59602. */
  59603. /* #include "sqliteInt.h" */
  59604. /* The following value is the maximum cell size assuming a maximum page
  59605. ** size give above.
  59606. */
  59607. #define MX_CELL_SIZE(pBt) ((int)(pBt->pageSize-8))
  59608. /* The maximum number of cells on a single page of the database. This
  59609. ** assumes a minimum cell size of 6 bytes (4 bytes for the cell itself
  59610. ** plus 2 bytes for the index to the cell in the page header). Such
  59611. ** small cells will be rare, but they are possible.
  59612. */
  59613. #define MX_CELL(pBt) ((pBt->pageSize-8)/6)
  59614. /* Forward declarations */
  59615. typedef struct MemPage MemPage;
  59616. typedef struct BtLock BtLock;
  59617. typedef struct CellInfo CellInfo;
  59618. /*
  59619. ** This is a magic string that appears at the beginning of every
  59620. ** SQLite database in order to identify the file as a real database.
  59621. **
  59622. ** You can change this value at compile-time by specifying a
  59623. ** -DSQLITE_FILE_HEADER="..." on the compiler command-line. The
  59624. ** header must be exactly 16 bytes including the zero-terminator so
  59625. ** the string itself should be 15 characters long. If you change
  59626. ** the header, then your custom library will not be able to read
  59627. ** databases generated by the standard tools and the standard tools
  59628. ** will not be able to read databases created by your custom library.
  59629. */
  59630. #ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
  59631. # define SQLITE_FILE_HEADER "SQLite format 3"
  59632. #endif
  59633. /*
  59634. ** Page type flags. An ORed combination of these flags appear as the
  59635. ** first byte of on-disk image of every BTree page.
  59636. */
  59637. #define PTF_INTKEY 0x01
  59638. #define PTF_ZERODATA 0x02
  59639. #define PTF_LEAFDATA 0x04
  59640. #define PTF_LEAF 0x08
  59641. /*
  59642. ** An instance of this object stores information about each a single database
  59643. ** page that has been loaded into memory. The information in this object
  59644. ** is derived from the raw on-disk page content.
  59645. **
  59646. ** As each database page is loaded into memory, the pager allocats an
  59647. ** instance of this object and zeros the first 8 bytes. (This is the
  59648. ** "extra" information associated with each page of the pager.)
  59649. **
  59650. ** Access to all fields of this structure is controlled by the mutex
  59651. ** stored in MemPage.pBt->mutex.
  59652. */
  59653. struct MemPage {
  59654. u8 isInit; /* True if previously initialized. MUST BE FIRST! */
  59655. u8 bBusy; /* Prevent endless loops on corrupt database files */
  59656. u8 intKey; /* True if table b-trees. False for index b-trees */
  59657. u8 intKeyLeaf; /* True if the leaf of an intKey table */
  59658. Pgno pgno; /* Page number for this page */
  59659. /* Only the first 8 bytes (above) are zeroed by pager.c when a new page
  59660. ** is allocated. All fields that follow must be initialized before use */
  59661. u8 leaf; /* True if a leaf page */
  59662. u8 hdrOffset; /* 100 for page 1. 0 otherwise */
  59663. u8 childPtrSize; /* 0 if leaf==1. 4 if leaf==0 */
  59664. u8 max1bytePayload; /* min(maxLocal,127) */
  59665. u8 nOverflow; /* Number of overflow cell bodies in aCell[] */
  59666. u16 maxLocal; /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
  59667. u16 minLocal; /* Copy of BtShared.minLocal or BtShared.minLeaf */
  59668. u16 cellOffset; /* Index in aData of first cell pointer */
  59669. int nFree; /* Number of free bytes on the page. -1 for unknown */
  59670. u16 nCell; /* Number of cells on this page, local and ovfl */
  59671. u16 maskPage; /* Mask for page offset */
  59672. u16 aiOvfl[4]; /* Insert the i-th overflow cell before the aiOvfl-th
  59673. ** non-overflow cell */
  59674. u8 *apOvfl[4]; /* Pointers to the body of overflow cells */
  59675. BtShared *pBt; /* Pointer to BtShared that this page is part of */
  59676. u8 *aData; /* Pointer to disk image of the page data */
  59677. u8 *aDataEnd; /* One byte past the end of usable data */
  59678. u8 *aCellIdx; /* The cell index area */
  59679. u8 *aDataOfst; /* Same as aData for leaves. aData+4 for interior */
  59680. DbPage *pDbPage; /* Pager page handle */
  59681. u16 (*xCellSize)(MemPage*,u8*); /* cellSizePtr method */
  59682. void (*xParseCell)(MemPage*,u8*,CellInfo*); /* btreeParseCell method */
  59683. };
  59684. /*
  59685. ** A linked list of the following structures is stored at BtShared.pLock.
  59686. ** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor
  59687. ** is opened on the table with root page BtShared.iTable. Locks are removed
  59688. ** from this list when a transaction is committed or rolled back, or when
  59689. ** a btree handle is closed.
  59690. */
  59691. struct BtLock {
  59692. Btree *pBtree; /* Btree handle holding this lock */
  59693. Pgno iTable; /* Root page of table */
  59694. u8 eLock; /* READ_LOCK or WRITE_LOCK */
  59695. BtLock *pNext; /* Next in BtShared.pLock list */
  59696. };
  59697. /* Candidate values for BtLock.eLock */
  59698. #define READ_LOCK 1
  59699. #define WRITE_LOCK 2
  59700. /* A Btree handle
  59701. **
  59702. ** A database connection contains a pointer to an instance of
  59703. ** this object for every database file that it has open. This structure
  59704. ** is opaque to the database connection. The database connection cannot
  59705. ** see the internals of this structure and only deals with pointers to
  59706. ** this structure.
  59707. **
  59708. ** For some database files, the same underlying database cache might be
  59709. ** shared between multiple connections. In that case, each connection
  59710. ** has it own instance of this object. But each instance of this object
  59711. ** points to the same BtShared object. The database cache and the
  59712. ** schema associated with the database file are all contained within
  59713. ** the BtShared object.
  59714. **
  59715. ** All fields in this structure are accessed under sqlite3.mutex.
  59716. ** The pBt pointer itself may not be changed while there exists cursors
  59717. ** in the referenced BtShared that point back to this Btree since those
  59718. ** cursors have to go through this Btree to find their BtShared and
  59719. ** they often do so without holding sqlite3.mutex.
  59720. */
  59721. struct Btree {
  59722. sqlite3 *db; /* The database connection holding this btree */
  59723. BtShared *pBt; /* Sharable content of this btree */
  59724. u8 inTrans; /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
  59725. u8 sharable; /* True if we can share pBt with another db */
  59726. u8 locked; /* True if db currently has pBt locked */
  59727. u8 hasIncrblobCur; /* True if there are one or more Incrblob cursors */
  59728. int wantToLock; /* Number of nested calls to sqlite3BtreeEnter() */
  59729. int nBackup; /* Number of backup operations reading this btree */
  59730. u32 iDataVersion; /* Combines with pBt->pPager->iDataVersion */
  59731. Btree *pNext; /* List of other sharable Btrees from the same db */
  59732. Btree *pPrev; /* Back pointer of the same list */
  59733. #ifndef SQLITE_OMIT_SHARED_CACHE
  59734. BtLock lock; /* Object used to lock page 1 */
  59735. #endif
  59736. };
  59737. /*
  59738. ** Btree.inTrans may take one of the following values.
  59739. **
  59740. ** If the shared-data extension is enabled, there may be multiple users
  59741. ** of the Btree structure. At most one of these may open a write transaction,
  59742. ** but any number may have active read transactions.
  59743. */
  59744. #define TRANS_NONE 0
  59745. #define TRANS_READ 1
  59746. #define TRANS_WRITE 2
  59747. /*
  59748. ** An instance of this object represents a single database file.
  59749. **
  59750. ** A single database file can be in use at the same time by two
  59751. ** or more database connections. When two or more connections are
  59752. ** sharing the same database file, each connection has it own
  59753. ** private Btree object for the file and each of those Btrees points
  59754. ** to this one BtShared object. BtShared.nRef is the number of
  59755. ** connections currently sharing this database file.
  59756. **
  59757. ** Fields in this structure are accessed under the BtShared.mutex
  59758. ** mutex, except for nRef and pNext which are accessed under the
  59759. ** global SQLITE_MUTEX_STATIC_MASTER mutex. The pPager field
  59760. ** may not be modified once it is initially set as long as nRef>0.
  59761. ** The pSchema field may be set once under BtShared.mutex and
  59762. ** thereafter is unchanged as long as nRef>0.
  59763. **
  59764. ** isPending:
  59765. **
  59766. ** If a BtShared client fails to obtain a write-lock on a database
  59767. ** table (because there exists one or more read-locks on the table),
  59768. ** the shared-cache enters 'pending-lock' state and isPending is
  59769. ** set to true.
  59770. **
  59771. ** The shared-cache leaves the 'pending lock' state when either of
  59772. ** the following occur:
  59773. **
  59774. ** 1) The current writer (BtShared.pWriter) concludes its transaction, OR
  59775. ** 2) The number of locks held by other connections drops to zero.
  59776. **
  59777. ** while in the 'pending-lock' state, no connection may start a new
  59778. ** transaction.
  59779. **
  59780. ** This feature is included to help prevent writer-starvation.
  59781. */
  59782. struct BtShared {
  59783. Pager *pPager; /* The page cache */
  59784. sqlite3 *db; /* Database connection currently using this Btree */
  59785. BtCursor *pCursor; /* A list of all open cursors */
  59786. MemPage *pPage1; /* First page of the database */
  59787. u8 openFlags; /* Flags to sqlite3BtreeOpen() */
  59788. #ifndef SQLITE_OMIT_AUTOVACUUM
  59789. u8 autoVacuum; /* True if auto-vacuum is enabled */
  59790. u8 incrVacuum; /* True if incr-vacuum is enabled */
  59791. u8 bDoTruncate; /* True to truncate db on commit */
  59792. #endif
  59793. u8 inTransaction; /* Transaction state */
  59794. u8 max1bytePayload; /* Maximum first byte of cell for a 1-byte payload */
  59795. u8 nReserveWanted; /* Desired number of extra bytes per page */
  59796. u16 btsFlags; /* Boolean parameters. See BTS_* macros below */
  59797. u16 maxLocal; /* Maximum local payload in non-LEAFDATA tables */
  59798. u16 minLocal; /* Minimum local payload in non-LEAFDATA tables */
  59799. u16 maxLeaf; /* Maximum local payload in a LEAFDATA table */
  59800. u16 minLeaf; /* Minimum local payload in a LEAFDATA table */
  59801. u32 pageSize; /* Total number of bytes on a page */
  59802. u32 usableSize; /* Number of usable bytes on each page */
  59803. int nTransaction; /* Number of open transactions (read + write) */
  59804. u32 nPage; /* Number of pages in the database */
  59805. void *pSchema; /* Pointer to space allocated by sqlite3BtreeSchema() */
  59806. void (*xFreeSchema)(void*); /* Destructor for BtShared.pSchema */
  59807. sqlite3_mutex *mutex; /* Non-recursive mutex required to access this object */
  59808. Bitvec *pHasContent; /* Set of pages moved to free-list this transaction */
  59809. #ifndef SQLITE_OMIT_SHARED_CACHE
  59810. int nRef; /* Number of references to this structure */
  59811. BtShared *pNext; /* Next on a list of sharable BtShared structs */
  59812. BtLock *pLock; /* List of locks held on this shared-btree struct */
  59813. Btree *pWriter; /* Btree with currently open write transaction */
  59814. #endif
  59815. u8 *pTmpSpace; /* Temp space sufficient to hold a single cell */
  59816. };
  59817. /*
  59818. ** Allowed values for BtShared.btsFlags
  59819. */
  59820. #define BTS_READ_ONLY 0x0001 /* Underlying file is readonly */
  59821. #define BTS_PAGESIZE_FIXED 0x0002 /* Page size can no longer be changed */
  59822. #define BTS_SECURE_DELETE 0x0004 /* PRAGMA secure_delete is enabled */
  59823. #define BTS_OVERWRITE 0x0008 /* Overwrite deleted content with zeros */
  59824. #define BTS_FAST_SECURE 0x000c /* Combination of the previous two */
  59825. #define BTS_INITIALLY_EMPTY 0x0010 /* Database was empty at trans start */
  59826. #define BTS_NO_WAL 0x0020 /* Do not open write-ahead-log files */
  59827. #define BTS_EXCLUSIVE 0x0040 /* pWriter has an exclusive lock */
  59828. #define BTS_PENDING 0x0080 /* Waiting for read-locks to clear */
  59829. /*
  59830. ** An instance of the following structure is used to hold information
  59831. ** about a cell. The parseCellPtr() function fills in this structure
  59832. ** based on information extract from the raw disk page.
  59833. */
  59834. struct CellInfo {
  59835. i64 nKey; /* The key for INTKEY tables, or nPayload otherwise */
  59836. u8 *pPayload; /* Pointer to the start of payload */
  59837. u32 nPayload; /* Bytes of payload */
  59838. u16 nLocal; /* Amount of payload held locally, not on overflow */
  59839. u16 nSize; /* Size of the cell content on the main b-tree page */
  59840. };
  59841. /*
  59842. ** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
  59843. ** this will be declared corrupt. This value is calculated based on a
  59844. ** maximum database size of 2^31 pages a minimum fanout of 2 for a
  59845. ** root-node and 3 for all other internal nodes.
  59846. **
  59847. ** If a tree that appears to be taller than this is encountered, it is
  59848. ** assumed that the database is corrupt.
  59849. */
  59850. #define BTCURSOR_MAX_DEPTH 20
  59851. /*
  59852. ** A cursor is a pointer to a particular entry within a particular
  59853. ** b-tree within a database file.
  59854. **
  59855. ** The entry is identified by its MemPage and the index in
  59856. ** MemPage.aCell[] of the entry.
  59857. **
  59858. ** A single database file can be shared by two more database connections,
  59859. ** but cursors cannot be shared. Each cursor is associated with a
  59860. ** particular database connection identified BtCursor.pBtree.db.
  59861. **
  59862. ** Fields in this structure are accessed under the BtShared.mutex
  59863. ** found at self->pBt->mutex.
  59864. **
  59865. ** skipNext meaning:
  59866. ** The meaning of skipNext depends on the value of eState:
  59867. **
  59868. ** eState Meaning of skipNext
  59869. ** VALID skipNext is meaningless and is ignored
  59870. ** INVALID skipNext is meaningless and is ignored
  59871. ** SKIPNEXT sqlite3BtreeNext() is a no-op if skipNext>0 and
  59872. ** sqlite3BtreePrevious() is no-op if skipNext<0.
  59873. ** REQUIRESEEK restoreCursorPosition() restores the cursor to
  59874. ** eState=SKIPNEXT if skipNext!=0
  59875. ** FAULT skipNext holds the cursor fault error code.
  59876. */
  59877. struct BtCursor {
  59878. u8 eState; /* One of the CURSOR_XXX constants (see below) */
  59879. u8 curFlags; /* zero or more BTCF_* flags defined below */
  59880. u8 curPagerFlags; /* Flags to send to sqlite3PagerGet() */
  59881. u8 hints; /* As configured by CursorSetHints() */
  59882. int skipNext; /* Prev() is noop if negative. Next() is noop if positive.
  59883. ** Error code if eState==CURSOR_FAULT */
  59884. Btree *pBtree; /* The Btree to which this cursor belongs */
  59885. Pgno *aOverflow; /* Cache of overflow page locations */
  59886. void *pKey; /* Saved key that was cursor last known position */
  59887. /* All fields above are zeroed when the cursor is allocated. See
  59888. ** sqlite3BtreeCursorZero(). Fields that follow must be manually
  59889. ** initialized. */
  59890. #define BTCURSOR_FIRST_UNINIT pBt /* Name of first uninitialized field */
  59891. BtShared *pBt; /* The BtShared this cursor points to */
  59892. BtCursor *pNext; /* Forms a linked list of all cursors */
  59893. CellInfo info; /* A parse of the cell we are pointing at */
  59894. i64 nKey; /* Size of pKey, or last integer key */
  59895. Pgno pgnoRoot; /* The root page of this tree */
  59896. i8 iPage; /* Index of current page in apPage */
  59897. u8 curIntKey; /* Value of apPage[0]->intKey */
  59898. u16 ix; /* Current index for apPage[iPage] */
  59899. u16 aiIdx[BTCURSOR_MAX_DEPTH-1]; /* Current index in apPage[i] */
  59900. struct KeyInfo *pKeyInfo; /* Arg passed to comparison function */
  59901. MemPage *pPage; /* Current page */
  59902. MemPage *apPage[BTCURSOR_MAX_DEPTH-1]; /* Stack of parents of current page */
  59903. };
  59904. /*
  59905. ** Legal values for BtCursor.curFlags
  59906. */
  59907. #define BTCF_WriteFlag 0x01 /* True if a write cursor */
  59908. #define BTCF_ValidNKey 0x02 /* True if info.nKey is valid */
  59909. #define BTCF_ValidOvfl 0x04 /* True if aOverflow is valid */
  59910. #define BTCF_AtLast 0x08 /* Cursor is pointing ot the last entry */
  59911. #define BTCF_Incrblob 0x10 /* True if an incremental I/O handle */
  59912. #define BTCF_Multiple 0x20 /* Maybe another cursor on the same btree */
  59913. #define BTCF_Pinned 0x40 /* Cursor is busy and cannot be moved */
  59914. /*
  59915. ** Potential values for BtCursor.eState.
  59916. **
  59917. ** CURSOR_INVALID:
  59918. ** Cursor does not point to a valid entry. This can happen (for example)
  59919. ** because the table is empty or because BtreeCursorFirst() has not been
  59920. ** called.
  59921. **
  59922. ** CURSOR_VALID:
  59923. ** Cursor points to a valid entry. getPayload() etc. may be called.
  59924. **
  59925. ** CURSOR_SKIPNEXT:
  59926. ** Cursor is valid except that the Cursor.skipNext field is non-zero
  59927. ** indicating that the next sqlite3BtreeNext() or sqlite3BtreePrevious()
  59928. ** operation should be a no-op.
  59929. **
  59930. ** CURSOR_REQUIRESEEK:
  59931. ** The table that this cursor was opened on still exists, but has been
  59932. ** modified since the cursor was last used. The cursor position is saved
  59933. ** in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in
  59934. ** this state, restoreCursorPosition() can be called to attempt to
  59935. ** seek the cursor to the saved position.
  59936. **
  59937. ** CURSOR_FAULT:
  59938. ** An unrecoverable error (an I/O error or a malloc failure) has occurred
  59939. ** on a different connection that shares the BtShared cache with this
  59940. ** cursor. The error has left the cache in an inconsistent state.
  59941. ** Do nothing else with this cursor. Any attempt to use the cursor
  59942. ** should return the error code stored in BtCursor.skipNext
  59943. */
  59944. #define CURSOR_VALID 0
  59945. #define CURSOR_INVALID 1
  59946. #define CURSOR_SKIPNEXT 2
  59947. #define CURSOR_REQUIRESEEK 3
  59948. #define CURSOR_FAULT 4
  59949. /*
  59950. ** The database page the PENDING_BYTE occupies. This page is never used.
  59951. */
  59952. # define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt)
  59953. /*
  59954. ** These macros define the location of the pointer-map entry for a
  59955. ** database page. The first argument to each is the number of usable
  59956. ** bytes on each page of the database (often 1024). The second is the
  59957. ** page number to look up in the pointer map.
  59958. **
  59959. ** PTRMAP_PAGENO returns the database page number of the pointer-map
  59960. ** page that stores the required pointer. PTRMAP_PTROFFSET returns
  59961. ** the offset of the requested map entry.
  59962. **
  59963. ** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
  59964. ** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
  59965. ** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
  59966. ** this test.
  59967. */
  59968. #define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
  59969. #define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
  59970. #define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
  59971. /*
  59972. ** The pointer map is a lookup table that identifies the parent page for
  59973. ** each child page in the database file. The parent page is the page that
  59974. ** contains a pointer to the child. Every page in the database contains
  59975. ** 0 or 1 parent pages. (In this context 'database page' refers
  59976. ** to any page that is not part of the pointer map itself.) Each pointer map
  59977. ** entry consists of a single byte 'type' and a 4 byte parent page number.
  59978. ** The PTRMAP_XXX identifiers below are the valid types.
  59979. **
  59980. ** The purpose of the pointer map is to facility moving pages from one
  59981. ** position in the file to another as part of autovacuum. When a page
  59982. ** is moved, the pointer in its parent must be updated to point to the
  59983. ** new location. The pointer map is used to locate the parent page quickly.
  59984. **
  59985. ** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
  59986. ** used in this case.
  59987. **
  59988. ** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number
  59989. ** is not used in this case.
  59990. **
  59991. ** PTRMAP_OVERFLOW1: The database page is the first page in a list of
  59992. ** overflow pages. The page number identifies the page that
  59993. ** contains the cell with a pointer to this overflow page.
  59994. **
  59995. ** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
  59996. ** overflow pages. The page-number identifies the previous
  59997. ** page in the overflow page list.
  59998. **
  59999. ** PTRMAP_BTREE: The database page is a non-root btree page. The page number
  60000. ** identifies the parent page in the btree.
  60001. */
  60002. #define PTRMAP_ROOTPAGE 1
  60003. #define PTRMAP_FREEPAGE 2
  60004. #define PTRMAP_OVERFLOW1 3
  60005. #define PTRMAP_OVERFLOW2 4
  60006. #define PTRMAP_BTREE 5
  60007. /* A bunch of assert() statements to check the transaction state variables
  60008. ** of handle p (type Btree*) are internally consistent.
  60009. */
  60010. #define btreeIntegrity(p) \
  60011. assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
  60012. assert( p->pBt->inTransaction>=p->inTrans );
  60013. /*
  60014. ** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
  60015. ** if the database supports auto-vacuum or not. Because it is used
  60016. ** within an expression that is an argument to another macro
  60017. ** (sqliteMallocRaw), it is not possible to use conditional compilation.
  60018. ** So, this macro is defined instead.
  60019. */
  60020. #ifndef SQLITE_OMIT_AUTOVACUUM
  60021. #define ISAUTOVACUUM (pBt->autoVacuum)
  60022. #else
  60023. #define ISAUTOVACUUM 0
  60024. #endif
  60025. /*
  60026. ** This structure is passed around through all the sanity checking routines
  60027. ** in order to keep track of some global state information.
  60028. **
  60029. ** The aRef[] array is allocated so that there is 1 bit for each page in
  60030. ** the database. As the integrity-check proceeds, for each page used in
  60031. ** the database the corresponding bit is set. This allows integrity-check to
  60032. ** detect pages that are used twice and orphaned pages (both of which
  60033. ** indicate corruption).
  60034. */
  60035. typedef struct IntegrityCk IntegrityCk;
  60036. struct IntegrityCk {
  60037. BtShared *pBt; /* The tree being checked out */
  60038. Pager *pPager; /* The associated pager. Also accessible by pBt->pPager */
  60039. u8 *aPgRef; /* 1 bit per page in the db (see above) */
  60040. Pgno nPage; /* Number of pages in the database */
  60041. int mxErr; /* Stop accumulating errors when this reaches zero */
  60042. int nErr; /* Number of messages written to zErrMsg so far */
  60043. int mallocFailed; /* A memory allocation error has occurred */
  60044. const char *zPfx; /* Error message prefix */
  60045. int v1, v2; /* Values for up to two %d fields in zPfx */
  60046. StrAccum errMsg; /* Accumulate the error message text here */
  60047. u32 *heap; /* Min-heap used for analyzing cell coverage */
  60048. sqlite3 *db; /* Database connection running the check */
  60049. };
  60050. /*
  60051. ** Routines to read or write a two- and four-byte big-endian integer values.
  60052. */
  60053. #define get2byte(x) ((x)[0]<<8 | (x)[1])
  60054. #define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v))
  60055. #define get4byte sqlite3Get4byte
  60056. #define put4byte sqlite3Put4byte
  60057. /*
  60058. ** get2byteAligned(), unlike get2byte(), requires that its argument point to a
  60059. ** two-byte aligned address. get2bytea() is only used for accessing the
  60060. ** cell addresses in a btree header.
  60061. */
  60062. #if SQLITE_BYTEORDER==4321
  60063. # define get2byteAligned(x) (*(u16*)(x))
  60064. #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4008000
  60065. # define get2byteAligned(x) __builtin_bswap16(*(u16*)(x))
  60066. #elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
  60067. # define get2byteAligned(x) _byteswap_ushort(*(u16*)(x))
  60068. #else
  60069. # define get2byteAligned(x) ((x)[0]<<8 | (x)[1])
  60070. #endif
  60071. /************** End of btreeInt.h ********************************************/
  60072. /************** Continuing where we left off in btmutex.c ********************/
  60073. #ifndef SQLITE_OMIT_SHARED_CACHE
  60074. #if SQLITE_THREADSAFE
  60075. /*
  60076. ** Obtain the BtShared mutex associated with B-Tree handle p. Also,
  60077. ** set BtShared.db to the database handle associated with p and the
  60078. ** p->locked boolean to true.
  60079. */
  60080. static void lockBtreeMutex(Btree *p){
  60081. assert( p->locked==0 );
  60082. assert( sqlite3_mutex_notheld(p->pBt->mutex) );
  60083. assert( sqlite3_mutex_held(p->db->mutex) );
  60084. sqlite3_mutex_enter(p->pBt->mutex);
  60085. p->pBt->db = p->db;
  60086. p->locked = 1;
  60087. }
  60088. /*
  60089. ** Release the BtShared mutex associated with B-Tree handle p and
  60090. ** clear the p->locked boolean.
  60091. */
  60092. static void SQLITE_NOINLINE unlockBtreeMutex(Btree *p){
  60093. BtShared *pBt = p->pBt;
  60094. assert( p->locked==1 );
  60095. assert( sqlite3_mutex_held(pBt->mutex) );
  60096. assert( sqlite3_mutex_held(p->db->mutex) );
  60097. assert( p->db==pBt->db );
  60098. sqlite3_mutex_leave(pBt->mutex);
  60099. p->locked = 0;
  60100. }
  60101. /* Forward reference */
  60102. static void SQLITE_NOINLINE btreeLockCarefully(Btree *p);
  60103. /*
  60104. ** Enter a mutex on the given BTree object.
  60105. **
  60106. ** If the object is not sharable, then no mutex is ever required
  60107. ** and this routine is a no-op. The underlying mutex is non-recursive.
  60108. ** But we keep a reference count in Btree.wantToLock so the behavior
  60109. ** of this interface is recursive.
  60110. **
  60111. ** To avoid deadlocks, multiple Btrees are locked in the same order
  60112. ** by all database connections. The p->pNext is a list of other
  60113. ** Btrees belonging to the same database connection as the p Btree
  60114. ** which need to be locked after p. If we cannot get a lock on
  60115. ** p, then first unlock all of the others on p->pNext, then wait
  60116. ** for the lock to become available on p, then relock all of the
  60117. ** subsequent Btrees that desire a lock.
  60118. */
  60119. SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
  60120. /* Some basic sanity checking on the Btree. The list of Btrees
  60121. ** connected by pNext and pPrev should be in sorted order by
  60122. ** Btree.pBt value. All elements of the list should belong to
  60123. ** the same connection. Only shared Btrees are on the list. */
  60124. assert( p->pNext==0 || p->pNext->pBt>p->pBt );
  60125. assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
  60126. assert( p->pNext==0 || p->pNext->db==p->db );
  60127. assert( p->pPrev==0 || p->pPrev->db==p->db );
  60128. assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
  60129. /* Check for locking consistency */
  60130. assert( !p->locked || p->wantToLock>0 );
  60131. assert( p->sharable || p->wantToLock==0 );
  60132. /* We should already hold a lock on the database connection */
  60133. assert( sqlite3_mutex_held(p->db->mutex) );
  60134. /* Unless the database is sharable and unlocked, then BtShared.db
  60135. ** should already be set correctly. */
  60136. assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db );
  60137. if( !p->sharable ) return;
  60138. p->wantToLock++;
  60139. if( p->locked ) return;
  60140. btreeLockCarefully(p);
  60141. }
  60142. /* This is a helper function for sqlite3BtreeLock(). By moving
  60143. ** complex, but seldom used logic, out of sqlite3BtreeLock() and
  60144. ** into this routine, we avoid unnecessary stack pointer changes
  60145. ** and thus help the sqlite3BtreeLock() routine to run much faster
  60146. ** in the common case.
  60147. */
  60148. static void SQLITE_NOINLINE btreeLockCarefully(Btree *p){
  60149. Btree *pLater;
  60150. /* In most cases, we should be able to acquire the lock we
  60151. ** want without having to go through the ascending lock
  60152. ** procedure that follows. Just be sure not to block.
  60153. */
  60154. if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
  60155. p->pBt->db = p->db;
  60156. p->locked = 1;
  60157. return;
  60158. }
  60159. /* To avoid deadlock, first release all locks with a larger
  60160. ** BtShared address. Then acquire our lock. Then reacquire
  60161. ** the other BtShared locks that we used to hold in ascending
  60162. ** order.
  60163. */
  60164. for(pLater=p->pNext; pLater; pLater=pLater->pNext){
  60165. assert( pLater->sharable );
  60166. assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
  60167. assert( !pLater->locked || pLater->wantToLock>0 );
  60168. if( pLater->locked ){
  60169. unlockBtreeMutex(pLater);
  60170. }
  60171. }
  60172. lockBtreeMutex(p);
  60173. for(pLater=p->pNext; pLater; pLater=pLater->pNext){
  60174. if( pLater->wantToLock ){
  60175. lockBtreeMutex(pLater);
  60176. }
  60177. }
  60178. }
  60179. /*
  60180. ** Exit the recursive mutex on a Btree.
  60181. */
  60182. SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){
  60183. assert( sqlite3_mutex_held(p->db->mutex) );
  60184. if( p->sharable ){
  60185. assert( p->wantToLock>0 );
  60186. p->wantToLock--;
  60187. if( p->wantToLock==0 ){
  60188. unlockBtreeMutex(p);
  60189. }
  60190. }
  60191. }
  60192. #ifndef NDEBUG
  60193. /*
  60194. ** Return true if the BtShared mutex is held on the btree, or if the
  60195. ** B-Tree is not marked as sharable.
  60196. **
  60197. ** This routine is used only from within assert() statements.
  60198. */
  60199. SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){
  60200. assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 );
  60201. assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db );
  60202. assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) );
  60203. assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) );
  60204. return (p->sharable==0 || p->locked);
  60205. }
  60206. #endif
  60207. /*
  60208. ** Enter the mutex on every Btree associated with a database
  60209. ** connection. This is needed (for example) prior to parsing
  60210. ** a statement since we will be comparing table and column names
  60211. ** against all schemas and we do not want those schemas being
  60212. ** reset out from under us.
  60213. **
  60214. ** There is a corresponding leave-all procedures.
  60215. **
  60216. ** Enter the mutexes in accending order by BtShared pointer address
  60217. ** to avoid the possibility of deadlock when two threads with
  60218. ** two or more btrees in common both try to lock all their btrees
  60219. ** at the same instant.
  60220. */
  60221. static void SQLITE_NOINLINE btreeEnterAll(sqlite3 *db){
  60222. int i;
  60223. int skipOk = 1;
  60224. Btree *p;
  60225. assert( sqlite3_mutex_held(db->mutex) );
  60226. for(i=0; i<db->nDb; i++){
  60227. p = db->aDb[i].pBt;
  60228. if( p && p->sharable ){
  60229. sqlite3BtreeEnter(p);
  60230. skipOk = 0;
  60231. }
  60232. }
  60233. db->noSharedCache = skipOk;
  60234. }
  60235. SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
  60236. if( db->noSharedCache==0 ) btreeEnterAll(db);
  60237. }
  60238. static void SQLITE_NOINLINE btreeLeaveAll(sqlite3 *db){
  60239. int i;
  60240. Btree *p;
  60241. assert( sqlite3_mutex_held(db->mutex) );
  60242. for(i=0; i<db->nDb; i++){
  60243. p = db->aDb[i].pBt;
  60244. if( p ) sqlite3BtreeLeave(p);
  60245. }
  60246. }
  60247. SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){
  60248. if( db->noSharedCache==0 ) btreeLeaveAll(db);
  60249. }
  60250. #ifndef NDEBUG
  60251. /*
  60252. ** Return true if the current thread holds the database connection
  60253. ** mutex and all required BtShared mutexes.
  60254. **
  60255. ** This routine is used inside assert() statements only.
  60256. */
  60257. SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){
  60258. int i;
  60259. if( !sqlite3_mutex_held(db->mutex) ){
  60260. return 0;
  60261. }
  60262. for(i=0; i<db->nDb; i++){
  60263. Btree *p;
  60264. p = db->aDb[i].pBt;
  60265. if( p && p->sharable &&
  60266. (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
  60267. return 0;
  60268. }
  60269. }
  60270. return 1;
  60271. }
  60272. #endif /* NDEBUG */
  60273. #ifndef NDEBUG
  60274. /*
  60275. ** Return true if the correct mutexes are held for accessing the
  60276. ** db->aDb[iDb].pSchema structure. The mutexes required for schema
  60277. ** access are:
  60278. **
  60279. ** (1) The mutex on db
  60280. ** (2) if iDb!=1, then the mutex on db->aDb[iDb].pBt.
  60281. **
  60282. ** If pSchema is not NULL, then iDb is computed from pSchema and
  60283. ** db using sqlite3SchemaToIndex().
  60284. */
  60285. SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3 *db, int iDb, Schema *pSchema){
  60286. Btree *p;
  60287. assert( db!=0 );
  60288. if( pSchema ) iDb = sqlite3SchemaToIndex(db, pSchema);
  60289. assert( iDb>=0 && iDb<db->nDb );
  60290. if( !sqlite3_mutex_held(db->mutex) ) return 0;
  60291. if( iDb==1 ) return 1;
  60292. p = db->aDb[iDb].pBt;
  60293. assert( p!=0 );
  60294. return p->sharable==0 || p->locked==1;
  60295. }
  60296. #endif /* NDEBUG */
  60297. #else /* SQLITE_THREADSAFE>0 above. SQLITE_THREADSAFE==0 below */
  60298. /*
  60299. ** The following are special cases for mutex enter routines for use
  60300. ** in single threaded applications that use shared cache. Except for
  60301. ** these two routines, all mutex operations are no-ops in that case and
  60302. ** are null #defines in btree.h.
  60303. **
  60304. ** If shared cache is disabled, then all btree mutex routines, including
  60305. ** the ones below, are no-ops and are null #defines in btree.h.
  60306. */
  60307. SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
  60308. p->pBt->db = p->db;
  60309. }
  60310. SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
  60311. int i;
  60312. for(i=0; i<db->nDb; i++){
  60313. Btree *p = db->aDb[i].pBt;
  60314. if( p ){
  60315. p->pBt->db = p->db;
  60316. }
  60317. }
  60318. }
  60319. #endif /* if SQLITE_THREADSAFE */
  60320. #ifndef SQLITE_OMIT_INCRBLOB
  60321. /*
  60322. ** Enter a mutex on a Btree given a cursor owned by that Btree.
  60323. **
  60324. ** These entry points are used by incremental I/O only. Enter() is required
  60325. ** any time OMIT_SHARED_CACHE is not defined, regardless of whether or not
  60326. ** the build is threadsafe. Leave() is only required by threadsafe builds.
  60327. */
  60328. SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){
  60329. sqlite3BtreeEnter(pCur->pBtree);
  60330. }
  60331. # if SQLITE_THREADSAFE
  60332. SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){
  60333. sqlite3BtreeLeave(pCur->pBtree);
  60334. }
  60335. # endif
  60336. #endif /* ifndef SQLITE_OMIT_INCRBLOB */
  60337. #endif /* ifndef SQLITE_OMIT_SHARED_CACHE */
  60338. /************** End of btmutex.c *********************************************/
  60339. /************** Begin file btree.c *******************************************/
  60340. /*
  60341. ** 2004 April 6
  60342. **
  60343. ** The author disclaims copyright to this source code. In place of
  60344. ** a legal notice, here is a blessing:
  60345. **
  60346. ** May you do good and not evil.
  60347. ** May you find forgiveness for yourself and forgive others.
  60348. ** May you share freely, never taking more than you give.
  60349. **
  60350. *************************************************************************
  60351. ** This file implements an external (disk-based) database using BTrees.
  60352. ** See the header comment on "btreeInt.h" for additional information.
  60353. ** Including a description of file format and an overview of operation.
  60354. */
  60355. /* #include "btreeInt.h" */
  60356. /*
  60357. ** The header string that appears at the beginning of every
  60358. ** SQLite database.
  60359. */
  60360. static const char zMagicHeader[] = SQLITE_FILE_HEADER;
  60361. /*
  60362. ** Set this global variable to 1 to enable tracing using the TRACE
  60363. ** macro.
  60364. */
  60365. #if 0
  60366. int sqlite3BtreeTrace=1; /* True to enable tracing */
  60367. # define TRACE(X) if(sqlite3BtreeTrace){printf X;fflush(stdout);}
  60368. #else
  60369. # define TRACE(X)
  60370. #endif
  60371. /*
  60372. ** Extract a 2-byte big-endian integer from an array of unsigned bytes.
  60373. ** But if the value is zero, make it 65536.
  60374. **
  60375. ** This routine is used to extract the "offset to cell content area" value
  60376. ** from the header of a btree page. If the page size is 65536 and the page
  60377. ** is empty, the offset should be 65536, but the 2-byte value stores zero.
  60378. ** This routine makes the necessary adjustment to 65536.
  60379. */
  60380. #define get2byteNotZero(X) (((((int)get2byte(X))-1)&0xffff)+1)
  60381. /*
  60382. ** Values passed as the 5th argument to allocateBtreePage()
  60383. */
  60384. #define BTALLOC_ANY 0 /* Allocate any page */
  60385. #define BTALLOC_EXACT 1 /* Allocate exact page if possible */
  60386. #define BTALLOC_LE 2 /* Allocate any page <= the parameter */
  60387. /*
  60388. ** Macro IfNotOmitAV(x) returns (x) if SQLITE_OMIT_AUTOVACUUM is not
  60389. ** defined, or 0 if it is. For example:
  60390. **
  60391. ** bIncrVacuum = IfNotOmitAV(pBtShared->incrVacuum);
  60392. */
  60393. #ifndef SQLITE_OMIT_AUTOVACUUM
  60394. #define IfNotOmitAV(expr) (expr)
  60395. #else
  60396. #define IfNotOmitAV(expr) 0
  60397. #endif
  60398. #ifndef SQLITE_OMIT_SHARED_CACHE
  60399. /*
  60400. ** A list of BtShared objects that are eligible for participation
  60401. ** in shared cache. This variable has file scope during normal builds,
  60402. ** but the test harness needs to access it so we make it global for
  60403. ** test builds.
  60404. **
  60405. ** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER.
  60406. */
  60407. #ifdef SQLITE_TEST
  60408. SQLITE_PRIVATE BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
  60409. #else
  60410. static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
  60411. #endif
  60412. #endif /* SQLITE_OMIT_SHARED_CACHE */
  60413. #ifndef SQLITE_OMIT_SHARED_CACHE
  60414. /*
  60415. ** Enable or disable the shared pager and schema features.
  60416. **
  60417. ** This routine has no effect on existing database connections.
  60418. ** The shared cache setting effects only future calls to
  60419. ** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
  60420. */
  60421. SQLITE_API int sqlite3_enable_shared_cache(int enable){
  60422. sqlite3GlobalConfig.sharedCacheEnabled = enable;
  60423. return SQLITE_OK;
  60424. }
  60425. #endif
  60426. #ifdef SQLITE_OMIT_SHARED_CACHE
  60427. /*
  60428. ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
  60429. ** and clearAllSharedCacheTableLocks()
  60430. ** manipulate entries in the BtShared.pLock linked list used to store
  60431. ** shared-cache table level locks. If the library is compiled with the
  60432. ** shared-cache feature disabled, then there is only ever one user
  60433. ** of each BtShared structure and so this locking is not necessary.
  60434. ** So define the lock related functions as no-ops.
  60435. */
  60436. #define querySharedCacheTableLock(a,b,c) SQLITE_OK
  60437. #define setSharedCacheTableLock(a,b,c) SQLITE_OK
  60438. #define clearAllSharedCacheTableLocks(a)
  60439. #define downgradeAllSharedCacheTableLocks(a)
  60440. #define hasSharedCacheTableLock(a,b,c,d) 1
  60441. #define hasReadConflicts(a, b) 0
  60442. #endif
  60443. /*
  60444. ** Implementation of the SQLITE_CORRUPT_PAGE() macro. Takes a single
  60445. ** (MemPage*) as an argument. The (MemPage*) must not be NULL.
  60446. **
  60447. ** If SQLITE_DEBUG is not defined, then this macro is equivalent to
  60448. ** SQLITE_CORRUPT_BKPT. Or, if SQLITE_DEBUG is set, then the log message
  60449. ** normally produced as a side-effect of SQLITE_CORRUPT_BKPT is augmented
  60450. ** with the page number and filename associated with the (MemPage*).
  60451. */
  60452. #ifdef SQLITE_DEBUG
  60453. int corruptPageError(int lineno, MemPage *p){
  60454. char *zMsg;
  60455. sqlite3BeginBenignMalloc();
  60456. zMsg = sqlite3_mprintf("database corruption page %d of %s",
  60457. (int)p->pgno, sqlite3PagerFilename(p->pBt->pPager, 0)
  60458. );
  60459. sqlite3EndBenignMalloc();
  60460. if( zMsg ){
  60461. sqlite3ReportError(SQLITE_CORRUPT, lineno, zMsg);
  60462. }
  60463. sqlite3_free(zMsg);
  60464. return SQLITE_CORRUPT_BKPT;
  60465. }
  60466. # define SQLITE_CORRUPT_PAGE(pMemPage) corruptPageError(__LINE__, pMemPage)
  60467. #else
  60468. # define SQLITE_CORRUPT_PAGE(pMemPage) SQLITE_CORRUPT_PGNO(pMemPage->pgno)
  60469. #endif
  60470. #ifndef SQLITE_OMIT_SHARED_CACHE
  60471. #ifdef SQLITE_DEBUG
  60472. /*
  60473. **** This function is only used as part of an assert() statement. ***
  60474. **
  60475. ** Check to see if pBtree holds the required locks to read or write to the
  60476. ** table with root page iRoot. Return 1 if it does and 0 if not.
  60477. **
  60478. ** For example, when writing to a table with root-page iRoot via
  60479. ** Btree connection pBtree:
  60480. **
  60481. ** assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
  60482. **
  60483. ** When writing to an index that resides in a sharable database, the
  60484. ** caller should have first obtained a lock specifying the root page of
  60485. ** the corresponding table. This makes things a bit more complicated,
  60486. ** as this module treats each table as a separate structure. To determine
  60487. ** the table corresponding to the index being written, this
  60488. ** function has to search through the database schema.
  60489. **
  60490. ** Instead of a lock on the table/index rooted at page iRoot, the caller may
  60491. ** hold a write-lock on the schema table (root page 1). This is also
  60492. ** acceptable.
  60493. */
  60494. static int hasSharedCacheTableLock(
  60495. Btree *pBtree, /* Handle that must hold lock */
  60496. Pgno iRoot, /* Root page of b-tree */
  60497. int isIndex, /* True if iRoot is the root of an index b-tree */
  60498. int eLockType /* Required lock type (READ_LOCK or WRITE_LOCK) */
  60499. ){
  60500. Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
  60501. Pgno iTab = 0;
  60502. BtLock *pLock;
  60503. /* If this database is not shareable, or if the client is reading
  60504. ** and has the read-uncommitted flag set, then no lock is required.
  60505. ** Return true immediately.
  60506. */
  60507. if( (pBtree->sharable==0)
  60508. || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommit))
  60509. ){
  60510. return 1;
  60511. }
  60512. /* If the client is reading or writing an index and the schema is
  60513. ** not loaded, then it is too difficult to actually check to see if
  60514. ** the correct locks are held. So do not bother - just return true.
  60515. ** This case does not come up very often anyhow.
  60516. */
  60517. if( isIndex && (!pSchema || (pSchema->schemaFlags&DB_SchemaLoaded)==0) ){
  60518. return 1;
  60519. }
  60520. /* Figure out the root-page that the lock should be held on. For table
  60521. ** b-trees, this is just the root page of the b-tree being read or
  60522. ** written. For index b-trees, it is the root page of the associated
  60523. ** table. */
  60524. if( isIndex ){
  60525. HashElem *p;
  60526. for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
  60527. Index *pIdx = (Index *)sqliteHashData(p);
  60528. if( pIdx->tnum==(int)iRoot ){
  60529. if( iTab ){
  60530. /* Two or more indexes share the same root page. There must
  60531. ** be imposter tables. So just return true. The assert is not
  60532. ** useful in that case. */
  60533. return 1;
  60534. }
  60535. iTab = pIdx->pTable->tnum;
  60536. }
  60537. }
  60538. }else{
  60539. iTab = iRoot;
  60540. }
  60541. /* Search for the required lock. Either a write-lock on root-page iTab, a
  60542. ** write-lock on the schema table, or (if the client is reading) a
  60543. ** read-lock on iTab will suffice. Return 1 if any of these are found. */
  60544. for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
  60545. if( pLock->pBtree==pBtree
  60546. && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
  60547. && pLock->eLock>=eLockType
  60548. ){
  60549. return 1;
  60550. }
  60551. }
  60552. /* Failed to find the required lock. */
  60553. return 0;
  60554. }
  60555. #endif /* SQLITE_DEBUG */
  60556. #ifdef SQLITE_DEBUG
  60557. /*
  60558. **** This function may be used as part of assert() statements only. ****
  60559. **
  60560. ** Return true if it would be illegal for pBtree to write into the
  60561. ** table or index rooted at iRoot because other shared connections are
  60562. ** simultaneously reading that same table or index.
  60563. **
  60564. ** It is illegal for pBtree to write if some other Btree object that
  60565. ** shares the same BtShared object is currently reading or writing
  60566. ** the iRoot table. Except, if the other Btree object has the
  60567. ** read-uncommitted flag set, then it is OK for the other object to
  60568. ** have a read cursor.
  60569. **
  60570. ** For example, before writing to any part of the table or index
  60571. ** rooted at page iRoot, one should call:
  60572. **
  60573. ** assert( !hasReadConflicts(pBtree, iRoot) );
  60574. */
  60575. static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
  60576. BtCursor *p;
  60577. for(p=pBtree->pBt->pCursor; p; p=p->pNext){
  60578. if( p->pgnoRoot==iRoot
  60579. && p->pBtree!=pBtree
  60580. && 0==(p->pBtree->db->flags & SQLITE_ReadUncommit)
  60581. ){
  60582. return 1;
  60583. }
  60584. }
  60585. return 0;
  60586. }
  60587. #endif /* #ifdef SQLITE_DEBUG */
  60588. /*
  60589. ** Query to see if Btree handle p may obtain a lock of type eLock
  60590. ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
  60591. ** SQLITE_OK if the lock may be obtained (by calling
  60592. ** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
  60593. */
  60594. static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
  60595. BtShared *pBt = p->pBt;
  60596. BtLock *pIter;
  60597. assert( sqlite3BtreeHoldsMutex(p) );
  60598. assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
  60599. assert( p->db!=0 );
  60600. assert( !(p->db->flags&SQLITE_ReadUncommit)||eLock==WRITE_LOCK||iTab==1 );
  60601. /* If requesting a write-lock, then the Btree must have an open write
  60602. ** transaction on this file. And, obviously, for this to be so there
  60603. ** must be an open write transaction on the file itself.
  60604. */
  60605. assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
  60606. assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
  60607. /* This routine is a no-op if the shared-cache is not enabled */
  60608. if( !p->sharable ){
  60609. return SQLITE_OK;
  60610. }
  60611. /* If some other connection is holding an exclusive lock, the
  60612. ** requested lock may not be obtained.
  60613. */
  60614. if( pBt->pWriter!=p && (pBt->btsFlags & BTS_EXCLUSIVE)!=0 ){
  60615. sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
  60616. return SQLITE_LOCKED_SHAREDCACHE;
  60617. }
  60618. for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
  60619. /* The condition (pIter->eLock!=eLock) in the following if(...)
  60620. ** statement is a simplification of:
  60621. **
  60622. ** (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
  60623. **
  60624. ** since we know that if eLock==WRITE_LOCK, then no other connection
  60625. ** may hold a WRITE_LOCK on any table in this file (since there can
  60626. ** only be a single writer).
  60627. */
  60628. assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
  60629. assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
  60630. if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
  60631. sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
  60632. if( eLock==WRITE_LOCK ){
  60633. assert( p==pBt->pWriter );
  60634. pBt->btsFlags |= BTS_PENDING;
  60635. }
  60636. return SQLITE_LOCKED_SHAREDCACHE;
  60637. }
  60638. }
  60639. return SQLITE_OK;
  60640. }
  60641. #endif /* !SQLITE_OMIT_SHARED_CACHE */
  60642. #ifndef SQLITE_OMIT_SHARED_CACHE
  60643. /*
  60644. ** Add a lock on the table with root-page iTable to the shared-btree used
  60645. ** by Btree handle p. Parameter eLock must be either READ_LOCK or
  60646. ** WRITE_LOCK.
  60647. **
  60648. ** This function assumes the following:
  60649. **
  60650. ** (a) The specified Btree object p is connected to a sharable
  60651. ** database (one with the BtShared.sharable flag set), and
  60652. **
  60653. ** (b) No other Btree objects hold a lock that conflicts
  60654. ** with the requested lock (i.e. querySharedCacheTableLock() has
  60655. ** already been called and returned SQLITE_OK).
  60656. **
  60657. ** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM
  60658. ** is returned if a malloc attempt fails.
  60659. */
  60660. static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
  60661. BtShared *pBt = p->pBt;
  60662. BtLock *pLock = 0;
  60663. BtLock *pIter;
  60664. assert( sqlite3BtreeHoldsMutex(p) );
  60665. assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
  60666. assert( p->db!=0 );
  60667. /* A connection with the read-uncommitted flag set will never try to
  60668. ** obtain a read-lock using this function. The only read-lock obtained
  60669. ** by a connection in read-uncommitted mode is on the sqlite_master
  60670. ** table, and that lock is obtained in BtreeBeginTrans(). */
  60671. assert( 0==(p->db->flags&SQLITE_ReadUncommit) || eLock==WRITE_LOCK );
  60672. /* This function should only be called on a sharable b-tree after it
  60673. ** has been determined that no other b-tree holds a conflicting lock. */
  60674. assert( p->sharable );
  60675. assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
  60676. /* First search the list for an existing lock on this table. */
  60677. for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
  60678. if( pIter->iTable==iTable && pIter->pBtree==p ){
  60679. pLock = pIter;
  60680. break;
  60681. }
  60682. }
  60683. /* If the above search did not find a BtLock struct associating Btree p
  60684. ** with table iTable, allocate one and link it into the list.
  60685. */
  60686. if( !pLock ){
  60687. pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
  60688. if( !pLock ){
  60689. return SQLITE_NOMEM_BKPT;
  60690. }
  60691. pLock->iTable = iTable;
  60692. pLock->pBtree = p;
  60693. pLock->pNext = pBt->pLock;
  60694. pBt->pLock = pLock;
  60695. }
  60696. /* Set the BtLock.eLock variable to the maximum of the current lock
  60697. ** and the requested lock. This means if a write-lock was already held
  60698. ** and a read-lock requested, we don't incorrectly downgrade the lock.
  60699. */
  60700. assert( WRITE_LOCK>READ_LOCK );
  60701. if( eLock>pLock->eLock ){
  60702. pLock->eLock = eLock;
  60703. }
  60704. return SQLITE_OK;
  60705. }
  60706. #endif /* !SQLITE_OMIT_SHARED_CACHE */
  60707. #ifndef SQLITE_OMIT_SHARED_CACHE
  60708. /*
  60709. ** Release all the table locks (locks obtained via calls to
  60710. ** the setSharedCacheTableLock() procedure) held by Btree object p.
  60711. **
  60712. ** This function assumes that Btree p has an open read or write
  60713. ** transaction. If it does not, then the BTS_PENDING flag
  60714. ** may be incorrectly cleared.
  60715. */
  60716. static void clearAllSharedCacheTableLocks(Btree *p){
  60717. BtShared *pBt = p->pBt;
  60718. BtLock **ppIter = &pBt->pLock;
  60719. assert( sqlite3BtreeHoldsMutex(p) );
  60720. assert( p->sharable || 0==*ppIter );
  60721. assert( p->inTrans>0 );
  60722. while( *ppIter ){
  60723. BtLock *pLock = *ppIter;
  60724. assert( (pBt->btsFlags & BTS_EXCLUSIVE)==0 || pBt->pWriter==pLock->pBtree );
  60725. assert( pLock->pBtree->inTrans>=pLock->eLock );
  60726. if( pLock->pBtree==p ){
  60727. *ppIter = pLock->pNext;
  60728. assert( pLock->iTable!=1 || pLock==&p->lock );
  60729. if( pLock->iTable!=1 ){
  60730. sqlite3_free(pLock);
  60731. }
  60732. }else{
  60733. ppIter = &pLock->pNext;
  60734. }
  60735. }
  60736. assert( (pBt->btsFlags & BTS_PENDING)==0 || pBt->pWriter );
  60737. if( pBt->pWriter==p ){
  60738. pBt->pWriter = 0;
  60739. pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
  60740. }else if( pBt->nTransaction==2 ){
  60741. /* This function is called when Btree p is concluding its
  60742. ** transaction. If there currently exists a writer, and p is not
  60743. ** that writer, then the number of locks held by connections other
  60744. ** than the writer must be about to drop to zero. In this case
  60745. ** set the BTS_PENDING flag to 0.
  60746. **
  60747. ** If there is not currently a writer, then BTS_PENDING must
  60748. ** be zero already. So this next line is harmless in that case.
  60749. */
  60750. pBt->btsFlags &= ~BTS_PENDING;
  60751. }
  60752. }
  60753. /*
  60754. ** This function changes all write-locks held by Btree p into read-locks.
  60755. */
  60756. static void downgradeAllSharedCacheTableLocks(Btree *p){
  60757. BtShared *pBt = p->pBt;
  60758. if( pBt->pWriter==p ){
  60759. BtLock *pLock;
  60760. pBt->pWriter = 0;
  60761. pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
  60762. for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
  60763. assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
  60764. pLock->eLock = READ_LOCK;
  60765. }
  60766. }
  60767. }
  60768. #endif /* SQLITE_OMIT_SHARED_CACHE */
  60769. static void releasePage(MemPage *pPage); /* Forward reference */
  60770. static void releasePageOne(MemPage *pPage); /* Forward reference */
  60771. static void releasePageNotNull(MemPage *pPage); /* Forward reference */
  60772. /*
  60773. ***** This routine is used inside of assert() only ****
  60774. **
  60775. ** Verify that the cursor holds the mutex on its BtShared
  60776. */
  60777. #ifdef SQLITE_DEBUG
  60778. static int cursorHoldsMutex(BtCursor *p){
  60779. return sqlite3_mutex_held(p->pBt->mutex);
  60780. }
  60781. /* Verify that the cursor and the BtShared agree about what is the current
  60782. ** database connetion. This is important in shared-cache mode. If the database
  60783. ** connection pointers get out-of-sync, it is possible for routines like
  60784. ** btreeInitPage() to reference an stale connection pointer that references a
  60785. ** a connection that has already closed. This routine is used inside assert()
  60786. ** statements only and for the purpose of double-checking that the btree code
  60787. ** does keep the database connection pointers up-to-date.
  60788. */
  60789. static int cursorOwnsBtShared(BtCursor *p){
  60790. assert( cursorHoldsMutex(p) );
  60791. return (p->pBtree->db==p->pBt->db);
  60792. }
  60793. #endif
  60794. /*
  60795. ** Invalidate the overflow cache of the cursor passed as the first argument.
  60796. ** on the shared btree structure pBt.
  60797. */
  60798. #define invalidateOverflowCache(pCur) (pCur->curFlags &= ~BTCF_ValidOvfl)
  60799. /*
  60800. ** Invalidate the overflow page-list cache for all cursors opened
  60801. ** on the shared btree structure pBt.
  60802. */
  60803. static void invalidateAllOverflowCache(BtShared *pBt){
  60804. BtCursor *p;
  60805. assert( sqlite3_mutex_held(pBt->mutex) );
  60806. for(p=pBt->pCursor; p; p=p->pNext){
  60807. invalidateOverflowCache(p);
  60808. }
  60809. }
  60810. #ifndef SQLITE_OMIT_INCRBLOB
  60811. /*
  60812. ** This function is called before modifying the contents of a table
  60813. ** to invalidate any incrblob cursors that are open on the
  60814. ** row or one of the rows being modified.
  60815. **
  60816. ** If argument isClearTable is true, then the entire contents of the
  60817. ** table is about to be deleted. In this case invalidate all incrblob
  60818. ** cursors open on any row within the table with root-page pgnoRoot.
  60819. **
  60820. ** Otherwise, if argument isClearTable is false, then the row with
  60821. ** rowid iRow is being replaced or deleted. In this case invalidate
  60822. ** only those incrblob cursors open on that specific row.
  60823. */
  60824. static void invalidateIncrblobCursors(
  60825. Btree *pBtree, /* The database file to check */
  60826. Pgno pgnoRoot, /* The table that might be changing */
  60827. i64 iRow, /* The rowid that might be changing */
  60828. int isClearTable /* True if all rows are being deleted */
  60829. ){
  60830. BtCursor *p;
  60831. if( pBtree->hasIncrblobCur==0 ) return;
  60832. assert( sqlite3BtreeHoldsMutex(pBtree) );
  60833. pBtree->hasIncrblobCur = 0;
  60834. for(p=pBtree->pBt->pCursor; p; p=p->pNext){
  60835. if( (p->curFlags & BTCF_Incrblob)!=0 ){
  60836. pBtree->hasIncrblobCur = 1;
  60837. if( p->pgnoRoot==pgnoRoot && (isClearTable || p->info.nKey==iRow) ){
  60838. p->eState = CURSOR_INVALID;
  60839. }
  60840. }
  60841. }
  60842. }
  60843. #else
  60844. /* Stub function when INCRBLOB is omitted */
  60845. #define invalidateIncrblobCursors(w,x,y,z)
  60846. #endif /* SQLITE_OMIT_INCRBLOB */
  60847. /*
  60848. ** Set bit pgno of the BtShared.pHasContent bitvec. This is called
  60849. ** when a page that previously contained data becomes a free-list leaf
  60850. ** page.
  60851. **
  60852. ** The BtShared.pHasContent bitvec exists to work around an obscure
  60853. ** bug caused by the interaction of two useful IO optimizations surrounding
  60854. ** free-list leaf pages:
  60855. **
  60856. ** 1) When all data is deleted from a page and the page becomes
  60857. ** a free-list leaf page, the page is not written to the database
  60858. ** (as free-list leaf pages contain no meaningful data). Sometimes
  60859. ** such a page is not even journalled (as it will not be modified,
  60860. ** why bother journalling it?).
  60861. **
  60862. ** 2) When a free-list leaf page is reused, its content is not read
  60863. ** from the database or written to the journal file (why should it
  60864. ** be, if it is not at all meaningful?).
  60865. **
  60866. ** By themselves, these optimizations work fine and provide a handy
  60867. ** performance boost to bulk delete or insert operations. However, if
  60868. ** a page is moved to the free-list and then reused within the same
  60869. ** transaction, a problem comes up. If the page is not journalled when
  60870. ** it is moved to the free-list and it is also not journalled when it
  60871. ** is extracted from the free-list and reused, then the original data
  60872. ** may be lost. In the event of a rollback, it may not be possible
  60873. ** to restore the database to its original configuration.
  60874. **
  60875. ** The solution is the BtShared.pHasContent bitvec. Whenever a page is
  60876. ** moved to become a free-list leaf page, the corresponding bit is
  60877. ** set in the bitvec. Whenever a leaf page is extracted from the free-list,
  60878. ** optimization 2 above is omitted if the corresponding bit is already
  60879. ** set in BtShared.pHasContent. The contents of the bitvec are cleared
  60880. ** at the end of every transaction.
  60881. */
  60882. static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
  60883. int rc = SQLITE_OK;
  60884. if( !pBt->pHasContent ){
  60885. assert( pgno<=pBt->nPage );
  60886. pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
  60887. if( !pBt->pHasContent ){
  60888. rc = SQLITE_NOMEM_BKPT;
  60889. }
  60890. }
  60891. if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
  60892. rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
  60893. }
  60894. return rc;
  60895. }
  60896. /*
  60897. ** Query the BtShared.pHasContent vector.
  60898. **
  60899. ** This function is called when a free-list leaf page is removed from the
  60900. ** free-list for reuse. It returns false if it is safe to retrieve the
  60901. ** page from the pager layer with the 'no-content' flag set. True otherwise.
  60902. */
  60903. static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
  60904. Bitvec *p = pBt->pHasContent;
  60905. return p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTestNotNull(p, pgno));
  60906. }
  60907. /*
  60908. ** Clear (destroy) the BtShared.pHasContent bitvec. This should be
  60909. ** invoked at the conclusion of each write-transaction.
  60910. */
  60911. static void btreeClearHasContent(BtShared *pBt){
  60912. sqlite3BitvecDestroy(pBt->pHasContent);
  60913. pBt->pHasContent = 0;
  60914. }
  60915. /*
  60916. ** Release all of the apPage[] pages for a cursor.
  60917. */
  60918. static void btreeReleaseAllCursorPages(BtCursor *pCur){
  60919. int i;
  60920. if( pCur->iPage>=0 ){
  60921. for(i=0; i<pCur->iPage; i++){
  60922. releasePageNotNull(pCur->apPage[i]);
  60923. }
  60924. releasePageNotNull(pCur->pPage);
  60925. pCur->iPage = -1;
  60926. }
  60927. }
  60928. /*
  60929. ** The cursor passed as the only argument must point to a valid entry
  60930. ** when this function is called (i.e. have eState==CURSOR_VALID). This
  60931. ** function saves the current cursor key in variables pCur->nKey and
  60932. ** pCur->pKey. SQLITE_OK is returned if successful or an SQLite error
  60933. ** code otherwise.
  60934. **
  60935. ** If the cursor is open on an intkey table, then the integer key
  60936. ** (the rowid) is stored in pCur->nKey and pCur->pKey is left set to
  60937. ** NULL. If the cursor is open on a non-intkey table, then pCur->pKey is
  60938. ** set to point to a malloced buffer pCur->nKey bytes in size containing
  60939. ** the key.
  60940. */
  60941. static int saveCursorKey(BtCursor *pCur){
  60942. int rc = SQLITE_OK;
  60943. assert( CURSOR_VALID==pCur->eState );
  60944. assert( 0==pCur->pKey );
  60945. assert( cursorHoldsMutex(pCur) );
  60946. if( pCur->curIntKey ){
  60947. /* Only the rowid is required for a table btree */
  60948. pCur->nKey = sqlite3BtreeIntegerKey(pCur);
  60949. }else{
  60950. /* For an index btree, save the complete key content. It is possible
  60951. ** that the current key is corrupt. In that case, it is possible that
  60952. ** the sqlite3VdbeRecordUnpack() function may overread the buffer by
  60953. ** up to the size of 1 varint plus 1 8-byte value when the cursor
  60954. ** position is restored. Hence the 17 bytes of padding allocated
  60955. ** below. */
  60956. void *pKey;
  60957. pCur->nKey = sqlite3BtreePayloadSize(pCur);
  60958. pKey = sqlite3Malloc( pCur->nKey + 9 + 8 );
  60959. if( pKey ){
  60960. rc = sqlite3BtreePayload(pCur, 0, (int)pCur->nKey, pKey);
  60961. if( rc==SQLITE_OK ){
  60962. memset(((u8*)pKey)+pCur->nKey, 0, 9+8);
  60963. pCur->pKey = pKey;
  60964. }else{
  60965. sqlite3_free(pKey);
  60966. }
  60967. }else{
  60968. rc = SQLITE_NOMEM_BKPT;
  60969. }
  60970. }
  60971. assert( !pCur->curIntKey || !pCur->pKey );
  60972. return rc;
  60973. }
  60974. /*
  60975. ** Save the current cursor position in the variables BtCursor.nKey
  60976. ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
  60977. **
  60978. ** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
  60979. ** prior to calling this routine.
  60980. */
  60981. static int saveCursorPosition(BtCursor *pCur){
  60982. int rc;
  60983. assert( CURSOR_VALID==pCur->eState || CURSOR_SKIPNEXT==pCur->eState );
  60984. assert( 0==pCur->pKey );
  60985. assert( cursorHoldsMutex(pCur) );
  60986. if( pCur->curFlags & BTCF_Pinned ){
  60987. return SQLITE_CONSTRAINT_PINNED;
  60988. }
  60989. if( pCur->eState==CURSOR_SKIPNEXT ){
  60990. pCur->eState = CURSOR_VALID;
  60991. }else{
  60992. pCur->skipNext = 0;
  60993. }
  60994. rc = saveCursorKey(pCur);
  60995. if( rc==SQLITE_OK ){
  60996. btreeReleaseAllCursorPages(pCur);
  60997. pCur->eState = CURSOR_REQUIRESEEK;
  60998. }
  60999. pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl|BTCF_AtLast);
  61000. return rc;
  61001. }
  61002. /* Forward reference */
  61003. static int SQLITE_NOINLINE saveCursorsOnList(BtCursor*,Pgno,BtCursor*);
  61004. /*
  61005. ** Save the positions of all cursors (except pExcept) that are open on
  61006. ** the table with root-page iRoot. "Saving the cursor position" means that
  61007. ** the location in the btree is remembered in such a way that it can be
  61008. ** moved back to the same spot after the btree has been modified. This
  61009. ** routine is called just before cursor pExcept is used to modify the
  61010. ** table, for example in BtreeDelete() or BtreeInsert().
  61011. **
  61012. ** If there are two or more cursors on the same btree, then all such
  61013. ** cursors should have their BTCF_Multiple flag set. The btreeCursor()
  61014. ** routine enforces that rule. This routine only needs to be called in
  61015. ** the uncommon case when pExpect has the BTCF_Multiple flag set.
  61016. **
  61017. ** If pExpect!=NULL and if no other cursors are found on the same root-page,
  61018. ** then the BTCF_Multiple flag on pExpect is cleared, to avoid another
  61019. ** pointless call to this routine.
  61020. **
  61021. ** Implementation note: This routine merely checks to see if any cursors
  61022. ** need to be saved. It calls out to saveCursorsOnList() in the (unusual)
  61023. ** event that cursors are in need to being saved.
  61024. */
  61025. static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
  61026. BtCursor *p;
  61027. assert( sqlite3_mutex_held(pBt->mutex) );
  61028. assert( pExcept==0 || pExcept->pBt==pBt );
  61029. for(p=pBt->pCursor; p; p=p->pNext){
  61030. if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ) break;
  61031. }
  61032. if( p ) return saveCursorsOnList(p, iRoot, pExcept);
  61033. if( pExcept ) pExcept->curFlags &= ~BTCF_Multiple;
  61034. return SQLITE_OK;
  61035. }
  61036. /* This helper routine to saveAllCursors does the actual work of saving
  61037. ** the cursors if and when a cursor is found that actually requires saving.
  61038. ** The common case is that no cursors need to be saved, so this routine is
  61039. ** broken out from its caller to avoid unnecessary stack pointer movement.
  61040. */
  61041. static int SQLITE_NOINLINE saveCursorsOnList(
  61042. BtCursor *p, /* The first cursor that needs saving */
  61043. Pgno iRoot, /* Only save cursor with this iRoot. Save all if zero */
  61044. BtCursor *pExcept /* Do not save this cursor */
  61045. ){
  61046. do{
  61047. if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ){
  61048. if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
  61049. int rc = saveCursorPosition(p);
  61050. if( SQLITE_OK!=rc ){
  61051. return rc;
  61052. }
  61053. }else{
  61054. testcase( p->iPage>=0 );
  61055. btreeReleaseAllCursorPages(p);
  61056. }
  61057. }
  61058. p = p->pNext;
  61059. }while( p );
  61060. return SQLITE_OK;
  61061. }
  61062. /*
  61063. ** Clear the current cursor position.
  61064. */
  61065. SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *pCur){
  61066. assert( cursorHoldsMutex(pCur) );
  61067. sqlite3_free(pCur->pKey);
  61068. pCur->pKey = 0;
  61069. pCur->eState = CURSOR_INVALID;
  61070. }
  61071. /*
  61072. ** In this version of BtreeMoveto, pKey is a packed index record
  61073. ** such as is generated by the OP_MakeRecord opcode. Unpack the
  61074. ** record and then call BtreeMovetoUnpacked() to do the work.
  61075. */
  61076. static int btreeMoveto(
  61077. BtCursor *pCur, /* Cursor open on the btree to be searched */
  61078. const void *pKey, /* Packed key if the btree is an index */
  61079. i64 nKey, /* Integer key for tables. Size of pKey for indices */
  61080. int bias, /* Bias search to the high end */
  61081. int *pRes /* Write search results here */
  61082. ){
  61083. int rc; /* Status code */
  61084. UnpackedRecord *pIdxKey; /* Unpacked index key */
  61085. if( pKey ){
  61086. KeyInfo *pKeyInfo = pCur->pKeyInfo;
  61087. assert( nKey==(i64)(int)nKey );
  61088. pIdxKey = sqlite3VdbeAllocUnpackedRecord(pKeyInfo);
  61089. if( pIdxKey==0 ) return SQLITE_NOMEM_BKPT;
  61090. sqlite3VdbeRecordUnpack(pKeyInfo, (int)nKey, pKey, pIdxKey);
  61091. if( pIdxKey->nField==0 || pIdxKey->nField>pKeyInfo->nAllField ){
  61092. rc = SQLITE_CORRUPT_BKPT;
  61093. goto moveto_done;
  61094. }
  61095. }else{
  61096. pIdxKey = 0;
  61097. }
  61098. rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
  61099. moveto_done:
  61100. if( pIdxKey ){
  61101. sqlite3DbFree(pCur->pKeyInfo->db, pIdxKey);
  61102. }
  61103. return rc;
  61104. }
  61105. /*
  61106. ** Restore the cursor to the position it was in (or as close to as possible)
  61107. ** when saveCursorPosition() was called. Note that this call deletes the
  61108. ** saved position info stored by saveCursorPosition(), so there can be
  61109. ** at most one effective restoreCursorPosition() call after each
  61110. ** saveCursorPosition().
  61111. */
  61112. static int btreeRestoreCursorPosition(BtCursor *pCur){
  61113. int rc;
  61114. int skipNext = 0;
  61115. assert( cursorOwnsBtShared(pCur) );
  61116. assert( pCur->eState>=CURSOR_REQUIRESEEK );
  61117. if( pCur->eState==CURSOR_FAULT ){
  61118. return pCur->skipNext;
  61119. }
  61120. pCur->eState = CURSOR_INVALID;
  61121. if( sqlite3FaultSim(410) ){
  61122. rc = SQLITE_IOERR;
  61123. }else{
  61124. rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &skipNext);
  61125. }
  61126. if( rc==SQLITE_OK ){
  61127. sqlite3_free(pCur->pKey);
  61128. pCur->pKey = 0;
  61129. assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
  61130. if( skipNext ) pCur->skipNext = skipNext;
  61131. if( pCur->skipNext && pCur->eState==CURSOR_VALID ){
  61132. pCur->eState = CURSOR_SKIPNEXT;
  61133. }
  61134. }
  61135. return rc;
  61136. }
  61137. #define restoreCursorPosition(p) \
  61138. (p->eState>=CURSOR_REQUIRESEEK ? \
  61139. btreeRestoreCursorPosition(p) : \
  61140. SQLITE_OK)
  61141. /*
  61142. ** Determine whether or not a cursor has moved from the position where
  61143. ** it was last placed, or has been invalidated for any other reason.
  61144. ** Cursors can move when the row they are pointing at is deleted out
  61145. ** from under them, for example. Cursor might also move if a btree
  61146. ** is rebalanced.
  61147. **
  61148. ** Calling this routine with a NULL cursor pointer returns false.
  61149. **
  61150. ** Use the separate sqlite3BtreeCursorRestore() routine to restore a cursor
  61151. ** back to where it ought to be if this routine returns true.
  61152. */
  61153. SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur){
  61154. assert( EIGHT_BYTE_ALIGNMENT(pCur)
  61155. || pCur==sqlite3BtreeFakeValidCursor() );
  61156. assert( offsetof(BtCursor, eState)==0 );
  61157. assert( sizeof(pCur->eState)==1 );
  61158. return CURSOR_VALID != *(u8*)pCur;
  61159. }
  61160. /*
  61161. ** Return a pointer to a fake BtCursor object that will always answer
  61162. ** false to the sqlite3BtreeCursorHasMoved() routine above. The fake
  61163. ** cursor returned must not be used with any other Btree interface.
  61164. */
  61165. SQLITE_PRIVATE BtCursor *sqlite3BtreeFakeValidCursor(void){
  61166. static u8 fakeCursor = CURSOR_VALID;
  61167. assert( offsetof(BtCursor, eState)==0 );
  61168. return (BtCursor*)&fakeCursor;
  61169. }
  61170. /*
  61171. ** This routine restores a cursor back to its original position after it
  61172. ** has been moved by some outside activity (such as a btree rebalance or
  61173. ** a row having been deleted out from under the cursor).
  61174. **
  61175. ** On success, the *pDifferentRow parameter is false if the cursor is left
  61176. ** pointing at exactly the same row. *pDifferntRow is the row the cursor
  61177. ** was pointing to has been deleted, forcing the cursor to point to some
  61178. ** nearby row.
  61179. **
  61180. ** This routine should only be called for a cursor that just returned
  61181. ** TRUE from sqlite3BtreeCursorHasMoved().
  61182. */
  61183. SQLITE_PRIVATE int sqlite3BtreeCursorRestore(BtCursor *pCur, int *pDifferentRow){
  61184. int rc;
  61185. assert( pCur!=0 );
  61186. assert( pCur->eState!=CURSOR_VALID );
  61187. rc = restoreCursorPosition(pCur);
  61188. if( rc ){
  61189. *pDifferentRow = 1;
  61190. return rc;
  61191. }
  61192. if( pCur->eState!=CURSOR_VALID ){
  61193. *pDifferentRow = 1;
  61194. }else{
  61195. *pDifferentRow = 0;
  61196. }
  61197. return SQLITE_OK;
  61198. }
  61199. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  61200. /*
  61201. ** Provide hints to the cursor. The particular hint given (and the type
  61202. ** and number of the varargs parameters) is determined by the eHintType
  61203. ** parameter. See the definitions of the BTREE_HINT_* macros for details.
  61204. */
  61205. SQLITE_PRIVATE void sqlite3BtreeCursorHint(BtCursor *pCur, int eHintType, ...){
  61206. /* Used only by system that substitute their own storage engine */
  61207. }
  61208. #endif
  61209. /*
  61210. ** Provide flag hints to the cursor.
  61211. */
  61212. SQLITE_PRIVATE void sqlite3BtreeCursorHintFlags(BtCursor *pCur, unsigned x){
  61213. assert( x==BTREE_SEEK_EQ || x==BTREE_BULKLOAD || x==0 );
  61214. pCur->hints = x;
  61215. }
  61216. #ifndef SQLITE_OMIT_AUTOVACUUM
  61217. /*
  61218. ** Given a page number of a regular database page, return the page
  61219. ** number for the pointer-map page that contains the entry for the
  61220. ** input page number.
  61221. **
  61222. ** Return 0 (not a valid page) for pgno==1 since there is
  61223. ** no pointer map associated with page 1. The integrity_check logic
  61224. ** requires that ptrmapPageno(*,1)!=1.
  61225. */
  61226. static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
  61227. int nPagesPerMapPage;
  61228. Pgno iPtrMap, ret;
  61229. assert( sqlite3_mutex_held(pBt->mutex) );
  61230. if( pgno<2 ) return 0;
  61231. nPagesPerMapPage = (pBt->usableSize/5)+1;
  61232. iPtrMap = (pgno-2)/nPagesPerMapPage;
  61233. ret = (iPtrMap*nPagesPerMapPage) + 2;
  61234. if( ret==PENDING_BYTE_PAGE(pBt) ){
  61235. ret++;
  61236. }
  61237. return ret;
  61238. }
  61239. /*
  61240. ** Write an entry into the pointer map.
  61241. **
  61242. ** This routine updates the pointer map entry for page number 'key'
  61243. ** so that it maps to type 'eType' and parent page number 'pgno'.
  61244. **
  61245. ** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
  61246. ** a no-op. If an error occurs, the appropriate error code is written
  61247. ** into *pRC.
  61248. */
  61249. static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
  61250. DbPage *pDbPage; /* The pointer map page */
  61251. u8 *pPtrmap; /* The pointer map data */
  61252. Pgno iPtrmap; /* The pointer map page number */
  61253. int offset; /* Offset in pointer map page */
  61254. int rc; /* Return code from subfunctions */
  61255. if( *pRC ) return;
  61256. assert( sqlite3_mutex_held(pBt->mutex) );
  61257. /* The master-journal page number must never be used as a pointer map page */
  61258. assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
  61259. assert( pBt->autoVacuum );
  61260. if( key==0 ){
  61261. *pRC = SQLITE_CORRUPT_BKPT;
  61262. return;
  61263. }
  61264. iPtrmap = PTRMAP_PAGENO(pBt, key);
  61265. rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0);
  61266. if( rc!=SQLITE_OK ){
  61267. *pRC = rc;
  61268. return;
  61269. }
  61270. if( ((char*)sqlite3PagerGetExtra(pDbPage))[0]!=0 ){
  61271. /* The first byte of the extra data is the MemPage.isInit byte.
  61272. ** If that byte is set, it means this page is also being used
  61273. ** as a btree page. */
  61274. *pRC = SQLITE_CORRUPT_BKPT;
  61275. goto ptrmap_exit;
  61276. }
  61277. offset = PTRMAP_PTROFFSET(iPtrmap, key);
  61278. if( offset<0 ){
  61279. *pRC = SQLITE_CORRUPT_BKPT;
  61280. goto ptrmap_exit;
  61281. }
  61282. assert( offset <= (int)pBt->usableSize-5 );
  61283. pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
  61284. if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
  61285. TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
  61286. *pRC= rc = sqlite3PagerWrite(pDbPage);
  61287. if( rc==SQLITE_OK ){
  61288. pPtrmap[offset] = eType;
  61289. put4byte(&pPtrmap[offset+1], parent);
  61290. }
  61291. }
  61292. ptrmap_exit:
  61293. sqlite3PagerUnref(pDbPage);
  61294. }
  61295. /*
  61296. ** Read an entry from the pointer map.
  61297. **
  61298. ** This routine retrieves the pointer map entry for page 'key', writing
  61299. ** the type and parent page number to *pEType and *pPgno respectively.
  61300. ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
  61301. */
  61302. static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
  61303. DbPage *pDbPage; /* The pointer map page */
  61304. int iPtrmap; /* Pointer map page index */
  61305. u8 *pPtrmap; /* Pointer map page data */
  61306. int offset; /* Offset of entry in pointer map */
  61307. int rc;
  61308. assert( sqlite3_mutex_held(pBt->mutex) );
  61309. iPtrmap = PTRMAP_PAGENO(pBt, key);
  61310. rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0);
  61311. if( rc!=0 ){
  61312. return rc;
  61313. }
  61314. pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
  61315. offset = PTRMAP_PTROFFSET(iPtrmap, key);
  61316. if( offset<0 ){
  61317. sqlite3PagerUnref(pDbPage);
  61318. return SQLITE_CORRUPT_BKPT;
  61319. }
  61320. assert( offset <= (int)pBt->usableSize-5 );
  61321. assert( pEType!=0 );
  61322. *pEType = pPtrmap[offset];
  61323. if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
  61324. sqlite3PagerUnref(pDbPage);
  61325. if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_PGNO(iPtrmap);
  61326. return SQLITE_OK;
  61327. }
  61328. #else /* if defined SQLITE_OMIT_AUTOVACUUM */
  61329. #define ptrmapPut(w,x,y,z,rc)
  61330. #define ptrmapGet(w,x,y,z) SQLITE_OK
  61331. #define ptrmapPutOvflPtr(x, y, z, rc)
  61332. #endif
  61333. /*
  61334. ** Given a btree page and a cell index (0 means the first cell on
  61335. ** the page, 1 means the second cell, and so forth) return a pointer
  61336. ** to the cell content.
  61337. **
  61338. ** findCellPastPtr() does the same except it skips past the initial
  61339. ** 4-byte child pointer found on interior pages, if there is one.
  61340. **
  61341. ** This routine works only for pages that do not contain overflow cells.
  61342. */
  61343. #define findCell(P,I) \
  61344. ((P)->aData + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)])))
  61345. #define findCellPastPtr(P,I) \
  61346. ((P)->aDataOfst + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)])))
  61347. /*
  61348. ** This is common tail processing for btreeParseCellPtr() and
  61349. ** btreeParseCellPtrIndex() for the case when the cell does not fit entirely
  61350. ** on a single B-tree page. Make necessary adjustments to the CellInfo
  61351. ** structure.
  61352. */
  61353. static SQLITE_NOINLINE void btreeParseCellAdjustSizeForOverflow(
  61354. MemPage *pPage, /* Page containing the cell */
  61355. u8 *pCell, /* Pointer to the cell text. */
  61356. CellInfo *pInfo /* Fill in this structure */
  61357. ){
  61358. /* If the payload will not fit completely on the local page, we have
  61359. ** to decide how much to store locally and how much to spill onto
  61360. ** overflow pages. The strategy is to minimize the amount of unused
  61361. ** space on overflow pages while keeping the amount of local storage
  61362. ** in between minLocal and maxLocal.
  61363. **
  61364. ** Warning: changing the way overflow payload is distributed in any
  61365. ** way will result in an incompatible file format.
  61366. */
  61367. int minLocal; /* Minimum amount of payload held locally */
  61368. int maxLocal; /* Maximum amount of payload held locally */
  61369. int surplus; /* Overflow payload available for local storage */
  61370. minLocal = pPage->minLocal;
  61371. maxLocal = pPage->maxLocal;
  61372. surplus = minLocal + (pInfo->nPayload - minLocal)%(pPage->pBt->usableSize-4);
  61373. testcase( surplus==maxLocal );
  61374. testcase( surplus==maxLocal+1 );
  61375. if( surplus <= maxLocal ){
  61376. pInfo->nLocal = (u16)surplus;
  61377. }else{
  61378. pInfo->nLocal = (u16)minLocal;
  61379. }
  61380. pInfo->nSize = (u16)(&pInfo->pPayload[pInfo->nLocal] - pCell) + 4;
  61381. }
  61382. /*
  61383. ** The following routines are implementations of the MemPage.xParseCell()
  61384. ** method.
  61385. **
  61386. ** Parse a cell content block and fill in the CellInfo structure.
  61387. **
  61388. ** btreeParseCellPtr() => table btree leaf nodes
  61389. ** btreeParseCellNoPayload() => table btree internal nodes
  61390. ** btreeParseCellPtrIndex() => index btree nodes
  61391. **
  61392. ** There is also a wrapper function btreeParseCell() that works for
  61393. ** all MemPage types and that references the cell by index rather than
  61394. ** by pointer.
  61395. */
  61396. static void btreeParseCellPtrNoPayload(
  61397. MemPage *pPage, /* Page containing the cell */
  61398. u8 *pCell, /* Pointer to the cell text. */
  61399. CellInfo *pInfo /* Fill in this structure */
  61400. ){
  61401. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  61402. assert( pPage->leaf==0 );
  61403. assert( pPage->childPtrSize==4 );
  61404. #ifndef SQLITE_DEBUG
  61405. UNUSED_PARAMETER(pPage);
  61406. #endif
  61407. pInfo->nSize = 4 + getVarint(&pCell[4], (u64*)&pInfo->nKey);
  61408. pInfo->nPayload = 0;
  61409. pInfo->nLocal = 0;
  61410. pInfo->pPayload = 0;
  61411. return;
  61412. }
  61413. static void btreeParseCellPtr(
  61414. MemPage *pPage, /* Page containing the cell */
  61415. u8 *pCell, /* Pointer to the cell text. */
  61416. CellInfo *pInfo /* Fill in this structure */
  61417. ){
  61418. u8 *pIter; /* For scanning through pCell */
  61419. u32 nPayload; /* Number of bytes of cell payload */
  61420. u64 iKey; /* Extracted Key value */
  61421. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  61422. assert( pPage->leaf==0 || pPage->leaf==1 );
  61423. assert( pPage->intKeyLeaf );
  61424. assert( pPage->childPtrSize==0 );
  61425. pIter = pCell;
  61426. /* The next block of code is equivalent to:
  61427. **
  61428. ** pIter += getVarint32(pIter, nPayload);
  61429. **
  61430. ** The code is inlined to avoid a function call.
  61431. */
  61432. nPayload = *pIter;
  61433. if( nPayload>=0x80 ){
  61434. u8 *pEnd = &pIter[8];
  61435. nPayload &= 0x7f;
  61436. do{
  61437. nPayload = (nPayload<<7) | (*++pIter & 0x7f);
  61438. }while( (*pIter)>=0x80 && pIter<pEnd );
  61439. }
  61440. pIter++;
  61441. /* The next block of code is equivalent to:
  61442. **
  61443. ** pIter += getVarint(pIter, (u64*)&pInfo->nKey);
  61444. **
  61445. ** The code is inlined to avoid a function call.
  61446. */
  61447. iKey = *pIter;
  61448. if( iKey>=0x80 ){
  61449. u8 *pEnd = &pIter[7];
  61450. iKey &= 0x7f;
  61451. while(1){
  61452. iKey = (iKey<<7) | (*++pIter & 0x7f);
  61453. if( (*pIter)<0x80 ) break;
  61454. if( pIter>=pEnd ){
  61455. iKey = (iKey<<8) | *++pIter;
  61456. break;
  61457. }
  61458. }
  61459. }
  61460. pIter++;
  61461. pInfo->nKey = *(i64*)&iKey;
  61462. pInfo->nPayload = nPayload;
  61463. pInfo->pPayload = pIter;
  61464. testcase( nPayload==pPage->maxLocal );
  61465. testcase( nPayload==pPage->maxLocal+1 );
  61466. if( nPayload<=pPage->maxLocal ){
  61467. /* This is the (easy) common case where the entire payload fits
  61468. ** on the local page. No overflow is required.
  61469. */
  61470. pInfo->nSize = nPayload + (u16)(pIter - pCell);
  61471. if( pInfo->nSize<4 ) pInfo->nSize = 4;
  61472. pInfo->nLocal = (u16)nPayload;
  61473. }else{
  61474. btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo);
  61475. }
  61476. }
  61477. static void btreeParseCellPtrIndex(
  61478. MemPage *pPage, /* Page containing the cell */
  61479. u8 *pCell, /* Pointer to the cell text. */
  61480. CellInfo *pInfo /* Fill in this structure */
  61481. ){
  61482. u8 *pIter; /* For scanning through pCell */
  61483. u32 nPayload; /* Number of bytes of cell payload */
  61484. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  61485. assert( pPage->leaf==0 || pPage->leaf==1 );
  61486. assert( pPage->intKeyLeaf==0 );
  61487. pIter = pCell + pPage->childPtrSize;
  61488. nPayload = *pIter;
  61489. if( nPayload>=0x80 ){
  61490. u8 *pEnd = &pIter[8];
  61491. nPayload &= 0x7f;
  61492. do{
  61493. nPayload = (nPayload<<7) | (*++pIter & 0x7f);
  61494. }while( *(pIter)>=0x80 && pIter<pEnd );
  61495. }
  61496. pIter++;
  61497. pInfo->nKey = nPayload;
  61498. pInfo->nPayload = nPayload;
  61499. pInfo->pPayload = pIter;
  61500. testcase( nPayload==pPage->maxLocal );
  61501. testcase( nPayload==pPage->maxLocal+1 );
  61502. if( nPayload<=pPage->maxLocal ){
  61503. /* This is the (easy) common case where the entire payload fits
  61504. ** on the local page. No overflow is required.
  61505. */
  61506. pInfo->nSize = nPayload + (u16)(pIter - pCell);
  61507. if( pInfo->nSize<4 ) pInfo->nSize = 4;
  61508. pInfo->nLocal = (u16)nPayload;
  61509. }else{
  61510. btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo);
  61511. }
  61512. }
  61513. static void btreeParseCell(
  61514. MemPage *pPage, /* Page containing the cell */
  61515. int iCell, /* The cell index. First cell is 0 */
  61516. CellInfo *pInfo /* Fill in this structure */
  61517. ){
  61518. pPage->xParseCell(pPage, findCell(pPage, iCell), pInfo);
  61519. }
  61520. /*
  61521. ** The following routines are implementations of the MemPage.xCellSize
  61522. ** method.
  61523. **
  61524. ** Compute the total number of bytes that a Cell needs in the cell
  61525. ** data area of the btree-page. The return number includes the cell
  61526. ** data header and the local payload, but not any overflow page or
  61527. ** the space used by the cell pointer.
  61528. **
  61529. ** cellSizePtrNoPayload() => table internal nodes
  61530. ** cellSizePtr() => all index nodes & table leaf nodes
  61531. */
  61532. static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
  61533. u8 *pIter = pCell + pPage->childPtrSize; /* For looping over bytes of pCell */
  61534. u8 *pEnd; /* End mark for a varint */
  61535. u32 nSize; /* Size value to return */
  61536. #ifdef SQLITE_DEBUG
  61537. /* The value returned by this function should always be the same as
  61538. ** the (CellInfo.nSize) value found by doing a full parse of the
  61539. ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
  61540. ** this function verifies that this invariant is not violated. */
  61541. CellInfo debuginfo;
  61542. pPage->xParseCell(pPage, pCell, &debuginfo);
  61543. #endif
  61544. nSize = *pIter;
  61545. if( nSize>=0x80 ){
  61546. pEnd = &pIter[8];
  61547. nSize &= 0x7f;
  61548. do{
  61549. nSize = (nSize<<7) | (*++pIter & 0x7f);
  61550. }while( *(pIter)>=0x80 && pIter<pEnd );
  61551. }
  61552. pIter++;
  61553. if( pPage->intKey ){
  61554. /* pIter now points at the 64-bit integer key value, a variable length
  61555. ** integer. The following block moves pIter to point at the first byte
  61556. ** past the end of the key value. */
  61557. pEnd = &pIter[9];
  61558. while( (*pIter++)&0x80 && pIter<pEnd );
  61559. }
  61560. testcase( nSize==pPage->maxLocal );
  61561. testcase( nSize==pPage->maxLocal+1 );
  61562. if( nSize<=pPage->maxLocal ){
  61563. nSize += (u32)(pIter - pCell);
  61564. if( nSize<4 ) nSize = 4;
  61565. }else{
  61566. int minLocal = pPage->minLocal;
  61567. nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
  61568. testcase( nSize==pPage->maxLocal );
  61569. testcase( nSize==pPage->maxLocal+1 );
  61570. if( nSize>pPage->maxLocal ){
  61571. nSize = minLocal;
  61572. }
  61573. nSize += 4 + (u16)(pIter - pCell);
  61574. }
  61575. assert( nSize==debuginfo.nSize || CORRUPT_DB );
  61576. return (u16)nSize;
  61577. }
  61578. static u16 cellSizePtrNoPayload(MemPage *pPage, u8 *pCell){
  61579. u8 *pIter = pCell + 4; /* For looping over bytes of pCell */
  61580. u8 *pEnd; /* End mark for a varint */
  61581. #ifdef SQLITE_DEBUG
  61582. /* The value returned by this function should always be the same as
  61583. ** the (CellInfo.nSize) value found by doing a full parse of the
  61584. ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
  61585. ** this function verifies that this invariant is not violated. */
  61586. CellInfo debuginfo;
  61587. pPage->xParseCell(pPage, pCell, &debuginfo);
  61588. #else
  61589. UNUSED_PARAMETER(pPage);
  61590. #endif
  61591. assert( pPage->childPtrSize==4 );
  61592. pEnd = pIter + 9;
  61593. while( (*pIter++)&0x80 && pIter<pEnd );
  61594. assert( debuginfo.nSize==(u16)(pIter - pCell) || CORRUPT_DB );
  61595. return (u16)(pIter - pCell);
  61596. }
  61597. #ifdef SQLITE_DEBUG
  61598. /* This variation on cellSizePtr() is used inside of assert() statements
  61599. ** only. */
  61600. static u16 cellSize(MemPage *pPage, int iCell){
  61601. return pPage->xCellSize(pPage, findCell(pPage, iCell));
  61602. }
  61603. #endif
  61604. #ifndef SQLITE_OMIT_AUTOVACUUM
  61605. /*
  61606. ** The cell pCell is currently part of page pSrc but will ultimately be part
  61607. ** of pPage. (pSrc and pPager are often the same.) If pCell contains a
  61608. ** pointer to an overflow page, insert an entry into the pointer-map for
  61609. ** the overflow page that will be valid after pCell has been moved to pPage.
  61610. */
  61611. static void ptrmapPutOvflPtr(MemPage *pPage, MemPage *pSrc, u8 *pCell,int *pRC){
  61612. CellInfo info;
  61613. if( *pRC ) return;
  61614. assert( pCell!=0 );
  61615. pPage->xParseCell(pPage, pCell, &info);
  61616. if( info.nLocal<info.nPayload ){
  61617. Pgno ovfl;
  61618. if( SQLITE_WITHIN(pSrc->aDataEnd, pCell, pCell+info.nLocal) ){
  61619. testcase( pSrc!=pPage );
  61620. *pRC = SQLITE_CORRUPT_BKPT;
  61621. return;
  61622. }
  61623. ovfl = get4byte(&pCell[info.nSize-4]);
  61624. ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
  61625. }
  61626. }
  61627. #endif
  61628. /*
  61629. ** Defragment the page given. This routine reorganizes cells within the
  61630. ** page so that there are no free-blocks on the free-block list.
  61631. **
  61632. ** Parameter nMaxFrag is the maximum amount of fragmented space that may be
  61633. ** present in the page after this routine returns.
  61634. **
  61635. ** EVIDENCE-OF: R-44582-60138 SQLite may from time to time reorganize a
  61636. ** b-tree page so that there are no freeblocks or fragment bytes, all
  61637. ** unused bytes are contained in the unallocated space region, and all
  61638. ** cells are packed tightly at the end of the page.
  61639. */
  61640. static int defragmentPage(MemPage *pPage, int nMaxFrag){
  61641. int i; /* Loop counter */
  61642. int pc; /* Address of the i-th cell */
  61643. int hdr; /* Offset to the page header */
  61644. int size; /* Size of a cell */
  61645. int usableSize; /* Number of usable bytes on a page */
  61646. int cellOffset; /* Offset to the cell pointer array */
  61647. int cbrk; /* Offset to the cell content area */
  61648. int nCell; /* Number of cells on the page */
  61649. unsigned char *data; /* The page data */
  61650. unsigned char *temp; /* Temp area for cell content */
  61651. unsigned char *src; /* Source of content */
  61652. int iCellFirst; /* First allowable cell index */
  61653. int iCellLast; /* Last possible cell index */
  61654. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  61655. assert( pPage->pBt!=0 );
  61656. assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
  61657. assert( pPage->nOverflow==0 );
  61658. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  61659. temp = 0;
  61660. src = data = pPage->aData;
  61661. hdr = pPage->hdrOffset;
  61662. cellOffset = pPage->cellOffset;
  61663. nCell = pPage->nCell;
  61664. assert( nCell==get2byte(&data[hdr+3]) || CORRUPT_DB );
  61665. iCellFirst = cellOffset + 2*nCell;
  61666. usableSize = pPage->pBt->usableSize;
  61667. /* This block handles pages with two or fewer free blocks and nMaxFrag
  61668. ** or fewer fragmented bytes. In this case it is faster to move the
  61669. ** two (or one) blocks of cells using memmove() and add the required
  61670. ** offsets to each pointer in the cell-pointer array than it is to
  61671. ** reconstruct the entire page. */
  61672. if( (int)data[hdr+7]<=nMaxFrag ){
  61673. int iFree = get2byte(&data[hdr+1]);
  61674. if( iFree>usableSize-4 ) return SQLITE_CORRUPT_PAGE(pPage);
  61675. if( iFree ){
  61676. int iFree2 = get2byte(&data[iFree]);
  61677. if( iFree2>usableSize-4 ) return SQLITE_CORRUPT_PAGE(pPage);
  61678. if( 0==iFree2 || (data[iFree2]==0 && data[iFree2+1]==0) ){
  61679. u8 *pEnd = &data[cellOffset + nCell*2];
  61680. u8 *pAddr;
  61681. int sz2 = 0;
  61682. int sz = get2byte(&data[iFree+2]);
  61683. int top = get2byte(&data[hdr+5]);
  61684. if( top>=iFree ){
  61685. return SQLITE_CORRUPT_PAGE(pPage);
  61686. }
  61687. if( iFree2 ){
  61688. if( iFree+sz>iFree2 ) return SQLITE_CORRUPT_PAGE(pPage);
  61689. sz2 = get2byte(&data[iFree2+2]);
  61690. if( iFree2+sz2 > usableSize ) return SQLITE_CORRUPT_PAGE(pPage);
  61691. memmove(&data[iFree+sz+sz2], &data[iFree+sz], iFree2-(iFree+sz));
  61692. sz += sz2;
  61693. }else if( NEVER(iFree+sz>usableSize) ){
  61694. return SQLITE_CORRUPT_PAGE(pPage);
  61695. }
  61696. cbrk = top+sz;
  61697. assert( cbrk+(iFree-top) <= usableSize );
  61698. memmove(&data[cbrk], &data[top], iFree-top);
  61699. for(pAddr=&data[cellOffset]; pAddr<pEnd; pAddr+=2){
  61700. pc = get2byte(pAddr);
  61701. if( pc<iFree ){ put2byte(pAddr, pc+sz); }
  61702. else if( pc<iFree2 ){ put2byte(pAddr, pc+sz2); }
  61703. }
  61704. goto defragment_out;
  61705. }
  61706. }
  61707. }
  61708. cbrk = usableSize;
  61709. iCellLast = usableSize - 4;
  61710. for(i=0; i<nCell; i++){
  61711. u8 *pAddr; /* The i-th cell pointer */
  61712. pAddr = &data[cellOffset + i*2];
  61713. pc = get2byte(pAddr);
  61714. testcase( pc==iCellFirst );
  61715. testcase( pc==iCellLast );
  61716. /* These conditions have already been verified in btreeInitPage()
  61717. ** if PRAGMA cell_size_check=ON.
  61718. */
  61719. if( pc<iCellFirst || pc>iCellLast ){
  61720. return SQLITE_CORRUPT_PAGE(pPage);
  61721. }
  61722. assert( pc>=iCellFirst && pc<=iCellLast );
  61723. size = pPage->xCellSize(pPage, &src[pc]);
  61724. cbrk -= size;
  61725. if( cbrk<iCellFirst || pc+size>usableSize ){
  61726. return SQLITE_CORRUPT_PAGE(pPage);
  61727. }
  61728. assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
  61729. testcase( cbrk+size==usableSize );
  61730. testcase( pc+size==usableSize );
  61731. put2byte(pAddr, cbrk);
  61732. if( temp==0 ){
  61733. int x;
  61734. if( cbrk==pc ) continue;
  61735. temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
  61736. x = get2byte(&data[hdr+5]);
  61737. memcpy(&temp[x], &data[x], (cbrk+size) - x);
  61738. src = temp;
  61739. }
  61740. memcpy(&data[cbrk], &src[pc], size);
  61741. }
  61742. data[hdr+7] = 0;
  61743. defragment_out:
  61744. assert( pPage->nFree>=0 );
  61745. if( data[hdr+7]+cbrk-iCellFirst!=pPage->nFree ){
  61746. return SQLITE_CORRUPT_PAGE(pPage);
  61747. }
  61748. assert( cbrk>=iCellFirst );
  61749. put2byte(&data[hdr+5], cbrk);
  61750. data[hdr+1] = 0;
  61751. data[hdr+2] = 0;
  61752. memset(&data[iCellFirst], 0, cbrk-iCellFirst);
  61753. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  61754. return SQLITE_OK;
  61755. }
  61756. /*
  61757. ** Search the free-list on page pPg for space to store a cell nByte bytes in
  61758. ** size. If one can be found, return a pointer to the space and remove it
  61759. ** from the free-list.
  61760. **
  61761. ** If no suitable space can be found on the free-list, return NULL.
  61762. **
  61763. ** This function may detect corruption within pPg. If corruption is
  61764. ** detected then *pRc is set to SQLITE_CORRUPT and NULL is returned.
  61765. **
  61766. ** Slots on the free list that are between 1 and 3 bytes larger than nByte
  61767. ** will be ignored if adding the extra space to the fragmentation count
  61768. ** causes the fragmentation count to exceed 60.
  61769. */
  61770. static u8 *pageFindSlot(MemPage *pPg, int nByte, int *pRc){
  61771. const int hdr = pPg->hdrOffset; /* Offset to page header */
  61772. u8 * const aData = pPg->aData; /* Page data */
  61773. int iAddr = hdr + 1; /* Address of ptr to pc */
  61774. int pc = get2byte(&aData[iAddr]); /* Address of a free slot */
  61775. int x; /* Excess size of the slot */
  61776. int maxPC = pPg->pBt->usableSize - nByte; /* Max address for a usable slot */
  61777. int size; /* Size of the free slot */
  61778. assert( pc>0 );
  61779. while( pc<=maxPC ){
  61780. /* EVIDENCE-OF: R-22710-53328 The third and fourth bytes of each
  61781. ** freeblock form a big-endian integer which is the size of the freeblock
  61782. ** in bytes, including the 4-byte header. */
  61783. size = get2byte(&aData[pc+2]);
  61784. if( (x = size - nByte)>=0 ){
  61785. testcase( x==4 );
  61786. testcase( x==3 );
  61787. if( x<4 ){
  61788. /* EVIDENCE-OF: R-11498-58022 In a well-formed b-tree page, the total
  61789. ** number of bytes in fragments may not exceed 60. */
  61790. if( aData[hdr+7]>57 ) return 0;
  61791. /* Remove the slot from the free-list. Update the number of
  61792. ** fragmented bytes within the page. */
  61793. memcpy(&aData[iAddr], &aData[pc], 2);
  61794. aData[hdr+7] += (u8)x;
  61795. }else if( x+pc > maxPC ){
  61796. /* This slot extends off the end of the usable part of the page */
  61797. *pRc = SQLITE_CORRUPT_PAGE(pPg);
  61798. return 0;
  61799. }else{
  61800. /* The slot remains on the free-list. Reduce its size to account
  61801. ** for the portion used by the new allocation. */
  61802. put2byte(&aData[pc+2], x);
  61803. }
  61804. return &aData[pc + x];
  61805. }
  61806. iAddr = pc;
  61807. pc = get2byte(&aData[pc]);
  61808. if( pc<=iAddr+size ){
  61809. if( pc ){
  61810. /* The next slot in the chain is not past the end of the current slot */
  61811. *pRc = SQLITE_CORRUPT_PAGE(pPg);
  61812. }
  61813. return 0;
  61814. }
  61815. }
  61816. if( pc>maxPC+nByte-4 ){
  61817. /* The free slot chain extends off the end of the page */
  61818. *pRc = SQLITE_CORRUPT_PAGE(pPg);
  61819. }
  61820. return 0;
  61821. }
  61822. /*
  61823. ** Allocate nByte bytes of space from within the B-Tree page passed
  61824. ** as the first argument. Write into *pIdx the index into pPage->aData[]
  61825. ** of the first byte of allocated space. Return either SQLITE_OK or
  61826. ** an error code (usually SQLITE_CORRUPT).
  61827. **
  61828. ** The caller guarantees that there is sufficient space to make the
  61829. ** allocation. This routine might need to defragment in order to bring
  61830. ** all the space together, however. This routine will avoid using
  61831. ** the first two bytes past the cell pointer area since presumably this
  61832. ** allocation is being made in order to insert a new cell, so we will
  61833. ** also end up needing a new cell pointer.
  61834. */
  61835. static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
  61836. const int hdr = pPage->hdrOffset; /* Local cache of pPage->hdrOffset */
  61837. u8 * const data = pPage->aData; /* Local cache of pPage->aData */
  61838. int top; /* First byte of cell content area */
  61839. int rc = SQLITE_OK; /* Integer return code */
  61840. int gap; /* First byte of gap between cell pointers and cell content */
  61841. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  61842. assert( pPage->pBt );
  61843. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  61844. assert( nByte>=0 ); /* Minimum cell size is 4 */
  61845. assert( pPage->nFree>=nByte );
  61846. assert( pPage->nOverflow==0 );
  61847. assert( nByte < (int)(pPage->pBt->usableSize-8) );
  61848. assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
  61849. gap = pPage->cellOffset + 2*pPage->nCell;
  61850. assert( gap<=65536 );
  61851. /* EVIDENCE-OF: R-29356-02391 If the database uses a 65536-byte page size
  61852. ** and the reserved space is zero (the usual value for reserved space)
  61853. ** then the cell content offset of an empty page wants to be 65536.
  61854. ** However, that integer is too large to be stored in a 2-byte unsigned
  61855. ** integer, so a value of 0 is used in its place. */
  61856. top = get2byte(&data[hdr+5]);
  61857. assert( top<=(int)pPage->pBt->usableSize ); /* by btreeComputeFreeSpace() */
  61858. if( gap>top ){
  61859. if( top==0 && pPage->pBt->usableSize==65536 ){
  61860. top = 65536;
  61861. }else{
  61862. return SQLITE_CORRUPT_PAGE(pPage);
  61863. }
  61864. }
  61865. /* If there is enough space between gap and top for one more cell pointer,
  61866. ** and if the freelist is not empty, then search the
  61867. ** freelist looking for a slot big enough to satisfy the request.
  61868. */
  61869. testcase( gap+2==top );
  61870. testcase( gap+1==top );
  61871. testcase( gap==top );
  61872. if( (data[hdr+2] || data[hdr+1]) && gap+2<=top ){
  61873. u8 *pSpace = pageFindSlot(pPage, nByte, &rc);
  61874. if( pSpace ){
  61875. int g2;
  61876. assert( pSpace+nByte<=data+pPage->pBt->usableSize );
  61877. *pIdx = g2 = (int)(pSpace-data);
  61878. if( NEVER(g2<=gap) ){
  61879. return SQLITE_CORRUPT_PAGE(pPage);
  61880. }else{
  61881. return SQLITE_OK;
  61882. }
  61883. }else if( rc ){
  61884. return rc;
  61885. }
  61886. }
  61887. /* The request could not be fulfilled using a freelist slot. Check
  61888. ** to see if defragmentation is necessary.
  61889. */
  61890. testcase( gap+2+nByte==top );
  61891. if( gap+2+nByte>top ){
  61892. assert( pPage->nCell>0 || CORRUPT_DB );
  61893. assert( pPage->nFree>=0 );
  61894. rc = defragmentPage(pPage, MIN(4, pPage->nFree - (2+nByte)));
  61895. if( rc ) return rc;
  61896. top = get2byteNotZero(&data[hdr+5]);
  61897. assert( gap+2+nByte<=top );
  61898. }
  61899. /* Allocate memory from the gap in between the cell pointer array
  61900. ** and the cell content area. The btreeComputeFreeSpace() call has already
  61901. ** validated the freelist. Given that the freelist is valid, there
  61902. ** is no way that the allocation can extend off the end of the page.
  61903. ** The assert() below verifies the previous sentence.
  61904. */
  61905. top -= nByte;
  61906. put2byte(&data[hdr+5], top);
  61907. assert( top+nByte <= (int)pPage->pBt->usableSize );
  61908. *pIdx = top;
  61909. return SQLITE_OK;
  61910. }
  61911. /*
  61912. ** Return a section of the pPage->aData to the freelist.
  61913. ** The first byte of the new free block is pPage->aData[iStart]
  61914. ** and the size of the block is iSize bytes.
  61915. **
  61916. ** Adjacent freeblocks are coalesced.
  61917. **
  61918. ** Even though the freeblock list was checked by btreeComputeFreeSpace(),
  61919. ** that routine will not detect overlap between cells or freeblocks. Nor
  61920. ** does it detect cells or freeblocks that encrouch into the reserved bytes
  61921. ** at the end of the page. So do additional corruption checks inside this
  61922. ** routine and return SQLITE_CORRUPT if any problems are found.
  61923. */
  61924. static int freeSpace(MemPage *pPage, u16 iStart, u16 iSize){
  61925. u16 iPtr; /* Address of ptr to next freeblock */
  61926. u16 iFreeBlk; /* Address of the next freeblock */
  61927. u8 hdr; /* Page header size. 0 or 100 */
  61928. u8 nFrag = 0; /* Reduction in fragmentation */
  61929. u16 iOrigSize = iSize; /* Original value of iSize */
  61930. u16 x; /* Offset to cell content area */
  61931. u32 iEnd = iStart + iSize; /* First byte past the iStart buffer */
  61932. unsigned char *data = pPage->aData; /* Page content */
  61933. assert( pPage->pBt!=0 );
  61934. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  61935. assert( CORRUPT_DB || iStart>=pPage->hdrOffset+6+pPage->childPtrSize );
  61936. assert( CORRUPT_DB || iEnd <= pPage->pBt->usableSize );
  61937. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  61938. assert( iSize>=4 ); /* Minimum cell size is 4 */
  61939. assert( iStart<=pPage->pBt->usableSize-4 );
  61940. /* The list of freeblocks must be in ascending order. Find the
  61941. ** spot on the list where iStart should be inserted.
  61942. */
  61943. hdr = pPage->hdrOffset;
  61944. iPtr = hdr + 1;
  61945. if( data[iPtr+1]==0 && data[iPtr]==0 ){
  61946. iFreeBlk = 0; /* Shortcut for the case when the freelist is empty */
  61947. }else{
  61948. while( (iFreeBlk = get2byte(&data[iPtr]))<iStart ){
  61949. if( iFreeBlk<iPtr+4 ){
  61950. if( iFreeBlk==0 ) break; /* TH3: corrupt082.100 */
  61951. return SQLITE_CORRUPT_PAGE(pPage);
  61952. }
  61953. iPtr = iFreeBlk;
  61954. }
  61955. if( iFreeBlk>pPage->pBt->usableSize-4 ){ /* TH3: corrupt081.100 */
  61956. return SQLITE_CORRUPT_PAGE(pPage);
  61957. }
  61958. assert( iFreeBlk>iPtr || iFreeBlk==0 );
  61959. /* At this point:
  61960. ** iFreeBlk: First freeblock after iStart, or zero if none
  61961. ** iPtr: The address of a pointer to iFreeBlk
  61962. **
  61963. ** Check to see if iFreeBlk should be coalesced onto the end of iStart.
  61964. */
  61965. if( iFreeBlk && iEnd+3>=iFreeBlk ){
  61966. nFrag = iFreeBlk - iEnd;
  61967. if( iEnd>iFreeBlk ) return SQLITE_CORRUPT_PAGE(pPage);
  61968. iEnd = iFreeBlk + get2byte(&data[iFreeBlk+2]);
  61969. if( NEVER(iEnd > pPage->pBt->usableSize) ){
  61970. return SQLITE_CORRUPT_PAGE(pPage);
  61971. }
  61972. iSize = iEnd - iStart;
  61973. iFreeBlk = get2byte(&data[iFreeBlk]);
  61974. }
  61975. /* If iPtr is another freeblock (that is, if iPtr is not the freelist
  61976. ** pointer in the page header) then check to see if iStart should be
  61977. ** coalesced onto the end of iPtr.
  61978. */
  61979. if( iPtr>hdr+1 ){
  61980. int iPtrEnd = iPtr + get2byte(&data[iPtr+2]);
  61981. if( iPtrEnd+3>=iStart ){
  61982. if( iPtrEnd>iStart ) return SQLITE_CORRUPT_PAGE(pPage);
  61983. nFrag += iStart - iPtrEnd;
  61984. iSize = iEnd - iPtr;
  61985. iStart = iPtr;
  61986. }
  61987. }
  61988. if( nFrag>data[hdr+7] ) return SQLITE_CORRUPT_PAGE(pPage);
  61989. data[hdr+7] -= nFrag;
  61990. }
  61991. x = get2byte(&data[hdr+5]);
  61992. if( iStart<=x ){
  61993. /* The new freeblock is at the beginning of the cell content area,
  61994. ** so just extend the cell content area rather than create another
  61995. ** freelist entry */
  61996. if( iStart<x ) return SQLITE_CORRUPT_PAGE(pPage);
  61997. if( iPtr!=hdr+1 ) return SQLITE_CORRUPT_PAGE(pPage);
  61998. put2byte(&data[hdr+1], iFreeBlk);
  61999. put2byte(&data[hdr+5], iEnd);
  62000. }else{
  62001. /* Insert the new freeblock into the freelist */
  62002. put2byte(&data[iPtr], iStart);
  62003. }
  62004. if( pPage->pBt->btsFlags & BTS_FAST_SECURE ){
  62005. /* Overwrite deleted information with zeros when the secure_delete
  62006. ** option is enabled */
  62007. memset(&data[iStart], 0, iSize);
  62008. }
  62009. put2byte(&data[iStart], iFreeBlk);
  62010. put2byte(&data[iStart+2], iSize);
  62011. pPage->nFree += iOrigSize;
  62012. return SQLITE_OK;
  62013. }
  62014. /*
  62015. ** Decode the flags byte (the first byte of the header) for a page
  62016. ** and initialize fields of the MemPage structure accordingly.
  62017. **
  62018. ** Only the following combinations are supported. Anything different
  62019. ** indicates a corrupt database files:
  62020. **
  62021. ** PTF_ZERODATA
  62022. ** PTF_ZERODATA | PTF_LEAF
  62023. ** PTF_LEAFDATA | PTF_INTKEY
  62024. ** PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
  62025. */
  62026. static int decodeFlags(MemPage *pPage, int flagByte){
  62027. BtShared *pBt; /* A copy of pPage->pBt */
  62028. assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
  62029. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  62030. pPage->leaf = (u8)(flagByte>>3); assert( PTF_LEAF == 1<<3 );
  62031. flagByte &= ~PTF_LEAF;
  62032. pPage->childPtrSize = 4-4*pPage->leaf;
  62033. pPage->xCellSize = cellSizePtr;
  62034. pBt = pPage->pBt;
  62035. if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
  62036. /* EVIDENCE-OF: R-07291-35328 A value of 5 (0x05) means the page is an
  62037. ** interior table b-tree page. */
  62038. assert( (PTF_LEAFDATA|PTF_INTKEY)==5 );
  62039. /* EVIDENCE-OF: R-26900-09176 A value of 13 (0x0d) means the page is a
  62040. ** leaf table b-tree page. */
  62041. assert( (PTF_LEAFDATA|PTF_INTKEY|PTF_LEAF)==13 );
  62042. pPage->intKey = 1;
  62043. if( pPage->leaf ){
  62044. pPage->intKeyLeaf = 1;
  62045. pPage->xParseCell = btreeParseCellPtr;
  62046. }else{
  62047. pPage->intKeyLeaf = 0;
  62048. pPage->xCellSize = cellSizePtrNoPayload;
  62049. pPage->xParseCell = btreeParseCellPtrNoPayload;
  62050. }
  62051. pPage->maxLocal = pBt->maxLeaf;
  62052. pPage->minLocal = pBt->minLeaf;
  62053. }else if( flagByte==PTF_ZERODATA ){
  62054. /* EVIDENCE-OF: R-43316-37308 A value of 2 (0x02) means the page is an
  62055. ** interior index b-tree page. */
  62056. assert( (PTF_ZERODATA)==2 );
  62057. /* EVIDENCE-OF: R-59615-42828 A value of 10 (0x0a) means the page is a
  62058. ** leaf index b-tree page. */
  62059. assert( (PTF_ZERODATA|PTF_LEAF)==10 );
  62060. pPage->intKey = 0;
  62061. pPage->intKeyLeaf = 0;
  62062. pPage->xParseCell = btreeParseCellPtrIndex;
  62063. pPage->maxLocal = pBt->maxLocal;
  62064. pPage->minLocal = pBt->minLocal;
  62065. }else{
  62066. /* EVIDENCE-OF: R-47608-56469 Any other value for the b-tree page type is
  62067. ** an error. */
  62068. return SQLITE_CORRUPT_PAGE(pPage);
  62069. }
  62070. pPage->max1bytePayload = pBt->max1bytePayload;
  62071. return SQLITE_OK;
  62072. }
  62073. /*
  62074. ** Compute the amount of freespace on the page. In other words, fill
  62075. ** in the pPage->nFree field.
  62076. */
  62077. static int btreeComputeFreeSpace(MemPage *pPage){
  62078. int pc; /* Address of a freeblock within pPage->aData[] */
  62079. u8 hdr; /* Offset to beginning of page header */
  62080. u8 *data; /* Equal to pPage->aData */
  62081. int usableSize; /* Amount of usable space on each page */
  62082. int nFree; /* Number of unused bytes on the page */
  62083. int top; /* First byte of the cell content area */
  62084. int iCellFirst; /* First allowable cell or freeblock offset */
  62085. int iCellLast; /* Last possible cell or freeblock offset */
  62086. assert( pPage->pBt!=0 );
  62087. assert( pPage->pBt->db!=0 );
  62088. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  62089. assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
  62090. assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
  62091. assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
  62092. assert( pPage->isInit==1 );
  62093. assert( pPage->nFree<0 );
  62094. usableSize = pPage->pBt->usableSize;
  62095. hdr = pPage->hdrOffset;
  62096. data = pPage->aData;
  62097. /* EVIDENCE-OF: R-58015-48175 The two-byte integer at offset 5 designates
  62098. ** the start of the cell content area. A zero value for this integer is
  62099. ** interpreted as 65536. */
  62100. top = get2byteNotZero(&data[hdr+5]);
  62101. iCellFirst = hdr + 8 + pPage->childPtrSize + 2*pPage->nCell;
  62102. iCellLast = usableSize - 4;
  62103. /* Compute the total free space on the page
  62104. ** EVIDENCE-OF: R-23588-34450 The two-byte integer at offset 1 gives the
  62105. ** start of the first freeblock on the page, or is zero if there are no
  62106. ** freeblocks. */
  62107. pc = get2byte(&data[hdr+1]);
  62108. nFree = data[hdr+7] + top; /* Init nFree to non-freeblock free space */
  62109. if( pc>0 ){
  62110. u32 next, size;
  62111. if( pc<top ){
  62112. /* EVIDENCE-OF: R-55530-52930 In a well-formed b-tree page, there will
  62113. ** always be at least one cell before the first freeblock.
  62114. */
  62115. return SQLITE_CORRUPT_PAGE(pPage);
  62116. }
  62117. while( 1 ){
  62118. if( pc>iCellLast ){
  62119. /* Freeblock off the end of the page */
  62120. return SQLITE_CORRUPT_PAGE(pPage);
  62121. }
  62122. next = get2byte(&data[pc]);
  62123. size = get2byte(&data[pc+2]);
  62124. nFree = nFree + size;
  62125. if( next<=pc+size+3 ) break;
  62126. pc = next;
  62127. }
  62128. if( next>0 ){
  62129. /* Freeblock not in ascending order */
  62130. return SQLITE_CORRUPT_PAGE(pPage);
  62131. }
  62132. if( pc+size>(unsigned int)usableSize ){
  62133. /* Last freeblock extends past page end */
  62134. return SQLITE_CORRUPT_PAGE(pPage);
  62135. }
  62136. }
  62137. /* At this point, nFree contains the sum of the offset to the start
  62138. ** of the cell-content area plus the number of free bytes within
  62139. ** the cell-content area. If this is greater than the usable-size
  62140. ** of the page, then the page must be corrupted. This check also
  62141. ** serves to verify that the offset to the start of the cell-content
  62142. ** area, according to the page header, lies within the page.
  62143. */
  62144. if( nFree>usableSize || nFree<iCellFirst ){
  62145. return SQLITE_CORRUPT_PAGE(pPage);
  62146. }
  62147. pPage->nFree = (u16)(nFree - iCellFirst);
  62148. return SQLITE_OK;
  62149. }
  62150. /*
  62151. ** Do additional sanity check after btreeInitPage() if
  62152. ** PRAGMA cell_size_check=ON
  62153. */
  62154. static SQLITE_NOINLINE int btreeCellSizeCheck(MemPage *pPage){
  62155. int iCellFirst; /* First allowable cell or freeblock offset */
  62156. int iCellLast; /* Last possible cell or freeblock offset */
  62157. int i; /* Index into the cell pointer array */
  62158. int sz; /* Size of a cell */
  62159. int pc; /* Address of a freeblock within pPage->aData[] */
  62160. u8 *data; /* Equal to pPage->aData */
  62161. int usableSize; /* Maximum usable space on the page */
  62162. int cellOffset; /* Start of cell content area */
  62163. iCellFirst = pPage->cellOffset + 2*pPage->nCell;
  62164. usableSize = pPage->pBt->usableSize;
  62165. iCellLast = usableSize - 4;
  62166. data = pPage->aData;
  62167. cellOffset = pPage->cellOffset;
  62168. if( !pPage->leaf ) iCellLast--;
  62169. for(i=0; i<pPage->nCell; i++){
  62170. pc = get2byteAligned(&data[cellOffset+i*2]);
  62171. testcase( pc==iCellFirst );
  62172. testcase( pc==iCellLast );
  62173. if( pc<iCellFirst || pc>iCellLast ){
  62174. return SQLITE_CORRUPT_PAGE(pPage);
  62175. }
  62176. sz = pPage->xCellSize(pPage, &data[pc]);
  62177. testcase( pc+sz==usableSize );
  62178. if( pc+sz>usableSize ){
  62179. return SQLITE_CORRUPT_PAGE(pPage);
  62180. }
  62181. }
  62182. return SQLITE_OK;
  62183. }
  62184. /*
  62185. ** Initialize the auxiliary information for a disk block.
  62186. **
  62187. ** Return SQLITE_OK on success. If we see that the page does
  62188. ** not contain a well-formed database page, then return
  62189. ** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not
  62190. ** guarantee that the page is well-formed. It only shows that
  62191. ** we failed to detect any corruption.
  62192. */
  62193. static int btreeInitPage(MemPage *pPage){
  62194. u8 *data; /* Equal to pPage->aData */
  62195. BtShared *pBt; /* The main btree structure */
  62196. assert( pPage->pBt!=0 );
  62197. assert( pPage->pBt->db!=0 );
  62198. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  62199. assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
  62200. assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
  62201. assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
  62202. assert( pPage->isInit==0 );
  62203. pBt = pPage->pBt;
  62204. data = pPage->aData + pPage->hdrOffset;
  62205. /* EVIDENCE-OF: R-28594-02890 The one-byte flag at offset 0 indicating
  62206. ** the b-tree page type. */
  62207. if( decodeFlags(pPage, data[0]) ){
  62208. return SQLITE_CORRUPT_PAGE(pPage);
  62209. }
  62210. assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
  62211. pPage->maskPage = (u16)(pBt->pageSize - 1);
  62212. pPage->nOverflow = 0;
  62213. pPage->cellOffset = pPage->hdrOffset + 8 + pPage->childPtrSize;
  62214. pPage->aCellIdx = data + pPage->childPtrSize + 8;
  62215. pPage->aDataEnd = pPage->aData + pBt->usableSize;
  62216. pPage->aDataOfst = pPage->aData + pPage->childPtrSize;
  62217. /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
  62218. ** number of cells on the page. */
  62219. pPage->nCell = get2byte(&data[3]);
  62220. if( pPage->nCell>MX_CELL(pBt) ){
  62221. /* To many cells for a single page. The page must be corrupt */
  62222. return SQLITE_CORRUPT_PAGE(pPage);
  62223. }
  62224. testcase( pPage->nCell==MX_CELL(pBt) );
  62225. /* EVIDENCE-OF: R-24089-57979 If a page contains no cells (which is only
  62226. ** possible for a root page of a table that contains no rows) then the
  62227. ** offset to the cell content area will equal the page size minus the
  62228. ** bytes of reserved space. */
  62229. assert( pPage->nCell>0
  62230. || get2byteNotZero(&data[5])==(int)pBt->usableSize
  62231. || CORRUPT_DB );
  62232. pPage->nFree = -1; /* Indicate that this value is yet uncomputed */
  62233. pPage->isInit = 1;
  62234. if( pBt->db->flags & SQLITE_CellSizeCk ){
  62235. return btreeCellSizeCheck(pPage);
  62236. }
  62237. return SQLITE_OK;
  62238. }
  62239. /*
  62240. ** Set up a raw page so that it looks like a database page holding
  62241. ** no entries.
  62242. */
  62243. static void zeroPage(MemPage *pPage, int flags){
  62244. unsigned char *data = pPage->aData;
  62245. BtShared *pBt = pPage->pBt;
  62246. u8 hdr = pPage->hdrOffset;
  62247. u16 first;
  62248. assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
  62249. assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
  62250. assert( sqlite3PagerGetData(pPage->pDbPage) == data );
  62251. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  62252. assert( sqlite3_mutex_held(pBt->mutex) );
  62253. if( pBt->btsFlags & BTS_FAST_SECURE ){
  62254. memset(&data[hdr], 0, pBt->usableSize - hdr);
  62255. }
  62256. data[hdr] = (char)flags;
  62257. first = hdr + ((flags&PTF_LEAF)==0 ? 12 : 8);
  62258. memset(&data[hdr+1], 0, 4);
  62259. data[hdr+7] = 0;
  62260. put2byte(&data[hdr+5], pBt->usableSize);
  62261. pPage->nFree = (u16)(pBt->usableSize - first);
  62262. decodeFlags(pPage, flags);
  62263. pPage->cellOffset = first;
  62264. pPage->aDataEnd = &data[pBt->usableSize];
  62265. pPage->aCellIdx = &data[first];
  62266. pPage->aDataOfst = &data[pPage->childPtrSize];
  62267. pPage->nOverflow = 0;
  62268. assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
  62269. pPage->maskPage = (u16)(pBt->pageSize - 1);
  62270. pPage->nCell = 0;
  62271. pPage->isInit = 1;
  62272. }
  62273. /*
  62274. ** Convert a DbPage obtained from the pager into a MemPage used by
  62275. ** the btree layer.
  62276. */
  62277. static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
  62278. MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
  62279. if( pgno!=pPage->pgno ){
  62280. pPage->aData = sqlite3PagerGetData(pDbPage);
  62281. pPage->pDbPage = pDbPage;
  62282. pPage->pBt = pBt;
  62283. pPage->pgno = pgno;
  62284. pPage->hdrOffset = pgno==1 ? 100 : 0;
  62285. }
  62286. assert( pPage->aData==sqlite3PagerGetData(pDbPage) );
  62287. return pPage;
  62288. }
  62289. /*
  62290. ** Get a page from the pager. Initialize the MemPage.pBt and
  62291. ** MemPage.aData elements if needed. See also: btreeGetUnusedPage().
  62292. **
  62293. ** If the PAGER_GET_NOCONTENT flag is set, it means that we do not care
  62294. ** about the content of the page at this time. So do not go to the disk
  62295. ** to fetch the content. Just fill in the content with zeros for now.
  62296. ** If in the future we call sqlite3PagerWrite() on this page, that
  62297. ** means we have started to be concerned about content and the disk
  62298. ** read should occur at that point.
  62299. */
  62300. static int btreeGetPage(
  62301. BtShared *pBt, /* The btree */
  62302. Pgno pgno, /* Number of the page to fetch */
  62303. MemPage **ppPage, /* Return the page in this parameter */
  62304. int flags /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
  62305. ){
  62306. int rc;
  62307. DbPage *pDbPage;
  62308. assert( flags==0 || flags==PAGER_GET_NOCONTENT || flags==PAGER_GET_READONLY );
  62309. assert( sqlite3_mutex_held(pBt->mutex) );
  62310. rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, flags);
  62311. if( rc ) return rc;
  62312. *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
  62313. return SQLITE_OK;
  62314. }
  62315. /*
  62316. ** Retrieve a page from the pager cache. If the requested page is not
  62317. ** already in the pager cache return NULL. Initialize the MemPage.pBt and
  62318. ** MemPage.aData elements if needed.
  62319. */
  62320. static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
  62321. DbPage *pDbPage;
  62322. assert( sqlite3_mutex_held(pBt->mutex) );
  62323. pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
  62324. if( pDbPage ){
  62325. return btreePageFromDbPage(pDbPage, pgno, pBt);
  62326. }
  62327. return 0;
  62328. }
  62329. /*
  62330. ** Return the size of the database file in pages. If there is any kind of
  62331. ** error, return ((unsigned int)-1).
  62332. */
  62333. static Pgno btreePagecount(BtShared *pBt){
  62334. assert( (pBt->nPage & 0x80000000)==0 || CORRUPT_DB );
  62335. return pBt->nPage;
  62336. }
  62337. SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree *p){
  62338. assert( sqlite3BtreeHoldsMutex(p) );
  62339. return btreePagecount(p->pBt) & 0x7fffffff;
  62340. }
  62341. /*
  62342. ** Get a page from the pager and initialize it.
  62343. **
  62344. ** If pCur!=0 then the page is being fetched as part of a moveToChild()
  62345. ** call. Do additional sanity checking on the page in this case.
  62346. ** And if the fetch fails, this routine must decrement pCur->iPage.
  62347. **
  62348. ** The page is fetched as read-write unless pCur is not NULL and is
  62349. ** a read-only cursor.
  62350. **
  62351. ** If an error occurs, then *ppPage is undefined. It
  62352. ** may remain unchanged, or it may be set to an invalid value.
  62353. */
  62354. static int getAndInitPage(
  62355. BtShared *pBt, /* The database file */
  62356. Pgno pgno, /* Number of the page to get */
  62357. MemPage **ppPage, /* Write the page pointer here */
  62358. BtCursor *pCur, /* Cursor to receive the page, or NULL */
  62359. int bReadOnly /* True for a read-only page */
  62360. ){
  62361. int rc;
  62362. DbPage *pDbPage;
  62363. assert( sqlite3_mutex_held(pBt->mutex) );
  62364. assert( pCur==0 || ppPage==&pCur->pPage );
  62365. assert( pCur==0 || bReadOnly==pCur->curPagerFlags );
  62366. assert( pCur==0 || pCur->iPage>0 );
  62367. if( pgno>btreePagecount(pBt) ){
  62368. rc = SQLITE_CORRUPT_BKPT;
  62369. goto getAndInitPage_error1;
  62370. }
  62371. rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, bReadOnly);
  62372. if( rc ){
  62373. goto getAndInitPage_error1;
  62374. }
  62375. *ppPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
  62376. if( (*ppPage)->isInit==0 ){
  62377. btreePageFromDbPage(pDbPage, pgno, pBt);
  62378. rc = btreeInitPage(*ppPage);
  62379. if( rc!=SQLITE_OK ){
  62380. goto getAndInitPage_error2;
  62381. }
  62382. }
  62383. assert( (*ppPage)->pgno==pgno );
  62384. assert( (*ppPage)->aData==sqlite3PagerGetData(pDbPage) );
  62385. /* If obtaining a child page for a cursor, we must verify that the page is
  62386. ** compatible with the root page. */
  62387. if( pCur && ((*ppPage)->nCell<1 || (*ppPage)->intKey!=pCur->curIntKey) ){
  62388. rc = SQLITE_CORRUPT_PGNO(pgno);
  62389. goto getAndInitPage_error2;
  62390. }
  62391. return SQLITE_OK;
  62392. getAndInitPage_error2:
  62393. releasePage(*ppPage);
  62394. getAndInitPage_error1:
  62395. if( pCur ){
  62396. pCur->iPage--;
  62397. pCur->pPage = pCur->apPage[pCur->iPage];
  62398. }
  62399. testcase( pgno==0 );
  62400. assert( pgno!=0 || rc==SQLITE_CORRUPT );
  62401. return rc;
  62402. }
  62403. /*
  62404. ** Release a MemPage. This should be called once for each prior
  62405. ** call to btreeGetPage.
  62406. **
  62407. ** Page1 is a special case and must be released using releasePageOne().
  62408. */
  62409. static void releasePageNotNull(MemPage *pPage){
  62410. assert( pPage->aData );
  62411. assert( pPage->pBt );
  62412. assert( pPage->pDbPage!=0 );
  62413. assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
  62414. assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
  62415. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  62416. sqlite3PagerUnrefNotNull(pPage->pDbPage);
  62417. }
  62418. static void releasePage(MemPage *pPage){
  62419. if( pPage ) releasePageNotNull(pPage);
  62420. }
  62421. static void releasePageOne(MemPage *pPage){
  62422. assert( pPage!=0 );
  62423. assert( pPage->aData );
  62424. assert( pPage->pBt );
  62425. assert( pPage->pDbPage!=0 );
  62426. assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
  62427. assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
  62428. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  62429. sqlite3PagerUnrefPageOne(pPage->pDbPage);
  62430. }
  62431. /*
  62432. ** Get an unused page.
  62433. **
  62434. ** This works just like btreeGetPage() with the addition:
  62435. **
  62436. ** * If the page is already in use for some other purpose, immediately
  62437. ** release it and return an SQLITE_CURRUPT error.
  62438. ** * Make sure the isInit flag is clear
  62439. */
  62440. static int btreeGetUnusedPage(
  62441. BtShared *pBt, /* The btree */
  62442. Pgno pgno, /* Number of the page to fetch */
  62443. MemPage **ppPage, /* Return the page in this parameter */
  62444. int flags /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
  62445. ){
  62446. int rc = btreeGetPage(pBt, pgno, ppPage, flags);
  62447. if( rc==SQLITE_OK ){
  62448. if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
  62449. releasePage(*ppPage);
  62450. *ppPage = 0;
  62451. return SQLITE_CORRUPT_BKPT;
  62452. }
  62453. (*ppPage)->isInit = 0;
  62454. }else{
  62455. *ppPage = 0;
  62456. }
  62457. return rc;
  62458. }
  62459. /*
  62460. ** During a rollback, when the pager reloads information into the cache
  62461. ** so that the cache is restored to its original state at the start of
  62462. ** the transaction, for each page restored this routine is called.
  62463. **
  62464. ** This routine needs to reset the extra data section at the end of the
  62465. ** page to agree with the restored data.
  62466. */
  62467. static void pageReinit(DbPage *pData){
  62468. MemPage *pPage;
  62469. pPage = (MemPage *)sqlite3PagerGetExtra(pData);
  62470. assert( sqlite3PagerPageRefcount(pData)>0 );
  62471. if( pPage->isInit ){
  62472. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  62473. pPage->isInit = 0;
  62474. if( sqlite3PagerPageRefcount(pData)>1 ){
  62475. /* pPage might not be a btree page; it might be an overflow page
  62476. ** or ptrmap page or a free page. In those cases, the following
  62477. ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
  62478. ** But no harm is done by this. And it is very important that
  62479. ** btreeInitPage() be called on every btree page so we make
  62480. ** the call for every page that comes in for re-initing. */
  62481. btreeInitPage(pPage);
  62482. }
  62483. }
  62484. }
  62485. /*
  62486. ** Invoke the busy handler for a btree.
  62487. */
  62488. static int btreeInvokeBusyHandler(void *pArg){
  62489. BtShared *pBt = (BtShared*)pArg;
  62490. assert( pBt->db );
  62491. assert( sqlite3_mutex_held(pBt->db->mutex) );
  62492. return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
  62493. }
  62494. /*
  62495. ** Open a database file.
  62496. **
  62497. ** zFilename is the name of the database file. If zFilename is NULL
  62498. ** then an ephemeral database is created. The ephemeral database might
  62499. ** be exclusively in memory, or it might use a disk-based memory cache.
  62500. ** Either way, the ephemeral database will be automatically deleted
  62501. ** when sqlite3BtreeClose() is called.
  62502. **
  62503. ** If zFilename is ":memory:" then an in-memory database is created
  62504. ** that is automatically destroyed when it is closed.
  62505. **
  62506. ** The "flags" parameter is a bitmask that might contain bits like
  62507. ** BTREE_OMIT_JOURNAL and/or BTREE_MEMORY.
  62508. **
  62509. ** If the database is already opened in the same database connection
  62510. ** and we are in shared cache mode, then the open will fail with an
  62511. ** SQLITE_CONSTRAINT error. We cannot allow two or more BtShared
  62512. ** objects in the same database connection since doing so will lead
  62513. ** to problems with locking.
  62514. */
  62515. SQLITE_PRIVATE int sqlite3BtreeOpen(
  62516. sqlite3_vfs *pVfs, /* VFS to use for this b-tree */
  62517. const char *zFilename, /* Name of the file containing the BTree database */
  62518. sqlite3 *db, /* Associated database handle */
  62519. Btree **ppBtree, /* Pointer to new Btree object written here */
  62520. int flags, /* Options */
  62521. int vfsFlags /* Flags passed through to sqlite3_vfs.xOpen() */
  62522. ){
  62523. BtShared *pBt = 0; /* Shared part of btree structure */
  62524. Btree *p; /* Handle to return */
  62525. sqlite3_mutex *mutexOpen = 0; /* Prevents a race condition. Ticket #3537 */
  62526. int rc = SQLITE_OK; /* Result code from this function */
  62527. u8 nReserve; /* Byte of unused space on each page */
  62528. unsigned char zDbHeader[100]; /* Database header content */
  62529. /* True if opening an ephemeral, temporary database */
  62530. const int isTempDb = zFilename==0 || zFilename[0]==0;
  62531. /* Set the variable isMemdb to true for an in-memory database, or
  62532. ** false for a file-based database.
  62533. */
  62534. #ifdef SQLITE_OMIT_MEMORYDB
  62535. const int isMemdb = 0;
  62536. #else
  62537. const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
  62538. || (isTempDb && sqlite3TempInMemory(db))
  62539. || (vfsFlags & SQLITE_OPEN_MEMORY)!=0;
  62540. #endif
  62541. assert( db!=0 );
  62542. assert( pVfs!=0 );
  62543. assert( sqlite3_mutex_held(db->mutex) );
  62544. assert( (flags&0xff)==flags ); /* flags fit in 8 bits */
  62545. /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
  62546. assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
  62547. /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
  62548. assert( (flags & BTREE_SINGLE)==0 || isTempDb );
  62549. if( isMemdb ){
  62550. flags |= BTREE_MEMORY;
  62551. }
  62552. if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
  62553. vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
  62554. }
  62555. p = sqlite3MallocZero(sizeof(Btree));
  62556. if( !p ){
  62557. return SQLITE_NOMEM_BKPT;
  62558. }
  62559. p->inTrans = TRANS_NONE;
  62560. p->db = db;
  62561. #ifndef SQLITE_OMIT_SHARED_CACHE
  62562. p->lock.pBtree = p;
  62563. p->lock.iTable = 1;
  62564. #endif
  62565. #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
  62566. /*
  62567. ** If this Btree is a candidate for shared cache, try to find an
  62568. ** existing BtShared object that we can share with
  62569. */
  62570. if( isTempDb==0 && (isMemdb==0 || (vfsFlags&SQLITE_OPEN_URI)!=0) ){
  62571. if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
  62572. int nFilename = sqlite3Strlen30(zFilename)+1;
  62573. int nFullPathname = pVfs->mxPathname+1;
  62574. char *zFullPathname = sqlite3Malloc(MAX(nFullPathname,nFilename));
  62575. MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
  62576. p->sharable = 1;
  62577. if( !zFullPathname ){
  62578. sqlite3_free(p);
  62579. return SQLITE_NOMEM_BKPT;
  62580. }
  62581. if( isMemdb ){
  62582. memcpy(zFullPathname, zFilename, nFilename);
  62583. }else{
  62584. rc = sqlite3OsFullPathname(pVfs, zFilename,
  62585. nFullPathname, zFullPathname);
  62586. if( rc ){
  62587. if( rc==SQLITE_OK_SYMLINK ){
  62588. rc = SQLITE_OK;
  62589. }else{
  62590. sqlite3_free(zFullPathname);
  62591. sqlite3_free(p);
  62592. return rc;
  62593. }
  62594. }
  62595. }
  62596. #if SQLITE_THREADSAFE
  62597. mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
  62598. sqlite3_mutex_enter(mutexOpen);
  62599. mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  62600. sqlite3_mutex_enter(mutexShared);
  62601. #endif
  62602. for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
  62603. assert( pBt->nRef>0 );
  62604. if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager, 0))
  62605. && sqlite3PagerVfs(pBt->pPager)==pVfs ){
  62606. int iDb;
  62607. for(iDb=db->nDb-1; iDb>=0; iDb--){
  62608. Btree *pExisting = db->aDb[iDb].pBt;
  62609. if( pExisting && pExisting->pBt==pBt ){
  62610. sqlite3_mutex_leave(mutexShared);
  62611. sqlite3_mutex_leave(mutexOpen);
  62612. sqlite3_free(zFullPathname);
  62613. sqlite3_free(p);
  62614. return SQLITE_CONSTRAINT;
  62615. }
  62616. }
  62617. p->pBt = pBt;
  62618. pBt->nRef++;
  62619. break;
  62620. }
  62621. }
  62622. sqlite3_mutex_leave(mutexShared);
  62623. sqlite3_free(zFullPathname);
  62624. }
  62625. #ifdef SQLITE_DEBUG
  62626. else{
  62627. /* In debug mode, we mark all persistent databases as sharable
  62628. ** even when they are not. This exercises the locking code and
  62629. ** gives more opportunity for asserts(sqlite3_mutex_held())
  62630. ** statements to find locking problems.
  62631. */
  62632. p->sharable = 1;
  62633. }
  62634. #endif
  62635. }
  62636. #endif
  62637. if( pBt==0 ){
  62638. /*
  62639. ** The following asserts make sure that structures used by the btree are
  62640. ** the right size. This is to guard against size changes that result
  62641. ** when compiling on a different architecture.
  62642. */
  62643. assert( sizeof(i64)==8 );
  62644. assert( sizeof(u64)==8 );
  62645. assert( sizeof(u32)==4 );
  62646. assert( sizeof(u16)==2 );
  62647. assert( sizeof(Pgno)==4 );
  62648. pBt = sqlite3MallocZero( sizeof(*pBt) );
  62649. if( pBt==0 ){
  62650. rc = SQLITE_NOMEM_BKPT;
  62651. goto btree_open_out;
  62652. }
  62653. rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
  62654. sizeof(MemPage), flags, vfsFlags, pageReinit);
  62655. if( rc==SQLITE_OK ){
  62656. sqlite3PagerSetMmapLimit(pBt->pPager, db->szMmap);
  62657. rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
  62658. }
  62659. if( rc!=SQLITE_OK ){
  62660. goto btree_open_out;
  62661. }
  62662. pBt->openFlags = (u8)flags;
  62663. pBt->db = db;
  62664. sqlite3PagerSetBusyHandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
  62665. p->pBt = pBt;
  62666. pBt->pCursor = 0;
  62667. pBt->pPage1 = 0;
  62668. if( sqlite3PagerIsreadonly(pBt->pPager) ) pBt->btsFlags |= BTS_READ_ONLY;
  62669. #if defined(SQLITE_SECURE_DELETE)
  62670. pBt->btsFlags |= BTS_SECURE_DELETE;
  62671. #elif defined(SQLITE_FAST_SECURE_DELETE)
  62672. pBt->btsFlags |= BTS_OVERWRITE;
  62673. #endif
  62674. /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
  62675. ** determined by the 2-byte integer located at an offset of 16 bytes from
  62676. ** the beginning of the database file. */
  62677. pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
  62678. if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
  62679. || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
  62680. pBt->pageSize = 0;
  62681. #ifndef SQLITE_OMIT_AUTOVACUUM
  62682. /* If the magic name ":memory:" will create an in-memory database, then
  62683. ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
  62684. ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
  62685. ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
  62686. ** regular file-name. In this case the auto-vacuum applies as per normal.
  62687. */
  62688. if( zFilename && !isMemdb ){
  62689. pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
  62690. pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
  62691. }
  62692. #endif
  62693. nReserve = 0;
  62694. }else{
  62695. /* EVIDENCE-OF: R-37497-42412 The size of the reserved region is
  62696. ** determined by the one-byte unsigned integer found at an offset of 20
  62697. ** into the database file header. */
  62698. nReserve = zDbHeader[20];
  62699. pBt->btsFlags |= BTS_PAGESIZE_FIXED;
  62700. #ifndef SQLITE_OMIT_AUTOVACUUM
  62701. pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
  62702. pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
  62703. #endif
  62704. }
  62705. rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
  62706. if( rc ) goto btree_open_out;
  62707. pBt->usableSize = pBt->pageSize - nReserve;
  62708. assert( (pBt->pageSize & 7)==0 ); /* 8-byte alignment of pageSize */
  62709. #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
  62710. /* Add the new BtShared object to the linked list sharable BtShareds.
  62711. */
  62712. pBt->nRef = 1;
  62713. if( p->sharable ){
  62714. MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
  62715. MUTEX_LOGIC( mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);)
  62716. if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
  62717. pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
  62718. if( pBt->mutex==0 ){
  62719. rc = SQLITE_NOMEM_BKPT;
  62720. goto btree_open_out;
  62721. }
  62722. }
  62723. sqlite3_mutex_enter(mutexShared);
  62724. pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
  62725. GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
  62726. sqlite3_mutex_leave(mutexShared);
  62727. }
  62728. #endif
  62729. }
  62730. #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
  62731. /* If the new Btree uses a sharable pBtShared, then link the new
  62732. ** Btree into the list of all sharable Btrees for the same connection.
  62733. ** The list is kept in ascending order by pBt address.
  62734. */
  62735. if( p->sharable ){
  62736. int i;
  62737. Btree *pSib;
  62738. for(i=0; i<db->nDb; i++){
  62739. if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
  62740. while( pSib->pPrev ){ pSib = pSib->pPrev; }
  62741. if( (uptr)p->pBt<(uptr)pSib->pBt ){
  62742. p->pNext = pSib;
  62743. p->pPrev = 0;
  62744. pSib->pPrev = p;
  62745. }else{
  62746. while( pSib->pNext && (uptr)pSib->pNext->pBt<(uptr)p->pBt ){
  62747. pSib = pSib->pNext;
  62748. }
  62749. p->pNext = pSib->pNext;
  62750. p->pPrev = pSib;
  62751. if( p->pNext ){
  62752. p->pNext->pPrev = p;
  62753. }
  62754. pSib->pNext = p;
  62755. }
  62756. break;
  62757. }
  62758. }
  62759. }
  62760. #endif
  62761. *ppBtree = p;
  62762. btree_open_out:
  62763. if( rc!=SQLITE_OK ){
  62764. if( pBt && pBt->pPager ){
  62765. sqlite3PagerClose(pBt->pPager, 0);
  62766. }
  62767. sqlite3_free(pBt);
  62768. sqlite3_free(p);
  62769. *ppBtree = 0;
  62770. }else{
  62771. sqlite3_file *pFile;
  62772. /* If the B-Tree was successfully opened, set the pager-cache size to the
  62773. ** default value. Except, when opening on an existing shared pager-cache,
  62774. ** do not change the pager-cache size.
  62775. */
  62776. if( sqlite3BtreeSchema(p, 0, 0)==0 ){
  62777. sqlite3PagerSetCachesize(p->pBt->pPager, SQLITE_DEFAULT_CACHE_SIZE);
  62778. }
  62779. pFile = sqlite3PagerFile(pBt->pPager);
  62780. if( pFile->pMethods ){
  62781. sqlite3OsFileControlHint(pFile, SQLITE_FCNTL_PDB, (void*)&pBt->db);
  62782. }
  62783. }
  62784. if( mutexOpen ){
  62785. assert( sqlite3_mutex_held(mutexOpen) );
  62786. sqlite3_mutex_leave(mutexOpen);
  62787. }
  62788. assert( rc!=SQLITE_OK || sqlite3BtreeConnectionCount(*ppBtree)>0 );
  62789. return rc;
  62790. }
  62791. /*
  62792. ** Decrement the BtShared.nRef counter. When it reaches zero,
  62793. ** remove the BtShared structure from the sharing list. Return
  62794. ** true if the BtShared.nRef counter reaches zero and return
  62795. ** false if it is still positive.
  62796. */
  62797. static int removeFromSharingList(BtShared *pBt){
  62798. #ifndef SQLITE_OMIT_SHARED_CACHE
  62799. MUTEX_LOGIC( sqlite3_mutex *pMaster; )
  62800. BtShared *pList;
  62801. int removed = 0;
  62802. assert( sqlite3_mutex_notheld(pBt->mutex) );
  62803. MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
  62804. sqlite3_mutex_enter(pMaster);
  62805. pBt->nRef--;
  62806. if( pBt->nRef<=0 ){
  62807. if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
  62808. GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
  62809. }else{
  62810. pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
  62811. while( ALWAYS(pList) && pList->pNext!=pBt ){
  62812. pList=pList->pNext;
  62813. }
  62814. if( ALWAYS(pList) ){
  62815. pList->pNext = pBt->pNext;
  62816. }
  62817. }
  62818. if( SQLITE_THREADSAFE ){
  62819. sqlite3_mutex_free(pBt->mutex);
  62820. }
  62821. removed = 1;
  62822. }
  62823. sqlite3_mutex_leave(pMaster);
  62824. return removed;
  62825. #else
  62826. return 1;
  62827. #endif
  62828. }
  62829. /*
  62830. ** Make sure pBt->pTmpSpace points to an allocation of
  62831. ** MX_CELL_SIZE(pBt) bytes with a 4-byte prefix for a left-child
  62832. ** pointer.
  62833. */
  62834. static void allocateTempSpace(BtShared *pBt){
  62835. if( !pBt->pTmpSpace ){
  62836. pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
  62837. /* One of the uses of pBt->pTmpSpace is to format cells before
  62838. ** inserting them into a leaf page (function fillInCell()). If
  62839. ** a cell is less than 4 bytes in size, it is rounded up to 4 bytes
  62840. ** by the various routines that manipulate binary cells. Which
  62841. ** can mean that fillInCell() only initializes the first 2 or 3
  62842. ** bytes of pTmpSpace, but that the first 4 bytes are copied from
  62843. ** it into a database page. This is not actually a problem, but it
  62844. ** does cause a valgrind error when the 1 or 2 bytes of unitialized
  62845. ** data is passed to system call write(). So to avoid this error,
  62846. ** zero the first 4 bytes of temp space here.
  62847. **
  62848. ** Also: Provide four bytes of initialized space before the
  62849. ** beginning of pTmpSpace as an area available to prepend the
  62850. ** left-child pointer to the beginning of a cell.
  62851. */
  62852. if( pBt->pTmpSpace ){
  62853. memset(pBt->pTmpSpace, 0, 8);
  62854. pBt->pTmpSpace += 4;
  62855. }
  62856. }
  62857. }
  62858. /*
  62859. ** Free the pBt->pTmpSpace allocation
  62860. */
  62861. static void freeTempSpace(BtShared *pBt){
  62862. if( pBt->pTmpSpace ){
  62863. pBt->pTmpSpace -= 4;
  62864. sqlite3PageFree(pBt->pTmpSpace);
  62865. pBt->pTmpSpace = 0;
  62866. }
  62867. }
  62868. /*
  62869. ** Close an open database and invalidate all cursors.
  62870. */
  62871. SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){
  62872. BtShared *pBt = p->pBt;
  62873. BtCursor *pCur;
  62874. /* Close all cursors opened via this handle. */
  62875. assert( sqlite3_mutex_held(p->db->mutex) );
  62876. sqlite3BtreeEnter(p);
  62877. pCur = pBt->pCursor;
  62878. while( pCur ){
  62879. BtCursor *pTmp = pCur;
  62880. pCur = pCur->pNext;
  62881. if( pTmp->pBtree==p ){
  62882. sqlite3BtreeCloseCursor(pTmp);
  62883. }
  62884. }
  62885. /* Rollback any active transaction and free the handle structure.
  62886. ** The call to sqlite3BtreeRollback() drops any table-locks held by
  62887. ** this handle.
  62888. */
  62889. sqlite3BtreeRollback(p, SQLITE_OK, 0);
  62890. sqlite3BtreeLeave(p);
  62891. /* If there are still other outstanding references to the shared-btree
  62892. ** structure, return now. The remainder of this procedure cleans
  62893. ** up the shared-btree.
  62894. */
  62895. assert( p->wantToLock==0 && p->locked==0 );
  62896. if( !p->sharable || removeFromSharingList(pBt) ){
  62897. /* The pBt is no longer on the sharing list, so we can access
  62898. ** it without having to hold the mutex.
  62899. **
  62900. ** Clean out and delete the BtShared object.
  62901. */
  62902. assert( !pBt->pCursor );
  62903. sqlite3PagerClose(pBt->pPager, p->db);
  62904. if( pBt->xFreeSchema && pBt->pSchema ){
  62905. pBt->xFreeSchema(pBt->pSchema);
  62906. }
  62907. sqlite3DbFree(0, pBt->pSchema);
  62908. freeTempSpace(pBt);
  62909. sqlite3_free(pBt);
  62910. }
  62911. #ifndef SQLITE_OMIT_SHARED_CACHE
  62912. assert( p->wantToLock==0 );
  62913. assert( p->locked==0 );
  62914. if( p->pPrev ) p->pPrev->pNext = p->pNext;
  62915. if( p->pNext ) p->pNext->pPrev = p->pPrev;
  62916. #endif
  62917. sqlite3_free(p);
  62918. return SQLITE_OK;
  62919. }
  62920. /*
  62921. ** Change the "soft" limit on the number of pages in the cache.
  62922. ** Unused and unmodified pages will be recycled when the number of
  62923. ** pages in the cache exceeds this soft limit. But the size of the
  62924. ** cache is allowed to grow larger than this limit if it contains
  62925. ** dirty pages or pages still in active use.
  62926. */
  62927. SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
  62928. BtShared *pBt = p->pBt;
  62929. assert( sqlite3_mutex_held(p->db->mutex) );
  62930. sqlite3BtreeEnter(p);
  62931. sqlite3PagerSetCachesize(pBt->pPager, mxPage);
  62932. sqlite3BtreeLeave(p);
  62933. return SQLITE_OK;
  62934. }
  62935. /*
  62936. ** Change the "spill" limit on the number of pages in the cache.
  62937. ** If the number of pages exceeds this limit during a write transaction,
  62938. ** the pager might attempt to "spill" pages to the journal early in
  62939. ** order to free up memory.
  62940. **
  62941. ** The value returned is the current spill size. If zero is passed
  62942. ** as an argument, no changes are made to the spill size setting, so
  62943. ** using mxPage of 0 is a way to query the current spill size.
  62944. */
  62945. SQLITE_PRIVATE int sqlite3BtreeSetSpillSize(Btree *p, int mxPage){
  62946. BtShared *pBt = p->pBt;
  62947. int res;
  62948. assert( sqlite3_mutex_held(p->db->mutex) );
  62949. sqlite3BtreeEnter(p);
  62950. res = sqlite3PagerSetSpillsize(pBt->pPager, mxPage);
  62951. sqlite3BtreeLeave(p);
  62952. return res;
  62953. }
  62954. #if SQLITE_MAX_MMAP_SIZE>0
  62955. /*
  62956. ** Change the limit on the amount of the database file that may be
  62957. ** memory mapped.
  62958. */
  62959. SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree *p, sqlite3_int64 szMmap){
  62960. BtShared *pBt = p->pBt;
  62961. assert( sqlite3_mutex_held(p->db->mutex) );
  62962. sqlite3BtreeEnter(p);
  62963. sqlite3PagerSetMmapLimit(pBt->pPager, szMmap);
  62964. sqlite3BtreeLeave(p);
  62965. return SQLITE_OK;
  62966. }
  62967. #endif /* SQLITE_MAX_MMAP_SIZE>0 */
  62968. /*
  62969. ** Change the way data is synced to disk in order to increase or decrease
  62970. ** how well the database resists damage due to OS crashes and power
  62971. ** failures. Level 1 is the same as asynchronous (no syncs() occur and
  62972. ** there is a high probability of damage) Level 2 is the default. There
  62973. ** is a very low but non-zero probability of damage. Level 3 reduces the
  62974. ** probability of damage to near zero but with a write performance reduction.
  62975. */
  62976. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  62977. SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(
  62978. Btree *p, /* The btree to set the safety level on */
  62979. unsigned pgFlags /* Various PAGER_* flags */
  62980. ){
  62981. BtShared *pBt = p->pBt;
  62982. assert( sqlite3_mutex_held(p->db->mutex) );
  62983. sqlite3BtreeEnter(p);
  62984. sqlite3PagerSetFlags(pBt->pPager, pgFlags);
  62985. sqlite3BtreeLeave(p);
  62986. return SQLITE_OK;
  62987. }
  62988. #endif
  62989. /*
  62990. ** Change the default pages size and the number of reserved bytes per page.
  62991. ** Or, if the page size has already been fixed, return SQLITE_READONLY
  62992. ** without changing anything.
  62993. **
  62994. ** The page size must be a power of 2 between 512 and 65536. If the page
  62995. ** size supplied does not meet this constraint then the page size is not
  62996. ** changed.
  62997. **
  62998. ** Page sizes are constrained to be a power of two so that the region
  62999. ** of the database file used for locking (beginning at PENDING_BYTE,
  63000. ** the first byte past the 1GB boundary, 0x40000000) needs to occur
  63001. ** at the beginning of a page.
  63002. **
  63003. ** If parameter nReserve is less than zero, then the number of reserved
  63004. ** bytes per page is left unchanged.
  63005. **
  63006. ** If the iFix!=0 then the BTS_PAGESIZE_FIXED flag is set so that the page size
  63007. ** and autovacuum mode can no longer be changed.
  63008. */
  63009. SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
  63010. int rc = SQLITE_OK;
  63011. int x;
  63012. BtShared *pBt = p->pBt;
  63013. assert( nReserve>=0 && nReserve<=255 );
  63014. sqlite3BtreeEnter(p);
  63015. pBt->nReserveWanted = nReserve;
  63016. x = pBt->pageSize - pBt->usableSize;
  63017. if( nReserve<x ) nReserve = x;
  63018. if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){
  63019. sqlite3BtreeLeave(p);
  63020. return SQLITE_READONLY;
  63021. }
  63022. assert( nReserve>=0 && nReserve<=255 );
  63023. if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
  63024. ((pageSize-1)&pageSize)==0 ){
  63025. assert( (pageSize & 7)==0 );
  63026. assert( !pBt->pCursor );
  63027. pBt->pageSize = (u32)pageSize;
  63028. freeTempSpace(pBt);
  63029. }
  63030. rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
  63031. pBt->usableSize = pBt->pageSize - (u16)nReserve;
  63032. if( iFix ) pBt->btsFlags |= BTS_PAGESIZE_FIXED;
  63033. sqlite3BtreeLeave(p);
  63034. return rc;
  63035. }
  63036. /*
  63037. ** Return the currently defined page size
  63038. */
  63039. SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){
  63040. return p->pBt->pageSize;
  63041. }
  63042. /*
  63043. ** This function is similar to sqlite3BtreeGetReserve(), except that it
  63044. ** may only be called if it is guaranteed that the b-tree mutex is already
  63045. ** held.
  63046. **
  63047. ** This is useful in one special case in the backup API code where it is
  63048. ** known that the shared b-tree mutex is held, but the mutex on the
  63049. ** database handle that owns *p is not. In this case if sqlite3BtreeEnter()
  63050. ** were to be called, it might collide with some other operation on the
  63051. ** database handle that owns *p, causing undefined behavior.
  63052. */
  63053. SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p){
  63054. int n;
  63055. assert( sqlite3_mutex_held(p->pBt->mutex) );
  63056. n = p->pBt->pageSize - p->pBt->usableSize;
  63057. return n;
  63058. }
  63059. /*
  63060. ** Return the number of bytes of space at the end of every page that
  63061. ** are intentually left unused. This is the "reserved" space that is
  63062. ** sometimes used by extensions.
  63063. **
  63064. ** The value returned is the larger of the current reserve size and
  63065. ** the latest reserve size requested by SQLITE_FILECTRL_RESERVE_BYTES.
  63066. ** The amount of reserve can only grow - never shrink.
  63067. */
  63068. SQLITE_PRIVATE int sqlite3BtreeGetRequestedReserve(Btree *p){
  63069. int n1, n2;
  63070. sqlite3BtreeEnter(p);
  63071. n1 = (int)p->pBt->nReserveWanted;
  63072. n2 = sqlite3BtreeGetReserveNoMutex(p);
  63073. sqlite3BtreeLeave(p);
  63074. return n1>n2 ? n1 : n2;
  63075. }
  63076. /*
  63077. ** Set the maximum page count for a database if mxPage is positive.
  63078. ** No changes are made if mxPage is 0 or negative.
  63079. ** Regardless of the value of mxPage, return the maximum page count.
  63080. */
  63081. SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
  63082. int n;
  63083. sqlite3BtreeEnter(p);
  63084. n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
  63085. sqlite3BtreeLeave(p);
  63086. return n;
  63087. }
  63088. /*
  63089. ** Change the values for the BTS_SECURE_DELETE and BTS_OVERWRITE flags:
  63090. **
  63091. ** newFlag==0 Both BTS_SECURE_DELETE and BTS_OVERWRITE are cleared
  63092. ** newFlag==1 BTS_SECURE_DELETE set and BTS_OVERWRITE is cleared
  63093. ** newFlag==2 BTS_SECURE_DELETE cleared and BTS_OVERWRITE is set
  63094. ** newFlag==(-1) No changes
  63095. **
  63096. ** This routine acts as a query if newFlag is less than zero
  63097. **
  63098. ** With BTS_OVERWRITE set, deleted content is overwritten by zeros, but
  63099. ** freelist leaf pages are not written back to the database. Thus in-page
  63100. ** deleted content is cleared, but freelist deleted content is not.
  63101. **
  63102. ** With BTS_SECURE_DELETE, operation is like BTS_OVERWRITE with the addition
  63103. ** that freelist leaf pages are written back into the database, increasing
  63104. ** the amount of disk I/O.
  63105. */
  63106. SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
  63107. int b;
  63108. if( p==0 ) return 0;
  63109. sqlite3BtreeEnter(p);
  63110. assert( BTS_OVERWRITE==BTS_SECURE_DELETE*2 );
  63111. assert( BTS_FAST_SECURE==(BTS_OVERWRITE|BTS_SECURE_DELETE) );
  63112. if( newFlag>=0 ){
  63113. p->pBt->btsFlags &= ~BTS_FAST_SECURE;
  63114. p->pBt->btsFlags |= BTS_SECURE_DELETE*newFlag;
  63115. }
  63116. b = (p->pBt->btsFlags & BTS_FAST_SECURE)/BTS_SECURE_DELETE;
  63117. sqlite3BtreeLeave(p);
  63118. return b;
  63119. }
  63120. /*
  63121. ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
  63122. ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
  63123. ** is disabled. The default value for the auto-vacuum property is
  63124. ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
  63125. */
  63126. SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
  63127. #ifdef SQLITE_OMIT_AUTOVACUUM
  63128. return SQLITE_READONLY;
  63129. #else
  63130. BtShared *pBt = p->pBt;
  63131. int rc = SQLITE_OK;
  63132. u8 av = (u8)autoVacuum;
  63133. sqlite3BtreeEnter(p);
  63134. if( (pBt->btsFlags & BTS_PAGESIZE_FIXED)!=0 && (av ?1:0)!=pBt->autoVacuum ){
  63135. rc = SQLITE_READONLY;
  63136. }else{
  63137. pBt->autoVacuum = av ?1:0;
  63138. pBt->incrVacuum = av==2 ?1:0;
  63139. }
  63140. sqlite3BtreeLeave(p);
  63141. return rc;
  63142. #endif
  63143. }
  63144. /*
  63145. ** Return the value of the 'auto-vacuum' property. If auto-vacuum is
  63146. ** enabled 1 is returned. Otherwise 0.
  63147. */
  63148. SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){
  63149. #ifdef SQLITE_OMIT_AUTOVACUUM
  63150. return BTREE_AUTOVACUUM_NONE;
  63151. #else
  63152. int rc;
  63153. sqlite3BtreeEnter(p);
  63154. rc = (
  63155. (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
  63156. (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
  63157. BTREE_AUTOVACUUM_INCR
  63158. );
  63159. sqlite3BtreeLeave(p);
  63160. return rc;
  63161. #endif
  63162. }
  63163. /*
  63164. ** If the user has not set the safety-level for this database connection
  63165. ** using "PRAGMA synchronous", and if the safety-level is not already
  63166. ** set to the value passed to this function as the second parameter,
  63167. ** set it so.
  63168. */
  63169. #if SQLITE_DEFAULT_SYNCHRONOUS!=SQLITE_DEFAULT_WAL_SYNCHRONOUS \
  63170. && !defined(SQLITE_OMIT_WAL)
  63171. static void setDefaultSyncFlag(BtShared *pBt, u8 safety_level){
  63172. sqlite3 *db;
  63173. Db *pDb;
  63174. if( (db=pBt->db)!=0 && (pDb=db->aDb)!=0 ){
  63175. while( pDb->pBt==0 || pDb->pBt->pBt!=pBt ){ pDb++; }
  63176. if( pDb->bSyncSet==0
  63177. && pDb->safety_level!=safety_level
  63178. && pDb!=&db->aDb[1]
  63179. ){
  63180. pDb->safety_level = safety_level;
  63181. sqlite3PagerSetFlags(pBt->pPager,
  63182. pDb->safety_level | (db->flags & PAGER_FLAGS_MASK));
  63183. }
  63184. }
  63185. }
  63186. #else
  63187. # define setDefaultSyncFlag(pBt,safety_level)
  63188. #endif
  63189. /* Forward declaration */
  63190. static int newDatabase(BtShared*);
  63191. /*
  63192. ** Get a reference to pPage1 of the database file. This will
  63193. ** also acquire a readlock on that file.
  63194. **
  63195. ** SQLITE_OK is returned on success. If the file is not a
  63196. ** well-formed database file, then SQLITE_CORRUPT is returned.
  63197. ** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM
  63198. ** is returned if we run out of memory.
  63199. */
  63200. static int lockBtree(BtShared *pBt){
  63201. int rc; /* Result code from subfunctions */
  63202. MemPage *pPage1; /* Page 1 of the database file */
  63203. u32 nPage; /* Number of pages in the database */
  63204. u32 nPageFile = 0; /* Number of pages in the database file */
  63205. u32 nPageHeader; /* Number of pages in the database according to hdr */
  63206. assert( sqlite3_mutex_held(pBt->mutex) );
  63207. assert( pBt->pPage1==0 );
  63208. rc = sqlite3PagerSharedLock(pBt->pPager);
  63209. if( rc!=SQLITE_OK ) return rc;
  63210. rc = btreeGetPage(pBt, 1, &pPage1, 0);
  63211. if( rc!=SQLITE_OK ) return rc;
  63212. /* Do some checking to help insure the file we opened really is
  63213. ** a valid database file.
  63214. */
  63215. nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
  63216. sqlite3PagerPagecount(pBt->pPager, (int*)&nPageFile);
  63217. if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
  63218. nPage = nPageFile;
  63219. }
  63220. if( (pBt->db->flags & SQLITE_ResetDatabase)!=0 ){
  63221. nPage = 0;
  63222. }
  63223. if( nPage>0 ){
  63224. u32 pageSize;
  63225. u32 usableSize;
  63226. u8 *page1 = pPage1->aData;
  63227. rc = SQLITE_NOTADB;
  63228. /* EVIDENCE-OF: R-43737-39999 Every valid SQLite database file begins
  63229. ** with the following 16 bytes (in hex): 53 51 4c 69 74 65 20 66 6f 72 6d
  63230. ** 61 74 20 33 00. */
  63231. if( memcmp(page1, zMagicHeader, 16)!=0 ){
  63232. goto page1_init_failed;
  63233. }
  63234. #ifdef SQLITE_OMIT_WAL
  63235. if( page1[18]>1 ){
  63236. pBt->btsFlags |= BTS_READ_ONLY;
  63237. }
  63238. if( page1[19]>1 ){
  63239. goto page1_init_failed;
  63240. }
  63241. #else
  63242. if( page1[18]>2 ){
  63243. pBt->btsFlags |= BTS_READ_ONLY;
  63244. }
  63245. if( page1[19]>2 ){
  63246. goto page1_init_failed;
  63247. }
  63248. /* If the write version is set to 2, this database should be accessed
  63249. ** in WAL mode. If the log is not already open, open it now. Then
  63250. ** return SQLITE_OK and return without populating BtShared.pPage1.
  63251. ** The caller detects this and calls this function again. This is
  63252. ** required as the version of page 1 currently in the page1 buffer
  63253. ** may not be the latest version - there may be a newer one in the log
  63254. ** file.
  63255. */
  63256. if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){
  63257. int isOpen = 0;
  63258. rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
  63259. if( rc!=SQLITE_OK ){
  63260. goto page1_init_failed;
  63261. }else{
  63262. setDefaultSyncFlag(pBt, SQLITE_DEFAULT_WAL_SYNCHRONOUS+1);
  63263. if( isOpen==0 ){
  63264. releasePageOne(pPage1);
  63265. return SQLITE_OK;
  63266. }
  63267. }
  63268. rc = SQLITE_NOTADB;
  63269. }else{
  63270. setDefaultSyncFlag(pBt, SQLITE_DEFAULT_SYNCHRONOUS+1);
  63271. }
  63272. #endif
  63273. /* EVIDENCE-OF: R-15465-20813 The maximum and minimum embedded payload
  63274. ** fractions and the leaf payload fraction values must be 64, 32, and 32.
  63275. **
  63276. ** The original design allowed these amounts to vary, but as of
  63277. ** version 3.6.0, we require them to be fixed.
  63278. */
  63279. if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
  63280. goto page1_init_failed;
  63281. }
  63282. /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
  63283. ** determined by the 2-byte integer located at an offset of 16 bytes from
  63284. ** the beginning of the database file. */
  63285. pageSize = (page1[16]<<8) | (page1[17]<<16);
  63286. /* EVIDENCE-OF: R-25008-21688 The size of a page is a power of two
  63287. ** between 512 and 65536 inclusive. */
  63288. if( ((pageSize-1)&pageSize)!=0
  63289. || pageSize>SQLITE_MAX_PAGE_SIZE
  63290. || pageSize<=256
  63291. ){
  63292. goto page1_init_failed;
  63293. }
  63294. pBt->btsFlags |= BTS_PAGESIZE_FIXED;
  63295. assert( (pageSize & 7)==0 );
  63296. /* EVIDENCE-OF: R-59310-51205 The "reserved space" size in the 1-byte
  63297. ** integer at offset 20 is the number of bytes of space at the end of
  63298. ** each page to reserve for extensions.
  63299. **
  63300. ** EVIDENCE-OF: R-37497-42412 The size of the reserved region is
  63301. ** determined by the one-byte unsigned integer found at an offset of 20
  63302. ** into the database file header. */
  63303. usableSize = pageSize - page1[20];
  63304. if( (u32)pageSize!=pBt->pageSize ){
  63305. /* After reading the first page of the database assuming a page size
  63306. ** of BtShared.pageSize, we have discovered that the page-size is
  63307. ** actually pageSize. Unlock the database, leave pBt->pPage1 at
  63308. ** zero and return SQLITE_OK. The caller will call this function
  63309. ** again with the correct page-size.
  63310. */
  63311. releasePageOne(pPage1);
  63312. pBt->usableSize = usableSize;
  63313. pBt->pageSize = pageSize;
  63314. freeTempSpace(pBt);
  63315. rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
  63316. pageSize-usableSize);
  63317. return rc;
  63318. }
  63319. if( sqlite3WritableSchema(pBt->db)==0 && nPage>nPageFile ){
  63320. rc = SQLITE_CORRUPT_BKPT;
  63321. goto page1_init_failed;
  63322. }
  63323. /* EVIDENCE-OF: R-28312-64704 However, the usable size is not allowed to
  63324. ** be less than 480. In other words, if the page size is 512, then the
  63325. ** reserved space size cannot exceed 32. */
  63326. if( usableSize<480 ){
  63327. goto page1_init_failed;
  63328. }
  63329. pBt->pageSize = pageSize;
  63330. pBt->usableSize = usableSize;
  63331. #ifndef SQLITE_OMIT_AUTOVACUUM
  63332. pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
  63333. pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
  63334. #endif
  63335. }
  63336. /* maxLocal is the maximum amount of payload to store locally for
  63337. ** a cell. Make sure it is small enough so that at least minFanout
  63338. ** cells can will fit on one page. We assume a 10-byte page header.
  63339. ** Besides the payload, the cell must store:
  63340. ** 2-byte pointer to the cell
  63341. ** 4-byte child pointer
  63342. ** 9-byte nKey value
  63343. ** 4-byte nData value
  63344. ** 4-byte overflow page pointer
  63345. ** So a cell consists of a 2-byte pointer, a header which is as much as
  63346. ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
  63347. ** page pointer.
  63348. */
  63349. pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
  63350. pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
  63351. pBt->maxLeaf = (u16)(pBt->usableSize - 35);
  63352. pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
  63353. if( pBt->maxLocal>127 ){
  63354. pBt->max1bytePayload = 127;
  63355. }else{
  63356. pBt->max1bytePayload = (u8)pBt->maxLocal;
  63357. }
  63358. assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
  63359. pBt->pPage1 = pPage1;
  63360. pBt->nPage = nPage;
  63361. return SQLITE_OK;
  63362. page1_init_failed:
  63363. releasePageOne(pPage1);
  63364. pBt->pPage1 = 0;
  63365. return rc;
  63366. }
  63367. #ifndef NDEBUG
  63368. /*
  63369. ** Return the number of cursors open on pBt. This is for use
  63370. ** in assert() expressions, so it is only compiled if NDEBUG is not
  63371. ** defined.
  63372. **
  63373. ** Only write cursors are counted if wrOnly is true. If wrOnly is
  63374. ** false then all cursors are counted.
  63375. **
  63376. ** For the purposes of this routine, a cursor is any cursor that
  63377. ** is capable of reading or writing to the database. Cursors that
  63378. ** have been tripped into the CURSOR_FAULT state are not counted.
  63379. */
  63380. static int countValidCursors(BtShared *pBt, int wrOnly){
  63381. BtCursor *pCur;
  63382. int r = 0;
  63383. for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
  63384. if( (wrOnly==0 || (pCur->curFlags & BTCF_WriteFlag)!=0)
  63385. && pCur->eState!=CURSOR_FAULT ) r++;
  63386. }
  63387. return r;
  63388. }
  63389. #endif
  63390. /*
  63391. ** If there are no outstanding cursors and we are not in the middle
  63392. ** of a transaction but there is a read lock on the database, then
  63393. ** this routine unrefs the first page of the database file which
  63394. ** has the effect of releasing the read lock.
  63395. **
  63396. ** If there is a transaction in progress, this routine is a no-op.
  63397. */
  63398. static void unlockBtreeIfUnused(BtShared *pBt){
  63399. assert( sqlite3_mutex_held(pBt->mutex) );
  63400. assert( countValidCursors(pBt,0)==0 || pBt->inTransaction>TRANS_NONE );
  63401. if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
  63402. MemPage *pPage1 = pBt->pPage1;
  63403. assert( pPage1->aData );
  63404. assert( sqlite3PagerRefcount(pBt->pPager)==1 );
  63405. pBt->pPage1 = 0;
  63406. releasePageOne(pPage1);
  63407. }
  63408. }
  63409. /*
  63410. ** If pBt points to an empty file then convert that empty file
  63411. ** into a new empty database by initializing the first page of
  63412. ** the database.
  63413. */
  63414. static int newDatabase(BtShared *pBt){
  63415. MemPage *pP1;
  63416. unsigned char *data;
  63417. int rc;
  63418. assert( sqlite3_mutex_held(pBt->mutex) );
  63419. if( pBt->nPage>0 ){
  63420. return SQLITE_OK;
  63421. }
  63422. pP1 = pBt->pPage1;
  63423. assert( pP1!=0 );
  63424. data = pP1->aData;
  63425. rc = sqlite3PagerWrite(pP1->pDbPage);
  63426. if( rc ) return rc;
  63427. memcpy(data, zMagicHeader, sizeof(zMagicHeader));
  63428. assert( sizeof(zMagicHeader)==16 );
  63429. data[16] = (u8)((pBt->pageSize>>8)&0xff);
  63430. data[17] = (u8)((pBt->pageSize>>16)&0xff);
  63431. data[18] = 1;
  63432. data[19] = 1;
  63433. assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
  63434. data[20] = (u8)(pBt->pageSize - pBt->usableSize);
  63435. data[21] = 64;
  63436. data[22] = 32;
  63437. data[23] = 32;
  63438. memset(&data[24], 0, 100-24);
  63439. zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
  63440. pBt->btsFlags |= BTS_PAGESIZE_FIXED;
  63441. #ifndef SQLITE_OMIT_AUTOVACUUM
  63442. assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
  63443. assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
  63444. put4byte(&data[36 + 4*4], pBt->autoVacuum);
  63445. put4byte(&data[36 + 7*4], pBt->incrVacuum);
  63446. #endif
  63447. pBt->nPage = 1;
  63448. data[31] = 1;
  63449. return SQLITE_OK;
  63450. }
  63451. /*
  63452. ** Initialize the first page of the database file (creating a database
  63453. ** consisting of a single page and no schema objects). Return SQLITE_OK
  63454. ** if successful, or an SQLite error code otherwise.
  63455. */
  63456. SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p){
  63457. int rc;
  63458. sqlite3BtreeEnter(p);
  63459. p->pBt->nPage = 0;
  63460. rc = newDatabase(p->pBt);
  63461. sqlite3BtreeLeave(p);
  63462. return rc;
  63463. }
  63464. /*
  63465. ** Attempt to start a new transaction. A write-transaction
  63466. ** is started if the second argument is nonzero, otherwise a read-
  63467. ** transaction. If the second argument is 2 or more and exclusive
  63468. ** transaction is started, meaning that no other process is allowed
  63469. ** to access the database. A preexisting transaction may not be
  63470. ** upgraded to exclusive by calling this routine a second time - the
  63471. ** exclusivity flag only works for a new transaction.
  63472. **
  63473. ** A write-transaction must be started before attempting any
  63474. ** changes to the database. None of the following routines
  63475. ** will work unless a transaction is started first:
  63476. **
  63477. ** sqlite3BtreeCreateTable()
  63478. ** sqlite3BtreeCreateIndex()
  63479. ** sqlite3BtreeClearTable()
  63480. ** sqlite3BtreeDropTable()
  63481. ** sqlite3BtreeInsert()
  63482. ** sqlite3BtreeDelete()
  63483. ** sqlite3BtreeUpdateMeta()
  63484. **
  63485. ** If an initial attempt to acquire the lock fails because of lock contention
  63486. ** and the database was previously unlocked, then invoke the busy handler
  63487. ** if there is one. But if there was previously a read-lock, do not
  63488. ** invoke the busy handler - just return SQLITE_BUSY. SQLITE_BUSY is
  63489. ** returned when there is already a read-lock in order to avoid a deadlock.
  63490. **
  63491. ** Suppose there are two processes A and B. A has a read lock and B has
  63492. ** a reserved lock. B tries to promote to exclusive but is blocked because
  63493. ** of A's read lock. A tries to promote to reserved but is blocked by B.
  63494. ** One or the other of the two processes must give way or there can be
  63495. ** no progress. By returning SQLITE_BUSY and not invoking the busy callback
  63496. ** when A already has a read lock, we encourage A to give up and let B
  63497. ** proceed.
  63498. */
  63499. SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag, int *pSchemaVersion){
  63500. BtShared *pBt = p->pBt;
  63501. Pager *pPager = pBt->pPager;
  63502. int rc = SQLITE_OK;
  63503. sqlite3BtreeEnter(p);
  63504. btreeIntegrity(p);
  63505. /* If the btree is already in a write-transaction, or it
  63506. ** is already in a read-transaction and a read-transaction
  63507. ** is requested, this is a no-op.
  63508. */
  63509. if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
  63510. goto trans_begun;
  63511. }
  63512. assert( pBt->inTransaction==TRANS_WRITE || IfNotOmitAV(pBt->bDoTruncate)==0 );
  63513. if( (p->db->flags & SQLITE_ResetDatabase)
  63514. && sqlite3PagerIsreadonly(pPager)==0
  63515. ){
  63516. pBt->btsFlags &= ~BTS_READ_ONLY;
  63517. }
  63518. /* Write transactions are not possible on a read-only database */
  63519. if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){
  63520. rc = SQLITE_READONLY;
  63521. goto trans_begun;
  63522. }
  63523. #ifndef SQLITE_OMIT_SHARED_CACHE
  63524. {
  63525. sqlite3 *pBlock = 0;
  63526. /* If another database handle has already opened a write transaction
  63527. ** on this shared-btree structure and a second write transaction is
  63528. ** requested, return SQLITE_LOCKED.
  63529. */
  63530. if( (wrflag && pBt->inTransaction==TRANS_WRITE)
  63531. || (pBt->btsFlags & BTS_PENDING)!=0
  63532. ){
  63533. pBlock = pBt->pWriter->db;
  63534. }else if( wrflag>1 ){
  63535. BtLock *pIter;
  63536. for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
  63537. if( pIter->pBtree!=p ){
  63538. pBlock = pIter->pBtree->db;
  63539. break;
  63540. }
  63541. }
  63542. }
  63543. if( pBlock ){
  63544. sqlite3ConnectionBlocked(p->db, pBlock);
  63545. rc = SQLITE_LOCKED_SHAREDCACHE;
  63546. goto trans_begun;
  63547. }
  63548. }
  63549. #endif
  63550. /* Any read-only or read-write transaction implies a read-lock on
  63551. ** page 1. So if some other shared-cache client already has a write-lock
  63552. ** on page 1, the transaction cannot be opened. */
  63553. rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
  63554. if( SQLITE_OK!=rc ) goto trans_begun;
  63555. pBt->btsFlags &= ~BTS_INITIALLY_EMPTY;
  63556. if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY;
  63557. do {
  63558. sqlite3PagerWalDb(pPager, p->db);
  63559. #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
  63560. /* If transitioning from no transaction directly to a write transaction,
  63561. ** block for the WRITER lock first if possible. */
  63562. if( pBt->pPage1==0 && wrflag ){
  63563. assert( pBt->inTransaction==TRANS_NONE );
  63564. rc = sqlite3PagerWalWriteLock(pPager, 1);
  63565. if( rc!=SQLITE_BUSY && rc!=SQLITE_OK ) break;
  63566. }
  63567. #endif
  63568. /* Call lockBtree() until either pBt->pPage1 is populated or
  63569. ** lockBtree() returns something other than SQLITE_OK. lockBtree()
  63570. ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
  63571. ** reading page 1 it discovers that the page-size of the database
  63572. ** file is not pBt->pageSize. In this case lockBtree() will update
  63573. ** pBt->pageSize to the page-size of the file on disk.
  63574. */
  63575. while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
  63576. if( rc==SQLITE_OK && wrflag ){
  63577. if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){
  63578. rc = SQLITE_READONLY;
  63579. }else{
  63580. rc = sqlite3PagerBegin(pPager, wrflag>1, sqlite3TempInMemory(p->db));
  63581. if( rc==SQLITE_OK ){
  63582. rc = newDatabase(pBt);
  63583. }else if( rc==SQLITE_BUSY_SNAPSHOT && pBt->inTransaction==TRANS_NONE ){
  63584. /* if there was no transaction opened when this function was
  63585. ** called and SQLITE_BUSY_SNAPSHOT is returned, change the error
  63586. ** code to SQLITE_BUSY. */
  63587. rc = SQLITE_BUSY;
  63588. }
  63589. }
  63590. }
  63591. if( rc!=SQLITE_OK ){
  63592. (void)sqlite3PagerWalWriteLock(pPager, 0);
  63593. unlockBtreeIfUnused(pBt);
  63594. }
  63595. }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
  63596. btreeInvokeBusyHandler(pBt) );
  63597. sqlite3PagerWalDb(pPager, 0);
  63598. #ifdef SQLITE_ENABLE_SETLK_TIMEOUT
  63599. if( rc==SQLITE_BUSY_TIMEOUT ) rc = SQLITE_BUSY;
  63600. #endif
  63601. if( rc==SQLITE_OK ){
  63602. if( p->inTrans==TRANS_NONE ){
  63603. pBt->nTransaction++;
  63604. #ifndef SQLITE_OMIT_SHARED_CACHE
  63605. if( p->sharable ){
  63606. assert( p->lock.pBtree==p && p->lock.iTable==1 );
  63607. p->lock.eLock = READ_LOCK;
  63608. p->lock.pNext = pBt->pLock;
  63609. pBt->pLock = &p->lock;
  63610. }
  63611. #endif
  63612. }
  63613. p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
  63614. if( p->inTrans>pBt->inTransaction ){
  63615. pBt->inTransaction = p->inTrans;
  63616. }
  63617. if( wrflag ){
  63618. MemPage *pPage1 = pBt->pPage1;
  63619. #ifndef SQLITE_OMIT_SHARED_CACHE
  63620. assert( !pBt->pWriter );
  63621. pBt->pWriter = p;
  63622. pBt->btsFlags &= ~BTS_EXCLUSIVE;
  63623. if( wrflag>1 ) pBt->btsFlags |= BTS_EXCLUSIVE;
  63624. #endif
  63625. /* If the db-size header field is incorrect (as it may be if an old
  63626. ** client has been writing the database file), update it now. Doing
  63627. ** this sooner rather than later means the database size can safely
  63628. ** re-read the database size from page 1 if a savepoint or transaction
  63629. ** rollback occurs within the transaction.
  63630. */
  63631. if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
  63632. rc = sqlite3PagerWrite(pPage1->pDbPage);
  63633. if( rc==SQLITE_OK ){
  63634. put4byte(&pPage1->aData[28], pBt->nPage);
  63635. }
  63636. }
  63637. }
  63638. }
  63639. trans_begun:
  63640. if( rc==SQLITE_OK ){
  63641. if( pSchemaVersion ){
  63642. *pSchemaVersion = get4byte(&pBt->pPage1->aData[40]);
  63643. }
  63644. if( wrflag ){
  63645. /* This call makes sure that the pager has the correct number of
  63646. ** open savepoints. If the second parameter is greater than 0 and
  63647. ** the sub-journal is not already open, then it will be opened here.
  63648. */
  63649. rc = sqlite3PagerOpenSavepoint(pPager, p->db->nSavepoint);
  63650. }
  63651. }
  63652. btreeIntegrity(p);
  63653. sqlite3BtreeLeave(p);
  63654. return rc;
  63655. }
  63656. #ifndef SQLITE_OMIT_AUTOVACUUM
  63657. /*
  63658. ** Set the pointer-map entries for all children of page pPage. Also, if
  63659. ** pPage contains cells that point to overflow pages, set the pointer
  63660. ** map entries for the overflow pages as well.
  63661. */
  63662. static int setChildPtrmaps(MemPage *pPage){
  63663. int i; /* Counter variable */
  63664. int nCell; /* Number of cells in page pPage */
  63665. int rc; /* Return code */
  63666. BtShared *pBt = pPage->pBt;
  63667. Pgno pgno = pPage->pgno;
  63668. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  63669. rc = pPage->isInit ? SQLITE_OK : btreeInitPage(pPage);
  63670. if( rc!=SQLITE_OK ) return rc;
  63671. nCell = pPage->nCell;
  63672. for(i=0; i<nCell; i++){
  63673. u8 *pCell = findCell(pPage, i);
  63674. ptrmapPutOvflPtr(pPage, pPage, pCell, &rc);
  63675. if( !pPage->leaf ){
  63676. Pgno childPgno = get4byte(pCell);
  63677. ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
  63678. }
  63679. }
  63680. if( !pPage->leaf ){
  63681. Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  63682. ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
  63683. }
  63684. return rc;
  63685. }
  63686. /*
  63687. ** Somewhere on pPage is a pointer to page iFrom. Modify this pointer so
  63688. ** that it points to iTo. Parameter eType describes the type of pointer to
  63689. ** be modified, as follows:
  63690. **
  63691. ** PTRMAP_BTREE: pPage is a btree-page. The pointer points at a child
  63692. ** page of pPage.
  63693. **
  63694. ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
  63695. ** page pointed to by one of the cells on pPage.
  63696. **
  63697. ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
  63698. ** overflow page in the list.
  63699. */
  63700. static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
  63701. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  63702. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  63703. if( eType==PTRMAP_OVERFLOW2 ){
  63704. /* The pointer is always the first 4 bytes of the page in this case. */
  63705. if( get4byte(pPage->aData)!=iFrom ){
  63706. return SQLITE_CORRUPT_PAGE(pPage);
  63707. }
  63708. put4byte(pPage->aData, iTo);
  63709. }else{
  63710. int i;
  63711. int nCell;
  63712. int rc;
  63713. rc = pPage->isInit ? SQLITE_OK : btreeInitPage(pPage);
  63714. if( rc ) return rc;
  63715. nCell = pPage->nCell;
  63716. for(i=0; i<nCell; i++){
  63717. u8 *pCell = findCell(pPage, i);
  63718. if( eType==PTRMAP_OVERFLOW1 ){
  63719. CellInfo info;
  63720. pPage->xParseCell(pPage, pCell, &info);
  63721. if( info.nLocal<info.nPayload ){
  63722. if( pCell+info.nSize > pPage->aData+pPage->pBt->usableSize ){
  63723. return SQLITE_CORRUPT_PAGE(pPage);
  63724. }
  63725. if( iFrom==get4byte(pCell+info.nSize-4) ){
  63726. put4byte(pCell+info.nSize-4, iTo);
  63727. break;
  63728. }
  63729. }
  63730. }else{
  63731. if( get4byte(pCell)==iFrom ){
  63732. put4byte(pCell, iTo);
  63733. break;
  63734. }
  63735. }
  63736. }
  63737. if( i==nCell ){
  63738. if( eType!=PTRMAP_BTREE ||
  63739. get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
  63740. return SQLITE_CORRUPT_PAGE(pPage);
  63741. }
  63742. put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
  63743. }
  63744. }
  63745. return SQLITE_OK;
  63746. }
  63747. /*
  63748. ** Move the open database page pDbPage to location iFreePage in the
  63749. ** database. The pDbPage reference remains valid.
  63750. **
  63751. ** The isCommit flag indicates that there is no need to remember that
  63752. ** the journal needs to be sync()ed before database page pDbPage->pgno
  63753. ** can be written to. The caller has already promised not to write to that
  63754. ** page.
  63755. */
  63756. static int relocatePage(
  63757. BtShared *pBt, /* Btree */
  63758. MemPage *pDbPage, /* Open page to move */
  63759. u8 eType, /* Pointer map 'type' entry for pDbPage */
  63760. Pgno iPtrPage, /* Pointer map 'page-no' entry for pDbPage */
  63761. Pgno iFreePage, /* The location to move pDbPage to */
  63762. int isCommit /* isCommit flag passed to sqlite3PagerMovepage */
  63763. ){
  63764. MemPage *pPtrPage; /* The page that contains a pointer to pDbPage */
  63765. Pgno iDbPage = pDbPage->pgno;
  63766. Pager *pPager = pBt->pPager;
  63767. int rc;
  63768. assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
  63769. eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
  63770. assert( sqlite3_mutex_held(pBt->mutex) );
  63771. assert( pDbPage->pBt==pBt );
  63772. if( iDbPage<3 ) return SQLITE_CORRUPT_BKPT;
  63773. /* Move page iDbPage from its current location to page number iFreePage */
  63774. TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
  63775. iDbPage, iFreePage, iPtrPage, eType));
  63776. rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
  63777. if( rc!=SQLITE_OK ){
  63778. return rc;
  63779. }
  63780. pDbPage->pgno = iFreePage;
  63781. /* If pDbPage was a btree-page, then it may have child pages and/or cells
  63782. ** that point to overflow pages. The pointer map entries for all these
  63783. ** pages need to be changed.
  63784. **
  63785. ** If pDbPage is an overflow page, then the first 4 bytes may store a
  63786. ** pointer to a subsequent overflow page. If this is the case, then
  63787. ** the pointer map needs to be updated for the subsequent overflow page.
  63788. */
  63789. if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
  63790. rc = setChildPtrmaps(pDbPage);
  63791. if( rc!=SQLITE_OK ){
  63792. return rc;
  63793. }
  63794. }else{
  63795. Pgno nextOvfl = get4byte(pDbPage->aData);
  63796. if( nextOvfl!=0 ){
  63797. ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
  63798. if( rc!=SQLITE_OK ){
  63799. return rc;
  63800. }
  63801. }
  63802. }
  63803. /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
  63804. ** that it points at iFreePage. Also fix the pointer map entry for
  63805. ** iPtrPage.
  63806. */
  63807. if( eType!=PTRMAP_ROOTPAGE ){
  63808. rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
  63809. if( rc!=SQLITE_OK ){
  63810. return rc;
  63811. }
  63812. rc = sqlite3PagerWrite(pPtrPage->pDbPage);
  63813. if( rc!=SQLITE_OK ){
  63814. releasePage(pPtrPage);
  63815. return rc;
  63816. }
  63817. rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
  63818. releasePage(pPtrPage);
  63819. if( rc==SQLITE_OK ){
  63820. ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
  63821. }
  63822. }
  63823. return rc;
  63824. }
  63825. /* Forward declaration required by incrVacuumStep(). */
  63826. static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
  63827. /*
  63828. ** Perform a single step of an incremental-vacuum. If successful, return
  63829. ** SQLITE_OK. If there is no work to do (and therefore no point in
  63830. ** calling this function again), return SQLITE_DONE. Or, if an error
  63831. ** occurs, return some other error code.
  63832. **
  63833. ** More specifically, this function attempts to re-organize the database so
  63834. ** that the last page of the file currently in use is no longer in use.
  63835. **
  63836. ** Parameter nFin is the number of pages that this database would contain
  63837. ** were this function called until it returns SQLITE_DONE.
  63838. **
  63839. ** If the bCommit parameter is non-zero, this function assumes that the
  63840. ** caller will keep calling incrVacuumStep() until it returns SQLITE_DONE
  63841. ** or an error. bCommit is passed true for an auto-vacuum-on-commit
  63842. ** operation, or false for an incremental vacuum.
  63843. */
  63844. static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg, int bCommit){
  63845. Pgno nFreeList; /* Number of pages still on the free-list */
  63846. int rc;
  63847. assert( sqlite3_mutex_held(pBt->mutex) );
  63848. assert( iLastPg>nFin );
  63849. if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
  63850. u8 eType;
  63851. Pgno iPtrPage;
  63852. nFreeList = get4byte(&pBt->pPage1->aData[36]);
  63853. if( nFreeList==0 ){
  63854. return SQLITE_DONE;
  63855. }
  63856. rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
  63857. if( rc!=SQLITE_OK ){
  63858. return rc;
  63859. }
  63860. if( eType==PTRMAP_ROOTPAGE ){
  63861. return SQLITE_CORRUPT_BKPT;
  63862. }
  63863. if( eType==PTRMAP_FREEPAGE ){
  63864. if( bCommit==0 ){
  63865. /* Remove the page from the files free-list. This is not required
  63866. ** if bCommit is non-zero. In that case, the free-list will be
  63867. ** truncated to zero after this function returns, so it doesn't
  63868. ** matter if it still contains some garbage entries.
  63869. */
  63870. Pgno iFreePg;
  63871. MemPage *pFreePg;
  63872. rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, BTALLOC_EXACT);
  63873. if( rc!=SQLITE_OK ){
  63874. return rc;
  63875. }
  63876. assert( iFreePg==iLastPg );
  63877. releasePage(pFreePg);
  63878. }
  63879. } else {
  63880. Pgno iFreePg; /* Index of free page to move pLastPg to */
  63881. MemPage *pLastPg;
  63882. u8 eMode = BTALLOC_ANY; /* Mode parameter for allocateBtreePage() */
  63883. Pgno iNear = 0; /* nearby parameter for allocateBtreePage() */
  63884. rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
  63885. if( rc!=SQLITE_OK ){
  63886. return rc;
  63887. }
  63888. /* If bCommit is zero, this loop runs exactly once and page pLastPg
  63889. ** is swapped with the first free page pulled off the free list.
  63890. **
  63891. ** On the other hand, if bCommit is greater than zero, then keep
  63892. ** looping until a free-page located within the first nFin pages
  63893. ** of the file is found.
  63894. */
  63895. if( bCommit==0 ){
  63896. eMode = BTALLOC_LE;
  63897. iNear = nFin;
  63898. }
  63899. do {
  63900. MemPage *pFreePg;
  63901. rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iNear, eMode);
  63902. if( rc!=SQLITE_OK ){
  63903. releasePage(pLastPg);
  63904. return rc;
  63905. }
  63906. releasePage(pFreePg);
  63907. }while( bCommit && iFreePg>nFin );
  63908. assert( iFreePg<iLastPg );
  63909. rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, bCommit);
  63910. releasePage(pLastPg);
  63911. if( rc!=SQLITE_OK ){
  63912. return rc;
  63913. }
  63914. }
  63915. }
  63916. if( bCommit==0 ){
  63917. do {
  63918. iLastPg--;
  63919. }while( iLastPg==PENDING_BYTE_PAGE(pBt) || PTRMAP_ISPAGE(pBt, iLastPg) );
  63920. pBt->bDoTruncate = 1;
  63921. pBt->nPage = iLastPg;
  63922. }
  63923. return SQLITE_OK;
  63924. }
  63925. /*
  63926. ** The database opened by the first argument is an auto-vacuum database
  63927. ** nOrig pages in size containing nFree free pages. Return the expected
  63928. ** size of the database in pages following an auto-vacuum operation.
  63929. */
  63930. static Pgno finalDbSize(BtShared *pBt, Pgno nOrig, Pgno nFree){
  63931. int nEntry; /* Number of entries on one ptrmap page */
  63932. Pgno nPtrmap; /* Number of PtrMap pages to be freed */
  63933. Pgno nFin; /* Return value */
  63934. nEntry = pBt->usableSize/5;
  63935. nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
  63936. nFin = nOrig - nFree - nPtrmap;
  63937. if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
  63938. nFin--;
  63939. }
  63940. while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
  63941. nFin--;
  63942. }
  63943. return nFin;
  63944. }
  63945. /*
  63946. ** A write-transaction must be opened before calling this function.
  63947. ** It performs a single unit of work towards an incremental vacuum.
  63948. **
  63949. ** If the incremental vacuum is finished after this function has run,
  63950. ** SQLITE_DONE is returned. If it is not finished, but no error occurred,
  63951. ** SQLITE_OK is returned. Otherwise an SQLite error code.
  63952. */
  63953. SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){
  63954. int rc;
  63955. BtShared *pBt = p->pBt;
  63956. sqlite3BtreeEnter(p);
  63957. assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
  63958. if( !pBt->autoVacuum ){
  63959. rc = SQLITE_DONE;
  63960. }else{
  63961. Pgno nOrig = btreePagecount(pBt);
  63962. Pgno nFree = get4byte(&pBt->pPage1->aData[36]);
  63963. Pgno nFin = finalDbSize(pBt, nOrig, nFree);
  63964. if( nOrig<nFin ){
  63965. rc = SQLITE_CORRUPT_BKPT;
  63966. }else if( nFree>0 ){
  63967. rc = saveAllCursors(pBt, 0, 0);
  63968. if( rc==SQLITE_OK ){
  63969. invalidateAllOverflowCache(pBt);
  63970. rc = incrVacuumStep(pBt, nFin, nOrig, 0);
  63971. }
  63972. if( rc==SQLITE_OK ){
  63973. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  63974. put4byte(&pBt->pPage1->aData[28], pBt->nPage);
  63975. }
  63976. }else{
  63977. rc = SQLITE_DONE;
  63978. }
  63979. }
  63980. sqlite3BtreeLeave(p);
  63981. return rc;
  63982. }
  63983. /*
  63984. ** This routine is called prior to sqlite3PagerCommit when a transaction
  63985. ** is committed for an auto-vacuum database.
  63986. **
  63987. ** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
  63988. ** the database file should be truncated to during the commit process.
  63989. ** i.e. the database has been reorganized so that only the first *pnTrunc
  63990. ** pages are in use.
  63991. */
  63992. static int autoVacuumCommit(BtShared *pBt){
  63993. int rc = SQLITE_OK;
  63994. Pager *pPager = pBt->pPager;
  63995. VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager); )
  63996. assert( sqlite3_mutex_held(pBt->mutex) );
  63997. invalidateAllOverflowCache(pBt);
  63998. assert(pBt->autoVacuum);
  63999. if( !pBt->incrVacuum ){
  64000. Pgno nFin; /* Number of pages in database after autovacuuming */
  64001. Pgno nFree; /* Number of pages on the freelist initially */
  64002. Pgno iFree; /* The next page to be freed */
  64003. Pgno nOrig; /* Database size before freeing */
  64004. nOrig = btreePagecount(pBt);
  64005. if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
  64006. /* It is not possible to create a database for which the final page
  64007. ** is either a pointer-map page or the pending-byte page. If one
  64008. ** is encountered, this indicates corruption.
  64009. */
  64010. return SQLITE_CORRUPT_BKPT;
  64011. }
  64012. nFree = get4byte(&pBt->pPage1->aData[36]);
  64013. nFin = finalDbSize(pBt, nOrig, nFree);
  64014. if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
  64015. if( nFin<nOrig ){
  64016. rc = saveAllCursors(pBt, 0, 0);
  64017. }
  64018. for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
  64019. rc = incrVacuumStep(pBt, nFin, iFree, 1);
  64020. }
  64021. if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
  64022. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  64023. put4byte(&pBt->pPage1->aData[32], 0);
  64024. put4byte(&pBt->pPage1->aData[36], 0);
  64025. put4byte(&pBt->pPage1->aData[28], nFin);
  64026. pBt->bDoTruncate = 1;
  64027. pBt->nPage = nFin;
  64028. }
  64029. if( rc!=SQLITE_OK ){
  64030. sqlite3PagerRollback(pPager);
  64031. }
  64032. }
  64033. assert( nRef>=sqlite3PagerRefcount(pPager) );
  64034. return rc;
  64035. }
  64036. #else /* ifndef SQLITE_OMIT_AUTOVACUUM */
  64037. # define setChildPtrmaps(x) SQLITE_OK
  64038. #endif
  64039. /*
  64040. ** This routine does the first phase of a two-phase commit. This routine
  64041. ** causes a rollback journal to be created (if it does not already exist)
  64042. ** and populated with enough information so that if a power loss occurs
  64043. ** the database can be restored to its original state by playing back
  64044. ** the journal. Then the contents of the journal are flushed out to
  64045. ** the disk. After the journal is safely on oxide, the changes to the
  64046. ** database are written into the database file and flushed to oxide.
  64047. ** At the end of this call, the rollback journal still exists on the
  64048. ** disk and we are still holding all locks, so the transaction has not
  64049. ** committed. See sqlite3BtreeCommitPhaseTwo() for the second phase of the
  64050. ** commit process.
  64051. **
  64052. ** This call is a no-op if no write-transaction is currently active on pBt.
  64053. **
  64054. ** Otherwise, sync the database file for the btree pBt. zMaster points to
  64055. ** the name of a master journal file that should be written into the
  64056. ** individual journal file, or is NULL, indicating no master journal file
  64057. ** (single database transaction).
  64058. **
  64059. ** When this is called, the master journal should already have been
  64060. ** created, populated with this journal pointer and synced to disk.
  64061. **
  64062. ** Once this is routine has returned, the only thing required to commit
  64063. ** the write-transaction for this database file is to delete the journal.
  64064. */
  64065. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
  64066. int rc = SQLITE_OK;
  64067. if( p->inTrans==TRANS_WRITE ){
  64068. BtShared *pBt = p->pBt;
  64069. sqlite3BtreeEnter(p);
  64070. #ifndef SQLITE_OMIT_AUTOVACUUM
  64071. if( pBt->autoVacuum ){
  64072. rc = autoVacuumCommit(pBt);
  64073. if( rc!=SQLITE_OK ){
  64074. sqlite3BtreeLeave(p);
  64075. return rc;
  64076. }
  64077. }
  64078. if( pBt->bDoTruncate ){
  64079. sqlite3PagerTruncateImage(pBt->pPager, pBt->nPage);
  64080. }
  64081. #endif
  64082. rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
  64083. sqlite3BtreeLeave(p);
  64084. }
  64085. return rc;
  64086. }
  64087. /*
  64088. ** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
  64089. ** at the conclusion of a transaction.
  64090. */
  64091. static void btreeEndTransaction(Btree *p){
  64092. BtShared *pBt = p->pBt;
  64093. sqlite3 *db = p->db;
  64094. assert( sqlite3BtreeHoldsMutex(p) );
  64095. #ifndef SQLITE_OMIT_AUTOVACUUM
  64096. pBt->bDoTruncate = 0;
  64097. #endif
  64098. if( p->inTrans>TRANS_NONE && db->nVdbeRead>1 ){
  64099. /* If there are other active statements that belong to this database
  64100. ** handle, downgrade to a read-only transaction. The other statements
  64101. ** may still be reading from the database. */
  64102. downgradeAllSharedCacheTableLocks(p);
  64103. p->inTrans = TRANS_READ;
  64104. }else{
  64105. /* If the handle had any kind of transaction open, decrement the
  64106. ** transaction count of the shared btree. If the transaction count
  64107. ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
  64108. ** call below will unlock the pager. */
  64109. if( p->inTrans!=TRANS_NONE ){
  64110. clearAllSharedCacheTableLocks(p);
  64111. pBt->nTransaction--;
  64112. if( 0==pBt->nTransaction ){
  64113. pBt->inTransaction = TRANS_NONE;
  64114. }
  64115. }
  64116. /* Set the current transaction state to TRANS_NONE and unlock the
  64117. ** pager if this call closed the only read or write transaction. */
  64118. p->inTrans = TRANS_NONE;
  64119. unlockBtreeIfUnused(pBt);
  64120. }
  64121. btreeIntegrity(p);
  64122. }
  64123. /*
  64124. ** Commit the transaction currently in progress.
  64125. **
  64126. ** This routine implements the second phase of a 2-phase commit. The
  64127. ** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
  64128. ** be invoked prior to calling this routine. The sqlite3BtreeCommitPhaseOne()
  64129. ** routine did all the work of writing information out to disk and flushing the
  64130. ** contents so that they are written onto the disk platter. All this
  64131. ** routine has to do is delete or truncate or zero the header in the
  64132. ** the rollback journal (which causes the transaction to commit) and
  64133. ** drop locks.
  64134. **
  64135. ** Normally, if an error occurs while the pager layer is attempting to
  64136. ** finalize the underlying journal file, this function returns an error and
  64137. ** the upper layer will attempt a rollback. However, if the second argument
  64138. ** is non-zero then this b-tree transaction is part of a multi-file
  64139. ** transaction. In this case, the transaction has already been committed
  64140. ** (by deleting a master journal file) and the caller will ignore this
  64141. ** functions return code. So, even if an error occurs in the pager layer,
  64142. ** reset the b-tree objects internal state to indicate that the write
  64143. ** transaction has been closed. This is quite safe, as the pager will have
  64144. ** transitioned to the error state.
  64145. **
  64146. ** This will release the write lock on the database file. If there
  64147. ** are no active cursors, it also releases the read lock.
  64148. */
  64149. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){
  64150. if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
  64151. sqlite3BtreeEnter(p);
  64152. btreeIntegrity(p);
  64153. /* If the handle has a write-transaction open, commit the shared-btrees
  64154. ** transaction and set the shared state to TRANS_READ.
  64155. */
  64156. if( p->inTrans==TRANS_WRITE ){
  64157. int rc;
  64158. BtShared *pBt = p->pBt;
  64159. assert( pBt->inTransaction==TRANS_WRITE );
  64160. assert( pBt->nTransaction>0 );
  64161. rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
  64162. if( rc!=SQLITE_OK && bCleanup==0 ){
  64163. sqlite3BtreeLeave(p);
  64164. return rc;
  64165. }
  64166. p->iDataVersion--; /* Compensate for pPager->iDataVersion++; */
  64167. pBt->inTransaction = TRANS_READ;
  64168. btreeClearHasContent(pBt);
  64169. }
  64170. btreeEndTransaction(p);
  64171. sqlite3BtreeLeave(p);
  64172. return SQLITE_OK;
  64173. }
  64174. /*
  64175. ** Do both phases of a commit.
  64176. */
  64177. SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){
  64178. int rc;
  64179. sqlite3BtreeEnter(p);
  64180. rc = sqlite3BtreeCommitPhaseOne(p, 0);
  64181. if( rc==SQLITE_OK ){
  64182. rc = sqlite3BtreeCommitPhaseTwo(p, 0);
  64183. }
  64184. sqlite3BtreeLeave(p);
  64185. return rc;
  64186. }
  64187. /*
  64188. ** This routine sets the state to CURSOR_FAULT and the error
  64189. ** code to errCode for every cursor on any BtShared that pBtree
  64190. ** references. Or if the writeOnly flag is set to 1, then only
  64191. ** trip write cursors and leave read cursors unchanged.
  64192. **
  64193. ** Every cursor is a candidate to be tripped, including cursors
  64194. ** that belong to other database connections that happen to be
  64195. ** sharing the cache with pBtree.
  64196. **
  64197. ** This routine gets called when a rollback occurs. If the writeOnly
  64198. ** flag is true, then only write-cursors need be tripped - read-only
  64199. ** cursors save their current positions so that they may continue
  64200. ** following the rollback. Or, if writeOnly is false, all cursors are
  64201. ** tripped. In general, writeOnly is false if the transaction being
  64202. ** rolled back modified the database schema. In this case b-tree root
  64203. ** pages may be moved or deleted from the database altogether, making
  64204. ** it unsafe for read cursors to continue.
  64205. **
  64206. ** If the writeOnly flag is true and an error is encountered while
  64207. ** saving the current position of a read-only cursor, all cursors,
  64208. ** including all read-cursors are tripped.
  64209. **
  64210. ** SQLITE_OK is returned if successful, or if an error occurs while
  64211. ** saving a cursor position, an SQLite error code.
  64212. */
  64213. SQLITE_PRIVATE int sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode, int writeOnly){
  64214. BtCursor *p;
  64215. int rc = SQLITE_OK;
  64216. assert( (writeOnly==0 || writeOnly==1) && BTCF_WriteFlag==1 );
  64217. if( pBtree ){
  64218. sqlite3BtreeEnter(pBtree);
  64219. for(p=pBtree->pBt->pCursor; p; p=p->pNext){
  64220. if( writeOnly && (p->curFlags & BTCF_WriteFlag)==0 ){
  64221. if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
  64222. rc = saveCursorPosition(p);
  64223. if( rc!=SQLITE_OK ){
  64224. (void)sqlite3BtreeTripAllCursors(pBtree, rc, 0);
  64225. break;
  64226. }
  64227. }
  64228. }else{
  64229. sqlite3BtreeClearCursor(p);
  64230. p->eState = CURSOR_FAULT;
  64231. p->skipNext = errCode;
  64232. }
  64233. btreeReleaseAllCursorPages(p);
  64234. }
  64235. sqlite3BtreeLeave(pBtree);
  64236. }
  64237. return rc;
  64238. }
  64239. /*
  64240. ** Set the pBt->nPage field correctly, according to the current
  64241. ** state of the database. Assume pBt->pPage1 is valid.
  64242. */
  64243. static void btreeSetNPage(BtShared *pBt, MemPage *pPage1){
  64244. int nPage = get4byte(&pPage1->aData[28]);
  64245. testcase( nPage==0 );
  64246. if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
  64247. testcase( pBt->nPage!=nPage );
  64248. pBt->nPage = nPage;
  64249. }
  64250. /*
  64251. ** Rollback the transaction in progress.
  64252. **
  64253. ** If tripCode is not SQLITE_OK then cursors will be invalidated (tripped).
  64254. ** Only write cursors are tripped if writeOnly is true but all cursors are
  64255. ** tripped if writeOnly is false. Any attempt to use
  64256. ** a tripped cursor will result in an error.
  64257. **
  64258. ** This will release the write lock on the database file. If there
  64259. ** are no active cursors, it also releases the read lock.
  64260. */
  64261. SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p, int tripCode, int writeOnly){
  64262. int rc;
  64263. BtShared *pBt = p->pBt;
  64264. MemPage *pPage1;
  64265. assert( writeOnly==1 || writeOnly==0 );
  64266. assert( tripCode==SQLITE_ABORT_ROLLBACK || tripCode==SQLITE_OK );
  64267. sqlite3BtreeEnter(p);
  64268. if( tripCode==SQLITE_OK ){
  64269. rc = tripCode = saveAllCursors(pBt, 0, 0);
  64270. if( rc ) writeOnly = 0;
  64271. }else{
  64272. rc = SQLITE_OK;
  64273. }
  64274. if( tripCode ){
  64275. int rc2 = sqlite3BtreeTripAllCursors(p, tripCode, writeOnly);
  64276. assert( rc==SQLITE_OK || (writeOnly==0 && rc2==SQLITE_OK) );
  64277. if( rc2!=SQLITE_OK ) rc = rc2;
  64278. }
  64279. btreeIntegrity(p);
  64280. if( p->inTrans==TRANS_WRITE ){
  64281. int rc2;
  64282. assert( TRANS_WRITE==pBt->inTransaction );
  64283. rc2 = sqlite3PagerRollback(pBt->pPager);
  64284. if( rc2!=SQLITE_OK ){
  64285. rc = rc2;
  64286. }
  64287. /* The rollback may have destroyed the pPage1->aData value. So
  64288. ** call btreeGetPage() on page 1 again to make
  64289. ** sure pPage1->aData is set correctly. */
  64290. if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
  64291. btreeSetNPage(pBt, pPage1);
  64292. releasePageOne(pPage1);
  64293. }
  64294. assert( countValidCursors(pBt, 1)==0 );
  64295. pBt->inTransaction = TRANS_READ;
  64296. btreeClearHasContent(pBt);
  64297. }
  64298. btreeEndTransaction(p);
  64299. sqlite3BtreeLeave(p);
  64300. return rc;
  64301. }
  64302. /*
  64303. ** Start a statement subtransaction. The subtransaction can be rolled
  64304. ** back independently of the main transaction. You must start a transaction
  64305. ** before starting a subtransaction. The subtransaction is ended automatically
  64306. ** if the main transaction commits or rolls back.
  64307. **
  64308. ** Statement subtransactions are used around individual SQL statements
  64309. ** that are contained within a BEGIN...COMMIT block. If a constraint
  64310. ** error occurs within the statement, the effect of that one statement
  64311. ** can be rolled back without having to rollback the entire transaction.
  64312. **
  64313. ** A statement sub-transaction is implemented as an anonymous savepoint. The
  64314. ** value passed as the second parameter is the total number of savepoints,
  64315. ** including the new anonymous savepoint, open on the B-Tree. i.e. if there
  64316. ** are no active savepoints and no other statement-transactions open,
  64317. ** iStatement is 1. This anonymous savepoint can be released or rolled back
  64318. ** using the sqlite3BtreeSavepoint() function.
  64319. */
  64320. SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
  64321. int rc;
  64322. BtShared *pBt = p->pBt;
  64323. sqlite3BtreeEnter(p);
  64324. assert( p->inTrans==TRANS_WRITE );
  64325. assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
  64326. assert( iStatement>0 );
  64327. assert( iStatement>p->db->nSavepoint );
  64328. assert( pBt->inTransaction==TRANS_WRITE );
  64329. /* At the pager level, a statement transaction is a savepoint with
  64330. ** an index greater than all savepoints created explicitly using
  64331. ** SQL statements. It is illegal to open, release or rollback any
  64332. ** such savepoints while the statement transaction savepoint is active.
  64333. */
  64334. rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
  64335. sqlite3BtreeLeave(p);
  64336. return rc;
  64337. }
  64338. /*
  64339. ** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
  64340. ** or SAVEPOINT_RELEASE. This function either releases or rolls back the
  64341. ** savepoint identified by parameter iSavepoint, depending on the value
  64342. ** of op.
  64343. **
  64344. ** Normally, iSavepoint is greater than or equal to zero. However, if op is
  64345. ** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
  64346. ** contents of the entire transaction are rolled back. This is different
  64347. ** from a normal transaction rollback, as no locks are released and the
  64348. ** transaction remains open.
  64349. */
  64350. SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
  64351. int rc = SQLITE_OK;
  64352. if( p && p->inTrans==TRANS_WRITE ){
  64353. BtShared *pBt = p->pBt;
  64354. assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
  64355. assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
  64356. sqlite3BtreeEnter(p);
  64357. if( op==SAVEPOINT_ROLLBACK ){
  64358. rc = saveAllCursors(pBt, 0, 0);
  64359. }
  64360. if( rc==SQLITE_OK ){
  64361. rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
  64362. }
  64363. if( rc==SQLITE_OK ){
  64364. if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){
  64365. pBt->nPage = 0;
  64366. }
  64367. rc = newDatabase(pBt);
  64368. btreeSetNPage(pBt, pBt->pPage1);
  64369. /* pBt->nPage might be zero if the database was corrupt when
  64370. ** the transaction was started. Otherwise, it must be at least 1. */
  64371. assert( CORRUPT_DB || pBt->nPage>0 );
  64372. }
  64373. sqlite3BtreeLeave(p);
  64374. }
  64375. return rc;
  64376. }
  64377. /*
  64378. ** Create a new cursor for the BTree whose root is on the page
  64379. ** iTable. If a read-only cursor is requested, it is assumed that
  64380. ** the caller already has at least a read-only transaction open
  64381. ** on the database already. If a write-cursor is requested, then
  64382. ** the caller is assumed to have an open write transaction.
  64383. **
  64384. ** If the BTREE_WRCSR bit of wrFlag is clear, then the cursor can only
  64385. ** be used for reading. If the BTREE_WRCSR bit is set, then the cursor
  64386. ** can be used for reading or for writing if other conditions for writing
  64387. ** are also met. These are the conditions that must be met in order
  64388. ** for writing to be allowed:
  64389. **
  64390. ** 1: The cursor must have been opened with wrFlag containing BTREE_WRCSR
  64391. **
  64392. ** 2: Other database connections that share the same pager cache
  64393. ** but which are not in the READ_UNCOMMITTED state may not have
  64394. ** cursors open with wrFlag==0 on the same table. Otherwise
  64395. ** the changes made by this write cursor would be visible to
  64396. ** the read cursors in the other database connection.
  64397. **
  64398. ** 3: The database must be writable (not on read-only media)
  64399. **
  64400. ** 4: There must be an active transaction.
  64401. **
  64402. ** The BTREE_FORDELETE bit of wrFlag may optionally be set if BTREE_WRCSR
  64403. ** is set. If FORDELETE is set, that is a hint to the implementation that
  64404. ** this cursor will only be used to seek to and delete entries of an index
  64405. ** as part of a larger DELETE statement. The FORDELETE hint is not used by
  64406. ** this implementation. But in a hypothetical alternative storage engine
  64407. ** in which index entries are automatically deleted when corresponding table
  64408. ** rows are deleted, the FORDELETE flag is a hint that all SEEK and DELETE
  64409. ** operations on this cursor can be no-ops and all READ operations can
  64410. ** return a null row (2-bytes: 0x01 0x00).
  64411. **
  64412. ** No checking is done to make sure that page iTable really is the
  64413. ** root page of a b-tree. If it is not, then the cursor acquired
  64414. ** will not work correctly.
  64415. **
  64416. ** It is assumed that the sqlite3BtreeCursorZero() has been called
  64417. ** on pCur to initialize the memory space prior to invoking this routine.
  64418. */
  64419. static int btreeCursor(
  64420. Btree *p, /* The btree */
  64421. int iTable, /* Root page of table to open */
  64422. int wrFlag, /* 1 to write. 0 read-only */
  64423. struct KeyInfo *pKeyInfo, /* First arg to comparison function */
  64424. BtCursor *pCur /* Space for new cursor */
  64425. ){
  64426. BtShared *pBt = p->pBt; /* Shared b-tree handle */
  64427. BtCursor *pX; /* Looping over other all cursors */
  64428. assert( sqlite3BtreeHoldsMutex(p) );
  64429. assert( wrFlag==0
  64430. || wrFlag==BTREE_WRCSR
  64431. || wrFlag==(BTREE_WRCSR|BTREE_FORDELETE)
  64432. );
  64433. /* The following assert statements verify that if this is a sharable
  64434. ** b-tree database, the connection is holding the required table locks,
  64435. ** and that no other connection has any open cursor that conflicts with
  64436. ** this lock. The iTable<1 term disables the check for corrupt schemas. */
  64437. assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, (wrFlag?2:1))
  64438. || iTable<1 );
  64439. assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
  64440. /* Assert that the caller has opened the required transaction. */
  64441. assert( p->inTrans>TRANS_NONE );
  64442. assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
  64443. assert( pBt->pPage1 && pBt->pPage1->aData );
  64444. assert( wrFlag==0 || (pBt->btsFlags & BTS_READ_ONLY)==0 );
  64445. if( wrFlag ){
  64446. allocateTempSpace(pBt);
  64447. if( pBt->pTmpSpace==0 ) return SQLITE_NOMEM_BKPT;
  64448. }
  64449. if( iTable<=1 ){
  64450. if( iTable<1 ){
  64451. return SQLITE_CORRUPT_BKPT;
  64452. }else if( btreePagecount(pBt)==0 ){
  64453. assert( wrFlag==0 );
  64454. iTable = 0;
  64455. }
  64456. }
  64457. /* Now that no other errors can occur, finish filling in the BtCursor
  64458. ** variables and link the cursor into the BtShared list. */
  64459. pCur->pgnoRoot = (Pgno)iTable;
  64460. pCur->iPage = -1;
  64461. pCur->pKeyInfo = pKeyInfo;
  64462. pCur->pBtree = p;
  64463. pCur->pBt = pBt;
  64464. pCur->curFlags = wrFlag ? BTCF_WriteFlag : 0;
  64465. pCur->curPagerFlags = wrFlag ? 0 : PAGER_GET_READONLY;
  64466. /* If there are two or more cursors on the same btree, then all such
  64467. ** cursors *must* have the BTCF_Multiple flag set. */
  64468. for(pX=pBt->pCursor; pX; pX=pX->pNext){
  64469. if( pX->pgnoRoot==(Pgno)iTable ){
  64470. pX->curFlags |= BTCF_Multiple;
  64471. pCur->curFlags |= BTCF_Multiple;
  64472. }
  64473. }
  64474. pCur->pNext = pBt->pCursor;
  64475. pBt->pCursor = pCur;
  64476. pCur->eState = CURSOR_INVALID;
  64477. return SQLITE_OK;
  64478. }
  64479. static int btreeCursorWithLock(
  64480. Btree *p, /* The btree */
  64481. int iTable, /* Root page of table to open */
  64482. int wrFlag, /* 1 to write. 0 read-only */
  64483. struct KeyInfo *pKeyInfo, /* First arg to comparison function */
  64484. BtCursor *pCur /* Space for new cursor */
  64485. ){
  64486. int rc;
  64487. sqlite3BtreeEnter(p);
  64488. rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
  64489. sqlite3BtreeLeave(p);
  64490. return rc;
  64491. }
  64492. SQLITE_PRIVATE int sqlite3BtreeCursor(
  64493. Btree *p, /* The btree */
  64494. int iTable, /* Root page of table to open */
  64495. int wrFlag, /* 1 to write. 0 read-only */
  64496. struct KeyInfo *pKeyInfo, /* First arg to xCompare() */
  64497. BtCursor *pCur /* Write new cursor here */
  64498. ){
  64499. if( p->sharable ){
  64500. return btreeCursorWithLock(p, iTable, wrFlag, pKeyInfo, pCur);
  64501. }else{
  64502. return btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
  64503. }
  64504. }
  64505. /*
  64506. ** Return the size of a BtCursor object in bytes.
  64507. **
  64508. ** This interfaces is needed so that users of cursors can preallocate
  64509. ** sufficient storage to hold a cursor. The BtCursor object is opaque
  64510. ** to users so they cannot do the sizeof() themselves - they must call
  64511. ** this routine.
  64512. */
  64513. SQLITE_PRIVATE int sqlite3BtreeCursorSize(void){
  64514. return ROUND8(sizeof(BtCursor));
  64515. }
  64516. /*
  64517. ** Initialize memory that will be converted into a BtCursor object.
  64518. **
  64519. ** The simple approach here would be to memset() the entire object
  64520. ** to zero. But it turns out that the apPage[] and aiIdx[] arrays
  64521. ** do not need to be zeroed and they are large, so we can save a lot
  64522. ** of run-time by skipping the initialization of those elements.
  64523. */
  64524. SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor *p){
  64525. memset(p, 0, offsetof(BtCursor, BTCURSOR_FIRST_UNINIT));
  64526. }
  64527. /*
  64528. ** Close a cursor. The read lock on the database file is released
  64529. ** when the last cursor is closed.
  64530. */
  64531. SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){
  64532. Btree *pBtree = pCur->pBtree;
  64533. if( pBtree ){
  64534. BtShared *pBt = pCur->pBt;
  64535. sqlite3BtreeEnter(pBtree);
  64536. assert( pBt->pCursor!=0 );
  64537. if( pBt->pCursor==pCur ){
  64538. pBt->pCursor = pCur->pNext;
  64539. }else{
  64540. BtCursor *pPrev = pBt->pCursor;
  64541. do{
  64542. if( pPrev->pNext==pCur ){
  64543. pPrev->pNext = pCur->pNext;
  64544. break;
  64545. }
  64546. pPrev = pPrev->pNext;
  64547. }while( ALWAYS(pPrev) );
  64548. }
  64549. btreeReleaseAllCursorPages(pCur);
  64550. unlockBtreeIfUnused(pBt);
  64551. sqlite3_free(pCur->aOverflow);
  64552. sqlite3_free(pCur->pKey);
  64553. sqlite3BtreeLeave(pBtree);
  64554. pCur->pBtree = 0;
  64555. }
  64556. return SQLITE_OK;
  64557. }
  64558. /*
  64559. ** Make sure the BtCursor* given in the argument has a valid
  64560. ** BtCursor.info structure. If it is not already valid, call
  64561. ** btreeParseCell() to fill it in.
  64562. **
  64563. ** BtCursor.info is a cache of the information in the current cell.
  64564. ** Using this cache reduces the number of calls to btreeParseCell().
  64565. */
  64566. #ifndef NDEBUG
  64567. static int cellInfoEqual(CellInfo *a, CellInfo *b){
  64568. if( a->nKey!=b->nKey ) return 0;
  64569. if( a->pPayload!=b->pPayload ) return 0;
  64570. if( a->nPayload!=b->nPayload ) return 0;
  64571. if( a->nLocal!=b->nLocal ) return 0;
  64572. if( a->nSize!=b->nSize ) return 0;
  64573. return 1;
  64574. }
  64575. static void assertCellInfo(BtCursor *pCur){
  64576. CellInfo info;
  64577. memset(&info, 0, sizeof(info));
  64578. btreeParseCell(pCur->pPage, pCur->ix, &info);
  64579. assert( CORRUPT_DB || cellInfoEqual(&info, &pCur->info) );
  64580. }
  64581. #else
  64582. #define assertCellInfo(x)
  64583. #endif
  64584. static SQLITE_NOINLINE void getCellInfo(BtCursor *pCur){
  64585. if( pCur->info.nSize==0 ){
  64586. pCur->curFlags |= BTCF_ValidNKey;
  64587. btreeParseCell(pCur->pPage,pCur->ix,&pCur->info);
  64588. }else{
  64589. assertCellInfo(pCur);
  64590. }
  64591. }
  64592. #ifndef NDEBUG /* The next routine used only within assert() statements */
  64593. /*
  64594. ** Return true if the given BtCursor is valid. A valid cursor is one
  64595. ** that is currently pointing to a row in a (non-empty) table.
  64596. ** This is a verification routine is used only within assert() statements.
  64597. */
  64598. SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor *pCur){
  64599. return pCur && pCur->eState==CURSOR_VALID;
  64600. }
  64601. #endif /* NDEBUG */
  64602. SQLITE_PRIVATE int sqlite3BtreeCursorIsValidNN(BtCursor *pCur){
  64603. assert( pCur!=0 );
  64604. return pCur->eState==CURSOR_VALID;
  64605. }
  64606. /*
  64607. ** Return the value of the integer key or "rowid" for a table btree.
  64608. ** This routine is only valid for a cursor that is pointing into a
  64609. ** ordinary table btree. If the cursor points to an index btree or
  64610. ** is invalid, the result of this routine is undefined.
  64611. */
  64612. SQLITE_PRIVATE i64 sqlite3BtreeIntegerKey(BtCursor *pCur){
  64613. assert( cursorHoldsMutex(pCur) );
  64614. assert( pCur->eState==CURSOR_VALID );
  64615. assert( pCur->curIntKey );
  64616. getCellInfo(pCur);
  64617. return pCur->info.nKey;
  64618. }
  64619. /*
  64620. ** Pin or unpin a cursor.
  64621. */
  64622. SQLITE_PRIVATE void sqlite3BtreeCursorPin(BtCursor *pCur){
  64623. assert( (pCur->curFlags & BTCF_Pinned)==0 );
  64624. pCur->curFlags |= BTCF_Pinned;
  64625. }
  64626. SQLITE_PRIVATE void sqlite3BtreeCursorUnpin(BtCursor *pCur){
  64627. assert( (pCur->curFlags & BTCF_Pinned)!=0 );
  64628. pCur->curFlags &= ~BTCF_Pinned;
  64629. }
  64630. #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
  64631. /*
  64632. ** Return the offset into the database file for the start of the
  64633. ** payload to which the cursor is pointing.
  64634. */
  64635. SQLITE_PRIVATE i64 sqlite3BtreeOffset(BtCursor *pCur){
  64636. assert( cursorHoldsMutex(pCur) );
  64637. assert( pCur->eState==CURSOR_VALID );
  64638. getCellInfo(pCur);
  64639. return (i64)pCur->pBt->pageSize*((i64)pCur->pPage->pgno - 1) +
  64640. (i64)(pCur->info.pPayload - pCur->pPage->aData);
  64641. }
  64642. #endif /* SQLITE_ENABLE_OFFSET_SQL_FUNC */
  64643. /*
  64644. ** Return the number of bytes of payload for the entry that pCur is
  64645. ** currently pointing to. For table btrees, this will be the amount
  64646. ** of data. For index btrees, this will be the size of the key.
  64647. **
  64648. ** The caller must guarantee that the cursor is pointing to a non-NULL
  64649. ** valid entry. In other words, the calling procedure must guarantee
  64650. ** that the cursor has Cursor.eState==CURSOR_VALID.
  64651. */
  64652. SQLITE_PRIVATE u32 sqlite3BtreePayloadSize(BtCursor *pCur){
  64653. assert( cursorHoldsMutex(pCur) );
  64654. assert( pCur->eState==CURSOR_VALID );
  64655. getCellInfo(pCur);
  64656. return pCur->info.nPayload;
  64657. }
  64658. /*
  64659. ** Return an upper bound on the size of any record for the table
  64660. ** that the cursor is pointing into.
  64661. **
  64662. ** This is an optimization. Everything will still work if this
  64663. ** routine always returns 2147483647 (which is the largest record
  64664. ** that SQLite can handle) or more. But returning a smaller value might
  64665. ** prevent large memory allocations when trying to interpret a
  64666. ** corrupt datrabase.
  64667. **
  64668. ** The current implementation merely returns the size of the underlying
  64669. ** database file.
  64670. */
  64671. SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeMaxRecordSize(BtCursor *pCur){
  64672. assert( cursorHoldsMutex(pCur) );
  64673. assert( pCur->eState==CURSOR_VALID );
  64674. return pCur->pBt->pageSize * (sqlite3_int64)pCur->pBt->nPage;
  64675. }
  64676. /*
  64677. ** Given the page number of an overflow page in the database (parameter
  64678. ** ovfl), this function finds the page number of the next page in the
  64679. ** linked list of overflow pages. If possible, it uses the auto-vacuum
  64680. ** pointer-map data instead of reading the content of page ovfl to do so.
  64681. **
  64682. ** If an error occurs an SQLite error code is returned. Otherwise:
  64683. **
  64684. ** The page number of the next overflow page in the linked list is
  64685. ** written to *pPgnoNext. If page ovfl is the last page in its linked
  64686. ** list, *pPgnoNext is set to zero.
  64687. **
  64688. ** If ppPage is not NULL, and a reference to the MemPage object corresponding
  64689. ** to page number pOvfl was obtained, then *ppPage is set to point to that
  64690. ** reference. It is the responsibility of the caller to call releasePage()
  64691. ** on *ppPage to free the reference. In no reference was obtained (because
  64692. ** the pointer-map was used to obtain the value for *pPgnoNext), then
  64693. ** *ppPage is set to zero.
  64694. */
  64695. static int getOverflowPage(
  64696. BtShared *pBt, /* The database file */
  64697. Pgno ovfl, /* Current overflow page number */
  64698. MemPage **ppPage, /* OUT: MemPage handle (may be NULL) */
  64699. Pgno *pPgnoNext /* OUT: Next overflow page number */
  64700. ){
  64701. Pgno next = 0;
  64702. MemPage *pPage = 0;
  64703. int rc = SQLITE_OK;
  64704. assert( sqlite3_mutex_held(pBt->mutex) );
  64705. assert(pPgnoNext);
  64706. #ifndef SQLITE_OMIT_AUTOVACUUM
  64707. /* Try to find the next page in the overflow list using the
  64708. ** autovacuum pointer-map pages. Guess that the next page in
  64709. ** the overflow list is page number (ovfl+1). If that guess turns
  64710. ** out to be wrong, fall back to loading the data of page
  64711. ** number ovfl to determine the next page number.
  64712. */
  64713. if( pBt->autoVacuum ){
  64714. Pgno pgno;
  64715. Pgno iGuess = ovfl+1;
  64716. u8 eType;
  64717. while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
  64718. iGuess++;
  64719. }
  64720. if( iGuess<=btreePagecount(pBt) ){
  64721. rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
  64722. if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
  64723. next = iGuess;
  64724. rc = SQLITE_DONE;
  64725. }
  64726. }
  64727. }
  64728. #endif
  64729. assert( next==0 || rc==SQLITE_DONE );
  64730. if( rc==SQLITE_OK ){
  64731. rc = btreeGetPage(pBt, ovfl, &pPage, (ppPage==0) ? PAGER_GET_READONLY : 0);
  64732. assert( rc==SQLITE_OK || pPage==0 );
  64733. if( rc==SQLITE_OK ){
  64734. next = get4byte(pPage->aData);
  64735. }
  64736. }
  64737. *pPgnoNext = next;
  64738. if( ppPage ){
  64739. *ppPage = pPage;
  64740. }else{
  64741. releasePage(pPage);
  64742. }
  64743. return (rc==SQLITE_DONE ? SQLITE_OK : rc);
  64744. }
  64745. /*
  64746. ** Copy data from a buffer to a page, or from a page to a buffer.
  64747. **
  64748. ** pPayload is a pointer to data stored on database page pDbPage.
  64749. ** If argument eOp is false, then nByte bytes of data are copied
  64750. ** from pPayload to the buffer pointed at by pBuf. If eOp is true,
  64751. ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
  64752. ** of data are copied from the buffer pBuf to pPayload.
  64753. **
  64754. ** SQLITE_OK is returned on success, otherwise an error code.
  64755. */
  64756. static int copyPayload(
  64757. void *pPayload, /* Pointer to page data */
  64758. void *pBuf, /* Pointer to buffer */
  64759. int nByte, /* Number of bytes to copy */
  64760. int eOp, /* 0 -> copy from page, 1 -> copy to page */
  64761. DbPage *pDbPage /* Page containing pPayload */
  64762. ){
  64763. if( eOp ){
  64764. /* Copy data from buffer to page (a write operation) */
  64765. int rc = sqlite3PagerWrite(pDbPage);
  64766. if( rc!=SQLITE_OK ){
  64767. return rc;
  64768. }
  64769. memcpy(pPayload, pBuf, nByte);
  64770. }else{
  64771. /* Copy data from page to buffer (a read operation) */
  64772. memcpy(pBuf, pPayload, nByte);
  64773. }
  64774. return SQLITE_OK;
  64775. }
  64776. /*
  64777. ** This function is used to read or overwrite payload information
  64778. ** for the entry that the pCur cursor is pointing to. The eOp
  64779. ** argument is interpreted as follows:
  64780. **
  64781. ** 0: The operation is a read. Populate the overflow cache.
  64782. ** 1: The operation is a write. Populate the overflow cache.
  64783. **
  64784. ** A total of "amt" bytes are read or written beginning at "offset".
  64785. ** Data is read to or from the buffer pBuf.
  64786. **
  64787. ** The content being read or written might appear on the main page
  64788. ** or be scattered out on multiple overflow pages.
  64789. **
  64790. ** If the current cursor entry uses one or more overflow pages
  64791. ** this function may allocate space for and lazily populate
  64792. ** the overflow page-list cache array (BtCursor.aOverflow).
  64793. ** Subsequent calls use this cache to make seeking to the supplied offset
  64794. ** more efficient.
  64795. **
  64796. ** Once an overflow page-list cache has been allocated, it must be
  64797. ** invalidated if some other cursor writes to the same table, or if
  64798. ** the cursor is moved to a different row. Additionally, in auto-vacuum
  64799. ** mode, the following events may invalidate an overflow page-list cache.
  64800. **
  64801. ** * An incremental vacuum,
  64802. ** * A commit in auto_vacuum="full" mode,
  64803. ** * Creating a table (may require moving an overflow page).
  64804. */
  64805. static int accessPayload(
  64806. BtCursor *pCur, /* Cursor pointing to entry to read from */
  64807. u32 offset, /* Begin reading this far into payload */
  64808. u32 amt, /* Read this many bytes */
  64809. unsigned char *pBuf, /* Write the bytes into this buffer */
  64810. int eOp /* zero to read. non-zero to write. */
  64811. ){
  64812. unsigned char *aPayload;
  64813. int rc = SQLITE_OK;
  64814. int iIdx = 0;
  64815. MemPage *pPage = pCur->pPage; /* Btree page of current entry */
  64816. BtShared *pBt = pCur->pBt; /* Btree this cursor belongs to */
  64817. #ifdef SQLITE_DIRECT_OVERFLOW_READ
  64818. unsigned char * const pBufStart = pBuf; /* Start of original out buffer */
  64819. #endif
  64820. assert( pPage );
  64821. assert( eOp==0 || eOp==1 );
  64822. assert( pCur->eState==CURSOR_VALID );
  64823. assert( pCur->ix<pPage->nCell );
  64824. assert( cursorHoldsMutex(pCur) );
  64825. getCellInfo(pCur);
  64826. aPayload = pCur->info.pPayload;
  64827. assert( offset+amt <= pCur->info.nPayload );
  64828. assert( aPayload > pPage->aData );
  64829. if( (uptr)(aPayload - pPage->aData) > (pBt->usableSize - pCur->info.nLocal) ){
  64830. /* Trying to read or write past the end of the data is an error. The
  64831. ** conditional above is really:
  64832. ** &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
  64833. ** but is recast into its current form to avoid integer overflow problems
  64834. */
  64835. return SQLITE_CORRUPT_PAGE(pPage);
  64836. }
  64837. /* Check if data must be read/written to/from the btree page itself. */
  64838. if( offset<pCur->info.nLocal ){
  64839. int a = amt;
  64840. if( a+offset>pCur->info.nLocal ){
  64841. a = pCur->info.nLocal - offset;
  64842. }
  64843. rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
  64844. offset = 0;
  64845. pBuf += a;
  64846. amt -= a;
  64847. }else{
  64848. offset -= pCur->info.nLocal;
  64849. }
  64850. if( rc==SQLITE_OK && amt>0 ){
  64851. const u32 ovflSize = pBt->usableSize - 4; /* Bytes content per ovfl page */
  64852. Pgno nextPage;
  64853. nextPage = get4byte(&aPayload[pCur->info.nLocal]);
  64854. /* If the BtCursor.aOverflow[] has not been allocated, allocate it now.
  64855. **
  64856. ** The aOverflow[] array is sized at one entry for each overflow page
  64857. ** in the overflow chain. The page number of the first overflow page is
  64858. ** stored in aOverflow[0], etc. A value of 0 in the aOverflow[] array
  64859. ** means "not yet known" (the cache is lazily populated).
  64860. */
  64861. if( (pCur->curFlags & BTCF_ValidOvfl)==0 ){
  64862. int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
  64863. if( pCur->aOverflow==0
  64864. || nOvfl*(int)sizeof(Pgno) > sqlite3MallocSize(pCur->aOverflow)
  64865. ){
  64866. Pgno *aNew = (Pgno*)sqlite3Realloc(
  64867. pCur->aOverflow, nOvfl*2*sizeof(Pgno)
  64868. );
  64869. if( aNew==0 ){
  64870. return SQLITE_NOMEM_BKPT;
  64871. }else{
  64872. pCur->aOverflow = aNew;
  64873. }
  64874. }
  64875. memset(pCur->aOverflow, 0, nOvfl*sizeof(Pgno));
  64876. pCur->curFlags |= BTCF_ValidOvfl;
  64877. }else{
  64878. /* If the overflow page-list cache has been allocated and the
  64879. ** entry for the first required overflow page is valid, skip
  64880. ** directly to it.
  64881. */
  64882. if( pCur->aOverflow[offset/ovflSize] ){
  64883. iIdx = (offset/ovflSize);
  64884. nextPage = pCur->aOverflow[iIdx];
  64885. offset = (offset%ovflSize);
  64886. }
  64887. }
  64888. assert( rc==SQLITE_OK && amt>0 );
  64889. while( nextPage ){
  64890. /* If required, populate the overflow page-list cache. */
  64891. assert( pCur->aOverflow[iIdx]==0
  64892. || pCur->aOverflow[iIdx]==nextPage
  64893. || CORRUPT_DB );
  64894. pCur->aOverflow[iIdx] = nextPage;
  64895. if( offset>=ovflSize ){
  64896. /* The only reason to read this page is to obtain the page
  64897. ** number for the next page in the overflow chain. The page
  64898. ** data is not required. So first try to lookup the overflow
  64899. ** page-list cache, if any, then fall back to the getOverflowPage()
  64900. ** function.
  64901. */
  64902. assert( pCur->curFlags & BTCF_ValidOvfl );
  64903. assert( pCur->pBtree->db==pBt->db );
  64904. if( pCur->aOverflow[iIdx+1] ){
  64905. nextPage = pCur->aOverflow[iIdx+1];
  64906. }else{
  64907. rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
  64908. }
  64909. offset -= ovflSize;
  64910. }else{
  64911. /* Need to read this page properly. It contains some of the
  64912. ** range of data that is being read (eOp==0) or written (eOp!=0).
  64913. */
  64914. int a = amt;
  64915. if( a + offset > ovflSize ){
  64916. a = ovflSize - offset;
  64917. }
  64918. #ifdef SQLITE_DIRECT_OVERFLOW_READ
  64919. /* If all the following are true:
  64920. **
  64921. ** 1) this is a read operation, and
  64922. ** 2) data is required from the start of this overflow page, and
  64923. ** 3) there are no dirty pages in the page-cache
  64924. ** 4) the database is file-backed, and
  64925. ** 5) the page is not in the WAL file
  64926. ** 6) at least 4 bytes have already been read into the output buffer
  64927. **
  64928. ** then data can be read directly from the database file into the
  64929. ** output buffer, bypassing the page-cache altogether. This speeds
  64930. ** up loading large records that span many overflow pages.
  64931. */
  64932. if( eOp==0 /* (1) */
  64933. && offset==0 /* (2) */
  64934. && sqlite3PagerDirectReadOk(pBt->pPager, nextPage) /* (3,4,5) */
  64935. && &pBuf[-4]>=pBufStart /* (6) */
  64936. ){
  64937. sqlite3_file *fd = sqlite3PagerFile(pBt->pPager);
  64938. u8 aSave[4];
  64939. u8 *aWrite = &pBuf[-4];
  64940. assert( aWrite>=pBufStart ); /* due to (6) */
  64941. memcpy(aSave, aWrite, 4);
  64942. rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1));
  64943. if( rc && nextPage>pBt->nPage ) rc = SQLITE_CORRUPT_BKPT;
  64944. nextPage = get4byte(aWrite);
  64945. memcpy(aWrite, aSave, 4);
  64946. }else
  64947. #endif
  64948. {
  64949. DbPage *pDbPage;
  64950. rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage,
  64951. (eOp==0 ? PAGER_GET_READONLY : 0)
  64952. );
  64953. if( rc==SQLITE_OK ){
  64954. aPayload = sqlite3PagerGetData(pDbPage);
  64955. nextPage = get4byte(aPayload);
  64956. rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
  64957. sqlite3PagerUnref(pDbPage);
  64958. offset = 0;
  64959. }
  64960. }
  64961. amt -= a;
  64962. if( amt==0 ) return rc;
  64963. pBuf += a;
  64964. }
  64965. if( rc ) break;
  64966. iIdx++;
  64967. }
  64968. }
  64969. if( rc==SQLITE_OK && amt>0 ){
  64970. /* Overflow chain ends prematurely */
  64971. return SQLITE_CORRUPT_PAGE(pPage);
  64972. }
  64973. return rc;
  64974. }
  64975. /*
  64976. ** Read part of the payload for the row at which that cursor pCur is currently
  64977. ** pointing. "amt" bytes will be transferred into pBuf[]. The transfer
  64978. ** begins at "offset".
  64979. **
  64980. ** pCur can be pointing to either a table or an index b-tree.
  64981. ** If pointing to a table btree, then the content section is read. If
  64982. ** pCur is pointing to an index b-tree then the key section is read.
  64983. **
  64984. ** For sqlite3BtreePayload(), the caller must ensure that pCur is pointing
  64985. ** to a valid row in the table. For sqlite3BtreePayloadChecked(), the
  64986. ** cursor might be invalid or might need to be restored before being read.
  64987. **
  64988. ** Return SQLITE_OK on success or an error code if anything goes
  64989. ** wrong. An error is returned if "offset+amt" is larger than
  64990. ** the available payload.
  64991. */
  64992. SQLITE_PRIVATE int sqlite3BtreePayload(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
  64993. assert( cursorHoldsMutex(pCur) );
  64994. assert( pCur->eState==CURSOR_VALID );
  64995. assert( pCur->iPage>=0 && pCur->pPage );
  64996. assert( pCur->ix<pCur->pPage->nCell );
  64997. return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
  64998. }
  64999. /*
  65000. ** This variant of sqlite3BtreePayload() works even if the cursor has not
  65001. ** in the CURSOR_VALID state. It is only used by the sqlite3_blob_read()
  65002. ** interface.
  65003. */
  65004. #ifndef SQLITE_OMIT_INCRBLOB
  65005. static SQLITE_NOINLINE int accessPayloadChecked(
  65006. BtCursor *pCur,
  65007. u32 offset,
  65008. u32 amt,
  65009. void *pBuf
  65010. ){
  65011. int rc;
  65012. if ( pCur->eState==CURSOR_INVALID ){
  65013. return SQLITE_ABORT;
  65014. }
  65015. assert( cursorOwnsBtShared(pCur) );
  65016. rc = btreeRestoreCursorPosition(pCur);
  65017. return rc ? rc : accessPayload(pCur, offset, amt, pBuf, 0);
  65018. }
  65019. SQLITE_PRIVATE int sqlite3BtreePayloadChecked(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
  65020. if( pCur->eState==CURSOR_VALID ){
  65021. assert( cursorOwnsBtShared(pCur) );
  65022. return accessPayload(pCur, offset, amt, pBuf, 0);
  65023. }else{
  65024. return accessPayloadChecked(pCur, offset, amt, pBuf);
  65025. }
  65026. }
  65027. #endif /* SQLITE_OMIT_INCRBLOB */
  65028. /*
  65029. ** Return a pointer to payload information from the entry that the
  65030. ** pCur cursor is pointing to. The pointer is to the beginning of
  65031. ** the key if index btrees (pPage->intKey==0) and is the data for
  65032. ** table btrees (pPage->intKey==1). The number of bytes of available
  65033. ** key/data is written into *pAmt. If *pAmt==0, then the value
  65034. ** returned will not be a valid pointer.
  65035. **
  65036. ** This routine is an optimization. It is common for the entire key
  65037. ** and data to fit on the local page and for there to be no overflow
  65038. ** pages. When that is so, this routine can be used to access the
  65039. ** key and data without making a copy. If the key and/or data spills
  65040. ** onto overflow pages, then accessPayload() must be used to reassemble
  65041. ** the key/data and copy it into a preallocated buffer.
  65042. **
  65043. ** The pointer returned by this routine looks directly into the cached
  65044. ** page of the database. The data might change or move the next time
  65045. ** any btree routine is called.
  65046. */
  65047. static const void *fetchPayload(
  65048. BtCursor *pCur, /* Cursor pointing to entry to read from */
  65049. u32 *pAmt /* Write the number of available bytes here */
  65050. ){
  65051. int amt;
  65052. assert( pCur!=0 && pCur->iPage>=0 && pCur->pPage);
  65053. assert( pCur->eState==CURSOR_VALID );
  65054. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  65055. assert( cursorOwnsBtShared(pCur) );
  65056. assert( pCur->ix<pCur->pPage->nCell );
  65057. assert( pCur->info.nSize>0 );
  65058. assert( pCur->info.pPayload>pCur->pPage->aData || CORRUPT_DB );
  65059. assert( pCur->info.pPayload<pCur->pPage->aDataEnd ||CORRUPT_DB);
  65060. amt = pCur->info.nLocal;
  65061. if( amt>(int)(pCur->pPage->aDataEnd - pCur->info.pPayload) ){
  65062. /* There is too little space on the page for the expected amount
  65063. ** of local content. Database must be corrupt. */
  65064. assert( CORRUPT_DB );
  65065. amt = MAX(0, (int)(pCur->pPage->aDataEnd - pCur->info.pPayload));
  65066. }
  65067. *pAmt = (u32)amt;
  65068. return (void*)pCur->info.pPayload;
  65069. }
  65070. /*
  65071. ** For the entry that cursor pCur is point to, return as
  65072. ** many bytes of the key or data as are available on the local
  65073. ** b-tree page. Write the number of available bytes into *pAmt.
  65074. **
  65075. ** The pointer returned is ephemeral. The key/data may move
  65076. ** or be destroyed on the next call to any Btree routine,
  65077. ** including calls from other threads against the same cache.
  65078. ** Hence, a mutex on the BtShared should be held prior to calling
  65079. ** this routine.
  65080. **
  65081. ** These routines is used to get quick access to key and data
  65082. ** in the common case where no overflow pages are used.
  65083. */
  65084. SQLITE_PRIVATE const void *sqlite3BtreePayloadFetch(BtCursor *pCur, u32 *pAmt){
  65085. return fetchPayload(pCur, pAmt);
  65086. }
  65087. /*
  65088. ** Move the cursor down to a new child page. The newPgno argument is the
  65089. ** page number of the child page to move to.
  65090. **
  65091. ** This function returns SQLITE_CORRUPT if the page-header flags field of
  65092. ** the new child page does not match the flags field of the parent (i.e.
  65093. ** if an intkey page appears to be the parent of a non-intkey page, or
  65094. ** vice-versa).
  65095. */
  65096. static int moveToChild(BtCursor *pCur, u32 newPgno){
  65097. BtShared *pBt = pCur->pBt;
  65098. assert( cursorOwnsBtShared(pCur) );
  65099. assert( pCur->eState==CURSOR_VALID );
  65100. assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
  65101. assert( pCur->iPage>=0 );
  65102. if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
  65103. return SQLITE_CORRUPT_BKPT;
  65104. }
  65105. pCur->info.nSize = 0;
  65106. pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
  65107. pCur->aiIdx[pCur->iPage] = pCur->ix;
  65108. pCur->apPage[pCur->iPage] = pCur->pPage;
  65109. pCur->ix = 0;
  65110. pCur->iPage++;
  65111. return getAndInitPage(pBt, newPgno, &pCur->pPage, pCur, pCur->curPagerFlags);
  65112. }
  65113. #ifdef SQLITE_DEBUG
  65114. /*
  65115. ** Page pParent is an internal (non-leaf) tree page. This function
  65116. ** asserts that page number iChild is the left-child if the iIdx'th
  65117. ** cell in page pParent. Or, if iIdx is equal to the total number of
  65118. ** cells in pParent, that page number iChild is the right-child of
  65119. ** the page.
  65120. */
  65121. static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
  65122. if( CORRUPT_DB ) return; /* The conditions tested below might not be true
  65123. ** in a corrupt database */
  65124. assert( iIdx<=pParent->nCell );
  65125. if( iIdx==pParent->nCell ){
  65126. assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
  65127. }else{
  65128. assert( get4byte(findCell(pParent, iIdx))==iChild );
  65129. }
  65130. }
  65131. #else
  65132. # define assertParentIndex(x,y,z)
  65133. #endif
  65134. /*
  65135. ** Move the cursor up to the parent page.
  65136. **
  65137. ** pCur->idx is set to the cell index that contains the pointer
  65138. ** to the page we are coming from. If we are coming from the
  65139. ** right-most child page then pCur->idx is set to one more than
  65140. ** the largest cell index.
  65141. */
  65142. static void moveToParent(BtCursor *pCur){
  65143. MemPage *pLeaf;
  65144. assert( cursorOwnsBtShared(pCur) );
  65145. assert( pCur->eState==CURSOR_VALID );
  65146. assert( pCur->iPage>0 );
  65147. assert( pCur->pPage );
  65148. assertParentIndex(
  65149. pCur->apPage[pCur->iPage-1],
  65150. pCur->aiIdx[pCur->iPage-1],
  65151. pCur->pPage->pgno
  65152. );
  65153. testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell );
  65154. pCur->info.nSize = 0;
  65155. pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
  65156. pCur->ix = pCur->aiIdx[pCur->iPage-1];
  65157. pLeaf = pCur->pPage;
  65158. pCur->pPage = pCur->apPage[--pCur->iPage];
  65159. releasePageNotNull(pLeaf);
  65160. }
  65161. /*
  65162. ** Move the cursor to point to the root page of its b-tree structure.
  65163. **
  65164. ** If the table has a virtual root page, then the cursor is moved to point
  65165. ** to the virtual root page instead of the actual root page. A table has a
  65166. ** virtual root page when the actual root page contains no cells and a
  65167. ** single child page. This can only happen with the table rooted at page 1.
  65168. **
  65169. ** If the b-tree structure is empty, the cursor state is set to
  65170. ** CURSOR_INVALID and this routine returns SQLITE_EMPTY. Otherwise,
  65171. ** the cursor is set to point to the first cell located on the root
  65172. ** (or virtual root) page and the cursor state is set to CURSOR_VALID.
  65173. **
  65174. ** If this function returns successfully, it may be assumed that the
  65175. ** page-header flags indicate that the [virtual] root-page is the expected
  65176. ** kind of b-tree page (i.e. if when opening the cursor the caller did not
  65177. ** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
  65178. ** indicating a table b-tree, or if the caller did specify a KeyInfo
  65179. ** structure the flags byte is set to 0x02 or 0x0A, indicating an index
  65180. ** b-tree).
  65181. */
  65182. static int moveToRoot(BtCursor *pCur){
  65183. MemPage *pRoot;
  65184. int rc = SQLITE_OK;
  65185. assert( cursorOwnsBtShared(pCur) );
  65186. assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
  65187. assert( CURSOR_VALID < CURSOR_REQUIRESEEK );
  65188. assert( CURSOR_FAULT > CURSOR_REQUIRESEEK );
  65189. assert( pCur->eState < CURSOR_REQUIRESEEK || pCur->iPage<0 );
  65190. assert( pCur->pgnoRoot>0 || pCur->iPage<0 );
  65191. if( pCur->iPage>=0 ){
  65192. if( pCur->iPage ){
  65193. releasePageNotNull(pCur->pPage);
  65194. while( --pCur->iPage ){
  65195. releasePageNotNull(pCur->apPage[pCur->iPage]);
  65196. }
  65197. pCur->pPage = pCur->apPage[0];
  65198. goto skip_init;
  65199. }
  65200. }else if( pCur->pgnoRoot==0 ){
  65201. pCur->eState = CURSOR_INVALID;
  65202. return SQLITE_EMPTY;
  65203. }else{
  65204. assert( pCur->iPage==(-1) );
  65205. if( pCur->eState>=CURSOR_REQUIRESEEK ){
  65206. if( pCur->eState==CURSOR_FAULT ){
  65207. assert( pCur->skipNext!=SQLITE_OK );
  65208. return pCur->skipNext;
  65209. }
  65210. sqlite3BtreeClearCursor(pCur);
  65211. }
  65212. rc = getAndInitPage(pCur->pBtree->pBt, pCur->pgnoRoot, &pCur->pPage,
  65213. 0, pCur->curPagerFlags);
  65214. if( rc!=SQLITE_OK ){
  65215. pCur->eState = CURSOR_INVALID;
  65216. return rc;
  65217. }
  65218. pCur->iPage = 0;
  65219. pCur->curIntKey = pCur->pPage->intKey;
  65220. }
  65221. pRoot = pCur->pPage;
  65222. assert( pRoot->pgno==pCur->pgnoRoot );
  65223. /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
  65224. ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
  65225. ** NULL, the caller expects a table b-tree. If this is not the case,
  65226. ** return an SQLITE_CORRUPT error.
  65227. **
  65228. ** Earlier versions of SQLite assumed that this test could not fail
  65229. ** if the root page was already loaded when this function was called (i.e.
  65230. ** if pCur->iPage>=0). But this is not so if the database is corrupted
  65231. ** in such a way that page pRoot is linked into a second b-tree table
  65232. ** (or the freelist). */
  65233. assert( pRoot->intKey==1 || pRoot->intKey==0 );
  65234. if( pRoot->isInit==0 || (pCur->pKeyInfo==0)!=pRoot->intKey ){
  65235. return SQLITE_CORRUPT_PAGE(pCur->pPage);
  65236. }
  65237. skip_init:
  65238. pCur->ix = 0;
  65239. pCur->info.nSize = 0;
  65240. pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidNKey|BTCF_ValidOvfl);
  65241. pRoot = pCur->pPage;
  65242. if( pRoot->nCell>0 ){
  65243. pCur->eState = CURSOR_VALID;
  65244. }else if( !pRoot->leaf ){
  65245. Pgno subpage;
  65246. if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
  65247. subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
  65248. pCur->eState = CURSOR_VALID;
  65249. rc = moveToChild(pCur, subpage);
  65250. }else{
  65251. pCur->eState = CURSOR_INVALID;
  65252. rc = SQLITE_EMPTY;
  65253. }
  65254. return rc;
  65255. }
  65256. /*
  65257. ** Move the cursor down to the left-most leaf entry beneath the
  65258. ** entry to which it is currently pointing.
  65259. **
  65260. ** The left-most leaf is the one with the smallest key - the first
  65261. ** in ascending order.
  65262. */
  65263. static int moveToLeftmost(BtCursor *pCur){
  65264. Pgno pgno;
  65265. int rc = SQLITE_OK;
  65266. MemPage *pPage;
  65267. assert( cursorOwnsBtShared(pCur) );
  65268. assert( pCur->eState==CURSOR_VALID );
  65269. while( rc==SQLITE_OK && !(pPage = pCur->pPage)->leaf ){
  65270. assert( pCur->ix<pPage->nCell );
  65271. pgno = get4byte(findCell(pPage, pCur->ix));
  65272. rc = moveToChild(pCur, pgno);
  65273. }
  65274. return rc;
  65275. }
  65276. /*
  65277. ** Move the cursor down to the right-most leaf entry beneath the
  65278. ** page to which it is currently pointing. Notice the difference
  65279. ** between moveToLeftmost() and moveToRightmost(). moveToLeftmost()
  65280. ** finds the left-most entry beneath the *entry* whereas moveToRightmost()
  65281. ** finds the right-most entry beneath the *page*.
  65282. **
  65283. ** The right-most entry is the one with the largest key - the last
  65284. ** key in ascending order.
  65285. */
  65286. static int moveToRightmost(BtCursor *pCur){
  65287. Pgno pgno;
  65288. int rc = SQLITE_OK;
  65289. MemPage *pPage = 0;
  65290. assert( cursorOwnsBtShared(pCur) );
  65291. assert( pCur->eState==CURSOR_VALID );
  65292. while( !(pPage = pCur->pPage)->leaf ){
  65293. pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  65294. pCur->ix = pPage->nCell;
  65295. rc = moveToChild(pCur, pgno);
  65296. if( rc ) return rc;
  65297. }
  65298. pCur->ix = pPage->nCell-1;
  65299. assert( pCur->info.nSize==0 );
  65300. assert( (pCur->curFlags & BTCF_ValidNKey)==0 );
  65301. return SQLITE_OK;
  65302. }
  65303. /* Move the cursor to the first entry in the table. Return SQLITE_OK
  65304. ** on success. Set *pRes to 0 if the cursor actually points to something
  65305. ** or set *pRes to 1 if the table is empty.
  65306. */
  65307. SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
  65308. int rc;
  65309. assert( cursorOwnsBtShared(pCur) );
  65310. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  65311. rc = moveToRoot(pCur);
  65312. if( rc==SQLITE_OK ){
  65313. assert( pCur->pPage->nCell>0 );
  65314. *pRes = 0;
  65315. rc = moveToLeftmost(pCur);
  65316. }else if( rc==SQLITE_EMPTY ){
  65317. assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
  65318. *pRes = 1;
  65319. rc = SQLITE_OK;
  65320. }
  65321. return rc;
  65322. }
  65323. /* Move the cursor to the last entry in the table. Return SQLITE_OK
  65324. ** on success. Set *pRes to 0 if the cursor actually points to something
  65325. ** or set *pRes to 1 if the table is empty.
  65326. */
  65327. SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
  65328. int rc;
  65329. assert( cursorOwnsBtShared(pCur) );
  65330. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  65331. /* If the cursor already points to the last entry, this is a no-op. */
  65332. if( CURSOR_VALID==pCur->eState && (pCur->curFlags & BTCF_AtLast)!=0 ){
  65333. #ifdef SQLITE_DEBUG
  65334. /* This block serves to assert() that the cursor really does point
  65335. ** to the last entry in the b-tree. */
  65336. int ii;
  65337. for(ii=0; ii<pCur->iPage; ii++){
  65338. assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
  65339. }
  65340. assert( pCur->ix==pCur->pPage->nCell-1 );
  65341. assert( pCur->pPage->leaf );
  65342. #endif
  65343. *pRes = 0;
  65344. return SQLITE_OK;
  65345. }
  65346. rc = moveToRoot(pCur);
  65347. if( rc==SQLITE_OK ){
  65348. assert( pCur->eState==CURSOR_VALID );
  65349. *pRes = 0;
  65350. rc = moveToRightmost(pCur);
  65351. if( rc==SQLITE_OK ){
  65352. pCur->curFlags |= BTCF_AtLast;
  65353. }else{
  65354. pCur->curFlags &= ~BTCF_AtLast;
  65355. }
  65356. }else if( rc==SQLITE_EMPTY ){
  65357. assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
  65358. *pRes = 1;
  65359. rc = SQLITE_OK;
  65360. }
  65361. return rc;
  65362. }
  65363. /* Move the cursor so that it points to an entry near the key
  65364. ** specified by pIdxKey or intKey. Return a success code.
  65365. **
  65366. ** For INTKEY tables, the intKey parameter is used. pIdxKey
  65367. ** must be NULL. For index tables, pIdxKey is used and intKey
  65368. ** is ignored.
  65369. **
  65370. ** If an exact match is not found, then the cursor is always
  65371. ** left pointing at a leaf page which would hold the entry if it
  65372. ** were present. The cursor might point to an entry that comes
  65373. ** before or after the key.
  65374. **
  65375. ** An integer is written into *pRes which is the result of
  65376. ** comparing the key with the entry to which the cursor is
  65377. ** pointing. The meaning of the integer written into
  65378. ** *pRes is as follows:
  65379. **
  65380. ** *pRes<0 The cursor is left pointing at an entry that
  65381. ** is smaller than intKey/pIdxKey or if the table is empty
  65382. ** and the cursor is therefore left point to nothing.
  65383. **
  65384. ** *pRes==0 The cursor is left pointing at an entry that
  65385. ** exactly matches intKey/pIdxKey.
  65386. **
  65387. ** *pRes>0 The cursor is left pointing at an entry that
  65388. ** is larger than intKey/pIdxKey.
  65389. **
  65390. ** For index tables, the pIdxKey->eqSeen field is set to 1 if there
  65391. ** exists an entry in the table that exactly matches pIdxKey.
  65392. */
  65393. SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
  65394. BtCursor *pCur, /* The cursor to be moved */
  65395. UnpackedRecord *pIdxKey, /* Unpacked index key */
  65396. i64 intKey, /* The table key */
  65397. int biasRight, /* If true, bias the search to the high end */
  65398. int *pRes /* Write search results here */
  65399. ){
  65400. int rc;
  65401. RecordCompare xRecordCompare;
  65402. assert( cursorOwnsBtShared(pCur) );
  65403. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  65404. assert( pRes );
  65405. assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
  65406. assert( pCur->eState!=CURSOR_VALID || (pIdxKey==0)==(pCur->curIntKey!=0) );
  65407. /* If the cursor is already positioned at the point we are trying
  65408. ** to move to, then just return without doing any work */
  65409. if( pIdxKey==0
  65410. && pCur->eState==CURSOR_VALID && (pCur->curFlags & BTCF_ValidNKey)!=0
  65411. ){
  65412. if( pCur->info.nKey==intKey ){
  65413. *pRes = 0;
  65414. return SQLITE_OK;
  65415. }
  65416. if( pCur->info.nKey<intKey ){
  65417. if( (pCur->curFlags & BTCF_AtLast)!=0 ){
  65418. *pRes = -1;
  65419. return SQLITE_OK;
  65420. }
  65421. /* If the requested key is one more than the previous key, then
  65422. ** try to get there using sqlite3BtreeNext() rather than a full
  65423. ** binary search. This is an optimization only. The correct answer
  65424. ** is still obtained without this case, only a little more slowely */
  65425. if( pCur->info.nKey+1==intKey ){
  65426. *pRes = 0;
  65427. rc = sqlite3BtreeNext(pCur, 0);
  65428. if( rc==SQLITE_OK ){
  65429. getCellInfo(pCur);
  65430. if( pCur->info.nKey==intKey ){
  65431. return SQLITE_OK;
  65432. }
  65433. }else if( rc==SQLITE_DONE ){
  65434. rc = SQLITE_OK;
  65435. }else{
  65436. return rc;
  65437. }
  65438. }
  65439. }
  65440. }
  65441. if( pIdxKey ){
  65442. xRecordCompare = sqlite3VdbeFindCompare(pIdxKey);
  65443. pIdxKey->errCode = 0;
  65444. assert( pIdxKey->default_rc==1
  65445. || pIdxKey->default_rc==0
  65446. || pIdxKey->default_rc==-1
  65447. );
  65448. }else{
  65449. xRecordCompare = 0; /* All keys are integers */
  65450. }
  65451. rc = moveToRoot(pCur);
  65452. if( rc ){
  65453. if( rc==SQLITE_EMPTY ){
  65454. assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
  65455. *pRes = -1;
  65456. return SQLITE_OK;
  65457. }
  65458. return rc;
  65459. }
  65460. assert( pCur->pPage );
  65461. assert( pCur->pPage->isInit );
  65462. assert( pCur->eState==CURSOR_VALID );
  65463. assert( pCur->pPage->nCell > 0 );
  65464. assert( pCur->iPage==0 || pCur->apPage[0]->intKey==pCur->curIntKey );
  65465. assert( pCur->curIntKey || pIdxKey );
  65466. for(;;){
  65467. int lwr, upr, idx, c;
  65468. Pgno chldPg;
  65469. MemPage *pPage = pCur->pPage;
  65470. u8 *pCell; /* Pointer to current cell in pPage */
  65471. /* pPage->nCell must be greater than zero. If this is the root-page
  65472. ** the cursor would have been INVALID above and this for(;;) loop
  65473. ** not run. If this is not the root-page, then the moveToChild() routine
  65474. ** would have already detected db corruption. Similarly, pPage must
  65475. ** be the right kind (index or table) of b-tree page. Otherwise
  65476. ** a moveToChild() or moveToRoot() call would have detected corruption. */
  65477. assert( pPage->nCell>0 );
  65478. assert( pPage->intKey==(pIdxKey==0) );
  65479. lwr = 0;
  65480. upr = pPage->nCell-1;
  65481. assert( biasRight==0 || biasRight==1 );
  65482. idx = upr>>(1-biasRight); /* idx = biasRight ? upr : (lwr+upr)/2; */
  65483. pCur->ix = (u16)idx;
  65484. if( xRecordCompare==0 ){
  65485. for(;;){
  65486. i64 nCellKey;
  65487. pCell = findCellPastPtr(pPage, idx);
  65488. if( pPage->intKeyLeaf ){
  65489. while( 0x80 <= *(pCell++) ){
  65490. if( pCell>=pPage->aDataEnd ){
  65491. return SQLITE_CORRUPT_PAGE(pPage);
  65492. }
  65493. }
  65494. }
  65495. getVarint(pCell, (u64*)&nCellKey);
  65496. if( nCellKey<intKey ){
  65497. lwr = idx+1;
  65498. if( lwr>upr ){ c = -1; break; }
  65499. }else if( nCellKey>intKey ){
  65500. upr = idx-1;
  65501. if( lwr>upr ){ c = +1; break; }
  65502. }else{
  65503. assert( nCellKey==intKey );
  65504. pCur->ix = (u16)idx;
  65505. if( !pPage->leaf ){
  65506. lwr = idx;
  65507. goto moveto_next_layer;
  65508. }else{
  65509. pCur->curFlags |= BTCF_ValidNKey;
  65510. pCur->info.nKey = nCellKey;
  65511. pCur->info.nSize = 0;
  65512. *pRes = 0;
  65513. return SQLITE_OK;
  65514. }
  65515. }
  65516. assert( lwr+upr>=0 );
  65517. idx = (lwr+upr)>>1; /* idx = (lwr+upr)/2; */
  65518. }
  65519. }else{
  65520. for(;;){
  65521. int nCell; /* Size of the pCell cell in bytes */
  65522. pCell = findCellPastPtr(pPage, idx);
  65523. /* The maximum supported page-size is 65536 bytes. This means that
  65524. ** the maximum number of record bytes stored on an index B-Tree
  65525. ** page is less than 16384 bytes and may be stored as a 2-byte
  65526. ** varint. This information is used to attempt to avoid parsing
  65527. ** the entire cell by checking for the cases where the record is
  65528. ** stored entirely within the b-tree page by inspecting the first
  65529. ** 2 bytes of the cell.
  65530. */
  65531. nCell = pCell[0];
  65532. if( nCell<=pPage->max1bytePayload ){
  65533. /* This branch runs if the record-size field of the cell is a
  65534. ** single byte varint and the record fits entirely on the main
  65535. ** b-tree page. */
  65536. testcase( pCell+nCell+1==pPage->aDataEnd );
  65537. c = xRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
  65538. }else if( !(pCell[1] & 0x80)
  65539. && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
  65540. ){
  65541. /* The record-size field is a 2 byte varint and the record
  65542. ** fits entirely on the main b-tree page. */
  65543. testcase( pCell+nCell+2==pPage->aDataEnd );
  65544. c = xRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
  65545. }else{
  65546. /* The record flows over onto one or more overflow pages. In
  65547. ** this case the whole cell needs to be parsed, a buffer allocated
  65548. ** and accessPayload() used to retrieve the record into the
  65549. ** buffer before VdbeRecordCompare() can be called.
  65550. **
  65551. ** If the record is corrupt, the xRecordCompare routine may read
  65552. ** up to two varints past the end of the buffer. An extra 18
  65553. ** bytes of padding is allocated at the end of the buffer in
  65554. ** case this happens. */
  65555. void *pCellKey;
  65556. u8 * const pCellBody = pCell - pPage->childPtrSize;
  65557. const int nOverrun = 18; /* Size of the overrun padding */
  65558. pPage->xParseCell(pPage, pCellBody, &pCur->info);
  65559. nCell = (int)pCur->info.nKey;
  65560. testcase( nCell<0 ); /* True if key size is 2^32 or more */
  65561. testcase( nCell==0 ); /* Invalid key size: 0x80 0x80 0x00 */
  65562. testcase( nCell==1 ); /* Invalid key size: 0x80 0x80 0x01 */
  65563. testcase( nCell==2 ); /* Minimum legal index key size */
  65564. if( nCell<2 || nCell/pCur->pBt->usableSize>pCur->pBt->nPage ){
  65565. rc = SQLITE_CORRUPT_PAGE(pPage);
  65566. goto moveto_finish;
  65567. }
  65568. pCellKey = sqlite3Malloc( nCell+nOverrun );
  65569. if( pCellKey==0 ){
  65570. rc = SQLITE_NOMEM_BKPT;
  65571. goto moveto_finish;
  65572. }
  65573. pCur->ix = (u16)idx;
  65574. rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0);
  65575. memset(((u8*)pCellKey)+nCell,0,nOverrun); /* Fix uninit warnings */
  65576. pCur->curFlags &= ~BTCF_ValidOvfl;
  65577. if( rc ){
  65578. sqlite3_free(pCellKey);
  65579. goto moveto_finish;
  65580. }
  65581. c = sqlite3VdbeRecordCompare(nCell, pCellKey, pIdxKey);
  65582. sqlite3_free(pCellKey);
  65583. }
  65584. assert(
  65585. (pIdxKey->errCode!=SQLITE_CORRUPT || c==0)
  65586. && (pIdxKey->errCode!=SQLITE_NOMEM || pCur->pBtree->db->mallocFailed)
  65587. );
  65588. if( c<0 ){
  65589. lwr = idx+1;
  65590. }else if( c>0 ){
  65591. upr = idx-1;
  65592. }else{
  65593. assert( c==0 );
  65594. *pRes = 0;
  65595. rc = SQLITE_OK;
  65596. pCur->ix = (u16)idx;
  65597. if( pIdxKey->errCode ) rc = SQLITE_CORRUPT_BKPT;
  65598. goto moveto_finish;
  65599. }
  65600. if( lwr>upr ) break;
  65601. assert( lwr+upr>=0 );
  65602. idx = (lwr+upr)>>1; /* idx = (lwr+upr)/2 */
  65603. }
  65604. }
  65605. assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) );
  65606. assert( pPage->isInit );
  65607. if( pPage->leaf ){
  65608. assert( pCur->ix<pCur->pPage->nCell );
  65609. pCur->ix = (u16)idx;
  65610. *pRes = c;
  65611. rc = SQLITE_OK;
  65612. goto moveto_finish;
  65613. }
  65614. moveto_next_layer:
  65615. if( lwr>=pPage->nCell ){
  65616. chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  65617. }else{
  65618. chldPg = get4byte(findCell(pPage, lwr));
  65619. }
  65620. pCur->ix = (u16)lwr;
  65621. rc = moveToChild(pCur, chldPg);
  65622. if( rc ) break;
  65623. }
  65624. moveto_finish:
  65625. pCur->info.nSize = 0;
  65626. assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
  65627. return rc;
  65628. }
  65629. /*
  65630. ** Return TRUE if the cursor is not pointing at an entry of the table.
  65631. **
  65632. ** TRUE will be returned after a call to sqlite3BtreeNext() moves
  65633. ** past the last entry in the table or sqlite3BtreePrev() moves past
  65634. ** the first entry. TRUE is also returned if the table is empty.
  65635. */
  65636. SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){
  65637. /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
  65638. ** have been deleted? This API will need to change to return an error code
  65639. ** as well as the boolean result value.
  65640. */
  65641. return (CURSOR_VALID!=pCur->eState);
  65642. }
  65643. /*
  65644. ** Return an estimate for the number of rows in the table that pCur is
  65645. ** pointing to. Return a negative number if no estimate is currently
  65646. ** available.
  65647. */
  65648. SQLITE_PRIVATE i64 sqlite3BtreeRowCountEst(BtCursor *pCur){
  65649. i64 n;
  65650. u8 i;
  65651. assert( cursorOwnsBtShared(pCur) );
  65652. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  65653. /* Currently this interface is only called by the OP_IfSmaller
  65654. ** opcode, and it that case the cursor will always be valid and
  65655. ** will always point to a leaf node. */
  65656. if( NEVER(pCur->eState!=CURSOR_VALID) ) return -1;
  65657. if( NEVER(pCur->pPage->leaf==0) ) return -1;
  65658. n = pCur->pPage->nCell;
  65659. for(i=0; i<pCur->iPage; i++){
  65660. n *= pCur->apPage[i]->nCell;
  65661. }
  65662. return n;
  65663. }
  65664. /*
  65665. ** Advance the cursor to the next entry in the database.
  65666. ** Return value:
  65667. **
  65668. ** SQLITE_OK success
  65669. ** SQLITE_DONE cursor is already pointing at the last element
  65670. ** otherwise some kind of error occurred
  65671. **
  65672. ** The main entry point is sqlite3BtreeNext(). That routine is optimized
  65673. ** for the common case of merely incrementing the cell counter BtCursor.aiIdx
  65674. ** to the next cell on the current page. The (slower) btreeNext() helper
  65675. ** routine is called when it is necessary to move to a different page or
  65676. ** to restore the cursor.
  65677. **
  65678. ** If bit 0x01 of the F argument in sqlite3BtreeNext(C,F) is 1, then the
  65679. ** cursor corresponds to an SQL index and this routine could have been
  65680. ** skipped if the SQL index had been a unique index. The F argument
  65681. ** is a hint to the implement. SQLite btree implementation does not use
  65682. ** this hint, but COMDB2 does.
  65683. */
  65684. static SQLITE_NOINLINE int btreeNext(BtCursor *pCur){
  65685. int rc;
  65686. int idx;
  65687. MemPage *pPage;
  65688. assert( cursorOwnsBtShared(pCur) );
  65689. if( pCur->eState!=CURSOR_VALID ){
  65690. assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
  65691. rc = restoreCursorPosition(pCur);
  65692. if( rc!=SQLITE_OK ){
  65693. return rc;
  65694. }
  65695. if( CURSOR_INVALID==pCur->eState ){
  65696. return SQLITE_DONE;
  65697. }
  65698. if( pCur->eState==CURSOR_SKIPNEXT ){
  65699. pCur->eState = CURSOR_VALID;
  65700. if( pCur->skipNext>0 ) return SQLITE_OK;
  65701. }
  65702. }
  65703. pPage = pCur->pPage;
  65704. idx = ++pCur->ix;
  65705. if( !pPage->isInit ){
  65706. /* The only known way for this to happen is for there to be a
  65707. ** recursive SQL function that does a DELETE operation as part of a
  65708. ** SELECT which deletes content out from under an active cursor
  65709. ** in a corrupt database file where the table being DELETE-ed from
  65710. ** has pages in common with the table being queried. See TH3
  65711. ** module cov1/btree78.test testcase 220 (2018-06-08) for an
  65712. ** example. */
  65713. return SQLITE_CORRUPT_BKPT;
  65714. }
  65715. /* If the database file is corrupt, it is possible for the value of idx
  65716. ** to be invalid here. This can only occur if a second cursor modifies
  65717. ** the page while cursor pCur is holding a reference to it. Which can
  65718. ** only happen if the database is corrupt in such a way as to link the
  65719. ** page into more than one b-tree structure.
  65720. **
  65721. ** Update 2019-12-23: appears to long longer be possible after the
  65722. ** addition of anotherValidCursor() condition on balance_deeper(). */
  65723. harmless( idx>pPage->nCell );
  65724. if( idx>=pPage->nCell ){
  65725. if( !pPage->leaf ){
  65726. rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
  65727. if( rc ) return rc;
  65728. return moveToLeftmost(pCur);
  65729. }
  65730. do{
  65731. if( pCur->iPage==0 ){
  65732. pCur->eState = CURSOR_INVALID;
  65733. return SQLITE_DONE;
  65734. }
  65735. moveToParent(pCur);
  65736. pPage = pCur->pPage;
  65737. }while( pCur->ix>=pPage->nCell );
  65738. if( pPage->intKey ){
  65739. return sqlite3BtreeNext(pCur, 0);
  65740. }else{
  65741. return SQLITE_OK;
  65742. }
  65743. }
  65744. if( pPage->leaf ){
  65745. return SQLITE_OK;
  65746. }else{
  65747. return moveToLeftmost(pCur);
  65748. }
  65749. }
  65750. SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int flags){
  65751. MemPage *pPage;
  65752. UNUSED_PARAMETER( flags ); /* Used in COMDB2 but not native SQLite */
  65753. assert( cursorOwnsBtShared(pCur) );
  65754. assert( flags==0 || flags==1 );
  65755. pCur->info.nSize = 0;
  65756. pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
  65757. if( pCur->eState!=CURSOR_VALID ) return btreeNext(pCur);
  65758. pPage = pCur->pPage;
  65759. if( (++pCur->ix)>=pPage->nCell ){
  65760. pCur->ix--;
  65761. return btreeNext(pCur);
  65762. }
  65763. if( pPage->leaf ){
  65764. return SQLITE_OK;
  65765. }else{
  65766. return moveToLeftmost(pCur);
  65767. }
  65768. }
  65769. /*
  65770. ** Step the cursor to the back to the previous entry in the database.
  65771. ** Return values:
  65772. **
  65773. ** SQLITE_OK success
  65774. ** SQLITE_DONE the cursor is already on the first element of the table
  65775. ** otherwise some kind of error occurred
  65776. **
  65777. ** The main entry point is sqlite3BtreePrevious(). That routine is optimized
  65778. ** for the common case of merely decrementing the cell counter BtCursor.aiIdx
  65779. ** to the previous cell on the current page. The (slower) btreePrevious()
  65780. ** helper routine is called when it is necessary to move to a different page
  65781. ** or to restore the cursor.
  65782. **
  65783. ** If bit 0x01 of the F argument to sqlite3BtreePrevious(C,F) is 1, then
  65784. ** the cursor corresponds to an SQL index and this routine could have been
  65785. ** skipped if the SQL index had been a unique index. The F argument is a
  65786. ** hint to the implement. The native SQLite btree implementation does not
  65787. ** use this hint, but COMDB2 does.
  65788. */
  65789. static SQLITE_NOINLINE int btreePrevious(BtCursor *pCur){
  65790. int rc;
  65791. MemPage *pPage;
  65792. assert( cursorOwnsBtShared(pCur) );
  65793. assert( (pCur->curFlags & (BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey))==0 );
  65794. assert( pCur->info.nSize==0 );
  65795. if( pCur->eState!=CURSOR_VALID ){
  65796. rc = restoreCursorPosition(pCur);
  65797. if( rc!=SQLITE_OK ){
  65798. return rc;
  65799. }
  65800. if( CURSOR_INVALID==pCur->eState ){
  65801. return SQLITE_DONE;
  65802. }
  65803. if( CURSOR_SKIPNEXT==pCur->eState ){
  65804. pCur->eState = CURSOR_VALID;
  65805. if( pCur->skipNext<0 ) return SQLITE_OK;
  65806. }
  65807. }
  65808. pPage = pCur->pPage;
  65809. assert( pPage->isInit );
  65810. if( !pPage->leaf ){
  65811. int idx = pCur->ix;
  65812. rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
  65813. if( rc ) return rc;
  65814. rc = moveToRightmost(pCur);
  65815. }else{
  65816. while( pCur->ix==0 ){
  65817. if( pCur->iPage==0 ){
  65818. pCur->eState = CURSOR_INVALID;
  65819. return SQLITE_DONE;
  65820. }
  65821. moveToParent(pCur);
  65822. }
  65823. assert( pCur->info.nSize==0 );
  65824. assert( (pCur->curFlags & (BTCF_ValidOvfl))==0 );
  65825. pCur->ix--;
  65826. pPage = pCur->pPage;
  65827. if( pPage->intKey && !pPage->leaf ){
  65828. rc = sqlite3BtreePrevious(pCur, 0);
  65829. }else{
  65830. rc = SQLITE_OK;
  65831. }
  65832. }
  65833. return rc;
  65834. }
  65835. SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int flags){
  65836. assert( cursorOwnsBtShared(pCur) );
  65837. assert( flags==0 || flags==1 );
  65838. UNUSED_PARAMETER( flags ); /* Used in COMDB2 but not native SQLite */
  65839. pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey);
  65840. pCur->info.nSize = 0;
  65841. if( pCur->eState!=CURSOR_VALID
  65842. || pCur->ix==0
  65843. || pCur->pPage->leaf==0
  65844. ){
  65845. return btreePrevious(pCur);
  65846. }
  65847. pCur->ix--;
  65848. return SQLITE_OK;
  65849. }
  65850. /*
  65851. ** Allocate a new page from the database file.
  65852. **
  65853. ** The new page is marked as dirty. (In other words, sqlite3PagerWrite()
  65854. ** has already been called on the new page.) The new page has also
  65855. ** been referenced and the calling routine is responsible for calling
  65856. ** sqlite3PagerUnref() on the new page when it is done.
  65857. **
  65858. ** SQLITE_OK is returned on success. Any other return value indicates
  65859. ** an error. *ppPage is set to NULL in the event of an error.
  65860. **
  65861. ** If the "nearby" parameter is not 0, then an effort is made to
  65862. ** locate a page close to the page number "nearby". This can be used in an
  65863. ** attempt to keep related pages close to each other in the database file,
  65864. ** which in turn can make database access faster.
  65865. **
  65866. ** If the eMode parameter is BTALLOC_EXACT and the nearby page exists
  65867. ** anywhere on the free-list, then it is guaranteed to be returned. If
  65868. ** eMode is BTALLOC_LT then the page returned will be less than or equal
  65869. ** to nearby if any such page exists. If eMode is BTALLOC_ANY then there
  65870. ** are no restrictions on which page is returned.
  65871. */
  65872. static int allocateBtreePage(
  65873. BtShared *pBt, /* The btree */
  65874. MemPage **ppPage, /* Store pointer to the allocated page here */
  65875. Pgno *pPgno, /* Store the page number here */
  65876. Pgno nearby, /* Search for a page near this one */
  65877. u8 eMode /* BTALLOC_EXACT, BTALLOC_LT, or BTALLOC_ANY */
  65878. ){
  65879. MemPage *pPage1;
  65880. int rc;
  65881. u32 n; /* Number of pages on the freelist */
  65882. u32 k; /* Number of leaves on the trunk of the freelist */
  65883. MemPage *pTrunk = 0;
  65884. MemPage *pPrevTrunk = 0;
  65885. Pgno mxPage; /* Total size of the database file */
  65886. assert( sqlite3_mutex_held(pBt->mutex) );
  65887. assert( eMode==BTALLOC_ANY || (nearby>0 && IfNotOmitAV(pBt->autoVacuum)) );
  65888. pPage1 = pBt->pPage1;
  65889. mxPage = btreePagecount(pBt);
  65890. /* EVIDENCE-OF: R-05119-02637 The 4-byte big-endian integer at offset 36
  65891. ** stores stores the total number of pages on the freelist. */
  65892. n = get4byte(&pPage1->aData[36]);
  65893. testcase( n==mxPage-1 );
  65894. if( n>=mxPage ){
  65895. return SQLITE_CORRUPT_BKPT;
  65896. }
  65897. if( n>0 ){
  65898. /* There are pages on the freelist. Reuse one of those pages. */
  65899. Pgno iTrunk;
  65900. u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
  65901. u32 nSearch = 0; /* Count of the number of search attempts */
  65902. /* If eMode==BTALLOC_EXACT and a query of the pointer-map
  65903. ** shows that the page 'nearby' is somewhere on the free-list, then
  65904. ** the entire-list will be searched for that page.
  65905. */
  65906. #ifndef SQLITE_OMIT_AUTOVACUUM
  65907. if( eMode==BTALLOC_EXACT ){
  65908. if( nearby<=mxPage ){
  65909. u8 eType;
  65910. assert( nearby>0 );
  65911. assert( pBt->autoVacuum );
  65912. rc = ptrmapGet(pBt, nearby, &eType, 0);
  65913. if( rc ) return rc;
  65914. if( eType==PTRMAP_FREEPAGE ){
  65915. searchList = 1;
  65916. }
  65917. }
  65918. }else if( eMode==BTALLOC_LE ){
  65919. searchList = 1;
  65920. }
  65921. #endif
  65922. /* Decrement the free-list count by 1. Set iTrunk to the index of the
  65923. ** first free-list trunk page. iPrevTrunk is initially 1.
  65924. */
  65925. rc = sqlite3PagerWrite(pPage1->pDbPage);
  65926. if( rc ) return rc;
  65927. put4byte(&pPage1->aData[36], n-1);
  65928. /* The code within this loop is run only once if the 'searchList' variable
  65929. ** is not true. Otherwise, it runs once for each trunk-page on the
  65930. ** free-list until the page 'nearby' is located (eMode==BTALLOC_EXACT)
  65931. ** or until a page less than 'nearby' is located (eMode==BTALLOC_LT)
  65932. */
  65933. do {
  65934. pPrevTrunk = pTrunk;
  65935. if( pPrevTrunk ){
  65936. /* EVIDENCE-OF: R-01506-11053 The first integer on a freelist trunk page
  65937. ** is the page number of the next freelist trunk page in the list or
  65938. ** zero if this is the last freelist trunk page. */
  65939. iTrunk = get4byte(&pPrevTrunk->aData[0]);
  65940. }else{
  65941. /* EVIDENCE-OF: R-59841-13798 The 4-byte big-endian integer at offset 32
  65942. ** stores the page number of the first page of the freelist, or zero if
  65943. ** the freelist is empty. */
  65944. iTrunk = get4byte(&pPage1->aData[32]);
  65945. }
  65946. testcase( iTrunk==mxPage );
  65947. if( iTrunk>mxPage || nSearch++ > n ){
  65948. rc = SQLITE_CORRUPT_PGNO(pPrevTrunk ? pPrevTrunk->pgno : 1);
  65949. }else{
  65950. rc = btreeGetUnusedPage(pBt, iTrunk, &pTrunk, 0);
  65951. }
  65952. if( rc ){
  65953. pTrunk = 0;
  65954. goto end_allocate_page;
  65955. }
  65956. assert( pTrunk!=0 );
  65957. assert( pTrunk->aData!=0 );
  65958. /* EVIDENCE-OF: R-13523-04394 The second integer on a freelist trunk page
  65959. ** is the number of leaf page pointers to follow. */
  65960. k = get4byte(&pTrunk->aData[4]);
  65961. if( k==0 && !searchList ){
  65962. /* The trunk has no leaves and the list is not being searched.
  65963. ** So extract the trunk page itself and use it as the newly
  65964. ** allocated page */
  65965. assert( pPrevTrunk==0 );
  65966. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  65967. if( rc ){
  65968. goto end_allocate_page;
  65969. }
  65970. *pPgno = iTrunk;
  65971. memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
  65972. *ppPage = pTrunk;
  65973. pTrunk = 0;
  65974. TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
  65975. }else if( k>(u32)(pBt->usableSize/4 - 2) ){
  65976. /* Value of k is out of range. Database corruption */
  65977. rc = SQLITE_CORRUPT_PGNO(iTrunk);
  65978. goto end_allocate_page;
  65979. #ifndef SQLITE_OMIT_AUTOVACUUM
  65980. }else if( searchList
  65981. && (nearby==iTrunk || (iTrunk<nearby && eMode==BTALLOC_LE))
  65982. ){
  65983. /* The list is being searched and this trunk page is the page
  65984. ** to allocate, regardless of whether it has leaves.
  65985. */
  65986. *pPgno = iTrunk;
  65987. *ppPage = pTrunk;
  65988. searchList = 0;
  65989. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  65990. if( rc ){
  65991. goto end_allocate_page;
  65992. }
  65993. if( k==0 ){
  65994. if( !pPrevTrunk ){
  65995. memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
  65996. }else{
  65997. rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
  65998. if( rc!=SQLITE_OK ){
  65999. goto end_allocate_page;
  66000. }
  66001. memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
  66002. }
  66003. }else{
  66004. /* The trunk page is required by the caller but it contains
  66005. ** pointers to free-list leaves. The first leaf becomes a trunk
  66006. ** page in this case.
  66007. */
  66008. MemPage *pNewTrunk;
  66009. Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
  66010. if( iNewTrunk>mxPage ){
  66011. rc = SQLITE_CORRUPT_PGNO(iTrunk);
  66012. goto end_allocate_page;
  66013. }
  66014. testcase( iNewTrunk==mxPage );
  66015. rc = btreeGetUnusedPage(pBt, iNewTrunk, &pNewTrunk, 0);
  66016. if( rc!=SQLITE_OK ){
  66017. goto end_allocate_page;
  66018. }
  66019. rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
  66020. if( rc!=SQLITE_OK ){
  66021. releasePage(pNewTrunk);
  66022. goto end_allocate_page;
  66023. }
  66024. memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
  66025. put4byte(&pNewTrunk->aData[4], k-1);
  66026. memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
  66027. releasePage(pNewTrunk);
  66028. if( !pPrevTrunk ){
  66029. assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
  66030. put4byte(&pPage1->aData[32], iNewTrunk);
  66031. }else{
  66032. rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
  66033. if( rc ){
  66034. goto end_allocate_page;
  66035. }
  66036. put4byte(&pPrevTrunk->aData[0], iNewTrunk);
  66037. }
  66038. }
  66039. pTrunk = 0;
  66040. TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
  66041. #endif
  66042. }else if( k>0 ){
  66043. /* Extract a leaf from the trunk */
  66044. u32 closest;
  66045. Pgno iPage;
  66046. unsigned char *aData = pTrunk->aData;
  66047. if( nearby>0 ){
  66048. u32 i;
  66049. closest = 0;
  66050. if( eMode==BTALLOC_LE ){
  66051. for(i=0; i<k; i++){
  66052. iPage = get4byte(&aData[8+i*4]);
  66053. if( iPage<=nearby ){
  66054. closest = i;
  66055. break;
  66056. }
  66057. }
  66058. }else{
  66059. int dist;
  66060. dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
  66061. for(i=1; i<k; i++){
  66062. int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
  66063. if( d2<dist ){
  66064. closest = i;
  66065. dist = d2;
  66066. }
  66067. }
  66068. }
  66069. }else{
  66070. closest = 0;
  66071. }
  66072. iPage = get4byte(&aData[8+closest*4]);
  66073. testcase( iPage==mxPage );
  66074. if( iPage>mxPage ){
  66075. rc = SQLITE_CORRUPT_PGNO(iTrunk);
  66076. goto end_allocate_page;
  66077. }
  66078. testcase( iPage==mxPage );
  66079. if( !searchList
  66080. || (iPage==nearby || (iPage<nearby && eMode==BTALLOC_LE))
  66081. ){
  66082. int noContent;
  66083. *pPgno = iPage;
  66084. TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
  66085. ": %d more free pages\n",
  66086. *pPgno, closest+1, k, pTrunk->pgno, n-1));
  66087. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  66088. if( rc ) goto end_allocate_page;
  66089. if( closest<k-1 ){
  66090. memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
  66091. }
  66092. put4byte(&aData[4], k-1);
  66093. noContent = !btreeGetHasContent(pBt, *pPgno)? PAGER_GET_NOCONTENT : 0;
  66094. rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, noContent);
  66095. if( rc==SQLITE_OK ){
  66096. rc = sqlite3PagerWrite((*ppPage)->pDbPage);
  66097. if( rc!=SQLITE_OK ){
  66098. releasePage(*ppPage);
  66099. *ppPage = 0;
  66100. }
  66101. }
  66102. searchList = 0;
  66103. }
  66104. }
  66105. releasePage(pPrevTrunk);
  66106. pPrevTrunk = 0;
  66107. }while( searchList );
  66108. }else{
  66109. /* There are no pages on the freelist, so append a new page to the
  66110. ** database image.
  66111. **
  66112. ** Normally, new pages allocated by this block can be requested from the
  66113. ** pager layer with the 'no-content' flag set. This prevents the pager
  66114. ** from trying to read the pages content from disk. However, if the
  66115. ** current transaction has already run one or more incremental-vacuum
  66116. ** steps, then the page we are about to allocate may contain content
  66117. ** that is required in the event of a rollback. In this case, do
  66118. ** not set the no-content flag. This causes the pager to load and journal
  66119. ** the current page content before overwriting it.
  66120. **
  66121. ** Note that the pager will not actually attempt to load or journal
  66122. ** content for any page that really does lie past the end of the database
  66123. ** file on disk. So the effects of disabling the no-content optimization
  66124. ** here are confined to those pages that lie between the end of the
  66125. ** database image and the end of the database file.
  66126. */
  66127. int bNoContent = (0==IfNotOmitAV(pBt->bDoTruncate))? PAGER_GET_NOCONTENT:0;
  66128. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  66129. if( rc ) return rc;
  66130. pBt->nPage++;
  66131. if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
  66132. #ifndef SQLITE_OMIT_AUTOVACUUM
  66133. if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
  66134. /* If *pPgno refers to a pointer-map page, allocate two new pages
  66135. ** at the end of the file instead of one. The first allocated page
  66136. ** becomes a new pointer-map page, the second is used by the caller.
  66137. */
  66138. MemPage *pPg = 0;
  66139. TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
  66140. assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
  66141. rc = btreeGetUnusedPage(pBt, pBt->nPage, &pPg, bNoContent);
  66142. if( rc==SQLITE_OK ){
  66143. rc = sqlite3PagerWrite(pPg->pDbPage);
  66144. releasePage(pPg);
  66145. }
  66146. if( rc ) return rc;
  66147. pBt->nPage++;
  66148. if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
  66149. }
  66150. #endif
  66151. put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
  66152. *pPgno = pBt->nPage;
  66153. assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
  66154. rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, bNoContent);
  66155. if( rc ) return rc;
  66156. rc = sqlite3PagerWrite((*ppPage)->pDbPage);
  66157. if( rc!=SQLITE_OK ){
  66158. releasePage(*ppPage);
  66159. *ppPage = 0;
  66160. }
  66161. TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
  66162. }
  66163. assert( CORRUPT_DB || *pPgno!=PENDING_BYTE_PAGE(pBt) );
  66164. end_allocate_page:
  66165. releasePage(pTrunk);
  66166. releasePage(pPrevTrunk);
  66167. assert( rc!=SQLITE_OK || sqlite3PagerPageRefcount((*ppPage)->pDbPage)<=1 );
  66168. assert( rc!=SQLITE_OK || (*ppPage)->isInit==0 );
  66169. return rc;
  66170. }
  66171. /*
  66172. ** This function is used to add page iPage to the database file free-list.
  66173. ** It is assumed that the page is not already a part of the free-list.
  66174. **
  66175. ** The value passed as the second argument to this function is optional.
  66176. ** If the caller happens to have a pointer to the MemPage object
  66177. ** corresponding to page iPage handy, it may pass it as the second value.
  66178. ** Otherwise, it may pass NULL.
  66179. **
  66180. ** If a pointer to a MemPage object is passed as the second argument,
  66181. ** its reference count is not altered by this function.
  66182. */
  66183. static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
  66184. MemPage *pTrunk = 0; /* Free-list trunk page */
  66185. Pgno iTrunk = 0; /* Page number of free-list trunk page */
  66186. MemPage *pPage1 = pBt->pPage1; /* Local reference to page 1 */
  66187. MemPage *pPage; /* Page being freed. May be NULL. */
  66188. int rc; /* Return Code */
  66189. u32 nFree; /* Initial number of pages on free-list */
  66190. assert( sqlite3_mutex_held(pBt->mutex) );
  66191. assert( CORRUPT_DB || iPage>1 );
  66192. assert( !pMemPage || pMemPage->pgno==iPage );
  66193. if( iPage<2 || iPage>pBt->nPage ){
  66194. return SQLITE_CORRUPT_BKPT;
  66195. }
  66196. if( pMemPage ){
  66197. pPage = pMemPage;
  66198. sqlite3PagerRef(pPage->pDbPage);
  66199. }else{
  66200. pPage = btreePageLookup(pBt, iPage);
  66201. }
  66202. /* Increment the free page count on pPage1 */
  66203. rc = sqlite3PagerWrite(pPage1->pDbPage);
  66204. if( rc ) goto freepage_out;
  66205. nFree = get4byte(&pPage1->aData[36]);
  66206. put4byte(&pPage1->aData[36], nFree+1);
  66207. if( pBt->btsFlags & BTS_SECURE_DELETE ){
  66208. /* If the secure_delete option is enabled, then
  66209. ** always fully overwrite deleted information with zeros.
  66210. */
  66211. if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
  66212. || ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
  66213. ){
  66214. goto freepage_out;
  66215. }
  66216. memset(pPage->aData, 0, pPage->pBt->pageSize);
  66217. }
  66218. /* If the database supports auto-vacuum, write an entry in the pointer-map
  66219. ** to indicate that the page is free.
  66220. */
  66221. if( ISAUTOVACUUM ){
  66222. ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
  66223. if( rc ) goto freepage_out;
  66224. }
  66225. /* Now manipulate the actual database free-list structure. There are two
  66226. ** possibilities. If the free-list is currently empty, or if the first
  66227. ** trunk page in the free-list is full, then this page will become a
  66228. ** new free-list trunk page. Otherwise, it will become a leaf of the
  66229. ** first trunk page in the current free-list. This block tests if it
  66230. ** is possible to add the page as a new free-list leaf.
  66231. */
  66232. if( nFree!=0 ){
  66233. u32 nLeaf; /* Initial number of leaf cells on trunk page */
  66234. iTrunk = get4byte(&pPage1->aData[32]);
  66235. rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
  66236. if( rc!=SQLITE_OK ){
  66237. goto freepage_out;
  66238. }
  66239. nLeaf = get4byte(&pTrunk->aData[4]);
  66240. assert( pBt->usableSize>32 );
  66241. if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
  66242. rc = SQLITE_CORRUPT_BKPT;
  66243. goto freepage_out;
  66244. }
  66245. if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
  66246. /* In this case there is room on the trunk page to insert the page
  66247. ** being freed as a new leaf.
  66248. **
  66249. ** Note that the trunk page is not really full until it contains
  66250. ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
  66251. ** coded. But due to a coding error in versions of SQLite prior to
  66252. ** 3.6.0, databases with freelist trunk pages holding more than
  66253. ** usableSize/4 - 8 entries will be reported as corrupt. In order
  66254. ** to maintain backwards compatibility with older versions of SQLite,
  66255. ** we will continue to restrict the number of entries to usableSize/4 - 8
  66256. ** for now. At some point in the future (once everyone has upgraded
  66257. ** to 3.6.0 or later) we should consider fixing the conditional above
  66258. ** to read "usableSize/4-2" instead of "usableSize/4-8".
  66259. **
  66260. ** EVIDENCE-OF: R-19920-11576 However, newer versions of SQLite still
  66261. ** avoid using the last six entries in the freelist trunk page array in
  66262. ** order that database files created by newer versions of SQLite can be
  66263. ** read by older versions of SQLite.
  66264. */
  66265. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  66266. if( rc==SQLITE_OK ){
  66267. put4byte(&pTrunk->aData[4], nLeaf+1);
  66268. put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
  66269. if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){
  66270. sqlite3PagerDontWrite(pPage->pDbPage);
  66271. }
  66272. rc = btreeSetHasContent(pBt, iPage);
  66273. }
  66274. TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
  66275. goto freepage_out;
  66276. }
  66277. }
  66278. /* If control flows to this point, then it was not possible to add the
  66279. ** the page being freed as a leaf page of the first trunk in the free-list.
  66280. ** Possibly because the free-list is empty, or possibly because the
  66281. ** first trunk in the free-list is full. Either way, the page being freed
  66282. ** will become the new first trunk page in the free-list.
  66283. */
  66284. if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
  66285. goto freepage_out;
  66286. }
  66287. rc = sqlite3PagerWrite(pPage->pDbPage);
  66288. if( rc!=SQLITE_OK ){
  66289. goto freepage_out;
  66290. }
  66291. put4byte(pPage->aData, iTrunk);
  66292. put4byte(&pPage->aData[4], 0);
  66293. put4byte(&pPage1->aData[32], iPage);
  66294. TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
  66295. freepage_out:
  66296. if( pPage ){
  66297. pPage->isInit = 0;
  66298. }
  66299. releasePage(pPage);
  66300. releasePage(pTrunk);
  66301. return rc;
  66302. }
  66303. static void freePage(MemPage *pPage, int *pRC){
  66304. if( (*pRC)==SQLITE_OK ){
  66305. *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
  66306. }
  66307. }
  66308. /*
  66309. ** Free any overflow pages associated with the given Cell. Store
  66310. ** size information about the cell in pInfo.
  66311. */
  66312. static int clearCell(
  66313. MemPage *pPage, /* The page that contains the Cell */
  66314. unsigned char *pCell, /* First byte of the Cell */
  66315. CellInfo *pInfo /* Size information about the cell */
  66316. ){
  66317. BtShared *pBt;
  66318. Pgno ovflPgno;
  66319. int rc;
  66320. int nOvfl;
  66321. u32 ovflPageSize;
  66322. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  66323. pPage->xParseCell(pPage, pCell, pInfo);
  66324. if( pInfo->nLocal==pInfo->nPayload ){
  66325. return SQLITE_OK; /* No overflow pages. Return without doing anything */
  66326. }
  66327. testcase( pCell + pInfo->nSize == pPage->aDataEnd );
  66328. testcase( pCell + (pInfo->nSize-1) == pPage->aDataEnd );
  66329. if( pCell + pInfo->nSize > pPage->aDataEnd ){
  66330. /* Cell extends past end of page */
  66331. return SQLITE_CORRUPT_PAGE(pPage);
  66332. }
  66333. ovflPgno = get4byte(pCell + pInfo->nSize - 4);
  66334. pBt = pPage->pBt;
  66335. assert( pBt->usableSize > 4 );
  66336. ovflPageSize = pBt->usableSize - 4;
  66337. nOvfl = (pInfo->nPayload - pInfo->nLocal + ovflPageSize - 1)/ovflPageSize;
  66338. assert( nOvfl>0 ||
  66339. (CORRUPT_DB && (pInfo->nPayload + ovflPageSize)<ovflPageSize)
  66340. );
  66341. while( nOvfl-- ){
  66342. Pgno iNext = 0;
  66343. MemPage *pOvfl = 0;
  66344. if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
  66345. /* 0 is not a legal page number and page 1 cannot be an
  66346. ** overflow page. Therefore if ovflPgno<2 or past the end of the
  66347. ** file the database must be corrupt. */
  66348. return SQLITE_CORRUPT_BKPT;
  66349. }
  66350. if( nOvfl ){
  66351. rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
  66352. if( rc ) return rc;
  66353. }
  66354. if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
  66355. && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
  66356. ){
  66357. /* There is no reason any cursor should have an outstanding reference
  66358. ** to an overflow page belonging to a cell that is being deleted/updated.
  66359. ** So if there exists more than one reference to this page, then it
  66360. ** must not really be an overflow page and the database must be corrupt.
  66361. ** It is helpful to detect this before calling freePage2(), as
  66362. ** freePage2() may zero the page contents if secure-delete mode is
  66363. ** enabled. If this 'overflow' page happens to be a page that the
  66364. ** caller is iterating through or using in some other way, this
  66365. ** can be problematic.
  66366. */
  66367. rc = SQLITE_CORRUPT_BKPT;
  66368. }else{
  66369. rc = freePage2(pBt, pOvfl, ovflPgno);
  66370. }
  66371. if( pOvfl ){
  66372. sqlite3PagerUnref(pOvfl->pDbPage);
  66373. }
  66374. if( rc ) return rc;
  66375. ovflPgno = iNext;
  66376. }
  66377. return SQLITE_OK;
  66378. }
  66379. /*
  66380. ** Create the byte sequence used to represent a cell on page pPage
  66381. ** and write that byte sequence into pCell[]. Overflow pages are
  66382. ** allocated and filled in as necessary. The calling procedure
  66383. ** is responsible for making sure sufficient space has been allocated
  66384. ** for pCell[].
  66385. **
  66386. ** Note that pCell does not necessary need to point to the pPage->aData
  66387. ** area. pCell might point to some temporary storage. The cell will
  66388. ** be constructed in this temporary area then copied into pPage->aData
  66389. ** later.
  66390. */
  66391. static int fillInCell(
  66392. MemPage *pPage, /* The page that contains the cell */
  66393. unsigned char *pCell, /* Complete text of the cell */
  66394. const BtreePayload *pX, /* Payload with which to construct the cell */
  66395. int *pnSize /* Write cell size here */
  66396. ){
  66397. int nPayload;
  66398. const u8 *pSrc;
  66399. int nSrc, n, rc, mn;
  66400. int spaceLeft;
  66401. MemPage *pToRelease;
  66402. unsigned char *pPrior;
  66403. unsigned char *pPayload;
  66404. BtShared *pBt;
  66405. Pgno pgnoOvfl;
  66406. int nHeader;
  66407. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  66408. /* pPage is not necessarily writeable since pCell might be auxiliary
  66409. ** buffer space that is separate from the pPage buffer area */
  66410. assert( pCell<pPage->aData || pCell>=&pPage->aData[pPage->pBt->pageSize]
  66411. || sqlite3PagerIswriteable(pPage->pDbPage) );
  66412. /* Fill in the header. */
  66413. nHeader = pPage->childPtrSize;
  66414. if( pPage->intKey ){
  66415. nPayload = pX->nData + pX->nZero;
  66416. pSrc = pX->pData;
  66417. nSrc = pX->nData;
  66418. assert( pPage->intKeyLeaf ); /* fillInCell() only called for leaves */
  66419. nHeader += putVarint32(&pCell[nHeader], nPayload);
  66420. nHeader += putVarint(&pCell[nHeader], *(u64*)&pX->nKey);
  66421. }else{
  66422. assert( pX->nKey<=0x7fffffff && pX->pKey!=0 );
  66423. nSrc = nPayload = (int)pX->nKey;
  66424. pSrc = pX->pKey;
  66425. nHeader += putVarint32(&pCell[nHeader], nPayload);
  66426. }
  66427. /* Fill in the payload */
  66428. pPayload = &pCell[nHeader];
  66429. if( nPayload<=pPage->maxLocal ){
  66430. /* This is the common case where everything fits on the btree page
  66431. ** and no overflow pages are required. */
  66432. n = nHeader + nPayload;
  66433. testcase( n==3 );
  66434. testcase( n==4 );
  66435. if( n<4 ) n = 4;
  66436. *pnSize = n;
  66437. assert( nSrc<=nPayload );
  66438. testcase( nSrc<nPayload );
  66439. memcpy(pPayload, pSrc, nSrc);
  66440. memset(pPayload+nSrc, 0, nPayload-nSrc);
  66441. return SQLITE_OK;
  66442. }
  66443. /* If we reach this point, it means that some of the content will need
  66444. ** to spill onto overflow pages.
  66445. */
  66446. mn = pPage->minLocal;
  66447. n = mn + (nPayload - mn) % (pPage->pBt->usableSize - 4);
  66448. testcase( n==pPage->maxLocal );
  66449. testcase( n==pPage->maxLocal+1 );
  66450. if( n > pPage->maxLocal ) n = mn;
  66451. spaceLeft = n;
  66452. *pnSize = n + nHeader + 4;
  66453. pPrior = &pCell[nHeader+n];
  66454. pToRelease = 0;
  66455. pgnoOvfl = 0;
  66456. pBt = pPage->pBt;
  66457. /* At this point variables should be set as follows:
  66458. **
  66459. ** nPayload Total payload size in bytes
  66460. ** pPayload Begin writing payload here
  66461. ** spaceLeft Space available at pPayload. If nPayload>spaceLeft,
  66462. ** that means content must spill into overflow pages.
  66463. ** *pnSize Size of the local cell (not counting overflow pages)
  66464. ** pPrior Where to write the pgno of the first overflow page
  66465. **
  66466. ** Use a call to btreeParseCellPtr() to verify that the values above
  66467. ** were computed correctly.
  66468. */
  66469. #ifdef SQLITE_DEBUG
  66470. {
  66471. CellInfo info;
  66472. pPage->xParseCell(pPage, pCell, &info);
  66473. assert( nHeader==(int)(info.pPayload - pCell) );
  66474. assert( info.nKey==pX->nKey );
  66475. assert( *pnSize == info.nSize );
  66476. assert( spaceLeft == info.nLocal );
  66477. }
  66478. #endif
  66479. /* Write the payload into the local Cell and any extra into overflow pages */
  66480. while( 1 ){
  66481. n = nPayload;
  66482. if( n>spaceLeft ) n = spaceLeft;
  66483. /* If pToRelease is not zero than pPayload points into the data area
  66484. ** of pToRelease. Make sure pToRelease is still writeable. */
  66485. assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
  66486. /* If pPayload is part of the data area of pPage, then make sure pPage
  66487. ** is still writeable */
  66488. assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
  66489. || sqlite3PagerIswriteable(pPage->pDbPage) );
  66490. if( nSrc>=n ){
  66491. memcpy(pPayload, pSrc, n);
  66492. }else if( nSrc>0 ){
  66493. n = nSrc;
  66494. memcpy(pPayload, pSrc, n);
  66495. }else{
  66496. memset(pPayload, 0, n);
  66497. }
  66498. nPayload -= n;
  66499. if( nPayload<=0 ) break;
  66500. pPayload += n;
  66501. pSrc += n;
  66502. nSrc -= n;
  66503. spaceLeft -= n;
  66504. if( spaceLeft==0 ){
  66505. MemPage *pOvfl = 0;
  66506. #ifndef SQLITE_OMIT_AUTOVACUUM
  66507. Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
  66508. if( pBt->autoVacuum ){
  66509. do{
  66510. pgnoOvfl++;
  66511. } while(
  66512. PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
  66513. );
  66514. }
  66515. #endif
  66516. rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
  66517. #ifndef SQLITE_OMIT_AUTOVACUUM
  66518. /* If the database supports auto-vacuum, and the second or subsequent
  66519. ** overflow page is being allocated, add an entry to the pointer-map
  66520. ** for that page now.
  66521. **
  66522. ** If this is the first overflow page, then write a partial entry
  66523. ** to the pointer-map. If we write nothing to this pointer-map slot,
  66524. ** then the optimistic overflow chain processing in clearCell()
  66525. ** may misinterpret the uninitialized values and delete the
  66526. ** wrong pages from the database.
  66527. */
  66528. if( pBt->autoVacuum && rc==SQLITE_OK ){
  66529. u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
  66530. ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
  66531. if( rc ){
  66532. releasePage(pOvfl);
  66533. }
  66534. }
  66535. #endif
  66536. if( rc ){
  66537. releasePage(pToRelease);
  66538. return rc;
  66539. }
  66540. /* If pToRelease is not zero than pPrior points into the data area
  66541. ** of pToRelease. Make sure pToRelease is still writeable. */
  66542. assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
  66543. /* If pPrior is part of the data area of pPage, then make sure pPage
  66544. ** is still writeable */
  66545. assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
  66546. || sqlite3PagerIswriteable(pPage->pDbPage) );
  66547. put4byte(pPrior, pgnoOvfl);
  66548. releasePage(pToRelease);
  66549. pToRelease = pOvfl;
  66550. pPrior = pOvfl->aData;
  66551. put4byte(pPrior, 0);
  66552. pPayload = &pOvfl->aData[4];
  66553. spaceLeft = pBt->usableSize - 4;
  66554. }
  66555. }
  66556. releasePage(pToRelease);
  66557. return SQLITE_OK;
  66558. }
  66559. /*
  66560. ** Remove the i-th cell from pPage. This routine effects pPage only.
  66561. ** The cell content is not freed or deallocated. It is assumed that
  66562. ** the cell content has been copied someplace else. This routine just
  66563. ** removes the reference to the cell from pPage.
  66564. **
  66565. ** "sz" must be the number of bytes in the cell.
  66566. */
  66567. static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
  66568. u32 pc; /* Offset to cell content of cell being deleted */
  66569. u8 *data; /* pPage->aData */
  66570. u8 *ptr; /* Used to move bytes around within data[] */
  66571. int rc; /* The return code */
  66572. int hdr; /* Beginning of the header. 0 most pages. 100 page 1 */
  66573. if( *pRC ) return;
  66574. assert( idx>=0 && idx<pPage->nCell );
  66575. assert( CORRUPT_DB || sz==cellSize(pPage, idx) );
  66576. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  66577. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  66578. assert( pPage->nFree>=0 );
  66579. data = pPage->aData;
  66580. ptr = &pPage->aCellIdx[2*idx];
  66581. pc = get2byte(ptr);
  66582. hdr = pPage->hdrOffset;
  66583. testcase( pc==get2byte(&data[hdr+5]) );
  66584. testcase( pc+sz==pPage->pBt->usableSize );
  66585. if( pc+sz > pPage->pBt->usableSize ){
  66586. *pRC = SQLITE_CORRUPT_BKPT;
  66587. return;
  66588. }
  66589. rc = freeSpace(pPage, pc, sz);
  66590. if( rc ){
  66591. *pRC = rc;
  66592. return;
  66593. }
  66594. pPage->nCell--;
  66595. if( pPage->nCell==0 ){
  66596. memset(&data[hdr+1], 0, 4);
  66597. data[hdr+7] = 0;
  66598. put2byte(&data[hdr+5], pPage->pBt->usableSize);
  66599. pPage->nFree = pPage->pBt->usableSize - pPage->hdrOffset
  66600. - pPage->childPtrSize - 8;
  66601. }else{
  66602. memmove(ptr, ptr+2, 2*(pPage->nCell - idx));
  66603. put2byte(&data[hdr+3], pPage->nCell);
  66604. pPage->nFree += 2;
  66605. }
  66606. }
  66607. /*
  66608. ** Insert a new cell on pPage at cell index "i". pCell points to the
  66609. ** content of the cell.
  66610. **
  66611. ** If the cell content will fit on the page, then put it there. If it
  66612. ** will not fit, then make a copy of the cell content into pTemp if
  66613. ** pTemp is not null. Regardless of pTemp, allocate a new entry
  66614. ** in pPage->apOvfl[] and make it point to the cell content (either
  66615. ** in pTemp or the original pCell) and also record its index.
  66616. ** Allocating a new entry in pPage->aCell[] implies that
  66617. ** pPage->nOverflow is incremented.
  66618. **
  66619. ** *pRC must be SQLITE_OK when this routine is called.
  66620. */
  66621. static void insertCell(
  66622. MemPage *pPage, /* Page into which we are copying */
  66623. int i, /* New cell becomes the i-th cell of the page */
  66624. u8 *pCell, /* Content of the new cell */
  66625. int sz, /* Bytes of content in pCell */
  66626. u8 *pTemp, /* Temp storage space for pCell, if needed */
  66627. Pgno iChild, /* If non-zero, replace first 4 bytes with this value */
  66628. int *pRC /* Read and write return code from here */
  66629. ){
  66630. int idx = 0; /* Where to write new cell content in data[] */
  66631. int j; /* Loop counter */
  66632. u8 *data; /* The content of the whole page */
  66633. u8 *pIns; /* The point in pPage->aCellIdx[] where no cell inserted */
  66634. assert( *pRC==SQLITE_OK );
  66635. assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
  66636. assert( MX_CELL(pPage->pBt)<=10921 );
  66637. assert( pPage->nCell<=MX_CELL(pPage->pBt) || CORRUPT_DB );
  66638. assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );
  66639. assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );
  66640. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  66641. assert( sz==pPage->xCellSize(pPage, pCell) || CORRUPT_DB );
  66642. assert( pPage->nFree>=0 );
  66643. if( pPage->nOverflow || sz+2>pPage->nFree ){
  66644. if( pTemp ){
  66645. memcpy(pTemp, pCell, sz);
  66646. pCell = pTemp;
  66647. }
  66648. if( iChild ){
  66649. put4byte(pCell, iChild);
  66650. }
  66651. j = pPage->nOverflow++;
  66652. /* Comparison against ArraySize-1 since we hold back one extra slot
  66653. ** as a contingency. In other words, never need more than 3 overflow
  66654. ** slots but 4 are allocated, just to be safe. */
  66655. assert( j < ArraySize(pPage->apOvfl)-1 );
  66656. pPage->apOvfl[j] = pCell;
  66657. pPage->aiOvfl[j] = (u16)i;
  66658. /* When multiple overflows occur, they are always sequential and in
  66659. ** sorted order. This invariants arise because multiple overflows can
  66660. ** only occur when inserting divider cells into the parent page during
  66661. ** balancing, and the dividers are adjacent and sorted.
  66662. */
  66663. assert( j==0 || pPage->aiOvfl[j-1]<(u16)i ); /* Overflows in sorted order */
  66664. assert( j==0 || i==pPage->aiOvfl[j-1]+1 ); /* Overflows are sequential */
  66665. }else{
  66666. int rc = sqlite3PagerWrite(pPage->pDbPage);
  66667. if( rc!=SQLITE_OK ){
  66668. *pRC = rc;
  66669. return;
  66670. }
  66671. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  66672. data = pPage->aData;
  66673. assert( &data[pPage->cellOffset]==pPage->aCellIdx );
  66674. rc = allocateSpace(pPage, sz, &idx);
  66675. if( rc ){ *pRC = rc; return; }
  66676. /* The allocateSpace() routine guarantees the following properties
  66677. ** if it returns successfully */
  66678. assert( idx >= 0 );
  66679. assert( idx >= pPage->cellOffset+2*pPage->nCell+2 || CORRUPT_DB );
  66680. assert( idx+sz <= (int)pPage->pBt->usableSize );
  66681. pPage->nFree -= (u16)(2 + sz);
  66682. if( iChild ){
  66683. /* In a corrupt database where an entry in the cell index section of
  66684. ** a btree page has a value of 3 or less, the pCell value might point
  66685. ** as many as 4 bytes in front of the start of the aData buffer for
  66686. ** the source page. Make sure this does not cause problems by not
  66687. ** reading the first 4 bytes */
  66688. memcpy(&data[idx+4], pCell+4, sz-4);
  66689. put4byte(&data[idx], iChild);
  66690. }else{
  66691. memcpy(&data[idx], pCell, sz);
  66692. }
  66693. pIns = pPage->aCellIdx + i*2;
  66694. memmove(pIns+2, pIns, 2*(pPage->nCell - i));
  66695. put2byte(pIns, idx);
  66696. pPage->nCell++;
  66697. /* increment the cell count */
  66698. if( (++data[pPage->hdrOffset+4])==0 ) data[pPage->hdrOffset+3]++;
  66699. assert( get2byte(&data[pPage->hdrOffset+3])==pPage->nCell || CORRUPT_DB );
  66700. #ifndef SQLITE_OMIT_AUTOVACUUM
  66701. if( pPage->pBt->autoVacuum ){
  66702. /* The cell may contain a pointer to an overflow page. If so, write
  66703. ** the entry for the overflow page into the pointer map.
  66704. */
  66705. ptrmapPutOvflPtr(pPage, pPage, pCell, pRC);
  66706. }
  66707. #endif
  66708. }
  66709. }
  66710. /*
  66711. ** The following parameters determine how many adjacent pages get involved
  66712. ** in a balancing operation. NN is the number of neighbors on either side
  66713. ** of the page that participate in the balancing operation. NB is the
  66714. ** total number of pages that participate, including the target page and
  66715. ** NN neighbors on either side.
  66716. **
  66717. ** The minimum value of NN is 1 (of course). Increasing NN above 1
  66718. ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
  66719. ** in exchange for a larger degradation in INSERT and UPDATE performance.
  66720. ** The value of NN appears to give the best results overall.
  66721. **
  66722. ** (Later:) The description above makes it seem as if these values are
  66723. ** tunable - as if you could change them and recompile and it would all work.
  66724. ** But that is unlikely. NB has been 3 since the inception of SQLite and
  66725. ** we have never tested any other value.
  66726. */
  66727. #define NN 1 /* Number of neighbors on either side of pPage */
  66728. #define NB 3 /* (NN*2+1): Total pages involved in the balance */
  66729. /*
  66730. ** A CellArray object contains a cache of pointers and sizes for a
  66731. ** consecutive sequence of cells that might be held on multiple pages.
  66732. **
  66733. ** The cells in this array are the divider cell or cells from the pParent
  66734. ** page plus up to three child pages. There are a total of nCell cells.
  66735. **
  66736. ** pRef is a pointer to one of the pages that contributes cells. This is
  66737. ** used to access information such as MemPage.intKey and MemPage.pBt->pageSize
  66738. ** which should be common to all pages that contribute cells to this array.
  66739. **
  66740. ** apCell[] and szCell[] hold, respectively, pointers to the start of each
  66741. ** cell and the size of each cell. Some of the apCell[] pointers might refer
  66742. ** to overflow cells. In other words, some apCel[] pointers might not point
  66743. ** to content area of the pages.
  66744. **
  66745. ** A szCell[] of zero means the size of that cell has not yet been computed.
  66746. **
  66747. ** The cells come from as many as four different pages:
  66748. **
  66749. ** -----------
  66750. ** | Parent |
  66751. ** -----------
  66752. ** / | \
  66753. ** / | \
  66754. ** --------- --------- ---------
  66755. ** |Child-1| |Child-2| |Child-3|
  66756. ** --------- --------- ---------
  66757. **
  66758. ** The order of cells is in the array is for an index btree is:
  66759. **
  66760. ** 1. All cells from Child-1 in order
  66761. ** 2. The first divider cell from Parent
  66762. ** 3. All cells from Child-2 in order
  66763. ** 4. The second divider cell from Parent
  66764. ** 5. All cells from Child-3 in order
  66765. **
  66766. ** For a table-btree (with rowids) the items 2 and 4 are empty because
  66767. ** content exists only in leaves and there are no divider cells.
  66768. **
  66769. ** For an index btree, the apEnd[] array holds pointer to the end of page
  66770. ** for Child-1, the Parent, Child-2, the Parent (again), and Child-3,
  66771. ** respectively. The ixNx[] array holds the number of cells contained in
  66772. ** each of these 5 stages, and all stages to the left. Hence:
  66773. **
  66774. ** ixNx[0] = Number of cells in Child-1.
  66775. ** ixNx[1] = Number of cells in Child-1 plus 1 for first divider.
  66776. ** ixNx[2] = Number of cells in Child-1 and Child-2 + 1 for 1st divider.
  66777. ** ixNx[3] = Number of cells in Child-1 and Child-2 + both divider cells
  66778. ** ixNx[4] = Total number of cells.
  66779. **
  66780. ** For a table-btree, the concept is similar, except only apEnd[0]..apEnd[2]
  66781. ** are used and they point to the leaf pages only, and the ixNx value are:
  66782. **
  66783. ** ixNx[0] = Number of cells in Child-1.
  66784. ** ixNx[1] = Number of cells in Child-1 and Child-2.
  66785. ** ixNx[2] = Total number of cells.
  66786. **
  66787. ** Sometimes when deleting, a child page can have zero cells. In those
  66788. ** cases, ixNx[] entries with higher indexes, and the corresponding apEnd[]
  66789. ** entries, shift down. The end result is that each ixNx[] entry should
  66790. ** be larger than the previous
  66791. */
  66792. typedef struct CellArray CellArray;
  66793. struct CellArray {
  66794. int nCell; /* Number of cells in apCell[] */
  66795. MemPage *pRef; /* Reference page */
  66796. u8 **apCell; /* All cells begin balanced */
  66797. u16 *szCell; /* Local size of all cells in apCell[] */
  66798. u8 *apEnd[NB*2]; /* MemPage.aDataEnd values */
  66799. int ixNx[NB*2]; /* Index of at which we move to the next apEnd[] */
  66800. };
  66801. /*
  66802. ** Make sure the cell sizes at idx, idx+1, ..., idx+N-1 have been
  66803. ** computed.
  66804. */
  66805. static void populateCellCache(CellArray *p, int idx, int N){
  66806. assert( idx>=0 && idx+N<=p->nCell );
  66807. while( N>0 ){
  66808. assert( p->apCell[idx]!=0 );
  66809. if( p->szCell[idx]==0 ){
  66810. p->szCell[idx] = p->pRef->xCellSize(p->pRef, p->apCell[idx]);
  66811. }else{
  66812. assert( CORRUPT_DB ||
  66813. p->szCell[idx]==p->pRef->xCellSize(p->pRef, p->apCell[idx]) );
  66814. }
  66815. idx++;
  66816. N--;
  66817. }
  66818. }
  66819. /*
  66820. ** Return the size of the Nth element of the cell array
  66821. */
  66822. static SQLITE_NOINLINE u16 computeCellSize(CellArray *p, int N){
  66823. assert( N>=0 && N<p->nCell );
  66824. assert( p->szCell[N]==0 );
  66825. p->szCell[N] = p->pRef->xCellSize(p->pRef, p->apCell[N]);
  66826. return p->szCell[N];
  66827. }
  66828. static u16 cachedCellSize(CellArray *p, int N){
  66829. assert( N>=0 && N<p->nCell );
  66830. if( p->szCell[N] ) return p->szCell[N];
  66831. return computeCellSize(p, N);
  66832. }
  66833. /*
  66834. ** Array apCell[] contains pointers to nCell b-tree page cells. The
  66835. ** szCell[] array contains the size in bytes of each cell. This function
  66836. ** replaces the current contents of page pPg with the contents of the cell
  66837. ** array.
  66838. **
  66839. ** Some of the cells in apCell[] may currently be stored in pPg. This
  66840. ** function works around problems caused by this by making a copy of any
  66841. ** such cells before overwriting the page data.
  66842. **
  66843. ** The MemPage.nFree field is invalidated by this function. It is the
  66844. ** responsibility of the caller to set it correctly.
  66845. */
  66846. static int rebuildPage(
  66847. CellArray *pCArray, /* Content to be added to page pPg */
  66848. int iFirst, /* First cell in pCArray to use */
  66849. int nCell, /* Final number of cells on page */
  66850. MemPage *pPg /* The page to be reconstructed */
  66851. ){
  66852. const int hdr = pPg->hdrOffset; /* Offset of header on pPg */
  66853. u8 * const aData = pPg->aData; /* Pointer to data for pPg */
  66854. const int usableSize = pPg->pBt->usableSize;
  66855. u8 * const pEnd = &aData[usableSize];
  66856. int i = iFirst; /* Which cell to copy from pCArray*/
  66857. u32 j; /* Start of cell content area */
  66858. int iEnd = i+nCell; /* Loop terminator */
  66859. u8 *pCellptr = pPg->aCellIdx;
  66860. u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
  66861. u8 *pData;
  66862. int k; /* Current slot in pCArray->apEnd[] */
  66863. u8 *pSrcEnd; /* Current pCArray->apEnd[k] value */
  66864. assert( i<iEnd );
  66865. j = get2byte(&aData[hdr+5]);
  66866. if( NEVER(j>(u32)usableSize) ){ j = 0; }
  66867. memcpy(&pTmp[j], &aData[j], usableSize - j);
  66868. for(k=0; pCArray->ixNx[k]<=i && ALWAYS(k<NB*2); k++){}
  66869. pSrcEnd = pCArray->apEnd[k];
  66870. pData = pEnd;
  66871. while( 1/*exit by break*/ ){
  66872. u8 *pCell = pCArray->apCell[i];
  66873. u16 sz = pCArray->szCell[i];
  66874. assert( sz>0 );
  66875. if( SQLITE_WITHIN(pCell,aData,pEnd) ){
  66876. if( ((uptr)(pCell+sz))>(uptr)pEnd ) return SQLITE_CORRUPT_BKPT;
  66877. pCell = &pTmp[pCell - aData];
  66878. }else if( (uptr)(pCell+sz)>(uptr)pSrcEnd
  66879. && (uptr)(pCell)<(uptr)pSrcEnd
  66880. ){
  66881. return SQLITE_CORRUPT_BKPT;
  66882. }
  66883. pData -= sz;
  66884. put2byte(pCellptr, (pData - aData));
  66885. pCellptr += 2;
  66886. if( pData < pCellptr ) return SQLITE_CORRUPT_BKPT;
  66887. memcpy(pData, pCell, sz);
  66888. assert( sz==pPg->xCellSize(pPg, pCell) || CORRUPT_DB );
  66889. testcase( sz!=pPg->xCellSize(pPg,pCell) )
  66890. i++;
  66891. if( i>=iEnd ) break;
  66892. if( pCArray->ixNx[k]<=i ){
  66893. k++;
  66894. pSrcEnd = pCArray->apEnd[k];
  66895. }
  66896. }
  66897. /* The pPg->nFree field is now set incorrectly. The caller will fix it. */
  66898. pPg->nCell = nCell;
  66899. pPg->nOverflow = 0;
  66900. put2byte(&aData[hdr+1], 0);
  66901. put2byte(&aData[hdr+3], pPg->nCell);
  66902. put2byte(&aData[hdr+5], pData - aData);
  66903. aData[hdr+7] = 0x00;
  66904. return SQLITE_OK;
  66905. }
  66906. /*
  66907. ** The pCArray objects contains pointers to b-tree cells and the cell sizes.
  66908. ** This function attempts to add the cells stored in the array to page pPg.
  66909. ** If it cannot (because the page needs to be defragmented before the cells
  66910. ** will fit), non-zero is returned. Otherwise, if the cells are added
  66911. ** successfully, zero is returned.
  66912. **
  66913. ** Argument pCellptr points to the first entry in the cell-pointer array
  66914. ** (part of page pPg) to populate. After cell apCell[0] is written to the
  66915. ** page body, a 16-bit offset is written to pCellptr. And so on, for each
  66916. ** cell in the array. It is the responsibility of the caller to ensure
  66917. ** that it is safe to overwrite this part of the cell-pointer array.
  66918. **
  66919. ** When this function is called, *ppData points to the start of the
  66920. ** content area on page pPg. If the size of the content area is extended,
  66921. ** *ppData is updated to point to the new start of the content area
  66922. ** before returning.
  66923. **
  66924. ** Finally, argument pBegin points to the byte immediately following the
  66925. ** end of the space required by this page for the cell-pointer area (for
  66926. ** all cells - not just those inserted by the current call). If the content
  66927. ** area must be extended to before this point in order to accomodate all
  66928. ** cells in apCell[], then the cells do not fit and non-zero is returned.
  66929. */
  66930. static int pageInsertArray(
  66931. MemPage *pPg, /* Page to add cells to */
  66932. u8 *pBegin, /* End of cell-pointer array */
  66933. u8 **ppData, /* IN/OUT: Page content-area pointer */
  66934. u8 *pCellptr, /* Pointer to cell-pointer area */
  66935. int iFirst, /* Index of first cell to add */
  66936. int nCell, /* Number of cells to add to pPg */
  66937. CellArray *pCArray /* Array of cells */
  66938. ){
  66939. int i = iFirst; /* Loop counter - cell index to insert */
  66940. u8 *aData = pPg->aData; /* Complete page */
  66941. u8 *pData = *ppData; /* Content area. A subset of aData[] */
  66942. int iEnd = iFirst + nCell; /* End of loop. One past last cell to ins */
  66943. int k; /* Current slot in pCArray->apEnd[] */
  66944. u8 *pEnd; /* Maximum extent of cell data */
  66945. assert( CORRUPT_DB || pPg->hdrOffset==0 ); /* Never called on page 1 */
  66946. if( iEnd<=iFirst ) return 0;
  66947. for(k=0; pCArray->ixNx[k]<=i && ALWAYS(k<NB*2); k++){}
  66948. pEnd = pCArray->apEnd[k];
  66949. while( 1 /*Exit by break*/ ){
  66950. int sz, rc;
  66951. u8 *pSlot;
  66952. assert( pCArray->szCell[i]!=0 );
  66953. sz = pCArray->szCell[i];
  66954. if( (aData[1]==0 && aData[2]==0) || (pSlot = pageFindSlot(pPg,sz,&rc))==0 ){
  66955. if( (pData - pBegin)<sz ) return 1;
  66956. pData -= sz;
  66957. pSlot = pData;
  66958. }
  66959. /* pSlot and pCArray->apCell[i] will never overlap on a well-formed
  66960. ** database. But they might for a corrupt database. Hence use memmove()
  66961. ** since memcpy() sends SIGABORT with overlapping buffers on OpenBSD */
  66962. assert( (pSlot+sz)<=pCArray->apCell[i]
  66963. || pSlot>=(pCArray->apCell[i]+sz)
  66964. || CORRUPT_DB );
  66965. if( (uptr)(pCArray->apCell[i]+sz)>(uptr)pEnd
  66966. && (uptr)(pCArray->apCell[i])<(uptr)pEnd
  66967. ){
  66968. assert( CORRUPT_DB );
  66969. (void)SQLITE_CORRUPT_BKPT;
  66970. return 1;
  66971. }
  66972. memmove(pSlot, pCArray->apCell[i], sz);
  66973. put2byte(pCellptr, (pSlot - aData));
  66974. pCellptr += 2;
  66975. i++;
  66976. if( i>=iEnd ) break;
  66977. if( pCArray->ixNx[k]<=i ){
  66978. k++;
  66979. pEnd = pCArray->apEnd[k];
  66980. }
  66981. }
  66982. *ppData = pData;
  66983. return 0;
  66984. }
  66985. /*
  66986. ** The pCArray object contains pointers to b-tree cells and their sizes.
  66987. **
  66988. ** This function adds the space associated with each cell in the array
  66989. ** that is currently stored within the body of pPg to the pPg free-list.
  66990. ** The cell-pointers and other fields of the page are not updated.
  66991. **
  66992. ** This function returns the total number of cells added to the free-list.
  66993. */
  66994. static int pageFreeArray(
  66995. MemPage *pPg, /* Page to edit */
  66996. int iFirst, /* First cell to delete */
  66997. int nCell, /* Cells to delete */
  66998. CellArray *pCArray /* Array of cells */
  66999. ){
  67000. u8 * const aData = pPg->aData;
  67001. u8 * const pEnd = &aData[pPg->pBt->usableSize];
  67002. u8 * const pStart = &aData[pPg->hdrOffset + 8 + pPg->childPtrSize];
  67003. int nRet = 0;
  67004. int i;
  67005. int iEnd = iFirst + nCell;
  67006. u8 *pFree = 0;
  67007. int szFree = 0;
  67008. for(i=iFirst; i<iEnd; i++){
  67009. u8 *pCell = pCArray->apCell[i];
  67010. if( SQLITE_WITHIN(pCell, pStart, pEnd) ){
  67011. int sz;
  67012. /* No need to use cachedCellSize() here. The sizes of all cells that
  67013. ** are to be freed have already been computing while deciding which
  67014. ** cells need freeing */
  67015. sz = pCArray->szCell[i]; assert( sz>0 );
  67016. if( pFree!=(pCell + sz) ){
  67017. if( pFree ){
  67018. assert( pFree>aData && (pFree - aData)<65536 );
  67019. freeSpace(pPg, (u16)(pFree - aData), szFree);
  67020. }
  67021. pFree = pCell;
  67022. szFree = sz;
  67023. if( pFree+sz>pEnd ) return 0;
  67024. }else{
  67025. pFree = pCell;
  67026. szFree += sz;
  67027. }
  67028. nRet++;
  67029. }
  67030. }
  67031. if( pFree ){
  67032. assert( pFree>aData && (pFree - aData)<65536 );
  67033. freeSpace(pPg, (u16)(pFree - aData), szFree);
  67034. }
  67035. return nRet;
  67036. }
  67037. /*
  67038. ** pCArray contains pointers to and sizes of all cells in the page being
  67039. ** balanced. The current page, pPg, has pPg->nCell cells starting with
  67040. ** pCArray->apCell[iOld]. After balancing, this page should hold nNew cells
  67041. ** starting at apCell[iNew].
  67042. **
  67043. ** This routine makes the necessary adjustments to pPg so that it contains
  67044. ** the correct cells after being balanced.
  67045. **
  67046. ** The pPg->nFree field is invalid when this function returns. It is the
  67047. ** responsibility of the caller to set it correctly.
  67048. */
  67049. static int editPage(
  67050. MemPage *pPg, /* Edit this page */
  67051. int iOld, /* Index of first cell currently on page */
  67052. int iNew, /* Index of new first cell on page */
  67053. int nNew, /* Final number of cells on page */
  67054. CellArray *pCArray /* Array of cells and sizes */
  67055. ){
  67056. u8 * const aData = pPg->aData;
  67057. const int hdr = pPg->hdrOffset;
  67058. u8 *pBegin = &pPg->aCellIdx[nNew * 2];
  67059. int nCell = pPg->nCell; /* Cells stored on pPg */
  67060. u8 *pData;
  67061. u8 *pCellptr;
  67062. int i;
  67063. int iOldEnd = iOld + pPg->nCell + pPg->nOverflow;
  67064. int iNewEnd = iNew + nNew;
  67065. #ifdef SQLITE_DEBUG
  67066. u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
  67067. memcpy(pTmp, aData, pPg->pBt->usableSize);
  67068. #endif
  67069. /* Remove cells from the start and end of the page */
  67070. assert( nCell>=0 );
  67071. if( iOld<iNew ){
  67072. int nShift = pageFreeArray(pPg, iOld, iNew-iOld, pCArray);
  67073. if( NEVER(nShift>nCell) ) return SQLITE_CORRUPT_BKPT;
  67074. memmove(pPg->aCellIdx, &pPg->aCellIdx[nShift*2], nCell*2);
  67075. nCell -= nShift;
  67076. }
  67077. if( iNewEnd < iOldEnd ){
  67078. int nTail = pageFreeArray(pPg, iNewEnd, iOldEnd - iNewEnd, pCArray);
  67079. assert( nCell>=nTail );
  67080. nCell -= nTail;
  67081. }
  67082. pData = &aData[get2byteNotZero(&aData[hdr+5])];
  67083. if( pData<pBegin ) goto editpage_fail;
  67084. /* Add cells to the start of the page */
  67085. if( iNew<iOld ){
  67086. int nAdd = MIN(nNew,iOld-iNew);
  67087. assert( (iOld-iNew)<nNew || nCell==0 || CORRUPT_DB );
  67088. assert( nAdd>=0 );
  67089. pCellptr = pPg->aCellIdx;
  67090. memmove(&pCellptr[nAdd*2], pCellptr, nCell*2);
  67091. if( pageInsertArray(
  67092. pPg, pBegin, &pData, pCellptr,
  67093. iNew, nAdd, pCArray
  67094. ) ) goto editpage_fail;
  67095. nCell += nAdd;
  67096. }
  67097. /* Add any overflow cells */
  67098. for(i=0; i<pPg->nOverflow; i++){
  67099. int iCell = (iOld + pPg->aiOvfl[i]) - iNew;
  67100. if( iCell>=0 && iCell<nNew ){
  67101. pCellptr = &pPg->aCellIdx[iCell * 2];
  67102. if( nCell>iCell ){
  67103. memmove(&pCellptr[2], pCellptr, (nCell - iCell) * 2);
  67104. }
  67105. nCell++;
  67106. cachedCellSize(pCArray, iCell+iNew);
  67107. if( pageInsertArray(
  67108. pPg, pBegin, &pData, pCellptr,
  67109. iCell+iNew, 1, pCArray
  67110. ) ) goto editpage_fail;
  67111. }
  67112. }
  67113. /* Append cells to the end of the page */
  67114. assert( nCell>=0 );
  67115. pCellptr = &pPg->aCellIdx[nCell*2];
  67116. if( pageInsertArray(
  67117. pPg, pBegin, &pData, pCellptr,
  67118. iNew+nCell, nNew-nCell, pCArray
  67119. ) ) goto editpage_fail;
  67120. pPg->nCell = nNew;
  67121. pPg->nOverflow = 0;
  67122. put2byte(&aData[hdr+3], pPg->nCell);
  67123. put2byte(&aData[hdr+5], pData - aData);
  67124. #ifdef SQLITE_DEBUG
  67125. for(i=0; i<nNew && !CORRUPT_DB; i++){
  67126. u8 *pCell = pCArray->apCell[i+iNew];
  67127. int iOff = get2byteAligned(&pPg->aCellIdx[i*2]);
  67128. if( SQLITE_WITHIN(pCell, aData, &aData[pPg->pBt->usableSize]) ){
  67129. pCell = &pTmp[pCell - aData];
  67130. }
  67131. assert( 0==memcmp(pCell, &aData[iOff],
  67132. pCArray->pRef->xCellSize(pCArray->pRef, pCArray->apCell[i+iNew])) );
  67133. }
  67134. #endif
  67135. return SQLITE_OK;
  67136. editpage_fail:
  67137. /* Unable to edit this page. Rebuild it from scratch instead. */
  67138. populateCellCache(pCArray, iNew, nNew);
  67139. return rebuildPage(pCArray, iNew, nNew, pPg);
  67140. }
  67141. #ifndef SQLITE_OMIT_QUICKBALANCE
  67142. /*
  67143. ** This version of balance() handles the common special case where
  67144. ** a new entry is being inserted on the extreme right-end of the
  67145. ** tree, in other words, when the new entry will become the largest
  67146. ** entry in the tree.
  67147. **
  67148. ** Instead of trying to balance the 3 right-most leaf pages, just add
  67149. ** a new page to the right-hand side and put the one new entry in
  67150. ** that page. This leaves the right side of the tree somewhat
  67151. ** unbalanced. But odds are that we will be inserting new entries
  67152. ** at the end soon afterwards so the nearly empty page will quickly
  67153. ** fill up. On average.
  67154. **
  67155. ** pPage is the leaf page which is the right-most page in the tree.
  67156. ** pParent is its parent. pPage must have a single overflow entry
  67157. ** which is also the right-most entry on the page.
  67158. **
  67159. ** The pSpace buffer is used to store a temporary copy of the divider
  67160. ** cell that will be inserted into pParent. Such a cell consists of a 4
  67161. ** byte page number followed by a variable length integer. In other
  67162. ** words, at most 13 bytes. Hence the pSpace buffer must be at
  67163. ** least 13 bytes in size.
  67164. */
  67165. static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
  67166. BtShared *const pBt = pPage->pBt; /* B-Tree Database */
  67167. MemPage *pNew; /* Newly allocated page */
  67168. int rc; /* Return Code */
  67169. Pgno pgnoNew; /* Page number of pNew */
  67170. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  67171. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  67172. assert( pPage->nOverflow==1 );
  67173. if( pPage->nCell==0 ) return SQLITE_CORRUPT_BKPT; /* dbfuzz001.test */
  67174. assert( pPage->nFree>=0 );
  67175. assert( pParent->nFree>=0 );
  67176. /* Allocate a new page. This page will become the right-sibling of
  67177. ** pPage. Make the parent page writable, so that the new divider cell
  67178. ** may be inserted. If both these operations are successful, proceed.
  67179. */
  67180. rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
  67181. if( rc==SQLITE_OK ){
  67182. u8 *pOut = &pSpace[4];
  67183. u8 *pCell = pPage->apOvfl[0];
  67184. u16 szCell = pPage->xCellSize(pPage, pCell);
  67185. u8 *pStop;
  67186. CellArray b;
  67187. assert( sqlite3PagerIswriteable(pNew->pDbPage) );
  67188. assert( CORRUPT_DB || pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
  67189. zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
  67190. b.nCell = 1;
  67191. b.pRef = pPage;
  67192. b.apCell = &pCell;
  67193. b.szCell = &szCell;
  67194. b.apEnd[0] = pPage->aDataEnd;
  67195. b.ixNx[0] = 2;
  67196. rc = rebuildPage(&b, 0, 1, pNew);
  67197. if( NEVER(rc) ){
  67198. releasePage(pNew);
  67199. return rc;
  67200. }
  67201. pNew->nFree = pBt->usableSize - pNew->cellOffset - 2 - szCell;
  67202. /* If this is an auto-vacuum database, update the pointer map
  67203. ** with entries for the new page, and any pointer from the
  67204. ** cell on the page to an overflow page. If either of these
  67205. ** operations fails, the return code is set, but the contents
  67206. ** of the parent page are still manipulated by thh code below.
  67207. ** That is Ok, at this point the parent page is guaranteed to
  67208. ** be marked as dirty. Returning an error code will cause a
  67209. ** rollback, undoing any changes made to the parent page.
  67210. */
  67211. if( ISAUTOVACUUM ){
  67212. ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
  67213. if( szCell>pNew->minLocal ){
  67214. ptrmapPutOvflPtr(pNew, pNew, pCell, &rc);
  67215. }
  67216. }
  67217. /* Create a divider cell to insert into pParent. The divider cell
  67218. ** consists of a 4-byte page number (the page number of pPage) and
  67219. ** a variable length key value (which must be the same value as the
  67220. ** largest key on pPage).
  67221. **
  67222. ** To find the largest key value on pPage, first find the right-most
  67223. ** cell on pPage. The first two fields of this cell are the
  67224. ** record-length (a variable length integer at most 32-bits in size)
  67225. ** and the key value (a variable length integer, may have any value).
  67226. ** The first of the while(...) loops below skips over the record-length
  67227. ** field. The second while(...) loop copies the key value from the
  67228. ** cell on pPage into the pSpace buffer.
  67229. */
  67230. pCell = findCell(pPage, pPage->nCell-1);
  67231. pStop = &pCell[9];
  67232. while( (*(pCell++)&0x80) && pCell<pStop );
  67233. pStop = &pCell[9];
  67234. while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
  67235. /* Insert the new divider cell into pParent. */
  67236. if( rc==SQLITE_OK ){
  67237. insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
  67238. 0, pPage->pgno, &rc);
  67239. }
  67240. /* Set the right-child pointer of pParent to point to the new page. */
  67241. put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
  67242. /* Release the reference to the new page. */
  67243. releasePage(pNew);
  67244. }
  67245. return rc;
  67246. }
  67247. #endif /* SQLITE_OMIT_QUICKBALANCE */
  67248. #if 0
  67249. /*
  67250. ** This function does not contribute anything to the operation of SQLite.
  67251. ** it is sometimes activated temporarily while debugging code responsible
  67252. ** for setting pointer-map entries.
  67253. */
  67254. static int ptrmapCheckPages(MemPage **apPage, int nPage){
  67255. int i, j;
  67256. for(i=0; i<nPage; i++){
  67257. Pgno n;
  67258. u8 e;
  67259. MemPage *pPage = apPage[i];
  67260. BtShared *pBt = pPage->pBt;
  67261. assert( pPage->isInit );
  67262. for(j=0; j<pPage->nCell; j++){
  67263. CellInfo info;
  67264. u8 *z;
  67265. z = findCell(pPage, j);
  67266. pPage->xParseCell(pPage, z, &info);
  67267. if( info.nLocal<info.nPayload ){
  67268. Pgno ovfl = get4byte(&z[info.nSize-4]);
  67269. ptrmapGet(pBt, ovfl, &e, &n);
  67270. assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
  67271. }
  67272. if( !pPage->leaf ){
  67273. Pgno child = get4byte(z);
  67274. ptrmapGet(pBt, child, &e, &n);
  67275. assert( n==pPage->pgno && e==PTRMAP_BTREE );
  67276. }
  67277. }
  67278. if( !pPage->leaf ){
  67279. Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  67280. ptrmapGet(pBt, child, &e, &n);
  67281. assert( n==pPage->pgno && e==PTRMAP_BTREE );
  67282. }
  67283. }
  67284. return 1;
  67285. }
  67286. #endif
  67287. /*
  67288. ** This function is used to copy the contents of the b-tree node stored
  67289. ** on page pFrom to page pTo. If page pFrom was not a leaf page, then
  67290. ** the pointer-map entries for each child page are updated so that the
  67291. ** parent page stored in the pointer map is page pTo. If pFrom contained
  67292. ** any cells with overflow page pointers, then the corresponding pointer
  67293. ** map entries are also updated so that the parent page is page pTo.
  67294. **
  67295. ** If pFrom is currently carrying any overflow cells (entries in the
  67296. ** MemPage.apOvfl[] array), they are not copied to pTo.
  67297. **
  67298. ** Before returning, page pTo is reinitialized using btreeInitPage().
  67299. **
  67300. ** The performance of this function is not critical. It is only used by
  67301. ** the balance_shallower() and balance_deeper() procedures, neither of
  67302. ** which are called often under normal circumstances.
  67303. */
  67304. static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
  67305. if( (*pRC)==SQLITE_OK ){
  67306. BtShared * const pBt = pFrom->pBt;
  67307. u8 * const aFrom = pFrom->aData;
  67308. u8 * const aTo = pTo->aData;
  67309. int const iFromHdr = pFrom->hdrOffset;
  67310. int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
  67311. int rc;
  67312. int iData;
  67313. assert( pFrom->isInit );
  67314. assert( pFrom->nFree>=iToHdr );
  67315. assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
  67316. /* Copy the b-tree node content from page pFrom to page pTo. */
  67317. iData = get2byte(&aFrom[iFromHdr+5]);
  67318. memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
  67319. memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
  67320. /* Reinitialize page pTo so that the contents of the MemPage structure
  67321. ** match the new data. The initialization of pTo can actually fail under
  67322. ** fairly obscure circumstances, even though it is a copy of initialized
  67323. ** page pFrom.
  67324. */
  67325. pTo->isInit = 0;
  67326. rc = btreeInitPage(pTo);
  67327. if( rc==SQLITE_OK ) rc = btreeComputeFreeSpace(pTo);
  67328. if( rc!=SQLITE_OK ){
  67329. *pRC = rc;
  67330. return;
  67331. }
  67332. /* If this is an auto-vacuum database, update the pointer-map entries
  67333. ** for any b-tree or overflow pages that pTo now contains the pointers to.
  67334. */
  67335. if( ISAUTOVACUUM ){
  67336. *pRC = setChildPtrmaps(pTo);
  67337. }
  67338. }
  67339. }
  67340. /*
  67341. ** This routine redistributes cells on the iParentIdx'th child of pParent
  67342. ** (hereafter "the page") and up to 2 siblings so that all pages have about the
  67343. ** same amount of free space. Usually a single sibling on either side of the
  67344. ** page are used in the balancing, though both siblings might come from one
  67345. ** side if the page is the first or last child of its parent. If the page
  67346. ** has fewer than 2 siblings (something which can only happen if the page
  67347. ** is a root page or a child of a root page) then all available siblings
  67348. ** participate in the balancing.
  67349. **
  67350. ** The number of siblings of the page might be increased or decreased by
  67351. ** one or two in an effort to keep pages nearly full but not over full.
  67352. **
  67353. ** Note that when this routine is called, some of the cells on the page
  67354. ** might not actually be stored in MemPage.aData[]. This can happen
  67355. ** if the page is overfull. This routine ensures that all cells allocated
  67356. ** to the page and its siblings fit into MemPage.aData[] before returning.
  67357. **
  67358. ** In the course of balancing the page and its siblings, cells may be
  67359. ** inserted into or removed from the parent page (pParent). Doing so
  67360. ** may cause the parent page to become overfull or underfull. If this
  67361. ** happens, it is the responsibility of the caller to invoke the correct
  67362. ** balancing routine to fix this problem (see the balance() routine).
  67363. **
  67364. ** If this routine fails for any reason, it might leave the database
  67365. ** in a corrupted state. So if this routine fails, the database should
  67366. ** be rolled back.
  67367. **
  67368. ** The third argument to this function, aOvflSpace, is a pointer to a
  67369. ** buffer big enough to hold one page. If while inserting cells into the parent
  67370. ** page (pParent) the parent page becomes overfull, this buffer is
  67371. ** used to store the parent's overflow cells. Because this function inserts
  67372. ** a maximum of four divider cells into the parent page, and the maximum
  67373. ** size of a cell stored within an internal node is always less than 1/4
  67374. ** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
  67375. ** enough for all overflow cells.
  67376. **
  67377. ** If aOvflSpace is set to a null pointer, this function returns
  67378. ** SQLITE_NOMEM.
  67379. */
  67380. static int balance_nonroot(
  67381. MemPage *pParent, /* Parent page of siblings being balanced */
  67382. int iParentIdx, /* Index of "the page" in pParent */
  67383. u8 *aOvflSpace, /* page-size bytes of space for parent ovfl */
  67384. int isRoot, /* True if pParent is a root-page */
  67385. int bBulk /* True if this call is part of a bulk load */
  67386. ){
  67387. BtShared *pBt; /* The whole database */
  67388. int nMaxCells = 0; /* Allocated size of apCell, szCell, aFrom. */
  67389. int nNew = 0; /* Number of pages in apNew[] */
  67390. int nOld; /* Number of pages in apOld[] */
  67391. int i, j, k; /* Loop counters */
  67392. int nxDiv; /* Next divider slot in pParent->aCell[] */
  67393. int rc = SQLITE_OK; /* The return code */
  67394. u16 leafCorrection; /* 4 if pPage is a leaf. 0 if not */
  67395. int leafData; /* True if pPage is a leaf of a LEAFDATA tree */
  67396. int usableSpace; /* Bytes in pPage beyond the header */
  67397. int pageFlags; /* Value of pPage->aData[0] */
  67398. int iSpace1 = 0; /* First unused byte of aSpace1[] */
  67399. int iOvflSpace = 0; /* First unused byte of aOvflSpace[] */
  67400. int szScratch; /* Size of scratch memory requested */
  67401. MemPage *apOld[NB]; /* pPage and up to two siblings */
  67402. MemPage *apNew[NB+2]; /* pPage and up to NB siblings after balancing */
  67403. u8 *pRight; /* Location in parent of right-sibling pointer */
  67404. u8 *apDiv[NB-1]; /* Divider cells in pParent */
  67405. int cntNew[NB+2]; /* Index in b.paCell[] of cell after i-th page */
  67406. int cntOld[NB+2]; /* Old index in b.apCell[] */
  67407. int szNew[NB+2]; /* Combined size of cells placed on i-th page */
  67408. u8 *aSpace1; /* Space for copies of dividers cells */
  67409. Pgno pgno; /* Temp var to store a page number in */
  67410. u8 abDone[NB+2]; /* True after i'th new page is populated */
  67411. Pgno aPgno[NB+2]; /* Page numbers of new pages before shuffling */
  67412. Pgno aPgOrder[NB+2]; /* Copy of aPgno[] used for sorting pages */
  67413. u16 aPgFlags[NB+2]; /* flags field of new pages before shuffling */
  67414. CellArray b; /* Parsed information on cells being balanced */
  67415. memset(abDone, 0, sizeof(abDone));
  67416. b.nCell = 0;
  67417. b.apCell = 0;
  67418. pBt = pParent->pBt;
  67419. assert( sqlite3_mutex_held(pBt->mutex) );
  67420. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  67421. /* At this point pParent may have at most one overflow cell. And if
  67422. ** this overflow cell is present, it must be the cell with
  67423. ** index iParentIdx. This scenario comes about when this function
  67424. ** is called (indirectly) from sqlite3BtreeDelete().
  67425. */
  67426. assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
  67427. assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx );
  67428. if( !aOvflSpace ){
  67429. return SQLITE_NOMEM_BKPT;
  67430. }
  67431. assert( pParent->nFree>=0 );
  67432. /* Find the sibling pages to balance. Also locate the cells in pParent
  67433. ** that divide the siblings. An attempt is made to find NN siblings on
  67434. ** either side of pPage. More siblings are taken from one side, however,
  67435. ** if there are fewer than NN siblings on the other side. If pParent
  67436. ** has NB or fewer children then all children of pParent are taken.
  67437. **
  67438. ** This loop also drops the divider cells from the parent page. This
  67439. ** way, the remainder of the function does not have to deal with any
  67440. ** overflow cells in the parent page, since if any existed they will
  67441. ** have already been removed.
  67442. */
  67443. i = pParent->nOverflow + pParent->nCell;
  67444. if( i<2 ){
  67445. nxDiv = 0;
  67446. }else{
  67447. assert( bBulk==0 || bBulk==1 );
  67448. if( iParentIdx==0 ){
  67449. nxDiv = 0;
  67450. }else if( iParentIdx==i ){
  67451. nxDiv = i-2+bBulk;
  67452. }else{
  67453. nxDiv = iParentIdx-1;
  67454. }
  67455. i = 2-bBulk;
  67456. }
  67457. nOld = i+1;
  67458. if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
  67459. pRight = &pParent->aData[pParent->hdrOffset+8];
  67460. }else{
  67461. pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
  67462. }
  67463. pgno = get4byte(pRight);
  67464. while( 1 ){
  67465. rc = getAndInitPage(pBt, pgno, &apOld[i], 0, 0);
  67466. if( rc ){
  67467. memset(apOld, 0, (i+1)*sizeof(MemPage*));
  67468. goto balance_cleanup;
  67469. }
  67470. if( apOld[i]->nFree<0 ){
  67471. rc = btreeComputeFreeSpace(apOld[i]);
  67472. if( rc ){
  67473. memset(apOld, 0, (i)*sizeof(MemPage*));
  67474. goto balance_cleanup;
  67475. }
  67476. }
  67477. if( (i--)==0 ) break;
  67478. if( pParent->nOverflow && i+nxDiv==pParent->aiOvfl[0] ){
  67479. apDiv[i] = pParent->apOvfl[0];
  67480. pgno = get4byte(apDiv[i]);
  67481. szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
  67482. pParent->nOverflow = 0;
  67483. }else{
  67484. apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
  67485. pgno = get4byte(apDiv[i]);
  67486. szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
  67487. /* Drop the cell from the parent page. apDiv[i] still points to
  67488. ** the cell within the parent, even though it has been dropped.
  67489. ** This is safe because dropping a cell only overwrites the first
  67490. ** four bytes of it, and this function does not need the first
  67491. ** four bytes of the divider cell. So the pointer is safe to use
  67492. ** later on.
  67493. **
  67494. ** But not if we are in secure-delete mode. In secure-delete mode,
  67495. ** the dropCell() routine will overwrite the entire cell with zeroes.
  67496. ** In this case, temporarily copy the cell into the aOvflSpace[]
  67497. ** buffer. It will be copied out again as soon as the aSpace[] buffer
  67498. ** is allocated. */
  67499. if( pBt->btsFlags & BTS_FAST_SECURE ){
  67500. int iOff;
  67501. iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
  67502. if( (iOff+szNew[i])>(int)pBt->usableSize ){
  67503. rc = SQLITE_CORRUPT_BKPT;
  67504. memset(apOld, 0, (i+1)*sizeof(MemPage*));
  67505. goto balance_cleanup;
  67506. }else{
  67507. memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
  67508. apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
  67509. }
  67510. }
  67511. dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
  67512. }
  67513. }
  67514. /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
  67515. ** alignment */
  67516. nMaxCells = nOld*(MX_CELL(pBt) + ArraySize(pParent->apOvfl));
  67517. nMaxCells = (nMaxCells + 3)&~3;
  67518. /*
  67519. ** Allocate space for memory structures
  67520. */
  67521. szScratch =
  67522. nMaxCells*sizeof(u8*) /* b.apCell */
  67523. + nMaxCells*sizeof(u16) /* b.szCell */
  67524. + pBt->pageSize; /* aSpace1 */
  67525. assert( szScratch<=7*(int)pBt->pageSize );
  67526. b.apCell = sqlite3StackAllocRaw(0, szScratch );
  67527. if( b.apCell==0 ){
  67528. rc = SQLITE_NOMEM_BKPT;
  67529. goto balance_cleanup;
  67530. }
  67531. b.szCell = (u16*)&b.apCell[nMaxCells];
  67532. aSpace1 = (u8*)&b.szCell[nMaxCells];
  67533. assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
  67534. /*
  67535. ** Load pointers to all cells on sibling pages and the divider cells
  67536. ** into the local b.apCell[] array. Make copies of the divider cells
  67537. ** into space obtained from aSpace1[]. The divider cells have already
  67538. ** been removed from pParent.
  67539. **
  67540. ** If the siblings are on leaf pages, then the child pointers of the
  67541. ** divider cells are stripped from the cells before they are copied
  67542. ** into aSpace1[]. In this way, all cells in b.apCell[] are without
  67543. ** child pointers. If siblings are not leaves, then all cell in
  67544. ** b.apCell[] include child pointers. Either way, all cells in b.apCell[]
  67545. ** are alike.
  67546. **
  67547. ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf.
  67548. ** leafData: 1 if pPage holds key+data and pParent holds only keys.
  67549. */
  67550. b.pRef = apOld[0];
  67551. leafCorrection = b.pRef->leaf*4;
  67552. leafData = b.pRef->intKeyLeaf;
  67553. for(i=0; i<nOld; i++){
  67554. MemPage *pOld = apOld[i];
  67555. int limit = pOld->nCell;
  67556. u8 *aData = pOld->aData;
  67557. u16 maskPage = pOld->maskPage;
  67558. u8 *piCell = aData + pOld->cellOffset;
  67559. u8 *piEnd;
  67560. VVA_ONLY( int nCellAtStart = b.nCell; )
  67561. /* Verify that all sibling pages are of the same "type" (table-leaf,
  67562. ** table-interior, index-leaf, or index-interior).
  67563. */
  67564. if( pOld->aData[0]!=apOld[0]->aData[0] ){
  67565. rc = SQLITE_CORRUPT_BKPT;
  67566. goto balance_cleanup;
  67567. }
  67568. /* Load b.apCell[] with pointers to all cells in pOld. If pOld
  67569. ** contains overflow cells, include them in the b.apCell[] array
  67570. ** in the correct spot.
  67571. **
  67572. ** Note that when there are multiple overflow cells, it is always the
  67573. ** case that they are sequential and adjacent. This invariant arises
  67574. ** because multiple overflows can only occurs when inserting divider
  67575. ** cells into a parent on a prior balance, and divider cells are always
  67576. ** adjacent and are inserted in order. There is an assert() tagged
  67577. ** with "NOTE 1" in the overflow cell insertion loop to prove this
  67578. ** invariant.
  67579. **
  67580. ** This must be done in advance. Once the balance starts, the cell
  67581. ** offset section of the btree page will be overwritten and we will no
  67582. ** long be able to find the cells if a pointer to each cell is not saved
  67583. ** first.
  67584. */
  67585. memset(&b.szCell[b.nCell], 0, sizeof(b.szCell[0])*(limit+pOld->nOverflow));
  67586. if( pOld->nOverflow>0 ){
  67587. if( NEVER(limit<pOld->aiOvfl[0]) ){
  67588. rc = SQLITE_CORRUPT_BKPT;
  67589. goto balance_cleanup;
  67590. }
  67591. limit = pOld->aiOvfl[0];
  67592. for(j=0; j<limit; j++){
  67593. b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));
  67594. piCell += 2;
  67595. b.nCell++;
  67596. }
  67597. for(k=0; k<pOld->nOverflow; k++){
  67598. assert( k==0 || pOld->aiOvfl[k-1]+1==pOld->aiOvfl[k] );/* NOTE 1 */
  67599. b.apCell[b.nCell] = pOld->apOvfl[k];
  67600. b.nCell++;
  67601. }
  67602. }
  67603. piEnd = aData + pOld->cellOffset + 2*pOld->nCell;
  67604. while( piCell<piEnd ){
  67605. assert( b.nCell<nMaxCells );
  67606. b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));
  67607. piCell += 2;
  67608. b.nCell++;
  67609. }
  67610. assert( (b.nCell-nCellAtStart)==(pOld->nCell+pOld->nOverflow) );
  67611. cntOld[i] = b.nCell;
  67612. if( i<nOld-1 && !leafData){
  67613. u16 sz = (u16)szNew[i];
  67614. u8 *pTemp;
  67615. assert( b.nCell<nMaxCells );
  67616. b.szCell[b.nCell] = sz;
  67617. pTemp = &aSpace1[iSpace1];
  67618. iSpace1 += sz;
  67619. assert( sz<=pBt->maxLocal+23 );
  67620. assert( iSpace1 <= (int)pBt->pageSize );
  67621. memcpy(pTemp, apDiv[i], sz);
  67622. b.apCell[b.nCell] = pTemp+leafCorrection;
  67623. assert( leafCorrection==0 || leafCorrection==4 );
  67624. b.szCell[b.nCell] = b.szCell[b.nCell] - leafCorrection;
  67625. if( !pOld->leaf ){
  67626. assert( leafCorrection==0 );
  67627. assert( pOld->hdrOffset==0 );
  67628. /* The right pointer of the child page pOld becomes the left
  67629. ** pointer of the divider cell */
  67630. memcpy(b.apCell[b.nCell], &pOld->aData[8], 4);
  67631. }else{
  67632. assert( leafCorrection==4 );
  67633. while( b.szCell[b.nCell]<4 ){
  67634. /* Do not allow any cells smaller than 4 bytes. If a smaller cell
  67635. ** does exist, pad it with 0x00 bytes. */
  67636. assert( b.szCell[b.nCell]==3 || CORRUPT_DB );
  67637. assert( b.apCell[b.nCell]==&aSpace1[iSpace1-3] || CORRUPT_DB );
  67638. aSpace1[iSpace1++] = 0x00;
  67639. b.szCell[b.nCell]++;
  67640. }
  67641. }
  67642. b.nCell++;
  67643. }
  67644. }
  67645. /*
  67646. ** Figure out the number of pages needed to hold all b.nCell cells.
  67647. ** Store this number in "k". Also compute szNew[] which is the total
  67648. ** size of all cells on the i-th page and cntNew[] which is the index
  67649. ** in b.apCell[] of the cell that divides page i from page i+1.
  67650. ** cntNew[k] should equal b.nCell.
  67651. **
  67652. ** Values computed by this block:
  67653. **
  67654. ** k: The total number of sibling pages
  67655. ** szNew[i]: Spaced used on the i-th sibling page.
  67656. ** cntNew[i]: Index in b.apCell[] and b.szCell[] for the first cell to
  67657. ** the right of the i-th sibling page.
  67658. ** usableSpace: Number of bytes of space available on each sibling.
  67659. **
  67660. */
  67661. usableSpace = pBt->usableSize - 12 + leafCorrection;
  67662. for(i=k=0; i<nOld; i++, k++){
  67663. MemPage *p = apOld[i];
  67664. b.apEnd[k] = p->aDataEnd;
  67665. b.ixNx[k] = cntOld[i];
  67666. if( k && b.ixNx[k]==b.ixNx[k-1] ){
  67667. k--; /* Omit b.ixNx[] entry for child pages with no cells */
  67668. }
  67669. if( !leafData ){
  67670. k++;
  67671. b.apEnd[k] = pParent->aDataEnd;
  67672. b.ixNx[k] = cntOld[i]+1;
  67673. }
  67674. assert( p->nFree>=0 );
  67675. szNew[i] = usableSpace - p->nFree;
  67676. for(j=0; j<p->nOverflow; j++){
  67677. szNew[i] += 2 + p->xCellSize(p, p->apOvfl[j]);
  67678. }
  67679. cntNew[i] = cntOld[i];
  67680. }
  67681. k = nOld;
  67682. for(i=0; i<k; i++){
  67683. int sz;
  67684. while( szNew[i]>usableSpace ){
  67685. if( i+1>=k ){
  67686. k = i+2;
  67687. if( k>NB+2 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
  67688. szNew[k-1] = 0;
  67689. cntNew[k-1] = b.nCell;
  67690. }
  67691. sz = 2 + cachedCellSize(&b, cntNew[i]-1);
  67692. szNew[i] -= sz;
  67693. if( !leafData ){
  67694. if( cntNew[i]<b.nCell ){
  67695. sz = 2 + cachedCellSize(&b, cntNew[i]);
  67696. }else{
  67697. sz = 0;
  67698. }
  67699. }
  67700. szNew[i+1] += sz;
  67701. cntNew[i]--;
  67702. }
  67703. while( cntNew[i]<b.nCell ){
  67704. sz = 2 + cachedCellSize(&b, cntNew[i]);
  67705. if( szNew[i]+sz>usableSpace ) break;
  67706. szNew[i] += sz;
  67707. cntNew[i]++;
  67708. if( !leafData ){
  67709. if( cntNew[i]<b.nCell ){
  67710. sz = 2 + cachedCellSize(&b, cntNew[i]);
  67711. }else{
  67712. sz = 0;
  67713. }
  67714. }
  67715. szNew[i+1] -= sz;
  67716. }
  67717. if( cntNew[i]>=b.nCell ){
  67718. k = i+1;
  67719. }else if( cntNew[i] <= (i>0 ? cntNew[i-1] : 0) ){
  67720. rc = SQLITE_CORRUPT_BKPT;
  67721. goto balance_cleanup;
  67722. }
  67723. }
  67724. /*
  67725. ** The packing computed by the previous block is biased toward the siblings
  67726. ** on the left side (siblings with smaller keys). The left siblings are
  67727. ** always nearly full, while the right-most sibling might be nearly empty.
  67728. ** The next block of code attempts to adjust the packing of siblings to
  67729. ** get a better balance.
  67730. **
  67731. ** This adjustment is more than an optimization. The packing above might
  67732. ** be so out of balance as to be illegal. For example, the right-most
  67733. ** sibling might be completely empty. This adjustment is not optional.
  67734. */
  67735. for(i=k-1; i>0; i--){
  67736. int szRight = szNew[i]; /* Size of sibling on the right */
  67737. int szLeft = szNew[i-1]; /* Size of sibling on the left */
  67738. int r; /* Index of right-most cell in left sibling */
  67739. int d; /* Index of first cell to the left of right sibling */
  67740. r = cntNew[i-1] - 1;
  67741. d = r + 1 - leafData;
  67742. (void)cachedCellSize(&b, d);
  67743. do{
  67744. assert( d<nMaxCells );
  67745. assert( r<nMaxCells );
  67746. (void)cachedCellSize(&b, r);
  67747. if( szRight!=0
  67748. && (bBulk || szRight+b.szCell[d]+2 > szLeft-(b.szCell[r]+(i==k-1?0:2)))){
  67749. break;
  67750. }
  67751. szRight += b.szCell[d] + 2;
  67752. szLeft -= b.szCell[r] + 2;
  67753. cntNew[i-1] = r;
  67754. r--;
  67755. d--;
  67756. }while( r>=0 );
  67757. szNew[i] = szRight;
  67758. szNew[i-1] = szLeft;
  67759. if( cntNew[i-1] <= (i>1 ? cntNew[i-2] : 0) ){
  67760. rc = SQLITE_CORRUPT_BKPT;
  67761. goto balance_cleanup;
  67762. }
  67763. }
  67764. /* Sanity check: For a non-corrupt database file one of the follwing
  67765. ** must be true:
  67766. ** (1) We found one or more cells (cntNew[0])>0), or
  67767. ** (2) pPage is a virtual root page. A virtual root page is when
  67768. ** the real root page is page 1 and we are the only child of
  67769. ** that page.
  67770. */
  67771. assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) || CORRUPT_DB);
  67772. TRACE(("BALANCE: old: %d(nc=%d) %d(nc=%d) %d(nc=%d)\n",
  67773. apOld[0]->pgno, apOld[0]->nCell,
  67774. nOld>=2 ? apOld[1]->pgno : 0, nOld>=2 ? apOld[1]->nCell : 0,
  67775. nOld>=3 ? apOld[2]->pgno : 0, nOld>=3 ? apOld[2]->nCell : 0
  67776. ));
  67777. /*
  67778. ** Allocate k new pages. Reuse old pages where possible.
  67779. */
  67780. pageFlags = apOld[0]->aData[0];
  67781. for(i=0; i<k; i++){
  67782. MemPage *pNew;
  67783. if( i<nOld ){
  67784. pNew = apNew[i] = apOld[i];
  67785. apOld[i] = 0;
  67786. rc = sqlite3PagerWrite(pNew->pDbPage);
  67787. nNew++;
  67788. if( rc ) goto balance_cleanup;
  67789. }else{
  67790. assert( i>0 );
  67791. rc = allocateBtreePage(pBt, &pNew, &pgno, (bBulk ? 1 : pgno), 0);
  67792. if( rc ) goto balance_cleanup;
  67793. zeroPage(pNew, pageFlags);
  67794. apNew[i] = pNew;
  67795. nNew++;
  67796. cntOld[i] = b.nCell;
  67797. /* Set the pointer-map entry for the new sibling page. */
  67798. if( ISAUTOVACUUM ){
  67799. ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
  67800. if( rc!=SQLITE_OK ){
  67801. goto balance_cleanup;
  67802. }
  67803. }
  67804. }
  67805. }
  67806. /*
  67807. ** Reassign page numbers so that the new pages are in ascending order.
  67808. ** This helps to keep entries in the disk file in order so that a scan
  67809. ** of the table is closer to a linear scan through the file. That in turn
  67810. ** helps the operating system to deliver pages from the disk more rapidly.
  67811. **
  67812. ** An O(n^2) insertion sort algorithm is used, but since n is never more
  67813. ** than (NB+2) (a small constant), that should not be a problem.
  67814. **
  67815. ** When NB==3, this one optimization makes the database about 25% faster
  67816. ** for large insertions and deletions.
  67817. */
  67818. for(i=0; i<nNew; i++){
  67819. aPgOrder[i] = aPgno[i] = apNew[i]->pgno;
  67820. aPgFlags[i] = apNew[i]->pDbPage->flags;
  67821. for(j=0; j<i; j++){
  67822. if( aPgno[j]==aPgno[i] ){
  67823. /* This branch is taken if the set of sibling pages somehow contains
  67824. ** duplicate entries. This can happen if the database is corrupt.
  67825. ** It would be simpler to detect this as part of the loop below, but
  67826. ** we do the detection here in order to avoid populating the pager
  67827. ** cache with two separate objects associated with the same
  67828. ** page number. */
  67829. assert( CORRUPT_DB );
  67830. rc = SQLITE_CORRUPT_BKPT;
  67831. goto balance_cleanup;
  67832. }
  67833. }
  67834. }
  67835. for(i=0; i<nNew; i++){
  67836. int iBest = 0; /* aPgno[] index of page number to use */
  67837. for(j=1; j<nNew; j++){
  67838. if( aPgOrder[j]<aPgOrder[iBest] ) iBest = j;
  67839. }
  67840. pgno = aPgOrder[iBest];
  67841. aPgOrder[iBest] = 0xffffffff;
  67842. if( iBest!=i ){
  67843. if( iBest>i ){
  67844. sqlite3PagerRekey(apNew[iBest]->pDbPage, pBt->nPage+iBest+1, 0);
  67845. }
  67846. sqlite3PagerRekey(apNew[i]->pDbPage, pgno, aPgFlags[iBest]);
  67847. apNew[i]->pgno = pgno;
  67848. }
  67849. }
  67850. TRACE(("BALANCE: new: %d(%d nc=%d) %d(%d nc=%d) %d(%d nc=%d) "
  67851. "%d(%d nc=%d) %d(%d nc=%d)\n",
  67852. apNew[0]->pgno, szNew[0], cntNew[0],
  67853. nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
  67854. nNew>=2 ? cntNew[1] - cntNew[0] - !leafData : 0,
  67855. nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
  67856. nNew>=3 ? cntNew[2] - cntNew[1] - !leafData : 0,
  67857. nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
  67858. nNew>=4 ? cntNew[3] - cntNew[2] - !leafData : 0,
  67859. nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0,
  67860. nNew>=5 ? cntNew[4] - cntNew[3] - !leafData : 0
  67861. ));
  67862. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  67863. assert( nNew>=1 && nNew<=ArraySize(apNew) );
  67864. assert( apNew[nNew-1]!=0 );
  67865. put4byte(pRight, apNew[nNew-1]->pgno);
  67866. /* If the sibling pages are not leaves, ensure that the right-child pointer
  67867. ** of the right-most new sibling page is set to the value that was
  67868. ** originally in the same field of the right-most old sibling page. */
  67869. if( (pageFlags & PTF_LEAF)==0 && nOld!=nNew ){
  67870. MemPage *pOld = (nNew>nOld ? apNew : apOld)[nOld-1];
  67871. memcpy(&apNew[nNew-1]->aData[8], &pOld->aData[8], 4);
  67872. }
  67873. /* Make any required updates to pointer map entries associated with
  67874. ** cells stored on sibling pages following the balance operation. Pointer
  67875. ** map entries associated with divider cells are set by the insertCell()
  67876. ** routine. The associated pointer map entries are:
  67877. **
  67878. ** a) if the cell contains a reference to an overflow chain, the
  67879. ** entry associated with the first page in the overflow chain, and
  67880. **
  67881. ** b) if the sibling pages are not leaves, the child page associated
  67882. ** with the cell.
  67883. **
  67884. ** If the sibling pages are not leaves, then the pointer map entry
  67885. ** associated with the right-child of each sibling may also need to be
  67886. ** updated. This happens below, after the sibling pages have been
  67887. ** populated, not here.
  67888. */
  67889. if( ISAUTOVACUUM ){
  67890. MemPage *pOld;
  67891. MemPage *pNew = pOld = apNew[0];
  67892. int cntOldNext = pNew->nCell + pNew->nOverflow;
  67893. int iNew = 0;
  67894. int iOld = 0;
  67895. for(i=0; i<b.nCell; i++){
  67896. u8 *pCell = b.apCell[i];
  67897. while( i==cntOldNext ){
  67898. iOld++;
  67899. assert( iOld<nNew || iOld<nOld );
  67900. assert( iOld>=0 && iOld<NB );
  67901. pOld = iOld<nNew ? apNew[iOld] : apOld[iOld];
  67902. cntOldNext += pOld->nCell + pOld->nOverflow + !leafData;
  67903. }
  67904. if( i==cntNew[iNew] ){
  67905. pNew = apNew[++iNew];
  67906. if( !leafData ) continue;
  67907. }
  67908. /* Cell pCell is destined for new sibling page pNew. Originally, it
  67909. ** was either part of sibling page iOld (possibly an overflow cell),
  67910. ** or else the divider cell to the left of sibling page iOld. So,
  67911. ** if sibling page iOld had the same page number as pNew, and if
  67912. ** pCell really was a part of sibling page iOld (not a divider or
  67913. ** overflow cell), we can skip updating the pointer map entries. */
  67914. if( iOld>=nNew
  67915. || pNew->pgno!=aPgno[iOld]
  67916. || !SQLITE_WITHIN(pCell,pOld->aData,pOld->aDataEnd)
  67917. ){
  67918. if( !leafCorrection ){
  67919. ptrmapPut(pBt, get4byte(pCell), PTRMAP_BTREE, pNew->pgno, &rc);
  67920. }
  67921. if( cachedCellSize(&b,i)>pNew->minLocal ){
  67922. ptrmapPutOvflPtr(pNew, pOld, pCell, &rc);
  67923. }
  67924. if( rc ) goto balance_cleanup;
  67925. }
  67926. }
  67927. }
  67928. /* Insert new divider cells into pParent. */
  67929. for(i=0; i<nNew-1; i++){
  67930. u8 *pCell;
  67931. u8 *pTemp;
  67932. int sz;
  67933. MemPage *pNew = apNew[i];
  67934. j = cntNew[i];
  67935. assert( j<nMaxCells );
  67936. assert( b.apCell[j]!=0 );
  67937. pCell = b.apCell[j];
  67938. sz = b.szCell[j] + leafCorrection;
  67939. pTemp = &aOvflSpace[iOvflSpace];
  67940. if( !pNew->leaf ){
  67941. memcpy(&pNew->aData[8], pCell, 4);
  67942. }else if( leafData ){
  67943. /* If the tree is a leaf-data tree, and the siblings are leaves,
  67944. ** then there is no divider cell in b.apCell[]. Instead, the divider
  67945. ** cell consists of the integer key for the right-most cell of
  67946. ** the sibling-page assembled above only.
  67947. */
  67948. CellInfo info;
  67949. j--;
  67950. pNew->xParseCell(pNew, b.apCell[j], &info);
  67951. pCell = pTemp;
  67952. sz = 4 + putVarint(&pCell[4], info.nKey);
  67953. pTemp = 0;
  67954. }else{
  67955. pCell -= 4;
  67956. /* Obscure case for non-leaf-data trees: If the cell at pCell was
  67957. ** previously stored on a leaf node, and its reported size was 4
  67958. ** bytes, then it may actually be smaller than this
  67959. ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
  67960. ** any cell). But it is important to pass the correct size to
  67961. ** insertCell(), so reparse the cell now.
  67962. **
  67963. ** This can only happen for b-trees used to evaluate "IN (SELECT ...)"
  67964. ** and WITHOUT ROWID tables with exactly one column which is the
  67965. ** primary key.
  67966. */
  67967. if( b.szCell[j]==4 ){
  67968. assert(leafCorrection==4);
  67969. sz = pParent->xCellSize(pParent, pCell);
  67970. }
  67971. }
  67972. iOvflSpace += sz;
  67973. assert( sz<=pBt->maxLocal+23 );
  67974. assert( iOvflSpace <= (int)pBt->pageSize );
  67975. insertCell(pParent, nxDiv+i, pCell, sz, pTemp, pNew->pgno, &rc);
  67976. if( rc!=SQLITE_OK ) goto balance_cleanup;
  67977. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  67978. }
  67979. /* Now update the actual sibling pages. The order in which they are updated
  67980. ** is important, as this code needs to avoid disrupting any page from which
  67981. ** cells may still to be read. In practice, this means:
  67982. **
  67983. ** (1) If cells are moving left (from apNew[iPg] to apNew[iPg-1])
  67984. ** then it is not safe to update page apNew[iPg] until after
  67985. ** the left-hand sibling apNew[iPg-1] has been updated.
  67986. **
  67987. ** (2) If cells are moving right (from apNew[iPg] to apNew[iPg+1])
  67988. ** then it is not safe to update page apNew[iPg] until after
  67989. ** the right-hand sibling apNew[iPg+1] has been updated.
  67990. **
  67991. ** If neither of the above apply, the page is safe to update.
  67992. **
  67993. ** The iPg value in the following loop starts at nNew-1 goes down
  67994. ** to 0, then back up to nNew-1 again, thus making two passes over
  67995. ** the pages. On the initial downward pass, only condition (1) above
  67996. ** needs to be tested because (2) will always be true from the previous
  67997. ** step. On the upward pass, both conditions are always true, so the
  67998. ** upwards pass simply processes pages that were missed on the downward
  67999. ** pass.
  68000. */
  68001. for(i=1-nNew; i<nNew; i++){
  68002. int iPg = i<0 ? -i : i;
  68003. assert( iPg>=0 && iPg<nNew );
  68004. if( abDone[iPg] ) continue; /* Skip pages already processed */
  68005. if( i>=0 /* On the upwards pass, or... */
  68006. || cntOld[iPg-1]>=cntNew[iPg-1] /* Condition (1) is true */
  68007. ){
  68008. int iNew;
  68009. int iOld;
  68010. int nNewCell;
  68011. /* Verify condition (1): If cells are moving left, update iPg
  68012. ** only after iPg-1 has already been updated. */
  68013. assert( iPg==0 || cntOld[iPg-1]>=cntNew[iPg-1] || abDone[iPg-1] );
  68014. /* Verify condition (2): If cells are moving right, update iPg
  68015. ** only after iPg+1 has already been updated. */
  68016. assert( cntNew[iPg]>=cntOld[iPg] || abDone[iPg+1] );
  68017. if( iPg==0 ){
  68018. iNew = iOld = 0;
  68019. nNewCell = cntNew[0];
  68020. }else{
  68021. iOld = iPg<nOld ? (cntOld[iPg-1] + !leafData) : b.nCell;
  68022. iNew = cntNew[iPg-1] + !leafData;
  68023. nNewCell = cntNew[iPg] - iNew;
  68024. }
  68025. rc = editPage(apNew[iPg], iOld, iNew, nNewCell, &b);
  68026. if( rc ) goto balance_cleanup;
  68027. abDone[iPg]++;
  68028. apNew[iPg]->nFree = usableSpace-szNew[iPg];
  68029. assert( apNew[iPg]->nOverflow==0 );
  68030. assert( apNew[iPg]->nCell==nNewCell );
  68031. }
  68032. }
  68033. /* All pages have been processed exactly once */
  68034. assert( memcmp(abDone, "\01\01\01\01\01", nNew)==0 );
  68035. assert( nOld>0 );
  68036. assert( nNew>0 );
  68037. if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
  68038. /* The root page of the b-tree now contains no cells. The only sibling
  68039. ** page is the right-child of the parent. Copy the contents of the
  68040. ** child page into the parent, decreasing the overall height of the
  68041. ** b-tree structure by one. This is described as the "balance-shallower"
  68042. ** sub-algorithm in some documentation.
  68043. **
  68044. ** If this is an auto-vacuum database, the call to copyNodeContent()
  68045. ** sets all pointer-map entries corresponding to database image pages
  68046. ** for which the pointer is stored within the content being copied.
  68047. **
  68048. ** It is critical that the child page be defragmented before being
  68049. ** copied into the parent, because if the parent is page 1 then it will
  68050. ** by smaller than the child due to the database header, and so all the
  68051. ** free space needs to be up front.
  68052. */
  68053. assert( nNew==1 || CORRUPT_DB );
  68054. rc = defragmentPage(apNew[0], -1);
  68055. testcase( rc!=SQLITE_OK );
  68056. assert( apNew[0]->nFree ==
  68057. (get2byteNotZero(&apNew[0]->aData[5]) - apNew[0]->cellOffset
  68058. - apNew[0]->nCell*2)
  68059. || rc!=SQLITE_OK
  68060. );
  68061. copyNodeContent(apNew[0], pParent, &rc);
  68062. freePage(apNew[0], &rc);
  68063. }else if( ISAUTOVACUUM && !leafCorrection ){
  68064. /* Fix the pointer map entries associated with the right-child of each
  68065. ** sibling page. All other pointer map entries have already been taken
  68066. ** care of. */
  68067. for(i=0; i<nNew; i++){
  68068. u32 key = get4byte(&apNew[i]->aData[8]);
  68069. ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
  68070. }
  68071. }
  68072. assert( pParent->isInit );
  68073. TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
  68074. nOld, nNew, b.nCell));
  68075. /* Free any old pages that were not reused as new pages.
  68076. */
  68077. for(i=nNew; i<nOld; i++){
  68078. freePage(apOld[i], &rc);
  68079. }
  68080. #if 0
  68081. if( ISAUTOVACUUM && rc==SQLITE_OK && apNew[0]->isInit ){
  68082. /* The ptrmapCheckPages() contains assert() statements that verify that
  68083. ** all pointer map pages are set correctly. This is helpful while
  68084. ** debugging. This is usually disabled because a corrupt database may
  68085. ** cause an assert() statement to fail. */
  68086. ptrmapCheckPages(apNew, nNew);
  68087. ptrmapCheckPages(&pParent, 1);
  68088. }
  68089. #endif
  68090. /*
  68091. ** Cleanup before returning.
  68092. */
  68093. balance_cleanup:
  68094. sqlite3StackFree(0, b.apCell);
  68095. for(i=0; i<nOld; i++){
  68096. releasePage(apOld[i]);
  68097. }
  68098. for(i=0; i<nNew; i++){
  68099. releasePage(apNew[i]);
  68100. }
  68101. return rc;
  68102. }
  68103. /*
  68104. ** This function is called when the root page of a b-tree structure is
  68105. ** overfull (has one or more overflow pages).
  68106. **
  68107. ** A new child page is allocated and the contents of the current root
  68108. ** page, including overflow cells, are copied into the child. The root
  68109. ** page is then overwritten to make it an empty page with the right-child
  68110. ** pointer pointing to the new page.
  68111. **
  68112. ** Before returning, all pointer-map entries corresponding to pages
  68113. ** that the new child-page now contains pointers to are updated. The
  68114. ** entry corresponding to the new right-child pointer of the root
  68115. ** page is also updated.
  68116. **
  68117. ** If successful, *ppChild is set to contain a reference to the child
  68118. ** page and SQLITE_OK is returned. In this case the caller is required
  68119. ** to call releasePage() on *ppChild exactly once. If an error occurs,
  68120. ** an error code is returned and *ppChild is set to 0.
  68121. */
  68122. static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
  68123. int rc; /* Return value from subprocedures */
  68124. MemPage *pChild = 0; /* Pointer to a new child page */
  68125. Pgno pgnoChild = 0; /* Page number of the new child page */
  68126. BtShared *pBt = pRoot->pBt; /* The BTree */
  68127. assert( pRoot->nOverflow>0 );
  68128. assert( sqlite3_mutex_held(pBt->mutex) );
  68129. /* Make pRoot, the root page of the b-tree, writable. Allocate a new
  68130. ** page that will become the new right-child of pPage. Copy the contents
  68131. ** of the node stored on pRoot into the new child page.
  68132. */
  68133. rc = sqlite3PagerWrite(pRoot->pDbPage);
  68134. if( rc==SQLITE_OK ){
  68135. rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
  68136. copyNodeContent(pRoot, pChild, &rc);
  68137. if( ISAUTOVACUUM ){
  68138. ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
  68139. }
  68140. }
  68141. if( rc ){
  68142. *ppChild = 0;
  68143. releasePage(pChild);
  68144. return rc;
  68145. }
  68146. assert( sqlite3PagerIswriteable(pChild->pDbPage) );
  68147. assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
  68148. assert( pChild->nCell==pRoot->nCell || CORRUPT_DB );
  68149. TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
  68150. /* Copy the overflow cells from pRoot to pChild */
  68151. memcpy(pChild->aiOvfl, pRoot->aiOvfl,
  68152. pRoot->nOverflow*sizeof(pRoot->aiOvfl[0]));
  68153. memcpy(pChild->apOvfl, pRoot->apOvfl,
  68154. pRoot->nOverflow*sizeof(pRoot->apOvfl[0]));
  68155. pChild->nOverflow = pRoot->nOverflow;
  68156. /* Zero the contents of pRoot. Then install pChild as the right-child. */
  68157. zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
  68158. put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
  68159. *ppChild = pChild;
  68160. return SQLITE_OK;
  68161. }
  68162. /*
  68163. ** Return SQLITE_CORRUPT if any cursor other than pCur is currently valid
  68164. ** on the same B-tree as pCur.
  68165. **
  68166. ** This can if a database is corrupt with two or more SQL tables
  68167. ** pointing to the same b-tree. If an insert occurs on one SQL table
  68168. ** and causes a BEFORE TRIGGER to do a secondary insert on the other SQL
  68169. ** table linked to the same b-tree. If the secondary insert causes a
  68170. ** rebalance, that can change content out from under the cursor on the
  68171. ** first SQL table, violating invariants on the first insert.
  68172. */
  68173. static int anotherValidCursor(BtCursor *pCur){
  68174. BtCursor *pOther;
  68175. for(pOther=pCur->pBt->pCursor; pOther; pOther=pOther->pNext){
  68176. if( pOther!=pCur
  68177. && pOther->eState==CURSOR_VALID
  68178. && pOther->pPage==pCur->pPage
  68179. ){
  68180. return SQLITE_CORRUPT_BKPT;
  68181. }
  68182. }
  68183. return SQLITE_OK;
  68184. }
  68185. /*
  68186. ** The page that pCur currently points to has just been modified in
  68187. ** some way. This function figures out if this modification means the
  68188. ** tree needs to be balanced, and if so calls the appropriate balancing
  68189. ** routine. Balancing routines are:
  68190. **
  68191. ** balance_quick()
  68192. ** balance_deeper()
  68193. ** balance_nonroot()
  68194. */
  68195. static int balance(BtCursor *pCur){
  68196. int rc = SQLITE_OK;
  68197. const int nMin = pCur->pBt->usableSize * 2 / 3;
  68198. u8 aBalanceQuickSpace[13];
  68199. u8 *pFree = 0;
  68200. VVA_ONLY( int balance_quick_called = 0 );
  68201. VVA_ONLY( int balance_deeper_called = 0 );
  68202. do {
  68203. int iPage;
  68204. MemPage *pPage = pCur->pPage;
  68205. if( NEVER(pPage->nFree<0) && btreeComputeFreeSpace(pPage) ) break;
  68206. if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
  68207. break;
  68208. }else if( (iPage = pCur->iPage)==0 ){
  68209. if( pPage->nOverflow && (rc = anotherValidCursor(pCur))==SQLITE_OK ){
  68210. /* The root page of the b-tree is overfull. In this case call the
  68211. ** balance_deeper() function to create a new child for the root-page
  68212. ** and copy the current contents of the root-page to it. The
  68213. ** next iteration of the do-loop will balance the child page.
  68214. */
  68215. assert( balance_deeper_called==0 );
  68216. VVA_ONLY( balance_deeper_called++ );
  68217. rc = balance_deeper(pPage, &pCur->apPage[1]);
  68218. if( rc==SQLITE_OK ){
  68219. pCur->iPage = 1;
  68220. pCur->ix = 0;
  68221. pCur->aiIdx[0] = 0;
  68222. pCur->apPage[0] = pPage;
  68223. pCur->pPage = pCur->apPage[1];
  68224. assert( pCur->pPage->nOverflow );
  68225. }
  68226. }else{
  68227. break;
  68228. }
  68229. }else{
  68230. MemPage * const pParent = pCur->apPage[iPage-1];
  68231. int const iIdx = pCur->aiIdx[iPage-1];
  68232. rc = sqlite3PagerWrite(pParent->pDbPage);
  68233. if( rc==SQLITE_OK && pParent->nFree<0 ){
  68234. rc = btreeComputeFreeSpace(pParent);
  68235. }
  68236. if( rc==SQLITE_OK ){
  68237. #ifndef SQLITE_OMIT_QUICKBALANCE
  68238. if( pPage->intKeyLeaf
  68239. && pPage->nOverflow==1
  68240. && pPage->aiOvfl[0]==pPage->nCell
  68241. && pParent->pgno!=1
  68242. && pParent->nCell==iIdx
  68243. ){
  68244. /* Call balance_quick() to create a new sibling of pPage on which
  68245. ** to store the overflow cell. balance_quick() inserts a new cell
  68246. ** into pParent, which may cause pParent overflow. If this
  68247. ** happens, the next iteration of the do-loop will balance pParent
  68248. ** use either balance_nonroot() or balance_deeper(). Until this
  68249. ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
  68250. ** buffer.
  68251. **
  68252. ** The purpose of the following assert() is to check that only a
  68253. ** single call to balance_quick() is made for each call to this
  68254. ** function. If this were not verified, a subtle bug involving reuse
  68255. ** of the aBalanceQuickSpace[] might sneak in.
  68256. */
  68257. assert( balance_quick_called==0 );
  68258. VVA_ONLY( balance_quick_called++ );
  68259. rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
  68260. }else
  68261. #endif
  68262. {
  68263. /* In this case, call balance_nonroot() to redistribute cells
  68264. ** between pPage and up to 2 of its sibling pages. This involves
  68265. ** modifying the contents of pParent, which may cause pParent to
  68266. ** become overfull or underfull. The next iteration of the do-loop
  68267. ** will balance the parent page to correct this.
  68268. **
  68269. ** If the parent page becomes overfull, the overflow cell or cells
  68270. ** are stored in the pSpace buffer allocated immediately below.
  68271. ** A subsequent iteration of the do-loop will deal with this by
  68272. ** calling balance_nonroot() (balance_deeper() may be called first,
  68273. ** but it doesn't deal with overflow cells - just moves them to a
  68274. ** different page). Once this subsequent call to balance_nonroot()
  68275. ** has completed, it is safe to release the pSpace buffer used by
  68276. ** the previous call, as the overflow cell data will have been
  68277. ** copied either into the body of a database page or into the new
  68278. ** pSpace buffer passed to the latter call to balance_nonroot().
  68279. */
  68280. u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
  68281. rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1,
  68282. pCur->hints&BTREE_BULKLOAD);
  68283. if( pFree ){
  68284. /* If pFree is not NULL, it points to the pSpace buffer used
  68285. ** by a previous call to balance_nonroot(). Its contents are
  68286. ** now stored either on real database pages or within the
  68287. ** new pSpace buffer, so it may be safely freed here. */
  68288. sqlite3PageFree(pFree);
  68289. }
  68290. /* The pSpace buffer will be freed after the next call to
  68291. ** balance_nonroot(), or just before this function returns, whichever
  68292. ** comes first. */
  68293. pFree = pSpace;
  68294. }
  68295. }
  68296. pPage->nOverflow = 0;
  68297. /* The next iteration of the do-loop balances the parent page. */
  68298. releasePage(pPage);
  68299. pCur->iPage--;
  68300. assert( pCur->iPage>=0 );
  68301. pCur->pPage = pCur->apPage[pCur->iPage];
  68302. }
  68303. }while( rc==SQLITE_OK );
  68304. if( pFree ){
  68305. sqlite3PageFree(pFree);
  68306. }
  68307. return rc;
  68308. }
  68309. /* Overwrite content from pX into pDest. Only do the write if the
  68310. ** content is different from what is already there.
  68311. */
  68312. static int btreeOverwriteContent(
  68313. MemPage *pPage, /* MemPage on which writing will occur */
  68314. u8 *pDest, /* Pointer to the place to start writing */
  68315. const BtreePayload *pX, /* Source of data to write */
  68316. int iOffset, /* Offset of first byte to write */
  68317. int iAmt /* Number of bytes to be written */
  68318. ){
  68319. int nData = pX->nData - iOffset;
  68320. if( nData<=0 ){
  68321. /* Overwritting with zeros */
  68322. int i;
  68323. for(i=0; i<iAmt && pDest[i]==0; i++){}
  68324. if( i<iAmt ){
  68325. int rc = sqlite3PagerWrite(pPage->pDbPage);
  68326. if( rc ) return rc;
  68327. memset(pDest + i, 0, iAmt - i);
  68328. }
  68329. }else{
  68330. if( nData<iAmt ){
  68331. /* Mixed read data and zeros at the end. Make a recursive call
  68332. ** to write the zeros then fall through to write the real data */
  68333. int rc = btreeOverwriteContent(pPage, pDest+nData, pX, iOffset+nData,
  68334. iAmt-nData);
  68335. if( rc ) return rc;
  68336. iAmt = nData;
  68337. }
  68338. if( memcmp(pDest, ((u8*)pX->pData) + iOffset, iAmt)!=0 ){
  68339. int rc = sqlite3PagerWrite(pPage->pDbPage);
  68340. if( rc ) return rc;
  68341. /* In a corrupt database, it is possible for the source and destination
  68342. ** buffers to overlap. This is harmless since the database is already
  68343. ** corrupt but it does cause valgrind and ASAN warnings. So use
  68344. ** memmove(). */
  68345. memmove(pDest, ((u8*)pX->pData) + iOffset, iAmt);
  68346. }
  68347. }
  68348. return SQLITE_OK;
  68349. }
  68350. /*
  68351. ** Overwrite the cell that cursor pCur is pointing to with fresh content
  68352. ** contained in pX.
  68353. */
  68354. static int btreeOverwriteCell(BtCursor *pCur, const BtreePayload *pX){
  68355. int iOffset; /* Next byte of pX->pData to write */
  68356. int nTotal = pX->nData + pX->nZero; /* Total bytes of to write */
  68357. int rc; /* Return code */
  68358. MemPage *pPage = pCur->pPage; /* Page being written */
  68359. BtShared *pBt; /* Btree */
  68360. Pgno ovflPgno; /* Next overflow page to write */
  68361. u32 ovflPageSize; /* Size to write on overflow page */
  68362. if( pCur->info.pPayload + pCur->info.nLocal > pPage->aDataEnd
  68363. || pCur->info.pPayload < pPage->aData + pPage->cellOffset
  68364. ){
  68365. return SQLITE_CORRUPT_BKPT;
  68366. }
  68367. /* Overwrite the local portion first */
  68368. rc = btreeOverwriteContent(pPage, pCur->info.pPayload, pX,
  68369. 0, pCur->info.nLocal);
  68370. if( rc ) return rc;
  68371. if( pCur->info.nLocal==nTotal ) return SQLITE_OK;
  68372. /* Now overwrite the overflow pages */
  68373. iOffset = pCur->info.nLocal;
  68374. assert( nTotal>=0 );
  68375. assert( iOffset>=0 );
  68376. ovflPgno = get4byte(pCur->info.pPayload + iOffset);
  68377. pBt = pPage->pBt;
  68378. ovflPageSize = pBt->usableSize - 4;
  68379. do{
  68380. rc = btreeGetPage(pBt, ovflPgno, &pPage, 0);
  68381. if( rc ) return rc;
  68382. if( sqlite3PagerPageRefcount(pPage->pDbPage)!=1 ){
  68383. rc = SQLITE_CORRUPT_BKPT;
  68384. }else{
  68385. if( iOffset+ovflPageSize<(u32)nTotal ){
  68386. ovflPgno = get4byte(pPage->aData);
  68387. }else{
  68388. ovflPageSize = nTotal - iOffset;
  68389. }
  68390. rc = btreeOverwriteContent(pPage, pPage->aData+4, pX,
  68391. iOffset, ovflPageSize);
  68392. }
  68393. sqlite3PagerUnref(pPage->pDbPage);
  68394. if( rc ) return rc;
  68395. iOffset += ovflPageSize;
  68396. }while( iOffset<nTotal );
  68397. return SQLITE_OK;
  68398. }
  68399. /*
  68400. ** Insert a new record into the BTree. The content of the new record
  68401. ** is described by the pX object. The pCur cursor is used only to
  68402. ** define what table the record should be inserted into, and is left
  68403. ** pointing at a random location.
  68404. **
  68405. ** For a table btree (used for rowid tables), only the pX.nKey value of
  68406. ** the key is used. The pX.pKey value must be NULL. The pX.nKey is the
  68407. ** rowid or INTEGER PRIMARY KEY of the row. The pX.nData,pData,nZero fields
  68408. ** hold the content of the row.
  68409. **
  68410. ** For an index btree (used for indexes and WITHOUT ROWID tables), the
  68411. ** key is an arbitrary byte sequence stored in pX.pKey,nKey. The
  68412. ** pX.pData,nData,nZero fields must be zero.
  68413. **
  68414. ** If the seekResult parameter is non-zero, then a successful call to
  68415. ** MovetoUnpacked() to seek cursor pCur to (pKey,nKey) has already
  68416. ** been performed. In other words, if seekResult!=0 then the cursor
  68417. ** is currently pointing to a cell that will be adjacent to the cell
  68418. ** to be inserted. If seekResult<0 then pCur points to a cell that is
  68419. ** smaller then (pKey,nKey). If seekResult>0 then pCur points to a cell
  68420. ** that is larger than (pKey,nKey).
  68421. **
  68422. ** If seekResult==0, that means pCur is pointing at some unknown location.
  68423. ** In that case, this routine must seek the cursor to the correct insertion
  68424. ** point for (pKey,nKey) before doing the insertion. For index btrees,
  68425. ** if pX->nMem is non-zero, then pX->aMem contains pointers to the unpacked
  68426. ** key values and pX->aMem can be used instead of pX->pKey to avoid having
  68427. ** to decode the key.
  68428. */
  68429. SQLITE_PRIVATE int sqlite3BtreeInsert(
  68430. BtCursor *pCur, /* Insert data into the table of this cursor */
  68431. const BtreePayload *pX, /* Content of the row to be inserted */
  68432. int flags, /* True if this is likely an append */
  68433. int seekResult /* Result of prior MovetoUnpacked() call */
  68434. ){
  68435. int rc;
  68436. int loc = seekResult; /* -1: before desired location +1: after */
  68437. int szNew = 0;
  68438. int idx;
  68439. MemPage *pPage;
  68440. Btree *p = pCur->pBtree;
  68441. BtShared *pBt = p->pBt;
  68442. unsigned char *oldCell;
  68443. unsigned char *newCell = 0;
  68444. assert( (flags & (BTREE_SAVEPOSITION|BTREE_APPEND))==flags );
  68445. if( pCur->eState==CURSOR_FAULT ){
  68446. assert( pCur->skipNext!=SQLITE_OK );
  68447. return pCur->skipNext;
  68448. }
  68449. assert( cursorOwnsBtShared(pCur) );
  68450. assert( (pCur->curFlags & BTCF_WriteFlag)!=0
  68451. && pBt->inTransaction==TRANS_WRITE
  68452. && (pBt->btsFlags & BTS_READ_ONLY)==0 );
  68453. assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
  68454. /* Assert that the caller has been consistent. If this cursor was opened
  68455. ** expecting an index b-tree, then the caller should be inserting blob
  68456. ** keys with no associated data. If the cursor was opened expecting an
  68457. ** intkey table, the caller should be inserting integer keys with a
  68458. ** blob of associated data. */
  68459. assert( (pX->pKey==0)==(pCur->pKeyInfo==0) );
  68460. /* Save the positions of any other cursors open on this table.
  68461. **
  68462. ** In some cases, the call to btreeMoveto() below is a no-op. For
  68463. ** example, when inserting data into a table with auto-generated integer
  68464. ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
  68465. ** integer key to use. It then calls this function to actually insert the
  68466. ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
  68467. ** that the cursor is already where it needs to be and returns without
  68468. ** doing any work. To avoid thwarting these optimizations, it is important
  68469. ** not to clear the cursor here.
  68470. */
  68471. if( pCur->curFlags & BTCF_Multiple ){
  68472. rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
  68473. if( rc ) return rc;
  68474. }
  68475. if( pCur->pKeyInfo==0 ){
  68476. assert( pX->pKey==0 );
  68477. /* If this is an insert into a table b-tree, invalidate any incrblob
  68478. ** cursors open on the row being replaced */
  68479. invalidateIncrblobCursors(p, pCur->pgnoRoot, pX->nKey, 0);
  68480. /* If BTREE_SAVEPOSITION is set, the cursor must already be pointing
  68481. ** to a row with the same key as the new entry being inserted.
  68482. */
  68483. #ifdef SQLITE_DEBUG
  68484. if( flags & BTREE_SAVEPOSITION ){
  68485. assert( pCur->curFlags & BTCF_ValidNKey );
  68486. assert( pX->nKey==pCur->info.nKey );
  68487. assert( loc==0 );
  68488. }
  68489. #endif
  68490. /* On the other hand, BTREE_SAVEPOSITION==0 does not imply
  68491. ** that the cursor is not pointing to a row to be overwritten.
  68492. ** So do a complete check.
  68493. */
  68494. if( (pCur->curFlags&BTCF_ValidNKey)!=0 && pX->nKey==pCur->info.nKey ){
  68495. /* The cursor is pointing to the entry that is to be
  68496. ** overwritten */
  68497. assert( pX->nData>=0 && pX->nZero>=0 );
  68498. if( pCur->info.nSize!=0
  68499. && pCur->info.nPayload==(u32)pX->nData+pX->nZero
  68500. ){
  68501. /* New entry is the same size as the old. Do an overwrite */
  68502. return btreeOverwriteCell(pCur, pX);
  68503. }
  68504. assert( loc==0 );
  68505. }else if( loc==0 ){
  68506. /* The cursor is *not* pointing to the cell to be overwritten, nor
  68507. ** to an adjacent cell. Move the cursor so that it is pointing either
  68508. ** to the cell to be overwritten or an adjacent cell.
  68509. */
  68510. rc = sqlite3BtreeMovetoUnpacked(pCur, 0, pX->nKey, flags!=0, &loc);
  68511. if( rc ) return rc;
  68512. }
  68513. }else{
  68514. /* This is an index or a WITHOUT ROWID table */
  68515. /* If BTREE_SAVEPOSITION is set, the cursor must already be pointing
  68516. ** to a row with the same key as the new entry being inserted.
  68517. */
  68518. assert( (flags & BTREE_SAVEPOSITION)==0 || loc==0 );
  68519. /* If the cursor is not already pointing either to the cell to be
  68520. ** overwritten, or if a new cell is being inserted, if the cursor is
  68521. ** not pointing to an immediately adjacent cell, then move the cursor
  68522. ** so that it does.
  68523. */
  68524. if( loc==0 && (flags & BTREE_SAVEPOSITION)==0 ){
  68525. if( pX->nMem ){
  68526. UnpackedRecord r;
  68527. r.pKeyInfo = pCur->pKeyInfo;
  68528. r.aMem = pX->aMem;
  68529. r.nField = pX->nMem;
  68530. r.default_rc = 0;
  68531. r.errCode = 0;
  68532. r.r1 = 0;
  68533. r.r2 = 0;
  68534. r.eqSeen = 0;
  68535. rc = sqlite3BtreeMovetoUnpacked(pCur, &r, 0, flags!=0, &loc);
  68536. }else{
  68537. rc = btreeMoveto(pCur, pX->pKey, pX->nKey, flags!=0, &loc);
  68538. }
  68539. if( rc ) return rc;
  68540. }
  68541. /* If the cursor is currently pointing to an entry to be overwritten
  68542. ** and the new content is the same as as the old, then use the
  68543. ** overwrite optimization.
  68544. */
  68545. if( loc==0 ){
  68546. getCellInfo(pCur);
  68547. if( pCur->info.nKey==pX->nKey ){
  68548. BtreePayload x2;
  68549. x2.pData = pX->pKey;
  68550. x2.nData = pX->nKey;
  68551. x2.nZero = 0;
  68552. return btreeOverwriteCell(pCur, &x2);
  68553. }
  68554. }
  68555. }
  68556. assert( pCur->eState==CURSOR_VALID
  68557. || (pCur->eState==CURSOR_INVALID && loc)
  68558. || CORRUPT_DB );
  68559. pPage = pCur->pPage;
  68560. assert( pPage->intKey || pX->nKey>=0 );
  68561. assert( pPage->leaf || !pPage->intKey );
  68562. if( pPage->nFree<0 ){
  68563. rc = btreeComputeFreeSpace(pPage);
  68564. if( rc ) return rc;
  68565. }
  68566. TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
  68567. pCur->pgnoRoot, pX->nKey, pX->nData, pPage->pgno,
  68568. loc==0 ? "overwrite" : "new entry"));
  68569. assert( pPage->isInit );
  68570. newCell = pBt->pTmpSpace;
  68571. assert( newCell!=0 );
  68572. rc = fillInCell(pPage, newCell, pX, &szNew);
  68573. if( rc ) goto end_insert;
  68574. assert( szNew==pPage->xCellSize(pPage, newCell) );
  68575. assert( szNew <= MX_CELL_SIZE(pBt) );
  68576. idx = pCur->ix;
  68577. if( loc==0 ){
  68578. CellInfo info;
  68579. assert( idx<pPage->nCell );
  68580. rc = sqlite3PagerWrite(pPage->pDbPage);
  68581. if( rc ){
  68582. goto end_insert;
  68583. }
  68584. oldCell = findCell(pPage, idx);
  68585. if( !pPage->leaf ){
  68586. memcpy(newCell, oldCell, 4);
  68587. }
  68588. rc = clearCell(pPage, oldCell, &info);
  68589. testcase( pCur->curFlags & BTCF_ValidOvfl );
  68590. invalidateOverflowCache(pCur);
  68591. if( info.nSize==szNew && info.nLocal==info.nPayload
  68592. && (!ISAUTOVACUUM || szNew<pPage->minLocal)
  68593. ){
  68594. /* Overwrite the old cell with the new if they are the same size.
  68595. ** We could also try to do this if the old cell is smaller, then add
  68596. ** the leftover space to the free list. But experiments show that
  68597. ** doing that is no faster then skipping this optimization and just
  68598. ** calling dropCell() and insertCell().
  68599. **
  68600. ** This optimization cannot be used on an autovacuum database if the
  68601. ** new entry uses overflow pages, as the insertCell() call below is
  68602. ** necessary to add the PTRMAP_OVERFLOW1 pointer-map entry. */
  68603. assert( rc==SQLITE_OK ); /* clearCell never fails when nLocal==nPayload */
  68604. if( oldCell < pPage->aData+pPage->hdrOffset+10 ){
  68605. return SQLITE_CORRUPT_BKPT;
  68606. }
  68607. if( oldCell+szNew > pPage->aDataEnd ){
  68608. return SQLITE_CORRUPT_BKPT;
  68609. }
  68610. memcpy(oldCell, newCell, szNew);
  68611. return SQLITE_OK;
  68612. }
  68613. dropCell(pPage, idx, info.nSize, &rc);
  68614. if( rc ) goto end_insert;
  68615. }else if( loc<0 && pPage->nCell>0 ){
  68616. assert( pPage->leaf );
  68617. idx = ++pCur->ix;
  68618. pCur->curFlags &= ~BTCF_ValidNKey;
  68619. }else{
  68620. assert( pPage->leaf );
  68621. }
  68622. insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
  68623. assert( pPage->nOverflow==0 || rc==SQLITE_OK );
  68624. assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
  68625. /* If no error has occurred and pPage has an overflow cell, call balance()
  68626. ** to redistribute the cells within the tree. Since balance() may move
  68627. ** the cursor, zero the BtCursor.info.nSize and BTCF_ValidNKey
  68628. ** variables.
  68629. **
  68630. ** Previous versions of SQLite called moveToRoot() to move the cursor
  68631. ** back to the root page as balance() used to invalidate the contents
  68632. ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
  68633. ** set the cursor state to "invalid". This makes common insert operations
  68634. ** slightly faster.
  68635. **
  68636. ** There is a subtle but important optimization here too. When inserting
  68637. ** multiple records into an intkey b-tree using a single cursor (as can
  68638. ** happen while processing an "INSERT INTO ... SELECT" statement), it
  68639. ** is advantageous to leave the cursor pointing to the last entry in
  68640. ** the b-tree if possible. If the cursor is left pointing to the last
  68641. ** entry in the table, and the next row inserted has an integer key
  68642. ** larger than the largest existing key, it is possible to insert the
  68643. ** row without seeking the cursor. This can be a big performance boost.
  68644. */
  68645. pCur->info.nSize = 0;
  68646. if( pPage->nOverflow ){
  68647. assert( rc==SQLITE_OK );
  68648. pCur->curFlags &= ~(BTCF_ValidNKey);
  68649. rc = balance(pCur);
  68650. /* Must make sure nOverflow is reset to zero even if the balance()
  68651. ** fails. Internal data structure corruption will result otherwise.
  68652. ** Also, set the cursor state to invalid. This stops saveCursorPosition()
  68653. ** from trying to save the current position of the cursor. */
  68654. pCur->pPage->nOverflow = 0;
  68655. pCur->eState = CURSOR_INVALID;
  68656. if( (flags & BTREE_SAVEPOSITION) && rc==SQLITE_OK ){
  68657. btreeReleaseAllCursorPages(pCur);
  68658. if( pCur->pKeyInfo ){
  68659. assert( pCur->pKey==0 );
  68660. pCur->pKey = sqlite3Malloc( pX->nKey );
  68661. if( pCur->pKey==0 ){
  68662. rc = SQLITE_NOMEM;
  68663. }else{
  68664. memcpy(pCur->pKey, pX->pKey, pX->nKey);
  68665. }
  68666. }
  68667. pCur->eState = CURSOR_REQUIRESEEK;
  68668. pCur->nKey = pX->nKey;
  68669. }
  68670. }
  68671. assert( pCur->iPage<0 || pCur->pPage->nOverflow==0 );
  68672. end_insert:
  68673. return rc;
  68674. }
  68675. /*
  68676. ** Delete the entry that the cursor is pointing to.
  68677. **
  68678. ** If the BTREE_SAVEPOSITION bit of the flags parameter is zero, then
  68679. ** the cursor is left pointing at an arbitrary location after the delete.
  68680. ** But if that bit is set, then the cursor is left in a state such that
  68681. ** the next call to BtreeNext() or BtreePrev() moves it to the same row
  68682. ** as it would have been on if the call to BtreeDelete() had been omitted.
  68683. **
  68684. ** The BTREE_AUXDELETE bit of flags indicates that is one of several deletes
  68685. ** associated with a single table entry and its indexes. Only one of those
  68686. ** deletes is considered the "primary" delete. The primary delete occurs
  68687. ** on a cursor that is not a BTREE_FORDELETE cursor. All but one delete
  68688. ** operation on non-FORDELETE cursors is tagged with the AUXDELETE flag.
  68689. ** The BTREE_AUXDELETE bit is a hint that is not used by this implementation,
  68690. ** but which might be used by alternative storage engines.
  68691. */
  68692. SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur, u8 flags){
  68693. Btree *p = pCur->pBtree;
  68694. BtShared *pBt = p->pBt;
  68695. int rc; /* Return code */
  68696. MemPage *pPage; /* Page to delete cell from */
  68697. unsigned char *pCell; /* Pointer to cell to delete */
  68698. int iCellIdx; /* Index of cell to delete */
  68699. int iCellDepth; /* Depth of node containing pCell */
  68700. CellInfo info; /* Size of the cell being deleted */
  68701. int bSkipnext = 0; /* Leaf cursor in SKIPNEXT state */
  68702. u8 bPreserve = flags & BTREE_SAVEPOSITION; /* Keep cursor valid */
  68703. assert( cursorOwnsBtShared(pCur) );
  68704. assert( pBt->inTransaction==TRANS_WRITE );
  68705. assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
  68706. assert( pCur->curFlags & BTCF_WriteFlag );
  68707. assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
  68708. assert( !hasReadConflicts(p, pCur->pgnoRoot) );
  68709. assert( (flags & ~(BTREE_SAVEPOSITION | BTREE_AUXDELETE))==0 );
  68710. if( pCur->eState==CURSOR_REQUIRESEEK ){
  68711. rc = btreeRestoreCursorPosition(pCur);
  68712. if( rc ) return rc;
  68713. }
  68714. assert( pCur->eState==CURSOR_VALID );
  68715. iCellDepth = pCur->iPage;
  68716. iCellIdx = pCur->ix;
  68717. pPage = pCur->pPage;
  68718. pCell = findCell(pPage, iCellIdx);
  68719. if( pPage->nFree<0 && btreeComputeFreeSpace(pPage) ) return SQLITE_CORRUPT;
  68720. /* If the bPreserve flag is set to true, then the cursor position must
  68721. ** be preserved following this delete operation. If the current delete
  68722. ** will cause a b-tree rebalance, then this is done by saving the cursor
  68723. ** key and leaving the cursor in CURSOR_REQUIRESEEK state before
  68724. ** returning.
  68725. **
  68726. ** Or, if the current delete will not cause a rebalance, then the cursor
  68727. ** will be left in CURSOR_SKIPNEXT state pointing to the entry immediately
  68728. ** before or after the deleted entry. In this case set bSkipnext to true. */
  68729. if( bPreserve ){
  68730. if( !pPage->leaf
  68731. || (pPage->nFree+cellSizePtr(pPage,pCell)+2)>(int)(pBt->usableSize*2/3)
  68732. || pPage->nCell==1 /* See dbfuzz001.test for a test case */
  68733. ){
  68734. /* A b-tree rebalance will be required after deleting this entry.
  68735. ** Save the cursor key. */
  68736. rc = saveCursorKey(pCur);
  68737. if( rc ) return rc;
  68738. }else{
  68739. bSkipnext = 1;
  68740. }
  68741. }
  68742. /* If the page containing the entry to delete is not a leaf page, move
  68743. ** the cursor to the largest entry in the tree that is smaller than
  68744. ** the entry being deleted. This cell will replace the cell being deleted
  68745. ** from the internal node. The 'previous' entry is used for this instead
  68746. ** of the 'next' entry, as the previous entry is always a part of the
  68747. ** sub-tree headed by the child page of the cell being deleted. This makes
  68748. ** balancing the tree following the delete operation easier. */
  68749. if( !pPage->leaf ){
  68750. rc = sqlite3BtreePrevious(pCur, 0);
  68751. assert( rc!=SQLITE_DONE );
  68752. if( rc ) return rc;
  68753. }
  68754. /* Save the positions of any other cursors open on this table before
  68755. ** making any modifications. */
  68756. if( pCur->curFlags & BTCF_Multiple ){
  68757. rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
  68758. if( rc ) return rc;
  68759. }
  68760. /* If this is a delete operation to remove a row from a table b-tree,
  68761. ** invalidate any incrblob cursors open on the row being deleted. */
  68762. if( pCur->pKeyInfo==0 ){
  68763. invalidateIncrblobCursors(p, pCur->pgnoRoot, pCur->info.nKey, 0);
  68764. }
  68765. /* Make the page containing the entry to be deleted writable. Then free any
  68766. ** overflow pages associated with the entry and finally remove the cell
  68767. ** itself from within the page. */
  68768. rc = sqlite3PagerWrite(pPage->pDbPage);
  68769. if( rc ) return rc;
  68770. rc = clearCell(pPage, pCell, &info);
  68771. dropCell(pPage, iCellIdx, info.nSize, &rc);
  68772. if( rc ) return rc;
  68773. /* If the cell deleted was not located on a leaf page, then the cursor
  68774. ** is currently pointing to the largest entry in the sub-tree headed
  68775. ** by the child-page of the cell that was just deleted from an internal
  68776. ** node. The cell from the leaf node needs to be moved to the internal
  68777. ** node to replace the deleted cell. */
  68778. if( !pPage->leaf ){
  68779. MemPage *pLeaf = pCur->pPage;
  68780. int nCell;
  68781. Pgno n;
  68782. unsigned char *pTmp;
  68783. if( pLeaf->nFree<0 ){
  68784. rc = btreeComputeFreeSpace(pLeaf);
  68785. if( rc ) return rc;
  68786. }
  68787. if( iCellDepth<pCur->iPage-1 ){
  68788. n = pCur->apPage[iCellDepth+1]->pgno;
  68789. }else{
  68790. n = pCur->pPage->pgno;
  68791. }
  68792. pCell = findCell(pLeaf, pLeaf->nCell-1);
  68793. if( pCell<&pLeaf->aData[4] ) return SQLITE_CORRUPT_BKPT;
  68794. nCell = pLeaf->xCellSize(pLeaf, pCell);
  68795. assert( MX_CELL_SIZE(pBt) >= nCell );
  68796. pTmp = pBt->pTmpSpace;
  68797. assert( pTmp!=0 );
  68798. rc = sqlite3PagerWrite(pLeaf->pDbPage);
  68799. if( rc==SQLITE_OK ){
  68800. insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
  68801. }
  68802. dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
  68803. if( rc ) return rc;
  68804. }
  68805. /* Balance the tree. If the entry deleted was located on a leaf page,
  68806. ** then the cursor still points to that page. In this case the first
  68807. ** call to balance() repairs the tree, and the if(...) condition is
  68808. ** never true.
  68809. **
  68810. ** Otherwise, if the entry deleted was on an internal node page, then
  68811. ** pCur is pointing to the leaf page from which a cell was removed to
  68812. ** replace the cell deleted from the internal node. This is slightly
  68813. ** tricky as the leaf node may be underfull, and the internal node may
  68814. ** be either under or overfull. In this case run the balancing algorithm
  68815. ** on the leaf node first. If the balance proceeds far enough up the
  68816. ** tree that we can be sure that any problem in the internal node has
  68817. ** been corrected, so be it. Otherwise, after balancing the leaf node,
  68818. ** walk the cursor up the tree to the internal node and balance it as
  68819. ** well. */
  68820. rc = balance(pCur);
  68821. if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
  68822. releasePageNotNull(pCur->pPage);
  68823. pCur->iPage--;
  68824. while( pCur->iPage>iCellDepth ){
  68825. releasePage(pCur->apPage[pCur->iPage--]);
  68826. }
  68827. pCur->pPage = pCur->apPage[pCur->iPage];
  68828. rc = balance(pCur);
  68829. }
  68830. if( rc==SQLITE_OK ){
  68831. if( bSkipnext ){
  68832. assert( bPreserve && (pCur->iPage==iCellDepth || CORRUPT_DB) );
  68833. assert( pPage==pCur->pPage || CORRUPT_DB );
  68834. assert( (pPage->nCell>0 || CORRUPT_DB) && iCellIdx<=pPage->nCell );
  68835. pCur->eState = CURSOR_SKIPNEXT;
  68836. if( iCellIdx>=pPage->nCell ){
  68837. pCur->skipNext = -1;
  68838. pCur->ix = pPage->nCell-1;
  68839. }else{
  68840. pCur->skipNext = 1;
  68841. }
  68842. }else{
  68843. rc = moveToRoot(pCur);
  68844. if( bPreserve ){
  68845. btreeReleaseAllCursorPages(pCur);
  68846. pCur->eState = CURSOR_REQUIRESEEK;
  68847. }
  68848. if( rc==SQLITE_EMPTY ) rc = SQLITE_OK;
  68849. }
  68850. }
  68851. return rc;
  68852. }
  68853. /*
  68854. ** Create a new BTree table. Write into *piTable the page
  68855. ** number for the root page of the new table.
  68856. **
  68857. ** The type of type is determined by the flags parameter. Only the
  68858. ** following values of flags are currently in use. Other values for
  68859. ** flags might not work:
  68860. **
  68861. ** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys
  68862. ** BTREE_ZERODATA Used for SQL indices
  68863. */
  68864. static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){
  68865. BtShared *pBt = p->pBt;
  68866. MemPage *pRoot;
  68867. Pgno pgnoRoot;
  68868. int rc;
  68869. int ptfFlags; /* Page-type flage for the root page of new table */
  68870. assert( sqlite3BtreeHoldsMutex(p) );
  68871. assert( pBt->inTransaction==TRANS_WRITE );
  68872. assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
  68873. #ifdef SQLITE_OMIT_AUTOVACUUM
  68874. rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
  68875. if( rc ){
  68876. return rc;
  68877. }
  68878. #else
  68879. if( pBt->autoVacuum ){
  68880. Pgno pgnoMove; /* Move a page here to make room for the root-page */
  68881. MemPage *pPageMove; /* The page to move to. */
  68882. /* Creating a new table may probably require moving an existing database
  68883. ** to make room for the new tables root page. In case this page turns
  68884. ** out to be an overflow page, delete all overflow page-map caches
  68885. ** held by open cursors.
  68886. */
  68887. invalidateAllOverflowCache(pBt);
  68888. /* Read the value of meta[3] from the database to determine where the
  68889. ** root page of the new table should go. meta[3] is the largest root-page
  68890. ** created so far, so the new root-page is (meta[3]+1).
  68891. */
  68892. sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
  68893. pgnoRoot++;
  68894. /* The new root-page may not be allocated on a pointer-map page, or the
  68895. ** PENDING_BYTE page.
  68896. */
  68897. while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
  68898. pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
  68899. pgnoRoot++;
  68900. }
  68901. assert( pgnoRoot>=3 || CORRUPT_DB );
  68902. testcase( pgnoRoot<3 );
  68903. /* Allocate a page. The page that currently resides at pgnoRoot will
  68904. ** be moved to the allocated page (unless the allocated page happens
  68905. ** to reside at pgnoRoot).
  68906. */
  68907. rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, BTALLOC_EXACT);
  68908. if( rc!=SQLITE_OK ){
  68909. return rc;
  68910. }
  68911. if( pgnoMove!=pgnoRoot ){
  68912. /* pgnoRoot is the page that will be used for the root-page of
  68913. ** the new table (assuming an error did not occur). But we were
  68914. ** allocated pgnoMove. If required (i.e. if it was not allocated
  68915. ** by extending the file), the current page at position pgnoMove
  68916. ** is already journaled.
  68917. */
  68918. u8 eType = 0;
  68919. Pgno iPtrPage = 0;
  68920. /* Save the positions of any open cursors. This is required in
  68921. ** case they are holding a reference to an xFetch reference
  68922. ** corresponding to page pgnoRoot. */
  68923. rc = saveAllCursors(pBt, 0, 0);
  68924. releasePage(pPageMove);
  68925. if( rc!=SQLITE_OK ){
  68926. return rc;
  68927. }
  68928. /* Move the page currently at pgnoRoot to pgnoMove. */
  68929. rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
  68930. if( rc!=SQLITE_OK ){
  68931. return rc;
  68932. }
  68933. rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
  68934. if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
  68935. rc = SQLITE_CORRUPT_BKPT;
  68936. }
  68937. if( rc!=SQLITE_OK ){
  68938. releasePage(pRoot);
  68939. return rc;
  68940. }
  68941. assert( eType!=PTRMAP_ROOTPAGE );
  68942. assert( eType!=PTRMAP_FREEPAGE );
  68943. rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
  68944. releasePage(pRoot);
  68945. /* Obtain the page at pgnoRoot */
  68946. if( rc!=SQLITE_OK ){
  68947. return rc;
  68948. }
  68949. rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
  68950. if( rc!=SQLITE_OK ){
  68951. return rc;
  68952. }
  68953. rc = sqlite3PagerWrite(pRoot->pDbPage);
  68954. if( rc!=SQLITE_OK ){
  68955. releasePage(pRoot);
  68956. return rc;
  68957. }
  68958. }else{
  68959. pRoot = pPageMove;
  68960. }
  68961. /* Update the pointer-map and meta-data with the new root-page number. */
  68962. ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
  68963. if( rc ){
  68964. releasePage(pRoot);
  68965. return rc;
  68966. }
  68967. /* When the new root page was allocated, page 1 was made writable in
  68968. ** order either to increase the database filesize, or to decrement the
  68969. ** freelist count. Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
  68970. */
  68971. assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
  68972. rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
  68973. if( NEVER(rc) ){
  68974. releasePage(pRoot);
  68975. return rc;
  68976. }
  68977. }else{
  68978. rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
  68979. if( rc ) return rc;
  68980. }
  68981. #endif
  68982. assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
  68983. if( createTabFlags & BTREE_INTKEY ){
  68984. ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
  68985. }else{
  68986. ptfFlags = PTF_ZERODATA | PTF_LEAF;
  68987. }
  68988. zeroPage(pRoot, ptfFlags);
  68989. sqlite3PagerUnref(pRoot->pDbPage);
  68990. assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
  68991. *piTable = (int)pgnoRoot;
  68992. return SQLITE_OK;
  68993. }
  68994. SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
  68995. int rc;
  68996. sqlite3BtreeEnter(p);
  68997. rc = btreeCreateTable(p, piTable, flags);
  68998. sqlite3BtreeLeave(p);
  68999. return rc;
  69000. }
  69001. /*
  69002. ** Erase the given database page and all its children. Return
  69003. ** the page to the freelist.
  69004. */
  69005. static int clearDatabasePage(
  69006. BtShared *pBt, /* The BTree that contains the table */
  69007. Pgno pgno, /* Page number to clear */
  69008. int freePageFlag, /* Deallocate page if true */
  69009. int *pnChange /* Add number of Cells freed to this counter */
  69010. ){
  69011. MemPage *pPage;
  69012. int rc;
  69013. unsigned char *pCell;
  69014. int i;
  69015. int hdr;
  69016. CellInfo info;
  69017. assert( sqlite3_mutex_held(pBt->mutex) );
  69018. if( pgno>btreePagecount(pBt) ){
  69019. return SQLITE_CORRUPT_BKPT;
  69020. }
  69021. rc = getAndInitPage(pBt, pgno, &pPage, 0, 0);
  69022. if( rc ) return rc;
  69023. if( pPage->bBusy ){
  69024. rc = SQLITE_CORRUPT_BKPT;
  69025. goto cleardatabasepage_out;
  69026. }
  69027. pPage->bBusy = 1;
  69028. hdr = pPage->hdrOffset;
  69029. for(i=0; i<pPage->nCell; i++){
  69030. pCell = findCell(pPage, i);
  69031. if( !pPage->leaf ){
  69032. rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
  69033. if( rc ) goto cleardatabasepage_out;
  69034. }
  69035. rc = clearCell(pPage, pCell, &info);
  69036. if( rc ) goto cleardatabasepage_out;
  69037. }
  69038. if( !pPage->leaf ){
  69039. rc = clearDatabasePage(pBt, get4byte(&pPage->aData[hdr+8]), 1, pnChange);
  69040. if( rc ) goto cleardatabasepage_out;
  69041. }else if( pnChange ){
  69042. assert( pPage->intKey || CORRUPT_DB );
  69043. testcase( !pPage->intKey );
  69044. *pnChange += pPage->nCell;
  69045. }
  69046. if( freePageFlag ){
  69047. freePage(pPage, &rc);
  69048. }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
  69049. zeroPage(pPage, pPage->aData[hdr] | PTF_LEAF);
  69050. }
  69051. cleardatabasepage_out:
  69052. pPage->bBusy = 0;
  69053. releasePage(pPage);
  69054. return rc;
  69055. }
  69056. /*
  69057. ** Delete all information from a single table in the database. iTable is
  69058. ** the page number of the root of the table. After this routine returns,
  69059. ** the root page is empty, but still exists.
  69060. **
  69061. ** This routine will fail with SQLITE_LOCKED if there are any open
  69062. ** read cursors on the table. Open write cursors are moved to the
  69063. ** root of the table.
  69064. **
  69065. ** If pnChange is not NULL, then table iTable must be an intkey table. The
  69066. ** integer value pointed to by pnChange is incremented by the number of
  69067. ** entries in the table.
  69068. */
  69069. SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
  69070. int rc;
  69071. BtShared *pBt = p->pBt;
  69072. sqlite3BtreeEnter(p);
  69073. assert( p->inTrans==TRANS_WRITE );
  69074. rc = saveAllCursors(pBt, (Pgno)iTable, 0);
  69075. if( SQLITE_OK==rc ){
  69076. /* Invalidate all incrblob cursors open on table iTable (assuming iTable
  69077. ** is the root of a table b-tree - if it is not, the following call is
  69078. ** a no-op). */
  69079. invalidateIncrblobCursors(p, (Pgno)iTable, 0, 1);
  69080. rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
  69081. }
  69082. sqlite3BtreeLeave(p);
  69083. return rc;
  69084. }
  69085. /*
  69086. ** Delete all information from the single table that pCur is open on.
  69087. **
  69088. ** This routine only work for pCur on an ephemeral table.
  69089. */
  69090. SQLITE_PRIVATE int sqlite3BtreeClearTableOfCursor(BtCursor *pCur){
  69091. return sqlite3BtreeClearTable(pCur->pBtree, pCur->pgnoRoot, 0);
  69092. }
  69093. /*
  69094. ** Erase all information in a table and add the root of the table to
  69095. ** the freelist. Except, the root of the principle table (the one on
  69096. ** page 1) is never added to the freelist.
  69097. **
  69098. ** This routine will fail with SQLITE_LOCKED if there are any open
  69099. ** cursors on the table.
  69100. **
  69101. ** If AUTOVACUUM is enabled and the page at iTable is not the last
  69102. ** root page in the database file, then the last root page
  69103. ** in the database file is moved into the slot formerly occupied by
  69104. ** iTable and that last slot formerly occupied by the last root page
  69105. ** is added to the freelist instead of iTable. In this say, all
  69106. ** root pages are kept at the beginning of the database file, which
  69107. ** is necessary for AUTOVACUUM to work right. *piMoved is set to the
  69108. ** page number that used to be the last root page in the file before
  69109. ** the move. If no page gets moved, *piMoved is set to 0.
  69110. ** The last root page is recorded in meta[3] and the value of
  69111. ** meta[3] is updated by this procedure.
  69112. */
  69113. static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
  69114. int rc;
  69115. MemPage *pPage = 0;
  69116. BtShared *pBt = p->pBt;
  69117. assert( sqlite3BtreeHoldsMutex(p) );
  69118. assert( p->inTrans==TRANS_WRITE );
  69119. assert( iTable>=2 );
  69120. if( iTable>btreePagecount(pBt) ){
  69121. return SQLITE_CORRUPT_BKPT;
  69122. }
  69123. rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
  69124. if( rc ) return rc;
  69125. rc = sqlite3BtreeClearTable(p, iTable, 0);
  69126. if( rc ){
  69127. releasePage(pPage);
  69128. return rc;
  69129. }
  69130. *piMoved = 0;
  69131. #ifdef SQLITE_OMIT_AUTOVACUUM
  69132. freePage(pPage, &rc);
  69133. releasePage(pPage);
  69134. #else
  69135. if( pBt->autoVacuum ){
  69136. Pgno maxRootPgno;
  69137. sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
  69138. if( iTable==maxRootPgno ){
  69139. /* If the table being dropped is the table with the largest root-page
  69140. ** number in the database, put the root page on the free list.
  69141. */
  69142. freePage(pPage, &rc);
  69143. releasePage(pPage);
  69144. if( rc!=SQLITE_OK ){
  69145. return rc;
  69146. }
  69147. }else{
  69148. /* The table being dropped does not have the largest root-page
  69149. ** number in the database. So move the page that does into the
  69150. ** gap left by the deleted root-page.
  69151. */
  69152. MemPage *pMove;
  69153. releasePage(pPage);
  69154. rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
  69155. if( rc!=SQLITE_OK ){
  69156. return rc;
  69157. }
  69158. rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
  69159. releasePage(pMove);
  69160. if( rc!=SQLITE_OK ){
  69161. return rc;
  69162. }
  69163. pMove = 0;
  69164. rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
  69165. freePage(pMove, &rc);
  69166. releasePage(pMove);
  69167. if( rc!=SQLITE_OK ){
  69168. return rc;
  69169. }
  69170. *piMoved = maxRootPgno;
  69171. }
  69172. /* Set the new 'max-root-page' value in the database header. This
  69173. ** is the old value less one, less one more if that happens to
  69174. ** be a root-page number, less one again if that is the
  69175. ** PENDING_BYTE_PAGE.
  69176. */
  69177. maxRootPgno--;
  69178. while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
  69179. || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
  69180. maxRootPgno--;
  69181. }
  69182. assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
  69183. rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
  69184. }else{
  69185. freePage(pPage, &rc);
  69186. releasePage(pPage);
  69187. }
  69188. #endif
  69189. return rc;
  69190. }
  69191. SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
  69192. int rc;
  69193. sqlite3BtreeEnter(p);
  69194. rc = btreeDropTable(p, iTable, piMoved);
  69195. sqlite3BtreeLeave(p);
  69196. return rc;
  69197. }
  69198. /*
  69199. ** This function may only be called if the b-tree connection already
  69200. ** has a read or write transaction open on the database.
  69201. **
  69202. ** Read the meta-information out of a database file. Meta[0]
  69203. ** is the number of free pages currently in the database. Meta[1]
  69204. ** through meta[15] are available for use by higher layers. Meta[0]
  69205. ** is read-only, the others are read/write.
  69206. **
  69207. ** The schema layer numbers meta values differently. At the schema
  69208. ** layer (and the SetCookie and ReadCookie opcodes) the number of
  69209. ** free pages is not visible. So Cookie[0] is the same as Meta[1].
  69210. **
  69211. ** This routine treats Meta[BTREE_DATA_VERSION] as a special case. Instead
  69212. ** of reading the value out of the header, it instead loads the "DataVersion"
  69213. ** from the pager. The BTREE_DATA_VERSION value is not actually stored in the
  69214. ** database file. It is a number computed by the pager. But its access
  69215. ** pattern is the same as header meta values, and so it is convenient to
  69216. ** read it from this routine.
  69217. */
  69218. SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
  69219. BtShared *pBt = p->pBt;
  69220. sqlite3BtreeEnter(p);
  69221. assert( p->inTrans>TRANS_NONE );
  69222. assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
  69223. assert( pBt->pPage1 );
  69224. assert( idx>=0 && idx<=15 );
  69225. if( idx==BTREE_DATA_VERSION ){
  69226. *pMeta = sqlite3PagerDataVersion(pBt->pPager) + p->iDataVersion;
  69227. }else{
  69228. *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
  69229. }
  69230. /* If auto-vacuum is disabled in this build and this is an auto-vacuum
  69231. ** database, mark the database as read-only. */
  69232. #ifdef SQLITE_OMIT_AUTOVACUUM
  69233. if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ){
  69234. pBt->btsFlags |= BTS_READ_ONLY;
  69235. }
  69236. #endif
  69237. sqlite3BtreeLeave(p);
  69238. }
  69239. /*
  69240. ** Write meta-information back into the database. Meta[0] is
  69241. ** read-only and may not be written.
  69242. */
  69243. SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
  69244. BtShared *pBt = p->pBt;
  69245. unsigned char *pP1;
  69246. int rc;
  69247. assert( idx>=1 && idx<=15 );
  69248. sqlite3BtreeEnter(p);
  69249. assert( p->inTrans==TRANS_WRITE );
  69250. assert( pBt->pPage1!=0 );
  69251. pP1 = pBt->pPage1->aData;
  69252. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  69253. if( rc==SQLITE_OK ){
  69254. put4byte(&pP1[36 + idx*4], iMeta);
  69255. #ifndef SQLITE_OMIT_AUTOVACUUM
  69256. if( idx==BTREE_INCR_VACUUM ){
  69257. assert( pBt->autoVacuum || iMeta==0 );
  69258. assert( iMeta==0 || iMeta==1 );
  69259. pBt->incrVacuum = (u8)iMeta;
  69260. }
  69261. #endif
  69262. }
  69263. sqlite3BtreeLeave(p);
  69264. return rc;
  69265. }
  69266. /*
  69267. ** The first argument, pCur, is a cursor opened on some b-tree. Count the
  69268. ** number of entries in the b-tree and write the result to *pnEntry.
  69269. **
  69270. ** SQLITE_OK is returned if the operation is successfully executed.
  69271. ** Otherwise, if an error is encountered (i.e. an IO error or database
  69272. ** corruption) an SQLite error code is returned.
  69273. */
  69274. SQLITE_PRIVATE int sqlite3BtreeCount(sqlite3 *db, BtCursor *pCur, i64 *pnEntry){
  69275. i64 nEntry = 0; /* Value to return in *pnEntry */
  69276. int rc; /* Return code */
  69277. rc = moveToRoot(pCur);
  69278. if( rc==SQLITE_EMPTY ){
  69279. *pnEntry = 0;
  69280. return SQLITE_OK;
  69281. }
  69282. /* Unless an error occurs, the following loop runs one iteration for each
  69283. ** page in the B-Tree structure (not including overflow pages).
  69284. */
  69285. while( rc==SQLITE_OK && !AtomicLoad(&db->u1.isInterrupted) ){
  69286. int iIdx; /* Index of child node in parent */
  69287. MemPage *pPage; /* Current page of the b-tree */
  69288. /* If this is a leaf page or the tree is not an int-key tree, then
  69289. ** this page contains countable entries. Increment the entry counter
  69290. ** accordingly.
  69291. */
  69292. pPage = pCur->pPage;
  69293. if( pPage->leaf || !pPage->intKey ){
  69294. nEntry += pPage->nCell;
  69295. }
  69296. /* pPage is a leaf node. This loop navigates the cursor so that it
  69297. ** points to the first interior cell that it points to the parent of
  69298. ** the next page in the tree that has not yet been visited. The
  69299. ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
  69300. ** of the page, or to the number of cells in the page if the next page
  69301. ** to visit is the right-child of its parent.
  69302. **
  69303. ** If all pages in the tree have been visited, return SQLITE_OK to the
  69304. ** caller.
  69305. */
  69306. if( pPage->leaf ){
  69307. do {
  69308. if( pCur->iPage==0 ){
  69309. /* All pages of the b-tree have been visited. Return successfully. */
  69310. *pnEntry = nEntry;
  69311. return moveToRoot(pCur);
  69312. }
  69313. moveToParent(pCur);
  69314. }while ( pCur->ix>=pCur->pPage->nCell );
  69315. pCur->ix++;
  69316. pPage = pCur->pPage;
  69317. }
  69318. /* Descend to the child node of the cell that the cursor currently
  69319. ** points at. This is the right-child if (iIdx==pPage->nCell).
  69320. */
  69321. iIdx = pCur->ix;
  69322. if( iIdx==pPage->nCell ){
  69323. rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
  69324. }else{
  69325. rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
  69326. }
  69327. }
  69328. /* An error has occurred. Return an error code. */
  69329. return rc;
  69330. }
  69331. /*
  69332. ** Return the pager associated with a BTree. This routine is used for
  69333. ** testing and debugging only.
  69334. */
  69335. SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){
  69336. return p->pBt->pPager;
  69337. }
  69338. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  69339. /*
  69340. ** Append a message to the error message string.
  69341. */
  69342. static void checkAppendMsg(
  69343. IntegrityCk *pCheck,
  69344. const char *zFormat,
  69345. ...
  69346. ){
  69347. va_list ap;
  69348. if( !pCheck->mxErr ) return;
  69349. pCheck->mxErr--;
  69350. pCheck->nErr++;
  69351. va_start(ap, zFormat);
  69352. if( pCheck->errMsg.nChar ){
  69353. sqlite3_str_append(&pCheck->errMsg, "\n", 1);
  69354. }
  69355. if( pCheck->zPfx ){
  69356. sqlite3_str_appendf(&pCheck->errMsg, pCheck->zPfx, pCheck->v1, pCheck->v2);
  69357. }
  69358. sqlite3_str_vappendf(&pCheck->errMsg, zFormat, ap);
  69359. va_end(ap);
  69360. if( pCheck->errMsg.accError==SQLITE_NOMEM ){
  69361. pCheck->mallocFailed = 1;
  69362. }
  69363. }
  69364. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  69365. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  69366. /*
  69367. ** Return non-zero if the bit in the IntegrityCk.aPgRef[] array that
  69368. ** corresponds to page iPg is already set.
  69369. */
  69370. static int getPageReferenced(IntegrityCk *pCheck, Pgno iPg){
  69371. assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
  69372. return (pCheck->aPgRef[iPg/8] & (1 << (iPg & 0x07)));
  69373. }
  69374. /*
  69375. ** Set the bit in the IntegrityCk.aPgRef[] array that corresponds to page iPg.
  69376. */
  69377. static void setPageReferenced(IntegrityCk *pCheck, Pgno iPg){
  69378. assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
  69379. pCheck->aPgRef[iPg/8] |= (1 << (iPg & 0x07));
  69380. }
  69381. /*
  69382. ** Add 1 to the reference count for page iPage. If this is the second
  69383. ** reference to the page, add an error message to pCheck->zErrMsg.
  69384. ** Return 1 if there are 2 or more references to the page and 0 if
  69385. ** if this is the first reference to the page.
  69386. **
  69387. ** Also check that the page number is in bounds.
  69388. */
  69389. static int checkRef(IntegrityCk *pCheck, Pgno iPage){
  69390. if( iPage>pCheck->nPage || iPage==0 ){
  69391. checkAppendMsg(pCheck, "invalid page number %d", iPage);
  69392. return 1;
  69393. }
  69394. if( getPageReferenced(pCheck, iPage) ){
  69395. checkAppendMsg(pCheck, "2nd reference to page %d", iPage);
  69396. return 1;
  69397. }
  69398. if( AtomicLoad(&pCheck->db->u1.isInterrupted) ) return 1;
  69399. setPageReferenced(pCheck, iPage);
  69400. return 0;
  69401. }
  69402. #ifndef SQLITE_OMIT_AUTOVACUUM
  69403. /*
  69404. ** Check that the entry in the pointer-map for page iChild maps to
  69405. ** page iParent, pointer type ptrType. If not, append an error message
  69406. ** to pCheck.
  69407. */
  69408. static void checkPtrmap(
  69409. IntegrityCk *pCheck, /* Integrity check context */
  69410. Pgno iChild, /* Child page number */
  69411. u8 eType, /* Expected pointer map type */
  69412. Pgno iParent /* Expected pointer map parent page number */
  69413. ){
  69414. int rc;
  69415. u8 ePtrmapType;
  69416. Pgno iPtrmapParent;
  69417. rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
  69418. if( rc!=SQLITE_OK ){
  69419. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
  69420. checkAppendMsg(pCheck, "Failed to read ptrmap key=%d", iChild);
  69421. return;
  69422. }
  69423. if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
  69424. checkAppendMsg(pCheck,
  69425. "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
  69426. iChild, eType, iParent, ePtrmapType, iPtrmapParent);
  69427. }
  69428. }
  69429. #endif
  69430. /*
  69431. ** Check the integrity of the freelist or of an overflow page list.
  69432. ** Verify that the number of pages on the list is N.
  69433. */
  69434. static void checkList(
  69435. IntegrityCk *pCheck, /* Integrity checking context */
  69436. int isFreeList, /* True for a freelist. False for overflow page list */
  69437. int iPage, /* Page number for first page in the list */
  69438. u32 N /* Expected number of pages in the list */
  69439. ){
  69440. int i;
  69441. u32 expected = N;
  69442. int nErrAtStart = pCheck->nErr;
  69443. while( iPage!=0 && pCheck->mxErr ){
  69444. DbPage *pOvflPage;
  69445. unsigned char *pOvflData;
  69446. if( checkRef(pCheck, iPage) ) break;
  69447. N--;
  69448. if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage, 0) ){
  69449. checkAppendMsg(pCheck, "failed to get page %d", iPage);
  69450. break;
  69451. }
  69452. pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
  69453. if( isFreeList ){
  69454. u32 n = (u32)get4byte(&pOvflData[4]);
  69455. #ifndef SQLITE_OMIT_AUTOVACUUM
  69456. if( pCheck->pBt->autoVacuum ){
  69457. checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0);
  69458. }
  69459. #endif
  69460. if( n>pCheck->pBt->usableSize/4-2 ){
  69461. checkAppendMsg(pCheck,
  69462. "freelist leaf count too big on page %d", iPage);
  69463. N--;
  69464. }else{
  69465. for(i=0; i<(int)n; i++){
  69466. Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
  69467. #ifndef SQLITE_OMIT_AUTOVACUUM
  69468. if( pCheck->pBt->autoVacuum ){
  69469. checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0);
  69470. }
  69471. #endif
  69472. checkRef(pCheck, iFreePage);
  69473. }
  69474. N -= n;
  69475. }
  69476. }
  69477. #ifndef SQLITE_OMIT_AUTOVACUUM
  69478. else{
  69479. /* If this database supports auto-vacuum and iPage is not the last
  69480. ** page in this overflow list, check that the pointer-map entry for
  69481. ** the following page matches iPage.
  69482. */
  69483. if( pCheck->pBt->autoVacuum && N>0 ){
  69484. i = get4byte(pOvflData);
  69485. checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage);
  69486. }
  69487. }
  69488. #endif
  69489. iPage = get4byte(pOvflData);
  69490. sqlite3PagerUnref(pOvflPage);
  69491. }
  69492. if( N && nErrAtStart==pCheck->nErr ){
  69493. checkAppendMsg(pCheck,
  69494. "%s is %d but should be %d",
  69495. isFreeList ? "size" : "overflow list length",
  69496. expected-N, expected);
  69497. }
  69498. }
  69499. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  69500. /*
  69501. ** An implementation of a min-heap.
  69502. **
  69503. ** aHeap[0] is the number of elements on the heap. aHeap[1] is the
  69504. ** root element. The daughter nodes of aHeap[N] are aHeap[N*2]
  69505. ** and aHeap[N*2+1].
  69506. **
  69507. ** The heap property is this: Every node is less than or equal to both
  69508. ** of its daughter nodes. A consequence of the heap property is that the
  69509. ** root node aHeap[1] is always the minimum value currently in the heap.
  69510. **
  69511. ** The btreeHeapInsert() routine inserts an unsigned 32-bit number onto
  69512. ** the heap, preserving the heap property. The btreeHeapPull() routine
  69513. ** removes the root element from the heap (the minimum value in the heap)
  69514. ** and then moves other nodes around as necessary to preserve the heap
  69515. ** property.
  69516. **
  69517. ** This heap is used for cell overlap and coverage testing. Each u32
  69518. ** entry represents the span of a cell or freeblock on a btree page.
  69519. ** The upper 16 bits are the index of the first byte of a range and the
  69520. ** lower 16 bits are the index of the last byte of that range.
  69521. */
  69522. static void btreeHeapInsert(u32 *aHeap, u32 x){
  69523. u32 j, i = ++aHeap[0];
  69524. aHeap[i] = x;
  69525. while( (j = i/2)>0 && aHeap[j]>aHeap[i] ){
  69526. x = aHeap[j];
  69527. aHeap[j] = aHeap[i];
  69528. aHeap[i] = x;
  69529. i = j;
  69530. }
  69531. }
  69532. static int btreeHeapPull(u32 *aHeap, u32 *pOut){
  69533. u32 j, i, x;
  69534. if( (x = aHeap[0])==0 ) return 0;
  69535. *pOut = aHeap[1];
  69536. aHeap[1] = aHeap[x];
  69537. aHeap[x] = 0xffffffff;
  69538. aHeap[0]--;
  69539. i = 1;
  69540. while( (j = i*2)<=aHeap[0] ){
  69541. if( aHeap[j]>aHeap[j+1] ) j++;
  69542. if( aHeap[i]<aHeap[j] ) break;
  69543. x = aHeap[i];
  69544. aHeap[i] = aHeap[j];
  69545. aHeap[j] = x;
  69546. i = j;
  69547. }
  69548. return 1;
  69549. }
  69550. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  69551. /*
  69552. ** Do various sanity checks on a single page of a tree. Return
  69553. ** the tree depth. Root pages return 0. Parents of root pages
  69554. ** return 1, and so forth.
  69555. **
  69556. ** These checks are done:
  69557. **
  69558. ** 1. Make sure that cells and freeblocks do not overlap
  69559. ** but combine to completely cover the page.
  69560. ** 2. Make sure integer cell keys are in order.
  69561. ** 3. Check the integrity of overflow pages.
  69562. ** 4. Recursively call checkTreePage on all children.
  69563. ** 5. Verify that the depth of all children is the same.
  69564. */
  69565. static int checkTreePage(
  69566. IntegrityCk *pCheck, /* Context for the sanity check */
  69567. int iPage, /* Page number of the page to check */
  69568. i64 *piMinKey, /* Write minimum integer primary key here */
  69569. i64 maxKey /* Error if integer primary key greater than this */
  69570. ){
  69571. MemPage *pPage = 0; /* The page being analyzed */
  69572. int i; /* Loop counter */
  69573. int rc; /* Result code from subroutine call */
  69574. int depth = -1, d2; /* Depth of a subtree */
  69575. int pgno; /* Page number */
  69576. int nFrag; /* Number of fragmented bytes on the page */
  69577. int hdr; /* Offset to the page header */
  69578. int cellStart; /* Offset to the start of the cell pointer array */
  69579. int nCell; /* Number of cells */
  69580. int doCoverageCheck = 1; /* True if cell coverage checking should be done */
  69581. int keyCanBeEqual = 1; /* True if IPK can be equal to maxKey
  69582. ** False if IPK must be strictly less than maxKey */
  69583. u8 *data; /* Page content */
  69584. u8 *pCell; /* Cell content */
  69585. u8 *pCellIdx; /* Next element of the cell pointer array */
  69586. BtShared *pBt; /* The BtShared object that owns pPage */
  69587. u32 pc; /* Address of a cell */
  69588. u32 usableSize; /* Usable size of the page */
  69589. u32 contentOffset; /* Offset to the start of the cell content area */
  69590. u32 *heap = 0; /* Min-heap used for checking cell coverage */
  69591. u32 x, prev = 0; /* Next and previous entry on the min-heap */
  69592. const char *saved_zPfx = pCheck->zPfx;
  69593. int saved_v1 = pCheck->v1;
  69594. int saved_v2 = pCheck->v2;
  69595. u8 savedIsInit = 0;
  69596. /* Check that the page exists
  69597. */
  69598. pBt = pCheck->pBt;
  69599. usableSize = pBt->usableSize;
  69600. if( iPage==0 ) return 0;
  69601. if( checkRef(pCheck, iPage) ) return 0;
  69602. pCheck->zPfx = "Page %d: ";
  69603. pCheck->v1 = iPage;
  69604. if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
  69605. checkAppendMsg(pCheck,
  69606. "unable to get the page. error code=%d", rc);
  69607. goto end_of_check;
  69608. }
  69609. /* Clear MemPage.isInit to make sure the corruption detection code in
  69610. ** btreeInitPage() is executed. */
  69611. savedIsInit = pPage->isInit;
  69612. pPage->isInit = 0;
  69613. if( (rc = btreeInitPage(pPage))!=0 ){
  69614. assert( rc==SQLITE_CORRUPT ); /* The only possible error from InitPage */
  69615. checkAppendMsg(pCheck,
  69616. "btreeInitPage() returns error code %d", rc);
  69617. goto end_of_check;
  69618. }
  69619. if( (rc = btreeComputeFreeSpace(pPage))!=0 ){
  69620. assert( rc==SQLITE_CORRUPT );
  69621. checkAppendMsg(pCheck, "free space corruption", rc);
  69622. goto end_of_check;
  69623. }
  69624. data = pPage->aData;
  69625. hdr = pPage->hdrOffset;
  69626. /* Set up for cell analysis */
  69627. pCheck->zPfx = "On tree page %d cell %d: ";
  69628. contentOffset = get2byteNotZero(&data[hdr+5]);
  69629. assert( contentOffset<=usableSize ); /* Enforced by btreeInitPage() */
  69630. /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
  69631. ** number of cells on the page. */
  69632. nCell = get2byte(&data[hdr+3]);
  69633. assert( pPage->nCell==nCell );
  69634. /* EVIDENCE-OF: R-23882-45353 The cell pointer array of a b-tree page
  69635. ** immediately follows the b-tree page header. */
  69636. cellStart = hdr + 12 - 4*pPage->leaf;
  69637. assert( pPage->aCellIdx==&data[cellStart] );
  69638. pCellIdx = &data[cellStart + 2*(nCell-1)];
  69639. if( !pPage->leaf ){
  69640. /* Analyze the right-child page of internal pages */
  69641. pgno = get4byte(&data[hdr+8]);
  69642. #ifndef SQLITE_OMIT_AUTOVACUUM
  69643. if( pBt->autoVacuum ){
  69644. pCheck->zPfx = "On page %d at right child: ";
  69645. checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
  69646. }
  69647. #endif
  69648. depth = checkTreePage(pCheck, pgno, &maxKey, maxKey);
  69649. keyCanBeEqual = 0;
  69650. }else{
  69651. /* For leaf pages, the coverage check will occur in the same loop
  69652. ** as the other cell checks, so initialize the heap. */
  69653. heap = pCheck->heap;
  69654. heap[0] = 0;
  69655. }
  69656. /* EVIDENCE-OF: R-02776-14802 The cell pointer array consists of K 2-byte
  69657. ** integer offsets to the cell contents. */
  69658. for(i=nCell-1; i>=0 && pCheck->mxErr; i--){
  69659. CellInfo info;
  69660. /* Check cell size */
  69661. pCheck->v2 = i;
  69662. assert( pCellIdx==&data[cellStart + i*2] );
  69663. pc = get2byteAligned(pCellIdx);
  69664. pCellIdx -= 2;
  69665. if( pc<contentOffset || pc>usableSize-4 ){
  69666. checkAppendMsg(pCheck, "Offset %d out of range %d..%d",
  69667. pc, contentOffset, usableSize-4);
  69668. doCoverageCheck = 0;
  69669. continue;
  69670. }
  69671. pCell = &data[pc];
  69672. pPage->xParseCell(pPage, pCell, &info);
  69673. if( pc+info.nSize>usableSize ){
  69674. checkAppendMsg(pCheck, "Extends off end of page");
  69675. doCoverageCheck = 0;
  69676. continue;
  69677. }
  69678. /* Check for integer primary key out of range */
  69679. if( pPage->intKey ){
  69680. if( keyCanBeEqual ? (info.nKey > maxKey) : (info.nKey >= maxKey) ){
  69681. checkAppendMsg(pCheck, "Rowid %lld out of order", info.nKey);
  69682. }
  69683. maxKey = info.nKey;
  69684. keyCanBeEqual = 0; /* Only the first key on the page may ==maxKey */
  69685. }
  69686. /* Check the content overflow list */
  69687. if( info.nPayload>info.nLocal ){
  69688. u32 nPage; /* Number of pages on the overflow chain */
  69689. Pgno pgnoOvfl; /* First page of the overflow chain */
  69690. assert( pc + info.nSize - 4 <= usableSize );
  69691. nPage = (info.nPayload - info.nLocal + usableSize - 5)/(usableSize - 4);
  69692. pgnoOvfl = get4byte(&pCell[info.nSize - 4]);
  69693. #ifndef SQLITE_OMIT_AUTOVACUUM
  69694. if( pBt->autoVacuum ){
  69695. checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage);
  69696. }
  69697. #endif
  69698. checkList(pCheck, 0, pgnoOvfl, nPage);
  69699. }
  69700. if( !pPage->leaf ){
  69701. /* Check sanity of left child page for internal pages */
  69702. pgno = get4byte(pCell);
  69703. #ifndef SQLITE_OMIT_AUTOVACUUM
  69704. if( pBt->autoVacuum ){
  69705. checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
  69706. }
  69707. #endif
  69708. d2 = checkTreePage(pCheck, pgno, &maxKey, maxKey);
  69709. keyCanBeEqual = 0;
  69710. if( d2!=depth ){
  69711. checkAppendMsg(pCheck, "Child page depth differs");
  69712. depth = d2;
  69713. }
  69714. }else{
  69715. /* Populate the coverage-checking heap for leaf pages */
  69716. btreeHeapInsert(heap, (pc<<16)|(pc+info.nSize-1));
  69717. }
  69718. }
  69719. *piMinKey = maxKey;
  69720. /* Check for complete coverage of the page
  69721. */
  69722. pCheck->zPfx = 0;
  69723. if( doCoverageCheck && pCheck->mxErr>0 ){
  69724. /* For leaf pages, the min-heap has already been initialized and the
  69725. ** cells have already been inserted. But for internal pages, that has
  69726. ** not yet been done, so do it now */
  69727. if( !pPage->leaf ){
  69728. heap = pCheck->heap;
  69729. heap[0] = 0;
  69730. for(i=nCell-1; i>=0; i--){
  69731. u32 size;
  69732. pc = get2byteAligned(&data[cellStart+i*2]);
  69733. size = pPage->xCellSize(pPage, &data[pc]);
  69734. btreeHeapInsert(heap, (pc<<16)|(pc+size-1));
  69735. }
  69736. }
  69737. /* Add the freeblocks to the min-heap
  69738. **
  69739. ** EVIDENCE-OF: R-20690-50594 The second field of the b-tree page header
  69740. ** is the offset of the first freeblock, or zero if there are no
  69741. ** freeblocks on the page.
  69742. */
  69743. i = get2byte(&data[hdr+1]);
  69744. while( i>0 ){
  69745. int size, j;
  69746. assert( (u32)i<=usableSize-4 ); /* Enforced by btreeComputeFreeSpace() */
  69747. size = get2byte(&data[i+2]);
  69748. assert( (u32)(i+size)<=usableSize ); /* due to btreeComputeFreeSpace() */
  69749. btreeHeapInsert(heap, (((u32)i)<<16)|(i+size-1));
  69750. /* EVIDENCE-OF: R-58208-19414 The first 2 bytes of a freeblock are a
  69751. ** big-endian integer which is the offset in the b-tree page of the next
  69752. ** freeblock in the chain, or zero if the freeblock is the last on the
  69753. ** chain. */
  69754. j = get2byte(&data[i]);
  69755. /* EVIDENCE-OF: R-06866-39125 Freeblocks are always connected in order of
  69756. ** increasing offset. */
  69757. assert( j==0 || j>i+size ); /* Enforced by btreeComputeFreeSpace() */
  69758. assert( (u32)j<=usableSize-4 ); /* Enforced by btreeComputeFreeSpace() */
  69759. i = j;
  69760. }
  69761. /* Analyze the min-heap looking for overlap between cells and/or
  69762. ** freeblocks, and counting the number of untracked bytes in nFrag.
  69763. **
  69764. ** Each min-heap entry is of the form: (start_address<<16)|end_address.
  69765. ** There is an implied first entry the covers the page header, the cell
  69766. ** pointer index, and the gap between the cell pointer index and the start
  69767. ** of cell content.
  69768. **
  69769. ** The loop below pulls entries from the min-heap in order and compares
  69770. ** the start_address against the previous end_address. If there is an
  69771. ** overlap, that means bytes are used multiple times. If there is a gap,
  69772. ** that gap is added to the fragmentation count.
  69773. */
  69774. nFrag = 0;
  69775. prev = contentOffset - 1; /* Implied first min-heap entry */
  69776. while( btreeHeapPull(heap,&x) ){
  69777. if( (prev&0xffff)>=(x>>16) ){
  69778. checkAppendMsg(pCheck,
  69779. "Multiple uses for byte %u of page %d", x>>16, iPage);
  69780. break;
  69781. }else{
  69782. nFrag += (x>>16) - (prev&0xffff) - 1;
  69783. prev = x;
  69784. }
  69785. }
  69786. nFrag += usableSize - (prev&0xffff) - 1;
  69787. /* EVIDENCE-OF: R-43263-13491 The total number of bytes in all fragments
  69788. ** is stored in the fifth field of the b-tree page header.
  69789. ** EVIDENCE-OF: R-07161-27322 The one-byte integer at offset 7 gives the
  69790. ** number of fragmented free bytes within the cell content area.
  69791. */
  69792. if( heap[0]==0 && nFrag!=data[hdr+7] ){
  69793. checkAppendMsg(pCheck,
  69794. "Fragmentation of %d bytes reported as %d on page %d",
  69795. nFrag, data[hdr+7], iPage);
  69796. }
  69797. }
  69798. end_of_check:
  69799. if( !doCoverageCheck ) pPage->isInit = savedIsInit;
  69800. releasePage(pPage);
  69801. pCheck->zPfx = saved_zPfx;
  69802. pCheck->v1 = saved_v1;
  69803. pCheck->v2 = saved_v2;
  69804. return depth+1;
  69805. }
  69806. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  69807. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  69808. /*
  69809. ** This routine does a complete check of the given BTree file. aRoot[] is
  69810. ** an array of pages numbers were each page number is the root page of
  69811. ** a table. nRoot is the number of entries in aRoot.
  69812. **
  69813. ** A read-only or read-write transaction must be opened before calling
  69814. ** this function.
  69815. **
  69816. ** Write the number of error seen in *pnErr. Except for some memory
  69817. ** allocation errors, an error message held in memory obtained from
  69818. ** malloc is returned if *pnErr is non-zero. If *pnErr==0 then NULL is
  69819. ** returned. If a memory allocation error occurs, NULL is returned.
  69820. */
  69821. SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
  69822. sqlite3 *db, /* Database connection that is running the check */
  69823. Btree *p, /* The btree to be checked */
  69824. int *aRoot, /* An array of root pages numbers for individual trees */
  69825. int nRoot, /* Number of entries in aRoot[] */
  69826. int mxErr, /* Stop reporting errors after this many */
  69827. int *pnErr /* Write number of errors seen to this variable */
  69828. ){
  69829. Pgno i;
  69830. IntegrityCk sCheck;
  69831. BtShared *pBt = p->pBt;
  69832. u64 savedDbFlags = pBt->db->flags;
  69833. char zErr[100];
  69834. VVA_ONLY( int nRef );
  69835. sqlite3BtreeEnter(p);
  69836. assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
  69837. VVA_ONLY( nRef = sqlite3PagerRefcount(pBt->pPager) );
  69838. assert( nRef>=0 );
  69839. sCheck.db = db;
  69840. sCheck.pBt = pBt;
  69841. sCheck.pPager = pBt->pPager;
  69842. sCheck.nPage = btreePagecount(sCheck.pBt);
  69843. sCheck.mxErr = mxErr;
  69844. sCheck.nErr = 0;
  69845. sCheck.mallocFailed = 0;
  69846. sCheck.zPfx = 0;
  69847. sCheck.v1 = 0;
  69848. sCheck.v2 = 0;
  69849. sCheck.aPgRef = 0;
  69850. sCheck.heap = 0;
  69851. sqlite3StrAccumInit(&sCheck.errMsg, 0, zErr, sizeof(zErr), SQLITE_MAX_LENGTH);
  69852. sCheck.errMsg.printfFlags = SQLITE_PRINTF_INTERNAL;
  69853. if( sCheck.nPage==0 ){
  69854. goto integrity_ck_cleanup;
  69855. }
  69856. sCheck.aPgRef = sqlite3MallocZero((sCheck.nPage / 8)+ 1);
  69857. if( !sCheck.aPgRef ){
  69858. sCheck.mallocFailed = 1;
  69859. goto integrity_ck_cleanup;
  69860. }
  69861. sCheck.heap = (u32*)sqlite3PageMalloc( pBt->pageSize );
  69862. if( sCheck.heap==0 ){
  69863. sCheck.mallocFailed = 1;
  69864. goto integrity_ck_cleanup;
  69865. }
  69866. i = PENDING_BYTE_PAGE(pBt);
  69867. if( i<=sCheck.nPage ) setPageReferenced(&sCheck, i);
  69868. /* Check the integrity of the freelist
  69869. */
  69870. sCheck.zPfx = "Main freelist: ";
  69871. checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
  69872. get4byte(&pBt->pPage1->aData[36]));
  69873. sCheck.zPfx = 0;
  69874. /* Check all the tables.
  69875. */
  69876. #ifndef SQLITE_OMIT_AUTOVACUUM
  69877. if( pBt->autoVacuum ){
  69878. int mx = 0;
  69879. int mxInHdr;
  69880. for(i=0; (int)i<nRoot; i++) if( mx<aRoot[i] ) mx = aRoot[i];
  69881. mxInHdr = get4byte(&pBt->pPage1->aData[52]);
  69882. if( mx!=mxInHdr ){
  69883. checkAppendMsg(&sCheck,
  69884. "max rootpage (%d) disagrees with header (%d)",
  69885. mx, mxInHdr
  69886. );
  69887. }
  69888. }else if( get4byte(&pBt->pPage1->aData[64])!=0 ){
  69889. checkAppendMsg(&sCheck,
  69890. "incremental_vacuum enabled with a max rootpage of zero"
  69891. );
  69892. }
  69893. #endif
  69894. testcase( pBt->db->flags & SQLITE_CellSizeCk );
  69895. pBt->db->flags &= ~(u64)SQLITE_CellSizeCk;
  69896. for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
  69897. i64 notUsed;
  69898. if( aRoot[i]==0 ) continue;
  69899. #ifndef SQLITE_OMIT_AUTOVACUUM
  69900. if( pBt->autoVacuum && aRoot[i]>1 ){
  69901. checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0);
  69902. }
  69903. #endif
  69904. checkTreePage(&sCheck, aRoot[i], &notUsed, LARGEST_INT64);
  69905. }
  69906. pBt->db->flags = savedDbFlags;
  69907. /* Make sure every page in the file is referenced
  69908. */
  69909. for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
  69910. #ifdef SQLITE_OMIT_AUTOVACUUM
  69911. if( getPageReferenced(&sCheck, i)==0 ){
  69912. checkAppendMsg(&sCheck, "Page %d is never used", i);
  69913. }
  69914. #else
  69915. /* If the database supports auto-vacuum, make sure no tables contain
  69916. ** references to pointer-map pages.
  69917. */
  69918. if( getPageReferenced(&sCheck, i)==0 &&
  69919. (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
  69920. checkAppendMsg(&sCheck, "Page %d is never used", i);
  69921. }
  69922. if( getPageReferenced(&sCheck, i)!=0 &&
  69923. (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
  69924. checkAppendMsg(&sCheck, "Pointer map page %d is referenced", i);
  69925. }
  69926. #endif
  69927. }
  69928. /* Clean up and report errors.
  69929. */
  69930. integrity_ck_cleanup:
  69931. sqlite3PageFree(sCheck.heap);
  69932. sqlite3_free(sCheck.aPgRef);
  69933. if( sCheck.mallocFailed ){
  69934. sqlite3_str_reset(&sCheck.errMsg);
  69935. sCheck.nErr++;
  69936. }
  69937. *pnErr = sCheck.nErr;
  69938. if( sCheck.nErr==0 ) sqlite3_str_reset(&sCheck.errMsg);
  69939. /* Make sure this analysis did not leave any unref() pages. */
  69940. assert( nRef==sqlite3PagerRefcount(pBt->pPager) );
  69941. sqlite3BtreeLeave(p);
  69942. return sqlite3StrAccumFinish(&sCheck.errMsg);
  69943. }
  69944. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  69945. /*
  69946. ** Return the full pathname of the underlying database file. Return
  69947. ** an empty string if the database is in-memory or a TEMP database.
  69948. **
  69949. ** The pager filename is invariant as long as the pager is
  69950. ** open so it is safe to access without the BtShared mutex.
  69951. */
  69952. SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){
  69953. assert( p->pBt->pPager!=0 );
  69954. return sqlite3PagerFilename(p->pBt->pPager, 1);
  69955. }
  69956. /*
  69957. ** Return the pathname of the journal file for this database. The return
  69958. ** value of this routine is the same regardless of whether the journal file
  69959. ** has been created or not.
  69960. **
  69961. ** The pager journal filename is invariant as long as the pager is
  69962. ** open so it is safe to access without the BtShared mutex.
  69963. */
  69964. SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){
  69965. assert( p->pBt->pPager!=0 );
  69966. return sqlite3PagerJournalname(p->pBt->pPager);
  69967. }
  69968. /*
  69969. ** Return non-zero if a transaction is active.
  69970. */
  69971. SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){
  69972. assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
  69973. return (p && (p->inTrans==TRANS_WRITE));
  69974. }
  69975. #ifndef SQLITE_OMIT_WAL
  69976. /*
  69977. ** Run a checkpoint on the Btree passed as the first argument.
  69978. **
  69979. ** Return SQLITE_LOCKED if this or any other connection has an open
  69980. ** transaction on the shared-cache the argument Btree is connected to.
  69981. **
  69982. ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
  69983. */
  69984. SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
  69985. int rc = SQLITE_OK;
  69986. if( p ){
  69987. BtShared *pBt = p->pBt;
  69988. sqlite3BtreeEnter(p);
  69989. if( pBt->inTransaction!=TRANS_NONE ){
  69990. rc = SQLITE_LOCKED;
  69991. }else{
  69992. rc = sqlite3PagerCheckpoint(pBt->pPager, p->db, eMode, pnLog, pnCkpt);
  69993. }
  69994. sqlite3BtreeLeave(p);
  69995. }
  69996. return rc;
  69997. }
  69998. #endif
  69999. /*
  70000. ** Return non-zero if a read (or write) transaction is active.
  70001. */
  70002. SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){
  70003. assert( p );
  70004. assert( sqlite3_mutex_held(p->db->mutex) );
  70005. return p->inTrans!=TRANS_NONE;
  70006. }
  70007. SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *p){
  70008. assert( p );
  70009. assert( sqlite3_mutex_held(p->db->mutex) );
  70010. return p->nBackup!=0;
  70011. }
  70012. /*
  70013. ** This function returns a pointer to a blob of memory associated with
  70014. ** a single shared-btree. The memory is used by client code for its own
  70015. ** purposes (for example, to store a high-level schema associated with
  70016. ** the shared-btree). The btree layer manages reference counting issues.
  70017. **
  70018. ** The first time this is called on a shared-btree, nBytes bytes of memory
  70019. ** are allocated, zeroed, and returned to the caller. For each subsequent
  70020. ** call the nBytes parameter is ignored and a pointer to the same blob
  70021. ** of memory returned.
  70022. **
  70023. ** If the nBytes parameter is 0 and the blob of memory has not yet been
  70024. ** allocated, a null pointer is returned. If the blob has already been
  70025. ** allocated, it is returned as normal.
  70026. **
  70027. ** Just before the shared-btree is closed, the function passed as the
  70028. ** xFree argument when the memory allocation was made is invoked on the
  70029. ** blob of allocated memory. The xFree function should not call sqlite3_free()
  70030. ** on the memory, the btree layer does that.
  70031. */
  70032. SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
  70033. BtShared *pBt = p->pBt;
  70034. sqlite3BtreeEnter(p);
  70035. if( !pBt->pSchema && nBytes ){
  70036. pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
  70037. pBt->xFreeSchema = xFree;
  70038. }
  70039. sqlite3BtreeLeave(p);
  70040. return pBt->pSchema;
  70041. }
  70042. /*
  70043. ** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
  70044. ** btree as the argument handle holds an exclusive lock on the
  70045. ** sqlite_master table. Otherwise SQLITE_OK.
  70046. */
  70047. SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){
  70048. int rc;
  70049. assert( sqlite3_mutex_held(p->db->mutex) );
  70050. sqlite3BtreeEnter(p);
  70051. rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
  70052. assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
  70053. sqlite3BtreeLeave(p);
  70054. return rc;
  70055. }
  70056. #ifndef SQLITE_OMIT_SHARED_CACHE
  70057. /*
  70058. ** Obtain a lock on the table whose root page is iTab. The
  70059. ** lock is a write lock if isWritelock is true or a read lock
  70060. ** if it is false.
  70061. */
  70062. SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
  70063. int rc = SQLITE_OK;
  70064. assert( p->inTrans!=TRANS_NONE );
  70065. if( p->sharable ){
  70066. u8 lockType = READ_LOCK + isWriteLock;
  70067. assert( READ_LOCK+1==WRITE_LOCK );
  70068. assert( isWriteLock==0 || isWriteLock==1 );
  70069. sqlite3BtreeEnter(p);
  70070. rc = querySharedCacheTableLock(p, iTab, lockType);
  70071. if( rc==SQLITE_OK ){
  70072. rc = setSharedCacheTableLock(p, iTab, lockType);
  70073. }
  70074. sqlite3BtreeLeave(p);
  70075. }
  70076. return rc;
  70077. }
  70078. #endif
  70079. #ifndef SQLITE_OMIT_INCRBLOB
  70080. /*
  70081. ** Argument pCsr must be a cursor opened for writing on an
  70082. ** INTKEY table currently pointing at a valid table entry.
  70083. ** This function modifies the data stored as part of that entry.
  70084. **
  70085. ** Only the data content may only be modified, it is not possible to
  70086. ** change the length of the data stored. If this function is called with
  70087. ** parameters that attempt to write past the end of the existing data,
  70088. ** no modifications are made and SQLITE_CORRUPT is returned.
  70089. */
  70090. SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
  70091. int rc;
  70092. assert( cursorOwnsBtShared(pCsr) );
  70093. assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
  70094. assert( pCsr->curFlags & BTCF_Incrblob );
  70095. rc = restoreCursorPosition(pCsr);
  70096. if( rc!=SQLITE_OK ){
  70097. return rc;
  70098. }
  70099. assert( pCsr->eState!=CURSOR_REQUIRESEEK );
  70100. if( pCsr->eState!=CURSOR_VALID ){
  70101. return SQLITE_ABORT;
  70102. }
  70103. /* Save the positions of all other cursors open on this table. This is
  70104. ** required in case any of them are holding references to an xFetch
  70105. ** version of the b-tree page modified by the accessPayload call below.
  70106. **
  70107. ** Note that pCsr must be open on a INTKEY table and saveCursorPosition()
  70108. ** and hence saveAllCursors() cannot fail on a BTREE_INTKEY table, hence
  70109. ** saveAllCursors can only return SQLITE_OK.
  70110. */
  70111. VVA_ONLY(rc =) saveAllCursors(pCsr->pBt, pCsr->pgnoRoot, pCsr);
  70112. assert( rc==SQLITE_OK );
  70113. /* Check some assumptions:
  70114. ** (a) the cursor is open for writing,
  70115. ** (b) there is a read/write transaction open,
  70116. ** (c) the connection holds a write-lock on the table (if required),
  70117. ** (d) there are no conflicting read-locks, and
  70118. ** (e) the cursor points at a valid row of an intKey table.
  70119. */
  70120. if( (pCsr->curFlags & BTCF_WriteFlag)==0 ){
  70121. return SQLITE_READONLY;
  70122. }
  70123. assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0
  70124. && pCsr->pBt->inTransaction==TRANS_WRITE );
  70125. assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
  70126. assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
  70127. assert( pCsr->pPage->intKey );
  70128. return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
  70129. }
  70130. /*
  70131. ** Mark this cursor as an incremental blob cursor.
  70132. */
  70133. SQLITE_PRIVATE void sqlite3BtreeIncrblobCursor(BtCursor *pCur){
  70134. pCur->curFlags |= BTCF_Incrblob;
  70135. pCur->pBtree->hasIncrblobCur = 1;
  70136. }
  70137. #endif
  70138. /*
  70139. ** Set both the "read version" (single byte at byte offset 18) and
  70140. ** "write version" (single byte at byte offset 19) fields in the database
  70141. ** header to iVersion.
  70142. */
  70143. SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
  70144. BtShared *pBt = pBtree->pBt;
  70145. int rc; /* Return code */
  70146. assert( iVersion==1 || iVersion==2 );
  70147. /* If setting the version fields to 1, do not automatically open the
  70148. ** WAL connection, even if the version fields are currently set to 2.
  70149. */
  70150. pBt->btsFlags &= ~BTS_NO_WAL;
  70151. if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL;
  70152. rc = sqlite3BtreeBeginTrans(pBtree, 0, 0);
  70153. if( rc==SQLITE_OK ){
  70154. u8 *aData = pBt->pPage1->aData;
  70155. if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
  70156. rc = sqlite3BtreeBeginTrans(pBtree, 2, 0);
  70157. if( rc==SQLITE_OK ){
  70158. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  70159. if( rc==SQLITE_OK ){
  70160. aData[18] = (u8)iVersion;
  70161. aData[19] = (u8)iVersion;
  70162. }
  70163. }
  70164. }
  70165. }
  70166. pBt->btsFlags &= ~BTS_NO_WAL;
  70167. return rc;
  70168. }
  70169. /*
  70170. ** Return true if the cursor has a hint specified. This routine is
  70171. ** only used from within assert() statements
  70172. */
  70173. SQLITE_PRIVATE int sqlite3BtreeCursorHasHint(BtCursor *pCsr, unsigned int mask){
  70174. return (pCsr->hints & mask)!=0;
  70175. }
  70176. /*
  70177. ** Return true if the given Btree is read-only.
  70178. */
  70179. SQLITE_PRIVATE int sqlite3BtreeIsReadonly(Btree *p){
  70180. return (p->pBt->btsFlags & BTS_READ_ONLY)!=0;
  70181. }
  70182. /*
  70183. ** Return the size of the header added to each page by this module.
  70184. */
  70185. SQLITE_PRIVATE int sqlite3HeaderSizeBtree(void){ return ROUND8(sizeof(MemPage)); }
  70186. #if !defined(SQLITE_OMIT_SHARED_CACHE)
  70187. /*
  70188. ** Return true if the Btree passed as the only argument is sharable.
  70189. */
  70190. SQLITE_PRIVATE int sqlite3BtreeSharable(Btree *p){
  70191. return p->sharable;
  70192. }
  70193. /*
  70194. ** Return the number of connections to the BtShared object accessed by
  70195. ** the Btree handle passed as the only argument. For private caches
  70196. ** this is always 1. For shared caches it may be 1 or greater.
  70197. */
  70198. SQLITE_PRIVATE int sqlite3BtreeConnectionCount(Btree *p){
  70199. testcase( p->sharable );
  70200. return p->pBt->nRef;
  70201. }
  70202. #endif
  70203. /************** End of btree.c ***********************************************/
  70204. /************** Begin file backup.c ******************************************/
  70205. /*
  70206. ** 2009 January 28
  70207. **
  70208. ** The author disclaims copyright to this source code. In place of
  70209. ** a legal notice, here is a blessing:
  70210. **
  70211. ** May you do good and not evil.
  70212. ** May you find forgiveness for yourself and forgive others.
  70213. ** May you share freely, never taking more than you give.
  70214. **
  70215. *************************************************************************
  70216. ** This file contains the implementation of the sqlite3_backup_XXX()
  70217. ** API functions and the related features.
  70218. */
  70219. /* #include "sqliteInt.h" */
  70220. /* #include "btreeInt.h" */
  70221. /*
  70222. ** Structure allocated for each backup operation.
  70223. */
  70224. struct sqlite3_backup {
  70225. sqlite3* pDestDb; /* Destination database handle */
  70226. Btree *pDest; /* Destination b-tree file */
  70227. u32 iDestSchema; /* Original schema cookie in destination */
  70228. int bDestLocked; /* True once a write-transaction is open on pDest */
  70229. Pgno iNext; /* Page number of the next source page to copy */
  70230. sqlite3* pSrcDb; /* Source database handle */
  70231. Btree *pSrc; /* Source b-tree file */
  70232. int rc; /* Backup process error code */
  70233. /* These two variables are set by every call to backup_step(). They are
  70234. ** read by calls to backup_remaining() and backup_pagecount().
  70235. */
  70236. Pgno nRemaining; /* Number of pages left to copy */
  70237. Pgno nPagecount; /* Total number of pages to copy */
  70238. int isAttached; /* True once backup has been registered with pager */
  70239. sqlite3_backup *pNext; /* Next backup associated with source pager */
  70240. };
  70241. /*
  70242. ** THREAD SAFETY NOTES:
  70243. **
  70244. ** Once it has been created using backup_init(), a single sqlite3_backup
  70245. ** structure may be accessed via two groups of thread-safe entry points:
  70246. **
  70247. ** * Via the sqlite3_backup_XXX() API function backup_step() and
  70248. ** backup_finish(). Both these functions obtain the source database
  70249. ** handle mutex and the mutex associated with the source BtShared
  70250. ** structure, in that order.
  70251. **
  70252. ** * Via the BackupUpdate() and BackupRestart() functions, which are
  70253. ** invoked by the pager layer to report various state changes in
  70254. ** the page cache associated with the source database. The mutex
  70255. ** associated with the source database BtShared structure will always
  70256. ** be held when either of these functions are invoked.
  70257. **
  70258. ** The other sqlite3_backup_XXX() API functions, backup_remaining() and
  70259. ** backup_pagecount() are not thread-safe functions. If they are called
  70260. ** while some other thread is calling backup_step() or backup_finish(),
  70261. ** the values returned may be invalid. There is no way for a call to
  70262. ** BackupUpdate() or BackupRestart() to interfere with backup_remaining()
  70263. ** or backup_pagecount().
  70264. **
  70265. ** Depending on the SQLite configuration, the database handles and/or
  70266. ** the Btree objects may have their own mutexes that require locking.
  70267. ** Non-sharable Btrees (in-memory databases for example), do not have
  70268. ** associated mutexes.
  70269. */
  70270. /*
  70271. ** Return a pointer corresponding to database zDb (i.e. "main", "temp")
  70272. ** in connection handle pDb. If such a database cannot be found, return
  70273. ** a NULL pointer and write an error message to pErrorDb.
  70274. **
  70275. ** If the "temp" database is requested, it may need to be opened by this
  70276. ** function. If an error occurs while doing so, return 0 and write an
  70277. ** error message to pErrorDb.
  70278. */
  70279. static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){
  70280. int i = sqlite3FindDbName(pDb, zDb);
  70281. if( i==1 ){
  70282. Parse sParse;
  70283. int rc = 0;
  70284. memset(&sParse, 0, sizeof(sParse));
  70285. sParse.db = pDb;
  70286. if( sqlite3OpenTempDatabase(&sParse) ){
  70287. sqlite3ErrorWithMsg(pErrorDb, sParse.rc, "%s", sParse.zErrMsg);
  70288. rc = SQLITE_ERROR;
  70289. }
  70290. sqlite3DbFree(pErrorDb, sParse.zErrMsg);
  70291. sqlite3ParserReset(&sParse);
  70292. if( rc ){
  70293. return 0;
  70294. }
  70295. }
  70296. if( i<0 ){
  70297. sqlite3ErrorWithMsg(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb);
  70298. return 0;
  70299. }
  70300. return pDb->aDb[i].pBt;
  70301. }
  70302. /*
  70303. ** Attempt to set the page size of the destination to match the page size
  70304. ** of the source.
  70305. */
  70306. static int setDestPgsz(sqlite3_backup *p){
  70307. int rc;
  70308. rc = sqlite3BtreeSetPageSize(p->pDest,sqlite3BtreeGetPageSize(p->pSrc),0,0);
  70309. return rc;
  70310. }
  70311. /*
  70312. ** Check that there is no open read-transaction on the b-tree passed as the
  70313. ** second argument. If there is not, return SQLITE_OK. Otherwise, if there
  70314. ** is an open read-transaction, return SQLITE_ERROR and leave an error
  70315. ** message in database handle db.
  70316. */
  70317. static int checkReadTransaction(sqlite3 *db, Btree *p){
  70318. if( sqlite3BtreeIsInReadTrans(p) ){
  70319. sqlite3ErrorWithMsg(db, SQLITE_ERROR, "destination database is in use");
  70320. return SQLITE_ERROR;
  70321. }
  70322. return SQLITE_OK;
  70323. }
  70324. /*
  70325. ** Create an sqlite3_backup process to copy the contents of zSrcDb from
  70326. ** connection handle pSrcDb to zDestDb in pDestDb. If successful, return
  70327. ** a pointer to the new sqlite3_backup object.
  70328. **
  70329. ** If an error occurs, NULL is returned and an error code and error message
  70330. ** stored in database handle pDestDb.
  70331. */
  70332. SQLITE_API sqlite3_backup *sqlite3_backup_init(
  70333. sqlite3* pDestDb, /* Database to write to */
  70334. const char *zDestDb, /* Name of database within pDestDb */
  70335. sqlite3* pSrcDb, /* Database connection to read from */
  70336. const char *zSrcDb /* Name of database within pSrcDb */
  70337. ){
  70338. sqlite3_backup *p; /* Value to return */
  70339. #ifdef SQLITE_ENABLE_API_ARMOR
  70340. if( !sqlite3SafetyCheckOk(pSrcDb)||!sqlite3SafetyCheckOk(pDestDb) ){
  70341. (void)SQLITE_MISUSE_BKPT;
  70342. return 0;
  70343. }
  70344. #endif
  70345. /* Lock the source database handle. The destination database
  70346. ** handle is not locked in this routine, but it is locked in
  70347. ** sqlite3_backup_step(). The user is required to ensure that no
  70348. ** other thread accesses the destination handle for the duration
  70349. ** of the backup operation. Any attempt to use the destination
  70350. ** database connection while a backup is in progress may cause
  70351. ** a malfunction or a deadlock.
  70352. */
  70353. sqlite3_mutex_enter(pSrcDb->mutex);
  70354. sqlite3_mutex_enter(pDestDb->mutex);
  70355. if( pSrcDb==pDestDb ){
  70356. sqlite3ErrorWithMsg(
  70357. pDestDb, SQLITE_ERROR, "source and destination must be distinct"
  70358. );
  70359. p = 0;
  70360. }else {
  70361. /* Allocate space for a new sqlite3_backup object...
  70362. ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
  70363. ** call to sqlite3_backup_init() and is destroyed by a call to
  70364. ** sqlite3_backup_finish(). */
  70365. p = (sqlite3_backup *)sqlite3MallocZero(sizeof(sqlite3_backup));
  70366. if( !p ){
  70367. sqlite3Error(pDestDb, SQLITE_NOMEM_BKPT);
  70368. }
  70369. }
  70370. /* If the allocation succeeded, populate the new object. */
  70371. if( p ){
  70372. p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
  70373. p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
  70374. p->pDestDb = pDestDb;
  70375. p->pSrcDb = pSrcDb;
  70376. p->iNext = 1;
  70377. p->isAttached = 0;
  70378. if( 0==p->pSrc || 0==p->pDest
  70379. || checkReadTransaction(pDestDb, p->pDest)!=SQLITE_OK
  70380. ){
  70381. /* One (or both) of the named databases did not exist or an OOM
  70382. ** error was hit. Or there is a transaction open on the destination
  70383. ** database. The error has already been written into the pDestDb
  70384. ** handle. All that is left to do here is free the sqlite3_backup
  70385. ** structure. */
  70386. sqlite3_free(p);
  70387. p = 0;
  70388. }
  70389. }
  70390. if( p ){
  70391. p->pSrc->nBackup++;
  70392. }
  70393. sqlite3_mutex_leave(pDestDb->mutex);
  70394. sqlite3_mutex_leave(pSrcDb->mutex);
  70395. return p;
  70396. }
  70397. /*
  70398. ** Argument rc is an SQLite error code. Return true if this error is
  70399. ** considered fatal if encountered during a backup operation. All errors
  70400. ** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED.
  70401. */
  70402. static int isFatalError(int rc){
  70403. return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && ALWAYS(rc!=SQLITE_LOCKED));
  70404. }
  70405. /*
  70406. ** Parameter zSrcData points to a buffer containing the data for
  70407. ** page iSrcPg from the source database. Copy this data into the
  70408. ** destination database.
  70409. */
  70410. static int backupOnePage(
  70411. sqlite3_backup *p, /* Backup handle */
  70412. Pgno iSrcPg, /* Source database page to backup */
  70413. const u8 *zSrcData, /* Source database page data */
  70414. int bUpdate /* True for an update, false otherwise */
  70415. ){
  70416. Pager * const pDestPager = sqlite3BtreePager(p->pDest);
  70417. const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);
  70418. int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);
  70419. const int nCopy = MIN(nSrcPgsz, nDestPgsz);
  70420. const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;
  70421. int rc = SQLITE_OK;
  70422. i64 iOff;
  70423. assert( sqlite3BtreeGetReserveNoMutex(p->pSrc)>=0 );
  70424. assert( p->bDestLocked );
  70425. assert( !isFatalError(p->rc) );
  70426. assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
  70427. assert( zSrcData );
  70428. /* Catch the case where the destination is an in-memory database and the
  70429. ** page sizes of the source and destination differ.
  70430. */
  70431. if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(pDestPager) ){
  70432. rc = SQLITE_READONLY;
  70433. }
  70434. /* This loop runs once for each destination page spanned by the source
  70435. ** page. For each iteration, variable iOff is set to the byte offset
  70436. ** of the destination page.
  70437. */
  70438. for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
  70439. DbPage *pDestPg = 0;
  70440. Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
  70441. if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
  70442. if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg, 0))
  70443. && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))
  70444. ){
  70445. const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
  70446. u8 *zDestData = sqlite3PagerGetData(pDestPg);
  70447. u8 *zOut = &zDestData[iOff%nDestPgsz];
  70448. /* Copy the data from the source page into the destination page.
  70449. ** Then clear the Btree layer MemPage.isInit flag. Both this module
  70450. ** and the pager code use this trick (clearing the first byte
  70451. ** of the page 'extra' space to invalidate the Btree layers
  70452. ** cached parse of the page). MemPage.isInit is marked
  70453. ** "MUST BE FIRST" for this purpose.
  70454. */
  70455. memcpy(zOut, zIn, nCopy);
  70456. ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;
  70457. if( iOff==0 && bUpdate==0 ){
  70458. sqlite3Put4byte(&zOut[28], sqlite3BtreeLastPage(p->pSrc));
  70459. }
  70460. }
  70461. sqlite3PagerUnref(pDestPg);
  70462. }
  70463. return rc;
  70464. }
  70465. /*
  70466. ** If pFile is currently larger than iSize bytes, then truncate it to
  70467. ** exactly iSize bytes. If pFile is not larger than iSize bytes, then
  70468. ** this function is a no-op.
  70469. **
  70470. ** Return SQLITE_OK if everything is successful, or an SQLite error
  70471. ** code if an error occurs.
  70472. */
  70473. static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){
  70474. i64 iCurrent;
  70475. int rc = sqlite3OsFileSize(pFile, &iCurrent);
  70476. if( rc==SQLITE_OK && iCurrent>iSize ){
  70477. rc = sqlite3OsTruncate(pFile, iSize);
  70478. }
  70479. return rc;
  70480. }
  70481. /*
  70482. ** Register this backup object with the associated source pager for
  70483. ** callbacks when pages are changed or the cache invalidated.
  70484. */
  70485. static void attachBackupObject(sqlite3_backup *p){
  70486. sqlite3_backup **pp;
  70487. assert( sqlite3BtreeHoldsMutex(p->pSrc) );
  70488. pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
  70489. p->pNext = *pp;
  70490. *pp = p;
  70491. p->isAttached = 1;
  70492. }
  70493. /*
  70494. ** Copy nPage pages from the source b-tree to the destination.
  70495. */
  70496. SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){
  70497. int rc;
  70498. int destMode; /* Destination journal mode */
  70499. int pgszSrc = 0; /* Source page size */
  70500. int pgszDest = 0; /* Destination page size */
  70501. #ifdef SQLITE_ENABLE_API_ARMOR
  70502. if( p==0 ) return SQLITE_MISUSE_BKPT;
  70503. #endif
  70504. sqlite3_mutex_enter(p->pSrcDb->mutex);
  70505. sqlite3BtreeEnter(p->pSrc);
  70506. if( p->pDestDb ){
  70507. sqlite3_mutex_enter(p->pDestDb->mutex);
  70508. }
  70509. rc = p->rc;
  70510. if( !isFatalError(rc) ){
  70511. Pager * const pSrcPager = sqlite3BtreePager(p->pSrc); /* Source pager */
  70512. Pager * const pDestPager = sqlite3BtreePager(p->pDest); /* Dest pager */
  70513. int ii; /* Iterator variable */
  70514. int nSrcPage = -1; /* Size of source db in pages */
  70515. int bCloseTrans = 0; /* True if src db requires unlocking */
  70516. /* If the source pager is currently in a write-transaction, return
  70517. ** SQLITE_BUSY immediately.
  70518. */
  70519. if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
  70520. rc = SQLITE_BUSY;
  70521. }else{
  70522. rc = SQLITE_OK;
  70523. }
  70524. /* If there is no open read-transaction on the source database, open
  70525. ** one now. If a transaction is opened here, then it will be closed
  70526. ** before this function exits.
  70527. */
  70528. if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){
  70529. rc = sqlite3BtreeBeginTrans(p->pSrc, 0, 0);
  70530. bCloseTrans = 1;
  70531. }
  70532. /* If the destination database has not yet been locked (i.e. if this
  70533. ** is the first call to backup_step() for the current backup operation),
  70534. ** try to set its page size to the same as the source database. This
  70535. ** is especially important on ZipVFS systems, as in that case it is
  70536. ** not possible to create a database file that uses one page size by
  70537. ** writing to it with another. */
  70538. if( p->bDestLocked==0 && rc==SQLITE_OK && setDestPgsz(p)==SQLITE_NOMEM ){
  70539. rc = SQLITE_NOMEM;
  70540. }
  70541. /* Lock the destination database, if it is not locked already. */
  70542. if( SQLITE_OK==rc && p->bDestLocked==0
  70543. && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2,
  70544. (int*)&p->iDestSchema))
  70545. ){
  70546. p->bDestLocked = 1;
  70547. }
  70548. /* Do not allow backup if the destination database is in WAL mode
  70549. ** and the page sizes are different between source and destination */
  70550. pgszSrc = sqlite3BtreeGetPageSize(p->pSrc);
  70551. pgszDest = sqlite3BtreeGetPageSize(p->pDest);
  70552. destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest));
  70553. if( SQLITE_OK==rc && destMode==PAGER_JOURNALMODE_WAL && pgszSrc!=pgszDest ){
  70554. rc = SQLITE_READONLY;
  70555. }
  70556. /* Now that there is a read-lock on the source database, query the
  70557. ** source pager for the number of pages in the database.
  70558. */
  70559. nSrcPage = (int)sqlite3BtreeLastPage(p->pSrc);
  70560. assert( nSrcPage>=0 );
  70561. for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
  70562. const Pgno iSrcPg = p->iNext; /* Source page number */
  70563. if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
  70564. DbPage *pSrcPg; /* Source page object */
  70565. rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg,PAGER_GET_READONLY);
  70566. if( rc==SQLITE_OK ){
  70567. rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg), 0);
  70568. sqlite3PagerUnref(pSrcPg);
  70569. }
  70570. }
  70571. p->iNext++;
  70572. }
  70573. if( rc==SQLITE_OK ){
  70574. p->nPagecount = nSrcPage;
  70575. p->nRemaining = nSrcPage+1-p->iNext;
  70576. if( p->iNext>(Pgno)nSrcPage ){
  70577. rc = SQLITE_DONE;
  70578. }else if( !p->isAttached ){
  70579. attachBackupObject(p);
  70580. }
  70581. }
  70582. /* Update the schema version field in the destination database. This
  70583. ** is to make sure that the schema-version really does change in
  70584. ** the case where the source and destination databases have the
  70585. ** same schema version.
  70586. */
  70587. if( rc==SQLITE_DONE ){
  70588. if( nSrcPage==0 ){
  70589. rc = sqlite3BtreeNewDb(p->pDest);
  70590. nSrcPage = 1;
  70591. }
  70592. if( rc==SQLITE_OK || rc==SQLITE_DONE ){
  70593. rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1);
  70594. }
  70595. if( rc==SQLITE_OK ){
  70596. if( p->pDestDb ){
  70597. sqlite3ResetAllSchemasOfConnection(p->pDestDb);
  70598. }
  70599. if( destMode==PAGER_JOURNALMODE_WAL ){
  70600. rc = sqlite3BtreeSetVersion(p->pDest, 2);
  70601. }
  70602. }
  70603. if( rc==SQLITE_OK ){
  70604. int nDestTruncate;
  70605. /* Set nDestTruncate to the final number of pages in the destination
  70606. ** database. The complication here is that the destination page
  70607. ** size may be different to the source page size.
  70608. **
  70609. ** If the source page size is smaller than the destination page size,
  70610. ** round up. In this case the call to sqlite3OsTruncate() below will
  70611. ** fix the size of the file. However it is important to call
  70612. ** sqlite3PagerTruncateImage() here so that any pages in the
  70613. ** destination file that lie beyond the nDestTruncate page mark are
  70614. ** journalled by PagerCommitPhaseOne() before they are destroyed
  70615. ** by the file truncation.
  70616. */
  70617. assert( pgszSrc==sqlite3BtreeGetPageSize(p->pSrc) );
  70618. assert( pgszDest==sqlite3BtreeGetPageSize(p->pDest) );
  70619. if( pgszSrc<pgszDest ){
  70620. int ratio = pgszDest/pgszSrc;
  70621. nDestTruncate = (nSrcPage+ratio-1)/ratio;
  70622. if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
  70623. nDestTruncate--;
  70624. }
  70625. }else{
  70626. nDestTruncate = nSrcPage * (pgszSrc/pgszDest);
  70627. }
  70628. assert( nDestTruncate>0 );
  70629. if( pgszSrc<pgszDest ){
  70630. /* If the source page-size is smaller than the destination page-size,
  70631. ** two extra things may need to happen:
  70632. **
  70633. ** * The destination may need to be truncated, and
  70634. **
  70635. ** * Data stored on the pages immediately following the
  70636. ** pending-byte page in the source database may need to be
  70637. ** copied into the destination database.
  70638. */
  70639. const i64 iSize = (i64)pgszSrc * (i64)nSrcPage;
  70640. sqlite3_file * const pFile = sqlite3PagerFile(pDestPager);
  70641. Pgno iPg;
  70642. int nDstPage;
  70643. i64 iOff;
  70644. i64 iEnd;
  70645. assert( pFile );
  70646. assert( nDestTruncate==0
  70647. || (i64)nDestTruncate*(i64)pgszDest >= iSize || (
  70648. nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
  70649. && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+pgszDest
  70650. ));
  70651. /* This block ensures that all data required to recreate the original
  70652. ** database has been stored in the journal for pDestPager and the
  70653. ** journal synced to disk. So at this point we may safely modify
  70654. ** the database file in any way, knowing that if a power failure
  70655. ** occurs, the original database will be reconstructed from the
  70656. ** journal file. */
  70657. sqlite3PagerPagecount(pDestPager, &nDstPage);
  70658. for(iPg=nDestTruncate; rc==SQLITE_OK && iPg<=(Pgno)nDstPage; iPg++){
  70659. if( iPg!=PENDING_BYTE_PAGE(p->pDest->pBt) ){
  70660. DbPage *pPg;
  70661. rc = sqlite3PagerGet(pDestPager, iPg, &pPg, 0);
  70662. if( rc==SQLITE_OK ){
  70663. rc = sqlite3PagerWrite(pPg);
  70664. sqlite3PagerUnref(pPg);
  70665. }
  70666. }
  70667. }
  70668. if( rc==SQLITE_OK ){
  70669. rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1);
  70670. }
  70671. /* Write the extra pages and truncate the database file as required */
  70672. iEnd = MIN(PENDING_BYTE + pgszDest, iSize);
  70673. for(
  70674. iOff=PENDING_BYTE+pgszSrc;
  70675. rc==SQLITE_OK && iOff<iEnd;
  70676. iOff+=pgszSrc
  70677. ){
  70678. PgHdr *pSrcPg = 0;
  70679. const Pgno iSrcPg = (Pgno)((iOff/pgszSrc)+1);
  70680. rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg, 0);
  70681. if( rc==SQLITE_OK ){
  70682. u8 *zData = sqlite3PagerGetData(pSrcPg);
  70683. rc = sqlite3OsWrite(pFile, zData, pgszSrc, iOff);
  70684. }
  70685. sqlite3PagerUnref(pSrcPg);
  70686. }
  70687. if( rc==SQLITE_OK ){
  70688. rc = backupTruncateFile(pFile, iSize);
  70689. }
  70690. /* Sync the database file to disk. */
  70691. if( rc==SQLITE_OK ){
  70692. rc = sqlite3PagerSync(pDestPager, 0);
  70693. }
  70694. }else{
  70695. sqlite3PagerTruncateImage(pDestPager, nDestTruncate);
  70696. rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);
  70697. }
  70698. /* Finish committing the transaction to the destination database. */
  70699. if( SQLITE_OK==rc
  70700. && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest, 0))
  70701. ){
  70702. rc = SQLITE_DONE;
  70703. }
  70704. }
  70705. }
  70706. /* If bCloseTrans is true, then this function opened a read transaction
  70707. ** on the source database. Close the read transaction here. There is
  70708. ** no need to check the return values of the btree methods here, as
  70709. ** "committing" a read-only transaction cannot fail.
  70710. */
  70711. if( bCloseTrans ){
  70712. TESTONLY( int rc2 );
  70713. TESTONLY( rc2 = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);
  70714. TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc, 0);
  70715. assert( rc2==SQLITE_OK );
  70716. }
  70717. if( rc==SQLITE_IOERR_NOMEM ){
  70718. rc = SQLITE_NOMEM_BKPT;
  70719. }
  70720. p->rc = rc;
  70721. }
  70722. if( p->pDestDb ){
  70723. sqlite3_mutex_leave(p->pDestDb->mutex);
  70724. }
  70725. sqlite3BtreeLeave(p->pSrc);
  70726. sqlite3_mutex_leave(p->pSrcDb->mutex);
  70727. return rc;
  70728. }
  70729. /*
  70730. ** Release all resources associated with an sqlite3_backup* handle.
  70731. */
  70732. SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p){
  70733. sqlite3_backup **pp; /* Ptr to head of pagers backup list */
  70734. sqlite3 *pSrcDb; /* Source database connection */
  70735. int rc; /* Value to return */
  70736. /* Enter the mutexes */
  70737. if( p==0 ) return SQLITE_OK;
  70738. pSrcDb = p->pSrcDb;
  70739. sqlite3_mutex_enter(pSrcDb->mutex);
  70740. sqlite3BtreeEnter(p->pSrc);
  70741. if( p->pDestDb ){
  70742. sqlite3_mutex_enter(p->pDestDb->mutex);
  70743. }
  70744. /* Detach this backup from the source pager. */
  70745. if( p->pDestDb ){
  70746. p->pSrc->nBackup--;
  70747. }
  70748. if( p->isAttached ){
  70749. pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
  70750. assert( pp!=0 );
  70751. while( *pp!=p ){
  70752. pp = &(*pp)->pNext;
  70753. assert( pp!=0 );
  70754. }
  70755. *pp = p->pNext;
  70756. }
  70757. /* If a transaction is still open on the Btree, roll it back. */
  70758. sqlite3BtreeRollback(p->pDest, SQLITE_OK, 0);
  70759. /* Set the error code of the destination database handle. */
  70760. rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;
  70761. if( p->pDestDb ){
  70762. sqlite3Error(p->pDestDb, rc);
  70763. /* Exit the mutexes and free the backup context structure. */
  70764. sqlite3LeaveMutexAndCloseZombie(p->pDestDb);
  70765. }
  70766. sqlite3BtreeLeave(p->pSrc);
  70767. if( p->pDestDb ){
  70768. /* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
  70769. ** call to sqlite3_backup_init() and is destroyed by a call to
  70770. ** sqlite3_backup_finish(). */
  70771. sqlite3_free(p);
  70772. }
  70773. sqlite3LeaveMutexAndCloseZombie(pSrcDb);
  70774. return rc;
  70775. }
  70776. /*
  70777. ** Return the number of pages still to be backed up as of the most recent
  70778. ** call to sqlite3_backup_step().
  70779. */
  70780. SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p){
  70781. #ifdef SQLITE_ENABLE_API_ARMOR
  70782. if( p==0 ){
  70783. (void)SQLITE_MISUSE_BKPT;
  70784. return 0;
  70785. }
  70786. #endif
  70787. return p->nRemaining;
  70788. }
  70789. /*
  70790. ** Return the total number of pages in the source database as of the most
  70791. ** recent call to sqlite3_backup_step().
  70792. */
  70793. SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p){
  70794. #ifdef SQLITE_ENABLE_API_ARMOR
  70795. if( p==0 ){
  70796. (void)SQLITE_MISUSE_BKPT;
  70797. return 0;
  70798. }
  70799. #endif
  70800. return p->nPagecount;
  70801. }
  70802. /*
  70803. ** This function is called after the contents of page iPage of the
  70804. ** source database have been modified. If page iPage has already been
  70805. ** copied into the destination database, then the data written to the
  70806. ** destination is now invalidated. The destination copy of iPage needs
  70807. ** to be updated with the new data before the backup operation is
  70808. ** complete.
  70809. **
  70810. ** It is assumed that the mutex associated with the BtShared object
  70811. ** corresponding to the source database is held when this function is
  70812. ** called.
  70813. */
  70814. static SQLITE_NOINLINE void backupUpdate(
  70815. sqlite3_backup *p,
  70816. Pgno iPage,
  70817. const u8 *aData
  70818. ){
  70819. assert( p!=0 );
  70820. do{
  70821. assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
  70822. if( !isFatalError(p->rc) && iPage<p->iNext ){
  70823. /* The backup process p has already copied page iPage. But now it
  70824. ** has been modified by a transaction on the source pager. Copy
  70825. ** the new data into the backup.
  70826. */
  70827. int rc;
  70828. assert( p->pDestDb );
  70829. sqlite3_mutex_enter(p->pDestDb->mutex);
  70830. rc = backupOnePage(p, iPage, aData, 1);
  70831. sqlite3_mutex_leave(p->pDestDb->mutex);
  70832. assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED );
  70833. if( rc!=SQLITE_OK ){
  70834. p->rc = rc;
  70835. }
  70836. }
  70837. }while( (p = p->pNext)!=0 );
  70838. }
  70839. SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){
  70840. if( pBackup ) backupUpdate(pBackup, iPage, aData);
  70841. }
  70842. /*
  70843. ** Restart the backup process. This is called when the pager layer
  70844. ** detects that the database has been modified by an external database
  70845. ** connection. In this case there is no way of knowing which of the
  70846. ** pages that have been copied into the destination database are still
  70847. ** valid and which are not, so the entire process needs to be restarted.
  70848. **
  70849. ** It is assumed that the mutex associated with the BtShared object
  70850. ** corresponding to the source database is held when this function is
  70851. ** called.
  70852. */
  70853. SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *pBackup){
  70854. sqlite3_backup *p; /* Iterator variable */
  70855. for(p=pBackup; p; p=p->pNext){
  70856. assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
  70857. p->iNext = 1;
  70858. }
  70859. }
  70860. #ifndef SQLITE_OMIT_VACUUM
  70861. /*
  70862. ** Copy the complete content of pBtFrom into pBtTo. A transaction
  70863. ** must be active for both files.
  70864. **
  70865. ** The size of file pTo may be reduced by this operation. If anything
  70866. ** goes wrong, the transaction on pTo is rolled back. If successful, the
  70867. ** transaction is committed before returning.
  70868. */
  70869. SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
  70870. int rc;
  70871. sqlite3_file *pFd; /* File descriptor for database pTo */
  70872. sqlite3_backup b;
  70873. sqlite3BtreeEnter(pTo);
  70874. sqlite3BtreeEnter(pFrom);
  70875. assert( sqlite3BtreeIsInTrans(pTo) );
  70876. pFd = sqlite3PagerFile(sqlite3BtreePager(pTo));
  70877. if( pFd->pMethods ){
  70878. i64 nByte = sqlite3BtreeGetPageSize(pFrom)*(i64)sqlite3BtreeLastPage(pFrom);
  70879. rc = sqlite3OsFileControl(pFd, SQLITE_FCNTL_OVERWRITE, &nByte);
  70880. if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
  70881. if( rc ) goto copy_finished;
  70882. }
  70883. /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
  70884. ** to 0. This is used by the implementations of sqlite3_backup_step()
  70885. ** and sqlite3_backup_finish() to detect that they are being called
  70886. ** from this function, not directly by the user.
  70887. */
  70888. memset(&b, 0, sizeof(b));
  70889. b.pSrcDb = pFrom->db;
  70890. b.pSrc = pFrom;
  70891. b.pDest = pTo;
  70892. b.iNext = 1;
  70893. /* 0x7FFFFFFF is the hard limit for the number of pages in a database
  70894. ** file. By passing this as the number of pages to copy to
  70895. ** sqlite3_backup_step(), we can guarantee that the copy finishes
  70896. ** within a single call (unless an error occurs). The assert() statement
  70897. ** checks this assumption - (p->rc) should be set to either SQLITE_DONE
  70898. ** or an error code. */
  70899. sqlite3_backup_step(&b, 0x7FFFFFFF);
  70900. assert( b.rc!=SQLITE_OK );
  70901. rc = sqlite3_backup_finish(&b);
  70902. if( rc==SQLITE_OK ){
  70903. pTo->pBt->btsFlags &= ~BTS_PAGESIZE_FIXED;
  70904. }else{
  70905. sqlite3PagerClearCache(sqlite3BtreePager(b.pDest));
  70906. }
  70907. assert( sqlite3BtreeIsInTrans(pTo)==0 );
  70908. copy_finished:
  70909. sqlite3BtreeLeave(pFrom);
  70910. sqlite3BtreeLeave(pTo);
  70911. return rc;
  70912. }
  70913. #endif /* SQLITE_OMIT_VACUUM */
  70914. /************** End of backup.c **********************************************/
  70915. /************** Begin file vdbemem.c *****************************************/
  70916. /*
  70917. ** 2004 May 26
  70918. **
  70919. ** The author disclaims copyright to this source code. In place of
  70920. ** a legal notice, here is a blessing:
  70921. **
  70922. ** May you do good and not evil.
  70923. ** May you find forgiveness for yourself and forgive others.
  70924. ** May you share freely, never taking more than you give.
  70925. **
  70926. *************************************************************************
  70927. **
  70928. ** This file contains code use to manipulate "Mem" structure. A "Mem"
  70929. ** stores a single value in the VDBE. Mem is an opaque structure visible
  70930. ** only within the VDBE. Interface routines refer to a Mem using the
  70931. ** name sqlite_value
  70932. */
  70933. /* #include "sqliteInt.h" */
  70934. /* #include "vdbeInt.h" */
  70935. /* True if X is a power of two. 0 is considered a power of two here.
  70936. ** In other words, return true if X has at most one bit set.
  70937. */
  70938. #define ISPOWEROF2(X) (((X)&((X)-1))==0)
  70939. #ifdef SQLITE_DEBUG
  70940. /*
  70941. ** Check invariants on a Mem object.
  70942. **
  70943. ** This routine is intended for use inside of assert() statements, like
  70944. ** this: assert( sqlite3VdbeCheckMemInvariants(pMem) );
  70945. */
  70946. SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem *p){
  70947. /* If MEM_Dyn is set then Mem.xDel!=0.
  70948. ** Mem.xDel might not be initialized if MEM_Dyn is clear.
  70949. */
  70950. assert( (p->flags & MEM_Dyn)==0 || p->xDel!=0 );
  70951. /* MEM_Dyn may only be set if Mem.szMalloc==0. In this way we
  70952. ** ensure that if Mem.szMalloc>0 then it is safe to do
  70953. ** Mem.z = Mem.zMalloc without having to check Mem.flags&MEM_Dyn.
  70954. ** That saves a few cycles in inner loops. */
  70955. assert( (p->flags & MEM_Dyn)==0 || p->szMalloc==0 );
  70956. /* Cannot have more than one of MEM_Int, MEM_Real, or MEM_IntReal */
  70957. assert( ISPOWEROF2(p->flags & (MEM_Int|MEM_Real|MEM_IntReal)) );
  70958. if( p->flags & MEM_Null ){
  70959. /* Cannot be both MEM_Null and some other type */
  70960. assert( (p->flags & (MEM_Int|MEM_Real|MEM_Str|MEM_Blob|MEM_Agg))==0 );
  70961. /* If MEM_Null is set, then either the value is a pure NULL (the usual
  70962. ** case) or it is a pointer set using sqlite3_bind_pointer() or
  70963. ** sqlite3_result_pointer(). If a pointer, then MEM_Term must also be
  70964. ** set.
  70965. */
  70966. if( (p->flags & (MEM_Term|MEM_Subtype))==(MEM_Term|MEM_Subtype) ){
  70967. /* This is a pointer type. There may be a flag to indicate what to
  70968. ** do with the pointer. */
  70969. assert( ((p->flags&MEM_Dyn)!=0 ? 1 : 0) +
  70970. ((p->flags&MEM_Ephem)!=0 ? 1 : 0) +
  70971. ((p->flags&MEM_Static)!=0 ? 1 : 0) <= 1 );
  70972. /* No other bits set */
  70973. assert( (p->flags & ~(MEM_Null|MEM_Term|MEM_Subtype|MEM_FromBind
  70974. |MEM_Dyn|MEM_Ephem|MEM_Static))==0 );
  70975. }else{
  70976. /* A pure NULL might have other flags, such as MEM_Static, MEM_Dyn,
  70977. ** MEM_Ephem, MEM_Cleared, or MEM_Subtype */
  70978. }
  70979. }else{
  70980. /* The MEM_Cleared bit is only allowed on NULLs */
  70981. assert( (p->flags & MEM_Cleared)==0 );
  70982. }
  70983. /* The szMalloc field holds the correct memory allocation size */
  70984. assert( p->szMalloc==0
  70985. || p->szMalloc==sqlite3DbMallocSize(p->db,p->zMalloc) );
  70986. /* If p holds a string or blob, the Mem.z must point to exactly
  70987. ** one of the following:
  70988. **
  70989. ** (1) Memory in Mem.zMalloc and managed by the Mem object
  70990. ** (2) Memory to be freed using Mem.xDel
  70991. ** (3) An ephemeral string or blob
  70992. ** (4) A static string or blob
  70993. */
  70994. if( (p->flags & (MEM_Str|MEM_Blob)) && p->n>0 ){
  70995. assert(
  70996. ((p->szMalloc>0 && p->z==p->zMalloc)? 1 : 0) +
  70997. ((p->flags&MEM_Dyn)!=0 ? 1 : 0) +
  70998. ((p->flags&MEM_Ephem)!=0 ? 1 : 0) +
  70999. ((p->flags&MEM_Static)!=0 ? 1 : 0) == 1
  71000. );
  71001. }
  71002. return 1;
  71003. }
  71004. #endif
  71005. /*
  71006. ** Render a Mem object which is one of MEM_Int, MEM_Real, or MEM_IntReal
  71007. ** into a buffer.
  71008. */
  71009. static void vdbeMemRenderNum(int sz, char *zBuf, Mem *p){
  71010. StrAccum acc;
  71011. assert( p->flags & (MEM_Int|MEM_Real|MEM_IntReal) );
  71012. sqlite3StrAccumInit(&acc, 0, zBuf, sz, 0);
  71013. if( p->flags & MEM_Int ){
  71014. sqlite3_str_appendf(&acc, "%lld", p->u.i);
  71015. }else if( p->flags & MEM_IntReal ){
  71016. sqlite3_str_appendf(&acc, "%!.15g", (double)p->u.i);
  71017. }else{
  71018. sqlite3_str_appendf(&acc, "%!.15g", p->u.r);
  71019. }
  71020. assert( acc.zText==zBuf && acc.mxAlloc<=0 );
  71021. zBuf[acc.nChar] = 0; /* Fast version of sqlite3StrAccumFinish(&acc) */
  71022. }
  71023. #ifdef SQLITE_DEBUG
  71024. /*
  71025. ** Validity checks on pMem. pMem holds a string.
  71026. **
  71027. ** (1) Check that string value of pMem agrees with its integer or real value.
  71028. ** (2) Check that the string is correctly zero terminated
  71029. **
  71030. ** A single int or real value always converts to the same strings. But
  71031. ** many different strings can be converted into the same int or real.
  71032. ** If a table contains a numeric value and an index is based on the
  71033. ** corresponding string value, then it is important that the string be
  71034. ** derived from the numeric value, not the other way around, to ensure
  71035. ** that the index and table are consistent. See ticket
  71036. ** https://www.sqlite.org/src/info/343634942dd54ab (2018-01-31) for
  71037. ** an example.
  71038. **
  71039. ** This routine looks at pMem to verify that if it has both a numeric
  71040. ** representation and a string representation then the string rep has
  71041. ** been derived from the numeric and not the other way around. It returns
  71042. ** true if everything is ok and false if there is a problem.
  71043. **
  71044. ** This routine is for use inside of assert() statements only.
  71045. */
  71046. SQLITE_PRIVATE int sqlite3VdbeMemValidStrRep(Mem *p){
  71047. char zBuf[100];
  71048. char *z;
  71049. int i, j, incr;
  71050. if( (p->flags & MEM_Str)==0 ) return 1;
  71051. if( p->flags & MEM_Term ){
  71052. /* Insure that the string is properly zero-terminated. Pay particular
  71053. ** attention to the case where p->n is odd */
  71054. if( p->szMalloc>0 && p->z==p->zMalloc ){
  71055. assert( p->enc==SQLITE_UTF8 || p->szMalloc >= ((p->n+1)&~1)+2 );
  71056. assert( p->enc!=SQLITE_UTF8 || p->szMalloc >= p->n+1 );
  71057. }
  71058. assert( p->z[p->n]==0 );
  71059. assert( p->enc==SQLITE_UTF8 || p->z[(p->n+1)&~1]==0 );
  71060. assert( p->enc==SQLITE_UTF8 || p->z[((p->n+1)&~1)+1]==0 );
  71061. }
  71062. if( (p->flags & (MEM_Int|MEM_Real|MEM_IntReal))==0 ) return 1;
  71063. vdbeMemRenderNum(sizeof(zBuf), zBuf, p);
  71064. z = p->z;
  71065. i = j = 0;
  71066. incr = 1;
  71067. if( p->enc!=SQLITE_UTF8 ){
  71068. incr = 2;
  71069. if( p->enc==SQLITE_UTF16BE ) z++;
  71070. }
  71071. while( zBuf[j] ){
  71072. if( zBuf[j++]!=z[i] ) return 0;
  71073. i += incr;
  71074. }
  71075. return 1;
  71076. }
  71077. #endif /* SQLITE_DEBUG */
  71078. /*
  71079. ** If pMem is an object with a valid string representation, this routine
  71080. ** ensures the internal encoding for the string representation is
  71081. ** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
  71082. **
  71083. ** If pMem is not a string object, or the encoding of the string
  71084. ** representation is already stored using the requested encoding, then this
  71085. ** routine is a no-op.
  71086. **
  71087. ** SQLITE_OK is returned if the conversion is successful (or not required).
  71088. ** SQLITE_NOMEM may be returned if a malloc() fails during conversion
  71089. ** between formats.
  71090. */
  71091. SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
  71092. #ifndef SQLITE_OMIT_UTF16
  71093. int rc;
  71094. #endif
  71095. assert( !sqlite3VdbeMemIsRowSet(pMem) );
  71096. assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE
  71097. || desiredEnc==SQLITE_UTF16BE );
  71098. if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
  71099. return SQLITE_OK;
  71100. }
  71101. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  71102. #ifdef SQLITE_OMIT_UTF16
  71103. return SQLITE_ERROR;
  71104. #else
  71105. /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
  71106. ** then the encoding of the value may not have changed.
  71107. */
  71108. rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc);
  71109. assert(rc==SQLITE_OK || rc==SQLITE_NOMEM);
  71110. assert(rc==SQLITE_OK || pMem->enc!=desiredEnc);
  71111. assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
  71112. return rc;
  71113. #endif
  71114. }
  71115. /*
  71116. ** Make sure pMem->z points to a writable allocation of at least n bytes.
  71117. **
  71118. ** If the bPreserve argument is true, then copy of the content of
  71119. ** pMem->z into the new allocation. pMem must be either a string or
  71120. ** blob if bPreserve is true. If bPreserve is false, any prior content
  71121. ** in pMem->z is discarded.
  71122. */
  71123. SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3VdbeMemGrow(Mem *pMem, int n, int bPreserve){
  71124. assert( sqlite3VdbeCheckMemInvariants(pMem) );
  71125. assert( !sqlite3VdbeMemIsRowSet(pMem) );
  71126. testcase( pMem->db==0 );
  71127. /* If the bPreserve flag is set to true, then the memory cell must already
  71128. ** contain a valid string or blob value. */
  71129. assert( bPreserve==0 || pMem->flags&(MEM_Blob|MEM_Str) );
  71130. testcase( bPreserve && pMem->z==0 );
  71131. assert( pMem->szMalloc==0
  71132. || pMem->szMalloc==sqlite3DbMallocSize(pMem->db, pMem->zMalloc) );
  71133. if( pMem->szMalloc>0 && bPreserve && pMem->z==pMem->zMalloc ){
  71134. if( pMem->db ){
  71135. pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
  71136. }else{
  71137. pMem->zMalloc = sqlite3Realloc(pMem->z, n);
  71138. if( pMem->zMalloc==0 ) sqlite3_free(pMem->z);
  71139. pMem->z = pMem->zMalloc;
  71140. }
  71141. bPreserve = 0;
  71142. }else{
  71143. if( pMem->szMalloc>0 ) sqlite3DbFreeNN(pMem->db, pMem->zMalloc);
  71144. pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
  71145. }
  71146. if( pMem->zMalloc==0 ){
  71147. sqlite3VdbeMemSetNull(pMem);
  71148. pMem->z = 0;
  71149. pMem->szMalloc = 0;
  71150. return SQLITE_NOMEM_BKPT;
  71151. }else{
  71152. pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc);
  71153. }
  71154. if( bPreserve && pMem->z ){
  71155. assert( pMem->z!=pMem->zMalloc );
  71156. memcpy(pMem->zMalloc, pMem->z, pMem->n);
  71157. }
  71158. if( (pMem->flags&MEM_Dyn)!=0 ){
  71159. assert( pMem->xDel!=0 && pMem->xDel!=SQLITE_DYNAMIC );
  71160. pMem->xDel((void *)(pMem->z));
  71161. }
  71162. pMem->z = pMem->zMalloc;
  71163. pMem->flags &= ~(MEM_Dyn|MEM_Ephem|MEM_Static);
  71164. return SQLITE_OK;
  71165. }
  71166. /*
  71167. ** Change the pMem->zMalloc allocation to be at least szNew bytes.
  71168. ** If pMem->zMalloc already meets or exceeds the requested size, this
  71169. ** routine is a no-op.
  71170. **
  71171. ** Any prior string or blob content in the pMem object may be discarded.
  71172. ** The pMem->xDel destructor is called, if it exists. Though MEM_Str
  71173. ** and MEM_Blob values may be discarded, MEM_Int, MEM_Real, MEM_IntReal,
  71174. ** and MEM_Null values are preserved.
  71175. **
  71176. ** Return SQLITE_OK on success or an error code (probably SQLITE_NOMEM)
  71177. ** if unable to complete the resizing.
  71178. */
  71179. SQLITE_PRIVATE int sqlite3VdbeMemClearAndResize(Mem *pMem, int szNew){
  71180. assert( CORRUPT_DB || szNew>0 );
  71181. assert( (pMem->flags & MEM_Dyn)==0 || pMem->szMalloc==0 );
  71182. if( pMem->szMalloc<szNew ){
  71183. return sqlite3VdbeMemGrow(pMem, szNew, 0);
  71184. }
  71185. assert( (pMem->flags & MEM_Dyn)==0 );
  71186. pMem->z = pMem->zMalloc;
  71187. pMem->flags &= (MEM_Null|MEM_Int|MEM_Real|MEM_IntReal);
  71188. return SQLITE_OK;
  71189. }
  71190. /*
  71191. ** It is already known that pMem contains an unterminated string.
  71192. ** Add the zero terminator.
  71193. **
  71194. ** Three bytes of zero are added. In this way, there is guaranteed
  71195. ** to be a double-zero byte at an even byte boundary in order to
  71196. ** terminate a UTF16 string, even if the initial size of the buffer
  71197. ** is an odd number of bytes.
  71198. */
  71199. static SQLITE_NOINLINE int vdbeMemAddTerminator(Mem *pMem){
  71200. if( sqlite3VdbeMemGrow(pMem, pMem->n+3, 1) ){
  71201. return SQLITE_NOMEM_BKPT;
  71202. }
  71203. pMem->z[pMem->n] = 0;
  71204. pMem->z[pMem->n+1] = 0;
  71205. pMem->z[pMem->n+2] = 0;
  71206. pMem->flags |= MEM_Term;
  71207. return SQLITE_OK;
  71208. }
  71209. /*
  71210. ** Change pMem so that its MEM_Str or MEM_Blob value is stored in
  71211. ** MEM.zMalloc, where it can be safely written.
  71212. **
  71213. ** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
  71214. */
  71215. SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){
  71216. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  71217. assert( !sqlite3VdbeMemIsRowSet(pMem) );
  71218. if( (pMem->flags & (MEM_Str|MEM_Blob))!=0 ){
  71219. if( ExpandBlob(pMem) ) return SQLITE_NOMEM;
  71220. if( pMem->szMalloc==0 || pMem->z!=pMem->zMalloc ){
  71221. int rc = vdbeMemAddTerminator(pMem);
  71222. if( rc ) return rc;
  71223. }
  71224. }
  71225. pMem->flags &= ~MEM_Ephem;
  71226. #ifdef SQLITE_DEBUG
  71227. pMem->pScopyFrom = 0;
  71228. #endif
  71229. return SQLITE_OK;
  71230. }
  71231. /*
  71232. ** If the given Mem* has a zero-filled tail, turn it into an ordinary
  71233. ** blob stored in dynamically allocated space.
  71234. */
  71235. #ifndef SQLITE_OMIT_INCRBLOB
  71236. SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){
  71237. int nByte;
  71238. assert( pMem->flags & MEM_Zero );
  71239. assert( (pMem->flags&MEM_Blob)!=0 || MemNullNochng(pMem) );
  71240. testcase( sqlite3_value_nochange(pMem) );
  71241. assert( !sqlite3VdbeMemIsRowSet(pMem) );
  71242. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  71243. /* Set nByte to the number of bytes required to store the expanded blob. */
  71244. nByte = pMem->n + pMem->u.nZero;
  71245. if( nByte<=0 ){
  71246. if( (pMem->flags & MEM_Blob)==0 ) return SQLITE_OK;
  71247. nByte = 1;
  71248. }
  71249. if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
  71250. return SQLITE_NOMEM_BKPT;
  71251. }
  71252. memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
  71253. pMem->n += pMem->u.nZero;
  71254. pMem->flags &= ~(MEM_Zero|MEM_Term);
  71255. return SQLITE_OK;
  71256. }
  71257. #endif
  71258. /*
  71259. ** Make sure the given Mem is \u0000 terminated.
  71260. */
  71261. SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){
  71262. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  71263. testcase( (pMem->flags & (MEM_Term|MEM_Str))==(MEM_Term|MEM_Str) );
  71264. testcase( (pMem->flags & (MEM_Term|MEM_Str))==0 );
  71265. if( (pMem->flags & (MEM_Term|MEM_Str))!=MEM_Str ){
  71266. return SQLITE_OK; /* Nothing to do */
  71267. }else{
  71268. return vdbeMemAddTerminator(pMem);
  71269. }
  71270. }
  71271. /*
  71272. ** Add MEM_Str to the set of representations for the given Mem. This
  71273. ** routine is only called if pMem is a number of some kind, not a NULL
  71274. ** or a BLOB.
  71275. **
  71276. ** Existing representations MEM_Int, MEM_Real, or MEM_IntReal are invalidated
  71277. ** if bForce is true but are retained if bForce is false.
  71278. **
  71279. ** A MEM_Null value will never be passed to this function. This function is
  71280. ** used for converting values to text for returning to the user (i.e. via
  71281. ** sqlite3_value_text()), or for ensuring that values to be used as btree
  71282. ** keys are strings. In the former case a NULL pointer is returned the
  71283. ** user and the latter is an internal programming error.
  71284. */
  71285. SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, u8 enc, u8 bForce){
  71286. const int nByte = 32;
  71287. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  71288. assert( !(pMem->flags&MEM_Zero) );
  71289. assert( !(pMem->flags&(MEM_Str|MEM_Blob)) );
  71290. assert( pMem->flags&(MEM_Int|MEM_Real|MEM_IntReal) );
  71291. assert( !sqlite3VdbeMemIsRowSet(pMem) );
  71292. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  71293. if( sqlite3VdbeMemClearAndResize(pMem, nByte) ){
  71294. pMem->enc = 0;
  71295. return SQLITE_NOMEM_BKPT;
  71296. }
  71297. vdbeMemRenderNum(nByte, pMem->z, pMem);
  71298. assert( pMem->z!=0 );
  71299. pMem->n = sqlite3Strlen30NN(pMem->z);
  71300. pMem->enc = SQLITE_UTF8;
  71301. pMem->flags |= MEM_Str|MEM_Term;
  71302. if( bForce ) pMem->flags &= ~(MEM_Int|MEM_Real|MEM_IntReal);
  71303. sqlite3VdbeChangeEncoding(pMem, enc);
  71304. return SQLITE_OK;
  71305. }
  71306. /*
  71307. ** Memory cell pMem contains the context of an aggregate function.
  71308. ** This routine calls the finalize method for that function. The
  71309. ** result of the aggregate is stored back into pMem.
  71310. **
  71311. ** Return SQLITE_ERROR if the finalizer reports an error. SQLITE_OK
  71312. ** otherwise.
  71313. */
  71314. SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
  71315. sqlite3_context ctx;
  71316. Mem t;
  71317. assert( pFunc!=0 );
  71318. assert( pFunc->xFinalize!=0 );
  71319. assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
  71320. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  71321. memset(&ctx, 0, sizeof(ctx));
  71322. memset(&t, 0, sizeof(t));
  71323. t.flags = MEM_Null;
  71324. t.db = pMem->db;
  71325. ctx.pOut = &t;
  71326. ctx.pMem = pMem;
  71327. ctx.pFunc = pFunc;
  71328. pFunc->xFinalize(&ctx); /* IMP: R-24505-23230 */
  71329. assert( (pMem->flags & MEM_Dyn)==0 );
  71330. if( pMem->szMalloc>0 ) sqlite3DbFreeNN(pMem->db, pMem->zMalloc);
  71331. memcpy(pMem, &t, sizeof(t));
  71332. return ctx.isError;
  71333. }
  71334. /*
  71335. ** Memory cell pAccum contains the context of an aggregate function.
  71336. ** This routine calls the xValue method for that function and stores
  71337. ** the results in memory cell pMem.
  71338. **
  71339. ** SQLITE_ERROR is returned if xValue() reports an error. SQLITE_OK
  71340. ** otherwise.
  71341. */
  71342. #ifndef SQLITE_OMIT_WINDOWFUNC
  71343. SQLITE_PRIVATE int sqlite3VdbeMemAggValue(Mem *pAccum, Mem *pOut, FuncDef *pFunc){
  71344. sqlite3_context ctx;
  71345. assert( pFunc!=0 );
  71346. assert( pFunc->xValue!=0 );
  71347. assert( (pAccum->flags & MEM_Null)!=0 || pFunc==pAccum->u.pDef );
  71348. assert( pAccum->db==0 || sqlite3_mutex_held(pAccum->db->mutex) );
  71349. memset(&ctx, 0, sizeof(ctx));
  71350. sqlite3VdbeMemSetNull(pOut);
  71351. ctx.pOut = pOut;
  71352. ctx.pMem = pAccum;
  71353. ctx.pFunc = pFunc;
  71354. pFunc->xValue(&ctx);
  71355. return ctx.isError;
  71356. }
  71357. #endif /* SQLITE_OMIT_WINDOWFUNC */
  71358. /*
  71359. ** If the memory cell contains a value that must be freed by
  71360. ** invoking the external callback in Mem.xDel, then this routine
  71361. ** will free that value. It also sets Mem.flags to MEM_Null.
  71362. **
  71363. ** This is a helper routine for sqlite3VdbeMemSetNull() and
  71364. ** for sqlite3VdbeMemRelease(). Use those other routines as the
  71365. ** entry point for releasing Mem resources.
  71366. */
  71367. static SQLITE_NOINLINE void vdbeMemClearExternAndSetNull(Mem *p){
  71368. assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
  71369. assert( VdbeMemDynamic(p) );
  71370. if( p->flags&MEM_Agg ){
  71371. sqlite3VdbeMemFinalize(p, p->u.pDef);
  71372. assert( (p->flags & MEM_Agg)==0 );
  71373. testcase( p->flags & MEM_Dyn );
  71374. }
  71375. if( p->flags&MEM_Dyn ){
  71376. assert( p->xDel!=SQLITE_DYNAMIC && p->xDel!=0 );
  71377. p->xDel((void *)p->z);
  71378. }
  71379. p->flags = MEM_Null;
  71380. }
  71381. /*
  71382. ** Release memory held by the Mem p, both external memory cleared
  71383. ** by p->xDel and memory in p->zMalloc.
  71384. **
  71385. ** This is a helper routine invoked by sqlite3VdbeMemRelease() in
  71386. ** the unusual case where there really is memory in p that needs
  71387. ** to be freed.
  71388. */
  71389. static SQLITE_NOINLINE void vdbeMemClear(Mem *p){
  71390. if( VdbeMemDynamic(p) ){
  71391. vdbeMemClearExternAndSetNull(p);
  71392. }
  71393. if( p->szMalloc ){
  71394. sqlite3DbFreeNN(p->db, p->zMalloc);
  71395. p->szMalloc = 0;
  71396. }
  71397. p->z = 0;
  71398. }
  71399. /*
  71400. ** Release any memory resources held by the Mem. Both the memory that is
  71401. ** free by Mem.xDel and the Mem.zMalloc allocation are freed.
  71402. **
  71403. ** Use this routine prior to clean up prior to abandoning a Mem, or to
  71404. ** reset a Mem back to its minimum memory utilization.
  71405. **
  71406. ** Use sqlite3VdbeMemSetNull() to release just the Mem.xDel space
  71407. ** prior to inserting new content into the Mem.
  71408. */
  71409. SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){
  71410. assert( sqlite3VdbeCheckMemInvariants(p) );
  71411. if( VdbeMemDynamic(p) || p->szMalloc ){
  71412. vdbeMemClear(p);
  71413. }
  71414. }
  71415. /*
  71416. ** Convert a 64-bit IEEE double into a 64-bit signed integer.
  71417. ** If the double is out of range of a 64-bit signed integer then
  71418. ** return the closest available 64-bit signed integer.
  71419. */
  71420. static SQLITE_NOINLINE i64 doubleToInt64(double r){
  71421. #ifdef SQLITE_OMIT_FLOATING_POINT
  71422. /* When floating-point is omitted, double and int64 are the same thing */
  71423. return r;
  71424. #else
  71425. /*
  71426. ** Many compilers we encounter do not define constants for the
  71427. ** minimum and maximum 64-bit integers, or they define them
  71428. ** inconsistently. And many do not understand the "LL" notation.
  71429. ** So we define our own static constants here using nothing
  71430. ** larger than a 32-bit integer constant.
  71431. */
  71432. static const i64 maxInt = LARGEST_INT64;
  71433. static const i64 minInt = SMALLEST_INT64;
  71434. if( r<=(double)minInt ){
  71435. return minInt;
  71436. }else if( r>=(double)maxInt ){
  71437. return maxInt;
  71438. }else{
  71439. return (i64)r;
  71440. }
  71441. #endif
  71442. }
  71443. /*
  71444. ** Return some kind of integer value which is the best we can do
  71445. ** at representing the value that *pMem describes as an integer.
  71446. ** If pMem is an integer, then the value is exact. If pMem is
  71447. ** a floating-point then the value returned is the integer part.
  71448. ** If pMem is a string or blob, then we make an attempt to convert
  71449. ** it into an integer and return that. If pMem represents an
  71450. ** an SQL-NULL value, return 0.
  71451. **
  71452. ** If pMem represents a string value, its encoding might be changed.
  71453. */
  71454. static SQLITE_NOINLINE i64 memIntValue(Mem *pMem){
  71455. i64 value = 0;
  71456. sqlite3Atoi64(pMem->z, &value, pMem->n, pMem->enc);
  71457. return value;
  71458. }
  71459. SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){
  71460. int flags;
  71461. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  71462. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  71463. flags = pMem->flags;
  71464. if( flags & (MEM_Int|MEM_IntReal) ){
  71465. testcase( flags & MEM_IntReal );
  71466. return pMem->u.i;
  71467. }else if( flags & MEM_Real ){
  71468. return doubleToInt64(pMem->u.r);
  71469. }else if( (flags & (MEM_Str|MEM_Blob))!=0 && pMem->z!=0 ){
  71470. return memIntValue(pMem);
  71471. }else{
  71472. return 0;
  71473. }
  71474. }
  71475. /*
  71476. ** Return the best representation of pMem that we can get into a
  71477. ** double. If pMem is already a double or an integer, return its
  71478. ** value. If it is a string or blob, try to convert it to a double.
  71479. ** If it is a NULL, return 0.0.
  71480. */
  71481. static SQLITE_NOINLINE double memRealValue(Mem *pMem){
  71482. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  71483. double val = (double)0;
  71484. sqlite3AtoF(pMem->z, &val, pMem->n, pMem->enc);
  71485. return val;
  71486. }
  71487. SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){
  71488. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  71489. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  71490. if( pMem->flags & MEM_Real ){
  71491. return pMem->u.r;
  71492. }else if( pMem->flags & (MEM_Int|MEM_IntReal) ){
  71493. testcase( pMem->flags & MEM_IntReal );
  71494. return (double)pMem->u.i;
  71495. }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
  71496. return memRealValue(pMem);
  71497. }else{
  71498. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  71499. return (double)0;
  71500. }
  71501. }
  71502. /*
  71503. ** Return 1 if pMem represents true, and return 0 if pMem represents false.
  71504. ** Return the value ifNull if pMem is NULL.
  71505. */
  71506. SQLITE_PRIVATE int sqlite3VdbeBooleanValue(Mem *pMem, int ifNull){
  71507. testcase( pMem->flags & MEM_IntReal );
  71508. if( pMem->flags & (MEM_Int|MEM_IntReal) ) return pMem->u.i!=0;
  71509. if( pMem->flags & MEM_Null ) return ifNull;
  71510. return sqlite3VdbeRealValue(pMem)!=0.0;
  71511. }
  71512. /*
  71513. ** The MEM structure is already a MEM_Real. Try to also make it a
  71514. ** MEM_Int if we can.
  71515. */
  71516. SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){
  71517. i64 ix;
  71518. assert( pMem->flags & MEM_Real );
  71519. assert( !sqlite3VdbeMemIsRowSet(pMem) );
  71520. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  71521. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  71522. ix = doubleToInt64(pMem->u.r);
  71523. /* Only mark the value as an integer if
  71524. **
  71525. ** (1) the round-trip conversion real->int->real is a no-op, and
  71526. ** (2) The integer is neither the largest nor the smallest
  71527. ** possible integer (ticket #3922)
  71528. **
  71529. ** The second and third terms in the following conditional enforces
  71530. ** the second condition under the assumption that addition overflow causes
  71531. ** values to wrap around.
  71532. */
  71533. if( pMem->u.r==ix && ix>SMALLEST_INT64 && ix<LARGEST_INT64 ){
  71534. pMem->u.i = ix;
  71535. MemSetTypeFlag(pMem, MEM_Int);
  71536. }
  71537. }
  71538. /*
  71539. ** Convert pMem to type integer. Invalidate any prior representations.
  71540. */
  71541. SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){
  71542. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  71543. assert( !sqlite3VdbeMemIsRowSet(pMem) );
  71544. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  71545. pMem->u.i = sqlite3VdbeIntValue(pMem);
  71546. MemSetTypeFlag(pMem, MEM_Int);
  71547. return SQLITE_OK;
  71548. }
  71549. /*
  71550. ** Convert pMem so that it is of type MEM_Real.
  71551. ** Invalidate any prior representations.
  71552. */
  71553. SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){
  71554. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  71555. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  71556. pMem->u.r = sqlite3VdbeRealValue(pMem);
  71557. MemSetTypeFlag(pMem, MEM_Real);
  71558. return SQLITE_OK;
  71559. }
  71560. /* Compare a floating point value to an integer. Return true if the two
  71561. ** values are the same within the precision of the floating point value.
  71562. **
  71563. ** This function assumes that i was obtained by assignment from r1.
  71564. **
  71565. ** For some versions of GCC on 32-bit machines, if you do the more obvious
  71566. ** comparison of "r1==(double)i" you sometimes get an answer of false even
  71567. ** though the r1 and (double)i values are bit-for-bit the same.
  71568. */
  71569. SQLITE_PRIVATE int sqlite3RealSameAsInt(double r1, sqlite3_int64 i){
  71570. double r2 = (double)i;
  71571. return r1==0.0
  71572. || (memcmp(&r1, &r2, sizeof(r1))==0
  71573. && i >= -2251799813685248LL && i < 2251799813685248LL);
  71574. }
  71575. /*
  71576. ** Convert pMem so that it has type MEM_Real or MEM_Int.
  71577. ** Invalidate any prior representations.
  71578. **
  71579. ** Every effort is made to force the conversion, even if the input
  71580. ** is a string that does not look completely like a number. Convert
  71581. ** as much of the string as we can and ignore the rest.
  71582. */
  71583. SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){
  71584. testcase( pMem->flags & MEM_Int );
  71585. testcase( pMem->flags & MEM_Real );
  71586. testcase( pMem->flags & MEM_IntReal );
  71587. testcase( pMem->flags & MEM_Null );
  71588. if( (pMem->flags & (MEM_Int|MEM_Real|MEM_IntReal|MEM_Null))==0 ){
  71589. int rc;
  71590. sqlite3_int64 ix;
  71591. assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
  71592. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  71593. rc = sqlite3AtoF(pMem->z, &pMem->u.r, pMem->n, pMem->enc);
  71594. if( ((rc==0 || rc==1) && sqlite3Atoi64(pMem->z, &ix, pMem->n, pMem->enc)<=1)
  71595. || sqlite3RealSameAsInt(pMem->u.r, (ix = (i64)pMem->u.r))
  71596. ){
  71597. pMem->u.i = ix;
  71598. MemSetTypeFlag(pMem, MEM_Int);
  71599. }else{
  71600. MemSetTypeFlag(pMem, MEM_Real);
  71601. }
  71602. }
  71603. assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_IntReal|MEM_Null))!=0 );
  71604. pMem->flags &= ~(MEM_Str|MEM_Blob|MEM_Zero);
  71605. return SQLITE_OK;
  71606. }
  71607. /*
  71608. ** Cast the datatype of the value in pMem according to the affinity
  71609. ** "aff". Casting is different from applying affinity in that a cast
  71610. ** is forced. In other words, the value is converted into the desired
  71611. ** affinity even if that results in loss of data. This routine is
  71612. ** used (for example) to implement the SQL "cast()" operator.
  71613. */
  71614. SQLITE_PRIVATE int sqlite3VdbeMemCast(Mem *pMem, u8 aff, u8 encoding){
  71615. if( pMem->flags & MEM_Null ) return SQLITE_OK;
  71616. switch( aff ){
  71617. case SQLITE_AFF_BLOB: { /* Really a cast to BLOB */
  71618. if( (pMem->flags & MEM_Blob)==0 ){
  71619. sqlite3ValueApplyAffinity(pMem, SQLITE_AFF_TEXT, encoding);
  71620. assert( pMem->flags & MEM_Str || pMem->db->mallocFailed );
  71621. if( pMem->flags & MEM_Str ) MemSetTypeFlag(pMem, MEM_Blob);
  71622. }else{
  71623. pMem->flags &= ~(MEM_TypeMask&~MEM_Blob);
  71624. }
  71625. break;
  71626. }
  71627. case SQLITE_AFF_NUMERIC: {
  71628. sqlite3VdbeMemNumerify(pMem);
  71629. break;
  71630. }
  71631. case SQLITE_AFF_INTEGER: {
  71632. sqlite3VdbeMemIntegerify(pMem);
  71633. break;
  71634. }
  71635. case SQLITE_AFF_REAL: {
  71636. sqlite3VdbeMemRealify(pMem);
  71637. break;
  71638. }
  71639. default: {
  71640. assert( aff==SQLITE_AFF_TEXT );
  71641. assert( MEM_Str==(MEM_Blob>>3) );
  71642. pMem->flags |= (pMem->flags&MEM_Blob)>>3;
  71643. sqlite3ValueApplyAffinity(pMem, SQLITE_AFF_TEXT, encoding);
  71644. assert( pMem->flags & MEM_Str || pMem->db->mallocFailed );
  71645. pMem->flags &= ~(MEM_Int|MEM_Real|MEM_IntReal|MEM_Blob|MEM_Zero);
  71646. return sqlite3VdbeChangeEncoding(pMem, encoding);
  71647. }
  71648. }
  71649. return SQLITE_OK;
  71650. }
  71651. /*
  71652. ** Initialize bulk memory to be a consistent Mem object.
  71653. **
  71654. ** The minimum amount of initialization feasible is performed.
  71655. */
  71656. SQLITE_PRIVATE void sqlite3VdbeMemInit(Mem *pMem, sqlite3 *db, u16 flags){
  71657. assert( (flags & ~MEM_TypeMask)==0 );
  71658. pMem->flags = flags;
  71659. pMem->db = db;
  71660. pMem->szMalloc = 0;
  71661. }
  71662. /*
  71663. ** Delete any previous value and set the value stored in *pMem to NULL.
  71664. **
  71665. ** This routine calls the Mem.xDel destructor to dispose of values that
  71666. ** require the destructor. But it preserves the Mem.zMalloc memory allocation.
  71667. ** To free all resources, use sqlite3VdbeMemRelease(), which both calls this
  71668. ** routine to invoke the destructor and deallocates Mem.zMalloc.
  71669. **
  71670. ** Use this routine to reset the Mem prior to insert a new value.
  71671. **
  71672. ** Use sqlite3VdbeMemRelease() to complete erase the Mem prior to abandoning it.
  71673. */
  71674. SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){
  71675. if( VdbeMemDynamic(pMem) ){
  71676. vdbeMemClearExternAndSetNull(pMem);
  71677. }else{
  71678. pMem->flags = MEM_Null;
  71679. }
  71680. }
  71681. SQLITE_PRIVATE void sqlite3ValueSetNull(sqlite3_value *p){
  71682. sqlite3VdbeMemSetNull((Mem*)p);
  71683. }
  71684. /*
  71685. ** Delete any previous value and set the value to be a BLOB of length
  71686. ** n containing all zeros.
  71687. */
  71688. SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
  71689. sqlite3VdbeMemRelease(pMem);
  71690. pMem->flags = MEM_Blob|MEM_Zero;
  71691. pMem->n = 0;
  71692. if( n<0 ) n = 0;
  71693. pMem->u.nZero = n;
  71694. pMem->enc = SQLITE_UTF8;
  71695. pMem->z = 0;
  71696. }
  71697. /*
  71698. ** The pMem is known to contain content that needs to be destroyed prior
  71699. ** to a value change. So invoke the destructor, then set the value to
  71700. ** a 64-bit integer.
  71701. */
  71702. static SQLITE_NOINLINE void vdbeReleaseAndSetInt64(Mem *pMem, i64 val){
  71703. sqlite3VdbeMemSetNull(pMem);
  71704. pMem->u.i = val;
  71705. pMem->flags = MEM_Int;
  71706. }
  71707. /*
  71708. ** Delete any previous value and set the value stored in *pMem to val,
  71709. ** manifest type INTEGER.
  71710. */
  71711. SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
  71712. if( VdbeMemDynamic(pMem) ){
  71713. vdbeReleaseAndSetInt64(pMem, val);
  71714. }else{
  71715. pMem->u.i = val;
  71716. pMem->flags = MEM_Int;
  71717. }
  71718. }
  71719. /* A no-op destructor */
  71720. SQLITE_PRIVATE void sqlite3NoopDestructor(void *p){ UNUSED_PARAMETER(p); }
  71721. /*
  71722. ** Set the value stored in *pMem should already be a NULL.
  71723. ** Also store a pointer to go with it.
  71724. */
  71725. SQLITE_PRIVATE void sqlite3VdbeMemSetPointer(
  71726. Mem *pMem,
  71727. void *pPtr,
  71728. const char *zPType,
  71729. void (*xDestructor)(void*)
  71730. ){
  71731. assert( pMem->flags==MEM_Null );
  71732. pMem->u.zPType = zPType ? zPType : "";
  71733. pMem->z = pPtr;
  71734. pMem->flags = MEM_Null|MEM_Dyn|MEM_Subtype|MEM_Term;
  71735. pMem->eSubtype = 'p';
  71736. pMem->xDel = xDestructor ? xDestructor : sqlite3NoopDestructor;
  71737. }
  71738. #ifndef SQLITE_OMIT_FLOATING_POINT
  71739. /*
  71740. ** Delete any previous value and set the value stored in *pMem to val,
  71741. ** manifest type REAL.
  71742. */
  71743. SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
  71744. sqlite3VdbeMemSetNull(pMem);
  71745. if( !sqlite3IsNaN(val) ){
  71746. pMem->u.r = val;
  71747. pMem->flags = MEM_Real;
  71748. }
  71749. }
  71750. #endif
  71751. #ifdef SQLITE_DEBUG
  71752. /*
  71753. ** Return true if the Mem holds a RowSet object. This routine is intended
  71754. ** for use inside of assert() statements.
  71755. */
  71756. SQLITE_PRIVATE int sqlite3VdbeMemIsRowSet(const Mem *pMem){
  71757. return (pMem->flags&(MEM_Blob|MEM_Dyn))==(MEM_Blob|MEM_Dyn)
  71758. && pMem->xDel==sqlite3RowSetDelete;
  71759. }
  71760. #endif
  71761. /*
  71762. ** Delete any previous value and set the value of pMem to be an
  71763. ** empty boolean index.
  71764. **
  71765. ** Return SQLITE_OK on success and SQLITE_NOMEM if a memory allocation
  71766. ** error occurs.
  71767. */
  71768. SQLITE_PRIVATE int sqlite3VdbeMemSetRowSet(Mem *pMem){
  71769. sqlite3 *db = pMem->db;
  71770. RowSet *p;
  71771. assert( db!=0 );
  71772. assert( !sqlite3VdbeMemIsRowSet(pMem) );
  71773. sqlite3VdbeMemRelease(pMem);
  71774. p = sqlite3RowSetInit(db);
  71775. if( p==0 ) return SQLITE_NOMEM;
  71776. pMem->z = (char*)p;
  71777. pMem->flags = MEM_Blob|MEM_Dyn;
  71778. pMem->xDel = sqlite3RowSetDelete;
  71779. return SQLITE_OK;
  71780. }
  71781. /*
  71782. ** Return true if the Mem object contains a TEXT or BLOB that is
  71783. ** too large - whose size exceeds SQLITE_MAX_LENGTH.
  71784. */
  71785. SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){
  71786. assert( p->db!=0 );
  71787. if( p->flags & (MEM_Str|MEM_Blob) ){
  71788. int n = p->n;
  71789. if( p->flags & MEM_Zero ){
  71790. n += p->u.nZero;
  71791. }
  71792. return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
  71793. }
  71794. return 0;
  71795. }
  71796. #ifdef SQLITE_DEBUG
  71797. /*
  71798. ** This routine prepares a memory cell for modification by breaking
  71799. ** its link to a shallow copy and by marking any current shallow
  71800. ** copies of this cell as invalid.
  71801. **
  71802. ** This is used for testing and debugging only - to help ensure that shallow
  71803. ** copies (created by OP_SCopy) are not misused.
  71804. */
  71805. SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe *pVdbe, Mem *pMem){
  71806. int i;
  71807. Mem *pX;
  71808. for(i=1, pX=pVdbe->aMem+1; i<pVdbe->nMem; i++, pX++){
  71809. if( pX->pScopyFrom==pMem ){
  71810. u16 mFlags;
  71811. if( pVdbe->db->flags & SQLITE_VdbeTrace ){
  71812. sqlite3DebugPrintf("Invalidate R[%d] due to change in R[%d]\n",
  71813. (int)(pX - pVdbe->aMem), (int)(pMem - pVdbe->aMem));
  71814. }
  71815. /* If pX is marked as a shallow copy of pMem, then try to verify that
  71816. ** no significant changes have been made to pX since the OP_SCopy.
  71817. ** A significant change would indicated a missed call to this
  71818. ** function for pX. Minor changes, such as adding or removing a
  71819. ** dual type, are allowed, as long as the underlying value is the
  71820. ** same. */
  71821. mFlags = pMem->flags & pX->flags & pX->mScopyFlags;
  71822. assert( (mFlags&(MEM_Int|MEM_IntReal))==0 || pMem->u.i==pX->u.i );
  71823. /* pMem is the register that is changing. But also mark pX as
  71824. ** undefined so that we can quickly detect the shallow-copy error */
  71825. pX->flags = MEM_Undefined;
  71826. pX->pScopyFrom = 0;
  71827. }
  71828. }
  71829. pMem->pScopyFrom = 0;
  71830. }
  71831. #endif /* SQLITE_DEBUG */
  71832. /*
  71833. ** Make an shallow copy of pFrom into pTo. Prior contents of
  71834. ** pTo are freed. The pFrom->z field is not duplicated. If
  71835. ** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
  71836. ** and flags gets srcType (either MEM_Ephem or MEM_Static).
  71837. */
  71838. static SQLITE_NOINLINE void vdbeClrCopy(Mem *pTo, const Mem *pFrom, int eType){
  71839. vdbeMemClearExternAndSetNull(pTo);
  71840. assert( !VdbeMemDynamic(pTo) );
  71841. sqlite3VdbeMemShallowCopy(pTo, pFrom, eType);
  71842. }
  71843. SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
  71844. assert( !sqlite3VdbeMemIsRowSet(pFrom) );
  71845. assert( pTo->db==pFrom->db );
  71846. if( VdbeMemDynamic(pTo) ){ vdbeClrCopy(pTo,pFrom,srcType); return; }
  71847. memcpy(pTo, pFrom, MEMCELLSIZE);
  71848. if( (pFrom->flags&MEM_Static)==0 ){
  71849. pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
  71850. assert( srcType==MEM_Ephem || srcType==MEM_Static );
  71851. pTo->flags |= srcType;
  71852. }
  71853. }
  71854. /*
  71855. ** Make a full copy of pFrom into pTo. Prior contents of pTo are
  71856. ** freed before the copy is made.
  71857. */
  71858. SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
  71859. int rc = SQLITE_OK;
  71860. assert( !sqlite3VdbeMemIsRowSet(pFrom) );
  71861. if( VdbeMemDynamic(pTo) ) vdbeMemClearExternAndSetNull(pTo);
  71862. memcpy(pTo, pFrom, MEMCELLSIZE);
  71863. pTo->flags &= ~MEM_Dyn;
  71864. if( pTo->flags&(MEM_Str|MEM_Blob) ){
  71865. if( 0==(pFrom->flags&MEM_Static) ){
  71866. pTo->flags |= MEM_Ephem;
  71867. rc = sqlite3VdbeMemMakeWriteable(pTo);
  71868. }
  71869. }
  71870. return rc;
  71871. }
  71872. /*
  71873. ** Transfer the contents of pFrom to pTo. Any existing value in pTo is
  71874. ** freed. If pFrom contains ephemeral data, a copy is made.
  71875. **
  71876. ** pFrom contains an SQL NULL when this routine returns.
  71877. */
  71878. SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
  71879. assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
  71880. assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
  71881. assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
  71882. sqlite3VdbeMemRelease(pTo);
  71883. memcpy(pTo, pFrom, sizeof(Mem));
  71884. pFrom->flags = MEM_Null;
  71885. pFrom->szMalloc = 0;
  71886. }
  71887. /*
  71888. ** Change the value of a Mem to be a string or a BLOB.
  71889. **
  71890. ** The memory management strategy depends on the value of the xDel
  71891. ** parameter. If the value passed is SQLITE_TRANSIENT, then the
  71892. ** string is copied into a (possibly existing) buffer managed by the
  71893. ** Mem structure. Otherwise, any existing buffer is freed and the
  71894. ** pointer copied.
  71895. **
  71896. ** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH
  71897. ** size limit) then no memory allocation occurs. If the string can be
  71898. ** stored without allocating memory, then it is. If a memory allocation
  71899. ** is required to store the string, then value of pMem is unchanged. In
  71900. ** either case, SQLITE_TOOBIG is returned.
  71901. */
  71902. SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
  71903. Mem *pMem, /* Memory cell to set to string value */
  71904. const char *z, /* String pointer */
  71905. int n, /* Bytes in string, or negative */
  71906. u8 enc, /* Encoding of z. 0 for BLOBs */
  71907. void (*xDel)(void*) /* Destructor function */
  71908. ){
  71909. int nByte = n; /* New value for pMem->n */
  71910. int iLimit; /* Maximum allowed string or blob size */
  71911. u16 flags = 0; /* New value for pMem->flags */
  71912. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  71913. assert( !sqlite3VdbeMemIsRowSet(pMem) );
  71914. /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
  71915. if( !z ){
  71916. sqlite3VdbeMemSetNull(pMem);
  71917. return SQLITE_OK;
  71918. }
  71919. if( pMem->db ){
  71920. iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
  71921. }else{
  71922. iLimit = SQLITE_MAX_LENGTH;
  71923. }
  71924. flags = (enc==0?MEM_Blob:MEM_Str);
  71925. if( nByte<0 ){
  71926. assert( enc!=0 );
  71927. if( enc==SQLITE_UTF8 ){
  71928. nByte = 0x7fffffff & (int)strlen(z);
  71929. }else{
  71930. for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
  71931. }
  71932. flags |= MEM_Term;
  71933. }
  71934. /* The following block sets the new values of Mem.z and Mem.xDel. It
  71935. ** also sets a flag in local variable "flags" to indicate the memory
  71936. ** management (one of MEM_Dyn or MEM_Static).
  71937. */
  71938. if( xDel==SQLITE_TRANSIENT ){
  71939. u32 nAlloc = nByte;
  71940. if( flags&MEM_Term ){
  71941. nAlloc += (enc==SQLITE_UTF8?1:2);
  71942. }
  71943. if( nByte>iLimit ){
  71944. return sqlite3ErrorToParser(pMem->db, SQLITE_TOOBIG);
  71945. }
  71946. testcase( nAlloc==0 );
  71947. testcase( nAlloc==31 );
  71948. testcase( nAlloc==32 );
  71949. if( sqlite3VdbeMemClearAndResize(pMem, (int)MAX(nAlloc,32)) ){
  71950. return SQLITE_NOMEM_BKPT;
  71951. }
  71952. memcpy(pMem->z, z, nAlloc);
  71953. }else{
  71954. sqlite3VdbeMemRelease(pMem);
  71955. pMem->z = (char *)z;
  71956. if( xDel==SQLITE_DYNAMIC ){
  71957. pMem->zMalloc = pMem->z;
  71958. pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc);
  71959. }else{
  71960. pMem->xDel = xDel;
  71961. flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
  71962. }
  71963. }
  71964. pMem->n = nByte;
  71965. pMem->flags = flags;
  71966. if( enc ){
  71967. pMem->enc = enc;
  71968. #ifdef SQLITE_ENABLE_SESSION
  71969. }else if( pMem->db==0 ){
  71970. pMem->enc = SQLITE_UTF8;
  71971. #endif
  71972. }else{
  71973. assert( pMem->db!=0 );
  71974. pMem->enc = ENC(pMem->db);
  71975. }
  71976. #ifndef SQLITE_OMIT_UTF16
  71977. if( enc>SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
  71978. return SQLITE_NOMEM_BKPT;
  71979. }
  71980. #endif
  71981. if( nByte>iLimit ){
  71982. return SQLITE_TOOBIG;
  71983. }
  71984. return SQLITE_OK;
  71985. }
  71986. /*
  71987. ** Move data out of a btree key or data field and into a Mem structure.
  71988. ** The data is payload from the entry that pCur is currently pointing
  71989. ** to. offset and amt determine what portion of the data or key to retrieve.
  71990. ** The result is written into the pMem element.
  71991. **
  71992. ** The pMem object must have been initialized. This routine will use
  71993. ** pMem->zMalloc to hold the content from the btree, if possible. New
  71994. ** pMem->zMalloc space will be allocated if necessary. The calling routine
  71995. ** is responsible for making sure that the pMem object is eventually
  71996. ** destroyed.
  71997. **
  71998. ** If this routine fails for any reason (malloc returns NULL or unable
  71999. ** to read from the disk) then the pMem is left in an inconsistent state.
  72000. */
  72001. SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(
  72002. BtCursor *pCur, /* Cursor pointing at record to retrieve. */
  72003. u32 offset, /* Offset from the start of data to return bytes from. */
  72004. u32 amt, /* Number of bytes to return. */
  72005. Mem *pMem /* OUT: Return data in this Mem structure. */
  72006. ){
  72007. int rc;
  72008. pMem->flags = MEM_Null;
  72009. if( sqlite3BtreeMaxRecordSize(pCur)<offset+amt ){
  72010. return SQLITE_CORRUPT_BKPT;
  72011. }
  72012. if( SQLITE_OK==(rc = sqlite3VdbeMemClearAndResize(pMem, amt+1)) ){
  72013. rc = sqlite3BtreePayload(pCur, offset, amt, pMem->z);
  72014. if( rc==SQLITE_OK ){
  72015. pMem->z[amt] = 0; /* Overrun area used when reading malformed records */
  72016. pMem->flags = MEM_Blob;
  72017. pMem->n = (int)amt;
  72018. }else{
  72019. sqlite3VdbeMemRelease(pMem);
  72020. }
  72021. }
  72022. return rc;
  72023. }
  72024. SQLITE_PRIVATE int sqlite3VdbeMemFromBtreeZeroOffset(
  72025. BtCursor *pCur, /* Cursor pointing at record to retrieve. */
  72026. u32 amt, /* Number of bytes to return. */
  72027. Mem *pMem /* OUT: Return data in this Mem structure. */
  72028. ){
  72029. u32 available = 0; /* Number of bytes available on the local btree page */
  72030. int rc = SQLITE_OK; /* Return code */
  72031. assert( sqlite3BtreeCursorIsValid(pCur) );
  72032. assert( !VdbeMemDynamic(pMem) );
  72033. /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert()
  72034. ** that both the BtShared and database handle mutexes are held. */
  72035. assert( !sqlite3VdbeMemIsRowSet(pMem) );
  72036. pMem->z = (char *)sqlite3BtreePayloadFetch(pCur, &available);
  72037. assert( pMem->z!=0 );
  72038. if( amt<=available ){
  72039. pMem->flags = MEM_Blob|MEM_Ephem;
  72040. pMem->n = (int)amt;
  72041. }else{
  72042. rc = sqlite3VdbeMemFromBtree(pCur, 0, amt, pMem);
  72043. }
  72044. return rc;
  72045. }
  72046. /*
  72047. ** The pVal argument is known to be a value other than NULL.
  72048. ** Convert it into a string with encoding enc and return a pointer
  72049. ** to a zero-terminated version of that string.
  72050. */
  72051. static SQLITE_NOINLINE const void *valueToText(sqlite3_value* pVal, u8 enc){
  72052. assert( pVal!=0 );
  72053. assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
  72054. assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
  72055. assert( !sqlite3VdbeMemIsRowSet(pVal) );
  72056. assert( (pVal->flags & (MEM_Null))==0 );
  72057. if( pVal->flags & (MEM_Blob|MEM_Str) ){
  72058. if( ExpandBlob(pVal) ) return 0;
  72059. pVal->flags |= MEM_Str;
  72060. if( pVal->enc != (enc & ~SQLITE_UTF16_ALIGNED) ){
  72061. sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
  72062. }
  72063. if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
  72064. assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
  72065. if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
  72066. return 0;
  72067. }
  72068. }
  72069. sqlite3VdbeMemNulTerminate(pVal); /* IMP: R-31275-44060 */
  72070. }else{
  72071. sqlite3VdbeMemStringify(pVal, enc, 0);
  72072. assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
  72073. }
  72074. assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
  72075. || pVal->db->mallocFailed );
  72076. if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
  72077. assert( sqlite3VdbeMemValidStrRep(pVal) );
  72078. return pVal->z;
  72079. }else{
  72080. return 0;
  72081. }
  72082. }
  72083. /* This function is only available internally, it is not part of the
  72084. ** external API. It works in a similar way to sqlite3_value_text(),
  72085. ** except the data returned is in the encoding specified by the second
  72086. ** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
  72087. ** SQLITE_UTF8.
  72088. **
  72089. ** (2006-02-16:) The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
  72090. ** If that is the case, then the result must be aligned on an even byte
  72091. ** boundary.
  72092. */
  72093. SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
  72094. if( !pVal ) return 0;
  72095. assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
  72096. assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
  72097. assert( !sqlite3VdbeMemIsRowSet(pVal) );
  72098. if( (pVal->flags&(MEM_Str|MEM_Term))==(MEM_Str|MEM_Term) && pVal->enc==enc ){
  72099. assert( sqlite3VdbeMemValidStrRep(pVal) );
  72100. return pVal->z;
  72101. }
  72102. if( pVal->flags&MEM_Null ){
  72103. return 0;
  72104. }
  72105. return valueToText(pVal, enc);
  72106. }
  72107. /*
  72108. ** Create a new sqlite3_value object.
  72109. */
  72110. SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){
  72111. Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
  72112. if( p ){
  72113. p->flags = MEM_Null;
  72114. p->db = db;
  72115. }
  72116. return p;
  72117. }
  72118. /*
  72119. ** Context object passed by sqlite3Stat4ProbeSetValue() through to
  72120. ** valueNew(). See comments above valueNew() for details.
  72121. */
  72122. struct ValueNewStat4Ctx {
  72123. Parse *pParse;
  72124. Index *pIdx;
  72125. UnpackedRecord **ppRec;
  72126. int iVal;
  72127. };
  72128. /*
  72129. ** Allocate and return a pointer to a new sqlite3_value object. If
  72130. ** the second argument to this function is NULL, the object is allocated
  72131. ** by calling sqlite3ValueNew().
  72132. **
  72133. ** Otherwise, if the second argument is non-zero, then this function is
  72134. ** being called indirectly by sqlite3Stat4ProbeSetValue(). If it has not
  72135. ** already been allocated, allocate the UnpackedRecord structure that
  72136. ** that function will return to its caller here. Then return a pointer to
  72137. ** an sqlite3_value within the UnpackedRecord.a[] array.
  72138. */
  72139. static sqlite3_value *valueNew(sqlite3 *db, struct ValueNewStat4Ctx *p){
  72140. #ifdef SQLITE_ENABLE_STAT4
  72141. if( p ){
  72142. UnpackedRecord *pRec = p->ppRec[0];
  72143. if( pRec==0 ){
  72144. Index *pIdx = p->pIdx; /* Index being probed */
  72145. int nByte; /* Bytes of space to allocate */
  72146. int i; /* Counter variable */
  72147. int nCol = pIdx->nColumn; /* Number of index columns including rowid */
  72148. nByte = sizeof(Mem) * nCol + ROUND8(sizeof(UnpackedRecord));
  72149. pRec = (UnpackedRecord*)sqlite3DbMallocZero(db, nByte);
  72150. if( pRec ){
  72151. pRec->pKeyInfo = sqlite3KeyInfoOfIndex(p->pParse, pIdx);
  72152. if( pRec->pKeyInfo ){
  72153. assert( pRec->pKeyInfo->nAllField==nCol );
  72154. assert( pRec->pKeyInfo->enc==ENC(db) );
  72155. pRec->aMem = (Mem *)((u8*)pRec + ROUND8(sizeof(UnpackedRecord)));
  72156. for(i=0; i<nCol; i++){
  72157. pRec->aMem[i].flags = MEM_Null;
  72158. pRec->aMem[i].db = db;
  72159. }
  72160. }else{
  72161. sqlite3DbFreeNN(db, pRec);
  72162. pRec = 0;
  72163. }
  72164. }
  72165. if( pRec==0 ) return 0;
  72166. p->ppRec[0] = pRec;
  72167. }
  72168. pRec->nField = p->iVal+1;
  72169. return &pRec->aMem[p->iVal];
  72170. }
  72171. #else
  72172. UNUSED_PARAMETER(p);
  72173. #endif /* defined(SQLITE_ENABLE_STAT4) */
  72174. return sqlite3ValueNew(db);
  72175. }
  72176. /*
  72177. ** The expression object indicated by the second argument is guaranteed
  72178. ** to be a scalar SQL function. If
  72179. **
  72180. ** * all function arguments are SQL literals,
  72181. ** * one of the SQLITE_FUNC_CONSTANT or _SLOCHNG function flags is set, and
  72182. ** * the SQLITE_FUNC_NEEDCOLL function flag is not set,
  72183. **
  72184. ** then this routine attempts to invoke the SQL function. Assuming no
  72185. ** error occurs, output parameter (*ppVal) is set to point to a value
  72186. ** object containing the result before returning SQLITE_OK.
  72187. **
  72188. ** Affinity aff is applied to the result of the function before returning.
  72189. ** If the result is a text value, the sqlite3_value object uses encoding
  72190. ** enc.
  72191. **
  72192. ** If the conditions above are not met, this function returns SQLITE_OK
  72193. ** and sets (*ppVal) to NULL. Or, if an error occurs, (*ppVal) is set to
  72194. ** NULL and an SQLite error code returned.
  72195. */
  72196. #ifdef SQLITE_ENABLE_STAT4
  72197. static int valueFromFunction(
  72198. sqlite3 *db, /* The database connection */
  72199. Expr *p, /* The expression to evaluate */
  72200. u8 enc, /* Encoding to use */
  72201. u8 aff, /* Affinity to use */
  72202. sqlite3_value **ppVal, /* Write the new value here */
  72203. struct ValueNewStat4Ctx *pCtx /* Second argument for valueNew() */
  72204. ){
  72205. sqlite3_context ctx; /* Context object for function invocation */
  72206. sqlite3_value **apVal = 0; /* Function arguments */
  72207. int nVal = 0; /* Size of apVal[] array */
  72208. FuncDef *pFunc = 0; /* Function definition */
  72209. sqlite3_value *pVal = 0; /* New value */
  72210. int rc = SQLITE_OK; /* Return code */
  72211. ExprList *pList = 0; /* Function arguments */
  72212. int i; /* Iterator variable */
  72213. assert( pCtx!=0 );
  72214. assert( (p->flags & EP_TokenOnly)==0 );
  72215. pList = p->x.pList;
  72216. if( pList ) nVal = pList->nExpr;
  72217. pFunc = sqlite3FindFunction(db, p->u.zToken, nVal, enc, 0);
  72218. assert( pFunc );
  72219. if( (pFunc->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG))==0
  72220. || (pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL)
  72221. ){
  72222. return SQLITE_OK;
  72223. }
  72224. if( pList ){
  72225. apVal = (sqlite3_value**)sqlite3DbMallocZero(db, sizeof(apVal[0]) * nVal);
  72226. if( apVal==0 ){
  72227. rc = SQLITE_NOMEM_BKPT;
  72228. goto value_from_function_out;
  72229. }
  72230. for(i=0; i<nVal; i++){
  72231. rc = sqlite3ValueFromExpr(db, pList->a[i].pExpr, enc, aff, &apVal[i]);
  72232. if( apVal[i]==0 || rc!=SQLITE_OK ) goto value_from_function_out;
  72233. }
  72234. }
  72235. pVal = valueNew(db, pCtx);
  72236. if( pVal==0 ){
  72237. rc = SQLITE_NOMEM_BKPT;
  72238. goto value_from_function_out;
  72239. }
  72240. assert( pCtx->pParse->rc==SQLITE_OK );
  72241. memset(&ctx, 0, sizeof(ctx));
  72242. ctx.pOut = pVal;
  72243. ctx.pFunc = pFunc;
  72244. pFunc->xSFunc(&ctx, nVal, apVal);
  72245. if( ctx.isError ){
  72246. rc = ctx.isError;
  72247. sqlite3ErrorMsg(pCtx->pParse, "%s", sqlite3_value_text(pVal));
  72248. }else{
  72249. sqlite3ValueApplyAffinity(pVal, aff, SQLITE_UTF8);
  72250. assert( rc==SQLITE_OK );
  72251. rc = sqlite3VdbeChangeEncoding(pVal, enc);
  72252. if( rc==SQLITE_OK && sqlite3VdbeMemTooBig(pVal) ){
  72253. rc = SQLITE_TOOBIG;
  72254. pCtx->pParse->nErr++;
  72255. }
  72256. }
  72257. pCtx->pParse->rc = rc;
  72258. value_from_function_out:
  72259. if( rc!=SQLITE_OK ){
  72260. pVal = 0;
  72261. }
  72262. if( apVal ){
  72263. for(i=0; i<nVal; i++){
  72264. sqlite3ValueFree(apVal[i]);
  72265. }
  72266. sqlite3DbFreeNN(db, apVal);
  72267. }
  72268. *ppVal = pVal;
  72269. return rc;
  72270. }
  72271. #else
  72272. # define valueFromFunction(a,b,c,d,e,f) SQLITE_OK
  72273. #endif /* defined(SQLITE_ENABLE_STAT4) */
  72274. /*
  72275. ** Extract a value from the supplied expression in the manner described
  72276. ** above sqlite3ValueFromExpr(). Allocate the sqlite3_value object
  72277. ** using valueNew().
  72278. **
  72279. ** If pCtx is NULL and an error occurs after the sqlite3_value object
  72280. ** has been allocated, it is freed before returning. Or, if pCtx is not
  72281. ** NULL, it is assumed that the caller will free any allocated object
  72282. ** in all cases.
  72283. */
  72284. static int valueFromExpr(
  72285. sqlite3 *db, /* The database connection */
  72286. Expr *pExpr, /* The expression to evaluate */
  72287. u8 enc, /* Encoding to use */
  72288. u8 affinity, /* Affinity to use */
  72289. sqlite3_value **ppVal, /* Write the new value here */
  72290. struct ValueNewStat4Ctx *pCtx /* Second argument for valueNew() */
  72291. ){
  72292. int op;
  72293. char *zVal = 0;
  72294. sqlite3_value *pVal = 0;
  72295. int negInt = 1;
  72296. const char *zNeg = "";
  72297. int rc = SQLITE_OK;
  72298. assert( pExpr!=0 );
  72299. while( (op = pExpr->op)==TK_UPLUS || op==TK_SPAN ) pExpr = pExpr->pLeft;
  72300. #if defined(SQLITE_ENABLE_STAT4)
  72301. if( op==TK_REGISTER ) op = pExpr->op2;
  72302. #else
  72303. if( NEVER(op==TK_REGISTER) ) op = pExpr->op2;
  72304. #endif
  72305. /* Compressed expressions only appear when parsing the DEFAULT clause
  72306. ** on a table column definition, and hence only when pCtx==0. This
  72307. ** check ensures that an EP_TokenOnly expression is never passed down
  72308. ** into valueFromFunction(). */
  72309. assert( (pExpr->flags & EP_TokenOnly)==0 || pCtx==0 );
  72310. if( op==TK_CAST ){
  72311. u8 aff = sqlite3AffinityType(pExpr->u.zToken,0);
  72312. rc = valueFromExpr(db, pExpr->pLeft, enc, aff, ppVal, pCtx);
  72313. testcase( rc!=SQLITE_OK );
  72314. if( *ppVal ){
  72315. sqlite3VdbeMemCast(*ppVal, aff, SQLITE_UTF8);
  72316. sqlite3ValueApplyAffinity(*ppVal, affinity, SQLITE_UTF8);
  72317. }
  72318. return rc;
  72319. }
  72320. /* Handle negative integers in a single step. This is needed in the
  72321. ** case when the value is -9223372036854775808.
  72322. */
  72323. if( op==TK_UMINUS
  72324. && (pExpr->pLeft->op==TK_INTEGER || pExpr->pLeft->op==TK_FLOAT) ){
  72325. pExpr = pExpr->pLeft;
  72326. op = pExpr->op;
  72327. negInt = -1;
  72328. zNeg = "-";
  72329. }
  72330. if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
  72331. pVal = valueNew(db, pCtx);
  72332. if( pVal==0 ) goto no_mem;
  72333. if( ExprHasProperty(pExpr, EP_IntValue) ){
  72334. sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue*negInt);
  72335. }else{
  72336. zVal = sqlite3MPrintf(db, "%s%s", zNeg, pExpr->u.zToken);
  72337. if( zVal==0 ) goto no_mem;
  72338. sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
  72339. }
  72340. if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_BLOB ){
  72341. sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8);
  72342. }else{
  72343. sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8);
  72344. }
  72345. assert( (pVal->flags & MEM_IntReal)==0 );
  72346. if( pVal->flags & (MEM_Int|MEM_IntReal|MEM_Real) ){
  72347. testcase( pVal->flags & MEM_Int );
  72348. testcase( pVal->flags & MEM_Real );
  72349. pVal->flags &= ~MEM_Str;
  72350. }
  72351. if( enc!=SQLITE_UTF8 ){
  72352. rc = sqlite3VdbeChangeEncoding(pVal, enc);
  72353. }
  72354. }else if( op==TK_UMINUS ) {
  72355. /* This branch happens for multiple negative signs. Ex: -(-5) */
  72356. if( SQLITE_OK==valueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal,pCtx)
  72357. && pVal!=0
  72358. ){
  72359. sqlite3VdbeMemNumerify(pVal);
  72360. if( pVal->flags & MEM_Real ){
  72361. pVal->u.r = -pVal->u.r;
  72362. }else if( pVal->u.i==SMALLEST_INT64 ){
  72363. #ifndef SQLITE_OMIT_FLOATING_POINT
  72364. pVal->u.r = -(double)SMALLEST_INT64;
  72365. #else
  72366. pVal->u.r = LARGEST_INT64;
  72367. #endif
  72368. MemSetTypeFlag(pVal, MEM_Real);
  72369. }else{
  72370. pVal->u.i = -pVal->u.i;
  72371. }
  72372. sqlite3ValueApplyAffinity(pVal, affinity, enc);
  72373. }
  72374. }else if( op==TK_NULL ){
  72375. pVal = valueNew(db, pCtx);
  72376. if( pVal==0 ) goto no_mem;
  72377. sqlite3VdbeMemSetNull(pVal);
  72378. }
  72379. #ifndef SQLITE_OMIT_BLOB_LITERAL
  72380. else if( op==TK_BLOB ){
  72381. int nVal;
  72382. assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
  72383. assert( pExpr->u.zToken[1]=='\'' );
  72384. pVal = valueNew(db, pCtx);
  72385. if( !pVal ) goto no_mem;
  72386. zVal = &pExpr->u.zToken[2];
  72387. nVal = sqlite3Strlen30(zVal)-1;
  72388. assert( zVal[nVal]=='\'' );
  72389. sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
  72390. 0, SQLITE_DYNAMIC);
  72391. }
  72392. #endif
  72393. #ifdef SQLITE_ENABLE_STAT4
  72394. else if( op==TK_FUNCTION && pCtx!=0 ){
  72395. rc = valueFromFunction(db, pExpr, enc, affinity, &pVal, pCtx);
  72396. }
  72397. #endif
  72398. else if( op==TK_TRUEFALSE ){
  72399. pVal = valueNew(db, pCtx);
  72400. if( pVal ){
  72401. pVal->flags = MEM_Int;
  72402. pVal->u.i = pExpr->u.zToken[4]==0;
  72403. }
  72404. }
  72405. *ppVal = pVal;
  72406. return rc;
  72407. no_mem:
  72408. #ifdef SQLITE_ENABLE_STAT4
  72409. if( pCtx==0 || pCtx->pParse->nErr==0 )
  72410. #endif
  72411. sqlite3OomFault(db);
  72412. sqlite3DbFree(db, zVal);
  72413. assert( *ppVal==0 );
  72414. #ifdef SQLITE_ENABLE_STAT4
  72415. if( pCtx==0 ) sqlite3ValueFree(pVal);
  72416. #else
  72417. assert( pCtx==0 ); sqlite3ValueFree(pVal);
  72418. #endif
  72419. return SQLITE_NOMEM_BKPT;
  72420. }
  72421. /*
  72422. ** Create a new sqlite3_value object, containing the value of pExpr.
  72423. **
  72424. ** This only works for very simple expressions that consist of one constant
  72425. ** token (i.e. "5", "5.1", "'a string'"). If the expression can
  72426. ** be converted directly into a value, then the value is allocated and
  72427. ** a pointer written to *ppVal. The caller is responsible for deallocating
  72428. ** the value by passing it to sqlite3ValueFree() later on. If the expression
  72429. ** cannot be converted to a value, then *ppVal is set to NULL.
  72430. */
  72431. SQLITE_PRIVATE int sqlite3ValueFromExpr(
  72432. sqlite3 *db, /* The database connection */
  72433. Expr *pExpr, /* The expression to evaluate */
  72434. u8 enc, /* Encoding to use */
  72435. u8 affinity, /* Affinity to use */
  72436. sqlite3_value **ppVal /* Write the new value here */
  72437. ){
  72438. return pExpr ? valueFromExpr(db, pExpr, enc, affinity, ppVal, 0) : 0;
  72439. }
  72440. #ifdef SQLITE_ENABLE_STAT4
  72441. /*
  72442. ** Attempt to extract a value from pExpr and use it to construct *ppVal.
  72443. **
  72444. ** If pAlloc is not NULL, then an UnpackedRecord object is created for
  72445. ** pAlloc if one does not exist and the new value is added to the
  72446. ** UnpackedRecord object.
  72447. **
  72448. ** A value is extracted in the following cases:
  72449. **
  72450. ** * (pExpr==0). In this case the value is assumed to be an SQL NULL,
  72451. **
  72452. ** * The expression is a bound variable, and this is a reprepare, or
  72453. **
  72454. ** * The expression is a literal value.
  72455. **
  72456. ** On success, *ppVal is made to point to the extracted value. The caller
  72457. ** is responsible for ensuring that the value is eventually freed.
  72458. */
  72459. static int stat4ValueFromExpr(
  72460. Parse *pParse, /* Parse context */
  72461. Expr *pExpr, /* The expression to extract a value from */
  72462. u8 affinity, /* Affinity to use */
  72463. struct ValueNewStat4Ctx *pAlloc,/* How to allocate space. Or NULL */
  72464. sqlite3_value **ppVal /* OUT: New value object (or NULL) */
  72465. ){
  72466. int rc = SQLITE_OK;
  72467. sqlite3_value *pVal = 0;
  72468. sqlite3 *db = pParse->db;
  72469. /* Skip over any TK_COLLATE nodes */
  72470. pExpr = sqlite3ExprSkipCollate(pExpr);
  72471. assert( pExpr==0 || pExpr->op!=TK_REGISTER || pExpr->op2!=TK_VARIABLE );
  72472. if( !pExpr ){
  72473. pVal = valueNew(db, pAlloc);
  72474. if( pVal ){
  72475. sqlite3VdbeMemSetNull((Mem*)pVal);
  72476. }
  72477. }else if( pExpr->op==TK_VARIABLE && (db->flags & SQLITE_EnableQPSG)==0 ){
  72478. Vdbe *v;
  72479. int iBindVar = pExpr->iColumn;
  72480. sqlite3VdbeSetVarmask(pParse->pVdbe, iBindVar);
  72481. if( (v = pParse->pReprepare)!=0 ){
  72482. pVal = valueNew(db, pAlloc);
  72483. if( pVal ){
  72484. rc = sqlite3VdbeMemCopy((Mem*)pVal, &v->aVar[iBindVar-1]);
  72485. sqlite3ValueApplyAffinity(pVal, affinity, ENC(db));
  72486. pVal->db = pParse->db;
  72487. }
  72488. }
  72489. }else{
  72490. rc = valueFromExpr(db, pExpr, ENC(db), affinity, &pVal, pAlloc);
  72491. }
  72492. assert( pVal==0 || pVal->db==db );
  72493. *ppVal = pVal;
  72494. return rc;
  72495. }
  72496. /*
  72497. ** This function is used to allocate and populate UnpackedRecord
  72498. ** structures intended to be compared against sample index keys stored
  72499. ** in the sqlite_stat4 table.
  72500. **
  72501. ** A single call to this function populates zero or more fields of the
  72502. ** record starting with field iVal (fields are numbered from left to
  72503. ** right starting with 0). A single field is populated if:
  72504. **
  72505. ** * (pExpr==0). In this case the value is assumed to be an SQL NULL,
  72506. **
  72507. ** * The expression is a bound variable, and this is a reprepare, or
  72508. **
  72509. ** * The sqlite3ValueFromExpr() function is able to extract a value
  72510. ** from the expression (i.e. the expression is a literal value).
  72511. **
  72512. ** Or, if pExpr is a TK_VECTOR, one field is populated for each of the
  72513. ** vector components that match either of the two latter criteria listed
  72514. ** above.
  72515. **
  72516. ** Before any value is appended to the record, the affinity of the
  72517. ** corresponding column within index pIdx is applied to it. Before
  72518. ** this function returns, output parameter *pnExtract is set to the
  72519. ** number of values appended to the record.
  72520. **
  72521. ** When this function is called, *ppRec must either point to an object
  72522. ** allocated by an earlier call to this function, or must be NULL. If it
  72523. ** is NULL and a value can be successfully extracted, a new UnpackedRecord
  72524. ** is allocated (and *ppRec set to point to it) before returning.
  72525. **
  72526. ** Unless an error is encountered, SQLITE_OK is returned. It is not an
  72527. ** error if a value cannot be extracted from pExpr. If an error does
  72528. ** occur, an SQLite error code is returned.
  72529. */
  72530. SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(
  72531. Parse *pParse, /* Parse context */
  72532. Index *pIdx, /* Index being probed */
  72533. UnpackedRecord **ppRec, /* IN/OUT: Probe record */
  72534. Expr *pExpr, /* The expression to extract a value from */
  72535. int nElem, /* Maximum number of values to append */
  72536. int iVal, /* Array element to populate */
  72537. int *pnExtract /* OUT: Values appended to the record */
  72538. ){
  72539. int rc = SQLITE_OK;
  72540. int nExtract = 0;
  72541. if( pExpr==0 || pExpr->op!=TK_SELECT ){
  72542. int i;
  72543. struct ValueNewStat4Ctx alloc;
  72544. alloc.pParse = pParse;
  72545. alloc.pIdx = pIdx;
  72546. alloc.ppRec = ppRec;
  72547. for(i=0; i<nElem; i++){
  72548. sqlite3_value *pVal = 0;
  72549. Expr *pElem = (pExpr ? sqlite3VectorFieldSubexpr(pExpr, i) : 0);
  72550. u8 aff = sqlite3IndexColumnAffinity(pParse->db, pIdx, iVal+i);
  72551. alloc.iVal = iVal+i;
  72552. rc = stat4ValueFromExpr(pParse, pElem, aff, &alloc, &pVal);
  72553. if( !pVal ) break;
  72554. nExtract++;
  72555. }
  72556. }
  72557. *pnExtract = nExtract;
  72558. return rc;
  72559. }
  72560. /*
  72561. ** Attempt to extract a value from expression pExpr using the methods
  72562. ** as described for sqlite3Stat4ProbeSetValue() above.
  72563. **
  72564. ** If successful, set *ppVal to point to a new value object and return
  72565. ** SQLITE_OK. If no value can be extracted, but no other error occurs
  72566. ** (e.g. OOM), return SQLITE_OK and set *ppVal to NULL. Or, if an error
  72567. ** does occur, return an SQLite error code. The final value of *ppVal
  72568. ** is undefined in this case.
  72569. */
  72570. SQLITE_PRIVATE int sqlite3Stat4ValueFromExpr(
  72571. Parse *pParse, /* Parse context */
  72572. Expr *pExpr, /* The expression to extract a value from */
  72573. u8 affinity, /* Affinity to use */
  72574. sqlite3_value **ppVal /* OUT: New value object (or NULL) */
  72575. ){
  72576. return stat4ValueFromExpr(pParse, pExpr, affinity, 0, ppVal);
  72577. }
  72578. /*
  72579. ** Extract the iCol-th column from the nRec-byte record in pRec. Write
  72580. ** the column value into *ppVal. If *ppVal is initially NULL then a new
  72581. ** sqlite3_value object is allocated.
  72582. **
  72583. ** If *ppVal is initially NULL then the caller is responsible for
  72584. ** ensuring that the value written into *ppVal is eventually freed.
  72585. */
  72586. SQLITE_PRIVATE int sqlite3Stat4Column(
  72587. sqlite3 *db, /* Database handle */
  72588. const void *pRec, /* Pointer to buffer containing record */
  72589. int nRec, /* Size of buffer pRec in bytes */
  72590. int iCol, /* Column to extract */
  72591. sqlite3_value **ppVal /* OUT: Extracted value */
  72592. ){
  72593. u32 t = 0; /* a column type code */
  72594. int nHdr; /* Size of the header in the record */
  72595. int iHdr; /* Next unread header byte */
  72596. int iField; /* Next unread data byte */
  72597. int szField = 0; /* Size of the current data field */
  72598. int i; /* Column index */
  72599. u8 *a = (u8*)pRec; /* Typecast byte array */
  72600. Mem *pMem = *ppVal; /* Write result into this Mem object */
  72601. assert( iCol>0 );
  72602. iHdr = getVarint32(a, nHdr);
  72603. if( nHdr>nRec || iHdr>=nHdr ) return SQLITE_CORRUPT_BKPT;
  72604. iField = nHdr;
  72605. for(i=0; i<=iCol; i++){
  72606. iHdr += getVarint32(&a[iHdr], t);
  72607. testcase( iHdr==nHdr );
  72608. testcase( iHdr==nHdr+1 );
  72609. if( iHdr>nHdr ) return SQLITE_CORRUPT_BKPT;
  72610. szField = sqlite3VdbeSerialTypeLen(t);
  72611. iField += szField;
  72612. }
  72613. testcase( iField==nRec );
  72614. testcase( iField==nRec+1 );
  72615. if( iField>nRec ) return SQLITE_CORRUPT_BKPT;
  72616. if( pMem==0 ){
  72617. pMem = *ppVal = sqlite3ValueNew(db);
  72618. if( pMem==0 ) return SQLITE_NOMEM_BKPT;
  72619. }
  72620. sqlite3VdbeSerialGet(&a[iField-szField], t, pMem);
  72621. pMem->enc = ENC(db);
  72622. return SQLITE_OK;
  72623. }
  72624. /*
  72625. ** Unless it is NULL, the argument must be an UnpackedRecord object returned
  72626. ** by an earlier call to sqlite3Stat4ProbeSetValue(). This call deletes
  72627. ** the object.
  72628. */
  72629. SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord *pRec){
  72630. if( pRec ){
  72631. int i;
  72632. int nCol = pRec->pKeyInfo->nAllField;
  72633. Mem *aMem = pRec->aMem;
  72634. sqlite3 *db = aMem[0].db;
  72635. for(i=0; i<nCol; i++){
  72636. sqlite3VdbeMemRelease(&aMem[i]);
  72637. }
  72638. sqlite3KeyInfoUnref(pRec->pKeyInfo);
  72639. sqlite3DbFreeNN(db, pRec);
  72640. }
  72641. }
  72642. #endif /* ifdef SQLITE_ENABLE_STAT4 */
  72643. /*
  72644. ** Change the string value of an sqlite3_value object
  72645. */
  72646. SQLITE_PRIVATE void sqlite3ValueSetStr(
  72647. sqlite3_value *v, /* Value to be set */
  72648. int n, /* Length of string z */
  72649. const void *z, /* Text of the new string */
  72650. u8 enc, /* Encoding to use */
  72651. void (*xDel)(void*) /* Destructor for the string */
  72652. ){
  72653. if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
  72654. }
  72655. /*
  72656. ** Free an sqlite3_value object
  72657. */
  72658. SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){
  72659. if( !v ) return;
  72660. sqlite3VdbeMemRelease((Mem *)v);
  72661. sqlite3DbFreeNN(((Mem*)v)->db, v);
  72662. }
  72663. /*
  72664. ** The sqlite3ValueBytes() routine returns the number of bytes in the
  72665. ** sqlite3_value object assuming that it uses the encoding "enc".
  72666. ** The valueBytes() routine is a helper function.
  72667. */
  72668. static SQLITE_NOINLINE int valueBytes(sqlite3_value *pVal, u8 enc){
  72669. return valueToText(pVal, enc)!=0 ? pVal->n : 0;
  72670. }
  72671. SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
  72672. Mem *p = (Mem*)pVal;
  72673. assert( (p->flags & MEM_Null)==0 || (p->flags & (MEM_Str|MEM_Blob))==0 );
  72674. if( (p->flags & MEM_Str)!=0 && pVal->enc==enc ){
  72675. return p->n;
  72676. }
  72677. if( (p->flags & MEM_Blob)!=0 ){
  72678. if( p->flags & MEM_Zero ){
  72679. return p->n + p->u.nZero;
  72680. }else{
  72681. return p->n;
  72682. }
  72683. }
  72684. if( p->flags & MEM_Null ) return 0;
  72685. return valueBytes(pVal, enc);
  72686. }
  72687. /************** End of vdbemem.c *********************************************/
  72688. /************** Begin file vdbeaux.c *****************************************/
  72689. /*
  72690. ** 2003 September 6
  72691. **
  72692. ** The author disclaims copyright to this source code. In place of
  72693. ** a legal notice, here is a blessing:
  72694. **
  72695. ** May you do good and not evil.
  72696. ** May you find forgiveness for yourself and forgive others.
  72697. ** May you share freely, never taking more than you give.
  72698. **
  72699. *************************************************************************
  72700. ** This file contains code used for creating, destroying, and populating
  72701. ** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.)
  72702. */
  72703. /* #include "sqliteInt.h" */
  72704. /* #include "vdbeInt.h" */
  72705. /* Forward references */
  72706. static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef);
  72707. static void vdbeFreeOpArray(sqlite3 *, Op *, int);
  72708. /*
  72709. ** Create a new virtual database engine.
  72710. */
  72711. SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(Parse *pParse){
  72712. sqlite3 *db = pParse->db;
  72713. Vdbe *p;
  72714. p = sqlite3DbMallocRawNN(db, sizeof(Vdbe) );
  72715. if( p==0 ) return 0;
  72716. memset(&p->aOp, 0, sizeof(Vdbe)-offsetof(Vdbe,aOp));
  72717. p->db = db;
  72718. if( db->pVdbe ){
  72719. db->pVdbe->pPrev = p;
  72720. }
  72721. p->pNext = db->pVdbe;
  72722. p->pPrev = 0;
  72723. db->pVdbe = p;
  72724. p->magic = VDBE_MAGIC_INIT;
  72725. p->pParse = pParse;
  72726. pParse->pVdbe = p;
  72727. assert( pParse->aLabel==0 );
  72728. assert( pParse->nLabel==0 );
  72729. assert( p->nOpAlloc==0 );
  72730. assert( pParse->szOpAlloc==0 );
  72731. sqlite3VdbeAddOp2(p, OP_Init, 0, 1);
  72732. return p;
  72733. }
  72734. /*
  72735. ** Return the Parse object that owns a Vdbe object.
  72736. */
  72737. SQLITE_PRIVATE Parse *sqlite3VdbeParser(Vdbe *p){
  72738. return p->pParse;
  72739. }
  72740. /*
  72741. ** Change the error string stored in Vdbe.zErrMsg
  72742. */
  72743. SQLITE_PRIVATE void sqlite3VdbeError(Vdbe *p, const char *zFormat, ...){
  72744. va_list ap;
  72745. sqlite3DbFree(p->db, p->zErrMsg);
  72746. va_start(ap, zFormat);
  72747. p->zErrMsg = sqlite3VMPrintf(p->db, zFormat, ap);
  72748. va_end(ap);
  72749. }
  72750. /*
  72751. ** Remember the SQL string for a prepared statement.
  72752. */
  72753. SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, u8 prepFlags){
  72754. if( p==0 ) return;
  72755. p->prepFlags = prepFlags;
  72756. if( (prepFlags & SQLITE_PREPARE_SAVESQL)==0 ){
  72757. p->expmask = 0;
  72758. }
  72759. assert( p->zSql==0 );
  72760. p->zSql = sqlite3DbStrNDup(p->db, z, n);
  72761. }
  72762. #ifdef SQLITE_ENABLE_NORMALIZE
  72763. /*
  72764. ** Add a new element to the Vdbe->pDblStr list.
  72765. */
  72766. SQLITE_PRIVATE void sqlite3VdbeAddDblquoteStr(sqlite3 *db, Vdbe *p, const char *z){
  72767. if( p ){
  72768. int n = sqlite3Strlen30(z);
  72769. DblquoteStr *pStr = sqlite3DbMallocRawNN(db,
  72770. sizeof(*pStr)+n+1-sizeof(pStr->z));
  72771. if( pStr ){
  72772. pStr->pNextStr = p->pDblStr;
  72773. p->pDblStr = pStr;
  72774. memcpy(pStr->z, z, n+1);
  72775. }
  72776. }
  72777. }
  72778. #endif
  72779. #ifdef SQLITE_ENABLE_NORMALIZE
  72780. /*
  72781. ** zId of length nId is a double-quoted identifier. Check to see if
  72782. ** that identifier is really used as a string literal.
  72783. */
  72784. SQLITE_PRIVATE int sqlite3VdbeUsesDoubleQuotedString(
  72785. Vdbe *pVdbe, /* The prepared statement */
  72786. const char *zId /* The double-quoted identifier, already dequoted */
  72787. ){
  72788. DblquoteStr *pStr;
  72789. assert( zId!=0 );
  72790. if( pVdbe->pDblStr==0 ) return 0;
  72791. for(pStr=pVdbe->pDblStr; pStr; pStr=pStr->pNextStr){
  72792. if( strcmp(zId, pStr->z)==0 ) return 1;
  72793. }
  72794. return 0;
  72795. }
  72796. #endif
  72797. /*
  72798. ** Swap all content between two VDBE structures.
  72799. */
  72800. SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
  72801. Vdbe tmp, *pTmp;
  72802. char *zTmp;
  72803. assert( pA->db==pB->db );
  72804. tmp = *pA;
  72805. *pA = *pB;
  72806. *pB = tmp;
  72807. pTmp = pA->pNext;
  72808. pA->pNext = pB->pNext;
  72809. pB->pNext = pTmp;
  72810. pTmp = pA->pPrev;
  72811. pA->pPrev = pB->pPrev;
  72812. pB->pPrev = pTmp;
  72813. zTmp = pA->zSql;
  72814. pA->zSql = pB->zSql;
  72815. pB->zSql = zTmp;
  72816. #ifdef SQLITE_ENABLE_NORMALIZE
  72817. zTmp = pA->zNormSql;
  72818. pA->zNormSql = pB->zNormSql;
  72819. pB->zNormSql = zTmp;
  72820. #endif
  72821. pB->expmask = pA->expmask;
  72822. pB->prepFlags = pA->prepFlags;
  72823. memcpy(pB->aCounter, pA->aCounter, sizeof(pB->aCounter));
  72824. pB->aCounter[SQLITE_STMTSTATUS_REPREPARE]++;
  72825. }
  72826. /*
  72827. ** Resize the Vdbe.aOp array so that it is at least nOp elements larger
  72828. ** than its current size. nOp is guaranteed to be less than or equal
  72829. ** to 1024/sizeof(Op).
  72830. **
  72831. ** If an out-of-memory error occurs while resizing the array, return
  72832. ** SQLITE_NOMEM. In this case Vdbe.aOp and Vdbe.nOpAlloc remain
  72833. ** unchanged (this is so that any opcodes already allocated can be
  72834. ** correctly deallocated along with the rest of the Vdbe).
  72835. */
  72836. static int growOpArray(Vdbe *v, int nOp){
  72837. VdbeOp *pNew;
  72838. Parse *p = v->pParse;
  72839. /* The SQLITE_TEST_REALLOC_STRESS compile-time option is designed to force
  72840. ** more frequent reallocs and hence provide more opportunities for
  72841. ** simulated OOM faults. SQLITE_TEST_REALLOC_STRESS is generally used
  72842. ** during testing only. With SQLITE_TEST_REALLOC_STRESS grow the op array
  72843. ** by the minimum* amount required until the size reaches 512. Normal
  72844. ** operation (without SQLITE_TEST_REALLOC_STRESS) is to double the current
  72845. ** size of the op array or add 1KB of space, whichever is smaller. */
  72846. #ifdef SQLITE_TEST_REALLOC_STRESS
  72847. sqlite3_int64 nNew = (v->nOpAlloc>=512 ? 2*(sqlite3_int64)v->nOpAlloc
  72848. : (sqlite3_int64)v->nOpAlloc+nOp);
  72849. #else
  72850. sqlite3_int64 nNew = (v->nOpAlloc ? 2*(sqlite3_int64)v->nOpAlloc
  72851. : (sqlite3_int64)(1024/sizeof(Op)));
  72852. UNUSED_PARAMETER(nOp);
  72853. #endif
  72854. /* Ensure that the size of a VDBE does not grow too large */
  72855. if( nNew > p->db->aLimit[SQLITE_LIMIT_VDBE_OP] ){
  72856. sqlite3OomFault(p->db);
  72857. return SQLITE_NOMEM;
  72858. }
  72859. assert( nOp<=(1024/sizeof(Op)) );
  72860. assert( nNew>=(v->nOpAlloc+nOp) );
  72861. pNew = sqlite3DbRealloc(p->db, v->aOp, nNew*sizeof(Op));
  72862. if( pNew ){
  72863. p->szOpAlloc = sqlite3DbMallocSize(p->db, pNew);
  72864. v->nOpAlloc = p->szOpAlloc/sizeof(Op);
  72865. v->aOp = pNew;
  72866. }
  72867. return (pNew ? SQLITE_OK : SQLITE_NOMEM_BKPT);
  72868. }
  72869. #ifdef SQLITE_DEBUG
  72870. /* This routine is just a convenient place to set a breakpoint that will
  72871. ** fire after each opcode is inserted and displayed using
  72872. ** "PRAGMA vdbe_addoptrace=on". Parameters "pc" (program counter) and
  72873. ** pOp are available to make the breakpoint conditional.
  72874. **
  72875. ** Other useful labels for breakpoints include:
  72876. ** test_trace_breakpoint(pc,pOp)
  72877. ** sqlite3CorruptError(lineno)
  72878. ** sqlite3MisuseError(lineno)
  72879. ** sqlite3CantopenError(lineno)
  72880. */
  72881. static void test_addop_breakpoint(int pc, Op *pOp){
  72882. static int n = 0;
  72883. n++;
  72884. }
  72885. #endif
  72886. /*
  72887. ** Add a new instruction to the list of instructions current in the
  72888. ** VDBE. Return the address of the new instruction.
  72889. **
  72890. ** Parameters:
  72891. **
  72892. ** p Pointer to the VDBE
  72893. **
  72894. ** op The opcode for this instruction
  72895. **
  72896. ** p1, p2, p3 Operands
  72897. **
  72898. ** Use the sqlite3VdbeResolveLabel() function to fix an address and
  72899. ** the sqlite3VdbeChangeP4() function to change the value of the P4
  72900. ** operand.
  72901. */
  72902. static SQLITE_NOINLINE int growOp3(Vdbe *p, int op, int p1, int p2, int p3){
  72903. assert( p->nOpAlloc<=p->nOp );
  72904. if( growOpArray(p, 1) ) return 1;
  72905. assert( p->nOpAlloc>p->nOp );
  72906. return sqlite3VdbeAddOp3(p, op, p1, p2, p3);
  72907. }
  72908. SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
  72909. int i;
  72910. VdbeOp *pOp;
  72911. i = p->nOp;
  72912. assert( p->magic==VDBE_MAGIC_INIT );
  72913. assert( op>=0 && op<0xff );
  72914. if( p->nOpAlloc<=i ){
  72915. return growOp3(p, op, p1, p2, p3);
  72916. }
  72917. p->nOp++;
  72918. pOp = &p->aOp[i];
  72919. pOp->opcode = (u8)op;
  72920. pOp->p5 = 0;
  72921. pOp->p1 = p1;
  72922. pOp->p2 = p2;
  72923. pOp->p3 = p3;
  72924. pOp->p4.p = 0;
  72925. pOp->p4type = P4_NOTUSED;
  72926. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  72927. pOp->zComment = 0;
  72928. #endif
  72929. #ifdef SQLITE_DEBUG
  72930. if( p->db->flags & SQLITE_VdbeAddopTrace ){
  72931. sqlite3VdbePrintOp(0, i, &p->aOp[i]);
  72932. test_addop_breakpoint(i, &p->aOp[i]);
  72933. }
  72934. #endif
  72935. #ifdef VDBE_PROFILE
  72936. pOp->cycles = 0;
  72937. pOp->cnt = 0;
  72938. #endif
  72939. #ifdef SQLITE_VDBE_COVERAGE
  72940. pOp->iSrcLine = 0;
  72941. #endif
  72942. return i;
  72943. }
  72944. SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){
  72945. return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
  72946. }
  72947. SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
  72948. return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
  72949. }
  72950. SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
  72951. return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
  72952. }
  72953. /* Generate code for an unconditional jump to instruction iDest
  72954. */
  72955. SQLITE_PRIVATE int sqlite3VdbeGoto(Vdbe *p, int iDest){
  72956. return sqlite3VdbeAddOp3(p, OP_Goto, 0, iDest, 0);
  72957. }
  72958. /* Generate code to cause the string zStr to be loaded into
  72959. ** register iDest
  72960. */
  72961. SQLITE_PRIVATE int sqlite3VdbeLoadString(Vdbe *p, int iDest, const char *zStr){
  72962. return sqlite3VdbeAddOp4(p, OP_String8, 0, iDest, 0, zStr, 0);
  72963. }
  72964. /*
  72965. ** Generate code that initializes multiple registers to string or integer
  72966. ** constants. The registers begin with iDest and increase consecutively.
  72967. ** One register is initialized for each characgter in zTypes[]. For each
  72968. ** "s" character in zTypes[], the register is a string if the argument is
  72969. ** not NULL, or OP_Null if the value is a null pointer. For each "i" character
  72970. ** in zTypes[], the register is initialized to an integer.
  72971. **
  72972. ** If the input string does not end with "X" then an OP_ResultRow instruction
  72973. ** is generated for the values inserted.
  72974. */
  72975. SQLITE_PRIVATE void sqlite3VdbeMultiLoad(Vdbe *p, int iDest, const char *zTypes, ...){
  72976. va_list ap;
  72977. int i;
  72978. char c;
  72979. va_start(ap, zTypes);
  72980. for(i=0; (c = zTypes[i])!=0; i++){
  72981. if( c=='s' ){
  72982. const char *z = va_arg(ap, const char*);
  72983. sqlite3VdbeAddOp4(p, z==0 ? OP_Null : OP_String8, 0, iDest+i, 0, z, 0);
  72984. }else if( c=='i' ){
  72985. sqlite3VdbeAddOp2(p, OP_Integer, va_arg(ap, int), iDest+i);
  72986. }else{
  72987. goto skip_op_resultrow;
  72988. }
  72989. }
  72990. sqlite3VdbeAddOp2(p, OP_ResultRow, iDest, i);
  72991. skip_op_resultrow:
  72992. va_end(ap);
  72993. }
  72994. /*
  72995. ** Add an opcode that includes the p4 value as a pointer.
  72996. */
  72997. SQLITE_PRIVATE int sqlite3VdbeAddOp4(
  72998. Vdbe *p, /* Add the opcode to this VM */
  72999. int op, /* The new opcode */
  73000. int p1, /* The P1 operand */
  73001. int p2, /* The P2 operand */
  73002. int p3, /* The P3 operand */
  73003. const char *zP4, /* The P4 operand */
  73004. int p4type /* P4 operand type */
  73005. ){
  73006. int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
  73007. sqlite3VdbeChangeP4(p, addr, zP4, p4type);
  73008. return addr;
  73009. }
  73010. /*
  73011. ** Add an OP_Function or OP_PureFunc opcode.
  73012. **
  73013. ** The eCallCtx argument is information (typically taken from Expr.op2)
  73014. ** that describes the calling context of the function. 0 means a general
  73015. ** function call. NC_IsCheck means called by a check constraint,
  73016. ** NC_IdxExpr means called as part of an index expression. NC_PartIdx
  73017. ** means in the WHERE clause of a partial index. NC_GenCol means called
  73018. ** while computing a generated column value. 0 is the usual case.
  73019. */
  73020. SQLITE_PRIVATE int sqlite3VdbeAddFunctionCall(
  73021. Parse *pParse, /* Parsing context */
  73022. int p1, /* Constant argument mask */
  73023. int p2, /* First argument register */
  73024. int p3, /* Register into which results are written */
  73025. int nArg, /* Number of argument */
  73026. const FuncDef *pFunc, /* The function to be invoked */
  73027. int eCallCtx /* Calling context */
  73028. ){
  73029. Vdbe *v = pParse->pVdbe;
  73030. int nByte;
  73031. int addr;
  73032. sqlite3_context *pCtx;
  73033. assert( v );
  73034. nByte = sizeof(*pCtx) + (nArg-1)*sizeof(sqlite3_value*);
  73035. pCtx = sqlite3DbMallocRawNN(pParse->db, nByte);
  73036. if( pCtx==0 ){
  73037. assert( pParse->db->mallocFailed );
  73038. freeEphemeralFunction(pParse->db, (FuncDef*)pFunc);
  73039. return 0;
  73040. }
  73041. pCtx->pOut = 0;
  73042. pCtx->pFunc = (FuncDef*)pFunc;
  73043. pCtx->pVdbe = 0;
  73044. pCtx->isError = 0;
  73045. pCtx->argc = nArg;
  73046. pCtx->iOp = sqlite3VdbeCurrentAddr(v);
  73047. addr = sqlite3VdbeAddOp4(v, eCallCtx ? OP_PureFunc : OP_Function,
  73048. p1, p2, p3, (char*)pCtx, P4_FUNCCTX);
  73049. sqlite3VdbeChangeP5(v, eCallCtx & NC_SelfRef);
  73050. return addr;
  73051. }
  73052. /*
  73053. ** Add an opcode that includes the p4 value with a P4_INT64 or
  73054. ** P4_REAL type.
  73055. */
  73056. SQLITE_PRIVATE int sqlite3VdbeAddOp4Dup8(
  73057. Vdbe *p, /* Add the opcode to this VM */
  73058. int op, /* The new opcode */
  73059. int p1, /* The P1 operand */
  73060. int p2, /* The P2 operand */
  73061. int p3, /* The P3 operand */
  73062. const u8 *zP4, /* The P4 operand */
  73063. int p4type /* P4 operand type */
  73064. ){
  73065. char *p4copy = sqlite3DbMallocRawNN(sqlite3VdbeDb(p), 8);
  73066. if( p4copy ) memcpy(p4copy, zP4, 8);
  73067. return sqlite3VdbeAddOp4(p, op, p1, p2, p3, p4copy, p4type);
  73068. }
  73069. #ifndef SQLITE_OMIT_EXPLAIN
  73070. /*
  73071. ** Return the address of the current EXPLAIN QUERY PLAN baseline.
  73072. ** 0 means "none".
  73073. */
  73074. SQLITE_PRIVATE int sqlite3VdbeExplainParent(Parse *pParse){
  73075. VdbeOp *pOp;
  73076. if( pParse->addrExplain==0 ) return 0;
  73077. pOp = sqlite3VdbeGetOp(pParse->pVdbe, pParse->addrExplain);
  73078. return pOp->p2;
  73079. }
  73080. /*
  73081. ** Set a debugger breakpoint on the following routine in order to
  73082. ** monitor the EXPLAIN QUERY PLAN code generation.
  73083. */
  73084. #if defined(SQLITE_DEBUG)
  73085. SQLITE_PRIVATE void sqlite3ExplainBreakpoint(const char *z1, const char *z2){
  73086. (void)z1;
  73087. (void)z2;
  73088. }
  73089. #endif
  73090. /*
  73091. ** Add a new OP_Explain opcode.
  73092. **
  73093. ** If the bPush flag is true, then make this opcode the parent for
  73094. ** subsequent Explains until sqlite3VdbeExplainPop() is called.
  73095. */
  73096. SQLITE_PRIVATE void sqlite3VdbeExplain(Parse *pParse, u8 bPush, const char *zFmt, ...){
  73097. #ifndef SQLITE_DEBUG
  73098. /* Always include the OP_Explain opcodes if SQLITE_DEBUG is defined.
  73099. ** But omit them (for performance) during production builds */
  73100. if( pParse->explain==2 )
  73101. #endif
  73102. {
  73103. char *zMsg;
  73104. Vdbe *v;
  73105. va_list ap;
  73106. int iThis;
  73107. va_start(ap, zFmt);
  73108. zMsg = sqlite3VMPrintf(pParse->db, zFmt, ap);
  73109. va_end(ap);
  73110. v = pParse->pVdbe;
  73111. iThis = v->nOp;
  73112. sqlite3VdbeAddOp4(v, OP_Explain, iThis, pParse->addrExplain, 0,
  73113. zMsg, P4_DYNAMIC);
  73114. sqlite3ExplainBreakpoint(bPush?"PUSH":"", sqlite3VdbeGetOp(v,-1)->p4.z);
  73115. if( bPush){
  73116. pParse->addrExplain = iThis;
  73117. }
  73118. }
  73119. }
  73120. /*
  73121. ** Pop the EXPLAIN QUERY PLAN stack one level.
  73122. */
  73123. SQLITE_PRIVATE void sqlite3VdbeExplainPop(Parse *pParse){
  73124. sqlite3ExplainBreakpoint("POP", 0);
  73125. pParse->addrExplain = sqlite3VdbeExplainParent(pParse);
  73126. }
  73127. #endif /* SQLITE_OMIT_EXPLAIN */
  73128. /*
  73129. ** Add an OP_ParseSchema opcode. This routine is broken out from
  73130. ** sqlite3VdbeAddOp4() since it needs to also needs to mark all btrees
  73131. ** as having been used.
  73132. **
  73133. ** The zWhere string must have been obtained from sqlite3_malloc().
  73134. ** This routine will take ownership of the allocated memory.
  73135. */
  73136. SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe *p, int iDb, char *zWhere){
  73137. int j;
  73138. sqlite3VdbeAddOp4(p, OP_ParseSchema, iDb, 0, 0, zWhere, P4_DYNAMIC);
  73139. for(j=0; j<p->db->nDb; j++) sqlite3VdbeUsesBtree(p, j);
  73140. }
  73141. /*
  73142. ** Add an opcode that includes the p4 value as an integer.
  73143. */
  73144. SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(
  73145. Vdbe *p, /* Add the opcode to this VM */
  73146. int op, /* The new opcode */
  73147. int p1, /* The P1 operand */
  73148. int p2, /* The P2 operand */
  73149. int p3, /* The P3 operand */
  73150. int p4 /* The P4 operand as an integer */
  73151. ){
  73152. int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
  73153. if( p->db->mallocFailed==0 ){
  73154. VdbeOp *pOp = &p->aOp[addr];
  73155. pOp->p4type = P4_INT32;
  73156. pOp->p4.i = p4;
  73157. }
  73158. return addr;
  73159. }
  73160. /* Insert the end of a co-routine
  73161. */
  73162. SQLITE_PRIVATE void sqlite3VdbeEndCoroutine(Vdbe *v, int regYield){
  73163. sqlite3VdbeAddOp1(v, OP_EndCoroutine, regYield);
  73164. /* Clear the temporary register cache, thereby ensuring that each
  73165. ** co-routine has its own independent set of registers, because co-routines
  73166. ** might expect their registers to be preserved across an OP_Yield, and
  73167. ** that could cause problems if two or more co-routines are using the same
  73168. ** temporary register.
  73169. */
  73170. v->pParse->nTempReg = 0;
  73171. v->pParse->nRangeReg = 0;
  73172. }
  73173. /*
  73174. ** Create a new symbolic label for an instruction that has yet to be
  73175. ** coded. The symbolic label is really just a negative number. The
  73176. ** label can be used as the P2 value of an operation. Later, when
  73177. ** the label is resolved to a specific address, the VDBE will scan
  73178. ** through its operation list and change all values of P2 which match
  73179. ** the label into the resolved address.
  73180. **
  73181. ** The VDBE knows that a P2 value is a label because labels are
  73182. ** always negative and P2 values are suppose to be non-negative.
  73183. ** Hence, a negative P2 value is a label that has yet to be resolved.
  73184. ** (Later:) This is only true for opcodes that have the OPFLG_JUMP
  73185. ** property.
  73186. **
  73187. ** Variable usage notes:
  73188. **
  73189. ** Parse.aLabel[x] Stores the address that the x-th label resolves
  73190. ** into. For testing (SQLITE_DEBUG), unresolved
  73191. ** labels stores -1, but that is not required.
  73192. ** Parse.nLabelAlloc Number of slots allocated to Parse.aLabel[]
  73193. ** Parse.nLabel The *negative* of the number of labels that have
  73194. ** been issued. The negative is stored because
  73195. ** that gives a performance improvement over storing
  73196. ** the equivalent positive value.
  73197. */
  73198. SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Parse *pParse){
  73199. return --pParse->nLabel;
  73200. }
  73201. /*
  73202. ** Resolve label "x" to be the address of the next instruction to
  73203. ** be inserted. The parameter "x" must have been obtained from
  73204. ** a prior call to sqlite3VdbeMakeLabel().
  73205. */
  73206. static SQLITE_NOINLINE void resizeResolveLabel(Parse *p, Vdbe *v, int j){
  73207. int nNewSize = 10 - p->nLabel;
  73208. p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
  73209. nNewSize*sizeof(p->aLabel[0]));
  73210. if( p->aLabel==0 ){
  73211. p->nLabelAlloc = 0;
  73212. }else{
  73213. #ifdef SQLITE_DEBUG
  73214. int i;
  73215. for(i=p->nLabelAlloc; i<nNewSize; i++) p->aLabel[i] = -1;
  73216. #endif
  73217. p->nLabelAlloc = nNewSize;
  73218. p->aLabel[j] = v->nOp;
  73219. }
  73220. }
  73221. SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *v, int x){
  73222. Parse *p = v->pParse;
  73223. int j = ADDR(x);
  73224. assert( v->magic==VDBE_MAGIC_INIT );
  73225. assert( j<-p->nLabel );
  73226. assert( j>=0 );
  73227. #ifdef SQLITE_DEBUG
  73228. if( p->db->flags & SQLITE_VdbeAddopTrace ){
  73229. printf("RESOLVE LABEL %d to %d\n", x, v->nOp);
  73230. }
  73231. #endif
  73232. if( p->nLabelAlloc + p->nLabel < 0 ){
  73233. resizeResolveLabel(p,v,j);
  73234. }else{
  73235. assert( p->aLabel[j]==(-1) ); /* Labels may only be resolved once */
  73236. p->aLabel[j] = v->nOp;
  73237. }
  73238. }
  73239. /*
  73240. ** Mark the VDBE as one that can only be run one time.
  73241. */
  73242. SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe *p){
  73243. p->runOnlyOnce = 1;
  73244. }
  73245. /*
  73246. ** Mark the VDBE as one that can only be run multiple times.
  73247. */
  73248. SQLITE_PRIVATE void sqlite3VdbeReusable(Vdbe *p){
  73249. p->runOnlyOnce = 0;
  73250. }
  73251. #ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
  73252. /*
  73253. ** The following type and function are used to iterate through all opcodes
  73254. ** in a Vdbe main program and each of the sub-programs (triggers) it may
  73255. ** invoke directly or indirectly. It should be used as follows:
  73256. **
  73257. ** Op *pOp;
  73258. ** VdbeOpIter sIter;
  73259. **
  73260. ** memset(&sIter, 0, sizeof(sIter));
  73261. ** sIter.v = v; // v is of type Vdbe*
  73262. ** while( (pOp = opIterNext(&sIter)) ){
  73263. ** // Do something with pOp
  73264. ** }
  73265. ** sqlite3DbFree(v->db, sIter.apSub);
  73266. **
  73267. */
  73268. typedef struct VdbeOpIter VdbeOpIter;
  73269. struct VdbeOpIter {
  73270. Vdbe *v; /* Vdbe to iterate through the opcodes of */
  73271. SubProgram **apSub; /* Array of subprograms */
  73272. int nSub; /* Number of entries in apSub */
  73273. int iAddr; /* Address of next instruction to return */
  73274. int iSub; /* 0 = main program, 1 = first sub-program etc. */
  73275. };
  73276. static Op *opIterNext(VdbeOpIter *p){
  73277. Vdbe *v = p->v;
  73278. Op *pRet = 0;
  73279. Op *aOp;
  73280. int nOp;
  73281. if( p->iSub<=p->nSub ){
  73282. if( p->iSub==0 ){
  73283. aOp = v->aOp;
  73284. nOp = v->nOp;
  73285. }else{
  73286. aOp = p->apSub[p->iSub-1]->aOp;
  73287. nOp = p->apSub[p->iSub-1]->nOp;
  73288. }
  73289. assert( p->iAddr<nOp );
  73290. pRet = &aOp[p->iAddr];
  73291. p->iAddr++;
  73292. if( p->iAddr==nOp ){
  73293. p->iSub++;
  73294. p->iAddr = 0;
  73295. }
  73296. if( pRet->p4type==P4_SUBPROGRAM ){
  73297. int nByte = (p->nSub+1)*sizeof(SubProgram*);
  73298. int j;
  73299. for(j=0; j<p->nSub; j++){
  73300. if( p->apSub[j]==pRet->p4.pProgram ) break;
  73301. }
  73302. if( j==p->nSub ){
  73303. p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
  73304. if( !p->apSub ){
  73305. pRet = 0;
  73306. }else{
  73307. p->apSub[p->nSub++] = pRet->p4.pProgram;
  73308. }
  73309. }
  73310. }
  73311. }
  73312. return pRet;
  73313. }
  73314. /*
  73315. ** Check if the program stored in the VM associated with pParse may
  73316. ** throw an ABORT exception (causing the statement, but not entire transaction
  73317. ** to be rolled back). This condition is true if the main program or any
  73318. ** sub-programs contains any of the following:
  73319. **
  73320. ** * OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
  73321. ** * OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
  73322. ** * OP_Destroy
  73323. ** * OP_VUpdate
  73324. ** * OP_VCreate
  73325. ** * OP_VRename
  73326. ** * OP_FkCounter with P2==0 (immediate foreign key constraint)
  73327. ** * OP_CreateBtree/BTREE_INTKEY and OP_InitCoroutine
  73328. ** (for CREATE TABLE AS SELECT ...)
  73329. **
  73330. ** Then check that the value of Parse.mayAbort is true if an
  73331. ** ABORT may be thrown, or false otherwise. Return true if it does
  73332. ** match, or false otherwise. This function is intended to be used as
  73333. ** part of an assert statement in the compiler. Similar to:
  73334. **
  73335. ** assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
  73336. */
  73337. SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
  73338. int hasAbort = 0;
  73339. int hasFkCounter = 0;
  73340. int hasCreateTable = 0;
  73341. int hasCreateIndex = 0;
  73342. int hasInitCoroutine = 0;
  73343. Op *pOp;
  73344. VdbeOpIter sIter;
  73345. memset(&sIter, 0, sizeof(sIter));
  73346. sIter.v = v;
  73347. while( (pOp = opIterNext(&sIter))!=0 ){
  73348. int opcode = pOp->opcode;
  73349. if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename
  73350. || opcode==OP_VDestroy
  73351. || opcode==OP_VCreate
  73352. || (opcode==OP_ParseSchema && pOp->p4.z==0)
  73353. || ((opcode==OP_Halt || opcode==OP_HaltIfNull)
  73354. && ((pOp->p1)!=SQLITE_OK && pOp->p2==OE_Abort))
  73355. ){
  73356. hasAbort = 1;
  73357. break;
  73358. }
  73359. if( opcode==OP_CreateBtree && pOp->p3==BTREE_INTKEY ) hasCreateTable = 1;
  73360. if( mayAbort ){
  73361. /* hasCreateIndex may also be set for some DELETE statements that use
  73362. ** OP_Clear. So this routine may end up returning true in the case
  73363. ** where a "DELETE FROM tbl" has a statement-journal but does not
  73364. ** require one. This is not so bad - it is an inefficiency, not a bug. */
  73365. if( opcode==OP_CreateBtree && pOp->p3==BTREE_BLOBKEY ) hasCreateIndex = 1;
  73366. if( opcode==OP_Clear ) hasCreateIndex = 1;
  73367. }
  73368. if( opcode==OP_InitCoroutine ) hasInitCoroutine = 1;
  73369. #ifndef SQLITE_OMIT_FOREIGN_KEY
  73370. if( opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1 ){
  73371. hasFkCounter = 1;
  73372. }
  73373. #endif
  73374. }
  73375. sqlite3DbFree(v->db, sIter.apSub);
  73376. /* Return true if hasAbort==mayAbort. Or if a malloc failure occurred.
  73377. ** If malloc failed, then the while() loop above may not have iterated
  73378. ** through all opcodes and hasAbort may be set incorrectly. Return
  73379. ** true for this case to prevent the assert() in the callers frame
  73380. ** from failing. */
  73381. return ( v->db->mallocFailed || hasAbort==mayAbort || hasFkCounter
  73382. || (hasCreateTable && hasInitCoroutine) || hasCreateIndex
  73383. );
  73384. }
  73385. #endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
  73386. #ifdef SQLITE_DEBUG
  73387. /*
  73388. ** Increment the nWrite counter in the VDBE if the cursor is not an
  73389. ** ephemeral cursor, or if the cursor argument is NULL.
  73390. */
  73391. SQLITE_PRIVATE void sqlite3VdbeIncrWriteCounter(Vdbe *p, VdbeCursor *pC){
  73392. if( pC==0
  73393. || (pC->eCurType!=CURTYPE_SORTER
  73394. && pC->eCurType!=CURTYPE_PSEUDO
  73395. && !pC->isEphemeral)
  73396. ){
  73397. p->nWrite++;
  73398. }
  73399. }
  73400. #endif
  73401. #ifdef SQLITE_DEBUG
  73402. /*
  73403. ** Assert if an Abort at this point in time might result in a corrupt
  73404. ** database.
  73405. */
  73406. SQLITE_PRIVATE void sqlite3VdbeAssertAbortable(Vdbe *p){
  73407. assert( p->nWrite==0 || p->usesStmtJournal );
  73408. }
  73409. #endif
  73410. /*
  73411. ** This routine is called after all opcodes have been inserted. It loops
  73412. ** through all the opcodes and fixes up some details.
  73413. **
  73414. ** (1) For each jump instruction with a negative P2 value (a label)
  73415. ** resolve the P2 value to an actual address.
  73416. **
  73417. ** (2) Compute the maximum number of arguments used by any SQL function
  73418. ** and store that value in *pMaxFuncArgs.
  73419. **
  73420. ** (3) Update the Vdbe.readOnly and Vdbe.bIsReader flags to accurately
  73421. ** indicate what the prepared statement actually does.
  73422. **
  73423. ** (4) Initialize the p4.xAdvance pointer on opcodes that use it.
  73424. **
  73425. ** (5) Reclaim the memory allocated for storing labels.
  73426. **
  73427. ** This routine will only function correctly if the mkopcodeh.tcl generator
  73428. ** script numbers the opcodes correctly. Changes to this routine must be
  73429. ** coordinated with changes to mkopcodeh.tcl.
  73430. */
  73431. static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
  73432. int nMaxArgs = *pMaxFuncArgs;
  73433. Op *pOp;
  73434. Parse *pParse = p->pParse;
  73435. int *aLabel = pParse->aLabel;
  73436. p->readOnly = 1;
  73437. p->bIsReader = 0;
  73438. pOp = &p->aOp[p->nOp-1];
  73439. while(1){
  73440. /* Only JUMP opcodes and the short list of special opcodes in the switch
  73441. ** below need to be considered. The mkopcodeh.tcl generator script groups
  73442. ** all these opcodes together near the front of the opcode list. Skip
  73443. ** any opcode that does not need processing by virtual of the fact that
  73444. ** it is larger than SQLITE_MX_JUMP_OPCODE, as a performance optimization.
  73445. */
  73446. if( pOp->opcode<=SQLITE_MX_JUMP_OPCODE ){
  73447. /* NOTE: Be sure to update mkopcodeh.tcl when adding or removing
  73448. ** cases from this switch! */
  73449. switch( pOp->opcode ){
  73450. case OP_Transaction: {
  73451. if( pOp->p2!=0 ) p->readOnly = 0;
  73452. /* fall thru */
  73453. }
  73454. case OP_AutoCommit:
  73455. case OP_Savepoint: {
  73456. p->bIsReader = 1;
  73457. break;
  73458. }
  73459. #ifndef SQLITE_OMIT_WAL
  73460. case OP_Checkpoint:
  73461. #endif
  73462. case OP_Vacuum:
  73463. case OP_JournalMode: {
  73464. p->readOnly = 0;
  73465. p->bIsReader = 1;
  73466. break;
  73467. }
  73468. case OP_Next:
  73469. case OP_SorterNext: {
  73470. pOp->p4.xAdvance = sqlite3BtreeNext;
  73471. pOp->p4type = P4_ADVANCE;
  73472. /* The code generator never codes any of these opcodes as a jump
  73473. ** to a label. They are always coded as a jump backwards to a
  73474. ** known address */
  73475. assert( pOp->p2>=0 );
  73476. break;
  73477. }
  73478. case OP_Prev: {
  73479. pOp->p4.xAdvance = sqlite3BtreePrevious;
  73480. pOp->p4type = P4_ADVANCE;
  73481. /* The code generator never codes any of these opcodes as a jump
  73482. ** to a label. They are always coded as a jump backwards to a
  73483. ** known address */
  73484. assert( pOp->p2>=0 );
  73485. break;
  73486. }
  73487. #ifndef SQLITE_OMIT_VIRTUALTABLE
  73488. case OP_VUpdate: {
  73489. if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
  73490. break;
  73491. }
  73492. case OP_VFilter: {
  73493. int n;
  73494. assert( (pOp - p->aOp) >= 3 );
  73495. assert( pOp[-1].opcode==OP_Integer );
  73496. n = pOp[-1].p1;
  73497. if( n>nMaxArgs ) nMaxArgs = n;
  73498. /* Fall through into the default case */
  73499. }
  73500. #endif
  73501. default: {
  73502. if( pOp->p2<0 ){
  73503. /* The mkopcodeh.tcl script has so arranged things that the only
  73504. ** non-jump opcodes less than SQLITE_MX_JUMP_CODE are guaranteed to
  73505. ** have non-negative values for P2. */
  73506. assert( (sqlite3OpcodeProperty[pOp->opcode] & OPFLG_JUMP)!=0 );
  73507. assert( ADDR(pOp->p2)<-pParse->nLabel );
  73508. pOp->p2 = aLabel[ADDR(pOp->p2)];
  73509. }
  73510. break;
  73511. }
  73512. }
  73513. /* The mkopcodeh.tcl script has so arranged things that the only
  73514. ** non-jump opcodes less than SQLITE_MX_JUMP_CODE are guaranteed to
  73515. ** have non-negative values for P2. */
  73516. assert( (sqlite3OpcodeProperty[pOp->opcode]&OPFLG_JUMP)==0 || pOp->p2>=0);
  73517. }
  73518. if( pOp==p->aOp ) break;
  73519. pOp--;
  73520. }
  73521. sqlite3DbFree(p->db, pParse->aLabel);
  73522. pParse->aLabel = 0;
  73523. pParse->nLabel = 0;
  73524. *pMaxFuncArgs = nMaxArgs;
  73525. assert( p->bIsReader!=0 || DbMaskAllZero(p->btreeMask) );
  73526. }
  73527. /*
  73528. ** Return the address of the next instruction to be inserted.
  73529. */
  73530. SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){
  73531. assert( p->magic==VDBE_MAGIC_INIT );
  73532. return p->nOp;
  73533. }
  73534. /*
  73535. ** Verify that at least N opcode slots are available in p without
  73536. ** having to malloc for more space (except when compiled using
  73537. ** SQLITE_TEST_REALLOC_STRESS). This interface is used during testing
  73538. ** to verify that certain calls to sqlite3VdbeAddOpList() can never
  73539. ** fail due to a OOM fault and hence that the return value from
  73540. ** sqlite3VdbeAddOpList() will always be non-NULL.
  73541. */
  73542. #if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS)
  73543. SQLITE_PRIVATE void sqlite3VdbeVerifyNoMallocRequired(Vdbe *p, int N){
  73544. assert( p->nOp + N <= p->nOpAlloc );
  73545. }
  73546. #endif
  73547. /*
  73548. ** Verify that the VM passed as the only argument does not contain
  73549. ** an OP_ResultRow opcode. Fail an assert() if it does. This is used
  73550. ** by code in pragma.c to ensure that the implementation of certain
  73551. ** pragmas comports with the flags specified in the mkpragmatab.tcl
  73552. ** script.
  73553. */
  73554. #if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS)
  73555. SQLITE_PRIVATE void sqlite3VdbeVerifyNoResultRow(Vdbe *p){
  73556. int i;
  73557. for(i=0; i<p->nOp; i++){
  73558. assert( p->aOp[i].opcode!=OP_ResultRow );
  73559. }
  73560. }
  73561. #endif
  73562. /*
  73563. ** Generate code (a single OP_Abortable opcode) that will
  73564. ** verify that the VDBE program can safely call Abort in the current
  73565. ** context.
  73566. */
  73567. #if defined(SQLITE_DEBUG)
  73568. SQLITE_PRIVATE void sqlite3VdbeVerifyAbortable(Vdbe *p, int onError){
  73569. if( onError==OE_Abort ) sqlite3VdbeAddOp0(p, OP_Abortable);
  73570. }
  73571. #endif
  73572. /*
  73573. ** This function returns a pointer to the array of opcodes associated with
  73574. ** the Vdbe passed as the first argument. It is the callers responsibility
  73575. ** to arrange for the returned array to be eventually freed using the
  73576. ** vdbeFreeOpArray() function.
  73577. **
  73578. ** Before returning, *pnOp is set to the number of entries in the returned
  73579. ** array. Also, *pnMaxArg is set to the larger of its current value and
  73580. ** the number of entries in the Vdbe.apArg[] array required to execute the
  73581. ** returned program.
  73582. */
  73583. SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
  73584. VdbeOp *aOp = p->aOp;
  73585. assert( aOp && !p->db->mallocFailed );
  73586. /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
  73587. assert( DbMaskAllZero(p->btreeMask) );
  73588. resolveP2Values(p, pnMaxArg);
  73589. *pnOp = p->nOp;
  73590. p->aOp = 0;
  73591. return aOp;
  73592. }
  73593. /*
  73594. ** Add a whole list of operations to the operation stack. Return a
  73595. ** pointer to the first operation inserted.
  73596. **
  73597. ** Non-zero P2 arguments to jump instructions are automatically adjusted
  73598. ** so that the jump target is relative to the first operation inserted.
  73599. */
  73600. SQLITE_PRIVATE VdbeOp *sqlite3VdbeAddOpList(
  73601. Vdbe *p, /* Add opcodes to the prepared statement */
  73602. int nOp, /* Number of opcodes to add */
  73603. VdbeOpList const *aOp, /* The opcodes to be added */
  73604. int iLineno /* Source-file line number of first opcode */
  73605. ){
  73606. int i;
  73607. VdbeOp *pOut, *pFirst;
  73608. assert( nOp>0 );
  73609. assert( p->magic==VDBE_MAGIC_INIT );
  73610. if( p->nOp + nOp > p->nOpAlloc && growOpArray(p, nOp) ){
  73611. return 0;
  73612. }
  73613. pFirst = pOut = &p->aOp[p->nOp];
  73614. for(i=0; i<nOp; i++, aOp++, pOut++){
  73615. pOut->opcode = aOp->opcode;
  73616. pOut->p1 = aOp->p1;
  73617. pOut->p2 = aOp->p2;
  73618. assert( aOp->p2>=0 );
  73619. if( (sqlite3OpcodeProperty[aOp->opcode] & OPFLG_JUMP)!=0 && aOp->p2>0 ){
  73620. pOut->p2 += p->nOp;
  73621. }
  73622. pOut->p3 = aOp->p3;
  73623. pOut->p4type = P4_NOTUSED;
  73624. pOut->p4.p = 0;
  73625. pOut->p5 = 0;
  73626. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  73627. pOut->zComment = 0;
  73628. #endif
  73629. #ifdef SQLITE_VDBE_COVERAGE
  73630. pOut->iSrcLine = iLineno+i;
  73631. #else
  73632. (void)iLineno;
  73633. #endif
  73634. #ifdef SQLITE_DEBUG
  73635. if( p->db->flags & SQLITE_VdbeAddopTrace ){
  73636. sqlite3VdbePrintOp(0, i+p->nOp, &p->aOp[i+p->nOp]);
  73637. }
  73638. #endif
  73639. }
  73640. p->nOp += nOp;
  73641. return pFirst;
  73642. }
  73643. #if defined(SQLITE_ENABLE_STMT_SCANSTATUS)
  73644. /*
  73645. ** Add an entry to the array of counters managed by sqlite3_stmt_scanstatus().
  73646. */
  73647. SQLITE_PRIVATE void sqlite3VdbeScanStatus(
  73648. Vdbe *p, /* VM to add scanstatus() to */
  73649. int addrExplain, /* Address of OP_Explain (or 0) */
  73650. int addrLoop, /* Address of loop counter */
  73651. int addrVisit, /* Address of rows visited counter */
  73652. LogEst nEst, /* Estimated number of output rows */
  73653. const char *zName /* Name of table or index being scanned */
  73654. ){
  73655. sqlite3_int64 nByte = (p->nScan+1) * sizeof(ScanStatus);
  73656. ScanStatus *aNew;
  73657. aNew = (ScanStatus*)sqlite3DbRealloc(p->db, p->aScan, nByte);
  73658. if( aNew ){
  73659. ScanStatus *pNew = &aNew[p->nScan++];
  73660. pNew->addrExplain = addrExplain;
  73661. pNew->addrLoop = addrLoop;
  73662. pNew->addrVisit = addrVisit;
  73663. pNew->nEst = nEst;
  73664. pNew->zName = sqlite3DbStrDup(p->db, zName);
  73665. p->aScan = aNew;
  73666. }
  73667. }
  73668. #endif
  73669. /*
  73670. ** Change the value of the opcode, or P1, P2, P3, or P5 operands
  73671. ** for a specific instruction.
  73672. */
  73673. SQLITE_PRIVATE void sqlite3VdbeChangeOpcode(Vdbe *p, int addr, u8 iNewOpcode){
  73674. sqlite3VdbeGetOp(p,addr)->opcode = iNewOpcode;
  73675. }
  73676. SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, int addr, int val){
  73677. sqlite3VdbeGetOp(p,addr)->p1 = val;
  73678. }
  73679. SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, int addr, int val){
  73680. sqlite3VdbeGetOp(p,addr)->p2 = val;
  73681. }
  73682. SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, int addr, int val){
  73683. sqlite3VdbeGetOp(p,addr)->p3 = val;
  73684. }
  73685. SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u16 p5){
  73686. assert( p->nOp>0 || p->db->mallocFailed );
  73687. if( p->nOp>0 ) p->aOp[p->nOp-1].p5 = p5;
  73688. }
  73689. /*
  73690. ** Change the P2 operand of instruction addr so that it points to
  73691. ** the address of the next instruction to be coded.
  73692. */
  73693. SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){
  73694. sqlite3VdbeChangeP2(p, addr, p->nOp);
  73695. }
  73696. /*
  73697. ** Change the P2 operand of the jump instruction at addr so that
  73698. ** the jump lands on the next opcode. Or if the jump instruction was
  73699. ** the previous opcode (and is thus a no-op) then simply back up
  73700. ** the next instruction counter by one slot so that the jump is
  73701. ** overwritten by the next inserted opcode.
  73702. **
  73703. ** This routine is an optimization of sqlite3VdbeJumpHere() that
  73704. ** strives to omit useless byte-code like this:
  73705. **
  73706. ** 7 Once 0 8 0
  73707. ** 8 ...
  73708. */
  73709. SQLITE_PRIVATE void sqlite3VdbeJumpHereOrPopInst(Vdbe *p, int addr){
  73710. if( addr==p->nOp-1 ){
  73711. assert( p->aOp[addr].opcode==OP_Once
  73712. || p->aOp[addr].opcode==OP_If
  73713. || p->aOp[addr].opcode==OP_FkIfZero );
  73714. assert( p->aOp[addr].p4type==0 );
  73715. #ifdef SQLITE_VDBE_COVERAGE
  73716. sqlite3VdbeGetOp(p,-1)->iSrcLine = 0; /* Erase VdbeCoverage() macros */
  73717. #endif
  73718. p->nOp--;
  73719. }else{
  73720. sqlite3VdbeChangeP2(p, addr, p->nOp);
  73721. }
  73722. }
  73723. /*
  73724. ** If the input FuncDef structure is ephemeral, then free it. If
  73725. ** the FuncDef is not ephermal, then do nothing.
  73726. */
  73727. static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
  73728. if( (pDef->funcFlags & SQLITE_FUNC_EPHEM)!=0 ){
  73729. sqlite3DbFreeNN(db, pDef);
  73730. }
  73731. }
  73732. /*
  73733. ** Delete a P4 value if necessary.
  73734. */
  73735. static SQLITE_NOINLINE void freeP4Mem(sqlite3 *db, Mem *p){
  73736. if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
  73737. sqlite3DbFreeNN(db, p);
  73738. }
  73739. static SQLITE_NOINLINE void freeP4FuncCtx(sqlite3 *db, sqlite3_context *p){
  73740. freeEphemeralFunction(db, p->pFunc);
  73741. sqlite3DbFreeNN(db, p);
  73742. }
  73743. static void freeP4(sqlite3 *db, int p4type, void *p4){
  73744. assert( db );
  73745. switch( p4type ){
  73746. case P4_FUNCCTX: {
  73747. freeP4FuncCtx(db, (sqlite3_context*)p4);
  73748. break;
  73749. }
  73750. case P4_REAL:
  73751. case P4_INT64:
  73752. case P4_DYNAMIC:
  73753. case P4_DYNBLOB:
  73754. case P4_INTARRAY: {
  73755. sqlite3DbFree(db, p4);
  73756. break;
  73757. }
  73758. case P4_KEYINFO: {
  73759. if( db->pnBytesFreed==0 ) sqlite3KeyInfoUnref((KeyInfo*)p4);
  73760. break;
  73761. }
  73762. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  73763. case P4_EXPR: {
  73764. sqlite3ExprDelete(db, (Expr*)p4);
  73765. break;
  73766. }
  73767. #endif
  73768. case P4_FUNCDEF: {
  73769. freeEphemeralFunction(db, (FuncDef*)p4);
  73770. break;
  73771. }
  73772. case P4_MEM: {
  73773. if( db->pnBytesFreed==0 ){
  73774. sqlite3ValueFree((sqlite3_value*)p4);
  73775. }else{
  73776. freeP4Mem(db, (Mem*)p4);
  73777. }
  73778. break;
  73779. }
  73780. case P4_VTAB : {
  73781. if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);
  73782. break;
  73783. }
  73784. }
  73785. }
  73786. /*
  73787. ** Free the space allocated for aOp and any p4 values allocated for the
  73788. ** opcodes contained within. If aOp is not NULL it is assumed to contain
  73789. ** nOp entries.
  73790. */
  73791. static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
  73792. if( aOp ){
  73793. Op *pOp;
  73794. for(pOp=&aOp[nOp-1]; pOp>=aOp; pOp--){
  73795. if( pOp->p4type <= P4_FREE_IF_LE ) freeP4(db, pOp->p4type, pOp->p4.p);
  73796. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  73797. sqlite3DbFree(db, pOp->zComment);
  73798. #endif
  73799. }
  73800. sqlite3DbFreeNN(db, aOp);
  73801. }
  73802. }
  73803. /*
  73804. ** Link the SubProgram object passed as the second argument into the linked
  73805. ** list at Vdbe.pSubProgram. This list is used to delete all sub-program
  73806. ** objects when the VM is no longer required.
  73807. */
  73808. SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){
  73809. p->pNext = pVdbe->pProgram;
  73810. pVdbe->pProgram = p;
  73811. }
  73812. /*
  73813. ** Return true if the given Vdbe has any SubPrograms.
  73814. */
  73815. SQLITE_PRIVATE int sqlite3VdbeHasSubProgram(Vdbe *pVdbe){
  73816. return pVdbe->pProgram!=0;
  73817. }
  73818. /*
  73819. ** Change the opcode at addr into OP_Noop
  73820. */
  73821. SQLITE_PRIVATE int sqlite3VdbeChangeToNoop(Vdbe *p, int addr){
  73822. VdbeOp *pOp;
  73823. if( p->db->mallocFailed ) return 0;
  73824. assert( addr>=0 && addr<p->nOp );
  73825. pOp = &p->aOp[addr];
  73826. freeP4(p->db, pOp->p4type, pOp->p4.p);
  73827. pOp->p4type = P4_NOTUSED;
  73828. pOp->p4.z = 0;
  73829. pOp->opcode = OP_Noop;
  73830. return 1;
  73831. }
  73832. /*
  73833. ** If the last opcode is "op" and it is not a jump destination,
  73834. ** then remove it. Return true if and only if an opcode was removed.
  73835. */
  73836. SQLITE_PRIVATE int sqlite3VdbeDeletePriorOpcode(Vdbe *p, u8 op){
  73837. if( p->nOp>0 && p->aOp[p->nOp-1].opcode==op ){
  73838. return sqlite3VdbeChangeToNoop(p, p->nOp-1);
  73839. }else{
  73840. return 0;
  73841. }
  73842. }
  73843. #ifdef SQLITE_DEBUG
  73844. /*
  73845. ** Generate an OP_ReleaseReg opcode to indicate that a range of
  73846. ** registers, except any identified by mask, are no longer in use.
  73847. */
  73848. SQLITE_PRIVATE void sqlite3VdbeReleaseRegisters(
  73849. Parse *pParse, /* Parsing context */
  73850. int iFirst, /* Index of first register to be released */
  73851. int N, /* Number of registers to release */
  73852. u32 mask, /* Mask of registers to NOT release */
  73853. int bUndefine /* If true, mark registers as undefined */
  73854. ){
  73855. if( N==0 ) return;
  73856. assert( pParse->pVdbe );
  73857. assert( iFirst>=1 );
  73858. assert( iFirst+N-1<=pParse->nMem );
  73859. if( N<=31 && mask!=0 ){
  73860. while( N>0 && (mask&1)!=0 ){
  73861. mask >>= 1;
  73862. iFirst++;
  73863. N--;
  73864. }
  73865. while( N>0 && N<=32 && (mask & MASKBIT32(N-1))!=0 ){
  73866. mask &= ~MASKBIT32(N-1);
  73867. N--;
  73868. }
  73869. }
  73870. if( N>0 ){
  73871. sqlite3VdbeAddOp3(pParse->pVdbe, OP_ReleaseReg, iFirst, N, *(int*)&mask);
  73872. if( bUndefine ) sqlite3VdbeChangeP5(pParse->pVdbe, 1);
  73873. }
  73874. }
  73875. #endif /* SQLITE_DEBUG */
  73876. /*
  73877. ** Change the value of the P4 operand for a specific instruction.
  73878. ** This routine is useful when a large program is loaded from a
  73879. ** static array using sqlite3VdbeAddOpList but we want to make a
  73880. ** few minor changes to the program.
  73881. **
  73882. ** If n>=0 then the P4 operand is dynamic, meaning that a copy of
  73883. ** the string is made into memory obtained from sqlite3_malloc().
  73884. ** A value of n==0 means copy bytes of zP4 up to and including the
  73885. ** first null byte. If n>0 then copy n+1 bytes of zP4.
  73886. **
  73887. ** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
  73888. ** to a string or structure that is guaranteed to exist for the lifetime of
  73889. ** the Vdbe. In these cases we can just copy the pointer.
  73890. **
  73891. ** If addr<0 then change P4 on the most recently inserted instruction.
  73892. */
  73893. static void SQLITE_NOINLINE vdbeChangeP4Full(
  73894. Vdbe *p,
  73895. Op *pOp,
  73896. const char *zP4,
  73897. int n
  73898. ){
  73899. if( pOp->p4type ){
  73900. freeP4(p->db, pOp->p4type, pOp->p4.p);
  73901. pOp->p4type = 0;
  73902. pOp->p4.p = 0;
  73903. }
  73904. if( n<0 ){
  73905. sqlite3VdbeChangeP4(p, (int)(pOp - p->aOp), zP4, n);
  73906. }else{
  73907. if( n==0 ) n = sqlite3Strlen30(zP4);
  73908. pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
  73909. pOp->p4type = P4_DYNAMIC;
  73910. }
  73911. }
  73912. SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
  73913. Op *pOp;
  73914. sqlite3 *db;
  73915. assert( p!=0 );
  73916. db = p->db;
  73917. assert( p->magic==VDBE_MAGIC_INIT );
  73918. assert( p->aOp!=0 || db->mallocFailed );
  73919. if( db->mallocFailed ){
  73920. if( n!=P4_VTAB ) freeP4(db, n, (void*)*(char**)&zP4);
  73921. return;
  73922. }
  73923. assert( p->nOp>0 );
  73924. assert( addr<p->nOp );
  73925. if( addr<0 ){
  73926. addr = p->nOp - 1;
  73927. }
  73928. pOp = &p->aOp[addr];
  73929. if( n>=0 || pOp->p4type ){
  73930. vdbeChangeP4Full(p, pOp, zP4, n);
  73931. return;
  73932. }
  73933. if( n==P4_INT32 ){
  73934. /* Note: this cast is safe, because the origin data point was an int
  73935. ** that was cast to a (const char *). */
  73936. pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
  73937. pOp->p4type = P4_INT32;
  73938. }else if( zP4!=0 ){
  73939. assert( n<0 );
  73940. pOp->p4.p = (void*)zP4;
  73941. pOp->p4type = (signed char)n;
  73942. if( n==P4_VTAB ) sqlite3VtabLock((VTable*)zP4);
  73943. }
  73944. }
  73945. /*
  73946. ** Change the P4 operand of the most recently coded instruction
  73947. ** to the value defined by the arguments. This is a high-speed
  73948. ** version of sqlite3VdbeChangeP4().
  73949. **
  73950. ** The P4 operand must not have been previously defined. And the new
  73951. ** P4 must not be P4_INT32. Use sqlite3VdbeChangeP4() in either of
  73952. ** those cases.
  73953. */
  73954. SQLITE_PRIVATE void sqlite3VdbeAppendP4(Vdbe *p, void *pP4, int n){
  73955. VdbeOp *pOp;
  73956. assert( n!=P4_INT32 && n!=P4_VTAB );
  73957. assert( n<=0 );
  73958. if( p->db->mallocFailed ){
  73959. freeP4(p->db, n, pP4);
  73960. }else{
  73961. assert( pP4!=0 );
  73962. assert( p->nOp>0 );
  73963. pOp = &p->aOp[p->nOp-1];
  73964. assert( pOp->p4type==P4_NOTUSED );
  73965. pOp->p4type = n;
  73966. pOp->p4.p = pP4;
  73967. }
  73968. }
  73969. /*
  73970. ** Set the P4 on the most recently added opcode to the KeyInfo for the
  73971. ** index given.
  73972. */
  73973. SQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse *pParse, Index *pIdx){
  73974. Vdbe *v = pParse->pVdbe;
  73975. KeyInfo *pKeyInfo;
  73976. assert( v!=0 );
  73977. assert( pIdx!=0 );
  73978. pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pIdx);
  73979. if( pKeyInfo ) sqlite3VdbeAppendP4(v, pKeyInfo, P4_KEYINFO);
  73980. }
  73981. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  73982. /*
  73983. ** Change the comment on the most recently coded instruction. Or
  73984. ** insert a No-op and add the comment to that new instruction. This
  73985. ** makes the code easier to read during debugging. None of this happens
  73986. ** in a production build.
  73987. */
  73988. static void vdbeVComment(Vdbe *p, const char *zFormat, va_list ap){
  73989. assert( p->nOp>0 || p->aOp==0 );
  73990. assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed
  73991. || p->pParse->nErr>0 );
  73992. if( p->nOp ){
  73993. assert( p->aOp );
  73994. sqlite3DbFree(p->db, p->aOp[p->nOp-1].zComment);
  73995. p->aOp[p->nOp-1].zComment = sqlite3VMPrintf(p->db, zFormat, ap);
  73996. }
  73997. }
  73998. SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
  73999. va_list ap;
  74000. if( p ){
  74001. va_start(ap, zFormat);
  74002. vdbeVComment(p, zFormat, ap);
  74003. va_end(ap);
  74004. }
  74005. }
  74006. SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
  74007. va_list ap;
  74008. if( p ){
  74009. sqlite3VdbeAddOp0(p, OP_Noop);
  74010. va_start(ap, zFormat);
  74011. vdbeVComment(p, zFormat, ap);
  74012. va_end(ap);
  74013. }
  74014. }
  74015. #endif /* NDEBUG */
  74016. #ifdef SQLITE_VDBE_COVERAGE
  74017. /*
  74018. ** Set the value if the iSrcLine field for the previously coded instruction.
  74019. */
  74020. SQLITE_PRIVATE void sqlite3VdbeSetLineNumber(Vdbe *v, int iLine){
  74021. sqlite3VdbeGetOp(v,-1)->iSrcLine = iLine;
  74022. }
  74023. #endif /* SQLITE_VDBE_COVERAGE */
  74024. /*
  74025. ** Return the opcode for a given address. If the address is -1, then
  74026. ** return the most recently inserted opcode.
  74027. **
  74028. ** If a memory allocation error has occurred prior to the calling of this
  74029. ** routine, then a pointer to a dummy VdbeOp will be returned. That opcode
  74030. ** is readable but not writable, though it is cast to a writable value.
  74031. ** The return of a dummy opcode allows the call to continue functioning
  74032. ** after an OOM fault without having to check to see if the return from
  74033. ** this routine is a valid pointer. But because the dummy.opcode is 0,
  74034. ** dummy will never be written to. This is verified by code inspection and
  74035. ** by running with Valgrind.
  74036. */
  74037. SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
  74038. /* C89 specifies that the constant "dummy" will be initialized to all
  74039. ** zeros, which is correct. MSVC generates a warning, nevertheless. */
  74040. static VdbeOp dummy; /* Ignore the MSVC warning about no initializer */
  74041. assert( p->magic==VDBE_MAGIC_INIT );
  74042. if( addr<0 ){
  74043. addr = p->nOp - 1;
  74044. }
  74045. assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
  74046. if( p->db->mallocFailed ){
  74047. return (VdbeOp*)&dummy;
  74048. }else{
  74049. return &p->aOp[addr];
  74050. }
  74051. }
  74052. #if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS)
  74053. /*
  74054. ** Return an integer value for one of the parameters to the opcode pOp
  74055. ** determined by character c.
  74056. */
  74057. static int translateP(char c, const Op *pOp){
  74058. if( c=='1' ) return pOp->p1;
  74059. if( c=='2' ) return pOp->p2;
  74060. if( c=='3' ) return pOp->p3;
  74061. if( c=='4' ) return pOp->p4.i;
  74062. return pOp->p5;
  74063. }
  74064. /*
  74065. ** Compute a string for the "comment" field of a VDBE opcode listing.
  74066. **
  74067. ** The Synopsis: field in comments in the vdbe.c source file gets converted
  74068. ** to an extra string that is appended to the sqlite3OpcodeName(). In the
  74069. ** absence of other comments, this synopsis becomes the comment on the opcode.
  74070. ** Some translation occurs:
  74071. **
  74072. ** "PX" -> "r[X]"
  74073. ** "PX@PY" -> "r[X..X+Y-1]" or "r[x]" if y is 0 or 1
  74074. ** "PX@PY+1" -> "r[X..X+Y]" or "r[x]" if y is 0
  74075. ** "PY..PY" -> "r[X..Y]" or "r[x]" if y<=x
  74076. */
  74077. SQLITE_PRIVATE char *sqlite3VdbeDisplayComment(
  74078. sqlite3 *db, /* Optional - Oom error reporting only */
  74079. const Op *pOp, /* The opcode to be commented */
  74080. const char *zP4 /* Previously obtained value for P4 */
  74081. ){
  74082. const char *zOpName;
  74083. const char *zSynopsis;
  74084. int nOpName;
  74085. int ii;
  74086. char zAlt[50];
  74087. StrAccum x;
  74088. sqlite3StrAccumInit(&x, 0, 0, 0, SQLITE_MAX_LENGTH);
  74089. zOpName = sqlite3OpcodeName(pOp->opcode);
  74090. nOpName = sqlite3Strlen30(zOpName);
  74091. if( zOpName[nOpName+1] ){
  74092. int seenCom = 0;
  74093. char c;
  74094. zSynopsis = zOpName += nOpName + 1;
  74095. if( strncmp(zSynopsis,"IF ",3)==0 ){
  74096. if( pOp->p5 & SQLITE_STOREP2 ){
  74097. sqlite3_snprintf(sizeof(zAlt), zAlt, "r[P2] = (%s)", zSynopsis+3);
  74098. }else{
  74099. sqlite3_snprintf(sizeof(zAlt), zAlt, "if %s goto P2", zSynopsis+3);
  74100. }
  74101. zSynopsis = zAlt;
  74102. }
  74103. for(ii=0; (c = zSynopsis[ii])!=0; ii++){
  74104. if( c=='P' ){
  74105. c = zSynopsis[++ii];
  74106. if( c=='4' ){
  74107. sqlite3_str_appendall(&x, zP4);
  74108. }else if( c=='X' ){
  74109. sqlite3_str_appendall(&x, pOp->zComment);
  74110. seenCom = 1;
  74111. }else{
  74112. int v1 = translateP(c, pOp);
  74113. int v2;
  74114. if( strncmp(zSynopsis+ii+1, "@P", 2)==0 ){
  74115. ii += 3;
  74116. v2 = translateP(zSynopsis[ii], pOp);
  74117. if( strncmp(zSynopsis+ii+1,"+1",2)==0 ){
  74118. ii += 2;
  74119. v2++;
  74120. }
  74121. if( v2<2 ){
  74122. sqlite3_str_appendf(&x, "%d", v1);
  74123. }else{
  74124. sqlite3_str_appendf(&x, "%d..%d", v1, v1+v2-1);
  74125. }
  74126. }else if( strncmp(zSynopsis+ii+1, "@NP", 3)==0 ){
  74127. sqlite3_context *pCtx = pOp->p4.pCtx;
  74128. if( pOp->p4type!=P4_FUNCCTX || pCtx->argc==1 ){
  74129. sqlite3_str_appendf(&x, "%d", v1);
  74130. }else if( pCtx->argc>1 ){
  74131. sqlite3_str_appendf(&x, "%d..%d", v1, v1+pCtx->argc-1);
  74132. }else{
  74133. assert( x.nChar>2 );
  74134. x.nChar -= 2;
  74135. ii++;
  74136. }
  74137. ii += 3;
  74138. }else{
  74139. sqlite3_str_appendf(&x, "%d", v1);
  74140. if( strncmp(zSynopsis+ii+1, "..P3", 4)==0 && pOp->p3==0 ){
  74141. ii += 4;
  74142. }
  74143. }
  74144. }
  74145. }else{
  74146. sqlite3_str_appendchar(&x, 1, c);
  74147. }
  74148. }
  74149. if( !seenCom && pOp->zComment ){
  74150. sqlite3_str_appendf(&x, "; %s", pOp->zComment);
  74151. }
  74152. }else if( pOp->zComment ){
  74153. sqlite3_str_appendall(&x, pOp->zComment);
  74154. }
  74155. if( (x.accError & SQLITE_NOMEM)!=0 && db!=0 ){
  74156. sqlite3OomFault(db);
  74157. }
  74158. return sqlite3StrAccumFinish(&x);
  74159. }
  74160. #endif /* SQLITE_ENABLE_EXPLAIN_COMMENTS */
  74161. #if VDBE_DISPLAY_P4 && defined(SQLITE_ENABLE_CURSOR_HINTS)
  74162. /*
  74163. ** Translate the P4.pExpr value for an OP_CursorHint opcode into text
  74164. ** that can be displayed in the P4 column of EXPLAIN output.
  74165. */
  74166. static void displayP4Expr(StrAccum *p, Expr *pExpr){
  74167. const char *zOp = 0;
  74168. switch( pExpr->op ){
  74169. case TK_STRING:
  74170. sqlite3_str_appendf(p, "%Q", pExpr->u.zToken);
  74171. break;
  74172. case TK_INTEGER:
  74173. sqlite3_str_appendf(p, "%d", pExpr->u.iValue);
  74174. break;
  74175. case TK_NULL:
  74176. sqlite3_str_appendf(p, "NULL");
  74177. break;
  74178. case TK_REGISTER: {
  74179. sqlite3_str_appendf(p, "r[%d]", pExpr->iTable);
  74180. break;
  74181. }
  74182. case TK_COLUMN: {
  74183. if( pExpr->iColumn<0 ){
  74184. sqlite3_str_appendf(p, "rowid");
  74185. }else{
  74186. sqlite3_str_appendf(p, "c%d", (int)pExpr->iColumn);
  74187. }
  74188. break;
  74189. }
  74190. case TK_LT: zOp = "LT"; break;
  74191. case TK_LE: zOp = "LE"; break;
  74192. case TK_GT: zOp = "GT"; break;
  74193. case TK_GE: zOp = "GE"; break;
  74194. case TK_NE: zOp = "NE"; break;
  74195. case TK_EQ: zOp = "EQ"; break;
  74196. case TK_IS: zOp = "IS"; break;
  74197. case TK_ISNOT: zOp = "ISNOT"; break;
  74198. case TK_AND: zOp = "AND"; break;
  74199. case TK_OR: zOp = "OR"; break;
  74200. case TK_PLUS: zOp = "ADD"; break;
  74201. case TK_STAR: zOp = "MUL"; break;
  74202. case TK_MINUS: zOp = "SUB"; break;
  74203. case TK_REM: zOp = "REM"; break;
  74204. case TK_BITAND: zOp = "BITAND"; break;
  74205. case TK_BITOR: zOp = "BITOR"; break;
  74206. case TK_SLASH: zOp = "DIV"; break;
  74207. case TK_LSHIFT: zOp = "LSHIFT"; break;
  74208. case TK_RSHIFT: zOp = "RSHIFT"; break;
  74209. case TK_CONCAT: zOp = "CONCAT"; break;
  74210. case TK_UMINUS: zOp = "MINUS"; break;
  74211. case TK_UPLUS: zOp = "PLUS"; break;
  74212. case TK_BITNOT: zOp = "BITNOT"; break;
  74213. case TK_NOT: zOp = "NOT"; break;
  74214. case TK_ISNULL: zOp = "ISNULL"; break;
  74215. case TK_NOTNULL: zOp = "NOTNULL"; break;
  74216. default:
  74217. sqlite3_str_appendf(p, "%s", "expr");
  74218. break;
  74219. }
  74220. if( zOp ){
  74221. sqlite3_str_appendf(p, "%s(", zOp);
  74222. displayP4Expr(p, pExpr->pLeft);
  74223. if( pExpr->pRight ){
  74224. sqlite3_str_append(p, ",", 1);
  74225. displayP4Expr(p, pExpr->pRight);
  74226. }
  74227. sqlite3_str_append(p, ")", 1);
  74228. }
  74229. }
  74230. #endif /* VDBE_DISPLAY_P4 && defined(SQLITE_ENABLE_CURSOR_HINTS) */
  74231. #if VDBE_DISPLAY_P4
  74232. /*
  74233. ** Compute a string that describes the P4 parameter for an opcode.
  74234. ** Use zTemp for any required temporary buffer space.
  74235. */
  74236. SQLITE_PRIVATE char *sqlite3VdbeDisplayP4(sqlite3 *db, Op *pOp){
  74237. char *zP4 = 0;
  74238. StrAccum x;
  74239. sqlite3StrAccumInit(&x, 0, 0, 0, SQLITE_MAX_LENGTH);
  74240. switch( pOp->p4type ){
  74241. case P4_KEYINFO: {
  74242. int j;
  74243. KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
  74244. assert( pKeyInfo->aSortFlags!=0 );
  74245. sqlite3_str_appendf(&x, "k(%d", pKeyInfo->nKeyField);
  74246. for(j=0; j<pKeyInfo->nKeyField; j++){
  74247. CollSeq *pColl = pKeyInfo->aColl[j];
  74248. const char *zColl = pColl ? pColl->zName : "";
  74249. if( strcmp(zColl, "BINARY")==0 ) zColl = "B";
  74250. sqlite3_str_appendf(&x, ",%s%s%s",
  74251. (pKeyInfo->aSortFlags[j] & KEYINFO_ORDER_DESC) ? "-" : "",
  74252. (pKeyInfo->aSortFlags[j] & KEYINFO_ORDER_BIGNULL)? "N." : "",
  74253. zColl);
  74254. }
  74255. sqlite3_str_append(&x, ")", 1);
  74256. break;
  74257. }
  74258. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  74259. case P4_EXPR: {
  74260. displayP4Expr(&x, pOp->p4.pExpr);
  74261. break;
  74262. }
  74263. #endif
  74264. case P4_COLLSEQ: {
  74265. static const char *const encnames[] = {"?", "8", "16LE", "16BE"};
  74266. CollSeq *pColl = pOp->p4.pColl;
  74267. assert( pColl->enc>=0 && pColl->enc<4 );
  74268. sqlite3_str_appendf(&x, "%.18s-%s", pColl->zName,
  74269. encnames[pColl->enc]);
  74270. break;
  74271. }
  74272. case P4_FUNCDEF: {
  74273. FuncDef *pDef = pOp->p4.pFunc;
  74274. sqlite3_str_appendf(&x, "%s(%d)", pDef->zName, pDef->nArg);
  74275. break;
  74276. }
  74277. case P4_FUNCCTX: {
  74278. FuncDef *pDef = pOp->p4.pCtx->pFunc;
  74279. sqlite3_str_appendf(&x, "%s(%d)", pDef->zName, pDef->nArg);
  74280. break;
  74281. }
  74282. case P4_INT64: {
  74283. sqlite3_str_appendf(&x, "%lld", *pOp->p4.pI64);
  74284. break;
  74285. }
  74286. case P4_INT32: {
  74287. sqlite3_str_appendf(&x, "%d", pOp->p4.i);
  74288. break;
  74289. }
  74290. case P4_REAL: {
  74291. sqlite3_str_appendf(&x, "%.16g", *pOp->p4.pReal);
  74292. break;
  74293. }
  74294. case P4_MEM: {
  74295. Mem *pMem = pOp->p4.pMem;
  74296. if( pMem->flags & MEM_Str ){
  74297. zP4 = pMem->z;
  74298. }else if( pMem->flags & (MEM_Int|MEM_IntReal) ){
  74299. sqlite3_str_appendf(&x, "%lld", pMem->u.i);
  74300. }else if( pMem->flags & MEM_Real ){
  74301. sqlite3_str_appendf(&x, "%.16g", pMem->u.r);
  74302. }else if( pMem->flags & MEM_Null ){
  74303. zP4 = "NULL";
  74304. }else{
  74305. assert( pMem->flags & MEM_Blob );
  74306. zP4 = "(blob)";
  74307. }
  74308. break;
  74309. }
  74310. #ifndef SQLITE_OMIT_VIRTUALTABLE
  74311. case P4_VTAB: {
  74312. sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
  74313. sqlite3_str_appendf(&x, "vtab:%p", pVtab);
  74314. break;
  74315. }
  74316. #endif
  74317. case P4_INTARRAY: {
  74318. int i;
  74319. int *ai = pOp->p4.ai;
  74320. int n = ai[0]; /* The first element of an INTARRAY is always the
  74321. ** count of the number of elements to follow */
  74322. for(i=1; i<=n; i++){
  74323. sqlite3_str_appendf(&x, "%c%d", (i==1 ? '[' : ','), ai[i]);
  74324. }
  74325. sqlite3_str_append(&x, "]", 1);
  74326. break;
  74327. }
  74328. case P4_SUBPROGRAM: {
  74329. zP4 = "program";
  74330. break;
  74331. }
  74332. case P4_DYNBLOB:
  74333. case P4_ADVANCE: {
  74334. break;
  74335. }
  74336. case P4_TABLE: {
  74337. zP4 = pOp->p4.pTab->zName;
  74338. break;
  74339. }
  74340. default: {
  74341. zP4 = pOp->p4.z;
  74342. }
  74343. }
  74344. if( zP4 ) sqlite3_str_appendall(&x, zP4);
  74345. if( (x.accError & SQLITE_NOMEM)!=0 ){
  74346. sqlite3OomFault(db);
  74347. }
  74348. return sqlite3StrAccumFinish(&x);
  74349. }
  74350. #endif /* VDBE_DISPLAY_P4 */
  74351. /*
  74352. ** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
  74353. **
  74354. ** The prepared statements need to know in advance the complete set of
  74355. ** attached databases that will be use. A mask of these databases
  74356. ** is maintained in p->btreeMask. The p->lockMask value is the subset of
  74357. ** p->btreeMask of databases that will require a lock.
  74358. */
  74359. SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
  74360. assert( i>=0 && i<p->db->nDb && i<(int)sizeof(yDbMask)*8 );
  74361. assert( i<(int)sizeof(p->btreeMask)*8 );
  74362. DbMaskSet(p->btreeMask, i);
  74363. if( i!=1 && sqlite3BtreeSharable(p->db->aDb[i].pBt) ){
  74364. DbMaskSet(p->lockMask, i);
  74365. }
  74366. }
  74367. #if !defined(SQLITE_OMIT_SHARED_CACHE)
  74368. /*
  74369. ** If SQLite is compiled to support shared-cache mode and to be threadsafe,
  74370. ** this routine obtains the mutex associated with each BtShared structure
  74371. ** that may be accessed by the VM passed as an argument. In doing so it also
  74372. ** sets the BtShared.db member of each of the BtShared structures, ensuring
  74373. ** that the correct busy-handler callback is invoked if required.
  74374. **
  74375. ** If SQLite is not threadsafe but does support shared-cache mode, then
  74376. ** sqlite3BtreeEnter() is invoked to set the BtShared.db variables
  74377. ** of all of BtShared structures accessible via the database handle
  74378. ** associated with the VM.
  74379. **
  74380. ** If SQLite is not threadsafe and does not support shared-cache mode, this
  74381. ** function is a no-op.
  74382. **
  74383. ** The p->btreeMask field is a bitmask of all btrees that the prepared
  74384. ** statement p will ever use. Let N be the number of bits in p->btreeMask
  74385. ** corresponding to btrees that use shared cache. Then the runtime of
  74386. ** this routine is N*N. But as N is rarely more than 1, this should not
  74387. ** be a problem.
  74388. */
  74389. SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe *p){
  74390. int i;
  74391. sqlite3 *db;
  74392. Db *aDb;
  74393. int nDb;
  74394. if( DbMaskAllZero(p->lockMask) ) return; /* The common case */
  74395. db = p->db;
  74396. aDb = db->aDb;
  74397. nDb = db->nDb;
  74398. for(i=0; i<nDb; i++){
  74399. if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
  74400. sqlite3BtreeEnter(aDb[i].pBt);
  74401. }
  74402. }
  74403. }
  74404. #endif
  74405. #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
  74406. /*
  74407. ** Unlock all of the btrees previously locked by a call to sqlite3VdbeEnter().
  74408. */
  74409. static SQLITE_NOINLINE void vdbeLeave(Vdbe *p){
  74410. int i;
  74411. sqlite3 *db;
  74412. Db *aDb;
  74413. int nDb;
  74414. db = p->db;
  74415. aDb = db->aDb;
  74416. nDb = db->nDb;
  74417. for(i=0; i<nDb; i++){
  74418. if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
  74419. sqlite3BtreeLeave(aDb[i].pBt);
  74420. }
  74421. }
  74422. }
  74423. SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe *p){
  74424. if( DbMaskAllZero(p->lockMask) ) return; /* The common case */
  74425. vdbeLeave(p);
  74426. }
  74427. #endif
  74428. #if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
  74429. /*
  74430. ** Print a single opcode. This routine is used for debugging only.
  74431. */
  74432. SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, VdbeOp *pOp){
  74433. char *zP4;
  74434. char *zCom;
  74435. sqlite3 dummyDb;
  74436. static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-13s %.2X %s\n";
  74437. if( pOut==0 ) pOut = stdout;
  74438. sqlite3BeginBenignMalloc();
  74439. dummyDb.mallocFailed = 1;
  74440. zP4 = sqlite3VdbeDisplayP4(&dummyDb, pOp);
  74441. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  74442. zCom = sqlite3VdbeDisplayComment(0, pOp, zP4);
  74443. #else
  74444. zCom = 0;
  74445. #endif
  74446. /* NB: The sqlite3OpcodeName() function is implemented by code created
  74447. ** by the mkopcodeh.awk and mkopcodec.awk scripts which extract the
  74448. ** information from the vdbe.c source text */
  74449. fprintf(pOut, zFormat1, pc,
  74450. sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3,
  74451. zP4 ? zP4 : "", pOp->p5,
  74452. zCom ? zCom : ""
  74453. );
  74454. fflush(pOut);
  74455. sqlite3_free(zP4);
  74456. sqlite3_free(zCom);
  74457. sqlite3EndBenignMalloc();
  74458. }
  74459. #endif
  74460. /*
  74461. ** Initialize an array of N Mem element.
  74462. */
  74463. static void initMemArray(Mem *p, int N, sqlite3 *db, u16 flags){
  74464. while( (N--)>0 ){
  74465. p->db = db;
  74466. p->flags = flags;
  74467. p->szMalloc = 0;
  74468. #ifdef SQLITE_DEBUG
  74469. p->pScopyFrom = 0;
  74470. #endif
  74471. p++;
  74472. }
  74473. }
  74474. /*
  74475. ** Release an array of N Mem elements
  74476. */
  74477. static void releaseMemArray(Mem *p, int N){
  74478. if( p && N ){
  74479. Mem *pEnd = &p[N];
  74480. sqlite3 *db = p->db;
  74481. if( db->pnBytesFreed ){
  74482. do{
  74483. if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
  74484. }while( (++p)<pEnd );
  74485. return;
  74486. }
  74487. do{
  74488. assert( (&p[1])==pEnd || p[0].db==p[1].db );
  74489. assert( sqlite3VdbeCheckMemInvariants(p) );
  74490. /* This block is really an inlined version of sqlite3VdbeMemRelease()
  74491. ** that takes advantage of the fact that the memory cell value is
  74492. ** being set to NULL after releasing any dynamic resources.
  74493. **
  74494. ** The justification for duplicating code is that according to
  74495. ** callgrind, this causes a certain test case to hit the CPU 4.7
  74496. ** percent less (x86 linux, gcc version 4.1.2, -O6) than if
  74497. ** sqlite3MemRelease() were called from here. With -O2, this jumps
  74498. ** to 6.6 percent. The test case is inserting 1000 rows into a table
  74499. ** with no indexes using a single prepared INSERT statement, bind()
  74500. ** and reset(). Inserts are grouped into a transaction.
  74501. */
  74502. testcase( p->flags & MEM_Agg );
  74503. testcase( p->flags & MEM_Dyn );
  74504. testcase( p->xDel==sqlite3VdbeFrameMemDel );
  74505. if( p->flags&(MEM_Agg|MEM_Dyn) ){
  74506. sqlite3VdbeMemRelease(p);
  74507. }else if( p->szMalloc ){
  74508. sqlite3DbFreeNN(db, p->zMalloc);
  74509. p->szMalloc = 0;
  74510. }
  74511. p->flags = MEM_Undefined;
  74512. }while( (++p)<pEnd );
  74513. }
  74514. }
  74515. #ifdef SQLITE_DEBUG
  74516. /*
  74517. ** Verify that pFrame is a valid VdbeFrame pointer. Return true if it is
  74518. ** and false if something is wrong.
  74519. **
  74520. ** This routine is intended for use inside of assert() statements only.
  74521. */
  74522. SQLITE_PRIVATE int sqlite3VdbeFrameIsValid(VdbeFrame *pFrame){
  74523. if( pFrame->iFrameMagic!=SQLITE_FRAME_MAGIC ) return 0;
  74524. return 1;
  74525. }
  74526. #endif
  74527. /*
  74528. ** This is a destructor on a Mem object (which is really an sqlite3_value)
  74529. ** that deletes the Frame object that is attached to it as a blob.
  74530. **
  74531. ** This routine does not delete the Frame right away. It merely adds the
  74532. ** frame to a list of frames to be deleted when the Vdbe halts.
  74533. */
  74534. SQLITE_PRIVATE void sqlite3VdbeFrameMemDel(void *pArg){
  74535. VdbeFrame *pFrame = (VdbeFrame*)pArg;
  74536. assert( sqlite3VdbeFrameIsValid(pFrame) );
  74537. pFrame->pParent = pFrame->v->pDelFrame;
  74538. pFrame->v->pDelFrame = pFrame;
  74539. }
  74540. #if defined(SQLITE_ENABLE_BYTECODE_VTAB) || !defined(SQLITE_OMIT_EXPLAIN)
  74541. /*
  74542. ** Locate the next opcode to be displayed in EXPLAIN or EXPLAIN
  74543. ** QUERY PLAN output.
  74544. **
  74545. ** Return SQLITE_ROW on success. Return SQLITE_DONE if there are no
  74546. ** more opcodes to be displayed.
  74547. */
  74548. SQLITE_PRIVATE int sqlite3VdbeNextOpcode(
  74549. Vdbe *p, /* The statement being explained */
  74550. Mem *pSub, /* Storage for keeping track of subprogram nesting */
  74551. int eMode, /* 0: normal. 1: EQP. 2: TablesUsed */
  74552. int *piPc, /* IN/OUT: Current rowid. Overwritten with next rowid */
  74553. int *piAddr, /* OUT: Write index into (*paOp)[] here */
  74554. Op **paOp /* OUT: Write the opcode array here */
  74555. ){
  74556. int nRow; /* Stop when row count reaches this */
  74557. int nSub = 0; /* Number of sub-vdbes seen so far */
  74558. SubProgram **apSub = 0; /* Array of sub-vdbes */
  74559. int i; /* Next instruction address */
  74560. int rc = SQLITE_OK; /* Result code */
  74561. Op *aOp = 0; /* Opcode array */
  74562. int iPc; /* Rowid. Copy of value in *piPc */
  74563. /* When the number of output rows reaches nRow, that means the
  74564. ** listing has finished and sqlite3_step() should return SQLITE_DONE.
  74565. ** nRow is the sum of the number of rows in the main program, plus
  74566. ** the sum of the number of rows in all trigger subprograms encountered
  74567. ** so far. The nRow value will increase as new trigger subprograms are
  74568. ** encountered, but p->pc will eventually catch up to nRow.
  74569. */
  74570. nRow = p->nOp;
  74571. if( pSub!=0 ){
  74572. if( pSub->flags&MEM_Blob ){
  74573. /* pSub is initiallly NULL. It is initialized to a BLOB by
  74574. ** the P4_SUBPROGRAM processing logic below */
  74575. nSub = pSub->n/sizeof(Vdbe*);
  74576. apSub = (SubProgram **)pSub->z;
  74577. }
  74578. for(i=0; i<nSub; i++){
  74579. nRow += apSub[i]->nOp;
  74580. }
  74581. }
  74582. iPc = *piPc;
  74583. while(1){ /* Loop exits via break */
  74584. i = iPc++;
  74585. if( i>=nRow ){
  74586. p->rc = SQLITE_OK;
  74587. rc = SQLITE_DONE;
  74588. break;
  74589. }
  74590. if( i<p->nOp ){
  74591. /* The rowid is small enough that we are still in the
  74592. ** main program. */
  74593. aOp = p->aOp;
  74594. }else{
  74595. /* We are currently listing subprograms. Figure out which one and
  74596. ** pick up the appropriate opcode. */
  74597. int j;
  74598. i -= p->nOp;
  74599. assert( apSub!=0 );
  74600. assert( nSub>0 );
  74601. for(j=0; i>=apSub[j]->nOp; j++){
  74602. i -= apSub[j]->nOp;
  74603. assert( i<apSub[j]->nOp || j+1<nSub );
  74604. }
  74605. aOp = apSub[j]->aOp;
  74606. }
  74607. /* When an OP_Program opcode is encounter (the only opcode that has
  74608. ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
  74609. ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
  74610. ** has not already been seen.
  74611. */
  74612. if( pSub!=0 && aOp[i].p4type==P4_SUBPROGRAM ){
  74613. int nByte = (nSub+1)*sizeof(SubProgram*);
  74614. int j;
  74615. for(j=0; j<nSub; j++){
  74616. if( apSub[j]==aOp[i].p4.pProgram ) break;
  74617. }
  74618. if( j==nSub ){
  74619. p->rc = sqlite3VdbeMemGrow(pSub, nByte, nSub!=0);
  74620. if( p->rc!=SQLITE_OK ){
  74621. rc = SQLITE_ERROR;
  74622. break;
  74623. }
  74624. apSub = (SubProgram **)pSub->z;
  74625. apSub[nSub++] = aOp[i].p4.pProgram;
  74626. MemSetTypeFlag(pSub, MEM_Blob);
  74627. pSub->n = nSub*sizeof(SubProgram*);
  74628. nRow += aOp[i].p4.pProgram->nOp;
  74629. }
  74630. }
  74631. if( eMode==0 ) break;
  74632. #ifdef SQLITE_ENABLE_BYTECODE_VTAB
  74633. if( eMode==2 ){
  74634. Op *pOp = aOp + i;
  74635. if( pOp->opcode==OP_OpenRead ) break;
  74636. if( pOp->opcode==OP_OpenWrite && (pOp->p5 & OPFLAG_P2ISREG)==0 ) break;
  74637. if( pOp->opcode==OP_ReopenIdx ) break;
  74638. }else
  74639. #endif
  74640. {
  74641. assert( eMode==1 );
  74642. if( aOp[i].opcode==OP_Explain ) break;
  74643. if( aOp[i].opcode==OP_Init && iPc>1 ) break;
  74644. }
  74645. }
  74646. *piPc = iPc;
  74647. *piAddr = i;
  74648. *paOp = aOp;
  74649. return rc;
  74650. }
  74651. #endif /* SQLITE_ENABLE_BYTECODE_VTAB || !SQLITE_OMIT_EXPLAIN */
  74652. /*
  74653. ** Delete a VdbeFrame object and its contents. VdbeFrame objects are
  74654. ** allocated by the OP_Program opcode in sqlite3VdbeExec().
  74655. */
  74656. SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame *p){
  74657. int i;
  74658. Mem *aMem = VdbeFrameMem(p);
  74659. VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
  74660. assert( sqlite3VdbeFrameIsValid(p) );
  74661. for(i=0; i<p->nChildCsr; i++){
  74662. sqlite3VdbeFreeCursor(p->v, apCsr[i]);
  74663. }
  74664. releaseMemArray(aMem, p->nChildMem);
  74665. sqlite3VdbeDeleteAuxData(p->v->db, &p->pAuxData, -1, 0);
  74666. sqlite3DbFree(p->v->db, p);
  74667. }
  74668. #ifndef SQLITE_OMIT_EXPLAIN
  74669. /*
  74670. ** Give a listing of the program in the virtual machine.
  74671. **
  74672. ** The interface is the same as sqlite3VdbeExec(). But instead of
  74673. ** running the code, it invokes the callback once for each instruction.
  74674. ** This feature is used to implement "EXPLAIN".
  74675. **
  74676. ** When p->explain==1, each instruction is listed. When
  74677. ** p->explain==2, only OP_Explain instructions are listed and these
  74678. ** are shown in a different format. p->explain==2 is used to implement
  74679. ** EXPLAIN QUERY PLAN.
  74680. ** 2018-04-24: In p->explain==2 mode, the OP_Init opcodes of triggers
  74681. ** are also shown, so that the boundaries between the main program and
  74682. ** each trigger are clear.
  74683. **
  74684. ** When p->explain==1, first the main program is listed, then each of
  74685. ** the trigger subprograms are listed one by one.
  74686. */
  74687. SQLITE_PRIVATE int sqlite3VdbeList(
  74688. Vdbe *p /* The VDBE */
  74689. ){
  74690. Mem *pSub = 0; /* Memory cell hold array of subprogs */
  74691. sqlite3 *db = p->db; /* The database connection */
  74692. int i; /* Loop counter */
  74693. int rc = SQLITE_OK; /* Return code */
  74694. Mem *pMem = &p->aMem[1]; /* First Mem of result set */
  74695. int bListSubprogs = (p->explain==1 || (db->flags & SQLITE_TriggerEQP)!=0);
  74696. Op *aOp; /* Array of opcodes */
  74697. Op *pOp; /* Current opcode */
  74698. assert( p->explain );
  74699. assert( p->magic==VDBE_MAGIC_RUN );
  74700. assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
  74701. /* Even though this opcode does not use dynamic strings for
  74702. ** the result, result columns may become dynamic if the user calls
  74703. ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
  74704. */
  74705. releaseMemArray(pMem, 8);
  74706. p->pResultSet = 0;
  74707. if( p->rc==SQLITE_NOMEM ){
  74708. /* This happens if a malloc() inside a call to sqlite3_column_text() or
  74709. ** sqlite3_column_text16() failed. */
  74710. sqlite3OomFault(db);
  74711. return SQLITE_ERROR;
  74712. }
  74713. if( bListSubprogs ){
  74714. /* The first 8 memory cells are used for the result set. So we will
  74715. ** commandeer the 9th cell to use as storage for an array of pointers
  74716. ** to trigger subprograms. The VDBE is guaranteed to have at least 9
  74717. ** cells. */
  74718. assert( p->nMem>9 );
  74719. pSub = &p->aMem[9];
  74720. }else{
  74721. pSub = 0;
  74722. }
  74723. /* Figure out which opcode is next to display */
  74724. rc = sqlite3VdbeNextOpcode(p, pSub, p->explain==2, &p->pc, &i, &aOp);
  74725. if( rc==SQLITE_OK ){
  74726. pOp = aOp + i;
  74727. if( AtomicLoad(&db->u1.isInterrupted) ){
  74728. p->rc = SQLITE_INTERRUPT;
  74729. rc = SQLITE_ERROR;
  74730. sqlite3VdbeError(p, sqlite3ErrStr(p->rc));
  74731. }else{
  74732. char *zP4 = sqlite3VdbeDisplayP4(db, pOp);
  74733. if( p->explain==2 ){
  74734. sqlite3VdbeMemSetInt64(pMem, pOp->p1);
  74735. sqlite3VdbeMemSetInt64(pMem+1, pOp->p2);
  74736. sqlite3VdbeMemSetInt64(pMem+2, pOp->p3);
  74737. sqlite3VdbeMemSetStr(pMem+3, zP4, -1, SQLITE_UTF8, sqlite3_free);
  74738. p->nResColumn = 4;
  74739. }else{
  74740. sqlite3VdbeMemSetInt64(pMem+0, i);
  74741. sqlite3VdbeMemSetStr(pMem+1, (char*)sqlite3OpcodeName(pOp->opcode),
  74742. -1, SQLITE_UTF8, SQLITE_STATIC);
  74743. sqlite3VdbeMemSetInt64(pMem+2, pOp->p1);
  74744. sqlite3VdbeMemSetInt64(pMem+3, pOp->p2);
  74745. sqlite3VdbeMemSetInt64(pMem+4, pOp->p3);
  74746. /* pMem+5 for p4 is done last */
  74747. sqlite3VdbeMemSetInt64(pMem+6, pOp->p5);
  74748. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  74749. {
  74750. char *zCom = sqlite3VdbeDisplayComment(db, pOp, zP4);
  74751. sqlite3VdbeMemSetStr(pMem+7, zCom, -1, SQLITE_UTF8, sqlite3_free);
  74752. }
  74753. #else
  74754. sqlite3VdbeMemSetNull(pMem+7);
  74755. #endif
  74756. sqlite3VdbeMemSetStr(pMem+5, zP4, -1, SQLITE_UTF8, sqlite3_free);
  74757. p->nResColumn = 8;
  74758. }
  74759. p->pResultSet = pMem;
  74760. if( db->mallocFailed ){
  74761. p->rc = SQLITE_NOMEM;
  74762. rc = SQLITE_ERROR;
  74763. }else{
  74764. p->rc = SQLITE_OK;
  74765. rc = SQLITE_ROW;
  74766. }
  74767. }
  74768. }
  74769. return rc;
  74770. }
  74771. #endif /* SQLITE_OMIT_EXPLAIN */
  74772. #ifdef SQLITE_DEBUG
  74773. /*
  74774. ** Print the SQL that was used to generate a VDBE program.
  74775. */
  74776. SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){
  74777. const char *z = 0;
  74778. if( p->zSql ){
  74779. z = p->zSql;
  74780. }else if( p->nOp>=1 ){
  74781. const VdbeOp *pOp = &p->aOp[0];
  74782. if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
  74783. z = pOp->p4.z;
  74784. while( sqlite3Isspace(*z) ) z++;
  74785. }
  74786. }
  74787. if( z ) printf("SQL: [%s]\n", z);
  74788. }
  74789. #endif
  74790. #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
  74791. /*
  74792. ** Print an IOTRACE message showing SQL content.
  74793. */
  74794. SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){
  74795. int nOp = p->nOp;
  74796. VdbeOp *pOp;
  74797. if( sqlite3IoTrace==0 ) return;
  74798. if( nOp<1 ) return;
  74799. pOp = &p->aOp[0];
  74800. if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
  74801. int i, j;
  74802. char z[1000];
  74803. sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
  74804. for(i=0; sqlite3Isspace(z[i]); i++){}
  74805. for(j=0; z[i]; i++){
  74806. if( sqlite3Isspace(z[i]) ){
  74807. if( z[i-1]!=' ' ){
  74808. z[j++] = ' ';
  74809. }
  74810. }else{
  74811. z[j++] = z[i];
  74812. }
  74813. }
  74814. z[j] = 0;
  74815. sqlite3IoTrace("SQL %s\n", z);
  74816. }
  74817. }
  74818. #endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
  74819. /* An instance of this object describes bulk memory available for use
  74820. ** by subcomponents of a prepared statement. Space is allocated out
  74821. ** of a ReusableSpace object by the allocSpace() routine below.
  74822. */
  74823. struct ReusableSpace {
  74824. u8 *pSpace; /* Available memory */
  74825. sqlite3_int64 nFree; /* Bytes of available memory */
  74826. sqlite3_int64 nNeeded; /* Total bytes that could not be allocated */
  74827. };
  74828. /* Try to allocate nByte bytes of 8-byte aligned bulk memory for pBuf
  74829. ** from the ReusableSpace object. Return a pointer to the allocated
  74830. ** memory on success. If insufficient memory is available in the
  74831. ** ReusableSpace object, increase the ReusableSpace.nNeeded
  74832. ** value by the amount needed and return NULL.
  74833. **
  74834. ** If pBuf is not initially NULL, that means that the memory has already
  74835. ** been allocated by a prior call to this routine, so just return a copy
  74836. ** of pBuf and leave ReusableSpace unchanged.
  74837. **
  74838. ** This allocator is employed to repurpose unused slots at the end of the
  74839. ** opcode array of prepared state for other memory needs of the prepared
  74840. ** statement.
  74841. */
  74842. static void *allocSpace(
  74843. struct ReusableSpace *p, /* Bulk memory available for allocation */
  74844. void *pBuf, /* Pointer to a prior allocation */
  74845. sqlite3_int64 nByte /* Bytes of memory needed */
  74846. ){
  74847. assert( EIGHT_BYTE_ALIGNMENT(p->pSpace) );
  74848. if( pBuf==0 ){
  74849. nByte = ROUND8(nByte);
  74850. if( nByte <= p->nFree ){
  74851. p->nFree -= nByte;
  74852. pBuf = &p->pSpace[p->nFree];
  74853. }else{
  74854. p->nNeeded += nByte;
  74855. }
  74856. }
  74857. assert( EIGHT_BYTE_ALIGNMENT(pBuf) );
  74858. return pBuf;
  74859. }
  74860. /*
  74861. ** Rewind the VDBE back to the beginning in preparation for
  74862. ** running it.
  74863. */
  74864. SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe *p){
  74865. #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
  74866. int i;
  74867. #endif
  74868. assert( p!=0 );
  74869. assert( p->magic==VDBE_MAGIC_INIT || p->magic==VDBE_MAGIC_RESET );
  74870. /* There should be at least one opcode.
  74871. */
  74872. assert( p->nOp>0 );
  74873. /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
  74874. p->magic = VDBE_MAGIC_RUN;
  74875. #ifdef SQLITE_DEBUG
  74876. for(i=0; i<p->nMem; i++){
  74877. assert( p->aMem[i].db==p->db );
  74878. }
  74879. #endif
  74880. p->pc = -1;
  74881. p->rc = SQLITE_OK;
  74882. p->errorAction = OE_Abort;
  74883. p->nChange = 0;
  74884. p->cacheCtr = 1;
  74885. p->minWriteFileFormat = 255;
  74886. p->iStatement = 0;
  74887. p->nFkConstraint = 0;
  74888. #ifdef VDBE_PROFILE
  74889. for(i=0; i<p->nOp; i++){
  74890. p->aOp[i].cnt = 0;
  74891. p->aOp[i].cycles = 0;
  74892. }
  74893. #endif
  74894. }
  74895. /*
  74896. ** Prepare a virtual machine for execution for the first time after
  74897. ** creating the virtual machine. This involves things such
  74898. ** as allocating registers and initializing the program counter.
  74899. ** After the VDBE has be prepped, it can be executed by one or more
  74900. ** calls to sqlite3VdbeExec().
  74901. **
  74902. ** This function may be called exactly once on each virtual machine.
  74903. ** After this routine is called the VM has been "packaged" and is ready
  74904. ** to run. After this routine is called, further calls to
  74905. ** sqlite3VdbeAddOp() functions are prohibited. This routine disconnects
  74906. ** the Vdbe from the Parse object that helped generate it so that the
  74907. ** the Vdbe becomes an independent entity and the Parse object can be
  74908. ** destroyed.
  74909. **
  74910. ** Use the sqlite3VdbeRewind() procedure to restore a virtual machine back
  74911. ** to its initial state after it has been run.
  74912. */
  74913. SQLITE_PRIVATE void sqlite3VdbeMakeReady(
  74914. Vdbe *p, /* The VDBE */
  74915. Parse *pParse /* Parsing context */
  74916. ){
  74917. sqlite3 *db; /* The database connection */
  74918. int nVar; /* Number of parameters */
  74919. int nMem; /* Number of VM memory registers */
  74920. int nCursor; /* Number of cursors required */
  74921. int nArg; /* Number of arguments in subprograms */
  74922. int n; /* Loop counter */
  74923. struct ReusableSpace x; /* Reusable bulk memory */
  74924. assert( p!=0 );
  74925. assert( p->nOp>0 );
  74926. assert( pParse!=0 );
  74927. assert( p->magic==VDBE_MAGIC_INIT );
  74928. assert( pParse==p->pParse );
  74929. db = p->db;
  74930. assert( db->mallocFailed==0 );
  74931. nVar = pParse->nVar;
  74932. nMem = pParse->nMem;
  74933. nCursor = pParse->nTab;
  74934. nArg = pParse->nMaxArg;
  74935. /* Each cursor uses a memory cell. The first cursor (cursor 0) can
  74936. ** use aMem[0] which is not otherwise used by the VDBE program. Allocate
  74937. ** space at the end of aMem[] for cursors 1 and greater.
  74938. ** See also: allocateCursor().
  74939. */
  74940. nMem += nCursor;
  74941. if( nCursor==0 && nMem>0 ) nMem++; /* Space for aMem[0] even if not used */
  74942. /* Figure out how much reusable memory is available at the end of the
  74943. ** opcode array. This extra memory will be reallocated for other elements
  74944. ** of the prepared statement.
  74945. */
  74946. n = ROUND8(sizeof(Op)*p->nOp); /* Bytes of opcode memory used */
  74947. x.pSpace = &((u8*)p->aOp)[n]; /* Unused opcode memory */
  74948. assert( EIGHT_BYTE_ALIGNMENT(x.pSpace) );
  74949. x.nFree = ROUNDDOWN8(pParse->szOpAlloc - n); /* Bytes of unused memory */
  74950. assert( x.nFree>=0 );
  74951. assert( EIGHT_BYTE_ALIGNMENT(&x.pSpace[x.nFree]) );
  74952. resolveP2Values(p, &nArg);
  74953. p->usesStmtJournal = (u8)(pParse->isMultiWrite && pParse->mayAbort);
  74954. if( pParse->explain ){
  74955. static const char * const azColName[] = {
  74956. "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment",
  74957. "id", "parent", "notused", "detail"
  74958. };
  74959. int iFirst, mx, i;
  74960. if( nMem<10 ) nMem = 10;
  74961. p->explain = pParse->explain;
  74962. if( pParse->explain==2 ){
  74963. sqlite3VdbeSetNumCols(p, 4);
  74964. iFirst = 8;
  74965. mx = 12;
  74966. }else{
  74967. sqlite3VdbeSetNumCols(p, 8);
  74968. iFirst = 0;
  74969. mx = 8;
  74970. }
  74971. for(i=iFirst; i<mx; i++){
  74972. sqlite3VdbeSetColName(p, i-iFirst, COLNAME_NAME,
  74973. azColName[i], SQLITE_STATIC);
  74974. }
  74975. }
  74976. p->expired = 0;
  74977. /* Memory for registers, parameters, cursor, etc, is allocated in one or two
  74978. ** passes. On the first pass, we try to reuse unused memory at the
  74979. ** end of the opcode array. If we are unable to satisfy all memory
  74980. ** requirements by reusing the opcode array tail, then the second
  74981. ** pass will fill in the remainder using a fresh memory allocation.
  74982. **
  74983. ** This two-pass approach that reuses as much memory as possible from
  74984. ** the leftover memory at the end of the opcode array. This can significantly
  74985. ** reduce the amount of memory held by a prepared statement.
  74986. */
  74987. x.nNeeded = 0;
  74988. p->aMem = allocSpace(&x, 0, nMem*sizeof(Mem));
  74989. p->aVar = allocSpace(&x, 0, nVar*sizeof(Mem));
  74990. p->apArg = allocSpace(&x, 0, nArg*sizeof(Mem*));
  74991. p->apCsr = allocSpace(&x, 0, nCursor*sizeof(VdbeCursor*));
  74992. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  74993. p->anExec = allocSpace(&x, 0, p->nOp*sizeof(i64));
  74994. #endif
  74995. if( x.nNeeded ){
  74996. x.pSpace = p->pFree = sqlite3DbMallocRawNN(db, x.nNeeded);
  74997. x.nFree = x.nNeeded;
  74998. if( !db->mallocFailed ){
  74999. p->aMem = allocSpace(&x, p->aMem, nMem*sizeof(Mem));
  75000. p->aVar = allocSpace(&x, p->aVar, nVar*sizeof(Mem));
  75001. p->apArg = allocSpace(&x, p->apArg, nArg*sizeof(Mem*));
  75002. p->apCsr = allocSpace(&x, p->apCsr, nCursor*sizeof(VdbeCursor*));
  75003. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  75004. p->anExec = allocSpace(&x, p->anExec, p->nOp*sizeof(i64));
  75005. #endif
  75006. }
  75007. }
  75008. p->pVList = pParse->pVList;
  75009. pParse->pVList = 0;
  75010. if( db->mallocFailed ){
  75011. p->nVar = 0;
  75012. p->nCursor = 0;
  75013. p->nMem = 0;
  75014. }else{
  75015. p->nCursor = nCursor;
  75016. p->nVar = (ynVar)nVar;
  75017. initMemArray(p->aVar, nVar, db, MEM_Null);
  75018. p->nMem = nMem;
  75019. initMemArray(p->aMem, nMem, db, MEM_Undefined);
  75020. memset(p->apCsr, 0, nCursor*sizeof(VdbeCursor*));
  75021. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  75022. memset(p->anExec, 0, p->nOp*sizeof(i64));
  75023. #endif
  75024. }
  75025. sqlite3VdbeRewind(p);
  75026. }
  75027. /*
  75028. ** Close a VDBE cursor and release all the resources that cursor
  75029. ** happens to hold.
  75030. */
  75031. SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
  75032. if( pCx==0 ){
  75033. return;
  75034. }
  75035. assert( pCx->pBtx==0 || pCx->eCurType==CURTYPE_BTREE );
  75036. switch( pCx->eCurType ){
  75037. case CURTYPE_SORTER: {
  75038. sqlite3VdbeSorterClose(p->db, pCx);
  75039. break;
  75040. }
  75041. case CURTYPE_BTREE: {
  75042. if( pCx->isEphemeral ){
  75043. if( pCx->pBtx ) sqlite3BtreeClose(pCx->pBtx);
  75044. /* The pCx->pCursor will be close automatically, if it exists, by
  75045. ** the call above. */
  75046. }else{
  75047. assert( pCx->uc.pCursor!=0 );
  75048. sqlite3BtreeCloseCursor(pCx->uc.pCursor);
  75049. }
  75050. break;
  75051. }
  75052. #ifndef SQLITE_OMIT_VIRTUALTABLE
  75053. case CURTYPE_VTAB: {
  75054. sqlite3_vtab_cursor *pVCur = pCx->uc.pVCur;
  75055. const sqlite3_module *pModule = pVCur->pVtab->pModule;
  75056. assert( pVCur->pVtab->nRef>0 );
  75057. pVCur->pVtab->nRef--;
  75058. pModule->xClose(pVCur);
  75059. break;
  75060. }
  75061. #endif
  75062. }
  75063. }
  75064. /*
  75065. ** Close all cursors in the current frame.
  75066. */
  75067. static void closeCursorsInFrame(Vdbe *p){
  75068. if( p->apCsr ){
  75069. int i;
  75070. for(i=0; i<p->nCursor; i++){
  75071. VdbeCursor *pC = p->apCsr[i];
  75072. if( pC ){
  75073. sqlite3VdbeFreeCursor(p, pC);
  75074. p->apCsr[i] = 0;
  75075. }
  75076. }
  75077. }
  75078. }
  75079. /*
  75080. ** Copy the values stored in the VdbeFrame structure to its Vdbe. This
  75081. ** is used, for example, when a trigger sub-program is halted to restore
  75082. ** control to the main program.
  75083. */
  75084. SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
  75085. Vdbe *v = pFrame->v;
  75086. closeCursorsInFrame(v);
  75087. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  75088. v->anExec = pFrame->anExec;
  75089. #endif
  75090. v->aOp = pFrame->aOp;
  75091. v->nOp = pFrame->nOp;
  75092. v->aMem = pFrame->aMem;
  75093. v->nMem = pFrame->nMem;
  75094. v->apCsr = pFrame->apCsr;
  75095. v->nCursor = pFrame->nCursor;
  75096. v->db->lastRowid = pFrame->lastRowid;
  75097. v->nChange = pFrame->nChange;
  75098. v->db->nChange = pFrame->nDbChange;
  75099. sqlite3VdbeDeleteAuxData(v->db, &v->pAuxData, -1, 0);
  75100. v->pAuxData = pFrame->pAuxData;
  75101. pFrame->pAuxData = 0;
  75102. return pFrame->pc;
  75103. }
  75104. /*
  75105. ** Close all cursors.
  75106. **
  75107. ** Also release any dynamic memory held by the VM in the Vdbe.aMem memory
  75108. ** cell array. This is necessary as the memory cell array may contain
  75109. ** pointers to VdbeFrame objects, which may in turn contain pointers to
  75110. ** open cursors.
  75111. */
  75112. static void closeAllCursors(Vdbe *p){
  75113. if( p->pFrame ){
  75114. VdbeFrame *pFrame;
  75115. for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
  75116. sqlite3VdbeFrameRestore(pFrame);
  75117. p->pFrame = 0;
  75118. p->nFrame = 0;
  75119. }
  75120. assert( p->nFrame==0 );
  75121. closeCursorsInFrame(p);
  75122. if( p->aMem ){
  75123. releaseMemArray(p->aMem, p->nMem);
  75124. }
  75125. while( p->pDelFrame ){
  75126. VdbeFrame *pDel = p->pDelFrame;
  75127. p->pDelFrame = pDel->pParent;
  75128. sqlite3VdbeFrameDelete(pDel);
  75129. }
  75130. /* Delete any auxdata allocations made by the VM */
  75131. if( p->pAuxData ) sqlite3VdbeDeleteAuxData(p->db, &p->pAuxData, -1, 0);
  75132. assert( p->pAuxData==0 );
  75133. }
  75134. /*
  75135. ** Set the number of result columns that will be returned by this SQL
  75136. ** statement. This is now set at compile time, rather than during
  75137. ** execution of the vdbe program so that sqlite3_column_count() can
  75138. ** be called on an SQL statement before sqlite3_step().
  75139. */
  75140. SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
  75141. int n;
  75142. sqlite3 *db = p->db;
  75143. if( p->nResColumn ){
  75144. releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
  75145. sqlite3DbFree(db, p->aColName);
  75146. }
  75147. n = nResColumn*COLNAME_N;
  75148. p->nResColumn = (u16)nResColumn;
  75149. p->aColName = (Mem*)sqlite3DbMallocRawNN(db, sizeof(Mem)*n );
  75150. if( p->aColName==0 ) return;
  75151. initMemArray(p->aColName, n, db, MEM_Null);
  75152. }
  75153. /*
  75154. ** Set the name of the idx'th column to be returned by the SQL statement.
  75155. ** zName must be a pointer to a nul terminated string.
  75156. **
  75157. ** This call must be made after a call to sqlite3VdbeSetNumCols().
  75158. **
  75159. ** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
  75160. ** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
  75161. ** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
  75162. */
  75163. SQLITE_PRIVATE int sqlite3VdbeSetColName(
  75164. Vdbe *p, /* Vdbe being configured */
  75165. int idx, /* Index of column zName applies to */
  75166. int var, /* One of the COLNAME_* constants */
  75167. const char *zName, /* Pointer to buffer containing name */
  75168. void (*xDel)(void*) /* Memory management strategy for zName */
  75169. ){
  75170. int rc;
  75171. Mem *pColName;
  75172. assert( idx<p->nResColumn );
  75173. assert( var<COLNAME_N );
  75174. if( p->db->mallocFailed ){
  75175. assert( !zName || xDel!=SQLITE_DYNAMIC );
  75176. return SQLITE_NOMEM_BKPT;
  75177. }
  75178. assert( p->aColName!=0 );
  75179. pColName = &(p->aColName[idx+var*p->nResColumn]);
  75180. rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
  75181. assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
  75182. return rc;
  75183. }
  75184. /*
  75185. ** A read or write transaction may or may not be active on database handle
  75186. ** db. If a transaction is active, commit it. If there is a
  75187. ** write-transaction spanning more than one database file, this routine
  75188. ** takes care of the master journal trickery.
  75189. */
  75190. static int vdbeCommit(sqlite3 *db, Vdbe *p){
  75191. int i;
  75192. int nTrans = 0; /* Number of databases with an active write-transaction
  75193. ** that are candidates for a two-phase commit using a
  75194. ** master-journal */
  75195. int rc = SQLITE_OK;
  75196. int needXcommit = 0;
  75197. #ifdef SQLITE_OMIT_VIRTUALTABLE
  75198. /* With this option, sqlite3VtabSync() is defined to be simply
  75199. ** SQLITE_OK so p is not used.
  75200. */
  75201. UNUSED_PARAMETER(p);
  75202. #endif
  75203. /* Before doing anything else, call the xSync() callback for any
  75204. ** virtual module tables written in this transaction. This has to
  75205. ** be done before determining whether a master journal file is
  75206. ** required, as an xSync() callback may add an attached database
  75207. ** to the transaction.
  75208. */
  75209. rc = sqlite3VtabSync(db, p);
  75210. /* This loop determines (a) if the commit hook should be invoked and
  75211. ** (b) how many database files have open write transactions, not
  75212. ** including the temp database. (b) is important because if more than
  75213. ** one database file has an open write transaction, a master journal
  75214. ** file is required for an atomic commit.
  75215. */
  75216. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  75217. Btree *pBt = db->aDb[i].pBt;
  75218. if( sqlite3BtreeIsInTrans(pBt) ){
  75219. /* Whether or not a database might need a master journal depends upon
  75220. ** its journal mode (among other things). This matrix determines which
  75221. ** journal modes use a master journal and which do not */
  75222. static const u8 aMJNeeded[] = {
  75223. /* DELETE */ 1,
  75224. /* PERSIST */ 1,
  75225. /* OFF */ 0,
  75226. /* TRUNCATE */ 1,
  75227. /* MEMORY */ 0,
  75228. /* WAL */ 0
  75229. };
  75230. Pager *pPager; /* Pager associated with pBt */
  75231. needXcommit = 1;
  75232. sqlite3BtreeEnter(pBt);
  75233. pPager = sqlite3BtreePager(pBt);
  75234. if( db->aDb[i].safety_level!=PAGER_SYNCHRONOUS_OFF
  75235. && aMJNeeded[sqlite3PagerGetJournalMode(pPager)]
  75236. && sqlite3PagerIsMemdb(pPager)==0
  75237. ){
  75238. assert( i!=1 );
  75239. nTrans++;
  75240. }
  75241. rc = sqlite3PagerExclusiveLock(pPager);
  75242. sqlite3BtreeLeave(pBt);
  75243. }
  75244. }
  75245. if( rc!=SQLITE_OK ){
  75246. return rc;
  75247. }
  75248. /* If there are any write-transactions at all, invoke the commit hook */
  75249. if( needXcommit && db->xCommitCallback ){
  75250. rc = db->xCommitCallback(db->pCommitArg);
  75251. if( rc ){
  75252. return SQLITE_CONSTRAINT_COMMITHOOK;
  75253. }
  75254. }
  75255. /* The simple case - no more than one database file (not counting the
  75256. ** TEMP database) has a transaction active. There is no need for the
  75257. ** master-journal.
  75258. **
  75259. ** If the return value of sqlite3BtreeGetFilename() is a zero length
  75260. ** string, it means the main database is :memory: or a temp file. In
  75261. ** that case we do not support atomic multi-file commits, so use the
  75262. ** simple case then too.
  75263. */
  75264. if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
  75265. || nTrans<=1
  75266. ){
  75267. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  75268. Btree *pBt = db->aDb[i].pBt;
  75269. if( pBt ){
  75270. rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
  75271. }
  75272. }
  75273. /* Do the commit only if all databases successfully complete phase 1.
  75274. ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
  75275. ** IO error while deleting or truncating a journal file. It is unlikely,
  75276. ** but could happen. In this case abandon processing and return the error.
  75277. */
  75278. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  75279. Btree *pBt = db->aDb[i].pBt;
  75280. if( pBt ){
  75281. rc = sqlite3BtreeCommitPhaseTwo(pBt, 0);
  75282. }
  75283. }
  75284. if( rc==SQLITE_OK ){
  75285. sqlite3VtabCommit(db);
  75286. }
  75287. }
  75288. /* The complex case - There is a multi-file write-transaction active.
  75289. ** This requires a master journal file to ensure the transaction is
  75290. ** committed atomically.
  75291. */
  75292. #ifndef SQLITE_OMIT_DISKIO
  75293. else{
  75294. sqlite3_vfs *pVfs = db->pVfs;
  75295. char *zMaster = 0; /* File-name for the master journal */
  75296. char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
  75297. sqlite3_file *pMaster = 0;
  75298. i64 offset = 0;
  75299. int res;
  75300. int retryCount = 0;
  75301. int nMainFile;
  75302. /* Select a master journal file name */
  75303. nMainFile = sqlite3Strlen30(zMainFile);
  75304. zMaster = sqlite3MPrintf(db, "%.4c%s%.16c", 0,zMainFile,0);
  75305. if( zMaster==0 ) return SQLITE_NOMEM_BKPT;
  75306. zMaster += 4;
  75307. do {
  75308. u32 iRandom;
  75309. if( retryCount ){
  75310. if( retryCount>100 ){
  75311. sqlite3_log(SQLITE_FULL, "MJ delete: %s", zMaster);
  75312. sqlite3OsDelete(pVfs, zMaster, 0);
  75313. break;
  75314. }else if( retryCount==1 ){
  75315. sqlite3_log(SQLITE_FULL, "MJ collide: %s", zMaster);
  75316. }
  75317. }
  75318. retryCount++;
  75319. sqlite3_randomness(sizeof(iRandom), &iRandom);
  75320. sqlite3_snprintf(13, &zMaster[nMainFile], "-mj%06X9%02X",
  75321. (iRandom>>8)&0xffffff, iRandom&0xff);
  75322. /* The antipenultimate character of the master journal name must
  75323. ** be "9" to avoid name collisions when using 8+3 filenames. */
  75324. assert( zMaster[sqlite3Strlen30(zMaster)-3]=='9' );
  75325. sqlite3FileSuffix3(zMainFile, zMaster);
  75326. rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
  75327. }while( rc==SQLITE_OK && res );
  75328. if( rc==SQLITE_OK ){
  75329. /* Open the master journal. */
  75330. rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster,
  75331. SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
  75332. SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
  75333. );
  75334. }
  75335. if( rc!=SQLITE_OK ){
  75336. sqlite3DbFree(db, zMaster-4);
  75337. return rc;
  75338. }
  75339. /* Write the name of each database file in the transaction into the new
  75340. ** master journal file. If an error occurs at this point close
  75341. ** and delete the master journal file. All the individual journal files
  75342. ** still have 'null' as the master journal pointer, so they will roll
  75343. ** back independently if a failure occurs.
  75344. */
  75345. for(i=0; i<db->nDb; i++){
  75346. Btree *pBt = db->aDb[i].pBt;
  75347. if( sqlite3BtreeIsInTrans(pBt) ){
  75348. char const *zFile = sqlite3BtreeGetJournalname(pBt);
  75349. if( zFile==0 ){
  75350. continue; /* Ignore TEMP and :memory: databases */
  75351. }
  75352. assert( zFile[0]!=0 );
  75353. rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
  75354. offset += sqlite3Strlen30(zFile)+1;
  75355. if( rc!=SQLITE_OK ){
  75356. sqlite3OsCloseFree(pMaster);
  75357. sqlite3OsDelete(pVfs, zMaster, 0);
  75358. sqlite3DbFree(db, zMaster-4);
  75359. return rc;
  75360. }
  75361. }
  75362. }
  75363. /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
  75364. ** flag is set this is not required.
  75365. */
  75366. if( 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
  75367. && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
  75368. ){
  75369. sqlite3OsCloseFree(pMaster);
  75370. sqlite3OsDelete(pVfs, zMaster, 0);
  75371. sqlite3DbFree(db, zMaster-4);
  75372. return rc;
  75373. }
  75374. /* Sync all the db files involved in the transaction. The same call
  75375. ** sets the master journal pointer in each individual journal. If
  75376. ** an error occurs here, do not delete the master journal file.
  75377. **
  75378. ** If the error occurs during the first call to
  75379. ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
  75380. ** master journal file will be orphaned. But we cannot delete it,
  75381. ** in case the master journal file name was written into the journal
  75382. ** file before the failure occurred.
  75383. */
  75384. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  75385. Btree *pBt = db->aDb[i].pBt;
  75386. if( pBt ){
  75387. rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
  75388. }
  75389. }
  75390. sqlite3OsCloseFree(pMaster);
  75391. assert( rc!=SQLITE_BUSY );
  75392. if( rc!=SQLITE_OK ){
  75393. sqlite3DbFree(db, zMaster-4);
  75394. return rc;
  75395. }
  75396. /* Delete the master journal file. This commits the transaction. After
  75397. ** doing this the directory is synced again before any individual
  75398. ** transaction files are deleted.
  75399. */
  75400. rc = sqlite3OsDelete(pVfs, zMaster, 1);
  75401. sqlite3DbFree(db, zMaster-4);
  75402. zMaster = 0;
  75403. if( rc ){
  75404. return rc;
  75405. }
  75406. /* All files and directories have already been synced, so the following
  75407. ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
  75408. ** deleting or truncating journals. If something goes wrong while
  75409. ** this is happening we don't really care. The integrity of the
  75410. ** transaction is already guaranteed, but some stray 'cold' journals
  75411. ** may be lying around. Returning an error code won't help matters.
  75412. */
  75413. disable_simulated_io_errors();
  75414. sqlite3BeginBenignMalloc();
  75415. for(i=0; i<db->nDb; i++){
  75416. Btree *pBt = db->aDb[i].pBt;
  75417. if( pBt ){
  75418. sqlite3BtreeCommitPhaseTwo(pBt, 1);
  75419. }
  75420. }
  75421. sqlite3EndBenignMalloc();
  75422. enable_simulated_io_errors();
  75423. sqlite3VtabCommit(db);
  75424. }
  75425. #endif
  75426. return rc;
  75427. }
  75428. /*
  75429. ** This routine checks that the sqlite3.nVdbeActive count variable
  75430. ** matches the number of vdbe's in the list sqlite3.pVdbe that are
  75431. ** currently active. An assertion fails if the two counts do not match.
  75432. ** This is an internal self-check only - it is not an essential processing
  75433. ** step.
  75434. **
  75435. ** This is a no-op if NDEBUG is defined.
  75436. */
  75437. #ifndef NDEBUG
  75438. static void checkActiveVdbeCnt(sqlite3 *db){
  75439. Vdbe *p;
  75440. int cnt = 0;
  75441. int nWrite = 0;
  75442. int nRead = 0;
  75443. p = db->pVdbe;
  75444. while( p ){
  75445. if( sqlite3_stmt_busy((sqlite3_stmt*)p) ){
  75446. cnt++;
  75447. if( p->readOnly==0 ) nWrite++;
  75448. if( p->bIsReader ) nRead++;
  75449. }
  75450. p = p->pNext;
  75451. }
  75452. assert( cnt==db->nVdbeActive );
  75453. assert( nWrite==db->nVdbeWrite );
  75454. assert( nRead==db->nVdbeRead );
  75455. }
  75456. #else
  75457. #define checkActiveVdbeCnt(x)
  75458. #endif
  75459. /*
  75460. ** If the Vdbe passed as the first argument opened a statement-transaction,
  75461. ** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
  75462. ** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
  75463. ** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the
  75464. ** statement transaction is committed.
  75465. **
  75466. ** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned.
  75467. ** Otherwise SQLITE_OK.
  75468. */
  75469. static SQLITE_NOINLINE int vdbeCloseStatement(Vdbe *p, int eOp){
  75470. sqlite3 *const db = p->db;
  75471. int rc = SQLITE_OK;
  75472. int i;
  75473. const int iSavepoint = p->iStatement-1;
  75474. assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
  75475. assert( db->nStatement>0 );
  75476. assert( p->iStatement==(db->nStatement+db->nSavepoint) );
  75477. for(i=0; i<db->nDb; i++){
  75478. int rc2 = SQLITE_OK;
  75479. Btree *pBt = db->aDb[i].pBt;
  75480. if( pBt ){
  75481. if( eOp==SAVEPOINT_ROLLBACK ){
  75482. rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
  75483. }
  75484. if( rc2==SQLITE_OK ){
  75485. rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
  75486. }
  75487. if( rc==SQLITE_OK ){
  75488. rc = rc2;
  75489. }
  75490. }
  75491. }
  75492. db->nStatement--;
  75493. p->iStatement = 0;
  75494. if( rc==SQLITE_OK ){
  75495. if( eOp==SAVEPOINT_ROLLBACK ){
  75496. rc = sqlite3VtabSavepoint(db, SAVEPOINT_ROLLBACK, iSavepoint);
  75497. }
  75498. if( rc==SQLITE_OK ){
  75499. rc = sqlite3VtabSavepoint(db, SAVEPOINT_RELEASE, iSavepoint);
  75500. }
  75501. }
  75502. /* If the statement transaction is being rolled back, also restore the
  75503. ** database handles deferred constraint counter to the value it had when
  75504. ** the statement transaction was opened. */
  75505. if( eOp==SAVEPOINT_ROLLBACK ){
  75506. db->nDeferredCons = p->nStmtDefCons;
  75507. db->nDeferredImmCons = p->nStmtDefImmCons;
  75508. }
  75509. return rc;
  75510. }
  75511. SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
  75512. if( p->db->nStatement && p->iStatement ){
  75513. return vdbeCloseStatement(p, eOp);
  75514. }
  75515. return SQLITE_OK;
  75516. }
  75517. /*
  75518. ** This function is called when a transaction opened by the database
  75519. ** handle associated with the VM passed as an argument is about to be
  75520. ** committed. If there are outstanding deferred foreign key constraint
  75521. ** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
  75522. **
  75523. ** If there are outstanding FK violations and this function returns
  75524. ** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT_FOREIGNKEY
  75525. ** and write an error message to it. Then return SQLITE_ERROR.
  75526. */
  75527. #ifndef SQLITE_OMIT_FOREIGN_KEY
  75528. SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
  75529. sqlite3 *db = p->db;
  75530. if( (deferred && (db->nDeferredCons+db->nDeferredImmCons)>0)
  75531. || (!deferred && p->nFkConstraint>0)
  75532. ){
  75533. p->rc = SQLITE_CONSTRAINT_FOREIGNKEY;
  75534. p->errorAction = OE_Abort;
  75535. sqlite3VdbeError(p, "FOREIGN KEY constraint failed");
  75536. return SQLITE_ERROR;
  75537. }
  75538. return SQLITE_OK;
  75539. }
  75540. #endif
  75541. /*
  75542. ** This routine is called the when a VDBE tries to halt. If the VDBE
  75543. ** has made changes and is in autocommit mode, then commit those
  75544. ** changes. If a rollback is needed, then do the rollback.
  75545. **
  75546. ** This routine is the only way to move the state of a VM from
  75547. ** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT. It is harmless to
  75548. ** call this on a VM that is in the SQLITE_MAGIC_HALT state.
  75549. **
  75550. ** Return an error code. If the commit could not complete because of
  75551. ** lock contention, return SQLITE_BUSY. If SQLITE_BUSY is returned, it
  75552. ** means the close did not happen and needs to be repeated.
  75553. */
  75554. SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
  75555. int rc; /* Used to store transient return codes */
  75556. sqlite3 *db = p->db;
  75557. /* This function contains the logic that determines if a statement or
  75558. ** transaction will be committed or rolled back as a result of the
  75559. ** execution of this virtual machine.
  75560. **
  75561. ** If any of the following errors occur:
  75562. **
  75563. ** SQLITE_NOMEM
  75564. ** SQLITE_IOERR
  75565. ** SQLITE_FULL
  75566. ** SQLITE_INTERRUPT
  75567. **
  75568. ** Then the internal cache might have been left in an inconsistent
  75569. ** state. We need to rollback the statement transaction, if there is
  75570. ** one, or the complete transaction if there is no statement transaction.
  75571. */
  75572. if( p->magic!=VDBE_MAGIC_RUN ){
  75573. return SQLITE_OK;
  75574. }
  75575. if( db->mallocFailed ){
  75576. p->rc = SQLITE_NOMEM_BKPT;
  75577. }
  75578. closeAllCursors(p);
  75579. checkActiveVdbeCnt(db);
  75580. /* No commit or rollback needed if the program never started or if the
  75581. ** SQL statement does not read or write a database file. */
  75582. if( p->pc>=0 && p->bIsReader ){
  75583. int mrc; /* Primary error code from p->rc */
  75584. int eStatementOp = 0;
  75585. int isSpecialError; /* Set to true if a 'special' error */
  75586. /* Lock all btrees used by the statement */
  75587. sqlite3VdbeEnter(p);
  75588. /* Check for one of the special errors */
  75589. mrc = p->rc & 0xff;
  75590. isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
  75591. || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
  75592. if( isSpecialError ){
  75593. /* If the query was read-only and the error code is SQLITE_INTERRUPT,
  75594. ** no rollback is necessary. Otherwise, at least a savepoint
  75595. ** transaction must be rolled back to restore the database to a
  75596. ** consistent state.
  75597. **
  75598. ** Even if the statement is read-only, it is important to perform
  75599. ** a statement or transaction rollback operation. If the error
  75600. ** occurred while writing to the journal, sub-journal or database
  75601. ** file as part of an effort to free up cache space (see function
  75602. ** pagerStress() in pager.c), the rollback is required to restore
  75603. ** the pager to a consistent state.
  75604. */
  75605. if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
  75606. if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
  75607. eStatementOp = SAVEPOINT_ROLLBACK;
  75608. }else{
  75609. /* We are forced to roll back the active transaction. Before doing
  75610. ** so, abort any other statements this handle currently has active.
  75611. */
  75612. sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
  75613. sqlite3CloseSavepoints(db);
  75614. db->autoCommit = 1;
  75615. p->nChange = 0;
  75616. }
  75617. }
  75618. }
  75619. /* Check for immediate foreign key violations. */
  75620. if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
  75621. sqlite3VdbeCheckFk(p, 0);
  75622. }
  75623. /* If the auto-commit flag is set and this is the only active writer
  75624. ** VM, then we do either a commit or rollback of the current transaction.
  75625. **
  75626. ** Note: This block also runs if one of the special errors handled
  75627. ** above has occurred.
  75628. */
  75629. if( !sqlite3VtabInSync(db)
  75630. && db->autoCommit
  75631. && db->nVdbeWrite==(p->readOnly==0)
  75632. ){
  75633. if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
  75634. rc = sqlite3VdbeCheckFk(p, 1);
  75635. if( rc!=SQLITE_OK ){
  75636. if( NEVER(p->readOnly) ){
  75637. sqlite3VdbeLeave(p);
  75638. return SQLITE_ERROR;
  75639. }
  75640. rc = SQLITE_CONSTRAINT_FOREIGNKEY;
  75641. }else{
  75642. /* The auto-commit flag is true, the vdbe program was successful
  75643. ** or hit an 'OR FAIL' constraint and there are no deferred foreign
  75644. ** key constraints to hold up the transaction. This means a commit
  75645. ** is required. */
  75646. rc = vdbeCommit(db, p);
  75647. }
  75648. if( rc==SQLITE_BUSY && p->readOnly ){
  75649. sqlite3VdbeLeave(p);
  75650. return SQLITE_BUSY;
  75651. }else if( rc!=SQLITE_OK ){
  75652. p->rc = rc;
  75653. sqlite3RollbackAll(db, SQLITE_OK);
  75654. p->nChange = 0;
  75655. }else{
  75656. db->nDeferredCons = 0;
  75657. db->nDeferredImmCons = 0;
  75658. db->flags &= ~(u64)SQLITE_DeferFKs;
  75659. sqlite3CommitInternalChanges(db);
  75660. }
  75661. }else{
  75662. sqlite3RollbackAll(db, SQLITE_OK);
  75663. p->nChange = 0;
  75664. }
  75665. db->nStatement = 0;
  75666. }else if( eStatementOp==0 ){
  75667. if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
  75668. eStatementOp = SAVEPOINT_RELEASE;
  75669. }else if( p->errorAction==OE_Abort ){
  75670. eStatementOp = SAVEPOINT_ROLLBACK;
  75671. }else{
  75672. sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
  75673. sqlite3CloseSavepoints(db);
  75674. db->autoCommit = 1;
  75675. p->nChange = 0;
  75676. }
  75677. }
  75678. /* If eStatementOp is non-zero, then a statement transaction needs to
  75679. ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
  75680. ** do so. If this operation returns an error, and the current statement
  75681. ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
  75682. ** current statement error code.
  75683. */
  75684. if( eStatementOp ){
  75685. rc = sqlite3VdbeCloseStatement(p, eStatementOp);
  75686. if( rc ){
  75687. if( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT ){
  75688. p->rc = rc;
  75689. sqlite3DbFree(db, p->zErrMsg);
  75690. p->zErrMsg = 0;
  75691. }
  75692. sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
  75693. sqlite3CloseSavepoints(db);
  75694. db->autoCommit = 1;
  75695. p->nChange = 0;
  75696. }
  75697. }
  75698. /* If this was an INSERT, UPDATE or DELETE and no statement transaction
  75699. ** has been rolled back, update the database connection change-counter.
  75700. */
  75701. if( p->changeCntOn ){
  75702. if( eStatementOp!=SAVEPOINT_ROLLBACK ){
  75703. sqlite3VdbeSetChanges(db, p->nChange);
  75704. }else{
  75705. sqlite3VdbeSetChanges(db, 0);
  75706. }
  75707. p->nChange = 0;
  75708. }
  75709. /* Release the locks */
  75710. sqlite3VdbeLeave(p);
  75711. }
  75712. /* We have successfully halted and closed the VM. Record this fact. */
  75713. if( p->pc>=0 ){
  75714. db->nVdbeActive--;
  75715. if( !p->readOnly ) db->nVdbeWrite--;
  75716. if( p->bIsReader ) db->nVdbeRead--;
  75717. assert( db->nVdbeActive>=db->nVdbeRead );
  75718. assert( db->nVdbeRead>=db->nVdbeWrite );
  75719. assert( db->nVdbeWrite>=0 );
  75720. }
  75721. p->magic = VDBE_MAGIC_HALT;
  75722. checkActiveVdbeCnt(db);
  75723. if( db->mallocFailed ){
  75724. p->rc = SQLITE_NOMEM_BKPT;
  75725. }
  75726. /* If the auto-commit flag is set to true, then any locks that were held
  75727. ** by connection db have now been released. Call sqlite3ConnectionUnlocked()
  75728. ** to invoke any required unlock-notify callbacks.
  75729. */
  75730. if( db->autoCommit ){
  75731. sqlite3ConnectionUnlocked(db);
  75732. }
  75733. assert( db->nVdbeActive>0 || db->autoCommit==0 || db->nStatement==0 );
  75734. return (p->rc==SQLITE_BUSY ? SQLITE_BUSY : SQLITE_OK);
  75735. }
  75736. /*
  75737. ** Each VDBE holds the result of the most recent sqlite3_step() call
  75738. ** in p->rc. This routine sets that result back to SQLITE_OK.
  75739. */
  75740. SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){
  75741. p->rc = SQLITE_OK;
  75742. }
  75743. /*
  75744. ** Copy the error code and error message belonging to the VDBE passed
  75745. ** as the first argument to its database handle (so that they will be
  75746. ** returned by calls to sqlite3_errcode() and sqlite3_errmsg()).
  75747. **
  75748. ** This function does not clear the VDBE error code or message, just
  75749. ** copies them to the database handle.
  75750. */
  75751. SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p){
  75752. sqlite3 *db = p->db;
  75753. int rc = p->rc;
  75754. if( p->zErrMsg ){
  75755. db->bBenignMalloc++;
  75756. sqlite3BeginBenignMalloc();
  75757. if( db->pErr==0 ) db->pErr = sqlite3ValueNew(db);
  75758. sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
  75759. sqlite3EndBenignMalloc();
  75760. db->bBenignMalloc--;
  75761. }else if( db->pErr ){
  75762. sqlite3ValueSetNull(db->pErr);
  75763. }
  75764. db->errCode = rc;
  75765. return rc;
  75766. }
  75767. #ifdef SQLITE_ENABLE_SQLLOG
  75768. /*
  75769. ** If an SQLITE_CONFIG_SQLLOG hook is registered and the VM has been run,
  75770. ** invoke it.
  75771. */
  75772. static void vdbeInvokeSqllog(Vdbe *v){
  75773. if( sqlite3GlobalConfig.xSqllog && v->rc==SQLITE_OK && v->zSql && v->pc>=0 ){
  75774. char *zExpanded = sqlite3VdbeExpandSql(v, v->zSql);
  75775. assert( v->db->init.busy==0 );
  75776. if( zExpanded ){
  75777. sqlite3GlobalConfig.xSqllog(
  75778. sqlite3GlobalConfig.pSqllogArg, v->db, zExpanded, 1
  75779. );
  75780. sqlite3DbFree(v->db, zExpanded);
  75781. }
  75782. }
  75783. }
  75784. #else
  75785. # define vdbeInvokeSqllog(x)
  75786. #endif
  75787. /*
  75788. ** Clean up a VDBE after execution but do not delete the VDBE just yet.
  75789. ** Write any error messages into *pzErrMsg. Return the result code.
  75790. **
  75791. ** After this routine is run, the VDBE should be ready to be executed
  75792. ** again.
  75793. **
  75794. ** To look at it another way, this routine resets the state of the
  75795. ** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
  75796. ** VDBE_MAGIC_INIT.
  75797. */
  75798. SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){
  75799. #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
  75800. int i;
  75801. #endif
  75802. sqlite3 *db;
  75803. db = p->db;
  75804. /* If the VM did not run to completion or if it encountered an
  75805. ** error, then it might not have been halted properly. So halt
  75806. ** it now.
  75807. */
  75808. sqlite3VdbeHalt(p);
  75809. /* If the VDBE has been run even partially, then transfer the error code
  75810. ** and error message from the VDBE into the main database structure. But
  75811. ** if the VDBE has just been set to run but has not actually executed any
  75812. ** instructions yet, leave the main database error information unchanged.
  75813. */
  75814. if( p->pc>=0 ){
  75815. vdbeInvokeSqllog(p);
  75816. sqlite3VdbeTransferError(p);
  75817. if( p->runOnlyOnce ) p->expired = 1;
  75818. }else if( p->rc && p->expired ){
  75819. /* The expired flag was set on the VDBE before the first call
  75820. ** to sqlite3_step(). For consistency (since sqlite3_step() was
  75821. ** called), set the database error in this case as well.
  75822. */
  75823. sqlite3ErrorWithMsg(db, p->rc, p->zErrMsg ? "%s" : 0, p->zErrMsg);
  75824. }
  75825. /* Reset register contents and reclaim error message memory.
  75826. */
  75827. #ifdef SQLITE_DEBUG
  75828. /* Execute assert() statements to ensure that the Vdbe.apCsr[] and
  75829. ** Vdbe.aMem[] arrays have already been cleaned up. */
  75830. if( p->apCsr ) for(i=0; i<p->nCursor; i++) assert( p->apCsr[i]==0 );
  75831. if( p->aMem ){
  75832. for(i=0; i<p->nMem; i++) assert( p->aMem[i].flags==MEM_Undefined );
  75833. }
  75834. #endif
  75835. sqlite3DbFree(db, p->zErrMsg);
  75836. p->zErrMsg = 0;
  75837. p->pResultSet = 0;
  75838. #ifdef SQLITE_DEBUG
  75839. p->nWrite = 0;
  75840. #endif
  75841. /* Save profiling information from this VDBE run.
  75842. */
  75843. #ifdef VDBE_PROFILE
  75844. {
  75845. FILE *out = fopen("vdbe_profile.out", "a");
  75846. if( out ){
  75847. fprintf(out, "---- ");
  75848. for(i=0; i<p->nOp; i++){
  75849. fprintf(out, "%02x", p->aOp[i].opcode);
  75850. }
  75851. fprintf(out, "\n");
  75852. if( p->zSql ){
  75853. char c, pc = 0;
  75854. fprintf(out, "-- ");
  75855. for(i=0; (c = p->zSql[i])!=0; i++){
  75856. if( pc=='\n' ) fprintf(out, "-- ");
  75857. putc(c, out);
  75858. pc = c;
  75859. }
  75860. if( pc!='\n' ) fprintf(out, "\n");
  75861. }
  75862. for(i=0; i<p->nOp; i++){
  75863. char zHdr[100];
  75864. sqlite3_snprintf(sizeof(zHdr), zHdr, "%6u %12llu %8llu ",
  75865. p->aOp[i].cnt,
  75866. p->aOp[i].cycles,
  75867. p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
  75868. );
  75869. fprintf(out, "%s", zHdr);
  75870. sqlite3VdbePrintOp(out, i, &p->aOp[i]);
  75871. }
  75872. fclose(out);
  75873. }
  75874. }
  75875. #endif
  75876. p->magic = VDBE_MAGIC_RESET;
  75877. return p->rc & db->errMask;
  75878. }
  75879. /*
  75880. ** Clean up and delete a VDBE after execution. Return an integer which is
  75881. ** the result code. Write any error message text into *pzErrMsg.
  75882. */
  75883. SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){
  75884. int rc = SQLITE_OK;
  75885. if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
  75886. rc = sqlite3VdbeReset(p);
  75887. assert( (rc & p->db->errMask)==rc );
  75888. }
  75889. sqlite3VdbeDelete(p);
  75890. return rc;
  75891. }
  75892. /*
  75893. ** If parameter iOp is less than zero, then invoke the destructor for
  75894. ** all auxiliary data pointers currently cached by the VM passed as
  75895. ** the first argument.
  75896. **
  75897. ** Or, if iOp is greater than or equal to zero, then the destructor is
  75898. ** only invoked for those auxiliary data pointers created by the user
  75899. ** function invoked by the OP_Function opcode at instruction iOp of
  75900. ** VM pVdbe, and only then if:
  75901. **
  75902. ** * the associated function parameter is the 32nd or later (counting
  75903. ** from left to right), or
  75904. **
  75905. ** * the corresponding bit in argument mask is clear (where the first
  75906. ** function parameter corresponds to bit 0 etc.).
  75907. */
  75908. SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(sqlite3 *db, AuxData **pp, int iOp, int mask){
  75909. while( *pp ){
  75910. AuxData *pAux = *pp;
  75911. if( (iOp<0)
  75912. || (pAux->iAuxOp==iOp
  75913. && pAux->iAuxArg>=0
  75914. && (pAux->iAuxArg>31 || !(mask & MASKBIT32(pAux->iAuxArg))))
  75915. ){
  75916. testcase( pAux->iAuxArg==31 );
  75917. if( pAux->xDeleteAux ){
  75918. pAux->xDeleteAux(pAux->pAux);
  75919. }
  75920. *pp = pAux->pNextAux;
  75921. sqlite3DbFree(db, pAux);
  75922. }else{
  75923. pp= &pAux->pNextAux;
  75924. }
  75925. }
  75926. }
  75927. /*
  75928. ** Free all memory associated with the Vdbe passed as the second argument,
  75929. ** except for object itself, which is preserved.
  75930. **
  75931. ** The difference between this function and sqlite3VdbeDelete() is that
  75932. ** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with
  75933. ** the database connection and frees the object itself.
  75934. */
  75935. SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3 *db, Vdbe *p){
  75936. SubProgram *pSub, *pNext;
  75937. assert( p->db==0 || p->db==db );
  75938. releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
  75939. for(pSub=p->pProgram; pSub; pSub=pNext){
  75940. pNext = pSub->pNext;
  75941. vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);
  75942. sqlite3DbFree(db, pSub);
  75943. }
  75944. if( p->magic!=VDBE_MAGIC_INIT ){
  75945. releaseMemArray(p->aVar, p->nVar);
  75946. sqlite3DbFree(db, p->pVList);
  75947. sqlite3DbFree(db, p->pFree);
  75948. }
  75949. vdbeFreeOpArray(db, p->aOp, p->nOp);
  75950. sqlite3DbFree(db, p->aColName);
  75951. sqlite3DbFree(db, p->zSql);
  75952. #ifdef SQLITE_ENABLE_NORMALIZE
  75953. sqlite3DbFree(db, p->zNormSql);
  75954. {
  75955. DblquoteStr *pThis, *pNext;
  75956. for(pThis=p->pDblStr; pThis; pThis=pNext){
  75957. pNext = pThis->pNextStr;
  75958. sqlite3DbFree(db, pThis);
  75959. }
  75960. }
  75961. #endif
  75962. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  75963. {
  75964. int i;
  75965. for(i=0; i<p->nScan; i++){
  75966. sqlite3DbFree(db, p->aScan[i].zName);
  75967. }
  75968. sqlite3DbFree(db, p->aScan);
  75969. }
  75970. #endif
  75971. }
  75972. /*
  75973. ** Delete an entire VDBE.
  75974. */
  75975. SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){
  75976. sqlite3 *db;
  75977. assert( p!=0 );
  75978. db = p->db;
  75979. assert( sqlite3_mutex_held(db->mutex) );
  75980. sqlite3VdbeClearObject(db, p);
  75981. if( p->pPrev ){
  75982. p->pPrev->pNext = p->pNext;
  75983. }else{
  75984. assert( db->pVdbe==p );
  75985. db->pVdbe = p->pNext;
  75986. }
  75987. if( p->pNext ){
  75988. p->pNext->pPrev = p->pPrev;
  75989. }
  75990. p->magic = VDBE_MAGIC_DEAD;
  75991. p->db = 0;
  75992. sqlite3DbFreeNN(db, p);
  75993. }
  75994. /*
  75995. ** The cursor "p" has a pending seek operation that has not yet been
  75996. ** carried out. Seek the cursor now. If an error occurs, return
  75997. ** the appropriate error code.
  75998. */
  75999. SQLITE_PRIVATE int SQLITE_NOINLINE sqlite3VdbeFinishMoveto(VdbeCursor *p){
  76000. int res, rc;
  76001. #ifdef SQLITE_TEST
  76002. extern int sqlite3_search_count;
  76003. #endif
  76004. assert( p->deferredMoveto );
  76005. assert( p->isTable );
  76006. assert( p->eCurType==CURTYPE_BTREE );
  76007. rc = sqlite3BtreeMovetoUnpacked(p->uc.pCursor, 0, p->movetoTarget, 0, &res);
  76008. if( rc ) return rc;
  76009. if( res!=0 ) return SQLITE_CORRUPT_BKPT;
  76010. #ifdef SQLITE_TEST
  76011. sqlite3_search_count++;
  76012. #endif
  76013. p->deferredMoveto = 0;
  76014. p->cacheStatus = CACHE_STALE;
  76015. return SQLITE_OK;
  76016. }
  76017. /*
  76018. ** Something has moved cursor "p" out of place. Maybe the row it was
  76019. ** pointed to was deleted out from under it. Or maybe the btree was
  76020. ** rebalanced. Whatever the cause, try to restore "p" to the place it
  76021. ** is supposed to be pointing. If the row was deleted out from under the
  76022. ** cursor, set the cursor to point to a NULL row.
  76023. */
  76024. static int SQLITE_NOINLINE handleMovedCursor(VdbeCursor *p){
  76025. int isDifferentRow, rc;
  76026. assert( p->eCurType==CURTYPE_BTREE );
  76027. assert( p->uc.pCursor!=0 );
  76028. assert( sqlite3BtreeCursorHasMoved(p->uc.pCursor) );
  76029. rc = sqlite3BtreeCursorRestore(p->uc.pCursor, &isDifferentRow);
  76030. p->cacheStatus = CACHE_STALE;
  76031. if( isDifferentRow ) p->nullRow = 1;
  76032. return rc;
  76033. }
  76034. /*
  76035. ** Check to ensure that the cursor is valid. Restore the cursor
  76036. ** if need be. Return any I/O error from the restore operation.
  76037. */
  76038. SQLITE_PRIVATE int sqlite3VdbeCursorRestore(VdbeCursor *p){
  76039. assert( p->eCurType==CURTYPE_BTREE );
  76040. if( sqlite3BtreeCursorHasMoved(p->uc.pCursor) ){
  76041. return handleMovedCursor(p);
  76042. }
  76043. return SQLITE_OK;
  76044. }
  76045. /*
  76046. ** Make sure the cursor p is ready to read or write the row to which it
  76047. ** was last positioned. Return an error code if an OOM fault or I/O error
  76048. ** prevents us from positioning the cursor to its correct position.
  76049. **
  76050. ** If a MoveTo operation is pending on the given cursor, then do that
  76051. ** MoveTo now. If no move is pending, check to see if the row has been
  76052. ** deleted out from under the cursor and if it has, mark the row as
  76053. ** a NULL row.
  76054. **
  76055. ** If the cursor is already pointing to the correct row and that row has
  76056. ** not been deleted out from under the cursor, then this routine is a no-op.
  76057. */
  76058. SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor **pp, int *piCol){
  76059. VdbeCursor *p = *pp;
  76060. assert( p->eCurType==CURTYPE_BTREE || p->eCurType==CURTYPE_PSEUDO );
  76061. if( p->deferredMoveto ){
  76062. int iMap;
  76063. if( p->aAltMap && (iMap = p->aAltMap[1+*piCol])>0 && !p->nullRow ){
  76064. *pp = p->pAltCursor;
  76065. *piCol = iMap - 1;
  76066. return SQLITE_OK;
  76067. }
  76068. return sqlite3VdbeFinishMoveto(p);
  76069. }
  76070. if( sqlite3BtreeCursorHasMoved(p->uc.pCursor) ){
  76071. return handleMovedCursor(p);
  76072. }
  76073. return SQLITE_OK;
  76074. }
  76075. /*
  76076. ** The following functions:
  76077. **
  76078. ** sqlite3VdbeSerialType()
  76079. ** sqlite3VdbeSerialTypeLen()
  76080. ** sqlite3VdbeSerialLen()
  76081. ** sqlite3VdbeSerialPut()
  76082. ** sqlite3VdbeSerialGet()
  76083. **
  76084. ** encapsulate the code that serializes values for storage in SQLite
  76085. ** data and index records. Each serialized value consists of a
  76086. ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
  76087. ** integer, stored as a varint.
  76088. **
  76089. ** In an SQLite index record, the serial type is stored directly before
  76090. ** the blob of data that it corresponds to. In a table record, all serial
  76091. ** types are stored at the start of the record, and the blobs of data at
  76092. ** the end. Hence these functions allow the caller to handle the
  76093. ** serial-type and data blob separately.
  76094. **
  76095. ** The following table describes the various storage classes for data:
  76096. **
  76097. ** serial type bytes of data type
  76098. ** -------------- --------------- ---------------
  76099. ** 0 0 NULL
  76100. ** 1 1 signed integer
  76101. ** 2 2 signed integer
  76102. ** 3 3 signed integer
  76103. ** 4 4 signed integer
  76104. ** 5 6 signed integer
  76105. ** 6 8 signed integer
  76106. ** 7 8 IEEE float
  76107. ** 8 0 Integer constant 0
  76108. ** 9 0 Integer constant 1
  76109. ** 10,11 reserved for expansion
  76110. ** N>=12 and even (N-12)/2 BLOB
  76111. ** N>=13 and odd (N-13)/2 text
  76112. **
  76113. ** The 8 and 9 types were added in 3.3.0, file format 4. Prior versions
  76114. ** of SQLite will not understand those serial types.
  76115. */
  76116. #if 0 /* Inlined into the OP_MakeRecord opcode */
  76117. /*
  76118. ** Return the serial-type for the value stored in pMem.
  76119. **
  76120. ** This routine might convert a large MEM_IntReal value into MEM_Real.
  76121. **
  76122. ** 2019-07-11: The primary user of this subroutine was the OP_MakeRecord
  76123. ** opcode in the byte-code engine. But by moving this routine in-line, we
  76124. ** can omit some redundant tests and make that opcode a lot faster. So
  76125. ** this routine is now only used by the STAT3 logic and STAT3 support has
  76126. ** ended. The code is kept here for historical reference only.
  76127. */
  76128. SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format, u32 *pLen){
  76129. int flags = pMem->flags;
  76130. u32 n;
  76131. assert( pLen!=0 );
  76132. if( flags&MEM_Null ){
  76133. *pLen = 0;
  76134. return 0;
  76135. }
  76136. if( flags&(MEM_Int|MEM_IntReal) ){
  76137. /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
  76138. # define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
  76139. i64 i = pMem->u.i;
  76140. u64 u;
  76141. testcase( flags & MEM_Int );
  76142. testcase( flags & MEM_IntReal );
  76143. if( i<0 ){
  76144. u = ~i;
  76145. }else{
  76146. u = i;
  76147. }
  76148. if( u<=127 ){
  76149. if( (i&1)==i && file_format>=4 ){
  76150. *pLen = 0;
  76151. return 8+(u32)u;
  76152. }else{
  76153. *pLen = 1;
  76154. return 1;
  76155. }
  76156. }
  76157. if( u<=32767 ){ *pLen = 2; return 2; }
  76158. if( u<=8388607 ){ *pLen = 3; return 3; }
  76159. if( u<=2147483647 ){ *pLen = 4; return 4; }
  76160. if( u<=MAX_6BYTE ){ *pLen = 6; return 5; }
  76161. *pLen = 8;
  76162. if( flags&MEM_IntReal ){
  76163. /* If the value is IntReal and is going to take up 8 bytes to store
  76164. ** as an integer, then we might as well make it an 8-byte floating
  76165. ** point value */
  76166. pMem->u.r = (double)pMem->u.i;
  76167. pMem->flags &= ~MEM_IntReal;
  76168. pMem->flags |= MEM_Real;
  76169. return 7;
  76170. }
  76171. return 6;
  76172. }
  76173. if( flags&MEM_Real ){
  76174. *pLen = 8;
  76175. return 7;
  76176. }
  76177. assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
  76178. assert( pMem->n>=0 );
  76179. n = (u32)pMem->n;
  76180. if( flags & MEM_Zero ){
  76181. n += pMem->u.nZero;
  76182. }
  76183. *pLen = n;
  76184. return ((n*2) + 12 + ((flags&MEM_Str)!=0));
  76185. }
  76186. #endif /* inlined into OP_MakeRecord */
  76187. /*
  76188. ** The sizes for serial types less than 128
  76189. */
  76190. static const u8 sqlite3SmallTypeSizes[] = {
  76191. /* 0 1 2 3 4 5 6 7 8 9 */
  76192. /* 0 */ 0, 1, 2, 3, 4, 6, 8, 8, 0, 0,
  76193. /* 10 */ 0, 0, 0, 0, 1, 1, 2, 2, 3, 3,
  76194. /* 20 */ 4, 4, 5, 5, 6, 6, 7, 7, 8, 8,
  76195. /* 30 */ 9, 9, 10, 10, 11, 11, 12, 12, 13, 13,
  76196. /* 40 */ 14, 14, 15, 15, 16, 16, 17, 17, 18, 18,
  76197. /* 50 */ 19, 19, 20, 20, 21, 21, 22, 22, 23, 23,
  76198. /* 60 */ 24, 24, 25, 25, 26, 26, 27, 27, 28, 28,
  76199. /* 70 */ 29, 29, 30, 30, 31, 31, 32, 32, 33, 33,
  76200. /* 80 */ 34, 34, 35, 35, 36, 36, 37, 37, 38, 38,
  76201. /* 90 */ 39, 39, 40, 40, 41, 41, 42, 42, 43, 43,
  76202. /* 100 */ 44, 44, 45, 45, 46, 46, 47, 47, 48, 48,
  76203. /* 110 */ 49, 49, 50, 50, 51, 51, 52, 52, 53, 53,
  76204. /* 120 */ 54, 54, 55, 55, 56, 56, 57, 57
  76205. };
  76206. /*
  76207. ** Return the length of the data corresponding to the supplied serial-type.
  76208. */
  76209. SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
  76210. if( serial_type>=128 ){
  76211. return (serial_type-12)/2;
  76212. }else{
  76213. assert( serial_type<12
  76214. || sqlite3SmallTypeSizes[serial_type]==(serial_type - 12)/2 );
  76215. return sqlite3SmallTypeSizes[serial_type];
  76216. }
  76217. }
  76218. SQLITE_PRIVATE u8 sqlite3VdbeOneByteSerialTypeLen(u8 serial_type){
  76219. assert( serial_type<128 );
  76220. return sqlite3SmallTypeSizes[serial_type];
  76221. }
  76222. /*
  76223. ** If we are on an architecture with mixed-endian floating
  76224. ** points (ex: ARM7) then swap the lower 4 bytes with the
  76225. ** upper 4 bytes. Return the result.
  76226. **
  76227. ** For most architectures, this is a no-op.
  76228. **
  76229. ** (later): It is reported to me that the mixed-endian problem
  76230. ** on ARM7 is an issue with GCC, not with the ARM7 chip. It seems
  76231. ** that early versions of GCC stored the two words of a 64-bit
  76232. ** float in the wrong order. And that error has been propagated
  76233. ** ever since. The blame is not necessarily with GCC, though.
  76234. ** GCC might have just copying the problem from a prior compiler.
  76235. ** I am also told that newer versions of GCC that follow a different
  76236. ** ABI get the byte order right.
  76237. **
  76238. ** Developers using SQLite on an ARM7 should compile and run their
  76239. ** application using -DSQLITE_DEBUG=1 at least once. With DEBUG
  76240. ** enabled, some asserts below will ensure that the byte order of
  76241. ** floating point values is correct.
  76242. **
  76243. ** (2007-08-30) Frank van Vugt has studied this problem closely
  76244. ** and has send his findings to the SQLite developers. Frank
  76245. ** writes that some Linux kernels offer floating point hardware
  76246. ** emulation that uses only 32-bit mantissas instead of a full
  76247. ** 48-bits as required by the IEEE standard. (This is the
  76248. ** CONFIG_FPE_FASTFPE option.) On such systems, floating point
  76249. ** byte swapping becomes very complicated. To avoid problems,
  76250. ** the necessary byte swapping is carried out using a 64-bit integer
  76251. ** rather than a 64-bit float. Frank assures us that the code here
  76252. ** works for him. We, the developers, have no way to independently
  76253. ** verify this, but Frank seems to know what he is talking about
  76254. ** so we trust him.
  76255. */
  76256. #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
  76257. static u64 floatSwap(u64 in){
  76258. union {
  76259. u64 r;
  76260. u32 i[2];
  76261. } u;
  76262. u32 t;
  76263. u.r = in;
  76264. t = u.i[0];
  76265. u.i[0] = u.i[1];
  76266. u.i[1] = t;
  76267. return u.r;
  76268. }
  76269. # define swapMixedEndianFloat(X) X = floatSwap(X)
  76270. #else
  76271. # define swapMixedEndianFloat(X)
  76272. #endif
  76273. /*
  76274. ** Write the serialized data blob for the value stored in pMem into
  76275. ** buf. It is assumed that the caller has allocated sufficient space.
  76276. ** Return the number of bytes written.
  76277. **
  76278. ** nBuf is the amount of space left in buf[]. The caller is responsible
  76279. ** for allocating enough space to buf[] to hold the entire field, exclusive
  76280. ** of the pMem->u.nZero bytes for a MEM_Zero value.
  76281. **
  76282. ** Return the number of bytes actually written into buf[]. The number
  76283. ** of bytes in the zero-filled tail is included in the return value only
  76284. ** if those bytes were zeroed in buf[].
  76285. */
  76286. SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, Mem *pMem, u32 serial_type){
  76287. u32 len;
  76288. /* Integer and Real */
  76289. if( serial_type<=7 && serial_type>0 ){
  76290. u64 v;
  76291. u32 i;
  76292. if( serial_type==7 ){
  76293. assert( sizeof(v)==sizeof(pMem->u.r) );
  76294. memcpy(&v, &pMem->u.r, sizeof(v));
  76295. swapMixedEndianFloat(v);
  76296. }else{
  76297. v = pMem->u.i;
  76298. }
  76299. len = i = sqlite3SmallTypeSizes[serial_type];
  76300. assert( i>0 );
  76301. do{
  76302. buf[--i] = (u8)(v&0xFF);
  76303. v >>= 8;
  76304. }while( i );
  76305. return len;
  76306. }
  76307. /* String or blob */
  76308. if( serial_type>=12 ){
  76309. assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
  76310. == (int)sqlite3VdbeSerialTypeLen(serial_type) );
  76311. len = pMem->n;
  76312. if( len>0 ) memcpy(buf, pMem->z, len);
  76313. return len;
  76314. }
  76315. /* NULL or constants 0 or 1 */
  76316. return 0;
  76317. }
  76318. /* Input "x" is a sequence of unsigned characters that represent a
  76319. ** big-endian integer. Return the equivalent native integer
  76320. */
  76321. #define ONE_BYTE_INT(x) ((i8)(x)[0])
  76322. #define TWO_BYTE_INT(x) (256*(i8)((x)[0])|(x)[1])
  76323. #define THREE_BYTE_INT(x) (65536*(i8)((x)[0])|((x)[1]<<8)|(x)[2])
  76324. #define FOUR_BYTE_UINT(x) (((u32)(x)[0]<<24)|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
  76325. #define FOUR_BYTE_INT(x) (16777216*(i8)((x)[0])|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
  76326. /*
  76327. ** Deserialize the data blob pointed to by buf as serial type serial_type
  76328. ** and store the result in pMem. Return the number of bytes read.
  76329. **
  76330. ** This function is implemented as two separate routines for performance.
  76331. ** The few cases that require local variables are broken out into a separate
  76332. ** routine so that in most cases the overhead of moving the stack pointer
  76333. ** is avoided.
  76334. */
  76335. static u32 serialGet(
  76336. const unsigned char *buf, /* Buffer to deserialize from */
  76337. u32 serial_type, /* Serial type to deserialize */
  76338. Mem *pMem /* Memory cell to write value into */
  76339. ){
  76340. u64 x = FOUR_BYTE_UINT(buf);
  76341. u32 y = FOUR_BYTE_UINT(buf+4);
  76342. x = (x<<32) + y;
  76343. if( serial_type==6 ){
  76344. /* EVIDENCE-OF: R-29851-52272 Value is a big-endian 64-bit
  76345. ** twos-complement integer. */
  76346. pMem->u.i = *(i64*)&x;
  76347. pMem->flags = MEM_Int;
  76348. testcase( pMem->u.i<0 );
  76349. }else{
  76350. /* EVIDENCE-OF: R-57343-49114 Value is a big-endian IEEE 754-2008 64-bit
  76351. ** floating point number. */
  76352. #if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
  76353. /* Verify that integers and floating point values use the same
  76354. ** byte order. Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
  76355. ** defined that 64-bit floating point values really are mixed
  76356. ** endian.
  76357. */
  76358. static const u64 t1 = ((u64)0x3ff00000)<<32;
  76359. static const double r1 = 1.0;
  76360. u64 t2 = t1;
  76361. swapMixedEndianFloat(t2);
  76362. assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
  76363. #endif
  76364. assert( sizeof(x)==8 && sizeof(pMem->u.r)==8 );
  76365. swapMixedEndianFloat(x);
  76366. memcpy(&pMem->u.r, &x, sizeof(x));
  76367. pMem->flags = IsNaN(x) ? MEM_Null : MEM_Real;
  76368. }
  76369. return 8;
  76370. }
  76371. SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(
  76372. const unsigned char *buf, /* Buffer to deserialize from */
  76373. u32 serial_type, /* Serial type to deserialize */
  76374. Mem *pMem /* Memory cell to write value into */
  76375. ){
  76376. switch( serial_type ){
  76377. case 10: { /* Internal use only: NULL with virtual table
  76378. ** UPDATE no-change flag set */
  76379. pMem->flags = MEM_Null|MEM_Zero;
  76380. pMem->n = 0;
  76381. pMem->u.nZero = 0;
  76382. break;
  76383. }
  76384. case 11: /* Reserved for future use */
  76385. case 0: { /* Null */
  76386. /* EVIDENCE-OF: R-24078-09375 Value is a NULL. */
  76387. pMem->flags = MEM_Null;
  76388. break;
  76389. }
  76390. case 1: {
  76391. /* EVIDENCE-OF: R-44885-25196 Value is an 8-bit twos-complement
  76392. ** integer. */
  76393. pMem->u.i = ONE_BYTE_INT(buf);
  76394. pMem->flags = MEM_Int;
  76395. testcase( pMem->u.i<0 );
  76396. return 1;
  76397. }
  76398. case 2: { /* 2-byte signed integer */
  76399. /* EVIDENCE-OF: R-49794-35026 Value is a big-endian 16-bit
  76400. ** twos-complement integer. */
  76401. pMem->u.i = TWO_BYTE_INT(buf);
  76402. pMem->flags = MEM_Int;
  76403. testcase( pMem->u.i<0 );
  76404. return 2;
  76405. }
  76406. case 3: { /* 3-byte signed integer */
  76407. /* EVIDENCE-OF: R-37839-54301 Value is a big-endian 24-bit
  76408. ** twos-complement integer. */
  76409. pMem->u.i = THREE_BYTE_INT(buf);
  76410. pMem->flags = MEM_Int;
  76411. testcase( pMem->u.i<0 );
  76412. return 3;
  76413. }
  76414. case 4: { /* 4-byte signed integer */
  76415. /* EVIDENCE-OF: R-01849-26079 Value is a big-endian 32-bit
  76416. ** twos-complement integer. */
  76417. pMem->u.i = FOUR_BYTE_INT(buf);
  76418. #ifdef __HP_cc
  76419. /* Work around a sign-extension bug in the HP compiler for HP/UX */
  76420. if( buf[0]&0x80 ) pMem->u.i |= 0xffffffff80000000LL;
  76421. #endif
  76422. pMem->flags = MEM_Int;
  76423. testcase( pMem->u.i<0 );
  76424. return 4;
  76425. }
  76426. case 5: { /* 6-byte signed integer */
  76427. /* EVIDENCE-OF: R-50385-09674 Value is a big-endian 48-bit
  76428. ** twos-complement integer. */
  76429. pMem->u.i = FOUR_BYTE_UINT(buf+2) + (((i64)1)<<32)*TWO_BYTE_INT(buf);
  76430. pMem->flags = MEM_Int;
  76431. testcase( pMem->u.i<0 );
  76432. return 6;
  76433. }
  76434. case 6: /* 8-byte signed integer */
  76435. case 7: { /* IEEE floating point */
  76436. /* These use local variables, so do them in a separate routine
  76437. ** to avoid having to move the frame pointer in the common case */
  76438. return serialGet(buf,serial_type,pMem);
  76439. }
  76440. case 8: /* Integer 0 */
  76441. case 9: { /* Integer 1 */
  76442. /* EVIDENCE-OF: R-12976-22893 Value is the integer 0. */
  76443. /* EVIDENCE-OF: R-18143-12121 Value is the integer 1. */
  76444. pMem->u.i = serial_type-8;
  76445. pMem->flags = MEM_Int;
  76446. return 0;
  76447. }
  76448. default: {
  76449. /* EVIDENCE-OF: R-14606-31564 Value is a BLOB that is (N-12)/2 bytes in
  76450. ** length.
  76451. ** EVIDENCE-OF: R-28401-00140 Value is a string in the text encoding and
  76452. ** (N-13)/2 bytes in length. */
  76453. static const u16 aFlag[] = { MEM_Blob|MEM_Ephem, MEM_Str|MEM_Ephem };
  76454. pMem->z = (char *)buf;
  76455. pMem->n = (serial_type-12)/2;
  76456. pMem->flags = aFlag[serial_type&1];
  76457. return pMem->n;
  76458. }
  76459. }
  76460. return 0;
  76461. }
  76462. /*
  76463. ** This routine is used to allocate sufficient space for an UnpackedRecord
  76464. ** structure large enough to be used with sqlite3VdbeRecordUnpack() if
  76465. ** the first argument is a pointer to KeyInfo structure pKeyInfo.
  76466. **
  76467. ** The space is either allocated using sqlite3DbMallocRaw() or from within
  76468. ** the unaligned buffer passed via the second and third arguments (presumably
  76469. ** stack space). If the former, then *ppFree is set to a pointer that should
  76470. ** be eventually freed by the caller using sqlite3DbFree(). Or, if the
  76471. ** allocation comes from the pSpace/szSpace buffer, *ppFree is set to NULL
  76472. ** before returning.
  76473. **
  76474. ** If an OOM error occurs, NULL is returned.
  76475. */
  76476. SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(
  76477. KeyInfo *pKeyInfo /* Description of the record */
  76478. ){
  76479. UnpackedRecord *p; /* Unpacked record to return */
  76480. int nByte; /* Number of bytes required for *p */
  76481. nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nKeyField+1);
  76482. p = (UnpackedRecord *)sqlite3DbMallocRaw(pKeyInfo->db, nByte);
  76483. if( !p ) return 0;
  76484. p->aMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
  76485. assert( pKeyInfo->aSortFlags!=0 );
  76486. p->pKeyInfo = pKeyInfo;
  76487. p->nField = pKeyInfo->nKeyField + 1;
  76488. return p;
  76489. }
  76490. /*
  76491. ** Given the nKey-byte encoding of a record in pKey[], populate the
  76492. ** UnpackedRecord structure indicated by the fourth argument with the
  76493. ** contents of the decoded record.
  76494. */
  76495. SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(
  76496. KeyInfo *pKeyInfo, /* Information about the record format */
  76497. int nKey, /* Size of the binary record */
  76498. const void *pKey, /* The binary record */
  76499. UnpackedRecord *p /* Populate this structure before returning. */
  76500. ){
  76501. const unsigned char *aKey = (const unsigned char *)pKey;
  76502. u32 d;
  76503. u32 idx; /* Offset in aKey[] to read from */
  76504. u16 u; /* Unsigned loop counter */
  76505. u32 szHdr;
  76506. Mem *pMem = p->aMem;
  76507. p->default_rc = 0;
  76508. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  76509. idx = getVarint32(aKey, szHdr);
  76510. d = szHdr;
  76511. u = 0;
  76512. while( idx<szHdr && d<=(u32)nKey ){
  76513. u32 serial_type;
  76514. idx += getVarint32(&aKey[idx], serial_type);
  76515. pMem->enc = pKeyInfo->enc;
  76516. pMem->db = pKeyInfo->db;
  76517. /* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */
  76518. pMem->szMalloc = 0;
  76519. pMem->z = 0;
  76520. d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
  76521. pMem++;
  76522. if( (++u)>=p->nField ) break;
  76523. }
  76524. if( d>(u32)nKey && u ){
  76525. assert( CORRUPT_DB );
  76526. /* In a corrupt record entry, the last pMem might have been set up using
  76527. ** uninitialized memory. Overwrite its value with NULL, to prevent
  76528. ** warnings from MSAN. */
  76529. sqlite3VdbeMemSetNull(pMem-1);
  76530. }
  76531. assert( u<=pKeyInfo->nKeyField + 1 );
  76532. p->nField = u;
  76533. }
  76534. #ifdef SQLITE_DEBUG
  76535. /*
  76536. ** This function compares two index or table record keys in the same way
  76537. ** as the sqlite3VdbeRecordCompare() routine. Unlike VdbeRecordCompare(),
  76538. ** this function deserializes and compares values using the
  76539. ** sqlite3VdbeSerialGet() and sqlite3MemCompare() functions. It is used
  76540. ** in assert() statements to ensure that the optimized code in
  76541. ** sqlite3VdbeRecordCompare() returns results with these two primitives.
  76542. **
  76543. ** Return true if the result of comparison is equivalent to desiredResult.
  76544. ** Return false if there is a disagreement.
  76545. */
  76546. static int vdbeRecordCompareDebug(
  76547. int nKey1, const void *pKey1, /* Left key */
  76548. const UnpackedRecord *pPKey2, /* Right key */
  76549. int desiredResult /* Correct answer */
  76550. ){
  76551. u32 d1; /* Offset into aKey[] of next data element */
  76552. u32 idx1; /* Offset into aKey[] of next header element */
  76553. u32 szHdr1; /* Number of bytes in header */
  76554. int i = 0;
  76555. int rc = 0;
  76556. const unsigned char *aKey1 = (const unsigned char *)pKey1;
  76557. KeyInfo *pKeyInfo;
  76558. Mem mem1;
  76559. pKeyInfo = pPKey2->pKeyInfo;
  76560. if( pKeyInfo->db==0 ) return 1;
  76561. mem1.enc = pKeyInfo->enc;
  76562. mem1.db = pKeyInfo->db;
  76563. /* mem1.flags = 0; // Will be initialized by sqlite3VdbeSerialGet() */
  76564. VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
  76565. /* Compilers may complain that mem1.u.i is potentially uninitialized.
  76566. ** We could initialize it, as shown here, to silence those complaints.
  76567. ** But in fact, mem1.u.i will never actually be used uninitialized, and doing
  76568. ** the unnecessary initialization has a measurable negative performance
  76569. ** impact, since this routine is a very high runner. And so, we choose
  76570. ** to ignore the compiler warnings and leave this variable uninitialized.
  76571. */
  76572. /* mem1.u.i = 0; // not needed, here to silence compiler warning */
  76573. idx1 = getVarint32(aKey1, szHdr1);
  76574. if( szHdr1>98307 ) return SQLITE_CORRUPT;
  76575. d1 = szHdr1;
  76576. assert( pKeyInfo->nAllField>=pPKey2->nField || CORRUPT_DB );
  76577. assert( pKeyInfo->aSortFlags!=0 );
  76578. assert( pKeyInfo->nKeyField>0 );
  76579. assert( idx1<=szHdr1 || CORRUPT_DB );
  76580. do{
  76581. u32 serial_type1;
  76582. /* Read the serial types for the next element in each key. */
  76583. idx1 += getVarint32( aKey1+idx1, serial_type1 );
  76584. /* Verify that there is enough key space remaining to avoid
  76585. ** a buffer overread. The "d1+serial_type1+2" subexpression will
  76586. ** always be greater than or equal to the amount of required key space.
  76587. ** Use that approximation to avoid the more expensive call to
  76588. ** sqlite3VdbeSerialTypeLen() in the common case.
  76589. */
  76590. if( d1+(u64)serial_type1+2>(u64)nKey1
  76591. && d1+(u64)sqlite3VdbeSerialTypeLen(serial_type1)>(u64)nKey1
  76592. ){
  76593. break;
  76594. }
  76595. /* Extract the values to be compared.
  76596. */
  76597. d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
  76598. /* Do the comparison
  76599. */
  76600. rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i],
  76601. pKeyInfo->nAllField>i ? pKeyInfo->aColl[i] : 0);
  76602. if( rc!=0 ){
  76603. assert( mem1.szMalloc==0 ); /* See comment below */
  76604. if( (pKeyInfo->aSortFlags[i] & KEYINFO_ORDER_BIGNULL)
  76605. && ((mem1.flags & MEM_Null) || (pPKey2->aMem[i].flags & MEM_Null))
  76606. ){
  76607. rc = -rc;
  76608. }
  76609. if( pKeyInfo->aSortFlags[i] & KEYINFO_ORDER_DESC ){
  76610. rc = -rc; /* Invert the result for DESC sort order. */
  76611. }
  76612. goto debugCompareEnd;
  76613. }
  76614. i++;
  76615. }while( idx1<szHdr1 && i<pPKey2->nField );
  76616. /* No memory allocation is ever used on mem1. Prove this using
  76617. ** the following assert(). If the assert() fails, it indicates a
  76618. ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
  76619. */
  76620. assert( mem1.szMalloc==0 );
  76621. /* rc==0 here means that one of the keys ran out of fields and
  76622. ** all the fields up to that point were equal. Return the default_rc
  76623. ** value. */
  76624. rc = pPKey2->default_rc;
  76625. debugCompareEnd:
  76626. if( desiredResult==0 && rc==0 ) return 1;
  76627. if( desiredResult<0 && rc<0 ) return 1;
  76628. if( desiredResult>0 && rc>0 ) return 1;
  76629. if( CORRUPT_DB ) return 1;
  76630. if( pKeyInfo->db->mallocFailed ) return 1;
  76631. return 0;
  76632. }
  76633. #endif
  76634. #ifdef SQLITE_DEBUG
  76635. /*
  76636. ** Count the number of fields (a.k.a. columns) in the record given by
  76637. ** pKey,nKey. The verify that this count is less than or equal to the
  76638. ** limit given by pKeyInfo->nAllField.
  76639. **
  76640. ** If this constraint is not satisfied, it means that the high-speed
  76641. ** vdbeRecordCompareInt() and vdbeRecordCompareString() routines will
  76642. ** not work correctly. If this assert() ever fires, it probably means
  76643. ** that the KeyInfo.nKeyField or KeyInfo.nAllField values were computed
  76644. ** incorrectly.
  76645. */
  76646. static void vdbeAssertFieldCountWithinLimits(
  76647. int nKey, const void *pKey, /* The record to verify */
  76648. const KeyInfo *pKeyInfo /* Compare size with this KeyInfo */
  76649. ){
  76650. int nField = 0;
  76651. u32 szHdr;
  76652. u32 idx;
  76653. u32 notUsed;
  76654. const unsigned char *aKey = (const unsigned char*)pKey;
  76655. if( CORRUPT_DB ) return;
  76656. idx = getVarint32(aKey, szHdr);
  76657. assert( nKey>=0 );
  76658. assert( szHdr<=(u32)nKey );
  76659. while( idx<szHdr ){
  76660. idx += getVarint32(aKey+idx, notUsed);
  76661. nField++;
  76662. }
  76663. assert( nField <= pKeyInfo->nAllField );
  76664. }
  76665. #else
  76666. # define vdbeAssertFieldCountWithinLimits(A,B,C)
  76667. #endif
  76668. /*
  76669. ** Both *pMem1 and *pMem2 contain string values. Compare the two values
  76670. ** using the collation sequence pColl. As usual, return a negative , zero
  76671. ** or positive value if *pMem1 is less than, equal to or greater than
  76672. ** *pMem2, respectively. Similar in spirit to "rc = (*pMem1) - (*pMem2);".
  76673. */
  76674. static int vdbeCompareMemString(
  76675. const Mem *pMem1,
  76676. const Mem *pMem2,
  76677. const CollSeq *pColl,
  76678. u8 *prcErr /* If an OOM occurs, set to SQLITE_NOMEM */
  76679. ){
  76680. if( pMem1->enc==pColl->enc ){
  76681. /* The strings are already in the correct encoding. Call the
  76682. ** comparison function directly */
  76683. return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
  76684. }else{
  76685. int rc;
  76686. const void *v1, *v2;
  76687. Mem c1;
  76688. Mem c2;
  76689. sqlite3VdbeMemInit(&c1, pMem1->db, MEM_Null);
  76690. sqlite3VdbeMemInit(&c2, pMem1->db, MEM_Null);
  76691. sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
  76692. sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
  76693. v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
  76694. v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
  76695. if( (v1==0 || v2==0) ){
  76696. if( prcErr ) *prcErr = SQLITE_NOMEM_BKPT;
  76697. rc = 0;
  76698. }else{
  76699. rc = pColl->xCmp(pColl->pUser, c1.n, v1, c2.n, v2);
  76700. }
  76701. sqlite3VdbeMemRelease(&c1);
  76702. sqlite3VdbeMemRelease(&c2);
  76703. return rc;
  76704. }
  76705. }
  76706. /*
  76707. ** The input pBlob is guaranteed to be a Blob that is not marked
  76708. ** with MEM_Zero. Return true if it could be a zero-blob.
  76709. */
  76710. static int isAllZero(const char *z, int n){
  76711. int i;
  76712. for(i=0; i<n; i++){
  76713. if( z[i] ) return 0;
  76714. }
  76715. return 1;
  76716. }
  76717. /*
  76718. ** Compare two blobs. Return negative, zero, or positive if the first
  76719. ** is less than, equal to, or greater than the second, respectively.
  76720. ** If one blob is a prefix of the other, then the shorter is the lessor.
  76721. */
  76722. SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3BlobCompare(const Mem *pB1, const Mem *pB2){
  76723. int c;
  76724. int n1 = pB1->n;
  76725. int n2 = pB2->n;
  76726. /* It is possible to have a Blob value that has some non-zero content
  76727. ** followed by zero content. But that only comes up for Blobs formed
  76728. ** by the OP_MakeRecord opcode, and such Blobs never get passed into
  76729. ** sqlite3MemCompare(). */
  76730. assert( (pB1->flags & MEM_Zero)==0 || n1==0 );
  76731. assert( (pB2->flags & MEM_Zero)==0 || n2==0 );
  76732. if( (pB1->flags|pB2->flags) & MEM_Zero ){
  76733. if( pB1->flags & pB2->flags & MEM_Zero ){
  76734. return pB1->u.nZero - pB2->u.nZero;
  76735. }else if( pB1->flags & MEM_Zero ){
  76736. if( !isAllZero(pB2->z, pB2->n) ) return -1;
  76737. return pB1->u.nZero - n2;
  76738. }else{
  76739. if( !isAllZero(pB1->z, pB1->n) ) return +1;
  76740. return n1 - pB2->u.nZero;
  76741. }
  76742. }
  76743. c = memcmp(pB1->z, pB2->z, n1>n2 ? n2 : n1);
  76744. if( c ) return c;
  76745. return n1 - n2;
  76746. }
  76747. /*
  76748. ** Do a comparison between a 64-bit signed integer and a 64-bit floating-point
  76749. ** number. Return negative, zero, or positive if the first (i64) is less than,
  76750. ** equal to, or greater than the second (double).
  76751. */
  76752. static int sqlite3IntFloatCompare(i64 i, double r){
  76753. if( sizeof(LONGDOUBLE_TYPE)>8 ){
  76754. LONGDOUBLE_TYPE x = (LONGDOUBLE_TYPE)i;
  76755. if( x<r ) return -1;
  76756. if( x>r ) return +1;
  76757. return 0;
  76758. }else{
  76759. i64 y;
  76760. double s;
  76761. if( r<-9223372036854775808.0 ) return +1;
  76762. if( r>=9223372036854775808.0 ) return -1;
  76763. y = (i64)r;
  76764. if( i<y ) return -1;
  76765. if( i>y ) return +1;
  76766. s = (double)i;
  76767. if( s<r ) return -1;
  76768. if( s>r ) return +1;
  76769. return 0;
  76770. }
  76771. }
  76772. /*
  76773. ** Compare the values contained by the two memory cells, returning
  76774. ** negative, zero or positive if pMem1 is less than, equal to, or greater
  76775. ** than pMem2. Sorting order is NULL's first, followed by numbers (integers
  76776. ** and reals) sorted numerically, followed by text ordered by the collating
  76777. ** sequence pColl and finally blob's ordered by memcmp().
  76778. **
  76779. ** Two NULL values are considered equal by this function.
  76780. */
  76781. SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
  76782. int f1, f2;
  76783. int combined_flags;
  76784. f1 = pMem1->flags;
  76785. f2 = pMem2->flags;
  76786. combined_flags = f1|f2;
  76787. assert( !sqlite3VdbeMemIsRowSet(pMem1) && !sqlite3VdbeMemIsRowSet(pMem2) );
  76788. /* If one value is NULL, it is less than the other. If both values
  76789. ** are NULL, return 0.
  76790. */
  76791. if( combined_flags&MEM_Null ){
  76792. return (f2&MEM_Null) - (f1&MEM_Null);
  76793. }
  76794. /* At least one of the two values is a number
  76795. */
  76796. if( combined_flags&(MEM_Int|MEM_Real|MEM_IntReal) ){
  76797. testcase( combined_flags & MEM_Int );
  76798. testcase( combined_flags & MEM_Real );
  76799. testcase( combined_flags & MEM_IntReal );
  76800. if( (f1 & f2 & (MEM_Int|MEM_IntReal))!=0 ){
  76801. testcase( f1 & f2 & MEM_Int );
  76802. testcase( f1 & f2 & MEM_IntReal );
  76803. if( pMem1->u.i < pMem2->u.i ) return -1;
  76804. if( pMem1->u.i > pMem2->u.i ) return +1;
  76805. return 0;
  76806. }
  76807. if( (f1 & f2 & MEM_Real)!=0 ){
  76808. if( pMem1->u.r < pMem2->u.r ) return -1;
  76809. if( pMem1->u.r > pMem2->u.r ) return +1;
  76810. return 0;
  76811. }
  76812. if( (f1&(MEM_Int|MEM_IntReal))!=0 ){
  76813. testcase( f1 & MEM_Int );
  76814. testcase( f1 & MEM_IntReal );
  76815. if( (f2&MEM_Real)!=0 ){
  76816. return sqlite3IntFloatCompare(pMem1->u.i, pMem2->u.r);
  76817. }else if( (f2&(MEM_Int|MEM_IntReal))!=0 ){
  76818. if( pMem1->u.i < pMem2->u.i ) return -1;
  76819. if( pMem1->u.i > pMem2->u.i ) return +1;
  76820. return 0;
  76821. }else{
  76822. return -1;
  76823. }
  76824. }
  76825. if( (f1&MEM_Real)!=0 ){
  76826. if( (f2&(MEM_Int|MEM_IntReal))!=0 ){
  76827. testcase( f2 & MEM_Int );
  76828. testcase( f2 & MEM_IntReal );
  76829. return -sqlite3IntFloatCompare(pMem2->u.i, pMem1->u.r);
  76830. }else{
  76831. return -1;
  76832. }
  76833. }
  76834. return +1;
  76835. }
  76836. /* If one value is a string and the other is a blob, the string is less.
  76837. ** If both are strings, compare using the collating functions.
  76838. */
  76839. if( combined_flags&MEM_Str ){
  76840. if( (f1 & MEM_Str)==0 ){
  76841. return 1;
  76842. }
  76843. if( (f2 & MEM_Str)==0 ){
  76844. return -1;
  76845. }
  76846. assert( pMem1->enc==pMem2->enc || pMem1->db->mallocFailed );
  76847. assert( pMem1->enc==SQLITE_UTF8 ||
  76848. pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
  76849. /* The collation sequence must be defined at this point, even if
  76850. ** the user deletes the collation sequence after the vdbe program is
  76851. ** compiled (this was not always the case).
  76852. */
  76853. assert( !pColl || pColl->xCmp );
  76854. if( pColl ){
  76855. return vdbeCompareMemString(pMem1, pMem2, pColl, 0);
  76856. }
  76857. /* If a NULL pointer was passed as the collate function, fall through
  76858. ** to the blob case and use memcmp(). */
  76859. }
  76860. /* Both values must be blobs. Compare using memcmp(). */
  76861. return sqlite3BlobCompare(pMem1, pMem2);
  76862. }
  76863. /*
  76864. ** The first argument passed to this function is a serial-type that
  76865. ** corresponds to an integer - all values between 1 and 9 inclusive
  76866. ** except 7. The second points to a buffer containing an integer value
  76867. ** serialized according to serial_type. This function deserializes
  76868. ** and returns the value.
  76869. */
  76870. static i64 vdbeRecordDecodeInt(u32 serial_type, const u8 *aKey){
  76871. u32 y;
  76872. assert( CORRUPT_DB || (serial_type>=1 && serial_type<=9 && serial_type!=7) );
  76873. switch( serial_type ){
  76874. case 0:
  76875. case 1:
  76876. testcase( aKey[0]&0x80 );
  76877. return ONE_BYTE_INT(aKey);
  76878. case 2:
  76879. testcase( aKey[0]&0x80 );
  76880. return TWO_BYTE_INT(aKey);
  76881. case 3:
  76882. testcase( aKey[0]&0x80 );
  76883. return THREE_BYTE_INT(aKey);
  76884. case 4: {
  76885. testcase( aKey[0]&0x80 );
  76886. y = FOUR_BYTE_UINT(aKey);
  76887. return (i64)*(int*)&y;
  76888. }
  76889. case 5: {
  76890. testcase( aKey[0]&0x80 );
  76891. return FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
  76892. }
  76893. case 6: {
  76894. u64 x = FOUR_BYTE_UINT(aKey);
  76895. testcase( aKey[0]&0x80 );
  76896. x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
  76897. return (i64)*(i64*)&x;
  76898. }
  76899. }
  76900. return (serial_type - 8);
  76901. }
  76902. /*
  76903. ** This function compares the two table rows or index records
  76904. ** specified by {nKey1, pKey1} and pPKey2. It returns a negative, zero
  76905. ** or positive integer if key1 is less than, equal to or
  76906. ** greater than key2. The {nKey1, pKey1} key must be a blob
  76907. ** created by the OP_MakeRecord opcode of the VDBE. The pPKey2
  76908. ** key must be a parsed key such as obtained from
  76909. ** sqlite3VdbeParseRecord.
  76910. **
  76911. ** If argument bSkip is non-zero, it is assumed that the caller has already
  76912. ** determined that the first fields of the keys are equal.
  76913. **
  76914. ** Key1 and Key2 do not have to contain the same number of fields. If all
  76915. ** fields that appear in both keys are equal, then pPKey2->default_rc is
  76916. ** returned.
  76917. **
  76918. ** If database corruption is discovered, set pPKey2->errCode to
  76919. ** SQLITE_CORRUPT and return 0. If an OOM error is encountered,
  76920. ** pPKey2->errCode is set to SQLITE_NOMEM and, if it is not NULL, the
  76921. ** malloc-failed flag set on database handle (pPKey2->pKeyInfo->db).
  76922. */
  76923. SQLITE_PRIVATE int sqlite3VdbeRecordCompareWithSkip(
  76924. int nKey1, const void *pKey1, /* Left key */
  76925. UnpackedRecord *pPKey2, /* Right key */
  76926. int bSkip /* If true, skip the first field */
  76927. ){
  76928. u32 d1; /* Offset into aKey[] of next data element */
  76929. int i; /* Index of next field to compare */
  76930. u32 szHdr1; /* Size of record header in bytes */
  76931. u32 idx1; /* Offset of first type in header */
  76932. int rc = 0; /* Return value */
  76933. Mem *pRhs = pPKey2->aMem; /* Next field of pPKey2 to compare */
  76934. KeyInfo *pKeyInfo;
  76935. const unsigned char *aKey1 = (const unsigned char *)pKey1;
  76936. Mem mem1;
  76937. /* If bSkip is true, then the caller has already determined that the first
  76938. ** two elements in the keys are equal. Fix the various stack variables so
  76939. ** that this routine begins comparing at the second field. */
  76940. if( bSkip ){
  76941. u32 s1;
  76942. idx1 = 1 + getVarint32(&aKey1[1], s1);
  76943. szHdr1 = aKey1[0];
  76944. d1 = szHdr1 + sqlite3VdbeSerialTypeLen(s1);
  76945. i = 1;
  76946. pRhs++;
  76947. }else{
  76948. idx1 = getVarint32(aKey1, szHdr1);
  76949. d1 = szHdr1;
  76950. i = 0;
  76951. }
  76952. if( d1>(unsigned)nKey1 ){
  76953. pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
  76954. return 0; /* Corruption */
  76955. }
  76956. VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
  76957. assert( pPKey2->pKeyInfo->nAllField>=pPKey2->nField
  76958. || CORRUPT_DB );
  76959. assert( pPKey2->pKeyInfo->aSortFlags!=0 );
  76960. assert( pPKey2->pKeyInfo->nKeyField>0 );
  76961. assert( idx1<=szHdr1 || CORRUPT_DB );
  76962. do{
  76963. u32 serial_type;
  76964. /* RHS is an integer */
  76965. if( pRhs->flags & (MEM_Int|MEM_IntReal) ){
  76966. testcase( pRhs->flags & MEM_Int );
  76967. testcase( pRhs->flags & MEM_IntReal );
  76968. serial_type = aKey1[idx1];
  76969. testcase( serial_type==12 );
  76970. if( serial_type>=10 ){
  76971. rc = +1;
  76972. }else if( serial_type==0 ){
  76973. rc = -1;
  76974. }else if( serial_type==7 ){
  76975. sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
  76976. rc = -sqlite3IntFloatCompare(pRhs->u.i, mem1.u.r);
  76977. }else{
  76978. i64 lhs = vdbeRecordDecodeInt(serial_type, &aKey1[d1]);
  76979. i64 rhs = pRhs->u.i;
  76980. if( lhs<rhs ){
  76981. rc = -1;
  76982. }else if( lhs>rhs ){
  76983. rc = +1;
  76984. }
  76985. }
  76986. }
  76987. /* RHS is real */
  76988. else if( pRhs->flags & MEM_Real ){
  76989. serial_type = aKey1[idx1];
  76990. if( serial_type>=10 ){
  76991. /* Serial types 12 or greater are strings and blobs (greater than
  76992. ** numbers). Types 10 and 11 are currently "reserved for future
  76993. ** use", so it doesn't really matter what the results of comparing
  76994. ** them to numberic values are. */
  76995. rc = +1;
  76996. }else if( serial_type==0 ){
  76997. rc = -1;
  76998. }else{
  76999. sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
  77000. if( serial_type==7 ){
  77001. if( mem1.u.r<pRhs->u.r ){
  77002. rc = -1;
  77003. }else if( mem1.u.r>pRhs->u.r ){
  77004. rc = +1;
  77005. }
  77006. }else{
  77007. rc = sqlite3IntFloatCompare(mem1.u.i, pRhs->u.r);
  77008. }
  77009. }
  77010. }
  77011. /* RHS is a string */
  77012. else if( pRhs->flags & MEM_Str ){
  77013. getVarint32NR(&aKey1[idx1], serial_type);
  77014. testcase( serial_type==12 );
  77015. if( serial_type<12 ){
  77016. rc = -1;
  77017. }else if( !(serial_type & 0x01) ){
  77018. rc = +1;
  77019. }else{
  77020. mem1.n = (serial_type - 12) / 2;
  77021. testcase( (d1+mem1.n)==(unsigned)nKey1 );
  77022. testcase( (d1+mem1.n+1)==(unsigned)nKey1 );
  77023. if( (d1+mem1.n) > (unsigned)nKey1
  77024. || (pKeyInfo = pPKey2->pKeyInfo)->nAllField<=i
  77025. ){
  77026. pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
  77027. return 0; /* Corruption */
  77028. }else if( pKeyInfo->aColl[i] ){
  77029. mem1.enc = pKeyInfo->enc;
  77030. mem1.db = pKeyInfo->db;
  77031. mem1.flags = MEM_Str;
  77032. mem1.z = (char*)&aKey1[d1];
  77033. rc = vdbeCompareMemString(
  77034. &mem1, pRhs, pKeyInfo->aColl[i], &pPKey2->errCode
  77035. );
  77036. }else{
  77037. int nCmp = MIN(mem1.n, pRhs->n);
  77038. rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
  77039. if( rc==0 ) rc = mem1.n - pRhs->n;
  77040. }
  77041. }
  77042. }
  77043. /* RHS is a blob */
  77044. else if( pRhs->flags & MEM_Blob ){
  77045. assert( (pRhs->flags & MEM_Zero)==0 || pRhs->n==0 );
  77046. getVarint32NR(&aKey1[idx1], serial_type);
  77047. testcase( serial_type==12 );
  77048. if( serial_type<12 || (serial_type & 0x01) ){
  77049. rc = -1;
  77050. }else{
  77051. int nStr = (serial_type - 12) / 2;
  77052. testcase( (d1+nStr)==(unsigned)nKey1 );
  77053. testcase( (d1+nStr+1)==(unsigned)nKey1 );
  77054. if( (d1+nStr) > (unsigned)nKey1 ){
  77055. pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
  77056. return 0; /* Corruption */
  77057. }else if( pRhs->flags & MEM_Zero ){
  77058. if( !isAllZero((const char*)&aKey1[d1],nStr) ){
  77059. rc = 1;
  77060. }else{
  77061. rc = nStr - pRhs->u.nZero;
  77062. }
  77063. }else{
  77064. int nCmp = MIN(nStr, pRhs->n);
  77065. rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
  77066. if( rc==0 ) rc = nStr - pRhs->n;
  77067. }
  77068. }
  77069. }
  77070. /* RHS is null */
  77071. else{
  77072. serial_type = aKey1[idx1];
  77073. rc = (serial_type!=0);
  77074. }
  77075. if( rc!=0 ){
  77076. int sortFlags = pPKey2->pKeyInfo->aSortFlags[i];
  77077. if( sortFlags ){
  77078. if( (sortFlags & KEYINFO_ORDER_BIGNULL)==0
  77079. || ((sortFlags & KEYINFO_ORDER_DESC)
  77080. !=(serial_type==0 || (pRhs->flags&MEM_Null)))
  77081. ){
  77082. rc = -rc;
  77083. }
  77084. }
  77085. assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, rc) );
  77086. assert( mem1.szMalloc==0 ); /* See comment below */
  77087. return rc;
  77088. }
  77089. i++;
  77090. if( i==pPKey2->nField ) break;
  77091. pRhs++;
  77092. d1 += sqlite3VdbeSerialTypeLen(serial_type);
  77093. idx1 += sqlite3VarintLen(serial_type);
  77094. }while( idx1<(unsigned)szHdr1 && d1<=(unsigned)nKey1 );
  77095. /* No memory allocation is ever used on mem1. Prove this using
  77096. ** the following assert(). If the assert() fails, it indicates a
  77097. ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1). */
  77098. assert( mem1.szMalloc==0 );
  77099. /* rc==0 here means that one or both of the keys ran out of fields and
  77100. ** all the fields up to that point were equal. Return the default_rc
  77101. ** value. */
  77102. assert( CORRUPT_DB
  77103. || vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, pPKey2->default_rc)
  77104. || pPKey2->pKeyInfo->db->mallocFailed
  77105. );
  77106. pPKey2->eqSeen = 1;
  77107. return pPKey2->default_rc;
  77108. }
  77109. SQLITE_PRIVATE int sqlite3VdbeRecordCompare(
  77110. int nKey1, const void *pKey1, /* Left key */
  77111. UnpackedRecord *pPKey2 /* Right key */
  77112. ){
  77113. return sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 0);
  77114. }
  77115. /*
  77116. ** This function is an optimized version of sqlite3VdbeRecordCompare()
  77117. ** that (a) the first field of pPKey2 is an integer, and (b) the
  77118. ** size-of-header varint at the start of (pKey1/nKey1) fits in a single
  77119. ** byte (i.e. is less than 128).
  77120. **
  77121. ** To avoid concerns about buffer overreads, this routine is only used
  77122. ** on schemas where the maximum valid header size is 63 bytes or less.
  77123. */
  77124. static int vdbeRecordCompareInt(
  77125. int nKey1, const void *pKey1, /* Left key */
  77126. UnpackedRecord *pPKey2 /* Right key */
  77127. ){
  77128. const u8 *aKey = &((const u8*)pKey1)[*(const u8*)pKey1 & 0x3F];
  77129. int serial_type = ((const u8*)pKey1)[1];
  77130. int res;
  77131. u32 y;
  77132. u64 x;
  77133. i64 v;
  77134. i64 lhs;
  77135. vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo);
  77136. assert( (*(u8*)pKey1)<=0x3F || CORRUPT_DB );
  77137. switch( serial_type ){
  77138. case 1: { /* 1-byte signed integer */
  77139. lhs = ONE_BYTE_INT(aKey);
  77140. testcase( lhs<0 );
  77141. break;
  77142. }
  77143. case 2: { /* 2-byte signed integer */
  77144. lhs = TWO_BYTE_INT(aKey);
  77145. testcase( lhs<0 );
  77146. break;
  77147. }
  77148. case 3: { /* 3-byte signed integer */
  77149. lhs = THREE_BYTE_INT(aKey);
  77150. testcase( lhs<0 );
  77151. break;
  77152. }
  77153. case 4: { /* 4-byte signed integer */
  77154. y = FOUR_BYTE_UINT(aKey);
  77155. lhs = (i64)*(int*)&y;
  77156. testcase( lhs<0 );
  77157. break;
  77158. }
  77159. case 5: { /* 6-byte signed integer */
  77160. lhs = FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
  77161. testcase( lhs<0 );
  77162. break;
  77163. }
  77164. case 6: { /* 8-byte signed integer */
  77165. x = FOUR_BYTE_UINT(aKey);
  77166. x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
  77167. lhs = *(i64*)&x;
  77168. testcase( lhs<0 );
  77169. break;
  77170. }
  77171. case 8:
  77172. lhs = 0;
  77173. break;
  77174. case 9:
  77175. lhs = 1;
  77176. break;
  77177. /* This case could be removed without changing the results of running
  77178. ** this code. Including it causes gcc to generate a faster switch
  77179. ** statement (since the range of switch targets now starts at zero and
  77180. ** is contiguous) but does not cause any duplicate code to be generated
  77181. ** (as gcc is clever enough to combine the two like cases). Other
  77182. ** compilers might be similar. */
  77183. case 0: case 7:
  77184. return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
  77185. default:
  77186. return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
  77187. }
  77188. v = pPKey2->aMem[0].u.i;
  77189. if( v>lhs ){
  77190. res = pPKey2->r1;
  77191. }else if( v<lhs ){
  77192. res = pPKey2->r2;
  77193. }else if( pPKey2->nField>1 ){
  77194. /* The first fields of the two keys are equal. Compare the trailing
  77195. ** fields. */
  77196. res = sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
  77197. }else{
  77198. /* The first fields of the two keys are equal and there are no trailing
  77199. ** fields. Return pPKey2->default_rc in this case. */
  77200. res = pPKey2->default_rc;
  77201. pPKey2->eqSeen = 1;
  77202. }
  77203. assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res) );
  77204. return res;
  77205. }
  77206. /*
  77207. ** This function is an optimized version of sqlite3VdbeRecordCompare()
  77208. ** that (a) the first field of pPKey2 is a string, that (b) the first field
  77209. ** uses the collation sequence BINARY and (c) that the size-of-header varint
  77210. ** at the start of (pKey1/nKey1) fits in a single byte.
  77211. */
  77212. static int vdbeRecordCompareString(
  77213. int nKey1, const void *pKey1, /* Left key */
  77214. UnpackedRecord *pPKey2 /* Right key */
  77215. ){
  77216. const u8 *aKey1 = (const u8*)pKey1;
  77217. int serial_type;
  77218. int res;
  77219. assert( pPKey2->aMem[0].flags & MEM_Str );
  77220. vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo);
  77221. serial_type = (u8)(aKey1[1]);
  77222. if( serial_type >= 0x80 ){
  77223. sqlite3GetVarint32(&aKey1[1], (u32*)&serial_type);
  77224. }
  77225. if( serial_type<12 ){
  77226. res = pPKey2->r1; /* (pKey1/nKey1) is a number or a null */
  77227. }else if( !(serial_type & 0x01) ){
  77228. res = pPKey2->r2; /* (pKey1/nKey1) is a blob */
  77229. }else{
  77230. int nCmp;
  77231. int nStr;
  77232. int szHdr = aKey1[0];
  77233. nStr = (serial_type-12) / 2;
  77234. if( (szHdr + nStr) > nKey1 ){
  77235. pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
  77236. return 0; /* Corruption */
  77237. }
  77238. nCmp = MIN( pPKey2->aMem[0].n, nStr );
  77239. res = memcmp(&aKey1[szHdr], pPKey2->aMem[0].z, nCmp);
  77240. if( res>0 ){
  77241. res = pPKey2->r2;
  77242. }else if( res<0 ){
  77243. res = pPKey2->r1;
  77244. }else{
  77245. res = nStr - pPKey2->aMem[0].n;
  77246. if( res==0 ){
  77247. if( pPKey2->nField>1 ){
  77248. res = sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
  77249. }else{
  77250. res = pPKey2->default_rc;
  77251. pPKey2->eqSeen = 1;
  77252. }
  77253. }else if( res>0 ){
  77254. res = pPKey2->r2;
  77255. }else{
  77256. res = pPKey2->r1;
  77257. }
  77258. }
  77259. }
  77260. assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res)
  77261. || CORRUPT_DB
  77262. || pPKey2->pKeyInfo->db->mallocFailed
  77263. );
  77264. return res;
  77265. }
  77266. /*
  77267. ** Return a pointer to an sqlite3VdbeRecordCompare() compatible function
  77268. ** suitable for comparing serialized records to the unpacked record passed
  77269. ** as the only argument.
  77270. */
  77271. SQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord *p){
  77272. /* varintRecordCompareInt() and varintRecordCompareString() both assume
  77273. ** that the size-of-header varint that occurs at the start of each record
  77274. ** fits in a single byte (i.e. is 127 or less). varintRecordCompareInt()
  77275. ** also assumes that it is safe to overread a buffer by at least the
  77276. ** maximum possible legal header size plus 8 bytes. Because there is
  77277. ** guaranteed to be at least 74 (but not 136) bytes of padding following each
  77278. ** buffer passed to varintRecordCompareInt() this makes it convenient to
  77279. ** limit the size of the header to 64 bytes in cases where the first field
  77280. ** is an integer.
  77281. **
  77282. ** The easiest way to enforce this limit is to consider only records with
  77283. ** 13 fields or less. If the first field is an integer, the maximum legal
  77284. ** header size is (12*5 + 1 + 1) bytes. */
  77285. if( p->pKeyInfo->nAllField<=13 ){
  77286. int flags = p->aMem[0].flags;
  77287. if( p->pKeyInfo->aSortFlags[0] ){
  77288. if( p->pKeyInfo->aSortFlags[0] & KEYINFO_ORDER_BIGNULL ){
  77289. return sqlite3VdbeRecordCompare;
  77290. }
  77291. p->r1 = 1;
  77292. p->r2 = -1;
  77293. }else{
  77294. p->r1 = -1;
  77295. p->r2 = 1;
  77296. }
  77297. if( (flags & MEM_Int) ){
  77298. return vdbeRecordCompareInt;
  77299. }
  77300. testcase( flags & MEM_Real );
  77301. testcase( flags & MEM_Null );
  77302. testcase( flags & MEM_Blob );
  77303. if( (flags & (MEM_Real|MEM_IntReal|MEM_Null|MEM_Blob))==0
  77304. && p->pKeyInfo->aColl[0]==0
  77305. ){
  77306. assert( flags & MEM_Str );
  77307. return vdbeRecordCompareString;
  77308. }
  77309. }
  77310. return sqlite3VdbeRecordCompare;
  77311. }
  77312. /*
  77313. ** pCur points at an index entry created using the OP_MakeRecord opcode.
  77314. ** Read the rowid (the last field in the record) and store it in *rowid.
  77315. ** Return SQLITE_OK if everything works, or an error code otherwise.
  77316. **
  77317. ** pCur might be pointing to text obtained from a corrupt database file.
  77318. ** So the content cannot be trusted. Do appropriate checks on the content.
  77319. */
  77320. SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
  77321. i64 nCellKey = 0;
  77322. int rc;
  77323. u32 szHdr; /* Size of the header */
  77324. u32 typeRowid; /* Serial type of the rowid */
  77325. u32 lenRowid; /* Size of the rowid */
  77326. Mem m, v;
  77327. /* Get the size of the index entry. Only indices entries of less
  77328. ** than 2GiB are support - anything large must be database corruption.
  77329. ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
  77330. ** this code can safely assume that nCellKey is 32-bits
  77331. */
  77332. assert( sqlite3BtreeCursorIsValid(pCur) );
  77333. nCellKey = sqlite3BtreePayloadSize(pCur);
  77334. assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
  77335. /* Read in the complete content of the index entry */
  77336. sqlite3VdbeMemInit(&m, db, 0);
  77337. rc = sqlite3VdbeMemFromBtreeZeroOffset(pCur, (u32)nCellKey, &m);
  77338. if( rc ){
  77339. return rc;
  77340. }
  77341. /* The index entry must begin with a header size */
  77342. getVarint32NR((u8*)m.z, szHdr);
  77343. testcase( szHdr==3 );
  77344. testcase( szHdr==m.n );
  77345. testcase( szHdr>0x7fffffff );
  77346. assert( m.n>=0 );
  77347. if( unlikely(szHdr<3 || szHdr>(unsigned)m.n) ){
  77348. goto idx_rowid_corruption;
  77349. }
  77350. /* The last field of the index should be an integer - the ROWID.
  77351. ** Verify that the last entry really is an integer. */
  77352. getVarint32NR((u8*)&m.z[szHdr-1], typeRowid);
  77353. testcase( typeRowid==1 );
  77354. testcase( typeRowid==2 );
  77355. testcase( typeRowid==3 );
  77356. testcase( typeRowid==4 );
  77357. testcase( typeRowid==5 );
  77358. testcase( typeRowid==6 );
  77359. testcase( typeRowid==8 );
  77360. testcase( typeRowid==9 );
  77361. if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
  77362. goto idx_rowid_corruption;
  77363. }
  77364. lenRowid = sqlite3SmallTypeSizes[typeRowid];
  77365. testcase( (u32)m.n==szHdr+lenRowid );
  77366. if( unlikely((u32)m.n<szHdr+lenRowid) ){
  77367. goto idx_rowid_corruption;
  77368. }
  77369. /* Fetch the integer off the end of the index record */
  77370. sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
  77371. *rowid = v.u.i;
  77372. sqlite3VdbeMemRelease(&m);
  77373. return SQLITE_OK;
  77374. /* Jump here if database corruption is detected after m has been
  77375. ** allocated. Free the m object and return SQLITE_CORRUPT. */
  77376. idx_rowid_corruption:
  77377. testcase( m.szMalloc!=0 );
  77378. sqlite3VdbeMemRelease(&m);
  77379. return SQLITE_CORRUPT_BKPT;
  77380. }
  77381. /*
  77382. ** Compare the key of the index entry that cursor pC is pointing to against
  77383. ** the key string in pUnpacked. Write into *pRes a number
  77384. ** that is negative, zero, or positive if pC is less than, equal to,
  77385. ** or greater than pUnpacked. Return SQLITE_OK on success.
  77386. **
  77387. ** pUnpacked is either created without a rowid or is truncated so that it
  77388. ** omits the rowid at the end. The rowid at the end of the index entry
  77389. ** is ignored as well. Hence, this routine only compares the prefixes
  77390. ** of the keys prior to the final rowid, not the entire key.
  77391. */
  77392. SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(
  77393. sqlite3 *db, /* Database connection */
  77394. VdbeCursor *pC, /* The cursor to compare against */
  77395. UnpackedRecord *pUnpacked, /* Unpacked version of key */
  77396. int *res /* Write the comparison result here */
  77397. ){
  77398. i64 nCellKey = 0;
  77399. int rc;
  77400. BtCursor *pCur;
  77401. Mem m;
  77402. assert( pC->eCurType==CURTYPE_BTREE );
  77403. pCur = pC->uc.pCursor;
  77404. assert( sqlite3BtreeCursorIsValid(pCur) );
  77405. nCellKey = sqlite3BtreePayloadSize(pCur);
  77406. /* nCellKey will always be between 0 and 0xffffffff because of the way
  77407. ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
  77408. if( nCellKey<=0 || nCellKey>0x7fffffff ){
  77409. *res = 0;
  77410. return SQLITE_CORRUPT_BKPT;
  77411. }
  77412. sqlite3VdbeMemInit(&m, db, 0);
  77413. rc = sqlite3VdbeMemFromBtreeZeroOffset(pCur, (u32)nCellKey, &m);
  77414. if( rc ){
  77415. return rc;
  77416. }
  77417. *res = sqlite3VdbeRecordCompareWithSkip(m.n, m.z, pUnpacked, 0);
  77418. sqlite3VdbeMemRelease(&m);
  77419. return SQLITE_OK;
  77420. }
  77421. /*
  77422. ** This routine sets the value to be returned by subsequent calls to
  77423. ** sqlite3_changes() on the database handle 'db'.
  77424. */
  77425. SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
  77426. assert( sqlite3_mutex_held(db->mutex) );
  77427. db->nChange = nChange;
  77428. db->nTotalChange += nChange;
  77429. }
  77430. /*
  77431. ** Set a flag in the vdbe to update the change counter when it is finalised
  77432. ** or reset.
  77433. */
  77434. SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){
  77435. v->changeCntOn = 1;
  77436. }
  77437. /*
  77438. ** Mark every prepared statement associated with a database connection
  77439. ** as expired.
  77440. **
  77441. ** An expired statement means that recompilation of the statement is
  77442. ** recommend. Statements expire when things happen that make their
  77443. ** programs obsolete. Removing user-defined functions or collating
  77444. ** sequences, or changing an authorization function are the types of
  77445. ** things that make prepared statements obsolete.
  77446. **
  77447. ** If iCode is 1, then expiration is advisory. The statement should
  77448. ** be reprepared before being restarted, but if it is already running
  77449. ** it is allowed to run to completion.
  77450. **
  77451. ** Internally, this function just sets the Vdbe.expired flag on all
  77452. ** prepared statements. The flag is set to 1 for an immediate expiration
  77453. ** and set to 2 for an advisory expiration.
  77454. */
  77455. SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db, int iCode){
  77456. Vdbe *p;
  77457. for(p = db->pVdbe; p; p=p->pNext){
  77458. p->expired = iCode+1;
  77459. }
  77460. }
  77461. /*
  77462. ** Return the database associated with the Vdbe.
  77463. */
  77464. SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){
  77465. return v->db;
  77466. }
  77467. /*
  77468. ** Return the SQLITE_PREPARE flags for a Vdbe.
  77469. */
  77470. SQLITE_PRIVATE u8 sqlite3VdbePrepareFlags(Vdbe *v){
  77471. return v->prepFlags;
  77472. }
  77473. /*
  77474. ** Return a pointer to an sqlite3_value structure containing the value bound
  77475. ** parameter iVar of VM v. Except, if the value is an SQL NULL, return
  77476. ** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
  77477. ** constants) to the value before returning it.
  77478. **
  77479. ** The returned value must be freed by the caller using sqlite3ValueFree().
  77480. */
  77481. SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe *v, int iVar, u8 aff){
  77482. assert( iVar>0 );
  77483. if( v ){
  77484. Mem *pMem = &v->aVar[iVar-1];
  77485. assert( (v->db->flags & SQLITE_EnableQPSG)==0 );
  77486. if( 0==(pMem->flags & MEM_Null) ){
  77487. sqlite3_value *pRet = sqlite3ValueNew(v->db);
  77488. if( pRet ){
  77489. sqlite3VdbeMemCopy((Mem *)pRet, pMem);
  77490. sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
  77491. }
  77492. return pRet;
  77493. }
  77494. }
  77495. return 0;
  77496. }
  77497. /*
  77498. ** Configure SQL variable iVar so that binding a new value to it signals
  77499. ** to sqlite3_reoptimize() that re-preparing the statement may result
  77500. ** in a better query plan.
  77501. */
  77502. SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
  77503. assert( iVar>0 );
  77504. assert( (v->db->flags & SQLITE_EnableQPSG)==0 );
  77505. if( iVar>=32 ){
  77506. v->expmask |= 0x80000000;
  77507. }else{
  77508. v->expmask |= ((u32)1 << (iVar-1));
  77509. }
  77510. }
  77511. /*
  77512. ** Cause a function to throw an error if it was call from OP_PureFunc
  77513. ** rather than OP_Function.
  77514. **
  77515. ** OP_PureFunc means that the function must be deterministic, and should
  77516. ** throw an error if it is given inputs that would make it non-deterministic.
  77517. ** This routine is invoked by date/time functions that use non-deterministic
  77518. ** features such as 'now'.
  77519. */
  77520. SQLITE_PRIVATE int sqlite3NotPureFunc(sqlite3_context *pCtx){
  77521. const VdbeOp *pOp;
  77522. #ifdef SQLITE_ENABLE_STAT4
  77523. if( pCtx->pVdbe==0 ) return 1;
  77524. #endif
  77525. pOp = pCtx->pVdbe->aOp + pCtx->iOp;
  77526. if( pOp->opcode==OP_PureFunc ){
  77527. const char *zContext;
  77528. char *zMsg;
  77529. if( pOp->p5 & NC_IsCheck ){
  77530. zContext = "a CHECK constraint";
  77531. }else if( pOp->p5 & NC_GenCol ){
  77532. zContext = "a generated column";
  77533. }else{
  77534. zContext = "an index";
  77535. }
  77536. zMsg = sqlite3_mprintf("non-deterministic use of %s() in %s",
  77537. pCtx->pFunc->zName, zContext);
  77538. sqlite3_result_error(pCtx, zMsg, -1);
  77539. sqlite3_free(zMsg);
  77540. return 0;
  77541. }
  77542. return 1;
  77543. }
  77544. #ifndef SQLITE_OMIT_VIRTUALTABLE
  77545. /*
  77546. ** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored
  77547. ** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored
  77548. ** in memory obtained from sqlite3DbMalloc).
  77549. */
  77550. SQLITE_PRIVATE void sqlite3VtabImportErrmsg(Vdbe *p, sqlite3_vtab *pVtab){
  77551. if( pVtab->zErrMsg ){
  77552. sqlite3 *db = p->db;
  77553. sqlite3DbFree(db, p->zErrMsg);
  77554. p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
  77555. sqlite3_free(pVtab->zErrMsg);
  77556. pVtab->zErrMsg = 0;
  77557. }
  77558. }
  77559. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  77560. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  77561. /*
  77562. ** If the second argument is not NULL, release any allocations associated
  77563. ** with the memory cells in the p->aMem[] array. Also free the UnpackedRecord
  77564. ** structure itself, using sqlite3DbFree().
  77565. **
  77566. ** This function is used to free UnpackedRecord structures allocated by
  77567. ** the vdbeUnpackRecord() function found in vdbeapi.c.
  77568. */
  77569. static void vdbeFreeUnpacked(sqlite3 *db, int nField, UnpackedRecord *p){
  77570. if( p ){
  77571. int i;
  77572. for(i=0; i<nField; i++){
  77573. Mem *pMem = &p->aMem[i];
  77574. if( pMem->zMalloc ) sqlite3VdbeMemRelease(pMem);
  77575. }
  77576. sqlite3DbFreeNN(db, p);
  77577. }
  77578. }
  77579. #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
  77580. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  77581. /*
  77582. ** Invoke the pre-update hook. If this is an UPDATE or DELETE pre-update call,
  77583. ** then cursor passed as the second argument should point to the row about
  77584. ** to be update or deleted. If the application calls sqlite3_preupdate_old(),
  77585. ** the required value will be read from the row the cursor points to.
  77586. */
  77587. SQLITE_PRIVATE void sqlite3VdbePreUpdateHook(
  77588. Vdbe *v, /* Vdbe pre-update hook is invoked by */
  77589. VdbeCursor *pCsr, /* Cursor to grab old.* values from */
  77590. int op, /* SQLITE_INSERT, UPDATE or DELETE */
  77591. const char *zDb, /* Database name */
  77592. Table *pTab, /* Modified table */
  77593. i64 iKey1, /* Initial key value */
  77594. int iReg /* Register for new.* record */
  77595. ){
  77596. sqlite3 *db = v->db;
  77597. i64 iKey2;
  77598. PreUpdate preupdate;
  77599. const char *zTbl = pTab->zName;
  77600. static const u8 fakeSortOrder = 0;
  77601. assert( db->pPreUpdate==0 );
  77602. memset(&preupdate, 0, sizeof(PreUpdate));
  77603. if( HasRowid(pTab)==0 ){
  77604. iKey1 = iKey2 = 0;
  77605. preupdate.pPk = sqlite3PrimaryKeyIndex(pTab);
  77606. }else{
  77607. if( op==SQLITE_UPDATE ){
  77608. iKey2 = v->aMem[iReg].u.i;
  77609. }else{
  77610. iKey2 = iKey1;
  77611. }
  77612. }
  77613. assert( pCsr->nField==pTab->nCol
  77614. || (pCsr->nField==pTab->nCol+1 && op==SQLITE_DELETE && iReg==-1)
  77615. );
  77616. preupdate.v = v;
  77617. preupdate.pCsr = pCsr;
  77618. preupdate.op = op;
  77619. preupdate.iNewReg = iReg;
  77620. preupdate.keyinfo.db = db;
  77621. preupdate.keyinfo.enc = ENC(db);
  77622. preupdate.keyinfo.nKeyField = pTab->nCol;
  77623. preupdate.keyinfo.aSortFlags = (u8*)&fakeSortOrder;
  77624. preupdate.iKey1 = iKey1;
  77625. preupdate.iKey2 = iKey2;
  77626. preupdate.pTab = pTab;
  77627. db->pPreUpdate = &preupdate;
  77628. db->xPreUpdateCallback(db->pPreUpdateArg, db, op, zDb, zTbl, iKey1, iKey2);
  77629. db->pPreUpdate = 0;
  77630. sqlite3DbFree(db, preupdate.aRecord);
  77631. vdbeFreeUnpacked(db, preupdate.keyinfo.nKeyField+1, preupdate.pUnpacked);
  77632. vdbeFreeUnpacked(db, preupdate.keyinfo.nKeyField+1, preupdate.pNewUnpacked);
  77633. if( preupdate.aNew ){
  77634. int i;
  77635. for(i=0; i<pCsr->nField; i++){
  77636. sqlite3VdbeMemRelease(&preupdate.aNew[i]);
  77637. }
  77638. sqlite3DbFreeNN(db, preupdate.aNew);
  77639. }
  77640. }
  77641. #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
  77642. /************** End of vdbeaux.c *********************************************/
  77643. /************** Begin file vdbeapi.c *****************************************/
  77644. /*
  77645. ** 2004 May 26
  77646. **
  77647. ** The author disclaims copyright to this source code. In place of
  77648. ** a legal notice, here is a blessing:
  77649. **
  77650. ** May you do good and not evil.
  77651. ** May you find forgiveness for yourself and forgive others.
  77652. ** May you share freely, never taking more than you give.
  77653. **
  77654. *************************************************************************
  77655. **
  77656. ** This file contains code use to implement APIs that are part of the
  77657. ** VDBE.
  77658. */
  77659. /* #include "sqliteInt.h" */
  77660. /* #include "vdbeInt.h" */
  77661. #ifndef SQLITE_OMIT_DEPRECATED
  77662. /*
  77663. ** Return TRUE (non-zero) of the statement supplied as an argument needs
  77664. ** to be recompiled. A statement needs to be recompiled whenever the
  77665. ** execution environment changes in a way that would alter the program
  77666. ** that sqlite3_prepare() generates. For example, if new functions or
  77667. ** collating sequences are registered or if an authorizer function is
  77668. ** added or changed.
  77669. */
  77670. SQLITE_API int sqlite3_expired(sqlite3_stmt *pStmt){
  77671. Vdbe *p = (Vdbe*)pStmt;
  77672. return p==0 || p->expired;
  77673. }
  77674. #endif
  77675. /*
  77676. ** Check on a Vdbe to make sure it has not been finalized. Log
  77677. ** an error and return true if it has been finalized (or is otherwise
  77678. ** invalid). Return false if it is ok.
  77679. */
  77680. static int vdbeSafety(Vdbe *p){
  77681. if( p->db==0 ){
  77682. sqlite3_log(SQLITE_MISUSE, "API called with finalized prepared statement");
  77683. return 1;
  77684. }else{
  77685. return 0;
  77686. }
  77687. }
  77688. static int vdbeSafetyNotNull(Vdbe *p){
  77689. if( p==0 ){
  77690. sqlite3_log(SQLITE_MISUSE, "API called with NULL prepared statement");
  77691. return 1;
  77692. }else{
  77693. return vdbeSafety(p);
  77694. }
  77695. }
  77696. #ifndef SQLITE_OMIT_TRACE
  77697. /*
  77698. ** Invoke the profile callback. This routine is only called if we already
  77699. ** know that the profile callback is defined and needs to be invoked.
  77700. */
  77701. static SQLITE_NOINLINE void invokeProfileCallback(sqlite3 *db, Vdbe *p){
  77702. sqlite3_int64 iNow;
  77703. sqlite3_int64 iElapse;
  77704. assert( p->startTime>0 );
  77705. assert( (db->mTrace & (SQLITE_TRACE_PROFILE|SQLITE_TRACE_XPROFILE))!=0 );
  77706. assert( db->init.busy==0 );
  77707. assert( p->zSql!=0 );
  77708. sqlite3OsCurrentTimeInt64(db->pVfs, &iNow);
  77709. iElapse = (iNow - p->startTime)*1000000;
  77710. #ifndef SQLITE_OMIT_DEPRECATED
  77711. if( db->xProfile ){
  77712. db->xProfile(db->pProfileArg, p->zSql, iElapse);
  77713. }
  77714. #endif
  77715. if( db->mTrace & SQLITE_TRACE_PROFILE ){
  77716. db->xTrace(SQLITE_TRACE_PROFILE, db->pTraceArg, p, (void*)&iElapse);
  77717. }
  77718. p->startTime = 0;
  77719. }
  77720. /*
  77721. ** The checkProfileCallback(DB,P) macro checks to see if a profile callback
  77722. ** is needed, and it invokes the callback if it is needed.
  77723. */
  77724. # define checkProfileCallback(DB,P) \
  77725. if( ((P)->startTime)>0 ){ invokeProfileCallback(DB,P); }
  77726. #else
  77727. # define checkProfileCallback(DB,P) /*no-op*/
  77728. #endif
  77729. /*
  77730. ** The following routine destroys a virtual machine that is created by
  77731. ** the sqlite3_compile() routine. The integer returned is an SQLITE_
  77732. ** success/failure code that describes the result of executing the virtual
  77733. ** machine.
  77734. **
  77735. ** This routine sets the error code and string returned by
  77736. ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
  77737. */
  77738. SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt){
  77739. int rc;
  77740. if( pStmt==0 ){
  77741. /* IMPLEMENTATION-OF: R-57228-12904 Invoking sqlite3_finalize() on a NULL
  77742. ** pointer is a harmless no-op. */
  77743. rc = SQLITE_OK;
  77744. }else{
  77745. Vdbe *v = (Vdbe*)pStmt;
  77746. sqlite3 *db = v->db;
  77747. if( vdbeSafety(v) ) return SQLITE_MISUSE_BKPT;
  77748. sqlite3_mutex_enter(db->mutex);
  77749. checkProfileCallback(db, v);
  77750. rc = sqlite3VdbeFinalize(v);
  77751. rc = sqlite3ApiExit(db, rc);
  77752. sqlite3LeaveMutexAndCloseZombie(db);
  77753. }
  77754. return rc;
  77755. }
  77756. /*
  77757. ** Terminate the current execution of an SQL statement and reset it
  77758. ** back to its starting state so that it can be reused. A success code from
  77759. ** the prior execution is returned.
  77760. **
  77761. ** This routine sets the error code and string returned by
  77762. ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
  77763. */
  77764. SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt){
  77765. int rc;
  77766. if( pStmt==0 ){
  77767. rc = SQLITE_OK;
  77768. }else{
  77769. Vdbe *v = (Vdbe*)pStmt;
  77770. sqlite3 *db = v->db;
  77771. sqlite3_mutex_enter(db->mutex);
  77772. checkProfileCallback(db, v);
  77773. rc = sqlite3VdbeReset(v);
  77774. sqlite3VdbeRewind(v);
  77775. assert( (rc & (db->errMask))==rc );
  77776. rc = sqlite3ApiExit(db, rc);
  77777. sqlite3_mutex_leave(db->mutex);
  77778. }
  77779. return rc;
  77780. }
  77781. /*
  77782. ** Set all the parameters in the compiled SQL statement to NULL.
  77783. */
  77784. SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt *pStmt){
  77785. int i;
  77786. int rc = SQLITE_OK;
  77787. Vdbe *p = (Vdbe*)pStmt;
  77788. #if SQLITE_THREADSAFE
  77789. sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
  77790. #endif
  77791. sqlite3_mutex_enter(mutex);
  77792. for(i=0; i<p->nVar; i++){
  77793. sqlite3VdbeMemRelease(&p->aVar[i]);
  77794. p->aVar[i].flags = MEM_Null;
  77795. }
  77796. assert( (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 || p->expmask==0 );
  77797. if( p->expmask ){
  77798. p->expired = 1;
  77799. }
  77800. sqlite3_mutex_leave(mutex);
  77801. return rc;
  77802. }
  77803. /**************************** sqlite3_value_ *******************************
  77804. ** The following routines extract information from a Mem or sqlite3_value
  77805. ** structure.
  77806. */
  77807. SQLITE_API const void *sqlite3_value_blob(sqlite3_value *pVal){
  77808. Mem *p = (Mem*)pVal;
  77809. if( p->flags & (MEM_Blob|MEM_Str) ){
  77810. if( ExpandBlob(p)!=SQLITE_OK ){
  77811. assert( p->flags==MEM_Null && p->z==0 );
  77812. return 0;
  77813. }
  77814. p->flags |= MEM_Blob;
  77815. return p->n ? p->z : 0;
  77816. }else{
  77817. return sqlite3_value_text(pVal);
  77818. }
  77819. }
  77820. SQLITE_API int sqlite3_value_bytes(sqlite3_value *pVal){
  77821. return sqlite3ValueBytes(pVal, SQLITE_UTF8);
  77822. }
  77823. SQLITE_API int sqlite3_value_bytes16(sqlite3_value *pVal){
  77824. return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
  77825. }
  77826. SQLITE_API double sqlite3_value_double(sqlite3_value *pVal){
  77827. return sqlite3VdbeRealValue((Mem*)pVal);
  77828. }
  77829. SQLITE_API int sqlite3_value_int(sqlite3_value *pVal){
  77830. return (int)sqlite3VdbeIntValue((Mem*)pVal);
  77831. }
  77832. SQLITE_API sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){
  77833. return sqlite3VdbeIntValue((Mem*)pVal);
  77834. }
  77835. SQLITE_API unsigned int sqlite3_value_subtype(sqlite3_value *pVal){
  77836. Mem *pMem = (Mem*)pVal;
  77837. return ((pMem->flags & MEM_Subtype) ? pMem->eSubtype : 0);
  77838. }
  77839. SQLITE_API void *sqlite3_value_pointer(sqlite3_value *pVal, const char *zPType){
  77840. Mem *p = (Mem*)pVal;
  77841. if( (p->flags&(MEM_TypeMask|MEM_Term|MEM_Subtype)) ==
  77842. (MEM_Null|MEM_Term|MEM_Subtype)
  77843. && zPType!=0
  77844. && p->eSubtype=='p'
  77845. && strcmp(p->u.zPType, zPType)==0
  77846. ){
  77847. return (void*)p->z;
  77848. }else{
  77849. return 0;
  77850. }
  77851. }
  77852. SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value *pVal){
  77853. return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
  77854. }
  77855. #ifndef SQLITE_OMIT_UTF16
  77856. SQLITE_API const void *sqlite3_value_text16(sqlite3_value* pVal){
  77857. return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
  77858. }
  77859. SQLITE_API const void *sqlite3_value_text16be(sqlite3_value *pVal){
  77860. return sqlite3ValueText(pVal, SQLITE_UTF16BE);
  77861. }
  77862. SQLITE_API const void *sqlite3_value_text16le(sqlite3_value *pVal){
  77863. return sqlite3ValueText(pVal, SQLITE_UTF16LE);
  77864. }
  77865. #endif /* SQLITE_OMIT_UTF16 */
  77866. /* EVIDENCE-OF: R-12793-43283 Every value in SQLite has one of five
  77867. ** fundamental datatypes: 64-bit signed integer 64-bit IEEE floating
  77868. ** point number string BLOB NULL
  77869. */
  77870. SQLITE_API int sqlite3_value_type(sqlite3_value* pVal){
  77871. static const u8 aType[] = {
  77872. SQLITE_BLOB, /* 0x00 (not possible) */
  77873. SQLITE_NULL, /* 0x01 NULL */
  77874. SQLITE_TEXT, /* 0x02 TEXT */
  77875. SQLITE_NULL, /* 0x03 (not possible) */
  77876. SQLITE_INTEGER, /* 0x04 INTEGER */
  77877. SQLITE_NULL, /* 0x05 (not possible) */
  77878. SQLITE_INTEGER, /* 0x06 INTEGER + TEXT */
  77879. SQLITE_NULL, /* 0x07 (not possible) */
  77880. SQLITE_FLOAT, /* 0x08 FLOAT */
  77881. SQLITE_NULL, /* 0x09 (not possible) */
  77882. SQLITE_FLOAT, /* 0x0a FLOAT + TEXT */
  77883. SQLITE_NULL, /* 0x0b (not possible) */
  77884. SQLITE_INTEGER, /* 0x0c (not possible) */
  77885. SQLITE_NULL, /* 0x0d (not possible) */
  77886. SQLITE_INTEGER, /* 0x0e (not possible) */
  77887. SQLITE_NULL, /* 0x0f (not possible) */
  77888. SQLITE_BLOB, /* 0x10 BLOB */
  77889. SQLITE_NULL, /* 0x11 (not possible) */
  77890. SQLITE_TEXT, /* 0x12 (not possible) */
  77891. SQLITE_NULL, /* 0x13 (not possible) */
  77892. SQLITE_INTEGER, /* 0x14 INTEGER + BLOB */
  77893. SQLITE_NULL, /* 0x15 (not possible) */
  77894. SQLITE_INTEGER, /* 0x16 (not possible) */
  77895. SQLITE_NULL, /* 0x17 (not possible) */
  77896. SQLITE_FLOAT, /* 0x18 FLOAT + BLOB */
  77897. SQLITE_NULL, /* 0x19 (not possible) */
  77898. SQLITE_FLOAT, /* 0x1a (not possible) */
  77899. SQLITE_NULL, /* 0x1b (not possible) */
  77900. SQLITE_INTEGER, /* 0x1c (not possible) */
  77901. SQLITE_NULL, /* 0x1d (not possible) */
  77902. SQLITE_INTEGER, /* 0x1e (not possible) */
  77903. SQLITE_NULL, /* 0x1f (not possible) */
  77904. SQLITE_FLOAT, /* 0x20 INTREAL */
  77905. SQLITE_NULL, /* 0x21 (not possible) */
  77906. SQLITE_TEXT, /* 0x22 INTREAL + TEXT */
  77907. SQLITE_NULL, /* 0x23 (not possible) */
  77908. SQLITE_FLOAT, /* 0x24 (not possible) */
  77909. SQLITE_NULL, /* 0x25 (not possible) */
  77910. SQLITE_FLOAT, /* 0x26 (not possible) */
  77911. SQLITE_NULL, /* 0x27 (not possible) */
  77912. SQLITE_FLOAT, /* 0x28 (not possible) */
  77913. SQLITE_NULL, /* 0x29 (not possible) */
  77914. SQLITE_FLOAT, /* 0x2a (not possible) */
  77915. SQLITE_NULL, /* 0x2b (not possible) */
  77916. SQLITE_FLOAT, /* 0x2c (not possible) */
  77917. SQLITE_NULL, /* 0x2d (not possible) */
  77918. SQLITE_FLOAT, /* 0x2e (not possible) */
  77919. SQLITE_NULL, /* 0x2f (not possible) */
  77920. SQLITE_BLOB, /* 0x30 (not possible) */
  77921. SQLITE_NULL, /* 0x31 (not possible) */
  77922. SQLITE_TEXT, /* 0x32 (not possible) */
  77923. SQLITE_NULL, /* 0x33 (not possible) */
  77924. SQLITE_FLOAT, /* 0x34 (not possible) */
  77925. SQLITE_NULL, /* 0x35 (not possible) */
  77926. SQLITE_FLOAT, /* 0x36 (not possible) */
  77927. SQLITE_NULL, /* 0x37 (not possible) */
  77928. SQLITE_FLOAT, /* 0x38 (not possible) */
  77929. SQLITE_NULL, /* 0x39 (not possible) */
  77930. SQLITE_FLOAT, /* 0x3a (not possible) */
  77931. SQLITE_NULL, /* 0x3b (not possible) */
  77932. SQLITE_FLOAT, /* 0x3c (not possible) */
  77933. SQLITE_NULL, /* 0x3d (not possible) */
  77934. SQLITE_FLOAT, /* 0x3e (not possible) */
  77935. SQLITE_NULL, /* 0x3f (not possible) */
  77936. };
  77937. #ifdef SQLITE_DEBUG
  77938. {
  77939. int eType = SQLITE_BLOB;
  77940. if( pVal->flags & MEM_Null ){
  77941. eType = SQLITE_NULL;
  77942. }else if( pVal->flags & (MEM_Real|MEM_IntReal) ){
  77943. eType = SQLITE_FLOAT;
  77944. }else if( pVal->flags & MEM_Int ){
  77945. eType = SQLITE_INTEGER;
  77946. }else if( pVal->flags & MEM_Str ){
  77947. eType = SQLITE_TEXT;
  77948. }
  77949. assert( eType == aType[pVal->flags&MEM_AffMask] );
  77950. }
  77951. #endif
  77952. return aType[pVal->flags&MEM_AffMask];
  77953. }
  77954. /* Return true if a parameter to xUpdate represents an unchanged column */
  77955. SQLITE_API int sqlite3_value_nochange(sqlite3_value *pVal){
  77956. return (pVal->flags&(MEM_Null|MEM_Zero))==(MEM_Null|MEM_Zero);
  77957. }
  77958. /* Return true if a parameter value originated from an sqlite3_bind() */
  77959. SQLITE_API int sqlite3_value_frombind(sqlite3_value *pVal){
  77960. return (pVal->flags&MEM_FromBind)!=0;
  77961. }
  77962. /* Make a copy of an sqlite3_value object
  77963. */
  77964. SQLITE_API sqlite3_value *sqlite3_value_dup(const sqlite3_value *pOrig){
  77965. sqlite3_value *pNew;
  77966. if( pOrig==0 ) return 0;
  77967. pNew = sqlite3_malloc( sizeof(*pNew) );
  77968. if( pNew==0 ) return 0;
  77969. memset(pNew, 0, sizeof(*pNew));
  77970. memcpy(pNew, pOrig, MEMCELLSIZE);
  77971. pNew->flags &= ~MEM_Dyn;
  77972. pNew->db = 0;
  77973. if( pNew->flags&(MEM_Str|MEM_Blob) ){
  77974. pNew->flags &= ~(MEM_Static|MEM_Dyn);
  77975. pNew->flags |= MEM_Ephem;
  77976. if( sqlite3VdbeMemMakeWriteable(pNew)!=SQLITE_OK ){
  77977. sqlite3ValueFree(pNew);
  77978. pNew = 0;
  77979. }
  77980. }
  77981. return pNew;
  77982. }
  77983. /* Destroy an sqlite3_value object previously obtained from
  77984. ** sqlite3_value_dup().
  77985. */
  77986. SQLITE_API void sqlite3_value_free(sqlite3_value *pOld){
  77987. sqlite3ValueFree(pOld);
  77988. }
  77989. /**************************** sqlite3_result_ *******************************
  77990. ** The following routines are used by user-defined functions to specify
  77991. ** the function result.
  77992. **
  77993. ** The setStrOrError() function calls sqlite3VdbeMemSetStr() to store the
  77994. ** result as a string or blob but if the string or blob is too large, it
  77995. ** then sets the error code to SQLITE_TOOBIG
  77996. **
  77997. ** The invokeValueDestructor(P,X) routine invokes destructor function X()
  77998. ** on value P is not going to be used and need to be destroyed.
  77999. */
  78000. static void setResultStrOrError(
  78001. sqlite3_context *pCtx, /* Function context */
  78002. const char *z, /* String pointer */
  78003. int n, /* Bytes in string, or negative */
  78004. u8 enc, /* Encoding of z. 0 for BLOBs */
  78005. void (*xDel)(void*) /* Destructor function */
  78006. ){
  78007. if( sqlite3VdbeMemSetStr(pCtx->pOut, z, n, enc, xDel)==SQLITE_TOOBIG ){
  78008. sqlite3_result_error_toobig(pCtx);
  78009. }
  78010. }
  78011. static int invokeValueDestructor(
  78012. const void *p, /* Value to destroy */
  78013. void (*xDel)(void*), /* The destructor */
  78014. sqlite3_context *pCtx /* Set a SQLITE_TOOBIG error if no NULL */
  78015. ){
  78016. assert( xDel!=SQLITE_DYNAMIC );
  78017. if( xDel==0 ){
  78018. /* noop */
  78019. }else if( xDel==SQLITE_TRANSIENT ){
  78020. /* noop */
  78021. }else{
  78022. xDel((void*)p);
  78023. }
  78024. if( pCtx ) sqlite3_result_error_toobig(pCtx);
  78025. return SQLITE_TOOBIG;
  78026. }
  78027. SQLITE_API void sqlite3_result_blob(
  78028. sqlite3_context *pCtx,
  78029. const void *z,
  78030. int n,
  78031. void (*xDel)(void *)
  78032. ){
  78033. assert( n>=0 );
  78034. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  78035. setResultStrOrError(pCtx, z, n, 0, xDel);
  78036. }
  78037. SQLITE_API void sqlite3_result_blob64(
  78038. sqlite3_context *pCtx,
  78039. const void *z,
  78040. sqlite3_uint64 n,
  78041. void (*xDel)(void *)
  78042. ){
  78043. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  78044. assert( xDel!=SQLITE_DYNAMIC );
  78045. if( n>0x7fffffff ){
  78046. (void)invokeValueDestructor(z, xDel, pCtx);
  78047. }else{
  78048. setResultStrOrError(pCtx, z, (int)n, 0, xDel);
  78049. }
  78050. }
  78051. SQLITE_API void sqlite3_result_double(sqlite3_context *pCtx, double rVal){
  78052. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  78053. sqlite3VdbeMemSetDouble(pCtx->pOut, rVal);
  78054. }
  78055. SQLITE_API void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
  78056. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  78057. pCtx->isError = SQLITE_ERROR;
  78058. sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
  78059. }
  78060. #ifndef SQLITE_OMIT_UTF16
  78061. SQLITE_API void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
  78062. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  78063. pCtx->isError = SQLITE_ERROR;
  78064. sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
  78065. }
  78066. #endif
  78067. SQLITE_API void sqlite3_result_int(sqlite3_context *pCtx, int iVal){
  78068. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  78069. sqlite3VdbeMemSetInt64(pCtx->pOut, (i64)iVal);
  78070. }
  78071. SQLITE_API void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
  78072. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  78073. sqlite3VdbeMemSetInt64(pCtx->pOut, iVal);
  78074. }
  78075. SQLITE_API void sqlite3_result_null(sqlite3_context *pCtx){
  78076. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  78077. sqlite3VdbeMemSetNull(pCtx->pOut);
  78078. }
  78079. SQLITE_API void sqlite3_result_pointer(
  78080. sqlite3_context *pCtx,
  78081. void *pPtr,
  78082. const char *zPType,
  78083. void (*xDestructor)(void*)
  78084. ){
  78085. Mem *pOut = pCtx->pOut;
  78086. assert( sqlite3_mutex_held(pOut->db->mutex) );
  78087. sqlite3VdbeMemRelease(pOut);
  78088. pOut->flags = MEM_Null;
  78089. sqlite3VdbeMemSetPointer(pOut, pPtr, zPType, xDestructor);
  78090. }
  78091. SQLITE_API void sqlite3_result_subtype(sqlite3_context *pCtx, unsigned int eSubtype){
  78092. Mem *pOut = pCtx->pOut;
  78093. assert( sqlite3_mutex_held(pOut->db->mutex) );
  78094. pOut->eSubtype = eSubtype & 0xff;
  78095. pOut->flags |= MEM_Subtype;
  78096. }
  78097. SQLITE_API void sqlite3_result_text(
  78098. sqlite3_context *pCtx,
  78099. const char *z,
  78100. int n,
  78101. void (*xDel)(void *)
  78102. ){
  78103. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  78104. setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel);
  78105. }
  78106. SQLITE_API void sqlite3_result_text64(
  78107. sqlite3_context *pCtx,
  78108. const char *z,
  78109. sqlite3_uint64 n,
  78110. void (*xDel)(void *),
  78111. unsigned char enc
  78112. ){
  78113. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  78114. assert( xDel!=SQLITE_DYNAMIC );
  78115. if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE;
  78116. if( n>0x7fffffff ){
  78117. (void)invokeValueDestructor(z, xDel, pCtx);
  78118. }else{
  78119. setResultStrOrError(pCtx, z, (int)n, enc, xDel);
  78120. }
  78121. }
  78122. #ifndef SQLITE_OMIT_UTF16
  78123. SQLITE_API void sqlite3_result_text16(
  78124. sqlite3_context *pCtx,
  78125. const void *z,
  78126. int n,
  78127. void (*xDel)(void *)
  78128. ){
  78129. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  78130. setResultStrOrError(pCtx, z, n, SQLITE_UTF16NATIVE, xDel);
  78131. }
  78132. SQLITE_API void sqlite3_result_text16be(
  78133. sqlite3_context *pCtx,
  78134. const void *z,
  78135. int n,
  78136. void (*xDel)(void *)
  78137. ){
  78138. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  78139. setResultStrOrError(pCtx, z, n, SQLITE_UTF16BE, xDel);
  78140. }
  78141. SQLITE_API void sqlite3_result_text16le(
  78142. sqlite3_context *pCtx,
  78143. const void *z,
  78144. int n,
  78145. void (*xDel)(void *)
  78146. ){
  78147. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  78148. setResultStrOrError(pCtx, z, n, SQLITE_UTF16LE, xDel);
  78149. }
  78150. #endif /* SQLITE_OMIT_UTF16 */
  78151. SQLITE_API void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
  78152. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  78153. sqlite3VdbeMemCopy(pCtx->pOut, pValue);
  78154. }
  78155. SQLITE_API void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
  78156. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  78157. sqlite3VdbeMemSetZeroBlob(pCtx->pOut, n);
  78158. }
  78159. SQLITE_API int sqlite3_result_zeroblob64(sqlite3_context *pCtx, u64 n){
  78160. Mem *pOut = pCtx->pOut;
  78161. assert( sqlite3_mutex_held(pOut->db->mutex) );
  78162. if( n>(u64)pOut->db->aLimit[SQLITE_LIMIT_LENGTH] ){
  78163. return SQLITE_TOOBIG;
  78164. }
  78165. sqlite3VdbeMemSetZeroBlob(pCtx->pOut, (int)n);
  78166. return SQLITE_OK;
  78167. }
  78168. SQLITE_API void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
  78169. pCtx->isError = errCode ? errCode : -1;
  78170. #ifdef SQLITE_DEBUG
  78171. if( pCtx->pVdbe ) pCtx->pVdbe->rcApp = errCode;
  78172. #endif
  78173. if( pCtx->pOut->flags & MEM_Null ){
  78174. sqlite3VdbeMemSetStr(pCtx->pOut, sqlite3ErrStr(errCode), -1,
  78175. SQLITE_UTF8, SQLITE_STATIC);
  78176. }
  78177. }
  78178. /* Force an SQLITE_TOOBIG error. */
  78179. SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){
  78180. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  78181. pCtx->isError = SQLITE_TOOBIG;
  78182. sqlite3VdbeMemSetStr(pCtx->pOut, "string or blob too big", -1,
  78183. SQLITE_UTF8, SQLITE_STATIC);
  78184. }
  78185. /* An SQLITE_NOMEM error. */
  78186. SQLITE_API void sqlite3_result_error_nomem(sqlite3_context *pCtx){
  78187. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  78188. sqlite3VdbeMemSetNull(pCtx->pOut);
  78189. pCtx->isError = SQLITE_NOMEM_BKPT;
  78190. sqlite3OomFault(pCtx->pOut->db);
  78191. }
  78192. #ifndef SQLITE_UNTESTABLE
  78193. /* Force the INT64 value currently stored as the result to be
  78194. ** a MEM_IntReal value. See the SQLITE_TESTCTRL_RESULT_INTREAL
  78195. ** test-control.
  78196. */
  78197. SQLITE_PRIVATE void sqlite3ResultIntReal(sqlite3_context *pCtx){
  78198. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  78199. if( pCtx->pOut->flags & MEM_Int ){
  78200. pCtx->pOut->flags &= ~MEM_Int;
  78201. pCtx->pOut->flags |= MEM_IntReal;
  78202. }
  78203. }
  78204. #endif
  78205. /*
  78206. ** This function is called after a transaction has been committed. It
  78207. ** invokes callbacks registered with sqlite3_wal_hook() as required.
  78208. */
  78209. static int doWalCallbacks(sqlite3 *db){
  78210. int rc = SQLITE_OK;
  78211. #ifndef SQLITE_OMIT_WAL
  78212. int i;
  78213. for(i=0; i<db->nDb; i++){
  78214. Btree *pBt = db->aDb[i].pBt;
  78215. if( pBt ){
  78216. int nEntry;
  78217. sqlite3BtreeEnter(pBt);
  78218. nEntry = sqlite3PagerWalCallback(sqlite3BtreePager(pBt));
  78219. sqlite3BtreeLeave(pBt);
  78220. if( nEntry>0 && db->xWalCallback && rc==SQLITE_OK ){
  78221. rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zDbSName, nEntry);
  78222. }
  78223. }
  78224. }
  78225. #endif
  78226. return rc;
  78227. }
  78228. /*
  78229. ** Execute the statement pStmt, either until a row of data is ready, the
  78230. ** statement is completely executed or an error occurs.
  78231. **
  78232. ** This routine implements the bulk of the logic behind the sqlite_step()
  78233. ** API. The only thing omitted is the automatic recompile if a
  78234. ** schema change has occurred. That detail is handled by the
  78235. ** outer sqlite3_step() wrapper procedure.
  78236. */
  78237. static int sqlite3Step(Vdbe *p){
  78238. sqlite3 *db;
  78239. int rc;
  78240. assert(p);
  78241. if( p->magic!=VDBE_MAGIC_RUN ){
  78242. /* We used to require that sqlite3_reset() be called before retrying
  78243. ** sqlite3_step() after any error or after SQLITE_DONE. But beginning
  78244. ** with version 3.7.0, we changed this so that sqlite3_reset() would
  78245. ** be called automatically instead of throwing the SQLITE_MISUSE error.
  78246. ** This "automatic-reset" change is not technically an incompatibility,
  78247. ** since any application that receives an SQLITE_MISUSE is broken by
  78248. ** definition.
  78249. **
  78250. ** Nevertheless, some published applications that were originally written
  78251. ** for version 3.6.23 or earlier do in fact depend on SQLITE_MISUSE
  78252. ** returns, and those were broken by the automatic-reset change. As a
  78253. ** a work-around, the SQLITE_OMIT_AUTORESET compile-time restores the
  78254. ** legacy behavior of returning SQLITE_MISUSE for cases where the
  78255. ** previous sqlite3_step() returned something other than a SQLITE_LOCKED
  78256. ** or SQLITE_BUSY error.
  78257. */
  78258. #ifdef SQLITE_OMIT_AUTORESET
  78259. if( (rc = p->rc&0xff)==SQLITE_BUSY || rc==SQLITE_LOCKED ){
  78260. sqlite3_reset((sqlite3_stmt*)p);
  78261. }else{
  78262. return SQLITE_MISUSE_BKPT;
  78263. }
  78264. #else
  78265. sqlite3_reset((sqlite3_stmt*)p);
  78266. #endif
  78267. }
  78268. /* Check that malloc() has not failed. If it has, return early. */
  78269. db = p->db;
  78270. if( db->mallocFailed ){
  78271. p->rc = SQLITE_NOMEM;
  78272. return SQLITE_NOMEM_BKPT;
  78273. }
  78274. if( p->pc<0 && p->expired ){
  78275. p->rc = SQLITE_SCHEMA;
  78276. rc = SQLITE_ERROR;
  78277. goto end_of_step;
  78278. }
  78279. if( p->pc<0 ){
  78280. /* If there are no other statements currently running, then
  78281. ** reset the interrupt flag. This prevents a call to sqlite3_interrupt
  78282. ** from interrupting a statement that has not yet started.
  78283. */
  78284. if( db->nVdbeActive==0 ){
  78285. AtomicStore(&db->u1.isInterrupted, 0);
  78286. }
  78287. assert( db->nVdbeWrite>0 || db->autoCommit==0
  78288. || (db->nDeferredCons==0 && db->nDeferredImmCons==0)
  78289. );
  78290. #ifndef SQLITE_OMIT_TRACE
  78291. if( (db->mTrace & (SQLITE_TRACE_PROFILE|SQLITE_TRACE_XPROFILE))!=0
  78292. && !db->init.busy && p->zSql ){
  78293. sqlite3OsCurrentTimeInt64(db->pVfs, &p->startTime);
  78294. }else{
  78295. assert( p->startTime==0 );
  78296. }
  78297. #endif
  78298. db->nVdbeActive++;
  78299. if( p->readOnly==0 ) db->nVdbeWrite++;
  78300. if( p->bIsReader ) db->nVdbeRead++;
  78301. p->pc = 0;
  78302. }
  78303. #ifdef SQLITE_DEBUG
  78304. p->rcApp = SQLITE_OK;
  78305. #endif
  78306. #ifndef SQLITE_OMIT_EXPLAIN
  78307. if( p->explain ){
  78308. rc = sqlite3VdbeList(p);
  78309. }else
  78310. #endif /* SQLITE_OMIT_EXPLAIN */
  78311. {
  78312. db->nVdbeExec++;
  78313. rc = sqlite3VdbeExec(p);
  78314. db->nVdbeExec--;
  78315. }
  78316. if( rc!=SQLITE_ROW ){
  78317. #ifndef SQLITE_OMIT_TRACE
  78318. /* If the statement completed successfully, invoke the profile callback */
  78319. checkProfileCallback(db, p);
  78320. #endif
  78321. if( rc==SQLITE_DONE && db->autoCommit ){
  78322. assert( p->rc==SQLITE_OK );
  78323. p->rc = doWalCallbacks(db);
  78324. if( p->rc!=SQLITE_OK ){
  78325. rc = SQLITE_ERROR;
  78326. }
  78327. }
  78328. }
  78329. db->errCode = rc;
  78330. if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
  78331. p->rc = SQLITE_NOMEM_BKPT;
  78332. }
  78333. end_of_step:
  78334. /* At this point local variable rc holds the value that should be
  78335. ** returned if this statement was compiled using the legacy
  78336. ** sqlite3_prepare() interface. According to the docs, this can only
  78337. ** be one of the values in the first assert() below. Variable p->rc
  78338. ** contains the value that would be returned if sqlite3_finalize()
  78339. ** were called on statement p.
  78340. */
  78341. assert( rc==SQLITE_ROW || rc==SQLITE_DONE || rc==SQLITE_ERROR
  78342. || (rc&0xff)==SQLITE_BUSY || rc==SQLITE_MISUSE
  78343. );
  78344. assert( (p->rc!=SQLITE_ROW && p->rc!=SQLITE_DONE) || p->rc==p->rcApp );
  78345. if( rc!=SQLITE_ROW
  78346. && rc!=SQLITE_DONE
  78347. && (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0
  78348. ){
  78349. /* If this statement was prepared using saved SQL and an
  78350. ** error has occurred, then return the error code in p->rc to the
  78351. ** caller. Set the error code in the database handle to the same value.
  78352. */
  78353. rc = sqlite3VdbeTransferError(p);
  78354. }
  78355. return (rc&db->errMask);
  78356. }
  78357. /*
  78358. ** This is the top-level implementation of sqlite3_step(). Call
  78359. ** sqlite3Step() to do most of the work. If a schema error occurs,
  78360. ** call sqlite3Reprepare() and try again.
  78361. */
  78362. SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){
  78363. int rc = SQLITE_OK; /* Result from sqlite3Step() */
  78364. Vdbe *v = (Vdbe*)pStmt; /* the prepared statement */
  78365. int cnt = 0; /* Counter to prevent infinite loop of reprepares */
  78366. sqlite3 *db; /* The database connection */
  78367. if( vdbeSafetyNotNull(v) ){
  78368. return SQLITE_MISUSE_BKPT;
  78369. }
  78370. db = v->db;
  78371. sqlite3_mutex_enter(db->mutex);
  78372. v->doingRerun = 0;
  78373. while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
  78374. && cnt++ < SQLITE_MAX_SCHEMA_RETRY ){
  78375. int savedPc = v->pc;
  78376. rc = sqlite3Reprepare(v);
  78377. if( rc!=SQLITE_OK ){
  78378. /* This case occurs after failing to recompile an sql statement.
  78379. ** The error message from the SQL compiler has already been loaded
  78380. ** into the database handle. This block copies the error message
  78381. ** from the database handle into the statement and sets the statement
  78382. ** program counter to 0 to ensure that when the statement is
  78383. ** finalized or reset the parser error message is available via
  78384. ** sqlite3_errmsg() and sqlite3_errcode().
  78385. */
  78386. const char *zErr = (const char *)sqlite3_value_text(db->pErr);
  78387. sqlite3DbFree(db, v->zErrMsg);
  78388. if( !db->mallocFailed ){
  78389. v->zErrMsg = sqlite3DbStrDup(db, zErr);
  78390. v->rc = rc = sqlite3ApiExit(db, rc);
  78391. } else {
  78392. v->zErrMsg = 0;
  78393. v->rc = rc = SQLITE_NOMEM_BKPT;
  78394. }
  78395. break;
  78396. }
  78397. sqlite3_reset(pStmt);
  78398. if( savedPc>=0 ) v->doingRerun = 1;
  78399. assert( v->expired==0 );
  78400. }
  78401. sqlite3_mutex_leave(db->mutex);
  78402. return rc;
  78403. }
  78404. /*
  78405. ** Extract the user data from a sqlite3_context structure and return a
  78406. ** pointer to it.
  78407. */
  78408. SQLITE_API void *sqlite3_user_data(sqlite3_context *p){
  78409. assert( p && p->pFunc );
  78410. return p->pFunc->pUserData;
  78411. }
  78412. /*
  78413. ** Extract the user data from a sqlite3_context structure and return a
  78414. ** pointer to it.
  78415. **
  78416. ** IMPLEMENTATION-OF: R-46798-50301 The sqlite3_context_db_handle() interface
  78417. ** returns a copy of the pointer to the database connection (the 1st
  78418. ** parameter) of the sqlite3_create_function() and
  78419. ** sqlite3_create_function16() routines that originally registered the
  78420. ** application defined function.
  78421. */
  78422. SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){
  78423. assert( p && p->pOut );
  78424. return p->pOut->db;
  78425. }
  78426. /*
  78427. ** If this routine is invoked from within an xColumn method of a virtual
  78428. ** table, then it returns true if and only if the the call is during an
  78429. ** UPDATE operation and the value of the column will not be modified
  78430. ** by the UPDATE.
  78431. **
  78432. ** If this routine is called from any context other than within the
  78433. ** xColumn method of a virtual table, then the return value is meaningless
  78434. ** and arbitrary.
  78435. **
  78436. ** Virtual table implements might use this routine to optimize their
  78437. ** performance by substituting a NULL result, or some other light-weight
  78438. ** value, as a signal to the xUpdate routine that the column is unchanged.
  78439. */
  78440. SQLITE_API int sqlite3_vtab_nochange(sqlite3_context *p){
  78441. assert( p );
  78442. return sqlite3_value_nochange(p->pOut);
  78443. }
  78444. /*
  78445. ** Return the current time for a statement. If the current time
  78446. ** is requested more than once within the same run of a single prepared
  78447. ** statement, the exact same time is returned for each invocation regardless
  78448. ** of the amount of time that elapses between invocations. In other words,
  78449. ** the time returned is always the time of the first call.
  78450. */
  78451. SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context *p){
  78452. int rc;
  78453. #ifndef SQLITE_ENABLE_STAT4
  78454. sqlite3_int64 *piTime = &p->pVdbe->iCurrentTime;
  78455. assert( p->pVdbe!=0 );
  78456. #else
  78457. sqlite3_int64 iTime = 0;
  78458. sqlite3_int64 *piTime = p->pVdbe!=0 ? &p->pVdbe->iCurrentTime : &iTime;
  78459. #endif
  78460. if( *piTime==0 ){
  78461. rc = sqlite3OsCurrentTimeInt64(p->pOut->db->pVfs, piTime);
  78462. if( rc ) *piTime = 0;
  78463. }
  78464. return *piTime;
  78465. }
  78466. /*
  78467. ** Create a new aggregate context for p and return a pointer to
  78468. ** its pMem->z element.
  78469. */
  78470. static SQLITE_NOINLINE void *createAggContext(sqlite3_context *p, int nByte){
  78471. Mem *pMem = p->pMem;
  78472. assert( (pMem->flags & MEM_Agg)==0 );
  78473. if( nByte<=0 ){
  78474. sqlite3VdbeMemSetNull(pMem);
  78475. pMem->z = 0;
  78476. }else{
  78477. sqlite3VdbeMemClearAndResize(pMem, nByte);
  78478. pMem->flags = MEM_Agg;
  78479. pMem->u.pDef = p->pFunc;
  78480. if( pMem->z ){
  78481. memset(pMem->z, 0, nByte);
  78482. }
  78483. }
  78484. return (void*)pMem->z;
  78485. }
  78486. /*
  78487. ** Allocate or return the aggregate context for a user function. A new
  78488. ** context is allocated on the first call. Subsequent calls return the
  78489. ** same context that was returned on prior calls.
  78490. */
  78491. SQLITE_API void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){
  78492. assert( p && p->pFunc && p->pFunc->xFinalize );
  78493. assert( sqlite3_mutex_held(p->pOut->db->mutex) );
  78494. testcase( nByte<0 );
  78495. if( (p->pMem->flags & MEM_Agg)==0 ){
  78496. return createAggContext(p, nByte);
  78497. }else{
  78498. return (void*)p->pMem->z;
  78499. }
  78500. }
  78501. /*
  78502. ** Return the auxiliary data pointer, if any, for the iArg'th argument to
  78503. ** the user-function defined by pCtx.
  78504. **
  78505. ** The left-most argument is 0.
  78506. **
  78507. ** Undocumented behavior: If iArg is negative then access a cache of
  78508. ** auxiliary data pointers that is available to all functions within a
  78509. ** single prepared statement. The iArg values must match.
  78510. */
  78511. SQLITE_API void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
  78512. AuxData *pAuxData;
  78513. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  78514. #if SQLITE_ENABLE_STAT4
  78515. if( pCtx->pVdbe==0 ) return 0;
  78516. #else
  78517. assert( pCtx->pVdbe!=0 );
  78518. #endif
  78519. for(pAuxData=pCtx->pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNextAux){
  78520. if( pAuxData->iAuxArg==iArg && (pAuxData->iAuxOp==pCtx->iOp || iArg<0) ){
  78521. return pAuxData->pAux;
  78522. }
  78523. }
  78524. return 0;
  78525. }
  78526. /*
  78527. ** Set the auxiliary data pointer and delete function, for the iArg'th
  78528. ** argument to the user-function defined by pCtx. Any previous value is
  78529. ** deleted by calling the delete function specified when it was set.
  78530. **
  78531. ** The left-most argument is 0.
  78532. **
  78533. ** Undocumented behavior: If iArg is negative then make the data available
  78534. ** to all functions within the current prepared statement using iArg as an
  78535. ** access code.
  78536. */
  78537. SQLITE_API void sqlite3_set_auxdata(
  78538. sqlite3_context *pCtx,
  78539. int iArg,
  78540. void *pAux,
  78541. void (*xDelete)(void*)
  78542. ){
  78543. AuxData *pAuxData;
  78544. Vdbe *pVdbe = pCtx->pVdbe;
  78545. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  78546. #ifdef SQLITE_ENABLE_STAT4
  78547. if( pVdbe==0 ) goto failed;
  78548. #else
  78549. assert( pVdbe!=0 );
  78550. #endif
  78551. for(pAuxData=pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNextAux){
  78552. if( pAuxData->iAuxArg==iArg && (pAuxData->iAuxOp==pCtx->iOp || iArg<0) ){
  78553. break;
  78554. }
  78555. }
  78556. if( pAuxData==0 ){
  78557. pAuxData = sqlite3DbMallocZero(pVdbe->db, sizeof(AuxData));
  78558. if( !pAuxData ) goto failed;
  78559. pAuxData->iAuxOp = pCtx->iOp;
  78560. pAuxData->iAuxArg = iArg;
  78561. pAuxData->pNextAux = pVdbe->pAuxData;
  78562. pVdbe->pAuxData = pAuxData;
  78563. if( pCtx->isError==0 ) pCtx->isError = -1;
  78564. }else if( pAuxData->xDeleteAux ){
  78565. pAuxData->xDeleteAux(pAuxData->pAux);
  78566. }
  78567. pAuxData->pAux = pAux;
  78568. pAuxData->xDeleteAux = xDelete;
  78569. return;
  78570. failed:
  78571. if( xDelete ){
  78572. xDelete(pAux);
  78573. }
  78574. }
  78575. #ifndef SQLITE_OMIT_DEPRECATED
  78576. /*
  78577. ** Return the number of times the Step function of an aggregate has been
  78578. ** called.
  78579. **
  78580. ** This function is deprecated. Do not use it for new code. It is
  78581. ** provide only to avoid breaking legacy code. New aggregate function
  78582. ** implementations should keep their own counts within their aggregate
  78583. ** context.
  78584. */
  78585. SQLITE_API int sqlite3_aggregate_count(sqlite3_context *p){
  78586. assert( p && p->pMem && p->pFunc && p->pFunc->xFinalize );
  78587. return p->pMem->n;
  78588. }
  78589. #endif
  78590. /*
  78591. ** Return the number of columns in the result set for the statement pStmt.
  78592. */
  78593. SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt){
  78594. Vdbe *pVm = (Vdbe *)pStmt;
  78595. return pVm ? pVm->nResColumn : 0;
  78596. }
  78597. /*
  78598. ** Return the number of values available from the current row of the
  78599. ** currently executing statement pStmt.
  78600. */
  78601. SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt){
  78602. Vdbe *pVm = (Vdbe *)pStmt;
  78603. if( pVm==0 || pVm->pResultSet==0 ) return 0;
  78604. return pVm->nResColumn;
  78605. }
  78606. /*
  78607. ** Return a pointer to static memory containing an SQL NULL value.
  78608. */
  78609. static const Mem *columnNullValue(void){
  78610. /* Even though the Mem structure contains an element
  78611. ** of type i64, on certain architectures (x86) with certain compiler
  78612. ** switches (-Os), gcc may align this Mem object on a 4-byte boundary
  78613. ** instead of an 8-byte one. This all works fine, except that when
  78614. ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s
  78615. ** that a Mem structure is located on an 8-byte boundary. To prevent
  78616. ** these assert()s from failing, when building with SQLITE_DEBUG defined
  78617. ** using gcc, we force nullMem to be 8-byte aligned using the magical
  78618. ** __attribute__((aligned(8))) macro. */
  78619. static const Mem nullMem
  78620. #if defined(SQLITE_DEBUG) && defined(__GNUC__)
  78621. __attribute__((aligned(8)))
  78622. #endif
  78623. = {
  78624. /* .u = */ {0},
  78625. /* .flags = */ (u16)MEM_Null,
  78626. /* .enc = */ (u8)0,
  78627. /* .eSubtype = */ (u8)0,
  78628. /* .n = */ (int)0,
  78629. /* .z = */ (char*)0,
  78630. /* .zMalloc = */ (char*)0,
  78631. /* .szMalloc = */ (int)0,
  78632. /* .uTemp = */ (u32)0,
  78633. /* .db = */ (sqlite3*)0,
  78634. /* .xDel = */ (void(*)(void*))0,
  78635. #ifdef SQLITE_DEBUG
  78636. /* .pScopyFrom = */ (Mem*)0,
  78637. /* .mScopyFlags= */ 0,
  78638. #endif
  78639. };
  78640. return &nullMem;
  78641. }
  78642. /*
  78643. ** Check to see if column iCol of the given statement is valid. If
  78644. ** it is, return a pointer to the Mem for the value of that column.
  78645. ** If iCol is not valid, return a pointer to a Mem which has a value
  78646. ** of NULL.
  78647. */
  78648. static Mem *columnMem(sqlite3_stmt *pStmt, int i){
  78649. Vdbe *pVm;
  78650. Mem *pOut;
  78651. pVm = (Vdbe *)pStmt;
  78652. if( pVm==0 ) return (Mem*)columnNullValue();
  78653. assert( pVm->db );
  78654. sqlite3_mutex_enter(pVm->db->mutex);
  78655. if( pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
  78656. pOut = &pVm->pResultSet[i];
  78657. }else{
  78658. sqlite3Error(pVm->db, SQLITE_RANGE);
  78659. pOut = (Mem*)columnNullValue();
  78660. }
  78661. return pOut;
  78662. }
  78663. /*
  78664. ** This function is called after invoking an sqlite3_value_XXX function on a
  78665. ** column value (i.e. a value returned by evaluating an SQL expression in the
  78666. ** select list of a SELECT statement) that may cause a malloc() failure. If
  78667. ** malloc() has failed, the threads mallocFailed flag is cleared and the result
  78668. ** code of statement pStmt set to SQLITE_NOMEM.
  78669. **
  78670. ** Specifically, this is called from within:
  78671. **
  78672. ** sqlite3_column_int()
  78673. ** sqlite3_column_int64()
  78674. ** sqlite3_column_text()
  78675. ** sqlite3_column_text16()
  78676. ** sqlite3_column_real()
  78677. ** sqlite3_column_bytes()
  78678. ** sqlite3_column_bytes16()
  78679. ** sqiite3_column_blob()
  78680. */
  78681. static void columnMallocFailure(sqlite3_stmt *pStmt)
  78682. {
  78683. /* If malloc() failed during an encoding conversion within an
  78684. ** sqlite3_column_XXX API, then set the return code of the statement to
  78685. ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
  78686. ** and _finalize() will return NOMEM.
  78687. */
  78688. Vdbe *p = (Vdbe *)pStmt;
  78689. if( p ){
  78690. assert( p->db!=0 );
  78691. assert( sqlite3_mutex_held(p->db->mutex) );
  78692. p->rc = sqlite3ApiExit(p->db, p->rc);
  78693. sqlite3_mutex_leave(p->db->mutex);
  78694. }
  78695. }
  78696. /**************************** sqlite3_column_ *******************************
  78697. ** The following routines are used to access elements of the current row
  78698. ** in the result set.
  78699. */
  78700. SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
  78701. const void *val;
  78702. val = sqlite3_value_blob( columnMem(pStmt,i) );
  78703. /* Even though there is no encoding conversion, value_blob() might
  78704. ** need to call malloc() to expand the result of a zeroblob()
  78705. ** expression.
  78706. */
  78707. columnMallocFailure(pStmt);
  78708. return val;
  78709. }
  78710. SQLITE_API int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
  78711. int val = sqlite3_value_bytes( columnMem(pStmt,i) );
  78712. columnMallocFailure(pStmt);
  78713. return val;
  78714. }
  78715. SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
  78716. int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
  78717. columnMallocFailure(pStmt);
  78718. return val;
  78719. }
  78720. SQLITE_API double sqlite3_column_double(sqlite3_stmt *pStmt, int i){
  78721. double val = sqlite3_value_double( columnMem(pStmt,i) );
  78722. columnMallocFailure(pStmt);
  78723. return val;
  78724. }
  78725. SQLITE_API int sqlite3_column_int(sqlite3_stmt *pStmt, int i){
  78726. int val = sqlite3_value_int( columnMem(pStmt,i) );
  78727. columnMallocFailure(pStmt);
  78728. return val;
  78729. }
  78730. SQLITE_API sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
  78731. sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
  78732. columnMallocFailure(pStmt);
  78733. return val;
  78734. }
  78735. SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){
  78736. const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
  78737. columnMallocFailure(pStmt);
  78738. return val;
  78739. }
  78740. SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){
  78741. Mem *pOut = columnMem(pStmt, i);
  78742. if( pOut->flags&MEM_Static ){
  78743. pOut->flags &= ~MEM_Static;
  78744. pOut->flags |= MEM_Ephem;
  78745. }
  78746. columnMallocFailure(pStmt);
  78747. return (sqlite3_value *)pOut;
  78748. }
  78749. #ifndef SQLITE_OMIT_UTF16
  78750. SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
  78751. const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
  78752. columnMallocFailure(pStmt);
  78753. return val;
  78754. }
  78755. #endif /* SQLITE_OMIT_UTF16 */
  78756. SQLITE_API int sqlite3_column_type(sqlite3_stmt *pStmt, int i){
  78757. int iType = sqlite3_value_type( columnMem(pStmt,i) );
  78758. columnMallocFailure(pStmt);
  78759. return iType;
  78760. }
  78761. /*
  78762. ** Convert the N-th element of pStmt->pColName[] into a string using
  78763. ** xFunc() then return that string. If N is out of range, return 0.
  78764. **
  78765. ** There are up to 5 names for each column. useType determines which
  78766. ** name is returned. Here are the names:
  78767. **
  78768. ** 0 The column name as it should be displayed for output
  78769. ** 1 The datatype name for the column
  78770. ** 2 The name of the database that the column derives from
  78771. ** 3 The name of the table that the column derives from
  78772. ** 4 The name of the table column that the result column derives from
  78773. **
  78774. ** If the result is not a simple column reference (if it is an expression
  78775. ** or a constant) then useTypes 2, 3, and 4 return NULL.
  78776. */
  78777. static const void *columnName(
  78778. sqlite3_stmt *pStmt, /* The statement */
  78779. int N, /* Which column to get the name for */
  78780. int useUtf16, /* True to return the name as UTF16 */
  78781. int useType /* What type of name */
  78782. ){
  78783. const void *ret;
  78784. Vdbe *p;
  78785. int n;
  78786. sqlite3 *db;
  78787. #ifdef SQLITE_ENABLE_API_ARMOR
  78788. if( pStmt==0 ){
  78789. (void)SQLITE_MISUSE_BKPT;
  78790. return 0;
  78791. }
  78792. #endif
  78793. ret = 0;
  78794. p = (Vdbe *)pStmt;
  78795. db = p->db;
  78796. assert( db!=0 );
  78797. n = sqlite3_column_count(pStmt);
  78798. if( N<n && N>=0 ){
  78799. N += useType*n;
  78800. sqlite3_mutex_enter(db->mutex);
  78801. assert( db->mallocFailed==0 );
  78802. #ifndef SQLITE_OMIT_UTF16
  78803. if( useUtf16 ){
  78804. ret = sqlite3_value_text16((sqlite3_value*)&p->aColName[N]);
  78805. }else
  78806. #endif
  78807. {
  78808. ret = sqlite3_value_text((sqlite3_value*)&p->aColName[N]);
  78809. }
  78810. /* A malloc may have failed inside of the _text() call. If this
  78811. ** is the case, clear the mallocFailed flag and return NULL.
  78812. */
  78813. if( db->mallocFailed ){
  78814. sqlite3OomClear(db);
  78815. ret = 0;
  78816. }
  78817. sqlite3_mutex_leave(db->mutex);
  78818. }
  78819. return ret;
  78820. }
  78821. /*
  78822. ** Return the name of the Nth column of the result set returned by SQL
  78823. ** statement pStmt.
  78824. */
  78825. SQLITE_API const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){
  78826. return columnName(pStmt, N, 0, COLNAME_NAME);
  78827. }
  78828. #ifndef SQLITE_OMIT_UTF16
  78829. SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
  78830. return columnName(pStmt, N, 1, COLNAME_NAME);
  78831. }
  78832. #endif
  78833. /*
  78834. ** Constraint: If you have ENABLE_COLUMN_METADATA then you must
  78835. ** not define OMIT_DECLTYPE.
  78836. */
  78837. #if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
  78838. # error "Must not define both SQLITE_OMIT_DECLTYPE \
  78839. and SQLITE_ENABLE_COLUMN_METADATA"
  78840. #endif
  78841. #ifndef SQLITE_OMIT_DECLTYPE
  78842. /*
  78843. ** Return the column declaration type (if applicable) of the 'i'th column
  78844. ** of the result set of SQL statement pStmt.
  78845. */
  78846. SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
  78847. return columnName(pStmt, N, 0, COLNAME_DECLTYPE);
  78848. }
  78849. #ifndef SQLITE_OMIT_UTF16
  78850. SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
  78851. return columnName(pStmt, N, 1, COLNAME_DECLTYPE);
  78852. }
  78853. #endif /* SQLITE_OMIT_UTF16 */
  78854. #endif /* SQLITE_OMIT_DECLTYPE */
  78855. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  78856. /*
  78857. ** Return the name of the database from which a result column derives.
  78858. ** NULL is returned if the result column is an expression or constant or
  78859. ** anything else which is not an unambiguous reference to a database column.
  78860. */
  78861. SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
  78862. return columnName(pStmt, N, 0, COLNAME_DATABASE);
  78863. }
  78864. #ifndef SQLITE_OMIT_UTF16
  78865. SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
  78866. return columnName(pStmt, N, 1, COLNAME_DATABASE);
  78867. }
  78868. #endif /* SQLITE_OMIT_UTF16 */
  78869. /*
  78870. ** Return the name of the table from which a result column derives.
  78871. ** NULL is returned if the result column is an expression or constant or
  78872. ** anything else which is not an unambiguous reference to a database column.
  78873. */
  78874. SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
  78875. return columnName(pStmt, N, 0, COLNAME_TABLE);
  78876. }
  78877. #ifndef SQLITE_OMIT_UTF16
  78878. SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
  78879. return columnName(pStmt, N, 1, COLNAME_TABLE);
  78880. }
  78881. #endif /* SQLITE_OMIT_UTF16 */
  78882. /*
  78883. ** Return the name of the table column from which a result column derives.
  78884. ** NULL is returned if the result column is an expression or constant or
  78885. ** anything else which is not an unambiguous reference to a database column.
  78886. */
  78887. SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
  78888. return columnName(pStmt, N, 0, COLNAME_COLUMN);
  78889. }
  78890. #ifndef SQLITE_OMIT_UTF16
  78891. SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
  78892. return columnName(pStmt, N, 1, COLNAME_COLUMN);
  78893. }
  78894. #endif /* SQLITE_OMIT_UTF16 */
  78895. #endif /* SQLITE_ENABLE_COLUMN_METADATA */
  78896. /******************************* sqlite3_bind_ ***************************
  78897. **
  78898. ** Routines used to attach values to wildcards in a compiled SQL statement.
  78899. */
  78900. /*
  78901. ** Unbind the value bound to variable i in virtual machine p. This is the
  78902. ** the same as binding a NULL value to the column. If the "i" parameter is
  78903. ** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
  78904. **
  78905. ** A successful evaluation of this routine acquires the mutex on p.
  78906. ** the mutex is released if any kind of error occurs.
  78907. **
  78908. ** The error code stored in database p->db is overwritten with the return
  78909. ** value in any case.
  78910. */
  78911. static int vdbeUnbind(Vdbe *p, int i){
  78912. Mem *pVar;
  78913. if( vdbeSafetyNotNull(p) ){
  78914. return SQLITE_MISUSE_BKPT;
  78915. }
  78916. sqlite3_mutex_enter(p->db->mutex);
  78917. if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
  78918. sqlite3Error(p->db, SQLITE_MISUSE);
  78919. sqlite3_mutex_leave(p->db->mutex);
  78920. sqlite3_log(SQLITE_MISUSE,
  78921. "bind on a busy prepared statement: [%s]", p->zSql);
  78922. return SQLITE_MISUSE_BKPT;
  78923. }
  78924. if( i<1 || i>p->nVar ){
  78925. sqlite3Error(p->db, SQLITE_RANGE);
  78926. sqlite3_mutex_leave(p->db->mutex);
  78927. return SQLITE_RANGE;
  78928. }
  78929. i--;
  78930. pVar = &p->aVar[i];
  78931. sqlite3VdbeMemRelease(pVar);
  78932. pVar->flags = MEM_Null;
  78933. p->db->errCode = SQLITE_OK;
  78934. /* If the bit corresponding to this variable in Vdbe.expmask is set, then
  78935. ** binding a new value to this variable invalidates the current query plan.
  78936. **
  78937. ** IMPLEMENTATION-OF: R-57496-20354 If the specific value bound to a host
  78938. ** parameter in the WHERE clause might influence the choice of query plan
  78939. ** for a statement, then the statement will be automatically recompiled,
  78940. ** as if there had been a schema change, on the first sqlite3_step() call
  78941. ** following any change to the bindings of that parameter.
  78942. */
  78943. assert( (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 || p->expmask==0 );
  78944. if( p->expmask!=0 && (p->expmask & (i>=31 ? 0x80000000 : (u32)1<<i))!=0 ){
  78945. p->expired = 1;
  78946. }
  78947. return SQLITE_OK;
  78948. }
  78949. /*
  78950. ** Bind a text or BLOB value.
  78951. */
  78952. static int bindText(
  78953. sqlite3_stmt *pStmt, /* The statement to bind against */
  78954. int i, /* Index of the parameter to bind */
  78955. const void *zData, /* Pointer to the data to be bound */
  78956. int nData, /* Number of bytes of data to be bound */
  78957. void (*xDel)(void*), /* Destructor for the data */
  78958. u8 encoding /* Encoding for the data */
  78959. ){
  78960. Vdbe *p = (Vdbe *)pStmt;
  78961. Mem *pVar;
  78962. int rc;
  78963. rc = vdbeUnbind(p, i);
  78964. if( rc==SQLITE_OK ){
  78965. if( zData!=0 ){
  78966. pVar = &p->aVar[i-1];
  78967. rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
  78968. if( rc==SQLITE_OK && encoding!=0 ){
  78969. rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
  78970. }
  78971. if( rc ){
  78972. sqlite3Error(p->db, rc);
  78973. rc = sqlite3ApiExit(p->db, rc);
  78974. }
  78975. }
  78976. sqlite3_mutex_leave(p->db->mutex);
  78977. }else if( xDel!=SQLITE_STATIC && xDel!=SQLITE_TRANSIENT ){
  78978. xDel((void*)zData);
  78979. }
  78980. return rc;
  78981. }
  78982. /*
  78983. ** Bind a blob value to an SQL statement variable.
  78984. */
  78985. SQLITE_API int sqlite3_bind_blob(
  78986. sqlite3_stmt *pStmt,
  78987. int i,
  78988. const void *zData,
  78989. int nData,
  78990. void (*xDel)(void*)
  78991. ){
  78992. #ifdef SQLITE_ENABLE_API_ARMOR
  78993. if( nData<0 ) return SQLITE_MISUSE_BKPT;
  78994. #endif
  78995. return bindText(pStmt, i, zData, nData, xDel, 0);
  78996. }
  78997. SQLITE_API int sqlite3_bind_blob64(
  78998. sqlite3_stmt *pStmt,
  78999. int i,
  79000. const void *zData,
  79001. sqlite3_uint64 nData,
  79002. void (*xDel)(void*)
  79003. ){
  79004. assert( xDel!=SQLITE_DYNAMIC );
  79005. if( nData>0x7fffffff ){
  79006. return invokeValueDestructor(zData, xDel, 0);
  79007. }else{
  79008. return bindText(pStmt, i, zData, (int)nData, xDel, 0);
  79009. }
  79010. }
  79011. SQLITE_API int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
  79012. int rc;
  79013. Vdbe *p = (Vdbe *)pStmt;
  79014. rc = vdbeUnbind(p, i);
  79015. if( rc==SQLITE_OK ){
  79016. sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
  79017. sqlite3_mutex_leave(p->db->mutex);
  79018. }
  79019. return rc;
  79020. }
  79021. SQLITE_API int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
  79022. return sqlite3_bind_int64(p, i, (i64)iValue);
  79023. }
  79024. SQLITE_API int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
  79025. int rc;
  79026. Vdbe *p = (Vdbe *)pStmt;
  79027. rc = vdbeUnbind(p, i);
  79028. if( rc==SQLITE_OK ){
  79029. sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
  79030. sqlite3_mutex_leave(p->db->mutex);
  79031. }
  79032. return rc;
  79033. }
  79034. SQLITE_API int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
  79035. int rc;
  79036. Vdbe *p = (Vdbe*)pStmt;
  79037. rc = vdbeUnbind(p, i);
  79038. if( rc==SQLITE_OK ){
  79039. sqlite3_mutex_leave(p->db->mutex);
  79040. }
  79041. return rc;
  79042. }
  79043. SQLITE_API int sqlite3_bind_pointer(
  79044. sqlite3_stmt *pStmt,
  79045. int i,
  79046. void *pPtr,
  79047. const char *zPTtype,
  79048. void (*xDestructor)(void*)
  79049. ){
  79050. int rc;
  79051. Vdbe *p = (Vdbe*)pStmt;
  79052. rc = vdbeUnbind(p, i);
  79053. if( rc==SQLITE_OK ){
  79054. sqlite3VdbeMemSetPointer(&p->aVar[i-1], pPtr, zPTtype, xDestructor);
  79055. sqlite3_mutex_leave(p->db->mutex);
  79056. }else if( xDestructor ){
  79057. xDestructor(pPtr);
  79058. }
  79059. return rc;
  79060. }
  79061. SQLITE_API int sqlite3_bind_text(
  79062. sqlite3_stmt *pStmt,
  79063. int i,
  79064. const char *zData,
  79065. int nData,
  79066. void (*xDel)(void*)
  79067. ){
  79068. return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
  79069. }
  79070. SQLITE_API int sqlite3_bind_text64(
  79071. sqlite3_stmt *pStmt,
  79072. int i,
  79073. const char *zData,
  79074. sqlite3_uint64 nData,
  79075. void (*xDel)(void*),
  79076. unsigned char enc
  79077. ){
  79078. assert( xDel!=SQLITE_DYNAMIC );
  79079. if( nData>0x7fffffff ){
  79080. return invokeValueDestructor(zData, xDel, 0);
  79081. }else{
  79082. if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE;
  79083. return bindText(pStmt, i, zData, (int)nData, xDel, enc);
  79084. }
  79085. }
  79086. #ifndef SQLITE_OMIT_UTF16
  79087. SQLITE_API int sqlite3_bind_text16(
  79088. sqlite3_stmt *pStmt,
  79089. int i,
  79090. const void *zData,
  79091. int nData,
  79092. void (*xDel)(void*)
  79093. ){
  79094. return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
  79095. }
  79096. #endif /* SQLITE_OMIT_UTF16 */
  79097. SQLITE_API int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
  79098. int rc;
  79099. switch( sqlite3_value_type((sqlite3_value*)pValue) ){
  79100. case SQLITE_INTEGER: {
  79101. rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);
  79102. break;
  79103. }
  79104. case SQLITE_FLOAT: {
  79105. rc = sqlite3_bind_double(pStmt, i, pValue->u.r);
  79106. break;
  79107. }
  79108. case SQLITE_BLOB: {
  79109. if( pValue->flags & MEM_Zero ){
  79110. rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);
  79111. }else{
  79112. rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);
  79113. }
  79114. break;
  79115. }
  79116. case SQLITE_TEXT: {
  79117. rc = bindText(pStmt,i, pValue->z, pValue->n, SQLITE_TRANSIENT,
  79118. pValue->enc);
  79119. break;
  79120. }
  79121. default: {
  79122. rc = sqlite3_bind_null(pStmt, i);
  79123. break;
  79124. }
  79125. }
  79126. return rc;
  79127. }
  79128. SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
  79129. int rc;
  79130. Vdbe *p = (Vdbe *)pStmt;
  79131. rc = vdbeUnbind(p, i);
  79132. if( rc==SQLITE_OK ){
  79133. sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
  79134. sqlite3_mutex_leave(p->db->mutex);
  79135. }
  79136. return rc;
  79137. }
  79138. SQLITE_API int sqlite3_bind_zeroblob64(sqlite3_stmt *pStmt, int i, sqlite3_uint64 n){
  79139. int rc;
  79140. Vdbe *p = (Vdbe *)pStmt;
  79141. sqlite3_mutex_enter(p->db->mutex);
  79142. if( n>(u64)p->db->aLimit[SQLITE_LIMIT_LENGTH] ){
  79143. rc = SQLITE_TOOBIG;
  79144. }else{
  79145. assert( (n & 0x7FFFFFFF)==n );
  79146. rc = sqlite3_bind_zeroblob(pStmt, i, n);
  79147. }
  79148. rc = sqlite3ApiExit(p->db, rc);
  79149. sqlite3_mutex_leave(p->db->mutex);
  79150. return rc;
  79151. }
  79152. /*
  79153. ** Return the number of wildcards that can be potentially bound to.
  79154. ** This routine is added to support DBD::SQLite.
  79155. */
  79156. SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
  79157. Vdbe *p = (Vdbe*)pStmt;
  79158. return p ? p->nVar : 0;
  79159. }
  79160. /*
  79161. ** Return the name of a wildcard parameter. Return NULL if the index
  79162. ** is out of range or if the wildcard is unnamed.
  79163. **
  79164. ** The result is always UTF-8.
  79165. */
  79166. SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
  79167. Vdbe *p = (Vdbe*)pStmt;
  79168. if( p==0 ) return 0;
  79169. return sqlite3VListNumToName(p->pVList, i);
  79170. }
  79171. /*
  79172. ** Given a wildcard parameter name, return the index of the variable
  79173. ** with that name. If there is no variable with the given name,
  79174. ** return 0.
  79175. */
  79176. SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){
  79177. if( p==0 || zName==0 ) return 0;
  79178. return sqlite3VListNameToNum(p->pVList, zName, nName);
  79179. }
  79180. SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
  79181. return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName));
  79182. }
  79183. /*
  79184. ** Transfer all bindings from the first statement over to the second.
  79185. */
  79186. SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
  79187. Vdbe *pFrom = (Vdbe*)pFromStmt;
  79188. Vdbe *pTo = (Vdbe*)pToStmt;
  79189. int i;
  79190. assert( pTo->db==pFrom->db );
  79191. assert( pTo->nVar==pFrom->nVar );
  79192. sqlite3_mutex_enter(pTo->db->mutex);
  79193. for(i=0; i<pFrom->nVar; i++){
  79194. sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
  79195. }
  79196. sqlite3_mutex_leave(pTo->db->mutex);
  79197. return SQLITE_OK;
  79198. }
  79199. #ifndef SQLITE_OMIT_DEPRECATED
  79200. /*
  79201. ** Deprecated external interface. Internal/core SQLite code
  79202. ** should call sqlite3TransferBindings.
  79203. **
  79204. ** It is misuse to call this routine with statements from different
  79205. ** database connections. But as this is a deprecated interface, we
  79206. ** will not bother to check for that condition.
  79207. **
  79208. ** If the two statements contain a different number of bindings, then
  79209. ** an SQLITE_ERROR is returned. Nothing else can go wrong, so otherwise
  79210. ** SQLITE_OK is returned.
  79211. */
  79212. SQLITE_API int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
  79213. Vdbe *pFrom = (Vdbe*)pFromStmt;
  79214. Vdbe *pTo = (Vdbe*)pToStmt;
  79215. if( pFrom->nVar!=pTo->nVar ){
  79216. return SQLITE_ERROR;
  79217. }
  79218. assert( (pTo->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 || pTo->expmask==0 );
  79219. if( pTo->expmask ){
  79220. pTo->expired = 1;
  79221. }
  79222. assert( (pFrom->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 || pFrom->expmask==0 );
  79223. if( pFrom->expmask ){
  79224. pFrom->expired = 1;
  79225. }
  79226. return sqlite3TransferBindings(pFromStmt, pToStmt);
  79227. }
  79228. #endif
  79229. /*
  79230. ** Return the sqlite3* database handle to which the prepared statement given
  79231. ** in the argument belongs. This is the same database handle that was
  79232. ** the first argument to the sqlite3_prepare() that was used to create
  79233. ** the statement in the first place.
  79234. */
  79235. SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){
  79236. return pStmt ? ((Vdbe*)pStmt)->db : 0;
  79237. }
  79238. /*
  79239. ** Return true if the prepared statement is guaranteed to not modify the
  79240. ** database.
  79241. */
  79242. SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt){
  79243. return pStmt ? ((Vdbe*)pStmt)->readOnly : 1;
  79244. }
  79245. /*
  79246. ** Return 1 if the statement is an EXPLAIN and return 2 if the
  79247. ** statement is an EXPLAIN QUERY PLAN
  79248. */
  79249. SQLITE_API int sqlite3_stmt_isexplain(sqlite3_stmt *pStmt){
  79250. return pStmt ? ((Vdbe*)pStmt)->explain : 0;
  79251. }
  79252. /*
  79253. ** Return true if the prepared statement is in need of being reset.
  79254. */
  79255. SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt *pStmt){
  79256. Vdbe *v = (Vdbe*)pStmt;
  79257. return v!=0 && v->magic==VDBE_MAGIC_RUN && v->pc>=0;
  79258. }
  79259. /*
  79260. ** Return a pointer to the next prepared statement after pStmt associated
  79261. ** with database connection pDb. If pStmt is NULL, return the first
  79262. ** prepared statement for the database connection. Return NULL if there
  79263. ** are no more.
  79264. */
  79265. SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){
  79266. sqlite3_stmt *pNext;
  79267. #ifdef SQLITE_ENABLE_API_ARMOR
  79268. if( !sqlite3SafetyCheckOk(pDb) ){
  79269. (void)SQLITE_MISUSE_BKPT;
  79270. return 0;
  79271. }
  79272. #endif
  79273. sqlite3_mutex_enter(pDb->mutex);
  79274. if( pStmt==0 ){
  79275. pNext = (sqlite3_stmt*)pDb->pVdbe;
  79276. }else{
  79277. pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext;
  79278. }
  79279. sqlite3_mutex_leave(pDb->mutex);
  79280. return pNext;
  79281. }
  79282. /*
  79283. ** Return the value of a status counter for a prepared statement
  79284. */
  79285. SQLITE_API int sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
  79286. Vdbe *pVdbe = (Vdbe*)pStmt;
  79287. u32 v;
  79288. #ifdef SQLITE_ENABLE_API_ARMOR
  79289. if( !pStmt
  79290. || (op!=SQLITE_STMTSTATUS_MEMUSED && (op<0||op>=ArraySize(pVdbe->aCounter)))
  79291. ){
  79292. (void)SQLITE_MISUSE_BKPT;
  79293. return 0;
  79294. }
  79295. #endif
  79296. if( op==SQLITE_STMTSTATUS_MEMUSED ){
  79297. sqlite3 *db = pVdbe->db;
  79298. sqlite3_mutex_enter(db->mutex);
  79299. v = 0;
  79300. db->pnBytesFreed = (int*)&v;
  79301. sqlite3VdbeClearObject(db, pVdbe);
  79302. sqlite3DbFree(db, pVdbe);
  79303. db->pnBytesFreed = 0;
  79304. sqlite3_mutex_leave(db->mutex);
  79305. }else{
  79306. v = pVdbe->aCounter[op];
  79307. if( resetFlag ) pVdbe->aCounter[op] = 0;
  79308. }
  79309. return (int)v;
  79310. }
  79311. /*
  79312. ** Return the SQL associated with a prepared statement
  79313. */
  79314. SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt){
  79315. Vdbe *p = (Vdbe *)pStmt;
  79316. return p ? p->zSql : 0;
  79317. }
  79318. /*
  79319. ** Return the SQL associated with a prepared statement with
  79320. ** bound parameters expanded. Space to hold the returned string is
  79321. ** obtained from sqlite3_malloc(). The caller is responsible for
  79322. ** freeing the returned string by passing it to sqlite3_free().
  79323. **
  79324. ** The SQLITE_TRACE_SIZE_LIMIT puts an upper bound on the size of
  79325. ** expanded bound parameters.
  79326. */
  79327. SQLITE_API char *sqlite3_expanded_sql(sqlite3_stmt *pStmt){
  79328. #ifdef SQLITE_OMIT_TRACE
  79329. return 0;
  79330. #else
  79331. char *z = 0;
  79332. const char *zSql = sqlite3_sql(pStmt);
  79333. if( zSql ){
  79334. Vdbe *p = (Vdbe *)pStmt;
  79335. sqlite3_mutex_enter(p->db->mutex);
  79336. z = sqlite3VdbeExpandSql(p, zSql);
  79337. sqlite3_mutex_leave(p->db->mutex);
  79338. }
  79339. return z;
  79340. #endif
  79341. }
  79342. #ifdef SQLITE_ENABLE_NORMALIZE
  79343. /*
  79344. ** Return the normalized SQL associated with a prepared statement.
  79345. */
  79346. SQLITE_API const char *sqlite3_normalized_sql(sqlite3_stmt *pStmt){
  79347. Vdbe *p = (Vdbe *)pStmt;
  79348. if( p==0 ) return 0;
  79349. if( p->zNormSql==0 && ALWAYS(p->zSql!=0) ){
  79350. sqlite3_mutex_enter(p->db->mutex);
  79351. p->zNormSql = sqlite3Normalize(p, p->zSql);
  79352. sqlite3_mutex_leave(p->db->mutex);
  79353. }
  79354. return p->zNormSql;
  79355. }
  79356. #endif /* SQLITE_ENABLE_NORMALIZE */
  79357. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  79358. /*
  79359. ** Allocate and populate an UnpackedRecord structure based on the serialized
  79360. ** record in nKey/pKey. Return a pointer to the new UnpackedRecord structure
  79361. ** if successful, or a NULL pointer if an OOM error is encountered.
  79362. */
  79363. static UnpackedRecord *vdbeUnpackRecord(
  79364. KeyInfo *pKeyInfo,
  79365. int nKey,
  79366. const void *pKey
  79367. ){
  79368. UnpackedRecord *pRet; /* Return value */
  79369. pRet = sqlite3VdbeAllocUnpackedRecord(pKeyInfo);
  79370. if( pRet ){
  79371. memset(pRet->aMem, 0, sizeof(Mem)*(pKeyInfo->nKeyField+1));
  79372. sqlite3VdbeRecordUnpack(pKeyInfo, nKey, pKey, pRet);
  79373. }
  79374. return pRet;
  79375. }
  79376. /*
  79377. ** This function is called from within a pre-update callback to retrieve
  79378. ** a field of the row currently being updated or deleted.
  79379. */
  79380. SQLITE_API int sqlite3_preupdate_old(sqlite3 *db, int iIdx, sqlite3_value **ppValue){
  79381. PreUpdate *p = db->pPreUpdate;
  79382. Mem *pMem;
  79383. int rc = SQLITE_OK;
  79384. /* Test that this call is being made from within an SQLITE_DELETE or
  79385. ** SQLITE_UPDATE pre-update callback, and that iIdx is within range. */
  79386. if( !p || p->op==SQLITE_INSERT ){
  79387. rc = SQLITE_MISUSE_BKPT;
  79388. goto preupdate_old_out;
  79389. }
  79390. if( p->pPk ){
  79391. iIdx = sqlite3TableColumnToIndex(p->pPk, iIdx);
  79392. }
  79393. if( iIdx>=p->pCsr->nField || iIdx<0 ){
  79394. rc = SQLITE_RANGE;
  79395. goto preupdate_old_out;
  79396. }
  79397. /* If the old.* record has not yet been loaded into memory, do so now. */
  79398. if( p->pUnpacked==0 ){
  79399. u32 nRec;
  79400. u8 *aRec;
  79401. nRec = sqlite3BtreePayloadSize(p->pCsr->uc.pCursor);
  79402. aRec = sqlite3DbMallocRaw(db, nRec);
  79403. if( !aRec ) goto preupdate_old_out;
  79404. rc = sqlite3BtreePayload(p->pCsr->uc.pCursor, 0, nRec, aRec);
  79405. if( rc==SQLITE_OK ){
  79406. p->pUnpacked = vdbeUnpackRecord(&p->keyinfo, nRec, aRec);
  79407. if( !p->pUnpacked ) rc = SQLITE_NOMEM;
  79408. }
  79409. if( rc!=SQLITE_OK ){
  79410. sqlite3DbFree(db, aRec);
  79411. goto preupdate_old_out;
  79412. }
  79413. p->aRecord = aRec;
  79414. }
  79415. pMem = *ppValue = &p->pUnpacked->aMem[iIdx];
  79416. if( iIdx==p->pTab->iPKey ){
  79417. sqlite3VdbeMemSetInt64(pMem, p->iKey1);
  79418. }else if( iIdx>=p->pUnpacked->nField ){
  79419. *ppValue = (sqlite3_value *)columnNullValue();
  79420. }else if( p->pTab->aCol[iIdx].affinity==SQLITE_AFF_REAL ){
  79421. if( pMem->flags & (MEM_Int|MEM_IntReal) ){
  79422. testcase( pMem->flags & MEM_Int );
  79423. testcase( pMem->flags & MEM_IntReal );
  79424. sqlite3VdbeMemRealify(pMem);
  79425. }
  79426. }
  79427. preupdate_old_out:
  79428. sqlite3Error(db, rc);
  79429. return sqlite3ApiExit(db, rc);
  79430. }
  79431. #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
  79432. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  79433. /*
  79434. ** This function is called from within a pre-update callback to retrieve
  79435. ** the number of columns in the row being updated, deleted or inserted.
  79436. */
  79437. SQLITE_API int sqlite3_preupdate_count(sqlite3 *db){
  79438. PreUpdate *p = db->pPreUpdate;
  79439. return (p ? p->keyinfo.nKeyField : 0);
  79440. }
  79441. #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
  79442. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  79443. /*
  79444. ** This function is designed to be called from within a pre-update callback
  79445. ** only. It returns zero if the change that caused the callback was made
  79446. ** immediately by a user SQL statement. Or, if the change was made by a
  79447. ** trigger program, it returns the number of trigger programs currently
  79448. ** on the stack (1 for a top-level trigger, 2 for a trigger fired by a
  79449. ** top-level trigger etc.).
  79450. **
  79451. ** For the purposes of the previous paragraph, a foreign key CASCADE, SET NULL
  79452. ** or SET DEFAULT action is considered a trigger.
  79453. */
  79454. SQLITE_API int sqlite3_preupdate_depth(sqlite3 *db){
  79455. PreUpdate *p = db->pPreUpdate;
  79456. return (p ? p->v->nFrame : 0);
  79457. }
  79458. #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
  79459. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  79460. /*
  79461. ** This function is called from within a pre-update callback to retrieve
  79462. ** a field of the row currently being updated or inserted.
  79463. */
  79464. SQLITE_API int sqlite3_preupdate_new(sqlite3 *db, int iIdx, sqlite3_value **ppValue){
  79465. PreUpdate *p = db->pPreUpdate;
  79466. int rc = SQLITE_OK;
  79467. Mem *pMem;
  79468. if( !p || p->op==SQLITE_DELETE ){
  79469. rc = SQLITE_MISUSE_BKPT;
  79470. goto preupdate_new_out;
  79471. }
  79472. if( p->pPk && p->op!=SQLITE_UPDATE ){
  79473. iIdx = sqlite3TableColumnToIndex(p->pPk, iIdx);
  79474. }
  79475. if( iIdx>=p->pCsr->nField || iIdx<0 ){
  79476. rc = SQLITE_RANGE;
  79477. goto preupdate_new_out;
  79478. }
  79479. if( p->op==SQLITE_INSERT ){
  79480. /* For an INSERT, memory cell p->iNewReg contains the serialized record
  79481. ** that is being inserted. Deserialize it. */
  79482. UnpackedRecord *pUnpack = p->pNewUnpacked;
  79483. if( !pUnpack ){
  79484. Mem *pData = &p->v->aMem[p->iNewReg];
  79485. rc = ExpandBlob(pData);
  79486. if( rc!=SQLITE_OK ) goto preupdate_new_out;
  79487. pUnpack = vdbeUnpackRecord(&p->keyinfo, pData->n, pData->z);
  79488. if( !pUnpack ){
  79489. rc = SQLITE_NOMEM;
  79490. goto preupdate_new_out;
  79491. }
  79492. p->pNewUnpacked = pUnpack;
  79493. }
  79494. pMem = &pUnpack->aMem[iIdx];
  79495. if( iIdx==p->pTab->iPKey ){
  79496. sqlite3VdbeMemSetInt64(pMem, p->iKey2);
  79497. }else if( iIdx>=pUnpack->nField ){
  79498. pMem = (sqlite3_value *)columnNullValue();
  79499. }
  79500. }else{
  79501. /* For an UPDATE, memory cell (p->iNewReg+1+iIdx) contains the required
  79502. ** value. Make a copy of the cell contents and return a pointer to it.
  79503. ** It is not safe to return a pointer to the memory cell itself as the
  79504. ** caller may modify the value text encoding.
  79505. */
  79506. assert( p->op==SQLITE_UPDATE );
  79507. if( !p->aNew ){
  79508. p->aNew = (Mem *)sqlite3DbMallocZero(db, sizeof(Mem) * p->pCsr->nField);
  79509. if( !p->aNew ){
  79510. rc = SQLITE_NOMEM;
  79511. goto preupdate_new_out;
  79512. }
  79513. }
  79514. assert( iIdx>=0 && iIdx<p->pCsr->nField );
  79515. pMem = &p->aNew[iIdx];
  79516. if( pMem->flags==0 ){
  79517. if( iIdx==p->pTab->iPKey ){
  79518. sqlite3VdbeMemSetInt64(pMem, p->iKey2);
  79519. }else{
  79520. rc = sqlite3VdbeMemCopy(pMem, &p->v->aMem[p->iNewReg+1+iIdx]);
  79521. if( rc!=SQLITE_OK ) goto preupdate_new_out;
  79522. }
  79523. }
  79524. }
  79525. *ppValue = pMem;
  79526. preupdate_new_out:
  79527. sqlite3Error(db, rc);
  79528. return sqlite3ApiExit(db, rc);
  79529. }
  79530. #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
  79531. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  79532. /*
  79533. ** Return status data for a single loop within query pStmt.
  79534. */
  79535. SQLITE_API int sqlite3_stmt_scanstatus(
  79536. sqlite3_stmt *pStmt, /* Prepared statement being queried */
  79537. int idx, /* Index of loop to report on */
  79538. int iScanStatusOp, /* Which metric to return */
  79539. void *pOut /* OUT: Write the answer here */
  79540. ){
  79541. Vdbe *p = (Vdbe*)pStmt;
  79542. ScanStatus *pScan;
  79543. if( idx<0 || idx>=p->nScan ) return 1;
  79544. pScan = &p->aScan[idx];
  79545. switch( iScanStatusOp ){
  79546. case SQLITE_SCANSTAT_NLOOP: {
  79547. *(sqlite3_int64*)pOut = p->anExec[pScan->addrLoop];
  79548. break;
  79549. }
  79550. case SQLITE_SCANSTAT_NVISIT: {
  79551. *(sqlite3_int64*)pOut = p->anExec[pScan->addrVisit];
  79552. break;
  79553. }
  79554. case SQLITE_SCANSTAT_EST: {
  79555. double r = 1.0;
  79556. LogEst x = pScan->nEst;
  79557. while( x<100 ){
  79558. x += 10;
  79559. r *= 0.5;
  79560. }
  79561. *(double*)pOut = r*sqlite3LogEstToInt(x);
  79562. break;
  79563. }
  79564. case SQLITE_SCANSTAT_NAME: {
  79565. *(const char**)pOut = pScan->zName;
  79566. break;
  79567. }
  79568. case SQLITE_SCANSTAT_EXPLAIN: {
  79569. if( pScan->addrExplain ){
  79570. *(const char**)pOut = p->aOp[ pScan->addrExplain ].p4.z;
  79571. }else{
  79572. *(const char**)pOut = 0;
  79573. }
  79574. break;
  79575. }
  79576. case SQLITE_SCANSTAT_SELECTID: {
  79577. if( pScan->addrExplain ){
  79578. *(int*)pOut = p->aOp[ pScan->addrExplain ].p1;
  79579. }else{
  79580. *(int*)pOut = -1;
  79581. }
  79582. break;
  79583. }
  79584. default: {
  79585. return 1;
  79586. }
  79587. }
  79588. return 0;
  79589. }
  79590. /*
  79591. ** Zero all counters associated with the sqlite3_stmt_scanstatus() data.
  79592. */
  79593. SQLITE_API void sqlite3_stmt_scanstatus_reset(sqlite3_stmt *pStmt){
  79594. Vdbe *p = (Vdbe*)pStmt;
  79595. memset(p->anExec, 0, p->nOp * sizeof(i64));
  79596. }
  79597. #endif /* SQLITE_ENABLE_STMT_SCANSTATUS */
  79598. /************** End of vdbeapi.c *********************************************/
  79599. /************** Begin file vdbetrace.c ***************************************/
  79600. /*
  79601. ** 2009 November 25
  79602. **
  79603. ** The author disclaims copyright to this source code. In place of
  79604. ** a legal notice, here is a blessing:
  79605. **
  79606. ** May you do good and not evil.
  79607. ** May you find forgiveness for yourself and forgive others.
  79608. ** May you share freely, never taking more than you give.
  79609. **
  79610. *************************************************************************
  79611. **
  79612. ** This file contains code used to insert the values of host parameters
  79613. ** (aka "wildcards") into the SQL text output by sqlite3_trace().
  79614. **
  79615. ** The Vdbe parse-tree explainer is also found here.
  79616. */
  79617. /* #include "sqliteInt.h" */
  79618. /* #include "vdbeInt.h" */
  79619. #ifndef SQLITE_OMIT_TRACE
  79620. /*
  79621. ** zSql is a zero-terminated string of UTF-8 SQL text. Return the number of
  79622. ** bytes in this text up to but excluding the first character in
  79623. ** a host parameter. If the text contains no host parameters, return
  79624. ** the total number of bytes in the text.
  79625. */
  79626. static int findNextHostParameter(const char *zSql, int *pnToken){
  79627. int tokenType;
  79628. int nTotal = 0;
  79629. int n;
  79630. *pnToken = 0;
  79631. while( zSql[0] ){
  79632. n = sqlite3GetToken((u8*)zSql, &tokenType);
  79633. assert( n>0 && tokenType!=TK_ILLEGAL );
  79634. if( tokenType==TK_VARIABLE ){
  79635. *pnToken = n;
  79636. break;
  79637. }
  79638. nTotal += n;
  79639. zSql += n;
  79640. }
  79641. return nTotal;
  79642. }
  79643. /*
  79644. ** This function returns a pointer to a nul-terminated string in memory
  79645. ** obtained from sqlite3DbMalloc(). If sqlite3.nVdbeExec is 1, then the
  79646. ** string contains a copy of zRawSql but with host parameters expanded to
  79647. ** their current bindings. Or, if sqlite3.nVdbeExec is greater than 1,
  79648. ** then the returned string holds a copy of zRawSql with "-- " prepended
  79649. ** to each line of text.
  79650. **
  79651. ** If the SQLITE_TRACE_SIZE_LIMIT macro is defined to an integer, then
  79652. ** then long strings and blobs are truncated to that many bytes. This
  79653. ** can be used to prevent unreasonably large trace strings when dealing
  79654. ** with large (multi-megabyte) strings and blobs.
  79655. **
  79656. ** The calling function is responsible for making sure the memory returned
  79657. ** is eventually freed.
  79658. **
  79659. ** ALGORITHM: Scan the input string looking for host parameters in any of
  79660. ** these forms: ?, ?N, $A, @A, :A. Take care to avoid text within
  79661. ** string literals, quoted identifier names, and comments. For text forms,
  79662. ** the host parameter index is found by scanning the prepared
  79663. ** statement for the corresponding OP_Variable opcode. Once the host
  79664. ** parameter index is known, locate the value in p->aVar[]. Then render
  79665. ** the value as a literal in place of the host parameter name.
  79666. */
  79667. SQLITE_PRIVATE char *sqlite3VdbeExpandSql(
  79668. Vdbe *p, /* The prepared statement being evaluated */
  79669. const char *zRawSql /* Raw text of the SQL statement */
  79670. ){
  79671. sqlite3 *db; /* The database connection */
  79672. int idx = 0; /* Index of a host parameter */
  79673. int nextIndex = 1; /* Index of next ? host parameter */
  79674. int n; /* Length of a token prefix */
  79675. int nToken; /* Length of the parameter token */
  79676. int i; /* Loop counter */
  79677. Mem *pVar; /* Value of a host parameter */
  79678. StrAccum out; /* Accumulate the output here */
  79679. #ifndef SQLITE_OMIT_UTF16
  79680. Mem utf8; /* Used to convert UTF16 into UTF8 for display */
  79681. #endif
  79682. char zBase[100]; /* Initial working space */
  79683. db = p->db;
  79684. sqlite3StrAccumInit(&out, 0, zBase, sizeof(zBase),
  79685. db->aLimit[SQLITE_LIMIT_LENGTH]);
  79686. if( db->nVdbeExec>1 ){
  79687. while( *zRawSql ){
  79688. const char *zStart = zRawSql;
  79689. while( *(zRawSql++)!='\n' && *zRawSql );
  79690. sqlite3_str_append(&out, "-- ", 3);
  79691. assert( (zRawSql - zStart) > 0 );
  79692. sqlite3_str_append(&out, zStart, (int)(zRawSql-zStart));
  79693. }
  79694. }else if( p->nVar==0 ){
  79695. sqlite3_str_append(&out, zRawSql, sqlite3Strlen30(zRawSql));
  79696. }else{
  79697. while( zRawSql[0] ){
  79698. n = findNextHostParameter(zRawSql, &nToken);
  79699. assert( n>0 );
  79700. sqlite3_str_append(&out, zRawSql, n);
  79701. zRawSql += n;
  79702. assert( zRawSql[0] || nToken==0 );
  79703. if( nToken==0 ) break;
  79704. if( zRawSql[0]=='?' ){
  79705. if( nToken>1 ){
  79706. assert( sqlite3Isdigit(zRawSql[1]) );
  79707. sqlite3GetInt32(&zRawSql[1], &idx);
  79708. }else{
  79709. idx = nextIndex;
  79710. }
  79711. }else{
  79712. assert( zRawSql[0]==':' || zRawSql[0]=='$' ||
  79713. zRawSql[0]=='@' || zRawSql[0]=='#' );
  79714. testcase( zRawSql[0]==':' );
  79715. testcase( zRawSql[0]=='$' );
  79716. testcase( zRawSql[0]=='@' );
  79717. testcase( zRawSql[0]=='#' );
  79718. idx = sqlite3VdbeParameterIndex(p, zRawSql, nToken);
  79719. assert( idx>0 );
  79720. }
  79721. zRawSql += nToken;
  79722. nextIndex = idx + 1;
  79723. assert( idx>0 && idx<=p->nVar );
  79724. pVar = &p->aVar[idx-1];
  79725. if( pVar->flags & MEM_Null ){
  79726. sqlite3_str_append(&out, "NULL", 4);
  79727. }else if( pVar->flags & (MEM_Int|MEM_IntReal) ){
  79728. sqlite3_str_appendf(&out, "%lld", pVar->u.i);
  79729. }else if( pVar->flags & MEM_Real ){
  79730. sqlite3_str_appendf(&out, "%!.15g", pVar->u.r);
  79731. }else if( pVar->flags & MEM_Str ){
  79732. int nOut; /* Number of bytes of the string text to include in output */
  79733. #ifndef SQLITE_OMIT_UTF16
  79734. u8 enc = ENC(db);
  79735. if( enc!=SQLITE_UTF8 ){
  79736. memset(&utf8, 0, sizeof(utf8));
  79737. utf8.db = db;
  79738. sqlite3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE_STATIC);
  79739. if( SQLITE_NOMEM==sqlite3VdbeChangeEncoding(&utf8, SQLITE_UTF8) ){
  79740. out.accError = SQLITE_NOMEM;
  79741. out.nAlloc = 0;
  79742. }
  79743. pVar = &utf8;
  79744. }
  79745. #endif
  79746. nOut = pVar->n;
  79747. #ifdef SQLITE_TRACE_SIZE_LIMIT
  79748. if( nOut>SQLITE_TRACE_SIZE_LIMIT ){
  79749. nOut = SQLITE_TRACE_SIZE_LIMIT;
  79750. while( nOut<pVar->n && (pVar->z[nOut]&0xc0)==0x80 ){ nOut++; }
  79751. }
  79752. #endif
  79753. sqlite3_str_appendf(&out, "'%.*q'", nOut, pVar->z);
  79754. #ifdef SQLITE_TRACE_SIZE_LIMIT
  79755. if( nOut<pVar->n ){
  79756. sqlite3_str_appendf(&out, "/*+%d bytes*/", pVar->n-nOut);
  79757. }
  79758. #endif
  79759. #ifndef SQLITE_OMIT_UTF16
  79760. if( enc!=SQLITE_UTF8 ) sqlite3VdbeMemRelease(&utf8);
  79761. #endif
  79762. }else if( pVar->flags & MEM_Zero ){
  79763. sqlite3_str_appendf(&out, "zeroblob(%d)", pVar->u.nZero);
  79764. }else{
  79765. int nOut; /* Number of bytes of the blob to include in output */
  79766. assert( pVar->flags & MEM_Blob );
  79767. sqlite3_str_append(&out, "x'", 2);
  79768. nOut = pVar->n;
  79769. #ifdef SQLITE_TRACE_SIZE_LIMIT
  79770. if( nOut>SQLITE_TRACE_SIZE_LIMIT ) nOut = SQLITE_TRACE_SIZE_LIMIT;
  79771. #endif
  79772. for(i=0; i<nOut; i++){
  79773. sqlite3_str_appendf(&out, "%02x", pVar->z[i]&0xff);
  79774. }
  79775. sqlite3_str_append(&out, "'", 1);
  79776. #ifdef SQLITE_TRACE_SIZE_LIMIT
  79777. if( nOut<pVar->n ){
  79778. sqlite3_str_appendf(&out, "/*+%d bytes*/", pVar->n-nOut);
  79779. }
  79780. #endif
  79781. }
  79782. }
  79783. }
  79784. if( out.accError ) sqlite3_str_reset(&out);
  79785. return sqlite3StrAccumFinish(&out);
  79786. }
  79787. #endif /* #ifndef SQLITE_OMIT_TRACE */
  79788. /************** End of vdbetrace.c *******************************************/
  79789. /************** Begin file vdbe.c ********************************************/
  79790. /*
  79791. ** 2001 September 15
  79792. **
  79793. ** The author disclaims copyright to this source code. In place of
  79794. ** a legal notice, here is a blessing:
  79795. **
  79796. ** May you do good and not evil.
  79797. ** May you find forgiveness for yourself and forgive others.
  79798. ** May you share freely, never taking more than you give.
  79799. **
  79800. *************************************************************************
  79801. ** The code in this file implements the function that runs the
  79802. ** bytecode of a prepared statement.
  79803. **
  79804. ** Various scripts scan this source file in order to generate HTML
  79805. ** documentation, headers files, or other derived files. The formatting
  79806. ** of the code in this file is, therefore, important. See other comments
  79807. ** in this file for details. If in doubt, do not deviate from existing
  79808. ** commenting and indentation practices when changing or adding code.
  79809. */
  79810. /* #include "sqliteInt.h" */
  79811. /* #include "vdbeInt.h" */
  79812. /*
  79813. ** Invoke this macro on memory cells just prior to changing the
  79814. ** value of the cell. This macro verifies that shallow copies are
  79815. ** not misused. A shallow copy of a string or blob just copies a
  79816. ** pointer to the string or blob, not the content. If the original
  79817. ** is changed while the copy is still in use, the string or blob might
  79818. ** be changed out from under the copy. This macro verifies that nothing
  79819. ** like that ever happens.
  79820. */
  79821. #ifdef SQLITE_DEBUG
  79822. # define memAboutToChange(P,M) sqlite3VdbeMemAboutToChange(P,M)
  79823. #else
  79824. # define memAboutToChange(P,M)
  79825. #endif
  79826. /*
  79827. ** The following global variable is incremented every time a cursor
  79828. ** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes. The test
  79829. ** procedures use this information to make sure that indices are
  79830. ** working correctly. This variable has no function other than to
  79831. ** help verify the correct operation of the library.
  79832. */
  79833. #ifdef SQLITE_TEST
  79834. SQLITE_API int sqlite3_search_count = 0;
  79835. #endif
  79836. /*
  79837. ** When this global variable is positive, it gets decremented once before
  79838. ** each instruction in the VDBE. When it reaches zero, the u1.isInterrupted
  79839. ** field of the sqlite3 structure is set in order to simulate an interrupt.
  79840. **
  79841. ** This facility is used for testing purposes only. It does not function
  79842. ** in an ordinary build.
  79843. */
  79844. #ifdef SQLITE_TEST
  79845. SQLITE_API int sqlite3_interrupt_count = 0;
  79846. #endif
  79847. /*
  79848. ** The next global variable is incremented each type the OP_Sort opcode
  79849. ** is executed. The test procedures use this information to make sure that
  79850. ** sorting is occurring or not occurring at appropriate times. This variable
  79851. ** has no function other than to help verify the correct operation of the
  79852. ** library.
  79853. */
  79854. #ifdef SQLITE_TEST
  79855. SQLITE_API int sqlite3_sort_count = 0;
  79856. #endif
  79857. /*
  79858. ** The next global variable records the size of the largest MEM_Blob
  79859. ** or MEM_Str that has been used by a VDBE opcode. The test procedures
  79860. ** use this information to make sure that the zero-blob functionality
  79861. ** is working correctly. This variable has no function other than to
  79862. ** help verify the correct operation of the library.
  79863. */
  79864. #ifdef SQLITE_TEST
  79865. SQLITE_API int sqlite3_max_blobsize = 0;
  79866. static void updateMaxBlobsize(Mem *p){
  79867. if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
  79868. sqlite3_max_blobsize = p->n;
  79869. }
  79870. }
  79871. #endif
  79872. /*
  79873. ** This macro evaluates to true if either the update hook or the preupdate
  79874. ** hook are enabled for database connect DB.
  79875. */
  79876. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  79877. # define HAS_UPDATE_HOOK(DB) ((DB)->xPreUpdateCallback||(DB)->xUpdateCallback)
  79878. #else
  79879. # define HAS_UPDATE_HOOK(DB) ((DB)->xUpdateCallback)
  79880. #endif
  79881. /*
  79882. ** The next global variable is incremented each time the OP_Found opcode
  79883. ** is executed. This is used to test whether or not the foreign key
  79884. ** operation implemented using OP_FkIsZero is working. This variable
  79885. ** has no function other than to help verify the correct operation of the
  79886. ** library.
  79887. */
  79888. #ifdef SQLITE_TEST
  79889. SQLITE_API int sqlite3_found_count = 0;
  79890. #endif
  79891. /*
  79892. ** Test a register to see if it exceeds the current maximum blob size.
  79893. ** If it does, record the new maximum blob size.
  79894. */
  79895. #if defined(SQLITE_TEST) && !defined(SQLITE_UNTESTABLE)
  79896. # define UPDATE_MAX_BLOBSIZE(P) updateMaxBlobsize(P)
  79897. #else
  79898. # define UPDATE_MAX_BLOBSIZE(P)
  79899. #endif
  79900. #ifdef SQLITE_DEBUG
  79901. /* This routine provides a convenient place to set a breakpoint during
  79902. ** tracing with PRAGMA vdbe_trace=on. The breakpoint fires right after
  79903. ** each opcode is printed. Variables "pc" (program counter) and pOp are
  79904. ** available to add conditionals to the breakpoint. GDB example:
  79905. **
  79906. ** break test_trace_breakpoint if pc=22
  79907. **
  79908. ** Other useful labels for breakpoints include:
  79909. ** test_addop_breakpoint(pc,pOp)
  79910. ** sqlite3CorruptError(lineno)
  79911. ** sqlite3MisuseError(lineno)
  79912. ** sqlite3CantopenError(lineno)
  79913. */
  79914. static void test_trace_breakpoint(int pc, Op *pOp, Vdbe *v){
  79915. static int n = 0;
  79916. n++;
  79917. }
  79918. #endif
  79919. /*
  79920. ** Invoke the VDBE coverage callback, if that callback is defined. This
  79921. ** feature is used for test suite validation only and does not appear an
  79922. ** production builds.
  79923. **
  79924. ** M is the type of branch. I is the direction taken for this instance of
  79925. ** the branch.
  79926. **
  79927. ** M: 2 - two-way branch (I=0: fall-thru 1: jump )
  79928. ** 3 - two-way + NULL (I=0: fall-thru 1: jump 2: NULL )
  79929. ** 4 - OP_Jump (I=0: jump p1 1: jump p2 2: jump p3)
  79930. **
  79931. ** In other words, if M is 2, then I is either 0 (for fall-through) or
  79932. ** 1 (for when the branch is taken). If M is 3, the I is 0 for an
  79933. ** ordinary fall-through, I is 1 if the branch was taken, and I is 2
  79934. ** if the result of comparison is NULL. For M=3, I=2 the jump may or
  79935. ** may not be taken, depending on the SQLITE_JUMPIFNULL flags in p5.
  79936. ** When M is 4, that means that an OP_Jump is being run. I is 0, 1, or 2
  79937. ** depending on if the operands are less than, equal, or greater than.
  79938. **
  79939. ** iSrcLine is the source code line (from the __LINE__ macro) that
  79940. ** generated the VDBE instruction combined with flag bits. The source
  79941. ** code line number is in the lower 24 bits of iSrcLine and the upper
  79942. ** 8 bytes are flags. The lower three bits of the flags indicate
  79943. ** values for I that should never occur. For example, if the branch is
  79944. ** always taken, the flags should be 0x05 since the fall-through and
  79945. ** alternate branch are never taken. If a branch is never taken then
  79946. ** flags should be 0x06 since only the fall-through approach is allowed.
  79947. **
  79948. ** Bit 0x08 of the flags indicates an OP_Jump opcode that is only
  79949. ** interested in equal or not-equal. In other words, I==0 and I==2
  79950. ** should be treated as equivalent
  79951. **
  79952. ** Since only a line number is retained, not the filename, this macro
  79953. ** only works for amalgamation builds. But that is ok, since these macros
  79954. ** should be no-ops except for special builds used to measure test coverage.
  79955. */
  79956. #if !defined(SQLITE_VDBE_COVERAGE)
  79957. # define VdbeBranchTaken(I,M)
  79958. #else
  79959. # define VdbeBranchTaken(I,M) vdbeTakeBranch(pOp->iSrcLine,I,M)
  79960. static void vdbeTakeBranch(u32 iSrcLine, u8 I, u8 M){
  79961. u8 mNever;
  79962. assert( I<=2 ); /* 0: fall through, 1: taken, 2: alternate taken */
  79963. assert( M<=4 ); /* 2: two-way branch, 3: three-way branch, 4: OP_Jump */
  79964. assert( I<M ); /* I can only be 2 if M is 3 or 4 */
  79965. /* Transform I from a integer [0,1,2] into a bitmask of [1,2,4] */
  79966. I = 1<<I;
  79967. /* The upper 8 bits of iSrcLine are flags. The lower three bits of
  79968. ** the flags indicate directions that the branch can never go. If
  79969. ** a branch really does go in one of those directions, assert right
  79970. ** away. */
  79971. mNever = iSrcLine >> 24;
  79972. assert( (I & mNever)==0 );
  79973. if( sqlite3GlobalConfig.xVdbeBranch==0 ) return; /*NO_TEST*/
  79974. /* Invoke the branch coverage callback with three arguments:
  79975. ** iSrcLine - the line number of the VdbeCoverage() macro, with
  79976. ** flags removed.
  79977. ** I - Mask of bits 0x07 indicating which cases are are
  79978. ** fulfilled by this instance of the jump. 0x01 means
  79979. ** fall-thru, 0x02 means taken, 0x04 means NULL. Any
  79980. ** impossible cases (ex: if the comparison is never NULL)
  79981. ** are filled in automatically so that the coverage
  79982. ** measurement logic does not flag those impossible cases
  79983. ** as missed coverage.
  79984. ** M - Type of jump. Same as M argument above
  79985. */
  79986. I |= mNever;
  79987. if( M==2 ) I |= 0x04;
  79988. if( M==4 ){
  79989. I |= 0x08;
  79990. if( (mNever&0x08)!=0 && (I&0x05)!=0) I |= 0x05; /*NO_TEST*/
  79991. }
  79992. sqlite3GlobalConfig.xVdbeBranch(sqlite3GlobalConfig.pVdbeBranchArg,
  79993. iSrcLine&0xffffff, I, M);
  79994. }
  79995. #endif
  79996. /*
  79997. ** An ephemeral string value (signified by the MEM_Ephem flag) contains
  79998. ** a pointer to a dynamically allocated string where some other entity
  79999. ** is responsible for deallocating that string. Because the register
  80000. ** does not control the string, it might be deleted without the register
  80001. ** knowing it.
  80002. **
  80003. ** This routine converts an ephemeral string into a dynamically allocated
  80004. ** string that the register itself controls. In other words, it
  80005. ** converts an MEM_Ephem string into a string with P.z==P.zMalloc.
  80006. */
  80007. #define Deephemeralize(P) \
  80008. if( ((P)->flags&MEM_Ephem)!=0 \
  80009. && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
  80010. /* Return true if the cursor was opened using the OP_OpenSorter opcode. */
  80011. #define isSorter(x) ((x)->eCurType==CURTYPE_SORTER)
  80012. /*
  80013. ** Allocate VdbeCursor number iCur. Return a pointer to it. Return NULL
  80014. ** if we run out of memory.
  80015. */
  80016. static VdbeCursor *allocateCursor(
  80017. Vdbe *p, /* The virtual machine */
  80018. int iCur, /* Index of the new VdbeCursor */
  80019. int nField, /* Number of fields in the table or index */
  80020. int iDb, /* Database the cursor belongs to, or -1 */
  80021. u8 eCurType /* Type of the new cursor */
  80022. ){
  80023. /* Find the memory cell that will be used to store the blob of memory
  80024. ** required for this VdbeCursor structure. It is convenient to use a
  80025. ** vdbe memory cell to manage the memory allocation required for a
  80026. ** VdbeCursor structure for the following reasons:
  80027. **
  80028. ** * Sometimes cursor numbers are used for a couple of different
  80029. ** purposes in a vdbe program. The different uses might require
  80030. ** different sized allocations. Memory cells provide growable
  80031. ** allocations.
  80032. **
  80033. ** * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
  80034. ** be freed lazily via the sqlite3_release_memory() API. This
  80035. ** minimizes the number of malloc calls made by the system.
  80036. **
  80037. ** The memory cell for cursor 0 is aMem[0]. The rest are allocated from
  80038. ** the top of the register space. Cursor 1 is at Mem[p->nMem-1].
  80039. ** Cursor 2 is at Mem[p->nMem-2]. And so forth.
  80040. */
  80041. Mem *pMem = iCur>0 ? &p->aMem[p->nMem-iCur] : p->aMem;
  80042. int nByte;
  80043. VdbeCursor *pCx = 0;
  80044. nByte =
  80045. ROUND8(sizeof(VdbeCursor)) + 2*sizeof(u32)*nField +
  80046. (eCurType==CURTYPE_BTREE?sqlite3BtreeCursorSize():0);
  80047. assert( iCur>=0 && iCur<p->nCursor );
  80048. if( p->apCsr[iCur] ){ /*OPTIMIZATION-IF-FALSE*/
  80049. /* Before calling sqlite3VdbeFreeCursor(), ensure the isEphemeral flag
  80050. ** is clear. Otherwise, if this is an ephemeral cursor created by
  80051. ** OP_OpenDup, the cursor will not be closed and will still be part
  80052. ** of a BtShared.pCursor list. */
  80053. if( p->apCsr[iCur]->pBtx==0 ) p->apCsr[iCur]->isEphemeral = 0;
  80054. sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
  80055. p->apCsr[iCur] = 0;
  80056. }
  80057. if( SQLITE_OK==sqlite3VdbeMemClearAndResize(pMem, nByte) ){
  80058. p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
  80059. memset(pCx, 0, offsetof(VdbeCursor,pAltCursor));
  80060. pCx->eCurType = eCurType;
  80061. pCx->iDb = iDb;
  80062. pCx->nField = nField;
  80063. pCx->aOffset = &pCx->aType[nField];
  80064. if( eCurType==CURTYPE_BTREE ){
  80065. pCx->uc.pCursor = (BtCursor*)
  80066. &pMem->z[ROUND8(sizeof(VdbeCursor))+2*sizeof(u32)*nField];
  80067. sqlite3BtreeCursorZero(pCx->uc.pCursor);
  80068. }
  80069. }
  80070. return pCx;
  80071. }
  80072. /*
  80073. ** The string in pRec is known to look like an integer and to have a
  80074. ** floating point value of rValue. Return true and set *piValue to the
  80075. ** integer value if the string is in range to be an integer. Otherwise,
  80076. ** return false.
  80077. */
  80078. static int alsoAnInt(Mem *pRec, double rValue, i64 *piValue){
  80079. i64 iValue = (double)rValue;
  80080. if( sqlite3RealSameAsInt(rValue,iValue) ){
  80081. *piValue = iValue;
  80082. return 1;
  80083. }
  80084. return 0==sqlite3Atoi64(pRec->z, piValue, pRec->n, pRec->enc);
  80085. }
  80086. /*
  80087. ** Try to convert a value into a numeric representation if we can
  80088. ** do so without loss of information. In other words, if the string
  80089. ** looks like a number, convert it into a number. If it does not
  80090. ** look like a number, leave it alone.
  80091. **
  80092. ** If the bTryForInt flag is true, then extra effort is made to give
  80093. ** an integer representation. Strings that look like floating point
  80094. ** values but which have no fractional component (example: '48.00')
  80095. ** will have a MEM_Int representation when bTryForInt is true.
  80096. **
  80097. ** If bTryForInt is false, then if the input string contains a decimal
  80098. ** point or exponential notation, the result is only MEM_Real, even
  80099. ** if there is an exact integer representation of the quantity.
  80100. */
  80101. static void applyNumericAffinity(Mem *pRec, int bTryForInt){
  80102. double rValue;
  80103. u8 enc = pRec->enc;
  80104. int rc;
  80105. assert( (pRec->flags & (MEM_Str|MEM_Int|MEM_Real|MEM_IntReal))==MEM_Str );
  80106. rc = sqlite3AtoF(pRec->z, &rValue, pRec->n, enc);
  80107. if( rc<=0 ) return;
  80108. if( rc==1 && alsoAnInt(pRec, rValue, &pRec->u.i) ){
  80109. pRec->flags |= MEM_Int;
  80110. }else{
  80111. pRec->u.r = rValue;
  80112. pRec->flags |= MEM_Real;
  80113. if( bTryForInt ) sqlite3VdbeIntegerAffinity(pRec);
  80114. }
  80115. /* TEXT->NUMERIC is many->one. Hence, it is important to invalidate the
  80116. ** string representation after computing a numeric equivalent, because the
  80117. ** string representation might not be the canonical representation for the
  80118. ** numeric value. Ticket [343634942dd54ab57b7024] 2018-01-31. */
  80119. pRec->flags &= ~MEM_Str;
  80120. }
  80121. /*
  80122. ** Processing is determine by the affinity parameter:
  80123. **
  80124. ** SQLITE_AFF_INTEGER:
  80125. ** SQLITE_AFF_REAL:
  80126. ** SQLITE_AFF_NUMERIC:
  80127. ** Try to convert pRec to an integer representation or a
  80128. ** floating-point representation if an integer representation
  80129. ** is not possible. Note that the integer representation is
  80130. ** always preferred, even if the affinity is REAL, because
  80131. ** an integer representation is more space efficient on disk.
  80132. **
  80133. ** SQLITE_AFF_TEXT:
  80134. ** Convert pRec to a text representation.
  80135. **
  80136. ** SQLITE_AFF_BLOB:
  80137. ** SQLITE_AFF_NONE:
  80138. ** No-op. pRec is unchanged.
  80139. */
  80140. static void applyAffinity(
  80141. Mem *pRec, /* The value to apply affinity to */
  80142. char affinity, /* The affinity to be applied */
  80143. u8 enc /* Use this text encoding */
  80144. ){
  80145. if( affinity>=SQLITE_AFF_NUMERIC ){
  80146. assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
  80147. || affinity==SQLITE_AFF_NUMERIC );
  80148. if( (pRec->flags & MEM_Int)==0 ){ /*OPTIMIZATION-IF-FALSE*/
  80149. if( (pRec->flags & MEM_Real)==0 ){
  80150. if( pRec->flags & MEM_Str ) applyNumericAffinity(pRec,1);
  80151. }else{
  80152. sqlite3VdbeIntegerAffinity(pRec);
  80153. }
  80154. }
  80155. }else if( affinity==SQLITE_AFF_TEXT ){
  80156. /* Only attempt the conversion to TEXT if there is an integer or real
  80157. ** representation (blob and NULL do not get converted) but no string
  80158. ** representation. It would be harmless to repeat the conversion if
  80159. ** there is already a string rep, but it is pointless to waste those
  80160. ** CPU cycles. */
  80161. if( 0==(pRec->flags&MEM_Str) ){ /*OPTIMIZATION-IF-FALSE*/
  80162. if( (pRec->flags&(MEM_Real|MEM_Int|MEM_IntReal)) ){
  80163. testcase( pRec->flags & MEM_Int );
  80164. testcase( pRec->flags & MEM_Real );
  80165. testcase( pRec->flags & MEM_IntReal );
  80166. sqlite3VdbeMemStringify(pRec, enc, 1);
  80167. }
  80168. }
  80169. pRec->flags &= ~(MEM_Real|MEM_Int|MEM_IntReal);
  80170. }
  80171. }
  80172. /*
  80173. ** Try to convert the type of a function argument or a result column
  80174. ** into a numeric representation. Use either INTEGER or REAL whichever
  80175. ** is appropriate. But only do the conversion if it is possible without
  80176. ** loss of information and return the revised type of the argument.
  80177. */
  80178. SQLITE_API int sqlite3_value_numeric_type(sqlite3_value *pVal){
  80179. int eType = sqlite3_value_type(pVal);
  80180. if( eType==SQLITE_TEXT ){
  80181. Mem *pMem = (Mem*)pVal;
  80182. applyNumericAffinity(pMem, 0);
  80183. eType = sqlite3_value_type(pVal);
  80184. }
  80185. return eType;
  80186. }
  80187. /*
  80188. ** Exported version of applyAffinity(). This one works on sqlite3_value*,
  80189. ** not the internal Mem* type.
  80190. */
  80191. SQLITE_PRIVATE void sqlite3ValueApplyAffinity(
  80192. sqlite3_value *pVal,
  80193. u8 affinity,
  80194. u8 enc
  80195. ){
  80196. applyAffinity((Mem *)pVal, affinity, enc);
  80197. }
  80198. /*
  80199. ** pMem currently only holds a string type (or maybe a BLOB that we can
  80200. ** interpret as a string if we want to). Compute its corresponding
  80201. ** numeric type, if has one. Set the pMem->u.r and pMem->u.i fields
  80202. ** accordingly.
  80203. */
  80204. static u16 SQLITE_NOINLINE computeNumericType(Mem *pMem){
  80205. int rc;
  80206. sqlite3_int64 ix;
  80207. assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_IntReal))==0 );
  80208. assert( (pMem->flags & (MEM_Str|MEM_Blob))!=0 );
  80209. ExpandBlob(pMem);
  80210. rc = sqlite3AtoF(pMem->z, &pMem->u.r, pMem->n, pMem->enc);
  80211. if( rc<=0 ){
  80212. if( rc==0 && sqlite3Atoi64(pMem->z, &ix, pMem->n, pMem->enc)<=1 ){
  80213. pMem->u.i = ix;
  80214. return MEM_Int;
  80215. }else{
  80216. return MEM_Real;
  80217. }
  80218. }else if( rc==1 && sqlite3Atoi64(pMem->z, &ix, pMem->n, pMem->enc)==0 ){
  80219. pMem->u.i = ix;
  80220. return MEM_Int;
  80221. }
  80222. return MEM_Real;
  80223. }
  80224. /*
  80225. ** Return the numeric type for pMem, either MEM_Int or MEM_Real or both or
  80226. ** none.
  80227. **
  80228. ** Unlike applyNumericAffinity(), this routine does not modify pMem->flags.
  80229. ** But it does set pMem->u.r and pMem->u.i appropriately.
  80230. */
  80231. static u16 numericType(Mem *pMem){
  80232. if( pMem->flags & (MEM_Int|MEM_Real|MEM_IntReal) ){
  80233. testcase( pMem->flags & MEM_Int );
  80234. testcase( pMem->flags & MEM_Real );
  80235. testcase( pMem->flags & MEM_IntReal );
  80236. return pMem->flags & (MEM_Int|MEM_Real|MEM_IntReal);
  80237. }
  80238. if( pMem->flags & (MEM_Str|MEM_Blob) ){
  80239. testcase( pMem->flags & MEM_Str );
  80240. testcase( pMem->flags & MEM_Blob );
  80241. return computeNumericType(pMem);
  80242. }
  80243. return 0;
  80244. }
  80245. #ifdef SQLITE_DEBUG
  80246. /*
  80247. ** Write a nice string representation of the contents of cell pMem
  80248. ** into buffer zBuf, length nBuf.
  80249. */
  80250. SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, StrAccum *pStr){
  80251. int f = pMem->flags;
  80252. static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
  80253. if( f&MEM_Blob ){
  80254. int i;
  80255. char c;
  80256. if( f & MEM_Dyn ){
  80257. c = 'z';
  80258. assert( (f & (MEM_Static|MEM_Ephem))==0 );
  80259. }else if( f & MEM_Static ){
  80260. c = 't';
  80261. assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
  80262. }else if( f & MEM_Ephem ){
  80263. c = 'e';
  80264. assert( (f & (MEM_Static|MEM_Dyn))==0 );
  80265. }else{
  80266. c = 's';
  80267. }
  80268. sqlite3_str_appendf(pStr, "%cx[", c);
  80269. for(i=0; i<25 && i<pMem->n; i++){
  80270. sqlite3_str_appendf(pStr, "%02X", ((int)pMem->z[i] & 0xFF));
  80271. }
  80272. sqlite3_str_appendf(pStr, "|");
  80273. for(i=0; i<25 && i<pMem->n; i++){
  80274. char z = pMem->z[i];
  80275. sqlite3_str_appendchar(pStr, 1, (z<32||z>126)?'.':z);
  80276. }
  80277. sqlite3_str_appendf(pStr,"]");
  80278. if( f & MEM_Zero ){
  80279. sqlite3_str_appendf(pStr, "+%dz",pMem->u.nZero);
  80280. }
  80281. }else if( f & MEM_Str ){
  80282. int j;
  80283. u8 c;
  80284. if( f & MEM_Dyn ){
  80285. c = 'z';
  80286. assert( (f & (MEM_Static|MEM_Ephem))==0 );
  80287. }else if( f & MEM_Static ){
  80288. c = 't';
  80289. assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
  80290. }else if( f & MEM_Ephem ){
  80291. c = 'e';
  80292. assert( (f & (MEM_Static|MEM_Dyn))==0 );
  80293. }else{
  80294. c = 's';
  80295. }
  80296. sqlite3_str_appendf(pStr, " %c%d[", c, pMem->n);
  80297. for(j=0; j<25 && j<pMem->n; j++){
  80298. c = pMem->z[j];
  80299. sqlite3_str_appendchar(pStr, 1, (c>=0x20&&c<=0x7f) ? c : '.');
  80300. }
  80301. sqlite3_str_appendf(pStr, "]%s", encnames[pMem->enc]);
  80302. }
  80303. }
  80304. #endif
  80305. #ifdef SQLITE_DEBUG
  80306. /*
  80307. ** Print the value of a register for tracing purposes:
  80308. */
  80309. static void memTracePrint(Mem *p){
  80310. if( p->flags & MEM_Undefined ){
  80311. printf(" undefined");
  80312. }else if( p->flags & MEM_Null ){
  80313. printf(p->flags & MEM_Zero ? " NULL-nochng" : " NULL");
  80314. }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
  80315. printf(" si:%lld", p->u.i);
  80316. }else if( (p->flags & (MEM_IntReal))!=0 ){
  80317. printf(" ir:%lld", p->u.i);
  80318. }else if( p->flags & MEM_Int ){
  80319. printf(" i:%lld", p->u.i);
  80320. #ifndef SQLITE_OMIT_FLOATING_POINT
  80321. }else if( p->flags & MEM_Real ){
  80322. printf(" r:%.17g", p->u.r);
  80323. #endif
  80324. }else if( sqlite3VdbeMemIsRowSet(p) ){
  80325. printf(" (rowset)");
  80326. }else{
  80327. StrAccum acc;
  80328. char zBuf[1000];
  80329. sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
  80330. sqlite3VdbeMemPrettyPrint(p, &acc);
  80331. printf(" %s", sqlite3StrAccumFinish(&acc));
  80332. }
  80333. if( p->flags & MEM_Subtype ) printf(" subtype=0x%02x", p->eSubtype);
  80334. }
  80335. static void registerTrace(int iReg, Mem *p){
  80336. printf("R[%d] = ", iReg);
  80337. memTracePrint(p);
  80338. if( p->pScopyFrom ){
  80339. printf(" <== R[%d]", (int)(p->pScopyFrom - &p[-iReg]));
  80340. }
  80341. printf("\n");
  80342. sqlite3VdbeCheckMemInvariants(p);
  80343. }
  80344. #endif
  80345. #ifdef SQLITE_DEBUG
  80346. /*
  80347. ** Show the values of all registers in the virtual machine. Used for
  80348. ** interactive debugging.
  80349. */
  80350. SQLITE_PRIVATE void sqlite3VdbeRegisterDump(Vdbe *v){
  80351. int i;
  80352. for(i=1; i<v->nMem; i++) registerTrace(i, v->aMem+i);
  80353. }
  80354. #endif /* SQLITE_DEBUG */
  80355. #ifdef SQLITE_DEBUG
  80356. # define REGISTER_TRACE(R,M) if(db->flags&SQLITE_VdbeTrace)registerTrace(R,M)
  80357. #else
  80358. # define REGISTER_TRACE(R,M)
  80359. #endif
  80360. #ifdef VDBE_PROFILE
  80361. /*
  80362. ** hwtime.h contains inline assembler code for implementing
  80363. ** high-performance timing routines.
  80364. */
  80365. /************** Include hwtime.h in the middle of vdbe.c *********************/
  80366. /************** Begin file hwtime.h ******************************************/
  80367. /*
  80368. ** 2008 May 27
  80369. **
  80370. ** The author disclaims copyright to this source code. In place of
  80371. ** a legal notice, here is a blessing:
  80372. **
  80373. ** May you do good and not evil.
  80374. ** May you find forgiveness for yourself and forgive others.
  80375. ** May you share freely, never taking more than you give.
  80376. **
  80377. ******************************************************************************
  80378. **
  80379. ** This file contains inline asm code for retrieving "high-performance"
  80380. ** counters for x86 and x86_64 class CPUs.
  80381. */
  80382. #ifndef SQLITE_HWTIME_H
  80383. #define SQLITE_HWTIME_H
  80384. /*
  80385. ** The following routine only works on pentium-class (or newer) processors.
  80386. ** It uses the RDTSC opcode to read the cycle count value out of the
  80387. ** processor and returns that value. This can be used for high-res
  80388. ** profiling.
  80389. */
  80390. #if !defined(__STRICT_ANSI__) && \
  80391. (defined(__GNUC__) || defined(_MSC_VER)) && \
  80392. (defined(i386) || defined(__i386__) || defined(_M_IX86))
  80393. #if defined(__GNUC__)
  80394. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  80395. unsigned int lo, hi;
  80396. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  80397. return (sqlite_uint64)hi << 32 | lo;
  80398. }
  80399. #elif defined(_MSC_VER)
  80400. __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
  80401. __asm {
  80402. rdtsc
  80403. ret ; return value at EDX:EAX
  80404. }
  80405. }
  80406. #endif
  80407. #elif !defined(__STRICT_ANSI__) && (defined(__GNUC__) && defined(__x86_64__))
  80408. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  80409. unsigned long val;
  80410. __asm__ __volatile__ ("rdtsc" : "=A" (val));
  80411. return val;
  80412. }
  80413. #elif !defined(__STRICT_ANSI__) && (defined(__GNUC__) && defined(__ppc__))
  80414. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  80415. unsigned long long retval;
  80416. unsigned long junk;
  80417. __asm__ __volatile__ ("\n\
  80418. 1: mftbu %1\n\
  80419. mftb %L0\n\
  80420. mftbu %0\n\
  80421. cmpw %0,%1\n\
  80422. bne 1b"
  80423. : "=r" (retval), "=r" (junk));
  80424. return retval;
  80425. }
  80426. #else
  80427. /*
  80428. ** asm() is needed for hardware timing support. Without asm(),
  80429. ** disable the sqlite3Hwtime() routine.
  80430. **
  80431. ** sqlite3Hwtime() is only used for some obscure debugging
  80432. ** and analysis configurations, not in any deliverable, so this
  80433. ** should not be a great loss.
  80434. */
  80435. SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
  80436. #endif
  80437. #endif /* !defined(SQLITE_HWTIME_H) */
  80438. /************** End of hwtime.h **********************************************/
  80439. /************** Continuing where we left off in vdbe.c ***********************/
  80440. #endif
  80441. #ifndef NDEBUG
  80442. /*
  80443. ** This function is only called from within an assert() expression. It
  80444. ** checks that the sqlite3.nTransaction variable is correctly set to
  80445. ** the number of non-transaction savepoints currently in the
  80446. ** linked list starting at sqlite3.pSavepoint.
  80447. **
  80448. ** Usage:
  80449. **
  80450. ** assert( checkSavepointCount(db) );
  80451. */
  80452. static int checkSavepointCount(sqlite3 *db){
  80453. int n = 0;
  80454. Savepoint *p;
  80455. for(p=db->pSavepoint; p; p=p->pNext) n++;
  80456. assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
  80457. return 1;
  80458. }
  80459. #endif
  80460. /*
  80461. ** Return the register of pOp->p2 after first preparing it to be
  80462. ** overwritten with an integer value.
  80463. */
  80464. static SQLITE_NOINLINE Mem *out2PrereleaseWithClear(Mem *pOut){
  80465. sqlite3VdbeMemSetNull(pOut);
  80466. pOut->flags = MEM_Int;
  80467. return pOut;
  80468. }
  80469. static Mem *out2Prerelease(Vdbe *p, VdbeOp *pOp){
  80470. Mem *pOut;
  80471. assert( pOp->p2>0 );
  80472. assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
  80473. pOut = &p->aMem[pOp->p2];
  80474. memAboutToChange(p, pOut);
  80475. if( VdbeMemDynamic(pOut) ){ /*OPTIMIZATION-IF-FALSE*/
  80476. return out2PrereleaseWithClear(pOut);
  80477. }else{
  80478. pOut->flags = MEM_Int;
  80479. return pOut;
  80480. }
  80481. }
  80482. /*
  80483. ** Execute as much of a VDBE program as we can.
  80484. ** This is the core of sqlite3_step().
  80485. */
  80486. SQLITE_PRIVATE int sqlite3VdbeExec(
  80487. Vdbe *p /* The VDBE */
  80488. ){
  80489. Op *aOp = p->aOp; /* Copy of p->aOp */
  80490. Op *pOp = aOp; /* Current operation */
  80491. #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
  80492. Op *pOrigOp; /* Value of pOp at the top of the loop */
  80493. #endif
  80494. #ifdef SQLITE_DEBUG
  80495. int nExtraDelete = 0; /* Verifies FORDELETE and AUXDELETE flags */
  80496. #endif
  80497. int rc = SQLITE_OK; /* Value to return */
  80498. sqlite3 *db = p->db; /* The database */
  80499. u8 resetSchemaOnFault = 0; /* Reset schema after an error if positive */
  80500. u8 encoding = ENC(db); /* The database encoding */
  80501. int iCompare = 0; /* Result of last comparison */
  80502. unsigned nVmStep = 0; /* Number of virtual machine steps */
  80503. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  80504. unsigned nProgressLimit; /* Invoke xProgress() when nVmStep reaches this */
  80505. #endif
  80506. Mem *aMem = p->aMem; /* Copy of p->aMem */
  80507. Mem *pIn1 = 0; /* 1st input operand */
  80508. Mem *pIn2 = 0; /* 2nd input operand */
  80509. Mem *pIn3 = 0; /* 3rd input operand */
  80510. Mem *pOut = 0; /* Output operand */
  80511. #ifdef VDBE_PROFILE
  80512. u64 start; /* CPU clock count at start of opcode */
  80513. #endif
  80514. /*** INSERT STACK UNION HERE ***/
  80515. assert( p->magic==VDBE_MAGIC_RUN ); /* sqlite3_step() verifies this */
  80516. sqlite3VdbeEnter(p);
  80517. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  80518. if( db->xProgress ){
  80519. u32 iPrior = p->aCounter[SQLITE_STMTSTATUS_VM_STEP];
  80520. assert( 0 < db->nProgressOps );
  80521. nProgressLimit = db->nProgressOps - (iPrior % db->nProgressOps);
  80522. }else{
  80523. nProgressLimit = 0xffffffff;
  80524. }
  80525. #endif
  80526. if( p->rc==SQLITE_NOMEM ){
  80527. /* This happens if a malloc() inside a call to sqlite3_column_text() or
  80528. ** sqlite3_column_text16() failed. */
  80529. goto no_mem;
  80530. }
  80531. assert( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_BUSY );
  80532. testcase( p->rc!=SQLITE_OK );
  80533. p->rc = SQLITE_OK;
  80534. assert( p->bIsReader || p->readOnly!=0 );
  80535. p->iCurrentTime = 0;
  80536. assert( p->explain==0 );
  80537. p->pResultSet = 0;
  80538. db->busyHandler.nBusy = 0;
  80539. if( AtomicLoad(&db->u1.isInterrupted) ) goto abort_due_to_interrupt;
  80540. sqlite3VdbeIOTraceSql(p);
  80541. #ifdef SQLITE_DEBUG
  80542. sqlite3BeginBenignMalloc();
  80543. if( p->pc==0
  80544. && (p->db->flags & (SQLITE_VdbeListing|SQLITE_VdbeEQP|SQLITE_VdbeTrace))!=0
  80545. ){
  80546. int i;
  80547. int once = 1;
  80548. sqlite3VdbePrintSql(p);
  80549. if( p->db->flags & SQLITE_VdbeListing ){
  80550. printf("VDBE Program Listing:\n");
  80551. for(i=0; i<p->nOp; i++){
  80552. sqlite3VdbePrintOp(stdout, i, &aOp[i]);
  80553. }
  80554. }
  80555. if( p->db->flags & SQLITE_VdbeEQP ){
  80556. for(i=0; i<p->nOp; i++){
  80557. if( aOp[i].opcode==OP_Explain ){
  80558. if( once ) printf("VDBE Query Plan:\n");
  80559. printf("%s\n", aOp[i].p4.z);
  80560. once = 0;
  80561. }
  80562. }
  80563. }
  80564. if( p->db->flags & SQLITE_VdbeTrace ) printf("VDBE Trace:\n");
  80565. }
  80566. sqlite3EndBenignMalloc();
  80567. #endif
  80568. for(pOp=&aOp[p->pc]; 1; pOp++){
  80569. /* Errors are detected by individual opcodes, with an immediate
  80570. ** jumps to abort_due_to_error. */
  80571. assert( rc==SQLITE_OK );
  80572. assert( pOp>=aOp && pOp<&aOp[p->nOp]);
  80573. #ifdef VDBE_PROFILE
  80574. start = sqlite3NProfileCnt ? sqlite3NProfileCnt : sqlite3Hwtime();
  80575. #endif
  80576. nVmStep++;
  80577. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  80578. if( p->anExec ) p->anExec[(int)(pOp-aOp)]++;
  80579. #endif
  80580. /* Only allow tracing if SQLITE_DEBUG is defined.
  80581. */
  80582. #ifdef SQLITE_DEBUG
  80583. if( db->flags & SQLITE_VdbeTrace ){
  80584. sqlite3VdbePrintOp(stdout, (int)(pOp - aOp), pOp);
  80585. test_trace_breakpoint((int)(pOp - aOp),pOp,p);
  80586. }
  80587. #endif
  80588. /* Check to see if we need to simulate an interrupt. This only happens
  80589. ** if we have a special test build.
  80590. */
  80591. #ifdef SQLITE_TEST
  80592. if( sqlite3_interrupt_count>0 ){
  80593. sqlite3_interrupt_count--;
  80594. if( sqlite3_interrupt_count==0 ){
  80595. sqlite3_interrupt(db);
  80596. }
  80597. }
  80598. #endif
  80599. /* Sanity checking on other operands */
  80600. #ifdef SQLITE_DEBUG
  80601. {
  80602. u8 opProperty = sqlite3OpcodeProperty[pOp->opcode];
  80603. if( (opProperty & OPFLG_IN1)!=0 ){
  80604. assert( pOp->p1>0 );
  80605. assert( pOp->p1<=(p->nMem+1 - p->nCursor) );
  80606. assert( memIsValid(&aMem[pOp->p1]) );
  80607. assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p1]) );
  80608. REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
  80609. }
  80610. if( (opProperty & OPFLG_IN2)!=0 ){
  80611. assert( pOp->p2>0 );
  80612. assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
  80613. assert( memIsValid(&aMem[pOp->p2]) );
  80614. assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p2]) );
  80615. REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
  80616. }
  80617. if( (opProperty & OPFLG_IN3)!=0 ){
  80618. assert( pOp->p3>0 );
  80619. assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
  80620. assert( memIsValid(&aMem[pOp->p3]) );
  80621. assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p3]) );
  80622. REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
  80623. }
  80624. if( (opProperty & OPFLG_OUT2)!=0 ){
  80625. assert( pOp->p2>0 );
  80626. assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
  80627. memAboutToChange(p, &aMem[pOp->p2]);
  80628. }
  80629. if( (opProperty & OPFLG_OUT3)!=0 ){
  80630. assert( pOp->p3>0 );
  80631. assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
  80632. memAboutToChange(p, &aMem[pOp->p3]);
  80633. }
  80634. }
  80635. #endif
  80636. #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
  80637. pOrigOp = pOp;
  80638. #endif
  80639. switch( pOp->opcode ){
  80640. /*****************************************************************************
  80641. ** What follows is a massive switch statement where each case implements a
  80642. ** separate instruction in the virtual machine. If we follow the usual
  80643. ** indentation conventions, each case should be indented by 6 spaces. But
  80644. ** that is a lot of wasted space on the left margin. So the code within
  80645. ** the switch statement will break with convention and be flush-left. Another
  80646. ** big comment (similar to this one) will mark the point in the code where
  80647. ** we transition back to normal indentation.
  80648. **
  80649. ** The formatting of each case is important. The makefile for SQLite
  80650. ** generates two C files "opcodes.h" and "opcodes.c" by scanning this
  80651. ** file looking for lines that begin with "case OP_". The opcodes.h files
  80652. ** will be filled with #defines that give unique integer values to each
  80653. ** opcode and the opcodes.c file is filled with an array of strings where
  80654. ** each string is the symbolic name for the corresponding opcode. If the
  80655. ** case statement is followed by a comment of the form "/# same as ... #/"
  80656. ** that comment is used to determine the particular value of the opcode.
  80657. **
  80658. ** Other keywords in the comment that follows each case are used to
  80659. ** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
  80660. ** Keywords include: in1, in2, in3, out2, out3. See
  80661. ** the mkopcodeh.awk script for additional information.
  80662. **
  80663. ** Documentation about VDBE opcodes is generated by scanning this file
  80664. ** for lines of that contain "Opcode:". That line and all subsequent
  80665. ** comment lines are used in the generation of the opcode.html documentation
  80666. ** file.
  80667. **
  80668. ** SUMMARY:
  80669. **
  80670. ** Formatting is important to scripts that scan this file.
  80671. ** Do not deviate from the formatting style currently in use.
  80672. **
  80673. *****************************************************************************/
  80674. /* Opcode: Goto * P2 * * *
  80675. **
  80676. ** An unconditional jump to address P2.
  80677. ** The next instruction executed will be
  80678. ** the one at index P2 from the beginning of
  80679. ** the program.
  80680. **
  80681. ** The P1 parameter is not actually used by this opcode. However, it
  80682. ** is sometimes set to 1 instead of 0 as a hint to the command-line shell
  80683. ** that this Goto is the bottom of a loop and that the lines from P2 down
  80684. ** to the current line should be indented for EXPLAIN output.
  80685. */
  80686. case OP_Goto: { /* jump */
  80687. #ifdef SQLITE_DEBUG
  80688. /* In debuggging mode, when the p5 flags is set on an OP_Goto, that
  80689. ** means we should really jump back to the preceeding OP_ReleaseReg
  80690. ** instruction. */
  80691. if( pOp->p5 ){
  80692. assert( pOp->p2 < (int)(pOp - aOp) );
  80693. assert( pOp->p2 > 1 );
  80694. pOp = &aOp[pOp->p2 - 2];
  80695. assert( pOp[1].opcode==OP_ReleaseReg );
  80696. goto check_for_interrupt;
  80697. }
  80698. #endif
  80699. jump_to_p2_and_check_for_interrupt:
  80700. pOp = &aOp[pOp->p2 - 1];
  80701. /* Opcodes that are used as the bottom of a loop (OP_Next, OP_Prev,
  80702. ** OP_VNext, or OP_SorterNext) all jump here upon
  80703. ** completion. Check to see if sqlite3_interrupt() has been called
  80704. ** or if the progress callback needs to be invoked.
  80705. **
  80706. ** This code uses unstructured "goto" statements and does not look clean.
  80707. ** But that is not due to sloppy coding habits. The code is written this
  80708. ** way for performance, to avoid having to run the interrupt and progress
  80709. ** checks on every opcode. This helps sqlite3_step() to run about 1.5%
  80710. ** faster according to "valgrind --tool=cachegrind" */
  80711. check_for_interrupt:
  80712. if( AtomicLoad(&db->u1.isInterrupted) ) goto abort_due_to_interrupt;
  80713. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  80714. /* Call the progress callback if it is configured and the required number
  80715. ** of VDBE ops have been executed (either since this invocation of
  80716. ** sqlite3VdbeExec() or since last time the progress callback was called).
  80717. ** If the progress callback returns non-zero, exit the virtual machine with
  80718. ** a return code SQLITE_ABORT.
  80719. */
  80720. while( nVmStep>=nProgressLimit && db->xProgress!=0 ){
  80721. assert( db->nProgressOps!=0 );
  80722. nProgressLimit += db->nProgressOps;
  80723. if( db->xProgress(db->pProgressArg) ){
  80724. nProgressLimit = 0xffffffff;
  80725. rc = SQLITE_INTERRUPT;
  80726. goto abort_due_to_error;
  80727. }
  80728. }
  80729. #endif
  80730. break;
  80731. }
  80732. /* Opcode: Gosub P1 P2 * * *
  80733. **
  80734. ** Write the current address onto register P1
  80735. ** and then jump to address P2.
  80736. */
  80737. case OP_Gosub: { /* jump */
  80738. assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
  80739. pIn1 = &aMem[pOp->p1];
  80740. assert( VdbeMemDynamic(pIn1)==0 );
  80741. memAboutToChange(p, pIn1);
  80742. pIn1->flags = MEM_Int;
  80743. pIn1->u.i = (int)(pOp-aOp);
  80744. REGISTER_TRACE(pOp->p1, pIn1);
  80745. /* Most jump operations do a goto to this spot in order to update
  80746. ** the pOp pointer. */
  80747. jump_to_p2:
  80748. pOp = &aOp[pOp->p2 - 1];
  80749. break;
  80750. }
  80751. /* Opcode: Return P1 * * * *
  80752. **
  80753. ** Jump to the next instruction after the address in register P1. After
  80754. ** the jump, register P1 becomes undefined.
  80755. */
  80756. case OP_Return: { /* in1 */
  80757. pIn1 = &aMem[pOp->p1];
  80758. assert( pIn1->flags==MEM_Int );
  80759. pOp = &aOp[pIn1->u.i];
  80760. pIn1->flags = MEM_Undefined;
  80761. break;
  80762. }
  80763. /* Opcode: InitCoroutine P1 P2 P3 * *
  80764. **
  80765. ** Set up register P1 so that it will Yield to the coroutine
  80766. ** located at address P3.
  80767. **
  80768. ** If P2!=0 then the coroutine implementation immediately follows
  80769. ** this opcode. So jump over the coroutine implementation to
  80770. ** address P2.
  80771. **
  80772. ** See also: EndCoroutine
  80773. */
  80774. case OP_InitCoroutine: { /* jump */
  80775. assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
  80776. assert( pOp->p2>=0 && pOp->p2<p->nOp );
  80777. assert( pOp->p3>=0 && pOp->p3<p->nOp );
  80778. pOut = &aMem[pOp->p1];
  80779. assert( !VdbeMemDynamic(pOut) );
  80780. pOut->u.i = pOp->p3 - 1;
  80781. pOut->flags = MEM_Int;
  80782. if( pOp->p2 ) goto jump_to_p2;
  80783. break;
  80784. }
  80785. /* Opcode: EndCoroutine P1 * * * *
  80786. **
  80787. ** The instruction at the address in register P1 is a Yield.
  80788. ** Jump to the P2 parameter of that Yield.
  80789. ** After the jump, register P1 becomes undefined.
  80790. **
  80791. ** See also: InitCoroutine
  80792. */
  80793. case OP_EndCoroutine: { /* in1 */
  80794. VdbeOp *pCaller;
  80795. pIn1 = &aMem[pOp->p1];
  80796. assert( pIn1->flags==MEM_Int );
  80797. assert( pIn1->u.i>=0 && pIn1->u.i<p->nOp );
  80798. pCaller = &aOp[pIn1->u.i];
  80799. assert( pCaller->opcode==OP_Yield );
  80800. assert( pCaller->p2>=0 && pCaller->p2<p->nOp );
  80801. pOp = &aOp[pCaller->p2 - 1];
  80802. pIn1->flags = MEM_Undefined;
  80803. break;
  80804. }
  80805. /* Opcode: Yield P1 P2 * * *
  80806. **
  80807. ** Swap the program counter with the value in register P1. This
  80808. ** has the effect of yielding to a coroutine.
  80809. **
  80810. ** If the coroutine that is launched by this instruction ends with
  80811. ** Yield or Return then continue to the next instruction. But if
  80812. ** the coroutine launched by this instruction ends with
  80813. ** EndCoroutine, then jump to P2 rather than continuing with the
  80814. ** next instruction.
  80815. **
  80816. ** See also: InitCoroutine
  80817. */
  80818. case OP_Yield: { /* in1, jump */
  80819. int pcDest;
  80820. pIn1 = &aMem[pOp->p1];
  80821. assert( VdbeMemDynamic(pIn1)==0 );
  80822. pIn1->flags = MEM_Int;
  80823. pcDest = (int)pIn1->u.i;
  80824. pIn1->u.i = (int)(pOp - aOp);
  80825. REGISTER_TRACE(pOp->p1, pIn1);
  80826. pOp = &aOp[pcDest];
  80827. break;
  80828. }
  80829. /* Opcode: HaltIfNull P1 P2 P3 P4 P5
  80830. ** Synopsis: if r[P3]=null halt
  80831. **
  80832. ** Check the value in register P3. If it is NULL then Halt using
  80833. ** parameter P1, P2, and P4 as if this were a Halt instruction. If the
  80834. ** value in register P3 is not NULL, then this routine is a no-op.
  80835. ** The P5 parameter should be 1.
  80836. */
  80837. case OP_HaltIfNull: { /* in3 */
  80838. pIn3 = &aMem[pOp->p3];
  80839. #ifdef SQLITE_DEBUG
  80840. if( pOp->p2==OE_Abort ){ sqlite3VdbeAssertAbortable(p); }
  80841. #endif
  80842. if( (pIn3->flags & MEM_Null)==0 ) break;
  80843. /* Fall through into OP_Halt */
  80844. }
  80845. /* Opcode: Halt P1 P2 * P4 P5
  80846. **
  80847. ** Exit immediately. All open cursors, etc are closed
  80848. ** automatically.
  80849. **
  80850. ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
  80851. ** or sqlite3_finalize(). For a normal halt, this should be SQLITE_OK (0).
  80852. ** For errors, it can be some other value. If P1!=0 then P2 will determine
  80853. ** whether or not to rollback the current transaction. Do not rollback
  80854. ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback. If P2==OE_Abort,
  80855. ** then back out all changes that have occurred during this execution of the
  80856. ** VDBE, but do not rollback the transaction.
  80857. **
  80858. ** If P4 is not null then it is an error message string.
  80859. **
  80860. ** P5 is a value between 0 and 4, inclusive, that modifies the P4 string.
  80861. **
  80862. ** 0: (no change)
  80863. ** 1: NOT NULL contraint failed: P4
  80864. ** 2: UNIQUE constraint failed: P4
  80865. ** 3: CHECK constraint failed: P4
  80866. ** 4: FOREIGN KEY constraint failed: P4
  80867. **
  80868. ** If P5 is not zero and P4 is NULL, then everything after the ":" is
  80869. ** omitted.
  80870. **
  80871. ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
  80872. ** every program. So a jump past the last instruction of the program
  80873. ** is the same as executing Halt.
  80874. */
  80875. case OP_Halt: {
  80876. VdbeFrame *pFrame;
  80877. int pcx;
  80878. pcx = (int)(pOp - aOp);
  80879. #ifdef SQLITE_DEBUG
  80880. if( pOp->p2==OE_Abort ){ sqlite3VdbeAssertAbortable(p); }
  80881. #endif
  80882. if( pOp->p1==SQLITE_OK && p->pFrame ){
  80883. /* Halt the sub-program. Return control to the parent frame. */
  80884. pFrame = p->pFrame;
  80885. p->pFrame = pFrame->pParent;
  80886. p->nFrame--;
  80887. sqlite3VdbeSetChanges(db, p->nChange);
  80888. pcx = sqlite3VdbeFrameRestore(pFrame);
  80889. if( pOp->p2==OE_Ignore ){
  80890. /* Instruction pcx is the OP_Program that invoked the sub-program
  80891. ** currently being halted. If the p2 instruction of this OP_Halt
  80892. ** instruction is set to OE_Ignore, then the sub-program is throwing
  80893. ** an IGNORE exception. In this case jump to the address specified
  80894. ** as the p2 of the calling OP_Program. */
  80895. pcx = p->aOp[pcx].p2-1;
  80896. }
  80897. aOp = p->aOp;
  80898. aMem = p->aMem;
  80899. pOp = &aOp[pcx];
  80900. break;
  80901. }
  80902. p->rc = pOp->p1;
  80903. p->errorAction = (u8)pOp->p2;
  80904. p->pc = pcx;
  80905. assert( pOp->p5<=4 );
  80906. if( p->rc ){
  80907. if( pOp->p5 ){
  80908. static const char * const azType[] = { "NOT NULL", "UNIQUE", "CHECK",
  80909. "FOREIGN KEY" };
  80910. testcase( pOp->p5==1 );
  80911. testcase( pOp->p5==2 );
  80912. testcase( pOp->p5==3 );
  80913. testcase( pOp->p5==4 );
  80914. sqlite3VdbeError(p, "%s constraint failed", azType[pOp->p5-1]);
  80915. if( pOp->p4.z ){
  80916. p->zErrMsg = sqlite3MPrintf(db, "%z: %s", p->zErrMsg, pOp->p4.z);
  80917. }
  80918. }else{
  80919. sqlite3VdbeError(p, "%s", pOp->p4.z);
  80920. }
  80921. sqlite3_log(pOp->p1, "abort at %d in [%s]: %s", pcx, p->zSql, p->zErrMsg);
  80922. }
  80923. rc = sqlite3VdbeHalt(p);
  80924. assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
  80925. if( rc==SQLITE_BUSY ){
  80926. p->rc = SQLITE_BUSY;
  80927. }else{
  80928. assert( rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT );
  80929. assert( rc==SQLITE_OK || db->nDeferredCons>0 || db->nDeferredImmCons>0 );
  80930. rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
  80931. }
  80932. goto vdbe_return;
  80933. }
  80934. /* Opcode: Integer P1 P2 * * *
  80935. ** Synopsis: r[P2]=P1
  80936. **
  80937. ** The 32-bit integer value P1 is written into register P2.
  80938. */
  80939. case OP_Integer: { /* out2 */
  80940. pOut = out2Prerelease(p, pOp);
  80941. pOut->u.i = pOp->p1;
  80942. break;
  80943. }
  80944. /* Opcode: Int64 * P2 * P4 *
  80945. ** Synopsis: r[P2]=P4
  80946. **
  80947. ** P4 is a pointer to a 64-bit integer value.
  80948. ** Write that value into register P2.
  80949. */
  80950. case OP_Int64: { /* out2 */
  80951. pOut = out2Prerelease(p, pOp);
  80952. assert( pOp->p4.pI64!=0 );
  80953. pOut->u.i = *pOp->p4.pI64;
  80954. break;
  80955. }
  80956. #ifndef SQLITE_OMIT_FLOATING_POINT
  80957. /* Opcode: Real * P2 * P4 *
  80958. ** Synopsis: r[P2]=P4
  80959. **
  80960. ** P4 is a pointer to a 64-bit floating point value.
  80961. ** Write that value into register P2.
  80962. */
  80963. case OP_Real: { /* same as TK_FLOAT, out2 */
  80964. pOut = out2Prerelease(p, pOp);
  80965. pOut->flags = MEM_Real;
  80966. assert( !sqlite3IsNaN(*pOp->p4.pReal) );
  80967. pOut->u.r = *pOp->p4.pReal;
  80968. break;
  80969. }
  80970. #endif
  80971. /* Opcode: String8 * P2 * P4 *
  80972. ** Synopsis: r[P2]='P4'
  80973. **
  80974. ** P4 points to a nul terminated UTF-8 string. This opcode is transformed
  80975. ** into a String opcode before it is executed for the first time. During
  80976. ** this transformation, the length of string P4 is computed and stored
  80977. ** as the P1 parameter.
  80978. */
  80979. case OP_String8: { /* same as TK_STRING, out2 */
  80980. assert( pOp->p4.z!=0 );
  80981. pOut = out2Prerelease(p, pOp);
  80982. pOp->p1 = sqlite3Strlen30(pOp->p4.z);
  80983. #ifndef SQLITE_OMIT_UTF16
  80984. if( encoding!=SQLITE_UTF8 ){
  80985. rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
  80986. assert( rc==SQLITE_OK || rc==SQLITE_TOOBIG );
  80987. if( rc ) goto too_big;
  80988. if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
  80989. assert( pOut->szMalloc>0 && pOut->zMalloc==pOut->z );
  80990. assert( VdbeMemDynamic(pOut)==0 );
  80991. pOut->szMalloc = 0;
  80992. pOut->flags |= MEM_Static;
  80993. if( pOp->p4type==P4_DYNAMIC ){
  80994. sqlite3DbFree(db, pOp->p4.z);
  80995. }
  80996. pOp->p4type = P4_DYNAMIC;
  80997. pOp->p4.z = pOut->z;
  80998. pOp->p1 = pOut->n;
  80999. }
  81000. #endif
  81001. if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  81002. goto too_big;
  81003. }
  81004. pOp->opcode = OP_String;
  81005. assert( rc==SQLITE_OK );
  81006. /* Fall through to the next case, OP_String */
  81007. }
  81008. /* Opcode: String P1 P2 P3 P4 P5
  81009. ** Synopsis: r[P2]='P4' (len=P1)
  81010. **
  81011. ** The string value P4 of length P1 (bytes) is stored in register P2.
  81012. **
  81013. ** If P3 is not zero and the content of register P3 is equal to P5, then
  81014. ** the datatype of the register P2 is converted to BLOB. The content is
  81015. ** the same sequence of bytes, it is merely interpreted as a BLOB instead
  81016. ** of a string, as if it had been CAST. In other words:
  81017. **
  81018. ** if( P3!=0 and reg[P3]==P5 ) reg[P2] := CAST(reg[P2] as BLOB)
  81019. */
  81020. case OP_String: { /* out2 */
  81021. assert( pOp->p4.z!=0 );
  81022. pOut = out2Prerelease(p, pOp);
  81023. pOut->flags = MEM_Str|MEM_Static|MEM_Term;
  81024. pOut->z = pOp->p4.z;
  81025. pOut->n = pOp->p1;
  81026. pOut->enc = encoding;
  81027. UPDATE_MAX_BLOBSIZE(pOut);
  81028. #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
  81029. if( pOp->p3>0 ){
  81030. assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
  81031. pIn3 = &aMem[pOp->p3];
  81032. assert( pIn3->flags & MEM_Int );
  81033. if( pIn3->u.i==pOp->p5 ) pOut->flags = MEM_Blob|MEM_Static|MEM_Term;
  81034. }
  81035. #endif
  81036. break;
  81037. }
  81038. /* Opcode: Null P1 P2 P3 * *
  81039. ** Synopsis: r[P2..P3]=NULL
  81040. **
  81041. ** Write a NULL into registers P2. If P3 greater than P2, then also write
  81042. ** NULL into register P3 and every register in between P2 and P3. If P3
  81043. ** is less than P2 (typically P3 is zero) then only register P2 is
  81044. ** set to NULL.
  81045. **
  81046. ** If the P1 value is non-zero, then also set the MEM_Cleared flag so that
  81047. ** NULL values will not compare equal even if SQLITE_NULLEQ is set on
  81048. ** OP_Ne or OP_Eq.
  81049. */
  81050. case OP_Null: { /* out2 */
  81051. int cnt;
  81052. u16 nullFlag;
  81053. pOut = out2Prerelease(p, pOp);
  81054. cnt = pOp->p3-pOp->p2;
  81055. assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
  81056. pOut->flags = nullFlag = pOp->p1 ? (MEM_Null|MEM_Cleared) : MEM_Null;
  81057. pOut->n = 0;
  81058. #ifdef SQLITE_DEBUG
  81059. pOut->uTemp = 0;
  81060. #endif
  81061. while( cnt>0 ){
  81062. pOut++;
  81063. memAboutToChange(p, pOut);
  81064. sqlite3VdbeMemSetNull(pOut);
  81065. pOut->flags = nullFlag;
  81066. pOut->n = 0;
  81067. cnt--;
  81068. }
  81069. break;
  81070. }
  81071. /* Opcode: SoftNull P1 * * * *
  81072. ** Synopsis: r[P1]=NULL
  81073. **
  81074. ** Set register P1 to have the value NULL as seen by the OP_MakeRecord
  81075. ** instruction, but do not free any string or blob memory associated with
  81076. ** the register, so that if the value was a string or blob that was
  81077. ** previously copied using OP_SCopy, the copies will continue to be valid.
  81078. */
  81079. case OP_SoftNull: {
  81080. assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
  81081. pOut = &aMem[pOp->p1];
  81082. pOut->flags = (pOut->flags&~(MEM_Undefined|MEM_AffMask))|MEM_Null;
  81083. break;
  81084. }
  81085. /* Opcode: Blob P1 P2 * P4 *
  81086. ** Synopsis: r[P2]=P4 (len=P1)
  81087. **
  81088. ** P4 points to a blob of data P1 bytes long. Store this
  81089. ** blob in register P2.
  81090. */
  81091. case OP_Blob: { /* out2 */
  81092. assert( pOp->p1 <= SQLITE_MAX_LENGTH );
  81093. pOut = out2Prerelease(p, pOp);
  81094. sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
  81095. pOut->enc = encoding;
  81096. UPDATE_MAX_BLOBSIZE(pOut);
  81097. break;
  81098. }
  81099. /* Opcode: Variable P1 P2 * P4 *
  81100. ** Synopsis: r[P2]=parameter(P1,P4)
  81101. **
  81102. ** Transfer the values of bound parameter P1 into register P2
  81103. **
  81104. ** If the parameter is named, then its name appears in P4.
  81105. ** The P4 value is used by sqlite3_bind_parameter_name().
  81106. */
  81107. case OP_Variable: { /* out2 */
  81108. Mem *pVar; /* Value being transferred */
  81109. assert( pOp->p1>0 && pOp->p1<=p->nVar );
  81110. assert( pOp->p4.z==0 || pOp->p4.z==sqlite3VListNumToName(p->pVList,pOp->p1) );
  81111. pVar = &p->aVar[pOp->p1 - 1];
  81112. if( sqlite3VdbeMemTooBig(pVar) ){
  81113. goto too_big;
  81114. }
  81115. pOut = &aMem[pOp->p2];
  81116. if( VdbeMemDynamic(pOut) ) sqlite3VdbeMemSetNull(pOut);
  81117. memcpy(pOut, pVar, MEMCELLSIZE);
  81118. pOut->flags &= ~(MEM_Dyn|MEM_Ephem);
  81119. pOut->flags |= MEM_Static|MEM_FromBind;
  81120. UPDATE_MAX_BLOBSIZE(pOut);
  81121. break;
  81122. }
  81123. /* Opcode: Move P1 P2 P3 * *
  81124. ** Synopsis: r[P2@P3]=r[P1@P3]
  81125. **
  81126. ** Move the P3 values in register P1..P1+P3-1 over into
  81127. ** registers P2..P2+P3-1. Registers P1..P1+P3-1 are
  81128. ** left holding a NULL. It is an error for register ranges
  81129. ** P1..P1+P3-1 and P2..P2+P3-1 to overlap. It is an error
  81130. ** for P3 to be less than 1.
  81131. */
  81132. case OP_Move: {
  81133. int n; /* Number of registers left to copy */
  81134. int p1; /* Register to copy from */
  81135. int p2; /* Register to copy to */
  81136. n = pOp->p3;
  81137. p1 = pOp->p1;
  81138. p2 = pOp->p2;
  81139. assert( n>0 && p1>0 && p2>0 );
  81140. assert( p1+n<=p2 || p2+n<=p1 );
  81141. pIn1 = &aMem[p1];
  81142. pOut = &aMem[p2];
  81143. do{
  81144. assert( pOut<=&aMem[(p->nMem+1 - p->nCursor)] );
  81145. assert( pIn1<=&aMem[(p->nMem+1 - p->nCursor)] );
  81146. assert( memIsValid(pIn1) );
  81147. memAboutToChange(p, pOut);
  81148. sqlite3VdbeMemMove(pOut, pIn1);
  81149. #ifdef SQLITE_DEBUG
  81150. pIn1->pScopyFrom = 0;
  81151. { int i;
  81152. for(i=1; i<p->nMem; i++){
  81153. if( aMem[i].pScopyFrom==pIn1 ){
  81154. aMem[i].pScopyFrom = pOut;
  81155. }
  81156. }
  81157. }
  81158. #endif
  81159. Deephemeralize(pOut);
  81160. REGISTER_TRACE(p2++, pOut);
  81161. pIn1++;
  81162. pOut++;
  81163. }while( --n );
  81164. break;
  81165. }
  81166. /* Opcode: Copy P1 P2 P3 * *
  81167. ** Synopsis: r[P2@P3+1]=r[P1@P3+1]
  81168. **
  81169. ** Make a copy of registers P1..P1+P3 into registers P2..P2+P3.
  81170. **
  81171. ** This instruction makes a deep copy of the value. A duplicate
  81172. ** is made of any string or blob constant. See also OP_SCopy.
  81173. */
  81174. case OP_Copy: {
  81175. int n;
  81176. n = pOp->p3;
  81177. pIn1 = &aMem[pOp->p1];
  81178. pOut = &aMem[pOp->p2];
  81179. assert( pOut!=pIn1 );
  81180. while( 1 ){
  81181. memAboutToChange(p, pOut);
  81182. sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
  81183. Deephemeralize(pOut);
  81184. #ifdef SQLITE_DEBUG
  81185. pOut->pScopyFrom = 0;
  81186. #endif
  81187. REGISTER_TRACE(pOp->p2+pOp->p3-n, pOut);
  81188. if( (n--)==0 ) break;
  81189. pOut++;
  81190. pIn1++;
  81191. }
  81192. break;
  81193. }
  81194. /* Opcode: SCopy P1 P2 * * *
  81195. ** Synopsis: r[P2]=r[P1]
  81196. **
  81197. ** Make a shallow copy of register P1 into register P2.
  81198. **
  81199. ** This instruction makes a shallow copy of the value. If the value
  81200. ** is a string or blob, then the copy is only a pointer to the
  81201. ** original and hence if the original changes so will the copy.
  81202. ** Worse, if the original is deallocated, the copy becomes invalid.
  81203. ** Thus the program must guarantee that the original will not change
  81204. ** during the lifetime of the copy. Use OP_Copy to make a complete
  81205. ** copy.
  81206. */
  81207. case OP_SCopy: { /* out2 */
  81208. pIn1 = &aMem[pOp->p1];
  81209. pOut = &aMem[pOp->p2];
  81210. assert( pOut!=pIn1 );
  81211. sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
  81212. #ifdef SQLITE_DEBUG
  81213. pOut->pScopyFrom = pIn1;
  81214. pOut->mScopyFlags = pIn1->flags;
  81215. #endif
  81216. break;
  81217. }
  81218. /* Opcode: IntCopy P1 P2 * * *
  81219. ** Synopsis: r[P2]=r[P1]
  81220. **
  81221. ** Transfer the integer value held in register P1 into register P2.
  81222. **
  81223. ** This is an optimized version of SCopy that works only for integer
  81224. ** values.
  81225. */
  81226. case OP_IntCopy: { /* out2 */
  81227. pIn1 = &aMem[pOp->p1];
  81228. assert( (pIn1->flags & MEM_Int)!=0 );
  81229. pOut = &aMem[pOp->p2];
  81230. sqlite3VdbeMemSetInt64(pOut, pIn1->u.i);
  81231. break;
  81232. }
  81233. /* Opcode: ResultRow P1 P2 * * *
  81234. ** Synopsis: output=r[P1@P2]
  81235. **
  81236. ** The registers P1 through P1+P2-1 contain a single row of
  81237. ** results. This opcode causes the sqlite3_step() call to terminate
  81238. ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
  81239. ** structure to provide access to the r(P1)..r(P1+P2-1) values as
  81240. ** the result row.
  81241. */
  81242. case OP_ResultRow: {
  81243. Mem *pMem;
  81244. int i;
  81245. assert( p->nResColumn==pOp->p2 );
  81246. assert( pOp->p1>0 );
  81247. assert( pOp->p1+pOp->p2<=(p->nMem+1 - p->nCursor)+1 );
  81248. /* If this statement has violated immediate foreign key constraints, do
  81249. ** not return the number of rows modified. And do not RELEASE the statement
  81250. ** transaction. It needs to be rolled back. */
  81251. if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){
  81252. assert( db->flags&SQLITE_CountRows );
  81253. assert( p->usesStmtJournal );
  81254. goto abort_due_to_error;
  81255. }
  81256. /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then
  81257. ** DML statements invoke this opcode to return the number of rows
  81258. ** modified to the user. This is the only way that a VM that
  81259. ** opens a statement transaction may invoke this opcode.
  81260. **
  81261. ** In case this is such a statement, close any statement transaction
  81262. ** opened by this VM before returning control to the user. This is to
  81263. ** ensure that statement-transactions are always nested, not overlapping.
  81264. ** If the open statement-transaction is not closed here, then the user
  81265. ** may step another VM that opens its own statement transaction. This
  81266. ** may lead to overlapping statement transactions.
  81267. **
  81268. ** The statement transaction is never a top-level transaction. Hence
  81269. ** the RELEASE call below can never fail.
  81270. */
  81271. assert( p->iStatement==0 || db->flags&SQLITE_CountRows );
  81272. rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE);
  81273. assert( rc==SQLITE_OK );
  81274. /* Invalidate all ephemeral cursor row caches */
  81275. p->cacheCtr = (p->cacheCtr + 2)|1;
  81276. /* Make sure the results of the current row are \000 terminated
  81277. ** and have an assigned type. The results are de-ephemeralized as
  81278. ** a side effect.
  81279. */
  81280. pMem = p->pResultSet = &aMem[pOp->p1];
  81281. for(i=0; i<pOp->p2; i++){
  81282. assert( memIsValid(&pMem[i]) );
  81283. Deephemeralize(&pMem[i]);
  81284. assert( (pMem[i].flags & MEM_Ephem)==0
  81285. || (pMem[i].flags & (MEM_Str|MEM_Blob))==0 );
  81286. sqlite3VdbeMemNulTerminate(&pMem[i]);
  81287. REGISTER_TRACE(pOp->p1+i, &pMem[i]);
  81288. #ifdef SQLITE_DEBUG
  81289. /* The registers in the result will not be used again when the
  81290. ** prepared statement restarts. This is because sqlite3_column()
  81291. ** APIs might have caused type conversions of made other changes to
  81292. ** the register values. Therefore, we can go ahead and break any
  81293. ** OP_SCopy dependencies. */
  81294. pMem[i].pScopyFrom = 0;
  81295. #endif
  81296. }
  81297. if( db->mallocFailed ) goto no_mem;
  81298. if( db->mTrace & SQLITE_TRACE_ROW ){
  81299. db->xTrace(SQLITE_TRACE_ROW, db->pTraceArg, p, 0);
  81300. }
  81301. /* Return SQLITE_ROW
  81302. */
  81303. p->pc = (int)(pOp - aOp) + 1;
  81304. rc = SQLITE_ROW;
  81305. goto vdbe_return;
  81306. }
  81307. /* Opcode: Concat P1 P2 P3 * *
  81308. ** Synopsis: r[P3]=r[P2]+r[P1]
  81309. **
  81310. ** Add the text in register P1 onto the end of the text in
  81311. ** register P2 and store the result in register P3.
  81312. ** If either the P1 or P2 text are NULL then store NULL in P3.
  81313. **
  81314. ** P3 = P2 || P1
  81315. **
  81316. ** It is illegal for P1 and P3 to be the same register. Sometimes,
  81317. ** if P3 is the same register as P2, the implementation is able
  81318. ** to avoid a memcpy().
  81319. */
  81320. case OP_Concat: { /* same as TK_CONCAT, in1, in2, out3 */
  81321. i64 nByte; /* Total size of the output string or blob */
  81322. u16 flags1; /* Initial flags for P1 */
  81323. u16 flags2; /* Initial flags for P2 */
  81324. pIn1 = &aMem[pOp->p1];
  81325. pIn2 = &aMem[pOp->p2];
  81326. pOut = &aMem[pOp->p3];
  81327. testcase( pOut==pIn2 );
  81328. assert( pIn1!=pOut );
  81329. flags1 = pIn1->flags;
  81330. testcase( flags1 & MEM_Null );
  81331. testcase( pIn2->flags & MEM_Null );
  81332. if( (flags1 | pIn2->flags) & MEM_Null ){
  81333. sqlite3VdbeMemSetNull(pOut);
  81334. break;
  81335. }
  81336. if( (flags1 & (MEM_Str|MEM_Blob))==0 ){
  81337. if( sqlite3VdbeMemStringify(pIn1,encoding,0) ) goto no_mem;
  81338. flags1 = pIn1->flags & ~MEM_Str;
  81339. }else if( (flags1 & MEM_Zero)!=0 ){
  81340. if( sqlite3VdbeMemExpandBlob(pIn1) ) goto no_mem;
  81341. flags1 = pIn1->flags & ~MEM_Str;
  81342. }
  81343. flags2 = pIn2->flags;
  81344. if( (flags2 & (MEM_Str|MEM_Blob))==0 ){
  81345. if( sqlite3VdbeMemStringify(pIn2,encoding,0) ) goto no_mem;
  81346. flags2 = pIn2->flags & ~MEM_Str;
  81347. }else if( (flags2 & MEM_Zero)!=0 ){
  81348. if( sqlite3VdbeMemExpandBlob(pIn2) ) goto no_mem;
  81349. flags2 = pIn2->flags & ~MEM_Str;
  81350. }
  81351. nByte = pIn1->n + pIn2->n;
  81352. if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  81353. goto too_big;
  81354. }
  81355. if( sqlite3VdbeMemGrow(pOut, (int)nByte+3, pOut==pIn2) ){
  81356. goto no_mem;
  81357. }
  81358. MemSetTypeFlag(pOut, MEM_Str);
  81359. if( pOut!=pIn2 ){
  81360. memcpy(pOut->z, pIn2->z, pIn2->n);
  81361. assert( (pIn2->flags & MEM_Dyn) == (flags2 & MEM_Dyn) );
  81362. pIn2->flags = flags2;
  81363. }
  81364. memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
  81365. assert( (pIn1->flags & MEM_Dyn) == (flags1 & MEM_Dyn) );
  81366. pIn1->flags = flags1;
  81367. pOut->z[nByte]=0;
  81368. pOut->z[nByte+1] = 0;
  81369. pOut->z[nByte+2] = 0;
  81370. pOut->flags |= MEM_Term;
  81371. pOut->n = (int)nByte;
  81372. pOut->enc = encoding;
  81373. UPDATE_MAX_BLOBSIZE(pOut);
  81374. break;
  81375. }
  81376. /* Opcode: Add P1 P2 P3 * *
  81377. ** Synopsis: r[P3]=r[P1]+r[P2]
  81378. **
  81379. ** Add the value in register P1 to the value in register P2
  81380. ** and store the result in register P3.
  81381. ** If either input is NULL, the result is NULL.
  81382. */
  81383. /* Opcode: Multiply P1 P2 P3 * *
  81384. ** Synopsis: r[P3]=r[P1]*r[P2]
  81385. **
  81386. **
  81387. ** Multiply the value in register P1 by the value in register P2
  81388. ** and store the result in register P3.
  81389. ** If either input is NULL, the result is NULL.
  81390. */
  81391. /* Opcode: Subtract P1 P2 P3 * *
  81392. ** Synopsis: r[P3]=r[P2]-r[P1]
  81393. **
  81394. ** Subtract the value in register P1 from the value in register P2
  81395. ** and store the result in register P3.
  81396. ** If either input is NULL, the result is NULL.
  81397. */
  81398. /* Opcode: Divide P1 P2 P3 * *
  81399. ** Synopsis: r[P3]=r[P2]/r[P1]
  81400. **
  81401. ** Divide the value in register P1 by the value in register P2
  81402. ** and store the result in register P3 (P3=P2/P1). If the value in
  81403. ** register P1 is zero, then the result is NULL. If either input is
  81404. ** NULL, the result is NULL.
  81405. */
  81406. /* Opcode: Remainder P1 P2 P3 * *
  81407. ** Synopsis: r[P3]=r[P2]%r[P1]
  81408. **
  81409. ** Compute the remainder after integer register P2 is divided by
  81410. ** register P1 and store the result in register P3.
  81411. ** If the value in register P1 is zero the result is NULL.
  81412. ** If either operand is NULL, the result is NULL.
  81413. */
  81414. case OP_Add: /* same as TK_PLUS, in1, in2, out3 */
  81415. case OP_Subtract: /* same as TK_MINUS, in1, in2, out3 */
  81416. case OP_Multiply: /* same as TK_STAR, in1, in2, out3 */
  81417. case OP_Divide: /* same as TK_SLASH, in1, in2, out3 */
  81418. case OP_Remainder: { /* same as TK_REM, in1, in2, out3 */
  81419. u16 flags; /* Combined MEM_* flags from both inputs */
  81420. u16 type1; /* Numeric type of left operand */
  81421. u16 type2; /* Numeric type of right operand */
  81422. i64 iA; /* Integer value of left operand */
  81423. i64 iB; /* Integer value of right operand */
  81424. double rA; /* Real value of left operand */
  81425. double rB; /* Real value of right operand */
  81426. pIn1 = &aMem[pOp->p1];
  81427. type1 = numericType(pIn1);
  81428. pIn2 = &aMem[pOp->p2];
  81429. type2 = numericType(pIn2);
  81430. pOut = &aMem[pOp->p3];
  81431. flags = pIn1->flags | pIn2->flags;
  81432. if( (type1 & type2 & MEM_Int)!=0 ){
  81433. iA = pIn1->u.i;
  81434. iB = pIn2->u.i;
  81435. switch( pOp->opcode ){
  81436. case OP_Add: if( sqlite3AddInt64(&iB,iA) ) goto fp_math; break;
  81437. case OP_Subtract: if( sqlite3SubInt64(&iB,iA) ) goto fp_math; break;
  81438. case OP_Multiply: if( sqlite3MulInt64(&iB,iA) ) goto fp_math; break;
  81439. case OP_Divide: {
  81440. if( iA==0 ) goto arithmetic_result_is_null;
  81441. if( iA==-1 && iB==SMALLEST_INT64 ) goto fp_math;
  81442. iB /= iA;
  81443. break;
  81444. }
  81445. default: {
  81446. if( iA==0 ) goto arithmetic_result_is_null;
  81447. if( iA==-1 ) iA = 1;
  81448. iB %= iA;
  81449. break;
  81450. }
  81451. }
  81452. pOut->u.i = iB;
  81453. MemSetTypeFlag(pOut, MEM_Int);
  81454. }else if( (flags & MEM_Null)!=0 ){
  81455. goto arithmetic_result_is_null;
  81456. }else{
  81457. fp_math:
  81458. rA = sqlite3VdbeRealValue(pIn1);
  81459. rB = sqlite3VdbeRealValue(pIn2);
  81460. switch( pOp->opcode ){
  81461. case OP_Add: rB += rA; break;
  81462. case OP_Subtract: rB -= rA; break;
  81463. case OP_Multiply: rB *= rA; break;
  81464. case OP_Divide: {
  81465. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  81466. if( rA==(double)0 ) goto arithmetic_result_is_null;
  81467. rB /= rA;
  81468. break;
  81469. }
  81470. default: {
  81471. iA = sqlite3VdbeIntValue(pIn1);
  81472. iB = sqlite3VdbeIntValue(pIn2);
  81473. if( iA==0 ) goto arithmetic_result_is_null;
  81474. if( iA==-1 ) iA = 1;
  81475. rB = (double)(iB % iA);
  81476. break;
  81477. }
  81478. }
  81479. #ifdef SQLITE_OMIT_FLOATING_POINT
  81480. pOut->u.i = rB;
  81481. MemSetTypeFlag(pOut, MEM_Int);
  81482. #else
  81483. if( sqlite3IsNaN(rB) ){
  81484. goto arithmetic_result_is_null;
  81485. }
  81486. pOut->u.r = rB;
  81487. MemSetTypeFlag(pOut, MEM_Real);
  81488. #endif
  81489. }
  81490. break;
  81491. arithmetic_result_is_null:
  81492. sqlite3VdbeMemSetNull(pOut);
  81493. break;
  81494. }
  81495. /* Opcode: CollSeq P1 * * P4
  81496. **
  81497. ** P4 is a pointer to a CollSeq object. If the next call to a user function
  81498. ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
  81499. ** be returned. This is used by the built-in min(), max() and nullif()
  81500. ** functions.
  81501. **
  81502. ** If P1 is not zero, then it is a register that a subsequent min() or
  81503. ** max() aggregate will set to 1 if the current row is not the minimum or
  81504. ** maximum. The P1 register is initialized to 0 by this instruction.
  81505. **
  81506. ** The interface used by the implementation of the aforementioned functions
  81507. ** to retrieve the collation sequence set by this opcode is not available
  81508. ** publicly. Only built-in functions have access to this feature.
  81509. */
  81510. case OP_CollSeq: {
  81511. assert( pOp->p4type==P4_COLLSEQ );
  81512. if( pOp->p1 ){
  81513. sqlite3VdbeMemSetInt64(&aMem[pOp->p1], 0);
  81514. }
  81515. break;
  81516. }
  81517. /* Opcode: BitAnd P1 P2 P3 * *
  81518. ** Synopsis: r[P3]=r[P1]&r[P2]
  81519. **
  81520. ** Take the bit-wise AND of the values in register P1 and P2 and
  81521. ** store the result in register P3.
  81522. ** If either input is NULL, the result is NULL.
  81523. */
  81524. /* Opcode: BitOr P1 P2 P3 * *
  81525. ** Synopsis: r[P3]=r[P1]|r[P2]
  81526. **
  81527. ** Take the bit-wise OR of the values in register P1 and P2 and
  81528. ** store the result in register P3.
  81529. ** If either input is NULL, the result is NULL.
  81530. */
  81531. /* Opcode: ShiftLeft P1 P2 P3 * *
  81532. ** Synopsis: r[P3]=r[P2]<<r[P1]
  81533. **
  81534. ** Shift the integer value in register P2 to the left by the
  81535. ** number of bits specified by the integer in register P1.
  81536. ** Store the result in register P3.
  81537. ** If either input is NULL, the result is NULL.
  81538. */
  81539. /* Opcode: ShiftRight P1 P2 P3 * *
  81540. ** Synopsis: r[P3]=r[P2]>>r[P1]
  81541. **
  81542. ** Shift the integer value in register P2 to the right by the
  81543. ** number of bits specified by the integer in register P1.
  81544. ** Store the result in register P3.
  81545. ** If either input is NULL, the result is NULL.
  81546. */
  81547. case OP_BitAnd: /* same as TK_BITAND, in1, in2, out3 */
  81548. case OP_BitOr: /* same as TK_BITOR, in1, in2, out3 */
  81549. case OP_ShiftLeft: /* same as TK_LSHIFT, in1, in2, out3 */
  81550. case OP_ShiftRight: { /* same as TK_RSHIFT, in1, in2, out3 */
  81551. i64 iA;
  81552. u64 uA;
  81553. i64 iB;
  81554. u8 op;
  81555. pIn1 = &aMem[pOp->p1];
  81556. pIn2 = &aMem[pOp->p2];
  81557. pOut = &aMem[pOp->p3];
  81558. if( (pIn1->flags | pIn2->flags) & MEM_Null ){
  81559. sqlite3VdbeMemSetNull(pOut);
  81560. break;
  81561. }
  81562. iA = sqlite3VdbeIntValue(pIn2);
  81563. iB = sqlite3VdbeIntValue(pIn1);
  81564. op = pOp->opcode;
  81565. if( op==OP_BitAnd ){
  81566. iA &= iB;
  81567. }else if( op==OP_BitOr ){
  81568. iA |= iB;
  81569. }else if( iB!=0 ){
  81570. assert( op==OP_ShiftRight || op==OP_ShiftLeft );
  81571. /* If shifting by a negative amount, shift in the other direction */
  81572. if( iB<0 ){
  81573. assert( OP_ShiftRight==OP_ShiftLeft+1 );
  81574. op = 2*OP_ShiftLeft + 1 - op;
  81575. iB = iB>(-64) ? -iB : 64;
  81576. }
  81577. if( iB>=64 ){
  81578. iA = (iA>=0 || op==OP_ShiftLeft) ? 0 : -1;
  81579. }else{
  81580. memcpy(&uA, &iA, sizeof(uA));
  81581. if( op==OP_ShiftLeft ){
  81582. uA <<= iB;
  81583. }else{
  81584. uA >>= iB;
  81585. /* Sign-extend on a right shift of a negative number */
  81586. if( iA<0 ) uA |= ((((u64)0xffffffff)<<32)|0xffffffff) << (64-iB);
  81587. }
  81588. memcpy(&iA, &uA, sizeof(iA));
  81589. }
  81590. }
  81591. pOut->u.i = iA;
  81592. MemSetTypeFlag(pOut, MEM_Int);
  81593. break;
  81594. }
  81595. /* Opcode: AddImm P1 P2 * * *
  81596. ** Synopsis: r[P1]=r[P1]+P2
  81597. **
  81598. ** Add the constant P2 to the value in register P1.
  81599. ** The result is always an integer.
  81600. **
  81601. ** To force any register to be an integer, just add 0.
  81602. */
  81603. case OP_AddImm: { /* in1 */
  81604. pIn1 = &aMem[pOp->p1];
  81605. memAboutToChange(p, pIn1);
  81606. sqlite3VdbeMemIntegerify(pIn1);
  81607. pIn1->u.i += pOp->p2;
  81608. break;
  81609. }
  81610. /* Opcode: MustBeInt P1 P2 * * *
  81611. **
  81612. ** Force the value in register P1 to be an integer. If the value
  81613. ** in P1 is not an integer and cannot be converted into an integer
  81614. ** without data loss, then jump immediately to P2, or if P2==0
  81615. ** raise an SQLITE_MISMATCH exception.
  81616. */
  81617. case OP_MustBeInt: { /* jump, in1 */
  81618. pIn1 = &aMem[pOp->p1];
  81619. if( (pIn1->flags & MEM_Int)==0 ){
  81620. applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
  81621. if( (pIn1->flags & MEM_Int)==0 ){
  81622. VdbeBranchTaken(1, 2);
  81623. if( pOp->p2==0 ){
  81624. rc = SQLITE_MISMATCH;
  81625. goto abort_due_to_error;
  81626. }else{
  81627. goto jump_to_p2;
  81628. }
  81629. }
  81630. }
  81631. VdbeBranchTaken(0, 2);
  81632. MemSetTypeFlag(pIn1, MEM_Int);
  81633. break;
  81634. }
  81635. #ifndef SQLITE_OMIT_FLOATING_POINT
  81636. /* Opcode: RealAffinity P1 * * * *
  81637. **
  81638. ** If register P1 holds an integer convert it to a real value.
  81639. **
  81640. ** This opcode is used when extracting information from a column that
  81641. ** has REAL affinity. Such column values may still be stored as
  81642. ** integers, for space efficiency, but after extraction we want them
  81643. ** to have only a real value.
  81644. */
  81645. case OP_RealAffinity: { /* in1 */
  81646. pIn1 = &aMem[pOp->p1];
  81647. if( pIn1->flags & (MEM_Int|MEM_IntReal) ){
  81648. testcase( pIn1->flags & MEM_Int );
  81649. testcase( pIn1->flags & MEM_IntReal );
  81650. sqlite3VdbeMemRealify(pIn1);
  81651. REGISTER_TRACE(pOp->p1, pIn1);
  81652. }
  81653. break;
  81654. }
  81655. #endif
  81656. #ifndef SQLITE_OMIT_CAST
  81657. /* Opcode: Cast P1 P2 * * *
  81658. ** Synopsis: affinity(r[P1])
  81659. **
  81660. ** Force the value in register P1 to be the type defined by P2.
  81661. **
  81662. ** <ul>
  81663. ** <li> P2=='A' &rarr; BLOB
  81664. ** <li> P2=='B' &rarr; TEXT
  81665. ** <li> P2=='C' &rarr; NUMERIC
  81666. ** <li> P2=='D' &rarr; INTEGER
  81667. ** <li> P2=='E' &rarr; REAL
  81668. ** </ul>
  81669. **
  81670. ** A NULL value is not changed by this routine. It remains NULL.
  81671. */
  81672. case OP_Cast: { /* in1 */
  81673. assert( pOp->p2>=SQLITE_AFF_BLOB && pOp->p2<=SQLITE_AFF_REAL );
  81674. testcase( pOp->p2==SQLITE_AFF_TEXT );
  81675. testcase( pOp->p2==SQLITE_AFF_BLOB );
  81676. testcase( pOp->p2==SQLITE_AFF_NUMERIC );
  81677. testcase( pOp->p2==SQLITE_AFF_INTEGER );
  81678. testcase( pOp->p2==SQLITE_AFF_REAL );
  81679. pIn1 = &aMem[pOp->p1];
  81680. memAboutToChange(p, pIn1);
  81681. rc = ExpandBlob(pIn1);
  81682. if( rc ) goto abort_due_to_error;
  81683. rc = sqlite3VdbeMemCast(pIn1, pOp->p2, encoding);
  81684. if( rc ) goto abort_due_to_error;
  81685. UPDATE_MAX_BLOBSIZE(pIn1);
  81686. REGISTER_TRACE(pOp->p1, pIn1);
  81687. break;
  81688. }
  81689. #endif /* SQLITE_OMIT_CAST */
  81690. /* Opcode: Eq P1 P2 P3 P4 P5
  81691. ** Synopsis: IF r[P3]==r[P1]
  81692. **
  81693. ** Compare the values in register P1 and P3. If reg(P3)==reg(P1) then
  81694. ** jump to address P2. Or if the SQLITE_STOREP2 flag is set in P5, then
  81695. ** store the result of comparison in register P2.
  81696. **
  81697. ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
  81698. ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
  81699. ** to coerce both inputs according to this affinity before the
  81700. ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
  81701. ** affinity is used. Note that the affinity conversions are stored
  81702. ** back into the input registers P1 and P3. So this opcode can cause
  81703. ** persistent changes to registers P1 and P3.
  81704. **
  81705. ** Once any conversions have taken place, and neither value is NULL,
  81706. ** the values are compared. If both values are blobs then memcmp() is
  81707. ** used to determine the results of the comparison. If both values
  81708. ** are text, then the appropriate collating function specified in
  81709. ** P4 is used to do the comparison. If P4 is not specified then
  81710. ** memcmp() is used to compare text string. If both values are
  81711. ** numeric, then a numeric comparison is used. If the two values
  81712. ** are of different types, then numbers are considered less than
  81713. ** strings and strings are considered less than blobs.
  81714. **
  81715. ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
  81716. ** true or false and is never NULL. If both operands are NULL then the result
  81717. ** of comparison is true. If either operand is NULL then the result is false.
  81718. ** If neither operand is NULL the result is the same as it would be if
  81719. ** the SQLITE_NULLEQ flag were omitted from P5.
  81720. **
  81721. ** If both SQLITE_STOREP2 and SQLITE_KEEPNULL flags are set then the
  81722. ** content of r[P2] is only changed if the new value is NULL or 0 (false).
  81723. ** In other words, a prior r[P2] value will not be overwritten by 1 (true).
  81724. */
  81725. /* Opcode: Ne P1 P2 P3 P4 P5
  81726. ** Synopsis: IF r[P3]!=r[P1]
  81727. **
  81728. ** This works just like the Eq opcode except that the jump is taken if
  81729. ** the operands in registers P1 and P3 are not equal. See the Eq opcode for
  81730. ** additional information.
  81731. **
  81732. ** If both SQLITE_STOREP2 and SQLITE_KEEPNULL flags are set then the
  81733. ** content of r[P2] is only changed if the new value is NULL or 1 (true).
  81734. ** In other words, a prior r[P2] value will not be overwritten by 0 (false).
  81735. */
  81736. /* Opcode: Lt P1 P2 P3 P4 P5
  81737. ** Synopsis: IF r[P3]<r[P1]
  81738. **
  81739. ** Compare the values in register P1 and P3. If reg(P3)<reg(P1) then
  81740. ** jump to address P2. Or if the SQLITE_STOREP2 flag is set in P5 store
  81741. ** the result of comparison (0 or 1 or NULL) into register P2.
  81742. **
  81743. ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
  81744. ** reg(P3) is NULL then the take the jump. If the SQLITE_JUMPIFNULL
  81745. ** bit is clear then fall through if either operand is NULL.
  81746. **
  81747. ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
  81748. ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
  81749. ** to coerce both inputs according to this affinity before the
  81750. ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
  81751. ** affinity is used. Note that the affinity conversions are stored
  81752. ** back into the input registers P1 and P3. So this opcode can cause
  81753. ** persistent changes to registers P1 and P3.
  81754. **
  81755. ** Once any conversions have taken place, and neither value is NULL,
  81756. ** the values are compared. If both values are blobs then memcmp() is
  81757. ** used to determine the results of the comparison. If both values
  81758. ** are text, then the appropriate collating function specified in
  81759. ** P4 is used to do the comparison. If P4 is not specified then
  81760. ** memcmp() is used to compare text string. If both values are
  81761. ** numeric, then a numeric comparison is used. If the two values
  81762. ** are of different types, then numbers are considered less than
  81763. ** strings and strings are considered less than blobs.
  81764. */
  81765. /* Opcode: Le P1 P2 P3 P4 P5
  81766. ** Synopsis: IF r[P3]<=r[P1]
  81767. **
  81768. ** This works just like the Lt opcode except that the jump is taken if
  81769. ** the content of register P3 is less than or equal to the content of
  81770. ** register P1. See the Lt opcode for additional information.
  81771. */
  81772. /* Opcode: Gt P1 P2 P3 P4 P5
  81773. ** Synopsis: IF r[P3]>r[P1]
  81774. **
  81775. ** This works just like the Lt opcode except that the jump is taken if
  81776. ** the content of register P3 is greater than the content of
  81777. ** register P1. See the Lt opcode for additional information.
  81778. */
  81779. /* Opcode: Ge P1 P2 P3 P4 P5
  81780. ** Synopsis: IF r[P3]>=r[P1]
  81781. **
  81782. ** This works just like the Lt opcode except that the jump is taken if
  81783. ** the content of register P3 is greater than or equal to the content of
  81784. ** register P1. See the Lt opcode for additional information.
  81785. */
  81786. case OP_Eq: /* same as TK_EQ, jump, in1, in3 */
  81787. case OP_Ne: /* same as TK_NE, jump, in1, in3 */
  81788. case OP_Lt: /* same as TK_LT, jump, in1, in3 */
  81789. case OP_Le: /* same as TK_LE, jump, in1, in3 */
  81790. case OP_Gt: /* same as TK_GT, jump, in1, in3 */
  81791. case OP_Ge: { /* same as TK_GE, jump, in1, in3 */
  81792. int res, res2; /* Result of the comparison of pIn1 against pIn3 */
  81793. char affinity; /* Affinity to use for comparison */
  81794. u16 flags1; /* Copy of initial value of pIn1->flags */
  81795. u16 flags3; /* Copy of initial value of pIn3->flags */
  81796. pIn1 = &aMem[pOp->p1];
  81797. pIn3 = &aMem[pOp->p3];
  81798. flags1 = pIn1->flags;
  81799. flags3 = pIn3->flags;
  81800. if( (flags1 | flags3)&MEM_Null ){
  81801. /* One or both operands are NULL */
  81802. if( pOp->p5 & SQLITE_NULLEQ ){
  81803. /* If SQLITE_NULLEQ is set (which will only happen if the operator is
  81804. ** OP_Eq or OP_Ne) then take the jump or not depending on whether
  81805. ** or not both operands are null.
  81806. */
  81807. assert( (flags1 & MEM_Cleared)==0 );
  81808. assert( (pOp->p5 & SQLITE_JUMPIFNULL)==0 || CORRUPT_DB );
  81809. testcase( (pOp->p5 & SQLITE_JUMPIFNULL)!=0 );
  81810. if( (flags1&flags3&MEM_Null)!=0
  81811. && (flags3&MEM_Cleared)==0
  81812. ){
  81813. res = 0; /* Operands are equal */
  81814. }else{
  81815. res = ((flags3 & MEM_Null) ? -1 : +1); /* Operands are not equal */
  81816. }
  81817. }else{
  81818. /* SQLITE_NULLEQ is clear and at least one operand is NULL,
  81819. ** then the result is always NULL.
  81820. ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
  81821. */
  81822. if( pOp->p5 & SQLITE_STOREP2 ){
  81823. pOut = &aMem[pOp->p2];
  81824. iCompare = 1; /* Operands are not equal */
  81825. memAboutToChange(p, pOut);
  81826. MemSetTypeFlag(pOut, MEM_Null);
  81827. REGISTER_TRACE(pOp->p2, pOut);
  81828. }else{
  81829. VdbeBranchTaken(2,3);
  81830. if( pOp->p5 & SQLITE_JUMPIFNULL ){
  81831. goto jump_to_p2;
  81832. }
  81833. }
  81834. break;
  81835. }
  81836. }else{
  81837. /* Neither operand is NULL. Do a comparison. */
  81838. affinity = pOp->p5 & SQLITE_AFF_MASK;
  81839. if( affinity>=SQLITE_AFF_NUMERIC ){
  81840. if( (flags1 | flags3)&MEM_Str ){
  81841. if( (flags1 & (MEM_Int|MEM_IntReal|MEM_Real|MEM_Str))==MEM_Str ){
  81842. applyNumericAffinity(pIn1,0);
  81843. assert( flags3==pIn3->flags );
  81844. flags3 = pIn3->flags;
  81845. }
  81846. if( (flags3 & (MEM_Int|MEM_IntReal|MEM_Real|MEM_Str))==MEM_Str ){
  81847. applyNumericAffinity(pIn3,0);
  81848. }
  81849. }
  81850. /* Handle the common case of integer comparison here, as an
  81851. ** optimization, to avoid a call to sqlite3MemCompare() */
  81852. if( (pIn1->flags & pIn3->flags & MEM_Int)!=0 ){
  81853. if( pIn3->u.i > pIn1->u.i ){ res = +1; goto compare_op; }
  81854. if( pIn3->u.i < pIn1->u.i ){ res = -1; goto compare_op; }
  81855. res = 0;
  81856. goto compare_op;
  81857. }
  81858. }else if( affinity==SQLITE_AFF_TEXT ){
  81859. if( (flags1 & MEM_Str)==0 && (flags1&(MEM_Int|MEM_Real|MEM_IntReal))!=0 ){
  81860. testcase( pIn1->flags & MEM_Int );
  81861. testcase( pIn1->flags & MEM_Real );
  81862. testcase( pIn1->flags & MEM_IntReal );
  81863. sqlite3VdbeMemStringify(pIn1, encoding, 1);
  81864. testcase( (flags1&MEM_Dyn) != (pIn1->flags&MEM_Dyn) );
  81865. flags1 = (pIn1->flags & ~MEM_TypeMask) | (flags1 & MEM_TypeMask);
  81866. if( NEVER(pIn1==pIn3) ) flags3 = flags1 | MEM_Str;
  81867. }
  81868. if( (flags3 & MEM_Str)==0 && (flags3&(MEM_Int|MEM_Real|MEM_IntReal))!=0 ){
  81869. testcase( pIn3->flags & MEM_Int );
  81870. testcase( pIn3->flags & MEM_Real );
  81871. testcase( pIn3->flags & MEM_IntReal );
  81872. sqlite3VdbeMemStringify(pIn3, encoding, 1);
  81873. testcase( (flags3&MEM_Dyn) != (pIn3->flags&MEM_Dyn) );
  81874. flags3 = (pIn3->flags & ~MEM_TypeMask) | (flags3 & MEM_TypeMask);
  81875. }
  81876. }
  81877. assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
  81878. res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
  81879. }
  81880. compare_op:
  81881. /* At this point, res is negative, zero, or positive if reg[P1] is
  81882. ** less than, equal to, or greater than reg[P3], respectively. Compute
  81883. ** the answer to this operator in res2, depending on what the comparison
  81884. ** operator actually is. The next block of code depends on the fact
  81885. ** that the 6 comparison operators are consecutive integers in this
  81886. ** order: NE, EQ, GT, LE, LT, GE */
  81887. assert( OP_Eq==OP_Ne+1 ); assert( OP_Gt==OP_Ne+2 ); assert( OP_Le==OP_Ne+3 );
  81888. assert( OP_Lt==OP_Ne+4 ); assert( OP_Ge==OP_Ne+5 );
  81889. if( res<0 ){ /* ne, eq, gt, le, lt, ge */
  81890. static const unsigned char aLTb[] = { 1, 0, 0, 1, 1, 0 };
  81891. res2 = aLTb[pOp->opcode - OP_Ne];
  81892. }else if( res==0 ){
  81893. static const unsigned char aEQb[] = { 0, 1, 0, 1, 0, 1 };
  81894. res2 = aEQb[pOp->opcode - OP_Ne];
  81895. }else{
  81896. static const unsigned char aGTb[] = { 1, 0, 1, 0, 0, 1 };
  81897. res2 = aGTb[pOp->opcode - OP_Ne];
  81898. }
  81899. /* Undo any changes made by applyAffinity() to the input registers. */
  81900. assert( (pIn3->flags & MEM_Dyn) == (flags3 & MEM_Dyn) );
  81901. pIn3->flags = flags3;
  81902. assert( (pIn1->flags & MEM_Dyn) == (flags1 & MEM_Dyn) );
  81903. pIn1->flags = flags1;
  81904. if( pOp->p5 & SQLITE_STOREP2 ){
  81905. pOut = &aMem[pOp->p2];
  81906. iCompare = res;
  81907. if( (pOp->p5 & SQLITE_KEEPNULL)!=0 ){
  81908. /* The KEEPNULL flag prevents OP_Eq from overwriting a NULL with 1
  81909. ** and prevents OP_Ne from overwriting NULL with 0. This flag
  81910. ** is only used in contexts where either:
  81911. ** (1) op==OP_Eq && (r[P2]==NULL || r[P2]==0)
  81912. ** (2) op==OP_Ne && (r[P2]==NULL || r[P2]==1)
  81913. ** Therefore it is not necessary to check the content of r[P2] for
  81914. ** NULL. */
  81915. assert( pOp->opcode==OP_Ne || pOp->opcode==OP_Eq );
  81916. assert( res2==0 || res2==1 );
  81917. testcase( res2==0 && pOp->opcode==OP_Eq );
  81918. testcase( res2==1 && pOp->opcode==OP_Eq );
  81919. testcase( res2==0 && pOp->opcode==OP_Ne );
  81920. testcase( res2==1 && pOp->opcode==OP_Ne );
  81921. if( (pOp->opcode==OP_Eq)==res2 ) break;
  81922. }
  81923. memAboutToChange(p, pOut);
  81924. MemSetTypeFlag(pOut, MEM_Int);
  81925. pOut->u.i = res2;
  81926. REGISTER_TRACE(pOp->p2, pOut);
  81927. }else{
  81928. VdbeBranchTaken(res2!=0, (pOp->p5 & SQLITE_NULLEQ)?2:3);
  81929. if( res2 ){
  81930. goto jump_to_p2;
  81931. }
  81932. }
  81933. break;
  81934. }
  81935. /* Opcode: ElseNotEq * P2 * * *
  81936. **
  81937. ** This opcode must follow an OP_Lt or OP_Gt comparison operator. There
  81938. ** can be zero or more OP_ReleaseReg opcodes intervening, but no other
  81939. ** opcodes are allowed to occur between this instruction and the previous
  81940. ** OP_Lt or OP_Gt. Furthermore, the prior OP_Lt or OP_Gt must have the
  81941. ** SQLITE_STOREP2 bit set in the P5 field.
  81942. **
  81943. ** If result of an OP_Eq comparison on the same two operands as the
  81944. ** prior OP_Lt or OP_Gt would have been NULL or false (0), then then
  81945. ** jump to P2. If the result of an OP_Eq comparison on the two previous
  81946. ** operands would have been true (1), then fall through.
  81947. */
  81948. case OP_ElseNotEq: { /* same as TK_ESCAPE, jump */
  81949. #ifdef SQLITE_DEBUG
  81950. /* Verify the preconditions of this opcode - that it follows an OP_Lt or
  81951. ** OP_Gt with the SQLITE_STOREP2 flag set, with zero or more intervening
  81952. ** OP_ReleaseReg opcodes */
  81953. int iAddr;
  81954. for(iAddr = (int)(pOp - aOp) - 1; ALWAYS(iAddr>=0); iAddr--){
  81955. if( aOp[iAddr].opcode==OP_ReleaseReg ) continue;
  81956. assert( aOp[iAddr].opcode==OP_Lt || aOp[iAddr].opcode==OP_Gt );
  81957. assert( aOp[iAddr].p5 & SQLITE_STOREP2 );
  81958. break;
  81959. }
  81960. #endif /* SQLITE_DEBUG */
  81961. VdbeBranchTaken(iCompare!=0, 2);
  81962. if( iCompare!=0 ) goto jump_to_p2;
  81963. break;
  81964. }
  81965. /* Opcode: Permutation * * * P4 *
  81966. **
  81967. ** Set the permutation used by the OP_Compare operator in the next
  81968. ** instruction. The permutation is stored in the P4 operand.
  81969. **
  81970. ** The permutation is only valid until the next OP_Compare that has
  81971. ** the OPFLAG_PERMUTE bit set in P5. Typically the OP_Permutation should
  81972. ** occur immediately prior to the OP_Compare.
  81973. **
  81974. ** The first integer in the P4 integer array is the length of the array
  81975. ** and does not become part of the permutation.
  81976. */
  81977. case OP_Permutation: {
  81978. assert( pOp->p4type==P4_INTARRAY );
  81979. assert( pOp->p4.ai );
  81980. assert( pOp[1].opcode==OP_Compare );
  81981. assert( pOp[1].p5 & OPFLAG_PERMUTE );
  81982. break;
  81983. }
  81984. /* Opcode: Compare P1 P2 P3 P4 P5
  81985. ** Synopsis: r[P1@P3] <-> r[P2@P3]
  81986. **
  81987. ** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this
  81988. ** vector "A") and in reg(P2)..reg(P2+P3-1) ("B"). Save the result of
  81989. ** the comparison for use by the next OP_Jump instruct.
  81990. **
  81991. ** If P5 has the OPFLAG_PERMUTE bit set, then the order of comparison is
  81992. ** determined by the most recent OP_Permutation operator. If the
  81993. ** OPFLAG_PERMUTE bit is clear, then register are compared in sequential
  81994. ** order.
  81995. **
  81996. ** P4 is a KeyInfo structure that defines collating sequences and sort
  81997. ** orders for the comparison. The permutation applies to registers
  81998. ** only. The KeyInfo elements are used sequentially.
  81999. **
  82000. ** The comparison is a sort comparison, so NULLs compare equal,
  82001. ** NULLs are less than numbers, numbers are less than strings,
  82002. ** and strings are less than blobs.
  82003. */
  82004. case OP_Compare: {
  82005. int n;
  82006. int i;
  82007. int p1;
  82008. int p2;
  82009. const KeyInfo *pKeyInfo;
  82010. int idx;
  82011. CollSeq *pColl; /* Collating sequence to use on this term */
  82012. int bRev; /* True for DESCENDING sort order */
  82013. int *aPermute; /* The permutation */
  82014. if( (pOp->p5 & OPFLAG_PERMUTE)==0 ){
  82015. aPermute = 0;
  82016. }else{
  82017. assert( pOp>aOp );
  82018. assert( pOp[-1].opcode==OP_Permutation );
  82019. assert( pOp[-1].p4type==P4_INTARRAY );
  82020. aPermute = pOp[-1].p4.ai + 1;
  82021. assert( aPermute!=0 );
  82022. }
  82023. n = pOp->p3;
  82024. pKeyInfo = pOp->p4.pKeyInfo;
  82025. assert( n>0 );
  82026. assert( pKeyInfo!=0 );
  82027. p1 = pOp->p1;
  82028. p2 = pOp->p2;
  82029. #ifdef SQLITE_DEBUG
  82030. if( aPermute ){
  82031. int k, mx = 0;
  82032. for(k=0; k<n; k++) if( aPermute[k]>mx ) mx = aPermute[k];
  82033. assert( p1>0 && p1+mx<=(p->nMem+1 - p->nCursor)+1 );
  82034. assert( p2>0 && p2+mx<=(p->nMem+1 - p->nCursor)+1 );
  82035. }else{
  82036. assert( p1>0 && p1+n<=(p->nMem+1 - p->nCursor)+1 );
  82037. assert( p2>0 && p2+n<=(p->nMem+1 - p->nCursor)+1 );
  82038. }
  82039. #endif /* SQLITE_DEBUG */
  82040. for(i=0; i<n; i++){
  82041. idx = aPermute ? aPermute[i] : i;
  82042. assert( memIsValid(&aMem[p1+idx]) );
  82043. assert( memIsValid(&aMem[p2+idx]) );
  82044. REGISTER_TRACE(p1+idx, &aMem[p1+idx]);
  82045. REGISTER_TRACE(p2+idx, &aMem[p2+idx]);
  82046. assert( i<pKeyInfo->nKeyField );
  82047. pColl = pKeyInfo->aColl[i];
  82048. bRev = (pKeyInfo->aSortFlags[i] & KEYINFO_ORDER_DESC);
  82049. iCompare = sqlite3MemCompare(&aMem[p1+idx], &aMem[p2+idx], pColl);
  82050. if( iCompare ){
  82051. if( (pKeyInfo->aSortFlags[i] & KEYINFO_ORDER_BIGNULL)
  82052. && ((aMem[p1+idx].flags & MEM_Null) || (aMem[p2+idx].flags & MEM_Null))
  82053. ){
  82054. iCompare = -iCompare;
  82055. }
  82056. if( bRev ) iCompare = -iCompare;
  82057. break;
  82058. }
  82059. }
  82060. break;
  82061. }
  82062. /* Opcode: Jump P1 P2 P3 * *
  82063. **
  82064. ** Jump to the instruction at address P1, P2, or P3 depending on whether
  82065. ** in the most recent OP_Compare instruction the P1 vector was less than
  82066. ** equal to, or greater than the P2 vector, respectively.
  82067. */
  82068. case OP_Jump: { /* jump */
  82069. if( iCompare<0 ){
  82070. VdbeBranchTaken(0,4); pOp = &aOp[pOp->p1 - 1];
  82071. }else if( iCompare==0 ){
  82072. VdbeBranchTaken(1,4); pOp = &aOp[pOp->p2 - 1];
  82073. }else{
  82074. VdbeBranchTaken(2,4); pOp = &aOp[pOp->p3 - 1];
  82075. }
  82076. break;
  82077. }
  82078. /* Opcode: And P1 P2 P3 * *
  82079. ** Synopsis: r[P3]=(r[P1] && r[P2])
  82080. **
  82081. ** Take the logical AND of the values in registers P1 and P2 and
  82082. ** write the result into register P3.
  82083. **
  82084. ** If either P1 or P2 is 0 (false) then the result is 0 even if
  82085. ** the other input is NULL. A NULL and true or two NULLs give
  82086. ** a NULL output.
  82087. */
  82088. /* Opcode: Or P1 P2 P3 * *
  82089. ** Synopsis: r[P3]=(r[P1] || r[P2])
  82090. **
  82091. ** Take the logical OR of the values in register P1 and P2 and
  82092. ** store the answer in register P3.
  82093. **
  82094. ** If either P1 or P2 is nonzero (true) then the result is 1 (true)
  82095. ** even if the other input is NULL. A NULL and false or two NULLs
  82096. ** give a NULL output.
  82097. */
  82098. case OP_And: /* same as TK_AND, in1, in2, out3 */
  82099. case OP_Or: { /* same as TK_OR, in1, in2, out3 */
  82100. int v1; /* Left operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
  82101. int v2; /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
  82102. v1 = sqlite3VdbeBooleanValue(&aMem[pOp->p1], 2);
  82103. v2 = sqlite3VdbeBooleanValue(&aMem[pOp->p2], 2);
  82104. if( pOp->opcode==OP_And ){
  82105. static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
  82106. v1 = and_logic[v1*3+v2];
  82107. }else{
  82108. static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
  82109. v1 = or_logic[v1*3+v2];
  82110. }
  82111. pOut = &aMem[pOp->p3];
  82112. if( v1==2 ){
  82113. MemSetTypeFlag(pOut, MEM_Null);
  82114. }else{
  82115. pOut->u.i = v1;
  82116. MemSetTypeFlag(pOut, MEM_Int);
  82117. }
  82118. break;
  82119. }
  82120. /* Opcode: IsTrue P1 P2 P3 P4 *
  82121. ** Synopsis: r[P2] = coalesce(r[P1]==TRUE,P3) ^ P4
  82122. **
  82123. ** This opcode implements the IS TRUE, IS FALSE, IS NOT TRUE, and
  82124. ** IS NOT FALSE operators.
  82125. **
  82126. ** Interpret the value in register P1 as a boolean value. Store that
  82127. ** boolean (a 0 or 1) in register P2. Or if the value in register P1 is
  82128. ** NULL, then the P3 is stored in register P2. Invert the answer if P4
  82129. ** is 1.
  82130. **
  82131. ** The logic is summarized like this:
  82132. **
  82133. ** <ul>
  82134. ** <li> If P3==0 and P4==0 then r[P2] := r[P1] IS TRUE
  82135. ** <li> If P3==1 and P4==1 then r[P2] := r[P1] IS FALSE
  82136. ** <li> If P3==0 and P4==1 then r[P2] := r[P1] IS NOT TRUE
  82137. ** <li> If P3==1 and P4==0 then r[P2] := r[P1] IS NOT FALSE
  82138. ** </ul>
  82139. */
  82140. case OP_IsTrue: { /* in1, out2 */
  82141. assert( pOp->p4type==P4_INT32 );
  82142. assert( pOp->p4.i==0 || pOp->p4.i==1 );
  82143. assert( pOp->p3==0 || pOp->p3==1 );
  82144. sqlite3VdbeMemSetInt64(&aMem[pOp->p2],
  82145. sqlite3VdbeBooleanValue(&aMem[pOp->p1], pOp->p3) ^ pOp->p4.i);
  82146. break;
  82147. }
  82148. /* Opcode: Not P1 P2 * * *
  82149. ** Synopsis: r[P2]= !r[P1]
  82150. **
  82151. ** Interpret the value in register P1 as a boolean value. Store the
  82152. ** boolean complement in register P2. If the value in register P1 is
  82153. ** NULL, then a NULL is stored in P2.
  82154. */
  82155. case OP_Not: { /* same as TK_NOT, in1, out2 */
  82156. pIn1 = &aMem[pOp->p1];
  82157. pOut = &aMem[pOp->p2];
  82158. if( (pIn1->flags & MEM_Null)==0 ){
  82159. sqlite3VdbeMemSetInt64(pOut, !sqlite3VdbeBooleanValue(pIn1,0));
  82160. }else{
  82161. sqlite3VdbeMemSetNull(pOut);
  82162. }
  82163. break;
  82164. }
  82165. /* Opcode: BitNot P1 P2 * * *
  82166. ** Synopsis: r[P2]= ~r[P1]
  82167. **
  82168. ** Interpret the content of register P1 as an integer. Store the
  82169. ** ones-complement of the P1 value into register P2. If P1 holds
  82170. ** a NULL then store a NULL in P2.
  82171. */
  82172. case OP_BitNot: { /* same as TK_BITNOT, in1, out2 */
  82173. pIn1 = &aMem[pOp->p1];
  82174. pOut = &aMem[pOp->p2];
  82175. sqlite3VdbeMemSetNull(pOut);
  82176. if( (pIn1->flags & MEM_Null)==0 ){
  82177. pOut->flags = MEM_Int;
  82178. pOut->u.i = ~sqlite3VdbeIntValue(pIn1);
  82179. }
  82180. break;
  82181. }
  82182. /* Opcode: Once P1 P2 * * *
  82183. **
  82184. ** Fall through to the next instruction the first time this opcode is
  82185. ** encountered on each invocation of the byte-code program. Jump to P2
  82186. ** on the second and all subsequent encounters during the same invocation.
  82187. **
  82188. ** Top-level programs determine first invocation by comparing the P1
  82189. ** operand against the P1 operand on the OP_Init opcode at the beginning
  82190. ** of the program. If the P1 values differ, then fall through and make
  82191. ** the P1 of this opcode equal to the P1 of OP_Init. If P1 values are
  82192. ** the same then take the jump.
  82193. **
  82194. ** For subprograms, there is a bitmask in the VdbeFrame that determines
  82195. ** whether or not the jump should be taken. The bitmask is necessary
  82196. ** because the self-altering code trick does not work for recursive
  82197. ** triggers.
  82198. */
  82199. case OP_Once: { /* jump */
  82200. u32 iAddr; /* Address of this instruction */
  82201. assert( p->aOp[0].opcode==OP_Init );
  82202. if( p->pFrame ){
  82203. iAddr = (int)(pOp - p->aOp);
  82204. if( (p->pFrame->aOnce[iAddr/8] & (1<<(iAddr & 7)))!=0 ){
  82205. VdbeBranchTaken(1, 2);
  82206. goto jump_to_p2;
  82207. }
  82208. p->pFrame->aOnce[iAddr/8] |= 1<<(iAddr & 7);
  82209. }else{
  82210. if( p->aOp[0].p1==pOp->p1 ){
  82211. VdbeBranchTaken(1, 2);
  82212. goto jump_to_p2;
  82213. }
  82214. }
  82215. VdbeBranchTaken(0, 2);
  82216. pOp->p1 = p->aOp[0].p1;
  82217. break;
  82218. }
  82219. /* Opcode: If P1 P2 P3 * *
  82220. **
  82221. ** Jump to P2 if the value in register P1 is true. The value
  82222. ** is considered true if it is numeric and non-zero. If the value
  82223. ** in P1 is NULL then take the jump if and only if P3 is non-zero.
  82224. */
  82225. case OP_If: { /* jump, in1 */
  82226. int c;
  82227. c = sqlite3VdbeBooleanValue(&aMem[pOp->p1], pOp->p3);
  82228. VdbeBranchTaken(c!=0, 2);
  82229. if( c ) goto jump_to_p2;
  82230. break;
  82231. }
  82232. /* Opcode: IfNot P1 P2 P3 * *
  82233. **
  82234. ** Jump to P2 if the value in register P1 is False. The value
  82235. ** is considered false if it has a numeric value of zero. If the value
  82236. ** in P1 is NULL then take the jump if and only if P3 is non-zero.
  82237. */
  82238. case OP_IfNot: { /* jump, in1 */
  82239. int c;
  82240. c = !sqlite3VdbeBooleanValue(&aMem[pOp->p1], !pOp->p3);
  82241. VdbeBranchTaken(c!=0, 2);
  82242. if( c ) goto jump_to_p2;
  82243. break;
  82244. }
  82245. /* Opcode: IsNull P1 P2 * * *
  82246. ** Synopsis: if r[P1]==NULL goto P2
  82247. **
  82248. ** Jump to P2 if the value in register P1 is NULL.
  82249. */
  82250. case OP_IsNull: { /* same as TK_ISNULL, jump, in1 */
  82251. pIn1 = &aMem[pOp->p1];
  82252. VdbeBranchTaken( (pIn1->flags & MEM_Null)!=0, 2);
  82253. if( (pIn1->flags & MEM_Null)!=0 ){
  82254. goto jump_to_p2;
  82255. }
  82256. break;
  82257. }
  82258. /* Opcode: NotNull P1 P2 * * *
  82259. ** Synopsis: if r[P1]!=NULL goto P2
  82260. **
  82261. ** Jump to P2 if the value in register P1 is not NULL.
  82262. */
  82263. case OP_NotNull: { /* same as TK_NOTNULL, jump, in1 */
  82264. pIn1 = &aMem[pOp->p1];
  82265. VdbeBranchTaken( (pIn1->flags & MEM_Null)==0, 2);
  82266. if( (pIn1->flags & MEM_Null)==0 ){
  82267. goto jump_to_p2;
  82268. }
  82269. break;
  82270. }
  82271. /* Opcode: IfNullRow P1 P2 P3 * *
  82272. ** Synopsis: if P1.nullRow then r[P3]=NULL, goto P2
  82273. **
  82274. ** Check the cursor P1 to see if it is currently pointing at a NULL row.
  82275. ** If it is, then set register P3 to NULL and jump immediately to P2.
  82276. ** If P1 is not on a NULL row, then fall through without making any
  82277. ** changes.
  82278. */
  82279. case OP_IfNullRow: { /* jump */
  82280. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  82281. assert( p->apCsr[pOp->p1]!=0 );
  82282. if( p->apCsr[pOp->p1]->nullRow ){
  82283. sqlite3VdbeMemSetNull(aMem + pOp->p3);
  82284. goto jump_to_p2;
  82285. }
  82286. break;
  82287. }
  82288. #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
  82289. /* Opcode: Offset P1 P2 P3 * *
  82290. ** Synopsis: r[P3] = sqlite_offset(P1)
  82291. **
  82292. ** Store in register r[P3] the byte offset into the database file that is the
  82293. ** start of the payload for the record at which that cursor P1 is currently
  82294. ** pointing.
  82295. **
  82296. ** P2 is the column number for the argument to the sqlite_offset() function.
  82297. ** This opcode does not use P2 itself, but the P2 value is used by the
  82298. ** code generator. The P1, P2, and P3 operands to this opcode are the
  82299. ** same as for OP_Column.
  82300. **
  82301. ** This opcode is only available if SQLite is compiled with the
  82302. ** -DSQLITE_ENABLE_OFFSET_SQL_FUNC option.
  82303. */
  82304. case OP_Offset: { /* out3 */
  82305. VdbeCursor *pC; /* The VDBE cursor */
  82306. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  82307. pC = p->apCsr[pOp->p1];
  82308. pOut = &p->aMem[pOp->p3];
  82309. if( NEVER(pC==0) || pC->eCurType!=CURTYPE_BTREE ){
  82310. sqlite3VdbeMemSetNull(pOut);
  82311. }else{
  82312. sqlite3VdbeMemSetInt64(pOut, sqlite3BtreeOffset(pC->uc.pCursor));
  82313. }
  82314. break;
  82315. }
  82316. #endif /* SQLITE_ENABLE_OFFSET_SQL_FUNC */
  82317. /* Opcode: Column P1 P2 P3 P4 P5
  82318. ** Synopsis: r[P3]=PX
  82319. **
  82320. ** Interpret the data that cursor P1 points to as a structure built using
  82321. ** the MakeRecord instruction. (See the MakeRecord opcode for additional
  82322. ** information about the format of the data.) Extract the P2-th column
  82323. ** from this record. If there are less that (P2+1)
  82324. ** values in the record, extract a NULL.
  82325. **
  82326. ** The value extracted is stored in register P3.
  82327. **
  82328. ** If the record contains fewer than P2 fields, then extract a NULL. Or,
  82329. ** if the P4 argument is a P4_MEM use the value of the P4 argument as
  82330. ** the result.
  82331. **
  82332. ** If the OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG bits are set on P5 then
  82333. ** the result is guaranteed to only be used as the argument of a length()
  82334. ** or typeof() function, respectively. The loading of large blobs can be
  82335. ** skipped for length() and all content loading can be skipped for typeof().
  82336. */
  82337. case OP_Column: {
  82338. int p2; /* column number to retrieve */
  82339. VdbeCursor *pC; /* The VDBE cursor */
  82340. BtCursor *pCrsr; /* The BTree cursor */
  82341. u32 *aOffset; /* aOffset[i] is offset to start of data for i-th column */
  82342. int len; /* The length of the serialized data for the column */
  82343. int i; /* Loop counter */
  82344. Mem *pDest; /* Where to write the extracted value */
  82345. Mem sMem; /* For storing the record being decoded */
  82346. const u8 *zData; /* Part of the record being decoded */
  82347. const u8 *zHdr; /* Next unparsed byte of the header */
  82348. const u8 *zEndHdr; /* Pointer to first byte after the header */
  82349. u64 offset64; /* 64-bit offset */
  82350. u32 t; /* A type code from the record header */
  82351. Mem *pReg; /* PseudoTable input register */
  82352. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  82353. pC = p->apCsr[pOp->p1];
  82354. assert( pC!=0 );
  82355. p2 = pOp->p2;
  82356. /* If the cursor cache is stale (meaning it is not currently point at
  82357. ** the correct row) then bring it up-to-date by doing the necessary
  82358. ** B-Tree seek. */
  82359. rc = sqlite3VdbeCursorMoveto(&pC, &p2);
  82360. if( rc ) goto abort_due_to_error;
  82361. assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
  82362. pDest = &aMem[pOp->p3];
  82363. memAboutToChange(p, pDest);
  82364. assert( pC!=0 );
  82365. assert( p2<pC->nField );
  82366. aOffset = pC->aOffset;
  82367. assert( pC->eCurType!=CURTYPE_VTAB );
  82368. assert( pC->eCurType!=CURTYPE_PSEUDO || pC->nullRow );
  82369. assert( pC->eCurType!=CURTYPE_SORTER );
  82370. if( pC->cacheStatus!=p->cacheCtr ){ /*OPTIMIZATION-IF-FALSE*/
  82371. if( pC->nullRow ){
  82372. if( pC->eCurType==CURTYPE_PSEUDO ){
  82373. /* For the special case of as pseudo-cursor, the seekResult field
  82374. ** identifies the register that holds the record */
  82375. assert( pC->seekResult>0 );
  82376. pReg = &aMem[pC->seekResult];
  82377. assert( pReg->flags & MEM_Blob );
  82378. assert( memIsValid(pReg) );
  82379. pC->payloadSize = pC->szRow = pReg->n;
  82380. pC->aRow = (u8*)pReg->z;
  82381. }else{
  82382. sqlite3VdbeMemSetNull(pDest);
  82383. goto op_column_out;
  82384. }
  82385. }else{
  82386. pCrsr = pC->uc.pCursor;
  82387. assert( pC->eCurType==CURTYPE_BTREE );
  82388. assert( pCrsr );
  82389. assert( sqlite3BtreeCursorIsValid(pCrsr) );
  82390. pC->payloadSize = sqlite3BtreePayloadSize(pCrsr);
  82391. pC->aRow = sqlite3BtreePayloadFetch(pCrsr, &pC->szRow);
  82392. assert( pC->szRow<=pC->payloadSize );
  82393. assert( pC->szRow<=65536 ); /* Maximum page size is 64KiB */
  82394. if( pC->payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
  82395. goto too_big;
  82396. }
  82397. }
  82398. pC->cacheStatus = p->cacheCtr;
  82399. pC->iHdrOffset = getVarint32(pC->aRow, aOffset[0]);
  82400. pC->nHdrParsed = 0;
  82401. if( pC->szRow<aOffset[0] ){ /*OPTIMIZATION-IF-FALSE*/
  82402. /* pC->aRow does not have to hold the entire row, but it does at least
  82403. ** need to cover the header of the record. If pC->aRow does not contain
  82404. ** the complete header, then set it to zero, forcing the header to be
  82405. ** dynamically allocated. */
  82406. pC->aRow = 0;
  82407. pC->szRow = 0;
  82408. /* Make sure a corrupt database has not given us an oversize header.
  82409. ** Do this now to avoid an oversize memory allocation.
  82410. **
  82411. ** Type entries can be between 1 and 5 bytes each. But 4 and 5 byte
  82412. ** types use so much data space that there can only be 4096 and 32 of
  82413. ** them, respectively. So the maximum header length results from a
  82414. ** 3-byte type for each of the maximum of 32768 columns plus three
  82415. ** extra bytes for the header length itself. 32768*3 + 3 = 98307.
  82416. */
  82417. if( aOffset[0] > 98307 || aOffset[0] > pC->payloadSize ){
  82418. goto op_column_corrupt;
  82419. }
  82420. }else{
  82421. /* This is an optimization. By skipping over the first few tests
  82422. ** (ex: pC->nHdrParsed<=p2) in the next section, we achieve a
  82423. ** measurable performance gain.
  82424. **
  82425. ** This branch is taken even if aOffset[0]==0. Such a record is never
  82426. ** generated by SQLite, and could be considered corruption, but we
  82427. ** accept it for historical reasons. When aOffset[0]==0, the code this
  82428. ** branch jumps to reads past the end of the record, but never more
  82429. ** than a few bytes. Even if the record occurs at the end of the page
  82430. ** content area, the "page header" comes after the page content and so
  82431. ** this overread is harmless. Similar overreads can occur for a corrupt
  82432. ** database file.
  82433. */
  82434. zData = pC->aRow;
  82435. assert( pC->nHdrParsed<=p2 ); /* Conditional skipped */
  82436. testcase( aOffset[0]==0 );
  82437. goto op_column_read_header;
  82438. }
  82439. }
  82440. /* Make sure at least the first p2+1 entries of the header have been
  82441. ** parsed and valid information is in aOffset[] and pC->aType[].
  82442. */
  82443. if( pC->nHdrParsed<=p2 ){
  82444. /* If there is more header available for parsing in the record, try
  82445. ** to extract additional fields up through the p2+1-th field
  82446. */
  82447. if( pC->iHdrOffset<aOffset[0] ){
  82448. /* Make sure zData points to enough of the record to cover the header. */
  82449. if( pC->aRow==0 ){
  82450. memset(&sMem, 0, sizeof(sMem));
  82451. rc = sqlite3VdbeMemFromBtreeZeroOffset(pC->uc.pCursor,aOffset[0],&sMem);
  82452. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  82453. zData = (u8*)sMem.z;
  82454. }else{
  82455. zData = pC->aRow;
  82456. }
  82457. /* Fill in pC->aType[i] and aOffset[i] values through the p2-th field. */
  82458. op_column_read_header:
  82459. i = pC->nHdrParsed;
  82460. offset64 = aOffset[i];
  82461. zHdr = zData + pC->iHdrOffset;
  82462. zEndHdr = zData + aOffset[0];
  82463. testcase( zHdr>=zEndHdr );
  82464. do{
  82465. if( (pC->aType[i] = t = zHdr[0])<0x80 ){
  82466. zHdr++;
  82467. offset64 += sqlite3VdbeOneByteSerialTypeLen(t);
  82468. }else{
  82469. zHdr += sqlite3GetVarint32(zHdr, &t);
  82470. pC->aType[i] = t;
  82471. offset64 += sqlite3VdbeSerialTypeLen(t);
  82472. }
  82473. aOffset[++i] = (u32)(offset64 & 0xffffffff);
  82474. }while( i<=p2 && zHdr<zEndHdr );
  82475. /* The record is corrupt if any of the following are true:
  82476. ** (1) the bytes of the header extend past the declared header size
  82477. ** (2) the entire header was used but not all data was used
  82478. ** (3) the end of the data extends beyond the end of the record.
  82479. */
  82480. if( (zHdr>=zEndHdr && (zHdr>zEndHdr || offset64!=pC->payloadSize))
  82481. || (offset64 > pC->payloadSize)
  82482. ){
  82483. if( aOffset[0]==0 ){
  82484. i = 0;
  82485. zHdr = zEndHdr;
  82486. }else{
  82487. if( pC->aRow==0 ) sqlite3VdbeMemRelease(&sMem);
  82488. goto op_column_corrupt;
  82489. }
  82490. }
  82491. pC->nHdrParsed = i;
  82492. pC->iHdrOffset = (u32)(zHdr - zData);
  82493. if( pC->aRow==0 ) sqlite3VdbeMemRelease(&sMem);
  82494. }else{
  82495. t = 0;
  82496. }
  82497. /* If after trying to extract new entries from the header, nHdrParsed is
  82498. ** still not up to p2, that means that the record has fewer than p2
  82499. ** columns. So the result will be either the default value or a NULL.
  82500. */
  82501. if( pC->nHdrParsed<=p2 ){
  82502. if( pOp->p4type==P4_MEM ){
  82503. sqlite3VdbeMemShallowCopy(pDest, pOp->p4.pMem, MEM_Static);
  82504. }else{
  82505. sqlite3VdbeMemSetNull(pDest);
  82506. }
  82507. goto op_column_out;
  82508. }
  82509. }else{
  82510. t = pC->aType[p2];
  82511. }
  82512. /* Extract the content for the p2+1-th column. Control can only
  82513. ** reach this point if aOffset[p2], aOffset[p2+1], and pC->aType[p2] are
  82514. ** all valid.
  82515. */
  82516. assert( p2<pC->nHdrParsed );
  82517. assert( rc==SQLITE_OK );
  82518. assert( sqlite3VdbeCheckMemInvariants(pDest) );
  82519. if( VdbeMemDynamic(pDest) ){
  82520. sqlite3VdbeMemSetNull(pDest);
  82521. }
  82522. assert( t==pC->aType[p2] );
  82523. if( pC->szRow>=aOffset[p2+1] ){
  82524. /* This is the common case where the desired content fits on the original
  82525. ** page - where the content is not on an overflow page */
  82526. zData = pC->aRow + aOffset[p2];
  82527. if( t<12 ){
  82528. sqlite3VdbeSerialGet(zData, t, pDest);
  82529. }else{
  82530. /* If the column value is a string, we need a persistent value, not
  82531. ** a MEM_Ephem value. This branch is a fast short-cut that is equivalent
  82532. ** to calling sqlite3VdbeSerialGet() and sqlite3VdbeDeephemeralize().
  82533. */
  82534. static const u16 aFlag[] = { MEM_Blob, MEM_Str|MEM_Term };
  82535. pDest->n = len = (t-12)/2;
  82536. pDest->enc = encoding;
  82537. if( pDest->szMalloc < len+2 ){
  82538. pDest->flags = MEM_Null;
  82539. if( sqlite3VdbeMemGrow(pDest, len+2, 0) ) goto no_mem;
  82540. }else{
  82541. pDest->z = pDest->zMalloc;
  82542. }
  82543. memcpy(pDest->z, zData, len);
  82544. pDest->z[len] = 0;
  82545. pDest->z[len+1] = 0;
  82546. pDest->flags = aFlag[t&1];
  82547. }
  82548. }else{
  82549. pDest->enc = encoding;
  82550. /* This branch happens only when content is on overflow pages */
  82551. if( ((pOp->p5 & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG))!=0
  82552. && ((t>=12 && (t&1)==0) || (pOp->p5 & OPFLAG_TYPEOFARG)!=0))
  82553. || (len = sqlite3VdbeSerialTypeLen(t))==0
  82554. ){
  82555. /* Content is irrelevant for
  82556. ** 1. the typeof() function,
  82557. ** 2. the length(X) function if X is a blob, and
  82558. ** 3. if the content length is zero.
  82559. ** So we might as well use bogus content rather than reading
  82560. ** content from disk.
  82561. **
  82562. ** Although sqlite3VdbeSerialGet() may read at most 8 bytes from the
  82563. ** buffer passed to it, debugging function VdbeMemPrettyPrint() may
  82564. ** read more. Use the global constant sqlite3CtypeMap[] as the array,
  82565. ** as that array is 256 bytes long (plenty for VdbeMemPrettyPrint())
  82566. ** and it begins with a bunch of zeros.
  82567. */
  82568. sqlite3VdbeSerialGet((u8*)sqlite3CtypeMap, t, pDest);
  82569. }else{
  82570. rc = sqlite3VdbeMemFromBtree(pC->uc.pCursor, aOffset[p2], len, pDest);
  82571. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  82572. sqlite3VdbeSerialGet((const u8*)pDest->z, t, pDest);
  82573. pDest->flags &= ~MEM_Ephem;
  82574. }
  82575. }
  82576. op_column_out:
  82577. UPDATE_MAX_BLOBSIZE(pDest);
  82578. REGISTER_TRACE(pOp->p3, pDest);
  82579. break;
  82580. op_column_corrupt:
  82581. if( aOp[0].p3>0 ){
  82582. pOp = &aOp[aOp[0].p3-1];
  82583. break;
  82584. }else{
  82585. rc = SQLITE_CORRUPT_BKPT;
  82586. goto abort_due_to_error;
  82587. }
  82588. }
  82589. /* Opcode: Affinity P1 P2 * P4 *
  82590. ** Synopsis: affinity(r[P1@P2])
  82591. **
  82592. ** Apply affinities to a range of P2 registers starting with P1.
  82593. **
  82594. ** P4 is a string that is P2 characters long. The N-th character of the
  82595. ** string indicates the column affinity that should be used for the N-th
  82596. ** memory cell in the range.
  82597. */
  82598. case OP_Affinity: {
  82599. const char *zAffinity; /* The affinity to be applied */
  82600. zAffinity = pOp->p4.z;
  82601. assert( zAffinity!=0 );
  82602. assert( pOp->p2>0 );
  82603. assert( zAffinity[pOp->p2]==0 );
  82604. pIn1 = &aMem[pOp->p1];
  82605. while( 1 /*exit-by-break*/ ){
  82606. assert( pIn1 <= &p->aMem[(p->nMem+1 - p->nCursor)] );
  82607. assert( zAffinity[0]==SQLITE_AFF_NONE || memIsValid(pIn1) );
  82608. applyAffinity(pIn1, zAffinity[0], encoding);
  82609. if( zAffinity[0]==SQLITE_AFF_REAL && (pIn1->flags & MEM_Int)!=0 ){
  82610. /* When applying REAL affinity, if the result is still an MEM_Int
  82611. ** that will fit in 6 bytes, then change the type to MEM_IntReal
  82612. ** so that we keep the high-resolution integer value but know that
  82613. ** the type really wants to be REAL. */
  82614. testcase( pIn1->u.i==140737488355328LL );
  82615. testcase( pIn1->u.i==140737488355327LL );
  82616. testcase( pIn1->u.i==-140737488355328LL );
  82617. testcase( pIn1->u.i==-140737488355329LL );
  82618. if( pIn1->u.i<=140737488355327LL && pIn1->u.i>=-140737488355328LL ){
  82619. pIn1->flags |= MEM_IntReal;
  82620. pIn1->flags &= ~MEM_Int;
  82621. }else{
  82622. pIn1->u.r = (double)pIn1->u.i;
  82623. pIn1->flags |= MEM_Real;
  82624. pIn1->flags &= ~MEM_Int;
  82625. }
  82626. }
  82627. REGISTER_TRACE((int)(pIn1-aMem), pIn1);
  82628. zAffinity++;
  82629. if( zAffinity[0]==0 ) break;
  82630. pIn1++;
  82631. }
  82632. break;
  82633. }
  82634. /* Opcode: MakeRecord P1 P2 P3 P4 *
  82635. ** Synopsis: r[P3]=mkrec(r[P1@P2])
  82636. **
  82637. ** Convert P2 registers beginning with P1 into the [record format]
  82638. ** use as a data record in a database table or as a key
  82639. ** in an index. The OP_Column opcode can decode the record later.
  82640. **
  82641. ** P4 may be a string that is P2 characters long. The N-th character of the
  82642. ** string indicates the column affinity that should be used for the N-th
  82643. ** field of the index key.
  82644. **
  82645. ** The mapping from character to affinity is given by the SQLITE_AFF_
  82646. ** macros defined in sqliteInt.h.
  82647. **
  82648. ** If P4 is NULL then all index fields have the affinity BLOB.
  82649. */
  82650. case OP_MakeRecord: {
  82651. Mem *pRec; /* The new record */
  82652. u64 nData; /* Number of bytes of data space */
  82653. int nHdr; /* Number of bytes of header space */
  82654. i64 nByte; /* Data space required for this record */
  82655. i64 nZero; /* Number of zero bytes at the end of the record */
  82656. int nVarint; /* Number of bytes in a varint */
  82657. u32 serial_type; /* Type field */
  82658. Mem *pData0; /* First field to be combined into the record */
  82659. Mem *pLast; /* Last field of the record */
  82660. int nField; /* Number of fields in the record */
  82661. char *zAffinity; /* The affinity string for the record */
  82662. int file_format; /* File format to use for encoding */
  82663. u32 len; /* Length of a field */
  82664. u8 *zHdr; /* Where to write next byte of the header */
  82665. u8 *zPayload; /* Where to write next byte of the payload */
  82666. /* Assuming the record contains N fields, the record format looks
  82667. ** like this:
  82668. **
  82669. ** ------------------------------------------------------------------------
  82670. ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
  82671. ** ------------------------------------------------------------------------
  82672. **
  82673. ** Data(0) is taken from register P1. Data(1) comes from register P1+1
  82674. ** and so forth.
  82675. **
  82676. ** Each type field is a varint representing the serial type of the
  82677. ** corresponding data element (see sqlite3VdbeSerialType()). The
  82678. ** hdr-size field is also a varint which is the offset from the beginning
  82679. ** of the record to data0.
  82680. */
  82681. nData = 0; /* Number of bytes of data space */
  82682. nHdr = 0; /* Number of bytes of header space */
  82683. nZero = 0; /* Number of zero bytes at the end of the record */
  82684. nField = pOp->p1;
  82685. zAffinity = pOp->p4.z;
  82686. assert( nField>0 && pOp->p2>0 && pOp->p2+nField<=(p->nMem+1 - p->nCursor)+1 );
  82687. pData0 = &aMem[nField];
  82688. nField = pOp->p2;
  82689. pLast = &pData0[nField-1];
  82690. file_format = p->minWriteFileFormat;
  82691. /* Identify the output register */
  82692. assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
  82693. pOut = &aMem[pOp->p3];
  82694. memAboutToChange(p, pOut);
  82695. /* Apply the requested affinity to all inputs
  82696. */
  82697. assert( pData0<=pLast );
  82698. if( zAffinity ){
  82699. pRec = pData0;
  82700. do{
  82701. applyAffinity(pRec, zAffinity[0], encoding);
  82702. if( zAffinity[0]==SQLITE_AFF_REAL && (pRec->flags & MEM_Int) ){
  82703. pRec->flags |= MEM_IntReal;
  82704. pRec->flags &= ~(MEM_Int);
  82705. }
  82706. REGISTER_TRACE((int)(pRec-aMem), pRec);
  82707. zAffinity++;
  82708. pRec++;
  82709. assert( zAffinity[0]==0 || pRec<=pLast );
  82710. }while( zAffinity[0] );
  82711. }
  82712. #ifdef SQLITE_ENABLE_NULL_TRIM
  82713. /* NULLs can be safely trimmed from the end of the record, as long as
  82714. ** as the schema format is 2 or more and none of the omitted columns
  82715. ** have a non-NULL default value. Also, the record must be left with
  82716. ** at least one field. If P5>0 then it will be one more than the
  82717. ** index of the right-most column with a non-NULL default value */
  82718. if( pOp->p5 ){
  82719. while( (pLast->flags & MEM_Null)!=0 && nField>pOp->p5 ){
  82720. pLast--;
  82721. nField--;
  82722. }
  82723. }
  82724. #endif
  82725. /* Loop through the elements that will make up the record to figure
  82726. ** out how much space is required for the new record. After this loop,
  82727. ** the Mem.uTemp field of each term should hold the serial-type that will
  82728. ** be used for that term in the generated record:
  82729. **
  82730. ** Mem.uTemp value type
  82731. ** --------------- ---------------
  82732. ** 0 NULL
  82733. ** 1 1-byte signed integer
  82734. ** 2 2-byte signed integer
  82735. ** 3 3-byte signed integer
  82736. ** 4 4-byte signed integer
  82737. ** 5 6-byte signed integer
  82738. ** 6 8-byte signed integer
  82739. ** 7 IEEE float
  82740. ** 8 Integer constant 0
  82741. ** 9 Integer constant 1
  82742. ** 10,11 reserved for expansion
  82743. ** N>=12 and even BLOB
  82744. ** N>=13 and odd text
  82745. **
  82746. ** The following additional values are computed:
  82747. ** nHdr Number of bytes needed for the record header
  82748. ** nData Number of bytes of data space needed for the record
  82749. ** nZero Zero bytes at the end of the record
  82750. */
  82751. pRec = pLast;
  82752. do{
  82753. assert( memIsValid(pRec) );
  82754. if( pRec->flags & MEM_Null ){
  82755. if( pRec->flags & MEM_Zero ){
  82756. /* Values with MEM_Null and MEM_Zero are created by xColumn virtual
  82757. ** table methods that never invoke sqlite3_result_xxxxx() while
  82758. ** computing an unchanging column value in an UPDATE statement.
  82759. ** Give such values a special internal-use-only serial-type of 10
  82760. ** so that they can be passed through to xUpdate and have
  82761. ** a true sqlite3_value_nochange(). */
  82762. assert( pOp->p5==OPFLAG_NOCHNG_MAGIC || CORRUPT_DB );
  82763. pRec->uTemp = 10;
  82764. }else{
  82765. pRec->uTemp = 0;
  82766. }
  82767. nHdr++;
  82768. }else if( pRec->flags & (MEM_Int|MEM_IntReal) ){
  82769. /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
  82770. i64 i = pRec->u.i;
  82771. u64 uu;
  82772. testcase( pRec->flags & MEM_Int );
  82773. testcase( pRec->flags & MEM_IntReal );
  82774. if( i<0 ){
  82775. uu = ~i;
  82776. }else{
  82777. uu = i;
  82778. }
  82779. nHdr++;
  82780. testcase( uu==127 ); testcase( uu==128 );
  82781. testcase( uu==32767 ); testcase( uu==32768 );
  82782. testcase( uu==8388607 ); testcase( uu==8388608 );
  82783. testcase( uu==2147483647 ); testcase( uu==2147483648 );
  82784. testcase( uu==140737488355327LL ); testcase( uu==140737488355328LL );
  82785. if( uu<=127 ){
  82786. if( (i&1)==i && file_format>=4 ){
  82787. pRec->uTemp = 8+(u32)uu;
  82788. }else{
  82789. nData++;
  82790. pRec->uTemp = 1;
  82791. }
  82792. }else if( uu<=32767 ){
  82793. nData += 2;
  82794. pRec->uTemp = 2;
  82795. }else if( uu<=8388607 ){
  82796. nData += 3;
  82797. pRec->uTemp = 3;
  82798. }else if( uu<=2147483647 ){
  82799. nData += 4;
  82800. pRec->uTemp = 4;
  82801. }else if( uu<=140737488355327LL ){
  82802. nData += 6;
  82803. pRec->uTemp = 5;
  82804. }else{
  82805. nData += 8;
  82806. if( pRec->flags & MEM_IntReal ){
  82807. /* If the value is IntReal and is going to take up 8 bytes to store
  82808. ** as an integer, then we might as well make it an 8-byte floating
  82809. ** point value */
  82810. pRec->u.r = (double)pRec->u.i;
  82811. pRec->flags &= ~MEM_IntReal;
  82812. pRec->flags |= MEM_Real;
  82813. pRec->uTemp = 7;
  82814. }else{
  82815. pRec->uTemp = 6;
  82816. }
  82817. }
  82818. }else if( pRec->flags & MEM_Real ){
  82819. nHdr++;
  82820. nData += 8;
  82821. pRec->uTemp = 7;
  82822. }else{
  82823. assert( db->mallocFailed || pRec->flags&(MEM_Str|MEM_Blob) );
  82824. assert( pRec->n>=0 );
  82825. len = (u32)pRec->n;
  82826. serial_type = (len*2) + 12 + ((pRec->flags & MEM_Str)!=0);
  82827. if( pRec->flags & MEM_Zero ){
  82828. serial_type += pRec->u.nZero*2;
  82829. if( nData ){
  82830. if( sqlite3VdbeMemExpandBlob(pRec) ) goto no_mem;
  82831. len += pRec->u.nZero;
  82832. }else{
  82833. nZero += pRec->u.nZero;
  82834. }
  82835. }
  82836. nData += len;
  82837. nHdr += sqlite3VarintLen(serial_type);
  82838. pRec->uTemp = serial_type;
  82839. }
  82840. if( pRec==pData0 ) break;
  82841. pRec--;
  82842. }while(1);
  82843. /* EVIDENCE-OF: R-22564-11647 The header begins with a single varint
  82844. ** which determines the total number of bytes in the header. The varint
  82845. ** value is the size of the header in bytes including the size varint
  82846. ** itself. */
  82847. testcase( nHdr==126 );
  82848. testcase( nHdr==127 );
  82849. if( nHdr<=126 ){
  82850. /* The common case */
  82851. nHdr += 1;
  82852. }else{
  82853. /* Rare case of a really large header */
  82854. nVarint = sqlite3VarintLen(nHdr);
  82855. nHdr += nVarint;
  82856. if( nVarint<sqlite3VarintLen(nHdr) ) nHdr++;
  82857. }
  82858. nByte = nHdr+nData;
  82859. /* Make sure the output register has a buffer large enough to store
  82860. ** the new record. The output register (pOp->p3) is not allowed to
  82861. ** be one of the input registers (because the following call to
  82862. ** sqlite3VdbeMemClearAndResize() could clobber the value before it is used).
  82863. */
  82864. if( nByte+nZero<=pOut->szMalloc ){
  82865. /* The output register is already large enough to hold the record.
  82866. ** No error checks or buffer enlargement is required */
  82867. pOut->z = pOut->zMalloc;
  82868. }else{
  82869. /* Need to make sure that the output is not too big and then enlarge
  82870. ** the output register to hold the full result */
  82871. if( nByte+nZero>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  82872. goto too_big;
  82873. }
  82874. if( sqlite3VdbeMemClearAndResize(pOut, (int)nByte) ){
  82875. goto no_mem;
  82876. }
  82877. }
  82878. pOut->n = (int)nByte;
  82879. pOut->flags = MEM_Blob;
  82880. if( nZero ){
  82881. pOut->u.nZero = nZero;
  82882. pOut->flags |= MEM_Zero;
  82883. }
  82884. UPDATE_MAX_BLOBSIZE(pOut);
  82885. zHdr = (u8 *)pOut->z;
  82886. zPayload = zHdr + nHdr;
  82887. /* Write the record */
  82888. zHdr += putVarint32(zHdr, nHdr);
  82889. assert( pData0<=pLast );
  82890. pRec = pData0;
  82891. do{
  82892. serial_type = pRec->uTemp;
  82893. /* EVIDENCE-OF: R-06529-47362 Following the size varint are one or more
  82894. ** additional varints, one per column. */
  82895. zHdr += putVarint32(zHdr, serial_type); /* serial type */
  82896. /* EVIDENCE-OF: R-64536-51728 The values for each column in the record
  82897. ** immediately follow the header. */
  82898. zPayload += sqlite3VdbeSerialPut(zPayload, pRec, serial_type); /* content */
  82899. }while( (++pRec)<=pLast );
  82900. assert( nHdr==(int)(zHdr - (u8*)pOut->z) );
  82901. assert( nByte==(int)(zPayload - (u8*)pOut->z) );
  82902. assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
  82903. REGISTER_TRACE(pOp->p3, pOut);
  82904. break;
  82905. }
  82906. /* Opcode: Count P1 P2 p3 * *
  82907. ** Synopsis: r[P2]=count()
  82908. **
  82909. ** Store the number of entries (an integer value) in the table or index
  82910. ** opened by cursor P1 in register P2.
  82911. **
  82912. ** If P3==0, then an exact count is obtained, which involves visiting
  82913. ** every btree page of the table. But if P3 is non-zero, an estimate
  82914. ** is returned based on the current cursor position.
  82915. */
  82916. case OP_Count: { /* out2 */
  82917. i64 nEntry;
  82918. BtCursor *pCrsr;
  82919. assert( p->apCsr[pOp->p1]->eCurType==CURTYPE_BTREE );
  82920. pCrsr = p->apCsr[pOp->p1]->uc.pCursor;
  82921. assert( pCrsr );
  82922. if( pOp->p3 ){
  82923. nEntry = sqlite3BtreeRowCountEst(pCrsr);
  82924. }else{
  82925. nEntry = 0; /* Not needed. Only used to silence a warning. */
  82926. rc = sqlite3BtreeCount(db, pCrsr, &nEntry);
  82927. if( rc ) goto abort_due_to_error;
  82928. }
  82929. pOut = out2Prerelease(p, pOp);
  82930. pOut->u.i = nEntry;
  82931. goto check_for_interrupt;
  82932. }
  82933. /* Opcode: Savepoint P1 * * P4 *
  82934. **
  82935. ** Open, release or rollback the savepoint named by parameter P4, depending
  82936. ** on the value of P1. To open a new savepoint set P1==0 (SAVEPOINT_BEGIN).
  82937. ** To release (commit) an existing savepoint set P1==1 (SAVEPOINT_RELEASE).
  82938. ** To rollback an existing savepoint set P1==2 (SAVEPOINT_ROLLBACK).
  82939. */
  82940. case OP_Savepoint: {
  82941. int p1; /* Value of P1 operand */
  82942. char *zName; /* Name of savepoint */
  82943. int nName;
  82944. Savepoint *pNew;
  82945. Savepoint *pSavepoint;
  82946. Savepoint *pTmp;
  82947. int iSavepoint;
  82948. int ii;
  82949. p1 = pOp->p1;
  82950. zName = pOp->p4.z;
  82951. /* Assert that the p1 parameter is valid. Also that if there is no open
  82952. ** transaction, then there cannot be any savepoints.
  82953. */
  82954. assert( db->pSavepoint==0 || db->autoCommit==0 );
  82955. assert( p1==SAVEPOINT_BEGIN||p1==SAVEPOINT_RELEASE||p1==SAVEPOINT_ROLLBACK );
  82956. assert( db->pSavepoint || db->isTransactionSavepoint==0 );
  82957. assert( checkSavepointCount(db) );
  82958. assert( p->bIsReader );
  82959. if( p1==SAVEPOINT_BEGIN ){
  82960. if( db->nVdbeWrite>0 ){
  82961. /* A new savepoint cannot be created if there are active write
  82962. ** statements (i.e. open read/write incremental blob handles).
  82963. */
  82964. sqlite3VdbeError(p, "cannot open savepoint - SQL statements in progress");
  82965. rc = SQLITE_BUSY;
  82966. }else{
  82967. nName = sqlite3Strlen30(zName);
  82968. #ifndef SQLITE_OMIT_VIRTUALTABLE
  82969. /* This call is Ok even if this savepoint is actually a transaction
  82970. ** savepoint (and therefore should not prompt xSavepoint()) callbacks.
  82971. ** If this is a transaction savepoint being opened, it is guaranteed
  82972. ** that the db->aVTrans[] array is empty. */
  82973. assert( db->autoCommit==0 || db->nVTrans==0 );
  82974. rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN,
  82975. db->nStatement+db->nSavepoint);
  82976. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  82977. #endif
  82978. /* Create a new savepoint structure. */
  82979. pNew = sqlite3DbMallocRawNN(db, sizeof(Savepoint)+nName+1);
  82980. if( pNew ){
  82981. pNew->zName = (char *)&pNew[1];
  82982. memcpy(pNew->zName, zName, nName+1);
  82983. /* If there is no open transaction, then mark this as a special
  82984. ** "transaction savepoint". */
  82985. if( db->autoCommit ){
  82986. db->autoCommit = 0;
  82987. db->isTransactionSavepoint = 1;
  82988. }else{
  82989. db->nSavepoint++;
  82990. }
  82991. /* Link the new savepoint into the database handle's list. */
  82992. pNew->pNext = db->pSavepoint;
  82993. db->pSavepoint = pNew;
  82994. pNew->nDeferredCons = db->nDeferredCons;
  82995. pNew->nDeferredImmCons = db->nDeferredImmCons;
  82996. }
  82997. }
  82998. }else{
  82999. assert( p1==SAVEPOINT_RELEASE || p1==SAVEPOINT_ROLLBACK );
  83000. iSavepoint = 0;
  83001. /* Find the named savepoint. If there is no such savepoint, then an
  83002. ** an error is returned to the user. */
  83003. for(
  83004. pSavepoint = db->pSavepoint;
  83005. pSavepoint && sqlite3StrICmp(pSavepoint->zName, zName);
  83006. pSavepoint = pSavepoint->pNext
  83007. ){
  83008. iSavepoint++;
  83009. }
  83010. if( !pSavepoint ){
  83011. sqlite3VdbeError(p, "no such savepoint: %s", zName);
  83012. rc = SQLITE_ERROR;
  83013. }else if( db->nVdbeWrite>0 && p1==SAVEPOINT_RELEASE ){
  83014. /* It is not possible to release (commit) a savepoint if there are
  83015. ** active write statements.
  83016. */
  83017. sqlite3VdbeError(p, "cannot release savepoint - "
  83018. "SQL statements in progress");
  83019. rc = SQLITE_BUSY;
  83020. }else{
  83021. /* Determine whether or not this is a transaction savepoint. If so,
  83022. ** and this is a RELEASE command, then the current transaction
  83023. ** is committed.
  83024. */
  83025. int isTransaction = pSavepoint->pNext==0 && db->isTransactionSavepoint;
  83026. if( isTransaction && p1==SAVEPOINT_RELEASE ){
  83027. if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
  83028. goto vdbe_return;
  83029. }
  83030. db->autoCommit = 1;
  83031. if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
  83032. p->pc = (int)(pOp - aOp);
  83033. db->autoCommit = 0;
  83034. p->rc = rc = SQLITE_BUSY;
  83035. goto vdbe_return;
  83036. }
  83037. rc = p->rc;
  83038. if( rc ){
  83039. db->autoCommit = 0;
  83040. }else{
  83041. db->isTransactionSavepoint = 0;
  83042. }
  83043. }else{
  83044. int isSchemaChange;
  83045. iSavepoint = db->nSavepoint - iSavepoint - 1;
  83046. if( p1==SAVEPOINT_ROLLBACK ){
  83047. isSchemaChange = (db->mDbFlags & DBFLAG_SchemaChange)!=0;
  83048. for(ii=0; ii<db->nDb; ii++){
  83049. rc = sqlite3BtreeTripAllCursors(db->aDb[ii].pBt,
  83050. SQLITE_ABORT_ROLLBACK,
  83051. isSchemaChange==0);
  83052. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  83053. }
  83054. }else{
  83055. assert( p1==SAVEPOINT_RELEASE );
  83056. isSchemaChange = 0;
  83057. }
  83058. for(ii=0; ii<db->nDb; ii++){
  83059. rc = sqlite3BtreeSavepoint(db->aDb[ii].pBt, p1, iSavepoint);
  83060. if( rc!=SQLITE_OK ){
  83061. goto abort_due_to_error;
  83062. }
  83063. }
  83064. if( isSchemaChange ){
  83065. sqlite3ExpirePreparedStatements(db, 0);
  83066. sqlite3ResetAllSchemasOfConnection(db);
  83067. db->mDbFlags |= DBFLAG_SchemaChange;
  83068. }
  83069. }
  83070. if( rc ) goto abort_due_to_error;
  83071. /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
  83072. ** savepoints nested inside of the savepoint being operated on. */
  83073. while( db->pSavepoint!=pSavepoint ){
  83074. pTmp = db->pSavepoint;
  83075. db->pSavepoint = pTmp->pNext;
  83076. sqlite3DbFree(db, pTmp);
  83077. db->nSavepoint--;
  83078. }
  83079. /* If it is a RELEASE, then destroy the savepoint being operated on
  83080. ** too. If it is a ROLLBACK TO, then set the number of deferred
  83081. ** constraint violations present in the database to the value stored
  83082. ** when the savepoint was created. */
  83083. if( p1==SAVEPOINT_RELEASE ){
  83084. assert( pSavepoint==db->pSavepoint );
  83085. db->pSavepoint = pSavepoint->pNext;
  83086. sqlite3DbFree(db, pSavepoint);
  83087. if( !isTransaction ){
  83088. db->nSavepoint--;
  83089. }
  83090. }else{
  83091. assert( p1==SAVEPOINT_ROLLBACK );
  83092. db->nDeferredCons = pSavepoint->nDeferredCons;
  83093. db->nDeferredImmCons = pSavepoint->nDeferredImmCons;
  83094. }
  83095. if( !isTransaction || p1==SAVEPOINT_ROLLBACK ){
  83096. rc = sqlite3VtabSavepoint(db, p1, iSavepoint);
  83097. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  83098. }
  83099. }
  83100. }
  83101. if( rc ) goto abort_due_to_error;
  83102. break;
  83103. }
  83104. /* Opcode: AutoCommit P1 P2 * * *
  83105. **
  83106. ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
  83107. ** back any currently active btree transactions. If there are any active
  83108. ** VMs (apart from this one), then a ROLLBACK fails. A COMMIT fails if
  83109. ** there are active writing VMs or active VMs that use shared cache.
  83110. **
  83111. ** This instruction causes the VM to halt.
  83112. */
  83113. case OP_AutoCommit: {
  83114. int desiredAutoCommit;
  83115. int iRollback;
  83116. desiredAutoCommit = pOp->p1;
  83117. iRollback = pOp->p2;
  83118. assert( desiredAutoCommit==1 || desiredAutoCommit==0 );
  83119. assert( desiredAutoCommit==1 || iRollback==0 );
  83120. assert( db->nVdbeActive>0 ); /* At least this one VM is active */
  83121. assert( p->bIsReader );
  83122. if( desiredAutoCommit!=db->autoCommit ){
  83123. if( iRollback ){
  83124. assert( desiredAutoCommit==1 );
  83125. sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
  83126. db->autoCommit = 1;
  83127. }else if( desiredAutoCommit && db->nVdbeWrite>0 ){
  83128. /* If this instruction implements a COMMIT and other VMs are writing
  83129. ** return an error indicating that the other VMs must complete first.
  83130. */
  83131. sqlite3VdbeError(p, "cannot commit transaction - "
  83132. "SQL statements in progress");
  83133. rc = SQLITE_BUSY;
  83134. goto abort_due_to_error;
  83135. }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
  83136. goto vdbe_return;
  83137. }else{
  83138. db->autoCommit = (u8)desiredAutoCommit;
  83139. }
  83140. if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
  83141. p->pc = (int)(pOp - aOp);
  83142. db->autoCommit = (u8)(1-desiredAutoCommit);
  83143. p->rc = rc = SQLITE_BUSY;
  83144. goto vdbe_return;
  83145. }
  83146. sqlite3CloseSavepoints(db);
  83147. if( p->rc==SQLITE_OK ){
  83148. rc = SQLITE_DONE;
  83149. }else{
  83150. rc = SQLITE_ERROR;
  83151. }
  83152. goto vdbe_return;
  83153. }else{
  83154. sqlite3VdbeError(p,
  83155. (!desiredAutoCommit)?"cannot start a transaction within a transaction":(
  83156. (iRollback)?"cannot rollback - no transaction is active":
  83157. "cannot commit - no transaction is active"));
  83158. rc = SQLITE_ERROR;
  83159. goto abort_due_to_error;
  83160. }
  83161. /*NOTREACHED*/ assert(0);
  83162. }
  83163. /* Opcode: Transaction P1 P2 P3 P4 P5
  83164. **
  83165. ** Begin a transaction on database P1 if a transaction is not already
  83166. ** active.
  83167. ** If P2 is non-zero, then a write-transaction is started, or if a
  83168. ** read-transaction is already active, it is upgraded to a write-transaction.
  83169. ** If P2 is zero, then a read-transaction is started.
  83170. **
  83171. ** P1 is the index of the database file on which the transaction is
  83172. ** started. Index 0 is the main database file and index 1 is the
  83173. ** file used for temporary tables. Indices of 2 or more are used for
  83174. ** attached databases.
  83175. **
  83176. ** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
  83177. ** true (this flag is set if the Vdbe may modify more than one row and may
  83178. ** throw an ABORT exception), a statement transaction may also be opened.
  83179. ** More specifically, a statement transaction is opened iff the database
  83180. ** connection is currently not in autocommit mode, or if there are other
  83181. ** active statements. A statement transaction allows the changes made by this
  83182. ** VDBE to be rolled back after an error without having to roll back the
  83183. ** entire transaction. If no error is encountered, the statement transaction
  83184. ** will automatically commit when the VDBE halts.
  83185. **
  83186. ** If P5!=0 then this opcode also checks the schema cookie against P3
  83187. ** and the schema generation counter against P4.
  83188. ** The cookie changes its value whenever the database schema changes.
  83189. ** This operation is used to detect when that the cookie has changed
  83190. ** and that the current process needs to reread the schema. If the schema
  83191. ** cookie in P3 differs from the schema cookie in the database header or
  83192. ** if the schema generation counter in P4 differs from the current
  83193. ** generation counter, then an SQLITE_SCHEMA error is raised and execution
  83194. ** halts. The sqlite3_step() wrapper function might then reprepare the
  83195. ** statement and rerun it from the beginning.
  83196. */
  83197. case OP_Transaction: {
  83198. Btree *pBt;
  83199. int iMeta = 0;
  83200. assert( p->bIsReader );
  83201. assert( p->readOnly==0 || pOp->p2==0 );
  83202. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  83203. assert( DbMaskTest(p->btreeMask, pOp->p1) );
  83204. if( pOp->p2 && (db->flags & SQLITE_QueryOnly)!=0 ){
  83205. rc = SQLITE_READONLY;
  83206. goto abort_due_to_error;
  83207. }
  83208. pBt = db->aDb[pOp->p1].pBt;
  83209. if( pBt ){
  83210. rc = sqlite3BtreeBeginTrans(pBt, pOp->p2, &iMeta);
  83211. testcase( rc==SQLITE_BUSY_SNAPSHOT );
  83212. testcase( rc==SQLITE_BUSY_RECOVERY );
  83213. if( rc!=SQLITE_OK ){
  83214. if( (rc&0xff)==SQLITE_BUSY ){
  83215. p->pc = (int)(pOp - aOp);
  83216. p->rc = rc;
  83217. goto vdbe_return;
  83218. }
  83219. goto abort_due_to_error;
  83220. }
  83221. if( p->usesStmtJournal
  83222. && pOp->p2
  83223. && (db->autoCommit==0 || db->nVdbeRead>1)
  83224. ){
  83225. assert( sqlite3BtreeIsInTrans(pBt) );
  83226. if( p->iStatement==0 ){
  83227. assert( db->nStatement>=0 && db->nSavepoint>=0 );
  83228. db->nStatement++;
  83229. p->iStatement = db->nSavepoint + db->nStatement;
  83230. }
  83231. rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, p->iStatement-1);
  83232. if( rc==SQLITE_OK ){
  83233. rc = sqlite3BtreeBeginStmt(pBt, p->iStatement);
  83234. }
  83235. /* Store the current value of the database handles deferred constraint
  83236. ** counter. If the statement transaction needs to be rolled back,
  83237. ** the value of this counter needs to be restored too. */
  83238. p->nStmtDefCons = db->nDeferredCons;
  83239. p->nStmtDefImmCons = db->nDeferredImmCons;
  83240. }
  83241. }
  83242. assert( pOp->p5==0 || pOp->p4type==P4_INT32 );
  83243. if( pOp->p5
  83244. && (iMeta!=pOp->p3
  83245. || db->aDb[pOp->p1].pSchema->iGeneration!=pOp->p4.i)
  83246. ){
  83247. /*
  83248. ** IMPLEMENTATION-OF: R-03189-51135 As each SQL statement runs, the schema
  83249. ** version is checked to ensure that the schema has not changed since the
  83250. ** SQL statement was prepared.
  83251. */
  83252. sqlite3DbFree(db, p->zErrMsg);
  83253. p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
  83254. /* If the schema-cookie from the database file matches the cookie
  83255. ** stored with the in-memory representation of the schema, do
  83256. ** not reload the schema from the database file.
  83257. **
  83258. ** If virtual-tables are in use, this is not just an optimization.
  83259. ** Often, v-tables store their data in other SQLite tables, which
  83260. ** are queried from within xNext() and other v-table methods using
  83261. ** prepared queries. If such a query is out-of-date, we do not want to
  83262. ** discard the database schema, as the user code implementing the
  83263. ** v-table would have to be ready for the sqlite3_vtab structure itself
  83264. ** to be invalidated whenever sqlite3_step() is called from within
  83265. ** a v-table method.
  83266. */
  83267. if( db->aDb[pOp->p1].pSchema->schema_cookie!=iMeta ){
  83268. sqlite3ResetOneSchema(db, pOp->p1);
  83269. }
  83270. p->expired = 1;
  83271. rc = SQLITE_SCHEMA;
  83272. }
  83273. if( rc ) goto abort_due_to_error;
  83274. break;
  83275. }
  83276. /* Opcode: ReadCookie P1 P2 P3 * *
  83277. **
  83278. ** Read cookie number P3 from database P1 and write it into register P2.
  83279. ** P3==1 is the schema version. P3==2 is the database format.
  83280. ** P3==3 is the recommended pager cache size, and so forth. P1==0 is
  83281. ** the main database file and P1==1 is the database file used to store
  83282. ** temporary tables.
  83283. **
  83284. ** There must be a read-lock on the database (either a transaction
  83285. ** must be started or there must be an open cursor) before
  83286. ** executing this instruction.
  83287. */
  83288. case OP_ReadCookie: { /* out2 */
  83289. int iMeta;
  83290. int iDb;
  83291. int iCookie;
  83292. assert( p->bIsReader );
  83293. iDb = pOp->p1;
  83294. iCookie = pOp->p3;
  83295. assert( pOp->p3<SQLITE_N_BTREE_META );
  83296. assert( iDb>=0 && iDb<db->nDb );
  83297. assert( db->aDb[iDb].pBt!=0 );
  83298. assert( DbMaskTest(p->btreeMask, iDb) );
  83299. sqlite3BtreeGetMeta(db->aDb[iDb].pBt, iCookie, (u32 *)&iMeta);
  83300. pOut = out2Prerelease(p, pOp);
  83301. pOut->u.i = iMeta;
  83302. break;
  83303. }
  83304. /* Opcode: SetCookie P1 P2 P3 * *
  83305. **
  83306. ** Write the integer value P3 into cookie number P2 of database P1.
  83307. ** P2==1 is the schema version. P2==2 is the database format.
  83308. ** P2==3 is the recommended pager cache
  83309. ** size, and so forth. P1==0 is the main database file and P1==1 is the
  83310. ** database file used to store temporary tables.
  83311. **
  83312. ** A transaction must be started before executing this opcode.
  83313. */
  83314. case OP_SetCookie: {
  83315. Db *pDb;
  83316. sqlite3VdbeIncrWriteCounter(p, 0);
  83317. assert( pOp->p2<SQLITE_N_BTREE_META );
  83318. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  83319. assert( DbMaskTest(p->btreeMask, pOp->p1) );
  83320. assert( p->readOnly==0 );
  83321. pDb = &db->aDb[pOp->p1];
  83322. assert( pDb->pBt!=0 );
  83323. assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
  83324. /* See note about index shifting on OP_ReadCookie */
  83325. rc = sqlite3BtreeUpdateMeta(pDb->pBt, pOp->p2, pOp->p3);
  83326. if( pOp->p2==BTREE_SCHEMA_VERSION ){
  83327. /* When the schema cookie changes, record the new cookie internally */
  83328. pDb->pSchema->schema_cookie = pOp->p3;
  83329. db->mDbFlags |= DBFLAG_SchemaChange;
  83330. }else if( pOp->p2==BTREE_FILE_FORMAT ){
  83331. /* Record changes in the file format */
  83332. pDb->pSchema->file_format = pOp->p3;
  83333. }
  83334. if( pOp->p1==1 ){
  83335. /* Invalidate all prepared statements whenever the TEMP database
  83336. ** schema is changed. Ticket #1644 */
  83337. sqlite3ExpirePreparedStatements(db, 0);
  83338. p->expired = 0;
  83339. }
  83340. if( rc ) goto abort_due_to_error;
  83341. break;
  83342. }
  83343. /* Opcode: OpenRead P1 P2 P3 P4 P5
  83344. ** Synopsis: root=P2 iDb=P3
  83345. **
  83346. ** Open a read-only cursor for the database table whose root page is
  83347. ** P2 in a database file. The database file is determined by P3.
  83348. ** P3==0 means the main database, P3==1 means the database used for
  83349. ** temporary tables, and P3>1 means used the corresponding attached
  83350. ** database. Give the new cursor an identifier of P1. The P1
  83351. ** values need not be contiguous but all P1 values should be small integers.
  83352. ** It is an error for P1 to be negative.
  83353. **
  83354. ** Allowed P5 bits:
  83355. ** <ul>
  83356. ** <li> <b>0x02 OPFLAG_SEEKEQ</b>: This cursor will only be used for
  83357. ** equality lookups (implemented as a pair of opcodes OP_SeekGE/OP_IdxGT
  83358. ** of OP_SeekLE/OP_IdxLT)
  83359. ** </ul>
  83360. **
  83361. ** The P4 value may be either an integer (P4_INT32) or a pointer to
  83362. ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
  83363. ** object, then table being opened must be an [index b-tree] where the
  83364. ** KeyInfo object defines the content and collating
  83365. ** sequence of that index b-tree. Otherwise, if P4 is an integer
  83366. ** value, then the table being opened must be a [table b-tree] with a
  83367. ** number of columns no less than the value of P4.
  83368. **
  83369. ** See also: OpenWrite, ReopenIdx
  83370. */
  83371. /* Opcode: ReopenIdx P1 P2 P3 P4 P5
  83372. ** Synopsis: root=P2 iDb=P3
  83373. **
  83374. ** The ReopenIdx opcode works like OP_OpenRead except that it first
  83375. ** checks to see if the cursor on P1 is already open on the same
  83376. ** b-tree and if it is this opcode becomes a no-op. In other words,
  83377. ** if the cursor is already open, do not reopen it.
  83378. **
  83379. ** The ReopenIdx opcode may only be used with P5==0 or P5==OPFLAG_SEEKEQ
  83380. ** and with P4 being a P4_KEYINFO object. Furthermore, the P3 value must
  83381. ** be the same as every other ReopenIdx or OpenRead for the same cursor
  83382. ** number.
  83383. **
  83384. ** Allowed P5 bits:
  83385. ** <ul>
  83386. ** <li> <b>0x02 OPFLAG_SEEKEQ</b>: This cursor will only be used for
  83387. ** equality lookups (implemented as a pair of opcodes OP_SeekGE/OP_IdxGT
  83388. ** of OP_SeekLE/OP_IdxLT)
  83389. ** </ul>
  83390. **
  83391. ** See also: OP_OpenRead, OP_OpenWrite
  83392. */
  83393. /* Opcode: OpenWrite P1 P2 P3 P4 P5
  83394. ** Synopsis: root=P2 iDb=P3
  83395. **
  83396. ** Open a read/write cursor named P1 on the table or index whose root
  83397. ** page is P2 (or whose root page is held in register P2 if the
  83398. ** OPFLAG_P2ISREG bit is set in P5 - see below).
  83399. **
  83400. ** The P4 value may be either an integer (P4_INT32) or a pointer to
  83401. ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
  83402. ** object, then table being opened must be an [index b-tree] where the
  83403. ** KeyInfo object defines the content and collating
  83404. ** sequence of that index b-tree. Otherwise, if P4 is an integer
  83405. ** value, then the table being opened must be a [table b-tree] with a
  83406. ** number of columns no less than the value of P4.
  83407. **
  83408. ** Allowed P5 bits:
  83409. ** <ul>
  83410. ** <li> <b>0x02 OPFLAG_SEEKEQ</b>: This cursor will only be used for
  83411. ** equality lookups (implemented as a pair of opcodes OP_SeekGE/OP_IdxGT
  83412. ** of OP_SeekLE/OP_IdxLT)
  83413. ** <li> <b>0x08 OPFLAG_FORDELETE</b>: This cursor is used only to seek
  83414. ** and subsequently delete entries in an index btree. This is a
  83415. ** hint to the storage engine that the storage engine is allowed to
  83416. ** ignore. The hint is not used by the official SQLite b*tree storage
  83417. ** engine, but is used by COMDB2.
  83418. ** <li> <b>0x10 OPFLAG_P2ISREG</b>: Use the content of register P2
  83419. ** as the root page, not the value of P2 itself.
  83420. ** </ul>
  83421. **
  83422. ** This instruction works like OpenRead except that it opens the cursor
  83423. ** in read/write mode.
  83424. **
  83425. ** See also: OP_OpenRead, OP_ReopenIdx
  83426. */
  83427. case OP_ReopenIdx: {
  83428. int nField;
  83429. KeyInfo *pKeyInfo;
  83430. int p2;
  83431. int iDb;
  83432. int wrFlag;
  83433. Btree *pX;
  83434. VdbeCursor *pCur;
  83435. Db *pDb;
  83436. assert( pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ );
  83437. assert( pOp->p4type==P4_KEYINFO );
  83438. pCur = p->apCsr[pOp->p1];
  83439. if( pCur && pCur->pgnoRoot==(u32)pOp->p2 ){
  83440. assert( pCur->iDb==pOp->p3 ); /* Guaranteed by the code generator */
  83441. goto open_cursor_set_hints;
  83442. }
  83443. /* If the cursor is not currently open or is open on a different
  83444. ** index, then fall through into OP_OpenRead to force a reopen */
  83445. case OP_OpenRead:
  83446. case OP_OpenWrite:
  83447. assert( pOp->opcode==OP_OpenWrite || pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ );
  83448. assert( p->bIsReader );
  83449. assert( pOp->opcode==OP_OpenRead || pOp->opcode==OP_ReopenIdx
  83450. || p->readOnly==0 );
  83451. if( p->expired==1 ){
  83452. rc = SQLITE_ABORT_ROLLBACK;
  83453. goto abort_due_to_error;
  83454. }
  83455. nField = 0;
  83456. pKeyInfo = 0;
  83457. p2 = pOp->p2;
  83458. iDb = pOp->p3;
  83459. assert( iDb>=0 && iDb<db->nDb );
  83460. assert( DbMaskTest(p->btreeMask, iDb) );
  83461. pDb = &db->aDb[iDb];
  83462. pX = pDb->pBt;
  83463. assert( pX!=0 );
  83464. if( pOp->opcode==OP_OpenWrite ){
  83465. assert( OPFLAG_FORDELETE==BTREE_FORDELETE );
  83466. wrFlag = BTREE_WRCSR | (pOp->p5 & OPFLAG_FORDELETE);
  83467. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  83468. if( pDb->pSchema->file_format < p->minWriteFileFormat ){
  83469. p->minWriteFileFormat = pDb->pSchema->file_format;
  83470. }
  83471. }else{
  83472. wrFlag = 0;
  83473. }
  83474. if( pOp->p5 & OPFLAG_P2ISREG ){
  83475. assert( p2>0 );
  83476. assert( p2<=(p->nMem+1 - p->nCursor) );
  83477. assert( pOp->opcode==OP_OpenWrite );
  83478. pIn2 = &aMem[p2];
  83479. assert( memIsValid(pIn2) );
  83480. assert( (pIn2->flags & MEM_Int)!=0 );
  83481. sqlite3VdbeMemIntegerify(pIn2);
  83482. p2 = (int)pIn2->u.i;
  83483. /* The p2 value always comes from a prior OP_CreateBtree opcode and
  83484. ** that opcode will always set the p2 value to 2 or more or else fail.
  83485. ** If there were a failure, the prepared statement would have halted
  83486. ** before reaching this instruction. */
  83487. assert( p2>=2 );
  83488. }
  83489. if( pOp->p4type==P4_KEYINFO ){
  83490. pKeyInfo = pOp->p4.pKeyInfo;
  83491. assert( pKeyInfo->enc==ENC(db) );
  83492. assert( pKeyInfo->db==db );
  83493. nField = pKeyInfo->nAllField;
  83494. }else if( pOp->p4type==P4_INT32 ){
  83495. nField = pOp->p4.i;
  83496. }
  83497. assert( pOp->p1>=0 );
  83498. assert( nField>=0 );
  83499. testcase( nField==0 ); /* Table with INTEGER PRIMARY KEY and nothing else */
  83500. pCur = allocateCursor(p, pOp->p1, nField, iDb, CURTYPE_BTREE);
  83501. if( pCur==0 ) goto no_mem;
  83502. pCur->nullRow = 1;
  83503. pCur->isOrdered = 1;
  83504. pCur->pgnoRoot = p2;
  83505. #ifdef SQLITE_DEBUG
  83506. pCur->wrFlag = wrFlag;
  83507. #endif
  83508. rc = sqlite3BtreeCursor(pX, p2, wrFlag, pKeyInfo, pCur->uc.pCursor);
  83509. pCur->pKeyInfo = pKeyInfo;
  83510. /* Set the VdbeCursor.isTable variable. Previous versions of
  83511. ** SQLite used to check if the root-page flags were sane at this point
  83512. ** and report database corruption if they were not, but this check has
  83513. ** since moved into the btree layer. */
  83514. pCur->isTable = pOp->p4type!=P4_KEYINFO;
  83515. open_cursor_set_hints:
  83516. assert( OPFLAG_BULKCSR==BTREE_BULKLOAD );
  83517. assert( OPFLAG_SEEKEQ==BTREE_SEEK_EQ );
  83518. testcase( pOp->p5 & OPFLAG_BULKCSR );
  83519. testcase( pOp->p2 & OPFLAG_SEEKEQ );
  83520. sqlite3BtreeCursorHintFlags(pCur->uc.pCursor,
  83521. (pOp->p5 & (OPFLAG_BULKCSR|OPFLAG_SEEKEQ)));
  83522. if( rc ) goto abort_due_to_error;
  83523. break;
  83524. }
  83525. /* Opcode: OpenDup P1 P2 * * *
  83526. **
  83527. ** Open a new cursor P1 that points to the same ephemeral table as
  83528. ** cursor P2. The P2 cursor must have been opened by a prior OP_OpenEphemeral
  83529. ** opcode. Only ephemeral cursors may be duplicated.
  83530. **
  83531. ** Duplicate ephemeral cursors are used for self-joins of materialized views.
  83532. */
  83533. case OP_OpenDup: {
  83534. VdbeCursor *pOrig; /* The original cursor to be duplicated */
  83535. VdbeCursor *pCx; /* The new cursor */
  83536. pOrig = p->apCsr[pOp->p2];
  83537. assert( pOrig );
  83538. assert( pOrig->pBtx!=0 ); /* Only ephemeral cursors can be duplicated */
  83539. pCx = allocateCursor(p, pOp->p1, pOrig->nField, -1, CURTYPE_BTREE);
  83540. if( pCx==0 ) goto no_mem;
  83541. pCx->nullRow = 1;
  83542. pCx->isEphemeral = 1;
  83543. pCx->pKeyInfo = pOrig->pKeyInfo;
  83544. pCx->isTable = pOrig->isTable;
  83545. pCx->pgnoRoot = pOrig->pgnoRoot;
  83546. pCx->isOrdered = pOrig->isOrdered;
  83547. rc = sqlite3BtreeCursor(pOrig->pBtx, pCx->pgnoRoot, BTREE_WRCSR,
  83548. pCx->pKeyInfo, pCx->uc.pCursor);
  83549. /* The sqlite3BtreeCursor() routine can only fail for the first cursor
  83550. ** opened for a database. Since there is already an open cursor when this
  83551. ** opcode is run, the sqlite3BtreeCursor() cannot fail */
  83552. assert( rc==SQLITE_OK );
  83553. break;
  83554. }
  83555. /* Opcode: OpenEphemeral P1 P2 * P4 P5
  83556. ** Synopsis: nColumn=P2
  83557. **
  83558. ** Open a new cursor P1 to a transient table.
  83559. ** The cursor is always opened read/write even if
  83560. ** the main database is read-only. The ephemeral
  83561. ** table is deleted automatically when the cursor is closed.
  83562. **
  83563. ** If the cursor P1 is already opened on an ephemeral table, the table
  83564. ** is cleared (all content is erased).
  83565. **
  83566. ** P2 is the number of columns in the ephemeral table.
  83567. ** The cursor points to a BTree table if P4==0 and to a BTree index
  83568. ** if P4 is not 0. If P4 is not NULL, it points to a KeyInfo structure
  83569. ** that defines the format of keys in the index.
  83570. **
  83571. ** The P5 parameter can be a mask of the BTREE_* flags defined
  83572. ** in btree.h. These flags control aspects of the operation of
  83573. ** the btree. The BTREE_OMIT_JOURNAL and BTREE_SINGLE flags are
  83574. ** added automatically.
  83575. */
  83576. /* Opcode: OpenAutoindex P1 P2 * P4 *
  83577. ** Synopsis: nColumn=P2
  83578. **
  83579. ** This opcode works the same as OP_OpenEphemeral. It has a
  83580. ** different name to distinguish its use. Tables created using
  83581. ** by this opcode will be used for automatically created transient
  83582. ** indices in joins.
  83583. */
  83584. case OP_OpenAutoindex:
  83585. case OP_OpenEphemeral: {
  83586. VdbeCursor *pCx;
  83587. KeyInfo *pKeyInfo;
  83588. static const int vfsFlags =
  83589. SQLITE_OPEN_READWRITE |
  83590. SQLITE_OPEN_CREATE |
  83591. SQLITE_OPEN_EXCLUSIVE |
  83592. SQLITE_OPEN_DELETEONCLOSE |
  83593. SQLITE_OPEN_TRANSIENT_DB;
  83594. assert( pOp->p1>=0 );
  83595. assert( pOp->p2>=0 );
  83596. pCx = p->apCsr[pOp->p1];
  83597. if( pCx && pCx->pBtx ){
  83598. /* If the ephermeral table is already open, erase all existing content
  83599. ** so that the table is empty again, rather than creating a new table. */
  83600. assert( pCx->isEphemeral );
  83601. pCx->seqCount = 0;
  83602. pCx->cacheStatus = CACHE_STALE;
  83603. rc = sqlite3BtreeClearTable(pCx->pBtx, pCx->pgnoRoot, 0);
  83604. }else{
  83605. pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, CURTYPE_BTREE);
  83606. if( pCx==0 ) goto no_mem;
  83607. pCx->isEphemeral = 1;
  83608. rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pCx->pBtx,
  83609. BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5,
  83610. vfsFlags);
  83611. if( rc==SQLITE_OK ){
  83612. rc = sqlite3BtreeBeginTrans(pCx->pBtx, 1, 0);
  83613. }
  83614. if( rc==SQLITE_OK ){
  83615. /* If a transient index is required, create it by calling
  83616. ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before
  83617. ** opening it. If a transient table is required, just use the
  83618. ** automatically created table with root-page 1 (an BLOB_INTKEY table).
  83619. */
  83620. if( (pCx->pKeyInfo = pKeyInfo = pOp->p4.pKeyInfo)!=0 ){
  83621. assert( pOp->p4type==P4_KEYINFO );
  83622. rc = sqlite3BtreeCreateTable(pCx->pBtx, (int*)&pCx->pgnoRoot,
  83623. BTREE_BLOBKEY | pOp->p5);
  83624. if( rc==SQLITE_OK ){
  83625. assert( pCx->pgnoRoot==MASTER_ROOT+1 );
  83626. assert( pKeyInfo->db==db );
  83627. assert( pKeyInfo->enc==ENC(db) );
  83628. rc = sqlite3BtreeCursor(pCx->pBtx, pCx->pgnoRoot, BTREE_WRCSR,
  83629. pKeyInfo, pCx->uc.pCursor);
  83630. }
  83631. pCx->isTable = 0;
  83632. }else{
  83633. pCx->pgnoRoot = MASTER_ROOT;
  83634. rc = sqlite3BtreeCursor(pCx->pBtx, MASTER_ROOT, BTREE_WRCSR,
  83635. 0, pCx->uc.pCursor);
  83636. pCx->isTable = 1;
  83637. }
  83638. }
  83639. pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
  83640. }
  83641. if( rc ) goto abort_due_to_error;
  83642. pCx->nullRow = 1;
  83643. break;
  83644. }
  83645. /* Opcode: SorterOpen P1 P2 P3 P4 *
  83646. **
  83647. ** This opcode works like OP_OpenEphemeral except that it opens
  83648. ** a transient index that is specifically designed to sort large
  83649. ** tables using an external merge-sort algorithm.
  83650. **
  83651. ** If argument P3 is non-zero, then it indicates that the sorter may
  83652. ** assume that a stable sort considering the first P3 fields of each
  83653. ** key is sufficient to produce the required results.
  83654. */
  83655. case OP_SorterOpen: {
  83656. VdbeCursor *pCx;
  83657. assert( pOp->p1>=0 );
  83658. assert( pOp->p2>=0 );
  83659. pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, CURTYPE_SORTER);
  83660. if( pCx==0 ) goto no_mem;
  83661. pCx->pKeyInfo = pOp->p4.pKeyInfo;
  83662. assert( pCx->pKeyInfo->db==db );
  83663. assert( pCx->pKeyInfo->enc==ENC(db) );
  83664. rc = sqlite3VdbeSorterInit(db, pOp->p3, pCx);
  83665. if( rc ) goto abort_due_to_error;
  83666. break;
  83667. }
  83668. /* Opcode: SequenceTest P1 P2 * * *
  83669. ** Synopsis: if( cursor[P1].ctr++ ) pc = P2
  83670. **
  83671. ** P1 is a sorter cursor. If the sequence counter is currently zero, jump
  83672. ** to P2. Regardless of whether or not the jump is taken, increment the
  83673. ** the sequence value.
  83674. */
  83675. case OP_SequenceTest: {
  83676. VdbeCursor *pC;
  83677. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  83678. pC = p->apCsr[pOp->p1];
  83679. assert( isSorter(pC) );
  83680. if( (pC->seqCount++)==0 ){
  83681. goto jump_to_p2;
  83682. }
  83683. break;
  83684. }
  83685. /* Opcode: OpenPseudo P1 P2 P3 * *
  83686. ** Synopsis: P3 columns in r[P2]
  83687. **
  83688. ** Open a new cursor that points to a fake table that contains a single
  83689. ** row of data. The content of that one row is the content of memory
  83690. ** register P2. In other words, cursor P1 becomes an alias for the
  83691. ** MEM_Blob content contained in register P2.
  83692. **
  83693. ** A pseudo-table created by this opcode is used to hold a single
  83694. ** row output from the sorter so that the row can be decomposed into
  83695. ** individual columns using the OP_Column opcode. The OP_Column opcode
  83696. ** is the only cursor opcode that works with a pseudo-table.
  83697. **
  83698. ** P3 is the number of fields in the records that will be stored by
  83699. ** the pseudo-table.
  83700. */
  83701. case OP_OpenPseudo: {
  83702. VdbeCursor *pCx;
  83703. assert( pOp->p1>=0 );
  83704. assert( pOp->p3>=0 );
  83705. pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, CURTYPE_PSEUDO);
  83706. if( pCx==0 ) goto no_mem;
  83707. pCx->nullRow = 1;
  83708. pCx->seekResult = pOp->p2;
  83709. pCx->isTable = 1;
  83710. /* Give this pseudo-cursor a fake BtCursor pointer so that pCx
  83711. ** can be safely passed to sqlite3VdbeCursorMoveto(). This avoids a test
  83712. ** for pCx->eCurType==CURTYPE_BTREE inside of sqlite3VdbeCursorMoveto()
  83713. ** which is a performance optimization */
  83714. pCx->uc.pCursor = sqlite3BtreeFakeValidCursor();
  83715. assert( pOp->p5==0 );
  83716. break;
  83717. }
  83718. /* Opcode: Close P1 * * * *
  83719. **
  83720. ** Close a cursor previously opened as P1. If P1 is not
  83721. ** currently open, this instruction is a no-op.
  83722. */
  83723. case OP_Close: {
  83724. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  83725. sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
  83726. p->apCsr[pOp->p1] = 0;
  83727. break;
  83728. }
  83729. #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
  83730. /* Opcode: ColumnsUsed P1 * * P4 *
  83731. **
  83732. ** This opcode (which only exists if SQLite was compiled with
  83733. ** SQLITE_ENABLE_COLUMN_USED_MASK) identifies which columns of the
  83734. ** table or index for cursor P1 are used. P4 is a 64-bit integer
  83735. ** (P4_INT64) in which the first 63 bits are one for each of the
  83736. ** first 63 columns of the table or index that are actually used
  83737. ** by the cursor. The high-order bit is set if any column after
  83738. ** the 64th is used.
  83739. */
  83740. case OP_ColumnsUsed: {
  83741. VdbeCursor *pC;
  83742. pC = p->apCsr[pOp->p1];
  83743. assert( pC->eCurType==CURTYPE_BTREE );
  83744. pC->maskUsed = *(u64*)pOp->p4.pI64;
  83745. break;
  83746. }
  83747. #endif
  83748. /* Opcode: SeekGE P1 P2 P3 P4 *
  83749. ** Synopsis: key=r[P3@P4]
  83750. **
  83751. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  83752. ** use the value in register P3 as the key. If cursor P1 refers
  83753. ** to an SQL index, then P3 is the first in an array of P4 registers
  83754. ** that are used as an unpacked index key.
  83755. **
  83756. ** Reposition cursor P1 so that it points to the smallest entry that
  83757. ** is greater than or equal to the key value. If there are no records
  83758. ** greater than or equal to the key and P2 is not zero, then jump to P2.
  83759. **
  83760. ** If the cursor P1 was opened using the OPFLAG_SEEKEQ flag, then this
  83761. ** opcode will either land on a record that exactly matches the key, or
  83762. ** else it will cause a jump to P2. When the cursor is OPFLAG_SEEKEQ,
  83763. ** this opcode must be followed by an IdxLE opcode with the same arguments.
  83764. ** The IdxGT opcode will be skipped if this opcode succeeds, but the
  83765. ** IdxGT opcode will be used on subsequent loop iterations. The
  83766. ** OPFLAG_SEEKEQ flags is a hint to the btree layer to say that this
  83767. ** is an equality search.
  83768. **
  83769. ** This opcode leaves the cursor configured to move in forward order,
  83770. ** from the beginning toward the end. In other words, the cursor is
  83771. ** configured to use Next, not Prev.
  83772. **
  83773. ** See also: Found, NotFound, SeekLt, SeekGt, SeekLe
  83774. */
  83775. /* Opcode: SeekGT P1 P2 P3 P4 *
  83776. ** Synopsis: key=r[P3@P4]
  83777. **
  83778. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  83779. ** use the value in register P3 as a key. If cursor P1 refers
  83780. ** to an SQL index, then P3 is the first in an array of P4 registers
  83781. ** that are used as an unpacked index key.
  83782. **
  83783. ** Reposition cursor P1 so that it points to the smallest entry that
  83784. ** is greater than the key value. If there are no records greater than
  83785. ** the key and P2 is not zero, then jump to P2.
  83786. **
  83787. ** This opcode leaves the cursor configured to move in forward order,
  83788. ** from the beginning toward the end. In other words, the cursor is
  83789. ** configured to use Next, not Prev.
  83790. **
  83791. ** See also: Found, NotFound, SeekLt, SeekGe, SeekLe
  83792. */
  83793. /* Opcode: SeekLT P1 P2 P3 P4 *
  83794. ** Synopsis: key=r[P3@P4]
  83795. **
  83796. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  83797. ** use the value in register P3 as a key. If cursor P1 refers
  83798. ** to an SQL index, then P3 is the first in an array of P4 registers
  83799. ** that are used as an unpacked index key.
  83800. **
  83801. ** Reposition cursor P1 so that it points to the largest entry that
  83802. ** is less than the key value. If there are no records less than
  83803. ** the key and P2 is not zero, then jump to P2.
  83804. **
  83805. ** This opcode leaves the cursor configured to move in reverse order,
  83806. ** from the end toward the beginning. In other words, the cursor is
  83807. ** configured to use Prev, not Next.
  83808. **
  83809. ** See also: Found, NotFound, SeekGt, SeekGe, SeekLe
  83810. */
  83811. /* Opcode: SeekLE P1 P2 P3 P4 *
  83812. ** Synopsis: key=r[P3@P4]
  83813. **
  83814. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  83815. ** use the value in register P3 as a key. If cursor P1 refers
  83816. ** to an SQL index, then P3 is the first in an array of P4 registers
  83817. ** that are used as an unpacked index key.
  83818. **
  83819. ** Reposition cursor P1 so that it points to the largest entry that
  83820. ** is less than or equal to the key value. If there are no records
  83821. ** less than or equal to the key and P2 is not zero, then jump to P2.
  83822. **
  83823. ** This opcode leaves the cursor configured to move in reverse order,
  83824. ** from the end toward the beginning. In other words, the cursor is
  83825. ** configured to use Prev, not Next.
  83826. **
  83827. ** If the cursor P1 was opened using the OPFLAG_SEEKEQ flag, then this
  83828. ** opcode will either land on a record that exactly matches the key, or
  83829. ** else it will cause a jump to P2. When the cursor is OPFLAG_SEEKEQ,
  83830. ** this opcode must be followed by an IdxLE opcode with the same arguments.
  83831. ** The IdxGE opcode will be skipped if this opcode succeeds, but the
  83832. ** IdxGE opcode will be used on subsequent loop iterations. The
  83833. ** OPFLAG_SEEKEQ flags is a hint to the btree layer to say that this
  83834. ** is an equality search.
  83835. **
  83836. ** See also: Found, NotFound, SeekGt, SeekGe, SeekLt
  83837. */
  83838. case OP_SeekLT: /* jump, in3, group */
  83839. case OP_SeekLE: /* jump, in3, group */
  83840. case OP_SeekGE: /* jump, in3, group */
  83841. case OP_SeekGT: { /* jump, in3, group */
  83842. int res; /* Comparison result */
  83843. int oc; /* Opcode */
  83844. VdbeCursor *pC; /* The cursor to seek */
  83845. UnpackedRecord r; /* The key to seek for */
  83846. int nField; /* Number of columns or fields in the key */
  83847. i64 iKey; /* The rowid we are to seek to */
  83848. int eqOnly; /* Only interested in == results */
  83849. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  83850. assert( pOp->p2!=0 );
  83851. pC = p->apCsr[pOp->p1];
  83852. assert( pC!=0 );
  83853. assert( pC->eCurType==CURTYPE_BTREE );
  83854. assert( OP_SeekLE == OP_SeekLT+1 );
  83855. assert( OP_SeekGE == OP_SeekLT+2 );
  83856. assert( OP_SeekGT == OP_SeekLT+3 );
  83857. assert( pC->isOrdered );
  83858. assert( pC->uc.pCursor!=0 );
  83859. oc = pOp->opcode;
  83860. eqOnly = 0;
  83861. pC->nullRow = 0;
  83862. #ifdef SQLITE_DEBUG
  83863. pC->seekOp = pOp->opcode;
  83864. #endif
  83865. pC->deferredMoveto = 0;
  83866. pC->cacheStatus = CACHE_STALE;
  83867. if( pC->isTable ){
  83868. u16 flags3, newType;
  83869. /* The OPFLAG_SEEKEQ/BTREE_SEEK_EQ flag is only set on index cursors */
  83870. assert( sqlite3BtreeCursorHasHint(pC->uc.pCursor, BTREE_SEEK_EQ)==0
  83871. || CORRUPT_DB );
  83872. /* The input value in P3 might be of any type: integer, real, string,
  83873. ** blob, or NULL. But it needs to be an integer before we can do
  83874. ** the seek, so convert it. */
  83875. pIn3 = &aMem[pOp->p3];
  83876. flags3 = pIn3->flags;
  83877. if( (flags3 & (MEM_Int|MEM_Real|MEM_IntReal|MEM_Str))==MEM_Str ){
  83878. applyNumericAffinity(pIn3, 0);
  83879. }
  83880. iKey = sqlite3VdbeIntValue(pIn3); /* Get the integer key value */
  83881. newType = pIn3->flags; /* Record the type after applying numeric affinity */
  83882. pIn3->flags = flags3; /* But convert the type back to its original */
  83883. /* If the P3 value could not be converted into an integer without
  83884. ** loss of information, then special processing is required... */
  83885. if( (newType & (MEM_Int|MEM_IntReal))==0 ){
  83886. if( (newType & MEM_Real)==0 ){
  83887. if( (newType & MEM_Null) || oc>=OP_SeekGE ){
  83888. VdbeBranchTaken(1,2);
  83889. goto jump_to_p2;
  83890. }else{
  83891. rc = sqlite3BtreeLast(pC->uc.pCursor, &res);
  83892. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  83893. goto seek_not_found;
  83894. }
  83895. }else
  83896. /* If the approximation iKey is larger than the actual real search
  83897. ** term, substitute >= for > and < for <=. e.g. if the search term
  83898. ** is 4.9 and the integer approximation 5:
  83899. **
  83900. ** (x > 4.9) -> (x >= 5)
  83901. ** (x <= 4.9) -> (x < 5)
  83902. */
  83903. if( pIn3->u.r<(double)iKey ){
  83904. assert( OP_SeekGE==(OP_SeekGT-1) );
  83905. assert( OP_SeekLT==(OP_SeekLE-1) );
  83906. assert( (OP_SeekLE & 0x0001)==(OP_SeekGT & 0x0001) );
  83907. if( (oc & 0x0001)==(OP_SeekGT & 0x0001) ) oc--;
  83908. }
  83909. /* If the approximation iKey is smaller than the actual real search
  83910. ** term, substitute <= for < and > for >=. */
  83911. else if( pIn3->u.r>(double)iKey ){
  83912. assert( OP_SeekLE==(OP_SeekLT+1) );
  83913. assert( OP_SeekGT==(OP_SeekGE+1) );
  83914. assert( (OP_SeekLT & 0x0001)==(OP_SeekGE & 0x0001) );
  83915. if( (oc & 0x0001)==(OP_SeekLT & 0x0001) ) oc++;
  83916. }
  83917. }
  83918. rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, 0, (u64)iKey, 0, &res);
  83919. pC->movetoTarget = iKey; /* Used by OP_Delete */
  83920. if( rc!=SQLITE_OK ){
  83921. goto abort_due_to_error;
  83922. }
  83923. }else{
  83924. /* For a cursor with the OPFLAG_SEEKEQ/BTREE_SEEK_EQ hint, only the
  83925. ** OP_SeekGE and OP_SeekLE opcodes are allowed, and these must be
  83926. ** immediately followed by an OP_IdxGT or OP_IdxLT opcode, respectively,
  83927. ** with the same key.
  83928. */
  83929. if( sqlite3BtreeCursorHasHint(pC->uc.pCursor, BTREE_SEEK_EQ) ){
  83930. eqOnly = 1;
  83931. assert( pOp->opcode==OP_SeekGE || pOp->opcode==OP_SeekLE );
  83932. assert( pOp[1].opcode==OP_IdxLT || pOp[1].opcode==OP_IdxGT );
  83933. assert( pOp->opcode==OP_SeekGE || pOp[1].opcode==OP_IdxLT );
  83934. assert( pOp->opcode==OP_SeekLE || pOp[1].opcode==OP_IdxGT );
  83935. assert( pOp[1].p1==pOp[0].p1 );
  83936. assert( pOp[1].p2==pOp[0].p2 );
  83937. assert( pOp[1].p3==pOp[0].p3 );
  83938. assert( pOp[1].p4.i==pOp[0].p4.i );
  83939. }
  83940. nField = pOp->p4.i;
  83941. assert( pOp->p4type==P4_INT32 );
  83942. assert( nField>0 );
  83943. r.pKeyInfo = pC->pKeyInfo;
  83944. r.nField = (u16)nField;
  83945. /* The next line of code computes as follows, only faster:
  83946. ** if( oc==OP_SeekGT || oc==OP_SeekLE ){
  83947. ** r.default_rc = -1;
  83948. ** }else{
  83949. ** r.default_rc = +1;
  83950. ** }
  83951. */
  83952. r.default_rc = ((1 & (oc - OP_SeekLT)) ? -1 : +1);
  83953. assert( oc!=OP_SeekGT || r.default_rc==-1 );
  83954. assert( oc!=OP_SeekLE || r.default_rc==-1 );
  83955. assert( oc!=OP_SeekGE || r.default_rc==+1 );
  83956. assert( oc!=OP_SeekLT || r.default_rc==+1 );
  83957. r.aMem = &aMem[pOp->p3];
  83958. #ifdef SQLITE_DEBUG
  83959. { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
  83960. #endif
  83961. r.eqSeen = 0;
  83962. rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, &r, 0, 0, &res);
  83963. if( rc!=SQLITE_OK ){
  83964. goto abort_due_to_error;
  83965. }
  83966. if( eqOnly && r.eqSeen==0 ){
  83967. assert( res!=0 );
  83968. goto seek_not_found;
  83969. }
  83970. }
  83971. #ifdef SQLITE_TEST
  83972. sqlite3_search_count++;
  83973. #endif
  83974. if( oc>=OP_SeekGE ){ assert( oc==OP_SeekGE || oc==OP_SeekGT );
  83975. if( res<0 || (res==0 && oc==OP_SeekGT) ){
  83976. res = 0;
  83977. rc = sqlite3BtreeNext(pC->uc.pCursor, 0);
  83978. if( rc!=SQLITE_OK ){
  83979. if( rc==SQLITE_DONE ){
  83980. rc = SQLITE_OK;
  83981. res = 1;
  83982. }else{
  83983. goto abort_due_to_error;
  83984. }
  83985. }
  83986. }else{
  83987. res = 0;
  83988. }
  83989. }else{
  83990. assert( oc==OP_SeekLT || oc==OP_SeekLE );
  83991. if( res>0 || (res==0 && oc==OP_SeekLT) ){
  83992. res = 0;
  83993. rc = sqlite3BtreePrevious(pC->uc.pCursor, 0);
  83994. if( rc!=SQLITE_OK ){
  83995. if( rc==SQLITE_DONE ){
  83996. rc = SQLITE_OK;
  83997. res = 1;
  83998. }else{
  83999. goto abort_due_to_error;
  84000. }
  84001. }
  84002. }else{
  84003. /* res might be negative because the table is empty. Check to
  84004. ** see if this is the case.
  84005. */
  84006. res = sqlite3BtreeEof(pC->uc.pCursor);
  84007. }
  84008. }
  84009. seek_not_found:
  84010. assert( pOp->p2>0 );
  84011. VdbeBranchTaken(res!=0,2);
  84012. if( res ){
  84013. goto jump_to_p2;
  84014. }else if( eqOnly ){
  84015. assert( pOp[1].opcode==OP_IdxLT || pOp[1].opcode==OP_IdxGT );
  84016. pOp++; /* Skip the OP_IdxLt or OP_IdxGT that follows */
  84017. }
  84018. break;
  84019. }
  84020. /* Opcode: SeekHit P1 P2 * * *
  84021. ** Synopsis: seekHit=P2
  84022. **
  84023. ** Set the seekHit flag on cursor P1 to the value in P2.
  84024. * The seekHit flag is used by the IfNoHope opcode.
  84025. **
  84026. ** P1 must be a valid b-tree cursor. P2 must be a boolean value,
  84027. ** either 0 or 1.
  84028. */
  84029. case OP_SeekHit: {
  84030. VdbeCursor *pC;
  84031. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  84032. pC = p->apCsr[pOp->p1];
  84033. assert( pC!=0 );
  84034. assert( pOp->p2==0 || pOp->p2==1 );
  84035. pC->seekHit = pOp->p2 & 1;
  84036. break;
  84037. }
  84038. /* Opcode: IfNotOpen P1 P2 * * *
  84039. ** Synopsis: if( !csr[P1] ) goto P2
  84040. **
  84041. ** If cursor P1 is not open, jump to instruction P2. Otherwise, fall through.
  84042. */
  84043. case OP_IfNotOpen: { /* jump */
  84044. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  84045. VdbeBranchTaken(p->apCsr[pOp->p1]==0, 2);
  84046. if( !p->apCsr[pOp->p1] ){
  84047. goto jump_to_p2_and_check_for_interrupt;
  84048. }
  84049. break;
  84050. }
  84051. /* Opcode: Found P1 P2 P3 P4 *
  84052. ** Synopsis: key=r[P3@P4]
  84053. **
  84054. ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
  84055. ** P4>0 then register P3 is the first of P4 registers that form an unpacked
  84056. ** record.
  84057. **
  84058. ** Cursor P1 is on an index btree. If the record identified by P3 and P4
  84059. ** is a prefix of any entry in P1 then a jump is made to P2 and
  84060. ** P1 is left pointing at the matching entry.
  84061. **
  84062. ** This operation leaves the cursor in a state where it can be
  84063. ** advanced in the forward direction. The Next instruction will work,
  84064. ** but not the Prev instruction.
  84065. **
  84066. ** See also: NotFound, NoConflict, NotExists. SeekGe
  84067. */
  84068. /* Opcode: NotFound P1 P2 P3 P4 *
  84069. ** Synopsis: key=r[P3@P4]
  84070. **
  84071. ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
  84072. ** P4>0 then register P3 is the first of P4 registers that form an unpacked
  84073. ** record.
  84074. **
  84075. ** Cursor P1 is on an index btree. If the record identified by P3 and P4
  84076. ** is not the prefix of any entry in P1 then a jump is made to P2. If P1
  84077. ** does contain an entry whose prefix matches the P3/P4 record then control
  84078. ** falls through to the next instruction and P1 is left pointing at the
  84079. ** matching entry.
  84080. **
  84081. ** This operation leaves the cursor in a state where it cannot be
  84082. ** advanced in either direction. In other words, the Next and Prev
  84083. ** opcodes do not work after this operation.
  84084. **
  84085. ** See also: Found, NotExists, NoConflict, IfNoHope
  84086. */
  84087. /* Opcode: IfNoHope P1 P2 P3 P4 *
  84088. ** Synopsis: key=r[P3@P4]
  84089. **
  84090. ** Register P3 is the first of P4 registers that form an unpacked
  84091. ** record.
  84092. **
  84093. ** Cursor P1 is on an index btree. If the seekHit flag is set on P1, then
  84094. ** this opcode is a no-op. But if the seekHit flag of P1 is clear, then
  84095. ** check to see if there is any entry in P1 that matches the
  84096. ** prefix identified by P3 and P4. If no entry matches the prefix,
  84097. ** jump to P2. Otherwise fall through.
  84098. **
  84099. ** This opcode behaves like OP_NotFound if the seekHit
  84100. ** flag is clear and it behaves like OP_Noop if the seekHit flag is set.
  84101. **
  84102. ** This opcode is used in IN clause processing for a multi-column key.
  84103. ** If an IN clause is attached to an element of the key other than the
  84104. ** left-most element, and if there are no matches on the most recent
  84105. ** seek over the whole key, then it might be that one of the key element
  84106. ** to the left is prohibiting a match, and hence there is "no hope" of
  84107. ** any match regardless of how many IN clause elements are checked.
  84108. ** In such a case, we abandon the IN clause search early, using this
  84109. ** opcode. The opcode name comes from the fact that the
  84110. ** jump is taken if there is "no hope" of achieving a match.
  84111. **
  84112. ** See also: NotFound, SeekHit
  84113. */
  84114. /* Opcode: NoConflict P1 P2 P3 P4 *
  84115. ** Synopsis: key=r[P3@P4]
  84116. **
  84117. ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
  84118. ** P4>0 then register P3 is the first of P4 registers that form an unpacked
  84119. ** record.
  84120. **
  84121. ** Cursor P1 is on an index btree. If the record identified by P3 and P4
  84122. ** contains any NULL value, jump immediately to P2. If all terms of the
  84123. ** record are not-NULL then a check is done to determine if any row in the
  84124. ** P1 index btree has a matching key prefix. If there are no matches, jump
  84125. ** immediately to P2. If there is a match, fall through and leave the P1
  84126. ** cursor pointing to the matching row.
  84127. **
  84128. ** This opcode is similar to OP_NotFound with the exceptions that the
  84129. ** branch is always taken if any part of the search key input is NULL.
  84130. **
  84131. ** This operation leaves the cursor in a state where it cannot be
  84132. ** advanced in either direction. In other words, the Next and Prev
  84133. ** opcodes do not work after this operation.
  84134. **
  84135. ** See also: NotFound, Found, NotExists
  84136. */
  84137. case OP_IfNoHope: { /* jump, in3 */
  84138. VdbeCursor *pC;
  84139. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  84140. pC = p->apCsr[pOp->p1];
  84141. assert( pC!=0 );
  84142. if( pC->seekHit ) break;
  84143. /* Fall through into OP_NotFound */
  84144. }
  84145. case OP_NoConflict: /* jump, in3 */
  84146. case OP_NotFound: /* jump, in3 */
  84147. case OP_Found: { /* jump, in3 */
  84148. int alreadyExists;
  84149. int takeJump;
  84150. int ii;
  84151. VdbeCursor *pC;
  84152. int res;
  84153. UnpackedRecord *pFree;
  84154. UnpackedRecord *pIdxKey;
  84155. UnpackedRecord r;
  84156. #ifdef SQLITE_TEST
  84157. if( pOp->opcode!=OP_NoConflict ) sqlite3_found_count++;
  84158. #endif
  84159. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  84160. assert( pOp->p4type==P4_INT32 );
  84161. pC = p->apCsr[pOp->p1];
  84162. assert( pC!=0 );
  84163. #ifdef SQLITE_DEBUG
  84164. pC->seekOp = pOp->opcode;
  84165. #endif
  84166. pIn3 = &aMem[pOp->p3];
  84167. assert( pC->eCurType==CURTYPE_BTREE );
  84168. assert( pC->uc.pCursor!=0 );
  84169. assert( pC->isTable==0 );
  84170. if( pOp->p4.i>0 ){
  84171. r.pKeyInfo = pC->pKeyInfo;
  84172. r.nField = (u16)pOp->p4.i;
  84173. r.aMem = pIn3;
  84174. #ifdef SQLITE_DEBUG
  84175. for(ii=0; ii<r.nField; ii++){
  84176. assert( memIsValid(&r.aMem[ii]) );
  84177. assert( (r.aMem[ii].flags & MEM_Zero)==0 || r.aMem[ii].n==0 );
  84178. if( ii ) REGISTER_TRACE(pOp->p3+ii, &r.aMem[ii]);
  84179. }
  84180. #endif
  84181. pIdxKey = &r;
  84182. pFree = 0;
  84183. }else{
  84184. assert( pIn3->flags & MEM_Blob );
  84185. rc = ExpandBlob(pIn3);
  84186. assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
  84187. if( rc ) goto no_mem;
  84188. pFree = pIdxKey = sqlite3VdbeAllocUnpackedRecord(pC->pKeyInfo);
  84189. if( pIdxKey==0 ) goto no_mem;
  84190. sqlite3VdbeRecordUnpack(pC->pKeyInfo, pIn3->n, pIn3->z, pIdxKey);
  84191. }
  84192. pIdxKey->default_rc = 0;
  84193. takeJump = 0;
  84194. if( pOp->opcode==OP_NoConflict ){
  84195. /* For the OP_NoConflict opcode, take the jump if any of the
  84196. ** input fields are NULL, since any key with a NULL will not
  84197. ** conflict */
  84198. for(ii=0; ii<pIdxKey->nField; ii++){
  84199. if( pIdxKey->aMem[ii].flags & MEM_Null ){
  84200. takeJump = 1;
  84201. break;
  84202. }
  84203. }
  84204. }
  84205. rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, pIdxKey, 0, 0, &res);
  84206. if( pFree ) sqlite3DbFreeNN(db, pFree);
  84207. if( rc!=SQLITE_OK ){
  84208. goto abort_due_to_error;
  84209. }
  84210. pC->seekResult = res;
  84211. alreadyExists = (res==0);
  84212. pC->nullRow = 1-alreadyExists;
  84213. pC->deferredMoveto = 0;
  84214. pC->cacheStatus = CACHE_STALE;
  84215. if( pOp->opcode==OP_Found ){
  84216. VdbeBranchTaken(alreadyExists!=0,2);
  84217. if( alreadyExists ) goto jump_to_p2;
  84218. }else{
  84219. VdbeBranchTaken(takeJump||alreadyExists==0,2);
  84220. if( takeJump || !alreadyExists ) goto jump_to_p2;
  84221. }
  84222. break;
  84223. }
  84224. /* Opcode: SeekRowid P1 P2 P3 * *
  84225. ** Synopsis: intkey=r[P3]
  84226. **
  84227. ** P1 is the index of a cursor open on an SQL table btree (with integer
  84228. ** keys). If register P3 does not contain an integer or if P1 does not
  84229. ** contain a record with rowid P3 then jump immediately to P2.
  84230. ** Or, if P2 is 0, raise an SQLITE_CORRUPT error. If P1 does contain
  84231. ** a record with rowid P3 then
  84232. ** leave the cursor pointing at that record and fall through to the next
  84233. ** instruction.
  84234. **
  84235. ** The OP_NotExists opcode performs the same operation, but with OP_NotExists
  84236. ** the P3 register must be guaranteed to contain an integer value. With this
  84237. ** opcode, register P3 might not contain an integer.
  84238. **
  84239. ** The OP_NotFound opcode performs the same operation on index btrees
  84240. ** (with arbitrary multi-value keys).
  84241. **
  84242. ** This opcode leaves the cursor in a state where it cannot be advanced
  84243. ** in either direction. In other words, the Next and Prev opcodes will
  84244. ** not work following this opcode.
  84245. **
  84246. ** See also: Found, NotFound, NoConflict, SeekRowid
  84247. */
  84248. /* Opcode: NotExists P1 P2 P3 * *
  84249. ** Synopsis: intkey=r[P3]
  84250. **
  84251. ** P1 is the index of a cursor open on an SQL table btree (with integer
  84252. ** keys). P3 is an integer rowid. If P1 does not contain a record with
  84253. ** rowid P3 then jump immediately to P2. Or, if P2 is 0, raise an
  84254. ** SQLITE_CORRUPT error. If P1 does contain a record with rowid P3 then
  84255. ** leave the cursor pointing at that record and fall through to the next
  84256. ** instruction.
  84257. **
  84258. ** The OP_SeekRowid opcode performs the same operation but also allows the
  84259. ** P3 register to contain a non-integer value, in which case the jump is
  84260. ** always taken. This opcode requires that P3 always contain an integer.
  84261. **
  84262. ** The OP_NotFound opcode performs the same operation on index btrees
  84263. ** (with arbitrary multi-value keys).
  84264. **
  84265. ** This opcode leaves the cursor in a state where it cannot be advanced
  84266. ** in either direction. In other words, the Next and Prev opcodes will
  84267. ** not work following this opcode.
  84268. **
  84269. ** See also: Found, NotFound, NoConflict, SeekRowid
  84270. */
  84271. case OP_SeekRowid: { /* jump, in3 */
  84272. VdbeCursor *pC;
  84273. BtCursor *pCrsr;
  84274. int res;
  84275. u64 iKey;
  84276. pIn3 = &aMem[pOp->p3];
  84277. testcase( pIn3->flags & MEM_Int );
  84278. testcase( pIn3->flags & MEM_IntReal );
  84279. testcase( pIn3->flags & MEM_Real );
  84280. testcase( (pIn3->flags & (MEM_Str|MEM_Int))==MEM_Str );
  84281. if( (pIn3->flags & (MEM_Int|MEM_IntReal))==0 ){
  84282. /* If pIn3->u.i does not contain an integer, compute iKey as the
  84283. ** integer value of pIn3. Jump to P2 if pIn3 cannot be converted
  84284. ** into an integer without loss of information. Take care to avoid
  84285. ** changing the datatype of pIn3, however, as it is used by other
  84286. ** parts of the prepared statement. */
  84287. Mem x = pIn3[0];
  84288. applyAffinity(&x, SQLITE_AFF_NUMERIC, encoding);
  84289. if( (x.flags & MEM_Int)==0 ) goto jump_to_p2;
  84290. iKey = x.u.i;
  84291. goto notExistsWithKey;
  84292. }
  84293. /* Fall through into OP_NotExists */
  84294. case OP_NotExists: /* jump, in3 */
  84295. pIn3 = &aMem[pOp->p3];
  84296. assert( (pIn3->flags & MEM_Int)!=0 || pOp->opcode==OP_SeekRowid );
  84297. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  84298. iKey = pIn3->u.i;
  84299. notExistsWithKey:
  84300. pC = p->apCsr[pOp->p1];
  84301. assert( pC!=0 );
  84302. #ifdef SQLITE_DEBUG
  84303. if( pOp->opcode==OP_SeekRowid ) pC->seekOp = OP_SeekRowid;
  84304. #endif
  84305. assert( pC->isTable );
  84306. assert( pC->eCurType==CURTYPE_BTREE );
  84307. pCrsr = pC->uc.pCursor;
  84308. assert( pCrsr!=0 );
  84309. res = 0;
  84310. rc = sqlite3BtreeMovetoUnpacked(pCrsr, 0, iKey, 0, &res);
  84311. assert( rc==SQLITE_OK || res==0 );
  84312. pC->movetoTarget = iKey; /* Used by OP_Delete */
  84313. pC->nullRow = 0;
  84314. pC->cacheStatus = CACHE_STALE;
  84315. pC->deferredMoveto = 0;
  84316. VdbeBranchTaken(res!=0,2);
  84317. pC->seekResult = res;
  84318. if( res!=0 ){
  84319. assert( rc==SQLITE_OK );
  84320. if( pOp->p2==0 ){
  84321. rc = SQLITE_CORRUPT_BKPT;
  84322. }else{
  84323. goto jump_to_p2;
  84324. }
  84325. }
  84326. if( rc ) goto abort_due_to_error;
  84327. break;
  84328. }
  84329. /* Opcode: Sequence P1 P2 * * *
  84330. ** Synopsis: r[P2]=cursor[P1].ctr++
  84331. **
  84332. ** Find the next available sequence number for cursor P1.
  84333. ** Write the sequence number into register P2.
  84334. ** The sequence number on the cursor is incremented after this
  84335. ** instruction.
  84336. */
  84337. case OP_Sequence: { /* out2 */
  84338. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  84339. assert( p->apCsr[pOp->p1]!=0 );
  84340. assert( p->apCsr[pOp->p1]->eCurType!=CURTYPE_VTAB );
  84341. pOut = out2Prerelease(p, pOp);
  84342. pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
  84343. break;
  84344. }
  84345. /* Opcode: NewRowid P1 P2 P3 * *
  84346. ** Synopsis: r[P2]=rowid
  84347. **
  84348. ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
  84349. ** The record number is not previously used as a key in the database
  84350. ** table that cursor P1 points to. The new record number is written
  84351. ** written to register P2.
  84352. **
  84353. ** If P3>0 then P3 is a register in the root frame of this VDBE that holds
  84354. ** the largest previously generated record number. No new record numbers are
  84355. ** allowed to be less than this value. When this value reaches its maximum,
  84356. ** an SQLITE_FULL error is generated. The P3 register is updated with the '
  84357. ** generated record number. This P3 mechanism is used to help implement the
  84358. ** AUTOINCREMENT feature.
  84359. */
  84360. case OP_NewRowid: { /* out2 */
  84361. i64 v; /* The new rowid */
  84362. VdbeCursor *pC; /* Cursor of table to get the new rowid */
  84363. int res; /* Result of an sqlite3BtreeLast() */
  84364. int cnt; /* Counter to limit the number of searches */
  84365. Mem *pMem; /* Register holding largest rowid for AUTOINCREMENT */
  84366. VdbeFrame *pFrame; /* Root frame of VDBE */
  84367. v = 0;
  84368. res = 0;
  84369. pOut = out2Prerelease(p, pOp);
  84370. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  84371. pC = p->apCsr[pOp->p1];
  84372. assert( pC!=0 );
  84373. assert( pC->isTable );
  84374. assert( pC->eCurType==CURTYPE_BTREE );
  84375. assert( pC->uc.pCursor!=0 );
  84376. {
  84377. /* The next rowid or record number (different terms for the same
  84378. ** thing) is obtained in a two-step algorithm.
  84379. **
  84380. ** First we attempt to find the largest existing rowid and add one
  84381. ** to that. But if the largest existing rowid is already the maximum
  84382. ** positive integer, we have to fall through to the second
  84383. ** probabilistic algorithm
  84384. **
  84385. ** The second algorithm is to select a rowid at random and see if
  84386. ** it already exists in the table. If it does not exist, we have
  84387. ** succeeded. If the random rowid does exist, we select a new one
  84388. ** and try again, up to 100 times.
  84389. */
  84390. assert( pC->isTable );
  84391. #ifdef SQLITE_32BIT_ROWID
  84392. # define MAX_ROWID 0x7fffffff
  84393. #else
  84394. /* Some compilers complain about constants of the form 0x7fffffffffffffff.
  84395. ** Others complain about 0x7ffffffffffffffffLL. The following macro seems
  84396. ** to provide the constant while making all compilers happy.
  84397. */
  84398. # define MAX_ROWID (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
  84399. #endif
  84400. if( !pC->useRandomRowid ){
  84401. rc = sqlite3BtreeLast(pC->uc.pCursor, &res);
  84402. if( rc!=SQLITE_OK ){
  84403. goto abort_due_to_error;
  84404. }
  84405. if( res ){
  84406. v = 1; /* IMP: R-61914-48074 */
  84407. }else{
  84408. assert( sqlite3BtreeCursorIsValid(pC->uc.pCursor) );
  84409. v = sqlite3BtreeIntegerKey(pC->uc.pCursor);
  84410. if( v>=MAX_ROWID ){
  84411. pC->useRandomRowid = 1;
  84412. }else{
  84413. v++; /* IMP: R-29538-34987 */
  84414. }
  84415. }
  84416. }
  84417. #ifndef SQLITE_OMIT_AUTOINCREMENT
  84418. if( pOp->p3 ){
  84419. /* Assert that P3 is a valid memory cell. */
  84420. assert( pOp->p3>0 );
  84421. if( p->pFrame ){
  84422. for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
  84423. /* Assert that P3 is a valid memory cell. */
  84424. assert( pOp->p3<=pFrame->nMem );
  84425. pMem = &pFrame->aMem[pOp->p3];
  84426. }else{
  84427. /* Assert that P3 is a valid memory cell. */
  84428. assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
  84429. pMem = &aMem[pOp->p3];
  84430. memAboutToChange(p, pMem);
  84431. }
  84432. assert( memIsValid(pMem) );
  84433. REGISTER_TRACE(pOp->p3, pMem);
  84434. sqlite3VdbeMemIntegerify(pMem);
  84435. assert( (pMem->flags & MEM_Int)!=0 ); /* mem(P3) holds an integer */
  84436. if( pMem->u.i==MAX_ROWID || pC->useRandomRowid ){
  84437. rc = SQLITE_FULL; /* IMP: R-17817-00630 */
  84438. goto abort_due_to_error;
  84439. }
  84440. if( v<pMem->u.i+1 ){
  84441. v = pMem->u.i + 1;
  84442. }
  84443. pMem->u.i = v;
  84444. }
  84445. #endif
  84446. if( pC->useRandomRowid ){
  84447. /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
  84448. ** largest possible integer (9223372036854775807) then the database
  84449. ** engine starts picking positive candidate ROWIDs at random until
  84450. ** it finds one that is not previously used. */
  84451. assert( pOp->p3==0 ); /* We cannot be in random rowid mode if this is
  84452. ** an AUTOINCREMENT table. */
  84453. cnt = 0;
  84454. do{
  84455. sqlite3_randomness(sizeof(v), &v);
  84456. v &= (MAX_ROWID>>1); v++; /* Ensure that v is greater than zero */
  84457. }while( ((rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, 0, (u64)v,
  84458. 0, &res))==SQLITE_OK)
  84459. && (res==0)
  84460. && (++cnt<100));
  84461. if( rc ) goto abort_due_to_error;
  84462. if( res==0 ){
  84463. rc = SQLITE_FULL; /* IMP: R-38219-53002 */
  84464. goto abort_due_to_error;
  84465. }
  84466. assert( v>0 ); /* EV: R-40812-03570 */
  84467. }
  84468. pC->deferredMoveto = 0;
  84469. pC->cacheStatus = CACHE_STALE;
  84470. }
  84471. pOut->u.i = v;
  84472. break;
  84473. }
  84474. /* Opcode: Insert P1 P2 P3 P4 P5
  84475. ** Synopsis: intkey=r[P3] data=r[P2]
  84476. **
  84477. ** Write an entry into the table of cursor P1. A new entry is
  84478. ** created if it doesn't already exist or the data for an existing
  84479. ** entry is overwritten. The data is the value MEM_Blob stored in register
  84480. ** number P2. The key is stored in register P3. The key must
  84481. ** be a MEM_Int.
  84482. **
  84483. ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
  84484. ** incremented (otherwise not). If the OPFLAG_LASTROWID flag of P5 is set,
  84485. ** then rowid is stored for subsequent return by the
  84486. ** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
  84487. **
  84488. ** If the OPFLAG_USESEEKRESULT flag of P5 is set, the implementation might
  84489. ** run faster by avoiding an unnecessary seek on cursor P1. However,
  84490. ** the OPFLAG_USESEEKRESULT flag must only be set if there have been no prior
  84491. ** seeks on the cursor or if the most recent seek used a key equal to P3.
  84492. **
  84493. ** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
  84494. ** UPDATE operation. Otherwise (if the flag is clear) then this opcode
  84495. ** is part of an INSERT operation. The difference is only important to
  84496. ** the update hook.
  84497. **
  84498. ** Parameter P4 may point to a Table structure, or may be NULL. If it is
  84499. ** not NULL, then the update-hook (sqlite3.xUpdateCallback) is invoked
  84500. ** following a successful insert.
  84501. **
  84502. ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
  84503. ** allocated, then ownership of P2 is transferred to the pseudo-cursor
  84504. ** and register P2 becomes ephemeral. If the cursor is changed, the
  84505. ** value of register P2 will then change. Make sure this does not
  84506. ** cause any problems.)
  84507. **
  84508. ** This instruction only works on tables. The equivalent instruction
  84509. ** for indices is OP_IdxInsert.
  84510. */
  84511. case OP_Insert: {
  84512. Mem *pData; /* MEM cell holding data for the record to be inserted */
  84513. Mem *pKey; /* MEM cell holding key for the record */
  84514. VdbeCursor *pC; /* Cursor to table into which insert is written */
  84515. int seekResult; /* Result of prior seek or 0 if no USESEEKRESULT flag */
  84516. const char *zDb; /* database name - used by the update hook */
  84517. Table *pTab; /* Table structure - used by update and pre-update hooks */
  84518. BtreePayload x; /* Payload to be inserted */
  84519. pData = &aMem[pOp->p2];
  84520. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  84521. assert( memIsValid(pData) );
  84522. pC = p->apCsr[pOp->p1];
  84523. assert( pC!=0 );
  84524. assert( pC->eCurType==CURTYPE_BTREE );
  84525. assert( pC->deferredMoveto==0 );
  84526. assert( pC->uc.pCursor!=0 );
  84527. assert( (pOp->p5 & OPFLAG_ISNOOP) || pC->isTable );
  84528. assert( pOp->p4type==P4_TABLE || pOp->p4type>=P4_STATIC );
  84529. REGISTER_TRACE(pOp->p2, pData);
  84530. sqlite3VdbeIncrWriteCounter(p, pC);
  84531. pKey = &aMem[pOp->p3];
  84532. assert( pKey->flags & MEM_Int );
  84533. assert( memIsValid(pKey) );
  84534. REGISTER_TRACE(pOp->p3, pKey);
  84535. x.nKey = pKey->u.i;
  84536. if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){
  84537. assert( pC->iDb>=0 );
  84538. zDb = db->aDb[pC->iDb].zDbSName;
  84539. pTab = pOp->p4.pTab;
  84540. assert( (pOp->p5 & OPFLAG_ISNOOP) || HasRowid(pTab) );
  84541. }else{
  84542. pTab = 0;
  84543. zDb = 0; /* Not needed. Silence a compiler warning. */
  84544. }
  84545. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  84546. /* Invoke the pre-update hook, if any */
  84547. if( pTab ){
  84548. if( db->xPreUpdateCallback && !(pOp->p5 & OPFLAG_ISUPDATE) ){
  84549. sqlite3VdbePreUpdateHook(p, pC, SQLITE_INSERT, zDb, pTab, x.nKey,pOp->p2);
  84550. }
  84551. if( db->xUpdateCallback==0 || pTab->aCol==0 ){
  84552. /* Prevent post-update hook from running in cases when it should not */
  84553. pTab = 0;
  84554. }
  84555. }
  84556. if( pOp->p5 & OPFLAG_ISNOOP ) break;
  84557. #endif
  84558. if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
  84559. if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = x.nKey;
  84560. assert( pData->flags & (MEM_Blob|MEM_Str) );
  84561. x.pData = pData->z;
  84562. x.nData = pData->n;
  84563. seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0);
  84564. if( pData->flags & MEM_Zero ){
  84565. x.nZero = pData->u.nZero;
  84566. }else{
  84567. x.nZero = 0;
  84568. }
  84569. x.pKey = 0;
  84570. rc = sqlite3BtreeInsert(pC->uc.pCursor, &x,
  84571. (pOp->p5 & (OPFLAG_APPEND|OPFLAG_SAVEPOSITION)), seekResult
  84572. );
  84573. pC->deferredMoveto = 0;
  84574. pC->cacheStatus = CACHE_STALE;
  84575. /* Invoke the update-hook if required. */
  84576. if( rc ) goto abort_due_to_error;
  84577. if( pTab ){
  84578. assert( db->xUpdateCallback!=0 );
  84579. assert( pTab->aCol!=0 );
  84580. db->xUpdateCallback(db->pUpdateArg,
  84581. (pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT,
  84582. zDb, pTab->zName, x.nKey);
  84583. }
  84584. break;
  84585. }
  84586. /* Opcode: Delete P1 P2 P3 P4 P5
  84587. **
  84588. ** Delete the record at which the P1 cursor is currently pointing.
  84589. **
  84590. ** If the OPFLAG_SAVEPOSITION bit of the P5 parameter is set, then
  84591. ** the cursor will be left pointing at either the next or the previous
  84592. ** record in the table. If it is left pointing at the next record, then
  84593. ** the next Next instruction will be a no-op. As a result, in this case
  84594. ** it is ok to delete a record from within a Next loop. If
  84595. ** OPFLAG_SAVEPOSITION bit of P5 is clear, then the cursor will be
  84596. ** left in an undefined state.
  84597. **
  84598. ** If the OPFLAG_AUXDELETE bit is set on P5, that indicates that this
  84599. ** delete one of several associated with deleting a table row and all its
  84600. ** associated index entries. Exactly one of those deletes is the "primary"
  84601. ** delete. The others are all on OPFLAG_FORDELETE cursors or else are
  84602. ** marked with the AUXDELETE flag.
  84603. **
  84604. ** If the OPFLAG_NCHANGE flag of P2 (NB: P2 not P5) is set, then the row
  84605. ** change count is incremented (otherwise not).
  84606. **
  84607. ** P1 must not be pseudo-table. It has to be a real table with
  84608. ** multiple rows.
  84609. **
  84610. ** If P4 is not NULL then it points to a Table object. In this case either
  84611. ** the update or pre-update hook, or both, may be invoked. The P1 cursor must
  84612. ** have been positioned using OP_NotFound prior to invoking this opcode in
  84613. ** this case. Specifically, if one is configured, the pre-update hook is
  84614. ** invoked if P4 is not NULL. The update-hook is invoked if one is configured,
  84615. ** P4 is not NULL, and the OPFLAG_NCHANGE flag is set in P2.
  84616. **
  84617. ** If the OPFLAG_ISUPDATE flag is set in P2, then P3 contains the address
  84618. ** of the memory cell that contains the value that the rowid of the row will
  84619. ** be set to by the update.
  84620. */
  84621. case OP_Delete: {
  84622. VdbeCursor *pC;
  84623. const char *zDb;
  84624. Table *pTab;
  84625. int opflags;
  84626. opflags = pOp->p2;
  84627. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  84628. pC = p->apCsr[pOp->p1];
  84629. assert( pC!=0 );
  84630. assert( pC->eCurType==CURTYPE_BTREE );
  84631. assert( pC->uc.pCursor!=0 );
  84632. assert( pC->deferredMoveto==0 );
  84633. sqlite3VdbeIncrWriteCounter(p, pC);
  84634. #ifdef SQLITE_DEBUG
  84635. if( pOp->p4type==P4_TABLE
  84636. && HasRowid(pOp->p4.pTab)
  84637. && pOp->p5==0
  84638. && sqlite3BtreeCursorIsValidNN(pC->uc.pCursor)
  84639. ){
  84640. /* If p5 is zero, the seek operation that positioned the cursor prior to
  84641. ** OP_Delete will have also set the pC->movetoTarget field to the rowid of
  84642. ** the row that is being deleted */
  84643. i64 iKey = sqlite3BtreeIntegerKey(pC->uc.pCursor);
  84644. assert( CORRUPT_DB || pC->movetoTarget==iKey );
  84645. }
  84646. #endif
  84647. /* If the update-hook or pre-update-hook will be invoked, set zDb to
  84648. ** the name of the db to pass as to it. Also set local pTab to a copy
  84649. ** of p4.pTab. Finally, if p5 is true, indicating that this cursor was
  84650. ** last moved with OP_Next or OP_Prev, not Seek or NotFound, set
  84651. ** VdbeCursor.movetoTarget to the current rowid. */
  84652. if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){
  84653. assert( pC->iDb>=0 );
  84654. assert( pOp->p4.pTab!=0 );
  84655. zDb = db->aDb[pC->iDb].zDbSName;
  84656. pTab = pOp->p4.pTab;
  84657. if( (pOp->p5 & OPFLAG_SAVEPOSITION)!=0 && pC->isTable ){
  84658. pC->movetoTarget = sqlite3BtreeIntegerKey(pC->uc.pCursor);
  84659. }
  84660. }else{
  84661. zDb = 0; /* Not needed. Silence a compiler warning. */
  84662. pTab = 0; /* Not needed. Silence a compiler warning. */
  84663. }
  84664. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  84665. /* Invoke the pre-update-hook if required. */
  84666. if( db->xPreUpdateCallback && pOp->p4.pTab ){
  84667. assert( !(opflags & OPFLAG_ISUPDATE)
  84668. || HasRowid(pTab)==0
  84669. || (aMem[pOp->p3].flags & MEM_Int)
  84670. );
  84671. sqlite3VdbePreUpdateHook(p, pC,
  84672. (opflags & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_DELETE,
  84673. zDb, pTab, pC->movetoTarget,
  84674. pOp->p3
  84675. );
  84676. }
  84677. if( opflags & OPFLAG_ISNOOP ) break;
  84678. #endif
  84679. /* Only flags that can be set are SAVEPOISTION and AUXDELETE */
  84680. assert( (pOp->p5 & ~(OPFLAG_SAVEPOSITION|OPFLAG_AUXDELETE))==0 );
  84681. assert( OPFLAG_SAVEPOSITION==BTREE_SAVEPOSITION );
  84682. assert( OPFLAG_AUXDELETE==BTREE_AUXDELETE );
  84683. #ifdef SQLITE_DEBUG
  84684. if( p->pFrame==0 ){
  84685. if( pC->isEphemeral==0
  84686. && (pOp->p5 & OPFLAG_AUXDELETE)==0
  84687. && (pC->wrFlag & OPFLAG_FORDELETE)==0
  84688. ){
  84689. nExtraDelete++;
  84690. }
  84691. if( pOp->p2 & OPFLAG_NCHANGE ){
  84692. nExtraDelete--;
  84693. }
  84694. }
  84695. #endif
  84696. rc = sqlite3BtreeDelete(pC->uc.pCursor, pOp->p5);
  84697. pC->cacheStatus = CACHE_STALE;
  84698. pC->seekResult = 0;
  84699. if( rc ) goto abort_due_to_error;
  84700. /* Invoke the update-hook if required. */
  84701. if( opflags & OPFLAG_NCHANGE ){
  84702. p->nChange++;
  84703. if( db->xUpdateCallback && HasRowid(pTab) ){
  84704. db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, pTab->zName,
  84705. pC->movetoTarget);
  84706. assert( pC->iDb>=0 );
  84707. }
  84708. }
  84709. break;
  84710. }
  84711. /* Opcode: ResetCount * * * * *
  84712. **
  84713. ** The value of the change counter is copied to the database handle
  84714. ** change counter (returned by subsequent calls to sqlite3_changes()).
  84715. ** Then the VMs internal change counter resets to 0.
  84716. ** This is used by trigger programs.
  84717. */
  84718. case OP_ResetCount: {
  84719. sqlite3VdbeSetChanges(db, p->nChange);
  84720. p->nChange = 0;
  84721. break;
  84722. }
  84723. /* Opcode: SorterCompare P1 P2 P3 P4
  84724. ** Synopsis: if key(P1)!=trim(r[P3],P4) goto P2
  84725. **
  84726. ** P1 is a sorter cursor. This instruction compares a prefix of the
  84727. ** record blob in register P3 against a prefix of the entry that
  84728. ** the sorter cursor currently points to. Only the first P4 fields
  84729. ** of r[P3] and the sorter record are compared.
  84730. **
  84731. ** If either P3 or the sorter contains a NULL in one of their significant
  84732. ** fields (not counting the P4 fields at the end which are ignored) then
  84733. ** the comparison is assumed to be equal.
  84734. **
  84735. ** Fall through to next instruction if the two records compare equal to
  84736. ** each other. Jump to P2 if they are different.
  84737. */
  84738. case OP_SorterCompare: {
  84739. VdbeCursor *pC;
  84740. int res;
  84741. int nKeyCol;
  84742. pC = p->apCsr[pOp->p1];
  84743. assert( isSorter(pC) );
  84744. assert( pOp->p4type==P4_INT32 );
  84745. pIn3 = &aMem[pOp->p3];
  84746. nKeyCol = pOp->p4.i;
  84747. res = 0;
  84748. rc = sqlite3VdbeSorterCompare(pC, pIn3, nKeyCol, &res);
  84749. VdbeBranchTaken(res!=0,2);
  84750. if( rc ) goto abort_due_to_error;
  84751. if( res ) goto jump_to_p2;
  84752. break;
  84753. };
  84754. /* Opcode: SorterData P1 P2 P3 * *
  84755. ** Synopsis: r[P2]=data
  84756. **
  84757. ** Write into register P2 the current sorter data for sorter cursor P1.
  84758. ** Then clear the column header cache on cursor P3.
  84759. **
  84760. ** This opcode is normally use to move a record out of the sorter and into
  84761. ** a register that is the source for a pseudo-table cursor created using
  84762. ** OpenPseudo. That pseudo-table cursor is the one that is identified by
  84763. ** parameter P3. Clearing the P3 column cache as part of this opcode saves
  84764. ** us from having to issue a separate NullRow instruction to clear that cache.
  84765. */
  84766. case OP_SorterData: {
  84767. VdbeCursor *pC;
  84768. pOut = &aMem[pOp->p2];
  84769. pC = p->apCsr[pOp->p1];
  84770. assert( isSorter(pC) );
  84771. rc = sqlite3VdbeSorterRowkey(pC, pOut);
  84772. assert( rc!=SQLITE_OK || (pOut->flags & MEM_Blob) );
  84773. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  84774. if( rc ) goto abort_due_to_error;
  84775. p->apCsr[pOp->p3]->cacheStatus = CACHE_STALE;
  84776. break;
  84777. }
  84778. /* Opcode: RowData P1 P2 P3 * *
  84779. ** Synopsis: r[P2]=data
  84780. **
  84781. ** Write into register P2 the complete row content for the row at
  84782. ** which cursor P1 is currently pointing.
  84783. ** There is no interpretation of the data.
  84784. ** It is just copied onto the P2 register exactly as
  84785. ** it is found in the database file.
  84786. **
  84787. ** If cursor P1 is an index, then the content is the key of the row.
  84788. ** If cursor P2 is a table, then the content extracted is the data.
  84789. **
  84790. ** If the P1 cursor must be pointing to a valid row (not a NULL row)
  84791. ** of a real table, not a pseudo-table.
  84792. **
  84793. ** If P3!=0 then this opcode is allowed to make an ephemeral pointer
  84794. ** into the database page. That means that the content of the output
  84795. ** register will be invalidated as soon as the cursor moves - including
  84796. ** moves caused by other cursors that "save" the current cursors
  84797. ** position in order that they can write to the same table. If P3==0
  84798. ** then a copy of the data is made into memory. P3!=0 is faster, but
  84799. ** P3==0 is safer.
  84800. **
  84801. ** If P3!=0 then the content of the P2 register is unsuitable for use
  84802. ** in OP_Result and any OP_Result will invalidate the P2 register content.
  84803. ** The P2 register content is invalidated by opcodes like OP_Function or
  84804. ** by any use of another cursor pointing to the same table.
  84805. */
  84806. case OP_RowData: {
  84807. VdbeCursor *pC;
  84808. BtCursor *pCrsr;
  84809. u32 n;
  84810. pOut = out2Prerelease(p, pOp);
  84811. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  84812. pC = p->apCsr[pOp->p1];
  84813. assert( pC!=0 );
  84814. assert( pC->eCurType==CURTYPE_BTREE );
  84815. assert( isSorter(pC)==0 );
  84816. assert( pC->nullRow==0 );
  84817. assert( pC->uc.pCursor!=0 );
  84818. pCrsr = pC->uc.pCursor;
  84819. /* The OP_RowData opcodes always follow OP_NotExists or
  84820. ** OP_SeekRowid or OP_Rewind/Op_Next with no intervening instructions
  84821. ** that might invalidate the cursor.
  84822. ** If this where not the case, on of the following assert()s
  84823. ** would fail. Should this ever change (because of changes in the code
  84824. ** generator) then the fix would be to insert a call to
  84825. ** sqlite3VdbeCursorMoveto().
  84826. */
  84827. assert( pC->deferredMoveto==0 );
  84828. assert( sqlite3BtreeCursorIsValid(pCrsr) );
  84829. #if 0 /* Not required due to the previous to assert() statements */
  84830. rc = sqlite3VdbeCursorMoveto(pC);
  84831. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  84832. #endif
  84833. n = sqlite3BtreePayloadSize(pCrsr);
  84834. if( n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
  84835. goto too_big;
  84836. }
  84837. testcase( n==0 );
  84838. rc = sqlite3VdbeMemFromBtreeZeroOffset(pCrsr, n, pOut);
  84839. if( rc ) goto abort_due_to_error;
  84840. if( !pOp->p3 ) Deephemeralize(pOut);
  84841. UPDATE_MAX_BLOBSIZE(pOut);
  84842. REGISTER_TRACE(pOp->p2, pOut);
  84843. break;
  84844. }
  84845. /* Opcode: Rowid P1 P2 * * *
  84846. ** Synopsis: r[P2]=rowid
  84847. **
  84848. ** Store in register P2 an integer which is the key of the table entry that
  84849. ** P1 is currently point to.
  84850. **
  84851. ** P1 can be either an ordinary table or a virtual table. There used to
  84852. ** be a separate OP_VRowid opcode for use with virtual tables, but this
  84853. ** one opcode now works for both table types.
  84854. */
  84855. case OP_Rowid: { /* out2 */
  84856. VdbeCursor *pC;
  84857. i64 v;
  84858. sqlite3_vtab *pVtab;
  84859. const sqlite3_module *pModule;
  84860. pOut = out2Prerelease(p, pOp);
  84861. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  84862. pC = p->apCsr[pOp->p1];
  84863. assert( pC!=0 );
  84864. assert( pC->eCurType!=CURTYPE_PSEUDO || pC->nullRow );
  84865. if( pC->nullRow ){
  84866. pOut->flags = MEM_Null;
  84867. break;
  84868. }else if( pC->deferredMoveto ){
  84869. v = pC->movetoTarget;
  84870. #ifndef SQLITE_OMIT_VIRTUALTABLE
  84871. }else if( pC->eCurType==CURTYPE_VTAB ){
  84872. assert( pC->uc.pVCur!=0 );
  84873. pVtab = pC->uc.pVCur->pVtab;
  84874. pModule = pVtab->pModule;
  84875. assert( pModule->xRowid );
  84876. rc = pModule->xRowid(pC->uc.pVCur, &v);
  84877. sqlite3VtabImportErrmsg(p, pVtab);
  84878. if( rc ) goto abort_due_to_error;
  84879. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  84880. }else{
  84881. assert( pC->eCurType==CURTYPE_BTREE );
  84882. assert( pC->uc.pCursor!=0 );
  84883. rc = sqlite3VdbeCursorRestore(pC);
  84884. if( rc ) goto abort_due_to_error;
  84885. if( pC->nullRow ){
  84886. pOut->flags = MEM_Null;
  84887. break;
  84888. }
  84889. v = sqlite3BtreeIntegerKey(pC->uc.pCursor);
  84890. }
  84891. pOut->u.i = v;
  84892. break;
  84893. }
  84894. /* Opcode: NullRow P1 * * * *
  84895. **
  84896. ** Move the cursor P1 to a null row. Any OP_Column operations
  84897. ** that occur while the cursor is on the null row will always
  84898. ** write a NULL.
  84899. */
  84900. case OP_NullRow: {
  84901. VdbeCursor *pC;
  84902. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  84903. pC = p->apCsr[pOp->p1];
  84904. assert( pC!=0 );
  84905. pC->nullRow = 1;
  84906. pC->cacheStatus = CACHE_STALE;
  84907. if( pC->eCurType==CURTYPE_BTREE ){
  84908. assert( pC->uc.pCursor!=0 );
  84909. sqlite3BtreeClearCursor(pC->uc.pCursor);
  84910. }
  84911. #ifdef SQLITE_DEBUG
  84912. if( pC->seekOp==0 ) pC->seekOp = OP_NullRow;
  84913. #endif
  84914. break;
  84915. }
  84916. /* Opcode: SeekEnd P1 * * * *
  84917. **
  84918. ** Position cursor P1 at the end of the btree for the purpose of
  84919. ** appending a new entry onto the btree.
  84920. **
  84921. ** It is assumed that the cursor is used only for appending and so
  84922. ** if the cursor is valid, then the cursor must already be pointing
  84923. ** at the end of the btree and so no changes are made to
  84924. ** the cursor.
  84925. */
  84926. /* Opcode: Last P1 P2 * * *
  84927. **
  84928. ** The next use of the Rowid or Column or Prev instruction for P1
  84929. ** will refer to the last entry in the database table or index.
  84930. ** If the table or index is empty and P2>0, then jump immediately to P2.
  84931. ** If P2 is 0 or if the table or index is not empty, fall through
  84932. ** to the following instruction.
  84933. **
  84934. ** This opcode leaves the cursor configured to move in reverse order,
  84935. ** from the end toward the beginning. In other words, the cursor is
  84936. ** configured to use Prev, not Next.
  84937. */
  84938. case OP_SeekEnd:
  84939. case OP_Last: { /* jump */
  84940. VdbeCursor *pC;
  84941. BtCursor *pCrsr;
  84942. int res;
  84943. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  84944. pC = p->apCsr[pOp->p1];
  84945. assert( pC!=0 );
  84946. assert( pC->eCurType==CURTYPE_BTREE );
  84947. pCrsr = pC->uc.pCursor;
  84948. res = 0;
  84949. assert( pCrsr!=0 );
  84950. #ifdef SQLITE_DEBUG
  84951. pC->seekOp = pOp->opcode;
  84952. #endif
  84953. if( pOp->opcode==OP_SeekEnd ){
  84954. assert( pOp->p2==0 );
  84955. pC->seekResult = -1;
  84956. if( sqlite3BtreeCursorIsValidNN(pCrsr) ){
  84957. break;
  84958. }
  84959. }
  84960. rc = sqlite3BtreeLast(pCrsr, &res);
  84961. pC->nullRow = (u8)res;
  84962. pC->deferredMoveto = 0;
  84963. pC->cacheStatus = CACHE_STALE;
  84964. if( rc ) goto abort_due_to_error;
  84965. if( pOp->p2>0 ){
  84966. VdbeBranchTaken(res!=0,2);
  84967. if( res ) goto jump_to_p2;
  84968. }
  84969. break;
  84970. }
  84971. /* Opcode: IfSmaller P1 P2 P3 * *
  84972. **
  84973. ** Estimate the number of rows in the table P1. Jump to P2 if that
  84974. ** estimate is less than approximately 2**(0.1*P3).
  84975. */
  84976. case OP_IfSmaller: { /* jump */
  84977. VdbeCursor *pC;
  84978. BtCursor *pCrsr;
  84979. int res;
  84980. i64 sz;
  84981. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  84982. pC = p->apCsr[pOp->p1];
  84983. assert( pC!=0 );
  84984. pCrsr = pC->uc.pCursor;
  84985. assert( pCrsr );
  84986. rc = sqlite3BtreeFirst(pCrsr, &res);
  84987. if( rc ) goto abort_due_to_error;
  84988. if( res==0 ){
  84989. sz = sqlite3BtreeRowCountEst(pCrsr);
  84990. if( ALWAYS(sz>=0) && sqlite3LogEst((u64)sz)<pOp->p3 ) res = 1;
  84991. }
  84992. VdbeBranchTaken(res!=0,2);
  84993. if( res ) goto jump_to_p2;
  84994. break;
  84995. }
  84996. /* Opcode: SorterSort P1 P2 * * *
  84997. **
  84998. ** After all records have been inserted into the Sorter object
  84999. ** identified by P1, invoke this opcode to actually do the sorting.
  85000. ** Jump to P2 if there are no records to be sorted.
  85001. **
  85002. ** This opcode is an alias for OP_Sort and OP_Rewind that is used
  85003. ** for Sorter objects.
  85004. */
  85005. /* Opcode: Sort P1 P2 * * *
  85006. **
  85007. ** This opcode does exactly the same thing as OP_Rewind except that
  85008. ** it increments an undocumented global variable used for testing.
  85009. **
  85010. ** Sorting is accomplished by writing records into a sorting index,
  85011. ** then rewinding that index and playing it back from beginning to
  85012. ** end. We use the OP_Sort opcode instead of OP_Rewind to do the
  85013. ** rewinding so that the global variable will be incremented and
  85014. ** regression tests can determine whether or not the optimizer is
  85015. ** correctly optimizing out sorts.
  85016. */
  85017. case OP_SorterSort: /* jump */
  85018. case OP_Sort: { /* jump */
  85019. #ifdef SQLITE_TEST
  85020. sqlite3_sort_count++;
  85021. sqlite3_search_count--;
  85022. #endif
  85023. p->aCounter[SQLITE_STMTSTATUS_SORT]++;
  85024. /* Fall through into OP_Rewind */
  85025. }
  85026. /* Opcode: Rewind P1 P2 * * *
  85027. **
  85028. ** The next use of the Rowid or Column or Next instruction for P1
  85029. ** will refer to the first entry in the database table or index.
  85030. ** If the table or index is empty, jump immediately to P2.
  85031. ** If the table or index is not empty, fall through to the following
  85032. ** instruction.
  85033. **
  85034. ** This opcode leaves the cursor configured to move in forward order,
  85035. ** from the beginning toward the end. In other words, the cursor is
  85036. ** configured to use Next, not Prev.
  85037. */
  85038. case OP_Rewind: { /* jump */
  85039. VdbeCursor *pC;
  85040. BtCursor *pCrsr;
  85041. int res;
  85042. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  85043. assert( pOp->p5==0 );
  85044. pC = p->apCsr[pOp->p1];
  85045. assert( pC!=0 );
  85046. assert( isSorter(pC)==(pOp->opcode==OP_SorterSort) );
  85047. res = 1;
  85048. #ifdef SQLITE_DEBUG
  85049. pC->seekOp = OP_Rewind;
  85050. #endif
  85051. if( isSorter(pC) ){
  85052. rc = sqlite3VdbeSorterRewind(pC, &res);
  85053. }else{
  85054. assert( pC->eCurType==CURTYPE_BTREE );
  85055. pCrsr = pC->uc.pCursor;
  85056. assert( pCrsr );
  85057. rc = sqlite3BtreeFirst(pCrsr, &res);
  85058. pC->deferredMoveto = 0;
  85059. pC->cacheStatus = CACHE_STALE;
  85060. }
  85061. if( rc ) goto abort_due_to_error;
  85062. pC->nullRow = (u8)res;
  85063. assert( pOp->p2>0 && pOp->p2<p->nOp );
  85064. VdbeBranchTaken(res!=0,2);
  85065. if( res ) goto jump_to_p2;
  85066. break;
  85067. }
  85068. /* Opcode: Next P1 P2 P3 P4 P5
  85069. **
  85070. ** Advance cursor P1 so that it points to the next key/data pair in its
  85071. ** table or index. If there are no more key/value pairs then fall through
  85072. ** to the following instruction. But if the cursor advance was successful,
  85073. ** jump immediately to P2.
  85074. **
  85075. ** The Next opcode is only valid following an SeekGT, SeekGE, or
  85076. ** OP_Rewind opcode used to position the cursor. Next is not allowed
  85077. ** to follow SeekLT, SeekLE, or OP_Last.
  85078. **
  85079. ** The P1 cursor must be for a real table, not a pseudo-table. P1 must have
  85080. ** been opened prior to this opcode or the program will segfault.
  85081. **
  85082. ** The P3 value is a hint to the btree implementation. If P3==1, that
  85083. ** means P1 is an SQL index and that this instruction could have been
  85084. ** omitted if that index had been unique. P3 is usually 0. P3 is
  85085. ** always either 0 or 1.
  85086. **
  85087. ** P4 is always of type P4_ADVANCE. The function pointer points to
  85088. ** sqlite3BtreeNext().
  85089. **
  85090. ** If P5 is positive and the jump is taken, then event counter
  85091. ** number P5-1 in the prepared statement is incremented.
  85092. **
  85093. ** See also: Prev
  85094. */
  85095. /* Opcode: Prev P1 P2 P3 P4 P5
  85096. **
  85097. ** Back up cursor P1 so that it points to the previous key/data pair in its
  85098. ** table or index. If there is no previous key/value pairs then fall through
  85099. ** to the following instruction. But if the cursor backup was successful,
  85100. ** jump immediately to P2.
  85101. **
  85102. **
  85103. ** The Prev opcode is only valid following an SeekLT, SeekLE, or
  85104. ** OP_Last opcode used to position the cursor. Prev is not allowed
  85105. ** to follow SeekGT, SeekGE, or OP_Rewind.
  85106. **
  85107. ** The P1 cursor must be for a real table, not a pseudo-table. If P1 is
  85108. ** not open then the behavior is undefined.
  85109. **
  85110. ** The P3 value is a hint to the btree implementation. If P3==1, that
  85111. ** means P1 is an SQL index and that this instruction could have been
  85112. ** omitted if that index had been unique. P3 is usually 0. P3 is
  85113. ** always either 0 or 1.
  85114. **
  85115. ** P4 is always of type P4_ADVANCE. The function pointer points to
  85116. ** sqlite3BtreePrevious().
  85117. **
  85118. ** If P5 is positive and the jump is taken, then event counter
  85119. ** number P5-1 in the prepared statement is incremented.
  85120. */
  85121. /* Opcode: SorterNext P1 P2 * * P5
  85122. **
  85123. ** This opcode works just like OP_Next except that P1 must be a
  85124. ** sorter object for which the OP_SorterSort opcode has been
  85125. ** invoked. This opcode advances the cursor to the next sorted
  85126. ** record, or jumps to P2 if there are no more sorted records.
  85127. */
  85128. case OP_SorterNext: { /* jump */
  85129. VdbeCursor *pC;
  85130. pC = p->apCsr[pOp->p1];
  85131. assert( isSorter(pC) );
  85132. rc = sqlite3VdbeSorterNext(db, pC);
  85133. goto next_tail;
  85134. case OP_Prev: /* jump */
  85135. case OP_Next: /* jump */
  85136. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  85137. assert( pOp->p5<ArraySize(p->aCounter) );
  85138. pC = p->apCsr[pOp->p1];
  85139. assert( pC!=0 );
  85140. assert( pC->deferredMoveto==0 );
  85141. assert( pC->eCurType==CURTYPE_BTREE );
  85142. assert( pOp->opcode!=OP_Next || pOp->p4.xAdvance==sqlite3BtreeNext );
  85143. assert( pOp->opcode!=OP_Prev || pOp->p4.xAdvance==sqlite3BtreePrevious );
  85144. /* The Next opcode is only used after SeekGT, SeekGE, Rewind, and Found.
  85145. ** The Prev opcode is only used after SeekLT, SeekLE, and Last. */
  85146. assert( pOp->opcode!=OP_Next
  85147. || pC->seekOp==OP_SeekGT || pC->seekOp==OP_SeekGE
  85148. || pC->seekOp==OP_Rewind || pC->seekOp==OP_Found
  85149. || pC->seekOp==OP_NullRow|| pC->seekOp==OP_SeekRowid
  85150. || pC->seekOp==OP_IfNoHope);
  85151. assert( pOp->opcode!=OP_Prev
  85152. || pC->seekOp==OP_SeekLT || pC->seekOp==OP_SeekLE
  85153. || pC->seekOp==OP_Last || pC->seekOp==OP_IfNoHope
  85154. || pC->seekOp==OP_NullRow);
  85155. rc = pOp->p4.xAdvance(pC->uc.pCursor, pOp->p3);
  85156. next_tail:
  85157. pC->cacheStatus = CACHE_STALE;
  85158. VdbeBranchTaken(rc==SQLITE_OK,2);
  85159. if( rc==SQLITE_OK ){
  85160. pC->nullRow = 0;
  85161. p->aCounter[pOp->p5]++;
  85162. #ifdef SQLITE_TEST
  85163. sqlite3_search_count++;
  85164. #endif
  85165. goto jump_to_p2_and_check_for_interrupt;
  85166. }
  85167. if( rc!=SQLITE_DONE ) goto abort_due_to_error;
  85168. rc = SQLITE_OK;
  85169. pC->nullRow = 1;
  85170. goto check_for_interrupt;
  85171. }
  85172. /* Opcode: IdxInsert P1 P2 P3 P4 P5
  85173. ** Synopsis: key=r[P2]
  85174. **
  85175. ** Register P2 holds an SQL index key made using the
  85176. ** MakeRecord instructions. This opcode writes that key
  85177. ** into the index P1. Data for the entry is nil.
  85178. **
  85179. ** If P4 is not zero, then it is the number of values in the unpacked
  85180. ** key of reg(P2). In that case, P3 is the index of the first register
  85181. ** for the unpacked key. The availability of the unpacked key can sometimes
  85182. ** be an optimization.
  85183. **
  85184. ** If P5 has the OPFLAG_APPEND bit set, that is a hint to the b-tree layer
  85185. ** that this insert is likely to be an append.
  85186. **
  85187. ** If P5 has the OPFLAG_NCHANGE bit set, then the change counter is
  85188. ** incremented by this instruction. If the OPFLAG_NCHANGE bit is clear,
  85189. ** then the change counter is unchanged.
  85190. **
  85191. ** If the OPFLAG_USESEEKRESULT flag of P5 is set, the implementation might
  85192. ** run faster by avoiding an unnecessary seek on cursor P1. However,
  85193. ** the OPFLAG_USESEEKRESULT flag must only be set if there have been no prior
  85194. ** seeks on the cursor or if the most recent seek used a key equivalent
  85195. ** to P2.
  85196. **
  85197. ** This instruction only works for indices. The equivalent instruction
  85198. ** for tables is OP_Insert.
  85199. */
  85200. case OP_IdxInsert: { /* in2 */
  85201. VdbeCursor *pC;
  85202. BtreePayload x;
  85203. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  85204. pC = p->apCsr[pOp->p1];
  85205. sqlite3VdbeIncrWriteCounter(p, pC);
  85206. assert( pC!=0 );
  85207. assert( !isSorter(pC) );
  85208. pIn2 = &aMem[pOp->p2];
  85209. assert( pIn2->flags & MEM_Blob );
  85210. if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
  85211. assert( pC->eCurType==CURTYPE_BTREE );
  85212. assert( pC->isTable==0 );
  85213. rc = ExpandBlob(pIn2);
  85214. if( rc ) goto abort_due_to_error;
  85215. x.nKey = pIn2->n;
  85216. x.pKey = pIn2->z;
  85217. x.aMem = aMem + pOp->p3;
  85218. x.nMem = (u16)pOp->p4.i;
  85219. rc = sqlite3BtreeInsert(pC->uc.pCursor, &x,
  85220. (pOp->p5 & (OPFLAG_APPEND|OPFLAG_SAVEPOSITION)),
  85221. ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0)
  85222. );
  85223. assert( pC->deferredMoveto==0 );
  85224. pC->cacheStatus = CACHE_STALE;
  85225. if( rc) goto abort_due_to_error;
  85226. break;
  85227. }
  85228. /* Opcode: SorterInsert P1 P2 * * *
  85229. ** Synopsis: key=r[P2]
  85230. **
  85231. ** Register P2 holds an SQL index key made using the
  85232. ** MakeRecord instructions. This opcode writes that key
  85233. ** into the sorter P1. Data for the entry is nil.
  85234. */
  85235. case OP_SorterInsert: { /* in2 */
  85236. VdbeCursor *pC;
  85237. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  85238. pC = p->apCsr[pOp->p1];
  85239. sqlite3VdbeIncrWriteCounter(p, pC);
  85240. assert( pC!=0 );
  85241. assert( isSorter(pC) );
  85242. pIn2 = &aMem[pOp->p2];
  85243. assert( pIn2->flags & MEM_Blob );
  85244. assert( pC->isTable==0 );
  85245. rc = ExpandBlob(pIn2);
  85246. if( rc ) goto abort_due_to_error;
  85247. rc = sqlite3VdbeSorterWrite(pC, pIn2);
  85248. if( rc) goto abort_due_to_error;
  85249. break;
  85250. }
  85251. /* Opcode: IdxDelete P1 P2 P3 * P5
  85252. ** Synopsis: key=r[P2@P3]
  85253. **
  85254. ** The content of P3 registers starting at register P2 form
  85255. ** an unpacked index key. This opcode removes that entry from the
  85256. ** index opened by cursor P1.
  85257. **
  85258. ** If P5 is not zero, then raise an SQLITE_CORRUPT_INDEX error
  85259. ** if no matching index entry is found. This happens when running
  85260. ** an UPDATE or DELETE statement and the index entry to be updated
  85261. ** or deleted is not found. For some uses of IdxDelete
  85262. ** (example: the EXCEPT operator) it does not matter that no matching
  85263. ** entry is found. For those cases, P5 is zero.
  85264. */
  85265. case OP_IdxDelete: {
  85266. VdbeCursor *pC;
  85267. BtCursor *pCrsr;
  85268. int res;
  85269. UnpackedRecord r;
  85270. assert( pOp->p3>0 );
  85271. assert( pOp->p2>0 && pOp->p2+pOp->p3<=(p->nMem+1 - p->nCursor)+1 );
  85272. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  85273. pC = p->apCsr[pOp->p1];
  85274. assert( pC!=0 );
  85275. assert( pC->eCurType==CURTYPE_BTREE );
  85276. sqlite3VdbeIncrWriteCounter(p, pC);
  85277. pCrsr = pC->uc.pCursor;
  85278. assert( pCrsr!=0 );
  85279. r.pKeyInfo = pC->pKeyInfo;
  85280. r.nField = (u16)pOp->p3;
  85281. r.default_rc = 0;
  85282. r.aMem = &aMem[pOp->p2];
  85283. rc = sqlite3BtreeMovetoUnpacked(pCrsr, &r, 0, 0, &res);
  85284. if( rc ) goto abort_due_to_error;
  85285. if( res==0 ){
  85286. rc = sqlite3BtreeDelete(pCrsr, BTREE_AUXDELETE);
  85287. if( rc ) goto abort_due_to_error;
  85288. }else if( pOp->p5 ){
  85289. rc = SQLITE_CORRUPT_INDEX;
  85290. goto abort_due_to_error;
  85291. }
  85292. assert( pC->deferredMoveto==0 );
  85293. pC->cacheStatus = CACHE_STALE;
  85294. pC->seekResult = 0;
  85295. break;
  85296. }
  85297. /* Opcode: DeferredSeek P1 * P3 P4 *
  85298. ** Synopsis: Move P3 to P1.rowid if needed
  85299. **
  85300. ** P1 is an open index cursor and P3 is a cursor on the corresponding
  85301. ** table. This opcode does a deferred seek of the P3 table cursor
  85302. ** to the row that corresponds to the current row of P1.
  85303. **
  85304. ** This is a deferred seek. Nothing actually happens until
  85305. ** the cursor is used to read a record. That way, if no reads
  85306. ** occur, no unnecessary I/O happens.
  85307. **
  85308. ** P4 may be an array of integers (type P4_INTARRAY) containing
  85309. ** one entry for each column in the P3 table. If array entry a(i)
  85310. ** is non-zero, then reading column a(i)-1 from cursor P3 is
  85311. ** equivalent to performing the deferred seek and then reading column i
  85312. ** from P1. This information is stored in P3 and used to redirect
  85313. ** reads against P3 over to P1, thus possibly avoiding the need to
  85314. ** seek and read cursor P3.
  85315. */
  85316. /* Opcode: IdxRowid P1 P2 * * *
  85317. ** Synopsis: r[P2]=rowid
  85318. **
  85319. ** Write into register P2 an integer which is the last entry in the record at
  85320. ** the end of the index key pointed to by cursor P1. This integer should be
  85321. ** the rowid of the table entry to which this index entry points.
  85322. **
  85323. ** See also: Rowid, MakeRecord.
  85324. */
  85325. case OP_DeferredSeek:
  85326. case OP_IdxRowid: { /* out2 */
  85327. VdbeCursor *pC; /* The P1 index cursor */
  85328. VdbeCursor *pTabCur; /* The P2 table cursor (OP_DeferredSeek only) */
  85329. i64 rowid; /* Rowid that P1 current points to */
  85330. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  85331. pC = p->apCsr[pOp->p1];
  85332. assert( pC!=0 );
  85333. assert( pC->eCurType==CURTYPE_BTREE );
  85334. assert( pC->uc.pCursor!=0 );
  85335. assert( pC->isTable==0 );
  85336. assert( pC->deferredMoveto==0 );
  85337. assert( !pC->nullRow || pOp->opcode==OP_IdxRowid );
  85338. /* The IdxRowid and Seek opcodes are combined because of the commonality
  85339. ** of sqlite3VdbeCursorRestore() and sqlite3VdbeIdxRowid(). */
  85340. rc = sqlite3VdbeCursorRestore(pC);
  85341. /* sqlite3VbeCursorRestore() can only fail if the record has been deleted
  85342. ** out from under the cursor. That will never happens for an IdxRowid
  85343. ** or Seek opcode */
  85344. if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
  85345. if( !pC->nullRow ){
  85346. rowid = 0; /* Not needed. Only used to silence a warning. */
  85347. rc = sqlite3VdbeIdxRowid(db, pC->uc.pCursor, &rowid);
  85348. if( rc!=SQLITE_OK ){
  85349. goto abort_due_to_error;
  85350. }
  85351. if( pOp->opcode==OP_DeferredSeek ){
  85352. assert( pOp->p3>=0 && pOp->p3<p->nCursor );
  85353. pTabCur = p->apCsr[pOp->p3];
  85354. assert( pTabCur!=0 );
  85355. assert( pTabCur->eCurType==CURTYPE_BTREE );
  85356. assert( pTabCur->uc.pCursor!=0 );
  85357. assert( pTabCur->isTable );
  85358. pTabCur->nullRow = 0;
  85359. pTabCur->movetoTarget = rowid;
  85360. pTabCur->deferredMoveto = 1;
  85361. assert( pOp->p4type==P4_INTARRAY || pOp->p4.ai==0 );
  85362. pTabCur->aAltMap = pOp->p4.ai;
  85363. pTabCur->pAltCursor = pC;
  85364. }else{
  85365. pOut = out2Prerelease(p, pOp);
  85366. pOut->u.i = rowid;
  85367. }
  85368. }else{
  85369. assert( pOp->opcode==OP_IdxRowid );
  85370. sqlite3VdbeMemSetNull(&aMem[pOp->p2]);
  85371. }
  85372. break;
  85373. }
  85374. /* Opcode: FinishSeek P1 * * * *
  85375. **
  85376. ** If cursor P1 was previously moved via OP_DeferredSeek, complete that
  85377. ** seek operation now, without further delay. If the cursor seek has
  85378. ** already occurred, this instruction is a no-op.
  85379. */
  85380. case OP_FinishSeek: {
  85381. VdbeCursor *pC; /* The P1 index cursor */
  85382. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  85383. pC = p->apCsr[pOp->p1];
  85384. if( pC->deferredMoveto ){
  85385. rc = sqlite3VdbeFinishMoveto(pC);
  85386. if( rc ) goto abort_due_to_error;
  85387. }
  85388. break;
  85389. }
  85390. /* Opcode: IdxGE P1 P2 P3 P4 P5
  85391. ** Synopsis: key=r[P3@P4]
  85392. **
  85393. ** The P4 register values beginning with P3 form an unpacked index
  85394. ** key that omits the PRIMARY KEY. Compare this key value against the index
  85395. ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
  85396. ** fields at the end.
  85397. **
  85398. ** If the P1 index entry is greater than or equal to the key value
  85399. ** then jump to P2. Otherwise fall through to the next instruction.
  85400. */
  85401. /* Opcode: IdxGT P1 P2 P3 P4 P5
  85402. ** Synopsis: key=r[P3@P4]
  85403. **
  85404. ** The P4 register values beginning with P3 form an unpacked index
  85405. ** key that omits the PRIMARY KEY. Compare this key value against the index
  85406. ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
  85407. ** fields at the end.
  85408. **
  85409. ** If the P1 index entry is greater than the key value
  85410. ** then jump to P2. Otherwise fall through to the next instruction.
  85411. */
  85412. /* Opcode: IdxLT P1 P2 P3 P4 P5
  85413. ** Synopsis: key=r[P3@P4]
  85414. **
  85415. ** The P4 register values beginning with P3 form an unpacked index
  85416. ** key that omits the PRIMARY KEY or ROWID. Compare this key value against
  85417. ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
  85418. ** ROWID on the P1 index.
  85419. **
  85420. ** If the P1 index entry is less than the key value then jump to P2.
  85421. ** Otherwise fall through to the next instruction.
  85422. */
  85423. /* Opcode: IdxLE P1 P2 P3 P4 P5
  85424. ** Synopsis: key=r[P3@P4]
  85425. **
  85426. ** The P4 register values beginning with P3 form an unpacked index
  85427. ** key that omits the PRIMARY KEY or ROWID. Compare this key value against
  85428. ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
  85429. ** ROWID on the P1 index.
  85430. **
  85431. ** If the P1 index entry is less than or equal to the key value then jump
  85432. ** to P2. Otherwise fall through to the next instruction.
  85433. */
  85434. case OP_IdxLE: /* jump */
  85435. case OP_IdxGT: /* jump */
  85436. case OP_IdxLT: /* jump */
  85437. case OP_IdxGE: { /* jump */
  85438. VdbeCursor *pC;
  85439. int res;
  85440. UnpackedRecord r;
  85441. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  85442. pC = p->apCsr[pOp->p1];
  85443. assert( pC!=0 );
  85444. assert( pC->isOrdered );
  85445. assert( pC->eCurType==CURTYPE_BTREE );
  85446. assert( pC->uc.pCursor!=0);
  85447. assert( pC->deferredMoveto==0 );
  85448. assert( pOp->p5==0 || pOp->p5==1 );
  85449. assert( pOp->p4type==P4_INT32 );
  85450. r.pKeyInfo = pC->pKeyInfo;
  85451. r.nField = (u16)pOp->p4.i;
  85452. if( pOp->opcode<OP_IdxLT ){
  85453. assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxGT );
  85454. r.default_rc = -1;
  85455. }else{
  85456. assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxLT );
  85457. r.default_rc = 0;
  85458. }
  85459. r.aMem = &aMem[pOp->p3];
  85460. #ifdef SQLITE_DEBUG
  85461. {
  85462. int i;
  85463. for(i=0; i<r.nField; i++){
  85464. assert( memIsValid(&r.aMem[i]) );
  85465. REGISTER_TRACE(pOp->p3+i, &aMem[pOp->p3+i]);
  85466. }
  85467. }
  85468. #endif
  85469. res = 0; /* Not needed. Only used to silence a warning. */
  85470. rc = sqlite3VdbeIdxKeyCompare(db, pC, &r, &res);
  85471. assert( (OP_IdxLE&1)==(OP_IdxLT&1) && (OP_IdxGE&1)==(OP_IdxGT&1) );
  85472. if( (pOp->opcode&1)==(OP_IdxLT&1) ){
  85473. assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxLT );
  85474. res = -res;
  85475. }else{
  85476. assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxGT );
  85477. res++;
  85478. }
  85479. VdbeBranchTaken(res>0,2);
  85480. if( rc ) goto abort_due_to_error;
  85481. if( res>0 ) goto jump_to_p2;
  85482. break;
  85483. }
  85484. /* Opcode: Destroy P1 P2 P3 * *
  85485. **
  85486. ** Delete an entire database table or index whose root page in the database
  85487. ** file is given by P1.
  85488. **
  85489. ** The table being destroyed is in the main database file if P3==0. If
  85490. ** P3==1 then the table to be clear is in the auxiliary database file
  85491. ** that is used to store tables create using CREATE TEMPORARY TABLE.
  85492. **
  85493. ** If AUTOVACUUM is enabled then it is possible that another root page
  85494. ** might be moved into the newly deleted root page in order to keep all
  85495. ** root pages contiguous at the beginning of the database. The former
  85496. ** value of the root page that moved - its value before the move occurred -
  85497. ** is stored in register P2. If no page movement was required (because the
  85498. ** table being dropped was already the last one in the database) then a
  85499. ** zero is stored in register P2. If AUTOVACUUM is disabled then a zero
  85500. ** is stored in register P2.
  85501. **
  85502. ** This opcode throws an error if there are any active reader VMs when
  85503. ** it is invoked. This is done to avoid the difficulty associated with
  85504. ** updating existing cursors when a root page is moved in an AUTOVACUUM
  85505. ** database. This error is thrown even if the database is not an AUTOVACUUM
  85506. ** db in order to avoid introducing an incompatibility between autovacuum
  85507. ** and non-autovacuum modes.
  85508. **
  85509. ** See also: Clear
  85510. */
  85511. case OP_Destroy: { /* out2 */
  85512. int iMoved;
  85513. int iDb;
  85514. sqlite3VdbeIncrWriteCounter(p, 0);
  85515. assert( p->readOnly==0 );
  85516. assert( pOp->p1>1 );
  85517. pOut = out2Prerelease(p, pOp);
  85518. pOut->flags = MEM_Null;
  85519. if( db->nVdbeRead > db->nVDestroy+1 ){
  85520. rc = SQLITE_LOCKED;
  85521. p->errorAction = OE_Abort;
  85522. goto abort_due_to_error;
  85523. }else{
  85524. iDb = pOp->p3;
  85525. assert( DbMaskTest(p->btreeMask, iDb) );
  85526. iMoved = 0; /* Not needed. Only to silence a warning. */
  85527. rc = sqlite3BtreeDropTable(db->aDb[iDb].pBt, pOp->p1, &iMoved);
  85528. pOut->flags = MEM_Int;
  85529. pOut->u.i = iMoved;
  85530. if( rc ) goto abort_due_to_error;
  85531. #ifndef SQLITE_OMIT_AUTOVACUUM
  85532. if( iMoved!=0 ){
  85533. sqlite3RootPageMoved(db, iDb, iMoved, pOp->p1);
  85534. /* All OP_Destroy operations occur on the same btree */
  85535. assert( resetSchemaOnFault==0 || resetSchemaOnFault==iDb+1 );
  85536. resetSchemaOnFault = iDb+1;
  85537. }
  85538. #endif
  85539. }
  85540. break;
  85541. }
  85542. /* Opcode: Clear P1 P2 P3
  85543. **
  85544. ** Delete all contents of the database table or index whose root page
  85545. ** in the database file is given by P1. But, unlike Destroy, do not
  85546. ** remove the table or index from the database file.
  85547. **
  85548. ** The table being clear is in the main database file if P2==0. If
  85549. ** P2==1 then the table to be clear is in the auxiliary database file
  85550. ** that is used to store tables create using CREATE TEMPORARY TABLE.
  85551. **
  85552. ** If the P3 value is non-zero, then the table referred to must be an
  85553. ** intkey table (an SQL table, not an index). In this case the row change
  85554. ** count is incremented by the number of rows in the table being cleared.
  85555. ** If P3 is greater than zero, then the value stored in register P3 is
  85556. ** also incremented by the number of rows in the table being cleared.
  85557. **
  85558. ** See also: Destroy
  85559. */
  85560. case OP_Clear: {
  85561. int nChange;
  85562. sqlite3VdbeIncrWriteCounter(p, 0);
  85563. nChange = 0;
  85564. assert( p->readOnly==0 );
  85565. assert( DbMaskTest(p->btreeMask, pOp->p2) );
  85566. rc = sqlite3BtreeClearTable(
  85567. db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &nChange : 0)
  85568. );
  85569. if( pOp->p3 ){
  85570. p->nChange += nChange;
  85571. if( pOp->p3>0 ){
  85572. assert( memIsValid(&aMem[pOp->p3]) );
  85573. memAboutToChange(p, &aMem[pOp->p3]);
  85574. aMem[pOp->p3].u.i += nChange;
  85575. }
  85576. }
  85577. if( rc ) goto abort_due_to_error;
  85578. break;
  85579. }
  85580. /* Opcode: ResetSorter P1 * * * *
  85581. **
  85582. ** Delete all contents from the ephemeral table or sorter
  85583. ** that is open on cursor P1.
  85584. **
  85585. ** This opcode only works for cursors used for sorting and
  85586. ** opened with OP_OpenEphemeral or OP_SorterOpen.
  85587. */
  85588. case OP_ResetSorter: {
  85589. VdbeCursor *pC;
  85590. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  85591. pC = p->apCsr[pOp->p1];
  85592. assert( pC!=0 );
  85593. if( isSorter(pC) ){
  85594. sqlite3VdbeSorterReset(db, pC->uc.pSorter);
  85595. }else{
  85596. assert( pC->eCurType==CURTYPE_BTREE );
  85597. assert( pC->isEphemeral );
  85598. rc = sqlite3BtreeClearTableOfCursor(pC->uc.pCursor);
  85599. if( rc ) goto abort_due_to_error;
  85600. }
  85601. break;
  85602. }
  85603. /* Opcode: CreateBtree P1 P2 P3 * *
  85604. ** Synopsis: r[P2]=root iDb=P1 flags=P3
  85605. **
  85606. ** Allocate a new b-tree in the main database file if P1==0 or in the
  85607. ** TEMP database file if P1==1 or in an attached database if
  85608. ** P1>1. The P3 argument must be 1 (BTREE_INTKEY) for a rowid table
  85609. ** it must be 2 (BTREE_BLOBKEY) for an index or WITHOUT ROWID table.
  85610. ** The root page number of the new b-tree is stored in register P2.
  85611. */
  85612. case OP_CreateBtree: { /* out2 */
  85613. int pgno;
  85614. Db *pDb;
  85615. sqlite3VdbeIncrWriteCounter(p, 0);
  85616. pOut = out2Prerelease(p, pOp);
  85617. pgno = 0;
  85618. assert( pOp->p3==BTREE_INTKEY || pOp->p3==BTREE_BLOBKEY );
  85619. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  85620. assert( DbMaskTest(p->btreeMask, pOp->p1) );
  85621. assert( p->readOnly==0 );
  85622. pDb = &db->aDb[pOp->p1];
  85623. assert( pDb->pBt!=0 );
  85624. rc = sqlite3BtreeCreateTable(pDb->pBt, &pgno, pOp->p3);
  85625. if( rc ) goto abort_due_to_error;
  85626. pOut->u.i = pgno;
  85627. break;
  85628. }
  85629. /* Opcode: SqlExec * * * P4 *
  85630. **
  85631. ** Run the SQL statement or statements specified in the P4 string.
  85632. */
  85633. case OP_SqlExec: {
  85634. sqlite3VdbeIncrWriteCounter(p, 0);
  85635. db->nSqlExec++;
  85636. rc = sqlite3_exec(db, pOp->p4.z, 0, 0, 0);
  85637. db->nSqlExec--;
  85638. if( rc ) goto abort_due_to_error;
  85639. break;
  85640. }
  85641. /* Opcode: ParseSchema P1 * * P4 *
  85642. **
  85643. ** Read and parse all entries from the SQLITE_MASTER table of database P1
  85644. ** that match the WHERE clause P4. If P4 is a NULL pointer, then the
  85645. ** entire schema for P1 is reparsed.
  85646. **
  85647. ** This opcode invokes the parser to create a new virtual machine,
  85648. ** then runs the new virtual machine. It is thus a re-entrant opcode.
  85649. */
  85650. case OP_ParseSchema: {
  85651. int iDb;
  85652. const char *zMaster;
  85653. char *zSql;
  85654. InitData initData;
  85655. /* Any prepared statement that invokes this opcode will hold mutexes
  85656. ** on every btree. This is a prerequisite for invoking
  85657. ** sqlite3InitCallback().
  85658. */
  85659. #ifdef SQLITE_DEBUG
  85660. for(iDb=0; iDb<db->nDb; iDb++){
  85661. assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
  85662. }
  85663. #endif
  85664. iDb = pOp->p1;
  85665. assert( iDb>=0 && iDb<db->nDb );
  85666. assert( DbHasProperty(db, iDb, DB_SchemaLoaded) );
  85667. #ifndef SQLITE_OMIT_ALTERTABLE
  85668. if( pOp->p4.z==0 ){
  85669. sqlite3SchemaClear(db->aDb[iDb].pSchema);
  85670. db->mDbFlags &= ~DBFLAG_SchemaKnownOk;
  85671. rc = sqlite3InitOne(db, iDb, &p->zErrMsg, INITFLAG_AlterTable);
  85672. db->mDbFlags |= DBFLAG_SchemaChange;
  85673. p->expired = 0;
  85674. }else
  85675. #endif
  85676. {
  85677. zMaster = MASTER_NAME;
  85678. initData.db = db;
  85679. initData.iDb = iDb;
  85680. initData.pzErrMsg = &p->zErrMsg;
  85681. initData.mInitFlags = 0;
  85682. zSql = sqlite3MPrintf(db,
  85683. "SELECT*FROM\"%w\".%s WHERE %s ORDER BY rowid",
  85684. db->aDb[iDb].zDbSName, zMaster, pOp->p4.z);
  85685. if( zSql==0 ){
  85686. rc = SQLITE_NOMEM_BKPT;
  85687. }else{
  85688. assert( db->init.busy==0 );
  85689. db->init.busy = 1;
  85690. initData.rc = SQLITE_OK;
  85691. initData.nInitRow = 0;
  85692. assert( !db->mallocFailed );
  85693. rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
  85694. if( rc==SQLITE_OK ) rc = initData.rc;
  85695. if( rc==SQLITE_OK && initData.nInitRow==0 ){
  85696. /* The OP_ParseSchema opcode with a non-NULL P4 argument should parse
  85697. ** at least one SQL statement. Any less than that indicates that
  85698. ** the sqlite_master table is corrupt. */
  85699. rc = SQLITE_CORRUPT_BKPT;
  85700. }
  85701. sqlite3DbFreeNN(db, zSql);
  85702. db->init.busy = 0;
  85703. }
  85704. }
  85705. if( rc ){
  85706. sqlite3ResetAllSchemasOfConnection(db);
  85707. if( rc==SQLITE_NOMEM ){
  85708. goto no_mem;
  85709. }
  85710. goto abort_due_to_error;
  85711. }
  85712. break;
  85713. }
  85714. #if !defined(SQLITE_OMIT_ANALYZE)
  85715. /* Opcode: LoadAnalysis P1 * * * *
  85716. **
  85717. ** Read the sqlite_stat1 table for database P1 and load the content
  85718. ** of that table into the internal index hash table. This will cause
  85719. ** the analysis to be used when preparing all subsequent queries.
  85720. */
  85721. case OP_LoadAnalysis: {
  85722. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  85723. rc = sqlite3AnalysisLoad(db, pOp->p1);
  85724. if( rc ) goto abort_due_to_error;
  85725. break;
  85726. }
  85727. #endif /* !defined(SQLITE_OMIT_ANALYZE) */
  85728. /* Opcode: DropTable P1 * * P4 *
  85729. **
  85730. ** Remove the internal (in-memory) data structures that describe
  85731. ** the table named P4 in database P1. This is called after a table
  85732. ** is dropped from disk (using the Destroy opcode) in order to keep
  85733. ** the internal representation of the
  85734. ** schema consistent with what is on disk.
  85735. */
  85736. case OP_DropTable: {
  85737. sqlite3VdbeIncrWriteCounter(p, 0);
  85738. sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
  85739. break;
  85740. }
  85741. /* Opcode: DropIndex P1 * * P4 *
  85742. **
  85743. ** Remove the internal (in-memory) data structures that describe
  85744. ** the index named P4 in database P1. This is called after an index
  85745. ** is dropped from disk (using the Destroy opcode)
  85746. ** in order to keep the internal representation of the
  85747. ** schema consistent with what is on disk.
  85748. */
  85749. case OP_DropIndex: {
  85750. sqlite3VdbeIncrWriteCounter(p, 0);
  85751. sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
  85752. break;
  85753. }
  85754. /* Opcode: DropTrigger P1 * * P4 *
  85755. **
  85756. ** Remove the internal (in-memory) data structures that describe
  85757. ** the trigger named P4 in database P1. This is called after a trigger
  85758. ** is dropped from disk (using the Destroy opcode) in order to keep
  85759. ** the internal representation of the
  85760. ** schema consistent with what is on disk.
  85761. */
  85762. case OP_DropTrigger: {
  85763. sqlite3VdbeIncrWriteCounter(p, 0);
  85764. sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
  85765. break;
  85766. }
  85767. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  85768. /* Opcode: IntegrityCk P1 P2 P3 P4 P5
  85769. **
  85770. ** Do an analysis of the currently open database. Store in
  85771. ** register P1 the text of an error message describing any problems.
  85772. ** If no problems are found, store a NULL in register P1.
  85773. **
  85774. ** The register P3 contains one less than the maximum number of allowed errors.
  85775. ** At most reg(P3) errors will be reported.
  85776. ** In other words, the analysis stops as soon as reg(P1) errors are
  85777. ** seen. Reg(P1) is updated with the number of errors remaining.
  85778. **
  85779. ** The root page numbers of all tables in the database are integers
  85780. ** stored in P4_INTARRAY argument.
  85781. **
  85782. ** If P5 is not zero, the check is done on the auxiliary database
  85783. ** file, not the main database file.
  85784. **
  85785. ** This opcode is used to implement the integrity_check pragma.
  85786. */
  85787. case OP_IntegrityCk: {
  85788. int nRoot; /* Number of tables to check. (Number of root pages.) */
  85789. int *aRoot; /* Array of rootpage numbers for tables to be checked */
  85790. int nErr; /* Number of errors reported */
  85791. char *z; /* Text of the error report */
  85792. Mem *pnErr; /* Register keeping track of errors remaining */
  85793. assert( p->bIsReader );
  85794. nRoot = pOp->p2;
  85795. aRoot = pOp->p4.ai;
  85796. assert( nRoot>0 );
  85797. assert( aRoot[0]==nRoot );
  85798. assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
  85799. pnErr = &aMem[pOp->p3];
  85800. assert( (pnErr->flags & MEM_Int)!=0 );
  85801. assert( (pnErr->flags & (MEM_Str|MEM_Blob))==0 );
  85802. pIn1 = &aMem[pOp->p1];
  85803. assert( pOp->p5<db->nDb );
  85804. assert( DbMaskTest(p->btreeMask, pOp->p5) );
  85805. z = sqlite3BtreeIntegrityCheck(db, db->aDb[pOp->p5].pBt, &aRoot[1], nRoot,
  85806. (int)pnErr->u.i+1, &nErr);
  85807. sqlite3VdbeMemSetNull(pIn1);
  85808. if( nErr==0 ){
  85809. assert( z==0 );
  85810. }else if( z==0 ){
  85811. goto no_mem;
  85812. }else{
  85813. pnErr->u.i -= nErr-1;
  85814. sqlite3VdbeMemSetStr(pIn1, z, -1, SQLITE_UTF8, sqlite3_free);
  85815. }
  85816. UPDATE_MAX_BLOBSIZE(pIn1);
  85817. sqlite3VdbeChangeEncoding(pIn1, encoding);
  85818. goto check_for_interrupt;
  85819. }
  85820. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  85821. /* Opcode: RowSetAdd P1 P2 * * *
  85822. ** Synopsis: rowset(P1)=r[P2]
  85823. **
  85824. ** Insert the integer value held by register P2 into a RowSet object
  85825. ** held in register P1.
  85826. **
  85827. ** An assertion fails if P2 is not an integer.
  85828. */
  85829. case OP_RowSetAdd: { /* in1, in2 */
  85830. pIn1 = &aMem[pOp->p1];
  85831. pIn2 = &aMem[pOp->p2];
  85832. assert( (pIn2->flags & MEM_Int)!=0 );
  85833. if( (pIn1->flags & MEM_Blob)==0 ){
  85834. if( sqlite3VdbeMemSetRowSet(pIn1) ) goto no_mem;
  85835. }
  85836. assert( sqlite3VdbeMemIsRowSet(pIn1) );
  85837. sqlite3RowSetInsert((RowSet*)pIn1->z, pIn2->u.i);
  85838. break;
  85839. }
  85840. /* Opcode: RowSetRead P1 P2 P3 * *
  85841. ** Synopsis: r[P3]=rowset(P1)
  85842. **
  85843. ** Extract the smallest value from the RowSet object in P1
  85844. ** and put that value into register P3.
  85845. ** Or, if RowSet object P1 is initially empty, leave P3
  85846. ** unchanged and jump to instruction P2.
  85847. */
  85848. case OP_RowSetRead: { /* jump, in1, out3 */
  85849. i64 val;
  85850. pIn1 = &aMem[pOp->p1];
  85851. assert( (pIn1->flags & MEM_Blob)==0 || sqlite3VdbeMemIsRowSet(pIn1) );
  85852. if( (pIn1->flags & MEM_Blob)==0
  85853. || sqlite3RowSetNext((RowSet*)pIn1->z, &val)==0
  85854. ){
  85855. /* The boolean index is empty */
  85856. sqlite3VdbeMemSetNull(pIn1);
  85857. VdbeBranchTaken(1,2);
  85858. goto jump_to_p2_and_check_for_interrupt;
  85859. }else{
  85860. /* A value was pulled from the index */
  85861. VdbeBranchTaken(0,2);
  85862. sqlite3VdbeMemSetInt64(&aMem[pOp->p3], val);
  85863. }
  85864. goto check_for_interrupt;
  85865. }
  85866. /* Opcode: RowSetTest P1 P2 P3 P4
  85867. ** Synopsis: if r[P3] in rowset(P1) goto P2
  85868. **
  85869. ** Register P3 is assumed to hold a 64-bit integer value. If register P1
  85870. ** contains a RowSet object and that RowSet object contains
  85871. ** the value held in P3, jump to register P2. Otherwise, insert the
  85872. ** integer in P3 into the RowSet and continue on to the
  85873. ** next opcode.
  85874. **
  85875. ** The RowSet object is optimized for the case where sets of integers
  85876. ** are inserted in distinct phases, which each set contains no duplicates.
  85877. ** Each set is identified by a unique P4 value. The first set
  85878. ** must have P4==0, the final set must have P4==-1, and for all other sets
  85879. ** must have P4>0.
  85880. **
  85881. ** This allows optimizations: (a) when P4==0 there is no need to test
  85882. ** the RowSet object for P3, as it is guaranteed not to contain it,
  85883. ** (b) when P4==-1 there is no need to insert the value, as it will
  85884. ** never be tested for, and (c) when a value that is part of set X is
  85885. ** inserted, there is no need to search to see if the same value was
  85886. ** previously inserted as part of set X (only if it was previously
  85887. ** inserted as part of some other set).
  85888. */
  85889. case OP_RowSetTest: { /* jump, in1, in3 */
  85890. int iSet;
  85891. int exists;
  85892. pIn1 = &aMem[pOp->p1];
  85893. pIn3 = &aMem[pOp->p3];
  85894. iSet = pOp->p4.i;
  85895. assert( pIn3->flags&MEM_Int );
  85896. /* If there is anything other than a rowset object in memory cell P1,
  85897. ** delete it now and initialize P1 with an empty rowset
  85898. */
  85899. if( (pIn1->flags & MEM_Blob)==0 ){
  85900. if( sqlite3VdbeMemSetRowSet(pIn1) ) goto no_mem;
  85901. }
  85902. assert( sqlite3VdbeMemIsRowSet(pIn1) );
  85903. assert( pOp->p4type==P4_INT32 );
  85904. assert( iSet==-1 || iSet>=0 );
  85905. if( iSet ){
  85906. exists = sqlite3RowSetTest((RowSet*)pIn1->z, iSet, pIn3->u.i);
  85907. VdbeBranchTaken(exists!=0,2);
  85908. if( exists ) goto jump_to_p2;
  85909. }
  85910. if( iSet>=0 ){
  85911. sqlite3RowSetInsert((RowSet*)pIn1->z, pIn3->u.i);
  85912. }
  85913. break;
  85914. }
  85915. #ifndef SQLITE_OMIT_TRIGGER
  85916. /* Opcode: Program P1 P2 P3 P4 P5
  85917. **
  85918. ** Execute the trigger program passed as P4 (type P4_SUBPROGRAM).
  85919. **
  85920. ** P1 contains the address of the memory cell that contains the first memory
  85921. ** cell in an array of values used as arguments to the sub-program. P2
  85922. ** contains the address to jump to if the sub-program throws an IGNORE
  85923. ** exception using the RAISE() function. Register P3 contains the address
  85924. ** of a memory cell in this (the parent) VM that is used to allocate the
  85925. ** memory required by the sub-vdbe at runtime.
  85926. **
  85927. ** P4 is a pointer to the VM containing the trigger program.
  85928. **
  85929. ** If P5 is non-zero, then recursive program invocation is enabled.
  85930. */
  85931. case OP_Program: { /* jump */
  85932. int nMem; /* Number of memory registers for sub-program */
  85933. int nByte; /* Bytes of runtime space required for sub-program */
  85934. Mem *pRt; /* Register to allocate runtime space */
  85935. Mem *pMem; /* Used to iterate through memory cells */
  85936. Mem *pEnd; /* Last memory cell in new array */
  85937. VdbeFrame *pFrame; /* New vdbe frame to execute in */
  85938. SubProgram *pProgram; /* Sub-program to execute */
  85939. void *t; /* Token identifying trigger */
  85940. pProgram = pOp->p4.pProgram;
  85941. pRt = &aMem[pOp->p3];
  85942. assert( pProgram->nOp>0 );
  85943. /* If the p5 flag is clear, then recursive invocation of triggers is
  85944. ** disabled for backwards compatibility (p5 is set if this sub-program
  85945. ** is really a trigger, not a foreign key action, and the flag set
  85946. ** and cleared by the "PRAGMA recursive_triggers" command is clear).
  85947. **
  85948. ** It is recursive invocation of triggers, at the SQL level, that is
  85949. ** disabled. In some cases a single trigger may generate more than one
  85950. ** SubProgram (if the trigger may be executed with more than one different
  85951. ** ON CONFLICT algorithm). SubProgram structures associated with a
  85952. ** single trigger all have the same value for the SubProgram.token
  85953. ** variable. */
  85954. if( pOp->p5 ){
  85955. t = pProgram->token;
  85956. for(pFrame=p->pFrame; pFrame && pFrame->token!=t; pFrame=pFrame->pParent);
  85957. if( pFrame ) break;
  85958. }
  85959. if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
  85960. rc = SQLITE_ERROR;
  85961. sqlite3VdbeError(p, "too many levels of trigger recursion");
  85962. goto abort_due_to_error;
  85963. }
  85964. /* Register pRt is used to store the memory required to save the state
  85965. ** of the current program, and the memory required at runtime to execute
  85966. ** the trigger program. If this trigger has been fired before, then pRt
  85967. ** is already allocated. Otherwise, it must be initialized. */
  85968. if( (pRt->flags&MEM_Blob)==0 ){
  85969. /* SubProgram.nMem is set to the number of memory cells used by the
  85970. ** program stored in SubProgram.aOp. As well as these, one memory
  85971. ** cell is required for each cursor used by the program. Set local
  85972. ** variable nMem (and later, VdbeFrame.nChildMem) to this value.
  85973. */
  85974. nMem = pProgram->nMem + pProgram->nCsr;
  85975. assert( nMem>0 );
  85976. if( pProgram->nCsr==0 ) nMem++;
  85977. nByte = ROUND8(sizeof(VdbeFrame))
  85978. + nMem * sizeof(Mem)
  85979. + pProgram->nCsr * sizeof(VdbeCursor*)
  85980. + (pProgram->nOp + 7)/8;
  85981. pFrame = sqlite3DbMallocZero(db, nByte);
  85982. if( !pFrame ){
  85983. goto no_mem;
  85984. }
  85985. sqlite3VdbeMemRelease(pRt);
  85986. pRt->flags = MEM_Blob|MEM_Dyn;
  85987. pRt->z = (char*)pFrame;
  85988. pRt->n = nByte;
  85989. pRt->xDel = sqlite3VdbeFrameMemDel;
  85990. pFrame->v = p;
  85991. pFrame->nChildMem = nMem;
  85992. pFrame->nChildCsr = pProgram->nCsr;
  85993. pFrame->pc = (int)(pOp - aOp);
  85994. pFrame->aMem = p->aMem;
  85995. pFrame->nMem = p->nMem;
  85996. pFrame->apCsr = p->apCsr;
  85997. pFrame->nCursor = p->nCursor;
  85998. pFrame->aOp = p->aOp;
  85999. pFrame->nOp = p->nOp;
  86000. pFrame->token = pProgram->token;
  86001. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  86002. pFrame->anExec = p->anExec;
  86003. #endif
  86004. #ifdef SQLITE_DEBUG
  86005. pFrame->iFrameMagic = SQLITE_FRAME_MAGIC;
  86006. #endif
  86007. pEnd = &VdbeFrameMem(pFrame)[pFrame->nChildMem];
  86008. for(pMem=VdbeFrameMem(pFrame); pMem!=pEnd; pMem++){
  86009. pMem->flags = MEM_Undefined;
  86010. pMem->db = db;
  86011. }
  86012. }else{
  86013. pFrame = (VdbeFrame*)pRt->z;
  86014. assert( pRt->xDel==sqlite3VdbeFrameMemDel );
  86015. assert( pProgram->nMem+pProgram->nCsr==pFrame->nChildMem
  86016. || (pProgram->nCsr==0 && pProgram->nMem+1==pFrame->nChildMem) );
  86017. assert( pProgram->nCsr==pFrame->nChildCsr );
  86018. assert( (int)(pOp - aOp)==pFrame->pc );
  86019. }
  86020. p->nFrame++;
  86021. pFrame->pParent = p->pFrame;
  86022. pFrame->lastRowid = db->lastRowid;
  86023. pFrame->nChange = p->nChange;
  86024. pFrame->nDbChange = p->db->nChange;
  86025. assert( pFrame->pAuxData==0 );
  86026. pFrame->pAuxData = p->pAuxData;
  86027. p->pAuxData = 0;
  86028. p->nChange = 0;
  86029. p->pFrame = pFrame;
  86030. p->aMem = aMem = VdbeFrameMem(pFrame);
  86031. p->nMem = pFrame->nChildMem;
  86032. p->nCursor = (u16)pFrame->nChildCsr;
  86033. p->apCsr = (VdbeCursor **)&aMem[p->nMem];
  86034. pFrame->aOnce = (u8*)&p->apCsr[pProgram->nCsr];
  86035. memset(pFrame->aOnce, 0, (pProgram->nOp + 7)/8);
  86036. p->aOp = aOp = pProgram->aOp;
  86037. p->nOp = pProgram->nOp;
  86038. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  86039. p->anExec = 0;
  86040. #endif
  86041. #ifdef SQLITE_DEBUG
  86042. /* Verify that second and subsequent executions of the same trigger do not
  86043. ** try to reuse register values from the first use. */
  86044. {
  86045. int i;
  86046. for(i=0; i<p->nMem; i++){
  86047. aMem[i].pScopyFrom = 0; /* Prevent false-positive AboutToChange() errs */
  86048. MemSetTypeFlag(&aMem[i], MEM_Undefined); /* Fault if this reg is reused */
  86049. }
  86050. }
  86051. #endif
  86052. pOp = &aOp[-1];
  86053. goto check_for_interrupt;
  86054. }
  86055. /* Opcode: Param P1 P2 * * *
  86056. **
  86057. ** This opcode is only ever present in sub-programs called via the
  86058. ** OP_Program instruction. Copy a value currently stored in a memory
  86059. ** cell of the calling (parent) frame to cell P2 in the current frames
  86060. ** address space. This is used by trigger programs to access the new.*
  86061. ** and old.* values.
  86062. **
  86063. ** The address of the cell in the parent frame is determined by adding
  86064. ** the value of the P1 argument to the value of the P1 argument to the
  86065. ** calling OP_Program instruction.
  86066. */
  86067. case OP_Param: { /* out2 */
  86068. VdbeFrame *pFrame;
  86069. Mem *pIn;
  86070. pOut = out2Prerelease(p, pOp);
  86071. pFrame = p->pFrame;
  86072. pIn = &pFrame->aMem[pOp->p1 + pFrame->aOp[pFrame->pc].p1];
  86073. sqlite3VdbeMemShallowCopy(pOut, pIn, MEM_Ephem);
  86074. break;
  86075. }
  86076. #endif /* #ifndef SQLITE_OMIT_TRIGGER */
  86077. #ifndef SQLITE_OMIT_FOREIGN_KEY
  86078. /* Opcode: FkCounter P1 P2 * * *
  86079. ** Synopsis: fkctr[P1]+=P2
  86080. **
  86081. ** Increment a "constraint counter" by P2 (P2 may be negative or positive).
  86082. ** If P1 is non-zero, the database constraint counter is incremented
  86083. ** (deferred foreign key constraints). Otherwise, if P1 is zero, the
  86084. ** statement counter is incremented (immediate foreign key constraints).
  86085. */
  86086. case OP_FkCounter: {
  86087. if( db->flags & SQLITE_DeferFKs ){
  86088. db->nDeferredImmCons += pOp->p2;
  86089. }else if( pOp->p1 ){
  86090. db->nDeferredCons += pOp->p2;
  86091. }else{
  86092. p->nFkConstraint += pOp->p2;
  86093. }
  86094. break;
  86095. }
  86096. /* Opcode: FkIfZero P1 P2 * * *
  86097. ** Synopsis: if fkctr[P1]==0 goto P2
  86098. **
  86099. ** This opcode tests if a foreign key constraint-counter is currently zero.
  86100. ** If so, jump to instruction P2. Otherwise, fall through to the next
  86101. ** instruction.
  86102. **
  86103. ** If P1 is non-zero, then the jump is taken if the database constraint-counter
  86104. ** is zero (the one that counts deferred constraint violations). If P1 is
  86105. ** zero, the jump is taken if the statement constraint-counter is zero
  86106. ** (immediate foreign key constraint violations).
  86107. */
  86108. case OP_FkIfZero: { /* jump */
  86109. if( pOp->p1 ){
  86110. VdbeBranchTaken(db->nDeferredCons==0 && db->nDeferredImmCons==0, 2);
  86111. if( db->nDeferredCons==0 && db->nDeferredImmCons==0 ) goto jump_to_p2;
  86112. }else{
  86113. VdbeBranchTaken(p->nFkConstraint==0 && db->nDeferredImmCons==0, 2);
  86114. if( p->nFkConstraint==0 && db->nDeferredImmCons==0 ) goto jump_to_p2;
  86115. }
  86116. break;
  86117. }
  86118. #endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
  86119. #ifndef SQLITE_OMIT_AUTOINCREMENT
  86120. /* Opcode: MemMax P1 P2 * * *
  86121. ** Synopsis: r[P1]=max(r[P1],r[P2])
  86122. **
  86123. ** P1 is a register in the root frame of this VM (the root frame is
  86124. ** different from the current frame if this instruction is being executed
  86125. ** within a sub-program). Set the value of register P1 to the maximum of
  86126. ** its current value and the value in register P2.
  86127. **
  86128. ** This instruction throws an error if the memory cell is not initially
  86129. ** an integer.
  86130. */
  86131. case OP_MemMax: { /* in2 */
  86132. VdbeFrame *pFrame;
  86133. if( p->pFrame ){
  86134. for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
  86135. pIn1 = &pFrame->aMem[pOp->p1];
  86136. }else{
  86137. pIn1 = &aMem[pOp->p1];
  86138. }
  86139. assert( memIsValid(pIn1) );
  86140. sqlite3VdbeMemIntegerify(pIn1);
  86141. pIn2 = &aMem[pOp->p2];
  86142. sqlite3VdbeMemIntegerify(pIn2);
  86143. if( pIn1->u.i<pIn2->u.i){
  86144. pIn1->u.i = pIn2->u.i;
  86145. }
  86146. break;
  86147. }
  86148. #endif /* SQLITE_OMIT_AUTOINCREMENT */
  86149. /* Opcode: IfPos P1 P2 P3 * *
  86150. ** Synopsis: if r[P1]>0 then r[P1]-=P3, goto P2
  86151. **
  86152. ** Register P1 must contain an integer.
  86153. ** If the value of register P1 is 1 or greater, subtract P3 from the
  86154. ** value in P1 and jump to P2.
  86155. **
  86156. ** If the initial value of register P1 is less than 1, then the
  86157. ** value is unchanged and control passes through to the next instruction.
  86158. */
  86159. case OP_IfPos: { /* jump, in1 */
  86160. pIn1 = &aMem[pOp->p1];
  86161. assert( pIn1->flags&MEM_Int );
  86162. VdbeBranchTaken( pIn1->u.i>0, 2);
  86163. if( pIn1->u.i>0 ){
  86164. pIn1->u.i -= pOp->p3;
  86165. goto jump_to_p2;
  86166. }
  86167. break;
  86168. }
  86169. /* Opcode: OffsetLimit P1 P2 P3 * *
  86170. ** Synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1)
  86171. **
  86172. ** This opcode performs a commonly used computation associated with
  86173. ** LIMIT and OFFSET process. r[P1] holds the limit counter. r[P3]
  86174. ** holds the offset counter. The opcode computes the combined value
  86175. ** of the LIMIT and OFFSET and stores that value in r[P2]. The r[P2]
  86176. ** value computed is the total number of rows that will need to be
  86177. ** visited in order to complete the query.
  86178. **
  86179. ** If r[P3] is zero or negative, that means there is no OFFSET
  86180. ** and r[P2] is set to be the value of the LIMIT, r[P1].
  86181. **
  86182. ** if r[P1] is zero or negative, that means there is no LIMIT
  86183. ** and r[P2] is set to -1.
  86184. **
  86185. ** Otherwise, r[P2] is set to the sum of r[P1] and r[P3].
  86186. */
  86187. case OP_OffsetLimit: { /* in1, out2, in3 */
  86188. i64 x;
  86189. pIn1 = &aMem[pOp->p1];
  86190. pIn3 = &aMem[pOp->p3];
  86191. pOut = out2Prerelease(p, pOp);
  86192. assert( pIn1->flags & MEM_Int );
  86193. assert( pIn3->flags & MEM_Int );
  86194. x = pIn1->u.i;
  86195. if( x<=0 || sqlite3AddInt64(&x, pIn3->u.i>0?pIn3->u.i:0) ){
  86196. /* If the LIMIT is less than or equal to zero, loop forever. This
  86197. ** is documented. But also, if the LIMIT+OFFSET exceeds 2^63 then
  86198. ** also loop forever. This is undocumented. In fact, one could argue
  86199. ** that the loop should terminate. But assuming 1 billion iterations
  86200. ** per second (far exceeding the capabilities of any current hardware)
  86201. ** it would take nearly 300 years to actually reach the limit. So
  86202. ** looping forever is a reasonable approximation. */
  86203. pOut->u.i = -1;
  86204. }else{
  86205. pOut->u.i = x;
  86206. }
  86207. break;
  86208. }
  86209. /* Opcode: IfNotZero P1 P2 * * *
  86210. ** Synopsis: if r[P1]!=0 then r[P1]--, goto P2
  86211. **
  86212. ** Register P1 must contain an integer. If the content of register P1 is
  86213. ** initially greater than zero, then decrement the value in register P1.
  86214. ** If it is non-zero (negative or positive) and then also jump to P2.
  86215. ** If register P1 is initially zero, leave it unchanged and fall through.
  86216. */
  86217. case OP_IfNotZero: { /* jump, in1 */
  86218. pIn1 = &aMem[pOp->p1];
  86219. assert( pIn1->flags&MEM_Int );
  86220. VdbeBranchTaken(pIn1->u.i<0, 2);
  86221. if( pIn1->u.i ){
  86222. if( pIn1->u.i>0 ) pIn1->u.i--;
  86223. goto jump_to_p2;
  86224. }
  86225. break;
  86226. }
  86227. /* Opcode: DecrJumpZero P1 P2 * * *
  86228. ** Synopsis: if (--r[P1])==0 goto P2
  86229. **
  86230. ** Register P1 must hold an integer. Decrement the value in P1
  86231. ** and jump to P2 if the new value is exactly zero.
  86232. */
  86233. case OP_DecrJumpZero: { /* jump, in1 */
  86234. pIn1 = &aMem[pOp->p1];
  86235. assert( pIn1->flags&MEM_Int );
  86236. if( pIn1->u.i>SMALLEST_INT64 ) pIn1->u.i--;
  86237. VdbeBranchTaken(pIn1->u.i==0, 2);
  86238. if( pIn1->u.i==0 ) goto jump_to_p2;
  86239. break;
  86240. }
  86241. /* Opcode: AggStep * P2 P3 P4 P5
  86242. ** Synopsis: accum=r[P3] step(r[P2@P5])
  86243. **
  86244. ** Execute the xStep function for an aggregate.
  86245. ** The function has P5 arguments. P4 is a pointer to the
  86246. ** FuncDef structure that specifies the function. Register P3 is the
  86247. ** accumulator.
  86248. **
  86249. ** The P5 arguments are taken from register P2 and its
  86250. ** successors.
  86251. */
  86252. /* Opcode: AggInverse * P2 P3 P4 P5
  86253. ** Synopsis: accum=r[P3] inverse(r[P2@P5])
  86254. **
  86255. ** Execute the xInverse function for an aggregate.
  86256. ** The function has P5 arguments. P4 is a pointer to the
  86257. ** FuncDef structure that specifies the function. Register P3 is the
  86258. ** accumulator.
  86259. **
  86260. ** The P5 arguments are taken from register P2 and its
  86261. ** successors.
  86262. */
  86263. /* Opcode: AggStep1 P1 P2 P3 P4 P5
  86264. ** Synopsis: accum=r[P3] step(r[P2@P5])
  86265. **
  86266. ** Execute the xStep (if P1==0) or xInverse (if P1!=0) function for an
  86267. ** aggregate. The function has P5 arguments. P4 is a pointer to the
  86268. ** FuncDef structure that specifies the function. Register P3 is the
  86269. ** accumulator.
  86270. **
  86271. ** The P5 arguments are taken from register P2 and its
  86272. ** successors.
  86273. **
  86274. ** This opcode is initially coded as OP_AggStep0. On first evaluation,
  86275. ** the FuncDef stored in P4 is converted into an sqlite3_context and
  86276. ** the opcode is changed. In this way, the initialization of the
  86277. ** sqlite3_context only happens once, instead of on each call to the
  86278. ** step function.
  86279. */
  86280. case OP_AggInverse:
  86281. case OP_AggStep: {
  86282. int n;
  86283. sqlite3_context *pCtx;
  86284. assert( pOp->p4type==P4_FUNCDEF );
  86285. n = pOp->p5;
  86286. assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
  86287. assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem+1 - p->nCursor)+1) );
  86288. assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
  86289. pCtx = sqlite3DbMallocRawNN(db, n*sizeof(sqlite3_value*) +
  86290. (sizeof(pCtx[0]) + sizeof(Mem) - sizeof(sqlite3_value*)));
  86291. if( pCtx==0 ) goto no_mem;
  86292. pCtx->pMem = 0;
  86293. pCtx->pOut = (Mem*)&(pCtx->argv[n]);
  86294. sqlite3VdbeMemInit(pCtx->pOut, db, MEM_Null);
  86295. pCtx->pFunc = pOp->p4.pFunc;
  86296. pCtx->iOp = (int)(pOp - aOp);
  86297. pCtx->pVdbe = p;
  86298. pCtx->skipFlag = 0;
  86299. pCtx->isError = 0;
  86300. pCtx->argc = n;
  86301. pOp->p4type = P4_FUNCCTX;
  86302. pOp->p4.pCtx = pCtx;
  86303. /* OP_AggInverse must have P1==1 and OP_AggStep must have P1==0 */
  86304. assert( pOp->p1==(pOp->opcode==OP_AggInverse) );
  86305. pOp->opcode = OP_AggStep1;
  86306. /* Fall through into OP_AggStep */
  86307. }
  86308. case OP_AggStep1: {
  86309. int i;
  86310. sqlite3_context *pCtx;
  86311. Mem *pMem;
  86312. assert( pOp->p4type==P4_FUNCCTX );
  86313. pCtx = pOp->p4.pCtx;
  86314. pMem = &aMem[pOp->p3];
  86315. #ifdef SQLITE_DEBUG
  86316. if( pOp->p1 ){
  86317. /* This is an OP_AggInverse call. Verify that xStep has always
  86318. ** been called at least once prior to any xInverse call. */
  86319. assert( pMem->uTemp==0x1122e0e3 );
  86320. }else{
  86321. /* This is an OP_AggStep call. Mark it as such. */
  86322. pMem->uTemp = 0x1122e0e3;
  86323. }
  86324. #endif
  86325. /* If this function is inside of a trigger, the register array in aMem[]
  86326. ** might change from one evaluation to the next. The next block of code
  86327. ** checks to see if the register array has changed, and if so it
  86328. ** reinitializes the relavant parts of the sqlite3_context object */
  86329. if( pCtx->pMem != pMem ){
  86330. pCtx->pMem = pMem;
  86331. for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i];
  86332. }
  86333. #ifdef SQLITE_DEBUG
  86334. for(i=0; i<pCtx->argc; i++){
  86335. assert( memIsValid(pCtx->argv[i]) );
  86336. REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]);
  86337. }
  86338. #endif
  86339. pMem->n++;
  86340. assert( pCtx->pOut->flags==MEM_Null );
  86341. assert( pCtx->isError==0 );
  86342. assert( pCtx->skipFlag==0 );
  86343. #ifndef SQLITE_OMIT_WINDOWFUNC
  86344. if( pOp->p1 ){
  86345. (pCtx->pFunc->xInverse)(pCtx,pCtx->argc,pCtx->argv);
  86346. }else
  86347. #endif
  86348. (pCtx->pFunc->xSFunc)(pCtx,pCtx->argc,pCtx->argv); /* IMP: R-24505-23230 */
  86349. if( pCtx->isError ){
  86350. if( pCtx->isError>0 ){
  86351. sqlite3VdbeError(p, "%s", sqlite3_value_text(pCtx->pOut));
  86352. rc = pCtx->isError;
  86353. }
  86354. if( pCtx->skipFlag ){
  86355. assert( pOp[-1].opcode==OP_CollSeq );
  86356. i = pOp[-1].p1;
  86357. if( i ) sqlite3VdbeMemSetInt64(&aMem[i], 1);
  86358. pCtx->skipFlag = 0;
  86359. }
  86360. sqlite3VdbeMemRelease(pCtx->pOut);
  86361. pCtx->pOut->flags = MEM_Null;
  86362. pCtx->isError = 0;
  86363. if( rc ) goto abort_due_to_error;
  86364. }
  86365. assert( pCtx->pOut->flags==MEM_Null );
  86366. assert( pCtx->skipFlag==0 );
  86367. break;
  86368. }
  86369. /* Opcode: AggFinal P1 P2 * P4 *
  86370. ** Synopsis: accum=r[P1] N=P2
  86371. **
  86372. ** P1 is the memory location that is the accumulator for an aggregate
  86373. ** or window function. Execute the finalizer function
  86374. ** for an aggregate and store the result in P1.
  86375. **
  86376. ** P2 is the number of arguments that the step function takes and
  86377. ** P4 is a pointer to the FuncDef for this function. The P2
  86378. ** argument is not used by this opcode. It is only there to disambiguate
  86379. ** functions that can take varying numbers of arguments. The
  86380. ** P4 argument is only needed for the case where
  86381. ** the step function was not previously called.
  86382. */
  86383. /* Opcode: AggValue * P2 P3 P4 *
  86384. ** Synopsis: r[P3]=value N=P2
  86385. **
  86386. ** Invoke the xValue() function and store the result in register P3.
  86387. **
  86388. ** P2 is the number of arguments that the step function takes and
  86389. ** P4 is a pointer to the FuncDef for this function. The P2
  86390. ** argument is not used by this opcode. It is only there to disambiguate
  86391. ** functions that can take varying numbers of arguments. The
  86392. ** P4 argument is only needed for the case where
  86393. ** the step function was not previously called.
  86394. */
  86395. case OP_AggValue:
  86396. case OP_AggFinal: {
  86397. Mem *pMem;
  86398. assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
  86399. assert( pOp->p3==0 || pOp->opcode==OP_AggValue );
  86400. pMem = &aMem[pOp->p1];
  86401. assert( (pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
  86402. #ifndef SQLITE_OMIT_WINDOWFUNC
  86403. if( pOp->p3 ){
  86404. memAboutToChange(p, &aMem[pOp->p3]);
  86405. rc = sqlite3VdbeMemAggValue(pMem, &aMem[pOp->p3], pOp->p4.pFunc);
  86406. pMem = &aMem[pOp->p3];
  86407. }else
  86408. #endif
  86409. {
  86410. rc = sqlite3VdbeMemFinalize(pMem, pOp->p4.pFunc);
  86411. }
  86412. if( rc ){
  86413. sqlite3VdbeError(p, "%s", sqlite3_value_text(pMem));
  86414. goto abort_due_to_error;
  86415. }
  86416. sqlite3VdbeChangeEncoding(pMem, encoding);
  86417. UPDATE_MAX_BLOBSIZE(pMem);
  86418. if( sqlite3VdbeMemTooBig(pMem) ){
  86419. goto too_big;
  86420. }
  86421. break;
  86422. }
  86423. #ifndef SQLITE_OMIT_WAL
  86424. /* Opcode: Checkpoint P1 P2 P3 * *
  86425. **
  86426. ** Checkpoint database P1. This is a no-op if P1 is not currently in
  86427. ** WAL mode. Parameter P2 is one of SQLITE_CHECKPOINT_PASSIVE, FULL,
  86428. ** RESTART, or TRUNCATE. Write 1 or 0 into mem[P3] if the checkpoint returns
  86429. ** SQLITE_BUSY or not, respectively. Write the number of pages in the
  86430. ** WAL after the checkpoint into mem[P3+1] and the number of pages
  86431. ** in the WAL that have been checkpointed after the checkpoint
  86432. ** completes into mem[P3+2]. However on an error, mem[P3+1] and
  86433. ** mem[P3+2] are initialized to -1.
  86434. */
  86435. case OP_Checkpoint: {
  86436. int i; /* Loop counter */
  86437. int aRes[3]; /* Results */
  86438. Mem *pMem; /* Write results here */
  86439. assert( p->readOnly==0 );
  86440. aRes[0] = 0;
  86441. aRes[1] = aRes[2] = -1;
  86442. assert( pOp->p2==SQLITE_CHECKPOINT_PASSIVE
  86443. || pOp->p2==SQLITE_CHECKPOINT_FULL
  86444. || pOp->p2==SQLITE_CHECKPOINT_RESTART
  86445. || pOp->p2==SQLITE_CHECKPOINT_TRUNCATE
  86446. );
  86447. rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &aRes[1], &aRes[2]);
  86448. if( rc ){
  86449. if( rc!=SQLITE_BUSY ) goto abort_due_to_error;
  86450. rc = SQLITE_OK;
  86451. aRes[0] = 1;
  86452. }
  86453. for(i=0, pMem = &aMem[pOp->p3]; i<3; i++, pMem++){
  86454. sqlite3VdbeMemSetInt64(pMem, (i64)aRes[i]);
  86455. }
  86456. break;
  86457. };
  86458. #endif
  86459. #ifndef SQLITE_OMIT_PRAGMA
  86460. /* Opcode: JournalMode P1 P2 P3 * *
  86461. **
  86462. ** Change the journal mode of database P1 to P3. P3 must be one of the
  86463. ** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
  86464. ** modes (delete, truncate, persist, off and memory), this is a simple
  86465. ** operation. No IO is required.
  86466. **
  86467. ** If changing into or out of WAL mode the procedure is more complicated.
  86468. **
  86469. ** Write a string containing the final journal-mode to register P2.
  86470. */
  86471. case OP_JournalMode: { /* out2 */
  86472. Btree *pBt; /* Btree to change journal mode of */
  86473. Pager *pPager; /* Pager associated with pBt */
  86474. int eNew; /* New journal mode */
  86475. int eOld; /* The old journal mode */
  86476. #ifndef SQLITE_OMIT_WAL
  86477. const char *zFilename; /* Name of database file for pPager */
  86478. #endif
  86479. pOut = out2Prerelease(p, pOp);
  86480. eNew = pOp->p3;
  86481. assert( eNew==PAGER_JOURNALMODE_DELETE
  86482. || eNew==PAGER_JOURNALMODE_TRUNCATE
  86483. || eNew==PAGER_JOURNALMODE_PERSIST
  86484. || eNew==PAGER_JOURNALMODE_OFF
  86485. || eNew==PAGER_JOURNALMODE_MEMORY
  86486. || eNew==PAGER_JOURNALMODE_WAL
  86487. || eNew==PAGER_JOURNALMODE_QUERY
  86488. );
  86489. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  86490. assert( p->readOnly==0 );
  86491. pBt = db->aDb[pOp->p1].pBt;
  86492. pPager = sqlite3BtreePager(pBt);
  86493. eOld = sqlite3PagerGetJournalMode(pPager);
  86494. if( eNew==PAGER_JOURNALMODE_QUERY ) eNew = eOld;
  86495. if( !sqlite3PagerOkToChangeJournalMode(pPager) ) eNew = eOld;
  86496. #ifndef SQLITE_OMIT_WAL
  86497. zFilename = sqlite3PagerFilename(pPager, 1);
  86498. /* Do not allow a transition to journal_mode=WAL for a database
  86499. ** in temporary storage or if the VFS does not support shared memory
  86500. */
  86501. if( eNew==PAGER_JOURNALMODE_WAL
  86502. && (sqlite3Strlen30(zFilename)==0 /* Temp file */
  86503. || !sqlite3PagerWalSupported(pPager)) /* No shared-memory support */
  86504. ){
  86505. eNew = eOld;
  86506. }
  86507. if( (eNew!=eOld)
  86508. && (eOld==PAGER_JOURNALMODE_WAL || eNew==PAGER_JOURNALMODE_WAL)
  86509. ){
  86510. if( !db->autoCommit || db->nVdbeRead>1 ){
  86511. rc = SQLITE_ERROR;
  86512. sqlite3VdbeError(p,
  86513. "cannot change %s wal mode from within a transaction",
  86514. (eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
  86515. );
  86516. goto abort_due_to_error;
  86517. }else{
  86518. if( eOld==PAGER_JOURNALMODE_WAL ){
  86519. /* If leaving WAL mode, close the log file. If successful, the call
  86520. ** to PagerCloseWal() checkpoints and deletes the write-ahead-log
  86521. ** file. An EXCLUSIVE lock may still be held on the database file
  86522. ** after a successful return.
  86523. */
  86524. rc = sqlite3PagerCloseWal(pPager, db);
  86525. if( rc==SQLITE_OK ){
  86526. sqlite3PagerSetJournalMode(pPager, eNew);
  86527. }
  86528. }else if( eOld==PAGER_JOURNALMODE_MEMORY ){
  86529. /* Cannot transition directly from MEMORY to WAL. Use mode OFF
  86530. ** as an intermediate */
  86531. sqlite3PagerSetJournalMode(pPager, PAGER_JOURNALMODE_OFF);
  86532. }
  86533. /* Open a transaction on the database file. Regardless of the journal
  86534. ** mode, this transaction always uses a rollback journal.
  86535. */
  86536. assert( sqlite3BtreeIsInTrans(pBt)==0 );
  86537. if( rc==SQLITE_OK ){
  86538. rc = sqlite3BtreeSetVersion(pBt, (eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
  86539. }
  86540. }
  86541. }
  86542. #endif /* ifndef SQLITE_OMIT_WAL */
  86543. if( rc ) eNew = eOld;
  86544. eNew = sqlite3PagerSetJournalMode(pPager, eNew);
  86545. pOut->flags = MEM_Str|MEM_Static|MEM_Term;
  86546. pOut->z = (char *)sqlite3JournalModename(eNew);
  86547. pOut->n = sqlite3Strlen30(pOut->z);
  86548. pOut->enc = SQLITE_UTF8;
  86549. sqlite3VdbeChangeEncoding(pOut, encoding);
  86550. if( rc ) goto abort_due_to_error;
  86551. break;
  86552. };
  86553. #endif /* SQLITE_OMIT_PRAGMA */
  86554. #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
  86555. /* Opcode: Vacuum P1 P2 * * *
  86556. **
  86557. ** Vacuum the entire database P1. P1 is 0 for "main", and 2 or more
  86558. ** for an attached database. The "temp" database may not be vacuumed.
  86559. **
  86560. ** If P2 is not zero, then it is a register holding a string which is
  86561. ** the file into which the result of vacuum should be written. When
  86562. ** P2 is zero, the vacuum overwrites the original database.
  86563. */
  86564. case OP_Vacuum: {
  86565. assert( p->readOnly==0 );
  86566. rc = sqlite3RunVacuum(&p->zErrMsg, db, pOp->p1,
  86567. pOp->p2 ? &aMem[pOp->p2] : 0);
  86568. if( rc ) goto abort_due_to_error;
  86569. break;
  86570. }
  86571. #endif
  86572. #if !defined(SQLITE_OMIT_AUTOVACUUM)
  86573. /* Opcode: IncrVacuum P1 P2 * * *
  86574. **
  86575. ** Perform a single step of the incremental vacuum procedure on
  86576. ** the P1 database. If the vacuum has finished, jump to instruction
  86577. ** P2. Otherwise, fall through to the next instruction.
  86578. */
  86579. case OP_IncrVacuum: { /* jump */
  86580. Btree *pBt;
  86581. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  86582. assert( DbMaskTest(p->btreeMask, pOp->p1) );
  86583. assert( p->readOnly==0 );
  86584. pBt = db->aDb[pOp->p1].pBt;
  86585. rc = sqlite3BtreeIncrVacuum(pBt);
  86586. VdbeBranchTaken(rc==SQLITE_DONE,2);
  86587. if( rc ){
  86588. if( rc!=SQLITE_DONE ) goto abort_due_to_error;
  86589. rc = SQLITE_OK;
  86590. goto jump_to_p2;
  86591. }
  86592. break;
  86593. }
  86594. #endif
  86595. /* Opcode: Expire P1 P2 * * *
  86596. **
  86597. ** Cause precompiled statements to expire. When an expired statement
  86598. ** is executed using sqlite3_step() it will either automatically
  86599. ** reprepare itself (if it was originally created using sqlite3_prepare_v2())
  86600. ** or it will fail with SQLITE_SCHEMA.
  86601. **
  86602. ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
  86603. ** then only the currently executing statement is expired.
  86604. **
  86605. ** If P2 is 0, then SQL statements are expired immediately. If P2 is 1,
  86606. ** then running SQL statements are allowed to continue to run to completion.
  86607. ** The P2==1 case occurs when a CREATE INDEX or similar schema change happens
  86608. ** that might help the statement run faster but which does not affect the
  86609. ** correctness of operation.
  86610. */
  86611. case OP_Expire: {
  86612. assert( pOp->p2==0 || pOp->p2==1 );
  86613. if( !pOp->p1 ){
  86614. sqlite3ExpirePreparedStatements(db, pOp->p2);
  86615. }else{
  86616. p->expired = pOp->p2+1;
  86617. }
  86618. break;
  86619. }
  86620. /* Opcode: CursorLock P1 * * * *
  86621. **
  86622. ** Lock the btree to which cursor P1 is pointing so that the btree cannot be
  86623. ** written by an other cursor.
  86624. */
  86625. case OP_CursorLock: {
  86626. VdbeCursor *pC;
  86627. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  86628. pC = p->apCsr[pOp->p1];
  86629. assert( pC!=0 );
  86630. assert( pC->eCurType==CURTYPE_BTREE );
  86631. sqlite3BtreeCursorPin(pC->uc.pCursor);
  86632. break;
  86633. }
  86634. /* Opcode: CursorUnlock P1 * * * *
  86635. **
  86636. ** Unlock the btree to which cursor P1 is pointing so that it can be
  86637. ** written by other cursors.
  86638. */
  86639. case OP_CursorUnlock: {
  86640. VdbeCursor *pC;
  86641. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  86642. pC = p->apCsr[pOp->p1];
  86643. assert( pC!=0 );
  86644. assert( pC->eCurType==CURTYPE_BTREE );
  86645. sqlite3BtreeCursorUnpin(pC->uc.pCursor);
  86646. break;
  86647. }
  86648. #ifndef SQLITE_OMIT_SHARED_CACHE
  86649. /* Opcode: TableLock P1 P2 P3 P4 *
  86650. ** Synopsis: iDb=P1 root=P2 write=P3
  86651. **
  86652. ** Obtain a lock on a particular table. This instruction is only used when
  86653. ** the shared-cache feature is enabled.
  86654. **
  86655. ** P1 is the index of the database in sqlite3.aDb[] of the database
  86656. ** on which the lock is acquired. A readlock is obtained if P3==0 or
  86657. ** a write lock if P3==1.
  86658. **
  86659. ** P2 contains the root-page of the table to lock.
  86660. **
  86661. ** P4 contains a pointer to the name of the table being locked. This is only
  86662. ** used to generate an error message if the lock cannot be obtained.
  86663. */
  86664. case OP_TableLock: {
  86665. u8 isWriteLock = (u8)pOp->p3;
  86666. if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommit) ){
  86667. int p1 = pOp->p1;
  86668. assert( p1>=0 && p1<db->nDb );
  86669. assert( DbMaskTest(p->btreeMask, p1) );
  86670. assert( isWriteLock==0 || isWriteLock==1 );
  86671. rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
  86672. if( rc ){
  86673. if( (rc&0xFF)==SQLITE_LOCKED ){
  86674. const char *z = pOp->p4.z;
  86675. sqlite3VdbeError(p, "database table is locked: %s", z);
  86676. }
  86677. goto abort_due_to_error;
  86678. }
  86679. }
  86680. break;
  86681. }
  86682. #endif /* SQLITE_OMIT_SHARED_CACHE */
  86683. #ifndef SQLITE_OMIT_VIRTUALTABLE
  86684. /* Opcode: VBegin * * * P4 *
  86685. **
  86686. ** P4 may be a pointer to an sqlite3_vtab structure. If so, call the
  86687. ** xBegin method for that table.
  86688. **
  86689. ** Also, whether or not P4 is set, check that this is not being called from
  86690. ** within a callback to a virtual table xSync() method. If it is, the error
  86691. ** code will be set to SQLITE_LOCKED.
  86692. */
  86693. case OP_VBegin: {
  86694. VTable *pVTab;
  86695. pVTab = pOp->p4.pVtab;
  86696. rc = sqlite3VtabBegin(db, pVTab);
  86697. if( pVTab ) sqlite3VtabImportErrmsg(p, pVTab->pVtab);
  86698. if( rc ) goto abort_due_to_error;
  86699. break;
  86700. }
  86701. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  86702. #ifndef SQLITE_OMIT_VIRTUALTABLE
  86703. /* Opcode: VCreate P1 P2 * * *
  86704. **
  86705. ** P2 is a register that holds the name of a virtual table in database
  86706. ** P1. Call the xCreate method for that table.
  86707. */
  86708. case OP_VCreate: {
  86709. Mem sMem; /* For storing the record being decoded */
  86710. const char *zTab; /* Name of the virtual table */
  86711. memset(&sMem, 0, sizeof(sMem));
  86712. sMem.db = db;
  86713. /* Because P2 is always a static string, it is impossible for the
  86714. ** sqlite3VdbeMemCopy() to fail */
  86715. assert( (aMem[pOp->p2].flags & MEM_Str)!=0 );
  86716. assert( (aMem[pOp->p2].flags & MEM_Static)!=0 );
  86717. rc = sqlite3VdbeMemCopy(&sMem, &aMem[pOp->p2]);
  86718. assert( rc==SQLITE_OK );
  86719. zTab = (const char*)sqlite3_value_text(&sMem);
  86720. assert( zTab || db->mallocFailed );
  86721. if( zTab ){
  86722. rc = sqlite3VtabCallCreate(db, pOp->p1, zTab, &p->zErrMsg);
  86723. }
  86724. sqlite3VdbeMemRelease(&sMem);
  86725. if( rc ) goto abort_due_to_error;
  86726. break;
  86727. }
  86728. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  86729. #ifndef SQLITE_OMIT_VIRTUALTABLE
  86730. /* Opcode: VDestroy P1 * * P4 *
  86731. **
  86732. ** P4 is the name of a virtual table in database P1. Call the xDestroy method
  86733. ** of that table.
  86734. */
  86735. case OP_VDestroy: {
  86736. db->nVDestroy++;
  86737. rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
  86738. db->nVDestroy--;
  86739. assert( p->errorAction==OE_Abort && p->usesStmtJournal );
  86740. if( rc ) goto abort_due_to_error;
  86741. break;
  86742. }
  86743. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  86744. #ifndef SQLITE_OMIT_VIRTUALTABLE
  86745. /* Opcode: VOpen P1 * * P4 *
  86746. **
  86747. ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
  86748. ** P1 is a cursor number. This opcode opens a cursor to the virtual
  86749. ** table and stores that cursor in P1.
  86750. */
  86751. case OP_VOpen: {
  86752. VdbeCursor *pCur;
  86753. sqlite3_vtab_cursor *pVCur;
  86754. sqlite3_vtab *pVtab;
  86755. const sqlite3_module *pModule;
  86756. assert( p->bIsReader );
  86757. pCur = 0;
  86758. pVCur = 0;
  86759. pVtab = pOp->p4.pVtab->pVtab;
  86760. if( pVtab==0 || NEVER(pVtab->pModule==0) ){
  86761. rc = SQLITE_LOCKED;
  86762. goto abort_due_to_error;
  86763. }
  86764. pModule = pVtab->pModule;
  86765. rc = pModule->xOpen(pVtab, &pVCur);
  86766. sqlite3VtabImportErrmsg(p, pVtab);
  86767. if( rc ) goto abort_due_to_error;
  86768. /* Initialize sqlite3_vtab_cursor base class */
  86769. pVCur->pVtab = pVtab;
  86770. /* Initialize vdbe cursor object */
  86771. pCur = allocateCursor(p, pOp->p1, 0, -1, CURTYPE_VTAB);
  86772. if( pCur ){
  86773. pCur->uc.pVCur = pVCur;
  86774. pVtab->nRef++;
  86775. }else{
  86776. assert( db->mallocFailed );
  86777. pModule->xClose(pVCur);
  86778. goto no_mem;
  86779. }
  86780. break;
  86781. }
  86782. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  86783. #ifndef SQLITE_OMIT_VIRTUALTABLE
  86784. /* Opcode: VFilter P1 P2 P3 P4 *
  86785. ** Synopsis: iplan=r[P3] zplan='P4'
  86786. **
  86787. ** P1 is a cursor opened using VOpen. P2 is an address to jump to if
  86788. ** the filtered result set is empty.
  86789. **
  86790. ** P4 is either NULL or a string that was generated by the xBestIndex
  86791. ** method of the module. The interpretation of the P4 string is left
  86792. ** to the module implementation.
  86793. **
  86794. ** This opcode invokes the xFilter method on the virtual table specified
  86795. ** by P1. The integer query plan parameter to xFilter is stored in register
  86796. ** P3. Register P3+1 stores the argc parameter to be passed to the
  86797. ** xFilter method. Registers P3+2..P3+1+argc are the argc
  86798. ** additional parameters which are passed to
  86799. ** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
  86800. **
  86801. ** A jump is made to P2 if the result set after filtering would be empty.
  86802. */
  86803. case OP_VFilter: { /* jump */
  86804. int nArg;
  86805. int iQuery;
  86806. const sqlite3_module *pModule;
  86807. Mem *pQuery;
  86808. Mem *pArgc;
  86809. sqlite3_vtab_cursor *pVCur;
  86810. sqlite3_vtab *pVtab;
  86811. VdbeCursor *pCur;
  86812. int res;
  86813. int i;
  86814. Mem **apArg;
  86815. pQuery = &aMem[pOp->p3];
  86816. pArgc = &pQuery[1];
  86817. pCur = p->apCsr[pOp->p1];
  86818. assert( memIsValid(pQuery) );
  86819. REGISTER_TRACE(pOp->p3, pQuery);
  86820. assert( pCur->eCurType==CURTYPE_VTAB );
  86821. pVCur = pCur->uc.pVCur;
  86822. pVtab = pVCur->pVtab;
  86823. pModule = pVtab->pModule;
  86824. /* Grab the index number and argc parameters */
  86825. assert( (pQuery->flags&MEM_Int)!=0 && pArgc->flags==MEM_Int );
  86826. nArg = (int)pArgc->u.i;
  86827. iQuery = (int)pQuery->u.i;
  86828. /* Invoke the xFilter method */
  86829. res = 0;
  86830. apArg = p->apArg;
  86831. for(i = 0; i<nArg; i++){
  86832. apArg[i] = &pArgc[i+1];
  86833. }
  86834. rc = pModule->xFilter(pVCur, iQuery, pOp->p4.z, nArg, apArg);
  86835. sqlite3VtabImportErrmsg(p, pVtab);
  86836. if( rc ) goto abort_due_to_error;
  86837. res = pModule->xEof(pVCur);
  86838. pCur->nullRow = 0;
  86839. VdbeBranchTaken(res!=0,2);
  86840. if( res ) goto jump_to_p2;
  86841. break;
  86842. }
  86843. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  86844. #ifndef SQLITE_OMIT_VIRTUALTABLE
  86845. /* Opcode: VColumn P1 P2 P3 * P5
  86846. ** Synopsis: r[P3]=vcolumn(P2)
  86847. **
  86848. ** Store in register P3 the value of the P2-th column of
  86849. ** the current row of the virtual-table of cursor P1.
  86850. **
  86851. ** If the VColumn opcode is being used to fetch the value of
  86852. ** an unchanging column during an UPDATE operation, then the P5
  86853. ** value is OPFLAG_NOCHNG. This will cause the sqlite3_vtab_nochange()
  86854. ** function to return true inside the xColumn method of the virtual
  86855. ** table implementation. The P5 column might also contain other
  86856. ** bits (OPFLAG_LENGTHARG or OPFLAG_TYPEOFARG) but those bits are
  86857. ** unused by OP_VColumn.
  86858. */
  86859. case OP_VColumn: {
  86860. sqlite3_vtab *pVtab;
  86861. const sqlite3_module *pModule;
  86862. Mem *pDest;
  86863. sqlite3_context sContext;
  86864. VdbeCursor *pCur = p->apCsr[pOp->p1];
  86865. assert( pCur->eCurType==CURTYPE_VTAB );
  86866. assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
  86867. pDest = &aMem[pOp->p3];
  86868. memAboutToChange(p, pDest);
  86869. if( pCur->nullRow ){
  86870. sqlite3VdbeMemSetNull(pDest);
  86871. break;
  86872. }
  86873. pVtab = pCur->uc.pVCur->pVtab;
  86874. pModule = pVtab->pModule;
  86875. assert( pModule->xColumn );
  86876. memset(&sContext, 0, sizeof(sContext));
  86877. sContext.pOut = pDest;
  86878. assert( pOp->p5==OPFLAG_NOCHNG || pOp->p5==0 );
  86879. if( pOp->p5 & OPFLAG_NOCHNG ){
  86880. sqlite3VdbeMemSetNull(pDest);
  86881. pDest->flags = MEM_Null|MEM_Zero;
  86882. pDest->u.nZero = 0;
  86883. }else{
  86884. MemSetTypeFlag(pDest, MEM_Null);
  86885. }
  86886. rc = pModule->xColumn(pCur->uc.pVCur, &sContext, pOp->p2);
  86887. sqlite3VtabImportErrmsg(p, pVtab);
  86888. if( sContext.isError>0 ){
  86889. sqlite3VdbeError(p, "%s", sqlite3_value_text(pDest));
  86890. rc = sContext.isError;
  86891. }
  86892. sqlite3VdbeChangeEncoding(pDest, encoding);
  86893. REGISTER_TRACE(pOp->p3, pDest);
  86894. UPDATE_MAX_BLOBSIZE(pDest);
  86895. if( sqlite3VdbeMemTooBig(pDest) ){
  86896. goto too_big;
  86897. }
  86898. if( rc ) goto abort_due_to_error;
  86899. break;
  86900. }
  86901. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  86902. #ifndef SQLITE_OMIT_VIRTUALTABLE
  86903. /* Opcode: VNext P1 P2 * * *
  86904. **
  86905. ** Advance virtual table P1 to the next row in its result set and
  86906. ** jump to instruction P2. Or, if the virtual table has reached
  86907. ** the end of its result set, then fall through to the next instruction.
  86908. */
  86909. case OP_VNext: { /* jump */
  86910. sqlite3_vtab *pVtab;
  86911. const sqlite3_module *pModule;
  86912. int res;
  86913. VdbeCursor *pCur;
  86914. res = 0;
  86915. pCur = p->apCsr[pOp->p1];
  86916. assert( pCur->eCurType==CURTYPE_VTAB );
  86917. if( pCur->nullRow ){
  86918. break;
  86919. }
  86920. pVtab = pCur->uc.pVCur->pVtab;
  86921. pModule = pVtab->pModule;
  86922. assert( pModule->xNext );
  86923. /* Invoke the xNext() method of the module. There is no way for the
  86924. ** underlying implementation to return an error if one occurs during
  86925. ** xNext(). Instead, if an error occurs, true is returned (indicating that
  86926. ** data is available) and the error code returned when xColumn or
  86927. ** some other method is next invoked on the save virtual table cursor.
  86928. */
  86929. rc = pModule->xNext(pCur->uc.pVCur);
  86930. sqlite3VtabImportErrmsg(p, pVtab);
  86931. if( rc ) goto abort_due_to_error;
  86932. res = pModule->xEof(pCur->uc.pVCur);
  86933. VdbeBranchTaken(!res,2);
  86934. if( !res ){
  86935. /* If there is data, jump to P2 */
  86936. goto jump_to_p2_and_check_for_interrupt;
  86937. }
  86938. goto check_for_interrupt;
  86939. }
  86940. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  86941. #ifndef SQLITE_OMIT_VIRTUALTABLE
  86942. /* Opcode: VRename P1 * * P4 *
  86943. **
  86944. ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
  86945. ** This opcode invokes the corresponding xRename method. The value
  86946. ** in register P1 is passed as the zName argument to the xRename method.
  86947. */
  86948. case OP_VRename: {
  86949. sqlite3_vtab *pVtab;
  86950. Mem *pName;
  86951. int isLegacy;
  86952. isLegacy = (db->flags & SQLITE_LegacyAlter);
  86953. db->flags |= SQLITE_LegacyAlter;
  86954. pVtab = pOp->p4.pVtab->pVtab;
  86955. pName = &aMem[pOp->p1];
  86956. assert( pVtab->pModule->xRename );
  86957. assert( memIsValid(pName) );
  86958. assert( p->readOnly==0 );
  86959. REGISTER_TRACE(pOp->p1, pName);
  86960. assert( pName->flags & MEM_Str );
  86961. testcase( pName->enc==SQLITE_UTF8 );
  86962. testcase( pName->enc==SQLITE_UTF16BE );
  86963. testcase( pName->enc==SQLITE_UTF16LE );
  86964. rc = sqlite3VdbeChangeEncoding(pName, SQLITE_UTF8);
  86965. if( rc ) goto abort_due_to_error;
  86966. rc = pVtab->pModule->xRename(pVtab, pName->z);
  86967. if( isLegacy==0 ) db->flags &= ~(u64)SQLITE_LegacyAlter;
  86968. sqlite3VtabImportErrmsg(p, pVtab);
  86969. p->expired = 0;
  86970. if( rc ) goto abort_due_to_error;
  86971. break;
  86972. }
  86973. #endif
  86974. #ifndef SQLITE_OMIT_VIRTUALTABLE
  86975. /* Opcode: VUpdate P1 P2 P3 P4 P5
  86976. ** Synopsis: data=r[P3@P2]
  86977. **
  86978. ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
  86979. ** This opcode invokes the corresponding xUpdate method. P2 values
  86980. ** are contiguous memory cells starting at P3 to pass to the xUpdate
  86981. ** invocation. The value in register (P3+P2-1) corresponds to the
  86982. ** p2th element of the argv array passed to xUpdate.
  86983. **
  86984. ** The xUpdate method will do a DELETE or an INSERT or both.
  86985. ** The argv[0] element (which corresponds to memory cell P3)
  86986. ** is the rowid of a row to delete. If argv[0] is NULL then no
  86987. ** deletion occurs. The argv[1] element is the rowid of the new
  86988. ** row. This can be NULL to have the virtual table select the new
  86989. ** rowid for itself. The subsequent elements in the array are
  86990. ** the values of columns in the new row.
  86991. **
  86992. ** If P2==1 then no insert is performed. argv[0] is the rowid of
  86993. ** a row to delete.
  86994. **
  86995. ** P1 is a boolean flag. If it is set to true and the xUpdate call
  86996. ** is successful, then the value returned by sqlite3_last_insert_rowid()
  86997. ** is set to the value of the rowid for the row just inserted.
  86998. **
  86999. ** P5 is the error actions (OE_Replace, OE_Fail, OE_Ignore, etc) to
  87000. ** apply in the case of a constraint failure on an insert or update.
  87001. */
  87002. case OP_VUpdate: {
  87003. sqlite3_vtab *pVtab;
  87004. const sqlite3_module *pModule;
  87005. int nArg;
  87006. int i;
  87007. sqlite_int64 rowid;
  87008. Mem **apArg;
  87009. Mem *pX;
  87010. assert( pOp->p2==1 || pOp->p5==OE_Fail || pOp->p5==OE_Rollback
  87011. || pOp->p5==OE_Abort || pOp->p5==OE_Ignore || pOp->p5==OE_Replace
  87012. );
  87013. assert( p->readOnly==0 );
  87014. if( db->mallocFailed ) goto no_mem;
  87015. sqlite3VdbeIncrWriteCounter(p, 0);
  87016. pVtab = pOp->p4.pVtab->pVtab;
  87017. if( pVtab==0 || NEVER(pVtab->pModule==0) ){
  87018. rc = SQLITE_LOCKED;
  87019. goto abort_due_to_error;
  87020. }
  87021. pModule = pVtab->pModule;
  87022. nArg = pOp->p2;
  87023. assert( pOp->p4type==P4_VTAB );
  87024. if( ALWAYS(pModule->xUpdate) ){
  87025. u8 vtabOnConflict = db->vtabOnConflict;
  87026. apArg = p->apArg;
  87027. pX = &aMem[pOp->p3];
  87028. for(i=0; i<nArg; i++){
  87029. assert( memIsValid(pX) );
  87030. memAboutToChange(p, pX);
  87031. apArg[i] = pX;
  87032. pX++;
  87033. }
  87034. db->vtabOnConflict = pOp->p5;
  87035. rc = pModule->xUpdate(pVtab, nArg, apArg, &rowid);
  87036. db->vtabOnConflict = vtabOnConflict;
  87037. sqlite3VtabImportErrmsg(p, pVtab);
  87038. if( rc==SQLITE_OK && pOp->p1 ){
  87039. assert( nArg>1 && apArg[0] && (apArg[0]->flags&MEM_Null) );
  87040. db->lastRowid = rowid;
  87041. }
  87042. if( (rc&0xff)==SQLITE_CONSTRAINT && pOp->p4.pVtab->bConstraint ){
  87043. if( pOp->p5==OE_Ignore ){
  87044. rc = SQLITE_OK;
  87045. }else{
  87046. p->errorAction = ((pOp->p5==OE_Replace) ? OE_Abort : pOp->p5);
  87047. }
  87048. }else{
  87049. p->nChange++;
  87050. }
  87051. if( rc ) goto abort_due_to_error;
  87052. }
  87053. break;
  87054. }
  87055. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  87056. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  87057. /* Opcode: Pagecount P1 P2 * * *
  87058. **
  87059. ** Write the current number of pages in database P1 to memory cell P2.
  87060. */
  87061. case OP_Pagecount: { /* out2 */
  87062. pOut = out2Prerelease(p, pOp);
  87063. pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt);
  87064. break;
  87065. }
  87066. #endif
  87067. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  87068. /* Opcode: MaxPgcnt P1 P2 P3 * *
  87069. **
  87070. ** Try to set the maximum page count for database P1 to the value in P3.
  87071. ** Do not let the maximum page count fall below the current page count and
  87072. ** do not change the maximum page count value if P3==0.
  87073. **
  87074. ** Store the maximum page count after the change in register P2.
  87075. */
  87076. case OP_MaxPgcnt: { /* out2 */
  87077. unsigned int newMax;
  87078. Btree *pBt;
  87079. pOut = out2Prerelease(p, pOp);
  87080. pBt = db->aDb[pOp->p1].pBt;
  87081. newMax = 0;
  87082. if( pOp->p3 ){
  87083. newMax = sqlite3BtreeLastPage(pBt);
  87084. if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3;
  87085. }
  87086. pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax);
  87087. break;
  87088. }
  87089. #endif
  87090. /* Opcode: Function P1 P2 P3 P4 *
  87091. ** Synopsis: r[P3]=func(r[P2@NP])
  87092. **
  87093. ** Invoke a user function (P4 is a pointer to an sqlite3_context object that
  87094. ** contains a pointer to the function to be run) with arguments taken
  87095. ** from register P2 and successors. The number of arguments is in
  87096. ** the sqlite3_context object that P4 points to.
  87097. ** The result of the function is stored
  87098. ** in register P3. Register P3 must not be one of the function inputs.
  87099. **
  87100. ** P1 is a 32-bit bitmask indicating whether or not each argument to the
  87101. ** function was determined to be constant at compile time. If the first
  87102. ** argument was constant then bit 0 of P1 is set. This is used to determine
  87103. ** whether meta data associated with a user function argument using the
  87104. ** sqlite3_set_auxdata() API may be safely retained until the next
  87105. ** invocation of this opcode.
  87106. **
  87107. ** See also: AggStep, AggFinal, PureFunc
  87108. */
  87109. /* Opcode: PureFunc P1 P2 P3 P4 *
  87110. ** Synopsis: r[P3]=func(r[P2@NP])
  87111. **
  87112. ** Invoke a user function (P4 is a pointer to an sqlite3_context object that
  87113. ** contains a pointer to the function to be run) with arguments taken
  87114. ** from register P2 and successors. The number of arguments is in
  87115. ** the sqlite3_context object that P4 points to.
  87116. ** The result of the function is stored
  87117. ** in register P3. Register P3 must not be one of the function inputs.
  87118. **
  87119. ** P1 is a 32-bit bitmask indicating whether or not each argument to the
  87120. ** function was determined to be constant at compile time. If the first
  87121. ** argument was constant then bit 0 of P1 is set. This is used to determine
  87122. ** whether meta data associated with a user function argument using the
  87123. ** sqlite3_set_auxdata() API may be safely retained until the next
  87124. ** invocation of this opcode.
  87125. **
  87126. ** This opcode works exactly like OP_Function. The only difference is in
  87127. ** its name. This opcode is used in places where the function must be
  87128. ** purely non-deterministic. Some built-in date/time functions can be
  87129. ** either determinitic of non-deterministic, depending on their arguments.
  87130. ** When those function are used in a non-deterministic way, they will check
  87131. ** to see if they were called using OP_PureFunc instead of OP_Function, and
  87132. ** if they were, they throw an error.
  87133. **
  87134. ** See also: AggStep, AggFinal, Function
  87135. */
  87136. case OP_PureFunc: /* group */
  87137. case OP_Function: { /* group */
  87138. int i;
  87139. sqlite3_context *pCtx;
  87140. assert( pOp->p4type==P4_FUNCCTX );
  87141. pCtx = pOp->p4.pCtx;
  87142. /* If this function is inside of a trigger, the register array in aMem[]
  87143. ** might change from one evaluation to the next. The next block of code
  87144. ** checks to see if the register array has changed, and if so it
  87145. ** reinitializes the relavant parts of the sqlite3_context object */
  87146. pOut = &aMem[pOp->p3];
  87147. if( pCtx->pOut != pOut ){
  87148. pCtx->pVdbe = p;
  87149. pCtx->pOut = pOut;
  87150. for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i];
  87151. }
  87152. assert( pCtx->pVdbe==p );
  87153. memAboutToChange(p, pOut);
  87154. #ifdef SQLITE_DEBUG
  87155. for(i=0; i<pCtx->argc; i++){
  87156. assert( memIsValid(pCtx->argv[i]) );
  87157. REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]);
  87158. }
  87159. #endif
  87160. MemSetTypeFlag(pOut, MEM_Null);
  87161. assert( pCtx->isError==0 );
  87162. (*pCtx->pFunc->xSFunc)(pCtx, pCtx->argc, pCtx->argv);/* IMP: R-24505-23230 */
  87163. /* If the function returned an error, throw an exception */
  87164. if( pCtx->isError ){
  87165. if( pCtx->isError>0 ){
  87166. sqlite3VdbeError(p, "%s", sqlite3_value_text(pOut));
  87167. rc = pCtx->isError;
  87168. }
  87169. sqlite3VdbeDeleteAuxData(db, &p->pAuxData, pCtx->iOp, pOp->p1);
  87170. pCtx->isError = 0;
  87171. if( rc ) goto abort_due_to_error;
  87172. }
  87173. /* Copy the result of the function into register P3 */
  87174. if( pOut->flags & (MEM_Str|MEM_Blob) ){
  87175. sqlite3VdbeChangeEncoding(pOut, encoding);
  87176. if( sqlite3VdbeMemTooBig(pOut) ) goto too_big;
  87177. }
  87178. REGISTER_TRACE(pOp->p3, pOut);
  87179. UPDATE_MAX_BLOBSIZE(pOut);
  87180. break;
  87181. }
  87182. /* Opcode: Trace P1 P2 * P4 *
  87183. **
  87184. ** Write P4 on the statement trace output if statement tracing is
  87185. ** enabled.
  87186. **
  87187. ** Operand P1 must be 0x7fffffff and P2 must positive.
  87188. */
  87189. /* Opcode: Init P1 P2 P3 P4 *
  87190. ** Synopsis: Start at P2
  87191. **
  87192. ** Programs contain a single instance of this opcode as the very first
  87193. ** opcode.
  87194. **
  87195. ** If tracing is enabled (by the sqlite3_trace()) interface, then
  87196. ** the UTF-8 string contained in P4 is emitted on the trace callback.
  87197. ** Or if P4 is blank, use the string returned by sqlite3_sql().
  87198. **
  87199. ** If P2 is not zero, jump to instruction P2.
  87200. **
  87201. ** Increment the value of P1 so that OP_Once opcodes will jump the
  87202. ** first time they are evaluated for this run.
  87203. **
  87204. ** If P3 is not zero, then it is an address to jump to if an SQLITE_CORRUPT
  87205. ** error is encountered.
  87206. */
  87207. case OP_Trace:
  87208. case OP_Init: { /* jump */
  87209. int i;
  87210. #ifndef SQLITE_OMIT_TRACE
  87211. char *zTrace;
  87212. #endif
  87213. /* If the P4 argument is not NULL, then it must be an SQL comment string.
  87214. ** The "--" string is broken up to prevent false-positives with srcck1.c.
  87215. **
  87216. ** This assert() provides evidence for:
  87217. ** EVIDENCE-OF: R-50676-09860 The callback can compute the same text that
  87218. ** would have been returned by the legacy sqlite3_trace() interface by
  87219. ** using the X argument when X begins with "--" and invoking
  87220. ** sqlite3_expanded_sql(P) otherwise.
  87221. */
  87222. assert( pOp->p4.z==0 || strncmp(pOp->p4.z, "-" "- ", 3)==0 );
  87223. /* OP_Init is always instruction 0 */
  87224. assert( pOp==p->aOp || pOp->opcode==OP_Trace );
  87225. #ifndef SQLITE_OMIT_TRACE
  87226. if( (db->mTrace & (SQLITE_TRACE_STMT|SQLITE_TRACE_LEGACY))!=0
  87227. && !p->doingRerun
  87228. && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
  87229. ){
  87230. #ifndef SQLITE_OMIT_DEPRECATED
  87231. if( db->mTrace & SQLITE_TRACE_LEGACY ){
  87232. void (*x)(void*,const char*) = (void(*)(void*,const char*))db->xTrace;
  87233. char *z = sqlite3VdbeExpandSql(p, zTrace);
  87234. x(db->pTraceArg, z);
  87235. sqlite3_free(z);
  87236. }else
  87237. #endif
  87238. if( db->nVdbeExec>1 ){
  87239. char *z = sqlite3MPrintf(db, "-- %s", zTrace);
  87240. (void)db->xTrace(SQLITE_TRACE_STMT, db->pTraceArg, p, z);
  87241. sqlite3DbFree(db, z);
  87242. }else{
  87243. (void)db->xTrace(SQLITE_TRACE_STMT, db->pTraceArg, p, zTrace);
  87244. }
  87245. }
  87246. #ifdef SQLITE_USE_FCNTL_TRACE
  87247. zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql);
  87248. if( zTrace ){
  87249. int j;
  87250. for(j=0; j<db->nDb; j++){
  87251. if( DbMaskTest(p->btreeMask, j)==0 ) continue;
  87252. sqlite3_file_control(db, db->aDb[j].zDbSName, SQLITE_FCNTL_TRACE, zTrace);
  87253. }
  87254. }
  87255. #endif /* SQLITE_USE_FCNTL_TRACE */
  87256. #ifdef SQLITE_DEBUG
  87257. if( (db->flags & SQLITE_SqlTrace)!=0
  87258. && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
  87259. ){
  87260. sqlite3DebugPrintf("SQL-trace: %s\n", zTrace);
  87261. }
  87262. #endif /* SQLITE_DEBUG */
  87263. #endif /* SQLITE_OMIT_TRACE */
  87264. assert( pOp->p2>0 );
  87265. if( pOp->p1>=sqlite3GlobalConfig.iOnceResetThreshold ){
  87266. if( pOp->opcode==OP_Trace ) break;
  87267. for(i=1; i<p->nOp; i++){
  87268. if( p->aOp[i].opcode==OP_Once ) p->aOp[i].p1 = 0;
  87269. }
  87270. pOp->p1 = 0;
  87271. }
  87272. pOp->p1++;
  87273. p->aCounter[SQLITE_STMTSTATUS_RUN]++;
  87274. goto jump_to_p2;
  87275. }
  87276. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  87277. /* Opcode: CursorHint P1 * * P4 *
  87278. **
  87279. ** Provide a hint to cursor P1 that it only needs to return rows that
  87280. ** satisfy the Expr in P4. TK_REGISTER terms in the P4 expression refer
  87281. ** to values currently held in registers. TK_COLUMN terms in the P4
  87282. ** expression refer to columns in the b-tree to which cursor P1 is pointing.
  87283. */
  87284. case OP_CursorHint: {
  87285. VdbeCursor *pC;
  87286. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  87287. assert( pOp->p4type==P4_EXPR );
  87288. pC = p->apCsr[pOp->p1];
  87289. if( pC ){
  87290. assert( pC->eCurType==CURTYPE_BTREE );
  87291. sqlite3BtreeCursorHint(pC->uc.pCursor, BTREE_HINT_RANGE,
  87292. pOp->p4.pExpr, aMem);
  87293. }
  87294. break;
  87295. }
  87296. #endif /* SQLITE_ENABLE_CURSOR_HINTS */
  87297. #ifdef SQLITE_DEBUG
  87298. /* Opcode: Abortable * * * * *
  87299. **
  87300. ** Verify that an Abort can happen. Assert if an Abort at this point
  87301. ** might cause database corruption. This opcode only appears in debugging
  87302. ** builds.
  87303. **
  87304. ** An Abort is safe if either there have been no writes, or if there is
  87305. ** an active statement journal.
  87306. */
  87307. case OP_Abortable: {
  87308. sqlite3VdbeAssertAbortable(p);
  87309. break;
  87310. }
  87311. #endif
  87312. #ifdef SQLITE_DEBUG
  87313. /* Opcode: ReleaseReg P1 P2 P3 * P5
  87314. ** Synopsis: release r[P1@P2] mask P3
  87315. **
  87316. ** Release registers from service. Any content that was in the
  87317. ** the registers is unreliable after this opcode completes.
  87318. **
  87319. ** The registers released will be the P2 registers starting at P1,
  87320. ** except if bit ii of P3 set, then do not release register P1+ii.
  87321. ** In other words, P3 is a mask of registers to preserve.
  87322. **
  87323. ** Releasing a register clears the Mem.pScopyFrom pointer. That means
  87324. ** that if the content of the released register was set using OP_SCopy,
  87325. ** a change to the value of the source register for the OP_SCopy will no longer
  87326. ** generate an assertion fault in sqlite3VdbeMemAboutToChange().
  87327. **
  87328. ** If P5 is set, then all released registers have their type set
  87329. ** to MEM_Undefined so that any subsequent attempt to read the released
  87330. ** register (before it is reinitialized) will generate an assertion fault.
  87331. **
  87332. ** P5 ought to be set on every call to this opcode.
  87333. ** However, there are places in the code generator will release registers
  87334. ** before their are used, under the (valid) assumption that the registers
  87335. ** will not be reallocated for some other purpose before they are used and
  87336. ** hence are safe to release.
  87337. **
  87338. ** This opcode is only available in testing and debugging builds. It is
  87339. ** not generated for release builds. The purpose of this opcode is to help
  87340. ** validate the generated bytecode. This opcode does not actually contribute
  87341. ** to computing an answer.
  87342. */
  87343. case OP_ReleaseReg: {
  87344. Mem *pMem;
  87345. int i;
  87346. u32 constMask;
  87347. assert( pOp->p1>0 );
  87348. assert( pOp->p1+pOp->p2<=(p->nMem+1 - p->nCursor)+1 );
  87349. pMem = &aMem[pOp->p1];
  87350. constMask = pOp->p3;
  87351. for(i=0; i<pOp->p2; i++, pMem++){
  87352. if( i>=32 || (constMask & MASKBIT32(i))==0 ){
  87353. pMem->pScopyFrom = 0;
  87354. if( i<32 && pOp->p5 ) MemSetTypeFlag(pMem, MEM_Undefined);
  87355. }
  87356. }
  87357. break;
  87358. }
  87359. #endif
  87360. /* Opcode: Noop * * * * *
  87361. **
  87362. ** Do nothing. This instruction is often useful as a jump
  87363. ** destination.
  87364. */
  87365. /*
  87366. ** The magic Explain opcode are only inserted when explain==2 (which
  87367. ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
  87368. ** This opcode records information from the optimizer. It is the
  87369. ** the same as a no-op. This opcodesnever appears in a real VM program.
  87370. */
  87371. default: { /* This is really OP_Noop, OP_Explain */
  87372. assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
  87373. break;
  87374. }
  87375. /*****************************************************************************
  87376. ** The cases of the switch statement above this line should all be indented
  87377. ** by 6 spaces. But the left-most 6 spaces have been removed to improve the
  87378. ** readability. From this point on down, the normal indentation rules are
  87379. ** restored.
  87380. *****************************************************************************/
  87381. }
  87382. #ifdef VDBE_PROFILE
  87383. {
  87384. u64 endTime = sqlite3NProfileCnt ? sqlite3NProfileCnt : sqlite3Hwtime();
  87385. if( endTime>start ) pOrigOp->cycles += endTime - start;
  87386. pOrigOp->cnt++;
  87387. }
  87388. #endif
  87389. /* The following code adds nothing to the actual functionality
  87390. ** of the program. It is only here for testing and debugging.
  87391. ** On the other hand, it does burn CPU cycles every time through
  87392. ** the evaluator loop. So we can leave it out when NDEBUG is defined.
  87393. */
  87394. #ifndef NDEBUG
  87395. assert( pOp>=&aOp[-1] && pOp<&aOp[p->nOp-1] );
  87396. #ifdef SQLITE_DEBUG
  87397. if( db->flags & SQLITE_VdbeTrace ){
  87398. u8 opProperty = sqlite3OpcodeProperty[pOrigOp->opcode];
  87399. if( rc!=0 ) printf("rc=%d\n",rc);
  87400. if( opProperty & (OPFLG_OUT2) ){
  87401. registerTrace(pOrigOp->p2, &aMem[pOrigOp->p2]);
  87402. }
  87403. if( opProperty & OPFLG_OUT3 ){
  87404. registerTrace(pOrigOp->p3, &aMem[pOrigOp->p3]);
  87405. }
  87406. if( opProperty==0xff ){
  87407. /* Never happens. This code exists to avoid a harmless linkage
  87408. ** warning aboud sqlite3VdbeRegisterDump() being defined but not
  87409. ** used. */
  87410. sqlite3VdbeRegisterDump(p);
  87411. }
  87412. }
  87413. #endif /* SQLITE_DEBUG */
  87414. #endif /* NDEBUG */
  87415. } /* The end of the for(;;) loop the loops through opcodes */
  87416. /* If we reach this point, it means that execution is finished with
  87417. ** an error of some kind.
  87418. */
  87419. abort_due_to_error:
  87420. if( db->mallocFailed ) rc = SQLITE_NOMEM_BKPT;
  87421. assert( rc );
  87422. if( p->zErrMsg==0 && rc!=SQLITE_IOERR_NOMEM ){
  87423. sqlite3VdbeError(p, "%s", sqlite3ErrStr(rc));
  87424. }
  87425. p->rc = rc;
  87426. sqlite3SystemError(db, rc);
  87427. testcase( sqlite3GlobalConfig.xLog!=0 );
  87428. sqlite3_log(rc, "statement aborts at %d: [%s] %s",
  87429. (int)(pOp - aOp), p->zSql, p->zErrMsg);
  87430. sqlite3VdbeHalt(p);
  87431. if( rc==SQLITE_IOERR_NOMEM ) sqlite3OomFault(db);
  87432. rc = SQLITE_ERROR;
  87433. if( resetSchemaOnFault>0 ){
  87434. sqlite3ResetOneSchema(db, resetSchemaOnFault-1);
  87435. }
  87436. /* This is the only way out of this procedure. We have to
  87437. ** release the mutexes on btrees that were acquired at the
  87438. ** top. */
  87439. vdbe_return:
  87440. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  87441. while( nVmStep>=nProgressLimit && db->xProgress!=0 ){
  87442. nProgressLimit += db->nProgressOps;
  87443. if( db->xProgress(db->pProgressArg) ){
  87444. nProgressLimit = 0xffffffff;
  87445. rc = SQLITE_INTERRUPT;
  87446. goto abort_due_to_error;
  87447. }
  87448. }
  87449. #endif
  87450. p->aCounter[SQLITE_STMTSTATUS_VM_STEP] += (int)nVmStep;
  87451. sqlite3VdbeLeave(p);
  87452. assert( rc!=SQLITE_OK || nExtraDelete==0
  87453. || sqlite3_strlike("DELETE%",p->zSql,0)!=0
  87454. );
  87455. return rc;
  87456. /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
  87457. ** is encountered.
  87458. */
  87459. too_big:
  87460. sqlite3VdbeError(p, "string or blob too big");
  87461. rc = SQLITE_TOOBIG;
  87462. goto abort_due_to_error;
  87463. /* Jump to here if a malloc() fails.
  87464. */
  87465. no_mem:
  87466. sqlite3OomFault(db);
  87467. sqlite3VdbeError(p, "out of memory");
  87468. rc = SQLITE_NOMEM_BKPT;
  87469. goto abort_due_to_error;
  87470. /* Jump to here if the sqlite3_interrupt() API sets the interrupt
  87471. ** flag.
  87472. */
  87473. abort_due_to_interrupt:
  87474. assert( AtomicLoad(&db->u1.isInterrupted) );
  87475. rc = db->mallocFailed ? SQLITE_NOMEM_BKPT : SQLITE_INTERRUPT;
  87476. p->rc = rc;
  87477. sqlite3VdbeError(p, "%s", sqlite3ErrStr(rc));
  87478. goto abort_due_to_error;
  87479. }
  87480. /************** End of vdbe.c ************************************************/
  87481. /************** Begin file vdbeblob.c ****************************************/
  87482. /*
  87483. ** 2007 May 1
  87484. **
  87485. ** The author disclaims copyright to this source code. In place of
  87486. ** a legal notice, here is a blessing:
  87487. **
  87488. ** May you do good and not evil.
  87489. ** May you find forgiveness for yourself and forgive others.
  87490. ** May you share freely, never taking more than you give.
  87491. **
  87492. *************************************************************************
  87493. **
  87494. ** This file contains code used to implement incremental BLOB I/O.
  87495. */
  87496. /* #include "sqliteInt.h" */
  87497. /* #include "vdbeInt.h" */
  87498. #ifndef SQLITE_OMIT_INCRBLOB
  87499. /*
  87500. ** Valid sqlite3_blob* handles point to Incrblob structures.
  87501. */
  87502. typedef struct Incrblob Incrblob;
  87503. struct Incrblob {
  87504. int nByte; /* Size of open blob, in bytes */
  87505. int iOffset; /* Byte offset of blob in cursor data */
  87506. u16 iCol; /* Table column this handle is open on */
  87507. BtCursor *pCsr; /* Cursor pointing at blob row */
  87508. sqlite3_stmt *pStmt; /* Statement holding cursor open */
  87509. sqlite3 *db; /* The associated database */
  87510. char *zDb; /* Database name */
  87511. Table *pTab; /* Table object */
  87512. };
  87513. /*
  87514. ** This function is used by both blob_open() and blob_reopen(). It seeks
  87515. ** the b-tree cursor associated with blob handle p to point to row iRow.
  87516. ** If successful, SQLITE_OK is returned and subsequent calls to
  87517. ** sqlite3_blob_read() or sqlite3_blob_write() access the specified row.
  87518. **
  87519. ** If an error occurs, or if the specified row does not exist or does not
  87520. ** contain a value of type TEXT or BLOB in the column nominated when the
  87521. ** blob handle was opened, then an error code is returned and *pzErr may
  87522. ** be set to point to a buffer containing an error message. It is the
  87523. ** responsibility of the caller to free the error message buffer using
  87524. ** sqlite3DbFree().
  87525. **
  87526. ** If an error does occur, then the b-tree cursor is closed. All subsequent
  87527. ** calls to sqlite3_blob_read(), blob_write() or blob_reopen() will
  87528. ** immediately return SQLITE_ABORT.
  87529. */
  87530. static int blobSeekToRow(Incrblob *p, sqlite3_int64 iRow, char **pzErr){
  87531. int rc; /* Error code */
  87532. char *zErr = 0; /* Error message */
  87533. Vdbe *v = (Vdbe *)p->pStmt;
  87534. /* Set the value of register r[1] in the SQL statement to integer iRow.
  87535. ** This is done directly as a performance optimization
  87536. */
  87537. v->aMem[1].flags = MEM_Int;
  87538. v->aMem[1].u.i = iRow;
  87539. /* If the statement has been run before (and is paused at the OP_ResultRow)
  87540. ** then back it up to the point where it does the OP_NotExists. This could
  87541. ** have been down with an extra OP_Goto, but simply setting the program
  87542. ** counter is faster. */
  87543. if( v->pc>4 ){
  87544. v->pc = 4;
  87545. assert( v->aOp[v->pc].opcode==OP_NotExists );
  87546. rc = sqlite3VdbeExec(v);
  87547. }else{
  87548. rc = sqlite3_step(p->pStmt);
  87549. }
  87550. if( rc==SQLITE_ROW ){
  87551. VdbeCursor *pC = v->apCsr[0];
  87552. u32 type = pC->nHdrParsed>p->iCol ? pC->aType[p->iCol] : 0;
  87553. testcase( pC->nHdrParsed==p->iCol );
  87554. testcase( pC->nHdrParsed==p->iCol+1 );
  87555. if( type<12 ){
  87556. zErr = sqlite3MPrintf(p->db, "cannot open value of type %s",
  87557. type==0?"null": type==7?"real": "integer"
  87558. );
  87559. rc = SQLITE_ERROR;
  87560. sqlite3_finalize(p->pStmt);
  87561. p->pStmt = 0;
  87562. }else{
  87563. p->iOffset = pC->aType[p->iCol + pC->nField];
  87564. p->nByte = sqlite3VdbeSerialTypeLen(type);
  87565. p->pCsr = pC->uc.pCursor;
  87566. sqlite3BtreeIncrblobCursor(p->pCsr);
  87567. }
  87568. }
  87569. if( rc==SQLITE_ROW ){
  87570. rc = SQLITE_OK;
  87571. }else if( p->pStmt ){
  87572. rc = sqlite3_finalize(p->pStmt);
  87573. p->pStmt = 0;
  87574. if( rc==SQLITE_OK ){
  87575. zErr = sqlite3MPrintf(p->db, "no such rowid: %lld", iRow);
  87576. rc = SQLITE_ERROR;
  87577. }else{
  87578. zErr = sqlite3MPrintf(p->db, "%s", sqlite3_errmsg(p->db));
  87579. }
  87580. }
  87581. assert( rc!=SQLITE_OK || zErr==0 );
  87582. assert( rc!=SQLITE_ROW && rc!=SQLITE_DONE );
  87583. *pzErr = zErr;
  87584. return rc;
  87585. }
  87586. /*
  87587. ** Open a blob handle.
  87588. */
  87589. SQLITE_API int sqlite3_blob_open(
  87590. sqlite3* db, /* The database connection */
  87591. const char *zDb, /* The attached database containing the blob */
  87592. const char *zTable, /* The table containing the blob */
  87593. const char *zColumn, /* The column containing the blob */
  87594. sqlite_int64 iRow, /* The row containing the glob */
  87595. int wrFlag, /* True -> read/write access, false -> read-only */
  87596. sqlite3_blob **ppBlob /* Handle for accessing the blob returned here */
  87597. ){
  87598. int nAttempt = 0;
  87599. int iCol; /* Index of zColumn in row-record */
  87600. int rc = SQLITE_OK;
  87601. char *zErr = 0;
  87602. Table *pTab;
  87603. Incrblob *pBlob = 0;
  87604. Parse sParse;
  87605. #ifdef SQLITE_ENABLE_API_ARMOR
  87606. if( ppBlob==0 ){
  87607. return SQLITE_MISUSE_BKPT;
  87608. }
  87609. #endif
  87610. *ppBlob = 0;
  87611. #ifdef SQLITE_ENABLE_API_ARMOR
  87612. if( !sqlite3SafetyCheckOk(db) || zTable==0 ){
  87613. return SQLITE_MISUSE_BKPT;
  87614. }
  87615. #endif
  87616. wrFlag = !!wrFlag; /* wrFlag = (wrFlag ? 1 : 0); */
  87617. sqlite3_mutex_enter(db->mutex);
  87618. pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
  87619. do {
  87620. memset(&sParse, 0, sizeof(Parse));
  87621. if( !pBlob ) goto blob_open_out;
  87622. sParse.db = db;
  87623. sqlite3DbFree(db, zErr);
  87624. zErr = 0;
  87625. sqlite3BtreeEnterAll(db);
  87626. pTab = sqlite3LocateTable(&sParse, 0, zTable, zDb);
  87627. if( pTab && IsVirtual(pTab) ){
  87628. pTab = 0;
  87629. sqlite3ErrorMsg(&sParse, "cannot open virtual table: %s", zTable);
  87630. }
  87631. if( pTab && !HasRowid(pTab) ){
  87632. pTab = 0;
  87633. sqlite3ErrorMsg(&sParse, "cannot open table without rowid: %s", zTable);
  87634. }
  87635. #ifndef SQLITE_OMIT_VIEW
  87636. if( pTab && pTab->pSelect ){
  87637. pTab = 0;
  87638. sqlite3ErrorMsg(&sParse, "cannot open view: %s", zTable);
  87639. }
  87640. #endif
  87641. if( !pTab ){
  87642. if( sParse.zErrMsg ){
  87643. sqlite3DbFree(db, zErr);
  87644. zErr = sParse.zErrMsg;
  87645. sParse.zErrMsg = 0;
  87646. }
  87647. rc = SQLITE_ERROR;
  87648. sqlite3BtreeLeaveAll(db);
  87649. goto blob_open_out;
  87650. }
  87651. pBlob->pTab = pTab;
  87652. pBlob->zDb = db->aDb[sqlite3SchemaToIndex(db, pTab->pSchema)].zDbSName;
  87653. /* Now search pTab for the exact column. */
  87654. for(iCol=0; iCol<pTab->nCol; iCol++) {
  87655. if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
  87656. break;
  87657. }
  87658. }
  87659. if( iCol==pTab->nCol ){
  87660. sqlite3DbFree(db, zErr);
  87661. zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn);
  87662. rc = SQLITE_ERROR;
  87663. sqlite3BtreeLeaveAll(db);
  87664. goto blob_open_out;
  87665. }
  87666. /* If the value is being opened for writing, check that the
  87667. ** column is not indexed, and that it is not part of a foreign key.
  87668. */
  87669. if( wrFlag ){
  87670. const char *zFault = 0;
  87671. Index *pIdx;
  87672. #ifndef SQLITE_OMIT_FOREIGN_KEY
  87673. if( db->flags&SQLITE_ForeignKeys ){
  87674. /* Check that the column is not part of an FK child key definition. It
  87675. ** is not necessary to check if it is part of a parent key, as parent
  87676. ** key columns must be indexed. The check below will pick up this
  87677. ** case. */
  87678. FKey *pFKey;
  87679. for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
  87680. int j;
  87681. for(j=0; j<pFKey->nCol; j++){
  87682. if( pFKey->aCol[j].iFrom==iCol ){
  87683. zFault = "foreign key";
  87684. }
  87685. }
  87686. }
  87687. }
  87688. #endif
  87689. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  87690. int j;
  87691. for(j=0; j<pIdx->nKeyCol; j++){
  87692. /* FIXME: Be smarter about indexes that use expressions */
  87693. if( pIdx->aiColumn[j]==iCol || pIdx->aiColumn[j]==XN_EXPR ){
  87694. zFault = "indexed";
  87695. }
  87696. }
  87697. }
  87698. if( zFault ){
  87699. sqlite3DbFree(db, zErr);
  87700. zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault);
  87701. rc = SQLITE_ERROR;
  87702. sqlite3BtreeLeaveAll(db);
  87703. goto blob_open_out;
  87704. }
  87705. }
  87706. pBlob->pStmt = (sqlite3_stmt *)sqlite3VdbeCreate(&sParse);
  87707. assert( pBlob->pStmt || db->mallocFailed );
  87708. if( pBlob->pStmt ){
  87709. /* This VDBE program seeks a btree cursor to the identified
  87710. ** db/table/row entry. The reason for using a vdbe program instead
  87711. ** of writing code to use the b-tree layer directly is that the
  87712. ** vdbe program will take advantage of the various transaction,
  87713. ** locking and error handling infrastructure built into the vdbe.
  87714. **
  87715. ** After seeking the cursor, the vdbe executes an OP_ResultRow.
  87716. ** Code external to the Vdbe then "borrows" the b-tree cursor and
  87717. ** uses it to implement the blob_read(), blob_write() and
  87718. ** blob_bytes() functions.
  87719. **
  87720. ** The sqlite3_blob_close() function finalizes the vdbe program,
  87721. ** which closes the b-tree cursor and (possibly) commits the
  87722. ** transaction.
  87723. */
  87724. static const int iLn = VDBE_OFFSET_LINENO(2);
  87725. static const VdbeOpList openBlob[] = {
  87726. {OP_TableLock, 0, 0, 0}, /* 0: Acquire a read or write lock */
  87727. {OP_OpenRead, 0, 0, 0}, /* 1: Open a cursor */
  87728. /* blobSeekToRow() will initialize r[1] to the desired rowid */
  87729. {OP_NotExists, 0, 5, 1}, /* 2: Seek the cursor to rowid=r[1] */
  87730. {OP_Column, 0, 0, 1}, /* 3 */
  87731. {OP_ResultRow, 1, 0, 0}, /* 4 */
  87732. {OP_Halt, 0, 0, 0}, /* 5 */
  87733. };
  87734. Vdbe *v = (Vdbe *)pBlob->pStmt;
  87735. int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  87736. VdbeOp *aOp;
  87737. sqlite3VdbeAddOp4Int(v, OP_Transaction, iDb, wrFlag,
  87738. pTab->pSchema->schema_cookie,
  87739. pTab->pSchema->iGeneration);
  87740. sqlite3VdbeChangeP5(v, 1);
  87741. assert( sqlite3VdbeCurrentAddr(v)==2 || db->mallocFailed );
  87742. aOp = sqlite3VdbeAddOpList(v, ArraySize(openBlob), openBlob, iLn);
  87743. /* Make sure a mutex is held on the table to be accessed */
  87744. sqlite3VdbeUsesBtree(v, iDb);
  87745. if( db->mallocFailed==0 ){
  87746. assert( aOp!=0 );
  87747. /* Configure the OP_TableLock instruction */
  87748. #ifdef SQLITE_OMIT_SHARED_CACHE
  87749. aOp[0].opcode = OP_Noop;
  87750. #else
  87751. aOp[0].p1 = iDb;
  87752. aOp[0].p2 = pTab->tnum;
  87753. aOp[0].p3 = wrFlag;
  87754. sqlite3VdbeChangeP4(v, 2, pTab->zName, P4_TRANSIENT);
  87755. }
  87756. if( db->mallocFailed==0 ){
  87757. #endif
  87758. /* Remove either the OP_OpenWrite or OpenRead. Set the P2
  87759. ** parameter of the other to pTab->tnum. */
  87760. if( wrFlag ) aOp[1].opcode = OP_OpenWrite;
  87761. aOp[1].p2 = pTab->tnum;
  87762. aOp[1].p3 = iDb;
  87763. /* Configure the number of columns. Configure the cursor to
  87764. ** think that the table has one more column than it really
  87765. ** does. An OP_Column to retrieve this imaginary column will
  87766. ** always return an SQL NULL. This is useful because it means
  87767. ** we can invoke OP_Column to fill in the vdbe cursors type
  87768. ** and offset cache without causing any IO.
  87769. */
  87770. aOp[1].p4type = P4_INT32;
  87771. aOp[1].p4.i = pTab->nCol+1;
  87772. aOp[3].p2 = pTab->nCol;
  87773. sParse.nVar = 0;
  87774. sParse.nMem = 1;
  87775. sParse.nTab = 1;
  87776. sqlite3VdbeMakeReady(v, &sParse);
  87777. }
  87778. }
  87779. pBlob->iCol = iCol;
  87780. pBlob->db = db;
  87781. sqlite3BtreeLeaveAll(db);
  87782. if( db->mallocFailed ){
  87783. goto blob_open_out;
  87784. }
  87785. rc = blobSeekToRow(pBlob, iRow, &zErr);
  87786. } while( (++nAttempt)<SQLITE_MAX_SCHEMA_RETRY && rc==SQLITE_SCHEMA );
  87787. blob_open_out:
  87788. if( rc==SQLITE_OK && db->mallocFailed==0 ){
  87789. *ppBlob = (sqlite3_blob *)pBlob;
  87790. }else{
  87791. if( pBlob && pBlob->pStmt ) sqlite3VdbeFinalize((Vdbe *)pBlob->pStmt);
  87792. sqlite3DbFree(db, pBlob);
  87793. }
  87794. sqlite3ErrorWithMsg(db, rc, (zErr ? "%s" : 0), zErr);
  87795. sqlite3DbFree(db, zErr);
  87796. sqlite3ParserReset(&sParse);
  87797. rc = sqlite3ApiExit(db, rc);
  87798. sqlite3_mutex_leave(db->mutex);
  87799. return rc;
  87800. }
  87801. /*
  87802. ** Close a blob handle that was previously created using
  87803. ** sqlite3_blob_open().
  87804. */
  87805. SQLITE_API int sqlite3_blob_close(sqlite3_blob *pBlob){
  87806. Incrblob *p = (Incrblob *)pBlob;
  87807. int rc;
  87808. sqlite3 *db;
  87809. if( p ){
  87810. sqlite3_stmt *pStmt = p->pStmt;
  87811. db = p->db;
  87812. sqlite3_mutex_enter(db->mutex);
  87813. sqlite3DbFree(db, p);
  87814. sqlite3_mutex_leave(db->mutex);
  87815. rc = sqlite3_finalize(pStmt);
  87816. }else{
  87817. rc = SQLITE_OK;
  87818. }
  87819. return rc;
  87820. }
  87821. /*
  87822. ** Perform a read or write operation on a blob
  87823. */
  87824. static int blobReadWrite(
  87825. sqlite3_blob *pBlob,
  87826. void *z,
  87827. int n,
  87828. int iOffset,
  87829. int (*xCall)(BtCursor*, u32, u32, void*)
  87830. ){
  87831. int rc;
  87832. Incrblob *p = (Incrblob *)pBlob;
  87833. Vdbe *v;
  87834. sqlite3 *db;
  87835. if( p==0 ) return SQLITE_MISUSE_BKPT;
  87836. db = p->db;
  87837. sqlite3_mutex_enter(db->mutex);
  87838. v = (Vdbe*)p->pStmt;
  87839. if( n<0 || iOffset<0 || ((sqlite3_int64)iOffset+n)>p->nByte ){
  87840. /* Request is out of range. Return a transient error. */
  87841. rc = SQLITE_ERROR;
  87842. }else if( v==0 ){
  87843. /* If there is no statement handle, then the blob-handle has
  87844. ** already been invalidated. Return SQLITE_ABORT in this case.
  87845. */
  87846. rc = SQLITE_ABORT;
  87847. }else{
  87848. /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
  87849. ** returned, clean-up the statement handle.
  87850. */
  87851. assert( db == v->db );
  87852. sqlite3BtreeEnterCursor(p->pCsr);
  87853. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  87854. if( xCall==sqlite3BtreePutData && db->xPreUpdateCallback ){
  87855. /* If a pre-update hook is registered and this is a write cursor,
  87856. ** invoke it here.
  87857. **
  87858. ** TODO: The preupdate-hook is passed SQLITE_DELETE, even though this
  87859. ** operation should really be an SQLITE_UPDATE. This is probably
  87860. ** incorrect, but is convenient because at this point the new.* values
  87861. ** are not easily obtainable. And for the sessions module, an
  87862. ** SQLITE_UPDATE where the PK columns do not change is handled in the
  87863. ** same way as an SQLITE_DELETE (the SQLITE_DELETE code is actually
  87864. ** slightly more efficient). Since you cannot write to a PK column
  87865. ** using the incremental-blob API, this works. For the sessions module
  87866. ** anyhow.
  87867. */
  87868. sqlite3_int64 iKey;
  87869. iKey = sqlite3BtreeIntegerKey(p->pCsr);
  87870. sqlite3VdbePreUpdateHook(
  87871. v, v->apCsr[0], SQLITE_DELETE, p->zDb, p->pTab, iKey, -1
  87872. );
  87873. }
  87874. #endif
  87875. rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
  87876. sqlite3BtreeLeaveCursor(p->pCsr);
  87877. if( rc==SQLITE_ABORT ){
  87878. sqlite3VdbeFinalize(v);
  87879. p->pStmt = 0;
  87880. }else{
  87881. v->rc = rc;
  87882. }
  87883. }
  87884. sqlite3Error(db, rc);
  87885. rc = sqlite3ApiExit(db, rc);
  87886. sqlite3_mutex_leave(db->mutex);
  87887. return rc;
  87888. }
  87889. /*
  87890. ** Read data from a blob handle.
  87891. */
  87892. SQLITE_API int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
  87893. return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreePayloadChecked);
  87894. }
  87895. /*
  87896. ** Write data to a blob handle.
  87897. */
  87898. SQLITE_API int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
  87899. return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
  87900. }
  87901. /*
  87902. ** Query a blob handle for the size of the data.
  87903. **
  87904. ** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
  87905. ** so no mutex is required for access.
  87906. */
  87907. SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *pBlob){
  87908. Incrblob *p = (Incrblob *)pBlob;
  87909. return (p && p->pStmt) ? p->nByte : 0;
  87910. }
  87911. /*
  87912. ** Move an existing blob handle to point to a different row of the same
  87913. ** database table.
  87914. **
  87915. ** If an error occurs, or if the specified row does not exist or does not
  87916. ** contain a blob or text value, then an error code is returned and the
  87917. ** database handle error code and message set. If this happens, then all
  87918. ** subsequent calls to sqlite3_blob_xxx() functions (except blob_close())
  87919. ** immediately return SQLITE_ABORT.
  87920. */
  87921. SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *pBlob, sqlite3_int64 iRow){
  87922. int rc;
  87923. Incrblob *p = (Incrblob *)pBlob;
  87924. sqlite3 *db;
  87925. if( p==0 ) return SQLITE_MISUSE_BKPT;
  87926. db = p->db;
  87927. sqlite3_mutex_enter(db->mutex);
  87928. if( p->pStmt==0 ){
  87929. /* If there is no statement handle, then the blob-handle has
  87930. ** already been invalidated. Return SQLITE_ABORT in this case.
  87931. */
  87932. rc = SQLITE_ABORT;
  87933. }else{
  87934. char *zErr;
  87935. rc = blobSeekToRow(p, iRow, &zErr);
  87936. if( rc!=SQLITE_OK ){
  87937. sqlite3ErrorWithMsg(db, rc, (zErr ? "%s" : 0), zErr);
  87938. sqlite3DbFree(db, zErr);
  87939. }
  87940. assert( rc!=SQLITE_SCHEMA );
  87941. }
  87942. rc = sqlite3ApiExit(db, rc);
  87943. assert( rc==SQLITE_OK || p->pStmt==0 );
  87944. sqlite3_mutex_leave(db->mutex);
  87945. return rc;
  87946. }
  87947. #endif /* #ifndef SQLITE_OMIT_INCRBLOB */
  87948. /************** End of vdbeblob.c ********************************************/
  87949. /************** Begin file vdbesort.c ****************************************/
  87950. /*
  87951. ** 2011-07-09
  87952. **
  87953. ** The author disclaims copyright to this source code. In place of
  87954. ** a legal notice, here is a blessing:
  87955. **
  87956. ** May you do good and not evil.
  87957. ** May you find forgiveness for yourself and forgive others.
  87958. ** May you share freely, never taking more than you give.
  87959. **
  87960. *************************************************************************
  87961. ** This file contains code for the VdbeSorter object, used in concert with
  87962. ** a VdbeCursor to sort large numbers of keys for CREATE INDEX statements
  87963. ** or by SELECT statements with ORDER BY clauses that cannot be satisfied
  87964. ** using indexes and without LIMIT clauses.
  87965. **
  87966. ** The VdbeSorter object implements a multi-threaded external merge sort
  87967. ** algorithm that is efficient even if the number of elements being sorted
  87968. ** exceeds the available memory.
  87969. **
  87970. ** Here is the (internal, non-API) interface between this module and the
  87971. ** rest of the SQLite system:
  87972. **
  87973. ** sqlite3VdbeSorterInit() Create a new VdbeSorter object.
  87974. **
  87975. ** sqlite3VdbeSorterWrite() Add a single new row to the VdbeSorter
  87976. ** object. The row is a binary blob in the
  87977. ** OP_MakeRecord format that contains both
  87978. ** the ORDER BY key columns and result columns
  87979. ** in the case of a SELECT w/ ORDER BY, or
  87980. ** the complete record for an index entry
  87981. ** in the case of a CREATE INDEX.
  87982. **
  87983. ** sqlite3VdbeSorterRewind() Sort all content previously added.
  87984. ** Position the read cursor on the
  87985. ** first sorted element.
  87986. **
  87987. ** sqlite3VdbeSorterNext() Advance the read cursor to the next sorted
  87988. ** element.
  87989. **
  87990. ** sqlite3VdbeSorterRowkey() Return the complete binary blob for the
  87991. ** row currently under the read cursor.
  87992. **
  87993. ** sqlite3VdbeSorterCompare() Compare the binary blob for the row
  87994. ** currently under the read cursor against
  87995. ** another binary blob X and report if
  87996. ** X is strictly less than the read cursor.
  87997. ** Used to enforce uniqueness in a
  87998. ** CREATE UNIQUE INDEX statement.
  87999. **
  88000. ** sqlite3VdbeSorterClose() Close the VdbeSorter object and reclaim
  88001. ** all resources.
  88002. **
  88003. ** sqlite3VdbeSorterReset() Refurbish the VdbeSorter for reuse. This
  88004. ** is like Close() followed by Init() only
  88005. ** much faster.
  88006. **
  88007. ** The interfaces above must be called in a particular order. Write() can
  88008. ** only occur in between Init()/Reset() and Rewind(). Next(), Rowkey(), and
  88009. ** Compare() can only occur in between Rewind() and Close()/Reset(). i.e.
  88010. **
  88011. ** Init()
  88012. ** for each record: Write()
  88013. ** Rewind()
  88014. ** Rowkey()/Compare()
  88015. ** Next()
  88016. ** Close()
  88017. **
  88018. ** Algorithm:
  88019. **
  88020. ** Records passed to the sorter via calls to Write() are initially held
  88021. ** unsorted in main memory. Assuming the amount of memory used never exceeds
  88022. ** a threshold, when Rewind() is called the set of records is sorted using
  88023. ** an in-memory merge sort. In this case, no temporary files are required
  88024. ** and subsequent calls to Rowkey(), Next() and Compare() read records
  88025. ** directly from main memory.
  88026. **
  88027. ** If the amount of space used to store records in main memory exceeds the
  88028. ** threshold, then the set of records currently in memory are sorted and
  88029. ** written to a temporary file in "Packed Memory Array" (PMA) format.
  88030. ** A PMA created at this point is known as a "level-0 PMA". Higher levels
  88031. ** of PMAs may be created by merging existing PMAs together - for example
  88032. ** merging two or more level-0 PMAs together creates a level-1 PMA.
  88033. **
  88034. ** The threshold for the amount of main memory to use before flushing
  88035. ** records to a PMA is roughly the same as the limit configured for the
  88036. ** page-cache of the main database. Specifically, the threshold is set to
  88037. ** the value returned by "PRAGMA main.page_size" multipled by
  88038. ** that returned by "PRAGMA main.cache_size", in bytes.
  88039. **
  88040. ** If the sorter is running in single-threaded mode, then all PMAs generated
  88041. ** are appended to a single temporary file. Or, if the sorter is running in
  88042. ** multi-threaded mode then up to (N+1) temporary files may be opened, where
  88043. ** N is the configured number of worker threads. In this case, instead of
  88044. ** sorting the records and writing the PMA to a temporary file itself, the
  88045. ** calling thread usually launches a worker thread to do so. Except, if
  88046. ** there are already N worker threads running, the main thread does the work
  88047. ** itself.
  88048. **
  88049. ** The sorter is running in multi-threaded mode if (a) the library was built
  88050. ** with pre-processor symbol SQLITE_MAX_WORKER_THREADS set to a value greater
  88051. ** than zero, and (b) worker threads have been enabled at runtime by calling
  88052. ** "PRAGMA threads=N" with some value of N greater than 0.
  88053. **
  88054. ** When Rewind() is called, any data remaining in memory is flushed to a
  88055. ** final PMA. So at this point the data is stored in some number of sorted
  88056. ** PMAs within temporary files on disk.
  88057. **
  88058. ** If there are fewer than SORTER_MAX_MERGE_COUNT PMAs in total and the
  88059. ** sorter is running in single-threaded mode, then these PMAs are merged
  88060. ** incrementally as keys are retreived from the sorter by the VDBE. The
  88061. ** MergeEngine object, described in further detail below, performs this
  88062. ** merge.
  88063. **
  88064. ** Or, if running in multi-threaded mode, then a background thread is
  88065. ** launched to merge the existing PMAs. Once the background thread has
  88066. ** merged T bytes of data into a single sorted PMA, the main thread
  88067. ** begins reading keys from that PMA while the background thread proceeds
  88068. ** with merging the next T bytes of data. And so on.
  88069. **
  88070. ** Parameter T is set to half the value of the memory threshold used
  88071. ** by Write() above to determine when to create a new PMA.
  88072. **
  88073. ** If there are more than SORTER_MAX_MERGE_COUNT PMAs in total when
  88074. ** Rewind() is called, then a hierarchy of incremental-merges is used.
  88075. ** First, T bytes of data from the first SORTER_MAX_MERGE_COUNT PMAs on
  88076. ** disk are merged together. Then T bytes of data from the second set, and
  88077. ** so on, such that no operation ever merges more than SORTER_MAX_MERGE_COUNT
  88078. ** PMAs at a time. This done is to improve locality.
  88079. **
  88080. ** If running in multi-threaded mode and there are more than
  88081. ** SORTER_MAX_MERGE_COUNT PMAs on disk when Rewind() is called, then more
  88082. ** than one background thread may be created. Specifically, there may be
  88083. ** one background thread for each temporary file on disk, and one background
  88084. ** thread to merge the output of each of the others to a single PMA for
  88085. ** the main thread to read from.
  88086. */
  88087. /* #include "sqliteInt.h" */
  88088. /* #include "vdbeInt.h" */
  88089. /*
  88090. ** If SQLITE_DEBUG_SORTER_THREADS is defined, this module outputs various
  88091. ** messages to stderr that may be helpful in understanding the performance
  88092. ** characteristics of the sorter in multi-threaded mode.
  88093. */
  88094. #if 0
  88095. # define SQLITE_DEBUG_SORTER_THREADS 1
  88096. #endif
  88097. /*
  88098. ** Hard-coded maximum amount of data to accumulate in memory before flushing
  88099. ** to a level 0 PMA. The purpose of this limit is to prevent various integer
  88100. ** overflows. 512MiB.
  88101. */
  88102. #define SQLITE_MAX_PMASZ (1<<29)
  88103. /*
  88104. ** Private objects used by the sorter
  88105. */
  88106. typedef struct MergeEngine MergeEngine; /* Merge PMAs together */
  88107. typedef struct PmaReader PmaReader; /* Incrementally read one PMA */
  88108. typedef struct PmaWriter PmaWriter; /* Incrementally write one PMA */
  88109. typedef struct SorterRecord SorterRecord; /* A record being sorted */
  88110. typedef struct SortSubtask SortSubtask; /* A sub-task in the sort process */
  88111. typedef struct SorterFile SorterFile; /* Temporary file object wrapper */
  88112. typedef struct SorterList SorterList; /* In-memory list of records */
  88113. typedef struct IncrMerger IncrMerger; /* Read & merge multiple PMAs */
  88114. /*
  88115. ** A container for a temp file handle and the current amount of data
  88116. ** stored in the file.
  88117. */
  88118. struct SorterFile {
  88119. sqlite3_file *pFd; /* File handle */
  88120. i64 iEof; /* Bytes of data stored in pFd */
  88121. };
  88122. /*
  88123. ** An in-memory list of objects to be sorted.
  88124. **
  88125. ** If aMemory==0 then each object is allocated separately and the objects
  88126. ** are connected using SorterRecord.u.pNext. If aMemory!=0 then all objects
  88127. ** are stored in the aMemory[] bulk memory, one right after the other, and
  88128. ** are connected using SorterRecord.u.iNext.
  88129. */
  88130. struct SorterList {
  88131. SorterRecord *pList; /* Linked list of records */
  88132. u8 *aMemory; /* If non-NULL, bulk memory to hold pList */
  88133. int szPMA; /* Size of pList as PMA in bytes */
  88134. };
  88135. /*
  88136. ** The MergeEngine object is used to combine two or more smaller PMAs into
  88137. ** one big PMA using a merge operation. Separate PMAs all need to be
  88138. ** combined into one big PMA in order to be able to step through the sorted
  88139. ** records in order.
  88140. **
  88141. ** The aReadr[] array contains a PmaReader object for each of the PMAs being
  88142. ** merged. An aReadr[] object either points to a valid key or else is at EOF.
  88143. ** ("EOF" means "End Of File". When aReadr[] is at EOF there is no more data.)
  88144. ** For the purposes of the paragraphs below, we assume that the array is
  88145. ** actually N elements in size, where N is the smallest power of 2 greater
  88146. ** to or equal to the number of PMAs being merged. The extra aReadr[] elements
  88147. ** are treated as if they are empty (always at EOF).
  88148. **
  88149. ** The aTree[] array is also N elements in size. The value of N is stored in
  88150. ** the MergeEngine.nTree variable.
  88151. **
  88152. ** The final (N/2) elements of aTree[] contain the results of comparing
  88153. ** pairs of PMA keys together. Element i contains the result of
  88154. ** comparing aReadr[2*i-N] and aReadr[2*i-N+1]. Whichever key is smaller, the
  88155. ** aTree element is set to the index of it.
  88156. **
  88157. ** For the purposes of this comparison, EOF is considered greater than any
  88158. ** other key value. If the keys are equal (only possible with two EOF
  88159. ** values), it doesn't matter which index is stored.
  88160. **
  88161. ** The (N/4) elements of aTree[] that precede the final (N/2) described
  88162. ** above contains the index of the smallest of each block of 4 PmaReaders
  88163. ** And so on. So that aTree[1] contains the index of the PmaReader that
  88164. ** currently points to the smallest key value. aTree[0] is unused.
  88165. **
  88166. ** Example:
  88167. **
  88168. ** aReadr[0] -> Banana
  88169. ** aReadr[1] -> Feijoa
  88170. ** aReadr[2] -> Elderberry
  88171. ** aReadr[3] -> Currant
  88172. ** aReadr[4] -> Grapefruit
  88173. ** aReadr[5] -> Apple
  88174. ** aReadr[6] -> Durian
  88175. ** aReadr[7] -> EOF
  88176. **
  88177. ** aTree[] = { X, 5 0, 5 0, 3, 5, 6 }
  88178. **
  88179. ** The current element is "Apple" (the value of the key indicated by
  88180. ** PmaReader 5). When the Next() operation is invoked, PmaReader 5 will
  88181. ** be advanced to the next key in its segment. Say the next key is
  88182. ** "Eggplant":
  88183. **
  88184. ** aReadr[5] -> Eggplant
  88185. **
  88186. ** The contents of aTree[] are updated first by comparing the new PmaReader
  88187. ** 5 key to the current key of PmaReader 4 (still "Grapefruit"). The PmaReader
  88188. ** 5 value is still smaller, so aTree[6] is set to 5. And so on up the tree.
  88189. ** The value of PmaReader 6 - "Durian" - is now smaller than that of PmaReader
  88190. ** 5, so aTree[3] is set to 6. Key 0 is smaller than key 6 (Banana<Durian),
  88191. ** so the value written into element 1 of the array is 0. As follows:
  88192. **
  88193. ** aTree[] = { X, 0 0, 6 0, 3, 5, 6 }
  88194. **
  88195. ** In other words, each time we advance to the next sorter element, log2(N)
  88196. ** key comparison operations are required, where N is the number of segments
  88197. ** being merged (rounded up to the next power of 2).
  88198. */
  88199. struct MergeEngine {
  88200. int nTree; /* Used size of aTree/aReadr (power of 2) */
  88201. SortSubtask *pTask; /* Used by this thread only */
  88202. int *aTree; /* Current state of incremental merge */
  88203. PmaReader *aReadr; /* Array of PmaReaders to merge data from */
  88204. };
  88205. /*
  88206. ** This object represents a single thread of control in a sort operation.
  88207. ** Exactly VdbeSorter.nTask instances of this object are allocated
  88208. ** as part of each VdbeSorter object. Instances are never allocated any
  88209. ** other way. VdbeSorter.nTask is set to the number of worker threads allowed
  88210. ** (see SQLITE_CONFIG_WORKER_THREADS) plus one (the main thread). Thus for
  88211. ** single-threaded operation, there is exactly one instance of this object
  88212. ** and for multi-threaded operation there are two or more instances.
  88213. **
  88214. ** Essentially, this structure contains all those fields of the VdbeSorter
  88215. ** structure for which each thread requires a separate instance. For example,
  88216. ** each thread requries its own UnpackedRecord object to unpack records in
  88217. ** as part of comparison operations.
  88218. **
  88219. ** Before a background thread is launched, variable bDone is set to 0. Then,
  88220. ** right before it exits, the thread itself sets bDone to 1. This is used for
  88221. ** two purposes:
  88222. **
  88223. ** 1. When flushing the contents of memory to a level-0 PMA on disk, to
  88224. ** attempt to select a SortSubtask for which there is not already an
  88225. ** active background thread (since doing so causes the main thread
  88226. ** to block until it finishes).
  88227. **
  88228. ** 2. If SQLITE_DEBUG_SORTER_THREADS is defined, to determine if a call
  88229. ** to sqlite3ThreadJoin() is likely to block. Cases that are likely to
  88230. ** block provoke debugging output.
  88231. **
  88232. ** In both cases, the effects of the main thread seeing (bDone==0) even
  88233. ** after the thread has finished are not dire. So we don't worry about
  88234. ** memory barriers and such here.
  88235. */
  88236. typedef int (*SorterCompare)(SortSubtask*,int*,const void*,int,const void*,int);
  88237. struct SortSubtask {
  88238. SQLiteThread *pThread; /* Background thread, if any */
  88239. int bDone; /* Set if thread is finished but not joined */
  88240. VdbeSorter *pSorter; /* Sorter that owns this sub-task */
  88241. UnpackedRecord *pUnpacked; /* Space to unpack a record */
  88242. SorterList list; /* List for thread to write to a PMA */
  88243. int nPMA; /* Number of PMAs currently in file */
  88244. SorterCompare xCompare; /* Compare function to use */
  88245. SorterFile file; /* Temp file for level-0 PMAs */
  88246. SorterFile file2; /* Space for other PMAs */
  88247. };
  88248. /*
  88249. ** Main sorter structure. A single instance of this is allocated for each
  88250. ** sorter cursor created by the VDBE.
  88251. **
  88252. ** mxKeysize:
  88253. ** As records are added to the sorter by calls to sqlite3VdbeSorterWrite(),
  88254. ** this variable is updated so as to be set to the size on disk of the
  88255. ** largest record in the sorter.
  88256. */
  88257. struct VdbeSorter {
  88258. int mnPmaSize; /* Minimum PMA size, in bytes */
  88259. int mxPmaSize; /* Maximum PMA size, in bytes. 0==no limit */
  88260. int mxKeysize; /* Largest serialized key seen so far */
  88261. int pgsz; /* Main database page size */
  88262. PmaReader *pReader; /* Readr data from here after Rewind() */
  88263. MergeEngine *pMerger; /* Or here, if bUseThreads==0 */
  88264. sqlite3 *db; /* Database connection */
  88265. KeyInfo *pKeyInfo; /* How to compare records */
  88266. UnpackedRecord *pUnpacked; /* Used by VdbeSorterCompare() */
  88267. SorterList list; /* List of in-memory records */
  88268. int iMemory; /* Offset of free space in list.aMemory */
  88269. int nMemory; /* Size of list.aMemory allocation in bytes */
  88270. u8 bUsePMA; /* True if one or more PMAs created */
  88271. u8 bUseThreads; /* True to use background threads */
  88272. u8 iPrev; /* Previous thread used to flush PMA */
  88273. u8 nTask; /* Size of aTask[] array */
  88274. u8 typeMask;
  88275. SortSubtask aTask[1]; /* One or more subtasks */
  88276. };
  88277. #define SORTER_TYPE_INTEGER 0x01
  88278. #define SORTER_TYPE_TEXT 0x02
  88279. /*
  88280. ** An instance of the following object is used to read records out of a
  88281. ** PMA, in sorted order. The next key to be read is cached in nKey/aKey.
  88282. ** aKey might point into aMap or into aBuffer. If neither of those locations
  88283. ** contain a contiguous representation of the key, then aAlloc is allocated
  88284. ** and the key is copied into aAlloc and aKey is made to poitn to aAlloc.
  88285. **
  88286. ** pFd==0 at EOF.
  88287. */
  88288. struct PmaReader {
  88289. i64 iReadOff; /* Current read offset */
  88290. i64 iEof; /* 1 byte past EOF for this PmaReader */
  88291. int nAlloc; /* Bytes of space at aAlloc */
  88292. int nKey; /* Number of bytes in key */
  88293. sqlite3_file *pFd; /* File handle we are reading from */
  88294. u8 *aAlloc; /* Space for aKey if aBuffer and pMap wont work */
  88295. u8 *aKey; /* Pointer to current key */
  88296. u8 *aBuffer; /* Current read buffer */
  88297. int nBuffer; /* Size of read buffer in bytes */
  88298. u8 *aMap; /* Pointer to mapping of entire file */
  88299. IncrMerger *pIncr; /* Incremental merger */
  88300. };
  88301. /*
  88302. ** Normally, a PmaReader object iterates through an existing PMA stored
  88303. ** within a temp file. However, if the PmaReader.pIncr variable points to
  88304. ** an object of the following type, it may be used to iterate/merge through
  88305. ** multiple PMAs simultaneously.
  88306. **
  88307. ** There are two types of IncrMerger object - single (bUseThread==0) and
  88308. ** multi-threaded (bUseThread==1).
  88309. **
  88310. ** A multi-threaded IncrMerger object uses two temporary files - aFile[0]
  88311. ** and aFile[1]. Neither file is allowed to grow to more than mxSz bytes in
  88312. ** size. When the IncrMerger is initialized, it reads enough data from
  88313. ** pMerger to populate aFile[0]. It then sets variables within the
  88314. ** corresponding PmaReader object to read from that file and kicks off
  88315. ** a background thread to populate aFile[1] with the next mxSz bytes of
  88316. ** sorted record data from pMerger.
  88317. **
  88318. ** When the PmaReader reaches the end of aFile[0], it blocks until the
  88319. ** background thread has finished populating aFile[1]. It then exchanges
  88320. ** the contents of the aFile[0] and aFile[1] variables within this structure,
  88321. ** sets the PmaReader fields to read from the new aFile[0] and kicks off
  88322. ** another background thread to populate the new aFile[1]. And so on, until
  88323. ** the contents of pMerger are exhausted.
  88324. **
  88325. ** A single-threaded IncrMerger does not open any temporary files of its
  88326. ** own. Instead, it has exclusive access to mxSz bytes of space beginning
  88327. ** at offset iStartOff of file pTask->file2. And instead of using a
  88328. ** background thread to prepare data for the PmaReader, with a single
  88329. ** threaded IncrMerger the allocate part of pTask->file2 is "refilled" with
  88330. ** keys from pMerger by the calling thread whenever the PmaReader runs out
  88331. ** of data.
  88332. */
  88333. struct IncrMerger {
  88334. SortSubtask *pTask; /* Task that owns this merger */
  88335. MergeEngine *pMerger; /* Merge engine thread reads data from */
  88336. i64 iStartOff; /* Offset to start writing file at */
  88337. int mxSz; /* Maximum bytes of data to store */
  88338. int bEof; /* Set to true when merge is finished */
  88339. int bUseThread; /* True to use a bg thread for this object */
  88340. SorterFile aFile[2]; /* aFile[0] for reading, [1] for writing */
  88341. };
  88342. /*
  88343. ** An instance of this object is used for writing a PMA.
  88344. **
  88345. ** The PMA is written one record at a time. Each record is of an arbitrary
  88346. ** size. But I/O is more efficient if it occurs in page-sized blocks where
  88347. ** each block is aligned on a page boundary. This object caches writes to
  88348. ** the PMA so that aligned, page-size blocks are written.
  88349. */
  88350. struct PmaWriter {
  88351. int eFWErr; /* Non-zero if in an error state */
  88352. u8 *aBuffer; /* Pointer to write buffer */
  88353. int nBuffer; /* Size of write buffer in bytes */
  88354. int iBufStart; /* First byte of buffer to write */
  88355. int iBufEnd; /* Last byte of buffer to write */
  88356. i64 iWriteOff; /* Offset of start of buffer in file */
  88357. sqlite3_file *pFd; /* File handle to write to */
  88358. };
  88359. /*
  88360. ** This object is the header on a single record while that record is being
  88361. ** held in memory and prior to being written out as part of a PMA.
  88362. **
  88363. ** How the linked list is connected depends on how memory is being managed
  88364. ** by this module. If using a separate allocation for each in-memory record
  88365. ** (VdbeSorter.list.aMemory==0), then the list is always connected using the
  88366. ** SorterRecord.u.pNext pointers.
  88367. **
  88368. ** Or, if using the single large allocation method (VdbeSorter.list.aMemory!=0),
  88369. ** then while records are being accumulated the list is linked using the
  88370. ** SorterRecord.u.iNext offset. This is because the aMemory[] array may
  88371. ** be sqlite3Realloc()ed while records are being accumulated. Once the VM
  88372. ** has finished passing records to the sorter, or when the in-memory buffer
  88373. ** is full, the list is sorted. As part of the sorting process, it is
  88374. ** converted to use the SorterRecord.u.pNext pointers. See function
  88375. ** vdbeSorterSort() for details.
  88376. */
  88377. struct SorterRecord {
  88378. int nVal; /* Size of the record in bytes */
  88379. union {
  88380. SorterRecord *pNext; /* Pointer to next record in list */
  88381. int iNext; /* Offset within aMemory of next record */
  88382. } u;
  88383. /* The data for the record immediately follows this header */
  88384. };
  88385. /* Return a pointer to the buffer containing the record data for SorterRecord
  88386. ** object p. Should be used as if:
  88387. **
  88388. ** void *SRVAL(SorterRecord *p) { return (void*)&p[1]; }
  88389. */
  88390. #define SRVAL(p) ((void*)((SorterRecord*)(p) + 1))
  88391. /* Maximum number of PMAs that a single MergeEngine can merge */
  88392. #define SORTER_MAX_MERGE_COUNT 16
  88393. static int vdbeIncrSwap(IncrMerger*);
  88394. static void vdbeIncrFree(IncrMerger *);
  88395. /*
  88396. ** Free all memory belonging to the PmaReader object passed as the
  88397. ** argument. All structure fields are set to zero before returning.
  88398. */
  88399. static void vdbePmaReaderClear(PmaReader *pReadr){
  88400. sqlite3_free(pReadr->aAlloc);
  88401. sqlite3_free(pReadr->aBuffer);
  88402. if( pReadr->aMap ) sqlite3OsUnfetch(pReadr->pFd, 0, pReadr->aMap);
  88403. vdbeIncrFree(pReadr->pIncr);
  88404. memset(pReadr, 0, sizeof(PmaReader));
  88405. }
  88406. /*
  88407. ** Read the next nByte bytes of data from the PMA p.
  88408. ** If successful, set *ppOut to point to a buffer containing the data
  88409. ** and return SQLITE_OK. Otherwise, if an error occurs, return an SQLite
  88410. ** error code.
  88411. **
  88412. ** The buffer returned in *ppOut is only valid until the
  88413. ** next call to this function.
  88414. */
  88415. static int vdbePmaReadBlob(
  88416. PmaReader *p, /* PmaReader from which to take the blob */
  88417. int nByte, /* Bytes of data to read */
  88418. u8 **ppOut /* OUT: Pointer to buffer containing data */
  88419. ){
  88420. int iBuf; /* Offset within buffer to read from */
  88421. int nAvail; /* Bytes of data available in buffer */
  88422. if( p->aMap ){
  88423. *ppOut = &p->aMap[p->iReadOff];
  88424. p->iReadOff += nByte;
  88425. return SQLITE_OK;
  88426. }
  88427. assert( p->aBuffer );
  88428. /* If there is no more data to be read from the buffer, read the next
  88429. ** p->nBuffer bytes of data from the file into it. Or, if there are less
  88430. ** than p->nBuffer bytes remaining in the PMA, read all remaining data. */
  88431. iBuf = p->iReadOff % p->nBuffer;
  88432. if( iBuf==0 ){
  88433. int nRead; /* Bytes to read from disk */
  88434. int rc; /* sqlite3OsRead() return code */
  88435. /* Determine how many bytes of data to read. */
  88436. if( (p->iEof - p->iReadOff) > (i64)p->nBuffer ){
  88437. nRead = p->nBuffer;
  88438. }else{
  88439. nRead = (int)(p->iEof - p->iReadOff);
  88440. }
  88441. assert( nRead>0 );
  88442. /* Readr data from the file. Return early if an error occurs. */
  88443. rc = sqlite3OsRead(p->pFd, p->aBuffer, nRead, p->iReadOff);
  88444. assert( rc!=SQLITE_IOERR_SHORT_READ );
  88445. if( rc!=SQLITE_OK ) return rc;
  88446. }
  88447. nAvail = p->nBuffer - iBuf;
  88448. if( nByte<=nAvail ){
  88449. /* The requested data is available in the in-memory buffer. In this
  88450. ** case there is no need to make a copy of the data, just return a
  88451. ** pointer into the buffer to the caller. */
  88452. *ppOut = &p->aBuffer[iBuf];
  88453. p->iReadOff += nByte;
  88454. }else{
  88455. /* The requested data is not all available in the in-memory buffer.
  88456. ** In this case, allocate space at p->aAlloc[] to copy the requested
  88457. ** range into. Then return a copy of pointer p->aAlloc to the caller. */
  88458. int nRem; /* Bytes remaining to copy */
  88459. /* Extend the p->aAlloc[] allocation if required. */
  88460. if( p->nAlloc<nByte ){
  88461. u8 *aNew;
  88462. sqlite3_int64 nNew = MAX(128, 2*(sqlite3_int64)p->nAlloc);
  88463. while( nByte>nNew ) nNew = nNew*2;
  88464. aNew = sqlite3Realloc(p->aAlloc, nNew);
  88465. if( !aNew ) return SQLITE_NOMEM_BKPT;
  88466. p->nAlloc = nNew;
  88467. p->aAlloc = aNew;
  88468. }
  88469. /* Copy as much data as is available in the buffer into the start of
  88470. ** p->aAlloc[]. */
  88471. memcpy(p->aAlloc, &p->aBuffer[iBuf], nAvail);
  88472. p->iReadOff += nAvail;
  88473. nRem = nByte - nAvail;
  88474. /* The following loop copies up to p->nBuffer bytes per iteration into
  88475. ** the p->aAlloc[] buffer. */
  88476. while( nRem>0 ){
  88477. int rc; /* vdbePmaReadBlob() return code */
  88478. int nCopy; /* Number of bytes to copy */
  88479. u8 *aNext; /* Pointer to buffer to copy data from */
  88480. nCopy = nRem;
  88481. if( nRem>p->nBuffer ) nCopy = p->nBuffer;
  88482. rc = vdbePmaReadBlob(p, nCopy, &aNext);
  88483. if( rc!=SQLITE_OK ) return rc;
  88484. assert( aNext!=p->aAlloc );
  88485. memcpy(&p->aAlloc[nByte - nRem], aNext, nCopy);
  88486. nRem -= nCopy;
  88487. }
  88488. *ppOut = p->aAlloc;
  88489. }
  88490. return SQLITE_OK;
  88491. }
  88492. /*
  88493. ** Read a varint from the stream of data accessed by p. Set *pnOut to
  88494. ** the value read.
  88495. */
  88496. static int vdbePmaReadVarint(PmaReader *p, u64 *pnOut){
  88497. int iBuf;
  88498. if( p->aMap ){
  88499. p->iReadOff += sqlite3GetVarint(&p->aMap[p->iReadOff], pnOut);
  88500. }else{
  88501. iBuf = p->iReadOff % p->nBuffer;
  88502. if( iBuf && (p->nBuffer-iBuf)>=9 ){
  88503. p->iReadOff += sqlite3GetVarint(&p->aBuffer[iBuf], pnOut);
  88504. }else{
  88505. u8 aVarint[16], *a;
  88506. int i = 0, rc;
  88507. do{
  88508. rc = vdbePmaReadBlob(p, 1, &a);
  88509. if( rc ) return rc;
  88510. aVarint[(i++)&0xf] = a[0];
  88511. }while( (a[0]&0x80)!=0 );
  88512. sqlite3GetVarint(aVarint, pnOut);
  88513. }
  88514. }
  88515. return SQLITE_OK;
  88516. }
  88517. /*
  88518. ** Attempt to memory map file pFile. If successful, set *pp to point to the
  88519. ** new mapping and return SQLITE_OK. If the mapping is not attempted
  88520. ** (because the file is too large or the VFS layer is configured not to use
  88521. ** mmap), return SQLITE_OK and set *pp to NULL.
  88522. **
  88523. ** Or, if an error occurs, return an SQLite error code. The final value of
  88524. ** *pp is undefined in this case.
  88525. */
  88526. static int vdbeSorterMapFile(SortSubtask *pTask, SorterFile *pFile, u8 **pp){
  88527. int rc = SQLITE_OK;
  88528. if( pFile->iEof<=(i64)(pTask->pSorter->db->nMaxSorterMmap) ){
  88529. sqlite3_file *pFd = pFile->pFd;
  88530. if( pFd->pMethods->iVersion>=3 ){
  88531. rc = sqlite3OsFetch(pFd, 0, (int)pFile->iEof, (void**)pp);
  88532. testcase( rc!=SQLITE_OK );
  88533. }
  88534. }
  88535. return rc;
  88536. }
  88537. /*
  88538. ** Attach PmaReader pReadr to file pFile (if it is not already attached to
  88539. ** that file) and seek it to offset iOff within the file. Return SQLITE_OK
  88540. ** if successful, or an SQLite error code if an error occurs.
  88541. */
  88542. static int vdbePmaReaderSeek(
  88543. SortSubtask *pTask, /* Task context */
  88544. PmaReader *pReadr, /* Reader whose cursor is to be moved */
  88545. SorterFile *pFile, /* Sorter file to read from */
  88546. i64 iOff /* Offset in pFile */
  88547. ){
  88548. int rc = SQLITE_OK;
  88549. assert( pReadr->pIncr==0 || pReadr->pIncr->bEof==0 );
  88550. if( sqlite3FaultSim(201) ) return SQLITE_IOERR_READ;
  88551. if( pReadr->aMap ){
  88552. sqlite3OsUnfetch(pReadr->pFd, 0, pReadr->aMap);
  88553. pReadr->aMap = 0;
  88554. }
  88555. pReadr->iReadOff = iOff;
  88556. pReadr->iEof = pFile->iEof;
  88557. pReadr->pFd = pFile->pFd;
  88558. rc = vdbeSorterMapFile(pTask, pFile, &pReadr->aMap);
  88559. if( rc==SQLITE_OK && pReadr->aMap==0 ){
  88560. int pgsz = pTask->pSorter->pgsz;
  88561. int iBuf = pReadr->iReadOff % pgsz;
  88562. if( pReadr->aBuffer==0 ){
  88563. pReadr->aBuffer = (u8*)sqlite3Malloc(pgsz);
  88564. if( pReadr->aBuffer==0 ) rc = SQLITE_NOMEM_BKPT;
  88565. pReadr->nBuffer = pgsz;
  88566. }
  88567. if( rc==SQLITE_OK && iBuf ){
  88568. int nRead = pgsz - iBuf;
  88569. if( (pReadr->iReadOff + nRead) > pReadr->iEof ){
  88570. nRead = (int)(pReadr->iEof - pReadr->iReadOff);
  88571. }
  88572. rc = sqlite3OsRead(
  88573. pReadr->pFd, &pReadr->aBuffer[iBuf], nRead, pReadr->iReadOff
  88574. );
  88575. testcase( rc!=SQLITE_OK );
  88576. }
  88577. }
  88578. return rc;
  88579. }
  88580. /*
  88581. ** Advance PmaReader pReadr to the next key in its PMA. Return SQLITE_OK if
  88582. ** no error occurs, or an SQLite error code if one does.
  88583. */
  88584. static int vdbePmaReaderNext(PmaReader *pReadr){
  88585. int rc = SQLITE_OK; /* Return Code */
  88586. u64 nRec = 0; /* Size of record in bytes */
  88587. if( pReadr->iReadOff>=pReadr->iEof ){
  88588. IncrMerger *pIncr = pReadr->pIncr;
  88589. int bEof = 1;
  88590. if( pIncr ){
  88591. rc = vdbeIncrSwap(pIncr);
  88592. if( rc==SQLITE_OK && pIncr->bEof==0 ){
  88593. rc = vdbePmaReaderSeek(
  88594. pIncr->pTask, pReadr, &pIncr->aFile[0], pIncr->iStartOff
  88595. );
  88596. bEof = 0;
  88597. }
  88598. }
  88599. if( bEof ){
  88600. /* This is an EOF condition */
  88601. vdbePmaReaderClear(pReadr);
  88602. testcase( rc!=SQLITE_OK );
  88603. return rc;
  88604. }
  88605. }
  88606. if( rc==SQLITE_OK ){
  88607. rc = vdbePmaReadVarint(pReadr, &nRec);
  88608. }
  88609. if( rc==SQLITE_OK ){
  88610. pReadr->nKey = (int)nRec;
  88611. rc = vdbePmaReadBlob(pReadr, (int)nRec, &pReadr->aKey);
  88612. testcase( rc!=SQLITE_OK );
  88613. }
  88614. return rc;
  88615. }
  88616. /*
  88617. ** Initialize PmaReader pReadr to scan through the PMA stored in file pFile
  88618. ** starting at offset iStart and ending at offset iEof-1. This function
  88619. ** leaves the PmaReader pointing to the first key in the PMA (or EOF if the
  88620. ** PMA is empty).
  88621. **
  88622. ** If the pnByte parameter is NULL, then it is assumed that the file
  88623. ** contains a single PMA, and that that PMA omits the initial length varint.
  88624. */
  88625. static int vdbePmaReaderInit(
  88626. SortSubtask *pTask, /* Task context */
  88627. SorterFile *pFile, /* Sorter file to read from */
  88628. i64 iStart, /* Start offset in pFile */
  88629. PmaReader *pReadr, /* PmaReader to populate */
  88630. i64 *pnByte /* IN/OUT: Increment this value by PMA size */
  88631. ){
  88632. int rc;
  88633. assert( pFile->iEof>iStart );
  88634. assert( pReadr->aAlloc==0 && pReadr->nAlloc==0 );
  88635. assert( pReadr->aBuffer==0 );
  88636. assert( pReadr->aMap==0 );
  88637. rc = vdbePmaReaderSeek(pTask, pReadr, pFile, iStart);
  88638. if( rc==SQLITE_OK ){
  88639. u64 nByte = 0; /* Size of PMA in bytes */
  88640. rc = vdbePmaReadVarint(pReadr, &nByte);
  88641. pReadr->iEof = pReadr->iReadOff + nByte;
  88642. *pnByte += nByte;
  88643. }
  88644. if( rc==SQLITE_OK ){
  88645. rc = vdbePmaReaderNext(pReadr);
  88646. }
  88647. return rc;
  88648. }
  88649. /*
  88650. ** A version of vdbeSorterCompare() that assumes that it has already been
  88651. ** determined that the first field of key1 is equal to the first field of
  88652. ** key2.
  88653. */
  88654. static int vdbeSorterCompareTail(
  88655. SortSubtask *pTask, /* Subtask context (for pKeyInfo) */
  88656. int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */
  88657. const void *pKey1, int nKey1, /* Left side of comparison */
  88658. const void *pKey2, int nKey2 /* Right side of comparison */
  88659. ){
  88660. UnpackedRecord *r2 = pTask->pUnpacked;
  88661. if( *pbKey2Cached==0 ){
  88662. sqlite3VdbeRecordUnpack(pTask->pSorter->pKeyInfo, nKey2, pKey2, r2);
  88663. *pbKey2Cached = 1;
  88664. }
  88665. return sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, r2, 1);
  88666. }
  88667. /*
  88668. ** Compare key1 (buffer pKey1, size nKey1 bytes) with key2 (buffer pKey2,
  88669. ** size nKey2 bytes). Use (pTask->pKeyInfo) for the collation sequences
  88670. ** used by the comparison. Return the result of the comparison.
  88671. **
  88672. ** If IN/OUT parameter *pbKey2Cached is true when this function is called,
  88673. ** it is assumed that (pTask->pUnpacked) contains the unpacked version
  88674. ** of key2. If it is false, (pTask->pUnpacked) is populated with the unpacked
  88675. ** version of key2 and *pbKey2Cached set to true before returning.
  88676. **
  88677. ** If an OOM error is encountered, (pTask->pUnpacked->error_rc) is set
  88678. ** to SQLITE_NOMEM.
  88679. */
  88680. static int vdbeSorterCompare(
  88681. SortSubtask *pTask, /* Subtask context (for pKeyInfo) */
  88682. int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */
  88683. const void *pKey1, int nKey1, /* Left side of comparison */
  88684. const void *pKey2, int nKey2 /* Right side of comparison */
  88685. ){
  88686. UnpackedRecord *r2 = pTask->pUnpacked;
  88687. if( !*pbKey2Cached ){
  88688. sqlite3VdbeRecordUnpack(pTask->pSorter->pKeyInfo, nKey2, pKey2, r2);
  88689. *pbKey2Cached = 1;
  88690. }
  88691. return sqlite3VdbeRecordCompare(nKey1, pKey1, r2);
  88692. }
  88693. /*
  88694. ** A specially optimized version of vdbeSorterCompare() that assumes that
  88695. ** the first field of each key is a TEXT value and that the collation
  88696. ** sequence to compare them with is BINARY.
  88697. */
  88698. static int vdbeSorterCompareText(
  88699. SortSubtask *pTask, /* Subtask context (for pKeyInfo) */
  88700. int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */
  88701. const void *pKey1, int nKey1, /* Left side of comparison */
  88702. const void *pKey2, int nKey2 /* Right side of comparison */
  88703. ){
  88704. const u8 * const p1 = (const u8 * const)pKey1;
  88705. const u8 * const p2 = (const u8 * const)pKey2;
  88706. const u8 * const v1 = &p1[ p1[0] ]; /* Pointer to value 1 */
  88707. const u8 * const v2 = &p2[ p2[0] ]; /* Pointer to value 2 */
  88708. int n1;
  88709. int n2;
  88710. int res;
  88711. getVarint32NR(&p1[1], n1);
  88712. getVarint32NR(&p2[1], n2);
  88713. res = memcmp(v1, v2, (MIN(n1, n2) - 13)/2);
  88714. if( res==0 ){
  88715. res = n1 - n2;
  88716. }
  88717. if( res==0 ){
  88718. if( pTask->pSorter->pKeyInfo->nKeyField>1 ){
  88719. res = vdbeSorterCompareTail(
  88720. pTask, pbKey2Cached, pKey1, nKey1, pKey2, nKey2
  88721. );
  88722. }
  88723. }else{
  88724. assert( !(pTask->pSorter->pKeyInfo->aSortFlags[0]&KEYINFO_ORDER_BIGNULL) );
  88725. if( pTask->pSorter->pKeyInfo->aSortFlags[0] ){
  88726. res = res * -1;
  88727. }
  88728. }
  88729. return res;
  88730. }
  88731. /*
  88732. ** A specially optimized version of vdbeSorterCompare() that assumes that
  88733. ** the first field of each key is an INTEGER value.
  88734. */
  88735. static int vdbeSorterCompareInt(
  88736. SortSubtask *pTask, /* Subtask context (for pKeyInfo) */
  88737. int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */
  88738. const void *pKey1, int nKey1, /* Left side of comparison */
  88739. const void *pKey2, int nKey2 /* Right side of comparison */
  88740. ){
  88741. const u8 * const p1 = (const u8 * const)pKey1;
  88742. const u8 * const p2 = (const u8 * const)pKey2;
  88743. const int s1 = p1[1]; /* Left hand serial type */
  88744. const int s2 = p2[1]; /* Right hand serial type */
  88745. const u8 * const v1 = &p1[ p1[0] ]; /* Pointer to value 1 */
  88746. const u8 * const v2 = &p2[ p2[0] ]; /* Pointer to value 2 */
  88747. int res; /* Return value */
  88748. assert( (s1>0 && s1<7) || s1==8 || s1==9 );
  88749. assert( (s2>0 && s2<7) || s2==8 || s2==9 );
  88750. if( s1==s2 ){
  88751. /* The two values have the same sign. Compare using memcmp(). */
  88752. static const u8 aLen[] = {0, 1, 2, 3, 4, 6, 8, 0, 0, 0 };
  88753. const u8 n = aLen[s1];
  88754. int i;
  88755. res = 0;
  88756. for(i=0; i<n; i++){
  88757. if( (res = v1[i] - v2[i])!=0 ){
  88758. if( ((v1[0] ^ v2[0]) & 0x80)!=0 ){
  88759. res = v1[0] & 0x80 ? -1 : +1;
  88760. }
  88761. break;
  88762. }
  88763. }
  88764. }else if( s1>7 && s2>7 ){
  88765. res = s1 - s2;
  88766. }else{
  88767. if( s2>7 ){
  88768. res = +1;
  88769. }else if( s1>7 ){
  88770. res = -1;
  88771. }else{
  88772. res = s1 - s2;
  88773. }
  88774. assert( res!=0 );
  88775. if( res>0 ){
  88776. if( *v1 & 0x80 ) res = -1;
  88777. }else{
  88778. if( *v2 & 0x80 ) res = +1;
  88779. }
  88780. }
  88781. if( res==0 ){
  88782. if( pTask->pSorter->pKeyInfo->nKeyField>1 ){
  88783. res = vdbeSorterCompareTail(
  88784. pTask, pbKey2Cached, pKey1, nKey1, pKey2, nKey2
  88785. );
  88786. }
  88787. }else if( pTask->pSorter->pKeyInfo->aSortFlags[0] ){
  88788. assert( !(pTask->pSorter->pKeyInfo->aSortFlags[0]&KEYINFO_ORDER_BIGNULL) );
  88789. res = res * -1;
  88790. }
  88791. return res;
  88792. }
  88793. /*
  88794. ** Initialize the temporary index cursor just opened as a sorter cursor.
  88795. **
  88796. ** Usually, the sorter module uses the value of (pCsr->pKeyInfo->nKeyField)
  88797. ** to determine the number of fields that should be compared from the
  88798. ** records being sorted. However, if the value passed as argument nField
  88799. ** is non-zero and the sorter is able to guarantee a stable sort, nField
  88800. ** is used instead. This is used when sorting records for a CREATE INDEX
  88801. ** statement. In this case, keys are always delivered to the sorter in
  88802. ** order of the primary key, which happens to be make up the final part
  88803. ** of the records being sorted. So if the sort is stable, there is never
  88804. ** any reason to compare PK fields and they can be ignored for a small
  88805. ** performance boost.
  88806. **
  88807. ** The sorter can guarantee a stable sort when running in single-threaded
  88808. ** mode, but not in multi-threaded mode.
  88809. **
  88810. ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
  88811. */
  88812. SQLITE_PRIVATE int sqlite3VdbeSorterInit(
  88813. sqlite3 *db, /* Database connection (for malloc()) */
  88814. int nField, /* Number of key fields in each record */
  88815. VdbeCursor *pCsr /* Cursor that holds the new sorter */
  88816. ){
  88817. int pgsz; /* Page size of main database */
  88818. int i; /* Used to iterate through aTask[] */
  88819. VdbeSorter *pSorter; /* The new sorter */
  88820. KeyInfo *pKeyInfo; /* Copy of pCsr->pKeyInfo with db==0 */
  88821. int szKeyInfo; /* Size of pCsr->pKeyInfo in bytes */
  88822. int sz; /* Size of pSorter in bytes */
  88823. int rc = SQLITE_OK;
  88824. #if SQLITE_MAX_WORKER_THREADS==0
  88825. # define nWorker 0
  88826. #else
  88827. int nWorker;
  88828. #endif
  88829. /* Initialize the upper limit on the number of worker threads */
  88830. #if SQLITE_MAX_WORKER_THREADS>0
  88831. if( sqlite3TempInMemory(db) || sqlite3GlobalConfig.bCoreMutex==0 ){
  88832. nWorker = 0;
  88833. }else{
  88834. nWorker = db->aLimit[SQLITE_LIMIT_WORKER_THREADS];
  88835. }
  88836. #endif
  88837. /* Do not allow the total number of threads (main thread + all workers)
  88838. ** to exceed the maximum merge count */
  88839. #if SQLITE_MAX_WORKER_THREADS>=SORTER_MAX_MERGE_COUNT
  88840. if( nWorker>=SORTER_MAX_MERGE_COUNT ){
  88841. nWorker = SORTER_MAX_MERGE_COUNT-1;
  88842. }
  88843. #endif
  88844. assert( pCsr->pKeyInfo && pCsr->pBtx==0 );
  88845. assert( pCsr->eCurType==CURTYPE_SORTER );
  88846. szKeyInfo = sizeof(KeyInfo) + (pCsr->pKeyInfo->nKeyField-1)*sizeof(CollSeq*);
  88847. sz = sizeof(VdbeSorter) + nWorker * sizeof(SortSubtask);
  88848. pSorter = (VdbeSorter*)sqlite3DbMallocZero(db, sz + szKeyInfo);
  88849. pCsr->uc.pSorter = pSorter;
  88850. if( pSorter==0 ){
  88851. rc = SQLITE_NOMEM_BKPT;
  88852. }else{
  88853. pSorter->pKeyInfo = pKeyInfo = (KeyInfo*)((u8*)pSorter + sz);
  88854. memcpy(pKeyInfo, pCsr->pKeyInfo, szKeyInfo);
  88855. pKeyInfo->db = 0;
  88856. if( nField && nWorker==0 ){
  88857. pKeyInfo->nKeyField = nField;
  88858. }
  88859. pSorter->pgsz = pgsz = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
  88860. pSorter->nTask = nWorker + 1;
  88861. pSorter->iPrev = (u8)(nWorker - 1);
  88862. pSorter->bUseThreads = (pSorter->nTask>1);
  88863. pSorter->db = db;
  88864. for(i=0; i<pSorter->nTask; i++){
  88865. SortSubtask *pTask = &pSorter->aTask[i];
  88866. pTask->pSorter = pSorter;
  88867. }
  88868. if( !sqlite3TempInMemory(db) ){
  88869. i64 mxCache; /* Cache size in bytes*/
  88870. u32 szPma = sqlite3GlobalConfig.szPma;
  88871. pSorter->mnPmaSize = szPma * pgsz;
  88872. mxCache = db->aDb[0].pSchema->cache_size;
  88873. if( mxCache<0 ){
  88874. /* A negative cache-size value C indicates that the cache is abs(C)
  88875. ** KiB in size. */
  88876. mxCache = mxCache * -1024;
  88877. }else{
  88878. mxCache = mxCache * pgsz;
  88879. }
  88880. mxCache = MIN(mxCache, SQLITE_MAX_PMASZ);
  88881. pSorter->mxPmaSize = MAX(pSorter->mnPmaSize, (int)mxCache);
  88882. /* Avoid large memory allocations if the application has requested
  88883. ** SQLITE_CONFIG_SMALL_MALLOC. */
  88884. if( sqlite3GlobalConfig.bSmallMalloc==0 ){
  88885. assert( pSorter->iMemory==0 );
  88886. pSorter->nMemory = pgsz;
  88887. pSorter->list.aMemory = (u8*)sqlite3Malloc(pgsz);
  88888. if( !pSorter->list.aMemory ) rc = SQLITE_NOMEM_BKPT;
  88889. }
  88890. }
  88891. if( pKeyInfo->nAllField<13
  88892. && (pKeyInfo->aColl[0]==0 || pKeyInfo->aColl[0]==db->pDfltColl)
  88893. && (pKeyInfo->aSortFlags[0] & KEYINFO_ORDER_BIGNULL)==0
  88894. ){
  88895. pSorter->typeMask = SORTER_TYPE_INTEGER | SORTER_TYPE_TEXT;
  88896. }
  88897. }
  88898. return rc;
  88899. }
  88900. #undef nWorker /* Defined at the top of this function */
  88901. /*
  88902. ** Free the list of sorted records starting at pRecord.
  88903. */
  88904. static void vdbeSorterRecordFree(sqlite3 *db, SorterRecord *pRecord){
  88905. SorterRecord *p;
  88906. SorterRecord *pNext;
  88907. for(p=pRecord; p; p=pNext){
  88908. pNext = p->u.pNext;
  88909. sqlite3DbFree(db, p);
  88910. }
  88911. }
  88912. /*
  88913. ** Free all resources owned by the object indicated by argument pTask. All
  88914. ** fields of *pTask are zeroed before returning.
  88915. */
  88916. static void vdbeSortSubtaskCleanup(sqlite3 *db, SortSubtask *pTask){
  88917. sqlite3DbFree(db, pTask->pUnpacked);
  88918. #if SQLITE_MAX_WORKER_THREADS>0
  88919. /* pTask->list.aMemory can only be non-zero if it was handed memory
  88920. ** from the main thread. That only occurs SQLITE_MAX_WORKER_THREADS>0 */
  88921. if( pTask->list.aMemory ){
  88922. sqlite3_free(pTask->list.aMemory);
  88923. }else
  88924. #endif
  88925. {
  88926. assert( pTask->list.aMemory==0 );
  88927. vdbeSorterRecordFree(0, pTask->list.pList);
  88928. }
  88929. if( pTask->file.pFd ){
  88930. sqlite3OsCloseFree(pTask->file.pFd);
  88931. }
  88932. if( pTask->file2.pFd ){
  88933. sqlite3OsCloseFree(pTask->file2.pFd);
  88934. }
  88935. memset(pTask, 0, sizeof(SortSubtask));
  88936. }
  88937. #ifdef SQLITE_DEBUG_SORTER_THREADS
  88938. static void vdbeSorterWorkDebug(SortSubtask *pTask, const char *zEvent){
  88939. i64 t;
  88940. int iTask = (pTask - pTask->pSorter->aTask);
  88941. sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
  88942. fprintf(stderr, "%lld:%d %s\n", t, iTask, zEvent);
  88943. }
  88944. static void vdbeSorterRewindDebug(const char *zEvent){
  88945. i64 t;
  88946. sqlite3OsCurrentTimeInt64(sqlite3_vfs_find(0), &t);
  88947. fprintf(stderr, "%lld:X %s\n", t, zEvent);
  88948. }
  88949. static void vdbeSorterPopulateDebug(
  88950. SortSubtask *pTask,
  88951. const char *zEvent
  88952. ){
  88953. i64 t;
  88954. int iTask = (pTask - pTask->pSorter->aTask);
  88955. sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
  88956. fprintf(stderr, "%lld:bg%d %s\n", t, iTask, zEvent);
  88957. }
  88958. static void vdbeSorterBlockDebug(
  88959. SortSubtask *pTask,
  88960. int bBlocked,
  88961. const char *zEvent
  88962. ){
  88963. if( bBlocked ){
  88964. i64 t;
  88965. sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
  88966. fprintf(stderr, "%lld:main %s\n", t, zEvent);
  88967. }
  88968. }
  88969. #else
  88970. # define vdbeSorterWorkDebug(x,y)
  88971. # define vdbeSorterRewindDebug(y)
  88972. # define vdbeSorterPopulateDebug(x,y)
  88973. # define vdbeSorterBlockDebug(x,y,z)
  88974. #endif
  88975. #if SQLITE_MAX_WORKER_THREADS>0
  88976. /*
  88977. ** Join thread pTask->thread.
  88978. */
  88979. static int vdbeSorterJoinThread(SortSubtask *pTask){
  88980. int rc = SQLITE_OK;
  88981. if( pTask->pThread ){
  88982. #ifdef SQLITE_DEBUG_SORTER_THREADS
  88983. int bDone = pTask->bDone;
  88984. #endif
  88985. void *pRet = SQLITE_INT_TO_PTR(SQLITE_ERROR);
  88986. vdbeSorterBlockDebug(pTask, !bDone, "enter");
  88987. (void)sqlite3ThreadJoin(pTask->pThread, &pRet);
  88988. vdbeSorterBlockDebug(pTask, !bDone, "exit");
  88989. rc = SQLITE_PTR_TO_INT(pRet);
  88990. assert( pTask->bDone==1 );
  88991. pTask->bDone = 0;
  88992. pTask->pThread = 0;
  88993. }
  88994. return rc;
  88995. }
  88996. /*
  88997. ** Launch a background thread to run xTask(pIn).
  88998. */
  88999. static int vdbeSorterCreateThread(
  89000. SortSubtask *pTask, /* Thread will use this task object */
  89001. void *(*xTask)(void*), /* Routine to run in a separate thread */
  89002. void *pIn /* Argument passed into xTask() */
  89003. ){
  89004. assert( pTask->pThread==0 && pTask->bDone==0 );
  89005. return sqlite3ThreadCreate(&pTask->pThread, xTask, pIn);
  89006. }
  89007. /*
  89008. ** Join all outstanding threads launched by SorterWrite() to create
  89009. ** level-0 PMAs.
  89010. */
  89011. static int vdbeSorterJoinAll(VdbeSorter *pSorter, int rcin){
  89012. int rc = rcin;
  89013. int i;
  89014. /* This function is always called by the main user thread.
  89015. **
  89016. ** If this function is being called after SorterRewind() has been called,
  89017. ** it is possible that thread pSorter->aTask[pSorter->nTask-1].pThread
  89018. ** is currently attempt to join one of the other threads. To avoid a race
  89019. ** condition where this thread also attempts to join the same object, join
  89020. ** thread pSorter->aTask[pSorter->nTask-1].pThread first. */
  89021. for(i=pSorter->nTask-1; i>=0; i--){
  89022. SortSubtask *pTask = &pSorter->aTask[i];
  89023. int rc2 = vdbeSorterJoinThread(pTask);
  89024. if( rc==SQLITE_OK ) rc = rc2;
  89025. }
  89026. return rc;
  89027. }
  89028. #else
  89029. # define vdbeSorterJoinAll(x,rcin) (rcin)
  89030. # define vdbeSorterJoinThread(pTask) SQLITE_OK
  89031. #endif
  89032. /*
  89033. ** Allocate a new MergeEngine object capable of handling up to
  89034. ** nReader PmaReader inputs.
  89035. **
  89036. ** nReader is automatically rounded up to the next power of two.
  89037. ** nReader may not exceed SORTER_MAX_MERGE_COUNT even after rounding up.
  89038. */
  89039. static MergeEngine *vdbeMergeEngineNew(int nReader){
  89040. int N = 2; /* Smallest power of two >= nReader */
  89041. int nByte; /* Total bytes of space to allocate */
  89042. MergeEngine *pNew; /* Pointer to allocated object to return */
  89043. assert( nReader<=SORTER_MAX_MERGE_COUNT );
  89044. while( N<nReader ) N += N;
  89045. nByte = sizeof(MergeEngine) + N * (sizeof(int) + sizeof(PmaReader));
  89046. pNew = sqlite3FaultSim(100) ? 0 : (MergeEngine*)sqlite3MallocZero(nByte);
  89047. if( pNew ){
  89048. pNew->nTree = N;
  89049. pNew->pTask = 0;
  89050. pNew->aReadr = (PmaReader*)&pNew[1];
  89051. pNew->aTree = (int*)&pNew->aReadr[N];
  89052. }
  89053. return pNew;
  89054. }
  89055. /*
  89056. ** Free the MergeEngine object passed as the only argument.
  89057. */
  89058. static void vdbeMergeEngineFree(MergeEngine *pMerger){
  89059. int i;
  89060. if( pMerger ){
  89061. for(i=0; i<pMerger->nTree; i++){
  89062. vdbePmaReaderClear(&pMerger->aReadr[i]);
  89063. }
  89064. }
  89065. sqlite3_free(pMerger);
  89066. }
  89067. /*
  89068. ** Free all resources associated with the IncrMerger object indicated by
  89069. ** the first argument.
  89070. */
  89071. static void vdbeIncrFree(IncrMerger *pIncr){
  89072. if( pIncr ){
  89073. #if SQLITE_MAX_WORKER_THREADS>0
  89074. if( pIncr->bUseThread ){
  89075. vdbeSorterJoinThread(pIncr->pTask);
  89076. if( pIncr->aFile[0].pFd ) sqlite3OsCloseFree(pIncr->aFile[0].pFd);
  89077. if( pIncr->aFile[1].pFd ) sqlite3OsCloseFree(pIncr->aFile[1].pFd);
  89078. }
  89079. #endif
  89080. vdbeMergeEngineFree(pIncr->pMerger);
  89081. sqlite3_free(pIncr);
  89082. }
  89083. }
  89084. /*
  89085. ** Reset a sorting cursor back to its original empty state.
  89086. */
  89087. SQLITE_PRIVATE void sqlite3VdbeSorterReset(sqlite3 *db, VdbeSorter *pSorter){
  89088. int i;
  89089. (void)vdbeSorterJoinAll(pSorter, SQLITE_OK);
  89090. assert( pSorter->bUseThreads || pSorter->pReader==0 );
  89091. #if SQLITE_MAX_WORKER_THREADS>0
  89092. if( pSorter->pReader ){
  89093. vdbePmaReaderClear(pSorter->pReader);
  89094. sqlite3DbFree(db, pSorter->pReader);
  89095. pSorter->pReader = 0;
  89096. }
  89097. #endif
  89098. vdbeMergeEngineFree(pSorter->pMerger);
  89099. pSorter->pMerger = 0;
  89100. for(i=0; i<pSorter->nTask; i++){
  89101. SortSubtask *pTask = &pSorter->aTask[i];
  89102. vdbeSortSubtaskCleanup(db, pTask);
  89103. pTask->pSorter = pSorter;
  89104. }
  89105. if( pSorter->list.aMemory==0 ){
  89106. vdbeSorterRecordFree(0, pSorter->list.pList);
  89107. }
  89108. pSorter->list.pList = 0;
  89109. pSorter->list.szPMA = 0;
  89110. pSorter->bUsePMA = 0;
  89111. pSorter->iMemory = 0;
  89112. pSorter->mxKeysize = 0;
  89113. sqlite3DbFree(db, pSorter->pUnpacked);
  89114. pSorter->pUnpacked = 0;
  89115. }
  89116. /*
  89117. ** Free any cursor components allocated by sqlite3VdbeSorterXXX routines.
  89118. */
  89119. SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *db, VdbeCursor *pCsr){
  89120. VdbeSorter *pSorter;
  89121. assert( pCsr->eCurType==CURTYPE_SORTER );
  89122. pSorter = pCsr->uc.pSorter;
  89123. if( pSorter ){
  89124. sqlite3VdbeSorterReset(db, pSorter);
  89125. sqlite3_free(pSorter->list.aMemory);
  89126. sqlite3DbFree(db, pSorter);
  89127. pCsr->uc.pSorter = 0;
  89128. }
  89129. }
  89130. #if SQLITE_MAX_MMAP_SIZE>0
  89131. /*
  89132. ** The first argument is a file-handle open on a temporary file. The file
  89133. ** is guaranteed to be nByte bytes or smaller in size. This function
  89134. ** attempts to extend the file to nByte bytes in size and to ensure that
  89135. ** the VFS has memory mapped it.
  89136. **
  89137. ** Whether or not the file does end up memory mapped of course depends on
  89138. ** the specific VFS implementation.
  89139. */
  89140. static void vdbeSorterExtendFile(sqlite3 *db, sqlite3_file *pFd, i64 nByte){
  89141. if( nByte<=(i64)(db->nMaxSorterMmap) && pFd->pMethods->iVersion>=3 ){
  89142. void *p = 0;
  89143. int chunksize = 4*1024;
  89144. sqlite3OsFileControlHint(pFd, SQLITE_FCNTL_CHUNK_SIZE, &chunksize);
  89145. sqlite3OsFileControlHint(pFd, SQLITE_FCNTL_SIZE_HINT, &nByte);
  89146. sqlite3OsFetch(pFd, 0, (int)nByte, &p);
  89147. sqlite3OsUnfetch(pFd, 0, p);
  89148. }
  89149. }
  89150. #else
  89151. # define vdbeSorterExtendFile(x,y,z)
  89152. #endif
  89153. /*
  89154. ** Allocate space for a file-handle and open a temporary file. If successful,
  89155. ** set *ppFd to point to the malloc'd file-handle and return SQLITE_OK.
  89156. ** Otherwise, set *ppFd to 0 and return an SQLite error code.
  89157. */
  89158. static int vdbeSorterOpenTempFile(
  89159. sqlite3 *db, /* Database handle doing sort */
  89160. i64 nExtend, /* Attempt to extend file to this size */
  89161. sqlite3_file **ppFd
  89162. ){
  89163. int rc;
  89164. if( sqlite3FaultSim(202) ) return SQLITE_IOERR_ACCESS;
  89165. rc = sqlite3OsOpenMalloc(db->pVfs, 0, ppFd,
  89166. SQLITE_OPEN_TEMP_JOURNAL |
  89167. SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
  89168. SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE, &rc
  89169. );
  89170. if( rc==SQLITE_OK ){
  89171. i64 max = SQLITE_MAX_MMAP_SIZE;
  89172. sqlite3OsFileControlHint(*ppFd, SQLITE_FCNTL_MMAP_SIZE, (void*)&max);
  89173. if( nExtend>0 ){
  89174. vdbeSorterExtendFile(db, *ppFd, nExtend);
  89175. }
  89176. }
  89177. return rc;
  89178. }
  89179. /*
  89180. ** If it has not already been allocated, allocate the UnpackedRecord
  89181. ** structure at pTask->pUnpacked. Return SQLITE_OK if successful (or
  89182. ** if no allocation was required), or SQLITE_NOMEM otherwise.
  89183. */
  89184. static int vdbeSortAllocUnpacked(SortSubtask *pTask){
  89185. if( pTask->pUnpacked==0 ){
  89186. pTask->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pTask->pSorter->pKeyInfo);
  89187. if( pTask->pUnpacked==0 ) return SQLITE_NOMEM_BKPT;
  89188. pTask->pUnpacked->nField = pTask->pSorter->pKeyInfo->nKeyField;
  89189. pTask->pUnpacked->errCode = 0;
  89190. }
  89191. return SQLITE_OK;
  89192. }
  89193. /*
  89194. ** Merge the two sorted lists p1 and p2 into a single list.
  89195. */
  89196. static SorterRecord *vdbeSorterMerge(
  89197. SortSubtask *pTask, /* Calling thread context */
  89198. SorterRecord *p1, /* First list to merge */
  89199. SorterRecord *p2 /* Second list to merge */
  89200. ){
  89201. SorterRecord *pFinal = 0;
  89202. SorterRecord **pp = &pFinal;
  89203. int bCached = 0;
  89204. assert( p1!=0 && p2!=0 );
  89205. for(;;){
  89206. int res;
  89207. res = pTask->xCompare(
  89208. pTask, &bCached, SRVAL(p1), p1->nVal, SRVAL(p2), p2->nVal
  89209. );
  89210. if( res<=0 ){
  89211. *pp = p1;
  89212. pp = &p1->u.pNext;
  89213. p1 = p1->u.pNext;
  89214. if( p1==0 ){
  89215. *pp = p2;
  89216. break;
  89217. }
  89218. }else{
  89219. *pp = p2;
  89220. pp = &p2->u.pNext;
  89221. p2 = p2->u.pNext;
  89222. bCached = 0;
  89223. if( p2==0 ){
  89224. *pp = p1;
  89225. break;
  89226. }
  89227. }
  89228. }
  89229. return pFinal;
  89230. }
  89231. /*
  89232. ** Return the SorterCompare function to compare values collected by the
  89233. ** sorter object passed as the only argument.
  89234. */
  89235. static SorterCompare vdbeSorterGetCompare(VdbeSorter *p){
  89236. if( p->typeMask==SORTER_TYPE_INTEGER ){
  89237. return vdbeSorterCompareInt;
  89238. }else if( p->typeMask==SORTER_TYPE_TEXT ){
  89239. return vdbeSorterCompareText;
  89240. }
  89241. return vdbeSorterCompare;
  89242. }
  89243. /*
  89244. ** Sort the linked list of records headed at pTask->pList. Return
  89245. ** SQLITE_OK if successful, or an SQLite error code (i.e. SQLITE_NOMEM) if
  89246. ** an error occurs.
  89247. */
  89248. static int vdbeSorterSort(SortSubtask *pTask, SorterList *pList){
  89249. int i;
  89250. SorterRecord *p;
  89251. int rc;
  89252. SorterRecord *aSlot[64];
  89253. rc = vdbeSortAllocUnpacked(pTask);
  89254. if( rc!=SQLITE_OK ) return rc;
  89255. p = pList->pList;
  89256. pTask->xCompare = vdbeSorterGetCompare(pTask->pSorter);
  89257. memset(aSlot, 0, sizeof(aSlot));
  89258. while( p ){
  89259. SorterRecord *pNext;
  89260. if( pList->aMemory ){
  89261. if( (u8*)p==pList->aMemory ){
  89262. pNext = 0;
  89263. }else{
  89264. assert( p->u.iNext<sqlite3MallocSize(pList->aMemory) );
  89265. pNext = (SorterRecord*)&pList->aMemory[p->u.iNext];
  89266. }
  89267. }else{
  89268. pNext = p->u.pNext;
  89269. }
  89270. p->u.pNext = 0;
  89271. for(i=0; aSlot[i]; i++){
  89272. p = vdbeSorterMerge(pTask, p, aSlot[i]);
  89273. aSlot[i] = 0;
  89274. }
  89275. aSlot[i] = p;
  89276. p = pNext;
  89277. }
  89278. p = 0;
  89279. for(i=0; i<ArraySize(aSlot); i++){
  89280. if( aSlot[i]==0 ) continue;
  89281. p = p ? vdbeSorterMerge(pTask, p, aSlot[i]) : aSlot[i];
  89282. }
  89283. pList->pList = p;
  89284. assert( pTask->pUnpacked->errCode==SQLITE_OK
  89285. || pTask->pUnpacked->errCode==SQLITE_NOMEM
  89286. );
  89287. return pTask->pUnpacked->errCode;
  89288. }
  89289. /*
  89290. ** Initialize a PMA-writer object.
  89291. */
  89292. static void vdbePmaWriterInit(
  89293. sqlite3_file *pFd, /* File handle to write to */
  89294. PmaWriter *p, /* Object to populate */
  89295. int nBuf, /* Buffer size */
  89296. i64 iStart /* Offset of pFd to begin writing at */
  89297. ){
  89298. memset(p, 0, sizeof(PmaWriter));
  89299. p->aBuffer = (u8*)sqlite3Malloc(nBuf);
  89300. if( !p->aBuffer ){
  89301. p->eFWErr = SQLITE_NOMEM_BKPT;
  89302. }else{
  89303. p->iBufEnd = p->iBufStart = (iStart % nBuf);
  89304. p->iWriteOff = iStart - p->iBufStart;
  89305. p->nBuffer = nBuf;
  89306. p->pFd = pFd;
  89307. }
  89308. }
  89309. /*
  89310. ** Write nData bytes of data to the PMA. Return SQLITE_OK
  89311. ** if successful, or an SQLite error code if an error occurs.
  89312. */
  89313. static void vdbePmaWriteBlob(PmaWriter *p, u8 *pData, int nData){
  89314. int nRem = nData;
  89315. while( nRem>0 && p->eFWErr==0 ){
  89316. int nCopy = nRem;
  89317. if( nCopy>(p->nBuffer - p->iBufEnd) ){
  89318. nCopy = p->nBuffer - p->iBufEnd;
  89319. }
  89320. memcpy(&p->aBuffer[p->iBufEnd], &pData[nData-nRem], nCopy);
  89321. p->iBufEnd += nCopy;
  89322. if( p->iBufEnd==p->nBuffer ){
  89323. p->eFWErr = sqlite3OsWrite(p->pFd,
  89324. &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
  89325. p->iWriteOff + p->iBufStart
  89326. );
  89327. p->iBufStart = p->iBufEnd = 0;
  89328. p->iWriteOff += p->nBuffer;
  89329. }
  89330. assert( p->iBufEnd<p->nBuffer );
  89331. nRem -= nCopy;
  89332. }
  89333. }
  89334. /*
  89335. ** Flush any buffered data to disk and clean up the PMA-writer object.
  89336. ** The results of using the PMA-writer after this call are undefined.
  89337. ** Return SQLITE_OK if flushing the buffered data succeeds or is not
  89338. ** required. Otherwise, return an SQLite error code.
  89339. **
  89340. ** Before returning, set *piEof to the offset immediately following the
  89341. ** last byte written to the file.
  89342. */
  89343. static int vdbePmaWriterFinish(PmaWriter *p, i64 *piEof){
  89344. int rc;
  89345. if( p->eFWErr==0 && ALWAYS(p->aBuffer) && p->iBufEnd>p->iBufStart ){
  89346. p->eFWErr = sqlite3OsWrite(p->pFd,
  89347. &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
  89348. p->iWriteOff + p->iBufStart
  89349. );
  89350. }
  89351. *piEof = (p->iWriteOff + p->iBufEnd);
  89352. sqlite3_free(p->aBuffer);
  89353. rc = p->eFWErr;
  89354. memset(p, 0, sizeof(PmaWriter));
  89355. return rc;
  89356. }
  89357. /*
  89358. ** Write value iVal encoded as a varint to the PMA. Return
  89359. ** SQLITE_OK if successful, or an SQLite error code if an error occurs.
  89360. */
  89361. static void vdbePmaWriteVarint(PmaWriter *p, u64 iVal){
  89362. int nByte;
  89363. u8 aByte[10];
  89364. nByte = sqlite3PutVarint(aByte, iVal);
  89365. vdbePmaWriteBlob(p, aByte, nByte);
  89366. }
  89367. /*
  89368. ** Write the current contents of in-memory linked-list pList to a level-0
  89369. ** PMA in the temp file belonging to sub-task pTask. Return SQLITE_OK if
  89370. ** successful, or an SQLite error code otherwise.
  89371. **
  89372. ** The format of a PMA is:
  89373. **
  89374. ** * A varint. This varint contains the total number of bytes of content
  89375. ** in the PMA (not including the varint itself).
  89376. **
  89377. ** * One or more records packed end-to-end in order of ascending keys.
  89378. ** Each record consists of a varint followed by a blob of data (the
  89379. ** key). The varint is the number of bytes in the blob of data.
  89380. */
  89381. static int vdbeSorterListToPMA(SortSubtask *pTask, SorterList *pList){
  89382. sqlite3 *db = pTask->pSorter->db;
  89383. int rc = SQLITE_OK; /* Return code */
  89384. PmaWriter writer; /* Object used to write to the file */
  89385. #ifdef SQLITE_DEBUG
  89386. /* Set iSz to the expected size of file pTask->file after writing the PMA.
  89387. ** This is used by an assert() statement at the end of this function. */
  89388. i64 iSz = pList->szPMA + sqlite3VarintLen(pList->szPMA) + pTask->file.iEof;
  89389. #endif
  89390. vdbeSorterWorkDebug(pTask, "enter");
  89391. memset(&writer, 0, sizeof(PmaWriter));
  89392. assert( pList->szPMA>0 );
  89393. /* If the first temporary PMA file has not been opened, open it now. */
  89394. if( pTask->file.pFd==0 ){
  89395. rc = vdbeSorterOpenTempFile(db, 0, &pTask->file.pFd);
  89396. assert( rc!=SQLITE_OK || pTask->file.pFd );
  89397. assert( pTask->file.iEof==0 );
  89398. assert( pTask->nPMA==0 );
  89399. }
  89400. /* Try to get the file to memory map */
  89401. if( rc==SQLITE_OK ){
  89402. vdbeSorterExtendFile(db, pTask->file.pFd, pTask->file.iEof+pList->szPMA+9);
  89403. }
  89404. /* Sort the list */
  89405. if( rc==SQLITE_OK ){
  89406. rc = vdbeSorterSort(pTask, pList);
  89407. }
  89408. if( rc==SQLITE_OK ){
  89409. SorterRecord *p;
  89410. SorterRecord *pNext = 0;
  89411. vdbePmaWriterInit(pTask->file.pFd, &writer, pTask->pSorter->pgsz,
  89412. pTask->file.iEof);
  89413. pTask->nPMA++;
  89414. vdbePmaWriteVarint(&writer, pList->szPMA);
  89415. for(p=pList->pList; p; p=pNext){
  89416. pNext = p->u.pNext;
  89417. vdbePmaWriteVarint(&writer, p->nVal);
  89418. vdbePmaWriteBlob(&writer, SRVAL(p), p->nVal);
  89419. if( pList->aMemory==0 ) sqlite3_free(p);
  89420. }
  89421. pList->pList = p;
  89422. rc = vdbePmaWriterFinish(&writer, &pTask->file.iEof);
  89423. }
  89424. vdbeSorterWorkDebug(pTask, "exit");
  89425. assert( rc!=SQLITE_OK || pList->pList==0 );
  89426. assert( rc!=SQLITE_OK || pTask->file.iEof==iSz );
  89427. return rc;
  89428. }
  89429. /*
  89430. ** Advance the MergeEngine to its next entry.
  89431. ** Set *pbEof to true there is no next entry because
  89432. ** the MergeEngine has reached the end of all its inputs.
  89433. **
  89434. ** Return SQLITE_OK if successful or an error code if an error occurs.
  89435. */
  89436. static int vdbeMergeEngineStep(
  89437. MergeEngine *pMerger, /* The merge engine to advance to the next row */
  89438. int *pbEof /* Set TRUE at EOF. Set false for more content */
  89439. ){
  89440. int rc;
  89441. int iPrev = pMerger->aTree[1];/* Index of PmaReader to advance */
  89442. SortSubtask *pTask = pMerger->pTask;
  89443. /* Advance the current PmaReader */
  89444. rc = vdbePmaReaderNext(&pMerger->aReadr[iPrev]);
  89445. /* Update contents of aTree[] */
  89446. if( rc==SQLITE_OK ){
  89447. int i; /* Index of aTree[] to recalculate */
  89448. PmaReader *pReadr1; /* First PmaReader to compare */
  89449. PmaReader *pReadr2; /* Second PmaReader to compare */
  89450. int bCached = 0;
  89451. /* Find the first two PmaReaders to compare. The one that was just
  89452. ** advanced (iPrev) and the one next to it in the array. */
  89453. pReadr1 = &pMerger->aReadr[(iPrev & 0xFFFE)];
  89454. pReadr2 = &pMerger->aReadr[(iPrev | 0x0001)];
  89455. for(i=(pMerger->nTree+iPrev)/2; i>0; i=i/2){
  89456. /* Compare pReadr1 and pReadr2. Store the result in variable iRes. */
  89457. int iRes;
  89458. if( pReadr1->pFd==0 ){
  89459. iRes = +1;
  89460. }else if( pReadr2->pFd==0 ){
  89461. iRes = -1;
  89462. }else{
  89463. iRes = pTask->xCompare(pTask, &bCached,
  89464. pReadr1->aKey, pReadr1->nKey, pReadr2->aKey, pReadr2->nKey
  89465. );
  89466. }
  89467. /* If pReadr1 contained the smaller value, set aTree[i] to its index.
  89468. ** Then set pReadr2 to the next PmaReader to compare to pReadr1. In this
  89469. ** case there is no cache of pReadr2 in pTask->pUnpacked, so set
  89470. ** pKey2 to point to the record belonging to pReadr2.
  89471. **
  89472. ** Alternatively, if pReadr2 contains the smaller of the two values,
  89473. ** set aTree[i] to its index and update pReadr1. If vdbeSorterCompare()
  89474. ** was actually called above, then pTask->pUnpacked now contains
  89475. ** a value equivalent to pReadr2. So set pKey2 to NULL to prevent
  89476. ** vdbeSorterCompare() from decoding pReadr2 again.
  89477. **
  89478. ** If the two values were equal, then the value from the oldest
  89479. ** PMA should be considered smaller. The VdbeSorter.aReadr[] array
  89480. ** is sorted from oldest to newest, so pReadr1 contains older values
  89481. ** than pReadr2 iff (pReadr1<pReadr2). */
  89482. if( iRes<0 || (iRes==0 && pReadr1<pReadr2) ){
  89483. pMerger->aTree[i] = (int)(pReadr1 - pMerger->aReadr);
  89484. pReadr2 = &pMerger->aReadr[ pMerger->aTree[i ^ 0x0001] ];
  89485. bCached = 0;
  89486. }else{
  89487. if( pReadr1->pFd ) bCached = 0;
  89488. pMerger->aTree[i] = (int)(pReadr2 - pMerger->aReadr);
  89489. pReadr1 = &pMerger->aReadr[ pMerger->aTree[i ^ 0x0001] ];
  89490. }
  89491. }
  89492. *pbEof = (pMerger->aReadr[pMerger->aTree[1]].pFd==0);
  89493. }
  89494. return (rc==SQLITE_OK ? pTask->pUnpacked->errCode : rc);
  89495. }
  89496. #if SQLITE_MAX_WORKER_THREADS>0
  89497. /*
  89498. ** The main routine for background threads that write level-0 PMAs.
  89499. */
  89500. static void *vdbeSorterFlushThread(void *pCtx){
  89501. SortSubtask *pTask = (SortSubtask*)pCtx;
  89502. int rc; /* Return code */
  89503. assert( pTask->bDone==0 );
  89504. rc = vdbeSorterListToPMA(pTask, &pTask->list);
  89505. pTask->bDone = 1;
  89506. return SQLITE_INT_TO_PTR(rc);
  89507. }
  89508. #endif /* SQLITE_MAX_WORKER_THREADS>0 */
  89509. /*
  89510. ** Flush the current contents of VdbeSorter.list to a new PMA, possibly
  89511. ** using a background thread.
  89512. */
  89513. static int vdbeSorterFlushPMA(VdbeSorter *pSorter){
  89514. #if SQLITE_MAX_WORKER_THREADS==0
  89515. pSorter->bUsePMA = 1;
  89516. return vdbeSorterListToPMA(&pSorter->aTask[0], &pSorter->list);
  89517. #else
  89518. int rc = SQLITE_OK;
  89519. int i;
  89520. SortSubtask *pTask = 0; /* Thread context used to create new PMA */
  89521. int nWorker = (pSorter->nTask-1);
  89522. /* Set the flag to indicate that at least one PMA has been written.
  89523. ** Or will be, anyhow. */
  89524. pSorter->bUsePMA = 1;
  89525. /* Select a sub-task to sort and flush the current list of in-memory
  89526. ** records to disk. If the sorter is running in multi-threaded mode,
  89527. ** round-robin between the first (pSorter->nTask-1) tasks. Except, if
  89528. ** the background thread from a sub-tasks previous turn is still running,
  89529. ** skip it. If the first (pSorter->nTask-1) sub-tasks are all still busy,
  89530. ** fall back to using the final sub-task. The first (pSorter->nTask-1)
  89531. ** sub-tasks are prefered as they use background threads - the final
  89532. ** sub-task uses the main thread. */
  89533. for(i=0; i<nWorker; i++){
  89534. int iTest = (pSorter->iPrev + i + 1) % nWorker;
  89535. pTask = &pSorter->aTask[iTest];
  89536. if( pTask->bDone ){
  89537. rc = vdbeSorterJoinThread(pTask);
  89538. }
  89539. if( rc!=SQLITE_OK || pTask->pThread==0 ) break;
  89540. }
  89541. if( rc==SQLITE_OK ){
  89542. if( i==nWorker ){
  89543. /* Use the foreground thread for this operation */
  89544. rc = vdbeSorterListToPMA(&pSorter->aTask[nWorker], &pSorter->list);
  89545. }else{
  89546. /* Launch a background thread for this operation */
  89547. u8 *aMem;
  89548. void *pCtx;
  89549. assert( pTask!=0 );
  89550. assert( pTask->pThread==0 && pTask->bDone==0 );
  89551. assert( pTask->list.pList==0 );
  89552. assert( pTask->list.aMemory==0 || pSorter->list.aMemory!=0 );
  89553. aMem = pTask->list.aMemory;
  89554. pCtx = (void*)pTask;
  89555. pSorter->iPrev = (u8)(pTask - pSorter->aTask);
  89556. pTask->list = pSorter->list;
  89557. pSorter->list.pList = 0;
  89558. pSorter->list.szPMA = 0;
  89559. if( aMem ){
  89560. pSorter->list.aMemory = aMem;
  89561. pSorter->nMemory = sqlite3MallocSize(aMem);
  89562. }else if( pSorter->list.aMemory ){
  89563. pSorter->list.aMemory = sqlite3Malloc(pSorter->nMemory);
  89564. if( !pSorter->list.aMemory ) return SQLITE_NOMEM_BKPT;
  89565. }
  89566. rc = vdbeSorterCreateThread(pTask, vdbeSorterFlushThread, pCtx);
  89567. }
  89568. }
  89569. return rc;
  89570. #endif /* SQLITE_MAX_WORKER_THREADS!=0 */
  89571. }
  89572. /*
  89573. ** Add a record to the sorter.
  89574. */
  89575. SQLITE_PRIVATE int sqlite3VdbeSorterWrite(
  89576. const VdbeCursor *pCsr, /* Sorter cursor */
  89577. Mem *pVal /* Memory cell containing record */
  89578. ){
  89579. VdbeSorter *pSorter;
  89580. int rc = SQLITE_OK; /* Return Code */
  89581. SorterRecord *pNew; /* New list element */
  89582. int bFlush; /* True to flush contents of memory to PMA */
  89583. int nReq; /* Bytes of memory required */
  89584. int nPMA; /* Bytes of PMA space required */
  89585. int t; /* serial type of first record field */
  89586. assert( pCsr->eCurType==CURTYPE_SORTER );
  89587. pSorter = pCsr->uc.pSorter;
  89588. getVarint32NR((const u8*)&pVal->z[1], t);
  89589. if( t>0 && t<10 && t!=7 ){
  89590. pSorter->typeMask &= SORTER_TYPE_INTEGER;
  89591. }else if( t>10 && (t & 0x01) ){
  89592. pSorter->typeMask &= SORTER_TYPE_TEXT;
  89593. }else{
  89594. pSorter->typeMask = 0;
  89595. }
  89596. assert( pSorter );
  89597. /* Figure out whether or not the current contents of memory should be
  89598. ** flushed to a PMA before continuing. If so, do so.
  89599. **
  89600. ** If using the single large allocation mode (pSorter->aMemory!=0), then
  89601. ** flush the contents of memory to a new PMA if (a) at least one value is
  89602. ** already in memory and (b) the new value will not fit in memory.
  89603. **
  89604. ** Or, if using separate allocations for each record, flush the contents
  89605. ** of memory to a PMA if either of the following are true:
  89606. **
  89607. ** * The total memory allocated for the in-memory list is greater
  89608. ** than (page-size * cache-size), or
  89609. **
  89610. ** * The total memory allocated for the in-memory list is greater
  89611. ** than (page-size * 10) and sqlite3HeapNearlyFull() returns true.
  89612. */
  89613. nReq = pVal->n + sizeof(SorterRecord);
  89614. nPMA = pVal->n + sqlite3VarintLen(pVal->n);
  89615. if( pSorter->mxPmaSize ){
  89616. if( pSorter->list.aMemory ){
  89617. bFlush = pSorter->iMemory && (pSorter->iMemory+nReq) > pSorter->mxPmaSize;
  89618. }else{
  89619. bFlush = (
  89620. (pSorter->list.szPMA > pSorter->mxPmaSize)
  89621. || (pSorter->list.szPMA > pSorter->mnPmaSize && sqlite3HeapNearlyFull())
  89622. );
  89623. }
  89624. if( bFlush ){
  89625. rc = vdbeSorterFlushPMA(pSorter);
  89626. pSorter->list.szPMA = 0;
  89627. pSorter->iMemory = 0;
  89628. assert( rc!=SQLITE_OK || pSorter->list.pList==0 );
  89629. }
  89630. }
  89631. pSorter->list.szPMA += nPMA;
  89632. if( nPMA>pSorter->mxKeysize ){
  89633. pSorter->mxKeysize = nPMA;
  89634. }
  89635. if( pSorter->list.aMemory ){
  89636. int nMin = pSorter->iMemory + nReq;
  89637. if( nMin>pSorter->nMemory ){
  89638. u8 *aNew;
  89639. sqlite3_int64 nNew = 2 * (sqlite3_int64)pSorter->nMemory;
  89640. int iListOff = -1;
  89641. if( pSorter->list.pList ){
  89642. iListOff = (u8*)pSorter->list.pList - pSorter->list.aMemory;
  89643. }
  89644. while( nNew < nMin ) nNew = nNew*2;
  89645. if( nNew > pSorter->mxPmaSize ) nNew = pSorter->mxPmaSize;
  89646. if( nNew < nMin ) nNew = nMin;
  89647. aNew = sqlite3Realloc(pSorter->list.aMemory, nNew);
  89648. if( !aNew ) return SQLITE_NOMEM_BKPT;
  89649. if( iListOff>=0 ){
  89650. pSorter->list.pList = (SorterRecord*)&aNew[iListOff];
  89651. }
  89652. pSorter->list.aMemory = aNew;
  89653. pSorter->nMemory = nNew;
  89654. }
  89655. pNew = (SorterRecord*)&pSorter->list.aMemory[pSorter->iMemory];
  89656. pSorter->iMemory += ROUND8(nReq);
  89657. if( pSorter->list.pList ){
  89658. pNew->u.iNext = (int)((u8*)(pSorter->list.pList) - pSorter->list.aMemory);
  89659. }
  89660. }else{
  89661. pNew = (SorterRecord *)sqlite3Malloc(nReq);
  89662. if( pNew==0 ){
  89663. return SQLITE_NOMEM_BKPT;
  89664. }
  89665. pNew->u.pNext = pSorter->list.pList;
  89666. }
  89667. memcpy(SRVAL(pNew), pVal->z, pVal->n);
  89668. pNew->nVal = pVal->n;
  89669. pSorter->list.pList = pNew;
  89670. return rc;
  89671. }
  89672. /*
  89673. ** Read keys from pIncr->pMerger and populate pIncr->aFile[1]. The format
  89674. ** of the data stored in aFile[1] is the same as that used by regular PMAs,
  89675. ** except that the number-of-bytes varint is omitted from the start.
  89676. */
  89677. static int vdbeIncrPopulate(IncrMerger *pIncr){
  89678. int rc = SQLITE_OK;
  89679. int rc2;
  89680. i64 iStart = pIncr->iStartOff;
  89681. SorterFile *pOut = &pIncr->aFile[1];
  89682. SortSubtask *pTask = pIncr->pTask;
  89683. MergeEngine *pMerger = pIncr->pMerger;
  89684. PmaWriter writer;
  89685. assert( pIncr->bEof==0 );
  89686. vdbeSorterPopulateDebug(pTask, "enter");
  89687. vdbePmaWriterInit(pOut->pFd, &writer, pTask->pSorter->pgsz, iStart);
  89688. while( rc==SQLITE_OK ){
  89689. int dummy;
  89690. PmaReader *pReader = &pMerger->aReadr[ pMerger->aTree[1] ];
  89691. int nKey = pReader->nKey;
  89692. i64 iEof = writer.iWriteOff + writer.iBufEnd;
  89693. /* Check if the output file is full or if the input has been exhausted.
  89694. ** In either case exit the loop. */
  89695. if( pReader->pFd==0 ) break;
  89696. if( (iEof + nKey + sqlite3VarintLen(nKey))>(iStart + pIncr->mxSz) ) break;
  89697. /* Write the next key to the output. */
  89698. vdbePmaWriteVarint(&writer, nKey);
  89699. vdbePmaWriteBlob(&writer, pReader->aKey, nKey);
  89700. assert( pIncr->pMerger->pTask==pTask );
  89701. rc = vdbeMergeEngineStep(pIncr->pMerger, &dummy);
  89702. }
  89703. rc2 = vdbePmaWriterFinish(&writer, &pOut->iEof);
  89704. if( rc==SQLITE_OK ) rc = rc2;
  89705. vdbeSorterPopulateDebug(pTask, "exit");
  89706. return rc;
  89707. }
  89708. #if SQLITE_MAX_WORKER_THREADS>0
  89709. /*
  89710. ** The main routine for background threads that populate aFile[1] of
  89711. ** multi-threaded IncrMerger objects.
  89712. */
  89713. static void *vdbeIncrPopulateThread(void *pCtx){
  89714. IncrMerger *pIncr = (IncrMerger*)pCtx;
  89715. void *pRet = SQLITE_INT_TO_PTR( vdbeIncrPopulate(pIncr) );
  89716. pIncr->pTask->bDone = 1;
  89717. return pRet;
  89718. }
  89719. /*
  89720. ** Launch a background thread to populate aFile[1] of pIncr.
  89721. */
  89722. static int vdbeIncrBgPopulate(IncrMerger *pIncr){
  89723. void *p = (void*)pIncr;
  89724. assert( pIncr->bUseThread );
  89725. return vdbeSorterCreateThread(pIncr->pTask, vdbeIncrPopulateThread, p);
  89726. }
  89727. #endif
  89728. /*
  89729. ** This function is called when the PmaReader corresponding to pIncr has
  89730. ** finished reading the contents of aFile[0]. Its purpose is to "refill"
  89731. ** aFile[0] such that the PmaReader should start rereading it from the
  89732. ** beginning.
  89733. **
  89734. ** For single-threaded objects, this is accomplished by literally reading
  89735. ** keys from pIncr->pMerger and repopulating aFile[0].
  89736. **
  89737. ** For multi-threaded objects, all that is required is to wait until the
  89738. ** background thread is finished (if it is not already) and then swap
  89739. ** aFile[0] and aFile[1] in place. If the contents of pMerger have not
  89740. ** been exhausted, this function also launches a new background thread
  89741. ** to populate the new aFile[1].
  89742. **
  89743. ** SQLITE_OK is returned on success, or an SQLite error code otherwise.
  89744. */
  89745. static int vdbeIncrSwap(IncrMerger *pIncr){
  89746. int rc = SQLITE_OK;
  89747. #if SQLITE_MAX_WORKER_THREADS>0
  89748. if( pIncr->bUseThread ){
  89749. rc = vdbeSorterJoinThread(pIncr->pTask);
  89750. if( rc==SQLITE_OK ){
  89751. SorterFile f0 = pIncr->aFile[0];
  89752. pIncr->aFile[0] = pIncr->aFile[1];
  89753. pIncr->aFile[1] = f0;
  89754. }
  89755. if( rc==SQLITE_OK ){
  89756. if( pIncr->aFile[0].iEof==pIncr->iStartOff ){
  89757. pIncr->bEof = 1;
  89758. }else{
  89759. rc = vdbeIncrBgPopulate(pIncr);
  89760. }
  89761. }
  89762. }else
  89763. #endif
  89764. {
  89765. rc = vdbeIncrPopulate(pIncr);
  89766. pIncr->aFile[0] = pIncr->aFile[1];
  89767. if( pIncr->aFile[0].iEof==pIncr->iStartOff ){
  89768. pIncr->bEof = 1;
  89769. }
  89770. }
  89771. return rc;
  89772. }
  89773. /*
  89774. ** Allocate and return a new IncrMerger object to read data from pMerger.
  89775. **
  89776. ** If an OOM condition is encountered, return NULL. In this case free the
  89777. ** pMerger argument before returning.
  89778. */
  89779. static int vdbeIncrMergerNew(
  89780. SortSubtask *pTask, /* The thread that will be using the new IncrMerger */
  89781. MergeEngine *pMerger, /* The MergeEngine that the IncrMerger will control */
  89782. IncrMerger **ppOut /* Write the new IncrMerger here */
  89783. ){
  89784. int rc = SQLITE_OK;
  89785. IncrMerger *pIncr = *ppOut = (IncrMerger*)
  89786. (sqlite3FaultSim(100) ? 0 : sqlite3MallocZero(sizeof(*pIncr)));
  89787. if( pIncr ){
  89788. pIncr->pMerger = pMerger;
  89789. pIncr->pTask = pTask;
  89790. pIncr->mxSz = MAX(pTask->pSorter->mxKeysize+9,pTask->pSorter->mxPmaSize/2);
  89791. pTask->file2.iEof += pIncr->mxSz;
  89792. }else{
  89793. vdbeMergeEngineFree(pMerger);
  89794. rc = SQLITE_NOMEM_BKPT;
  89795. }
  89796. return rc;
  89797. }
  89798. #if SQLITE_MAX_WORKER_THREADS>0
  89799. /*
  89800. ** Set the "use-threads" flag on object pIncr.
  89801. */
  89802. static void vdbeIncrMergerSetThreads(IncrMerger *pIncr){
  89803. pIncr->bUseThread = 1;
  89804. pIncr->pTask->file2.iEof -= pIncr->mxSz;
  89805. }
  89806. #endif /* SQLITE_MAX_WORKER_THREADS>0 */
  89807. /*
  89808. ** Recompute pMerger->aTree[iOut] by comparing the next keys on the
  89809. ** two PmaReaders that feed that entry. Neither of the PmaReaders
  89810. ** are advanced. This routine merely does the comparison.
  89811. */
  89812. static void vdbeMergeEngineCompare(
  89813. MergeEngine *pMerger, /* Merge engine containing PmaReaders to compare */
  89814. int iOut /* Store the result in pMerger->aTree[iOut] */
  89815. ){
  89816. int i1;
  89817. int i2;
  89818. int iRes;
  89819. PmaReader *p1;
  89820. PmaReader *p2;
  89821. assert( iOut<pMerger->nTree && iOut>0 );
  89822. if( iOut>=(pMerger->nTree/2) ){
  89823. i1 = (iOut - pMerger->nTree/2) * 2;
  89824. i2 = i1 + 1;
  89825. }else{
  89826. i1 = pMerger->aTree[iOut*2];
  89827. i2 = pMerger->aTree[iOut*2+1];
  89828. }
  89829. p1 = &pMerger->aReadr[i1];
  89830. p2 = &pMerger->aReadr[i2];
  89831. if( p1->pFd==0 ){
  89832. iRes = i2;
  89833. }else if( p2->pFd==0 ){
  89834. iRes = i1;
  89835. }else{
  89836. SortSubtask *pTask = pMerger->pTask;
  89837. int bCached = 0;
  89838. int res;
  89839. assert( pTask->pUnpacked!=0 ); /* from vdbeSortSubtaskMain() */
  89840. res = pTask->xCompare(
  89841. pTask, &bCached, p1->aKey, p1->nKey, p2->aKey, p2->nKey
  89842. );
  89843. if( res<=0 ){
  89844. iRes = i1;
  89845. }else{
  89846. iRes = i2;
  89847. }
  89848. }
  89849. pMerger->aTree[iOut] = iRes;
  89850. }
  89851. /*
  89852. ** Allowed values for the eMode parameter to vdbeMergeEngineInit()
  89853. ** and vdbePmaReaderIncrMergeInit().
  89854. **
  89855. ** Only INCRINIT_NORMAL is valid in single-threaded builds (when
  89856. ** SQLITE_MAX_WORKER_THREADS==0). The other values are only used
  89857. ** when there exists one or more separate worker threads.
  89858. */
  89859. #define INCRINIT_NORMAL 0
  89860. #define INCRINIT_TASK 1
  89861. #define INCRINIT_ROOT 2
  89862. /*
  89863. ** Forward reference required as the vdbeIncrMergeInit() and
  89864. ** vdbePmaReaderIncrInit() routines are called mutually recursively when
  89865. ** building a merge tree.
  89866. */
  89867. static int vdbePmaReaderIncrInit(PmaReader *pReadr, int eMode);
  89868. /*
  89869. ** Initialize the MergeEngine object passed as the second argument. Once this
  89870. ** function returns, the first key of merged data may be read from the
  89871. ** MergeEngine object in the usual fashion.
  89872. **
  89873. ** If argument eMode is INCRINIT_ROOT, then it is assumed that any IncrMerge
  89874. ** objects attached to the PmaReader objects that the merger reads from have
  89875. ** already been populated, but that they have not yet populated aFile[0] and
  89876. ** set the PmaReader objects up to read from it. In this case all that is
  89877. ** required is to call vdbePmaReaderNext() on each PmaReader to point it at
  89878. ** its first key.
  89879. **
  89880. ** Otherwise, if eMode is any value other than INCRINIT_ROOT, then use
  89881. ** vdbePmaReaderIncrMergeInit() to initialize each PmaReader that feeds data
  89882. ** to pMerger.
  89883. **
  89884. ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
  89885. */
  89886. static int vdbeMergeEngineInit(
  89887. SortSubtask *pTask, /* Thread that will run pMerger */
  89888. MergeEngine *pMerger, /* MergeEngine to initialize */
  89889. int eMode /* One of the INCRINIT_XXX constants */
  89890. ){
  89891. int rc = SQLITE_OK; /* Return code */
  89892. int i; /* For looping over PmaReader objects */
  89893. int nTree; /* Number of subtrees to merge */
  89894. /* Failure to allocate the merge would have been detected prior to
  89895. ** invoking this routine */
  89896. assert( pMerger!=0 );
  89897. /* eMode is always INCRINIT_NORMAL in single-threaded mode */
  89898. assert( SQLITE_MAX_WORKER_THREADS>0 || eMode==INCRINIT_NORMAL );
  89899. /* Verify that the MergeEngine is assigned to a single thread */
  89900. assert( pMerger->pTask==0 );
  89901. pMerger->pTask = pTask;
  89902. nTree = pMerger->nTree;
  89903. for(i=0; i<nTree; i++){
  89904. if( SQLITE_MAX_WORKER_THREADS>0 && eMode==INCRINIT_ROOT ){
  89905. /* PmaReaders should be normally initialized in order, as if they are
  89906. ** reading from the same temp file this makes for more linear file IO.
  89907. ** However, in the INCRINIT_ROOT case, if PmaReader aReadr[nTask-1] is
  89908. ** in use it will block the vdbePmaReaderNext() call while it uses
  89909. ** the main thread to fill its buffer. So calling PmaReaderNext()
  89910. ** on this PmaReader before any of the multi-threaded PmaReaders takes
  89911. ** better advantage of multi-processor hardware. */
  89912. rc = vdbePmaReaderNext(&pMerger->aReadr[nTree-i-1]);
  89913. }else{
  89914. rc = vdbePmaReaderIncrInit(&pMerger->aReadr[i], INCRINIT_NORMAL);
  89915. }
  89916. if( rc!=SQLITE_OK ) return rc;
  89917. }
  89918. for(i=pMerger->nTree-1; i>0; i--){
  89919. vdbeMergeEngineCompare(pMerger, i);
  89920. }
  89921. return pTask->pUnpacked->errCode;
  89922. }
  89923. /*
  89924. ** The PmaReader passed as the first argument is guaranteed to be an
  89925. ** incremental-reader (pReadr->pIncr!=0). This function serves to open
  89926. ** and/or initialize the temp file related fields of the IncrMerge
  89927. ** object at (pReadr->pIncr).
  89928. **
  89929. ** If argument eMode is set to INCRINIT_NORMAL, then all PmaReaders
  89930. ** in the sub-tree headed by pReadr are also initialized. Data is then
  89931. ** loaded into the buffers belonging to pReadr and it is set to point to
  89932. ** the first key in its range.
  89933. **
  89934. ** If argument eMode is set to INCRINIT_TASK, then pReadr is guaranteed
  89935. ** to be a multi-threaded PmaReader and this function is being called in a
  89936. ** background thread. In this case all PmaReaders in the sub-tree are
  89937. ** initialized as for INCRINIT_NORMAL and the aFile[1] buffer belonging to
  89938. ** pReadr is populated. However, pReadr itself is not set up to point
  89939. ** to its first key. A call to vdbePmaReaderNext() is still required to do
  89940. ** that.
  89941. **
  89942. ** The reason this function does not call vdbePmaReaderNext() immediately
  89943. ** in the INCRINIT_TASK case is that vdbePmaReaderNext() assumes that it has
  89944. ** to block on thread (pTask->thread) before accessing aFile[1]. But, since
  89945. ** this entire function is being run by thread (pTask->thread), that will
  89946. ** lead to the current background thread attempting to join itself.
  89947. **
  89948. ** Finally, if argument eMode is set to INCRINIT_ROOT, it may be assumed
  89949. ** that pReadr->pIncr is a multi-threaded IncrMerge objects, and that all
  89950. ** child-trees have already been initialized using IncrInit(INCRINIT_TASK).
  89951. ** In this case vdbePmaReaderNext() is called on all child PmaReaders and
  89952. ** the current PmaReader set to point to the first key in its range.
  89953. **
  89954. ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
  89955. */
  89956. static int vdbePmaReaderIncrMergeInit(PmaReader *pReadr, int eMode){
  89957. int rc = SQLITE_OK;
  89958. IncrMerger *pIncr = pReadr->pIncr;
  89959. SortSubtask *pTask = pIncr->pTask;
  89960. sqlite3 *db = pTask->pSorter->db;
  89961. /* eMode is always INCRINIT_NORMAL in single-threaded mode */
  89962. assert( SQLITE_MAX_WORKER_THREADS>0 || eMode==INCRINIT_NORMAL );
  89963. rc = vdbeMergeEngineInit(pTask, pIncr->pMerger, eMode);
  89964. /* Set up the required files for pIncr. A multi-theaded IncrMerge object
  89965. ** requires two temp files to itself, whereas a single-threaded object
  89966. ** only requires a region of pTask->file2. */
  89967. if( rc==SQLITE_OK ){
  89968. int mxSz = pIncr->mxSz;
  89969. #if SQLITE_MAX_WORKER_THREADS>0
  89970. if( pIncr->bUseThread ){
  89971. rc = vdbeSorterOpenTempFile(db, mxSz, &pIncr->aFile[0].pFd);
  89972. if( rc==SQLITE_OK ){
  89973. rc = vdbeSorterOpenTempFile(db, mxSz, &pIncr->aFile[1].pFd);
  89974. }
  89975. }else
  89976. #endif
  89977. /*if( !pIncr->bUseThread )*/{
  89978. if( pTask->file2.pFd==0 ){
  89979. assert( pTask->file2.iEof>0 );
  89980. rc = vdbeSorterOpenTempFile(db, pTask->file2.iEof, &pTask->file2.pFd);
  89981. pTask->file2.iEof = 0;
  89982. }
  89983. if( rc==SQLITE_OK ){
  89984. pIncr->aFile[1].pFd = pTask->file2.pFd;
  89985. pIncr->iStartOff = pTask->file2.iEof;
  89986. pTask->file2.iEof += mxSz;
  89987. }
  89988. }
  89989. }
  89990. #if SQLITE_MAX_WORKER_THREADS>0
  89991. if( rc==SQLITE_OK && pIncr->bUseThread ){
  89992. /* Use the current thread to populate aFile[1], even though this
  89993. ** PmaReader is multi-threaded. If this is an INCRINIT_TASK object,
  89994. ** then this function is already running in background thread
  89995. ** pIncr->pTask->thread.
  89996. **
  89997. ** If this is the INCRINIT_ROOT object, then it is running in the
  89998. ** main VDBE thread. But that is Ok, as that thread cannot return
  89999. ** control to the VDBE or proceed with anything useful until the
  90000. ** first results are ready from this merger object anyway.
  90001. */
  90002. assert( eMode==INCRINIT_ROOT || eMode==INCRINIT_TASK );
  90003. rc = vdbeIncrPopulate(pIncr);
  90004. }
  90005. #endif
  90006. if( rc==SQLITE_OK && (SQLITE_MAX_WORKER_THREADS==0 || eMode!=INCRINIT_TASK) ){
  90007. rc = vdbePmaReaderNext(pReadr);
  90008. }
  90009. return rc;
  90010. }
  90011. #if SQLITE_MAX_WORKER_THREADS>0
  90012. /*
  90013. ** The main routine for vdbePmaReaderIncrMergeInit() operations run in
  90014. ** background threads.
  90015. */
  90016. static void *vdbePmaReaderBgIncrInit(void *pCtx){
  90017. PmaReader *pReader = (PmaReader*)pCtx;
  90018. void *pRet = SQLITE_INT_TO_PTR(
  90019. vdbePmaReaderIncrMergeInit(pReader,INCRINIT_TASK)
  90020. );
  90021. pReader->pIncr->pTask->bDone = 1;
  90022. return pRet;
  90023. }
  90024. #endif
  90025. /*
  90026. ** If the PmaReader passed as the first argument is not an incremental-reader
  90027. ** (if pReadr->pIncr==0), then this function is a no-op. Otherwise, it invokes
  90028. ** the vdbePmaReaderIncrMergeInit() function with the parameters passed to
  90029. ** this routine to initialize the incremental merge.
  90030. **
  90031. ** If the IncrMerger object is multi-threaded (IncrMerger.bUseThread==1),
  90032. ** then a background thread is launched to call vdbePmaReaderIncrMergeInit().
  90033. ** Or, if the IncrMerger is single threaded, the same function is called
  90034. ** using the current thread.
  90035. */
  90036. static int vdbePmaReaderIncrInit(PmaReader *pReadr, int eMode){
  90037. IncrMerger *pIncr = pReadr->pIncr; /* Incremental merger */
  90038. int rc = SQLITE_OK; /* Return code */
  90039. if( pIncr ){
  90040. #if SQLITE_MAX_WORKER_THREADS>0
  90041. assert( pIncr->bUseThread==0 || eMode==INCRINIT_TASK );
  90042. if( pIncr->bUseThread ){
  90043. void *pCtx = (void*)pReadr;
  90044. rc = vdbeSorterCreateThread(pIncr->pTask, vdbePmaReaderBgIncrInit, pCtx);
  90045. }else
  90046. #endif
  90047. {
  90048. rc = vdbePmaReaderIncrMergeInit(pReadr, eMode);
  90049. }
  90050. }
  90051. return rc;
  90052. }
  90053. /*
  90054. ** Allocate a new MergeEngine object to merge the contents of nPMA level-0
  90055. ** PMAs from pTask->file. If no error occurs, set *ppOut to point to
  90056. ** the new object and return SQLITE_OK. Or, if an error does occur, set *ppOut
  90057. ** to NULL and return an SQLite error code.
  90058. **
  90059. ** When this function is called, *piOffset is set to the offset of the
  90060. ** first PMA to read from pTask->file. Assuming no error occurs, it is
  90061. ** set to the offset immediately following the last byte of the last
  90062. ** PMA before returning. If an error does occur, then the final value of
  90063. ** *piOffset is undefined.
  90064. */
  90065. static int vdbeMergeEngineLevel0(
  90066. SortSubtask *pTask, /* Sorter task to read from */
  90067. int nPMA, /* Number of PMAs to read */
  90068. i64 *piOffset, /* IN/OUT: Readr offset in pTask->file */
  90069. MergeEngine **ppOut /* OUT: New merge-engine */
  90070. ){
  90071. MergeEngine *pNew; /* Merge engine to return */
  90072. i64 iOff = *piOffset;
  90073. int i;
  90074. int rc = SQLITE_OK;
  90075. *ppOut = pNew = vdbeMergeEngineNew(nPMA);
  90076. if( pNew==0 ) rc = SQLITE_NOMEM_BKPT;
  90077. for(i=0; i<nPMA && rc==SQLITE_OK; i++){
  90078. i64 nDummy = 0;
  90079. PmaReader *pReadr = &pNew->aReadr[i];
  90080. rc = vdbePmaReaderInit(pTask, &pTask->file, iOff, pReadr, &nDummy);
  90081. iOff = pReadr->iEof;
  90082. }
  90083. if( rc!=SQLITE_OK ){
  90084. vdbeMergeEngineFree(pNew);
  90085. *ppOut = 0;
  90086. }
  90087. *piOffset = iOff;
  90088. return rc;
  90089. }
  90090. /*
  90091. ** Return the depth of a tree comprising nPMA PMAs, assuming a fanout of
  90092. ** SORTER_MAX_MERGE_COUNT. The returned value does not include leaf nodes.
  90093. **
  90094. ** i.e.
  90095. **
  90096. ** nPMA<=16 -> TreeDepth() == 0
  90097. ** nPMA<=256 -> TreeDepth() == 1
  90098. ** nPMA<=65536 -> TreeDepth() == 2
  90099. */
  90100. static int vdbeSorterTreeDepth(int nPMA){
  90101. int nDepth = 0;
  90102. i64 nDiv = SORTER_MAX_MERGE_COUNT;
  90103. while( nDiv < (i64)nPMA ){
  90104. nDiv = nDiv * SORTER_MAX_MERGE_COUNT;
  90105. nDepth++;
  90106. }
  90107. return nDepth;
  90108. }
  90109. /*
  90110. ** pRoot is the root of an incremental merge-tree with depth nDepth (according
  90111. ** to vdbeSorterTreeDepth()). pLeaf is the iSeq'th leaf to be added to the
  90112. ** tree, counting from zero. This function adds pLeaf to the tree.
  90113. **
  90114. ** If successful, SQLITE_OK is returned. If an error occurs, an SQLite error
  90115. ** code is returned and pLeaf is freed.
  90116. */
  90117. static int vdbeSorterAddToTree(
  90118. SortSubtask *pTask, /* Task context */
  90119. int nDepth, /* Depth of tree according to TreeDepth() */
  90120. int iSeq, /* Sequence number of leaf within tree */
  90121. MergeEngine *pRoot, /* Root of tree */
  90122. MergeEngine *pLeaf /* Leaf to add to tree */
  90123. ){
  90124. int rc = SQLITE_OK;
  90125. int nDiv = 1;
  90126. int i;
  90127. MergeEngine *p = pRoot;
  90128. IncrMerger *pIncr;
  90129. rc = vdbeIncrMergerNew(pTask, pLeaf, &pIncr);
  90130. for(i=1; i<nDepth; i++){
  90131. nDiv = nDiv * SORTER_MAX_MERGE_COUNT;
  90132. }
  90133. for(i=1; i<nDepth && rc==SQLITE_OK; i++){
  90134. int iIter = (iSeq / nDiv) % SORTER_MAX_MERGE_COUNT;
  90135. PmaReader *pReadr = &p->aReadr[iIter];
  90136. if( pReadr->pIncr==0 ){
  90137. MergeEngine *pNew = vdbeMergeEngineNew(SORTER_MAX_MERGE_COUNT);
  90138. if( pNew==0 ){
  90139. rc = SQLITE_NOMEM_BKPT;
  90140. }else{
  90141. rc = vdbeIncrMergerNew(pTask, pNew, &pReadr->pIncr);
  90142. }
  90143. }
  90144. if( rc==SQLITE_OK ){
  90145. p = pReadr->pIncr->pMerger;
  90146. nDiv = nDiv / SORTER_MAX_MERGE_COUNT;
  90147. }
  90148. }
  90149. if( rc==SQLITE_OK ){
  90150. p->aReadr[iSeq % SORTER_MAX_MERGE_COUNT].pIncr = pIncr;
  90151. }else{
  90152. vdbeIncrFree(pIncr);
  90153. }
  90154. return rc;
  90155. }
  90156. /*
  90157. ** This function is called as part of a SorterRewind() operation on a sorter
  90158. ** that has already written two or more level-0 PMAs to one or more temp
  90159. ** files. It builds a tree of MergeEngine/IncrMerger/PmaReader objects that
  90160. ** can be used to incrementally merge all PMAs on disk.
  90161. **
  90162. ** If successful, SQLITE_OK is returned and *ppOut set to point to the
  90163. ** MergeEngine object at the root of the tree before returning. Or, if an
  90164. ** error occurs, an SQLite error code is returned and the final value
  90165. ** of *ppOut is undefined.
  90166. */
  90167. static int vdbeSorterMergeTreeBuild(
  90168. VdbeSorter *pSorter, /* The VDBE cursor that implements the sort */
  90169. MergeEngine **ppOut /* Write the MergeEngine here */
  90170. ){
  90171. MergeEngine *pMain = 0;
  90172. int rc = SQLITE_OK;
  90173. int iTask;
  90174. #if SQLITE_MAX_WORKER_THREADS>0
  90175. /* If the sorter uses more than one task, then create the top-level
  90176. ** MergeEngine here. This MergeEngine will read data from exactly
  90177. ** one PmaReader per sub-task. */
  90178. assert( pSorter->bUseThreads || pSorter->nTask==1 );
  90179. if( pSorter->nTask>1 ){
  90180. pMain = vdbeMergeEngineNew(pSorter->nTask);
  90181. if( pMain==0 ) rc = SQLITE_NOMEM_BKPT;
  90182. }
  90183. #endif
  90184. for(iTask=0; rc==SQLITE_OK && iTask<pSorter->nTask; iTask++){
  90185. SortSubtask *pTask = &pSorter->aTask[iTask];
  90186. assert( pTask->nPMA>0 || SQLITE_MAX_WORKER_THREADS>0 );
  90187. if( SQLITE_MAX_WORKER_THREADS==0 || pTask->nPMA ){
  90188. MergeEngine *pRoot = 0; /* Root node of tree for this task */
  90189. int nDepth = vdbeSorterTreeDepth(pTask->nPMA);
  90190. i64 iReadOff = 0;
  90191. if( pTask->nPMA<=SORTER_MAX_MERGE_COUNT ){
  90192. rc = vdbeMergeEngineLevel0(pTask, pTask->nPMA, &iReadOff, &pRoot);
  90193. }else{
  90194. int i;
  90195. int iSeq = 0;
  90196. pRoot = vdbeMergeEngineNew(SORTER_MAX_MERGE_COUNT);
  90197. if( pRoot==0 ) rc = SQLITE_NOMEM_BKPT;
  90198. for(i=0; i<pTask->nPMA && rc==SQLITE_OK; i += SORTER_MAX_MERGE_COUNT){
  90199. MergeEngine *pMerger = 0; /* New level-0 PMA merger */
  90200. int nReader; /* Number of level-0 PMAs to merge */
  90201. nReader = MIN(pTask->nPMA - i, SORTER_MAX_MERGE_COUNT);
  90202. rc = vdbeMergeEngineLevel0(pTask, nReader, &iReadOff, &pMerger);
  90203. if( rc==SQLITE_OK ){
  90204. rc = vdbeSorterAddToTree(pTask, nDepth, iSeq++, pRoot, pMerger);
  90205. }
  90206. }
  90207. }
  90208. if( rc==SQLITE_OK ){
  90209. #if SQLITE_MAX_WORKER_THREADS>0
  90210. if( pMain!=0 ){
  90211. rc = vdbeIncrMergerNew(pTask, pRoot, &pMain->aReadr[iTask].pIncr);
  90212. }else
  90213. #endif
  90214. {
  90215. assert( pMain==0 );
  90216. pMain = pRoot;
  90217. }
  90218. }else{
  90219. vdbeMergeEngineFree(pRoot);
  90220. }
  90221. }
  90222. }
  90223. if( rc!=SQLITE_OK ){
  90224. vdbeMergeEngineFree(pMain);
  90225. pMain = 0;
  90226. }
  90227. *ppOut = pMain;
  90228. return rc;
  90229. }
  90230. /*
  90231. ** This function is called as part of an sqlite3VdbeSorterRewind() operation
  90232. ** on a sorter that has written two or more PMAs to temporary files. It sets
  90233. ** up either VdbeSorter.pMerger (for single threaded sorters) or pReader
  90234. ** (for multi-threaded sorters) so that it can be used to iterate through
  90235. ** all records stored in the sorter.
  90236. **
  90237. ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
  90238. */
  90239. static int vdbeSorterSetupMerge(VdbeSorter *pSorter){
  90240. int rc; /* Return code */
  90241. SortSubtask *pTask0 = &pSorter->aTask[0];
  90242. MergeEngine *pMain = 0;
  90243. #if SQLITE_MAX_WORKER_THREADS
  90244. sqlite3 *db = pTask0->pSorter->db;
  90245. int i;
  90246. SorterCompare xCompare = vdbeSorterGetCompare(pSorter);
  90247. for(i=0; i<pSorter->nTask; i++){
  90248. pSorter->aTask[i].xCompare = xCompare;
  90249. }
  90250. #endif
  90251. rc = vdbeSorterMergeTreeBuild(pSorter, &pMain);
  90252. if( rc==SQLITE_OK ){
  90253. #if SQLITE_MAX_WORKER_THREADS
  90254. assert( pSorter->bUseThreads==0 || pSorter->nTask>1 );
  90255. if( pSorter->bUseThreads ){
  90256. int iTask;
  90257. PmaReader *pReadr = 0;
  90258. SortSubtask *pLast = &pSorter->aTask[pSorter->nTask-1];
  90259. rc = vdbeSortAllocUnpacked(pLast);
  90260. if( rc==SQLITE_OK ){
  90261. pReadr = (PmaReader*)sqlite3DbMallocZero(db, sizeof(PmaReader));
  90262. pSorter->pReader = pReadr;
  90263. if( pReadr==0 ) rc = SQLITE_NOMEM_BKPT;
  90264. }
  90265. if( rc==SQLITE_OK ){
  90266. rc = vdbeIncrMergerNew(pLast, pMain, &pReadr->pIncr);
  90267. if( rc==SQLITE_OK ){
  90268. vdbeIncrMergerSetThreads(pReadr->pIncr);
  90269. for(iTask=0; iTask<(pSorter->nTask-1); iTask++){
  90270. IncrMerger *pIncr;
  90271. if( (pIncr = pMain->aReadr[iTask].pIncr) ){
  90272. vdbeIncrMergerSetThreads(pIncr);
  90273. assert( pIncr->pTask!=pLast );
  90274. }
  90275. }
  90276. for(iTask=0; rc==SQLITE_OK && iTask<pSorter->nTask; iTask++){
  90277. /* Check that:
  90278. **
  90279. ** a) The incremental merge object is configured to use the
  90280. ** right task, and
  90281. ** b) If it is using task (nTask-1), it is configured to run
  90282. ** in single-threaded mode. This is important, as the
  90283. ** root merge (INCRINIT_ROOT) will be using the same task
  90284. ** object.
  90285. */
  90286. PmaReader *p = &pMain->aReadr[iTask];
  90287. assert( p->pIncr==0 || (
  90288. (p->pIncr->pTask==&pSorter->aTask[iTask]) /* a */
  90289. && (iTask!=pSorter->nTask-1 || p->pIncr->bUseThread==0) /* b */
  90290. ));
  90291. rc = vdbePmaReaderIncrInit(p, INCRINIT_TASK);
  90292. }
  90293. }
  90294. pMain = 0;
  90295. }
  90296. if( rc==SQLITE_OK ){
  90297. rc = vdbePmaReaderIncrMergeInit(pReadr, INCRINIT_ROOT);
  90298. }
  90299. }else
  90300. #endif
  90301. {
  90302. rc = vdbeMergeEngineInit(pTask0, pMain, INCRINIT_NORMAL);
  90303. pSorter->pMerger = pMain;
  90304. pMain = 0;
  90305. }
  90306. }
  90307. if( rc!=SQLITE_OK ){
  90308. vdbeMergeEngineFree(pMain);
  90309. }
  90310. return rc;
  90311. }
  90312. /*
  90313. ** Once the sorter has been populated by calls to sqlite3VdbeSorterWrite,
  90314. ** this function is called to prepare for iterating through the records
  90315. ** in sorted order.
  90316. */
  90317. SQLITE_PRIVATE int sqlite3VdbeSorterRewind(const VdbeCursor *pCsr, int *pbEof){
  90318. VdbeSorter *pSorter;
  90319. int rc = SQLITE_OK; /* Return code */
  90320. assert( pCsr->eCurType==CURTYPE_SORTER );
  90321. pSorter = pCsr->uc.pSorter;
  90322. assert( pSorter );
  90323. /* If no data has been written to disk, then do not do so now. Instead,
  90324. ** sort the VdbeSorter.pRecord list. The vdbe layer will read data directly
  90325. ** from the in-memory list. */
  90326. if( pSorter->bUsePMA==0 ){
  90327. if( pSorter->list.pList ){
  90328. *pbEof = 0;
  90329. rc = vdbeSorterSort(&pSorter->aTask[0], &pSorter->list);
  90330. }else{
  90331. *pbEof = 1;
  90332. }
  90333. return rc;
  90334. }
  90335. /* Write the current in-memory list to a PMA. When the VdbeSorterWrite()
  90336. ** function flushes the contents of memory to disk, it immediately always
  90337. ** creates a new list consisting of a single key immediately afterwards.
  90338. ** So the list is never empty at this point. */
  90339. assert( pSorter->list.pList );
  90340. rc = vdbeSorterFlushPMA(pSorter);
  90341. /* Join all threads */
  90342. rc = vdbeSorterJoinAll(pSorter, rc);
  90343. vdbeSorterRewindDebug("rewind");
  90344. /* Assuming no errors have occurred, set up a merger structure to
  90345. ** incrementally read and merge all remaining PMAs. */
  90346. assert( pSorter->pReader==0 );
  90347. if( rc==SQLITE_OK ){
  90348. rc = vdbeSorterSetupMerge(pSorter);
  90349. *pbEof = 0;
  90350. }
  90351. vdbeSorterRewindDebug("rewinddone");
  90352. return rc;
  90353. }
  90354. /*
  90355. ** Advance to the next element in the sorter. Return value:
  90356. **
  90357. ** SQLITE_OK success
  90358. ** SQLITE_DONE end of data
  90359. ** otherwise some kind of error.
  90360. */
  90361. SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *db, const VdbeCursor *pCsr){
  90362. VdbeSorter *pSorter;
  90363. int rc; /* Return code */
  90364. assert( pCsr->eCurType==CURTYPE_SORTER );
  90365. pSorter = pCsr->uc.pSorter;
  90366. assert( pSorter->bUsePMA || (pSorter->pReader==0 && pSorter->pMerger==0) );
  90367. if( pSorter->bUsePMA ){
  90368. assert( pSorter->pReader==0 || pSorter->pMerger==0 );
  90369. assert( pSorter->bUseThreads==0 || pSorter->pReader );
  90370. assert( pSorter->bUseThreads==1 || pSorter->pMerger );
  90371. #if SQLITE_MAX_WORKER_THREADS>0
  90372. if( pSorter->bUseThreads ){
  90373. rc = vdbePmaReaderNext(pSorter->pReader);
  90374. if( rc==SQLITE_OK && pSorter->pReader->pFd==0 ) rc = SQLITE_DONE;
  90375. }else
  90376. #endif
  90377. /*if( !pSorter->bUseThreads )*/ {
  90378. int res = 0;
  90379. assert( pSorter->pMerger!=0 );
  90380. assert( pSorter->pMerger->pTask==(&pSorter->aTask[0]) );
  90381. rc = vdbeMergeEngineStep(pSorter->pMerger, &res);
  90382. if( rc==SQLITE_OK && res ) rc = SQLITE_DONE;
  90383. }
  90384. }else{
  90385. SorterRecord *pFree = pSorter->list.pList;
  90386. pSorter->list.pList = pFree->u.pNext;
  90387. pFree->u.pNext = 0;
  90388. if( pSorter->list.aMemory==0 ) vdbeSorterRecordFree(db, pFree);
  90389. rc = pSorter->list.pList ? SQLITE_OK : SQLITE_DONE;
  90390. }
  90391. return rc;
  90392. }
  90393. /*
  90394. ** Return a pointer to a buffer owned by the sorter that contains the
  90395. ** current key.
  90396. */
  90397. static void *vdbeSorterRowkey(
  90398. const VdbeSorter *pSorter, /* Sorter object */
  90399. int *pnKey /* OUT: Size of current key in bytes */
  90400. ){
  90401. void *pKey;
  90402. if( pSorter->bUsePMA ){
  90403. PmaReader *pReader;
  90404. #if SQLITE_MAX_WORKER_THREADS>0
  90405. if( pSorter->bUseThreads ){
  90406. pReader = pSorter->pReader;
  90407. }else
  90408. #endif
  90409. /*if( !pSorter->bUseThreads )*/{
  90410. pReader = &pSorter->pMerger->aReadr[pSorter->pMerger->aTree[1]];
  90411. }
  90412. *pnKey = pReader->nKey;
  90413. pKey = pReader->aKey;
  90414. }else{
  90415. *pnKey = pSorter->list.pList->nVal;
  90416. pKey = SRVAL(pSorter->list.pList);
  90417. }
  90418. return pKey;
  90419. }
  90420. /*
  90421. ** Copy the current sorter key into the memory cell pOut.
  90422. */
  90423. SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *pCsr, Mem *pOut){
  90424. VdbeSorter *pSorter;
  90425. void *pKey; int nKey; /* Sorter key to copy into pOut */
  90426. assert( pCsr->eCurType==CURTYPE_SORTER );
  90427. pSorter = pCsr->uc.pSorter;
  90428. pKey = vdbeSorterRowkey(pSorter, &nKey);
  90429. if( sqlite3VdbeMemClearAndResize(pOut, nKey) ){
  90430. return SQLITE_NOMEM_BKPT;
  90431. }
  90432. pOut->n = nKey;
  90433. MemSetTypeFlag(pOut, MEM_Blob);
  90434. memcpy(pOut->z, pKey, nKey);
  90435. return SQLITE_OK;
  90436. }
  90437. /*
  90438. ** Compare the key in memory cell pVal with the key that the sorter cursor
  90439. ** passed as the first argument currently points to. For the purposes of
  90440. ** the comparison, ignore the rowid field at the end of each record.
  90441. **
  90442. ** If the sorter cursor key contains any NULL values, consider it to be
  90443. ** less than pVal. Even if pVal also contains NULL values.
  90444. **
  90445. ** If an error occurs, return an SQLite error code (i.e. SQLITE_NOMEM).
  90446. ** Otherwise, set *pRes to a negative, zero or positive value if the
  90447. ** key in pVal is smaller than, equal to or larger than the current sorter
  90448. ** key.
  90449. **
  90450. ** This routine forms the core of the OP_SorterCompare opcode, which in
  90451. ** turn is used to verify uniqueness when constructing a UNIQUE INDEX.
  90452. */
  90453. SQLITE_PRIVATE int sqlite3VdbeSorterCompare(
  90454. const VdbeCursor *pCsr, /* Sorter cursor */
  90455. Mem *pVal, /* Value to compare to current sorter key */
  90456. int nKeyCol, /* Compare this many columns */
  90457. int *pRes /* OUT: Result of comparison */
  90458. ){
  90459. VdbeSorter *pSorter;
  90460. UnpackedRecord *r2;
  90461. KeyInfo *pKeyInfo;
  90462. int i;
  90463. void *pKey; int nKey; /* Sorter key to compare pVal with */
  90464. assert( pCsr->eCurType==CURTYPE_SORTER );
  90465. pSorter = pCsr->uc.pSorter;
  90466. r2 = pSorter->pUnpacked;
  90467. pKeyInfo = pCsr->pKeyInfo;
  90468. if( r2==0 ){
  90469. r2 = pSorter->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pKeyInfo);
  90470. if( r2==0 ) return SQLITE_NOMEM_BKPT;
  90471. r2->nField = nKeyCol;
  90472. }
  90473. assert( r2->nField==nKeyCol );
  90474. pKey = vdbeSorterRowkey(pSorter, &nKey);
  90475. sqlite3VdbeRecordUnpack(pKeyInfo, nKey, pKey, r2);
  90476. for(i=0; i<nKeyCol; i++){
  90477. if( r2->aMem[i].flags & MEM_Null ){
  90478. *pRes = -1;
  90479. return SQLITE_OK;
  90480. }
  90481. }
  90482. *pRes = sqlite3VdbeRecordCompare(pVal->n, pVal->z, r2);
  90483. return SQLITE_OK;
  90484. }
  90485. /************** End of vdbesort.c ********************************************/
  90486. /************** Begin file vdbevtab.c ****************************************/
  90487. /*
  90488. ** 2020-03-23
  90489. **
  90490. ** The author disclaims copyright to this source code. In place of
  90491. ** a legal notice, here is a blessing:
  90492. **
  90493. ** May you do good and not evil.
  90494. ** May you find forgiveness for yourself and forgive others.
  90495. ** May you share freely, never taking more than you give.
  90496. **
  90497. *************************************************************************
  90498. **
  90499. ** This file implements virtual-tables for examining the bytecode content
  90500. ** of a prepared statement.
  90501. */
  90502. /* #include "sqliteInt.h" */
  90503. #if defined(SQLITE_ENABLE_BYTECODE_VTAB) && !defined(SQLITE_OMIT_VIRTUALTABLE)
  90504. /* #include "vdbeInt.h" */
  90505. /* An instance of the bytecode() table-valued function.
  90506. */
  90507. typedef struct bytecodevtab bytecodevtab;
  90508. struct bytecodevtab {
  90509. sqlite3_vtab base; /* Base class - must be first */
  90510. sqlite3 *db; /* Database connection */
  90511. int bTablesUsed; /* 2 for tables_used(). 0 for bytecode(). */
  90512. };
  90513. /* A cursor for scanning through the bytecode
  90514. */
  90515. typedef struct bytecodevtab_cursor bytecodevtab_cursor;
  90516. struct bytecodevtab_cursor {
  90517. sqlite3_vtab_cursor base; /* Base class - must be first */
  90518. sqlite3_stmt *pStmt; /* The statement whose bytecode is displayed */
  90519. int iRowid; /* The rowid of the output table */
  90520. int iAddr; /* Address */
  90521. int needFinalize; /* Cursors owns pStmt and must finalize it */
  90522. int showSubprograms; /* Provide a listing of subprograms */
  90523. Op *aOp; /* Operand array */
  90524. char *zP4; /* Rendered P4 value */
  90525. const char *zType; /* tables_used.type */
  90526. const char *zSchema; /* tables_used.schema */
  90527. const char *zName; /* tables_used.name */
  90528. Mem sub; /* Subprograms */
  90529. };
  90530. /*
  90531. ** Create a new bytecode() table-valued function.
  90532. */
  90533. static int bytecodevtabConnect(
  90534. sqlite3 *db,
  90535. void *pAux,
  90536. int argc, const char *const*argv,
  90537. sqlite3_vtab **ppVtab,
  90538. char **pzErr
  90539. ){
  90540. bytecodevtab *pNew;
  90541. int rc;
  90542. int isTabUsed = pAux!=0;
  90543. const char *azSchema[2] = {
  90544. /* bytecode() schema */
  90545. "CREATE TABLE x("
  90546. "addr INT,"
  90547. "opcode TEXT,"
  90548. "p1 INT,"
  90549. "p2 INT,"
  90550. "p3 INT,"
  90551. "p4 TEXT,"
  90552. "p5 INT,"
  90553. "comment TEXT,"
  90554. "subprog TEXT,"
  90555. "stmt HIDDEN"
  90556. ");",
  90557. /* Tables_used() schema */
  90558. "CREATE TABLE x("
  90559. "type TEXT,"
  90560. "schema TEXT,"
  90561. "name TEXT,"
  90562. "wr INT,"
  90563. "subprog TEXT,"
  90564. "stmt HIDDEN"
  90565. ");"
  90566. };
  90567. rc = sqlite3_declare_vtab(db, azSchema[isTabUsed]);
  90568. if( rc==SQLITE_OK ){
  90569. pNew = sqlite3_malloc( sizeof(*pNew) );
  90570. *ppVtab = (sqlite3_vtab*)pNew;
  90571. if( pNew==0 ) return SQLITE_NOMEM;
  90572. memset(pNew, 0, sizeof(*pNew));
  90573. pNew->db = db;
  90574. pNew->bTablesUsed = isTabUsed*2;
  90575. }
  90576. return rc;
  90577. }
  90578. /*
  90579. ** This method is the destructor for bytecodevtab objects.
  90580. */
  90581. static int bytecodevtabDisconnect(sqlite3_vtab *pVtab){
  90582. bytecodevtab *p = (bytecodevtab*)pVtab;
  90583. sqlite3_free(p);
  90584. return SQLITE_OK;
  90585. }
  90586. /*
  90587. ** Constructor for a new bytecodevtab_cursor object.
  90588. */
  90589. static int bytecodevtabOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
  90590. bytecodevtab *pVTab = (bytecodevtab*)p;
  90591. bytecodevtab_cursor *pCur;
  90592. pCur = sqlite3_malloc( sizeof(*pCur) );
  90593. if( pCur==0 ) return SQLITE_NOMEM;
  90594. memset(pCur, 0, sizeof(*pCur));
  90595. sqlite3VdbeMemInit(&pCur->sub, pVTab->db, 1);
  90596. *ppCursor = &pCur->base;
  90597. return SQLITE_OK;
  90598. }
  90599. /*
  90600. ** Clear all internal content from a bytecodevtab cursor.
  90601. */
  90602. static void bytecodevtabCursorClear(bytecodevtab_cursor *pCur){
  90603. sqlite3_free(pCur->zP4);
  90604. pCur->zP4 = 0;
  90605. sqlite3VdbeMemRelease(&pCur->sub);
  90606. sqlite3VdbeMemSetNull(&pCur->sub);
  90607. if( pCur->needFinalize ){
  90608. sqlite3_finalize(pCur->pStmt);
  90609. }
  90610. pCur->pStmt = 0;
  90611. pCur->needFinalize = 0;
  90612. pCur->zType = 0;
  90613. pCur->zSchema = 0;
  90614. pCur->zName = 0;
  90615. }
  90616. /*
  90617. ** Destructor for a bytecodevtab_cursor.
  90618. */
  90619. static int bytecodevtabClose(sqlite3_vtab_cursor *cur){
  90620. bytecodevtab_cursor *pCur = (bytecodevtab_cursor*)cur;
  90621. bytecodevtabCursorClear(pCur);
  90622. sqlite3_free(pCur);
  90623. return SQLITE_OK;
  90624. }
  90625. /*
  90626. ** Advance a bytecodevtab_cursor to its next row of output.
  90627. */
  90628. static int bytecodevtabNext(sqlite3_vtab_cursor *cur){
  90629. bytecodevtab_cursor *pCur = (bytecodevtab_cursor*)cur;
  90630. bytecodevtab *pTab = (bytecodevtab*)cur->pVtab;
  90631. int rc;
  90632. if( pCur->zP4 ){
  90633. sqlite3_free(pCur->zP4);
  90634. pCur->zP4 = 0;
  90635. }
  90636. if( pCur->zName ){
  90637. pCur->zName = 0;
  90638. pCur->zType = 0;
  90639. pCur->zSchema = 0;
  90640. }
  90641. rc = sqlite3VdbeNextOpcode(
  90642. (Vdbe*)pCur->pStmt,
  90643. pCur->showSubprograms ? &pCur->sub : 0,
  90644. pTab->bTablesUsed,
  90645. &pCur->iRowid,
  90646. &pCur->iAddr,
  90647. &pCur->aOp);
  90648. if( rc!=SQLITE_OK ){
  90649. sqlite3VdbeMemSetNull(&pCur->sub);
  90650. pCur->aOp = 0;
  90651. }
  90652. return SQLITE_OK;
  90653. }
  90654. /*
  90655. ** Return TRUE if the cursor has been moved off of the last
  90656. ** row of output.
  90657. */
  90658. static int bytecodevtabEof(sqlite3_vtab_cursor *cur){
  90659. bytecodevtab_cursor *pCur = (bytecodevtab_cursor*)cur;
  90660. return pCur->aOp==0;
  90661. }
  90662. /*
  90663. ** Return values of columns for the row at which the bytecodevtab_cursor
  90664. ** is currently pointing.
  90665. */
  90666. static int bytecodevtabColumn(
  90667. sqlite3_vtab_cursor *cur, /* The cursor */
  90668. sqlite3_context *ctx, /* First argument to sqlite3_result_...() */
  90669. int i /* Which column to return */
  90670. ){
  90671. bytecodevtab_cursor *pCur = (bytecodevtab_cursor*)cur;
  90672. bytecodevtab *pVTab = (bytecodevtab*)cur->pVtab;
  90673. Op *pOp = pCur->aOp + pCur->iAddr;
  90674. if( pVTab->bTablesUsed ){
  90675. if( i==4 ){
  90676. i = 8;
  90677. }else{
  90678. if( i<=2 && pCur->zType==0 ){
  90679. Schema *pSchema;
  90680. HashElem *k;
  90681. int iDb = pOp->p3;
  90682. int iRoot = pOp->p2;
  90683. sqlite3 *db = pVTab->db;
  90684. pSchema = db->aDb[iDb].pSchema;
  90685. pCur->zSchema = db->aDb[iDb].zDbSName;
  90686. for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
  90687. Table *pTab = (Table*)sqliteHashData(k);
  90688. if( !IsVirtual(pTab) && pTab->tnum==iRoot ){
  90689. pCur->zName = pTab->zName;
  90690. pCur->zType = "table";
  90691. break;
  90692. }
  90693. }
  90694. if( pCur->zName==0 ){
  90695. for(k=sqliteHashFirst(&pSchema->idxHash); k; k=sqliteHashNext(k)){
  90696. Index *pIdx = (Index*)sqliteHashData(k);
  90697. if( pIdx->tnum==iRoot ){
  90698. pCur->zName = pIdx->zName;
  90699. pCur->zType = "index";
  90700. }
  90701. }
  90702. }
  90703. }
  90704. i += 10;
  90705. }
  90706. }
  90707. switch( i ){
  90708. case 0: /* addr */
  90709. sqlite3_result_int(ctx, pCur->iAddr);
  90710. break;
  90711. case 1: /* opcode */
  90712. sqlite3_result_text(ctx, (char*)sqlite3OpcodeName(pOp->opcode),
  90713. -1, SQLITE_STATIC);
  90714. break;
  90715. case 2: /* p1 */
  90716. sqlite3_result_int(ctx, pOp->p1);
  90717. break;
  90718. case 3: /* p2 */
  90719. sqlite3_result_int(ctx, pOp->p2);
  90720. break;
  90721. case 4: /* p3 */
  90722. sqlite3_result_int(ctx, pOp->p3);
  90723. break;
  90724. case 5: /* p4 */
  90725. case 7: /* comment */
  90726. if( pCur->zP4==0 ){
  90727. pCur->zP4 = sqlite3VdbeDisplayP4(pVTab->db, pOp);
  90728. }
  90729. if( i==5 ){
  90730. sqlite3_result_text(ctx, pCur->zP4, -1, SQLITE_STATIC);
  90731. }else{
  90732. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  90733. char *zCom = sqlite3VdbeDisplayComment(pVTab->db, pOp, pCur->zP4);
  90734. sqlite3_result_text(ctx, zCom, -1, sqlite3_free);
  90735. #endif
  90736. }
  90737. break;
  90738. case 6: /* p5 */
  90739. sqlite3_result_int(ctx, pOp->p5);
  90740. break;
  90741. case 8: { /* subprog */
  90742. Op *aOp = pCur->aOp;
  90743. assert( aOp[0].opcode==OP_Init );
  90744. assert( aOp[0].p4.z==0 || strncmp(aOp[0].p4.z,"-" "- ",3)==0 );
  90745. if( pCur->iRowid==pCur->iAddr+1 ){
  90746. break; /* Result is NULL for the main program */
  90747. }else if( aOp[0].p4.z!=0 ){
  90748. sqlite3_result_text(ctx, aOp[0].p4.z+3, -1, SQLITE_STATIC);
  90749. }else{
  90750. sqlite3_result_text(ctx, "(FK)", 4, SQLITE_STATIC);
  90751. }
  90752. break;
  90753. }
  90754. case 10: /* tables_used.type */
  90755. sqlite3_result_text(ctx, pCur->zType, -1, SQLITE_STATIC);
  90756. break;
  90757. case 11: /* tables_used.schema */
  90758. sqlite3_result_text(ctx, pCur->zSchema, -1, SQLITE_STATIC);
  90759. break;
  90760. case 12: /* tables_used.name */
  90761. sqlite3_result_text(ctx, pCur->zName, -1, SQLITE_STATIC);
  90762. break;
  90763. case 13: /* tables_used.wr */
  90764. sqlite3_result_int(ctx, pOp->opcode==OP_OpenWrite);
  90765. break;
  90766. }
  90767. return SQLITE_OK;
  90768. }
  90769. /*
  90770. ** Return the rowid for the current row. In this implementation, the
  90771. ** rowid is the same as the output value.
  90772. */
  90773. static int bytecodevtabRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
  90774. bytecodevtab_cursor *pCur = (bytecodevtab_cursor*)cur;
  90775. *pRowid = pCur->iRowid;
  90776. return SQLITE_OK;
  90777. }
  90778. /*
  90779. ** Initialize a cursor.
  90780. **
  90781. ** idxNum==0 means show all subprograms
  90782. ** idxNum==1 means show only the main bytecode and omit subprograms.
  90783. */
  90784. static int bytecodevtabFilter(
  90785. sqlite3_vtab_cursor *pVtabCursor,
  90786. int idxNum, const char *idxStr,
  90787. int argc, sqlite3_value **argv
  90788. ){
  90789. bytecodevtab_cursor *pCur = (bytecodevtab_cursor *)pVtabCursor;
  90790. bytecodevtab *pVTab = (bytecodevtab *)pVtabCursor->pVtab;
  90791. int rc = SQLITE_OK;
  90792. bytecodevtabCursorClear(pCur);
  90793. pCur->iRowid = 0;
  90794. pCur->iAddr = 0;
  90795. pCur->showSubprograms = idxNum==0;
  90796. assert( argc==1 );
  90797. if( sqlite3_value_type(argv[0])==SQLITE_TEXT ){
  90798. const char *zSql = (const char*)sqlite3_value_text(argv[0]);
  90799. if( zSql==0 ){
  90800. rc = SQLITE_NOMEM;
  90801. }else{
  90802. rc = sqlite3_prepare_v2(pVTab->db, zSql, -1, &pCur->pStmt, 0);
  90803. pCur->needFinalize = 1;
  90804. }
  90805. }else{
  90806. pCur->pStmt = (sqlite3_stmt*)sqlite3_value_pointer(argv[0],"stmt-pointer");
  90807. }
  90808. if( pCur->pStmt==0 ){
  90809. pVTab->base.zErrMsg = sqlite3_mprintf(
  90810. "argument to %s() is not a valid SQL statement",
  90811. pVTab->bTablesUsed ? "tables_used" : "bytecode"
  90812. );
  90813. rc = SQLITE_ERROR;
  90814. }else{
  90815. bytecodevtabNext(pVtabCursor);
  90816. }
  90817. return rc;
  90818. }
  90819. /*
  90820. ** We must have a single stmt=? constraint that will be passed through
  90821. ** into the xFilter method. If there is no valid stmt=? constraint,
  90822. ** then return an SQLITE_CONSTRAINT error.
  90823. */
  90824. static int bytecodevtabBestIndex(
  90825. sqlite3_vtab *tab,
  90826. sqlite3_index_info *pIdxInfo
  90827. ){
  90828. int i;
  90829. int rc = SQLITE_CONSTRAINT;
  90830. struct sqlite3_index_constraint *p;
  90831. bytecodevtab *pVTab = (bytecodevtab*)tab;
  90832. int iBaseCol = pVTab->bTablesUsed ? 4 : 8;
  90833. pIdxInfo->estimatedCost = (double)100;
  90834. pIdxInfo->estimatedRows = 100;
  90835. pIdxInfo->idxNum = 0;
  90836. for(i=0, p=pIdxInfo->aConstraint; i<pIdxInfo->nConstraint; i++, p++){
  90837. if( p->usable==0 ) continue;
  90838. if( p->op==SQLITE_INDEX_CONSTRAINT_EQ && p->iColumn==iBaseCol+1 ){
  90839. rc = SQLITE_OK;
  90840. pIdxInfo->aConstraintUsage[i].omit = 1;
  90841. pIdxInfo->aConstraintUsage[i].argvIndex = 1;
  90842. }
  90843. if( p->op==SQLITE_INDEX_CONSTRAINT_ISNULL && p->iColumn==iBaseCol ){
  90844. pIdxInfo->aConstraintUsage[i].omit = 1;
  90845. pIdxInfo->idxNum = 1;
  90846. }
  90847. }
  90848. return rc;
  90849. }
  90850. /*
  90851. ** This following structure defines all the methods for the
  90852. ** virtual table.
  90853. */
  90854. static sqlite3_module bytecodevtabModule = {
  90855. /* iVersion */ 0,
  90856. /* xCreate */ 0,
  90857. /* xConnect */ bytecodevtabConnect,
  90858. /* xBestIndex */ bytecodevtabBestIndex,
  90859. /* xDisconnect */ bytecodevtabDisconnect,
  90860. /* xDestroy */ 0,
  90861. /* xOpen */ bytecodevtabOpen,
  90862. /* xClose */ bytecodevtabClose,
  90863. /* xFilter */ bytecodevtabFilter,
  90864. /* xNext */ bytecodevtabNext,
  90865. /* xEof */ bytecodevtabEof,
  90866. /* xColumn */ bytecodevtabColumn,
  90867. /* xRowid */ bytecodevtabRowid,
  90868. /* xUpdate */ 0,
  90869. /* xBegin */ 0,
  90870. /* xSync */ 0,
  90871. /* xCommit */ 0,
  90872. /* xRollback */ 0,
  90873. /* xFindMethod */ 0,
  90874. /* xRename */ 0,
  90875. /* xSavepoint */ 0,
  90876. /* xRelease */ 0,
  90877. /* xRollbackTo */ 0,
  90878. /* xShadowName */ 0
  90879. };
  90880. SQLITE_PRIVATE int sqlite3VdbeBytecodeVtabInit(sqlite3 *db){
  90881. int rc;
  90882. rc = sqlite3_create_module(db, "bytecode", &bytecodevtabModule, 0);
  90883. if( rc==SQLITE_OK ){
  90884. rc = sqlite3_create_module(db, "tables_used", &bytecodevtabModule, &db);
  90885. }
  90886. return rc;
  90887. }
  90888. #elif defined(SQLITE_ENABLE_BYTECODE_VTAB)
  90889. SQLITE_PRIVATE int sqlite3VdbeBytecodeVtabInit(sqlite3 *db){ return SQLITE_OK; }
  90890. #endif /* SQLITE_ENABLE_BYTECODE_VTAB */
  90891. /************** End of vdbevtab.c ********************************************/
  90892. /************** Begin file memjournal.c **************************************/
  90893. /*
  90894. ** 2008 October 7
  90895. **
  90896. ** The author disclaims copyright to this source code. In place of
  90897. ** a legal notice, here is a blessing:
  90898. **
  90899. ** May you do good and not evil.
  90900. ** May you find forgiveness for yourself and forgive others.
  90901. ** May you share freely, never taking more than you give.
  90902. **
  90903. *************************************************************************
  90904. **
  90905. ** This file contains code use to implement an in-memory rollback journal.
  90906. ** The in-memory rollback journal is used to journal transactions for
  90907. ** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
  90908. **
  90909. ** Update: The in-memory journal is also used to temporarily cache
  90910. ** smaller journals that are not critical for power-loss recovery.
  90911. ** For example, statement journals that are not too big will be held
  90912. ** entirely in memory, thus reducing the number of file I/O calls, and
  90913. ** more importantly, reducing temporary file creation events. If these
  90914. ** journals become too large for memory, they are spilled to disk. But
  90915. ** in the common case, they are usually small and no file I/O needs to
  90916. ** occur.
  90917. */
  90918. /* #include "sqliteInt.h" */
  90919. /* Forward references to internal structures */
  90920. typedef struct MemJournal MemJournal;
  90921. typedef struct FilePoint FilePoint;
  90922. typedef struct FileChunk FileChunk;
  90923. /*
  90924. ** The rollback journal is composed of a linked list of these structures.
  90925. **
  90926. ** The zChunk array is always at least 8 bytes in size - usually much more.
  90927. ** Its actual size is stored in the MemJournal.nChunkSize variable.
  90928. */
  90929. struct FileChunk {
  90930. FileChunk *pNext; /* Next chunk in the journal */
  90931. u8 zChunk[8]; /* Content of this chunk */
  90932. };
  90933. /*
  90934. ** By default, allocate this many bytes of memory for each FileChunk object.
  90935. */
  90936. #define MEMJOURNAL_DFLT_FILECHUNKSIZE 1024
  90937. /*
  90938. ** For chunk size nChunkSize, return the number of bytes that should
  90939. ** be allocated for each FileChunk structure.
  90940. */
  90941. #define fileChunkSize(nChunkSize) (sizeof(FileChunk) + ((nChunkSize)-8))
  90942. /*
  90943. ** An instance of this object serves as a cursor into the rollback journal.
  90944. ** The cursor can be either for reading or writing.
  90945. */
  90946. struct FilePoint {
  90947. sqlite3_int64 iOffset; /* Offset from the beginning of the file */
  90948. FileChunk *pChunk; /* Specific chunk into which cursor points */
  90949. };
  90950. /*
  90951. ** This structure is a subclass of sqlite3_file. Each open memory-journal
  90952. ** is an instance of this class.
  90953. */
  90954. struct MemJournal {
  90955. const sqlite3_io_methods *pMethod; /* Parent class. MUST BE FIRST */
  90956. int nChunkSize; /* In-memory chunk-size */
  90957. int nSpill; /* Bytes of data before flushing */
  90958. int nSize; /* Bytes of data currently in memory */
  90959. FileChunk *pFirst; /* Head of in-memory chunk-list */
  90960. FilePoint endpoint; /* Pointer to the end of the file */
  90961. FilePoint readpoint; /* Pointer to the end of the last xRead() */
  90962. int flags; /* xOpen flags */
  90963. sqlite3_vfs *pVfs; /* The "real" underlying VFS */
  90964. const char *zJournal; /* Name of the journal file */
  90965. };
  90966. /*
  90967. ** Read data from the in-memory journal file. This is the implementation
  90968. ** of the sqlite3_vfs.xRead method.
  90969. */
  90970. static int memjrnlRead(
  90971. sqlite3_file *pJfd, /* The journal file from which to read */
  90972. void *zBuf, /* Put the results here */
  90973. int iAmt, /* Number of bytes to read */
  90974. sqlite_int64 iOfst /* Begin reading at this offset */
  90975. ){
  90976. MemJournal *p = (MemJournal *)pJfd;
  90977. u8 *zOut = zBuf;
  90978. int nRead = iAmt;
  90979. int iChunkOffset;
  90980. FileChunk *pChunk;
  90981. if( (iAmt+iOfst)>p->endpoint.iOffset ){
  90982. return SQLITE_IOERR_SHORT_READ;
  90983. }
  90984. assert( p->readpoint.iOffset==0 || p->readpoint.pChunk!=0 );
  90985. if( p->readpoint.iOffset!=iOfst || iOfst==0 ){
  90986. sqlite3_int64 iOff = 0;
  90987. for(pChunk=p->pFirst;
  90988. ALWAYS(pChunk) && (iOff+p->nChunkSize)<=iOfst;
  90989. pChunk=pChunk->pNext
  90990. ){
  90991. iOff += p->nChunkSize;
  90992. }
  90993. }else{
  90994. pChunk = p->readpoint.pChunk;
  90995. assert( pChunk!=0 );
  90996. }
  90997. iChunkOffset = (int)(iOfst%p->nChunkSize);
  90998. do {
  90999. int iSpace = p->nChunkSize - iChunkOffset;
  91000. int nCopy = MIN(nRead, (p->nChunkSize - iChunkOffset));
  91001. memcpy(zOut, (u8*)pChunk->zChunk + iChunkOffset, nCopy);
  91002. zOut += nCopy;
  91003. nRead -= iSpace;
  91004. iChunkOffset = 0;
  91005. } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 );
  91006. p->readpoint.iOffset = pChunk ? iOfst+iAmt : 0;
  91007. p->readpoint.pChunk = pChunk;
  91008. return SQLITE_OK;
  91009. }
  91010. /*
  91011. ** Free the list of FileChunk structures headed at MemJournal.pFirst.
  91012. */
  91013. static void memjrnlFreeChunks(MemJournal *p){
  91014. FileChunk *pIter;
  91015. FileChunk *pNext;
  91016. for(pIter=p->pFirst; pIter; pIter=pNext){
  91017. pNext = pIter->pNext;
  91018. sqlite3_free(pIter);
  91019. }
  91020. p->pFirst = 0;
  91021. }
  91022. /*
  91023. ** Flush the contents of memory to a real file on disk.
  91024. */
  91025. static int memjrnlCreateFile(MemJournal *p){
  91026. int rc;
  91027. sqlite3_file *pReal = (sqlite3_file*)p;
  91028. MemJournal copy = *p;
  91029. memset(p, 0, sizeof(MemJournal));
  91030. rc = sqlite3OsOpen(copy.pVfs, copy.zJournal, pReal, copy.flags, 0);
  91031. if( rc==SQLITE_OK ){
  91032. int nChunk = copy.nChunkSize;
  91033. i64 iOff = 0;
  91034. FileChunk *pIter;
  91035. for(pIter=copy.pFirst; pIter; pIter=pIter->pNext){
  91036. if( iOff + nChunk > copy.endpoint.iOffset ){
  91037. nChunk = copy.endpoint.iOffset - iOff;
  91038. }
  91039. rc = sqlite3OsWrite(pReal, (u8*)pIter->zChunk, nChunk, iOff);
  91040. if( rc ) break;
  91041. iOff += nChunk;
  91042. }
  91043. if( rc==SQLITE_OK ){
  91044. /* No error has occurred. Free the in-memory buffers. */
  91045. memjrnlFreeChunks(&copy);
  91046. }
  91047. }
  91048. if( rc!=SQLITE_OK ){
  91049. /* If an error occurred while creating or writing to the file, restore
  91050. ** the original before returning. This way, SQLite uses the in-memory
  91051. ** journal data to roll back changes made to the internal page-cache
  91052. ** before this function was called. */
  91053. sqlite3OsClose(pReal);
  91054. *p = copy;
  91055. }
  91056. return rc;
  91057. }
  91058. /*
  91059. ** Write data to the file.
  91060. */
  91061. static int memjrnlWrite(
  91062. sqlite3_file *pJfd, /* The journal file into which to write */
  91063. const void *zBuf, /* Take data to be written from here */
  91064. int iAmt, /* Number of bytes to write */
  91065. sqlite_int64 iOfst /* Begin writing at this offset into the file */
  91066. ){
  91067. MemJournal *p = (MemJournal *)pJfd;
  91068. int nWrite = iAmt;
  91069. u8 *zWrite = (u8 *)zBuf;
  91070. /* If the file should be created now, create it and write the new data
  91071. ** into the file on disk. */
  91072. if( p->nSpill>0 && (iAmt+iOfst)>p->nSpill ){
  91073. int rc = memjrnlCreateFile(p);
  91074. if( rc==SQLITE_OK ){
  91075. rc = sqlite3OsWrite(pJfd, zBuf, iAmt, iOfst);
  91076. }
  91077. return rc;
  91078. }
  91079. /* If the contents of this write should be stored in memory */
  91080. else{
  91081. /* An in-memory journal file should only ever be appended to. Random
  91082. ** access writes are not required. The only exception to this is when
  91083. ** the in-memory journal is being used by a connection using the
  91084. ** atomic-write optimization. In this case the first 28 bytes of the
  91085. ** journal file may be written as part of committing the transaction. */
  91086. assert( iOfst==p->endpoint.iOffset || iOfst==0 );
  91087. #if defined(SQLITE_ENABLE_ATOMIC_WRITE) \
  91088. || defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
  91089. if( iOfst==0 && p->pFirst ){
  91090. assert( p->nChunkSize>iAmt );
  91091. memcpy((u8*)p->pFirst->zChunk, zBuf, iAmt);
  91092. }else
  91093. #else
  91094. assert( iOfst>0 || p->pFirst==0 );
  91095. #endif
  91096. {
  91097. while( nWrite>0 ){
  91098. FileChunk *pChunk = p->endpoint.pChunk;
  91099. int iChunkOffset = (int)(p->endpoint.iOffset%p->nChunkSize);
  91100. int iSpace = MIN(nWrite, p->nChunkSize - iChunkOffset);
  91101. if( iChunkOffset==0 ){
  91102. /* New chunk is required to extend the file. */
  91103. FileChunk *pNew = sqlite3_malloc(fileChunkSize(p->nChunkSize));
  91104. if( !pNew ){
  91105. return SQLITE_IOERR_NOMEM_BKPT;
  91106. }
  91107. pNew->pNext = 0;
  91108. if( pChunk ){
  91109. assert( p->pFirst );
  91110. pChunk->pNext = pNew;
  91111. }else{
  91112. assert( !p->pFirst );
  91113. p->pFirst = pNew;
  91114. }
  91115. p->endpoint.pChunk = pNew;
  91116. }
  91117. memcpy((u8*)p->endpoint.pChunk->zChunk + iChunkOffset, zWrite, iSpace);
  91118. zWrite += iSpace;
  91119. nWrite -= iSpace;
  91120. p->endpoint.iOffset += iSpace;
  91121. }
  91122. p->nSize = iAmt + iOfst;
  91123. }
  91124. }
  91125. return SQLITE_OK;
  91126. }
  91127. /*
  91128. ** Truncate the file.
  91129. **
  91130. ** If the journal file is already on disk, truncate it there. Or, if it
  91131. ** is still in main memory but is being truncated to zero bytes in size,
  91132. ** ignore
  91133. */
  91134. static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
  91135. MemJournal *p = (MemJournal *)pJfd;
  91136. if( ALWAYS(size==0) ){
  91137. memjrnlFreeChunks(p);
  91138. p->nSize = 0;
  91139. p->endpoint.pChunk = 0;
  91140. p->endpoint.iOffset = 0;
  91141. p->readpoint.pChunk = 0;
  91142. p->readpoint.iOffset = 0;
  91143. }
  91144. return SQLITE_OK;
  91145. }
  91146. /*
  91147. ** Close the file.
  91148. */
  91149. static int memjrnlClose(sqlite3_file *pJfd){
  91150. MemJournal *p = (MemJournal *)pJfd;
  91151. memjrnlFreeChunks(p);
  91152. return SQLITE_OK;
  91153. }
  91154. /*
  91155. ** Sync the file.
  91156. **
  91157. ** If the real file has been created, call its xSync method. Otherwise,
  91158. ** syncing an in-memory journal is a no-op.
  91159. */
  91160. static int memjrnlSync(sqlite3_file *pJfd, int flags){
  91161. UNUSED_PARAMETER2(pJfd, flags);
  91162. return SQLITE_OK;
  91163. }
  91164. /*
  91165. ** Query the size of the file in bytes.
  91166. */
  91167. static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
  91168. MemJournal *p = (MemJournal *)pJfd;
  91169. *pSize = (sqlite_int64) p->endpoint.iOffset;
  91170. return SQLITE_OK;
  91171. }
  91172. /*
  91173. ** Table of methods for MemJournal sqlite3_file object.
  91174. */
  91175. static const struct sqlite3_io_methods MemJournalMethods = {
  91176. 1, /* iVersion */
  91177. memjrnlClose, /* xClose */
  91178. memjrnlRead, /* xRead */
  91179. memjrnlWrite, /* xWrite */
  91180. memjrnlTruncate, /* xTruncate */
  91181. memjrnlSync, /* xSync */
  91182. memjrnlFileSize, /* xFileSize */
  91183. 0, /* xLock */
  91184. 0, /* xUnlock */
  91185. 0, /* xCheckReservedLock */
  91186. 0, /* xFileControl */
  91187. 0, /* xSectorSize */
  91188. 0, /* xDeviceCharacteristics */
  91189. 0, /* xShmMap */
  91190. 0, /* xShmLock */
  91191. 0, /* xShmBarrier */
  91192. 0, /* xShmUnmap */
  91193. 0, /* xFetch */
  91194. 0 /* xUnfetch */
  91195. };
  91196. /*
  91197. ** Open a journal file.
  91198. **
  91199. ** The behaviour of the journal file depends on the value of parameter
  91200. ** nSpill. If nSpill is 0, then the journal file is always create and
  91201. ** accessed using the underlying VFS. If nSpill is less than zero, then
  91202. ** all content is always stored in main-memory. Finally, if nSpill is a
  91203. ** positive value, then the journal file is initially created in-memory
  91204. ** but may be flushed to disk later on. In this case the journal file is
  91205. ** flushed to disk either when it grows larger than nSpill bytes in size,
  91206. ** or when sqlite3JournalCreate() is called.
  91207. */
  91208. SQLITE_PRIVATE int sqlite3JournalOpen(
  91209. sqlite3_vfs *pVfs, /* The VFS to use for actual file I/O */
  91210. const char *zName, /* Name of the journal file */
  91211. sqlite3_file *pJfd, /* Preallocated, blank file handle */
  91212. int flags, /* Opening flags */
  91213. int nSpill /* Bytes buffered before opening the file */
  91214. ){
  91215. MemJournal *p = (MemJournal*)pJfd;
  91216. /* Zero the file-handle object. If nSpill was passed zero, initialize
  91217. ** it using the sqlite3OsOpen() function of the underlying VFS. In this
  91218. ** case none of the code in this module is executed as a result of calls
  91219. ** made on the journal file-handle. */
  91220. memset(p, 0, sizeof(MemJournal));
  91221. if( nSpill==0 ){
  91222. return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);
  91223. }
  91224. if( nSpill>0 ){
  91225. p->nChunkSize = nSpill;
  91226. }else{
  91227. p->nChunkSize = 8 + MEMJOURNAL_DFLT_FILECHUNKSIZE - sizeof(FileChunk);
  91228. assert( MEMJOURNAL_DFLT_FILECHUNKSIZE==fileChunkSize(p->nChunkSize) );
  91229. }
  91230. p->pMethod = (const sqlite3_io_methods*)&MemJournalMethods;
  91231. p->nSpill = nSpill;
  91232. p->flags = flags;
  91233. p->zJournal = zName;
  91234. p->pVfs = pVfs;
  91235. return SQLITE_OK;
  91236. }
  91237. /*
  91238. ** Open an in-memory journal file.
  91239. */
  91240. SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *pJfd){
  91241. sqlite3JournalOpen(0, 0, pJfd, 0, -1);
  91242. }
  91243. #if defined(SQLITE_ENABLE_ATOMIC_WRITE) \
  91244. || defined(SQLITE_ENABLE_BATCH_ATOMIC_WRITE)
  91245. /*
  91246. ** If the argument p points to a MemJournal structure that is not an
  91247. ** in-memory-only journal file (i.e. is one that was opened with a +ve
  91248. ** nSpill parameter or as SQLITE_OPEN_MAIN_JOURNAL), and the underlying
  91249. ** file has not yet been created, create it now.
  91250. */
  91251. SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *pJfd){
  91252. int rc = SQLITE_OK;
  91253. MemJournal *p = (MemJournal*)pJfd;
  91254. if( p->pMethod==&MemJournalMethods && (
  91255. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  91256. p->nSpill>0
  91257. #else
  91258. /* While this appears to not be possible without ATOMIC_WRITE, the
  91259. ** paths are complex, so it seems prudent to leave the test in as
  91260. ** a NEVER(), in case our analysis is subtly flawed. */
  91261. NEVER(p->nSpill>0)
  91262. #endif
  91263. #ifdef SQLITE_ENABLE_BATCH_ATOMIC_WRITE
  91264. || (p->flags & SQLITE_OPEN_MAIN_JOURNAL)
  91265. #endif
  91266. )){
  91267. rc = memjrnlCreateFile(p);
  91268. }
  91269. return rc;
  91270. }
  91271. #endif
  91272. /*
  91273. ** The file-handle passed as the only argument is open on a journal file.
  91274. ** Return true if this "journal file" is currently stored in heap memory,
  91275. ** or false otherwise.
  91276. */
  91277. SQLITE_PRIVATE int sqlite3JournalIsInMemory(sqlite3_file *p){
  91278. return p->pMethods==&MemJournalMethods;
  91279. }
  91280. /*
  91281. ** Return the number of bytes required to store a JournalFile that uses vfs
  91282. ** pVfs to create the underlying on-disk files.
  91283. */
  91284. SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){
  91285. return MAX(pVfs->szOsFile, (int)sizeof(MemJournal));
  91286. }
  91287. /************** End of memjournal.c ******************************************/
  91288. /************** Begin file walker.c ******************************************/
  91289. /*
  91290. ** 2008 August 16
  91291. **
  91292. ** The author disclaims copyright to this source code. In place of
  91293. ** a legal notice, here is a blessing:
  91294. **
  91295. ** May you do good and not evil.
  91296. ** May you find forgiveness for yourself and forgive others.
  91297. ** May you share freely, never taking more than you give.
  91298. **
  91299. *************************************************************************
  91300. ** This file contains routines used for walking the parser tree for
  91301. ** an SQL statement.
  91302. */
  91303. /* #include "sqliteInt.h" */
  91304. /* #include <stdlib.h> */
  91305. /* #include <string.h> */
  91306. #if !defined(SQLITE_OMIT_WINDOWFUNC)
  91307. /*
  91308. ** Walk all expressions linked into the list of Window objects passed
  91309. ** as the second argument.
  91310. */
  91311. static int walkWindowList(Walker *pWalker, Window *pList){
  91312. Window *pWin;
  91313. for(pWin=pList; pWin; pWin=pWin->pNextWin){
  91314. int rc;
  91315. rc = sqlite3WalkExprList(pWalker, pWin->pOrderBy);
  91316. if( rc ) return WRC_Abort;
  91317. rc = sqlite3WalkExprList(pWalker, pWin->pPartition);
  91318. if( rc ) return WRC_Abort;
  91319. rc = sqlite3WalkExpr(pWalker, pWin->pFilter);
  91320. if( rc ) return WRC_Abort;
  91321. /* The next two are purely for calls to sqlite3RenameExprUnmap()
  91322. ** within sqlite3WindowOffsetExpr(). Because of constraints imposed
  91323. ** by sqlite3WindowOffsetExpr(), they can never fail. The results do
  91324. ** not matter anyhow. */
  91325. rc = sqlite3WalkExpr(pWalker, pWin->pStart);
  91326. if( NEVER(rc) ) return WRC_Abort;
  91327. rc = sqlite3WalkExpr(pWalker, pWin->pEnd);
  91328. if( NEVER(rc) ) return WRC_Abort;
  91329. }
  91330. return WRC_Continue;
  91331. }
  91332. #endif
  91333. /*
  91334. ** Walk an expression tree. Invoke the callback once for each node
  91335. ** of the expression, while descending. (In other words, the callback
  91336. ** is invoked before visiting children.)
  91337. **
  91338. ** The return value from the callback should be one of the WRC_*
  91339. ** constants to specify how to proceed with the walk.
  91340. **
  91341. ** WRC_Continue Continue descending down the tree.
  91342. **
  91343. ** WRC_Prune Do not descend into child nodes, but allow
  91344. ** the walk to continue with sibling nodes.
  91345. **
  91346. ** WRC_Abort Do no more callbacks. Unwind the stack and
  91347. ** return from the top-level walk call.
  91348. **
  91349. ** The return value from this routine is WRC_Abort to abandon the tree walk
  91350. ** and WRC_Continue to continue.
  91351. */
  91352. static SQLITE_NOINLINE int walkExpr(Walker *pWalker, Expr *pExpr){
  91353. int rc;
  91354. testcase( ExprHasProperty(pExpr, EP_TokenOnly) );
  91355. testcase( ExprHasProperty(pExpr, EP_Reduced) );
  91356. while(1){
  91357. rc = pWalker->xExprCallback(pWalker, pExpr);
  91358. if( rc ) return rc & WRC_Abort;
  91359. if( !ExprHasProperty(pExpr,(EP_TokenOnly|EP_Leaf)) ){
  91360. assert( pExpr->x.pList==0 || pExpr->pRight==0 );
  91361. if( pExpr->pLeft && walkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;
  91362. if( pExpr->pRight ){
  91363. assert( !ExprHasProperty(pExpr, EP_WinFunc) );
  91364. pExpr = pExpr->pRight;
  91365. continue;
  91366. }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  91367. assert( !ExprHasProperty(pExpr, EP_WinFunc) );
  91368. if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort;
  91369. }else{
  91370. if( pExpr->x.pList ){
  91371. if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort;
  91372. }
  91373. #ifndef SQLITE_OMIT_WINDOWFUNC
  91374. if( ExprHasProperty(pExpr, EP_WinFunc) ){
  91375. if( walkWindowList(pWalker, pExpr->y.pWin) ) return WRC_Abort;
  91376. }
  91377. #endif
  91378. }
  91379. }
  91380. break;
  91381. }
  91382. return WRC_Continue;
  91383. }
  91384. SQLITE_PRIVATE int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){
  91385. return pExpr ? walkExpr(pWalker,pExpr) : WRC_Continue;
  91386. }
  91387. /*
  91388. ** Call sqlite3WalkExpr() for every expression in list p or until
  91389. ** an abort request is seen.
  91390. */
  91391. SQLITE_PRIVATE int sqlite3WalkExprList(Walker *pWalker, ExprList *p){
  91392. int i;
  91393. struct ExprList_item *pItem;
  91394. if( p ){
  91395. for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
  91396. if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort;
  91397. }
  91398. }
  91399. return WRC_Continue;
  91400. }
  91401. /*
  91402. ** Walk all expressions associated with SELECT statement p. Do
  91403. ** not invoke the SELECT callback on p, but do (of course) invoke
  91404. ** any expr callbacks and SELECT callbacks that come from subqueries.
  91405. ** Return WRC_Abort or WRC_Continue.
  91406. */
  91407. SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){
  91408. if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort;
  91409. if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort;
  91410. if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort;
  91411. if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;
  91412. if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;
  91413. if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;
  91414. #if !defined(SQLITE_OMIT_WINDOWFUNC) && !defined(SQLITE_OMIT_ALTERTABLE)
  91415. {
  91416. Parse *pParse = pWalker->pParse;
  91417. if( pParse && IN_RENAME_OBJECT ){
  91418. /* The following may return WRC_Abort if there are unresolvable
  91419. ** symbols (e.g. a table that does not exist) in a window definition. */
  91420. int rc = walkWindowList(pWalker, p->pWinDefn);
  91421. return rc;
  91422. }
  91423. }
  91424. #endif
  91425. return WRC_Continue;
  91426. }
  91427. /*
  91428. ** Walk the parse trees associated with all subqueries in the
  91429. ** FROM clause of SELECT statement p. Do not invoke the select
  91430. ** callback on p, but do invoke it on each FROM clause subquery
  91431. ** and on any subqueries further down in the tree. Return
  91432. ** WRC_Abort or WRC_Continue;
  91433. */
  91434. SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){
  91435. SrcList *pSrc;
  91436. int i;
  91437. struct SrcList_item *pItem;
  91438. pSrc = p->pSrc;
  91439. if( pSrc ){
  91440. for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
  91441. if( pItem->pSelect && sqlite3WalkSelect(pWalker, pItem->pSelect) ){
  91442. return WRC_Abort;
  91443. }
  91444. if( pItem->fg.isTabFunc
  91445. && sqlite3WalkExprList(pWalker, pItem->u1.pFuncArg)
  91446. ){
  91447. return WRC_Abort;
  91448. }
  91449. }
  91450. }
  91451. return WRC_Continue;
  91452. }
  91453. /*
  91454. ** Call sqlite3WalkExpr() for every expression in Select statement p.
  91455. ** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and
  91456. ** on the compound select chain, p->pPrior.
  91457. **
  91458. ** If it is not NULL, the xSelectCallback() callback is invoked before
  91459. ** the walk of the expressions and FROM clause. The xSelectCallback2()
  91460. ** method is invoked following the walk of the expressions and FROM clause,
  91461. ** but only if both xSelectCallback and xSelectCallback2 are both non-NULL
  91462. ** and if the expressions and FROM clause both return WRC_Continue;
  91463. **
  91464. ** Return WRC_Continue under normal conditions. Return WRC_Abort if
  91465. ** there is an abort request.
  91466. **
  91467. ** If the Walker does not have an xSelectCallback() then this routine
  91468. ** is a no-op returning WRC_Continue.
  91469. */
  91470. SQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){
  91471. int rc;
  91472. if( p==0 ) return WRC_Continue;
  91473. if( pWalker->xSelectCallback==0 ) return WRC_Continue;
  91474. do{
  91475. rc = pWalker->xSelectCallback(pWalker, p);
  91476. if( rc ) return rc & WRC_Abort;
  91477. if( sqlite3WalkSelectExpr(pWalker, p)
  91478. || sqlite3WalkSelectFrom(pWalker, p)
  91479. ){
  91480. return WRC_Abort;
  91481. }
  91482. if( pWalker->xSelectCallback2 ){
  91483. pWalker->xSelectCallback2(pWalker, p);
  91484. }
  91485. p = p->pPrior;
  91486. }while( p!=0 );
  91487. return WRC_Continue;
  91488. }
  91489. /* Increase the walkerDepth when entering a subquery, and
  91490. ** descrease when leaving the subquery.
  91491. */
  91492. SQLITE_PRIVATE int sqlite3WalkerDepthIncrease(Walker *pWalker, Select *pSelect){
  91493. UNUSED_PARAMETER(pSelect);
  91494. pWalker->walkerDepth++;
  91495. return WRC_Continue;
  91496. }
  91497. SQLITE_PRIVATE void sqlite3WalkerDepthDecrease(Walker *pWalker, Select *pSelect){
  91498. UNUSED_PARAMETER(pSelect);
  91499. pWalker->walkerDepth--;
  91500. }
  91501. /*
  91502. ** No-op routine for the parse-tree walker.
  91503. **
  91504. ** When this routine is the Walker.xExprCallback then expression trees
  91505. ** are walked without any actions being taken at each node. Presumably,
  91506. ** when this routine is used for Walker.xExprCallback then
  91507. ** Walker.xSelectCallback is set to do something useful for every
  91508. ** subquery in the parser tree.
  91509. */
  91510. SQLITE_PRIVATE int sqlite3ExprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
  91511. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  91512. return WRC_Continue;
  91513. }
  91514. /*
  91515. ** No-op routine for the parse-tree walker for SELECT statements.
  91516. ** subquery in the parser tree.
  91517. */
  91518. SQLITE_PRIVATE int sqlite3SelectWalkNoop(Walker *NotUsed, Select *NotUsed2){
  91519. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  91520. return WRC_Continue;
  91521. }
  91522. /************** End of walker.c **********************************************/
  91523. /************** Begin file resolve.c *****************************************/
  91524. /*
  91525. ** 2008 August 18
  91526. **
  91527. ** The author disclaims copyright to this source code. In place of
  91528. ** a legal notice, here is a blessing:
  91529. **
  91530. ** May you do good and not evil.
  91531. ** May you find forgiveness for yourself and forgive others.
  91532. ** May you share freely, never taking more than you give.
  91533. **
  91534. *************************************************************************
  91535. **
  91536. ** This file contains routines used for walking the parser tree and
  91537. ** resolve all identifiers by associating them with a particular
  91538. ** table and column.
  91539. */
  91540. /* #include "sqliteInt.h" */
  91541. /*
  91542. ** Walk the expression tree pExpr and increase the aggregate function
  91543. ** depth (the Expr.op2 field) by N on every TK_AGG_FUNCTION node.
  91544. ** This needs to occur when copying a TK_AGG_FUNCTION node from an
  91545. ** outer query into an inner subquery.
  91546. **
  91547. ** incrAggFunctionDepth(pExpr,n) is the main routine. incrAggDepth(..)
  91548. ** is a helper function - a callback for the tree walker.
  91549. **
  91550. ** See also the sqlite3WindowExtraAggFuncDepth() routine in window.c
  91551. */
  91552. static int incrAggDepth(Walker *pWalker, Expr *pExpr){
  91553. if( pExpr->op==TK_AGG_FUNCTION ) pExpr->op2 += pWalker->u.n;
  91554. return WRC_Continue;
  91555. }
  91556. static void incrAggFunctionDepth(Expr *pExpr, int N){
  91557. if( N>0 ){
  91558. Walker w;
  91559. memset(&w, 0, sizeof(w));
  91560. w.xExprCallback = incrAggDepth;
  91561. w.u.n = N;
  91562. sqlite3WalkExpr(&w, pExpr);
  91563. }
  91564. }
  91565. /*
  91566. ** Turn the pExpr expression into an alias for the iCol-th column of the
  91567. ** result set in pEList.
  91568. **
  91569. ** If the reference is followed by a COLLATE operator, then make sure
  91570. ** the COLLATE operator is preserved. For example:
  91571. **
  91572. ** SELECT a+b, c+d FROM t1 ORDER BY 1 COLLATE nocase;
  91573. **
  91574. ** Should be transformed into:
  91575. **
  91576. ** SELECT a+b, c+d FROM t1 ORDER BY (a+b) COLLATE nocase;
  91577. **
  91578. ** The nSubquery parameter specifies how many levels of subquery the
  91579. ** alias is removed from the original expression. The usual value is
  91580. ** zero but it might be more if the alias is contained within a subquery
  91581. ** of the original expression. The Expr.op2 field of TK_AGG_FUNCTION
  91582. ** structures must be increased by the nSubquery amount.
  91583. */
  91584. static void resolveAlias(
  91585. Parse *pParse, /* Parsing context */
  91586. ExprList *pEList, /* A result set */
  91587. int iCol, /* A column in the result set. 0..pEList->nExpr-1 */
  91588. Expr *pExpr, /* Transform this into an alias to the result set */
  91589. const char *zType, /* "GROUP" or "ORDER" or "" */
  91590. int nSubquery /* Number of subqueries that the label is moving */
  91591. ){
  91592. Expr *pOrig; /* The iCol-th column of the result set */
  91593. Expr *pDup; /* Copy of pOrig */
  91594. sqlite3 *db; /* The database connection */
  91595. assert( iCol>=0 && iCol<pEList->nExpr );
  91596. pOrig = pEList->a[iCol].pExpr;
  91597. assert( pOrig!=0 );
  91598. db = pParse->db;
  91599. pDup = sqlite3ExprDup(db, pOrig, 0);
  91600. if( pDup!=0 ){
  91601. if( zType[0]!='G' ) incrAggFunctionDepth(pDup, nSubquery);
  91602. if( pExpr->op==TK_COLLATE ){
  91603. pDup = sqlite3ExprAddCollateString(pParse, pDup, pExpr->u.zToken);
  91604. }
  91605. /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This
  91606. ** prevents ExprDelete() from deleting the Expr structure itself,
  91607. ** allowing it to be repopulated by the memcpy() on the following line.
  91608. ** The pExpr->u.zToken might point into memory that will be freed by the
  91609. ** sqlite3DbFree(db, pDup) on the last line of this block, so be sure to
  91610. ** make a copy of the token before doing the sqlite3DbFree().
  91611. */
  91612. ExprSetProperty(pExpr, EP_Static);
  91613. sqlite3ExprDelete(db, pExpr);
  91614. memcpy(pExpr, pDup, sizeof(*pExpr));
  91615. if( !ExprHasProperty(pExpr, EP_IntValue) && pExpr->u.zToken!=0 ){
  91616. assert( (pExpr->flags & (EP_Reduced|EP_TokenOnly))==0 );
  91617. pExpr->u.zToken = sqlite3DbStrDup(db, pExpr->u.zToken);
  91618. pExpr->flags |= EP_MemToken;
  91619. }
  91620. if( ExprHasProperty(pExpr, EP_WinFunc) ){
  91621. if( pExpr->y.pWin!=0 ){
  91622. pExpr->y.pWin->pOwner = pExpr;
  91623. }else{
  91624. assert( db->mallocFailed );
  91625. }
  91626. }
  91627. sqlite3DbFree(db, pDup);
  91628. }
  91629. ExprSetProperty(pExpr, EP_Alias);
  91630. }
  91631. /*
  91632. ** Return TRUE if the name zCol occurs anywhere in the USING clause.
  91633. **
  91634. ** Return FALSE if the USING clause is NULL or if it does not contain
  91635. ** zCol.
  91636. */
  91637. static int nameInUsingClause(IdList *pUsing, const char *zCol){
  91638. if( pUsing ){
  91639. int k;
  91640. for(k=0; k<pUsing->nId; k++){
  91641. if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ) return 1;
  91642. }
  91643. }
  91644. return 0;
  91645. }
  91646. /*
  91647. ** Subqueries stores the original database, table and column names for their
  91648. ** result sets in ExprList.a[].zSpan, in the form "DATABASE.TABLE.COLUMN".
  91649. ** Check to see if the zSpan given to this routine matches the zDb, zTab,
  91650. ** and zCol. If any of zDb, zTab, and zCol are NULL then those fields will
  91651. ** match anything.
  91652. */
  91653. SQLITE_PRIVATE int sqlite3MatchEName(
  91654. const struct ExprList_item *pItem,
  91655. const char *zCol,
  91656. const char *zTab,
  91657. const char *zDb
  91658. ){
  91659. int n;
  91660. const char *zSpan;
  91661. if( pItem->eEName!=ENAME_TAB ) return 0;
  91662. zSpan = pItem->zEName;
  91663. for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
  91664. if( zDb && (sqlite3StrNICmp(zSpan, zDb, n)!=0 || zDb[n]!=0) ){
  91665. return 0;
  91666. }
  91667. zSpan += n+1;
  91668. for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
  91669. if( zTab && (sqlite3StrNICmp(zSpan, zTab, n)!=0 || zTab[n]!=0) ){
  91670. return 0;
  91671. }
  91672. zSpan += n+1;
  91673. if( zCol && sqlite3StrICmp(zSpan, zCol)!=0 ){
  91674. return 0;
  91675. }
  91676. return 1;
  91677. }
  91678. /*
  91679. ** Return TRUE if the double-quoted string mis-feature should be supported.
  91680. */
  91681. static int areDoubleQuotedStringsEnabled(sqlite3 *db, NameContext *pTopNC){
  91682. if( db->init.busy ) return 1; /* Always support for legacy schemas */
  91683. if( pTopNC->ncFlags & NC_IsDDL ){
  91684. /* Currently parsing a DDL statement */
  91685. if( sqlite3WritableSchema(db) && (db->flags & SQLITE_DqsDML)!=0 ){
  91686. return 1;
  91687. }
  91688. return (db->flags & SQLITE_DqsDDL)!=0;
  91689. }else{
  91690. /* Currently parsing a DML statement */
  91691. return (db->flags & SQLITE_DqsDML)!=0;
  91692. }
  91693. }
  91694. /*
  91695. ** The argument is guaranteed to be a non-NULL Expr node of type TK_COLUMN.
  91696. ** return the appropriate colUsed mask.
  91697. */
  91698. SQLITE_PRIVATE Bitmask sqlite3ExprColUsed(Expr *pExpr){
  91699. int n;
  91700. Table *pExTab;
  91701. n = pExpr->iColumn;
  91702. pExTab = pExpr->y.pTab;
  91703. assert( pExTab!=0 );
  91704. if( (pExTab->tabFlags & TF_HasGenerated)!=0
  91705. && (pExTab->aCol[n].colFlags & COLFLAG_GENERATED)!=0
  91706. ){
  91707. testcase( pExTab->nCol==BMS-1 );
  91708. testcase( pExTab->nCol==BMS );
  91709. return pExTab->nCol>=BMS ? ALLBITS : MASKBIT(pExTab->nCol)-1;
  91710. }else{
  91711. testcase( n==BMS-1 );
  91712. testcase( n==BMS );
  91713. if( n>=BMS ) n = BMS-1;
  91714. return ((Bitmask)1)<<n;
  91715. }
  91716. }
  91717. /*
  91718. ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
  91719. ** that name in the set of source tables in pSrcList and make the pExpr
  91720. ** expression node refer back to that source column. The following changes
  91721. ** are made to pExpr:
  91722. **
  91723. ** pExpr->iDb Set the index in db->aDb[] of the database X
  91724. ** (even if X is implied).
  91725. ** pExpr->iTable Set to the cursor number for the table obtained
  91726. ** from pSrcList.
  91727. ** pExpr->y.pTab Points to the Table structure of X.Y (even if
  91728. ** X and/or Y are implied.)
  91729. ** pExpr->iColumn Set to the column number within the table.
  91730. ** pExpr->op Set to TK_COLUMN.
  91731. ** pExpr->pLeft Any expression this points to is deleted
  91732. ** pExpr->pRight Any expression this points to is deleted.
  91733. **
  91734. ** The zDb variable is the name of the database (the "X"). This value may be
  91735. ** NULL meaning that name is of the form Y.Z or Z. Any available database
  91736. ** can be used. The zTable variable is the name of the table (the "Y"). This
  91737. ** value can be NULL if zDb is also NULL. If zTable is NULL it
  91738. ** means that the form of the name is Z and that columns from any table
  91739. ** can be used.
  91740. **
  91741. ** If the name cannot be resolved unambiguously, leave an error message
  91742. ** in pParse and return WRC_Abort. Return WRC_Prune on success.
  91743. */
  91744. static int lookupName(
  91745. Parse *pParse, /* The parsing context */
  91746. const char *zDb, /* Name of the database containing table, or NULL */
  91747. const char *zTab, /* Name of table containing column, or NULL */
  91748. const char *zCol, /* Name of the column. */
  91749. NameContext *pNC, /* The name context used to resolve the name */
  91750. Expr *pExpr /* Make this EXPR node point to the selected column */
  91751. ){
  91752. int i, j; /* Loop counters */
  91753. int cnt = 0; /* Number of matching column names */
  91754. int cntTab = 0; /* Number of matching table names */
  91755. int nSubquery = 0; /* How many levels of subquery */
  91756. sqlite3 *db = pParse->db; /* The database connection */
  91757. struct SrcList_item *pItem; /* Use for looping over pSrcList items */
  91758. struct SrcList_item *pMatch = 0; /* The matching pSrcList item */
  91759. NameContext *pTopNC = pNC; /* First namecontext in the list */
  91760. Schema *pSchema = 0; /* Schema of the expression */
  91761. int eNewExprOp = TK_COLUMN; /* New value for pExpr->op on success */
  91762. Table *pTab = 0; /* Table hold the row */
  91763. Column *pCol; /* A column of pTab */
  91764. assert( pNC ); /* the name context cannot be NULL. */
  91765. assert( zCol ); /* The Z in X.Y.Z cannot be NULL */
  91766. assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
  91767. /* Initialize the node to no-match */
  91768. pExpr->iTable = -1;
  91769. ExprSetVVAProperty(pExpr, EP_NoReduce);
  91770. /* Translate the schema name in zDb into a pointer to the corresponding
  91771. ** schema. If not found, pSchema will remain NULL and nothing will match
  91772. ** resulting in an appropriate error message toward the end of this routine
  91773. */
  91774. if( zDb ){
  91775. testcase( pNC->ncFlags & NC_PartIdx );
  91776. testcase( pNC->ncFlags & NC_IsCheck );
  91777. if( (pNC->ncFlags & (NC_PartIdx|NC_IsCheck))!=0 ){
  91778. /* Silently ignore database qualifiers inside CHECK constraints and
  91779. ** partial indices. Do not raise errors because that might break
  91780. ** legacy and because it does not hurt anything to just ignore the
  91781. ** database name. */
  91782. zDb = 0;
  91783. }else{
  91784. for(i=0; i<db->nDb; i++){
  91785. assert( db->aDb[i].zDbSName );
  91786. if( sqlite3StrICmp(db->aDb[i].zDbSName,zDb)==0 ){
  91787. pSchema = db->aDb[i].pSchema;
  91788. break;
  91789. }
  91790. }
  91791. if( i==db->nDb && sqlite3StrICmp("main", zDb)==0 ){
  91792. /* This branch is taken when the main database has been renamed
  91793. ** using SQLITE_DBCONFIG_MAINDBNAME. */
  91794. pSchema = db->aDb[0].pSchema;
  91795. zDb = db->aDb[0].zDbSName;
  91796. }
  91797. }
  91798. }
  91799. /* Start at the inner-most context and move outward until a match is found */
  91800. assert( pNC && cnt==0 );
  91801. do{
  91802. ExprList *pEList;
  91803. SrcList *pSrcList = pNC->pSrcList;
  91804. if( pSrcList ){
  91805. for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
  91806. u8 hCol;
  91807. pTab = pItem->pTab;
  91808. assert( pTab!=0 && pTab->zName!=0 );
  91809. assert( pTab->nCol>0 );
  91810. if( pItem->pSelect && (pItem->pSelect->selFlags & SF_NestedFrom)!=0 ){
  91811. int hit = 0;
  91812. pEList = pItem->pSelect->pEList;
  91813. for(j=0; j<pEList->nExpr; j++){
  91814. if( sqlite3MatchEName(&pEList->a[j], zCol, zTab, zDb) ){
  91815. cnt++;
  91816. cntTab = 2;
  91817. pMatch = pItem;
  91818. pExpr->iColumn = j;
  91819. hit = 1;
  91820. }
  91821. }
  91822. if( hit || zTab==0 ) continue;
  91823. }
  91824. if( zDb && pTab->pSchema!=pSchema ){
  91825. continue;
  91826. }
  91827. if( zTab ){
  91828. const char *zTabName = pItem->zAlias ? pItem->zAlias : pTab->zName;
  91829. assert( zTabName!=0 );
  91830. if( sqlite3StrICmp(zTabName, zTab)!=0 ){
  91831. continue;
  91832. }
  91833. if( IN_RENAME_OBJECT && pItem->zAlias ){
  91834. sqlite3RenameTokenRemap(pParse, 0, (void*)&pExpr->y.pTab);
  91835. }
  91836. }
  91837. if( 0==(cntTab++) ){
  91838. pMatch = pItem;
  91839. }
  91840. hCol = sqlite3StrIHash(zCol);
  91841. for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
  91842. if( pCol->hName==hCol && sqlite3StrICmp(pCol->zName, zCol)==0 ){
  91843. /* If there has been exactly one prior match and this match
  91844. ** is for the right-hand table of a NATURAL JOIN or is in a
  91845. ** USING clause, then skip this match.
  91846. */
  91847. if( cnt==1 ){
  91848. if( pItem->fg.jointype & JT_NATURAL ) continue;
  91849. if( nameInUsingClause(pItem->pUsing, zCol) ) continue;
  91850. }
  91851. cnt++;
  91852. pMatch = pItem;
  91853. /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
  91854. pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
  91855. break;
  91856. }
  91857. }
  91858. }
  91859. if( pMatch ){
  91860. pExpr->iTable = pMatch->iCursor;
  91861. pExpr->y.pTab = pMatch->pTab;
  91862. /* RIGHT JOIN not (yet) supported */
  91863. assert( (pMatch->fg.jointype & JT_RIGHT)==0 );
  91864. if( (pMatch->fg.jointype & JT_LEFT)!=0 ){
  91865. ExprSetProperty(pExpr, EP_CanBeNull);
  91866. }
  91867. pSchema = pExpr->y.pTab->pSchema;
  91868. }
  91869. } /* if( pSrcList ) */
  91870. #if !defined(SQLITE_OMIT_TRIGGER) || !defined(SQLITE_OMIT_UPSERT)
  91871. /* If we have not already resolved the name, then maybe
  91872. ** it is a new.* or old.* trigger argument reference. Or
  91873. ** maybe it is an excluded.* from an upsert.
  91874. */
  91875. if( zDb==0 && zTab!=0 && cntTab==0 ){
  91876. pTab = 0;
  91877. #ifndef SQLITE_OMIT_TRIGGER
  91878. if( pParse->pTriggerTab!=0 ){
  91879. int op = pParse->eTriggerOp;
  91880. assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
  91881. if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
  91882. pExpr->iTable = 1;
  91883. pTab = pParse->pTriggerTab;
  91884. }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
  91885. pExpr->iTable = 0;
  91886. pTab = pParse->pTriggerTab;
  91887. }
  91888. }
  91889. #endif /* SQLITE_OMIT_TRIGGER */
  91890. #ifndef SQLITE_OMIT_UPSERT
  91891. if( (pNC->ncFlags & NC_UUpsert)!=0 ){
  91892. Upsert *pUpsert = pNC->uNC.pUpsert;
  91893. if( pUpsert && sqlite3StrICmp("excluded",zTab)==0 ){
  91894. pTab = pUpsert->pUpsertSrc->a[0].pTab;
  91895. pExpr->iTable = 2;
  91896. }
  91897. }
  91898. #endif /* SQLITE_OMIT_UPSERT */
  91899. if( pTab ){
  91900. int iCol;
  91901. u8 hCol = sqlite3StrIHash(zCol);
  91902. pSchema = pTab->pSchema;
  91903. cntTab++;
  91904. for(iCol=0, pCol=pTab->aCol; iCol<pTab->nCol; iCol++, pCol++){
  91905. if( pCol->hName==hCol && sqlite3StrICmp(pCol->zName, zCol)==0 ){
  91906. if( iCol==pTab->iPKey ){
  91907. iCol = -1;
  91908. }
  91909. break;
  91910. }
  91911. }
  91912. if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) && VisibleRowid(pTab) ){
  91913. /* IMP: R-51414-32910 */
  91914. iCol = -1;
  91915. }
  91916. if( iCol<pTab->nCol ){
  91917. cnt++;
  91918. #ifndef SQLITE_OMIT_UPSERT
  91919. if( pExpr->iTable==2 ){
  91920. testcase( iCol==(-1) );
  91921. if( IN_RENAME_OBJECT ){
  91922. pExpr->iColumn = iCol;
  91923. pExpr->y.pTab = pTab;
  91924. eNewExprOp = TK_COLUMN;
  91925. }else{
  91926. pExpr->iTable = pNC->uNC.pUpsert->regData + iCol;
  91927. eNewExprOp = TK_REGISTER;
  91928. ExprSetProperty(pExpr, EP_Alias);
  91929. }
  91930. }else
  91931. #endif /* SQLITE_OMIT_UPSERT */
  91932. {
  91933. #ifndef SQLITE_OMIT_TRIGGER
  91934. if( iCol<0 ){
  91935. pExpr->affExpr = SQLITE_AFF_INTEGER;
  91936. }else if( pExpr->iTable==0 ){
  91937. testcase( iCol==31 );
  91938. testcase( iCol==32 );
  91939. pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
  91940. }else{
  91941. testcase( iCol==31 );
  91942. testcase( iCol==32 );
  91943. pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
  91944. }
  91945. pExpr->y.pTab = pTab;
  91946. pExpr->iColumn = (i16)iCol;
  91947. eNewExprOp = TK_TRIGGER;
  91948. #endif /* SQLITE_OMIT_TRIGGER */
  91949. }
  91950. }
  91951. }
  91952. }
  91953. #endif /* !defined(SQLITE_OMIT_TRIGGER) || !defined(SQLITE_OMIT_UPSERT) */
  91954. /*
  91955. ** Perhaps the name is a reference to the ROWID
  91956. */
  91957. if( cnt==0
  91958. && cntTab==1
  91959. && pMatch
  91960. && (pNC->ncFlags & (NC_IdxExpr|NC_GenCol))==0
  91961. && sqlite3IsRowid(zCol)
  91962. && VisibleRowid(pMatch->pTab)
  91963. ){
  91964. cnt = 1;
  91965. pExpr->iColumn = -1;
  91966. pExpr->affExpr = SQLITE_AFF_INTEGER;
  91967. }
  91968. /*
  91969. ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
  91970. ** might refer to an result-set alias. This happens, for example, when
  91971. ** we are resolving names in the WHERE clause of the following command:
  91972. **
  91973. ** SELECT a+b AS x FROM table WHERE x<10;
  91974. **
  91975. ** In cases like this, replace pExpr with a copy of the expression that
  91976. ** forms the result set entry ("a+b" in the example) and return immediately.
  91977. ** Note that the expression in the result set should have already been
  91978. ** resolved by the time the WHERE clause is resolved.
  91979. **
  91980. ** The ability to use an output result-set column in the WHERE, GROUP BY,
  91981. ** or HAVING clauses, or as part of a larger expression in the ORDER BY
  91982. ** clause is not standard SQL. This is a (goofy) SQLite extension, that
  91983. ** is supported for backwards compatibility only. Hence, we issue a warning
  91984. ** on sqlite3_log() whenever the capability is used.
  91985. */
  91986. if( (pNC->ncFlags & NC_UEList)!=0
  91987. && cnt==0
  91988. && zTab==0
  91989. ){
  91990. pEList = pNC->uNC.pEList;
  91991. assert( pEList!=0 );
  91992. for(j=0; j<pEList->nExpr; j++){
  91993. char *zAs = pEList->a[j].zEName;
  91994. if( pEList->a[j].eEName==ENAME_NAME
  91995. && sqlite3_stricmp(zAs, zCol)==0
  91996. ){
  91997. Expr *pOrig;
  91998. assert( pExpr->pLeft==0 && pExpr->pRight==0 );
  91999. assert( pExpr->x.pList==0 );
  92000. assert( pExpr->x.pSelect==0 );
  92001. pOrig = pEList->a[j].pExpr;
  92002. if( (pNC->ncFlags&NC_AllowAgg)==0 && ExprHasProperty(pOrig, EP_Agg) ){
  92003. sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
  92004. return WRC_Abort;
  92005. }
  92006. if( ExprHasProperty(pOrig, EP_Win)
  92007. && ((pNC->ncFlags&NC_AllowWin)==0 || pNC!=pTopNC )
  92008. ){
  92009. sqlite3ErrorMsg(pParse, "misuse of aliased window function %s",zAs);
  92010. return WRC_Abort;
  92011. }
  92012. if( sqlite3ExprVectorSize(pOrig)!=1 ){
  92013. sqlite3ErrorMsg(pParse, "row value misused");
  92014. return WRC_Abort;
  92015. }
  92016. resolveAlias(pParse, pEList, j, pExpr, "", nSubquery);
  92017. cnt = 1;
  92018. pMatch = 0;
  92019. assert( zTab==0 && zDb==0 );
  92020. if( IN_RENAME_OBJECT ){
  92021. sqlite3RenameTokenRemap(pParse, 0, (void*)pExpr);
  92022. }
  92023. goto lookupname_end;
  92024. }
  92025. }
  92026. }
  92027. /* Advance to the next name context. The loop will exit when either
  92028. ** we have a match (cnt>0) or when we run out of name contexts.
  92029. */
  92030. if( cnt ) break;
  92031. pNC = pNC->pNext;
  92032. nSubquery++;
  92033. }while( pNC );
  92034. /*
  92035. ** If X and Y are NULL (in other words if only the column name Z is
  92036. ** supplied) and the value of Z is enclosed in double-quotes, then
  92037. ** Z is a string literal if it doesn't match any column names. In that
  92038. ** case, we need to return right away and not make any changes to
  92039. ** pExpr.
  92040. **
  92041. ** Because no reference was made to outer contexts, the pNC->nRef
  92042. ** fields are not changed in any context.
  92043. */
  92044. if( cnt==0 && zTab==0 ){
  92045. assert( pExpr->op==TK_ID );
  92046. if( ExprHasProperty(pExpr,EP_DblQuoted)
  92047. && areDoubleQuotedStringsEnabled(db, pTopNC)
  92048. ){
  92049. /* If a double-quoted identifier does not match any known column name,
  92050. ** then treat it as a string.
  92051. **
  92052. ** This hack was added in the early days of SQLite in a misguided attempt
  92053. ** to be compatible with MySQL 3.x, which used double-quotes for strings.
  92054. ** I now sorely regret putting in this hack. The effect of this hack is
  92055. ** that misspelled identifier names are silently converted into strings
  92056. ** rather than causing an error, to the frustration of countless
  92057. ** programmers. To all those frustrated programmers, my apologies.
  92058. **
  92059. ** Someday, I hope to get rid of this hack. Unfortunately there is
  92060. ** a huge amount of legacy SQL that uses it. So for now, we just
  92061. ** issue a warning.
  92062. */
  92063. sqlite3_log(SQLITE_WARNING,
  92064. "double-quoted string literal: \"%w\"", zCol);
  92065. #ifdef SQLITE_ENABLE_NORMALIZE
  92066. sqlite3VdbeAddDblquoteStr(db, pParse->pVdbe, zCol);
  92067. #endif
  92068. pExpr->op = TK_STRING;
  92069. pExpr->y.pTab = 0;
  92070. return WRC_Prune;
  92071. }
  92072. if( sqlite3ExprIdToTrueFalse(pExpr) ){
  92073. return WRC_Prune;
  92074. }
  92075. }
  92076. /*
  92077. ** cnt==0 means there was not match. cnt>1 means there were two or
  92078. ** more matches. Either way, we have an error.
  92079. */
  92080. if( cnt!=1 ){
  92081. const char *zErr;
  92082. zErr = cnt==0 ? "no such column" : "ambiguous column name";
  92083. if( zDb ){
  92084. sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
  92085. }else if( zTab ){
  92086. sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
  92087. }else{
  92088. sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
  92089. }
  92090. pParse->checkSchema = 1;
  92091. pTopNC->nErr++;
  92092. }
  92093. /* If a column from a table in pSrcList is referenced, then record
  92094. ** this fact in the pSrcList.a[].colUsed bitmask. Column 0 causes
  92095. ** bit 0 to be set. Column 1 sets bit 1. And so forth. Bit 63 is
  92096. ** set if the 63rd or any subsequent column is used.
  92097. **
  92098. ** The colUsed mask is an optimization used to help determine if an
  92099. ** index is a covering index. The correct answer is still obtained
  92100. ** if the mask contains extra set bits. However, it is important to
  92101. ** avoid setting bits beyond the maximum column number of the table.
  92102. ** (See ticket [b92e5e8ec2cdbaa1]).
  92103. **
  92104. ** If a generated column is referenced, set bits for every column
  92105. ** of the table.
  92106. */
  92107. if( pExpr->iColumn>=0 && pMatch!=0 ){
  92108. pMatch->colUsed |= sqlite3ExprColUsed(pExpr);
  92109. }
  92110. /* Clean up and return
  92111. */
  92112. sqlite3ExprDelete(db, pExpr->pLeft);
  92113. pExpr->pLeft = 0;
  92114. sqlite3ExprDelete(db, pExpr->pRight);
  92115. pExpr->pRight = 0;
  92116. pExpr->op = eNewExprOp;
  92117. ExprSetProperty(pExpr, EP_Leaf);
  92118. lookupname_end:
  92119. if( cnt==1 ){
  92120. assert( pNC!=0 );
  92121. if( !ExprHasProperty(pExpr, EP_Alias) ){
  92122. sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
  92123. }
  92124. /* Increment the nRef value on all name contexts from TopNC up to
  92125. ** the point where the name matched. */
  92126. for(;;){
  92127. assert( pTopNC!=0 );
  92128. pTopNC->nRef++;
  92129. if( pTopNC==pNC ) break;
  92130. pTopNC = pTopNC->pNext;
  92131. }
  92132. return WRC_Prune;
  92133. } else {
  92134. return WRC_Abort;
  92135. }
  92136. }
  92137. /*
  92138. ** Allocate and return a pointer to an expression to load the column iCol
  92139. ** from datasource iSrc in SrcList pSrc.
  92140. */
  92141. SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
  92142. Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
  92143. if( p ){
  92144. struct SrcList_item *pItem = &pSrc->a[iSrc];
  92145. Table *pTab = p->y.pTab = pItem->pTab;
  92146. p->iTable = pItem->iCursor;
  92147. if( p->y.pTab->iPKey==iCol ){
  92148. p->iColumn = -1;
  92149. }else{
  92150. p->iColumn = (ynVar)iCol;
  92151. if( (pTab->tabFlags & TF_HasGenerated)!=0
  92152. && (pTab->aCol[iCol].colFlags & COLFLAG_GENERATED)!=0
  92153. ){
  92154. testcase( pTab->nCol==63 );
  92155. testcase( pTab->nCol==64 );
  92156. pItem->colUsed = pTab->nCol>=64 ? ALLBITS : MASKBIT(pTab->nCol)-1;
  92157. }else{
  92158. testcase( iCol==BMS );
  92159. testcase( iCol==BMS-1 );
  92160. pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
  92161. }
  92162. }
  92163. }
  92164. return p;
  92165. }
  92166. /*
  92167. ** Report an error that an expression is not valid for some set of
  92168. ** pNC->ncFlags values determined by validMask.
  92169. **
  92170. ** static void notValid(
  92171. ** Parse *pParse, // Leave error message here
  92172. ** NameContext *pNC, // The name context
  92173. ** const char *zMsg, // Type of error
  92174. ** int validMask, // Set of contexts for which prohibited
  92175. ** Expr *pExpr // Invalidate this expression on error
  92176. ** ){...}
  92177. **
  92178. ** As an optimization, since the conditional is almost always false
  92179. ** (because errors are rare), the conditional is moved outside of the
  92180. ** function call using a macro.
  92181. */
  92182. static void notValidImpl(
  92183. Parse *pParse, /* Leave error message here */
  92184. NameContext *pNC, /* The name context */
  92185. const char *zMsg, /* Type of error */
  92186. Expr *pExpr /* Invalidate this expression on error */
  92187. ){
  92188. const char *zIn = "partial index WHERE clauses";
  92189. if( pNC->ncFlags & NC_IdxExpr ) zIn = "index expressions";
  92190. #ifndef SQLITE_OMIT_CHECK
  92191. else if( pNC->ncFlags & NC_IsCheck ) zIn = "CHECK constraints";
  92192. #endif
  92193. #ifndef SQLITE_OMIT_GENERATED_COLUMNS
  92194. else if( pNC->ncFlags & NC_GenCol ) zIn = "generated columns";
  92195. #endif
  92196. sqlite3ErrorMsg(pParse, "%s prohibited in %s", zMsg, zIn);
  92197. if( pExpr ) pExpr->op = TK_NULL;
  92198. }
  92199. #define sqlite3ResolveNotValid(P,N,M,X,E) \
  92200. assert( ((X)&~(NC_IsCheck|NC_PartIdx|NC_IdxExpr|NC_GenCol))==0 ); \
  92201. if( ((N)->ncFlags & (X))!=0 ) notValidImpl(P,N,M,E);
  92202. /*
  92203. ** Expression p should encode a floating point value between 1.0 and 0.0.
  92204. ** Return 1024 times this value. Or return -1 if p is not a floating point
  92205. ** value between 1.0 and 0.0.
  92206. */
  92207. static int exprProbability(Expr *p){
  92208. double r = -1.0;
  92209. if( p->op!=TK_FLOAT ) return -1;
  92210. sqlite3AtoF(p->u.zToken, &r, sqlite3Strlen30(p->u.zToken), SQLITE_UTF8);
  92211. assert( r>=0.0 );
  92212. if( r>1.0 ) return -1;
  92213. return (int)(r*134217728.0);
  92214. }
  92215. /*
  92216. ** This routine is callback for sqlite3WalkExpr().
  92217. **
  92218. ** Resolve symbolic names into TK_COLUMN operators for the current
  92219. ** node in the expression tree. Return 0 to continue the search down
  92220. ** the tree or 2 to abort the tree walk.
  92221. **
  92222. ** This routine also does error checking and name resolution for
  92223. ** function names. The operator for aggregate functions is changed
  92224. ** to TK_AGG_FUNCTION.
  92225. */
  92226. static int resolveExprStep(Walker *pWalker, Expr *pExpr){
  92227. NameContext *pNC;
  92228. Parse *pParse;
  92229. pNC = pWalker->u.pNC;
  92230. assert( pNC!=0 );
  92231. pParse = pNC->pParse;
  92232. assert( pParse==pWalker->pParse );
  92233. #ifndef NDEBUG
  92234. if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
  92235. SrcList *pSrcList = pNC->pSrcList;
  92236. int i;
  92237. for(i=0; i<pNC->pSrcList->nSrc; i++){
  92238. assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
  92239. }
  92240. }
  92241. #endif
  92242. switch( pExpr->op ){
  92243. #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
  92244. /* The special operator TK_ROW means use the rowid for the first
  92245. ** column in the FROM clause. This is used by the LIMIT and ORDER BY
  92246. ** clause processing on UPDATE and DELETE statements.
  92247. */
  92248. case TK_ROW: {
  92249. SrcList *pSrcList = pNC->pSrcList;
  92250. struct SrcList_item *pItem;
  92251. assert( pSrcList && pSrcList->nSrc==1 );
  92252. pItem = pSrcList->a;
  92253. assert( HasRowid(pItem->pTab) && pItem->pTab->pSelect==0 );
  92254. pExpr->op = TK_COLUMN;
  92255. pExpr->y.pTab = pItem->pTab;
  92256. pExpr->iTable = pItem->iCursor;
  92257. pExpr->iColumn = -1;
  92258. pExpr->affExpr = SQLITE_AFF_INTEGER;
  92259. break;
  92260. }
  92261. #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT)
  92262. && !defined(SQLITE_OMIT_SUBQUERY) */
  92263. /* A column name: ID
  92264. ** Or table name and column name: ID.ID
  92265. ** Or a database, table and column: ID.ID.ID
  92266. **
  92267. ** The TK_ID and TK_OUT cases are combined so that there will only
  92268. ** be one call to lookupName(). Then the compiler will in-line
  92269. ** lookupName() for a size reduction and performance increase.
  92270. */
  92271. case TK_ID:
  92272. case TK_DOT: {
  92273. const char *zColumn;
  92274. const char *zTable;
  92275. const char *zDb;
  92276. Expr *pRight;
  92277. if( pExpr->op==TK_ID ){
  92278. zDb = 0;
  92279. zTable = 0;
  92280. zColumn = pExpr->u.zToken;
  92281. }else{
  92282. Expr *pLeft = pExpr->pLeft;
  92283. testcase( pNC->ncFlags & NC_IdxExpr );
  92284. testcase( pNC->ncFlags & NC_GenCol );
  92285. sqlite3ResolveNotValid(pParse, pNC, "the \".\" operator",
  92286. NC_IdxExpr|NC_GenCol, 0);
  92287. pRight = pExpr->pRight;
  92288. if( pRight->op==TK_ID ){
  92289. zDb = 0;
  92290. }else{
  92291. assert( pRight->op==TK_DOT );
  92292. zDb = pLeft->u.zToken;
  92293. pLeft = pRight->pLeft;
  92294. pRight = pRight->pRight;
  92295. }
  92296. zTable = pLeft->u.zToken;
  92297. zColumn = pRight->u.zToken;
  92298. if( IN_RENAME_OBJECT ){
  92299. sqlite3RenameTokenRemap(pParse, (void*)pExpr, (void*)pRight);
  92300. sqlite3RenameTokenRemap(pParse, (void*)&pExpr->y.pTab, (void*)pLeft);
  92301. }
  92302. }
  92303. return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
  92304. }
  92305. /* Resolve function names
  92306. */
  92307. case TK_FUNCTION: {
  92308. ExprList *pList = pExpr->x.pList; /* The argument list */
  92309. int n = pList ? pList->nExpr : 0; /* Number of arguments */
  92310. int no_such_func = 0; /* True if no such function exists */
  92311. int wrong_num_args = 0; /* True if wrong number of arguments */
  92312. int is_agg = 0; /* True if is an aggregate function */
  92313. int nId; /* Number of characters in function name */
  92314. const char *zId; /* The function name. */
  92315. FuncDef *pDef; /* Information about the function */
  92316. u8 enc = ENC(pParse->db); /* The database encoding */
  92317. int savedAllowFlags = (pNC->ncFlags & (NC_AllowAgg | NC_AllowWin));
  92318. #ifndef SQLITE_OMIT_WINDOWFUNC
  92319. Window *pWin = (IsWindowFunc(pExpr) ? pExpr->y.pWin : 0);
  92320. #endif
  92321. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  92322. zId = pExpr->u.zToken;
  92323. nId = sqlite3Strlen30(zId);
  92324. pDef = sqlite3FindFunction(pParse->db, zId, n, enc, 0);
  92325. if( pDef==0 ){
  92326. pDef = sqlite3FindFunction(pParse->db, zId, -2, enc, 0);
  92327. if( pDef==0 ){
  92328. no_such_func = 1;
  92329. }else{
  92330. wrong_num_args = 1;
  92331. }
  92332. }else{
  92333. is_agg = pDef->xFinalize!=0;
  92334. if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
  92335. ExprSetProperty(pExpr, EP_Unlikely);
  92336. if( n==2 ){
  92337. pExpr->iTable = exprProbability(pList->a[1].pExpr);
  92338. if( pExpr->iTable<0 ){
  92339. sqlite3ErrorMsg(pParse,
  92340. "second argument to likelihood() must be a "
  92341. "constant between 0.0 and 1.0");
  92342. pNC->nErr++;
  92343. }
  92344. }else{
  92345. /* EVIDENCE-OF: R-61304-29449 The unlikely(X) function is
  92346. ** equivalent to likelihood(X, 0.0625).
  92347. ** EVIDENCE-OF: R-01283-11636 The unlikely(X) function is
  92348. ** short-hand for likelihood(X,0.0625).
  92349. ** EVIDENCE-OF: R-36850-34127 The likely(X) function is short-hand
  92350. ** for likelihood(X,0.9375).
  92351. ** EVIDENCE-OF: R-53436-40973 The likely(X) function is equivalent
  92352. ** to likelihood(X,0.9375). */
  92353. /* TUNING: unlikely() probability is 0.0625. likely() is 0.9375 */
  92354. pExpr->iTable = pDef->zName[0]=='u' ? 8388608 : 125829120;
  92355. }
  92356. }
  92357. #ifndef SQLITE_OMIT_AUTHORIZATION
  92358. {
  92359. int auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0,pDef->zName,0);
  92360. if( auth!=SQLITE_OK ){
  92361. if( auth==SQLITE_DENY ){
  92362. sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
  92363. pDef->zName);
  92364. pNC->nErr++;
  92365. }
  92366. pExpr->op = TK_NULL;
  92367. return WRC_Prune;
  92368. }
  92369. }
  92370. #endif
  92371. if( pDef->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG) ){
  92372. /* For the purposes of the EP_ConstFunc flag, date and time
  92373. ** functions and other functions that change slowly are considered
  92374. ** constant because they are constant for the duration of one query.
  92375. ** This allows them to be factored out of inner loops. */
  92376. ExprSetProperty(pExpr,EP_ConstFunc);
  92377. }
  92378. if( (pDef->funcFlags & SQLITE_FUNC_CONSTANT)==0 ){
  92379. /* Clearly non-deterministic functions like random(), but also
  92380. ** date/time functions that use 'now', and other functions like
  92381. ** sqlite_version() that might change over time cannot be used
  92382. ** in an index or generated column. Curiously, they can be used
  92383. ** in a CHECK constraint. SQLServer, MySQL, and PostgreSQL all
  92384. ** all this. */
  92385. sqlite3ResolveNotValid(pParse, pNC, "non-deterministic functions",
  92386. NC_IdxExpr|NC_PartIdx|NC_GenCol, 0);
  92387. }else{
  92388. assert( (NC_SelfRef & 0xff)==NC_SelfRef ); /* Must fit in 8 bits */
  92389. pExpr->op2 = pNC->ncFlags & NC_SelfRef;
  92390. if( pNC->ncFlags & NC_FromDDL ) ExprSetProperty(pExpr, EP_FromDDL);
  92391. }
  92392. if( (pDef->funcFlags & SQLITE_FUNC_INTERNAL)!=0
  92393. && pParse->nested==0
  92394. && (pParse->db->mDbFlags & DBFLAG_InternalFunc)==0
  92395. ){
  92396. /* Internal-use-only functions are disallowed unless the
  92397. ** SQL is being compiled using sqlite3NestedParse() or
  92398. ** the SQLITE_TESTCTRL_INTERNAL_FUNCTIONS test-control has be
  92399. ** used to activate internal functionsn for testing purposes */
  92400. no_such_func = 1;
  92401. pDef = 0;
  92402. }else
  92403. if( (pDef->funcFlags & (SQLITE_FUNC_DIRECT|SQLITE_FUNC_UNSAFE))!=0
  92404. && !IN_RENAME_OBJECT
  92405. ){
  92406. sqlite3ExprFunctionUsable(pParse, pExpr, pDef);
  92407. }
  92408. }
  92409. if( 0==IN_RENAME_OBJECT ){
  92410. #ifndef SQLITE_OMIT_WINDOWFUNC
  92411. assert( is_agg==0 || (pDef->funcFlags & SQLITE_FUNC_MINMAX)
  92412. || (pDef->xValue==0 && pDef->xInverse==0)
  92413. || (pDef->xValue && pDef->xInverse && pDef->xSFunc && pDef->xFinalize)
  92414. );
  92415. if( pDef && pDef->xValue==0 && pWin ){
  92416. sqlite3ErrorMsg(pParse,
  92417. "%.*s() may not be used as a window function", nId, zId
  92418. );
  92419. pNC->nErr++;
  92420. }else if(
  92421. (is_agg && (pNC->ncFlags & NC_AllowAgg)==0)
  92422. || (is_agg && (pDef->funcFlags&SQLITE_FUNC_WINDOW) && !pWin)
  92423. || (is_agg && pWin && (pNC->ncFlags & NC_AllowWin)==0)
  92424. ){
  92425. const char *zType;
  92426. if( (pDef->funcFlags & SQLITE_FUNC_WINDOW) || pWin ){
  92427. zType = "window";
  92428. }else{
  92429. zType = "aggregate";
  92430. }
  92431. sqlite3ErrorMsg(pParse, "misuse of %s function %.*s()",zType,nId,zId);
  92432. pNC->nErr++;
  92433. is_agg = 0;
  92434. }
  92435. #else
  92436. if( (is_agg && (pNC->ncFlags & NC_AllowAgg)==0) ){
  92437. sqlite3ErrorMsg(pParse,"misuse of aggregate function %.*s()",nId,zId);
  92438. pNC->nErr++;
  92439. is_agg = 0;
  92440. }
  92441. #endif
  92442. else if( no_such_func && pParse->db->init.busy==0
  92443. #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
  92444. && pParse->explain==0
  92445. #endif
  92446. ){
  92447. sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
  92448. pNC->nErr++;
  92449. }else if( wrong_num_args ){
  92450. sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
  92451. nId, zId);
  92452. pNC->nErr++;
  92453. }
  92454. #ifndef SQLITE_OMIT_WINDOWFUNC
  92455. else if( is_agg==0 && ExprHasProperty(pExpr, EP_WinFunc) ){
  92456. sqlite3ErrorMsg(pParse,
  92457. "FILTER may not be used with non-aggregate %.*s()",
  92458. nId, zId
  92459. );
  92460. pNC->nErr++;
  92461. }
  92462. #endif
  92463. if( is_agg ){
  92464. /* Window functions may not be arguments of aggregate functions.
  92465. ** Or arguments of other window functions. But aggregate functions
  92466. ** may be arguments for window functions. */
  92467. #ifndef SQLITE_OMIT_WINDOWFUNC
  92468. pNC->ncFlags &= ~(NC_AllowWin | (!pWin ? NC_AllowAgg : 0));
  92469. #else
  92470. pNC->ncFlags &= ~NC_AllowAgg;
  92471. #endif
  92472. }
  92473. }
  92474. #ifndef SQLITE_OMIT_WINDOWFUNC
  92475. else if( ExprHasProperty(pExpr, EP_WinFunc) ){
  92476. is_agg = 1;
  92477. }
  92478. #endif
  92479. sqlite3WalkExprList(pWalker, pList);
  92480. if( is_agg ){
  92481. #ifndef SQLITE_OMIT_WINDOWFUNC
  92482. if( pWin ){
  92483. Select *pSel = pNC->pWinSelect;
  92484. assert( pWin==pExpr->y.pWin );
  92485. if( IN_RENAME_OBJECT==0 ){
  92486. sqlite3WindowUpdate(pParse, pSel ? pSel->pWinDefn : 0, pWin, pDef);
  92487. }
  92488. sqlite3WalkExprList(pWalker, pWin->pPartition);
  92489. sqlite3WalkExprList(pWalker, pWin->pOrderBy);
  92490. sqlite3WalkExpr(pWalker, pWin->pFilter);
  92491. sqlite3WindowLink(pSel, pWin);
  92492. pNC->ncFlags |= NC_HasWin;
  92493. }else
  92494. #endif /* SQLITE_OMIT_WINDOWFUNC */
  92495. {
  92496. NameContext *pNC2 = pNC;
  92497. pExpr->op = TK_AGG_FUNCTION;
  92498. pExpr->op2 = 0;
  92499. #ifndef SQLITE_OMIT_WINDOWFUNC
  92500. if( ExprHasProperty(pExpr, EP_WinFunc) ){
  92501. sqlite3WalkExpr(pWalker, pExpr->y.pWin->pFilter);
  92502. }
  92503. #endif
  92504. while( pNC2 && !sqlite3FunctionUsesThisSrc(pExpr, pNC2->pSrcList) ){
  92505. pExpr->op2++;
  92506. pNC2 = pNC2->pNext;
  92507. }
  92508. assert( pDef!=0 || IN_RENAME_OBJECT );
  92509. if( pNC2 && pDef ){
  92510. assert( SQLITE_FUNC_MINMAX==NC_MinMaxAgg );
  92511. testcase( (pDef->funcFlags & SQLITE_FUNC_MINMAX)!=0 );
  92512. pNC2->ncFlags |= NC_HasAgg | (pDef->funcFlags & SQLITE_FUNC_MINMAX);
  92513. }
  92514. }
  92515. pNC->ncFlags |= savedAllowFlags;
  92516. }
  92517. /* FIX ME: Compute pExpr->affinity based on the expected return
  92518. ** type of the function
  92519. */
  92520. return WRC_Prune;
  92521. }
  92522. #ifndef SQLITE_OMIT_SUBQUERY
  92523. case TK_SELECT:
  92524. case TK_EXISTS: testcase( pExpr->op==TK_EXISTS );
  92525. #endif
  92526. case TK_IN: {
  92527. testcase( pExpr->op==TK_IN );
  92528. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  92529. int nRef = pNC->nRef;
  92530. testcase( pNC->ncFlags & NC_IsCheck );
  92531. testcase( pNC->ncFlags & NC_PartIdx );
  92532. testcase( pNC->ncFlags & NC_IdxExpr );
  92533. testcase( pNC->ncFlags & NC_GenCol );
  92534. sqlite3ResolveNotValid(pParse, pNC, "subqueries",
  92535. NC_IsCheck|NC_PartIdx|NC_IdxExpr|NC_GenCol, pExpr);
  92536. sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
  92537. assert( pNC->nRef>=nRef );
  92538. if( nRef!=pNC->nRef ){
  92539. ExprSetProperty(pExpr, EP_VarSelect);
  92540. pNC->ncFlags |= NC_VarSelect;
  92541. }
  92542. }
  92543. break;
  92544. }
  92545. case TK_VARIABLE: {
  92546. testcase( pNC->ncFlags & NC_IsCheck );
  92547. testcase( pNC->ncFlags & NC_PartIdx );
  92548. testcase( pNC->ncFlags & NC_IdxExpr );
  92549. testcase( pNC->ncFlags & NC_GenCol );
  92550. sqlite3ResolveNotValid(pParse, pNC, "parameters",
  92551. NC_IsCheck|NC_PartIdx|NC_IdxExpr|NC_GenCol, pExpr);
  92552. break;
  92553. }
  92554. case TK_IS:
  92555. case TK_ISNOT: {
  92556. Expr *pRight = sqlite3ExprSkipCollateAndLikely(pExpr->pRight);
  92557. assert( !ExprHasProperty(pExpr, EP_Reduced) );
  92558. /* Handle special cases of "x IS TRUE", "x IS FALSE", "x IS NOT TRUE",
  92559. ** and "x IS NOT FALSE". */
  92560. if( pRight && pRight->op==TK_ID ){
  92561. int rc = resolveExprStep(pWalker, pRight);
  92562. if( rc==WRC_Abort ) return WRC_Abort;
  92563. if( pRight->op==TK_TRUEFALSE ){
  92564. pExpr->op2 = pExpr->op;
  92565. pExpr->op = TK_TRUTH;
  92566. return WRC_Continue;
  92567. }
  92568. }
  92569. /* Fall thru */
  92570. }
  92571. case TK_BETWEEN:
  92572. case TK_EQ:
  92573. case TK_NE:
  92574. case TK_LT:
  92575. case TK_LE:
  92576. case TK_GT:
  92577. case TK_GE: {
  92578. int nLeft, nRight;
  92579. if( pParse->db->mallocFailed ) break;
  92580. assert( pExpr->pLeft!=0 );
  92581. nLeft = sqlite3ExprVectorSize(pExpr->pLeft);
  92582. if( pExpr->op==TK_BETWEEN ){
  92583. nRight = sqlite3ExprVectorSize(pExpr->x.pList->a[0].pExpr);
  92584. if( nRight==nLeft ){
  92585. nRight = sqlite3ExprVectorSize(pExpr->x.pList->a[1].pExpr);
  92586. }
  92587. }else{
  92588. assert( pExpr->pRight!=0 );
  92589. nRight = sqlite3ExprVectorSize(pExpr->pRight);
  92590. }
  92591. if( nLeft!=nRight ){
  92592. testcase( pExpr->op==TK_EQ );
  92593. testcase( pExpr->op==TK_NE );
  92594. testcase( pExpr->op==TK_LT );
  92595. testcase( pExpr->op==TK_LE );
  92596. testcase( pExpr->op==TK_GT );
  92597. testcase( pExpr->op==TK_GE );
  92598. testcase( pExpr->op==TK_IS );
  92599. testcase( pExpr->op==TK_ISNOT );
  92600. testcase( pExpr->op==TK_BETWEEN );
  92601. sqlite3ErrorMsg(pParse, "row value misused");
  92602. }
  92603. break;
  92604. }
  92605. }
  92606. return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
  92607. }
  92608. /*
  92609. ** pEList is a list of expressions which are really the result set of the
  92610. ** a SELECT statement. pE is a term in an ORDER BY or GROUP BY clause.
  92611. ** This routine checks to see if pE is a simple identifier which corresponds
  92612. ** to the AS-name of one of the terms of the expression list. If it is,
  92613. ** this routine return an integer between 1 and N where N is the number of
  92614. ** elements in pEList, corresponding to the matching entry. If there is
  92615. ** no match, or if pE is not a simple identifier, then this routine
  92616. ** return 0.
  92617. **
  92618. ** pEList has been resolved. pE has not.
  92619. */
  92620. static int resolveAsName(
  92621. Parse *pParse, /* Parsing context for error messages */
  92622. ExprList *pEList, /* List of expressions to scan */
  92623. Expr *pE /* Expression we are trying to match */
  92624. ){
  92625. int i; /* Loop counter */
  92626. UNUSED_PARAMETER(pParse);
  92627. if( pE->op==TK_ID ){
  92628. char *zCol = pE->u.zToken;
  92629. for(i=0; i<pEList->nExpr; i++){
  92630. if( pEList->a[i].eEName==ENAME_NAME
  92631. && sqlite3_stricmp(pEList->a[i].zEName, zCol)==0
  92632. ){
  92633. return i+1;
  92634. }
  92635. }
  92636. }
  92637. return 0;
  92638. }
  92639. /*
  92640. ** pE is a pointer to an expression which is a single term in the
  92641. ** ORDER BY of a compound SELECT. The expression has not been
  92642. ** name resolved.
  92643. **
  92644. ** At the point this routine is called, we already know that the
  92645. ** ORDER BY term is not an integer index into the result set. That
  92646. ** case is handled by the calling routine.
  92647. **
  92648. ** Attempt to match pE against result set columns in the left-most
  92649. ** SELECT statement. Return the index i of the matching column,
  92650. ** as an indication to the caller that it should sort by the i-th column.
  92651. ** The left-most column is 1. In other words, the value returned is the
  92652. ** same integer value that would be used in the SQL statement to indicate
  92653. ** the column.
  92654. **
  92655. ** If there is no match, return 0. Return -1 if an error occurs.
  92656. */
  92657. static int resolveOrderByTermToExprList(
  92658. Parse *pParse, /* Parsing context for error messages */
  92659. Select *pSelect, /* The SELECT statement with the ORDER BY clause */
  92660. Expr *pE /* The specific ORDER BY term */
  92661. ){
  92662. int i; /* Loop counter */
  92663. ExprList *pEList; /* The columns of the result set */
  92664. NameContext nc; /* Name context for resolving pE */
  92665. sqlite3 *db; /* Database connection */
  92666. int rc; /* Return code from subprocedures */
  92667. u8 savedSuppErr; /* Saved value of db->suppressErr */
  92668. assert( sqlite3ExprIsInteger(pE, &i)==0 );
  92669. pEList = pSelect->pEList;
  92670. /* Resolve all names in the ORDER BY term expression
  92671. */
  92672. memset(&nc, 0, sizeof(nc));
  92673. nc.pParse = pParse;
  92674. nc.pSrcList = pSelect->pSrc;
  92675. nc.uNC.pEList = pEList;
  92676. nc.ncFlags = NC_AllowAgg|NC_UEList;
  92677. nc.nErr = 0;
  92678. db = pParse->db;
  92679. savedSuppErr = db->suppressErr;
  92680. if( IN_RENAME_OBJECT==0 ) db->suppressErr = 1;
  92681. rc = sqlite3ResolveExprNames(&nc, pE);
  92682. db->suppressErr = savedSuppErr;
  92683. if( rc ) return 0;
  92684. /* Try to match the ORDER BY expression against an expression
  92685. ** in the result set. Return an 1-based index of the matching
  92686. ** result-set entry.
  92687. */
  92688. for(i=0; i<pEList->nExpr; i++){
  92689. if( sqlite3ExprCompare(0, pEList->a[i].pExpr, pE, -1)<2 ){
  92690. return i+1;
  92691. }
  92692. }
  92693. /* If no match, return 0. */
  92694. return 0;
  92695. }
  92696. /*
  92697. ** Generate an ORDER BY or GROUP BY term out-of-range error.
  92698. */
  92699. static void resolveOutOfRangeError(
  92700. Parse *pParse, /* The error context into which to write the error */
  92701. const char *zType, /* "ORDER" or "GROUP" */
  92702. int i, /* The index (1-based) of the term out of range */
  92703. int mx /* Largest permissible value of i */
  92704. ){
  92705. sqlite3ErrorMsg(pParse,
  92706. "%r %s BY term out of range - should be "
  92707. "between 1 and %d", i, zType, mx);
  92708. }
  92709. /*
  92710. ** Analyze the ORDER BY clause in a compound SELECT statement. Modify
  92711. ** each term of the ORDER BY clause is a constant integer between 1
  92712. ** and N where N is the number of columns in the compound SELECT.
  92713. **
  92714. ** ORDER BY terms that are already an integer between 1 and N are
  92715. ** unmodified. ORDER BY terms that are integers outside the range of
  92716. ** 1 through N generate an error. ORDER BY terms that are expressions
  92717. ** are matched against result set expressions of compound SELECT
  92718. ** beginning with the left-most SELECT and working toward the right.
  92719. ** At the first match, the ORDER BY expression is transformed into
  92720. ** the integer column number.
  92721. **
  92722. ** Return the number of errors seen.
  92723. */
  92724. static int resolveCompoundOrderBy(
  92725. Parse *pParse, /* Parsing context. Leave error messages here */
  92726. Select *pSelect /* The SELECT statement containing the ORDER BY */
  92727. ){
  92728. int i;
  92729. ExprList *pOrderBy;
  92730. ExprList *pEList;
  92731. sqlite3 *db;
  92732. int moreToDo = 1;
  92733. pOrderBy = pSelect->pOrderBy;
  92734. if( pOrderBy==0 ) return 0;
  92735. db = pParse->db;
  92736. if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  92737. sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
  92738. return 1;
  92739. }
  92740. for(i=0; i<pOrderBy->nExpr; i++){
  92741. pOrderBy->a[i].done = 0;
  92742. }
  92743. pSelect->pNext = 0;
  92744. while( pSelect->pPrior ){
  92745. pSelect->pPrior->pNext = pSelect;
  92746. pSelect = pSelect->pPrior;
  92747. }
  92748. while( pSelect && moreToDo ){
  92749. struct ExprList_item *pItem;
  92750. moreToDo = 0;
  92751. pEList = pSelect->pEList;
  92752. assert( pEList!=0 );
  92753. for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
  92754. int iCol = -1;
  92755. Expr *pE, *pDup;
  92756. if( pItem->done ) continue;
  92757. pE = sqlite3ExprSkipCollateAndLikely(pItem->pExpr);
  92758. if( sqlite3ExprIsInteger(pE, &iCol) ){
  92759. if( iCol<=0 || iCol>pEList->nExpr ){
  92760. resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
  92761. return 1;
  92762. }
  92763. }else{
  92764. iCol = resolveAsName(pParse, pEList, pE);
  92765. if( iCol==0 ){
  92766. /* Now test if expression pE matches one of the values returned
  92767. ** by pSelect. In the usual case this is done by duplicating the
  92768. ** expression, resolving any symbols in it, and then comparing
  92769. ** it against each expression returned by the SELECT statement.
  92770. ** Once the comparisons are finished, the duplicate expression
  92771. ** is deleted.
  92772. **
  92773. ** Or, if this is running as part of an ALTER TABLE operation,
  92774. ** resolve the symbols in the actual expression, not a duplicate.
  92775. ** And, if one of the comparisons is successful, leave the expression
  92776. ** as is instead of transforming it to an integer as in the usual
  92777. ** case. This allows the code in alter.c to modify column
  92778. ** refererences within the ORDER BY expression as required. */
  92779. if( IN_RENAME_OBJECT ){
  92780. pDup = pE;
  92781. }else{
  92782. pDup = sqlite3ExprDup(db, pE, 0);
  92783. }
  92784. if( !db->mallocFailed ){
  92785. assert(pDup);
  92786. iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
  92787. }
  92788. if( !IN_RENAME_OBJECT ){
  92789. sqlite3ExprDelete(db, pDup);
  92790. }
  92791. }
  92792. }
  92793. if( iCol>0 ){
  92794. /* Convert the ORDER BY term into an integer column number iCol,
  92795. ** taking care to preserve the COLLATE clause if it exists */
  92796. if( !IN_RENAME_OBJECT ){
  92797. Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
  92798. if( pNew==0 ) return 1;
  92799. pNew->flags |= EP_IntValue;
  92800. pNew->u.iValue = iCol;
  92801. if( pItem->pExpr==pE ){
  92802. pItem->pExpr = pNew;
  92803. }else{
  92804. Expr *pParent = pItem->pExpr;
  92805. assert( pParent->op==TK_COLLATE );
  92806. while( pParent->pLeft->op==TK_COLLATE ) pParent = pParent->pLeft;
  92807. assert( pParent->pLeft==pE );
  92808. pParent->pLeft = pNew;
  92809. }
  92810. sqlite3ExprDelete(db, pE);
  92811. pItem->u.x.iOrderByCol = (u16)iCol;
  92812. }
  92813. pItem->done = 1;
  92814. }else{
  92815. moreToDo = 1;
  92816. }
  92817. }
  92818. pSelect = pSelect->pNext;
  92819. }
  92820. for(i=0; i<pOrderBy->nExpr; i++){
  92821. if( pOrderBy->a[i].done==0 ){
  92822. sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
  92823. "column in the result set", i+1);
  92824. return 1;
  92825. }
  92826. }
  92827. return 0;
  92828. }
  92829. /*
  92830. ** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
  92831. ** the SELECT statement pSelect. If any term is reference to a
  92832. ** result set expression (as determined by the ExprList.a.u.x.iOrderByCol
  92833. ** field) then convert that term into a copy of the corresponding result set
  92834. ** column.
  92835. **
  92836. ** If any errors are detected, add an error message to pParse and
  92837. ** return non-zero. Return zero if no errors are seen.
  92838. */
  92839. SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(
  92840. Parse *pParse, /* Parsing context. Leave error messages here */
  92841. Select *pSelect, /* The SELECT statement containing the clause */
  92842. ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */
  92843. const char *zType /* "ORDER" or "GROUP" */
  92844. ){
  92845. int i;
  92846. sqlite3 *db = pParse->db;
  92847. ExprList *pEList;
  92848. struct ExprList_item *pItem;
  92849. if( pOrderBy==0 || pParse->db->mallocFailed || IN_RENAME_OBJECT ) return 0;
  92850. if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  92851. sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
  92852. return 1;
  92853. }
  92854. pEList = pSelect->pEList;
  92855. assert( pEList!=0 ); /* sqlite3SelectNew() guarantees this */
  92856. for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
  92857. if( pItem->u.x.iOrderByCol ){
  92858. if( pItem->u.x.iOrderByCol>pEList->nExpr ){
  92859. resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
  92860. return 1;
  92861. }
  92862. resolveAlias(pParse, pEList, pItem->u.x.iOrderByCol-1, pItem->pExpr,
  92863. zType,0);
  92864. }
  92865. }
  92866. return 0;
  92867. }
  92868. #ifndef SQLITE_OMIT_WINDOWFUNC
  92869. /*
  92870. ** Walker callback for windowRemoveExprFromSelect().
  92871. */
  92872. static int resolveRemoveWindowsCb(Walker *pWalker, Expr *pExpr){
  92873. UNUSED_PARAMETER(pWalker);
  92874. if( ExprHasProperty(pExpr, EP_WinFunc) ){
  92875. Window *pWin = pExpr->y.pWin;
  92876. sqlite3WindowUnlinkFromSelect(pWin);
  92877. }
  92878. return WRC_Continue;
  92879. }
  92880. /*
  92881. ** Remove any Window objects owned by the expression pExpr from the
  92882. ** Select.pWin list of Select object pSelect.
  92883. */
  92884. static void windowRemoveExprFromSelect(Select *pSelect, Expr *pExpr){
  92885. if( pSelect->pWin ){
  92886. Walker sWalker;
  92887. memset(&sWalker, 0, sizeof(Walker));
  92888. sWalker.xExprCallback = resolveRemoveWindowsCb;
  92889. sWalker.u.pSelect = pSelect;
  92890. sqlite3WalkExpr(&sWalker, pExpr);
  92891. }
  92892. }
  92893. #else
  92894. # define windowRemoveExprFromSelect(a, b)
  92895. #endif /* SQLITE_OMIT_WINDOWFUNC */
  92896. /*
  92897. ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
  92898. ** The Name context of the SELECT statement is pNC. zType is either
  92899. ** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
  92900. **
  92901. ** This routine resolves each term of the clause into an expression.
  92902. ** If the order-by term is an integer I between 1 and N (where N is the
  92903. ** number of columns in the result set of the SELECT) then the expression
  92904. ** in the resolution is a copy of the I-th result-set expression. If
  92905. ** the order-by term is an identifier that corresponds to the AS-name of
  92906. ** a result-set expression, then the term resolves to a copy of the
  92907. ** result-set expression. Otherwise, the expression is resolved in
  92908. ** the usual way - using sqlite3ResolveExprNames().
  92909. **
  92910. ** This routine returns the number of errors. If errors occur, then
  92911. ** an appropriate error message might be left in pParse. (OOM errors
  92912. ** excepted.)
  92913. */
  92914. static int resolveOrderGroupBy(
  92915. NameContext *pNC, /* The name context of the SELECT statement */
  92916. Select *pSelect, /* The SELECT statement holding pOrderBy */
  92917. ExprList *pOrderBy, /* An ORDER BY or GROUP BY clause to resolve */
  92918. const char *zType /* Either "ORDER" or "GROUP", as appropriate */
  92919. ){
  92920. int i, j; /* Loop counters */
  92921. int iCol; /* Column number */
  92922. struct ExprList_item *pItem; /* A term of the ORDER BY clause */
  92923. Parse *pParse; /* Parsing context */
  92924. int nResult; /* Number of terms in the result set */
  92925. if( pOrderBy==0 ) return 0;
  92926. nResult = pSelect->pEList->nExpr;
  92927. pParse = pNC->pParse;
  92928. for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
  92929. Expr *pE = pItem->pExpr;
  92930. Expr *pE2 = sqlite3ExprSkipCollateAndLikely(pE);
  92931. if( zType[0]!='G' ){
  92932. iCol = resolveAsName(pParse, pSelect->pEList, pE2);
  92933. if( iCol>0 ){
  92934. /* If an AS-name match is found, mark this ORDER BY column as being
  92935. ** a copy of the iCol-th result-set column. The subsequent call to
  92936. ** sqlite3ResolveOrderGroupBy() will convert the expression to a
  92937. ** copy of the iCol-th result-set expression. */
  92938. pItem->u.x.iOrderByCol = (u16)iCol;
  92939. continue;
  92940. }
  92941. }
  92942. if( sqlite3ExprIsInteger(pE2, &iCol) ){
  92943. /* The ORDER BY term is an integer constant. Again, set the column
  92944. ** number so that sqlite3ResolveOrderGroupBy() will convert the
  92945. ** order-by term to a copy of the result-set expression */
  92946. if( iCol<1 || iCol>0xffff ){
  92947. resolveOutOfRangeError(pParse, zType, i+1, nResult);
  92948. return 1;
  92949. }
  92950. pItem->u.x.iOrderByCol = (u16)iCol;
  92951. continue;
  92952. }
  92953. /* Otherwise, treat the ORDER BY term as an ordinary expression */
  92954. pItem->u.x.iOrderByCol = 0;
  92955. if( sqlite3ResolveExprNames(pNC, pE) ){
  92956. return 1;
  92957. }
  92958. for(j=0; j<pSelect->pEList->nExpr; j++){
  92959. if( sqlite3ExprCompare(0, pE, pSelect->pEList->a[j].pExpr, -1)==0 ){
  92960. /* Since this expresion is being changed into a reference
  92961. ** to an identical expression in the result set, remove all Window
  92962. ** objects belonging to the expression from the Select.pWin list. */
  92963. windowRemoveExprFromSelect(pSelect, pE);
  92964. pItem->u.x.iOrderByCol = j+1;
  92965. }
  92966. }
  92967. }
  92968. return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
  92969. }
  92970. /*
  92971. ** Resolve names in the SELECT statement p and all of its descendants.
  92972. */
  92973. static int resolveSelectStep(Walker *pWalker, Select *p){
  92974. NameContext *pOuterNC; /* Context that contains this SELECT */
  92975. NameContext sNC; /* Name context of this SELECT */
  92976. int isCompound; /* True if p is a compound select */
  92977. int nCompound; /* Number of compound terms processed so far */
  92978. Parse *pParse; /* Parsing context */
  92979. int i; /* Loop counter */
  92980. ExprList *pGroupBy; /* The GROUP BY clause */
  92981. Select *pLeftmost; /* Left-most of SELECT of a compound */
  92982. sqlite3 *db; /* Database connection */
  92983. assert( p!=0 );
  92984. if( p->selFlags & SF_Resolved ){
  92985. return WRC_Prune;
  92986. }
  92987. pOuterNC = pWalker->u.pNC;
  92988. pParse = pWalker->pParse;
  92989. db = pParse->db;
  92990. /* Normally sqlite3SelectExpand() will be called first and will have
  92991. ** already expanded this SELECT. However, if this is a subquery within
  92992. ** an expression, sqlite3ResolveExprNames() will be called without a
  92993. ** prior call to sqlite3SelectExpand(). When that happens, let
  92994. ** sqlite3SelectPrep() do all of the processing for this SELECT.
  92995. ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
  92996. ** this routine in the correct order.
  92997. */
  92998. if( (p->selFlags & SF_Expanded)==0 ){
  92999. sqlite3SelectPrep(pParse, p, pOuterNC);
  93000. return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
  93001. }
  93002. isCompound = p->pPrior!=0;
  93003. nCompound = 0;
  93004. pLeftmost = p;
  93005. while( p ){
  93006. assert( (p->selFlags & SF_Expanded)!=0 );
  93007. assert( (p->selFlags & SF_Resolved)==0 );
  93008. p->selFlags |= SF_Resolved;
  93009. /* Resolve the expressions in the LIMIT and OFFSET clauses. These
  93010. ** are not allowed to refer to any names, so pass an empty NameContext.
  93011. */
  93012. memset(&sNC, 0, sizeof(sNC));
  93013. sNC.pParse = pParse;
  93014. sNC.pWinSelect = p;
  93015. if( sqlite3ResolveExprNames(&sNC, p->pLimit) ){
  93016. return WRC_Abort;
  93017. }
  93018. /* If the SF_Converted flags is set, then this Select object was
  93019. ** was created by the convertCompoundSelectToSubquery() function.
  93020. ** In this case the ORDER BY clause (p->pOrderBy) should be resolved
  93021. ** as if it were part of the sub-query, not the parent. This block
  93022. ** moves the pOrderBy down to the sub-query. It will be moved back
  93023. ** after the names have been resolved. */
  93024. if( p->selFlags & SF_Converted ){
  93025. Select *pSub = p->pSrc->a[0].pSelect;
  93026. assert( p->pSrc->nSrc==1 && p->pOrderBy );
  93027. assert( pSub->pPrior && pSub->pOrderBy==0 );
  93028. pSub->pOrderBy = p->pOrderBy;
  93029. p->pOrderBy = 0;
  93030. }
  93031. /* Recursively resolve names in all subqueries
  93032. */
  93033. for(i=0; i<p->pSrc->nSrc; i++){
  93034. struct SrcList_item *pItem = &p->pSrc->a[i];
  93035. if( pItem->pSelect && (pItem->pSelect->selFlags & SF_Resolved)==0 ){
  93036. NameContext *pNC; /* Used to iterate name contexts */
  93037. int nRef = 0; /* Refcount for pOuterNC and outer contexts */
  93038. const char *zSavedContext = pParse->zAuthContext;
  93039. /* Count the total number of references to pOuterNC and all of its
  93040. ** parent contexts. After resolving references to expressions in
  93041. ** pItem->pSelect, check if this value has changed. If so, then
  93042. ** SELECT statement pItem->pSelect must be correlated. Set the
  93043. ** pItem->fg.isCorrelated flag if this is the case. */
  93044. for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef += pNC->nRef;
  93045. if( pItem->zName ) pParse->zAuthContext = pItem->zName;
  93046. sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
  93047. pParse->zAuthContext = zSavedContext;
  93048. if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
  93049. for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef -= pNC->nRef;
  93050. assert( pItem->fg.isCorrelated==0 && nRef<=0 );
  93051. pItem->fg.isCorrelated = (nRef!=0);
  93052. }
  93053. }
  93054. /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
  93055. ** resolve the result-set expression list.
  93056. */
  93057. sNC.ncFlags = NC_AllowAgg|NC_AllowWin;
  93058. sNC.pSrcList = p->pSrc;
  93059. sNC.pNext = pOuterNC;
  93060. /* Resolve names in the result set. */
  93061. if( sqlite3ResolveExprListNames(&sNC, p->pEList) ) return WRC_Abort;
  93062. sNC.ncFlags &= ~NC_AllowWin;
  93063. /* If there are no aggregate functions in the result-set, and no GROUP BY
  93064. ** expression, do not allow aggregates in any of the other expressions.
  93065. */
  93066. assert( (p->selFlags & SF_Aggregate)==0 );
  93067. pGroupBy = p->pGroupBy;
  93068. if( pGroupBy || (sNC.ncFlags & NC_HasAgg)!=0 ){
  93069. assert( NC_MinMaxAgg==SF_MinMaxAgg );
  93070. p->selFlags |= SF_Aggregate | (sNC.ncFlags&NC_MinMaxAgg);
  93071. }else{
  93072. sNC.ncFlags &= ~NC_AllowAgg;
  93073. }
  93074. /* If a HAVING clause is present, then there must be a GROUP BY clause.
  93075. */
  93076. if( p->pHaving && !pGroupBy ){
  93077. sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
  93078. return WRC_Abort;
  93079. }
  93080. /* Add the output column list to the name-context before parsing the
  93081. ** other expressions in the SELECT statement. This is so that
  93082. ** expressions in the WHERE clause (etc.) can refer to expressions by
  93083. ** aliases in the result set.
  93084. **
  93085. ** Minor point: If this is the case, then the expression will be
  93086. ** re-evaluated for each reference to it.
  93087. */
  93088. assert( (sNC.ncFlags & (NC_UAggInfo|NC_UUpsert))==0 );
  93089. sNC.uNC.pEList = p->pEList;
  93090. sNC.ncFlags |= NC_UEList;
  93091. if( sqlite3ResolveExprNames(&sNC, p->pHaving) ) return WRC_Abort;
  93092. if( sqlite3ResolveExprNames(&sNC, p->pWhere) ) return WRC_Abort;
  93093. /* Resolve names in table-valued-function arguments */
  93094. for(i=0; i<p->pSrc->nSrc; i++){
  93095. struct SrcList_item *pItem = &p->pSrc->a[i];
  93096. if( pItem->fg.isTabFunc
  93097. && sqlite3ResolveExprListNames(&sNC, pItem->u1.pFuncArg)
  93098. ){
  93099. return WRC_Abort;
  93100. }
  93101. }
  93102. /* The ORDER BY and GROUP BY clauses may not refer to terms in
  93103. ** outer queries
  93104. */
  93105. sNC.pNext = 0;
  93106. sNC.ncFlags |= NC_AllowAgg|NC_AllowWin;
  93107. /* If this is a converted compound query, move the ORDER BY clause from
  93108. ** the sub-query back to the parent query. At this point each term
  93109. ** within the ORDER BY clause has been transformed to an integer value.
  93110. ** These integers will be replaced by copies of the corresponding result
  93111. ** set expressions by the call to resolveOrderGroupBy() below. */
  93112. if( p->selFlags & SF_Converted ){
  93113. Select *pSub = p->pSrc->a[0].pSelect;
  93114. p->pOrderBy = pSub->pOrderBy;
  93115. pSub->pOrderBy = 0;
  93116. }
  93117. /* Process the ORDER BY clause for singleton SELECT statements.
  93118. ** The ORDER BY clause for compounds SELECT statements is handled
  93119. ** below, after all of the result-sets for all of the elements of
  93120. ** the compound have been resolved.
  93121. **
  93122. ** If there is an ORDER BY clause on a term of a compound-select other
  93123. ** than the right-most term, then that is a syntax error. But the error
  93124. ** is not detected until much later, and so we need to go ahead and
  93125. ** resolve those symbols on the incorrect ORDER BY for consistency.
  93126. */
  93127. if( isCompound<=nCompound /* Defer right-most ORDER BY of a compound */
  93128. && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER")
  93129. ){
  93130. return WRC_Abort;
  93131. }
  93132. if( db->mallocFailed ){
  93133. return WRC_Abort;
  93134. }
  93135. sNC.ncFlags &= ~NC_AllowWin;
  93136. /* Resolve the GROUP BY clause. At the same time, make sure
  93137. ** the GROUP BY clause does not contain aggregate functions.
  93138. */
  93139. if( pGroupBy ){
  93140. struct ExprList_item *pItem;
  93141. if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
  93142. return WRC_Abort;
  93143. }
  93144. for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
  93145. if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
  93146. sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
  93147. "the GROUP BY clause");
  93148. return WRC_Abort;
  93149. }
  93150. }
  93151. }
  93152. #ifndef SQLITE_OMIT_WINDOWFUNC
  93153. if( IN_RENAME_OBJECT ){
  93154. Window *pWin;
  93155. for(pWin=p->pWinDefn; pWin; pWin=pWin->pNextWin){
  93156. if( sqlite3ResolveExprListNames(&sNC, pWin->pOrderBy)
  93157. || sqlite3ResolveExprListNames(&sNC, pWin->pPartition)
  93158. ){
  93159. return WRC_Abort;
  93160. }
  93161. }
  93162. }
  93163. #endif
  93164. /* If this is part of a compound SELECT, check that it has the right
  93165. ** number of expressions in the select list. */
  93166. if( p->pNext && p->pEList->nExpr!=p->pNext->pEList->nExpr ){
  93167. sqlite3SelectWrongNumTermsError(pParse, p->pNext);
  93168. return WRC_Abort;
  93169. }
  93170. /* Advance to the next term of the compound
  93171. */
  93172. p = p->pPrior;
  93173. nCompound++;
  93174. }
  93175. /* Resolve the ORDER BY on a compound SELECT after all terms of
  93176. ** the compound have been resolved.
  93177. */
  93178. if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
  93179. return WRC_Abort;
  93180. }
  93181. return WRC_Prune;
  93182. }
  93183. /*
  93184. ** This routine walks an expression tree and resolves references to
  93185. ** table columns and result-set columns. At the same time, do error
  93186. ** checking on function usage and set a flag if any aggregate functions
  93187. ** are seen.
  93188. **
  93189. ** To resolve table columns references we look for nodes (or subtrees) of the
  93190. ** form X.Y.Z or Y.Z or just Z where
  93191. **
  93192. ** X: The name of a database. Ex: "main" or "temp" or
  93193. ** the symbolic name assigned to an ATTACH-ed database.
  93194. **
  93195. ** Y: The name of a table in a FROM clause. Or in a trigger
  93196. ** one of the special names "old" or "new".
  93197. **
  93198. ** Z: The name of a column in table Y.
  93199. **
  93200. ** The node at the root of the subtree is modified as follows:
  93201. **
  93202. ** Expr.op Changed to TK_COLUMN
  93203. ** Expr.pTab Points to the Table object for X.Y
  93204. ** Expr.iColumn The column index in X.Y. -1 for the rowid.
  93205. ** Expr.iTable The VDBE cursor number for X.Y
  93206. **
  93207. **
  93208. ** To resolve result-set references, look for expression nodes of the
  93209. ** form Z (with no X and Y prefix) where the Z matches the right-hand
  93210. ** size of an AS clause in the result-set of a SELECT. The Z expression
  93211. ** is replaced by a copy of the left-hand side of the result-set expression.
  93212. ** Table-name and function resolution occurs on the substituted expression
  93213. ** tree. For example, in:
  93214. **
  93215. ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
  93216. **
  93217. ** The "x" term of the order by is replaced by "a+b" to render:
  93218. **
  93219. ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
  93220. **
  93221. ** Function calls are checked to make sure that the function is
  93222. ** defined and that the correct number of arguments are specified.
  93223. ** If the function is an aggregate function, then the NC_HasAgg flag is
  93224. ** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
  93225. ** If an expression contains aggregate functions then the EP_Agg
  93226. ** property on the expression is set.
  93227. **
  93228. ** An error message is left in pParse if anything is amiss. The number
  93229. ** if errors is returned.
  93230. */
  93231. SQLITE_PRIVATE int sqlite3ResolveExprNames(
  93232. NameContext *pNC, /* Namespace to resolve expressions in. */
  93233. Expr *pExpr /* The expression to be analyzed. */
  93234. ){
  93235. int savedHasAgg;
  93236. Walker w;
  93237. if( pExpr==0 ) return SQLITE_OK;
  93238. savedHasAgg = pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg|NC_HasWin);
  93239. pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg|NC_HasWin);
  93240. w.pParse = pNC->pParse;
  93241. w.xExprCallback = resolveExprStep;
  93242. w.xSelectCallback = resolveSelectStep;
  93243. w.xSelectCallback2 = 0;
  93244. w.u.pNC = pNC;
  93245. #if SQLITE_MAX_EXPR_DEPTH>0
  93246. w.pParse->nHeight += pExpr->nHeight;
  93247. if( sqlite3ExprCheckHeight(w.pParse, w.pParse->nHeight) ){
  93248. return SQLITE_ERROR;
  93249. }
  93250. #endif
  93251. sqlite3WalkExpr(&w, pExpr);
  93252. #if SQLITE_MAX_EXPR_DEPTH>0
  93253. w.pParse->nHeight -= pExpr->nHeight;
  93254. #endif
  93255. assert( EP_Agg==NC_HasAgg );
  93256. assert( EP_Win==NC_HasWin );
  93257. testcase( pNC->ncFlags & NC_HasAgg );
  93258. testcase( pNC->ncFlags & NC_HasWin );
  93259. ExprSetProperty(pExpr, pNC->ncFlags & (NC_HasAgg|NC_HasWin) );
  93260. pNC->ncFlags |= savedHasAgg;
  93261. return pNC->nErr>0 || w.pParse->nErr>0;
  93262. }
  93263. /*
  93264. ** Resolve all names for all expression in an expression list. This is
  93265. ** just like sqlite3ResolveExprNames() except that it works for an expression
  93266. ** list rather than a single expression.
  93267. */
  93268. SQLITE_PRIVATE int sqlite3ResolveExprListNames(
  93269. NameContext *pNC, /* Namespace to resolve expressions in. */
  93270. ExprList *pList /* The expression list to be analyzed. */
  93271. ){
  93272. int i;
  93273. int savedHasAgg = 0;
  93274. Walker w;
  93275. if( pList==0 ) return WRC_Continue;
  93276. w.pParse = pNC->pParse;
  93277. w.xExprCallback = resolveExprStep;
  93278. w.xSelectCallback = resolveSelectStep;
  93279. w.xSelectCallback2 = 0;
  93280. w.u.pNC = pNC;
  93281. savedHasAgg = pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg|NC_HasWin);
  93282. pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg|NC_HasWin);
  93283. for(i=0; i<pList->nExpr; i++){
  93284. Expr *pExpr = pList->a[i].pExpr;
  93285. if( pExpr==0 ) continue;
  93286. #if SQLITE_MAX_EXPR_DEPTH>0
  93287. w.pParse->nHeight += pExpr->nHeight;
  93288. if( sqlite3ExprCheckHeight(w.pParse, w.pParse->nHeight) ){
  93289. return WRC_Abort;
  93290. }
  93291. #endif
  93292. sqlite3WalkExpr(&w, pExpr);
  93293. #if SQLITE_MAX_EXPR_DEPTH>0
  93294. w.pParse->nHeight -= pExpr->nHeight;
  93295. #endif
  93296. assert( EP_Agg==NC_HasAgg );
  93297. assert( EP_Win==NC_HasWin );
  93298. testcase( pNC->ncFlags & NC_HasAgg );
  93299. testcase( pNC->ncFlags & NC_HasWin );
  93300. if( pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg|NC_HasWin) ){
  93301. ExprSetProperty(pExpr, pNC->ncFlags & (NC_HasAgg|NC_HasWin) );
  93302. savedHasAgg |= pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg|NC_HasWin);
  93303. pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg|NC_HasWin);
  93304. }
  93305. if( pNC->nErr>0 || w.pParse->nErr>0 ) return WRC_Abort;
  93306. }
  93307. pNC->ncFlags |= savedHasAgg;
  93308. return WRC_Continue;
  93309. }
  93310. /*
  93311. ** Resolve all names in all expressions of a SELECT and in all
  93312. ** decendents of the SELECT, including compounds off of p->pPrior,
  93313. ** subqueries in expressions, and subqueries used as FROM clause
  93314. ** terms.
  93315. **
  93316. ** See sqlite3ResolveExprNames() for a description of the kinds of
  93317. ** transformations that occur.
  93318. **
  93319. ** All SELECT statements should have been expanded using
  93320. ** sqlite3SelectExpand() prior to invoking this routine.
  93321. */
  93322. SQLITE_PRIVATE void sqlite3ResolveSelectNames(
  93323. Parse *pParse, /* The parser context */
  93324. Select *p, /* The SELECT statement being coded. */
  93325. NameContext *pOuterNC /* Name context for parent SELECT statement */
  93326. ){
  93327. Walker w;
  93328. assert( p!=0 );
  93329. w.xExprCallback = resolveExprStep;
  93330. w.xSelectCallback = resolveSelectStep;
  93331. w.xSelectCallback2 = 0;
  93332. w.pParse = pParse;
  93333. w.u.pNC = pOuterNC;
  93334. sqlite3WalkSelect(&w, p);
  93335. }
  93336. /*
  93337. ** Resolve names in expressions that can only reference a single table
  93338. ** or which cannot reference any tables at all. Examples:
  93339. **
  93340. ** "type" flag
  93341. ** ------------
  93342. ** (1) CHECK constraints NC_IsCheck
  93343. ** (2) WHERE clauses on partial indices NC_PartIdx
  93344. ** (3) Expressions in indexes on expressions NC_IdxExpr
  93345. ** (4) Expression arguments to VACUUM INTO. 0
  93346. ** (5) GENERATED ALWAYS as expressions NC_GenCol
  93347. **
  93348. ** In all cases except (4), the Expr.iTable value for Expr.op==TK_COLUMN
  93349. ** nodes of the expression is set to -1 and the Expr.iColumn value is
  93350. ** set to the column number. In case (4), TK_COLUMN nodes cause an error.
  93351. **
  93352. ** Any errors cause an error message to be set in pParse.
  93353. */
  93354. SQLITE_PRIVATE int sqlite3ResolveSelfReference(
  93355. Parse *pParse, /* Parsing context */
  93356. Table *pTab, /* The table being referenced, or NULL */
  93357. int type, /* NC_IsCheck, NC_PartIdx, NC_IdxExpr, NC_GenCol, or 0 */
  93358. Expr *pExpr, /* Expression to resolve. May be NULL. */
  93359. ExprList *pList /* Expression list to resolve. May be NULL. */
  93360. ){
  93361. SrcList sSrc; /* Fake SrcList for pParse->pNewTable */
  93362. NameContext sNC; /* Name context for pParse->pNewTable */
  93363. int rc;
  93364. assert( type==0 || pTab!=0 );
  93365. assert( type==NC_IsCheck || type==NC_PartIdx || type==NC_IdxExpr
  93366. || type==NC_GenCol || pTab==0 );
  93367. memset(&sNC, 0, sizeof(sNC));
  93368. memset(&sSrc, 0, sizeof(sSrc));
  93369. if( pTab ){
  93370. sSrc.nSrc = 1;
  93371. sSrc.a[0].zName = pTab->zName;
  93372. sSrc.a[0].pTab = pTab;
  93373. sSrc.a[0].iCursor = -1;
  93374. if( pTab->pSchema!=pParse->db->aDb[1].pSchema ){
  93375. /* Cause EP_FromDDL to be set on TK_FUNCTION nodes of non-TEMP
  93376. ** schema elements */
  93377. type |= NC_FromDDL;
  93378. }
  93379. }
  93380. sNC.pParse = pParse;
  93381. sNC.pSrcList = &sSrc;
  93382. sNC.ncFlags = type | NC_IsDDL;
  93383. if( (rc = sqlite3ResolveExprNames(&sNC, pExpr))!=SQLITE_OK ) return rc;
  93384. if( pList ) rc = sqlite3ResolveExprListNames(&sNC, pList);
  93385. return rc;
  93386. }
  93387. /************** End of resolve.c *********************************************/
  93388. /************** Begin file expr.c ********************************************/
  93389. /*
  93390. ** 2001 September 15
  93391. **
  93392. ** The author disclaims copyright to this source code. In place of
  93393. ** a legal notice, here is a blessing:
  93394. **
  93395. ** May you do good and not evil.
  93396. ** May you find forgiveness for yourself and forgive others.
  93397. ** May you share freely, never taking more than you give.
  93398. **
  93399. *************************************************************************
  93400. ** This file contains routines used for analyzing expressions and
  93401. ** for generating VDBE code that evaluates expressions in SQLite.
  93402. */
  93403. /* #include "sqliteInt.h" */
  93404. /* Forward declarations */
  93405. static void exprCodeBetween(Parse*,Expr*,int,void(*)(Parse*,Expr*,int,int),int);
  93406. static int exprCodeVector(Parse *pParse, Expr *p, int *piToFree);
  93407. /*
  93408. ** Return the affinity character for a single column of a table.
  93409. */
  93410. SQLITE_PRIVATE char sqlite3TableColumnAffinity(Table *pTab, int iCol){
  93411. assert( iCol<pTab->nCol );
  93412. return iCol>=0 ? pTab->aCol[iCol].affinity : SQLITE_AFF_INTEGER;
  93413. }
  93414. /*
  93415. ** Return the 'affinity' of the expression pExpr if any.
  93416. **
  93417. ** If pExpr is a column, a reference to a column via an 'AS' alias,
  93418. ** or a sub-select with a column as the return value, then the
  93419. ** affinity of that column is returned. Otherwise, 0x00 is returned,
  93420. ** indicating no affinity for the expression.
  93421. **
  93422. ** i.e. the WHERE clause expressions in the following statements all
  93423. ** have an affinity:
  93424. **
  93425. ** CREATE TABLE t1(a);
  93426. ** SELECT * FROM t1 WHERE a;
  93427. ** SELECT a AS b FROM t1 WHERE b;
  93428. ** SELECT * FROM t1 WHERE (select a from t1);
  93429. */
  93430. SQLITE_PRIVATE char sqlite3ExprAffinity(const Expr *pExpr){
  93431. int op;
  93432. while( ExprHasProperty(pExpr, EP_Skip) ){
  93433. assert( pExpr->op==TK_COLLATE || pExpr->op==TK_IF_NULL_ROW );
  93434. pExpr = pExpr->pLeft;
  93435. assert( pExpr!=0 );
  93436. }
  93437. op = pExpr->op;
  93438. if( op==TK_SELECT ){
  93439. assert( pExpr->flags&EP_xIsSelect );
  93440. return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
  93441. }
  93442. if( op==TK_REGISTER ) op = pExpr->op2;
  93443. #ifndef SQLITE_OMIT_CAST
  93444. if( op==TK_CAST ){
  93445. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  93446. return sqlite3AffinityType(pExpr->u.zToken, 0);
  93447. }
  93448. #endif
  93449. if( (op==TK_AGG_COLUMN || op==TK_COLUMN) && pExpr->y.pTab ){
  93450. return sqlite3TableColumnAffinity(pExpr->y.pTab, pExpr->iColumn);
  93451. }
  93452. if( op==TK_SELECT_COLUMN ){
  93453. assert( pExpr->pLeft->flags&EP_xIsSelect );
  93454. return sqlite3ExprAffinity(
  93455. pExpr->pLeft->x.pSelect->pEList->a[pExpr->iColumn].pExpr
  93456. );
  93457. }
  93458. if( op==TK_VECTOR ){
  93459. return sqlite3ExprAffinity(pExpr->x.pList->a[0].pExpr);
  93460. }
  93461. return pExpr->affExpr;
  93462. }
  93463. /*
  93464. ** Set the collating sequence for expression pExpr to be the collating
  93465. ** sequence named by pToken. Return a pointer to a new Expr node that
  93466. ** implements the COLLATE operator.
  93467. **
  93468. ** If a memory allocation error occurs, that fact is recorded in pParse->db
  93469. ** and the pExpr parameter is returned unchanged.
  93470. */
  93471. SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(
  93472. Parse *pParse, /* Parsing context */
  93473. Expr *pExpr, /* Add the "COLLATE" clause to this expression */
  93474. const Token *pCollName, /* Name of collating sequence */
  93475. int dequote /* True to dequote pCollName */
  93476. ){
  93477. if( pCollName->n>0 ){
  93478. Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLLATE, pCollName, dequote);
  93479. if( pNew ){
  93480. pNew->pLeft = pExpr;
  93481. pNew->flags |= EP_Collate|EP_Skip;
  93482. pExpr = pNew;
  93483. }
  93484. }
  93485. return pExpr;
  93486. }
  93487. SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse *pParse, Expr *pExpr, const char *zC){
  93488. Token s;
  93489. assert( zC!=0 );
  93490. sqlite3TokenInit(&s, (char*)zC);
  93491. return sqlite3ExprAddCollateToken(pParse, pExpr, &s, 0);
  93492. }
  93493. /*
  93494. ** Skip over any TK_COLLATE operators.
  93495. */
  93496. SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr *pExpr){
  93497. while( pExpr && ExprHasProperty(pExpr, EP_Skip) ){
  93498. assert( pExpr->op==TK_COLLATE || pExpr->op==TK_IF_NULL_ROW );
  93499. pExpr = pExpr->pLeft;
  93500. }
  93501. return pExpr;
  93502. }
  93503. /*
  93504. ** Skip over any TK_COLLATE operators and/or any unlikely()
  93505. ** or likelihood() or likely() functions at the root of an
  93506. ** expression.
  93507. */
  93508. SQLITE_PRIVATE Expr *sqlite3ExprSkipCollateAndLikely(Expr *pExpr){
  93509. while( pExpr && ExprHasProperty(pExpr, EP_Skip|EP_Unlikely) ){
  93510. if( ExprHasProperty(pExpr, EP_Unlikely) ){
  93511. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  93512. assert( pExpr->x.pList->nExpr>0 );
  93513. assert( pExpr->op==TK_FUNCTION );
  93514. pExpr = pExpr->x.pList->a[0].pExpr;
  93515. }else{
  93516. assert( pExpr->op==TK_COLLATE || pExpr->op==TK_IF_NULL_ROW );
  93517. pExpr = pExpr->pLeft;
  93518. }
  93519. }
  93520. return pExpr;
  93521. }
  93522. /*
  93523. ** Return the collation sequence for the expression pExpr. If
  93524. ** there is no defined collating sequence, return NULL.
  93525. **
  93526. ** See also: sqlite3ExprNNCollSeq()
  93527. **
  93528. ** The sqlite3ExprNNCollSeq() works the same exact that it returns the
  93529. ** default collation if pExpr has no defined collation.
  93530. **
  93531. ** The collating sequence might be determined by a COLLATE operator
  93532. ** or by the presence of a column with a defined collating sequence.
  93533. ** COLLATE operators take first precedence. Left operands take
  93534. ** precedence over right operands.
  93535. */
  93536. SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, const Expr *pExpr){
  93537. sqlite3 *db = pParse->db;
  93538. CollSeq *pColl = 0;
  93539. const Expr *p = pExpr;
  93540. while( p ){
  93541. int op = p->op;
  93542. if( op==TK_REGISTER ) op = p->op2;
  93543. if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_TRIGGER)
  93544. && p->y.pTab!=0
  93545. ){
  93546. /* op==TK_REGISTER && p->y.pTab!=0 happens when pExpr was originally
  93547. ** a TK_COLUMN but was previously evaluated and cached in a register */
  93548. int j = p->iColumn;
  93549. if( j>=0 ){
  93550. const char *zColl = p->y.pTab->aCol[j].zColl;
  93551. pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
  93552. }
  93553. break;
  93554. }
  93555. if( op==TK_CAST || op==TK_UPLUS ){
  93556. p = p->pLeft;
  93557. continue;
  93558. }
  93559. if( op==TK_VECTOR ){
  93560. p = p->x.pList->a[0].pExpr;
  93561. continue;
  93562. }
  93563. if( op==TK_COLLATE ){
  93564. pColl = sqlite3GetCollSeq(pParse, ENC(db), 0, p->u.zToken);
  93565. break;
  93566. }
  93567. if( p->flags & EP_Collate ){
  93568. if( p->pLeft && (p->pLeft->flags & EP_Collate)!=0 ){
  93569. p = p->pLeft;
  93570. }else{
  93571. Expr *pNext = p->pRight;
  93572. /* The Expr.x union is never used at the same time as Expr.pRight */
  93573. assert( p->x.pList==0 || p->pRight==0 );
  93574. if( p->x.pList!=0
  93575. && !db->mallocFailed
  93576. && ALWAYS(!ExprHasProperty(p, EP_xIsSelect))
  93577. ){
  93578. int i;
  93579. for(i=0; i<p->x.pList->nExpr; i++){
  93580. if( ExprHasProperty(p->x.pList->a[i].pExpr, EP_Collate) ){
  93581. pNext = p->x.pList->a[i].pExpr;
  93582. break;
  93583. }
  93584. }
  93585. }
  93586. p = pNext;
  93587. }
  93588. }else{
  93589. break;
  93590. }
  93591. }
  93592. if( sqlite3CheckCollSeq(pParse, pColl) ){
  93593. pColl = 0;
  93594. }
  93595. return pColl;
  93596. }
  93597. /*
  93598. ** Return the collation sequence for the expression pExpr. If
  93599. ** there is no defined collating sequence, return a pointer to the
  93600. ** defautl collation sequence.
  93601. **
  93602. ** See also: sqlite3ExprCollSeq()
  93603. **
  93604. ** The sqlite3ExprCollSeq() routine works the same except that it
  93605. ** returns NULL if there is no defined collation.
  93606. */
  93607. SQLITE_PRIVATE CollSeq *sqlite3ExprNNCollSeq(Parse *pParse, const Expr *pExpr){
  93608. CollSeq *p = sqlite3ExprCollSeq(pParse, pExpr);
  93609. if( p==0 ) p = pParse->db->pDfltColl;
  93610. assert( p!=0 );
  93611. return p;
  93612. }
  93613. /*
  93614. ** Return TRUE if the two expressions have equivalent collating sequences.
  93615. */
  93616. SQLITE_PRIVATE int sqlite3ExprCollSeqMatch(Parse *pParse, const Expr *pE1, const Expr *pE2){
  93617. CollSeq *pColl1 = sqlite3ExprNNCollSeq(pParse, pE1);
  93618. CollSeq *pColl2 = sqlite3ExprNNCollSeq(pParse, pE2);
  93619. return sqlite3StrICmp(pColl1->zName, pColl2->zName)==0;
  93620. }
  93621. /*
  93622. ** pExpr is an operand of a comparison operator. aff2 is the
  93623. ** type affinity of the other operand. This routine returns the
  93624. ** type affinity that should be used for the comparison operator.
  93625. */
  93626. SQLITE_PRIVATE char sqlite3CompareAffinity(const Expr *pExpr, char aff2){
  93627. char aff1 = sqlite3ExprAffinity(pExpr);
  93628. if( aff1>SQLITE_AFF_NONE && aff2>SQLITE_AFF_NONE ){
  93629. /* Both sides of the comparison are columns. If one has numeric
  93630. ** affinity, use that. Otherwise use no affinity.
  93631. */
  93632. if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
  93633. return SQLITE_AFF_NUMERIC;
  93634. }else{
  93635. return SQLITE_AFF_BLOB;
  93636. }
  93637. }else{
  93638. /* One side is a column, the other is not. Use the columns affinity. */
  93639. assert( aff1<=SQLITE_AFF_NONE || aff2<=SQLITE_AFF_NONE );
  93640. return (aff1<=SQLITE_AFF_NONE ? aff2 : aff1) | SQLITE_AFF_NONE;
  93641. }
  93642. }
  93643. /*
  93644. ** pExpr is a comparison operator. Return the type affinity that should
  93645. ** be applied to both operands prior to doing the comparison.
  93646. */
  93647. static char comparisonAffinity(const Expr *pExpr){
  93648. char aff;
  93649. assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
  93650. pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
  93651. pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
  93652. assert( pExpr->pLeft );
  93653. aff = sqlite3ExprAffinity(pExpr->pLeft);
  93654. if( pExpr->pRight ){
  93655. aff = sqlite3CompareAffinity(pExpr->pRight, aff);
  93656. }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  93657. aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
  93658. }else if( aff==0 ){
  93659. aff = SQLITE_AFF_BLOB;
  93660. }
  93661. return aff;
  93662. }
  93663. /*
  93664. ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
  93665. ** idx_affinity is the affinity of an indexed column. Return true
  93666. ** if the index with affinity idx_affinity may be used to implement
  93667. ** the comparison in pExpr.
  93668. */
  93669. SQLITE_PRIVATE int sqlite3IndexAffinityOk(const Expr *pExpr, char idx_affinity){
  93670. char aff = comparisonAffinity(pExpr);
  93671. if( aff<SQLITE_AFF_TEXT ){
  93672. return 1;
  93673. }
  93674. if( aff==SQLITE_AFF_TEXT ){
  93675. return idx_affinity==SQLITE_AFF_TEXT;
  93676. }
  93677. return sqlite3IsNumericAffinity(idx_affinity);
  93678. }
  93679. /*
  93680. ** Return the P5 value that should be used for a binary comparison
  93681. ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
  93682. */
  93683. static u8 binaryCompareP5(
  93684. const Expr *pExpr1, /* Left operand */
  93685. const Expr *pExpr2, /* Right operand */
  93686. int jumpIfNull /* Extra flags added to P5 */
  93687. ){
  93688. u8 aff = (char)sqlite3ExprAffinity(pExpr2);
  93689. aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
  93690. return aff;
  93691. }
  93692. /*
  93693. ** Return a pointer to the collation sequence that should be used by
  93694. ** a binary comparison operator comparing pLeft and pRight.
  93695. **
  93696. ** If the left hand expression has a collating sequence type, then it is
  93697. ** used. Otherwise the collation sequence for the right hand expression
  93698. ** is used, or the default (BINARY) if neither expression has a collating
  93699. ** type.
  93700. **
  93701. ** Argument pRight (but not pLeft) may be a null pointer. In this case,
  93702. ** it is not considered.
  93703. */
  93704. SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(
  93705. Parse *pParse,
  93706. const Expr *pLeft,
  93707. const Expr *pRight
  93708. ){
  93709. CollSeq *pColl;
  93710. assert( pLeft );
  93711. if( pLeft->flags & EP_Collate ){
  93712. pColl = sqlite3ExprCollSeq(pParse, pLeft);
  93713. }else if( pRight && (pRight->flags & EP_Collate)!=0 ){
  93714. pColl = sqlite3ExprCollSeq(pParse, pRight);
  93715. }else{
  93716. pColl = sqlite3ExprCollSeq(pParse, pLeft);
  93717. if( !pColl ){
  93718. pColl = sqlite3ExprCollSeq(pParse, pRight);
  93719. }
  93720. }
  93721. return pColl;
  93722. }
  93723. /* Expresssion p is a comparison operator. Return a collation sequence
  93724. ** appropriate for the comparison operator.
  93725. **
  93726. ** This is normally just a wrapper around sqlite3BinaryCompareCollSeq().
  93727. ** However, if the OP_Commuted flag is set, then the order of the operands
  93728. ** is reversed in the sqlite3BinaryCompareCollSeq() call so that the
  93729. ** correct collating sequence is found.
  93730. */
  93731. SQLITE_PRIVATE CollSeq *sqlite3ExprCompareCollSeq(Parse *pParse, const Expr *p){
  93732. if( ExprHasProperty(p, EP_Commuted) ){
  93733. return sqlite3BinaryCompareCollSeq(pParse, p->pRight, p->pLeft);
  93734. }else{
  93735. return sqlite3BinaryCompareCollSeq(pParse, p->pLeft, p->pRight);
  93736. }
  93737. }
  93738. /*
  93739. ** Generate code for a comparison operator.
  93740. */
  93741. static int codeCompare(
  93742. Parse *pParse, /* The parsing (and code generating) context */
  93743. Expr *pLeft, /* The left operand */
  93744. Expr *pRight, /* The right operand */
  93745. int opcode, /* The comparison opcode */
  93746. int in1, int in2, /* Register holding operands */
  93747. int dest, /* Jump here if true. */
  93748. int jumpIfNull, /* If true, jump if either operand is NULL */
  93749. int isCommuted /* The comparison has been commuted */
  93750. ){
  93751. int p5;
  93752. int addr;
  93753. CollSeq *p4;
  93754. if( pParse->nErr ) return 0;
  93755. if( isCommuted ){
  93756. p4 = sqlite3BinaryCompareCollSeq(pParse, pRight, pLeft);
  93757. }else{
  93758. p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
  93759. }
  93760. p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
  93761. addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
  93762. (void*)p4, P4_COLLSEQ);
  93763. sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
  93764. return addr;
  93765. }
  93766. /*
  93767. ** Return true if expression pExpr is a vector, or false otherwise.
  93768. **
  93769. ** A vector is defined as any expression that results in two or more
  93770. ** columns of result. Every TK_VECTOR node is an vector because the
  93771. ** parser will not generate a TK_VECTOR with fewer than two entries.
  93772. ** But a TK_SELECT might be either a vector or a scalar. It is only
  93773. ** considered a vector if it has two or more result columns.
  93774. */
  93775. SQLITE_PRIVATE int sqlite3ExprIsVector(Expr *pExpr){
  93776. return sqlite3ExprVectorSize(pExpr)>1;
  93777. }
  93778. /*
  93779. ** If the expression passed as the only argument is of type TK_VECTOR
  93780. ** return the number of expressions in the vector. Or, if the expression
  93781. ** is a sub-select, return the number of columns in the sub-select. For
  93782. ** any other type of expression, return 1.
  93783. */
  93784. SQLITE_PRIVATE int sqlite3ExprVectorSize(Expr *pExpr){
  93785. u8 op = pExpr->op;
  93786. if( op==TK_REGISTER ) op = pExpr->op2;
  93787. if( op==TK_VECTOR ){
  93788. return pExpr->x.pList->nExpr;
  93789. }else if( op==TK_SELECT ){
  93790. return pExpr->x.pSelect->pEList->nExpr;
  93791. }else{
  93792. return 1;
  93793. }
  93794. }
  93795. /*
  93796. ** Return a pointer to a subexpression of pVector that is the i-th
  93797. ** column of the vector (numbered starting with 0). The caller must
  93798. ** ensure that i is within range.
  93799. **
  93800. ** If pVector is really a scalar (and "scalar" here includes subqueries
  93801. ** that return a single column!) then return pVector unmodified.
  93802. **
  93803. ** pVector retains ownership of the returned subexpression.
  93804. **
  93805. ** If the vector is a (SELECT ...) then the expression returned is
  93806. ** just the expression for the i-th term of the result set, and may
  93807. ** not be ready for evaluation because the table cursor has not yet
  93808. ** been positioned.
  93809. */
  93810. SQLITE_PRIVATE Expr *sqlite3VectorFieldSubexpr(Expr *pVector, int i){
  93811. assert( i<sqlite3ExprVectorSize(pVector) );
  93812. if( sqlite3ExprIsVector(pVector) ){
  93813. assert( pVector->op2==0 || pVector->op==TK_REGISTER );
  93814. if( pVector->op==TK_SELECT || pVector->op2==TK_SELECT ){
  93815. return pVector->x.pSelect->pEList->a[i].pExpr;
  93816. }else{
  93817. return pVector->x.pList->a[i].pExpr;
  93818. }
  93819. }
  93820. return pVector;
  93821. }
  93822. /*
  93823. ** Compute and return a new Expr object which when passed to
  93824. ** sqlite3ExprCode() will generate all necessary code to compute
  93825. ** the iField-th column of the vector expression pVector.
  93826. **
  93827. ** It is ok for pVector to be a scalar (as long as iField==0).
  93828. ** In that case, this routine works like sqlite3ExprDup().
  93829. **
  93830. ** The caller owns the returned Expr object and is responsible for
  93831. ** ensuring that the returned value eventually gets freed.
  93832. **
  93833. ** The caller retains ownership of pVector. If pVector is a TK_SELECT,
  93834. ** then the returned object will reference pVector and so pVector must remain
  93835. ** valid for the life of the returned object. If pVector is a TK_VECTOR
  93836. ** or a scalar expression, then it can be deleted as soon as this routine
  93837. ** returns.
  93838. **
  93839. ** A trick to cause a TK_SELECT pVector to be deleted together with
  93840. ** the returned Expr object is to attach the pVector to the pRight field
  93841. ** of the returned TK_SELECT_COLUMN Expr object.
  93842. */
  93843. SQLITE_PRIVATE Expr *sqlite3ExprForVectorField(
  93844. Parse *pParse, /* Parsing context */
  93845. Expr *pVector, /* The vector. List of expressions or a sub-SELECT */
  93846. int iField /* Which column of the vector to return */
  93847. ){
  93848. Expr *pRet;
  93849. if( pVector->op==TK_SELECT ){
  93850. assert( pVector->flags & EP_xIsSelect );
  93851. /* The TK_SELECT_COLUMN Expr node:
  93852. **
  93853. ** pLeft: pVector containing TK_SELECT. Not deleted.
  93854. ** pRight: not used. But recursively deleted.
  93855. ** iColumn: Index of a column in pVector
  93856. ** iTable: 0 or the number of columns on the LHS of an assignment
  93857. ** pLeft->iTable: First in an array of register holding result, or 0
  93858. ** if the result is not yet computed.
  93859. **
  93860. ** sqlite3ExprDelete() specifically skips the recursive delete of
  93861. ** pLeft on TK_SELECT_COLUMN nodes. But pRight is followed, so pVector
  93862. ** can be attached to pRight to cause this node to take ownership of
  93863. ** pVector. Typically there will be multiple TK_SELECT_COLUMN nodes
  93864. ** with the same pLeft pointer to the pVector, but only one of them
  93865. ** will own the pVector.
  93866. */
  93867. pRet = sqlite3PExpr(pParse, TK_SELECT_COLUMN, 0, 0);
  93868. if( pRet ){
  93869. pRet->iColumn = iField;
  93870. pRet->pLeft = pVector;
  93871. }
  93872. assert( pRet==0 || pRet->iTable==0 );
  93873. }else{
  93874. if( pVector->op==TK_VECTOR ) pVector = pVector->x.pList->a[iField].pExpr;
  93875. pRet = sqlite3ExprDup(pParse->db, pVector, 0);
  93876. sqlite3RenameTokenRemap(pParse, pRet, pVector);
  93877. }
  93878. return pRet;
  93879. }
  93880. /*
  93881. ** If expression pExpr is of type TK_SELECT, generate code to evaluate
  93882. ** it. Return the register in which the result is stored (or, if the
  93883. ** sub-select returns more than one column, the first in an array
  93884. ** of registers in which the result is stored).
  93885. **
  93886. ** If pExpr is not a TK_SELECT expression, return 0.
  93887. */
  93888. static int exprCodeSubselect(Parse *pParse, Expr *pExpr){
  93889. int reg = 0;
  93890. #ifndef SQLITE_OMIT_SUBQUERY
  93891. if( pExpr->op==TK_SELECT ){
  93892. reg = sqlite3CodeSubselect(pParse, pExpr);
  93893. }
  93894. #endif
  93895. return reg;
  93896. }
  93897. /*
  93898. ** Argument pVector points to a vector expression - either a TK_VECTOR
  93899. ** or TK_SELECT that returns more than one column. This function returns
  93900. ** the register number of a register that contains the value of
  93901. ** element iField of the vector.
  93902. **
  93903. ** If pVector is a TK_SELECT expression, then code for it must have
  93904. ** already been generated using the exprCodeSubselect() routine. In this
  93905. ** case parameter regSelect should be the first in an array of registers
  93906. ** containing the results of the sub-select.
  93907. **
  93908. ** If pVector is of type TK_VECTOR, then code for the requested field
  93909. ** is generated. In this case (*pRegFree) may be set to the number of
  93910. ** a temporary register to be freed by the caller before returning.
  93911. **
  93912. ** Before returning, output parameter (*ppExpr) is set to point to the
  93913. ** Expr object corresponding to element iElem of the vector.
  93914. */
  93915. static int exprVectorRegister(
  93916. Parse *pParse, /* Parse context */
  93917. Expr *pVector, /* Vector to extract element from */
  93918. int iField, /* Field to extract from pVector */
  93919. int regSelect, /* First in array of registers */
  93920. Expr **ppExpr, /* OUT: Expression element */
  93921. int *pRegFree /* OUT: Temp register to free */
  93922. ){
  93923. u8 op = pVector->op;
  93924. assert( op==TK_VECTOR || op==TK_REGISTER || op==TK_SELECT );
  93925. if( op==TK_REGISTER ){
  93926. *ppExpr = sqlite3VectorFieldSubexpr(pVector, iField);
  93927. return pVector->iTable+iField;
  93928. }
  93929. if( op==TK_SELECT ){
  93930. *ppExpr = pVector->x.pSelect->pEList->a[iField].pExpr;
  93931. return regSelect+iField;
  93932. }
  93933. *ppExpr = pVector->x.pList->a[iField].pExpr;
  93934. return sqlite3ExprCodeTemp(pParse, *ppExpr, pRegFree);
  93935. }
  93936. /*
  93937. ** Expression pExpr is a comparison between two vector values. Compute
  93938. ** the result of the comparison (1, 0, or NULL) and write that
  93939. ** result into register dest.
  93940. **
  93941. ** The caller must satisfy the following preconditions:
  93942. **
  93943. ** if pExpr->op==TK_IS: op==TK_EQ and p5==SQLITE_NULLEQ
  93944. ** if pExpr->op==TK_ISNOT: op==TK_NE and p5==SQLITE_NULLEQ
  93945. ** otherwise: op==pExpr->op and p5==0
  93946. */
  93947. static void codeVectorCompare(
  93948. Parse *pParse, /* Code generator context */
  93949. Expr *pExpr, /* The comparison operation */
  93950. int dest, /* Write results into this register */
  93951. u8 op, /* Comparison operator */
  93952. u8 p5 /* SQLITE_NULLEQ or zero */
  93953. ){
  93954. Vdbe *v = pParse->pVdbe;
  93955. Expr *pLeft = pExpr->pLeft;
  93956. Expr *pRight = pExpr->pRight;
  93957. int nLeft = sqlite3ExprVectorSize(pLeft);
  93958. int i;
  93959. int regLeft = 0;
  93960. int regRight = 0;
  93961. u8 opx = op;
  93962. int addrDone = sqlite3VdbeMakeLabel(pParse);
  93963. int isCommuted = ExprHasProperty(pExpr,EP_Commuted);
  93964. assert( !ExprHasVVAProperty(pExpr,EP_Immutable) );
  93965. if( pParse->nErr ) return;
  93966. if( nLeft!=sqlite3ExprVectorSize(pRight) ){
  93967. sqlite3ErrorMsg(pParse, "row value misused");
  93968. return;
  93969. }
  93970. assert( pExpr->op==TK_EQ || pExpr->op==TK_NE
  93971. || pExpr->op==TK_IS || pExpr->op==TK_ISNOT
  93972. || pExpr->op==TK_LT || pExpr->op==TK_GT
  93973. || pExpr->op==TK_LE || pExpr->op==TK_GE
  93974. );
  93975. assert( pExpr->op==op || (pExpr->op==TK_IS && op==TK_EQ)
  93976. || (pExpr->op==TK_ISNOT && op==TK_NE) );
  93977. assert( p5==0 || pExpr->op!=op );
  93978. assert( p5==SQLITE_NULLEQ || pExpr->op==op );
  93979. p5 |= SQLITE_STOREP2;
  93980. if( opx==TK_LE ) opx = TK_LT;
  93981. if( opx==TK_GE ) opx = TK_GT;
  93982. regLeft = exprCodeSubselect(pParse, pLeft);
  93983. regRight = exprCodeSubselect(pParse, pRight);
  93984. for(i=0; 1 /*Loop exits by "break"*/; i++){
  93985. int regFree1 = 0, regFree2 = 0;
  93986. Expr *pL, *pR;
  93987. int r1, r2;
  93988. assert( i>=0 && i<nLeft );
  93989. r1 = exprVectorRegister(pParse, pLeft, i, regLeft, &pL, &regFree1);
  93990. r2 = exprVectorRegister(pParse, pRight, i, regRight, &pR, &regFree2);
  93991. codeCompare(pParse, pL, pR, opx, r1, r2, dest, p5, isCommuted);
  93992. testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
  93993. testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
  93994. testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
  93995. testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
  93996. testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
  93997. testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
  93998. sqlite3ReleaseTempReg(pParse, regFree1);
  93999. sqlite3ReleaseTempReg(pParse, regFree2);
  94000. if( i==nLeft-1 ){
  94001. break;
  94002. }
  94003. if( opx==TK_EQ ){
  94004. sqlite3VdbeAddOp2(v, OP_IfNot, dest, addrDone); VdbeCoverage(v);
  94005. p5 |= SQLITE_KEEPNULL;
  94006. }else if( opx==TK_NE ){
  94007. sqlite3VdbeAddOp2(v, OP_If, dest, addrDone); VdbeCoverage(v);
  94008. p5 |= SQLITE_KEEPNULL;
  94009. }else{
  94010. assert( op==TK_LT || op==TK_GT || op==TK_LE || op==TK_GE );
  94011. sqlite3VdbeAddOp2(v, OP_ElseNotEq, 0, addrDone);
  94012. VdbeCoverageIf(v, op==TK_LT);
  94013. VdbeCoverageIf(v, op==TK_GT);
  94014. VdbeCoverageIf(v, op==TK_LE);
  94015. VdbeCoverageIf(v, op==TK_GE);
  94016. if( i==nLeft-2 ) opx = op;
  94017. }
  94018. }
  94019. sqlite3VdbeResolveLabel(v, addrDone);
  94020. }
  94021. #if SQLITE_MAX_EXPR_DEPTH>0
  94022. /*
  94023. ** Check that argument nHeight is less than or equal to the maximum
  94024. ** expression depth allowed. If it is not, leave an error message in
  94025. ** pParse.
  94026. */
  94027. SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
  94028. int rc = SQLITE_OK;
  94029. int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
  94030. if( nHeight>mxHeight ){
  94031. sqlite3ErrorMsg(pParse,
  94032. "Expression tree is too large (maximum depth %d)", mxHeight
  94033. );
  94034. rc = SQLITE_ERROR;
  94035. }
  94036. return rc;
  94037. }
  94038. /* The following three functions, heightOfExpr(), heightOfExprList()
  94039. ** and heightOfSelect(), are used to determine the maximum height
  94040. ** of any expression tree referenced by the structure passed as the
  94041. ** first argument.
  94042. **
  94043. ** If this maximum height is greater than the current value pointed
  94044. ** to by pnHeight, the second parameter, then set *pnHeight to that
  94045. ** value.
  94046. */
  94047. static void heightOfExpr(Expr *p, int *pnHeight){
  94048. if( p ){
  94049. if( p->nHeight>*pnHeight ){
  94050. *pnHeight = p->nHeight;
  94051. }
  94052. }
  94053. }
  94054. static void heightOfExprList(ExprList *p, int *pnHeight){
  94055. if( p ){
  94056. int i;
  94057. for(i=0; i<p->nExpr; i++){
  94058. heightOfExpr(p->a[i].pExpr, pnHeight);
  94059. }
  94060. }
  94061. }
  94062. static void heightOfSelect(Select *pSelect, int *pnHeight){
  94063. Select *p;
  94064. for(p=pSelect; p; p=p->pPrior){
  94065. heightOfExpr(p->pWhere, pnHeight);
  94066. heightOfExpr(p->pHaving, pnHeight);
  94067. heightOfExpr(p->pLimit, pnHeight);
  94068. heightOfExprList(p->pEList, pnHeight);
  94069. heightOfExprList(p->pGroupBy, pnHeight);
  94070. heightOfExprList(p->pOrderBy, pnHeight);
  94071. }
  94072. }
  94073. /*
  94074. ** Set the Expr.nHeight variable in the structure passed as an
  94075. ** argument. An expression with no children, Expr.pList or
  94076. ** Expr.pSelect member has a height of 1. Any other expression
  94077. ** has a height equal to the maximum height of any other
  94078. ** referenced Expr plus one.
  94079. **
  94080. ** Also propagate EP_Propagate flags up from Expr.x.pList to Expr.flags,
  94081. ** if appropriate.
  94082. */
  94083. static void exprSetHeight(Expr *p){
  94084. int nHeight = 0;
  94085. heightOfExpr(p->pLeft, &nHeight);
  94086. heightOfExpr(p->pRight, &nHeight);
  94087. if( ExprHasProperty(p, EP_xIsSelect) ){
  94088. heightOfSelect(p->x.pSelect, &nHeight);
  94089. }else if( p->x.pList ){
  94090. heightOfExprList(p->x.pList, &nHeight);
  94091. p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
  94092. }
  94093. p->nHeight = nHeight + 1;
  94094. }
  94095. /*
  94096. ** Set the Expr.nHeight variable using the exprSetHeight() function. If
  94097. ** the height is greater than the maximum allowed expression depth,
  94098. ** leave an error in pParse.
  94099. **
  94100. ** Also propagate all EP_Propagate flags from the Expr.x.pList into
  94101. ** Expr.flags.
  94102. */
  94103. SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
  94104. if( pParse->nErr ) return;
  94105. exprSetHeight(p);
  94106. sqlite3ExprCheckHeight(pParse, p->nHeight);
  94107. }
  94108. /*
  94109. ** Return the maximum height of any expression tree referenced
  94110. ** by the select statement passed as an argument.
  94111. */
  94112. SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){
  94113. int nHeight = 0;
  94114. heightOfSelect(p, &nHeight);
  94115. return nHeight;
  94116. }
  94117. #else /* ABOVE: Height enforcement enabled. BELOW: Height enforcement off */
  94118. /*
  94119. ** Propagate all EP_Propagate flags from the Expr.x.pList into
  94120. ** Expr.flags.
  94121. */
  94122. SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
  94123. if( p && p->x.pList && !ExprHasProperty(p, EP_xIsSelect) ){
  94124. p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
  94125. }
  94126. }
  94127. #define exprSetHeight(y)
  94128. #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
  94129. /*
  94130. ** This routine is the core allocator for Expr nodes.
  94131. **
  94132. ** Construct a new expression node and return a pointer to it. Memory
  94133. ** for this node and for the pToken argument is a single allocation
  94134. ** obtained from sqlite3DbMalloc(). The calling function
  94135. ** is responsible for making sure the node eventually gets freed.
  94136. **
  94137. ** If dequote is true, then the token (if it exists) is dequoted.
  94138. ** If dequote is false, no dequoting is performed. The deQuote
  94139. ** parameter is ignored if pToken is NULL or if the token does not
  94140. ** appear to be quoted. If the quotes were of the form "..." (double-quotes)
  94141. ** then the EP_DblQuoted flag is set on the expression node.
  94142. **
  94143. ** Special case: If op==TK_INTEGER and pToken points to a string that
  94144. ** can be translated into a 32-bit integer, then the token is not
  94145. ** stored in u.zToken. Instead, the integer values is written
  94146. ** into u.iValue and the EP_IntValue flag is set. No extra storage
  94147. ** is allocated to hold the integer text and the dequote flag is ignored.
  94148. */
  94149. SQLITE_PRIVATE Expr *sqlite3ExprAlloc(
  94150. sqlite3 *db, /* Handle for sqlite3DbMallocRawNN() */
  94151. int op, /* Expression opcode */
  94152. const Token *pToken, /* Token argument. Might be NULL */
  94153. int dequote /* True to dequote */
  94154. ){
  94155. Expr *pNew;
  94156. int nExtra = 0;
  94157. int iValue = 0;
  94158. assert( db!=0 );
  94159. if( pToken ){
  94160. if( op!=TK_INTEGER || pToken->z==0
  94161. || sqlite3GetInt32(pToken->z, &iValue)==0 ){
  94162. nExtra = pToken->n+1;
  94163. assert( iValue>=0 );
  94164. }
  94165. }
  94166. pNew = sqlite3DbMallocRawNN(db, sizeof(Expr)+nExtra);
  94167. if( pNew ){
  94168. memset(pNew, 0, sizeof(Expr));
  94169. pNew->op = (u8)op;
  94170. pNew->iAgg = -1;
  94171. if( pToken ){
  94172. if( nExtra==0 ){
  94173. pNew->flags |= EP_IntValue|EP_Leaf|(iValue?EP_IsTrue:EP_IsFalse);
  94174. pNew->u.iValue = iValue;
  94175. }else{
  94176. pNew->u.zToken = (char*)&pNew[1];
  94177. assert( pToken->z!=0 || pToken->n==0 );
  94178. if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
  94179. pNew->u.zToken[pToken->n] = 0;
  94180. if( dequote && sqlite3Isquote(pNew->u.zToken[0]) ){
  94181. sqlite3DequoteExpr(pNew);
  94182. }
  94183. }
  94184. }
  94185. #if SQLITE_MAX_EXPR_DEPTH>0
  94186. pNew->nHeight = 1;
  94187. #endif
  94188. }
  94189. return pNew;
  94190. }
  94191. /*
  94192. ** Allocate a new expression node from a zero-terminated token that has
  94193. ** already been dequoted.
  94194. */
  94195. SQLITE_PRIVATE Expr *sqlite3Expr(
  94196. sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */
  94197. int op, /* Expression opcode */
  94198. const char *zToken /* Token argument. Might be NULL */
  94199. ){
  94200. Token x;
  94201. x.z = zToken;
  94202. x.n = sqlite3Strlen30(zToken);
  94203. return sqlite3ExprAlloc(db, op, &x, 0);
  94204. }
  94205. /*
  94206. ** Attach subtrees pLeft and pRight to the Expr node pRoot.
  94207. **
  94208. ** If pRoot==NULL that means that a memory allocation error has occurred.
  94209. ** In that case, delete the subtrees pLeft and pRight.
  94210. */
  94211. SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(
  94212. sqlite3 *db,
  94213. Expr *pRoot,
  94214. Expr *pLeft,
  94215. Expr *pRight
  94216. ){
  94217. if( pRoot==0 ){
  94218. assert( db->mallocFailed );
  94219. sqlite3ExprDelete(db, pLeft);
  94220. sqlite3ExprDelete(db, pRight);
  94221. }else{
  94222. if( pRight ){
  94223. pRoot->pRight = pRight;
  94224. pRoot->flags |= EP_Propagate & pRight->flags;
  94225. }
  94226. if( pLeft ){
  94227. pRoot->pLeft = pLeft;
  94228. pRoot->flags |= EP_Propagate & pLeft->flags;
  94229. }
  94230. exprSetHeight(pRoot);
  94231. }
  94232. }
  94233. /*
  94234. ** Allocate an Expr node which joins as many as two subtrees.
  94235. **
  94236. ** One or both of the subtrees can be NULL. Return a pointer to the new
  94237. ** Expr node. Or, if an OOM error occurs, set pParse->db->mallocFailed,
  94238. ** free the subtrees and return NULL.
  94239. */
  94240. SQLITE_PRIVATE Expr *sqlite3PExpr(
  94241. Parse *pParse, /* Parsing context */
  94242. int op, /* Expression opcode */
  94243. Expr *pLeft, /* Left operand */
  94244. Expr *pRight /* Right operand */
  94245. ){
  94246. Expr *p;
  94247. p = sqlite3DbMallocRawNN(pParse->db, sizeof(Expr));
  94248. if( p ){
  94249. memset(p, 0, sizeof(Expr));
  94250. p->op = op & 0xff;
  94251. p->iAgg = -1;
  94252. sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
  94253. sqlite3ExprCheckHeight(pParse, p->nHeight);
  94254. }else{
  94255. sqlite3ExprDelete(pParse->db, pLeft);
  94256. sqlite3ExprDelete(pParse->db, pRight);
  94257. }
  94258. return p;
  94259. }
  94260. /*
  94261. ** Add pSelect to the Expr.x.pSelect field. Or, if pExpr is NULL (due
  94262. ** do a memory allocation failure) then delete the pSelect object.
  94263. */
  94264. SQLITE_PRIVATE void sqlite3PExprAddSelect(Parse *pParse, Expr *pExpr, Select *pSelect){
  94265. if( pExpr ){
  94266. pExpr->x.pSelect = pSelect;
  94267. ExprSetProperty(pExpr, EP_xIsSelect|EP_Subquery);
  94268. sqlite3ExprSetHeightAndFlags(pParse, pExpr);
  94269. }else{
  94270. assert( pParse->db->mallocFailed );
  94271. sqlite3SelectDelete(pParse->db, pSelect);
  94272. }
  94273. }
  94274. /*
  94275. ** Join two expressions using an AND operator. If either expression is
  94276. ** NULL, then just return the other expression.
  94277. **
  94278. ** If one side or the other of the AND is known to be false, then instead
  94279. ** of returning an AND expression, just return a constant expression with
  94280. ** a value of false.
  94281. */
  94282. SQLITE_PRIVATE Expr *sqlite3ExprAnd(Parse *pParse, Expr *pLeft, Expr *pRight){
  94283. sqlite3 *db = pParse->db;
  94284. if( pLeft==0 ){
  94285. return pRight;
  94286. }else if( pRight==0 ){
  94287. return pLeft;
  94288. }else if( (ExprAlwaysFalse(pLeft) || ExprAlwaysFalse(pRight))
  94289. && !IN_RENAME_OBJECT
  94290. ){
  94291. sqlite3ExprDelete(db, pLeft);
  94292. sqlite3ExprDelete(db, pRight);
  94293. return sqlite3Expr(db, TK_INTEGER, "0");
  94294. }else{
  94295. return sqlite3PExpr(pParse, TK_AND, pLeft, pRight);
  94296. }
  94297. }
  94298. /*
  94299. ** Construct a new expression node for a function with multiple
  94300. ** arguments.
  94301. */
  94302. SQLITE_PRIVATE Expr *sqlite3ExprFunction(
  94303. Parse *pParse, /* Parsing context */
  94304. ExprList *pList, /* Argument list */
  94305. Token *pToken, /* Name of the function */
  94306. int eDistinct /* SF_Distinct or SF_ALL or 0 */
  94307. ){
  94308. Expr *pNew;
  94309. sqlite3 *db = pParse->db;
  94310. assert( pToken );
  94311. pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
  94312. if( pNew==0 ){
  94313. sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
  94314. return 0;
  94315. }
  94316. if( pList && pList->nExpr > pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
  94317. sqlite3ErrorMsg(pParse, "too many arguments on function %T", pToken);
  94318. }
  94319. pNew->x.pList = pList;
  94320. ExprSetProperty(pNew, EP_HasFunc);
  94321. assert( !ExprHasProperty(pNew, EP_xIsSelect) );
  94322. sqlite3ExprSetHeightAndFlags(pParse, pNew);
  94323. if( eDistinct==SF_Distinct ) ExprSetProperty(pNew, EP_Distinct);
  94324. return pNew;
  94325. }
  94326. /*
  94327. ** Check to see if a function is usable according to current access
  94328. ** rules:
  94329. **
  94330. ** SQLITE_FUNC_DIRECT - Only usable from top-level SQL
  94331. **
  94332. ** SQLITE_FUNC_UNSAFE - Usable if TRUSTED_SCHEMA or from
  94333. ** top-level SQL
  94334. **
  94335. ** If the function is not usable, create an error.
  94336. */
  94337. SQLITE_PRIVATE void sqlite3ExprFunctionUsable(
  94338. Parse *pParse, /* Parsing and code generating context */
  94339. Expr *pExpr, /* The function invocation */
  94340. FuncDef *pDef /* The function being invoked */
  94341. ){
  94342. assert( !IN_RENAME_OBJECT );
  94343. assert( (pDef->funcFlags & (SQLITE_FUNC_DIRECT|SQLITE_FUNC_UNSAFE))!=0 );
  94344. if( ExprHasProperty(pExpr, EP_FromDDL) ){
  94345. if( (pDef->funcFlags & SQLITE_FUNC_DIRECT)!=0
  94346. || (pParse->db->flags & SQLITE_TrustedSchema)==0
  94347. ){
  94348. /* Functions prohibited in triggers and views if:
  94349. ** (1) tagged with SQLITE_DIRECTONLY
  94350. ** (2) not tagged with SQLITE_INNOCUOUS (which means it
  94351. ** is tagged with SQLITE_FUNC_UNSAFE) and
  94352. ** SQLITE_DBCONFIG_TRUSTED_SCHEMA is off (meaning
  94353. ** that the schema is possibly tainted).
  94354. */
  94355. sqlite3ErrorMsg(pParse, "unsafe use of %s()", pDef->zName);
  94356. }
  94357. }
  94358. }
  94359. /*
  94360. ** Assign a variable number to an expression that encodes a wildcard
  94361. ** in the original SQL statement.
  94362. **
  94363. ** Wildcards consisting of a single "?" are assigned the next sequential
  94364. ** variable number.
  94365. **
  94366. ** Wildcards of the form "?nnn" are assigned the number "nnn". We make
  94367. ** sure "nnn" is not too big to avoid a denial of service attack when
  94368. ** the SQL statement comes from an external source.
  94369. **
  94370. ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
  94371. ** as the previous instance of the same wildcard. Or if this is the first
  94372. ** instance of the wildcard, the next sequential variable number is
  94373. ** assigned.
  94374. */
  94375. SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr, u32 n){
  94376. sqlite3 *db = pParse->db;
  94377. const char *z;
  94378. ynVar x;
  94379. if( pExpr==0 ) return;
  94380. assert( !ExprHasProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
  94381. z = pExpr->u.zToken;
  94382. assert( z!=0 );
  94383. assert( z[0]!=0 );
  94384. assert( n==(u32)sqlite3Strlen30(z) );
  94385. if( z[1]==0 ){
  94386. /* Wildcard of the form "?". Assign the next variable number */
  94387. assert( z[0]=='?' );
  94388. x = (ynVar)(++pParse->nVar);
  94389. }else{
  94390. int doAdd = 0;
  94391. if( z[0]=='?' ){
  94392. /* Wildcard of the form "?nnn". Convert "nnn" to an integer and
  94393. ** use it as the variable number */
  94394. i64 i;
  94395. int bOk;
  94396. if( n==2 ){ /*OPTIMIZATION-IF-TRUE*/
  94397. i = z[1]-'0'; /* The common case of ?N for a single digit N */
  94398. bOk = 1;
  94399. }else{
  94400. bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8);
  94401. }
  94402. testcase( i==0 );
  94403. testcase( i==1 );
  94404. testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
  94405. testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
  94406. if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
  94407. sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
  94408. db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
  94409. return;
  94410. }
  94411. x = (ynVar)i;
  94412. if( x>pParse->nVar ){
  94413. pParse->nVar = (int)x;
  94414. doAdd = 1;
  94415. }else if( sqlite3VListNumToName(pParse->pVList, x)==0 ){
  94416. doAdd = 1;
  94417. }
  94418. }else{
  94419. /* Wildcards like ":aaa", "$aaa" or "@aaa". Reuse the same variable
  94420. ** number as the prior appearance of the same name, or if the name
  94421. ** has never appeared before, reuse the same variable number
  94422. */
  94423. x = (ynVar)sqlite3VListNameToNum(pParse->pVList, z, n);
  94424. if( x==0 ){
  94425. x = (ynVar)(++pParse->nVar);
  94426. doAdd = 1;
  94427. }
  94428. }
  94429. if( doAdd ){
  94430. pParse->pVList = sqlite3VListAdd(db, pParse->pVList, z, n, x);
  94431. }
  94432. }
  94433. pExpr->iColumn = x;
  94434. if( x>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
  94435. sqlite3ErrorMsg(pParse, "too many SQL variables");
  94436. }
  94437. }
  94438. /*
  94439. ** Recursively delete an expression tree.
  94440. */
  94441. static SQLITE_NOINLINE void sqlite3ExprDeleteNN(sqlite3 *db, Expr *p){
  94442. assert( p!=0 );
  94443. /* Sanity check: Assert that the IntValue is non-negative if it exists */
  94444. assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
  94445. assert( !ExprHasProperty(p, EP_WinFunc) || p->y.pWin!=0 || db->mallocFailed );
  94446. assert( p->op!=TK_FUNCTION || ExprHasProperty(p, EP_TokenOnly|EP_Reduced)
  94447. || p->y.pWin==0 || ExprHasProperty(p, EP_WinFunc) );
  94448. #ifdef SQLITE_DEBUG
  94449. if( ExprHasProperty(p, EP_Leaf) && !ExprHasProperty(p, EP_TokenOnly) ){
  94450. assert( p->pLeft==0 );
  94451. assert( p->pRight==0 );
  94452. assert( p->x.pSelect==0 );
  94453. }
  94454. #endif
  94455. if( !ExprHasProperty(p, (EP_TokenOnly|EP_Leaf)) ){
  94456. /* The Expr.x union is never used at the same time as Expr.pRight */
  94457. assert( p->x.pList==0 || p->pRight==0 );
  94458. if( p->pLeft && p->op!=TK_SELECT_COLUMN ) sqlite3ExprDeleteNN(db, p->pLeft);
  94459. if( p->pRight ){
  94460. assert( !ExprHasProperty(p, EP_WinFunc) );
  94461. sqlite3ExprDeleteNN(db, p->pRight);
  94462. }else if( ExprHasProperty(p, EP_xIsSelect) ){
  94463. assert( !ExprHasProperty(p, EP_WinFunc) );
  94464. sqlite3SelectDelete(db, p->x.pSelect);
  94465. }else{
  94466. sqlite3ExprListDelete(db, p->x.pList);
  94467. #ifndef SQLITE_OMIT_WINDOWFUNC
  94468. if( ExprHasProperty(p, EP_WinFunc) ){
  94469. sqlite3WindowDelete(db, p->y.pWin);
  94470. }
  94471. #endif
  94472. }
  94473. }
  94474. if( ExprHasProperty(p, EP_MemToken) ) sqlite3DbFree(db, p->u.zToken);
  94475. if( !ExprHasProperty(p, EP_Static) ){
  94476. sqlite3DbFreeNN(db, p);
  94477. }
  94478. }
  94479. SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){
  94480. if( p ) sqlite3ExprDeleteNN(db, p);
  94481. }
  94482. /* Invoke sqlite3RenameExprUnmap() and sqlite3ExprDelete() on the
  94483. ** expression.
  94484. */
  94485. SQLITE_PRIVATE void sqlite3ExprUnmapAndDelete(Parse *pParse, Expr *p){
  94486. if( p ){
  94487. if( IN_RENAME_OBJECT ){
  94488. sqlite3RenameExprUnmap(pParse, p);
  94489. }
  94490. sqlite3ExprDeleteNN(pParse->db, p);
  94491. }
  94492. }
  94493. /*
  94494. ** Return the number of bytes allocated for the expression structure
  94495. ** passed as the first argument. This is always one of EXPR_FULLSIZE,
  94496. ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
  94497. */
  94498. static int exprStructSize(Expr *p){
  94499. if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
  94500. if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
  94501. return EXPR_FULLSIZE;
  94502. }
  94503. /*
  94504. ** The dupedExpr*Size() routines each return the number of bytes required
  94505. ** to store a copy of an expression or expression tree. They differ in
  94506. ** how much of the tree is measured.
  94507. **
  94508. ** dupedExprStructSize() Size of only the Expr structure
  94509. ** dupedExprNodeSize() Size of Expr + space for token
  94510. ** dupedExprSize() Expr + token + subtree components
  94511. **
  94512. ***************************************************************************
  94513. **
  94514. ** The dupedExprStructSize() function returns two values OR-ed together:
  94515. ** (1) the space required for a copy of the Expr structure only and
  94516. ** (2) the EP_xxx flags that indicate what the structure size should be.
  94517. ** The return values is always one of:
  94518. **
  94519. ** EXPR_FULLSIZE
  94520. ** EXPR_REDUCEDSIZE | EP_Reduced
  94521. ** EXPR_TOKENONLYSIZE | EP_TokenOnly
  94522. **
  94523. ** The size of the structure can be found by masking the return value
  94524. ** of this routine with 0xfff. The flags can be found by masking the
  94525. ** return value with EP_Reduced|EP_TokenOnly.
  94526. **
  94527. ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
  94528. ** (unreduced) Expr objects as they or originally constructed by the parser.
  94529. ** During expression analysis, extra information is computed and moved into
  94530. ** later parts of the Expr object and that extra information might get chopped
  94531. ** off if the expression is reduced. Note also that it does not work to
  94532. ** make an EXPRDUP_REDUCE copy of a reduced expression. It is only legal
  94533. ** to reduce a pristine expression tree from the parser. The implementation
  94534. ** of dupedExprStructSize() contain multiple assert() statements that attempt
  94535. ** to enforce this constraint.
  94536. */
  94537. static int dupedExprStructSize(Expr *p, int flags){
  94538. int nSize;
  94539. assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
  94540. assert( EXPR_FULLSIZE<=0xfff );
  94541. assert( (0xfff & (EP_Reduced|EP_TokenOnly))==0 );
  94542. if( 0==flags || p->op==TK_SELECT_COLUMN
  94543. #ifndef SQLITE_OMIT_WINDOWFUNC
  94544. || ExprHasProperty(p, EP_WinFunc)
  94545. #endif
  94546. ){
  94547. nSize = EXPR_FULLSIZE;
  94548. }else{
  94549. assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
  94550. assert( !ExprHasProperty(p, EP_FromJoin) );
  94551. assert( !ExprHasProperty(p, EP_MemToken) );
  94552. assert( !ExprHasVVAProperty(p, EP_NoReduce) );
  94553. if( p->pLeft || p->x.pList ){
  94554. nSize = EXPR_REDUCEDSIZE | EP_Reduced;
  94555. }else{
  94556. assert( p->pRight==0 );
  94557. nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
  94558. }
  94559. }
  94560. return nSize;
  94561. }
  94562. /*
  94563. ** This function returns the space in bytes required to store the copy
  94564. ** of the Expr structure and a copy of the Expr.u.zToken string (if that
  94565. ** string is defined.)
  94566. */
  94567. static int dupedExprNodeSize(Expr *p, int flags){
  94568. int nByte = dupedExprStructSize(p, flags) & 0xfff;
  94569. if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
  94570. nByte += sqlite3Strlen30NN(p->u.zToken)+1;
  94571. }
  94572. return ROUND8(nByte);
  94573. }
  94574. /*
  94575. ** Return the number of bytes required to create a duplicate of the
  94576. ** expression passed as the first argument. The second argument is a
  94577. ** mask containing EXPRDUP_XXX flags.
  94578. **
  94579. ** The value returned includes space to create a copy of the Expr struct
  94580. ** itself and the buffer referred to by Expr.u.zToken, if any.
  94581. **
  94582. ** If the EXPRDUP_REDUCE flag is set, then the return value includes
  94583. ** space to duplicate all Expr nodes in the tree formed by Expr.pLeft
  94584. ** and Expr.pRight variables (but not for any structures pointed to or
  94585. ** descended from the Expr.x.pList or Expr.x.pSelect variables).
  94586. */
  94587. static int dupedExprSize(Expr *p, int flags){
  94588. int nByte = 0;
  94589. if( p ){
  94590. nByte = dupedExprNodeSize(p, flags);
  94591. if( flags&EXPRDUP_REDUCE ){
  94592. nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
  94593. }
  94594. }
  94595. return nByte;
  94596. }
  94597. /*
  94598. ** This function is similar to sqlite3ExprDup(), except that if pzBuffer
  94599. ** is not NULL then *pzBuffer is assumed to point to a buffer large enough
  94600. ** to store the copy of expression p, the copies of p->u.zToken
  94601. ** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
  94602. ** if any. Before returning, *pzBuffer is set to the first byte past the
  94603. ** portion of the buffer copied into by this function.
  94604. */
  94605. static Expr *exprDup(sqlite3 *db, Expr *p, int dupFlags, u8 **pzBuffer){
  94606. Expr *pNew; /* Value to return */
  94607. u8 *zAlloc; /* Memory space from which to build Expr object */
  94608. u32 staticFlag; /* EP_Static if space not obtained from malloc */
  94609. assert( db!=0 );
  94610. assert( p );
  94611. assert( dupFlags==0 || dupFlags==EXPRDUP_REDUCE );
  94612. assert( pzBuffer==0 || dupFlags==EXPRDUP_REDUCE );
  94613. /* Figure out where to write the new Expr structure. */
  94614. if( pzBuffer ){
  94615. zAlloc = *pzBuffer;
  94616. staticFlag = EP_Static;
  94617. }else{
  94618. zAlloc = sqlite3DbMallocRawNN(db, dupedExprSize(p, dupFlags));
  94619. staticFlag = 0;
  94620. }
  94621. pNew = (Expr *)zAlloc;
  94622. if( pNew ){
  94623. /* Set nNewSize to the size allocated for the structure pointed to
  94624. ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
  94625. ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
  94626. ** by the copy of the p->u.zToken string (if any).
  94627. */
  94628. const unsigned nStructSize = dupedExprStructSize(p, dupFlags);
  94629. const int nNewSize = nStructSize & 0xfff;
  94630. int nToken;
  94631. if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
  94632. nToken = sqlite3Strlen30(p->u.zToken) + 1;
  94633. }else{
  94634. nToken = 0;
  94635. }
  94636. if( dupFlags ){
  94637. assert( ExprHasProperty(p, EP_Reduced)==0 );
  94638. memcpy(zAlloc, p, nNewSize);
  94639. }else{
  94640. u32 nSize = (u32)exprStructSize(p);
  94641. memcpy(zAlloc, p, nSize);
  94642. if( nSize<EXPR_FULLSIZE ){
  94643. memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
  94644. }
  94645. }
  94646. /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
  94647. pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static|EP_MemToken);
  94648. pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
  94649. pNew->flags |= staticFlag;
  94650. ExprClearVVAProperties(pNew);
  94651. if( dupFlags ){
  94652. ExprSetVVAProperty(pNew, EP_Immutable);
  94653. }
  94654. /* Copy the p->u.zToken string, if any. */
  94655. if( nToken ){
  94656. char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
  94657. memcpy(zToken, p->u.zToken, nToken);
  94658. }
  94659. if( 0==((p->flags|pNew->flags) & (EP_TokenOnly|EP_Leaf)) ){
  94660. /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
  94661. if( ExprHasProperty(p, EP_xIsSelect) ){
  94662. pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, dupFlags);
  94663. }else{
  94664. pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, dupFlags);
  94665. }
  94666. }
  94667. /* Fill in pNew->pLeft and pNew->pRight. */
  94668. if( ExprHasProperty(pNew, EP_Reduced|EP_TokenOnly|EP_WinFunc) ){
  94669. zAlloc += dupedExprNodeSize(p, dupFlags);
  94670. if( !ExprHasProperty(pNew, EP_TokenOnly|EP_Leaf) ){
  94671. pNew->pLeft = p->pLeft ?
  94672. exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc) : 0;
  94673. pNew->pRight = p->pRight ?
  94674. exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc) : 0;
  94675. }
  94676. #ifndef SQLITE_OMIT_WINDOWFUNC
  94677. if( ExprHasProperty(p, EP_WinFunc) ){
  94678. pNew->y.pWin = sqlite3WindowDup(db, pNew, p->y.pWin);
  94679. assert( ExprHasProperty(pNew, EP_WinFunc) );
  94680. }
  94681. #endif /* SQLITE_OMIT_WINDOWFUNC */
  94682. if( pzBuffer ){
  94683. *pzBuffer = zAlloc;
  94684. }
  94685. }else{
  94686. if( !ExprHasProperty(p, EP_TokenOnly|EP_Leaf) ){
  94687. if( pNew->op==TK_SELECT_COLUMN ){
  94688. pNew->pLeft = p->pLeft;
  94689. assert( p->iColumn==0 || p->pRight==0 );
  94690. assert( p->pRight==0 || p->pRight==p->pLeft );
  94691. }else{
  94692. pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
  94693. }
  94694. pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
  94695. }
  94696. }
  94697. }
  94698. return pNew;
  94699. }
  94700. /*
  94701. ** Create and return a deep copy of the object passed as the second
  94702. ** argument. If an OOM condition is encountered, NULL is returned
  94703. ** and the db->mallocFailed flag set.
  94704. */
  94705. #ifndef SQLITE_OMIT_CTE
  94706. static With *withDup(sqlite3 *db, With *p){
  94707. With *pRet = 0;
  94708. if( p ){
  94709. sqlite3_int64 nByte = sizeof(*p) + sizeof(p->a[0]) * (p->nCte-1);
  94710. pRet = sqlite3DbMallocZero(db, nByte);
  94711. if( pRet ){
  94712. int i;
  94713. pRet->nCte = p->nCte;
  94714. for(i=0; i<p->nCte; i++){
  94715. pRet->a[i].pSelect = sqlite3SelectDup(db, p->a[i].pSelect, 0);
  94716. pRet->a[i].pCols = sqlite3ExprListDup(db, p->a[i].pCols, 0);
  94717. pRet->a[i].zName = sqlite3DbStrDup(db, p->a[i].zName);
  94718. }
  94719. }
  94720. }
  94721. return pRet;
  94722. }
  94723. #else
  94724. # define withDup(x,y) 0
  94725. #endif
  94726. #ifndef SQLITE_OMIT_WINDOWFUNC
  94727. /*
  94728. ** The gatherSelectWindows() procedure and its helper routine
  94729. ** gatherSelectWindowsCallback() are used to scan all the expressions
  94730. ** an a newly duplicated SELECT statement and gather all of the Window
  94731. ** objects found there, assembling them onto the linked list at Select->pWin.
  94732. */
  94733. static int gatherSelectWindowsCallback(Walker *pWalker, Expr *pExpr){
  94734. if( pExpr->op==TK_FUNCTION && ExprHasProperty(pExpr, EP_WinFunc) ){
  94735. Select *pSelect = pWalker->u.pSelect;
  94736. Window *pWin = pExpr->y.pWin;
  94737. assert( pWin );
  94738. assert( IsWindowFunc(pExpr) );
  94739. assert( pWin->ppThis==0 );
  94740. sqlite3WindowLink(pSelect, pWin);
  94741. }
  94742. return WRC_Continue;
  94743. }
  94744. static int gatherSelectWindowsSelectCallback(Walker *pWalker, Select *p){
  94745. return p==pWalker->u.pSelect ? WRC_Continue : WRC_Prune;
  94746. }
  94747. static void gatherSelectWindows(Select *p){
  94748. Walker w;
  94749. w.xExprCallback = gatherSelectWindowsCallback;
  94750. w.xSelectCallback = gatherSelectWindowsSelectCallback;
  94751. w.xSelectCallback2 = 0;
  94752. w.pParse = 0;
  94753. w.u.pSelect = p;
  94754. sqlite3WalkSelect(&w, p);
  94755. }
  94756. #endif
  94757. /*
  94758. ** The following group of routines make deep copies of expressions,
  94759. ** expression lists, ID lists, and select statements. The copies can
  94760. ** be deleted (by being passed to their respective ...Delete() routines)
  94761. ** without effecting the originals.
  94762. **
  94763. ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
  94764. ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
  94765. ** by subsequent calls to sqlite*ListAppend() routines.
  94766. **
  94767. ** Any tables that the SrcList might point to are not duplicated.
  94768. **
  94769. ** The flags parameter contains a combination of the EXPRDUP_XXX flags.
  94770. ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
  94771. ** truncated version of the usual Expr structure that will be stored as
  94772. ** part of the in-memory representation of the database schema.
  94773. */
  94774. SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
  94775. assert( flags==0 || flags==EXPRDUP_REDUCE );
  94776. return p ? exprDup(db, p, flags, 0) : 0;
  94777. }
  94778. SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
  94779. ExprList *pNew;
  94780. struct ExprList_item *pItem, *pOldItem;
  94781. int i;
  94782. Expr *pPriorSelectCol = 0;
  94783. assert( db!=0 );
  94784. if( p==0 ) return 0;
  94785. pNew = sqlite3DbMallocRawNN(db, sqlite3DbMallocSize(db, p));
  94786. if( pNew==0 ) return 0;
  94787. pNew->nExpr = p->nExpr;
  94788. pItem = pNew->a;
  94789. pOldItem = p->a;
  94790. for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
  94791. Expr *pOldExpr = pOldItem->pExpr;
  94792. Expr *pNewExpr;
  94793. pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
  94794. if( pOldExpr
  94795. && pOldExpr->op==TK_SELECT_COLUMN
  94796. && (pNewExpr = pItem->pExpr)!=0
  94797. ){
  94798. assert( pNewExpr->iColumn==0 || i>0 );
  94799. if( pNewExpr->iColumn==0 ){
  94800. assert( pOldExpr->pLeft==pOldExpr->pRight );
  94801. pPriorSelectCol = pNewExpr->pLeft = pNewExpr->pRight;
  94802. }else{
  94803. assert( i>0 );
  94804. assert( pItem[-1].pExpr!=0 );
  94805. assert( pNewExpr->iColumn==pItem[-1].pExpr->iColumn+1 );
  94806. assert( pPriorSelectCol==pItem[-1].pExpr->pLeft );
  94807. pNewExpr->pLeft = pPriorSelectCol;
  94808. }
  94809. }
  94810. pItem->zEName = sqlite3DbStrDup(db, pOldItem->zEName);
  94811. pItem->sortFlags = pOldItem->sortFlags;
  94812. pItem->eEName = pOldItem->eEName;
  94813. pItem->done = 0;
  94814. pItem->bNulls = pOldItem->bNulls;
  94815. pItem->bSorterRef = pOldItem->bSorterRef;
  94816. pItem->u = pOldItem->u;
  94817. }
  94818. return pNew;
  94819. }
  94820. /*
  94821. ** If cursors, triggers, views and subqueries are all omitted from
  94822. ** the build, then none of the following routines, except for
  94823. ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
  94824. ** called with a NULL argument.
  94825. */
  94826. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
  94827. || !defined(SQLITE_OMIT_SUBQUERY)
  94828. SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
  94829. SrcList *pNew;
  94830. int i;
  94831. int nByte;
  94832. assert( db!=0 );
  94833. if( p==0 ) return 0;
  94834. nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
  94835. pNew = sqlite3DbMallocRawNN(db, nByte );
  94836. if( pNew==0 ) return 0;
  94837. pNew->nSrc = pNew->nAlloc = p->nSrc;
  94838. for(i=0; i<p->nSrc; i++){
  94839. struct SrcList_item *pNewItem = &pNew->a[i];
  94840. struct SrcList_item *pOldItem = &p->a[i];
  94841. Table *pTab;
  94842. pNewItem->pSchema = pOldItem->pSchema;
  94843. pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
  94844. pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
  94845. pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
  94846. pNewItem->fg = pOldItem->fg;
  94847. pNewItem->iCursor = pOldItem->iCursor;
  94848. pNewItem->addrFillSub = pOldItem->addrFillSub;
  94849. pNewItem->regReturn = pOldItem->regReturn;
  94850. if( pNewItem->fg.isIndexedBy ){
  94851. pNewItem->u1.zIndexedBy = sqlite3DbStrDup(db, pOldItem->u1.zIndexedBy);
  94852. }
  94853. pNewItem->pIBIndex = pOldItem->pIBIndex;
  94854. if( pNewItem->fg.isTabFunc ){
  94855. pNewItem->u1.pFuncArg =
  94856. sqlite3ExprListDup(db, pOldItem->u1.pFuncArg, flags);
  94857. }
  94858. pTab = pNewItem->pTab = pOldItem->pTab;
  94859. if( pTab ){
  94860. pTab->nTabRef++;
  94861. }
  94862. pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
  94863. pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
  94864. pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
  94865. pNewItem->colUsed = pOldItem->colUsed;
  94866. }
  94867. return pNew;
  94868. }
  94869. SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
  94870. IdList *pNew;
  94871. int i;
  94872. assert( db!=0 );
  94873. if( p==0 ) return 0;
  94874. pNew = sqlite3DbMallocRawNN(db, sizeof(*pNew) );
  94875. if( pNew==0 ) return 0;
  94876. pNew->nId = p->nId;
  94877. pNew->a = sqlite3DbMallocRawNN(db, p->nId*sizeof(p->a[0]) );
  94878. if( pNew->a==0 ){
  94879. sqlite3DbFreeNN(db, pNew);
  94880. return 0;
  94881. }
  94882. /* Note that because the size of the allocation for p->a[] is not
  94883. ** necessarily a power of two, sqlite3IdListAppend() may not be called
  94884. ** on the duplicate created by this function. */
  94885. for(i=0; i<p->nId; i++){
  94886. struct IdList_item *pNewItem = &pNew->a[i];
  94887. struct IdList_item *pOldItem = &p->a[i];
  94888. pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
  94889. pNewItem->idx = pOldItem->idx;
  94890. }
  94891. return pNew;
  94892. }
  94893. SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *pDup, int flags){
  94894. Select *pRet = 0;
  94895. Select *pNext = 0;
  94896. Select **pp = &pRet;
  94897. Select *p;
  94898. assert( db!=0 );
  94899. for(p=pDup; p; p=p->pPrior){
  94900. Select *pNew = sqlite3DbMallocRawNN(db, sizeof(*p) );
  94901. if( pNew==0 ) break;
  94902. pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
  94903. pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
  94904. pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
  94905. pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
  94906. pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
  94907. pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
  94908. pNew->op = p->op;
  94909. pNew->pNext = pNext;
  94910. pNew->pPrior = 0;
  94911. pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
  94912. pNew->iLimit = 0;
  94913. pNew->iOffset = 0;
  94914. pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
  94915. pNew->addrOpenEphm[0] = -1;
  94916. pNew->addrOpenEphm[1] = -1;
  94917. pNew->nSelectRow = p->nSelectRow;
  94918. pNew->pWith = withDup(db, p->pWith);
  94919. #ifndef SQLITE_OMIT_WINDOWFUNC
  94920. pNew->pWin = 0;
  94921. pNew->pWinDefn = sqlite3WindowListDup(db, p->pWinDefn);
  94922. if( p->pWin && db->mallocFailed==0 ) gatherSelectWindows(pNew);
  94923. #endif
  94924. pNew->selId = p->selId;
  94925. *pp = pNew;
  94926. pp = &pNew->pPrior;
  94927. pNext = pNew;
  94928. }
  94929. return pRet;
  94930. }
  94931. #else
  94932. SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
  94933. assert( p==0 );
  94934. return 0;
  94935. }
  94936. #endif
  94937. /*
  94938. ** Add a new element to the end of an expression list. If pList is
  94939. ** initially NULL, then create a new expression list.
  94940. **
  94941. ** The pList argument must be either NULL or a pointer to an ExprList
  94942. ** obtained from a prior call to sqlite3ExprListAppend(). This routine
  94943. ** may not be used with an ExprList obtained from sqlite3ExprListDup().
  94944. ** Reason: This routine assumes that the number of slots in pList->a[]
  94945. ** is a power of two. That is true for sqlite3ExprListAppend() returns
  94946. ** but is not necessarily true from the return value of sqlite3ExprListDup().
  94947. **
  94948. ** If a memory allocation error occurs, the entire list is freed and
  94949. ** NULL is returned. If non-NULL is returned, then it is guaranteed
  94950. ** that the new entry was successfully appended.
  94951. */
  94952. SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(
  94953. Parse *pParse, /* Parsing context */
  94954. ExprList *pList, /* List to which to append. Might be NULL */
  94955. Expr *pExpr /* Expression to be appended. Might be NULL */
  94956. ){
  94957. struct ExprList_item *pItem;
  94958. sqlite3 *db = pParse->db;
  94959. assert( db!=0 );
  94960. if( pList==0 ){
  94961. pList = sqlite3DbMallocRawNN(db, sizeof(ExprList) );
  94962. if( pList==0 ){
  94963. goto no_mem;
  94964. }
  94965. pList->nExpr = 0;
  94966. }else if( (pList->nExpr & (pList->nExpr-1))==0 ){
  94967. ExprList *pNew;
  94968. pNew = sqlite3DbRealloc(db, pList,
  94969. sizeof(*pList)+(2*(sqlite3_int64)pList->nExpr-1)*sizeof(pList->a[0]));
  94970. if( pNew==0 ){
  94971. goto no_mem;
  94972. }
  94973. pList = pNew;
  94974. }
  94975. pItem = &pList->a[pList->nExpr++];
  94976. assert( offsetof(struct ExprList_item,zEName)==sizeof(pItem->pExpr) );
  94977. assert( offsetof(struct ExprList_item,pExpr)==0 );
  94978. memset(&pItem->zEName,0,sizeof(*pItem)-offsetof(struct ExprList_item,zEName));
  94979. pItem->pExpr = pExpr;
  94980. return pList;
  94981. no_mem:
  94982. /* Avoid leaking memory if malloc has failed. */
  94983. sqlite3ExprDelete(db, pExpr);
  94984. sqlite3ExprListDelete(db, pList);
  94985. return 0;
  94986. }
  94987. /*
  94988. ** pColumns and pExpr form a vector assignment which is part of the SET
  94989. ** clause of an UPDATE statement. Like this:
  94990. **
  94991. ** (a,b,c) = (expr1,expr2,expr3)
  94992. ** Or: (a,b,c) = (SELECT x,y,z FROM ....)
  94993. **
  94994. ** For each term of the vector assignment, append new entries to the
  94995. ** expression list pList. In the case of a subquery on the RHS, append
  94996. ** TK_SELECT_COLUMN expressions.
  94997. */
  94998. SQLITE_PRIVATE ExprList *sqlite3ExprListAppendVector(
  94999. Parse *pParse, /* Parsing context */
  95000. ExprList *pList, /* List to which to append. Might be NULL */
  95001. IdList *pColumns, /* List of names of LHS of the assignment */
  95002. Expr *pExpr /* Vector expression to be appended. Might be NULL */
  95003. ){
  95004. sqlite3 *db = pParse->db;
  95005. int n;
  95006. int i;
  95007. int iFirst = pList ? pList->nExpr : 0;
  95008. /* pColumns can only be NULL due to an OOM but an OOM will cause an
  95009. ** exit prior to this routine being invoked */
  95010. if( NEVER(pColumns==0) ) goto vector_append_error;
  95011. if( pExpr==0 ) goto vector_append_error;
  95012. /* If the RHS is a vector, then we can immediately check to see that
  95013. ** the size of the RHS and LHS match. But if the RHS is a SELECT,
  95014. ** wildcards ("*") in the result set of the SELECT must be expanded before
  95015. ** we can do the size check, so defer the size check until code generation.
  95016. */
  95017. if( pExpr->op!=TK_SELECT && pColumns->nId!=(n=sqlite3ExprVectorSize(pExpr)) ){
  95018. sqlite3ErrorMsg(pParse, "%d columns assigned %d values",
  95019. pColumns->nId, n);
  95020. goto vector_append_error;
  95021. }
  95022. for(i=0; i<pColumns->nId; i++){
  95023. Expr *pSubExpr = sqlite3ExprForVectorField(pParse, pExpr, i);
  95024. assert( pSubExpr!=0 || db->mallocFailed );
  95025. assert( pSubExpr==0 || pSubExpr->iTable==0 );
  95026. if( pSubExpr==0 ) continue;
  95027. pSubExpr->iTable = pColumns->nId;
  95028. pList = sqlite3ExprListAppend(pParse, pList, pSubExpr);
  95029. if( pList ){
  95030. assert( pList->nExpr==iFirst+i+1 );
  95031. pList->a[pList->nExpr-1].zEName = pColumns->a[i].zName;
  95032. pColumns->a[i].zName = 0;
  95033. }
  95034. }
  95035. if( !db->mallocFailed && pExpr->op==TK_SELECT && ALWAYS(pList!=0) ){
  95036. Expr *pFirst = pList->a[iFirst].pExpr;
  95037. assert( pFirst!=0 );
  95038. assert( pFirst->op==TK_SELECT_COLUMN );
  95039. /* Store the SELECT statement in pRight so it will be deleted when
  95040. ** sqlite3ExprListDelete() is called */
  95041. pFirst->pRight = pExpr;
  95042. pExpr = 0;
  95043. /* Remember the size of the LHS in iTable so that we can check that
  95044. ** the RHS and LHS sizes match during code generation. */
  95045. pFirst->iTable = pColumns->nId;
  95046. }
  95047. vector_append_error:
  95048. sqlite3ExprUnmapAndDelete(pParse, pExpr);
  95049. sqlite3IdListDelete(db, pColumns);
  95050. return pList;
  95051. }
  95052. /*
  95053. ** Set the sort order for the last element on the given ExprList.
  95054. */
  95055. SQLITE_PRIVATE void sqlite3ExprListSetSortOrder(ExprList *p, int iSortOrder, int eNulls){
  95056. struct ExprList_item *pItem;
  95057. if( p==0 ) return;
  95058. assert( p->nExpr>0 );
  95059. assert( SQLITE_SO_UNDEFINED<0 && SQLITE_SO_ASC==0 && SQLITE_SO_DESC>0 );
  95060. assert( iSortOrder==SQLITE_SO_UNDEFINED
  95061. || iSortOrder==SQLITE_SO_ASC
  95062. || iSortOrder==SQLITE_SO_DESC
  95063. );
  95064. assert( eNulls==SQLITE_SO_UNDEFINED
  95065. || eNulls==SQLITE_SO_ASC
  95066. || eNulls==SQLITE_SO_DESC
  95067. );
  95068. pItem = &p->a[p->nExpr-1];
  95069. assert( pItem->bNulls==0 );
  95070. if( iSortOrder==SQLITE_SO_UNDEFINED ){
  95071. iSortOrder = SQLITE_SO_ASC;
  95072. }
  95073. pItem->sortFlags = (u8)iSortOrder;
  95074. if( eNulls!=SQLITE_SO_UNDEFINED ){
  95075. pItem->bNulls = 1;
  95076. if( iSortOrder!=eNulls ){
  95077. pItem->sortFlags |= KEYINFO_ORDER_BIGNULL;
  95078. }
  95079. }
  95080. }
  95081. /*
  95082. ** Set the ExprList.a[].zEName element of the most recently added item
  95083. ** on the expression list.
  95084. **
  95085. ** pList might be NULL following an OOM error. But pName should never be
  95086. ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
  95087. ** is set.
  95088. */
  95089. SQLITE_PRIVATE void sqlite3ExprListSetName(
  95090. Parse *pParse, /* Parsing context */
  95091. ExprList *pList, /* List to which to add the span. */
  95092. Token *pName, /* Name to be added */
  95093. int dequote /* True to cause the name to be dequoted */
  95094. ){
  95095. assert( pList!=0 || pParse->db->mallocFailed!=0 );
  95096. assert( pParse->eParseMode!=PARSE_MODE_UNMAP || dequote==0 );
  95097. if( pList ){
  95098. struct ExprList_item *pItem;
  95099. assert( pList->nExpr>0 );
  95100. pItem = &pList->a[pList->nExpr-1];
  95101. assert( pItem->zEName==0 );
  95102. assert( pItem->eEName==ENAME_NAME );
  95103. pItem->zEName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
  95104. if( dequote ){
  95105. /* If dequote==0, then pName->z does not point to part of a DDL
  95106. ** statement handled by the parser. And so no token need be added
  95107. ** to the token-map. */
  95108. sqlite3Dequote(pItem->zEName);
  95109. if( IN_RENAME_OBJECT ){
  95110. sqlite3RenameTokenMap(pParse, (void*)pItem->zEName, pName);
  95111. }
  95112. }
  95113. }
  95114. }
  95115. /*
  95116. ** Set the ExprList.a[].zSpan element of the most recently added item
  95117. ** on the expression list.
  95118. **
  95119. ** pList might be NULL following an OOM error. But pSpan should never be
  95120. ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
  95121. ** is set.
  95122. */
  95123. SQLITE_PRIVATE void sqlite3ExprListSetSpan(
  95124. Parse *pParse, /* Parsing context */
  95125. ExprList *pList, /* List to which to add the span. */
  95126. const char *zStart, /* Start of the span */
  95127. const char *zEnd /* End of the span */
  95128. ){
  95129. sqlite3 *db = pParse->db;
  95130. assert( pList!=0 || db->mallocFailed!=0 );
  95131. if( pList ){
  95132. struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
  95133. assert( pList->nExpr>0 );
  95134. if( pItem->zEName==0 ){
  95135. pItem->zEName = sqlite3DbSpanDup(db, zStart, zEnd);
  95136. pItem->eEName = ENAME_SPAN;
  95137. }
  95138. }
  95139. }
  95140. /*
  95141. ** If the expression list pEList contains more than iLimit elements,
  95142. ** leave an error message in pParse.
  95143. */
  95144. SQLITE_PRIVATE void sqlite3ExprListCheckLength(
  95145. Parse *pParse,
  95146. ExprList *pEList,
  95147. const char *zObject
  95148. ){
  95149. int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
  95150. testcase( pEList && pEList->nExpr==mx );
  95151. testcase( pEList && pEList->nExpr==mx+1 );
  95152. if( pEList && pEList->nExpr>mx ){
  95153. sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
  95154. }
  95155. }
  95156. /*
  95157. ** Delete an entire expression list.
  95158. */
  95159. static SQLITE_NOINLINE void exprListDeleteNN(sqlite3 *db, ExprList *pList){
  95160. int i = pList->nExpr;
  95161. struct ExprList_item *pItem = pList->a;
  95162. assert( pList->nExpr>0 );
  95163. do{
  95164. sqlite3ExprDelete(db, pItem->pExpr);
  95165. sqlite3DbFree(db, pItem->zEName);
  95166. pItem++;
  95167. }while( --i>0 );
  95168. sqlite3DbFreeNN(db, pList);
  95169. }
  95170. SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
  95171. if( pList ) exprListDeleteNN(db, pList);
  95172. }
  95173. /*
  95174. ** Return the bitwise-OR of all Expr.flags fields in the given
  95175. ** ExprList.
  95176. */
  95177. SQLITE_PRIVATE u32 sqlite3ExprListFlags(const ExprList *pList){
  95178. int i;
  95179. u32 m = 0;
  95180. assert( pList!=0 );
  95181. for(i=0; i<pList->nExpr; i++){
  95182. Expr *pExpr = pList->a[i].pExpr;
  95183. assert( pExpr!=0 );
  95184. m |= pExpr->flags;
  95185. }
  95186. return m;
  95187. }
  95188. /*
  95189. ** This is a SELECT-node callback for the expression walker that
  95190. ** always "fails". By "fail" in this case, we mean set
  95191. ** pWalker->eCode to zero and abort.
  95192. **
  95193. ** This callback is used by multiple expression walkers.
  95194. */
  95195. SQLITE_PRIVATE int sqlite3SelectWalkFail(Walker *pWalker, Select *NotUsed){
  95196. UNUSED_PARAMETER(NotUsed);
  95197. pWalker->eCode = 0;
  95198. return WRC_Abort;
  95199. }
  95200. /*
  95201. ** Check the input string to see if it is "true" or "false" (in any case).
  95202. **
  95203. ** If the string is.... Return
  95204. ** "true" EP_IsTrue
  95205. ** "false" EP_IsFalse
  95206. ** anything else 0
  95207. */
  95208. SQLITE_PRIVATE u32 sqlite3IsTrueOrFalse(const char *zIn){
  95209. if( sqlite3StrICmp(zIn, "true")==0 ) return EP_IsTrue;
  95210. if( sqlite3StrICmp(zIn, "false")==0 ) return EP_IsFalse;
  95211. return 0;
  95212. }
  95213. /*
  95214. ** If the input expression is an ID with the name "true" or "false"
  95215. ** then convert it into an TK_TRUEFALSE term. Return non-zero if
  95216. ** the conversion happened, and zero if the expression is unaltered.
  95217. */
  95218. SQLITE_PRIVATE int sqlite3ExprIdToTrueFalse(Expr *pExpr){
  95219. u32 v;
  95220. assert( pExpr->op==TK_ID || pExpr->op==TK_STRING );
  95221. if( !ExprHasProperty(pExpr, EP_Quoted)
  95222. && (v = sqlite3IsTrueOrFalse(pExpr->u.zToken))!=0
  95223. ){
  95224. pExpr->op = TK_TRUEFALSE;
  95225. ExprSetProperty(pExpr, v);
  95226. return 1;
  95227. }
  95228. return 0;
  95229. }
  95230. /*
  95231. ** The argument must be a TK_TRUEFALSE Expr node. Return 1 if it is TRUE
  95232. ** and 0 if it is FALSE.
  95233. */
  95234. SQLITE_PRIVATE int sqlite3ExprTruthValue(const Expr *pExpr){
  95235. pExpr = sqlite3ExprSkipCollate((Expr*)pExpr);
  95236. assert( pExpr->op==TK_TRUEFALSE );
  95237. assert( sqlite3StrICmp(pExpr->u.zToken,"true")==0
  95238. || sqlite3StrICmp(pExpr->u.zToken,"false")==0 );
  95239. return pExpr->u.zToken[4]==0;
  95240. }
  95241. /*
  95242. ** If pExpr is an AND or OR expression, try to simplify it by eliminating
  95243. ** terms that are always true or false. Return the simplified expression.
  95244. ** Or return the original expression if no simplification is possible.
  95245. **
  95246. ** Examples:
  95247. **
  95248. ** (x<10) AND true => (x<10)
  95249. ** (x<10) AND false => false
  95250. ** (x<10) AND (y=22 OR false) => (x<10) AND (y=22)
  95251. ** (x<10) AND (y=22 OR true) => (x<10)
  95252. ** (y=22) OR true => true
  95253. */
  95254. SQLITE_PRIVATE Expr *sqlite3ExprSimplifiedAndOr(Expr *pExpr){
  95255. assert( pExpr!=0 );
  95256. if( pExpr->op==TK_AND || pExpr->op==TK_OR ){
  95257. Expr *pRight = sqlite3ExprSimplifiedAndOr(pExpr->pRight);
  95258. Expr *pLeft = sqlite3ExprSimplifiedAndOr(pExpr->pLeft);
  95259. if( ExprAlwaysTrue(pLeft) || ExprAlwaysFalse(pRight) ){
  95260. pExpr = pExpr->op==TK_AND ? pRight : pLeft;
  95261. }else if( ExprAlwaysTrue(pRight) || ExprAlwaysFalse(pLeft) ){
  95262. pExpr = pExpr->op==TK_AND ? pLeft : pRight;
  95263. }
  95264. }
  95265. return pExpr;
  95266. }
  95267. /*
  95268. ** These routines are Walker callbacks used to check expressions to
  95269. ** see if they are "constant" for some definition of constant. The
  95270. ** Walker.eCode value determines the type of "constant" we are looking
  95271. ** for.
  95272. **
  95273. ** These callback routines are used to implement the following:
  95274. **
  95275. ** sqlite3ExprIsConstant() pWalker->eCode==1
  95276. ** sqlite3ExprIsConstantNotJoin() pWalker->eCode==2
  95277. ** sqlite3ExprIsTableConstant() pWalker->eCode==3
  95278. ** sqlite3ExprIsConstantOrFunction() pWalker->eCode==4 or 5
  95279. **
  95280. ** In all cases, the callbacks set Walker.eCode=0 and abort if the expression
  95281. ** is found to not be a constant.
  95282. **
  95283. ** The sqlite3ExprIsConstantOrFunction() is used for evaluating DEFAULT
  95284. ** expressions in a CREATE TABLE statement. The Walker.eCode value is 5
  95285. ** when parsing an existing schema out of the sqlite_master table and 4
  95286. ** when processing a new CREATE TABLE statement. A bound parameter raises
  95287. ** an error for new statements, but is silently converted
  95288. ** to NULL for existing schemas. This allows sqlite_master tables that
  95289. ** contain a bound parameter because they were generated by older versions
  95290. ** of SQLite to be parsed by newer versions of SQLite without raising a
  95291. ** malformed schema error.
  95292. */
  95293. static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
  95294. /* If pWalker->eCode is 2 then any term of the expression that comes from
  95295. ** the ON or USING clauses of a left join disqualifies the expression
  95296. ** from being considered constant. */
  95297. if( pWalker->eCode==2 && ExprHasProperty(pExpr, EP_FromJoin) ){
  95298. pWalker->eCode = 0;
  95299. return WRC_Abort;
  95300. }
  95301. switch( pExpr->op ){
  95302. /* Consider functions to be constant if all their arguments are constant
  95303. ** and either pWalker->eCode==4 or 5 or the function has the
  95304. ** SQLITE_FUNC_CONST flag. */
  95305. case TK_FUNCTION:
  95306. if( (pWalker->eCode>=4 || ExprHasProperty(pExpr,EP_ConstFunc))
  95307. && !ExprHasProperty(pExpr, EP_WinFunc)
  95308. ){
  95309. if( pWalker->eCode==5 ) ExprSetProperty(pExpr, EP_FromDDL);
  95310. return WRC_Continue;
  95311. }else{
  95312. pWalker->eCode = 0;
  95313. return WRC_Abort;
  95314. }
  95315. case TK_ID:
  95316. /* Convert "true" or "false" in a DEFAULT clause into the
  95317. ** appropriate TK_TRUEFALSE operator */
  95318. if( sqlite3ExprIdToTrueFalse(pExpr) ){
  95319. return WRC_Prune;
  95320. }
  95321. /* Fall thru */
  95322. case TK_COLUMN:
  95323. case TK_AGG_FUNCTION:
  95324. case TK_AGG_COLUMN:
  95325. testcase( pExpr->op==TK_ID );
  95326. testcase( pExpr->op==TK_COLUMN );
  95327. testcase( pExpr->op==TK_AGG_FUNCTION );
  95328. testcase( pExpr->op==TK_AGG_COLUMN );
  95329. if( ExprHasProperty(pExpr, EP_FixedCol) && pWalker->eCode!=2 ){
  95330. return WRC_Continue;
  95331. }
  95332. if( pWalker->eCode==3 && pExpr->iTable==pWalker->u.iCur ){
  95333. return WRC_Continue;
  95334. }
  95335. /* Fall through */
  95336. case TK_IF_NULL_ROW:
  95337. case TK_REGISTER:
  95338. testcase( pExpr->op==TK_REGISTER );
  95339. testcase( pExpr->op==TK_IF_NULL_ROW );
  95340. pWalker->eCode = 0;
  95341. return WRC_Abort;
  95342. case TK_VARIABLE:
  95343. if( pWalker->eCode==5 ){
  95344. /* Silently convert bound parameters that appear inside of CREATE
  95345. ** statements into a NULL when parsing the CREATE statement text out
  95346. ** of the sqlite_master table */
  95347. pExpr->op = TK_NULL;
  95348. }else if( pWalker->eCode==4 ){
  95349. /* A bound parameter in a CREATE statement that originates from
  95350. ** sqlite3_prepare() causes an error */
  95351. pWalker->eCode = 0;
  95352. return WRC_Abort;
  95353. }
  95354. /* Fall through */
  95355. default:
  95356. testcase( pExpr->op==TK_SELECT ); /* sqlite3SelectWalkFail() disallows */
  95357. testcase( pExpr->op==TK_EXISTS ); /* sqlite3SelectWalkFail() disallows */
  95358. return WRC_Continue;
  95359. }
  95360. }
  95361. static int exprIsConst(Expr *p, int initFlag, int iCur){
  95362. Walker w;
  95363. w.eCode = initFlag;
  95364. w.xExprCallback = exprNodeIsConstant;
  95365. w.xSelectCallback = sqlite3SelectWalkFail;
  95366. #ifdef SQLITE_DEBUG
  95367. w.xSelectCallback2 = sqlite3SelectWalkAssert2;
  95368. #endif
  95369. w.u.iCur = iCur;
  95370. sqlite3WalkExpr(&w, p);
  95371. return w.eCode;
  95372. }
  95373. /*
  95374. ** Walk an expression tree. Return non-zero if the expression is constant
  95375. ** and 0 if it involves variables or function calls.
  95376. **
  95377. ** For the purposes of this function, a double-quoted string (ex: "abc")
  95378. ** is considered a variable but a single-quoted string (ex: 'abc') is
  95379. ** a constant.
  95380. */
  95381. SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){
  95382. return exprIsConst(p, 1, 0);
  95383. }
  95384. /*
  95385. ** Walk an expression tree. Return non-zero if
  95386. **
  95387. ** (1) the expression is constant, and
  95388. ** (2) the expression does originate in the ON or USING clause
  95389. ** of a LEFT JOIN, and
  95390. ** (3) the expression does not contain any EP_FixedCol TK_COLUMN
  95391. ** operands created by the constant propagation optimization.
  95392. **
  95393. ** When this routine returns true, it indicates that the expression
  95394. ** can be added to the pParse->pConstExpr list and evaluated once when
  95395. ** the prepared statement starts up. See sqlite3ExprCodeRunJustOnce().
  95396. */
  95397. SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){
  95398. return exprIsConst(p, 2, 0);
  95399. }
  95400. /*
  95401. ** Walk an expression tree. Return non-zero if the expression is constant
  95402. ** for any single row of the table with cursor iCur. In other words, the
  95403. ** expression must not refer to any non-deterministic function nor any
  95404. ** table other than iCur.
  95405. */
  95406. SQLITE_PRIVATE int sqlite3ExprIsTableConstant(Expr *p, int iCur){
  95407. return exprIsConst(p, 3, iCur);
  95408. }
  95409. /*
  95410. ** sqlite3WalkExpr() callback used by sqlite3ExprIsConstantOrGroupBy().
  95411. */
  95412. static int exprNodeIsConstantOrGroupBy(Walker *pWalker, Expr *pExpr){
  95413. ExprList *pGroupBy = pWalker->u.pGroupBy;
  95414. int i;
  95415. /* Check if pExpr is identical to any GROUP BY term. If so, consider
  95416. ** it constant. */
  95417. for(i=0; i<pGroupBy->nExpr; i++){
  95418. Expr *p = pGroupBy->a[i].pExpr;
  95419. if( sqlite3ExprCompare(0, pExpr, p, -1)<2 ){
  95420. CollSeq *pColl = sqlite3ExprNNCollSeq(pWalker->pParse, p);
  95421. if( sqlite3IsBinary(pColl) ){
  95422. return WRC_Prune;
  95423. }
  95424. }
  95425. }
  95426. /* Check if pExpr is a sub-select. If so, consider it variable. */
  95427. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  95428. pWalker->eCode = 0;
  95429. return WRC_Abort;
  95430. }
  95431. return exprNodeIsConstant(pWalker, pExpr);
  95432. }
  95433. /*
  95434. ** Walk the expression tree passed as the first argument. Return non-zero
  95435. ** if the expression consists entirely of constants or copies of terms
  95436. ** in pGroupBy that sort with the BINARY collation sequence.
  95437. **
  95438. ** This routine is used to determine if a term of the HAVING clause can
  95439. ** be promoted into the WHERE clause. In order for such a promotion to work,
  95440. ** the value of the HAVING clause term must be the same for all members of
  95441. ** a "group". The requirement that the GROUP BY term must be BINARY
  95442. ** assumes that no other collating sequence will have a finer-grained
  95443. ** grouping than binary. In other words (A=B COLLATE binary) implies
  95444. ** A=B in every other collating sequence. The requirement that the
  95445. ** GROUP BY be BINARY is stricter than necessary. It would also work
  95446. ** to promote HAVING clauses that use the same alternative collating
  95447. ** sequence as the GROUP BY term, but that is much harder to check,
  95448. ** alternative collating sequences are uncommon, and this is only an
  95449. ** optimization, so we take the easy way out and simply require the
  95450. ** GROUP BY to use the BINARY collating sequence.
  95451. */
  95452. SQLITE_PRIVATE int sqlite3ExprIsConstantOrGroupBy(Parse *pParse, Expr *p, ExprList *pGroupBy){
  95453. Walker w;
  95454. w.eCode = 1;
  95455. w.xExprCallback = exprNodeIsConstantOrGroupBy;
  95456. w.xSelectCallback = 0;
  95457. w.u.pGroupBy = pGroupBy;
  95458. w.pParse = pParse;
  95459. sqlite3WalkExpr(&w, p);
  95460. return w.eCode;
  95461. }
  95462. /*
  95463. ** Walk an expression tree for the DEFAULT field of a column definition
  95464. ** in a CREATE TABLE statement. Return non-zero if the expression is
  95465. ** acceptable for use as a DEFAULT. That is to say, return non-zero if
  95466. ** the expression is constant or a function call with constant arguments.
  95467. ** Return and 0 if there are any variables.
  95468. **
  95469. ** isInit is true when parsing from sqlite_master. isInit is false when
  95470. ** processing a new CREATE TABLE statement. When isInit is true, parameters
  95471. ** (such as ? or $abc) in the expression are converted into NULL. When
  95472. ** isInit is false, parameters raise an error. Parameters should not be
  95473. ** allowed in a CREATE TABLE statement, but some legacy versions of SQLite
  95474. ** allowed it, so we need to support it when reading sqlite_master for
  95475. ** backwards compatibility.
  95476. **
  95477. ** If isInit is true, set EP_FromDDL on every TK_FUNCTION node.
  95478. **
  95479. ** For the purposes of this function, a double-quoted string (ex: "abc")
  95480. ** is considered a variable but a single-quoted string (ex: 'abc') is
  95481. ** a constant.
  95482. */
  95483. SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p, u8 isInit){
  95484. assert( isInit==0 || isInit==1 );
  95485. return exprIsConst(p, 4+isInit, 0);
  95486. }
  95487. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  95488. /*
  95489. ** Walk an expression tree. Return 1 if the expression contains a
  95490. ** subquery of some kind. Return 0 if there are no subqueries.
  95491. */
  95492. SQLITE_PRIVATE int sqlite3ExprContainsSubquery(Expr *p){
  95493. Walker w;
  95494. w.eCode = 1;
  95495. w.xExprCallback = sqlite3ExprWalkNoop;
  95496. w.xSelectCallback = sqlite3SelectWalkFail;
  95497. #ifdef SQLITE_DEBUG
  95498. w.xSelectCallback2 = sqlite3SelectWalkAssert2;
  95499. #endif
  95500. sqlite3WalkExpr(&w, p);
  95501. return w.eCode==0;
  95502. }
  95503. #endif
  95504. /*
  95505. ** If the expression p codes a constant integer that is small enough
  95506. ** to fit in a 32-bit integer, return 1 and put the value of the integer
  95507. ** in *pValue. If the expression is not an integer or if it is too big
  95508. ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
  95509. */
  95510. SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){
  95511. int rc = 0;
  95512. if( NEVER(p==0) ) return 0; /* Used to only happen following on OOM */
  95513. /* If an expression is an integer literal that fits in a signed 32-bit
  95514. ** integer, then the EP_IntValue flag will have already been set */
  95515. assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
  95516. || sqlite3GetInt32(p->u.zToken, &rc)==0 );
  95517. if( p->flags & EP_IntValue ){
  95518. *pValue = p->u.iValue;
  95519. return 1;
  95520. }
  95521. switch( p->op ){
  95522. case TK_UPLUS: {
  95523. rc = sqlite3ExprIsInteger(p->pLeft, pValue);
  95524. break;
  95525. }
  95526. case TK_UMINUS: {
  95527. int v;
  95528. if( sqlite3ExprIsInteger(p->pLeft, &v) ){
  95529. assert( v!=(-2147483647-1) );
  95530. *pValue = -v;
  95531. rc = 1;
  95532. }
  95533. break;
  95534. }
  95535. default: break;
  95536. }
  95537. return rc;
  95538. }
  95539. /*
  95540. ** Return FALSE if there is no chance that the expression can be NULL.
  95541. **
  95542. ** If the expression might be NULL or if the expression is too complex
  95543. ** to tell return TRUE.
  95544. **
  95545. ** This routine is used as an optimization, to skip OP_IsNull opcodes
  95546. ** when we know that a value cannot be NULL. Hence, a false positive
  95547. ** (returning TRUE when in fact the expression can never be NULL) might
  95548. ** be a small performance hit but is otherwise harmless. On the other
  95549. ** hand, a false negative (returning FALSE when the result could be NULL)
  95550. ** will likely result in an incorrect answer. So when in doubt, return
  95551. ** TRUE.
  95552. */
  95553. SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr *p){
  95554. u8 op;
  95555. while( p->op==TK_UPLUS || p->op==TK_UMINUS ){
  95556. p = p->pLeft;
  95557. }
  95558. op = p->op;
  95559. if( op==TK_REGISTER ) op = p->op2;
  95560. switch( op ){
  95561. case TK_INTEGER:
  95562. case TK_STRING:
  95563. case TK_FLOAT:
  95564. case TK_BLOB:
  95565. return 0;
  95566. case TK_COLUMN:
  95567. return ExprHasProperty(p, EP_CanBeNull) ||
  95568. p->y.pTab==0 || /* Reference to column of index on expression */
  95569. (p->iColumn>=0
  95570. && ALWAYS(p->y.pTab->aCol!=0) /* Defense against OOM problems */
  95571. && p->y.pTab->aCol[p->iColumn].notNull==0);
  95572. default:
  95573. return 1;
  95574. }
  95575. }
  95576. /*
  95577. ** Return TRUE if the given expression is a constant which would be
  95578. ** unchanged by OP_Affinity with the affinity given in the second
  95579. ** argument.
  95580. **
  95581. ** This routine is used to determine if the OP_Affinity operation
  95582. ** can be omitted. When in doubt return FALSE. A false negative
  95583. ** is harmless. A false positive, however, can result in the wrong
  95584. ** answer.
  95585. */
  95586. SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
  95587. u8 op;
  95588. int unaryMinus = 0;
  95589. if( aff==SQLITE_AFF_BLOB ) return 1;
  95590. while( p->op==TK_UPLUS || p->op==TK_UMINUS ){
  95591. if( p->op==TK_UMINUS ) unaryMinus = 1;
  95592. p = p->pLeft;
  95593. }
  95594. op = p->op;
  95595. if( op==TK_REGISTER ) op = p->op2;
  95596. switch( op ){
  95597. case TK_INTEGER: {
  95598. return aff>=SQLITE_AFF_NUMERIC;
  95599. }
  95600. case TK_FLOAT: {
  95601. return aff>=SQLITE_AFF_NUMERIC;
  95602. }
  95603. case TK_STRING: {
  95604. return !unaryMinus && aff==SQLITE_AFF_TEXT;
  95605. }
  95606. case TK_BLOB: {
  95607. return !unaryMinus;
  95608. }
  95609. case TK_COLUMN: {
  95610. assert( p->iTable>=0 ); /* p cannot be part of a CHECK constraint */
  95611. return aff>=SQLITE_AFF_NUMERIC && p->iColumn<0;
  95612. }
  95613. default: {
  95614. return 0;
  95615. }
  95616. }
  95617. }
  95618. /*
  95619. ** Return TRUE if the given string is a row-id column name.
  95620. */
  95621. SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
  95622. if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
  95623. if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
  95624. if( sqlite3StrICmp(z, "OID")==0 ) return 1;
  95625. return 0;
  95626. }
  95627. /*
  95628. ** pX is the RHS of an IN operator. If pX is a SELECT statement
  95629. ** that can be simplified to a direct table access, then return
  95630. ** a pointer to the SELECT statement. If pX is not a SELECT statement,
  95631. ** or if the SELECT statement needs to be manifested into a transient
  95632. ** table, then return NULL.
  95633. */
  95634. #ifndef SQLITE_OMIT_SUBQUERY
  95635. static Select *isCandidateForInOpt(Expr *pX){
  95636. Select *p;
  95637. SrcList *pSrc;
  95638. ExprList *pEList;
  95639. Table *pTab;
  95640. int i;
  95641. if( !ExprHasProperty(pX, EP_xIsSelect) ) return 0; /* Not a subquery */
  95642. if( ExprHasProperty(pX, EP_VarSelect) ) return 0; /* Correlated subq */
  95643. p = pX->x.pSelect;
  95644. if( p->pPrior ) return 0; /* Not a compound SELECT */
  95645. if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
  95646. testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
  95647. testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
  95648. return 0; /* No DISTINCT keyword and no aggregate functions */
  95649. }
  95650. assert( p->pGroupBy==0 ); /* Has no GROUP BY clause */
  95651. if( p->pLimit ) return 0; /* Has no LIMIT clause */
  95652. if( p->pWhere ) return 0; /* Has no WHERE clause */
  95653. pSrc = p->pSrc;
  95654. assert( pSrc!=0 );
  95655. if( pSrc->nSrc!=1 ) return 0; /* Single term in FROM clause */
  95656. if( pSrc->a[0].pSelect ) return 0; /* FROM is not a subquery or view */
  95657. pTab = pSrc->a[0].pTab;
  95658. assert( pTab!=0 );
  95659. assert( pTab->pSelect==0 ); /* FROM clause is not a view */
  95660. if( IsVirtual(pTab) ) return 0; /* FROM clause not a virtual table */
  95661. pEList = p->pEList;
  95662. assert( pEList!=0 );
  95663. /* All SELECT results must be columns. */
  95664. for(i=0; i<pEList->nExpr; i++){
  95665. Expr *pRes = pEList->a[i].pExpr;
  95666. if( pRes->op!=TK_COLUMN ) return 0;
  95667. assert( pRes->iTable==pSrc->a[0].iCursor ); /* Not a correlated subquery */
  95668. }
  95669. return p;
  95670. }
  95671. #endif /* SQLITE_OMIT_SUBQUERY */
  95672. #ifndef SQLITE_OMIT_SUBQUERY
  95673. /*
  95674. ** Generate code that checks the left-most column of index table iCur to see if
  95675. ** it contains any NULL entries. Cause the register at regHasNull to be set
  95676. ** to a non-NULL value if iCur contains no NULLs. Cause register regHasNull
  95677. ** to be set to NULL if iCur contains one or more NULL values.
  95678. */
  95679. static void sqlite3SetHasNullFlag(Vdbe *v, int iCur, int regHasNull){
  95680. int addr1;
  95681. sqlite3VdbeAddOp2(v, OP_Integer, 0, regHasNull);
  95682. addr1 = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v);
  95683. sqlite3VdbeAddOp3(v, OP_Column, iCur, 0, regHasNull);
  95684. sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
  95685. VdbeComment((v, "first_entry_in(%d)", iCur));
  95686. sqlite3VdbeJumpHere(v, addr1);
  95687. }
  95688. #endif
  95689. #ifndef SQLITE_OMIT_SUBQUERY
  95690. /*
  95691. ** The argument is an IN operator with a list (not a subquery) on the
  95692. ** right-hand side. Return TRUE if that list is constant.
  95693. */
  95694. static int sqlite3InRhsIsConstant(Expr *pIn){
  95695. Expr *pLHS;
  95696. int res;
  95697. assert( !ExprHasProperty(pIn, EP_xIsSelect) );
  95698. pLHS = pIn->pLeft;
  95699. pIn->pLeft = 0;
  95700. res = sqlite3ExprIsConstant(pIn);
  95701. pIn->pLeft = pLHS;
  95702. return res;
  95703. }
  95704. #endif
  95705. /*
  95706. ** This function is used by the implementation of the IN (...) operator.
  95707. ** The pX parameter is the expression on the RHS of the IN operator, which
  95708. ** might be either a list of expressions or a subquery.
  95709. **
  95710. ** The job of this routine is to find or create a b-tree object that can
  95711. ** be used either to test for membership in the RHS set or to iterate through
  95712. ** all members of the RHS set, skipping duplicates.
  95713. **
  95714. ** A cursor is opened on the b-tree object that is the RHS of the IN operator
  95715. ** and pX->iTable is set to the index of that cursor.
  95716. **
  95717. ** The returned value of this function indicates the b-tree type, as follows:
  95718. **
  95719. ** IN_INDEX_ROWID - The cursor was opened on a database table.
  95720. ** IN_INDEX_INDEX_ASC - The cursor was opened on an ascending index.
  95721. ** IN_INDEX_INDEX_DESC - The cursor was opened on a descending index.
  95722. ** IN_INDEX_EPH - The cursor was opened on a specially created and
  95723. ** populated epheremal table.
  95724. ** IN_INDEX_NOOP - No cursor was allocated. The IN operator must be
  95725. ** implemented as a sequence of comparisons.
  95726. **
  95727. ** An existing b-tree might be used if the RHS expression pX is a simple
  95728. ** subquery such as:
  95729. **
  95730. ** SELECT <column1>, <column2>... FROM <table>
  95731. **
  95732. ** If the RHS of the IN operator is a list or a more complex subquery, then
  95733. ** an ephemeral table might need to be generated from the RHS and then
  95734. ** pX->iTable made to point to the ephemeral table instead of an
  95735. ** existing table.
  95736. **
  95737. ** The inFlags parameter must contain, at a minimum, one of the bits
  95738. ** IN_INDEX_MEMBERSHIP or IN_INDEX_LOOP but not both. If inFlags contains
  95739. ** IN_INDEX_MEMBERSHIP, then the generated table will be used for a fast
  95740. ** membership test. When the IN_INDEX_LOOP bit is set, the IN index will
  95741. ** be used to loop over all values of the RHS of the IN operator.
  95742. **
  95743. ** When IN_INDEX_LOOP is used (and the b-tree will be used to iterate
  95744. ** through the set members) then the b-tree must not contain duplicates.
  95745. ** An epheremal table will be created unless the selected columns are guaranteed
  95746. ** to be unique - either because it is an INTEGER PRIMARY KEY or due to
  95747. ** a UNIQUE constraint or index.
  95748. **
  95749. ** When IN_INDEX_MEMBERSHIP is used (and the b-tree will be used
  95750. ** for fast set membership tests) then an epheremal table must
  95751. ** be used unless <columns> is a single INTEGER PRIMARY KEY column or an
  95752. ** index can be found with the specified <columns> as its left-most.
  95753. **
  95754. ** If the IN_INDEX_NOOP_OK and IN_INDEX_MEMBERSHIP are both set and
  95755. ** if the RHS of the IN operator is a list (not a subquery) then this
  95756. ** routine might decide that creating an ephemeral b-tree for membership
  95757. ** testing is too expensive and return IN_INDEX_NOOP. In that case, the
  95758. ** calling routine should implement the IN operator using a sequence
  95759. ** of Eq or Ne comparison operations.
  95760. **
  95761. ** When the b-tree is being used for membership tests, the calling function
  95762. ** might need to know whether or not the RHS side of the IN operator
  95763. ** contains a NULL. If prRhsHasNull is not a NULL pointer and
  95764. ** if there is any chance that the (...) might contain a NULL value at
  95765. ** runtime, then a register is allocated and the register number written
  95766. ** to *prRhsHasNull. If there is no chance that the (...) contains a
  95767. ** NULL value, then *prRhsHasNull is left unchanged.
  95768. **
  95769. ** If a register is allocated and its location stored in *prRhsHasNull, then
  95770. ** the value in that register will be NULL if the b-tree contains one or more
  95771. ** NULL values, and it will be some non-NULL value if the b-tree contains no
  95772. ** NULL values.
  95773. **
  95774. ** If the aiMap parameter is not NULL, it must point to an array containing
  95775. ** one element for each column returned by the SELECT statement on the RHS
  95776. ** of the IN(...) operator. The i'th entry of the array is populated with the
  95777. ** offset of the index column that matches the i'th column returned by the
  95778. ** SELECT. For example, if the expression and selected index are:
  95779. **
  95780. ** (?,?,?) IN (SELECT a, b, c FROM t1)
  95781. ** CREATE INDEX i1 ON t1(b, c, a);
  95782. **
  95783. ** then aiMap[] is populated with {2, 0, 1}.
  95784. */
  95785. #ifndef SQLITE_OMIT_SUBQUERY
  95786. SQLITE_PRIVATE int sqlite3FindInIndex(
  95787. Parse *pParse, /* Parsing context */
  95788. Expr *pX, /* The IN expression */
  95789. u32 inFlags, /* IN_INDEX_LOOP, _MEMBERSHIP, and/or _NOOP_OK */
  95790. int *prRhsHasNull, /* Register holding NULL status. See notes */
  95791. int *aiMap, /* Mapping from Index fields to RHS fields */
  95792. int *piTab /* OUT: index to use */
  95793. ){
  95794. Select *p; /* SELECT to the right of IN operator */
  95795. int eType = 0; /* Type of RHS table. IN_INDEX_* */
  95796. int iTab = pParse->nTab++; /* Cursor of the RHS table */
  95797. int mustBeUnique; /* True if RHS must be unique */
  95798. Vdbe *v = sqlite3GetVdbe(pParse); /* Virtual machine being coded */
  95799. assert( pX->op==TK_IN );
  95800. mustBeUnique = (inFlags & IN_INDEX_LOOP)!=0;
  95801. /* If the RHS of this IN(...) operator is a SELECT, and if it matters
  95802. ** whether or not the SELECT result contains NULL values, check whether
  95803. ** or not NULL is actually possible (it may not be, for example, due
  95804. ** to NOT NULL constraints in the schema). If no NULL values are possible,
  95805. ** set prRhsHasNull to 0 before continuing. */
  95806. if( prRhsHasNull && (pX->flags & EP_xIsSelect) ){
  95807. int i;
  95808. ExprList *pEList = pX->x.pSelect->pEList;
  95809. for(i=0; i<pEList->nExpr; i++){
  95810. if( sqlite3ExprCanBeNull(pEList->a[i].pExpr) ) break;
  95811. }
  95812. if( i==pEList->nExpr ){
  95813. prRhsHasNull = 0;
  95814. }
  95815. }
  95816. /* Check to see if an existing table or index can be used to
  95817. ** satisfy the query. This is preferable to generating a new
  95818. ** ephemeral table. */
  95819. if( pParse->nErr==0 && (p = isCandidateForInOpt(pX))!=0 ){
  95820. sqlite3 *db = pParse->db; /* Database connection */
  95821. Table *pTab; /* Table <table>. */
  95822. i16 iDb; /* Database idx for pTab */
  95823. ExprList *pEList = p->pEList;
  95824. int nExpr = pEList->nExpr;
  95825. assert( p->pEList!=0 ); /* Because of isCandidateForInOpt(p) */
  95826. assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */
  95827. assert( p->pSrc!=0 ); /* Because of isCandidateForInOpt(p) */
  95828. pTab = p->pSrc->a[0].pTab;
  95829. /* Code an OP_Transaction and OP_TableLock for <table>. */
  95830. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  95831. sqlite3CodeVerifySchema(pParse, iDb);
  95832. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  95833. assert(v); /* sqlite3GetVdbe() has always been previously called */
  95834. if( nExpr==1 && pEList->a[0].pExpr->iColumn<0 ){
  95835. /* The "x IN (SELECT rowid FROM table)" case */
  95836. int iAddr = sqlite3VdbeAddOp0(v, OP_Once);
  95837. VdbeCoverage(v);
  95838. sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
  95839. eType = IN_INDEX_ROWID;
  95840. ExplainQueryPlan((pParse, 0,
  95841. "USING ROWID SEARCH ON TABLE %s FOR IN-OPERATOR",pTab->zName));
  95842. sqlite3VdbeJumpHere(v, iAddr);
  95843. }else{
  95844. Index *pIdx; /* Iterator variable */
  95845. int affinity_ok = 1;
  95846. int i;
  95847. /* Check that the affinity that will be used to perform each
  95848. ** comparison is the same as the affinity of each column in table
  95849. ** on the RHS of the IN operator. If it not, it is not possible to
  95850. ** use any index of the RHS table. */
  95851. for(i=0; i<nExpr && affinity_ok; i++){
  95852. Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i);
  95853. int iCol = pEList->a[i].pExpr->iColumn;
  95854. char idxaff = sqlite3TableColumnAffinity(pTab,iCol); /* RHS table */
  95855. char cmpaff = sqlite3CompareAffinity(pLhs, idxaff);
  95856. testcase( cmpaff==SQLITE_AFF_BLOB );
  95857. testcase( cmpaff==SQLITE_AFF_TEXT );
  95858. switch( cmpaff ){
  95859. case SQLITE_AFF_BLOB:
  95860. break;
  95861. case SQLITE_AFF_TEXT:
  95862. /* sqlite3CompareAffinity() only returns TEXT if one side or the
  95863. ** other has no affinity and the other side is TEXT. Hence,
  95864. ** the only way for cmpaff to be TEXT is for idxaff to be TEXT
  95865. ** and for the term on the LHS of the IN to have no affinity. */
  95866. assert( idxaff==SQLITE_AFF_TEXT );
  95867. break;
  95868. default:
  95869. affinity_ok = sqlite3IsNumericAffinity(idxaff);
  95870. }
  95871. }
  95872. if( affinity_ok ){
  95873. /* Search for an existing index that will work for this IN operator */
  95874. for(pIdx=pTab->pIndex; pIdx && eType==0; pIdx=pIdx->pNext){
  95875. Bitmask colUsed; /* Columns of the index used */
  95876. Bitmask mCol; /* Mask for the current column */
  95877. if( pIdx->nColumn<nExpr ) continue;
  95878. if( pIdx->pPartIdxWhere!=0 ) continue;
  95879. /* Maximum nColumn is BMS-2, not BMS-1, so that we can compute
  95880. ** BITMASK(nExpr) without overflowing */
  95881. testcase( pIdx->nColumn==BMS-2 );
  95882. testcase( pIdx->nColumn==BMS-1 );
  95883. if( pIdx->nColumn>=BMS-1 ) continue;
  95884. if( mustBeUnique ){
  95885. if( pIdx->nKeyCol>nExpr
  95886. ||(pIdx->nColumn>nExpr && !IsUniqueIndex(pIdx))
  95887. ){
  95888. continue; /* This index is not unique over the IN RHS columns */
  95889. }
  95890. }
  95891. colUsed = 0; /* Columns of index used so far */
  95892. for(i=0; i<nExpr; i++){
  95893. Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i);
  95894. Expr *pRhs = pEList->a[i].pExpr;
  95895. CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pLhs, pRhs);
  95896. int j;
  95897. assert( pReq!=0 || pRhs->iColumn==XN_ROWID || pParse->nErr );
  95898. for(j=0; j<nExpr; j++){
  95899. if( pIdx->aiColumn[j]!=pRhs->iColumn ) continue;
  95900. assert( pIdx->azColl[j] );
  95901. if( pReq!=0 && sqlite3StrICmp(pReq->zName, pIdx->azColl[j])!=0 ){
  95902. continue;
  95903. }
  95904. break;
  95905. }
  95906. if( j==nExpr ) break;
  95907. mCol = MASKBIT(j);
  95908. if( mCol & colUsed ) break; /* Each column used only once */
  95909. colUsed |= mCol;
  95910. if( aiMap ) aiMap[i] = j;
  95911. }
  95912. assert( i==nExpr || colUsed!=(MASKBIT(nExpr)-1) );
  95913. if( colUsed==(MASKBIT(nExpr)-1) ){
  95914. /* If we reach this point, that means the index pIdx is usable */
  95915. int iAddr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
  95916. ExplainQueryPlan((pParse, 0,
  95917. "USING INDEX %s FOR IN-OPERATOR",pIdx->zName));
  95918. sqlite3VdbeAddOp3(v, OP_OpenRead, iTab, pIdx->tnum, iDb);
  95919. sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  95920. VdbeComment((v, "%s", pIdx->zName));
  95921. assert( IN_INDEX_INDEX_DESC == IN_INDEX_INDEX_ASC+1 );
  95922. eType = IN_INDEX_INDEX_ASC + pIdx->aSortOrder[0];
  95923. if( prRhsHasNull ){
  95924. #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
  95925. i64 mask = (1<<nExpr)-1;
  95926. sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed,
  95927. iTab, 0, 0, (u8*)&mask, P4_INT64);
  95928. #endif
  95929. *prRhsHasNull = ++pParse->nMem;
  95930. if( nExpr==1 ){
  95931. sqlite3SetHasNullFlag(v, iTab, *prRhsHasNull);
  95932. }
  95933. }
  95934. sqlite3VdbeJumpHere(v, iAddr);
  95935. }
  95936. } /* End loop over indexes */
  95937. } /* End if( affinity_ok ) */
  95938. } /* End if not an rowid index */
  95939. } /* End attempt to optimize using an index */
  95940. /* If no preexisting index is available for the IN clause
  95941. ** and IN_INDEX_NOOP is an allowed reply
  95942. ** and the RHS of the IN operator is a list, not a subquery
  95943. ** and the RHS is not constant or has two or fewer terms,
  95944. ** then it is not worth creating an ephemeral table to evaluate
  95945. ** the IN operator so return IN_INDEX_NOOP.
  95946. */
  95947. if( eType==0
  95948. && (inFlags & IN_INDEX_NOOP_OK)
  95949. && !ExprHasProperty(pX, EP_xIsSelect)
  95950. && (!sqlite3InRhsIsConstant(pX) || pX->x.pList->nExpr<=2)
  95951. ){
  95952. eType = IN_INDEX_NOOP;
  95953. }
  95954. if( eType==0 ){
  95955. /* Could not find an existing table or index to use as the RHS b-tree.
  95956. ** We will have to generate an ephemeral table to do the job.
  95957. */
  95958. u32 savedNQueryLoop = pParse->nQueryLoop;
  95959. int rMayHaveNull = 0;
  95960. eType = IN_INDEX_EPH;
  95961. if( inFlags & IN_INDEX_LOOP ){
  95962. pParse->nQueryLoop = 0;
  95963. }else if( prRhsHasNull ){
  95964. *prRhsHasNull = rMayHaveNull = ++pParse->nMem;
  95965. }
  95966. assert( pX->op==TK_IN );
  95967. sqlite3CodeRhsOfIN(pParse, pX, iTab);
  95968. if( rMayHaveNull ){
  95969. sqlite3SetHasNullFlag(v, iTab, rMayHaveNull);
  95970. }
  95971. pParse->nQueryLoop = savedNQueryLoop;
  95972. }
  95973. if( aiMap && eType!=IN_INDEX_INDEX_ASC && eType!=IN_INDEX_INDEX_DESC ){
  95974. int i, n;
  95975. n = sqlite3ExprVectorSize(pX->pLeft);
  95976. for(i=0; i<n; i++) aiMap[i] = i;
  95977. }
  95978. *piTab = iTab;
  95979. return eType;
  95980. }
  95981. #endif
  95982. #ifndef SQLITE_OMIT_SUBQUERY
  95983. /*
  95984. ** Argument pExpr is an (?, ?...) IN(...) expression. This
  95985. ** function allocates and returns a nul-terminated string containing
  95986. ** the affinities to be used for each column of the comparison.
  95987. **
  95988. ** It is the responsibility of the caller to ensure that the returned
  95989. ** string is eventually freed using sqlite3DbFree().
  95990. */
  95991. static char *exprINAffinity(Parse *pParse, Expr *pExpr){
  95992. Expr *pLeft = pExpr->pLeft;
  95993. int nVal = sqlite3ExprVectorSize(pLeft);
  95994. Select *pSelect = (pExpr->flags & EP_xIsSelect) ? pExpr->x.pSelect : 0;
  95995. char *zRet;
  95996. assert( pExpr->op==TK_IN );
  95997. zRet = sqlite3DbMallocRaw(pParse->db, nVal+1);
  95998. if( zRet ){
  95999. int i;
  96000. for(i=0; i<nVal; i++){
  96001. Expr *pA = sqlite3VectorFieldSubexpr(pLeft, i);
  96002. char a = sqlite3ExprAffinity(pA);
  96003. if( pSelect ){
  96004. zRet[i] = sqlite3CompareAffinity(pSelect->pEList->a[i].pExpr, a);
  96005. }else{
  96006. zRet[i] = a;
  96007. }
  96008. }
  96009. zRet[nVal] = '\0';
  96010. }
  96011. return zRet;
  96012. }
  96013. #endif
  96014. #ifndef SQLITE_OMIT_SUBQUERY
  96015. /*
  96016. ** Load the Parse object passed as the first argument with an error
  96017. ** message of the form:
  96018. **
  96019. ** "sub-select returns N columns - expected M"
  96020. */
  96021. SQLITE_PRIVATE void sqlite3SubselectError(Parse *pParse, int nActual, int nExpect){
  96022. if( pParse->nErr==0 ){
  96023. const char *zFmt = "sub-select returns %d columns - expected %d";
  96024. sqlite3ErrorMsg(pParse, zFmt, nActual, nExpect);
  96025. }
  96026. }
  96027. #endif
  96028. /*
  96029. ** Expression pExpr is a vector that has been used in a context where
  96030. ** it is not permitted. If pExpr is a sub-select vector, this routine
  96031. ** loads the Parse object with a message of the form:
  96032. **
  96033. ** "sub-select returns N columns - expected 1"
  96034. **
  96035. ** Or, if it is a regular scalar vector:
  96036. **
  96037. ** "row value misused"
  96038. */
  96039. SQLITE_PRIVATE void sqlite3VectorErrorMsg(Parse *pParse, Expr *pExpr){
  96040. #ifndef SQLITE_OMIT_SUBQUERY
  96041. if( pExpr->flags & EP_xIsSelect ){
  96042. sqlite3SubselectError(pParse, pExpr->x.pSelect->pEList->nExpr, 1);
  96043. }else
  96044. #endif
  96045. {
  96046. sqlite3ErrorMsg(pParse, "row value misused");
  96047. }
  96048. }
  96049. #ifndef SQLITE_OMIT_SUBQUERY
  96050. /*
  96051. ** Generate code that will construct an ephemeral table containing all terms
  96052. ** in the RHS of an IN operator. The IN operator can be in either of two
  96053. ** forms:
  96054. **
  96055. ** x IN (4,5,11) -- IN operator with list on right-hand side
  96056. ** x IN (SELECT a FROM b) -- IN operator with subquery on the right
  96057. **
  96058. ** The pExpr parameter is the IN operator. The cursor number for the
  96059. ** constructed ephermeral table is returned. The first time the ephemeral
  96060. ** table is computed, the cursor number is also stored in pExpr->iTable,
  96061. ** however the cursor number returned might not be the same, as it might
  96062. ** have been duplicated using OP_OpenDup.
  96063. **
  96064. ** If the LHS expression ("x" in the examples) is a column value, or
  96065. ** the SELECT statement returns a column value, then the affinity of that
  96066. ** column is used to build the index keys. If both 'x' and the
  96067. ** SELECT... statement are columns, then numeric affinity is used
  96068. ** if either column has NUMERIC or INTEGER affinity. If neither
  96069. ** 'x' nor the SELECT... statement are columns, then numeric affinity
  96070. ** is used.
  96071. */
  96072. SQLITE_PRIVATE void sqlite3CodeRhsOfIN(
  96073. Parse *pParse, /* Parsing context */
  96074. Expr *pExpr, /* The IN operator */
  96075. int iTab /* Use this cursor number */
  96076. ){
  96077. int addrOnce = 0; /* Address of the OP_Once instruction at top */
  96078. int addr; /* Address of OP_OpenEphemeral instruction */
  96079. Expr *pLeft; /* the LHS of the IN operator */
  96080. KeyInfo *pKeyInfo = 0; /* Key information */
  96081. int nVal; /* Size of vector pLeft */
  96082. Vdbe *v; /* The prepared statement under construction */
  96083. v = pParse->pVdbe;
  96084. assert( v!=0 );
  96085. /* The evaluation of the IN must be repeated every time it
  96086. ** is encountered if any of the following is true:
  96087. **
  96088. ** * The right-hand side is a correlated subquery
  96089. ** * The right-hand side is an expression list containing variables
  96090. ** * We are inside a trigger
  96091. **
  96092. ** If all of the above are false, then we can compute the RHS just once
  96093. ** and reuse it many names.
  96094. */
  96095. if( !ExprHasProperty(pExpr, EP_VarSelect) && pParse->iSelfTab==0 ){
  96096. /* Reuse of the RHS is allowed */
  96097. /* If this routine has already been coded, but the previous code
  96098. ** might not have been invoked yet, so invoke it now as a subroutine.
  96099. */
  96100. if( ExprHasProperty(pExpr, EP_Subrtn) ){
  96101. addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
  96102. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  96103. ExplainQueryPlan((pParse, 0, "REUSE LIST SUBQUERY %d",
  96104. pExpr->x.pSelect->selId));
  96105. }
  96106. sqlite3VdbeAddOp2(v, OP_Gosub, pExpr->y.sub.regReturn,
  96107. pExpr->y.sub.iAddr);
  96108. sqlite3VdbeAddOp2(v, OP_OpenDup, iTab, pExpr->iTable);
  96109. sqlite3VdbeJumpHere(v, addrOnce);
  96110. return;
  96111. }
  96112. /* Begin coding the subroutine */
  96113. ExprSetProperty(pExpr, EP_Subrtn);
  96114. assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
  96115. pExpr->y.sub.regReturn = ++pParse->nMem;
  96116. pExpr->y.sub.iAddr =
  96117. sqlite3VdbeAddOp2(v, OP_Integer, 0, pExpr->y.sub.regReturn) + 1;
  96118. VdbeComment((v, "return address"));
  96119. addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
  96120. }
  96121. /* Check to see if this is a vector IN operator */
  96122. pLeft = pExpr->pLeft;
  96123. nVal = sqlite3ExprVectorSize(pLeft);
  96124. /* Construct the ephemeral table that will contain the content of
  96125. ** RHS of the IN operator.
  96126. */
  96127. pExpr->iTable = iTab;
  96128. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, nVal);
  96129. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  96130. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  96131. VdbeComment((v, "Result of SELECT %u", pExpr->x.pSelect->selId));
  96132. }else{
  96133. VdbeComment((v, "RHS of IN operator"));
  96134. }
  96135. #endif
  96136. pKeyInfo = sqlite3KeyInfoAlloc(pParse->db, nVal, 1);
  96137. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  96138. /* Case 1: expr IN (SELECT ...)
  96139. **
  96140. ** Generate code to write the results of the select into the temporary
  96141. ** table allocated and opened above.
  96142. */
  96143. Select *pSelect = pExpr->x.pSelect;
  96144. ExprList *pEList = pSelect->pEList;
  96145. ExplainQueryPlan((pParse, 1, "%sLIST SUBQUERY %d",
  96146. addrOnce?"":"CORRELATED ", pSelect->selId
  96147. ));
  96148. /* If the LHS and RHS of the IN operator do not match, that
  96149. ** error will have been caught long before we reach this point. */
  96150. if( ALWAYS(pEList->nExpr==nVal) ){
  96151. SelectDest dest;
  96152. int i;
  96153. sqlite3SelectDestInit(&dest, SRT_Set, iTab);
  96154. dest.zAffSdst = exprINAffinity(pParse, pExpr);
  96155. pSelect->iLimit = 0;
  96156. testcase( pSelect->selFlags & SF_Distinct );
  96157. testcase( pKeyInfo==0 ); /* Caused by OOM in sqlite3KeyInfoAlloc() */
  96158. if( sqlite3Select(pParse, pSelect, &dest) ){
  96159. sqlite3DbFree(pParse->db, dest.zAffSdst);
  96160. sqlite3KeyInfoUnref(pKeyInfo);
  96161. return;
  96162. }
  96163. sqlite3DbFree(pParse->db, dest.zAffSdst);
  96164. assert( pKeyInfo!=0 ); /* OOM will cause exit after sqlite3Select() */
  96165. assert( pEList!=0 );
  96166. assert( pEList->nExpr>0 );
  96167. assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
  96168. for(i=0; i<nVal; i++){
  96169. Expr *p = sqlite3VectorFieldSubexpr(pLeft, i);
  96170. pKeyInfo->aColl[i] = sqlite3BinaryCompareCollSeq(
  96171. pParse, p, pEList->a[i].pExpr
  96172. );
  96173. }
  96174. }
  96175. }else if( ALWAYS(pExpr->x.pList!=0) ){
  96176. /* Case 2: expr IN (exprlist)
  96177. **
  96178. ** For each expression, build an index key from the evaluation and
  96179. ** store it in the temporary table. If <expr> is a column, then use
  96180. ** that columns affinity when building index keys. If <expr> is not
  96181. ** a column, use numeric affinity.
  96182. */
  96183. char affinity; /* Affinity of the LHS of the IN */
  96184. int i;
  96185. ExprList *pList = pExpr->x.pList;
  96186. struct ExprList_item *pItem;
  96187. int r1, r2;
  96188. affinity = sqlite3ExprAffinity(pLeft);
  96189. if( affinity<=SQLITE_AFF_NONE ){
  96190. affinity = SQLITE_AFF_BLOB;
  96191. }else if( affinity==SQLITE_AFF_REAL ){
  96192. affinity = SQLITE_AFF_NUMERIC;
  96193. }
  96194. if( pKeyInfo ){
  96195. assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
  96196. pKeyInfo->aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
  96197. }
  96198. /* Loop through each expression in <exprlist>. */
  96199. r1 = sqlite3GetTempReg(pParse);
  96200. r2 = sqlite3GetTempReg(pParse);
  96201. for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
  96202. Expr *pE2 = pItem->pExpr;
  96203. /* If the expression is not constant then we will need to
  96204. ** disable the test that was generated above that makes sure
  96205. ** this code only executes once. Because for a non-constant
  96206. ** expression we need to rerun this code each time.
  96207. */
  96208. if( addrOnce && !sqlite3ExprIsConstant(pE2) ){
  96209. sqlite3VdbeChangeToNoop(v, addrOnce);
  96210. ExprClearProperty(pExpr, EP_Subrtn);
  96211. addrOnce = 0;
  96212. }
  96213. /* Evaluate the expression and insert it into the temp table */
  96214. sqlite3ExprCode(pParse, pE2, r1);
  96215. sqlite3VdbeAddOp4(v, OP_MakeRecord, r1, 1, r2, &affinity, 1);
  96216. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iTab, r2, r1, 1);
  96217. }
  96218. sqlite3ReleaseTempReg(pParse, r1);
  96219. sqlite3ReleaseTempReg(pParse, r2);
  96220. }
  96221. if( pKeyInfo ){
  96222. sqlite3VdbeChangeP4(v, addr, (void *)pKeyInfo, P4_KEYINFO);
  96223. }
  96224. if( addrOnce ){
  96225. sqlite3VdbeJumpHere(v, addrOnce);
  96226. /* Subroutine return */
  96227. sqlite3VdbeAddOp1(v, OP_Return, pExpr->y.sub.regReturn);
  96228. sqlite3VdbeChangeP1(v, pExpr->y.sub.iAddr-1, sqlite3VdbeCurrentAddr(v)-1);
  96229. sqlite3ClearTempRegCache(pParse);
  96230. }
  96231. }
  96232. #endif /* SQLITE_OMIT_SUBQUERY */
  96233. /*
  96234. ** Generate code for scalar subqueries used as a subquery expression
  96235. ** or EXISTS operator:
  96236. **
  96237. ** (SELECT a FROM b) -- subquery
  96238. ** EXISTS (SELECT a FROM b) -- EXISTS subquery
  96239. **
  96240. ** The pExpr parameter is the SELECT or EXISTS operator to be coded.
  96241. **
  96242. ** Return the register that holds the result. For a multi-column SELECT,
  96243. ** the result is stored in a contiguous array of registers and the
  96244. ** return value is the register of the left-most result column.
  96245. ** Return 0 if an error occurs.
  96246. */
  96247. #ifndef SQLITE_OMIT_SUBQUERY
  96248. SQLITE_PRIVATE int sqlite3CodeSubselect(Parse *pParse, Expr *pExpr){
  96249. int addrOnce = 0; /* Address of OP_Once at top of subroutine */
  96250. int rReg = 0; /* Register storing resulting */
  96251. Select *pSel; /* SELECT statement to encode */
  96252. SelectDest dest; /* How to deal with SELECT result */
  96253. int nReg; /* Registers to allocate */
  96254. Expr *pLimit; /* New limit expression */
  96255. Vdbe *v = pParse->pVdbe;
  96256. assert( v!=0 );
  96257. testcase( pExpr->op==TK_EXISTS );
  96258. testcase( pExpr->op==TK_SELECT );
  96259. assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
  96260. assert( ExprHasProperty(pExpr, EP_xIsSelect) );
  96261. pSel = pExpr->x.pSelect;
  96262. /* The evaluation of the EXISTS/SELECT must be repeated every time it
  96263. ** is encountered if any of the following is true:
  96264. **
  96265. ** * The right-hand side is a correlated subquery
  96266. ** * The right-hand side is an expression list containing variables
  96267. ** * We are inside a trigger
  96268. **
  96269. ** If all of the above are false, then we can run this code just once
  96270. ** save the results, and reuse the same result on subsequent invocations.
  96271. */
  96272. if( !ExprHasProperty(pExpr, EP_VarSelect) ){
  96273. /* If this routine has already been coded, then invoke it as a
  96274. ** subroutine. */
  96275. if( ExprHasProperty(pExpr, EP_Subrtn) ){
  96276. ExplainQueryPlan((pParse, 0, "REUSE SUBQUERY %d", pSel->selId));
  96277. sqlite3VdbeAddOp2(v, OP_Gosub, pExpr->y.sub.regReturn,
  96278. pExpr->y.sub.iAddr);
  96279. return pExpr->iTable;
  96280. }
  96281. /* Begin coding the subroutine */
  96282. ExprSetProperty(pExpr, EP_Subrtn);
  96283. pExpr->y.sub.regReturn = ++pParse->nMem;
  96284. pExpr->y.sub.iAddr =
  96285. sqlite3VdbeAddOp2(v, OP_Integer, 0, pExpr->y.sub.regReturn) + 1;
  96286. VdbeComment((v, "return address"));
  96287. addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
  96288. }
  96289. /* For a SELECT, generate code to put the values for all columns of
  96290. ** the first row into an array of registers and return the index of
  96291. ** the first register.
  96292. **
  96293. ** If this is an EXISTS, write an integer 0 (not exists) or 1 (exists)
  96294. ** into a register and return that register number.
  96295. **
  96296. ** In both cases, the query is augmented with "LIMIT 1". Any
  96297. ** preexisting limit is discarded in place of the new LIMIT 1.
  96298. */
  96299. ExplainQueryPlan((pParse, 1, "%sSCALAR SUBQUERY %d",
  96300. addrOnce?"":"CORRELATED ", pSel->selId));
  96301. nReg = pExpr->op==TK_SELECT ? pSel->pEList->nExpr : 1;
  96302. sqlite3SelectDestInit(&dest, 0, pParse->nMem+1);
  96303. pParse->nMem += nReg;
  96304. if( pExpr->op==TK_SELECT ){
  96305. dest.eDest = SRT_Mem;
  96306. dest.iSdst = dest.iSDParm;
  96307. dest.nSdst = nReg;
  96308. sqlite3VdbeAddOp3(v, OP_Null, 0, dest.iSDParm, dest.iSDParm+nReg-1);
  96309. VdbeComment((v, "Init subquery result"));
  96310. }else{
  96311. dest.eDest = SRT_Exists;
  96312. sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm);
  96313. VdbeComment((v, "Init EXISTS result"));
  96314. }
  96315. if( pSel->pLimit ){
  96316. /* The subquery already has a limit. If the pre-existing limit is X
  96317. ** then make the new limit X<>0 so that the new limit is either 1 or 0 */
  96318. sqlite3 *db = pParse->db;
  96319. pLimit = sqlite3Expr(db, TK_INTEGER, "0");
  96320. if( pLimit ){
  96321. pLimit->affExpr = SQLITE_AFF_NUMERIC;
  96322. pLimit = sqlite3PExpr(pParse, TK_NE,
  96323. sqlite3ExprDup(db, pSel->pLimit->pLeft, 0), pLimit);
  96324. }
  96325. sqlite3ExprDelete(db, pSel->pLimit->pLeft);
  96326. pSel->pLimit->pLeft = pLimit;
  96327. }else{
  96328. /* If there is no pre-existing limit add a limit of 1 */
  96329. pLimit = sqlite3Expr(pParse->db, TK_INTEGER, "1");
  96330. pSel->pLimit = sqlite3PExpr(pParse, TK_LIMIT, pLimit, 0);
  96331. }
  96332. pSel->iLimit = 0;
  96333. if( sqlite3Select(pParse, pSel, &dest) ){
  96334. return 0;
  96335. }
  96336. pExpr->iTable = rReg = dest.iSDParm;
  96337. ExprSetVVAProperty(pExpr, EP_NoReduce);
  96338. if( addrOnce ){
  96339. sqlite3VdbeJumpHere(v, addrOnce);
  96340. /* Subroutine return */
  96341. sqlite3VdbeAddOp1(v, OP_Return, pExpr->y.sub.regReturn);
  96342. sqlite3VdbeChangeP1(v, pExpr->y.sub.iAddr-1, sqlite3VdbeCurrentAddr(v)-1);
  96343. sqlite3ClearTempRegCache(pParse);
  96344. }
  96345. return rReg;
  96346. }
  96347. #endif /* SQLITE_OMIT_SUBQUERY */
  96348. #ifndef SQLITE_OMIT_SUBQUERY
  96349. /*
  96350. ** Expr pIn is an IN(...) expression. This function checks that the
  96351. ** sub-select on the RHS of the IN() operator has the same number of
  96352. ** columns as the vector on the LHS. Or, if the RHS of the IN() is not
  96353. ** a sub-query, that the LHS is a vector of size 1.
  96354. */
  96355. SQLITE_PRIVATE int sqlite3ExprCheckIN(Parse *pParse, Expr *pIn){
  96356. int nVector = sqlite3ExprVectorSize(pIn->pLeft);
  96357. if( (pIn->flags & EP_xIsSelect) ){
  96358. if( nVector!=pIn->x.pSelect->pEList->nExpr ){
  96359. sqlite3SubselectError(pParse, pIn->x.pSelect->pEList->nExpr, nVector);
  96360. return 1;
  96361. }
  96362. }else if( nVector!=1 ){
  96363. sqlite3VectorErrorMsg(pParse, pIn->pLeft);
  96364. return 1;
  96365. }
  96366. return 0;
  96367. }
  96368. #endif
  96369. #ifndef SQLITE_OMIT_SUBQUERY
  96370. /*
  96371. ** Generate code for an IN expression.
  96372. **
  96373. ** x IN (SELECT ...)
  96374. ** x IN (value, value, ...)
  96375. **
  96376. ** The left-hand side (LHS) is a scalar or vector expression. The
  96377. ** right-hand side (RHS) is an array of zero or more scalar values, or a
  96378. ** subquery. If the RHS is a subquery, the number of result columns must
  96379. ** match the number of columns in the vector on the LHS. If the RHS is
  96380. ** a list of values, the LHS must be a scalar.
  96381. **
  96382. ** The IN operator is true if the LHS value is contained within the RHS.
  96383. ** The result is false if the LHS is definitely not in the RHS. The
  96384. ** result is NULL if the presence of the LHS in the RHS cannot be
  96385. ** determined due to NULLs.
  96386. **
  96387. ** This routine generates code that jumps to destIfFalse if the LHS is not
  96388. ** contained within the RHS. If due to NULLs we cannot determine if the LHS
  96389. ** is contained in the RHS then jump to destIfNull. If the LHS is contained
  96390. ** within the RHS then fall through.
  96391. **
  96392. ** See the separate in-operator.md documentation file in the canonical
  96393. ** SQLite source tree for additional information.
  96394. */
  96395. static void sqlite3ExprCodeIN(
  96396. Parse *pParse, /* Parsing and code generating context */
  96397. Expr *pExpr, /* The IN expression */
  96398. int destIfFalse, /* Jump here if LHS is not contained in the RHS */
  96399. int destIfNull /* Jump here if the results are unknown due to NULLs */
  96400. ){
  96401. int rRhsHasNull = 0; /* Register that is true if RHS contains NULL values */
  96402. int eType; /* Type of the RHS */
  96403. int rLhs; /* Register(s) holding the LHS values */
  96404. int rLhsOrig; /* LHS values prior to reordering by aiMap[] */
  96405. Vdbe *v; /* Statement under construction */
  96406. int *aiMap = 0; /* Map from vector field to index column */
  96407. char *zAff = 0; /* Affinity string for comparisons */
  96408. int nVector; /* Size of vectors for this IN operator */
  96409. int iDummy; /* Dummy parameter to exprCodeVector() */
  96410. Expr *pLeft; /* The LHS of the IN operator */
  96411. int i; /* loop counter */
  96412. int destStep2; /* Where to jump when NULLs seen in step 2 */
  96413. int destStep6 = 0; /* Start of code for Step 6 */
  96414. int addrTruthOp; /* Address of opcode that determines the IN is true */
  96415. int destNotNull; /* Jump here if a comparison is not true in step 6 */
  96416. int addrTop; /* Top of the step-6 loop */
  96417. int iTab = 0; /* Index to use */
  96418. u8 okConstFactor = pParse->okConstFactor;
  96419. assert( !ExprHasVVAProperty(pExpr,EP_Immutable) );
  96420. pLeft = pExpr->pLeft;
  96421. if( sqlite3ExprCheckIN(pParse, pExpr) ) return;
  96422. zAff = exprINAffinity(pParse, pExpr);
  96423. nVector = sqlite3ExprVectorSize(pExpr->pLeft);
  96424. aiMap = (int*)sqlite3DbMallocZero(
  96425. pParse->db, nVector*(sizeof(int) + sizeof(char)) + 1
  96426. );
  96427. if( pParse->db->mallocFailed ) goto sqlite3ExprCodeIN_oom_error;
  96428. /* Attempt to compute the RHS. After this step, if anything other than
  96429. ** IN_INDEX_NOOP is returned, the table opened with cursor iTab
  96430. ** contains the values that make up the RHS. If IN_INDEX_NOOP is returned,
  96431. ** the RHS has not yet been coded. */
  96432. v = pParse->pVdbe;
  96433. assert( v!=0 ); /* OOM detected prior to this routine */
  96434. VdbeNoopComment((v, "begin IN expr"));
  96435. eType = sqlite3FindInIndex(pParse, pExpr,
  96436. IN_INDEX_MEMBERSHIP | IN_INDEX_NOOP_OK,
  96437. destIfFalse==destIfNull ? 0 : &rRhsHasNull,
  96438. aiMap, &iTab);
  96439. assert( pParse->nErr || nVector==1 || eType==IN_INDEX_EPH
  96440. || eType==IN_INDEX_INDEX_ASC || eType==IN_INDEX_INDEX_DESC
  96441. );
  96442. #ifdef SQLITE_DEBUG
  96443. /* Confirm that aiMap[] contains nVector integer values between 0 and
  96444. ** nVector-1. */
  96445. for(i=0; i<nVector; i++){
  96446. int j, cnt;
  96447. for(cnt=j=0; j<nVector; j++) if( aiMap[j]==i ) cnt++;
  96448. assert( cnt==1 );
  96449. }
  96450. #endif
  96451. /* Code the LHS, the <expr> from "<expr> IN (...)". If the LHS is a
  96452. ** vector, then it is stored in an array of nVector registers starting
  96453. ** at r1.
  96454. **
  96455. ** sqlite3FindInIndex() might have reordered the fields of the LHS vector
  96456. ** so that the fields are in the same order as an existing index. The
  96457. ** aiMap[] array contains a mapping from the original LHS field order to
  96458. ** the field order that matches the RHS index.
  96459. **
  96460. ** Avoid factoring the LHS of the IN(...) expression out of the loop,
  96461. ** even if it is constant, as OP_Affinity may be used on the register
  96462. ** by code generated below. */
  96463. assert( pParse->okConstFactor==okConstFactor );
  96464. pParse->okConstFactor = 0;
  96465. rLhsOrig = exprCodeVector(pParse, pLeft, &iDummy);
  96466. pParse->okConstFactor = okConstFactor;
  96467. for(i=0; i<nVector && aiMap[i]==i; i++){} /* Are LHS fields reordered? */
  96468. if( i==nVector ){
  96469. /* LHS fields are not reordered */
  96470. rLhs = rLhsOrig;
  96471. }else{
  96472. /* Need to reorder the LHS fields according to aiMap */
  96473. rLhs = sqlite3GetTempRange(pParse, nVector);
  96474. for(i=0; i<nVector; i++){
  96475. sqlite3VdbeAddOp3(v, OP_Copy, rLhsOrig+i, rLhs+aiMap[i], 0);
  96476. }
  96477. }
  96478. /* If sqlite3FindInIndex() did not find or create an index that is
  96479. ** suitable for evaluating the IN operator, then evaluate using a
  96480. ** sequence of comparisons.
  96481. **
  96482. ** This is step (1) in the in-operator.md optimized algorithm.
  96483. */
  96484. if( eType==IN_INDEX_NOOP ){
  96485. ExprList *pList = pExpr->x.pList;
  96486. CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
  96487. int labelOk = sqlite3VdbeMakeLabel(pParse);
  96488. int r2, regToFree;
  96489. int regCkNull = 0;
  96490. int ii;
  96491. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  96492. if( destIfNull!=destIfFalse ){
  96493. regCkNull = sqlite3GetTempReg(pParse);
  96494. sqlite3VdbeAddOp3(v, OP_BitAnd, rLhs, rLhs, regCkNull);
  96495. }
  96496. for(ii=0; ii<pList->nExpr; ii++){
  96497. r2 = sqlite3ExprCodeTemp(pParse, pList->a[ii].pExpr, &regToFree);
  96498. if( regCkNull && sqlite3ExprCanBeNull(pList->a[ii].pExpr) ){
  96499. sqlite3VdbeAddOp3(v, OP_BitAnd, regCkNull, r2, regCkNull);
  96500. }
  96501. sqlite3ReleaseTempReg(pParse, regToFree);
  96502. if( ii<pList->nExpr-1 || destIfNull!=destIfFalse ){
  96503. int op = rLhs!=r2 ? OP_Eq : OP_NotNull;
  96504. sqlite3VdbeAddOp4(v, op, rLhs, labelOk, r2,
  96505. (void*)pColl, P4_COLLSEQ);
  96506. VdbeCoverageIf(v, ii<pList->nExpr-1 && op==OP_Eq);
  96507. VdbeCoverageIf(v, ii==pList->nExpr-1 && op==OP_Eq);
  96508. VdbeCoverageIf(v, ii<pList->nExpr-1 && op==OP_NotNull);
  96509. VdbeCoverageIf(v, ii==pList->nExpr-1 && op==OP_NotNull);
  96510. sqlite3VdbeChangeP5(v, zAff[0]);
  96511. }else{
  96512. int op = rLhs!=r2 ? OP_Ne : OP_IsNull;
  96513. assert( destIfNull==destIfFalse );
  96514. sqlite3VdbeAddOp4(v, op, rLhs, destIfFalse, r2,
  96515. (void*)pColl, P4_COLLSEQ);
  96516. VdbeCoverageIf(v, op==OP_Ne);
  96517. VdbeCoverageIf(v, op==OP_IsNull);
  96518. sqlite3VdbeChangeP5(v, zAff[0] | SQLITE_JUMPIFNULL);
  96519. }
  96520. }
  96521. if( regCkNull ){
  96522. sqlite3VdbeAddOp2(v, OP_IsNull, regCkNull, destIfNull); VdbeCoverage(v);
  96523. sqlite3VdbeGoto(v, destIfFalse);
  96524. }
  96525. sqlite3VdbeResolveLabel(v, labelOk);
  96526. sqlite3ReleaseTempReg(pParse, regCkNull);
  96527. goto sqlite3ExprCodeIN_finished;
  96528. }
  96529. /* Step 2: Check to see if the LHS contains any NULL columns. If the
  96530. ** LHS does contain NULLs then the result must be either FALSE or NULL.
  96531. ** We will then skip the binary search of the RHS.
  96532. */
  96533. if( destIfNull==destIfFalse ){
  96534. destStep2 = destIfFalse;
  96535. }else{
  96536. destStep2 = destStep6 = sqlite3VdbeMakeLabel(pParse);
  96537. }
  96538. if( pParse->nErr ) goto sqlite3ExprCodeIN_finished;
  96539. for(i=0; i<nVector; i++){
  96540. Expr *p = sqlite3VectorFieldSubexpr(pExpr->pLeft, i);
  96541. if( sqlite3ExprCanBeNull(p) ){
  96542. sqlite3VdbeAddOp2(v, OP_IsNull, rLhs+i, destStep2);
  96543. VdbeCoverage(v);
  96544. }
  96545. }
  96546. /* Step 3. The LHS is now known to be non-NULL. Do the binary search
  96547. ** of the RHS using the LHS as a probe. If found, the result is
  96548. ** true.
  96549. */
  96550. if( eType==IN_INDEX_ROWID ){
  96551. /* In this case, the RHS is the ROWID of table b-tree and so we also
  96552. ** know that the RHS is non-NULL. Hence, we combine steps 3 and 4
  96553. ** into a single opcode. */
  96554. sqlite3VdbeAddOp3(v, OP_SeekRowid, iTab, destIfFalse, rLhs);
  96555. VdbeCoverage(v);
  96556. addrTruthOp = sqlite3VdbeAddOp0(v, OP_Goto); /* Return True */
  96557. }else{
  96558. sqlite3VdbeAddOp4(v, OP_Affinity, rLhs, nVector, 0, zAff, nVector);
  96559. if( destIfFalse==destIfNull ){
  96560. /* Combine Step 3 and Step 5 into a single opcode */
  96561. sqlite3VdbeAddOp4Int(v, OP_NotFound, iTab, destIfFalse,
  96562. rLhs, nVector); VdbeCoverage(v);
  96563. goto sqlite3ExprCodeIN_finished;
  96564. }
  96565. /* Ordinary Step 3, for the case where FALSE and NULL are distinct */
  96566. addrTruthOp = sqlite3VdbeAddOp4Int(v, OP_Found, iTab, 0,
  96567. rLhs, nVector); VdbeCoverage(v);
  96568. }
  96569. /* Step 4. If the RHS is known to be non-NULL and we did not find
  96570. ** an match on the search above, then the result must be FALSE.
  96571. */
  96572. if( rRhsHasNull && nVector==1 ){
  96573. sqlite3VdbeAddOp2(v, OP_NotNull, rRhsHasNull, destIfFalse);
  96574. VdbeCoverage(v);
  96575. }
  96576. /* Step 5. If we do not care about the difference between NULL and
  96577. ** FALSE, then just return false.
  96578. */
  96579. if( destIfFalse==destIfNull ) sqlite3VdbeGoto(v, destIfFalse);
  96580. /* Step 6: Loop through rows of the RHS. Compare each row to the LHS.
  96581. ** If any comparison is NULL, then the result is NULL. If all
  96582. ** comparisons are FALSE then the final result is FALSE.
  96583. **
  96584. ** For a scalar LHS, it is sufficient to check just the first row
  96585. ** of the RHS.
  96586. */
  96587. if( destStep6 ) sqlite3VdbeResolveLabel(v, destStep6);
  96588. addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, destIfFalse);
  96589. VdbeCoverage(v);
  96590. if( nVector>1 ){
  96591. destNotNull = sqlite3VdbeMakeLabel(pParse);
  96592. }else{
  96593. /* For nVector==1, combine steps 6 and 7 by immediately returning
  96594. ** FALSE if the first comparison is not NULL */
  96595. destNotNull = destIfFalse;
  96596. }
  96597. for(i=0; i<nVector; i++){
  96598. Expr *p;
  96599. CollSeq *pColl;
  96600. int r3 = sqlite3GetTempReg(pParse);
  96601. p = sqlite3VectorFieldSubexpr(pLeft, i);
  96602. pColl = sqlite3ExprCollSeq(pParse, p);
  96603. sqlite3VdbeAddOp3(v, OP_Column, iTab, i, r3);
  96604. sqlite3VdbeAddOp4(v, OP_Ne, rLhs+i, destNotNull, r3,
  96605. (void*)pColl, P4_COLLSEQ);
  96606. VdbeCoverage(v);
  96607. sqlite3ReleaseTempReg(pParse, r3);
  96608. }
  96609. sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
  96610. if( nVector>1 ){
  96611. sqlite3VdbeResolveLabel(v, destNotNull);
  96612. sqlite3VdbeAddOp2(v, OP_Next, iTab, addrTop+1);
  96613. VdbeCoverage(v);
  96614. /* Step 7: If we reach this point, we know that the result must
  96615. ** be false. */
  96616. sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
  96617. }
  96618. /* Jumps here in order to return true. */
  96619. sqlite3VdbeJumpHere(v, addrTruthOp);
  96620. sqlite3ExprCodeIN_finished:
  96621. if( rLhs!=rLhsOrig ) sqlite3ReleaseTempReg(pParse, rLhs);
  96622. VdbeComment((v, "end IN expr"));
  96623. sqlite3ExprCodeIN_oom_error:
  96624. sqlite3DbFree(pParse->db, aiMap);
  96625. sqlite3DbFree(pParse->db, zAff);
  96626. }
  96627. #endif /* SQLITE_OMIT_SUBQUERY */
  96628. #ifndef SQLITE_OMIT_FLOATING_POINT
  96629. /*
  96630. ** Generate an instruction that will put the floating point
  96631. ** value described by z[0..n-1] into register iMem.
  96632. **
  96633. ** The z[] string will probably not be zero-terminated. But the
  96634. ** z[n] character is guaranteed to be something that does not look
  96635. ** like the continuation of the number.
  96636. */
  96637. static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
  96638. if( ALWAYS(z!=0) ){
  96639. double value;
  96640. sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
  96641. assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
  96642. if( negateFlag ) value = -value;
  96643. sqlite3VdbeAddOp4Dup8(v, OP_Real, 0, iMem, 0, (u8*)&value, P4_REAL);
  96644. }
  96645. }
  96646. #endif
  96647. /*
  96648. ** Generate an instruction that will put the integer describe by
  96649. ** text z[0..n-1] into register iMem.
  96650. **
  96651. ** Expr.u.zToken is always UTF8 and zero-terminated.
  96652. */
  96653. static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
  96654. Vdbe *v = pParse->pVdbe;
  96655. if( pExpr->flags & EP_IntValue ){
  96656. int i = pExpr->u.iValue;
  96657. assert( i>=0 );
  96658. if( negFlag ) i = -i;
  96659. sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
  96660. }else{
  96661. int c;
  96662. i64 value;
  96663. const char *z = pExpr->u.zToken;
  96664. assert( z!=0 );
  96665. c = sqlite3DecOrHexToI64(z, &value);
  96666. if( (c==3 && !negFlag) || (c==2) || (negFlag && value==SMALLEST_INT64)){
  96667. #ifdef SQLITE_OMIT_FLOATING_POINT
  96668. sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
  96669. #else
  96670. #ifndef SQLITE_OMIT_HEX_INTEGER
  96671. if( sqlite3_strnicmp(z,"0x",2)==0 ){
  96672. sqlite3ErrorMsg(pParse, "hex literal too big: %s%s", negFlag?"-":"",z);
  96673. }else
  96674. #endif
  96675. {
  96676. codeReal(v, z, negFlag, iMem);
  96677. }
  96678. #endif
  96679. }else{
  96680. if( negFlag ){ value = c==3 ? SMALLEST_INT64 : -value; }
  96681. sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, iMem, 0, (u8*)&value, P4_INT64);
  96682. }
  96683. }
  96684. }
  96685. /* Generate code that will load into register regOut a value that is
  96686. ** appropriate for the iIdxCol-th column of index pIdx.
  96687. */
  96688. SQLITE_PRIVATE void sqlite3ExprCodeLoadIndexColumn(
  96689. Parse *pParse, /* The parsing context */
  96690. Index *pIdx, /* The index whose column is to be loaded */
  96691. int iTabCur, /* Cursor pointing to a table row */
  96692. int iIdxCol, /* The column of the index to be loaded */
  96693. int regOut /* Store the index column value in this register */
  96694. ){
  96695. i16 iTabCol = pIdx->aiColumn[iIdxCol];
  96696. if( iTabCol==XN_EXPR ){
  96697. assert( pIdx->aColExpr );
  96698. assert( pIdx->aColExpr->nExpr>iIdxCol );
  96699. pParse->iSelfTab = iTabCur + 1;
  96700. sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[iIdxCol].pExpr, regOut);
  96701. pParse->iSelfTab = 0;
  96702. }else{
  96703. sqlite3ExprCodeGetColumnOfTable(pParse->pVdbe, pIdx->pTable, iTabCur,
  96704. iTabCol, regOut);
  96705. }
  96706. }
  96707. #ifndef SQLITE_OMIT_GENERATED_COLUMNS
  96708. /*
  96709. ** Generate code that will compute the value of generated column pCol
  96710. ** and store the result in register regOut
  96711. */
  96712. SQLITE_PRIVATE void sqlite3ExprCodeGeneratedColumn(
  96713. Parse *pParse,
  96714. Column *pCol,
  96715. int regOut
  96716. ){
  96717. int iAddr;
  96718. Vdbe *v = pParse->pVdbe;
  96719. assert( v!=0 );
  96720. assert( pParse->iSelfTab!=0 );
  96721. if( pParse->iSelfTab>0 ){
  96722. iAddr = sqlite3VdbeAddOp3(v, OP_IfNullRow, pParse->iSelfTab-1, 0, regOut);
  96723. }else{
  96724. iAddr = 0;
  96725. }
  96726. sqlite3ExprCodeCopy(pParse, pCol->pDflt, regOut);
  96727. if( pCol->affinity>=SQLITE_AFF_TEXT ){
  96728. sqlite3VdbeAddOp4(v, OP_Affinity, regOut, 1, 0, &pCol->affinity, 1);
  96729. }
  96730. if( iAddr ) sqlite3VdbeJumpHere(v, iAddr);
  96731. }
  96732. #endif /* SQLITE_OMIT_GENERATED_COLUMNS */
  96733. /*
  96734. ** Generate code to extract the value of the iCol-th column of a table.
  96735. */
  96736. SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(
  96737. Vdbe *v, /* Parsing context */
  96738. Table *pTab, /* The table containing the value */
  96739. int iTabCur, /* The table cursor. Or the PK cursor for WITHOUT ROWID */
  96740. int iCol, /* Index of the column to extract */
  96741. int regOut /* Extract the value into this register */
  96742. ){
  96743. Column *pCol;
  96744. assert( v!=0 );
  96745. if( pTab==0 ){
  96746. sqlite3VdbeAddOp3(v, OP_Column, iTabCur, iCol, regOut);
  96747. return;
  96748. }
  96749. if( iCol<0 || iCol==pTab->iPKey ){
  96750. sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
  96751. }else{
  96752. int op;
  96753. int x;
  96754. if( IsVirtual(pTab) ){
  96755. op = OP_VColumn;
  96756. x = iCol;
  96757. #ifndef SQLITE_OMIT_GENERATED_COLUMNS
  96758. }else if( (pCol = &pTab->aCol[iCol])->colFlags & COLFLAG_VIRTUAL ){
  96759. Parse *pParse = sqlite3VdbeParser(v);
  96760. if( pCol->colFlags & COLFLAG_BUSY ){
  96761. sqlite3ErrorMsg(pParse, "generated column loop on \"%s\"", pCol->zName);
  96762. }else{
  96763. int savedSelfTab = pParse->iSelfTab;
  96764. pCol->colFlags |= COLFLAG_BUSY;
  96765. pParse->iSelfTab = iTabCur+1;
  96766. sqlite3ExprCodeGeneratedColumn(pParse, pCol, regOut);
  96767. pParse->iSelfTab = savedSelfTab;
  96768. pCol->colFlags &= ~COLFLAG_BUSY;
  96769. }
  96770. return;
  96771. #endif
  96772. }else if( !HasRowid(pTab) ){
  96773. testcase( iCol!=sqlite3TableColumnToStorage(pTab, iCol) );
  96774. x = sqlite3TableColumnToIndex(sqlite3PrimaryKeyIndex(pTab), iCol);
  96775. op = OP_Column;
  96776. }else{
  96777. x = sqlite3TableColumnToStorage(pTab,iCol);
  96778. testcase( x!=iCol );
  96779. op = OP_Column;
  96780. }
  96781. sqlite3VdbeAddOp3(v, op, iTabCur, x, regOut);
  96782. sqlite3ColumnDefault(v, pTab, iCol, regOut);
  96783. }
  96784. }
  96785. /*
  96786. ** Generate code that will extract the iColumn-th column from
  96787. ** table pTab and store the column value in register iReg.
  96788. **
  96789. ** There must be an open cursor to pTab in iTable when this routine
  96790. ** is called. If iColumn<0 then code is generated that extracts the rowid.
  96791. */
  96792. SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(
  96793. Parse *pParse, /* Parsing and code generating context */
  96794. Table *pTab, /* Description of the table we are reading from */
  96795. int iColumn, /* Index of the table column */
  96796. int iTable, /* The cursor pointing to the table */
  96797. int iReg, /* Store results here */
  96798. u8 p5 /* P5 value for OP_Column + FLAGS */
  96799. ){
  96800. assert( pParse->pVdbe!=0 );
  96801. sqlite3ExprCodeGetColumnOfTable(pParse->pVdbe, pTab, iTable, iColumn, iReg);
  96802. if( p5 ){
  96803. VdbeOp *pOp = sqlite3VdbeGetOp(pParse->pVdbe,-1);
  96804. if( pOp->opcode==OP_Column ) pOp->p5 = p5;
  96805. }
  96806. return iReg;
  96807. }
  96808. /*
  96809. ** Generate code to move content from registers iFrom...iFrom+nReg-1
  96810. ** over to iTo..iTo+nReg-1.
  96811. */
  96812. SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
  96813. sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
  96814. }
  96815. /*
  96816. ** Convert a scalar expression node to a TK_REGISTER referencing
  96817. ** register iReg. The caller must ensure that iReg already contains
  96818. ** the correct value for the expression.
  96819. */
  96820. static void exprToRegister(Expr *pExpr, int iReg){
  96821. Expr *p = sqlite3ExprSkipCollateAndLikely(pExpr);
  96822. p->op2 = p->op;
  96823. p->op = TK_REGISTER;
  96824. p->iTable = iReg;
  96825. ExprClearProperty(p, EP_Skip);
  96826. }
  96827. /*
  96828. ** Evaluate an expression (either a vector or a scalar expression) and store
  96829. ** the result in continguous temporary registers. Return the index of
  96830. ** the first register used to store the result.
  96831. **
  96832. ** If the returned result register is a temporary scalar, then also write
  96833. ** that register number into *piFreeable. If the returned result register
  96834. ** is not a temporary or if the expression is a vector set *piFreeable
  96835. ** to 0.
  96836. */
  96837. static int exprCodeVector(Parse *pParse, Expr *p, int *piFreeable){
  96838. int iResult;
  96839. int nResult = sqlite3ExprVectorSize(p);
  96840. if( nResult==1 ){
  96841. iResult = sqlite3ExprCodeTemp(pParse, p, piFreeable);
  96842. }else{
  96843. *piFreeable = 0;
  96844. if( p->op==TK_SELECT ){
  96845. #if SQLITE_OMIT_SUBQUERY
  96846. iResult = 0;
  96847. #else
  96848. iResult = sqlite3CodeSubselect(pParse, p);
  96849. #endif
  96850. }else{
  96851. int i;
  96852. iResult = pParse->nMem+1;
  96853. pParse->nMem += nResult;
  96854. for(i=0; i<nResult; i++){
  96855. sqlite3ExprCodeFactorable(pParse, p->x.pList->a[i].pExpr, i+iResult);
  96856. }
  96857. }
  96858. }
  96859. return iResult;
  96860. }
  96861. /*
  96862. ** If the last opcode is a OP_Copy, then set the do-not-merge flag (p5)
  96863. ** so that a subsequent copy will not be merged into this one.
  96864. */
  96865. static void setDoNotMergeFlagOnCopy(Vdbe *v){
  96866. if( sqlite3VdbeGetOp(v, -1)->opcode==OP_Copy ){
  96867. sqlite3VdbeChangeP5(v, 1); /* Tag trailing OP_Copy as not mergable */
  96868. }
  96869. }
  96870. /*
  96871. ** Generate code to implement special SQL functions that are implemented
  96872. ** in-line rather than by using the usual callbacks.
  96873. */
  96874. static int exprCodeInlineFunction(
  96875. Parse *pParse, /* Parsing context */
  96876. ExprList *pFarg, /* List of function arguments */
  96877. int iFuncId, /* Function ID. One of the INTFUNC_... values */
  96878. int target /* Store function result in this register */
  96879. ){
  96880. int nFarg;
  96881. Vdbe *v = pParse->pVdbe;
  96882. assert( v!=0 );
  96883. assert( pFarg!=0 );
  96884. nFarg = pFarg->nExpr;
  96885. assert( nFarg>0 ); /* All in-line functions have at least one argument */
  96886. switch( iFuncId ){
  96887. case INLINEFUNC_coalesce: {
  96888. /* Attempt a direct implementation of the built-in COALESCE() and
  96889. ** IFNULL() functions. This avoids unnecessary evaluation of
  96890. ** arguments past the first non-NULL argument.
  96891. */
  96892. int endCoalesce = sqlite3VdbeMakeLabel(pParse);
  96893. int i;
  96894. assert( nFarg>=2 );
  96895. sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
  96896. for(i=1; i<nFarg; i++){
  96897. sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
  96898. VdbeCoverage(v);
  96899. sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
  96900. }
  96901. setDoNotMergeFlagOnCopy(v);
  96902. sqlite3VdbeResolveLabel(v, endCoalesce);
  96903. break;
  96904. }
  96905. case INLINEFUNC_iif: {
  96906. Expr caseExpr;
  96907. memset(&caseExpr, 0, sizeof(caseExpr));
  96908. caseExpr.op = TK_CASE;
  96909. caseExpr.x.pList = pFarg;
  96910. return sqlite3ExprCodeTarget(pParse, &caseExpr, target);
  96911. }
  96912. default: {
  96913. /* The UNLIKELY() function is a no-op. The result is the value
  96914. ** of the first argument.
  96915. */
  96916. assert( nFarg==1 || nFarg==2 );
  96917. target = sqlite3ExprCodeTarget(pParse, pFarg->a[0].pExpr, target);
  96918. break;
  96919. }
  96920. /***********************************************************************
  96921. ** Test-only SQL functions that are only usable if enabled
  96922. ** via SQLITE_TESTCTRL_INTERNAL_FUNCTIONS
  96923. */
  96924. case INLINEFUNC_expr_compare: {
  96925. /* Compare two expressions using sqlite3ExprCompare() */
  96926. assert( nFarg==2 );
  96927. sqlite3VdbeAddOp2(v, OP_Integer,
  96928. sqlite3ExprCompare(0,pFarg->a[0].pExpr, pFarg->a[1].pExpr,-1),
  96929. target);
  96930. break;
  96931. }
  96932. case INLINEFUNC_expr_implies_expr: {
  96933. /* Compare two expressions using sqlite3ExprImpliesExpr() */
  96934. assert( nFarg==2 );
  96935. sqlite3VdbeAddOp2(v, OP_Integer,
  96936. sqlite3ExprImpliesExpr(pParse,pFarg->a[0].pExpr, pFarg->a[1].pExpr,-1),
  96937. target);
  96938. break;
  96939. }
  96940. case INLINEFUNC_implies_nonnull_row: {
  96941. /* REsult of sqlite3ExprImpliesNonNullRow() */
  96942. Expr *pA1;
  96943. assert( nFarg==2 );
  96944. pA1 = pFarg->a[1].pExpr;
  96945. if( pA1->op==TK_COLUMN ){
  96946. sqlite3VdbeAddOp2(v, OP_Integer,
  96947. sqlite3ExprImpliesNonNullRow(pFarg->a[0].pExpr,pA1->iTable),
  96948. target);
  96949. }else{
  96950. sqlite3VdbeAddOp2(v, OP_Null, 0, target);
  96951. }
  96952. break;
  96953. }
  96954. #ifdef SQLITE_DEBUG
  96955. case INLINEFUNC_affinity: {
  96956. /* The AFFINITY() function evaluates to a string that describes
  96957. ** the type affinity of the argument. This is used for testing of
  96958. ** the SQLite type logic.
  96959. */
  96960. const char *azAff[] = { "blob", "text", "numeric", "integer", "real" };
  96961. char aff;
  96962. assert( nFarg==1 );
  96963. aff = sqlite3ExprAffinity(pFarg->a[0].pExpr);
  96964. sqlite3VdbeLoadString(v, target,
  96965. (aff<=SQLITE_AFF_NONE) ? "none" : azAff[aff-SQLITE_AFF_BLOB]);
  96966. break;
  96967. }
  96968. #endif
  96969. }
  96970. return target;
  96971. }
  96972. /*
  96973. ** Generate code into the current Vdbe to evaluate the given
  96974. ** expression. Attempt to store the results in register "target".
  96975. ** Return the register where results are stored.
  96976. **
  96977. ** With this routine, there is no guarantee that results will
  96978. ** be stored in target. The result might be stored in some other
  96979. ** register if it is convenient to do so. The calling function
  96980. ** must check the return code and move the results to the desired
  96981. ** register.
  96982. */
  96983. SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
  96984. Vdbe *v = pParse->pVdbe; /* The VM under construction */
  96985. int op; /* The opcode being coded */
  96986. int inReg = target; /* Results stored in register inReg */
  96987. int regFree1 = 0; /* If non-zero free this temporary register */
  96988. int regFree2 = 0; /* If non-zero free this temporary register */
  96989. int r1, r2; /* Various register numbers */
  96990. Expr tempX; /* Temporary expression node */
  96991. int p5 = 0;
  96992. assert( target>0 && target<=pParse->nMem );
  96993. if( v==0 ){
  96994. assert( pParse->db->mallocFailed );
  96995. return 0;
  96996. }
  96997. expr_code_doover:
  96998. if( pExpr==0 ){
  96999. op = TK_NULL;
  97000. }else{
  97001. assert( !ExprHasVVAProperty(pExpr,EP_Immutable) );
  97002. op = pExpr->op;
  97003. }
  97004. switch( op ){
  97005. case TK_AGG_COLUMN: {
  97006. AggInfo *pAggInfo = pExpr->pAggInfo;
  97007. struct AggInfo_col *pCol;
  97008. assert( pAggInfo!=0 );
  97009. assert( pExpr->iAgg>=0 && pExpr->iAgg<pAggInfo->nColumn );
  97010. pCol = &pAggInfo->aCol[pExpr->iAgg];
  97011. if( !pAggInfo->directMode ){
  97012. assert( pCol->iMem>0 );
  97013. return pCol->iMem;
  97014. }else if( pAggInfo->useSortingIdx ){
  97015. Table *pTab = pCol->pTab;
  97016. sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
  97017. pCol->iSorterColumn, target);
  97018. if( pCol->iColumn<0 ){
  97019. VdbeComment((v,"%s.rowid",pTab->zName));
  97020. }else{
  97021. VdbeComment((v,"%s.%s",pTab->zName,pTab->aCol[pCol->iColumn].zName));
  97022. if( pTab->aCol[pCol->iColumn].affinity==SQLITE_AFF_REAL ){
  97023. sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
  97024. }
  97025. }
  97026. return target;
  97027. }
  97028. /* Otherwise, fall thru into the TK_COLUMN case */
  97029. }
  97030. case TK_COLUMN: {
  97031. int iTab = pExpr->iTable;
  97032. int iReg;
  97033. if( ExprHasProperty(pExpr, EP_FixedCol) ){
  97034. /* This COLUMN expression is really a constant due to WHERE clause
  97035. ** constraints, and that constant is coded by the pExpr->pLeft
  97036. ** expresssion. However, make sure the constant has the correct
  97037. ** datatype by applying the Affinity of the table column to the
  97038. ** constant.
  97039. */
  97040. int aff;
  97041. iReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft,target);
  97042. if( pExpr->y.pTab ){
  97043. aff = sqlite3TableColumnAffinity(pExpr->y.pTab, pExpr->iColumn);
  97044. }else{
  97045. aff = pExpr->affExpr;
  97046. }
  97047. if( aff>SQLITE_AFF_BLOB ){
  97048. static const char zAff[] = "B\000C\000D\000E";
  97049. assert( SQLITE_AFF_BLOB=='A' );
  97050. assert( SQLITE_AFF_TEXT=='B' );
  97051. sqlite3VdbeAddOp4(v, OP_Affinity, iReg, 1, 0,
  97052. &zAff[(aff-'B')*2], P4_STATIC);
  97053. }
  97054. return iReg;
  97055. }
  97056. if( iTab<0 ){
  97057. if( pParse->iSelfTab<0 ){
  97058. /* Other columns in the same row for CHECK constraints or
  97059. ** generated columns or for inserting into partial index.
  97060. ** The row is unpacked into registers beginning at
  97061. ** 0-(pParse->iSelfTab). The rowid (if any) is in a register
  97062. ** immediately prior to the first column.
  97063. */
  97064. Column *pCol;
  97065. Table *pTab = pExpr->y.pTab;
  97066. int iSrc;
  97067. int iCol = pExpr->iColumn;
  97068. assert( pTab!=0 );
  97069. assert( iCol>=XN_ROWID );
  97070. assert( iCol<pTab->nCol );
  97071. if( iCol<0 ){
  97072. return -1-pParse->iSelfTab;
  97073. }
  97074. pCol = pTab->aCol + iCol;
  97075. testcase( iCol!=sqlite3TableColumnToStorage(pTab,iCol) );
  97076. iSrc = sqlite3TableColumnToStorage(pTab, iCol) - pParse->iSelfTab;
  97077. #ifndef SQLITE_OMIT_GENERATED_COLUMNS
  97078. if( pCol->colFlags & COLFLAG_GENERATED ){
  97079. if( pCol->colFlags & COLFLAG_BUSY ){
  97080. sqlite3ErrorMsg(pParse, "generated column loop on \"%s\"",
  97081. pCol->zName);
  97082. return 0;
  97083. }
  97084. pCol->colFlags |= COLFLAG_BUSY;
  97085. if( pCol->colFlags & COLFLAG_NOTAVAIL ){
  97086. sqlite3ExprCodeGeneratedColumn(pParse, pCol, iSrc);
  97087. }
  97088. pCol->colFlags &= ~(COLFLAG_BUSY|COLFLAG_NOTAVAIL);
  97089. return iSrc;
  97090. }else
  97091. #endif /* SQLITE_OMIT_GENERATED_COLUMNS */
  97092. if( pCol->affinity==SQLITE_AFF_REAL ){
  97093. sqlite3VdbeAddOp2(v, OP_SCopy, iSrc, target);
  97094. sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
  97095. return target;
  97096. }else{
  97097. return iSrc;
  97098. }
  97099. }else{
  97100. /* Coding an expression that is part of an index where column names
  97101. ** in the index refer to the table to which the index belongs */
  97102. iTab = pParse->iSelfTab - 1;
  97103. }
  97104. }
  97105. iReg = sqlite3ExprCodeGetColumn(pParse, pExpr->y.pTab,
  97106. pExpr->iColumn, iTab, target,
  97107. pExpr->op2);
  97108. if( pExpr->y.pTab==0 && pExpr->affExpr==SQLITE_AFF_REAL ){
  97109. sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
  97110. }
  97111. return iReg;
  97112. }
  97113. case TK_INTEGER: {
  97114. codeInteger(pParse, pExpr, 0, target);
  97115. return target;
  97116. }
  97117. case TK_TRUEFALSE: {
  97118. sqlite3VdbeAddOp2(v, OP_Integer, sqlite3ExprTruthValue(pExpr), target);
  97119. return target;
  97120. }
  97121. #ifndef SQLITE_OMIT_FLOATING_POINT
  97122. case TK_FLOAT: {
  97123. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  97124. codeReal(v, pExpr->u.zToken, 0, target);
  97125. return target;
  97126. }
  97127. #endif
  97128. case TK_STRING: {
  97129. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  97130. sqlite3VdbeLoadString(v, target, pExpr->u.zToken);
  97131. return target;
  97132. }
  97133. default: {
  97134. /* Make NULL the default case so that if a bug causes an illegal
  97135. ** Expr node to be passed into this function, it will be handled
  97136. ** sanely and not crash. But keep the assert() to bring the problem
  97137. ** to the attention of the developers. */
  97138. assert( op==TK_NULL );
  97139. sqlite3VdbeAddOp2(v, OP_Null, 0, target);
  97140. return target;
  97141. }
  97142. #ifndef SQLITE_OMIT_BLOB_LITERAL
  97143. case TK_BLOB: {
  97144. int n;
  97145. const char *z;
  97146. char *zBlob;
  97147. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  97148. assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
  97149. assert( pExpr->u.zToken[1]=='\'' );
  97150. z = &pExpr->u.zToken[2];
  97151. n = sqlite3Strlen30(z) - 1;
  97152. assert( z[n]=='\'' );
  97153. zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
  97154. sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
  97155. return target;
  97156. }
  97157. #endif
  97158. case TK_VARIABLE: {
  97159. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  97160. assert( pExpr->u.zToken!=0 );
  97161. assert( pExpr->u.zToken[0]!=0 );
  97162. sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
  97163. if( pExpr->u.zToken[1]!=0 ){
  97164. const char *z = sqlite3VListNumToName(pParse->pVList, pExpr->iColumn);
  97165. assert( pExpr->u.zToken[0]=='?' || (z && !strcmp(pExpr->u.zToken, z)) );
  97166. pParse->pVList[0] = 0; /* Indicate VList may no longer be enlarged */
  97167. sqlite3VdbeAppendP4(v, (char*)z, P4_STATIC);
  97168. }
  97169. return target;
  97170. }
  97171. case TK_REGISTER: {
  97172. return pExpr->iTable;
  97173. }
  97174. #ifndef SQLITE_OMIT_CAST
  97175. case TK_CAST: {
  97176. /* Expressions of the form: CAST(pLeft AS token) */
  97177. inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
  97178. if( inReg!=target ){
  97179. sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
  97180. inReg = target;
  97181. }
  97182. sqlite3VdbeAddOp2(v, OP_Cast, target,
  97183. sqlite3AffinityType(pExpr->u.zToken, 0));
  97184. return inReg;
  97185. }
  97186. #endif /* SQLITE_OMIT_CAST */
  97187. case TK_IS:
  97188. case TK_ISNOT:
  97189. op = (op==TK_IS) ? TK_EQ : TK_NE;
  97190. p5 = SQLITE_NULLEQ;
  97191. /* fall-through */
  97192. case TK_LT:
  97193. case TK_LE:
  97194. case TK_GT:
  97195. case TK_GE:
  97196. case TK_NE:
  97197. case TK_EQ: {
  97198. Expr *pLeft = pExpr->pLeft;
  97199. if( sqlite3ExprIsVector(pLeft) ){
  97200. codeVectorCompare(pParse, pExpr, target, op, p5);
  97201. }else{
  97202. r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
  97203. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  97204. codeCompare(pParse, pLeft, pExpr->pRight, op,
  97205. r1, r2, inReg, SQLITE_STOREP2 | p5,
  97206. ExprHasProperty(pExpr,EP_Commuted));
  97207. assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
  97208. assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
  97209. assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
  97210. assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
  97211. assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
  97212. assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
  97213. testcase( regFree1==0 );
  97214. testcase( regFree2==0 );
  97215. }
  97216. break;
  97217. }
  97218. case TK_AND:
  97219. case TK_OR:
  97220. case TK_PLUS:
  97221. case TK_STAR:
  97222. case TK_MINUS:
  97223. case TK_REM:
  97224. case TK_BITAND:
  97225. case TK_BITOR:
  97226. case TK_SLASH:
  97227. case TK_LSHIFT:
  97228. case TK_RSHIFT:
  97229. case TK_CONCAT: {
  97230. assert( TK_AND==OP_And ); testcase( op==TK_AND );
  97231. assert( TK_OR==OP_Or ); testcase( op==TK_OR );
  97232. assert( TK_PLUS==OP_Add ); testcase( op==TK_PLUS );
  97233. assert( TK_MINUS==OP_Subtract ); testcase( op==TK_MINUS );
  97234. assert( TK_REM==OP_Remainder ); testcase( op==TK_REM );
  97235. assert( TK_BITAND==OP_BitAnd ); testcase( op==TK_BITAND );
  97236. assert( TK_BITOR==OP_BitOr ); testcase( op==TK_BITOR );
  97237. assert( TK_SLASH==OP_Divide ); testcase( op==TK_SLASH );
  97238. assert( TK_LSHIFT==OP_ShiftLeft ); testcase( op==TK_LSHIFT );
  97239. assert( TK_RSHIFT==OP_ShiftRight ); testcase( op==TK_RSHIFT );
  97240. assert( TK_CONCAT==OP_Concat ); testcase( op==TK_CONCAT );
  97241. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  97242. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  97243. sqlite3VdbeAddOp3(v, op, r2, r1, target);
  97244. testcase( regFree1==0 );
  97245. testcase( regFree2==0 );
  97246. break;
  97247. }
  97248. case TK_UMINUS: {
  97249. Expr *pLeft = pExpr->pLeft;
  97250. assert( pLeft );
  97251. if( pLeft->op==TK_INTEGER ){
  97252. codeInteger(pParse, pLeft, 1, target);
  97253. return target;
  97254. #ifndef SQLITE_OMIT_FLOATING_POINT
  97255. }else if( pLeft->op==TK_FLOAT ){
  97256. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  97257. codeReal(v, pLeft->u.zToken, 1, target);
  97258. return target;
  97259. #endif
  97260. }else{
  97261. tempX.op = TK_INTEGER;
  97262. tempX.flags = EP_IntValue|EP_TokenOnly;
  97263. tempX.u.iValue = 0;
  97264. ExprClearVVAProperties(&tempX);
  97265. r1 = sqlite3ExprCodeTemp(pParse, &tempX, &regFree1);
  97266. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
  97267. sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
  97268. testcase( regFree2==0 );
  97269. }
  97270. break;
  97271. }
  97272. case TK_BITNOT:
  97273. case TK_NOT: {
  97274. assert( TK_BITNOT==OP_BitNot ); testcase( op==TK_BITNOT );
  97275. assert( TK_NOT==OP_Not ); testcase( op==TK_NOT );
  97276. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  97277. testcase( regFree1==0 );
  97278. sqlite3VdbeAddOp2(v, op, r1, inReg);
  97279. break;
  97280. }
  97281. case TK_TRUTH: {
  97282. int isTrue; /* IS TRUE or IS NOT TRUE */
  97283. int bNormal; /* IS TRUE or IS FALSE */
  97284. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  97285. testcase( regFree1==0 );
  97286. isTrue = sqlite3ExprTruthValue(pExpr->pRight);
  97287. bNormal = pExpr->op2==TK_IS;
  97288. testcase( isTrue && bNormal);
  97289. testcase( !isTrue && bNormal);
  97290. sqlite3VdbeAddOp4Int(v, OP_IsTrue, r1, inReg, !isTrue, isTrue ^ bNormal);
  97291. break;
  97292. }
  97293. case TK_ISNULL:
  97294. case TK_NOTNULL: {
  97295. int addr;
  97296. assert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL );
  97297. assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
  97298. sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
  97299. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  97300. testcase( regFree1==0 );
  97301. addr = sqlite3VdbeAddOp1(v, op, r1);
  97302. VdbeCoverageIf(v, op==TK_ISNULL);
  97303. VdbeCoverageIf(v, op==TK_NOTNULL);
  97304. sqlite3VdbeAddOp2(v, OP_Integer, 0, target);
  97305. sqlite3VdbeJumpHere(v, addr);
  97306. break;
  97307. }
  97308. case TK_AGG_FUNCTION: {
  97309. AggInfo *pInfo = pExpr->pAggInfo;
  97310. if( pInfo==0
  97311. || NEVER(pExpr->iAgg<0)
  97312. || NEVER(pExpr->iAgg>=pInfo->nFunc)
  97313. ){
  97314. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  97315. sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
  97316. }else{
  97317. return pInfo->aFunc[pExpr->iAgg].iMem;
  97318. }
  97319. break;
  97320. }
  97321. case TK_FUNCTION: {
  97322. ExprList *pFarg; /* List of function arguments */
  97323. int nFarg; /* Number of function arguments */
  97324. FuncDef *pDef; /* The function definition object */
  97325. const char *zId; /* The function name */
  97326. u32 constMask = 0; /* Mask of function arguments that are constant */
  97327. int i; /* Loop counter */
  97328. sqlite3 *db = pParse->db; /* The database connection */
  97329. u8 enc = ENC(db); /* The text encoding used by this database */
  97330. CollSeq *pColl = 0; /* A collating sequence */
  97331. #ifndef SQLITE_OMIT_WINDOWFUNC
  97332. if( ExprHasProperty(pExpr, EP_WinFunc) ){
  97333. return pExpr->y.pWin->regResult;
  97334. }
  97335. #endif
  97336. if( ConstFactorOk(pParse) && sqlite3ExprIsConstantNotJoin(pExpr) ){
  97337. /* SQL functions can be expensive. So try to avoid running them
  97338. ** multiple times if we know they always give the same result */
  97339. return sqlite3ExprCodeRunJustOnce(pParse, pExpr, -1);
  97340. }
  97341. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  97342. assert( !ExprHasProperty(pExpr, EP_TokenOnly) );
  97343. pFarg = pExpr->x.pList;
  97344. nFarg = pFarg ? pFarg->nExpr : 0;
  97345. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  97346. zId = pExpr->u.zToken;
  97347. pDef = sqlite3FindFunction(db, zId, nFarg, enc, 0);
  97348. #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
  97349. if( pDef==0 && pParse->explain ){
  97350. pDef = sqlite3FindFunction(db, "unknown", nFarg, enc, 0);
  97351. }
  97352. #endif
  97353. if( pDef==0 || pDef->xFinalize!=0 ){
  97354. sqlite3ErrorMsg(pParse, "unknown function: %s()", zId);
  97355. break;
  97356. }
  97357. if( pDef->funcFlags & SQLITE_FUNC_INLINE ){
  97358. assert( (pDef->funcFlags & SQLITE_FUNC_UNSAFE)==0 );
  97359. assert( (pDef->funcFlags & SQLITE_FUNC_DIRECT)==0 );
  97360. return exprCodeInlineFunction(pParse, pFarg,
  97361. SQLITE_PTR_TO_INT(pDef->pUserData), target);
  97362. }else if( pDef->funcFlags & (SQLITE_FUNC_DIRECT|SQLITE_FUNC_UNSAFE) ){
  97363. sqlite3ExprFunctionUsable(pParse, pExpr, pDef);
  97364. }
  97365. for(i=0; i<nFarg; i++){
  97366. if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
  97367. testcase( i==31 );
  97368. constMask |= MASKBIT32(i);
  97369. }
  97370. if( (pDef->funcFlags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
  97371. pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
  97372. }
  97373. }
  97374. if( pFarg ){
  97375. if( constMask ){
  97376. r1 = pParse->nMem+1;
  97377. pParse->nMem += nFarg;
  97378. }else{
  97379. r1 = sqlite3GetTempRange(pParse, nFarg);
  97380. }
  97381. /* For length() and typeof() functions with a column argument,
  97382. ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG
  97383. ** or OPFLAG_TYPEOFARG respectively, to avoid unnecessary data
  97384. ** loading.
  97385. */
  97386. if( (pDef->funcFlags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){
  97387. u8 exprOp;
  97388. assert( nFarg==1 );
  97389. assert( pFarg->a[0].pExpr!=0 );
  97390. exprOp = pFarg->a[0].pExpr->op;
  97391. if( exprOp==TK_COLUMN || exprOp==TK_AGG_COLUMN ){
  97392. assert( SQLITE_FUNC_LENGTH==OPFLAG_LENGTHARG );
  97393. assert( SQLITE_FUNC_TYPEOF==OPFLAG_TYPEOFARG );
  97394. testcase( pDef->funcFlags & OPFLAG_LENGTHARG );
  97395. pFarg->a[0].pExpr->op2 =
  97396. pDef->funcFlags & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG);
  97397. }
  97398. }
  97399. sqlite3ExprCodeExprList(pParse, pFarg, r1, 0,
  97400. SQLITE_ECEL_DUP|SQLITE_ECEL_FACTOR);
  97401. }else{
  97402. r1 = 0;
  97403. }
  97404. #ifndef SQLITE_OMIT_VIRTUALTABLE
  97405. /* Possibly overload the function if the first argument is
  97406. ** a virtual table column.
  97407. **
  97408. ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
  97409. ** second argument, not the first, as the argument to test to
  97410. ** see if it is a column in a virtual table. This is done because
  97411. ** the left operand of infix functions (the operand we want to
  97412. ** control overloading) ends up as the second argument to the
  97413. ** function. The expression "A glob B" is equivalent to
  97414. ** "glob(B,A). We want to use the A in "A glob B" to test
  97415. ** for function overloading. But we use the B term in "glob(B,A)".
  97416. */
  97417. if( nFarg>=2 && ExprHasProperty(pExpr, EP_InfixFunc) ){
  97418. pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
  97419. }else if( nFarg>0 ){
  97420. pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
  97421. }
  97422. #endif
  97423. if( pDef->funcFlags & SQLITE_FUNC_NEEDCOLL ){
  97424. if( !pColl ) pColl = db->pDfltColl;
  97425. sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
  97426. }
  97427. #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
  97428. if( pDef->funcFlags & SQLITE_FUNC_OFFSET ){
  97429. Expr *pArg = pFarg->a[0].pExpr;
  97430. if( pArg->op==TK_COLUMN ){
  97431. sqlite3VdbeAddOp3(v, OP_Offset, pArg->iTable, pArg->iColumn, target);
  97432. }else{
  97433. sqlite3VdbeAddOp2(v, OP_Null, 0, target);
  97434. }
  97435. }else
  97436. #endif
  97437. {
  97438. sqlite3VdbeAddFunctionCall(pParse, constMask, r1, target, nFarg,
  97439. pDef, pExpr->op2);
  97440. }
  97441. if( nFarg ){
  97442. if( constMask==0 ){
  97443. sqlite3ReleaseTempRange(pParse, r1, nFarg);
  97444. }else{
  97445. sqlite3VdbeReleaseRegisters(pParse, r1, nFarg, constMask, 1);
  97446. }
  97447. }
  97448. return target;
  97449. }
  97450. #ifndef SQLITE_OMIT_SUBQUERY
  97451. case TK_EXISTS:
  97452. case TK_SELECT: {
  97453. int nCol;
  97454. testcase( op==TK_EXISTS );
  97455. testcase( op==TK_SELECT );
  97456. if( op==TK_SELECT && (nCol = pExpr->x.pSelect->pEList->nExpr)!=1 ){
  97457. sqlite3SubselectError(pParse, nCol, 1);
  97458. }else{
  97459. return sqlite3CodeSubselect(pParse, pExpr);
  97460. }
  97461. break;
  97462. }
  97463. case TK_SELECT_COLUMN: {
  97464. int n;
  97465. if( pExpr->pLeft->iTable==0 ){
  97466. pExpr->pLeft->iTable = sqlite3CodeSubselect(pParse, pExpr->pLeft);
  97467. }
  97468. assert( pExpr->iTable==0 || pExpr->pLeft->op==TK_SELECT );
  97469. if( pExpr->iTable!=0
  97470. && pExpr->iTable!=(n = sqlite3ExprVectorSize(pExpr->pLeft))
  97471. ){
  97472. sqlite3ErrorMsg(pParse, "%d columns assigned %d values",
  97473. pExpr->iTable, n);
  97474. }
  97475. return pExpr->pLeft->iTable + pExpr->iColumn;
  97476. }
  97477. case TK_IN: {
  97478. int destIfFalse = sqlite3VdbeMakeLabel(pParse);
  97479. int destIfNull = sqlite3VdbeMakeLabel(pParse);
  97480. sqlite3VdbeAddOp2(v, OP_Null, 0, target);
  97481. sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
  97482. sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
  97483. sqlite3VdbeResolveLabel(v, destIfFalse);
  97484. sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
  97485. sqlite3VdbeResolveLabel(v, destIfNull);
  97486. return target;
  97487. }
  97488. #endif /* SQLITE_OMIT_SUBQUERY */
  97489. /*
  97490. ** x BETWEEN y AND z
  97491. **
  97492. ** This is equivalent to
  97493. **
  97494. ** x>=y AND x<=z
  97495. **
  97496. ** X is stored in pExpr->pLeft.
  97497. ** Y is stored in pExpr->pList->a[0].pExpr.
  97498. ** Z is stored in pExpr->pList->a[1].pExpr.
  97499. */
  97500. case TK_BETWEEN: {
  97501. exprCodeBetween(pParse, pExpr, target, 0, 0);
  97502. return target;
  97503. }
  97504. case TK_SPAN:
  97505. case TK_COLLATE:
  97506. case TK_UPLUS: {
  97507. pExpr = pExpr->pLeft;
  97508. goto expr_code_doover; /* 2018-04-28: Prevent deep recursion. OSSFuzz. */
  97509. }
  97510. case TK_TRIGGER: {
  97511. /* If the opcode is TK_TRIGGER, then the expression is a reference
  97512. ** to a column in the new.* or old.* pseudo-tables available to
  97513. ** trigger programs. In this case Expr.iTable is set to 1 for the
  97514. ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
  97515. ** is set to the column of the pseudo-table to read, or to -1 to
  97516. ** read the rowid field.
  97517. **
  97518. ** The expression is implemented using an OP_Param opcode. The p1
  97519. ** parameter is set to 0 for an old.rowid reference, or to (i+1)
  97520. ** to reference another column of the old.* pseudo-table, where
  97521. ** i is the index of the column. For a new.rowid reference, p1 is
  97522. ** set to (n+1), where n is the number of columns in each pseudo-table.
  97523. ** For a reference to any other column in the new.* pseudo-table, p1
  97524. ** is set to (n+2+i), where n and i are as defined previously. For
  97525. ** example, if the table on which triggers are being fired is
  97526. ** declared as:
  97527. **
  97528. ** CREATE TABLE t1(a, b);
  97529. **
  97530. ** Then p1 is interpreted as follows:
  97531. **
  97532. ** p1==0 -> old.rowid p1==3 -> new.rowid
  97533. ** p1==1 -> old.a p1==4 -> new.a
  97534. ** p1==2 -> old.b p1==5 -> new.b
  97535. */
  97536. Table *pTab = pExpr->y.pTab;
  97537. int iCol = pExpr->iColumn;
  97538. int p1 = pExpr->iTable * (pTab->nCol+1) + 1
  97539. + sqlite3TableColumnToStorage(pTab, iCol);
  97540. assert( pExpr->iTable==0 || pExpr->iTable==1 );
  97541. assert( iCol>=-1 && iCol<pTab->nCol );
  97542. assert( pTab->iPKey<0 || iCol!=pTab->iPKey );
  97543. assert( p1>=0 && p1<(pTab->nCol*2+2) );
  97544. sqlite3VdbeAddOp2(v, OP_Param, p1, target);
  97545. VdbeComment((v, "r[%d]=%s.%s", target,
  97546. (pExpr->iTable ? "new" : "old"),
  97547. (pExpr->iColumn<0 ? "rowid" : pExpr->y.pTab->aCol[iCol].zName)
  97548. ));
  97549. #ifndef SQLITE_OMIT_FLOATING_POINT
  97550. /* If the column has REAL affinity, it may currently be stored as an
  97551. ** integer. Use OP_RealAffinity to make sure it is really real.
  97552. **
  97553. ** EVIDENCE-OF: R-60985-57662 SQLite will convert the value back to
  97554. ** floating point when extracting it from the record. */
  97555. if( iCol>=0 && pTab->aCol[iCol].affinity==SQLITE_AFF_REAL ){
  97556. sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
  97557. }
  97558. #endif
  97559. break;
  97560. }
  97561. case TK_VECTOR: {
  97562. sqlite3ErrorMsg(pParse, "row value misused");
  97563. break;
  97564. }
  97565. /* TK_IF_NULL_ROW Expr nodes are inserted ahead of expressions
  97566. ** that derive from the right-hand table of a LEFT JOIN. The
  97567. ** Expr.iTable value is the table number for the right-hand table.
  97568. ** The expression is only evaluated if that table is not currently
  97569. ** on a LEFT JOIN NULL row.
  97570. */
  97571. case TK_IF_NULL_ROW: {
  97572. int addrINR;
  97573. u8 okConstFactor = pParse->okConstFactor;
  97574. addrINR = sqlite3VdbeAddOp1(v, OP_IfNullRow, pExpr->iTable);
  97575. /* Temporarily disable factoring of constant expressions, since
  97576. ** even though expressions may appear to be constant, they are not
  97577. ** really constant because they originate from the right-hand side
  97578. ** of a LEFT JOIN. */
  97579. pParse->okConstFactor = 0;
  97580. inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
  97581. pParse->okConstFactor = okConstFactor;
  97582. sqlite3VdbeJumpHere(v, addrINR);
  97583. sqlite3VdbeChangeP3(v, addrINR, inReg);
  97584. break;
  97585. }
  97586. /*
  97587. ** Form A:
  97588. ** CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
  97589. **
  97590. ** Form B:
  97591. ** CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
  97592. **
  97593. ** Form A is can be transformed into the equivalent form B as follows:
  97594. ** CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
  97595. ** WHEN x=eN THEN rN ELSE y END
  97596. **
  97597. ** X (if it exists) is in pExpr->pLeft.
  97598. ** Y is in the last element of pExpr->x.pList if pExpr->x.pList->nExpr is
  97599. ** odd. The Y is also optional. If the number of elements in x.pList
  97600. ** is even, then Y is omitted and the "otherwise" result is NULL.
  97601. ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
  97602. **
  97603. ** The result of the expression is the Ri for the first matching Ei,
  97604. ** or if there is no matching Ei, the ELSE term Y, or if there is
  97605. ** no ELSE term, NULL.
  97606. */
  97607. case TK_CASE: {
  97608. int endLabel; /* GOTO label for end of CASE stmt */
  97609. int nextCase; /* GOTO label for next WHEN clause */
  97610. int nExpr; /* 2x number of WHEN terms */
  97611. int i; /* Loop counter */
  97612. ExprList *pEList; /* List of WHEN terms */
  97613. struct ExprList_item *aListelem; /* Array of WHEN terms */
  97614. Expr opCompare; /* The X==Ei expression */
  97615. Expr *pX; /* The X expression */
  97616. Expr *pTest = 0; /* X==Ei (form A) or just Ei (form B) */
  97617. Expr *pDel = 0;
  97618. sqlite3 *db = pParse->db;
  97619. assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
  97620. assert(pExpr->x.pList->nExpr > 0);
  97621. pEList = pExpr->x.pList;
  97622. aListelem = pEList->a;
  97623. nExpr = pEList->nExpr;
  97624. endLabel = sqlite3VdbeMakeLabel(pParse);
  97625. if( (pX = pExpr->pLeft)!=0 ){
  97626. pDel = sqlite3ExprDup(db, pX, 0);
  97627. if( db->mallocFailed ){
  97628. sqlite3ExprDelete(db, pDel);
  97629. break;
  97630. }
  97631. testcase( pX->op==TK_COLUMN );
  97632. exprToRegister(pDel, exprCodeVector(pParse, pDel, &regFree1));
  97633. testcase( regFree1==0 );
  97634. memset(&opCompare, 0, sizeof(opCompare));
  97635. opCompare.op = TK_EQ;
  97636. opCompare.pLeft = pDel;
  97637. pTest = &opCompare;
  97638. /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
  97639. ** The value in regFree1 might get SCopy-ed into the file result.
  97640. ** So make sure that the regFree1 register is not reused for other
  97641. ** purposes and possibly overwritten. */
  97642. regFree1 = 0;
  97643. }
  97644. for(i=0; i<nExpr-1; i=i+2){
  97645. if( pX ){
  97646. assert( pTest!=0 );
  97647. opCompare.pRight = aListelem[i].pExpr;
  97648. }else{
  97649. pTest = aListelem[i].pExpr;
  97650. }
  97651. nextCase = sqlite3VdbeMakeLabel(pParse);
  97652. testcase( pTest->op==TK_COLUMN );
  97653. sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
  97654. testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
  97655. sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
  97656. sqlite3VdbeGoto(v, endLabel);
  97657. sqlite3VdbeResolveLabel(v, nextCase);
  97658. }
  97659. if( (nExpr&1)!=0 ){
  97660. sqlite3ExprCode(pParse, pEList->a[nExpr-1].pExpr, target);
  97661. }else{
  97662. sqlite3VdbeAddOp2(v, OP_Null, 0, target);
  97663. }
  97664. sqlite3ExprDelete(db, pDel);
  97665. setDoNotMergeFlagOnCopy(v);
  97666. sqlite3VdbeResolveLabel(v, endLabel);
  97667. break;
  97668. }
  97669. #ifndef SQLITE_OMIT_TRIGGER
  97670. case TK_RAISE: {
  97671. assert( pExpr->affExpr==OE_Rollback
  97672. || pExpr->affExpr==OE_Abort
  97673. || pExpr->affExpr==OE_Fail
  97674. || pExpr->affExpr==OE_Ignore
  97675. );
  97676. if( !pParse->pTriggerTab && !pParse->nested ){
  97677. sqlite3ErrorMsg(pParse,
  97678. "RAISE() may only be used within a trigger-program");
  97679. return 0;
  97680. }
  97681. if( pExpr->affExpr==OE_Abort ){
  97682. sqlite3MayAbort(pParse);
  97683. }
  97684. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  97685. if( pExpr->affExpr==OE_Ignore ){
  97686. sqlite3VdbeAddOp4(
  97687. v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
  97688. VdbeCoverage(v);
  97689. }else{
  97690. sqlite3HaltConstraint(pParse,
  97691. pParse->pTriggerTab ? SQLITE_CONSTRAINT_TRIGGER : SQLITE_ERROR,
  97692. pExpr->affExpr, pExpr->u.zToken, 0, 0);
  97693. }
  97694. break;
  97695. }
  97696. #endif
  97697. }
  97698. sqlite3ReleaseTempReg(pParse, regFree1);
  97699. sqlite3ReleaseTempReg(pParse, regFree2);
  97700. return inReg;
  97701. }
  97702. /*
  97703. ** Generate code that will evaluate expression pExpr just one time
  97704. ** per prepared statement execution.
  97705. **
  97706. ** If the expression uses functions (that might throw an exception) then
  97707. ** guard them with an OP_Once opcode to ensure that the code is only executed
  97708. ** once. If no functions are involved, then factor the code out and put it at
  97709. ** the end of the prepared statement in the initialization section.
  97710. **
  97711. ** If regDest>=0 then the result is always stored in that register and the
  97712. ** result is not reusable. If regDest<0 then this routine is free to
  97713. ** store the value whereever it wants. The register where the expression
  97714. ** is stored is returned. When regDest<0, two identical expressions might
  97715. ** code to the same register, if they do not contain function calls and hence
  97716. ** are factored out into the initialization section at the end of the
  97717. ** prepared statement.
  97718. */
  97719. SQLITE_PRIVATE int sqlite3ExprCodeRunJustOnce(
  97720. Parse *pParse, /* Parsing context */
  97721. Expr *pExpr, /* The expression to code when the VDBE initializes */
  97722. int regDest /* Store the value in this register */
  97723. ){
  97724. ExprList *p;
  97725. assert( ConstFactorOk(pParse) );
  97726. p = pParse->pConstExpr;
  97727. if( regDest<0 && p ){
  97728. struct ExprList_item *pItem;
  97729. int i;
  97730. for(pItem=p->a, i=p->nExpr; i>0; pItem++, i--){
  97731. if( pItem->reusable && sqlite3ExprCompare(0,pItem->pExpr,pExpr,-1)==0 ){
  97732. return pItem->u.iConstExprReg;
  97733. }
  97734. }
  97735. }
  97736. pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);
  97737. if( pExpr!=0 && ExprHasProperty(pExpr, EP_HasFunc) ){
  97738. Vdbe *v = pParse->pVdbe;
  97739. int addr;
  97740. assert( v );
  97741. addr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
  97742. pParse->okConstFactor = 0;
  97743. if( !pParse->db->mallocFailed ){
  97744. if( regDest<0 ) regDest = ++pParse->nMem;
  97745. sqlite3ExprCode(pParse, pExpr, regDest);
  97746. }
  97747. pParse->okConstFactor = 1;
  97748. sqlite3ExprDelete(pParse->db, pExpr);
  97749. sqlite3VdbeJumpHere(v, addr);
  97750. }else{
  97751. p = sqlite3ExprListAppend(pParse, p, pExpr);
  97752. if( p ){
  97753. struct ExprList_item *pItem = &p->a[p->nExpr-1];
  97754. pItem->reusable = regDest<0;
  97755. if( regDest<0 ) regDest = ++pParse->nMem;
  97756. pItem->u.iConstExprReg = regDest;
  97757. }
  97758. pParse->pConstExpr = p;
  97759. }
  97760. return regDest;
  97761. }
  97762. /*
  97763. ** Generate code to evaluate an expression and store the results
  97764. ** into a register. Return the register number where the results
  97765. ** are stored.
  97766. **
  97767. ** If the register is a temporary register that can be deallocated,
  97768. ** then write its number into *pReg. If the result register is not
  97769. ** a temporary, then set *pReg to zero.
  97770. **
  97771. ** If pExpr is a constant, then this routine might generate this
  97772. ** code to fill the register in the initialization section of the
  97773. ** VDBE program, in order to factor it out of the evaluation loop.
  97774. */
  97775. SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
  97776. int r2;
  97777. pExpr = sqlite3ExprSkipCollateAndLikely(pExpr);
  97778. if( ConstFactorOk(pParse)
  97779. && pExpr->op!=TK_REGISTER
  97780. && sqlite3ExprIsConstantNotJoin(pExpr)
  97781. ){
  97782. *pReg = 0;
  97783. r2 = sqlite3ExprCodeRunJustOnce(pParse, pExpr, -1);
  97784. }else{
  97785. int r1 = sqlite3GetTempReg(pParse);
  97786. r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
  97787. if( r2==r1 ){
  97788. *pReg = r1;
  97789. }else{
  97790. sqlite3ReleaseTempReg(pParse, r1);
  97791. *pReg = 0;
  97792. }
  97793. }
  97794. return r2;
  97795. }
  97796. /*
  97797. ** Generate code that will evaluate expression pExpr and store the
  97798. ** results in register target. The results are guaranteed to appear
  97799. ** in register target.
  97800. */
  97801. SQLITE_PRIVATE void sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
  97802. int inReg;
  97803. assert( pExpr==0 || !ExprHasVVAProperty(pExpr,EP_Immutable) );
  97804. assert( target>0 && target<=pParse->nMem );
  97805. inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
  97806. assert( pParse->pVdbe!=0 || pParse->db->mallocFailed );
  97807. if( inReg!=target && pParse->pVdbe ){
  97808. u8 op;
  97809. if( ExprHasProperty(pExpr,EP_Subquery) ){
  97810. op = OP_Copy;
  97811. }else{
  97812. op = OP_SCopy;
  97813. }
  97814. sqlite3VdbeAddOp2(pParse->pVdbe, op, inReg, target);
  97815. }
  97816. }
  97817. /*
  97818. ** Make a transient copy of expression pExpr and then code it using
  97819. ** sqlite3ExprCode(). This routine works just like sqlite3ExprCode()
  97820. ** except that the input expression is guaranteed to be unchanged.
  97821. */
  97822. SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse *pParse, Expr *pExpr, int target){
  97823. sqlite3 *db = pParse->db;
  97824. pExpr = sqlite3ExprDup(db, pExpr, 0);
  97825. if( !db->mallocFailed ) sqlite3ExprCode(pParse, pExpr, target);
  97826. sqlite3ExprDelete(db, pExpr);
  97827. }
  97828. /*
  97829. ** Generate code that will evaluate expression pExpr and store the
  97830. ** results in register target. The results are guaranteed to appear
  97831. ** in register target. If the expression is constant, then this routine
  97832. ** might choose to code the expression at initialization time.
  97833. */
  97834. SQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse *pParse, Expr *pExpr, int target){
  97835. if( pParse->okConstFactor && sqlite3ExprIsConstantNotJoin(pExpr) ){
  97836. sqlite3ExprCodeRunJustOnce(pParse, pExpr, target);
  97837. }else{
  97838. sqlite3ExprCodeCopy(pParse, pExpr, target);
  97839. }
  97840. }
  97841. /*
  97842. ** Generate code that pushes the value of every element of the given
  97843. ** expression list into a sequence of registers beginning at target.
  97844. **
  97845. ** Return the number of elements evaluated. The number returned will
  97846. ** usually be pList->nExpr but might be reduced if SQLITE_ECEL_OMITREF
  97847. ** is defined.
  97848. **
  97849. ** The SQLITE_ECEL_DUP flag prevents the arguments from being
  97850. ** filled using OP_SCopy. OP_Copy must be used instead.
  97851. **
  97852. ** The SQLITE_ECEL_FACTOR argument allows constant arguments to be
  97853. ** factored out into initialization code.
  97854. **
  97855. ** The SQLITE_ECEL_REF flag means that expressions in the list with
  97856. ** ExprList.a[].u.x.iOrderByCol>0 have already been evaluated and stored
  97857. ** in registers at srcReg, and so the value can be copied from there.
  97858. ** If SQLITE_ECEL_OMITREF is also set, then the values with u.x.iOrderByCol>0
  97859. ** are simply omitted rather than being copied from srcReg.
  97860. */
  97861. SQLITE_PRIVATE int sqlite3ExprCodeExprList(
  97862. Parse *pParse, /* Parsing context */
  97863. ExprList *pList, /* The expression list to be coded */
  97864. int target, /* Where to write results */
  97865. int srcReg, /* Source registers if SQLITE_ECEL_REF */
  97866. u8 flags /* SQLITE_ECEL_* flags */
  97867. ){
  97868. struct ExprList_item *pItem;
  97869. int i, j, n;
  97870. u8 copyOp = (flags & SQLITE_ECEL_DUP) ? OP_Copy : OP_SCopy;
  97871. Vdbe *v = pParse->pVdbe;
  97872. assert( pList!=0 );
  97873. assert( target>0 );
  97874. assert( pParse->pVdbe!=0 ); /* Never gets this far otherwise */
  97875. n = pList->nExpr;
  97876. if( !ConstFactorOk(pParse) ) flags &= ~SQLITE_ECEL_FACTOR;
  97877. for(pItem=pList->a, i=0; i<n; i++, pItem++){
  97878. Expr *pExpr = pItem->pExpr;
  97879. #ifdef SQLITE_ENABLE_SORTER_REFERENCES
  97880. if( pItem->bSorterRef ){
  97881. i--;
  97882. n--;
  97883. }else
  97884. #endif
  97885. if( (flags & SQLITE_ECEL_REF)!=0 && (j = pItem->u.x.iOrderByCol)>0 ){
  97886. if( flags & SQLITE_ECEL_OMITREF ){
  97887. i--;
  97888. n--;
  97889. }else{
  97890. sqlite3VdbeAddOp2(v, copyOp, j+srcReg-1, target+i);
  97891. }
  97892. }else if( (flags & SQLITE_ECEL_FACTOR)!=0
  97893. && sqlite3ExprIsConstantNotJoin(pExpr)
  97894. ){
  97895. sqlite3ExprCodeRunJustOnce(pParse, pExpr, target+i);
  97896. }else{
  97897. int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
  97898. if( inReg!=target+i ){
  97899. VdbeOp *pOp;
  97900. if( copyOp==OP_Copy
  97901. && (pOp=sqlite3VdbeGetOp(v, -1))->opcode==OP_Copy
  97902. && pOp->p1+pOp->p3+1==inReg
  97903. && pOp->p2+pOp->p3+1==target+i
  97904. && pOp->p5==0 /* The do-not-merge flag must be clear */
  97905. ){
  97906. pOp->p3++;
  97907. }else{
  97908. sqlite3VdbeAddOp2(v, copyOp, inReg, target+i);
  97909. }
  97910. }
  97911. }
  97912. }
  97913. return n;
  97914. }
  97915. /*
  97916. ** Generate code for a BETWEEN operator.
  97917. **
  97918. ** x BETWEEN y AND z
  97919. **
  97920. ** The above is equivalent to
  97921. **
  97922. ** x>=y AND x<=z
  97923. **
  97924. ** Code it as such, taking care to do the common subexpression
  97925. ** elimination of x.
  97926. **
  97927. ** The xJumpIf parameter determines details:
  97928. **
  97929. ** NULL: Store the boolean result in reg[dest]
  97930. ** sqlite3ExprIfTrue: Jump to dest if true
  97931. ** sqlite3ExprIfFalse: Jump to dest if false
  97932. **
  97933. ** The jumpIfNull parameter is ignored if xJumpIf is NULL.
  97934. */
  97935. static void exprCodeBetween(
  97936. Parse *pParse, /* Parsing and code generating context */
  97937. Expr *pExpr, /* The BETWEEN expression */
  97938. int dest, /* Jump destination or storage location */
  97939. void (*xJump)(Parse*,Expr*,int,int), /* Action to take */
  97940. int jumpIfNull /* Take the jump if the BETWEEN is NULL */
  97941. ){
  97942. Expr exprAnd; /* The AND operator in x>=y AND x<=z */
  97943. Expr compLeft; /* The x>=y term */
  97944. Expr compRight; /* The x<=z term */
  97945. int regFree1 = 0; /* Temporary use register */
  97946. Expr *pDel = 0;
  97947. sqlite3 *db = pParse->db;
  97948. memset(&compLeft, 0, sizeof(Expr));
  97949. memset(&compRight, 0, sizeof(Expr));
  97950. memset(&exprAnd, 0, sizeof(Expr));
  97951. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  97952. pDel = sqlite3ExprDup(db, pExpr->pLeft, 0);
  97953. if( db->mallocFailed==0 ){
  97954. exprAnd.op = TK_AND;
  97955. exprAnd.pLeft = &compLeft;
  97956. exprAnd.pRight = &compRight;
  97957. compLeft.op = TK_GE;
  97958. compLeft.pLeft = pDel;
  97959. compLeft.pRight = pExpr->x.pList->a[0].pExpr;
  97960. compRight.op = TK_LE;
  97961. compRight.pLeft = pDel;
  97962. compRight.pRight = pExpr->x.pList->a[1].pExpr;
  97963. exprToRegister(pDel, exprCodeVector(pParse, pDel, &regFree1));
  97964. if( xJump ){
  97965. xJump(pParse, &exprAnd, dest, jumpIfNull);
  97966. }else{
  97967. /* Mark the expression is being from the ON or USING clause of a join
  97968. ** so that the sqlite3ExprCodeTarget() routine will not attempt to move
  97969. ** it into the Parse.pConstExpr list. We should use a new bit for this,
  97970. ** for clarity, but we are out of bits in the Expr.flags field so we
  97971. ** have to reuse the EP_FromJoin bit. Bummer. */
  97972. pDel->flags |= EP_FromJoin;
  97973. sqlite3ExprCodeTarget(pParse, &exprAnd, dest);
  97974. }
  97975. sqlite3ReleaseTempReg(pParse, regFree1);
  97976. }
  97977. sqlite3ExprDelete(db, pDel);
  97978. /* Ensure adequate test coverage */
  97979. testcase( xJump==sqlite3ExprIfTrue && jumpIfNull==0 && regFree1==0 );
  97980. testcase( xJump==sqlite3ExprIfTrue && jumpIfNull==0 && regFree1!=0 );
  97981. testcase( xJump==sqlite3ExprIfTrue && jumpIfNull!=0 && regFree1==0 );
  97982. testcase( xJump==sqlite3ExprIfTrue && jumpIfNull!=0 && regFree1!=0 );
  97983. testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1==0 );
  97984. testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1!=0 );
  97985. testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1==0 );
  97986. testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1!=0 );
  97987. testcase( xJump==0 );
  97988. }
  97989. /*
  97990. ** Generate code for a boolean expression such that a jump is made
  97991. ** to the label "dest" if the expression is true but execution
  97992. ** continues straight thru if the expression is false.
  97993. **
  97994. ** If the expression evaluates to NULL (neither true nor false), then
  97995. ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
  97996. **
  97997. ** This code depends on the fact that certain token values (ex: TK_EQ)
  97998. ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
  97999. ** operation. Special comments in vdbe.c and the mkopcodeh.awk script in
  98000. ** the make process cause these values to align. Assert()s in the code
  98001. ** below verify that the numbers are aligned correctly.
  98002. */
  98003. SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
  98004. Vdbe *v = pParse->pVdbe;
  98005. int op = 0;
  98006. int regFree1 = 0;
  98007. int regFree2 = 0;
  98008. int r1, r2;
  98009. assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
  98010. if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
  98011. if( NEVER(pExpr==0) ) return; /* No way this can happen */
  98012. assert( !ExprHasVVAProperty(pExpr, EP_Immutable) );
  98013. op = pExpr->op;
  98014. switch( op ){
  98015. case TK_AND:
  98016. case TK_OR: {
  98017. Expr *pAlt = sqlite3ExprSimplifiedAndOr(pExpr);
  98018. if( pAlt!=pExpr ){
  98019. sqlite3ExprIfTrue(pParse, pAlt, dest, jumpIfNull);
  98020. }else if( op==TK_AND ){
  98021. int d2 = sqlite3VdbeMakeLabel(pParse);
  98022. testcase( jumpIfNull==0 );
  98023. sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,
  98024. jumpIfNull^SQLITE_JUMPIFNULL);
  98025. sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
  98026. sqlite3VdbeResolveLabel(v, d2);
  98027. }else{
  98028. testcase( jumpIfNull==0 );
  98029. sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
  98030. sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
  98031. }
  98032. break;
  98033. }
  98034. case TK_NOT: {
  98035. testcase( jumpIfNull==0 );
  98036. sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
  98037. break;
  98038. }
  98039. case TK_TRUTH: {
  98040. int isNot; /* IS NOT TRUE or IS NOT FALSE */
  98041. int isTrue; /* IS TRUE or IS NOT TRUE */
  98042. testcase( jumpIfNull==0 );
  98043. isNot = pExpr->op2==TK_ISNOT;
  98044. isTrue = sqlite3ExprTruthValue(pExpr->pRight);
  98045. testcase( isTrue && isNot );
  98046. testcase( !isTrue && isNot );
  98047. if( isTrue ^ isNot ){
  98048. sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest,
  98049. isNot ? SQLITE_JUMPIFNULL : 0);
  98050. }else{
  98051. sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest,
  98052. isNot ? SQLITE_JUMPIFNULL : 0);
  98053. }
  98054. break;
  98055. }
  98056. case TK_IS:
  98057. case TK_ISNOT:
  98058. testcase( op==TK_IS );
  98059. testcase( op==TK_ISNOT );
  98060. op = (op==TK_IS) ? TK_EQ : TK_NE;
  98061. jumpIfNull = SQLITE_NULLEQ;
  98062. /* Fall thru */
  98063. case TK_LT:
  98064. case TK_LE:
  98065. case TK_GT:
  98066. case TK_GE:
  98067. case TK_NE:
  98068. case TK_EQ: {
  98069. if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr;
  98070. testcase( jumpIfNull==0 );
  98071. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  98072. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  98073. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  98074. r1, r2, dest, jumpIfNull, ExprHasProperty(pExpr,EP_Commuted));
  98075. assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
  98076. assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
  98077. assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
  98078. assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
  98079. assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
  98080. VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
  98081. VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
  98082. assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
  98083. VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
  98084. VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
  98085. testcase( regFree1==0 );
  98086. testcase( regFree2==0 );
  98087. break;
  98088. }
  98089. case TK_ISNULL:
  98090. case TK_NOTNULL: {
  98091. assert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL );
  98092. assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
  98093. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  98094. sqlite3VdbeAddOp2(v, op, r1, dest);
  98095. VdbeCoverageIf(v, op==TK_ISNULL);
  98096. VdbeCoverageIf(v, op==TK_NOTNULL);
  98097. testcase( regFree1==0 );
  98098. break;
  98099. }
  98100. case TK_BETWEEN: {
  98101. testcase( jumpIfNull==0 );
  98102. exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfTrue, jumpIfNull);
  98103. break;
  98104. }
  98105. #ifndef SQLITE_OMIT_SUBQUERY
  98106. case TK_IN: {
  98107. int destIfFalse = sqlite3VdbeMakeLabel(pParse);
  98108. int destIfNull = jumpIfNull ? dest : destIfFalse;
  98109. sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
  98110. sqlite3VdbeGoto(v, dest);
  98111. sqlite3VdbeResolveLabel(v, destIfFalse);
  98112. break;
  98113. }
  98114. #endif
  98115. default: {
  98116. default_expr:
  98117. if( ExprAlwaysTrue(pExpr) ){
  98118. sqlite3VdbeGoto(v, dest);
  98119. }else if( ExprAlwaysFalse(pExpr) ){
  98120. /* No-op */
  98121. }else{
  98122. r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
  98123. sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
  98124. VdbeCoverage(v);
  98125. testcase( regFree1==0 );
  98126. testcase( jumpIfNull==0 );
  98127. }
  98128. break;
  98129. }
  98130. }
  98131. sqlite3ReleaseTempReg(pParse, regFree1);
  98132. sqlite3ReleaseTempReg(pParse, regFree2);
  98133. }
  98134. /*
  98135. ** Generate code for a boolean expression such that a jump is made
  98136. ** to the label "dest" if the expression is false but execution
  98137. ** continues straight thru if the expression is true.
  98138. **
  98139. ** If the expression evaluates to NULL (neither true nor false) then
  98140. ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
  98141. ** is 0.
  98142. */
  98143. SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
  98144. Vdbe *v = pParse->pVdbe;
  98145. int op = 0;
  98146. int regFree1 = 0;
  98147. int regFree2 = 0;
  98148. int r1, r2;
  98149. assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
  98150. if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
  98151. if( pExpr==0 ) return;
  98152. assert( !ExprHasVVAProperty(pExpr,EP_Immutable) );
  98153. /* The value of pExpr->op and op are related as follows:
  98154. **
  98155. ** pExpr->op op
  98156. ** --------- ----------
  98157. ** TK_ISNULL OP_NotNull
  98158. ** TK_NOTNULL OP_IsNull
  98159. ** TK_NE OP_Eq
  98160. ** TK_EQ OP_Ne
  98161. ** TK_GT OP_Le
  98162. ** TK_LE OP_Gt
  98163. ** TK_GE OP_Lt
  98164. ** TK_LT OP_Ge
  98165. **
  98166. ** For other values of pExpr->op, op is undefined and unused.
  98167. ** The value of TK_ and OP_ constants are arranged such that we
  98168. ** can compute the mapping above using the following expression.
  98169. ** Assert()s verify that the computation is correct.
  98170. */
  98171. op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
  98172. /* Verify correct alignment of TK_ and OP_ constants
  98173. */
  98174. assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
  98175. assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
  98176. assert( pExpr->op!=TK_NE || op==OP_Eq );
  98177. assert( pExpr->op!=TK_EQ || op==OP_Ne );
  98178. assert( pExpr->op!=TK_LT || op==OP_Ge );
  98179. assert( pExpr->op!=TK_LE || op==OP_Gt );
  98180. assert( pExpr->op!=TK_GT || op==OP_Le );
  98181. assert( pExpr->op!=TK_GE || op==OP_Lt );
  98182. switch( pExpr->op ){
  98183. case TK_AND:
  98184. case TK_OR: {
  98185. Expr *pAlt = sqlite3ExprSimplifiedAndOr(pExpr);
  98186. if( pAlt!=pExpr ){
  98187. sqlite3ExprIfFalse(pParse, pAlt, dest, jumpIfNull);
  98188. }else if( pExpr->op==TK_AND ){
  98189. testcase( jumpIfNull==0 );
  98190. sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
  98191. sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
  98192. }else{
  98193. int d2 = sqlite3VdbeMakeLabel(pParse);
  98194. testcase( jumpIfNull==0 );
  98195. sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2,
  98196. jumpIfNull^SQLITE_JUMPIFNULL);
  98197. sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
  98198. sqlite3VdbeResolveLabel(v, d2);
  98199. }
  98200. break;
  98201. }
  98202. case TK_NOT: {
  98203. testcase( jumpIfNull==0 );
  98204. sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
  98205. break;
  98206. }
  98207. case TK_TRUTH: {
  98208. int isNot; /* IS NOT TRUE or IS NOT FALSE */
  98209. int isTrue; /* IS TRUE or IS NOT TRUE */
  98210. testcase( jumpIfNull==0 );
  98211. isNot = pExpr->op2==TK_ISNOT;
  98212. isTrue = sqlite3ExprTruthValue(pExpr->pRight);
  98213. testcase( isTrue && isNot );
  98214. testcase( !isTrue && isNot );
  98215. if( isTrue ^ isNot ){
  98216. /* IS TRUE and IS NOT FALSE */
  98217. sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest,
  98218. isNot ? 0 : SQLITE_JUMPIFNULL);
  98219. }else{
  98220. /* IS FALSE and IS NOT TRUE */
  98221. sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest,
  98222. isNot ? 0 : SQLITE_JUMPIFNULL);
  98223. }
  98224. break;
  98225. }
  98226. case TK_IS:
  98227. case TK_ISNOT:
  98228. testcase( pExpr->op==TK_IS );
  98229. testcase( pExpr->op==TK_ISNOT );
  98230. op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
  98231. jumpIfNull = SQLITE_NULLEQ;
  98232. /* Fall thru */
  98233. case TK_LT:
  98234. case TK_LE:
  98235. case TK_GT:
  98236. case TK_GE:
  98237. case TK_NE:
  98238. case TK_EQ: {
  98239. if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr;
  98240. testcase( jumpIfNull==0 );
  98241. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  98242. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  98243. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  98244. r1, r2, dest, jumpIfNull,ExprHasProperty(pExpr,EP_Commuted));
  98245. assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
  98246. assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
  98247. assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
  98248. assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
  98249. assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
  98250. VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
  98251. VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
  98252. assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
  98253. VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
  98254. VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
  98255. testcase( regFree1==0 );
  98256. testcase( regFree2==0 );
  98257. break;
  98258. }
  98259. case TK_ISNULL:
  98260. case TK_NOTNULL: {
  98261. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  98262. sqlite3VdbeAddOp2(v, op, r1, dest);
  98263. testcase( op==TK_ISNULL ); VdbeCoverageIf(v, op==TK_ISNULL);
  98264. testcase( op==TK_NOTNULL ); VdbeCoverageIf(v, op==TK_NOTNULL);
  98265. testcase( regFree1==0 );
  98266. break;
  98267. }
  98268. case TK_BETWEEN: {
  98269. testcase( jumpIfNull==0 );
  98270. exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfFalse, jumpIfNull);
  98271. break;
  98272. }
  98273. #ifndef SQLITE_OMIT_SUBQUERY
  98274. case TK_IN: {
  98275. if( jumpIfNull ){
  98276. sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
  98277. }else{
  98278. int destIfNull = sqlite3VdbeMakeLabel(pParse);
  98279. sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
  98280. sqlite3VdbeResolveLabel(v, destIfNull);
  98281. }
  98282. break;
  98283. }
  98284. #endif
  98285. default: {
  98286. default_expr:
  98287. if( ExprAlwaysFalse(pExpr) ){
  98288. sqlite3VdbeGoto(v, dest);
  98289. }else if( ExprAlwaysTrue(pExpr) ){
  98290. /* no-op */
  98291. }else{
  98292. r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
  98293. sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
  98294. VdbeCoverage(v);
  98295. testcase( regFree1==0 );
  98296. testcase( jumpIfNull==0 );
  98297. }
  98298. break;
  98299. }
  98300. }
  98301. sqlite3ReleaseTempReg(pParse, regFree1);
  98302. sqlite3ReleaseTempReg(pParse, regFree2);
  98303. }
  98304. /*
  98305. ** Like sqlite3ExprIfFalse() except that a copy is made of pExpr before
  98306. ** code generation, and that copy is deleted after code generation. This
  98307. ** ensures that the original pExpr is unchanged.
  98308. */
  98309. SQLITE_PRIVATE void sqlite3ExprIfFalseDup(Parse *pParse, Expr *pExpr, int dest,int jumpIfNull){
  98310. sqlite3 *db = pParse->db;
  98311. Expr *pCopy = sqlite3ExprDup(db, pExpr, 0);
  98312. if( db->mallocFailed==0 ){
  98313. sqlite3ExprIfFalse(pParse, pCopy, dest, jumpIfNull);
  98314. }
  98315. sqlite3ExprDelete(db, pCopy);
  98316. }
  98317. /*
  98318. ** Expression pVar is guaranteed to be an SQL variable. pExpr may be any
  98319. ** type of expression.
  98320. **
  98321. ** If pExpr is a simple SQL value - an integer, real, string, blob
  98322. ** or NULL value - then the VDBE currently being prepared is configured
  98323. ** to re-prepare each time a new value is bound to variable pVar.
  98324. **
  98325. ** Additionally, if pExpr is a simple SQL value and the value is the
  98326. ** same as that currently bound to variable pVar, non-zero is returned.
  98327. ** Otherwise, if the values are not the same or if pExpr is not a simple
  98328. ** SQL value, zero is returned.
  98329. */
  98330. static int exprCompareVariable(Parse *pParse, Expr *pVar, Expr *pExpr){
  98331. int res = 0;
  98332. int iVar;
  98333. sqlite3_value *pL, *pR = 0;
  98334. sqlite3ValueFromExpr(pParse->db, pExpr, SQLITE_UTF8, SQLITE_AFF_BLOB, &pR);
  98335. if( pR ){
  98336. iVar = pVar->iColumn;
  98337. sqlite3VdbeSetVarmask(pParse->pVdbe, iVar);
  98338. pL = sqlite3VdbeGetBoundValue(pParse->pReprepare, iVar, SQLITE_AFF_BLOB);
  98339. if( pL ){
  98340. if( sqlite3_value_type(pL)==SQLITE_TEXT ){
  98341. sqlite3_value_text(pL); /* Make sure the encoding is UTF-8 */
  98342. }
  98343. res = 0==sqlite3MemCompare(pL, pR, 0);
  98344. }
  98345. sqlite3ValueFree(pR);
  98346. sqlite3ValueFree(pL);
  98347. }
  98348. return res;
  98349. }
  98350. /*
  98351. ** Do a deep comparison of two expression trees. Return 0 if the two
  98352. ** expressions are completely identical. Return 1 if they differ only
  98353. ** by a COLLATE operator at the top level. Return 2 if there are differences
  98354. ** other than the top-level COLLATE operator.
  98355. **
  98356. ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
  98357. ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
  98358. **
  98359. ** The pA side might be using TK_REGISTER. If that is the case and pB is
  98360. ** not using TK_REGISTER but is otherwise equivalent, then still return 0.
  98361. **
  98362. ** Sometimes this routine will return 2 even if the two expressions
  98363. ** really are equivalent. If we cannot prove that the expressions are
  98364. ** identical, we return 2 just to be safe. So if this routine
  98365. ** returns 2, then you do not really know for certain if the two
  98366. ** expressions are the same. But if you get a 0 or 1 return, then you
  98367. ** can be sure the expressions are the same. In the places where
  98368. ** this routine is used, it does not hurt to get an extra 2 - that
  98369. ** just might result in some slightly slower code. But returning
  98370. ** an incorrect 0 or 1 could lead to a malfunction.
  98371. **
  98372. ** If pParse is not NULL then TK_VARIABLE terms in pA with bindings in
  98373. ** pParse->pReprepare can be matched against literals in pB. The
  98374. ** pParse->pVdbe->expmask bitmask is updated for each variable referenced.
  98375. ** If pParse is NULL (the normal case) then any TK_VARIABLE term in
  98376. ** Argument pParse should normally be NULL. If it is not NULL and pA or
  98377. ** pB causes a return value of 2.
  98378. */
  98379. SQLITE_PRIVATE int sqlite3ExprCompare(Parse *pParse, Expr *pA, Expr *pB, int iTab){
  98380. u32 combinedFlags;
  98381. if( pA==0 || pB==0 ){
  98382. return pB==pA ? 0 : 2;
  98383. }
  98384. if( pParse && pA->op==TK_VARIABLE && exprCompareVariable(pParse, pA, pB) ){
  98385. return 0;
  98386. }
  98387. combinedFlags = pA->flags | pB->flags;
  98388. if( combinedFlags & EP_IntValue ){
  98389. if( (pA->flags&pB->flags&EP_IntValue)!=0 && pA->u.iValue==pB->u.iValue ){
  98390. return 0;
  98391. }
  98392. return 2;
  98393. }
  98394. if( pA->op!=pB->op || pA->op==TK_RAISE ){
  98395. if( pA->op==TK_COLLATE && sqlite3ExprCompare(pParse, pA->pLeft,pB,iTab)<2 ){
  98396. return 1;
  98397. }
  98398. if( pB->op==TK_COLLATE && sqlite3ExprCompare(pParse, pA,pB->pLeft,iTab)<2 ){
  98399. return 1;
  98400. }
  98401. return 2;
  98402. }
  98403. if( pA->op!=TK_COLUMN && pA->op!=TK_AGG_COLUMN && pA->u.zToken ){
  98404. if( pA->op==TK_FUNCTION || pA->op==TK_AGG_FUNCTION ){
  98405. if( sqlite3StrICmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2;
  98406. #ifndef SQLITE_OMIT_WINDOWFUNC
  98407. assert( pA->op==pB->op );
  98408. if( ExprHasProperty(pA,EP_WinFunc)!=ExprHasProperty(pB,EP_WinFunc) ){
  98409. return 2;
  98410. }
  98411. if( ExprHasProperty(pA,EP_WinFunc) ){
  98412. if( sqlite3WindowCompare(pParse, pA->y.pWin, pB->y.pWin, 1)!=0 ){
  98413. return 2;
  98414. }
  98415. }
  98416. #endif
  98417. }else if( pA->op==TK_NULL ){
  98418. return 0;
  98419. }else if( pA->op==TK_COLLATE ){
  98420. if( sqlite3_stricmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2;
  98421. }else if( ALWAYS(pB->u.zToken!=0) && strcmp(pA->u.zToken,pB->u.zToken)!=0 ){
  98422. return 2;
  98423. }
  98424. }
  98425. if( (pA->flags & (EP_Distinct|EP_Commuted))
  98426. != (pB->flags & (EP_Distinct|EP_Commuted)) ) return 2;
  98427. if( ALWAYS((combinedFlags & EP_TokenOnly)==0) ){
  98428. if( combinedFlags & EP_xIsSelect ) return 2;
  98429. if( (combinedFlags & EP_FixedCol)==0
  98430. && sqlite3ExprCompare(pParse, pA->pLeft, pB->pLeft, iTab) ) return 2;
  98431. if( sqlite3ExprCompare(pParse, pA->pRight, pB->pRight, iTab) ) return 2;
  98432. if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList, iTab) ) return 2;
  98433. if( pA->op!=TK_STRING
  98434. && pA->op!=TK_TRUEFALSE
  98435. && ALWAYS((combinedFlags & EP_Reduced)==0)
  98436. ){
  98437. if( pA->iColumn!=pB->iColumn ) return 2;
  98438. if( pA->op2!=pB->op2 && pA->op==TK_TRUTH ) return 2;
  98439. if( pA->op!=TK_IN && pA->iTable!=pB->iTable && pA->iTable!=iTab ){
  98440. return 2;
  98441. }
  98442. }
  98443. }
  98444. return 0;
  98445. }
  98446. /*
  98447. ** Compare two ExprList objects. Return 0 if they are identical, 1
  98448. ** if they are certainly different, or 2 if it is not possible to
  98449. ** determine if they are identical or not.
  98450. **
  98451. ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
  98452. ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
  98453. **
  98454. ** This routine might return non-zero for equivalent ExprLists. The
  98455. ** only consequence will be disabled optimizations. But this routine
  98456. ** must never return 0 if the two ExprList objects are different, or
  98457. ** a malfunction will result.
  98458. **
  98459. ** Two NULL pointers are considered to be the same. But a NULL pointer
  98460. ** always differs from a non-NULL pointer.
  98461. */
  98462. SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList *pA, ExprList *pB, int iTab){
  98463. int i;
  98464. if( pA==0 && pB==0 ) return 0;
  98465. if( pA==0 || pB==0 ) return 1;
  98466. if( pA->nExpr!=pB->nExpr ) return 1;
  98467. for(i=0; i<pA->nExpr; i++){
  98468. int res;
  98469. Expr *pExprA = pA->a[i].pExpr;
  98470. Expr *pExprB = pB->a[i].pExpr;
  98471. if( pA->a[i].sortFlags!=pB->a[i].sortFlags ) return 1;
  98472. if( (res = sqlite3ExprCompare(0, pExprA, pExprB, iTab)) ) return res;
  98473. }
  98474. return 0;
  98475. }
  98476. /*
  98477. ** Like sqlite3ExprCompare() except COLLATE operators at the top-level
  98478. ** are ignored.
  98479. */
  98480. SQLITE_PRIVATE int sqlite3ExprCompareSkip(Expr *pA, Expr *pB, int iTab){
  98481. return sqlite3ExprCompare(0,
  98482. sqlite3ExprSkipCollateAndLikely(pA),
  98483. sqlite3ExprSkipCollateAndLikely(pB),
  98484. iTab);
  98485. }
  98486. /*
  98487. ** Return non-zero if Expr p can only be true if pNN is not NULL.
  98488. **
  98489. ** Or if seenNot is true, return non-zero if Expr p can only be
  98490. ** non-NULL if pNN is not NULL
  98491. */
  98492. static int exprImpliesNotNull(
  98493. Parse *pParse, /* Parsing context */
  98494. Expr *p, /* The expression to be checked */
  98495. Expr *pNN, /* The expression that is NOT NULL */
  98496. int iTab, /* Table being evaluated */
  98497. int seenNot /* Return true only if p can be any non-NULL value */
  98498. ){
  98499. assert( p );
  98500. assert( pNN );
  98501. if( sqlite3ExprCompare(pParse, p, pNN, iTab)==0 ){
  98502. return pNN->op!=TK_NULL;
  98503. }
  98504. switch( p->op ){
  98505. case TK_IN: {
  98506. if( seenNot && ExprHasProperty(p, EP_xIsSelect) ) return 0;
  98507. assert( ExprHasProperty(p,EP_xIsSelect)
  98508. || (p->x.pList!=0 && p->x.pList->nExpr>0) );
  98509. return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, 1);
  98510. }
  98511. case TK_BETWEEN: {
  98512. ExprList *pList = p->x.pList;
  98513. assert( pList!=0 );
  98514. assert( pList->nExpr==2 );
  98515. if( seenNot ) return 0;
  98516. if( exprImpliesNotNull(pParse, pList->a[0].pExpr, pNN, iTab, 1)
  98517. || exprImpliesNotNull(pParse, pList->a[1].pExpr, pNN, iTab, 1)
  98518. ){
  98519. return 1;
  98520. }
  98521. return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, 1);
  98522. }
  98523. case TK_EQ:
  98524. case TK_NE:
  98525. case TK_LT:
  98526. case TK_LE:
  98527. case TK_GT:
  98528. case TK_GE:
  98529. case TK_PLUS:
  98530. case TK_MINUS:
  98531. case TK_BITOR:
  98532. case TK_LSHIFT:
  98533. case TK_RSHIFT:
  98534. case TK_CONCAT:
  98535. seenNot = 1;
  98536. /* Fall thru */
  98537. case TK_STAR:
  98538. case TK_REM:
  98539. case TK_BITAND:
  98540. case TK_SLASH: {
  98541. if( exprImpliesNotNull(pParse, p->pRight, pNN, iTab, seenNot) ) return 1;
  98542. /* Fall thru into the next case */
  98543. }
  98544. case TK_SPAN:
  98545. case TK_COLLATE:
  98546. case TK_UPLUS:
  98547. case TK_UMINUS: {
  98548. return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, seenNot);
  98549. }
  98550. case TK_TRUTH: {
  98551. if( seenNot ) return 0;
  98552. if( p->op2!=TK_IS ) return 0;
  98553. return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, 1);
  98554. }
  98555. case TK_BITNOT:
  98556. case TK_NOT: {
  98557. return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, 1);
  98558. }
  98559. }
  98560. return 0;
  98561. }
  98562. /*
  98563. ** Return true if we can prove the pE2 will always be true if pE1 is
  98564. ** true. Return false if we cannot complete the proof or if pE2 might
  98565. ** be false. Examples:
  98566. **
  98567. ** pE1: x==5 pE2: x==5 Result: true
  98568. ** pE1: x>0 pE2: x==5 Result: false
  98569. ** pE1: x=21 pE2: x=21 OR y=43 Result: true
  98570. ** pE1: x!=123 pE2: x IS NOT NULL Result: true
  98571. ** pE1: x!=?1 pE2: x IS NOT NULL Result: true
  98572. ** pE1: x IS NULL pE2: x IS NOT NULL Result: false
  98573. ** pE1: x IS ?2 pE2: x IS NOT NULL Reuslt: false
  98574. **
  98575. ** When comparing TK_COLUMN nodes between pE1 and pE2, if pE2 has
  98576. ** Expr.iTable<0 then assume a table number given by iTab.
  98577. **
  98578. ** If pParse is not NULL, then the values of bound variables in pE1 are
  98579. ** compared against literal values in pE2 and pParse->pVdbe->expmask is
  98580. ** modified to record which bound variables are referenced. If pParse
  98581. ** is NULL, then false will be returned if pE1 contains any bound variables.
  98582. **
  98583. ** When in doubt, return false. Returning true might give a performance
  98584. ** improvement. Returning false might cause a performance reduction, but
  98585. ** it will always give the correct answer and is hence always safe.
  98586. */
  98587. SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Parse *pParse, Expr *pE1, Expr *pE2, int iTab){
  98588. if( sqlite3ExprCompare(pParse, pE1, pE2, iTab)==0 ){
  98589. return 1;
  98590. }
  98591. if( pE2->op==TK_OR
  98592. && (sqlite3ExprImpliesExpr(pParse, pE1, pE2->pLeft, iTab)
  98593. || sqlite3ExprImpliesExpr(pParse, pE1, pE2->pRight, iTab) )
  98594. ){
  98595. return 1;
  98596. }
  98597. if( pE2->op==TK_NOTNULL
  98598. && exprImpliesNotNull(pParse, pE1, pE2->pLeft, iTab, 0)
  98599. ){
  98600. return 1;
  98601. }
  98602. return 0;
  98603. }
  98604. /*
  98605. ** This is the Expr node callback for sqlite3ExprImpliesNonNullRow().
  98606. ** If the expression node requires that the table at pWalker->iCur
  98607. ** have one or more non-NULL column, then set pWalker->eCode to 1 and abort.
  98608. **
  98609. ** This routine controls an optimization. False positives (setting
  98610. ** pWalker->eCode to 1 when it should not be) are deadly, but false-negatives
  98611. ** (never setting pWalker->eCode) is a harmless missed optimization.
  98612. */
  98613. static int impliesNotNullRow(Walker *pWalker, Expr *pExpr){
  98614. testcase( pExpr->op==TK_AGG_COLUMN );
  98615. testcase( pExpr->op==TK_AGG_FUNCTION );
  98616. if( ExprHasProperty(pExpr, EP_FromJoin) ) return WRC_Prune;
  98617. switch( pExpr->op ){
  98618. case TK_ISNOT:
  98619. case TK_ISNULL:
  98620. case TK_NOTNULL:
  98621. case TK_IS:
  98622. case TK_OR:
  98623. case TK_VECTOR:
  98624. case TK_CASE:
  98625. case TK_IN:
  98626. case TK_FUNCTION:
  98627. case TK_TRUTH:
  98628. testcase( pExpr->op==TK_ISNOT );
  98629. testcase( pExpr->op==TK_ISNULL );
  98630. testcase( pExpr->op==TK_NOTNULL );
  98631. testcase( pExpr->op==TK_IS );
  98632. testcase( pExpr->op==TK_OR );
  98633. testcase( pExpr->op==TK_VECTOR );
  98634. testcase( pExpr->op==TK_CASE );
  98635. testcase( pExpr->op==TK_IN );
  98636. testcase( pExpr->op==TK_FUNCTION );
  98637. testcase( pExpr->op==TK_TRUTH );
  98638. return WRC_Prune;
  98639. case TK_COLUMN:
  98640. if( pWalker->u.iCur==pExpr->iTable ){
  98641. pWalker->eCode = 1;
  98642. return WRC_Abort;
  98643. }
  98644. return WRC_Prune;
  98645. case TK_AND:
  98646. if( pWalker->eCode==0 ){
  98647. sqlite3WalkExpr(pWalker, pExpr->pLeft);
  98648. if( pWalker->eCode ){
  98649. pWalker->eCode = 0;
  98650. sqlite3WalkExpr(pWalker, pExpr->pRight);
  98651. }
  98652. }
  98653. return WRC_Prune;
  98654. case TK_BETWEEN:
  98655. if( sqlite3WalkExpr(pWalker, pExpr->pLeft)==WRC_Abort ){
  98656. assert( pWalker->eCode );
  98657. return WRC_Abort;
  98658. }
  98659. return WRC_Prune;
  98660. /* Virtual tables are allowed to use constraints like x=NULL. So
  98661. ** a term of the form x=y does not prove that y is not null if x
  98662. ** is the column of a virtual table */
  98663. case TK_EQ:
  98664. case TK_NE:
  98665. case TK_LT:
  98666. case TK_LE:
  98667. case TK_GT:
  98668. case TK_GE: {
  98669. Expr *pLeft = pExpr->pLeft;
  98670. Expr *pRight = pExpr->pRight;
  98671. testcase( pExpr->op==TK_EQ );
  98672. testcase( pExpr->op==TK_NE );
  98673. testcase( pExpr->op==TK_LT );
  98674. testcase( pExpr->op==TK_LE );
  98675. testcase( pExpr->op==TK_GT );
  98676. testcase( pExpr->op==TK_GE );
  98677. /* The y.pTab=0 assignment in wherecode.c always happens after the
  98678. ** impliesNotNullRow() test */
  98679. if( (pLeft->op==TK_COLUMN && ALWAYS(pLeft->y.pTab!=0)
  98680. && IsVirtual(pLeft->y.pTab))
  98681. || (pRight->op==TK_COLUMN && ALWAYS(pRight->y.pTab!=0)
  98682. && IsVirtual(pRight->y.pTab))
  98683. ){
  98684. return WRC_Prune;
  98685. }
  98686. }
  98687. default:
  98688. return WRC_Continue;
  98689. }
  98690. }
  98691. /*
  98692. ** Return true (non-zero) if expression p can only be true if at least
  98693. ** one column of table iTab is non-null. In other words, return true
  98694. ** if expression p will always be NULL or false if every column of iTab
  98695. ** is NULL.
  98696. **
  98697. ** False negatives are acceptable. In other words, it is ok to return
  98698. ** zero even if expression p will never be true of every column of iTab
  98699. ** is NULL. A false negative is merely a missed optimization opportunity.
  98700. **
  98701. ** False positives are not allowed, however. A false positive may result
  98702. ** in an incorrect answer.
  98703. **
  98704. ** Terms of p that are marked with EP_FromJoin (and hence that come from
  98705. ** the ON or USING clauses of LEFT JOINS) are excluded from the analysis.
  98706. **
  98707. ** This routine is used to check if a LEFT JOIN can be converted into
  98708. ** an ordinary JOIN. The p argument is the WHERE clause. If the WHERE
  98709. ** clause requires that some column of the right table of the LEFT JOIN
  98710. ** be non-NULL, then the LEFT JOIN can be safely converted into an
  98711. ** ordinary join.
  98712. */
  98713. SQLITE_PRIVATE int sqlite3ExprImpliesNonNullRow(Expr *p, int iTab){
  98714. Walker w;
  98715. p = sqlite3ExprSkipCollateAndLikely(p);
  98716. if( p==0 ) return 0;
  98717. if( p->op==TK_NOTNULL ){
  98718. p = p->pLeft;
  98719. }else{
  98720. while( p->op==TK_AND ){
  98721. if( sqlite3ExprImpliesNonNullRow(p->pLeft, iTab) ) return 1;
  98722. p = p->pRight;
  98723. }
  98724. }
  98725. w.xExprCallback = impliesNotNullRow;
  98726. w.xSelectCallback = 0;
  98727. w.xSelectCallback2 = 0;
  98728. w.eCode = 0;
  98729. w.u.iCur = iTab;
  98730. sqlite3WalkExpr(&w, p);
  98731. return w.eCode;
  98732. }
  98733. /*
  98734. ** An instance of the following structure is used by the tree walker
  98735. ** to determine if an expression can be evaluated by reference to the
  98736. ** index only, without having to do a search for the corresponding
  98737. ** table entry. The IdxCover.pIdx field is the index. IdxCover.iCur
  98738. ** is the cursor for the table.
  98739. */
  98740. struct IdxCover {
  98741. Index *pIdx; /* The index to be tested for coverage */
  98742. int iCur; /* Cursor number for the table corresponding to the index */
  98743. };
  98744. /*
  98745. ** Check to see if there are references to columns in table
  98746. ** pWalker->u.pIdxCover->iCur can be satisfied using the index
  98747. ** pWalker->u.pIdxCover->pIdx.
  98748. */
  98749. static int exprIdxCover(Walker *pWalker, Expr *pExpr){
  98750. if( pExpr->op==TK_COLUMN
  98751. && pExpr->iTable==pWalker->u.pIdxCover->iCur
  98752. && sqlite3TableColumnToIndex(pWalker->u.pIdxCover->pIdx, pExpr->iColumn)<0
  98753. ){
  98754. pWalker->eCode = 1;
  98755. return WRC_Abort;
  98756. }
  98757. return WRC_Continue;
  98758. }
  98759. /*
  98760. ** Determine if an index pIdx on table with cursor iCur contains will
  98761. ** the expression pExpr. Return true if the index does cover the
  98762. ** expression and false if the pExpr expression references table columns
  98763. ** that are not found in the index pIdx.
  98764. **
  98765. ** An index covering an expression means that the expression can be
  98766. ** evaluated using only the index and without having to lookup the
  98767. ** corresponding table entry.
  98768. */
  98769. SQLITE_PRIVATE int sqlite3ExprCoveredByIndex(
  98770. Expr *pExpr, /* The index to be tested */
  98771. int iCur, /* The cursor number for the corresponding table */
  98772. Index *pIdx /* The index that might be used for coverage */
  98773. ){
  98774. Walker w;
  98775. struct IdxCover xcov;
  98776. memset(&w, 0, sizeof(w));
  98777. xcov.iCur = iCur;
  98778. xcov.pIdx = pIdx;
  98779. w.xExprCallback = exprIdxCover;
  98780. w.u.pIdxCover = &xcov;
  98781. sqlite3WalkExpr(&w, pExpr);
  98782. return !w.eCode;
  98783. }
  98784. /*
  98785. ** An instance of the following structure is used by the tree walker
  98786. ** to count references to table columns in the arguments of an
  98787. ** aggregate function, in order to implement the
  98788. ** sqlite3FunctionThisSrc() routine.
  98789. */
  98790. struct SrcCount {
  98791. SrcList *pSrc; /* One particular FROM clause in a nested query */
  98792. int nThis; /* Number of references to columns in pSrcList */
  98793. int nOther; /* Number of references to columns in other FROM clauses */
  98794. };
  98795. /*
  98796. ** Count the number of references to columns.
  98797. */
  98798. static int exprSrcCount(Walker *pWalker, Expr *pExpr){
  98799. /* There was once a NEVER() on the second term on the grounds that
  98800. ** sqlite3FunctionUsesThisSrc() was always called before
  98801. ** sqlite3ExprAnalyzeAggregates() and so the TK_COLUMNs have not yet
  98802. ** been converted into TK_AGG_COLUMN. But this is no longer true due
  98803. ** to window functions - sqlite3WindowRewrite() may now indirectly call
  98804. ** FunctionUsesThisSrc() when creating a new sub-select. */
  98805. if( pExpr->op==TK_COLUMN || pExpr->op==TK_AGG_COLUMN ){
  98806. int i;
  98807. struct SrcCount *p = pWalker->u.pSrcCount;
  98808. SrcList *pSrc = p->pSrc;
  98809. int nSrc = pSrc ? pSrc->nSrc : 0;
  98810. for(i=0; i<nSrc; i++){
  98811. if( pExpr->iTable==pSrc->a[i].iCursor ) break;
  98812. }
  98813. if( i<nSrc ){
  98814. p->nThis++;
  98815. }else if( nSrc==0 || pExpr->iTable<pSrc->a[0].iCursor ){
  98816. /* In a well-formed parse tree (no name resolution errors),
  98817. ** TK_COLUMN nodes with smaller Expr.iTable values are in an
  98818. ** outer context. Those are the only ones to count as "other" */
  98819. p->nOther++;
  98820. }
  98821. }
  98822. return WRC_Continue;
  98823. }
  98824. /*
  98825. ** Determine if any of the arguments to the pExpr Function reference
  98826. ** pSrcList. Return true if they do. Also return true if the function
  98827. ** has no arguments or has only constant arguments. Return false if pExpr
  98828. ** references columns but not columns of tables found in pSrcList.
  98829. */
  98830. SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr *pExpr, SrcList *pSrcList){
  98831. Walker w;
  98832. struct SrcCount cnt;
  98833. assert( pExpr->op==TK_AGG_FUNCTION );
  98834. memset(&w, 0, sizeof(w));
  98835. w.xExprCallback = exprSrcCount;
  98836. w.xSelectCallback = sqlite3SelectWalkNoop;
  98837. w.u.pSrcCount = &cnt;
  98838. cnt.pSrc = pSrcList;
  98839. cnt.nThis = 0;
  98840. cnt.nOther = 0;
  98841. sqlite3WalkExprList(&w, pExpr->x.pList);
  98842. #ifndef SQLITE_OMIT_WINDOWFUNC
  98843. if( ExprHasProperty(pExpr, EP_WinFunc) ){
  98844. sqlite3WalkExpr(&w, pExpr->y.pWin->pFilter);
  98845. }
  98846. #endif
  98847. return cnt.nThis>0 || cnt.nOther==0;
  98848. }
  98849. /*
  98850. ** Add a new element to the pAggInfo->aCol[] array. Return the index of
  98851. ** the new element. Return a negative number if malloc fails.
  98852. */
  98853. static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
  98854. int i;
  98855. pInfo->aCol = sqlite3ArrayAllocate(
  98856. db,
  98857. pInfo->aCol,
  98858. sizeof(pInfo->aCol[0]),
  98859. &pInfo->nColumn,
  98860. &i
  98861. );
  98862. return i;
  98863. }
  98864. /*
  98865. ** Add a new element to the pAggInfo->aFunc[] array. Return the index of
  98866. ** the new element. Return a negative number if malloc fails.
  98867. */
  98868. static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
  98869. int i;
  98870. pInfo->aFunc = sqlite3ArrayAllocate(
  98871. db,
  98872. pInfo->aFunc,
  98873. sizeof(pInfo->aFunc[0]),
  98874. &pInfo->nFunc,
  98875. &i
  98876. );
  98877. return i;
  98878. }
  98879. /*
  98880. ** This is the xExprCallback for a tree walker. It is used to
  98881. ** implement sqlite3ExprAnalyzeAggregates(). See sqlite3ExprAnalyzeAggregates
  98882. ** for additional information.
  98883. */
  98884. static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
  98885. int i;
  98886. NameContext *pNC = pWalker->u.pNC;
  98887. Parse *pParse = pNC->pParse;
  98888. SrcList *pSrcList = pNC->pSrcList;
  98889. AggInfo *pAggInfo = pNC->uNC.pAggInfo;
  98890. assert( pNC->ncFlags & NC_UAggInfo );
  98891. switch( pExpr->op ){
  98892. case TK_AGG_COLUMN:
  98893. case TK_COLUMN: {
  98894. testcase( pExpr->op==TK_AGG_COLUMN );
  98895. testcase( pExpr->op==TK_COLUMN );
  98896. /* Check to see if the column is in one of the tables in the FROM
  98897. ** clause of the aggregate query */
  98898. if( ALWAYS(pSrcList!=0) ){
  98899. struct SrcList_item *pItem = pSrcList->a;
  98900. for(i=0; i<pSrcList->nSrc; i++, pItem++){
  98901. struct AggInfo_col *pCol;
  98902. assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
  98903. if( pExpr->iTable==pItem->iCursor ){
  98904. /* If we reach this point, it means that pExpr refers to a table
  98905. ** that is in the FROM clause of the aggregate query.
  98906. **
  98907. ** Make an entry for the column in pAggInfo->aCol[] if there
  98908. ** is not an entry there already.
  98909. */
  98910. int k;
  98911. pCol = pAggInfo->aCol;
  98912. for(k=0; k<pAggInfo->nColumn; k++, pCol++){
  98913. if( pCol->iTable==pExpr->iTable &&
  98914. pCol->iColumn==pExpr->iColumn ){
  98915. break;
  98916. }
  98917. }
  98918. if( (k>=pAggInfo->nColumn)
  98919. && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
  98920. ){
  98921. pCol = &pAggInfo->aCol[k];
  98922. pCol->pTab = pExpr->y.pTab;
  98923. pCol->iTable = pExpr->iTable;
  98924. pCol->iColumn = pExpr->iColumn;
  98925. pCol->iMem = ++pParse->nMem;
  98926. pCol->iSorterColumn = -1;
  98927. pCol->pExpr = pExpr;
  98928. if( pAggInfo->pGroupBy ){
  98929. int j, n;
  98930. ExprList *pGB = pAggInfo->pGroupBy;
  98931. struct ExprList_item *pTerm = pGB->a;
  98932. n = pGB->nExpr;
  98933. for(j=0; j<n; j++, pTerm++){
  98934. Expr *pE = pTerm->pExpr;
  98935. if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
  98936. pE->iColumn==pExpr->iColumn ){
  98937. pCol->iSorterColumn = j;
  98938. break;
  98939. }
  98940. }
  98941. }
  98942. if( pCol->iSorterColumn<0 ){
  98943. pCol->iSorterColumn = pAggInfo->nSortingColumn++;
  98944. }
  98945. }
  98946. /* There is now an entry for pExpr in pAggInfo->aCol[] (either
  98947. ** because it was there before or because we just created it).
  98948. ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
  98949. ** pAggInfo->aCol[] entry.
  98950. */
  98951. ExprSetVVAProperty(pExpr, EP_NoReduce);
  98952. pExpr->pAggInfo = pAggInfo;
  98953. pExpr->op = TK_AGG_COLUMN;
  98954. pExpr->iAgg = (i16)k;
  98955. break;
  98956. } /* endif pExpr->iTable==pItem->iCursor */
  98957. } /* end loop over pSrcList */
  98958. }
  98959. return WRC_Prune;
  98960. }
  98961. case TK_AGG_FUNCTION: {
  98962. if( (pNC->ncFlags & NC_InAggFunc)==0
  98963. && pWalker->walkerDepth==pExpr->op2
  98964. ){
  98965. /* Check to see if pExpr is a duplicate of another aggregate
  98966. ** function that is already in the pAggInfo structure
  98967. */
  98968. struct AggInfo_func *pItem = pAggInfo->aFunc;
  98969. for(i=0; i<pAggInfo->nFunc; i++, pItem++){
  98970. if( sqlite3ExprCompare(0, pItem->pExpr, pExpr, -1)==0 ){
  98971. break;
  98972. }
  98973. }
  98974. if( i>=pAggInfo->nFunc ){
  98975. /* pExpr is original. Make a new entry in pAggInfo->aFunc[]
  98976. */
  98977. u8 enc = ENC(pParse->db);
  98978. i = addAggInfoFunc(pParse->db, pAggInfo);
  98979. if( i>=0 ){
  98980. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  98981. pItem = &pAggInfo->aFunc[i];
  98982. pItem->pExpr = pExpr;
  98983. pItem->iMem = ++pParse->nMem;
  98984. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  98985. pItem->pFunc = sqlite3FindFunction(pParse->db,
  98986. pExpr->u.zToken,
  98987. pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
  98988. if( pExpr->flags & EP_Distinct ){
  98989. pItem->iDistinct = pParse->nTab++;
  98990. }else{
  98991. pItem->iDistinct = -1;
  98992. }
  98993. }
  98994. }
  98995. /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
  98996. */
  98997. assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
  98998. ExprSetVVAProperty(pExpr, EP_NoReduce);
  98999. pExpr->iAgg = (i16)i;
  99000. pExpr->pAggInfo = pAggInfo;
  99001. return WRC_Prune;
  99002. }else{
  99003. return WRC_Continue;
  99004. }
  99005. }
  99006. }
  99007. return WRC_Continue;
  99008. }
  99009. /*
  99010. ** Analyze the pExpr expression looking for aggregate functions and
  99011. ** for variables that need to be added to AggInfo object that pNC->pAggInfo
  99012. ** points to. Additional entries are made on the AggInfo object as
  99013. ** necessary.
  99014. **
  99015. ** This routine should only be called after the expression has been
  99016. ** analyzed by sqlite3ResolveExprNames().
  99017. */
  99018. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
  99019. Walker w;
  99020. w.xExprCallback = analyzeAggregate;
  99021. w.xSelectCallback = sqlite3WalkerDepthIncrease;
  99022. w.xSelectCallback2 = sqlite3WalkerDepthDecrease;
  99023. w.walkerDepth = 0;
  99024. w.u.pNC = pNC;
  99025. w.pParse = 0;
  99026. assert( pNC->pSrcList!=0 );
  99027. sqlite3WalkExpr(&w, pExpr);
  99028. }
  99029. /*
  99030. ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
  99031. ** expression list. Return the number of errors.
  99032. **
  99033. ** If an error is found, the analysis is cut short.
  99034. */
  99035. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
  99036. struct ExprList_item *pItem;
  99037. int i;
  99038. if( pList ){
  99039. for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
  99040. sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
  99041. }
  99042. }
  99043. }
  99044. /*
  99045. ** Allocate a single new register for use to hold some intermediate result.
  99046. */
  99047. SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){
  99048. if( pParse->nTempReg==0 ){
  99049. return ++pParse->nMem;
  99050. }
  99051. return pParse->aTempReg[--pParse->nTempReg];
  99052. }
  99053. /*
  99054. ** Deallocate a register, making available for reuse for some other
  99055. ** purpose.
  99056. */
  99057. SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
  99058. if( iReg ){
  99059. sqlite3VdbeReleaseRegisters(pParse, iReg, 1, 0, 0);
  99060. if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
  99061. pParse->aTempReg[pParse->nTempReg++] = iReg;
  99062. }
  99063. }
  99064. }
  99065. /*
  99066. ** Allocate or deallocate a block of nReg consecutive registers.
  99067. */
  99068. SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){
  99069. int i, n;
  99070. if( nReg==1 ) return sqlite3GetTempReg(pParse);
  99071. i = pParse->iRangeReg;
  99072. n = pParse->nRangeReg;
  99073. if( nReg<=n ){
  99074. pParse->iRangeReg += nReg;
  99075. pParse->nRangeReg -= nReg;
  99076. }else{
  99077. i = pParse->nMem+1;
  99078. pParse->nMem += nReg;
  99079. }
  99080. return i;
  99081. }
  99082. SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
  99083. if( nReg==1 ){
  99084. sqlite3ReleaseTempReg(pParse, iReg);
  99085. return;
  99086. }
  99087. sqlite3VdbeReleaseRegisters(pParse, iReg, nReg, 0, 0);
  99088. if( nReg>pParse->nRangeReg ){
  99089. pParse->nRangeReg = nReg;
  99090. pParse->iRangeReg = iReg;
  99091. }
  99092. }
  99093. /*
  99094. ** Mark all temporary registers as being unavailable for reuse.
  99095. **
  99096. ** Always invoke this procedure after coding a subroutine or co-routine
  99097. ** that might be invoked from other parts of the code, to ensure that
  99098. ** the sub/co-routine does not use registers in common with the code that
  99099. ** invokes the sub/co-routine.
  99100. */
  99101. SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse *pParse){
  99102. pParse->nTempReg = 0;
  99103. pParse->nRangeReg = 0;
  99104. }
  99105. /*
  99106. ** Validate that no temporary register falls within the range of
  99107. ** iFirst..iLast, inclusive. This routine is only call from within assert()
  99108. ** statements.
  99109. */
  99110. #ifdef SQLITE_DEBUG
  99111. SQLITE_PRIVATE int sqlite3NoTempsInRange(Parse *pParse, int iFirst, int iLast){
  99112. int i;
  99113. if( pParse->nRangeReg>0
  99114. && pParse->iRangeReg+pParse->nRangeReg > iFirst
  99115. && pParse->iRangeReg <= iLast
  99116. ){
  99117. return 0;
  99118. }
  99119. for(i=0; i<pParse->nTempReg; i++){
  99120. if( pParse->aTempReg[i]>=iFirst && pParse->aTempReg[i]<=iLast ){
  99121. return 0;
  99122. }
  99123. }
  99124. return 1;
  99125. }
  99126. #endif /* SQLITE_DEBUG */
  99127. /************** End of expr.c ************************************************/
  99128. /************** Begin file alter.c *******************************************/
  99129. /*
  99130. ** 2005 February 15
  99131. **
  99132. ** The author disclaims copyright to this source code. In place of
  99133. ** a legal notice, here is a blessing:
  99134. **
  99135. ** May you do good and not evil.
  99136. ** May you find forgiveness for yourself and forgive others.
  99137. ** May you share freely, never taking more than you give.
  99138. **
  99139. *************************************************************************
  99140. ** This file contains C code routines that used to generate VDBE code
  99141. ** that implements the ALTER TABLE command.
  99142. */
  99143. /* #include "sqliteInt.h" */
  99144. /*
  99145. ** The code in this file only exists if we are not omitting the
  99146. ** ALTER TABLE logic from the build.
  99147. */
  99148. #ifndef SQLITE_OMIT_ALTERTABLE
  99149. /*
  99150. ** Parameter zName is the name of a table that is about to be altered
  99151. ** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN).
  99152. ** If the table is a system table, this function leaves an error message
  99153. ** in pParse->zErr (system tables may not be altered) and returns non-zero.
  99154. **
  99155. ** Or, if zName is not a system table, zero is returned.
  99156. */
  99157. static int isAlterableTable(Parse *pParse, Table *pTab){
  99158. if( 0==sqlite3StrNICmp(pTab->zName, "sqlite_", 7)
  99159. #ifndef SQLITE_OMIT_VIRTUALTABLE
  99160. || ( (pTab->tabFlags & TF_Shadow)!=0
  99161. && sqlite3ReadOnlyShadowTables(pParse->db)
  99162. )
  99163. #endif
  99164. ){
  99165. sqlite3ErrorMsg(pParse, "table %s may not be altered", pTab->zName);
  99166. return 1;
  99167. }
  99168. return 0;
  99169. }
  99170. /*
  99171. ** Generate code to verify that the schemas of database zDb and, if
  99172. ** bTemp is not true, database "temp", can still be parsed. This is
  99173. ** called at the end of the generation of an ALTER TABLE ... RENAME ...
  99174. ** statement to ensure that the operation has not rendered any schema
  99175. ** objects unusable.
  99176. */
  99177. static void renameTestSchema(Parse *pParse, const char *zDb, int bTemp){
  99178. sqlite3NestedParse(pParse,
  99179. "SELECT 1 "
  99180. "FROM \"%w\".%s "
  99181. "WHERE name NOT LIKE 'sqliteX_%%' ESCAPE 'X'"
  99182. " AND sql NOT LIKE 'create virtual%%'"
  99183. " AND sqlite_rename_test(%Q, sql, type, name, %d)=NULL ",
  99184. zDb, MASTER_NAME,
  99185. zDb, bTemp
  99186. );
  99187. if( bTemp==0 ){
  99188. sqlite3NestedParse(pParse,
  99189. "SELECT 1 "
  99190. "FROM temp.%s "
  99191. "WHERE name NOT LIKE 'sqliteX_%%' ESCAPE 'X'"
  99192. " AND sql NOT LIKE 'create virtual%%'"
  99193. " AND sqlite_rename_test(%Q, sql, type, name, 1)=NULL ",
  99194. MASTER_NAME, zDb
  99195. );
  99196. }
  99197. }
  99198. /*
  99199. ** Generate code to reload the schema for database iDb. And, if iDb!=1, for
  99200. ** the temp database as well.
  99201. */
  99202. static void renameReloadSchema(Parse *pParse, int iDb){
  99203. Vdbe *v = pParse->pVdbe;
  99204. if( v ){
  99205. sqlite3ChangeCookie(pParse, iDb);
  99206. sqlite3VdbeAddParseSchemaOp(pParse->pVdbe, iDb, 0);
  99207. if( iDb!=1 ) sqlite3VdbeAddParseSchemaOp(pParse->pVdbe, 1, 0);
  99208. }
  99209. }
  99210. /*
  99211. ** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
  99212. ** command.
  99213. */
  99214. SQLITE_PRIVATE void sqlite3AlterRenameTable(
  99215. Parse *pParse, /* Parser context. */
  99216. SrcList *pSrc, /* The table to rename. */
  99217. Token *pName /* The new table name. */
  99218. ){
  99219. int iDb; /* Database that contains the table */
  99220. char *zDb; /* Name of database iDb */
  99221. Table *pTab; /* Table being renamed */
  99222. char *zName = 0; /* NULL-terminated version of pName */
  99223. sqlite3 *db = pParse->db; /* Database connection */
  99224. int nTabName; /* Number of UTF-8 characters in zTabName */
  99225. const char *zTabName; /* Original name of the table */
  99226. Vdbe *v;
  99227. VTable *pVTab = 0; /* Non-zero if this is a v-tab with an xRename() */
  99228. u32 savedDbFlags; /* Saved value of db->mDbFlags */
  99229. savedDbFlags = db->mDbFlags;
  99230. if( NEVER(db->mallocFailed) ) goto exit_rename_table;
  99231. assert( pSrc->nSrc==1 );
  99232. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  99233. pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
  99234. if( !pTab ) goto exit_rename_table;
  99235. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  99236. zDb = db->aDb[iDb].zDbSName;
  99237. db->mDbFlags |= DBFLAG_PreferBuiltin;
  99238. /* Get a NULL terminated version of the new table name. */
  99239. zName = sqlite3NameFromToken(db, pName);
  99240. if( !zName ) goto exit_rename_table;
  99241. /* Check that a table or index named 'zName' does not already exist
  99242. ** in database iDb. If so, this is an error.
  99243. */
  99244. if( sqlite3FindTable(db, zName, zDb)
  99245. || sqlite3FindIndex(db, zName, zDb)
  99246. || sqlite3IsShadowTableOf(db, pTab, zName)
  99247. ){
  99248. sqlite3ErrorMsg(pParse,
  99249. "there is already another table or index with this name: %s", zName);
  99250. goto exit_rename_table;
  99251. }
  99252. /* Make sure it is not a system table being altered, or a reserved name
  99253. ** that the table is being renamed to.
  99254. */
  99255. if( SQLITE_OK!=isAlterableTable(pParse, pTab) ){
  99256. goto exit_rename_table;
  99257. }
  99258. if( SQLITE_OK!=sqlite3CheckObjectName(pParse,zName,"table",zName) ){
  99259. goto exit_rename_table;
  99260. }
  99261. #ifndef SQLITE_OMIT_VIEW
  99262. if( pTab->pSelect ){
  99263. sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
  99264. goto exit_rename_table;
  99265. }
  99266. #endif
  99267. #ifndef SQLITE_OMIT_AUTHORIZATION
  99268. /* Invoke the authorization callback. */
  99269. if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
  99270. goto exit_rename_table;
  99271. }
  99272. #endif
  99273. #ifndef SQLITE_OMIT_VIRTUALTABLE
  99274. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  99275. goto exit_rename_table;
  99276. }
  99277. if( IsVirtual(pTab) ){
  99278. pVTab = sqlite3GetVTable(db, pTab);
  99279. if( pVTab->pVtab->pModule->xRename==0 ){
  99280. pVTab = 0;
  99281. }
  99282. }
  99283. #endif
  99284. /* Begin a transaction for database iDb. Then modify the schema cookie
  99285. ** (since the ALTER TABLE modifies the schema). Call sqlite3MayAbort(),
  99286. ** as the scalar functions (e.g. sqlite_rename_table()) invoked by the
  99287. ** nested SQL may raise an exception. */
  99288. v = sqlite3GetVdbe(pParse);
  99289. if( v==0 ){
  99290. goto exit_rename_table;
  99291. }
  99292. sqlite3MayAbort(pParse);
  99293. /* figure out how many UTF-8 characters are in zName */
  99294. zTabName = pTab->zName;
  99295. nTabName = sqlite3Utf8CharLen(zTabName, -1);
  99296. /* Rewrite all CREATE TABLE, INDEX, TRIGGER or VIEW statements in
  99297. ** the schema to use the new table name. */
  99298. sqlite3NestedParse(pParse,
  99299. "UPDATE \"%w\".%s SET "
  99300. "sql = sqlite_rename_table(%Q, type, name, sql, %Q, %Q, %d) "
  99301. "WHERE (type!='index' OR tbl_name=%Q COLLATE nocase)"
  99302. "AND name NOT LIKE 'sqliteX_%%' ESCAPE 'X'"
  99303. , zDb, MASTER_NAME, zDb, zTabName, zName, (iDb==1), zTabName
  99304. );
  99305. /* Update the tbl_name and name columns of the sqlite_master table
  99306. ** as required. */
  99307. sqlite3NestedParse(pParse,
  99308. "UPDATE %Q.%s SET "
  99309. "tbl_name = %Q, "
  99310. "name = CASE "
  99311. "WHEN type='table' THEN %Q "
  99312. "WHEN name LIKE 'sqliteX_autoindex%%' ESCAPE 'X' "
  99313. " AND type='index' THEN "
  99314. "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
  99315. "ELSE name END "
  99316. "WHERE tbl_name=%Q COLLATE nocase AND "
  99317. "(type='table' OR type='index' OR type='trigger');",
  99318. zDb, MASTER_NAME,
  99319. zName, zName, zName,
  99320. nTabName, zTabName
  99321. );
  99322. #ifndef SQLITE_OMIT_AUTOINCREMENT
  99323. /* If the sqlite_sequence table exists in this database, then update
  99324. ** it with the new table name.
  99325. */
  99326. if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
  99327. sqlite3NestedParse(pParse,
  99328. "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
  99329. zDb, zName, pTab->zName);
  99330. }
  99331. #endif
  99332. /* If the table being renamed is not itself part of the temp database,
  99333. ** edit view and trigger definitions within the temp database
  99334. ** as required. */
  99335. if( iDb!=1 ){
  99336. sqlite3NestedParse(pParse,
  99337. "UPDATE sqlite_temp_master SET "
  99338. "sql = sqlite_rename_table(%Q, type, name, sql, %Q, %Q, 1), "
  99339. "tbl_name = "
  99340. "CASE WHEN tbl_name=%Q COLLATE nocase AND "
  99341. " sqlite_rename_test(%Q, sql, type, name, 1) "
  99342. "THEN %Q ELSE tbl_name END "
  99343. "WHERE type IN ('view', 'trigger')"
  99344. , zDb, zTabName, zName, zTabName, zDb, zName);
  99345. }
  99346. /* If this is a virtual table, invoke the xRename() function if
  99347. ** one is defined. The xRename() callback will modify the names
  99348. ** of any resources used by the v-table implementation (including other
  99349. ** SQLite tables) that are identified by the name of the virtual table.
  99350. */
  99351. #ifndef SQLITE_OMIT_VIRTUALTABLE
  99352. if( pVTab ){
  99353. int i = ++pParse->nMem;
  99354. sqlite3VdbeLoadString(v, i, zName);
  99355. sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
  99356. }
  99357. #endif
  99358. renameReloadSchema(pParse, iDb);
  99359. renameTestSchema(pParse, zDb, iDb==1);
  99360. exit_rename_table:
  99361. sqlite3SrcListDelete(db, pSrc);
  99362. sqlite3DbFree(db, zName);
  99363. db->mDbFlags = savedDbFlags;
  99364. }
  99365. /*
  99366. ** Write code that will raise an error if the table described by
  99367. ** zDb and zTab is not empty.
  99368. */
  99369. static void sqlite3ErrorIfNotEmpty(
  99370. Parse *pParse, /* Parsing context */
  99371. const char *zDb, /* Schema holding the table */
  99372. const char *zTab, /* Table to check for empty */
  99373. const char *zErr /* Error message text */
  99374. ){
  99375. sqlite3NestedParse(pParse,
  99376. "SELECT raise(ABORT,%Q) FROM \"%w\".\"%w\"",
  99377. zErr, zDb, zTab
  99378. );
  99379. }
  99380. /*
  99381. ** This function is called after an "ALTER TABLE ... ADD" statement
  99382. ** has been parsed. Argument pColDef contains the text of the new
  99383. ** column definition.
  99384. **
  99385. ** The Table structure pParse->pNewTable was extended to include
  99386. ** the new column during parsing.
  99387. */
  99388. SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
  99389. Table *pNew; /* Copy of pParse->pNewTable */
  99390. Table *pTab; /* Table being altered */
  99391. int iDb; /* Database number */
  99392. const char *zDb; /* Database name */
  99393. const char *zTab; /* Table name */
  99394. char *zCol; /* Null-terminated column definition */
  99395. Column *pCol; /* The new column */
  99396. Expr *pDflt; /* Default value for the new column */
  99397. sqlite3 *db; /* The database connection; */
  99398. Vdbe *v; /* The prepared statement under construction */
  99399. int r1; /* Temporary registers */
  99400. db = pParse->db;
  99401. if( pParse->nErr || db->mallocFailed ) return;
  99402. pNew = pParse->pNewTable;
  99403. assert( pNew );
  99404. assert( sqlite3BtreeHoldsAllMutexes(db) );
  99405. iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
  99406. zDb = db->aDb[iDb].zDbSName;
  99407. zTab = &pNew->zName[16]; /* Skip the "sqlite_altertab_" prefix on the name */
  99408. pCol = &pNew->aCol[pNew->nCol-1];
  99409. pDflt = pCol->pDflt;
  99410. pTab = sqlite3FindTable(db, zTab, zDb);
  99411. assert( pTab );
  99412. #ifndef SQLITE_OMIT_AUTHORIZATION
  99413. /* Invoke the authorization callback. */
  99414. if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
  99415. return;
  99416. }
  99417. #endif
  99418. /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
  99419. ** If there is a NOT NULL constraint, then the default value for the
  99420. ** column must not be NULL.
  99421. */
  99422. if( pCol->colFlags & COLFLAG_PRIMKEY ){
  99423. sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
  99424. return;
  99425. }
  99426. if( pNew->pIndex ){
  99427. sqlite3ErrorMsg(pParse,
  99428. "Cannot add a UNIQUE column");
  99429. return;
  99430. }
  99431. if( (pCol->colFlags & COLFLAG_GENERATED)==0 ){
  99432. /* If the default value for the new column was specified with a
  99433. ** literal NULL, then set pDflt to 0. This simplifies checking
  99434. ** for an SQL NULL default below.
  99435. */
  99436. assert( pDflt==0 || pDflt->op==TK_SPAN );
  99437. if( pDflt && pDflt->pLeft->op==TK_NULL ){
  99438. pDflt = 0;
  99439. }
  99440. if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
  99441. sqlite3ErrorIfNotEmpty(pParse, zDb, zTab,
  99442. "Cannot add a REFERENCES column with non-NULL default value");
  99443. }
  99444. if( pCol->notNull && !pDflt ){
  99445. sqlite3ErrorIfNotEmpty(pParse, zDb, zTab,
  99446. "Cannot add a NOT NULL column with default value NULL");
  99447. }
  99448. /* Ensure the default expression is something that sqlite3ValueFromExpr()
  99449. ** can handle (i.e. not CURRENT_TIME etc.)
  99450. */
  99451. if( pDflt ){
  99452. sqlite3_value *pVal = 0;
  99453. int rc;
  99454. rc = sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_BLOB, &pVal);
  99455. assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
  99456. if( rc!=SQLITE_OK ){
  99457. assert( db->mallocFailed == 1 );
  99458. return;
  99459. }
  99460. if( !pVal ){
  99461. sqlite3ErrorIfNotEmpty(pParse, zDb, zTab,
  99462. "Cannot add a column with non-constant default");
  99463. }
  99464. sqlite3ValueFree(pVal);
  99465. }
  99466. }else if( pCol->colFlags & COLFLAG_STORED ){
  99467. sqlite3ErrorIfNotEmpty(pParse, zDb, zTab, "cannot add a STORED column");
  99468. }
  99469. /* Modify the CREATE TABLE statement. */
  99470. zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
  99471. if( zCol ){
  99472. char *zEnd = &zCol[pColDef->n-1];
  99473. u32 savedDbFlags = db->mDbFlags;
  99474. while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
  99475. *zEnd-- = '\0';
  99476. }
  99477. db->mDbFlags |= DBFLAG_PreferBuiltin;
  99478. sqlite3NestedParse(pParse,
  99479. "UPDATE \"%w\".%s SET "
  99480. "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
  99481. "WHERE type = 'table' AND name = %Q",
  99482. zDb, MASTER_NAME, pNew->addColOffset, zCol, pNew->addColOffset+1,
  99483. zTab
  99484. );
  99485. sqlite3DbFree(db, zCol);
  99486. db->mDbFlags = savedDbFlags;
  99487. }
  99488. /* Make sure the schema version is at least 3. But do not upgrade
  99489. ** from less than 3 to 4, as that will corrupt any preexisting DESC
  99490. ** index.
  99491. */
  99492. v = sqlite3GetVdbe(pParse);
  99493. if( v ){
  99494. r1 = sqlite3GetTempReg(pParse);
  99495. sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
  99496. sqlite3VdbeUsesBtree(v, iDb);
  99497. sqlite3VdbeAddOp2(v, OP_AddImm, r1, -2);
  99498. sqlite3VdbeAddOp2(v, OP_IfPos, r1, sqlite3VdbeCurrentAddr(v)+2);
  99499. VdbeCoverage(v);
  99500. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, 3);
  99501. sqlite3ReleaseTempReg(pParse, r1);
  99502. }
  99503. /* Reload the table definition */
  99504. renameReloadSchema(pParse, iDb);
  99505. }
  99506. /*
  99507. ** This function is called by the parser after the table-name in
  99508. ** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
  99509. ** pSrc is the full-name of the table being altered.
  99510. **
  99511. ** This routine makes a (partial) copy of the Table structure
  99512. ** for the table being altered and sets Parse.pNewTable to point
  99513. ** to it. Routines called by the parser as the column definition
  99514. ** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
  99515. ** the copy. The copy of the Table structure is deleted by tokenize.c
  99516. ** after parsing is finished.
  99517. **
  99518. ** Routine sqlite3AlterFinishAddColumn() will be called to complete
  99519. ** coding the "ALTER TABLE ... ADD" statement.
  99520. */
  99521. SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
  99522. Table *pNew;
  99523. Table *pTab;
  99524. int iDb;
  99525. int i;
  99526. int nAlloc;
  99527. sqlite3 *db = pParse->db;
  99528. /* Look up the table being altered. */
  99529. assert( pParse->pNewTable==0 );
  99530. assert( sqlite3BtreeHoldsAllMutexes(db) );
  99531. if( db->mallocFailed ) goto exit_begin_add_column;
  99532. pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
  99533. if( !pTab ) goto exit_begin_add_column;
  99534. #ifndef SQLITE_OMIT_VIRTUALTABLE
  99535. if( IsVirtual(pTab) ){
  99536. sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
  99537. goto exit_begin_add_column;
  99538. }
  99539. #endif
  99540. /* Make sure this is not an attempt to ALTER a view. */
  99541. if( pTab->pSelect ){
  99542. sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
  99543. goto exit_begin_add_column;
  99544. }
  99545. if( SQLITE_OK!=isAlterableTable(pParse, pTab) ){
  99546. goto exit_begin_add_column;
  99547. }
  99548. sqlite3MayAbort(pParse);
  99549. assert( pTab->addColOffset>0 );
  99550. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  99551. /* Put a copy of the Table struct in Parse.pNewTable for the
  99552. ** sqlite3AddColumn() function and friends to modify. But modify
  99553. ** the name by adding an "sqlite_altertab_" prefix. By adding this
  99554. ** prefix, we insure that the name will not collide with an existing
  99555. ** table because user table are not allowed to have the "sqlite_"
  99556. ** prefix on their name.
  99557. */
  99558. pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
  99559. if( !pNew ) goto exit_begin_add_column;
  99560. pParse->pNewTable = pNew;
  99561. pNew->nTabRef = 1;
  99562. pNew->nCol = pTab->nCol;
  99563. assert( pNew->nCol>0 );
  99564. nAlloc = (((pNew->nCol-1)/8)*8)+8;
  99565. assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
  99566. pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
  99567. pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
  99568. if( !pNew->aCol || !pNew->zName ){
  99569. assert( db->mallocFailed );
  99570. goto exit_begin_add_column;
  99571. }
  99572. memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
  99573. for(i=0; i<pNew->nCol; i++){
  99574. Column *pCol = &pNew->aCol[i];
  99575. pCol->zName = sqlite3DbStrDup(db, pCol->zName);
  99576. pCol->hName = sqlite3StrIHash(pCol->zName);
  99577. pCol->zColl = 0;
  99578. pCol->pDflt = 0;
  99579. }
  99580. pNew->pSchema = db->aDb[iDb].pSchema;
  99581. pNew->addColOffset = pTab->addColOffset;
  99582. pNew->nTabRef = 1;
  99583. exit_begin_add_column:
  99584. sqlite3SrcListDelete(db, pSrc);
  99585. return;
  99586. }
  99587. /*
  99588. ** Parameter pTab is the subject of an ALTER TABLE ... RENAME COLUMN
  99589. ** command. This function checks if the table is a view or virtual
  99590. ** table (columns of views or virtual tables may not be renamed). If so,
  99591. ** it loads an error message into pParse and returns non-zero.
  99592. **
  99593. ** Or, if pTab is not a view or virtual table, zero is returned.
  99594. */
  99595. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
  99596. static int isRealTable(Parse *pParse, Table *pTab){
  99597. const char *zType = 0;
  99598. #ifndef SQLITE_OMIT_VIEW
  99599. if( pTab->pSelect ){
  99600. zType = "view";
  99601. }
  99602. #endif
  99603. #ifndef SQLITE_OMIT_VIRTUALTABLE
  99604. if( IsVirtual(pTab) ){
  99605. zType = "virtual table";
  99606. }
  99607. #endif
  99608. if( zType ){
  99609. sqlite3ErrorMsg(
  99610. pParse, "cannot rename columns of %s \"%s\"", zType, pTab->zName
  99611. );
  99612. return 1;
  99613. }
  99614. return 0;
  99615. }
  99616. #else /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
  99617. # define isRealTable(x,y) (0)
  99618. #endif
  99619. /*
  99620. ** Handles the following parser reduction:
  99621. **
  99622. ** cmd ::= ALTER TABLE pSrc RENAME COLUMN pOld TO pNew
  99623. */
  99624. SQLITE_PRIVATE void sqlite3AlterRenameColumn(
  99625. Parse *pParse, /* Parsing context */
  99626. SrcList *pSrc, /* Table being altered. pSrc->nSrc==1 */
  99627. Token *pOld, /* Name of column being changed */
  99628. Token *pNew /* New column name */
  99629. ){
  99630. sqlite3 *db = pParse->db; /* Database connection */
  99631. Table *pTab; /* Table being updated */
  99632. int iCol; /* Index of column being renamed */
  99633. char *zOld = 0; /* Old column name */
  99634. char *zNew = 0; /* New column name */
  99635. const char *zDb; /* Name of schema containing the table */
  99636. int iSchema; /* Index of the schema */
  99637. int bQuote; /* True to quote the new name */
  99638. /* Locate the table to be altered */
  99639. pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
  99640. if( !pTab ) goto exit_rename_column;
  99641. /* Cannot alter a system table */
  99642. if( SQLITE_OK!=isAlterableTable(pParse, pTab) ) goto exit_rename_column;
  99643. if( SQLITE_OK!=isRealTable(pParse, pTab) ) goto exit_rename_column;
  99644. /* Which schema holds the table to be altered */
  99645. iSchema = sqlite3SchemaToIndex(db, pTab->pSchema);
  99646. assert( iSchema>=0 );
  99647. zDb = db->aDb[iSchema].zDbSName;
  99648. #ifndef SQLITE_OMIT_AUTHORIZATION
  99649. /* Invoke the authorization callback. */
  99650. if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
  99651. goto exit_rename_column;
  99652. }
  99653. #endif
  99654. /* Make sure the old name really is a column name in the table to be
  99655. ** altered. Set iCol to be the index of the column being renamed */
  99656. zOld = sqlite3NameFromToken(db, pOld);
  99657. if( !zOld ) goto exit_rename_column;
  99658. for(iCol=0; iCol<pTab->nCol; iCol++){
  99659. if( 0==sqlite3StrICmp(pTab->aCol[iCol].zName, zOld) ) break;
  99660. }
  99661. if( iCol==pTab->nCol ){
  99662. sqlite3ErrorMsg(pParse, "no such column: \"%s\"", zOld);
  99663. goto exit_rename_column;
  99664. }
  99665. /* Do the rename operation using a recursive UPDATE statement that
  99666. ** uses the sqlite_rename_column() SQL function to compute the new
  99667. ** CREATE statement text for the sqlite_master table.
  99668. */
  99669. sqlite3MayAbort(pParse);
  99670. zNew = sqlite3NameFromToken(db, pNew);
  99671. if( !zNew ) goto exit_rename_column;
  99672. assert( pNew->n>0 );
  99673. bQuote = sqlite3Isquote(pNew->z[0]);
  99674. sqlite3NestedParse(pParse,
  99675. "UPDATE \"%w\".%s SET "
  99676. "sql = sqlite_rename_column(sql, type, name, %Q, %Q, %d, %Q, %d, %d) "
  99677. "WHERE name NOT LIKE 'sqliteX_%%' ESCAPE 'X' "
  99678. " AND (type != 'index' OR tbl_name = %Q)"
  99679. " AND sql NOT LIKE 'create virtual%%'",
  99680. zDb, MASTER_NAME,
  99681. zDb, pTab->zName, iCol, zNew, bQuote, iSchema==1,
  99682. pTab->zName
  99683. );
  99684. sqlite3NestedParse(pParse,
  99685. "UPDATE temp.%s SET "
  99686. "sql = sqlite_rename_column(sql, type, name, %Q, %Q, %d, %Q, %d, 1) "
  99687. "WHERE type IN ('trigger', 'view')",
  99688. MASTER_NAME,
  99689. zDb, pTab->zName, iCol, zNew, bQuote
  99690. );
  99691. /* Drop and reload the database schema. */
  99692. renameReloadSchema(pParse, iSchema);
  99693. renameTestSchema(pParse, zDb, iSchema==1);
  99694. exit_rename_column:
  99695. sqlite3SrcListDelete(db, pSrc);
  99696. sqlite3DbFree(db, zOld);
  99697. sqlite3DbFree(db, zNew);
  99698. return;
  99699. }
  99700. /*
  99701. ** Each RenameToken object maps an element of the parse tree into
  99702. ** the token that generated that element. The parse tree element
  99703. ** might be one of:
  99704. **
  99705. ** * A pointer to an Expr that represents an ID
  99706. ** * The name of a table column in Column.zName
  99707. **
  99708. ** A list of RenameToken objects can be constructed during parsing.
  99709. ** Each new object is created by sqlite3RenameTokenMap().
  99710. ** As the parse tree is transformed, the sqlite3RenameTokenRemap()
  99711. ** routine is used to keep the mapping current.
  99712. **
  99713. ** After the parse finishes, renameTokenFind() routine can be used
  99714. ** to look up the actual token value that created some element in
  99715. ** the parse tree.
  99716. */
  99717. struct RenameToken {
  99718. void *p; /* Parse tree element created by token t */
  99719. Token t; /* The token that created parse tree element p */
  99720. RenameToken *pNext; /* Next is a list of all RenameToken objects */
  99721. };
  99722. /*
  99723. ** The context of an ALTER TABLE RENAME COLUMN operation that gets passed
  99724. ** down into the Walker.
  99725. */
  99726. typedef struct RenameCtx RenameCtx;
  99727. struct RenameCtx {
  99728. RenameToken *pList; /* List of tokens to overwrite */
  99729. int nList; /* Number of tokens in pList */
  99730. int iCol; /* Index of column being renamed */
  99731. Table *pTab; /* Table being ALTERed */
  99732. const char *zOld; /* Old column name */
  99733. };
  99734. #ifdef SQLITE_DEBUG
  99735. /*
  99736. ** This function is only for debugging. It performs two tasks:
  99737. **
  99738. ** 1. Checks that pointer pPtr does not already appear in the
  99739. ** rename-token list.
  99740. **
  99741. ** 2. Dereferences each pointer in the rename-token list.
  99742. **
  99743. ** The second is most effective when debugging under valgrind or
  99744. ** address-sanitizer or similar. If any of these pointers no longer
  99745. ** point to valid objects, an exception is raised by the memory-checking
  99746. ** tool.
  99747. **
  99748. ** The point of this is to prevent comparisons of invalid pointer values.
  99749. ** Even though this always seems to work, it is undefined according to the
  99750. ** C standard. Example of undefined comparison:
  99751. **
  99752. ** sqlite3_free(x);
  99753. ** if( x==y ) ...
  99754. **
  99755. ** Technically, as x no longer points into a valid object or to the byte
  99756. ** following a valid object, it may not be used in comparison operations.
  99757. */
  99758. static void renameTokenCheckAll(Parse *pParse, void *pPtr){
  99759. if( pParse->nErr==0 && pParse->db->mallocFailed==0 ){
  99760. RenameToken *p;
  99761. u8 i = 0;
  99762. for(p=pParse->pRename; p; p=p->pNext){
  99763. if( p->p ){
  99764. assert( p->p!=pPtr );
  99765. i += *(u8*)(p->p);
  99766. }
  99767. }
  99768. }
  99769. }
  99770. #else
  99771. # define renameTokenCheckAll(x,y)
  99772. #endif
  99773. /*
  99774. ** Remember that the parser tree element pPtr was created using
  99775. ** the token pToken.
  99776. **
  99777. ** In other words, construct a new RenameToken object and add it
  99778. ** to the list of RenameToken objects currently being built up
  99779. ** in pParse->pRename.
  99780. **
  99781. ** The pPtr argument is returned so that this routine can be used
  99782. ** with tail recursion in tokenExpr() routine, for a small performance
  99783. ** improvement.
  99784. */
  99785. SQLITE_PRIVATE void *sqlite3RenameTokenMap(Parse *pParse, void *pPtr, Token *pToken){
  99786. RenameToken *pNew;
  99787. assert( pPtr || pParse->db->mallocFailed );
  99788. renameTokenCheckAll(pParse, pPtr);
  99789. if( ALWAYS(pParse->eParseMode!=PARSE_MODE_UNMAP) ){
  99790. pNew = sqlite3DbMallocZero(pParse->db, sizeof(RenameToken));
  99791. if( pNew ){
  99792. pNew->p = pPtr;
  99793. pNew->t = *pToken;
  99794. pNew->pNext = pParse->pRename;
  99795. pParse->pRename = pNew;
  99796. }
  99797. }
  99798. return pPtr;
  99799. }
  99800. /*
  99801. ** It is assumed that there is already a RenameToken object associated
  99802. ** with parse tree element pFrom. This function remaps the associated token
  99803. ** to parse tree element pTo.
  99804. */
  99805. SQLITE_PRIVATE void sqlite3RenameTokenRemap(Parse *pParse, void *pTo, void *pFrom){
  99806. RenameToken *p;
  99807. renameTokenCheckAll(pParse, pTo);
  99808. for(p=pParse->pRename; p; p=p->pNext){
  99809. if( p->p==pFrom ){
  99810. p->p = pTo;
  99811. break;
  99812. }
  99813. }
  99814. }
  99815. /*
  99816. ** Walker callback used by sqlite3RenameExprUnmap().
  99817. */
  99818. static int renameUnmapExprCb(Walker *pWalker, Expr *pExpr){
  99819. Parse *pParse = pWalker->pParse;
  99820. sqlite3RenameTokenRemap(pParse, 0, (void*)pExpr);
  99821. return WRC_Continue;
  99822. }
  99823. /*
  99824. ** Iterate through the Select objects that are part of WITH clauses attached
  99825. ** to select statement pSelect.
  99826. */
  99827. static void renameWalkWith(Walker *pWalker, Select *pSelect){
  99828. With *pWith = pSelect->pWith;
  99829. if( pWith ){
  99830. int i;
  99831. for(i=0; i<pWith->nCte; i++){
  99832. Select *p = pWith->a[i].pSelect;
  99833. NameContext sNC;
  99834. memset(&sNC, 0, sizeof(sNC));
  99835. sNC.pParse = pWalker->pParse;
  99836. sqlite3SelectPrep(sNC.pParse, p, &sNC);
  99837. sqlite3WalkSelect(pWalker, p);
  99838. sqlite3RenameExprlistUnmap(pWalker->pParse, pWith->a[i].pCols);
  99839. }
  99840. }
  99841. }
  99842. /*
  99843. ** Unmap all tokens in the IdList object passed as the second argument.
  99844. */
  99845. static void unmapColumnIdlistNames(
  99846. Parse *pParse,
  99847. IdList *pIdList
  99848. ){
  99849. if( pIdList ){
  99850. int ii;
  99851. for(ii=0; ii<pIdList->nId; ii++){
  99852. sqlite3RenameTokenRemap(pParse, 0, (void*)pIdList->a[ii].zName);
  99853. }
  99854. }
  99855. }
  99856. /*
  99857. ** Walker callback used by sqlite3RenameExprUnmap().
  99858. */
  99859. static int renameUnmapSelectCb(Walker *pWalker, Select *p){
  99860. Parse *pParse = pWalker->pParse;
  99861. int i;
  99862. if( pParse->nErr ) return WRC_Abort;
  99863. if( NEVER(p->selFlags & SF_View) ) return WRC_Prune;
  99864. if( ALWAYS(p->pEList) ){
  99865. ExprList *pList = p->pEList;
  99866. for(i=0; i<pList->nExpr; i++){
  99867. if( pList->a[i].zEName && pList->a[i].eEName==ENAME_NAME ){
  99868. sqlite3RenameTokenRemap(pParse, 0, (void*)pList->a[i].zEName);
  99869. }
  99870. }
  99871. }
  99872. if( ALWAYS(p->pSrc) ){ /* Every Select as a SrcList, even if it is empty */
  99873. SrcList *pSrc = p->pSrc;
  99874. for(i=0; i<pSrc->nSrc; i++){
  99875. sqlite3RenameTokenRemap(pParse, 0, (void*)pSrc->a[i].zName);
  99876. if( sqlite3WalkExpr(pWalker, pSrc->a[i].pOn) ) return WRC_Abort;
  99877. unmapColumnIdlistNames(pParse, pSrc->a[i].pUsing);
  99878. }
  99879. }
  99880. renameWalkWith(pWalker, p);
  99881. return WRC_Continue;
  99882. }
  99883. /*
  99884. ** Remove all nodes that are part of expression pExpr from the rename list.
  99885. */
  99886. SQLITE_PRIVATE void sqlite3RenameExprUnmap(Parse *pParse, Expr *pExpr){
  99887. u8 eMode = pParse->eParseMode;
  99888. Walker sWalker;
  99889. memset(&sWalker, 0, sizeof(Walker));
  99890. sWalker.pParse = pParse;
  99891. sWalker.xExprCallback = renameUnmapExprCb;
  99892. sWalker.xSelectCallback = renameUnmapSelectCb;
  99893. pParse->eParseMode = PARSE_MODE_UNMAP;
  99894. sqlite3WalkExpr(&sWalker, pExpr);
  99895. pParse->eParseMode = eMode;
  99896. }
  99897. /*
  99898. ** Remove all nodes that are part of expression-list pEList from the
  99899. ** rename list.
  99900. */
  99901. SQLITE_PRIVATE void sqlite3RenameExprlistUnmap(Parse *pParse, ExprList *pEList){
  99902. if( pEList ){
  99903. int i;
  99904. Walker sWalker;
  99905. memset(&sWalker, 0, sizeof(Walker));
  99906. sWalker.pParse = pParse;
  99907. sWalker.xExprCallback = renameUnmapExprCb;
  99908. sqlite3WalkExprList(&sWalker, pEList);
  99909. for(i=0; i<pEList->nExpr; i++){
  99910. if( ALWAYS(pEList->a[i].eEName==ENAME_NAME) ){
  99911. sqlite3RenameTokenRemap(pParse, 0, (void*)pEList->a[i].zEName);
  99912. }
  99913. }
  99914. }
  99915. }
  99916. /*
  99917. ** Free the list of RenameToken objects given in the second argument
  99918. */
  99919. static void renameTokenFree(sqlite3 *db, RenameToken *pToken){
  99920. RenameToken *pNext;
  99921. RenameToken *p;
  99922. for(p=pToken; p; p=pNext){
  99923. pNext = p->pNext;
  99924. sqlite3DbFree(db, p);
  99925. }
  99926. }
  99927. /*
  99928. ** Search the Parse object passed as the first argument for a RenameToken
  99929. ** object associated with parse tree element pPtr. If found, remove it
  99930. ** from the Parse object and add it to the list maintained by the
  99931. ** RenameCtx object passed as the second argument.
  99932. */
  99933. static void renameTokenFind(Parse *pParse, struct RenameCtx *pCtx, void *pPtr){
  99934. RenameToken **pp;
  99935. assert( pPtr!=0 );
  99936. for(pp=&pParse->pRename; (*pp); pp=&(*pp)->pNext){
  99937. if( (*pp)->p==pPtr ){
  99938. RenameToken *pToken = *pp;
  99939. *pp = pToken->pNext;
  99940. pToken->pNext = pCtx->pList;
  99941. pCtx->pList = pToken;
  99942. pCtx->nList++;
  99943. break;
  99944. }
  99945. }
  99946. }
  99947. /*
  99948. ** This is a Walker select callback. It does nothing. It is only required
  99949. ** because without a dummy callback, sqlite3WalkExpr() and similar do not
  99950. ** descend into sub-select statements.
  99951. */
  99952. static int renameColumnSelectCb(Walker *pWalker, Select *p){
  99953. if( p->selFlags & SF_View ) return WRC_Prune;
  99954. renameWalkWith(pWalker, p);
  99955. return WRC_Continue;
  99956. }
  99957. /*
  99958. ** This is a Walker expression callback.
  99959. **
  99960. ** For every TK_COLUMN node in the expression tree, search to see
  99961. ** if the column being references is the column being renamed by an
  99962. ** ALTER TABLE statement. If it is, then attach its associated
  99963. ** RenameToken object to the list of RenameToken objects being
  99964. ** constructed in RenameCtx object at pWalker->u.pRename.
  99965. */
  99966. static int renameColumnExprCb(Walker *pWalker, Expr *pExpr){
  99967. RenameCtx *p = pWalker->u.pRename;
  99968. if( pExpr->op==TK_TRIGGER
  99969. && pExpr->iColumn==p->iCol
  99970. && pWalker->pParse->pTriggerTab==p->pTab
  99971. ){
  99972. renameTokenFind(pWalker->pParse, p, (void*)pExpr);
  99973. }else if( pExpr->op==TK_COLUMN
  99974. && pExpr->iColumn==p->iCol
  99975. && p->pTab==pExpr->y.pTab
  99976. ){
  99977. renameTokenFind(pWalker->pParse, p, (void*)pExpr);
  99978. }
  99979. return WRC_Continue;
  99980. }
  99981. /*
  99982. ** The RenameCtx contains a list of tokens that reference a column that
  99983. ** is being renamed by an ALTER TABLE statement. Return the "last"
  99984. ** RenameToken in the RenameCtx and remove that RenameToken from the
  99985. ** RenameContext. "Last" means the last RenameToken encountered when
  99986. ** the input SQL is parsed from left to right. Repeated calls to this routine
  99987. ** return all column name tokens in the order that they are encountered
  99988. ** in the SQL statement.
  99989. */
  99990. static RenameToken *renameColumnTokenNext(RenameCtx *pCtx){
  99991. RenameToken *pBest = pCtx->pList;
  99992. RenameToken *pToken;
  99993. RenameToken **pp;
  99994. for(pToken=pBest->pNext; pToken; pToken=pToken->pNext){
  99995. if( pToken->t.z>pBest->t.z ) pBest = pToken;
  99996. }
  99997. for(pp=&pCtx->pList; *pp!=pBest; pp=&(*pp)->pNext);
  99998. *pp = pBest->pNext;
  99999. return pBest;
  100000. }
  100001. /*
  100002. ** An error occured while parsing or otherwise processing a database
  100003. ** object (either pParse->pNewTable, pNewIndex or pNewTrigger) as part of an
  100004. ** ALTER TABLE RENAME COLUMN program. The error message emitted by the
  100005. ** sub-routine is currently stored in pParse->zErrMsg. This function
  100006. ** adds context to the error message and then stores it in pCtx.
  100007. */
  100008. static void renameColumnParseError(
  100009. sqlite3_context *pCtx,
  100010. int bPost,
  100011. sqlite3_value *pType,
  100012. sqlite3_value *pObject,
  100013. Parse *pParse
  100014. ){
  100015. const char *zT = (const char*)sqlite3_value_text(pType);
  100016. const char *zN = (const char*)sqlite3_value_text(pObject);
  100017. char *zErr;
  100018. zErr = sqlite3_mprintf("error in %s %s%s: %s",
  100019. zT, zN, (bPost ? " after rename" : ""),
  100020. pParse->zErrMsg
  100021. );
  100022. sqlite3_result_error(pCtx, zErr, -1);
  100023. sqlite3_free(zErr);
  100024. }
  100025. /*
  100026. ** For each name in the the expression-list pEList (i.e. each
  100027. ** pEList->a[i].zName) that matches the string in zOld, extract the
  100028. ** corresponding rename-token from Parse object pParse and add it
  100029. ** to the RenameCtx pCtx.
  100030. */
  100031. static void renameColumnElistNames(
  100032. Parse *pParse,
  100033. RenameCtx *pCtx,
  100034. ExprList *pEList,
  100035. const char *zOld
  100036. ){
  100037. if( pEList ){
  100038. int i;
  100039. for(i=0; i<pEList->nExpr; i++){
  100040. char *zName = pEList->a[i].zEName;
  100041. if( ALWAYS(pEList->a[i].eEName==ENAME_NAME)
  100042. && ALWAYS(zName!=0)
  100043. && 0==sqlite3_stricmp(zName, zOld)
  100044. ){
  100045. renameTokenFind(pParse, pCtx, (void*)zName);
  100046. }
  100047. }
  100048. }
  100049. }
  100050. /*
  100051. ** For each name in the the id-list pIdList (i.e. each pIdList->a[i].zName)
  100052. ** that matches the string in zOld, extract the corresponding rename-token
  100053. ** from Parse object pParse and add it to the RenameCtx pCtx.
  100054. */
  100055. static void renameColumnIdlistNames(
  100056. Parse *pParse,
  100057. RenameCtx *pCtx,
  100058. IdList *pIdList,
  100059. const char *zOld
  100060. ){
  100061. if( pIdList ){
  100062. int i;
  100063. for(i=0; i<pIdList->nId; i++){
  100064. char *zName = pIdList->a[i].zName;
  100065. if( 0==sqlite3_stricmp(zName, zOld) ){
  100066. renameTokenFind(pParse, pCtx, (void*)zName);
  100067. }
  100068. }
  100069. }
  100070. }
  100071. /*
  100072. ** Parse the SQL statement zSql using Parse object (*p). The Parse object
  100073. ** is initialized by this function before it is used.
  100074. */
  100075. static int renameParseSql(
  100076. Parse *p, /* Memory to use for Parse object */
  100077. const char *zDb, /* Name of schema SQL belongs to */
  100078. sqlite3 *db, /* Database handle */
  100079. const char *zSql, /* SQL to parse */
  100080. int bTemp /* True if SQL is from temp schema */
  100081. ){
  100082. int rc;
  100083. char *zErr = 0;
  100084. db->init.iDb = bTemp ? 1 : sqlite3FindDbName(db, zDb);
  100085. /* Parse the SQL statement passed as the first argument. If no error
  100086. ** occurs and the parse does not result in a new table, index or
  100087. ** trigger object, the database must be corrupt. */
  100088. memset(p, 0, sizeof(Parse));
  100089. p->eParseMode = PARSE_MODE_RENAME;
  100090. p->db = db;
  100091. p->nQueryLoop = 1;
  100092. rc = sqlite3RunParser(p, zSql, &zErr);
  100093. assert( p->zErrMsg==0 );
  100094. assert( rc!=SQLITE_OK || zErr==0 );
  100095. p->zErrMsg = zErr;
  100096. if( db->mallocFailed ) rc = SQLITE_NOMEM;
  100097. if( rc==SQLITE_OK
  100098. && p->pNewTable==0 && p->pNewIndex==0 && p->pNewTrigger==0
  100099. ){
  100100. rc = SQLITE_CORRUPT_BKPT;
  100101. }
  100102. #ifdef SQLITE_DEBUG
  100103. /* Ensure that all mappings in the Parse.pRename list really do map to
  100104. ** a part of the input string. */
  100105. if( rc==SQLITE_OK ){
  100106. int nSql = sqlite3Strlen30(zSql);
  100107. RenameToken *pToken;
  100108. for(pToken=p->pRename; pToken; pToken=pToken->pNext){
  100109. assert( pToken->t.z>=zSql && &pToken->t.z[pToken->t.n]<=&zSql[nSql] );
  100110. }
  100111. }
  100112. #endif
  100113. db->init.iDb = 0;
  100114. return rc;
  100115. }
  100116. /*
  100117. ** This function edits SQL statement zSql, replacing each token identified
  100118. ** by the linked list pRename with the text of zNew. If argument bQuote is
  100119. ** true, then zNew is always quoted first. If no error occurs, the result
  100120. ** is loaded into context object pCtx as the result.
  100121. **
  100122. ** Or, if an error occurs (i.e. an OOM condition), an error is left in
  100123. ** pCtx and an SQLite error code returned.
  100124. */
  100125. static int renameEditSql(
  100126. sqlite3_context *pCtx, /* Return result here */
  100127. RenameCtx *pRename, /* Rename context */
  100128. const char *zSql, /* SQL statement to edit */
  100129. const char *zNew, /* New token text */
  100130. int bQuote /* True to always quote token */
  100131. ){
  100132. int nNew = sqlite3Strlen30(zNew);
  100133. int nSql = sqlite3Strlen30(zSql);
  100134. sqlite3 *db = sqlite3_context_db_handle(pCtx);
  100135. int rc = SQLITE_OK;
  100136. char *zQuot;
  100137. char *zOut;
  100138. int nQuot;
  100139. /* Set zQuot to point to a buffer containing a quoted copy of the
  100140. ** identifier zNew. If the corresponding identifier in the original
  100141. ** ALTER TABLE statement was quoted (bQuote==1), then set zNew to
  100142. ** point to zQuot so that all substitutions are made using the
  100143. ** quoted version of the new column name. */
  100144. zQuot = sqlite3MPrintf(db, "\"%w\"", zNew);
  100145. if( zQuot==0 ){
  100146. return SQLITE_NOMEM;
  100147. }else{
  100148. nQuot = sqlite3Strlen30(zQuot);
  100149. }
  100150. if( bQuote ){
  100151. zNew = zQuot;
  100152. nNew = nQuot;
  100153. }
  100154. /* At this point pRename->pList contains a list of RenameToken objects
  100155. ** corresponding to all tokens in the input SQL that must be replaced
  100156. ** with the new column name. All that remains is to construct and
  100157. ** return the edited SQL string. */
  100158. assert( nQuot>=nNew );
  100159. zOut = sqlite3DbMallocZero(db, nSql + pRename->nList*nQuot + 1);
  100160. if( zOut ){
  100161. int nOut = nSql;
  100162. memcpy(zOut, zSql, nSql);
  100163. while( pRename->pList ){
  100164. int iOff; /* Offset of token to replace in zOut */
  100165. RenameToken *pBest = renameColumnTokenNext(pRename);
  100166. u32 nReplace;
  100167. const char *zReplace;
  100168. if( sqlite3IsIdChar(*pBest->t.z) ){
  100169. nReplace = nNew;
  100170. zReplace = zNew;
  100171. }else{
  100172. nReplace = nQuot;
  100173. zReplace = zQuot;
  100174. }
  100175. iOff = pBest->t.z - zSql;
  100176. if( pBest->t.n!=nReplace ){
  100177. memmove(&zOut[iOff + nReplace], &zOut[iOff + pBest->t.n],
  100178. nOut - (iOff + pBest->t.n)
  100179. );
  100180. nOut += nReplace - pBest->t.n;
  100181. zOut[nOut] = '\0';
  100182. }
  100183. memcpy(&zOut[iOff], zReplace, nReplace);
  100184. sqlite3DbFree(db, pBest);
  100185. }
  100186. sqlite3_result_text(pCtx, zOut, -1, SQLITE_TRANSIENT);
  100187. sqlite3DbFree(db, zOut);
  100188. }else{
  100189. rc = SQLITE_NOMEM;
  100190. }
  100191. sqlite3_free(zQuot);
  100192. return rc;
  100193. }
  100194. /*
  100195. ** Resolve all symbols in the trigger at pParse->pNewTrigger, assuming
  100196. ** it was read from the schema of database zDb. Return SQLITE_OK if
  100197. ** successful. Otherwise, return an SQLite error code and leave an error
  100198. ** message in the Parse object.
  100199. */
  100200. static int renameResolveTrigger(Parse *pParse, const char *zDb){
  100201. sqlite3 *db = pParse->db;
  100202. Trigger *pNew = pParse->pNewTrigger;
  100203. TriggerStep *pStep;
  100204. NameContext sNC;
  100205. int rc = SQLITE_OK;
  100206. memset(&sNC, 0, sizeof(sNC));
  100207. sNC.pParse = pParse;
  100208. assert( pNew->pTabSchema );
  100209. pParse->pTriggerTab = sqlite3FindTable(db, pNew->table,
  100210. db->aDb[sqlite3SchemaToIndex(db, pNew->pTabSchema)].zDbSName
  100211. );
  100212. pParse->eTriggerOp = pNew->op;
  100213. /* ALWAYS() because if the table of the trigger does not exist, the
  100214. ** error would have been hit before this point */
  100215. if( ALWAYS(pParse->pTriggerTab) ){
  100216. rc = sqlite3ViewGetColumnNames(pParse, pParse->pTriggerTab);
  100217. }
  100218. /* Resolve symbols in WHEN clause */
  100219. if( rc==SQLITE_OK && pNew->pWhen ){
  100220. rc = sqlite3ResolveExprNames(&sNC, pNew->pWhen);
  100221. }
  100222. for(pStep=pNew->step_list; rc==SQLITE_OK && pStep; pStep=pStep->pNext){
  100223. if( pStep->pSelect ){
  100224. sqlite3SelectPrep(pParse, pStep->pSelect, &sNC);
  100225. if( pParse->nErr ) rc = pParse->rc;
  100226. }
  100227. if( rc==SQLITE_OK && pStep->zTarget ){
  100228. Table *pTarget = sqlite3LocateTable(pParse, 0, pStep->zTarget, zDb);
  100229. if( pTarget==0 ){
  100230. rc = SQLITE_ERROR;
  100231. }else if( SQLITE_OK==(rc = sqlite3ViewGetColumnNames(pParse, pTarget)) ){
  100232. SrcList sSrc;
  100233. memset(&sSrc, 0, sizeof(sSrc));
  100234. sSrc.nSrc = 1;
  100235. sSrc.a[0].zName = pStep->zTarget;
  100236. sSrc.a[0].pTab = pTarget;
  100237. sNC.pSrcList = &sSrc;
  100238. if( pStep->pWhere ){
  100239. rc = sqlite3ResolveExprNames(&sNC, pStep->pWhere);
  100240. }
  100241. if( rc==SQLITE_OK ){
  100242. rc = sqlite3ResolveExprListNames(&sNC, pStep->pExprList);
  100243. }
  100244. assert( !pStep->pUpsert || (!pStep->pWhere && !pStep->pExprList) );
  100245. if( pStep->pUpsert ){
  100246. Upsert *pUpsert = pStep->pUpsert;
  100247. assert( rc==SQLITE_OK );
  100248. pUpsert->pUpsertSrc = &sSrc;
  100249. sNC.uNC.pUpsert = pUpsert;
  100250. sNC.ncFlags = NC_UUpsert;
  100251. rc = sqlite3ResolveExprListNames(&sNC, pUpsert->pUpsertTarget);
  100252. if( rc==SQLITE_OK ){
  100253. ExprList *pUpsertSet = pUpsert->pUpsertSet;
  100254. rc = sqlite3ResolveExprListNames(&sNC, pUpsertSet);
  100255. }
  100256. if( rc==SQLITE_OK ){
  100257. rc = sqlite3ResolveExprNames(&sNC, pUpsert->pUpsertWhere);
  100258. }
  100259. if( rc==SQLITE_OK ){
  100260. rc = sqlite3ResolveExprNames(&sNC, pUpsert->pUpsertTargetWhere);
  100261. }
  100262. sNC.ncFlags = 0;
  100263. }
  100264. sNC.pSrcList = 0;
  100265. }
  100266. }
  100267. }
  100268. return rc;
  100269. }
  100270. /*
  100271. ** Invoke sqlite3WalkExpr() or sqlite3WalkSelect() on all Select or Expr
  100272. ** objects that are part of the trigger passed as the second argument.
  100273. */
  100274. static void renameWalkTrigger(Walker *pWalker, Trigger *pTrigger){
  100275. TriggerStep *pStep;
  100276. /* Find tokens to edit in WHEN clause */
  100277. sqlite3WalkExpr(pWalker, pTrigger->pWhen);
  100278. /* Find tokens to edit in trigger steps */
  100279. for(pStep=pTrigger->step_list; pStep; pStep=pStep->pNext){
  100280. sqlite3WalkSelect(pWalker, pStep->pSelect);
  100281. sqlite3WalkExpr(pWalker, pStep->pWhere);
  100282. sqlite3WalkExprList(pWalker, pStep->pExprList);
  100283. if( pStep->pUpsert ){
  100284. Upsert *pUpsert = pStep->pUpsert;
  100285. sqlite3WalkExprList(pWalker, pUpsert->pUpsertTarget);
  100286. sqlite3WalkExprList(pWalker, pUpsert->pUpsertSet);
  100287. sqlite3WalkExpr(pWalker, pUpsert->pUpsertWhere);
  100288. sqlite3WalkExpr(pWalker, pUpsert->pUpsertTargetWhere);
  100289. }
  100290. }
  100291. }
  100292. /*
  100293. ** Free the contents of Parse object (*pParse). Do not free the memory
  100294. ** occupied by the Parse object itself.
  100295. */
  100296. static void renameParseCleanup(Parse *pParse){
  100297. sqlite3 *db = pParse->db;
  100298. Index *pIdx;
  100299. if( pParse->pVdbe ){
  100300. sqlite3VdbeFinalize(pParse->pVdbe);
  100301. }
  100302. sqlite3DeleteTable(db, pParse->pNewTable);
  100303. while( (pIdx = pParse->pNewIndex)!=0 ){
  100304. pParse->pNewIndex = pIdx->pNext;
  100305. sqlite3FreeIndex(db, pIdx);
  100306. }
  100307. sqlite3DeleteTrigger(db, pParse->pNewTrigger);
  100308. sqlite3DbFree(db, pParse->zErrMsg);
  100309. renameTokenFree(db, pParse->pRename);
  100310. sqlite3ParserReset(pParse);
  100311. }
  100312. /*
  100313. ** SQL function:
  100314. **
  100315. ** sqlite_rename_column(zSql, iCol, bQuote, zNew, zTable, zOld)
  100316. **
  100317. ** 0. zSql: SQL statement to rewrite
  100318. ** 1. type: Type of object ("table", "view" etc.)
  100319. ** 2. object: Name of object
  100320. ** 3. Database: Database name (e.g. "main")
  100321. ** 4. Table: Table name
  100322. ** 5. iCol: Index of column to rename
  100323. ** 6. zNew: New column name
  100324. ** 7. bQuote: Non-zero if the new column name should be quoted.
  100325. ** 8. bTemp: True if zSql comes from temp schema
  100326. **
  100327. ** Do a column rename operation on the CREATE statement given in zSql.
  100328. ** The iCol-th column (left-most is 0) of table zTable is renamed from zCol
  100329. ** into zNew. The name should be quoted if bQuote is true.
  100330. **
  100331. ** This function is used internally by the ALTER TABLE RENAME COLUMN command.
  100332. ** It is only accessible to SQL created using sqlite3NestedParse(). It is
  100333. ** not reachable from ordinary SQL passed into sqlite3_prepare().
  100334. */
  100335. static void renameColumnFunc(
  100336. sqlite3_context *context,
  100337. int NotUsed,
  100338. sqlite3_value **argv
  100339. ){
  100340. sqlite3 *db = sqlite3_context_db_handle(context);
  100341. RenameCtx sCtx;
  100342. const char *zSql = (const char*)sqlite3_value_text(argv[0]);
  100343. const char *zDb = (const char*)sqlite3_value_text(argv[3]);
  100344. const char *zTable = (const char*)sqlite3_value_text(argv[4]);
  100345. int iCol = sqlite3_value_int(argv[5]);
  100346. const char *zNew = (const char*)sqlite3_value_text(argv[6]);
  100347. int bQuote = sqlite3_value_int(argv[7]);
  100348. int bTemp = sqlite3_value_int(argv[8]);
  100349. const char *zOld;
  100350. int rc;
  100351. Parse sParse;
  100352. Walker sWalker;
  100353. Index *pIdx;
  100354. int i;
  100355. Table *pTab;
  100356. #ifndef SQLITE_OMIT_AUTHORIZATION
  100357. sqlite3_xauth xAuth = db->xAuth;
  100358. #endif
  100359. UNUSED_PARAMETER(NotUsed);
  100360. if( zSql==0 ) return;
  100361. if( zTable==0 ) return;
  100362. if( zNew==0 ) return;
  100363. if( iCol<0 ) return;
  100364. sqlite3BtreeEnterAll(db);
  100365. pTab = sqlite3FindTable(db, zTable, zDb);
  100366. if( pTab==0 || iCol>=pTab->nCol ){
  100367. sqlite3BtreeLeaveAll(db);
  100368. return;
  100369. }
  100370. zOld = pTab->aCol[iCol].zName;
  100371. memset(&sCtx, 0, sizeof(sCtx));
  100372. sCtx.iCol = ((iCol==pTab->iPKey) ? -1 : iCol);
  100373. #ifndef SQLITE_OMIT_AUTHORIZATION
  100374. db->xAuth = 0;
  100375. #endif
  100376. rc = renameParseSql(&sParse, zDb, db, zSql, bTemp);
  100377. /* Find tokens that need to be replaced. */
  100378. memset(&sWalker, 0, sizeof(Walker));
  100379. sWalker.pParse = &sParse;
  100380. sWalker.xExprCallback = renameColumnExprCb;
  100381. sWalker.xSelectCallback = renameColumnSelectCb;
  100382. sWalker.u.pRename = &sCtx;
  100383. sCtx.pTab = pTab;
  100384. if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
  100385. if( sParse.pNewTable ){
  100386. Select *pSelect = sParse.pNewTable->pSelect;
  100387. if( pSelect ){
  100388. pSelect->selFlags &= ~SF_View;
  100389. sParse.rc = SQLITE_OK;
  100390. sqlite3SelectPrep(&sParse, pSelect, 0);
  100391. rc = (db->mallocFailed ? SQLITE_NOMEM : sParse.rc);
  100392. if( rc==SQLITE_OK ){
  100393. sqlite3WalkSelect(&sWalker, pSelect);
  100394. }
  100395. if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
  100396. }else{
  100397. /* A regular table */
  100398. int bFKOnly = sqlite3_stricmp(zTable, sParse.pNewTable->zName);
  100399. FKey *pFKey;
  100400. assert( sParse.pNewTable->pSelect==0 );
  100401. sCtx.pTab = sParse.pNewTable;
  100402. if( bFKOnly==0 ){
  100403. renameTokenFind(
  100404. &sParse, &sCtx, (void*)sParse.pNewTable->aCol[iCol].zName
  100405. );
  100406. if( sCtx.iCol<0 ){
  100407. renameTokenFind(&sParse, &sCtx, (void*)&sParse.pNewTable->iPKey);
  100408. }
  100409. sqlite3WalkExprList(&sWalker, sParse.pNewTable->pCheck);
  100410. for(pIdx=sParse.pNewTable->pIndex; pIdx; pIdx=pIdx->pNext){
  100411. sqlite3WalkExprList(&sWalker, pIdx->aColExpr);
  100412. }
  100413. for(pIdx=sParse.pNewIndex; pIdx; pIdx=pIdx->pNext){
  100414. sqlite3WalkExprList(&sWalker, pIdx->aColExpr);
  100415. }
  100416. }
  100417. #ifndef SQLITE_OMIT_GENERATED_COLUMNS
  100418. for(i=0; i<sParse.pNewTable->nCol; i++){
  100419. sqlite3WalkExpr(&sWalker, sParse.pNewTable->aCol[i].pDflt);
  100420. }
  100421. #endif
  100422. for(pFKey=sParse.pNewTable->pFKey; pFKey; pFKey=pFKey->pNextFrom){
  100423. for(i=0; i<pFKey->nCol; i++){
  100424. if( bFKOnly==0 && pFKey->aCol[i].iFrom==iCol ){
  100425. renameTokenFind(&sParse, &sCtx, (void*)&pFKey->aCol[i]);
  100426. }
  100427. if( 0==sqlite3_stricmp(pFKey->zTo, zTable)
  100428. && 0==sqlite3_stricmp(pFKey->aCol[i].zCol, zOld)
  100429. ){
  100430. renameTokenFind(&sParse, &sCtx, (void*)pFKey->aCol[i].zCol);
  100431. }
  100432. }
  100433. }
  100434. }
  100435. }else if( sParse.pNewIndex ){
  100436. sqlite3WalkExprList(&sWalker, sParse.pNewIndex->aColExpr);
  100437. sqlite3WalkExpr(&sWalker, sParse.pNewIndex->pPartIdxWhere);
  100438. }else{
  100439. /* A trigger */
  100440. TriggerStep *pStep;
  100441. rc = renameResolveTrigger(&sParse, (bTemp ? 0 : zDb));
  100442. if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
  100443. for(pStep=sParse.pNewTrigger->step_list; pStep; pStep=pStep->pNext){
  100444. if( pStep->zTarget ){
  100445. Table *pTarget = sqlite3LocateTable(&sParse, 0, pStep->zTarget, zDb);
  100446. if( pTarget==pTab ){
  100447. if( pStep->pUpsert ){
  100448. ExprList *pUpsertSet = pStep->pUpsert->pUpsertSet;
  100449. renameColumnElistNames(&sParse, &sCtx, pUpsertSet, zOld);
  100450. }
  100451. renameColumnIdlistNames(&sParse, &sCtx, pStep->pIdList, zOld);
  100452. renameColumnElistNames(&sParse, &sCtx, pStep->pExprList, zOld);
  100453. }
  100454. }
  100455. }
  100456. /* Find tokens to edit in UPDATE OF clause */
  100457. if( sParse.pTriggerTab==pTab ){
  100458. renameColumnIdlistNames(&sParse, &sCtx,sParse.pNewTrigger->pColumns,zOld);
  100459. }
  100460. /* Find tokens to edit in various expressions and selects */
  100461. renameWalkTrigger(&sWalker, sParse.pNewTrigger);
  100462. }
  100463. assert( rc==SQLITE_OK );
  100464. rc = renameEditSql(context, &sCtx, zSql, zNew, bQuote);
  100465. renameColumnFunc_done:
  100466. if( rc!=SQLITE_OK ){
  100467. if( sParse.zErrMsg ){
  100468. renameColumnParseError(context, 0, argv[1], argv[2], &sParse);
  100469. }else{
  100470. sqlite3_result_error_code(context, rc);
  100471. }
  100472. }
  100473. renameParseCleanup(&sParse);
  100474. renameTokenFree(db, sCtx.pList);
  100475. #ifndef SQLITE_OMIT_AUTHORIZATION
  100476. db->xAuth = xAuth;
  100477. #endif
  100478. sqlite3BtreeLeaveAll(db);
  100479. }
  100480. /*
  100481. ** Walker expression callback used by "RENAME TABLE".
  100482. */
  100483. static int renameTableExprCb(Walker *pWalker, Expr *pExpr){
  100484. RenameCtx *p = pWalker->u.pRename;
  100485. if( pExpr->op==TK_COLUMN && p->pTab==pExpr->y.pTab ){
  100486. renameTokenFind(pWalker->pParse, p, (void*)&pExpr->y.pTab);
  100487. }
  100488. return WRC_Continue;
  100489. }
  100490. /*
  100491. ** Walker select callback used by "RENAME TABLE".
  100492. */
  100493. static int renameTableSelectCb(Walker *pWalker, Select *pSelect){
  100494. int i;
  100495. RenameCtx *p = pWalker->u.pRename;
  100496. SrcList *pSrc = pSelect->pSrc;
  100497. if( pSelect->selFlags & SF_View ) return WRC_Prune;
  100498. if( pSrc==0 ){
  100499. assert( pWalker->pParse->db->mallocFailed );
  100500. return WRC_Abort;
  100501. }
  100502. for(i=0; i<pSrc->nSrc; i++){
  100503. struct SrcList_item *pItem = &pSrc->a[i];
  100504. if( pItem->pTab==p->pTab ){
  100505. renameTokenFind(pWalker->pParse, p, pItem->zName);
  100506. }
  100507. }
  100508. renameWalkWith(pWalker, pSelect);
  100509. return WRC_Continue;
  100510. }
  100511. /*
  100512. ** This C function implements an SQL user function that is used by SQL code
  100513. ** generated by the ALTER TABLE ... RENAME command to modify the definition
  100514. ** of any foreign key constraints that use the table being renamed as the
  100515. ** parent table. It is passed three arguments:
  100516. **
  100517. ** 0: The database containing the table being renamed.
  100518. ** 1. type: Type of object ("table", "view" etc.)
  100519. ** 2. object: Name of object
  100520. ** 3: The complete text of the schema statement being modified,
  100521. ** 4: The old name of the table being renamed, and
  100522. ** 5: The new name of the table being renamed.
  100523. ** 6: True if the schema statement comes from the temp db.
  100524. **
  100525. ** It returns the new schema statement. For example:
  100526. **
  100527. ** sqlite_rename_table('main', 'CREATE TABLE t1(a REFERENCES t2)','t2','t3',0)
  100528. ** -> 'CREATE TABLE t1(a REFERENCES t3)'
  100529. */
  100530. static void renameTableFunc(
  100531. sqlite3_context *context,
  100532. int NotUsed,
  100533. sqlite3_value **argv
  100534. ){
  100535. sqlite3 *db = sqlite3_context_db_handle(context);
  100536. const char *zDb = (const char*)sqlite3_value_text(argv[0]);
  100537. const char *zInput = (const char*)sqlite3_value_text(argv[3]);
  100538. const char *zOld = (const char*)sqlite3_value_text(argv[4]);
  100539. const char *zNew = (const char*)sqlite3_value_text(argv[5]);
  100540. int bTemp = sqlite3_value_int(argv[6]);
  100541. UNUSED_PARAMETER(NotUsed);
  100542. if( zInput && zOld && zNew ){
  100543. Parse sParse;
  100544. int rc;
  100545. int bQuote = 1;
  100546. RenameCtx sCtx;
  100547. Walker sWalker;
  100548. #ifndef SQLITE_OMIT_AUTHORIZATION
  100549. sqlite3_xauth xAuth = db->xAuth;
  100550. db->xAuth = 0;
  100551. #endif
  100552. sqlite3BtreeEnterAll(db);
  100553. memset(&sCtx, 0, sizeof(RenameCtx));
  100554. sCtx.pTab = sqlite3FindTable(db, zOld, zDb);
  100555. memset(&sWalker, 0, sizeof(Walker));
  100556. sWalker.pParse = &sParse;
  100557. sWalker.xExprCallback = renameTableExprCb;
  100558. sWalker.xSelectCallback = renameTableSelectCb;
  100559. sWalker.u.pRename = &sCtx;
  100560. rc = renameParseSql(&sParse, zDb, db, zInput, bTemp);
  100561. if( rc==SQLITE_OK ){
  100562. int isLegacy = (db->flags & SQLITE_LegacyAlter);
  100563. if( sParse.pNewTable ){
  100564. Table *pTab = sParse.pNewTable;
  100565. if( pTab->pSelect ){
  100566. if( isLegacy==0 ){
  100567. Select *pSelect = pTab->pSelect;
  100568. NameContext sNC;
  100569. memset(&sNC, 0, sizeof(sNC));
  100570. sNC.pParse = &sParse;
  100571. assert( pSelect->selFlags & SF_View );
  100572. pSelect->selFlags &= ~SF_View;
  100573. sqlite3SelectPrep(&sParse, pTab->pSelect, &sNC);
  100574. if( sParse.nErr ){
  100575. rc = sParse.rc;
  100576. }else{
  100577. sqlite3WalkSelect(&sWalker, pTab->pSelect);
  100578. }
  100579. }
  100580. }else{
  100581. /* Modify any FK definitions to point to the new table. */
  100582. #ifndef SQLITE_OMIT_FOREIGN_KEY
  100583. if( isLegacy==0 || (db->flags & SQLITE_ForeignKeys) ){
  100584. FKey *pFKey;
  100585. for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
  100586. if( sqlite3_stricmp(pFKey->zTo, zOld)==0 ){
  100587. renameTokenFind(&sParse, &sCtx, (void*)pFKey->zTo);
  100588. }
  100589. }
  100590. }
  100591. #endif
  100592. /* If this is the table being altered, fix any table refs in CHECK
  100593. ** expressions. Also update the name that appears right after the
  100594. ** "CREATE [VIRTUAL] TABLE" bit. */
  100595. if( sqlite3_stricmp(zOld, pTab->zName)==0 ){
  100596. sCtx.pTab = pTab;
  100597. if( isLegacy==0 ){
  100598. sqlite3WalkExprList(&sWalker, pTab->pCheck);
  100599. }
  100600. renameTokenFind(&sParse, &sCtx, pTab->zName);
  100601. }
  100602. }
  100603. }
  100604. else if( sParse.pNewIndex ){
  100605. renameTokenFind(&sParse, &sCtx, sParse.pNewIndex->zName);
  100606. if( isLegacy==0 ){
  100607. sqlite3WalkExpr(&sWalker, sParse.pNewIndex->pPartIdxWhere);
  100608. }
  100609. }
  100610. #ifndef SQLITE_OMIT_TRIGGER
  100611. else{
  100612. Trigger *pTrigger = sParse.pNewTrigger;
  100613. TriggerStep *pStep;
  100614. if( 0==sqlite3_stricmp(sParse.pNewTrigger->table, zOld)
  100615. && sCtx.pTab->pSchema==pTrigger->pTabSchema
  100616. ){
  100617. renameTokenFind(&sParse, &sCtx, sParse.pNewTrigger->table);
  100618. }
  100619. if( isLegacy==0 ){
  100620. rc = renameResolveTrigger(&sParse, bTemp ? 0 : zDb);
  100621. if( rc==SQLITE_OK ){
  100622. renameWalkTrigger(&sWalker, pTrigger);
  100623. for(pStep=pTrigger->step_list; pStep; pStep=pStep->pNext){
  100624. if( pStep->zTarget && 0==sqlite3_stricmp(pStep->zTarget, zOld) ){
  100625. renameTokenFind(&sParse, &sCtx, pStep->zTarget);
  100626. }
  100627. }
  100628. }
  100629. }
  100630. }
  100631. #endif
  100632. }
  100633. if( rc==SQLITE_OK ){
  100634. rc = renameEditSql(context, &sCtx, zInput, zNew, bQuote);
  100635. }
  100636. if( rc!=SQLITE_OK ){
  100637. if( sParse.zErrMsg ){
  100638. renameColumnParseError(context, 0, argv[1], argv[2], &sParse);
  100639. }else{
  100640. sqlite3_result_error_code(context, rc);
  100641. }
  100642. }
  100643. renameParseCleanup(&sParse);
  100644. renameTokenFree(db, sCtx.pList);
  100645. sqlite3BtreeLeaveAll(db);
  100646. #ifndef SQLITE_OMIT_AUTHORIZATION
  100647. db->xAuth = xAuth;
  100648. #endif
  100649. }
  100650. return;
  100651. }
  100652. /*
  100653. ** An SQL user function that checks that there are no parse or symbol
  100654. ** resolution problems in a CREATE TRIGGER|TABLE|VIEW|INDEX statement.
  100655. ** After an ALTER TABLE .. RENAME operation is performed and the schema
  100656. ** reloaded, this function is called on each SQL statement in the schema
  100657. ** to ensure that it is still usable.
  100658. **
  100659. ** 0: Database name ("main", "temp" etc.).
  100660. ** 1: SQL statement.
  100661. ** 2: Object type ("view", "table", "trigger" or "index").
  100662. ** 3: Object name.
  100663. ** 4: True if object is from temp schema.
  100664. **
  100665. ** Unless it finds an error, this function normally returns NULL. However, it
  100666. ** returns integer value 1 if:
  100667. **
  100668. ** * the SQL argument creates a trigger, and
  100669. ** * the table that the trigger is attached to is in database zDb.
  100670. */
  100671. static void renameTableTest(
  100672. sqlite3_context *context,
  100673. int NotUsed,
  100674. sqlite3_value **argv
  100675. ){
  100676. sqlite3 *db = sqlite3_context_db_handle(context);
  100677. char const *zDb = (const char*)sqlite3_value_text(argv[0]);
  100678. char const *zInput = (const char*)sqlite3_value_text(argv[1]);
  100679. int bTemp = sqlite3_value_int(argv[4]);
  100680. int isLegacy = (db->flags & SQLITE_LegacyAlter);
  100681. #ifndef SQLITE_OMIT_AUTHORIZATION
  100682. sqlite3_xauth xAuth = db->xAuth;
  100683. db->xAuth = 0;
  100684. #endif
  100685. UNUSED_PARAMETER(NotUsed);
  100686. if( zDb && zInput ){
  100687. int rc;
  100688. Parse sParse;
  100689. rc = renameParseSql(&sParse, zDb, db, zInput, bTemp);
  100690. if( rc==SQLITE_OK ){
  100691. if( isLegacy==0 && sParse.pNewTable && sParse.pNewTable->pSelect ){
  100692. NameContext sNC;
  100693. memset(&sNC, 0, sizeof(sNC));
  100694. sNC.pParse = &sParse;
  100695. sqlite3SelectPrep(&sParse, sParse.pNewTable->pSelect, &sNC);
  100696. if( sParse.nErr ) rc = sParse.rc;
  100697. }
  100698. else if( sParse.pNewTrigger ){
  100699. if( isLegacy==0 ){
  100700. rc = renameResolveTrigger(&sParse, bTemp ? 0 : zDb);
  100701. }
  100702. if( rc==SQLITE_OK ){
  100703. int i1 = sqlite3SchemaToIndex(db, sParse.pNewTrigger->pTabSchema);
  100704. int i2 = sqlite3FindDbName(db, zDb);
  100705. if( i1==i2 ) sqlite3_result_int(context, 1);
  100706. }
  100707. }
  100708. }
  100709. if( rc!=SQLITE_OK ){
  100710. renameColumnParseError(context, 1, argv[2], argv[3], &sParse);
  100711. }
  100712. renameParseCleanup(&sParse);
  100713. }
  100714. #ifndef SQLITE_OMIT_AUTHORIZATION
  100715. db->xAuth = xAuth;
  100716. #endif
  100717. }
  100718. /*
  100719. ** Register built-in functions used to help implement ALTER TABLE
  100720. */
  100721. SQLITE_PRIVATE void sqlite3AlterFunctions(void){
  100722. static FuncDef aAlterTableFuncs[] = {
  100723. INTERNAL_FUNCTION(sqlite_rename_column, 9, renameColumnFunc),
  100724. INTERNAL_FUNCTION(sqlite_rename_table, 7, renameTableFunc),
  100725. INTERNAL_FUNCTION(sqlite_rename_test, 5, renameTableTest),
  100726. };
  100727. sqlite3InsertBuiltinFuncs(aAlterTableFuncs, ArraySize(aAlterTableFuncs));
  100728. }
  100729. #endif /* SQLITE_ALTER_TABLE */
  100730. /************** End of alter.c ***********************************************/
  100731. /************** Begin file analyze.c *****************************************/
  100732. /*
  100733. ** 2005-07-08
  100734. **
  100735. ** The author disclaims copyright to this source code. In place of
  100736. ** a legal notice, here is a blessing:
  100737. **
  100738. ** May you do good and not evil.
  100739. ** May you find forgiveness for yourself and forgive others.
  100740. ** May you share freely, never taking more than you give.
  100741. **
  100742. *************************************************************************
  100743. ** This file contains code associated with the ANALYZE command.
  100744. **
  100745. ** The ANALYZE command gather statistics about the content of tables
  100746. ** and indices. These statistics are made available to the query planner
  100747. ** to help it make better decisions about how to perform queries.
  100748. **
  100749. ** The following system tables are or have been supported:
  100750. **
  100751. ** CREATE TABLE sqlite_stat1(tbl, idx, stat);
  100752. ** CREATE TABLE sqlite_stat2(tbl, idx, sampleno, sample);
  100753. ** CREATE TABLE sqlite_stat3(tbl, idx, nEq, nLt, nDLt, sample);
  100754. ** CREATE TABLE sqlite_stat4(tbl, idx, nEq, nLt, nDLt, sample);
  100755. **
  100756. ** Additional tables might be added in future releases of SQLite.
  100757. ** The sqlite_stat2 table is not created or used unless the SQLite version
  100758. ** is between 3.6.18 and 3.7.8, inclusive, and unless SQLite is compiled
  100759. ** with SQLITE_ENABLE_STAT2. The sqlite_stat2 table is deprecated.
  100760. ** The sqlite_stat2 table is superseded by sqlite_stat3, which is only
  100761. ** created and used by SQLite versions 3.7.9 through 3.29.0 when
  100762. ** SQLITE_ENABLE_STAT3 defined. The functionality of sqlite_stat3
  100763. ** is a superset of sqlite_stat2 and is also now deprecated. The
  100764. ** sqlite_stat4 is an enhanced version of sqlite_stat3 and is only
  100765. ** available when compiled with SQLITE_ENABLE_STAT4 and in SQLite
  100766. ** versions 3.8.1 and later. STAT4 is the only variant that is still
  100767. ** supported.
  100768. **
  100769. ** For most applications, sqlite_stat1 provides all the statistics required
  100770. ** for the query planner to make good choices.
  100771. **
  100772. ** Format of sqlite_stat1:
  100773. **
  100774. ** There is normally one row per index, with the index identified by the
  100775. ** name in the idx column. The tbl column is the name of the table to
  100776. ** which the index belongs. In each such row, the stat column will be
  100777. ** a string consisting of a list of integers. The first integer in this
  100778. ** list is the number of rows in the index. (This is the same as the
  100779. ** number of rows in the table, except for partial indices.) The second
  100780. ** integer is the average number of rows in the index that have the same
  100781. ** value in the first column of the index. The third integer is the average
  100782. ** number of rows in the index that have the same value for the first two
  100783. ** columns. The N-th integer (for N>1) is the average number of rows in
  100784. ** the index which have the same value for the first N-1 columns. For
  100785. ** a K-column index, there will be K+1 integers in the stat column. If
  100786. ** the index is unique, then the last integer will be 1.
  100787. **
  100788. ** The list of integers in the stat column can optionally be followed
  100789. ** by the keyword "unordered". The "unordered" keyword, if it is present,
  100790. ** must be separated from the last integer by a single space. If the
  100791. ** "unordered" keyword is present, then the query planner assumes that
  100792. ** the index is unordered and will not use the index for a range query.
  100793. **
  100794. ** If the sqlite_stat1.idx column is NULL, then the sqlite_stat1.stat
  100795. ** column contains a single integer which is the (estimated) number of
  100796. ** rows in the table identified by sqlite_stat1.tbl.
  100797. **
  100798. ** Format of sqlite_stat2:
  100799. **
  100800. ** The sqlite_stat2 is only created and is only used if SQLite is compiled
  100801. ** with SQLITE_ENABLE_STAT2 and if the SQLite version number is between
  100802. ** 3.6.18 and 3.7.8. The "stat2" table contains additional information
  100803. ** about the distribution of keys within an index. The index is identified by
  100804. ** the "idx" column and the "tbl" column is the name of the table to which
  100805. ** the index belongs. There are usually 10 rows in the sqlite_stat2
  100806. ** table for each index.
  100807. **
  100808. ** The sqlite_stat2 entries for an index that have sampleno between 0 and 9
  100809. ** inclusive are samples of the left-most key value in the index taken at
  100810. ** evenly spaced points along the index. Let the number of samples be S
  100811. ** (10 in the standard build) and let C be the number of rows in the index.
  100812. ** Then the sampled rows are given by:
  100813. **
  100814. ** rownumber = (i*C*2 + C)/(S*2)
  100815. **
  100816. ** For i between 0 and S-1. Conceptually, the index space is divided into
  100817. ** S uniform buckets and the samples are the middle row from each bucket.
  100818. **
  100819. ** The format for sqlite_stat2 is recorded here for legacy reference. This
  100820. ** version of SQLite does not support sqlite_stat2. It neither reads nor
  100821. ** writes the sqlite_stat2 table. This version of SQLite only supports
  100822. ** sqlite_stat3.
  100823. **
  100824. ** Format for sqlite_stat3:
  100825. **
  100826. ** The sqlite_stat3 format is a subset of sqlite_stat4. Hence, the
  100827. ** sqlite_stat4 format will be described first. Further information
  100828. ** about sqlite_stat3 follows the sqlite_stat4 description.
  100829. **
  100830. ** Format for sqlite_stat4:
  100831. **
  100832. ** As with sqlite_stat2, the sqlite_stat4 table contains histogram data
  100833. ** to aid the query planner in choosing good indices based on the values
  100834. ** that indexed columns are compared against in the WHERE clauses of
  100835. ** queries.
  100836. **
  100837. ** The sqlite_stat4 table contains multiple entries for each index.
  100838. ** The idx column names the index and the tbl column is the table of the
  100839. ** index. If the idx and tbl columns are the same, then the sample is
  100840. ** of the INTEGER PRIMARY KEY. The sample column is a blob which is the
  100841. ** binary encoding of a key from the index. The nEq column is a
  100842. ** list of integers. The first integer is the approximate number
  100843. ** of entries in the index whose left-most column exactly matches
  100844. ** the left-most column of the sample. The second integer in nEq
  100845. ** is the approximate number of entries in the index where the
  100846. ** first two columns match the first two columns of the sample.
  100847. ** And so forth. nLt is another list of integers that show the approximate
  100848. ** number of entries that are strictly less than the sample. The first
  100849. ** integer in nLt contains the number of entries in the index where the
  100850. ** left-most column is less than the left-most column of the sample.
  100851. ** The K-th integer in the nLt entry is the number of index entries
  100852. ** where the first K columns are less than the first K columns of the
  100853. ** sample. The nDLt column is like nLt except that it contains the
  100854. ** number of distinct entries in the index that are less than the
  100855. ** sample.
  100856. **
  100857. ** There can be an arbitrary number of sqlite_stat4 entries per index.
  100858. ** The ANALYZE command will typically generate sqlite_stat4 tables
  100859. ** that contain between 10 and 40 samples which are distributed across
  100860. ** the key space, though not uniformly, and which include samples with
  100861. ** large nEq values.
  100862. **
  100863. ** Format for sqlite_stat3 redux:
  100864. **
  100865. ** The sqlite_stat3 table is like sqlite_stat4 except that it only
  100866. ** looks at the left-most column of the index. The sqlite_stat3.sample
  100867. ** column contains the actual value of the left-most column instead
  100868. ** of a blob encoding of the complete index key as is found in
  100869. ** sqlite_stat4.sample. The nEq, nLt, and nDLt entries of sqlite_stat3
  100870. ** all contain just a single integer which is the same as the first
  100871. ** integer in the equivalent columns in sqlite_stat4.
  100872. */
  100873. #ifndef SQLITE_OMIT_ANALYZE
  100874. /* #include "sqliteInt.h" */
  100875. #if defined(SQLITE_ENABLE_STAT4)
  100876. # define IsStat4 1
  100877. #else
  100878. # define IsStat4 0
  100879. # undef SQLITE_STAT4_SAMPLES
  100880. # define SQLITE_STAT4_SAMPLES 1
  100881. #endif
  100882. /*
  100883. ** This routine generates code that opens the sqlite_statN tables.
  100884. ** The sqlite_stat1 table is always relevant. sqlite_stat2 is now
  100885. ** obsolete. sqlite_stat3 and sqlite_stat4 are only opened when
  100886. ** appropriate compile-time options are provided.
  100887. **
  100888. ** If the sqlite_statN tables do not previously exist, it is created.
  100889. **
  100890. ** Argument zWhere may be a pointer to a buffer containing a table name,
  100891. ** or it may be a NULL pointer. If it is not NULL, then all entries in
  100892. ** the sqlite_statN tables associated with the named table are deleted.
  100893. ** If zWhere==0, then code is generated to delete all stat table entries.
  100894. */
  100895. static void openStatTable(
  100896. Parse *pParse, /* Parsing context */
  100897. int iDb, /* The database we are looking in */
  100898. int iStatCur, /* Open the sqlite_stat1 table on this cursor */
  100899. const char *zWhere, /* Delete entries for this table or index */
  100900. const char *zWhereType /* Either "tbl" or "idx" */
  100901. ){
  100902. static const struct {
  100903. const char *zName;
  100904. const char *zCols;
  100905. } aTable[] = {
  100906. { "sqlite_stat1", "tbl,idx,stat" },
  100907. #if defined(SQLITE_ENABLE_STAT4)
  100908. { "sqlite_stat4", "tbl,idx,neq,nlt,ndlt,sample" },
  100909. #else
  100910. { "sqlite_stat4", 0 },
  100911. #endif
  100912. { "sqlite_stat3", 0 },
  100913. };
  100914. int i;
  100915. sqlite3 *db = pParse->db;
  100916. Db *pDb;
  100917. Vdbe *v = sqlite3GetVdbe(pParse);
  100918. int aRoot[ArraySize(aTable)];
  100919. u8 aCreateTbl[ArraySize(aTable)];
  100920. #ifdef SQLITE_ENABLE_STAT4
  100921. const int nToOpen = OptimizationEnabled(db,SQLITE_Stat4) ? 2 : 1;
  100922. #else
  100923. const int nToOpen = 1;
  100924. #endif
  100925. if( v==0 ) return;
  100926. assert( sqlite3BtreeHoldsAllMutexes(db) );
  100927. assert( sqlite3VdbeDb(v)==db );
  100928. pDb = &db->aDb[iDb];
  100929. /* Create new statistic tables if they do not exist, or clear them
  100930. ** if they do already exist.
  100931. */
  100932. for(i=0; i<ArraySize(aTable); i++){
  100933. const char *zTab = aTable[i].zName;
  100934. Table *pStat;
  100935. aCreateTbl[i] = 0;
  100936. if( (pStat = sqlite3FindTable(db, zTab, pDb->zDbSName))==0 ){
  100937. if( i<nToOpen ){
  100938. /* The sqlite_statN table does not exist. Create it. Note that a
  100939. ** side-effect of the CREATE TABLE statement is to leave the rootpage
  100940. ** of the new table in register pParse->regRoot. This is important
  100941. ** because the OpenWrite opcode below will be needing it. */
  100942. sqlite3NestedParse(pParse,
  100943. "CREATE TABLE %Q.%s(%s)", pDb->zDbSName, zTab, aTable[i].zCols
  100944. );
  100945. aRoot[i] = pParse->regRoot;
  100946. aCreateTbl[i] = OPFLAG_P2ISREG;
  100947. }
  100948. }else{
  100949. /* The table already exists. If zWhere is not NULL, delete all entries
  100950. ** associated with the table zWhere. If zWhere is NULL, delete the
  100951. ** entire contents of the table. */
  100952. aRoot[i] = pStat->tnum;
  100953. sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab);
  100954. if( zWhere ){
  100955. sqlite3NestedParse(pParse,
  100956. "DELETE FROM %Q.%s WHERE %s=%Q",
  100957. pDb->zDbSName, zTab, zWhereType, zWhere
  100958. );
  100959. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  100960. }else if( db->xPreUpdateCallback ){
  100961. sqlite3NestedParse(pParse, "DELETE FROM %Q.%s", pDb->zDbSName, zTab);
  100962. #endif
  100963. }else{
  100964. /* The sqlite_stat[134] table already exists. Delete all rows. */
  100965. sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb);
  100966. }
  100967. }
  100968. }
  100969. /* Open the sqlite_stat[134] tables for writing. */
  100970. for(i=0; i<nToOpen; i++){
  100971. assert( i<ArraySize(aTable) );
  100972. sqlite3VdbeAddOp4Int(v, OP_OpenWrite, iStatCur+i, aRoot[i], iDb, 3);
  100973. sqlite3VdbeChangeP5(v, aCreateTbl[i]);
  100974. VdbeComment((v, aTable[i].zName));
  100975. }
  100976. }
  100977. /*
  100978. ** Recommended number of samples for sqlite_stat4
  100979. */
  100980. #ifndef SQLITE_STAT4_SAMPLES
  100981. # define SQLITE_STAT4_SAMPLES 24
  100982. #endif
  100983. /*
  100984. ** Three SQL functions - stat_init(), stat_push(), and stat_get() -
  100985. ** share an instance of the following structure to hold their state
  100986. ** information.
  100987. */
  100988. typedef struct StatAccum StatAccum;
  100989. typedef struct StatSample StatSample;
  100990. struct StatSample {
  100991. tRowcnt *anEq; /* sqlite_stat4.nEq */
  100992. tRowcnt *anDLt; /* sqlite_stat4.nDLt */
  100993. #ifdef SQLITE_ENABLE_STAT4
  100994. tRowcnt *anLt; /* sqlite_stat4.nLt */
  100995. union {
  100996. i64 iRowid; /* Rowid in main table of the key */
  100997. u8 *aRowid; /* Key for WITHOUT ROWID tables */
  100998. } u;
  100999. u32 nRowid; /* Sizeof aRowid[] */
  101000. u8 isPSample; /* True if a periodic sample */
  101001. int iCol; /* If !isPSample, the reason for inclusion */
  101002. u32 iHash; /* Tiebreaker hash */
  101003. #endif
  101004. };
  101005. struct StatAccum {
  101006. sqlite3 *db; /* Database connection, for malloc() */
  101007. tRowcnt nEst; /* Estimated number of rows */
  101008. tRowcnt nRow; /* Number of rows visited so far */
  101009. int nLimit; /* Analysis row-scan limit */
  101010. int nCol; /* Number of columns in index + pk/rowid */
  101011. int nKeyCol; /* Number of index columns w/o the pk/rowid */
  101012. u8 nSkipAhead; /* Number of times of skip-ahead */
  101013. StatSample current; /* Current row as a StatSample */
  101014. #ifdef SQLITE_ENABLE_STAT4
  101015. tRowcnt nPSample; /* How often to do a periodic sample */
  101016. int mxSample; /* Maximum number of samples to accumulate */
  101017. u32 iPrn; /* Pseudo-random number used for sampling */
  101018. StatSample *aBest; /* Array of nCol best samples */
  101019. int iMin; /* Index in a[] of entry with minimum score */
  101020. int nSample; /* Current number of samples */
  101021. int nMaxEqZero; /* Max leading 0 in anEq[] for any a[] entry */
  101022. int iGet; /* Index of current sample accessed by stat_get() */
  101023. StatSample *a; /* Array of mxSample StatSample objects */
  101024. #endif
  101025. };
  101026. /* Reclaim memory used by a StatSample
  101027. */
  101028. #ifdef SQLITE_ENABLE_STAT4
  101029. static void sampleClear(sqlite3 *db, StatSample *p){
  101030. assert( db!=0 );
  101031. if( p->nRowid ){
  101032. sqlite3DbFree(db, p->u.aRowid);
  101033. p->nRowid = 0;
  101034. }
  101035. }
  101036. #endif
  101037. /* Initialize the BLOB value of a ROWID
  101038. */
  101039. #ifdef SQLITE_ENABLE_STAT4
  101040. static void sampleSetRowid(sqlite3 *db, StatSample *p, int n, const u8 *pData){
  101041. assert( db!=0 );
  101042. if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);
  101043. p->u.aRowid = sqlite3DbMallocRawNN(db, n);
  101044. if( p->u.aRowid ){
  101045. p->nRowid = n;
  101046. memcpy(p->u.aRowid, pData, n);
  101047. }else{
  101048. p->nRowid = 0;
  101049. }
  101050. }
  101051. #endif
  101052. /* Initialize the INTEGER value of a ROWID.
  101053. */
  101054. #ifdef SQLITE_ENABLE_STAT4
  101055. static void sampleSetRowidInt64(sqlite3 *db, StatSample *p, i64 iRowid){
  101056. assert( db!=0 );
  101057. if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);
  101058. p->nRowid = 0;
  101059. p->u.iRowid = iRowid;
  101060. }
  101061. #endif
  101062. /*
  101063. ** Copy the contents of object (*pFrom) into (*pTo).
  101064. */
  101065. #ifdef SQLITE_ENABLE_STAT4
  101066. static void sampleCopy(StatAccum *p, StatSample *pTo, StatSample *pFrom){
  101067. pTo->isPSample = pFrom->isPSample;
  101068. pTo->iCol = pFrom->iCol;
  101069. pTo->iHash = pFrom->iHash;
  101070. memcpy(pTo->anEq, pFrom->anEq, sizeof(tRowcnt)*p->nCol);
  101071. memcpy(pTo->anLt, pFrom->anLt, sizeof(tRowcnt)*p->nCol);
  101072. memcpy(pTo->anDLt, pFrom->anDLt, sizeof(tRowcnt)*p->nCol);
  101073. if( pFrom->nRowid ){
  101074. sampleSetRowid(p->db, pTo, pFrom->nRowid, pFrom->u.aRowid);
  101075. }else{
  101076. sampleSetRowidInt64(p->db, pTo, pFrom->u.iRowid);
  101077. }
  101078. }
  101079. #endif
  101080. /*
  101081. ** Reclaim all memory of a StatAccum structure.
  101082. */
  101083. static void statAccumDestructor(void *pOld){
  101084. StatAccum *p = (StatAccum*)pOld;
  101085. #ifdef SQLITE_ENABLE_STAT4
  101086. if( p->mxSample ){
  101087. int i;
  101088. for(i=0; i<p->nCol; i++) sampleClear(p->db, p->aBest+i);
  101089. for(i=0; i<p->mxSample; i++) sampleClear(p->db, p->a+i);
  101090. sampleClear(p->db, &p->current);
  101091. }
  101092. #endif
  101093. sqlite3DbFree(p->db, p);
  101094. }
  101095. /*
  101096. ** Implementation of the stat_init(N,K,C,L) SQL function. The four parameters
  101097. ** are:
  101098. ** N: The number of columns in the index including the rowid/pk (note 1)
  101099. ** K: The number of columns in the index excluding the rowid/pk.
  101100. ** C: Estimated number of rows in the index
  101101. ** L: A limit on the number of rows to scan, or 0 for no-limit
  101102. **
  101103. ** Note 1: In the special case of the covering index that implements a
  101104. ** WITHOUT ROWID table, N is the number of PRIMARY KEY columns, not the
  101105. ** total number of columns in the table.
  101106. **
  101107. ** For indexes on ordinary rowid tables, N==K+1. But for indexes on
  101108. ** WITHOUT ROWID tables, N=K+P where P is the number of columns in the
  101109. ** PRIMARY KEY of the table. The covering index that implements the
  101110. ** original WITHOUT ROWID table as N==K as a special case.
  101111. **
  101112. ** This routine allocates the StatAccum object in heap memory. The return
  101113. ** value is a pointer to the StatAccum object. The datatype of the
  101114. ** return value is BLOB, but it is really just a pointer to the StatAccum
  101115. ** object.
  101116. */
  101117. static void statInit(
  101118. sqlite3_context *context,
  101119. int argc,
  101120. sqlite3_value **argv
  101121. ){
  101122. StatAccum *p;
  101123. int nCol; /* Number of columns in index being sampled */
  101124. int nKeyCol; /* Number of key columns */
  101125. int nColUp; /* nCol rounded up for alignment */
  101126. int n; /* Bytes of space to allocate */
  101127. sqlite3 *db = sqlite3_context_db_handle(context); /* Database connection */
  101128. #ifdef SQLITE_ENABLE_STAT4
  101129. /* Maximum number of samples. 0 if STAT4 data is not collected */
  101130. int mxSample = OptimizationEnabled(db,SQLITE_Stat4) ?SQLITE_STAT4_SAMPLES :0;
  101131. #endif
  101132. /* Decode the three function arguments */
  101133. UNUSED_PARAMETER(argc);
  101134. nCol = sqlite3_value_int(argv[0]);
  101135. assert( nCol>0 );
  101136. nColUp = sizeof(tRowcnt)<8 ? (nCol+1)&~1 : nCol;
  101137. nKeyCol = sqlite3_value_int(argv[1]);
  101138. assert( nKeyCol<=nCol );
  101139. assert( nKeyCol>0 );
  101140. /* Allocate the space required for the StatAccum object */
  101141. n = sizeof(*p)
  101142. + sizeof(tRowcnt)*nColUp /* StatAccum.anEq */
  101143. + sizeof(tRowcnt)*nColUp; /* StatAccum.anDLt */
  101144. #ifdef SQLITE_ENABLE_STAT4
  101145. if( mxSample ){
  101146. n += sizeof(tRowcnt)*nColUp /* StatAccum.anLt */
  101147. + sizeof(StatSample)*(nCol+mxSample) /* StatAccum.aBest[], a[] */
  101148. + sizeof(tRowcnt)*3*nColUp*(nCol+mxSample);
  101149. }
  101150. #endif
  101151. db = sqlite3_context_db_handle(context);
  101152. p = sqlite3DbMallocZero(db, n);
  101153. if( p==0 ){
  101154. sqlite3_result_error_nomem(context);
  101155. return;
  101156. }
  101157. p->db = db;
  101158. p->nEst = sqlite3_value_int64(argv[2]);
  101159. p->nRow = 0;
  101160. p->nLimit = sqlite3_value_int64(argv[3]);
  101161. p->nCol = nCol;
  101162. p->nKeyCol = nKeyCol;
  101163. p->nSkipAhead = 0;
  101164. p->current.anDLt = (tRowcnt*)&p[1];
  101165. p->current.anEq = &p->current.anDLt[nColUp];
  101166. #ifdef SQLITE_ENABLE_STAT4
  101167. p->mxSample = p->nLimit==0 ? mxSample : 0;
  101168. if( mxSample ){
  101169. u8 *pSpace; /* Allocated space not yet assigned */
  101170. int i; /* Used to iterate through p->aSample[] */
  101171. p->iGet = -1;
  101172. p->nPSample = (tRowcnt)(p->nEst/(mxSample/3+1) + 1);
  101173. p->current.anLt = &p->current.anEq[nColUp];
  101174. p->iPrn = 0x689e962d*(u32)nCol ^ 0xd0944565*(u32)sqlite3_value_int(argv[2]);
  101175. /* Set up the StatAccum.a[] and aBest[] arrays */
  101176. p->a = (struct StatSample*)&p->current.anLt[nColUp];
  101177. p->aBest = &p->a[mxSample];
  101178. pSpace = (u8*)(&p->a[mxSample+nCol]);
  101179. for(i=0; i<(mxSample+nCol); i++){
  101180. p->a[i].anEq = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
  101181. p->a[i].anLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
  101182. p->a[i].anDLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
  101183. }
  101184. assert( (pSpace - (u8*)p)==n );
  101185. for(i=0; i<nCol; i++){
  101186. p->aBest[i].iCol = i;
  101187. }
  101188. }
  101189. #endif
  101190. /* Return a pointer to the allocated object to the caller. Note that
  101191. ** only the pointer (the 2nd parameter) matters. The size of the object
  101192. ** (given by the 3rd parameter) is never used and can be any positive
  101193. ** value. */
  101194. sqlite3_result_blob(context, p, sizeof(*p), statAccumDestructor);
  101195. }
  101196. static const FuncDef statInitFuncdef = {
  101197. 4, /* nArg */
  101198. SQLITE_UTF8, /* funcFlags */
  101199. 0, /* pUserData */
  101200. 0, /* pNext */
  101201. statInit, /* xSFunc */
  101202. 0, /* xFinalize */
  101203. 0, 0, /* xValue, xInverse */
  101204. "stat_init", /* zName */
  101205. {0}
  101206. };
  101207. #ifdef SQLITE_ENABLE_STAT4
  101208. /*
  101209. ** pNew and pOld are both candidate non-periodic samples selected for
  101210. ** the same column (pNew->iCol==pOld->iCol). Ignoring this column and
  101211. ** considering only any trailing columns and the sample hash value, this
  101212. ** function returns true if sample pNew is to be preferred over pOld.
  101213. ** In other words, if we assume that the cardinalities of the selected
  101214. ** column for pNew and pOld are equal, is pNew to be preferred over pOld.
  101215. **
  101216. ** This function assumes that for each argument sample, the contents of
  101217. ** the anEq[] array from pSample->anEq[pSample->iCol+1] onwards are valid.
  101218. */
  101219. static int sampleIsBetterPost(
  101220. StatAccum *pAccum,
  101221. StatSample *pNew,
  101222. StatSample *pOld
  101223. ){
  101224. int nCol = pAccum->nCol;
  101225. int i;
  101226. assert( pNew->iCol==pOld->iCol );
  101227. for(i=pNew->iCol+1; i<nCol; i++){
  101228. if( pNew->anEq[i]>pOld->anEq[i] ) return 1;
  101229. if( pNew->anEq[i]<pOld->anEq[i] ) return 0;
  101230. }
  101231. if( pNew->iHash>pOld->iHash ) return 1;
  101232. return 0;
  101233. }
  101234. #endif
  101235. #ifdef SQLITE_ENABLE_STAT4
  101236. /*
  101237. ** Return true if pNew is to be preferred over pOld.
  101238. **
  101239. ** This function assumes that for each argument sample, the contents of
  101240. ** the anEq[] array from pSample->anEq[pSample->iCol] onwards are valid.
  101241. */
  101242. static int sampleIsBetter(
  101243. StatAccum *pAccum,
  101244. StatSample *pNew,
  101245. StatSample *pOld
  101246. ){
  101247. tRowcnt nEqNew = pNew->anEq[pNew->iCol];
  101248. tRowcnt nEqOld = pOld->anEq[pOld->iCol];
  101249. assert( pOld->isPSample==0 && pNew->isPSample==0 );
  101250. assert( IsStat4 || (pNew->iCol==0 && pOld->iCol==0) );
  101251. if( (nEqNew>nEqOld) ) return 1;
  101252. if( nEqNew==nEqOld ){
  101253. if( pNew->iCol<pOld->iCol ) return 1;
  101254. return (pNew->iCol==pOld->iCol && sampleIsBetterPost(pAccum, pNew, pOld));
  101255. }
  101256. return 0;
  101257. }
  101258. /*
  101259. ** Copy the contents of sample *pNew into the p->a[] array. If necessary,
  101260. ** remove the least desirable sample from p->a[] to make room.
  101261. */
  101262. static void sampleInsert(StatAccum *p, StatSample *pNew, int nEqZero){
  101263. StatSample *pSample = 0;
  101264. int i;
  101265. assert( IsStat4 || nEqZero==0 );
  101266. /* StatAccum.nMaxEqZero is set to the maximum number of leading 0
  101267. ** values in the anEq[] array of any sample in StatAccum.a[]. In
  101268. ** other words, if nMaxEqZero is n, then it is guaranteed that there
  101269. ** are no samples with StatSample.anEq[m]==0 for (m>=n). */
  101270. if( nEqZero>p->nMaxEqZero ){
  101271. p->nMaxEqZero = nEqZero;
  101272. }
  101273. if( pNew->isPSample==0 ){
  101274. StatSample *pUpgrade = 0;
  101275. assert( pNew->anEq[pNew->iCol]>0 );
  101276. /* This sample is being added because the prefix that ends in column
  101277. ** iCol occurs many times in the table. However, if we have already
  101278. ** added a sample that shares this prefix, there is no need to add
  101279. ** this one. Instead, upgrade the priority of the highest priority
  101280. ** existing sample that shares this prefix. */
  101281. for(i=p->nSample-1; i>=0; i--){
  101282. StatSample *pOld = &p->a[i];
  101283. if( pOld->anEq[pNew->iCol]==0 ){
  101284. if( pOld->isPSample ) return;
  101285. assert( pOld->iCol>pNew->iCol );
  101286. assert( sampleIsBetter(p, pNew, pOld) );
  101287. if( pUpgrade==0 || sampleIsBetter(p, pOld, pUpgrade) ){
  101288. pUpgrade = pOld;
  101289. }
  101290. }
  101291. }
  101292. if( pUpgrade ){
  101293. pUpgrade->iCol = pNew->iCol;
  101294. pUpgrade->anEq[pUpgrade->iCol] = pNew->anEq[pUpgrade->iCol];
  101295. goto find_new_min;
  101296. }
  101297. }
  101298. /* If necessary, remove sample iMin to make room for the new sample. */
  101299. if( p->nSample>=p->mxSample ){
  101300. StatSample *pMin = &p->a[p->iMin];
  101301. tRowcnt *anEq = pMin->anEq;
  101302. tRowcnt *anLt = pMin->anLt;
  101303. tRowcnt *anDLt = pMin->anDLt;
  101304. sampleClear(p->db, pMin);
  101305. memmove(pMin, &pMin[1], sizeof(p->a[0])*(p->nSample-p->iMin-1));
  101306. pSample = &p->a[p->nSample-1];
  101307. pSample->nRowid = 0;
  101308. pSample->anEq = anEq;
  101309. pSample->anDLt = anDLt;
  101310. pSample->anLt = anLt;
  101311. p->nSample = p->mxSample-1;
  101312. }
  101313. /* The "rows less-than" for the rowid column must be greater than that
  101314. ** for the last sample in the p->a[] array. Otherwise, the samples would
  101315. ** be out of order. */
  101316. assert( p->nSample==0
  101317. || pNew->anLt[p->nCol-1] > p->a[p->nSample-1].anLt[p->nCol-1] );
  101318. /* Insert the new sample */
  101319. pSample = &p->a[p->nSample];
  101320. sampleCopy(p, pSample, pNew);
  101321. p->nSample++;
  101322. /* Zero the first nEqZero entries in the anEq[] array. */
  101323. memset(pSample->anEq, 0, sizeof(tRowcnt)*nEqZero);
  101324. find_new_min:
  101325. if( p->nSample>=p->mxSample ){
  101326. int iMin = -1;
  101327. for(i=0; i<p->mxSample; i++){
  101328. if( p->a[i].isPSample ) continue;
  101329. if( iMin<0 || sampleIsBetter(p, &p->a[iMin], &p->a[i]) ){
  101330. iMin = i;
  101331. }
  101332. }
  101333. assert( iMin>=0 );
  101334. p->iMin = iMin;
  101335. }
  101336. }
  101337. #endif /* SQLITE_ENABLE_STAT4 */
  101338. #ifdef SQLITE_ENABLE_STAT4
  101339. /*
  101340. ** Field iChng of the index being scanned has changed. So at this point
  101341. ** p->current contains a sample that reflects the previous row of the
  101342. ** index. The value of anEq[iChng] and subsequent anEq[] elements are
  101343. ** correct at this point.
  101344. */
  101345. static void samplePushPrevious(StatAccum *p, int iChng){
  101346. int i;
  101347. /* Check if any samples from the aBest[] array should be pushed
  101348. ** into IndexSample.a[] at this point. */
  101349. for(i=(p->nCol-2); i>=iChng; i--){
  101350. StatSample *pBest = &p->aBest[i];
  101351. pBest->anEq[i] = p->current.anEq[i];
  101352. if( p->nSample<p->mxSample || sampleIsBetter(p, pBest, &p->a[p->iMin]) ){
  101353. sampleInsert(p, pBest, i);
  101354. }
  101355. }
  101356. /* Check that no sample contains an anEq[] entry with an index of
  101357. ** p->nMaxEqZero or greater set to zero. */
  101358. for(i=p->nSample-1; i>=0; i--){
  101359. int j;
  101360. for(j=p->nMaxEqZero; j<p->nCol; j++) assert( p->a[i].anEq[j]>0 );
  101361. }
  101362. /* Update the anEq[] fields of any samples already collected. */
  101363. if( iChng<p->nMaxEqZero ){
  101364. for(i=p->nSample-1; i>=0; i--){
  101365. int j;
  101366. for(j=iChng; j<p->nCol; j++){
  101367. if( p->a[i].anEq[j]==0 ) p->a[i].anEq[j] = p->current.anEq[j];
  101368. }
  101369. }
  101370. p->nMaxEqZero = iChng;
  101371. }
  101372. }
  101373. #endif /* SQLITE_ENABLE_STAT4 */
  101374. /*
  101375. ** Implementation of the stat_push SQL function: stat_push(P,C,R)
  101376. ** Arguments:
  101377. **
  101378. ** P Pointer to the StatAccum object created by stat_init()
  101379. ** C Index of left-most column to differ from previous row
  101380. ** R Rowid for the current row. Might be a key record for
  101381. ** WITHOUT ROWID tables.
  101382. **
  101383. ** The purpose of this routine is to collect statistical data and/or
  101384. ** samples from the index being analyzed into the StatAccum object.
  101385. ** The stat_get() SQL function will be used afterwards to
  101386. ** retrieve the information gathered.
  101387. **
  101388. ** This SQL function usually returns NULL, but might return an integer
  101389. ** if it wants the byte-code to do special processing.
  101390. **
  101391. ** The R parameter is only used for STAT4
  101392. */
  101393. static void statPush(
  101394. sqlite3_context *context,
  101395. int argc,
  101396. sqlite3_value **argv
  101397. ){
  101398. int i;
  101399. /* The three function arguments */
  101400. StatAccum *p = (StatAccum*)sqlite3_value_blob(argv[0]);
  101401. int iChng = sqlite3_value_int(argv[1]);
  101402. UNUSED_PARAMETER( argc );
  101403. UNUSED_PARAMETER( context );
  101404. assert( p->nCol>0 );
  101405. assert( iChng<p->nCol );
  101406. if( p->nRow==0 ){
  101407. /* This is the first call to this function. Do initialization. */
  101408. for(i=0; i<p->nCol; i++) p->current.anEq[i] = 1;
  101409. }else{
  101410. /* Second and subsequent calls get processed here */
  101411. #ifdef SQLITE_ENABLE_STAT4
  101412. if( p->mxSample ) samplePushPrevious(p, iChng);
  101413. #endif
  101414. /* Update anDLt[], anLt[] and anEq[] to reflect the values that apply
  101415. ** to the current row of the index. */
  101416. for(i=0; i<iChng; i++){
  101417. p->current.anEq[i]++;
  101418. }
  101419. for(i=iChng; i<p->nCol; i++){
  101420. p->current.anDLt[i]++;
  101421. #ifdef SQLITE_ENABLE_STAT4
  101422. if( p->mxSample ) p->current.anLt[i] += p->current.anEq[i];
  101423. #endif
  101424. p->current.anEq[i] = 1;
  101425. }
  101426. }
  101427. p->nRow++;
  101428. #ifdef SQLITE_ENABLE_STAT4
  101429. if( p->mxSample ){
  101430. tRowcnt nLt;
  101431. if( sqlite3_value_type(argv[2])==SQLITE_INTEGER ){
  101432. sampleSetRowidInt64(p->db, &p->current, sqlite3_value_int64(argv[2]));
  101433. }else{
  101434. sampleSetRowid(p->db, &p->current, sqlite3_value_bytes(argv[2]),
  101435. sqlite3_value_blob(argv[2]));
  101436. }
  101437. p->current.iHash = p->iPrn = p->iPrn*1103515245 + 12345;
  101438. nLt = p->current.anLt[p->nCol-1];
  101439. /* Check if this is to be a periodic sample. If so, add it. */
  101440. if( (nLt/p->nPSample)!=(nLt+1)/p->nPSample ){
  101441. p->current.isPSample = 1;
  101442. p->current.iCol = 0;
  101443. sampleInsert(p, &p->current, p->nCol-1);
  101444. p->current.isPSample = 0;
  101445. }
  101446. /* Update the aBest[] array. */
  101447. for(i=0; i<(p->nCol-1); i++){
  101448. p->current.iCol = i;
  101449. if( i>=iChng || sampleIsBetterPost(p, &p->current, &p->aBest[i]) ){
  101450. sampleCopy(p, &p->aBest[i], &p->current);
  101451. }
  101452. }
  101453. }else
  101454. #endif
  101455. if( p->nLimit && p->nRow>(tRowcnt)p->nLimit*(p->nSkipAhead+1) ){
  101456. p->nSkipAhead++;
  101457. sqlite3_result_int(context, p->current.anDLt[0]>0);
  101458. }
  101459. }
  101460. static const FuncDef statPushFuncdef = {
  101461. 2+IsStat4, /* nArg */
  101462. SQLITE_UTF8, /* funcFlags */
  101463. 0, /* pUserData */
  101464. 0, /* pNext */
  101465. statPush, /* xSFunc */
  101466. 0, /* xFinalize */
  101467. 0, 0, /* xValue, xInverse */
  101468. "stat_push", /* zName */
  101469. {0}
  101470. };
  101471. #define STAT_GET_STAT1 0 /* "stat" column of stat1 table */
  101472. #define STAT_GET_ROWID 1 /* "rowid" column of stat[34] entry */
  101473. #define STAT_GET_NEQ 2 /* "neq" column of stat[34] entry */
  101474. #define STAT_GET_NLT 3 /* "nlt" column of stat[34] entry */
  101475. #define STAT_GET_NDLT 4 /* "ndlt" column of stat[34] entry */
  101476. /*
  101477. ** Implementation of the stat_get(P,J) SQL function. This routine is
  101478. ** used to query statistical information that has been gathered into
  101479. ** the StatAccum object by prior calls to stat_push(). The P parameter
  101480. ** has type BLOB but it is really just a pointer to the StatAccum object.
  101481. ** The content to returned is determined by the parameter J
  101482. ** which is one of the STAT_GET_xxxx values defined above.
  101483. **
  101484. ** The stat_get(P,J) function is not available to generic SQL. It is
  101485. ** inserted as part of a manually constructed bytecode program. (See
  101486. ** the callStatGet() routine below.) It is guaranteed that the P
  101487. ** parameter will always be a pointer to a StatAccum object, never a
  101488. ** NULL.
  101489. **
  101490. ** If STAT4 is not enabled, then J is always
  101491. ** STAT_GET_STAT1 and is hence omitted and this routine becomes
  101492. ** a one-parameter function, stat_get(P), that always returns the
  101493. ** stat1 table entry information.
  101494. */
  101495. static void statGet(
  101496. sqlite3_context *context,
  101497. int argc,
  101498. sqlite3_value **argv
  101499. ){
  101500. StatAccum *p = (StatAccum*)sqlite3_value_blob(argv[0]);
  101501. #ifdef SQLITE_ENABLE_STAT4
  101502. /* STAT4 has a parameter on this routine. */
  101503. int eCall = sqlite3_value_int(argv[1]);
  101504. assert( argc==2 );
  101505. assert( eCall==STAT_GET_STAT1 || eCall==STAT_GET_NEQ
  101506. || eCall==STAT_GET_ROWID || eCall==STAT_GET_NLT
  101507. || eCall==STAT_GET_NDLT
  101508. );
  101509. assert( eCall==STAT_GET_STAT1 || p->mxSample );
  101510. if( eCall==STAT_GET_STAT1 )
  101511. #else
  101512. assert( argc==1 );
  101513. #endif
  101514. {
  101515. /* Return the value to store in the "stat" column of the sqlite_stat1
  101516. ** table for this index.
  101517. **
  101518. ** The value is a string composed of a list of integers describing
  101519. ** the index. The first integer in the list is the total number of
  101520. ** entries in the index. There is one additional integer in the list
  101521. ** for each indexed column. This additional integer is an estimate of
  101522. ** the number of rows matched by a equality query on the index using
  101523. ** a key with the corresponding number of fields. In other words,
  101524. ** if the index is on columns (a,b) and the sqlite_stat1 value is
  101525. ** "100 10 2", then SQLite estimates that:
  101526. **
  101527. ** * the index contains 100 rows,
  101528. ** * "WHERE a=?" matches 10 rows, and
  101529. ** * "WHERE a=? AND b=?" matches 2 rows.
  101530. **
  101531. ** If D is the count of distinct values and K is the total number of
  101532. ** rows, then each estimate is computed as:
  101533. **
  101534. ** I = (K+D-1)/D
  101535. */
  101536. char *z;
  101537. int i;
  101538. char *zRet = sqlite3MallocZero( (p->nKeyCol+1)*25 );
  101539. if( zRet==0 ){
  101540. sqlite3_result_error_nomem(context);
  101541. return;
  101542. }
  101543. sqlite3_snprintf(24, zRet, "%llu",
  101544. p->nSkipAhead ? (u64)p->nEst : (u64)p->nRow);
  101545. z = zRet + sqlite3Strlen30(zRet);
  101546. for(i=0; i<p->nKeyCol; i++){
  101547. u64 nDistinct = p->current.anDLt[i] + 1;
  101548. u64 iVal = (p->nRow + nDistinct - 1) / nDistinct;
  101549. sqlite3_snprintf(24, z, " %llu", iVal);
  101550. z += sqlite3Strlen30(z);
  101551. assert( p->current.anEq[i] );
  101552. }
  101553. assert( z[0]=='\0' && z>zRet );
  101554. sqlite3_result_text(context, zRet, -1, sqlite3_free);
  101555. }
  101556. #ifdef SQLITE_ENABLE_STAT4
  101557. else if( eCall==STAT_GET_ROWID ){
  101558. if( p->iGet<0 ){
  101559. samplePushPrevious(p, 0);
  101560. p->iGet = 0;
  101561. }
  101562. if( p->iGet<p->nSample ){
  101563. StatSample *pS = p->a + p->iGet;
  101564. if( pS->nRowid==0 ){
  101565. sqlite3_result_int64(context, pS->u.iRowid);
  101566. }else{
  101567. sqlite3_result_blob(context, pS->u.aRowid, pS->nRowid,
  101568. SQLITE_TRANSIENT);
  101569. }
  101570. }
  101571. }else{
  101572. tRowcnt *aCnt = 0;
  101573. assert( p->iGet<p->nSample );
  101574. switch( eCall ){
  101575. case STAT_GET_NEQ: aCnt = p->a[p->iGet].anEq; break;
  101576. case STAT_GET_NLT: aCnt = p->a[p->iGet].anLt; break;
  101577. default: {
  101578. aCnt = p->a[p->iGet].anDLt;
  101579. p->iGet++;
  101580. break;
  101581. }
  101582. }
  101583. {
  101584. char *zRet = sqlite3MallocZero(p->nCol * 25);
  101585. if( zRet==0 ){
  101586. sqlite3_result_error_nomem(context);
  101587. }else{
  101588. int i;
  101589. char *z = zRet;
  101590. for(i=0; i<p->nCol; i++){
  101591. sqlite3_snprintf(24, z, "%llu ", (u64)aCnt[i]);
  101592. z += sqlite3Strlen30(z);
  101593. }
  101594. assert( z[0]=='\0' && z>zRet );
  101595. z[-1] = '\0';
  101596. sqlite3_result_text(context, zRet, -1, sqlite3_free);
  101597. }
  101598. }
  101599. }
  101600. #endif /* SQLITE_ENABLE_STAT4 */
  101601. #ifndef SQLITE_DEBUG
  101602. UNUSED_PARAMETER( argc );
  101603. #endif
  101604. }
  101605. static const FuncDef statGetFuncdef = {
  101606. 1+IsStat4, /* nArg */
  101607. SQLITE_UTF8, /* funcFlags */
  101608. 0, /* pUserData */
  101609. 0, /* pNext */
  101610. statGet, /* xSFunc */
  101611. 0, /* xFinalize */
  101612. 0, 0, /* xValue, xInverse */
  101613. "stat_get", /* zName */
  101614. {0}
  101615. };
  101616. static void callStatGet(Parse *pParse, int regStat, int iParam, int regOut){
  101617. #ifdef SQLITE_ENABLE_STAT4
  101618. sqlite3VdbeAddOp2(pParse->pVdbe, OP_Integer, iParam, regStat+1);
  101619. #elif SQLITE_DEBUG
  101620. assert( iParam==STAT_GET_STAT1 );
  101621. #else
  101622. UNUSED_PARAMETER( iParam );
  101623. #endif
  101624. assert( regOut!=regStat && regOut!=regStat+1 );
  101625. sqlite3VdbeAddFunctionCall(pParse, 0, regStat, regOut, 1+IsStat4,
  101626. &statGetFuncdef, 0);
  101627. }
  101628. /*
  101629. ** Generate code to do an analysis of all indices associated with
  101630. ** a single table.
  101631. */
  101632. static void analyzeOneTable(
  101633. Parse *pParse, /* Parser context */
  101634. Table *pTab, /* Table whose indices are to be analyzed */
  101635. Index *pOnlyIdx, /* If not NULL, only analyze this one index */
  101636. int iStatCur, /* Index of VdbeCursor that writes the sqlite_stat1 table */
  101637. int iMem, /* Available memory locations begin here */
  101638. int iTab /* Next available cursor */
  101639. ){
  101640. sqlite3 *db = pParse->db; /* Database handle */
  101641. Index *pIdx; /* An index to being analyzed */
  101642. int iIdxCur; /* Cursor open on index being analyzed */
  101643. int iTabCur; /* Table cursor */
  101644. Vdbe *v; /* The virtual machine being built up */
  101645. int i; /* Loop counter */
  101646. int jZeroRows = -1; /* Jump from here if number of rows is zero */
  101647. int iDb; /* Index of database containing pTab */
  101648. u8 needTableCnt = 1; /* True to count the table */
  101649. int regNewRowid = iMem++; /* Rowid for the inserted record */
  101650. int regStat = iMem++; /* Register to hold StatAccum object */
  101651. int regChng = iMem++; /* Index of changed index field */
  101652. int regRowid = iMem++; /* Rowid argument passed to stat_push() */
  101653. int regTemp = iMem++; /* Temporary use register */
  101654. int regTemp2 = iMem++; /* Second temporary use register */
  101655. int regTabname = iMem++; /* Register containing table name */
  101656. int regIdxname = iMem++; /* Register containing index name */
  101657. int regStat1 = iMem++; /* Value for the stat column of sqlite_stat1 */
  101658. int regPrev = iMem; /* MUST BE LAST (see below) */
  101659. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  101660. Table *pStat1 = 0;
  101661. #endif
  101662. pParse->nMem = MAX(pParse->nMem, iMem);
  101663. v = sqlite3GetVdbe(pParse);
  101664. if( v==0 || NEVER(pTab==0) ){
  101665. return;
  101666. }
  101667. if( pTab->tnum==0 ){
  101668. /* Do not gather statistics on views or virtual tables */
  101669. return;
  101670. }
  101671. if( sqlite3_strlike("sqlite\\_%", pTab->zName, '\\')==0 ){
  101672. /* Do not gather statistics on system tables */
  101673. return;
  101674. }
  101675. assert( sqlite3BtreeHoldsAllMutexes(db) );
  101676. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  101677. assert( iDb>=0 );
  101678. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  101679. #ifndef SQLITE_OMIT_AUTHORIZATION
  101680. if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
  101681. db->aDb[iDb].zDbSName ) ){
  101682. return;
  101683. }
  101684. #endif
  101685. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  101686. if( db->xPreUpdateCallback ){
  101687. pStat1 = (Table*)sqlite3DbMallocZero(db, sizeof(Table) + 13);
  101688. if( pStat1==0 ) return;
  101689. pStat1->zName = (char*)&pStat1[1];
  101690. memcpy(pStat1->zName, "sqlite_stat1", 13);
  101691. pStat1->nCol = 3;
  101692. pStat1->iPKey = -1;
  101693. sqlite3VdbeAddOp4(pParse->pVdbe, OP_Noop, 0, 0, 0,(char*)pStat1,P4_DYNBLOB);
  101694. }
  101695. #endif
  101696. /* Establish a read-lock on the table at the shared-cache level.
  101697. ** Open a read-only cursor on the table. Also allocate a cursor number
  101698. ** to use for scanning indexes (iIdxCur). No index cursor is opened at
  101699. ** this time though. */
  101700. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  101701. iTabCur = iTab++;
  101702. iIdxCur = iTab++;
  101703. pParse->nTab = MAX(pParse->nTab, iTab);
  101704. sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);
  101705. sqlite3VdbeLoadString(v, regTabname, pTab->zName);
  101706. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  101707. int nCol; /* Number of columns in pIdx. "N" */
  101708. int addrRewind; /* Address of "OP_Rewind iIdxCur" */
  101709. int addrNextRow; /* Address of "next_row:" */
  101710. const char *zIdxName; /* Name of the index */
  101711. int nColTest; /* Number of columns to test for changes */
  101712. if( pOnlyIdx && pOnlyIdx!=pIdx ) continue;
  101713. if( pIdx->pPartIdxWhere==0 ) needTableCnt = 0;
  101714. if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIdx) ){
  101715. nCol = pIdx->nKeyCol;
  101716. zIdxName = pTab->zName;
  101717. nColTest = nCol - 1;
  101718. }else{
  101719. nCol = pIdx->nColumn;
  101720. zIdxName = pIdx->zName;
  101721. nColTest = pIdx->uniqNotNull ? pIdx->nKeyCol-1 : nCol-1;
  101722. }
  101723. /* Populate the register containing the index name. */
  101724. sqlite3VdbeLoadString(v, regIdxname, zIdxName);
  101725. VdbeComment((v, "Analysis for %s.%s", pTab->zName, zIdxName));
  101726. /*
  101727. ** Pseudo-code for loop that calls stat_push():
  101728. **
  101729. ** Rewind csr
  101730. ** if eof(csr) goto end_of_scan;
  101731. ** regChng = 0
  101732. ** goto chng_addr_0;
  101733. **
  101734. ** next_row:
  101735. ** regChng = 0
  101736. ** if( idx(0) != regPrev(0) ) goto chng_addr_0
  101737. ** regChng = 1
  101738. ** if( idx(1) != regPrev(1) ) goto chng_addr_1
  101739. ** ...
  101740. ** regChng = N
  101741. ** goto chng_addr_N
  101742. **
  101743. ** chng_addr_0:
  101744. ** regPrev(0) = idx(0)
  101745. ** chng_addr_1:
  101746. ** regPrev(1) = idx(1)
  101747. ** ...
  101748. **
  101749. ** endDistinctTest:
  101750. ** regRowid = idx(rowid)
  101751. ** stat_push(P, regChng, regRowid)
  101752. ** Next csr
  101753. ** if !eof(csr) goto next_row;
  101754. **
  101755. ** end_of_scan:
  101756. */
  101757. /* Make sure there are enough memory cells allocated to accommodate
  101758. ** the regPrev array and a trailing rowid (the rowid slot is required
  101759. ** when building a record to insert into the sample column of
  101760. ** the sqlite_stat4 table. */
  101761. pParse->nMem = MAX(pParse->nMem, regPrev+nColTest);
  101762. /* Open a read-only cursor on the index being analyzed. */
  101763. assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
  101764. sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb);
  101765. sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  101766. VdbeComment((v, "%s", pIdx->zName));
  101767. /* Invoke the stat_init() function. The arguments are:
  101768. **
  101769. ** (1) the number of columns in the index including the rowid
  101770. ** (or for a WITHOUT ROWID table, the number of PK columns),
  101771. ** (2) the number of columns in the key without the rowid/pk
  101772. ** (3) estimated number of rows in the index,
  101773. */
  101774. sqlite3VdbeAddOp2(v, OP_Integer, nCol, regStat+1);
  101775. assert( regRowid==regStat+2 );
  101776. sqlite3VdbeAddOp2(v, OP_Integer, pIdx->nKeyCol, regRowid);
  101777. #ifdef SQLITE_ENABLE_STAT4
  101778. if( OptimizationEnabled(db, SQLITE_Stat4) ){
  101779. sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regTemp);
  101780. addrRewind = sqlite3VdbeAddOp1(v, OP_Rewind, iIdxCur);
  101781. VdbeCoverage(v);
  101782. }else
  101783. #endif
  101784. {
  101785. addrRewind = sqlite3VdbeAddOp1(v, OP_Rewind, iIdxCur);
  101786. VdbeCoverage(v);
  101787. sqlite3VdbeAddOp3(v, OP_Count, iIdxCur, regTemp, 1);
  101788. }
  101789. assert( regTemp2==regStat+4 );
  101790. sqlite3VdbeAddOp2(v, OP_Integer, db->nAnalysisLimit, regTemp2);
  101791. sqlite3VdbeAddFunctionCall(pParse, 0, regStat+1, regStat, 4,
  101792. &statInitFuncdef, 0);
  101793. /* Implementation of the following:
  101794. **
  101795. ** Rewind csr
  101796. ** if eof(csr) goto end_of_scan;
  101797. ** regChng = 0
  101798. ** goto next_push_0;
  101799. **
  101800. */
  101801. sqlite3VdbeAddOp2(v, OP_Integer, 0, regChng);
  101802. addrNextRow = sqlite3VdbeCurrentAddr(v);
  101803. if( nColTest>0 ){
  101804. int endDistinctTest = sqlite3VdbeMakeLabel(pParse);
  101805. int *aGotoChng; /* Array of jump instruction addresses */
  101806. aGotoChng = sqlite3DbMallocRawNN(db, sizeof(int)*nColTest);
  101807. if( aGotoChng==0 ) continue;
  101808. /*
  101809. ** next_row:
  101810. ** regChng = 0
  101811. ** if( idx(0) != regPrev(0) ) goto chng_addr_0
  101812. ** regChng = 1
  101813. ** if( idx(1) != regPrev(1) ) goto chng_addr_1
  101814. ** ...
  101815. ** regChng = N
  101816. ** goto endDistinctTest
  101817. */
  101818. sqlite3VdbeAddOp0(v, OP_Goto);
  101819. addrNextRow = sqlite3VdbeCurrentAddr(v);
  101820. if( nColTest==1 && pIdx->nKeyCol==1 && IsUniqueIndex(pIdx) ){
  101821. /* For a single-column UNIQUE index, once we have found a non-NULL
  101822. ** row, we know that all the rest will be distinct, so skip
  101823. ** subsequent distinctness tests. */
  101824. sqlite3VdbeAddOp2(v, OP_NotNull, regPrev, endDistinctTest);
  101825. VdbeCoverage(v);
  101826. }
  101827. for(i=0; i<nColTest; i++){
  101828. char *pColl = (char*)sqlite3LocateCollSeq(pParse, pIdx->azColl[i]);
  101829. sqlite3VdbeAddOp2(v, OP_Integer, i, regChng);
  101830. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regTemp);
  101831. VdbeComment((v, "%s.column(%d)", pIdx->zName, i));
  101832. aGotoChng[i] =
  101833. sqlite3VdbeAddOp4(v, OP_Ne, regTemp, 0, regPrev+i, pColl, P4_COLLSEQ);
  101834. sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
  101835. VdbeCoverage(v);
  101836. }
  101837. sqlite3VdbeAddOp2(v, OP_Integer, nColTest, regChng);
  101838. sqlite3VdbeGoto(v, endDistinctTest);
  101839. /*
  101840. ** chng_addr_0:
  101841. ** regPrev(0) = idx(0)
  101842. ** chng_addr_1:
  101843. ** regPrev(1) = idx(1)
  101844. ** ...
  101845. */
  101846. sqlite3VdbeJumpHere(v, addrNextRow-1);
  101847. for(i=0; i<nColTest; i++){
  101848. sqlite3VdbeJumpHere(v, aGotoChng[i]);
  101849. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regPrev+i);
  101850. VdbeComment((v, "%s.column(%d)", pIdx->zName, i));
  101851. }
  101852. sqlite3VdbeResolveLabel(v, endDistinctTest);
  101853. sqlite3DbFree(db, aGotoChng);
  101854. }
  101855. /*
  101856. ** chng_addr_N:
  101857. ** regRowid = idx(rowid) // STAT4 only
  101858. ** stat_push(P, regChng, regRowid) // 3rd parameter STAT4 only
  101859. ** Next csr
  101860. ** if !eof(csr) goto next_row;
  101861. */
  101862. #ifdef SQLITE_ENABLE_STAT4
  101863. if( OptimizationEnabled(db, SQLITE_Stat4) ){
  101864. assert( regRowid==(regStat+2) );
  101865. if( HasRowid(pTab) ){
  101866. sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, regRowid);
  101867. }else{
  101868. Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
  101869. int j, k, regKey;
  101870. regKey = sqlite3GetTempRange(pParse, pPk->nKeyCol);
  101871. for(j=0; j<pPk->nKeyCol; j++){
  101872. k = sqlite3TableColumnToIndex(pIdx, pPk->aiColumn[j]);
  101873. assert( k>=0 && k<pIdx->nColumn );
  101874. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, regKey+j);
  101875. VdbeComment((v, "%s.column(%d)", pIdx->zName, i));
  101876. }
  101877. sqlite3VdbeAddOp3(v, OP_MakeRecord, regKey, pPk->nKeyCol, regRowid);
  101878. sqlite3ReleaseTempRange(pParse, regKey, pPk->nKeyCol);
  101879. }
  101880. }
  101881. #endif
  101882. assert( regChng==(regStat+1) );
  101883. {
  101884. sqlite3VdbeAddFunctionCall(pParse, 1, regStat, regTemp, 2+IsStat4,
  101885. &statPushFuncdef, 0);
  101886. if( db->nAnalysisLimit ){
  101887. int j1, j2, j3;
  101888. j1 = sqlite3VdbeAddOp1(v, OP_IsNull, regTemp); VdbeCoverage(v);
  101889. j2 = sqlite3VdbeAddOp1(v, OP_If, regTemp); VdbeCoverage(v);
  101890. j3 = sqlite3VdbeAddOp4Int(v, OP_SeekGT, iIdxCur, 0, regPrev, 1);
  101891. VdbeCoverage(v);
  101892. sqlite3VdbeJumpHere(v, j1);
  101893. sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, addrNextRow); VdbeCoverage(v);
  101894. sqlite3VdbeJumpHere(v, j2);
  101895. sqlite3VdbeJumpHere(v, j3);
  101896. }else{
  101897. sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, addrNextRow); VdbeCoverage(v);
  101898. }
  101899. }
  101900. /* Add the entry to the stat1 table. */
  101901. callStatGet(pParse, regStat, STAT_GET_STAT1, regStat1);
  101902. assert( "BBB"[0]==SQLITE_AFF_TEXT );
  101903. sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "BBB", 0);
  101904. sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
  101905. sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
  101906. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  101907. sqlite3VdbeChangeP4(v, -1, (char*)pStat1, P4_TABLE);
  101908. #endif
  101909. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  101910. /* Add the entries to the stat4 table. */
  101911. #ifdef SQLITE_ENABLE_STAT4
  101912. if( OptimizationEnabled(db, SQLITE_Stat4) && db->nAnalysisLimit==0 ){
  101913. int regEq = regStat1;
  101914. int regLt = regStat1+1;
  101915. int regDLt = regStat1+2;
  101916. int regSample = regStat1+3;
  101917. int regCol = regStat1+4;
  101918. int regSampleRowid = regCol + nCol;
  101919. int addrNext;
  101920. int addrIsNull;
  101921. u8 seekOp = HasRowid(pTab) ? OP_NotExists : OP_NotFound;
  101922. pParse->nMem = MAX(pParse->nMem, regCol+nCol);
  101923. addrNext = sqlite3VdbeCurrentAddr(v);
  101924. callStatGet(pParse, regStat, STAT_GET_ROWID, regSampleRowid);
  101925. addrIsNull = sqlite3VdbeAddOp1(v, OP_IsNull, regSampleRowid);
  101926. VdbeCoverage(v);
  101927. callStatGet(pParse, regStat, STAT_GET_NEQ, regEq);
  101928. callStatGet(pParse, regStat, STAT_GET_NLT, regLt);
  101929. callStatGet(pParse, regStat, STAT_GET_NDLT, regDLt);
  101930. sqlite3VdbeAddOp4Int(v, seekOp, iTabCur, addrNext, regSampleRowid, 0);
  101931. VdbeCoverage(v);
  101932. for(i=0; i<nCol; i++){
  101933. sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iTabCur, i, regCol+i);
  101934. }
  101935. sqlite3VdbeAddOp3(v, OP_MakeRecord, regCol, nCol, regSample);
  101936. sqlite3VdbeAddOp3(v, OP_MakeRecord, regTabname, 6, regTemp);
  101937. sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regNewRowid);
  101938. sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regTemp, regNewRowid);
  101939. sqlite3VdbeAddOp2(v, OP_Goto, 1, addrNext); /* P1==1 for end-of-loop */
  101940. sqlite3VdbeJumpHere(v, addrIsNull);
  101941. }
  101942. #endif /* SQLITE_ENABLE_STAT4 */
  101943. /* End of analysis */
  101944. sqlite3VdbeJumpHere(v, addrRewind);
  101945. }
  101946. /* Create a single sqlite_stat1 entry containing NULL as the index
  101947. ** name and the row count as the content.
  101948. */
  101949. if( pOnlyIdx==0 && needTableCnt ){
  101950. VdbeComment((v, "%s", pTab->zName));
  101951. sqlite3VdbeAddOp2(v, OP_Count, iTabCur, regStat1);
  101952. jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, regStat1); VdbeCoverage(v);
  101953. sqlite3VdbeAddOp2(v, OP_Null, 0, regIdxname);
  101954. assert( "BBB"[0]==SQLITE_AFF_TEXT );
  101955. sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "BBB", 0);
  101956. sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
  101957. sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
  101958. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  101959. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  101960. sqlite3VdbeChangeP4(v, -1, (char*)pStat1, P4_TABLE);
  101961. #endif
  101962. sqlite3VdbeJumpHere(v, jZeroRows);
  101963. }
  101964. }
  101965. /*
  101966. ** Generate code that will cause the most recent index analysis to
  101967. ** be loaded into internal hash tables where is can be used.
  101968. */
  101969. static void loadAnalysis(Parse *pParse, int iDb){
  101970. Vdbe *v = sqlite3GetVdbe(pParse);
  101971. if( v ){
  101972. sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
  101973. }
  101974. }
  101975. /*
  101976. ** Generate code that will do an analysis of an entire database
  101977. */
  101978. static void analyzeDatabase(Parse *pParse, int iDb){
  101979. sqlite3 *db = pParse->db;
  101980. Schema *pSchema = db->aDb[iDb].pSchema; /* Schema of database iDb */
  101981. HashElem *k;
  101982. int iStatCur;
  101983. int iMem;
  101984. int iTab;
  101985. sqlite3BeginWriteOperation(pParse, 0, iDb);
  101986. iStatCur = pParse->nTab;
  101987. pParse->nTab += 3;
  101988. openStatTable(pParse, iDb, iStatCur, 0, 0);
  101989. iMem = pParse->nMem+1;
  101990. iTab = pParse->nTab;
  101991. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  101992. for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
  101993. Table *pTab = (Table*)sqliteHashData(k);
  101994. analyzeOneTable(pParse, pTab, 0, iStatCur, iMem, iTab);
  101995. }
  101996. loadAnalysis(pParse, iDb);
  101997. }
  101998. /*
  101999. ** Generate code that will do an analysis of a single table in
  102000. ** a database. If pOnlyIdx is not NULL then it is a single index
  102001. ** in pTab that should be analyzed.
  102002. */
  102003. static void analyzeTable(Parse *pParse, Table *pTab, Index *pOnlyIdx){
  102004. int iDb;
  102005. int iStatCur;
  102006. assert( pTab!=0 );
  102007. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  102008. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  102009. sqlite3BeginWriteOperation(pParse, 0, iDb);
  102010. iStatCur = pParse->nTab;
  102011. pParse->nTab += 3;
  102012. if( pOnlyIdx ){
  102013. openStatTable(pParse, iDb, iStatCur, pOnlyIdx->zName, "idx");
  102014. }else{
  102015. openStatTable(pParse, iDb, iStatCur, pTab->zName, "tbl");
  102016. }
  102017. analyzeOneTable(pParse, pTab, pOnlyIdx, iStatCur,pParse->nMem+1,pParse->nTab);
  102018. loadAnalysis(pParse, iDb);
  102019. }
  102020. /*
  102021. ** Generate code for the ANALYZE command. The parser calls this routine
  102022. ** when it recognizes an ANALYZE command.
  102023. **
  102024. ** ANALYZE -- 1
  102025. ** ANALYZE <database> -- 2
  102026. ** ANALYZE ?<database>.?<tablename> -- 3
  102027. **
  102028. ** Form 1 causes all indices in all attached databases to be analyzed.
  102029. ** Form 2 analyzes all indices the single database named.
  102030. ** Form 3 analyzes all indices associated with the named table.
  102031. */
  102032. SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
  102033. sqlite3 *db = pParse->db;
  102034. int iDb;
  102035. int i;
  102036. char *z, *zDb;
  102037. Table *pTab;
  102038. Index *pIdx;
  102039. Token *pTableName;
  102040. Vdbe *v;
  102041. /* Read the database schema. If an error occurs, leave an error message
  102042. ** and code in pParse and return NULL. */
  102043. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  102044. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  102045. return;
  102046. }
  102047. assert( pName2!=0 || pName1==0 );
  102048. if( pName1==0 ){
  102049. /* Form 1: Analyze everything */
  102050. for(i=0; i<db->nDb; i++){
  102051. if( i==1 ) continue; /* Do not analyze the TEMP database */
  102052. analyzeDatabase(pParse, i);
  102053. }
  102054. }else if( pName2->n==0 && (iDb = sqlite3FindDb(db, pName1))>=0 ){
  102055. /* Analyze the schema named as the argument */
  102056. analyzeDatabase(pParse, iDb);
  102057. }else{
  102058. /* Form 3: Analyze the table or index named as an argument */
  102059. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
  102060. if( iDb>=0 ){
  102061. zDb = pName2->n ? db->aDb[iDb].zDbSName : 0;
  102062. z = sqlite3NameFromToken(db, pTableName);
  102063. if( z ){
  102064. if( (pIdx = sqlite3FindIndex(db, z, zDb))!=0 ){
  102065. analyzeTable(pParse, pIdx->pTable, pIdx);
  102066. }else if( (pTab = sqlite3LocateTable(pParse, 0, z, zDb))!=0 ){
  102067. analyzeTable(pParse, pTab, 0);
  102068. }
  102069. sqlite3DbFree(db, z);
  102070. }
  102071. }
  102072. }
  102073. if( db->nSqlExec==0 && (v = sqlite3GetVdbe(pParse))!=0 ){
  102074. sqlite3VdbeAddOp0(v, OP_Expire);
  102075. }
  102076. }
  102077. /*
  102078. ** Used to pass information from the analyzer reader through to the
  102079. ** callback routine.
  102080. */
  102081. typedef struct analysisInfo analysisInfo;
  102082. struct analysisInfo {
  102083. sqlite3 *db;
  102084. const char *zDatabase;
  102085. };
  102086. /*
  102087. ** The first argument points to a nul-terminated string containing a
  102088. ** list of space separated integers. Read the first nOut of these into
  102089. ** the array aOut[].
  102090. */
  102091. static void decodeIntArray(
  102092. char *zIntArray, /* String containing int array to decode */
  102093. int nOut, /* Number of slots in aOut[] */
  102094. tRowcnt *aOut, /* Store integers here */
  102095. LogEst *aLog, /* Or, if aOut==0, here */
  102096. Index *pIndex /* Handle extra flags for this index, if not NULL */
  102097. ){
  102098. char *z = zIntArray;
  102099. int c;
  102100. int i;
  102101. tRowcnt v;
  102102. #ifdef SQLITE_ENABLE_STAT4
  102103. if( z==0 ) z = "";
  102104. #else
  102105. assert( z!=0 );
  102106. #endif
  102107. for(i=0; *z && i<nOut; i++){
  102108. v = 0;
  102109. while( (c=z[0])>='0' && c<='9' ){
  102110. v = v*10 + c - '0';
  102111. z++;
  102112. }
  102113. #ifdef SQLITE_ENABLE_STAT4
  102114. if( aOut ) aOut[i] = v;
  102115. if( aLog ) aLog[i] = sqlite3LogEst(v);
  102116. #else
  102117. assert( aOut==0 );
  102118. UNUSED_PARAMETER(aOut);
  102119. assert( aLog!=0 );
  102120. aLog[i] = sqlite3LogEst(v);
  102121. #endif
  102122. if( *z==' ' ) z++;
  102123. }
  102124. #ifndef SQLITE_ENABLE_STAT4
  102125. assert( pIndex!=0 ); {
  102126. #else
  102127. if( pIndex ){
  102128. #endif
  102129. pIndex->bUnordered = 0;
  102130. pIndex->noSkipScan = 0;
  102131. while( z[0] ){
  102132. if( sqlite3_strglob("unordered*", z)==0 ){
  102133. pIndex->bUnordered = 1;
  102134. }else if( sqlite3_strglob("sz=[0-9]*", z)==0 ){
  102135. int sz = sqlite3Atoi(z+3);
  102136. if( sz<2 ) sz = 2;
  102137. pIndex->szIdxRow = sqlite3LogEst(sz);
  102138. }else if( sqlite3_strglob("noskipscan*", z)==0 ){
  102139. pIndex->noSkipScan = 1;
  102140. }
  102141. #ifdef SQLITE_ENABLE_COSTMULT
  102142. else if( sqlite3_strglob("costmult=[0-9]*",z)==0 ){
  102143. pIndex->pTable->costMult = sqlite3LogEst(sqlite3Atoi(z+9));
  102144. }
  102145. #endif
  102146. while( z[0]!=0 && z[0]!=' ' ) z++;
  102147. while( z[0]==' ' ) z++;
  102148. }
  102149. }
  102150. }
  102151. /*
  102152. ** This callback is invoked once for each index when reading the
  102153. ** sqlite_stat1 table.
  102154. **
  102155. ** argv[0] = name of the table
  102156. ** argv[1] = name of the index (might be NULL)
  102157. ** argv[2] = results of analysis - on integer for each column
  102158. **
  102159. ** Entries for which argv[1]==NULL simply record the number of rows in
  102160. ** the table.
  102161. */
  102162. static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
  102163. analysisInfo *pInfo = (analysisInfo*)pData;
  102164. Index *pIndex;
  102165. Table *pTable;
  102166. const char *z;
  102167. assert( argc==3 );
  102168. UNUSED_PARAMETER2(NotUsed, argc);
  102169. if( argv==0 || argv[0]==0 || argv[2]==0 ){
  102170. return 0;
  102171. }
  102172. pTable = sqlite3FindTable(pInfo->db, argv[0], pInfo->zDatabase);
  102173. if( pTable==0 ){
  102174. return 0;
  102175. }
  102176. if( argv[1]==0 ){
  102177. pIndex = 0;
  102178. }else if( sqlite3_stricmp(argv[0],argv[1])==0 ){
  102179. pIndex = sqlite3PrimaryKeyIndex(pTable);
  102180. }else{
  102181. pIndex = sqlite3FindIndex(pInfo->db, argv[1], pInfo->zDatabase);
  102182. }
  102183. z = argv[2];
  102184. if( pIndex ){
  102185. tRowcnt *aiRowEst = 0;
  102186. int nCol = pIndex->nKeyCol+1;
  102187. #ifdef SQLITE_ENABLE_STAT4
  102188. /* Index.aiRowEst may already be set here if there are duplicate
  102189. ** sqlite_stat1 entries for this index. In that case just clobber
  102190. ** the old data with the new instead of allocating a new array. */
  102191. if( pIndex->aiRowEst==0 ){
  102192. pIndex->aiRowEst = (tRowcnt*)sqlite3MallocZero(sizeof(tRowcnt) * nCol);
  102193. if( pIndex->aiRowEst==0 ) sqlite3OomFault(pInfo->db);
  102194. }
  102195. aiRowEst = pIndex->aiRowEst;
  102196. #endif
  102197. pIndex->bUnordered = 0;
  102198. decodeIntArray((char*)z, nCol, aiRowEst, pIndex->aiRowLogEst, pIndex);
  102199. pIndex->hasStat1 = 1;
  102200. if( pIndex->pPartIdxWhere==0 ){
  102201. pTable->nRowLogEst = pIndex->aiRowLogEst[0];
  102202. pTable->tabFlags |= TF_HasStat1;
  102203. }
  102204. }else{
  102205. Index fakeIdx;
  102206. fakeIdx.szIdxRow = pTable->szTabRow;
  102207. #ifdef SQLITE_ENABLE_COSTMULT
  102208. fakeIdx.pTable = pTable;
  102209. #endif
  102210. decodeIntArray((char*)z, 1, 0, &pTable->nRowLogEst, &fakeIdx);
  102211. pTable->szTabRow = fakeIdx.szIdxRow;
  102212. pTable->tabFlags |= TF_HasStat1;
  102213. }
  102214. return 0;
  102215. }
  102216. /*
  102217. ** If the Index.aSample variable is not NULL, delete the aSample[] array
  102218. ** and its contents.
  102219. */
  102220. SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3 *db, Index *pIdx){
  102221. #ifdef SQLITE_ENABLE_STAT4
  102222. if( pIdx->aSample ){
  102223. int j;
  102224. for(j=0; j<pIdx->nSample; j++){
  102225. IndexSample *p = &pIdx->aSample[j];
  102226. sqlite3DbFree(db, p->p);
  102227. }
  102228. sqlite3DbFree(db, pIdx->aSample);
  102229. }
  102230. if( db && db->pnBytesFreed==0 ){
  102231. pIdx->nSample = 0;
  102232. pIdx->aSample = 0;
  102233. }
  102234. #else
  102235. UNUSED_PARAMETER(db);
  102236. UNUSED_PARAMETER(pIdx);
  102237. #endif /* SQLITE_ENABLE_STAT4 */
  102238. }
  102239. #ifdef SQLITE_ENABLE_STAT4
  102240. /*
  102241. ** Populate the pIdx->aAvgEq[] array based on the samples currently
  102242. ** stored in pIdx->aSample[].
  102243. */
  102244. static void initAvgEq(Index *pIdx){
  102245. if( pIdx ){
  102246. IndexSample *aSample = pIdx->aSample;
  102247. IndexSample *pFinal = &aSample[pIdx->nSample-1];
  102248. int iCol;
  102249. int nCol = 1;
  102250. if( pIdx->nSampleCol>1 ){
  102251. /* If this is stat4 data, then calculate aAvgEq[] values for all
  102252. ** sample columns except the last. The last is always set to 1, as
  102253. ** once the trailing PK fields are considered all index keys are
  102254. ** unique. */
  102255. nCol = pIdx->nSampleCol-1;
  102256. pIdx->aAvgEq[nCol] = 1;
  102257. }
  102258. for(iCol=0; iCol<nCol; iCol++){
  102259. int nSample = pIdx->nSample;
  102260. int i; /* Used to iterate through samples */
  102261. tRowcnt sumEq = 0; /* Sum of the nEq values */
  102262. tRowcnt avgEq = 0;
  102263. tRowcnt nRow; /* Number of rows in index */
  102264. i64 nSum100 = 0; /* Number of terms contributing to sumEq */
  102265. i64 nDist100; /* Number of distinct values in index */
  102266. if( !pIdx->aiRowEst || iCol>=pIdx->nKeyCol || pIdx->aiRowEst[iCol+1]==0 ){
  102267. nRow = pFinal->anLt[iCol];
  102268. nDist100 = (i64)100 * pFinal->anDLt[iCol];
  102269. nSample--;
  102270. }else{
  102271. nRow = pIdx->aiRowEst[0];
  102272. nDist100 = ((i64)100 * pIdx->aiRowEst[0]) / pIdx->aiRowEst[iCol+1];
  102273. }
  102274. pIdx->nRowEst0 = nRow;
  102275. /* Set nSum to the number of distinct (iCol+1) field prefixes that
  102276. ** occur in the stat4 table for this index. Set sumEq to the sum of
  102277. ** the nEq values for column iCol for the same set (adding the value
  102278. ** only once where there exist duplicate prefixes). */
  102279. for(i=0; i<nSample; i++){
  102280. if( i==(pIdx->nSample-1)
  102281. || aSample[i].anDLt[iCol]!=aSample[i+1].anDLt[iCol]
  102282. ){
  102283. sumEq += aSample[i].anEq[iCol];
  102284. nSum100 += 100;
  102285. }
  102286. }
  102287. if( nDist100>nSum100 && sumEq<nRow ){
  102288. avgEq = ((i64)100 * (nRow - sumEq))/(nDist100 - nSum100);
  102289. }
  102290. if( avgEq==0 ) avgEq = 1;
  102291. pIdx->aAvgEq[iCol] = avgEq;
  102292. }
  102293. }
  102294. }
  102295. /*
  102296. ** Look up an index by name. Or, if the name of a WITHOUT ROWID table
  102297. ** is supplied instead, find the PRIMARY KEY index for that table.
  102298. */
  102299. static Index *findIndexOrPrimaryKey(
  102300. sqlite3 *db,
  102301. const char *zName,
  102302. const char *zDb
  102303. ){
  102304. Index *pIdx = sqlite3FindIndex(db, zName, zDb);
  102305. if( pIdx==0 ){
  102306. Table *pTab = sqlite3FindTable(db, zName, zDb);
  102307. if( pTab && !HasRowid(pTab) ) pIdx = sqlite3PrimaryKeyIndex(pTab);
  102308. }
  102309. return pIdx;
  102310. }
  102311. /*
  102312. ** Load the content from either the sqlite_stat4
  102313. ** into the relevant Index.aSample[] arrays.
  102314. **
  102315. ** Arguments zSql1 and zSql2 must point to SQL statements that return
  102316. ** data equivalent to the following:
  102317. **
  102318. ** zSql1: SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx
  102319. ** zSql2: SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4
  102320. **
  102321. ** where %Q is replaced with the database name before the SQL is executed.
  102322. */
  102323. static int loadStatTbl(
  102324. sqlite3 *db, /* Database handle */
  102325. const char *zSql1, /* SQL statement 1 (see above) */
  102326. const char *zSql2, /* SQL statement 2 (see above) */
  102327. const char *zDb /* Database name (e.g. "main") */
  102328. ){
  102329. int rc; /* Result codes from subroutines */
  102330. sqlite3_stmt *pStmt = 0; /* An SQL statement being run */
  102331. char *zSql; /* Text of the SQL statement */
  102332. Index *pPrevIdx = 0; /* Previous index in the loop */
  102333. IndexSample *pSample; /* A slot in pIdx->aSample[] */
  102334. assert( db->lookaside.bDisable );
  102335. zSql = sqlite3MPrintf(db, zSql1, zDb);
  102336. if( !zSql ){
  102337. return SQLITE_NOMEM_BKPT;
  102338. }
  102339. rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
  102340. sqlite3DbFree(db, zSql);
  102341. if( rc ) return rc;
  102342. while( sqlite3_step(pStmt)==SQLITE_ROW ){
  102343. int nIdxCol = 1; /* Number of columns in stat4 records */
  102344. char *zIndex; /* Index name */
  102345. Index *pIdx; /* Pointer to the index object */
  102346. int nSample; /* Number of samples */
  102347. int nByte; /* Bytes of space required */
  102348. int i; /* Bytes of space required */
  102349. tRowcnt *pSpace;
  102350. zIndex = (char *)sqlite3_column_text(pStmt, 0);
  102351. if( zIndex==0 ) continue;
  102352. nSample = sqlite3_column_int(pStmt, 1);
  102353. pIdx = findIndexOrPrimaryKey(db, zIndex, zDb);
  102354. assert( pIdx==0 || pIdx->nSample==0 );
  102355. if( pIdx==0 ) continue;
  102356. assert( !HasRowid(pIdx->pTable) || pIdx->nColumn==pIdx->nKeyCol+1 );
  102357. if( !HasRowid(pIdx->pTable) && IsPrimaryKeyIndex(pIdx) ){
  102358. nIdxCol = pIdx->nKeyCol;
  102359. }else{
  102360. nIdxCol = pIdx->nColumn;
  102361. }
  102362. pIdx->nSampleCol = nIdxCol;
  102363. nByte = sizeof(IndexSample) * nSample;
  102364. nByte += sizeof(tRowcnt) * nIdxCol * 3 * nSample;
  102365. nByte += nIdxCol * sizeof(tRowcnt); /* Space for Index.aAvgEq[] */
  102366. pIdx->aSample = sqlite3DbMallocZero(db, nByte);
  102367. if( pIdx->aSample==0 ){
  102368. sqlite3_finalize(pStmt);
  102369. return SQLITE_NOMEM_BKPT;
  102370. }
  102371. pSpace = (tRowcnt*)&pIdx->aSample[nSample];
  102372. pIdx->aAvgEq = pSpace; pSpace += nIdxCol;
  102373. for(i=0; i<nSample; i++){
  102374. pIdx->aSample[i].anEq = pSpace; pSpace += nIdxCol;
  102375. pIdx->aSample[i].anLt = pSpace; pSpace += nIdxCol;
  102376. pIdx->aSample[i].anDLt = pSpace; pSpace += nIdxCol;
  102377. }
  102378. assert( ((u8*)pSpace)-nByte==(u8*)(pIdx->aSample) );
  102379. }
  102380. rc = sqlite3_finalize(pStmt);
  102381. if( rc ) return rc;
  102382. zSql = sqlite3MPrintf(db, zSql2, zDb);
  102383. if( !zSql ){
  102384. return SQLITE_NOMEM_BKPT;
  102385. }
  102386. rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
  102387. sqlite3DbFree(db, zSql);
  102388. if( rc ) return rc;
  102389. while( sqlite3_step(pStmt)==SQLITE_ROW ){
  102390. char *zIndex; /* Index name */
  102391. Index *pIdx; /* Pointer to the index object */
  102392. int nCol = 1; /* Number of columns in index */
  102393. zIndex = (char *)sqlite3_column_text(pStmt, 0);
  102394. if( zIndex==0 ) continue;
  102395. pIdx = findIndexOrPrimaryKey(db, zIndex, zDb);
  102396. if( pIdx==0 ) continue;
  102397. /* This next condition is true if data has already been loaded from
  102398. ** the sqlite_stat4 table. */
  102399. nCol = pIdx->nSampleCol;
  102400. if( pIdx!=pPrevIdx ){
  102401. initAvgEq(pPrevIdx);
  102402. pPrevIdx = pIdx;
  102403. }
  102404. pSample = &pIdx->aSample[pIdx->nSample];
  102405. decodeIntArray((char*)sqlite3_column_text(pStmt,1),nCol,pSample->anEq,0,0);
  102406. decodeIntArray((char*)sqlite3_column_text(pStmt,2),nCol,pSample->anLt,0,0);
  102407. decodeIntArray((char*)sqlite3_column_text(pStmt,3),nCol,pSample->anDLt,0,0);
  102408. /* Take a copy of the sample. Add two 0x00 bytes the end of the buffer.
  102409. ** This is in case the sample record is corrupted. In that case, the
  102410. ** sqlite3VdbeRecordCompare() may read up to two varints past the
  102411. ** end of the allocated buffer before it realizes it is dealing with
  102412. ** a corrupt record. Adding the two 0x00 bytes prevents this from causing
  102413. ** a buffer overread. */
  102414. pSample->n = sqlite3_column_bytes(pStmt, 4);
  102415. pSample->p = sqlite3DbMallocZero(db, pSample->n + 2);
  102416. if( pSample->p==0 ){
  102417. sqlite3_finalize(pStmt);
  102418. return SQLITE_NOMEM_BKPT;
  102419. }
  102420. if( pSample->n ){
  102421. memcpy(pSample->p, sqlite3_column_blob(pStmt, 4), pSample->n);
  102422. }
  102423. pIdx->nSample++;
  102424. }
  102425. rc = sqlite3_finalize(pStmt);
  102426. if( rc==SQLITE_OK ) initAvgEq(pPrevIdx);
  102427. return rc;
  102428. }
  102429. /*
  102430. ** Load content from the sqlite_stat4 table into
  102431. ** the Index.aSample[] arrays of all indices.
  102432. */
  102433. static int loadStat4(sqlite3 *db, const char *zDb){
  102434. int rc = SQLITE_OK; /* Result codes from subroutines */
  102435. assert( db->lookaside.bDisable );
  102436. if( sqlite3FindTable(db, "sqlite_stat4", zDb) ){
  102437. rc = loadStatTbl(db,
  102438. "SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx",
  102439. "SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4",
  102440. zDb
  102441. );
  102442. }
  102443. return rc;
  102444. }
  102445. #endif /* SQLITE_ENABLE_STAT4 */
  102446. /*
  102447. ** Load the content of the sqlite_stat1 and sqlite_stat4 tables. The
  102448. ** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]
  102449. ** arrays. The contents of sqlite_stat4 are used to populate the
  102450. ** Index.aSample[] arrays.
  102451. **
  102452. ** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR
  102453. ** is returned. In this case, even if SQLITE_ENABLE_STAT4 was defined
  102454. ** during compilation and the sqlite_stat4 table is present, no data is
  102455. ** read from it.
  102456. **
  102457. ** If SQLITE_ENABLE_STAT4 was defined during compilation and the
  102458. ** sqlite_stat4 table is not present in the database, SQLITE_ERROR is
  102459. ** returned. However, in this case, data is read from the sqlite_stat1
  102460. ** table (if it is present) before returning.
  102461. **
  102462. ** If an OOM error occurs, this function always sets db->mallocFailed.
  102463. ** This means if the caller does not care about other errors, the return
  102464. ** code may be ignored.
  102465. */
  102466. SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
  102467. analysisInfo sInfo;
  102468. HashElem *i;
  102469. char *zSql;
  102470. int rc = SQLITE_OK;
  102471. Schema *pSchema = db->aDb[iDb].pSchema;
  102472. assert( iDb>=0 && iDb<db->nDb );
  102473. assert( db->aDb[iDb].pBt!=0 );
  102474. /* Clear any prior statistics */
  102475. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  102476. for(i=sqliteHashFirst(&pSchema->tblHash); i; i=sqliteHashNext(i)){
  102477. Table *pTab = sqliteHashData(i);
  102478. pTab->tabFlags &= ~TF_HasStat1;
  102479. }
  102480. for(i=sqliteHashFirst(&pSchema->idxHash); i; i=sqliteHashNext(i)){
  102481. Index *pIdx = sqliteHashData(i);
  102482. pIdx->hasStat1 = 0;
  102483. #ifdef SQLITE_ENABLE_STAT4
  102484. sqlite3DeleteIndexSamples(db, pIdx);
  102485. pIdx->aSample = 0;
  102486. #endif
  102487. }
  102488. /* Load new statistics out of the sqlite_stat1 table */
  102489. sInfo.db = db;
  102490. sInfo.zDatabase = db->aDb[iDb].zDbSName;
  102491. if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)!=0 ){
  102492. zSql = sqlite3MPrintf(db,
  102493. "SELECT tbl,idx,stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
  102494. if( zSql==0 ){
  102495. rc = SQLITE_NOMEM_BKPT;
  102496. }else{
  102497. rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
  102498. sqlite3DbFree(db, zSql);
  102499. }
  102500. }
  102501. /* Set appropriate defaults on all indexes not in the sqlite_stat1 table */
  102502. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  102503. for(i=sqliteHashFirst(&pSchema->idxHash); i; i=sqliteHashNext(i)){
  102504. Index *pIdx = sqliteHashData(i);
  102505. if( !pIdx->hasStat1 ) sqlite3DefaultRowEst(pIdx);
  102506. }
  102507. /* Load the statistics from the sqlite_stat4 table. */
  102508. #ifdef SQLITE_ENABLE_STAT4
  102509. if( rc==SQLITE_OK ){
  102510. DisableLookaside;
  102511. rc = loadStat4(db, sInfo.zDatabase);
  102512. EnableLookaside;
  102513. }
  102514. for(i=sqliteHashFirst(&pSchema->idxHash); i; i=sqliteHashNext(i)){
  102515. Index *pIdx = sqliteHashData(i);
  102516. sqlite3_free(pIdx->aiRowEst);
  102517. pIdx->aiRowEst = 0;
  102518. }
  102519. #endif
  102520. if( rc==SQLITE_NOMEM ){
  102521. sqlite3OomFault(db);
  102522. }
  102523. return rc;
  102524. }
  102525. #endif /* SQLITE_OMIT_ANALYZE */
  102526. /************** End of analyze.c *********************************************/
  102527. /************** Begin file attach.c ******************************************/
  102528. /*
  102529. ** 2003 April 6
  102530. **
  102531. ** The author disclaims copyright to this source code. In place of
  102532. ** a legal notice, here is a blessing:
  102533. **
  102534. ** May you do good and not evil.
  102535. ** May you find forgiveness for yourself and forgive others.
  102536. ** May you share freely, never taking more than you give.
  102537. **
  102538. *************************************************************************
  102539. ** This file contains code used to implement the ATTACH and DETACH commands.
  102540. */
  102541. /* #include "sqliteInt.h" */
  102542. #ifndef SQLITE_OMIT_ATTACH
  102543. /*
  102544. ** Resolve an expression that was part of an ATTACH or DETACH statement. This
  102545. ** is slightly different from resolving a normal SQL expression, because simple
  102546. ** identifiers are treated as strings, not possible column names or aliases.
  102547. **
  102548. ** i.e. if the parser sees:
  102549. **
  102550. ** ATTACH DATABASE abc AS def
  102551. **
  102552. ** it treats the two expressions as literal strings 'abc' and 'def' instead of
  102553. ** looking for columns of the same name.
  102554. **
  102555. ** This only applies to the root node of pExpr, so the statement:
  102556. **
  102557. ** ATTACH DATABASE abc||def AS 'db2'
  102558. **
  102559. ** will fail because neither abc or def can be resolved.
  102560. */
  102561. static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
  102562. {
  102563. int rc = SQLITE_OK;
  102564. if( pExpr ){
  102565. if( pExpr->op!=TK_ID ){
  102566. rc = sqlite3ResolveExprNames(pName, pExpr);
  102567. }else{
  102568. pExpr->op = TK_STRING;
  102569. }
  102570. }
  102571. return rc;
  102572. }
  102573. /*
  102574. ** Return true if zName points to a name that may be used to refer to
  102575. ** database iDb attached to handle db.
  102576. */
  102577. SQLITE_PRIVATE int sqlite3DbIsNamed(sqlite3 *db, int iDb, const char *zName){
  102578. return (
  102579. sqlite3StrICmp(db->aDb[iDb].zDbSName, zName)==0
  102580. || (iDb==0 && sqlite3StrICmp("main", zName)==0)
  102581. );
  102582. }
  102583. /*
  102584. ** An SQL user-function registered to do the work of an ATTACH statement. The
  102585. ** three arguments to the function come directly from an attach statement:
  102586. **
  102587. ** ATTACH DATABASE x AS y KEY z
  102588. **
  102589. ** SELECT sqlite_attach(x, y, z)
  102590. **
  102591. ** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
  102592. ** third argument.
  102593. **
  102594. ** If the db->init.reopenMemdb flags is set, then instead of attaching a
  102595. ** new database, close the database on db->init.iDb and reopen it as an
  102596. ** empty MemDB.
  102597. */
  102598. static void attachFunc(
  102599. sqlite3_context *context,
  102600. int NotUsed,
  102601. sqlite3_value **argv
  102602. ){
  102603. int i;
  102604. int rc = 0;
  102605. sqlite3 *db = sqlite3_context_db_handle(context);
  102606. const char *zName;
  102607. const char *zFile;
  102608. char *zPath = 0;
  102609. char *zErr = 0;
  102610. unsigned int flags;
  102611. Db *aNew; /* New array of Db pointers */
  102612. Db *pNew; /* Db object for the newly attached database */
  102613. char *zErrDyn = 0;
  102614. sqlite3_vfs *pVfs;
  102615. UNUSED_PARAMETER(NotUsed);
  102616. zFile = (const char *)sqlite3_value_text(argv[0]);
  102617. zName = (const char *)sqlite3_value_text(argv[1]);
  102618. if( zFile==0 ) zFile = "";
  102619. if( zName==0 ) zName = "";
  102620. #ifdef SQLITE_ENABLE_DESERIALIZE
  102621. # define REOPEN_AS_MEMDB(db) (db->init.reopenMemdb)
  102622. #else
  102623. # define REOPEN_AS_MEMDB(db) (0)
  102624. #endif
  102625. if( REOPEN_AS_MEMDB(db) ){
  102626. /* This is not a real ATTACH. Instead, this routine is being called
  102627. ** from sqlite3_deserialize() to close database db->init.iDb and
  102628. ** reopen it as a MemDB */
  102629. pVfs = sqlite3_vfs_find("memdb");
  102630. if( pVfs==0 ) return;
  102631. pNew = &db->aDb[db->init.iDb];
  102632. if( pNew->pBt ) sqlite3BtreeClose(pNew->pBt);
  102633. pNew->pBt = 0;
  102634. pNew->pSchema = 0;
  102635. rc = sqlite3BtreeOpen(pVfs, "x\0", db, &pNew->pBt, 0, SQLITE_OPEN_MAIN_DB);
  102636. }else{
  102637. /* This is a real ATTACH
  102638. **
  102639. ** Check for the following errors:
  102640. **
  102641. ** * Too many attached databases,
  102642. ** * Transaction currently open
  102643. ** * Specified database name already being used.
  102644. */
  102645. if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
  102646. zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d",
  102647. db->aLimit[SQLITE_LIMIT_ATTACHED]
  102648. );
  102649. goto attach_error;
  102650. }
  102651. for(i=0; i<db->nDb; i++){
  102652. assert( zName );
  102653. if( sqlite3DbIsNamed(db, i, zName) ){
  102654. zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName);
  102655. goto attach_error;
  102656. }
  102657. }
  102658. /* Allocate the new entry in the db->aDb[] array and initialize the schema
  102659. ** hash tables.
  102660. */
  102661. if( db->aDb==db->aDbStatic ){
  102662. aNew = sqlite3DbMallocRawNN(db, sizeof(db->aDb[0])*3 );
  102663. if( aNew==0 ) return;
  102664. memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
  102665. }else{
  102666. aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
  102667. if( aNew==0 ) return;
  102668. }
  102669. db->aDb = aNew;
  102670. pNew = &db->aDb[db->nDb];
  102671. memset(pNew, 0, sizeof(*pNew));
  102672. /* Open the database file. If the btree is successfully opened, use
  102673. ** it to obtain the database schema. At this point the schema may
  102674. ** or may not be initialized.
  102675. */
  102676. flags = db->openFlags;
  102677. rc = sqlite3ParseUri(db->pVfs->zName, zFile, &flags, &pVfs, &zPath, &zErr);
  102678. if( rc!=SQLITE_OK ){
  102679. if( rc==SQLITE_NOMEM ) sqlite3OomFault(db);
  102680. sqlite3_result_error(context, zErr, -1);
  102681. sqlite3_free(zErr);
  102682. return;
  102683. }
  102684. assert( pVfs );
  102685. flags |= SQLITE_OPEN_MAIN_DB;
  102686. rc = sqlite3BtreeOpen(pVfs, zPath, db, &pNew->pBt, 0, flags);
  102687. db->nDb++;
  102688. pNew->zDbSName = sqlite3DbStrDup(db, zName);
  102689. }
  102690. db->noSharedCache = 0;
  102691. if( rc==SQLITE_CONSTRAINT ){
  102692. rc = SQLITE_ERROR;
  102693. zErrDyn = sqlite3MPrintf(db, "database is already attached");
  102694. }else if( rc==SQLITE_OK ){
  102695. Pager *pPager;
  102696. pNew->pSchema = sqlite3SchemaGet(db, pNew->pBt);
  102697. if( !pNew->pSchema ){
  102698. rc = SQLITE_NOMEM_BKPT;
  102699. }else if( pNew->pSchema->file_format && pNew->pSchema->enc!=ENC(db) ){
  102700. zErrDyn = sqlite3MPrintf(db,
  102701. "attached databases must use the same text encoding as main database");
  102702. rc = SQLITE_ERROR;
  102703. }
  102704. sqlite3BtreeEnter(pNew->pBt);
  102705. pPager = sqlite3BtreePager(pNew->pBt);
  102706. sqlite3PagerLockingMode(pPager, db->dfltLockMode);
  102707. sqlite3BtreeSecureDelete(pNew->pBt,
  102708. sqlite3BtreeSecureDelete(db->aDb[0].pBt,-1) );
  102709. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  102710. sqlite3BtreeSetPagerFlags(pNew->pBt,
  102711. PAGER_SYNCHRONOUS_FULL | (db->flags & PAGER_FLAGS_MASK));
  102712. #endif
  102713. sqlite3BtreeLeave(pNew->pBt);
  102714. }
  102715. pNew->safety_level = SQLITE_DEFAULT_SYNCHRONOUS+1;
  102716. if( rc==SQLITE_OK && pNew->zDbSName==0 ){
  102717. rc = SQLITE_NOMEM_BKPT;
  102718. }
  102719. sqlite3_free_filename( zPath );
  102720. /* If the file was opened successfully, read the schema for the new database.
  102721. ** If this fails, or if opening the file failed, then close the file and
  102722. ** remove the entry from the db->aDb[] array. i.e. put everything back the
  102723. ** way we found it.
  102724. */
  102725. if( rc==SQLITE_OK ){
  102726. sqlite3BtreeEnterAll(db);
  102727. db->init.iDb = 0;
  102728. db->mDbFlags &= ~(DBFLAG_SchemaKnownOk);
  102729. if( !REOPEN_AS_MEMDB(db) ){
  102730. rc = sqlite3Init(db, &zErrDyn);
  102731. }
  102732. sqlite3BtreeLeaveAll(db);
  102733. assert( zErrDyn==0 || rc!=SQLITE_OK );
  102734. }
  102735. #ifdef SQLITE_USER_AUTHENTICATION
  102736. if( rc==SQLITE_OK && !REOPEN_AS_MEMDB(db) ){
  102737. u8 newAuth = 0;
  102738. rc = sqlite3UserAuthCheckLogin(db, zName, &newAuth);
  102739. if( newAuth<db->auth.authLevel ){
  102740. rc = SQLITE_AUTH_USER;
  102741. }
  102742. }
  102743. #endif
  102744. if( rc ){
  102745. if( !REOPEN_AS_MEMDB(db) ){
  102746. int iDb = db->nDb - 1;
  102747. assert( iDb>=2 );
  102748. if( db->aDb[iDb].pBt ){
  102749. sqlite3BtreeClose(db->aDb[iDb].pBt);
  102750. db->aDb[iDb].pBt = 0;
  102751. db->aDb[iDb].pSchema = 0;
  102752. }
  102753. sqlite3ResetAllSchemasOfConnection(db);
  102754. db->nDb = iDb;
  102755. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
  102756. sqlite3OomFault(db);
  102757. sqlite3DbFree(db, zErrDyn);
  102758. zErrDyn = sqlite3MPrintf(db, "out of memory");
  102759. }else if( zErrDyn==0 ){
  102760. zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile);
  102761. }
  102762. }
  102763. goto attach_error;
  102764. }
  102765. return;
  102766. attach_error:
  102767. /* Return an error if we get here */
  102768. if( zErrDyn ){
  102769. sqlite3_result_error(context, zErrDyn, -1);
  102770. sqlite3DbFree(db, zErrDyn);
  102771. }
  102772. if( rc ) sqlite3_result_error_code(context, rc);
  102773. }
  102774. /*
  102775. ** An SQL user-function registered to do the work of an DETACH statement. The
  102776. ** three arguments to the function come directly from a detach statement:
  102777. **
  102778. ** DETACH DATABASE x
  102779. **
  102780. ** SELECT sqlite_detach(x)
  102781. */
  102782. static void detachFunc(
  102783. sqlite3_context *context,
  102784. int NotUsed,
  102785. sqlite3_value **argv
  102786. ){
  102787. const char *zName = (const char *)sqlite3_value_text(argv[0]);
  102788. sqlite3 *db = sqlite3_context_db_handle(context);
  102789. int i;
  102790. Db *pDb = 0;
  102791. HashElem *pEntry;
  102792. char zErr[128];
  102793. UNUSED_PARAMETER(NotUsed);
  102794. if( zName==0 ) zName = "";
  102795. for(i=0; i<db->nDb; i++){
  102796. pDb = &db->aDb[i];
  102797. if( pDb->pBt==0 ) continue;
  102798. if( sqlite3DbIsNamed(db, i, zName) ) break;
  102799. }
  102800. if( i>=db->nDb ){
  102801. sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
  102802. goto detach_error;
  102803. }
  102804. if( i<2 ){
  102805. sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
  102806. goto detach_error;
  102807. }
  102808. if( sqlite3BtreeIsInReadTrans(pDb->pBt) || sqlite3BtreeIsInBackup(pDb->pBt) ){
  102809. sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
  102810. goto detach_error;
  102811. }
  102812. /* If any TEMP triggers reference the schema being detached, move those
  102813. ** triggers to reference the TEMP schema itself. */
  102814. assert( db->aDb[1].pSchema );
  102815. pEntry = sqliteHashFirst(&db->aDb[1].pSchema->trigHash);
  102816. while( pEntry ){
  102817. Trigger *pTrig = (Trigger*)sqliteHashData(pEntry);
  102818. if( pTrig->pTabSchema==pDb->pSchema ){
  102819. pTrig->pTabSchema = pTrig->pSchema;
  102820. }
  102821. pEntry = sqliteHashNext(pEntry);
  102822. }
  102823. sqlite3BtreeClose(pDb->pBt);
  102824. pDb->pBt = 0;
  102825. pDb->pSchema = 0;
  102826. sqlite3CollapseDatabaseArray(db);
  102827. return;
  102828. detach_error:
  102829. sqlite3_result_error(context, zErr, -1);
  102830. }
  102831. /*
  102832. ** This procedure generates VDBE code for a single invocation of either the
  102833. ** sqlite_detach() or sqlite_attach() SQL user functions.
  102834. */
  102835. static void codeAttach(
  102836. Parse *pParse, /* The parser context */
  102837. int type, /* Either SQLITE_ATTACH or SQLITE_DETACH */
  102838. FuncDef const *pFunc,/* FuncDef wrapper for detachFunc() or attachFunc() */
  102839. Expr *pAuthArg, /* Expression to pass to authorization callback */
  102840. Expr *pFilename, /* Name of database file */
  102841. Expr *pDbname, /* Name of the database to use internally */
  102842. Expr *pKey /* Database key for encryption extension */
  102843. ){
  102844. int rc;
  102845. NameContext sName;
  102846. Vdbe *v;
  102847. sqlite3* db = pParse->db;
  102848. int regArgs;
  102849. if( pParse->nErr ) goto attach_end;
  102850. memset(&sName, 0, sizeof(NameContext));
  102851. sName.pParse = pParse;
  102852. if(
  102853. SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
  102854. SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
  102855. SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
  102856. ){
  102857. goto attach_end;
  102858. }
  102859. #ifndef SQLITE_OMIT_AUTHORIZATION
  102860. if( pAuthArg ){
  102861. char *zAuthArg;
  102862. if( pAuthArg->op==TK_STRING ){
  102863. zAuthArg = pAuthArg->u.zToken;
  102864. }else{
  102865. zAuthArg = 0;
  102866. }
  102867. rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
  102868. if(rc!=SQLITE_OK ){
  102869. goto attach_end;
  102870. }
  102871. }
  102872. #endif /* SQLITE_OMIT_AUTHORIZATION */
  102873. v = sqlite3GetVdbe(pParse);
  102874. regArgs = sqlite3GetTempRange(pParse, 4);
  102875. sqlite3ExprCode(pParse, pFilename, regArgs);
  102876. sqlite3ExprCode(pParse, pDbname, regArgs+1);
  102877. sqlite3ExprCode(pParse, pKey, regArgs+2);
  102878. assert( v || db->mallocFailed );
  102879. if( v ){
  102880. sqlite3VdbeAddFunctionCall(pParse, 0, regArgs+3-pFunc->nArg, regArgs+3,
  102881. pFunc->nArg, pFunc, 0);
  102882. /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
  102883. ** statement only). For DETACH, set it to false (expire all existing
  102884. ** statements).
  102885. */
  102886. sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
  102887. }
  102888. attach_end:
  102889. sqlite3ExprDelete(db, pFilename);
  102890. sqlite3ExprDelete(db, pDbname);
  102891. sqlite3ExprDelete(db, pKey);
  102892. }
  102893. /*
  102894. ** Called by the parser to compile a DETACH statement.
  102895. **
  102896. ** DETACH pDbname
  102897. */
  102898. SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){
  102899. static const FuncDef detach_func = {
  102900. 1, /* nArg */
  102901. SQLITE_UTF8, /* funcFlags */
  102902. 0, /* pUserData */
  102903. 0, /* pNext */
  102904. detachFunc, /* xSFunc */
  102905. 0, /* xFinalize */
  102906. 0, 0, /* xValue, xInverse */
  102907. "sqlite_detach", /* zName */
  102908. {0}
  102909. };
  102910. codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
  102911. }
  102912. /*
  102913. ** Called by the parser to compile an ATTACH statement.
  102914. **
  102915. ** ATTACH p AS pDbname KEY pKey
  102916. */
  102917. SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
  102918. static const FuncDef attach_func = {
  102919. 3, /* nArg */
  102920. SQLITE_UTF8, /* funcFlags */
  102921. 0, /* pUserData */
  102922. 0, /* pNext */
  102923. attachFunc, /* xSFunc */
  102924. 0, /* xFinalize */
  102925. 0, 0, /* xValue, xInverse */
  102926. "sqlite_attach", /* zName */
  102927. {0}
  102928. };
  102929. codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
  102930. }
  102931. #endif /* SQLITE_OMIT_ATTACH */
  102932. /*
  102933. ** Initialize a DbFixer structure. This routine must be called prior
  102934. ** to passing the structure to one of the sqliteFixAAAA() routines below.
  102935. */
  102936. SQLITE_PRIVATE void sqlite3FixInit(
  102937. DbFixer *pFix, /* The fixer to be initialized */
  102938. Parse *pParse, /* Error messages will be written here */
  102939. int iDb, /* This is the database that must be used */
  102940. const char *zType, /* "view", "trigger", or "index" */
  102941. const Token *pName /* Name of the view, trigger, or index */
  102942. ){
  102943. sqlite3 *db;
  102944. db = pParse->db;
  102945. assert( db->nDb>iDb );
  102946. pFix->pParse = pParse;
  102947. pFix->zDb = db->aDb[iDb].zDbSName;
  102948. pFix->pSchema = db->aDb[iDb].pSchema;
  102949. pFix->zType = zType;
  102950. pFix->pName = pName;
  102951. pFix->bTemp = (iDb==1);
  102952. }
  102953. /*
  102954. ** The following set of routines walk through the parse tree and assign
  102955. ** a specific database to all table references where the database name
  102956. ** was left unspecified in the original SQL statement. The pFix structure
  102957. ** must have been initialized by a prior call to sqlite3FixInit().
  102958. **
  102959. ** These routines are used to make sure that an index, trigger, or
  102960. ** view in one database does not refer to objects in a different database.
  102961. ** (Exception: indices, triggers, and views in the TEMP database are
  102962. ** allowed to refer to anything.) If a reference is explicitly made
  102963. ** to an object in a different database, an error message is added to
  102964. ** pParse->zErrMsg and these routines return non-zero. If everything
  102965. ** checks out, these routines return 0.
  102966. */
  102967. SQLITE_PRIVATE int sqlite3FixSrcList(
  102968. DbFixer *pFix, /* Context of the fixation */
  102969. SrcList *pList /* The Source list to check and modify */
  102970. ){
  102971. int i;
  102972. struct SrcList_item *pItem;
  102973. sqlite3 *db = pFix->pParse->db;
  102974. int iDb = sqlite3FindDbName(db, pFix->zDb);
  102975. if( NEVER(pList==0) ) return 0;
  102976. for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
  102977. if( pFix->bTemp==0 ){
  102978. if( pItem->zDatabase && iDb!=sqlite3FindDbName(db, pItem->zDatabase) ){
  102979. sqlite3ErrorMsg(pFix->pParse,
  102980. "%s %T cannot reference objects in database %s",
  102981. pFix->zType, pFix->pName, pItem->zDatabase);
  102982. return 1;
  102983. }
  102984. sqlite3DbFree(db, pItem->zDatabase);
  102985. pItem->zDatabase = 0;
  102986. pItem->pSchema = pFix->pSchema;
  102987. pItem->fg.fromDDL = 1;
  102988. }
  102989. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
  102990. if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
  102991. if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
  102992. #endif
  102993. if( pItem->fg.isTabFunc && sqlite3FixExprList(pFix, pItem->u1.pFuncArg) ){
  102994. return 1;
  102995. }
  102996. }
  102997. return 0;
  102998. }
  102999. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
  103000. SQLITE_PRIVATE int sqlite3FixSelect(
  103001. DbFixer *pFix, /* Context of the fixation */
  103002. Select *pSelect /* The SELECT statement to be fixed to one database */
  103003. ){
  103004. while( pSelect ){
  103005. if( sqlite3FixExprList(pFix, pSelect->pEList) ){
  103006. return 1;
  103007. }
  103008. if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
  103009. return 1;
  103010. }
  103011. if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
  103012. return 1;
  103013. }
  103014. if( sqlite3FixExprList(pFix, pSelect->pGroupBy) ){
  103015. return 1;
  103016. }
  103017. if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
  103018. return 1;
  103019. }
  103020. if( sqlite3FixExprList(pFix, pSelect->pOrderBy) ){
  103021. return 1;
  103022. }
  103023. if( sqlite3FixExpr(pFix, pSelect->pLimit) ){
  103024. return 1;
  103025. }
  103026. if( pSelect->pWith ){
  103027. int i;
  103028. for(i=0; i<pSelect->pWith->nCte; i++){
  103029. if( sqlite3FixSelect(pFix, pSelect->pWith->a[i].pSelect) ){
  103030. return 1;
  103031. }
  103032. }
  103033. }
  103034. pSelect = pSelect->pPrior;
  103035. }
  103036. return 0;
  103037. }
  103038. SQLITE_PRIVATE int sqlite3FixExpr(
  103039. DbFixer *pFix, /* Context of the fixation */
  103040. Expr *pExpr /* The expression to be fixed to one database */
  103041. ){
  103042. while( pExpr ){
  103043. if( !pFix->bTemp ) ExprSetProperty(pExpr, EP_FromDDL);
  103044. if( pExpr->op==TK_VARIABLE ){
  103045. if( pFix->pParse->db->init.busy ){
  103046. pExpr->op = TK_NULL;
  103047. }else{
  103048. sqlite3ErrorMsg(pFix->pParse, "%s cannot use variables", pFix->zType);
  103049. return 1;
  103050. }
  103051. }
  103052. if( ExprHasProperty(pExpr, EP_TokenOnly|EP_Leaf) ) break;
  103053. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  103054. if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1;
  103055. }else{
  103056. if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1;
  103057. }
  103058. if( sqlite3FixExpr(pFix, pExpr->pRight) ){
  103059. return 1;
  103060. }
  103061. pExpr = pExpr->pLeft;
  103062. }
  103063. return 0;
  103064. }
  103065. SQLITE_PRIVATE int sqlite3FixExprList(
  103066. DbFixer *pFix, /* Context of the fixation */
  103067. ExprList *pList /* The expression to be fixed to one database */
  103068. ){
  103069. int i;
  103070. struct ExprList_item *pItem;
  103071. if( pList==0 ) return 0;
  103072. for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
  103073. if( sqlite3FixExpr(pFix, pItem->pExpr) ){
  103074. return 1;
  103075. }
  103076. }
  103077. return 0;
  103078. }
  103079. #endif
  103080. #ifndef SQLITE_OMIT_TRIGGER
  103081. SQLITE_PRIVATE int sqlite3FixTriggerStep(
  103082. DbFixer *pFix, /* Context of the fixation */
  103083. TriggerStep *pStep /* The trigger step be fixed to one database */
  103084. ){
  103085. while( pStep ){
  103086. if( sqlite3FixSelect(pFix, pStep->pSelect) ){
  103087. return 1;
  103088. }
  103089. if( sqlite3FixExpr(pFix, pStep->pWhere) ){
  103090. return 1;
  103091. }
  103092. if( sqlite3FixExprList(pFix, pStep->pExprList) ){
  103093. return 1;
  103094. }
  103095. #ifndef SQLITE_OMIT_UPSERT
  103096. if( pStep->pUpsert ){
  103097. Upsert *pUp = pStep->pUpsert;
  103098. if( sqlite3FixExprList(pFix, pUp->pUpsertTarget)
  103099. || sqlite3FixExpr(pFix, pUp->pUpsertTargetWhere)
  103100. || sqlite3FixExprList(pFix, pUp->pUpsertSet)
  103101. || sqlite3FixExpr(pFix, pUp->pUpsertWhere)
  103102. ){
  103103. return 1;
  103104. }
  103105. }
  103106. #endif
  103107. pStep = pStep->pNext;
  103108. }
  103109. return 0;
  103110. }
  103111. #endif
  103112. /************** End of attach.c **********************************************/
  103113. /************** Begin file auth.c ********************************************/
  103114. /*
  103115. ** 2003 January 11
  103116. **
  103117. ** The author disclaims copyright to this source code. In place of
  103118. ** a legal notice, here is a blessing:
  103119. **
  103120. ** May you do good and not evil.
  103121. ** May you find forgiveness for yourself and forgive others.
  103122. ** May you share freely, never taking more than you give.
  103123. **
  103124. *************************************************************************
  103125. ** This file contains code used to implement the sqlite3_set_authorizer()
  103126. ** API. This facility is an optional feature of the library. Embedded
  103127. ** systems that do not need this facility may omit it by recompiling
  103128. ** the library with -DSQLITE_OMIT_AUTHORIZATION=1
  103129. */
  103130. /* #include "sqliteInt.h" */
  103131. /*
  103132. ** All of the code in this file may be omitted by defining a single
  103133. ** macro.
  103134. */
  103135. #ifndef SQLITE_OMIT_AUTHORIZATION
  103136. /*
  103137. ** Set or clear the access authorization function.
  103138. **
  103139. ** The access authorization function is be called during the compilation
  103140. ** phase to verify that the user has read and/or write access permission on
  103141. ** various fields of the database. The first argument to the auth function
  103142. ** is a copy of the 3rd argument to this routine. The second argument
  103143. ** to the auth function is one of these constants:
  103144. **
  103145. ** SQLITE_CREATE_INDEX
  103146. ** SQLITE_CREATE_TABLE
  103147. ** SQLITE_CREATE_TEMP_INDEX
  103148. ** SQLITE_CREATE_TEMP_TABLE
  103149. ** SQLITE_CREATE_TEMP_TRIGGER
  103150. ** SQLITE_CREATE_TEMP_VIEW
  103151. ** SQLITE_CREATE_TRIGGER
  103152. ** SQLITE_CREATE_VIEW
  103153. ** SQLITE_DELETE
  103154. ** SQLITE_DROP_INDEX
  103155. ** SQLITE_DROP_TABLE
  103156. ** SQLITE_DROP_TEMP_INDEX
  103157. ** SQLITE_DROP_TEMP_TABLE
  103158. ** SQLITE_DROP_TEMP_TRIGGER
  103159. ** SQLITE_DROP_TEMP_VIEW
  103160. ** SQLITE_DROP_TRIGGER
  103161. ** SQLITE_DROP_VIEW
  103162. ** SQLITE_INSERT
  103163. ** SQLITE_PRAGMA
  103164. ** SQLITE_READ
  103165. ** SQLITE_SELECT
  103166. ** SQLITE_TRANSACTION
  103167. ** SQLITE_UPDATE
  103168. **
  103169. ** The third and fourth arguments to the auth function are the name of
  103170. ** the table and the column that are being accessed. The auth function
  103171. ** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE. If
  103172. ** SQLITE_OK is returned, it means that access is allowed. SQLITE_DENY
  103173. ** means that the SQL statement will never-run - the sqlite3_exec() call
  103174. ** will return with an error. SQLITE_IGNORE means that the SQL statement
  103175. ** should run but attempts to read the specified column will return NULL
  103176. ** and attempts to write the column will be ignored.
  103177. **
  103178. ** Setting the auth function to NULL disables this hook. The default
  103179. ** setting of the auth function is NULL.
  103180. */
  103181. SQLITE_API int sqlite3_set_authorizer(
  103182. sqlite3 *db,
  103183. int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
  103184. void *pArg
  103185. ){
  103186. #ifdef SQLITE_ENABLE_API_ARMOR
  103187. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  103188. #endif
  103189. sqlite3_mutex_enter(db->mutex);
  103190. db->xAuth = (sqlite3_xauth)xAuth;
  103191. db->pAuthArg = pArg;
  103192. if( db->xAuth ) sqlite3ExpirePreparedStatements(db, 1);
  103193. sqlite3_mutex_leave(db->mutex);
  103194. return SQLITE_OK;
  103195. }
  103196. /*
  103197. ** Write an error message into pParse->zErrMsg that explains that the
  103198. ** user-supplied authorization function returned an illegal value.
  103199. */
  103200. static void sqliteAuthBadReturnCode(Parse *pParse){
  103201. sqlite3ErrorMsg(pParse, "authorizer malfunction");
  103202. pParse->rc = SQLITE_ERROR;
  103203. }
  103204. /*
  103205. ** Invoke the authorization callback for permission to read column zCol from
  103206. ** table zTab in database zDb. This function assumes that an authorization
  103207. ** callback has been registered (i.e. that sqlite3.xAuth is not NULL).
  103208. **
  103209. ** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed
  103210. ** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE
  103211. ** is treated as SQLITE_DENY. In this case an error is left in pParse.
  103212. */
  103213. SQLITE_PRIVATE int sqlite3AuthReadCol(
  103214. Parse *pParse, /* The parser context */
  103215. const char *zTab, /* Table name */
  103216. const char *zCol, /* Column name */
  103217. int iDb /* Index of containing database. */
  103218. ){
  103219. sqlite3 *db = pParse->db; /* Database handle */
  103220. char *zDb = db->aDb[iDb].zDbSName; /* Schema name of attached database */
  103221. int rc; /* Auth callback return code */
  103222. if( db->init.busy ) return SQLITE_OK;
  103223. rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext
  103224. #ifdef SQLITE_USER_AUTHENTICATION
  103225. ,db->auth.zAuthUser
  103226. #endif
  103227. );
  103228. if( rc==SQLITE_DENY ){
  103229. char *z = sqlite3_mprintf("%s.%s", zTab, zCol);
  103230. if( db->nDb>2 || iDb!=0 ) z = sqlite3_mprintf("%s.%z", zDb, z);
  103231. sqlite3ErrorMsg(pParse, "access to %z is prohibited", z);
  103232. pParse->rc = SQLITE_AUTH;
  103233. }else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){
  103234. sqliteAuthBadReturnCode(pParse);
  103235. }
  103236. return rc;
  103237. }
  103238. /*
  103239. ** The pExpr should be a TK_COLUMN expression. The table referred to
  103240. ** is in pTabList or else it is the NEW or OLD table of a trigger.
  103241. ** Check to see if it is OK to read this particular column.
  103242. **
  103243. ** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN
  103244. ** instruction into a TK_NULL. If the auth function returns SQLITE_DENY,
  103245. ** then generate an error.
  103246. */
  103247. SQLITE_PRIVATE void sqlite3AuthRead(
  103248. Parse *pParse, /* The parser context */
  103249. Expr *pExpr, /* The expression to check authorization on */
  103250. Schema *pSchema, /* The schema of the expression */
  103251. SrcList *pTabList /* All table that pExpr might refer to */
  103252. ){
  103253. sqlite3 *db = pParse->db;
  103254. Table *pTab = 0; /* The table being read */
  103255. const char *zCol; /* Name of the column of the table */
  103256. int iSrc; /* Index in pTabList->a[] of table being read */
  103257. int iDb; /* The index of the database the expression refers to */
  103258. int iCol; /* Index of column in table */
  103259. assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );
  103260. assert( !IN_RENAME_OBJECT || db->xAuth==0 );
  103261. if( db->xAuth==0 ) return;
  103262. iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
  103263. if( iDb<0 ){
  103264. /* An attempt to read a column out of a subquery or other
  103265. ** temporary table. */
  103266. return;
  103267. }
  103268. if( pExpr->op==TK_TRIGGER ){
  103269. pTab = pParse->pTriggerTab;
  103270. }else{
  103271. assert( pTabList );
  103272. for(iSrc=0; ALWAYS(iSrc<pTabList->nSrc); iSrc++){
  103273. if( pExpr->iTable==pTabList->a[iSrc].iCursor ){
  103274. pTab = pTabList->a[iSrc].pTab;
  103275. break;
  103276. }
  103277. }
  103278. }
  103279. iCol = pExpr->iColumn;
  103280. if( NEVER(pTab==0) ) return;
  103281. if( iCol>=0 ){
  103282. assert( iCol<pTab->nCol );
  103283. zCol = pTab->aCol[iCol].zName;
  103284. }else if( pTab->iPKey>=0 ){
  103285. assert( pTab->iPKey<pTab->nCol );
  103286. zCol = pTab->aCol[pTab->iPKey].zName;
  103287. }else{
  103288. zCol = "ROWID";
  103289. }
  103290. assert( iDb>=0 && iDb<db->nDb );
  103291. if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){
  103292. pExpr->op = TK_NULL;
  103293. }
  103294. }
  103295. /*
  103296. ** Do an authorization check using the code and arguments given. Return
  103297. ** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY. If SQLITE_DENY
  103298. ** is returned, then the error count and error message in pParse are
  103299. ** modified appropriately.
  103300. */
  103301. SQLITE_PRIVATE int sqlite3AuthCheck(
  103302. Parse *pParse,
  103303. int code,
  103304. const char *zArg1,
  103305. const char *zArg2,
  103306. const char *zArg3
  103307. ){
  103308. sqlite3 *db = pParse->db;
  103309. int rc;
  103310. /* Don't do any authorization checks if the database is initialising
  103311. ** or if the parser is being invoked from within sqlite3_declare_vtab.
  103312. */
  103313. assert( !IN_RENAME_OBJECT || db->xAuth==0 );
  103314. if( db->init.busy || IN_SPECIAL_PARSE ){
  103315. return SQLITE_OK;
  103316. }
  103317. if( db->xAuth==0 ){
  103318. return SQLITE_OK;
  103319. }
  103320. /* EVIDENCE-OF: R-43249-19882 The third through sixth parameters to the
  103321. ** callback are either NULL pointers or zero-terminated strings that
  103322. ** contain additional details about the action to be authorized.
  103323. **
  103324. ** The following testcase() macros show that any of the 3rd through 6th
  103325. ** parameters can be either NULL or a string. */
  103326. testcase( zArg1==0 );
  103327. testcase( zArg2==0 );
  103328. testcase( zArg3==0 );
  103329. testcase( pParse->zAuthContext==0 );
  103330. rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext
  103331. #ifdef SQLITE_USER_AUTHENTICATION
  103332. ,db->auth.zAuthUser
  103333. #endif
  103334. );
  103335. if( rc==SQLITE_DENY ){
  103336. sqlite3ErrorMsg(pParse, "not authorized");
  103337. pParse->rc = SQLITE_AUTH;
  103338. }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
  103339. rc = SQLITE_DENY;
  103340. sqliteAuthBadReturnCode(pParse);
  103341. }
  103342. return rc;
  103343. }
  103344. /*
  103345. ** Push an authorization context. After this routine is called, the
  103346. ** zArg3 argument to authorization callbacks will be zContext until
  103347. ** popped. Or if pParse==0, this routine is a no-op.
  103348. */
  103349. SQLITE_PRIVATE void sqlite3AuthContextPush(
  103350. Parse *pParse,
  103351. AuthContext *pContext,
  103352. const char *zContext
  103353. ){
  103354. assert( pParse );
  103355. pContext->pParse = pParse;
  103356. pContext->zAuthContext = pParse->zAuthContext;
  103357. pParse->zAuthContext = zContext;
  103358. }
  103359. /*
  103360. ** Pop an authorization context that was previously pushed
  103361. ** by sqlite3AuthContextPush
  103362. */
  103363. SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){
  103364. if( pContext->pParse ){
  103365. pContext->pParse->zAuthContext = pContext->zAuthContext;
  103366. pContext->pParse = 0;
  103367. }
  103368. }
  103369. #endif /* SQLITE_OMIT_AUTHORIZATION */
  103370. /************** End of auth.c ************************************************/
  103371. /************** Begin file build.c *******************************************/
  103372. /*
  103373. ** 2001 September 15
  103374. **
  103375. ** The author disclaims copyright to this source code. In place of
  103376. ** a legal notice, here is a blessing:
  103377. **
  103378. ** May you do good and not evil.
  103379. ** May you find forgiveness for yourself and forgive others.
  103380. ** May you share freely, never taking more than you give.
  103381. **
  103382. *************************************************************************
  103383. ** This file contains C code routines that are called by the SQLite parser
  103384. ** when syntax rules are reduced. The routines in this file handle the
  103385. ** following kinds of SQL syntax:
  103386. **
  103387. ** CREATE TABLE
  103388. ** DROP TABLE
  103389. ** CREATE INDEX
  103390. ** DROP INDEX
  103391. ** creating ID lists
  103392. ** BEGIN TRANSACTION
  103393. ** COMMIT
  103394. ** ROLLBACK
  103395. */
  103396. /* #include "sqliteInt.h" */
  103397. #ifndef SQLITE_OMIT_SHARED_CACHE
  103398. /*
  103399. ** The TableLock structure is only used by the sqlite3TableLock() and
  103400. ** codeTableLocks() functions.
  103401. */
  103402. struct TableLock {
  103403. int iDb; /* The database containing the table to be locked */
  103404. int iTab; /* The root page of the table to be locked */
  103405. u8 isWriteLock; /* True for write lock. False for a read lock */
  103406. const char *zLockName; /* Name of the table */
  103407. };
  103408. /*
  103409. ** Record the fact that we want to lock a table at run-time.
  103410. **
  103411. ** The table to be locked has root page iTab and is found in database iDb.
  103412. ** A read or a write lock can be taken depending on isWritelock.
  103413. **
  103414. ** This routine just records the fact that the lock is desired. The
  103415. ** code to make the lock occur is generated by a later call to
  103416. ** codeTableLocks() which occurs during sqlite3FinishCoding().
  103417. */
  103418. SQLITE_PRIVATE void sqlite3TableLock(
  103419. Parse *pParse, /* Parsing context */
  103420. int iDb, /* Index of the database containing the table to lock */
  103421. int iTab, /* Root page number of the table to be locked */
  103422. u8 isWriteLock, /* True for a write lock */
  103423. const char *zName /* Name of the table to be locked */
  103424. ){
  103425. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  103426. int i;
  103427. int nBytes;
  103428. TableLock *p;
  103429. assert( iDb>=0 );
  103430. if( iDb==1 ) return;
  103431. if( !sqlite3BtreeSharable(pParse->db->aDb[iDb].pBt) ) return;
  103432. for(i=0; i<pToplevel->nTableLock; i++){
  103433. p = &pToplevel->aTableLock[i];
  103434. if( p->iDb==iDb && p->iTab==iTab ){
  103435. p->isWriteLock = (p->isWriteLock || isWriteLock);
  103436. return;
  103437. }
  103438. }
  103439. nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
  103440. pToplevel->aTableLock =
  103441. sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
  103442. if( pToplevel->aTableLock ){
  103443. p = &pToplevel->aTableLock[pToplevel->nTableLock++];
  103444. p->iDb = iDb;
  103445. p->iTab = iTab;
  103446. p->isWriteLock = isWriteLock;
  103447. p->zLockName = zName;
  103448. }else{
  103449. pToplevel->nTableLock = 0;
  103450. sqlite3OomFault(pToplevel->db);
  103451. }
  103452. }
  103453. /*
  103454. ** Code an OP_TableLock instruction for each table locked by the
  103455. ** statement (configured by calls to sqlite3TableLock()).
  103456. */
  103457. static void codeTableLocks(Parse *pParse){
  103458. int i;
  103459. Vdbe *pVdbe;
  103460. pVdbe = sqlite3GetVdbe(pParse);
  103461. assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
  103462. for(i=0; i<pParse->nTableLock; i++){
  103463. TableLock *p = &pParse->aTableLock[i];
  103464. int p1 = p->iDb;
  103465. sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
  103466. p->zLockName, P4_STATIC);
  103467. }
  103468. }
  103469. #else
  103470. #define codeTableLocks(x)
  103471. #endif
  103472. /*
  103473. ** Return TRUE if the given yDbMask object is empty - if it contains no
  103474. ** 1 bits. This routine is used by the DbMaskAllZero() and DbMaskNotZero()
  103475. ** macros when SQLITE_MAX_ATTACHED is greater than 30.
  103476. */
  103477. #if SQLITE_MAX_ATTACHED>30
  103478. SQLITE_PRIVATE int sqlite3DbMaskAllZero(yDbMask m){
  103479. int i;
  103480. for(i=0; i<sizeof(yDbMask); i++) if( m[i] ) return 0;
  103481. return 1;
  103482. }
  103483. #endif
  103484. /*
  103485. ** This routine is called after a single SQL statement has been
  103486. ** parsed and a VDBE program to execute that statement has been
  103487. ** prepared. This routine puts the finishing touches on the
  103488. ** VDBE program and resets the pParse structure for the next
  103489. ** parse.
  103490. **
  103491. ** Note that if an error occurred, it might be the case that
  103492. ** no VDBE code was generated.
  103493. */
  103494. SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
  103495. sqlite3 *db;
  103496. Vdbe *v;
  103497. assert( pParse->pToplevel==0 );
  103498. db = pParse->db;
  103499. if( pParse->nested ) return;
  103500. if( db->mallocFailed || pParse->nErr ){
  103501. if( pParse->rc==SQLITE_OK ) pParse->rc = SQLITE_ERROR;
  103502. return;
  103503. }
  103504. /* Begin by generating some termination code at the end of the
  103505. ** vdbe program
  103506. */
  103507. v = sqlite3GetVdbe(pParse);
  103508. assert( !pParse->isMultiWrite
  103509. || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
  103510. if( v ){
  103511. sqlite3VdbeAddOp0(v, OP_Halt);
  103512. #if SQLITE_USER_AUTHENTICATION
  103513. if( pParse->nTableLock>0 && db->init.busy==0 ){
  103514. sqlite3UserAuthInit(db);
  103515. if( db->auth.authLevel<UAUTH_User ){
  103516. sqlite3ErrorMsg(pParse, "user not authenticated");
  103517. pParse->rc = SQLITE_AUTH_USER;
  103518. return;
  103519. }
  103520. }
  103521. #endif
  103522. /* The cookie mask contains one bit for each database file open.
  103523. ** (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are
  103524. ** set for each database that is used. Generate code to start a
  103525. ** transaction on each used database and to verify the schema cookie
  103526. ** on each used database.
  103527. */
  103528. if( db->mallocFailed==0
  103529. && (DbMaskNonZero(pParse->cookieMask) || pParse->pConstExpr)
  103530. ){
  103531. int iDb, i;
  103532. assert( sqlite3VdbeGetOp(v, 0)->opcode==OP_Init );
  103533. sqlite3VdbeJumpHere(v, 0);
  103534. for(iDb=0; iDb<db->nDb; iDb++){
  103535. Schema *pSchema;
  103536. if( DbMaskTest(pParse->cookieMask, iDb)==0 ) continue;
  103537. sqlite3VdbeUsesBtree(v, iDb);
  103538. pSchema = db->aDb[iDb].pSchema;
  103539. sqlite3VdbeAddOp4Int(v,
  103540. OP_Transaction, /* Opcode */
  103541. iDb, /* P1 */
  103542. DbMaskTest(pParse->writeMask,iDb), /* P2 */
  103543. pSchema->schema_cookie, /* P3 */
  103544. pSchema->iGeneration /* P4 */
  103545. );
  103546. if( db->init.busy==0 ) sqlite3VdbeChangeP5(v, 1);
  103547. VdbeComment((v,
  103548. "usesStmtJournal=%d", pParse->mayAbort && pParse->isMultiWrite));
  103549. }
  103550. #ifndef SQLITE_OMIT_VIRTUALTABLE
  103551. for(i=0; i<pParse->nVtabLock; i++){
  103552. char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
  103553. sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
  103554. }
  103555. pParse->nVtabLock = 0;
  103556. #endif
  103557. /* Once all the cookies have been verified and transactions opened,
  103558. ** obtain the required table-locks. This is a no-op unless the
  103559. ** shared-cache feature is enabled.
  103560. */
  103561. codeTableLocks(pParse);
  103562. /* Initialize any AUTOINCREMENT data structures required.
  103563. */
  103564. sqlite3AutoincrementBegin(pParse);
  103565. /* Code constant expressions that where factored out of inner loops */
  103566. if( pParse->pConstExpr ){
  103567. ExprList *pEL = pParse->pConstExpr;
  103568. pParse->okConstFactor = 0;
  103569. for(i=0; i<pEL->nExpr; i++){
  103570. sqlite3ExprCode(pParse, pEL->a[i].pExpr, pEL->a[i].u.iConstExprReg);
  103571. }
  103572. }
  103573. /* Finally, jump back to the beginning of the executable code. */
  103574. sqlite3VdbeGoto(v, 1);
  103575. }
  103576. }
  103577. /* Get the VDBE program ready for execution
  103578. */
  103579. if( v && pParse->nErr==0 && !db->mallocFailed ){
  103580. /* A minimum of one cursor is required if autoincrement is used
  103581. * See ticket [a696379c1f08866] */
  103582. assert( pParse->pAinc==0 || pParse->nTab>0 );
  103583. sqlite3VdbeMakeReady(v, pParse);
  103584. pParse->rc = SQLITE_DONE;
  103585. }else{
  103586. pParse->rc = SQLITE_ERROR;
  103587. }
  103588. }
  103589. /*
  103590. ** Run the parser and code generator recursively in order to generate
  103591. ** code for the SQL statement given onto the end of the pParse context
  103592. ** currently under construction. When the parser is run recursively
  103593. ** this way, the final OP_Halt is not appended and other initialization
  103594. ** and finalization steps are omitted because those are handling by the
  103595. ** outermost parser.
  103596. **
  103597. ** Not everything is nestable. This facility is designed to permit
  103598. ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER. Use
  103599. ** care if you decide to try to use this routine for some other purposes.
  103600. */
  103601. SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
  103602. va_list ap;
  103603. char *zSql;
  103604. char *zErrMsg = 0;
  103605. sqlite3 *db = pParse->db;
  103606. char saveBuf[PARSE_TAIL_SZ];
  103607. if( pParse->nErr ) return;
  103608. assert( pParse->nested<10 ); /* Nesting should only be of limited depth */
  103609. va_start(ap, zFormat);
  103610. zSql = sqlite3VMPrintf(db, zFormat, ap);
  103611. va_end(ap);
  103612. if( zSql==0 ){
  103613. /* This can result either from an OOM or because the formatted string
  103614. ** exceeds SQLITE_LIMIT_LENGTH. In the latter case, we need to set
  103615. ** an error */
  103616. if( !db->mallocFailed ) pParse->rc = SQLITE_TOOBIG;
  103617. pParse->nErr++;
  103618. return;
  103619. }
  103620. pParse->nested++;
  103621. memcpy(saveBuf, PARSE_TAIL(pParse), PARSE_TAIL_SZ);
  103622. memset(PARSE_TAIL(pParse), 0, PARSE_TAIL_SZ);
  103623. sqlite3RunParser(pParse, zSql, &zErrMsg);
  103624. sqlite3DbFree(db, zErrMsg);
  103625. sqlite3DbFree(db, zSql);
  103626. memcpy(PARSE_TAIL(pParse), saveBuf, PARSE_TAIL_SZ);
  103627. pParse->nested--;
  103628. }
  103629. #if SQLITE_USER_AUTHENTICATION
  103630. /*
  103631. ** Return TRUE if zTable is the name of the system table that stores the
  103632. ** list of users and their access credentials.
  103633. */
  103634. SQLITE_PRIVATE int sqlite3UserAuthTable(const char *zTable){
  103635. return sqlite3_stricmp(zTable, "sqlite_user")==0;
  103636. }
  103637. #endif
  103638. /*
  103639. ** Locate the in-memory structure that describes a particular database
  103640. ** table given the name of that table and (optionally) the name of the
  103641. ** database containing the table. Return NULL if not found.
  103642. **
  103643. ** If zDatabase is 0, all databases are searched for the table and the
  103644. ** first matching table is returned. (No checking for duplicate table
  103645. ** names is done.) The search order is TEMP first, then MAIN, then any
  103646. ** auxiliary databases added using the ATTACH command.
  103647. **
  103648. ** See also sqlite3LocateTable().
  103649. */
  103650. SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
  103651. Table *p = 0;
  103652. int i;
  103653. /* All mutexes are required for schema access. Make sure we hold them. */
  103654. assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );
  103655. #if SQLITE_USER_AUTHENTICATION
  103656. /* Only the admin user is allowed to know that the sqlite_user table
  103657. ** exists */
  103658. if( db->auth.authLevel<UAUTH_Admin && sqlite3UserAuthTable(zName)!=0 ){
  103659. return 0;
  103660. }
  103661. #endif
  103662. if( zDatabase ){
  103663. for(i=0; i<db->nDb; i++){
  103664. if( sqlite3StrICmp(zDatabase, db->aDb[i].zDbSName)==0 ) break;
  103665. }
  103666. if( i>=db->nDb ){
  103667. /* No match against the official names. But always match "main"
  103668. ** to schema 0 as a legacy fallback. */
  103669. if( sqlite3StrICmp(zDatabase,"main")==0 ){
  103670. i = 0;
  103671. }else{
  103672. return 0;
  103673. }
  103674. }
  103675. p = sqlite3HashFind(&db->aDb[i].pSchema->tblHash, zName);
  103676. if( p==0 && i==1 && sqlite3StrICmp(zName, MASTER_NAME)==0 ){
  103677. /* All temp.sqlite_master to be an alias for sqlite_temp_master */
  103678. p = sqlite3HashFind(&db->aDb[1].pSchema->tblHash, TEMP_MASTER_NAME);
  103679. }
  103680. }else{
  103681. /* Match against TEMP first */
  103682. p = sqlite3HashFind(&db->aDb[1].pSchema->tblHash, zName);
  103683. if( p ) return p;
  103684. /* The main database is second */
  103685. p = sqlite3HashFind(&db->aDb[0].pSchema->tblHash, zName);
  103686. if( p ) return p;
  103687. /* Attached databases are in order of attachment */
  103688. for(i=2; i<db->nDb; i++){
  103689. assert( sqlite3SchemaMutexHeld(db, i, 0) );
  103690. p = sqlite3HashFind(&db->aDb[i].pSchema->tblHash, zName);
  103691. if( p ) break;
  103692. }
  103693. }
  103694. return p;
  103695. }
  103696. /*
  103697. ** Locate the in-memory structure that describes a particular database
  103698. ** table given the name of that table and (optionally) the name of the
  103699. ** database containing the table. Return NULL if not found. Also leave an
  103700. ** error message in pParse->zErrMsg.
  103701. **
  103702. ** The difference between this routine and sqlite3FindTable() is that this
  103703. ** routine leaves an error message in pParse->zErrMsg where
  103704. ** sqlite3FindTable() does not.
  103705. */
  103706. SQLITE_PRIVATE Table *sqlite3LocateTable(
  103707. Parse *pParse, /* context in which to report errors */
  103708. u32 flags, /* LOCATE_VIEW or LOCATE_NOERR */
  103709. const char *zName, /* Name of the table we are looking for */
  103710. const char *zDbase /* Name of the database. Might be NULL */
  103711. ){
  103712. Table *p;
  103713. sqlite3 *db = pParse->db;
  103714. /* Read the database schema. If an error occurs, leave an error message
  103715. ** and code in pParse and return NULL. */
  103716. if( (db->mDbFlags & DBFLAG_SchemaKnownOk)==0
  103717. && SQLITE_OK!=sqlite3ReadSchema(pParse)
  103718. ){
  103719. return 0;
  103720. }
  103721. p = sqlite3FindTable(db, zName, zDbase);
  103722. if( p==0 ){
  103723. #ifndef SQLITE_OMIT_VIRTUALTABLE
  103724. /* If zName is the not the name of a table in the schema created using
  103725. ** CREATE, then check to see if it is the name of an virtual table that
  103726. ** can be an eponymous virtual table. */
  103727. if( pParse->disableVtab==0 ){
  103728. Module *pMod = (Module*)sqlite3HashFind(&db->aModule, zName);
  103729. if( pMod==0 && sqlite3_strnicmp(zName, "pragma_", 7)==0 ){
  103730. pMod = sqlite3PragmaVtabRegister(db, zName);
  103731. }
  103732. if( pMod && sqlite3VtabEponymousTableInit(pParse, pMod) ){
  103733. return pMod->pEpoTab;
  103734. }
  103735. }
  103736. #endif
  103737. if( flags & LOCATE_NOERR ) return 0;
  103738. pParse->checkSchema = 1;
  103739. }else if( IsVirtual(p) && pParse->disableVtab ){
  103740. p = 0;
  103741. }
  103742. if( p==0 ){
  103743. const char *zMsg = flags & LOCATE_VIEW ? "no such view" : "no such table";
  103744. if( zDbase ){
  103745. sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
  103746. }else{
  103747. sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
  103748. }
  103749. }
  103750. return p;
  103751. }
  103752. /*
  103753. ** Locate the table identified by *p.
  103754. **
  103755. ** This is a wrapper around sqlite3LocateTable(). The difference between
  103756. ** sqlite3LocateTable() and this function is that this function restricts
  103757. ** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be
  103758. ** non-NULL if it is part of a view or trigger program definition. See
  103759. ** sqlite3FixSrcList() for details.
  103760. */
  103761. SQLITE_PRIVATE Table *sqlite3LocateTableItem(
  103762. Parse *pParse,
  103763. u32 flags,
  103764. struct SrcList_item *p
  103765. ){
  103766. const char *zDb;
  103767. assert( p->pSchema==0 || p->zDatabase==0 );
  103768. if( p->pSchema ){
  103769. int iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema);
  103770. zDb = pParse->db->aDb[iDb].zDbSName;
  103771. }else{
  103772. zDb = p->zDatabase;
  103773. }
  103774. return sqlite3LocateTable(pParse, flags, p->zName, zDb);
  103775. }
  103776. /*
  103777. ** Locate the in-memory structure that describes
  103778. ** a particular index given the name of that index
  103779. ** and the name of the database that contains the index.
  103780. ** Return NULL if not found.
  103781. **
  103782. ** If zDatabase is 0, all databases are searched for the
  103783. ** table and the first matching index is returned. (No checking
  103784. ** for duplicate index names is done.) The search order is
  103785. ** TEMP first, then MAIN, then any auxiliary databases added
  103786. ** using the ATTACH command.
  103787. */
  103788. SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
  103789. Index *p = 0;
  103790. int i;
  103791. /* All mutexes are required for schema access. Make sure we hold them. */
  103792. assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
  103793. for(i=OMIT_TEMPDB; i<db->nDb; i++){
  103794. int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
  103795. Schema *pSchema = db->aDb[j].pSchema;
  103796. assert( pSchema );
  103797. if( zDb && sqlite3DbIsNamed(db, j, zDb)==0 ) continue;
  103798. assert( sqlite3SchemaMutexHeld(db, j, 0) );
  103799. p = sqlite3HashFind(&pSchema->idxHash, zName);
  103800. if( p ) break;
  103801. }
  103802. return p;
  103803. }
  103804. /*
  103805. ** Reclaim the memory used by an index
  103806. */
  103807. SQLITE_PRIVATE void sqlite3FreeIndex(sqlite3 *db, Index *p){
  103808. #ifndef SQLITE_OMIT_ANALYZE
  103809. sqlite3DeleteIndexSamples(db, p);
  103810. #endif
  103811. sqlite3ExprDelete(db, p->pPartIdxWhere);
  103812. sqlite3ExprListDelete(db, p->aColExpr);
  103813. sqlite3DbFree(db, p->zColAff);
  103814. if( p->isResized ) sqlite3DbFree(db, (void *)p->azColl);
  103815. #ifdef SQLITE_ENABLE_STAT4
  103816. sqlite3_free(p->aiRowEst);
  103817. #endif
  103818. sqlite3DbFree(db, p);
  103819. }
  103820. /*
  103821. ** For the index called zIdxName which is found in the database iDb,
  103822. ** unlike that index from its Table then remove the index from
  103823. ** the index hash table and free all memory structures associated
  103824. ** with the index.
  103825. */
  103826. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
  103827. Index *pIndex;
  103828. Hash *pHash;
  103829. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  103830. pHash = &db->aDb[iDb].pSchema->idxHash;
  103831. pIndex = sqlite3HashInsert(pHash, zIdxName, 0);
  103832. if( ALWAYS(pIndex) ){
  103833. if( pIndex->pTable->pIndex==pIndex ){
  103834. pIndex->pTable->pIndex = pIndex->pNext;
  103835. }else{
  103836. Index *p;
  103837. /* Justification of ALWAYS(); The index must be on the list of
  103838. ** indices. */
  103839. p = pIndex->pTable->pIndex;
  103840. while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
  103841. if( ALWAYS(p && p->pNext==pIndex) ){
  103842. p->pNext = pIndex->pNext;
  103843. }
  103844. }
  103845. sqlite3FreeIndex(db, pIndex);
  103846. }
  103847. db->mDbFlags |= DBFLAG_SchemaChange;
  103848. }
  103849. /*
  103850. ** Look through the list of open database files in db->aDb[] and if
  103851. ** any have been closed, remove them from the list. Reallocate the
  103852. ** db->aDb[] structure to a smaller size, if possible.
  103853. **
  103854. ** Entry 0 (the "main" database) and entry 1 (the "temp" database)
  103855. ** are never candidates for being collapsed.
  103856. */
  103857. SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3 *db){
  103858. int i, j;
  103859. for(i=j=2; i<db->nDb; i++){
  103860. struct Db *pDb = &db->aDb[i];
  103861. if( pDb->pBt==0 ){
  103862. sqlite3DbFree(db, pDb->zDbSName);
  103863. pDb->zDbSName = 0;
  103864. continue;
  103865. }
  103866. if( j<i ){
  103867. db->aDb[j] = db->aDb[i];
  103868. }
  103869. j++;
  103870. }
  103871. db->nDb = j;
  103872. if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
  103873. memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
  103874. sqlite3DbFree(db, db->aDb);
  103875. db->aDb = db->aDbStatic;
  103876. }
  103877. }
  103878. /*
  103879. ** Reset the schema for the database at index iDb. Also reset the
  103880. ** TEMP schema. The reset is deferred if db->nSchemaLock is not zero.
  103881. ** Deferred resets may be run by calling with iDb<0.
  103882. */
  103883. SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3 *db, int iDb){
  103884. int i;
  103885. assert( iDb<db->nDb );
  103886. if( iDb>=0 ){
  103887. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  103888. DbSetProperty(db, iDb, DB_ResetWanted);
  103889. DbSetProperty(db, 1, DB_ResetWanted);
  103890. db->mDbFlags &= ~DBFLAG_SchemaKnownOk;
  103891. }
  103892. if( db->nSchemaLock==0 ){
  103893. for(i=0; i<db->nDb; i++){
  103894. if( DbHasProperty(db, i, DB_ResetWanted) ){
  103895. sqlite3SchemaClear(db->aDb[i].pSchema);
  103896. }
  103897. }
  103898. }
  103899. }
  103900. /*
  103901. ** Erase all schema information from all attached databases (including
  103902. ** "main" and "temp") for a single database connection.
  103903. */
  103904. SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){
  103905. int i;
  103906. sqlite3BtreeEnterAll(db);
  103907. for(i=0; i<db->nDb; i++){
  103908. Db *pDb = &db->aDb[i];
  103909. if( pDb->pSchema ){
  103910. if( db->nSchemaLock==0 ){
  103911. sqlite3SchemaClear(pDb->pSchema);
  103912. }else{
  103913. DbSetProperty(db, i, DB_ResetWanted);
  103914. }
  103915. }
  103916. }
  103917. db->mDbFlags &= ~(DBFLAG_SchemaChange|DBFLAG_SchemaKnownOk);
  103918. sqlite3VtabUnlockList(db);
  103919. sqlite3BtreeLeaveAll(db);
  103920. if( db->nSchemaLock==0 ){
  103921. sqlite3CollapseDatabaseArray(db);
  103922. }
  103923. }
  103924. /*
  103925. ** This routine is called when a commit occurs.
  103926. */
  103927. SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){
  103928. db->mDbFlags &= ~DBFLAG_SchemaChange;
  103929. }
  103930. /*
  103931. ** Delete memory allocated for the column names of a table or view (the
  103932. ** Table.aCol[] array).
  103933. */
  103934. SQLITE_PRIVATE void sqlite3DeleteColumnNames(sqlite3 *db, Table *pTable){
  103935. int i;
  103936. Column *pCol;
  103937. assert( pTable!=0 );
  103938. if( (pCol = pTable->aCol)!=0 ){
  103939. for(i=0; i<pTable->nCol; i++, pCol++){
  103940. assert( pCol->zName==0 || pCol->hName==sqlite3StrIHash(pCol->zName) );
  103941. sqlite3DbFree(db, pCol->zName);
  103942. sqlite3ExprDelete(db, pCol->pDflt);
  103943. sqlite3DbFree(db, pCol->zColl);
  103944. }
  103945. sqlite3DbFree(db, pTable->aCol);
  103946. }
  103947. }
  103948. /*
  103949. ** Remove the memory data structures associated with the given
  103950. ** Table. No changes are made to disk by this routine.
  103951. **
  103952. ** This routine just deletes the data structure. It does not unlink
  103953. ** the table data structure from the hash table. But it does destroy
  103954. ** memory structures of the indices and foreign keys associated with
  103955. ** the table.
  103956. **
  103957. ** The db parameter is optional. It is needed if the Table object
  103958. ** contains lookaside memory. (Table objects in the schema do not use
  103959. ** lookaside memory, but some ephemeral Table objects do.) Or the
  103960. ** db parameter can be used with db->pnBytesFreed to measure the memory
  103961. ** used by the Table object.
  103962. */
  103963. static void SQLITE_NOINLINE deleteTable(sqlite3 *db, Table *pTable){
  103964. Index *pIndex, *pNext;
  103965. #ifdef SQLITE_DEBUG
  103966. /* Record the number of outstanding lookaside allocations in schema Tables
  103967. ** prior to doing any free() operations. Since schema Tables do not use
  103968. ** lookaside, this number should not change.
  103969. **
  103970. ** If malloc has already failed, it may be that it failed while allocating
  103971. ** a Table object that was going to be marked ephemeral. So do not check
  103972. ** that no lookaside memory is used in this case either. */
  103973. int nLookaside = 0;
  103974. if( db && !db->mallocFailed && (pTable->tabFlags & TF_Ephemeral)==0 ){
  103975. nLookaside = sqlite3LookasideUsed(db, 0);
  103976. }
  103977. #endif
  103978. /* Delete all indices associated with this table. */
  103979. for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
  103980. pNext = pIndex->pNext;
  103981. assert( pIndex->pSchema==pTable->pSchema
  103982. || (IsVirtual(pTable) && pIndex->idxType!=SQLITE_IDXTYPE_APPDEF) );
  103983. if( (db==0 || db->pnBytesFreed==0) && !IsVirtual(pTable) ){
  103984. char *zName = pIndex->zName;
  103985. TESTONLY ( Index *pOld = ) sqlite3HashInsert(
  103986. &pIndex->pSchema->idxHash, zName, 0
  103987. );
  103988. assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
  103989. assert( pOld==pIndex || pOld==0 );
  103990. }
  103991. sqlite3FreeIndex(db, pIndex);
  103992. }
  103993. /* Delete any foreign keys attached to this table. */
  103994. sqlite3FkDelete(db, pTable);
  103995. /* Delete the Table structure itself.
  103996. */
  103997. sqlite3DeleteColumnNames(db, pTable);
  103998. sqlite3DbFree(db, pTable->zName);
  103999. sqlite3DbFree(db, pTable->zColAff);
  104000. sqlite3SelectDelete(db, pTable->pSelect);
  104001. sqlite3ExprListDelete(db, pTable->pCheck);
  104002. #ifndef SQLITE_OMIT_VIRTUALTABLE
  104003. sqlite3VtabClear(db, pTable);
  104004. #endif
  104005. sqlite3DbFree(db, pTable);
  104006. /* Verify that no lookaside memory was used by schema tables */
  104007. assert( nLookaside==0 || nLookaside==sqlite3LookasideUsed(db,0) );
  104008. }
  104009. SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
  104010. /* Do not delete the table until the reference count reaches zero. */
  104011. if( !pTable ) return;
  104012. if( ((!db || db->pnBytesFreed==0) && (--pTable->nTabRef)>0) ) return;
  104013. deleteTable(db, pTable);
  104014. }
  104015. /*
  104016. ** Unlink the given table from the hash tables and the delete the
  104017. ** table structure with all its indices and foreign keys.
  104018. */
  104019. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
  104020. Table *p;
  104021. Db *pDb;
  104022. assert( db!=0 );
  104023. assert( iDb>=0 && iDb<db->nDb );
  104024. assert( zTabName );
  104025. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  104026. testcase( zTabName[0]==0 ); /* Zero-length table names are allowed */
  104027. pDb = &db->aDb[iDb];
  104028. p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, 0);
  104029. sqlite3DeleteTable(db, p);
  104030. db->mDbFlags |= DBFLAG_SchemaChange;
  104031. }
  104032. /*
  104033. ** Given a token, return a string that consists of the text of that
  104034. ** token. Space to hold the returned string
  104035. ** is obtained from sqliteMalloc() and must be freed by the calling
  104036. ** function.
  104037. **
  104038. ** Any quotation marks (ex: "name", 'name', [name], or `name`) that
  104039. ** surround the body of the token are removed.
  104040. **
  104041. ** Tokens are often just pointers into the original SQL text and so
  104042. ** are not \000 terminated and are not persistent. The returned string
  104043. ** is \000 terminated and is persistent.
  104044. */
  104045. SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
  104046. char *zName;
  104047. if( pName ){
  104048. zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
  104049. sqlite3Dequote(zName);
  104050. }else{
  104051. zName = 0;
  104052. }
  104053. return zName;
  104054. }
  104055. /*
  104056. ** Open the sqlite_master table stored in database number iDb for
  104057. ** writing. The table is opened using cursor 0.
  104058. */
  104059. SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){
  104060. Vdbe *v = sqlite3GetVdbe(p);
  104061. sqlite3TableLock(p, iDb, MASTER_ROOT, 1, MASTER_NAME);
  104062. sqlite3VdbeAddOp4Int(v, OP_OpenWrite, 0, MASTER_ROOT, iDb, 5);
  104063. if( p->nTab==0 ){
  104064. p->nTab = 1;
  104065. }
  104066. }
  104067. /*
  104068. ** Parameter zName points to a nul-terminated buffer containing the name
  104069. ** of a database ("main", "temp" or the name of an attached db). This
  104070. ** function returns the index of the named database in db->aDb[], or
  104071. ** -1 if the named db cannot be found.
  104072. */
  104073. SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *db, const char *zName){
  104074. int i = -1; /* Database number */
  104075. if( zName ){
  104076. Db *pDb;
  104077. for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
  104078. if( 0==sqlite3_stricmp(pDb->zDbSName, zName) ) break;
  104079. /* "main" is always an acceptable alias for the primary database
  104080. ** even if it has been renamed using SQLITE_DBCONFIG_MAINDBNAME. */
  104081. if( i==0 && 0==sqlite3_stricmp("main", zName) ) break;
  104082. }
  104083. }
  104084. return i;
  104085. }
  104086. /*
  104087. ** The token *pName contains the name of a database (either "main" or
  104088. ** "temp" or the name of an attached db). This routine returns the
  104089. ** index of the named database in db->aDb[], or -1 if the named db
  104090. ** does not exist.
  104091. */
  104092. SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){
  104093. int i; /* Database number */
  104094. char *zName; /* Name we are searching for */
  104095. zName = sqlite3NameFromToken(db, pName);
  104096. i = sqlite3FindDbName(db, zName);
  104097. sqlite3DbFree(db, zName);
  104098. return i;
  104099. }
  104100. /* The table or view or trigger name is passed to this routine via tokens
  104101. ** pName1 and pName2. If the table name was fully qualified, for example:
  104102. **
  104103. ** CREATE TABLE xxx.yyy (...);
  104104. **
  104105. ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
  104106. ** the table name is not fully qualified, i.e.:
  104107. **
  104108. ** CREATE TABLE yyy(...);
  104109. **
  104110. ** Then pName1 is set to "yyy" and pName2 is "".
  104111. **
  104112. ** This routine sets the *ppUnqual pointer to point at the token (pName1 or
  104113. ** pName2) that stores the unqualified table name. The index of the
  104114. ** database "xxx" is returned.
  104115. */
  104116. SQLITE_PRIVATE int sqlite3TwoPartName(
  104117. Parse *pParse, /* Parsing and code generating context */
  104118. Token *pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */
  104119. Token *pName2, /* The "yyy" in the name "xxx.yyy" */
  104120. Token **pUnqual /* Write the unqualified object name here */
  104121. ){
  104122. int iDb; /* Database holding the object */
  104123. sqlite3 *db = pParse->db;
  104124. assert( pName2!=0 );
  104125. if( pName2->n>0 ){
  104126. if( db->init.busy ) {
  104127. sqlite3ErrorMsg(pParse, "corrupt database");
  104128. return -1;
  104129. }
  104130. *pUnqual = pName2;
  104131. iDb = sqlite3FindDb(db, pName1);
  104132. if( iDb<0 ){
  104133. sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
  104134. return -1;
  104135. }
  104136. }else{
  104137. assert( db->init.iDb==0 || db->init.busy || IN_RENAME_OBJECT
  104138. || (db->mDbFlags & DBFLAG_Vacuum)!=0);
  104139. iDb = db->init.iDb;
  104140. *pUnqual = pName1;
  104141. }
  104142. return iDb;
  104143. }
  104144. /*
  104145. ** True if PRAGMA writable_schema is ON
  104146. */
  104147. SQLITE_PRIVATE int sqlite3WritableSchema(sqlite3 *db){
  104148. testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==0 );
  104149. testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==
  104150. SQLITE_WriteSchema );
  104151. testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==
  104152. SQLITE_Defensive );
  104153. testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==
  104154. (SQLITE_WriteSchema|SQLITE_Defensive) );
  104155. return (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==SQLITE_WriteSchema;
  104156. }
  104157. /*
  104158. ** This routine is used to check if the UTF-8 string zName is a legal
  104159. ** unqualified name for a new schema object (table, index, view or
  104160. ** trigger). All names are legal except those that begin with the string
  104161. ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
  104162. ** is reserved for internal use.
  104163. **
  104164. ** When parsing the sqlite_master table, this routine also checks to
  104165. ** make sure the "type", "name", and "tbl_name" columns are consistent
  104166. ** with the SQL.
  104167. */
  104168. SQLITE_PRIVATE int sqlite3CheckObjectName(
  104169. Parse *pParse, /* Parsing context */
  104170. const char *zName, /* Name of the object to check */
  104171. const char *zType, /* Type of this object */
  104172. const char *zTblName /* Parent table name for triggers and indexes */
  104173. ){
  104174. sqlite3 *db = pParse->db;
  104175. if( sqlite3WritableSchema(db) || db->init.imposterTable ){
  104176. /* Skip these error checks for writable_schema=ON */
  104177. return SQLITE_OK;
  104178. }
  104179. if( db->init.busy ){
  104180. if( sqlite3_stricmp(zType, db->init.azInit[0])
  104181. || sqlite3_stricmp(zName, db->init.azInit[1])
  104182. || sqlite3_stricmp(zTblName, db->init.azInit[2])
  104183. ){
  104184. if( sqlite3Config.bExtraSchemaChecks ){
  104185. sqlite3ErrorMsg(pParse, ""); /* corruptSchema() will supply the error */
  104186. return SQLITE_ERROR;
  104187. }
  104188. }
  104189. }else{
  104190. if( (pParse->nested==0 && 0==sqlite3StrNICmp(zName, "sqlite_", 7))
  104191. || (sqlite3ReadOnlyShadowTables(db) && sqlite3ShadowTableName(db, zName))
  104192. ){
  104193. sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s",
  104194. zName);
  104195. return SQLITE_ERROR;
  104196. }
  104197. }
  104198. return SQLITE_OK;
  104199. }
  104200. /*
  104201. ** Return the PRIMARY KEY index of a table
  104202. */
  104203. SQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table *pTab){
  104204. Index *p;
  104205. for(p=pTab->pIndex; p && !IsPrimaryKeyIndex(p); p=p->pNext){}
  104206. return p;
  104207. }
  104208. /*
  104209. ** Convert an table column number into a index column number. That is,
  104210. ** for the column iCol in the table (as defined by the CREATE TABLE statement)
  104211. ** find the (first) offset of that column in index pIdx. Or return -1
  104212. ** if column iCol is not used in index pIdx.
  104213. */
  104214. SQLITE_PRIVATE i16 sqlite3TableColumnToIndex(Index *pIdx, i16 iCol){
  104215. int i;
  104216. for(i=0; i<pIdx->nColumn; i++){
  104217. if( iCol==pIdx->aiColumn[i] ) return i;
  104218. }
  104219. return -1;
  104220. }
  104221. #ifndef SQLITE_OMIT_GENERATED_COLUMNS
  104222. /* Convert a storage column number into a table column number.
  104223. **
  104224. ** The storage column number (0,1,2,....) is the index of the value
  104225. ** as it appears in the record on disk. The true column number
  104226. ** is the index (0,1,2,...) of the column in the CREATE TABLE statement.
  104227. **
  104228. ** The storage column number is less than the table column number if
  104229. ** and only there are VIRTUAL columns to the left.
  104230. **
  104231. ** If SQLITE_OMIT_GENERATED_COLUMNS, this routine is a no-op macro.
  104232. */
  104233. SQLITE_PRIVATE i16 sqlite3StorageColumnToTable(Table *pTab, i16 iCol){
  104234. if( pTab->tabFlags & TF_HasVirtual ){
  104235. int i;
  104236. for(i=0; i<=iCol; i++){
  104237. if( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL ) iCol++;
  104238. }
  104239. }
  104240. return iCol;
  104241. }
  104242. #endif
  104243. #ifndef SQLITE_OMIT_GENERATED_COLUMNS
  104244. /* Convert a table column number into a storage column number.
  104245. **
  104246. ** The storage column number (0,1,2,....) is the index of the value
  104247. ** as it appears in the record on disk. Or, if the input column is
  104248. ** the N-th virtual column (zero-based) then the storage number is
  104249. ** the number of non-virtual columns in the table plus N.
  104250. **
  104251. ** The true column number is the index (0,1,2,...) of the column in
  104252. ** the CREATE TABLE statement.
  104253. **
  104254. ** If the input column is a VIRTUAL column, then it should not appear
  104255. ** in storage. But the value sometimes is cached in registers that
  104256. ** follow the range of registers used to construct storage. This
  104257. ** avoids computing the same VIRTUAL column multiple times, and provides
  104258. ** values for use by OP_Param opcodes in triggers. Hence, if the
  104259. ** input column is a VIRTUAL table, put it after all the other columns.
  104260. **
  104261. ** In the following, N means "normal column", S means STORED, and
  104262. ** V means VIRTUAL. Suppose the CREATE TABLE has columns like this:
  104263. **
  104264. ** CREATE TABLE ex(N,S,V,N,S,V,N,S,V);
  104265. ** -- 0 1 2 3 4 5 6 7 8
  104266. **
  104267. ** Then the mapping from this function is as follows:
  104268. **
  104269. ** INPUTS: 0 1 2 3 4 5 6 7 8
  104270. ** OUTPUTS: 0 1 6 2 3 7 4 5 8
  104271. **
  104272. ** So, in other words, this routine shifts all the virtual columns to
  104273. ** the end.
  104274. **
  104275. ** If SQLITE_OMIT_GENERATED_COLUMNS then there are no virtual columns and
  104276. ** this routine is a no-op macro. If the pTab does not have any virtual
  104277. ** columns, then this routine is no-op that always return iCol. If iCol
  104278. ** is negative (indicating the ROWID column) then this routine return iCol.
  104279. */
  104280. SQLITE_PRIVATE i16 sqlite3TableColumnToStorage(Table *pTab, i16 iCol){
  104281. int i;
  104282. i16 n;
  104283. assert( iCol<pTab->nCol );
  104284. if( (pTab->tabFlags & TF_HasVirtual)==0 || iCol<0 ) return iCol;
  104285. for(i=0, n=0; i<iCol; i++){
  104286. if( (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0 ) n++;
  104287. }
  104288. if( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL ){
  104289. /* iCol is a virtual column itself */
  104290. return pTab->nNVCol + i - n;
  104291. }else{
  104292. /* iCol is a normal or stored column */
  104293. return n;
  104294. }
  104295. }
  104296. #endif
  104297. /*
  104298. ** Begin constructing a new table representation in memory. This is
  104299. ** the first of several action routines that get called in response
  104300. ** to a CREATE TABLE statement. In particular, this routine is called
  104301. ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
  104302. ** flag is true if the table should be stored in the auxiliary database
  104303. ** file instead of in the main database file. This is normally the case
  104304. ** when the "TEMP" or "TEMPORARY" keyword occurs in between
  104305. ** CREATE and TABLE.
  104306. **
  104307. ** The new table record is initialized and put in pParse->pNewTable.
  104308. ** As more of the CREATE TABLE statement is parsed, additional action
  104309. ** routines will be called to add more information to this record.
  104310. ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
  104311. ** is called to complete the construction of the new table record.
  104312. */
  104313. SQLITE_PRIVATE void sqlite3StartTable(
  104314. Parse *pParse, /* Parser context */
  104315. Token *pName1, /* First part of the name of the table or view */
  104316. Token *pName2, /* Second part of the name of the table or view */
  104317. int isTemp, /* True if this is a TEMP table */
  104318. int isView, /* True if this is a VIEW */
  104319. int isVirtual, /* True if this is a VIRTUAL table */
  104320. int noErr /* Do nothing if table already exists */
  104321. ){
  104322. Table *pTable;
  104323. char *zName = 0; /* The name of the new table */
  104324. sqlite3 *db = pParse->db;
  104325. Vdbe *v;
  104326. int iDb; /* Database number to create the table in */
  104327. Token *pName; /* Unqualified name of the table to create */
  104328. if( db->init.busy && db->init.newTnum==1 ){
  104329. /* Special case: Parsing the sqlite_master or sqlite_temp_master schema */
  104330. iDb = db->init.iDb;
  104331. zName = sqlite3DbStrDup(db, SCHEMA_TABLE(iDb));
  104332. pName = pName1;
  104333. }else{
  104334. /* The common case */
  104335. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  104336. if( iDb<0 ) return;
  104337. if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
  104338. /* If creating a temp table, the name may not be qualified. Unless
  104339. ** the database name is "temp" anyway. */
  104340. sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
  104341. return;
  104342. }
  104343. if( !OMIT_TEMPDB && isTemp ) iDb = 1;
  104344. zName = sqlite3NameFromToken(db, pName);
  104345. if( IN_RENAME_OBJECT ){
  104346. sqlite3RenameTokenMap(pParse, (void*)zName, pName);
  104347. }
  104348. }
  104349. pParse->sNameToken = *pName;
  104350. if( zName==0 ) return;
  104351. if( sqlite3CheckObjectName(pParse, zName, isView?"view":"table", zName) ){
  104352. goto begin_table_error;
  104353. }
  104354. if( db->init.iDb==1 ) isTemp = 1;
  104355. #ifndef SQLITE_OMIT_AUTHORIZATION
  104356. assert( isTemp==0 || isTemp==1 );
  104357. assert( isView==0 || isView==1 );
  104358. {
  104359. static const u8 aCode[] = {
  104360. SQLITE_CREATE_TABLE,
  104361. SQLITE_CREATE_TEMP_TABLE,
  104362. SQLITE_CREATE_VIEW,
  104363. SQLITE_CREATE_TEMP_VIEW
  104364. };
  104365. char *zDb = db->aDb[iDb].zDbSName;
  104366. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
  104367. goto begin_table_error;
  104368. }
  104369. if( !isVirtual && sqlite3AuthCheck(pParse, (int)aCode[isTemp+2*isView],
  104370. zName, 0, zDb) ){
  104371. goto begin_table_error;
  104372. }
  104373. }
  104374. #endif
  104375. /* Make sure the new table name does not collide with an existing
  104376. ** index or table name in the same database. Issue an error message if
  104377. ** it does. The exception is if the statement being parsed was passed
  104378. ** to an sqlite3_declare_vtab() call. In that case only the column names
  104379. ** and types will be used, so there is no need to test for namespace
  104380. ** collisions.
  104381. */
  104382. if( !IN_SPECIAL_PARSE ){
  104383. char *zDb = db->aDb[iDb].zDbSName;
  104384. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  104385. goto begin_table_error;
  104386. }
  104387. pTable = sqlite3FindTable(db, zName, zDb);
  104388. if( pTable ){
  104389. if( !noErr ){
  104390. sqlite3ErrorMsg(pParse, "table %T already exists", pName);
  104391. }else{
  104392. assert( !db->init.busy || CORRUPT_DB );
  104393. sqlite3CodeVerifySchema(pParse, iDb);
  104394. }
  104395. goto begin_table_error;
  104396. }
  104397. if( sqlite3FindIndex(db, zName, zDb)!=0 ){
  104398. sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
  104399. goto begin_table_error;
  104400. }
  104401. }
  104402. pTable = sqlite3DbMallocZero(db, sizeof(Table));
  104403. if( pTable==0 ){
  104404. assert( db->mallocFailed );
  104405. pParse->rc = SQLITE_NOMEM_BKPT;
  104406. pParse->nErr++;
  104407. goto begin_table_error;
  104408. }
  104409. pTable->zName = zName;
  104410. pTable->iPKey = -1;
  104411. pTable->pSchema = db->aDb[iDb].pSchema;
  104412. pTable->nTabRef = 1;
  104413. #ifdef SQLITE_DEFAULT_ROWEST
  104414. pTable->nRowLogEst = sqlite3LogEst(SQLITE_DEFAULT_ROWEST);
  104415. #else
  104416. pTable->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
  104417. #endif
  104418. assert( pParse->pNewTable==0 );
  104419. pParse->pNewTable = pTable;
  104420. /* If this is the magic sqlite_sequence table used by autoincrement,
  104421. ** then record a pointer to this table in the main database structure
  104422. ** so that INSERT can find the table easily.
  104423. */
  104424. #ifndef SQLITE_OMIT_AUTOINCREMENT
  104425. if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
  104426. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  104427. pTable->pSchema->pSeqTab = pTable;
  104428. }
  104429. #endif
  104430. /* Begin generating the code that will insert the table record into
  104431. ** the SQLITE_MASTER table. Note in particular that we must go ahead
  104432. ** and allocate the record number for the table entry now. Before any
  104433. ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause
  104434. ** indices to be created and the table record must come before the
  104435. ** indices. Hence, the record number for the table must be allocated
  104436. ** now.
  104437. */
  104438. if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
  104439. int addr1;
  104440. int fileFormat;
  104441. int reg1, reg2, reg3;
  104442. /* nullRow[] is an OP_Record encoding of a row containing 5 NULLs */
  104443. static const char nullRow[] = { 6, 0, 0, 0, 0, 0 };
  104444. sqlite3BeginWriteOperation(pParse, 1, iDb);
  104445. #ifndef SQLITE_OMIT_VIRTUALTABLE
  104446. if( isVirtual ){
  104447. sqlite3VdbeAddOp0(v, OP_VBegin);
  104448. }
  104449. #endif
  104450. /* If the file format and encoding in the database have not been set,
  104451. ** set them now.
  104452. */
  104453. reg1 = pParse->regRowid = ++pParse->nMem;
  104454. reg2 = pParse->regRoot = ++pParse->nMem;
  104455. reg3 = ++pParse->nMem;
  104456. sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
  104457. sqlite3VdbeUsesBtree(v, iDb);
  104458. addr1 = sqlite3VdbeAddOp1(v, OP_If, reg3); VdbeCoverage(v);
  104459. fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
  104460. 1 : SQLITE_MAX_FILE_FORMAT;
  104461. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, fileFormat);
  104462. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, ENC(db));
  104463. sqlite3VdbeJumpHere(v, addr1);
  104464. /* This just creates a place-holder record in the sqlite_master table.
  104465. ** The record created does not contain anything yet. It will be replaced
  104466. ** by the real entry in code generated at sqlite3EndTable().
  104467. **
  104468. ** The rowid for the new entry is left in register pParse->regRowid.
  104469. ** The root page number of the new table is left in reg pParse->regRoot.
  104470. ** The rowid and root page number values are needed by the code that
  104471. ** sqlite3EndTable will generate.
  104472. */
  104473. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
  104474. if( isView || isVirtual ){
  104475. sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
  104476. }else
  104477. #endif
  104478. {
  104479. pParse->addrCrTab =
  104480. sqlite3VdbeAddOp3(v, OP_CreateBtree, iDb, reg2, BTREE_INTKEY);
  104481. }
  104482. sqlite3OpenMasterTable(pParse, iDb);
  104483. sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
  104484. sqlite3VdbeAddOp4(v, OP_Blob, 6, reg3, 0, nullRow, P4_STATIC);
  104485. sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
  104486. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  104487. sqlite3VdbeAddOp0(v, OP_Close);
  104488. }
  104489. /* Normal (non-error) return. */
  104490. return;
  104491. /* If an error occurs, we jump here */
  104492. begin_table_error:
  104493. sqlite3DbFree(db, zName);
  104494. return;
  104495. }
  104496. /* Set properties of a table column based on the (magical)
  104497. ** name of the column.
  104498. */
  104499. #if SQLITE_ENABLE_HIDDEN_COLUMNS
  104500. SQLITE_PRIVATE void sqlite3ColumnPropertiesFromName(Table *pTab, Column *pCol){
  104501. if( sqlite3_strnicmp(pCol->zName, "__hidden__", 10)==0 ){
  104502. pCol->colFlags |= COLFLAG_HIDDEN;
  104503. }else if( pTab && pCol!=pTab->aCol && (pCol[-1].colFlags & COLFLAG_HIDDEN) ){
  104504. pTab->tabFlags |= TF_OOOHidden;
  104505. }
  104506. }
  104507. #endif
  104508. /*
  104509. ** Add a new column to the table currently being constructed.
  104510. **
  104511. ** The parser calls this routine once for each column declaration
  104512. ** in a CREATE TABLE statement. sqlite3StartTable() gets called
  104513. ** first to get things going. Then this routine is called for each
  104514. ** column.
  104515. */
  104516. SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName, Token *pType){
  104517. Table *p;
  104518. int i;
  104519. char *z;
  104520. char *zType;
  104521. Column *pCol;
  104522. sqlite3 *db = pParse->db;
  104523. if( (p = pParse->pNewTable)==0 ) return;
  104524. if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  104525. sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
  104526. return;
  104527. }
  104528. z = sqlite3DbMallocRaw(db, pName->n + pType->n + 2);
  104529. if( z==0 ) return;
  104530. if( IN_RENAME_OBJECT ) sqlite3RenameTokenMap(pParse, (void*)z, pName);
  104531. memcpy(z, pName->z, pName->n);
  104532. z[pName->n] = 0;
  104533. sqlite3Dequote(z);
  104534. for(i=0; i<p->nCol; i++){
  104535. if( sqlite3_stricmp(z, p->aCol[i].zName)==0 ){
  104536. sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
  104537. sqlite3DbFree(db, z);
  104538. return;
  104539. }
  104540. }
  104541. if( (p->nCol & 0x7)==0 ){
  104542. Column *aNew;
  104543. aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
  104544. if( aNew==0 ){
  104545. sqlite3DbFree(db, z);
  104546. return;
  104547. }
  104548. p->aCol = aNew;
  104549. }
  104550. pCol = &p->aCol[p->nCol];
  104551. memset(pCol, 0, sizeof(p->aCol[0]));
  104552. pCol->zName = z;
  104553. pCol->hName = sqlite3StrIHash(z);
  104554. sqlite3ColumnPropertiesFromName(p, pCol);
  104555. if( pType->n==0 ){
  104556. /* If there is no type specified, columns have the default affinity
  104557. ** 'BLOB' with a default size of 4 bytes. */
  104558. pCol->affinity = SQLITE_AFF_BLOB;
  104559. pCol->szEst = 1;
  104560. #ifdef SQLITE_ENABLE_SORTER_REFERENCES
  104561. if( 4>=sqlite3GlobalConfig.szSorterRef ){
  104562. pCol->colFlags |= COLFLAG_SORTERREF;
  104563. }
  104564. #endif
  104565. }else{
  104566. zType = z + sqlite3Strlen30(z) + 1;
  104567. memcpy(zType, pType->z, pType->n);
  104568. zType[pType->n] = 0;
  104569. sqlite3Dequote(zType);
  104570. pCol->affinity = sqlite3AffinityType(zType, pCol);
  104571. pCol->colFlags |= COLFLAG_HASTYPE;
  104572. }
  104573. p->nCol++;
  104574. p->nNVCol++;
  104575. pParse->constraintName.n = 0;
  104576. }
  104577. /*
  104578. ** This routine is called by the parser while in the middle of
  104579. ** parsing a CREATE TABLE statement. A "NOT NULL" constraint has
  104580. ** been seen on a column. This routine sets the notNull flag on
  104581. ** the column currently under construction.
  104582. */
  104583. SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){
  104584. Table *p;
  104585. Column *pCol;
  104586. p = pParse->pNewTable;
  104587. if( p==0 || NEVER(p->nCol<1) ) return;
  104588. pCol = &p->aCol[p->nCol-1];
  104589. pCol->notNull = (u8)onError;
  104590. p->tabFlags |= TF_HasNotNull;
  104591. /* Set the uniqNotNull flag on any UNIQUE or PK indexes already created
  104592. ** on this column. */
  104593. if( pCol->colFlags & COLFLAG_UNIQUE ){
  104594. Index *pIdx;
  104595. for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
  104596. assert( pIdx->nKeyCol==1 && pIdx->onError!=OE_None );
  104597. if( pIdx->aiColumn[0]==p->nCol-1 ){
  104598. pIdx->uniqNotNull = 1;
  104599. }
  104600. }
  104601. }
  104602. }
  104603. /*
  104604. ** Scan the column type name zType (length nType) and return the
  104605. ** associated affinity type.
  104606. **
  104607. ** This routine does a case-independent search of zType for the
  104608. ** substrings in the following table. If one of the substrings is
  104609. ** found, the corresponding affinity is returned. If zType contains
  104610. ** more than one of the substrings, entries toward the top of
  104611. ** the table take priority. For example, if zType is 'BLOBINT',
  104612. ** SQLITE_AFF_INTEGER is returned.
  104613. **
  104614. ** Substring | Affinity
  104615. ** --------------------------------
  104616. ** 'INT' | SQLITE_AFF_INTEGER
  104617. ** 'CHAR' | SQLITE_AFF_TEXT
  104618. ** 'CLOB' | SQLITE_AFF_TEXT
  104619. ** 'TEXT' | SQLITE_AFF_TEXT
  104620. ** 'BLOB' | SQLITE_AFF_BLOB
  104621. ** 'REAL' | SQLITE_AFF_REAL
  104622. ** 'FLOA' | SQLITE_AFF_REAL
  104623. ** 'DOUB' | SQLITE_AFF_REAL
  104624. **
  104625. ** If none of the substrings in the above table are found,
  104626. ** SQLITE_AFF_NUMERIC is returned.
  104627. */
  104628. SQLITE_PRIVATE char sqlite3AffinityType(const char *zIn, Column *pCol){
  104629. u32 h = 0;
  104630. char aff = SQLITE_AFF_NUMERIC;
  104631. const char *zChar = 0;
  104632. assert( zIn!=0 );
  104633. while( zIn[0] ){
  104634. h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
  104635. zIn++;
  104636. if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */
  104637. aff = SQLITE_AFF_TEXT;
  104638. zChar = zIn;
  104639. }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */
  104640. aff = SQLITE_AFF_TEXT;
  104641. }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */
  104642. aff = SQLITE_AFF_TEXT;
  104643. }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */
  104644. && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
  104645. aff = SQLITE_AFF_BLOB;
  104646. if( zIn[0]=='(' ) zChar = zIn;
  104647. #ifndef SQLITE_OMIT_FLOATING_POINT
  104648. }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */
  104649. && aff==SQLITE_AFF_NUMERIC ){
  104650. aff = SQLITE_AFF_REAL;
  104651. }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */
  104652. && aff==SQLITE_AFF_NUMERIC ){
  104653. aff = SQLITE_AFF_REAL;
  104654. }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */
  104655. && aff==SQLITE_AFF_NUMERIC ){
  104656. aff = SQLITE_AFF_REAL;
  104657. #endif
  104658. }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */
  104659. aff = SQLITE_AFF_INTEGER;
  104660. break;
  104661. }
  104662. }
  104663. /* If pCol is not NULL, store an estimate of the field size. The
  104664. ** estimate is scaled so that the size of an integer is 1. */
  104665. if( pCol ){
  104666. int v = 0; /* default size is approx 4 bytes */
  104667. if( aff<SQLITE_AFF_NUMERIC ){
  104668. if( zChar ){
  104669. while( zChar[0] ){
  104670. if( sqlite3Isdigit(zChar[0]) ){
  104671. /* BLOB(k), VARCHAR(k), CHAR(k) -> r=(k/4+1) */
  104672. sqlite3GetInt32(zChar, &v);
  104673. break;
  104674. }
  104675. zChar++;
  104676. }
  104677. }else{
  104678. v = 16; /* BLOB, TEXT, CLOB -> r=5 (approx 20 bytes)*/
  104679. }
  104680. }
  104681. #ifdef SQLITE_ENABLE_SORTER_REFERENCES
  104682. if( v>=sqlite3GlobalConfig.szSorterRef ){
  104683. pCol->colFlags |= COLFLAG_SORTERREF;
  104684. }
  104685. #endif
  104686. v = v/4 + 1;
  104687. if( v>255 ) v = 255;
  104688. pCol->szEst = v;
  104689. }
  104690. return aff;
  104691. }
  104692. /*
  104693. ** The expression is the default value for the most recently added column
  104694. ** of the table currently under construction.
  104695. **
  104696. ** Default value expressions must be constant. Raise an exception if this
  104697. ** is not the case.
  104698. **
  104699. ** This routine is called by the parser while in the middle of
  104700. ** parsing a CREATE TABLE statement.
  104701. */
  104702. SQLITE_PRIVATE void sqlite3AddDefaultValue(
  104703. Parse *pParse, /* Parsing context */
  104704. Expr *pExpr, /* The parsed expression of the default value */
  104705. const char *zStart, /* Start of the default value text */
  104706. const char *zEnd /* First character past end of defaut value text */
  104707. ){
  104708. Table *p;
  104709. Column *pCol;
  104710. sqlite3 *db = pParse->db;
  104711. p = pParse->pNewTable;
  104712. if( p!=0 ){
  104713. int isInit = db->init.busy && db->init.iDb!=1;
  104714. pCol = &(p->aCol[p->nCol-1]);
  104715. if( !sqlite3ExprIsConstantOrFunction(pExpr, isInit) ){
  104716. sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
  104717. pCol->zName);
  104718. #ifndef SQLITE_OMIT_GENERATED_COLUMNS
  104719. }else if( pCol->colFlags & COLFLAG_GENERATED ){
  104720. testcase( pCol->colFlags & COLFLAG_VIRTUAL );
  104721. testcase( pCol->colFlags & COLFLAG_STORED );
  104722. sqlite3ErrorMsg(pParse, "cannot use DEFAULT on a generated column");
  104723. #endif
  104724. }else{
  104725. /* A copy of pExpr is used instead of the original, as pExpr contains
  104726. ** tokens that point to volatile memory.
  104727. */
  104728. Expr x;
  104729. sqlite3ExprDelete(db, pCol->pDflt);
  104730. memset(&x, 0, sizeof(x));
  104731. x.op = TK_SPAN;
  104732. x.u.zToken = sqlite3DbSpanDup(db, zStart, zEnd);
  104733. x.pLeft = pExpr;
  104734. x.flags = EP_Skip;
  104735. pCol->pDflt = sqlite3ExprDup(db, &x, EXPRDUP_REDUCE);
  104736. sqlite3DbFree(db, x.u.zToken);
  104737. }
  104738. }
  104739. if( IN_RENAME_OBJECT ){
  104740. sqlite3RenameExprUnmap(pParse, pExpr);
  104741. }
  104742. sqlite3ExprDelete(db, pExpr);
  104743. }
  104744. /*
  104745. ** Backwards Compatibility Hack:
  104746. **
  104747. ** Historical versions of SQLite accepted strings as column names in
  104748. ** indexes and PRIMARY KEY constraints and in UNIQUE constraints. Example:
  104749. **
  104750. ** CREATE TABLE xyz(a,b,c,d,e,PRIMARY KEY('a'),UNIQUE('b','c' COLLATE trim)
  104751. ** CREATE INDEX abc ON xyz('c','d' DESC,'e' COLLATE nocase DESC);
  104752. **
  104753. ** This is goofy. But to preserve backwards compatibility we continue to
  104754. ** accept it. This routine does the necessary conversion. It converts
  104755. ** the expression given in its argument from a TK_STRING into a TK_ID
  104756. ** if the expression is just a TK_STRING with an optional COLLATE clause.
  104757. ** If the expression is anything other than TK_STRING, the expression is
  104758. ** unchanged.
  104759. */
  104760. static void sqlite3StringToId(Expr *p){
  104761. if( p->op==TK_STRING ){
  104762. p->op = TK_ID;
  104763. }else if( p->op==TK_COLLATE && p->pLeft->op==TK_STRING ){
  104764. p->pLeft->op = TK_ID;
  104765. }
  104766. }
  104767. /*
  104768. ** Tag the given column as being part of the PRIMARY KEY
  104769. */
  104770. static void makeColumnPartOfPrimaryKey(Parse *pParse, Column *pCol){
  104771. pCol->colFlags |= COLFLAG_PRIMKEY;
  104772. #ifndef SQLITE_OMIT_GENERATED_COLUMNS
  104773. if( pCol->colFlags & COLFLAG_GENERATED ){
  104774. testcase( pCol->colFlags & COLFLAG_VIRTUAL );
  104775. testcase( pCol->colFlags & COLFLAG_STORED );
  104776. sqlite3ErrorMsg(pParse,
  104777. "generated columns cannot be part of the PRIMARY KEY");
  104778. }
  104779. #endif
  104780. }
  104781. /*
  104782. ** Designate the PRIMARY KEY for the table. pList is a list of names
  104783. ** of columns that form the primary key. If pList is NULL, then the
  104784. ** most recently added column of the table is the primary key.
  104785. **
  104786. ** A table can have at most one primary key. If the table already has
  104787. ** a primary key (and this is the second primary key) then create an
  104788. ** error.
  104789. **
  104790. ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
  104791. ** then we will try to use that column as the rowid. Set the Table.iPKey
  104792. ** field of the table under construction to be the index of the
  104793. ** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is
  104794. ** no INTEGER PRIMARY KEY.
  104795. **
  104796. ** If the key is not an INTEGER PRIMARY KEY, then create a unique
  104797. ** index for the key. No index is created for INTEGER PRIMARY KEYs.
  104798. */
  104799. SQLITE_PRIVATE void sqlite3AddPrimaryKey(
  104800. Parse *pParse, /* Parsing context */
  104801. ExprList *pList, /* List of field names to be indexed */
  104802. int onError, /* What to do with a uniqueness conflict */
  104803. int autoInc, /* True if the AUTOINCREMENT keyword is present */
  104804. int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */
  104805. ){
  104806. Table *pTab = pParse->pNewTable;
  104807. Column *pCol = 0;
  104808. int iCol = -1, i;
  104809. int nTerm;
  104810. if( pTab==0 ) goto primary_key_exit;
  104811. if( pTab->tabFlags & TF_HasPrimaryKey ){
  104812. sqlite3ErrorMsg(pParse,
  104813. "table \"%s\" has more than one primary key", pTab->zName);
  104814. goto primary_key_exit;
  104815. }
  104816. pTab->tabFlags |= TF_HasPrimaryKey;
  104817. if( pList==0 ){
  104818. iCol = pTab->nCol - 1;
  104819. pCol = &pTab->aCol[iCol];
  104820. makeColumnPartOfPrimaryKey(pParse, pCol);
  104821. nTerm = 1;
  104822. }else{
  104823. nTerm = pList->nExpr;
  104824. for(i=0; i<nTerm; i++){
  104825. Expr *pCExpr = sqlite3ExprSkipCollate(pList->a[i].pExpr);
  104826. assert( pCExpr!=0 );
  104827. sqlite3StringToId(pCExpr);
  104828. if( pCExpr->op==TK_ID ){
  104829. const char *zCName = pCExpr->u.zToken;
  104830. for(iCol=0; iCol<pTab->nCol; iCol++){
  104831. if( sqlite3StrICmp(zCName, pTab->aCol[iCol].zName)==0 ){
  104832. pCol = &pTab->aCol[iCol];
  104833. makeColumnPartOfPrimaryKey(pParse, pCol);
  104834. break;
  104835. }
  104836. }
  104837. }
  104838. }
  104839. }
  104840. if( nTerm==1
  104841. && pCol
  104842. && sqlite3StrICmp(sqlite3ColumnType(pCol,""), "INTEGER")==0
  104843. && sortOrder!=SQLITE_SO_DESC
  104844. ){
  104845. if( IN_RENAME_OBJECT && pList ){
  104846. Expr *pCExpr = sqlite3ExprSkipCollate(pList->a[0].pExpr);
  104847. sqlite3RenameTokenRemap(pParse, &pTab->iPKey, pCExpr);
  104848. }
  104849. pTab->iPKey = iCol;
  104850. pTab->keyConf = (u8)onError;
  104851. assert( autoInc==0 || autoInc==1 );
  104852. pTab->tabFlags |= autoInc*TF_Autoincrement;
  104853. if( pList ) pParse->iPkSortOrder = pList->a[0].sortFlags;
  104854. (void)sqlite3HasExplicitNulls(pParse, pList);
  104855. }else if( autoInc ){
  104856. #ifndef SQLITE_OMIT_AUTOINCREMENT
  104857. sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
  104858. "INTEGER PRIMARY KEY");
  104859. #endif
  104860. }else{
  104861. sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0,
  104862. 0, sortOrder, 0, SQLITE_IDXTYPE_PRIMARYKEY);
  104863. pList = 0;
  104864. }
  104865. primary_key_exit:
  104866. sqlite3ExprListDelete(pParse->db, pList);
  104867. return;
  104868. }
  104869. /*
  104870. ** Add a new CHECK constraint to the table currently under construction.
  104871. */
  104872. SQLITE_PRIVATE void sqlite3AddCheckConstraint(
  104873. Parse *pParse, /* Parsing context */
  104874. Expr *pCheckExpr /* The check expression */
  104875. ){
  104876. #ifndef SQLITE_OMIT_CHECK
  104877. Table *pTab = pParse->pNewTable;
  104878. sqlite3 *db = pParse->db;
  104879. if( pTab && !IN_DECLARE_VTAB
  104880. && !sqlite3BtreeIsReadonly(db->aDb[db->init.iDb].pBt)
  104881. ){
  104882. pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr);
  104883. if( pParse->constraintName.n ){
  104884. sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1);
  104885. }
  104886. }else
  104887. #endif
  104888. {
  104889. sqlite3ExprDelete(pParse->db, pCheckExpr);
  104890. }
  104891. }
  104892. /*
  104893. ** Set the collation function of the most recently parsed table column
  104894. ** to the CollSeq given.
  104895. */
  104896. SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){
  104897. Table *p;
  104898. int i;
  104899. char *zColl; /* Dequoted name of collation sequence */
  104900. sqlite3 *db;
  104901. if( (p = pParse->pNewTable)==0 ) return;
  104902. i = p->nCol-1;
  104903. db = pParse->db;
  104904. zColl = sqlite3NameFromToken(db, pToken);
  104905. if( !zColl ) return;
  104906. if( sqlite3LocateCollSeq(pParse, zColl) ){
  104907. Index *pIdx;
  104908. sqlite3DbFree(db, p->aCol[i].zColl);
  104909. p->aCol[i].zColl = zColl;
  104910. /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
  104911. ** then an index may have been created on this column before the
  104912. ** collation type was added. Correct this if it is the case.
  104913. */
  104914. for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
  104915. assert( pIdx->nKeyCol==1 );
  104916. if( pIdx->aiColumn[0]==i ){
  104917. pIdx->azColl[0] = p->aCol[i].zColl;
  104918. }
  104919. }
  104920. }else{
  104921. sqlite3DbFree(db, zColl);
  104922. }
  104923. }
  104924. /* Change the most recently parsed column to be a GENERATED ALWAYS AS
  104925. ** column.
  104926. */
  104927. SQLITE_PRIVATE void sqlite3AddGenerated(Parse *pParse, Expr *pExpr, Token *pType){
  104928. #ifndef SQLITE_OMIT_GENERATED_COLUMNS
  104929. u8 eType = COLFLAG_VIRTUAL;
  104930. Table *pTab = pParse->pNewTable;
  104931. Column *pCol;
  104932. if( pTab==0 ){
  104933. /* generated column in an CREATE TABLE IF NOT EXISTS that already exists */
  104934. goto generated_done;
  104935. }
  104936. pCol = &(pTab->aCol[pTab->nCol-1]);
  104937. if( IN_DECLARE_VTAB ){
  104938. sqlite3ErrorMsg(pParse, "virtual tables cannot use computed columns");
  104939. goto generated_done;
  104940. }
  104941. if( pCol->pDflt ) goto generated_error;
  104942. if( pType ){
  104943. if( pType->n==7 && sqlite3StrNICmp("virtual",pType->z,7)==0 ){
  104944. /* no-op */
  104945. }else if( pType->n==6 && sqlite3StrNICmp("stored",pType->z,6)==0 ){
  104946. eType = COLFLAG_STORED;
  104947. }else{
  104948. goto generated_error;
  104949. }
  104950. }
  104951. if( eType==COLFLAG_VIRTUAL ) pTab->nNVCol--;
  104952. pCol->colFlags |= eType;
  104953. assert( TF_HasVirtual==COLFLAG_VIRTUAL );
  104954. assert( TF_HasStored==COLFLAG_STORED );
  104955. pTab->tabFlags |= eType;
  104956. if( pCol->colFlags & COLFLAG_PRIMKEY ){
  104957. makeColumnPartOfPrimaryKey(pParse, pCol); /* For the error message */
  104958. }
  104959. pCol->pDflt = pExpr;
  104960. pExpr = 0;
  104961. goto generated_done;
  104962. generated_error:
  104963. sqlite3ErrorMsg(pParse, "error in generated column \"%s\"",
  104964. pCol->zName);
  104965. generated_done:
  104966. sqlite3ExprDelete(pParse->db, pExpr);
  104967. #else
  104968. /* Throw and error for the GENERATED ALWAYS AS clause if the
  104969. ** SQLITE_OMIT_GENERATED_COLUMNS compile-time option is used. */
  104970. sqlite3ErrorMsg(pParse, "generated columns not supported");
  104971. sqlite3ExprDelete(pParse->db, pExpr);
  104972. #endif
  104973. }
  104974. /*
  104975. ** Generate code that will increment the schema cookie.
  104976. **
  104977. ** The schema cookie is used to determine when the schema for the
  104978. ** database changes. After each schema change, the cookie value
  104979. ** changes. When a process first reads the schema it records the
  104980. ** cookie. Thereafter, whenever it goes to access the database,
  104981. ** it checks the cookie to make sure the schema has not changed
  104982. ** since it was last read.
  104983. **
  104984. ** This plan is not completely bullet-proof. It is possible for
  104985. ** the schema to change multiple times and for the cookie to be
  104986. ** set back to prior value. But schema changes are infrequent
  104987. ** and the probability of hitting the same cookie value is only
  104988. ** 1 chance in 2^32. So we're safe enough.
  104989. **
  104990. ** IMPLEMENTATION-OF: R-34230-56049 SQLite automatically increments
  104991. ** the schema-version whenever the schema changes.
  104992. */
  104993. SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){
  104994. sqlite3 *db = pParse->db;
  104995. Vdbe *v = pParse->pVdbe;
  104996. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  104997. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION,
  104998. (int)(1+(unsigned)db->aDb[iDb].pSchema->schema_cookie));
  104999. }
  105000. /*
  105001. ** Measure the number of characters needed to output the given
  105002. ** identifier. The number returned includes any quotes used
  105003. ** but does not include the null terminator.
  105004. **
  105005. ** The estimate is conservative. It might be larger that what is
  105006. ** really needed.
  105007. */
  105008. static int identLength(const char *z){
  105009. int n;
  105010. for(n=0; *z; n++, z++){
  105011. if( *z=='"' ){ n++; }
  105012. }
  105013. return n + 2;
  105014. }
  105015. /*
  105016. ** The first parameter is a pointer to an output buffer. The second
  105017. ** parameter is a pointer to an integer that contains the offset at
  105018. ** which to write into the output buffer. This function copies the
  105019. ** nul-terminated string pointed to by the third parameter, zSignedIdent,
  105020. ** to the specified offset in the buffer and updates *pIdx to refer
  105021. ** to the first byte after the last byte written before returning.
  105022. **
  105023. ** If the string zSignedIdent consists entirely of alpha-numeric
  105024. ** characters, does not begin with a digit and is not an SQL keyword,
  105025. ** then it is copied to the output buffer exactly as it is. Otherwise,
  105026. ** it is quoted using double-quotes.
  105027. */
  105028. static void identPut(char *z, int *pIdx, char *zSignedIdent){
  105029. unsigned char *zIdent = (unsigned char*)zSignedIdent;
  105030. int i, j, needQuote;
  105031. i = *pIdx;
  105032. for(j=0; zIdent[j]; j++){
  105033. if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
  105034. }
  105035. needQuote = sqlite3Isdigit(zIdent[0])
  105036. || sqlite3KeywordCode(zIdent, j)!=TK_ID
  105037. || zIdent[j]!=0
  105038. || j==0;
  105039. if( needQuote ) z[i++] = '"';
  105040. for(j=0; zIdent[j]; j++){
  105041. z[i++] = zIdent[j];
  105042. if( zIdent[j]=='"' ) z[i++] = '"';
  105043. }
  105044. if( needQuote ) z[i++] = '"';
  105045. z[i] = 0;
  105046. *pIdx = i;
  105047. }
  105048. /*
  105049. ** Generate a CREATE TABLE statement appropriate for the given
  105050. ** table. Memory to hold the text of the statement is obtained
  105051. ** from sqliteMalloc() and must be freed by the calling function.
  105052. */
  105053. static char *createTableStmt(sqlite3 *db, Table *p){
  105054. int i, k, n;
  105055. char *zStmt;
  105056. char *zSep, *zSep2, *zEnd;
  105057. Column *pCol;
  105058. n = 0;
  105059. for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
  105060. n += identLength(pCol->zName) + 5;
  105061. }
  105062. n += identLength(p->zName);
  105063. if( n<50 ){
  105064. zSep = "";
  105065. zSep2 = ",";
  105066. zEnd = ")";
  105067. }else{
  105068. zSep = "\n ";
  105069. zSep2 = ",\n ";
  105070. zEnd = "\n)";
  105071. }
  105072. n += 35 + 6*p->nCol;
  105073. zStmt = sqlite3DbMallocRaw(0, n);
  105074. if( zStmt==0 ){
  105075. sqlite3OomFault(db);
  105076. return 0;
  105077. }
  105078. sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
  105079. k = sqlite3Strlen30(zStmt);
  105080. identPut(zStmt, &k, p->zName);
  105081. zStmt[k++] = '(';
  105082. for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
  105083. static const char * const azType[] = {
  105084. /* SQLITE_AFF_BLOB */ "",
  105085. /* SQLITE_AFF_TEXT */ " TEXT",
  105086. /* SQLITE_AFF_NUMERIC */ " NUM",
  105087. /* SQLITE_AFF_INTEGER */ " INT",
  105088. /* SQLITE_AFF_REAL */ " REAL"
  105089. };
  105090. int len;
  105091. const char *zType;
  105092. sqlite3_snprintf(n-k, &zStmt[k], zSep);
  105093. k += sqlite3Strlen30(&zStmt[k]);
  105094. zSep = zSep2;
  105095. identPut(zStmt, &k, pCol->zName);
  105096. assert( pCol->affinity-SQLITE_AFF_BLOB >= 0 );
  105097. assert( pCol->affinity-SQLITE_AFF_BLOB < ArraySize(azType) );
  105098. testcase( pCol->affinity==SQLITE_AFF_BLOB );
  105099. testcase( pCol->affinity==SQLITE_AFF_TEXT );
  105100. testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
  105101. testcase( pCol->affinity==SQLITE_AFF_INTEGER );
  105102. testcase( pCol->affinity==SQLITE_AFF_REAL );
  105103. zType = azType[pCol->affinity - SQLITE_AFF_BLOB];
  105104. len = sqlite3Strlen30(zType);
  105105. assert( pCol->affinity==SQLITE_AFF_BLOB
  105106. || pCol->affinity==sqlite3AffinityType(zType, 0) );
  105107. memcpy(&zStmt[k], zType, len);
  105108. k += len;
  105109. assert( k<=n );
  105110. }
  105111. sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
  105112. return zStmt;
  105113. }
  105114. /*
  105115. ** Resize an Index object to hold N columns total. Return SQLITE_OK
  105116. ** on success and SQLITE_NOMEM on an OOM error.
  105117. */
  105118. static int resizeIndexObject(sqlite3 *db, Index *pIdx, int N){
  105119. char *zExtra;
  105120. int nByte;
  105121. if( pIdx->nColumn>=N ) return SQLITE_OK;
  105122. assert( pIdx->isResized==0 );
  105123. nByte = (sizeof(char*) + sizeof(i16) + 1)*N;
  105124. zExtra = sqlite3DbMallocZero(db, nByte);
  105125. if( zExtra==0 ) return SQLITE_NOMEM_BKPT;
  105126. memcpy(zExtra, pIdx->azColl, sizeof(char*)*pIdx->nColumn);
  105127. pIdx->azColl = (const char**)zExtra;
  105128. zExtra += sizeof(char*)*N;
  105129. memcpy(zExtra, pIdx->aiColumn, sizeof(i16)*pIdx->nColumn);
  105130. pIdx->aiColumn = (i16*)zExtra;
  105131. zExtra += sizeof(i16)*N;
  105132. memcpy(zExtra, pIdx->aSortOrder, pIdx->nColumn);
  105133. pIdx->aSortOrder = (u8*)zExtra;
  105134. pIdx->nColumn = N;
  105135. pIdx->isResized = 1;
  105136. return SQLITE_OK;
  105137. }
  105138. /*
  105139. ** Estimate the total row width for a table.
  105140. */
  105141. static void estimateTableWidth(Table *pTab){
  105142. unsigned wTable = 0;
  105143. const Column *pTabCol;
  105144. int i;
  105145. for(i=pTab->nCol, pTabCol=pTab->aCol; i>0; i--, pTabCol++){
  105146. wTable += pTabCol->szEst;
  105147. }
  105148. if( pTab->iPKey<0 ) wTable++;
  105149. pTab->szTabRow = sqlite3LogEst(wTable*4);
  105150. }
  105151. /*
  105152. ** Estimate the average size of a row for an index.
  105153. */
  105154. static void estimateIndexWidth(Index *pIdx){
  105155. unsigned wIndex = 0;
  105156. int i;
  105157. const Column *aCol = pIdx->pTable->aCol;
  105158. for(i=0; i<pIdx->nColumn; i++){
  105159. i16 x = pIdx->aiColumn[i];
  105160. assert( x<pIdx->pTable->nCol );
  105161. wIndex += x<0 ? 1 : aCol[pIdx->aiColumn[i]].szEst;
  105162. }
  105163. pIdx->szIdxRow = sqlite3LogEst(wIndex*4);
  105164. }
  105165. /* Return true if column number x is any of the first nCol entries of aiCol[].
  105166. ** This is used to determine if the column number x appears in any of the
  105167. ** first nCol entries of an index.
  105168. */
  105169. static int hasColumn(const i16 *aiCol, int nCol, int x){
  105170. while( nCol-- > 0 ){
  105171. assert( aiCol[0]>=0 );
  105172. if( x==*(aiCol++) ){
  105173. return 1;
  105174. }
  105175. }
  105176. return 0;
  105177. }
  105178. /*
  105179. ** Return true if any of the first nKey entries of index pIdx exactly
  105180. ** match the iCol-th entry of pPk. pPk is always a WITHOUT ROWID
  105181. ** PRIMARY KEY index. pIdx is an index on the same table. pIdx may
  105182. ** or may not be the same index as pPk.
  105183. **
  105184. ** The first nKey entries of pIdx are guaranteed to be ordinary columns,
  105185. ** not a rowid or expression.
  105186. **
  105187. ** This routine differs from hasColumn() in that both the column and the
  105188. ** collating sequence must match for this routine, but for hasColumn() only
  105189. ** the column name must match.
  105190. */
  105191. static int isDupColumn(Index *pIdx, int nKey, Index *pPk, int iCol){
  105192. int i, j;
  105193. assert( nKey<=pIdx->nColumn );
  105194. assert( iCol<MAX(pPk->nColumn,pPk->nKeyCol) );
  105195. assert( pPk->idxType==SQLITE_IDXTYPE_PRIMARYKEY );
  105196. assert( pPk->pTable->tabFlags & TF_WithoutRowid );
  105197. assert( pPk->pTable==pIdx->pTable );
  105198. testcase( pPk==pIdx );
  105199. j = pPk->aiColumn[iCol];
  105200. assert( j!=XN_ROWID && j!=XN_EXPR );
  105201. for(i=0; i<nKey; i++){
  105202. assert( pIdx->aiColumn[i]>=0 || j>=0 );
  105203. if( pIdx->aiColumn[i]==j
  105204. && sqlite3StrICmp(pIdx->azColl[i], pPk->azColl[iCol])==0
  105205. ){
  105206. return 1;
  105207. }
  105208. }
  105209. return 0;
  105210. }
  105211. /* Recompute the colNotIdxed field of the Index.
  105212. **
  105213. ** colNotIdxed is a bitmask that has a 0 bit representing each indexed
  105214. ** columns that are within the first 63 columns of the table. The
  105215. ** high-order bit of colNotIdxed is always 1. All unindexed columns
  105216. ** of the table have a 1.
  105217. **
  105218. ** 2019-10-24: For the purpose of this computation, virtual columns are
  105219. ** not considered to be covered by the index, even if they are in the
  105220. ** index, because we do not trust the logic in whereIndexExprTrans() to be
  105221. ** able to find all instances of a reference to the indexed table column
  105222. ** and convert them into references to the index. Hence we always want
  105223. ** the actual table at hand in order to recompute the virtual column, if
  105224. ** necessary.
  105225. **
  105226. ** The colNotIdxed mask is AND-ed with the SrcList.a[].colUsed mask
  105227. ** to determine if the index is covering index.
  105228. */
  105229. static void recomputeColumnsNotIndexed(Index *pIdx){
  105230. Bitmask m = 0;
  105231. int j;
  105232. Table *pTab = pIdx->pTable;
  105233. for(j=pIdx->nColumn-1; j>=0; j--){
  105234. int x = pIdx->aiColumn[j];
  105235. if( x>=0 && (pTab->aCol[x].colFlags & COLFLAG_VIRTUAL)==0 ){
  105236. testcase( x==BMS-1 );
  105237. testcase( x==BMS-2 );
  105238. if( x<BMS-1 ) m |= MASKBIT(x);
  105239. }
  105240. }
  105241. pIdx->colNotIdxed = ~m;
  105242. assert( (pIdx->colNotIdxed>>63)==1 );
  105243. }
  105244. /*
  105245. ** This routine runs at the end of parsing a CREATE TABLE statement that
  105246. ** has a WITHOUT ROWID clause. The job of this routine is to convert both
  105247. ** internal schema data structures and the generated VDBE code so that they
  105248. ** are appropriate for a WITHOUT ROWID table instead of a rowid table.
  105249. ** Changes include:
  105250. **
  105251. ** (1) Set all columns of the PRIMARY KEY schema object to be NOT NULL.
  105252. ** (2) Convert P3 parameter of the OP_CreateBtree from BTREE_INTKEY
  105253. ** into BTREE_BLOBKEY.
  105254. ** (3) Bypass the creation of the sqlite_master table entry
  105255. ** for the PRIMARY KEY as the primary key index is now
  105256. ** identified by the sqlite_master table entry of the table itself.
  105257. ** (4) Set the Index.tnum of the PRIMARY KEY Index object in the
  105258. ** schema to the rootpage from the main table.
  105259. ** (5) Add all table columns to the PRIMARY KEY Index object
  105260. ** so that the PRIMARY KEY is a covering index. The surplus
  105261. ** columns are part of KeyInfo.nAllField and are not used for
  105262. ** sorting or lookup or uniqueness checks.
  105263. ** (6) Replace the rowid tail on all automatically generated UNIQUE
  105264. ** indices with the PRIMARY KEY columns.
  105265. **
  105266. ** For virtual tables, only (1) is performed.
  105267. */
  105268. static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){
  105269. Index *pIdx;
  105270. Index *pPk;
  105271. int nPk;
  105272. int nExtra;
  105273. int i, j;
  105274. sqlite3 *db = pParse->db;
  105275. Vdbe *v = pParse->pVdbe;
  105276. /* Mark every PRIMARY KEY column as NOT NULL (except for imposter tables)
  105277. */
  105278. if( !db->init.imposterTable ){
  105279. for(i=0; i<pTab->nCol; i++){
  105280. if( (pTab->aCol[i].colFlags & COLFLAG_PRIMKEY)!=0 ){
  105281. pTab->aCol[i].notNull = OE_Abort;
  105282. }
  105283. }
  105284. pTab->tabFlags |= TF_HasNotNull;
  105285. }
  105286. /* Convert the P3 operand of the OP_CreateBtree opcode from BTREE_INTKEY
  105287. ** into BTREE_BLOBKEY.
  105288. */
  105289. if( pParse->addrCrTab ){
  105290. assert( v );
  105291. sqlite3VdbeChangeP3(v, pParse->addrCrTab, BTREE_BLOBKEY);
  105292. }
  105293. /* Locate the PRIMARY KEY index. Or, if this table was originally
  105294. ** an INTEGER PRIMARY KEY table, create a new PRIMARY KEY index.
  105295. */
  105296. if( pTab->iPKey>=0 ){
  105297. ExprList *pList;
  105298. Token ipkToken;
  105299. sqlite3TokenInit(&ipkToken, pTab->aCol[pTab->iPKey].zName);
  105300. pList = sqlite3ExprListAppend(pParse, 0,
  105301. sqlite3ExprAlloc(db, TK_ID, &ipkToken, 0));
  105302. if( pList==0 ) return;
  105303. if( IN_RENAME_OBJECT ){
  105304. sqlite3RenameTokenRemap(pParse, pList->a[0].pExpr, &pTab->iPKey);
  105305. }
  105306. pList->a[0].sortFlags = pParse->iPkSortOrder;
  105307. assert( pParse->pNewTable==pTab );
  105308. pTab->iPKey = -1;
  105309. sqlite3CreateIndex(pParse, 0, 0, 0, pList, pTab->keyConf, 0, 0, 0, 0,
  105310. SQLITE_IDXTYPE_PRIMARYKEY);
  105311. if( db->mallocFailed || pParse->nErr ) return;
  105312. pPk = sqlite3PrimaryKeyIndex(pTab);
  105313. assert( pPk->nKeyCol==1 );
  105314. }else{
  105315. pPk = sqlite3PrimaryKeyIndex(pTab);
  105316. assert( pPk!=0 );
  105317. /*
  105318. ** Remove all redundant columns from the PRIMARY KEY. For example, change
  105319. ** "PRIMARY KEY(a,b,a,b,c,b,c,d)" into just "PRIMARY KEY(a,b,c,d)". Later
  105320. ** code assumes the PRIMARY KEY contains no repeated columns.
  105321. */
  105322. for(i=j=1; i<pPk->nKeyCol; i++){
  105323. if( isDupColumn(pPk, j, pPk, i) ){
  105324. pPk->nColumn--;
  105325. }else{
  105326. testcase( hasColumn(pPk->aiColumn, j, pPk->aiColumn[i]) );
  105327. pPk->azColl[j] = pPk->azColl[i];
  105328. pPk->aSortOrder[j] = pPk->aSortOrder[i];
  105329. pPk->aiColumn[j++] = pPk->aiColumn[i];
  105330. }
  105331. }
  105332. pPk->nKeyCol = j;
  105333. }
  105334. assert( pPk!=0 );
  105335. pPk->isCovering = 1;
  105336. if( !db->init.imposterTable ) pPk->uniqNotNull = 1;
  105337. nPk = pPk->nColumn = pPk->nKeyCol;
  105338. /* Bypass the creation of the PRIMARY KEY btree and the sqlite_master
  105339. ** table entry. This is only required if currently generating VDBE
  105340. ** code for a CREATE TABLE (not when parsing one as part of reading
  105341. ** a database schema). */
  105342. if( v && pPk->tnum>0 ){
  105343. assert( db->init.busy==0 );
  105344. sqlite3VdbeChangeOpcode(v, pPk->tnum, OP_Goto);
  105345. }
  105346. /* The root page of the PRIMARY KEY is the table root page */
  105347. pPk->tnum = pTab->tnum;
  105348. /* Update the in-memory representation of all UNIQUE indices by converting
  105349. ** the final rowid column into one or more columns of the PRIMARY KEY.
  105350. */
  105351. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  105352. int n;
  105353. if( IsPrimaryKeyIndex(pIdx) ) continue;
  105354. for(i=n=0; i<nPk; i++){
  105355. if( !isDupColumn(pIdx, pIdx->nKeyCol, pPk, i) ){
  105356. testcase( hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) );
  105357. n++;
  105358. }
  105359. }
  105360. if( n==0 ){
  105361. /* This index is a superset of the primary key */
  105362. pIdx->nColumn = pIdx->nKeyCol;
  105363. continue;
  105364. }
  105365. if( resizeIndexObject(db, pIdx, pIdx->nKeyCol+n) ) return;
  105366. for(i=0, j=pIdx->nKeyCol; i<nPk; i++){
  105367. if( !isDupColumn(pIdx, pIdx->nKeyCol, pPk, i) ){
  105368. testcase( hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) );
  105369. pIdx->aiColumn[j] = pPk->aiColumn[i];
  105370. pIdx->azColl[j] = pPk->azColl[i];
  105371. if( pPk->aSortOrder[i] ){
  105372. /* See ticket https://www.sqlite.org/src/info/bba7b69f9849b5bf */
  105373. pIdx->bAscKeyBug = 1;
  105374. }
  105375. j++;
  105376. }
  105377. }
  105378. assert( pIdx->nColumn>=pIdx->nKeyCol+n );
  105379. assert( pIdx->nColumn>=j );
  105380. }
  105381. /* Add all table columns to the PRIMARY KEY index
  105382. */
  105383. nExtra = 0;
  105384. for(i=0; i<pTab->nCol; i++){
  105385. if( !hasColumn(pPk->aiColumn, nPk, i)
  105386. && (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0 ) nExtra++;
  105387. }
  105388. if( resizeIndexObject(db, pPk, nPk+nExtra) ) return;
  105389. for(i=0, j=nPk; i<pTab->nCol; i++){
  105390. if( !hasColumn(pPk->aiColumn, j, i)
  105391. && (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0
  105392. ){
  105393. assert( j<pPk->nColumn );
  105394. pPk->aiColumn[j] = i;
  105395. pPk->azColl[j] = sqlite3StrBINARY;
  105396. j++;
  105397. }
  105398. }
  105399. assert( pPk->nColumn==j );
  105400. assert( pTab->nNVCol<=j );
  105401. recomputeColumnsNotIndexed(pPk);
  105402. }
  105403. #ifndef SQLITE_OMIT_VIRTUALTABLE
  105404. /*
  105405. ** Return true if pTab is a virtual table and zName is a shadow table name
  105406. ** for that virtual table.
  105407. */
  105408. SQLITE_PRIVATE int sqlite3IsShadowTableOf(sqlite3 *db, Table *pTab, const char *zName){
  105409. int nName; /* Length of zName */
  105410. Module *pMod; /* Module for the virtual table */
  105411. if( !IsVirtual(pTab) ) return 0;
  105412. nName = sqlite3Strlen30(pTab->zName);
  105413. if( sqlite3_strnicmp(zName, pTab->zName, nName)!=0 ) return 0;
  105414. if( zName[nName]!='_' ) return 0;
  105415. pMod = (Module*)sqlite3HashFind(&db->aModule, pTab->azModuleArg[0]);
  105416. if( pMod==0 ) return 0;
  105417. if( pMod->pModule->iVersion<3 ) return 0;
  105418. if( pMod->pModule->xShadowName==0 ) return 0;
  105419. return pMod->pModule->xShadowName(zName+nName+1);
  105420. }
  105421. #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
  105422. #ifndef SQLITE_OMIT_VIRTUALTABLE
  105423. /*
  105424. ** Return true if zName is a shadow table name in the current database
  105425. ** connection.
  105426. **
  105427. ** zName is temporarily modified while this routine is running, but is
  105428. ** restored to its original value prior to this routine returning.
  105429. */
  105430. SQLITE_PRIVATE int sqlite3ShadowTableName(sqlite3 *db, const char *zName){
  105431. char *zTail; /* Pointer to the last "_" in zName */
  105432. Table *pTab; /* Table that zName is a shadow of */
  105433. zTail = strrchr(zName, '_');
  105434. if( zTail==0 ) return 0;
  105435. *zTail = 0;
  105436. pTab = sqlite3FindTable(db, zName, 0);
  105437. *zTail = '_';
  105438. if( pTab==0 ) return 0;
  105439. if( !IsVirtual(pTab) ) return 0;
  105440. return sqlite3IsShadowTableOf(db, pTab, zName);
  105441. }
  105442. #endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
  105443. #ifdef SQLITE_DEBUG
  105444. /*
  105445. ** Mark all nodes of an expression as EP_Immutable, indicating that
  105446. ** they should not be changed. Expressions attached to a table or
  105447. ** index definition are tagged this way to help ensure that we do
  105448. ** not pass them into code generator routines by mistake.
  105449. */
  105450. static int markImmutableExprStep(Walker *pWalker, Expr *pExpr){
  105451. ExprSetVVAProperty(pExpr, EP_Immutable);
  105452. return WRC_Continue;
  105453. }
  105454. static void markExprListImmutable(ExprList *pList){
  105455. if( pList ){
  105456. Walker w;
  105457. memset(&w, 0, sizeof(w));
  105458. w.xExprCallback = markImmutableExprStep;
  105459. w.xSelectCallback = sqlite3SelectWalkNoop;
  105460. w.xSelectCallback2 = 0;
  105461. sqlite3WalkExprList(&w, pList);
  105462. }
  105463. }
  105464. #else
  105465. #define markExprListImmutable(X) /* no-op */
  105466. #endif /* SQLITE_DEBUG */
  105467. /*
  105468. ** This routine is called to report the final ")" that terminates
  105469. ** a CREATE TABLE statement.
  105470. **
  105471. ** The table structure that other action routines have been building
  105472. ** is added to the internal hash tables, assuming no errors have
  105473. ** occurred.
  105474. **
  105475. ** An entry for the table is made in the master table on disk, unless
  105476. ** this is a temporary table or db->init.busy==1. When db->init.busy==1
  105477. ** it means we are reading the sqlite_master table because we just
  105478. ** connected to the database or because the sqlite_master table has
  105479. ** recently changed, so the entry for this table already exists in
  105480. ** the sqlite_master table. We do not want to create it again.
  105481. **
  105482. ** If the pSelect argument is not NULL, it means that this routine
  105483. ** was called to create a table generated from a
  105484. ** "CREATE TABLE ... AS SELECT ..." statement. The column names of
  105485. ** the new table will match the result set of the SELECT.
  105486. */
  105487. SQLITE_PRIVATE void sqlite3EndTable(
  105488. Parse *pParse, /* Parse context */
  105489. Token *pCons, /* The ',' token after the last column defn. */
  105490. Token *pEnd, /* The ')' before options in the CREATE TABLE */
  105491. u8 tabOpts, /* Extra table options. Usually 0. */
  105492. Select *pSelect /* Select from a "CREATE ... AS SELECT" */
  105493. ){
  105494. Table *p; /* The new table */
  105495. sqlite3 *db = pParse->db; /* The database connection */
  105496. int iDb; /* Database in which the table lives */
  105497. Index *pIdx; /* An implied index of the table */
  105498. if( pEnd==0 && pSelect==0 ){
  105499. return;
  105500. }
  105501. assert( !db->mallocFailed );
  105502. p = pParse->pNewTable;
  105503. if( p==0 ) return;
  105504. if( pSelect==0 && sqlite3ShadowTableName(db, p->zName) ){
  105505. p->tabFlags |= TF_Shadow;
  105506. }
  105507. /* If the db->init.busy is 1 it means we are reading the SQL off the
  105508. ** "sqlite_master" or "sqlite_temp_master" table on the disk.
  105509. ** So do not write to the disk again. Extract the root page number
  105510. ** for the table from the db->init.newTnum field. (The page number
  105511. ** should have been put there by the sqliteOpenCb routine.)
  105512. **
  105513. ** If the root page number is 1, that means this is the sqlite_master
  105514. ** table itself. So mark it read-only.
  105515. */
  105516. if( db->init.busy ){
  105517. if( pSelect ){
  105518. sqlite3ErrorMsg(pParse, "");
  105519. return;
  105520. }
  105521. p->tnum = db->init.newTnum;
  105522. if( p->tnum==1 ) p->tabFlags |= TF_Readonly;
  105523. }
  105524. assert( (p->tabFlags & TF_HasPrimaryKey)==0
  105525. || p->iPKey>=0 || sqlite3PrimaryKeyIndex(p)!=0 );
  105526. assert( (p->tabFlags & TF_HasPrimaryKey)!=0
  105527. || (p->iPKey<0 && sqlite3PrimaryKeyIndex(p)==0) );
  105528. /* Special processing for WITHOUT ROWID Tables */
  105529. if( tabOpts & TF_WithoutRowid ){
  105530. if( (p->tabFlags & TF_Autoincrement) ){
  105531. sqlite3ErrorMsg(pParse,
  105532. "AUTOINCREMENT not allowed on WITHOUT ROWID tables");
  105533. return;
  105534. }
  105535. if( (p->tabFlags & TF_HasPrimaryKey)==0 ){
  105536. sqlite3ErrorMsg(pParse, "PRIMARY KEY missing on table %s", p->zName);
  105537. return;
  105538. }
  105539. p->tabFlags |= TF_WithoutRowid | TF_NoVisibleRowid;
  105540. convertToWithoutRowidTable(pParse, p);
  105541. }
  105542. iDb = sqlite3SchemaToIndex(db, p->pSchema);
  105543. #ifndef SQLITE_OMIT_CHECK
  105544. /* Resolve names in all CHECK constraint expressions.
  105545. */
  105546. if( p->pCheck ){
  105547. sqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck);
  105548. if( pParse->nErr ){
  105549. /* If errors are seen, delete the CHECK constraints now, else they might
  105550. ** actually be used if PRAGMA writable_schema=ON is set. */
  105551. sqlite3ExprListDelete(db, p->pCheck);
  105552. p->pCheck = 0;
  105553. }else{
  105554. markExprListImmutable(p->pCheck);
  105555. }
  105556. }
  105557. #endif /* !defined(SQLITE_OMIT_CHECK) */
  105558. #ifndef SQLITE_OMIT_GENERATED_COLUMNS
  105559. if( p->tabFlags & TF_HasGenerated ){
  105560. int ii, nNG = 0;
  105561. testcase( p->tabFlags & TF_HasVirtual );
  105562. testcase( p->tabFlags & TF_HasStored );
  105563. for(ii=0; ii<p->nCol; ii++){
  105564. u32 colFlags = p->aCol[ii].colFlags;
  105565. if( (colFlags & COLFLAG_GENERATED)!=0 ){
  105566. Expr *pX = p->aCol[ii].pDflt;
  105567. testcase( colFlags & COLFLAG_VIRTUAL );
  105568. testcase( colFlags & COLFLAG_STORED );
  105569. if( sqlite3ResolveSelfReference(pParse, p, NC_GenCol, pX, 0) ){
  105570. /* If there are errors in resolving the expression, change the
  105571. ** expression to a NULL. This prevents code generators that operate
  105572. ** on the expression from inserting extra parts into the expression
  105573. ** tree that have been allocated from lookaside memory, which is
  105574. ** illegal in a schema and will lead to errors or heap corruption
  105575. ** when the database connection closes. */
  105576. sqlite3ExprDelete(db, pX);
  105577. p->aCol[ii].pDflt = sqlite3ExprAlloc(db, TK_NULL, 0, 0);
  105578. }
  105579. }else{
  105580. nNG++;
  105581. }
  105582. }
  105583. if( nNG==0 ){
  105584. sqlite3ErrorMsg(pParse, "must have at least one non-generated column");
  105585. return;
  105586. }
  105587. }
  105588. #endif
  105589. /* Estimate the average row size for the table and for all implied indices */
  105590. estimateTableWidth(p);
  105591. for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
  105592. estimateIndexWidth(pIdx);
  105593. }
  105594. /* If not initializing, then create a record for the new table
  105595. ** in the SQLITE_MASTER table of the database.
  105596. **
  105597. ** If this is a TEMPORARY table, write the entry into the auxiliary
  105598. ** file instead of into the main database file.
  105599. */
  105600. if( !db->init.busy ){
  105601. int n;
  105602. Vdbe *v;
  105603. char *zType; /* "view" or "table" */
  105604. char *zType2; /* "VIEW" or "TABLE" */
  105605. char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */
  105606. v = sqlite3GetVdbe(pParse);
  105607. if( NEVER(v==0) ) return;
  105608. sqlite3VdbeAddOp1(v, OP_Close, 0);
  105609. /*
  105610. ** Initialize zType for the new view or table.
  105611. */
  105612. if( p->pSelect==0 ){
  105613. /* A regular table */
  105614. zType = "table";
  105615. zType2 = "TABLE";
  105616. #ifndef SQLITE_OMIT_VIEW
  105617. }else{
  105618. /* A view */
  105619. zType = "view";
  105620. zType2 = "VIEW";
  105621. #endif
  105622. }
  105623. /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
  105624. ** statement to populate the new table. The root-page number for the
  105625. ** new table is in register pParse->regRoot.
  105626. **
  105627. ** Once the SELECT has been coded by sqlite3Select(), it is in a
  105628. ** suitable state to query for the column names and types to be used
  105629. ** by the new table.
  105630. **
  105631. ** A shared-cache write-lock is not required to write to the new table,
  105632. ** as a schema-lock must have already been obtained to create it. Since
  105633. ** a schema-lock excludes all other database users, the write-lock would
  105634. ** be redundant.
  105635. */
  105636. if( pSelect ){
  105637. SelectDest dest; /* Where the SELECT should store results */
  105638. int regYield; /* Register holding co-routine entry-point */
  105639. int addrTop; /* Top of the co-routine */
  105640. int regRec; /* A record to be insert into the new table */
  105641. int regRowid; /* Rowid of the next row to insert */
  105642. int addrInsLoop; /* Top of the loop for inserting rows */
  105643. Table *pSelTab; /* A table that describes the SELECT results */
  105644. regYield = ++pParse->nMem;
  105645. regRec = ++pParse->nMem;
  105646. regRowid = ++pParse->nMem;
  105647. assert(pParse->nTab==1);
  105648. sqlite3MayAbort(pParse);
  105649. sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
  105650. sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG);
  105651. pParse->nTab = 2;
  105652. addrTop = sqlite3VdbeCurrentAddr(v) + 1;
  105653. sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
  105654. if( pParse->nErr ) return;
  105655. pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect, SQLITE_AFF_BLOB);
  105656. if( pSelTab==0 ) return;
  105657. assert( p->aCol==0 );
  105658. p->nCol = p->nNVCol = pSelTab->nCol;
  105659. p->aCol = pSelTab->aCol;
  105660. pSelTab->nCol = 0;
  105661. pSelTab->aCol = 0;
  105662. sqlite3DeleteTable(db, pSelTab);
  105663. sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
  105664. sqlite3Select(pParse, pSelect, &dest);
  105665. if( pParse->nErr ) return;
  105666. sqlite3VdbeEndCoroutine(v, regYield);
  105667. sqlite3VdbeJumpHere(v, addrTop - 1);
  105668. addrInsLoop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
  105669. VdbeCoverage(v);
  105670. sqlite3VdbeAddOp3(v, OP_MakeRecord, dest.iSdst, dest.nSdst, regRec);
  105671. sqlite3TableAffinity(v, p, 0);
  105672. sqlite3VdbeAddOp2(v, OP_NewRowid, 1, regRowid);
  105673. sqlite3VdbeAddOp3(v, OP_Insert, 1, regRec, regRowid);
  105674. sqlite3VdbeGoto(v, addrInsLoop);
  105675. sqlite3VdbeJumpHere(v, addrInsLoop);
  105676. sqlite3VdbeAddOp1(v, OP_Close, 1);
  105677. }
  105678. /* Compute the complete text of the CREATE statement */
  105679. if( pSelect ){
  105680. zStmt = createTableStmt(db, p);
  105681. }else{
  105682. Token *pEnd2 = tabOpts ? &pParse->sLastToken : pEnd;
  105683. n = (int)(pEnd2->z - pParse->sNameToken.z);
  105684. if( pEnd2->z[0]!=';' ) n += pEnd2->n;
  105685. zStmt = sqlite3MPrintf(db,
  105686. "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
  105687. );
  105688. }
  105689. /* A slot for the record has already been allocated in the
  105690. ** SQLITE_MASTER table. We just need to update that slot with all
  105691. ** the information we've collected.
  105692. */
  105693. sqlite3NestedParse(pParse,
  105694. "UPDATE %Q.%s "
  105695. "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
  105696. "WHERE rowid=#%d",
  105697. db->aDb[iDb].zDbSName, MASTER_NAME,
  105698. zType,
  105699. p->zName,
  105700. p->zName,
  105701. pParse->regRoot,
  105702. zStmt,
  105703. pParse->regRowid
  105704. );
  105705. sqlite3DbFree(db, zStmt);
  105706. sqlite3ChangeCookie(pParse, iDb);
  105707. #ifndef SQLITE_OMIT_AUTOINCREMENT
  105708. /* Check to see if we need to create an sqlite_sequence table for
  105709. ** keeping track of autoincrement keys.
  105710. */
  105711. if( (p->tabFlags & TF_Autoincrement)!=0 ){
  105712. Db *pDb = &db->aDb[iDb];
  105713. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  105714. if( pDb->pSchema->pSeqTab==0 ){
  105715. sqlite3NestedParse(pParse,
  105716. "CREATE TABLE %Q.sqlite_sequence(name,seq)",
  105717. pDb->zDbSName
  105718. );
  105719. }
  105720. }
  105721. #endif
  105722. /* Reparse everything to update our internal data structures */
  105723. sqlite3VdbeAddParseSchemaOp(v, iDb,
  105724. sqlite3MPrintf(db, "tbl_name='%q' AND type!='trigger'", p->zName));
  105725. }
  105726. /* Add the table to the in-memory representation of the database.
  105727. */
  105728. if( db->init.busy ){
  105729. Table *pOld;
  105730. Schema *pSchema = p->pSchema;
  105731. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  105732. pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, p);
  105733. if( pOld ){
  105734. assert( p==pOld ); /* Malloc must have failed inside HashInsert() */
  105735. sqlite3OomFault(db);
  105736. return;
  105737. }
  105738. pParse->pNewTable = 0;
  105739. db->mDbFlags |= DBFLAG_SchemaChange;
  105740. #ifndef SQLITE_OMIT_ALTERTABLE
  105741. if( !p->pSelect ){
  105742. const char *zName = (const char *)pParse->sNameToken.z;
  105743. int nName;
  105744. assert( !pSelect && pCons && pEnd );
  105745. if( pCons->z==0 ){
  105746. pCons = pEnd;
  105747. }
  105748. nName = (int)((const char *)pCons->z - zName);
  105749. p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
  105750. }
  105751. #endif
  105752. }
  105753. }
  105754. #ifndef SQLITE_OMIT_VIEW
  105755. /*
  105756. ** The parser calls this routine in order to create a new VIEW
  105757. */
  105758. SQLITE_PRIVATE void sqlite3CreateView(
  105759. Parse *pParse, /* The parsing context */
  105760. Token *pBegin, /* The CREATE token that begins the statement */
  105761. Token *pName1, /* The token that holds the name of the view */
  105762. Token *pName2, /* The token that holds the name of the view */
  105763. ExprList *pCNames, /* Optional list of view column names */
  105764. Select *pSelect, /* A SELECT statement that will become the new view */
  105765. int isTemp, /* TRUE for a TEMPORARY view */
  105766. int noErr /* Suppress error messages if VIEW already exists */
  105767. ){
  105768. Table *p;
  105769. int n;
  105770. const char *z;
  105771. Token sEnd;
  105772. DbFixer sFix;
  105773. Token *pName = 0;
  105774. int iDb;
  105775. sqlite3 *db = pParse->db;
  105776. if( pParse->nVar>0 ){
  105777. sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
  105778. goto create_view_fail;
  105779. }
  105780. sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
  105781. p = pParse->pNewTable;
  105782. if( p==0 || pParse->nErr ) goto create_view_fail;
  105783. sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  105784. iDb = sqlite3SchemaToIndex(db, p->pSchema);
  105785. sqlite3FixInit(&sFix, pParse, iDb, "view", pName);
  105786. if( sqlite3FixSelect(&sFix, pSelect) ) goto create_view_fail;
  105787. /* Make a copy of the entire SELECT statement that defines the view.
  105788. ** This will force all the Expr.token.z values to be dynamically
  105789. ** allocated rather than point to the input string - which means that
  105790. ** they will persist after the current sqlite3_exec() call returns.
  105791. */
  105792. pSelect->selFlags |= SF_View;
  105793. if( IN_RENAME_OBJECT ){
  105794. p->pSelect = pSelect;
  105795. pSelect = 0;
  105796. }else{
  105797. p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
  105798. }
  105799. p->pCheck = sqlite3ExprListDup(db, pCNames, EXPRDUP_REDUCE);
  105800. if( db->mallocFailed ) goto create_view_fail;
  105801. /* Locate the end of the CREATE VIEW statement. Make sEnd point to
  105802. ** the end.
  105803. */
  105804. sEnd = pParse->sLastToken;
  105805. assert( sEnd.z[0]!=0 || sEnd.n==0 );
  105806. if( sEnd.z[0]!=';' ){
  105807. sEnd.z += sEnd.n;
  105808. }
  105809. sEnd.n = 0;
  105810. n = (int)(sEnd.z - pBegin->z);
  105811. assert( n>0 );
  105812. z = pBegin->z;
  105813. while( sqlite3Isspace(z[n-1]) ){ n--; }
  105814. sEnd.z = &z[n-1];
  105815. sEnd.n = 1;
  105816. /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
  105817. sqlite3EndTable(pParse, 0, &sEnd, 0, 0);
  105818. create_view_fail:
  105819. sqlite3SelectDelete(db, pSelect);
  105820. if( IN_RENAME_OBJECT ){
  105821. sqlite3RenameExprlistUnmap(pParse, pCNames);
  105822. }
  105823. sqlite3ExprListDelete(db, pCNames);
  105824. return;
  105825. }
  105826. #endif /* SQLITE_OMIT_VIEW */
  105827. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
  105828. /*
  105829. ** The Table structure pTable is really a VIEW. Fill in the names of
  105830. ** the columns of the view in the pTable structure. Return the number
  105831. ** of errors. If an error is seen leave an error message in pParse->zErrMsg.
  105832. */
  105833. SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
  105834. Table *pSelTab; /* A fake table from which we get the result set */
  105835. Select *pSel; /* Copy of the SELECT that implements the view */
  105836. int nErr = 0; /* Number of errors encountered */
  105837. int n; /* Temporarily holds the number of cursors assigned */
  105838. sqlite3 *db = pParse->db; /* Database connection for malloc errors */
  105839. #ifndef SQLITE_OMIT_VIRTUALTABLE
  105840. int rc;
  105841. #endif
  105842. #ifndef SQLITE_OMIT_AUTHORIZATION
  105843. sqlite3_xauth xAuth; /* Saved xAuth pointer */
  105844. #endif
  105845. assert( pTable );
  105846. #ifndef SQLITE_OMIT_VIRTUALTABLE
  105847. db->nSchemaLock++;
  105848. rc = sqlite3VtabCallConnect(pParse, pTable);
  105849. db->nSchemaLock--;
  105850. if( rc ){
  105851. return 1;
  105852. }
  105853. if( IsVirtual(pTable) ) return 0;
  105854. #endif
  105855. #ifndef SQLITE_OMIT_VIEW
  105856. /* A positive nCol means the columns names for this view are
  105857. ** already known.
  105858. */
  105859. if( pTable->nCol>0 ) return 0;
  105860. /* A negative nCol is a special marker meaning that we are currently
  105861. ** trying to compute the column names. If we enter this routine with
  105862. ** a negative nCol, it means two or more views form a loop, like this:
  105863. **
  105864. ** CREATE VIEW one AS SELECT * FROM two;
  105865. ** CREATE VIEW two AS SELECT * FROM one;
  105866. **
  105867. ** Actually, the error above is now caught prior to reaching this point.
  105868. ** But the following test is still important as it does come up
  105869. ** in the following:
  105870. **
  105871. ** CREATE TABLE main.ex1(a);
  105872. ** CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
  105873. ** SELECT * FROM temp.ex1;
  105874. */
  105875. if( pTable->nCol<0 ){
  105876. sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
  105877. return 1;
  105878. }
  105879. assert( pTable->nCol>=0 );
  105880. /* If we get this far, it means we need to compute the table names.
  105881. ** Note that the call to sqlite3ResultSetOfSelect() will expand any
  105882. ** "*" elements in the results set of the view and will assign cursors
  105883. ** to the elements of the FROM clause. But we do not want these changes
  105884. ** to be permanent. So the computation is done on a copy of the SELECT
  105885. ** statement that defines the view.
  105886. */
  105887. assert( pTable->pSelect );
  105888. pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
  105889. if( pSel ){
  105890. #ifndef SQLITE_OMIT_ALTERTABLE
  105891. u8 eParseMode = pParse->eParseMode;
  105892. pParse->eParseMode = PARSE_MODE_NORMAL;
  105893. #endif
  105894. n = pParse->nTab;
  105895. sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
  105896. pTable->nCol = -1;
  105897. DisableLookaside;
  105898. #ifndef SQLITE_OMIT_AUTHORIZATION
  105899. xAuth = db->xAuth;
  105900. db->xAuth = 0;
  105901. pSelTab = sqlite3ResultSetOfSelect(pParse, pSel, SQLITE_AFF_NONE);
  105902. db->xAuth = xAuth;
  105903. #else
  105904. pSelTab = sqlite3ResultSetOfSelect(pParse, pSel, SQLITE_AFF_NONE);
  105905. #endif
  105906. pParse->nTab = n;
  105907. if( pSelTab==0 ){
  105908. pTable->nCol = 0;
  105909. nErr++;
  105910. }else if( pTable->pCheck ){
  105911. /* CREATE VIEW name(arglist) AS ...
  105912. ** The names of the columns in the table are taken from
  105913. ** arglist which is stored in pTable->pCheck. The pCheck field
  105914. ** normally holds CHECK constraints on an ordinary table, but for
  105915. ** a VIEW it holds the list of column names.
  105916. */
  105917. sqlite3ColumnsFromExprList(pParse, pTable->pCheck,
  105918. &pTable->nCol, &pTable->aCol);
  105919. if( db->mallocFailed==0
  105920. && pParse->nErr==0
  105921. && pTable->nCol==pSel->pEList->nExpr
  105922. ){
  105923. sqlite3SelectAddColumnTypeAndCollation(pParse, pTable, pSel,
  105924. SQLITE_AFF_NONE);
  105925. }
  105926. }else{
  105927. /* CREATE VIEW name AS... without an argument list. Construct
  105928. ** the column names from the SELECT statement that defines the view.
  105929. */
  105930. assert( pTable->aCol==0 );
  105931. pTable->nCol = pSelTab->nCol;
  105932. pTable->aCol = pSelTab->aCol;
  105933. pSelTab->nCol = 0;
  105934. pSelTab->aCol = 0;
  105935. assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
  105936. }
  105937. pTable->nNVCol = pTable->nCol;
  105938. sqlite3DeleteTable(db, pSelTab);
  105939. sqlite3SelectDelete(db, pSel);
  105940. EnableLookaside;
  105941. #ifndef SQLITE_OMIT_ALTERTABLE
  105942. pParse->eParseMode = eParseMode;
  105943. #endif
  105944. } else {
  105945. nErr++;
  105946. }
  105947. pTable->pSchema->schemaFlags |= DB_UnresetViews;
  105948. if( db->mallocFailed ){
  105949. sqlite3DeleteColumnNames(db, pTable);
  105950. pTable->aCol = 0;
  105951. pTable->nCol = 0;
  105952. }
  105953. #endif /* SQLITE_OMIT_VIEW */
  105954. return nErr;
  105955. }
  105956. #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
  105957. #ifndef SQLITE_OMIT_VIEW
  105958. /*
  105959. ** Clear the column names from every VIEW in database idx.
  105960. */
  105961. static void sqliteViewResetAll(sqlite3 *db, int idx){
  105962. HashElem *i;
  105963. assert( sqlite3SchemaMutexHeld(db, idx, 0) );
  105964. if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
  105965. for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
  105966. Table *pTab = sqliteHashData(i);
  105967. if( pTab->pSelect ){
  105968. sqlite3DeleteColumnNames(db, pTab);
  105969. pTab->aCol = 0;
  105970. pTab->nCol = 0;
  105971. }
  105972. }
  105973. DbClearProperty(db, idx, DB_UnresetViews);
  105974. }
  105975. #else
  105976. # define sqliteViewResetAll(A,B)
  105977. #endif /* SQLITE_OMIT_VIEW */
  105978. /*
  105979. ** This function is called by the VDBE to adjust the internal schema
  105980. ** used by SQLite when the btree layer moves a table root page. The
  105981. ** root-page of a table or index in database iDb has changed from iFrom
  105982. ** to iTo.
  105983. **
  105984. ** Ticket #1728: The symbol table might still contain information
  105985. ** on tables and/or indices that are the process of being deleted.
  105986. ** If you are unlucky, one of those deleted indices or tables might
  105987. ** have the same rootpage number as the real table or index that is
  105988. ** being moved. So we cannot stop searching after the first match
  105989. ** because the first match might be for one of the deleted indices
  105990. ** or tables and not the table/index that is actually being moved.
  105991. ** We must continue looping until all tables and indices with
  105992. ** rootpage==iFrom have been converted to have a rootpage of iTo
  105993. ** in order to be certain that we got the right one.
  105994. */
  105995. #ifndef SQLITE_OMIT_AUTOVACUUM
  105996. SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){
  105997. HashElem *pElem;
  105998. Hash *pHash;
  105999. Db *pDb;
  106000. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  106001. pDb = &db->aDb[iDb];
  106002. pHash = &pDb->pSchema->tblHash;
  106003. for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
  106004. Table *pTab = sqliteHashData(pElem);
  106005. if( pTab->tnum==iFrom ){
  106006. pTab->tnum = iTo;
  106007. }
  106008. }
  106009. pHash = &pDb->pSchema->idxHash;
  106010. for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
  106011. Index *pIdx = sqliteHashData(pElem);
  106012. if( pIdx->tnum==iFrom ){
  106013. pIdx->tnum = iTo;
  106014. }
  106015. }
  106016. }
  106017. #endif
  106018. /*
  106019. ** Write code to erase the table with root-page iTable from database iDb.
  106020. ** Also write code to modify the sqlite_master table and internal schema
  106021. ** if a root-page of another table is moved by the btree-layer whilst
  106022. ** erasing iTable (this can happen with an auto-vacuum database).
  106023. */
  106024. static void destroyRootPage(Parse *pParse, int iTable, int iDb){
  106025. Vdbe *v = sqlite3GetVdbe(pParse);
  106026. int r1 = sqlite3GetTempReg(pParse);
  106027. if( iTable<2 ) sqlite3ErrorMsg(pParse, "corrupt schema");
  106028. sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
  106029. sqlite3MayAbort(pParse);
  106030. #ifndef SQLITE_OMIT_AUTOVACUUM
  106031. /* OP_Destroy stores an in integer r1. If this integer
  106032. ** is non-zero, then it is the root page number of a table moved to
  106033. ** location iTable. The following code modifies the sqlite_master table to
  106034. ** reflect this.
  106035. **
  106036. ** The "#NNN" in the SQL is a special constant that means whatever value
  106037. ** is in register NNN. See grammar rules associated with the TK_REGISTER
  106038. ** token for additional information.
  106039. */
  106040. sqlite3NestedParse(pParse,
  106041. "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
  106042. pParse->db->aDb[iDb].zDbSName, MASTER_NAME, iTable, r1, r1);
  106043. #endif
  106044. sqlite3ReleaseTempReg(pParse, r1);
  106045. }
  106046. /*
  106047. ** Write VDBE code to erase table pTab and all associated indices on disk.
  106048. ** Code to update the sqlite_master tables and internal schema definitions
  106049. ** in case a root-page belonging to another table is moved by the btree layer
  106050. ** is also added (this can happen with an auto-vacuum database).
  106051. */
  106052. static void destroyTable(Parse *pParse, Table *pTab){
  106053. /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
  106054. ** is not defined), then it is important to call OP_Destroy on the
  106055. ** table and index root-pages in order, starting with the numerically
  106056. ** largest root-page number. This guarantees that none of the root-pages
  106057. ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
  106058. ** following were coded:
  106059. **
  106060. ** OP_Destroy 4 0
  106061. ** ...
  106062. ** OP_Destroy 5 0
  106063. **
  106064. ** and root page 5 happened to be the largest root-page number in the
  106065. ** database, then root page 5 would be moved to page 4 by the
  106066. ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
  106067. ** a free-list page.
  106068. */
  106069. int iTab = pTab->tnum;
  106070. int iDestroyed = 0;
  106071. while( 1 ){
  106072. Index *pIdx;
  106073. int iLargest = 0;
  106074. if( iDestroyed==0 || iTab<iDestroyed ){
  106075. iLargest = iTab;
  106076. }
  106077. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  106078. int iIdx = pIdx->tnum;
  106079. assert( pIdx->pSchema==pTab->pSchema );
  106080. if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
  106081. iLargest = iIdx;
  106082. }
  106083. }
  106084. if( iLargest==0 ){
  106085. return;
  106086. }else{
  106087. int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  106088. assert( iDb>=0 && iDb<pParse->db->nDb );
  106089. destroyRootPage(pParse, iLargest, iDb);
  106090. iDestroyed = iLargest;
  106091. }
  106092. }
  106093. }
  106094. /*
  106095. ** Remove entries from the sqlite_statN tables (for N in (1,2,3))
  106096. ** after a DROP INDEX or DROP TABLE command.
  106097. */
  106098. static void sqlite3ClearStatTables(
  106099. Parse *pParse, /* The parsing context */
  106100. int iDb, /* The database number */
  106101. const char *zType, /* "idx" or "tbl" */
  106102. const char *zName /* Name of index or table */
  106103. ){
  106104. int i;
  106105. const char *zDbName = pParse->db->aDb[iDb].zDbSName;
  106106. for(i=1; i<=4; i++){
  106107. char zTab[24];
  106108. sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
  106109. if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
  106110. sqlite3NestedParse(pParse,
  106111. "DELETE FROM %Q.%s WHERE %s=%Q",
  106112. zDbName, zTab, zType, zName
  106113. );
  106114. }
  106115. }
  106116. }
  106117. /*
  106118. ** Generate code to drop a table.
  106119. */
  106120. SQLITE_PRIVATE void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
  106121. Vdbe *v;
  106122. sqlite3 *db = pParse->db;
  106123. Trigger *pTrigger;
  106124. Db *pDb = &db->aDb[iDb];
  106125. v = sqlite3GetVdbe(pParse);
  106126. assert( v!=0 );
  106127. sqlite3BeginWriteOperation(pParse, 1, iDb);
  106128. #ifndef SQLITE_OMIT_VIRTUALTABLE
  106129. if( IsVirtual(pTab) ){
  106130. sqlite3VdbeAddOp0(v, OP_VBegin);
  106131. }
  106132. #endif
  106133. /* Drop all triggers associated with the table being dropped. Code
  106134. ** is generated to remove entries from sqlite_master and/or
  106135. ** sqlite_temp_master if required.
  106136. */
  106137. pTrigger = sqlite3TriggerList(pParse, pTab);
  106138. while( pTrigger ){
  106139. assert( pTrigger->pSchema==pTab->pSchema ||
  106140. pTrigger->pSchema==db->aDb[1].pSchema );
  106141. sqlite3DropTriggerPtr(pParse, pTrigger);
  106142. pTrigger = pTrigger->pNext;
  106143. }
  106144. #ifndef SQLITE_OMIT_AUTOINCREMENT
  106145. /* Remove any entries of the sqlite_sequence table associated with
  106146. ** the table being dropped. This is done before the table is dropped
  106147. ** at the btree level, in case the sqlite_sequence table needs to
  106148. ** move as a result of the drop (can happen in auto-vacuum mode).
  106149. */
  106150. if( pTab->tabFlags & TF_Autoincrement ){
  106151. sqlite3NestedParse(pParse,
  106152. "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
  106153. pDb->zDbSName, pTab->zName
  106154. );
  106155. }
  106156. #endif
  106157. /* Drop all SQLITE_MASTER table and index entries that refer to the
  106158. ** table. The program name loops through the master table and deletes
  106159. ** every row that refers to a table of the same name as the one being
  106160. ** dropped. Triggers are handled separately because a trigger can be
  106161. ** created in the temp database that refers to a table in another
  106162. ** database.
  106163. */
  106164. sqlite3NestedParse(pParse,
  106165. "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
  106166. pDb->zDbSName, MASTER_NAME, pTab->zName);
  106167. if( !isView && !IsVirtual(pTab) ){
  106168. destroyTable(pParse, pTab);
  106169. }
  106170. /* Remove the table entry from SQLite's internal schema and modify
  106171. ** the schema cookie.
  106172. */
  106173. if( IsVirtual(pTab) ){
  106174. sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
  106175. sqlite3MayAbort(pParse);
  106176. }
  106177. sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
  106178. sqlite3ChangeCookie(pParse, iDb);
  106179. sqliteViewResetAll(db, iDb);
  106180. }
  106181. /*
  106182. ** Return TRUE if shadow tables should be read-only in the current
  106183. ** context.
  106184. */
  106185. SQLITE_PRIVATE int sqlite3ReadOnlyShadowTables(sqlite3 *db){
  106186. #ifndef SQLITE_OMIT_VIRTUALTABLE
  106187. if( (db->flags & SQLITE_Defensive)!=0
  106188. && db->pVtabCtx==0
  106189. && db->nVdbeExec==0
  106190. ){
  106191. return 1;
  106192. }
  106193. #endif
  106194. return 0;
  106195. }
  106196. /*
  106197. ** Return true if it is not allowed to drop the given table
  106198. */
  106199. static int tableMayNotBeDropped(sqlite3 *db, Table *pTab){
  106200. if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
  106201. if( sqlite3StrNICmp(pTab->zName+7, "stat", 4)==0 ) return 0;
  106202. if( sqlite3StrNICmp(pTab->zName+7, "parameters", 10)==0 ) return 0;
  106203. return 1;
  106204. }
  106205. if( (pTab->tabFlags & TF_Shadow)!=0 && sqlite3ReadOnlyShadowTables(db) ){
  106206. return 1;
  106207. }
  106208. return 0;
  106209. }
  106210. /*
  106211. ** This routine is called to do the work of a DROP TABLE statement.
  106212. ** pName is the name of the table to be dropped.
  106213. */
  106214. SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
  106215. Table *pTab;
  106216. Vdbe *v;
  106217. sqlite3 *db = pParse->db;
  106218. int iDb;
  106219. if( db->mallocFailed ){
  106220. goto exit_drop_table;
  106221. }
  106222. assert( pParse->nErr==0 );
  106223. assert( pName->nSrc==1 );
  106224. if( sqlite3ReadSchema(pParse) ) goto exit_drop_table;
  106225. if( noErr ) db->suppressErr++;
  106226. assert( isView==0 || isView==LOCATE_VIEW );
  106227. pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]);
  106228. if( noErr ) db->suppressErr--;
  106229. if( pTab==0 ){
  106230. if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
  106231. goto exit_drop_table;
  106232. }
  106233. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  106234. assert( iDb>=0 && iDb<db->nDb );
  106235. /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
  106236. ** it is initialized.
  106237. */
  106238. if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
  106239. goto exit_drop_table;
  106240. }
  106241. #ifndef SQLITE_OMIT_AUTHORIZATION
  106242. {
  106243. int code;
  106244. const char *zTab = SCHEMA_TABLE(iDb);
  106245. const char *zDb = db->aDb[iDb].zDbSName;
  106246. const char *zArg2 = 0;
  106247. if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
  106248. goto exit_drop_table;
  106249. }
  106250. if( isView ){
  106251. if( !OMIT_TEMPDB && iDb==1 ){
  106252. code = SQLITE_DROP_TEMP_VIEW;
  106253. }else{
  106254. code = SQLITE_DROP_VIEW;
  106255. }
  106256. #ifndef SQLITE_OMIT_VIRTUALTABLE
  106257. }else if( IsVirtual(pTab) ){
  106258. code = SQLITE_DROP_VTABLE;
  106259. zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
  106260. #endif
  106261. }else{
  106262. if( !OMIT_TEMPDB && iDb==1 ){
  106263. code = SQLITE_DROP_TEMP_TABLE;
  106264. }else{
  106265. code = SQLITE_DROP_TABLE;
  106266. }
  106267. }
  106268. if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
  106269. goto exit_drop_table;
  106270. }
  106271. if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
  106272. goto exit_drop_table;
  106273. }
  106274. }
  106275. #endif
  106276. if( tableMayNotBeDropped(db, pTab) ){
  106277. sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
  106278. goto exit_drop_table;
  106279. }
  106280. #ifndef SQLITE_OMIT_VIEW
  106281. /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
  106282. ** on a table.
  106283. */
  106284. if( isView && pTab->pSelect==0 ){
  106285. sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
  106286. goto exit_drop_table;
  106287. }
  106288. if( !isView && pTab->pSelect ){
  106289. sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
  106290. goto exit_drop_table;
  106291. }
  106292. #endif
  106293. /* Generate code to remove the table from the master table
  106294. ** on disk.
  106295. */
  106296. v = sqlite3GetVdbe(pParse);
  106297. if( v ){
  106298. sqlite3BeginWriteOperation(pParse, 1, iDb);
  106299. if( !isView ){
  106300. sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
  106301. sqlite3FkDropTable(pParse, pName, pTab);
  106302. }
  106303. sqlite3CodeDropTable(pParse, pTab, iDb, isView);
  106304. }
  106305. exit_drop_table:
  106306. sqlite3SrcListDelete(db, pName);
  106307. }
  106308. /*
  106309. ** This routine is called to create a new foreign key on the table
  106310. ** currently under construction. pFromCol determines which columns
  106311. ** in the current table point to the foreign key. If pFromCol==0 then
  106312. ** connect the key to the last column inserted. pTo is the name of
  106313. ** the table referred to (a.k.a the "parent" table). pToCol is a list
  106314. ** of tables in the parent pTo table. flags contains all
  106315. ** information about the conflict resolution algorithms specified
  106316. ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
  106317. **
  106318. ** An FKey structure is created and added to the table currently
  106319. ** under construction in the pParse->pNewTable field.
  106320. **
  106321. ** The foreign key is set for IMMEDIATE processing. A subsequent call
  106322. ** to sqlite3DeferForeignKey() might change this to DEFERRED.
  106323. */
  106324. SQLITE_PRIVATE void sqlite3CreateForeignKey(
  106325. Parse *pParse, /* Parsing context */
  106326. ExprList *pFromCol, /* Columns in this table that point to other table */
  106327. Token *pTo, /* Name of the other table */
  106328. ExprList *pToCol, /* Columns in the other table */
  106329. int flags /* Conflict resolution algorithms. */
  106330. ){
  106331. sqlite3 *db = pParse->db;
  106332. #ifndef SQLITE_OMIT_FOREIGN_KEY
  106333. FKey *pFKey = 0;
  106334. FKey *pNextTo;
  106335. Table *p = pParse->pNewTable;
  106336. int nByte;
  106337. int i;
  106338. int nCol;
  106339. char *z;
  106340. assert( pTo!=0 );
  106341. if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
  106342. if( pFromCol==0 ){
  106343. int iCol = p->nCol-1;
  106344. if( NEVER(iCol<0) ) goto fk_end;
  106345. if( pToCol && pToCol->nExpr!=1 ){
  106346. sqlite3ErrorMsg(pParse, "foreign key on %s"
  106347. " should reference only one column of table %T",
  106348. p->aCol[iCol].zName, pTo);
  106349. goto fk_end;
  106350. }
  106351. nCol = 1;
  106352. }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
  106353. sqlite3ErrorMsg(pParse,
  106354. "number of columns in foreign key does not match the number of "
  106355. "columns in the referenced table");
  106356. goto fk_end;
  106357. }else{
  106358. nCol = pFromCol->nExpr;
  106359. }
  106360. nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
  106361. if( pToCol ){
  106362. for(i=0; i<pToCol->nExpr; i++){
  106363. nByte += sqlite3Strlen30(pToCol->a[i].zEName) + 1;
  106364. }
  106365. }
  106366. pFKey = sqlite3DbMallocZero(db, nByte );
  106367. if( pFKey==0 ){
  106368. goto fk_end;
  106369. }
  106370. pFKey->pFrom = p;
  106371. pFKey->pNextFrom = p->pFKey;
  106372. z = (char*)&pFKey->aCol[nCol];
  106373. pFKey->zTo = z;
  106374. if( IN_RENAME_OBJECT ){
  106375. sqlite3RenameTokenMap(pParse, (void*)z, pTo);
  106376. }
  106377. memcpy(z, pTo->z, pTo->n);
  106378. z[pTo->n] = 0;
  106379. sqlite3Dequote(z);
  106380. z += pTo->n+1;
  106381. pFKey->nCol = nCol;
  106382. if( pFromCol==0 ){
  106383. pFKey->aCol[0].iFrom = p->nCol-1;
  106384. }else{
  106385. for(i=0; i<nCol; i++){
  106386. int j;
  106387. for(j=0; j<p->nCol; j++){
  106388. if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zEName)==0 ){
  106389. pFKey->aCol[i].iFrom = j;
  106390. break;
  106391. }
  106392. }
  106393. if( j>=p->nCol ){
  106394. sqlite3ErrorMsg(pParse,
  106395. "unknown column \"%s\" in foreign key definition",
  106396. pFromCol->a[i].zEName);
  106397. goto fk_end;
  106398. }
  106399. if( IN_RENAME_OBJECT ){
  106400. sqlite3RenameTokenRemap(pParse, &pFKey->aCol[i], pFromCol->a[i].zEName);
  106401. }
  106402. }
  106403. }
  106404. if( pToCol ){
  106405. for(i=0; i<nCol; i++){
  106406. int n = sqlite3Strlen30(pToCol->a[i].zEName);
  106407. pFKey->aCol[i].zCol = z;
  106408. if( IN_RENAME_OBJECT ){
  106409. sqlite3RenameTokenRemap(pParse, z, pToCol->a[i].zEName);
  106410. }
  106411. memcpy(z, pToCol->a[i].zEName, n);
  106412. z[n] = 0;
  106413. z += n+1;
  106414. }
  106415. }
  106416. pFKey->isDeferred = 0;
  106417. pFKey->aAction[0] = (u8)(flags & 0xff); /* ON DELETE action */
  106418. pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff); /* ON UPDATE action */
  106419. assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
  106420. pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
  106421. pFKey->zTo, (void *)pFKey
  106422. );
  106423. if( pNextTo==pFKey ){
  106424. sqlite3OomFault(db);
  106425. goto fk_end;
  106426. }
  106427. if( pNextTo ){
  106428. assert( pNextTo->pPrevTo==0 );
  106429. pFKey->pNextTo = pNextTo;
  106430. pNextTo->pPrevTo = pFKey;
  106431. }
  106432. /* Link the foreign key to the table as the last step.
  106433. */
  106434. p->pFKey = pFKey;
  106435. pFKey = 0;
  106436. fk_end:
  106437. sqlite3DbFree(db, pFKey);
  106438. #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
  106439. sqlite3ExprListDelete(db, pFromCol);
  106440. sqlite3ExprListDelete(db, pToCol);
  106441. }
  106442. /*
  106443. ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
  106444. ** clause is seen as part of a foreign key definition. The isDeferred
  106445. ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
  106446. ** The behavior of the most recently created foreign key is adjusted
  106447. ** accordingly.
  106448. */
  106449. SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
  106450. #ifndef SQLITE_OMIT_FOREIGN_KEY
  106451. Table *pTab;
  106452. FKey *pFKey;
  106453. if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
  106454. assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
  106455. pFKey->isDeferred = (u8)isDeferred;
  106456. #endif
  106457. }
  106458. /*
  106459. ** Generate code that will erase and refill index *pIdx. This is
  106460. ** used to initialize a newly created index or to recompute the
  106461. ** content of an index in response to a REINDEX command.
  106462. **
  106463. ** if memRootPage is not negative, it means that the index is newly
  106464. ** created. The register specified by memRootPage contains the
  106465. ** root page number of the index. If memRootPage is negative, then
  106466. ** the index already exists and must be cleared before being refilled and
  106467. ** the root page number of the index is taken from pIndex->tnum.
  106468. */
  106469. static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
  106470. Table *pTab = pIndex->pTable; /* The table that is indexed */
  106471. int iTab = pParse->nTab++; /* Btree cursor used for pTab */
  106472. int iIdx = pParse->nTab++; /* Btree cursor used for pIndex */
  106473. int iSorter; /* Cursor opened by OpenSorter (if in use) */
  106474. int addr1; /* Address of top of loop */
  106475. int addr2; /* Address to jump to for next iteration */
  106476. int tnum; /* Root page of index */
  106477. int iPartIdxLabel; /* Jump to this label to skip a row */
  106478. Vdbe *v; /* Generate code into this virtual machine */
  106479. KeyInfo *pKey; /* KeyInfo for index */
  106480. int regRecord; /* Register holding assembled index record */
  106481. sqlite3 *db = pParse->db; /* The database connection */
  106482. int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
  106483. #ifndef SQLITE_OMIT_AUTHORIZATION
  106484. if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
  106485. db->aDb[iDb].zDbSName ) ){
  106486. return;
  106487. }
  106488. #endif
  106489. /* Require a write-lock on the table to perform this operation */
  106490. sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
  106491. v = sqlite3GetVdbe(pParse);
  106492. if( v==0 ) return;
  106493. if( memRootPage>=0 ){
  106494. tnum = memRootPage;
  106495. }else{
  106496. tnum = pIndex->tnum;
  106497. }
  106498. pKey = sqlite3KeyInfoOfIndex(pParse, pIndex);
  106499. assert( pKey!=0 || db->mallocFailed || pParse->nErr );
  106500. /* Open the sorter cursor if we are to use one. */
  106501. iSorter = pParse->nTab++;
  106502. sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, pIndex->nKeyCol, (char*)
  106503. sqlite3KeyInfoRef(pKey), P4_KEYINFO);
  106504. /* Open the table. Loop through all rows of the table, inserting index
  106505. ** records into the sorter. */
  106506. sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
  106507. addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0); VdbeCoverage(v);
  106508. regRecord = sqlite3GetTempReg(pParse);
  106509. sqlite3MultiWrite(pParse);
  106510. sqlite3GenerateIndexKey(pParse,pIndex,iTab,regRecord,0,&iPartIdxLabel,0,0);
  106511. sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
  106512. sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
  106513. sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1); VdbeCoverage(v);
  106514. sqlite3VdbeJumpHere(v, addr1);
  106515. if( memRootPage<0 ) sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
  106516. sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
  106517. (char *)pKey, P4_KEYINFO);
  106518. sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));
  106519. addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0); VdbeCoverage(v);
  106520. if( IsUniqueIndex(pIndex) ){
  106521. int j2 = sqlite3VdbeGoto(v, 1);
  106522. addr2 = sqlite3VdbeCurrentAddr(v);
  106523. sqlite3VdbeVerifyAbortable(v, OE_Abort);
  106524. sqlite3VdbeAddOp4Int(v, OP_SorterCompare, iSorter, j2, regRecord,
  106525. pIndex->nKeyCol); VdbeCoverage(v);
  106526. sqlite3UniqueConstraint(pParse, OE_Abort, pIndex);
  106527. sqlite3VdbeJumpHere(v, j2);
  106528. }else{
  106529. /* Most CREATE INDEX and REINDEX statements that are not UNIQUE can not
  106530. ** abort. The exception is if one of the indexed expressions contains a
  106531. ** user function that throws an exception when it is evaluated. But the
  106532. ** overhead of adding a statement journal to a CREATE INDEX statement is
  106533. ** very small (since most of the pages written do not contain content that
  106534. ** needs to be restored if the statement aborts), so we call
  106535. ** sqlite3MayAbort() for all CREATE INDEX statements. */
  106536. sqlite3MayAbort(pParse);
  106537. addr2 = sqlite3VdbeCurrentAddr(v);
  106538. }
  106539. sqlite3VdbeAddOp3(v, OP_SorterData, iSorter, regRecord, iIdx);
  106540. if( !pIndex->bAscKeyBug ){
  106541. /* This OP_SeekEnd opcode makes index insert for a REINDEX go much
  106542. ** faster by avoiding unnecessary seeks. But the optimization does
  106543. ** not work for UNIQUE constraint indexes on WITHOUT ROWID tables
  106544. ** with DESC primary keys, since those indexes have there keys in
  106545. ** a different order from the main table.
  106546. ** See ticket: https://www.sqlite.org/src/info/bba7b69f9849b5bf
  106547. */
  106548. sqlite3VdbeAddOp1(v, OP_SeekEnd, iIdx);
  106549. }
  106550. sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdx, regRecord);
  106551. sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  106552. sqlite3ReleaseTempReg(pParse, regRecord);
  106553. sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2); VdbeCoverage(v);
  106554. sqlite3VdbeJumpHere(v, addr1);
  106555. sqlite3VdbeAddOp1(v, OP_Close, iTab);
  106556. sqlite3VdbeAddOp1(v, OP_Close, iIdx);
  106557. sqlite3VdbeAddOp1(v, OP_Close, iSorter);
  106558. }
  106559. /*
  106560. ** Allocate heap space to hold an Index object with nCol columns.
  106561. **
  106562. ** Increase the allocation size to provide an extra nExtra bytes
  106563. ** of 8-byte aligned space after the Index object and return a
  106564. ** pointer to this extra space in *ppExtra.
  106565. */
  106566. SQLITE_PRIVATE Index *sqlite3AllocateIndexObject(
  106567. sqlite3 *db, /* Database connection */
  106568. i16 nCol, /* Total number of columns in the index */
  106569. int nExtra, /* Number of bytes of extra space to alloc */
  106570. char **ppExtra /* Pointer to the "extra" space */
  106571. ){
  106572. Index *p; /* Allocated index object */
  106573. int nByte; /* Bytes of space for Index object + arrays */
  106574. nByte = ROUND8(sizeof(Index)) + /* Index structure */
  106575. ROUND8(sizeof(char*)*nCol) + /* Index.azColl */
  106576. ROUND8(sizeof(LogEst)*(nCol+1) + /* Index.aiRowLogEst */
  106577. sizeof(i16)*nCol + /* Index.aiColumn */
  106578. sizeof(u8)*nCol); /* Index.aSortOrder */
  106579. p = sqlite3DbMallocZero(db, nByte + nExtra);
  106580. if( p ){
  106581. char *pExtra = ((char*)p)+ROUND8(sizeof(Index));
  106582. p->azColl = (const char**)pExtra; pExtra += ROUND8(sizeof(char*)*nCol);
  106583. p->aiRowLogEst = (LogEst*)pExtra; pExtra += sizeof(LogEst)*(nCol+1);
  106584. p->aiColumn = (i16*)pExtra; pExtra += sizeof(i16)*nCol;
  106585. p->aSortOrder = (u8*)pExtra;
  106586. p->nColumn = nCol;
  106587. p->nKeyCol = nCol - 1;
  106588. *ppExtra = ((char*)p) + nByte;
  106589. }
  106590. return p;
  106591. }
  106592. /*
  106593. ** If expression list pList contains an expression that was parsed with
  106594. ** an explicit "NULLS FIRST" or "NULLS LAST" clause, leave an error in
  106595. ** pParse and return non-zero. Otherwise, return zero.
  106596. */
  106597. SQLITE_PRIVATE int sqlite3HasExplicitNulls(Parse *pParse, ExprList *pList){
  106598. if( pList ){
  106599. int i;
  106600. for(i=0; i<pList->nExpr; i++){
  106601. if( pList->a[i].bNulls ){
  106602. u8 sf = pList->a[i].sortFlags;
  106603. sqlite3ErrorMsg(pParse, "unsupported use of NULLS %s",
  106604. (sf==0 || sf==3) ? "FIRST" : "LAST"
  106605. );
  106606. return 1;
  106607. }
  106608. }
  106609. }
  106610. return 0;
  106611. }
  106612. /*
  106613. ** Create a new index for an SQL table. pName1.pName2 is the name of the index
  106614. ** and pTblList is the name of the table that is to be indexed. Both will
  106615. ** be NULL for a primary key or an index that is created to satisfy a
  106616. ** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable
  106617. ** as the table to be indexed. pParse->pNewTable is a table that is
  106618. ** currently being constructed by a CREATE TABLE statement.
  106619. **
  106620. ** pList is a list of columns to be indexed. pList will be NULL if this
  106621. ** is a primary key or unique-constraint on the most recent column added
  106622. ** to the table currently under construction.
  106623. */
  106624. SQLITE_PRIVATE void sqlite3CreateIndex(
  106625. Parse *pParse, /* All information about this parse */
  106626. Token *pName1, /* First part of index name. May be NULL */
  106627. Token *pName2, /* Second part of index name. May be NULL */
  106628. SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
  106629. ExprList *pList, /* A list of columns to be indexed */
  106630. int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
  106631. Token *pStart, /* The CREATE token that begins this statement */
  106632. Expr *pPIWhere, /* WHERE clause for partial indices */
  106633. int sortOrder, /* Sort order of primary key when pList==NULL */
  106634. int ifNotExist, /* Omit error if index already exists */
  106635. u8 idxType /* The index type */
  106636. ){
  106637. Table *pTab = 0; /* Table to be indexed */
  106638. Index *pIndex = 0; /* The index to be created */
  106639. char *zName = 0; /* Name of the index */
  106640. int nName; /* Number of characters in zName */
  106641. int i, j;
  106642. DbFixer sFix; /* For assigning database names to pTable */
  106643. int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */
  106644. sqlite3 *db = pParse->db;
  106645. Db *pDb; /* The specific table containing the indexed database */
  106646. int iDb; /* Index of the database that is being written */
  106647. Token *pName = 0; /* Unqualified name of the index to create */
  106648. struct ExprList_item *pListItem; /* For looping over pList */
  106649. int nExtra = 0; /* Space allocated for zExtra[] */
  106650. int nExtraCol; /* Number of extra columns needed */
  106651. char *zExtra = 0; /* Extra space after the Index object */
  106652. Index *pPk = 0; /* PRIMARY KEY index for WITHOUT ROWID tables */
  106653. if( db->mallocFailed || pParse->nErr>0 ){
  106654. goto exit_create_index;
  106655. }
  106656. if( IN_DECLARE_VTAB && idxType!=SQLITE_IDXTYPE_PRIMARYKEY ){
  106657. goto exit_create_index;
  106658. }
  106659. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  106660. goto exit_create_index;
  106661. }
  106662. if( sqlite3HasExplicitNulls(pParse, pList) ){
  106663. goto exit_create_index;
  106664. }
  106665. /*
  106666. ** Find the table that is to be indexed. Return early if not found.
  106667. */
  106668. if( pTblName!=0 ){
  106669. /* Use the two-part index name to determine the database
  106670. ** to search for the table. 'Fix' the table name to this db
  106671. ** before looking up the table.
  106672. */
  106673. assert( pName1 && pName2 );
  106674. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  106675. if( iDb<0 ) goto exit_create_index;
  106676. assert( pName && pName->z );
  106677. #ifndef SQLITE_OMIT_TEMPDB
  106678. /* If the index name was unqualified, check if the table
  106679. ** is a temp table. If so, set the database to 1. Do not do this
  106680. ** if initialising a database schema.
  106681. */
  106682. if( !db->init.busy ){
  106683. pTab = sqlite3SrcListLookup(pParse, pTblName);
  106684. if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
  106685. iDb = 1;
  106686. }
  106687. }
  106688. #endif
  106689. sqlite3FixInit(&sFix, pParse, iDb, "index", pName);
  106690. if( sqlite3FixSrcList(&sFix, pTblName) ){
  106691. /* Because the parser constructs pTblName from a single identifier,
  106692. ** sqlite3FixSrcList can never fail. */
  106693. assert(0);
  106694. }
  106695. pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]);
  106696. assert( db->mallocFailed==0 || pTab==0 );
  106697. if( pTab==0 ) goto exit_create_index;
  106698. if( iDb==1 && db->aDb[iDb].pSchema!=pTab->pSchema ){
  106699. sqlite3ErrorMsg(pParse,
  106700. "cannot create a TEMP index on non-TEMP table \"%s\"",
  106701. pTab->zName);
  106702. goto exit_create_index;
  106703. }
  106704. if( !HasRowid(pTab) ) pPk = sqlite3PrimaryKeyIndex(pTab);
  106705. }else{
  106706. assert( pName==0 );
  106707. assert( pStart==0 );
  106708. pTab = pParse->pNewTable;
  106709. if( !pTab ) goto exit_create_index;
  106710. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  106711. }
  106712. pDb = &db->aDb[iDb];
  106713. assert( pTab!=0 );
  106714. assert( pParse->nErr==0 );
  106715. if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
  106716. && db->init.busy==0
  106717. && pTblName!=0
  106718. #if SQLITE_USER_AUTHENTICATION
  106719. && sqlite3UserAuthTable(pTab->zName)==0
  106720. #endif
  106721. #ifdef SQLITE_ALLOW_SQLITE_MASTER_INDEX
  106722. && sqlite3StrICmp(&pTab->zName[7],"master")!=0
  106723. #endif
  106724. ){
  106725. sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
  106726. goto exit_create_index;
  106727. }
  106728. #ifndef SQLITE_OMIT_VIEW
  106729. if( pTab->pSelect ){
  106730. sqlite3ErrorMsg(pParse, "views may not be indexed");
  106731. goto exit_create_index;
  106732. }
  106733. #endif
  106734. #ifndef SQLITE_OMIT_VIRTUALTABLE
  106735. if( IsVirtual(pTab) ){
  106736. sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
  106737. goto exit_create_index;
  106738. }
  106739. #endif
  106740. /*
  106741. ** Find the name of the index. Make sure there is not already another
  106742. ** index or table with the same name.
  106743. **
  106744. ** Exception: If we are reading the names of permanent indices from the
  106745. ** sqlite_master table (because some other process changed the schema) and
  106746. ** one of the index names collides with the name of a temporary table or
  106747. ** index, then we will continue to process this index.
  106748. **
  106749. ** If pName==0 it means that we are
  106750. ** dealing with a primary key or UNIQUE constraint. We have to invent our
  106751. ** own name.
  106752. */
  106753. if( pName ){
  106754. zName = sqlite3NameFromToken(db, pName);
  106755. if( zName==0 ) goto exit_create_index;
  106756. assert( pName->z!=0 );
  106757. if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName,"index",pTab->zName) ){
  106758. goto exit_create_index;
  106759. }
  106760. if( !IN_RENAME_OBJECT ){
  106761. if( !db->init.busy ){
  106762. if( sqlite3FindTable(db, zName, 0)!=0 ){
  106763. sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
  106764. goto exit_create_index;
  106765. }
  106766. }
  106767. if( sqlite3FindIndex(db, zName, pDb->zDbSName)!=0 ){
  106768. if( !ifNotExist ){
  106769. sqlite3ErrorMsg(pParse, "index %s already exists", zName);
  106770. }else{
  106771. assert( !db->init.busy );
  106772. sqlite3CodeVerifySchema(pParse, iDb);
  106773. }
  106774. goto exit_create_index;
  106775. }
  106776. }
  106777. }else{
  106778. int n;
  106779. Index *pLoop;
  106780. for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
  106781. zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
  106782. if( zName==0 ){
  106783. goto exit_create_index;
  106784. }
  106785. /* Automatic index names generated from within sqlite3_declare_vtab()
  106786. ** must have names that are distinct from normal automatic index names.
  106787. ** The following statement converts "sqlite3_autoindex..." into
  106788. ** "sqlite3_butoindex..." in order to make the names distinct.
  106789. ** The "vtab_err.test" test demonstrates the need of this statement. */
  106790. if( IN_SPECIAL_PARSE ) zName[7]++;
  106791. }
  106792. /* Check for authorization to create an index.
  106793. */
  106794. #ifndef SQLITE_OMIT_AUTHORIZATION
  106795. if( !IN_RENAME_OBJECT ){
  106796. const char *zDb = pDb->zDbSName;
  106797. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
  106798. goto exit_create_index;
  106799. }
  106800. i = SQLITE_CREATE_INDEX;
  106801. if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
  106802. if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
  106803. goto exit_create_index;
  106804. }
  106805. }
  106806. #endif
  106807. /* If pList==0, it means this routine was called to make a primary
  106808. ** key out of the last column added to the table under construction.
  106809. ** So create a fake list to simulate this.
  106810. */
  106811. if( pList==0 ){
  106812. Token prevCol;
  106813. Column *pCol = &pTab->aCol[pTab->nCol-1];
  106814. pCol->colFlags |= COLFLAG_UNIQUE;
  106815. sqlite3TokenInit(&prevCol, pCol->zName);
  106816. pList = sqlite3ExprListAppend(pParse, 0,
  106817. sqlite3ExprAlloc(db, TK_ID, &prevCol, 0));
  106818. if( pList==0 ) goto exit_create_index;
  106819. assert( pList->nExpr==1 );
  106820. sqlite3ExprListSetSortOrder(pList, sortOrder, SQLITE_SO_UNDEFINED);
  106821. }else{
  106822. sqlite3ExprListCheckLength(pParse, pList, "index");
  106823. if( pParse->nErr ) goto exit_create_index;
  106824. }
  106825. /* Figure out how many bytes of space are required to store explicitly
  106826. ** specified collation sequence names.
  106827. */
  106828. for(i=0; i<pList->nExpr; i++){
  106829. Expr *pExpr = pList->a[i].pExpr;
  106830. assert( pExpr!=0 );
  106831. if( pExpr->op==TK_COLLATE ){
  106832. nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken));
  106833. }
  106834. }
  106835. /*
  106836. ** Allocate the index structure.
  106837. */
  106838. nName = sqlite3Strlen30(zName);
  106839. nExtraCol = pPk ? pPk->nKeyCol : 1;
  106840. assert( pList->nExpr + nExtraCol <= 32767 /* Fits in i16 */ );
  106841. pIndex = sqlite3AllocateIndexObject(db, pList->nExpr + nExtraCol,
  106842. nName + nExtra + 1, &zExtra);
  106843. if( db->mallocFailed ){
  106844. goto exit_create_index;
  106845. }
  106846. assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowLogEst) );
  106847. assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
  106848. pIndex->zName = zExtra;
  106849. zExtra += nName + 1;
  106850. memcpy(pIndex->zName, zName, nName+1);
  106851. pIndex->pTable = pTab;
  106852. pIndex->onError = (u8)onError;
  106853. pIndex->uniqNotNull = onError!=OE_None;
  106854. pIndex->idxType = idxType;
  106855. pIndex->pSchema = db->aDb[iDb].pSchema;
  106856. pIndex->nKeyCol = pList->nExpr;
  106857. if( pPIWhere ){
  106858. sqlite3ResolveSelfReference(pParse, pTab, NC_PartIdx, pPIWhere, 0);
  106859. pIndex->pPartIdxWhere = pPIWhere;
  106860. pPIWhere = 0;
  106861. }
  106862. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  106863. /* Check to see if we should honor DESC requests on index columns
  106864. */
  106865. if( pDb->pSchema->file_format>=4 ){
  106866. sortOrderMask = -1; /* Honor DESC */
  106867. }else{
  106868. sortOrderMask = 0; /* Ignore DESC */
  106869. }
  106870. /* Analyze the list of expressions that form the terms of the index and
  106871. ** report any errors. In the common case where the expression is exactly
  106872. ** a table column, store that column in aiColumn[]. For general expressions,
  106873. ** populate pIndex->aColExpr and store XN_EXPR (-2) in aiColumn[].
  106874. **
  106875. ** TODO: Issue a warning if two or more columns of the index are identical.
  106876. ** TODO: Issue a warning if the table primary key is used as part of the
  106877. ** index key.
  106878. */
  106879. pListItem = pList->a;
  106880. if( IN_RENAME_OBJECT ){
  106881. pIndex->aColExpr = pList;
  106882. pList = 0;
  106883. }
  106884. for(i=0; i<pIndex->nKeyCol; i++, pListItem++){
  106885. Expr *pCExpr; /* The i-th index expression */
  106886. int requestedSortOrder; /* ASC or DESC on the i-th expression */
  106887. const char *zColl; /* Collation sequence name */
  106888. sqlite3StringToId(pListItem->pExpr);
  106889. sqlite3ResolveSelfReference(pParse, pTab, NC_IdxExpr, pListItem->pExpr, 0);
  106890. if( pParse->nErr ) goto exit_create_index;
  106891. pCExpr = sqlite3ExprSkipCollate(pListItem->pExpr);
  106892. if( pCExpr->op!=TK_COLUMN ){
  106893. if( pTab==pParse->pNewTable ){
  106894. sqlite3ErrorMsg(pParse, "expressions prohibited in PRIMARY KEY and "
  106895. "UNIQUE constraints");
  106896. goto exit_create_index;
  106897. }
  106898. if( pIndex->aColExpr==0 ){
  106899. pIndex->aColExpr = pList;
  106900. pList = 0;
  106901. }
  106902. j = XN_EXPR;
  106903. pIndex->aiColumn[i] = XN_EXPR;
  106904. pIndex->uniqNotNull = 0;
  106905. }else{
  106906. j = pCExpr->iColumn;
  106907. assert( j<=0x7fff );
  106908. if( j<0 ){
  106909. j = pTab->iPKey;
  106910. }else{
  106911. if( pTab->aCol[j].notNull==0 ){
  106912. pIndex->uniqNotNull = 0;
  106913. }
  106914. if( pTab->aCol[j].colFlags & COLFLAG_VIRTUAL ){
  106915. pIndex->bHasVCol = 1;
  106916. }
  106917. }
  106918. pIndex->aiColumn[i] = (i16)j;
  106919. }
  106920. zColl = 0;
  106921. if( pListItem->pExpr->op==TK_COLLATE ){
  106922. int nColl;
  106923. zColl = pListItem->pExpr->u.zToken;
  106924. nColl = sqlite3Strlen30(zColl) + 1;
  106925. assert( nExtra>=nColl );
  106926. memcpy(zExtra, zColl, nColl);
  106927. zColl = zExtra;
  106928. zExtra += nColl;
  106929. nExtra -= nColl;
  106930. }else if( j>=0 ){
  106931. zColl = pTab->aCol[j].zColl;
  106932. }
  106933. if( !zColl ) zColl = sqlite3StrBINARY;
  106934. if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
  106935. goto exit_create_index;
  106936. }
  106937. pIndex->azColl[i] = zColl;
  106938. requestedSortOrder = pListItem->sortFlags & sortOrderMask;
  106939. pIndex->aSortOrder[i] = (u8)requestedSortOrder;
  106940. }
  106941. /* Append the table key to the end of the index. For WITHOUT ROWID
  106942. ** tables (when pPk!=0) this will be the declared PRIMARY KEY. For
  106943. ** normal tables (when pPk==0) this will be the rowid.
  106944. */
  106945. if( pPk ){
  106946. for(j=0; j<pPk->nKeyCol; j++){
  106947. int x = pPk->aiColumn[j];
  106948. assert( x>=0 );
  106949. if( isDupColumn(pIndex, pIndex->nKeyCol, pPk, j) ){
  106950. pIndex->nColumn--;
  106951. }else{
  106952. testcase( hasColumn(pIndex->aiColumn,pIndex->nKeyCol,x) );
  106953. pIndex->aiColumn[i] = x;
  106954. pIndex->azColl[i] = pPk->azColl[j];
  106955. pIndex->aSortOrder[i] = pPk->aSortOrder[j];
  106956. i++;
  106957. }
  106958. }
  106959. assert( i==pIndex->nColumn );
  106960. }else{
  106961. pIndex->aiColumn[i] = XN_ROWID;
  106962. pIndex->azColl[i] = sqlite3StrBINARY;
  106963. }
  106964. sqlite3DefaultRowEst(pIndex);
  106965. if( pParse->pNewTable==0 ) estimateIndexWidth(pIndex);
  106966. /* If this index contains every column of its table, then mark
  106967. ** it as a covering index */
  106968. assert( HasRowid(pTab)
  106969. || pTab->iPKey<0 || sqlite3TableColumnToIndex(pIndex, pTab->iPKey)>=0 );
  106970. recomputeColumnsNotIndexed(pIndex);
  106971. if( pTblName!=0 && pIndex->nColumn>=pTab->nCol ){
  106972. pIndex->isCovering = 1;
  106973. for(j=0; j<pTab->nCol; j++){
  106974. if( j==pTab->iPKey ) continue;
  106975. if( sqlite3TableColumnToIndex(pIndex,j)>=0 ) continue;
  106976. pIndex->isCovering = 0;
  106977. break;
  106978. }
  106979. }
  106980. if( pTab==pParse->pNewTable ){
  106981. /* This routine has been called to create an automatic index as a
  106982. ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
  106983. ** a PRIMARY KEY or UNIQUE clause following the column definitions.
  106984. ** i.e. one of:
  106985. **
  106986. ** CREATE TABLE t(x PRIMARY KEY, y);
  106987. ** CREATE TABLE t(x, y, UNIQUE(x, y));
  106988. **
  106989. ** Either way, check to see if the table already has such an index. If
  106990. ** so, don't bother creating this one. This only applies to
  106991. ** automatically created indices. Users can do as they wish with
  106992. ** explicit indices.
  106993. **
  106994. ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
  106995. ** (and thus suppressing the second one) even if they have different
  106996. ** sort orders.
  106997. **
  106998. ** If there are different collating sequences or if the columns of
  106999. ** the constraint occur in different orders, then the constraints are
  107000. ** considered distinct and both result in separate indices.
  107001. */
  107002. Index *pIdx;
  107003. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  107004. int k;
  107005. assert( IsUniqueIndex(pIdx) );
  107006. assert( pIdx->idxType!=SQLITE_IDXTYPE_APPDEF );
  107007. assert( IsUniqueIndex(pIndex) );
  107008. if( pIdx->nKeyCol!=pIndex->nKeyCol ) continue;
  107009. for(k=0; k<pIdx->nKeyCol; k++){
  107010. const char *z1;
  107011. const char *z2;
  107012. assert( pIdx->aiColumn[k]>=0 );
  107013. if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
  107014. z1 = pIdx->azColl[k];
  107015. z2 = pIndex->azColl[k];
  107016. if( sqlite3StrICmp(z1, z2) ) break;
  107017. }
  107018. if( k==pIdx->nKeyCol ){
  107019. if( pIdx->onError!=pIndex->onError ){
  107020. /* This constraint creates the same index as a previous
  107021. ** constraint specified somewhere in the CREATE TABLE statement.
  107022. ** However the ON CONFLICT clauses are different. If both this
  107023. ** constraint and the previous equivalent constraint have explicit
  107024. ** ON CONFLICT clauses this is an error. Otherwise, use the
  107025. ** explicitly specified behavior for the index.
  107026. */
  107027. if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
  107028. sqlite3ErrorMsg(pParse,
  107029. "conflicting ON CONFLICT clauses specified", 0);
  107030. }
  107031. if( pIdx->onError==OE_Default ){
  107032. pIdx->onError = pIndex->onError;
  107033. }
  107034. }
  107035. if( idxType==SQLITE_IDXTYPE_PRIMARYKEY ) pIdx->idxType = idxType;
  107036. if( IN_RENAME_OBJECT ){
  107037. pIndex->pNext = pParse->pNewIndex;
  107038. pParse->pNewIndex = pIndex;
  107039. pIndex = 0;
  107040. }
  107041. goto exit_create_index;
  107042. }
  107043. }
  107044. }
  107045. if( !IN_RENAME_OBJECT ){
  107046. /* Link the new Index structure to its table and to the other
  107047. ** in-memory database structures.
  107048. */
  107049. assert( pParse->nErr==0 );
  107050. if( db->init.busy ){
  107051. Index *p;
  107052. assert( !IN_SPECIAL_PARSE );
  107053. assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
  107054. if( pTblName!=0 ){
  107055. pIndex->tnum = db->init.newTnum;
  107056. if( sqlite3IndexHasDuplicateRootPage(pIndex) ){
  107057. sqlite3ErrorMsg(pParse, "invalid rootpage");
  107058. pParse->rc = SQLITE_CORRUPT_BKPT;
  107059. goto exit_create_index;
  107060. }
  107061. }
  107062. p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
  107063. pIndex->zName, pIndex);
  107064. if( p ){
  107065. assert( p==pIndex ); /* Malloc must have failed */
  107066. sqlite3OomFault(db);
  107067. goto exit_create_index;
  107068. }
  107069. db->mDbFlags |= DBFLAG_SchemaChange;
  107070. }
  107071. /* If this is the initial CREATE INDEX statement (or CREATE TABLE if the
  107072. ** index is an implied index for a UNIQUE or PRIMARY KEY constraint) then
  107073. ** emit code to allocate the index rootpage on disk and make an entry for
  107074. ** the index in the sqlite_master table and populate the index with
  107075. ** content. But, do not do this if we are simply reading the sqlite_master
  107076. ** table to parse the schema, or if this index is the PRIMARY KEY index
  107077. ** of a WITHOUT ROWID table.
  107078. **
  107079. ** If pTblName==0 it means this index is generated as an implied PRIMARY KEY
  107080. ** or UNIQUE index in a CREATE TABLE statement. Since the table
  107081. ** has just been created, it contains no data and the index initialization
  107082. ** step can be skipped.
  107083. */
  107084. else if( HasRowid(pTab) || pTblName!=0 ){
  107085. Vdbe *v;
  107086. char *zStmt;
  107087. int iMem = ++pParse->nMem;
  107088. v = sqlite3GetVdbe(pParse);
  107089. if( v==0 ) goto exit_create_index;
  107090. sqlite3BeginWriteOperation(pParse, 1, iDb);
  107091. /* Create the rootpage for the index using CreateIndex. But before
  107092. ** doing so, code a Noop instruction and store its address in
  107093. ** Index.tnum. This is required in case this index is actually a
  107094. ** PRIMARY KEY and the table is actually a WITHOUT ROWID table. In
  107095. ** that case the convertToWithoutRowidTable() routine will replace
  107096. ** the Noop with a Goto to jump over the VDBE code generated below. */
  107097. pIndex->tnum = sqlite3VdbeAddOp0(v, OP_Noop);
  107098. sqlite3VdbeAddOp3(v, OP_CreateBtree, iDb, iMem, BTREE_BLOBKEY);
  107099. /* Gather the complete text of the CREATE INDEX statement into
  107100. ** the zStmt variable
  107101. */
  107102. assert( pName!=0 || pStart==0 );
  107103. if( pStart ){
  107104. int n = (int)(pParse->sLastToken.z - pName->z) + pParse->sLastToken.n;
  107105. if( pName->z[n-1]==';' ) n--;
  107106. /* A named index with an explicit CREATE INDEX statement */
  107107. zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
  107108. onError==OE_None ? "" : " UNIQUE", n, pName->z);
  107109. }else{
  107110. /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
  107111. /* zStmt = sqlite3MPrintf(""); */
  107112. zStmt = 0;
  107113. }
  107114. /* Add an entry in sqlite_master for this index
  107115. */
  107116. sqlite3NestedParse(pParse,
  107117. "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
  107118. db->aDb[iDb].zDbSName, MASTER_NAME,
  107119. pIndex->zName,
  107120. pTab->zName,
  107121. iMem,
  107122. zStmt
  107123. );
  107124. sqlite3DbFree(db, zStmt);
  107125. /* Fill the index with data and reparse the schema. Code an OP_Expire
  107126. ** to invalidate all pre-compiled statements.
  107127. */
  107128. if( pTblName ){
  107129. sqlite3RefillIndex(pParse, pIndex, iMem);
  107130. sqlite3ChangeCookie(pParse, iDb);
  107131. sqlite3VdbeAddParseSchemaOp(v, iDb,
  107132. sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName));
  107133. sqlite3VdbeAddOp2(v, OP_Expire, 0, 1);
  107134. }
  107135. sqlite3VdbeJumpHere(v, pIndex->tnum);
  107136. }
  107137. }
  107138. if( db->init.busy || pTblName==0 ){
  107139. pIndex->pNext = pTab->pIndex;
  107140. pTab->pIndex = pIndex;
  107141. pIndex = 0;
  107142. }
  107143. else if( IN_RENAME_OBJECT ){
  107144. assert( pParse->pNewIndex==0 );
  107145. pParse->pNewIndex = pIndex;
  107146. pIndex = 0;
  107147. }
  107148. /* Clean up before exiting */
  107149. exit_create_index:
  107150. if( pIndex ) sqlite3FreeIndex(db, pIndex);
  107151. if( pTab ){ /* Ensure all REPLACE indexes are at the end of the list */
  107152. Index **ppFrom = &pTab->pIndex;
  107153. Index *pThis;
  107154. for(ppFrom=&pTab->pIndex; (pThis = *ppFrom)!=0; ppFrom=&pThis->pNext){
  107155. Index *pNext;
  107156. if( pThis->onError!=OE_Replace ) continue;
  107157. while( (pNext = pThis->pNext)!=0 && pNext->onError!=OE_Replace ){
  107158. *ppFrom = pNext;
  107159. pThis->pNext = pNext->pNext;
  107160. pNext->pNext = pThis;
  107161. ppFrom = &pNext->pNext;
  107162. }
  107163. break;
  107164. }
  107165. }
  107166. sqlite3ExprDelete(db, pPIWhere);
  107167. sqlite3ExprListDelete(db, pList);
  107168. sqlite3SrcListDelete(db, pTblName);
  107169. sqlite3DbFree(db, zName);
  107170. }
  107171. /*
  107172. ** Fill the Index.aiRowEst[] array with default information - information
  107173. ** to be used when we have not run the ANALYZE command.
  107174. **
  107175. ** aiRowEst[0] is supposed to contain the number of elements in the index.
  107176. ** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the
  107177. ** number of rows in the table that match any particular value of the
  107178. ** first column of the index. aiRowEst[2] is an estimate of the number
  107179. ** of rows that match any particular combination of the first 2 columns
  107180. ** of the index. And so forth. It must always be the case that
  107181. *
  107182. ** aiRowEst[N]<=aiRowEst[N-1]
  107183. ** aiRowEst[N]>=1
  107184. **
  107185. ** Apart from that, we have little to go on besides intuition as to
  107186. ** how aiRowEst[] should be initialized. The numbers generated here
  107187. ** are based on typical values found in actual indices.
  107188. */
  107189. SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
  107190. /* 10, 9, 8, 7, 6 */
  107191. LogEst aVal[] = { 33, 32, 30, 28, 26 };
  107192. LogEst *a = pIdx->aiRowLogEst;
  107193. int nCopy = MIN(ArraySize(aVal), pIdx->nKeyCol);
  107194. int i;
  107195. /* Indexes with default row estimates should not have stat1 data */
  107196. assert( !pIdx->hasStat1 );
  107197. /* Set the first entry (number of rows in the index) to the estimated
  107198. ** number of rows in the table, or half the number of rows in the table
  107199. ** for a partial index. But do not let the estimate drop below 10. */
  107200. a[0] = pIdx->pTable->nRowLogEst;
  107201. if( pIdx->pPartIdxWhere!=0 ) a[0] -= 10; assert( 10==sqlite3LogEst(2) );
  107202. if( a[0]<33 ) a[0] = 33; assert( 33==sqlite3LogEst(10) );
  107203. /* Estimate that a[1] is 10, a[2] is 9, a[3] is 8, a[4] is 7, a[5] is
  107204. ** 6 and each subsequent value (if any) is 5. */
  107205. memcpy(&a[1], aVal, nCopy*sizeof(LogEst));
  107206. for(i=nCopy+1; i<=pIdx->nKeyCol; i++){
  107207. a[i] = 23; assert( 23==sqlite3LogEst(5) );
  107208. }
  107209. assert( 0==sqlite3LogEst(1) );
  107210. if( IsUniqueIndex(pIdx) ) a[pIdx->nKeyCol] = 0;
  107211. }
  107212. /*
  107213. ** This routine will drop an existing named index. This routine
  107214. ** implements the DROP INDEX statement.
  107215. */
  107216. SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
  107217. Index *pIndex;
  107218. Vdbe *v;
  107219. sqlite3 *db = pParse->db;
  107220. int iDb;
  107221. assert( pParse->nErr==0 ); /* Never called with prior errors */
  107222. if( db->mallocFailed ){
  107223. goto exit_drop_index;
  107224. }
  107225. assert( pName->nSrc==1 );
  107226. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  107227. goto exit_drop_index;
  107228. }
  107229. pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
  107230. if( pIndex==0 ){
  107231. if( !ifExists ){
  107232. sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
  107233. }else{
  107234. sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
  107235. }
  107236. pParse->checkSchema = 1;
  107237. goto exit_drop_index;
  107238. }
  107239. if( pIndex->idxType!=SQLITE_IDXTYPE_APPDEF ){
  107240. sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
  107241. "or PRIMARY KEY constraint cannot be dropped", 0);
  107242. goto exit_drop_index;
  107243. }
  107244. iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
  107245. #ifndef SQLITE_OMIT_AUTHORIZATION
  107246. {
  107247. int code = SQLITE_DROP_INDEX;
  107248. Table *pTab = pIndex->pTable;
  107249. const char *zDb = db->aDb[iDb].zDbSName;
  107250. const char *zTab = SCHEMA_TABLE(iDb);
  107251. if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
  107252. goto exit_drop_index;
  107253. }
  107254. if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
  107255. if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
  107256. goto exit_drop_index;
  107257. }
  107258. }
  107259. #endif
  107260. /* Generate code to remove the index and from the master table */
  107261. v = sqlite3GetVdbe(pParse);
  107262. if( v ){
  107263. sqlite3BeginWriteOperation(pParse, 1, iDb);
  107264. sqlite3NestedParse(pParse,
  107265. "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
  107266. db->aDb[iDb].zDbSName, MASTER_NAME, pIndex->zName
  107267. );
  107268. sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
  107269. sqlite3ChangeCookie(pParse, iDb);
  107270. destroyRootPage(pParse, pIndex->tnum, iDb);
  107271. sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
  107272. }
  107273. exit_drop_index:
  107274. sqlite3SrcListDelete(db, pName);
  107275. }
  107276. /*
  107277. ** pArray is a pointer to an array of objects. Each object in the
  107278. ** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()
  107279. ** to extend the array so that there is space for a new object at the end.
  107280. **
  107281. ** When this function is called, *pnEntry contains the current size of
  107282. ** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
  107283. ** in total).
  107284. **
  107285. ** If the realloc() is successful (i.e. if no OOM condition occurs), the
  107286. ** space allocated for the new object is zeroed, *pnEntry updated to
  107287. ** reflect the new size of the array and a pointer to the new allocation
  107288. ** returned. *pIdx is set to the index of the new array entry in this case.
  107289. **
  107290. ** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
  107291. ** unchanged and a copy of pArray returned.
  107292. */
  107293. SQLITE_PRIVATE void *sqlite3ArrayAllocate(
  107294. sqlite3 *db, /* Connection to notify of malloc failures */
  107295. void *pArray, /* Array of objects. Might be reallocated */
  107296. int szEntry, /* Size of each object in the array */
  107297. int *pnEntry, /* Number of objects currently in use */
  107298. int *pIdx /* Write the index of a new slot here */
  107299. ){
  107300. char *z;
  107301. sqlite3_int64 n = *pIdx = *pnEntry;
  107302. if( (n & (n-1))==0 ){
  107303. sqlite3_int64 sz = (n==0) ? 1 : 2*n;
  107304. void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry);
  107305. if( pNew==0 ){
  107306. *pIdx = -1;
  107307. return pArray;
  107308. }
  107309. pArray = pNew;
  107310. }
  107311. z = (char*)pArray;
  107312. memset(&z[n * szEntry], 0, szEntry);
  107313. ++*pnEntry;
  107314. return pArray;
  107315. }
  107316. /*
  107317. ** Append a new element to the given IdList. Create a new IdList if
  107318. ** need be.
  107319. **
  107320. ** A new IdList is returned, or NULL if malloc() fails.
  107321. */
  107322. SQLITE_PRIVATE IdList *sqlite3IdListAppend(Parse *pParse, IdList *pList, Token *pToken){
  107323. sqlite3 *db = pParse->db;
  107324. int i;
  107325. if( pList==0 ){
  107326. pList = sqlite3DbMallocZero(db, sizeof(IdList) );
  107327. if( pList==0 ) return 0;
  107328. }
  107329. pList->a = sqlite3ArrayAllocate(
  107330. db,
  107331. pList->a,
  107332. sizeof(pList->a[0]),
  107333. &pList->nId,
  107334. &i
  107335. );
  107336. if( i<0 ){
  107337. sqlite3IdListDelete(db, pList);
  107338. return 0;
  107339. }
  107340. pList->a[i].zName = sqlite3NameFromToken(db, pToken);
  107341. if( IN_RENAME_OBJECT && pList->a[i].zName ){
  107342. sqlite3RenameTokenMap(pParse, (void*)pList->a[i].zName, pToken);
  107343. }
  107344. return pList;
  107345. }
  107346. /*
  107347. ** Delete an IdList.
  107348. */
  107349. SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
  107350. int i;
  107351. if( pList==0 ) return;
  107352. for(i=0; i<pList->nId; i++){
  107353. sqlite3DbFree(db, pList->a[i].zName);
  107354. }
  107355. sqlite3DbFree(db, pList->a);
  107356. sqlite3DbFreeNN(db, pList);
  107357. }
  107358. /*
  107359. ** Return the index in pList of the identifier named zId. Return -1
  107360. ** if not found.
  107361. */
  107362. SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){
  107363. int i;
  107364. if( pList==0 ) return -1;
  107365. for(i=0; i<pList->nId; i++){
  107366. if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
  107367. }
  107368. return -1;
  107369. }
  107370. /*
  107371. ** Maximum size of a SrcList object.
  107372. ** The SrcList object is used to represent the FROM clause of a
  107373. ** SELECT statement, and the query planner cannot deal with more
  107374. ** than 64 tables in a join. So any value larger than 64 here
  107375. ** is sufficient for most uses. Smaller values, like say 10, are
  107376. ** appropriate for small and memory-limited applications.
  107377. */
  107378. #ifndef SQLITE_MAX_SRCLIST
  107379. # define SQLITE_MAX_SRCLIST 200
  107380. #endif
  107381. /*
  107382. ** Expand the space allocated for the given SrcList object by
  107383. ** creating nExtra new slots beginning at iStart. iStart is zero based.
  107384. ** New slots are zeroed.
  107385. **
  107386. ** For example, suppose a SrcList initially contains two entries: A,B.
  107387. ** To append 3 new entries onto the end, do this:
  107388. **
  107389. ** sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
  107390. **
  107391. ** After the call above it would contain: A, B, nil, nil, nil.
  107392. ** If the iStart argument had been 1 instead of 2, then the result
  107393. ** would have been: A, nil, nil, nil, B. To prepend the new slots,
  107394. ** the iStart value would be 0. The result then would
  107395. ** be: nil, nil, nil, A, B.
  107396. **
  107397. ** If a memory allocation fails or the SrcList becomes too large, leave
  107398. ** the original SrcList unchanged, return NULL, and leave an error message
  107399. ** in pParse.
  107400. */
  107401. SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(
  107402. Parse *pParse, /* Parsing context into which errors are reported */
  107403. SrcList *pSrc, /* The SrcList to be enlarged */
  107404. int nExtra, /* Number of new slots to add to pSrc->a[] */
  107405. int iStart /* Index in pSrc->a[] of first new slot */
  107406. ){
  107407. int i;
  107408. /* Sanity checking on calling parameters */
  107409. assert( iStart>=0 );
  107410. assert( nExtra>=1 );
  107411. assert( pSrc!=0 );
  107412. assert( iStart<=pSrc->nSrc );
  107413. /* Allocate additional space if needed */
  107414. if( (u32)pSrc->nSrc+nExtra>pSrc->nAlloc ){
  107415. SrcList *pNew;
  107416. sqlite3_int64 nAlloc = 2*(sqlite3_int64)pSrc->nSrc+nExtra;
  107417. sqlite3 *db = pParse->db;
  107418. if( pSrc->nSrc+nExtra>=SQLITE_MAX_SRCLIST ){
  107419. sqlite3ErrorMsg(pParse, "too many FROM clause terms, max: %d",
  107420. SQLITE_MAX_SRCLIST);
  107421. return 0;
  107422. }
  107423. if( nAlloc>SQLITE_MAX_SRCLIST ) nAlloc = SQLITE_MAX_SRCLIST;
  107424. pNew = sqlite3DbRealloc(db, pSrc,
  107425. sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
  107426. if( pNew==0 ){
  107427. assert( db->mallocFailed );
  107428. return 0;
  107429. }
  107430. pSrc = pNew;
  107431. pSrc->nAlloc = nAlloc;
  107432. }
  107433. /* Move existing slots that come after the newly inserted slots
  107434. ** out of the way */
  107435. for(i=pSrc->nSrc-1; i>=iStart; i--){
  107436. pSrc->a[i+nExtra] = pSrc->a[i];
  107437. }
  107438. pSrc->nSrc += nExtra;
  107439. /* Zero the newly allocated slots */
  107440. memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
  107441. for(i=iStart; i<iStart+nExtra; i++){
  107442. pSrc->a[i].iCursor = -1;
  107443. }
  107444. /* Return a pointer to the enlarged SrcList */
  107445. return pSrc;
  107446. }
  107447. /*
  107448. ** Append a new table name to the given SrcList. Create a new SrcList if
  107449. ** need be. A new entry is created in the SrcList even if pTable is NULL.
  107450. **
  107451. ** A SrcList is returned, or NULL if there is an OOM error or if the
  107452. ** SrcList grows to large. The returned
  107453. ** SrcList might be the same as the SrcList that was input or it might be
  107454. ** a new one. If an OOM error does occurs, then the prior value of pList
  107455. ** that is input to this routine is automatically freed.
  107456. **
  107457. ** If pDatabase is not null, it means that the table has an optional
  107458. ** database name prefix. Like this: "database.table". The pDatabase
  107459. ** points to the table name and the pTable points to the database name.
  107460. ** The SrcList.a[].zName field is filled with the table name which might
  107461. ** come from pTable (if pDatabase is NULL) or from pDatabase.
  107462. ** SrcList.a[].zDatabase is filled with the database name from pTable,
  107463. ** or with NULL if no database is specified.
  107464. **
  107465. ** In other words, if call like this:
  107466. **
  107467. ** sqlite3SrcListAppend(D,A,B,0);
  107468. **
  107469. ** Then B is a table name and the database name is unspecified. If called
  107470. ** like this:
  107471. **
  107472. ** sqlite3SrcListAppend(D,A,B,C);
  107473. **
  107474. ** Then C is the table name and B is the database name. If C is defined
  107475. ** then so is B. In other words, we never have a case where:
  107476. **
  107477. ** sqlite3SrcListAppend(D,A,0,C);
  107478. **
  107479. ** Both pTable and pDatabase are assumed to be quoted. They are dequoted
  107480. ** before being added to the SrcList.
  107481. */
  107482. SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(
  107483. Parse *pParse, /* Parsing context, in which errors are reported */
  107484. SrcList *pList, /* Append to this SrcList. NULL creates a new SrcList */
  107485. Token *pTable, /* Table to append */
  107486. Token *pDatabase /* Database of the table */
  107487. ){
  107488. struct SrcList_item *pItem;
  107489. sqlite3 *db;
  107490. assert( pDatabase==0 || pTable!=0 ); /* Cannot have C without B */
  107491. assert( pParse!=0 );
  107492. assert( pParse->db!=0 );
  107493. db = pParse->db;
  107494. if( pList==0 ){
  107495. pList = sqlite3DbMallocRawNN(pParse->db, sizeof(SrcList) );
  107496. if( pList==0 ) return 0;
  107497. pList->nAlloc = 1;
  107498. pList->nSrc = 1;
  107499. memset(&pList->a[0], 0, sizeof(pList->a[0]));
  107500. pList->a[0].iCursor = -1;
  107501. }else{
  107502. SrcList *pNew = sqlite3SrcListEnlarge(pParse, pList, 1, pList->nSrc);
  107503. if( pNew==0 ){
  107504. sqlite3SrcListDelete(db, pList);
  107505. return 0;
  107506. }else{
  107507. pList = pNew;
  107508. }
  107509. }
  107510. pItem = &pList->a[pList->nSrc-1];
  107511. if( pDatabase && pDatabase->z==0 ){
  107512. pDatabase = 0;
  107513. }
  107514. if( pDatabase ){
  107515. pItem->zName = sqlite3NameFromToken(db, pDatabase);
  107516. pItem->zDatabase = sqlite3NameFromToken(db, pTable);
  107517. }else{
  107518. pItem->zName = sqlite3NameFromToken(db, pTable);
  107519. pItem->zDatabase = 0;
  107520. }
  107521. return pList;
  107522. }
  107523. /*
  107524. ** Assign VdbeCursor index numbers to all tables in a SrcList
  107525. */
  107526. SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
  107527. int i;
  107528. struct SrcList_item *pItem;
  107529. assert(pList || pParse->db->mallocFailed );
  107530. if( pList ){
  107531. for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
  107532. if( pItem->iCursor>=0 ) break;
  107533. pItem->iCursor = pParse->nTab++;
  107534. if( pItem->pSelect ){
  107535. sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
  107536. }
  107537. }
  107538. }
  107539. }
  107540. /*
  107541. ** Delete an entire SrcList including all its substructure.
  107542. */
  107543. SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
  107544. int i;
  107545. struct SrcList_item *pItem;
  107546. if( pList==0 ) return;
  107547. for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
  107548. sqlite3DbFree(db, pItem->zDatabase);
  107549. sqlite3DbFree(db, pItem->zName);
  107550. sqlite3DbFree(db, pItem->zAlias);
  107551. if( pItem->fg.isIndexedBy ) sqlite3DbFree(db, pItem->u1.zIndexedBy);
  107552. if( pItem->fg.isTabFunc ) sqlite3ExprListDelete(db, pItem->u1.pFuncArg);
  107553. sqlite3DeleteTable(db, pItem->pTab);
  107554. sqlite3SelectDelete(db, pItem->pSelect);
  107555. sqlite3ExprDelete(db, pItem->pOn);
  107556. sqlite3IdListDelete(db, pItem->pUsing);
  107557. }
  107558. sqlite3DbFreeNN(db, pList);
  107559. }
  107560. /*
  107561. ** This routine is called by the parser to add a new term to the
  107562. ** end of a growing FROM clause. The "p" parameter is the part of
  107563. ** the FROM clause that has already been constructed. "p" is NULL
  107564. ** if this is the first term of the FROM clause. pTable and pDatabase
  107565. ** are the name of the table and database named in the FROM clause term.
  107566. ** pDatabase is NULL if the database name qualifier is missing - the
  107567. ** usual case. If the term has an alias, then pAlias points to the
  107568. ** alias token. If the term is a subquery, then pSubquery is the
  107569. ** SELECT statement that the subquery encodes. The pTable and
  107570. ** pDatabase parameters are NULL for subqueries. The pOn and pUsing
  107571. ** parameters are the content of the ON and USING clauses.
  107572. **
  107573. ** Return a new SrcList which encodes is the FROM with the new
  107574. ** term added.
  107575. */
  107576. SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(
  107577. Parse *pParse, /* Parsing context */
  107578. SrcList *p, /* The left part of the FROM clause already seen */
  107579. Token *pTable, /* Name of the table to add to the FROM clause */
  107580. Token *pDatabase, /* Name of the database containing pTable */
  107581. Token *pAlias, /* The right-hand side of the AS subexpression */
  107582. Select *pSubquery, /* A subquery used in place of a table name */
  107583. Expr *pOn, /* The ON clause of a join */
  107584. IdList *pUsing /* The USING clause of a join */
  107585. ){
  107586. struct SrcList_item *pItem;
  107587. sqlite3 *db = pParse->db;
  107588. if( !p && (pOn || pUsing) ){
  107589. sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
  107590. (pOn ? "ON" : "USING")
  107591. );
  107592. goto append_from_error;
  107593. }
  107594. p = sqlite3SrcListAppend(pParse, p, pTable, pDatabase);
  107595. if( p==0 ){
  107596. goto append_from_error;
  107597. }
  107598. assert( p->nSrc>0 );
  107599. pItem = &p->a[p->nSrc-1];
  107600. assert( (pTable==0)==(pDatabase==0) );
  107601. assert( pItem->zName==0 || pDatabase!=0 );
  107602. if( IN_RENAME_OBJECT && pItem->zName ){
  107603. Token *pToken = (ALWAYS(pDatabase) && pDatabase->z) ? pDatabase : pTable;
  107604. sqlite3RenameTokenMap(pParse, pItem->zName, pToken);
  107605. }
  107606. assert( pAlias!=0 );
  107607. if( pAlias->n ){
  107608. pItem->zAlias = sqlite3NameFromToken(db, pAlias);
  107609. }
  107610. pItem->pSelect = pSubquery;
  107611. pItem->pOn = pOn;
  107612. pItem->pUsing = pUsing;
  107613. return p;
  107614. append_from_error:
  107615. assert( p==0 );
  107616. sqlite3ExprDelete(db, pOn);
  107617. sqlite3IdListDelete(db, pUsing);
  107618. sqlite3SelectDelete(db, pSubquery);
  107619. return 0;
  107620. }
  107621. /*
  107622. ** Add an INDEXED BY or NOT INDEXED clause to the most recently added
  107623. ** element of the source-list passed as the second argument.
  107624. */
  107625. SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
  107626. assert( pIndexedBy!=0 );
  107627. if( p && pIndexedBy->n>0 ){
  107628. struct SrcList_item *pItem;
  107629. assert( p->nSrc>0 );
  107630. pItem = &p->a[p->nSrc-1];
  107631. assert( pItem->fg.notIndexed==0 );
  107632. assert( pItem->fg.isIndexedBy==0 );
  107633. assert( pItem->fg.isTabFunc==0 );
  107634. if( pIndexedBy->n==1 && !pIndexedBy->z ){
  107635. /* A "NOT INDEXED" clause was supplied. See parse.y
  107636. ** construct "indexed_opt" for details. */
  107637. pItem->fg.notIndexed = 1;
  107638. }else{
  107639. pItem->u1.zIndexedBy = sqlite3NameFromToken(pParse->db, pIndexedBy);
  107640. pItem->fg.isIndexedBy = 1;
  107641. }
  107642. }
  107643. }
  107644. /*
  107645. ** Add the list of function arguments to the SrcList entry for a
  107646. ** table-valued-function.
  107647. */
  107648. SQLITE_PRIVATE void sqlite3SrcListFuncArgs(Parse *pParse, SrcList *p, ExprList *pList){
  107649. if( p ){
  107650. struct SrcList_item *pItem = &p->a[p->nSrc-1];
  107651. assert( pItem->fg.notIndexed==0 );
  107652. assert( pItem->fg.isIndexedBy==0 );
  107653. assert( pItem->fg.isTabFunc==0 );
  107654. pItem->u1.pFuncArg = pList;
  107655. pItem->fg.isTabFunc = 1;
  107656. }else{
  107657. sqlite3ExprListDelete(pParse->db, pList);
  107658. }
  107659. }
  107660. /*
  107661. ** When building up a FROM clause in the parser, the join operator
  107662. ** is initially attached to the left operand. But the code generator
  107663. ** expects the join operator to be on the right operand. This routine
  107664. ** Shifts all join operators from left to right for an entire FROM
  107665. ** clause.
  107666. **
  107667. ** Example: Suppose the join is like this:
  107668. **
  107669. ** A natural cross join B
  107670. **
  107671. ** The operator is "natural cross join". The A and B operands are stored
  107672. ** in p->a[0] and p->a[1], respectively. The parser initially stores the
  107673. ** operator with A. This routine shifts that operator over to B.
  107674. */
  107675. SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){
  107676. if( p ){
  107677. int i;
  107678. for(i=p->nSrc-1; i>0; i--){
  107679. p->a[i].fg.jointype = p->a[i-1].fg.jointype;
  107680. }
  107681. p->a[0].fg.jointype = 0;
  107682. }
  107683. }
  107684. /*
  107685. ** Generate VDBE code for a BEGIN statement.
  107686. */
  107687. SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){
  107688. sqlite3 *db;
  107689. Vdbe *v;
  107690. int i;
  107691. assert( pParse!=0 );
  107692. db = pParse->db;
  107693. assert( db!=0 );
  107694. if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
  107695. return;
  107696. }
  107697. v = sqlite3GetVdbe(pParse);
  107698. if( !v ) return;
  107699. if( type!=TK_DEFERRED ){
  107700. for(i=0; i<db->nDb; i++){
  107701. sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
  107702. sqlite3VdbeUsesBtree(v, i);
  107703. }
  107704. }
  107705. sqlite3VdbeAddOp0(v, OP_AutoCommit);
  107706. }
  107707. /*
  107708. ** Generate VDBE code for a COMMIT or ROLLBACK statement.
  107709. ** Code for ROLLBACK is generated if eType==TK_ROLLBACK. Otherwise
  107710. ** code is generated for a COMMIT.
  107711. */
  107712. SQLITE_PRIVATE void sqlite3EndTransaction(Parse *pParse, int eType){
  107713. Vdbe *v;
  107714. int isRollback;
  107715. assert( pParse!=0 );
  107716. assert( pParse->db!=0 );
  107717. assert( eType==TK_COMMIT || eType==TK_END || eType==TK_ROLLBACK );
  107718. isRollback = eType==TK_ROLLBACK;
  107719. if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION,
  107720. isRollback ? "ROLLBACK" : "COMMIT", 0, 0) ){
  107721. return;
  107722. }
  107723. v = sqlite3GetVdbe(pParse);
  107724. if( v ){
  107725. sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, isRollback);
  107726. }
  107727. }
  107728. /*
  107729. ** This function is called by the parser when it parses a command to create,
  107730. ** release or rollback an SQL savepoint.
  107731. */
  107732. SQLITE_PRIVATE void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
  107733. char *zName = sqlite3NameFromToken(pParse->db, pName);
  107734. if( zName ){
  107735. Vdbe *v = sqlite3GetVdbe(pParse);
  107736. #ifndef SQLITE_OMIT_AUTHORIZATION
  107737. static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
  107738. assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
  107739. #endif
  107740. if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
  107741. sqlite3DbFree(pParse->db, zName);
  107742. return;
  107743. }
  107744. sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
  107745. }
  107746. }
  107747. /*
  107748. ** Make sure the TEMP database is open and available for use. Return
  107749. ** the number of errors. Leave any error messages in the pParse structure.
  107750. */
  107751. SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){
  107752. sqlite3 *db = pParse->db;
  107753. if( db->aDb[1].pBt==0 && !pParse->explain ){
  107754. int rc;
  107755. Btree *pBt;
  107756. static const int flags =
  107757. SQLITE_OPEN_READWRITE |
  107758. SQLITE_OPEN_CREATE |
  107759. SQLITE_OPEN_EXCLUSIVE |
  107760. SQLITE_OPEN_DELETEONCLOSE |
  107761. SQLITE_OPEN_TEMP_DB;
  107762. rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
  107763. if( rc!=SQLITE_OK ){
  107764. sqlite3ErrorMsg(pParse, "unable to open a temporary database "
  107765. "file for storing temporary tables");
  107766. pParse->rc = rc;
  107767. return 1;
  107768. }
  107769. db->aDb[1].pBt = pBt;
  107770. assert( db->aDb[1].pSchema );
  107771. if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, 0, 0) ){
  107772. sqlite3OomFault(db);
  107773. return 1;
  107774. }
  107775. }
  107776. return 0;
  107777. }
  107778. /*
  107779. ** Record the fact that the schema cookie will need to be verified
  107780. ** for database iDb. The code to actually verify the schema cookie
  107781. ** will occur at the end of the top-level VDBE and will be generated
  107782. ** later, by sqlite3FinishCoding().
  107783. */
  107784. SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
  107785. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  107786. assert( iDb>=0 && iDb<pParse->db->nDb );
  107787. assert( pParse->db->aDb[iDb].pBt!=0 || iDb==1 );
  107788. assert( iDb<SQLITE_MAX_ATTACHED+2 );
  107789. assert( sqlite3SchemaMutexHeld(pParse->db, iDb, 0) );
  107790. if( DbMaskTest(pToplevel->cookieMask, iDb)==0 ){
  107791. DbMaskSet(pToplevel->cookieMask, iDb);
  107792. if( !OMIT_TEMPDB && iDb==1 ){
  107793. sqlite3OpenTempDatabase(pToplevel);
  107794. }
  107795. }
  107796. }
  107797. /*
  107798. ** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
  107799. ** attached database. Otherwise, invoke it for the database named zDb only.
  107800. */
  107801. SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
  107802. sqlite3 *db = pParse->db;
  107803. int i;
  107804. for(i=0; i<db->nDb; i++){
  107805. Db *pDb = &db->aDb[i];
  107806. if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zDbSName)) ){
  107807. sqlite3CodeVerifySchema(pParse, i);
  107808. }
  107809. }
  107810. }
  107811. /*
  107812. ** Generate VDBE code that prepares for doing an operation that
  107813. ** might change the database.
  107814. **
  107815. ** This routine starts a new transaction if we are not already within
  107816. ** a transaction. If we are already within a transaction, then a checkpoint
  107817. ** is set if the setStatement parameter is true. A checkpoint should
  107818. ** be set for operations that might fail (due to a constraint) part of
  107819. ** the way through and which will need to undo some writes without having to
  107820. ** rollback the whole transaction. For operations where all constraints
  107821. ** can be checked before any changes are made to the database, it is never
  107822. ** necessary to undo a write and the checkpoint should not be set.
  107823. */
  107824. SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
  107825. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  107826. sqlite3CodeVerifySchema(pParse, iDb);
  107827. DbMaskSet(pToplevel->writeMask, iDb);
  107828. pToplevel->isMultiWrite |= setStatement;
  107829. }
  107830. /*
  107831. ** Indicate that the statement currently under construction might write
  107832. ** more than one entry (example: deleting one row then inserting another,
  107833. ** inserting multiple rows in a table, or inserting a row and index entries.)
  107834. ** If an abort occurs after some of these writes have completed, then it will
  107835. ** be necessary to undo the completed writes.
  107836. */
  107837. SQLITE_PRIVATE void sqlite3MultiWrite(Parse *pParse){
  107838. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  107839. pToplevel->isMultiWrite = 1;
  107840. }
  107841. /*
  107842. ** The code generator calls this routine if is discovers that it is
  107843. ** possible to abort a statement prior to completion. In order to
  107844. ** perform this abort without corrupting the database, we need to make
  107845. ** sure that the statement is protected by a statement transaction.
  107846. **
  107847. ** Technically, we only need to set the mayAbort flag if the
  107848. ** isMultiWrite flag was previously set. There is a time dependency
  107849. ** such that the abort must occur after the multiwrite. This makes
  107850. ** some statements involving the REPLACE conflict resolution algorithm
  107851. ** go a little faster. But taking advantage of this time dependency
  107852. ** makes it more difficult to prove that the code is correct (in
  107853. ** particular, it prevents us from writing an effective
  107854. ** implementation of sqlite3AssertMayAbort()) and so we have chosen
  107855. ** to take the safe route and skip the optimization.
  107856. */
  107857. SQLITE_PRIVATE void sqlite3MayAbort(Parse *pParse){
  107858. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  107859. pToplevel->mayAbort = 1;
  107860. }
  107861. /*
  107862. ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
  107863. ** error. The onError parameter determines which (if any) of the statement
  107864. ** and/or current transaction is rolled back.
  107865. */
  107866. SQLITE_PRIVATE void sqlite3HaltConstraint(
  107867. Parse *pParse, /* Parsing context */
  107868. int errCode, /* extended error code */
  107869. int onError, /* Constraint type */
  107870. char *p4, /* Error message */
  107871. i8 p4type, /* P4_STATIC or P4_TRANSIENT */
  107872. u8 p5Errmsg /* P5_ErrMsg type */
  107873. ){
  107874. Vdbe *v = sqlite3GetVdbe(pParse);
  107875. assert( (errCode&0xff)==SQLITE_CONSTRAINT || pParse->nested );
  107876. if( onError==OE_Abort ){
  107877. sqlite3MayAbort(pParse);
  107878. }
  107879. sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type);
  107880. sqlite3VdbeChangeP5(v, p5Errmsg);
  107881. }
  107882. /*
  107883. ** Code an OP_Halt due to UNIQUE or PRIMARY KEY constraint violation.
  107884. */
  107885. SQLITE_PRIVATE void sqlite3UniqueConstraint(
  107886. Parse *pParse, /* Parsing context */
  107887. int onError, /* Constraint type */
  107888. Index *pIdx /* The index that triggers the constraint */
  107889. ){
  107890. char *zErr;
  107891. int j;
  107892. StrAccum errMsg;
  107893. Table *pTab = pIdx->pTable;
  107894. sqlite3StrAccumInit(&errMsg, pParse->db, 0, 0,
  107895. pParse->db->aLimit[SQLITE_LIMIT_LENGTH]);
  107896. if( pIdx->aColExpr ){
  107897. sqlite3_str_appendf(&errMsg, "index '%q'", pIdx->zName);
  107898. }else{
  107899. for(j=0; j<pIdx->nKeyCol; j++){
  107900. char *zCol;
  107901. assert( pIdx->aiColumn[j]>=0 );
  107902. zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
  107903. if( j ) sqlite3_str_append(&errMsg, ", ", 2);
  107904. sqlite3_str_appendall(&errMsg, pTab->zName);
  107905. sqlite3_str_append(&errMsg, ".", 1);
  107906. sqlite3_str_appendall(&errMsg, zCol);
  107907. }
  107908. }
  107909. zErr = sqlite3StrAccumFinish(&errMsg);
  107910. sqlite3HaltConstraint(pParse,
  107911. IsPrimaryKeyIndex(pIdx) ? SQLITE_CONSTRAINT_PRIMARYKEY
  107912. : SQLITE_CONSTRAINT_UNIQUE,
  107913. onError, zErr, P4_DYNAMIC, P5_ConstraintUnique);
  107914. }
  107915. /*
  107916. ** Code an OP_Halt due to non-unique rowid.
  107917. */
  107918. SQLITE_PRIVATE void sqlite3RowidConstraint(
  107919. Parse *pParse, /* Parsing context */
  107920. int onError, /* Conflict resolution algorithm */
  107921. Table *pTab /* The table with the non-unique rowid */
  107922. ){
  107923. char *zMsg;
  107924. int rc;
  107925. if( pTab->iPKey>=0 ){
  107926. zMsg = sqlite3MPrintf(pParse->db, "%s.%s", pTab->zName,
  107927. pTab->aCol[pTab->iPKey].zName);
  107928. rc = SQLITE_CONSTRAINT_PRIMARYKEY;
  107929. }else{
  107930. zMsg = sqlite3MPrintf(pParse->db, "%s.rowid", pTab->zName);
  107931. rc = SQLITE_CONSTRAINT_ROWID;
  107932. }
  107933. sqlite3HaltConstraint(pParse, rc, onError, zMsg, P4_DYNAMIC,
  107934. P5_ConstraintUnique);
  107935. }
  107936. /*
  107937. ** Check to see if pIndex uses the collating sequence pColl. Return
  107938. ** true if it does and false if it does not.
  107939. */
  107940. #ifndef SQLITE_OMIT_REINDEX
  107941. static int collationMatch(const char *zColl, Index *pIndex){
  107942. int i;
  107943. assert( zColl!=0 );
  107944. for(i=0; i<pIndex->nColumn; i++){
  107945. const char *z = pIndex->azColl[i];
  107946. assert( z!=0 || pIndex->aiColumn[i]<0 );
  107947. if( pIndex->aiColumn[i]>=0 && 0==sqlite3StrICmp(z, zColl) ){
  107948. return 1;
  107949. }
  107950. }
  107951. return 0;
  107952. }
  107953. #endif
  107954. /*
  107955. ** Recompute all indices of pTab that use the collating sequence pColl.
  107956. ** If pColl==0 then recompute all indices of pTab.
  107957. */
  107958. #ifndef SQLITE_OMIT_REINDEX
  107959. static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
  107960. if( !IsVirtual(pTab) ){
  107961. Index *pIndex; /* An index associated with pTab */
  107962. for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
  107963. if( zColl==0 || collationMatch(zColl, pIndex) ){
  107964. int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  107965. sqlite3BeginWriteOperation(pParse, 0, iDb);
  107966. sqlite3RefillIndex(pParse, pIndex, -1);
  107967. }
  107968. }
  107969. }
  107970. }
  107971. #endif
  107972. /*
  107973. ** Recompute all indices of all tables in all databases where the
  107974. ** indices use the collating sequence pColl. If pColl==0 then recompute
  107975. ** all indices everywhere.
  107976. */
  107977. #ifndef SQLITE_OMIT_REINDEX
  107978. static void reindexDatabases(Parse *pParse, char const *zColl){
  107979. Db *pDb; /* A single database */
  107980. int iDb; /* The database index number */
  107981. sqlite3 *db = pParse->db; /* The database connection */
  107982. HashElem *k; /* For looping over tables in pDb */
  107983. Table *pTab; /* A table in the database */
  107984. assert( sqlite3BtreeHoldsAllMutexes(db) ); /* Needed for schema access */
  107985. for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
  107986. assert( pDb!=0 );
  107987. for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){
  107988. pTab = (Table*)sqliteHashData(k);
  107989. reindexTable(pParse, pTab, zColl);
  107990. }
  107991. }
  107992. }
  107993. #endif
  107994. /*
  107995. ** Generate code for the REINDEX command.
  107996. **
  107997. ** REINDEX -- 1
  107998. ** REINDEX <collation> -- 2
  107999. ** REINDEX ?<database>.?<tablename> -- 3
  108000. ** REINDEX ?<database>.?<indexname> -- 4
  108001. **
  108002. ** Form 1 causes all indices in all attached databases to be rebuilt.
  108003. ** Form 2 rebuilds all indices in all databases that use the named
  108004. ** collating function. Forms 3 and 4 rebuild the named index or all
  108005. ** indices associated with the named table.
  108006. */
  108007. #ifndef SQLITE_OMIT_REINDEX
  108008. SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
  108009. CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */
  108010. char *z; /* Name of a table or index */
  108011. const char *zDb; /* Name of the database */
  108012. Table *pTab; /* A table in the database */
  108013. Index *pIndex; /* An index associated with pTab */
  108014. int iDb; /* The database index number */
  108015. sqlite3 *db = pParse->db; /* The database connection */
  108016. Token *pObjName; /* Name of the table or index to be reindexed */
  108017. /* Read the database schema. If an error occurs, leave an error message
  108018. ** and code in pParse and return NULL. */
  108019. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  108020. return;
  108021. }
  108022. if( pName1==0 ){
  108023. reindexDatabases(pParse, 0);
  108024. return;
  108025. }else if( NEVER(pName2==0) || pName2->z==0 ){
  108026. char *zColl;
  108027. assert( pName1->z );
  108028. zColl = sqlite3NameFromToken(pParse->db, pName1);
  108029. if( !zColl ) return;
  108030. pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
  108031. if( pColl ){
  108032. reindexDatabases(pParse, zColl);
  108033. sqlite3DbFree(db, zColl);
  108034. return;
  108035. }
  108036. sqlite3DbFree(db, zColl);
  108037. }
  108038. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
  108039. if( iDb<0 ) return;
  108040. z = sqlite3NameFromToken(db, pObjName);
  108041. if( z==0 ) return;
  108042. zDb = db->aDb[iDb].zDbSName;
  108043. pTab = sqlite3FindTable(db, z, zDb);
  108044. if( pTab ){
  108045. reindexTable(pParse, pTab, 0);
  108046. sqlite3DbFree(db, z);
  108047. return;
  108048. }
  108049. pIndex = sqlite3FindIndex(db, z, zDb);
  108050. sqlite3DbFree(db, z);
  108051. if( pIndex ){
  108052. sqlite3BeginWriteOperation(pParse, 0, iDb);
  108053. sqlite3RefillIndex(pParse, pIndex, -1);
  108054. return;
  108055. }
  108056. sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
  108057. }
  108058. #endif
  108059. /*
  108060. ** Return a KeyInfo structure that is appropriate for the given Index.
  108061. **
  108062. ** The caller should invoke sqlite3KeyInfoUnref() on the returned object
  108063. ** when it has finished using it.
  108064. */
  108065. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoOfIndex(Parse *pParse, Index *pIdx){
  108066. int i;
  108067. int nCol = pIdx->nColumn;
  108068. int nKey = pIdx->nKeyCol;
  108069. KeyInfo *pKey;
  108070. if( pParse->nErr ) return 0;
  108071. if( pIdx->uniqNotNull ){
  108072. pKey = sqlite3KeyInfoAlloc(pParse->db, nKey, nCol-nKey);
  108073. }else{
  108074. pKey = sqlite3KeyInfoAlloc(pParse->db, nCol, 0);
  108075. }
  108076. if( pKey ){
  108077. assert( sqlite3KeyInfoIsWriteable(pKey) );
  108078. for(i=0; i<nCol; i++){
  108079. const char *zColl = pIdx->azColl[i];
  108080. pKey->aColl[i] = zColl==sqlite3StrBINARY ? 0 :
  108081. sqlite3LocateCollSeq(pParse, zColl);
  108082. pKey->aSortFlags[i] = pIdx->aSortOrder[i];
  108083. assert( 0==(pKey->aSortFlags[i] & KEYINFO_ORDER_BIGNULL) );
  108084. }
  108085. if( pParse->nErr ){
  108086. assert( pParse->rc==SQLITE_ERROR_MISSING_COLLSEQ );
  108087. if( pIdx->bNoQuery==0 ){
  108088. /* Deactivate the index because it contains an unknown collating
  108089. ** sequence. The only way to reactive the index is to reload the
  108090. ** schema. Adding the missing collating sequence later does not
  108091. ** reactive the index. The application had the chance to register
  108092. ** the missing index using the collation-needed callback. For
  108093. ** simplicity, SQLite will not give the application a second chance.
  108094. */
  108095. pIdx->bNoQuery = 1;
  108096. pParse->rc = SQLITE_ERROR_RETRY;
  108097. }
  108098. sqlite3KeyInfoUnref(pKey);
  108099. pKey = 0;
  108100. }
  108101. }
  108102. return pKey;
  108103. }
  108104. #ifndef SQLITE_OMIT_CTE
  108105. /*
  108106. ** This routine is invoked once per CTE by the parser while parsing a
  108107. ** WITH clause.
  108108. */
  108109. SQLITE_PRIVATE With *sqlite3WithAdd(
  108110. Parse *pParse, /* Parsing context */
  108111. With *pWith, /* Existing WITH clause, or NULL */
  108112. Token *pName, /* Name of the common-table */
  108113. ExprList *pArglist, /* Optional column name list for the table */
  108114. Select *pQuery /* Query used to initialize the table */
  108115. ){
  108116. sqlite3 *db = pParse->db;
  108117. With *pNew;
  108118. char *zName;
  108119. /* Check that the CTE name is unique within this WITH clause. If
  108120. ** not, store an error in the Parse structure. */
  108121. zName = sqlite3NameFromToken(pParse->db, pName);
  108122. if( zName && pWith ){
  108123. int i;
  108124. for(i=0; i<pWith->nCte; i++){
  108125. if( sqlite3StrICmp(zName, pWith->a[i].zName)==0 ){
  108126. sqlite3ErrorMsg(pParse, "duplicate WITH table name: %s", zName);
  108127. }
  108128. }
  108129. }
  108130. if( pWith ){
  108131. sqlite3_int64 nByte = sizeof(*pWith) + (sizeof(pWith->a[1]) * pWith->nCte);
  108132. pNew = sqlite3DbRealloc(db, pWith, nByte);
  108133. }else{
  108134. pNew = sqlite3DbMallocZero(db, sizeof(*pWith));
  108135. }
  108136. assert( (pNew!=0 && zName!=0) || db->mallocFailed );
  108137. if( db->mallocFailed ){
  108138. sqlite3ExprListDelete(db, pArglist);
  108139. sqlite3SelectDelete(db, pQuery);
  108140. sqlite3DbFree(db, zName);
  108141. pNew = pWith;
  108142. }else{
  108143. pNew->a[pNew->nCte].pSelect = pQuery;
  108144. pNew->a[pNew->nCte].pCols = pArglist;
  108145. pNew->a[pNew->nCte].zName = zName;
  108146. pNew->a[pNew->nCte].zCteErr = 0;
  108147. pNew->nCte++;
  108148. }
  108149. return pNew;
  108150. }
  108151. /*
  108152. ** Free the contents of the With object passed as the second argument.
  108153. */
  108154. SQLITE_PRIVATE void sqlite3WithDelete(sqlite3 *db, With *pWith){
  108155. if( pWith ){
  108156. int i;
  108157. for(i=0; i<pWith->nCte; i++){
  108158. struct Cte *pCte = &pWith->a[i];
  108159. sqlite3ExprListDelete(db, pCte->pCols);
  108160. sqlite3SelectDelete(db, pCte->pSelect);
  108161. sqlite3DbFree(db, pCte->zName);
  108162. }
  108163. sqlite3DbFree(db, pWith);
  108164. }
  108165. }
  108166. #endif /* !defined(SQLITE_OMIT_CTE) */
  108167. /************** End of build.c ***********************************************/
  108168. /************** Begin file callback.c ****************************************/
  108169. /*
  108170. ** 2005 May 23
  108171. **
  108172. ** The author disclaims copyright to this source code. In place of
  108173. ** a legal notice, here is a blessing:
  108174. **
  108175. ** May you do good and not evil.
  108176. ** May you find forgiveness for yourself and forgive others.
  108177. ** May you share freely, never taking more than you give.
  108178. **
  108179. *************************************************************************
  108180. **
  108181. ** This file contains functions used to access the internal hash tables
  108182. ** of user defined functions and collation sequences.
  108183. */
  108184. /* #include "sqliteInt.h" */
  108185. /*
  108186. ** Invoke the 'collation needed' callback to request a collation sequence
  108187. ** in the encoding enc of name zName, length nName.
  108188. */
  108189. static void callCollNeeded(sqlite3 *db, int enc, const char *zName){
  108190. assert( !db->xCollNeeded || !db->xCollNeeded16 );
  108191. if( db->xCollNeeded ){
  108192. char *zExternal = sqlite3DbStrDup(db, zName);
  108193. if( !zExternal ) return;
  108194. db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal);
  108195. sqlite3DbFree(db, zExternal);
  108196. }
  108197. #ifndef SQLITE_OMIT_UTF16
  108198. if( db->xCollNeeded16 ){
  108199. char const *zExternal;
  108200. sqlite3_value *pTmp = sqlite3ValueNew(db);
  108201. sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC);
  108202. zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
  108203. if( zExternal ){
  108204. db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
  108205. }
  108206. sqlite3ValueFree(pTmp);
  108207. }
  108208. #endif
  108209. }
  108210. /*
  108211. ** This routine is called if the collation factory fails to deliver a
  108212. ** collation function in the best encoding but there may be other versions
  108213. ** of this collation function (for other text encodings) available. Use one
  108214. ** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
  108215. ** possible.
  108216. */
  108217. static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
  108218. CollSeq *pColl2;
  108219. char *z = pColl->zName;
  108220. int i;
  108221. static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
  108222. for(i=0; i<3; i++){
  108223. pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, 0);
  108224. if( pColl2->xCmp!=0 ){
  108225. memcpy(pColl, pColl2, sizeof(CollSeq));
  108226. pColl->xDel = 0; /* Do not copy the destructor */
  108227. return SQLITE_OK;
  108228. }
  108229. }
  108230. return SQLITE_ERROR;
  108231. }
  108232. /*
  108233. ** This routine is called on a collation sequence before it is used to
  108234. ** check that it is defined. An undefined collation sequence exists when
  108235. ** a database is loaded that contains references to collation sequences
  108236. ** that have not been defined by sqlite3_create_collation() etc.
  108237. **
  108238. ** If required, this routine calls the 'collation needed' callback to
  108239. ** request a definition of the collating sequence. If this doesn't work,
  108240. ** an equivalent collating sequence that uses a text encoding different
  108241. ** from the main database is substituted, if one is available.
  108242. */
  108243. SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
  108244. if( pColl && pColl->xCmp==0 ){
  108245. const char *zName = pColl->zName;
  108246. sqlite3 *db = pParse->db;
  108247. CollSeq *p = sqlite3GetCollSeq(pParse, ENC(db), pColl, zName);
  108248. if( !p ){
  108249. return SQLITE_ERROR;
  108250. }
  108251. assert( p==pColl );
  108252. }
  108253. return SQLITE_OK;
  108254. }
  108255. /*
  108256. ** Locate and return an entry from the db.aCollSeq hash table. If the entry
  108257. ** specified by zName and nName is not found and parameter 'create' is
  108258. ** true, then create a new entry. Otherwise return NULL.
  108259. **
  108260. ** Each pointer stored in the sqlite3.aCollSeq hash table contains an
  108261. ** array of three CollSeq structures. The first is the collation sequence
  108262. ** preferred for UTF-8, the second UTF-16le, and the third UTF-16be.
  108263. **
  108264. ** Stored immediately after the three collation sequences is a copy of
  108265. ** the collation sequence name. A pointer to this string is stored in
  108266. ** each collation sequence structure.
  108267. */
  108268. static CollSeq *findCollSeqEntry(
  108269. sqlite3 *db, /* Database connection */
  108270. const char *zName, /* Name of the collating sequence */
  108271. int create /* Create a new entry if true */
  108272. ){
  108273. CollSeq *pColl;
  108274. pColl = sqlite3HashFind(&db->aCollSeq, zName);
  108275. if( 0==pColl && create ){
  108276. int nName = sqlite3Strlen30(zName) + 1;
  108277. pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName);
  108278. if( pColl ){
  108279. CollSeq *pDel = 0;
  108280. pColl[0].zName = (char*)&pColl[3];
  108281. pColl[0].enc = SQLITE_UTF8;
  108282. pColl[1].zName = (char*)&pColl[3];
  108283. pColl[1].enc = SQLITE_UTF16LE;
  108284. pColl[2].zName = (char*)&pColl[3];
  108285. pColl[2].enc = SQLITE_UTF16BE;
  108286. memcpy(pColl[0].zName, zName, nName);
  108287. pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, pColl);
  108288. /* If a malloc() failure occurred in sqlite3HashInsert(), it will
  108289. ** return the pColl pointer to be deleted (because it wasn't added
  108290. ** to the hash table).
  108291. */
  108292. assert( pDel==0 || pDel==pColl );
  108293. if( pDel!=0 ){
  108294. sqlite3OomFault(db);
  108295. sqlite3DbFree(db, pDel);
  108296. pColl = 0;
  108297. }
  108298. }
  108299. }
  108300. return pColl;
  108301. }
  108302. /*
  108303. ** Parameter zName points to a UTF-8 encoded string nName bytes long.
  108304. ** Return the CollSeq* pointer for the collation sequence named zName
  108305. ** for the encoding 'enc' from the database 'db'.
  108306. **
  108307. ** If the entry specified is not found and 'create' is true, then create a
  108308. ** new entry. Otherwise return NULL.
  108309. **
  108310. ** A separate function sqlite3LocateCollSeq() is a wrapper around
  108311. ** this routine. sqlite3LocateCollSeq() invokes the collation factory
  108312. ** if necessary and generates an error message if the collating sequence
  108313. ** cannot be found.
  108314. **
  108315. ** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq()
  108316. */
  108317. SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(
  108318. sqlite3 *db, /* Database connection to search */
  108319. u8 enc, /* Desired text encoding */
  108320. const char *zName, /* Name of the collating sequence. Might be NULL */
  108321. int create /* True to create CollSeq if doesn't already exist */
  108322. ){
  108323. CollSeq *pColl;
  108324. assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
  108325. assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
  108326. if( zName ){
  108327. pColl = findCollSeqEntry(db, zName, create);
  108328. if( pColl ) pColl += enc-1;
  108329. }else{
  108330. pColl = db->pDfltColl;
  108331. }
  108332. return pColl;
  108333. }
  108334. /*
  108335. ** Change the text encoding for a database connection. This means that
  108336. ** the pDfltColl must change as well.
  108337. */
  108338. SQLITE_PRIVATE void sqlite3SetTextEncoding(sqlite3 *db, u8 enc){
  108339. assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
  108340. db->enc = enc;
  108341. /* EVIDENCE-OF: R-08308-17224 The default collating function for all
  108342. ** strings is BINARY.
  108343. */
  108344. db->pDfltColl = sqlite3FindCollSeq(db, enc, sqlite3StrBINARY, 0);
  108345. }
  108346. /*
  108347. ** This function is responsible for invoking the collation factory callback
  108348. ** or substituting a collation sequence of a different encoding when the
  108349. ** requested collation sequence is not available in the desired encoding.
  108350. **
  108351. ** If it is not NULL, then pColl must point to the database native encoding
  108352. ** collation sequence with name zName, length nName.
  108353. **
  108354. ** The return value is either the collation sequence to be used in database
  108355. ** db for collation type name zName, length nName, or NULL, if no collation
  108356. ** sequence can be found. If no collation is found, leave an error message.
  108357. **
  108358. ** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq()
  108359. */
  108360. SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(
  108361. Parse *pParse, /* Parsing context */
  108362. u8 enc, /* The desired encoding for the collating sequence */
  108363. CollSeq *pColl, /* Collating sequence with native encoding, or NULL */
  108364. const char *zName /* Collating sequence name */
  108365. ){
  108366. CollSeq *p;
  108367. sqlite3 *db = pParse->db;
  108368. p = pColl;
  108369. if( !p ){
  108370. p = sqlite3FindCollSeq(db, enc, zName, 0);
  108371. }
  108372. if( !p || !p->xCmp ){
  108373. /* No collation sequence of this type for this encoding is registered.
  108374. ** Call the collation factory to see if it can supply us with one.
  108375. */
  108376. callCollNeeded(db, enc, zName);
  108377. p = sqlite3FindCollSeq(db, enc, zName, 0);
  108378. }
  108379. if( p && !p->xCmp && synthCollSeq(db, p) ){
  108380. p = 0;
  108381. }
  108382. assert( !p || p->xCmp );
  108383. if( p==0 ){
  108384. sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
  108385. pParse->rc = SQLITE_ERROR_MISSING_COLLSEQ;
  108386. }
  108387. return p;
  108388. }
  108389. /*
  108390. ** This function returns the collation sequence for database native text
  108391. ** encoding identified by the string zName.
  108392. **
  108393. ** If the requested collation sequence is not available, or not available
  108394. ** in the database native encoding, the collation factory is invoked to
  108395. ** request it. If the collation factory does not supply such a sequence,
  108396. ** and the sequence is available in another text encoding, then that is
  108397. ** returned instead.
  108398. **
  108399. ** If no versions of the requested collations sequence are available, or
  108400. ** another error occurs, NULL is returned and an error message written into
  108401. ** pParse.
  108402. **
  108403. ** This routine is a wrapper around sqlite3FindCollSeq(). This routine
  108404. ** invokes the collation factory if the named collation cannot be found
  108405. ** and generates an error message.
  108406. **
  108407. ** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
  108408. */
  108409. SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
  108410. sqlite3 *db = pParse->db;
  108411. u8 enc = ENC(db);
  108412. u8 initbusy = db->init.busy;
  108413. CollSeq *pColl;
  108414. pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
  108415. if( !initbusy && (!pColl || !pColl->xCmp) ){
  108416. pColl = sqlite3GetCollSeq(pParse, enc, pColl, zName);
  108417. }
  108418. return pColl;
  108419. }
  108420. /* During the search for the best function definition, this procedure
  108421. ** is called to test how well the function passed as the first argument
  108422. ** matches the request for a function with nArg arguments in a system
  108423. ** that uses encoding enc. The value returned indicates how well the
  108424. ** request is matched. A higher value indicates a better match.
  108425. **
  108426. ** If nArg is -1 that means to only return a match (non-zero) if p->nArg
  108427. ** is also -1. In other words, we are searching for a function that
  108428. ** takes a variable number of arguments.
  108429. **
  108430. ** If nArg is -2 that means that we are searching for any function
  108431. ** regardless of the number of arguments it uses, so return a positive
  108432. ** match score for any
  108433. **
  108434. ** The returned value is always between 0 and 6, as follows:
  108435. **
  108436. ** 0: Not a match.
  108437. ** 1: UTF8/16 conversion required and function takes any number of arguments.
  108438. ** 2: UTF16 byte order change required and function takes any number of args.
  108439. ** 3: encoding matches and function takes any number of arguments
  108440. ** 4: UTF8/16 conversion required - argument count matches exactly
  108441. ** 5: UTF16 byte order conversion required - argument count matches exactly
  108442. ** 6: Perfect match: encoding and argument count match exactly.
  108443. **
  108444. ** If nArg==(-2) then any function with a non-null xSFunc is
  108445. ** a perfect match and any function with xSFunc NULL is
  108446. ** a non-match.
  108447. */
  108448. #define FUNC_PERFECT_MATCH 6 /* The score for a perfect match */
  108449. static int matchQuality(
  108450. FuncDef *p, /* The function we are evaluating for match quality */
  108451. int nArg, /* Desired number of arguments. (-1)==any */
  108452. u8 enc /* Desired text encoding */
  108453. ){
  108454. int match;
  108455. assert( p->nArg>=-1 );
  108456. /* Wrong number of arguments means "no match" */
  108457. if( p->nArg!=nArg ){
  108458. if( nArg==(-2) ) return (p->xSFunc==0) ? 0 : FUNC_PERFECT_MATCH;
  108459. if( p->nArg>=0 ) return 0;
  108460. }
  108461. /* Give a better score to a function with a specific number of arguments
  108462. ** than to function that accepts any number of arguments. */
  108463. if( p->nArg==nArg ){
  108464. match = 4;
  108465. }else{
  108466. match = 1;
  108467. }
  108468. /* Bonus points if the text encoding matches */
  108469. if( enc==(p->funcFlags & SQLITE_FUNC_ENCMASK) ){
  108470. match += 2; /* Exact encoding match */
  108471. }else if( (enc & p->funcFlags & 2)!=0 ){
  108472. match += 1; /* Both are UTF16, but with different byte orders */
  108473. }
  108474. return match;
  108475. }
  108476. /*
  108477. ** Search a FuncDefHash for a function with the given name. Return
  108478. ** a pointer to the matching FuncDef if found, or 0 if there is no match.
  108479. */
  108480. SQLITE_PRIVATE FuncDef *sqlite3FunctionSearch(
  108481. int h, /* Hash of the name */
  108482. const char *zFunc /* Name of function */
  108483. ){
  108484. FuncDef *p;
  108485. for(p=sqlite3BuiltinFunctions.a[h]; p; p=p->u.pHash){
  108486. if( sqlite3StrICmp(p->zName, zFunc)==0 ){
  108487. return p;
  108488. }
  108489. }
  108490. return 0;
  108491. }
  108492. /*
  108493. ** Insert a new FuncDef into a FuncDefHash hash table.
  108494. */
  108495. SQLITE_PRIVATE void sqlite3InsertBuiltinFuncs(
  108496. FuncDef *aDef, /* List of global functions to be inserted */
  108497. int nDef /* Length of the apDef[] list */
  108498. ){
  108499. int i;
  108500. for(i=0; i<nDef; i++){
  108501. FuncDef *pOther;
  108502. const char *zName = aDef[i].zName;
  108503. int nName = sqlite3Strlen30(zName);
  108504. int h = SQLITE_FUNC_HASH(zName[0], nName);
  108505. assert( zName[0]>='a' && zName[0]<='z' );
  108506. pOther = sqlite3FunctionSearch(h, zName);
  108507. if( pOther ){
  108508. assert( pOther!=&aDef[i] && pOther->pNext!=&aDef[i] );
  108509. aDef[i].pNext = pOther->pNext;
  108510. pOther->pNext = &aDef[i];
  108511. }else{
  108512. aDef[i].pNext = 0;
  108513. aDef[i].u.pHash = sqlite3BuiltinFunctions.a[h];
  108514. sqlite3BuiltinFunctions.a[h] = &aDef[i];
  108515. }
  108516. }
  108517. }
  108518. /*
  108519. ** Locate a user function given a name, a number of arguments and a flag
  108520. ** indicating whether the function prefers UTF-16 over UTF-8. Return a
  108521. ** pointer to the FuncDef structure that defines that function, or return
  108522. ** NULL if the function does not exist.
  108523. **
  108524. ** If the createFlag argument is true, then a new (blank) FuncDef
  108525. ** structure is created and liked into the "db" structure if a
  108526. ** no matching function previously existed.
  108527. **
  108528. ** If nArg is -2, then the first valid function found is returned. A
  108529. ** function is valid if xSFunc is non-zero. The nArg==(-2)
  108530. ** case is used to see if zName is a valid function name for some number
  108531. ** of arguments. If nArg is -2, then createFlag must be 0.
  108532. **
  108533. ** If createFlag is false, then a function with the required name and
  108534. ** number of arguments may be returned even if the eTextRep flag does not
  108535. ** match that requested.
  108536. */
  108537. SQLITE_PRIVATE FuncDef *sqlite3FindFunction(
  108538. sqlite3 *db, /* An open database */
  108539. const char *zName, /* Name of the function. zero-terminated */
  108540. int nArg, /* Number of arguments. -1 means any number */
  108541. u8 enc, /* Preferred text encoding */
  108542. u8 createFlag /* Create new entry if true and does not otherwise exist */
  108543. ){
  108544. FuncDef *p; /* Iterator variable */
  108545. FuncDef *pBest = 0; /* Best match found so far */
  108546. int bestScore = 0; /* Score of best match */
  108547. int h; /* Hash value */
  108548. int nName; /* Length of the name */
  108549. assert( nArg>=(-2) );
  108550. assert( nArg>=(-1) || createFlag==0 );
  108551. nName = sqlite3Strlen30(zName);
  108552. /* First search for a match amongst the application-defined functions.
  108553. */
  108554. p = (FuncDef*)sqlite3HashFind(&db->aFunc, zName);
  108555. while( p ){
  108556. int score = matchQuality(p, nArg, enc);
  108557. if( score>bestScore ){
  108558. pBest = p;
  108559. bestScore = score;
  108560. }
  108561. p = p->pNext;
  108562. }
  108563. /* If no match is found, search the built-in functions.
  108564. **
  108565. ** If the DBFLAG_PreferBuiltin flag is set, then search the built-in
  108566. ** functions even if a prior app-defined function was found. And give
  108567. ** priority to built-in functions.
  108568. **
  108569. ** Except, if createFlag is true, that means that we are trying to
  108570. ** install a new function. Whatever FuncDef structure is returned it will
  108571. ** have fields overwritten with new information appropriate for the
  108572. ** new function. But the FuncDefs for built-in functions are read-only.
  108573. ** So we must not search for built-ins when creating a new function.
  108574. */
  108575. if( !createFlag && (pBest==0 || (db->mDbFlags & DBFLAG_PreferBuiltin)!=0) ){
  108576. bestScore = 0;
  108577. h = SQLITE_FUNC_HASH(sqlite3UpperToLower[(u8)zName[0]], nName);
  108578. p = sqlite3FunctionSearch(h, zName);
  108579. while( p ){
  108580. int score = matchQuality(p, nArg, enc);
  108581. if( score>bestScore ){
  108582. pBest = p;
  108583. bestScore = score;
  108584. }
  108585. p = p->pNext;
  108586. }
  108587. }
  108588. /* If the createFlag parameter is true and the search did not reveal an
  108589. ** exact match for the name, number of arguments and encoding, then add a
  108590. ** new entry to the hash table and return it.
  108591. */
  108592. if( createFlag && bestScore<FUNC_PERFECT_MATCH &&
  108593. (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
  108594. FuncDef *pOther;
  108595. u8 *z;
  108596. pBest->zName = (const char*)&pBest[1];
  108597. pBest->nArg = (u16)nArg;
  108598. pBest->funcFlags = enc;
  108599. memcpy((char*)&pBest[1], zName, nName+1);
  108600. for(z=(u8*)pBest->zName; *z; z++) *z = sqlite3UpperToLower[*z];
  108601. pOther = (FuncDef*)sqlite3HashInsert(&db->aFunc, pBest->zName, pBest);
  108602. if( pOther==pBest ){
  108603. sqlite3DbFree(db, pBest);
  108604. sqlite3OomFault(db);
  108605. return 0;
  108606. }else{
  108607. pBest->pNext = pOther;
  108608. }
  108609. }
  108610. if( pBest && (pBest->xSFunc || createFlag) ){
  108611. return pBest;
  108612. }
  108613. return 0;
  108614. }
  108615. /*
  108616. ** Free all resources held by the schema structure. The void* argument points
  108617. ** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the
  108618. ** pointer itself, it just cleans up subsidiary resources (i.e. the contents
  108619. ** of the schema hash tables).
  108620. **
  108621. ** The Schema.cache_size variable is not cleared.
  108622. */
  108623. SQLITE_PRIVATE void sqlite3SchemaClear(void *p){
  108624. Hash temp1;
  108625. Hash temp2;
  108626. HashElem *pElem;
  108627. Schema *pSchema = (Schema *)p;
  108628. temp1 = pSchema->tblHash;
  108629. temp2 = pSchema->trigHash;
  108630. sqlite3HashInit(&pSchema->trigHash);
  108631. sqlite3HashClear(&pSchema->idxHash);
  108632. for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
  108633. sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
  108634. }
  108635. sqlite3HashClear(&temp2);
  108636. sqlite3HashInit(&pSchema->tblHash);
  108637. for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
  108638. Table *pTab = sqliteHashData(pElem);
  108639. sqlite3DeleteTable(0, pTab);
  108640. }
  108641. sqlite3HashClear(&temp1);
  108642. sqlite3HashClear(&pSchema->fkeyHash);
  108643. pSchema->pSeqTab = 0;
  108644. if( pSchema->schemaFlags & DB_SchemaLoaded ){
  108645. pSchema->iGeneration++;
  108646. }
  108647. pSchema->schemaFlags &= ~(DB_SchemaLoaded|DB_ResetWanted);
  108648. }
  108649. /*
  108650. ** Find and return the schema associated with a BTree. Create
  108651. ** a new one if necessary.
  108652. */
  108653. SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
  108654. Schema * p;
  108655. if( pBt ){
  108656. p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaClear);
  108657. }else{
  108658. p = (Schema *)sqlite3DbMallocZero(0, sizeof(Schema));
  108659. }
  108660. if( !p ){
  108661. sqlite3OomFault(db);
  108662. }else if ( 0==p->file_format ){
  108663. sqlite3HashInit(&p->tblHash);
  108664. sqlite3HashInit(&p->idxHash);
  108665. sqlite3HashInit(&p->trigHash);
  108666. sqlite3HashInit(&p->fkeyHash);
  108667. p->enc = SQLITE_UTF8;
  108668. }
  108669. return p;
  108670. }
  108671. /************** End of callback.c ********************************************/
  108672. /************** Begin file delete.c ******************************************/
  108673. /*
  108674. ** 2001 September 15
  108675. **
  108676. ** The author disclaims copyright to this source code. In place of
  108677. ** a legal notice, here is a blessing:
  108678. **
  108679. ** May you do good and not evil.
  108680. ** May you find forgiveness for yourself and forgive others.
  108681. ** May you share freely, never taking more than you give.
  108682. **
  108683. *************************************************************************
  108684. ** This file contains C code routines that are called by the parser
  108685. ** in order to generate code for DELETE FROM statements.
  108686. */
  108687. /* #include "sqliteInt.h" */
  108688. /*
  108689. ** While a SrcList can in general represent multiple tables and subqueries
  108690. ** (as in the FROM clause of a SELECT statement) in this case it contains
  108691. ** the name of a single table, as one might find in an INSERT, DELETE,
  108692. ** or UPDATE statement. Look up that table in the symbol table and
  108693. ** return a pointer. Set an error message and return NULL if the table
  108694. ** name is not found or if any other error occurs.
  108695. **
  108696. ** The following fields are initialized appropriate in pSrc:
  108697. **
  108698. ** pSrc->a[0].pTab Pointer to the Table object
  108699. ** pSrc->a[0].pIndex Pointer to the INDEXED BY index, if there is one
  108700. **
  108701. */
  108702. SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
  108703. struct SrcList_item *pItem = pSrc->a;
  108704. Table *pTab;
  108705. assert( pItem && pSrc->nSrc==1 );
  108706. pTab = sqlite3LocateTableItem(pParse, 0, pItem);
  108707. sqlite3DeleteTable(pParse->db, pItem->pTab);
  108708. pItem->pTab = pTab;
  108709. if( pTab ){
  108710. pTab->nTabRef++;
  108711. }
  108712. if( sqlite3IndexedByLookup(pParse, pItem) ){
  108713. pTab = 0;
  108714. }
  108715. return pTab;
  108716. }
  108717. /* Return true if table pTab is read-only.
  108718. **
  108719. ** A table is read-only if any of the following are true:
  108720. **
  108721. ** 1) It is a virtual table and no implementation of the xUpdate method
  108722. ** has been provided
  108723. **
  108724. ** 2) It is a system table (i.e. sqlite_master), this call is not
  108725. ** part of a nested parse and writable_schema pragma has not
  108726. ** been specified
  108727. **
  108728. ** 3) The table is a shadow table, the database connection is in
  108729. ** defensive mode, and the current sqlite3_prepare()
  108730. ** is for a top-level SQL statement.
  108731. */
  108732. static int tabIsReadOnly(Parse *pParse, Table *pTab){
  108733. sqlite3 *db;
  108734. if( IsVirtual(pTab) ){
  108735. return sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0;
  108736. }
  108737. if( (pTab->tabFlags & (TF_Readonly|TF_Shadow))==0 ) return 0;
  108738. db = pParse->db;
  108739. if( (pTab->tabFlags & TF_Readonly)!=0 ){
  108740. return sqlite3WritableSchema(db)==0 && pParse->nested==0;
  108741. }
  108742. assert( pTab->tabFlags & TF_Shadow );
  108743. return sqlite3ReadOnlyShadowTables(db);
  108744. }
  108745. /*
  108746. ** Check to make sure the given table is writable. If it is not
  108747. ** writable, generate an error message and return 1. If it is
  108748. ** writable return 0;
  108749. */
  108750. SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
  108751. if( tabIsReadOnly(pParse, pTab) ){
  108752. sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
  108753. return 1;
  108754. }
  108755. #ifndef SQLITE_OMIT_VIEW
  108756. if( !viewOk && pTab->pSelect ){
  108757. sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
  108758. return 1;
  108759. }
  108760. #endif
  108761. return 0;
  108762. }
  108763. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  108764. /*
  108765. ** Evaluate a view and store its result in an ephemeral table. The
  108766. ** pWhere argument is an optional WHERE clause that restricts the
  108767. ** set of rows in the view that are to be added to the ephemeral table.
  108768. */
  108769. SQLITE_PRIVATE void sqlite3MaterializeView(
  108770. Parse *pParse, /* Parsing context */
  108771. Table *pView, /* View definition */
  108772. Expr *pWhere, /* Optional WHERE clause to be added */
  108773. ExprList *pOrderBy, /* Optional ORDER BY clause */
  108774. Expr *pLimit, /* Optional LIMIT clause */
  108775. int iCur /* Cursor number for ephemeral table */
  108776. ){
  108777. SelectDest dest;
  108778. Select *pSel;
  108779. SrcList *pFrom;
  108780. sqlite3 *db = pParse->db;
  108781. int iDb = sqlite3SchemaToIndex(db, pView->pSchema);
  108782. pWhere = sqlite3ExprDup(db, pWhere, 0);
  108783. pFrom = sqlite3SrcListAppend(pParse, 0, 0, 0);
  108784. if( pFrom ){
  108785. assert( pFrom->nSrc==1 );
  108786. pFrom->a[0].zName = sqlite3DbStrDup(db, pView->zName);
  108787. pFrom->a[0].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zDbSName);
  108788. assert( pFrom->a[0].pOn==0 );
  108789. assert( pFrom->a[0].pUsing==0 );
  108790. }
  108791. pSel = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, pOrderBy,
  108792. SF_IncludeHidden, pLimit);
  108793. sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
  108794. sqlite3Select(pParse, pSel, &dest);
  108795. sqlite3SelectDelete(db, pSel);
  108796. }
  108797. #endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
  108798. #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
  108799. /*
  108800. ** Generate an expression tree to implement the WHERE, ORDER BY,
  108801. ** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
  108802. **
  108803. ** DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
  108804. ** \__________________________/
  108805. ** pLimitWhere (pInClause)
  108806. */
  108807. SQLITE_PRIVATE Expr *sqlite3LimitWhere(
  108808. Parse *pParse, /* The parser context */
  108809. SrcList *pSrc, /* the FROM clause -- which tables to scan */
  108810. Expr *pWhere, /* The WHERE clause. May be null */
  108811. ExprList *pOrderBy, /* The ORDER BY clause. May be null */
  108812. Expr *pLimit, /* The LIMIT clause. May be null */
  108813. char *zStmtType /* Either DELETE or UPDATE. For err msgs. */
  108814. ){
  108815. sqlite3 *db = pParse->db;
  108816. Expr *pLhs = NULL; /* LHS of IN(SELECT...) operator */
  108817. Expr *pInClause = NULL; /* WHERE rowid IN ( select ) */
  108818. ExprList *pEList = NULL; /* Expression list contaning only pSelectRowid */
  108819. SrcList *pSelectSrc = NULL; /* SELECT rowid FROM x ... (dup of pSrc) */
  108820. Select *pSelect = NULL; /* Complete SELECT tree */
  108821. Table *pTab;
  108822. /* Check that there isn't an ORDER BY without a LIMIT clause.
  108823. */
  108824. if( pOrderBy && pLimit==0 ) {
  108825. sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
  108826. sqlite3ExprDelete(pParse->db, pWhere);
  108827. sqlite3ExprListDelete(pParse->db, pOrderBy);
  108828. return 0;
  108829. }
  108830. /* We only need to generate a select expression if there
  108831. ** is a limit/offset term to enforce.
  108832. */
  108833. if( pLimit == 0 ) {
  108834. return pWhere;
  108835. }
  108836. /* Generate a select expression tree to enforce the limit/offset
  108837. ** term for the DELETE or UPDATE statement. For example:
  108838. ** DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
  108839. ** becomes:
  108840. ** DELETE FROM table_a WHERE rowid IN (
  108841. ** SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
  108842. ** );
  108843. */
  108844. pTab = pSrc->a[0].pTab;
  108845. if( HasRowid(pTab) ){
  108846. pLhs = sqlite3PExpr(pParse, TK_ROW, 0, 0);
  108847. pEList = sqlite3ExprListAppend(
  108848. pParse, 0, sqlite3PExpr(pParse, TK_ROW, 0, 0)
  108849. );
  108850. }else{
  108851. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  108852. if( pPk->nKeyCol==1 ){
  108853. const char *zName = pTab->aCol[pPk->aiColumn[0]].zName;
  108854. pLhs = sqlite3Expr(db, TK_ID, zName);
  108855. pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ID, zName));
  108856. }else{
  108857. int i;
  108858. for(i=0; i<pPk->nKeyCol; i++){
  108859. Expr *p = sqlite3Expr(db, TK_ID, pTab->aCol[pPk->aiColumn[i]].zName);
  108860. pEList = sqlite3ExprListAppend(pParse, pEList, p);
  108861. }
  108862. pLhs = sqlite3PExpr(pParse, TK_VECTOR, 0, 0);
  108863. if( pLhs ){
  108864. pLhs->x.pList = sqlite3ExprListDup(db, pEList, 0);
  108865. }
  108866. }
  108867. }
  108868. /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
  108869. ** and the SELECT subtree. */
  108870. pSrc->a[0].pTab = 0;
  108871. pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0);
  108872. pSrc->a[0].pTab = pTab;
  108873. pSrc->a[0].pIBIndex = 0;
  108874. /* generate the SELECT expression tree. */
  108875. pSelect = sqlite3SelectNew(pParse, pEList, pSelectSrc, pWhere, 0 ,0,
  108876. pOrderBy,0,pLimit
  108877. );
  108878. /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
  108879. pInClause = sqlite3PExpr(pParse, TK_IN, pLhs, 0);
  108880. sqlite3PExprAddSelect(pParse, pInClause, pSelect);
  108881. return pInClause;
  108882. }
  108883. #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) */
  108884. /* && !defined(SQLITE_OMIT_SUBQUERY) */
  108885. /*
  108886. ** Generate code for a DELETE FROM statement.
  108887. **
  108888. ** DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
  108889. ** \________/ \________________/
  108890. ** pTabList pWhere
  108891. */
  108892. SQLITE_PRIVATE void sqlite3DeleteFrom(
  108893. Parse *pParse, /* The parser context */
  108894. SrcList *pTabList, /* The table from which we should delete things */
  108895. Expr *pWhere, /* The WHERE clause. May be null */
  108896. ExprList *pOrderBy, /* ORDER BY clause. May be null */
  108897. Expr *pLimit /* LIMIT clause. May be null */
  108898. ){
  108899. Vdbe *v; /* The virtual database engine */
  108900. Table *pTab; /* The table from which records will be deleted */
  108901. int i; /* Loop counter */
  108902. WhereInfo *pWInfo; /* Information about the WHERE clause */
  108903. Index *pIdx; /* For looping over indices of the table */
  108904. int iTabCur; /* Cursor number for the table */
  108905. int iDataCur = 0; /* VDBE cursor for the canonical data source */
  108906. int iIdxCur = 0; /* Cursor number of the first index */
  108907. int nIdx; /* Number of indices */
  108908. sqlite3 *db; /* Main database structure */
  108909. AuthContext sContext; /* Authorization context */
  108910. NameContext sNC; /* Name context to resolve expressions in */
  108911. int iDb; /* Database number */
  108912. int memCnt = 0; /* Memory cell used for change counting */
  108913. int rcauth; /* Value returned by authorization callback */
  108914. int eOnePass; /* ONEPASS_OFF or _SINGLE or _MULTI */
  108915. int aiCurOnePass[2]; /* The write cursors opened by WHERE_ONEPASS */
  108916. u8 *aToOpen = 0; /* Open cursor iTabCur+j if aToOpen[j] is true */
  108917. Index *pPk; /* The PRIMARY KEY index on the table */
  108918. int iPk = 0; /* First of nPk registers holding PRIMARY KEY value */
  108919. i16 nPk = 1; /* Number of columns in the PRIMARY KEY */
  108920. int iKey; /* Memory cell holding key of row to be deleted */
  108921. i16 nKey; /* Number of memory cells in the row key */
  108922. int iEphCur = 0; /* Ephemeral table holding all primary key values */
  108923. int iRowSet = 0; /* Register for rowset of rows to delete */
  108924. int addrBypass = 0; /* Address of jump over the delete logic */
  108925. int addrLoop = 0; /* Top of the delete loop */
  108926. int addrEphOpen = 0; /* Instruction to open the Ephemeral table */
  108927. int bComplex; /* True if there are triggers or FKs or
  108928. ** subqueries in the WHERE clause */
  108929. #ifndef SQLITE_OMIT_TRIGGER
  108930. int isView; /* True if attempting to delete from a view */
  108931. Trigger *pTrigger; /* List of table triggers, if required */
  108932. #endif
  108933. memset(&sContext, 0, sizeof(sContext));
  108934. db = pParse->db;
  108935. if( pParse->nErr || db->mallocFailed ){
  108936. goto delete_from_cleanup;
  108937. }
  108938. assert( pTabList->nSrc==1 );
  108939. /* Locate the table which we want to delete. This table has to be
  108940. ** put in an SrcList structure because some of the subroutines we
  108941. ** will be calling are designed to work with multiple tables and expect
  108942. ** an SrcList* parameter instead of just a Table* parameter.
  108943. */
  108944. pTab = sqlite3SrcListLookup(pParse, pTabList);
  108945. if( pTab==0 ) goto delete_from_cleanup;
  108946. /* Figure out if we have any triggers and if the table being
  108947. ** deleted from is a view
  108948. */
  108949. #ifndef SQLITE_OMIT_TRIGGER
  108950. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
  108951. isView = pTab->pSelect!=0;
  108952. #else
  108953. # define pTrigger 0
  108954. # define isView 0
  108955. #endif
  108956. bComplex = pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0);
  108957. #ifdef SQLITE_OMIT_VIEW
  108958. # undef isView
  108959. # define isView 0
  108960. #endif
  108961. #ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
  108962. if( !isView ){
  108963. pWhere = sqlite3LimitWhere(
  108964. pParse, pTabList, pWhere, pOrderBy, pLimit, "DELETE"
  108965. );
  108966. pOrderBy = 0;
  108967. pLimit = 0;
  108968. }
  108969. #endif
  108970. /* If pTab is really a view, make sure it has been initialized.
  108971. */
  108972. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  108973. goto delete_from_cleanup;
  108974. }
  108975. if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){
  108976. goto delete_from_cleanup;
  108977. }
  108978. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  108979. assert( iDb<db->nDb );
  108980. rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0,
  108981. db->aDb[iDb].zDbSName);
  108982. assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );
  108983. if( rcauth==SQLITE_DENY ){
  108984. goto delete_from_cleanup;
  108985. }
  108986. assert(!isView || pTrigger);
  108987. /* Assign cursor numbers to the table and all its indices.
  108988. */
  108989. assert( pTabList->nSrc==1 );
  108990. iTabCur = pTabList->a[0].iCursor = pParse->nTab++;
  108991. for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
  108992. pParse->nTab++;
  108993. }
  108994. /* Start the view context
  108995. */
  108996. if( isView ){
  108997. sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
  108998. }
  108999. /* Begin generating code.
  109000. */
  109001. v = sqlite3GetVdbe(pParse);
  109002. if( v==0 ){
  109003. goto delete_from_cleanup;
  109004. }
  109005. if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
  109006. sqlite3BeginWriteOperation(pParse, bComplex, iDb);
  109007. /* If we are trying to delete from a view, realize that view into
  109008. ** an ephemeral table.
  109009. */
  109010. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  109011. if( isView ){
  109012. sqlite3MaterializeView(pParse, pTab,
  109013. pWhere, pOrderBy, pLimit, iTabCur
  109014. );
  109015. iDataCur = iIdxCur = iTabCur;
  109016. pOrderBy = 0;
  109017. pLimit = 0;
  109018. }
  109019. #endif
  109020. /* Resolve the column names in the WHERE clause.
  109021. */
  109022. memset(&sNC, 0, sizeof(sNC));
  109023. sNC.pParse = pParse;
  109024. sNC.pSrcList = pTabList;
  109025. if( sqlite3ResolveExprNames(&sNC, pWhere) ){
  109026. goto delete_from_cleanup;
  109027. }
  109028. /* Initialize the counter of the number of rows deleted, if
  109029. ** we are counting rows.
  109030. */
  109031. if( (db->flags & SQLITE_CountRows)!=0
  109032. && !pParse->nested
  109033. && !pParse->pTriggerTab
  109034. ){
  109035. memCnt = ++pParse->nMem;
  109036. sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
  109037. }
  109038. #ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
  109039. /* Special case: A DELETE without a WHERE clause deletes everything.
  109040. ** It is easier just to erase the whole table. Prior to version 3.6.5,
  109041. ** this optimization caused the row change count (the value returned by
  109042. ** API function sqlite3_count_changes) to be set incorrectly.
  109043. **
  109044. ** The "rcauth==SQLITE_OK" terms is the
  109045. ** IMPLEMENTATION-OF: R-17228-37124 If the action code is SQLITE_DELETE and
  109046. ** the callback returns SQLITE_IGNORE then the DELETE operation proceeds but
  109047. ** the truncate optimization is disabled and all rows are deleted
  109048. ** individually.
  109049. */
  109050. if( rcauth==SQLITE_OK
  109051. && pWhere==0
  109052. && !bComplex
  109053. && !IsVirtual(pTab)
  109054. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  109055. && db->xPreUpdateCallback==0
  109056. #endif
  109057. ){
  109058. assert( !isView );
  109059. sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
  109060. if( HasRowid(pTab) ){
  109061. sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt ? memCnt : -1,
  109062. pTab->zName, P4_STATIC);
  109063. }
  109064. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  109065. assert( pIdx->pSchema==pTab->pSchema );
  109066. sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
  109067. }
  109068. }else
  109069. #endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
  109070. {
  109071. u16 wcf = WHERE_ONEPASS_DESIRED|WHERE_DUPLICATES_OK|WHERE_SEEK_TABLE;
  109072. if( sNC.ncFlags & NC_VarSelect ) bComplex = 1;
  109073. wcf |= (bComplex ? 0 : WHERE_ONEPASS_MULTIROW);
  109074. if( HasRowid(pTab) ){
  109075. /* For a rowid table, initialize the RowSet to an empty set */
  109076. pPk = 0;
  109077. nPk = 1;
  109078. iRowSet = ++pParse->nMem;
  109079. sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
  109080. }else{
  109081. /* For a WITHOUT ROWID table, create an ephemeral table used to
  109082. ** hold all primary keys for rows to be deleted. */
  109083. pPk = sqlite3PrimaryKeyIndex(pTab);
  109084. assert( pPk!=0 );
  109085. nPk = pPk->nKeyCol;
  109086. iPk = pParse->nMem+1;
  109087. pParse->nMem += nPk;
  109088. iEphCur = pParse->nTab++;
  109089. addrEphOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEphCur, nPk);
  109090. sqlite3VdbeSetP4KeyInfo(pParse, pPk);
  109091. }
  109092. /* Construct a query to find the rowid or primary key for every row
  109093. ** to be deleted, based on the WHERE clause. Set variable eOnePass
  109094. ** to indicate the strategy used to implement this delete:
  109095. **
  109096. ** ONEPASS_OFF: Two-pass approach - use a FIFO for rowids/PK values.
  109097. ** ONEPASS_SINGLE: One-pass approach - at most one row deleted.
  109098. ** ONEPASS_MULTI: One-pass approach - any number of rows may be deleted.
  109099. */
  109100. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0, wcf, iTabCur+1);
  109101. if( pWInfo==0 ) goto delete_from_cleanup;
  109102. eOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
  109103. assert( IsVirtual(pTab)==0 || eOnePass!=ONEPASS_MULTI );
  109104. assert( IsVirtual(pTab) || bComplex || eOnePass!=ONEPASS_OFF );
  109105. if( eOnePass!=ONEPASS_SINGLE ) sqlite3MultiWrite(pParse);
  109106. /* Keep track of the number of rows to be deleted */
  109107. if( memCnt ){
  109108. sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
  109109. }
  109110. /* Extract the rowid or primary key for the current row */
  109111. if( pPk ){
  109112. for(i=0; i<nPk; i++){
  109113. assert( pPk->aiColumn[i]>=0 );
  109114. sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur,
  109115. pPk->aiColumn[i], iPk+i);
  109116. }
  109117. iKey = iPk;
  109118. }else{
  109119. iKey = ++pParse->nMem;
  109120. sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur, -1, iKey);
  109121. }
  109122. if( eOnePass!=ONEPASS_OFF ){
  109123. /* For ONEPASS, no need to store the rowid/primary-key. There is only
  109124. ** one, so just keep it in its register(s) and fall through to the
  109125. ** delete code. */
  109126. nKey = nPk; /* OP_Found will use an unpacked key */
  109127. aToOpen = sqlite3DbMallocRawNN(db, nIdx+2);
  109128. if( aToOpen==0 ){
  109129. sqlite3WhereEnd(pWInfo);
  109130. goto delete_from_cleanup;
  109131. }
  109132. memset(aToOpen, 1, nIdx+1);
  109133. aToOpen[nIdx+1] = 0;
  109134. if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iTabCur] = 0;
  109135. if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iTabCur] = 0;
  109136. if( addrEphOpen ) sqlite3VdbeChangeToNoop(v, addrEphOpen);
  109137. }else{
  109138. if( pPk ){
  109139. /* Add the PK key for this row to the temporary table */
  109140. iKey = ++pParse->nMem;
  109141. nKey = 0; /* Zero tells OP_Found to use a composite key */
  109142. sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, iKey,
  109143. sqlite3IndexAffinityStr(pParse->db, pPk), nPk);
  109144. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iEphCur, iKey, iPk, nPk);
  109145. }else{
  109146. /* Add the rowid of the row to be deleted to the RowSet */
  109147. nKey = 1; /* OP_DeferredSeek always uses a single rowid */
  109148. sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, iKey);
  109149. }
  109150. }
  109151. /* If this DELETE cannot use the ONEPASS strategy, this is the
  109152. ** end of the WHERE loop */
  109153. if( eOnePass!=ONEPASS_OFF ){
  109154. addrBypass = sqlite3VdbeMakeLabel(pParse);
  109155. }else{
  109156. sqlite3WhereEnd(pWInfo);
  109157. }
  109158. /* Unless this is a view, open cursors for the table we are
  109159. ** deleting from and all its indices. If this is a view, then the
  109160. ** only effect this statement has is to fire the INSTEAD OF
  109161. ** triggers.
  109162. */
  109163. if( !isView ){
  109164. int iAddrOnce = 0;
  109165. if( eOnePass==ONEPASS_MULTI ){
  109166. iAddrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
  109167. }
  109168. testcase( IsVirtual(pTab) );
  109169. sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, OPFLAG_FORDELETE,
  109170. iTabCur, aToOpen, &iDataCur, &iIdxCur);
  109171. assert( pPk || IsVirtual(pTab) || iDataCur==iTabCur );
  109172. assert( pPk || IsVirtual(pTab) || iIdxCur==iDataCur+1 );
  109173. if( eOnePass==ONEPASS_MULTI ){
  109174. sqlite3VdbeJumpHereOrPopInst(v, iAddrOnce);
  109175. }
  109176. }
  109177. /* Set up a loop over the rowids/primary-keys that were found in the
  109178. ** where-clause loop above.
  109179. */
  109180. if( eOnePass!=ONEPASS_OFF ){
  109181. assert( nKey==nPk ); /* OP_Found will use an unpacked key */
  109182. if( !IsVirtual(pTab) && aToOpen[iDataCur-iTabCur] ){
  109183. assert( pPk!=0 || pTab->pSelect!=0 );
  109184. sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, addrBypass, iKey, nKey);
  109185. VdbeCoverage(v);
  109186. }
  109187. }else if( pPk ){
  109188. addrLoop = sqlite3VdbeAddOp1(v, OP_Rewind, iEphCur); VdbeCoverage(v);
  109189. if( IsVirtual(pTab) ){
  109190. sqlite3VdbeAddOp3(v, OP_Column, iEphCur, 0, iKey);
  109191. }else{
  109192. sqlite3VdbeAddOp2(v, OP_RowData, iEphCur, iKey);
  109193. }
  109194. assert( nKey==0 ); /* OP_Found will use a composite key */
  109195. }else{
  109196. addrLoop = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, 0, iKey);
  109197. VdbeCoverage(v);
  109198. assert( nKey==1 );
  109199. }
  109200. /* Delete the row */
  109201. #ifndef SQLITE_OMIT_VIRTUALTABLE
  109202. if( IsVirtual(pTab) ){
  109203. const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
  109204. sqlite3VtabMakeWritable(pParse, pTab);
  109205. assert( eOnePass==ONEPASS_OFF || eOnePass==ONEPASS_SINGLE );
  109206. sqlite3MayAbort(pParse);
  109207. if( eOnePass==ONEPASS_SINGLE ){
  109208. sqlite3VdbeAddOp1(v, OP_Close, iTabCur);
  109209. if( sqlite3IsToplevel(pParse) ){
  109210. pParse->isMultiWrite = 0;
  109211. }
  109212. }
  109213. sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iKey, pVTab, P4_VTAB);
  109214. sqlite3VdbeChangeP5(v, OE_Abort);
  109215. }else
  109216. #endif
  109217. {
  109218. int count = (pParse->nested==0); /* True to count changes */
  109219. sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
  109220. iKey, nKey, count, OE_Default, eOnePass, aiCurOnePass[1]);
  109221. }
  109222. /* End of the loop over all rowids/primary-keys. */
  109223. if( eOnePass!=ONEPASS_OFF ){
  109224. sqlite3VdbeResolveLabel(v, addrBypass);
  109225. sqlite3WhereEnd(pWInfo);
  109226. }else if( pPk ){
  109227. sqlite3VdbeAddOp2(v, OP_Next, iEphCur, addrLoop+1); VdbeCoverage(v);
  109228. sqlite3VdbeJumpHere(v, addrLoop);
  109229. }else{
  109230. sqlite3VdbeGoto(v, addrLoop);
  109231. sqlite3VdbeJumpHere(v, addrLoop);
  109232. }
  109233. } /* End non-truncate path */
  109234. /* Update the sqlite_sequence table by storing the content of the
  109235. ** maximum rowid counter values recorded while inserting into
  109236. ** autoincrement tables.
  109237. */
  109238. if( pParse->nested==0 && pParse->pTriggerTab==0 ){
  109239. sqlite3AutoincrementEnd(pParse);
  109240. }
  109241. /* Return the number of rows that were deleted. If this routine is
  109242. ** generating code because of a call to sqlite3NestedParse(), do not
  109243. ** invoke the callback function.
  109244. */
  109245. if( memCnt ){
  109246. sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
  109247. sqlite3VdbeSetNumCols(v, 1);
  109248. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
  109249. }
  109250. delete_from_cleanup:
  109251. sqlite3AuthContextPop(&sContext);
  109252. sqlite3SrcListDelete(db, pTabList);
  109253. sqlite3ExprDelete(db, pWhere);
  109254. #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT)
  109255. sqlite3ExprListDelete(db, pOrderBy);
  109256. sqlite3ExprDelete(db, pLimit);
  109257. #endif
  109258. sqlite3DbFree(db, aToOpen);
  109259. return;
  109260. }
  109261. /* Make sure "isView" and other macros defined above are undefined. Otherwise
  109262. ** they may interfere with compilation of other functions in this file
  109263. ** (or in another file, if this file becomes part of the amalgamation). */
  109264. #ifdef isView
  109265. #undef isView
  109266. #endif
  109267. #ifdef pTrigger
  109268. #undef pTrigger
  109269. #endif
  109270. /*
  109271. ** This routine generates VDBE code that causes a single row of a
  109272. ** single table to be deleted. Both the original table entry and
  109273. ** all indices are removed.
  109274. **
  109275. ** Preconditions:
  109276. **
  109277. ** 1. iDataCur is an open cursor on the btree that is the canonical data
  109278. ** store for the table. (This will be either the table itself,
  109279. ** in the case of a rowid table, or the PRIMARY KEY index in the case
  109280. ** of a WITHOUT ROWID table.)
  109281. **
  109282. ** 2. Read/write cursors for all indices of pTab must be open as
  109283. ** cursor number iIdxCur+i for the i-th index.
  109284. **
  109285. ** 3. The primary key for the row to be deleted must be stored in a
  109286. ** sequence of nPk memory cells starting at iPk. If nPk==0 that means
  109287. ** that a search record formed from OP_MakeRecord is contained in the
  109288. ** single memory location iPk.
  109289. **
  109290. ** eMode:
  109291. ** Parameter eMode may be passed either ONEPASS_OFF (0), ONEPASS_SINGLE, or
  109292. ** ONEPASS_MULTI. If eMode is not ONEPASS_OFF, then the cursor
  109293. ** iDataCur already points to the row to delete. If eMode is ONEPASS_OFF
  109294. ** then this function must seek iDataCur to the entry identified by iPk
  109295. ** and nPk before reading from it.
  109296. **
  109297. ** If eMode is ONEPASS_MULTI, then this call is being made as part
  109298. ** of a ONEPASS delete that affects multiple rows. In this case, if
  109299. ** iIdxNoSeek is a valid cursor number (>=0) and is not the same as
  109300. ** iDataCur, then its position should be preserved following the delete
  109301. ** operation. Or, if iIdxNoSeek is not a valid cursor number, the
  109302. ** position of iDataCur should be preserved instead.
  109303. **
  109304. ** iIdxNoSeek:
  109305. ** If iIdxNoSeek is a valid cursor number (>=0) not equal to iDataCur,
  109306. ** then it identifies an index cursor (from within array of cursors
  109307. ** starting at iIdxCur) that already points to the index entry to be deleted.
  109308. ** Except, this optimization is disabled if there are BEFORE triggers since
  109309. ** the trigger body might have moved the cursor.
  109310. */
  109311. SQLITE_PRIVATE void sqlite3GenerateRowDelete(
  109312. Parse *pParse, /* Parsing context */
  109313. Table *pTab, /* Table containing the row to be deleted */
  109314. Trigger *pTrigger, /* List of triggers to (potentially) fire */
  109315. int iDataCur, /* Cursor from which column data is extracted */
  109316. int iIdxCur, /* First index cursor */
  109317. int iPk, /* First memory cell containing the PRIMARY KEY */
  109318. i16 nPk, /* Number of PRIMARY KEY memory cells */
  109319. u8 count, /* If non-zero, increment the row change counter */
  109320. u8 onconf, /* Default ON CONFLICT policy for triggers */
  109321. u8 eMode, /* ONEPASS_OFF, _SINGLE, or _MULTI. See above */
  109322. int iIdxNoSeek /* Cursor number of cursor that does not need seeking */
  109323. ){
  109324. Vdbe *v = pParse->pVdbe; /* Vdbe */
  109325. int iOld = 0; /* First register in OLD.* array */
  109326. int iLabel; /* Label resolved to end of generated code */
  109327. u8 opSeek; /* Seek opcode */
  109328. /* Vdbe is guaranteed to have been allocated by this stage. */
  109329. assert( v );
  109330. VdbeModuleComment((v, "BEGIN: GenRowDel(%d,%d,%d,%d)",
  109331. iDataCur, iIdxCur, iPk, (int)nPk));
  109332. /* Seek cursor iCur to the row to delete. If this row no longer exists
  109333. ** (this can happen if a trigger program has already deleted it), do
  109334. ** not attempt to delete it or fire any DELETE triggers. */
  109335. iLabel = sqlite3VdbeMakeLabel(pParse);
  109336. opSeek = HasRowid(pTab) ? OP_NotExists : OP_NotFound;
  109337. if( eMode==ONEPASS_OFF ){
  109338. sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk);
  109339. VdbeCoverageIf(v, opSeek==OP_NotExists);
  109340. VdbeCoverageIf(v, opSeek==OP_NotFound);
  109341. }
  109342. /* If there are any triggers to fire, allocate a range of registers to
  109343. ** use for the old.* references in the triggers. */
  109344. if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){
  109345. u32 mask; /* Mask of OLD.* columns in use */
  109346. int iCol; /* Iterator used while populating OLD.* */
  109347. int addrStart; /* Start of BEFORE trigger programs */
  109348. /* TODO: Could use temporary registers here. Also could attempt to
  109349. ** avoid copying the contents of the rowid register. */
  109350. mask = sqlite3TriggerColmask(
  109351. pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf
  109352. );
  109353. mask |= sqlite3FkOldmask(pParse, pTab);
  109354. iOld = pParse->nMem+1;
  109355. pParse->nMem += (1 + pTab->nCol);
  109356. /* Populate the OLD.* pseudo-table register array. These values will be
  109357. ** used by any BEFORE and AFTER triggers that exist. */
  109358. sqlite3VdbeAddOp2(v, OP_Copy, iPk, iOld);
  109359. for(iCol=0; iCol<pTab->nCol; iCol++){
  109360. testcase( mask!=0xffffffff && iCol==31 );
  109361. testcase( mask!=0xffffffff && iCol==32 );
  109362. if( mask==0xffffffff || (iCol<=31 && (mask & MASKBIT32(iCol))!=0) ){
  109363. int kk = sqlite3TableColumnToStorage(pTab, iCol);
  109364. sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, iCol, iOld+kk+1);
  109365. }
  109366. }
  109367. /* Invoke BEFORE DELETE trigger programs. */
  109368. addrStart = sqlite3VdbeCurrentAddr(v);
  109369. sqlite3CodeRowTrigger(pParse, pTrigger,
  109370. TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
  109371. );
  109372. /* If any BEFORE triggers were coded, then seek the cursor to the
  109373. ** row to be deleted again. It may be that the BEFORE triggers moved
  109374. ** the cursor or already deleted the row that the cursor was
  109375. ** pointing to.
  109376. **
  109377. ** Also disable the iIdxNoSeek optimization since the BEFORE trigger
  109378. ** may have moved that cursor.
  109379. */
  109380. if( addrStart<sqlite3VdbeCurrentAddr(v) ){
  109381. sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk);
  109382. VdbeCoverageIf(v, opSeek==OP_NotExists);
  109383. VdbeCoverageIf(v, opSeek==OP_NotFound);
  109384. testcase( iIdxNoSeek>=0 );
  109385. iIdxNoSeek = -1;
  109386. }
  109387. /* Do FK processing. This call checks that any FK constraints that
  109388. ** refer to this table (i.e. constraints attached to other tables)
  109389. ** are not violated by deleting this row. */
  109390. sqlite3FkCheck(pParse, pTab, iOld, 0, 0, 0);
  109391. }
  109392. /* Delete the index and table entries. Skip this step if pTab is really
  109393. ** a view (in which case the only effect of the DELETE statement is to
  109394. ** fire the INSTEAD OF triggers).
  109395. **
  109396. ** If variable 'count' is non-zero, then this OP_Delete instruction should
  109397. ** invoke the update-hook. The pre-update-hook, on the other hand should
  109398. ** be invoked unless table pTab is a system table. The difference is that
  109399. ** the update-hook is not invoked for rows removed by REPLACE, but the
  109400. ** pre-update-hook is.
  109401. */
  109402. if( pTab->pSelect==0 ){
  109403. u8 p5 = 0;
  109404. sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,iIdxNoSeek);
  109405. sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, (count?OPFLAG_NCHANGE:0));
  109406. if( pParse->nested==0 || 0==sqlite3_stricmp(pTab->zName, "sqlite_stat1") ){
  109407. sqlite3VdbeAppendP4(v, (char*)pTab, P4_TABLE);
  109408. }
  109409. if( eMode!=ONEPASS_OFF ){
  109410. sqlite3VdbeChangeP5(v, OPFLAG_AUXDELETE);
  109411. }
  109412. if( iIdxNoSeek>=0 && iIdxNoSeek!=iDataCur ){
  109413. sqlite3VdbeAddOp1(v, OP_Delete, iIdxNoSeek);
  109414. }
  109415. if( eMode==ONEPASS_MULTI ) p5 |= OPFLAG_SAVEPOSITION;
  109416. sqlite3VdbeChangeP5(v, p5);
  109417. }
  109418. /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
  109419. ** handle rows (possibly in other tables) that refer via a foreign key
  109420. ** to the row just deleted. */
  109421. sqlite3FkActions(pParse, pTab, 0, iOld, 0, 0);
  109422. /* Invoke AFTER DELETE trigger programs. */
  109423. sqlite3CodeRowTrigger(pParse, pTrigger,
  109424. TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
  109425. );
  109426. /* Jump here if the row had already been deleted before any BEFORE
  109427. ** trigger programs were invoked. Or if a trigger program throws a
  109428. ** RAISE(IGNORE) exception. */
  109429. sqlite3VdbeResolveLabel(v, iLabel);
  109430. VdbeModuleComment((v, "END: GenRowDel()"));
  109431. }
  109432. /*
  109433. ** This routine generates VDBE code that causes the deletion of all
  109434. ** index entries associated with a single row of a single table, pTab
  109435. **
  109436. ** Preconditions:
  109437. **
  109438. ** 1. A read/write cursor "iDataCur" must be open on the canonical storage
  109439. ** btree for the table pTab. (This will be either the table itself
  109440. ** for rowid tables or to the primary key index for WITHOUT ROWID
  109441. ** tables.)
  109442. **
  109443. ** 2. Read/write cursors for all indices of pTab must be open as
  109444. ** cursor number iIdxCur+i for the i-th index. (The pTab->pIndex
  109445. ** index is the 0-th index.)
  109446. **
  109447. ** 3. The "iDataCur" cursor must be already be positioned on the row
  109448. ** that is to be deleted.
  109449. */
  109450. SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(
  109451. Parse *pParse, /* Parsing and code generating context */
  109452. Table *pTab, /* Table containing the row to be deleted */
  109453. int iDataCur, /* Cursor of table holding data. */
  109454. int iIdxCur, /* First index cursor */
  109455. int *aRegIdx, /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
  109456. int iIdxNoSeek /* Do not delete from this cursor */
  109457. ){
  109458. int i; /* Index loop counter */
  109459. int r1 = -1; /* Register holding an index key */
  109460. int iPartIdxLabel; /* Jump destination for skipping partial index entries */
  109461. Index *pIdx; /* Current index */
  109462. Index *pPrior = 0; /* Prior index */
  109463. Vdbe *v; /* The prepared statement under construction */
  109464. Index *pPk; /* PRIMARY KEY index, or NULL for rowid tables */
  109465. v = pParse->pVdbe;
  109466. pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
  109467. for(i=0, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
  109468. assert( iIdxCur+i!=iDataCur || pPk==pIdx );
  109469. if( aRegIdx!=0 && aRegIdx[i]==0 ) continue;
  109470. if( pIdx==pPk ) continue;
  109471. if( iIdxCur+i==iIdxNoSeek ) continue;
  109472. VdbeModuleComment((v, "GenRowIdxDel for %s", pIdx->zName));
  109473. r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 1,
  109474. &iPartIdxLabel, pPrior, r1);
  109475. sqlite3VdbeAddOp3(v, OP_IdxDelete, iIdxCur+i, r1,
  109476. pIdx->uniqNotNull ? pIdx->nKeyCol : pIdx->nColumn);
  109477. sqlite3VdbeChangeP5(v, 1); /* Cause IdxDelete to error if no entry found */
  109478. sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
  109479. pPrior = pIdx;
  109480. }
  109481. }
  109482. /*
  109483. ** Generate code that will assemble an index key and stores it in register
  109484. ** regOut. The key with be for index pIdx which is an index on pTab.
  109485. ** iCur is the index of a cursor open on the pTab table and pointing to
  109486. ** the entry that needs indexing. If pTab is a WITHOUT ROWID table, then
  109487. ** iCur must be the cursor of the PRIMARY KEY index.
  109488. **
  109489. ** Return a register number which is the first in a block of
  109490. ** registers that holds the elements of the index key. The
  109491. ** block of registers has already been deallocated by the time
  109492. ** this routine returns.
  109493. **
  109494. ** If *piPartIdxLabel is not NULL, fill it in with a label and jump
  109495. ** to that label if pIdx is a partial index that should be skipped.
  109496. ** The label should be resolved using sqlite3ResolvePartIdxLabel().
  109497. ** A partial index should be skipped if its WHERE clause evaluates
  109498. ** to false or null. If pIdx is not a partial index, *piPartIdxLabel
  109499. ** will be set to zero which is an empty label that is ignored by
  109500. ** sqlite3ResolvePartIdxLabel().
  109501. **
  109502. ** The pPrior and regPrior parameters are used to implement a cache to
  109503. ** avoid unnecessary register loads. If pPrior is not NULL, then it is
  109504. ** a pointer to a different index for which an index key has just been
  109505. ** computed into register regPrior. If the current pIdx index is generating
  109506. ** its key into the same sequence of registers and if pPrior and pIdx share
  109507. ** a column in common, then the register corresponding to that column already
  109508. ** holds the correct value and the loading of that register is skipped.
  109509. ** This optimization is helpful when doing a DELETE or an INTEGRITY_CHECK
  109510. ** on a table with multiple indices, and especially with the ROWID or
  109511. ** PRIMARY KEY columns of the index.
  109512. */
  109513. SQLITE_PRIVATE int sqlite3GenerateIndexKey(
  109514. Parse *pParse, /* Parsing context */
  109515. Index *pIdx, /* The index for which to generate a key */
  109516. int iDataCur, /* Cursor number from which to take column data */
  109517. int regOut, /* Put the new key into this register if not 0 */
  109518. int prefixOnly, /* Compute only a unique prefix of the key */
  109519. int *piPartIdxLabel, /* OUT: Jump to this label to skip partial index */
  109520. Index *pPrior, /* Previously generated index key */
  109521. int regPrior /* Register holding previous generated key */
  109522. ){
  109523. Vdbe *v = pParse->pVdbe;
  109524. int j;
  109525. int regBase;
  109526. int nCol;
  109527. if( piPartIdxLabel ){
  109528. if( pIdx->pPartIdxWhere ){
  109529. *piPartIdxLabel = sqlite3VdbeMakeLabel(pParse);
  109530. pParse->iSelfTab = iDataCur + 1;
  109531. sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, *piPartIdxLabel,
  109532. SQLITE_JUMPIFNULL);
  109533. pParse->iSelfTab = 0;
  109534. pPrior = 0; /* Ticket a9efb42811fa41ee 2019-11-02;
  109535. ** pPartIdxWhere may have corrupted regPrior registers */
  109536. }else{
  109537. *piPartIdxLabel = 0;
  109538. }
  109539. }
  109540. nCol = (prefixOnly && pIdx->uniqNotNull) ? pIdx->nKeyCol : pIdx->nColumn;
  109541. regBase = sqlite3GetTempRange(pParse, nCol);
  109542. if( pPrior && (regBase!=regPrior || pPrior->pPartIdxWhere) ) pPrior = 0;
  109543. for(j=0; j<nCol; j++){
  109544. if( pPrior
  109545. && pPrior->aiColumn[j]==pIdx->aiColumn[j]
  109546. && pPrior->aiColumn[j]!=XN_EXPR
  109547. ){
  109548. /* This column was already computed by the previous index */
  109549. continue;
  109550. }
  109551. sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iDataCur, j, regBase+j);
  109552. /* If the column affinity is REAL but the number is an integer, then it
  109553. ** might be stored in the table as an integer (using a compact
  109554. ** representation) then converted to REAL by an OP_RealAffinity opcode.
  109555. ** But we are getting ready to store this value back into an index, where
  109556. ** it should be converted by to INTEGER again. So omit the OP_RealAffinity
  109557. ** opcode if it is present */
  109558. sqlite3VdbeDeletePriorOpcode(v, OP_RealAffinity);
  109559. }
  109560. if( regOut ){
  109561. sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regOut);
  109562. if( pIdx->pTable->pSelect ){
  109563. const char *zAff = sqlite3IndexAffinityStr(pParse->db, pIdx);
  109564. sqlite3VdbeChangeP4(v, -1, zAff, P4_TRANSIENT);
  109565. }
  109566. }
  109567. sqlite3ReleaseTempRange(pParse, regBase, nCol);
  109568. return regBase;
  109569. }
  109570. /*
  109571. ** If a prior call to sqlite3GenerateIndexKey() generated a jump-over label
  109572. ** because it was a partial index, then this routine should be called to
  109573. ** resolve that label.
  109574. */
  109575. SQLITE_PRIVATE void sqlite3ResolvePartIdxLabel(Parse *pParse, int iLabel){
  109576. if( iLabel ){
  109577. sqlite3VdbeResolveLabel(pParse->pVdbe, iLabel);
  109578. }
  109579. }
  109580. /************** End of delete.c **********************************************/
  109581. /************** Begin file func.c ********************************************/
  109582. /*
  109583. ** 2002 February 23
  109584. **
  109585. ** The author disclaims copyright to this source code. In place of
  109586. ** a legal notice, here is a blessing:
  109587. **
  109588. ** May you do good and not evil.
  109589. ** May you find forgiveness for yourself and forgive others.
  109590. ** May you share freely, never taking more than you give.
  109591. **
  109592. *************************************************************************
  109593. ** This file contains the C-language implementations for many of the SQL
  109594. ** functions of SQLite. (Some function, and in particular the date and
  109595. ** time functions, are implemented separately.)
  109596. */
  109597. /* #include "sqliteInt.h" */
  109598. /* #include <stdlib.h> */
  109599. /* #include <assert.h> */
  109600. #ifndef SQLITE_OMIT_FLOATING_POINT
  109601. /* #include <math.h> */
  109602. #endif
  109603. /* #include "vdbeInt.h" */
  109604. /*
  109605. ** Return the collating function associated with a function.
  109606. */
  109607. static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
  109608. VdbeOp *pOp;
  109609. assert( context->pVdbe!=0 );
  109610. pOp = &context->pVdbe->aOp[context->iOp-1];
  109611. assert( pOp->opcode==OP_CollSeq );
  109612. assert( pOp->p4type==P4_COLLSEQ );
  109613. return pOp->p4.pColl;
  109614. }
  109615. /*
  109616. ** Indicate that the accumulator load should be skipped on this
  109617. ** iteration of the aggregate loop.
  109618. */
  109619. static void sqlite3SkipAccumulatorLoad(sqlite3_context *context){
  109620. assert( context->isError<=0 );
  109621. context->isError = -1;
  109622. context->skipFlag = 1;
  109623. }
  109624. /*
  109625. ** Implementation of the non-aggregate min() and max() functions
  109626. */
  109627. static void minmaxFunc(
  109628. sqlite3_context *context,
  109629. int argc,
  109630. sqlite3_value **argv
  109631. ){
  109632. int i;
  109633. int mask; /* 0 for min() or 0xffffffff for max() */
  109634. int iBest;
  109635. CollSeq *pColl;
  109636. assert( argc>1 );
  109637. mask = sqlite3_user_data(context)==0 ? 0 : -1;
  109638. pColl = sqlite3GetFuncCollSeq(context);
  109639. assert( pColl );
  109640. assert( mask==-1 || mask==0 );
  109641. iBest = 0;
  109642. if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  109643. for(i=1; i<argc; i++){
  109644. if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
  109645. if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
  109646. testcase( mask==0 );
  109647. iBest = i;
  109648. }
  109649. }
  109650. sqlite3_result_value(context, argv[iBest]);
  109651. }
  109652. /*
  109653. ** Return the type of the argument.
  109654. */
  109655. static void typeofFunc(
  109656. sqlite3_context *context,
  109657. int NotUsed,
  109658. sqlite3_value **argv
  109659. ){
  109660. static const char *azType[] = { "integer", "real", "text", "blob", "null" };
  109661. int i = sqlite3_value_type(argv[0]) - 1;
  109662. UNUSED_PARAMETER(NotUsed);
  109663. assert( i>=0 && i<ArraySize(azType) );
  109664. assert( SQLITE_INTEGER==1 );
  109665. assert( SQLITE_FLOAT==2 );
  109666. assert( SQLITE_TEXT==3 );
  109667. assert( SQLITE_BLOB==4 );
  109668. assert( SQLITE_NULL==5 );
  109669. /* EVIDENCE-OF: R-01470-60482 The sqlite3_value_type(V) interface returns
  109670. ** the datatype code for the initial datatype of the sqlite3_value object
  109671. ** V. The returned value is one of SQLITE_INTEGER, SQLITE_FLOAT,
  109672. ** SQLITE_TEXT, SQLITE_BLOB, or SQLITE_NULL. */
  109673. sqlite3_result_text(context, azType[i], -1, SQLITE_STATIC);
  109674. }
  109675. /*
  109676. ** Implementation of the length() function
  109677. */
  109678. static void lengthFunc(
  109679. sqlite3_context *context,
  109680. int argc,
  109681. sqlite3_value **argv
  109682. ){
  109683. assert( argc==1 );
  109684. UNUSED_PARAMETER(argc);
  109685. switch( sqlite3_value_type(argv[0]) ){
  109686. case SQLITE_BLOB:
  109687. case SQLITE_INTEGER:
  109688. case SQLITE_FLOAT: {
  109689. sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
  109690. break;
  109691. }
  109692. case SQLITE_TEXT: {
  109693. const unsigned char *z = sqlite3_value_text(argv[0]);
  109694. const unsigned char *z0;
  109695. unsigned char c;
  109696. if( z==0 ) return;
  109697. z0 = z;
  109698. while( (c = *z)!=0 ){
  109699. z++;
  109700. if( c>=0xc0 ){
  109701. while( (*z & 0xc0)==0x80 ){ z++; z0++; }
  109702. }
  109703. }
  109704. sqlite3_result_int(context, (int)(z-z0));
  109705. break;
  109706. }
  109707. default: {
  109708. sqlite3_result_null(context);
  109709. break;
  109710. }
  109711. }
  109712. }
  109713. /*
  109714. ** Implementation of the abs() function.
  109715. **
  109716. ** IMP: R-23979-26855 The abs(X) function returns the absolute value of
  109717. ** the numeric argument X.
  109718. */
  109719. static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  109720. assert( argc==1 );
  109721. UNUSED_PARAMETER(argc);
  109722. switch( sqlite3_value_type(argv[0]) ){
  109723. case SQLITE_INTEGER: {
  109724. i64 iVal = sqlite3_value_int64(argv[0]);
  109725. if( iVal<0 ){
  109726. if( iVal==SMALLEST_INT64 ){
  109727. /* IMP: R-31676-45509 If X is the integer -9223372036854775808
  109728. ** then abs(X) throws an integer overflow error since there is no
  109729. ** equivalent positive 64-bit two complement value. */
  109730. sqlite3_result_error(context, "integer overflow", -1);
  109731. return;
  109732. }
  109733. iVal = -iVal;
  109734. }
  109735. sqlite3_result_int64(context, iVal);
  109736. break;
  109737. }
  109738. case SQLITE_NULL: {
  109739. /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */
  109740. sqlite3_result_null(context);
  109741. break;
  109742. }
  109743. default: {
  109744. /* Because sqlite3_value_double() returns 0.0 if the argument is not
  109745. ** something that can be converted into a number, we have:
  109746. ** IMP: R-01992-00519 Abs(X) returns 0.0 if X is a string or blob
  109747. ** that cannot be converted to a numeric value.
  109748. */
  109749. double rVal = sqlite3_value_double(argv[0]);
  109750. if( rVal<0 ) rVal = -rVal;
  109751. sqlite3_result_double(context, rVal);
  109752. break;
  109753. }
  109754. }
  109755. }
  109756. /*
  109757. ** Implementation of the instr() function.
  109758. **
  109759. ** instr(haystack,needle) finds the first occurrence of needle
  109760. ** in haystack and returns the number of previous characters plus 1,
  109761. ** or 0 if needle does not occur within haystack.
  109762. **
  109763. ** If both haystack and needle are BLOBs, then the result is one more than
  109764. ** the number of bytes in haystack prior to the first occurrence of needle,
  109765. ** or 0 if needle never occurs in haystack.
  109766. */
  109767. static void instrFunc(
  109768. sqlite3_context *context,
  109769. int argc,
  109770. sqlite3_value **argv
  109771. ){
  109772. const unsigned char *zHaystack;
  109773. const unsigned char *zNeedle;
  109774. int nHaystack;
  109775. int nNeedle;
  109776. int typeHaystack, typeNeedle;
  109777. int N = 1;
  109778. int isText;
  109779. unsigned char firstChar;
  109780. sqlite3_value *pC1 = 0;
  109781. sqlite3_value *pC2 = 0;
  109782. UNUSED_PARAMETER(argc);
  109783. typeHaystack = sqlite3_value_type(argv[0]);
  109784. typeNeedle = sqlite3_value_type(argv[1]);
  109785. if( typeHaystack==SQLITE_NULL || typeNeedle==SQLITE_NULL ) return;
  109786. nHaystack = sqlite3_value_bytes(argv[0]);
  109787. nNeedle = sqlite3_value_bytes(argv[1]);
  109788. if( nNeedle>0 ){
  109789. if( typeHaystack==SQLITE_BLOB && typeNeedle==SQLITE_BLOB ){
  109790. zHaystack = sqlite3_value_blob(argv[0]);
  109791. zNeedle = sqlite3_value_blob(argv[1]);
  109792. isText = 0;
  109793. }else if( typeHaystack!=SQLITE_BLOB && typeNeedle!=SQLITE_BLOB ){
  109794. zHaystack = sqlite3_value_text(argv[0]);
  109795. zNeedle = sqlite3_value_text(argv[1]);
  109796. isText = 1;
  109797. }else{
  109798. pC1 = sqlite3_value_dup(argv[0]);
  109799. zHaystack = sqlite3_value_text(pC1);
  109800. if( zHaystack==0 ) goto endInstrOOM;
  109801. nHaystack = sqlite3_value_bytes(pC1);
  109802. pC2 = sqlite3_value_dup(argv[1]);
  109803. zNeedle = sqlite3_value_text(pC2);
  109804. if( zNeedle==0 ) goto endInstrOOM;
  109805. nNeedle = sqlite3_value_bytes(pC2);
  109806. isText = 1;
  109807. }
  109808. if( zNeedle==0 || (nHaystack && zHaystack==0) ) goto endInstrOOM;
  109809. firstChar = zNeedle[0];
  109810. while( nNeedle<=nHaystack
  109811. && (zHaystack[0]!=firstChar || memcmp(zHaystack, zNeedle, nNeedle)!=0)
  109812. ){
  109813. N++;
  109814. do{
  109815. nHaystack--;
  109816. zHaystack++;
  109817. }while( isText && (zHaystack[0]&0xc0)==0x80 );
  109818. }
  109819. if( nNeedle>nHaystack ) N = 0;
  109820. }
  109821. sqlite3_result_int(context, N);
  109822. endInstr:
  109823. sqlite3_value_free(pC1);
  109824. sqlite3_value_free(pC2);
  109825. return;
  109826. endInstrOOM:
  109827. sqlite3_result_error_nomem(context);
  109828. goto endInstr;
  109829. }
  109830. /*
  109831. ** Implementation of the printf() function.
  109832. */
  109833. static void printfFunc(
  109834. sqlite3_context *context,
  109835. int argc,
  109836. sqlite3_value **argv
  109837. ){
  109838. PrintfArguments x;
  109839. StrAccum str;
  109840. const char *zFormat;
  109841. int n;
  109842. sqlite3 *db = sqlite3_context_db_handle(context);
  109843. if( argc>=1 && (zFormat = (const char*)sqlite3_value_text(argv[0]))!=0 ){
  109844. x.nArg = argc-1;
  109845. x.nUsed = 0;
  109846. x.apArg = argv+1;
  109847. sqlite3StrAccumInit(&str, db, 0, 0, db->aLimit[SQLITE_LIMIT_LENGTH]);
  109848. str.printfFlags = SQLITE_PRINTF_SQLFUNC;
  109849. sqlite3_str_appendf(&str, zFormat, &x);
  109850. n = str.nChar;
  109851. sqlite3_result_text(context, sqlite3StrAccumFinish(&str), n,
  109852. SQLITE_DYNAMIC);
  109853. }
  109854. }
  109855. /*
  109856. ** Implementation of the substr() function.
  109857. **
  109858. ** substr(x,p1,p2) returns p2 characters of x[] beginning with p1.
  109859. ** p1 is 1-indexed. So substr(x,1,1) returns the first character
  109860. ** of x. If x is text, then we actually count UTF-8 characters.
  109861. ** If x is a blob, then we count bytes.
  109862. **
  109863. ** If p1 is negative, then we begin abs(p1) from the end of x[].
  109864. **
  109865. ** If p2 is negative, return the p2 characters preceding p1.
  109866. */
  109867. static void substrFunc(
  109868. sqlite3_context *context,
  109869. int argc,
  109870. sqlite3_value **argv
  109871. ){
  109872. const unsigned char *z;
  109873. const unsigned char *z2;
  109874. int len;
  109875. int p0type;
  109876. i64 p1, p2;
  109877. int negP2 = 0;
  109878. assert( argc==3 || argc==2 );
  109879. if( sqlite3_value_type(argv[1])==SQLITE_NULL
  109880. || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL)
  109881. ){
  109882. return;
  109883. }
  109884. p0type = sqlite3_value_type(argv[0]);
  109885. p1 = sqlite3_value_int(argv[1]);
  109886. if( p0type==SQLITE_BLOB ){
  109887. len = sqlite3_value_bytes(argv[0]);
  109888. z = sqlite3_value_blob(argv[0]);
  109889. if( z==0 ) return;
  109890. assert( len==sqlite3_value_bytes(argv[0]) );
  109891. }else{
  109892. z = sqlite3_value_text(argv[0]);
  109893. if( z==0 ) return;
  109894. len = 0;
  109895. if( p1<0 ){
  109896. for(z2=z; *z2; len++){
  109897. SQLITE_SKIP_UTF8(z2);
  109898. }
  109899. }
  109900. }
  109901. #ifdef SQLITE_SUBSTR_COMPATIBILITY
  109902. /* If SUBSTR_COMPATIBILITY is defined then substr(X,0,N) work the same as
  109903. ** as substr(X,1,N) - it returns the first N characters of X. This
  109904. ** is essentially a back-out of the bug-fix in check-in [5fc125d362df4b8]
  109905. ** from 2009-02-02 for compatibility of applications that exploited the
  109906. ** old buggy behavior. */
  109907. if( p1==0 ) p1 = 1; /* <rdar://problem/6778339> */
  109908. #endif
  109909. if( argc==3 ){
  109910. p2 = sqlite3_value_int(argv[2]);
  109911. if( p2<0 ){
  109912. p2 = -p2;
  109913. negP2 = 1;
  109914. }
  109915. }else{
  109916. p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
  109917. }
  109918. if( p1<0 ){
  109919. p1 += len;
  109920. if( p1<0 ){
  109921. p2 += p1;
  109922. if( p2<0 ) p2 = 0;
  109923. p1 = 0;
  109924. }
  109925. }else if( p1>0 ){
  109926. p1--;
  109927. }else if( p2>0 ){
  109928. p2--;
  109929. }
  109930. if( negP2 ){
  109931. p1 -= p2;
  109932. if( p1<0 ){
  109933. p2 += p1;
  109934. p1 = 0;
  109935. }
  109936. }
  109937. assert( p1>=0 && p2>=0 );
  109938. if( p0type!=SQLITE_BLOB ){
  109939. while( *z && p1 ){
  109940. SQLITE_SKIP_UTF8(z);
  109941. p1--;
  109942. }
  109943. for(z2=z; *z2 && p2; p2--){
  109944. SQLITE_SKIP_UTF8(z2);
  109945. }
  109946. sqlite3_result_text64(context, (char*)z, z2-z, SQLITE_TRANSIENT,
  109947. SQLITE_UTF8);
  109948. }else{
  109949. if( p1+p2>len ){
  109950. p2 = len-p1;
  109951. if( p2<0 ) p2 = 0;
  109952. }
  109953. sqlite3_result_blob64(context, (char*)&z[p1], (u64)p2, SQLITE_TRANSIENT);
  109954. }
  109955. }
  109956. /*
  109957. ** Implementation of the round() function
  109958. */
  109959. #ifndef SQLITE_OMIT_FLOATING_POINT
  109960. static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  109961. int n = 0;
  109962. double r;
  109963. char *zBuf;
  109964. assert( argc==1 || argc==2 );
  109965. if( argc==2 ){
  109966. if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
  109967. n = sqlite3_value_int(argv[1]);
  109968. if( n>30 ) n = 30;
  109969. if( n<0 ) n = 0;
  109970. }
  109971. if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  109972. r = sqlite3_value_double(argv[0]);
  109973. /* If Y==0 and X will fit in a 64-bit int,
  109974. ** handle the rounding directly,
  109975. ** otherwise use printf.
  109976. */
  109977. if( r<-4503599627370496.0 || r>+4503599627370496.0 ){
  109978. /* The value has no fractional part so there is nothing to round */
  109979. }else if( n==0 ){
  109980. r = (double)((sqlite_int64)(r+(r<0?-0.5:+0.5)));
  109981. }else{
  109982. zBuf = sqlite3_mprintf("%.*f",n,r);
  109983. if( zBuf==0 ){
  109984. sqlite3_result_error_nomem(context);
  109985. return;
  109986. }
  109987. sqlite3AtoF(zBuf, &r, sqlite3Strlen30(zBuf), SQLITE_UTF8);
  109988. sqlite3_free(zBuf);
  109989. }
  109990. sqlite3_result_double(context, r);
  109991. }
  109992. #endif
  109993. /*
  109994. ** Allocate nByte bytes of space using sqlite3Malloc(). If the
  109995. ** allocation fails, call sqlite3_result_error_nomem() to notify
  109996. ** the database handle that malloc() has failed and return NULL.
  109997. ** If nByte is larger than the maximum string or blob length, then
  109998. ** raise an SQLITE_TOOBIG exception and return NULL.
  109999. */
  110000. static void *contextMalloc(sqlite3_context *context, i64 nByte){
  110001. char *z;
  110002. sqlite3 *db = sqlite3_context_db_handle(context);
  110003. assert( nByte>0 );
  110004. testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );
  110005. testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
  110006. if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  110007. sqlite3_result_error_toobig(context);
  110008. z = 0;
  110009. }else{
  110010. z = sqlite3Malloc(nByte);
  110011. if( !z ){
  110012. sqlite3_result_error_nomem(context);
  110013. }
  110014. }
  110015. return z;
  110016. }
  110017. /*
  110018. ** Implementation of the upper() and lower() SQL functions.
  110019. */
  110020. static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  110021. char *z1;
  110022. const char *z2;
  110023. int i, n;
  110024. UNUSED_PARAMETER(argc);
  110025. z2 = (char*)sqlite3_value_text(argv[0]);
  110026. n = sqlite3_value_bytes(argv[0]);
  110027. /* Verify that the call to _bytes() does not invalidate the _text() pointer */
  110028. assert( z2==(char*)sqlite3_value_text(argv[0]) );
  110029. if( z2 ){
  110030. z1 = contextMalloc(context, ((i64)n)+1);
  110031. if( z1 ){
  110032. for(i=0; i<n; i++){
  110033. z1[i] = (char)sqlite3Toupper(z2[i]);
  110034. }
  110035. sqlite3_result_text(context, z1, n, sqlite3_free);
  110036. }
  110037. }
  110038. }
  110039. static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  110040. char *z1;
  110041. const char *z2;
  110042. int i, n;
  110043. UNUSED_PARAMETER(argc);
  110044. z2 = (char*)sqlite3_value_text(argv[0]);
  110045. n = sqlite3_value_bytes(argv[0]);
  110046. /* Verify that the call to _bytes() does not invalidate the _text() pointer */
  110047. assert( z2==(char*)sqlite3_value_text(argv[0]) );
  110048. if( z2 ){
  110049. z1 = contextMalloc(context, ((i64)n)+1);
  110050. if( z1 ){
  110051. for(i=0; i<n; i++){
  110052. z1[i] = sqlite3Tolower(z2[i]);
  110053. }
  110054. sqlite3_result_text(context, z1, n, sqlite3_free);
  110055. }
  110056. }
  110057. }
  110058. /*
  110059. ** Some functions like COALESCE() and IFNULL() and UNLIKELY() are implemented
  110060. ** as VDBE code so that unused argument values do not have to be computed.
  110061. ** However, we still need some kind of function implementation for this
  110062. ** routines in the function table. The noopFunc macro provides this.
  110063. ** noopFunc will never be called so it doesn't matter what the implementation
  110064. ** is. We might as well use the "version()" function as a substitute.
  110065. */
  110066. #define noopFunc versionFunc /* Substitute function - never called */
  110067. /*
  110068. ** Implementation of random(). Return a random integer.
  110069. */
  110070. static void randomFunc(
  110071. sqlite3_context *context,
  110072. int NotUsed,
  110073. sqlite3_value **NotUsed2
  110074. ){
  110075. sqlite_int64 r;
  110076. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  110077. sqlite3_randomness(sizeof(r), &r);
  110078. if( r<0 ){
  110079. /* We need to prevent a random number of 0x8000000000000000
  110080. ** (or -9223372036854775808) since when you do abs() of that
  110081. ** number of you get the same value back again. To do this
  110082. ** in a way that is testable, mask the sign bit off of negative
  110083. ** values, resulting in a positive value. Then take the
  110084. ** 2s complement of that positive value. The end result can
  110085. ** therefore be no less than -9223372036854775807.
  110086. */
  110087. r = -(r & LARGEST_INT64);
  110088. }
  110089. sqlite3_result_int64(context, r);
  110090. }
  110091. /*
  110092. ** Implementation of randomblob(N). Return a random blob
  110093. ** that is N bytes long.
  110094. */
  110095. static void randomBlob(
  110096. sqlite3_context *context,
  110097. int argc,
  110098. sqlite3_value **argv
  110099. ){
  110100. sqlite3_int64 n;
  110101. unsigned char *p;
  110102. assert( argc==1 );
  110103. UNUSED_PARAMETER(argc);
  110104. n = sqlite3_value_int64(argv[0]);
  110105. if( n<1 ){
  110106. n = 1;
  110107. }
  110108. p = contextMalloc(context, n);
  110109. if( p ){
  110110. sqlite3_randomness(n, p);
  110111. sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
  110112. }
  110113. }
  110114. /*
  110115. ** Implementation of the last_insert_rowid() SQL function. The return
  110116. ** value is the same as the sqlite3_last_insert_rowid() API function.
  110117. */
  110118. static void last_insert_rowid(
  110119. sqlite3_context *context,
  110120. int NotUsed,
  110121. sqlite3_value **NotUsed2
  110122. ){
  110123. sqlite3 *db = sqlite3_context_db_handle(context);
  110124. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  110125. /* IMP: R-51513-12026 The last_insert_rowid() SQL function is a
  110126. ** wrapper around the sqlite3_last_insert_rowid() C/C++ interface
  110127. ** function. */
  110128. sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
  110129. }
  110130. /*
  110131. ** Implementation of the changes() SQL function.
  110132. **
  110133. ** IMP: R-62073-11209 The changes() SQL function is a wrapper
  110134. ** around the sqlite3_changes() C/C++ function and hence follows the same
  110135. ** rules for counting changes.
  110136. */
  110137. static void changes(
  110138. sqlite3_context *context,
  110139. int NotUsed,
  110140. sqlite3_value **NotUsed2
  110141. ){
  110142. sqlite3 *db = sqlite3_context_db_handle(context);
  110143. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  110144. sqlite3_result_int(context, sqlite3_changes(db));
  110145. }
  110146. /*
  110147. ** Implementation of the total_changes() SQL function. The return value is
  110148. ** the same as the sqlite3_total_changes() API function.
  110149. */
  110150. static void total_changes(
  110151. sqlite3_context *context,
  110152. int NotUsed,
  110153. sqlite3_value **NotUsed2
  110154. ){
  110155. sqlite3 *db = sqlite3_context_db_handle(context);
  110156. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  110157. /* IMP: R-52756-41993 This function is a wrapper around the
  110158. ** sqlite3_total_changes() C/C++ interface. */
  110159. sqlite3_result_int(context, sqlite3_total_changes(db));
  110160. }
  110161. /*
  110162. ** A structure defining how to do GLOB-style comparisons.
  110163. */
  110164. struct compareInfo {
  110165. u8 matchAll; /* "*" or "%" */
  110166. u8 matchOne; /* "?" or "_" */
  110167. u8 matchSet; /* "[" or 0 */
  110168. u8 noCase; /* true to ignore case differences */
  110169. };
  110170. /*
  110171. ** For LIKE and GLOB matching on EBCDIC machines, assume that every
  110172. ** character is exactly one byte in size. Also, provde the Utf8Read()
  110173. ** macro for fast reading of the next character in the common case where
  110174. ** the next character is ASCII.
  110175. */
  110176. #if defined(SQLITE_EBCDIC)
  110177. # define sqlite3Utf8Read(A) (*((*A)++))
  110178. # define Utf8Read(A) (*(A++))
  110179. #else
  110180. # define Utf8Read(A) (A[0]<0x80?*(A++):sqlite3Utf8Read(&A))
  110181. #endif
  110182. static const struct compareInfo globInfo = { '*', '?', '[', 0 };
  110183. /* The correct SQL-92 behavior is for the LIKE operator to ignore
  110184. ** case. Thus 'a' LIKE 'A' would be true. */
  110185. static const struct compareInfo likeInfoNorm = { '%', '_', 0, 1 };
  110186. /* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
  110187. ** is case sensitive causing 'a' LIKE 'A' to be false */
  110188. static const struct compareInfo likeInfoAlt = { '%', '_', 0, 0 };
  110189. /*
  110190. ** Possible error returns from patternMatch()
  110191. */
  110192. #define SQLITE_MATCH 0
  110193. #define SQLITE_NOMATCH 1
  110194. #define SQLITE_NOWILDCARDMATCH 2
  110195. /*
  110196. ** Compare two UTF-8 strings for equality where the first string is
  110197. ** a GLOB or LIKE expression. Return values:
  110198. **
  110199. ** SQLITE_MATCH: Match
  110200. ** SQLITE_NOMATCH: No match
  110201. ** SQLITE_NOWILDCARDMATCH: No match in spite of having * or % wildcards.
  110202. **
  110203. ** Globbing rules:
  110204. **
  110205. ** '*' Matches any sequence of zero or more characters.
  110206. **
  110207. ** '?' Matches exactly one character.
  110208. **
  110209. ** [...] Matches one character from the enclosed list of
  110210. ** characters.
  110211. **
  110212. ** [^...] Matches one character not in the enclosed list.
  110213. **
  110214. ** With the [...] and [^...] matching, a ']' character can be included
  110215. ** in the list by making it the first character after '[' or '^'. A
  110216. ** range of characters can be specified using '-'. Example:
  110217. ** "[a-z]" matches any single lower-case letter. To match a '-', make
  110218. ** it the last character in the list.
  110219. **
  110220. ** Like matching rules:
  110221. **
  110222. ** '%' Matches any sequence of zero or more characters
  110223. **
  110224. *** '_' Matches any one character
  110225. **
  110226. ** Ec Where E is the "esc" character and c is any other
  110227. ** character, including '%', '_', and esc, match exactly c.
  110228. **
  110229. ** The comments within this routine usually assume glob matching.
  110230. **
  110231. ** This routine is usually quick, but can be N**2 in the worst case.
  110232. */
  110233. static int patternCompare(
  110234. const u8 *zPattern, /* The glob pattern */
  110235. const u8 *zString, /* The string to compare against the glob */
  110236. const struct compareInfo *pInfo, /* Information about how to do the compare */
  110237. u32 matchOther /* The escape char (LIKE) or '[' (GLOB) */
  110238. ){
  110239. u32 c, c2; /* Next pattern and input string chars */
  110240. u32 matchOne = pInfo->matchOne; /* "?" or "_" */
  110241. u32 matchAll = pInfo->matchAll; /* "*" or "%" */
  110242. u8 noCase = pInfo->noCase; /* True if uppercase==lowercase */
  110243. const u8 *zEscaped = 0; /* One past the last escaped input char */
  110244. while( (c = Utf8Read(zPattern))!=0 ){
  110245. if( c==matchAll ){ /* Match "*" */
  110246. /* Skip over multiple "*" characters in the pattern. If there
  110247. ** are also "?" characters, skip those as well, but consume a
  110248. ** single character of the input string for each "?" skipped */
  110249. while( (c=Utf8Read(zPattern)) == matchAll || c == matchOne ){
  110250. if( c==matchOne && sqlite3Utf8Read(&zString)==0 ){
  110251. return SQLITE_NOWILDCARDMATCH;
  110252. }
  110253. }
  110254. if( c==0 ){
  110255. return SQLITE_MATCH; /* "*" at the end of the pattern matches */
  110256. }else if( c==matchOther ){
  110257. if( pInfo->matchSet==0 ){
  110258. c = sqlite3Utf8Read(&zPattern);
  110259. if( c==0 ) return SQLITE_NOWILDCARDMATCH;
  110260. }else{
  110261. /* "[...]" immediately follows the "*". We have to do a slow
  110262. ** recursive search in this case, but it is an unusual case. */
  110263. assert( matchOther<0x80 ); /* '[' is a single-byte character */
  110264. while( *zString ){
  110265. int bMatch = patternCompare(&zPattern[-1],zString,pInfo,matchOther);
  110266. if( bMatch!=SQLITE_NOMATCH ) return bMatch;
  110267. SQLITE_SKIP_UTF8(zString);
  110268. }
  110269. return SQLITE_NOWILDCARDMATCH;
  110270. }
  110271. }
  110272. /* At this point variable c contains the first character of the
  110273. ** pattern string past the "*". Search in the input string for the
  110274. ** first matching character and recursively continue the match from
  110275. ** that point.
  110276. **
  110277. ** For a case-insensitive search, set variable cx to be the same as
  110278. ** c but in the other case and search the input string for either
  110279. ** c or cx.
  110280. */
  110281. if( c<=0x80 ){
  110282. char zStop[3];
  110283. int bMatch;
  110284. if( noCase ){
  110285. zStop[0] = sqlite3Toupper(c);
  110286. zStop[1] = sqlite3Tolower(c);
  110287. zStop[2] = 0;
  110288. }else{
  110289. zStop[0] = c;
  110290. zStop[1] = 0;
  110291. }
  110292. while(1){
  110293. zString += strcspn((const char*)zString, zStop);
  110294. if( zString[0]==0 ) break;
  110295. zString++;
  110296. bMatch = patternCompare(zPattern,zString,pInfo,matchOther);
  110297. if( bMatch!=SQLITE_NOMATCH ) return bMatch;
  110298. }
  110299. }else{
  110300. int bMatch;
  110301. while( (c2 = Utf8Read(zString))!=0 ){
  110302. if( c2!=c ) continue;
  110303. bMatch = patternCompare(zPattern,zString,pInfo,matchOther);
  110304. if( bMatch!=SQLITE_NOMATCH ) return bMatch;
  110305. }
  110306. }
  110307. return SQLITE_NOWILDCARDMATCH;
  110308. }
  110309. if( c==matchOther ){
  110310. if( pInfo->matchSet==0 ){
  110311. c = sqlite3Utf8Read(&zPattern);
  110312. if( c==0 ) return SQLITE_NOMATCH;
  110313. zEscaped = zPattern;
  110314. }else{
  110315. u32 prior_c = 0;
  110316. int seen = 0;
  110317. int invert = 0;
  110318. c = sqlite3Utf8Read(&zString);
  110319. if( c==0 ) return SQLITE_NOMATCH;
  110320. c2 = sqlite3Utf8Read(&zPattern);
  110321. if( c2=='^' ){
  110322. invert = 1;
  110323. c2 = sqlite3Utf8Read(&zPattern);
  110324. }
  110325. if( c2==']' ){
  110326. if( c==']' ) seen = 1;
  110327. c2 = sqlite3Utf8Read(&zPattern);
  110328. }
  110329. while( c2 && c2!=']' ){
  110330. if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
  110331. c2 = sqlite3Utf8Read(&zPattern);
  110332. if( c>=prior_c && c<=c2 ) seen = 1;
  110333. prior_c = 0;
  110334. }else{
  110335. if( c==c2 ){
  110336. seen = 1;
  110337. }
  110338. prior_c = c2;
  110339. }
  110340. c2 = sqlite3Utf8Read(&zPattern);
  110341. }
  110342. if( c2==0 || (seen ^ invert)==0 ){
  110343. return SQLITE_NOMATCH;
  110344. }
  110345. continue;
  110346. }
  110347. }
  110348. c2 = Utf8Read(zString);
  110349. if( c==c2 ) continue;
  110350. if( noCase && sqlite3Tolower(c)==sqlite3Tolower(c2) && c<0x80 && c2<0x80 ){
  110351. continue;
  110352. }
  110353. if( c==matchOne && zPattern!=zEscaped && c2!=0 ) continue;
  110354. return SQLITE_NOMATCH;
  110355. }
  110356. return *zString==0 ? SQLITE_MATCH : SQLITE_NOMATCH;
  110357. }
  110358. /*
  110359. ** The sqlite3_strglob() interface. Return 0 on a match (like strcmp()) and
  110360. ** non-zero if there is no match.
  110361. */
  110362. SQLITE_API int sqlite3_strglob(const char *zGlobPattern, const char *zString){
  110363. return patternCompare((u8*)zGlobPattern, (u8*)zString, &globInfo, '[');
  110364. }
  110365. /*
  110366. ** The sqlite3_strlike() interface. Return 0 on a match and non-zero for
  110367. ** a miss - like strcmp().
  110368. */
  110369. SQLITE_API int sqlite3_strlike(const char *zPattern, const char *zStr, unsigned int esc){
  110370. return patternCompare((u8*)zPattern, (u8*)zStr, &likeInfoNorm, esc);
  110371. }
  110372. /*
  110373. ** Count the number of times that the LIKE operator (or GLOB which is
  110374. ** just a variation of LIKE) gets called. This is used for testing
  110375. ** only.
  110376. */
  110377. #ifdef SQLITE_TEST
  110378. SQLITE_API int sqlite3_like_count = 0;
  110379. #endif
  110380. /*
  110381. ** Implementation of the like() SQL function. This function implements
  110382. ** the build-in LIKE operator. The first argument to the function is the
  110383. ** pattern and the second argument is the string. So, the SQL statements:
  110384. **
  110385. ** A LIKE B
  110386. **
  110387. ** is implemented as like(B,A).
  110388. **
  110389. ** This same function (with a different compareInfo structure) computes
  110390. ** the GLOB operator.
  110391. */
  110392. static void likeFunc(
  110393. sqlite3_context *context,
  110394. int argc,
  110395. sqlite3_value **argv
  110396. ){
  110397. const unsigned char *zA, *zB;
  110398. u32 escape;
  110399. int nPat;
  110400. sqlite3 *db = sqlite3_context_db_handle(context);
  110401. struct compareInfo *pInfo = sqlite3_user_data(context);
  110402. struct compareInfo backupInfo;
  110403. #ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS
  110404. if( sqlite3_value_type(argv[0])==SQLITE_BLOB
  110405. || sqlite3_value_type(argv[1])==SQLITE_BLOB
  110406. ){
  110407. #ifdef SQLITE_TEST
  110408. sqlite3_like_count++;
  110409. #endif
  110410. sqlite3_result_int(context, 0);
  110411. return;
  110412. }
  110413. #endif
  110414. /* Limit the length of the LIKE or GLOB pattern to avoid problems
  110415. ** of deep recursion and N*N behavior in patternCompare().
  110416. */
  110417. nPat = sqlite3_value_bytes(argv[0]);
  110418. testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] );
  110419. testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 );
  110420. if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
  110421. sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
  110422. return;
  110423. }
  110424. if( argc==3 ){
  110425. /* The escape character string must consist of a single UTF-8 character.
  110426. ** Otherwise, return an error.
  110427. */
  110428. const unsigned char *zEsc = sqlite3_value_text(argv[2]);
  110429. if( zEsc==0 ) return;
  110430. if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
  110431. sqlite3_result_error(context,
  110432. "ESCAPE expression must be a single character", -1);
  110433. return;
  110434. }
  110435. escape = sqlite3Utf8Read(&zEsc);
  110436. if( escape==pInfo->matchAll || escape==pInfo->matchOne ){
  110437. memcpy(&backupInfo, pInfo, sizeof(backupInfo));
  110438. pInfo = &backupInfo;
  110439. if( escape==pInfo->matchAll ) pInfo->matchAll = 0;
  110440. if( escape==pInfo->matchOne ) pInfo->matchOne = 0;
  110441. }
  110442. }else{
  110443. escape = pInfo->matchSet;
  110444. }
  110445. zB = sqlite3_value_text(argv[0]);
  110446. zA = sqlite3_value_text(argv[1]);
  110447. if( zA && zB ){
  110448. #ifdef SQLITE_TEST
  110449. sqlite3_like_count++;
  110450. #endif
  110451. sqlite3_result_int(context,
  110452. patternCompare(zB, zA, pInfo, escape)==SQLITE_MATCH);
  110453. }
  110454. }
  110455. /*
  110456. ** Implementation of the NULLIF(x,y) function. The result is the first
  110457. ** argument if the arguments are different. The result is NULL if the
  110458. ** arguments are equal to each other.
  110459. */
  110460. static void nullifFunc(
  110461. sqlite3_context *context,
  110462. int NotUsed,
  110463. sqlite3_value **argv
  110464. ){
  110465. CollSeq *pColl = sqlite3GetFuncCollSeq(context);
  110466. UNUSED_PARAMETER(NotUsed);
  110467. if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
  110468. sqlite3_result_value(context, argv[0]);
  110469. }
  110470. }
  110471. /*
  110472. ** Implementation of the sqlite_version() function. The result is the version
  110473. ** of the SQLite library that is running.
  110474. */
  110475. static void versionFunc(
  110476. sqlite3_context *context,
  110477. int NotUsed,
  110478. sqlite3_value **NotUsed2
  110479. ){
  110480. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  110481. /* IMP: R-48699-48617 This function is an SQL wrapper around the
  110482. ** sqlite3_libversion() C-interface. */
  110483. sqlite3_result_text(context, sqlite3_libversion(), -1, SQLITE_STATIC);
  110484. }
  110485. /*
  110486. ** Implementation of the sqlite_source_id() function. The result is a string
  110487. ** that identifies the particular version of the source code used to build
  110488. ** SQLite.
  110489. */
  110490. static void sourceidFunc(
  110491. sqlite3_context *context,
  110492. int NotUsed,
  110493. sqlite3_value **NotUsed2
  110494. ){
  110495. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  110496. /* IMP: R-24470-31136 This function is an SQL wrapper around the
  110497. ** sqlite3_sourceid() C interface. */
  110498. sqlite3_result_text(context, sqlite3_sourceid(), -1, SQLITE_STATIC);
  110499. }
  110500. /*
  110501. ** Implementation of the sqlite_log() function. This is a wrapper around
  110502. ** sqlite3_log(). The return value is NULL. The function exists purely for
  110503. ** its side-effects.
  110504. */
  110505. static void errlogFunc(
  110506. sqlite3_context *context,
  110507. int argc,
  110508. sqlite3_value **argv
  110509. ){
  110510. UNUSED_PARAMETER(argc);
  110511. UNUSED_PARAMETER(context);
  110512. sqlite3_log(sqlite3_value_int(argv[0]), "%s", sqlite3_value_text(argv[1]));
  110513. }
  110514. /*
  110515. ** Implementation of the sqlite_compileoption_used() function.
  110516. ** The result is an integer that identifies if the compiler option
  110517. ** was used to build SQLite.
  110518. */
  110519. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  110520. static void compileoptionusedFunc(
  110521. sqlite3_context *context,
  110522. int argc,
  110523. sqlite3_value **argv
  110524. ){
  110525. const char *zOptName;
  110526. assert( argc==1 );
  110527. UNUSED_PARAMETER(argc);
  110528. /* IMP: R-39564-36305 The sqlite_compileoption_used() SQL
  110529. ** function is a wrapper around the sqlite3_compileoption_used() C/C++
  110530. ** function.
  110531. */
  110532. if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){
  110533. sqlite3_result_int(context, sqlite3_compileoption_used(zOptName));
  110534. }
  110535. }
  110536. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  110537. /*
  110538. ** Implementation of the sqlite_compileoption_get() function.
  110539. ** The result is a string that identifies the compiler options
  110540. ** used to build SQLite.
  110541. */
  110542. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  110543. static void compileoptiongetFunc(
  110544. sqlite3_context *context,
  110545. int argc,
  110546. sqlite3_value **argv
  110547. ){
  110548. int n;
  110549. assert( argc==1 );
  110550. UNUSED_PARAMETER(argc);
  110551. /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function
  110552. ** is a wrapper around the sqlite3_compileoption_get() C/C++ function.
  110553. */
  110554. n = sqlite3_value_int(argv[0]);
  110555. sqlite3_result_text(context, sqlite3_compileoption_get(n), -1, SQLITE_STATIC);
  110556. }
  110557. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  110558. /* Array for converting from half-bytes (nybbles) into ASCII hex
  110559. ** digits. */
  110560. static const char hexdigits[] = {
  110561. '0', '1', '2', '3', '4', '5', '6', '7',
  110562. '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
  110563. };
  110564. /*
  110565. ** Implementation of the QUOTE() function. This function takes a single
  110566. ** argument. If the argument is numeric, the return value is the same as
  110567. ** the argument. If the argument is NULL, the return value is the string
  110568. ** "NULL". Otherwise, the argument is enclosed in single quotes with
  110569. ** single-quote escapes.
  110570. */
  110571. static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  110572. assert( argc==1 );
  110573. UNUSED_PARAMETER(argc);
  110574. switch( sqlite3_value_type(argv[0]) ){
  110575. case SQLITE_FLOAT: {
  110576. double r1, r2;
  110577. char zBuf[50];
  110578. r1 = sqlite3_value_double(argv[0]);
  110579. sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.15g", r1);
  110580. sqlite3AtoF(zBuf, &r2, 20, SQLITE_UTF8);
  110581. if( r1!=r2 ){
  110582. sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.20e", r1);
  110583. }
  110584. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  110585. break;
  110586. }
  110587. case SQLITE_INTEGER: {
  110588. sqlite3_result_value(context, argv[0]);
  110589. break;
  110590. }
  110591. case SQLITE_BLOB: {
  110592. char *zText = 0;
  110593. char const *zBlob = sqlite3_value_blob(argv[0]);
  110594. int nBlob = sqlite3_value_bytes(argv[0]);
  110595. assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
  110596. zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4);
  110597. if( zText ){
  110598. int i;
  110599. for(i=0; i<nBlob; i++){
  110600. zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
  110601. zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
  110602. }
  110603. zText[(nBlob*2)+2] = '\'';
  110604. zText[(nBlob*2)+3] = '\0';
  110605. zText[0] = 'X';
  110606. zText[1] = '\'';
  110607. sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
  110608. sqlite3_free(zText);
  110609. }
  110610. break;
  110611. }
  110612. case SQLITE_TEXT: {
  110613. int i,j;
  110614. u64 n;
  110615. const unsigned char *zArg = sqlite3_value_text(argv[0]);
  110616. char *z;
  110617. if( zArg==0 ) return;
  110618. for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
  110619. z = contextMalloc(context, ((i64)i)+((i64)n)+3);
  110620. if( z ){
  110621. z[0] = '\'';
  110622. for(i=0, j=1; zArg[i]; i++){
  110623. z[j++] = zArg[i];
  110624. if( zArg[i]=='\'' ){
  110625. z[j++] = '\'';
  110626. }
  110627. }
  110628. z[j++] = '\'';
  110629. z[j] = 0;
  110630. sqlite3_result_text(context, z, j, sqlite3_free);
  110631. }
  110632. break;
  110633. }
  110634. default: {
  110635. assert( sqlite3_value_type(argv[0])==SQLITE_NULL );
  110636. sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
  110637. break;
  110638. }
  110639. }
  110640. }
  110641. /*
  110642. ** The unicode() function. Return the integer unicode code-point value
  110643. ** for the first character of the input string.
  110644. */
  110645. static void unicodeFunc(
  110646. sqlite3_context *context,
  110647. int argc,
  110648. sqlite3_value **argv
  110649. ){
  110650. const unsigned char *z = sqlite3_value_text(argv[0]);
  110651. (void)argc;
  110652. if( z && z[0] ) sqlite3_result_int(context, sqlite3Utf8Read(&z));
  110653. }
  110654. /*
  110655. ** The char() function takes zero or more arguments, each of which is
  110656. ** an integer. It constructs a string where each character of the string
  110657. ** is the unicode character for the corresponding integer argument.
  110658. */
  110659. static void charFunc(
  110660. sqlite3_context *context,
  110661. int argc,
  110662. sqlite3_value **argv
  110663. ){
  110664. unsigned char *z, *zOut;
  110665. int i;
  110666. zOut = z = sqlite3_malloc64( argc*4+1 );
  110667. if( z==0 ){
  110668. sqlite3_result_error_nomem(context);
  110669. return;
  110670. }
  110671. for(i=0; i<argc; i++){
  110672. sqlite3_int64 x;
  110673. unsigned c;
  110674. x = sqlite3_value_int64(argv[i]);
  110675. if( x<0 || x>0x10ffff ) x = 0xfffd;
  110676. c = (unsigned)(x & 0x1fffff);
  110677. if( c<0x00080 ){
  110678. *zOut++ = (u8)(c&0xFF);
  110679. }else if( c<0x00800 ){
  110680. *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);
  110681. *zOut++ = 0x80 + (u8)(c & 0x3F);
  110682. }else if( c<0x10000 ){
  110683. *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);
  110684. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
  110685. *zOut++ = 0x80 + (u8)(c & 0x3F);
  110686. }else{
  110687. *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);
  110688. *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);
  110689. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
  110690. *zOut++ = 0x80 + (u8)(c & 0x3F);
  110691. } \
  110692. }
  110693. sqlite3_result_text64(context, (char*)z, zOut-z, sqlite3_free, SQLITE_UTF8);
  110694. }
  110695. /*
  110696. ** The hex() function. Interpret the argument as a blob. Return
  110697. ** a hexadecimal rendering as text.
  110698. */
  110699. static void hexFunc(
  110700. sqlite3_context *context,
  110701. int argc,
  110702. sqlite3_value **argv
  110703. ){
  110704. int i, n;
  110705. const unsigned char *pBlob;
  110706. char *zHex, *z;
  110707. assert( argc==1 );
  110708. UNUSED_PARAMETER(argc);
  110709. pBlob = sqlite3_value_blob(argv[0]);
  110710. n = sqlite3_value_bytes(argv[0]);
  110711. assert( pBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
  110712. z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
  110713. if( zHex ){
  110714. for(i=0; i<n; i++, pBlob++){
  110715. unsigned char c = *pBlob;
  110716. *(z++) = hexdigits[(c>>4)&0xf];
  110717. *(z++) = hexdigits[c&0xf];
  110718. }
  110719. *z = 0;
  110720. sqlite3_result_text(context, zHex, n*2, sqlite3_free);
  110721. }
  110722. }
  110723. /*
  110724. ** The zeroblob(N) function returns a zero-filled blob of size N bytes.
  110725. */
  110726. static void zeroblobFunc(
  110727. sqlite3_context *context,
  110728. int argc,
  110729. sqlite3_value **argv
  110730. ){
  110731. i64 n;
  110732. int rc;
  110733. assert( argc==1 );
  110734. UNUSED_PARAMETER(argc);
  110735. n = sqlite3_value_int64(argv[0]);
  110736. if( n<0 ) n = 0;
  110737. rc = sqlite3_result_zeroblob64(context, n); /* IMP: R-00293-64994 */
  110738. if( rc ){
  110739. sqlite3_result_error_code(context, rc);
  110740. }
  110741. }
  110742. /*
  110743. ** The replace() function. Three arguments are all strings: call
  110744. ** them A, B, and C. The result is also a string which is derived
  110745. ** from A by replacing every occurrence of B with C. The match
  110746. ** must be exact. Collating sequences are not used.
  110747. */
  110748. static void replaceFunc(
  110749. sqlite3_context *context,
  110750. int argc,
  110751. sqlite3_value **argv
  110752. ){
  110753. const unsigned char *zStr; /* The input string A */
  110754. const unsigned char *zPattern; /* The pattern string B */
  110755. const unsigned char *zRep; /* The replacement string C */
  110756. unsigned char *zOut; /* The output */
  110757. int nStr; /* Size of zStr */
  110758. int nPattern; /* Size of zPattern */
  110759. int nRep; /* Size of zRep */
  110760. i64 nOut; /* Maximum size of zOut */
  110761. int loopLimit; /* Last zStr[] that might match zPattern[] */
  110762. int i, j; /* Loop counters */
  110763. unsigned cntExpand; /* Number zOut expansions */
  110764. sqlite3 *db = sqlite3_context_db_handle(context);
  110765. assert( argc==3 );
  110766. UNUSED_PARAMETER(argc);
  110767. zStr = sqlite3_value_text(argv[0]);
  110768. if( zStr==0 ) return;
  110769. nStr = sqlite3_value_bytes(argv[0]);
  110770. assert( zStr==sqlite3_value_text(argv[0]) ); /* No encoding change */
  110771. zPattern = sqlite3_value_text(argv[1]);
  110772. if( zPattern==0 ){
  110773. assert( sqlite3_value_type(argv[1])==SQLITE_NULL
  110774. || sqlite3_context_db_handle(context)->mallocFailed );
  110775. return;
  110776. }
  110777. if( zPattern[0]==0 ){
  110778. assert( sqlite3_value_type(argv[1])!=SQLITE_NULL );
  110779. sqlite3_result_value(context, argv[0]);
  110780. return;
  110781. }
  110782. nPattern = sqlite3_value_bytes(argv[1]);
  110783. assert( zPattern==sqlite3_value_text(argv[1]) ); /* No encoding change */
  110784. zRep = sqlite3_value_text(argv[2]);
  110785. if( zRep==0 ) return;
  110786. nRep = sqlite3_value_bytes(argv[2]);
  110787. assert( zRep==sqlite3_value_text(argv[2]) );
  110788. nOut = nStr + 1;
  110789. assert( nOut<SQLITE_MAX_LENGTH );
  110790. zOut = contextMalloc(context, (i64)nOut);
  110791. if( zOut==0 ){
  110792. return;
  110793. }
  110794. loopLimit = nStr - nPattern;
  110795. cntExpand = 0;
  110796. for(i=j=0; i<=loopLimit; i++){
  110797. if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
  110798. zOut[j++] = zStr[i];
  110799. }else{
  110800. if( nRep>nPattern ){
  110801. nOut += nRep - nPattern;
  110802. testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] );
  110803. testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );
  110804. if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  110805. sqlite3_result_error_toobig(context);
  110806. sqlite3_free(zOut);
  110807. return;
  110808. }
  110809. cntExpand++;
  110810. if( (cntExpand&(cntExpand-1))==0 ){
  110811. /* Grow the size of the output buffer only on substitutions
  110812. ** whose index is a power of two: 1, 2, 4, 8, 16, 32, ... */
  110813. u8 *zOld;
  110814. zOld = zOut;
  110815. zOut = sqlite3Realloc(zOut, (int)nOut + (nOut - nStr - 1));
  110816. if( zOut==0 ){
  110817. sqlite3_result_error_nomem(context);
  110818. sqlite3_free(zOld);
  110819. return;
  110820. }
  110821. }
  110822. }
  110823. memcpy(&zOut[j], zRep, nRep);
  110824. j += nRep;
  110825. i += nPattern-1;
  110826. }
  110827. }
  110828. assert( j+nStr-i+1<=nOut );
  110829. memcpy(&zOut[j], &zStr[i], nStr-i);
  110830. j += nStr - i;
  110831. assert( j<=nOut );
  110832. zOut[j] = 0;
  110833. sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
  110834. }
  110835. /*
  110836. ** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
  110837. ** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
  110838. */
  110839. static void trimFunc(
  110840. sqlite3_context *context,
  110841. int argc,
  110842. sqlite3_value **argv
  110843. ){
  110844. const unsigned char *zIn; /* Input string */
  110845. const unsigned char *zCharSet; /* Set of characters to trim */
  110846. int nIn; /* Number of bytes in input */
  110847. int flags; /* 1: trimleft 2: trimright 3: trim */
  110848. int i; /* Loop counter */
  110849. unsigned char *aLen = 0; /* Length of each character in zCharSet */
  110850. unsigned char **azChar = 0; /* Individual characters in zCharSet */
  110851. int nChar; /* Number of characters in zCharSet */
  110852. if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
  110853. return;
  110854. }
  110855. zIn = sqlite3_value_text(argv[0]);
  110856. if( zIn==0 ) return;
  110857. nIn = sqlite3_value_bytes(argv[0]);
  110858. assert( zIn==sqlite3_value_text(argv[0]) );
  110859. if( argc==1 ){
  110860. static const unsigned char lenOne[] = { 1 };
  110861. static unsigned char * const azOne[] = { (u8*)" " };
  110862. nChar = 1;
  110863. aLen = (u8*)lenOne;
  110864. azChar = (unsigned char **)azOne;
  110865. zCharSet = 0;
  110866. }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
  110867. return;
  110868. }else{
  110869. const unsigned char *z;
  110870. for(z=zCharSet, nChar=0; *z; nChar++){
  110871. SQLITE_SKIP_UTF8(z);
  110872. }
  110873. if( nChar>0 ){
  110874. azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
  110875. if( azChar==0 ){
  110876. return;
  110877. }
  110878. aLen = (unsigned char*)&azChar[nChar];
  110879. for(z=zCharSet, nChar=0; *z; nChar++){
  110880. azChar[nChar] = (unsigned char *)z;
  110881. SQLITE_SKIP_UTF8(z);
  110882. aLen[nChar] = (u8)(z - azChar[nChar]);
  110883. }
  110884. }
  110885. }
  110886. if( nChar>0 ){
  110887. flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
  110888. if( flags & 1 ){
  110889. while( nIn>0 ){
  110890. int len = 0;
  110891. for(i=0; i<nChar; i++){
  110892. len = aLen[i];
  110893. if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break;
  110894. }
  110895. if( i>=nChar ) break;
  110896. zIn += len;
  110897. nIn -= len;
  110898. }
  110899. }
  110900. if( flags & 2 ){
  110901. while( nIn>0 ){
  110902. int len = 0;
  110903. for(i=0; i<nChar; i++){
  110904. len = aLen[i];
  110905. if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
  110906. }
  110907. if( i>=nChar ) break;
  110908. nIn -= len;
  110909. }
  110910. }
  110911. if( zCharSet ){
  110912. sqlite3_free(azChar);
  110913. }
  110914. }
  110915. sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
  110916. }
  110917. #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
  110918. /*
  110919. ** The "unknown" function is automatically substituted in place of
  110920. ** any unrecognized function name when doing an EXPLAIN or EXPLAIN QUERY PLAN
  110921. ** when the SQLITE_ENABLE_UNKNOWN_FUNCTION compile-time option is used.
  110922. ** When the "sqlite3" command-line shell is built using this functionality,
  110923. ** that allows an EXPLAIN or EXPLAIN QUERY PLAN for complex queries
  110924. ** involving application-defined functions to be examined in a generic
  110925. ** sqlite3 shell.
  110926. */
  110927. static void unknownFunc(
  110928. sqlite3_context *context,
  110929. int argc,
  110930. sqlite3_value **argv
  110931. ){
  110932. /* no-op */
  110933. }
  110934. #endif /*SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION*/
  110935. /* IMP: R-25361-16150 This function is omitted from SQLite by default. It
  110936. ** is only available if the SQLITE_SOUNDEX compile-time option is used
  110937. ** when SQLite is built.
  110938. */
  110939. #ifdef SQLITE_SOUNDEX
  110940. /*
  110941. ** Compute the soundex encoding of a word.
  110942. **
  110943. ** IMP: R-59782-00072 The soundex(X) function returns a string that is the
  110944. ** soundex encoding of the string X.
  110945. */
  110946. static void soundexFunc(
  110947. sqlite3_context *context,
  110948. int argc,
  110949. sqlite3_value **argv
  110950. ){
  110951. char zResult[8];
  110952. const u8 *zIn;
  110953. int i, j;
  110954. static const unsigned char iCode[] = {
  110955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  110956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  110957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  110958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  110959. 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
  110960. 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
  110961. 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
  110962. 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
  110963. };
  110964. assert( argc==1 );
  110965. zIn = (u8*)sqlite3_value_text(argv[0]);
  110966. if( zIn==0 ) zIn = (u8*)"";
  110967. for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){}
  110968. if( zIn[i] ){
  110969. u8 prevcode = iCode[zIn[i]&0x7f];
  110970. zResult[0] = sqlite3Toupper(zIn[i]);
  110971. for(j=1; j<4 && zIn[i]; i++){
  110972. int code = iCode[zIn[i]&0x7f];
  110973. if( code>0 ){
  110974. if( code!=prevcode ){
  110975. prevcode = code;
  110976. zResult[j++] = code + '0';
  110977. }
  110978. }else{
  110979. prevcode = 0;
  110980. }
  110981. }
  110982. while( j<4 ){
  110983. zResult[j++] = '0';
  110984. }
  110985. zResult[j] = 0;
  110986. sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
  110987. }else{
  110988. /* IMP: R-64894-50321 The string "?000" is returned if the argument
  110989. ** is NULL or contains no ASCII alphabetic characters. */
  110990. sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
  110991. }
  110992. }
  110993. #endif /* SQLITE_SOUNDEX */
  110994. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  110995. /*
  110996. ** A function that loads a shared-library extension then returns NULL.
  110997. */
  110998. static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
  110999. const char *zFile = (const char *)sqlite3_value_text(argv[0]);
  111000. const char *zProc;
  111001. sqlite3 *db = sqlite3_context_db_handle(context);
  111002. char *zErrMsg = 0;
  111003. /* Disallow the load_extension() SQL function unless the SQLITE_LoadExtFunc
  111004. ** flag is set. See the sqlite3_enable_load_extension() API.
  111005. */
  111006. if( (db->flags & SQLITE_LoadExtFunc)==0 ){
  111007. sqlite3_result_error(context, "not authorized", -1);
  111008. return;
  111009. }
  111010. if( argc==2 ){
  111011. zProc = (const char *)sqlite3_value_text(argv[1]);
  111012. }else{
  111013. zProc = 0;
  111014. }
  111015. if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
  111016. sqlite3_result_error(context, zErrMsg, -1);
  111017. sqlite3_free(zErrMsg);
  111018. }
  111019. }
  111020. #endif
  111021. /*
  111022. ** An instance of the following structure holds the context of a
  111023. ** sum() or avg() aggregate computation.
  111024. */
  111025. typedef struct SumCtx SumCtx;
  111026. struct SumCtx {
  111027. double rSum; /* Floating point sum */
  111028. i64 iSum; /* Integer sum */
  111029. i64 cnt; /* Number of elements summed */
  111030. u8 overflow; /* True if integer overflow seen */
  111031. u8 approx; /* True if non-integer value was input to the sum */
  111032. };
  111033. /*
  111034. ** Routines used to compute the sum, average, and total.
  111035. **
  111036. ** The SUM() function follows the (broken) SQL standard which means
  111037. ** that it returns NULL if it sums over no inputs. TOTAL returns
  111038. ** 0.0 in that case. In addition, TOTAL always returns a float where
  111039. ** SUM might return an integer if it never encounters a floating point
  111040. ** value. TOTAL never fails, but SUM might through an exception if
  111041. ** it overflows an integer.
  111042. */
  111043. static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
  111044. SumCtx *p;
  111045. int type;
  111046. assert( argc==1 );
  111047. UNUSED_PARAMETER(argc);
  111048. p = sqlite3_aggregate_context(context, sizeof(*p));
  111049. type = sqlite3_value_numeric_type(argv[0]);
  111050. if( p && type!=SQLITE_NULL ){
  111051. p->cnt++;
  111052. if( type==SQLITE_INTEGER ){
  111053. i64 v = sqlite3_value_int64(argv[0]);
  111054. p->rSum += v;
  111055. if( (p->approx|p->overflow)==0 && sqlite3AddInt64(&p->iSum, v) ){
  111056. p->approx = p->overflow = 1;
  111057. }
  111058. }else{
  111059. p->rSum += sqlite3_value_double(argv[0]);
  111060. p->approx = 1;
  111061. }
  111062. }
  111063. }
  111064. #ifndef SQLITE_OMIT_WINDOWFUNC
  111065. static void sumInverse(sqlite3_context *context, int argc, sqlite3_value**argv){
  111066. SumCtx *p;
  111067. int type;
  111068. assert( argc==1 );
  111069. UNUSED_PARAMETER(argc);
  111070. p = sqlite3_aggregate_context(context, sizeof(*p));
  111071. type = sqlite3_value_numeric_type(argv[0]);
  111072. /* p is always non-NULL because sumStep() will have been called first
  111073. ** to initialize it */
  111074. if( ALWAYS(p) && type!=SQLITE_NULL ){
  111075. assert( p->cnt>0 );
  111076. p->cnt--;
  111077. assert( type==SQLITE_INTEGER || p->approx );
  111078. if( type==SQLITE_INTEGER && p->approx==0 ){
  111079. i64 v = sqlite3_value_int64(argv[0]);
  111080. p->rSum -= v;
  111081. p->iSum -= v;
  111082. }else{
  111083. p->rSum -= sqlite3_value_double(argv[0]);
  111084. }
  111085. }
  111086. }
  111087. #else
  111088. # define sumInverse 0
  111089. #endif /* SQLITE_OMIT_WINDOWFUNC */
  111090. static void sumFinalize(sqlite3_context *context){
  111091. SumCtx *p;
  111092. p = sqlite3_aggregate_context(context, 0);
  111093. if( p && p->cnt>0 ){
  111094. if( p->overflow ){
  111095. sqlite3_result_error(context,"integer overflow",-1);
  111096. }else if( p->approx ){
  111097. sqlite3_result_double(context, p->rSum);
  111098. }else{
  111099. sqlite3_result_int64(context, p->iSum);
  111100. }
  111101. }
  111102. }
  111103. static void avgFinalize(sqlite3_context *context){
  111104. SumCtx *p;
  111105. p = sqlite3_aggregate_context(context, 0);
  111106. if( p && p->cnt>0 ){
  111107. sqlite3_result_double(context, p->rSum/(double)p->cnt);
  111108. }
  111109. }
  111110. static void totalFinalize(sqlite3_context *context){
  111111. SumCtx *p;
  111112. p = sqlite3_aggregate_context(context, 0);
  111113. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  111114. sqlite3_result_double(context, p ? p->rSum : (double)0);
  111115. }
  111116. /*
  111117. ** The following structure keeps track of state information for the
  111118. ** count() aggregate function.
  111119. */
  111120. typedef struct CountCtx CountCtx;
  111121. struct CountCtx {
  111122. i64 n;
  111123. #ifdef SQLITE_DEBUG
  111124. int bInverse; /* True if xInverse() ever called */
  111125. #endif
  111126. };
  111127. /*
  111128. ** Routines to implement the count() aggregate function.
  111129. */
  111130. static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
  111131. CountCtx *p;
  111132. p = sqlite3_aggregate_context(context, sizeof(*p));
  111133. if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
  111134. p->n++;
  111135. }
  111136. #ifndef SQLITE_OMIT_DEPRECATED
  111137. /* The sqlite3_aggregate_count() function is deprecated. But just to make
  111138. ** sure it still operates correctly, verify that its count agrees with our
  111139. ** internal count when using count(*) and when the total count can be
  111140. ** expressed as a 32-bit integer. */
  111141. assert( argc==1 || p==0 || p->n>0x7fffffff || p->bInverse
  111142. || p->n==sqlite3_aggregate_count(context) );
  111143. #endif
  111144. }
  111145. static void countFinalize(sqlite3_context *context){
  111146. CountCtx *p;
  111147. p = sqlite3_aggregate_context(context, 0);
  111148. sqlite3_result_int64(context, p ? p->n : 0);
  111149. }
  111150. #ifndef SQLITE_OMIT_WINDOWFUNC
  111151. static void countInverse(sqlite3_context *ctx, int argc, sqlite3_value **argv){
  111152. CountCtx *p;
  111153. p = sqlite3_aggregate_context(ctx, sizeof(*p));
  111154. /* p is always non-NULL since countStep() will have been called first */
  111155. if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && ALWAYS(p) ){
  111156. p->n--;
  111157. #ifdef SQLITE_DEBUG
  111158. p->bInverse = 1;
  111159. #endif
  111160. }
  111161. }
  111162. #else
  111163. # define countInverse 0
  111164. #endif /* SQLITE_OMIT_WINDOWFUNC */
  111165. /*
  111166. ** Routines to implement min() and max() aggregate functions.
  111167. */
  111168. static void minmaxStep(
  111169. sqlite3_context *context,
  111170. int NotUsed,
  111171. sqlite3_value **argv
  111172. ){
  111173. Mem *pArg = (Mem *)argv[0];
  111174. Mem *pBest;
  111175. UNUSED_PARAMETER(NotUsed);
  111176. pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
  111177. if( !pBest ) return;
  111178. if( sqlite3_value_type(pArg)==SQLITE_NULL ){
  111179. if( pBest->flags ) sqlite3SkipAccumulatorLoad(context);
  111180. }else if( pBest->flags ){
  111181. int max;
  111182. int cmp;
  111183. CollSeq *pColl = sqlite3GetFuncCollSeq(context);
  111184. /* This step function is used for both the min() and max() aggregates,
  111185. ** the only difference between the two being that the sense of the
  111186. ** comparison is inverted. For the max() aggregate, the
  111187. ** sqlite3_user_data() function returns (void *)-1. For min() it
  111188. ** returns (void *)db, where db is the sqlite3* database pointer.
  111189. ** Therefore the next statement sets variable 'max' to 1 for the max()
  111190. ** aggregate, or 0 for min().
  111191. */
  111192. max = sqlite3_user_data(context)!=0;
  111193. cmp = sqlite3MemCompare(pBest, pArg, pColl);
  111194. if( (max && cmp<0) || (!max && cmp>0) ){
  111195. sqlite3VdbeMemCopy(pBest, pArg);
  111196. }else{
  111197. sqlite3SkipAccumulatorLoad(context);
  111198. }
  111199. }else{
  111200. pBest->db = sqlite3_context_db_handle(context);
  111201. sqlite3VdbeMemCopy(pBest, pArg);
  111202. }
  111203. }
  111204. static void minMaxValueFinalize(sqlite3_context *context, int bValue){
  111205. sqlite3_value *pRes;
  111206. pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
  111207. if( pRes ){
  111208. if( pRes->flags ){
  111209. sqlite3_result_value(context, pRes);
  111210. }
  111211. if( bValue==0 ) sqlite3VdbeMemRelease(pRes);
  111212. }
  111213. }
  111214. #ifndef SQLITE_OMIT_WINDOWFUNC
  111215. static void minMaxValue(sqlite3_context *context){
  111216. minMaxValueFinalize(context, 1);
  111217. }
  111218. #else
  111219. # define minMaxValue 0
  111220. #endif /* SQLITE_OMIT_WINDOWFUNC */
  111221. static void minMaxFinalize(sqlite3_context *context){
  111222. minMaxValueFinalize(context, 0);
  111223. }
  111224. /*
  111225. ** group_concat(EXPR, ?SEPARATOR?)
  111226. */
  111227. static void groupConcatStep(
  111228. sqlite3_context *context,
  111229. int argc,
  111230. sqlite3_value **argv
  111231. ){
  111232. const char *zVal;
  111233. StrAccum *pAccum;
  111234. const char *zSep;
  111235. int nVal, nSep;
  111236. assert( argc==1 || argc==2 );
  111237. if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  111238. pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
  111239. if( pAccum ){
  111240. sqlite3 *db = sqlite3_context_db_handle(context);
  111241. int firstTerm = pAccum->mxAlloc==0;
  111242. pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
  111243. if( !firstTerm ){
  111244. if( argc==2 ){
  111245. zSep = (char*)sqlite3_value_text(argv[1]);
  111246. nSep = sqlite3_value_bytes(argv[1]);
  111247. }else{
  111248. zSep = ",";
  111249. nSep = 1;
  111250. }
  111251. if( zSep ) sqlite3_str_append(pAccum, zSep, nSep);
  111252. }
  111253. zVal = (char*)sqlite3_value_text(argv[0]);
  111254. nVal = sqlite3_value_bytes(argv[0]);
  111255. if( zVal ) sqlite3_str_append(pAccum, zVal, nVal);
  111256. }
  111257. }
  111258. #ifndef SQLITE_OMIT_WINDOWFUNC
  111259. static void groupConcatInverse(
  111260. sqlite3_context *context,
  111261. int argc,
  111262. sqlite3_value **argv
  111263. ){
  111264. int n;
  111265. StrAccum *pAccum;
  111266. assert( argc==1 || argc==2 );
  111267. if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  111268. pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
  111269. /* pAccum is always non-NULL since groupConcatStep() will have always
  111270. ** run frist to initialize it */
  111271. if( ALWAYS(pAccum) ){
  111272. n = sqlite3_value_bytes(argv[0]);
  111273. if( argc==2 ){
  111274. n += sqlite3_value_bytes(argv[1]);
  111275. }else{
  111276. n++;
  111277. }
  111278. if( n>=(int)pAccum->nChar ){
  111279. pAccum->nChar = 0;
  111280. }else{
  111281. pAccum->nChar -= n;
  111282. memmove(pAccum->zText, &pAccum->zText[n], pAccum->nChar);
  111283. }
  111284. if( pAccum->nChar==0 ) pAccum->mxAlloc = 0;
  111285. }
  111286. }
  111287. #else
  111288. # define groupConcatInverse 0
  111289. #endif /* SQLITE_OMIT_WINDOWFUNC */
  111290. static void groupConcatFinalize(sqlite3_context *context){
  111291. StrAccum *pAccum;
  111292. pAccum = sqlite3_aggregate_context(context, 0);
  111293. if( pAccum ){
  111294. if( pAccum->accError==SQLITE_TOOBIG ){
  111295. sqlite3_result_error_toobig(context);
  111296. }else if( pAccum->accError==SQLITE_NOMEM ){
  111297. sqlite3_result_error_nomem(context);
  111298. }else{
  111299. sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1,
  111300. sqlite3_free);
  111301. }
  111302. }
  111303. }
  111304. #ifndef SQLITE_OMIT_WINDOWFUNC
  111305. static void groupConcatValue(sqlite3_context *context){
  111306. sqlite3_str *pAccum;
  111307. pAccum = (sqlite3_str*)sqlite3_aggregate_context(context, 0);
  111308. if( pAccum ){
  111309. if( pAccum->accError==SQLITE_TOOBIG ){
  111310. sqlite3_result_error_toobig(context);
  111311. }else if( pAccum->accError==SQLITE_NOMEM ){
  111312. sqlite3_result_error_nomem(context);
  111313. }else{
  111314. const char *zText = sqlite3_str_value(pAccum);
  111315. sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
  111316. }
  111317. }
  111318. }
  111319. #else
  111320. # define groupConcatValue 0
  111321. #endif /* SQLITE_OMIT_WINDOWFUNC */
  111322. /*
  111323. ** This routine does per-connection function registration. Most
  111324. ** of the built-in functions above are part of the global function set.
  111325. ** This routine only deals with those that are not global.
  111326. */
  111327. SQLITE_PRIVATE void sqlite3RegisterPerConnectionBuiltinFunctions(sqlite3 *db){
  111328. int rc = sqlite3_overload_function(db, "MATCH", 2);
  111329. assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
  111330. if( rc==SQLITE_NOMEM ){
  111331. sqlite3OomFault(db);
  111332. }
  111333. }
  111334. /*
  111335. ** Re-register the built-in LIKE functions. The caseSensitive
  111336. ** parameter determines whether or not the LIKE operator is case
  111337. ** sensitive.
  111338. */
  111339. SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
  111340. struct compareInfo *pInfo;
  111341. int flags;
  111342. if( caseSensitive ){
  111343. pInfo = (struct compareInfo*)&likeInfoAlt;
  111344. flags = SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE;
  111345. }else{
  111346. pInfo = (struct compareInfo*)&likeInfoNorm;
  111347. flags = SQLITE_FUNC_LIKE;
  111348. }
  111349. sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0, 0, 0);
  111350. sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0, 0, 0);
  111351. sqlite3FindFunction(db, "like", 2, SQLITE_UTF8, 0)->funcFlags |= flags;
  111352. sqlite3FindFunction(db, "like", 3, SQLITE_UTF8, 0)->funcFlags |= flags;
  111353. }
  111354. /*
  111355. ** pExpr points to an expression which implements a function. If
  111356. ** it is appropriate to apply the LIKE optimization to that function
  111357. ** then set aWc[0] through aWc[2] to the wildcard characters and the
  111358. ** escape character and then return TRUE. If the function is not a
  111359. ** LIKE-style function then return FALSE.
  111360. **
  111361. ** The expression "a LIKE b ESCAPE c" is only considered a valid LIKE
  111362. ** operator if c is a string literal that is exactly one byte in length.
  111363. ** That one byte is stored in aWc[3]. aWc[3] is set to zero if there is
  111364. ** no ESCAPE clause.
  111365. **
  111366. ** *pIsNocase is set to true if uppercase and lowercase are equivalent for
  111367. ** the function (default for LIKE). If the function makes the distinction
  111368. ** between uppercase and lowercase (as does GLOB) then *pIsNocase is set to
  111369. ** false.
  111370. */
  111371. SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
  111372. FuncDef *pDef;
  111373. int nExpr;
  111374. if( pExpr->op!=TK_FUNCTION || !pExpr->x.pList ){
  111375. return 0;
  111376. }
  111377. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  111378. nExpr = pExpr->x.pList->nExpr;
  111379. pDef = sqlite3FindFunction(db, pExpr->u.zToken, nExpr, SQLITE_UTF8, 0);
  111380. #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
  111381. if( pDef==0 ) return 0;
  111382. #endif
  111383. if( NEVER(pDef==0) || (pDef->funcFlags & SQLITE_FUNC_LIKE)==0 ){
  111384. return 0;
  111385. }
  111386. /* The memcpy() statement assumes that the wildcard characters are
  111387. ** the first three statements in the compareInfo structure. The
  111388. ** asserts() that follow verify that assumption
  111389. */
  111390. memcpy(aWc, pDef->pUserData, 3);
  111391. assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
  111392. assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
  111393. assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
  111394. if( nExpr<3 ){
  111395. aWc[3] = 0;
  111396. }else{
  111397. Expr *pEscape = pExpr->x.pList->a[2].pExpr;
  111398. char *zEscape;
  111399. if( pEscape->op!=TK_STRING ) return 0;
  111400. zEscape = pEscape->u.zToken;
  111401. if( zEscape[0]==0 || zEscape[1]!=0 ) return 0;
  111402. if( zEscape[0]==aWc[0] ) return 0;
  111403. if( zEscape[0]==aWc[1] ) return 0;
  111404. aWc[3] = zEscape[0];
  111405. }
  111406. *pIsNocase = (pDef->funcFlags & SQLITE_FUNC_CASE)==0;
  111407. return 1;
  111408. }
  111409. /*
  111410. ** All of the FuncDef structures in the aBuiltinFunc[] array above
  111411. ** to the global function hash table. This occurs at start-time (as
  111412. ** a consequence of calling sqlite3_initialize()).
  111413. **
  111414. ** After this routine runs
  111415. */
  111416. SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void){
  111417. /*
  111418. ** The following array holds FuncDef structures for all of the functions
  111419. ** defined in this file.
  111420. **
  111421. ** The array cannot be constant since changes are made to the
  111422. ** FuncDef.pHash elements at start-time. The elements of this array
  111423. ** are read-only after initialization is complete.
  111424. **
  111425. ** For peak efficiency, put the most frequently used function last.
  111426. */
  111427. static FuncDef aBuiltinFunc[] = {
  111428. /***** Functions only available with SQLITE_TESTCTRL_INTERNAL_FUNCTIONS *****/
  111429. TEST_FUNC(implies_nonnull_row, 2, INLINEFUNC_implies_nonnull_row, 0),
  111430. TEST_FUNC(expr_compare, 2, INLINEFUNC_expr_compare, 0),
  111431. TEST_FUNC(expr_implies_expr, 2, INLINEFUNC_expr_implies_expr, 0),
  111432. #ifdef SQLITE_DEBUG
  111433. TEST_FUNC(affinity, 1, INLINEFUNC_affinity, 0),
  111434. #endif
  111435. /***** Regular functions *****/
  111436. #ifdef SQLITE_SOUNDEX
  111437. FUNCTION(soundex, 1, 0, 0, soundexFunc ),
  111438. #endif
  111439. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  111440. SFUNCTION(load_extension, 1, 0, 0, loadExt ),
  111441. SFUNCTION(load_extension, 2, 0, 0, loadExt ),
  111442. #endif
  111443. #if SQLITE_USER_AUTHENTICATION
  111444. FUNCTION(sqlite_crypt, 2, 0, 0, sqlite3CryptFunc ),
  111445. #endif
  111446. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  111447. DFUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc ),
  111448. DFUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc ),
  111449. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  111450. INLINE_FUNC(unlikely, 1, INLINEFUNC_unlikely, SQLITE_FUNC_UNLIKELY),
  111451. INLINE_FUNC(likelihood, 2, INLINEFUNC_unlikely, SQLITE_FUNC_UNLIKELY),
  111452. INLINE_FUNC(likely, 1, INLINEFUNC_unlikely, SQLITE_FUNC_UNLIKELY),
  111453. #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
  111454. FUNCTION2(sqlite_offset, 1, 0, 0, noopFunc, SQLITE_FUNC_OFFSET|
  111455. SQLITE_FUNC_TYPEOF),
  111456. #endif
  111457. FUNCTION(ltrim, 1, 1, 0, trimFunc ),
  111458. FUNCTION(ltrim, 2, 1, 0, trimFunc ),
  111459. FUNCTION(rtrim, 1, 2, 0, trimFunc ),
  111460. FUNCTION(rtrim, 2, 2, 0, trimFunc ),
  111461. FUNCTION(trim, 1, 3, 0, trimFunc ),
  111462. FUNCTION(trim, 2, 3, 0, trimFunc ),
  111463. FUNCTION(min, -1, 0, 1, minmaxFunc ),
  111464. FUNCTION(min, 0, 0, 1, 0 ),
  111465. WAGGREGATE(min, 1, 0, 1, minmaxStep, minMaxFinalize, minMaxValue, 0,
  111466. SQLITE_FUNC_MINMAX ),
  111467. FUNCTION(max, -1, 1, 1, minmaxFunc ),
  111468. FUNCTION(max, 0, 1, 1, 0 ),
  111469. WAGGREGATE(max, 1, 1, 1, minmaxStep, minMaxFinalize, minMaxValue, 0,
  111470. SQLITE_FUNC_MINMAX ),
  111471. FUNCTION2(typeof, 1, 0, 0, typeofFunc, SQLITE_FUNC_TYPEOF),
  111472. FUNCTION2(length, 1, 0, 0, lengthFunc, SQLITE_FUNC_LENGTH),
  111473. FUNCTION(instr, 2, 0, 0, instrFunc ),
  111474. FUNCTION(printf, -1, 0, 0, printfFunc ),
  111475. FUNCTION(unicode, 1, 0, 0, unicodeFunc ),
  111476. FUNCTION(char, -1, 0, 0, charFunc ),
  111477. FUNCTION(abs, 1, 0, 0, absFunc ),
  111478. #ifndef SQLITE_OMIT_FLOATING_POINT
  111479. FUNCTION(round, 1, 0, 0, roundFunc ),
  111480. FUNCTION(round, 2, 0, 0, roundFunc ),
  111481. #endif
  111482. FUNCTION(upper, 1, 0, 0, upperFunc ),
  111483. FUNCTION(lower, 1, 0, 0, lowerFunc ),
  111484. FUNCTION(hex, 1, 0, 0, hexFunc ),
  111485. INLINE_FUNC(ifnull, 2, INLINEFUNC_coalesce, 0 ),
  111486. VFUNCTION(random, 0, 0, 0, randomFunc ),
  111487. VFUNCTION(randomblob, 1, 0, 0, randomBlob ),
  111488. FUNCTION(nullif, 2, 0, 1, nullifFunc ),
  111489. DFUNCTION(sqlite_version, 0, 0, 0, versionFunc ),
  111490. DFUNCTION(sqlite_source_id, 0, 0, 0, sourceidFunc ),
  111491. FUNCTION(sqlite_log, 2, 0, 0, errlogFunc ),
  111492. FUNCTION(quote, 1, 0, 0, quoteFunc ),
  111493. VFUNCTION(last_insert_rowid, 0, 0, 0, last_insert_rowid),
  111494. VFUNCTION(changes, 0, 0, 0, changes ),
  111495. VFUNCTION(total_changes, 0, 0, 0, total_changes ),
  111496. FUNCTION(replace, 3, 0, 0, replaceFunc ),
  111497. FUNCTION(zeroblob, 1, 0, 0, zeroblobFunc ),
  111498. FUNCTION(substr, 2, 0, 0, substrFunc ),
  111499. FUNCTION(substr, 3, 0, 0, substrFunc ),
  111500. WAGGREGATE(sum, 1,0,0, sumStep, sumFinalize, sumFinalize, sumInverse, 0),
  111501. WAGGREGATE(total, 1,0,0, sumStep,totalFinalize,totalFinalize,sumInverse, 0),
  111502. WAGGREGATE(avg, 1,0,0, sumStep, avgFinalize, avgFinalize, sumInverse, 0),
  111503. WAGGREGATE(count, 0,0,0, countStep,
  111504. countFinalize, countFinalize, countInverse, SQLITE_FUNC_COUNT ),
  111505. WAGGREGATE(count, 1,0,0, countStep,
  111506. countFinalize, countFinalize, countInverse, 0 ),
  111507. WAGGREGATE(group_concat, 1, 0, 0, groupConcatStep,
  111508. groupConcatFinalize, groupConcatValue, groupConcatInverse, 0),
  111509. WAGGREGATE(group_concat, 2, 0, 0, groupConcatStep,
  111510. groupConcatFinalize, groupConcatValue, groupConcatInverse, 0),
  111511. LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
  111512. #ifdef SQLITE_CASE_SENSITIVE_LIKE
  111513. LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
  111514. LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
  111515. #else
  111516. LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
  111517. LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
  111518. #endif
  111519. #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
  111520. FUNCTION(unknown, -1, 0, 0, unknownFunc ),
  111521. #endif
  111522. FUNCTION(coalesce, 1, 0, 0, 0 ),
  111523. FUNCTION(coalesce, 0, 0, 0, 0 ),
  111524. INLINE_FUNC(coalesce, -1, INLINEFUNC_coalesce, 0 ),
  111525. INLINE_FUNC(iif, 3, INLINEFUNC_iif, 0 ),
  111526. };
  111527. #ifndef SQLITE_OMIT_ALTERTABLE
  111528. sqlite3AlterFunctions();
  111529. #endif
  111530. sqlite3WindowFunctions();
  111531. sqlite3RegisterDateTimeFunctions();
  111532. sqlite3InsertBuiltinFuncs(aBuiltinFunc, ArraySize(aBuiltinFunc));
  111533. #if 0 /* Enable to print out how the built-in functions are hashed */
  111534. {
  111535. int i;
  111536. FuncDef *p;
  111537. for(i=0; i<SQLITE_FUNC_HASH_SZ; i++){
  111538. printf("FUNC-HASH %02d:", i);
  111539. for(p=sqlite3BuiltinFunctions.a[i]; p; p=p->u.pHash){
  111540. int n = sqlite3Strlen30(p->zName);
  111541. int h = p->zName[0] + n;
  111542. printf(" %s(%d)", p->zName, h);
  111543. }
  111544. printf("\n");
  111545. }
  111546. }
  111547. #endif
  111548. }
  111549. /************** End of func.c ************************************************/
  111550. /************** Begin file fkey.c ********************************************/
  111551. /*
  111552. **
  111553. ** The author disclaims copyright to this source code. In place of
  111554. ** a legal notice, here is a blessing:
  111555. **
  111556. ** May you do good and not evil.
  111557. ** May you find forgiveness for yourself and forgive others.
  111558. ** May you share freely, never taking more than you give.
  111559. **
  111560. *************************************************************************
  111561. ** This file contains code used by the compiler to add foreign key
  111562. ** support to compiled SQL statements.
  111563. */
  111564. /* #include "sqliteInt.h" */
  111565. #ifndef SQLITE_OMIT_FOREIGN_KEY
  111566. #ifndef SQLITE_OMIT_TRIGGER
  111567. /*
  111568. ** Deferred and Immediate FKs
  111569. ** --------------------------
  111570. **
  111571. ** Foreign keys in SQLite come in two flavours: deferred and immediate.
  111572. ** If an immediate foreign key constraint is violated,
  111573. ** SQLITE_CONSTRAINT_FOREIGNKEY is returned and the current
  111574. ** statement transaction rolled back. If a
  111575. ** deferred foreign key constraint is violated, no action is taken
  111576. ** immediately. However if the application attempts to commit the
  111577. ** transaction before fixing the constraint violation, the attempt fails.
  111578. **
  111579. ** Deferred constraints are implemented using a simple counter associated
  111580. ** with the database handle. The counter is set to zero each time a
  111581. ** database transaction is opened. Each time a statement is executed
  111582. ** that causes a foreign key violation, the counter is incremented. Each
  111583. ** time a statement is executed that removes an existing violation from
  111584. ** the database, the counter is decremented. When the transaction is
  111585. ** committed, the commit fails if the current value of the counter is
  111586. ** greater than zero. This scheme has two big drawbacks:
  111587. **
  111588. ** * When a commit fails due to a deferred foreign key constraint,
  111589. ** there is no way to tell which foreign constraint is not satisfied,
  111590. ** or which row it is not satisfied for.
  111591. **
  111592. ** * If the database contains foreign key violations when the
  111593. ** transaction is opened, this may cause the mechanism to malfunction.
  111594. **
  111595. ** Despite these problems, this approach is adopted as it seems simpler
  111596. ** than the alternatives.
  111597. **
  111598. ** INSERT operations:
  111599. **
  111600. ** I.1) For each FK for which the table is the child table, search
  111601. ** the parent table for a match. If none is found increment the
  111602. ** constraint counter.
  111603. **
  111604. ** I.2) For each FK for which the table is the parent table,
  111605. ** search the child table for rows that correspond to the new
  111606. ** row in the parent table. Decrement the counter for each row
  111607. ** found (as the constraint is now satisfied).
  111608. **
  111609. ** DELETE operations:
  111610. **
  111611. ** D.1) For each FK for which the table is the child table,
  111612. ** search the parent table for a row that corresponds to the
  111613. ** deleted row in the child table. If such a row is not found,
  111614. ** decrement the counter.
  111615. **
  111616. ** D.2) For each FK for which the table is the parent table, search
  111617. ** the child table for rows that correspond to the deleted row
  111618. ** in the parent table. For each found increment the counter.
  111619. **
  111620. ** UPDATE operations:
  111621. **
  111622. ** An UPDATE command requires that all 4 steps above are taken, but only
  111623. ** for FK constraints for which the affected columns are actually
  111624. ** modified (values must be compared at runtime).
  111625. **
  111626. ** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2.
  111627. ** This simplifies the implementation a bit.
  111628. **
  111629. ** For the purposes of immediate FK constraints, the OR REPLACE conflict
  111630. ** resolution is considered to delete rows before the new row is inserted.
  111631. ** If a delete caused by OR REPLACE violates an FK constraint, an exception
  111632. ** is thrown, even if the FK constraint would be satisfied after the new
  111633. ** row is inserted.
  111634. **
  111635. ** Immediate constraints are usually handled similarly. The only difference
  111636. ** is that the counter used is stored as part of each individual statement
  111637. ** object (struct Vdbe). If, after the statement has run, its immediate
  111638. ** constraint counter is greater than zero,
  111639. ** it returns SQLITE_CONSTRAINT_FOREIGNKEY
  111640. ** and the statement transaction is rolled back. An exception is an INSERT
  111641. ** statement that inserts a single row only (no triggers). In this case,
  111642. ** instead of using a counter, an exception is thrown immediately if the
  111643. ** INSERT violates a foreign key constraint. This is necessary as such
  111644. ** an INSERT does not open a statement transaction.
  111645. **
  111646. ** TODO: How should dropping a table be handled? How should renaming a
  111647. ** table be handled?
  111648. **
  111649. **
  111650. ** Query API Notes
  111651. ** ---------------
  111652. **
  111653. ** Before coding an UPDATE or DELETE row operation, the code-generator
  111654. ** for those two operations needs to know whether or not the operation
  111655. ** requires any FK processing and, if so, which columns of the original
  111656. ** row are required by the FK processing VDBE code (i.e. if FKs were
  111657. ** implemented using triggers, which of the old.* columns would be
  111658. ** accessed). No information is required by the code-generator before
  111659. ** coding an INSERT operation. The functions used by the UPDATE/DELETE
  111660. ** generation code to query for this information are:
  111661. **
  111662. ** sqlite3FkRequired() - Test to see if FK processing is required.
  111663. ** sqlite3FkOldmask() - Query for the set of required old.* columns.
  111664. **
  111665. **
  111666. ** Externally accessible module functions
  111667. ** --------------------------------------
  111668. **
  111669. ** sqlite3FkCheck() - Check for foreign key violations.
  111670. ** sqlite3FkActions() - Code triggers for ON UPDATE/ON DELETE actions.
  111671. ** sqlite3FkDelete() - Delete an FKey structure.
  111672. */
  111673. /*
  111674. ** VDBE Calling Convention
  111675. ** -----------------------
  111676. **
  111677. ** Example:
  111678. **
  111679. ** For the following INSERT statement:
  111680. **
  111681. ** CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c);
  111682. ** INSERT INTO t1 VALUES(1, 2, 3.1);
  111683. **
  111684. ** Register (x): 2 (type integer)
  111685. ** Register (x+1): 1 (type integer)
  111686. ** Register (x+2): NULL (type NULL)
  111687. ** Register (x+3): 3.1 (type real)
  111688. */
  111689. /*
  111690. ** A foreign key constraint requires that the key columns in the parent
  111691. ** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.
  111692. ** Given that pParent is the parent table for foreign key constraint pFKey,
  111693. ** search the schema for a unique index on the parent key columns.
  111694. **
  111695. ** If successful, zero is returned. If the parent key is an INTEGER PRIMARY
  111696. ** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx
  111697. ** is set to point to the unique index.
  111698. **
  111699. ** If the parent key consists of a single column (the foreign key constraint
  111700. ** is not a composite foreign key), output variable *paiCol is set to NULL.
  111701. ** Otherwise, it is set to point to an allocated array of size N, where
  111702. ** N is the number of columns in the parent key. The first element of the
  111703. ** array is the index of the child table column that is mapped by the FK
  111704. ** constraint to the parent table column stored in the left-most column
  111705. ** of index *ppIdx. The second element of the array is the index of the
  111706. ** child table column that corresponds to the second left-most column of
  111707. ** *ppIdx, and so on.
  111708. **
  111709. ** If the required index cannot be found, either because:
  111710. **
  111711. ** 1) The named parent key columns do not exist, or
  111712. **
  111713. ** 2) The named parent key columns do exist, but are not subject to a
  111714. ** UNIQUE or PRIMARY KEY constraint, or
  111715. **
  111716. ** 3) No parent key columns were provided explicitly as part of the
  111717. ** foreign key definition, and the parent table does not have a
  111718. ** PRIMARY KEY, or
  111719. **
  111720. ** 4) No parent key columns were provided explicitly as part of the
  111721. ** foreign key definition, and the PRIMARY KEY of the parent table
  111722. ** consists of a different number of columns to the child key in
  111723. ** the child table.
  111724. **
  111725. ** then non-zero is returned, and a "foreign key mismatch" error loaded
  111726. ** into pParse. If an OOM error occurs, non-zero is returned and the
  111727. ** pParse->db->mallocFailed flag is set.
  111728. */
  111729. SQLITE_PRIVATE int sqlite3FkLocateIndex(
  111730. Parse *pParse, /* Parse context to store any error in */
  111731. Table *pParent, /* Parent table of FK constraint pFKey */
  111732. FKey *pFKey, /* Foreign key to find index for */
  111733. Index **ppIdx, /* OUT: Unique index on parent table */
  111734. int **paiCol /* OUT: Map of index columns in pFKey */
  111735. ){
  111736. Index *pIdx = 0; /* Value to return via *ppIdx */
  111737. int *aiCol = 0; /* Value to return via *paiCol */
  111738. int nCol = pFKey->nCol; /* Number of columns in parent key */
  111739. char *zKey = pFKey->aCol[0].zCol; /* Name of left-most parent key column */
  111740. /* The caller is responsible for zeroing output parameters. */
  111741. assert( ppIdx && *ppIdx==0 );
  111742. assert( !paiCol || *paiCol==0 );
  111743. assert( pParse );
  111744. /* If this is a non-composite (single column) foreign key, check if it
  111745. ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx
  111746. ** and *paiCol set to zero and return early.
  111747. **
  111748. ** Otherwise, for a composite foreign key (more than one column), allocate
  111749. ** space for the aiCol array (returned via output parameter *paiCol).
  111750. ** Non-composite foreign keys do not require the aiCol array.
  111751. */
  111752. if( nCol==1 ){
  111753. /* The FK maps to the IPK if any of the following are true:
  111754. **
  111755. ** 1) There is an INTEGER PRIMARY KEY column and the FK is implicitly
  111756. ** mapped to the primary key of table pParent, or
  111757. ** 2) The FK is explicitly mapped to a column declared as INTEGER
  111758. ** PRIMARY KEY.
  111759. */
  111760. if( pParent->iPKey>=0 ){
  111761. if( !zKey ) return 0;
  111762. if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0;
  111763. }
  111764. }else if( paiCol ){
  111765. assert( nCol>1 );
  111766. aiCol = (int *)sqlite3DbMallocRawNN(pParse->db, nCol*sizeof(int));
  111767. if( !aiCol ) return 1;
  111768. *paiCol = aiCol;
  111769. }
  111770. for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
  111771. if( pIdx->nKeyCol==nCol && IsUniqueIndex(pIdx) && pIdx->pPartIdxWhere==0 ){
  111772. /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
  111773. ** of columns. If each indexed column corresponds to a foreign key
  111774. ** column of pFKey, then this index is a winner. */
  111775. if( zKey==0 ){
  111776. /* If zKey is NULL, then this foreign key is implicitly mapped to
  111777. ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be
  111778. ** identified by the test. */
  111779. if( IsPrimaryKeyIndex(pIdx) ){
  111780. if( aiCol ){
  111781. int i;
  111782. for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom;
  111783. }
  111784. break;
  111785. }
  111786. }else{
  111787. /* If zKey is non-NULL, then this foreign key was declared to
  111788. ** map to an explicit list of columns in table pParent. Check if this
  111789. ** index matches those columns. Also, check that the index uses
  111790. ** the default collation sequences for each column. */
  111791. int i, j;
  111792. for(i=0; i<nCol; i++){
  111793. i16 iCol = pIdx->aiColumn[i]; /* Index of column in parent tbl */
  111794. const char *zDfltColl; /* Def. collation for column */
  111795. char *zIdxCol; /* Name of indexed column */
  111796. if( iCol<0 ) break; /* No foreign keys against expression indexes */
  111797. /* If the index uses a collation sequence that is different from
  111798. ** the default collation sequence for the column, this index is
  111799. ** unusable. Bail out early in this case. */
  111800. zDfltColl = pParent->aCol[iCol].zColl;
  111801. if( !zDfltColl ) zDfltColl = sqlite3StrBINARY;
  111802. if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break;
  111803. zIdxCol = pParent->aCol[iCol].zName;
  111804. for(j=0; j<nCol; j++){
  111805. if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
  111806. if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
  111807. break;
  111808. }
  111809. }
  111810. if( j==nCol ) break;
  111811. }
  111812. if( i==nCol ) break; /* pIdx is usable */
  111813. }
  111814. }
  111815. }
  111816. if( !pIdx ){
  111817. if( !pParse->disableTriggers ){
  111818. sqlite3ErrorMsg(pParse,
  111819. "foreign key mismatch - \"%w\" referencing \"%w\"",
  111820. pFKey->pFrom->zName, pFKey->zTo);
  111821. }
  111822. sqlite3DbFree(pParse->db, aiCol);
  111823. return 1;
  111824. }
  111825. *ppIdx = pIdx;
  111826. return 0;
  111827. }
  111828. /*
  111829. ** This function is called when a row is inserted into or deleted from the
  111830. ** child table of foreign key constraint pFKey. If an SQL UPDATE is executed
  111831. ** on the child table of pFKey, this function is invoked twice for each row
  111832. ** affected - once to "delete" the old row, and then again to "insert" the
  111833. ** new row.
  111834. **
  111835. ** Each time it is called, this function generates VDBE code to locate the
  111836. ** row in the parent table that corresponds to the row being inserted into
  111837. ** or deleted from the child table. If the parent row can be found, no
  111838. ** special action is taken. Otherwise, if the parent row can *not* be
  111839. ** found in the parent table:
  111840. **
  111841. ** Operation | FK type | Action taken
  111842. ** --------------------------------------------------------------------------
  111843. ** INSERT immediate Increment the "immediate constraint counter".
  111844. **
  111845. ** DELETE immediate Decrement the "immediate constraint counter".
  111846. **
  111847. ** INSERT deferred Increment the "deferred constraint counter".
  111848. **
  111849. ** DELETE deferred Decrement the "deferred constraint counter".
  111850. **
  111851. ** These operations are identified in the comment at the top of this file
  111852. ** (fkey.c) as "I.1" and "D.1".
  111853. */
  111854. static void fkLookupParent(
  111855. Parse *pParse, /* Parse context */
  111856. int iDb, /* Index of database housing pTab */
  111857. Table *pTab, /* Parent table of FK pFKey */
  111858. Index *pIdx, /* Unique index on parent key columns in pTab */
  111859. FKey *pFKey, /* Foreign key constraint */
  111860. int *aiCol, /* Map from parent key columns to child table columns */
  111861. int regData, /* Address of array containing child table row */
  111862. int nIncr, /* Increment constraint counter by this */
  111863. int isIgnore /* If true, pretend pTab contains all NULL values */
  111864. ){
  111865. int i; /* Iterator variable */
  111866. Vdbe *v = sqlite3GetVdbe(pParse); /* Vdbe to add code to */
  111867. int iCur = pParse->nTab - 1; /* Cursor number to use */
  111868. int iOk = sqlite3VdbeMakeLabel(pParse); /* jump here if parent key found */
  111869. sqlite3VdbeVerifyAbortable(v,
  111870. (!pFKey->isDeferred
  111871. && !(pParse->db->flags & SQLITE_DeferFKs)
  111872. && !pParse->pToplevel
  111873. && !pParse->isMultiWrite) ? OE_Abort : OE_Ignore);
  111874. /* If nIncr is less than zero, then check at runtime if there are any
  111875. ** outstanding constraints to resolve. If there are not, there is no need
  111876. ** to check if deleting this row resolves any outstanding violations.
  111877. **
  111878. ** Check if any of the key columns in the child table row are NULL. If
  111879. ** any are, then the constraint is considered satisfied. No need to
  111880. ** search for a matching row in the parent table. */
  111881. if( nIncr<0 ){
  111882. sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);
  111883. VdbeCoverage(v);
  111884. }
  111885. for(i=0; i<pFKey->nCol; i++){
  111886. int iReg = sqlite3TableColumnToStorage(pFKey->pFrom,aiCol[i]) + regData + 1;
  111887. sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk); VdbeCoverage(v);
  111888. }
  111889. if( isIgnore==0 ){
  111890. if( pIdx==0 ){
  111891. /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
  111892. ** column of the parent table (table pTab). */
  111893. int iMustBeInt; /* Address of MustBeInt instruction */
  111894. int regTemp = sqlite3GetTempReg(pParse);
  111895. /* Invoke MustBeInt to coerce the child key value to an integer (i.e.
  111896. ** apply the affinity of the parent key). If this fails, then there
  111897. ** is no matching parent key. Before using MustBeInt, make a copy of
  111898. ** the value. Otherwise, the value inserted into the child key column
  111899. ** will have INTEGER affinity applied to it, which may not be correct. */
  111900. sqlite3VdbeAddOp2(v, OP_SCopy,
  111901. sqlite3TableColumnToStorage(pFKey->pFrom,aiCol[0])+1+regData, regTemp);
  111902. iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);
  111903. VdbeCoverage(v);
  111904. /* If the parent table is the same as the child table, and we are about
  111905. ** to increment the constraint-counter (i.e. this is an INSERT operation),
  111906. ** then check if the row being inserted matches itself. If so, do not
  111907. ** increment the constraint-counter. */
  111908. if( pTab==pFKey->pFrom && nIncr==1 ){
  111909. sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp); VdbeCoverage(v);
  111910. sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
  111911. }
  111912. sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
  111913. sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp); VdbeCoverage(v);
  111914. sqlite3VdbeGoto(v, iOk);
  111915. sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
  111916. sqlite3VdbeJumpHere(v, iMustBeInt);
  111917. sqlite3ReleaseTempReg(pParse, regTemp);
  111918. }else{
  111919. int nCol = pFKey->nCol;
  111920. int regTemp = sqlite3GetTempRange(pParse, nCol);
  111921. int regRec = sqlite3GetTempReg(pParse);
  111922. sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
  111923. sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  111924. for(i=0; i<nCol; i++){
  111925. sqlite3VdbeAddOp2(v, OP_Copy,
  111926. sqlite3TableColumnToStorage(pFKey->pFrom, aiCol[i])+1+regData,
  111927. regTemp+i);
  111928. }
  111929. /* If the parent table is the same as the child table, and we are about
  111930. ** to increment the constraint-counter (i.e. this is an INSERT operation),
  111931. ** then check if the row being inserted matches itself. If so, do not
  111932. ** increment the constraint-counter.
  111933. **
  111934. ** If any of the parent-key values are NULL, then the row cannot match
  111935. ** itself. So set JUMPIFNULL to make sure we do the OP_Found if any
  111936. ** of the parent-key values are NULL (at this point it is known that
  111937. ** none of the child key values are).
  111938. */
  111939. if( pTab==pFKey->pFrom && nIncr==1 ){
  111940. int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1;
  111941. for(i=0; i<nCol; i++){
  111942. int iChild = sqlite3TableColumnToStorage(pFKey->pFrom,aiCol[i])
  111943. +1+regData;
  111944. int iParent = 1+regData;
  111945. iParent += sqlite3TableColumnToStorage(pIdx->pTable,
  111946. pIdx->aiColumn[i]);
  111947. assert( pIdx->aiColumn[i]>=0 );
  111948. assert( aiCol[i]!=pTab->iPKey );
  111949. if( pIdx->aiColumn[i]==pTab->iPKey ){
  111950. /* The parent key is a composite key that includes the IPK column */
  111951. iParent = regData;
  111952. }
  111953. sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent); VdbeCoverage(v);
  111954. sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
  111955. }
  111956. sqlite3VdbeGoto(v, iOk);
  111957. }
  111958. sqlite3VdbeAddOp4(v, OP_MakeRecord, regTemp, nCol, regRec,
  111959. sqlite3IndexAffinityStr(pParse->db,pIdx), nCol);
  111960. sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0); VdbeCoverage(v);
  111961. sqlite3ReleaseTempReg(pParse, regRec);
  111962. sqlite3ReleaseTempRange(pParse, regTemp, nCol);
  111963. }
  111964. }
  111965. if( !pFKey->isDeferred && !(pParse->db->flags & SQLITE_DeferFKs)
  111966. && !pParse->pToplevel
  111967. && !pParse->isMultiWrite
  111968. ){
  111969. /* Special case: If this is an INSERT statement that will insert exactly
  111970. ** one row into the table, raise a constraint immediately instead of
  111971. ** incrementing a counter. This is necessary as the VM code is being
  111972. ** generated for will not open a statement transaction. */
  111973. assert( nIncr==1 );
  111974. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
  111975. OE_Abort, 0, P4_STATIC, P5_ConstraintFK);
  111976. }else{
  111977. if( nIncr>0 && pFKey->isDeferred==0 ){
  111978. sqlite3MayAbort(pParse);
  111979. }
  111980. sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
  111981. }
  111982. sqlite3VdbeResolveLabel(v, iOk);
  111983. sqlite3VdbeAddOp1(v, OP_Close, iCur);
  111984. }
  111985. /*
  111986. ** Return an Expr object that refers to a memory register corresponding
  111987. ** to column iCol of table pTab.
  111988. **
  111989. ** regBase is the first of an array of register that contains the data
  111990. ** for pTab. regBase itself holds the rowid. regBase+1 holds the first
  111991. ** column. regBase+2 holds the second column, and so forth.
  111992. */
  111993. static Expr *exprTableRegister(
  111994. Parse *pParse, /* Parsing and code generating context */
  111995. Table *pTab, /* The table whose content is at r[regBase]... */
  111996. int regBase, /* Contents of table pTab */
  111997. i16 iCol /* Which column of pTab is desired */
  111998. ){
  111999. Expr *pExpr;
  112000. Column *pCol;
  112001. const char *zColl;
  112002. sqlite3 *db = pParse->db;
  112003. pExpr = sqlite3Expr(db, TK_REGISTER, 0);
  112004. if( pExpr ){
  112005. if( iCol>=0 && iCol!=pTab->iPKey ){
  112006. pCol = &pTab->aCol[iCol];
  112007. pExpr->iTable = regBase + sqlite3TableColumnToStorage(pTab,iCol) + 1;
  112008. pExpr->affExpr = pCol->affinity;
  112009. zColl = pCol->zColl;
  112010. if( zColl==0 ) zColl = db->pDfltColl->zName;
  112011. pExpr = sqlite3ExprAddCollateString(pParse, pExpr, zColl);
  112012. }else{
  112013. pExpr->iTable = regBase;
  112014. pExpr->affExpr = SQLITE_AFF_INTEGER;
  112015. }
  112016. }
  112017. return pExpr;
  112018. }
  112019. /*
  112020. ** Return an Expr object that refers to column iCol of table pTab which
  112021. ** has cursor iCur.
  112022. */
  112023. static Expr *exprTableColumn(
  112024. sqlite3 *db, /* The database connection */
  112025. Table *pTab, /* The table whose column is desired */
  112026. int iCursor, /* The open cursor on the table */
  112027. i16 iCol /* The column that is wanted */
  112028. ){
  112029. Expr *pExpr = sqlite3Expr(db, TK_COLUMN, 0);
  112030. if( pExpr ){
  112031. pExpr->y.pTab = pTab;
  112032. pExpr->iTable = iCursor;
  112033. pExpr->iColumn = iCol;
  112034. }
  112035. return pExpr;
  112036. }
  112037. /*
  112038. ** This function is called to generate code executed when a row is deleted
  112039. ** from the parent table of foreign key constraint pFKey and, if pFKey is
  112040. ** deferred, when a row is inserted into the same table. When generating
  112041. ** code for an SQL UPDATE operation, this function may be called twice -
  112042. ** once to "delete" the old row and once to "insert" the new row.
  112043. **
  112044. ** Parameter nIncr is passed -1 when inserting a row (as this may decrease
  112045. ** the number of FK violations in the db) or +1 when deleting one (as this
  112046. ** may increase the number of FK constraint problems).
  112047. **
  112048. ** The code generated by this function scans through the rows in the child
  112049. ** table that correspond to the parent table row being deleted or inserted.
  112050. ** For each child row found, one of the following actions is taken:
  112051. **
  112052. ** Operation | FK type | Action taken
  112053. ** --------------------------------------------------------------------------
  112054. ** DELETE immediate Increment the "immediate constraint counter".
  112055. ** Or, if the ON (UPDATE|DELETE) action is RESTRICT,
  112056. ** throw a "FOREIGN KEY constraint failed" exception.
  112057. **
  112058. ** INSERT immediate Decrement the "immediate constraint counter".
  112059. **
  112060. ** DELETE deferred Increment the "deferred constraint counter".
  112061. ** Or, if the ON (UPDATE|DELETE) action is RESTRICT,
  112062. ** throw a "FOREIGN KEY constraint failed" exception.
  112063. **
  112064. ** INSERT deferred Decrement the "deferred constraint counter".
  112065. **
  112066. ** These operations are identified in the comment at the top of this file
  112067. ** (fkey.c) as "I.2" and "D.2".
  112068. */
  112069. static void fkScanChildren(
  112070. Parse *pParse, /* Parse context */
  112071. SrcList *pSrc, /* The child table to be scanned */
  112072. Table *pTab, /* The parent table */
  112073. Index *pIdx, /* Index on parent covering the foreign key */
  112074. FKey *pFKey, /* The foreign key linking pSrc to pTab */
  112075. int *aiCol, /* Map from pIdx cols to child table cols */
  112076. int regData, /* Parent row data starts here */
  112077. int nIncr /* Amount to increment deferred counter by */
  112078. ){
  112079. sqlite3 *db = pParse->db; /* Database handle */
  112080. int i; /* Iterator variable */
  112081. Expr *pWhere = 0; /* WHERE clause to scan with */
  112082. NameContext sNameContext; /* Context used to resolve WHERE clause */
  112083. WhereInfo *pWInfo; /* Context used by sqlite3WhereXXX() */
  112084. int iFkIfZero = 0; /* Address of OP_FkIfZero */
  112085. Vdbe *v = sqlite3GetVdbe(pParse);
  112086. assert( pIdx==0 || pIdx->pTable==pTab );
  112087. assert( pIdx==0 || pIdx->nKeyCol==pFKey->nCol );
  112088. assert( pIdx!=0 || pFKey->nCol==1 );
  112089. assert( pIdx!=0 || HasRowid(pTab) );
  112090. if( nIncr<0 ){
  112091. iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0);
  112092. VdbeCoverage(v);
  112093. }
  112094. /* Create an Expr object representing an SQL expression like:
  112095. **
  112096. ** <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...
  112097. **
  112098. ** The collation sequence used for the comparison should be that of
  112099. ** the parent key columns. The affinity of the parent key column should
  112100. ** be applied to each child key value before the comparison takes place.
  112101. */
  112102. for(i=0; i<pFKey->nCol; i++){
  112103. Expr *pLeft; /* Value from parent table row */
  112104. Expr *pRight; /* Column ref to child table */
  112105. Expr *pEq; /* Expression (pLeft = pRight) */
  112106. i16 iCol; /* Index of column in child table */
  112107. const char *zCol; /* Name of column in child table */
  112108. iCol = pIdx ? pIdx->aiColumn[i] : -1;
  112109. pLeft = exprTableRegister(pParse, pTab, regData, iCol);
  112110. iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
  112111. assert( iCol>=0 );
  112112. zCol = pFKey->pFrom->aCol[iCol].zName;
  112113. pRight = sqlite3Expr(db, TK_ID, zCol);
  112114. pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight);
  112115. pWhere = sqlite3ExprAnd(pParse, pWhere, pEq);
  112116. }
  112117. /* If the child table is the same as the parent table, then add terms
  112118. ** to the WHERE clause that prevent this entry from being scanned.
  112119. ** The added WHERE clause terms are like this:
  112120. **
  112121. ** $current_rowid!=rowid
  112122. ** NOT( $current_a==a AND $current_b==b AND ... )
  112123. **
  112124. ** The first form is used for rowid tables. The second form is used
  112125. ** for WITHOUT ROWID tables. In the second form, the *parent* key is
  112126. ** (a,b,...). Either the parent or primary key could be used to
  112127. ** uniquely identify the current row, but the parent key is more convenient
  112128. ** as the required values have already been loaded into registers
  112129. ** by the caller.
  112130. */
  112131. if( pTab==pFKey->pFrom && nIncr>0 ){
  112132. Expr *pNe; /* Expression (pLeft != pRight) */
  112133. Expr *pLeft; /* Value from parent table row */
  112134. Expr *pRight; /* Column ref to child table */
  112135. if( HasRowid(pTab) ){
  112136. pLeft = exprTableRegister(pParse, pTab, regData, -1);
  112137. pRight = exprTableColumn(db, pTab, pSrc->a[0].iCursor, -1);
  112138. pNe = sqlite3PExpr(pParse, TK_NE, pLeft, pRight);
  112139. }else{
  112140. Expr *pEq, *pAll = 0;
  112141. assert( pIdx!=0 );
  112142. for(i=0; i<pIdx->nKeyCol; i++){
  112143. i16 iCol = pIdx->aiColumn[i];
  112144. assert( iCol>=0 );
  112145. pLeft = exprTableRegister(pParse, pTab, regData, iCol);
  112146. pRight = sqlite3Expr(db, TK_ID, pTab->aCol[iCol].zName);
  112147. pEq = sqlite3PExpr(pParse, TK_IS, pLeft, pRight);
  112148. pAll = sqlite3ExprAnd(pParse, pAll, pEq);
  112149. }
  112150. pNe = sqlite3PExpr(pParse, TK_NOT, pAll, 0);
  112151. }
  112152. pWhere = sqlite3ExprAnd(pParse, pWhere, pNe);
  112153. }
  112154. /* Resolve the references in the WHERE clause. */
  112155. memset(&sNameContext, 0, sizeof(NameContext));
  112156. sNameContext.pSrcList = pSrc;
  112157. sNameContext.pParse = pParse;
  112158. sqlite3ResolveExprNames(&sNameContext, pWhere);
  112159. /* Create VDBE to loop through the entries in pSrc that match the WHERE
  112160. ** clause. For each row found, increment either the deferred or immediate
  112161. ** foreign key constraint counter. */
  112162. if( pParse->nErr==0 ){
  112163. pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0, 0, 0);
  112164. sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
  112165. if( pWInfo ){
  112166. sqlite3WhereEnd(pWInfo);
  112167. }
  112168. }
  112169. /* Clean up the WHERE clause constructed above. */
  112170. sqlite3ExprDelete(db, pWhere);
  112171. if( iFkIfZero ){
  112172. sqlite3VdbeJumpHereOrPopInst(v, iFkIfZero);
  112173. }
  112174. }
  112175. /*
  112176. ** This function returns a linked list of FKey objects (connected by
  112177. ** FKey.pNextTo) holding all children of table pTab. For example,
  112178. ** given the following schema:
  112179. **
  112180. ** CREATE TABLE t1(a PRIMARY KEY);
  112181. ** CREATE TABLE t2(b REFERENCES t1(a);
  112182. **
  112183. ** Calling this function with table "t1" as an argument returns a pointer
  112184. ** to the FKey structure representing the foreign key constraint on table
  112185. ** "t2". Calling this function with "t2" as the argument would return a
  112186. ** NULL pointer (as there are no FK constraints for which t2 is the parent
  112187. ** table).
  112188. */
  112189. SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *pTab){
  112190. return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName);
  112191. }
  112192. /*
  112193. ** The second argument is a Trigger structure allocated by the
  112194. ** fkActionTrigger() routine. This function deletes the Trigger structure
  112195. ** and all of its sub-components.
  112196. **
  112197. ** The Trigger structure or any of its sub-components may be allocated from
  112198. ** the lookaside buffer belonging to database handle dbMem.
  112199. */
  112200. static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
  112201. if( p ){
  112202. TriggerStep *pStep = p->step_list;
  112203. sqlite3ExprDelete(dbMem, pStep->pWhere);
  112204. sqlite3ExprListDelete(dbMem, pStep->pExprList);
  112205. sqlite3SelectDelete(dbMem, pStep->pSelect);
  112206. sqlite3ExprDelete(dbMem, p->pWhen);
  112207. sqlite3DbFree(dbMem, p);
  112208. }
  112209. }
  112210. /*
  112211. ** This function is called to generate code that runs when table pTab is
  112212. ** being dropped from the database. The SrcList passed as the second argument
  112213. ** to this function contains a single entry guaranteed to resolve to
  112214. ** table pTab.
  112215. **
  112216. ** Normally, no code is required. However, if either
  112217. **
  112218. ** (a) The table is the parent table of a FK constraint, or
  112219. ** (b) The table is the child table of a deferred FK constraint and it is
  112220. ** determined at runtime that there are outstanding deferred FK
  112221. ** constraint violations in the database,
  112222. **
  112223. ** then the equivalent of "DELETE FROM <tbl>" is executed before dropping
  112224. ** the table from the database. Triggers are disabled while running this
  112225. ** DELETE, but foreign key actions are not.
  112226. */
  112227. SQLITE_PRIVATE void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){
  112228. sqlite3 *db = pParse->db;
  112229. if( (db->flags&SQLITE_ForeignKeys) && !IsVirtual(pTab) ){
  112230. int iSkip = 0;
  112231. Vdbe *v = sqlite3GetVdbe(pParse);
  112232. assert( v ); /* VDBE has already been allocated */
  112233. assert( pTab->pSelect==0 ); /* Not a view */
  112234. if( sqlite3FkReferences(pTab)==0 ){
  112235. /* Search for a deferred foreign key constraint for which this table
  112236. ** is the child table. If one cannot be found, return without
  112237. ** generating any VDBE code. If one can be found, then jump over
  112238. ** the entire DELETE if there are no outstanding deferred constraints
  112239. ** when this statement is run. */
  112240. FKey *p;
  112241. for(p=pTab->pFKey; p; p=p->pNextFrom){
  112242. if( p->isDeferred || (db->flags & SQLITE_DeferFKs) ) break;
  112243. }
  112244. if( !p ) return;
  112245. iSkip = sqlite3VdbeMakeLabel(pParse);
  112246. sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip); VdbeCoverage(v);
  112247. }
  112248. pParse->disableTriggers = 1;
  112249. sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0, 0, 0);
  112250. pParse->disableTriggers = 0;
  112251. /* If the DELETE has generated immediate foreign key constraint
  112252. ** violations, halt the VDBE and return an error at this point, before
  112253. ** any modifications to the schema are made. This is because statement
  112254. ** transactions are not able to rollback schema changes.
  112255. **
  112256. ** If the SQLITE_DeferFKs flag is set, then this is not required, as
  112257. ** the statement transaction will not be rolled back even if FK
  112258. ** constraints are violated.
  112259. */
  112260. if( (db->flags & SQLITE_DeferFKs)==0 ){
  112261. sqlite3VdbeVerifyAbortable(v, OE_Abort);
  112262. sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2);
  112263. VdbeCoverage(v);
  112264. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
  112265. OE_Abort, 0, P4_STATIC, P5_ConstraintFK);
  112266. }
  112267. if( iSkip ){
  112268. sqlite3VdbeResolveLabel(v, iSkip);
  112269. }
  112270. }
  112271. }
  112272. /*
  112273. ** The second argument points to an FKey object representing a foreign key
  112274. ** for which pTab is the child table. An UPDATE statement against pTab
  112275. ** is currently being processed. For each column of the table that is
  112276. ** actually updated, the corresponding element in the aChange[] array
  112277. ** is zero or greater (if a column is unmodified the corresponding element
  112278. ** is set to -1). If the rowid column is modified by the UPDATE statement
  112279. ** the bChngRowid argument is non-zero.
  112280. **
  112281. ** This function returns true if any of the columns that are part of the
  112282. ** child key for FK constraint *p are modified.
  112283. */
  112284. static int fkChildIsModified(
  112285. Table *pTab, /* Table being updated */
  112286. FKey *p, /* Foreign key for which pTab is the child */
  112287. int *aChange, /* Array indicating modified columns */
  112288. int bChngRowid /* True if rowid is modified by this update */
  112289. ){
  112290. int i;
  112291. for(i=0; i<p->nCol; i++){
  112292. int iChildKey = p->aCol[i].iFrom;
  112293. if( aChange[iChildKey]>=0 ) return 1;
  112294. if( iChildKey==pTab->iPKey && bChngRowid ) return 1;
  112295. }
  112296. return 0;
  112297. }
  112298. /*
  112299. ** The second argument points to an FKey object representing a foreign key
  112300. ** for which pTab is the parent table. An UPDATE statement against pTab
  112301. ** is currently being processed. For each column of the table that is
  112302. ** actually updated, the corresponding element in the aChange[] array
  112303. ** is zero or greater (if a column is unmodified the corresponding element
  112304. ** is set to -1). If the rowid column is modified by the UPDATE statement
  112305. ** the bChngRowid argument is non-zero.
  112306. **
  112307. ** This function returns true if any of the columns that are part of the
  112308. ** parent key for FK constraint *p are modified.
  112309. */
  112310. static int fkParentIsModified(
  112311. Table *pTab,
  112312. FKey *p,
  112313. int *aChange,
  112314. int bChngRowid
  112315. ){
  112316. int i;
  112317. for(i=0; i<p->nCol; i++){
  112318. char *zKey = p->aCol[i].zCol;
  112319. int iKey;
  112320. for(iKey=0; iKey<pTab->nCol; iKey++){
  112321. if( aChange[iKey]>=0 || (iKey==pTab->iPKey && bChngRowid) ){
  112322. Column *pCol = &pTab->aCol[iKey];
  112323. if( zKey ){
  112324. if( 0==sqlite3StrICmp(pCol->zName, zKey) ) return 1;
  112325. }else if( pCol->colFlags & COLFLAG_PRIMKEY ){
  112326. return 1;
  112327. }
  112328. }
  112329. }
  112330. }
  112331. return 0;
  112332. }
  112333. /*
  112334. ** Return true if the parser passed as the first argument is being
  112335. ** used to code a trigger that is really a "SET NULL" action belonging
  112336. ** to trigger pFKey.
  112337. */
  112338. static int isSetNullAction(Parse *pParse, FKey *pFKey){
  112339. Parse *pTop = sqlite3ParseToplevel(pParse);
  112340. if( pTop->pTriggerPrg ){
  112341. Trigger *p = pTop->pTriggerPrg->pTrigger;
  112342. if( (p==pFKey->apTrigger[0] && pFKey->aAction[0]==OE_SetNull)
  112343. || (p==pFKey->apTrigger[1] && pFKey->aAction[1]==OE_SetNull)
  112344. ){
  112345. return 1;
  112346. }
  112347. }
  112348. return 0;
  112349. }
  112350. /*
  112351. ** This function is called when inserting, deleting or updating a row of
  112352. ** table pTab to generate VDBE code to perform foreign key constraint
  112353. ** processing for the operation.
  112354. **
  112355. ** For a DELETE operation, parameter regOld is passed the index of the
  112356. ** first register in an array of (pTab->nCol+1) registers containing the
  112357. ** rowid of the row being deleted, followed by each of the column values
  112358. ** of the row being deleted, from left to right. Parameter regNew is passed
  112359. ** zero in this case.
  112360. **
  112361. ** For an INSERT operation, regOld is passed zero and regNew is passed the
  112362. ** first register of an array of (pTab->nCol+1) registers containing the new
  112363. ** row data.
  112364. **
  112365. ** For an UPDATE operation, this function is called twice. Once before
  112366. ** the original record is deleted from the table using the calling convention
  112367. ** described for DELETE. Then again after the original record is deleted
  112368. ** but before the new record is inserted using the INSERT convention.
  112369. */
  112370. SQLITE_PRIVATE void sqlite3FkCheck(
  112371. Parse *pParse, /* Parse context */
  112372. Table *pTab, /* Row is being deleted from this table */
  112373. int regOld, /* Previous row data is stored here */
  112374. int regNew, /* New row data is stored here */
  112375. int *aChange, /* Array indicating UPDATEd columns (or 0) */
  112376. int bChngRowid /* True if rowid is UPDATEd */
  112377. ){
  112378. sqlite3 *db = pParse->db; /* Database handle */
  112379. FKey *pFKey; /* Used to iterate through FKs */
  112380. int iDb; /* Index of database containing pTab */
  112381. const char *zDb; /* Name of database containing pTab */
  112382. int isIgnoreErrors = pParse->disableTriggers;
  112383. /* Exactly one of regOld and regNew should be non-zero. */
  112384. assert( (regOld==0)!=(regNew==0) );
  112385. /* If foreign-keys are disabled, this function is a no-op. */
  112386. if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
  112387. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  112388. zDb = db->aDb[iDb].zDbSName;
  112389. /* Loop through all the foreign key constraints for which pTab is the
  112390. ** child table (the table that the foreign key definition is part of). */
  112391. for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
  112392. Table *pTo; /* Parent table of foreign key pFKey */
  112393. Index *pIdx = 0; /* Index on key columns in pTo */
  112394. int *aiFree = 0;
  112395. int *aiCol;
  112396. int iCol;
  112397. int i;
  112398. int bIgnore = 0;
  112399. if( aChange
  112400. && sqlite3_stricmp(pTab->zName, pFKey->zTo)!=0
  112401. && fkChildIsModified(pTab, pFKey, aChange, bChngRowid)==0
  112402. ){
  112403. continue;
  112404. }
  112405. /* Find the parent table of this foreign key. Also find a unique index
  112406. ** on the parent key columns in the parent table. If either of these
  112407. ** schema items cannot be located, set an error in pParse and return
  112408. ** early. */
  112409. if( pParse->disableTriggers ){
  112410. pTo = sqlite3FindTable(db, pFKey->zTo, zDb);
  112411. }else{
  112412. pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
  112413. }
  112414. if( !pTo || sqlite3FkLocateIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){
  112415. assert( isIgnoreErrors==0 || (regOld!=0 && regNew==0) );
  112416. if( !isIgnoreErrors || db->mallocFailed ) return;
  112417. if( pTo==0 ){
  112418. /* If isIgnoreErrors is true, then a table is being dropped. In this
  112419. ** case SQLite runs a "DELETE FROM xxx" on the table being dropped
  112420. ** before actually dropping it in order to check FK constraints.
  112421. ** If the parent table of an FK constraint on the current table is
  112422. ** missing, behave as if it is empty. i.e. decrement the relevant
  112423. ** FK counter for each row of the current table with non-NULL keys.
  112424. */
  112425. Vdbe *v = sqlite3GetVdbe(pParse);
  112426. int iJump = sqlite3VdbeCurrentAddr(v) + pFKey->nCol + 1;
  112427. for(i=0; i<pFKey->nCol; i++){
  112428. int iFromCol, iReg;
  112429. iFromCol = pFKey->aCol[i].iFrom;
  112430. iReg = sqlite3TableColumnToStorage(pFKey->pFrom,iFromCol) + regOld+1;
  112431. sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iJump); VdbeCoverage(v);
  112432. }
  112433. sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, -1);
  112434. }
  112435. continue;
  112436. }
  112437. assert( pFKey->nCol==1 || (aiFree && pIdx) );
  112438. if( aiFree ){
  112439. aiCol = aiFree;
  112440. }else{
  112441. iCol = pFKey->aCol[0].iFrom;
  112442. aiCol = &iCol;
  112443. }
  112444. for(i=0; i<pFKey->nCol; i++){
  112445. if( aiCol[i]==pTab->iPKey ){
  112446. aiCol[i] = -1;
  112447. }
  112448. assert( pIdx==0 || pIdx->aiColumn[i]>=0 );
  112449. #ifndef SQLITE_OMIT_AUTHORIZATION
  112450. /* Request permission to read the parent key columns. If the
  112451. ** authorization callback returns SQLITE_IGNORE, behave as if any
  112452. ** values read from the parent table are NULL. */
  112453. if( db->xAuth ){
  112454. int rcauth;
  112455. char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zName;
  112456. rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb);
  112457. bIgnore = (rcauth==SQLITE_IGNORE);
  112458. }
  112459. #endif
  112460. }
  112461. /* Take a shared-cache advisory read-lock on the parent table. Allocate
  112462. ** a cursor to use to search the unique index on the parent key columns
  112463. ** in the parent table. */
  112464. sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
  112465. pParse->nTab++;
  112466. if( regOld!=0 ){
  112467. /* A row is being removed from the child table. Search for the parent.
  112468. ** If the parent does not exist, removing the child row resolves an
  112469. ** outstanding foreign key constraint violation. */
  112470. fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1, bIgnore);
  112471. }
  112472. if( regNew!=0 && !isSetNullAction(pParse, pFKey) ){
  112473. /* A row is being added to the child table. If a parent row cannot
  112474. ** be found, adding the child row has violated the FK constraint.
  112475. **
  112476. ** If this operation is being performed as part of a trigger program
  112477. ** that is actually a "SET NULL" action belonging to this very
  112478. ** foreign key, then omit this scan altogether. As all child key
  112479. ** values are guaranteed to be NULL, it is not possible for adding
  112480. ** this row to cause an FK violation. */
  112481. fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1, bIgnore);
  112482. }
  112483. sqlite3DbFree(db, aiFree);
  112484. }
  112485. /* Loop through all the foreign key constraints that refer to this table.
  112486. ** (the "child" constraints) */
  112487. for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
  112488. Index *pIdx = 0; /* Foreign key index for pFKey */
  112489. SrcList *pSrc;
  112490. int *aiCol = 0;
  112491. if( aChange && fkParentIsModified(pTab, pFKey, aChange, bChngRowid)==0 ){
  112492. continue;
  112493. }
  112494. if( !pFKey->isDeferred && !(db->flags & SQLITE_DeferFKs)
  112495. && !pParse->pToplevel && !pParse->isMultiWrite
  112496. ){
  112497. assert( regOld==0 && regNew!=0 );
  112498. /* Inserting a single row into a parent table cannot cause (or fix)
  112499. ** an immediate foreign key violation. So do nothing in this case. */
  112500. continue;
  112501. }
  112502. if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){
  112503. if( !isIgnoreErrors || db->mallocFailed ) return;
  112504. continue;
  112505. }
  112506. assert( aiCol || pFKey->nCol==1 );
  112507. /* Create a SrcList structure containing the child table. We need the
  112508. ** child table as a SrcList for sqlite3WhereBegin() */
  112509. pSrc = sqlite3SrcListAppend(pParse, 0, 0, 0);
  112510. if( pSrc ){
  112511. struct SrcList_item *pItem = pSrc->a;
  112512. pItem->pTab = pFKey->pFrom;
  112513. pItem->zName = pFKey->pFrom->zName;
  112514. pItem->pTab->nTabRef++;
  112515. pItem->iCursor = pParse->nTab++;
  112516. if( regNew!=0 ){
  112517. fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1);
  112518. }
  112519. if( regOld!=0 ){
  112520. int eAction = pFKey->aAction[aChange!=0];
  112521. fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1);
  112522. /* If this is a deferred FK constraint, or a CASCADE or SET NULL
  112523. ** action applies, then any foreign key violations caused by
  112524. ** removing the parent key will be rectified by the action trigger.
  112525. ** So do not set the "may-abort" flag in this case.
  112526. **
  112527. ** Note 1: If the FK is declared "ON UPDATE CASCADE", then the
  112528. ** may-abort flag will eventually be set on this statement anyway
  112529. ** (when this function is called as part of processing the UPDATE
  112530. ** within the action trigger).
  112531. **
  112532. ** Note 2: At first glance it may seem like SQLite could simply omit
  112533. ** all OP_FkCounter related scans when either CASCADE or SET NULL
  112534. ** applies. The trouble starts if the CASCADE or SET NULL action
  112535. ** trigger causes other triggers or action rules attached to the
  112536. ** child table to fire. In these cases the fk constraint counters
  112537. ** might be set incorrectly if any OP_FkCounter related scans are
  112538. ** omitted. */
  112539. if( !pFKey->isDeferred && eAction!=OE_Cascade && eAction!=OE_SetNull ){
  112540. sqlite3MayAbort(pParse);
  112541. }
  112542. }
  112543. pItem->zName = 0;
  112544. sqlite3SrcListDelete(db, pSrc);
  112545. }
  112546. sqlite3DbFree(db, aiCol);
  112547. }
  112548. }
  112549. #define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
  112550. /*
  112551. ** This function is called before generating code to update or delete a
  112552. ** row contained in table pTab.
  112553. */
  112554. SQLITE_PRIVATE u32 sqlite3FkOldmask(
  112555. Parse *pParse, /* Parse context */
  112556. Table *pTab /* Table being modified */
  112557. ){
  112558. u32 mask = 0;
  112559. if( pParse->db->flags&SQLITE_ForeignKeys ){
  112560. FKey *p;
  112561. int i;
  112562. for(p=pTab->pFKey; p; p=p->pNextFrom){
  112563. for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
  112564. }
  112565. for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
  112566. Index *pIdx = 0;
  112567. sqlite3FkLocateIndex(pParse, pTab, p, &pIdx, 0);
  112568. if( pIdx ){
  112569. for(i=0; i<pIdx->nKeyCol; i++){
  112570. assert( pIdx->aiColumn[i]>=0 );
  112571. mask |= COLUMN_MASK(pIdx->aiColumn[i]);
  112572. }
  112573. }
  112574. }
  112575. }
  112576. return mask;
  112577. }
  112578. /*
  112579. ** This function is called before generating code to update or delete a
  112580. ** row contained in table pTab. If the operation is a DELETE, then
  112581. ** parameter aChange is passed a NULL value. For an UPDATE, aChange points
  112582. ** to an array of size N, where N is the number of columns in table pTab.
  112583. ** If the i'th column is not modified by the UPDATE, then the corresponding
  112584. ** entry in the aChange[] array is set to -1. If the column is modified,
  112585. ** the value is 0 or greater. Parameter chngRowid is set to true if the
  112586. ** UPDATE statement modifies the rowid fields of the table.
  112587. **
  112588. ** If any foreign key processing will be required, this function returns
  112589. ** non-zero. If there is no foreign key related processing, this function
  112590. ** returns zero.
  112591. **
  112592. ** For an UPDATE, this function returns 2 if:
  112593. **
  112594. ** * There are any FKs for which pTab is the child and the parent table, or
  112595. ** * the UPDATE modifies one or more parent keys for which the action is
  112596. ** not "NO ACTION" (i.e. is CASCADE, SET DEFAULT or SET NULL).
  112597. **
  112598. ** Or, assuming some other foreign key processing is required, 1.
  112599. */
  112600. SQLITE_PRIVATE int sqlite3FkRequired(
  112601. Parse *pParse, /* Parse context */
  112602. Table *pTab, /* Table being modified */
  112603. int *aChange, /* Non-NULL for UPDATE operations */
  112604. int chngRowid /* True for UPDATE that affects rowid */
  112605. ){
  112606. int eRet = 0;
  112607. if( pParse->db->flags&SQLITE_ForeignKeys ){
  112608. if( !aChange ){
  112609. /* A DELETE operation. Foreign key processing is required if the
  112610. ** table in question is either the child or parent table for any
  112611. ** foreign key constraint. */
  112612. eRet = (sqlite3FkReferences(pTab) || pTab->pFKey);
  112613. }else{
  112614. /* This is an UPDATE. Foreign key processing is only required if the
  112615. ** operation modifies one or more child or parent key columns. */
  112616. FKey *p;
  112617. /* Check if any child key columns are being modified. */
  112618. for(p=pTab->pFKey; p; p=p->pNextFrom){
  112619. if( 0==sqlite3_stricmp(pTab->zName, p->zTo) ) return 2;
  112620. if( fkChildIsModified(pTab, p, aChange, chngRowid) ){
  112621. eRet = 1;
  112622. }
  112623. }
  112624. /* Check if any parent key columns are being modified. */
  112625. for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
  112626. if( fkParentIsModified(pTab, p, aChange, chngRowid) ){
  112627. if( p->aAction[1]!=OE_None ) return 2;
  112628. eRet = 1;
  112629. }
  112630. }
  112631. }
  112632. }
  112633. return eRet;
  112634. }
  112635. /*
  112636. ** This function is called when an UPDATE or DELETE operation is being
  112637. ** compiled on table pTab, which is the parent table of foreign-key pFKey.
  112638. ** If the current operation is an UPDATE, then the pChanges parameter is
  112639. ** passed a pointer to the list of columns being modified. If it is a
  112640. ** DELETE, pChanges is passed a NULL pointer.
  112641. **
  112642. ** It returns a pointer to a Trigger structure containing a trigger
  112643. ** equivalent to the ON UPDATE or ON DELETE action specified by pFKey.
  112644. ** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is
  112645. ** returned (these actions require no special handling by the triggers
  112646. ** sub-system, code for them is created by fkScanChildren()).
  112647. **
  112648. ** For example, if pFKey is the foreign key and pTab is table "p" in
  112649. ** the following schema:
  112650. **
  112651. ** CREATE TABLE p(pk PRIMARY KEY);
  112652. ** CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE);
  112653. **
  112654. ** then the returned trigger structure is equivalent to:
  112655. **
  112656. ** CREATE TRIGGER ... DELETE ON p BEGIN
  112657. ** DELETE FROM c WHERE ck = old.pk;
  112658. ** END;
  112659. **
  112660. ** The returned pointer is cached as part of the foreign key object. It
  112661. ** is eventually freed along with the rest of the foreign key object by
  112662. ** sqlite3FkDelete().
  112663. */
  112664. static Trigger *fkActionTrigger(
  112665. Parse *pParse, /* Parse context */
  112666. Table *pTab, /* Table being updated or deleted from */
  112667. FKey *pFKey, /* Foreign key to get action for */
  112668. ExprList *pChanges /* Change-list for UPDATE, NULL for DELETE */
  112669. ){
  112670. sqlite3 *db = pParse->db; /* Database handle */
  112671. int action; /* One of OE_None, OE_Cascade etc. */
  112672. Trigger *pTrigger; /* Trigger definition to return */
  112673. int iAction = (pChanges!=0); /* 1 for UPDATE, 0 for DELETE */
  112674. action = pFKey->aAction[iAction];
  112675. if( action==OE_Restrict && (db->flags & SQLITE_DeferFKs) ){
  112676. return 0;
  112677. }
  112678. pTrigger = pFKey->apTrigger[iAction];
  112679. if( action!=OE_None && !pTrigger ){
  112680. char const *zFrom; /* Name of child table */
  112681. int nFrom; /* Length in bytes of zFrom */
  112682. Index *pIdx = 0; /* Parent key index for this FK */
  112683. int *aiCol = 0; /* child table cols -> parent key cols */
  112684. TriggerStep *pStep = 0; /* First (only) step of trigger program */
  112685. Expr *pWhere = 0; /* WHERE clause of trigger step */
  112686. ExprList *pList = 0; /* Changes list if ON UPDATE CASCADE */
  112687. Select *pSelect = 0; /* If RESTRICT, "SELECT RAISE(...)" */
  112688. int i; /* Iterator variable */
  112689. Expr *pWhen = 0; /* WHEN clause for the trigger */
  112690. if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
  112691. assert( aiCol || pFKey->nCol==1 );
  112692. for(i=0; i<pFKey->nCol; i++){
  112693. Token tOld = { "old", 3 }; /* Literal "old" token */
  112694. Token tNew = { "new", 3 }; /* Literal "new" token */
  112695. Token tFromCol; /* Name of column in child table */
  112696. Token tToCol; /* Name of column in parent table */
  112697. int iFromCol; /* Idx of column in child table */
  112698. Expr *pEq; /* tFromCol = OLD.tToCol */
  112699. iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
  112700. assert( iFromCol>=0 );
  112701. assert( pIdx!=0 || (pTab->iPKey>=0 && pTab->iPKey<pTab->nCol) );
  112702. assert( pIdx==0 || pIdx->aiColumn[i]>=0 );
  112703. sqlite3TokenInit(&tToCol,
  112704. pTab->aCol[pIdx ? pIdx->aiColumn[i] : pTab->iPKey].zName);
  112705. sqlite3TokenInit(&tFromCol, pFKey->pFrom->aCol[iFromCol].zName);
  112706. /* Create the expression "OLD.zToCol = zFromCol". It is important
  112707. ** that the "OLD.zToCol" term is on the LHS of the = operator, so
  112708. ** that the affinity and collation sequence associated with the
  112709. ** parent table are used for the comparison. */
  112710. pEq = sqlite3PExpr(pParse, TK_EQ,
  112711. sqlite3PExpr(pParse, TK_DOT,
  112712. sqlite3ExprAlloc(db, TK_ID, &tOld, 0),
  112713. sqlite3ExprAlloc(db, TK_ID, &tToCol, 0)),
  112714. sqlite3ExprAlloc(db, TK_ID, &tFromCol, 0)
  112715. );
  112716. pWhere = sqlite3ExprAnd(pParse, pWhere, pEq);
  112717. /* For ON UPDATE, construct the next term of the WHEN clause.
  112718. ** The final WHEN clause will be like this:
  112719. **
  112720. ** WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)
  112721. */
  112722. if( pChanges ){
  112723. pEq = sqlite3PExpr(pParse, TK_IS,
  112724. sqlite3PExpr(pParse, TK_DOT,
  112725. sqlite3ExprAlloc(db, TK_ID, &tOld, 0),
  112726. sqlite3ExprAlloc(db, TK_ID, &tToCol, 0)),
  112727. sqlite3PExpr(pParse, TK_DOT,
  112728. sqlite3ExprAlloc(db, TK_ID, &tNew, 0),
  112729. sqlite3ExprAlloc(db, TK_ID, &tToCol, 0))
  112730. );
  112731. pWhen = sqlite3ExprAnd(pParse, pWhen, pEq);
  112732. }
  112733. if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){
  112734. Expr *pNew;
  112735. if( action==OE_Cascade ){
  112736. pNew = sqlite3PExpr(pParse, TK_DOT,
  112737. sqlite3ExprAlloc(db, TK_ID, &tNew, 0),
  112738. sqlite3ExprAlloc(db, TK_ID, &tToCol, 0));
  112739. }else if( action==OE_SetDflt ){
  112740. Column *pCol = pFKey->pFrom->aCol + iFromCol;
  112741. Expr *pDflt;
  112742. if( pCol->colFlags & COLFLAG_GENERATED ){
  112743. testcase( pCol->colFlags & COLFLAG_VIRTUAL );
  112744. testcase( pCol->colFlags & COLFLAG_STORED );
  112745. pDflt = 0;
  112746. }else{
  112747. pDflt = pCol->pDflt;
  112748. }
  112749. if( pDflt ){
  112750. pNew = sqlite3ExprDup(db, pDflt, 0);
  112751. }else{
  112752. pNew = sqlite3ExprAlloc(db, TK_NULL, 0, 0);
  112753. }
  112754. }else{
  112755. pNew = sqlite3ExprAlloc(db, TK_NULL, 0, 0);
  112756. }
  112757. pList = sqlite3ExprListAppend(pParse, pList, pNew);
  112758. sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);
  112759. }
  112760. }
  112761. sqlite3DbFree(db, aiCol);
  112762. zFrom = pFKey->pFrom->zName;
  112763. nFrom = sqlite3Strlen30(zFrom);
  112764. if( action==OE_Restrict ){
  112765. Token tFrom;
  112766. Expr *pRaise;
  112767. tFrom.z = zFrom;
  112768. tFrom.n = nFrom;
  112769. pRaise = sqlite3Expr(db, TK_RAISE, "FOREIGN KEY constraint failed");
  112770. if( pRaise ){
  112771. pRaise->affExpr = OE_Abort;
  112772. }
  112773. pSelect = sqlite3SelectNew(pParse,
  112774. sqlite3ExprListAppend(pParse, 0, pRaise),
  112775. sqlite3SrcListAppend(pParse, 0, &tFrom, 0),
  112776. pWhere,
  112777. 0, 0, 0, 0, 0
  112778. );
  112779. pWhere = 0;
  112780. }
  112781. /* Disable lookaside memory allocation */
  112782. DisableLookaside;
  112783. pTrigger = (Trigger *)sqlite3DbMallocZero(db,
  112784. sizeof(Trigger) + /* struct Trigger */
  112785. sizeof(TriggerStep) + /* Single step in trigger program */
  112786. nFrom + 1 /* Space for pStep->zTarget */
  112787. );
  112788. if( pTrigger ){
  112789. pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
  112790. pStep->zTarget = (char *)&pStep[1];
  112791. memcpy((char *)pStep->zTarget, zFrom, nFrom);
  112792. pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
  112793. pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
  112794. pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
  112795. if( pWhen ){
  112796. pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0);
  112797. pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
  112798. }
  112799. }
  112800. /* Re-enable the lookaside buffer, if it was disabled earlier. */
  112801. EnableLookaside;
  112802. sqlite3ExprDelete(db, pWhere);
  112803. sqlite3ExprDelete(db, pWhen);
  112804. sqlite3ExprListDelete(db, pList);
  112805. sqlite3SelectDelete(db, pSelect);
  112806. if( db->mallocFailed==1 ){
  112807. fkTriggerDelete(db, pTrigger);
  112808. return 0;
  112809. }
  112810. assert( pStep!=0 );
  112811. assert( pTrigger!=0 );
  112812. switch( action ){
  112813. case OE_Restrict:
  112814. pStep->op = TK_SELECT;
  112815. break;
  112816. case OE_Cascade:
  112817. if( !pChanges ){
  112818. pStep->op = TK_DELETE;
  112819. break;
  112820. }
  112821. default:
  112822. pStep->op = TK_UPDATE;
  112823. }
  112824. pStep->pTrig = pTrigger;
  112825. pTrigger->pSchema = pTab->pSchema;
  112826. pTrigger->pTabSchema = pTab->pSchema;
  112827. pFKey->apTrigger[iAction] = pTrigger;
  112828. pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);
  112829. }
  112830. return pTrigger;
  112831. }
  112832. /*
  112833. ** This function is called when deleting or updating a row to implement
  112834. ** any required CASCADE, SET NULL or SET DEFAULT actions.
  112835. */
  112836. SQLITE_PRIVATE void sqlite3FkActions(
  112837. Parse *pParse, /* Parse context */
  112838. Table *pTab, /* Table being updated or deleted from */
  112839. ExprList *pChanges, /* Change-list for UPDATE, NULL for DELETE */
  112840. int regOld, /* Address of array containing old row */
  112841. int *aChange, /* Array indicating UPDATEd columns (or 0) */
  112842. int bChngRowid /* True if rowid is UPDATEd */
  112843. ){
  112844. /* If foreign-key support is enabled, iterate through all FKs that
  112845. ** refer to table pTab. If there is an action associated with the FK
  112846. ** for this operation (either update or delete), invoke the associated
  112847. ** trigger sub-program. */
  112848. if( pParse->db->flags&SQLITE_ForeignKeys ){
  112849. FKey *pFKey; /* Iterator variable */
  112850. for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
  112851. if( aChange==0 || fkParentIsModified(pTab, pFKey, aChange, bChngRowid) ){
  112852. Trigger *pAct = fkActionTrigger(pParse, pTab, pFKey, pChanges);
  112853. if( pAct ){
  112854. sqlite3CodeRowTriggerDirect(pParse, pAct, pTab, regOld, OE_Abort, 0);
  112855. }
  112856. }
  112857. }
  112858. }
  112859. }
  112860. #endif /* ifndef SQLITE_OMIT_TRIGGER */
  112861. /*
  112862. ** Free all memory associated with foreign key definitions attached to
  112863. ** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
  112864. ** hash table.
  112865. */
  112866. SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *db, Table *pTab){
  112867. FKey *pFKey; /* Iterator variable */
  112868. FKey *pNext; /* Copy of pFKey->pNextFrom */
  112869. assert( db==0 || IsVirtual(pTab)
  112870. || sqlite3SchemaMutexHeld(db, 0, pTab->pSchema) );
  112871. for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
  112872. /* Remove the FK from the fkeyHash hash table. */
  112873. if( !db || db->pnBytesFreed==0 ){
  112874. if( pFKey->pPrevTo ){
  112875. pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
  112876. }else{
  112877. void *p = (void *)pFKey->pNextTo;
  112878. const char *z = (p ? pFKey->pNextTo->zTo : pFKey->zTo);
  112879. sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, p);
  112880. }
  112881. if( pFKey->pNextTo ){
  112882. pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
  112883. }
  112884. }
  112885. /* EV: R-30323-21917 Each foreign key constraint in SQLite is
  112886. ** classified as either immediate or deferred.
  112887. */
  112888. assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );
  112889. /* Delete any triggers created to implement actions for this FK. */
  112890. #ifndef SQLITE_OMIT_TRIGGER
  112891. fkTriggerDelete(db, pFKey->apTrigger[0]);
  112892. fkTriggerDelete(db, pFKey->apTrigger[1]);
  112893. #endif
  112894. pNext = pFKey->pNextFrom;
  112895. sqlite3DbFree(db, pFKey);
  112896. }
  112897. }
  112898. #endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */
  112899. /************** End of fkey.c ************************************************/
  112900. /************** Begin file insert.c ******************************************/
  112901. /*
  112902. ** 2001 September 15
  112903. **
  112904. ** The author disclaims copyright to this source code. In place of
  112905. ** a legal notice, here is a blessing:
  112906. **
  112907. ** May you do good and not evil.
  112908. ** May you find forgiveness for yourself and forgive others.
  112909. ** May you share freely, never taking more than you give.
  112910. **
  112911. *************************************************************************
  112912. ** This file contains C code routines that are called by the parser
  112913. ** to handle INSERT statements in SQLite.
  112914. */
  112915. /* #include "sqliteInt.h" */
  112916. /*
  112917. ** Generate code that will
  112918. **
  112919. ** (1) acquire a lock for table pTab then
  112920. ** (2) open pTab as cursor iCur.
  112921. **
  112922. ** If pTab is a WITHOUT ROWID table, then it is the PRIMARY KEY index
  112923. ** for that table that is actually opened.
  112924. */
  112925. SQLITE_PRIVATE void sqlite3OpenTable(
  112926. Parse *pParse, /* Generate code into this VDBE */
  112927. int iCur, /* The cursor number of the table */
  112928. int iDb, /* The database index in sqlite3.aDb[] */
  112929. Table *pTab, /* The table to be opened */
  112930. int opcode /* OP_OpenRead or OP_OpenWrite */
  112931. ){
  112932. Vdbe *v;
  112933. assert( !IsVirtual(pTab) );
  112934. v = sqlite3GetVdbe(pParse);
  112935. assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
  112936. sqlite3TableLock(pParse, iDb, pTab->tnum,
  112937. (opcode==OP_OpenWrite)?1:0, pTab->zName);
  112938. if( HasRowid(pTab) ){
  112939. sqlite3VdbeAddOp4Int(v, opcode, iCur, pTab->tnum, iDb, pTab->nNVCol);
  112940. VdbeComment((v, "%s", pTab->zName));
  112941. }else{
  112942. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  112943. assert( pPk!=0 );
  112944. assert( pPk->tnum==pTab->tnum );
  112945. sqlite3VdbeAddOp3(v, opcode, iCur, pPk->tnum, iDb);
  112946. sqlite3VdbeSetP4KeyInfo(pParse, pPk);
  112947. VdbeComment((v, "%s", pTab->zName));
  112948. }
  112949. }
  112950. /*
  112951. ** Return a pointer to the column affinity string associated with index
  112952. ** pIdx. A column affinity string has one character for each column in
  112953. ** the table, according to the affinity of the column:
  112954. **
  112955. ** Character Column affinity
  112956. ** ------------------------------
  112957. ** 'A' BLOB
  112958. ** 'B' TEXT
  112959. ** 'C' NUMERIC
  112960. ** 'D' INTEGER
  112961. ** 'F' REAL
  112962. **
  112963. ** An extra 'D' is appended to the end of the string to cover the
  112964. ** rowid that appears as the last column in every index.
  112965. **
  112966. ** Memory for the buffer containing the column index affinity string
  112967. ** is managed along with the rest of the Index structure. It will be
  112968. ** released when sqlite3DeleteIndex() is called.
  112969. */
  112970. SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(sqlite3 *db, Index *pIdx){
  112971. if( !pIdx->zColAff ){
  112972. /* The first time a column affinity string for a particular index is
  112973. ** required, it is allocated and populated here. It is then stored as
  112974. ** a member of the Index structure for subsequent use.
  112975. **
  112976. ** The column affinity string will eventually be deleted by
  112977. ** sqliteDeleteIndex() when the Index structure itself is cleaned
  112978. ** up.
  112979. */
  112980. int n;
  112981. Table *pTab = pIdx->pTable;
  112982. pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+1);
  112983. if( !pIdx->zColAff ){
  112984. sqlite3OomFault(db);
  112985. return 0;
  112986. }
  112987. for(n=0; n<pIdx->nColumn; n++){
  112988. i16 x = pIdx->aiColumn[n];
  112989. char aff;
  112990. if( x>=0 ){
  112991. aff = pTab->aCol[x].affinity;
  112992. }else if( x==XN_ROWID ){
  112993. aff = SQLITE_AFF_INTEGER;
  112994. }else{
  112995. assert( x==XN_EXPR );
  112996. assert( pIdx->aColExpr!=0 );
  112997. aff = sqlite3ExprAffinity(pIdx->aColExpr->a[n].pExpr);
  112998. }
  112999. if( aff<SQLITE_AFF_BLOB ) aff = SQLITE_AFF_BLOB;
  113000. if( aff>SQLITE_AFF_NUMERIC) aff = SQLITE_AFF_NUMERIC;
  113001. pIdx->zColAff[n] = aff;
  113002. }
  113003. pIdx->zColAff[n] = 0;
  113004. }
  113005. return pIdx->zColAff;
  113006. }
  113007. /*
  113008. ** Compute the affinity string for table pTab, if it has not already been
  113009. ** computed. As an optimization, omit trailing SQLITE_AFF_BLOB affinities.
  113010. **
  113011. ** If the affinity exists (if it is no entirely SQLITE_AFF_BLOB values) and
  113012. ** if iReg>0 then code an OP_Affinity opcode that will set the affinities
  113013. ** for register iReg and following. Or if affinities exists and iReg==0,
  113014. ** then just set the P4 operand of the previous opcode (which should be
  113015. ** an OP_MakeRecord) to the affinity string.
  113016. **
  113017. ** A column affinity string has one character per column:
  113018. **
  113019. ** Character Column affinity
  113020. ** ------------------------------
  113021. ** 'A' BLOB
  113022. ** 'B' TEXT
  113023. ** 'C' NUMERIC
  113024. ** 'D' INTEGER
  113025. ** 'E' REAL
  113026. */
  113027. SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe *v, Table *pTab, int iReg){
  113028. int i, j;
  113029. char *zColAff = pTab->zColAff;
  113030. if( zColAff==0 ){
  113031. sqlite3 *db = sqlite3VdbeDb(v);
  113032. zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
  113033. if( !zColAff ){
  113034. sqlite3OomFault(db);
  113035. return;
  113036. }
  113037. for(i=j=0; i<pTab->nCol; i++){
  113038. assert( pTab->aCol[i].affinity!=0 );
  113039. if( (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0 ){
  113040. zColAff[j++] = pTab->aCol[i].affinity;
  113041. }
  113042. }
  113043. do{
  113044. zColAff[j--] = 0;
  113045. }while( j>=0 && zColAff[j]<=SQLITE_AFF_BLOB );
  113046. pTab->zColAff = zColAff;
  113047. }
  113048. assert( zColAff!=0 );
  113049. i = sqlite3Strlen30NN(zColAff);
  113050. if( i ){
  113051. if( iReg ){
  113052. sqlite3VdbeAddOp4(v, OP_Affinity, iReg, i, 0, zColAff, i);
  113053. }else{
  113054. sqlite3VdbeChangeP4(v, -1, zColAff, i);
  113055. }
  113056. }
  113057. }
  113058. /*
  113059. ** Return non-zero if the table pTab in database iDb or any of its indices
  113060. ** have been opened at any point in the VDBE program. This is used to see if
  113061. ** a statement of the form "INSERT INTO <iDb, pTab> SELECT ..." can
  113062. ** run without using a temporary table for the results of the SELECT.
  113063. */
  113064. static int readsTable(Parse *p, int iDb, Table *pTab){
  113065. Vdbe *v = sqlite3GetVdbe(p);
  113066. int i;
  113067. int iEnd = sqlite3VdbeCurrentAddr(v);
  113068. #ifndef SQLITE_OMIT_VIRTUALTABLE
  113069. VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
  113070. #endif
  113071. for(i=1; i<iEnd; i++){
  113072. VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
  113073. assert( pOp!=0 );
  113074. if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
  113075. Index *pIndex;
  113076. int tnum = pOp->p2;
  113077. if( tnum==pTab->tnum ){
  113078. return 1;
  113079. }
  113080. for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
  113081. if( tnum==pIndex->tnum ){
  113082. return 1;
  113083. }
  113084. }
  113085. }
  113086. #ifndef SQLITE_OMIT_VIRTUALTABLE
  113087. if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
  113088. assert( pOp->p4.pVtab!=0 );
  113089. assert( pOp->p4type==P4_VTAB );
  113090. return 1;
  113091. }
  113092. #endif
  113093. }
  113094. return 0;
  113095. }
  113096. /* This walker callback will compute the union of colFlags flags for all
  113097. ** referenced columns in a CHECK constraint or generated column expression.
  113098. */
  113099. static int exprColumnFlagUnion(Walker *pWalker, Expr *pExpr){
  113100. if( pExpr->op==TK_COLUMN && pExpr->iColumn>=0 ){
  113101. assert( pExpr->iColumn < pWalker->u.pTab->nCol );
  113102. pWalker->eCode |= pWalker->u.pTab->aCol[pExpr->iColumn].colFlags;
  113103. }
  113104. return WRC_Continue;
  113105. }
  113106. #ifndef SQLITE_OMIT_GENERATED_COLUMNS
  113107. /*
  113108. ** All regular columns for table pTab have been puts into registers
  113109. ** starting with iRegStore. The registers that correspond to STORED
  113110. ** or VIRTUAL columns have not yet been initialized. This routine goes
  113111. ** back and computes the values for those columns based on the previously
  113112. ** computed normal columns.
  113113. */
  113114. SQLITE_PRIVATE void sqlite3ComputeGeneratedColumns(
  113115. Parse *pParse, /* Parsing context */
  113116. int iRegStore, /* Register holding the first column */
  113117. Table *pTab /* The table */
  113118. ){
  113119. int i;
  113120. Walker w;
  113121. Column *pRedo;
  113122. int eProgress;
  113123. VdbeOp *pOp;
  113124. assert( pTab->tabFlags & TF_HasGenerated );
  113125. testcase( pTab->tabFlags & TF_HasVirtual );
  113126. testcase( pTab->tabFlags & TF_HasStored );
  113127. /* Before computing generated columns, first go through and make sure
  113128. ** that appropriate affinity has been applied to the regular columns
  113129. */
  113130. sqlite3TableAffinity(pParse->pVdbe, pTab, iRegStore);
  113131. if( (pTab->tabFlags & TF_HasStored)!=0
  113132. && (pOp = sqlite3VdbeGetOp(pParse->pVdbe,-1))->opcode==OP_Affinity
  113133. ){
  113134. /* Change the OP_Affinity argument to '@' (NONE) for all stored
  113135. ** columns. '@' is the no-op affinity and those columns have not
  113136. ** yet been computed. */
  113137. int ii, jj;
  113138. char *zP4 = pOp->p4.z;
  113139. assert( zP4!=0 );
  113140. assert( pOp->p4type==P4_DYNAMIC );
  113141. for(ii=jj=0; zP4[jj]; ii++){
  113142. if( pTab->aCol[ii].colFlags & COLFLAG_VIRTUAL ){
  113143. continue;
  113144. }
  113145. if( pTab->aCol[ii].colFlags & COLFLAG_STORED ){
  113146. zP4[jj] = SQLITE_AFF_NONE;
  113147. }
  113148. jj++;
  113149. }
  113150. }
  113151. /* Because there can be multiple generated columns that refer to one another,
  113152. ** this is a two-pass algorithm. On the first pass, mark all generated
  113153. ** columns as "not available".
  113154. */
  113155. for(i=0; i<pTab->nCol; i++){
  113156. if( pTab->aCol[i].colFlags & COLFLAG_GENERATED ){
  113157. testcase( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL );
  113158. testcase( pTab->aCol[i].colFlags & COLFLAG_STORED );
  113159. pTab->aCol[i].colFlags |= COLFLAG_NOTAVAIL;
  113160. }
  113161. }
  113162. w.u.pTab = pTab;
  113163. w.xExprCallback = exprColumnFlagUnion;
  113164. w.xSelectCallback = 0;
  113165. w.xSelectCallback2 = 0;
  113166. /* On the second pass, compute the value of each NOT-AVAILABLE column.
  113167. ** Companion code in the TK_COLUMN case of sqlite3ExprCodeTarget() will
  113168. ** compute dependencies and mark remove the COLSPAN_NOTAVAIL mark, as
  113169. ** they are needed.
  113170. */
  113171. pParse->iSelfTab = -iRegStore;
  113172. do{
  113173. eProgress = 0;
  113174. pRedo = 0;
  113175. for(i=0; i<pTab->nCol; i++){
  113176. Column *pCol = pTab->aCol + i;
  113177. if( (pCol->colFlags & COLFLAG_NOTAVAIL)!=0 ){
  113178. int x;
  113179. pCol->colFlags |= COLFLAG_BUSY;
  113180. w.eCode = 0;
  113181. sqlite3WalkExpr(&w, pCol->pDflt);
  113182. pCol->colFlags &= ~COLFLAG_BUSY;
  113183. if( w.eCode & COLFLAG_NOTAVAIL ){
  113184. pRedo = pCol;
  113185. continue;
  113186. }
  113187. eProgress = 1;
  113188. assert( pCol->colFlags & COLFLAG_GENERATED );
  113189. x = sqlite3TableColumnToStorage(pTab, i) + iRegStore;
  113190. sqlite3ExprCodeGeneratedColumn(pParse, pCol, x);
  113191. pCol->colFlags &= ~COLFLAG_NOTAVAIL;
  113192. }
  113193. }
  113194. }while( pRedo && eProgress );
  113195. if( pRedo ){
  113196. sqlite3ErrorMsg(pParse, "generated column loop on \"%s\"", pRedo->zName);
  113197. }
  113198. pParse->iSelfTab = 0;
  113199. }
  113200. #endif /* SQLITE_OMIT_GENERATED_COLUMNS */
  113201. #ifndef SQLITE_OMIT_AUTOINCREMENT
  113202. /*
  113203. ** Locate or create an AutoincInfo structure associated with table pTab
  113204. ** which is in database iDb. Return the register number for the register
  113205. ** that holds the maximum rowid. Return zero if pTab is not an AUTOINCREMENT
  113206. ** table. (Also return zero when doing a VACUUM since we do not want to
  113207. ** update the AUTOINCREMENT counters during a VACUUM.)
  113208. **
  113209. ** There is at most one AutoincInfo structure per table even if the
  113210. ** same table is autoincremented multiple times due to inserts within
  113211. ** triggers. A new AutoincInfo structure is created if this is the
  113212. ** first use of table pTab. On 2nd and subsequent uses, the original
  113213. ** AutoincInfo structure is used.
  113214. **
  113215. ** Four consecutive registers are allocated:
  113216. **
  113217. ** (1) The name of the pTab table.
  113218. ** (2) The maximum ROWID of pTab.
  113219. ** (3) The rowid in sqlite_sequence of pTab
  113220. ** (4) The original value of the max ROWID in pTab, or NULL if none
  113221. **
  113222. ** The 2nd register is the one that is returned. That is all the
  113223. ** insert routine needs to know about.
  113224. */
  113225. static int autoIncBegin(
  113226. Parse *pParse, /* Parsing context */
  113227. int iDb, /* Index of the database holding pTab */
  113228. Table *pTab /* The table we are writing to */
  113229. ){
  113230. int memId = 0; /* Register holding maximum rowid */
  113231. assert( pParse->db->aDb[iDb].pSchema!=0 );
  113232. if( (pTab->tabFlags & TF_Autoincrement)!=0
  113233. && (pParse->db->mDbFlags & DBFLAG_Vacuum)==0
  113234. ){
  113235. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  113236. AutoincInfo *pInfo;
  113237. Table *pSeqTab = pParse->db->aDb[iDb].pSchema->pSeqTab;
  113238. /* Verify that the sqlite_sequence table exists and is an ordinary
  113239. ** rowid table with exactly two columns.
  113240. ** Ticket d8dc2b3a58cd5dc2918a1d4acb 2018-05-23 */
  113241. if( pSeqTab==0
  113242. || !HasRowid(pSeqTab)
  113243. || IsVirtual(pSeqTab)
  113244. || pSeqTab->nCol!=2
  113245. ){
  113246. pParse->nErr++;
  113247. pParse->rc = SQLITE_CORRUPT_SEQUENCE;
  113248. return 0;
  113249. }
  113250. pInfo = pToplevel->pAinc;
  113251. while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
  113252. if( pInfo==0 ){
  113253. pInfo = sqlite3DbMallocRawNN(pParse->db, sizeof(*pInfo));
  113254. if( pInfo==0 ) return 0;
  113255. pInfo->pNext = pToplevel->pAinc;
  113256. pToplevel->pAinc = pInfo;
  113257. pInfo->pTab = pTab;
  113258. pInfo->iDb = iDb;
  113259. pToplevel->nMem++; /* Register to hold name of table */
  113260. pInfo->regCtr = ++pToplevel->nMem; /* Max rowid register */
  113261. pToplevel->nMem +=2; /* Rowid in sqlite_sequence + orig max val */
  113262. }
  113263. memId = pInfo->regCtr;
  113264. }
  113265. return memId;
  113266. }
  113267. /*
  113268. ** This routine generates code that will initialize all of the
  113269. ** register used by the autoincrement tracker.
  113270. */
  113271. SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse){
  113272. AutoincInfo *p; /* Information about an AUTOINCREMENT */
  113273. sqlite3 *db = pParse->db; /* The database connection */
  113274. Db *pDb; /* Database only autoinc table */
  113275. int memId; /* Register holding max rowid */
  113276. Vdbe *v = pParse->pVdbe; /* VDBE under construction */
  113277. /* This routine is never called during trigger-generation. It is
  113278. ** only called from the top-level */
  113279. assert( pParse->pTriggerTab==0 );
  113280. assert( sqlite3IsToplevel(pParse) );
  113281. assert( v ); /* We failed long ago if this is not so */
  113282. for(p = pParse->pAinc; p; p = p->pNext){
  113283. static const int iLn = VDBE_OFFSET_LINENO(2);
  113284. static const VdbeOpList autoInc[] = {
  113285. /* 0 */ {OP_Null, 0, 0, 0},
  113286. /* 1 */ {OP_Rewind, 0, 10, 0},
  113287. /* 2 */ {OP_Column, 0, 0, 0},
  113288. /* 3 */ {OP_Ne, 0, 9, 0},
  113289. /* 4 */ {OP_Rowid, 0, 0, 0},
  113290. /* 5 */ {OP_Column, 0, 1, 0},
  113291. /* 6 */ {OP_AddImm, 0, 0, 0},
  113292. /* 7 */ {OP_Copy, 0, 0, 0},
  113293. /* 8 */ {OP_Goto, 0, 11, 0},
  113294. /* 9 */ {OP_Next, 0, 2, 0},
  113295. /* 10 */ {OP_Integer, 0, 0, 0},
  113296. /* 11 */ {OP_Close, 0, 0, 0}
  113297. };
  113298. VdbeOp *aOp;
  113299. pDb = &db->aDb[p->iDb];
  113300. memId = p->regCtr;
  113301. assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
  113302. sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
  113303. sqlite3VdbeLoadString(v, memId-1, p->pTab->zName);
  113304. aOp = sqlite3VdbeAddOpList(v, ArraySize(autoInc), autoInc, iLn);
  113305. if( aOp==0 ) break;
  113306. aOp[0].p2 = memId;
  113307. aOp[0].p3 = memId+2;
  113308. aOp[2].p3 = memId;
  113309. aOp[3].p1 = memId-1;
  113310. aOp[3].p3 = memId;
  113311. aOp[3].p5 = SQLITE_JUMPIFNULL;
  113312. aOp[4].p2 = memId+1;
  113313. aOp[5].p3 = memId;
  113314. aOp[6].p1 = memId;
  113315. aOp[7].p2 = memId+2;
  113316. aOp[7].p1 = memId;
  113317. aOp[10].p2 = memId;
  113318. if( pParse->nTab==0 ) pParse->nTab = 1;
  113319. }
  113320. }
  113321. /*
  113322. ** Update the maximum rowid for an autoincrement calculation.
  113323. **
  113324. ** This routine should be called when the regRowid register holds a
  113325. ** new rowid that is about to be inserted. If that new rowid is
  113326. ** larger than the maximum rowid in the memId memory cell, then the
  113327. ** memory cell is updated.
  113328. */
  113329. static void autoIncStep(Parse *pParse, int memId, int regRowid){
  113330. if( memId>0 ){
  113331. sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
  113332. }
  113333. }
  113334. /*
  113335. ** This routine generates the code needed to write autoincrement
  113336. ** maximum rowid values back into the sqlite_sequence register.
  113337. ** Every statement that might do an INSERT into an autoincrement
  113338. ** table (either directly or through triggers) needs to call this
  113339. ** routine just before the "exit" code.
  113340. */
  113341. static SQLITE_NOINLINE void autoIncrementEnd(Parse *pParse){
  113342. AutoincInfo *p;
  113343. Vdbe *v = pParse->pVdbe;
  113344. sqlite3 *db = pParse->db;
  113345. assert( v );
  113346. for(p = pParse->pAinc; p; p = p->pNext){
  113347. static const int iLn = VDBE_OFFSET_LINENO(2);
  113348. static const VdbeOpList autoIncEnd[] = {
  113349. /* 0 */ {OP_NotNull, 0, 2, 0},
  113350. /* 1 */ {OP_NewRowid, 0, 0, 0},
  113351. /* 2 */ {OP_MakeRecord, 0, 2, 0},
  113352. /* 3 */ {OP_Insert, 0, 0, 0},
  113353. /* 4 */ {OP_Close, 0, 0, 0}
  113354. };
  113355. VdbeOp *aOp;
  113356. Db *pDb = &db->aDb[p->iDb];
  113357. int iRec;
  113358. int memId = p->regCtr;
  113359. iRec = sqlite3GetTempReg(pParse);
  113360. assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
  113361. sqlite3VdbeAddOp3(v, OP_Le, memId+2, sqlite3VdbeCurrentAddr(v)+7, memId);
  113362. VdbeCoverage(v);
  113363. sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
  113364. aOp = sqlite3VdbeAddOpList(v, ArraySize(autoIncEnd), autoIncEnd, iLn);
  113365. if( aOp==0 ) break;
  113366. aOp[0].p1 = memId+1;
  113367. aOp[1].p2 = memId+1;
  113368. aOp[2].p1 = memId-1;
  113369. aOp[2].p3 = iRec;
  113370. aOp[3].p2 = iRec;
  113371. aOp[3].p3 = memId+1;
  113372. aOp[3].p5 = OPFLAG_APPEND;
  113373. sqlite3ReleaseTempReg(pParse, iRec);
  113374. }
  113375. }
  113376. SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse){
  113377. if( pParse->pAinc ) autoIncrementEnd(pParse);
  113378. }
  113379. #else
  113380. /*
  113381. ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
  113382. ** above are all no-ops
  113383. */
  113384. # define autoIncBegin(A,B,C) (0)
  113385. # define autoIncStep(A,B,C)
  113386. #endif /* SQLITE_OMIT_AUTOINCREMENT */
  113387. /* Forward declaration */
  113388. static int xferOptimization(
  113389. Parse *pParse, /* Parser context */
  113390. Table *pDest, /* The table we are inserting into */
  113391. Select *pSelect, /* A SELECT statement to use as the data source */
  113392. int onError, /* How to handle constraint errors */
  113393. int iDbDest /* The database of pDest */
  113394. );
  113395. /*
  113396. ** This routine is called to handle SQL of the following forms:
  113397. **
  113398. ** insert into TABLE (IDLIST) values(EXPRLIST),(EXPRLIST),...
  113399. ** insert into TABLE (IDLIST) select
  113400. ** insert into TABLE (IDLIST) default values
  113401. **
  113402. ** The IDLIST following the table name is always optional. If omitted,
  113403. ** then a list of all (non-hidden) columns for the table is substituted.
  113404. ** The IDLIST appears in the pColumn parameter. pColumn is NULL if IDLIST
  113405. ** is omitted.
  113406. **
  113407. ** For the pSelect parameter holds the values to be inserted for the
  113408. ** first two forms shown above. A VALUES clause is really just short-hand
  113409. ** for a SELECT statement that omits the FROM clause and everything else
  113410. ** that follows. If the pSelect parameter is NULL, that means that the
  113411. ** DEFAULT VALUES form of the INSERT statement is intended.
  113412. **
  113413. ** The code generated follows one of four templates. For a simple
  113414. ** insert with data coming from a single-row VALUES clause, the code executes
  113415. ** once straight down through. Pseudo-code follows (we call this
  113416. ** the "1st template"):
  113417. **
  113418. ** open write cursor to <table> and its indices
  113419. ** put VALUES clause expressions into registers
  113420. ** write the resulting record into <table>
  113421. ** cleanup
  113422. **
  113423. ** The three remaining templates assume the statement is of the form
  113424. **
  113425. ** INSERT INTO <table> SELECT ...
  113426. **
  113427. ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
  113428. ** in other words if the SELECT pulls all columns from a single table
  113429. ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
  113430. ** if <table2> and <table1> are distinct tables but have identical
  113431. ** schemas, including all the same indices, then a special optimization
  113432. ** is invoked that copies raw records from <table2> over to <table1>.
  113433. ** See the xferOptimization() function for the implementation of this
  113434. ** template. This is the 2nd template.
  113435. **
  113436. ** open a write cursor to <table>
  113437. ** open read cursor on <table2>
  113438. ** transfer all records in <table2> over to <table>
  113439. ** close cursors
  113440. ** foreach index on <table>
  113441. ** open a write cursor on the <table> index
  113442. ** open a read cursor on the corresponding <table2> index
  113443. ** transfer all records from the read to the write cursors
  113444. ** close cursors
  113445. ** end foreach
  113446. **
  113447. ** The 3rd template is for when the second template does not apply
  113448. ** and the SELECT clause does not read from <table> at any time.
  113449. ** The generated code follows this template:
  113450. **
  113451. ** X <- A
  113452. ** goto B
  113453. ** A: setup for the SELECT
  113454. ** loop over the rows in the SELECT
  113455. ** load values into registers R..R+n
  113456. ** yield X
  113457. ** end loop
  113458. ** cleanup after the SELECT
  113459. ** end-coroutine X
  113460. ** B: open write cursor to <table> and its indices
  113461. ** C: yield X, at EOF goto D
  113462. ** insert the select result into <table> from R..R+n
  113463. ** goto C
  113464. ** D: cleanup
  113465. **
  113466. ** The 4th template is used if the insert statement takes its
  113467. ** values from a SELECT but the data is being inserted into a table
  113468. ** that is also read as part of the SELECT. In the third form,
  113469. ** we have to use an intermediate table to store the results of
  113470. ** the select. The template is like this:
  113471. **
  113472. ** X <- A
  113473. ** goto B
  113474. ** A: setup for the SELECT
  113475. ** loop over the tables in the SELECT
  113476. ** load value into register R..R+n
  113477. ** yield X
  113478. ** end loop
  113479. ** cleanup after the SELECT
  113480. ** end co-routine R
  113481. ** B: open temp table
  113482. ** L: yield X, at EOF goto M
  113483. ** insert row from R..R+n into temp table
  113484. ** goto L
  113485. ** M: open write cursor to <table> and its indices
  113486. ** rewind temp table
  113487. ** C: loop over rows of intermediate table
  113488. ** transfer values form intermediate table into <table>
  113489. ** end loop
  113490. ** D: cleanup
  113491. */
  113492. SQLITE_PRIVATE void sqlite3Insert(
  113493. Parse *pParse, /* Parser context */
  113494. SrcList *pTabList, /* Name of table into which we are inserting */
  113495. Select *pSelect, /* A SELECT statement to use as the data source */
  113496. IdList *pColumn, /* Column names corresponding to IDLIST, or NULL. */
  113497. int onError, /* How to handle constraint errors */
  113498. Upsert *pUpsert /* ON CONFLICT clauses for upsert, or NULL */
  113499. ){
  113500. sqlite3 *db; /* The main database structure */
  113501. Table *pTab; /* The table to insert into. aka TABLE */
  113502. int i, j; /* Loop counters */
  113503. Vdbe *v; /* Generate code into this virtual machine */
  113504. Index *pIdx; /* For looping over indices of the table */
  113505. int nColumn; /* Number of columns in the data */
  113506. int nHidden = 0; /* Number of hidden columns if TABLE is virtual */
  113507. int iDataCur = 0; /* VDBE cursor that is the main data repository */
  113508. int iIdxCur = 0; /* First index cursor */
  113509. int ipkColumn = -1; /* Column that is the INTEGER PRIMARY KEY */
  113510. int endOfLoop; /* Label for the end of the insertion loop */
  113511. int srcTab = 0; /* Data comes from this temporary cursor if >=0 */
  113512. int addrInsTop = 0; /* Jump to label "D" */
  113513. int addrCont = 0; /* Top of insert loop. Label "C" in templates 3 and 4 */
  113514. SelectDest dest; /* Destination for SELECT on rhs of INSERT */
  113515. int iDb; /* Index of database holding TABLE */
  113516. u8 useTempTable = 0; /* Store SELECT results in intermediate table */
  113517. u8 appendFlag = 0; /* True if the insert is likely to be an append */
  113518. u8 withoutRowid; /* 0 for normal table. 1 for WITHOUT ROWID table */
  113519. u8 bIdListInOrder; /* True if IDLIST is in table order */
  113520. ExprList *pList = 0; /* List of VALUES() to be inserted */
  113521. int iRegStore; /* Register in which to store next column */
  113522. /* Register allocations */
  113523. int regFromSelect = 0;/* Base register for data coming from SELECT */
  113524. int regAutoinc = 0; /* Register holding the AUTOINCREMENT counter */
  113525. int regRowCount = 0; /* Memory cell used for the row counter */
  113526. int regIns; /* Block of regs holding rowid+data being inserted */
  113527. int regRowid; /* registers holding insert rowid */
  113528. int regData; /* register holding first column to insert */
  113529. int *aRegIdx = 0; /* One register allocated to each index */
  113530. #ifndef SQLITE_OMIT_TRIGGER
  113531. int isView; /* True if attempting to insert into a view */
  113532. Trigger *pTrigger; /* List of triggers on pTab, if required */
  113533. int tmask; /* Mask of trigger times */
  113534. #endif
  113535. db = pParse->db;
  113536. if( pParse->nErr || db->mallocFailed ){
  113537. goto insert_cleanup;
  113538. }
  113539. dest.iSDParm = 0; /* Suppress a harmless compiler warning */
  113540. /* If the Select object is really just a simple VALUES() list with a
  113541. ** single row (the common case) then keep that one row of values
  113542. ** and discard the other (unused) parts of the pSelect object
  113543. */
  113544. if( pSelect && (pSelect->selFlags & SF_Values)!=0 && pSelect->pPrior==0 ){
  113545. pList = pSelect->pEList;
  113546. pSelect->pEList = 0;
  113547. sqlite3SelectDelete(db, pSelect);
  113548. pSelect = 0;
  113549. }
  113550. /* Locate the table into which we will be inserting new information.
  113551. */
  113552. assert( pTabList->nSrc==1 );
  113553. pTab = sqlite3SrcListLookup(pParse, pTabList);
  113554. if( pTab==0 ){
  113555. goto insert_cleanup;
  113556. }
  113557. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  113558. assert( iDb<db->nDb );
  113559. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0,
  113560. db->aDb[iDb].zDbSName) ){
  113561. goto insert_cleanup;
  113562. }
  113563. withoutRowid = !HasRowid(pTab);
  113564. /* Figure out if we have any triggers and if the table being
  113565. ** inserted into is a view
  113566. */
  113567. #ifndef SQLITE_OMIT_TRIGGER
  113568. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
  113569. isView = pTab->pSelect!=0;
  113570. #else
  113571. # define pTrigger 0
  113572. # define tmask 0
  113573. # define isView 0
  113574. #endif
  113575. #ifdef SQLITE_OMIT_VIEW
  113576. # undef isView
  113577. # define isView 0
  113578. #endif
  113579. assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
  113580. /* If pTab is really a view, make sure it has been initialized.
  113581. ** ViewGetColumnNames() is a no-op if pTab is not a view.
  113582. */
  113583. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  113584. goto insert_cleanup;
  113585. }
  113586. /* Cannot insert into a read-only table.
  113587. */
  113588. if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
  113589. goto insert_cleanup;
  113590. }
  113591. /* Allocate a VDBE
  113592. */
  113593. v = sqlite3GetVdbe(pParse);
  113594. if( v==0 ) goto insert_cleanup;
  113595. if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
  113596. sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
  113597. #ifndef SQLITE_OMIT_XFER_OPT
  113598. /* If the statement is of the form
  113599. **
  113600. ** INSERT INTO <table1> SELECT * FROM <table2>;
  113601. **
  113602. ** Then special optimizations can be applied that make the transfer
  113603. ** very fast and which reduce fragmentation of indices.
  113604. **
  113605. ** This is the 2nd template.
  113606. */
  113607. if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
  113608. assert( !pTrigger );
  113609. assert( pList==0 );
  113610. goto insert_end;
  113611. }
  113612. #endif /* SQLITE_OMIT_XFER_OPT */
  113613. /* If this is an AUTOINCREMENT table, look up the sequence number in the
  113614. ** sqlite_sequence table and store it in memory cell regAutoinc.
  113615. */
  113616. regAutoinc = autoIncBegin(pParse, iDb, pTab);
  113617. /* Allocate a block registers to hold the rowid and the values
  113618. ** for all columns of the new row.
  113619. */
  113620. regRowid = regIns = pParse->nMem+1;
  113621. pParse->nMem += pTab->nCol + 1;
  113622. if( IsVirtual(pTab) ){
  113623. regRowid++;
  113624. pParse->nMem++;
  113625. }
  113626. regData = regRowid+1;
  113627. /* If the INSERT statement included an IDLIST term, then make sure
  113628. ** all elements of the IDLIST really are columns of the table and
  113629. ** remember the column indices.
  113630. **
  113631. ** If the table has an INTEGER PRIMARY KEY column and that column
  113632. ** is named in the IDLIST, then record in the ipkColumn variable
  113633. ** the index into IDLIST of the primary key column. ipkColumn is
  113634. ** the index of the primary key as it appears in IDLIST, not as
  113635. ** is appears in the original table. (The index of the INTEGER
  113636. ** PRIMARY KEY in the original table is pTab->iPKey.) After this
  113637. ** loop, if ipkColumn==(-1), that means that integer primary key
  113638. ** is unspecified, and hence the table is either WITHOUT ROWID or
  113639. ** it will automatically generated an integer primary key.
  113640. **
  113641. ** bIdListInOrder is true if the columns in IDLIST are in storage
  113642. ** order. This enables an optimization that avoids shuffling the
  113643. ** columns into storage order. False negatives are harmless,
  113644. ** but false positives will cause database corruption.
  113645. */
  113646. bIdListInOrder = (pTab->tabFlags & (TF_OOOHidden|TF_HasStored))==0;
  113647. if( pColumn ){
  113648. for(i=0; i<pColumn->nId; i++){
  113649. pColumn->a[i].idx = -1;
  113650. }
  113651. for(i=0; i<pColumn->nId; i++){
  113652. for(j=0; j<pTab->nCol; j++){
  113653. if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
  113654. pColumn->a[i].idx = j;
  113655. if( i!=j ) bIdListInOrder = 0;
  113656. if( j==pTab->iPKey ){
  113657. ipkColumn = i; assert( !withoutRowid );
  113658. }
  113659. #ifndef SQLITE_OMIT_GENERATED_COLUMNS
  113660. if( pTab->aCol[j].colFlags & (COLFLAG_STORED|COLFLAG_VIRTUAL) ){
  113661. sqlite3ErrorMsg(pParse,
  113662. "cannot INSERT into generated column \"%s\"",
  113663. pTab->aCol[j].zName);
  113664. goto insert_cleanup;
  113665. }
  113666. #endif
  113667. break;
  113668. }
  113669. }
  113670. if( j>=pTab->nCol ){
  113671. if( sqlite3IsRowid(pColumn->a[i].zName) && !withoutRowid ){
  113672. ipkColumn = i;
  113673. bIdListInOrder = 0;
  113674. }else{
  113675. sqlite3ErrorMsg(pParse, "table %S has no column named %s",
  113676. pTabList, 0, pColumn->a[i].zName);
  113677. pParse->checkSchema = 1;
  113678. goto insert_cleanup;
  113679. }
  113680. }
  113681. }
  113682. }
  113683. /* Figure out how many columns of data are supplied. If the data
  113684. ** is coming from a SELECT statement, then generate a co-routine that
  113685. ** produces a single row of the SELECT on each invocation. The
  113686. ** co-routine is the common header to the 3rd and 4th templates.
  113687. */
  113688. if( pSelect ){
  113689. /* Data is coming from a SELECT or from a multi-row VALUES clause.
  113690. ** Generate a co-routine to run the SELECT. */
  113691. int regYield; /* Register holding co-routine entry-point */
  113692. int addrTop; /* Top of the co-routine */
  113693. int rc; /* Result code */
  113694. regYield = ++pParse->nMem;
  113695. addrTop = sqlite3VdbeCurrentAddr(v) + 1;
  113696. sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
  113697. sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
  113698. dest.iSdst = bIdListInOrder ? regData : 0;
  113699. dest.nSdst = pTab->nCol;
  113700. rc = sqlite3Select(pParse, pSelect, &dest);
  113701. regFromSelect = dest.iSdst;
  113702. if( rc || db->mallocFailed || pParse->nErr ) goto insert_cleanup;
  113703. sqlite3VdbeEndCoroutine(v, regYield);
  113704. sqlite3VdbeJumpHere(v, addrTop - 1); /* label B: */
  113705. assert( pSelect->pEList );
  113706. nColumn = pSelect->pEList->nExpr;
  113707. /* Set useTempTable to TRUE if the result of the SELECT statement
  113708. ** should be written into a temporary table (template 4). Set to
  113709. ** FALSE if each output row of the SELECT can be written directly into
  113710. ** the destination table (template 3).
  113711. **
  113712. ** A temp table must be used if the table being updated is also one
  113713. ** of the tables being read by the SELECT statement. Also use a
  113714. ** temp table in the case of row triggers.
  113715. */
  113716. if( pTrigger || readsTable(pParse, iDb, pTab) ){
  113717. useTempTable = 1;
  113718. }
  113719. if( useTempTable ){
  113720. /* Invoke the coroutine to extract information from the SELECT
  113721. ** and add it to a transient table srcTab. The code generated
  113722. ** here is from the 4th template:
  113723. **
  113724. ** B: open temp table
  113725. ** L: yield X, goto M at EOF
  113726. ** insert row from R..R+n into temp table
  113727. ** goto L
  113728. ** M: ...
  113729. */
  113730. int regRec; /* Register to hold packed record */
  113731. int regTempRowid; /* Register to hold temp table ROWID */
  113732. int addrL; /* Label "L" */
  113733. srcTab = pParse->nTab++;
  113734. regRec = sqlite3GetTempReg(pParse);
  113735. regTempRowid = sqlite3GetTempReg(pParse);
  113736. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
  113737. addrL = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); VdbeCoverage(v);
  113738. sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
  113739. sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
  113740. sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
  113741. sqlite3VdbeGoto(v, addrL);
  113742. sqlite3VdbeJumpHere(v, addrL);
  113743. sqlite3ReleaseTempReg(pParse, regRec);
  113744. sqlite3ReleaseTempReg(pParse, regTempRowid);
  113745. }
  113746. }else{
  113747. /* This is the case if the data for the INSERT is coming from a
  113748. ** single-row VALUES clause
  113749. */
  113750. NameContext sNC;
  113751. memset(&sNC, 0, sizeof(sNC));
  113752. sNC.pParse = pParse;
  113753. srcTab = -1;
  113754. assert( useTempTable==0 );
  113755. if( pList ){
  113756. nColumn = pList->nExpr;
  113757. if( sqlite3ResolveExprListNames(&sNC, pList) ){
  113758. goto insert_cleanup;
  113759. }
  113760. }else{
  113761. nColumn = 0;
  113762. }
  113763. }
  113764. /* If there is no IDLIST term but the table has an integer primary
  113765. ** key, the set the ipkColumn variable to the integer primary key
  113766. ** column index in the original table definition.
  113767. */
  113768. if( pColumn==0 && nColumn>0 ){
  113769. ipkColumn = pTab->iPKey;
  113770. #ifndef SQLITE_OMIT_GENERATED_COLUMNS
  113771. if( ipkColumn>=0 && (pTab->tabFlags & TF_HasGenerated)!=0 ){
  113772. testcase( pTab->tabFlags & TF_HasVirtual );
  113773. testcase( pTab->tabFlags & TF_HasStored );
  113774. for(i=ipkColumn-1; i>=0; i--){
  113775. if( pTab->aCol[i].colFlags & COLFLAG_GENERATED ){
  113776. testcase( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL );
  113777. testcase( pTab->aCol[i].colFlags & COLFLAG_STORED );
  113778. ipkColumn--;
  113779. }
  113780. }
  113781. }
  113782. #endif
  113783. }
  113784. /* Make sure the number of columns in the source data matches the number
  113785. ** of columns to be inserted into the table.
  113786. */
  113787. for(i=0; i<pTab->nCol; i++){
  113788. if( pTab->aCol[i].colFlags & COLFLAG_NOINSERT ) nHidden++;
  113789. }
  113790. if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
  113791. sqlite3ErrorMsg(pParse,
  113792. "table %S has %d columns but %d values were supplied",
  113793. pTabList, 0, pTab->nCol-nHidden, nColumn);
  113794. goto insert_cleanup;
  113795. }
  113796. if( pColumn!=0 && nColumn!=pColumn->nId ){
  113797. sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
  113798. goto insert_cleanup;
  113799. }
  113800. /* Initialize the count of rows to be inserted
  113801. */
  113802. if( (db->flags & SQLITE_CountRows)!=0
  113803. && !pParse->nested
  113804. && !pParse->pTriggerTab
  113805. ){
  113806. regRowCount = ++pParse->nMem;
  113807. sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
  113808. }
  113809. /* If this is not a view, open the table and and all indices */
  113810. if( !isView ){
  113811. int nIdx;
  113812. nIdx = sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, 0, -1, 0,
  113813. &iDataCur, &iIdxCur);
  113814. aRegIdx = sqlite3DbMallocRawNN(db, sizeof(int)*(nIdx+2));
  113815. if( aRegIdx==0 ){
  113816. goto insert_cleanup;
  113817. }
  113818. for(i=0, pIdx=pTab->pIndex; i<nIdx; pIdx=pIdx->pNext, i++){
  113819. assert( pIdx );
  113820. aRegIdx[i] = ++pParse->nMem;
  113821. pParse->nMem += pIdx->nColumn;
  113822. }
  113823. aRegIdx[i] = ++pParse->nMem; /* Register to store the table record */
  113824. }
  113825. #ifndef SQLITE_OMIT_UPSERT
  113826. if( pUpsert ){
  113827. if( IsVirtual(pTab) ){
  113828. sqlite3ErrorMsg(pParse, "UPSERT not implemented for virtual table \"%s\"",
  113829. pTab->zName);
  113830. goto insert_cleanup;
  113831. }
  113832. if( pTab->pSelect ){
  113833. sqlite3ErrorMsg(pParse, "cannot UPSERT a view");
  113834. goto insert_cleanup;
  113835. }
  113836. if( sqlite3HasExplicitNulls(pParse, pUpsert->pUpsertTarget) ){
  113837. goto insert_cleanup;
  113838. }
  113839. pTabList->a[0].iCursor = iDataCur;
  113840. pUpsert->pUpsertSrc = pTabList;
  113841. pUpsert->regData = regData;
  113842. pUpsert->iDataCur = iDataCur;
  113843. pUpsert->iIdxCur = iIdxCur;
  113844. if( pUpsert->pUpsertTarget ){
  113845. sqlite3UpsertAnalyzeTarget(pParse, pTabList, pUpsert);
  113846. }
  113847. }
  113848. #endif
  113849. /* This is the top of the main insertion loop */
  113850. if( useTempTable ){
  113851. /* This block codes the top of loop only. The complete loop is the
  113852. ** following pseudocode (template 4):
  113853. **
  113854. ** rewind temp table, if empty goto D
  113855. ** C: loop over rows of intermediate table
  113856. ** transfer values form intermediate table into <table>
  113857. ** end loop
  113858. ** D: ...
  113859. */
  113860. addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab); VdbeCoverage(v);
  113861. addrCont = sqlite3VdbeCurrentAddr(v);
  113862. }else if( pSelect ){
  113863. /* This block codes the top of loop only. The complete loop is the
  113864. ** following pseudocode (template 3):
  113865. **
  113866. ** C: yield X, at EOF goto D
  113867. ** insert the select result into <table> from R..R+n
  113868. ** goto C
  113869. ** D: ...
  113870. */
  113871. sqlite3VdbeReleaseRegisters(pParse, regData, pTab->nCol, 0, 0);
  113872. addrInsTop = addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
  113873. VdbeCoverage(v);
  113874. if( ipkColumn>=0 ){
  113875. /* tag-20191021-001: If the INTEGER PRIMARY KEY is being generated by the
  113876. ** SELECT, go ahead and copy the value into the rowid slot now, so that
  113877. ** the value does not get overwritten by a NULL at tag-20191021-002. */
  113878. sqlite3VdbeAddOp2(v, OP_Copy, regFromSelect+ipkColumn, regRowid);
  113879. }
  113880. }
  113881. /* Compute data for ordinary columns of the new entry. Values
  113882. ** are written in storage order into registers starting with regData.
  113883. ** Only ordinary columns are computed in this loop. The rowid
  113884. ** (if there is one) is computed later and generated columns are
  113885. ** computed after the rowid since they might depend on the value
  113886. ** of the rowid.
  113887. */
  113888. nHidden = 0;
  113889. iRegStore = regData; assert( regData==regRowid+1 );
  113890. for(i=0; i<pTab->nCol; i++, iRegStore++){
  113891. int k;
  113892. u32 colFlags;
  113893. assert( i>=nHidden );
  113894. if( i==pTab->iPKey ){
  113895. /* tag-20191021-002: References to the INTEGER PRIMARY KEY are filled
  113896. ** using the rowid. So put a NULL in the IPK slot of the record to avoid
  113897. ** using excess space. The file format definition requires this extra
  113898. ** NULL - we cannot optimize further by skipping the column completely */
  113899. sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore);
  113900. continue;
  113901. }
  113902. if( ((colFlags = pTab->aCol[i].colFlags) & COLFLAG_NOINSERT)!=0 ){
  113903. nHidden++;
  113904. if( (colFlags & COLFLAG_VIRTUAL)!=0 ){
  113905. /* Virtual columns do not participate in OP_MakeRecord. So back up
  113906. ** iRegStore by one slot to compensate for the iRegStore++ in the
  113907. ** outer for() loop */
  113908. iRegStore--;
  113909. continue;
  113910. }else if( (colFlags & COLFLAG_STORED)!=0 ){
  113911. /* Stored columns are computed later. But if there are BEFORE
  113912. ** triggers, the slots used for stored columns will be OP_Copy-ed
  113913. ** to a second block of registers, so the register needs to be
  113914. ** initialized to NULL to avoid an uninitialized register read */
  113915. if( tmask & TRIGGER_BEFORE ){
  113916. sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore);
  113917. }
  113918. continue;
  113919. }else if( pColumn==0 ){
  113920. /* Hidden columns that are not explicitly named in the INSERT
  113921. ** get there default value */
  113922. sqlite3ExprCodeFactorable(pParse, pTab->aCol[i].pDflt, iRegStore);
  113923. continue;
  113924. }
  113925. }
  113926. if( pColumn ){
  113927. for(j=0; j<pColumn->nId && pColumn->a[j].idx!=i; j++){}
  113928. if( j>=pColumn->nId ){
  113929. /* A column not named in the insert column list gets its
  113930. ** default value */
  113931. sqlite3ExprCodeFactorable(pParse, pTab->aCol[i].pDflt, iRegStore);
  113932. continue;
  113933. }
  113934. k = j;
  113935. }else if( nColumn==0 ){
  113936. /* This is INSERT INTO ... DEFAULT VALUES. Load the default value. */
  113937. sqlite3ExprCodeFactorable(pParse, pTab->aCol[i].pDflt, iRegStore);
  113938. continue;
  113939. }else{
  113940. k = i - nHidden;
  113941. }
  113942. if( useTempTable ){
  113943. sqlite3VdbeAddOp3(v, OP_Column, srcTab, k, iRegStore);
  113944. }else if( pSelect ){
  113945. if( regFromSelect!=regData ){
  113946. sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+k, iRegStore);
  113947. }
  113948. }else{
  113949. sqlite3ExprCode(pParse, pList->a[k].pExpr, iRegStore);
  113950. }
  113951. }
  113952. /* Run the BEFORE and INSTEAD OF triggers, if there are any
  113953. */
  113954. endOfLoop = sqlite3VdbeMakeLabel(pParse);
  113955. if( tmask & TRIGGER_BEFORE ){
  113956. int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
  113957. /* build the NEW.* reference row. Note that if there is an INTEGER
  113958. ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
  113959. ** translated into a unique ID for the row. But on a BEFORE trigger,
  113960. ** we do not know what the unique ID will be (because the insert has
  113961. ** not happened yet) so we substitute a rowid of -1
  113962. */
  113963. if( ipkColumn<0 ){
  113964. sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
  113965. }else{
  113966. int addr1;
  113967. assert( !withoutRowid );
  113968. if( useTempTable ){
  113969. sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regCols);
  113970. }else{
  113971. assert( pSelect==0 ); /* Otherwise useTempTable is true */
  113972. sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regCols);
  113973. }
  113974. addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols); VdbeCoverage(v);
  113975. sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
  113976. sqlite3VdbeJumpHere(v, addr1);
  113977. sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols); VdbeCoverage(v);
  113978. }
  113979. /* Cannot have triggers on a virtual table. If it were possible,
  113980. ** this block would have to account for hidden column.
  113981. */
  113982. assert( !IsVirtual(pTab) );
  113983. /* Copy the new data already generated. */
  113984. assert( pTab->nNVCol>0 );
  113985. sqlite3VdbeAddOp3(v, OP_Copy, regRowid+1, regCols+1, pTab->nNVCol-1);
  113986. #ifndef SQLITE_OMIT_GENERATED_COLUMNS
  113987. /* Compute the new value for generated columns after all other
  113988. ** columns have already been computed. This must be done after
  113989. ** computing the ROWID in case one of the generated columns
  113990. ** refers to the ROWID. */
  113991. if( pTab->tabFlags & TF_HasGenerated ){
  113992. testcase( pTab->tabFlags & TF_HasVirtual );
  113993. testcase( pTab->tabFlags & TF_HasStored );
  113994. sqlite3ComputeGeneratedColumns(pParse, regCols+1, pTab);
  113995. }
  113996. #endif
  113997. /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
  113998. ** do not attempt any conversions before assembling the record.
  113999. ** If this is a real table, attempt conversions as required by the
  114000. ** table column affinities.
  114001. */
  114002. if( !isView ){
  114003. sqlite3TableAffinity(v, pTab, regCols+1);
  114004. }
  114005. /* Fire BEFORE or INSTEAD OF triggers */
  114006. sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
  114007. pTab, regCols-pTab->nCol-1, onError, endOfLoop);
  114008. sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
  114009. }
  114010. if( !isView ){
  114011. if( IsVirtual(pTab) ){
  114012. /* The row that the VUpdate opcode will delete: none */
  114013. sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
  114014. }
  114015. if( ipkColumn>=0 ){
  114016. /* Compute the new rowid */
  114017. if( useTempTable ){
  114018. sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regRowid);
  114019. }else if( pSelect ){
  114020. /* Rowid already initialized at tag-20191021-001 */
  114021. }else{
  114022. Expr *pIpk = pList->a[ipkColumn].pExpr;
  114023. if( pIpk->op==TK_NULL && !IsVirtual(pTab) ){
  114024. sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
  114025. appendFlag = 1;
  114026. }else{
  114027. sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regRowid);
  114028. }
  114029. }
  114030. /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
  114031. ** to generate a unique primary key value.
  114032. */
  114033. if( !appendFlag ){
  114034. int addr1;
  114035. if( !IsVirtual(pTab) ){
  114036. addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid); VdbeCoverage(v);
  114037. sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
  114038. sqlite3VdbeJumpHere(v, addr1);
  114039. }else{
  114040. addr1 = sqlite3VdbeCurrentAddr(v);
  114041. sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, addr1+2); VdbeCoverage(v);
  114042. }
  114043. sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid); VdbeCoverage(v);
  114044. }
  114045. }else if( IsVirtual(pTab) || withoutRowid ){
  114046. sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
  114047. }else{
  114048. sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
  114049. appendFlag = 1;
  114050. }
  114051. autoIncStep(pParse, regAutoinc, regRowid);
  114052. #ifndef SQLITE_OMIT_GENERATED_COLUMNS
  114053. /* Compute the new value for generated columns after all other
  114054. ** columns have already been computed. This must be done after
  114055. ** computing the ROWID in case one of the generated columns
  114056. ** is derived from the INTEGER PRIMARY KEY. */
  114057. if( pTab->tabFlags & TF_HasGenerated ){
  114058. sqlite3ComputeGeneratedColumns(pParse, regRowid+1, pTab);
  114059. }
  114060. #endif
  114061. /* Generate code to check constraints and generate index keys and
  114062. ** do the insertion.
  114063. */
  114064. #ifndef SQLITE_OMIT_VIRTUALTABLE
  114065. if( IsVirtual(pTab) ){
  114066. const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
  114067. sqlite3VtabMakeWritable(pParse, pTab);
  114068. sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
  114069. sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
  114070. sqlite3MayAbort(pParse);
  114071. }else
  114072. #endif
  114073. {
  114074. int isReplace; /* Set to true if constraints may cause a replace */
  114075. int bUseSeek; /* True to use OPFLAG_SEEKRESULT */
  114076. sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
  114077. regIns, 0, ipkColumn>=0, onError, endOfLoop, &isReplace, 0, pUpsert
  114078. );
  114079. sqlite3FkCheck(pParse, pTab, 0, regIns, 0, 0);
  114080. /* Set the OPFLAG_USESEEKRESULT flag if either (a) there are no REPLACE
  114081. ** constraints or (b) there are no triggers and this table is not a
  114082. ** parent table in a foreign key constraint. It is safe to set the
  114083. ** flag in the second case as if any REPLACE constraint is hit, an
  114084. ** OP_Delete or OP_IdxDelete instruction will be executed on each
  114085. ** cursor that is disturbed. And these instructions both clear the
  114086. ** VdbeCursor.seekResult variable, disabling the OPFLAG_USESEEKRESULT
  114087. ** functionality. */
  114088. bUseSeek = (isReplace==0 || !sqlite3VdbeHasSubProgram(v));
  114089. sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur,
  114090. regIns, aRegIdx, 0, appendFlag, bUseSeek
  114091. );
  114092. }
  114093. }
  114094. /* Update the count of rows that are inserted
  114095. */
  114096. if( regRowCount ){
  114097. sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
  114098. }
  114099. if( pTrigger ){
  114100. /* Code AFTER triggers */
  114101. sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
  114102. pTab, regData-2-pTab->nCol, onError, endOfLoop);
  114103. }
  114104. /* The bottom of the main insertion loop, if the data source
  114105. ** is a SELECT statement.
  114106. */
  114107. sqlite3VdbeResolveLabel(v, endOfLoop);
  114108. if( useTempTable ){
  114109. sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont); VdbeCoverage(v);
  114110. sqlite3VdbeJumpHere(v, addrInsTop);
  114111. sqlite3VdbeAddOp1(v, OP_Close, srcTab);
  114112. }else if( pSelect ){
  114113. sqlite3VdbeGoto(v, addrCont);
  114114. #ifdef SQLITE_DEBUG
  114115. /* If we are jumping back to an OP_Yield that is preceded by an
  114116. ** OP_ReleaseReg, set the p5 flag on the OP_Goto so that the
  114117. ** OP_ReleaseReg will be included in the loop. */
  114118. if( sqlite3VdbeGetOp(v, addrCont-1)->opcode==OP_ReleaseReg ){
  114119. assert( sqlite3VdbeGetOp(v, addrCont)->opcode==OP_Yield );
  114120. sqlite3VdbeChangeP5(v, 1);
  114121. }
  114122. #endif
  114123. sqlite3VdbeJumpHere(v, addrInsTop);
  114124. }
  114125. insert_end:
  114126. /* Update the sqlite_sequence table by storing the content of the
  114127. ** maximum rowid counter values recorded while inserting into
  114128. ** autoincrement tables.
  114129. */
  114130. if( pParse->nested==0 && pParse->pTriggerTab==0 ){
  114131. sqlite3AutoincrementEnd(pParse);
  114132. }
  114133. /*
  114134. ** Return the number of rows inserted. If this routine is
  114135. ** generating code because of a call to sqlite3NestedParse(), do not
  114136. ** invoke the callback function.
  114137. */
  114138. if( regRowCount ){
  114139. sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
  114140. sqlite3VdbeSetNumCols(v, 1);
  114141. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
  114142. }
  114143. insert_cleanup:
  114144. sqlite3SrcListDelete(db, pTabList);
  114145. sqlite3ExprListDelete(db, pList);
  114146. sqlite3UpsertDelete(db, pUpsert);
  114147. sqlite3SelectDelete(db, pSelect);
  114148. sqlite3IdListDelete(db, pColumn);
  114149. sqlite3DbFree(db, aRegIdx);
  114150. }
  114151. /* Make sure "isView" and other macros defined above are undefined. Otherwise
  114152. ** they may interfere with compilation of other functions in this file
  114153. ** (or in another file, if this file becomes part of the amalgamation). */
  114154. #ifdef isView
  114155. #undef isView
  114156. #endif
  114157. #ifdef pTrigger
  114158. #undef pTrigger
  114159. #endif
  114160. #ifdef tmask
  114161. #undef tmask
  114162. #endif
  114163. /*
  114164. ** Meanings of bits in of pWalker->eCode for
  114165. ** sqlite3ExprReferencesUpdatedColumn()
  114166. */
  114167. #define CKCNSTRNT_COLUMN 0x01 /* CHECK constraint uses a changing column */
  114168. #define CKCNSTRNT_ROWID 0x02 /* CHECK constraint references the ROWID */
  114169. /* This is the Walker callback from sqlite3ExprReferencesUpdatedColumn().
  114170. * Set bit 0x01 of pWalker->eCode if pWalker->eCode to 0 and if this
  114171. ** expression node references any of the
  114172. ** columns that are being modifed by an UPDATE statement.
  114173. */
  114174. static int checkConstraintExprNode(Walker *pWalker, Expr *pExpr){
  114175. if( pExpr->op==TK_COLUMN ){
  114176. assert( pExpr->iColumn>=0 || pExpr->iColumn==-1 );
  114177. if( pExpr->iColumn>=0 ){
  114178. if( pWalker->u.aiCol[pExpr->iColumn]>=0 ){
  114179. pWalker->eCode |= CKCNSTRNT_COLUMN;
  114180. }
  114181. }else{
  114182. pWalker->eCode |= CKCNSTRNT_ROWID;
  114183. }
  114184. }
  114185. return WRC_Continue;
  114186. }
  114187. /*
  114188. ** pExpr is a CHECK constraint on a row that is being UPDATE-ed. The
  114189. ** only columns that are modified by the UPDATE are those for which
  114190. ** aiChng[i]>=0, and also the ROWID is modified if chngRowid is true.
  114191. **
  114192. ** Return true if CHECK constraint pExpr uses any of the
  114193. ** changing columns (or the rowid if it is changing). In other words,
  114194. ** return true if this CHECK constraint must be validated for
  114195. ** the new row in the UPDATE statement.
  114196. **
  114197. ** 2018-09-15: pExpr might also be an expression for an index-on-expressions.
  114198. ** The operation of this routine is the same - return true if an only if
  114199. ** the expression uses one or more of columns identified by the second and
  114200. ** third arguments.
  114201. */
  114202. SQLITE_PRIVATE int sqlite3ExprReferencesUpdatedColumn(
  114203. Expr *pExpr, /* The expression to be checked */
  114204. int *aiChng, /* aiChng[x]>=0 if column x changed by the UPDATE */
  114205. int chngRowid /* True if UPDATE changes the rowid */
  114206. ){
  114207. Walker w;
  114208. memset(&w, 0, sizeof(w));
  114209. w.eCode = 0;
  114210. w.xExprCallback = checkConstraintExprNode;
  114211. w.u.aiCol = aiChng;
  114212. sqlite3WalkExpr(&w, pExpr);
  114213. if( !chngRowid ){
  114214. testcase( (w.eCode & CKCNSTRNT_ROWID)!=0 );
  114215. w.eCode &= ~CKCNSTRNT_ROWID;
  114216. }
  114217. testcase( w.eCode==0 );
  114218. testcase( w.eCode==CKCNSTRNT_COLUMN );
  114219. testcase( w.eCode==CKCNSTRNT_ROWID );
  114220. testcase( w.eCode==(CKCNSTRNT_ROWID|CKCNSTRNT_COLUMN) );
  114221. return w.eCode!=0;
  114222. }
  114223. /*
  114224. ** Generate code to do constraint checks prior to an INSERT or an UPDATE
  114225. ** on table pTab.
  114226. **
  114227. ** The regNewData parameter is the first register in a range that contains
  114228. ** the data to be inserted or the data after the update. There will be
  114229. ** pTab->nCol+1 registers in this range. The first register (the one
  114230. ** that regNewData points to) will contain the new rowid, or NULL in the
  114231. ** case of a WITHOUT ROWID table. The second register in the range will
  114232. ** contain the content of the first table column. The third register will
  114233. ** contain the content of the second table column. And so forth.
  114234. **
  114235. ** The regOldData parameter is similar to regNewData except that it contains
  114236. ** the data prior to an UPDATE rather than afterwards. regOldData is zero
  114237. ** for an INSERT. This routine can distinguish between UPDATE and INSERT by
  114238. ** checking regOldData for zero.
  114239. **
  114240. ** For an UPDATE, the pkChng boolean is true if the true primary key (the
  114241. ** rowid for a normal table or the PRIMARY KEY for a WITHOUT ROWID table)
  114242. ** might be modified by the UPDATE. If pkChng is false, then the key of
  114243. ** the iDataCur content table is guaranteed to be unchanged by the UPDATE.
  114244. **
  114245. ** For an INSERT, the pkChng boolean indicates whether or not the rowid
  114246. ** was explicitly specified as part of the INSERT statement. If pkChng
  114247. ** is zero, it means that the either rowid is computed automatically or
  114248. ** that the table is a WITHOUT ROWID table and has no rowid. On an INSERT,
  114249. ** pkChng will only be true if the INSERT statement provides an integer
  114250. ** value for either the rowid column or its INTEGER PRIMARY KEY alias.
  114251. **
  114252. ** The code generated by this routine will store new index entries into
  114253. ** registers identified by aRegIdx[]. No index entry is created for
  114254. ** indices where aRegIdx[i]==0. The order of indices in aRegIdx[] is
  114255. ** the same as the order of indices on the linked list of indices
  114256. ** at pTab->pIndex.
  114257. **
  114258. ** (2019-05-07) The generated code also creates a new record for the
  114259. ** main table, if pTab is a rowid table, and stores that record in the
  114260. ** register identified by aRegIdx[nIdx] - in other words in the first
  114261. ** entry of aRegIdx[] past the last index. It is important that the
  114262. ** record be generated during constraint checks to avoid affinity changes
  114263. ** to the register content that occur after constraint checks but before
  114264. ** the new record is inserted.
  114265. **
  114266. ** The caller must have already opened writeable cursors on the main
  114267. ** table and all applicable indices (that is to say, all indices for which
  114268. ** aRegIdx[] is not zero). iDataCur is the cursor for the main table when
  114269. ** inserting or updating a rowid table, or the cursor for the PRIMARY KEY
  114270. ** index when operating on a WITHOUT ROWID table. iIdxCur is the cursor
  114271. ** for the first index in the pTab->pIndex list. Cursors for other indices
  114272. ** are at iIdxCur+N for the N-th element of the pTab->pIndex list.
  114273. **
  114274. ** This routine also generates code to check constraints. NOT NULL,
  114275. ** CHECK, and UNIQUE constraints are all checked. If a constraint fails,
  114276. ** then the appropriate action is performed. There are five possible
  114277. ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
  114278. **
  114279. ** Constraint type Action What Happens
  114280. ** --------------- ---------- ----------------------------------------
  114281. ** any ROLLBACK The current transaction is rolled back and
  114282. ** sqlite3_step() returns immediately with a
  114283. ** return code of SQLITE_CONSTRAINT.
  114284. **
  114285. ** any ABORT Back out changes from the current command
  114286. ** only (do not do a complete rollback) then
  114287. ** cause sqlite3_step() to return immediately
  114288. ** with SQLITE_CONSTRAINT.
  114289. **
  114290. ** any FAIL Sqlite3_step() returns immediately with a
  114291. ** return code of SQLITE_CONSTRAINT. The
  114292. ** transaction is not rolled back and any
  114293. ** changes to prior rows are retained.
  114294. **
  114295. ** any IGNORE The attempt in insert or update the current
  114296. ** row is skipped, without throwing an error.
  114297. ** Processing continues with the next row.
  114298. ** (There is an immediate jump to ignoreDest.)
  114299. **
  114300. ** NOT NULL REPLACE The NULL value is replace by the default
  114301. ** value for that column. If the default value
  114302. ** is NULL, the action is the same as ABORT.
  114303. **
  114304. ** UNIQUE REPLACE The other row that conflicts with the row
  114305. ** being inserted is removed.
  114306. **
  114307. ** CHECK REPLACE Illegal. The results in an exception.
  114308. **
  114309. ** Which action to take is determined by the overrideError parameter.
  114310. ** Or if overrideError==OE_Default, then the pParse->onError parameter
  114311. ** is used. Or if pParse->onError==OE_Default then the onError value
  114312. ** for the constraint is used.
  114313. */
  114314. SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
  114315. Parse *pParse, /* The parser context */
  114316. Table *pTab, /* The table being inserted or updated */
  114317. int *aRegIdx, /* Use register aRegIdx[i] for index i. 0 for unused */
  114318. int iDataCur, /* Canonical data cursor (main table or PK index) */
  114319. int iIdxCur, /* First index cursor */
  114320. int regNewData, /* First register in a range holding values to insert */
  114321. int regOldData, /* Previous content. 0 for INSERTs */
  114322. u8 pkChng, /* Non-zero if the rowid or PRIMARY KEY changed */
  114323. u8 overrideError, /* Override onError to this if not OE_Default */
  114324. int ignoreDest, /* Jump to this label on an OE_Ignore resolution */
  114325. int *pbMayReplace, /* OUT: Set to true if constraint may cause a replace */
  114326. int *aiChng, /* column i is unchanged if aiChng[i]<0 */
  114327. Upsert *pUpsert /* ON CONFLICT clauses, if any. NULL otherwise */
  114328. ){
  114329. Vdbe *v; /* VDBE under constrution */
  114330. Index *pIdx; /* Pointer to one of the indices */
  114331. Index *pPk = 0; /* The PRIMARY KEY index */
  114332. sqlite3 *db; /* Database connection */
  114333. int i; /* loop counter */
  114334. int ix; /* Index loop counter */
  114335. int nCol; /* Number of columns */
  114336. int onError; /* Conflict resolution strategy */
  114337. int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
  114338. int nPkField; /* Number of fields in PRIMARY KEY. 1 for ROWID tables */
  114339. Index *pUpIdx = 0; /* Index to which to apply the upsert */
  114340. u8 isUpdate; /* True if this is an UPDATE operation */
  114341. u8 bAffinityDone = 0; /* True if the OP_Affinity operation has been run */
  114342. int upsertBypass = 0; /* Address of Goto to bypass upsert subroutine */
  114343. int upsertJump = 0; /* Address of Goto that jumps into upsert subroutine */
  114344. int ipkTop = 0; /* Top of the IPK uniqueness check */
  114345. int ipkBottom = 0; /* OP_Goto at the end of the IPK uniqueness check */
  114346. /* Variables associated with retesting uniqueness constraints after
  114347. ** replace triggers fire have run */
  114348. int regTrigCnt; /* Register used to count replace trigger invocations */
  114349. int addrRecheck = 0; /* Jump here to recheck all uniqueness constraints */
  114350. int lblRecheckOk = 0; /* Each recheck jumps to this label if it passes */
  114351. Trigger *pTrigger; /* List of DELETE triggers on the table pTab */
  114352. int nReplaceTrig = 0; /* Number of replace triggers coded */
  114353. isUpdate = regOldData!=0;
  114354. db = pParse->db;
  114355. v = sqlite3GetVdbe(pParse);
  114356. assert( v!=0 );
  114357. assert( pTab->pSelect==0 ); /* This table is not a VIEW */
  114358. nCol = pTab->nCol;
  114359. /* pPk is the PRIMARY KEY index for WITHOUT ROWID tables and NULL for
  114360. ** normal rowid tables. nPkField is the number of key fields in the
  114361. ** pPk index or 1 for a rowid table. In other words, nPkField is the
  114362. ** number of fields in the true primary key of the table. */
  114363. if( HasRowid(pTab) ){
  114364. pPk = 0;
  114365. nPkField = 1;
  114366. }else{
  114367. pPk = sqlite3PrimaryKeyIndex(pTab);
  114368. nPkField = pPk->nKeyCol;
  114369. }
  114370. /* Record that this module has started */
  114371. VdbeModuleComment((v, "BEGIN: GenCnstCks(%d,%d,%d,%d,%d)",
  114372. iDataCur, iIdxCur, regNewData, regOldData, pkChng));
  114373. /* Test all NOT NULL constraints.
  114374. */
  114375. if( pTab->tabFlags & TF_HasNotNull ){
  114376. int b2ndPass = 0; /* True if currently running 2nd pass */
  114377. int nSeenReplace = 0; /* Number of ON CONFLICT REPLACE operations */
  114378. int nGenerated = 0; /* Number of generated columns with NOT NULL */
  114379. while(1){ /* Make 2 passes over columns. Exit loop via "break" */
  114380. for(i=0; i<nCol; i++){
  114381. int iReg; /* Register holding column value */
  114382. Column *pCol = &pTab->aCol[i]; /* The column to check for NOT NULL */
  114383. int isGenerated; /* non-zero if column is generated */
  114384. onError = pCol->notNull;
  114385. if( onError==OE_None ) continue; /* No NOT NULL on this column */
  114386. if( i==pTab->iPKey ){
  114387. continue; /* ROWID is never NULL */
  114388. }
  114389. isGenerated = pCol->colFlags & COLFLAG_GENERATED;
  114390. if( isGenerated && !b2ndPass ){
  114391. nGenerated++;
  114392. continue; /* Generated columns processed on 2nd pass */
  114393. }
  114394. if( aiChng && aiChng[i]<0 && !isGenerated ){
  114395. /* Do not check NOT NULL on columns that do not change */
  114396. continue;
  114397. }
  114398. if( overrideError!=OE_Default ){
  114399. onError = overrideError;
  114400. }else if( onError==OE_Default ){
  114401. onError = OE_Abort;
  114402. }
  114403. if( onError==OE_Replace ){
  114404. if( b2ndPass /* REPLACE becomes ABORT on the 2nd pass */
  114405. || pCol->pDflt==0 /* REPLACE is ABORT if no DEFAULT value */
  114406. ){
  114407. testcase( pCol->colFlags & COLFLAG_VIRTUAL );
  114408. testcase( pCol->colFlags & COLFLAG_STORED );
  114409. testcase( pCol->colFlags & COLFLAG_GENERATED );
  114410. onError = OE_Abort;
  114411. }else{
  114412. assert( !isGenerated );
  114413. }
  114414. }else if( b2ndPass && !isGenerated ){
  114415. continue;
  114416. }
  114417. assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
  114418. || onError==OE_Ignore || onError==OE_Replace );
  114419. testcase( i!=sqlite3TableColumnToStorage(pTab, i) );
  114420. iReg = sqlite3TableColumnToStorage(pTab, i) + regNewData + 1;
  114421. switch( onError ){
  114422. case OE_Replace: {
  114423. int addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, iReg);
  114424. VdbeCoverage(v);
  114425. assert( (pCol->colFlags & COLFLAG_GENERATED)==0 );
  114426. nSeenReplace++;
  114427. sqlite3ExprCodeCopy(pParse, pCol->pDflt, iReg);
  114428. sqlite3VdbeJumpHere(v, addr1);
  114429. break;
  114430. }
  114431. case OE_Abort:
  114432. sqlite3MayAbort(pParse);
  114433. /* Fall through */
  114434. case OE_Rollback:
  114435. case OE_Fail: {
  114436. char *zMsg = sqlite3MPrintf(db, "%s.%s", pTab->zName,
  114437. pCol->zName);
  114438. sqlite3VdbeAddOp3(v, OP_HaltIfNull, SQLITE_CONSTRAINT_NOTNULL,
  114439. onError, iReg);
  114440. sqlite3VdbeAppendP4(v, zMsg, P4_DYNAMIC);
  114441. sqlite3VdbeChangeP5(v, P5_ConstraintNotNull);
  114442. VdbeCoverage(v);
  114443. break;
  114444. }
  114445. default: {
  114446. assert( onError==OE_Ignore );
  114447. sqlite3VdbeAddOp2(v, OP_IsNull, iReg, ignoreDest);
  114448. VdbeCoverage(v);
  114449. break;
  114450. }
  114451. } /* end switch(onError) */
  114452. } /* end loop i over columns */
  114453. if( nGenerated==0 && nSeenReplace==0 ){
  114454. /* If there are no generated columns with NOT NULL constraints
  114455. ** and no NOT NULL ON CONFLICT REPLACE constraints, then a single
  114456. ** pass is sufficient */
  114457. break;
  114458. }
  114459. if( b2ndPass ) break; /* Never need more than 2 passes */
  114460. b2ndPass = 1;
  114461. #ifndef SQLITE_OMIT_GENERATED_COLUMNS
  114462. if( nSeenReplace>0 && (pTab->tabFlags & TF_HasGenerated)!=0 ){
  114463. /* If any NOT NULL ON CONFLICT REPLACE constraints fired on the
  114464. ** first pass, recomputed values for all generated columns, as
  114465. ** those values might depend on columns affected by the REPLACE.
  114466. */
  114467. sqlite3ComputeGeneratedColumns(pParse, regNewData+1, pTab);
  114468. }
  114469. #endif
  114470. } /* end of 2-pass loop */
  114471. } /* end if( has-not-null-constraints ) */
  114472. /* Test all CHECK constraints
  114473. */
  114474. #ifndef SQLITE_OMIT_CHECK
  114475. if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
  114476. ExprList *pCheck = pTab->pCheck;
  114477. pParse->iSelfTab = -(regNewData+1);
  114478. onError = overrideError!=OE_Default ? overrideError : OE_Abort;
  114479. for(i=0; i<pCheck->nExpr; i++){
  114480. int allOk;
  114481. Expr *pCopy;
  114482. Expr *pExpr = pCheck->a[i].pExpr;
  114483. if( aiChng
  114484. && !sqlite3ExprReferencesUpdatedColumn(pExpr, aiChng, pkChng)
  114485. ){
  114486. /* The check constraints do not reference any of the columns being
  114487. ** updated so there is no point it verifying the check constraint */
  114488. continue;
  114489. }
  114490. if( bAffinityDone==0 ){
  114491. sqlite3TableAffinity(v, pTab, regNewData+1);
  114492. bAffinityDone = 1;
  114493. }
  114494. allOk = sqlite3VdbeMakeLabel(pParse);
  114495. sqlite3VdbeVerifyAbortable(v, onError);
  114496. pCopy = sqlite3ExprDup(db, pExpr, 0);
  114497. if( !db->mallocFailed ){
  114498. sqlite3ExprIfTrue(pParse, pCopy, allOk, SQLITE_JUMPIFNULL);
  114499. }
  114500. sqlite3ExprDelete(db, pCopy);
  114501. if( onError==OE_Ignore ){
  114502. sqlite3VdbeGoto(v, ignoreDest);
  114503. }else{
  114504. char *zName = pCheck->a[i].zEName;
  114505. if( zName==0 ) zName = pTab->zName;
  114506. if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-26383-51744 */
  114507. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK,
  114508. onError, zName, P4_TRANSIENT,
  114509. P5_ConstraintCheck);
  114510. }
  114511. sqlite3VdbeResolveLabel(v, allOk);
  114512. }
  114513. pParse->iSelfTab = 0;
  114514. }
  114515. #endif /* !defined(SQLITE_OMIT_CHECK) */
  114516. /* UNIQUE and PRIMARY KEY constraints should be handled in the following
  114517. ** order:
  114518. **
  114519. ** (1) OE_Update
  114520. ** (2) OE_Abort, OE_Fail, OE_Rollback, OE_Ignore
  114521. ** (3) OE_Replace
  114522. **
  114523. ** OE_Fail and OE_Ignore must happen before any changes are made.
  114524. ** OE_Update guarantees that only a single row will change, so it
  114525. ** must happen before OE_Replace. Technically, OE_Abort and OE_Rollback
  114526. ** could happen in any order, but they are grouped up front for
  114527. ** convenience.
  114528. **
  114529. ** 2018-08-14: Ticket https://www.sqlite.org/src/info/908f001483982c43
  114530. ** The order of constraints used to have OE_Update as (2) and OE_Abort
  114531. ** and so forth as (1). But apparently PostgreSQL checks the OE_Update
  114532. ** constraint before any others, so it had to be moved.
  114533. **
  114534. ** Constraint checking code is generated in this order:
  114535. ** (A) The rowid constraint
  114536. ** (B) Unique index constraints that do not have OE_Replace as their
  114537. ** default conflict resolution strategy
  114538. ** (C) Unique index that do use OE_Replace by default.
  114539. **
  114540. ** The ordering of (2) and (3) is accomplished by making sure the linked
  114541. ** list of indexes attached to a table puts all OE_Replace indexes last
  114542. ** in the list. See sqlite3CreateIndex() for where that happens.
  114543. */
  114544. if( pUpsert ){
  114545. if( pUpsert->pUpsertTarget==0 ){
  114546. /* An ON CONFLICT DO NOTHING clause, without a constraint-target.
  114547. ** Make all unique constraint resolution be OE_Ignore */
  114548. assert( pUpsert->pUpsertSet==0 );
  114549. overrideError = OE_Ignore;
  114550. pUpsert = 0;
  114551. }else if( (pUpIdx = pUpsert->pUpsertIdx)!=0 ){
  114552. /* If the constraint-target uniqueness check must be run first.
  114553. ** Jump to that uniqueness check now */
  114554. upsertJump = sqlite3VdbeAddOp0(v, OP_Goto);
  114555. VdbeComment((v, "UPSERT constraint goes first"));
  114556. }
  114557. }
  114558. /* Determine if it is possible that triggers (either explicitly coded
  114559. ** triggers or FK resolution actions) might run as a result of deletes
  114560. ** that happen when OE_Replace conflict resolution occurs. (Call these
  114561. ** "replace triggers".) If any replace triggers run, we will need to
  114562. ** recheck all of the uniqueness constraints after they have all run.
  114563. ** But on the recheck, the resolution is OE_Abort instead of OE_Replace.
  114564. **
  114565. ** If replace triggers are a possibility, then
  114566. **
  114567. ** (1) Allocate register regTrigCnt and initialize it to zero.
  114568. ** That register will count the number of replace triggers that
  114569. ** fire. Constraint recheck only occurs if the number is positive.
  114570. ** (2) Initialize pTrigger to the list of all DELETE triggers on pTab.
  114571. ** (3) Initialize addrRecheck and lblRecheckOk
  114572. **
  114573. ** The uniqueness rechecking code will create a series of tests to run
  114574. ** in a second pass. The addrRecheck and lblRecheckOk variables are
  114575. ** used to link together these tests which are separated from each other
  114576. ** in the generate bytecode.
  114577. */
  114578. if( (db->flags & (SQLITE_RecTriggers|SQLITE_ForeignKeys))==0 ){
  114579. /* There are not DELETE triggers nor FK constraints. No constraint
  114580. ** rechecks are needed. */
  114581. pTrigger = 0;
  114582. regTrigCnt = 0;
  114583. }else{
  114584. if( db->flags&SQLITE_RecTriggers ){
  114585. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
  114586. regTrigCnt = pTrigger!=0 || sqlite3FkRequired(pParse, pTab, 0, 0);
  114587. }else{
  114588. pTrigger = 0;
  114589. regTrigCnt = sqlite3FkRequired(pParse, pTab, 0, 0);
  114590. }
  114591. if( regTrigCnt ){
  114592. /* Replace triggers might exist. Allocate the counter and
  114593. ** initialize it to zero. */
  114594. regTrigCnt = ++pParse->nMem;
  114595. sqlite3VdbeAddOp2(v, OP_Integer, 0, regTrigCnt);
  114596. VdbeComment((v, "trigger count"));
  114597. lblRecheckOk = sqlite3VdbeMakeLabel(pParse);
  114598. addrRecheck = lblRecheckOk;
  114599. }
  114600. }
  114601. /* If rowid is changing, make sure the new rowid does not previously
  114602. ** exist in the table.
  114603. */
  114604. if( pkChng && pPk==0 ){
  114605. int addrRowidOk = sqlite3VdbeMakeLabel(pParse);
  114606. /* Figure out what action to take in case of a rowid collision */
  114607. onError = pTab->keyConf;
  114608. if( overrideError!=OE_Default ){
  114609. onError = overrideError;
  114610. }else if( onError==OE_Default ){
  114611. onError = OE_Abort;
  114612. }
  114613. /* figure out whether or not upsert applies in this case */
  114614. if( pUpsert && pUpsert->pUpsertIdx==0 ){
  114615. if( pUpsert->pUpsertSet==0 ){
  114616. onError = OE_Ignore; /* DO NOTHING is the same as INSERT OR IGNORE */
  114617. }else{
  114618. onError = OE_Update; /* DO UPDATE */
  114619. }
  114620. }
  114621. /* If the response to a rowid conflict is REPLACE but the response
  114622. ** to some other UNIQUE constraint is FAIL or IGNORE, then we need
  114623. ** to defer the running of the rowid conflict checking until after
  114624. ** the UNIQUE constraints have run.
  114625. */
  114626. if( onError==OE_Replace /* IPK rule is REPLACE */
  114627. && onError!=overrideError /* Rules for other contraints are different */
  114628. && pTab->pIndex /* There exist other constraints */
  114629. ){
  114630. ipkTop = sqlite3VdbeAddOp0(v, OP_Goto)+1;
  114631. VdbeComment((v, "defer IPK REPLACE until last"));
  114632. }
  114633. if( isUpdate ){
  114634. /* pkChng!=0 does not mean that the rowid has changed, only that
  114635. ** it might have changed. Skip the conflict logic below if the rowid
  114636. ** is unchanged. */
  114637. sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRowidOk, regOldData);
  114638. sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
  114639. VdbeCoverage(v);
  114640. }
  114641. /* Check to see if the new rowid already exists in the table. Skip
  114642. ** the following conflict logic if it does not. */
  114643. VdbeNoopComment((v, "uniqueness check for ROWID"));
  114644. sqlite3VdbeVerifyAbortable(v, onError);
  114645. sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRowidOk, regNewData);
  114646. VdbeCoverage(v);
  114647. switch( onError ){
  114648. default: {
  114649. onError = OE_Abort;
  114650. /* Fall thru into the next case */
  114651. }
  114652. case OE_Rollback:
  114653. case OE_Abort:
  114654. case OE_Fail: {
  114655. testcase( onError==OE_Rollback );
  114656. testcase( onError==OE_Abort );
  114657. testcase( onError==OE_Fail );
  114658. sqlite3RowidConstraint(pParse, onError, pTab);
  114659. break;
  114660. }
  114661. case OE_Replace: {
  114662. /* If there are DELETE triggers on this table and the
  114663. ** recursive-triggers flag is set, call GenerateRowDelete() to
  114664. ** remove the conflicting row from the table. This will fire
  114665. ** the triggers and remove both the table and index b-tree entries.
  114666. **
  114667. ** Otherwise, if there are no triggers or the recursive-triggers
  114668. ** flag is not set, but the table has one or more indexes, call
  114669. ** GenerateRowIndexDelete(). This removes the index b-tree entries
  114670. ** only. The table b-tree entry will be replaced by the new entry
  114671. ** when it is inserted.
  114672. **
  114673. ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
  114674. ** also invoke MultiWrite() to indicate that this VDBE may require
  114675. ** statement rollback (if the statement is aborted after the delete
  114676. ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
  114677. ** but being more selective here allows statements like:
  114678. **
  114679. ** REPLACE INTO t(rowid) VALUES($newrowid)
  114680. **
  114681. ** to run without a statement journal if there are no indexes on the
  114682. ** table.
  114683. */
  114684. if( regTrigCnt ){
  114685. sqlite3MultiWrite(pParse);
  114686. sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
  114687. regNewData, 1, 0, OE_Replace, 1, -1);
  114688. sqlite3VdbeAddOp2(v, OP_AddImm, regTrigCnt, 1); /* incr trigger cnt */
  114689. nReplaceTrig++;
  114690. }else{
  114691. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  114692. assert( HasRowid(pTab) );
  114693. /* This OP_Delete opcode fires the pre-update-hook only. It does
  114694. ** not modify the b-tree. It is more efficient to let the coming
  114695. ** OP_Insert replace the existing entry than it is to delete the
  114696. ** existing entry and then insert a new one. */
  114697. sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, OPFLAG_ISNOOP);
  114698. sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
  114699. #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
  114700. if( pTab->pIndex ){
  114701. sqlite3MultiWrite(pParse);
  114702. sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,-1);
  114703. }
  114704. }
  114705. seenReplace = 1;
  114706. break;
  114707. }
  114708. #ifndef SQLITE_OMIT_UPSERT
  114709. case OE_Update: {
  114710. sqlite3UpsertDoUpdate(pParse, pUpsert, pTab, 0, iDataCur);
  114711. /* Fall through */
  114712. }
  114713. #endif
  114714. case OE_Ignore: {
  114715. testcase( onError==OE_Ignore );
  114716. sqlite3VdbeGoto(v, ignoreDest);
  114717. break;
  114718. }
  114719. }
  114720. sqlite3VdbeResolveLabel(v, addrRowidOk);
  114721. if( ipkTop ){
  114722. ipkBottom = sqlite3VdbeAddOp0(v, OP_Goto);
  114723. sqlite3VdbeJumpHere(v, ipkTop-1);
  114724. }
  114725. }
  114726. /* Test all UNIQUE constraints by creating entries for each UNIQUE
  114727. ** index and making sure that duplicate entries do not already exist.
  114728. ** Compute the revised record entries for indices as we go.
  114729. **
  114730. ** This loop also handles the case of the PRIMARY KEY index for a
  114731. ** WITHOUT ROWID table.
  114732. */
  114733. for(ix=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, ix++){
  114734. int regIdx; /* Range of registers hold conent for pIdx */
  114735. int regR; /* Range of registers holding conflicting PK */
  114736. int iThisCur; /* Cursor for this UNIQUE index */
  114737. int addrUniqueOk; /* Jump here if the UNIQUE constraint is satisfied */
  114738. int addrConflictCk; /* First opcode in the conflict check logic */
  114739. if( aRegIdx[ix]==0 ) continue; /* Skip indices that do not change */
  114740. if( pUpIdx==pIdx ){
  114741. addrUniqueOk = upsertJump+1;
  114742. upsertBypass = sqlite3VdbeGoto(v, 0);
  114743. VdbeComment((v, "Skip upsert subroutine"));
  114744. sqlite3VdbeJumpHere(v, upsertJump);
  114745. }else{
  114746. addrUniqueOk = sqlite3VdbeMakeLabel(pParse);
  114747. }
  114748. if( bAffinityDone==0 && (pUpIdx==0 || pUpIdx==pIdx) ){
  114749. sqlite3TableAffinity(v, pTab, regNewData+1);
  114750. bAffinityDone = 1;
  114751. }
  114752. VdbeNoopComment((v, "prep index %s", pIdx->zName));
  114753. iThisCur = iIdxCur+ix;
  114754. /* Skip partial indices for which the WHERE clause is not true */
  114755. if( pIdx->pPartIdxWhere ){
  114756. sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[ix]);
  114757. pParse->iSelfTab = -(regNewData+1);
  114758. sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, addrUniqueOk,
  114759. SQLITE_JUMPIFNULL);
  114760. pParse->iSelfTab = 0;
  114761. }
  114762. /* Create a record for this index entry as it should appear after
  114763. ** the insert or update. Store that record in the aRegIdx[ix] register
  114764. */
  114765. regIdx = aRegIdx[ix]+1;
  114766. for(i=0; i<pIdx->nColumn; i++){
  114767. int iField = pIdx->aiColumn[i];
  114768. int x;
  114769. if( iField==XN_EXPR ){
  114770. pParse->iSelfTab = -(regNewData+1);
  114771. sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[i].pExpr, regIdx+i);
  114772. pParse->iSelfTab = 0;
  114773. VdbeComment((v, "%s column %d", pIdx->zName, i));
  114774. }else if( iField==XN_ROWID || iField==pTab->iPKey ){
  114775. x = regNewData;
  114776. sqlite3VdbeAddOp2(v, OP_IntCopy, x, regIdx+i);
  114777. VdbeComment((v, "rowid"));
  114778. }else{
  114779. testcase( sqlite3TableColumnToStorage(pTab, iField)!=iField );
  114780. x = sqlite3TableColumnToStorage(pTab, iField) + regNewData + 1;
  114781. sqlite3VdbeAddOp2(v, OP_SCopy, x, regIdx+i);
  114782. VdbeComment((v, "%s", pTab->aCol[iField].zName));
  114783. }
  114784. }
  114785. sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn, aRegIdx[ix]);
  114786. VdbeComment((v, "for %s", pIdx->zName));
  114787. #ifdef SQLITE_ENABLE_NULL_TRIM
  114788. if( pIdx->idxType==SQLITE_IDXTYPE_PRIMARYKEY ){
  114789. sqlite3SetMakeRecordP5(v, pIdx->pTable);
  114790. }
  114791. #endif
  114792. sqlite3VdbeReleaseRegisters(pParse, regIdx, pIdx->nColumn, 0, 0);
  114793. /* In an UPDATE operation, if this index is the PRIMARY KEY index
  114794. ** of a WITHOUT ROWID table and there has been no change the
  114795. ** primary key, then no collision is possible. The collision detection
  114796. ** logic below can all be skipped. */
  114797. if( isUpdate && pPk==pIdx && pkChng==0 ){
  114798. sqlite3VdbeResolveLabel(v, addrUniqueOk);
  114799. continue;
  114800. }
  114801. /* Find out what action to take in case there is a uniqueness conflict */
  114802. onError = pIdx->onError;
  114803. if( onError==OE_None ){
  114804. sqlite3VdbeResolveLabel(v, addrUniqueOk);
  114805. continue; /* pIdx is not a UNIQUE index */
  114806. }
  114807. if( overrideError!=OE_Default ){
  114808. onError = overrideError;
  114809. }else if( onError==OE_Default ){
  114810. onError = OE_Abort;
  114811. }
  114812. /* Figure out if the upsert clause applies to this index */
  114813. if( pUpIdx==pIdx ){
  114814. if( pUpsert->pUpsertSet==0 ){
  114815. onError = OE_Ignore; /* DO NOTHING is the same as INSERT OR IGNORE */
  114816. }else{
  114817. onError = OE_Update; /* DO UPDATE */
  114818. }
  114819. }
  114820. /* Collision detection may be omitted if all of the following are true:
  114821. ** (1) The conflict resolution algorithm is REPLACE
  114822. ** (2) The table is a WITHOUT ROWID table
  114823. ** (3) There are no secondary indexes on the table
  114824. ** (4) No delete triggers need to be fired if there is a conflict
  114825. ** (5) No FK constraint counters need to be updated if a conflict occurs.
  114826. **
  114827. ** This is not possible for ENABLE_PREUPDATE_HOOK builds, as the row
  114828. ** must be explicitly deleted in order to ensure any pre-update hook
  114829. ** is invoked. */
  114830. #ifndef SQLITE_ENABLE_PREUPDATE_HOOK
  114831. if( (ix==0 && pIdx->pNext==0) /* Condition 3 */
  114832. && pPk==pIdx /* Condition 2 */
  114833. && onError==OE_Replace /* Condition 1 */
  114834. && ( 0==(db->flags&SQLITE_RecTriggers) || /* Condition 4 */
  114835. 0==sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0))
  114836. && ( 0==(db->flags&SQLITE_ForeignKeys) || /* Condition 5 */
  114837. (0==pTab->pFKey && 0==sqlite3FkReferences(pTab)))
  114838. ){
  114839. sqlite3VdbeResolveLabel(v, addrUniqueOk);
  114840. continue;
  114841. }
  114842. #endif /* ifndef SQLITE_ENABLE_PREUPDATE_HOOK */
  114843. /* Check to see if the new index entry will be unique */
  114844. sqlite3VdbeVerifyAbortable(v, onError);
  114845. addrConflictCk =
  114846. sqlite3VdbeAddOp4Int(v, OP_NoConflict, iThisCur, addrUniqueOk,
  114847. regIdx, pIdx->nKeyCol); VdbeCoverage(v);
  114848. /* Generate code to handle collisions */
  114849. regR = (pIdx==pPk) ? regIdx : sqlite3GetTempRange(pParse, nPkField);
  114850. if( isUpdate || onError==OE_Replace ){
  114851. if( HasRowid(pTab) ){
  114852. sqlite3VdbeAddOp2(v, OP_IdxRowid, iThisCur, regR);
  114853. /* Conflict only if the rowid of the existing index entry
  114854. ** is different from old-rowid */
  114855. if( isUpdate ){
  114856. sqlite3VdbeAddOp3(v, OP_Eq, regR, addrUniqueOk, regOldData);
  114857. sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
  114858. VdbeCoverage(v);
  114859. }
  114860. }else{
  114861. int x;
  114862. /* Extract the PRIMARY KEY from the end of the index entry and
  114863. ** store it in registers regR..regR+nPk-1 */
  114864. if( pIdx!=pPk ){
  114865. for(i=0; i<pPk->nKeyCol; i++){
  114866. assert( pPk->aiColumn[i]>=0 );
  114867. x = sqlite3TableColumnToIndex(pIdx, pPk->aiColumn[i]);
  114868. sqlite3VdbeAddOp3(v, OP_Column, iThisCur, x, regR+i);
  114869. VdbeComment((v, "%s.%s", pTab->zName,
  114870. pTab->aCol[pPk->aiColumn[i]].zName));
  114871. }
  114872. }
  114873. if( isUpdate ){
  114874. /* If currently processing the PRIMARY KEY of a WITHOUT ROWID
  114875. ** table, only conflict if the new PRIMARY KEY values are actually
  114876. ** different from the old.
  114877. **
  114878. ** For a UNIQUE index, only conflict if the PRIMARY KEY values
  114879. ** of the matched index row are different from the original PRIMARY
  114880. ** KEY values of this row before the update. */
  114881. int addrJump = sqlite3VdbeCurrentAddr(v)+pPk->nKeyCol;
  114882. int op = OP_Ne;
  114883. int regCmp = (IsPrimaryKeyIndex(pIdx) ? regIdx : regR);
  114884. for(i=0; i<pPk->nKeyCol; i++){
  114885. char *p4 = (char*)sqlite3LocateCollSeq(pParse, pPk->azColl[i]);
  114886. x = pPk->aiColumn[i];
  114887. assert( x>=0 );
  114888. if( i==(pPk->nKeyCol-1) ){
  114889. addrJump = addrUniqueOk;
  114890. op = OP_Eq;
  114891. }
  114892. x = sqlite3TableColumnToStorage(pTab, x);
  114893. sqlite3VdbeAddOp4(v, op,
  114894. regOldData+1+x, addrJump, regCmp+i, p4, P4_COLLSEQ
  114895. );
  114896. sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
  114897. VdbeCoverageIf(v, op==OP_Eq);
  114898. VdbeCoverageIf(v, op==OP_Ne);
  114899. }
  114900. }
  114901. }
  114902. }
  114903. /* Generate code that executes if the new index entry is not unique */
  114904. assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
  114905. || onError==OE_Ignore || onError==OE_Replace || onError==OE_Update );
  114906. switch( onError ){
  114907. case OE_Rollback:
  114908. case OE_Abort:
  114909. case OE_Fail: {
  114910. testcase( onError==OE_Rollback );
  114911. testcase( onError==OE_Abort );
  114912. testcase( onError==OE_Fail );
  114913. sqlite3UniqueConstraint(pParse, onError, pIdx);
  114914. break;
  114915. }
  114916. #ifndef SQLITE_OMIT_UPSERT
  114917. case OE_Update: {
  114918. sqlite3UpsertDoUpdate(pParse, pUpsert, pTab, pIdx, iIdxCur+ix);
  114919. /* Fall through */
  114920. }
  114921. #endif
  114922. case OE_Ignore: {
  114923. testcase( onError==OE_Ignore );
  114924. sqlite3VdbeGoto(v, ignoreDest);
  114925. break;
  114926. }
  114927. default: {
  114928. int nConflictCk; /* Number of opcodes in conflict check logic */
  114929. assert( onError==OE_Replace );
  114930. nConflictCk = sqlite3VdbeCurrentAddr(v) - addrConflictCk;
  114931. assert( nConflictCk>0 );
  114932. testcase( nConflictCk>1 );
  114933. if( regTrigCnt ){
  114934. sqlite3MultiWrite(pParse);
  114935. nReplaceTrig++;
  114936. }
  114937. if( pTrigger && isUpdate ){
  114938. sqlite3VdbeAddOp1(v, OP_CursorLock, iDataCur);
  114939. }
  114940. sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
  114941. regR, nPkField, 0, OE_Replace,
  114942. (pIdx==pPk ? ONEPASS_SINGLE : ONEPASS_OFF), iThisCur);
  114943. if( pTrigger && isUpdate ){
  114944. sqlite3VdbeAddOp1(v, OP_CursorUnlock, iDataCur);
  114945. }
  114946. if( regTrigCnt ){
  114947. int addrBypass; /* Jump destination to bypass recheck logic */
  114948. sqlite3VdbeAddOp2(v, OP_AddImm, regTrigCnt, 1); /* incr trigger cnt */
  114949. addrBypass = sqlite3VdbeAddOp0(v, OP_Goto); /* Bypass recheck */
  114950. VdbeComment((v, "bypass recheck"));
  114951. /* Here we insert code that will be invoked after all constraint
  114952. ** checks have run, if and only if one or more replace triggers
  114953. ** fired. */
  114954. sqlite3VdbeResolveLabel(v, lblRecheckOk);
  114955. lblRecheckOk = sqlite3VdbeMakeLabel(pParse);
  114956. if( pIdx->pPartIdxWhere ){
  114957. /* Bypass the recheck if this partial index is not defined
  114958. ** for the current row */
  114959. sqlite3VdbeAddOp2(v, OP_IsNull, regIdx-1, lblRecheckOk);
  114960. VdbeCoverage(v);
  114961. }
  114962. /* Copy the constraint check code from above, except change
  114963. ** the constraint-ok jump destination to be the address of
  114964. ** the next retest block */
  114965. while( nConflictCk>0 ){
  114966. VdbeOp x; /* Conflict check opcode to copy */
  114967. /* The sqlite3VdbeAddOp4() call might reallocate the opcode array.
  114968. ** Hence, make a complete copy of the opcode, rather than using
  114969. ** a pointer to the opcode. */
  114970. x = *sqlite3VdbeGetOp(v, addrConflictCk);
  114971. if( x.opcode!=OP_IdxRowid ){
  114972. int p2; /* New P2 value for copied conflict check opcode */
  114973. const char *zP4;
  114974. if( sqlite3OpcodeProperty[x.opcode]&OPFLG_JUMP ){
  114975. p2 = lblRecheckOk;
  114976. }else{
  114977. p2 = x.p2;
  114978. }
  114979. zP4 = x.p4type==P4_INT32 ? SQLITE_INT_TO_PTR(x.p4.i) : x.p4.z;
  114980. sqlite3VdbeAddOp4(v, x.opcode, x.p1, p2, x.p3, zP4, x.p4type);
  114981. sqlite3VdbeChangeP5(v, x.p5);
  114982. VdbeCoverageIf(v, p2!=x.p2);
  114983. }
  114984. nConflictCk--;
  114985. addrConflictCk++;
  114986. }
  114987. /* If the retest fails, issue an abort */
  114988. sqlite3UniqueConstraint(pParse, OE_Abort, pIdx);
  114989. sqlite3VdbeJumpHere(v, addrBypass); /* Terminate the recheck bypass */
  114990. }
  114991. seenReplace = 1;
  114992. break;
  114993. }
  114994. }
  114995. if( pUpIdx==pIdx ){
  114996. sqlite3VdbeGoto(v, upsertJump+1);
  114997. sqlite3VdbeJumpHere(v, upsertBypass);
  114998. }else{
  114999. sqlite3VdbeResolveLabel(v, addrUniqueOk);
  115000. }
  115001. if( regR!=regIdx ) sqlite3ReleaseTempRange(pParse, regR, nPkField);
  115002. }
  115003. /* If the IPK constraint is a REPLACE, run it last */
  115004. if( ipkTop ){
  115005. sqlite3VdbeGoto(v, ipkTop);
  115006. VdbeComment((v, "Do IPK REPLACE"));
  115007. sqlite3VdbeJumpHere(v, ipkBottom);
  115008. }
  115009. /* Recheck all uniqueness constraints after replace triggers have run */
  115010. testcase( regTrigCnt!=0 && nReplaceTrig==0 );
  115011. assert( regTrigCnt!=0 || nReplaceTrig==0 );
  115012. if( nReplaceTrig ){
  115013. sqlite3VdbeAddOp2(v, OP_IfNot, regTrigCnt, lblRecheckOk);VdbeCoverage(v);
  115014. if( !pPk ){
  115015. if( isUpdate ){
  115016. sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRecheck, regOldData);
  115017. sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
  115018. VdbeCoverage(v);
  115019. }
  115020. sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRecheck, regNewData);
  115021. VdbeCoverage(v);
  115022. sqlite3RowidConstraint(pParse, OE_Abort, pTab);
  115023. }else{
  115024. sqlite3VdbeGoto(v, addrRecheck);
  115025. }
  115026. sqlite3VdbeResolveLabel(v, lblRecheckOk);
  115027. }
  115028. /* Generate the table record */
  115029. if( HasRowid(pTab) ){
  115030. int regRec = aRegIdx[ix];
  115031. sqlite3VdbeAddOp3(v, OP_MakeRecord, regNewData+1, pTab->nNVCol, regRec);
  115032. sqlite3SetMakeRecordP5(v, pTab);
  115033. if( !bAffinityDone ){
  115034. sqlite3TableAffinity(v, pTab, 0);
  115035. }
  115036. }
  115037. *pbMayReplace = seenReplace;
  115038. VdbeModuleComment((v, "END: GenCnstCks(%d)", seenReplace));
  115039. }
  115040. #ifdef SQLITE_ENABLE_NULL_TRIM
  115041. /*
  115042. ** Change the P5 operand on the last opcode (which should be an OP_MakeRecord)
  115043. ** to be the number of columns in table pTab that must not be NULL-trimmed.
  115044. **
  115045. ** Or if no columns of pTab may be NULL-trimmed, leave P5 at zero.
  115046. */
  115047. SQLITE_PRIVATE void sqlite3SetMakeRecordP5(Vdbe *v, Table *pTab){
  115048. u16 i;
  115049. /* Records with omitted columns are only allowed for schema format
  115050. ** version 2 and later (SQLite version 3.1.4, 2005-02-20). */
  115051. if( pTab->pSchema->file_format<2 ) return;
  115052. for(i=pTab->nCol-1; i>0; i--){
  115053. if( pTab->aCol[i].pDflt!=0 ) break;
  115054. if( pTab->aCol[i].colFlags & COLFLAG_PRIMKEY ) break;
  115055. }
  115056. sqlite3VdbeChangeP5(v, i+1);
  115057. }
  115058. #endif
  115059. /*
  115060. ** This routine generates code to finish the INSERT or UPDATE operation
  115061. ** that was started by a prior call to sqlite3GenerateConstraintChecks.
  115062. ** A consecutive range of registers starting at regNewData contains the
  115063. ** rowid and the content to be inserted.
  115064. **
  115065. ** The arguments to this routine should be the same as the first six
  115066. ** arguments to sqlite3GenerateConstraintChecks.
  115067. */
  115068. SQLITE_PRIVATE void sqlite3CompleteInsertion(
  115069. Parse *pParse, /* The parser context */
  115070. Table *pTab, /* the table into which we are inserting */
  115071. int iDataCur, /* Cursor of the canonical data source */
  115072. int iIdxCur, /* First index cursor */
  115073. int regNewData, /* Range of content */
  115074. int *aRegIdx, /* Register used by each index. 0 for unused indices */
  115075. int update_flags, /* True for UPDATE, False for INSERT */
  115076. int appendBias, /* True if this is likely to be an append */
  115077. int useSeekResult /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
  115078. ){
  115079. Vdbe *v; /* Prepared statements under construction */
  115080. Index *pIdx; /* An index being inserted or updated */
  115081. u8 pik_flags; /* flag values passed to the btree insert */
  115082. int i; /* Loop counter */
  115083. assert( update_flags==0
  115084. || update_flags==OPFLAG_ISUPDATE
  115085. || update_flags==(OPFLAG_ISUPDATE|OPFLAG_SAVEPOSITION)
  115086. );
  115087. v = sqlite3GetVdbe(pParse);
  115088. assert( v!=0 );
  115089. assert( pTab->pSelect==0 ); /* This table is not a VIEW */
  115090. for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
  115091. /* All REPLACE indexes are at the end of the list */
  115092. assert( pIdx->onError!=OE_Replace
  115093. || pIdx->pNext==0
  115094. || pIdx->pNext->onError==OE_Replace );
  115095. if( aRegIdx[i]==0 ) continue;
  115096. if( pIdx->pPartIdxWhere ){
  115097. sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2);
  115098. VdbeCoverage(v);
  115099. }
  115100. pik_flags = (useSeekResult ? OPFLAG_USESEEKRESULT : 0);
  115101. if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
  115102. assert( pParse->nested==0 );
  115103. pik_flags |= OPFLAG_NCHANGE;
  115104. pik_flags |= (update_flags & OPFLAG_SAVEPOSITION);
  115105. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  115106. if( update_flags==0 ){
  115107. int r = sqlite3GetTempReg(pParse);
  115108. sqlite3VdbeAddOp2(v, OP_Integer, 0, r);
  115109. sqlite3VdbeAddOp4(v, OP_Insert,
  115110. iIdxCur+i, aRegIdx[i], r, (char*)pTab, P4_TABLE
  115111. );
  115112. sqlite3VdbeChangeP5(v, OPFLAG_ISNOOP);
  115113. sqlite3ReleaseTempReg(pParse, r);
  115114. }
  115115. #endif
  115116. }
  115117. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iIdxCur+i, aRegIdx[i],
  115118. aRegIdx[i]+1,
  115119. pIdx->uniqNotNull ? pIdx->nKeyCol: pIdx->nColumn);
  115120. sqlite3VdbeChangeP5(v, pik_flags);
  115121. }
  115122. if( !HasRowid(pTab) ) return;
  115123. if( pParse->nested ){
  115124. pik_flags = 0;
  115125. }else{
  115126. pik_flags = OPFLAG_NCHANGE;
  115127. pik_flags |= (update_flags?update_flags:OPFLAG_LASTROWID);
  115128. }
  115129. if( appendBias ){
  115130. pik_flags |= OPFLAG_APPEND;
  115131. }
  115132. if( useSeekResult ){
  115133. pik_flags |= OPFLAG_USESEEKRESULT;
  115134. }
  115135. sqlite3VdbeAddOp3(v, OP_Insert, iDataCur, aRegIdx[i], regNewData);
  115136. if( !pParse->nested ){
  115137. sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
  115138. }
  115139. sqlite3VdbeChangeP5(v, pik_flags);
  115140. }
  115141. /*
  115142. ** Allocate cursors for the pTab table and all its indices and generate
  115143. ** code to open and initialized those cursors.
  115144. **
  115145. ** The cursor for the object that contains the complete data (normally
  115146. ** the table itself, but the PRIMARY KEY index in the case of a WITHOUT
  115147. ** ROWID table) is returned in *piDataCur. The first index cursor is
  115148. ** returned in *piIdxCur. The number of indices is returned.
  115149. **
  115150. ** Use iBase as the first cursor (either the *piDataCur for rowid tables
  115151. ** or the first index for WITHOUT ROWID tables) if it is non-negative.
  115152. ** If iBase is negative, then allocate the next available cursor.
  115153. **
  115154. ** For a rowid table, *piDataCur will be exactly one less than *piIdxCur.
  115155. ** For a WITHOUT ROWID table, *piDataCur will be somewhere in the range
  115156. ** of *piIdxCurs, depending on where the PRIMARY KEY index appears on the
  115157. ** pTab->pIndex list.
  115158. **
  115159. ** If pTab is a virtual table, then this routine is a no-op and the
  115160. ** *piDataCur and *piIdxCur values are left uninitialized.
  115161. */
  115162. SQLITE_PRIVATE int sqlite3OpenTableAndIndices(
  115163. Parse *pParse, /* Parsing context */
  115164. Table *pTab, /* Table to be opened */
  115165. int op, /* OP_OpenRead or OP_OpenWrite */
  115166. u8 p5, /* P5 value for OP_Open* opcodes (except on WITHOUT ROWID) */
  115167. int iBase, /* Use this for the table cursor, if there is one */
  115168. u8 *aToOpen, /* If not NULL: boolean for each table and index */
  115169. int *piDataCur, /* Write the database source cursor number here */
  115170. int *piIdxCur /* Write the first index cursor number here */
  115171. ){
  115172. int i;
  115173. int iDb;
  115174. int iDataCur;
  115175. Index *pIdx;
  115176. Vdbe *v;
  115177. assert( op==OP_OpenRead || op==OP_OpenWrite );
  115178. assert( op==OP_OpenWrite || p5==0 );
  115179. if( IsVirtual(pTab) ){
  115180. /* This routine is a no-op for virtual tables. Leave the output
  115181. ** variables *piDataCur and *piIdxCur uninitialized so that valgrind
  115182. ** can detect if they are used by mistake in the caller. */
  115183. return 0;
  115184. }
  115185. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  115186. v = sqlite3GetVdbe(pParse);
  115187. assert( v!=0 );
  115188. if( iBase<0 ) iBase = pParse->nTab;
  115189. iDataCur = iBase++;
  115190. if( piDataCur ) *piDataCur = iDataCur;
  115191. if( HasRowid(pTab) && (aToOpen==0 || aToOpen[0]) ){
  115192. sqlite3OpenTable(pParse, iDataCur, iDb, pTab, op);
  115193. }else{
  115194. sqlite3TableLock(pParse, iDb, pTab->tnum, op==OP_OpenWrite, pTab->zName);
  115195. }
  115196. if( piIdxCur ) *piIdxCur = iBase;
  115197. for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
  115198. int iIdxCur = iBase++;
  115199. assert( pIdx->pSchema==pTab->pSchema );
  115200. if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
  115201. if( piDataCur ) *piDataCur = iIdxCur;
  115202. p5 = 0;
  115203. }
  115204. if( aToOpen==0 || aToOpen[i+1] ){
  115205. sqlite3VdbeAddOp3(v, op, iIdxCur, pIdx->tnum, iDb);
  115206. sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  115207. sqlite3VdbeChangeP5(v, p5);
  115208. VdbeComment((v, "%s", pIdx->zName));
  115209. }
  115210. }
  115211. if( iBase>pParse->nTab ) pParse->nTab = iBase;
  115212. return i;
  115213. }
  115214. #ifdef SQLITE_TEST
  115215. /*
  115216. ** The following global variable is incremented whenever the
  115217. ** transfer optimization is used. This is used for testing
  115218. ** purposes only - to make sure the transfer optimization really
  115219. ** is happening when it is supposed to.
  115220. */
  115221. SQLITE_API int sqlite3_xferopt_count;
  115222. #endif /* SQLITE_TEST */
  115223. #ifndef SQLITE_OMIT_XFER_OPT
  115224. /*
  115225. ** Check to see if index pSrc is compatible as a source of data
  115226. ** for index pDest in an insert transfer optimization. The rules
  115227. ** for a compatible index:
  115228. **
  115229. ** * The index is over the same set of columns
  115230. ** * The same DESC and ASC markings occurs on all columns
  115231. ** * The same onError processing (OE_Abort, OE_Ignore, etc)
  115232. ** * The same collating sequence on each column
  115233. ** * The index has the exact same WHERE clause
  115234. */
  115235. static int xferCompatibleIndex(Index *pDest, Index *pSrc){
  115236. int i;
  115237. assert( pDest && pSrc );
  115238. assert( pDest->pTable!=pSrc->pTable );
  115239. if( pDest->nKeyCol!=pSrc->nKeyCol || pDest->nColumn!=pSrc->nColumn ){
  115240. return 0; /* Different number of columns */
  115241. }
  115242. if( pDest->onError!=pSrc->onError ){
  115243. return 0; /* Different conflict resolution strategies */
  115244. }
  115245. for(i=0; i<pSrc->nKeyCol; i++){
  115246. if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
  115247. return 0; /* Different columns indexed */
  115248. }
  115249. if( pSrc->aiColumn[i]==XN_EXPR ){
  115250. assert( pSrc->aColExpr!=0 && pDest->aColExpr!=0 );
  115251. if( sqlite3ExprCompare(0, pSrc->aColExpr->a[i].pExpr,
  115252. pDest->aColExpr->a[i].pExpr, -1)!=0 ){
  115253. return 0; /* Different expressions in the index */
  115254. }
  115255. }
  115256. if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
  115257. return 0; /* Different sort orders */
  115258. }
  115259. if( sqlite3_stricmp(pSrc->azColl[i],pDest->azColl[i])!=0 ){
  115260. return 0; /* Different collating sequences */
  115261. }
  115262. }
  115263. if( sqlite3ExprCompare(0, pSrc->pPartIdxWhere, pDest->pPartIdxWhere, -1) ){
  115264. return 0; /* Different WHERE clauses */
  115265. }
  115266. /* If no test above fails then the indices must be compatible */
  115267. return 1;
  115268. }
  115269. /*
  115270. ** Attempt the transfer optimization on INSERTs of the form
  115271. **
  115272. ** INSERT INTO tab1 SELECT * FROM tab2;
  115273. **
  115274. ** The xfer optimization transfers raw records from tab2 over to tab1.
  115275. ** Columns are not decoded and reassembled, which greatly improves
  115276. ** performance. Raw index records are transferred in the same way.
  115277. **
  115278. ** The xfer optimization is only attempted if tab1 and tab2 are compatible.
  115279. ** There are lots of rules for determining compatibility - see comments
  115280. ** embedded in the code for details.
  115281. **
  115282. ** This routine returns TRUE if the optimization is guaranteed to be used.
  115283. ** Sometimes the xfer optimization will only work if the destination table
  115284. ** is empty - a factor that can only be determined at run-time. In that
  115285. ** case, this routine generates code for the xfer optimization but also
  115286. ** does a test to see if the destination table is empty and jumps over the
  115287. ** xfer optimization code if the test fails. In that case, this routine
  115288. ** returns FALSE so that the caller will know to go ahead and generate
  115289. ** an unoptimized transfer. This routine also returns FALSE if there
  115290. ** is no chance that the xfer optimization can be applied.
  115291. **
  115292. ** This optimization is particularly useful at making VACUUM run faster.
  115293. */
  115294. static int xferOptimization(
  115295. Parse *pParse, /* Parser context */
  115296. Table *pDest, /* The table we are inserting into */
  115297. Select *pSelect, /* A SELECT statement to use as the data source */
  115298. int onError, /* How to handle constraint errors */
  115299. int iDbDest /* The database of pDest */
  115300. ){
  115301. sqlite3 *db = pParse->db;
  115302. ExprList *pEList; /* The result set of the SELECT */
  115303. Table *pSrc; /* The table in the FROM clause of SELECT */
  115304. Index *pSrcIdx, *pDestIdx; /* Source and destination indices */
  115305. struct SrcList_item *pItem; /* An element of pSelect->pSrc */
  115306. int i; /* Loop counter */
  115307. int iDbSrc; /* The database of pSrc */
  115308. int iSrc, iDest; /* Cursors from source and destination */
  115309. int addr1, addr2; /* Loop addresses */
  115310. int emptyDestTest = 0; /* Address of test for empty pDest */
  115311. int emptySrcTest = 0; /* Address of test for empty pSrc */
  115312. Vdbe *v; /* The VDBE we are building */
  115313. int regAutoinc; /* Memory register used by AUTOINC */
  115314. int destHasUniqueIdx = 0; /* True if pDest has a UNIQUE index */
  115315. int regData, regRowid; /* Registers holding data and rowid */
  115316. if( pSelect==0 ){
  115317. return 0; /* Must be of the form INSERT INTO ... SELECT ... */
  115318. }
  115319. if( pParse->pWith || pSelect->pWith ){
  115320. /* Do not attempt to process this query if there are an WITH clauses
  115321. ** attached to it. Proceeding may generate a false "no such table: xxx"
  115322. ** error if pSelect reads from a CTE named "xxx". */
  115323. return 0;
  115324. }
  115325. if( sqlite3TriggerList(pParse, pDest) ){
  115326. return 0; /* tab1 must not have triggers */
  115327. }
  115328. #ifndef SQLITE_OMIT_VIRTUALTABLE
  115329. if( IsVirtual(pDest) ){
  115330. return 0; /* tab1 must not be a virtual table */
  115331. }
  115332. #endif
  115333. if( onError==OE_Default ){
  115334. if( pDest->iPKey>=0 ) onError = pDest->keyConf;
  115335. if( onError==OE_Default ) onError = OE_Abort;
  115336. }
  115337. assert(pSelect->pSrc); /* allocated even if there is no FROM clause */
  115338. if( pSelect->pSrc->nSrc!=1 ){
  115339. return 0; /* FROM clause must have exactly one term */
  115340. }
  115341. if( pSelect->pSrc->a[0].pSelect ){
  115342. return 0; /* FROM clause cannot contain a subquery */
  115343. }
  115344. if( pSelect->pWhere ){
  115345. return 0; /* SELECT may not have a WHERE clause */
  115346. }
  115347. if( pSelect->pOrderBy ){
  115348. return 0; /* SELECT may not have an ORDER BY clause */
  115349. }
  115350. /* Do not need to test for a HAVING clause. If HAVING is present but
  115351. ** there is no ORDER BY, we will get an error. */
  115352. if( pSelect->pGroupBy ){
  115353. return 0; /* SELECT may not have a GROUP BY clause */
  115354. }
  115355. if( pSelect->pLimit ){
  115356. return 0; /* SELECT may not have a LIMIT clause */
  115357. }
  115358. if( pSelect->pPrior ){
  115359. return 0; /* SELECT may not be a compound query */
  115360. }
  115361. if( pSelect->selFlags & SF_Distinct ){
  115362. return 0; /* SELECT may not be DISTINCT */
  115363. }
  115364. pEList = pSelect->pEList;
  115365. assert( pEList!=0 );
  115366. if( pEList->nExpr!=1 ){
  115367. return 0; /* The result set must have exactly one column */
  115368. }
  115369. assert( pEList->a[0].pExpr );
  115370. if( pEList->a[0].pExpr->op!=TK_ASTERISK ){
  115371. return 0; /* The result set must be the special operator "*" */
  115372. }
  115373. /* At this point we have established that the statement is of the
  115374. ** correct syntactic form to participate in this optimization. Now
  115375. ** we have to check the semantics.
  115376. */
  115377. pItem = pSelect->pSrc->a;
  115378. pSrc = sqlite3LocateTableItem(pParse, 0, pItem);
  115379. if( pSrc==0 ){
  115380. return 0; /* FROM clause does not contain a real table */
  115381. }
  115382. if( pSrc->tnum==pDest->tnum && pSrc->pSchema==pDest->pSchema ){
  115383. testcase( pSrc!=pDest ); /* Possible due to bad sqlite_master.rootpage */
  115384. return 0; /* tab1 and tab2 may not be the same table */
  115385. }
  115386. if( HasRowid(pDest)!=HasRowid(pSrc) ){
  115387. return 0; /* source and destination must both be WITHOUT ROWID or not */
  115388. }
  115389. #ifndef SQLITE_OMIT_VIRTUALTABLE
  115390. if( IsVirtual(pSrc) ){
  115391. return 0; /* tab2 must not be a virtual table */
  115392. }
  115393. #endif
  115394. if( pSrc->pSelect ){
  115395. return 0; /* tab2 may not be a view */
  115396. }
  115397. if( pDest->nCol!=pSrc->nCol ){
  115398. return 0; /* Number of columns must be the same in tab1 and tab2 */
  115399. }
  115400. if( pDest->iPKey!=pSrc->iPKey ){
  115401. return 0; /* Both tables must have the same INTEGER PRIMARY KEY */
  115402. }
  115403. for(i=0; i<pDest->nCol; i++){
  115404. Column *pDestCol = &pDest->aCol[i];
  115405. Column *pSrcCol = &pSrc->aCol[i];
  115406. #ifdef SQLITE_ENABLE_HIDDEN_COLUMNS
  115407. if( (db->mDbFlags & DBFLAG_Vacuum)==0
  115408. && (pDestCol->colFlags | pSrcCol->colFlags) & COLFLAG_HIDDEN
  115409. ){
  115410. return 0; /* Neither table may have __hidden__ columns */
  115411. }
  115412. #endif
  115413. #ifndef SQLITE_OMIT_GENERATED_COLUMNS
  115414. /* Even if tables t1 and t2 have identical schemas, if they contain
  115415. ** generated columns, then this statement is semantically incorrect:
  115416. **
  115417. ** INSERT INTO t2 SELECT * FROM t1;
  115418. **
  115419. ** The reason is that generated column values are returned by the
  115420. ** the SELECT statement on the right but the INSERT statement on the
  115421. ** left wants them to be omitted.
  115422. **
  115423. ** Nevertheless, this is a useful notational shorthand to tell SQLite
  115424. ** to do a bulk transfer all of the content from t1 over to t2.
  115425. **
  115426. ** We could, in theory, disable this (except for internal use by the
  115427. ** VACUUM command where it is actually needed). But why do that? It
  115428. ** seems harmless enough, and provides a useful service.
  115429. */
  115430. if( (pDestCol->colFlags & COLFLAG_GENERATED) !=
  115431. (pSrcCol->colFlags & COLFLAG_GENERATED) ){
  115432. return 0; /* Both columns have the same generated-column type */
  115433. }
  115434. /* But the transfer is only allowed if both the source and destination
  115435. ** tables have the exact same expressions for generated columns.
  115436. ** This requirement could be relaxed for VIRTUAL columns, I suppose.
  115437. */
  115438. if( (pDestCol->colFlags & COLFLAG_GENERATED)!=0 ){
  115439. if( sqlite3ExprCompare(0, pSrcCol->pDflt, pDestCol->pDflt, -1)!=0 ){
  115440. testcase( pDestCol->colFlags & COLFLAG_VIRTUAL );
  115441. testcase( pDestCol->colFlags & COLFLAG_STORED );
  115442. return 0; /* Different generator expressions */
  115443. }
  115444. }
  115445. #endif
  115446. if( pDestCol->affinity!=pSrcCol->affinity ){
  115447. return 0; /* Affinity must be the same on all columns */
  115448. }
  115449. if( sqlite3_stricmp(pDestCol->zColl, pSrcCol->zColl)!=0 ){
  115450. return 0; /* Collating sequence must be the same on all columns */
  115451. }
  115452. if( pDestCol->notNull && !pSrcCol->notNull ){
  115453. return 0; /* tab2 must be NOT NULL if tab1 is */
  115454. }
  115455. /* Default values for second and subsequent columns need to match. */
  115456. if( (pDestCol->colFlags & COLFLAG_GENERATED)==0 && i>0 ){
  115457. assert( pDestCol->pDflt==0 || pDestCol->pDflt->op==TK_SPAN );
  115458. assert( pSrcCol->pDflt==0 || pSrcCol->pDflt->op==TK_SPAN );
  115459. if( (pDestCol->pDflt==0)!=(pSrcCol->pDflt==0)
  115460. || (pDestCol->pDflt && strcmp(pDestCol->pDflt->u.zToken,
  115461. pSrcCol->pDflt->u.zToken)!=0)
  115462. ){
  115463. return 0; /* Default values must be the same for all columns */
  115464. }
  115465. }
  115466. }
  115467. for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
  115468. if( IsUniqueIndex(pDestIdx) ){
  115469. destHasUniqueIdx = 1;
  115470. }
  115471. for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
  115472. if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
  115473. }
  115474. if( pSrcIdx==0 ){
  115475. return 0; /* pDestIdx has no corresponding index in pSrc */
  115476. }
  115477. if( pSrcIdx->tnum==pDestIdx->tnum && pSrc->pSchema==pDest->pSchema
  115478. && sqlite3FaultSim(411)==SQLITE_OK ){
  115479. /* The sqlite3FaultSim() call allows this corruption test to be
  115480. ** bypassed during testing, in order to exercise other corruption tests
  115481. ** further downstream. */
  115482. return 0; /* Corrupt schema - two indexes on the same btree */
  115483. }
  115484. }
  115485. #ifndef SQLITE_OMIT_CHECK
  115486. if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1) ){
  115487. return 0; /* Tables have different CHECK constraints. Ticket #2252 */
  115488. }
  115489. #endif
  115490. #ifndef SQLITE_OMIT_FOREIGN_KEY
  115491. /* Disallow the transfer optimization if the destination table constains
  115492. ** any foreign key constraints. This is more restrictive than necessary.
  115493. ** But the main beneficiary of the transfer optimization is the VACUUM
  115494. ** command, and the VACUUM command disables foreign key constraints. So
  115495. ** the extra complication to make this rule less restrictive is probably
  115496. ** not worth the effort. Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
  115497. */
  115498. if( (db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){
  115499. return 0;
  115500. }
  115501. #endif
  115502. if( (db->flags & SQLITE_CountRows)!=0 ){
  115503. return 0; /* xfer opt does not play well with PRAGMA count_changes */
  115504. }
  115505. /* If we get this far, it means that the xfer optimization is at
  115506. ** least a possibility, though it might only work if the destination
  115507. ** table (tab1) is initially empty.
  115508. */
  115509. #ifdef SQLITE_TEST
  115510. sqlite3_xferopt_count++;
  115511. #endif
  115512. iDbSrc = sqlite3SchemaToIndex(db, pSrc->pSchema);
  115513. v = sqlite3GetVdbe(pParse);
  115514. sqlite3CodeVerifySchema(pParse, iDbSrc);
  115515. iSrc = pParse->nTab++;
  115516. iDest = pParse->nTab++;
  115517. regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
  115518. regData = sqlite3GetTempReg(pParse);
  115519. regRowid = sqlite3GetTempReg(pParse);
  115520. sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
  115521. assert( HasRowid(pDest) || destHasUniqueIdx );
  115522. if( (db->mDbFlags & DBFLAG_Vacuum)==0 && (
  115523. (pDest->iPKey<0 && pDest->pIndex!=0) /* (1) */
  115524. || destHasUniqueIdx /* (2) */
  115525. || (onError!=OE_Abort && onError!=OE_Rollback) /* (3) */
  115526. )){
  115527. /* In some circumstances, we are able to run the xfer optimization
  115528. ** only if the destination table is initially empty. Unless the
  115529. ** DBFLAG_Vacuum flag is set, this block generates code to make
  115530. ** that determination. If DBFLAG_Vacuum is set, then the destination
  115531. ** table is always empty.
  115532. **
  115533. ** Conditions under which the destination must be empty:
  115534. **
  115535. ** (1) There is no INTEGER PRIMARY KEY but there are indices.
  115536. ** (If the destination is not initially empty, the rowid fields
  115537. ** of index entries might need to change.)
  115538. **
  115539. ** (2) The destination has a unique index. (The xfer optimization
  115540. ** is unable to test uniqueness.)
  115541. **
  115542. ** (3) onError is something other than OE_Abort and OE_Rollback.
  115543. */
  115544. addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0); VdbeCoverage(v);
  115545. emptyDestTest = sqlite3VdbeAddOp0(v, OP_Goto);
  115546. sqlite3VdbeJumpHere(v, addr1);
  115547. }
  115548. if( HasRowid(pSrc) ){
  115549. u8 insFlags;
  115550. sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
  115551. emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
  115552. if( pDest->iPKey>=0 ){
  115553. addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
  115554. sqlite3VdbeVerifyAbortable(v, onError);
  115555. addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
  115556. VdbeCoverage(v);
  115557. sqlite3RowidConstraint(pParse, onError, pDest);
  115558. sqlite3VdbeJumpHere(v, addr2);
  115559. autoIncStep(pParse, regAutoinc, regRowid);
  115560. }else if( pDest->pIndex==0 && !(db->mDbFlags & DBFLAG_VacuumInto) ){
  115561. addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
  115562. }else{
  115563. addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
  115564. assert( (pDest->tabFlags & TF_Autoincrement)==0 );
  115565. }
  115566. if( db->mDbFlags & DBFLAG_Vacuum ){
  115567. sqlite3VdbeAddOp1(v, OP_SeekEnd, iDest);
  115568. insFlags = OPFLAG_APPEND|OPFLAG_USESEEKRESULT;
  115569. }else{
  115570. insFlags = OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND;
  115571. }
  115572. sqlite3VdbeAddOp3(v, OP_RowData, iSrc, regData, 1);
  115573. sqlite3VdbeAddOp4(v, OP_Insert, iDest, regData, regRowid,
  115574. (char*)pDest, P4_TABLE);
  115575. sqlite3VdbeChangeP5(v, insFlags);
  115576. sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1); VdbeCoverage(v);
  115577. sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
  115578. sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
  115579. }else{
  115580. sqlite3TableLock(pParse, iDbDest, pDest->tnum, 1, pDest->zName);
  115581. sqlite3TableLock(pParse, iDbSrc, pSrc->tnum, 0, pSrc->zName);
  115582. }
  115583. for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
  115584. u8 idxInsFlags = 0;
  115585. for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
  115586. if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
  115587. }
  115588. assert( pSrcIdx );
  115589. sqlite3VdbeAddOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc);
  115590. sqlite3VdbeSetP4KeyInfo(pParse, pSrcIdx);
  115591. VdbeComment((v, "%s", pSrcIdx->zName));
  115592. sqlite3VdbeAddOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest);
  115593. sqlite3VdbeSetP4KeyInfo(pParse, pDestIdx);
  115594. sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR);
  115595. VdbeComment((v, "%s", pDestIdx->zName));
  115596. addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
  115597. if( db->mDbFlags & DBFLAG_Vacuum ){
  115598. /* This INSERT command is part of a VACUUM operation, which guarantees
  115599. ** that the destination table is empty. If all indexed columns use
  115600. ** collation sequence BINARY, then it can also be assumed that the
  115601. ** index will be populated by inserting keys in strictly sorted
  115602. ** order. In this case, instead of seeking within the b-tree as part
  115603. ** of every OP_IdxInsert opcode, an OP_SeekEnd is added before the
  115604. ** OP_IdxInsert to seek to the point within the b-tree where each key
  115605. ** should be inserted. This is faster.
  115606. **
  115607. ** If any of the indexed columns use a collation sequence other than
  115608. ** BINARY, this optimization is disabled. This is because the user
  115609. ** might change the definition of a collation sequence and then run
  115610. ** a VACUUM command. In that case keys may not be written in strictly
  115611. ** sorted order. */
  115612. for(i=0; i<pSrcIdx->nColumn; i++){
  115613. const char *zColl = pSrcIdx->azColl[i];
  115614. if( sqlite3_stricmp(sqlite3StrBINARY, zColl) ) break;
  115615. }
  115616. if( i==pSrcIdx->nColumn ){
  115617. idxInsFlags = OPFLAG_USESEEKRESULT;
  115618. sqlite3VdbeAddOp1(v, OP_SeekEnd, iDest);
  115619. }
  115620. }else if( !HasRowid(pSrc) && pDestIdx->idxType==SQLITE_IDXTYPE_PRIMARYKEY ){
  115621. idxInsFlags |= OPFLAG_NCHANGE;
  115622. }
  115623. sqlite3VdbeAddOp3(v, OP_RowData, iSrc, regData, 1);
  115624. sqlite3VdbeAddOp2(v, OP_IdxInsert, iDest, regData);
  115625. sqlite3VdbeChangeP5(v, idxInsFlags|OPFLAG_APPEND);
  115626. sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1); VdbeCoverage(v);
  115627. sqlite3VdbeJumpHere(v, addr1);
  115628. sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
  115629. sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
  115630. }
  115631. if( emptySrcTest ) sqlite3VdbeJumpHere(v, emptySrcTest);
  115632. sqlite3ReleaseTempReg(pParse, regRowid);
  115633. sqlite3ReleaseTempReg(pParse, regData);
  115634. if( emptyDestTest ){
  115635. sqlite3AutoincrementEnd(pParse);
  115636. sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
  115637. sqlite3VdbeJumpHere(v, emptyDestTest);
  115638. sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
  115639. return 0;
  115640. }else{
  115641. return 1;
  115642. }
  115643. }
  115644. #endif /* SQLITE_OMIT_XFER_OPT */
  115645. /************** End of insert.c **********************************************/
  115646. /************** Begin file legacy.c ******************************************/
  115647. /*
  115648. ** 2001 September 15
  115649. **
  115650. ** The author disclaims copyright to this source code. In place of
  115651. ** a legal notice, here is a blessing:
  115652. **
  115653. ** May you do good and not evil.
  115654. ** May you find forgiveness for yourself and forgive others.
  115655. ** May you share freely, never taking more than you give.
  115656. **
  115657. *************************************************************************
  115658. ** Main file for the SQLite library. The routines in this file
  115659. ** implement the programmer interface to the library. Routines in
  115660. ** other files are for internal use by SQLite and should not be
  115661. ** accessed by users of the library.
  115662. */
  115663. /* #include "sqliteInt.h" */
  115664. /*
  115665. ** Execute SQL code. Return one of the SQLITE_ success/failure
  115666. ** codes. Also write an error message into memory obtained from
  115667. ** malloc() and make *pzErrMsg point to that message.
  115668. **
  115669. ** If the SQL is a query, then for each row in the query result
  115670. ** the xCallback() function is called. pArg becomes the first
  115671. ** argument to xCallback(). If xCallback=NULL then no callback
  115672. ** is invoked, even for queries.
  115673. */
  115674. SQLITE_API int sqlite3_exec(
  115675. sqlite3 *db, /* The database on which the SQL executes */
  115676. const char *zSql, /* The SQL to be executed */
  115677. sqlite3_callback xCallback, /* Invoke this callback routine */
  115678. void *pArg, /* First argument to xCallback() */
  115679. char **pzErrMsg /* Write error messages here */
  115680. ){
  115681. int rc = SQLITE_OK; /* Return code */
  115682. const char *zLeftover; /* Tail of unprocessed SQL */
  115683. sqlite3_stmt *pStmt = 0; /* The current SQL statement */
  115684. char **azCols = 0; /* Names of result columns */
  115685. int callbackIsInit; /* True if callback data is initialized */
  115686. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  115687. if( zSql==0 ) zSql = "";
  115688. sqlite3_mutex_enter(db->mutex);
  115689. sqlite3Error(db, SQLITE_OK);
  115690. while( rc==SQLITE_OK && zSql[0] ){
  115691. int nCol = 0;
  115692. char **azVals = 0;
  115693. pStmt = 0;
  115694. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
  115695. assert( rc==SQLITE_OK || pStmt==0 );
  115696. if( rc!=SQLITE_OK ){
  115697. continue;
  115698. }
  115699. if( !pStmt ){
  115700. /* this happens for a comment or white-space */
  115701. zSql = zLeftover;
  115702. continue;
  115703. }
  115704. callbackIsInit = 0;
  115705. while( 1 ){
  115706. int i;
  115707. rc = sqlite3_step(pStmt);
  115708. /* Invoke the callback function if required */
  115709. if( xCallback && (SQLITE_ROW==rc ||
  115710. (SQLITE_DONE==rc && !callbackIsInit
  115711. && db->flags&SQLITE_NullCallback)) ){
  115712. if( !callbackIsInit ){
  115713. nCol = sqlite3_column_count(pStmt);
  115714. azCols = sqlite3DbMallocRaw(db, (2*nCol+1)*sizeof(const char*));
  115715. if( azCols==0 ){
  115716. goto exec_out;
  115717. }
  115718. for(i=0; i<nCol; i++){
  115719. azCols[i] = (char *)sqlite3_column_name(pStmt, i);
  115720. /* sqlite3VdbeSetColName() installs column names as UTF8
  115721. ** strings so there is no way for sqlite3_column_name() to fail. */
  115722. assert( azCols[i]!=0 );
  115723. }
  115724. callbackIsInit = 1;
  115725. }
  115726. if( rc==SQLITE_ROW ){
  115727. azVals = &azCols[nCol];
  115728. for(i=0; i<nCol; i++){
  115729. azVals[i] = (char *)sqlite3_column_text(pStmt, i);
  115730. if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
  115731. sqlite3OomFault(db);
  115732. goto exec_out;
  115733. }
  115734. }
  115735. azVals[i] = 0;
  115736. }
  115737. if( xCallback(pArg, nCol, azVals, azCols) ){
  115738. /* EVIDENCE-OF: R-38229-40159 If the callback function to
  115739. ** sqlite3_exec() returns non-zero, then sqlite3_exec() will
  115740. ** return SQLITE_ABORT. */
  115741. rc = SQLITE_ABORT;
  115742. sqlite3VdbeFinalize((Vdbe *)pStmt);
  115743. pStmt = 0;
  115744. sqlite3Error(db, SQLITE_ABORT);
  115745. goto exec_out;
  115746. }
  115747. }
  115748. if( rc!=SQLITE_ROW ){
  115749. rc = sqlite3VdbeFinalize((Vdbe *)pStmt);
  115750. pStmt = 0;
  115751. zSql = zLeftover;
  115752. while( sqlite3Isspace(zSql[0]) ) zSql++;
  115753. break;
  115754. }
  115755. }
  115756. sqlite3DbFree(db, azCols);
  115757. azCols = 0;
  115758. }
  115759. exec_out:
  115760. if( pStmt ) sqlite3VdbeFinalize((Vdbe *)pStmt);
  115761. sqlite3DbFree(db, azCols);
  115762. rc = sqlite3ApiExit(db, rc);
  115763. if( rc!=SQLITE_OK && pzErrMsg ){
  115764. *pzErrMsg = sqlite3DbStrDup(0, sqlite3_errmsg(db));
  115765. if( *pzErrMsg==0 ){
  115766. rc = SQLITE_NOMEM_BKPT;
  115767. sqlite3Error(db, SQLITE_NOMEM);
  115768. }
  115769. }else if( pzErrMsg ){
  115770. *pzErrMsg = 0;
  115771. }
  115772. assert( (rc&db->errMask)==rc );
  115773. sqlite3_mutex_leave(db->mutex);
  115774. return rc;
  115775. }
  115776. /************** End of legacy.c **********************************************/
  115777. /************** Begin file loadext.c *****************************************/
  115778. /*
  115779. ** 2006 June 7
  115780. **
  115781. ** The author disclaims copyright to this source code. In place of
  115782. ** a legal notice, here is a blessing:
  115783. **
  115784. ** May you do good and not evil.
  115785. ** May you find forgiveness for yourself and forgive others.
  115786. ** May you share freely, never taking more than you give.
  115787. **
  115788. *************************************************************************
  115789. ** This file contains code used to dynamically load extensions into
  115790. ** the SQLite library.
  115791. */
  115792. #ifndef SQLITE_CORE
  115793. #define SQLITE_CORE 1 /* Disable the API redefinition in sqlite3ext.h */
  115794. #endif
  115795. /************** Include sqlite3ext.h in the middle of loadext.c **************/
  115796. /************** Begin file sqlite3ext.h **************************************/
  115797. /*
  115798. ** 2006 June 7
  115799. **
  115800. ** The author disclaims copyright to this source code. In place of
  115801. ** a legal notice, here is a blessing:
  115802. **
  115803. ** May you do good and not evil.
  115804. ** May you find forgiveness for yourself and forgive others.
  115805. ** May you share freely, never taking more than you give.
  115806. **
  115807. *************************************************************************
  115808. ** This header file defines the SQLite interface for use by
  115809. ** shared libraries that want to be imported as extensions into
  115810. ** an SQLite instance. Shared libraries that intend to be loaded
  115811. ** as extensions by SQLite should #include this file instead of
  115812. ** sqlite3.h.
  115813. */
  115814. #ifndef SQLITE3EXT_H
  115815. #define SQLITE3EXT_H
  115816. /* #include "sqlite3.h" */
  115817. /*
  115818. ** The following structure holds pointers to all of the SQLite API
  115819. ** routines.
  115820. **
  115821. ** WARNING: In order to maintain backwards compatibility, add new
  115822. ** interfaces to the end of this structure only. If you insert new
  115823. ** interfaces in the middle of this structure, then older different
  115824. ** versions of SQLite will not be able to load each other's shared
  115825. ** libraries!
  115826. */
  115827. struct sqlite3_api_routines {
  115828. void * (*aggregate_context)(sqlite3_context*,int nBytes);
  115829. int (*aggregate_count)(sqlite3_context*);
  115830. int (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
  115831. int (*bind_double)(sqlite3_stmt*,int,double);
  115832. int (*bind_int)(sqlite3_stmt*,int,int);
  115833. int (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
  115834. int (*bind_null)(sqlite3_stmt*,int);
  115835. int (*bind_parameter_count)(sqlite3_stmt*);
  115836. int (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
  115837. const char * (*bind_parameter_name)(sqlite3_stmt*,int);
  115838. int (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
  115839. int (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
  115840. int (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
  115841. int (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
  115842. int (*busy_timeout)(sqlite3*,int ms);
  115843. int (*changes)(sqlite3*);
  115844. int (*close)(sqlite3*);
  115845. int (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,
  115846. int eTextRep,const char*));
  115847. int (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,
  115848. int eTextRep,const void*));
  115849. const void * (*column_blob)(sqlite3_stmt*,int iCol);
  115850. int (*column_bytes)(sqlite3_stmt*,int iCol);
  115851. int (*column_bytes16)(sqlite3_stmt*,int iCol);
  115852. int (*column_count)(sqlite3_stmt*pStmt);
  115853. const char * (*column_database_name)(sqlite3_stmt*,int);
  115854. const void * (*column_database_name16)(sqlite3_stmt*,int);
  115855. const char * (*column_decltype)(sqlite3_stmt*,int i);
  115856. const void * (*column_decltype16)(sqlite3_stmt*,int);
  115857. double (*column_double)(sqlite3_stmt*,int iCol);
  115858. int (*column_int)(sqlite3_stmt*,int iCol);
  115859. sqlite_int64 (*column_int64)(sqlite3_stmt*,int iCol);
  115860. const char * (*column_name)(sqlite3_stmt*,int);
  115861. const void * (*column_name16)(sqlite3_stmt*,int);
  115862. const char * (*column_origin_name)(sqlite3_stmt*,int);
  115863. const void * (*column_origin_name16)(sqlite3_stmt*,int);
  115864. const char * (*column_table_name)(sqlite3_stmt*,int);
  115865. const void * (*column_table_name16)(sqlite3_stmt*,int);
  115866. const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
  115867. const void * (*column_text16)(sqlite3_stmt*,int iCol);
  115868. int (*column_type)(sqlite3_stmt*,int iCol);
  115869. sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
  115870. void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
  115871. int (*complete)(const char*sql);
  115872. int (*complete16)(const void*sql);
  115873. int (*create_collation)(sqlite3*,const char*,int,void*,
  115874. int(*)(void*,int,const void*,int,const void*));
  115875. int (*create_collation16)(sqlite3*,const void*,int,void*,
  115876. int(*)(void*,int,const void*,int,const void*));
  115877. int (*create_function)(sqlite3*,const char*,int,int,void*,
  115878. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  115879. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  115880. void (*xFinal)(sqlite3_context*));
  115881. int (*create_function16)(sqlite3*,const void*,int,int,void*,
  115882. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  115883. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  115884. void (*xFinal)(sqlite3_context*));
  115885. int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
  115886. int (*data_count)(sqlite3_stmt*pStmt);
  115887. sqlite3 * (*db_handle)(sqlite3_stmt*);
  115888. int (*declare_vtab)(sqlite3*,const char*);
  115889. int (*enable_shared_cache)(int);
  115890. int (*errcode)(sqlite3*db);
  115891. const char * (*errmsg)(sqlite3*);
  115892. const void * (*errmsg16)(sqlite3*);
  115893. int (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
  115894. int (*expired)(sqlite3_stmt*);
  115895. int (*finalize)(sqlite3_stmt*pStmt);
  115896. void (*free)(void*);
  115897. void (*free_table)(char**result);
  115898. int (*get_autocommit)(sqlite3*);
  115899. void * (*get_auxdata)(sqlite3_context*,int);
  115900. int (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
  115901. int (*global_recover)(void);
  115902. void (*interruptx)(sqlite3*);
  115903. sqlite_int64 (*last_insert_rowid)(sqlite3*);
  115904. const char * (*libversion)(void);
  115905. int (*libversion_number)(void);
  115906. void *(*malloc)(int);
  115907. char * (*mprintf)(const char*,...);
  115908. int (*open)(const char*,sqlite3**);
  115909. int (*open16)(const void*,sqlite3**);
  115910. int (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
  115911. int (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
  115912. void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
  115913. void (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
  115914. void *(*realloc)(void*,int);
  115915. int (*reset)(sqlite3_stmt*pStmt);
  115916. void (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
  115917. void (*result_double)(sqlite3_context*,double);
  115918. void (*result_error)(sqlite3_context*,const char*,int);
  115919. void (*result_error16)(sqlite3_context*,const void*,int);
  115920. void (*result_int)(sqlite3_context*,int);
  115921. void (*result_int64)(sqlite3_context*,sqlite_int64);
  115922. void (*result_null)(sqlite3_context*);
  115923. void (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
  115924. void (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
  115925. void (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
  115926. void (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
  115927. void (*result_value)(sqlite3_context*,sqlite3_value*);
  115928. void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
  115929. int (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,
  115930. const char*,const char*),void*);
  115931. void (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
  115932. char * (*xsnprintf)(int,char*,const char*,...);
  115933. int (*step)(sqlite3_stmt*);
  115934. int (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,
  115935. char const**,char const**,int*,int*,int*);
  115936. void (*thread_cleanup)(void);
  115937. int (*total_changes)(sqlite3*);
  115938. void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
  115939. int (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
  115940. void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,
  115941. sqlite_int64),void*);
  115942. void * (*user_data)(sqlite3_context*);
  115943. const void * (*value_blob)(sqlite3_value*);
  115944. int (*value_bytes)(sqlite3_value*);
  115945. int (*value_bytes16)(sqlite3_value*);
  115946. double (*value_double)(sqlite3_value*);
  115947. int (*value_int)(sqlite3_value*);
  115948. sqlite_int64 (*value_int64)(sqlite3_value*);
  115949. int (*value_numeric_type)(sqlite3_value*);
  115950. const unsigned char * (*value_text)(sqlite3_value*);
  115951. const void * (*value_text16)(sqlite3_value*);
  115952. const void * (*value_text16be)(sqlite3_value*);
  115953. const void * (*value_text16le)(sqlite3_value*);
  115954. int (*value_type)(sqlite3_value*);
  115955. char *(*vmprintf)(const char*,va_list);
  115956. /* Added ??? */
  115957. int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
  115958. /* Added by 3.3.13 */
  115959. int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
  115960. int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
  115961. int (*clear_bindings)(sqlite3_stmt*);
  115962. /* Added by 3.4.1 */
  115963. int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,
  115964. void (*xDestroy)(void *));
  115965. /* Added by 3.5.0 */
  115966. int (*bind_zeroblob)(sqlite3_stmt*,int,int);
  115967. int (*blob_bytes)(sqlite3_blob*);
  115968. int (*blob_close)(sqlite3_blob*);
  115969. int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,
  115970. int,sqlite3_blob**);
  115971. int (*blob_read)(sqlite3_blob*,void*,int,int);
  115972. int (*blob_write)(sqlite3_blob*,const void*,int,int);
  115973. int (*create_collation_v2)(sqlite3*,const char*,int,void*,
  115974. int(*)(void*,int,const void*,int,const void*),
  115975. void(*)(void*));
  115976. int (*file_control)(sqlite3*,const char*,int,void*);
  115977. sqlite3_int64 (*memory_highwater)(int);
  115978. sqlite3_int64 (*memory_used)(void);
  115979. sqlite3_mutex *(*mutex_alloc)(int);
  115980. void (*mutex_enter)(sqlite3_mutex*);
  115981. void (*mutex_free)(sqlite3_mutex*);
  115982. void (*mutex_leave)(sqlite3_mutex*);
  115983. int (*mutex_try)(sqlite3_mutex*);
  115984. int (*open_v2)(const char*,sqlite3**,int,const char*);
  115985. int (*release_memory)(int);
  115986. void (*result_error_nomem)(sqlite3_context*);
  115987. void (*result_error_toobig)(sqlite3_context*);
  115988. int (*sleep)(int);
  115989. void (*soft_heap_limit)(int);
  115990. sqlite3_vfs *(*vfs_find)(const char*);
  115991. int (*vfs_register)(sqlite3_vfs*,int);
  115992. int (*vfs_unregister)(sqlite3_vfs*);
  115993. int (*xthreadsafe)(void);
  115994. void (*result_zeroblob)(sqlite3_context*,int);
  115995. void (*result_error_code)(sqlite3_context*,int);
  115996. int (*test_control)(int, ...);
  115997. void (*randomness)(int,void*);
  115998. sqlite3 *(*context_db_handle)(sqlite3_context*);
  115999. int (*extended_result_codes)(sqlite3*,int);
  116000. int (*limit)(sqlite3*,int,int);
  116001. sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
  116002. const char *(*sql)(sqlite3_stmt*);
  116003. int (*status)(int,int*,int*,int);
  116004. int (*backup_finish)(sqlite3_backup*);
  116005. sqlite3_backup *(*backup_init)(sqlite3*,const char*,sqlite3*,const char*);
  116006. int (*backup_pagecount)(sqlite3_backup*);
  116007. int (*backup_remaining)(sqlite3_backup*);
  116008. int (*backup_step)(sqlite3_backup*,int);
  116009. const char *(*compileoption_get)(int);
  116010. int (*compileoption_used)(const char*);
  116011. int (*create_function_v2)(sqlite3*,const char*,int,int,void*,
  116012. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  116013. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  116014. void (*xFinal)(sqlite3_context*),
  116015. void(*xDestroy)(void*));
  116016. int (*db_config)(sqlite3*,int,...);
  116017. sqlite3_mutex *(*db_mutex)(sqlite3*);
  116018. int (*db_status)(sqlite3*,int,int*,int*,int);
  116019. int (*extended_errcode)(sqlite3*);
  116020. void (*log)(int,const char*,...);
  116021. sqlite3_int64 (*soft_heap_limit64)(sqlite3_int64);
  116022. const char *(*sourceid)(void);
  116023. int (*stmt_status)(sqlite3_stmt*,int,int);
  116024. int (*strnicmp)(const char*,const char*,int);
  116025. int (*unlock_notify)(sqlite3*,void(*)(void**,int),void*);
  116026. int (*wal_autocheckpoint)(sqlite3*,int);
  116027. int (*wal_checkpoint)(sqlite3*,const char*);
  116028. void *(*wal_hook)(sqlite3*,int(*)(void*,sqlite3*,const char*,int),void*);
  116029. int (*blob_reopen)(sqlite3_blob*,sqlite3_int64);
  116030. int (*vtab_config)(sqlite3*,int op,...);
  116031. int (*vtab_on_conflict)(sqlite3*);
  116032. /* Version 3.7.16 and later */
  116033. int (*close_v2)(sqlite3*);
  116034. const char *(*db_filename)(sqlite3*,const char*);
  116035. int (*db_readonly)(sqlite3*,const char*);
  116036. int (*db_release_memory)(sqlite3*);
  116037. const char *(*errstr)(int);
  116038. int (*stmt_busy)(sqlite3_stmt*);
  116039. int (*stmt_readonly)(sqlite3_stmt*);
  116040. int (*stricmp)(const char*,const char*);
  116041. int (*uri_boolean)(const char*,const char*,int);
  116042. sqlite3_int64 (*uri_int64)(const char*,const char*,sqlite3_int64);
  116043. const char *(*uri_parameter)(const char*,const char*);
  116044. char *(*xvsnprintf)(int,char*,const char*,va_list);
  116045. int (*wal_checkpoint_v2)(sqlite3*,const char*,int,int*,int*);
  116046. /* Version 3.8.7 and later */
  116047. int (*auto_extension)(void(*)(void));
  116048. int (*bind_blob64)(sqlite3_stmt*,int,const void*,sqlite3_uint64,
  116049. void(*)(void*));
  116050. int (*bind_text64)(sqlite3_stmt*,int,const char*,sqlite3_uint64,
  116051. void(*)(void*),unsigned char);
  116052. int (*cancel_auto_extension)(void(*)(void));
  116053. int (*load_extension)(sqlite3*,const char*,const char*,char**);
  116054. void *(*malloc64)(sqlite3_uint64);
  116055. sqlite3_uint64 (*msize)(void*);
  116056. void *(*realloc64)(void*,sqlite3_uint64);
  116057. void (*reset_auto_extension)(void);
  116058. void (*result_blob64)(sqlite3_context*,const void*,sqlite3_uint64,
  116059. void(*)(void*));
  116060. void (*result_text64)(sqlite3_context*,const char*,sqlite3_uint64,
  116061. void(*)(void*), unsigned char);
  116062. int (*strglob)(const char*,const char*);
  116063. /* Version 3.8.11 and later */
  116064. sqlite3_value *(*value_dup)(const sqlite3_value*);
  116065. void (*value_free)(sqlite3_value*);
  116066. int (*result_zeroblob64)(sqlite3_context*,sqlite3_uint64);
  116067. int (*bind_zeroblob64)(sqlite3_stmt*, int, sqlite3_uint64);
  116068. /* Version 3.9.0 and later */
  116069. unsigned int (*value_subtype)(sqlite3_value*);
  116070. void (*result_subtype)(sqlite3_context*,unsigned int);
  116071. /* Version 3.10.0 and later */
  116072. int (*status64)(int,sqlite3_int64*,sqlite3_int64*,int);
  116073. int (*strlike)(const char*,const char*,unsigned int);
  116074. int (*db_cacheflush)(sqlite3*);
  116075. /* Version 3.12.0 and later */
  116076. int (*system_errno)(sqlite3*);
  116077. /* Version 3.14.0 and later */
  116078. int (*trace_v2)(sqlite3*,unsigned,int(*)(unsigned,void*,void*,void*),void*);
  116079. char *(*expanded_sql)(sqlite3_stmt*);
  116080. /* Version 3.18.0 and later */
  116081. void (*set_last_insert_rowid)(sqlite3*,sqlite3_int64);
  116082. /* Version 3.20.0 and later */
  116083. int (*prepare_v3)(sqlite3*,const char*,int,unsigned int,
  116084. sqlite3_stmt**,const char**);
  116085. int (*prepare16_v3)(sqlite3*,const void*,int,unsigned int,
  116086. sqlite3_stmt**,const void**);
  116087. int (*bind_pointer)(sqlite3_stmt*,int,void*,const char*,void(*)(void*));
  116088. void (*result_pointer)(sqlite3_context*,void*,const char*,void(*)(void*));
  116089. void *(*value_pointer)(sqlite3_value*,const char*);
  116090. int (*vtab_nochange)(sqlite3_context*);
  116091. int (*value_nochange)(sqlite3_value*);
  116092. const char *(*vtab_collation)(sqlite3_index_info*,int);
  116093. /* Version 3.24.0 and later */
  116094. int (*keyword_count)(void);
  116095. int (*keyword_name)(int,const char**,int*);
  116096. int (*keyword_check)(const char*,int);
  116097. sqlite3_str *(*str_new)(sqlite3*);
  116098. char *(*str_finish)(sqlite3_str*);
  116099. void (*str_appendf)(sqlite3_str*, const char *zFormat, ...);
  116100. void (*str_vappendf)(sqlite3_str*, const char *zFormat, va_list);
  116101. void (*str_append)(sqlite3_str*, const char *zIn, int N);
  116102. void (*str_appendall)(sqlite3_str*, const char *zIn);
  116103. void (*str_appendchar)(sqlite3_str*, int N, char C);
  116104. void (*str_reset)(sqlite3_str*);
  116105. int (*str_errcode)(sqlite3_str*);
  116106. int (*str_length)(sqlite3_str*);
  116107. char *(*str_value)(sqlite3_str*);
  116108. /* Version 3.25.0 and later */
  116109. int (*create_window_function)(sqlite3*,const char*,int,int,void*,
  116110. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  116111. void (*xFinal)(sqlite3_context*),
  116112. void (*xValue)(sqlite3_context*),
  116113. void (*xInv)(sqlite3_context*,int,sqlite3_value**),
  116114. void(*xDestroy)(void*));
  116115. /* Version 3.26.0 and later */
  116116. const char *(*normalized_sql)(sqlite3_stmt*);
  116117. /* Version 3.28.0 and later */
  116118. int (*stmt_isexplain)(sqlite3_stmt*);
  116119. int (*value_frombind)(sqlite3_value*);
  116120. /* Version 3.30.0 and later */
  116121. int (*drop_modules)(sqlite3*,const char**);
  116122. /* Version 3.31.0 and later */
  116123. sqlite3_int64 (*hard_heap_limit64)(sqlite3_int64);
  116124. const char *(*uri_key)(const char*,int);
  116125. const char *(*filename_database)(const char*);
  116126. const char *(*filename_journal)(const char*);
  116127. const char *(*filename_wal)(const char*);
  116128. /* Version 3.32.0 and later */
  116129. char *(*create_filename)(const char*,const char*,const char*,
  116130. int,const char**);
  116131. void (*free_filename)(char*);
  116132. sqlite3_file *(*database_file_object)(const char*);
  116133. };
  116134. /*
  116135. ** This is the function signature used for all extension entry points. It
  116136. ** is also defined in the file "loadext.c".
  116137. */
  116138. typedef int (*sqlite3_loadext_entry)(
  116139. sqlite3 *db, /* Handle to the database. */
  116140. char **pzErrMsg, /* Used to set error string on failure. */
  116141. const sqlite3_api_routines *pThunk /* Extension API function pointers. */
  116142. );
  116143. /*
  116144. ** The following macros redefine the API routines so that they are
  116145. ** redirected through the global sqlite3_api structure.
  116146. **
  116147. ** This header file is also used by the loadext.c source file
  116148. ** (part of the main SQLite library - not an extension) so that
  116149. ** it can get access to the sqlite3_api_routines structure
  116150. ** definition. But the main library does not want to redefine
  116151. ** the API. So the redefinition macros are only valid if the
  116152. ** SQLITE_CORE macros is undefined.
  116153. */
  116154. #if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
  116155. #define sqlite3_aggregate_context sqlite3_api->aggregate_context
  116156. #ifndef SQLITE_OMIT_DEPRECATED
  116157. #define sqlite3_aggregate_count sqlite3_api->aggregate_count
  116158. #endif
  116159. #define sqlite3_bind_blob sqlite3_api->bind_blob
  116160. #define sqlite3_bind_double sqlite3_api->bind_double
  116161. #define sqlite3_bind_int sqlite3_api->bind_int
  116162. #define sqlite3_bind_int64 sqlite3_api->bind_int64
  116163. #define sqlite3_bind_null sqlite3_api->bind_null
  116164. #define sqlite3_bind_parameter_count sqlite3_api->bind_parameter_count
  116165. #define sqlite3_bind_parameter_index sqlite3_api->bind_parameter_index
  116166. #define sqlite3_bind_parameter_name sqlite3_api->bind_parameter_name
  116167. #define sqlite3_bind_text sqlite3_api->bind_text
  116168. #define sqlite3_bind_text16 sqlite3_api->bind_text16
  116169. #define sqlite3_bind_value sqlite3_api->bind_value
  116170. #define sqlite3_busy_handler sqlite3_api->busy_handler
  116171. #define sqlite3_busy_timeout sqlite3_api->busy_timeout
  116172. #define sqlite3_changes sqlite3_api->changes
  116173. #define sqlite3_close sqlite3_api->close
  116174. #define sqlite3_collation_needed sqlite3_api->collation_needed
  116175. #define sqlite3_collation_needed16 sqlite3_api->collation_needed16
  116176. #define sqlite3_column_blob sqlite3_api->column_blob
  116177. #define sqlite3_column_bytes sqlite3_api->column_bytes
  116178. #define sqlite3_column_bytes16 sqlite3_api->column_bytes16
  116179. #define sqlite3_column_count sqlite3_api->column_count
  116180. #define sqlite3_column_database_name sqlite3_api->column_database_name
  116181. #define sqlite3_column_database_name16 sqlite3_api->column_database_name16
  116182. #define sqlite3_column_decltype sqlite3_api->column_decltype
  116183. #define sqlite3_column_decltype16 sqlite3_api->column_decltype16
  116184. #define sqlite3_column_double sqlite3_api->column_double
  116185. #define sqlite3_column_int sqlite3_api->column_int
  116186. #define sqlite3_column_int64 sqlite3_api->column_int64
  116187. #define sqlite3_column_name sqlite3_api->column_name
  116188. #define sqlite3_column_name16 sqlite3_api->column_name16
  116189. #define sqlite3_column_origin_name sqlite3_api->column_origin_name
  116190. #define sqlite3_column_origin_name16 sqlite3_api->column_origin_name16
  116191. #define sqlite3_column_table_name sqlite3_api->column_table_name
  116192. #define sqlite3_column_table_name16 sqlite3_api->column_table_name16
  116193. #define sqlite3_column_text sqlite3_api->column_text
  116194. #define sqlite3_column_text16 sqlite3_api->column_text16
  116195. #define sqlite3_column_type sqlite3_api->column_type
  116196. #define sqlite3_column_value sqlite3_api->column_value
  116197. #define sqlite3_commit_hook sqlite3_api->commit_hook
  116198. #define sqlite3_complete sqlite3_api->complete
  116199. #define sqlite3_complete16 sqlite3_api->complete16
  116200. #define sqlite3_create_collation sqlite3_api->create_collation
  116201. #define sqlite3_create_collation16 sqlite3_api->create_collation16
  116202. #define sqlite3_create_function sqlite3_api->create_function
  116203. #define sqlite3_create_function16 sqlite3_api->create_function16
  116204. #define sqlite3_create_module sqlite3_api->create_module
  116205. #define sqlite3_create_module_v2 sqlite3_api->create_module_v2
  116206. #define sqlite3_data_count sqlite3_api->data_count
  116207. #define sqlite3_db_handle sqlite3_api->db_handle
  116208. #define sqlite3_declare_vtab sqlite3_api->declare_vtab
  116209. #define sqlite3_enable_shared_cache sqlite3_api->enable_shared_cache
  116210. #define sqlite3_errcode sqlite3_api->errcode
  116211. #define sqlite3_errmsg sqlite3_api->errmsg
  116212. #define sqlite3_errmsg16 sqlite3_api->errmsg16
  116213. #define sqlite3_exec sqlite3_api->exec
  116214. #ifndef SQLITE_OMIT_DEPRECATED
  116215. #define sqlite3_expired sqlite3_api->expired
  116216. #endif
  116217. #define sqlite3_finalize sqlite3_api->finalize
  116218. #define sqlite3_free sqlite3_api->free
  116219. #define sqlite3_free_table sqlite3_api->free_table
  116220. #define sqlite3_get_autocommit sqlite3_api->get_autocommit
  116221. #define sqlite3_get_auxdata sqlite3_api->get_auxdata
  116222. #define sqlite3_get_table sqlite3_api->get_table
  116223. #ifndef SQLITE_OMIT_DEPRECATED
  116224. #define sqlite3_global_recover sqlite3_api->global_recover
  116225. #endif
  116226. #define sqlite3_interrupt sqlite3_api->interruptx
  116227. #define sqlite3_last_insert_rowid sqlite3_api->last_insert_rowid
  116228. #define sqlite3_libversion sqlite3_api->libversion
  116229. #define sqlite3_libversion_number sqlite3_api->libversion_number
  116230. #define sqlite3_malloc sqlite3_api->malloc
  116231. #define sqlite3_mprintf sqlite3_api->mprintf
  116232. #define sqlite3_open sqlite3_api->open
  116233. #define sqlite3_open16 sqlite3_api->open16
  116234. #define sqlite3_prepare sqlite3_api->prepare
  116235. #define sqlite3_prepare16 sqlite3_api->prepare16
  116236. #define sqlite3_prepare_v2 sqlite3_api->prepare_v2
  116237. #define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2
  116238. #define sqlite3_profile sqlite3_api->profile
  116239. #define sqlite3_progress_handler sqlite3_api->progress_handler
  116240. #define sqlite3_realloc sqlite3_api->realloc
  116241. #define sqlite3_reset sqlite3_api->reset
  116242. #define sqlite3_result_blob sqlite3_api->result_blob
  116243. #define sqlite3_result_double sqlite3_api->result_double
  116244. #define sqlite3_result_error sqlite3_api->result_error
  116245. #define sqlite3_result_error16 sqlite3_api->result_error16
  116246. #define sqlite3_result_int sqlite3_api->result_int
  116247. #define sqlite3_result_int64 sqlite3_api->result_int64
  116248. #define sqlite3_result_null sqlite3_api->result_null
  116249. #define sqlite3_result_text sqlite3_api->result_text
  116250. #define sqlite3_result_text16 sqlite3_api->result_text16
  116251. #define sqlite3_result_text16be sqlite3_api->result_text16be
  116252. #define sqlite3_result_text16le sqlite3_api->result_text16le
  116253. #define sqlite3_result_value sqlite3_api->result_value
  116254. #define sqlite3_rollback_hook sqlite3_api->rollback_hook
  116255. #define sqlite3_set_authorizer sqlite3_api->set_authorizer
  116256. #define sqlite3_set_auxdata sqlite3_api->set_auxdata
  116257. #define sqlite3_snprintf sqlite3_api->xsnprintf
  116258. #define sqlite3_step sqlite3_api->step
  116259. #define sqlite3_table_column_metadata sqlite3_api->table_column_metadata
  116260. #define sqlite3_thread_cleanup sqlite3_api->thread_cleanup
  116261. #define sqlite3_total_changes sqlite3_api->total_changes
  116262. #define sqlite3_trace sqlite3_api->trace
  116263. #ifndef SQLITE_OMIT_DEPRECATED
  116264. #define sqlite3_transfer_bindings sqlite3_api->transfer_bindings
  116265. #endif
  116266. #define sqlite3_update_hook sqlite3_api->update_hook
  116267. #define sqlite3_user_data sqlite3_api->user_data
  116268. #define sqlite3_value_blob sqlite3_api->value_blob
  116269. #define sqlite3_value_bytes sqlite3_api->value_bytes
  116270. #define sqlite3_value_bytes16 sqlite3_api->value_bytes16
  116271. #define sqlite3_value_double sqlite3_api->value_double
  116272. #define sqlite3_value_int sqlite3_api->value_int
  116273. #define sqlite3_value_int64 sqlite3_api->value_int64
  116274. #define sqlite3_value_numeric_type sqlite3_api->value_numeric_type
  116275. #define sqlite3_value_text sqlite3_api->value_text
  116276. #define sqlite3_value_text16 sqlite3_api->value_text16
  116277. #define sqlite3_value_text16be sqlite3_api->value_text16be
  116278. #define sqlite3_value_text16le sqlite3_api->value_text16le
  116279. #define sqlite3_value_type sqlite3_api->value_type
  116280. #define sqlite3_vmprintf sqlite3_api->vmprintf
  116281. #define sqlite3_vsnprintf sqlite3_api->xvsnprintf
  116282. #define sqlite3_overload_function sqlite3_api->overload_function
  116283. #define sqlite3_prepare_v2 sqlite3_api->prepare_v2
  116284. #define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2
  116285. #define sqlite3_clear_bindings sqlite3_api->clear_bindings
  116286. #define sqlite3_bind_zeroblob sqlite3_api->bind_zeroblob
  116287. #define sqlite3_blob_bytes sqlite3_api->blob_bytes
  116288. #define sqlite3_blob_close sqlite3_api->blob_close
  116289. #define sqlite3_blob_open sqlite3_api->blob_open
  116290. #define sqlite3_blob_read sqlite3_api->blob_read
  116291. #define sqlite3_blob_write sqlite3_api->blob_write
  116292. #define sqlite3_create_collation_v2 sqlite3_api->create_collation_v2
  116293. #define sqlite3_file_control sqlite3_api->file_control
  116294. #define sqlite3_memory_highwater sqlite3_api->memory_highwater
  116295. #define sqlite3_memory_used sqlite3_api->memory_used
  116296. #define sqlite3_mutex_alloc sqlite3_api->mutex_alloc
  116297. #define sqlite3_mutex_enter sqlite3_api->mutex_enter
  116298. #define sqlite3_mutex_free sqlite3_api->mutex_free
  116299. #define sqlite3_mutex_leave sqlite3_api->mutex_leave
  116300. #define sqlite3_mutex_try sqlite3_api->mutex_try
  116301. #define sqlite3_open_v2 sqlite3_api->open_v2
  116302. #define sqlite3_release_memory sqlite3_api->release_memory
  116303. #define sqlite3_result_error_nomem sqlite3_api->result_error_nomem
  116304. #define sqlite3_result_error_toobig sqlite3_api->result_error_toobig
  116305. #define sqlite3_sleep sqlite3_api->sleep
  116306. #define sqlite3_soft_heap_limit sqlite3_api->soft_heap_limit
  116307. #define sqlite3_vfs_find sqlite3_api->vfs_find
  116308. #define sqlite3_vfs_register sqlite3_api->vfs_register
  116309. #define sqlite3_vfs_unregister sqlite3_api->vfs_unregister
  116310. #define sqlite3_threadsafe sqlite3_api->xthreadsafe
  116311. #define sqlite3_result_zeroblob sqlite3_api->result_zeroblob
  116312. #define sqlite3_result_error_code sqlite3_api->result_error_code
  116313. #define sqlite3_test_control sqlite3_api->test_control
  116314. #define sqlite3_randomness sqlite3_api->randomness
  116315. #define sqlite3_context_db_handle sqlite3_api->context_db_handle
  116316. #define sqlite3_extended_result_codes sqlite3_api->extended_result_codes
  116317. #define sqlite3_limit sqlite3_api->limit
  116318. #define sqlite3_next_stmt sqlite3_api->next_stmt
  116319. #define sqlite3_sql sqlite3_api->sql
  116320. #define sqlite3_status sqlite3_api->status
  116321. #define sqlite3_backup_finish sqlite3_api->backup_finish
  116322. #define sqlite3_backup_init sqlite3_api->backup_init
  116323. #define sqlite3_backup_pagecount sqlite3_api->backup_pagecount
  116324. #define sqlite3_backup_remaining sqlite3_api->backup_remaining
  116325. #define sqlite3_backup_step sqlite3_api->backup_step
  116326. #define sqlite3_compileoption_get sqlite3_api->compileoption_get
  116327. #define sqlite3_compileoption_used sqlite3_api->compileoption_used
  116328. #define sqlite3_create_function_v2 sqlite3_api->create_function_v2
  116329. #define sqlite3_db_config sqlite3_api->db_config
  116330. #define sqlite3_db_mutex sqlite3_api->db_mutex
  116331. #define sqlite3_db_status sqlite3_api->db_status
  116332. #define sqlite3_extended_errcode sqlite3_api->extended_errcode
  116333. #define sqlite3_log sqlite3_api->log
  116334. #define sqlite3_soft_heap_limit64 sqlite3_api->soft_heap_limit64
  116335. #define sqlite3_sourceid sqlite3_api->sourceid
  116336. #define sqlite3_stmt_status sqlite3_api->stmt_status
  116337. #define sqlite3_strnicmp sqlite3_api->strnicmp
  116338. #define sqlite3_unlock_notify sqlite3_api->unlock_notify
  116339. #define sqlite3_wal_autocheckpoint sqlite3_api->wal_autocheckpoint
  116340. #define sqlite3_wal_checkpoint sqlite3_api->wal_checkpoint
  116341. #define sqlite3_wal_hook sqlite3_api->wal_hook
  116342. #define sqlite3_blob_reopen sqlite3_api->blob_reopen
  116343. #define sqlite3_vtab_config sqlite3_api->vtab_config
  116344. #define sqlite3_vtab_on_conflict sqlite3_api->vtab_on_conflict
  116345. /* Version 3.7.16 and later */
  116346. #define sqlite3_close_v2 sqlite3_api->close_v2
  116347. #define sqlite3_db_filename sqlite3_api->db_filename
  116348. #define sqlite3_db_readonly sqlite3_api->db_readonly
  116349. #define sqlite3_db_release_memory sqlite3_api->db_release_memory
  116350. #define sqlite3_errstr sqlite3_api->errstr
  116351. #define sqlite3_stmt_busy sqlite3_api->stmt_busy
  116352. #define sqlite3_stmt_readonly sqlite3_api->stmt_readonly
  116353. #define sqlite3_stricmp sqlite3_api->stricmp
  116354. #define sqlite3_uri_boolean sqlite3_api->uri_boolean
  116355. #define sqlite3_uri_int64 sqlite3_api->uri_int64
  116356. #define sqlite3_uri_parameter sqlite3_api->uri_parameter
  116357. #define sqlite3_uri_vsnprintf sqlite3_api->xvsnprintf
  116358. #define sqlite3_wal_checkpoint_v2 sqlite3_api->wal_checkpoint_v2
  116359. /* Version 3.8.7 and later */
  116360. #define sqlite3_auto_extension sqlite3_api->auto_extension
  116361. #define sqlite3_bind_blob64 sqlite3_api->bind_blob64
  116362. #define sqlite3_bind_text64 sqlite3_api->bind_text64
  116363. #define sqlite3_cancel_auto_extension sqlite3_api->cancel_auto_extension
  116364. #define sqlite3_load_extension sqlite3_api->load_extension
  116365. #define sqlite3_malloc64 sqlite3_api->malloc64
  116366. #define sqlite3_msize sqlite3_api->msize
  116367. #define sqlite3_realloc64 sqlite3_api->realloc64
  116368. #define sqlite3_reset_auto_extension sqlite3_api->reset_auto_extension
  116369. #define sqlite3_result_blob64 sqlite3_api->result_blob64
  116370. #define sqlite3_result_text64 sqlite3_api->result_text64
  116371. #define sqlite3_strglob sqlite3_api->strglob
  116372. /* Version 3.8.11 and later */
  116373. #define sqlite3_value_dup sqlite3_api->value_dup
  116374. #define sqlite3_value_free sqlite3_api->value_free
  116375. #define sqlite3_result_zeroblob64 sqlite3_api->result_zeroblob64
  116376. #define sqlite3_bind_zeroblob64 sqlite3_api->bind_zeroblob64
  116377. /* Version 3.9.0 and later */
  116378. #define sqlite3_value_subtype sqlite3_api->value_subtype
  116379. #define sqlite3_result_subtype sqlite3_api->result_subtype
  116380. /* Version 3.10.0 and later */
  116381. #define sqlite3_status64 sqlite3_api->status64
  116382. #define sqlite3_strlike sqlite3_api->strlike
  116383. #define sqlite3_db_cacheflush sqlite3_api->db_cacheflush
  116384. /* Version 3.12.0 and later */
  116385. #define sqlite3_system_errno sqlite3_api->system_errno
  116386. /* Version 3.14.0 and later */
  116387. #define sqlite3_trace_v2 sqlite3_api->trace_v2
  116388. #define sqlite3_expanded_sql sqlite3_api->expanded_sql
  116389. /* Version 3.18.0 and later */
  116390. #define sqlite3_set_last_insert_rowid sqlite3_api->set_last_insert_rowid
  116391. /* Version 3.20.0 and later */
  116392. #define sqlite3_prepare_v3 sqlite3_api->prepare_v3
  116393. #define sqlite3_prepare16_v3 sqlite3_api->prepare16_v3
  116394. #define sqlite3_bind_pointer sqlite3_api->bind_pointer
  116395. #define sqlite3_result_pointer sqlite3_api->result_pointer
  116396. #define sqlite3_value_pointer sqlite3_api->value_pointer
  116397. /* Version 3.22.0 and later */
  116398. #define sqlite3_vtab_nochange sqlite3_api->vtab_nochange
  116399. #define sqlite3_value_nochange sqlite3_api->value_nochange
  116400. #define sqlite3_vtab_collation sqlite3_api->vtab_collation
  116401. /* Version 3.24.0 and later */
  116402. #define sqlite3_keyword_count sqlite3_api->keyword_count
  116403. #define sqlite3_keyword_name sqlite3_api->keyword_name
  116404. #define sqlite3_keyword_check sqlite3_api->keyword_check
  116405. #define sqlite3_str_new sqlite3_api->str_new
  116406. #define sqlite3_str_finish sqlite3_api->str_finish
  116407. #define sqlite3_str_appendf sqlite3_api->str_appendf
  116408. #define sqlite3_str_vappendf sqlite3_api->str_vappendf
  116409. #define sqlite3_str_append sqlite3_api->str_append
  116410. #define sqlite3_str_appendall sqlite3_api->str_appendall
  116411. #define sqlite3_str_appendchar sqlite3_api->str_appendchar
  116412. #define sqlite3_str_reset sqlite3_api->str_reset
  116413. #define sqlite3_str_errcode sqlite3_api->str_errcode
  116414. #define sqlite3_str_length sqlite3_api->str_length
  116415. #define sqlite3_str_value sqlite3_api->str_value
  116416. /* Version 3.25.0 and later */
  116417. #define sqlite3_create_window_function sqlite3_api->create_window_function
  116418. /* Version 3.26.0 and later */
  116419. #define sqlite3_normalized_sql sqlite3_api->normalized_sql
  116420. /* Version 3.28.0 and later */
  116421. #define sqlite3_stmt_isexplain sqlite3_api->stmt_isexplain
  116422. #define sqlite3_value_frombind sqlite3_api->value_frombind
  116423. /* Version 3.30.0 and later */
  116424. #define sqlite3_drop_modules sqlite3_api->drop_modules
  116425. /* Version 3.31.0 and later */
  116426. #define sqlite3_hard_heap_limit64 sqlite3_api->hard_heap_limit64
  116427. #define sqlite3_uri_key sqlite3_api->uri_key
  116428. #define sqlite3_filename_database sqlite3_api->filename_database
  116429. #define sqlite3_filename_journal sqlite3_api->filename_journal
  116430. #define sqlite3_filename_wal sqlite3_api->filename_wal
  116431. /* Version 3.32.0 and later */
  116432. #define sqlite3_create_filename sqlite3_api->create_filename
  116433. #define sqlite3_free_filename sqlite3_api->free_filename
  116434. #define sqlite3_database_file_object sqlite3_api->database_file_object
  116435. #endif /* !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION) */
  116436. #if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
  116437. /* This case when the file really is being compiled as a loadable
  116438. ** extension */
  116439. # define SQLITE_EXTENSION_INIT1 const sqlite3_api_routines *sqlite3_api=0;
  116440. # define SQLITE_EXTENSION_INIT2(v) sqlite3_api=v;
  116441. # define SQLITE_EXTENSION_INIT3 \
  116442. extern const sqlite3_api_routines *sqlite3_api;
  116443. #else
  116444. /* This case when the file is being statically linked into the
  116445. ** application */
  116446. # define SQLITE_EXTENSION_INIT1 /*no-op*/
  116447. # define SQLITE_EXTENSION_INIT2(v) (void)v; /* unused parameter */
  116448. # define SQLITE_EXTENSION_INIT3 /*no-op*/
  116449. #endif
  116450. #endif /* SQLITE3EXT_H */
  116451. /************** End of sqlite3ext.h ******************************************/
  116452. /************** Continuing where we left off in loadext.c ********************/
  116453. /* #include "sqliteInt.h" */
  116454. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  116455. /*
  116456. ** Some API routines are omitted when various features are
  116457. ** excluded from a build of SQLite. Substitute a NULL pointer
  116458. ** for any missing APIs.
  116459. */
  116460. #ifndef SQLITE_ENABLE_COLUMN_METADATA
  116461. # define sqlite3_column_database_name 0
  116462. # define sqlite3_column_database_name16 0
  116463. # define sqlite3_column_table_name 0
  116464. # define sqlite3_column_table_name16 0
  116465. # define sqlite3_column_origin_name 0
  116466. # define sqlite3_column_origin_name16 0
  116467. #endif
  116468. #ifdef SQLITE_OMIT_AUTHORIZATION
  116469. # define sqlite3_set_authorizer 0
  116470. #endif
  116471. #ifdef SQLITE_OMIT_UTF16
  116472. # define sqlite3_bind_text16 0
  116473. # define sqlite3_collation_needed16 0
  116474. # define sqlite3_column_decltype16 0
  116475. # define sqlite3_column_name16 0
  116476. # define sqlite3_column_text16 0
  116477. # define sqlite3_complete16 0
  116478. # define sqlite3_create_collation16 0
  116479. # define sqlite3_create_function16 0
  116480. # define sqlite3_errmsg16 0
  116481. # define sqlite3_open16 0
  116482. # define sqlite3_prepare16 0
  116483. # define sqlite3_prepare16_v2 0
  116484. # define sqlite3_prepare16_v3 0
  116485. # define sqlite3_result_error16 0
  116486. # define sqlite3_result_text16 0
  116487. # define sqlite3_result_text16be 0
  116488. # define sqlite3_result_text16le 0
  116489. # define sqlite3_value_text16 0
  116490. # define sqlite3_value_text16be 0
  116491. # define sqlite3_value_text16le 0
  116492. # define sqlite3_column_database_name16 0
  116493. # define sqlite3_column_table_name16 0
  116494. # define sqlite3_column_origin_name16 0
  116495. #endif
  116496. #ifdef SQLITE_OMIT_COMPLETE
  116497. # define sqlite3_complete 0
  116498. # define sqlite3_complete16 0
  116499. #endif
  116500. #ifdef SQLITE_OMIT_DECLTYPE
  116501. # define sqlite3_column_decltype16 0
  116502. # define sqlite3_column_decltype 0
  116503. #endif
  116504. #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
  116505. # define sqlite3_progress_handler 0
  116506. #endif
  116507. #ifdef SQLITE_OMIT_VIRTUALTABLE
  116508. # define sqlite3_create_module 0
  116509. # define sqlite3_create_module_v2 0
  116510. # define sqlite3_declare_vtab 0
  116511. # define sqlite3_vtab_config 0
  116512. # define sqlite3_vtab_on_conflict 0
  116513. # define sqlite3_vtab_collation 0
  116514. #endif
  116515. #ifdef SQLITE_OMIT_SHARED_CACHE
  116516. # define sqlite3_enable_shared_cache 0
  116517. #endif
  116518. #if defined(SQLITE_OMIT_TRACE) || defined(SQLITE_OMIT_DEPRECATED)
  116519. # define sqlite3_profile 0
  116520. # define sqlite3_trace 0
  116521. #endif
  116522. #ifdef SQLITE_OMIT_GET_TABLE
  116523. # define sqlite3_free_table 0
  116524. # define sqlite3_get_table 0
  116525. #endif
  116526. #ifdef SQLITE_OMIT_INCRBLOB
  116527. #define sqlite3_bind_zeroblob 0
  116528. #define sqlite3_blob_bytes 0
  116529. #define sqlite3_blob_close 0
  116530. #define sqlite3_blob_open 0
  116531. #define sqlite3_blob_read 0
  116532. #define sqlite3_blob_write 0
  116533. #define sqlite3_blob_reopen 0
  116534. #endif
  116535. #if defined(SQLITE_OMIT_TRACE)
  116536. # define sqlite3_trace_v2 0
  116537. #endif
  116538. /*
  116539. ** The following structure contains pointers to all SQLite API routines.
  116540. ** A pointer to this structure is passed into extensions when they are
  116541. ** loaded so that the extension can make calls back into the SQLite
  116542. ** library.
  116543. **
  116544. ** When adding new APIs, add them to the bottom of this structure
  116545. ** in order to preserve backwards compatibility.
  116546. **
  116547. ** Extensions that use newer APIs should first call the
  116548. ** sqlite3_libversion_number() to make sure that the API they
  116549. ** intend to use is supported by the library. Extensions should
  116550. ** also check to make sure that the pointer to the function is
  116551. ** not NULL before calling it.
  116552. */
  116553. static const sqlite3_api_routines sqlite3Apis = {
  116554. sqlite3_aggregate_context,
  116555. #ifndef SQLITE_OMIT_DEPRECATED
  116556. sqlite3_aggregate_count,
  116557. #else
  116558. 0,
  116559. #endif
  116560. sqlite3_bind_blob,
  116561. sqlite3_bind_double,
  116562. sqlite3_bind_int,
  116563. sqlite3_bind_int64,
  116564. sqlite3_bind_null,
  116565. sqlite3_bind_parameter_count,
  116566. sqlite3_bind_parameter_index,
  116567. sqlite3_bind_parameter_name,
  116568. sqlite3_bind_text,
  116569. sqlite3_bind_text16,
  116570. sqlite3_bind_value,
  116571. sqlite3_busy_handler,
  116572. sqlite3_busy_timeout,
  116573. sqlite3_changes,
  116574. sqlite3_close,
  116575. sqlite3_collation_needed,
  116576. sqlite3_collation_needed16,
  116577. sqlite3_column_blob,
  116578. sqlite3_column_bytes,
  116579. sqlite3_column_bytes16,
  116580. sqlite3_column_count,
  116581. sqlite3_column_database_name,
  116582. sqlite3_column_database_name16,
  116583. sqlite3_column_decltype,
  116584. sqlite3_column_decltype16,
  116585. sqlite3_column_double,
  116586. sqlite3_column_int,
  116587. sqlite3_column_int64,
  116588. sqlite3_column_name,
  116589. sqlite3_column_name16,
  116590. sqlite3_column_origin_name,
  116591. sqlite3_column_origin_name16,
  116592. sqlite3_column_table_name,
  116593. sqlite3_column_table_name16,
  116594. sqlite3_column_text,
  116595. sqlite3_column_text16,
  116596. sqlite3_column_type,
  116597. sqlite3_column_value,
  116598. sqlite3_commit_hook,
  116599. sqlite3_complete,
  116600. sqlite3_complete16,
  116601. sqlite3_create_collation,
  116602. sqlite3_create_collation16,
  116603. sqlite3_create_function,
  116604. sqlite3_create_function16,
  116605. sqlite3_create_module,
  116606. sqlite3_data_count,
  116607. sqlite3_db_handle,
  116608. sqlite3_declare_vtab,
  116609. sqlite3_enable_shared_cache,
  116610. sqlite3_errcode,
  116611. sqlite3_errmsg,
  116612. sqlite3_errmsg16,
  116613. sqlite3_exec,
  116614. #ifndef SQLITE_OMIT_DEPRECATED
  116615. sqlite3_expired,
  116616. #else
  116617. 0,
  116618. #endif
  116619. sqlite3_finalize,
  116620. sqlite3_free,
  116621. sqlite3_free_table,
  116622. sqlite3_get_autocommit,
  116623. sqlite3_get_auxdata,
  116624. sqlite3_get_table,
  116625. 0, /* Was sqlite3_global_recover(), but that function is deprecated */
  116626. sqlite3_interrupt,
  116627. sqlite3_last_insert_rowid,
  116628. sqlite3_libversion,
  116629. sqlite3_libversion_number,
  116630. sqlite3_malloc,
  116631. sqlite3_mprintf,
  116632. sqlite3_open,
  116633. sqlite3_open16,
  116634. sqlite3_prepare,
  116635. sqlite3_prepare16,
  116636. sqlite3_profile,
  116637. sqlite3_progress_handler,
  116638. sqlite3_realloc,
  116639. sqlite3_reset,
  116640. sqlite3_result_blob,
  116641. sqlite3_result_double,
  116642. sqlite3_result_error,
  116643. sqlite3_result_error16,
  116644. sqlite3_result_int,
  116645. sqlite3_result_int64,
  116646. sqlite3_result_null,
  116647. sqlite3_result_text,
  116648. sqlite3_result_text16,
  116649. sqlite3_result_text16be,
  116650. sqlite3_result_text16le,
  116651. sqlite3_result_value,
  116652. sqlite3_rollback_hook,
  116653. sqlite3_set_authorizer,
  116654. sqlite3_set_auxdata,
  116655. sqlite3_snprintf,
  116656. sqlite3_step,
  116657. sqlite3_table_column_metadata,
  116658. #ifndef SQLITE_OMIT_DEPRECATED
  116659. sqlite3_thread_cleanup,
  116660. #else
  116661. 0,
  116662. #endif
  116663. sqlite3_total_changes,
  116664. sqlite3_trace,
  116665. #ifndef SQLITE_OMIT_DEPRECATED
  116666. sqlite3_transfer_bindings,
  116667. #else
  116668. 0,
  116669. #endif
  116670. sqlite3_update_hook,
  116671. sqlite3_user_data,
  116672. sqlite3_value_blob,
  116673. sqlite3_value_bytes,
  116674. sqlite3_value_bytes16,
  116675. sqlite3_value_double,
  116676. sqlite3_value_int,
  116677. sqlite3_value_int64,
  116678. sqlite3_value_numeric_type,
  116679. sqlite3_value_text,
  116680. sqlite3_value_text16,
  116681. sqlite3_value_text16be,
  116682. sqlite3_value_text16le,
  116683. sqlite3_value_type,
  116684. sqlite3_vmprintf,
  116685. /*
  116686. ** The original API set ends here. All extensions can call any
  116687. ** of the APIs above provided that the pointer is not NULL. But
  116688. ** before calling APIs that follow, extension should check the
  116689. ** sqlite3_libversion_number() to make sure they are dealing with
  116690. ** a library that is new enough to support that API.
  116691. *************************************************************************
  116692. */
  116693. sqlite3_overload_function,
  116694. /*
  116695. ** Added after 3.3.13
  116696. */
  116697. sqlite3_prepare_v2,
  116698. sqlite3_prepare16_v2,
  116699. sqlite3_clear_bindings,
  116700. /*
  116701. ** Added for 3.4.1
  116702. */
  116703. sqlite3_create_module_v2,
  116704. /*
  116705. ** Added for 3.5.0
  116706. */
  116707. sqlite3_bind_zeroblob,
  116708. sqlite3_blob_bytes,
  116709. sqlite3_blob_close,
  116710. sqlite3_blob_open,
  116711. sqlite3_blob_read,
  116712. sqlite3_blob_write,
  116713. sqlite3_create_collation_v2,
  116714. sqlite3_file_control,
  116715. sqlite3_memory_highwater,
  116716. sqlite3_memory_used,
  116717. #ifdef SQLITE_MUTEX_OMIT
  116718. 0,
  116719. 0,
  116720. 0,
  116721. 0,
  116722. 0,
  116723. #else
  116724. sqlite3_mutex_alloc,
  116725. sqlite3_mutex_enter,
  116726. sqlite3_mutex_free,
  116727. sqlite3_mutex_leave,
  116728. sqlite3_mutex_try,
  116729. #endif
  116730. sqlite3_open_v2,
  116731. sqlite3_release_memory,
  116732. sqlite3_result_error_nomem,
  116733. sqlite3_result_error_toobig,
  116734. sqlite3_sleep,
  116735. sqlite3_soft_heap_limit,
  116736. sqlite3_vfs_find,
  116737. sqlite3_vfs_register,
  116738. sqlite3_vfs_unregister,
  116739. /*
  116740. ** Added for 3.5.8
  116741. */
  116742. sqlite3_threadsafe,
  116743. sqlite3_result_zeroblob,
  116744. sqlite3_result_error_code,
  116745. sqlite3_test_control,
  116746. sqlite3_randomness,
  116747. sqlite3_context_db_handle,
  116748. /*
  116749. ** Added for 3.6.0
  116750. */
  116751. sqlite3_extended_result_codes,
  116752. sqlite3_limit,
  116753. sqlite3_next_stmt,
  116754. sqlite3_sql,
  116755. sqlite3_status,
  116756. /*
  116757. ** Added for 3.7.4
  116758. */
  116759. sqlite3_backup_finish,
  116760. sqlite3_backup_init,
  116761. sqlite3_backup_pagecount,
  116762. sqlite3_backup_remaining,
  116763. sqlite3_backup_step,
  116764. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  116765. sqlite3_compileoption_get,
  116766. sqlite3_compileoption_used,
  116767. #else
  116768. 0,
  116769. 0,
  116770. #endif
  116771. sqlite3_create_function_v2,
  116772. sqlite3_db_config,
  116773. sqlite3_db_mutex,
  116774. sqlite3_db_status,
  116775. sqlite3_extended_errcode,
  116776. sqlite3_log,
  116777. sqlite3_soft_heap_limit64,
  116778. sqlite3_sourceid,
  116779. sqlite3_stmt_status,
  116780. sqlite3_strnicmp,
  116781. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  116782. sqlite3_unlock_notify,
  116783. #else
  116784. 0,
  116785. #endif
  116786. #ifndef SQLITE_OMIT_WAL
  116787. sqlite3_wal_autocheckpoint,
  116788. sqlite3_wal_checkpoint,
  116789. sqlite3_wal_hook,
  116790. #else
  116791. 0,
  116792. 0,
  116793. 0,
  116794. #endif
  116795. sqlite3_blob_reopen,
  116796. sqlite3_vtab_config,
  116797. sqlite3_vtab_on_conflict,
  116798. sqlite3_close_v2,
  116799. sqlite3_db_filename,
  116800. sqlite3_db_readonly,
  116801. sqlite3_db_release_memory,
  116802. sqlite3_errstr,
  116803. sqlite3_stmt_busy,
  116804. sqlite3_stmt_readonly,
  116805. sqlite3_stricmp,
  116806. sqlite3_uri_boolean,
  116807. sqlite3_uri_int64,
  116808. sqlite3_uri_parameter,
  116809. sqlite3_vsnprintf,
  116810. sqlite3_wal_checkpoint_v2,
  116811. /* Version 3.8.7 and later */
  116812. sqlite3_auto_extension,
  116813. sqlite3_bind_blob64,
  116814. sqlite3_bind_text64,
  116815. sqlite3_cancel_auto_extension,
  116816. sqlite3_load_extension,
  116817. sqlite3_malloc64,
  116818. sqlite3_msize,
  116819. sqlite3_realloc64,
  116820. sqlite3_reset_auto_extension,
  116821. sqlite3_result_blob64,
  116822. sqlite3_result_text64,
  116823. sqlite3_strglob,
  116824. /* Version 3.8.11 and later */
  116825. (sqlite3_value*(*)(const sqlite3_value*))sqlite3_value_dup,
  116826. sqlite3_value_free,
  116827. sqlite3_result_zeroblob64,
  116828. sqlite3_bind_zeroblob64,
  116829. /* Version 3.9.0 and later */
  116830. sqlite3_value_subtype,
  116831. sqlite3_result_subtype,
  116832. /* Version 3.10.0 and later */
  116833. sqlite3_status64,
  116834. sqlite3_strlike,
  116835. sqlite3_db_cacheflush,
  116836. /* Version 3.12.0 and later */
  116837. sqlite3_system_errno,
  116838. /* Version 3.14.0 and later */
  116839. sqlite3_trace_v2,
  116840. sqlite3_expanded_sql,
  116841. /* Version 3.18.0 and later */
  116842. sqlite3_set_last_insert_rowid,
  116843. /* Version 3.20.0 and later */
  116844. sqlite3_prepare_v3,
  116845. sqlite3_prepare16_v3,
  116846. sqlite3_bind_pointer,
  116847. sqlite3_result_pointer,
  116848. sqlite3_value_pointer,
  116849. /* Version 3.22.0 and later */
  116850. sqlite3_vtab_nochange,
  116851. sqlite3_value_nochange,
  116852. sqlite3_vtab_collation,
  116853. /* Version 3.24.0 and later */
  116854. sqlite3_keyword_count,
  116855. sqlite3_keyword_name,
  116856. sqlite3_keyword_check,
  116857. sqlite3_str_new,
  116858. sqlite3_str_finish,
  116859. sqlite3_str_appendf,
  116860. sqlite3_str_vappendf,
  116861. sqlite3_str_append,
  116862. sqlite3_str_appendall,
  116863. sqlite3_str_appendchar,
  116864. sqlite3_str_reset,
  116865. sqlite3_str_errcode,
  116866. sqlite3_str_length,
  116867. sqlite3_str_value,
  116868. /* Version 3.25.0 and later */
  116869. sqlite3_create_window_function,
  116870. /* Version 3.26.0 and later */
  116871. #ifdef SQLITE_ENABLE_NORMALIZE
  116872. sqlite3_normalized_sql,
  116873. #else
  116874. 0,
  116875. #endif
  116876. /* Version 3.28.0 and later */
  116877. sqlite3_stmt_isexplain,
  116878. sqlite3_value_frombind,
  116879. /* Version 3.30.0 and later */
  116880. #ifndef SQLITE_OMIT_VIRTUALTABLE
  116881. sqlite3_drop_modules,
  116882. #else
  116883. 0,
  116884. #endif
  116885. /* Version 3.31.0 and later */
  116886. sqlite3_hard_heap_limit64,
  116887. sqlite3_uri_key,
  116888. sqlite3_filename_database,
  116889. sqlite3_filename_journal,
  116890. sqlite3_filename_wal,
  116891. /* Version 3.32.0 and later */
  116892. sqlite3_create_filename,
  116893. sqlite3_free_filename,
  116894. sqlite3_database_file_object,
  116895. };
  116896. /* True if x is the directory separator character
  116897. */
  116898. #if SQLITE_OS_WIN
  116899. # define DirSep(X) ((X)=='/'||(X)=='\\')
  116900. #else
  116901. # define DirSep(X) ((X)=='/')
  116902. #endif
  116903. /*
  116904. ** Attempt to load an SQLite extension library contained in the file
  116905. ** zFile. The entry point is zProc. zProc may be 0 in which case a
  116906. ** default entry point name (sqlite3_extension_init) is used. Use
  116907. ** of the default name is recommended.
  116908. **
  116909. ** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
  116910. **
  116911. ** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with
  116912. ** error message text. The calling function should free this memory
  116913. ** by calling sqlite3DbFree(db, ).
  116914. */
  116915. static int sqlite3LoadExtension(
  116916. sqlite3 *db, /* Load the extension into this database connection */
  116917. const char *zFile, /* Name of the shared library containing extension */
  116918. const char *zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */
  116919. char **pzErrMsg /* Put error message here if not 0 */
  116920. ){
  116921. sqlite3_vfs *pVfs = db->pVfs;
  116922. void *handle;
  116923. sqlite3_loadext_entry xInit;
  116924. char *zErrmsg = 0;
  116925. const char *zEntry;
  116926. char *zAltEntry = 0;
  116927. void **aHandle;
  116928. u64 nMsg = 300 + sqlite3Strlen30(zFile);
  116929. int ii;
  116930. int rc;
  116931. /* Shared library endings to try if zFile cannot be loaded as written */
  116932. static const char *azEndings[] = {
  116933. #if SQLITE_OS_WIN
  116934. "dll"
  116935. #elif defined(__APPLE__)
  116936. "dylib"
  116937. #else
  116938. "so"
  116939. #endif
  116940. };
  116941. if( pzErrMsg ) *pzErrMsg = 0;
  116942. /* Ticket #1863. To avoid a creating security problems for older
  116943. ** applications that relink against newer versions of SQLite, the
  116944. ** ability to run load_extension is turned off by default. One
  116945. ** must call either sqlite3_enable_load_extension(db) or
  116946. ** sqlite3_db_config(db, SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION, 1, 0)
  116947. ** to turn on extension loading.
  116948. */
  116949. if( (db->flags & SQLITE_LoadExtension)==0 ){
  116950. if( pzErrMsg ){
  116951. *pzErrMsg = sqlite3_mprintf("not authorized");
  116952. }
  116953. return SQLITE_ERROR;
  116954. }
  116955. zEntry = zProc ? zProc : "sqlite3_extension_init";
  116956. handle = sqlite3OsDlOpen(pVfs, zFile);
  116957. #if SQLITE_OS_UNIX || SQLITE_OS_WIN
  116958. for(ii=0; ii<ArraySize(azEndings) && handle==0; ii++){
  116959. char *zAltFile = sqlite3_mprintf("%s.%s", zFile, azEndings[ii]);
  116960. if( zAltFile==0 ) return SQLITE_NOMEM_BKPT;
  116961. handle = sqlite3OsDlOpen(pVfs, zAltFile);
  116962. sqlite3_free(zAltFile);
  116963. }
  116964. #endif
  116965. if( handle==0 ){
  116966. if( pzErrMsg ){
  116967. *pzErrMsg = zErrmsg = sqlite3_malloc64(nMsg);
  116968. if( zErrmsg ){
  116969. sqlite3_snprintf(nMsg, zErrmsg,
  116970. "unable to open shared library [%s]", zFile);
  116971. sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
  116972. }
  116973. }
  116974. return SQLITE_ERROR;
  116975. }
  116976. xInit = (sqlite3_loadext_entry)sqlite3OsDlSym(pVfs, handle, zEntry);
  116977. /* If no entry point was specified and the default legacy
  116978. ** entry point name "sqlite3_extension_init" was not found, then
  116979. ** construct an entry point name "sqlite3_X_init" where the X is
  116980. ** replaced by the lowercase value of every ASCII alphabetic
  116981. ** character in the filename after the last "/" upto the first ".",
  116982. ** and eliding the first three characters if they are "lib".
  116983. ** Examples:
  116984. **
  116985. ** /usr/local/lib/libExample5.4.3.so ==> sqlite3_example_init
  116986. ** C:/lib/mathfuncs.dll ==> sqlite3_mathfuncs_init
  116987. */
  116988. if( xInit==0 && zProc==0 ){
  116989. int iFile, iEntry, c;
  116990. int ncFile = sqlite3Strlen30(zFile);
  116991. zAltEntry = sqlite3_malloc64(ncFile+30);
  116992. if( zAltEntry==0 ){
  116993. sqlite3OsDlClose(pVfs, handle);
  116994. return SQLITE_NOMEM_BKPT;
  116995. }
  116996. memcpy(zAltEntry, "sqlite3_", 8);
  116997. for(iFile=ncFile-1; iFile>=0 && !DirSep(zFile[iFile]); iFile--){}
  116998. iFile++;
  116999. if( sqlite3_strnicmp(zFile+iFile, "lib", 3)==0 ) iFile += 3;
  117000. for(iEntry=8; (c = zFile[iFile])!=0 && c!='.'; iFile++){
  117001. if( sqlite3Isalpha(c) ){
  117002. zAltEntry[iEntry++] = (char)sqlite3UpperToLower[(unsigned)c];
  117003. }
  117004. }
  117005. memcpy(zAltEntry+iEntry, "_init", 6);
  117006. zEntry = zAltEntry;
  117007. xInit = (sqlite3_loadext_entry)sqlite3OsDlSym(pVfs, handle, zEntry);
  117008. }
  117009. if( xInit==0 ){
  117010. if( pzErrMsg ){
  117011. nMsg += sqlite3Strlen30(zEntry);
  117012. *pzErrMsg = zErrmsg = sqlite3_malloc64(nMsg);
  117013. if( zErrmsg ){
  117014. sqlite3_snprintf(nMsg, zErrmsg,
  117015. "no entry point [%s] in shared library [%s]", zEntry, zFile);
  117016. sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
  117017. }
  117018. }
  117019. sqlite3OsDlClose(pVfs, handle);
  117020. sqlite3_free(zAltEntry);
  117021. return SQLITE_ERROR;
  117022. }
  117023. sqlite3_free(zAltEntry);
  117024. rc = xInit(db, &zErrmsg, &sqlite3Apis);
  117025. if( rc ){
  117026. if( rc==SQLITE_OK_LOAD_PERMANENTLY ) return SQLITE_OK;
  117027. if( pzErrMsg ){
  117028. *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
  117029. }
  117030. sqlite3_free(zErrmsg);
  117031. sqlite3OsDlClose(pVfs, handle);
  117032. return SQLITE_ERROR;
  117033. }
  117034. /* Append the new shared library handle to the db->aExtension array. */
  117035. aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));
  117036. if( aHandle==0 ){
  117037. return SQLITE_NOMEM_BKPT;
  117038. }
  117039. if( db->nExtension>0 ){
  117040. memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);
  117041. }
  117042. sqlite3DbFree(db, db->aExtension);
  117043. db->aExtension = aHandle;
  117044. db->aExtension[db->nExtension++] = handle;
  117045. return SQLITE_OK;
  117046. }
  117047. SQLITE_API int sqlite3_load_extension(
  117048. sqlite3 *db, /* Load the extension into this database connection */
  117049. const char *zFile, /* Name of the shared library containing extension */
  117050. const char *zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */
  117051. char **pzErrMsg /* Put error message here if not 0 */
  117052. ){
  117053. int rc;
  117054. sqlite3_mutex_enter(db->mutex);
  117055. rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg);
  117056. rc = sqlite3ApiExit(db, rc);
  117057. sqlite3_mutex_leave(db->mutex);
  117058. return rc;
  117059. }
  117060. /*
  117061. ** Call this routine when the database connection is closing in order
  117062. ** to clean up loaded extensions
  117063. */
  117064. SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){
  117065. int i;
  117066. assert( sqlite3_mutex_held(db->mutex) );
  117067. for(i=0; i<db->nExtension; i++){
  117068. sqlite3OsDlClose(db->pVfs, db->aExtension[i]);
  117069. }
  117070. sqlite3DbFree(db, db->aExtension);
  117071. }
  117072. /*
  117073. ** Enable or disable extension loading. Extension loading is disabled by
  117074. ** default so as not to open security holes in older applications.
  117075. */
  117076. SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff){
  117077. sqlite3_mutex_enter(db->mutex);
  117078. if( onoff ){
  117079. db->flags |= SQLITE_LoadExtension|SQLITE_LoadExtFunc;
  117080. }else{
  117081. db->flags &= ~(u64)(SQLITE_LoadExtension|SQLITE_LoadExtFunc);
  117082. }
  117083. sqlite3_mutex_leave(db->mutex);
  117084. return SQLITE_OK;
  117085. }
  117086. #endif /* !defined(SQLITE_OMIT_LOAD_EXTENSION) */
  117087. /*
  117088. ** The following object holds the list of automatically loaded
  117089. ** extensions.
  117090. **
  117091. ** This list is shared across threads. The SQLITE_MUTEX_STATIC_MASTER
  117092. ** mutex must be held while accessing this list.
  117093. */
  117094. typedef struct sqlite3AutoExtList sqlite3AutoExtList;
  117095. static SQLITE_WSD struct sqlite3AutoExtList {
  117096. u32 nExt; /* Number of entries in aExt[] */
  117097. void (**aExt)(void); /* Pointers to the extension init functions */
  117098. } sqlite3Autoext = { 0, 0 };
  117099. /* The "wsdAutoext" macro will resolve to the autoextension
  117100. ** state vector. If writable static data is unsupported on the target,
  117101. ** we have to locate the state vector at run-time. In the more common
  117102. ** case where writable static data is supported, wsdStat can refer directly
  117103. ** to the "sqlite3Autoext" state vector declared above.
  117104. */
  117105. #ifdef SQLITE_OMIT_WSD
  117106. # define wsdAutoextInit \
  117107. sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext)
  117108. # define wsdAutoext x[0]
  117109. #else
  117110. # define wsdAutoextInit
  117111. # define wsdAutoext sqlite3Autoext
  117112. #endif
  117113. /*
  117114. ** Register a statically linked extension that is automatically
  117115. ** loaded by every new database connection.
  117116. */
  117117. SQLITE_API int sqlite3_auto_extension(
  117118. void (*xInit)(void)
  117119. ){
  117120. int rc = SQLITE_OK;
  117121. #ifndef SQLITE_OMIT_AUTOINIT
  117122. rc = sqlite3_initialize();
  117123. if( rc ){
  117124. return rc;
  117125. }else
  117126. #endif
  117127. {
  117128. u32 i;
  117129. #if SQLITE_THREADSAFE
  117130. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  117131. #endif
  117132. wsdAutoextInit;
  117133. sqlite3_mutex_enter(mutex);
  117134. for(i=0; i<wsdAutoext.nExt; i++){
  117135. if( wsdAutoext.aExt[i]==xInit ) break;
  117136. }
  117137. if( i==wsdAutoext.nExt ){
  117138. u64 nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);
  117139. void (**aNew)(void);
  117140. aNew = sqlite3_realloc64(wsdAutoext.aExt, nByte);
  117141. if( aNew==0 ){
  117142. rc = SQLITE_NOMEM_BKPT;
  117143. }else{
  117144. wsdAutoext.aExt = aNew;
  117145. wsdAutoext.aExt[wsdAutoext.nExt] = xInit;
  117146. wsdAutoext.nExt++;
  117147. }
  117148. }
  117149. sqlite3_mutex_leave(mutex);
  117150. assert( (rc&0xff)==rc );
  117151. return rc;
  117152. }
  117153. }
  117154. /*
  117155. ** Cancel a prior call to sqlite3_auto_extension. Remove xInit from the
  117156. ** set of routines that is invoked for each new database connection, if it
  117157. ** is currently on the list. If xInit is not on the list, then this
  117158. ** routine is a no-op.
  117159. **
  117160. ** Return 1 if xInit was found on the list and removed. Return 0 if xInit
  117161. ** was not on the list.
  117162. */
  117163. SQLITE_API int sqlite3_cancel_auto_extension(
  117164. void (*xInit)(void)
  117165. ){
  117166. #if SQLITE_THREADSAFE
  117167. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  117168. #endif
  117169. int i;
  117170. int n = 0;
  117171. wsdAutoextInit;
  117172. sqlite3_mutex_enter(mutex);
  117173. for(i=(int)wsdAutoext.nExt-1; i>=0; i--){
  117174. if( wsdAutoext.aExt[i]==xInit ){
  117175. wsdAutoext.nExt--;
  117176. wsdAutoext.aExt[i] = wsdAutoext.aExt[wsdAutoext.nExt];
  117177. n++;
  117178. break;
  117179. }
  117180. }
  117181. sqlite3_mutex_leave(mutex);
  117182. return n;
  117183. }
  117184. /*
  117185. ** Reset the automatic extension loading mechanism.
  117186. */
  117187. SQLITE_API void sqlite3_reset_auto_extension(void){
  117188. #ifndef SQLITE_OMIT_AUTOINIT
  117189. if( sqlite3_initialize()==SQLITE_OK )
  117190. #endif
  117191. {
  117192. #if SQLITE_THREADSAFE
  117193. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  117194. #endif
  117195. wsdAutoextInit;
  117196. sqlite3_mutex_enter(mutex);
  117197. sqlite3_free(wsdAutoext.aExt);
  117198. wsdAutoext.aExt = 0;
  117199. wsdAutoext.nExt = 0;
  117200. sqlite3_mutex_leave(mutex);
  117201. }
  117202. }
  117203. /*
  117204. ** Load all automatic extensions.
  117205. **
  117206. ** If anything goes wrong, set an error in the database connection.
  117207. */
  117208. SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *db){
  117209. u32 i;
  117210. int go = 1;
  117211. int rc;
  117212. sqlite3_loadext_entry xInit;
  117213. wsdAutoextInit;
  117214. if( wsdAutoext.nExt==0 ){
  117215. /* Common case: early out without every having to acquire a mutex */
  117216. return;
  117217. }
  117218. for(i=0; go; i++){
  117219. char *zErrmsg;
  117220. #if SQLITE_THREADSAFE
  117221. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  117222. #endif
  117223. #ifdef SQLITE_OMIT_LOAD_EXTENSION
  117224. const sqlite3_api_routines *pThunk = 0;
  117225. #else
  117226. const sqlite3_api_routines *pThunk = &sqlite3Apis;
  117227. #endif
  117228. sqlite3_mutex_enter(mutex);
  117229. if( i>=wsdAutoext.nExt ){
  117230. xInit = 0;
  117231. go = 0;
  117232. }else{
  117233. xInit = (sqlite3_loadext_entry)wsdAutoext.aExt[i];
  117234. }
  117235. sqlite3_mutex_leave(mutex);
  117236. zErrmsg = 0;
  117237. if( xInit && (rc = xInit(db, &zErrmsg, pThunk))!=0 ){
  117238. sqlite3ErrorWithMsg(db, rc,
  117239. "automatic extension loading failed: %s", zErrmsg);
  117240. go = 0;
  117241. }
  117242. sqlite3_free(zErrmsg);
  117243. }
  117244. }
  117245. /************** End of loadext.c *********************************************/
  117246. /************** Begin file pragma.c ******************************************/
  117247. /*
  117248. ** 2003 April 6
  117249. **
  117250. ** The author disclaims copyright to this source code. In place of
  117251. ** a legal notice, here is a blessing:
  117252. **
  117253. ** May you do good and not evil.
  117254. ** May you find forgiveness for yourself and forgive others.
  117255. ** May you share freely, never taking more than you give.
  117256. **
  117257. *************************************************************************
  117258. ** This file contains code used to implement the PRAGMA command.
  117259. */
  117260. /* #include "sqliteInt.h" */
  117261. #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
  117262. # if defined(__APPLE__)
  117263. # define SQLITE_ENABLE_LOCKING_STYLE 1
  117264. # else
  117265. # define SQLITE_ENABLE_LOCKING_STYLE 0
  117266. # endif
  117267. #endif
  117268. /***************************************************************************
  117269. ** The "pragma.h" include file is an automatically generated file that
  117270. ** that includes the PragType_XXXX macro definitions and the aPragmaName[]
  117271. ** object. This ensures that the aPragmaName[] table is arranged in
  117272. ** lexicographical order to facility a binary search of the pragma name.
  117273. ** Do not edit pragma.h directly. Edit and rerun the script in at
  117274. ** ../tool/mkpragmatab.tcl. */
  117275. /************** Include pragma.h in the middle of pragma.c *******************/
  117276. /************** Begin file pragma.h ******************************************/
  117277. /* DO NOT EDIT!
  117278. ** This file is automatically generated by the script at
  117279. ** ../tool/mkpragmatab.tcl. To update the set of pragmas, edit
  117280. ** that script and rerun it.
  117281. */
  117282. /* The various pragma types */
  117283. #define PragTyp_ACTIVATE_EXTENSIONS 0
  117284. #define PragTyp_ANALYSIS_LIMIT 1
  117285. #define PragTyp_HEADER_VALUE 2
  117286. #define PragTyp_AUTO_VACUUM 3
  117287. #define PragTyp_FLAG 4
  117288. #define PragTyp_BUSY_TIMEOUT 5
  117289. #define PragTyp_CACHE_SIZE 6
  117290. #define PragTyp_CACHE_SPILL 7
  117291. #define PragTyp_CASE_SENSITIVE_LIKE 8
  117292. #define PragTyp_COLLATION_LIST 9
  117293. #define PragTyp_COMPILE_OPTIONS 10
  117294. #define PragTyp_DATA_STORE_DIRECTORY 11
  117295. #define PragTyp_DATABASE_LIST 12
  117296. #define PragTyp_DEFAULT_CACHE_SIZE 13
  117297. #define PragTyp_ENCODING 14
  117298. #define PragTyp_FOREIGN_KEY_CHECK 15
  117299. #define PragTyp_FOREIGN_KEY_LIST 16
  117300. #define PragTyp_FUNCTION_LIST 17
  117301. #define PragTyp_HARD_HEAP_LIMIT 18
  117302. #define PragTyp_INCREMENTAL_VACUUM 19
  117303. #define PragTyp_INDEX_INFO 20
  117304. #define PragTyp_INDEX_LIST 21
  117305. #define PragTyp_INTEGRITY_CHECK 22
  117306. #define PragTyp_JOURNAL_MODE 23
  117307. #define PragTyp_JOURNAL_SIZE_LIMIT 24
  117308. #define PragTyp_LOCK_PROXY_FILE 25
  117309. #define PragTyp_LOCKING_MODE 26
  117310. #define PragTyp_PAGE_COUNT 27
  117311. #define PragTyp_MMAP_SIZE 28
  117312. #define PragTyp_MODULE_LIST 29
  117313. #define PragTyp_OPTIMIZE 30
  117314. #define PragTyp_PAGE_SIZE 31
  117315. #define PragTyp_PRAGMA_LIST 32
  117316. #define PragTyp_SECURE_DELETE 33
  117317. #define PragTyp_SHRINK_MEMORY 34
  117318. #define PragTyp_SOFT_HEAP_LIMIT 35
  117319. #define PragTyp_SYNCHRONOUS 36
  117320. #define PragTyp_TABLE_INFO 37
  117321. #define PragTyp_TEMP_STORE 38
  117322. #define PragTyp_TEMP_STORE_DIRECTORY 39
  117323. #define PragTyp_THREADS 40
  117324. #define PragTyp_WAL_AUTOCHECKPOINT 41
  117325. #define PragTyp_WAL_CHECKPOINT 42
  117326. #define PragTyp_LOCK_STATUS 43
  117327. #define PragTyp_STATS 44
  117328. /* Property flags associated with various pragma. */
  117329. #define PragFlg_NeedSchema 0x01 /* Force schema load before running */
  117330. #define PragFlg_NoColumns 0x02 /* OP_ResultRow called with zero columns */
  117331. #define PragFlg_NoColumns1 0x04 /* zero columns if RHS argument is present */
  117332. #define PragFlg_ReadOnly 0x08 /* Read-only HEADER_VALUE */
  117333. #define PragFlg_Result0 0x10 /* Acts as query when no argument */
  117334. #define PragFlg_Result1 0x20 /* Acts as query when has one argument */
  117335. #define PragFlg_SchemaOpt 0x40 /* Schema restricts name search if present */
  117336. #define PragFlg_SchemaReq 0x80 /* Schema required - "main" is default */
  117337. /* Names of columns for pragmas that return multi-column result
  117338. ** or that return single-column results where the name of the
  117339. ** result column is different from the name of the pragma
  117340. */
  117341. static const char *const pragCName[] = {
  117342. /* 0 */ "id", /* Used by: foreign_key_list */
  117343. /* 1 */ "seq",
  117344. /* 2 */ "table",
  117345. /* 3 */ "from",
  117346. /* 4 */ "to",
  117347. /* 5 */ "on_update",
  117348. /* 6 */ "on_delete",
  117349. /* 7 */ "match",
  117350. /* 8 */ "cid", /* Used by: table_xinfo */
  117351. /* 9 */ "name",
  117352. /* 10 */ "type",
  117353. /* 11 */ "notnull",
  117354. /* 12 */ "dflt_value",
  117355. /* 13 */ "pk",
  117356. /* 14 */ "hidden",
  117357. /* table_info reuses 8 */
  117358. /* 15 */ "seqno", /* Used by: index_xinfo */
  117359. /* 16 */ "cid",
  117360. /* 17 */ "name",
  117361. /* 18 */ "desc",
  117362. /* 19 */ "coll",
  117363. /* 20 */ "key",
  117364. /* 21 */ "name", /* Used by: function_list */
  117365. /* 22 */ "builtin",
  117366. /* 23 */ "type",
  117367. /* 24 */ "enc",
  117368. /* 25 */ "narg",
  117369. /* 26 */ "flags",
  117370. /* 27 */ "tbl", /* Used by: stats */
  117371. /* 28 */ "idx",
  117372. /* 29 */ "wdth",
  117373. /* 30 */ "hght",
  117374. /* 31 */ "flgs",
  117375. /* 32 */ "seq", /* Used by: index_list */
  117376. /* 33 */ "name",
  117377. /* 34 */ "unique",
  117378. /* 35 */ "origin",
  117379. /* 36 */ "partial",
  117380. /* 37 */ "table", /* Used by: foreign_key_check */
  117381. /* 38 */ "rowid",
  117382. /* 39 */ "parent",
  117383. /* 40 */ "fkid",
  117384. /* index_info reuses 15 */
  117385. /* 41 */ "seq", /* Used by: database_list */
  117386. /* 42 */ "name",
  117387. /* 43 */ "file",
  117388. /* 44 */ "busy", /* Used by: wal_checkpoint */
  117389. /* 45 */ "log",
  117390. /* 46 */ "checkpointed",
  117391. /* collation_list reuses 32 */
  117392. /* 47 */ "database", /* Used by: lock_status */
  117393. /* 48 */ "status",
  117394. /* 49 */ "cache_size", /* Used by: default_cache_size */
  117395. /* module_list pragma_list reuses 9 */
  117396. /* 50 */ "timeout", /* Used by: busy_timeout */
  117397. };
  117398. /* Definitions of all built-in pragmas */
  117399. typedef struct PragmaName {
  117400. const char *const zName; /* Name of pragma */
  117401. u8 ePragTyp; /* PragTyp_XXX value */
  117402. u8 mPragFlg; /* Zero or more PragFlg_XXX values */
  117403. u8 iPragCName; /* Start of column names in pragCName[] */
  117404. u8 nPragCName; /* Num of col names. 0 means use pragma name */
  117405. u64 iArg; /* Extra argument */
  117406. } PragmaName;
  117407. static const PragmaName aPragmaName[] = {
  117408. #if defined(SQLITE_ENABLE_CEROD)
  117409. {/* zName: */ "activate_extensions",
  117410. /* ePragTyp: */ PragTyp_ACTIVATE_EXTENSIONS,
  117411. /* ePragFlg: */ 0,
  117412. /* ColNames: */ 0, 0,
  117413. /* iArg: */ 0 },
  117414. #endif
  117415. {/* zName: */ "analysis_limit",
  117416. /* ePragTyp: */ PragTyp_ANALYSIS_LIMIT,
  117417. /* ePragFlg: */ PragFlg_Result0,
  117418. /* ColNames: */ 0, 0,
  117419. /* iArg: */ 0 },
  117420. #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  117421. {/* zName: */ "application_id",
  117422. /* ePragTyp: */ PragTyp_HEADER_VALUE,
  117423. /* ePragFlg: */ PragFlg_NoColumns1|PragFlg_Result0,
  117424. /* ColNames: */ 0, 0,
  117425. /* iArg: */ BTREE_APPLICATION_ID },
  117426. #endif
  117427. #if !defined(SQLITE_OMIT_AUTOVACUUM)
  117428. {/* zName: */ "auto_vacuum",
  117429. /* ePragTyp: */ PragTyp_AUTO_VACUUM,
  117430. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
  117431. /* ColNames: */ 0, 0,
  117432. /* iArg: */ 0 },
  117433. #endif
  117434. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  117435. #if !defined(SQLITE_OMIT_AUTOMATIC_INDEX)
  117436. {/* zName: */ "automatic_index",
  117437. /* ePragTyp: */ PragTyp_FLAG,
  117438. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  117439. /* ColNames: */ 0, 0,
  117440. /* iArg: */ SQLITE_AutoIndex },
  117441. #endif
  117442. #endif
  117443. {/* zName: */ "busy_timeout",
  117444. /* ePragTyp: */ PragTyp_BUSY_TIMEOUT,
  117445. /* ePragFlg: */ PragFlg_Result0,
  117446. /* ColNames: */ 50, 1,
  117447. /* iArg: */ 0 },
  117448. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  117449. {/* zName: */ "cache_size",
  117450. /* ePragTyp: */ PragTyp_CACHE_SIZE,
  117451. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
  117452. /* ColNames: */ 0, 0,
  117453. /* iArg: */ 0 },
  117454. #endif
  117455. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  117456. {/* zName: */ "cache_spill",
  117457. /* ePragTyp: */ PragTyp_CACHE_SPILL,
  117458. /* ePragFlg: */ PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
  117459. /* ColNames: */ 0, 0,
  117460. /* iArg: */ 0 },
  117461. #endif
  117462. #if !defined(SQLITE_OMIT_CASE_SENSITIVE_LIKE_PRAGMA)
  117463. {/* zName: */ "case_sensitive_like",
  117464. /* ePragTyp: */ PragTyp_CASE_SENSITIVE_LIKE,
  117465. /* ePragFlg: */ PragFlg_NoColumns,
  117466. /* ColNames: */ 0, 0,
  117467. /* iArg: */ 0 },
  117468. #endif
  117469. {/* zName: */ "cell_size_check",
  117470. /* ePragTyp: */ PragTyp_FLAG,
  117471. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  117472. /* ColNames: */ 0, 0,
  117473. /* iArg: */ SQLITE_CellSizeCk },
  117474. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  117475. {/* zName: */ "checkpoint_fullfsync",
  117476. /* ePragTyp: */ PragTyp_FLAG,
  117477. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  117478. /* ColNames: */ 0, 0,
  117479. /* iArg: */ SQLITE_CkptFullFSync },
  117480. #endif
  117481. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  117482. {/* zName: */ "collation_list",
  117483. /* ePragTyp: */ PragTyp_COLLATION_LIST,
  117484. /* ePragFlg: */ PragFlg_Result0,
  117485. /* ColNames: */ 32, 2,
  117486. /* iArg: */ 0 },
  117487. #endif
  117488. #if !defined(SQLITE_OMIT_COMPILEOPTION_DIAGS)
  117489. {/* zName: */ "compile_options",
  117490. /* ePragTyp: */ PragTyp_COMPILE_OPTIONS,
  117491. /* ePragFlg: */ PragFlg_Result0,
  117492. /* ColNames: */ 0, 0,
  117493. /* iArg: */ 0 },
  117494. #endif
  117495. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  117496. {/* zName: */ "count_changes",
  117497. /* ePragTyp: */ PragTyp_FLAG,
  117498. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  117499. /* ColNames: */ 0, 0,
  117500. /* iArg: */ SQLITE_CountRows },
  117501. #endif
  117502. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_OS_WIN
  117503. {/* zName: */ "data_store_directory",
  117504. /* ePragTyp: */ PragTyp_DATA_STORE_DIRECTORY,
  117505. /* ePragFlg: */ PragFlg_NoColumns1,
  117506. /* ColNames: */ 0, 0,
  117507. /* iArg: */ 0 },
  117508. #endif
  117509. #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  117510. {/* zName: */ "data_version",
  117511. /* ePragTyp: */ PragTyp_HEADER_VALUE,
  117512. /* ePragFlg: */ PragFlg_ReadOnly|PragFlg_Result0,
  117513. /* ColNames: */ 0, 0,
  117514. /* iArg: */ BTREE_DATA_VERSION },
  117515. #endif
  117516. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  117517. {/* zName: */ "database_list",
  117518. /* ePragTyp: */ PragTyp_DATABASE_LIST,
  117519. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0,
  117520. /* ColNames: */ 41, 3,
  117521. /* iArg: */ 0 },
  117522. #endif
  117523. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
  117524. {/* zName: */ "default_cache_size",
  117525. /* ePragTyp: */ PragTyp_DEFAULT_CACHE_SIZE,
  117526. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
  117527. /* ColNames: */ 49, 1,
  117528. /* iArg: */ 0 },
  117529. #endif
  117530. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  117531. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  117532. {/* zName: */ "defer_foreign_keys",
  117533. /* ePragTyp: */ PragTyp_FLAG,
  117534. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  117535. /* ColNames: */ 0, 0,
  117536. /* iArg: */ SQLITE_DeferFKs },
  117537. #endif
  117538. #endif
  117539. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  117540. {/* zName: */ "empty_result_callbacks",
  117541. /* ePragTyp: */ PragTyp_FLAG,
  117542. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  117543. /* ColNames: */ 0, 0,
  117544. /* iArg: */ SQLITE_NullCallback },
  117545. #endif
  117546. #if !defined(SQLITE_OMIT_UTF16)
  117547. {/* zName: */ "encoding",
  117548. /* ePragTyp: */ PragTyp_ENCODING,
  117549. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  117550. /* ColNames: */ 0, 0,
  117551. /* iArg: */ 0 },
  117552. #endif
  117553. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  117554. {/* zName: */ "foreign_key_check",
  117555. /* ePragTyp: */ PragTyp_FOREIGN_KEY_CHECK,
  117556. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0,
  117557. /* ColNames: */ 37, 4,
  117558. /* iArg: */ 0 },
  117559. #endif
  117560. #if !defined(SQLITE_OMIT_FOREIGN_KEY)
  117561. {/* zName: */ "foreign_key_list",
  117562. /* ePragTyp: */ PragTyp_FOREIGN_KEY_LIST,
  117563. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
  117564. /* ColNames: */ 0, 8,
  117565. /* iArg: */ 0 },
  117566. #endif
  117567. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  117568. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  117569. {/* zName: */ "foreign_keys",
  117570. /* ePragTyp: */ PragTyp_FLAG,
  117571. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  117572. /* ColNames: */ 0, 0,
  117573. /* iArg: */ SQLITE_ForeignKeys },
  117574. #endif
  117575. #endif
  117576. #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  117577. {/* zName: */ "freelist_count",
  117578. /* ePragTyp: */ PragTyp_HEADER_VALUE,
  117579. /* ePragFlg: */ PragFlg_ReadOnly|PragFlg_Result0,
  117580. /* ColNames: */ 0, 0,
  117581. /* iArg: */ BTREE_FREE_PAGE_COUNT },
  117582. #endif
  117583. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  117584. {/* zName: */ "full_column_names",
  117585. /* ePragTyp: */ PragTyp_FLAG,
  117586. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  117587. /* ColNames: */ 0, 0,
  117588. /* iArg: */ SQLITE_FullColNames },
  117589. {/* zName: */ "fullfsync",
  117590. /* ePragTyp: */ PragTyp_FLAG,
  117591. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  117592. /* ColNames: */ 0, 0,
  117593. /* iArg: */ SQLITE_FullFSync },
  117594. #endif
  117595. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  117596. #if !defined(SQLITE_OMIT_INTROSPECTION_PRAGMAS)
  117597. {/* zName: */ "function_list",
  117598. /* ePragTyp: */ PragTyp_FUNCTION_LIST,
  117599. /* ePragFlg: */ PragFlg_Result0,
  117600. /* ColNames: */ 21, 6,
  117601. /* iArg: */ 0 },
  117602. #endif
  117603. #endif
  117604. {/* zName: */ "hard_heap_limit",
  117605. /* ePragTyp: */ PragTyp_HARD_HEAP_LIMIT,
  117606. /* ePragFlg: */ PragFlg_Result0,
  117607. /* ColNames: */ 0, 0,
  117608. /* iArg: */ 0 },
  117609. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  117610. #if !defined(SQLITE_OMIT_CHECK)
  117611. {/* zName: */ "ignore_check_constraints",
  117612. /* ePragTyp: */ PragTyp_FLAG,
  117613. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  117614. /* ColNames: */ 0, 0,
  117615. /* iArg: */ SQLITE_IgnoreChecks },
  117616. #endif
  117617. #endif
  117618. #if !defined(SQLITE_OMIT_AUTOVACUUM)
  117619. {/* zName: */ "incremental_vacuum",
  117620. /* ePragTyp: */ PragTyp_INCREMENTAL_VACUUM,
  117621. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_NoColumns,
  117622. /* ColNames: */ 0, 0,
  117623. /* iArg: */ 0 },
  117624. #endif
  117625. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  117626. {/* zName: */ "index_info",
  117627. /* ePragTyp: */ PragTyp_INDEX_INFO,
  117628. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
  117629. /* ColNames: */ 15, 3,
  117630. /* iArg: */ 0 },
  117631. {/* zName: */ "index_list",
  117632. /* ePragTyp: */ PragTyp_INDEX_LIST,
  117633. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
  117634. /* ColNames: */ 32, 5,
  117635. /* iArg: */ 0 },
  117636. {/* zName: */ "index_xinfo",
  117637. /* ePragTyp: */ PragTyp_INDEX_INFO,
  117638. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
  117639. /* ColNames: */ 15, 6,
  117640. /* iArg: */ 1 },
  117641. #endif
  117642. #if !defined(SQLITE_OMIT_INTEGRITY_CHECK)
  117643. {/* zName: */ "integrity_check",
  117644. /* ePragTyp: */ PragTyp_INTEGRITY_CHECK,
  117645. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_Result1,
  117646. /* ColNames: */ 0, 0,
  117647. /* iArg: */ 0 },
  117648. #endif
  117649. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  117650. {/* zName: */ "journal_mode",
  117651. /* ePragTyp: */ PragTyp_JOURNAL_MODE,
  117652. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq,
  117653. /* ColNames: */ 0, 0,
  117654. /* iArg: */ 0 },
  117655. {/* zName: */ "journal_size_limit",
  117656. /* ePragTyp: */ PragTyp_JOURNAL_SIZE_LIMIT,
  117657. /* ePragFlg: */ PragFlg_Result0|PragFlg_SchemaReq,
  117658. /* ColNames: */ 0, 0,
  117659. /* iArg: */ 0 },
  117660. #endif
  117661. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  117662. {/* zName: */ "legacy_alter_table",
  117663. /* ePragTyp: */ PragTyp_FLAG,
  117664. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  117665. /* ColNames: */ 0, 0,
  117666. /* iArg: */ SQLITE_LegacyAlter },
  117667. #endif
  117668. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_ENABLE_LOCKING_STYLE
  117669. {/* zName: */ "lock_proxy_file",
  117670. /* ePragTyp: */ PragTyp_LOCK_PROXY_FILE,
  117671. /* ePragFlg: */ PragFlg_NoColumns1,
  117672. /* ColNames: */ 0, 0,
  117673. /* iArg: */ 0 },
  117674. #endif
  117675. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  117676. {/* zName: */ "lock_status",
  117677. /* ePragTyp: */ PragTyp_LOCK_STATUS,
  117678. /* ePragFlg: */ PragFlg_Result0,
  117679. /* ColNames: */ 47, 2,
  117680. /* iArg: */ 0 },
  117681. #endif
  117682. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  117683. {/* zName: */ "locking_mode",
  117684. /* ePragTyp: */ PragTyp_LOCKING_MODE,
  117685. /* ePragFlg: */ PragFlg_Result0|PragFlg_SchemaReq,
  117686. /* ColNames: */ 0, 0,
  117687. /* iArg: */ 0 },
  117688. {/* zName: */ "max_page_count",
  117689. /* ePragTyp: */ PragTyp_PAGE_COUNT,
  117690. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq,
  117691. /* ColNames: */ 0, 0,
  117692. /* iArg: */ 0 },
  117693. {/* zName: */ "mmap_size",
  117694. /* ePragTyp: */ PragTyp_MMAP_SIZE,
  117695. /* ePragFlg: */ 0,
  117696. /* ColNames: */ 0, 0,
  117697. /* iArg: */ 0 },
  117698. #endif
  117699. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  117700. #if !defined(SQLITE_OMIT_VIRTUALTABLE)
  117701. #if !defined(SQLITE_OMIT_INTROSPECTION_PRAGMAS)
  117702. {/* zName: */ "module_list",
  117703. /* ePragTyp: */ PragTyp_MODULE_LIST,
  117704. /* ePragFlg: */ PragFlg_Result0,
  117705. /* ColNames: */ 9, 1,
  117706. /* iArg: */ 0 },
  117707. #endif
  117708. #endif
  117709. #endif
  117710. {/* zName: */ "optimize",
  117711. /* ePragTyp: */ PragTyp_OPTIMIZE,
  117712. /* ePragFlg: */ PragFlg_Result1|PragFlg_NeedSchema,
  117713. /* ColNames: */ 0, 0,
  117714. /* iArg: */ 0 },
  117715. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  117716. {/* zName: */ "page_count",
  117717. /* ePragTyp: */ PragTyp_PAGE_COUNT,
  117718. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq,
  117719. /* ColNames: */ 0, 0,
  117720. /* iArg: */ 0 },
  117721. {/* zName: */ "page_size",
  117722. /* ePragTyp: */ PragTyp_PAGE_SIZE,
  117723. /* ePragFlg: */ PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
  117724. /* ColNames: */ 0, 0,
  117725. /* iArg: */ 0 },
  117726. #endif
  117727. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  117728. #if defined(SQLITE_DEBUG)
  117729. {/* zName: */ "parser_trace",
  117730. /* ePragTyp: */ PragTyp_FLAG,
  117731. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  117732. /* ColNames: */ 0, 0,
  117733. /* iArg: */ SQLITE_ParserTrace },
  117734. #endif
  117735. #endif
  117736. #if !defined(SQLITE_OMIT_INTROSPECTION_PRAGMAS)
  117737. {/* zName: */ "pragma_list",
  117738. /* ePragTyp: */ PragTyp_PRAGMA_LIST,
  117739. /* ePragFlg: */ PragFlg_Result0,
  117740. /* ColNames: */ 9, 1,
  117741. /* iArg: */ 0 },
  117742. #endif
  117743. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  117744. {/* zName: */ "query_only",
  117745. /* ePragTyp: */ PragTyp_FLAG,
  117746. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  117747. /* ColNames: */ 0, 0,
  117748. /* iArg: */ SQLITE_QueryOnly },
  117749. #endif
  117750. #if !defined(SQLITE_OMIT_INTEGRITY_CHECK)
  117751. {/* zName: */ "quick_check",
  117752. /* ePragTyp: */ PragTyp_INTEGRITY_CHECK,
  117753. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_Result1,
  117754. /* ColNames: */ 0, 0,
  117755. /* iArg: */ 0 },
  117756. #endif
  117757. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  117758. {/* zName: */ "read_uncommitted",
  117759. /* ePragTyp: */ PragTyp_FLAG,
  117760. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  117761. /* ColNames: */ 0, 0,
  117762. /* iArg: */ SQLITE_ReadUncommit },
  117763. {/* zName: */ "recursive_triggers",
  117764. /* ePragTyp: */ PragTyp_FLAG,
  117765. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  117766. /* ColNames: */ 0, 0,
  117767. /* iArg: */ SQLITE_RecTriggers },
  117768. {/* zName: */ "reverse_unordered_selects",
  117769. /* ePragTyp: */ PragTyp_FLAG,
  117770. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  117771. /* ColNames: */ 0, 0,
  117772. /* iArg: */ SQLITE_ReverseOrder },
  117773. #endif
  117774. #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  117775. {/* zName: */ "schema_version",
  117776. /* ePragTyp: */ PragTyp_HEADER_VALUE,
  117777. /* ePragFlg: */ PragFlg_NoColumns1|PragFlg_Result0,
  117778. /* ColNames: */ 0, 0,
  117779. /* iArg: */ BTREE_SCHEMA_VERSION },
  117780. #endif
  117781. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  117782. {/* zName: */ "secure_delete",
  117783. /* ePragTyp: */ PragTyp_SECURE_DELETE,
  117784. /* ePragFlg: */ PragFlg_Result0,
  117785. /* ColNames: */ 0, 0,
  117786. /* iArg: */ 0 },
  117787. #endif
  117788. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  117789. {/* zName: */ "short_column_names",
  117790. /* ePragTyp: */ PragTyp_FLAG,
  117791. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  117792. /* ColNames: */ 0, 0,
  117793. /* iArg: */ SQLITE_ShortColNames },
  117794. #endif
  117795. {/* zName: */ "shrink_memory",
  117796. /* ePragTyp: */ PragTyp_SHRINK_MEMORY,
  117797. /* ePragFlg: */ PragFlg_NoColumns,
  117798. /* ColNames: */ 0, 0,
  117799. /* iArg: */ 0 },
  117800. {/* zName: */ "soft_heap_limit",
  117801. /* ePragTyp: */ PragTyp_SOFT_HEAP_LIMIT,
  117802. /* ePragFlg: */ PragFlg_Result0,
  117803. /* ColNames: */ 0, 0,
  117804. /* iArg: */ 0 },
  117805. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  117806. #if defined(SQLITE_DEBUG)
  117807. {/* zName: */ "sql_trace",
  117808. /* ePragTyp: */ PragTyp_FLAG,
  117809. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  117810. /* ColNames: */ 0, 0,
  117811. /* iArg: */ SQLITE_SqlTrace },
  117812. #endif
  117813. #endif
  117814. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) && defined(SQLITE_DEBUG)
  117815. {/* zName: */ "stats",
  117816. /* ePragTyp: */ PragTyp_STATS,
  117817. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq,
  117818. /* ColNames: */ 27, 5,
  117819. /* iArg: */ 0 },
  117820. #endif
  117821. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  117822. {/* zName: */ "synchronous",
  117823. /* ePragTyp: */ PragTyp_SYNCHRONOUS,
  117824. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result0|PragFlg_SchemaReq|PragFlg_NoColumns1,
  117825. /* ColNames: */ 0, 0,
  117826. /* iArg: */ 0 },
  117827. #endif
  117828. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  117829. {/* zName: */ "table_info",
  117830. /* ePragTyp: */ PragTyp_TABLE_INFO,
  117831. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
  117832. /* ColNames: */ 8, 6,
  117833. /* iArg: */ 0 },
  117834. {/* zName: */ "table_xinfo",
  117835. /* ePragTyp: */ PragTyp_TABLE_INFO,
  117836. /* ePragFlg: */ PragFlg_NeedSchema|PragFlg_Result1|PragFlg_SchemaOpt,
  117837. /* ColNames: */ 8, 7,
  117838. /* iArg: */ 1 },
  117839. #endif
  117840. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  117841. {/* zName: */ "temp_store",
  117842. /* ePragTyp: */ PragTyp_TEMP_STORE,
  117843. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  117844. /* ColNames: */ 0, 0,
  117845. /* iArg: */ 0 },
  117846. {/* zName: */ "temp_store_directory",
  117847. /* ePragTyp: */ PragTyp_TEMP_STORE_DIRECTORY,
  117848. /* ePragFlg: */ PragFlg_NoColumns1,
  117849. /* ColNames: */ 0, 0,
  117850. /* iArg: */ 0 },
  117851. #endif
  117852. {/* zName: */ "threads",
  117853. /* ePragTyp: */ PragTyp_THREADS,
  117854. /* ePragFlg: */ PragFlg_Result0,
  117855. /* ColNames: */ 0, 0,
  117856. /* iArg: */ 0 },
  117857. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  117858. {/* zName: */ "trusted_schema",
  117859. /* ePragTyp: */ PragTyp_FLAG,
  117860. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  117861. /* ColNames: */ 0, 0,
  117862. /* iArg: */ SQLITE_TrustedSchema },
  117863. #endif
  117864. #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  117865. {/* zName: */ "user_version",
  117866. /* ePragTyp: */ PragTyp_HEADER_VALUE,
  117867. /* ePragFlg: */ PragFlg_NoColumns1|PragFlg_Result0,
  117868. /* ColNames: */ 0, 0,
  117869. /* iArg: */ BTREE_USER_VERSION },
  117870. #endif
  117871. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  117872. #if defined(SQLITE_DEBUG)
  117873. {/* zName: */ "vdbe_addoptrace",
  117874. /* ePragTyp: */ PragTyp_FLAG,
  117875. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  117876. /* ColNames: */ 0, 0,
  117877. /* iArg: */ SQLITE_VdbeAddopTrace },
  117878. {/* zName: */ "vdbe_debug",
  117879. /* ePragTyp: */ PragTyp_FLAG,
  117880. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  117881. /* ColNames: */ 0, 0,
  117882. /* iArg: */ SQLITE_SqlTrace|SQLITE_VdbeListing|SQLITE_VdbeTrace },
  117883. {/* zName: */ "vdbe_eqp",
  117884. /* ePragTyp: */ PragTyp_FLAG,
  117885. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  117886. /* ColNames: */ 0, 0,
  117887. /* iArg: */ SQLITE_VdbeEQP },
  117888. {/* zName: */ "vdbe_listing",
  117889. /* ePragTyp: */ PragTyp_FLAG,
  117890. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  117891. /* ColNames: */ 0, 0,
  117892. /* iArg: */ SQLITE_VdbeListing },
  117893. {/* zName: */ "vdbe_trace",
  117894. /* ePragTyp: */ PragTyp_FLAG,
  117895. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  117896. /* ColNames: */ 0, 0,
  117897. /* iArg: */ SQLITE_VdbeTrace },
  117898. #endif
  117899. #endif
  117900. #if !defined(SQLITE_OMIT_WAL)
  117901. {/* zName: */ "wal_autocheckpoint",
  117902. /* ePragTyp: */ PragTyp_WAL_AUTOCHECKPOINT,
  117903. /* ePragFlg: */ 0,
  117904. /* ColNames: */ 0, 0,
  117905. /* iArg: */ 0 },
  117906. {/* zName: */ "wal_checkpoint",
  117907. /* ePragTyp: */ PragTyp_WAL_CHECKPOINT,
  117908. /* ePragFlg: */ PragFlg_NeedSchema,
  117909. /* ColNames: */ 44, 3,
  117910. /* iArg: */ 0 },
  117911. #endif
  117912. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  117913. {/* zName: */ "writable_schema",
  117914. /* ePragTyp: */ PragTyp_FLAG,
  117915. /* ePragFlg: */ PragFlg_Result0|PragFlg_NoColumns1,
  117916. /* ColNames: */ 0, 0,
  117917. /* iArg: */ SQLITE_WriteSchema|SQLITE_NoSchemaError },
  117918. #endif
  117919. };
  117920. /* Number of pragmas: 67 on by default, 77 total. */
  117921. /************** End of pragma.h **********************************************/
  117922. /************** Continuing where we left off in pragma.c *********************/
  117923. /*
  117924. ** Interpret the given string as a safety level. Return 0 for OFF,
  117925. ** 1 for ON or NORMAL, 2 for FULL, and 3 for EXTRA. Return 1 for an empty or
  117926. ** unrecognized string argument. The FULL and EXTRA option is disallowed
  117927. ** if the omitFull parameter it 1.
  117928. **
  117929. ** Note that the values returned are one less that the values that
  117930. ** should be passed into sqlite3BtreeSetSafetyLevel(). The is done
  117931. ** to support legacy SQL code. The safety level used to be boolean
  117932. ** and older scripts may have used numbers 0 for OFF and 1 for ON.
  117933. */
  117934. static u8 getSafetyLevel(const char *z, int omitFull, u8 dflt){
  117935. /* 123456789 123456789 123 */
  117936. static const char zText[] = "onoffalseyestruextrafull";
  117937. static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 15, 20};
  117938. static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 5, 4};
  117939. static const u8 iValue[] = {1, 0, 0, 0, 1, 1, 3, 2};
  117940. /* on no off false yes true extra full */
  117941. int i, n;
  117942. if( sqlite3Isdigit(*z) ){
  117943. return (u8)sqlite3Atoi(z);
  117944. }
  117945. n = sqlite3Strlen30(z);
  117946. for(i=0; i<ArraySize(iLength); i++){
  117947. if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0
  117948. && (!omitFull || iValue[i]<=1)
  117949. ){
  117950. return iValue[i];
  117951. }
  117952. }
  117953. return dflt;
  117954. }
  117955. /*
  117956. ** Interpret the given string as a boolean value.
  117957. */
  117958. SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z, u8 dflt){
  117959. return getSafetyLevel(z,1,dflt)!=0;
  117960. }
  117961. /* The sqlite3GetBoolean() function is used by other modules but the
  117962. ** remainder of this file is specific to PRAGMA processing. So omit
  117963. ** the rest of the file if PRAGMAs are omitted from the build.
  117964. */
  117965. #if !defined(SQLITE_OMIT_PRAGMA)
  117966. /*
  117967. ** Interpret the given string as a locking mode value.
  117968. */
  117969. static int getLockingMode(const char *z){
  117970. if( z ){
  117971. if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
  117972. if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
  117973. }
  117974. return PAGER_LOCKINGMODE_QUERY;
  117975. }
  117976. #ifndef SQLITE_OMIT_AUTOVACUUM
  117977. /*
  117978. ** Interpret the given string as an auto-vacuum mode value.
  117979. **
  117980. ** The following strings, "none", "full" and "incremental" are
  117981. ** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
  117982. */
  117983. static int getAutoVacuum(const char *z){
  117984. int i;
  117985. if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
  117986. if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
  117987. if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
  117988. i = sqlite3Atoi(z);
  117989. return (u8)((i>=0&&i<=2)?i:0);
  117990. }
  117991. #endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
  117992. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  117993. /*
  117994. ** Interpret the given string as a temp db location. Return 1 for file
  117995. ** backed temporary databases, 2 for the Red-Black tree in memory database
  117996. ** and 0 to use the compile-time default.
  117997. */
  117998. static int getTempStore(const char *z){
  117999. if( z[0]>='0' && z[0]<='2' ){
  118000. return z[0] - '0';
  118001. }else if( sqlite3StrICmp(z, "file")==0 ){
  118002. return 1;
  118003. }else if( sqlite3StrICmp(z, "memory")==0 ){
  118004. return 2;
  118005. }else{
  118006. return 0;
  118007. }
  118008. }
  118009. #endif /* SQLITE_PAGER_PRAGMAS */
  118010. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  118011. /*
  118012. ** Invalidate temp storage, either when the temp storage is changed
  118013. ** from default, or when 'file' and the temp_store_directory has changed
  118014. */
  118015. static int invalidateTempStorage(Parse *pParse){
  118016. sqlite3 *db = pParse->db;
  118017. if( db->aDb[1].pBt!=0 ){
  118018. if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){
  118019. sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
  118020. "from within a transaction");
  118021. return SQLITE_ERROR;
  118022. }
  118023. sqlite3BtreeClose(db->aDb[1].pBt);
  118024. db->aDb[1].pBt = 0;
  118025. sqlite3ResetAllSchemasOfConnection(db);
  118026. }
  118027. return SQLITE_OK;
  118028. }
  118029. #endif /* SQLITE_PAGER_PRAGMAS */
  118030. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  118031. /*
  118032. ** If the TEMP database is open, close it and mark the database schema
  118033. ** as needing reloading. This must be done when using the SQLITE_TEMP_STORE
  118034. ** or DEFAULT_TEMP_STORE pragmas.
  118035. */
  118036. static int changeTempStorage(Parse *pParse, const char *zStorageType){
  118037. int ts = getTempStore(zStorageType);
  118038. sqlite3 *db = pParse->db;
  118039. if( db->temp_store==ts ) return SQLITE_OK;
  118040. if( invalidateTempStorage( pParse ) != SQLITE_OK ){
  118041. return SQLITE_ERROR;
  118042. }
  118043. db->temp_store = (u8)ts;
  118044. return SQLITE_OK;
  118045. }
  118046. #endif /* SQLITE_PAGER_PRAGMAS */
  118047. /*
  118048. ** Set result column names for a pragma.
  118049. */
  118050. static void setPragmaResultColumnNames(
  118051. Vdbe *v, /* The query under construction */
  118052. const PragmaName *pPragma /* The pragma */
  118053. ){
  118054. u8 n = pPragma->nPragCName;
  118055. sqlite3VdbeSetNumCols(v, n==0 ? 1 : n);
  118056. if( n==0 ){
  118057. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, pPragma->zName, SQLITE_STATIC);
  118058. }else{
  118059. int i, j;
  118060. for(i=0, j=pPragma->iPragCName; i<n; i++, j++){
  118061. sqlite3VdbeSetColName(v, i, COLNAME_NAME, pragCName[j], SQLITE_STATIC);
  118062. }
  118063. }
  118064. }
  118065. /*
  118066. ** Generate code to return a single integer value.
  118067. */
  118068. static void returnSingleInt(Vdbe *v, i64 value){
  118069. sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, 1, 0, (const u8*)&value, P4_INT64);
  118070. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  118071. }
  118072. /*
  118073. ** Generate code to return a single text value.
  118074. */
  118075. static void returnSingleText(
  118076. Vdbe *v, /* Prepared statement under construction */
  118077. const char *zValue /* Value to be returned */
  118078. ){
  118079. if( zValue ){
  118080. sqlite3VdbeLoadString(v, 1, (const char*)zValue);
  118081. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  118082. }
  118083. }
  118084. /*
  118085. ** Set the safety_level and pager flags for pager iDb. Or if iDb<0
  118086. ** set these values for all pagers.
  118087. */
  118088. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  118089. static void setAllPagerFlags(sqlite3 *db){
  118090. if( db->autoCommit ){
  118091. Db *pDb = db->aDb;
  118092. int n = db->nDb;
  118093. assert( SQLITE_FullFSync==PAGER_FULLFSYNC );
  118094. assert( SQLITE_CkptFullFSync==PAGER_CKPT_FULLFSYNC );
  118095. assert( SQLITE_CacheSpill==PAGER_CACHESPILL );
  118096. assert( (PAGER_FULLFSYNC | PAGER_CKPT_FULLFSYNC | PAGER_CACHESPILL)
  118097. == PAGER_FLAGS_MASK );
  118098. assert( (pDb->safety_level & PAGER_SYNCHRONOUS_MASK)==pDb->safety_level );
  118099. while( (n--) > 0 ){
  118100. if( pDb->pBt ){
  118101. sqlite3BtreeSetPagerFlags(pDb->pBt,
  118102. pDb->safety_level | (db->flags & PAGER_FLAGS_MASK) );
  118103. }
  118104. pDb++;
  118105. }
  118106. }
  118107. }
  118108. #else
  118109. # define setAllPagerFlags(X) /* no-op */
  118110. #endif
  118111. /*
  118112. ** Return a human-readable name for a constraint resolution action.
  118113. */
  118114. #ifndef SQLITE_OMIT_FOREIGN_KEY
  118115. static const char *actionName(u8 action){
  118116. const char *zName;
  118117. switch( action ){
  118118. case OE_SetNull: zName = "SET NULL"; break;
  118119. case OE_SetDflt: zName = "SET DEFAULT"; break;
  118120. case OE_Cascade: zName = "CASCADE"; break;
  118121. case OE_Restrict: zName = "RESTRICT"; break;
  118122. default: zName = "NO ACTION";
  118123. assert( action==OE_None ); break;
  118124. }
  118125. return zName;
  118126. }
  118127. #endif
  118128. /*
  118129. ** Parameter eMode must be one of the PAGER_JOURNALMODE_XXX constants
  118130. ** defined in pager.h. This function returns the associated lowercase
  118131. ** journal-mode name.
  118132. */
  118133. SQLITE_PRIVATE const char *sqlite3JournalModename(int eMode){
  118134. static char * const azModeName[] = {
  118135. "delete", "persist", "off", "truncate", "memory"
  118136. #ifndef SQLITE_OMIT_WAL
  118137. , "wal"
  118138. #endif
  118139. };
  118140. assert( PAGER_JOURNALMODE_DELETE==0 );
  118141. assert( PAGER_JOURNALMODE_PERSIST==1 );
  118142. assert( PAGER_JOURNALMODE_OFF==2 );
  118143. assert( PAGER_JOURNALMODE_TRUNCATE==3 );
  118144. assert( PAGER_JOURNALMODE_MEMORY==4 );
  118145. assert( PAGER_JOURNALMODE_WAL==5 );
  118146. assert( eMode>=0 && eMode<=ArraySize(azModeName) );
  118147. if( eMode==ArraySize(azModeName) ) return 0;
  118148. return azModeName[eMode];
  118149. }
  118150. /*
  118151. ** Locate a pragma in the aPragmaName[] array.
  118152. */
  118153. static const PragmaName *pragmaLocate(const char *zName){
  118154. int upr, lwr, mid = 0, rc;
  118155. lwr = 0;
  118156. upr = ArraySize(aPragmaName)-1;
  118157. while( lwr<=upr ){
  118158. mid = (lwr+upr)/2;
  118159. rc = sqlite3_stricmp(zName, aPragmaName[mid].zName);
  118160. if( rc==0 ) break;
  118161. if( rc<0 ){
  118162. upr = mid - 1;
  118163. }else{
  118164. lwr = mid + 1;
  118165. }
  118166. }
  118167. return lwr>upr ? 0 : &aPragmaName[mid];
  118168. }
  118169. /*
  118170. ** Create zero or more entries in the output for the SQL functions
  118171. ** defined by FuncDef p.
  118172. */
  118173. static void pragmaFunclistLine(
  118174. Vdbe *v, /* The prepared statement being created */
  118175. FuncDef *p, /* A particular function definition */
  118176. int isBuiltin, /* True if this is a built-in function */
  118177. int showInternFuncs /* True if showing internal functions */
  118178. ){
  118179. for(; p; p=p->pNext){
  118180. const char *zType;
  118181. static const u32 mask =
  118182. SQLITE_DETERMINISTIC |
  118183. SQLITE_DIRECTONLY |
  118184. SQLITE_SUBTYPE |
  118185. SQLITE_INNOCUOUS |
  118186. SQLITE_FUNC_INTERNAL
  118187. ;
  118188. static const char *azEnc[] = { 0, "utf8", "utf16le", "utf16be" };
  118189. assert( SQLITE_FUNC_ENCMASK==0x3 );
  118190. assert( strcmp(azEnc[SQLITE_UTF8],"utf8")==0 );
  118191. assert( strcmp(azEnc[SQLITE_UTF16LE],"utf16le")==0 );
  118192. assert( strcmp(azEnc[SQLITE_UTF16BE],"utf16be")==0 );
  118193. if( p->xSFunc==0 ) continue;
  118194. if( (p->funcFlags & SQLITE_FUNC_INTERNAL)!=0
  118195. && showInternFuncs==0
  118196. ){
  118197. continue;
  118198. }
  118199. if( p->xValue!=0 ){
  118200. zType = "w";
  118201. }else if( p->xFinalize!=0 ){
  118202. zType = "a";
  118203. }else{
  118204. zType = "s";
  118205. }
  118206. sqlite3VdbeMultiLoad(v, 1, "sissii",
  118207. p->zName, isBuiltin,
  118208. zType, azEnc[p->funcFlags&SQLITE_FUNC_ENCMASK],
  118209. p->nArg,
  118210. (p->funcFlags & mask) ^ SQLITE_INNOCUOUS
  118211. );
  118212. }
  118213. }
  118214. /*
  118215. ** Helper subroutine for PRAGMA integrity_check:
  118216. **
  118217. ** Generate code to output a single-column result row with a value of the
  118218. ** string held in register 3. Decrement the result count in register 1
  118219. ** and halt if the maximum number of result rows have been issued.
  118220. */
  118221. static int integrityCheckResultRow(Vdbe *v){
  118222. int addr;
  118223. sqlite3VdbeAddOp2(v, OP_ResultRow, 3, 1);
  118224. addr = sqlite3VdbeAddOp3(v, OP_IfPos, 1, sqlite3VdbeCurrentAddr(v)+2, 1);
  118225. VdbeCoverage(v);
  118226. sqlite3VdbeAddOp0(v, OP_Halt);
  118227. return addr;
  118228. }
  118229. /*
  118230. ** Process a pragma statement.
  118231. **
  118232. ** Pragmas are of this form:
  118233. **
  118234. ** PRAGMA [schema.]id [= value]
  118235. **
  118236. ** The identifier might also be a string. The value is a string, and
  118237. ** identifier, or a number. If minusFlag is true, then the value is
  118238. ** a number that was preceded by a minus sign.
  118239. **
  118240. ** If the left side is "database.id" then pId1 is the database name
  118241. ** and pId2 is the id. If the left side is just "id" then pId1 is the
  118242. ** id and pId2 is any empty string.
  118243. */
  118244. SQLITE_PRIVATE void sqlite3Pragma(
  118245. Parse *pParse,
  118246. Token *pId1, /* First part of [schema.]id field */
  118247. Token *pId2, /* Second part of [schema.]id field, or NULL */
  118248. Token *pValue, /* Token for <value>, or NULL */
  118249. int minusFlag /* True if a '-' sign preceded <value> */
  118250. ){
  118251. char *zLeft = 0; /* Nul-terminated UTF-8 string <id> */
  118252. char *zRight = 0; /* Nul-terminated UTF-8 string <value>, or NULL */
  118253. const char *zDb = 0; /* The database name */
  118254. Token *pId; /* Pointer to <id> token */
  118255. char *aFcntl[4]; /* Argument to SQLITE_FCNTL_PRAGMA */
  118256. int iDb; /* Database index for <database> */
  118257. int rc; /* return value form SQLITE_FCNTL_PRAGMA */
  118258. sqlite3 *db = pParse->db; /* The database connection */
  118259. Db *pDb; /* The specific database being pragmaed */
  118260. Vdbe *v = sqlite3GetVdbe(pParse); /* Prepared statement */
  118261. const PragmaName *pPragma; /* The pragma */
  118262. if( v==0 ) return;
  118263. sqlite3VdbeRunOnlyOnce(v);
  118264. pParse->nMem = 2;
  118265. /* Interpret the [schema.] part of the pragma statement. iDb is the
  118266. ** index of the database this pragma is being applied to in db.aDb[]. */
  118267. iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
  118268. if( iDb<0 ) return;
  118269. pDb = &db->aDb[iDb];
  118270. /* If the temp database has been explicitly named as part of the
  118271. ** pragma, make sure it is open.
  118272. */
  118273. if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
  118274. return;
  118275. }
  118276. zLeft = sqlite3NameFromToken(db, pId);
  118277. if( !zLeft ) return;
  118278. if( minusFlag ){
  118279. zRight = sqlite3MPrintf(db, "-%T", pValue);
  118280. }else{
  118281. zRight = sqlite3NameFromToken(db, pValue);
  118282. }
  118283. assert( pId2 );
  118284. zDb = pId2->n>0 ? pDb->zDbSName : 0;
  118285. if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
  118286. goto pragma_out;
  118287. }
  118288. /* Send an SQLITE_FCNTL_PRAGMA file-control to the underlying VFS
  118289. ** connection. If it returns SQLITE_OK, then assume that the VFS
  118290. ** handled the pragma and generate a no-op prepared statement.
  118291. **
  118292. ** IMPLEMENTATION-OF: R-12238-55120 Whenever a PRAGMA statement is parsed,
  118293. ** an SQLITE_FCNTL_PRAGMA file control is sent to the open sqlite3_file
  118294. ** object corresponding to the database file to which the pragma
  118295. ** statement refers.
  118296. **
  118297. ** IMPLEMENTATION-OF: R-29875-31678 The argument to the SQLITE_FCNTL_PRAGMA
  118298. ** file control is an array of pointers to strings (char**) in which the
  118299. ** second element of the array is the name of the pragma and the third
  118300. ** element is the argument to the pragma or NULL if the pragma has no
  118301. ** argument.
  118302. */
  118303. aFcntl[0] = 0;
  118304. aFcntl[1] = zLeft;
  118305. aFcntl[2] = zRight;
  118306. aFcntl[3] = 0;
  118307. db->busyHandler.nBusy = 0;
  118308. rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_PRAGMA, (void*)aFcntl);
  118309. if( rc==SQLITE_OK ){
  118310. sqlite3VdbeSetNumCols(v, 1);
  118311. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, aFcntl[0], SQLITE_TRANSIENT);
  118312. returnSingleText(v, aFcntl[0]);
  118313. sqlite3_free(aFcntl[0]);
  118314. goto pragma_out;
  118315. }
  118316. if( rc!=SQLITE_NOTFOUND ){
  118317. if( aFcntl[0] ){
  118318. sqlite3ErrorMsg(pParse, "%s", aFcntl[0]);
  118319. sqlite3_free(aFcntl[0]);
  118320. }
  118321. pParse->nErr++;
  118322. pParse->rc = rc;
  118323. goto pragma_out;
  118324. }
  118325. /* Locate the pragma in the lookup table */
  118326. pPragma = pragmaLocate(zLeft);
  118327. if( pPragma==0 ) goto pragma_out;
  118328. /* Make sure the database schema is loaded if the pragma requires that */
  118329. if( (pPragma->mPragFlg & PragFlg_NeedSchema)!=0 ){
  118330. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  118331. }
  118332. /* Register the result column names for pragmas that return results */
  118333. if( (pPragma->mPragFlg & PragFlg_NoColumns)==0
  118334. && ((pPragma->mPragFlg & PragFlg_NoColumns1)==0 || zRight==0)
  118335. ){
  118336. setPragmaResultColumnNames(v, pPragma);
  118337. }
  118338. /* Jump to the appropriate pragma handler */
  118339. switch( pPragma->ePragTyp ){
  118340. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
  118341. /*
  118342. ** PRAGMA [schema.]default_cache_size
  118343. ** PRAGMA [schema.]default_cache_size=N
  118344. **
  118345. ** The first form reports the current persistent setting for the
  118346. ** page cache size. The value returned is the maximum number of
  118347. ** pages in the page cache. The second form sets both the current
  118348. ** page cache size value and the persistent page cache size value
  118349. ** stored in the database file.
  118350. **
  118351. ** Older versions of SQLite would set the default cache size to a
  118352. ** negative number to indicate synchronous=OFF. These days, synchronous
  118353. ** is always on by default regardless of the sign of the default cache
  118354. ** size. But continue to take the absolute value of the default cache
  118355. ** size of historical compatibility.
  118356. */
  118357. case PragTyp_DEFAULT_CACHE_SIZE: {
  118358. static const int iLn = VDBE_OFFSET_LINENO(2);
  118359. static const VdbeOpList getCacheSize[] = {
  118360. { OP_Transaction, 0, 0, 0}, /* 0 */
  118361. { OP_ReadCookie, 0, 1, BTREE_DEFAULT_CACHE_SIZE}, /* 1 */
  118362. { OP_IfPos, 1, 8, 0},
  118363. { OP_Integer, 0, 2, 0},
  118364. { OP_Subtract, 1, 2, 1},
  118365. { OP_IfPos, 1, 8, 0},
  118366. { OP_Integer, 0, 1, 0}, /* 6 */
  118367. { OP_Noop, 0, 0, 0},
  118368. { OP_ResultRow, 1, 1, 0},
  118369. };
  118370. VdbeOp *aOp;
  118371. sqlite3VdbeUsesBtree(v, iDb);
  118372. if( !zRight ){
  118373. pParse->nMem += 2;
  118374. sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(getCacheSize));
  118375. aOp = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize, iLn);
  118376. if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
  118377. aOp[0].p1 = iDb;
  118378. aOp[1].p1 = iDb;
  118379. aOp[6].p1 = SQLITE_DEFAULT_CACHE_SIZE;
  118380. }else{
  118381. int size = sqlite3AbsInt32(sqlite3Atoi(zRight));
  118382. sqlite3BeginWriteOperation(pParse, 0, iDb);
  118383. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, size);
  118384. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  118385. pDb->pSchema->cache_size = size;
  118386. sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
  118387. }
  118388. break;
  118389. }
  118390. #endif /* !SQLITE_OMIT_PAGER_PRAGMAS && !SQLITE_OMIT_DEPRECATED */
  118391. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  118392. /*
  118393. ** PRAGMA [schema.]page_size
  118394. ** PRAGMA [schema.]page_size=N
  118395. **
  118396. ** The first form reports the current setting for the
  118397. ** database page size in bytes. The second form sets the
  118398. ** database page size value. The value can only be set if
  118399. ** the database has not yet been created.
  118400. */
  118401. case PragTyp_PAGE_SIZE: {
  118402. Btree *pBt = pDb->pBt;
  118403. assert( pBt!=0 );
  118404. if( !zRight ){
  118405. int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;
  118406. returnSingleInt(v, size);
  118407. }else{
  118408. /* Malloc may fail when setting the page-size, as there is an internal
  118409. ** buffer that the pager module resizes using sqlite3_realloc().
  118410. */
  118411. db->nextPagesize = sqlite3Atoi(zRight);
  118412. if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize,0,0) ){
  118413. sqlite3OomFault(db);
  118414. }
  118415. }
  118416. break;
  118417. }
  118418. /*
  118419. ** PRAGMA [schema.]secure_delete
  118420. ** PRAGMA [schema.]secure_delete=ON/OFF/FAST
  118421. **
  118422. ** The first form reports the current setting for the
  118423. ** secure_delete flag. The second form changes the secure_delete
  118424. ** flag setting and reports the new value.
  118425. */
  118426. case PragTyp_SECURE_DELETE: {
  118427. Btree *pBt = pDb->pBt;
  118428. int b = -1;
  118429. assert( pBt!=0 );
  118430. if( zRight ){
  118431. if( sqlite3_stricmp(zRight, "fast")==0 ){
  118432. b = 2;
  118433. }else{
  118434. b = sqlite3GetBoolean(zRight, 0);
  118435. }
  118436. }
  118437. if( pId2->n==0 && b>=0 ){
  118438. int ii;
  118439. for(ii=0; ii<db->nDb; ii++){
  118440. sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b);
  118441. }
  118442. }
  118443. b = sqlite3BtreeSecureDelete(pBt, b);
  118444. returnSingleInt(v, b);
  118445. break;
  118446. }
  118447. /*
  118448. ** PRAGMA [schema.]max_page_count
  118449. ** PRAGMA [schema.]max_page_count=N
  118450. **
  118451. ** The first form reports the current setting for the
  118452. ** maximum number of pages in the database file. The
  118453. ** second form attempts to change this setting. Both
  118454. ** forms return the current setting.
  118455. **
  118456. ** The absolute value of N is used. This is undocumented and might
  118457. ** change. The only purpose is to provide an easy way to test
  118458. ** the sqlite3AbsInt32() function.
  118459. **
  118460. ** PRAGMA [schema.]page_count
  118461. **
  118462. ** Return the number of pages in the specified database.
  118463. */
  118464. case PragTyp_PAGE_COUNT: {
  118465. int iReg;
  118466. sqlite3CodeVerifySchema(pParse, iDb);
  118467. iReg = ++pParse->nMem;
  118468. if( sqlite3Tolower(zLeft[0])=='p' ){
  118469. sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
  118470. }else{
  118471. sqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg,
  118472. sqlite3AbsInt32(sqlite3Atoi(zRight)));
  118473. }
  118474. sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
  118475. break;
  118476. }
  118477. /*
  118478. ** PRAGMA [schema.]locking_mode
  118479. ** PRAGMA [schema.]locking_mode = (normal|exclusive)
  118480. */
  118481. case PragTyp_LOCKING_MODE: {
  118482. const char *zRet = "normal";
  118483. int eMode = getLockingMode(zRight);
  118484. if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
  118485. /* Simple "PRAGMA locking_mode;" statement. This is a query for
  118486. ** the current default locking mode (which may be different to
  118487. ** the locking-mode of the main database).
  118488. */
  118489. eMode = db->dfltLockMode;
  118490. }else{
  118491. Pager *pPager;
  118492. if( pId2->n==0 ){
  118493. /* This indicates that no database name was specified as part
  118494. ** of the PRAGMA command. In this case the locking-mode must be
  118495. ** set on all attached databases, as well as the main db file.
  118496. **
  118497. ** Also, the sqlite3.dfltLockMode variable is set so that
  118498. ** any subsequently attached databases also use the specified
  118499. ** locking mode.
  118500. */
  118501. int ii;
  118502. assert(pDb==&db->aDb[0]);
  118503. for(ii=2; ii<db->nDb; ii++){
  118504. pPager = sqlite3BtreePager(db->aDb[ii].pBt);
  118505. sqlite3PagerLockingMode(pPager, eMode);
  118506. }
  118507. db->dfltLockMode = (u8)eMode;
  118508. }
  118509. pPager = sqlite3BtreePager(pDb->pBt);
  118510. eMode = sqlite3PagerLockingMode(pPager, eMode);
  118511. }
  118512. assert( eMode==PAGER_LOCKINGMODE_NORMAL
  118513. || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
  118514. if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
  118515. zRet = "exclusive";
  118516. }
  118517. returnSingleText(v, zRet);
  118518. break;
  118519. }
  118520. /*
  118521. ** PRAGMA [schema.]journal_mode
  118522. ** PRAGMA [schema.]journal_mode =
  118523. ** (delete|persist|off|truncate|memory|wal|off)
  118524. */
  118525. case PragTyp_JOURNAL_MODE: {
  118526. int eMode; /* One of the PAGER_JOURNALMODE_XXX symbols */
  118527. int ii; /* Loop counter */
  118528. if( zRight==0 ){
  118529. /* If there is no "=MODE" part of the pragma, do a query for the
  118530. ** current mode */
  118531. eMode = PAGER_JOURNALMODE_QUERY;
  118532. }else{
  118533. const char *zMode;
  118534. int n = sqlite3Strlen30(zRight);
  118535. for(eMode=0; (zMode = sqlite3JournalModename(eMode))!=0; eMode++){
  118536. if( sqlite3StrNICmp(zRight, zMode, n)==0 ) break;
  118537. }
  118538. if( !zMode ){
  118539. /* If the "=MODE" part does not match any known journal mode,
  118540. ** then do a query */
  118541. eMode = PAGER_JOURNALMODE_QUERY;
  118542. }
  118543. if( eMode==PAGER_JOURNALMODE_OFF && (db->flags & SQLITE_Defensive)!=0 ){
  118544. /* Do not allow journal-mode "OFF" in defensive since the database
  118545. ** can become corrupted using ordinary SQL when the journal is off */
  118546. eMode = PAGER_JOURNALMODE_QUERY;
  118547. }
  118548. }
  118549. if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){
  118550. /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */
  118551. iDb = 0;
  118552. pId2->n = 1;
  118553. }
  118554. for(ii=db->nDb-1; ii>=0; ii--){
  118555. if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
  118556. sqlite3VdbeUsesBtree(v, ii);
  118557. sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode);
  118558. }
  118559. }
  118560. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  118561. break;
  118562. }
  118563. /*
  118564. ** PRAGMA [schema.]journal_size_limit
  118565. ** PRAGMA [schema.]journal_size_limit=N
  118566. **
  118567. ** Get or set the size limit on rollback journal files.
  118568. */
  118569. case PragTyp_JOURNAL_SIZE_LIMIT: {
  118570. Pager *pPager = sqlite3BtreePager(pDb->pBt);
  118571. i64 iLimit = -2;
  118572. if( zRight ){
  118573. sqlite3DecOrHexToI64(zRight, &iLimit);
  118574. if( iLimit<-1 ) iLimit = -1;
  118575. }
  118576. iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
  118577. returnSingleInt(v, iLimit);
  118578. break;
  118579. }
  118580. #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
  118581. /*
  118582. ** PRAGMA [schema.]auto_vacuum
  118583. ** PRAGMA [schema.]auto_vacuum=N
  118584. **
  118585. ** Get or set the value of the database 'auto-vacuum' parameter.
  118586. ** The value is one of: 0 NONE 1 FULL 2 INCREMENTAL
  118587. */
  118588. #ifndef SQLITE_OMIT_AUTOVACUUM
  118589. case PragTyp_AUTO_VACUUM: {
  118590. Btree *pBt = pDb->pBt;
  118591. assert( pBt!=0 );
  118592. if( !zRight ){
  118593. returnSingleInt(v, sqlite3BtreeGetAutoVacuum(pBt));
  118594. }else{
  118595. int eAuto = getAutoVacuum(zRight);
  118596. assert( eAuto>=0 && eAuto<=2 );
  118597. db->nextAutovac = (u8)eAuto;
  118598. /* Call SetAutoVacuum() to set initialize the internal auto and
  118599. ** incr-vacuum flags. This is required in case this connection
  118600. ** creates the database file. It is important that it is created
  118601. ** as an auto-vacuum capable db.
  118602. */
  118603. rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
  118604. if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
  118605. /* When setting the auto_vacuum mode to either "full" or
  118606. ** "incremental", write the value of meta[6] in the database
  118607. ** file. Before writing to meta[6], check that meta[3] indicates
  118608. ** that this really is an auto-vacuum capable database.
  118609. */
  118610. static const int iLn = VDBE_OFFSET_LINENO(2);
  118611. static const VdbeOpList setMeta6[] = {
  118612. { OP_Transaction, 0, 1, 0}, /* 0 */
  118613. { OP_ReadCookie, 0, 1, BTREE_LARGEST_ROOT_PAGE},
  118614. { OP_If, 1, 0, 0}, /* 2 */
  118615. { OP_Halt, SQLITE_OK, OE_Abort, 0}, /* 3 */
  118616. { OP_SetCookie, 0, BTREE_INCR_VACUUM, 0}, /* 4 */
  118617. };
  118618. VdbeOp *aOp;
  118619. int iAddr = sqlite3VdbeCurrentAddr(v);
  118620. sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(setMeta6));
  118621. aOp = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6, iLn);
  118622. if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
  118623. aOp[0].p1 = iDb;
  118624. aOp[1].p1 = iDb;
  118625. aOp[2].p2 = iAddr+4;
  118626. aOp[4].p1 = iDb;
  118627. aOp[4].p3 = eAuto - 1;
  118628. sqlite3VdbeUsesBtree(v, iDb);
  118629. }
  118630. }
  118631. break;
  118632. }
  118633. #endif
  118634. /*
  118635. ** PRAGMA [schema.]incremental_vacuum(N)
  118636. **
  118637. ** Do N steps of incremental vacuuming on a database.
  118638. */
  118639. #ifndef SQLITE_OMIT_AUTOVACUUM
  118640. case PragTyp_INCREMENTAL_VACUUM: {
  118641. int iLimit, addr;
  118642. if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
  118643. iLimit = 0x7fffffff;
  118644. }
  118645. sqlite3BeginWriteOperation(pParse, 0, iDb);
  118646. sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
  118647. addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb); VdbeCoverage(v);
  118648. sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
  118649. sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
  118650. sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr); VdbeCoverage(v);
  118651. sqlite3VdbeJumpHere(v, addr);
  118652. break;
  118653. }
  118654. #endif
  118655. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  118656. /*
  118657. ** PRAGMA [schema.]cache_size
  118658. ** PRAGMA [schema.]cache_size=N
  118659. **
  118660. ** The first form reports the current local setting for the
  118661. ** page cache size. The second form sets the local
  118662. ** page cache size value. If N is positive then that is the
  118663. ** number of pages in the cache. If N is negative, then the
  118664. ** number of pages is adjusted so that the cache uses -N kibibytes
  118665. ** of memory.
  118666. */
  118667. case PragTyp_CACHE_SIZE: {
  118668. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  118669. if( !zRight ){
  118670. returnSingleInt(v, pDb->pSchema->cache_size);
  118671. }else{
  118672. int size = sqlite3Atoi(zRight);
  118673. pDb->pSchema->cache_size = size;
  118674. sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
  118675. }
  118676. break;
  118677. }
  118678. /*
  118679. ** PRAGMA [schema.]cache_spill
  118680. ** PRAGMA cache_spill=BOOLEAN
  118681. ** PRAGMA [schema.]cache_spill=N
  118682. **
  118683. ** The first form reports the current local setting for the
  118684. ** page cache spill size. The second form turns cache spill on
  118685. ** or off. When turnning cache spill on, the size is set to the
  118686. ** current cache_size. The third form sets a spill size that
  118687. ** may be different form the cache size.
  118688. ** If N is positive then that is the
  118689. ** number of pages in the cache. If N is negative, then the
  118690. ** number of pages is adjusted so that the cache uses -N kibibytes
  118691. ** of memory.
  118692. **
  118693. ** If the number of cache_spill pages is less then the number of
  118694. ** cache_size pages, no spilling occurs until the page count exceeds
  118695. ** the number of cache_size pages.
  118696. **
  118697. ** The cache_spill=BOOLEAN setting applies to all attached schemas,
  118698. ** not just the schema specified.
  118699. */
  118700. case PragTyp_CACHE_SPILL: {
  118701. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  118702. if( !zRight ){
  118703. returnSingleInt(v,
  118704. (db->flags & SQLITE_CacheSpill)==0 ? 0 :
  118705. sqlite3BtreeSetSpillSize(pDb->pBt,0));
  118706. }else{
  118707. int size = 1;
  118708. if( sqlite3GetInt32(zRight, &size) ){
  118709. sqlite3BtreeSetSpillSize(pDb->pBt, size);
  118710. }
  118711. if( sqlite3GetBoolean(zRight, size!=0) ){
  118712. db->flags |= SQLITE_CacheSpill;
  118713. }else{
  118714. db->flags &= ~(u64)SQLITE_CacheSpill;
  118715. }
  118716. setAllPagerFlags(db);
  118717. }
  118718. break;
  118719. }
  118720. /*
  118721. ** PRAGMA [schema.]mmap_size(N)
  118722. **
  118723. ** Used to set mapping size limit. The mapping size limit is
  118724. ** used to limit the aggregate size of all memory mapped regions of the
  118725. ** database file. If this parameter is set to zero, then memory mapping
  118726. ** is not used at all. If N is negative, then the default memory map
  118727. ** limit determined by sqlite3_config(SQLITE_CONFIG_MMAP_SIZE) is set.
  118728. ** The parameter N is measured in bytes.
  118729. **
  118730. ** This value is advisory. The underlying VFS is free to memory map
  118731. ** as little or as much as it wants. Except, if N is set to 0 then the
  118732. ** upper layers will never invoke the xFetch interfaces to the VFS.
  118733. */
  118734. case PragTyp_MMAP_SIZE: {
  118735. sqlite3_int64 sz;
  118736. #if SQLITE_MAX_MMAP_SIZE>0
  118737. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  118738. if( zRight ){
  118739. int ii;
  118740. sqlite3DecOrHexToI64(zRight, &sz);
  118741. if( sz<0 ) sz = sqlite3GlobalConfig.szMmap;
  118742. if( pId2->n==0 ) db->szMmap = sz;
  118743. for(ii=db->nDb-1; ii>=0; ii--){
  118744. if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
  118745. sqlite3BtreeSetMmapLimit(db->aDb[ii].pBt, sz);
  118746. }
  118747. }
  118748. }
  118749. sz = -1;
  118750. rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_MMAP_SIZE, &sz);
  118751. #else
  118752. sz = 0;
  118753. rc = SQLITE_OK;
  118754. #endif
  118755. if( rc==SQLITE_OK ){
  118756. returnSingleInt(v, sz);
  118757. }else if( rc!=SQLITE_NOTFOUND ){
  118758. pParse->nErr++;
  118759. pParse->rc = rc;
  118760. }
  118761. break;
  118762. }
  118763. /*
  118764. ** PRAGMA temp_store
  118765. ** PRAGMA temp_store = "default"|"memory"|"file"
  118766. **
  118767. ** Return or set the local value of the temp_store flag. Changing
  118768. ** the local value does not make changes to the disk file and the default
  118769. ** value will be restored the next time the database is opened.
  118770. **
  118771. ** Note that it is possible for the library compile-time options to
  118772. ** override this setting
  118773. */
  118774. case PragTyp_TEMP_STORE: {
  118775. if( !zRight ){
  118776. returnSingleInt(v, db->temp_store);
  118777. }else{
  118778. changeTempStorage(pParse, zRight);
  118779. }
  118780. break;
  118781. }
  118782. /*
  118783. ** PRAGMA temp_store_directory
  118784. ** PRAGMA temp_store_directory = ""|"directory_name"
  118785. **
  118786. ** Return or set the local value of the temp_store_directory flag. Changing
  118787. ** the value sets a specific directory to be used for temporary files.
  118788. ** Setting to a null string reverts to the default temporary directory search.
  118789. ** If temporary directory is changed, then invalidateTempStorage.
  118790. **
  118791. */
  118792. case PragTyp_TEMP_STORE_DIRECTORY: {
  118793. if( !zRight ){
  118794. returnSingleText(v, sqlite3_temp_directory);
  118795. }else{
  118796. #ifndef SQLITE_OMIT_WSD
  118797. if( zRight[0] ){
  118798. int res;
  118799. rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
  118800. if( rc!=SQLITE_OK || res==0 ){
  118801. sqlite3ErrorMsg(pParse, "not a writable directory");
  118802. goto pragma_out;
  118803. }
  118804. }
  118805. if( SQLITE_TEMP_STORE==0
  118806. || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
  118807. || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
  118808. ){
  118809. invalidateTempStorage(pParse);
  118810. }
  118811. sqlite3_free(sqlite3_temp_directory);
  118812. if( zRight[0] ){
  118813. sqlite3_temp_directory = sqlite3_mprintf("%s", zRight);
  118814. }else{
  118815. sqlite3_temp_directory = 0;
  118816. }
  118817. #endif /* SQLITE_OMIT_WSD */
  118818. }
  118819. break;
  118820. }
  118821. #if SQLITE_OS_WIN
  118822. /*
  118823. ** PRAGMA data_store_directory
  118824. ** PRAGMA data_store_directory = ""|"directory_name"
  118825. **
  118826. ** Return or set the local value of the data_store_directory flag. Changing
  118827. ** the value sets a specific directory to be used for database files that
  118828. ** were specified with a relative pathname. Setting to a null string reverts
  118829. ** to the default database directory, which for database files specified with
  118830. ** a relative path will probably be based on the current directory for the
  118831. ** process. Database file specified with an absolute path are not impacted
  118832. ** by this setting, regardless of its value.
  118833. **
  118834. */
  118835. case PragTyp_DATA_STORE_DIRECTORY: {
  118836. if( !zRight ){
  118837. returnSingleText(v, sqlite3_data_directory);
  118838. }else{
  118839. #ifndef SQLITE_OMIT_WSD
  118840. if( zRight[0] ){
  118841. int res;
  118842. rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
  118843. if( rc!=SQLITE_OK || res==0 ){
  118844. sqlite3ErrorMsg(pParse, "not a writable directory");
  118845. goto pragma_out;
  118846. }
  118847. }
  118848. sqlite3_free(sqlite3_data_directory);
  118849. if( zRight[0] ){
  118850. sqlite3_data_directory = sqlite3_mprintf("%s", zRight);
  118851. }else{
  118852. sqlite3_data_directory = 0;
  118853. }
  118854. #endif /* SQLITE_OMIT_WSD */
  118855. }
  118856. break;
  118857. }
  118858. #endif
  118859. #if SQLITE_ENABLE_LOCKING_STYLE
  118860. /*
  118861. ** PRAGMA [schema.]lock_proxy_file
  118862. ** PRAGMA [schema.]lock_proxy_file = ":auto:"|"lock_file_path"
  118863. **
  118864. ** Return or set the value of the lock_proxy_file flag. Changing
  118865. ** the value sets a specific file to be used for database access locks.
  118866. **
  118867. */
  118868. case PragTyp_LOCK_PROXY_FILE: {
  118869. if( !zRight ){
  118870. Pager *pPager = sqlite3BtreePager(pDb->pBt);
  118871. char *proxy_file_path = NULL;
  118872. sqlite3_file *pFile = sqlite3PagerFile(pPager);
  118873. sqlite3OsFileControlHint(pFile, SQLITE_GET_LOCKPROXYFILE,
  118874. &proxy_file_path);
  118875. returnSingleText(v, proxy_file_path);
  118876. }else{
  118877. Pager *pPager = sqlite3BtreePager(pDb->pBt);
  118878. sqlite3_file *pFile = sqlite3PagerFile(pPager);
  118879. int res;
  118880. if( zRight[0] ){
  118881. res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
  118882. zRight);
  118883. } else {
  118884. res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
  118885. NULL);
  118886. }
  118887. if( res!=SQLITE_OK ){
  118888. sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
  118889. goto pragma_out;
  118890. }
  118891. }
  118892. break;
  118893. }
  118894. #endif /* SQLITE_ENABLE_LOCKING_STYLE */
  118895. /*
  118896. ** PRAGMA [schema.]synchronous
  118897. ** PRAGMA [schema.]synchronous=OFF|ON|NORMAL|FULL|EXTRA
  118898. **
  118899. ** Return or set the local value of the synchronous flag. Changing
  118900. ** the local value does not make changes to the disk file and the
  118901. ** default value will be restored the next time the database is
  118902. ** opened.
  118903. */
  118904. case PragTyp_SYNCHRONOUS: {
  118905. if( !zRight ){
  118906. returnSingleInt(v, pDb->safety_level-1);
  118907. }else{
  118908. if( !db->autoCommit ){
  118909. sqlite3ErrorMsg(pParse,
  118910. "Safety level may not be changed inside a transaction");
  118911. }else if( iDb!=1 ){
  118912. int iLevel = (getSafetyLevel(zRight,0,1)+1) & PAGER_SYNCHRONOUS_MASK;
  118913. if( iLevel==0 ) iLevel = 1;
  118914. pDb->safety_level = iLevel;
  118915. pDb->bSyncSet = 1;
  118916. setAllPagerFlags(db);
  118917. }
  118918. }
  118919. break;
  118920. }
  118921. #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
  118922. #ifndef SQLITE_OMIT_FLAG_PRAGMAS
  118923. case PragTyp_FLAG: {
  118924. if( zRight==0 ){
  118925. setPragmaResultColumnNames(v, pPragma);
  118926. returnSingleInt(v, (db->flags & pPragma->iArg)!=0 );
  118927. }else{
  118928. u64 mask = pPragma->iArg; /* Mask of bits to set or clear. */
  118929. if( db->autoCommit==0 ){
  118930. /* Foreign key support may not be enabled or disabled while not
  118931. ** in auto-commit mode. */
  118932. mask &= ~(SQLITE_ForeignKeys);
  118933. }
  118934. #if SQLITE_USER_AUTHENTICATION
  118935. if( db->auth.authLevel==UAUTH_User ){
  118936. /* Do not allow non-admin users to modify the schema arbitrarily */
  118937. mask &= ~(SQLITE_WriteSchema);
  118938. }
  118939. #endif
  118940. if( sqlite3GetBoolean(zRight, 0) ){
  118941. db->flags |= mask;
  118942. }else{
  118943. db->flags &= ~mask;
  118944. if( mask==SQLITE_DeferFKs ) db->nDeferredImmCons = 0;
  118945. }
  118946. /* Many of the flag-pragmas modify the code generated by the SQL
  118947. ** compiler (eg. count_changes). So add an opcode to expire all
  118948. ** compiled SQL statements after modifying a pragma value.
  118949. */
  118950. sqlite3VdbeAddOp0(v, OP_Expire);
  118951. setAllPagerFlags(db);
  118952. }
  118953. break;
  118954. }
  118955. #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
  118956. #ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
  118957. /*
  118958. ** PRAGMA table_info(<table>)
  118959. **
  118960. ** Return a single row for each column of the named table. The columns of
  118961. ** the returned data set are:
  118962. **
  118963. ** cid: Column id (numbered from left to right, starting at 0)
  118964. ** name: Column name
  118965. ** type: Column declaration type.
  118966. ** notnull: True if 'NOT NULL' is part of column declaration
  118967. ** dflt_value: The default value for the column, if any.
  118968. ** pk: Non-zero for PK fields.
  118969. */
  118970. case PragTyp_TABLE_INFO: if( zRight ){
  118971. Table *pTab;
  118972. pTab = sqlite3LocateTable(pParse, LOCATE_NOERR, zRight, zDb);
  118973. if( pTab ){
  118974. int iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  118975. int i, k;
  118976. int nHidden = 0;
  118977. Column *pCol;
  118978. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  118979. pParse->nMem = 7;
  118980. sqlite3CodeVerifySchema(pParse, iTabDb);
  118981. sqlite3ViewGetColumnNames(pParse, pTab);
  118982. for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
  118983. int isHidden = 0;
  118984. if( pCol->colFlags & COLFLAG_NOINSERT ){
  118985. if( pPragma->iArg==0 ){
  118986. nHidden++;
  118987. continue;
  118988. }
  118989. if( pCol->colFlags & COLFLAG_VIRTUAL ){
  118990. isHidden = 2; /* GENERATED ALWAYS AS ... VIRTUAL */
  118991. }else if( pCol->colFlags & COLFLAG_STORED ){
  118992. isHidden = 3; /* GENERATED ALWAYS AS ... STORED */
  118993. }else{ assert( pCol->colFlags & COLFLAG_HIDDEN );
  118994. isHidden = 1; /* HIDDEN */
  118995. }
  118996. }
  118997. if( (pCol->colFlags & COLFLAG_PRIMKEY)==0 ){
  118998. k = 0;
  118999. }else if( pPk==0 ){
  119000. k = 1;
  119001. }else{
  119002. for(k=1; k<=pTab->nCol && pPk->aiColumn[k-1]!=i; k++){}
  119003. }
  119004. assert( pCol->pDflt==0 || pCol->pDflt->op==TK_SPAN || isHidden>=2 );
  119005. sqlite3VdbeMultiLoad(v, 1, pPragma->iArg ? "issisii" : "issisi",
  119006. i-nHidden,
  119007. pCol->zName,
  119008. sqlite3ColumnType(pCol,""),
  119009. pCol->notNull ? 1 : 0,
  119010. pCol->pDflt && isHidden<2 ? pCol->pDflt->u.zToken : 0,
  119011. k,
  119012. isHidden);
  119013. }
  119014. }
  119015. }
  119016. break;
  119017. #ifdef SQLITE_DEBUG
  119018. case PragTyp_STATS: {
  119019. Index *pIdx;
  119020. HashElem *i;
  119021. pParse->nMem = 5;
  119022. sqlite3CodeVerifySchema(pParse, iDb);
  119023. for(i=sqliteHashFirst(&pDb->pSchema->tblHash); i; i=sqliteHashNext(i)){
  119024. Table *pTab = sqliteHashData(i);
  119025. sqlite3VdbeMultiLoad(v, 1, "ssiii",
  119026. pTab->zName,
  119027. 0,
  119028. pTab->szTabRow,
  119029. pTab->nRowLogEst,
  119030. pTab->tabFlags);
  119031. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  119032. sqlite3VdbeMultiLoad(v, 2, "siiiX",
  119033. pIdx->zName,
  119034. pIdx->szIdxRow,
  119035. pIdx->aiRowLogEst[0],
  119036. pIdx->hasStat1);
  119037. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 5);
  119038. }
  119039. }
  119040. }
  119041. break;
  119042. #endif
  119043. case PragTyp_INDEX_INFO: if( zRight ){
  119044. Index *pIdx;
  119045. Table *pTab;
  119046. pIdx = sqlite3FindIndex(db, zRight, zDb);
  119047. if( pIdx==0 ){
  119048. /* If there is no index named zRight, check to see if there is a
  119049. ** WITHOUT ROWID table named zRight, and if there is, show the
  119050. ** structure of the PRIMARY KEY index for that table. */
  119051. pTab = sqlite3LocateTable(pParse, LOCATE_NOERR, zRight, zDb);
  119052. if( pTab && !HasRowid(pTab) ){
  119053. pIdx = sqlite3PrimaryKeyIndex(pTab);
  119054. }
  119055. }
  119056. if( pIdx ){
  119057. int iIdxDb = sqlite3SchemaToIndex(db, pIdx->pSchema);
  119058. int i;
  119059. int mx;
  119060. if( pPragma->iArg ){
  119061. /* PRAGMA index_xinfo (newer version with more rows and columns) */
  119062. mx = pIdx->nColumn;
  119063. pParse->nMem = 6;
  119064. }else{
  119065. /* PRAGMA index_info (legacy version) */
  119066. mx = pIdx->nKeyCol;
  119067. pParse->nMem = 3;
  119068. }
  119069. pTab = pIdx->pTable;
  119070. sqlite3CodeVerifySchema(pParse, iIdxDb);
  119071. assert( pParse->nMem<=pPragma->nPragCName );
  119072. for(i=0; i<mx; i++){
  119073. i16 cnum = pIdx->aiColumn[i];
  119074. sqlite3VdbeMultiLoad(v, 1, "iisX", i, cnum,
  119075. cnum<0 ? 0 : pTab->aCol[cnum].zName);
  119076. if( pPragma->iArg ){
  119077. sqlite3VdbeMultiLoad(v, 4, "isiX",
  119078. pIdx->aSortOrder[i],
  119079. pIdx->azColl[i],
  119080. i<pIdx->nKeyCol);
  119081. }
  119082. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, pParse->nMem);
  119083. }
  119084. }
  119085. }
  119086. break;
  119087. case PragTyp_INDEX_LIST: if( zRight ){
  119088. Index *pIdx;
  119089. Table *pTab;
  119090. int i;
  119091. pTab = sqlite3FindTable(db, zRight, zDb);
  119092. if( pTab ){
  119093. int iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  119094. pParse->nMem = 5;
  119095. sqlite3CodeVerifySchema(pParse, iTabDb);
  119096. for(pIdx=pTab->pIndex, i=0; pIdx; pIdx=pIdx->pNext, i++){
  119097. const char *azOrigin[] = { "c", "u", "pk" };
  119098. sqlite3VdbeMultiLoad(v, 1, "isisi",
  119099. i,
  119100. pIdx->zName,
  119101. IsUniqueIndex(pIdx),
  119102. azOrigin[pIdx->idxType],
  119103. pIdx->pPartIdxWhere!=0);
  119104. }
  119105. }
  119106. }
  119107. break;
  119108. case PragTyp_DATABASE_LIST: {
  119109. int i;
  119110. pParse->nMem = 3;
  119111. for(i=0; i<db->nDb; i++){
  119112. if( db->aDb[i].pBt==0 ) continue;
  119113. assert( db->aDb[i].zDbSName!=0 );
  119114. sqlite3VdbeMultiLoad(v, 1, "iss",
  119115. i,
  119116. db->aDb[i].zDbSName,
  119117. sqlite3BtreeGetFilename(db->aDb[i].pBt));
  119118. }
  119119. }
  119120. break;
  119121. case PragTyp_COLLATION_LIST: {
  119122. int i = 0;
  119123. HashElem *p;
  119124. pParse->nMem = 2;
  119125. for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
  119126. CollSeq *pColl = (CollSeq *)sqliteHashData(p);
  119127. sqlite3VdbeMultiLoad(v, 1, "is", i++, pColl->zName);
  119128. }
  119129. }
  119130. break;
  119131. #ifndef SQLITE_OMIT_INTROSPECTION_PRAGMAS
  119132. case PragTyp_FUNCTION_LIST: {
  119133. int i;
  119134. HashElem *j;
  119135. FuncDef *p;
  119136. int showInternFunc = (db->mDbFlags & DBFLAG_InternalFunc)!=0;
  119137. pParse->nMem = 6;
  119138. for(i=0; i<SQLITE_FUNC_HASH_SZ; i++){
  119139. for(p=sqlite3BuiltinFunctions.a[i]; p; p=p->u.pHash ){
  119140. pragmaFunclistLine(v, p, 1, showInternFunc);
  119141. }
  119142. }
  119143. for(j=sqliteHashFirst(&db->aFunc); j; j=sqliteHashNext(j)){
  119144. p = (FuncDef*)sqliteHashData(j);
  119145. pragmaFunclistLine(v, p, 0, showInternFunc);
  119146. }
  119147. }
  119148. break;
  119149. #ifndef SQLITE_OMIT_VIRTUALTABLE
  119150. case PragTyp_MODULE_LIST: {
  119151. HashElem *j;
  119152. pParse->nMem = 1;
  119153. for(j=sqliteHashFirst(&db->aModule); j; j=sqliteHashNext(j)){
  119154. Module *pMod = (Module*)sqliteHashData(j);
  119155. sqlite3VdbeMultiLoad(v, 1, "s", pMod->zName);
  119156. }
  119157. }
  119158. break;
  119159. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  119160. case PragTyp_PRAGMA_LIST: {
  119161. int i;
  119162. for(i=0; i<ArraySize(aPragmaName); i++){
  119163. sqlite3VdbeMultiLoad(v, 1, "s", aPragmaName[i].zName);
  119164. }
  119165. }
  119166. break;
  119167. #endif /* SQLITE_INTROSPECTION_PRAGMAS */
  119168. #endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
  119169. #ifndef SQLITE_OMIT_FOREIGN_KEY
  119170. case PragTyp_FOREIGN_KEY_LIST: if( zRight ){
  119171. FKey *pFK;
  119172. Table *pTab;
  119173. pTab = sqlite3FindTable(db, zRight, zDb);
  119174. if( pTab ){
  119175. pFK = pTab->pFKey;
  119176. if( pFK ){
  119177. int iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  119178. int i = 0;
  119179. pParse->nMem = 8;
  119180. sqlite3CodeVerifySchema(pParse, iTabDb);
  119181. while(pFK){
  119182. int j;
  119183. for(j=0; j<pFK->nCol; j++){
  119184. sqlite3VdbeMultiLoad(v, 1, "iissssss",
  119185. i,
  119186. j,
  119187. pFK->zTo,
  119188. pTab->aCol[pFK->aCol[j].iFrom].zName,
  119189. pFK->aCol[j].zCol,
  119190. actionName(pFK->aAction[1]), /* ON UPDATE */
  119191. actionName(pFK->aAction[0]), /* ON DELETE */
  119192. "NONE");
  119193. }
  119194. ++i;
  119195. pFK = pFK->pNextFrom;
  119196. }
  119197. }
  119198. }
  119199. }
  119200. break;
  119201. #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
  119202. #ifndef SQLITE_OMIT_FOREIGN_KEY
  119203. #ifndef SQLITE_OMIT_TRIGGER
  119204. case PragTyp_FOREIGN_KEY_CHECK: {
  119205. FKey *pFK; /* A foreign key constraint */
  119206. Table *pTab; /* Child table contain "REFERENCES" keyword */
  119207. Table *pParent; /* Parent table that child points to */
  119208. Index *pIdx; /* Index in the parent table */
  119209. int i; /* Loop counter: Foreign key number for pTab */
  119210. int j; /* Loop counter: Field of the foreign key */
  119211. HashElem *k; /* Loop counter: Next table in schema */
  119212. int x; /* result variable */
  119213. int regResult; /* 3 registers to hold a result row */
  119214. int regKey; /* Register to hold key for checking the FK */
  119215. int regRow; /* Registers to hold a row from pTab */
  119216. int addrTop; /* Top of a loop checking foreign keys */
  119217. int addrOk; /* Jump here if the key is OK */
  119218. int *aiCols; /* child to parent column mapping */
  119219. regResult = pParse->nMem+1;
  119220. pParse->nMem += 4;
  119221. regKey = ++pParse->nMem;
  119222. regRow = ++pParse->nMem;
  119223. k = sqliteHashFirst(&db->aDb[iDb].pSchema->tblHash);
  119224. while( k ){
  119225. int iTabDb;
  119226. if( zRight ){
  119227. pTab = sqlite3LocateTable(pParse, 0, zRight, zDb);
  119228. k = 0;
  119229. }else{
  119230. pTab = (Table*)sqliteHashData(k);
  119231. k = sqliteHashNext(k);
  119232. }
  119233. if( pTab==0 || pTab->pFKey==0 ) continue;
  119234. iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  119235. sqlite3CodeVerifySchema(pParse, iTabDb);
  119236. sqlite3TableLock(pParse, iTabDb, pTab->tnum, 0, pTab->zName);
  119237. if( pTab->nCol+regRow>pParse->nMem ) pParse->nMem = pTab->nCol + regRow;
  119238. sqlite3OpenTable(pParse, 0, iTabDb, pTab, OP_OpenRead);
  119239. sqlite3VdbeLoadString(v, regResult, pTab->zName);
  119240. for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
  119241. pParent = sqlite3FindTable(db, pFK->zTo, zDb);
  119242. if( pParent==0 ) continue;
  119243. pIdx = 0;
  119244. sqlite3TableLock(pParse, iTabDb, pParent->tnum, 0, pParent->zName);
  119245. x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, 0);
  119246. if( x==0 ){
  119247. if( pIdx==0 ){
  119248. sqlite3OpenTable(pParse, i, iTabDb, pParent, OP_OpenRead);
  119249. }else{
  119250. sqlite3VdbeAddOp3(v, OP_OpenRead, i, pIdx->tnum, iTabDb);
  119251. sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  119252. }
  119253. }else{
  119254. k = 0;
  119255. break;
  119256. }
  119257. }
  119258. assert( pParse->nErr>0 || pFK==0 );
  119259. if( pFK ) break;
  119260. if( pParse->nTab<i ) pParse->nTab = i;
  119261. addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, 0); VdbeCoverage(v);
  119262. for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
  119263. pParent = sqlite3FindTable(db, pFK->zTo, zDb);
  119264. pIdx = 0;
  119265. aiCols = 0;
  119266. if( pParent ){
  119267. x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, &aiCols);
  119268. assert( x==0 );
  119269. }
  119270. addrOk = sqlite3VdbeMakeLabel(pParse);
  119271. /* Generate code to read the child key values into registers
  119272. ** regRow..regRow+n. If any of the child key values are NULL, this
  119273. ** row cannot cause an FK violation. Jump directly to addrOk in
  119274. ** this case. */
  119275. for(j=0; j<pFK->nCol; j++){
  119276. int iCol = aiCols ? aiCols[j] : pFK->aCol[j].iFrom;
  119277. sqlite3ExprCodeGetColumnOfTable(v, pTab, 0, iCol, regRow+j);
  119278. sqlite3VdbeAddOp2(v, OP_IsNull, regRow+j, addrOk); VdbeCoverage(v);
  119279. }
  119280. /* Generate code to query the parent index for a matching parent
  119281. ** key. If a match is found, jump to addrOk. */
  119282. if( pIdx ){
  119283. sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, pFK->nCol, regKey,
  119284. sqlite3IndexAffinityStr(db,pIdx), pFK->nCol);
  119285. sqlite3VdbeAddOp4Int(v, OP_Found, i, addrOk, regKey, 0);
  119286. VdbeCoverage(v);
  119287. }else if( pParent ){
  119288. int jmp = sqlite3VdbeCurrentAddr(v)+2;
  119289. sqlite3VdbeAddOp3(v, OP_SeekRowid, i, jmp, regRow); VdbeCoverage(v);
  119290. sqlite3VdbeGoto(v, addrOk);
  119291. assert( pFK->nCol==1 );
  119292. }
  119293. /* Generate code to report an FK violation to the caller. */
  119294. if( HasRowid(pTab) ){
  119295. sqlite3VdbeAddOp2(v, OP_Rowid, 0, regResult+1);
  119296. }else{
  119297. sqlite3VdbeAddOp2(v, OP_Null, 0, regResult+1);
  119298. }
  119299. sqlite3VdbeMultiLoad(v, regResult+2, "siX", pFK->zTo, i-1);
  119300. sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, 4);
  119301. sqlite3VdbeResolveLabel(v, addrOk);
  119302. sqlite3DbFree(db, aiCols);
  119303. }
  119304. sqlite3VdbeAddOp2(v, OP_Next, 0, addrTop+1); VdbeCoverage(v);
  119305. sqlite3VdbeJumpHere(v, addrTop);
  119306. }
  119307. }
  119308. break;
  119309. #endif /* !defined(SQLITE_OMIT_TRIGGER) */
  119310. #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
  119311. #ifndef SQLITE_OMIT_CASE_SENSITIVE_LIKE_PRAGMA
  119312. /* Reinstall the LIKE and GLOB functions. The variant of LIKE
  119313. ** used will be case sensitive or not depending on the RHS.
  119314. */
  119315. case PragTyp_CASE_SENSITIVE_LIKE: {
  119316. if( zRight ){
  119317. sqlite3RegisterLikeFunctions(db, sqlite3GetBoolean(zRight, 0));
  119318. }
  119319. }
  119320. break;
  119321. #endif /* SQLITE_OMIT_CASE_SENSITIVE_LIKE_PRAGMA */
  119322. #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
  119323. # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
  119324. #endif
  119325. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  119326. /* PRAGMA integrity_check
  119327. ** PRAGMA integrity_check(N)
  119328. ** PRAGMA quick_check
  119329. ** PRAGMA quick_check(N)
  119330. **
  119331. ** Verify the integrity of the database.
  119332. **
  119333. ** The "quick_check" is reduced version of
  119334. ** integrity_check designed to detect most database corruption
  119335. ** without the overhead of cross-checking indexes. Quick_check
  119336. ** is linear time wherease integrity_check is O(NlogN).
  119337. */
  119338. case PragTyp_INTEGRITY_CHECK: {
  119339. int i, j, addr, mxErr;
  119340. int isQuick = (sqlite3Tolower(zLeft[0])=='q');
  119341. /* If the PRAGMA command was of the form "PRAGMA <db>.integrity_check",
  119342. ** then iDb is set to the index of the database identified by <db>.
  119343. ** In this case, the integrity of database iDb only is verified by
  119344. ** the VDBE created below.
  119345. **
  119346. ** Otherwise, if the command was simply "PRAGMA integrity_check" (or
  119347. ** "PRAGMA quick_check"), then iDb is set to 0. In this case, set iDb
  119348. ** to -1 here, to indicate that the VDBE should verify the integrity
  119349. ** of all attached databases. */
  119350. assert( iDb>=0 );
  119351. assert( iDb==0 || pId2->z );
  119352. if( pId2->z==0 ) iDb = -1;
  119353. /* Initialize the VDBE program */
  119354. pParse->nMem = 6;
  119355. /* Set the maximum error count */
  119356. mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
  119357. if( zRight ){
  119358. sqlite3GetInt32(zRight, &mxErr);
  119359. if( mxErr<=0 ){
  119360. mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
  119361. }
  119362. }
  119363. sqlite3VdbeAddOp2(v, OP_Integer, mxErr-1, 1); /* reg[1] holds errors left */
  119364. /* Do an integrity check on each database file */
  119365. for(i=0; i<db->nDb; i++){
  119366. HashElem *x; /* For looping over tables in the schema */
  119367. Hash *pTbls; /* Set of all tables in the schema */
  119368. int *aRoot; /* Array of root page numbers of all btrees */
  119369. int cnt = 0; /* Number of entries in aRoot[] */
  119370. int mxIdx = 0; /* Maximum number of indexes for any table */
  119371. if( OMIT_TEMPDB && i==1 ) continue;
  119372. if( iDb>=0 && i!=iDb ) continue;
  119373. sqlite3CodeVerifySchema(pParse, i);
  119374. /* Do an integrity check of the B-Tree
  119375. **
  119376. ** Begin by finding the root pages numbers
  119377. ** for all tables and indices in the database.
  119378. */
  119379. assert( sqlite3SchemaMutexHeld(db, i, 0) );
  119380. pTbls = &db->aDb[i].pSchema->tblHash;
  119381. for(cnt=0, x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
  119382. Table *pTab = sqliteHashData(x); /* Current table */
  119383. Index *pIdx; /* An index on pTab */
  119384. int nIdx; /* Number of indexes on pTab */
  119385. if( HasRowid(pTab) ) cnt++;
  119386. for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){ cnt++; }
  119387. if( nIdx>mxIdx ) mxIdx = nIdx;
  119388. }
  119389. aRoot = sqlite3DbMallocRawNN(db, sizeof(int)*(cnt+1));
  119390. if( aRoot==0 ) break;
  119391. for(cnt=0, x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
  119392. Table *pTab = sqliteHashData(x);
  119393. Index *pIdx;
  119394. if( HasRowid(pTab) ) aRoot[++cnt] = pTab->tnum;
  119395. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  119396. aRoot[++cnt] = pIdx->tnum;
  119397. }
  119398. }
  119399. aRoot[0] = cnt;
  119400. /* Make sure sufficient number of registers have been allocated */
  119401. pParse->nMem = MAX( pParse->nMem, 8+mxIdx );
  119402. sqlite3ClearTempRegCache(pParse);
  119403. /* Do the b-tree integrity checks */
  119404. sqlite3VdbeAddOp4(v, OP_IntegrityCk, 2, cnt, 1, (char*)aRoot,P4_INTARRAY);
  119405. sqlite3VdbeChangeP5(v, (u8)i);
  119406. addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2); VdbeCoverage(v);
  119407. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
  119408. sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zDbSName),
  119409. P4_DYNAMIC);
  119410. sqlite3VdbeAddOp3(v, OP_Concat, 2, 3, 3);
  119411. integrityCheckResultRow(v);
  119412. sqlite3VdbeJumpHere(v, addr);
  119413. /* Make sure all the indices are constructed correctly.
  119414. */
  119415. for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
  119416. Table *pTab = sqliteHashData(x);
  119417. Index *pIdx, *pPk;
  119418. Index *pPrior = 0;
  119419. int loopTop;
  119420. int iDataCur, iIdxCur;
  119421. int r1 = -1;
  119422. if( pTab->tnum<1 ) continue; /* Skip VIEWs or VIRTUAL TABLEs */
  119423. pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
  119424. sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenRead, 0,
  119425. 1, 0, &iDataCur, &iIdxCur);
  119426. /* reg[7] counts the number of entries in the table.
  119427. ** reg[8+i] counts the number of entries in the i-th index
  119428. */
  119429. sqlite3VdbeAddOp2(v, OP_Integer, 0, 7);
  119430. for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  119431. sqlite3VdbeAddOp2(v, OP_Integer, 0, 8+j); /* index entries counter */
  119432. }
  119433. assert( pParse->nMem>=8+j );
  119434. assert( sqlite3NoTempsInRange(pParse,1,7+j) );
  119435. sqlite3VdbeAddOp2(v, OP_Rewind, iDataCur, 0); VdbeCoverage(v);
  119436. loopTop = sqlite3VdbeAddOp2(v, OP_AddImm, 7, 1);
  119437. if( !isQuick ){
  119438. /* Sanity check on record header decoding */
  119439. sqlite3VdbeAddOp3(v, OP_Column, iDataCur, pTab->nNVCol-1,3);
  119440. sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
  119441. }
  119442. /* Verify that all NOT NULL columns really are NOT NULL */
  119443. for(j=0; j<pTab->nCol; j++){
  119444. char *zErr;
  119445. int jmp2;
  119446. if( j==pTab->iPKey ) continue;
  119447. if( pTab->aCol[j].notNull==0 ) continue;
  119448. sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, j, 3);
  119449. if( sqlite3VdbeGetOp(v,-1)->opcode==OP_Column ){
  119450. sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
  119451. }
  119452. jmp2 = sqlite3VdbeAddOp1(v, OP_NotNull, 3); VdbeCoverage(v);
  119453. zErr = sqlite3MPrintf(db, "NULL value in %s.%s", pTab->zName,
  119454. pTab->aCol[j].zName);
  119455. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
  119456. integrityCheckResultRow(v);
  119457. sqlite3VdbeJumpHere(v, jmp2);
  119458. }
  119459. /* Verify CHECK constraints */
  119460. if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
  119461. ExprList *pCheck = sqlite3ExprListDup(db, pTab->pCheck, 0);
  119462. if( db->mallocFailed==0 ){
  119463. int addrCkFault = sqlite3VdbeMakeLabel(pParse);
  119464. int addrCkOk = sqlite3VdbeMakeLabel(pParse);
  119465. char *zErr;
  119466. int k;
  119467. pParse->iSelfTab = iDataCur + 1;
  119468. for(k=pCheck->nExpr-1; k>0; k--){
  119469. sqlite3ExprIfFalse(pParse, pCheck->a[k].pExpr, addrCkFault, 0);
  119470. }
  119471. sqlite3ExprIfTrue(pParse, pCheck->a[0].pExpr, addrCkOk,
  119472. SQLITE_JUMPIFNULL);
  119473. sqlite3VdbeResolveLabel(v, addrCkFault);
  119474. pParse->iSelfTab = 0;
  119475. zErr = sqlite3MPrintf(db, "CHECK constraint failed in %s",
  119476. pTab->zName);
  119477. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
  119478. integrityCheckResultRow(v);
  119479. sqlite3VdbeResolveLabel(v, addrCkOk);
  119480. }
  119481. sqlite3ExprListDelete(db, pCheck);
  119482. }
  119483. if( !isQuick ){ /* Omit the remaining tests for quick_check */
  119484. /* Validate index entries for the current row */
  119485. for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  119486. int jmp2, jmp3, jmp4, jmp5;
  119487. int ckUniq = sqlite3VdbeMakeLabel(pParse);
  119488. if( pPk==pIdx ) continue;
  119489. r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 0, &jmp3,
  119490. pPrior, r1);
  119491. pPrior = pIdx;
  119492. sqlite3VdbeAddOp2(v, OP_AddImm, 8+j, 1);/* increment entry count */
  119493. /* Verify that an index entry exists for the current table row */
  119494. jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, iIdxCur+j, ckUniq, r1,
  119495. pIdx->nColumn); VdbeCoverage(v);
  119496. sqlite3VdbeLoadString(v, 3, "row ");
  119497. sqlite3VdbeAddOp3(v, OP_Concat, 7, 3, 3);
  119498. sqlite3VdbeLoadString(v, 4, " missing from index ");
  119499. sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
  119500. jmp5 = sqlite3VdbeLoadString(v, 4, pIdx->zName);
  119501. sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
  119502. jmp4 = integrityCheckResultRow(v);
  119503. sqlite3VdbeJumpHere(v, jmp2);
  119504. /* For UNIQUE indexes, verify that only one entry exists with the
  119505. ** current key. The entry is unique if (1) any column is NULL
  119506. ** or (2) the next entry has a different key */
  119507. if( IsUniqueIndex(pIdx) ){
  119508. int uniqOk = sqlite3VdbeMakeLabel(pParse);
  119509. int jmp6;
  119510. int kk;
  119511. for(kk=0; kk<pIdx->nKeyCol; kk++){
  119512. int iCol = pIdx->aiColumn[kk];
  119513. assert( iCol!=XN_ROWID && iCol<pTab->nCol );
  119514. if( iCol>=0 && pTab->aCol[iCol].notNull ) continue;
  119515. sqlite3VdbeAddOp2(v, OP_IsNull, r1+kk, uniqOk);
  119516. VdbeCoverage(v);
  119517. }
  119518. jmp6 = sqlite3VdbeAddOp1(v, OP_Next, iIdxCur+j); VdbeCoverage(v);
  119519. sqlite3VdbeGoto(v, uniqOk);
  119520. sqlite3VdbeJumpHere(v, jmp6);
  119521. sqlite3VdbeAddOp4Int(v, OP_IdxGT, iIdxCur+j, uniqOk, r1,
  119522. pIdx->nKeyCol); VdbeCoverage(v);
  119523. sqlite3VdbeLoadString(v, 3, "non-unique entry in index ");
  119524. sqlite3VdbeGoto(v, jmp5);
  119525. sqlite3VdbeResolveLabel(v, uniqOk);
  119526. }
  119527. sqlite3VdbeJumpHere(v, jmp4);
  119528. sqlite3ResolvePartIdxLabel(pParse, jmp3);
  119529. }
  119530. }
  119531. sqlite3VdbeAddOp2(v, OP_Next, iDataCur, loopTop); VdbeCoverage(v);
  119532. sqlite3VdbeJumpHere(v, loopTop-1);
  119533. if( !isQuick ){
  119534. sqlite3VdbeLoadString(v, 2, "wrong # of entries in index ");
  119535. for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  119536. if( pPk==pIdx ) continue;
  119537. sqlite3VdbeAddOp2(v, OP_Count, iIdxCur+j, 3);
  119538. addr = sqlite3VdbeAddOp3(v, OP_Eq, 8+j, 0, 3); VdbeCoverage(v);
  119539. sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
  119540. sqlite3VdbeLoadString(v, 4, pIdx->zName);
  119541. sqlite3VdbeAddOp3(v, OP_Concat, 4, 2, 3);
  119542. integrityCheckResultRow(v);
  119543. sqlite3VdbeJumpHere(v, addr);
  119544. }
  119545. }
  119546. }
  119547. }
  119548. {
  119549. static const int iLn = VDBE_OFFSET_LINENO(2);
  119550. static const VdbeOpList endCode[] = {
  119551. { OP_AddImm, 1, 0, 0}, /* 0 */
  119552. { OP_IfNotZero, 1, 4, 0}, /* 1 */
  119553. { OP_String8, 0, 3, 0}, /* 2 */
  119554. { OP_ResultRow, 3, 1, 0}, /* 3 */
  119555. { OP_Halt, 0, 0, 0}, /* 4 */
  119556. { OP_String8, 0, 3, 0}, /* 5 */
  119557. { OP_Goto, 0, 3, 0}, /* 6 */
  119558. };
  119559. VdbeOp *aOp;
  119560. aOp = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode, iLn);
  119561. if( aOp ){
  119562. aOp[0].p2 = 1-mxErr;
  119563. aOp[2].p4type = P4_STATIC;
  119564. aOp[2].p4.z = "ok";
  119565. aOp[5].p4type = P4_STATIC;
  119566. aOp[5].p4.z = (char*)sqlite3ErrStr(SQLITE_CORRUPT);
  119567. }
  119568. sqlite3VdbeChangeP3(v, 0, sqlite3VdbeCurrentAddr(v)-2);
  119569. }
  119570. }
  119571. break;
  119572. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  119573. #ifndef SQLITE_OMIT_UTF16
  119574. /*
  119575. ** PRAGMA encoding
  119576. ** PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
  119577. **
  119578. ** In its first form, this pragma returns the encoding of the main
  119579. ** database. If the database is not initialized, it is initialized now.
  119580. **
  119581. ** The second form of this pragma is a no-op if the main database file
  119582. ** has not already been initialized. In this case it sets the default
  119583. ** encoding that will be used for the main database file if a new file
  119584. ** is created. If an existing main database file is opened, then the
  119585. ** default text encoding for the existing database is used.
  119586. **
  119587. ** In all cases new databases created using the ATTACH command are
  119588. ** created to use the same default text encoding as the main database. If
  119589. ** the main database has not been initialized and/or created when ATTACH
  119590. ** is executed, this is done before the ATTACH operation.
  119591. **
  119592. ** In the second form this pragma sets the text encoding to be used in
  119593. ** new database files created using this database handle. It is only
  119594. ** useful if invoked immediately after the main database i
  119595. */
  119596. case PragTyp_ENCODING: {
  119597. static const struct EncName {
  119598. char *zName;
  119599. u8 enc;
  119600. } encnames[] = {
  119601. { "UTF8", SQLITE_UTF8 },
  119602. { "UTF-8", SQLITE_UTF8 }, /* Must be element [1] */
  119603. { "UTF-16le", SQLITE_UTF16LE }, /* Must be element [2] */
  119604. { "UTF-16be", SQLITE_UTF16BE }, /* Must be element [3] */
  119605. { "UTF16le", SQLITE_UTF16LE },
  119606. { "UTF16be", SQLITE_UTF16BE },
  119607. { "UTF-16", 0 }, /* SQLITE_UTF16NATIVE */
  119608. { "UTF16", 0 }, /* SQLITE_UTF16NATIVE */
  119609. { 0, 0 }
  119610. };
  119611. const struct EncName *pEnc;
  119612. if( !zRight ){ /* "PRAGMA encoding" */
  119613. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  119614. assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
  119615. assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
  119616. assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
  119617. returnSingleText(v, encnames[ENC(pParse->db)].zName);
  119618. }else{ /* "PRAGMA encoding = XXX" */
  119619. /* Only change the value of sqlite.enc if the database handle is not
  119620. ** initialized. If the main database exists, the new sqlite.enc value
  119621. ** will be overwritten when the schema is next loaded. If it does not
  119622. ** already exists, it will be created to use the new encoding value.
  119623. */
  119624. if( (db->mDbFlags & DBFLAG_EncodingFixed)==0 ){
  119625. for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
  119626. if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
  119627. u8 enc = pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
  119628. SCHEMA_ENC(db) = enc;
  119629. sqlite3SetTextEncoding(db, enc);
  119630. break;
  119631. }
  119632. }
  119633. if( !pEnc->zName ){
  119634. sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
  119635. }
  119636. }
  119637. }
  119638. }
  119639. break;
  119640. #endif /* SQLITE_OMIT_UTF16 */
  119641. #ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
  119642. /*
  119643. ** PRAGMA [schema.]schema_version
  119644. ** PRAGMA [schema.]schema_version = <integer>
  119645. **
  119646. ** PRAGMA [schema.]user_version
  119647. ** PRAGMA [schema.]user_version = <integer>
  119648. **
  119649. ** PRAGMA [schema.]freelist_count
  119650. **
  119651. ** PRAGMA [schema.]data_version
  119652. **
  119653. ** PRAGMA [schema.]application_id
  119654. ** PRAGMA [schema.]application_id = <integer>
  119655. **
  119656. ** The pragma's schema_version and user_version are used to set or get
  119657. ** the value of the schema-version and user-version, respectively. Both
  119658. ** the schema-version and the user-version are 32-bit signed integers
  119659. ** stored in the database header.
  119660. **
  119661. ** The schema-cookie is usually only manipulated internally by SQLite. It
  119662. ** is incremented by SQLite whenever the database schema is modified (by
  119663. ** creating or dropping a table or index). The schema version is used by
  119664. ** SQLite each time a query is executed to ensure that the internal cache
  119665. ** of the schema used when compiling the SQL query matches the schema of
  119666. ** the database against which the compiled query is actually executed.
  119667. ** Subverting this mechanism by using "PRAGMA schema_version" to modify
  119668. ** the schema-version is potentially dangerous and may lead to program
  119669. ** crashes or database corruption. Use with caution!
  119670. **
  119671. ** The user-version is not used internally by SQLite. It may be used by
  119672. ** applications for any purpose.
  119673. */
  119674. case PragTyp_HEADER_VALUE: {
  119675. int iCookie = pPragma->iArg; /* Which cookie to read or write */
  119676. sqlite3VdbeUsesBtree(v, iDb);
  119677. if( zRight && (pPragma->mPragFlg & PragFlg_ReadOnly)==0 ){
  119678. /* Write the specified cookie value */
  119679. static const VdbeOpList setCookie[] = {
  119680. { OP_Transaction, 0, 1, 0}, /* 0 */
  119681. { OP_SetCookie, 0, 0, 0}, /* 1 */
  119682. };
  119683. VdbeOp *aOp;
  119684. sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(setCookie));
  119685. aOp = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie, 0);
  119686. if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
  119687. aOp[0].p1 = iDb;
  119688. aOp[1].p1 = iDb;
  119689. aOp[1].p2 = iCookie;
  119690. aOp[1].p3 = sqlite3Atoi(zRight);
  119691. }else{
  119692. /* Read the specified cookie value */
  119693. static const VdbeOpList readCookie[] = {
  119694. { OP_Transaction, 0, 0, 0}, /* 0 */
  119695. { OP_ReadCookie, 0, 1, 0}, /* 1 */
  119696. { OP_ResultRow, 1, 1, 0}
  119697. };
  119698. VdbeOp *aOp;
  119699. sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(readCookie));
  119700. aOp = sqlite3VdbeAddOpList(v, ArraySize(readCookie),readCookie,0);
  119701. if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
  119702. aOp[0].p1 = iDb;
  119703. aOp[1].p1 = iDb;
  119704. aOp[1].p3 = iCookie;
  119705. sqlite3VdbeReusable(v);
  119706. }
  119707. }
  119708. break;
  119709. #endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
  119710. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  119711. /*
  119712. ** PRAGMA compile_options
  119713. **
  119714. ** Return the names of all compile-time options used in this build,
  119715. ** one option per row.
  119716. */
  119717. case PragTyp_COMPILE_OPTIONS: {
  119718. int i = 0;
  119719. const char *zOpt;
  119720. pParse->nMem = 1;
  119721. while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){
  119722. sqlite3VdbeLoadString(v, 1, zOpt);
  119723. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  119724. }
  119725. sqlite3VdbeReusable(v);
  119726. }
  119727. break;
  119728. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  119729. #ifndef SQLITE_OMIT_WAL
  119730. /*
  119731. ** PRAGMA [schema.]wal_checkpoint = passive|full|restart|truncate
  119732. **
  119733. ** Checkpoint the database.
  119734. */
  119735. case PragTyp_WAL_CHECKPOINT: {
  119736. int iBt = (pId2->z?iDb:SQLITE_MAX_ATTACHED);
  119737. int eMode = SQLITE_CHECKPOINT_PASSIVE;
  119738. if( zRight ){
  119739. if( sqlite3StrICmp(zRight, "full")==0 ){
  119740. eMode = SQLITE_CHECKPOINT_FULL;
  119741. }else if( sqlite3StrICmp(zRight, "restart")==0 ){
  119742. eMode = SQLITE_CHECKPOINT_RESTART;
  119743. }else if( sqlite3StrICmp(zRight, "truncate")==0 ){
  119744. eMode = SQLITE_CHECKPOINT_TRUNCATE;
  119745. }
  119746. }
  119747. pParse->nMem = 3;
  119748. sqlite3VdbeAddOp3(v, OP_Checkpoint, iBt, eMode, 1);
  119749. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
  119750. }
  119751. break;
  119752. /*
  119753. ** PRAGMA wal_autocheckpoint
  119754. ** PRAGMA wal_autocheckpoint = N
  119755. **
  119756. ** Configure a database connection to automatically checkpoint a database
  119757. ** after accumulating N frames in the log. Or query for the current value
  119758. ** of N.
  119759. */
  119760. case PragTyp_WAL_AUTOCHECKPOINT: {
  119761. if( zRight ){
  119762. sqlite3_wal_autocheckpoint(db, sqlite3Atoi(zRight));
  119763. }
  119764. returnSingleInt(v,
  119765. db->xWalCallback==sqlite3WalDefaultHook ?
  119766. SQLITE_PTR_TO_INT(db->pWalArg) : 0);
  119767. }
  119768. break;
  119769. #endif
  119770. /*
  119771. ** PRAGMA shrink_memory
  119772. **
  119773. ** IMPLEMENTATION-OF: R-23445-46109 This pragma causes the database
  119774. ** connection on which it is invoked to free up as much memory as it
  119775. ** can, by calling sqlite3_db_release_memory().
  119776. */
  119777. case PragTyp_SHRINK_MEMORY: {
  119778. sqlite3_db_release_memory(db);
  119779. break;
  119780. }
  119781. /*
  119782. ** PRAGMA optimize
  119783. ** PRAGMA optimize(MASK)
  119784. ** PRAGMA schema.optimize
  119785. ** PRAGMA schema.optimize(MASK)
  119786. **
  119787. ** Attempt to optimize the database. All schemas are optimized in the first
  119788. ** two forms, and only the specified schema is optimized in the latter two.
  119789. **
  119790. ** The details of optimizations performed by this pragma are expected
  119791. ** to change and improve over time. Applications should anticipate that
  119792. ** this pragma will perform new optimizations in future releases.
  119793. **
  119794. ** The optional argument is a bitmask of optimizations to perform:
  119795. **
  119796. ** 0x0001 Debugging mode. Do not actually perform any optimizations
  119797. ** but instead return one line of text for each optimization
  119798. ** that would have been done. Off by default.
  119799. **
  119800. ** 0x0002 Run ANALYZE on tables that might benefit. On by default.
  119801. ** See below for additional information.
  119802. **
  119803. ** 0x0004 (Not yet implemented) Record usage and performance
  119804. ** information from the current session in the
  119805. ** database file so that it will be available to "optimize"
  119806. ** pragmas run by future database connections.
  119807. **
  119808. ** 0x0008 (Not yet implemented) Create indexes that might have
  119809. ** been helpful to recent queries
  119810. **
  119811. ** The default MASK is and always shall be 0xfffe. 0xfffe means perform all
  119812. ** of the optimizations listed above except Debug Mode, including new
  119813. ** optimizations that have not yet been invented. If new optimizations are
  119814. ** ever added that should be off by default, those off-by-default
  119815. ** optimizations will have bitmasks of 0x10000 or larger.
  119816. **
  119817. ** DETERMINATION OF WHEN TO RUN ANALYZE
  119818. **
  119819. ** In the current implementation, a table is analyzed if only if all of
  119820. ** the following are true:
  119821. **
  119822. ** (1) MASK bit 0x02 is set.
  119823. **
  119824. ** (2) The query planner used sqlite_stat1-style statistics for one or
  119825. ** more indexes of the table at some point during the lifetime of
  119826. ** the current connection.
  119827. **
  119828. ** (3) One or more indexes of the table are currently unanalyzed OR
  119829. ** the number of rows in the table has increased by 25 times or more
  119830. ** since the last time ANALYZE was run.
  119831. **
  119832. ** The rules for when tables are analyzed are likely to change in
  119833. ** future releases.
  119834. */
  119835. case PragTyp_OPTIMIZE: {
  119836. int iDbLast; /* Loop termination point for the schema loop */
  119837. int iTabCur; /* Cursor for a table whose size needs checking */
  119838. HashElem *k; /* Loop over tables of a schema */
  119839. Schema *pSchema; /* The current schema */
  119840. Table *pTab; /* A table in the schema */
  119841. Index *pIdx; /* An index of the table */
  119842. LogEst szThreshold; /* Size threshold above which reanalysis is needd */
  119843. char *zSubSql; /* SQL statement for the OP_SqlExec opcode */
  119844. u32 opMask; /* Mask of operations to perform */
  119845. if( zRight ){
  119846. opMask = (u32)sqlite3Atoi(zRight);
  119847. if( (opMask & 0x02)==0 ) break;
  119848. }else{
  119849. opMask = 0xfffe;
  119850. }
  119851. iTabCur = pParse->nTab++;
  119852. for(iDbLast = zDb?iDb:db->nDb-1; iDb<=iDbLast; iDb++){
  119853. if( iDb==1 ) continue;
  119854. sqlite3CodeVerifySchema(pParse, iDb);
  119855. pSchema = db->aDb[iDb].pSchema;
  119856. for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
  119857. pTab = (Table*)sqliteHashData(k);
  119858. /* If table pTab has not been used in a way that would benefit from
  119859. ** having analysis statistics during the current session, then skip it.
  119860. ** This also has the effect of skipping virtual tables and views */
  119861. if( (pTab->tabFlags & TF_StatsUsed)==0 ) continue;
  119862. /* Reanalyze if the table is 25 times larger than the last analysis */
  119863. szThreshold = pTab->nRowLogEst + 46; assert( sqlite3LogEst(25)==46 );
  119864. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  119865. if( !pIdx->hasStat1 ){
  119866. szThreshold = 0; /* Always analyze if any index lacks statistics */
  119867. break;
  119868. }
  119869. }
  119870. if( szThreshold ){
  119871. sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);
  119872. sqlite3VdbeAddOp3(v, OP_IfSmaller, iTabCur,
  119873. sqlite3VdbeCurrentAddr(v)+2+(opMask&1), szThreshold);
  119874. VdbeCoverage(v);
  119875. }
  119876. zSubSql = sqlite3MPrintf(db, "ANALYZE \"%w\".\"%w\"",
  119877. db->aDb[iDb].zDbSName, pTab->zName);
  119878. if( opMask & 0x01 ){
  119879. int r1 = sqlite3GetTempReg(pParse);
  119880. sqlite3VdbeAddOp4(v, OP_String8, 0, r1, 0, zSubSql, P4_DYNAMIC);
  119881. sqlite3VdbeAddOp2(v, OP_ResultRow, r1, 1);
  119882. }else{
  119883. sqlite3VdbeAddOp4(v, OP_SqlExec, 0, 0, 0, zSubSql, P4_DYNAMIC);
  119884. }
  119885. }
  119886. }
  119887. sqlite3VdbeAddOp0(v, OP_Expire);
  119888. break;
  119889. }
  119890. /*
  119891. ** PRAGMA busy_timeout
  119892. ** PRAGMA busy_timeout = N
  119893. **
  119894. ** Call sqlite3_busy_timeout(db, N). Return the current timeout value
  119895. ** if one is set. If no busy handler or a different busy handler is set
  119896. ** then 0 is returned. Setting the busy_timeout to 0 or negative
  119897. ** disables the timeout.
  119898. */
  119899. /*case PragTyp_BUSY_TIMEOUT*/ default: {
  119900. assert( pPragma->ePragTyp==PragTyp_BUSY_TIMEOUT );
  119901. if( zRight ){
  119902. sqlite3_busy_timeout(db, sqlite3Atoi(zRight));
  119903. }
  119904. returnSingleInt(v, db->busyTimeout);
  119905. break;
  119906. }
  119907. /*
  119908. ** PRAGMA soft_heap_limit
  119909. ** PRAGMA soft_heap_limit = N
  119910. **
  119911. ** IMPLEMENTATION-OF: R-26343-45930 This pragma invokes the
  119912. ** sqlite3_soft_heap_limit64() interface with the argument N, if N is
  119913. ** specified and is a non-negative integer.
  119914. ** IMPLEMENTATION-OF: R-64451-07163 The soft_heap_limit pragma always
  119915. ** returns the same integer that would be returned by the
  119916. ** sqlite3_soft_heap_limit64(-1) C-language function.
  119917. */
  119918. case PragTyp_SOFT_HEAP_LIMIT: {
  119919. sqlite3_int64 N;
  119920. if( zRight && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK ){
  119921. sqlite3_soft_heap_limit64(N);
  119922. }
  119923. returnSingleInt(v, sqlite3_soft_heap_limit64(-1));
  119924. break;
  119925. }
  119926. /*
  119927. ** PRAGMA hard_heap_limit
  119928. ** PRAGMA hard_heap_limit = N
  119929. **
  119930. ** Invoke sqlite3_hard_heap_limit64() to query or set the hard heap
  119931. ** limit. The hard heap limit can be activated or lowered by this
  119932. ** pragma, but not raised or deactivated. Only the
  119933. ** sqlite3_hard_heap_limit64() C-language API can raise or deactivate
  119934. ** the hard heap limit. This allows an application to set a heap limit
  119935. ** constraint that cannot be relaxed by an untrusted SQL script.
  119936. */
  119937. case PragTyp_HARD_HEAP_LIMIT: {
  119938. sqlite3_int64 N;
  119939. if( zRight && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK ){
  119940. sqlite3_int64 iPrior = sqlite3_hard_heap_limit64(-1);
  119941. if( N>0 && (iPrior==0 || iPrior>N) ) sqlite3_hard_heap_limit64(N);
  119942. }
  119943. returnSingleInt(v, sqlite3_hard_heap_limit64(-1));
  119944. break;
  119945. }
  119946. /*
  119947. ** PRAGMA threads
  119948. ** PRAGMA threads = N
  119949. **
  119950. ** Configure the maximum number of worker threads. Return the new
  119951. ** maximum, which might be less than requested.
  119952. */
  119953. case PragTyp_THREADS: {
  119954. sqlite3_int64 N;
  119955. if( zRight
  119956. && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK
  119957. && N>=0
  119958. ){
  119959. sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, (int)(N&0x7fffffff));
  119960. }
  119961. returnSingleInt(v, sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, -1));
  119962. break;
  119963. }
  119964. /*
  119965. ** PRAGMA analysis_limit
  119966. ** PRAGMA analysis_limit = N
  119967. **
  119968. ** Configure the maximum number of rows that ANALYZE will examine
  119969. ** in each index that it looks at. Return the new limit.
  119970. */
  119971. case PragTyp_ANALYSIS_LIMIT: {
  119972. sqlite3_int64 N;
  119973. if( zRight
  119974. && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK
  119975. && N>=0
  119976. ){
  119977. db->nAnalysisLimit = (int)(N&0x7fffffff);
  119978. }
  119979. returnSingleInt(v, db->nAnalysisLimit);
  119980. break;
  119981. }
  119982. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  119983. /*
  119984. ** Report the current state of file logs for all databases
  119985. */
  119986. case PragTyp_LOCK_STATUS: {
  119987. static const char *const azLockName[] = {
  119988. "unlocked", "shared", "reserved", "pending", "exclusive"
  119989. };
  119990. int i;
  119991. pParse->nMem = 2;
  119992. for(i=0; i<db->nDb; i++){
  119993. Btree *pBt;
  119994. const char *zState = "unknown";
  119995. int j;
  119996. if( db->aDb[i].zDbSName==0 ) continue;
  119997. pBt = db->aDb[i].pBt;
  119998. if( pBt==0 || sqlite3BtreePager(pBt)==0 ){
  119999. zState = "closed";
  120000. }else if( sqlite3_file_control(db, i ? db->aDb[i].zDbSName : 0,
  120001. SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
  120002. zState = azLockName[j];
  120003. }
  120004. sqlite3VdbeMultiLoad(v, 1, "ss", db->aDb[i].zDbSName, zState);
  120005. }
  120006. break;
  120007. }
  120008. #endif
  120009. #if defined(SQLITE_ENABLE_CEROD)
  120010. case PragTyp_ACTIVATE_EXTENSIONS: if( zRight ){
  120011. if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
  120012. sqlite3_activate_cerod(&zRight[6]);
  120013. }
  120014. }
  120015. break;
  120016. #endif
  120017. } /* End of the PRAGMA switch */
  120018. /* The following block is a no-op unless SQLITE_DEBUG is defined. Its only
  120019. ** purpose is to execute assert() statements to verify that if the
  120020. ** PragFlg_NoColumns1 flag is set and the caller specified an argument
  120021. ** to the PRAGMA, the implementation has not added any OP_ResultRow
  120022. ** instructions to the VM. */
  120023. if( (pPragma->mPragFlg & PragFlg_NoColumns1) && zRight ){
  120024. sqlite3VdbeVerifyNoResultRow(v);
  120025. }
  120026. pragma_out:
  120027. sqlite3DbFree(db, zLeft);
  120028. sqlite3DbFree(db, zRight);
  120029. }
  120030. #ifndef SQLITE_OMIT_VIRTUALTABLE
  120031. /*****************************************************************************
  120032. ** Implementation of an eponymous virtual table that runs a pragma.
  120033. **
  120034. */
  120035. typedef struct PragmaVtab PragmaVtab;
  120036. typedef struct PragmaVtabCursor PragmaVtabCursor;
  120037. struct PragmaVtab {
  120038. sqlite3_vtab base; /* Base class. Must be first */
  120039. sqlite3 *db; /* The database connection to which it belongs */
  120040. const PragmaName *pName; /* Name of the pragma */
  120041. u8 nHidden; /* Number of hidden columns */
  120042. u8 iHidden; /* Index of the first hidden column */
  120043. };
  120044. struct PragmaVtabCursor {
  120045. sqlite3_vtab_cursor base; /* Base class. Must be first */
  120046. sqlite3_stmt *pPragma; /* The pragma statement to run */
  120047. sqlite_int64 iRowid; /* Current rowid */
  120048. char *azArg[2]; /* Value of the argument and schema */
  120049. };
  120050. /*
  120051. ** Pragma virtual table module xConnect method.
  120052. */
  120053. static int pragmaVtabConnect(
  120054. sqlite3 *db,
  120055. void *pAux,
  120056. int argc, const char *const*argv,
  120057. sqlite3_vtab **ppVtab,
  120058. char **pzErr
  120059. ){
  120060. const PragmaName *pPragma = (const PragmaName*)pAux;
  120061. PragmaVtab *pTab = 0;
  120062. int rc;
  120063. int i, j;
  120064. char cSep = '(';
  120065. StrAccum acc;
  120066. char zBuf[200];
  120067. UNUSED_PARAMETER(argc);
  120068. UNUSED_PARAMETER(argv);
  120069. sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
  120070. sqlite3_str_appendall(&acc, "CREATE TABLE x");
  120071. for(i=0, j=pPragma->iPragCName; i<pPragma->nPragCName; i++, j++){
  120072. sqlite3_str_appendf(&acc, "%c\"%s\"", cSep, pragCName[j]);
  120073. cSep = ',';
  120074. }
  120075. if( i==0 ){
  120076. sqlite3_str_appendf(&acc, "(\"%s\"", pPragma->zName);
  120077. i++;
  120078. }
  120079. j = 0;
  120080. if( pPragma->mPragFlg & PragFlg_Result1 ){
  120081. sqlite3_str_appendall(&acc, ",arg HIDDEN");
  120082. j++;
  120083. }
  120084. if( pPragma->mPragFlg & (PragFlg_SchemaOpt|PragFlg_SchemaReq) ){
  120085. sqlite3_str_appendall(&acc, ",schema HIDDEN");
  120086. j++;
  120087. }
  120088. sqlite3_str_append(&acc, ")", 1);
  120089. sqlite3StrAccumFinish(&acc);
  120090. assert( strlen(zBuf) < sizeof(zBuf)-1 );
  120091. rc = sqlite3_declare_vtab(db, zBuf);
  120092. if( rc==SQLITE_OK ){
  120093. pTab = (PragmaVtab*)sqlite3_malloc(sizeof(PragmaVtab));
  120094. if( pTab==0 ){
  120095. rc = SQLITE_NOMEM;
  120096. }else{
  120097. memset(pTab, 0, sizeof(PragmaVtab));
  120098. pTab->pName = pPragma;
  120099. pTab->db = db;
  120100. pTab->iHidden = i;
  120101. pTab->nHidden = j;
  120102. }
  120103. }else{
  120104. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  120105. }
  120106. *ppVtab = (sqlite3_vtab*)pTab;
  120107. return rc;
  120108. }
  120109. /*
  120110. ** Pragma virtual table module xDisconnect method.
  120111. */
  120112. static int pragmaVtabDisconnect(sqlite3_vtab *pVtab){
  120113. PragmaVtab *pTab = (PragmaVtab*)pVtab;
  120114. sqlite3_free(pTab);
  120115. return SQLITE_OK;
  120116. }
  120117. /* Figure out the best index to use to search a pragma virtual table.
  120118. **
  120119. ** There are not really any index choices. But we want to encourage the
  120120. ** query planner to give == constraints on as many hidden parameters as
  120121. ** possible, and especially on the first hidden parameter. So return a
  120122. ** high cost if hidden parameters are unconstrained.
  120123. */
  120124. static int pragmaVtabBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
  120125. PragmaVtab *pTab = (PragmaVtab*)tab;
  120126. const struct sqlite3_index_constraint *pConstraint;
  120127. int i, j;
  120128. int seen[2];
  120129. pIdxInfo->estimatedCost = (double)1;
  120130. if( pTab->nHidden==0 ){ return SQLITE_OK; }
  120131. pConstraint = pIdxInfo->aConstraint;
  120132. seen[0] = 0;
  120133. seen[1] = 0;
  120134. for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
  120135. if( pConstraint->usable==0 ) continue;
  120136. if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
  120137. if( pConstraint->iColumn < pTab->iHidden ) continue;
  120138. j = pConstraint->iColumn - pTab->iHidden;
  120139. assert( j < 2 );
  120140. seen[j] = i+1;
  120141. }
  120142. if( seen[0]==0 ){
  120143. pIdxInfo->estimatedCost = (double)2147483647;
  120144. pIdxInfo->estimatedRows = 2147483647;
  120145. return SQLITE_OK;
  120146. }
  120147. j = seen[0]-1;
  120148. pIdxInfo->aConstraintUsage[j].argvIndex = 1;
  120149. pIdxInfo->aConstraintUsage[j].omit = 1;
  120150. if( seen[1]==0 ) return SQLITE_OK;
  120151. pIdxInfo->estimatedCost = (double)20;
  120152. pIdxInfo->estimatedRows = 20;
  120153. j = seen[1]-1;
  120154. pIdxInfo->aConstraintUsage[j].argvIndex = 2;
  120155. pIdxInfo->aConstraintUsage[j].omit = 1;
  120156. return SQLITE_OK;
  120157. }
  120158. /* Create a new cursor for the pragma virtual table */
  120159. static int pragmaVtabOpen(sqlite3_vtab *pVtab, sqlite3_vtab_cursor **ppCursor){
  120160. PragmaVtabCursor *pCsr;
  120161. pCsr = (PragmaVtabCursor*)sqlite3_malloc(sizeof(*pCsr));
  120162. if( pCsr==0 ) return SQLITE_NOMEM;
  120163. memset(pCsr, 0, sizeof(PragmaVtabCursor));
  120164. pCsr->base.pVtab = pVtab;
  120165. *ppCursor = &pCsr->base;
  120166. return SQLITE_OK;
  120167. }
  120168. /* Clear all content from pragma virtual table cursor. */
  120169. static void pragmaVtabCursorClear(PragmaVtabCursor *pCsr){
  120170. int i;
  120171. sqlite3_finalize(pCsr->pPragma);
  120172. pCsr->pPragma = 0;
  120173. for(i=0; i<ArraySize(pCsr->azArg); i++){
  120174. sqlite3_free(pCsr->azArg[i]);
  120175. pCsr->azArg[i] = 0;
  120176. }
  120177. }
  120178. /* Close a pragma virtual table cursor */
  120179. static int pragmaVtabClose(sqlite3_vtab_cursor *cur){
  120180. PragmaVtabCursor *pCsr = (PragmaVtabCursor*)cur;
  120181. pragmaVtabCursorClear(pCsr);
  120182. sqlite3_free(pCsr);
  120183. return SQLITE_OK;
  120184. }
  120185. /* Advance the pragma virtual table cursor to the next row */
  120186. static int pragmaVtabNext(sqlite3_vtab_cursor *pVtabCursor){
  120187. PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
  120188. int rc = SQLITE_OK;
  120189. /* Increment the xRowid value */
  120190. pCsr->iRowid++;
  120191. assert( pCsr->pPragma );
  120192. if( SQLITE_ROW!=sqlite3_step(pCsr->pPragma) ){
  120193. rc = sqlite3_finalize(pCsr->pPragma);
  120194. pCsr->pPragma = 0;
  120195. pragmaVtabCursorClear(pCsr);
  120196. }
  120197. return rc;
  120198. }
  120199. /*
  120200. ** Pragma virtual table module xFilter method.
  120201. */
  120202. static int pragmaVtabFilter(
  120203. sqlite3_vtab_cursor *pVtabCursor,
  120204. int idxNum, const char *idxStr,
  120205. int argc, sqlite3_value **argv
  120206. ){
  120207. PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
  120208. PragmaVtab *pTab = (PragmaVtab*)(pVtabCursor->pVtab);
  120209. int rc;
  120210. int i, j;
  120211. StrAccum acc;
  120212. char *zSql;
  120213. UNUSED_PARAMETER(idxNum);
  120214. UNUSED_PARAMETER(idxStr);
  120215. pragmaVtabCursorClear(pCsr);
  120216. j = (pTab->pName->mPragFlg & PragFlg_Result1)!=0 ? 0 : 1;
  120217. for(i=0; i<argc; i++, j++){
  120218. const char *zText = (const char*)sqlite3_value_text(argv[i]);
  120219. assert( j<ArraySize(pCsr->azArg) );
  120220. assert( pCsr->azArg[j]==0 );
  120221. if( zText ){
  120222. pCsr->azArg[j] = sqlite3_mprintf("%s", zText);
  120223. if( pCsr->azArg[j]==0 ){
  120224. return SQLITE_NOMEM;
  120225. }
  120226. }
  120227. }
  120228. sqlite3StrAccumInit(&acc, 0, 0, 0, pTab->db->aLimit[SQLITE_LIMIT_SQL_LENGTH]);
  120229. sqlite3_str_appendall(&acc, "PRAGMA ");
  120230. if( pCsr->azArg[1] ){
  120231. sqlite3_str_appendf(&acc, "%Q.", pCsr->azArg[1]);
  120232. }
  120233. sqlite3_str_appendall(&acc, pTab->pName->zName);
  120234. if( pCsr->azArg[0] ){
  120235. sqlite3_str_appendf(&acc, "=%Q", pCsr->azArg[0]);
  120236. }
  120237. zSql = sqlite3StrAccumFinish(&acc);
  120238. if( zSql==0 ) return SQLITE_NOMEM;
  120239. rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pCsr->pPragma, 0);
  120240. sqlite3_free(zSql);
  120241. if( rc!=SQLITE_OK ){
  120242. pTab->base.zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(pTab->db));
  120243. return rc;
  120244. }
  120245. return pragmaVtabNext(pVtabCursor);
  120246. }
  120247. /*
  120248. ** Pragma virtual table module xEof method.
  120249. */
  120250. static int pragmaVtabEof(sqlite3_vtab_cursor *pVtabCursor){
  120251. PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
  120252. return (pCsr->pPragma==0);
  120253. }
  120254. /* The xColumn method simply returns the corresponding column from
  120255. ** the PRAGMA.
  120256. */
  120257. static int pragmaVtabColumn(
  120258. sqlite3_vtab_cursor *pVtabCursor,
  120259. sqlite3_context *ctx,
  120260. int i
  120261. ){
  120262. PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
  120263. PragmaVtab *pTab = (PragmaVtab*)(pVtabCursor->pVtab);
  120264. if( i<pTab->iHidden ){
  120265. sqlite3_result_value(ctx, sqlite3_column_value(pCsr->pPragma, i));
  120266. }else{
  120267. sqlite3_result_text(ctx, pCsr->azArg[i-pTab->iHidden],-1,SQLITE_TRANSIENT);
  120268. }
  120269. return SQLITE_OK;
  120270. }
  120271. /*
  120272. ** Pragma virtual table module xRowid method.
  120273. */
  120274. static int pragmaVtabRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *p){
  120275. PragmaVtabCursor *pCsr = (PragmaVtabCursor*)pVtabCursor;
  120276. *p = pCsr->iRowid;
  120277. return SQLITE_OK;
  120278. }
  120279. /* The pragma virtual table object */
  120280. static const sqlite3_module pragmaVtabModule = {
  120281. 0, /* iVersion */
  120282. 0, /* xCreate - create a table */
  120283. pragmaVtabConnect, /* xConnect - connect to an existing table */
  120284. pragmaVtabBestIndex, /* xBestIndex - Determine search strategy */
  120285. pragmaVtabDisconnect, /* xDisconnect - Disconnect from a table */
  120286. 0, /* xDestroy - Drop a table */
  120287. pragmaVtabOpen, /* xOpen - open a cursor */
  120288. pragmaVtabClose, /* xClose - close a cursor */
  120289. pragmaVtabFilter, /* xFilter - configure scan constraints */
  120290. pragmaVtabNext, /* xNext - advance a cursor */
  120291. pragmaVtabEof, /* xEof */
  120292. pragmaVtabColumn, /* xColumn - read data */
  120293. pragmaVtabRowid, /* xRowid - read data */
  120294. 0, /* xUpdate - write data */
  120295. 0, /* xBegin - begin transaction */
  120296. 0, /* xSync - sync transaction */
  120297. 0, /* xCommit - commit transaction */
  120298. 0, /* xRollback - rollback transaction */
  120299. 0, /* xFindFunction - function overloading */
  120300. 0, /* xRename - rename the table */
  120301. 0, /* xSavepoint */
  120302. 0, /* xRelease */
  120303. 0, /* xRollbackTo */
  120304. 0 /* xShadowName */
  120305. };
  120306. /*
  120307. ** Check to see if zTabName is really the name of a pragma. If it is,
  120308. ** then register an eponymous virtual table for that pragma and return
  120309. ** a pointer to the Module object for the new virtual table.
  120310. */
  120311. SQLITE_PRIVATE Module *sqlite3PragmaVtabRegister(sqlite3 *db, const char *zName){
  120312. const PragmaName *pName;
  120313. assert( sqlite3_strnicmp(zName, "pragma_", 7)==0 );
  120314. pName = pragmaLocate(zName+7);
  120315. if( pName==0 ) return 0;
  120316. if( (pName->mPragFlg & (PragFlg_Result0|PragFlg_Result1))==0 ) return 0;
  120317. assert( sqlite3HashFind(&db->aModule, zName)==0 );
  120318. return sqlite3VtabCreateModule(db, zName, &pragmaVtabModule, (void*)pName, 0);
  120319. }
  120320. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  120321. #endif /* SQLITE_OMIT_PRAGMA */
  120322. /************** End of pragma.c **********************************************/
  120323. /************** Begin file prepare.c *****************************************/
  120324. /*
  120325. ** 2005 May 25
  120326. **
  120327. ** The author disclaims copyright to this source code. In place of
  120328. ** a legal notice, here is a blessing:
  120329. **
  120330. ** May you do good and not evil.
  120331. ** May you find forgiveness for yourself and forgive others.
  120332. ** May you share freely, never taking more than you give.
  120333. **
  120334. *************************************************************************
  120335. ** This file contains the implementation of the sqlite3_prepare()
  120336. ** interface, and routines that contribute to loading the database schema
  120337. ** from disk.
  120338. */
  120339. /* #include "sqliteInt.h" */
  120340. /*
  120341. ** Fill the InitData structure with an error message that indicates
  120342. ** that the database is corrupt.
  120343. */
  120344. static void corruptSchema(
  120345. InitData *pData, /* Initialization context */
  120346. const char *zObj, /* Object being parsed at the point of error */
  120347. const char *zExtra /* Error information */
  120348. ){
  120349. sqlite3 *db = pData->db;
  120350. if( db->mallocFailed ){
  120351. pData->rc = SQLITE_NOMEM_BKPT;
  120352. }else if( pData->pzErrMsg[0]!=0 ){
  120353. /* A error message has already been generated. Do not overwrite it */
  120354. }else if( pData->mInitFlags & INITFLAG_AlterTable ){
  120355. *pData->pzErrMsg = sqlite3DbStrDup(db, zExtra);
  120356. pData->rc = SQLITE_ERROR;
  120357. }else if( db->flags & SQLITE_WriteSchema ){
  120358. pData->rc = SQLITE_CORRUPT_BKPT;
  120359. }else{
  120360. char *z;
  120361. if( zObj==0 ) zObj = "?";
  120362. z = sqlite3MPrintf(db, "malformed database schema (%s)", zObj);
  120363. if( zExtra && zExtra[0] ) z = sqlite3MPrintf(db, "%z - %s", z, zExtra);
  120364. *pData->pzErrMsg = z;
  120365. pData->rc = SQLITE_CORRUPT_BKPT;
  120366. }
  120367. }
  120368. /*
  120369. ** Check to see if any sibling index (another index on the same table)
  120370. ** of pIndex has the same root page number, and if it does, return true.
  120371. ** This would indicate a corrupt schema.
  120372. */
  120373. SQLITE_PRIVATE int sqlite3IndexHasDuplicateRootPage(Index *pIndex){
  120374. Index *p;
  120375. for(p=pIndex->pTable->pIndex; p; p=p->pNext){
  120376. if( p->tnum==pIndex->tnum && p!=pIndex ) return 1;
  120377. }
  120378. return 0;
  120379. }
  120380. /* forward declaration */
  120381. static int sqlite3Prepare(
  120382. sqlite3 *db, /* Database handle. */
  120383. const char *zSql, /* UTF-8 encoded SQL statement. */
  120384. int nBytes, /* Length of zSql in bytes. */
  120385. u32 prepFlags, /* Zero or more SQLITE_PREPARE_* flags */
  120386. Vdbe *pReprepare, /* VM being reprepared */
  120387. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  120388. const char **pzTail /* OUT: End of parsed string */
  120389. );
  120390. /*
  120391. ** This is the callback routine for the code that initializes the
  120392. ** database. See sqlite3Init() below for additional information.
  120393. ** This routine is also called from the OP_ParseSchema opcode of the VDBE.
  120394. **
  120395. ** Each callback contains the following information:
  120396. **
  120397. ** argv[0] = type of object: "table", "index", "trigger", or "view".
  120398. ** argv[1] = name of thing being created
  120399. ** argv[2] = associated table if an index or trigger
  120400. ** argv[3] = root page number for table or index. 0 for trigger or view.
  120401. ** argv[4] = SQL text for the CREATE statement.
  120402. **
  120403. */
  120404. SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){
  120405. InitData *pData = (InitData*)pInit;
  120406. sqlite3 *db = pData->db;
  120407. int iDb = pData->iDb;
  120408. assert( argc==5 );
  120409. UNUSED_PARAMETER2(NotUsed, argc);
  120410. assert( sqlite3_mutex_held(db->mutex) );
  120411. db->mDbFlags |= DBFLAG_EncodingFixed;
  120412. pData->nInitRow++;
  120413. if( db->mallocFailed ){
  120414. corruptSchema(pData, argv[1], 0);
  120415. return 1;
  120416. }
  120417. assert( iDb>=0 && iDb<db->nDb );
  120418. if( argv==0 ) return 0; /* Might happen if EMPTY_RESULT_CALLBACKS are on */
  120419. if( argv[3]==0 ){
  120420. corruptSchema(pData, argv[1], 0);
  120421. }else if( sqlite3_strnicmp(argv[4],"create ",7)==0 ){
  120422. /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
  120423. ** But because db->init.busy is set to 1, no VDBE code is generated
  120424. ** or executed. All the parser does is build the internal data
  120425. ** structures that describe the table, index, or view.
  120426. */
  120427. int rc;
  120428. u8 saved_iDb = db->init.iDb;
  120429. sqlite3_stmt *pStmt;
  120430. TESTONLY(int rcp); /* Return code from sqlite3_prepare() */
  120431. assert( db->init.busy );
  120432. db->init.iDb = iDb;
  120433. db->init.newTnum = sqlite3Atoi(argv[3]);
  120434. db->init.orphanTrigger = 0;
  120435. db->init.azInit = argv;
  120436. pStmt = 0;
  120437. TESTONLY(rcp = ) sqlite3Prepare(db, argv[4], -1, 0, 0, &pStmt, 0);
  120438. rc = db->errCode;
  120439. assert( (rc&0xFF)==(rcp&0xFF) );
  120440. db->init.iDb = saved_iDb;
  120441. /* assert( saved_iDb==0 || (db->mDbFlags & DBFLAG_Vacuum)!=0 ); */
  120442. if( SQLITE_OK!=rc ){
  120443. if( db->init.orphanTrigger ){
  120444. assert( iDb==1 );
  120445. }else{
  120446. if( rc > pData->rc ) pData->rc = rc;
  120447. if( rc==SQLITE_NOMEM ){
  120448. sqlite3OomFault(db);
  120449. }else if( rc!=SQLITE_INTERRUPT && (rc&0xFF)!=SQLITE_LOCKED ){
  120450. corruptSchema(pData, argv[1], sqlite3_errmsg(db));
  120451. }
  120452. }
  120453. }
  120454. sqlite3_finalize(pStmt);
  120455. }else if( argv[1]==0 || (argv[4]!=0 && argv[4][0]!=0) ){
  120456. corruptSchema(pData, argv[1], 0);
  120457. }else{
  120458. /* If the SQL column is blank it means this is an index that
  120459. ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
  120460. ** constraint for a CREATE TABLE. The index should have already
  120461. ** been created when we processed the CREATE TABLE. All we have
  120462. ** to do here is record the root page number for that index.
  120463. */
  120464. Index *pIndex;
  120465. pIndex = sqlite3FindIndex(db, argv[1], db->aDb[iDb].zDbSName);
  120466. if( pIndex==0
  120467. || sqlite3GetInt32(argv[3],&pIndex->tnum)==0
  120468. || pIndex->tnum<2
  120469. || sqlite3IndexHasDuplicateRootPage(pIndex)
  120470. ){
  120471. corruptSchema(pData, argv[1], pIndex?"invalid rootpage":"orphan index");
  120472. }
  120473. }
  120474. return 0;
  120475. }
  120476. /*
  120477. ** Attempt to read the database schema and initialize internal
  120478. ** data structures for a single database file. The index of the
  120479. ** database file is given by iDb. iDb==0 is used for the main
  120480. ** database. iDb==1 should never be used. iDb>=2 is used for
  120481. ** auxiliary databases. Return one of the SQLITE_ error codes to
  120482. ** indicate success or failure.
  120483. */
  120484. SQLITE_PRIVATE int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg, u32 mFlags){
  120485. int rc;
  120486. int i;
  120487. #ifndef SQLITE_OMIT_DEPRECATED
  120488. int size;
  120489. #endif
  120490. Db *pDb;
  120491. char const *azArg[6];
  120492. int meta[5];
  120493. InitData initData;
  120494. const char *zMasterName;
  120495. int openedTransaction = 0;
  120496. int mask = ((db->mDbFlags & DBFLAG_EncodingFixed) | ~DBFLAG_EncodingFixed);
  120497. assert( (db->mDbFlags & DBFLAG_SchemaKnownOk)==0 );
  120498. assert( iDb>=0 && iDb<db->nDb );
  120499. assert( db->aDb[iDb].pSchema );
  120500. assert( sqlite3_mutex_held(db->mutex) );
  120501. assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
  120502. db->init.busy = 1;
  120503. /* Construct the in-memory representation schema tables (sqlite_master or
  120504. ** sqlite_temp_master) by invoking the parser directly. The appropriate
  120505. ** table name will be inserted automatically by the parser so we can just
  120506. ** use the abbreviation "x" here. The parser will also automatically tag
  120507. ** the schema table as read-only. */
  120508. azArg[0] = "table";
  120509. azArg[1] = zMasterName = SCHEMA_TABLE(iDb);
  120510. azArg[2] = azArg[1];
  120511. azArg[3] = "1";
  120512. azArg[4] = "CREATE TABLE x(type text,name text,tbl_name text,"
  120513. "rootpage int,sql text)";
  120514. azArg[5] = 0;
  120515. initData.db = db;
  120516. initData.iDb = iDb;
  120517. initData.rc = SQLITE_OK;
  120518. initData.pzErrMsg = pzErrMsg;
  120519. initData.mInitFlags = mFlags;
  120520. initData.nInitRow = 0;
  120521. sqlite3InitCallback(&initData, 5, (char **)azArg, 0);
  120522. db->mDbFlags &= mask;
  120523. if( initData.rc ){
  120524. rc = initData.rc;
  120525. goto error_out;
  120526. }
  120527. /* Create a cursor to hold the database open
  120528. */
  120529. pDb = &db->aDb[iDb];
  120530. if( pDb->pBt==0 ){
  120531. assert( iDb==1 );
  120532. DbSetProperty(db, 1, DB_SchemaLoaded);
  120533. rc = SQLITE_OK;
  120534. goto error_out;
  120535. }
  120536. /* If there is not already a read-only (or read-write) transaction opened
  120537. ** on the b-tree database, open one now. If a transaction is opened, it
  120538. ** will be closed before this function returns. */
  120539. sqlite3BtreeEnter(pDb->pBt);
  120540. if( !sqlite3BtreeIsInReadTrans(pDb->pBt) ){
  120541. rc = sqlite3BtreeBeginTrans(pDb->pBt, 0, 0);
  120542. if( rc!=SQLITE_OK ){
  120543. sqlite3SetString(pzErrMsg, db, sqlite3ErrStr(rc));
  120544. goto initone_error_out;
  120545. }
  120546. openedTransaction = 1;
  120547. }
  120548. /* Get the database meta information.
  120549. **
  120550. ** Meta values are as follows:
  120551. ** meta[0] Schema cookie. Changes with each schema change.
  120552. ** meta[1] File format of schema layer.
  120553. ** meta[2] Size of the page cache.
  120554. ** meta[3] Largest rootpage (auto/incr_vacuum mode)
  120555. ** meta[4] Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
  120556. ** meta[5] User version
  120557. ** meta[6] Incremental vacuum mode
  120558. ** meta[7] unused
  120559. ** meta[8] unused
  120560. ** meta[9] unused
  120561. **
  120562. ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
  120563. ** the possible values of meta[4].
  120564. */
  120565. for(i=0; i<ArraySize(meta); i++){
  120566. sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
  120567. }
  120568. if( (db->flags & SQLITE_ResetDatabase)!=0 ){
  120569. memset(meta, 0, sizeof(meta));
  120570. }
  120571. pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1];
  120572. /* If opening a non-empty database, check the text encoding. For the
  120573. ** main database, set sqlite3.enc to the encoding of the main database.
  120574. ** For an attached db, it is an error if the encoding is not the same
  120575. ** as sqlite3.enc.
  120576. */
  120577. if( meta[BTREE_TEXT_ENCODING-1] ){ /* text encoding */
  120578. if( iDb==0 && (db->mDbFlags & DBFLAG_EncodingFixed)==0 ){
  120579. u8 encoding;
  120580. #ifndef SQLITE_OMIT_UTF16
  120581. /* If opening the main database, set ENC(db). */
  120582. encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;
  120583. if( encoding==0 ) encoding = SQLITE_UTF8;
  120584. #else
  120585. encoding = SQLITE_UTF8;
  120586. #endif
  120587. sqlite3SetTextEncoding(db, encoding);
  120588. }else{
  120589. /* If opening an attached database, the encoding much match ENC(db) */
  120590. if( (meta[BTREE_TEXT_ENCODING-1] & 3)!=ENC(db) ){
  120591. sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
  120592. " text encoding as main database");
  120593. rc = SQLITE_ERROR;
  120594. goto initone_error_out;
  120595. }
  120596. }
  120597. }
  120598. pDb->pSchema->enc = ENC(db);
  120599. if( pDb->pSchema->cache_size==0 ){
  120600. #ifndef SQLITE_OMIT_DEPRECATED
  120601. size = sqlite3AbsInt32(meta[BTREE_DEFAULT_CACHE_SIZE-1]);
  120602. if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
  120603. pDb->pSchema->cache_size = size;
  120604. #else
  120605. pDb->pSchema->cache_size = SQLITE_DEFAULT_CACHE_SIZE;
  120606. #endif
  120607. sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
  120608. }
  120609. /*
  120610. ** file_format==1 Version 3.0.0.
  120611. ** file_format==2 Version 3.1.3. // ALTER TABLE ADD COLUMN
  120612. ** file_format==3 Version 3.1.4. // ditto but with non-NULL defaults
  120613. ** file_format==4 Version 3.3.0. // DESC indices. Boolean constants
  120614. */
  120615. pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1];
  120616. if( pDb->pSchema->file_format==0 ){
  120617. pDb->pSchema->file_format = 1;
  120618. }
  120619. if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
  120620. sqlite3SetString(pzErrMsg, db, "unsupported file format");
  120621. rc = SQLITE_ERROR;
  120622. goto initone_error_out;
  120623. }
  120624. /* Ticket #2804: When we open a database in the newer file format,
  120625. ** clear the legacy_file_format pragma flag so that a VACUUM will
  120626. ** not downgrade the database and thus invalidate any descending
  120627. ** indices that the user might have created.
  120628. */
  120629. if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){
  120630. db->flags &= ~(u64)SQLITE_LegacyFileFmt;
  120631. }
  120632. /* Read the schema information out of the schema tables
  120633. */
  120634. assert( db->init.busy );
  120635. {
  120636. char *zSql;
  120637. zSql = sqlite3MPrintf(db,
  120638. "SELECT*FROM\"%w\".%s ORDER BY rowid",
  120639. db->aDb[iDb].zDbSName, zMasterName);
  120640. #ifndef SQLITE_OMIT_AUTHORIZATION
  120641. {
  120642. sqlite3_xauth xAuth;
  120643. xAuth = db->xAuth;
  120644. db->xAuth = 0;
  120645. #endif
  120646. rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
  120647. #ifndef SQLITE_OMIT_AUTHORIZATION
  120648. db->xAuth = xAuth;
  120649. }
  120650. #endif
  120651. if( rc==SQLITE_OK ) rc = initData.rc;
  120652. sqlite3DbFree(db, zSql);
  120653. #ifndef SQLITE_OMIT_ANALYZE
  120654. if( rc==SQLITE_OK ){
  120655. sqlite3AnalysisLoad(db, iDb);
  120656. }
  120657. #endif
  120658. }
  120659. if( db->mallocFailed ){
  120660. rc = SQLITE_NOMEM_BKPT;
  120661. sqlite3ResetAllSchemasOfConnection(db);
  120662. }
  120663. if( rc==SQLITE_OK || (db->flags&SQLITE_NoSchemaError)){
  120664. /* Black magic: If the SQLITE_NoSchemaError flag is set, then consider
  120665. ** the schema loaded, even if errors occurred. In this situation the
  120666. ** current sqlite3_prepare() operation will fail, but the following one
  120667. ** will attempt to compile the supplied statement against whatever subset
  120668. ** of the schema was loaded before the error occurred. The primary
  120669. ** purpose of this is to allow access to the sqlite_master table
  120670. ** even when its contents have been corrupted.
  120671. */
  120672. DbSetProperty(db, iDb, DB_SchemaLoaded);
  120673. rc = SQLITE_OK;
  120674. }
  120675. /* Jump here for an error that occurs after successfully allocating
  120676. ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
  120677. ** before that point, jump to error_out.
  120678. */
  120679. initone_error_out:
  120680. if( openedTransaction ){
  120681. sqlite3BtreeCommit(pDb->pBt);
  120682. }
  120683. sqlite3BtreeLeave(pDb->pBt);
  120684. error_out:
  120685. if( rc ){
  120686. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
  120687. sqlite3OomFault(db);
  120688. }
  120689. sqlite3ResetOneSchema(db, iDb);
  120690. }
  120691. db->init.busy = 0;
  120692. return rc;
  120693. }
  120694. /*
  120695. ** Initialize all database files - the main database file, the file
  120696. ** used to store temporary tables, and any additional database files
  120697. ** created using ATTACH statements. Return a success code. If an
  120698. ** error occurs, write an error message into *pzErrMsg.
  120699. **
  120700. ** After a database is initialized, the DB_SchemaLoaded bit is set
  120701. ** bit is set in the flags field of the Db structure.
  120702. */
  120703. SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){
  120704. int i, rc;
  120705. int commit_internal = !(db->mDbFlags&DBFLAG_SchemaChange);
  120706. assert( sqlite3_mutex_held(db->mutex) );
  120707. assert( sqlite3BtreeHoldsMutex(db->aDb[0].pBt) );
  120708. assert( db->init.busy==0 );
  120709. ENC(db) = SCHEMA_ENC(db);
  120710. assert( db->nDb>0 );
  120711. /* Do the main schema first */
  120712. if( !DbHasProperty(db, 0, DB_SchemaLoaded) ){
  120713. rc = sqlite3InitOne(db, 0, pzErrMsg, 0);
  120714. if( rc ) return rc;
  120715. }
  120716. /* All other schemas after the main schema. The "temp" schema must be last */
  120717. for(i=db->nDb-1; i>0; i--){
  120718. assert( i==1 || sqlite3BtreeHoldsMutex(db->aDb[i].pBt) );
  120719. if( !DbHasProperty(db, i, DB_SchemaLoaded) ){
  120720. rc = sqlite3InitOne(db, i, pzErrMsg, 0);
  120721. if( rc ) return rc;
  120722. }
  120723. }
  120724. if( commit_internal ){
  120725. sqlite3CommitInternalChanges(db);
  120726. }
  120727. return SQLITE_OK;
  120728. }
  120729. /*
  120730. ** This routine is a no-op if the database schema is already initialized.
  120731. ** Otherwise, the schema is loaded. An error code is returned.
  120732. */
  120733. SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){
  120734. int rc = SQLITE_OK;
  120735. sqlite3 *db = pParse->db;
  120736. assert( sqlite3_mutex_held(db->mutex) );
  120737. if( !db->init.busy ){
  120738. rc = sqlite3Init(db, &pParse->zErrMsg);
  120739. if( rc!=SQLITE_OK ){
  120740. pParse->rc = rc;
  120741. pParse->nErr++;
  120742. }else if( db->noSharedCache ){
  120743. db->mDbFlags |= DBFLAG_SchemaKnownOk;
  120744. }
  120745. }
  120746. return rc;
  120747. }
  120748. /*
  120749. ** Check schema cookies in all databases. If any cookie is out
  120750. ** of date set pParse->rc to SQLITE_SCHEMA. If all schema cookies
  120751. ** make no changes to pParse->rc.
  120752. */
  120753. static void schemaIsValid(Parse *pParse){
  120754. sqlite3 *db = pParse->db;
  120755. int iDb;
  120756. int rc;
  120757. int cookie;
  120758. assert( pParse->checkSchema );
  120759. assert( sqlite3_mutex_held(db->mutex) );
  120760. for(iDb=0; iDb<db->nDb; iDb++){
  120761. int openedTransaction = 0; /* True if a transaction is opened */
  120762. Btree *pBt = db->aDb[iDb].pBt; /* Btree database to read cookie from */
  120763. if( pBt==0 ) continue;
  120764. /* If there is not already a read-only (or read-write) transaction opened
  120765. ** on the b-tree database, open one now. If a transaction is opened, it
  120766. ** will be closed immediately after reading the meta-value. */
  120767. if( !sqlite3BtreeIsInReadTrans(pBt) ){
  120768. rc = sqlite3BtreeBeginTrans(pBt, 0, 0);
  120769. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
  120770. sqlite3OomFault(db);
  120771. }
  120772. if( rc!=SQLITE_OK ) return;
  120773. openedTransaction = 1;
  120774. }
  120775. /* Read the schema cookie from the database. If it does not match the
  120776. ** value stored as part of the in-memory schema representation,
  120777. ** set Parse.rc to SQLITE_SCHEMA. */
  120778. sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie);
  120779. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  120780. if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){
  120781. sqlite3ResetOneSchema(db, iDb);
  120782. pParse->rc = SQLITE_SCHEMA;
  120783. }
  120784. /* Close the transaction, if one was opened. */
  120785. if( openedTransaction ){
  120786. sqlite3BtreeCommit(pBt);
  120787. }
  120788. }
  120789. }
  120790. /*
  120791. ** Convert a schema pointer into the iDb index that indicates
  120792. ** which database file in db->aDb[] the schema refers to.
  120793. **
  120794. ** If the same database is attached more than once, the first
  120795. ** attached database is returned.
  120796. */
  120797. SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
  120798. int i = -1000000;
  120799. /* If pSchema is NULL, then return -1000000. This happens when code in
  120800. ** expr.c is trying to resolve a reference to a transient table (i.e. one
  120801. ** created by a sub-select). In this case the return value of this
  120802. ** function should never be used.
  120803. **
  120804. ** We return -1000000 instead of the more usual -1 simply because using
  120805. ** -1000000 as the incorrect index into db->aDb[] is much
  120806. ** more likely to cause a segfault than -1 (of course there are assert()
  120807. ** statements too, but it never hurts to play the odds).
  120808. */
  120809. assert( sqlite3_mutex_held(db->mutex) );
  120810. if( pSchema ){
  120811. for(i=0; 1; i++){
  120812. assert( i<db->nDb );
  120813. if( db->aDb[i].pSchema==pSchema ){
  120814. break;
  120815. }
  120816. }
  120817. assert( i>=0 && i<db->nDb );
  120818. }
  120819. return i;
  120820. }
  120821. /*
  120822. ** Free all memory allocations in the pParse object
  120823. */
  120824. SQLITE_PRIVATE void sqlite3ParserReset(Parse *pParse){
  120825. sqlite3 *db = pParse->db;
  120826. sqlite3DbFree(db, pParse->aLabel);
  120827. sqlite3ExprListDelete(db, pParse->pConstExpr);
  120828. if( db ){
  120829. assert( db->lookaside.bDisable >= pParse->disableLookaside );
  120830. db->lookaside.bDisable -= pParse->disableLookaside;
  120831. db->lookaside.sz = db->lookaside.bDisable ? 0 : db->lookaside.szTrue;
  120832. }
  120833. pParse->disableLookaside = 0;
  120834. }
  120835. /*
  120836. ** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
  120837. */
  120838. static int sqlite3Prepare(
  120839. sqlite3 *db, /* Database handle. */
  120840. const char *zSql, /* UTF-8 encoded SQL statement. */
  120841. int nBytes, /* Length of zSql in bytes. */
  120842. u32 prepFlags, /* Zero or more SQLITE_PREPARE_* flags */
  120843. Vdbe *pReprepare, /* VM being reprepared */
  120844. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  120845. const char **pzTail /* OUT: End of parsed string */
  120846. ){
  120847. char *zErrMsg = 0; /* Error message */
  120848. int rc = SQLITE_OK; /* Result code */
  120849. int i; /* Loop counter */
  120850. Parse sParse; /* Parsing context */
  120851. memset(&sParse, 0, PARSE_HDR_SZ);
  120852. memset(PARSE_TAIL(&sParse), 0, PARSE_TAIL_SZ);
  120853. sParse.pReprepare = pReprepare;
  120854. assert( ppStmt && *ppStmt==0 );
  120855. /* assert( !db->mallocFailed ); // not true with SQLITE_USE_ALLOCA */
  120856. assert( sqlite3_mutex_held(db->mutex) );
  120857. /* For a long-term use prepared statement avoid the use of
  120858. ** lookaside memory.
  120859. */
  120860. if( prepFlags & SQLITE_PREPARE_PERSISTENT ){
  120861. sParse.disableLookaside++;
  120862. DisableLookaside;
  120863. }
  120864. sParse.disableVtab = (prepFlags & SQLITE_PREPARE_NO_VTAB)!=0;
  120865. /* Check to verify that it is possible to get a read lock on all
  120866. ** database schemas. The inability to get a read lock indicates that
  120867. ** some other database connection is holding a write-lock, which in
  120868. ** turn means that the other connection has made uncommitted changes
  120869. ** to the schema.
  120870. **
  120871. ** Were we to proceed and prepare the statement against the uncommitted
  120872. ** schema changes and if those schema changes are subsequently rolled
  120873. ** back and different changes are made in their place, then when this
  120874. ** prepared statement goes to run the schema cookie would fail to detect
  120875. ** the schema change. Disaster would follow.
  120876. **
  120877. ** This thread is currently holding mutexes on all Btrees (because
  120878. ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it
  120879. ** is not possible for another thread to start a new schema change
  120880. ** while this routine is running. Hence, we do not need to hold
  120881. ** locks on the schema, we just need to make sure nobody else is
  120882. ** holding them.
  120883. **
  120884. ** Note that setting READ_UNCOMMITTED overrides most lock detection,
  120885. ** but it does *not* override schema lock detection, so this all still
  120886. ** works even if READ_UNCOMMITTED is set.
  120887. */
  120888. if( !db->noSharedCache ){
  120889. for(i=0; i<db->nDb; i++) {
  120890. Btree *pBt = db->aDb[i].pBt;
  120891. if( pBt ){
  120892. assert( sqlite3BtreeHoldsMutex(pBt) );
  120893. rc = sqlite3BtreeSchemaLocked(pBt);
  120894. if( rc ){
  120895. const char *zDb = db->aDb[i].zDbSName;
  120896. sqlite3ErrorWithMsg(db, rc, "database schema is locked: %s", zDb);
  120897. testcase( db->flags & SQLITE_ReadUncommit );
  120898. goto end_prepare;
  120899. }
  120900. }
  120901. }
  120902. }
  120903. sqlite3VtabUnlockList(db);
  120904. sParse.db = db;
  120905. if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
  120906. char *zSqlCopy;
  120907. int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
  120908. testcase( nBytes==mxLen );
  120909. testcase( nBytes==mxLen+1 );
  120910. if( nBytes>mxLen ){
  120911. sqlite3ErrorWithMsg(db, SQLITE_TOOBIG, "statement too long");
  120912. rc = sqlite3ApiExit(db, SQLITE_TOOBIG);
  120913. goto end_prepare;
  120914. }
  120915. zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
  120916. if( zSqlCopy ){
  120917. sqlite3RunParser(&sParse, zSqlCopy, &zErrMsg);
  120918. sParse.zTail = &zSql[sParse.zTail-zSqlCopy];
  120919. sqlite3DbFree(db, zSqlCopy);
  120920. }else{
  120921. sParse.zTail = &zSql[nBytes];
  120922. }
  120923. }else{
  120924. sqlite3RunParser(&sParse, zSql, &zErrMsg);
  120925. }
  120926. assert( 0==sParse.nQueryLoop );
  120927. if( sParse.rc==SQLITE_DONE ){
  120928. sParse.rc = SQLITE_OK;
  120929. }
  120930. if( sParse.checkSchema ){
  120931. schemaIsValid(&sParse);
  120932. }
  120933. if( pzTail ){
  120934. *pzTail = sParse.zTail;
  120935. }
  120936. if( db->init.busy==0 ){
  120937. sqlite3VdbeSetSql(sParse.pVdbe, zSql, (int)(sParse.zTail-zSql), prepFlags);
  120938. }
  120939. if( db->mallocFailed ){
  120940. sParse.rc = SQLITE_NOMEM_BKPT;
  120941. }
  120942. rc = sParse.rc;
  120943. if( rc!=SQLITE_OK ){
  120944. if( sParse.pVdbe ) sqlite3VdbeFinalize(sParse.pVdbe);
  120945. assert(!(*ppStmt));
  120946. }else{
  120947. *ppStmt = (sqlite3_stmt*)sParse.pVdbe;
  120948. }
  120949. if( zErrMsg ){
  120950. sqlite3ErrorWithMsg(db, rc, "%s", zErrMsg);
  120951. sqlite3DbFree(db, zErrMsg);
  120952. }else{
  120953. sqlite3Error(db, rc);
  120954. }
  120955. /* Delete any TriggerPrg structures allocated while parsing this statement. */
  120956. while( sParse.pTriggerPrg ){
  120957. TriggerPrg *pT = sParse.pTriggerPrg;
  120958. sParse.pTriggerPrg = pT->pNext;
  120959. sqlite3DbFree(db, pT);
  120960. }
  120961. end_prepare:
  120962. sqlite3ParserReset(&sParse);
  120963. return rc;
  120964. }
  120965. static int sqlite3LockAndPrepare(
  120966. sqlite3 *db, /* Database handle. */
  120967. const char *zSql, /* UTF-8 encoded SQL statement. */
  120968. int nBytes, /* Length of zSql in bytes. */
  120969. u32 prepFlags, /* Zero or more SQLITE_PREPARE_* flags */
  120970. Vdbe *pOld, /* VM being reprepared */
  120971. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  120972. const char **pzTail /* OUT: End of parsed string */
  120973. ){
  120974. int rc;
  120975. int cnt = 0;
  120976. #ifdef SQLITE_ENABLE_API_ARMOR
  120977. if( ppStmt==0 ) return SQLITE_MISUSE_BKPT;
  120978. #endif
  120979. *ppStmt = 0;
  120980. if( !sqlite3SafetyCheckOk(db)||zSql==0 ){
  120981. return SQLITE_MISUSE_BKPT;
  120982. }
  120983. sqlite3_mutex_enter(db->mutex);
  120984. sqlite3BtreeEnterAll(db);
  120985. do{
  120986. /* Make multiple attempts to compile the SQL, until it either succeeds
  120987. ** or encounters a permanent error. A schema problem after one schema
  120988. ** reset is considered a permanent error. */
  120989. rc = sqlite3Prepare(db, zSql, nBytes, prepFlags, pOld, ppStmt, pzTail);
  120990. assert( rc==SQLITE_OK || *ppStmt==0 );
  120991. }while( rc==SQLITE_ERROR_RETRY
  120992. || (rc==SQLITE_SCHEMA && (sqlite3ResetOneSchema(db,-1), cnt++)==0) );
  120993. sqlite3BtreeLeaveAll(db);
  120994. rc = sqlite3ApiExit(db, rc);
  120995. assert( (rc&db->errMask)==rc );
  120996. sqlite3_mutex_leave(db->mutex);
  120997. return rc;
  120998. }
  120999. /*
  121000. ** Rerun the compilation of a statement after a schema change.
  121001. **
  121002. ** If the statement is successfully recompiled, return SQLITE_OK. Otherwise,
  121003. ** if the statement cannot be recompiled because another connection has
  121004. ** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error
  121005. ** occurs, return SQLITE_SCHEMA.
  121006. */
  121007. SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){
  121008. int rc;
  121009. sqlite3_stmt *pNew;
  121010. const char *zSql;
  121011. sqlite3 *db;
  121012. u8 prepFlags;
  121013. assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
  121014. zSql = sqlite3_sql((sqlite3_stmt *)p);
  121015. assert( zSql!=0 ); /* Reprepare only called for prepare_v2() statements */
  121016. db = sqlite3VdbeDb(p);
  121017. assert( sqlite3_mutex_held(db->mutex) );
  121018. prepFlags = sqlite3VdbePrepareFlags(p);
  121019. rc = sqlite3LockAndPrepare(db, zSql, -1, prepFlags, p, &pNew, 0);
  121020. if( rc ){
  121021. if( rc==SQLITE_NOMEM ){
  121022. sqlite3OomFault(db);
  121023. }
  121024. assert( pNew==0 );
  121025. return rc;
  121026. }else{
  121027. assert( pNew!=0 );
  121028. }
  121029. sqlite3VdbeSwap((Vdbe*)pNew, p);
  121030. sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);
  121031. sqlite3VdbeResetStepResult((Vdbe*)pNew);
  121032. sqlite3VdbeFinalize((Vdbe*)pNew);
  121033. return SQLITE_OK;
  121034. }
  121035. /*
  121036. ** Two versions of the official API. Legacy and new use. In the legacy
  121037. ** version, the original SQL text is not saved in the prepared statement
  121038. ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
  121039. ** sqlite3_step(). In the new version, the original SQL text is retained
  121040. ** and the statement is automatically recompiled if an schema change
  121041. ** occurs.
  121042. */
  121043. SQLITE_API int sqlite3_prepare(
  121044. sqlite3 *db, /* Database handle. */
  121045. const char *zSql, /* UTF-8 encoded SQL statement. */
  121046. int nBytes, /* Length of zSql in bytes. */
  121047. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  121048. const char **pzTail /* OUT: End of parsed string */
  121049. ){
  121050. int rc;
  121051. rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail);
  121052. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  121053. return rc;
  121054. }
  121055. SQLITE_API int sqlite3_prepare_v2(
  121056. sqlite3 *db, /* Database handle. */
  121057. const char *zSql, /* UTF-8 encoded SQL statement. */
  121058. int nBytes, /* Length of zSql in bytes. */
  121059. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  121060. const char **pzTail /* OUT: End of parsed string */
  121061. ){
  121062. int rc;
  121063. /* EVIDENCE-OF: R-37923-12173 The sqlite3_prepare_v2() interface works
  121064. ** exactly the same as sqlite3_prepare_v3() with a zero prepFlags
  121065. ** parameter.
  121066. **
  121067. ** Proof in that the 5th parameter to sqlite3LockAndPrepare is 0 */
  121068. rc = sqlite3LockAndPrepare(db,zSql,nBytes,SQLITE_PREPARE_SAVESQL,0,
  121069. ppStmt,pzTail);
  121070. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );
  121071. return rc;
  121072. }
  121073. SQLITE_API int sqlite3_prepare_v3(
  121074. sqlite3 *db, /* Database handle. */
  121075. const char *zSql, /* UTF-8 encoded SQL statement. */
  121076. int nBytes, /* Length of zSql in bytes. */
  121077. unsigned int prepFlags, /* Zero or more SQLITE_PREPARE_* flags */
  121078. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  121079. const char **pzTail /* OUT: End of parsed string */
  121080. ){
  121081. int rc;
  121082. /* EVIDENCE-OF: R-56861-42673 sqlite3_prepare_v3() differs from
  121083. ** sqlite3_prepare_v2() only in having the extra prepFlags parameter,
  121084. ** which is a bit array consisting of zero or more of the
  121085. ** SQLITE_PREPARE_* flags.
  121086. **
  121087. ** Proof by comparison to the implementation of sqlite3_prepare_v2()
  121088. ** directly above. */
  121089. rc = sqlite3LockAndPrepare(db,zSql,nBytes,
  121090. SQLITE_PREPARE_SAVESQL|(prepFlags&SQLITE_PREPARE_MASK),
  121091. 0,ppStmt,pzTail);
  121092. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );
  121093. return rc;
  121094. }
  121095. #ifndef SQLITE_OMIT_UTF16
  121096. /*
  121097. ** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
  121098. */
  121099. static int sqlite3Prepare16(
  121100. sqlite3 *db, /* Database handle. */
  121101. const void *zSql, /* UTF-16 encoded SQL statement. */
  121102. int nBytes, /* Length of zSql in bytes. */
  121103. u32 prepFlags, /* Zero or more SQLITE_PREPARE_* flags */
  121104. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  121105. const void **pzTail /* OUT: End of parsed string */
  121106. ){
  121107. /* This function currently works by first transforming the UTF-16
  121108. ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
  121109. ** tricky bit is figuring out the pointer to return in *pzTail.
  121110. */
  121111. char *zSql8;
  121112. const char *zTail8 = 0;
  121113. int rc = SQLITE_OK;
  121114. #ifdef SQLITE_ENABLE_API_ARMOR
  121115. if( ppStmt==0 ) return SQLITE_MISUSE_BKPT;
  121116. #endif
  121117. *ppStmt = 0;
  121118. if( !sqlite3SafetyCheckOk(db)||zSql==0 ){
  121119. return SQLITE_MISUSE_BKPT;
  121120. }
  121121. if( nBytes>=0 ){
  121122. int sz;
  121123. const char *z = (const char*)zSql;
  121124. for(sz=0; sz<nBytes && (z[sz]!=0 || z[sz+1]!=0); sz += 2){}
  121125. nBytes = sz;
  121126. }
  121127. sqlite3_mutex_enter(db->mutex);
  121128. zSql8 = sqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE);
  121129. if( zSql8 ){
  121130. rc = sqlite3LockAndPrepare(db, zSql8, -1, prepFlags, 0, ppStmt, &zTail8);
  121131. }
  121132. if( zTail8 && pzTail ){
  121133. /* If sqlite3_prepare returns a tail pointer, we calculate the
  121134. ** equivalent pointer into the UTF-16 string by counting the unicode
  121135. ** characters between zSql8 and zTail8, and then returning a pointer
  121136. ** the same number of characters into the UTF-16 string.
  121137. */
  121138. int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
  121139. *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
  121140. }
  121141. sqlite3DbFree(db, zSql8);
  121142. rc = sqlite3ApiExit(db, rc);
  121143. sqlite3_mutex_leave(db->mutex);
  121144. return rc;
  121145. }
  121146. /*
  121147. ** Two versions of the official API. Legacy and new use. In the legacy
  121148. ** version, the original SQL text is not saved in the prepared statement
  121149. ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
  121150. ** sqlite3_step(). In the new version, the original SQL text is retained
  121151. ** and the statement is automatically recompiled if an schema change
  121152. ** occurs.
  121153. */
  121154. SQLITE_API int sqlite3_prepare16(
  121155. sqlite3 *db, /* Database handle. */
  121156. const void *zSql, /* UTF-16 encoded SQL statement. */
  121157. int nBytes, /* Length of zSql in bytes. */
  121158. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  121159. const void **pzTail /* OUT: End of parsed string */
  121160. ){
  121161. int rc;
  121162. rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
  121163. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  121164. return rc;
  121165. }
  121166. SQLITE_API int sqlite3_prepare16_v2(
  121167. sqlite3 *db, /* Database handle. */
  121168. const void *zSql, /* UTF-16 encoded SQL statement. */
  121169. int nBytes, /* Length of zSql in bytes. */
  121170. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  121171. const void **pzTail /* OUT: End of parsed string */
  121172. ){
  121173. int rc;
  121174. rc = sqlite3Prepare16(db,zSql,nBytes,SQLITE_PREPARE_SAVESQL,ppStmt,pzTail);
  121175. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  121176. return rc;
  121177. }
  121178. SQLITE_API int sqlite3_prepare16_v3(
  121179. sqlite3 *db, /* Database handle. */
  121180. const void *zSql, /* UTF-16 encoded SQL statement. */
  121181. int nBytes, /* Length of zSql in bytes. */
  121182. unsigned int prepFlags, /* Zero or more SQLITE_PREPARE_* flags */
  121183. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  121184. const void **pzTail /* OUT: End of parsed string */
  121185. ){
  121186. int rc;
  121187. rc = sqlite3Prepare16(db,zSql,nBytes,
  121188. SQLITE_PREPARE_SAVESQL|(prepFlags&SQLITE_PREPARE_MASK),
  121189. ppStmt,pzTail);
  121190. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  121191. return rc;
  121192. }
  121193. #endif /* SQLITE_OMIT_UTF16 */
  121194. /************** End of prepare.c *********************************************/
  121195. /************** Begin file select.c ******************************************/
  121196. /*
  121197. ** 2001 September 15
  121198. **
  121199. ** The author disclaims copyright to this source code. In place of
  121200. ** a legal notice, here is a blessing:
  121201. **
  121202. ** May you do good and not evil.
  121203. ** May you find forgiveness for yourself and forgive others.
  121204. ** May you share freely, never taking more than you give.
  121205. **
  121206. *************************************************************************
  121207. ** This file contains C code routines that are called by the parser
  121208. ** to handle SELECT statements in SQLite.
  121209. */
  121210. /* #include "sqliteInt.h" */
  121211. /*
  121212. ** Trace output macros
  121213. */
  121214. #if SELECTTRACE_ENABLED
  121215. /***/ int sqlite3SelectTrace = 0;
  121216. # define SELECTTRACE(K,P,S,X) \
  121217. if(sqlite3SelectTrace&(K)) \
  121218. sqlite3DebugPrintf("%u/%d/%p: ",(S)->selId,(P)->addrExplain,(S)),\
  121219. sqlite3DebugPrintf X
  121220. #else
  121221. # define SELECTTRACE(K,P,S,X)
  121222. #endif
  121223. /*
  121224. ** An instance of the following object is used to record information about
  121225. ** how to process the DISTINCT keyword, to simplify passing that information
  121226. ** into the selectInnerLoop() routine.
  121227. */
  121228. typedef struct DistinctCtx DistinctCtx;
  121229. struct DistinctCtx {
  121230. u8 isTnct; /* True if the DISTINCT keyword is present */
  121231. u8 eTnctType; /* One of the WHERE_DISTINCT_* operators */
  121232. int tabTnct; /* Ephemeral table used for DISTINCT processing */
  121233. int addrTnct; /* Address of OP_OpenEphemeral opcode for tabTnct */
  121234. };
  121235. /*
  121236. ** An instance of the following object is used to record information about
  121237. ** the ORDER BY (or GROUP BY) clause of query is being coded.
  121238. **
  121239. ** The aDefer[] array is used by the sorter-references optimization. For
  121240. ** example, assuming there is no index that can be used for the ORDER BY,
  121241. ** for the query:
  121242. **
  121243. ** SELECT a, bigblob FROM t1 ORDER BY a LIMIT 10;
  121244. **
  121245. ** it may be more efficient to add just the "a" values to the sorter, and
  121246. ** retrieve the associated "bigblob" values directly from table t1 as the
  121247. ** 10 smallest "a" values are extracted from the sorter.
  121248. **
  121249. ** When the sorter-reference optimization is used, there is one entry in the
  121250. ** aDefer[] array for each database table that may be read as values are
  121251. ** extracted from the sorter.
  121252. */
  121253. typedef struct SortCtx SortCtx;
  121254. struct SortCtx {
  121255. ExprList *pOrderBy; /* The ORDER BY (or GROUP BY clause) */
  121256. int nOBSat; /* Number of ORDER BY terms satisfied by indices */
  121257. int iECursor; /* Cursor number for the sorter */
  121258. int regReturn; /* Register holding block-output return address */
  121259. int labelBkOut; /* Start label for the block-output subroutine */
  121260. int addrSortIndex; /* Address of the OP_SorterOpen or OP_OpenEphemeral */
  121261. int labelDone; /* Jump here when done, ex: LIMIT reached */
  121262. int labelOBLopt; /* Jump here when sorter is full */
  121263. u8 sortFlags; /* Zero or more SORTFLAG_* bits */
  121264. #ifdef SQLITE_ENABLE_SORTER_REFERENCES
  121265. u8 nDefer; /* Number of valid entries in aDefer[] */
  121266. struct DeferredCsr {
  121267. Table *pTab; /* Table definition */
  121268. int iCsr; /* Cursor number for table */
  121269. int nKey; /* Number of PK columns for table pTab (>=1) */
  121270. } aDefer[4];
  121271. #endif
  121272. struct RowLoadInfo *pDeferredRowLoad; /* Deferred row loading info or NULL */
  121273. };
  121274. #define SORTFLAG_UseSorter 0x01 /* Use SorterOpen instead of OpenEphemeral */
  121275. /*
  121276. ** Delete all the content of a Select structure. Deallocate the structure
  121277. ** itself depending on the value of bFree
  121278. **
  121279. ** If bFree==1, call sqlite3DbFree() on the p object.
  121280. ** If bFree==0, Leave the first Select object unfreed
  121281. */
  121282. static void clearSelect(sqlite3 *db, Select *p, int bFree){
  121283. while( p ){
  121284. Select *pPrior = p->pPrior;
  121285. sqlite3ExprListDelete(db, p->pEList);
  121286. sqlite3SrcListDelete(db, p->pSrc);
  121287. sqlite3ExprDelete(db, p->pWhere);
  121288. sqlite3ExprListDelete(db, p->pGroupBy);
  121289. sqlite3ExprDelete(db, p->pHaving);
  121290. sqlite3ExprListDelete(db, p->pOrderBy);
  121291. sqlite3ExprDelete(db, p->pLimit);
  121292. #ifndef SQLITE_OMIT_WINDOWFUNC
  121293. if( OK_IF_ALWAYS_TRUE(p->pWinDefn) ){
  121294. sqlite3WindowListDelete(db, p->pWinDefn);
  121295. }
  121296. #endif
  121297. if( OK_IF_ALWAYS_TRUE(p->pWith) ) sqlite3WithDelete(db, p->pWith);
  121298. if( bFree ) sqlite3DbFreeNN(db, p);
  121299. p = pPrior;
  121300. bFree = 1;
  121301. }
  121302. }
  121303. /*
  121304. ** Initialize a SelectDest structure.
  121305. */
  121306. SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
  121307. pDest->eDest = (u8)eDest;
  121308. pDest->iSDParm = iParm;
  121309. pDest->zAffSdst = 0;
  121310. pDest->iSdst = 0;
  121311. pDest->nSdst = 0;
  121312. }
  121313. /*
  121314. ** Allocate a new Select structure and return a pointer to that
  121315. ** structure.
  121316. */
  121317. SQLITE_PRIVATE Select *sqlite3SelectNew(
  121318. Parse *pParse, /* Parsing context */
  121319. ExprList *pEList, /* which columns to include in the result */
  121320. SrcList *pSrc, /* the FROM clause -- which tables to scan */
  121321. Expr *pWhere, /* the WHERE clause */
  121322. ExprList *pGroupBy, /* the GROUP BY clause */
  121323. Expr *pHaving, /* the HAVING clause */
  121324. ExprList *pOrderBy, /* the ORDER BY clause */
  121325. u32 selFlags, /* Flag parameters, such as SF_Distinct */
  121326. Expr *pLimit /* LIMIT value. NULL means not used */
  121327. ){
  121328. Select *pNew;
  121329. Select standin;
  121330. pNew = sqlite3DbMallocRawNN(pParse->db, sizeof(*pNew) );
  121331. if( pNew==0 ){
  121332. assert( pParse->db->mallocFailed );
  121333. pNew = &standin;
  121334. }
  121335. if( pEList==0 ){
  121336. pEList = sqlite3ExprListAppend(pParse, 0,
  121337. sqlite3Expr(pParse->db,TK_ASTERISK,0));
  121338. }
  121339. pNew->pEList = pEList;
  121340. pNew->op = TK_SELECT;
  121341. pNew->selFlags = selFlags;
  121342. pNew->iLimit = 0;
  121343. pNew->iOffset = 0;
  121344. pNew->selId = ++pParse->nSelect;
  121345. pNew->addrOpenEphm[0] = -1;
  121346. pNew->addrOpenEphm[1] = -1;
  121347. pNew->nSelectRow = 0;
  121348. if( pSrc==0 ) pSrc = sqlite3DbMallocZero(pParse->db, sizeof(*pSrc));
  121349. pNew->pSrc = pSrc;
  121350. pNew->pWhere = pWhere;
  121351. pNew->pGroupBy = pGroupBy;
  121352. pNew->pHaving = pHaving;
  121353. pNew->pOrderBy = pOrderBy;
  121354. pNew->pPrior = 0;
  121355. pNew->pNext = 0;
  121356. pNew->pLimit = pLimit;
  121357. pNew->pWith = 0;
  121358. #ifndef SQLITE_OMIT_WINDOWFUNC
  121359. pNew->pWin = 0;
  121360. pNew->pWinDefn = 0;
  121361. #endif
  121362. if( pParse->db->mallocFailed ) {
  121363. clearSelect(pParse->db, pNew, pNew!=&standin);
  121364. pNew = 0;
  121365. }else{
  121366. assert( pNew->pSrc!=0 || pParse->nErr>0 );
  121367. }
  121368. assert( pNew!=&standin );
  121369. return pNew;
  121370. }
  121371. /*
  121372. ** Delete the given Select structure and all of its substructures.
  121373. */
  121374. SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){
  121375. if( OK_IF_ALWAYS_TRUE(p) ) clearSelect(db, p, 1);
  121376. }
  121377. /*
  121378. ** Delete all the substructure for p, but keep p allocated. Redefine
  121379. ** p to be a single SELECT where every column of the result set has a
  121380. ** value of NULL.
  121381. */
  121382. SQLITE_PRIVATE void sqlite3SelectReset(Parse *pParse, Select *p){
  121383. if( ALWAYS(p) ){
  121384. clearSelect(pParse->db, p, 0);
  121385. memset(&p->iLimit, 0, sizeof(Select) - offsetof(Select,iLimit));
  121386. p->pEList = sqlite3ExprListAppend(pParse, 0,
  121387. sqlite3ExprAlloc(pParse->db,TK_NULL,0,0));
  121388. p->pSrc = sqlite3DbMallocZero(pParse->db, sizeof(SrcList));
  121389. }
  121390. }
  121391. /*
  121392. ** Return a pointer to the right-most SELECT statement in a compound.
  121393. */
  121394. static Select *findRightmost(Select *p){
  121395. while( p->pNext ) p = p->pNext;
  121396. return p;
  121397. }
  121398. /*
  121399. ** Given 1 to 3 identifiers preceding the JOIN keyword, determine the
  121400. ** type of join. Return an integer constant that expresses that type
  121401. ** in terms of the following bit values:
  121402. **
  121403. ** JT_INNER
  121404. ** JT_CROSS
  121405. ** JT_OUTER
  121406. ** JT_NATURAL
  121407. ** JT_LEFT
  121408. ** JT_RIGHT
  121409. **
  121410. ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
  121411. **
  121412. ** If an illegal or unsupported join type is seen, then still return
  121413. ** a join type, but put an error in the pParse structure.
  121414. */
  121415. SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
  121416. int jointype = 0;
  121417. Token *apAll[3];
  121418. Token *p;
  121419. /* 0123456789 123456789 123456789 123 */
  121420. static const char zKeyText[] = "naturaleftouterightfullinnercross";
  121421. static const struct {
  121422. u8 i; /* Beginning of keyword text in zKeyText[] */
  121423. u8 nChar; /* Length of the keyword in characters */
  121424. u8 code; /* Join type mask */
  121425. } aKeyword[] = {
  121426. /* natural */ { 0, 7, JT_NATURAL },
  121427. /* left */ { 6, 4, JT_LEFT|JT_OUTER },
  121428. /* outer */ { 10, 5, JT_OUTER },
  121429. /* right */ { 14, 5, JT_RIGHT|JT_OUTER },
  121430. /* full */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
  121431. /* inner */ { 23, 5, JT_INNER },
  121432. /* cross */ { 28, 5, JT_INNER|JT_CROSS },
  121433. };
  121434. int i, j;
  121435. apAll[0] = pA;
  121436. apAll[1] = pB;
  121437. apAll[2] = pC;
  121438. for(i=0; i<3 && apAll[i]; i++){
  121439. p = apAll[i];
  121440. for(j=0; j<ArraySize(aKeyword); j++){
  121441. if( p->n==aKeyword[j].nChar
  121442. && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
  121443. jointype |= aKeyword[j].code;
  121444. break;
  121445. }
  121446. }
  121447. testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
  121448. if( j>=ArraySize(aKeyword) ){
  121449. jointype |= JT_ERROR;
  121450. break;
  121451. }
  121452. }
  121453. if(
  121454. (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
  121455. (jointype & JT_ERROR)!=0
  121456. ){
  121457. const char *zSp = " ";
  121458. assert( pB!=0 );
  121459. if( pC==0 ){ zSp++; }
  121460. sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
  121461. "%T %T%s%T", pA, pB, zSp, pC);
  121462. jointype = JT_INNER;
  121463. }else if( (jointype & JT_OUTER)!=0
  121464. && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
  121465. sqlite3ErrorMsg(pParse,
  121466. "RIGHT and FULL OUTER JOINs are not currently supported");
  121467. jointype = JT_INNER;
  121468. }
  121469. return jointype;
  121470. }
  121471. /*
  121472. ** Return the index of a column in a table. Return -1 if the column
  121473. ** is not contained in the table.
  121474. */
  121475. static int columnIndex(Table *pTab, const char *zCol){
  121476. int i;
  121477. for(i=0; i<pTab->nCol; i++){
  121478. if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
  121479. }
  121480. return -1;
  121481. }
  121482. /*
  121483. ** Search the first N tables in pSrc, from left to right, looking for a
  121484. ** table that has a column named zCol.
  121485. **
  121486. ** When found, set *piTab and *piCol to the table index and column index
  121487. ** of the matching column and return TRUE.
  121488. **
  121489. ** If not found, return FALSE.
  121490. */
  121491. static int tableAndColumnIndex(
  121492. SrcList *pSrc, /* Array of tables to search */
  121493. int N, /* Number of tables in pSrc->a[] to search */
  121494. const char *zCol, /* Name of the column we are looking for */
  121495. int *piTab, /* Write index of pSrc->a[] here */
  121496. int *piCol, /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
  121497. int bIgnoreHidden /* True to ignore hidden columns */
  121498. ){
  121499. int i; /* For looping over tables in pSrc */
  121500. int iCol; /* Index of column matching zCol */
  121501. assert( (piTab==0)==(piCol==0) ); /* Both or neither are NULL */
  121502. for(i=0; i<N; i++){
  121503. iCol = columnIndex(pSrc->a[i].pTab, zCol);
  121504. if( iCol>=0
  121505. && (bIgnoreHidden==0 || IsHiddenColumn(&pSrc->a[i].pTab->aCol[iCol])==0)
  121506. ){
  121507. if( piTab ){
  121508. *piTab = i;
  121509. *piCol = iCol;
  121510. }
  121511. return 1;
  121512. }
  121513. }
  121514. return 0;
  121515. }
  121516. /*
  121517. ** This function is used to add terms implied by JOIN syntax to the
  121518. ** WHERE clause expression of a SELECT statement. The new term, which
  121519. ** is ANDed with the existing WHERE clause, is of the form:
  121520. **
  121521. ** (tab1.col1 = tab2.col2)
  121522. **
  121523. ** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the
  121524. ** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
  121525. ** column iColRight of tab2.
  121526. */
  121527. static void addWhereTerm(
  121528. Parse *pParse, /* Parsing context */
  121529. SrcList *pSrc, /* List of tables in FROM clause */
  121530. int iLeft, /* Index of first table to join in pSrc */
  121531. int iColLeft, /* Index of column in first table */
  121532. int iRight, /* Index of second table in pSrc */
  121533. int iColRight, /* Index of column in second table */
  121534. int isOuterJoin, /* True if this is an OUTER join */
  121535. Expr **ppWhere /* IN/OUT: The WHERE clause to add to */
  121536. ){
  121537. sqlite3 *db = pParse->db;
  121538. Expr *pE1;
  121539. Expr *pE2;
  121540. Expr *pEq;
  121541. assert( iLeft<iRight );
  121542. assert( pSrc->nSrc>iRight );
  121543. assert( pSrc->a[iLeft].pTab );
  121544. assert( pSrc->a[iRight].pTab );
  121545. pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
  121546. pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);
  121547. pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2);
  121548. if( pEq && isOuterJoin ){
  121549. ExprSetProperty(pEq, EP_FromJoin);
  121550. assert( !ExprHasProperty(pEq, EP_TokenOnly|EP_Reduced) );
  121551. ExprSetVVAProperty(pEq, EP_NoReduce);
  121552. pEq->iRightJoinTable = (i16)pE2->iTable;
  121553. }
  121554. *ppWhere = sqlite3ExprAnd(pParse, *ppWhere, pEq);
  121555. }
  121556. /*
  121557. ** Set the EP_FromJoin property on all terms of the given expression.
  121558. ** And set the Expr.iRightJoinTable to iTable for every term in the
  121559. ** expression.
  121560. **
  121561. ** The EP_FromJoin property is used on terms of an expression to tell
  121562. ** the LEFT OUTER JOIN processing logic that this term is part of the
  121563. ** join restriction specified in the ON or USING clause and not a part
  121564. ** of the more general WHERE clause. These terms are moved over to the
  121565. ** WHERE clause during join processing but we need to remember that they
  121566. ** originated in the ON or USING clause.
  121567. **
  121568. ** The Expr.iRightJoinTable tells the WHERE clause processing that the
  121569. ** expression depends on table iRightJoinTable even if that table is not
  121570. ** explicitly mentioned in the expression. That information is needed
  121571. ** for cases like this:
  121572. **
  121573. ** SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
  121574. **
  121575. ** The where clause needs to defer the handling of the t1.x=5
  121576. ** term until after the t2 loop of the join. In that way, a
  121577. ** NULL t2 row will be inserted whenever t1.x!=5. If we do not
  121578. ** defer the handling of t1.x=5, it will be processed immediately
  121579. ** after the t1 loop and rows with t1.x!=5 will never appear in
  121580. ** the output, which is incorrect.
  121581. */
  121582. SQLITE_PRIVATE void sqlite3SetJoinExpr(Expr *p, int iTable){
  121583. while( p ){
  121584. ExprSetProperty(p, EP_FromJoin);
  121585. assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
  121586. ExprSetVVAProperty(p, EP_NoReduce);
  121587. p->iRightJoinTable = (i16)iTable;
  121588. if( p->op==TK_FUNCTION && p->x.pList ){
  121589. int i;
  121590. for(i=0; i<p->x.pList->nExpr; i++){
  121591. sqlite3SetJoinExpr(p->x.pList->a[i].pExpr, iTable);
  121592. }
  121593. }
  121594. sqlite3SetJoinExpr(p->pLeft, iTable);
  121595. p = p->pRight;
  121596. }
  121597. }
  121598. /* Undo the work of sqlite3SetJoinExpr(). In the expression p, convert every
  121599. ** term that is marked with EP_FromJoin and iRightJoinTable==iTable into
  121600. ** an ordinary term that omits the EP_FromJoin mark.
  121601. **
  121602. ** This happens when a LEFT JOIN is simplified into an ordinary JOIN.
  121603. */
  121604. static void unsetJoinExpr(Expr *p, int iTable){
  121605. while( p ){
  121606. if( ExprHasProperty(p, EP_FromJoin)
  121607. && (iTable<0 || p->iRightJoinTable==iTable) ){
  121608. ExprClearProperty(p, EP_FromJoin);
  121609. }
  121610. if( p->op==TK_FUNCTION && p->x.pList ){
  121611. int i;
  121612. for(i=0; i<p->x.pList->nExpr; i++){
  121613. unsetJoinExpr(p->x.pList->a[i].pExpr, iTable);
  121614. }
  121615. }
  121616. unsetJoinExpr(p->pLeft, iTable);
  121617. p = p->pRight;
  121618. }
  121619. }
  121620. /*
  121621. ** This routine processes the join information for a SELECT statement.
  121622. ** ON and USING clauses are converted into extra terms of the WHERE clause.
  121623. ** NATURAL joins also create extra WHERE clause terms.
  121624. **
  121625. ** The terms of a FROM clause are contained in the Select.pSrc structure.
  121626. ** The left most table is the first entry in Select.pSrc. The right-most
  121627. ** table is the last entry. The join operator is held in the entry to
  121628. ** the left. Thus entry 0 contains the join operator for the join between
  121629. ** entries 0 and 1. Any ON or USING clauses associated with the join are
  121630. ** also attached to the left entry.
  121631. **
  121632. ** This routine returns the number of errors encountered.
  121633. */
  121634. static int sqliteProcessJoin(Parse *pParse, Select *p){
  121635. SrcList *pSrc; /* All tables in the FROM clause */
  121636. int i, j; /* Loop counters */
  121637. struct SrcList_item *pLeft; /* Left table being joined */
  121638. struct SrcList_item *pRight; /* Right table being joined */
  121639. pSrc = p->pSrc;
  121640. pLeft = &pSrc->a[0];
  121641. pRight = &pLeft[1];
  121642. for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
  121643. Table *pRightTab = pRight->pTab;
  121644. int isOuter;
  121645. if( NEVER(pLeft->pTab==0 || pRightTab==0) ) continue;
  121646. isOuter = (pRight->fg.jointype & JT_OUTER)!=0;
  121647. /* When the NATURAL keyword is present, add WHERE clause terms for
  121648. ** every column that the two tables have in common.
  121649. */
  121650. if( pRight->fg.jointype & JT_NATURAL ){
  121651. if( pRight->pOn || pRight->pUsing ){
  121652. sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
  121653. "an ON or USING clause", 0);
  121654. return 1;
  121655. }
  121656. for(j=0; j<pRightTab->nCol; j++){
  121657. char *zName; /* Name of column in the right table */
  121658. int iLeft; /* Matching left table */
  121659. int iLeftCol; /* Matching column in the left table */
  121660. if( IsHiddenColumn(&pRightTab->aCol[j]) ) continue;
  121661. zName = pRightTab->aCol[j].zName;
  121662. if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol, 1) ){
  121663. addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
  121664. isOuter, &p->pWhere);
  121665. }
  121666. }
  121667. }
  121668. /* Disallow both ON and USING clauses in the same join
  121669. */
  121670. if( pRight->pOn && pRight->pUsing ){
  121671. sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
  121672. "clauses in the same join");
  121673. return 1;
  121674. }
  121675. /* Add the ON clause to the end of the WHERE clause, connected by
  121676. ** an AND operator.
  121677. */
  121678. if( pRight->pOn ){
  121679. if( isOuter ) sqlite3SetJoinExpr(pRight->pOn, pRight->iCursor);
  121680. p->pWhere = sqlite3ExprAnd(pParse, p->pWhere, pRight->pOn);
  121681. pRight->pOn = 0;
  121682. }
  121683. /* Create extra terms on the WHERE clause for each column named
  121684. ** in the USING clause. Example: If the two tables to be joined are
  121685. ** A and B and the USING clause names X, Y, and Z, then add this
  121686. ** to the WHERE clause: A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
  121687. ** Report an error if any column mentioned in the USING clause is
  121688. ** not contained in both tables to be joined.
  121689. */
  121690. if( pRight->pUsing ){
  121691. IdList *pList = pRight->pUsing;
  121692. for(j=0; j<pList->nId; j++){
  121693. char *zName; /* Name of the term in the USING clause */
  121694. int iLeft; /* Table on the left with matching column name */
  121695. int iLeftCol; /* Column number of matching column on the left */
  121696. int iRightCol; /* Column number of matching column on the right */
  121697. zName = pList->a[j].zName;
  121698. iRightCol = columnIndex(pRightTab, zName);
  121699. if( iRightCol<0
  121700. || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol, 0)
  121701. ){
  121702. sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
  121703. "not present in both tables", zName);
  121704. return 1;
  121705. }
  121706. addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,
  121707. isOuter, &p->pWhere);
  121708. }
  121709. }
  121710. }
  121711. return 0;
  121712. }
  121713. /*
  121714. ** An instance of this object holds information (beyond pParse and pSelect)
  121715. ** needed to load the next result row that is to be added to the sorter.
  121716. */
  121717. typedef struct RowLoadInfo RowLoadInfo;
  121718. struct RowLoadInfo {
  121719. int regResult; /* Store results in array of registers here */
  121720. u8 ecelFlags; /* Flag argument to ExprCodeExprList() */
  121721. #ifdef SQLITE_ENABLE_SORTER_REFERENCES
  121722. ExprList *pExtra; /* Extra columns needed by sorter refs */
  121723. int regExtraResult; /* Where to load the extra columns */
  121724. #endif
  121725. };
  121726. /*
  121727. ** This routine does the work of loading query data into an array of
  121728. ** registers so that it can be added to the sorter.
  121729. */
  121730. static void innerLoopLoadRow(
  121731. Parse *pParse, /* Statement under construction */
  121732. Select *pSelect, /* The query being coded */
  121733. RowLoadInfo *pInfo /* Info needed to complete the row load */
  121734. ){
  121735. sqlite3ExprCodeExprList(pParse, pSelect->pEList, pInfo->regResult,
  121736. 0, pInfo->ecelFlags);
  121737. #ifdef SQLITE_ENABLE_SORTER_REFERENCES
  121738. if( pInfo->pExtra ){
  121739. sqlite3ExprCodeExprList(pParse, pInfo->pExtra, pInfo->regExtraResult, 0, 0);
  121740. sqlite3ExprListDelete(pParse->db, pInfo->pExtra);
  121741. }
  121742. #endif
  121743. }
  121744. /*
  121745. ** Code the OP_MakeRecord instruction that generates the entry to be
  121746. ** added into the sorter.
  121747. **
  121748. ** Return the register in which the result is stored.
  121749. */
  121750. static int makeSorterRecord(
  121751. Parse *pParse,
  121752. SortCtx *pSort,
  121753. Select *pSelect,
  121754. int regBase,
  121755. int nBase
  121756. ){
  121757. int nOBSat = pSort->nOBSat;
  121758. Vdbe *v = pParse->pVdbe;
  121759. int regOut = ++pParse->nMem;
  121760. if( pSort->pDeferredRowLoad ){
  121761. innerLoopLoadRow(pParse, pSelect, pSort->pDeferredRowLoad);
  121762. }
  121763. sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase+nOBSat, nBase-nOBSat, regOut);
  121764. return regOut;
  121765. }
  121766. /*
  121767. ** Generate code that will push the record in registers regData
  121768. ** through regData+nData-1 onto the sorter.
  121769. */
  121770. static void pushOntoSorter(
  121771. Parse *pParse, /* Parser context */
  121772. SortCtx *pSort, /* Information about the ORDER BY clause */
  121773. Select *pSelect, /* The whole SELECT statement */
  121774. int regData, /* First register holding data to be sorted */
  121775. int regOrigData, /* First register holding data before packing */
  121776. int nData, /* Number of elements in the regData data array */
  121777. int nPrefixReg /* No. of reg prior to regData available for use */
  121778. ){
  121779. Vdbe *v = pParse->pVdbe; /* Stmt under construction */
  121780. int bSeq = ((pSort->sortFlags & SORTFLAG_UseSorter)==0);
  121781. int nExpr = pSort->pOrderBy->nExpr; /* No. of ORDER BY terms */
  121782. int nBase = nExpr + bSeq + nData; /* Fields in sorter record */
  121783. int regBase; /* Regs for sorter record */
  121784. int regRecord = 0; /* Assembled sorter record */
  121785. int nOBSat = pSort->nOBSat; /* ORDER BY terms to skip */
  121786. int op; /* Opcode to add sorter record to sorter */
  121787. int iLimit; /* LIMIT counter */
  121788. int iSkip = 0; /* End of the sorter insert loop */
  121789. assert( bSeq==0 || bSeq==1 );
  121790. /* Three cases:
  121791. ** (1) The data to be sorted has already been packed into a Record
  121792. ** by a prior OP_MakeRecord. In this case nData==1 and regData
  121793. ** will be completely unrelated to regOrigData.
  121794. ** (2) All output columns are included in the sort record. In that
  121795. ** case regData==regOrigData.
  121796. ** (3) Some output columns are omitted from the sort record due to
  121797. ** the SQLITE_ENABLE_SORTER_REFERENCE optimization, or due to the
  121798. ** SQLITE_ECEL_OMITREF optimization, or due to the
  121799. ** SortCtx.pDeferredRowLoad optimiation. In any of these cases
  121800. ** regOrigData is 0 to prevent this routine from trying to copy
  121801. ** values that might not yet exist.
  121802. */
  121803. assert( nData==1 || regData==regOrigData || regOrigData==0 );
  121804. if( nPrefixReg ){
  121805. assert( nPrefixReg==nExpr+bSeq );
  121806. regBase = regData - nPrefixReg;
  121807. }else{
  121808. regBase = pParse->nMem + 1;
  121809. pParse->nMem += nBase;
  121810. }
  121811. assert( pSelect->iOffset==0 || pSelect->iLimit!=0 );
  121812. iLimit = pSelect->iOffset ? pSelect->iOffset+1 : pSelect->iLimit;
  121813. pSort->labelDone = sqlite3VdbeMakeLabel(pParse);
  121814. sqlite3ExprCodeExprList(pParse, pSort->pOrderBy, regBase, regOrigData,
  121815. SQLITE_ECEL_DUP | (regOrigData? SQLITE_ECEL_REF : 0));
  121816. if( bSeq ){
  121817. sqlite3VdbeAddOp2(v, OP_Sequence, pSort->iECursor, regBase+nExpr);
  121818. }
  121819. if( nPrefixReg==0 && nData>0 ){
  121820. sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+bSeq, nData);
  121821. }
  121822. if( nOBSat>0 ){
  121823. int regPrevKey; /* The first nOBSat columns of the previous row */
  121824. int addrFirst; /* Address of the OP_IfNot opcode */
  121825. int addrJmp; /* Address of the OP_Jump opcode */
  121826. VdbeOp *pOp; /* Opcode that opens the sorter */
  121827. int nKey; /* Number of sorting key columns, including OP_Sequence */
  121828. KeyInfo *pKI; /* Original KeyInfo on the sorter table */
  121829. regRecord = makeSorterRecord(pParse, pSort, pSelect, regBase, nBase);
  121830. regPrevKey = pParse->nMem+1;
  121831. pParse->nMem += pSort->nOBSat;
  121832. nKey = nExpr - pSort->nOBSat + bSeq;
  121833. if( bSeq ){
  121834. addrFirst = sqlite3VdbeAddOp1(v, OP_IfNot, regBase+nExpr);
  121835. }else{
  121836. addrFirst = sqlite3VdbeAddOp1(v, OP_SequenceTest, pSort->iECursor);
  121837. }
  121838. VdbeCoverage(v);
  121839. sqlite3VdbeAddOp3(v, OP_Compare, regPrevKey, regBase, pSort->nOBSat);
  121840. pOp = sqlite3VdbeGetOp(v, pSort->addrSortIndex);
  121841. if( pParse->db->mallocFailed ) return;
  121842. pOp->p2 = nKey + nData;
  121843. pKI = pOp->p4.pKeyInfo;
  121844. memset(pKI->aSortFlags, 0, pKI->nKeyField); /* Makes OP_Jump testable */
  121845. sqlite3VdbeChangeP4(v, -1, (char*)pKI, P4_KEYINFO);
  121846. testcase( pKI->nAllField > pKI->nKeyField+2 );
  121847. pOp->p4.pKeyInfo = sqlite3KeyInfoFromExprList(pParse,pSort->pOrderBy,nOBSat,
  121848. pKI->nAllField-pKI->nKeyField-1);
  121849. pOp = 0; /* Ensure pOp not used after sqltie3VdbeAddOp3() */
  121850. addrJmp = sqlite3VdbeCurrentAddr(v);
  121851. sqlite3VdbeAddOp3(v, OP_Jump, addrJmp+1, 0, addrJmp+1); VdbeCoverage(v);
  121852. pSort->labelBkOut = sqlite3VdbeMakeLabel(pParse);
  121853. pSort->regReturn = ++pParse->nMem;
  121854. sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
  121855. sqlite3VdbeAddOp1(v, OP_ResetSorter, pSort->iECursor);
  121856. if( iLimit ){
  121857. sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, pSort->labelDone);
  121858. VdbeCoverage(v);
  121859. }
  121860. sqlite3VdbeJumpHere(v, addrFirst);
  121861. sqlite3ExprCodeMove(pParse, regBase, regPrevKey, pSort->nOBSat);
  121862. sqlite3VdbeJumpHere(v, addrJmp);
  121863. }
  121864. if( iLimit ){
  121865. /* At this point the values for the new sorter entry are stored
  121866. ** in an array of registers. They need to be composed into a record
  121867. ** and inserted into the sorter if either (a) there are currently
  121868. ** less than LIMIT+OFFSET items or (b) the new record is smaller than
  121869. ** the largest record currently in the sorter. If (b) is true and there
  121870. ** are already LIMIT+OFFSET items in the sorter, delete the largest
  121871. ** entry before inserting the new one. This way there are never more
  121872. ** than LIMIT+OFFSET items in the sorter.
  121873. **
  121874. ** If the new record does not need to be inserted into the sorter,
  121875. ** jump to the next iteration of the loop. If the pSort->labelOBLopt
  121876. ** value is not zero, then it is a label of where to jump. Otherwise,
  121877. ** just bypass the row insert logic. See the header comment on the
  121878. ** sqlite3WhereOrderByLimitOptLabel() function for additional info.
  121879. */
  121880. int iCsr = pSort->iECursor;
  121881. sqlite3VdbeAddOp2(v, OP_IfNotZero, iLimit, sqlite3VdbeCurrentAddr(v)+4);
  121882. VdbeCoverage(v);
  121883. sqlite3VdbeAddOp2(v, OP_Last, iCsr, 0);
  121884. iSkip = sqlite3VdbeAddOp4Int(v, OP_IdxLE,
  121885. iCsr, 0, regBase+nOBSat, nExpr-nOBSat);
  121886. VdbeCoverage(v);
  121887. sqlite3VdbeAddOp1(v, OP_Delete, iCsr);
  121888. }
  121889. if( regRecord==0 ){
  121890. regRecord = makeSorterRecord(pParse, pSort, pSelect, regBase, nBase);
  121891. }
  121892. if( pSort->sortFlags & SORTFLAG_UseSorter ){
  121893. op = OP_SorterInsert;
  121894. }else{
  121895. op = OP_IdxInsert;
  121896. }
  121897. sqlite3VdbeAddOp4Int(v, op, pSort->iECursor, regRecord,
  121898. regBase+nOBSat, nBase-nOBSat);
  121899. if( iSkip ){
  121900. sqlite3VdbeChangeP2(v, iSkip,
  121901. pSort->labelOBLopt ? pSort->labelOBLopt : sqlite3VdbeCurrentAddr(v));
  121902. }
  121903. }
  121904. /*
  121905. ** Add code to implement the OFFSET
  121906. */
  121907. static void codeOffset(
  121908. Vdbe *v, /* Generate code into this VM */
  121909. int iOffset, /* Register holding the offset counter */
  121910. int iContinue /* Jump here to skip the current record */
  121911. ){
  121912. if( iOffset>0 ){
  121913. sqlite3VdbeAddOp3(v, OP_IfPos, iOffset, iContinue, 1); VdbeCoverage(v);
  121914. VdbeComment((v, "OFFSET"));
  121915. }
  121916. }
  121917. /*
  121918. ** Add code that will check to make sure the N registers starting at iMem
  121919. ** form a distinct entry. iTab is a sorting index that holds previously
  121920. ** seen combinations of the N values. A new entry is made in iTab
  121921. ** if the current N values are new.
  121922. **
  121923. ** A jump to addrRepeat is made and the N+1 values are popped from the
  121924. ** stack if the top N elements are not distinct.
  121925. */
  121926. static void codeDistinct(
  121927. Parse *pParse, /* Parsing and code generating context */
  121928. int iTab, /* A sorting index used to test for distinctness */
  121929. int addrRepeat, /* Jump to here if not distinct */
  121930. int N, /* Number of elements */
  121931. int iMem /* First element */
  121932. ){
  121933. Vdbe *v;
  121934. int r1;
  121935. v = pParse->pVdbe;
  121936. r1 = sqlite3GetTempReg(pParse);
  121937. sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N); VdbeCoverage(v);
  121938. sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
  121939. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iTab, r1, iMem, N);
  121940. sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  121941. sqlite3ReleaseTempReg(pParse, r1);
  121942. }
  121943. #ifdef SQLITE_ENABLE_SORTER_REFERENCES
  121944. /*
  121945. ** This function is called as part of inner-loop generation for a SELECT
  121946. ** statement with an ORDER BY that is not optimized by an index. It
  121947. ** determines the expressions, if any, that the sorter-reference
  121948. ** optimization should be used for. The sorter-reference optimization
  121949. ** is used for SELECT queries like:
  121950. **
  121951. ** SELECT a, bigblob FROM t1 ORDER BY a LIMIT 10
  121952. **
  121953. ** If the optimization is used for expression "bigblob", then instead of
  121954. ** storing values read from that column in the sorter records, the PK of
  121955. ** the row from table t1 is stored instead. Then, as records are extracted from
  121956. ** the sorter to return to the user, the required value of bigblob is
  121957. ** retrieved directly from table t1. If the values are very large, this
  121958. ** can be more efficient than storing them directly in the sorter records.
  121959. **
  121960. ** The ExprList_item.bSorterRef flag is set for each expression in pEList
  121961. ** for which the sorter-reference optimization should be enabled.
  121962. ** Additionally, the pSort->aDefer[] array is populated with entries
  121963. ** for all cursors required to evaluate all selected expressions. Finally.
  121964. ** output variable (*ppExtra) is set to an expression list containing
  121965. ** expressions for all extra PK values that should be stored in the
  121966. ** sorter records.
  121967. */
  121968. static void selectExprDefer(
  121969. Parse *pParse, /* Leave any error here */
  121970. SortCtx *pSort, /* Sorter context */
  121971. ExprList *pEList, /* Expressions destined for sorter */
  121972. ExprList **ppExtra /* Expressions to append to sorter record */
  121973. ){
  121974. int i;
  121975. int nDefer = 0;
  121976. ExprList *pExtra = 0;
  121977. for(i=0; i<pEList->nExpr; i++){
  121978. struct ExprList_item *pItem = &pEList->a[i];
  121979. if( pItem->u.x.iOrderByCol==0 ){
  121980. Expr *pExpr = pItem->pExpr;
  121981. Table *pTab = pExpr->y.pTab;
  121982. if( pExpr->op==TK_COLUMN && pExpr->iColumn>=0 && pTab && !IsVirtual(pTab)
  121983. && (pTab->aCol[pExpr->iColumn].colFlags & COLFLAG_SORTERREF)
  121984. ){
  121985. int j;
  121986. for(j=0; j<nDefer; j++){
  121987. if( pSort->aDefer[j].iCsr==pExpr->iTable ) break;
  121988. }
  121989. if( j==nDefer ){
  121990. if( nDefer==ArraySize(pSort->aDefer) ){
  121991. continue;
  121992. }else{
  121993. int nKey = 1;
  121994. int k;
  121995. Index *pPk = 0;
  121996. if( !HasRowid(pTab) ){
  121997. pPk = sqlite3PrimaryKeyIndex(pTab);
  121998. nKey = pPk->nKeyCol;
  121999. }
  122000. for(k=0; k<nKey; k++){
  122001. Expr *pNew = sqlite3PExpr(pParse, TK_COLUMN, 0, 0);
  122002. if( pNew ){
  122003. pNew->iTable = pExpr->iTable;
  122004. pNew->y.pTab = pExpr->y.pTab;
  122005. pNew->iColumn = pPk ? pPk->aiColumn[k] : -1;
  122006. pExtra = sqlite3ExprListAppend(pParse, pExtra, pNew);
  122007. }
  122008. }
  122009. pSort->aDefer[nDefer].pTab = pExpr->y.pTab;
  122010. pSort->aDefer[nDefer].iCsr = pExpr->iTable;
  122011. pSort->aDefer[nDefer].nKey = nKey;
  122012. nDefer++;
  122013. }
  122014. }
  122015. pItem->bSorterRef = 1;
  122016. }
  122017. }
  122018. }
  122019. pSort->nDefer = (u8)nDefer;
  122020. *ppExtra = pExtra;
  122021. }
  122022. #endif
  122023. /*
  122024. ** This routine generates the code for the inside of the inner loop
  122025. ** of a SELECT.
  122026. **
  122027. ** If srcTab is negative, then the p->pEList expressions
  122028. ** are evaluated in order to get the data for this row. If srcTab is
  122029. ** zero or more, then data is pulled from srcTab and p->pEList is used only
  122030. ** to get the number of columns and the collation sequence for each column.
  122031. */
  122032. static void selectInnerLoop(
  122033. Parse *pParse, /* The parser context */
  122034. Select *p, /* The complete select statement being coded */
  122035. int srcTab, /* Pull data from this table if non-negative */
  122036. SortCtx *pSort, /* If not NULL, info on how to process ORDER BY */
  122037. DistinctCtx *pDistinct, /* If not NULL, info on how to process DISTINCT */
  122038. SelectDest *pDest, /* How to dispose of the results */
  122039. int iContinue, /* Jump here to continue with next row */
  122040. int iBreak /* Jump here to break out of the inner loop */
  122041. ){
  122042. Vdbe *v = pParse->pVdbe;
  122043. int i;
  122044. int hasDistinct; /* True if the DISTINCT keyword is present */
  122045. int eDest = pDest->eDest; /* How to dispose of results */
  122046. int iParm = pDest->iSDParm; /* First argument to disposal method */
  122047. int nResultCol; /* Number of result columns */
  122048. int nPrefixReg = 0; /* Number of extra registers before regResult */
  122049. RowLoadInfo sRowLoadInfo; /* Info for deferred row loading */
  122050. /* Usually, regResult is the first cell in an array of memory cells
  122051. ** containing the current result row. In this case regOrig is set to the
  122052. ** same value. However, if the results are being sent to the sorter, the
  122053. ** values for any expressions that are also part of the sort-key are omitted
  122054. ** from this array. In this case regOrig is set to zero. */
  122055. int regResult; /* Start of memory holding current results */
  122056. int regOrig; /* Start of memory holding full result (or 0) */
  122057. assert( v );
  122058. assert( p->pEList!=0 );
  122059. hasDistinct = pDistinct ? pDistinct->eTnctType : WHERE_DISTINCT_NOOP;
  122060. if( pSort && pSort->pOrderBy==0 ) pSort = 0;
  122061. if( pSort==0 && !hasDistinct ){
  122062. assert( iContinue!=0 );
  122063. codeOffset(v, p->iOffset, iContinue);
  122064. }
  122065. /* Pull the requested columns.
  122066. */
  122067. nResultCol = p->pEList->nExpr;
  122068. if( pDest->iSdst==0 ){
  122069. if( pSort ){
  122070. nPrefixReg = pSort->pOrderBy->nExpr;
  122071. if( !(pSort->sortFlags & SORTFLAG_UseSorter) ) nPrefixReg++;
  122072. pParse->nMem += nPrefixReg;
  122073. }
  122074. pDest->iSdst = pParse->nMem+1;
  122075. pParse->nMem += nResultCol;
  122076. }else if( pDest->iSdst+nResultCol > pParse->nMem ){
  122077. /* This is an error condition that can result, for example, when a SELECT
  122078. ** on the right-hand side of an INSERT contains more result columns than
  122079. ** there are columns in the table on the left. The error will be caught
  122080. ** and reported later. But we need to make sure enough memory is allocated
  122081. ** to avoid other spurious errors in the meantime. */
  122082. pParse->nMem += nResultCol;
  122083. }
  122084. pDest->nSdst = nResultCol;
  122085. regOrig = regResult = pDest->iSdst;
  122086. if( srcTab>=0 ){
  122087. for(i=0; i<nResultCol; i++){
  122088. sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
  122089. VdbeComment((v, "%s", p->pEList->a[i].zEName));
  122090. }
  122091. }else if( eDest!=SRT_Exists ){
  122092. #ifdef SQLITE_ENABLE_SORTER_REFERENCES
  122093. ExprList *pExtra = 0;
  122094. #endif
  122095. /* If the destination is an EXISTS(...) expression, the actual
  122096. ** values returned by the SELECT are not required.
  122097. */
  122098. u8 ecelFlags; /* "ecel" is an abbreviation of "ExprCodeExprList" */
  122099. ExprList *pEList;
  122100. if( eDest==SRT_Mem || eDest==SRT_Output || eDest==SRT_Coroutine ){
  122101. ecelFlags = SQLITE_ECEL_DUP;
  122102. }else{
  122103. ecelFlags = 0;
  122104. }
  122105. if( pSort && hasDistinct==0 && eDest!=SRT_EphemTab && eDest!=SRT_Table ){
  122106. /* For each expression in p->pEList that is a copy of an expression in
  122107. ** the ORDER BY clause (pSort->pOrderBy), set the associated
  122108. ** iOrderByCol value to one more than the index of the ORDER BY
  122109. ** expression within the sort-key that pushOntoSorter() will generate.
  122110. ** This allows the p->pEList field to be omitted from the sorted record,
  122111. ** saving space and CPU cycles. */
  122112. ecelFlags |= (SQLITE_ECEL_OMITREF|SQLITE_ECEL_REF);
  122113. for(i=pSort->nOBSat; i<pSort->pOrderBy->nExpr; i++){
  122114. int j;
  122115. if( (j = pSort->pOrderBy->a[i].u.x.iOrderByCol)>0 ){
  122116. p->pEList->a[j-1].u.x.iOrderByCol = i+1-pSort->nOBSat;
  122117. }
  122118. }
  122119. #ifdef SQLITE_ENABLE_SORTER_REFERENCES
  122120. selectExprDefer(pParse, pSort, p->pEList, &pExtra);
  122121. if( pExtra && pParse->db->mallocFailed==0 ){
  122122. /* If there are any extra PK columns to add to the sorter records,
  122123. ** allocate extra memory cells and adjust the OpenEphemeral
  122124. ** instruction to account for the larger records. This is only
  122125. ** required if there are one or more WITHOUT ROWID tables with
  122126. ** composite primary keys in the SortCtx.aDefer[] array. */
  122127. VdbeOp *pOp = sqlite3VdbeGetOp(v, pSort->addrSortIndex);
  122128. pOp->p2 += (pExtra->nExpr - pSort->nDefer);
  122129. pOp->p4.pKeyInfo->nAllField += (pExtra->nExpr - pSort->nDefer);
  122130. pParse->nMem += pExtra->nExpr;
  122131. }
  122132. #endif
  122133. /* Adjust nResultCol to account for columns that are omitted
  122134. ** from the sorter by the optimizations in this branch */
  122135. pEList = p->pEList;
  122136. for(i=0; i<pEList->nExpr; i++){
  122137. if( pEList->a[i].u.x.iOrderByCol>0
  122138. #ifdef SQLITE_ENABLE_SORTER_REFERENCES
  122139. || pEList->a[i].bSorterRef
  122140. #endif
  122141. ){
  122142. nResultCol--;
  122143. regOrig = 0;
  122144. }
  122145. }
  122146. testcase( regOrig );
  122147. testcase( eDest==SRT_Set );
  122148. testcase( eDest==SRT_Mem );
  122149. testcase( eDest==SRT_Coroutine );
  122150. testcase( eDest==SRT_Output );
  122151. assert( eDest==SRT_Set || eDest==SRT_Mem
  122152. || eDest==SRT_Coroutine || eDest==SRT_Output );
  122153. }
  122154. sRowLoadInfo.regResult = regResult;
  122155. sRowLoadInfo.ecelFlags = ecelFlags;
  122156. #ifdef SQLITE_ENABLE_SORTER_REFERENCES
  122157. sRowLoadInfo.pExtra = pExtra;
  122158. sRowLoadInfo.regExtraResult = regResult + nResultCol;
  122159. if( pExtra ) nResultCol += pExtra->nExpr;
  122160. #endif
  122161. if( p->iLimit
  122162. && (ecelFlags & SQLITE_ECEL_OMITREF)!=0
  122163. && nPrefixReg>0
  122164. ){
  122165. assert( pSort!=0 );
  122166. assert( hasDistinct==0 );
  122167. pSort->pDeferredRowLoad = &sRowLoadInfo;
  122168. regOrig = 0;
  122169. }else{
  122170. innerLoopLoadRow(pParse, p, &sRowLoadInfo);
  122171. }
  122172. }
  122173. /* If the DISTINCT keyword was present on the SELECT statement
  122174. ** and this row has been seen before, then do not make this row
  122175. ** part of the result.
  122176. */
  122177. if( hasDistinct ){
  122178. switch( pDistinct->eTnctType ){
  122179. case WHERE_DISTINCT_ORDERED: {
  122180. VdbeOp *pOp; /* No longer required OpenEphemeral instr. */
  122181. int iJump; /* Jump destination */
  122182. int regPrev; /* Previous row content */
  122183. /* Allocate space for the previous row */
  122184. regPrev = pParse->nMem+1;
  122185. pParse->nMem += nResultCol;
  122186. /* Change the OP_OpenEphemeral coded earlier to an OP_Null
  122187. ** sets the MEM_Cleared bit on the first register of the
  122188. ** previous value. This will cause the OP_Ne below to always
  122189. ** fail on the first iteration of the loop even if the first
  122190. ** row is all NULLs.
  122191. */
  122192. sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
  122193. pOp = sqlite3VdbeGetOp(v, pDistinct->addrTnct);
  122194. pOp->opcode = OP_Null;
  122195. pOp->p1 = 1;
  122196. pOp->p2 = regPrev;
  122197. pOp = 0; /* Ensure pOp is not used after sqlite3VdbeAddOp() */
  122198. iJump = sqlite3VdbeCurrentAddr(v) + nResultCol;
  122199. for(i=0; i<nResultCol; i++){
  122200. CollSeq *pColl = sqlite3ExprCollSeq(pParse, p->pEList->a[i].pExpr);
  122201. if( i<nResultCol-1 ){
  122202. sqlite3VdbeAddOp3(v, OP_Ne, regResult+i, iJump, regPrev+i);
  122203. VdbeCoverage(v);
  122204. }else{
  122205. sqlite3VdbeAddOp3(v, OP_Eq, regResult+i, iContinue, regPrev+i);
  122206. VdbeCoverage(v);
  122207. }
  122208. sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ);
  122209. sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
  122210. }
  122211. assert( sqlite3VdbeCurrentAddr(v)==iJump || pParse->db->mallocFailed );
  122212. sqlite3VdbeAddOp3(v, OP_Copy, regResult, regPrev, nResultCol-1);
  122213. break;
  122214. }
  122215. case WHERE_DISTINCT_UNIQUE: {
  122216. sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
  122217. break;
  122218. }
  122219. default: {
  122220. assert( pDistinct->eTnctType==WHERE_DISTINCT_UNORDERED );
  122221. codeDistinct(pParse, pDistinct->tabTnct, iContinue, nResultCol,
  122222. regResult);
  122223. break;
  122224. }
  122225. }
  122226. if( pSort==0 ){
  122227. codeOffset(v, p->iOffset, iContinue);
  122228. }
  122229. }
  122230. switch( eDest ){
  122231. /* In this mode, write each query result to the key of the temporary
  122232. ** table iParm.
  122233. */
  122234. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  122235. case SRT_Union: {
  122236. int r1;
  122237. r1 = sqlite3GetTempReg(pParse);
  122238. sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1);
  122239. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regResult, nResultCol);
  122240. sqlite3ReleaseTempReg(pParse, r1);
  122241. break;
  122242. }
  122243. /* Construct a record from the query result, but instead of
  122244. ** saving that record, use it as a key to delete elements from
  122245. ** the temporary table iParm.
  122246. */
  122247. case SRT_Except: {
  122248. sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nResultCol);
  122249. break;
  122250. }
  122251. #endif /* SQLITE_OMIT_COMPOUND_SELECT */
  122252. /* Store the result as data using a unique key.
  122253. */
  122254. case SRT_Fifo:
  122255. case SRT_DistFifo:
  122256. case SRT_Table:
  122257. case SRT_EphemTab: {
  122258. int r1 = sqlite3GetTempRange(pParse, nPrefixReg+1);
  122259. testcase( eDest==SRT_Table );
  122260. testcase( eDest==SRT_EphemTab );
  122261. testcase( eDest==SRT_Fifo );
  122262. testcase( eDest==SRT_DistFifo );
  122263. sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1+nPrefixReg);
  122264. #ifndef SQLITE_OMIT_CTE
  122265. if( eDest==SRT_DistFifo ){
  122266. /* If the destination is DistFifo, then cursor (iParm+1) is open
  122267. ** on an ephemeral index. If the current row is already present
  122268. ** in the index, do not write it to the output. If not, add the
  122269. ** current row to the index and proceed with writing it to the
  122270. ** output table as well. */
  122271. int addr = sqlite3VdbeCurrentAddr(v) + 4;
  122272. sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, addr, r1, 0);
  122273. VdbeCoverage(v);
  122274. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm+1, r1,regResult,nResultCol);
  122275. assert( pSort==0 );
  122276. }
  122277. #endif
  122278. if( pSort ){
  122279. assert( regResult==regOrig );
  122280. pushOntoSorter(pParse, pSort, p, r1+nPrefixReg, regOrig, 1, nPrefixReg);
  122281. }else{
  122282. int r2 = sqlite3GetTempReg(pParse);
  122283. sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
  122284. sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
  122285. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  122286. sqlite3ReleaseTempReg(pParse, r2);
  122287. }
  122288. sqlite3ReleaseTempRange(pParse, r1, nPrefixReg+1);
  122289. break;
  122290. }
  122291. #ifndef SQLITE_OMIT_SUBQUERY
  122292. /* If we are creating a set for an "expr IN (SELECT ...)" construct,
  122293. ** then there should be a single item on the stack. Write this
  122294. ** item into the set table with bogus data.
  122295. */
  122296. case SRT_Set: {
  122297. if( pSort ){
  122298. /* At first glance you would think we could optimize out the
  122299. ** ORDER BY in this case since the order of entries in the set
  122300. ** does not matter. But there might be a LIMIT clause, in which
  122301. ** case the order does matter */
  122302. pushOntoSorter(
  122303. pParse, pSort, p, regResult, regOrig, nResultCol, nPrefixReg);
  122304. }else{
  122305. int r1 = sqlite3GetTempReg(pParse);
  122306. assert( sqlite3Strlen30(pDest->zAffSdst)==nResultCol );
  122307. sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, nResultCol,
  122308. r1, pDest->zAffSdst, nResultCol);
  122309. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regResult, nResultCol);
  122310. sqlite3ReleaseTempReg(pParse, r1);
  122311. }
  122312. break;
  122313. }
  122314. /* If any row exist in the result set, record that fact and abort.
  122315. */
  122316. case SRT_Exists: {
  122317. sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
  122318. /* The LIMIT clause will terminate the loop for us */
  122319. break;
  122320. }
  122321. /* If this is a scalar select that is part of an expression, then
  122322. ** store the results in the appropriate memory cell or array of
  122323. ** memory cells and break out of the scan loop.
  122324. */
  122325. case SRT_Mem: {
  122326. if( pSort ){
  122327. assert( nResultCol<=pDest->nSdst );
  122328. pushOntoSorter(
  122329. pParse, pSort, p, regResult, regOrig, nResultCol, nPrefixReg);
  122330. }else{
  122331. assert( nResultCol==pDest->nSdst );
  122332. assert( regResult==iParm );
  122333. /* The LIMIT clause will jump out of the loop for us */
  122334. }
  122335. break;
  122336. }
  122337. #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
  122338. case SRT_Coroutine: /* Send data to a co-routine */
  122339. case SRT_Output: { /* Return the results */
  122340. testcase( eDest==SRT_Coroutine );
  122341. testcase( eDest==SRT_Output );
  122342. if( pSort ){
  122343. pushOntoSorter(pParse, pSort, p, regResult, regOrig, nResultCol,
  122344. nPrefixReg);
  122345. }else if( eDest==SRT_Coroutine ){
  122346. sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
  122347. }else{
  122348. sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nResultCol);
  122349. }
  122350. break;
  122351. }
  122352. #ifndef SQLITE_OMIT_CTE
  122353. /* Write the results into a priority queue that is order according to
  122354. ** pDest->pOrderBy (in pSO). pDest->iSDParm (in iParm) is the cursor for an
  122355. ** index with pSO->nExpr+2 columns. Build a key using pSO for the first
  122356. ** pSO->nExpr columns, then make sure all keys are unique by adding a
  122357. ** final OP_Sequence column. The last column is the record as a blob.
  122358. */
  122359. case SRT_DistQueue:
  122360. case SRT_Queue: {
  122361. int nKey;
  122362. int r1, r2, r3;
  122363. int addrTest = 0;
  122364. ExprList *pSO;
  122365. pSO = pDest->pOrderBy;
  122366. assert( pSO );
  122367. nKey = pSO->nExpr;
  122368. r1 = sqlite3GetTempReg(pParse);
  122369. r2 = sqlite3GetTempRange(pParse, nKey+2);
  122370. r3 = r2+nKey+1;
  122371. if( eDest==SRT_DistQueue ){
  122372. /* If the destination is DistQueue, then cursor (iParm+1) is open
  122373. ** on a second ephemeral index that holds all values every previously
  122374. ** added to the queue. */
  122375. addrTest = sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, 0,
  122376. regResult, nResultCol);
  122377. VdbeCoverage(v);
  122378. }
  122379. sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r3);
  122380. if( eDest==SRT_DistQueue ){
  122381. sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r3);
  122382. sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  122383. }
  122384. for(i=0; i<nKey; i++){
  122385. sqlite3VdbeAddOp2(v, OP_SCopy,
  122386. regResult + pSO->a[i].u.x.iOrderByCol - 1,
  122387. r2+i);
  122388. }
  122389. sqlite3VdbeAddOp2(v, OP_Sequence, iParm, r2+nKey);
  122390. sqlite3VdbeAddOp3(v, OP_MakeRecord, r2, nKey+2, r1);
  122391. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, r2, nKey+2);
  122392. if( addrTest ) sqlite3VdbeJumpHere(v, addrTest);
  122393. sqlite3ReleaseTempReg(pParse, r1);
  122394. sqlite3ReleaseTempRange(pParse, r2, nKey+2);
  122395. break;
  122396. }
  122397. #endif /* SQLITE_OMIT_CTE */
  122398. #if !defined(SQLITE_OMIT_TRIGGER)
  122399. /* Discard the results. This is used for SELECT statements inside
  122400. ** the body of a TRIGGER. The purpose of such selects is to call
  122401. ** user-defined functions that have side effects. We do not care
  122402. ** about the actual results of the select.
  122403. */
  122404. default: {
  122405. assert( eDest==SRT_Discard );
  122406. break;
  122407. }
  122408. #endif
  122409. }
  122410. /* Jump to the end of the loop if the LIMIT is reached. Except, if
  122411. ** there is a sorter, in which case the sorter has already limited
  122412. ** the output for us.
  122413. */
  122414. if( pSort==0 && p->iLimit ){
  122415. sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v);
  122416. }
  122417. }
  122418. /*
  122419. ** Allocate a KeyInfo object sufficient for an index of N key columns and
  122420. ** X extra columns.
  122421. */
  122422. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3 *db, int N, int X){
  122423. int nExtra = (N+X)*(sizeof(CollSeq*)+1) - sizeof(CollSeq*);
  122424. KeyInfo *p = sqlite3DbMallocRawNN(db, sizeof(KeyInfo) + nExtra);
  122425. if( p ){
  122426. p->aSortFlags = (u8*)&p->aColl[N+X];
  122427. p->nKeyField = (u16)N;
  122428. p->nAllField = (u16)(N+X);
  122429. p->enc = ENC(db);
  122430. p->db = db;
  122431. p->nRef = 1;
  122432. memset(&p[1], 0, nExtra);
  122433. }else{
  122434. sqlite3OomFault(db);
  122435. }
  122436. return p;
  122437. }
  122438. /*
  122439. ** Deallocate a KeyInfo object
  122440. */
  122441. SQLITE_PRIVATE void sqlite3KeyInfoUnref(KeyInfo *p){
  122442. if( p ){
  122443. assert( p->nRef>0 );
  122444. p->nRef--;
  122445. if( p->nRef==0 ) sqlite3DbFreeNN(p->db, p);
  122446. }
  122447. }
  122448. /*
  122449. ** Make a new pointer to a KeyInfo object
  122450. */
  122451. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoRef(KeyInfo *p){
  122452. if( p ){
  122453. assert( p->nRef>0 );
  122454. p->nRef++;
  122455. }
  122456. return p;
  122457. }
  122458. #ifdef SQLITE_DEBUG
  122459. /*
  122460. ** Return TRUE if a KeyInfo object can be change. The KeyInfo object
  122461. ** can only be changed if this is just a single reference to the object.
  122462. **
  122463. ** This routine is used only inside of assert() statements.
  122464. */
  122465. SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo *p){ return p->nRef==1; }
  122466. #endif /* SQLITE_DEBUG */
  122467. /*
  122468. ** Given an expression list, generate a KeyInfo structure that records
  122469. ** the collating sequence for each expression in that expression list.
  122470. **
  122471. ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
  122472. ** KeyInfo structure is appropriate for initializing a virtual index to
  122473. ** implement that clause. If the ExprList is the result set of a SELECT
  122474. ** then the KeyInfo structure is appropriate for initializing a virtual
  122475. ** index to implement a DISTINCT test.
  122476. **
  122477. ** Space to hold the KeyInfo structure is obtained from malloc. The calling
  122478. ** function is responsible for seeing that this structure is eventually
  122479. ** freed.
  122480. */
  122481. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoFromExprList(
  122482. Parse *pParse, /* Parsing context */
  122483. ExprList *pList, /* Form the KeyInfo object from this ExprList */
  122484. int iStart, /* Begin with this column of pList */
  122485. int nExtra /* Add this many extra columns to the end */
  122486. ){
  122487. int nExpr;
  122488. KeyInfo *pInfo;
  122489. struct ExprList_item *pItem;
  122490. sqlite3 *db = pParse->db;
  122491. int i;
  122492. nExpr = pList->nExpr;
  122493. pInfo = sqlite3KeyInfoAlloc(db, nExpr-iStart, nExtra+1);
  122494. if( pInfo ){
  122495. assert( sqlite3KeyInfoIsWriteable(pInfo) );
  122496. for(i=iStart, pItem=pList->a+iStart; i<nExpr; i++, pItem++){
  122497. pInfo->aColl[i-iStart] = sqlite3ExprNNCollSeq(pParse, pItem->pExpr);
  122498. pInfo->aSortFlags[i-iStart] = pItem->sortFlags;
  122499. }
  122500. }
  122501. return pInfo;
  122502. }
  122503. /*
  122504. ** Name of the connection operator, used for error messages.
  122505. */
  122506. static const char *selectOpName(int id){
  122507. char *z;
  122508. switch( id ){
  122509. case TK_ALL: z = "UNION ALL"; break;
  122510. case TK_INTERSECT: z = "INTERSECT"; break;
  122511. case TK_EXCEPT: z = "EXCEPT"; break;
  122512. default: z = "UNION"; break;
  122513. }
  122514. return z;
  122515. }
  122516. #ifndef SQLITE_OMIT_EXPLAIN
  122517. /*
  122518. ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
  122519. ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
  122520. ** where the caption is of the form:
  122521. **
  122522. ** "USE TEMP B-TREE FOR xxx"
  122523. **
  122524. ** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which
  122525. ** is determined by the zUsage argument.
  122526. */
  122527. static void explainTempTable(Parse *pParse, const char *zUsage){
  122528. ExplainQueryPlan((pParse, 0, "USE TEMP B-TREE FOR %s", zUsage));
  122529. }
  122530. /*
  122531. ** Assign expression b to lvalue a. A second, no-op, version of this macro
  122532. ** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code
  122533. ** in sqlite3Select() to assign values to structure member variables that
  122534. ** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the
  122535. ** code with #ifndef directives.
  122536. */
  122537. # define explainSetInteger(a, b) a = b
  122538. #else
  122539. /* No-op versions of the explainXXX() functions and macros. */
  122540. # define explainTempTable(y,z)
  122541. # define explainSetInteger(y,z)
  122542. #endif
  122543. /*
  122544. ** If the inner loop was generated using a non-null pOrderBy argument,
  122545. ** then the results were placed in a sorter. After the loop is terminated
  122546. ** we need to run the sorter and output the results. The following
  122547. ** routine generates the code needed to do that.
  122548. */
  122549. static void generateSortTail(
  122550. Parse *pParse, /* Parsing context */
  122551. Select *p, /* The SELECT statement */
  122552. SortCtx *pSort, /* Information on the ORDER BY clause */
  122553. int nColumn, /* Number of columns of data */
  122554. SelectDest *pDest /* Write the sorted results here */
  122555. ){
  122556. Vdbe *v = pParse->pVdbe; /* The prepared statement */
  122557. int addrBreak = pSort->labelDone; /* Jump here to exit loop */
  122558. int addrContinue = sqlite3VdbeMakeLabel(pParse);/* Jump here for next cycle */
  122559. int addr; /* Top of output loop. Jump for Next. */
  122560. int addrOnce = 0;
  122561. int iTab;
  122562. ExprList *pOrderBy = pSort->pOrderBy;
  122563. int eDest = pDest->eDest;
  122564. int iParm = pDest->iSDParm;
  122565. int regRow;
  122566. int regRowid;
  122567. int iCol;
  122568. int nKey; /* Number of key columns in sorter record */
  122569. int iSortTab; /* Sorter cursor to read from */
  122570. int i;
  122571. int bSeq; /* True if sorter record includes seq. no. */
  122572. int nRefKey = 0;
  122573. struct ExprList_item *aOutEx = p->pEList->a;
  122574. assert( addrBreak<0 );
  122575. if( pSort->labelBkOut ){
  122576. sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
  122577. sqlite3VdbeGoto(v, addrBreak);
  122578. sqlite3VdbeResolveLabel(v, pSort->labelBkOut);
  122579. }
  122580. #ifdef SQLITE_ENABLE_SORTER_REFERENCES
  122581. /* Open any cursors needed for sorter-reference expressions */
  122582. for(i=0; i<pSort->nDefer; i++){
  122583. Table *pTab = pSort->aDefer[i].pTab;
  122584. int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  122585. sqlite3OpenTable(pParse, pSort->aDefer[i].iCsr, iDb, pTab, OP_OpenRead);
  122586. nRefKey = MAX(nRefKey, pSort->aDefer[i].nKey);
  122587. }
  122588. #endif
  122589. iTab = pSort->iECursor;
  122590. if( eDest==SRT_Output || eDest==SRT_Coroutine || eDest==SRT_Mem ){
  122591. regRowid = 0;
  122592. regRow = pDest->iSdst;
  122593. }else{
  122594. regRowid = sqlite3GetTempReg(pParse);
  122595. if( eDest==SRT_EphemTab || eDest==SRT_Table ){
  122596. regRow = sqlite3GetTempReg(pParse);
  122597. nColumn = 0;
  122598. }else{
  122599. regRow = sqlite3GetTempRange(pParse, nColumn);
  122600. }
  122601. }
  122602. nKey = pOrderBy->nExpr - pSort->nOBSat;
  122603. if( pSort->sortFlags & SORTFLAG_UseSorter ){
  122604. int regSortOut = ++pParse->nMem;
  122605. iSortTab = pParse->nTab++;
  122606. if( pSort->labelBkOut ){
  122607. addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
  122608. }
  122609. sqlite3VdbeAddOp3(v, OP_OpenPseudo, iSortTab, regSortOut,
  122610. nKey+1+nColumn+nRefKey);
  122611. if( addrOnce ) sqlite3VdbeJumpHere(v, addrOnce);
  122612. addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak);
  122613. VdbeCoverage(v);
  122614. codeOffset(v, p->iOffset, addrContinue);
  122615. sqlite3VdbeAddOp3(v, OP_SorterData, iTab, regSortOut, iSortTab);
  122616. bSeq = 0;
  122617. }else{
  122618. addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak); VdbeCoverage(v);
  122619. codeOffset(v, p->iOffset, addrContinue);
  122620. iSortTab = iTab;
  122621. bSeq = 1;
  122622. }
  122623. for(i=0, iCol=nKey+bSeq-1; i<nColumn; i++){
  122624. #ifdef SQLITE_ENABLE_SORTER_REFERENCES
  122625. if( aOutEx[i].bSorterRef ) continue;
  122626. #endif
  122627. if( aOutEx[i].u.x.iOrderByCol==0 ) iCol++;
  122628. }
  122629. #ifdef SQLITE_ENABLE_SORTER_REFERENCES
  122630. if( pSort->nDefer ){
  122631. int iKey = iCol+1;
  122632. int regKey = sqlite3GetTempRange(pParse, nRefKey);
  122633. for(i=0; i<pSort->nDefer; i++){
  122634. int iCsr = pSort->aDefer[i].iCsr;
  122635. Table *pTab = pSort->aDefer[i].pTab;
  122636. int nKey = pSort->aDefer[i].nKey;
  122637. sqlite3VdbeAddOp1(v, OP_NullRow, iCsr);
  122638. if( HasRowid(pTab) ){
  122639. sqlite3VdbeAddOp3(v, OP_Column, iSortTab, iKey++, regKey);
  122640. sqlite3VdbeAddOp3(v, OP_SeekRowid, iCsr,
  122641. sqlite3VdbeCurrentAddr(v)+1, regKey);
  122642. }else{
  122643. int k;
  122644. int iJmp;
  122645. assert( sqlite3PrimaryKeyIndex(pTab)->nKeyCol==nKey );
  122646. for(k=0; k<nKey; k++){
  122647. sqlite3VdbeAddOp3(v, OP_Column, iSortTab, iKey++, regKey+k);
  122648. }
  122649. iJmp = sqlite3VdbeCurrentAddr(v);
  122650. sqlite3VdbeAddOp4Int(v, OP_SeekGE, iCsr, iJmp+2, regKey, nKey);
  122651. sqlite3VdbeAddOp4Int(v, OP_IdxLE, iCsr, iJmp+3, regKey, nKey);
  122652. sqlite3VdbeAddOp1(v, OP_NullRow, iCsr);
  122653. }
  122654. }
  122655. sqlite3ReleaseTempRange(pParse, regKey, nRefKey);
  122656. }
  122657. #endif
  122658. for(i=nColumn-1; i>=0; i--){
  122659. #ifdef SQLITE_ENABLE_SORTER_REFERENCES
  122660. if( aOutEx[i].bSorterRef ){
  122661. sqlite3ExprCode(pParse, aOutEx[i].pExpr, regRow+i);
  122662. }else
  122663. #endif
  122664. {
  122665. int iRead;
  122666. if( aOutEx[i].u.x.iOrderByCol ){
  122667. iRead = aOutEx[i].u.x.iOrderByCol-1;
  122668. }else{
  122669. iRead = iCol--;
  122670. }
  122671. sqlite3VdbeAddOp3(v, OP_Column, iSortTab, iRead, regRow+i);
  122672. VdbeComment((v, "%s", aOutEx[i].zEName));
  122673. }
  122674. }
  122675. switch( eDest ){
  122676. case SRT_Table:
  122677. case SRT_EphemTab: {
  122678. sqlite3VdbeAddOp3(v, OP_Column, iSortTab, nKey+bSeq, regRow);
  122679. sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
  122680. sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
  122681. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  122682. break;
  122683. }
  122684. #ifndef SQLITE_OMIT_SUBQUERY
  122685. case SRT_Set: {
  122686. assert( nColumn==sqlite3Strlen30(pDest->zAffSdst) );
  122687. sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, nColumn, regRowid,
  122688. pDest->zAffSdst, nColumn);
  122689. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, regRowid, regRow, nColumn);
  122690. break;
  122691. }
  122692. case SRT_Mem: {
  122693. /* The LIMIT clause will terminate the loop for us */
  122694. break;
  122695. }
  122696. #endif
  122697. default: {
  122698. assert( eDest==SRT_Output || eDest==SRT_Coroutine );
  122699. testcase( eDest==SRT_Output );
  122700. testcase( eDest==SRT_Coroutine );
  122701. if( eDest==SRT_Output ){
  122702. sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iSdst, nColumn);
  122703. }else{
  122704. sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
  122705. }
  122706. break;
  122707. }
  122708. }
  122709. if( regRowid ){
  122710. if( eDest==SRT_Set ){
  122711. sqlite3ReleaseTempRange(pParse, regRow, nColumn);
  122712. }else{
  122713. sqlite3ReleaseTempReg(pParse, regRow);
  122714. }
  122715. sqlite3ReleaseTempReg(pParse, regRowid);
  122716. }
  122717. /* The bottom of the loop
  122718. */
  122719. sqlite3VdbeResolveLabel(v, addrContinue);
  122720. if( pSort->sortFlags & SORTFLAG_UseSorter ){
  122721. sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr); VdbeCoverage(v);
  122722. }else{
  122723. sqlite3VdbeAddOp2(v, OP_Next, iTab, addr); VdbeCoverage(v);
  122724. }
  122725. if( pSort->regReturn ) sqlite3VdbeAddOp1(v, OP_Return, pSort->regReturn);
  122726. sqlite3VdbeResolveLabel(v, addrBreak);
  122727. }
  122728. /*
  122729. ** Return a pointer to a string containing the 'declaration type' of the
  122730. ** expression pExpr. The string may be treated as static by the caller.
  122731. **
  122732. ** Also try to estimate the size of the returned value and return that
  122733. ** result in *pEstWidth.
  122734. **
  122735. ** The declaration type is the exact datatype definition extracted from the
  122736. ** original CREATE TABLE statement if the expression is a column. The
  122737. ** declaration type for a ROWID field is INTEGER. Exactly when an expression
  122738. ** is considered a column can be complex in the presence of subqueries. The
  122739. ** result-set expression in all of the following SELECT statements is
  122740. ** considered a column by this function.
  122741. **
  122742. ** SELECT col FROM tbl;
  122743. ** SELECT (SELECT col FROM tbl;
  122744. ** SELECT (SELECT col FROM tbl);
  122745. ** SELECT abc FROM (SELECT col AS abc FROM tbl);
  122746. **
  122747. ** The declaration type for any expression other than a column is NULL.
  122748. **
  122749. ** This routine has either 3 or 6 parameters depending on whether or not
  122750. ** the SQLITE_ENABLE_COLUMN_METADATA compile-time option is used.
  122751. */
  122752. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  122753. # define columnType(A,B,C,D,E) columnTypeImpl(A,B,C,D,E)
  122754. #else /* if !defined(SQLITE_ENABLE_COLUMN_METADATA) */
  122755. # define columnType(A,B,C,D,E) columnTypeImpl(A,B)
  122756. #endif
  122757. static const char *columnTypeImpl(
  122758. NameContext *pNC,
  122759. #ifndef SQLITE_ENABLE_COLUMN_METADATA
  122760. Expr *pExpr
  122761. #else
  122762. Expr *pExpr,
  122763. const char **pzOrigDb,
  122764. const char **pzOrigTab,
  122765. const char **pzOrigCol
  122766. #endif
  122767. ){
  122768. char const *zType = 0;
  122769. int j;
  122770. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  122771. char const *zOrigDb = 0;
  122772. char const *zOrigTab = 0;
  122773. char const *zOrigCol = 0;
  122774. #endif
  122775. assert( pExpr!=0 );
  122776. assert( pNC->pSrcList!=0 );
  122777. switch( pExpr->op ){
  122778. case TK_COLUMN: {
  122779. /* The expression is a column. Locate the table the column is being
  122780. ** extracted from in NameContext.pSrcList. This table may be real
  122781. ** database table or a subquery.
  122782. */
  122783. Table *pTab = 0; /* Table structure column is extracted from */
  122784. Select *pS = 0; /* Select the column is extracted from */
  122785. int iCol = pExpr->iColumn; /* Index of column in pTab */
  122786. while( pNC && !pTab ){
  122787. SrcList *pTabList = pNC->pSrcList;
  122788. for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
  122789. if( j<pTabList->nSrc ){
  122790. pTab = pTabList->a[j].pTab;
  122791. pS = pTabList->a[j].pSelect;
  122792. }else{
  122793. pNC = pNC->pNext;
  122794. }
  122795. }
  122796. if( pTab==0 ){
  122797. /* At one time, code such as "SELECT new.x" within a trigger would
  122798. ** cause this condition to run. Since then, we have restructured how
  122799. ** trigger code is generated and so this condition is no longer
  122800. ** possible. However, it can still be true for statements like
  122801. ** the following:
  122802. **
  122803. ** CREATE TABLE t1(col INTEGER);
  122804. ** SELECT (SELECT t1.col) FROM FROM t1;
  122805. **
  122806. ** when columnType() is called on the expression "t1.col" in the
  122807. ** sub-select. In this case, set the column type to NULL, even
  122808. ** though it should really be "INTEGER".
  122809. **
  122810. ** This is not a problem, as the column type of "t1.col" is never
  122811. ** used. When columnType() is called on the expression
  122812. ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
  122813. ** branch below. */
  122814. break;
  122815. }
  122816. assert( pTab && pExpr->y.pTab==pTab );
  122817. if( pS ){
  122818. /* The "table" is actually a sub-select or a view in the FROM clause
  122819. ** of the SELECT statement. Return the declaration type and origin
  122820. ** data for the result-set column of the sub-select.
  122821. */
  122822. if( iCol>=0 && iCol<pS->pEList->nExpr ){
  122823. /* If iCol is less than zero, then the expression requests the
  122824. ** rowid of the sub-select or view. This expression is legal (see
  122825. ** test case misc2.2.2) - it always evaluates to NULL.
  122826. */
  122827. NameContext sNC;
  122828. Expr *p = pS->pEList->a[iCol].pExpr;
  122829. sNC.pSrcList = pS->pSrc;
  122830. sNC.pNext = pNC;
  122831. sNC.pParse = pNC->pParse;
  122832. zType = columnType(&sNC, p,&zOrigDb,&zOrigTab,&zOrigCol);
  122833. }
  122834. }else{
  122835. /* A real table or a CTE table */
  122836. assert( !pS );
  122837. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  122838. if( iCol<0 ) iCol = pTab->iPKey;
  122839. assert( iCol==XN_ROWID || (iCol>=0 && iCol<pTab->nCol) );
  122840. if( iCol<0 ){
  122841. zType = "INTEGER";
  122842. zOrigCol = "rowid";
  122843. }else{
  122844. zOrigCol = pTab->aCol[iCol].zName;
  122845. zType = sqlite3ColumnType(&pTab->aCol[iCol],0);
  122846. }
  122847. zOrigTab = pTab->zName;
  122848. if( pNC->pParse && pTab->pSchema ){
  122849. int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
  122850. zOrigDb = pNC->pParse->db->aDb[iDb].zDbSName;
  122851. }
  122852. #else
  122853. assert( iCol==XN_ROWID || (iCol>=0 && iCol<pTab->nCol) );
  122854. if( iCol<0 ){
  122855. zType = "INTEGER";
  122856. }else{
  122857. zType = sqlite3ColumnType(&pTab->aCol[iCol],0);
  122858. }
  122859. #endif
  122860. }
  122861. break;
  122862. }
  122863. #ifndef SQLITE_OMIT_SUBQUERY
  122864. case TK_SELECT: {
  122865. /* The expression is a sub-select. Return the declaration type and
  122866. ** origin info for the single column in the result set of the SELECT
  122867. ** statement.
  122868. */
  122869. NameContext sNC;
  122870. Select *pS = pExpr->x.pSelect;
  122871. Expr *p = pS->pEList->a[0].pExpr;
  122872. assert( ExprHasProperty(pExpr, EP_xIsSelect) );
  122873. sNC.pSrcList = pS->pSrc;
  122874. sNC.pNext = pNC;
  122875. sNC.pParse = pNC->pParse;
  122876. zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
  122877. break;
  122878. }
  122879. #endif
  122880. }
  122881. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  122882. if( pzOrigDb ){
  122883. assert( pzOrigTab && pzOrigCol );
  122884. *pzOrigDb = zOrigDb;
  122885. *pzOrigTab = zOrigTab;
  122886. *pzOrigCol = zOrigCol;
  122887. }
  122888. #endif
  122889. return zType;
  122890. }
  122891. /*
  122892. ** Generate code that will tell the VDBE the declaration types of columns
  122893. ** in the result set.
  122894. */
  122895. static void generateColumnTypes(
  122896. Parse *pParse, /* Parser context */
  122897. SrcList *pTabList, /* List of tables */
  122898. ExprList *pEList /* Expressions defining the result set */
  122899. ){
  122900. #ifndef SQLITE_OMIT_DECLTYPE
  122901. Vdbe *v = pParse->pVdbe;
  122902. int i;
  122903. NameContext sNC;
  122904. sNC.pSrcList = pTabList;
  122905. sNC.pParse = pParse;
  122906. sNC.pNext = 0;
  122907. for(i=0; i<pEList->nExpr; i++){
  122908. Expr *p = pEList->a[i].pExpr;
  122909. const char *zType;
  122910. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  122911. const char *zOrigDb = 0;
  122912. const char *zOrigTab = 0;
  122913. const char *zOrigCol = 0;
  122914. zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
  122915. /* The vdbe must make its own copy of the column-type and other
  122916. ** column specific strings, in case the schema is reset before this
  122917. ** virtual machine is deleted.
  122918. */
  122919. sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
  122920. sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
  122921. sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
  122922. #else
  122923. zType = columnType(&sNC, p, 0, 0, 0);
  122924. #endif
  122925. sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
  122926. }
  122927. #endif /* !defined(SQLITE_OMIT_DECLTYPE) */
  122928. }
  122929. /*
  122930. ** Compute the column names for a SELECT statement.
  122931. **
  122932. ** The only guarantee that SQLite makes about column names is that if the
  122933. ** column has an AS clause assigning it a name, that will be the name used.
  122934. ** That is the only documented guarantee. However, countless applications
  122935. ** developed over the years have made baseless assumptions about column names
  122936. ** and will break if those assumptions changes. Hence, use extreme caution
  122937. ** when modifying this routine to avoid breaking legacy.
  122938. **
  122939. ** See Also: sqlite3ColumnsFromExprList()
  122940. **
  122941. ** The PRAGMA short_column_names and PRAGMA full_column_names settings are
  122942. ** deprecated. The default setting is short=ON, full=OFF. 99.9% of all
  122943. ** applications should operate this way. Nevertheless, we need to support the
  122944. ** other modes for legacy:
  122945. **
  122946. ** short=OFF, full=OFF: Column name is the text of the expression has it
  122947. ** originally appears in the SELECT statement. In
  122948. ** other words, the zSpan of the result expression.
  122949. **
  122950. ** short=ON, full=OFF: (This is the default setting). If the result
  122951. ** refers directly to a table column, then the
  122952. ** result column name is just the table column
  122953. ** name: COLUMN. Otherwise use zSpan.
  122954. **
  122955. ** full=ON, short=ANY: If the result refers directly to a table column,
  122956. ** then the result column name with the table name
  122957. ** prefix, ex: TABLE.COLUMN. Otherwise use zSpan.
  122958. */
  122959. static void generateColumnNames(
  122960. Parse *pParse, /* Parser context */
  122961. Select *pSelect /* Generate column names for this SELECT statement */
  122962. ){
  122963. Vdbe *v = pParse->pVdbe;
  122964. int i;
  122965. Table *pTab;
  122966. SrcList *pTabList;
  122967. ExprList *pEList;
  122968. sqlite3 *db = pParse->db;
  122969. int fullName; /* TABLE.COLUMN if no AS clause and is a direct table ref */
  122970. int srcName; /* COLUMN or TABLE.COLUMN if no AS clause and is direct */
  122971. #ifndef SQLITE_OMIT_EXPLAIN
  122972. /* If this is an EXPLAIN, skip this step */
  122973. if( pParse->explain ){
  122974. return;
  122975. }
  122976. #endif
  122977. if( pParse->colNamesSet ) return;
  122978. /* Column names are determined by the left-most term of a compound select */
  122979. while( pSelect->pPrior ) pSelect = pSelect->pPrior;
  122980. SELECTTRACE(1,pParse,pSelect,("generating column names\n"));
  122981. pTabList = pSelect->pSrc;
  122982. pEList = pSelect->pEList;
  122983. assert( v!=0 );
  122984. assert( pTabList!=0 );
  122985. pParse->colNamesSet = 1;
  122986. fullName = (db->flags & SQLITE_FullColNames)!=0;
  122987. srcName = (db->flags & SQLITE_ShortColNames)!=0 || fullName;
  122988. sqlite3VdbeSetNumCols(v, pEList->nExpr);
  122989. for(i=0; i<pEList->nExpr; i++){
  122990. Expr *p = pEList->a[i].pExpr;
  122991. assert( p!=0 );
  122992. assert( p->op!=TK_AGG_COLUMN ); /* Agg processing has not run yet */
  122993. assert( p->op!=TK_COLUMN || p->y.pTab!=0 ); /* Covering idx not yet coded */
  122994. if( pEList->a[i].zEName && pEList->a[i].eEName==ENAME_NAME ){
  122995. /* An AS clause always takes first priority */
  122996. char *zName = pEList->a[i].zEName;
  122997. sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
  122998. }else if( srcName && p->op==TK_COLUMN ){
  122999. char *zCol;
  123000. int iCol = p->iColumn;
  123001. pTab = p->y.pTab;
  123002. assert( pTab!=0 );
  123003. if( iCol<0 ) iCol = pTab->iPKey;
  123004. assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
  123005. if( iCol<0 ){
  123006. zCol = "rowid";
  123007. }else{
  123008. zCol = pTab->aCol[iCol].zName;
  123009. }
  123010. if( fullName ){
  123011. char *zName = 0;
  123012. zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
  123013. sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
  123014. }else{
  123015. sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
  123016. }
  123017. }else{
  123018. const char *z = pEList->a[i].zEName;
  123019. z = z==0 ? sqlite3MPrintf(db, "column%d", i+1) : sqlite3DbStrDup(db, z);
  123020. sqlite3VdbeSetColName(v, i, COLNAME_NAME, z, SQLITE_DYNAMIC);
  123021. }
  123022. }
  123023. generateColumnTypes(pParse, pTabList, pEList);
  123024. }
  123025. /*
  123026. ** Given an expression list (which is really the list of expressions
  123027. ** that form the result set of a SELECT statement) compute appropriate
  123028. ** column names for a table that would hold the expression list.
  123029. **
  123030. ** All column names will be unique.
  123031. **
  123032. ** Only the column names are computed. Column.zType, Column.zColl,
  123033. ** and other fields of Column are zeroed.
  123034. **
  123035. ** Return SQLITE_OK on success. If a memory allocation error occurs,
  123036. ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
  123037. **
  123038. ** The only guarantee that SQLite makes about column names is that if the
  123039. ** column has an AS clause assigning it a name, that will be the name used.
  123040. ** That is the only documented guarantee. However, countless applications
  123041. ** developed over the years have made baseless assumptions about column names
  123042. ** and will break if those assumptions changes. Hence, use extreme caution
  123043. ** when modifying this routine to avoid breaking legacy.
  123044. **
  123045. ** See Also: generateColumnNames()
  123046. */
  123047. SQLITE_PRIVATE int sqlite3ColumnsFromExprList(
  123048. Parse *pParse, /* Parsing context */
  123049. ExprList *pEList, /* Expr list from which to derive column names */
  123050. i16 *pnCol, /* Write the number of columns here */
  123051. Column **paCol /* Write the new column list here */
  123052. ){
  123053. sqlite3 *db = pParse->db; /* Database connection */
  123054. int i, j; /* Loop counters */
  123055. u32 cnt; /* Index added to make the name unique */
  123056. Column *aCol, *pCol; /* For looping over result columns */
  123057. int nCol; /* Number of columns in the result set */
  123058. char *zName; /* Column name */
  123059. int nName; /* Size of name in zName[] */
  123060. Hash ht; /* Hash table of column names */
  123061. sqlite3HashInit(&ht);
  123062. if( pEList ){
  123063. nCol = pEList->nExpr;
  123064. aCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
  123065. testcase( aCol==0 );
  123066. if( nCol>32767 ) nCol = 32767;
  123067. }else{
  123068. nCol = 0;
  123069. aCol = 0;
  123070. }
  123071. assert( nCol==(i16)nCol );
  123072. *pnCol = nCol;
  123073. *paCol = aCol;
  123074. for(i=0, pCol=aCol; i<nCol && !db->mallocFailed; i++, pCol++){
  123075. /* Get an appropriate name for the column
  123076. */
  123077. if( (zName = pEList->a[i].zEName)!=0 && pEList->a[i].eEName==ENAME_NAME ){
  123078. /* If the column contains an "AS <name>" phrase, use <name> as the name */
  123079. }else{
  123080. Expr *pColExpr = sqlite3ExprSkipCollateAndLikely(pEList->a[i].pExpr);
  123081. while( pColExpr->op==TK_DOT ){
  123082. pColExpr = pColExpr->pRight;
  123083. assert( pColExpr!=0 );
  123084. }
  123085. if( pColExpr->op==TK_COLUMN ){
  123086. /* For columns use the column name name */
  123087. int iCol = pColExpr->iColumn;
  123088. Table *pTab = pColExpr->y.pTab;
  123089. assert( pTab!=0 );
  123090. if( iCol<0 ) iCol = pTab->iPKey;
  123091. zName = iCol>=0 ? pTab->aCol[iCol].zName : "rowid";
  123092. }else if( pColExpr->op==TK_ID ){
  123093. assert( !ExprHasProperty(pColExpr, EP_IntValue) );
  123094. zName = pColExpr->u.zToken;
  123095. }else{
  123096. /* Use the original text of the column expression as its name */
  123097. zName = pEList->a[i].zEName;
  123098. }
  123099. }
  123100. if( zName && !sqlite3IsTrueOrFalse(zName) ){
  123101. zName = sqlite3DbStrDup(db, zName);
  123102. }else{
  123103. zName = sqlite3MPrintf(db,"column%d",i+1);
  123104. }
  123105. /* Make sure the column name is unique. If the name is not unique,
  123106. ** append an integer to the name so that it becomes unique.
  123107. */
  123108. cnt = 0;
  123109. while( zName && sqlite3HashFind(&ht, zName)!=0 ){
  123110. nName = sqlite3Strlen30(zName);
  123111. if( nName>0 ){
  123112. for(j=nName-1; j>0 && sqlite3Isdigit(zName[j]); j--){}
  123113. if( zName[j]==':' ) nName = j;
  123114. }
  123115. zName = sqlite3MPrintf(db, "%.*z:%u", nName, zName, ++cnt);
  123116. if( cnt>3 ) sqlite3_randomness(sizeof(cnt), &cnt);
  123117. }
  123118. pCol->zName = zName;
  123119. pCol->hName = sqlite3StrIHash(zName);
  123120. sqlite3ColumnPropertiesFromName(0, pCol);
  123121. if( zName && sqlite3HashInsert(&ht, zName, pCol)==pCol ){
  123122. sqlite3OomFault(db);
  123123. }
  123124. }
  123125. sqlite3HashClear(&ht);
  123126. if( db->mallocFailed ){
  123127. for(j=0; j<i; j++){
  123128. sqlite3DbFree(db, aCol[j].zName);
  123129. }
  123130. sqlite3DbFree(db, aCol);
  123131. *paCol = 0;
  123132. *pnCol = 0;
  123133. return SQLITE_NOMEM_BKPT;
  123134. }
  123135. return SQLITE_OK;
  123136. }
  123137. /*
  123138. ** Add type and collation information to a column list based on
  123139. ** a SELECT statement.
  123140. **
  123141. ** The column list presumably came from selectColumnNamesFromExprList().
  123142. ** The column list has only names, not types or collations. This
  123143. ** routine goes through and adds the types and collations.
  123144. **
  123145. ** This routine requires that all identifiers in the SELECT
  123146. ** statement be resolved.
  123147. */
  123148. SQLITE_PRIVATE void sqlite3SelectAddColumnTypeAndCollation(
  123149. Parse *pParse, /* Parsing contexts */
  123150. Table *pTab, /* Add column type information to this table */
  123151. Select *pSelect, /* SELECT used to determine types and collations */
  123152. char aff /* Default affinity for columns */
  123153. ){
  123154. sqlite3 *db = pParse->db;
  123155. NameContext sNC;
  123156. Column *pCol;
  123157. CollSeq *pColl;
  123158. int i;
  123159. Expr *p;
  123160. struct ExprList_item *a;
  123161. assert( pSelect!=0 );
  123162. assert( (pSelect->selFlags & SF_Resolved)!=0 );
  123163. assert( pTab->nCol==pSelect->pEList->nExpr || db->mallocFailed );
  123164. if( db->mallocFailed ) return;
  123165. memset(&sNC, 0, sizeof(sNC));
  123166. sNC.pSrcList = pSelect->pSrc;
  123167. a = pSelect->pEList->a;
  123168. for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
  123169. const char *zType;
  123170. int n, m;
  123171. p = a[i].pExpr;
  123172. zType = columnType(&sNC, p, 0, 0, 0);
  123173. /* pCol->szEst = ... // Column size est for SELECT tables never used */
  123174. pCol->affinity = sqlite3ExprAffinity(p);
  123175. if( zType ){
  123176. m = sqlite3Strlen30(zType);
  123177. n = sqlite3Strlen30(pCol->zName);
  123178. pCol->zName = sqlite3DbReallocOrFree(db, pCol->zName, n+m+2);
  123179. if( pCol->zName ){
  123180. memcpy(&pCol->zName[n+1], zType, m+1);
  123181. pCol->colFlags |= COLFLAG_HASTYPE;
  123182. }
  123183. }
  123184. if( pCol->affinity<=SQLITE_AFF_NONE ) pCol->affinity = aff;
  123185. pColl = sqlite3ExprCollSeq(pParse, p);
  123186. if( pColl && pCol->zColl==0 ){
  123187. pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
  123188. }
  123189. }
  123190. pTab->szTabRow = 1; /* Any non-zero value works */
  123191. }
  123192. /*
  123193. ** Given a SELECT statement, generate a Table structure that describes
  123194. ** the result set of that SELECT.
  123195. */
  123196. SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect, char aff){
  123197. Table *pTab;
  123198. sqlite3 *db = pParse->db;
  123199. u64 savedFlags;
  123200. savedFlags = db->flags;
  123201. db->flags &= ~(u64)SQLITE_FullColNames;
  123202. db->flags |= SQLITE_ShortColNames;
  123203. sqlite3SelectPrep(pParse, pSelect, 0);
  123204. db->flags = savedFlags;
  123205. if( pParse->nErr ) return 0;
  123206. while( pSelect->pPrior ) pSelect = pSelect->pPrior;
  123207. pTab = sqlite3DbMallocZero(db, sizeof(Table) );
  123208. if( pTab==0 ){
  123209. return 0;
  123210. }
  123211. pTab->nTabRef = 1;
  123212. pTab->zName = 0;
  123213. pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
  123214. sqlite3ColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
  123215. sqlite3SelectAddColumnTypeAndCollation(pParse, pTab, pSelect, aff);
  123216. pTab->iPKey = -1;
  123217. if( db->mallocFailed ){
  123218. sqlite3DeleteTable(db, pTab);
  123219. return 0;
  123220. }
  123221. return pTab;
  123222. }
  123223. /*
  123224. ** Get a VDBE for the given parser context. Create a new one if necessary.
  123225. ** If an error occurs, return NULL and leave a message in pParse.
  123226. */
  123227. SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
  123228. if( pParse->pVdbe ){
  123229. return pParse->pVdbe;
  123230. }
  123231. if( pParse->pToplevel==0
  123232. && OptimizationEnabled(pParse->db,SQLITE_FactorOutConst)
  123233. ){
  123234. pParse->okConstFactor = 1;
  123235. }
  123236. return sqlite3VdbeCreate(pParse);
  123237. }
  123238. /*
  123239. ** Compute the iLimit and iOffset fields of the SELECT based on the
  123240. ** pLimit expressions. pLimit->pLeft and pLimit->pRight hold the expressions
  123241. ** that appear in the original SQL statement after the LIMIT and OFFSET
  123242. ** keywords. Or NULL if those keywords are omitted. iLimit and iOffset
  123243. ** are the integer memory register numbers for counters used to compute
  123244. ** the limit and offset. If there is no limit and/or offset, then
  123245. ** iLimit and iOffset are negative.
  123246. **
  123247. ** This routine changes the values of iLimit and iOffset only if
  123248. ** a limit or offset is defined by pLimit->pLeft and pLimit->pRight. iLimit
  123249. ** and iOffset should have been preset to appropriate default values (zero)
  123250. ** prior to calling this routine.
  123251. **
  123252. ** The iOffset register (if it exists) is initialized to the value
  123253. ** of the OFFSET. The iLimit register is initialized to LIMIT. Register
  123254. ** iOffset+1 is initialized to LIMIT+OFFSET.
  123255. **
  123256. ** Only if pLimit->pLeft!=0 do the limit registers get
  123257. ** redefined. The UNION ALL operator uses this property to force
  123258. ** the reuse of the same limit and offset registers across multiple
  123259. ** SELECT statements.
  123260. */
  123261. static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
  123262. Vdbe *v = 0;
  123263. int iLimit = 0;
  123264. int iOffset;
  123265. int n;
  123266. Expr *pLimit = p->pLimit;
  123267. if( p->iLimit ) return;
  123268. /*
  123269. ** "LIMIT -1" always shows all rows. There is some
  123270. ** controversy about what the correct behavior should be.
  123271. ** The current implementation interprets "LIMIT 0" to mean
  123272. ** no rows.
  123273. */
  123274. if( pLimit ){
  123275. assert( pLimit->op==TK_LIMIT );
  123276. assert( pLimit->pLeft!=0 );
  123277. p->iLimit = iLimit = ++pParse->nMem;
  123278. v = sqlite3GetVdbe(pParse);
  123279. assert( v!=0 );
  123280. if( sqlite3ExprIsInteger(pLimit->pLeft, &n) ){
  123281. sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
  123282. VdbeComment((v, "LIMIT counter"));
  123283. if( n==0 ){
  123284. sqlite3VdbeGoto(v, iBreak);
  123285. }else if( n>=0 && p->nSelectRow>sqlite3LogEst((u64)n) ){
  123286. p->nSelectRow = sqlite3LogEst((u64)n);
  123287. p->selFlags |= SF_FixedLimit;
  123288. }
  123289. }else{
  123290. sqlite3ExprCode(pParse, pLimit->pLeft, iLimit);
  123291. sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit); VdbeCoverage(v);
  123292. VdbeComment((v, "LIMIT counter"));
  123293. sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, iBreak); VdbeCoverage(v);
  123294. }
  123295. if( pLimit->pRight ){
  123296. p->iOffset = iOffset = ++pParse->nMem;
  123297. pParse->nMem++; /* Allocate an extra register for limit+offset */
  123298. sqlite3ExprCode(pParse, pLimit->pRight, iOffset);
  123299. sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset); VdbeCoverage(v);
  123300. VdbeComment((v, "OFFSET counter"));
  123301. sqlite3VdbeAddOp3(v, OP_OffsetLimit, iLimit, iOffset+1, iOffset);
  123302. VdbeComment((v, "LIMIT+OFFSET"));
  123303. }
  123304. }
  123305. }
  123306. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  123307. /*
  123308. ** Return the appropriate collating sequence for the iCol-th column of
  123309. ** the result set for the compound-select statement "p". Return NULL if
  123310. ** the column has no default collating sequence.
  123311. **
  123312. ** The collating sequence for the compound select is taken from the
  123313. ** left-most term of the select that has a collating sequence.
  123314. */
  123315. static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
  123316. CollSeq *pRet;
  123317. if( p->pPrior ){
  123318. pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
  123319. }else{
  123320. pRet = 0;
  123321. }
  123322. assert( iCol>=0 );
  123323. /* iCol must be less than p->pEList->nExpr. Otherwise an error would
  123324. ** have been thrown during name resolution and we would not have gotten
  123325. ** this far */
  123326. if( pRet==0 && ALWAYS(iCol<p->pEList->nExpr) ){
  123327. pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
  123328. }
  123329. return pRet;
  123330. }
  123331. /*
  123332. ** The select statement passed as the second parameter is a compound SELECT
  123333. ** with an ORDER BY clause. This function allocates and returns a KeyInfo
  123334. ** structure suitable for implementing the ORDER BY.
  123335. **
  123336. ** Space to hold the KeyInfo structure is obtained from malloc. The calling
  123337. ** function is responsible for ensuring that this structure is eventually
  123338. ** freed.
  123339. */
  123340. static KeyInfo *multiSelectOrderByKeyInfo(Parse *pParse, Select *p, int nExtra){
  123341. ExprList *pOrderBy = p->pOrderBy;
  123342. int nOrderBy = p->pOrderBy->nExpr;
  123343. sqlite3 *db = pParse->db;
  123344. KeyInfo *pRet = sqlite3KeyInfoAlloc(db, nOrderBy+nExtra, 1);
  123345. if( pRet ){
  123346. int i;
  123347. for(i=0; i<nOrderBy; i++){
  123348. struct ExprList_item *pItem = &pOrderBy->a[i];
  123349. Expr *pTerm = pItem->pExpr;
  123350. CollSeq *pColl;
  123351. if( pTerm->flags & EP_Collate ){
  123352. pColl = sqlite3ExprCollSeq(pParse, pTerm);
  123353. }else{
  123354. pColl = multiSelectCollSeq(pParse, p, pItem->u.x.iOrderByCol-1);
  123355. if( pColl==0 ) pColl = db->pDfltColl;
  123356. pOrderBy->a[i].pExpr =
  123357. sqlite3ExprAddCollateString(pParse, pTerm, pColl->zName);
  123358. }
  123359. assert( sqlite3KeyInfoIsWriteable(pRet) );
  123360. pRet->aColl[i] = pColl;
  123361. pRet->aSortFlags[i] = pOrderBy->a[i].sortFlags;
  123362. }
  123363. }
  123364. return pRet;
  123365. }
  123366. #ifndef SQLITE_OMIT_CTE
  123367. /*
  123368. ** This routine generates VDBE code to compute the content of a WITH RECURSIVE
  123369. ** query of the form:
  123370. **
  123371. ** <recursive-table> AS (<setup-query> UNION [ALL] <recursive-query>)
  123372. ** \___________/ \_______________/
  123373. ** p->pPrior p
  123374. **
  123375. **
  123376. ** There is exactly one reference to the recursive-table in the FROM clause
  123377. ** of recursive-query, marked with the SrcList->a[].fg.isRecursive flag.
  123378. **
  123379. ** The setup-query runs once to generate an initial set of rows that go
  123380. ** into a Queue table. Rows are extracted from the Queue table one by
  123381. ** one. Each row extracted from Queue is output to pDest. Then the single
  123382. ** extracted row (now in the iCurrent table) becomes the content of the
  123383. ** recursive-table for a recursive-query run. The output of the recursive-query
  123384. ** is added back into the Queue table. Then another row is extracted from Queue
  123385. ** and the iteration continues until the Queue table is empty.
  123386. **
  123387. ** If the compound query operator is UNION then no duplicate rows are ever
  123388. ** inserted into the Queue table. The iDistinct table keeps a copy of all rows
  123389. ** that have ever been inserted into Queue and causes duplicates to be
  123390. ** discarded. If the operator is UNION ALL, then duplicates are allowed.
  123391. **
  123392. ** If the query has an ORDER BY, then entries in the Queue table are kept in
  123393. ** ORDER BY order and the first entry is extracted for each cycle. Without
  123394. ** an ORDER BY, the Queue table is just a FIFO.
  123395. **
  123396. ** If a LIMIT clause is provided, then the iteration stops after LIMIT rows
  123397. ** have been output to pDest. A LIMIT of zero means to output no rows and a
  123398. ** negative LIMIT means to output all rows. If there is also an OFFSET clause
  123399. ** with a positive value, then the first OFFSET outputs are discarded rather
  123400. ** than being sent to pDest. The LIMIT count does not begin until after OFFSET
  123401. ** rows have been skipped.
  123402. */
  123403. static void generateWithRecursiveQuery(
  123404. Parse *pParse, /* Parsing context */
  123405. Select *p, /* The recursive SELECT to be coded */
  123406. SelectDest *pDest /* What to do with query results */
  123407. ){
  123408. SrcList *pSrc = p->pSrc; /* The FROM clause of the recursive query */
  123409. int nCol = p->pEList->nExpr; /* Number of columns in the recursive table */
  123410. Vdbe *v = pParse->pVdbe; /* The prepared statement under construction */
  123411. Select *pSetup = p->pPrior; /* The setup query */
  123412. int addrTop; /* Top of the loop */
  123413. int addrCont, addrBreak; /* CONTINUE and BREAK addresses */
  123414. int iCurrent = 0; /* The Current table */
  123415. int regCurrent; /* Register holding Current table */
  123416. int iQueue; /* The Queue table */
  123417. int iDistinct = 0; /* To ensure unique results if UNION */
  123418. int eDest = SRT_Fifo; /* How to write to Queue */
  123419. SelectDest destQueue; /* SelectDest targetting the Queue table */
  123420. int i; /* Loop counter */
  123421. int rc; /* Result code */
  123422. ExprList *pOrderBy; /* The ORDER BY clause */
  123423. Expr *pLimit; /* Saved LIMIT and OFFSET */
  123424. int regLimit, regOffset; /* Registers used by LIMIT and OFFSET */
  123425. #ifndef SQLITE_OMIT_WINDOWFUNC
  123426. if( p->pWin ){
  123427. sqlite3ErrorMsg(pParse, "cannot use window functions in recursive queries");
  123428. return;
  123429. }
  123430. #endif
  123431. /* Obtain authorization to do a recursive query */
  123432. if( sqlite3AuthCheck(pParse, SQLITE_RECURSIVE, 0, 0, 0) ) return;
  123433. /* Process the LIMIT and OFFSET clauses, if they exist */
  123434. addrBreak = sqlite3VdbeMakeLabel(pParse);
  123435. p->nSelectRow = 320; /* 4 billion rows */
  123436. computeLimitRegisters(pParse, p, addrBreak);
  123437. pLimit = p->pLimit;
  123438. regLimit = p->iLimit;
  123439. regOffset = p->iOffset;
  123440. p->pLimit = 0;
  123441. p->iLimit = p->iOffset = 0;
  123442. pOrderBy = p->pOrderBy;
  123443. /* Locate the cursor number of the Current table */
  123444. for(i=0; ALWAYS(i<pSrc->nSrc); i++){
  123445. if( pSrc->a[i].fg.isRecursive ){
  123446. iCurrent = pSrc->a[i].iCursor;
  123447. break;
  123448. }
  123449. }
  123450. /* Allocate cursors numbers for Queue and Distinct. The cursor number for
  123451. ** the Distinct table must be exactly one greater than Queue in order
  123452. ** for the SRT_DistFifo and SRT_DistQueue destinations to work. */
  123453. iQueue = pParse->nTab++;
  123454. if( p->op==TK_UNION ){
  123455. eDest = pOrderBy ? SRT_DistQueue : SRT_DistFifo;
  123456. iDistinct = pParse->nTab++;
  123457. }else{
  123458. eDest = pOrderBy ? SRT_Queue : SRT_Fifo;
  123459. }
  123460. sqlite3SelectDestInit(&destQueue, eDest, iQueue);
  123461. /* Allocate cursors for Current, Queue, and Distinct. */
  123462. regCurrent = ++pParse->nMem;
  123463. sqlite3VdbeAddOp3(v, OP_OpenPseudo, iCurrent, regCurrent, nCol);
  123464. if( pOrderBy ){
  123465. KeyInfo *pKeyInfo = multiSelectOrderByKeyInfo(pParse, p, 1);
  123466. sqlite3VdbeAddOp4(v, OP_OpenEphemeral, iQueue, pOrderBy->nExpr+2, 0,
  123467. (char*)pKeyInfo, P4_KEYINFO);
  123468. destQueue.pOrderBy = pOrderBy;
  123469. }else{
  123470. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iQueue, nCol);
  123471. }
  123472. VdbeComment((v, "Queue table"));
  123473. if( iDistinct ){
  123474. p->addrOpenEphm[0] = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iDistinct, 0);
  123475. p->selFlags |= SF_UsesEphemeral;
  123476. }
  123477. /* Detach the ORDER BY clause from the compound SELECT */
  123478. p->pOrderBy = 0;
  123479. /* Store the results of the setup-query in Queue. */
  123480. pSetup->pNext = 0;
  123481. ExplainQueryPlan((pParse, 1, "SETUP"));
  123482. rc = sqlite3Select(pParse, pSetup, &destQueue);
  123483. pSetup->pNext = p;
  123484. if( rc ) goto end_of_recursive_query;
  123485. /* Find the next row in the Queue and output that row */
  123486. addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iQueue, addrBreak); VdbeCoverage(v);
  123487. /* Transfer the next row in Queue over to Current */
  123488. sqlite3VdbeAddOp1(v, OP_NullRow, iCurrent); /* To reset column cache */
  123489. if( pOrderBy ){
  123490. sqlite3VdbeAddOp3(v, OP_Column, iQueue, pOrderBy->nExpr+1, regCurrent);
  123491. }else{
  123492. sqlite3VdbeAddOp2(v, OP_RowData, iQueue, regCurrent);
  123493. }
  123494. sqlite3VdbeAddOp1(v, OP_Delete, iQueue);
  123495. /* Output the single row in Current */
  123496. addrCont = sqlite3VdbeMakeLabel(pParse);
  123497. codeOffset(v, regOffset, addrCont);
  123498. selectInnerLoop(pParse, p, iCurrent,
  123499. 0, 0, pDest, addrCont, addrBreak);
  123500. if( regLimit ){
  123501. sqlite3VdbeAddOp2(v, OP_DecrJumpZero, regLimit, addrBreak);
  123502. VdbeCoverage(v);
  123503. }
  123504. sqlite3VdbeResolveLabel(v, addrCont);
  123505. /* Execute the recursive SELECT taking the single row in Current as
  123506. ** the value for the recursive-table. Store the results in the Queue.
  123507. */
  123508. if( p->selFlags & SF_Aggregate ){
  123509. sqlite3ErrorMsg(pParse, "recursive aggregate queries not supported");
  123510. }else{
  123511. p->pPrior = 0;
  123512. ExplainQueryPlan((pParse, 1, "RECURSIVE STEP"));
  123513. sqlite3Select(pParse, p, &destQueue);
  123514. assert( p->pPrior==0 );
  123515. p->pPrior = pSetup;
  123516. }
  123517. /* Keep running the loop until the Queue is empty */
  123518. sqlite3VdbeGoto(v, addrTop);
  123519. sqlite3VdbeResolveLabel(v, addrBreak);
  123520. end_of_recursive_query:
  123521. sqlite3ExprListDelete(pParse->db, p->pOrderBy);
  123522. p->pOrderBy = pOrderBy;
  123523. p->pLimit = pLimit;
  123524. return;
  123525. }
  123526. #endif /* SQLITE_OMIT_CTE */
  123527. /* Forward references */
  123528. static int multiSelectOrderBy(
  123529. Parse *pParse, /* Parsing context */
  123530. Select *p, /* The right-most of SELECTs to be coded */
  123531. SelectDest *pDest /* What to do with query results */
  123532. );
  123533. /*
  123534. ** Handle the special case of a compound-select that originates from a
  123535. ** VALUES clause. By handling this as a special case, we avoid deep
  123536. ** recursion, and thus do not need to enforce the SQLITE_LIMIT_COMPOUND_SELECT
  123537. ** on a VALUES clause.
  123538. **
  123539. ** Because the Select object originates from a VALUES clause:
  123540. ** (1) There is no LIMIT or OFFSET or else there is a LIMIT of exactly 1
  123541. ** (2) All terms are UNION ALL
  123542. ** (3) There is no ORDER BY clause
  123543. **
  123544. ** The "LIMIT of exactly 1" case of condition (1) comes about when a VALUES
  123545. ** clause occurs within scalar expression (ex: "SELECT (VALUES(1),(2),(3))").
  123546. ** The sqlite3CodeSubselect will have added the LIMIT 1 clause in tht case.
  123547. ** Since the limit is exactly 1, we only need to evalutes the left-most VALUES.
  123548. */
  123549. static int multiSelectValues(
  123550. Parse *pParse, /* Parsing context */
  123551. Select *p, /* The right-most of SELECTs to be coded */
  123552. SelectDest *pDest /* What to do with query results */
  123553. ){
  123554. int nRow = 1;
  123555. int rc = 0;
  123556. int bShowAll = p->pLimit==0;
  123557. assert( p->selFlags & SF_MultiValue );
  123558. do{
  123559. assert( p->selFlags & SF_Values );
  123560. assert( p->op==TK_ALL || (p->op==TK_SELECT && p->pPrior==0) );
  123561. assert( p->pNext==0 || p->pEList->nExpr==p->pNext->pEList->nExpr );
  123562. #ifndef SQLITE_OMIT_WINDOWFUNC
  123563. if( p->pWin ) return -1;
  123564. #endif
  123565. if( p->pPrior==0 ) break;
  123566. assert( p->pPrior->pNext==p );
  123567. p = p->pPrior;
  123568. nRow += bShowAll;
  123569. }while(1);
  123570. ExplainQueryPlan((pParse, 0, "SCAN %d CONSTANT ROW%s", nRow,
  123571. nRow==1 ? "" : "S"));
  123572. while( p ){
  123573. selectInnerLoop(pParse, p, -1, 0, 0, pDest, 1, 1);
  123574. if( !bShowAll ) break;
  123575. p->nSelectRow = nRow;
  123576. p = p->pNext;
  123577. }
  123578. return rc;
  123579. }
  123580. /*
  123581. ** This routine is called to process a compound query form from
  123582. ** two or more separate queries using UNION, UNION ALL, EXCEPT, or
  123583. ** INTERSECT
  123584. **
  123585. ** "p" points to the right-most of the two queries. the query on the
  123586. ** left is p->pPrior. The left query could also be a compound query
  123587. ** in which case this routine will be called recursively.
  123588. **
  123589. ** The results of the total query are to be written into a destination
  123590. ** of type eDest with parameter iParm.
  123591. **
  123592. ** Example 1: Consider a three-way compound SQL statement.
  123593. **
  123594. ** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
  123595. **
  123596. ** This statement is parsed up as follows:
  123597. **
  123598. ** SELECT c FROM t3
  123599. ** |
  123600. ** `-----> SELECT b FROM t2
  123601. ** |
  123602. ** `------> SELECT a FROM t1
  123603. **
  123604. ** The arrows in the diagram above represent the Select.pPrior pointer.
  123605. ** So if this routine is called with p equal to the t3 query, then
  123606. ** pPrior will be the t2 query. p->op will be TK_UNION in this case.
  123607. **
  123608. ** Notice that because of the way SQLite parses compound SELECTs, the
  123609. ** individual selects always group from left to right.
  123610. */
  123611. static int multiSelect(
  123612. Parse *pParse, /* Parsing context */
  123613. Select *p, /* The right-most of SELECTs to be coded */
  123614. SelectDest *pDest /* What to do with query results */
  123615. ){
  123616. int rc = SQLITE_OK; /* Success code from a subroutine */
  123617. Select *pPrior; /* Another SELECT immediately to our left */
  123618. Vdbe *v; /* Generate code to this VDBE */
  123619. SelectDest dest; /* Alternative data destination */
  123620. Select *pDelete = 0; /* Chain of simple selects to delete */
  123621. sqlite3 *db; /* Database connection */
  123622. /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only
  123623. ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
  123624. */
  123625. assert( p && p->pPrior ); /* Calling function guarantees this much */
  123626. assert( (p->selFlags & SF_Recursive)==0 || p->op==TK_ALL || p->op==TK_UNION );
  123627. assert( p->selFlags & SF_Compound );
  123628. db = pParse->db;
  123629. pPrior = p->pPrior;
  123630. dest = *pDest;
  123631. if( pPrior->pOrderBy || pPrior->pLimit ){
  123632. sqlite3ErrorMsg(pParse,"%s clause should come after %s not before",
  123633. pPrior->pOrderBy!=0 ? "ORDER BY" : "LIMIT", selectOpName(p->op));
  123634. rc = 1;
  123635. goto multi_select_end;
  123636. }
  123637. v = sqlite3GetVdbe(pParse);
  123638. assert( v!=0 ); /* The VDBE already created by calling function */
  123639. /* Create the destination temporary table if necessary
  123640. */
  123641. if( dest.eDest==SRT_EphemTab ){
  123642. assert( p->pEList );
  123643. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr);
  123644. dest.eDest = SRT_Table;
  123645. }
  123646. /* Special handling for a compound-select that originates as a VALUES clause.
  123647. */
  123648. if( p->selFlags & SF_MultiValue ){
  123649. rc = multiSelectValues(pParse, p, &dest);
  123650. if( rc>=0 ) goto multi_select_end;
  123651. rc = SQLITE_OK;
  123652. }
  123653. /* Make sure all SELECTs in the statement have the same number of elements
  123654. ** in their result sets.
  123655. */
  123656. assert( p->pEList && pPrior->pEList );
  123657. assert( p->pEList->nExpr==pPrior->pEList->nExpr );
  123658. #ifndef SQLITE_OMIT_CTE
  123659. if( p->selFlags & SF_Recursive ){
  123660. generateWithRecursiveQuery(pParse, p, &dest);
  123661. }else
  123662. #endif
  123663. /* Compound SELECTs that have an ORDER BY clause are handled separately.
  123664. */
  123665. if( p->pOrderBy ){
  123666. return multiSelectOrderBy(pParse, p, pDest);
  123667. }else{
  123668. #ifndef SQLITE_OMIT_EXPLAIN
  123669. if( pPrior->pPrior==0 ){
  123670. ExplainQueryPlan((pParse, 1, "COMPOUND QUERY"));
  123671. ExplainQueryPlan((pParse, 1, "LEFT-MOST SUBQUERY"));
  123672. }
  123673. #endif
  123674. /* Generate code for the left and right SELECT statements.
  123675. */
  123676. switch( p->op ){
  123677. case TK_ALL: {
  123678. int addr = 0;
  123679. int nLimit;
  123680. assert( !pPrior->pLimit );
  123681. pPrior->iLimit = p->iLimit;
  123682. pPrior->iOffset = p->iOffset;
  123683. pPrior->pLimit = p->pLimit;
  123684. rc = sqlite3Select(pParse, pPrior, &dest);
  123685. p->pLimit = 0;
  123686. if( rc ){
  123687. goto multi_select_end;
  123688. }
  123689. p->pPrior = 0;
  123690. p->iLimit = pPrior->iLimit;
  123691. p->iOffset = pPrior->iOffset;
  123692. if( p->iLimit ){
  123693. addr = sqlite3VdbeAddOp1(v, OP_IfNot, p->iLimit); VdbeCoverage(v);
  123694. VdbeComment((v, "Jump ahead if LIMIT reached"));
  123695. if( p->iOffset ){
  123696. sqlite3VdbeAddOp3(v, OP_OffsetLimit,
  123697. p->iLimit, p->iOffset+1, p->iOffset);
  123698. }
  123699. }
  123700. ExplainQueryPlan((pParse, 1, "UNION ALL"));
  123701. rc = sqlite3Select(pParse, p, &dest);
  123702. testcase( rc!=SQLITE_OK );
  123703. pDelete = p->pPrior;
  123704. p->pPrior = pPrior;
  123705. p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
  123706. if( pPrior->pLimit
  123707. && sqlite3ExprIsInteger(pPrior->pLimit->pLeft, &nLimit)
  123708. && nLimit>0 && p->nSelectRow > sqlite3LogEst((u64)nLimit)
  123709. ){
  123710. p->nSelectRow = sqlite3LogEst((u64)nLimit);
  123711. }
  123712. if( addr ){
  123713. sqlite3VdbeJumpHere(v, addr);
  123714. }
  123715. break;
  123716. }
  123717. case TK_EXCEPT:
  123718. case TK_UNION: {
  123719. int unionTab; /* Cursor number of the temp table holding result */
  123720. u8 op = 0; /* One of the SRT_ operations to apply to self */
  123721. int priorOp; /* The SRT_ operation to apply to prior selects */
  123722. Expr *pLimit; /* Saved values of p->nLimit */
  123723. int addr;
  123724. SelectDest uniondest;
  123725. testcase( p->op==TK_EXCEPT );
  123726. testcase( p->op==TK_UNION );
  123727. priorOp = SRT_Union;
  123728. if( dest.eDest==priorOp ){
  123729. /* We can reuse a temporary table generated by a SELECT to our
  123730. ** right.
  123731. */
  123732. assert( p->pLimit==0 ); /* Not allowed on leftward elements */
  123733. unionTab = dest.iSDParm;
  123734. }else{
  123735. /* We will need to create our own temporary table to hold the
  123736. ** intermediate results.
  123737. */
  123738. unionTab = pParse->nTab++;
  123739. assert( p->pOrderBy==0 );
  123740. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
  123741. assert( p->addrOpenEphm[0] == -1 );
  123742. p->addrOpenEphm[0] = addr;
  123743. findRightmost(p)->selFlags |= SF_UsesEphemeral;
  123744. assert( p->pEList );
  123745. }
  123746. /* Code the SELECT statements to our left
  123747. */
  123748. assert( !pPrior->pOrderBy );
  123749. sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
  123750. rc = sqlite3Select(pParse, pPrior, &uniondest);
  123751. if( rc ){
  123752. goto multi_select_end;
  123753. }
  123754. /* Code the current SELECT statement
  123755. */
  123756. if( p->op==TK_EXCEPT ){
  123757. op = SRT_Except;
  123758. }else{
  123759. assert( p->op==TK_UNION );
  123760. op = SRT_Union;
  123761. }
  123762. p->pPrior = 0;
  123763. pLimit = p->pLimit;
  123764. p->pLimit = 0;
  123765. uniondest.eDest = op;
  123766. ExplainQueryPlan((pParse, 1, "%s USING TEMP B-TREE",
  123767. selectOpName(p->op)));
  123768. rc = sqlite3Select(pParse, p, &uniondest);
  123769. testcase( rc!=SQLITE_OK );
  123770. /* Query flattening in sqlite3Select() might refill p->pOrderBy.
  123771. ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
  123772. sqlite3ExprListDelete(db, p->pOrderBy);
  123773. pDelete = p->pPrior;
  123774. p->pPrior = pPrior;
  123775. p->pOrderBy = 0;
  123776. if( p->op==TK_UNION ){
  123777. p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
  123778. }
  123779. sqlite3ExprDelete(db, p->pLimit);
  123780. p->pLimit = pLimit;
  123781. p->iLimit = 0;
  123782. p->iOffset = 0;
  123783. /* Convert the data in the temporary table into whatever form
  123784. ** it is that we currently need.
  123785. */
  123786. assert( unionTab==dest.iSDParm || dest.eDest!=priorOp );
  123787. assert( p->pEList || db->mallocFailed );
  123788. if( dest.eDest!=priorOp && db->mallocFailed==0 ){
  123789. int iCont, iBreak, iStart;
  123790. iBreak = sqlite3VdbeMakeLabel(pParse);
  123791. iCont = sqlite3VdbeMakeLabel(pParse);
  123792. computeLimitRegisters(pParse, p, iBreak);
  123793. sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak); VdbeCoverage(v);
  123794. iStart = sqlite3VdbeCurrentAddr(v);
  123795. selectInnerLoop(pParse, p, unionTab,
  123796. 0, 0, &dest, iCont, iBreak);
  123797. sqlite3VdbeResolveLabel(v, iCont);
  123798. sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart); VdbeCoverage(v);
  123799. sqlite3VdbeResolveLabel(v, iBreak);
  123800. sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
  123801. }
  123802. break;
  123803. }
  123804. default: assert( p->op==TK_INTERSECT ); {
  123805. int tab1, tab2;
  123806. int iCont, iBreak, iStart;
  123807. Expr *pLimit;
  123808. int addr;
  123809. SelectDest intersectdest;
  123810. int r1;
  123811. /* INTERSECT is different from the others since it requires
  123812. ** two temporary tables. Hence it has its own case. Begin
  123813. ** by allocating the tables we will need.
  123814. */
  123815. tab1 = pParse->nTab++;
  123816. tab2 = pParse->nTab++;
  123817. assert( p->pOrderBy==0 );
  123818. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
  123819. assert( p->addrOpenEphm[0] == -1 );
  123820. p->addrOpenEphm[0] = addr;
  123821. findRightmost(p)->selFlags |= SF_UsesEphemeral;
  123822. assert( p->pEList );
  123823. /* Code the SELECTs to our left into temporary table "tab1".
  123824. */
  123825. sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
  123826. rc = sqlite3Select(pParse, pPrior, &intersectdest);
  123827. if( rc ){
  123828. goto multi_select_end;
  123829. }
  123830. /* Code the current SELECT into temporary table "tab2"
  123831. */
  123832. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
  123833. assert( p->addrOpenEphm[1] == -1 );
  123834. p->addrOpenEphm[1] = addr;
  123835. p->pPrior = 0;
  123836. pLimit = p->pLimit;
  123837. p->pLimit = 0;
  123838. intersectdest.iSDParm = tab2;
  123839. ExplainQueryPlan((pParse, 1, "%s USING TEMP B-TREE",
  123840. selectOpName(p->op)));
  123841. rc = sqlite3Select(pParse, p, &intersectdest);
  123842. testcase( rc!=SQLITE_OK );
  123843. pDelete = p->pPrior;
  123844. p->pPrior = pPrior;
  123845. if( p->nSelectRow>pPrior->nSelectRow ){
  123846. p->nSelectRow = pPrior->nSelectRow;
  123847. }
  123848. sqlite3ExprDelete(db, p->pLimit);
  123849. p->pLimit = pLimit;
  123850. /* Generate code to take the intersection of the two temporary
  123851. ** tables.
  123852. */
  123853. if( rc ) break;
  123854. assert( p->pEList );
  123855. iBreak = sqlite3VdbeMakeLabel(pParse);
  123856. iCont = sqlite3VdbeMakeLabel(pParse);
  123857. computeLimitRegisters(pParse, p, iBreak);
  123858. sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak); VdbeCoverage(v);
  123859. r1 = sqlite3GetTempReg(pParse);
  123860. iStart = sqlite3VdbeAddOp2(v, OP_RowData, tab1, r1);
  123861. sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0);
  123862. VdbeCoverage(v);
  123863. sqlite3ReleaseTempReg(pParse, r1);
  123864. selectInnerLoop(pParse, p, tab1,
  123865. 0, 0, &dest, iCont, iBreak);
  123866. sqlite3VdbeResolveLabel(v, iCont);
  123867. sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart); VdbeCoverage(v);
  123868. sqlite3VdbeResolveLabel(v, iBreak);
  123869. sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
  123870. sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
  123871. break;
  123872. }
  123873. }
  123874. #ifndef SQLITE_OMIT_EXPLAIN
  123875. if( p->pNext==0 ){
  123876. ExplainQueryPlanPop(pParse);
  123877. }
  123878. #endif
  123879. }
  123880. if( pParse->nErr ) goto multi_select_end;
  123881. /* Compute collating sequences used by
  123882. ** temporary tables needed to implement the compound select.
  123883. ** Attach the KeyInfo structure to all temporary tables.
  123884. **
  123885. ** This section is run by the right-most SELECT statement only.
  123886. ** SELECT statements to the left always skip this part. The right-most
  123887. ** SELECT might also skip this part if it has no ORDER BY clause and
  123888. ** no temp tables are required.
  123889. */
  123890. if( p->selFlags & SF_UsesEphemeral ){
  123891. int i; /* Loop counter */
  123892. KeyInfo *pKeyInfo; /* Collating sequence for the result set */
  123893. Select *pLoop; /* For looping through SELECT statements */
  123894. CollSeq **apColl; /* For looping through pKeyInfo->aColl[] */
  123895. int nCol; /* Number of columns in result set */
  123896. assert( p->pNext==0 );
  123897. nCol = p->pEList->nExpr;
  123898. pKeyInfo = sqlite3KeyInfoAlloc(db, nCol, 1);
  123899. if( !pKeyInfo ){
  123900. rc = SQLITE_NOMEM_BKPT;
  123901. goto multi_select_end;
  123902. }
  123903. for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
  123904. *apColl = multiSelectCollSeq(pParse, p, i);
  123905. if( 0==*apColl ){
  123906. *apColl = db->pDfltColl;
  123907. }
  123908. }
  123909. for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
  123910. for(i=0; i<2; i++){
  123911. int addr = pLoop->addrOpenEphm[i];
  123912. if( addr<0 ){
  123913. /* If [0] is unused then [1] is also unused. So we can
  123914. ** always safely abort as soon as the first unused slot is found */
  123915. assert( pLoop->addrOpenEphm[1]<0 );
  123916. break;
  123917. }
  123918. sqlite3VdbeChangeP2(v, addr, nCol);
  123919. sqlite3VdbeChangeP4(v, addr, (char*)sqlite3KeyInfoRef(pKeyInfo),
  123920. P4_KEYINFO);
  123921. pLoop->addrOpenEphm[i] = -1;
  123922. }
  123923. }
  123924. sqlite3KeyInfoUnref(pKeyInfo);
  123925. }
  123926. multi_select_end:
  123927. pDest->iSdst = dest.iSdst;
  123928. pDest->nSdst = dest.nSdst;
  123929. sqlite3SelectDelete(db, pDelete);
  123930. return rc;
  123931. }
  123932. #endif /* SQLITE_OMIT_COMPOUND_SELECT */
  123933. /*
  123934. ** Error message for when two or more terms of a compound select have different
  123935. ** size result sets.
  123936. */
  123937. SQLITE_PRIVATE void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p){
  123938. if( p->selFlags & SF_Values ){
  123939. sqlite3ErrorMsg(pParse, "all VALUES must have the same number of terms");
  123940. }else{
  123941. sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
  123942. " do not have the same number of result columns", selectOpName(p->op));
  123943. }
  123944. }
  123945. /*
  123946. ** Code an output subroutine for a coroutine implementation of a
  123947. ** SELECT statment.
  123948. **
  123949. ** The data to be output is contained in pIn->iSdst. There are
  123950. ** pIn->nSdst columns to be output. pDest is where the output should
  123951. ** be sent.
  123952. **
  123953. ** regReturn is the number of the register holding the subroutine
  123954. ** return address.
  123955. **
  123956. ** If regPrev>0 then it is the first register in a vector that
  123957. ** records the previous output. mem[regPrev] is a flag that is false
  123958. ** if there has been no previous output. If regPrev>0 then code is
  123959. ** generated to suppress duplicates. pKeyInfo is used for comparing
  123960. ** keys.
  123961. **
  123962. ** If the LIMIT found in p->iLimit is reached, jump immediately to
  123963. ** iBreak.
  123964. */
  123965. static int generateOutputSubroutine(
  123966. Parse *pParse, /* Parsing context */
  123967. Select *p, /* The SELECT statement */
  123968. SelectDest *pIn, /* Coroutine supplying data */
  123969. SelectDest *pDest, /* Where to send the data */
  123970. int regReturn, /* The return address register */
  123971. int regPrev, /* Previous result register. No uniqueness if 0 */
  123972. KeyInfo *pKeyInfo, /* For comparing with previous entry */
  123973. int iBreak /* Jump here if we hit the LIMIT */
  123974. ){
  123975. Vdbe *v = pParse->pVdbe;
  123976. int iContinue;
  123977. int addr;
  123978. addr = sqlite3VdbeCurrentAddr(v);
  123979. iContinue = sqlite3VdbeMakeLabel(pParse);
  123980. /* Suppress duplicates for UNION, EXCEPT, and INTERSECT
  123981. */
  123982. if( regPrev ){
  123983. int addr1, addr2;
  123984. addr1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev); VdbeCoverage(v);
  123985. addr2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iSdst, regPrev+1, pIn->nSdst,
  123986. (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
  123987. sqlite3VdbeAddOp3(v, OP_Jump, addr2+2, iContinue, addr2+2); VdbeCoverage(v);
  123988. sqlite3VdbeJumpHere(v, addr1);
  123989. sqlite3VdbeAddOp3(v, OP_Copy, pIn->iSdst, regPrev+1, pIn->nSdst-1);
  123990. sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
  123991. }
  123992. if( pParse->db->mallocFailed ) return 0;
  123993. /* Suppress the first OFFSET entries if there is an OFFSET clause
  123994. */
  123995. codeOffset(v, p->iOffset, iContinue);
  123996. assert( pDest->eDest!=SRT_Exists );
  123997. assert( pDest->eDest!=SRT_Table );
  123998. switch( pDest->eDest ){
  123999. /* Store the result as data using a unique key.
  124000. */
  124001. case SRT_EphemTab: {
  124002. int r1 = sqlite3GetTempReg(pParse);
  124003. int r2 = sqlite3GetTempReg(pParse);
  124004. sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1);
  124005. sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iSDParm, r2);
  124006. sqlite3VdbeAddOp3(v, OP_Insert, pDest->iSDParm, r1, r2);
  124007. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  124008. sqlite3ReleaseTempReg(pParse, r2);
  124009. sqlite3ReleaseTempReg(pParse, r1);
  124010. break;
  124011. }
  124012. #ifndef SQLITE_OMIT_SUBQUERY
  124013. /* If we are creating a set for an "expr IN (SELECT ...)".
  124014. */
  124015. case SRT_Set: {
  124016. int r1;
  124017. testcase( pIn->nSdst>1 );
  124018. r1 = sqlite3GetTempReg(pParse);
  124019. sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst,
  124020. r1, pDest->zAffSdst, pIn->nSdst);
  124021. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, pDest->iSDParm, r1,
  124022. pIn->iSdst, pIn->nSdst);
  124023. sqlite3ReleaseTempReg(pParse, r1);
  124024. break;
  124025. }
  124026. /* If this is a scalar select that is part of an expression, then
  124027. ** store the results in the appropriate memory cell and break out
  124028. ** of the scan loop. Note that the select might return multiple columns
  124029. ** if it is the RHS of a row-value IN operator.
  124030. */
  124031. case SRT_Mem: {
  124032. if( pParse->nErr==0 ){
  124033. testcase( pIn->nSdst>1 );
  124034. sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSDParm, pIn->nSdst);
  124035. }
  124036. /* The LIMIT clause will jump out of the loop for us */
  124037. break;
  124038. }
  124039. #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
  124040. /* The results are stored in a sequence of registers
  124041. ** starting at pDest->iSdst. Then the co-routine yields.
  124042. */
  124043. case SRT_Coroutine: {
  124044. if( pDest->iSdst==0 ){
  124045. pDest->iSdst = sqlite3GetTempRange(pParse, pIn->nSdst);
  124046. pDest->nSdst = pIn->nSdst;
  124047. }
  124048. sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSdst, pIn->nSdst);
  124049. sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
  124050. break;
  124051. }
  124052. /* If none of the above, then the result destination must be
  124053. ** SRT_Output. This routine is never called with any other
  124054. ** destination other than the ones handled above or SRT_Output.
  124055. **
  124056. ** For SRT_Output, results are stored in a sequence of registers.
  124057. ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
  124058. ** return the next row of result.
  124059. */
  124060. default: {
  124061. assert( pDest->eDest==SRT_Output );
  124062. sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iSdst, pIn->nSdst);
  124063. break;
  124064. }
  124065. }
  124066. /* Jump to the end of the loop if the LIMIT is reached.
  124067. */
  124068. if( p->iLimit ){
  124069. sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v);
  124070. }
  124071. /* Generate the subroutine return
  124072. */
  124073. sqlite3VdbeResolveLabel(v, iContinue);
  124074. sqlite3VdbeAddOp1(v, OP_Return, regReturn);
  124075. return addr;
  124076. }
  124077. /*
  124078. ** Alternative compound select code generator for cases when there
  124079. ** is an ORDER BY clause.
  124080. **
  124081. ** We assume a query of the following form:
  124082. **
  124083. ** <selectA> <operator> <selectB> ORDER BY <orderbylist>
  124084. **
  124085. ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT. The idea
  124086. ** is to code both <selectA> and <selectB> with the ORDER BY clause as
  124087. ** co-routines. Then run the co-routines in parallel and merge the results
  124088. ** into the output. In addition to the two coroutines (called selectA and
  124089. ** selectB) there are 7 subroutines:
  124090. **
  124091. ** outA: Move the output of the selectA coroutine into the output
  124092. ** of the compound query.
  124093. **
  124094. ** outB: Move the output of the selectB coroutine into the output
  124095. ** of the compound query. (Only generated for UNION and
  124096. ** UNION ALL. EXCEPT and INSERTSECT never output a row that
  124097. ** appears only in B.)
  124098. **
  124099. ** AltB: Called when there is data from both coroutines and A<B.
  124100. **
  124101. ** AeqB: Called when there is data from both coroutines and A==B.
  124102. **
  124103. ** AgtB: Called when there is data from both coroutines and A>B.
  124104. **
  124105. ** EofA: Called when data is exhausted from selectA.
  124106. **
  124107. ** EofB: Called when data is exhausted from selectB.
  124108. **
  124109. ** The implementation of the latter five subroutines depend on which
  124110. ** <operator> is used:
  124111. **
  124112. **
  124113. ** UNION ALL UNION EXCEPT INTERSECT
  124114. ** ------------- ----------------- -------------- -----------------
  124115. ** AltB: outA, nextA outA, nextA outA, nextA nextA
  124116. **
  124117. ** AeqB: outA, nextA nextA nextA outA, nextA
  124118. **
  124119. ** AgtB: outB, nextB outB, nextB nextB nextB
  124120. **
  124121. ** EofA: outB, nextB outB, nextB halt halt
  124122. **
  124123. ** EofB: outA, nextA outA, nextA outA, nextA halt
  124124. **
  124125. ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
  124126. ** causes an immediate jump to EofA and an EOF on B following nextB causes
  124127. ** an immediate jump to EofB. Within EofA and EofB, and EOF on entry or
  124128. ** following nextX causes a jump to the end of the select processing.
  124129. **
  124130. ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
  124131. ** within the output subroutine. The regPrev register set holds the previously
  124132. ** output value. A comparison is made against this value and the output
  124133. ** is skipped if the next results would be the same as the previous.
  124134. **
  124135. ** The implementation plan is to implement the two coroutines and seven
  124136. ** subroutines first, then put the control logic at the bottom. Like this:
  124137. **
  124138. ** goto Init
  124139. ** coA: coroutine for left query (A)
  124140. ** coB: coroutine for right query (B)
  124141. ** outA: output one row of A
  124142. ** outB: output one row of B (UNION and UNION ALL only)
  124143. ** EofA: ...
  124144. ** EofB: ...
  124145. ** AltB: ...
  124146. ** AeqB: ...
  124147. ** AgtB: ...
  124148. ** Init: initialize coroutine registers
  124149. ** yield coA
  124150. ** if eof(A) goto EofA
  124151. ** yield coB
  124152. ** if eof(B) goto EofB
  124153. ** Cmpr: Compare A, B
  124154. ** Jump AltB, AeqB, AgtB
  124155. ** End: ...
  124156. **
  124157. ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
  124158. ** actually called using Gosub and they do not Return. EofA and EofB loop
  124159. ** until all data is exhausted then jump to the "end" labe. AltB, AeqB,
  124160. ** and AgtB jump to either L2 or to one of EofA or EofB.
  124161. */
  124162. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  124163. static int multiSelectOrderBy(
  124164. Parse *pParse, /* Parsing context */
  124165. Select *p, /* The right-most of SELECTs to be coded */
  124166. SelectDest *pDest /* What to do with query results */
  124167. ){
  124168. int i, j; /* Loop counters */
  124169. Select *pPrior; /* Another SELECT immediately to our left */
  124170. Vdbe *v; /* Generate code to this VDBE */
  124171. SelectDest destA; /* Destination for coroutine A */
  124172. SelectDest destB; /* Destination for coroutine B */
  124173. int regAddrA; /* Address register for select-A coroutine */
  124174. int regAddrB; /* Address register for select-B coroutine */
  124175. int addrSelectA; /* Address of the select-A coroutine */
  124176. int addrSelectB; /* Address of the select-B coroutine */
  124177. int regOutA; /* Address register for the output-A subroutine */
  124178. int regOutB; /* Address register for the output-B subroutine */
  124179. int addrOutA; /* Address of the output-A subroutine */
  124180. int addrOutB = 0; /* Address of the output-B subroutine */
  124181. int addrEofA; /* Address of the select-A-exhausted subroutine */
  124182. int addrEofA_noB; /* Alternate addrEofA if B is uninitialized */
  124183. int addrEofB; /* Address of the select-B-exhausted subroutine */
  124184. int addrAltB; /* Address of the A<B subroutine */
  124185. int addrAeqB; /* Address of the A==B subroutine */
  124186. int addrAgtB; /* Address of the A>B subroutine */
  124187. int regLimitA; /* Limit register for select-A */
  124188. int regLimitB; /* Limit register for select-A */
  124189. int regPrev; /* A range of registers to hold previous output */
  124190. int savedLimit; /* Saved value of p->iLimit */
  124191. int savedOffset; /* Saved value of p->iOffset */
  124192. int labelCmpr; /* Label for the start of the merge algorithm */
  124193. int labelEnd; /* Label for the end of the overall SELECT stmt */
  124194. int addr1; /* Jump instructions that get retargetted */
  124195. int op; /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
  124196. KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
  124197. KeyInfo *pKeyMerge; /* Comparison information for merging rows */
  124198. sqlite3 *db; /* Database connection */
  124199. ExprList *pOrderBy; /* The ORDER BY clause */
  124200. int nOrderBy; /* Number of terms in the ORDER BY clause */
  124201. int *aPermute; /* Mapping from ORDER BY terms to result set columns */
  124202. assert( p->pOrderBy!=0 );
  124203. assert( pKeyDup==0 ); /* "Managed" code needs this. Ticket #3382. */
  124204. db = pParse->db;
  124205. v = pParse->pVdbe;
  124206. assert( v!=0 ); /* Already thrown the error if VDBE alloc failed */
  124207. labelEnd = sqlite3VdbeMakeLabel(pParse);
  124208. labelCmpr = sqlite3VdbeMakeLabel(pParse);
  124209. /* Patch up the ORDER BY clause
  124210. */
  124211. op = p->op;
  124212. pPrior = p->pPrior;
  124213. assert( pPrior->pOrderBy==0 );
  124214. pOrderBy = p->pOrderBy;
  124215. assert( pOrderBy );
  124216. nOrderBy = pOrderBy->nExpr;
  124217. /* For operators other than UNION ALL we have to make sure that
  124218. ** the ORDER BY clause covers every term of the result set. Add
  124219. ** terms to the ORDER BY clause as necessary.
  124220. */
  124221. if( op!=TK_ALL ){
  124222. for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
  124223. struct ExprList_item *pItem;
  124224. for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
  124225. assert( pItem->u.x.iOrderByCol>0 );
  124226. if( pItem->u.x.iOrderByCol==i ) break;
  124227. }
  124228. if( j==nOrderBy ){
  124229. Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
  124230. if( pNew==0 ) return SQLITE_NOMEM_BKPT;
  124231. pNew->flags |= EP_IntValue;
  124232. pNew->u.iValue = i;
  124233. p->pOrderBy = pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
  124234. if( pOrderBy ) pOrderBy->a[nOrderBy++].u.x.iOrderByCol = (u16)i;
  124235. }
  124236. }
  124237. }
  124238. /* Compute the comparison permutation and keyinfo that is used with
  124239. ** the permutation used to determine if the next
  124240. ** row of results comes from selectA or selectB. Also add explicit
  124241. ** collations to the ORDER BY clause terms so that when the subqueries
  124242. ** to the right and the left are evaluated, they use the correct
  124243. ** collation.
  124244. */
  124245. aPermute = sqlite3DbMallocRawNN(db, sizeof(int)*(nOrderBy + 1));
  124246. if( aPermute ){
  124247. struct ExprList_item *pItem;
  124248. aPermute[0] = nOrderBy;
  124249. for(i=1, pItem=pOrderBy->a; i<=nOrderBy; i++, pItem++){
  124250. assert( pItem->u.x.iOrderByCol>0 );
  124251. assert( pItem->u.x.iOrderByCol<=p->pEList->nExpr );
  124252. aPermute[i] = pItem->u.x.iOrderByCol - 1;
  124253. }
  124254. pKeyMerge = multiSelectOrderByKeyInfo(pParse, p, 1);
  124255. }else{
  124256. pKeyMerge = 0;
  124257. }
  124258. /* Reattach the ORDER BY clause to the query.
  124259. */
  124260. p->pOrderBy = pOrderBy;
  124261. pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
  124262. /* Allocate a range of temporary registers and the KeyInfo needed
  124263. ** for the logic that removes duplicate result rows when the
  124264. ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
  124265. */
  124266. if( op==TK_ALL ){
  124267. regPrev = 0;
  124268. }else{
  124269. int nExpr = p->pEList->nExpr;
  124270. assert( nOrderBy>=nExpr || db->mallocFailed );
  124271. regPrev = pParse->nMem+1;
  124272. pParse->nMem += nExpr+1;
  124273. sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
  124274. pKeyDup = sqlite3KeyInfoAlloc(db, nExpr, 1);
  124275. if( pKeyDup ){
  124276. assert( sqlite3KeyInfoIsWriteable(pKeyDup) );
  124277. for(i=0; i<nExpr; i++){
  124278. pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
  124279. pKeyDup->aSortFlags[i] = 0;
  124280. }
  124281. }
  124282. }
  124283. /* Separate the left and the right query from one another
  124284. */
  124285. p->pPrior = 0;
  124286. pPrior->pNext = 0;
  124287. sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
  124288. if( pPrior->pPrior==0 ){
  124289. sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
  124290. }
  124291. /* Compute the limit registers */
  124292. computeLimitRegisters(pParse, p, labelEnd);
  124293. if( p->iLimit && op==TK_ALL ){
  124294. regLimitA = ++pParse->nMem;
  124295. regLimitB = ++pParse->nMem;
  124296. sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
  124297. regLimitA);
  124298. sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
  124299. }else{
  124300. regLimitA = regLimitB = 0;
  124301. }
  124302. sqlite3ExprDelete(db, p->pLimit);
  124303. p->pLimit = 0;
  124304. regAddrA = ++pParse->nMem;
  124305. regAddrB = ++pParse->nMem;
  124306. regOutA = ++pParse->nMem;
  124307. regOutB = ++pParse->nMem;
  124308. sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
  124309. sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
  124310. ExplainQueryPlan((pParse, 1, "MERGE (%s)", selectOpName(p->op)));
  124311. /* Generate a coroutine to evaluate the SELECT statement to the
  124312. ** left of the compound operator - the "A" select.
  124313. */
  124314. addrSelectA = sqlite3VdbeCurrentAddr(v) + 1;
  124315. addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrA, 0, addrSelectA);
  124316. VdbeComment((v, "left SELECT"));
  124317. pPrior->iLimit = regLimitA;
  124318. ExplainQueryPlan((pParse, 1, "LEFT"));
  124319. sqlite3Select(pParse, pPrior, &destA);
  124320. sqlite3VdbeEndCoroutine(v, regAddrA);
  124321. sqlite3VdbeJumpHere(v, addr1);
  124322. /* Generate a coroutine to evaluate the SELECT statement on
  124323. ** the right - the "B" select
  124324. */
  124325. addrSelectB = sqlite3VdbeCurrentAddr(v) + 1;
  124326. addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrB, 0, addrSelectB);
  124327. VdbeComment((v, "right SELECT"));
  124328. savedLimit = p->iLimit;
  124329. savedOffset = p->iOffset;
  124330. p->iLimit = regLimitB;
  124331. p->iOffset = 0;
  124332. ExplainQueryPlan((pParse, 1, "RIGHT"));
  124333. sqlite3Select(pParse, p, &destB);
  124334. p->iLimit = savedLimit;
  124335. p->iOffset = savedOffset;
  124336. sqlite3VdbeEndCoroutine(v, regAddrB);
  124337. /* Generate a subroutine that outputs the current row of the A
  124338. ** select as the next output row of the compound select.
  124339. */
  124340. VdbeNoopComment((v, "Output routine for A"));
  124341. addrOutA = generateOutputSubroutine(pParse,
  124342. p, &destA, pDest, regOutA,
  124343. regPrev, pKeyDup, labelEnd);
  124344. /* Generate a subroutine that outputs the current row of the B
  124345. ** select as the next output row of the compound select.
  124346. */
  124347. if( op==TK_ALL || op==TK_UNION ){
  124348. VdbeNoopComment((v, "Output routine for B"));
  124349. addrOutB = generateOutputSubroutine(pParse,
  124350. p, &destB, pDest, regOutB,
  124351. regPrev, pKeyDup, labelEnd);
  124352. }
  124353. sqlite3KeyInfoUnref(pKeyDup);
  124354. /* Generate a subroutine to run when the results from select A
  124355. ** are exhausted and only data in select B remains.
  124356. */
  124357. if( op==TK_EXCEPT || op==TK_INTERSECT ){
  124358. addrEofA_noB = addrEofA = labelEnd;
  124359. }else{
  124360. VdbeNoopComment((v, "eof-A subroutine"));
  124361. addrEofA = sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
  124362. addrEofA_noB = sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, labelEnd);
  124363. VdbeCoverage(v);
  124364. sqlite3VdbeGoto(v, addrEofA);
  124365. p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
  124366. }
  124367. /* Generate a subroutine to run when the results from select B
  124368. ** are exhausted and only data in select A remains.
  124369. */
  124370. if( op==TK_INTERSECT ){
  124371. addrEofB = addrEofA;
  124372. if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
  124373. }else{
  124374. VdbeNoopComment((v, "eof-B subroutine"));
  124375. addrEofB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
  124376. sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, labelEnd); VdbeCoverage(v);
  124377. sqlite3VdbeGoto(v, addrEofB);
  124378. }
  124379. /* Generate code to handle the case of A<B
  124380. */
  124381. VdbeNoopComment((v, "A-lt-B subroutine"));
  124382. addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
  124383. sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
  124384. sqlite3VdbeGoto(v, labelCmpr);
  124385. /* Generate code to handle the case of A==B
  124386. */
  124387. if( op==TK_ALL ){
  124388. addrAeqB = addrAltB;
  124389. }else if( op==TK_INTERSECT ){
  124390. addrAeqB = addrAltB;
  124391. addrAltB++;
  124392. }else{
  124393. VdbeNoopComment((v, "A-eq-B subroutine"));
  124394. addrAeqB =
  124395. sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
  124396. sqlite3VdbeGoto(v, labelCmpr);
  124397. }
  124398. /* Generate code to handle the case of A>B
  124399. */
  124400. VdbeNoopComment((v, "A-gt-B subroutine"));
  124401. addrAgtB = sqlite3VdbeCurrentAddr(v);
  124402. if( op==TK_ALL || op==TK_UNION ){
  124403. sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
  124404. }
  124405. sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
  124406. sqlite3VdbeGoto(v, labelCmpr);
  124407. /* This code runs once to initialize everything.
  124408. */
  124409. sqlite3VdbeJumpHere(v, addr1);
  124410. sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA_noB); VdbeCoverage(v);
  124411. sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
  124412. /* Implement the main merge loop
  124413. */
  124414. sqlite3VdbeResolveLabel(v, labelCmpr);
  124415. sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
  124416. sqlite3VdbeAddOp4(v, OP_Compare, destA.iSdst, destB.iSdst, nOrderBy,
  124417. (char*)pKeyMerge, P4_KEYINFO);
  124418. sqlite3VdbeChangeP5(v, OPFLAG_PERMUTE);
  124419. sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB); VdbeCoverage(v);
  124420. /* Jump to the this point in order to terminate the query.
  124421. */
  124422. sqlite3VdbeResolveLabel(v, labelEnd);
  124423. /* Reassembly the compound query so that it will be freed correctly
  124424. ** by the calling function */
  124425. if( p->pPrior ){
  124426. sqlite3SelectDelete(db, p->pPrior);
  124427. }
  124428. p->pPrior = pPrior;
  124429. pPrior->pNext = p;
  124430. /*** TBD: Insert subroutine calls to close cursors on incomplete
  124431. **** subqueries ****/
  124432. ExplainQueryPlanPop(pParse);
  124433. return pParse->nErr!=0;
  124434. }
  124435. #endif
  124436. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  124437. /* An instance of the SubstContext object describes an substitution edit
  124438. ** to be performed on a parse tree.
  124439. **
  124440. ** All references to columns in table iTable are to be replaced by corresponding
  124441. ** expressions in pEList.
  124442. */
  124443. typedef struct SubstContext {
  124444. Parse *pParse; /* The parsing context */
  124445. int iTable; /* Replace references to this table */
  124446. int iNewTable; /* New table number */
  124447. int isLeftJoin; /* Add TK_IF_NULL_ROW opcodes on each replacement */
  124448. ExprList *pEList; /* Replacement expressions */
  124449. } SubstContext;
  124450. /* Forward Declarations */
  124451. static void substExprList(SubstContext*, ExprList*);
  124452. static void substSelect(SubstContext*, Select*, int);
  124453. /*
  124454. ** Scan through the expression pExpr. Replace every reference to
  124455. ** a column in table number iTable with a copy of the iColumn-th
  124456. ** entry in pEList. (But leave references to the ROWID column
  124457. ** unchanged.)
  124458. **
  124459. ** This routine is part of the flattening procedure. A subquery
  124460. ** whose result set is defined by pEList appears as entry in the
  124461. ** FROM clause of a SELECT such that the VDBE cursor assigned to that
  124462. ** FORM clause entry is iTable. This routine makes the necessary
  124463. ** changes to pExpr so that it refers directly to the source table
  124464. ** of the subquery rather the result set of the subquery.
  124465. */
  124466. static Expr *substExpr(
  124467. SubstContext *pSubst, /* Description of the substitution */
  124468. Expr *pExpr /* Expr in which substitution occurs */
  124469. ){
  124470. if( pExpr==0 ) return 0;
  124471. if( ExprHasProperty(pExpr, EP_FromJoin)
  124472. && pExpr->iRightJoinTable==pSubst->iTable
  124473. ){
  124474. pExpr->iRightJoinTable = pSubst->iNewTable;
  124475. }
  124476. if( pExpr->op==TK_COLUMN
  124477. && pExpr->iTable==pSubst->iTable
  124478. && !ExprHasProperty(pExpr, EP_FixedCol)
  124479. ){
  124480. if( pExpr->iColumn<0 ){
  124481. pExpr->op = TK_NULL;
  124482. }else{
  124483. Expr *pNew;
  124484. Expr *pCopy = pSubst->pEList->a[pExpr->iColumn].pExpr;
  124485. Expr ifNullRow;
  124486. assert( pSubst->pEList!=0 && pExpr->iColumn<pSubst->pEList->nExpr );
  124487. assert( pExpr->pRight==0 );
  124488. if( sqlite3ExprIsVector(pCopy) ){
  124489. sqlite3VectorErrorMsg(pSubst->pParse, pCopy);
  124490. }else{
  124491. sqlite3 *db = pSubst->pParse->db;
  124492. if( pSubst->isLeftJoin && pCopy->op!=TK_COLUMN ){
  124493. memset(&ifNullRow, 0, sizeof(ifNullRow));
  124494. ifNullRow.op = TK_IF_NULL_ROW;
  124495. ifNullRow.pLeft = pCopy;
  124496. ifNullRow.iTable = pSubst->iNewTable;
  124497. ifNullRow.flags = EP_Skip;
  124498. pCopy = &ifNullRow;
  124499. }
  124500. testcase( ExprHasProperty(pCopy, EP_Subquery) );
  124501. pNew = sqlite3ExprDup(db, pCopy, 0);
  124502. if( pNew && pSubst->isLeftJoin ){
  124503. ExprSetProperty(pNew, EP_CanBeNull);
  124504. }
  124505. if( pNew && ExprHasProperty(pExpr,EP_FromJoin) ){
  124506. pNew->iRightJoinTable = pExpr->iRightJoinTable;
  124507. ExprSetProperty(pNew, EP_FromJoin);
  124508. }
  124509. sqlite3ExprDelete(db, pExpr);
  124510. pExpr = pNew;
  124511. /* Ensure that the expression now has an implicit collation sequence,
  124512. ** just as it did when it was a column of a view or sub-query. */
  124513. if( pExpr ){
  124514. if( pExpr->op!=TK_COLUMN && pExpr->op!=TK_COLLATE ){
  124515. CollSeq *pColl = sqlite3ExprCollSeq(pSubst->pParse, pExpr);
  124516. pExpr = sqlite3ExprAddCollateString(pSubst->pParse, pExpr,
  124517. (pColl ? pColl->zName : "BINARY")
  124518. );
  124519. }
  124520. ExprClearProperty(pExpr, EP_Collate);
  124521. }
  124522. }
  124523. }
  124524. }else{
  124525. if( pExpr->op==TK_IF_NULL_ROW && pExpr->iTable==pSubst->iTable ){
  124526. pExpr->iTable = pSubst->iNewTable;
  124527. }
  124528. pExpr->pLeft = substExpr(pSubst, pExpr->pLeft);
  124529. pExpr->pRight = substExpr(pSubst, pExpr->pRight);
  124530. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  124531. substSelect(pSubst, pExpr->x.pSelect, 1);
  124532. }else{
  124533. substExprList(pSubst, pExpr->x.pList);
  124534. }
  124535. #ifndef SQLITE_OMIT_WINDOWFUNC
  124536. if( ExprHasProperty(pExpr, EP_WinFunc) ){
  124537. Window *pWin = pExpr->y.pWin;
  124538. pWin->pFilter = substExpr(pSubst, pWin->pFilter);
  124539. substExprList(pSubst, pWin->pPartition);
  124540. substExprList(pSubst, pWin->pOrderBy);
  124541. }
  124542. #endif
  124543. }
  124544. return pExpr;
  124545. }
  124546. static void substExprList(
  124547. SubstContext *pSubst, /* Description of the substitution */
  124548. ExprList *pList /* List to scan and in which to make substitutes */
  124549. ){
  124550. int i;
  124551. if( pList==0 ) return;
  124552. for(i=0; i<pList->nExpr; i++){
  124553. pList->a[i].pExpr = substExpr(pSubst, pList->a[i].pExpr);
  124554. }
  124555. }
  124556. static void substSelect(
  124557. SubstContext *pSubst, /* Description of the substitution */
  124558. Select *p, /* SELECT statement in which to make substitutions */
  124559. int doPrior /* Do substitutes on p->pPrior too */
  124560. ){
  124561. SrcList *pSrc;
  124562. struct SrcList_item *pItem;
  124563. int i;
  124564. if( !p ) return;
  124565. do{
  124566. substExprList(pSubst, p->pEList);
  124567. substExprList(pSubst, p->pGroupBy);
  124568. substExprList(pSubst, p->pOrderBy);
  124569. p->pHaving = substExpr(pSubst, p->pHaving);
  124570. p->pWhere = substExpr(pSubst, p->pWhere);
  124571. pSrc = p->pSrc;
  124572. assert( pSrc!=0 );
  124573. for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
  124574. substSelect(pSubst, pItem->pSelect, 1);
  124575. if( pItem->fg.isTabFunc ){
  124576. substExprList(pSubst, pItem->u1.pFuncArg);
  124577. }
  124578. }
  124579. }while( doPrior && (p = p->pPrior)!=0 );
  124580. }
  124581. #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
  124582. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  124583. /*
  124584. ** pSelect is a SELECT statement and pSrcItem is one item in the FROM
  124585. ** clause of that SELECT.
  124586. **
  124587. ** This routine scans the entire SELECT statement and recomputes the
  124588. ** pSrcItem->colUsed mask.
  124589. */
  124590. static int recomputeColumnsUsedExpr(Walker *pWalker, Expr *pExpr){
  124591. struct SrcList_item *pItem;
  124592. if( pExpr->op!=TK_COLUMN ) return WRC_Continue;
  124593. pItem = pWalker->u.pSrcItem;
  124594. if( pItem->iCursor!=pExpr->iTable ) return WRC_Continue;
  124595. if( pExpr->iColumn<0 ) return WRC_Continue;
  124596. pItem->colUsed |= sqlite3ExprColUsed(pExpr);
  124597. return WRC_Continue;
  124598. }
  124599. static void recomputeColumnsUsed(
  124600. Select *pSelect, /* The complete SELECT statement */
  124601. struct SrcList_item *pSrcItem /* Which FROM clause item to recompute */
  124602. ){
  124603. Walker w;
  124604. if( NEVER(pSrcItem->pTab==0) ) return;
  124605. memset(&w, 0, sizeof(w));
  124606. w.xExprCallback = recomputeColumnsUsedExpr;
  124607. w.xSelectCallback = sqlite3SelectWalkNoop;
  124608. w.u.pSrcItem = pSrcItem;
  124609. pSrcItem->colUsed = 0;
  124610. sqlite3WalkSelect(&w, pSelect);
  124611. }
  124612. #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
  124613. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  124614. /*
  124615. ** This routine attempts to flatten subqueries as a performance optimization.
  124616. ** This routine returns 1 if it makes changes and 0 if no flattening occurs.
  124617. **
  124618. ** To understand the concept of flattening, consider the following
  124619. ** query:
  124620. **
  124621. ** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
  124622. **
  124623. ** The default way of implementing this query is to execute the
  124624. ** subquery first and store the results in a temporary table, then
  124625. ** run the outer query on that temporary table. This requires two
  124626. ** passes over the data. Furthermore, because the temporary table
  124627. ** has no indices, the WHERE clause on the outer query cannot be
  124628. ** optimized.
  124629. **
  124630. ** This routine attempts to rewrite queries such as the above into
  124631. ** a single flat select, like this:
  124632. **
  124633. ** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
  124634. **
  124635. ** The code generated for this simplification gives the same result
  124636. ** but only has to scan the data once. And because indices might
  124637. ** exist on the table t1, a complete scan of the data might be
  124638. ** avoided.
  124639. **
  124640. ** Flattening is subject to the following constraints:
  124641. **
  124642. ** (**) We no longer attempt to flatten aggregate subqueries. Was:
  124643. ** The subquery and the outer query cannot both be aggregates.
  124644. **
  124645. ** (**) We no longer attempt to flatten aggregate subqueries. Was:
  124646. ** (2) If the subquery is an aggregate then
  124647. ** (2a) the outer query must not be a join and
  124648. ** (2b) the outer query must not use subqueries
  124649. ** other than the one FROM-clause subquery that is a candidate
  124650. ** for flattening. (This is due to ticket [2f7170d73bf9abf80]
  124651. ** from 2015-02-09.)
  124652. **
  124653. ** (3) If the subquery is the right operand of a LEFT JOIN then
  124654. ** (3a) the subquery may not be a join and
  124655. ** (3b) the FROM clause of the subquery may not contain a virtual
  124656. ** table and
  124657. ** (3c) the outer query may not be an aggregate.
  124658. ** (3d) the outer query may not be DISTINCT.
  124659. **
  124660. ** (4) The subquery can not be DISTINCT.
  124661. **
  124662. ** (**) At one point restrictions (4) and (5) defined a subset of DISTINCT
  124663. ** sub-queries that were excluded from this optimization. Restriction
  124664. ** (4) has since been expanded to exclude all DISTINCT subqueries.
  124665. **
  124666. ** (**) We no longer attempt to flatten aggregate subqueries. Was:
  124667. ** If the subquery is aggregate, the outer query may not be DISTINCT.
  124668. **
  124669. ** (7) The subquery must have a FROM clause. TODO: For subqueries without
  124670. ** A FROM clause, consider adding a FROM clause with the special
  124671. ** table sqlite_once that consists of a single row containing a
  124672. ** single NULL.
  124673. **
  124674. ** (8) If the subquery uses LIMIT then the outer query may not be a join.
  124675. **
  124676. ** (9) If the subquery uses LIMIT then the outer query may not be aggregate.
  124677. **
  124678. ** (**) Restriction (10) was removed from the code on 2005-02-05 but we
  124679. ** accidently carried the comment forward until 2014-09-15. Original
  124680. ** constraint: "If the subquery is aggregate then the outer query
  124681. ** may not use LIMIT."
  124682. **
  124683. ** (11) The subquery and the outer query may not both have ORDER BY clauses.
  124684. **
  124685. ** (**) Not implemented. Subsumed into restriction (3). Was previously
  124686. ** a separate restriction deriving from ticket #350.
  124687. **
  124688. ** (13) The subquery and outer query may not both use LIMIT.
  124689. **
  124690. ** (14) The subquery may not use OFFSET.
  124691. **
  124692. ** (15) If the outer query is part of a compound select, then the
  124693. ** subquery may not use LIMIT.
  124694. ** (See ticket #2339 and ticket [02a8e81d44]).
  124695. **
  124696. ** (16) If the outer query is aggregate, then the subquery may not
  124697. ** use ORDER BY. (Ticket #2942) This used to not matter
  124698. ** until we introduced the group_concat() function.
  124699. **
  124700. ** (17) If the subquery is a compound select, then
  124701. ** (17a) all compound operators must be a UNION ALL, and
  124702. ** (17b) no terms within the subquery compound may be aggregate
  124703. ** or DISTINCT, and
  124704. ** (17c) every term within the subquery compound must have a FROM clause
  124705. ** (17d) the outer query may not be
  124706. ** (17d1) aggregate, or
  124707. ** (17d2) DISTINCT, or
  124708. ** (17d3) a join.
  124709. ** (17e) the subquery may not contain window functions
  124710. **
  124711. ** The parent and sub-query may contain WHERE clauses. Subject to
  124712. ** rules (11), (13) and (14), they may also contain ORDER BY,
  124713. ** LIMIT and OFFSET clauses. The subquery cannot use any compound
  124714. ** operator other than UNION ALL because all the other compound
  124715. ** operators have an implied DISTINCT which is disallowed by
  124716. ** restriction (4).
  124717. **
  124718. ** Also, each component of the sub-query must return the same number
  124719. ** of result columns. This is actually a requirement for any compound
  124720. ** SELECT statement, but all the code here does is make sure that no
  124721. ** such (illegal) sub-query is flattened. The caller will detect the
  124722. ** syntax error and return a detailed message.
  124723. **
  124724. ** (18) If the sub-query is a compound select, then all terms of the
  124725. ** ORDER BY clause of the parent must be simple references to
  124726. ** columns of the sub-query.
  124727. **
  124728. ** (19) If the subquery uses LIMIT then the outer query may not
  124729. ** have a WHERE clause.
  124730. **
  124731. ** (20) If the sub-query is a compound select, then it must not use
  124732. ** an ORDER BY clause. Ticket #3773. We could relax this constraint
  124733. ** somewhat by saying that the terms of the ORDER BY clause must
  124734. ** appear as unmodified result columns in the outer query. But we
  124735. ** have other optimizations in mind to deal with that case.
  124736. **
  124737. ** (21) If the subquery uses LIMIT then the outer query may not be
  124738. ** DISTINCT. (See ticket [752e1646fc]).
  124739. **
  124740. ** (22) The subquery may not be a recursive CTE.
  124741. **
  124742. ** (**) Subsumed into restriction (17d3). Was: If the outer query is
  124743. ** a recursive CTE, then the sub-query may not be a compound query.
  124744. ** This restriction is because transforming the
  124745. ** parent to a compound query confuses the code that handles
  124746. ** recursive queries in multiSelect().
  124747. **
  124748. ** (**) We no longer attempt to flatten aggregate subqueries. Was:
  124749. ** The subquery may not be an aggregate that uses the built-in min() or
  124750. ** or max() functions. (Without this restriction, a query like:
  124751. ** "SELECT x FROM (SELECT max(y), x FROM t1)" would not necessarily
  124752. ** return the value X for which Y was maximal.)
  124753. **
  124754. ** (25) If either the subquery or the parent query contains a window
  124755. ** function in the select list or ORDER BY clause, flattening
  124756. ** is not attempted.
  124757. **
  124758. **
  124759. ** In this routine, the "p" parameter is a pointer to the outer query.
  124760. ** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query
  124761. ** uses aggregates.
  124762. **
  124763. ** If flattening is not attempted, this routine is a no-op and returns 0.
  124764. ** If flattening is attempted this routine returns 1.
  124765. **
  124766. ** All of the expression analysis must occur on both the outer query and
  124767. ** the subquery before this routine runs.
  124768. */
  124769. static int flattenSubquery(
  124770. Parse *pParse, /* Parsing context */
  124771. Select *p, /* The parent or outer SELECT statement */
  124772. int iFrom, /* Index in p->pSrc->a[] of the inner subquery */
  124773. int isAgg /* True if outer SELECT uses aggregate functions */
  124774. ){
  124775. const char *zSavedAuthContext = pParse->zAuthContext;
  124776. Select *pParent; /* Current UNION ALL term of the other query */
  124777. Select *pSub; /* The inner query or "subquery" */
  124778. Select *pSub1; /* Pointer to the rightmost select in sub-query */
  124779. SrcList *pSrc; /* The FROM clause of the outer query */
  124780. SrcList *pSubSrc; /* The FROM clause of the subquery */
  124781. int iParent; /* VDBE cursor number of the pSub result set temp table */
  124782. int iNewParent = -1;/* Replacement table for iParent */
  124783. int isLeftJoin = 0; /* True if pSub is the right side of a LEFT JOIN */
  124784. int i; /* Loop counter */
  124785. Expr *pWhere; /* The WHERE clause */
  124786. struct SrcList_item *pSubitem; /* The subquery */
  124787. sqlite3 *db = pParse->db;
  124788. /* Check to see if flattening is permitted. Return 0 if not.
  124789. */
  124790. assert( p!=0 );
  124791. assert( p->pPrior==0 );
  124792. if( OptimizationDisabled(db, SQLITE_QueryFlattener) ) return 0;
  124793. pSrc = p->pSrc;
  124794. assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
  124795. pSubitem = &pSrc->a[iFrom];
  124796. iParent = pSubitem->iCursor;
  124797. pSub = pSubitem->pSelect;
  124798. assert( pSub!=0 );
  124799. #ifndef SQLITE_OMIT_WINDOWFUNC
  124800. if( p->pWin || pSub->pWin ) return 0; /* Restriction (25) */
  124801. #endif
  124802. pSubSrc = pSub->pSrc;
  124803. assert( pSubSrc );
  124804. /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
  124805. ** not arbitrary expressions, we allowed some combining of LIMIT and OFFSET
  124806. ** because they could be computed at compile-time. But when LIMIT and OFFSET
  124807. ** became arbitrary expressions, we were forced to add restrictions (13)
  124808. ** and (14). */
  124809. if( pSub->pLimit && p->pLimit ) return 0; /* Restriction (13) */
  124810. if( pSub->pLimit && pSub->pLimit->pRight ) return 0; /* Restriction (14) */
  124811. if( (p->selFlags & SF_Compound)!=0 && pSub->pLimit ){
  124812. return 0; /* Restriction (15) */
  124813. }
  124814. if( pSubSrc->nSrc==0 ) return 0; /* Restriction (7) */
  124815. if( pSub->selFlags & SF_Distinct ) return 0; /* Restriction (4) */
  124816. if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
  124817. return 0; /* Restrictions (8)(9) */
  124818. }
  124819. if( p->pOrderBy && pSub->pOrderBy ){
  124820. return 0; /* Restriction (11) */
  124821. }
  124822. if( isAgg && pSub->pOrderBy ) return 0; /* Restriction (16) */
  124823. if( pSub->pLimit && p->pWhere ) return 0; /* Restriction (19) */
  124824. if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){
  124825. return 0; /* Restriction (21) */
  124826. }
  124827. if( pSub->selFlags & (SF_Recursive) ){
  124828. return 0; /* Restrictions (22) */
  124829. }
  124830. /*
  124831. ** If the subquery is the right operand of a LEFT JOIN, then the
  124832. ** subquery may not be a join itself (3a). Example of why this is not
  124833. ** allowed:
  124834. **
  124835. ** t1 LEFT OUTER JOIN (t2 JOIN t3)
  124836. **
  124837. ** If we flatten the above, we would get
  124838. **
  124839. ** (t1 LEFT OUTER JOIN t2) JOIN t3
  124840. **
  124841. ** which is not at all the same thing.
  124842. **
  124843. ** If the subquery is the right operand of a LEFT JOIN, then the outer
  124844. ** query cannot be an aggregate. (3c) This is an artifact of the way
  124845. ** aggregates are processed - there is no mechanism to determine if
  124846. ** the LEFT JOIN table should be all-NULL.
  124847. **
  124848. ** See also tickets #306, #350, and #3300.
  124849. */
  124850. if( (pSubitem->fg.jointype & JT_OUTER)!=0 ){
  124851. isLeftJoin = 1;
  124852. if( pSubSrc->nSrc>1 /* (3a) */
  124853. || isAgg /* (3b) */
  124854. || IsVirtual(pSubSrc->a[0].pTab) /* (3c) */
  124855. || (p->selFlags & SF_Distinct)!=0 /* (3d) */
  124856. ){
  124857. return 0;
  124858. }
  124859. }
  124860. #ifdef SQLITE_EXTRA_IFNULLROW
  124861. else if( iFrom>0 && !isAgg ){
  124862. /* Setting isLeftJoin to -1 causes OP_IfNullRow opcodes to be generated for
  124863. ** every reference to any result column from subquery in a join, even
  124864. ** though they are not necessary. This will stress-test the OP_IfNullRow
  124865. ** opcode. */
  124866. isLeftJoin = -1;
  124867. }
  124868. #endif
  124869. /* Restriction (17): If the sub-query is a compound SELECT, then it must
  124870. ** use only the UNION ALL operator. And none of the simple select queries
  124871. ** that make up the compound SELECT are allowed to be aggregate or distinct
  124872. ** queries.
  124873. */
  124874. if( pSub->pPrior ){
  124875. if( pSub->pOrderBy ){
  124876. return 0; /* Restriction (20) */
  124877. }
  124878. if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
  124879. return 0; /* (17d1), (17d2), or (17d3) */
  124880. }
  124881. for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
  124882. testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
  124883. testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
  124884. assert( pSub->pSrc!=0 );
  124885. assert( pSub->pEList->nExpr==pSub1->pEList->nExpr );
  124886. if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0 /* (17b) */
  124887. || (pSub1->pPrior && pSub1->op!=TK_ALL) /* (17a) */
  124888. || pSub1->pSrc->nSrc<1 /* (17c) */
  124889. #ifndef SQLITE_OMIT_WINDOWFUNC
  124890. || pSub1->pWin /* (17e) */
  124891. #endif
  124892. ){
  124893. return 0;
  124894. }
  124895. testcase( pSub1->pSrc->nSrc>1 );
  124896. }
  124897. /* Restriction (18). */
  124898. if( p->pOrderBy ){
  124899. int ii;
  124900. for(ii=0; ii<p->pOrderBy->nExpr; ii++){
  124901. if( p->pOrderBy->a[ii].u.x.iOrderByCol==0 ) return 0;
  124902. }
  124903. }
  124904. }
  124905. /* Ex-restriction (23):
  124906. ** The only way that the recursive part of a CTE can contain a compound
  124907. ** subquery is for the subquery to be one term of a join. But if the
  124908. ** subquery is a join, then the flattening has already been stopped by
  124909. ** restriction (17d3)
  124910. */
  124911. assert( (p->selFlags & SF_Recursive)==0 || pSub->pPrior==0 );
  124912. /***** If we reach this point, flattening is permitted. *****/
  124913. SELECTTRACE(1,pParse,p,("flatten %u.%p from term %d\n",
  124914. pSub->selId, pSub, iFrom));
  124915. /* Authorize the subquery */
  124916. pParse->zAuthContext = pSubitem->zName;
  124917. TESTONLY(i =) sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
  124918. testcase( i==SQLITE_DENY );
  124919. pParse->zAuthContext = zSavedAuthContext;
  124920. /* If the sub-query is a compound SELECT statement, then (by restrictions
  124921. ** 17 and 18 above) it must be a UNION ALL and the parent query must
  124922. ** be of the form:
  124923. **
  124924. ** SELECT <expr-list> FROM (<sub-query>) <where-clause>
  124925. **
  124926. ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
  124927. ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or
  124928. ** OFFSET clauses and joins them to the left-hand-side of the original
  124929. ** using UNION ALL operators. In this case N is the number of simple
  124930. ** select statements in the compound sub-query.
  124931. **
  124932. ** Example:
  124933. **
  124934. ** SELECT a+1 FROM (
  124935. ** SELECT x FROM tab
  124936. ** UNION ALL
  124937. ** SELECT y FROM tab
  124938. ** UNION ALL
  124939. ** SELECT abs(z*2) FROM tab2
  124940. ** ) WHERE a!=5 ORDER BY 1
  124941. **
  124942. ** Transformed into:
  124943. **
  124944. ** SELECT x+1 FROM tab WHERE x+1!=5
  124945. ** UNION ALL
  124946. ** SELECT y+1 FROM tab WHERE y+1!=5
  124947. ** UNION ALL
  124948. ** SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
  124949. ** ORDER BY 1
  124950. **
  124951. ** We call this the "compound-subquery flattening".
  124952. */
  124953. for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
  124954. Select *pNew;
  124955. ExprList *pOrderBy = p->pOrderBy;
  124956. Expr *pLimit = p->pLimit;
  124957. Select *pPrior = p->pPrior;
  124958. p->pOrderBy = 0;
  124959. p->pSrc = 0;
  124960. p->pPrior = 0;
  124961. p->pLimit = 0;
  124962. pNew = sqlite3SelectDup(db, p, 0);
  124963. p->pLimit = pLimit;
  124964. p->pOrderBy = pOrderBy;
  124965. p->pSrc = pSrc;
  124966. p->op = TK_ALL;
  124967. if( pNew==0 ){
  124968. p->pPrior = pPrior;
  124969. }else{
  124970. pNew->pPrior = pPrior;
  124971. if( pPrior ) pPrior->pNext = pNew;
  124972. pNew->pNext = p;
  124973. p->pPrior = pNew;
  124974. SELECTTRACE(2,pParse,p,("compound-subquery flattener"
  124975. " creates %u as peer\n",pNew->selId));
  124976. }
  124977. if( db->mallocFailed ) return 1;
  124978. }
  124979. /* Begin flattening the iFrom-th entry of the FROM clause
  124980. ** in the outer query.
  124981. */
  124982. pSub = pSub1 = pSubitem->pSelect;
  124983. /* Delete the transient table structure associated with the
  124984. ** subquery
  124985. */
  124986. sqlite3DbFree(db, pSubitem->zDatabase);
  124987. sqlite3DbFree(db, pSubitem->zName);
  124988. sqlite3DbFree(db, pSubitem->zAlias);
  124989. pSubitem->zDatabase = 0;
  124990. pSubitem->zName = 0;
  124991. pSubitem->zAlias = 0;
  124992. pSubitem->pSelect = 0;
  124993. /* Defer deleting the Table object associated with the
  124994. ** subquery until code generation is
  124995. ** complete, since there may still exist Expr.pTab entries that
  124996. ** refer to the subquery even after flattening. Ticket #3346.
  124997. **
  124998. ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
  124999. */
  125000. if( ALWAYS(pSubitem->pTab!=0) ){
  125001. Table *pTabToDel = pSubitem->pTab;
  125002. if( pTabToDel->nTabRef==1 ){
  125003. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  125004. pTabToDel->pNextZombie = pToplevel->pZombieTab;
  125005. pToplevel->pZombieTab = pTabToDel;
  125006. }else{
  125007. pTabToDel->nTabRef--;
  125008. }
  125009. pSubitem->pTab = 0;
  125010. }
  125011. /* The following loop runs once for each term in a compound-subquery
  125012. ** flattening (as described above). If we are doing a different kind
  125013. ** of flattening - a flattening other than a compound-subquery flattening -
  125014. ** then this loop only runs once.
  125015. **
  125016. ** This loop moves all of the FROM elements of the subquery into the
  125017. ** the FROM clause of the outer query. Before doing this, remember
  125018. ** the cursor number for the original outer query FROM element in
  125019. ** iParent. The iParent cursor will never be used. Subsequent code
  125020. ** will scan expressions looking for iParent references and replace
  125021. ** those references with expressions that resolve to the subquery FROM
  125022. ** elements we are now copying in.
  125023. */
  125024. for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
  125025. int nSubSrc;
  125026. u8 jointype = 0;
  125027. assert( pSub!=0 );
  125028. pSubSrc = pSub->pSrc; /* FROM clause of subquery */
  125029. nSubSrc = pSubSrc->nSrc; /* Number of terms in subquery FROM clause */
  125030. pSrc = pParent->pSrc; /* FROM clause of the outer query */
  125031. if( pSrc ){
  125032. assert( pParent==p ); /* First time through the loop */
  125033. jointype = pSubitem->fg.jointype;
  125034. }else{
  125035. assert( pParent!=p ); /* 2nd and subsequent times through the loop */
  125036. pSrc = sqlite3SrcListAppend(pParse, 0, 0, 0);
  125037. if( pSrc==0 ) break;
  125038. pParent->pSrc = pSrc;
  125039. }
  125040. /* The subquery uses a single slot of the FROM clause of the outer
  125041. ** query. If the subquery has more than one element in its FROM clause,
  125042. ** then expand the outer query to make space for it to hold all elements
  125043. ** of the subquery.
  125044. **
  125045. ** Example:
  125046. **
  125047. ** SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
  125048. **
  125049. ** The outer query has 3 slots in its FROM clause. One slot of the
  125050. ** outer query (the middle slot) is used by the subquery. The next
  125051. ** block of code will expand the outer query FROM clause to 4 slots.
  125052. ** The middle slot is expanded to two slots in order to make space
  125053. ** for the two elements in the FROM clause of the subquery.
  125054. */
  125055. if( nSubSrc>1 ){
  125056. pSrc = sqlite3SrcListEnlarge(pParse, pSrc, nSubSrc-1,iFrom+1);
  125057. if( pSrc==0 ) break;
  125058. pParent->pSrc = pSrc;
  125059. }
  125060. /* Transfer the FROM clause terms from the subquery into the
  125061. ** outer query.
  125062. */
  125063. for(i=0; i<nSubSrc; i++){
  125064. sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
  125065. assert( pSrc->a[i+iFrom].fg.isTabFunc==0 );
  125066. pSrc->a[i+iFrom] = pSubSrc->a[i];
  125067. iNewParent = pSubSrc->a[i].iCursor;
  125068. memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
  125069. }
  125070. pSrc->a[iFrom].fg.jointype = jointype;
  125071. /* Now begin substituting subquery result set expressions for
  125072. ** references to the iParent in the outer query.
  125073. **
  125074. ** Example:
  125075. **
  125076. ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
  125077. ** \ \_____________ subquery __________/ /
  125078. ** \_____________________ outer query ______________________________/
  125079. **
  125080. ** We look at every expression in the outer query and every place we see
  125081. ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
  125082. */
  125083. if( pSub->pOrderBy ){
  125084. /* At this point, any non-zero iOrderByCol values indicate that the
  125085. ** ORDER BY column expression is identical to the iOrderByCol'th
  125086. ** expression returned by SELECT statement pSub. Since these values
  125087. ** do not necessarily correspond to columns in SELECT statement pParent,
  125088. ** zero them before transfering the ORDER BY clause.
  125089. **
  125090. ** Not doing this may cause an error if a subsequent call to this
  125091. ** function attempts to flatten a compound sub-query into pParent
  125092. ** (the only way this can happen is if the compound sub-query is
  125093. ** currently part of pSub->pSrc). See ticket [d11a6e908f]. */
  125094. ExprList *pOrderBy = pSub->pOrderBy;
  125095. for(i=0; i<pOrderBy->nExpr; i++){
  125096. pOrderBy->a[i].u.x.iOrderByCol = 0;
  125097. }
  125098. assert( pParent->pOrderBy==0 );
  125099. pParent->pOrderBy = pOrderBy;
  125100. pSub->pOrderBy = 0;
  125101. }
  125102. pWhere = pSub->pWhere;
  125103. pSub->pWhere = 0;
  125104. if( isLeftJoin>0 ){
  125105. sqlite3SetJoinExpr(pWhere, iNewParent);
  125106. }
  125107. pParent->pWhere = sqlite3ExprAnd(pParse, pWhere, pParent->pWhere);
  125108. if( db->mallocFailed==0 ){
  125109. SubstContext x;
  125110. x.pParse = pParse;
  125111. x.iTable = iParent;
  125112. x.iNewTable = iNewParent;
  125113. x.isLeftJoin = isLeftJoin;
  125114. x.pEList = pSub->pEList;
  125115. substSelect(&x, pParent, 0);
  125116. }
  125117. /* The flattened query is a compound if either the inner or the
  125118. ** outer query is a compound. */
  125119. pParent->selFlags |= pSub->selFlags & SF_Compound;
  125120. assert( (pSub->selFlags & SF_Distinct)==0 ); /* restriction (17b) */
  125121. /*
  125122. ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
  125123. **
  125124. ** One is tempted to try to add a and b to combine the limits. But this
  125125. ** does not work if either limit is negative.
  125126. */
  125127. if( pSub->pLimit ){
  125128. pParent->pLimit = pSub->pLimit;
  125129. pSub->pLimit = 0;
  125130. }
  125131. /* Recompute the SrcList_item.colUsed masks for the flattened
  125132. ** tables. */
  125133. for(i=0; i<nSubSrc; i++){
  125134. recomputeColumnsUsed(pParent, &pSrc->a[i+iFrom]);
  125135. }
  125136. }
  125137. /* Finially, delete what is left of the subquery and return
  125138. ** success.
  125139. */
  125140. sqlite3SelectDelete(db, pSub1);
  125141. #if SELECTTRACE_ENABLED
  125142. if( sqlite3SelectTrace & 0x100 ){
  125143. SELECTTRACE(0x100,pParse,p,("After flattening:\n"));
  125144. sqlite3TreeViewSelect(0, p, 0);
  125145. }
  125146. #endif
  125147. return 1;
  125148. }
  125149. #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
  125150. /*
  125151. ** A structure to keep track of all of the column values that are fixed to
  125152. ** a known value due to WHERE clause constraints of the form COLUMN=VALUE.
  125153. */
  125154. typedef struct WhereConst WhereConst;
  125155. struct WhereConst {
  125156. Parse *pParse; /* Parsing context */
  125157. int nConst; /* Number for COLUMN=CONSTANT terms */
  125158. int nChng; /* Number of times a constant is propagated */
  125159. Expr **apExpr; /* [i*2] is COLUMN and [i*2+1] is VALUE */
  125160. };
  125161. /*
  125162. ** Add a new entry to the pConst object. Except, do not add duplicate
  125163. ** pColumn entires. Also, do not add if doing so would not be appropriate.
  125164. **
  125165. ** The caller guarantees the pColumn is a column and pValue is a constant.
  125166. ** This routine has to do some additional checks before completing the
  125167. ** insert.
  125168. */
  125169. static void constInsert(
  125170. WhereConst *pConst, /* The WhereConst into which we are inserting */
  125171. Expr *pColumn, /* The COLUMN part of the constraint */
  125172. Expr *pValue, /* The VALUE part of the constraint */
  125173. Expr *pExpr /* Overall expression: COLUMN=VALUE or VALUE=COLUMN */
  125174. ){
  125175. int i;
  125176. assert( pColumn->op==TK_COLUMN );
  125177. assert( sqlite3ExprIsConstant(pValue) );
  125178. if( ExprHasProperty(pColumn, EP_FixedCol) ) return;
  125179. if( sqlite3ExprAffinity(pValue)!=0 ) return;
  125180. if( !sqlite3IsBinary(sqlite3ExprCompareCollSeq(pConst->pParse,pExpr)) ){
  125181. return;
  125182. }
  125183. /* 2018-10-25 ticket [cf5ed20f]
  125184. ** Make sure the same pColumn is not inserted more than once */
  125185. for(i=0; i<pConst->nConst; i++){
  125186. const Expr *pE2 = pConst->apExpr[i*2];
  125187. assert( pE2->op==TK_COLUMN );
  125188. if( pE2->iTable==pColumn->iTable
  125189. && pE2->iColumn==pColumn->iColumn
  125190. ){
  125191. return; /* Already present. Return without doing anything. */
  125192. }
  125193. }
  125194. pConst->nConst++;
  125195. pConst->apExpr = sqlite3DbReallocOrFree(pConst->pParse->db, pConst->apExpr,
  125196. pConst->nConst*2*sizeof(Expr*));
  125197. if( pConst->apExpr==0 ){
  125198. pConst->nConst = 0;
  125199. }else{
  125200. pConst->apExpr[pConst->nConst*2-2] = pColumn;
  125201. pConst->apExpr[pConst->nConst*2-1] = pValue;
  125202. }
  125203. }
  125204. /*
  125205. ** Find all terms of COLUMN=VALUE or VALUE=COLUMN in pExpr where VALUE
  125206. ** is a constant expression and where the term must be true because it
  125207. ** is part of the AND-connected terms of the expression. For each term
  125208. ** found, add it to the pConst structure.
  125209. */
  125210. static void findConstInWhere(WhereConst *pConst, Expr *pExpr){
  125211. Expr *pRight, *pLeft;
  125212. if( pExpr==0 ) return;
  125213. if( ExprHasProperty(pExpr, EP_FromJoin) ) return;
  125214. if( pExpr->op==TK_AND ){
  125215. findConstInWhere(pConst, pExpr->pRight);
  125216. findConstInWhere(pConst, pExpr->pLeft);
  125217. return;
  125218. }
  125219. if( pExpr->op!=TK_EQ ) return;
  125220. pRight = pExpr->pRight;
  125221. pLeft = pExpr->pLeft;
  125222. assert( pRight!=0 );
  125223. assert( pLeft!=0 );
  125224. if( pRight->op==TK_COLUMN && sqlite3ExprIsConstant(pLeft) ){
  125225. constInsert(pConst,pRight,pLeft,pExpr);
  125226. }
  125227. if( pLeft->op==TK_COLUMN && sqlite3ExprIsConstant(pRight) ){
  125228. constInsert(pConst,pLeft,pRight,pExpr);
  125229. }
  125230. }
  125231. /*
  125232. ** This is a Walker expression callback. pExpr is a candidate expression
  125233. ** to be replaced by a value. If pExpr is equivalent to one of the
  125234. ** columns named in pWalker->u.pConst, then overwrite it with its
  125235. ** corresponding value.
  125236. */
  125237. static int propagateConstantExprRewrite(Walker *pWalker, Expr *pExpr){
  125238. int i;
  125239. WhereConst *pConst;
  125240. if( pExpr->op!=TK_COLUMN ) return WRC_Continue;
  125241. if( ExprHasProperty(pExpr, EP_FixedCol|EP_FromJoin) ){
  125242. testcase( ExprHasProperty(pExpr, EP_FixedCol) );
  125243. testcase( ExprHasProperty(pExpr, EP_FromJoin) );
  125244. return WRC_Continue;
  125245. }
  125246. pConst = pWalker->u.pConst;
  125247. for(i=0; i<pConst->nConst; i++){
  125248. Expr *pColumn = pConst->apExpr[i*2];
  125249. if( pColumn==pExpr ) continue;
  125250. if( pColumn->iTable!=pExpr->iTable ) continue;
  125251. if( pColumn->iColumn!=pExpr->iColumn ) continue;
  125252. /* A match is found. Add the EP_FixedCol property */
  125253. pConst->nChng++;
  125254. ExprClearProperty(pExpr, EP_Leaf);
  125255. ExprSetProperty(pExpr, EP_FixedCol);
  125256. assert( pExpr->pLeft==0 );
  125257. pExpr->pLeft = sqlite3ExprDup(pConst->pParse->db, pConst->apExpr[i*2+1], 0);
  125258. break;
  125259. }
  125260. return WRC_Prune;
  125261. }
  125262. /*
  125263. ** The WHERE-clause constant propagation optimization.
  125264. **
  125265. ** If the WHERE clause contains terms of the form COLUMN=CONSTANT or
  125266. ** CONSTANT=COLUMN that are top-level AND-connected terms that are not
  125267. ** part of a ON clause from a LEFT JOIN, then throughout the query
  125268. ** replace all other occurrences of COLUMN with CONSTANT.
  125269. **
  125270. ** For example, the query:
  125271. **
  125272. ** SELECT * FROM t1, t2, t3 WHERE t1.a=39 AND t2.b=t1.a AND t3.c=t2.b
  125273. **
  125274. ** Is transformed into
  125275. **
  125276. ** SELECT * FROM t1, t2, t3 WHERE t1.a=39 AND t2.b=39 AND t3.c=39
  125277. **
  125278. ** Return true if any transformations where made and false if not.
  125279. **
  125280. ** Implementation note: Constant propagation is tricky due to affinity
  125281. ** and collating sequence interactions. Consider this example:
  125282. **
  125283. ** CREATE TABLE t1(a INT,b TEXT);
  125284. ** INSERT INTO t1 VALUES(123,'0123');
  125285. ** SELECT * FROM t1 WHERE a=123 AND b=a;
  125286. ** SELECT * FROM t1 WHERE a=123 AND b=123;
  125287. **
  125288. ** The two SELECT statements above should return different answers. b=a
  125289. ** is alway true because the comparison uses numeric affinity, but b=123
  125290. ** is false because it uses text affinity and '0123' is not the same as '123'.
  125291. ** To work around this, the expression tree is not actually changed from
  125292. ** "b=a" to "b=123" but rather the "a" in "b=a" is tagged with EP_FixedCol
  125293. ** and the "123" value is hung off of the pLeft pointer. Code generator
  125294. ** routines know to generate the constant "123" instead of looking up the
  125295. ** column value. Also, to avoid collation problems, this optimization is
  125296. ** only attempted if the "a=123" term uses the default BINARY collation.
  125297. */
  125298. static int propagateConstants(
  125299. Parse *pParse, /* The parsing context */
  125300. Select *p /* The query in which to propagate constants */
  125301. ){
  125302. WhereConst x;
  125303. Walker w;
  125304. int nChng = 0;
  125305. x.pParse = pParse;
  125306. do{
  125307. x.nConst = 0;
  125308. x.nChng = 0;
  125309. x.apExpr = 0;
  125310. findConstInWhere(&x, p->pWhere);
  125311. if( x.nConst ){
  125312. memset(&w, 0, sizeof(w));
  125313. w.pParse = pParse;
  125314. w.xExprCallback = propagateConstantExprRewrite;
  125315. w.xSelectCallback = sqlite3SelectWalkNoop;
  125316. w.xSelectCallback2 = 0;
  125317. w.walkerDepth = 0;
  125318. w.u.pConst = &x;
  125319. sqlite3WalkExpr(&w, p->pWhere);
  125320. sqlite3DbFree(x.pParse->db, x.apExpr);
  125321. nChng += x.nChng;
  125322. }
  125323. }while( x.nChng );
  125324. return nChng;
  125325. }
  125326. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  125327. /*
  125328. ** Make copies of relevant WHERE clause terms of the outer query into
  125329. ** the WHERE clause of subquery. Example:
  125330. **
  125331. ** SELECT * FROM (SELECT a AS x, c-d AS y FROM t1) WHERE x=5 AND y=10;
  125332. **
  125333. ** Transformed into:
  125334. **
  125335. ** SELECT * FROM (SELECT a AS x, c-d AS y FROM t1 WHERE a=5 AND c-d=10)
  125336. ** WHERE x=5 AND y=10;
  125337. **
  125338. ** The hope is that the terms added to the inner query will make it more
  125339. ** efficient.
  125340. **
  125341. ** Do not attempt this optimization if:
  125342. **
  125343. ** (1) (** This restriction was removed on 2017-09-29. We used to
  125344. ** disallow this optimization for aggregate subqueries, but now
  125345. ** it is allowed by putting the extra terms on the HAVING clause.
  125346. ** The added HAVING clause is pointless if the subquery lacks
  125347. ** a GROUP BY clause. But such a HAVING clause is also harmless
  125348. ** so there does not appear to be any reason to add extra logic
  125349. ** to suppress it. **)
  125350. **
  125351. ** (2) The inner query is the recursive part of a common table expression.
  125352. **
  125353. ** (3) The inner query has a LIMIT clause (since the changes to the WHERE
  125354. ** clause would change the meaning of the LIMIT).
  125355. **
  125356. ** (4) The inner query is the right operand of a LEFT JOIN and the
  125357. ** expression to be pushed down does not come from the ON clause
  125358. ** on that LEFT JOIN.
  125359. **
  125360. ** (5) The WHERE clause expression originates in the ON or USING clause
  125361. ** of a LEFT JOIN where iCursor is not the right-hand table of that
  125362. ** left join. An example:
  125363. **
  125364. ** SELECT *
  125365. ** FROM (SELECT 1 AS a1 UNION ALL SELECT 2) AS aa
  125366. ** JOIN (SELECT 1 AS b2 UNION ALL SELECT 2) AS bb ON (a1=b2)
  125367. ** LEFT JOIN (SELECT 8 AS c3 UNION ALL SELECT 9) AS cc ON (b2=2);
  125368. **
  125369. ** The correct answer is three rows: (1,1,NULL),(2,2,8),(2,2,9).
  125370. ** But if the (b2=2) term were to be pushed down into the bb subquery,
  125371. ** then the (1,1,NULL) row would be suppressed.
  125372. **
  125373. ** (6) The inner query features one or more window-functions (since
  125374. ** changes to the WHERE clause of the inner query could change the
  125375. ** window over which window functions are calculated).
  125376. **
  125377. ** Return 0 if no changes are made and non-zero if one or more WHERE clause
  125378. ** terms are duplicated into the subquery.
  125379. */
  125380. static int pushDownWhereTerms(
  125381. Parse *pParse, /* Parse context (for malloc() and error reporting) */
  125382. Select *pSubq, /* The subquery whose WHERE clause is to be augmented */
  125383. Expr *pWhere, /* The WHERE clause of the outer query */
  125384. int iCursor, /* Cursor number of the subquery */
  125385. int isLeftJoin /* True if pSubq is the right term of a LEFT JOIN */
  125386. ){
  125387. Expr *pNew;
  125388. int nChng = 0;
  125389. if( pWhere==0 ) return 0;
  125390. if( pSubq->selFlags & SF_Recursive ) return 0; /* restriction (2) */
  125391. #ifndef SQLITE_OMIT_WINDOWFUNC
  125392. if( pSubq->pWin ) return 0; /* restriction (6) */
  125393. #endif
  125394. #ifdef SQLITE_DEBUG
  125395. /* Only the first term of a compound can have a WITH clause. But make
  125396. ** sure no other terms are marked SF_Recursive in case something changes
  125397. ** in the future.
  125398. */
  125399. {
  125400. Select *pX;
  125401. for(pX=pSubq; pX; pX=pX->pPrior){
  125402. assert( (pX->selFlags & (SF_Recursive))==0 );
  125403. }
  125404. }
  125405. #endif
  125406. if( pSubq->pLimit!=0 ){
  125407. return 0; /* restriction (3) */
  125408. }
  125409. while( pWhere->op==TK_AND ){
  125410. nChng += pushDownWhereTerms(pParse, pSubq, pWhere->pRight,
  125411. iCursor, isLeftJoin);
  125412. pWhere = pWhere->pLeft;
  125413. }
  125414. if( isLeftJoin
  125415. && (ExprHasProperty(pWhere,EP_FromJoin)==0
  125416. || pWhere->iRightJoinTable!=iCursor)
  125417. ){
  125418. return 0; /* restriction (4) */
  125419. }
  125420. if( ExprHasProperty(pWhere,EP_FromJoin) && pWhere->iRightJoinTable!=iCursor ){
  125421. return 0; /* restriction (5) */
  125422. }
  125423. if( sqlite3ExprIsTableConstant(pWhere, iCursor) ){
  125424. nChng++;
  125425. while( pSubq ){
  125426. SubstContext x;
  125427. pNew = sqlite3ExprDup(pParse->db, pWhere, 0);
  125428. unsetJoinExpr(pNew, -1);
  125429. x.pParse = pParse;
  125430. x.iTable = iCursor;
  125431. x.iNewTable = iCursor;
  125432. x.isLeftJoin = 0;
  125433. x.pEList = pSubq->pEList;
  125434. pNew = substExpr(&x, pNew);
  125435. if( pSubq->selFlags & SF_Aggregate ){
  125436. pSubq->pHaving = sqlite3ExprAnd(pParse, pSubq->pHaving, pNew);
  125437. }else{
  125438. pSubq->pWhere = sqlite3ExprAnd(pParse, pSubq->pWhere, pNew);
  125439. }
  125440. pSubq = pSubq->pPrior;
  125441. }
  125442. }
  125443. return nChng;
  125444. }
  125445. #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
  125446. /*
  125447. ** The pFunc is the only aggregate function in the query. Check to see
  125448. ** if the query is a candidate for the min/max optimization.
  125449. **
  125450. ** If the query is a candidate for the min/max optimization, then set
  125451. ** *ppMinMax to be an ORDER BY clause to be used for the optimization
  125452. ** and return either WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX depending on
  125453. ** whether pFunc is a min() or max() function.
  125454. **
  125455. ** If the query is not a candidate for the min/max optimization, return
  125456. ** WHERE_ORDERBY_NORMAL (which must be zero).
  125457. **
  125458. ** This routine must be called after aggregate functions have been
  125459. ** located but before their arguments have been subjected to aggregate
  125460. ** analysis.
  125461. */
  125462. static u8 minMaxQuery(sqlite3 *db, Expr *pFunc, ExprList **ppMinMax){
  125463. int eRet = WHERE_ORDERBY_NORMAL; /* Return value */
  125464. ExprList *pEList = pFunc->x.pList; /* Arguments to agg function */
  125465. const char *zFunc; /* Name of aggregate function pFunc */
  125466. ExprList *pOrderBy;
  125467. u8 sortFlags = 0;
  125468. assert( *ppMinMax==0 );
  125469. assert( pFunc->op==TK_AGG_FUNCTION );
  125470. assert( !IsWindowFunc(pFunc) );
  125471. if( pEList==0 || pEList->nExpr!=1 || ExprHasProperty(pFunc, EP_WinFunc) ){
  125472. return eRet;
  125473. }
  125474. zFunc = pFunc->u.zToken;
  125475. if( sqlite3StrICmp(zFunc, "min")==0 ){
  125476. eRet = WHERE_ORDERBY_MIN;
  125477. if( sqlite3ExprCanBeNull(pEList->a[0].pExpr) ){
  125478. sortFlags = KEYINFO_ORDER_BIGNULL;
  125479. }
  125480. }else if( sqlite3StrICmp(zFunc, "max")==0 ){
  125481. eRet = WHERE_ORDERBY_MAX;
  125482. sortFlags = KEYINFO_ORDER_DESC;
  125483. }else{
  125484. return eRet;
  125485. }
  125486. *ppMinMax = pOrderBy = sqlite3ExprListDup(db, pEList, 0);
  125487. assert( pOrderBy!=0 || db->mallocFailed );
  125488. if( pOrderBy ) pOrderBy->a[0].sortFlags = sortFlags;
  125489. return eRet;
  125490. }
  125491. /*
  125492. ** The select statement passed as the first argument is an aggregate query.
  125493. ** The second argument is the associated aggregate-info object. This
  125494. ** function tests if the SELECT is of the form:
  125495. **
  125496. ** SELECT count(*) FROM <tbl>
  125497. **
  125498. ** where table is a database table, not a sub-select or view. If the query
  125499. ** does match this pattern, then a pointer to the Table object representing
  125500. ** <tbl> is returned. Otherwise, 0 is returned.
  125501. */
  125502. static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
  125503. Table *pTab;
  125504. Expr *pExpr;
  125505. assert( !p->pGroupBy );
  125506. if( p->pWhere || p->pEList->nExpr!=1
  125507. || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
  125508. ){
  125509. return 0;
  125510. }
  125511. pTab = p->pSrc->a[0].pTab;
  125512. pExpr = p->pEList->a[0].pExpr;
  125513. assert( pTab && !pTab->pSelect && pExpr );
  125514. if( IsVirtual(pTab) ) return 0;
  125515. if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
  125516. if( NEVER(pAggInfo->nFunc==0) ) return 0;
  125517. if( (pAggInfo->aFunc[0].pFunc->funcFlags&SQLITE_FUNC_COUNT)==0 ) return 0;
  125518. if( ExprHasProperty(pExpr, EP_Distinct|EP_WinFunc) ) return 0;
  125519. return pTab;
  125520. }
  125521. /*
  125522. ** If the source-list item passed as an argument was augmented with an
  125523. ** INDEXED BY clause, then try to locate the specified index. If there
  125524. ** was such a clause and the named index cannot be found, return
  125525. ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate
  125526. ** pFrom->pIndex and return SQLITE_OK.
  125527. */
  125528. SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
  125529. if( pFrom->pTab && pFrom->fg.isIndexedBy ){
  125530. Table *pTab = pFrom->pTab;
  125531. char *zIndexedBy = pFrom->u1.zIndexedBy;
  125532. Index *pIdx;
  125533. for(pIdx=pTab->pIndex;
  125534. pIdx && sqlite3StrICmp(pIdx->zName, zIndexedBy);
  125535. pIdx=pIdx->pNext
  125536. );
  125537. if( !pIdx ){
  125538. sqlite3ErrorMsg(pParse, "no such index: %s", zIndexedBy, 0);
  125539. pParse->checkSchema = 1;
  125540. return SQLITE_ERROR;
  125541. }
  125542. pFrom->pIBIndex = pIdx;
  125543. }
  125544. return SQLITE_OK;
  125545. }
  125546. /*
  125547. ** Detect compound SELECT statements that use an ORDER BY clause with
  125548. ** an alternative collating sequence.
  125549. **
  125550. ** SELECT ... FROM t1 EXCEPT SELECT ... FROM t2 ORDER BY .. COLLATE ...
  125551. **
  125552. ** These are rewritten as a subquery:
  125553. **
  125554. ** SELECT * FROM (SELECT ... FROM t1 EXCEPT SELECT ... FROM t2)
  125555. ** ORDER BY ... COLLATE ...
  125556. **
  125557. ** This transformation is necessary because the multiSelectOrderBy() routine
  125558. ** above that generates the code for a compound SELECT with an ORDER BY clause
  125559. ** uses a merge algorithm that requires the same collating sequence on the
  125560. ** result columns as on the ORDER BY clause. See ticket
  125561. ** http://www.sqlite.org/src/info/6709574d2a
  125562. **
  125563. ** This transformation is only needed for EXCEPT, INTERSECT, and UNION.
  125564. ** The UNION ALL operator works fine with multiSelectOrderBy() even when
  125565. ** there are COLLATE terms in the ORDER BY.
  125566. */
  125567. static int convertCompoundSelectToSubquery(Walker *pWalker, Select *p){
  125568. int i;
  125569. Select *pNew;
  125570. Select *pX;
  125571. sqlite3 *db;
  125572. struct ExprList_item *a;
  125573. SrcList *pNewSrc;
  125574. Parse *pParse;
  125575. Token dummy;
  125576. if( p->pPrior==0 ) return WRC_Continue;
  125577. if( p->pOrderBy==0 ) return WRC_Continue;
  125578. for(pX=p; pX && (pX->op==TK_ALL || pX->op==TK_SELECT); pX=pX->pPrior){}
  125579. if( pX==0 ) return WRC_Continue;
  125580. a = p->pOrderBy->a;
  125581. for(i=p->pOrderBy->nExpr-1; i>=0; i--){
  125582. if( a[i].pExpr->flags & EP_Collate ) break;
  125583. }
  125584. if( i<0 ) return WRC_Continue;
  125585. /* If we reach this point, that means the transformation is required. */
  125586. pParse = pWalker->pParse;
  125587. db = pParse->db;
  125588. pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
  125589. if( pNew==0 ) return WRC_Abort;
  125590. memset(&dummy, 0, sizeof(dummy));
  125591. pNewSrc = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&dummy,pNew,0,0);
  125592. if( pNewSrc==0 ) return WRC_Abort;
  125593. *pNew = *p;
  125594. p->pSrc = pNewSrc;
  125595. p->pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ASTERISK, 0));
  125596. p->op = TK_SELECT;
  125597. p->pWhere = 0;
  125598. pNew->pGroupBy = 0;
  125599. pNew->pHaving = 0;
  125600. pNew->pOrderBy = 0;
  125601. p->pPrior = 0;
  125602. p->pNext = 0;
  125603. p->pWith = 0;
  125604. #ifndef SQLITE_OMIT_WINDOWFUNC
  125605. p->pWinDefn = 0;
  125606. #endif
  125607. p->selFlags &= ~SF_Compound;
  125608. assert( (p->selFlags & SF_Converted)==0 );
  125609. p->selFlags |= SF_Converted;
  125610. assert( pNew->pPrior!=0 );
  125611. pNew->pPrior->pNext = pNew;
  125612. pNew->pLimit = 0;
  125613. return WRC_Continue;
  125614. }
  125615. /*
  125616. ** Check to see if the FROM clause term pFrom has table-valued function
  125617. ** arguments. If it does, leave an error message in pParse and return
  125618. ** non-zero, since pFrom is not allowed to be a table-valued function.
  125619. */
  125620. static int cannotBeFunction(Parse *pParse, struct SrcList_item *pFrom){
  125621. if( pFrom->fg.isTabFunc ){
  125622. sqlite3ErrorMsg(pParse, "'%s' is not a function", pFrom->zName);
  125623. return 1;
  125624. }
  125625. return 0;
  125626. }
  125627. #ifndef SQLITE_OMIT_CTE
  125628. /*
  125629. ** Argument pWith (which may be NULL) points to a linked list of nested
  125630. ** WITH contexts, from inner to outermost. If the table identified by
  125631. ** FROM clause element pItem is really a common-table-expression (CTE)
  125632. ** then return a pointer to the CTE definition for that table. Otherwise
  125633. ** return NULL.
  125634. **
  125635. ** If a non-NULL value is returned, set *ppContext to point to the With
  125636. ** object that the returned CTE belongs to.
  125637. */
  125638. static struct Cte *searchWith(
  125639. With *pWith, /* Current innermost WITH clause */
  125640. struct SrcList_item *pItem, /* FROM clause element to resolve */
  125641. With **ppContext /* OUT: WITH clause return value belongs to */
  125642. ){
  125643. const char *zName;
  125644. if( pItem->zDatabase==0 && (zName = pItem->zName)!=0 ){
  125645. With *p;
  125646. for(p=pWith; p; p=p->pOuter){
  125647. int i;
  125648. for(i=0; i<p->nCte; i++){
  125649. if( sqlite3StrICmp(zName, p->a[i].zName)==0 ){
  125650. *ppContext = p;
  125651. return &p->a[i];
  125652. }
  125653. }
  125654. }
  125655. }
  125656. return 0;
  125657. }
  125658. /* The code generator maintains a stack of active WITH clauses
  125659. ** with the inner-most WITH clause being at the top of the stack.
  125660. **
  125661. ** This routine pushes the WITH clause passed as the second argument
  125662. ** onto the top of the stack. If argument bFree is true, then this
  125663. ** WITH clause will never be popped from the stack. In this case it
  125664. ** should be freed along with the Parse object. In other cases, when
  125665. ** bFree==0, the With object will be freed along with the SELECT
  125666. ** statement with which it is associated.
  125667. */
  125668. SQLITE_PRIVATE void sqlite3WithPush(Parse *pParse, With *pWith, u8 bFree){
  125669. assert( bFree==0 || (pParse->pWith==0 && pParse->pWithToFree==0) );
  125670. if( pWith ){
  125671. assert( pParse->pWith!=pWith );
  125672. pWith->pOuter = pParse->pWith;
  125673. pParse->pWith = pWith;
  125674. if( bFree ) pParse->pWithToFree = pWith;
  125675. }
  125676. }
  125677. /*
  125678. ** This function checks if argument pFrom refers to a CTE declared by
  125679. ** a WITH clause on the stack currently maintained by the parser. And,
  125680. ** if currently processing a CTE expression, if it is a recursive
  125681. ** reference to the current CTE.
  125682. **
  125683. ** If pFrom falls into either of the two categories above, pFrom->pTab
  125684. ** and other fields are populated accordingly. The caller should check
  125685. ** (pFrom->pTab!=0) to determine whether or not a successful match
  125686. ** was found.
  125687. **
  125688. ** Whether or not a match is found, SQLITE_OK is returned if no error
  125689. ** occurs. If an error does occur, an error message is stored in the
  125690. ** parser and some error code other than SQLITE_OK returned.
  125691. */
  125692. static int withExpand(
  125693. Walker *pWalker,
  125694. struct SrcList_item *pFrom
  125695. ){
  125696. Parse *pParse = pWalker->pParse;
  125697. sqlite3 *db = pParse->db;
  125698. struct Cte *pCte; /* Matched CTE (or NULL if no match) */
  125699. With *pWith; /* WITH clause that pCte belongs to */
  125700. assert( pFrom->pTab==0 );
  125701. if( pParse->nErr ){
  125702. return SQLITE_ERROR;
  125703. }
  125704. pCte = searchWith(pParse->pWith, pFrom, &pWith);
  125705. if( pCte ){
  125706. Table *pTab;
  125707. ExprList *pEList;
  125708. Select *pSel;
  125709. Select *pLeft; /* Left-most SELECT statement */
  125710. int bMayRecursive; /* True if compound joined by UNION [ALL] */
  125711. With *pSavedWith; /* Initial value of pParse->pWith */
  125712. /* If pCte->zCteErr is non-NULL at this point, then this is an illegal
  125713. ** recursive reference to CTE pCte. Leave an error in pParse and return
  125714. ** early. If pCte->zCteErr is NULL, then this is not a recursive reference.
  125715. ** In this case, proceed. */
  125716. if( pCte->zCteErr ){
  125717. sqlite3ErrorMsg(pParse, pCte->zCteErr, pCte->zName);
  125718. return SQLITE_ERROR;
  125719. }
  125720. if( cannotBeFunction(pParse, pFrom) ) return SQLITE_ERROR;
  125721. assert( pFrom->pTab==0 );
  125722. pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
  125723. if( pTab==0 ) return WRC_Abort;
  125724. pTab->nTabRef = 1;
  125725. pTab->zName = sqlite3DbStrDup(db, pCte->zName);
  125726. pTab->iPKey = -1;
  125727. pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
  125728. pTab->tabFlags |= TF_Ephemeral | TF_NoVisibleRowid;
  125729. pFrom->pSelect = sqlite3SelectDup(db, pCte->pSelect, 0);
  125730. if( db->mallocFailed ) return SQLITE_NOMEM_BKPT;
  125731. assert( pFrom->pSelect );
  125732. /* Check if this is a recursive CTE. */
  125733. pSel = pFrom->pSelect;
  125734. bMayRecursive = ( pSel->op==TK_ALL || pSel->op==TK_UNION );
  125735. if( bMayRecursive ){
  125736. int i;
  125737. SrcList *pSrc = pFrom->pSelect->pSrc;
  125738. for(i=0; i<pSrc->nSrc; i++){
  125739. struct SrcList_item *pItem = &pSrc->a[i];
  125740. if( pItem->zDatabase==0
  125741. && pItem->zName!=0
  125742. && 0==sqlite3StrICmp(pItem->zName, pCte->zName)
  125743. ){
  125744. pItem->pTab = pTab;
  125745. pItem->fg.isRecursive = 1;
  125746. pTab->nTabRef++;
  125747. pSel->selFlags |= SF_Recursive;
  125748. }
  125749. }
  125750. }
  125751. /* Only one recursive reference is permitted. */
  125752. if( pTab->nTabRef>2 ){
  125753. sqlite3ErrorMsg(
  125754. pParse, "multiple references to recursive table: %s", pCte->zName
  125755. );
  125756. return SQLITE_ERROR;
  125757. }
  125758. assert( pTab->nTabRef==1 ||
  125759. ((pSel->selFlags&SF_Recursive) && pTab->nTabRef==2 ));
  125760. pCte->zCteErr = "circular reference: %s";
  125761. pSavedWith = pParse->pWith;
  125762. pParse->pWith = pWith;
  125763. if( bMayRecursive ){
  125764. Select *pPrior = pSel->pPrior;
  125765. assert( pPrior->pWith==0 );
  125766. pPrior->pWith = pSel->pWith;
  125767. sqlite3WalkSelect(pWalker, pPrior);
  125768. pPrior->pWith = 0;
  125769. }else{
  125770. sqlite3WalkSelect(pWalker, pSel);
  125771. }
  125772. pParse->pWith = pWith;
  125773. for(pLeft=pSel; pLeft->pPrior; pLeft=pLeft->pPrior);
  125774. pEList = pLeft->pEList;
  125775. if( pCte->pCols ){
  125776. if( pEList && pEList->nExpr!=pCte->pCols->nExpr ){
  125777. sqlite3ErrorMsg(pParse, "table %s has %d values for %d columns",
  125778. pCte->zName, pEList->nExpr, pCte->pCols->nExpr
  125779. );
  125780. pParse->pWith = pSavedWith;
  125781. return SQLITE_ERROR;
  125782. }
  125783. pEList = pCte->pCols;
  125784. }
  125785. sqlite3ColumnsFromExprList(pParse, pEList, &pTab->nCol, &pTab->aCol);
  125786. if( bMayRecursive ){
  125787. if( pSel->selFlags & SF_Recursive ){
  125788. pCte->zCteErr = "multiple recursive references: %s";
  125789. }else{
  125790. pCte->zCteErr = "recursive reference in a subquery: %s";
  125791. }
  125792. sqlite3WalkSelect(pWalker, pSel);
  125793. }
  125794. pCte->zCteErr = 0;
  125795. pParse->pWith = pSavedWith;
  125796. }
  125797. return SQLITE_OK;
  125798. }
  125799. #endif
  125800. #ifndef SQLITE_OMIT_CTE
  125801. /*
  125802. ** If the SELECT passed as the second argument has an associated WITH
  125803. ** clause, pop it from the stack stored as part of the Parse object.
  125804. **
  125805. ** This function is used as the xSelectCallback2() callback by
  125806. ** sqlite3SelectExpand() when walking a SELECT tree to resolve table
  125807. ** names and other FROM clause elements.
  125808. */
  125809. static void selectPopWith(Walker *pWalker, Select *p){
  125810. Parse *pParse = pWalker->pParse;
  125811. if( OK_IF_ALWAYS_TRUE(pParse->pWith) && p->pPrior==0 ){
  125812. With *pWith = findRightmost(p)->pWith;
  125813. if( pWith!=0 ){
  125814. assert( pParse->pWith==pWith || pParse->nErr );
  125815. pParse->pWith = pWith->pOuter;
  125816. }
  125817. }
  125818. }
  125819. #else
  125820. #define selectPopWith 0
  125821. #endif
  125822. /*
  125823. ** The SrcList_item structure passed as the second argument represents a
  125824. ** sub-query in the FROM clause of a SELECT statement. This function
  125825. ** allocates and populates the SrcList_item.pTab object. If successful,
  125826. ** SQLITE_OK is returned. Otherwise, if an OOM error is encountered,
  125827. ** SQLITE_NOMEM.
  125828. */
  125829. SQLITE_PRIVATE int sqlite3ExpandSubquery(Parse *pParse, struct SrcList_item *pFrom){
  125830. Select *pSel = pFrom->pSelect;
  125831. Table *pTab;
  125832. assert( pSel );
  125833. pFrom->pTab = pTab = sqlite3DbMallocZero(pParse->db, sizeof(Table));
  125834. if( pTab==0 ) return SQLITE_NOMEM;
  125835. pTab->nTabRef = 1;
  125836. if( pFrom->zAlias ){
  125837. pTab->zName = sqlite3DbStrDup(pParse->db, pFrom->zAlias);
  125838. }else{
  125839. pTab->zName = sqlite3MPrintf(pParse->db, "subquery_%u", pSel->selId);
  125840. }
  125841. while( pSel->pPrior ){ pSel = pSel->pPrior; }
  125842. sqlite3ColumnsFromExprList(pParse, pSel->pEList,&pTab->nCol,&pTab->aCol);
  125843. pTab->iPKey = -1;
  125844. pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
  125845. pTab->tabFlags |= TF_Ephemeral;
  125846. return pParse->nErr ? SQLITE_ERROR : SQLITE_OK;
  125847. }
  125848. /*
  125849. ** This routine is a Walker callback for "expanding" a SELECT statement.
  125850. ** "Expanding" means to do the following:
  125851. **
  125852. ** (1) Make sure VDBE cursor numbers have been assigned to every
  125853. ** element of the FROM clause.
  125854. **
  125855. ** (2) Fill in the pTabList->a[].pTab fields in the SrcList that
  125856. ** defines FROM clause. When views appear in the FROM clause,
  125857. ** fill pTabList->a[].pSelect with a copy of the SELECT statement
  125858. ** that implements the view. A copy is made of the view's SELECT
  125859. ** statement so that we can freely modify or delete that statement
  125860. ** without worrying about messing up the persistent representation
  125861. ** of the view.
  125862. **
  125863. ** (3) Add terms to the WHERE clause to accommodate the NATURAL keyword
  125864. ** on joins and the ON and USING clause of joins.
  125865. **
  125866. ** (4) Scan the list of columns in the result set (pEList) looking
  125867. ** for instances of the "*" operator or the TABLE.* operator.
  125868. ** If found, expand each "*" to be every column in every table
  125869. ** and TABLE.* to be every column in TABLE.
  125870. **
  125871. */
  125872. static int selectExpander(Walker *pWalker, Select *p){
  125873. Parse *pParse = pWalker->pParse;
  125874. int i, j, k;
  125875. SrcList *pTabList;
  125876. ExprList *pEList;
  125877. struct SrcList_item *pFrom;
  125878. sqlite3 *db = pParse->db;
  125879. Expr *pE, *pRight, *pExpr;
  125880. u16 selFlags = p->selFlags;
  125881. u32 elistFlags = 0;
  125882. p->selFlags |= SF_Expanded;
  125883. if( db->mallocFailed ){
  125884. return WRC_Abort;
  125885. }
  125886. assert( p->pSrc!=0 );
  125887. if( (selFlags & SF_Expanded)!=0 ){
  125888. return WRC_Prune;
  125889. }
  125890. if( pWalker->eCode ){
  125891. /* Renumber selId because it has been copied from a view */
  125892. p->selId = ++pParse->nSelect;
  125893. }
  125894. pTabList = p->pSrc;
  125895. pEList = p->pEList;
  125896. sqlite3WithPush(pParse, p->pWith, 0);
  125897. /* Make sure cursor numbers have been assigned to all entries in
  125898. ** the FROM clause of the SELECT statement.
  125899. */
  125900. sqlite3SrcListAssignCursors(pParse, pTabList);
  125901. /* Look up every table named in the FROM clause of the select. If
  125902. ** an entry of the FROM clause is a subquery instead of a table or view,
  125903. ** then create a transient table structure to describe the subquery.
  125904. */
  125905. for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
  125906. Table *pTab;
  125907. assert( pFrom->fg.isRecursive==0 || pFrom->pTab!=0 );
  125908. if( pFrom->fg.isRecursive ) continue;
  125909. assert( pFrom->pTab==0 );
  125910. #ifndef SQLITE_OMIT_CTE
  125911. if( withExpand(pWalker, pFrom) ) return WRC_Abort;
  125912. if( pFrom->pTab ) {} else
  125913. #endif
  125914. if( pFrom->zName==0 ){
  125915. #ifndef SQLITE_OMIT_SUBQUERY
  125916. Select *pSel = pFrom->pSelect;
  125917. /* A sub-query in the FROM clause of a SELECT */
  125918. assert( pSel!=0 );
  125919. assert( pFrom->pTab==0 );
  125920. if( sqlite3WalkSelect(pWalker, pSel) ) return WRC_Abort;
  125921. if( sqlite3ExpandSubquery(pParse, pFrom) ) return WRC_Abort;
  125922. #endif
  125923. }else{
  125924. /* An ordinary table or view name in the FROM clause */
  125925. assert( pFrom->pTab==0 );
  125926. pFrom->pTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom);
  125927. if( pTab==0 ) return WRC_Abort;
  125928. if( pTab->nTabRef>=0xffff ){
  125929. sqlite3ErrorMsg(pParse, "too many references to \"%s\": max 65535",
  125930. pTab->zName);
  125931. pFrom->pTab = 0;
  125932. return WRC_Abort;
  125933. }
  125934. pTab->nTabRef++;
  125935. if( !IsVirtual(pTab) && cannotBeFunction(pParse, pFrom) ){
  125936. return WRC_Abort;
  125937. }
  125938. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
  125939. if( IsVirtual(pTab) || pTab->pSelect ){
  125940. i16 nCol;
  125941. u8 eCodeOrig = pWalker->eCode;
  125942. if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
  125943. assert( pFrom->pSelect==0 );
  125944. if( pTab->pSelect && (db->flags & SQLITE_EnableView)==0 ){
  125945. sqlite3ErrorMsg(pParse, "access to view \"%s\" prohibited",
  125946. pTab->zName);
  125947. }
  125948. #ifndef SQLITE_OMIT_VIRTUALTABLE
  125949. if( IsVirtual(pTab)
  125950. && pFrom->fg.fromDDL
  125951. && ALWAYS(pTab->pVTable!=0)
  125952. && pTab->pVTable->eVtabRisk > ((db->flags & SQLITE_TrustedSchema)!=0)
  125953. ){
  125954. sqlite3ErrorMsg(pParse, "unsafe use of virtual table \"%s\"",
  125955. pTab->zName);
  125956. }
  125957. #endif
  125958. pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
  125959. nCol = pTab->nCol;
  125960. pTab->nCol = -1;
  125961. pWalker->eCode = 1; /* Turn on Select.selId renumbering */
  125962. sqlite3WalkSelect(pWalker, pFrom->pSelect);
  125963. pWalker->eCode = eCodeOrig;
  125964. pTab->nCol = nCol;
  125965. }
  125966. #endif
  125967. }
  125968. /* Locate the index named by the INDEXED BY clause, if any. */
  125969. if( sqlite3IndexedByLookup(pParse, pFrom) ){
  125970. return WRC_Abort;
  125971. }
  125972. }
  125973. /* Process NATURAL keywords, and ON and USING clauses of joins.
  125974. */
  125975. if( pParse->nErr || db->mallocFailed || sqliteProcessJoin(pParse, p) ){
  125976. return WRC_Abort;
  125977. }
  125978. /* For every "*" that occurs in the column list, insert the names of
  125979. ** all columns in all tables. And for every TABLE.* insert the names
  125980. ** of all columns in TABLE. The parser inserted a special expression
  125981. ** with the TK_ASTERISK operator for each "*" that it found in the column
  125982. ** list. The following code just has to locate the TK_ASTERISK
  125983. ** expressions and expand each one to the list of all columns in
  125984. ** all tables.
  125985. **
  125986. ** The first loop just checks to see if there are any "*" operators
  125987. ** that need expanding.
  125988. */
  125989. for(k=0; k<pEList->nExpr; k++){
  125990. pE = pEList->a[k].pExpr;
  125991. if( pE->op==TK_ASTERISK ) break;
  125992. assert( pE->op!=TK_DOT || pE->pRight!=0 );
  125993. assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
  125994. if( pE->op==TK_DOT && pE->pRight->op==TK_ASTERISK ) break;
  125995. elistFlags |= pE->flags;
  125996. }
  125997. if( k<pEList->nExpr ){
  125998. /*
  125999. ** If we get here it means the result set contains one or more "*"
  126000. ** operators that need to be expanded. Loop through each expression
  126001. ** in the result set and expand them one by one.
  126002. */
  126003. struct ExprList_item *a = pEList->a;
  126004. ExprList *pNew = 0;
  126005. int flags = pParse->db->flags;
  126006. int longNames = (flags & SQLITE_FullColNames)!=0
  126007. && (flags & SQLITE_ShortColNames)==0;
  126008. for(k=0; k<pEList->nExpr; k++){
  126009. pE = a[k].pExpr;
  126010. elistFlags |= pE->flags;
  126011. pRight = pE->pRight;
  126012. assert( pE->op!=TK_DOT || pRight!=0 );
  126013. if( pE->op!=TK_ASTERISK
  126014. && (pE->op!=TK_DOT || pRight->op!=TK_ASTERISK)
  126015. ){
  126016. /* This particular expression does not need to be expanded.
  126017. */
  126018. pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
  126019. if( pNew ){
  126020. pNew->a[pNew->nExpr-1].zEName = a[k].zEName;
  126021. pNew->a[pNew->nExpr-1].eEName = a[k].eEName;
  126022. a[k].zEName = 0;
  126023. }
  126024. a[k].pExpr = 0;
  126025. }else{
  126026. /* This expression is a "*" or a "TABLE.*" and needs to be
  126027. ** expanded. */
  126028. int tableSeen = 0; /* Set to 1 when TABLE matches */
  126029. char *zTName = 0; /* text of name of TABLE */
  126030. if( pE->op==TK_DOT ){
  126031. assert( pE->pLeft!=0 );
  126032. assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
  126033. zTName = pE->pLeft->u.zToken;
  126034. }
  126035. for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
  126036. Table *pTab = pFrom->pTab;
  126037. Select *pSub = pFrom->pSelect;
  126038. char *zTabName = pFrom->zAlias;
  126039. const char *zSchemaName = 0;
  126040. int iDb;
  126041. if( zTabName==0 ){
  126042. zTabName = pTab->zName;
  126043. }
  126044. if( db->mallocFailed ) break;
  126045. if( pSub==0 || (pSub->selFlags & SF_NestedFrom)==0 ){
  126046. pSub = 0;
  126047. if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
  126048. continue;
  126049. }
  126050. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  126051. zSchemaName = iDb>=0 ? db->aDb[iDb].zDbSName : "*";
  126052. }
  126053. for(j=0; j<pTab->nCol; j++){
  126054. char *zName = pTab->aCol[j].zName;
  126055. char *zColname; /* The computed column name */
  126056. char *zToFree; /* Malloced string that needs to be freed */
  126057. Token sColname; /* Computed column name as a token */
  126058. assert( zName );
  126059. if( zTName && pSub
  126060. && sqlite3MatchEName(&pSub->pEList->a[j], 0, zTName, 0)==0
  126061. ){
  126062. continue;
  126063. }
  126064. /* If a column is marked as 'hidden', omit it from the expanded
  126065. ** result-set list unless the SELECT has the SF_IncludeHidden
  126066. ** bit set.
  126067. */
  126068. if( (p->selFlags & SF_IncludeHidden)==0
  126069. && IsHiddenColumn(&pTab->aCol[j])
  126070. ){
  126071. continue;
  126072. }
  126073. tableSeen = 1;
  126074. if( i>0 && zTName==0 ){
  126075. if( (pFrom->fg.jointype & JT_NATURAL)!=0
  126076. && tableAndColumnIndex(pTabList, i, zName, 0, 0, 1)
  126077. ){
  126078. /* In a NATURAL join, omit the join columns from the
  126079. ** table to the right of the join */
  126080. continue;
  126081. }
  126082. if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){
  126083. /* In a join with a USING clause, omit columns in the
  126084. ** using clause from the table on the right. */
  126085. continue;
  126086. }
  126087. }
  126088. pRight = sqlite3Expr(db, TK_ID, zName);
  126089. zColname = zName;
  126090. zToFree = 0;
  126091. if( longNames || pTabList->nSrc>1 ){
  126092. Expr *pLeft;
  126093. pLeft = sqlite3Expr(db, TK_ID, zTabName);
  126094. pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight);
  126095. if( zSchemaName ){
  126096. pLeft = sqlite3Expr(db, TK_ID, zSchemaName);
  126097. pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pExpr);
  126098. }
  126099. if( longNames ){
  126100. zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
  126101. zToFree = zColname;
  126102. }
  126103. }else{
  126104. pExpr = pRight;
  126105. }
  126106. pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
  126107. sqlite3TokenInit(&sColname, zColname);
  126108. sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
  126109. if( pNew && (p->selFlags & SF_NestedFrom)!=0 && !IN_RENAME_OBJECT ){
  126110. struct ExprList_item *pX = &pNew->a[pNew->nExpr-1];
  126111. sqlite3DbFree(db, pX->zEName);
  126112. if( pSub ){
  126113. pX->zEName = sqlite3DbStrDup(db, pSub->pEList->a[j].zEName);
  126114. testcase( pX->zEName==0 );
  126115. }else{
  126116. pX->zEName = sqlite3MPrintf(db, "%s.%s.%s",
  126117. zSchemaName, zTabName, zColname);
  126118. testcase( pX->zEName==0 );
  126119. }
  126120. pX->eEName = ENAME_TAB;
  126121. }
  126122. sqlite3DbFree(db, zToFree);
  126123. }
  126124. }
  126125. if( !tableSeen ){
  126126. if( zTName ){
  126127. sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
  126128. }else{
  126129. sqlite3ErrorMsg(pParse, "no tables specified");
  126130. }
  126131. }
  126132. }
  126133. }
  126134. sqlite3ExprListDelete(db, pEList);
  126135. p->pEList = pNew;
  126136. }
  126137. if( p->pEList ){
  126138. if( p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  126139. sqlite3ErrorMsg(pParse, "too many columns in result set");
  126140. return WRC_Abort;
  126141. }
  126142. if( (elistFlags & (EP_HasFunc|EP_Subquery))!=0 ){
  126143. p->selFlags |= SF_ComplexResult;
  126144. }
  126145. }
  126146. return WRC_Continue;
  126147. }
  126148. #if SQLITE_DEBUG
  126149. /*
  126150. ** Always assert. This xSelectCallback2 implementation proves that the
  126151. ** xSelectCallback2 is never invoked.
  126152. */
  126153. SQLITE_PRIVATE void sqlite3SelectWalkAssert2(Walker *NotUsed, Select *NotUsed2){
  126154. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  126155. assert( 0 );
  126156. }
  126157. #endif
  126158. /*
  126159. ** This routine "expands" a SELECT statement and all of its subqueries.
  126160. ** For additional information on what it means to "expand" a SELECT
  126161. ** statement, see the comment on the selectExpand worker callback above.
  126162. **
  126163. ** Expanding a SELECT statement is the first step in processing a
  126164. ** SELECT statement. The SELECT statement must be expanded before
  126165. ** name resolution is performed.
  126166. **
  126167. ** If anything goes wrong, an error message is written into pParse.
  126168. ** The calling function can detect the problem by looking at pParse->nErr
  126169. ** and/or pParse->db->mallocFailed.
  126170. */
  126171. static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
  126172. Walker w;
  126173. w.xExprCallback = sqlite3ExprWalkNoop;
  126174. w.pParse = pParse;
  126175. if( OK_IF_ALWAYS_TRUE(pParse->hasCompound) ){
  126176. w.xSelectCallback = convertCompoundSelectToSubquery;
  126177. w.xSelectCallback2 = 0;
  126178. sqlite3WalkSelect(&w, pSelect);
  126179. }
  126180. w.xSelectCallback = selectExpander;
  126181. w.xSelectCallback2 = selectPopWith;
  126182. w.eCode = 0;
  126183. sqlite3WalkSelect(&w, pSelect);
  126184. }
  126185. #ifndef SQLITE_OMIT_SUBQUERY
  126186. /*
  126187. ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
  126188. ** interface.
  126189. **
  126190. ** For each FROM-clause subquery, add Column.zType and Column.zColl
  126191. ** information to the Table structure that represents the result set
  126192. ** of that subquery.
  126193. **
  126194. ** The Table structure that represents the result set was constructed
  126195. ** by selectExpander() but the type and collation information was omitted
  126196. ** at that point because identifiers had not yet been resolved. This
  126197. ** routine is called after identifier resolution.
  126198. */
  126199. static void selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
  126200. Parse *pParse;
  126201. int i;
  126202. SrcList *pTabList;
  126203. struct SrcList_item *pFrom;
  126204. assert( p->selFlags & SF_Resolved );
  126205. if( p->selFlags & SF_HasTypeInfo ) return;
  126206. p->selFlags |= SF_HasTypeInfo;
  126207. pParse = pWalker->pParse;
  126208. pTabList = p->pSrc;
  126209. for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
  126210. Table *pTab = pFrom->pTab;
  126211. assert( pTab!=0 );
  126212. if( (pTab->tabFlags & TF_Ephemeral)!=0 ){
  126213. /* A sub-query in the FROM clause of a SELECT */
  126214. Select *pSel = pFrom->pSelect;
  126215. if( pSel ){
  126216. while( pSel->pPrior ) pSel = pSel->pPrior;
  126217. sqlite3SelectAddColumnTypeAndCollation(pParse, pTab, pSel,
  126218. SQLITE_AFF_NONE);
  126219. }
  126220. }
  126221. }
  126222. }
  126223. #endif
  126224. /*
  126225. ** This routine adds datatype and collating sequence information to
  126226. ** the Table structures of all FROM-clause subqueries in a
  126227. ** SELECT statement.
  126228. **
  126229. ** Use this routine after name resolution.
  126230. */
  126231. static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
  126232. #ifndef SQLITE_OMIT_SUBQUERY
  126233. Walker w;
  126234. w.xSelectCallback = sqlite3SelectWalkNoop;
  126235. w.xSelectCallback2 = selectAddSubqueryTypeInfo;
  126236. w.xExprCallback = sqlite3ExprWalkNoop;
  126237. w.pParse = pParse;
  126238. sqlite3WalkSelect(&w, pSelect);
  126239. #endif
  126240. }
  126241. /*
  126242. ** This routine sets up a SELECT statement for processing. The
  126243. ** following is accomplished:
  126244. **
  126245. ** * VDBE Cursor numbers are assigned to all FROM-clause terms.
  126246. ** * Ephemeral Table objects are created for all FROM-clause subqueries.
  126247. ** * ON and USING clauses are shifted into WHERE statements
  126248. ** * Wildcards "*" and "TABLE.*" in result sets are expanded.
  126249. ** * Identifiers in expression are matched to tables.
  126250. **
  126251. ** This routine acts recursively on all subqueries within the SELECT.
  126252. */
  126253. SQLITE_PRIVATE void sqlite3SelectPrep(
  126254. Parse *pParse, /* The parser context */
  126255. Select *p, /* The SELECT statement being coded. */
  126256. NameContext *pOuterNC /* Name context for container */
  126257. ){
  126258. assert( p!=0 || pParse->db->mallocFailed );
  126259. if( pParse->db->mallocFailed ) return;
  126260. if( p->selFlags & SF_HasTypeInfo ) return;
  126261. sqlite3SelectExpand(pParse, p);
  126262. if( pParse->nErr || pParse->db->mallocFailed ) return;
  126263. sqlite3ResolveSelectNames(pParse, p, pOuterNC);
  126264. if( pParse->nErr || pParse->db->mallocFailed ) return;
  126265. sqlite3SelectAddTypeInfo(pParse, p);
  126266. }
  126267. /*
  126268. ** Reset the aggregate accumulator.
  126269. **
  126270. ** The aggregate accumulator is a set of memory cells that hold
  126271. ** intermediate results while calculating an aggregate. This
  126272. ** routine generates code that stores NULLs in all of those memory
  126273. ** cells.
  126274. */
  126275. static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
  126276. Vdbe *v = pParse->pVdbe;
  126277. int i;
  126278. struct AggInfo_func *pFunc;
  126279. int nReg = pAggInfo->nFunc + pAggInfo->nColumn;
  126280. if( nReg==0 ) return;
  126281. if( pParse->nErr ) return;
  126282. #ifdef SQLITE_DEBUG
  126283. /* Verify that all AggInfo registers are within the range specified by
  126284. ** AggInfo.mnReg..AggInfo.mxReg */
  126285. assert( nReg==pAggInfo->mxReg-pAggInfo->mnReg+1 );
  126286. for(i=0; i<pAggInfo->nColumn; i++){
  126287. assert( pAggInfo->aCol[i].iMem>=pAggInfo->mnReg
  126288. && pAggInfo->aCol[i].iMem<=pAggInfo->mxReg );
  126289. }
  126290. for(i=0; i<pAggInfo->nFunc; i++){
  126291. assert( pAggInfo->aFunc[i].iMem>=pAggInfo->mnReg
  126292. && pAggInfo->aFunc[i].iMem<=pAggInfo->mxReg );
  126293. }
  126294. #endif
  126295. sqlite3VdbeAddOp3(v, OP_Null, 0, pAggInfo->mnReg, pAggInfo->mxReg);
  126296. for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
  126297. if( pFunc->iDistinct>=0 ){
  126298. Expr *pE = pFunc->pExpr;
  126299. assert( !ExprHasProperty(pE, EP_xIsSelect) );
  126300. if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
  126301. sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
  126302. "argument");
  126303. pFunc->iDistinct = -1;
  126304. }else{
  126305. KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pE->x.pList,0,0);
  126306. sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
  126307. (char*)pKeyInfo, P4_KEYINFO);
  126308. }
  126309. }
  126310. }
  126311. }
  126312. /*
  126313. ** Invoke the OP_AggFinalize opcode for every aggregate function
  126314. ** in the AggInfo structure.
  126315. */
  126316. static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
  126317. Vdbe *v = pParse->pVdbe;
  126318. int i;
  126319. struct AggInfo_func *pF;
  126320. for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
  126321. ExprList *pList = pF->pExpr->x.pList;
  126322. assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
  126323. sqlite3VdbeAddOp2(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0);
  126324. sqlite3VdbeAppendP4(v, pF->pFunc, P4_FUNCDEF);
  126325. }
  126326. }
  126327. /*
  126328. ** Update the accumulator memory cells for an aggregate based on
  126329. ** the current cursor position.
  126330. **
  126331. ** If regAcc is non-zero and there are no min() or max() aggregates
  126332. ** in pAggInfo, then only populate the pAggInfo->nAccumulator accumulator
  126333. ** registers if register regAcc contains 0. The caller will take care
  126334. ** of setting and clearing regAcc.
  126335. */
  126336. static void updateAccumulator(Parse *pParse, int regAcc, AggInfo *pAggInfo){
  126337. Vdbe *v = pParse->pVdbe;
  126338. int i;
  126339. int regHit = 0;
  126340. int addrHitTest = 0;
  126341. struct AggInfo_func *pF;
  126342. struct AggInfo_col *pC;
  126343. pAggInfo->directMode = 1;
  126344. for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
  126345. int nArg;
  126346. int addrNext = 0;
  126347. int regAgg;
  126348. ExprList *pList = pF->pExpr->x.pList;
  126349. assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
  126350. assert( !IsWindowFunc(pF->pExpr) );
  126351. if( ExprHasProperty(pF->pExpr, EP_WinFunc) ){
  126352. Expr *pFilter = pF->pExpr->y.pWin->pFilter;
  126353. if( pAggInfo->nAccumulator
  126354. && (pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL)
  126355. ){
  126356. if( regHit==0 ) regHit = ++pParse->nMem;
  126357. /* If this is the first row of the group (regAcc==0), clear the
  126358. ** "magnet" register regHit so that the accumulator registers
  126359. ** are populated if the FILTER clause jumps over the the
  126360. ** invocation of min() or max() altogether. Or, if this is not
  126361. ** the first row (regAcc==1), set the magnet register so that the
  126362. ** accumulators are not populated unless the min()/max() is invoked and
  126363. ** indicates that they should be. */
  126364. sqlite3VdbeAddOp2(v, OP_Copy, regAcc, regHit);
  126365. }
  126366. addrNext = sqlite3VdbeMakeLabel(pParse);
  126367. sqlite3ExprIfFalse(pParse, pFilter, addrNext, SQLITE_JUMPIFNULL);
  126368. }
  126369. if( pList ){
  126370. nArg = pList->nExpr;
  126371. regAgg = sqlite3GetTempRange(pParse, nArg);
  126372. sqlite3ExprCodeExprList(pParse, pList, regAgg, 0, SQLITE_ECEL_DUP);
  126373. }else{
  126374. nArg = 0;
  126375. regAgg = 0;
  126376. }
  126377. if( pF->iDistinct>=0 ){
  126378. if( addrNext==0 ){
  126379. addrNext = sqlite3VdbeMakeLabel(pParse);
  126380. }
  126381. testcase( nArg==0 ); /* Error condition */
  126382. testcase( nArg>1 ); /* Also an error */
  126383. codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
  126384. }
  126385. if( pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
  126386. CollSeq *pColl = 0;
  126387. struct ExprList_item *pItem;
  126388. int j;
  126389. assert( pList!=0 ); /* pList!=0 if pF->pFunc has NEEDCOLL */
  126390. for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
  126391. pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
  126392. }
  126393. if( !pColl ){
  126394. pColl = pParse->db->pDfltColl;
  126395. }
  126396. if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem;
  126397. sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0, (char *)pColl, P4_COLLSEQ);
  126398. }
  126399. sqlite3VdbeAddOp3(v, OP_AggStep, 0, regAgg, pF->iMem);
  126400. sqlite3VdbeAppendP4(v, pF->pFunc, P4_FUNCDEF);
  126401. sqlite3VdbeChangeP5(v, (u8)nArg);
  126402. sqlite3ReleaseTempRange(pParse, regAgg, nArg);
  126403. if( addrNext ){
  126404. sqlite3VdbeResolveLabel(v, addrNext);
  126405. }
  126406. }
  126407. if( regHit==0 && pAggInfo->nAccumulator ){
  126408. regHit = regAcc;
  126409. }
  126410. if( regHit ){
  126411. addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit); VdbeCoverage(v);
  126412. }
  126413. for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
  126414. sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
  126415. }
  126416. pAggInfo->directMode = 0;
  126417. if( addrHitTest ){
  126418. sqlite3VdbeJumpHereOrPopInst(v, addrHitTest);
  126419. }
  126420. }
  126421. /*
  126422. ** Add a single OP_Explain instruction to the VDBE to explain a simple
  126423. ** count(*) query ("SELECT count(*) FROM pTab").
  126424. */
  126425. #ifndef SQLITE_OMIT_EXPLAIN
  126426. static void explainSimpleCount(
  126427. Parse *pParse, /* Parse context */
  126428. Table *pTab, /* Table being queried */
  126429. Index *pIdx /* Index used to optimize scan, or NULL */
  126430. ){
  126431. if( pParse->explain==2 ){
  126432. int bCover = (pIdx!=0 && (HasRowid(pTab) || !IsPrimaryKeyIndex(pIdx)));
  126433. sqlite3VdbeExplain(pParse, 0, "SCAN TABLE %s%s%s",
  126434. pTab->zName,
  126435. bCover ? " USING COVERING INDEX " : "",
  126436. bCover ? pIdx->zName : ""
  126437. );
  126438. }
  126439. }
  126440. #else
  126441. # define explainSimpleCount(a,b,c)
  126442. #endif
  126443. /*
  126444. ** sqlite3WalkExpr() callback used by havingToWhere().
  126445. **
  126446. ** If the node passed to the callback is a TK_AND node, return
  126447. ** WRC_Continue to tell sqlite3WalkExpr() to iterate through child nodes.
  126448. **
  126449. ** Otherwise, return WRC_Prune. In this case, also check if the
  126450. ** sub-expression matches the criteria for being moved to the WHERE
  126451. ** clause. If so, add it to the WHERE clause and replace the sub-expression
  126452. ** within the HAVING expression with a constant "1".
  126453. */
  126454. static int havingToWhereExprCb(Walker *pWalker, Expr *pExpr){
  126455. if( pExpr->op!=TK_AND ){
  126456. Select *pS = pWalker->u.pSelect;
  126457. if( sqlite3ExprIsConstantOrGroupBy(pWalker->pParse, pExpr, pS->pGroupBy) ){
  126458. sqlite3 *db = pWalker->pParse->db;
  126459. Expr *pNew = sqlite3Expr(db, TK_INTEGER, "1");
  126460. if( pNew ){
  126461. Expr *pWhere = pS->pWhere;
  126462. SWAP(Expr, *pNew, *pExpr);
  126463. pNew = sqlite3ExprAnd(pWalker->pParse, pWhere, pNew);
  126464. pS->pWhere = pNew;
  126465. pWalker->eCode = 1;
  126466. }
  126467. }
  126468. return WRC_Prune;
  126469. }
  126470. return WRC_Continue;
  126471. }
  126472. /*
  126473. ** Transfer eligible terms from the HAVING clause of a query, which is
  126474. ** processed after grouping, to the WHERE clause, which is processed before
  126475. ** grouping. For example, the query:
  126476. **
  126477. ** SELECT * FROM <tables> WHERE a=? GROUP BY b HAVING b=? AND c=?
  126478. **
  126479. ** can be rewritten as:
  126480. **
  126481. ** SELECT * FROM <tables> WHERE a=? AND b=? GROUP BY b HAVING c=?
  126482. **
  126483. ** A term of the HAVING expression is eligible for transfer if it consists
  126484. ** entirely of constants and expressions that are also GROUP BY terms that
  126485. ** use the "BINARY" collation sequence.
  126486. */
  126487. static void havingToWhere(Parse *pParse, Select *p){
  126488. Walker sWalker;
  126489. memset(&sWalker, 0, sizeof(sWalker));
  126490. sWalker.pParse = pParse;
  126491. sWalker.xExprCallback = havingToWhereExprCb;
  126492. sWalker.u.pSelect = p;
  126493. sqlite3WalkExpr(&sWalker, p->pHaving);
  126494. #if SELECTTRACE_ENABLED
  126495. if( sWalker.eCode && (sqlite3SelectTrace & 0x100)!=0 ){
  126496. SELECTTRACE(0x100,pParse,p,("Move HAVING terms into WHERE:\n"));
  126497. sqlite3TreeViewSelect(0, p, 0);
  126498. }
  126499. #endif
  126500. }
  126501. /*
  126502. ** Check to see if the pThis entry of pTabList is a self-join of a prior view.
  126503. ** If it is, then return the SrcList_item for the prior view. If it is not,
  126504. ** then return 0.
  126505. */
  126506. static struct SrcList_item *isSelfJoinView(
  126507. SrcList *pTabList, /* Search for self-joins in this FROM clause */
  126508. struct SrcList_item *pThis /* Search for prior reference to this subquery */
  126509. ){
  126510. struct SrcList_item *pItem;
  126511. for(pItem = pTabList->a; pItem<pThis; pItem++){
  126512. Select *pS1;
  126513. if( pItem->pSelect==0 ) continue;
  126514. if( pItem->fg.viaCoroutine ) continue;
  126515. if( pItem->zName==0 ) continue;
  126516. assert( pItem->pTab!=0 );
  126517. assert( pThis->pTab!=0 );
  126518. if( pItem->pTab->pSchema!=pThis->pTab->pSchema ) continue;
  126519. if( sqlite3_stricmp(pItem->zName, pThis->zName)!=0 ) continue;
  126520. pS1 = pItem->pSelect;
  126521. if( pItem->pTab->pSchema==0 && pThis->pSelect->selId!=pS1->selId ){
  126522. /* The query flattener left two different CTE tables with identical
  126523. ** names in the same FROM clause. */
  126524. continue;
  126525. }
  126526. if( sqlite3ExprCompare(0, pThis->pSelect->pWhere, pS1->pWhere, -1)
  126527. || sqlite3ExprCompare(0, pThis->pSelect->pHaving, pS1->pHaving, -1)
  126528. ){
  126529. /* The view was modified by some other optimization such as
  126530. ** pushDownWhereTerms() */
  126531. continue;
  126532. }
  126533. return pItem;
  126534. }
  126535. return 0;
  126536. }
  126537. #ifdef SQLITE_COUNTOFVIEW_OPTIMIZATION
  126538. /*
  126539. ** Attempt to transform a query of the form
  126540. **
  126541. ** SELECT count(*) FROM (SELECT x FROM t1 UNION ALL SELECT y FROM t2)
  126542. **
  126543. ** Into this:
  126544. **
  126545. ** SELECT (SELECT count(*) FROM t1)+(SELECT count(*) FROM t2)
  126546. **
  126547. ** The transformation only works if all of the following are true:
  126548. **
  126549. ** * The subquery is a UNION ALL of two or more terms
  126550. ** * The subquery does not have a LIMIT clause
  126551. ** * There is no WHERE or GROUP BY or HAVING clauses on the subqueries
  126552. ** * The outer query is a simple count(*) with no WHERE clause or other
  126553. ** extraneous syntax.
  126554. **
  126555. ** Return TRUE if the optimization is undertaken.
  126556. */
  126557. static int countOfViewOptimization(Parse *pParse, Select *p){
  126558. Select *pSub, *pPrior;
  126559. Expr *pExpr;
  126560. Expr *pCount;
  126561. sqlite3 *db;
  126562. if( (p->selFlags & SF_Aggregate)==0 ) return 0; /* This is an aggregate */
  126563. if( p->pEList->nExpr!=1 ) return 0; /* Single result column */
  126564. if( p->pWhere ) return 0;
  126565. if( p->pGroupBy ) return 0;
  126566. pExpr = p->pEList->a[0].pExpr;
  126567. if( pExpr->op!=TK_AGG_FUNCTION ) return 0; /* Result is an aggregate */
  126568. if( sqlite3_stricmp(pExpr->u.zToken,"count") ) return 0; /* Is count() */
  126569. if( pExpr->x.pList!=0 ) return 0; /* Must be count(*) */
  126570. if( p->pSrc->nSrc!=1 ) return 0; /* One table in FROM */
  126571. pSub = p->pSrc->a[0].pSelect;
  126572. if( pSub==0 ) return 0; /* The FROM is a subquery */
  126573. if( pSub->pPrior==0 ) return 0; /* Must be a compound ry */
  126574. do{
  126575. if( pSub->op!=TK_ALL && pSub->pPrior ) return 0; /* Must be UNION ALL */
  126576. if( pSub->pWhere ) return 0; /* No WHERE clause */
  126577. if( pSub->pLimit ) return 0; /* No LIMIT clause */
  126578. if( pSub->selFlags & SF_Aggregate ) return 0; /* Not an aggregate */
  126579. pSub = pSub->pPrior; /* Repeat over compound */
  126580. }while( pSub );
  126581. /* If we reach this point then it is OK to perform the transformation */
  126582. db = pParse->db;
  126583. pCount = pExpr;
  126584. pExpr = 0;
  126585. pSub = p->pSrc->a[0].pSelect;
  126586. p->pSrc->a[0].pSelect = 0;
  126587. sqlite3SrcListDelete(db, p->pSrc);
  126588. p->pSrc = sqlite3DbMallocZero(pParse->db, sizeof(*p->pSrc));
  126589. while( pSub ){
  126590. Expr *pTerm;
  126591. pPrior = pSub->pPrior;
  126592. pSub->pPrior = 0;
  126593. pSub->pNext = 0;
  126594. pSub->selFlags |= SF_Aggregate;
  126595. pSub->selFlags &= ~SF_Compound;
  126596. pSub->nSelectRow = 0;
  126597. sqlite3ExprListDelete(db, pSub->pEList);
  126598. pTerm = pPrior ? sqlite3ExprDup(db, pCount, 0) : pCount;
  126599. pSub->pEList = sqlite3ExprListAppend(pParse, 0, pTerm);
  126600. pTerm = sqlite3PExpr(pParse, TK_SELECT, 0, 0);
  126601. sqlite3PExprAddSelect(pParse, pTerm, pSub);
  126602. if( pExpr==0 ){
  126603. pExpr = pTerm;
  126604. }else{
  126605. pExpr = sqlite3PExpr(pParse, TK_PLUS, pTerm, pExpr);
  126606. }
  126607. pSub = pPrior;
  126608. }
  126609. p->pEList->a[0].pExpr = pExpr;
  126610. p->selFlags &= ~SF_Aggregate;
  126611. #if SELECTTRACE_ENABLED
  126612. if( sqlite3SelectTrace & 0x400 ){
  126613. SELECTTRACE(0x400,pParse,p,("After count-of-view optimization:\n"));
  126614. sqlite3TreeViewSelect(0, p, 0);
  126615. }
  126616. #endif
  126617. return 1;
  126618. }
  126619. #endif /* SQLITE_COUNTOFVIEW_OPTIMIZATION */
  126620. /*
  126621. ** Generate code for the SELECT statement given in the p argument.
  126622. **
  126623. ** The results are returned according to the SelectDest structure.
  126624. ** See comments in sqliteInt.h for further information.
  126625. **
  126626. ** This routine returns the number of errors. If any errors are
  126627. ** encountered, then an appropriate error message is left in
  126628. ** pParse->zErrMsg.
  126629. **
  126630. ** This routine does NOT free the Select structure passed in. The
  126631. ** calling function needs to do that.
  126632. */
  126633. SQLITE_PRIVATE int sqlite3Select(
  126634. Parse *pParse, /* The parser context */
  126635. Select *p, /* The SELECT statement being coded. */
  126636. SelectDest *pDest /* What to do with the query results */
  126637. ){
  126638. int i, j; /* Loop counters */
  126639. WhereInfo *pWInfo; /* Return from sqlite3WhereBegin() */
  126640. Vdbe *v; /* The virtual machine under construction */
  126641. int isAgg; /* True for select lists like "count(*)" */
  126642. ExprList *pEList = 0; /* List of columns to extract. */
  126643. SrcList *pTabList; /* List of tables to select from */
  126644. Expr *pWhere; /* The WHERE clause. May be NULL */
  126645. ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */
  126646. Expr *pHaving; /* The HAVING clause. May be NULL */
  126647. int rc = 1; /* Value to return from this function */
  126648. DistinctCtx sDistinct; /* Info on how to code the DISTINCT keyword */
  126649. SortCtx sSort; /* Info on how to code the ORDER BY clause */
  126650. AggInfo sAggInfo; /* Information used by aggregate queries */
  126651. int iEnd; /* Address of the end of the query */
  126652. sqlite3 *db; /* The database connection */
  126653. ExprList *pMinMaxOrderBy = 0; /* Added ORDER BY for min/max queries */
  126654. u8 minMaxFlag; /* Flag for min/max queries */
  126655. db = pParse->db;
  126656. v = sqlite3GetVdbe(pParse);
  126657. if( p==0 || db->mallocFailed || pParse->nErr ){
  126658. return 1;
  126659. }
  126660. if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
  126661. memset(&sAggInfo, 0, sizeof(sAggInfo));
  126662. #if SELECTTRACE_ENABLED
  126663. SELECTTRACE(1,pParse,p, ("begin processing:\n", pParse->addrExplain));
  126664. if( sqlite3SelectTrace & 0x100 ){
  126665. sqlite3TreeViewSelect(0, p, 0);
  126666. }
  126667. #endif
  126668. assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistFifo );
  126669. assert( p->pOrderBy==0 || pDest->eDest!=SRT_Fifo );
  126670. assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistQueue );
  126671. assert( p->pOrderBy==0 || pDest->eDest!=SRT_Queue );
  126672. if( IgnorableOrderby(pDest) ){
  126673. assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union ||
  126674. pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard ||
  126675. pDest->eDest==SRT_Queue || pDest->eDest==SRT_DistFifo ||
  126676. pDest->eDest==SRT_DistQueue || pDest->eDest==SRT_Fifo);
  126677. /* If ORDER BY makes no difference in the output then neither does
  126678. ** DISTINCT so it can be removed too. */
  126679. sqlite3ExprListDelete(db, p->pOrderBy);
  126680. p->pOrderBy = 0;
  126681. p->selFlags &= ~SF_Distinct;
  126682. }
  126683. sqlite3SelectPrep(pParse, p, 0);
  126684. if( pParse->nErr || db->mallocFailed ){
  126685. goto select_end;
  126686. }
  126687. assert( p->pEList!=0 );
  126688. #if SELECTTRACE_ENABLED
  126689. if( sqlite3SelectTrace & 0x104 ){
  126690. SELECTTRACE(0x104,pParse,p, ("after name resolution:\n"));
  126691. sqlite3TreeViewSelect(0, p, 0);
  126692. }
  126693. #endif
  126694. if( pDest->eDest==SRT_Output ){
  126695. generateColumnNames(pParse, p);
  126696. }
  126697. #ifndef SQLITE_OMIT_WINDOWFUNC
  126698. rc = sqlite3WindowRewrite(pParse, p);
  126699. if( rc ){
  126700. assert( db->mallocFailed || pParse->nErr>0 );
  126701. goto select_end;
  126702. }
  126703. #if SELECTTRACE_ENABLED
  126704. if( p->pWin && (sqlite3SelectTrace & 0x108)!=0 ){
  126705. SELECTTRACE(0x104,pParse,p, ("after window rewrite:\n"));
  126706. sqlite3TreeViewSelect(0, p, 0);
  126707. }
  126708. #endif
  126709. #endif /* SQLITE_OMIT_WINDOWFUNC */
  126710. pTabList = p->pSrc;
  126711. isAgg = (p->selFlags & SF_Aggregate)!=0;
  126712. memset(&sSort, 0, sizeof(sSort));
  126713. sSort.pOrderBy = p->pOrderBy;
  126714. /* Try to various optimizations (flattening subqueries, and strength
  126715. ** reduction of join operators) in the FROM clause up into the main query
  126716. */
  126717. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  126718. for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
  126719. struct SrcList_item *pItem = &pTabList->a[i];
  126720. Select *pSub = pItem->pSelect;
  126721. Table *pTab = pItem->pTab;
  126722. /* Convert LEFT JOIN into JOIN if there are terms of the right table
  126723. ** of the LEFT JOIN used in the WHERE clause.
  126724. */
  126725. if( (pItem->fg.jointype & JT_LEFT)!=0
  126726. && sqlite3ExprImpliesNonNullRow(p->pWhere, pItem->iCursor)
  126727. && OptimizationEnabled(db, SQLITE_SimplifyJoin)
  126728. ){
  126729. SELECTTRACE(0x100,pParse,p,
  126730. ("LEFT-JOIN simplifies to JOIN on term %d\n",i));
  126731. pItem->fg.jointype &= ~(JT_LEFT|JT_OUTER);
  126732. unsetJoinExpr(p->pWhere, pItem->iCursor);
  126733. }
  126734. /* No futher action if this term of the FROM clause is no a subquery */
  126735. if( pSub==0 ) continue;
  126736. /* Catch mismatch in the declared columns of a view and the number of
  126737. ** columns in the SELECT on the RHS */
  126738. if( pTab->nCol!=pSub->pEList->nExpr ){
  126739. sqlite3ErrorMsg(pParse, "expected %d columns for '%s' but got %d",
  126740. pTab->nCol, pTab->zName, pSub->pEList->nExpr);
  126741. goto select_end;
  126742. }
  126743. /* Do not try to flatten an aggregate subquery.
  126744. **
  126745. ** Flattening an aggregate subquery is only possible if the outer query
  126746. ** is not a join. But if the outer query is not a join, then the subquery
  126747. ** will be implemented as a co-routine and there is no advantage to
  126748. ** flattening in that case.
  126749. */
  126750. if( (pSub->selFlags & SF_Aggregate)!=0 ) continue;
  126751. assert( pSub->pGroupBy==0 );
  126752. /* If the outer query contains a "complex" result set (that is,
  126753. ** if the result set of the outer query uses functions or subqueries)
  126754. ** and if the subquery contains an ORDER BY clause and if
  126755. ** it will be implemented as a co-routine, then do not flatten. This
  126756. ** restriction allows SQL constructs like this:
  126757. **
  126758. ** SELECT expensive_function(x)
  126759. ** FROM (SELECT x FROM tab ORDER BY y LIMIT 10);
  126760. **
  126761. ** The expensive_function() is only computed on the 10 rows that
  126762. ** are output, rather than every row of the table.
  126763. **
  126764. ** The requirement that the outer query have a complex result set
  126765. ** means that flattening does occur on simpler SQL constraints without
  126766. ** the expensive_function() like:
  126767. **
  126768. ** SELECT x FROM (SELECT x FROM tab ORDER BY y LIMIT 10);
  126769. */
  126770. if( pSub->pOrderBy!=0
  126771. && i==0
  126772. && (p->selFlags & SF_ComplexResult)!=0
  126773. && (pTabList->nSrc==1
  126774. || (pTabList->a[1].fg.jointype&(JT_LEFT|JT_CROSS))!=0)
  126775. ){
  126776. continue;
  126777. }
  126778. if( flattenSubquery(pParse, p, i, isAgg) ){
  126779. if( pParse->nErr ) goto select_end;
  126780. /* This subquery can be absorbed into its parent. */
  126781. i = -1;
  126782. }
  126783. pTabList = p->pSrc;
  126784. if( db->mallocFailed ) goto select_end;
  126785. if( !IgnorableOrderby(pDest) ){
  126786. sSort.pOrderBy = p->pOrderBy;
  126787. }
  126788. }
  126789. #endif
  126790. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  126791. /* Handle compound SELECT statements using the separate multiSelect()
  126792. ** procedure.
  126793. */
  126794. if( p->pPrior ){
  126795. rc = multiSelect(pParse, p, pDest);
  126796. #if SELECTTRACE_ENABLED
  126797. SELECTTRACE(0x1,pParse,p,("end compound-select processing\n"));
  126798. if( (sqlite3SelectTrace & 0x2000)!=0 && ExplainQueryPlanParent(pParse)==0 ){
  126799. sqlite3TreeViewSelect(0, p, 0);
  126800. }
  126801. #endif
  126802. if( p->pNext==0 ) ExplainQueryPlanPop(pParse);
  126803. return rc;
  126804. }
  126805. #endif
  126806. /* Do the WHERE-clause constant propagation optimization if this is
  126807. ** a join. No need to speed time on this operation for non-join queries
  126808. ** as the equivalent optimization will be handled by query planner in
  126809. ** sqlite3WhereBegin().
  126810. */
  126811. if( pTabList->nSrc>1
  126812. && OptimizationEnabled(db, SQLITE_PropagateConst)
  126813. && propagateConstants(pParse, p)
  126814. ){
  126815. #if SELECTTRACE_ENABLED
  126816. if( sqlite3SelectTrace & 0x100 ){
  126817. SELECTTRACE(0x100,pParse,p,("After constant propagation:\n"));
  126818. sqlite3TreeViewSelect(0, p, 0);
  126819. }
  126820. #endif
  126821. }else{
  126822. SELECTTRACE(0x100,pParse,p,("Constant propagation not helpful\n"));
  126823. }
  126824. #ifdef SQLITE_COUNTOFVIEW_OPTIMIZATION
  126825. if( OptimizationEnabled(db, SQLITE_QueryFlattener|SQLITE_CountOfView)
  126826. && countOfViewOptimization(pParse, p)
  126827. ){
  126828. if( db->mallocFailed ) goto select_end;
  126829. pEList = p->pEList;
  126830. pTabList = p->pSrc;
  126831. }
  126832. #endif
  126833. /* For each term in the FROM clause, do two things:
  126834. ** (1) Authorized unreferenced tables
  126835. ** (2) Generate code for all sub-queries
  126836. */
  126837. for(i=0; i<pTabList->nSrc; i++){
  126838. struct SrcList_item *pItem = &pTabList->a[i];
  126839. SelectDest dest;
  126840. Select *pSub;
  126841. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  126842. const char *zSavedAuthContext;
  126843. #endif
  126844. /* Issue SQLITE_READ authorizations with a fake column name for any
  126845. ** tables that are referenced but from which no values are extracted.
  126846. ** Examples of where these kinds of null SQLITE_READ authorizations
  126847. ** would occur:
  126848. **
  126849. ** SELECT count(*) FROM t1; -- SQLITE_READ t1.""
  126850. ** SELECT t1.* FROM t1, t2; -- SQLITE_READ t2.""
  126851. **
  126852. ** The fake column name is an empty string. It is possible for a table to
  126853. ** have a column named by the empty string, in which case there is no way to
  126854. ** distinguish between an unreferenced table and an actual reference to the
  126855. ** "" column. The original design was for the fake column name to be a NULL,
  126856. ** which would be unambiguous. But legacy authorization callbacks might
  126857. ** assume the column name is non-NULL and segfault. The use of an empty
  126858. ** string for the fake column name seems safer.
  126859. */
  126860. if( pItem->colUsed==0 && pItem->zName!=0 ){
  126861. sqlite3AuthCheck(pParse, SQLITE_READ, pItem->zName, "", pItem->zDatabase);
  126862. }
  126863. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  126864. /* Generate code for all sub-queries in the FROM clause
  126865. */
  126866. pSub = pItem->pSelect;
  126867. if( pSub==0 ) continue;
  126868. /* The code for a subquery should only be generated once, though it is
  126869. ** technically harmless for it to be generated multiple times. The
  126870. ** following assert() will detect if something changes to cause
  126871. ** the same subquery to be coded multiple times, as a signal to the
  126872. ** developers to try to optimize the situation.
  126873. **
  126874. ** Update 2019-07-24:
  126875. ** See ticket https://sqlite.org/src/tktview/c52b09c7f38903b1311cec40.
  126876. ** The dbsqlfuzz fuzzer found a case where the same subquery gets
  126877. ** coded twice. So this assert() now becomes a testcase(). It should
  126878. ** be very rare, though.
  126879. */
  126880. testcase( pItem->addrFillSub!=0 );
  126881. /* Increment Parse.nHeight by the height of the largest expression
  126882. ** tree referred to by this, the parent select. The child select
  126883. ** may contain expression trees of at most
  126884. ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
  126885. ** more conservative than necessary, but much easier than enforcing
  126886. ** an exact limit.
  126887. */
  126888. pParse->nHeight += sqlite3SelectExprHeight(p);
  126889. /* Make copies of constant WHERE-clause terms in the outer query down
  126890. ** inside the subquery. This can help the subquery to run more efficiently.
  126891. */
  126892. if( OptimizationEnabled(db, SQLITE_PushDown)
  126893. && pushDownWhereTerms(pParse, pSub, p->pWhere, pItem->iCursor,
  126894. (pItem->fg.jointype & JT_OUTER)!=0)
  126895. ){
  126896. #if SELECTTRACE_ENABLED
  126897. if( sqlite3SelectTrace & 0x100 ){
  126898. SELECTTRACE(0x100,pParse,p,
  126899. ("After WHERE-clause push-down into subquery %d:\n", pSub->selId));
  126900. sqlite3TreeViewSelect(0, p, 0);
  126901. }
  126902. #endif
  126903. }else{
  126904. SELECTTRACE(0x100,pParse,p,("Push-down not possible\n"));
  126905. }
  126906. zSavedAuthContext = pParse->zAuthContext;
  126907. pParse->zAuthContext = pItem->zName;
  126908. /* Generate code to implement the subquery
  126909. **
  126910. ** The subquery is implemented as a co-routine if the subquery is
  126911. ** guaranteed to be the outer loop (so that it does not need to be
  126912. ** computed more than once)
  126913. **
  126914. ** TODO: Are there other reasons beside (1) to use a co-routine
  126915. ** implementation?
  126916. */
  126917. if( i==0
  126918. && (pTabList->nSrc==1
  126919. || (pTabList->a[1].fg.jointype&(JT_LEFT|JT_CROSS))!=0) /* (1) */
  126920. ){
  126921. /* Implement a co-routine that will return a single row of the result
  126922. ** set on each invocation.
  126923. */
  126924. int addrTop = sqlite3VdbeCurrentAddr(v)+1;
  126925. pItem->regReturn = ++pParse->nMem;
  126926. sqlite3VdbeAddOp3(v, OP_InitCoroutine, pItem->regReturn, 0, addrTop);
  126927. VdbeComment((v, "%s", pItem->pTab->zName));
  126928. pItem->addrFillSub = addrTop;
  126929. sqlite3SelectDestInit(&dest, SRT_Coroutine, pItem->regReturn);
  126930. ExplainQueryPlan((pParse, 1, "CO-ROUTINE %u", pSub->selId));
  126931. sqlite3Select(pParse, pSub, &dest);
  126932. pItem->pTab->nRowLogEst = pSub->nSelectRow;
  126933. pItem->fg.viaCoroutine = 1;
  126934. pItem->regResult = dest.iSdst;
  126935. sqlite3VdbeEndCoroutine(v, pItem->regReturn);
  126936. sqlite3VdbeJumpHere(v, addrTop-1);
  126937. sqlite3ClearTempRegCache(pParse);
  126938. }else{
  126939. /* Generate a subroutine that will fill an ephemeral table with
  126940. ** the content of this subquery. pItem->addrFillSub will point
  126941. ** to the address of the generated subroutine. pItem->regReturn
  126942. ** is a register allocated to hold the subroutine return address
  126943. */
  126944. int topAddr;
  126945. int onceAddr = 0;
  126946. int retAddr;
  126947. struct SrcList_item *pPrior;
  126948. testcase( pItem->addrFillSub==0 ); /* Ticket c52b09c7f38903b1311 */
  126949. pItem->regReturn = ++pParse->nMem;
  126950. topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn);
  126951. pItem->addrFillSub = topAddr+1;
  126952. if( pItem->fg.isCorrelated==0 ){
  126953. /* If the subquery is not correlated and if we are not inside of
  126954. ** a trigger, then we only need to compute the value of the subquery
  126955. ** once. */
  126956. onceAddr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
  126957. VdbeComment((v, "materialize \"%s\"", pItem->pTab->zName));
  126958. }else{
  126959. VdbeNoopComment((v, "materialize \"%s\"", pItem->pTab->zName));
  126960. }
  126961. pPrior = isSelfJoinView(pTabList, pItem);
  126962. if( pPrior ){
  126963. sqlite3VdbeAddOp2(v, OP_OpenDup, pItem->iCursor, pPrior->iCursor);
  126964. assert( pPrior->pSelect!=0 );
  126965. pSub->nSelectRow = pPrior->pSelect->nSelectRow;
  126966. }else{
  126967. sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
  126968. ExplainQueryPlan((pParse, 1, "MATERIALIZE %u", pSub->selId));
  126969. sqlite3Select(pParse, pSub, &dest);
  126970. }
  126971. pItem->pTab->nRowLogEst = pSub->nSelectRow;
  126972. if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr);
  126973. retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn);
  126974. VdbeComment((v, "end %s", pItem->pTab->zName));
  126975. sqlite3VdbeChangeP1(v, topAddr, retAddr);
  126976. sqlite3ClearTempRegCache(pParse);
  126977. }
  126978. if( db->mallocFailed ) goto select_end;
  126979. pParse->nHeight -= sqlite3SelectExprHeight(p);
  126980. pParse->zAuthContext = zSavedAuthContext;
  126981. #endif
  126982. }
  126983. /* Various elements of the SELECT copied into local variables for
  126984. ** convenience */
  126985. pEList = p->pEList;
  126986. pWhere = p->pWhere;
  126987. pGroupBy = p->pGroupBy;
  126988. pHaving = p->pHaving;
  126989. sDistinct.isTnct = (p->selFlags & SF_Distinct)!=0;
  126990. #if SELECTTRACE_ENABLED
  126991. if( sqlite3SelectTrace & 0x400 ){
  126992. SELECTTRACE(0x400,pParse,p,("After all FROM-clause analysis:\n"));
  126993. sqlite3TreeViewSelect(0, p, 0);
  126994. }
  126995. #endif
  126996. /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and
  126997. ** if the select-list is the same as the ORDER BY list, then this query
  126998. ** can be rewritten as a GROUP BY. In other words, this:
  126999. **
  127000. ** SELECT DISTINCT xyz FROM ... ORDER BY xyz
  127001. **
  127002. ** is transformed to:
  127003. **
  127004. ** SELECT xyz FROM ... GROUP BY xyz ORDER BY xyz
  127005. **
  127006. ** The second form is preferred as a single index (or temp-table) may be
  127007. ** used for both the ORDER BY and DISTINCT processing. As originally
  127008. ** written the query must use a temp-table for at least one of the ORDER
  127009. ** BY and DISTINCT, and an index or separate temp-table for the other.
  127010. */
  127011. if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct
  127012. && sqlite3ExprListCompare(sSort.pOrderBy, pEList, -1)==0
  127013. #ifndef SQLITE_OMIT_WINDOWFUNC
  127014. && p->pWin==0
  127015. #endif
  127016. ){
  127017. p->selFlags &= ~SF_Distinct;
  127018. pGroupBy = p->pGroupBy = sqlite3ExprListDup(db, pEList, 0);
  127019. p->selFlags |= SF_Aggregate;
  127020. /* Notice that even thought SF_Distinct has been cleared from p->selFlags,
  127021. ** the sDistinct.isTnct is still set. Hence, isTnct represents the
  127022. ** original setting of the SF_Distinct flag, not the current setting */
  127023. assert( sDistinct.isTnct );
  127024. #if SELECTTRACE_ENABLED
  127025. if( sqlite3SelectTrace & 0x400 ){
  127026. SELECTTRACE(0x400,pParse,p,("Transform DISTINCT into GROUP BY:\n"));
  127027. sqlite3TreeViewSelect(0, p, 0);
  127028. }
  127029. #endif
  127030. }
  127031. /* If there is an ORDER BY clause, then create an ephemeral index to
  127032. ** do the sorting. But this sorting ephemeral index might end up
  127033. ** being unused if the data can be extracted in pre-sorted order.
  127034. ** If that is the case, then the OP_OpenEphemeral instruction will be
  127035. ** changed to an OP_Noop once we figure out that the sorting index is
  127036. ** not needed. The sSort.addrSortIndex variable is used to facilitate
  127037. ** that change.
  127038. */
  127039. if( sSort.pOrderBy ){
  127040. KeyInfo *pKeyInfo;
  127041. pKeyInfo = sqlite3KeyInfoFromExprList(
  127042. pParse, sSort.pOrderBy, 0, pEList->nExpr);
  127043. sSort.iECursor = pParse->nTab++;
  127044. sSort.addrSortIndex =
  127045. sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
  127046. sSort.iECursor, sSort.pOrderBy->nExpr+1+pEList->nExpr, 0,
  127047. (char*)pKeyInfo, P4_KEYINFO
  127048. );
  127049. }else{
  127050. sSort.addrSortIndex = -1;
  127051. }
  127052. /* If the output is destined for a temporary table, open that table.
  127053. */
  127054. if( pDest->eDest==SRT_EphemTab ){
  127055. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iSDParm, pEList->nExpr);
  127056. }
  127057. /* Set the limiter.
  127058. */
  127059. iEnd = sqlite3VdbeMakeLabel(pParse);
  127060. if( (p->selFlags & SF_FixedLimit)==0 ){
  127061. p->nSelectRow = 320; /* 4 billion rows */
  127062. }
  127063. computeLimitRegisters(pParse, p, iEnd);
  127064. if( p->iLimit==0 && sSort.addrSortIndex>=0 ){
  127065. sqlite3VdbeChangeOpcode(v, sSort.addrSortIndex, OP_SorterOpen);
  127066. sSort.sortFlags |= SORTFLAG_UseSorter;
  127067. }
  127068. /* Open an ephemeral index to use for the distinct set.
  127069. */
  127070. if( p->selFlags & SF_Distinct ){
  127071. sDistinct.tabTnct = pParse->nTab++;
  127072. sDistinct.addrTnct = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
  127073. sDistinct.tabTnct, 0, 0,
  127074. (char*)sqlite3KeyInfoFromExprList(pParse, p->pEList,0,0),
  127075. P4_KEYINFO);
  127076. sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
  127077. sDistinct.eTnctType = WHERE_DISTINCT_UNORDERED;
  127078. }else{
  127079. sDistinct.eTnctType = WHERE_DISTINCT_NOOP;
  127080. }
  127081. if( !isAgg && pGroupBy==0 ){
  127082. /* No aggregate functions and no GROUP BY clause */
  127083. u16 wctrlFlags = (sDistinct.isTnct ? WHERE_WANT_DISTINCT : 0)
  127084. | (p->selFlags & SF_FixedLimit);
  127085. #ifndef SQLITE_OMIT_WINDOWFUNC
  127086. Window *pWin = p->pWin; /* Master window object (or NULL) */
  127087. if( pWin ){
  127088. sqlite3WindowCodeInit(pParse, p);
  127089. }
  127090. #endif
  127091. assert( WHERE_USE_LIMIT==SF_FixedLimit );
  127092. /* Begin the database scan. */
  127093. SELECTTRACE(1,pParse,p,("WhereBegin\n"));
  127094. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, sSort.pOrderBy,
  127095. p->pEList, wctrlFlags, p->nSelectRow);
  127096. if( pWInfo==0 ) goto select_end;
  127097. if( sqlite3WhereOutputRowCount(pWInfo) < p->nSelectRow ){
  127098. p->nSelectRow = sqlite3WhereOutputRowCount(pWInfo);
  127099. }
  127100. if( sDistinct.isTnct && sqlite3WhereIsDistinct(pWInfo) ){
  127101. sDistinct.eTnctType = sqlite3WhereIsDistinct(pWInfo);
  127102. }
  127103. if( sSort.pOrderBy ){
  127104. sSort.nOBSat = sqlite3WhereIsOrdered(pWInfo);
  127105. sSort.labelOBLopt = sqlite3WhereOrderByLimitOptLabel(pWInfo);
  127106. if( sSort.nOBSat==sSort.pOrderBy->nExpr ){
  127107. sSort.pOrderBy = 0;
  127108. }
  127109. }
  127110. /* If sorting index that was created by a prior OP_OpenEphemeral
  127111. ** instruction ended up not being needed, then change the OP_OpenEphemeral
  127112. ** into an OP_Noop.
  127113. */
  127114. if( sSort.addrSortIndex>=0 && sSort.pOrderBy==0 ){
  127115. sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
  127116. }
  127117. assert( p->pEList==pEList );
  127118. #ifndef SQLITE_OMIT_WINDOWFUNC
  127119. if( pWin ){
  127120. int addrGosub = sqlite3VdbeMakeLabel(pParse);
  127121. int iCont = sqlite3VdbeMakeLabel(pParse);
  127122. int iBreak = sqlite3VdbeMakeLabel(pParse);
  127123. int regGosub = ++pParse->nMem;
  127124. sqlite3WindowCodeStep(pParse, p, pWInfo, regGosub, addrGosub);
  127125. sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak);
  127126. sqlite3VdbeResolveLabel(v, addrGosub);
  127127. VdbeNoopComment((v, "inner-loop subroutine"));
  127128. sSort.labelOBLopt = 0;
  127129. selectInnerLoop(pParse, p, -1, &sSort, &sDistinct, pDest, iCont, iBreak);
  127130. sqlite3VdbeResolveLabel(v, iCont);
  127131. sqlite3VdbeAddOp1(v, OP_Return, regGosub);
  127132. VdbeComment((v, "end inner-loop subroutine"));
  127133. sqlite3VdbeResolveLabel(v, iBreak);
  127134. }else
  127135. #endif /* SQLITE_OMIT_WINDOWFUNC */
  127136. {
  127137. /* Use the standard inner loop. */
  127138. selectInnerLoop(pParse, p, -1, &sSort, &sDistinct, pDest,
  127139. sqlite3WhereContinueLabel(pWInfo),
  127140. sqlite3WhereBreakLabel(pWInfo));
  127141. /* End the database scan loop.
  127142. */
  127143. sqlite3WhereEnd(pWInfo);
  127144. }
  127145. }else{
  127146. /* This case when there exist aggregate functions or a GROUP BY clause
  127147. ** or both */
  127148. NameContext sNC; /* Name context for processing aggregate information */
  127149. int iAMem; /* First Mem address for storing current GROUP BY */
  127150. int iBMem; /* First Mem address for previous GROUP BY */
  127151. int iUseFlag; /* Mem address holding flag indicating that at least
  127152. ** one row of the input to the aggregator has been
  127153. ** processed */
  127154. int iAbortFlag; /* Mem address which causes query abort if positive */
  127155. int groupBySort; /* Rows come from source in GROUP BY order */
  127156. int addrEnd; /* End of processing for this SELECT */
  127157. int sortPTab = 0; /* Pseudotable used to decode sorting results */
  127158. int sortOut = 0; /* Output register from the sorter */
  127159. int orderByGrp = 0; /* True if the GROUP BY and ORDER BY are the same */
  127160. /* Remove any and all aliases between the result set and the
  127161. ** GROUP BY clause.
  127162. */
  127163. if( pGroupBy ){
  127164. int k; /* Loop counter */
  127165. struct ExprList_item *pItem; /* For looping over expression in a list */
  127166. for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
  127167. pItem->u.x.iAlias = 0;
  127168. }
  127169. for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
  127170. pItem->u.x.iAlias = 0;
  127171. }
  127172. assert( 66==sqlite3LogEst(100) );
  127173. if( p->nSelectRow>66 ) p->nSelectRow = 66;
  127174. /* If there is both a GROUP BY and an ORDER BY clause and they are
  127175. ** identical, then it may be possible to disable the ORDER BY clause
  127176. ** on the grounds that the GROUP BY will cause elements to come out
  127177. ** in the correct order. It also may not - the GROUP BY might use a
  127178. ** database index that causes rows to be grouped together as required
  127179. ** but not actually sorted. Either way, record the fact that the
  127180. ** ORDER BY and GROUP BY clauses are the same by setting the orderByGrp
  127181. ** variable. */
  127182. if( sSort.pOrderBy && pGroupBy->nExpr==sSort.pOrderBy->nExpr ){
  127183. int ii;
  127184. /* The GROUP BY processing doesn't care whether rows are delivered in
  127185. ** ASC or DESC order - only that each group is returned contiguously.
  127186. ** So set the ASC/DESC flags in the GROUP BY to match those in the
  127187. ** ORDER BY to maximize the chances of rows being delivered in an
  127188. ** order that makes the ORDER BY redundant. */
  127189. for(ii=0; ii<pGroupBy->nExpr; ii++){
  127190. u8 sortFlags = sSort.pOrderBy->a[ii].sortFlags & KEYINFO_ORDER_DESC;
  127191. pGroupBy->a[ii].sortFlags = sortFlags;
  127192. }
  127193. if( sqlite3ExprListCompare(pGroupBy, sSort.pOrderBy, -1)==0 ){
  127194. orderByGrp = 1;
  127195. }
  127196. }
  127197. }else{
  127198. assert( 0==sqlite3LogEst(1) );
  127199. p->nSelectRow = 0;
  127200. }
  127201. /* Create a label to jump to when we want to abort the query */
  127202. addrEnd = sqlite3VdbeMakeLabel(pParse);
  127203. /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
  127204. ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
  127205. ** SELECT statement.
  127206. */
  127207. memset(&sNC, 0, sizeof(sNC));
  127208. sNC.pParse = pParse;
  127209. sNC.pSrcList = pTabList;
  127210. sNC.uNC.pAggInfo = &sAggInfo;
  127211. VVA_ONLY( sNC.ncFlags = NC_UAggInfo; )
  127212. sAggInfo.mnReg = pParse->nMem+1;
  127213. sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr : 0;
  127214. sAggInfo.pGroupBy = pGroupBy;
  127215. sqlite3ExprAnalyzeAggList(&sNC, pEList);
  127216. sqlite3ExprAnalyzeAggList(&sNC, sSort.pOrderBy);
  127217. if( pHaving ){
  127218. if( pGroupBy ){
  127219. assert( pWhere==p->pWhere );
  127220. assert( pHaving==p->pHaving );
  127221. assert( pGroupBy==p->pGroupBy );
  127222. havingToWhere(pParse, p);
  127223. pWhere = p->pWhere;
  127224. }
  127225. sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
  127226. }
  127227. sAggInfo.nAccumulator = sAggInfo.nColumn;
  127228. if( p->pGroupBy==0 && p->pHaving==0 && sAggInfo.nFunc==1 ){
  127229. minMaxFlag = minMaxQuery(db, sAggInfo.aFunc[0].pExpr, &pMinMaxOrderBy);
  127230. }else{
  127231. minMaxFlag = WHERE_ORDERBY_NORMAL;
  127232. }
  127233. for(i=0; i<sAggInfo.nFunc; i++){
  127234. Expr *pExpr = sAggInfo.aFunc[i].pExpr;
  127235. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  127236. sNC.ncFlags |= NC_InAggFunc;
  127237. sqlite3ExprAnalyzeAggList(&sNC, pExpr->x.pList);
  127238. #ifndef SQLITE_OMIT_WINDOWFUNC
  127239. assert( !IsWindowFunc(pExpr) );
  127240. if( ExprHasProperty(pExpr, EP_WinFunc) ){
  127241. sqlite3ExprAnalyzeAggregates(&sNC, pExpr->y.pWin->pFilter);
  127242. }
  127243. #endif
  127244. sNC.ncFlags &= ~NC_InAggFunc;
  127245. }
  127246. sAggInfo.mxReg = pParse->nMem;
  127247. if( db->mallocFailed ) goto select_end;
  127248. #if SELECTTRACE_ENABLED
  127249. if( sqlite3SelectTrace & 0x400 ){
  127250. int ii;
  127251. SELECTTRACE(0x400,pParse,p,("After aggregate analysis %p:\n", &sAggInfo));
  127252. sqlite3TreeViewSelect(0, p, 0);
  127253. for(ii=0; ii<sAggInfo.nColumn; ii++){
  127254. sqlite3DebugPrintf("agg-column[%d] iMem=%d\n",
  127255. ii, sAggInfo.aCol[ii].iMem);
  127256. sqlite3TreeViewExpr(0, sAggInfo.aCol[ii].pExpr, 0);
  127257. }
  127258. for(ii=0; ii<sAggInfo.nFunc; ii++){
  127259. sqlite3DebugPrintf("agg-func[%d]: iMem=%d\n",
  127260. ii, sAggInfo.aFunc[ii].iMem);
  127261. sqlite3TreeViewExpr(0, sAggInfo.aFunc[ii].pExpr, 0);
  127262. }
  127263. }
  127264. #endif
  127265. /* Processing for aggregates with GROUP BY is very different and
  127266. ** much more complex than aggregates without a GROUP BY.
  127267. */
  127268. if( pGroupBy ){
  127269. KeyInfo *pKeyInfo; /* Keying information for the group by clause */
  127270. int addr1; /* A-vs-B comparision jump */
  127271. int addrOutputRow; /* Start of subroutine that outputs a result row */
  127272. int regOutputRow; /* Return address register for output subroutine */
  127273. int addrSetAbort; /* Set the abort flag and return */
  127274. int addrTopOfLoop; /* Top of the input loop */
  127275. int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
  127276. int addrReset; /* Subroutine for resetting the accumulator */
  127277. int regReset; /* Return address register for reset subroutine */
  127278. /* If there is a GROUP BY clause we might need a sorting index to
  127279. ** implement it. Allocate that sorting index now. If it turns out
  127280. ** that we do not need it after all, the OP_SorterOpen instruction
  127281. ** will be converted into a Noop.
  127282. */
  127283. sAggInfo.sortingIdx = pParse->nTab++;
  127284. pKeyInfo = sqlite3KeyInfoFromExprList(pParse,pGroupBy,0,sAggInfo.nColumn);
  127285. addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen,
  127286. sAggInfo.sortingIdx, sAggInfo.nSortingColumn,
  127287. 0, (char*)pKeyInfo, P4_KEYINFO);
  127288. /* Initialize memory locations used by GROUP BY aggregate processing
  127289. */
  127290. iUseFlag = ++pParse->nMem;
  127291. iAbortFlag = ++pParse->nMem;
  127292. regOutputRow = ++pParse->nMem;
  127293. addrOutputRow = sqlite3VdbeMakeLabel(pParse);
  127294. regReset = ++pParse->nMem;
  127295. addrReset = sqlite3VdbeMakeLabel(pParse);
  127296. iAMem = pParse->nMem + 1;
  127297. pParse->nMem += pGroupBy->nExpr;
  127298. iBMem = pParse->nMem + 1;
  127299. pParse->nMem += pGroupBy->nExpr;
  127300. sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
  127301. VdbeComment((v, "clear abort flag"));
  127302. sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1);
  127303. /* Begin a loop that will extract all source rows in GROUP BY order.
  127304. ** This might involve two separate loops with an OP_Sort in between, or
  127305. ** it might be a single loop that uses an index to extract information
  127306. ** in the right order to begin with.
  127307. */
  127308. sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
  127309. SELECTTRACE(1,pParse,p,("WhereBegin\n"));
  127310. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, 0,
  127311. WHERE_GROUPBY | (orderByGrp ? WHERE_SORTBYGROUP : 0), 0
  127312. );
  127313. if( pWInfo==0 ) goto select_end;
  127314. if( sqlite3WhereIsOrdered(pWInfo)==pGroupBy->nExpr ){
  127315. /* The optimizer is able to deliver rows in group by order so
  127316. ** we do not have to sort. The OP_OpenEphemeral table will be
  127317. ** cancelled later because we still need to use the pKeyInfo
  127318. */
  127319. groupBySort = 0;
  127320. }else{
  127321. /* Rows are coming out in undetermined order. We have to push
  127322. ** each row into a sorting index, terminate the first loop,
  127323. ** then loop over the sorting index in order to get the output
  127324. ** in sorted order
  127325. */
  127326. int regBase;
  127327. int regRecord;
  127328. int nCol;
  127329. int nGroupBy;
  127330. explainTempTable(pParse,
  127331. (sDistinct.isTnct && (p->selFlags&SF_Distinct)==0) ?
  127332. "DISTINCT" : "GROUP BY");
  127333. groupBySort = 1;
  127334. nGroupBy = pGroupBy->nExpr;
  127335. nCol = nGroupBy;
  127336. j = nGroupBy;
  127337. for(i=0; i<sAggInfo.nColumn; i++){
  127338. if( sAggInfo.aCol[i].iSorterColumn>=j ){
  127339. nCol++;
  127340. j++;
  127341. }
  127342. }
  127343. regBase = sqlite3GetTempRange(pParse, nCol);
  127344. sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0, 0);
  127345. j = nGroupBy;
  127346. for(i=0; i<sAggInfo.nColumn; i++){
  127347. struct AggInfo_col *pCol = &sAggInfo.aCol[i];
  127348. if( pCol->iSorterColumn>=j ){
  127349. int r1 = j + regBase;
  127350. sqlite3ExprCodeGetColumnOfTable(v,
  127351. pCol->pTab, pCol->iTable, pCol->iColumn, r1);
  127352. j++;
  127353. }
  127354. }
  127355. regRecord = sqlite3GetTempReg(pParse);
  127356. sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
  127357. sqlite3VdbeAddOp2(v, OP_SorterInsert, sAggInfo.sortingIdx, regRecord);
  127358. sqlite3ReleaseTempReg(pParse, regRecord);
  127359. sqlite3ReleaseTempRange(pParse, regBase, nCol);
  127360. sqlite3WhereEnd(pWInfo);
  127361. sAggInfo.sortingIdxPTab = sortPTab = pParse->nTab++;
  127362. sortOut = sqlite3GetTempReg(pParse);
  127363. sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol);
  127364. sqlite3VdbeAddOp2(v, OP_SorterSort, sAggInfo.sortingIdx, addrEnd);
  127365. VdbeComment((v, "GROUP BY sort")); VdbeCoverage(v);
  127366. sAggInfo.useSortingIdx = 1;
  127367. }
  127368. /* If the index or temporary table used by the GROUP BY sort
  127369. ** will naturally deliver rows in the order required by the ORDER BY
  127370. ** clause, cancel the ephemeral table open coded earlier.
  127371. **
  127372. ** This is an optimization - the correct answer should result regardless.
  127373. ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER to
  127374. ** disable this optimization for testing purposes. */
  127375. if( orderByGrp && OptimizationEnabled(db, SQLITE_GroupByOrder)
  127376. && (groupBySort || sqlite3WhereIsSorted(pWInfo))
  127377. ){
  127378. sSort.pOrderBy = 0;
  127379. sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
  127380. }
  127381. /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
  127382. ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
  127383. ** Then compare the current GROUP BY terms against the GROUP BY terms
  127384. ** from the previous row currently stored in a0, a1, a2...
  127385. */
  127386. addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
  127387. if( groupBySort ){
  127388. sqlite3VdbeAddOp3(v, OP_SorterData, sAggInfo.sortingIdx,
  127389. sortOut, sortPTab);
  127390. }
  127391. for(j=0; j<pGroupBy->nExpr; j++){
  127392. if( groupBySort ){
  127393. sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j);
  127394. }else{
  127395. sAggInfo.directMode = 1;
  127396. sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
  127397. }
  127398. }
  127399. sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
  127400. (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
  127401. addr1 = sqlite3VdbeCurrentAddr(v);
  127402. sqlite3VdbeAddOp3(v, OP_Jump, addr1+1, 0, addr1+1); VdbeCoverage(v);
  127403. /* Generate code that runs whenever the GROUP BY changes.
  127404. ** Changes in the GROUP BY are detected by the previous code
  127405. ** block. If there were no changes, this block is skipped.
  127406. **
  127407. ** This code copies current group by terms in b0,b1,b2,...
  127408. ** over to a0,a1,a2. It then calls the output subroutine
  127409. ** and resets the aggregate accumulator registers in preparation
  127410. ** for the next GROUP BY batch.
  127411. */
  127412. sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
  127413. sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
  127414. VdbeComment((v, "output one row"));
  127415. sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd); VdbeCoverage(v);
  127416. VdbeComment((v, "check abort flag"));
  127417. sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
  127418. VdbeComment((v, "reset accumulator"));
  127419. /* Update the aggregate accumulators based on the content of
  127420. ** the current row
  127421. */
  127422. sqlite3VdbeJumpHere(v, addr1);
  127423. updateAccumulator(pParse, iUseFlag, &sAggInfo);
  127424. sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
  127425. VdbeComment((v, "indicate data in accumulator"));
  127426. /* End of the loop
  127427. */
  127428. if( groupBySort ){
  127429. sqlite3VdbeAddOp2(v, OP_SorterNext, sAggInfo.sortingIdx, addrTopOfLoop);
  127430. VdbeCoverage(v);
  127431. }else{
  127432. sqlite3WhereEnd(pWInfo);
  127433. sqlite3VdbeChangeToNoop(v, addrSortingIdx);
  127434. }
  127435. /* Output the final row of result
  127436. */
  127437. sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
  127438. VdbeComment((v, "output final row"));
  127439. /* Jump over the subroutines
  127440. */
  127441. sqlite3VdbeGoto(v, addrEnd);
  127442. /* Generate a subroutine that outputs a single row of the result
  127443. ** set. This subroutine first looks at the iUseFlag. If iUseFlag
  127444. ** is less than or equal to zero, the subroutine is a no-op. If
  127445. ** the processing calls for the query to abort, this subroutine
  127446. ** increments the iAbortFlag memory location before returning in
  127447. ** order to signal the caller to abort.
  127448. */
  127449. addrSetAbort = sqlite3VdbeCurrentAddr(v);
  127450. sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
  127451. VdbeComment((v, "set abort flag"));
  127452. sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
  127453. sqlite3VdbeResolveLabel(v, addrOutputRow);
  127454. addrOutputRow = sqlite3VdbeCurrentAddr(v);
  127455. sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
  127456. VdbeCoverage(v);
  127457. VdbeComment((v, "Groupby result generator entry point"));
  127458. sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
  127459. finalizeAggFunctions(pParse, &sAggInfo);
  127460. sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
  127461. selectInnerLoop(pParse, p, -1, &sSort,
  127462. &sDistinct, pDest,
  127463. addrOutputRow+1, addrSetAbort);
  127464. sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
  127465. VdbeComment((v, "end groupby result generator"));
  127466. /* Generate a subroutine that will reset the group-by accumulator
  127467. */
  127468. sqlite3VdbeResolveLabel(v, addrReset);
  127469. resetAccumulator(pParse, &sAggInfo);
  127470. sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
  127471. VdbeComment((v, "indicate accumulator empty"));
  127472. sqlite3VdbeAddOp1(v, OP_Return, regReset);
  127473. } /* endif pGroupBy. Begin aggregate queries without GROUP BY: */
  127474. else {
  127475. Table *pTab;
  127476. if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
  127477. /* If isSimpleCount() returns a pointer to a Table structure, then
  127478. ** the SQL statement is of the form:
  127479. **
  127480. ** SELECT count(*) FROM <tbl>
  127481. **
  127482. ** where the Table structure returned represents table <tbl>.
  127483. **
  127484. ** This statement is so common that it is optimized specially. The
  127485. ** OP_Count instruction is executed either on the intkey table that
  127486. ** contains the data for table <tbl> or on one of its indexes. It
  127487. ** is better to execute the op on an index, as indexes are almost
  127488. ** always spread across less pages than their corresponding tables.
  127489. */
  127490. const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  127491. const int iCsr = pParse->nTab++; /* Cursor to scan b-tree */
  127492. Index *pIdx; /* Iterator variable */
  127493. KeyInfo *pKeyInfo = 0; /* Keyinfo for scanned index */
  127494. Index *pBest = 0; /* Best index found so far */
  127495. int iRoot = pTab->tnum; /* Root page of scanned b-tree */
  127496. sqlite3CodeVerifySchema(pParse, iDb);
  127497. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  127498. /* Search for the index that has the lowest scan cost.
  127499. **
  127500. ** (2011-04-15) Do not do a full scan of an unordered index.
  127501. **
  127502. ** (2013-10-03) Do not count the entries in a partial index.
  127503. **
  127504. ** In practice the KeyInfo structure will not be used. It is only
  127505. ** passed to keep OP_OpenRead happy.
  127506. */
  127507. if( !HasRowid(pTab) ) pBest = sqlite3PrimaryKeyIndex(pTab);
  127508. if( !p->pSrc->a[0].fg.notIndexed ){
  127509. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  127510. if( pIdx->bUnordered==0
  127511. && pIdx->szIdxRow<pTab->szTabRow
  127512. && pIdx->pPartIdxWhere==0
  127513. && (!pBest || pIdx->szIdxRow<pBest->szIdxRow)
  127514. ){
  127515. pBest = pIdx;
  127516. }
  127517. }
  127518. }
  127519. if( pBest ){
  127520. iRoot = pBest->tnum;
  127521. pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pBest);
  127522. }
  127523. /* Open a read-only cursor, execute the OP_Count, close the cursor. */
  127524. sqlite3VdbeAddOp4Int(v, OP_OpenRead, iCsr, iRoot, iDb, 1);
  127525. if( pKeyInfo ){
  127526. sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO);
  127527. }
  127528. sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
  127529. sqlite3VdbeAddOp1(v, OP_Close, iCsr);
  127530. explainSimpleCount(pParse, pTab, pBest);
  127531. }else{
  127532. int regAcc = 0; /* "populate accumulators" flag */
  127533. /* If there are accumulator registers but no min() or max() functions
  127534. ** without FILTER clauses, allocate register regAcc. Register regAcc
  127535. ** will contain 0 the first time the inner loop runs, and 1 thereafter.
  127536. ** The code generated by updateAccumulator() uses this to ensure
  127537. ** that the accumulator registers are (a) updated only once if
  127538. ** there are no min() or max functions or (b) always updated for the
  127539. ** first row visited by the aggregate, so that they are updated at
  127540. ** least once even if the FILTER clause means the min() or max()
  127541. ** function visits zero rows. */
  127542. if( sAggInfo.nAccumulator ){
  127543. for(i=0; i<sAggInfo.nFunc; i++){
  127544. if( ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_WinFunc) ) continue;
  127545. if( sAggInfo.aFunc[i].pFunc->funcFlags&SQLITE_FUNC_NEEDCOLL ) break;
  127546. }
  127547. if( i==sAggInfo.nFunc ){
  127548. regAcc = ++pParse->nMem;
  127549. sqlite3VdbeAddOp2(v, OP_Integer, 0, regAcc);
  127550. }
  127551. }
  127552. /* This case runs if the aggregate has no GROUP BY clause. The
  127553. ** processing is much simpler since there is only a single row
  127554. ** of output.
  127555. */
  127556. assert( p->pGroupBy==0 );
  127557. resetAccumulator(pParse, &sAggInfo);
  127558. /* If this query is a candidate for the min/max optimization, then
  127559. ** minMaxFlag will have been previously set to either
  127560. ** WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX and pMinMaxOrderBy will
  127561. ** be an appropriate ORDER BY expression for the optimization.
  127562. */
  127563. assert( minMaxFlag==WHERE_ORDERBY_NORMAL || pMinMaxOrderBy!=0 );
  127564. assert( pMinMaxOrderBy==0 || pMinMaxOrderBy->nExpr==1 );
  127565. SELECTTRACE(1,pParse,p,("WhereBegin\n"));
  127566. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pMinMaxOrderBy,
  127567. 0, minMaxFlag, 0);
  127568. if( pWInfo==0 ){
  127569. goto select_end;
  127570. }
  127571. updateAccumulator(pParse, regAcc, &sAggInfo);
  127572. if( regAcc ) sqlite3VdbeAddOp2(v, OP_Integer, 1, regAcc);
  127573. if( sqlite3WhereIsOrdered(pWInfo)>0 ){
  127574. sqlite3VdbeGoto(v, sqlite3WhereBreakLabel(pWInfo));
  127575. VdbeComment((v, "%s() by index",
  127576. (minMaxFlag==WHERE_ORDERBY_MIN?"min":"max")));
  127577. }
  127578. sqlite3WhereEnd(pWInfo);
  127579. finalizeAggFunctions(pParse, &sAggInfo);
  127580. }
  127581. sSort.pOrderBy = 0;
  127582. sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
  127583. selectInnerLoop(pParse, p, -1, 0, 0,
  127584. pDest, addrEnd, addrEnd);
  127585. }
  127586. sqlite3VdbeResolveLabel(v, addrEnd);
  127587. } /* endif aggregate query */
  127588. if( sDistinct.eTnctType==WHERE_DISTINCT_UNORDERED ){
  127589. explainTempTable(pParse, "DISTINCT");
  127590. }
  127591. /* If there is an ORDER BY clause, then we need to sort the results
  127592. ** and send them to the callback one by one.
  127593. */
  127594. if( sSort.pOrderBy ){
  127595. explainTempTable(pParse,
  127596. sSort.nOBSat>0 ? "RIGHT PART OF ORDER BY":"ORDER BY");
  127597. assert( p->pEList==pEList );
  127598. generateSortTail(pParse, p, &sSort, pEList->nExpr, pDest);
  127599. }
  127600. /* Jump here to skip this query
  127601. */
  127602. sqlite3VdbeResolveLabel(v, iEnd);
  127603. /* The SELECT has been coded. If there is an error in the Parse structure,
  127604. ** set the return code to 1. Otherwise 0. */
  127605. rc = (pParse->nErr>0);
  127606. /* Control jumps to here if an error is encountered above, or upon
  127607. ** successful coding of the SELECT.
  127608. */
  127609. select_end:
  127610. sqlite3ExprListDelete(db, pMinMaxOrderBy);
  127611. sqlite3DbFree(db, sAggInfo.aCol);
  127612. sqlite3DbFree(db, sAggInfo.aFunc);
  127613. #if SELECTTRACE_ENABLED
  127614. SELECTTRACE(0x1,pParse,p,("end processing\n"));
  127615. if( (sqlite3SelectTrace & 0x2000)!=0 && ExplainQueryPlanParent(pParse)==0 ){
  127616. sqlite3TreeViewSelect(0, p, 0);
  127617. }
  127618. #endif
  127619. ExplainQueryPlanPop(pParse);
  127620. return rc;
  127621. }
  127622. /************** End of select.c **********************************************/
  127623. /************** Begin file table.c *******************************************/
  127624. /*
  127625. ** 2001 September 15
  127626. **
  127627. ** The author disclaims copyright to this source code. In place of
  127628. ** a legal notice, here is a blessing:
  127629. **
  127630. ** May you do good and not evil.
  127631. ** May you find forgiveness for yourself and forgive others.
  127632. ** May you share freely, never taking more than you give.
  127633. **
  127634. *************************************************************************
  127635. ** This file contains the sqlite3_get_table() and sqlite3_free_table()
  127636. ** interface routines. These are just wrappers around the main
  127637. ** interface routine of sqlite3_exec().
  127638. **
  127639. ** These routines are in a separate files so that they will not be linked
  127640. ** if they are not used.
  127641. */
  127642. /* #include "sqliteInt.h" */
  127643. #ifndef SQLITE_OMIT_GET_TABLE
  127644. /*
  127645. ** This structure is used to pass data from sqlite3_get_table() through
  127646. ** to the callback function is uses to build the result.
  127647. */
  127648. typedef struct TabResult {
  127649. char **azResult; /* Accumulated output */
  127650. char *zErrMsg; /* Error message text, if an error occurs */
  127651. u32 nAlloc; /* Slots allocated for azResult[] */
  127652. u32 nRow; /* Number of rows in the result */
  127653. u32 nColumn; /* Number of columns in the result */
  127654. u32 nData; /* Slots used in azResult[]. (nRow+1)*nColumn */
  127655. int rc; /* Return code from sqlite3_exec() */
  127656. } TabResult;
  127657. /*
  127658. ** This routine is called once for each row in the result table. Its job
  127659. ** is to fill in the TabResult structure appropriately, allocating new
  127660. ** memory as necessary.
  127661. */
  127662. static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
  127663. TabResult *p = (TabResult*)pArg; /* Result accumulator */
  127664. int need; /* Slots needed in p->azResult[] */
  127665. int i; /* Loop counter */
  127666. char *z; /* A single column of result */
  127667. /* Make sure there is enough space in p->azResult to hold everything
  127668. ** we need to remember from this invocation of the callback.
  127669. */
  127670. if( p->nRow==0 && argv!=0 ){
  127671. need = nCol*2;
  127672. }else{
  127673. need = nCol;
  127674. }
  127675. if( p->nData + need > p->nAlloc ){
  127676. char **azNew;
  127677. p->nAlloc = p->nAlloc*2 + need;
  127678. azNew = sqlite3Realloc( p->azResult, sizeof(char*)*p->nAlloc );
  127679. if( azNew==0 ) goto malloc_failed;
  127680. p->azResult = azNew;
  127681. }
  127682. /* If this is the first row, then generate an extra row containing
  127683. ** the names of all columns.
  127684. */
  127685. if( p->nRow==0 ){
  127686. p->nColumn = nCol;
  127687. for(i=0; i<nCol; i++){
  127688. z = sqlite3_mprintf("%s", colv[i]);
  127689. if( z==0 ) goto malloc_failed;
  127690. p->azResult[p->nData++] = z;
  127691. }
  127692. }else if( (int)p->nColumn!=nCol ){
  127693. sqlite3_free(p->zErrMsg);
  127694. p->zErrMsg = sqlite3_mprintf(
  127695. "sqlite3_get_table() called with two or more incompatible queries"
  127696. );
  127697. p->rc = SQLITE_ERROR;
  127698. return 1;
  127699. }
  127700. /* Copy over the row data
  127701. */
  127702. if( argv!=0 ){
  127703. for(i=0; i<nCol; i++){
  127704. if( argv[i]==0 ){
  127705. z = 0;
  127706. }else{
  127707. int n = sqlite3Strlen30(argv[i])+1;
  127708. z = sqlite3_malloc64( n );
  127709. if( z==0 ) goto malloc_failed;
  127710. memcpy(z, argv[i], n);
  127711. }
  127712. p->azResult[p->nData++] = z;
  127713. }
  127714. p->nRow++;
  127715. }
  127716. return 0;
  127717. malloc_failed:
  127718. p->rc = SQLITE_NOMEM_BKPT;
  127719. return 1;
  127720. }
  127721. /*
  127722. ** Query the database. But instead of invoking a callback for each row,
  127723. ** malloc() for space to hold the result and return the entire results
  127724. ** at the conclusion of the call.
  127725. **
  127726. ** The result that is written to ***pazResult is held in memory obtained
  127727. ** from malloc(). But the caller cannot free this memory directly.
  127728. ** Instead, the entire table should be passed to sqlite3_free_table() when
  127729. ** the calling procedure is finished using it.
  127730. */
  127731. SQLITE_API int sqlite3_get_table(
  127732. sqlite3 *db, /* The database on which the SQL executes */
  127733. const char *zSql, /* The SQL to be executed */
  127734. char ***pazResult, /* Write the result table here */
  127735. int *pnRow, /* Write the number of rows in the result here */
  127736. int *pnColumn, /* Write the number of columns of result here */
  127737. char **pzErrMsg /* Write error messages here */
  127738. ){
  127739. int rc;
  127740. TabResult res;
  127741. #ifdef SQLITE_ENABLE_API_ARMOR
  127742. if( !sqlite3SafetyCheckOk(db) || pazResult==0 ) return SQLITE_MISUSE_BKPT;
  127743. #endif
  127744. *pazResult = 0;
  127745. if( pnColumn ) *pnColumn = 0;
  127746. if( pnRow ) *pnRow = 0;
  127747. if( pzErrMsg ) *pzErrMsg = 0;
  127748. res.zErrMsg = 0;
  127749. res.nRow = 0;
  127750. res.nColumn = 0;
  127751. res.nData = 1;
  127752. res.nAlloc = 20;
  127753. res.rc = SQLITE_OK;
  127754. res.azResult = sqlite3_malloc64(sizeof(char*)*res.nAlloc );
  127755. if( res.azResult==0 ){
  127756. db->errCode = SQLITE_NOMEM;
  127757. return SQLITE_NOMEM_BKPT;
  127758. }
  127759. res.azResult[0] = 0;
  127760. rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
  127761. assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
  127762. res.azResult[0] = SQLITE_INT_TO_PTR(res.nData);
  127763. if( (rc&0xff)==SQLITE_ABORT ){
  127764. sqlite3_free_table(&res.azResult[1]);
  127765. if( res.zErrMsg ){
  127766. if( pzErrMsg ){
  127767. sqlite3_free(*pzErrMsg);
  127768. *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
  127769. }
  127770. sqlite3_free(res.zErrMsg);
  127771. }
  127772. db->errCode = res.rc; /* Assume 32-bit assignment is atomic */
  127773. return res.rc;
  127774. }
  127775. sqlite3_free(res.zErrMsg);
  127776. if( rc!=SQLITE_OK ){
  127777. sqlite3_free_table(&res.azResult[1]);
  127778. return rc;
  127779. }
  127780. if( res.nAlloc>res.nData ){
  127781. char **azNew;
  127782. azNew = sqlite3Realloc( res.azResult, sizeof(char*)*res.nData );
  127783. if( azNew==0 ){
  127784. sqlite3_free_table(&res.azResult[1]);
  127785. db->errCode = SQLITE_NOMEM;
  127786. return SQLITE_NOMEM_BKPT;
  127787. }
  127788. res.azResult = azNew;
  127789. }
  127790. *pazResult = &res.azResult[1];
  127791. if( pnColumn ) *pnColumn = res.nColumn;
  127792. if( pnRow ) *pnRow = res.nRow;
  127793. return rc;
  127794. }
  127795. /*
  127796. ** This routine frees the space the sqlite3_get_table() malloced.
  127797. */
  127798. SQLITE_API void sqlite3_free_table(
  127799. char **azResult /* Result returned from sqlite3_get_table() */
  127800. ){
  127801. if( azResult ){
  127802. int i, n;
  127803. azResult--;
  127804. assert( azResult!=0 );
  127805. n = SQLITE_PTR_TO_INT(azResult[0]);
  127806. for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }
  127807. sqlite3_free(azResult);
  127808. }
  127809. }
  127810. #endif /* SQLITE_OMIT_GET_TABLE */
  127811. /************** End of table.c ***********************************************/
  127812. /************** Begin file trigger.c *****************************************/
  127813. /*
  127814. **
  127815. ** The author disclaims copyright to this source code. In place of
  127816. ** a legal notice, here is a blessing:
  127817. **
  127818. ** May you do good and not evil.
  127819. ** May you find forgiveness for yourself and forgive others.
  127820. ** May you share freely, never taking more than you give.
  127821. **
  127822. *************************************************************************
  127823. ** This file contains the implementation for TRIGGERs
  127824. */
  127825. /* #include "sqliteInt.h" */
  127826. #ifndef SQLITE_OMIT_TRIGGER
  127827. /*
  127828. ** Delete a linked list of TriggerStep structures.
  127829. */
  127830. SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
  127831. while( pTriggerStep ){
  127832. TriggerStep * pTmp = pTriggerStep;
  127833. pTriggerStep = pTriggerStep->pNext;
  127834. sqlite3ExprDelete(db, pTmp->pWhere);
  127835. sqlite3ExprListDelete(db, pTmp->pExprList);
  127836. sqlite3SelectDelete(db, pTmp->pSelect);
  127837. sqlite3IdListDelete(db, pTmp->pIdList);
  127838. sqlite3UpsertDelete(db, pTmp->pUpsert);
  127839. sqlite3DbFree(db, pTmp->zSpan);
  127840. sqlite3DbFree(db, pTmp);
  127841. }
  127842. }
  127843. /*
  127844. ** Given table pTab, return a list of all the triggers attached to
  127845. ** the table. The list is connected by Trigger.pNext pointers.
  127846. **
  127847. ** All of the triggers on pTab that are in the same database as pTab
  127848. ** are already attached to pTab->pTrigger. But there might be additional
  127849. ** triggers on pTab in the TEMP schema. This routine prepends all
  127850. ** TEMP triggers on pTab to the beginning of the pTab->pTrigger list
  127851. ** and returns the combined list.
  127852. **
  127853. ** To state it another way: This routine returns a list of all triggers
  127854. ** that fire off of pTab. The list will include any TEMP triggers on
  127855. ** pTab as well as the triggers lised in pTab->pTrigger.
  127856. */
  127857. SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){
  127858. Schema * const pTmpSchema = pParse->db->aDb[1].pSchema;
  127859. Trigger *pList = 0; /* List of triggers to return */
  127860. if( pParse->disableTriggers ){
  127861. return 0;
  127862. }
  127863. if( pTmpSchema!=pTab->pSchema ){
  127864. HashElem *p;
  127865. assert( sqlite3SchemaMutexHeld(pParse->db, 0, pTmpSchema) );
  127866. for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){
  127867. Trigger *pTrig = (Trigger *)sqliteHashData(p);
  127868. if( pTrig->pTabSchema==pTab->pSchema
  127869. && 0==sqlite3StrICmp(pTrig->table, pTab->zName)
  127870. ){
  127871. pTrig->pNext = (pList ? pList : pTab->pTrigger);
  127872. pList = pTrig;
  127873. }
  127874. }
  127875. }
  127876. return (pList ? pList : pTab->pTrigger);
  127877. }
  127878. /*
  127879. ** This is called by the parser when it sees a CREATE TRIGGER statement
  127880. ** up to the point of the BEGIN before the trigger actions. A Trigger
  127881. ** structure is generated based on the information available and stored
  127882. ** in pParse->pNewTrigger. After the trigger actions have been parsed, the
  127883. ** sqlite3FinishTrigger() function is called to complete the trigger
  127884. ** construction process.
  127885. */
  127886. SQLITE_PRIVATE void sqlite3BeginTrigger(
  127887. Parse *pParse, /* The parse context of the CREATE TRIGGER statement */
  127888. Token *pName1, /* The name of the trigger */
  127889. Token *pName2, /* The name of the trigger */
  127890. int tr_tm, /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
  127891. int op, /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
  127892. IdList *pColumns, /* column list if this is an UPDATE OF trigger */
  127893. SrcList *pTableName,/* The name of the table/view the trigger applies to */
  127894. Expr *pWhen, /* WHEN clause */
  127895. int isTemp, /* True if the TEMPORARY keyword is present */
  127896. int noErr /* Suppress errors if the trigger already exists */
  127897. ){
  127898. Trigger *pTrigger = 0; /* The new trigger */
  127899. Table *pTab; /* Table that the trigger fires off of */
  127900. char *zName = 0; /* Name of the trigger */
  127901. sqlite3 *db = pParse->db; /* The database connection */
  127902. int iDb; /* The database to store the trigger in */
  127903. Token *pName; /* The unqualified db name */
  127904. DbFixer sFix; /* State vector for the DB fixer */
  127905. assert( pName1!=0 ); /* pName1->z might be NULL, but not pName1 itself */
  127906. assert( pName2!=0 );
  127907. assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
  127908. assert( op>0 && op<0xff );
  127909. if( isTemp ){
  127910. /* If TEMP was specified, then the trigger name may not be qualified. */
  127911. if( pName2->n>0 ){
  127912. sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
  127913. goto trigger_cleanup;
  127914. }
  127915. iDb = 1;
  127916. pName = pName1;
  127917. }else{
  127918. /* Figure out the db that the trigger will be created in */
  127919. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  127920. if( iDb<0 ){
  127921. goto trigger_cleanup;
  127922. }
  127923. }
  127924. if( !pTableName || db->mallocFailed ){
  127925. goto trigger_cleanup;
  127926. }
  127927. /* A long-standing parser bug is that this syntax was allowed:
  127928. **
  127929. ** CREATE TRIGGER attached.demo AFTER INSERT ON attached.tab ....
  127930. ** ^^^^^^^^
  127931. **
  127932. ** To maintain backwards compatibility, ignore the database
  127933. ** name on pTableName if we are reparsing out of SQLITE_MASTER.
  127934. */
  127935. if( db->init.busy && iDb!=1 ){
  127936. sqlite3DbFree(db, pTableName->a[0].zDatabase);
  127937. pTableName->a[0].zDatabase = 0;
  127938. }
  127939. /* If the trigger name was unqualified, and the table is a temp table,
  127940. ** then set iDb to 1 to create the trigger in the temporary database.
  127941. ** If sqlite3SrcListLookup() returns 0, indicating the table does not
  127942. ** exist, the error is caught by the block below.
  127943. */
  127944. pTab = sqlite3SrcListLookup(pParse, pTableName);
  127945. if( db->init.busy==0 && pName2->n==0 && pTab
  127946. && pTab->pSchema==db->aDb[1].pSchema ){
  127947. iDb = 1;
  127948. }
  127949. /* Ensure the table name matches database name and that the table exists */
  127950. if( db->mallocFailed ) goto trigger_cleanup;
  127951. assert( pTableName->nSrc==1 );
  127952. sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName);
  127953. if( sqlite3FixSrcList(&sFix, pTableName) ){
  127954. goto trigger_cleanup;
  127955. }
  127956. pTab = sqlite3SrcListLookup(pParse, pTableName);
  127957. if( !pTab ){
  127958. /* The table does not exist. */
  127959. if( db->init.iDb==1 ){
  127960. /* Ticket #3810.
  127961. ** Normally, whenever a table is dropped, all associated triggers are
  127962. ** dropped too. But if a TEMP trigger is created on a non-TEMP table
  127963. ** and the table is dropped by a different database connection, the
  127964. ** trigger is not visible to the database connection that does the
  127965. ** drop so the trigger cannot be dropped. This results in an
  127966. ** "orphaned trigger" - a trigger whose associated table is missing.
  127967. */
  127968. db->init.orphanTrigger = 1;
  127969. }
  127970. goto trigger_cleanup;
  127971. }
  127972. if( IsVirtual(pTab) ){
  127973. sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
  127974. goto trigger_cleanup;
  127975. }
  127976. /* Check that the trigger name is not reserved and that no trigger of the
  127977. ** specified name exists */
  127978. zName = sqlite3NameFromToken(db, pName);
  127979. if( zName==0 ){
  127980. assert( db->mallocFailed );
  127981. goto trigger_cleanup;
  127982. }
  127983. if( sqlite3CheckObjectName(pParse, zName, "trigger", pTab->zName) ){
  127984. goto trigger_cleanup;
  127985. }
  127986. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  127987. if( !IN_RENAME_OBJECT ){
  127988. if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),zName) ){
  127989. if( !noErr ){
  127990. sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
  127991. }else{
  127992. assert( !db->init.busy );
  127993. sqlite3CodeVerifySchema(pParse, iDb);
  127994. }
  127995. goto trigger_cleanup;
  127996. }
  127997. }
  127998. /* Do not create a trigger on a system table */
  127999. if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
  128000. sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
  128001. goto trigger_cleanup;
  128002. }
  128003. /* INSTEAD of triggers are only for views and views only support INSTEAD
  128004. ** of triggers.
  128005. */
  128006. if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
  128007. sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S",
  128008. (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
  128009. goto trigger_cleanup;
  128010. }
  128011. if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
  128012. sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
  128013. " trigger on table: %S", pTableName, 0);
  128014. goto trigger_cleanup;
  128015. }
  128016. #ifndef SQLITE_OMIT_AUTHORIZATION
  128017. if( !IN_RENAME_OBJECT ){
  128018. int iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  128019. int code = SQLITE_CREATE_TRIGGER;
  128020. const char *zDb = db->aDb[iTabDb].zDbSName;
  128021. const char *zDbTrig = isTemp ? db->aDb[1].zDbSName : zDb;
  128022. if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
  128023. if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
  128024. goto trigger_cleanup;
  128025. }
  128026. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
  128027. goto trigger_cleanup;
  128028. }
  128029. }
  128030. #endif
  128031. /* INSTEAD OF triggers can only appear on views and BEFORE triggers
  128032. ** cannot appear on views. So we might as well translate every
  128033. ** INSTEAD OF trigger into a BEFORE trigger. It simplifies code
  128034. ** elsewhere.
  128035. */
  128036. if (tr_tm == TK_INSTEAD){
  128037. tr_tm = TK_BEFORE;
  128038. }
  128039. /* Build the Trigger object */
  128040. pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
  128041. if( pTrigger==0 ) goto trigger_cleanup;
  128042. pTrigger->zName = zName;
  128043. zName = 0;
  128044. pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
  128045. pTrigger->pSchema = db->aDb[iDb].pSchema;
  128046. pTrigger->pTabSchema = pTab->pSchema;
  128047. pTrigger->op = (u8)op;
  128048. pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
  128049. if( IN_RENAME_OBJECT ){
  128050. sqlite3RenameTokenRemap(pParse, pTrigger->table, pTableName->a[0].zName);
  128051. pTrigger->pWhen = pWhen;
  128052. pWhen = 0;
  128053. }else{
  128054. pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
  128055. }
  128056. pTrigger->pColumns = pColumns;
  128057. pColumns = 0;
  128058. assert( pParse->pNewTrigger==0 );
  128059. pParse->pNewTrigger = pTrigger;
  128060. trigger_cleanup:
  128061. sqlite3DbFree(db, zName);
  128062. sqlite3SrcListDelete(db, pTableName);
  128063. sqlite3IdListDelete(db, pColumns);
  128064. sqlite3ExprDelete(db, pWhen);
  128065. if( !pParse->pNewTrigger ){
  128066. sqlite3DeleteTrigger(db, pTrigger);
  128067. }else{
  128068. assert( pParse->pNewTrigger==pTrigger );
  128069. }
  128070. }
  128071. /*
  128072. ** This routine is called after all of the trigger actions have been parsed
  128073. ** in order to complete the process of building the trigger.
  128074. */
  128075. SQLITE_PRIVATE void sqlite3FinishTrigger(
  128076. Parse *pParse, /* Parser context */
  128077. TriggerStep *pStepList, /* The triggered program */
  128078. Token *pAll /* Token that describes the complete CREATE TRIGGER */
  128079. ){
  128080. Trigger *pTrig = pParse->pNewTrigger; /* Trigger being finished */
  128081. char *zName; /* Name of trigger */
  128082. sqlite3 *db = pParse->db; /* The database */
  128083. DbFixer sFix; /* Fixer object */
  128084. int iDb; /* Database containing the trigger */
  128085. Token nameToken; /* Trigger name for error reporting */
  128086. pParse->pNewTrigger = 0;
  128087. if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
  128088. zName = pTrig->zName;
  128089. iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
  128090. pTrig->step_list = pStepList;
  128091. while( pStepList ){
  128092. pStepList->pTrig = pTrig;
  128093. pStepList = pStepList->pNext;
  128094. }
  128095. sqlite3TokenInit(&nameToken, pTrig->zName);
  128096. sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken);
  128097. if( sqlite3FixTriggerStep(&sFix, pTrig->step_list)
  128098. || sqlite3FixExpr(&sFix, pTrig->pWhen)
  128099. ){
  128100. goto triggerfinish_cleanup;
  128101. }
  128102. #ifndef SQLITE_OMIT_ALTERTABLE
  128103. if( IN_RENAME_OBJECT ){
  128104. assert( !db->init.busy );
  128105. pParse->pNewTrigger = pTrig;
  128106. pTrig = 0;
  128107. }else
  128108. #endif
  128109. /* if we are not initializing,
  128110. ** build the sqlite_master entry
  128111. */
  128112. if( !db->init.busy ){
  128113. Vdbe *v;
  128114. char *z;
  128115. /* Make an entry in the sqlite_master table */
  128116. v = sqlite3GetVdbe(pParse);
  128117. if( v==0 ) goto triggerfinish_cleanup;
  128118. sqlite3BeginWriteOperation(pParse, 0, iDb);
  128119. z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
  128120. testcase( z==0 );
  128121. sqlite3NestedParse(pParse,
  128122. "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
  128123. db->aDb[iDb].zDbSName, MASTER_NAME, zName,
  128124. pTrig->table, z);
  128125. sqlite3DbFree(db, z);
  128126. sqlite3ChangeCookie(pParse, iDb);
  128127. sqlite3VdbeAddParseSchemaOp(v, iDb,
  128128. sqlite3MPrintf(db, "type='trigger' AND name='%q'", zName));
  128129. }
  128130. if( db->init.busy ){
  128131. Trigger *pLink = pTrig;
  128132. Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
  128133. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  128134. assert( pLink!=0 );
  128135. pTrig = sqlite3HashInsert(pHash, zName, pTrig);
  128136. if( pTrig ){
  128137. sqlite3OomFault(db);
  128138. }else if( pLink->pSchema==pLink->pTabSchema ){
  128139. Table *pTab;
  128140. pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table);
  128141. assert( pTab!=0 );
  128142. pLink->pNext = pTab->pTrigger;
  128143. pTab->pTrigger = pLink;
  128144. }
  128145. }
  128146. triggerfinish_cleanup:
  128147. sqlite3DeleteTrigger(db, pTrig);
  128148. assert( IN_RENAME_OBJECT || !pParse->pNewTrigger );
  128149. sqlite3DeleteTriggerStep(db, pStepList);
  128150. }
  128151. /*
  128152. ** Duplicate a range of text from an SQL statement, then convert all
  128153. ** whitespace characters into ordinary space characters.
  128154. */
  128155. static char *triggerSpanDup(sqlite3 *db, const char *zStart, const char *zEnd){
  128156. char *z = sqlite3DbSpanDup(db, zStart, zEnd);
  128157. int i;
  128158. if( z ) for(i=0; z[i]; i++) if( sqlite3Isspace(z[i]) ) z[i] = ' ';
  128159. return z;
  128160. }
  128161. /*
  128162. ** Turn a SELECT statement (that the pSelect parameter points to) into
  128163. ** a trigger step. Return a pointer to a TriggerStep structure.
  128164. **
  128165. ** The parser calls this routine when it finds a SELECT statement in
  128166. ** body of a TRIGGER.
  128167. */
  128168. SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(
  128169. sqlite3 *db, /* Database connection */
  128170. Select *pSelect, /* The SELECT statement */
  128171. const char *zStart, /* Start of SQL text */
  128172. const char *zEnd /* End of SQL text */
  128173. ){
  128174. TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
  128175. if( pTriggerStep==0 ) {
  128176. sqlite3SelectDelete(db, pSelect);
  128177. return 0;
  128178. }
  128179. pTriggerStep->op = TK_SELECT;
  128180. pTriggerStep->pSelect = pSelect;
  128181. pTriggerStep->orconf = OE_Default;
  128182. pTriggerStep->zSpan = triggerSpanDup(db, zStart, zEnd);
  128183. return pTriggerStep;
  128184. }
  128185. /*
  128186. ** Allocate space to hold a new trigger step. The allocated space
  128187. ** holds both the TriggerStep object and the TriggerStep.target.z string.
  128188. **
  128189. ** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
  128190. */
  128191. static TriggerStep *triggerStepAllocate(
  128192. Parse *pParse, /* Parser context */
  128193. u8 op, /* Trigger opcode */
  128194. Token *pName, /* The target name */
  128195. const char *zStart, /* Start of SQL text */
  128196. const char *zEnd /* End of SQL text */
  128197. ){
  128198. sqlite3 *db = pParse->db;
  128199. TriggerStep *pTriggerStep;
  128200. pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n + 1);
  128201. if( pTriggerStep ){
  128202. char *z = (char*)&pTriggerStep[1];
  128203. memcpy(z, pName->z, pName->n);
  128204. sqlite3Dequote(z);
  128205. pTriggerStep->zTarget = z;
  128206. pTriggerStep->op = op;
  128207. pTriggerStep->zSpan = triggerSpanDup(db, zStart, zEnd);
  128208. if( IN_RENAME_OBJECT ){
  128209. sqlite3RenameTokenMap(pParse, pTriggerStep->zTarget, pName);
  128210. }
  128211. }
  128212. return pTriggerStep;
  128213. }
  128214. /*
  128215. ** Build a trigger step out of an INSERT statement. Return a pointer
  128216. ** to the new trigger step.
  128217. **
  128218. ** The parser calls this routine when it sees an INSERT inside the
  128219. ** body of a trigger.
  128220. */
  128221. SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(
  128222. Parse *pParse, /* Parser */
  128223. Token *pTableName, /* Name of the table into which we insert */
  128224. IdList *pColumn, /* List of columns in pTableName to insert into */
  128225. Select *pSelect, /* A SELECT statement that supplies values */
  128226. u8 orconf, /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
  128227. Upsert *pUpsert, /* ON CONFLICT clauses for upsert */
  128228. const char *zStart, /* Start of SQL text */
  128229. const char *zEnd /* End of SQL text */
  128230. ){
  128231. sqlite3 *db = pParse->db;
  128232. TriggerStep *pTriggerStep;
  128233. assert(pSelect != 0 || db->mallocFailed);
  128234. pTriggerStep = triggerStepAllocate(pParse, TK_INSERT, pTableName,zStart,zEnd);
  128235. if( pTriggerStep ){
  128236. if( IN_RENAME_OBJECT ){
  128237. pTriggerStep->pSelect = pSelect;
  128238. pSelect = 0;
  128239. }else{
  128240. pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
  128241. }
  128242. pTriggerStep->pIdList = pColumn;
  128243. pTriggerStep->pUpsert = pUpsert;
  128244. pTriggerStep->orconf = orconf;
  128245. if( pUpsert ){
  128246. sqlite3HasExplicitNulls(pParse, pUpsert->pUpsertTarget);
  128247. }
  128248. }else{
  128249. testcase( pColumn );
  128250. sqlite3IdListDelete(db, pColumn);
  128251. testcase( pUpsert );
  128252. sqlite3UpsertDelete(db, pUpsert);
  128253. }
  128254. sqlite3SelectDelete(db, pSelect);
  128255. return pTriggerStep;
  128256. }
  128257. /*
  128258. ** Construct a trigger step that implements an UPDATE statement and return
  128259. ** a pointer to that trigger step. The parser calls this routine when it
  128260. ** sees an UPDATE statement inside the body of a CREATE TRIGGER.
  128261. */
  128262. SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(
  128263. Parse *pParse, /* Parser */
  128264. Token *pTableName, /* Name of the table to be updated */
  128265. ExprList *pEList, /* The SET clause: list of column and new values */
  128266. Expr *pWhere, /* The WHERE clause */
  128267. u8 orconf, /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
  128268. const char *zStart, /* Start of SQL text */
  128269. const char *zEnd /* End of SQL text */
  128270. ){
  128271. sqlite3 *db = pParse->db;
  128272. TriggerStep *pTriggerStep;
  128273. pTriggerStep = triggerStepAllocate(pParse, TK_UPDATE, pTableName,zStart,zEnd);
  128274. if( pTriggerStep ){
  128275. if( IN_RENAME_OBJECT ){
  128276. pTriggerStep->pExprList = pEList;
  128277. pTriggerStep->pWhere = pWhere;
  128278. pEList = 0;
  128279. pWhere = 0;
  128280. }else{
  128281. pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
  128282. pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
  128283. }
  128284. pTriggerStep->orconf = orconf;
  128285. }
  128286. sqlite3ExprListDelete(db, pEList);
  128287. sqlite3ExprDelete(db, pWhere);
  128288. return pTriggerStep;
  128289. }
  128290. /*
  128291. ** Construct a trigger step that implements a DELETE statement and return
  128292. ** a pointer to that trigger step. The parser calls this routine when it
  128293. ** sees a DELETE statement inside the body of a CREATE TRIGGER.
  128294. */
  128295. SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(
  128296. Parse *pParse, /* Parser */
  128297. Token *pTableName, /* The table from which rows are deleted */
  128298. Expr *pWhere, /* The WHERE clause */
  128299. const char *zStart, /* Start of SQL text */
  128300. const char *zEnd /* End of SQL text */
  128301. ){
  128302. sqlite3 *db = pParse->db;
  128303. TriggerStep *pTriggerStep;
  128304. pTriggerStep = triggerStepAllocate(pParse, TK_DELETE, pTableName,zStart,zEnd);
  128305. if( pTriggerStep ){
  128306. if( IN_RENAME_OBJECT ){
  128307. pTriggerStep->pWhere = pWhere;
  128308. pWhere = 0;
  128309. }else{
  128310. pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
  128311. }
  128312. pTriggerStep->orconf = OE_Default;
  128313. }
  128314. sqlite3ExprDelete(db, pWhere);
  128315. return pTriggerStep;
  128316. }
  128317. /*
  128318. ** Recursively delete a Trigger structure
  128319. */
  128320. SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
  128321. if( pTrigger==0 ) return;
  128322. sqlite3DeleteTriggerStep(db, pTrigger->step_list);
  128323. sqlite3DbFree(db, pTrigger->zName);
  128324. sqlite3DbFree(db, pTrigger->table);
  128325. sqlite3ExprDelete(db, pTrigger->pWhen);
  128326. sqlite3IdListDelete(db, pTrigger->pColumns);
  128327. sqlite3DbFree(db, pTrigger);
  128328. }
  128329. /*
  128330. ** This function is called to drop a trigger from the database schema.
  128331. **
  128332. ** This may be called directly from the parser and therefore identifies
  128333. ** the trigger by name. The sqlite3DropTriggerPtr() routine does the
  128334. ** same job as this routine except it takes a pointer to the trigger
  128335. ** instead of the trigger name.
  128336. **/
  128337. SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
  128338. Trigger *pTrigger = 0;
  128339. int i;
  128340. const char *zDb;
  128341. const char *zName;
  128342. sqlite3 *db = pParse->db;
  128343. if( db->mallocFailed ) goto drop_trigger_cleanup;
  128344. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  128345. goto drop_trigger_cleanup;
  128346. }
  128347. assert( pName->nSrc==1 );
  128348. zDb = pName->a[0].zDatabase;
  128349. zName = pName->a[0].zName;
  128350. assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
  128351. for(i=OMIT_TEMPDB; i<db->nDb; i++){
  128352. int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
  128353. if( zDb && sqlite3DbIsNamed(db, j, zDb)==0 ) continue;
  128354. assert( sqlite3SchemaMutexHeld(db, j, 0) );
  128355. pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName);
  128356. if( pTrigger ) break;
  128357. }
  128358. if( !pTrigger ){
  128359. if( !noErr ){
  128360. sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
  128361. }else{
  128362. sqlite3CodeVerifyNamedSchema(pParse, zDb);
  128363. }
  128364. pParse->checkSchema = 1;
  128365. goto drop_trigger_cleanup;
  128366. }
  128367. sqlite3DropTriggerPtr(pParse, pTrigger);
  128368. drop_trigger_cleanup:
  128369. sqlite3SrcListDelete(db, pName);
  128370. }
  128371. /*
  128372. ** Return a pointer to the Table structure for the table that a trigger
  128373. ** is set on.
  128374. */
  128375. static Table *tableOfTrigger(Trigger *pTrigger){
  128376. return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table);
  128377. }
  128378. /*
  128379. ** Drop a trigger given a pointer to that trigger.
  128380. */
  128381. SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
  128382. Table *pTable;
  128383. Vdbe *v;
  128384. sqlite3 *db = pParse->db;
  128385. int iDb;
  128386. iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
  128387. assert( iDb>=0 && iDb<db->nDb );
  128388. pTable = tableOfTrigger(pTrigger);
  128389. assert( (pTable && pTable->pSchema==pTrigger->pSchema) || iDb==1 );
  128390. #ifndef SQLITE_OMIT_AUTHORIZATION
  128391. if( pTable ){
  128392. int code = SQLITE_DROP_TRIGGER;
  128393. const char *zDb = db->aDb[iDb].zDbSName;
  128394. const char *zTab = SCHEMA_TABLE(iDb);
  128395. if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
  128396. if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
  128397. sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
  128398. return;
  128399. }
  128400. }
  128401. #endif
  128402. /* Generate code to destroy the database record of the trigger.
  128403. */
  128404. if( (v = sqlite3GetVdbe(pParse))!=0 ){
  128405. sqlite3NestedParse(pParse,
  128406. "DELETE FROM %Q.%s WHERE name=%Q AND type='trigger'",
  128407. db->aDb[iDb].zDbSName, MASTER_NAME, pTrigger->zName
  128408. );
  128409. sqlite3ChangeCookie(pParse, iDb);
  128410. sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
  128411. }
  128412. }
  128413. /*
  128414. ** Remove a trigger from the hash tables of the sqlite* pointer.
  128415. */
  128416. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
  128417. Trigger *pTrigger;
  128418. Hash *pHash;
  128419. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  128420. pHash = &(db->aDb[iDb].pSchema->trigHash);
  128421. pTrigger = sqlite3HashInsert(pHash, zName, 0);
  128422. if( ALWAYS(pTrigger) ){
  128423. if( pTrigger->pSchema==pTrigger->pTabSchema ){
  128424. Table *pTab = tableOfTrigger(pTrigger);
  128425. if( pTab ){
  128426. Trigger **pp;
  128427. for(pp=&pTab->pTrigger; *pp; pp=&((*pp)->pNext)){
  128428. if( *pp==pTrigger ){
  128429. *pp = (*pp)->pNext;
  128430. break;
  128431. }
  128432. }
  128433. }
  128434. }
  128435. sqlite3DeleteTrigger(db, pTrigger);
  128436. db->mDbFlags |= DBFLAG_SchemaChange;
  128437. }
  128438. }
  128439. /*
  128440. ** pEList is the SET clause of an UPDATE statement. Each entry
  128441. ** in pEList is of the format <id>=<expr>. If any of the entries
  128442. ** in pEList have an <id> which matches an identifier in pIdList,
  128443. ** then return TRUE. If pIdList==NULL, then it is considered a
  128444. ** wildcard that matches anything. Likewise if pEList==NULL then
  128445. ** it matches anything so always return true. Return false only
  128446. ** if there is no match.
  128447. */
  128448. static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){
  128449. int e;
  128450. if( pIdList==0 || NEVER(pEList==0) ) return 1;
  128451. for(e=0; e<pEList->nExpr; e++){
  128452. if( sqlite3IdListIndex(pIdList, pEList->a[e].zEName)>=0 ) return 1;
  128453. }
  128454. return 0;
  128455. }
  128456. /*
  128457. ** Return a list of all triggers on table pTab if there exists at least
  128458. ** one trigger that must be fired when an operation of type 'op' is
  128459. ** performed on the table, and, if that operation is an UPDATE, if at
  128460. ** least one of the columns in pChanges is being modified.
  128461. */
  128462. SQLITE_PRIVATE Trigger *sqlite3TriggersExist(
  128463. Parse *pParse, /* Parse context */
  128464. Table *pTab, /* The table the contains the triggers */
  128465. int op, /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
  128466. ExprList *pChanges, /* Columns that change in an UPDATE statement */
  128467. int *pMask /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
  128468. ){
  128469. int mask = 0;
  128470. Trigger *pList = 0;
  128471. Trigger *p;
  128472. if( (pParse->db->flags & SQLITE_EnableTrigger)!=0 ){
  128473. pList = sqlite3TriggerList(pParse, pTab);
  128474. }
  128475. assert( pList==0 || IsVirtual(pTab)==0 );
  128476. for(p=pList; p; p=p->pNext){
  128477. if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
  128478. mask |= p->tr_tm;
  128479. }
  128480. }
  128481. if( pMask ){
  128482. *pMask = mask;
  128483. }
  128484. return (mask ? pList : 0);
  128485. }
  128486. /*
  128487. ** Convert the pStep->zTarget string into a SrcList and return a pointer
  128488. ** to that SrcList.
  128489. **
  128490. ** This routine adds a specific database name, if needed, to the target when
  128491. ** forming the SrcList. This prevents a trigger in one database from
  128492. ** referring to a target in another database. An exception is when the
  128493. ** trigger is in TEMP in which case it can refer to any other database it
  128494. ** wants.
  128495. */
  128496. static SrcList *targetSrcList(
  128497. Parse *pParse, /* The parsing context */
  128498. TriggerStep *pStep /* The trigger containing the target token */
  128499. ){
  128500. sqlite3 *db = pParse->db;
  128501. int iDb; /* Index of the database to use */
  128502. SrcList *pSrc; /* SrcList to be returned */
  128503. pSrc = sqlite3SrcListAppend(pParse, 0, 0, 0);
  128504. if( pSrc ){
  128505. assert( pSrc->nSrc>0 );
  128506. pSrc->a[pSrc->nSrc-1].zName = sqlite3DbStrDup(db, pStep->zTarget);
  128507. iDb = sqlite3SchemaToIndex(db, pStep->pTrig->pSchema);
  128508. if( iDb==0 || iDb>=2 ){
  128509. const char *zDb;
  128510. assert( iDb<db->nDb );
  128511. zDb = db->aDb[iDb].zDbSName;
  128512. pSrc->a[pSrc->nSrc-1].zDatabase = sqlite3DbStrDup(db, zDb);
  128513. }
  128514. }
  128515. return pSrc;
  128516. }
  128517. /*
  128518. ** Generate VDBE code for the statements inside the body of a single
  128519. ** trigger.
  128520. */
  128521. static int codeTriggerProgram(
  128522. Parse *pParse, /* The parser context */
  128523. TriggerStep *pStepList, /* List of statements inside the trigger body */
  128524. int orconf /* Conflict algorithm. (OE_Abort, etc) */
  128525. ){
  128526. TriggerStep *pStep;
  128527. Vdbe *v = pParse->pVdbe;
  128528. sqlite3 *db = pParse->db;
  128529. assert( pParse->pTriggerTab && pParse->pToplevel );
  128530. assert( pStepList );
  128531. assert( v!=0 );
  128532. for(pStep=pStepList; pStep; pStep=pStep->pNext){
  128533. /* Figure out the ON CONFLICT policy that will be used for this step
  128534. ** of the trigger program. If the statement that caused this trigger
  128535. ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
  128536. ** the ON CONFLICT policy that was specified as part of the trigger
  128537. ** step statement. Example:
  128538. **
  128539. ** CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
  128540. ** INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
  128541. ** END;
  128542. **
  128543. ** INSERT INTO t1 ... ; -- insert into t2 uses REPLACE policy
  128544. ** INSERT OR IGNORE INTO t1 ... ; -- insert into t2 uses IGNORE policy
  128545. */
  128546. pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;
  128547. assert( pParse->okConstFactor==0 );
  128548. #ifndef SQLITE_OMIT_TRACE
  128549. if( pStep->zSpan ){
  128550. sqlite3VdbeAddOp4(v, OP_Trace, 0x7fffffff, 1, 0,
  128551. sqlite3MPrintf(db, "-- %s", pStep->zSpan),
  128552. P4_DYNAMIC);
  128553. }
  128554. #endif
  128555. switch( pStep->op ){
  128556. case TK_UPDATE: {
  128557. sqlite3Update(pParse,
  128558. targetSrcList(pParse, pStep),
  128559. sqlite3ExprListDup(db, pStep->pExprList, 0),
  128560. sqlite3ExprDup(db, pStep->pWhere, 0),
  128561. pParse->eOrconf, 0, 0, 0
  128562. );
  128563. break;
  128564. }
  128565. case TK_INSERT: {
  128566. sqlite3Insert(pParse,
  128567. targetSrcList(pParse, pStep),
  128568. sqlite3SelectDup(db, pStep->pSelect, 0),
  128569. sqlite3IdListDup(db, pStep->pIdList),
  128570. pParse->eOrconf,
  128571. sqlite3UpsertDup(db, pStep->pUpsert)
  128572. );
  128573. break;
  128574. }
  128575. case TK_DELETE: {
  128576. sqlite3DeleteFrom(pParse,
  128577. targetSrcList(pParse, pStep),
  128578. sqlite3ExprDup(db, pStep->pWhere, 0), 0, 0
  128579. );
  128580. break;
  128581. }
  128582. default: assert( pStep->op==TK_SELECT ); {
  128583. SelectDest sDest;
  128584. Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);
  128585. sqlite3SelectDestInit(&sDest, SRT_Discard, 0);
  128586. sqlite3Select(pParse, pSelect, &sDest);
  128587. sqlite3SelectDelete(db, pSelect);
  128588. break;
  128589. }
  128590. }
  128591. if( pStep->op!=TK_SELECT ){
  128592. sqlite3VdbeAddOp0(v, OP_ResetCount);
  128593. }
  128594. }
  128595. return 0;
  128596. }
  128597. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  128598. /*
  128599. ** This function is used to add VdbeComment() annotations to a VDBE
  128600. ** program. It is not used in production code, only for debugging.
  128601. */
  128602. static const char *onErrorText(int onError){
  128603. switch( onError ){
  128604. case OE_Abort: return "abort";
  128605. case OE_Rollback: return "rollback";
  128606. case OE_Fail: return "fail";
  128607. case OE_Replace: return "replace";
  128608. case OE_Ignore: return "ignore";
  128609. case OE_Default: return "default";
  128610. }
  128611. return "n/a";
  128612. }
  128613. #endif
  128614. /*
  128615. ** Parse context structure pFrom has just been used to create a sub-vdbe
  128616. ** (trigger program). If an error has occurred, transfer error information
  128617. ** from pFrom to pTo.
  128618. */
  128619. static void transferParseError(Parse *pTo, Parse *pFrom){
  128620. assert( pFrom->zErrMsg==0 || pFrom->nErr );
  128621. assert( pTo->zErrMsg==0 || pTo->nErr );
  128622. if( pTo->nErr==0 ){
  128623. pTo->zErrMsg = pFrom->zErrMsg;
  128624. pTo->nErr = pFrom->nErr;
  128625. pTo->rc = pFrom->rc;
  128626. }else{
  128627. sqlite3DbFree(pFrom->db, pFrom->zErrMsg);
  128628. }
  128629. }
  128630. /*
  128631. ** Create and populate a new TriggerPrg object with a sub-program
  128632. ** implementing trigger pTrigger with ON CONFLICT policy orconf.
  128633. */
  128634. static TriggerPrg *codeRowTrigger(
  128635. Parse *pParse, /* Current parse context */
  128636. Trigger *pTrigger, /* Trigger to code */
  128637. Table *pTab, /* The table pTrigger is attached to */
  128638. int orconf /* ON CONFLICT policy to code trigger program with */
  128639. ){
  128640. Parse *pTop = sqlite3ParseToplevel(pParse);
  128641. sqlite3 *db = pParse->db; /* Database handle */
  128642. TriggerPrg *pPrg; /* Value to return */
  128643. Expr *pWhen = 0; /* Duplicate of trigger WHEN expression */
  128644. Vdbe *v; /* Temporary VM */
  128645. NameContext sNC; /* Name context for sub-vdbe */
  128646. SubProgram *pProgram = 0; /* Sub-vdbe for trigger program */
  128647. Parse *pSubParse; /* Parse context for sub-vdbe */
  128648. int iEndTrigger = 0; /* Label to jump to if WHEN is false */
  128649. assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
  128650. assert( pTop->pVdbe );
  128651. /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
  128652. ** are freed if an error occurs, link them into the Parse.pTriggerPrg
  128653. ** list of the top-level Parse object sooner rather than later. */
  128654. pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
  128655. if( !pPrg ) return 0;
  128656. pPrg->pNext = pTop->pTriggerPrg;
  128657. pTop->pTriggerPrg = pPrg;
  128658. pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
  128659. if( !pProgram ) return 0;
  128660. sqlite3VdbeLinkSubProgram(pTop->pVdbe, pProgram);
  128661. pPrg->pTrigger = pTrigger;
  128662. pPrg->orconf = orconf;
  128663. pPrg->aColmask[0] = 0xffffffff;
  128664. pPrg->aColmask[1] = 0xffffffff;
  128665. /* Allocate and populate a new Parse context to use for coding the
  128666. ** trigger sub-program. */
  128667. pSubParse = sqlite3StackAllocZero(db, sizeof(Parse));
  128668. if( !pSubParse ) return 0;
  128669. memset(&sNC, 0, sizeof(sNC));
  128670. sNC.pParse = pSubParse;
  128671. pSubParse->db = db;
  128672. pSubParse->pTriggerTab = pTab;
  128673. pSubParse->pToplevel = pTop;
  128674. pSubParse->zAuthContext = pTrigger->zName;
  128675. pSubParse->eTriggerOp = pTrigger->op;
  128676. pSubParse->nQueryLoop = pParse->nQueryLoop;
  128677. pSubParse->disableVtab = pParse->disableVtab;
  128678. v = sqlite3GetVdbe(pSubParse);
  128679. if( v ){
  128680. VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)",
  128681. pTrigger->zName, onErrorText(orconf),
  128682. (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
  128683. (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
  128684. (pTrigger->op==TK_INSERT ? "INSERT" : ""),
  128685. (pTrigger->op==TK_DELETE ? "DELETE" : ""),
  128686. pTab->zName
  128687. ));
  128688. #ifndef SQLITE_OMIT_TRACE
  128689. if( pTrigger->zName ){
  128690. sqlite3VdbeChangeP4(v, -1,
  128691. sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
  128692. );
  128693. }
  128694. #endif
  128695. /* If one was specified, code the WHEN clause. If it evaluates to false
  128696. ** (or NULL) the sub-vdbe is immediately halted by jumping to the
  128697. ** OP_Halt inserted at the end of the program. */
  128698. if( pTrigger->pWhen ){
  128699. pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
  128700. if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen)
  128701. && db->mallocFailed==0
  128702. ){
  128703. iEndTrigger = sqlite3VdbeMakeLabel(pSubParse);
  128704. sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
  128705. }
  128706. sqlite3ExprDelete(db, pWhen);
  128707. }
  128708. /* Code the trigger program into the sub-vdbe. */
  128709. codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);
  128710. /* Insert an OP_Halt at the end of the sub-program. */
  128711. if( iEndTrigger ){
  128712. sqlite3VdbeResolveLabel(v, iEndTrigger);
  128713. }
  128714. sqlite3VdbeAddOp0(v, OP_Halt);
  128715. VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
  128716. transferParseError(pParse, pSubParse);
  128717. if( db->mallocFailed==0 && pParse->nErr==0 ){
  128718. pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
  128719. }
  128720. pProgram->nMem = pSubParse->nMem;
  128721. pProgram->nCsr = pSubParse->nTab;
  128722. pProgram->token = (void *)pTrigger;
  128723. pPrg->aColmask[0] = pSubParse->oldmask;
  128724. pPrg->aColmask[1] = pSubParse->newmask;
  128725. sqlite3VdbeDelete(v);
  128726. }
  128727. assert( !pSubParse->pAinc && !pSubParse->pZombieTab );
  128728. assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
  128729. sqlite3ParserReset(pSubParse);
  128730. sqlite3StackFree(db, pSubParse);
  128731. return pPrg;
  128732. }
  128733. /*
  128734. ** Return a pointer to a TriggerPrg object containing the sub-program for
  128735. ** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
  128736. ** TriggerPrg object exists, a new object is allocated and populated before
  128737. ** being returned.
  128738. */
  128739. static TriggerPrg *getRowTrigger(
  128740. Parse *pParse, /* Current parse context */
  128741. Trigger *pTrigger, /* Trigger to code */
  128742. Table *pTab, /* The table trigger pTrigger is attached to */
  128743. int orconf /* ON CONFLICT algorithm. */
  128744. ){
  128745. Parse *pRoot = sqlite3ParseToplevel(pParse);
  128746. TriggerPrg *pPrg;
  128747. assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
  128748. /* It may be that this trigger has already been coded (or is in the
  128749. ** process of being coded). If this is the case, then an entry with
  128750. ** a matching TriggerPrg.pTrigger field will be present somewhere
  128751. ** in the Parse.pTriggerPrg list. Search for such an entry. */
  128752. for(pPrg=pRoot->pTriggerPrg;
  128753. pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf);
  128754. pPrg=pPrg->pNext
  128755. );
  128756. /* If an existing TriggerPrg could not be located, create a new one. */
  128757. if( !pPrg ){
  128758. pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
  128759. }
  128760. return pPrg;
  128761. }
  128762. /*
  128763. ** Generate code for the trigger program associated with trigger p on
  128764. ** table pTab. The reg, orconf and ignoreJump parameters passed to this
  128765. ** function are the same as those described in the header function for
  128766. ** sqlite3CodeRowTrigger()
  128767. */
  128768. SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(
  128769. Parse *pParse, /* Parse context */
  128770. Trigger *p, /* Trigger to code */
  128771. Table *pTab, /* The table to code triggers from */
  128772. int reg, /* Reg array containing OLD.* and NEW.* values */
  128773. int orconf, /* ON CONFLICT policy */
  128774. int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */
  128775. ){
  128776. Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */
  128777. TriggerPrg *pPrg;
  128778. pPrg = getRowTrigger(pParse, p, pTab, orconf);
  128779. assert( pPrg || pParse->nErr || pParse->db->mallocFailed );
  128780. /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program
  128781. ** is a pointer to the sub-vdbe containing the trigger program. */
  128782. if( pPrg ){
  128783. int bRecursive = (p->zName && 0==(pParse->db->flags&SQLITE_RecTriggers));
  128784. sqlite3VdbeAddOp4(v, OP_Program, reg, ignoreJump, ++pParse->nMem,
  128785. (const char *)pPrg->pProgram, P4_SUBPROGRAM);
  128786. VdbeComment(
  128787. (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
  128788. /* Set the P5 operand of the OP_Program instruction to non-zero if
  128789. ** recursive invocation of this trigger program is disallowed. Recursive
  128790. ** invocation is disallowed if (a) the sub-program is really a trigger,
  128791. ** not a foreign key action, and (b) the flag to enable recursive triggers
  128792. ** is clear. */
  128793. sqlite3VdbeChangeP5(v, (u8)bRecursive);
  128794. }
  128795. }
  128796. /*
  128797. ** This is called to code the required FOR EACH ROW triggers for an operation
  128798. ** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
  128799. ** is given by the op parameter. The tr_tm parameter determines whether the
  128800. ** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
  128801. ** parameter pChanges is passed the list of columns being modified.
  128802. **
  128803. ** If there are no triggers that fire at the specified time for the specified
  128804. ** operation on pTab, this function is a no-op.
  128805. **
  128806. ** The reg argument is the address of the first in an array of registers
  128807. ** that contain the values substituted for the new.* and old.* references
  128808. ** in the trigger program. If N is the number of columns in table pTab
  128809. ** (a copy of pTab->nCol), then registers are populated as follows:
  128810. **
  128811. ** Register Contains
  128812. ** ------------------------------------------------------
  128813. ** reg+0 OLD.rowid
  128814. ** reg+1 OLD.* value of left-most column of pTab
  128815. ** ... ...
  128816. ** reg+N OLD.* value of right-most column of pTab
  128817. ** reg+N+1 NEW.rowid
  128818. ** reg+N+2 OLD.* value of left-most column of pTab
  128819. ** ... ...
  128820. ** reg+N+N+1 NEW.* value of right-most column of pTab
  128821. **
  128822. ** For ON DELETE triggers, the registers containing the NEW.* values will
  128823. ** never be accessed by the trigger program, so they are not allocated or
  128824. ** populated by the caller (there is no data to populate them with anyway).
  128825. ** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
  128826. ** are never accessed, and so are not allocated by the caller. So, for an
  128827. ** ON INSERT trigger, the value passed to this function as parameter reg
  128828. ** is not a readable register, although registers (reg+N) through
  128829. ** (reg+N+N+1) are.
  128830. **
  128831. ** Parameter orconf is the default conflict resolution algorithm for the
  128832. ** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump
  128833. ** is the instruction that control should jump to if a trigger program
  128834. ** raises an IGNORE exception.
  128835. */
  128836. SQLITE_PRIVATE void sqlite3CodeRowTrigger(
  128837. Parse *pParse, /* Parse context */
  128838. Trigger *pTrigger, /* List of triggers on table pTab */
  128839. int op, /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
  128840. ExprList *pChanges, /* Changes list for any UPDATE OF triggers */
  128841. int tr_tm, /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
  128842. Table *pTab, /* The table to code triggers from */
  128843. int reg, /* The first in an array of registers (see above) */
  128844. int orconf, /* ON CONFLICT policy */
  128845. int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */
  128846. ){
  128847. Trigger *p; /* Used to iterate through pTrigger list */
  128848. assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE );
  128849. assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER );
  128850. assert( (op==TK_UPDATE)==(pChanges!=0) );
  128851. for(p=pTrigger; p; p=p->pNext){
  128852. /* Sanity checking: The schema for the trigger and for the table are
  128853. ** always defined. The trigger must be in the same schema as the table
  128854. ** or else it must be a TEMP trigger. */
  128855. assert( p->pSchema!=0 );
  128856. assert( p->pTabSchema!=0 );
  128857. assert( p->pSchema==p->pTabSchema
  128858. || p->pSchema==pParse->db->aDb[1].pSchema );
  128859. /* Determine whether we should code this trigger */
  128860. if( p->op==op
  128861. && p->tr_tm==tr_tm
  128862. && checkColumnOverlap(p->pColumns, pChanges)
  128863. ){
  128864. sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
  128865. }
  128866. }
  128867. }
  128868. /*
  128869. ** Triggers may access values stored in the old.* or new.* pseudo-table.
  128870. ** This function returns a 32-bit bitmask indicating which columns of the
  128871. ** old.* or new.* tables actually are used by triggers. This information
  128872. ** may be used by the caller, for example, to avoid having to load the entire
  128873. ** old.* record into memory when executing an UPDATE or DELETE command.
  128874. **
  128875. ** Bit 0 of the returned mask is set if the left-most column of the
  128876. ** table may be accessed using an [old|new].<col> reference. Bit 1 is set if
  128877. ** the second leftmost column value is required, and so on. If there
  128878. ** are more than 32 columns in the table, and at least one of the columns
  128879. ** with an index greater than 32 may be accessed, 0xffffffff is returned.
  128880. **
  128881. ** It is not possible to determine if the old.rowid or new.rowid column is
  128882. ** accessed by triggers. The caller must always assume that it is.
  128883. **
  128884. ** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned
  128885. ** applies to the old.* table. If 1, the new.* table.
  128886. **
  128887. ** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE
  128888. ** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only
  128889. ** included in the returned mask if the TRIGGER_BEFORE bit is set in the
  128890. ** tr_tm parameter. Similarly, values accessed by AFTER triggers are only
  128891. ** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.
  128892. */
  128893. SQLITE_PRIVATE u32 sqlite3TriggerColmask(
  128894. Parse *pParse, /* Parse context */
  128895. Trigger *pTrigger, /* List of triggers on table pTab */
  128896. ExprList *pChanges, /* Changes list for any UPDATE OF triggers */
  128897. int isNew, /* 1 for new.* ref mask, 0 for old.* ref mask */
  128898. int tr_tm, /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
  128899. Table *pTab, /* The table to code triggers from */
  128900. int orconf /* Default ON CONFLICT policy for trigger steps */
  128901. ){
  128902. const int op = pChanges ? TK_UPDATE : TK_DELETE;
  128903. u32 mask = 0;
  128904. Trigger *p;
  128905. assert( isNew==1 || isNew==0 );
  128906. for(p=pTrigger; p; p=p->pNext){
  128907. if( p->op==op && (tr_tm&p->tr_tm)
  128908. && checkColumnOverlap(p->pColumns,pChanges)
  128909. ){
  128910. TriggerPrg *pPrg;
  128911. pPrg = getRowTrigger(pParse, p, pTab, orconf);
  128912. if( pPrg ){
  128913. mask |= pPrg->aColmask[isNew];
  128914. }
  128915. }
  128916. }
  128917. return mask;
  128918. }
  128919. #endif /* !defined(SQLITE_OMIT_TRIGGER) */
  128920. /************** End of trigger.c *********************************************/
  128921. /************** Begin file update.c ******************************************/
  128922. /*
  128923. ** 2001 September 15
  128924. **
  128925. ** The author disclaims copyright to this source code. In place of
  128926. ** a legal notice, here is a blessing:
  128927. **
  128928. ** May you do good and not evil.
  128929. ** May you find forgiveness for yourself and forgive others.
  128930. ** May you share freely, never taking more than you give.
  128931. **
  128932. *************************************************************************
  128933. ** This file contains C code routines that are called by the parser
  128934. ** to handle UPDATE statements.
  128935. */
  128936. /* #include "sqliteInt.h" */
  128937. #ifndef SQLITE_OMIT_VIRTUALTABLE
  128938. /* Forward declaration */
  128939. static void updateVirtualTable(
  128940. Parse *pParse, /* The parsing context */
  128941. SrcList *pSrc, /* The virtual table to be modified */
  128942. Table *pTab, /* The virtual table */
  128943. ExprList *pChanges, /* The columns to change in the UPDATE statement */
  128944. Expr *pRowidExpr, /* Expression used to recompute the rowid */
  128945. int *aXRef, /* Mapping from columns of pTab to entries in pChanges */
  128946. Expr *pWhere, /* WHERE clause of the UPDATE statement */
  128947. int onError /* ON CONFLICT strategy */
  128948. );
  128949. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  128950. /*
  128951. ** The most recently coded instruction was an OP_Column to retrieve the
  128952. ** i-th column of table pTab. This routine sets the P4 parameter of the
  128953. ** OP_Column to the default value, if any.
  128954. **
  128955. ** The default value of a column is specified by a DEFAULT clause in the
  128956. ** column definition. This was either supplied by the user when the table
  128957. ** was created, or added later to the table definition by an ALTER TABLE
  128958. ** command. If the latter, then the row-records in the table btree on disk
  128959. ** may not contain a value for the column and the default value, taken
  128960. ** from the P4 parameter of the OP_Column instruction, is returned instead.
  128961. ** If the former, then all row-records are guaranteed to include a value
  128962. ** for the column and the P4 value is not required.
  128963. **
  128964. ** Column definitions created by an ALTER TABLE command may only have
  128965. ** literal default values specified: a number, null or a string. (If a more
  128966. ** complicated default expression value was provided, it is evaluated
  128967. ** when the ALTER TABLE is executed and one of the literal values written
  128968. ** into the sqlite_master table.)
  128969. **
  128970. ** Therefore, the P4 parameter is only required if the default value for
  128971. ** the column is a literal number, string or null. The sqlite3ValueFromExpr()
  128972. ** function is capable of transforming these types of expressions into
  128973. ** sqlite3_value objects.
  128974. **
  128975. ** If column as REAL affinity and the table is an ordinary b-tree table
  128976. ** (not a virtual table) then the value might have been stored as an
  128977. ** integer. In that case, add an OP_RealAffinity opcode to make sure
  128978. ** it has been converted into REAL.
  128979. */
  128980. SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){
  128981. assert( pTab!=0 );
  128982. if( !pTab->pSelect ){
  128983. sqlite3_value *pValue = 0;
  128984. u8 enc = ENC(sqlite3VdbeDb(v));
  128985. Column *pCol = &pTab->aCol[i];
  128986. VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
  128987. assert( i<pTab->nCol );
  128988. sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc,
  128989. pCol->affinity, &pValue);
  128990. if( pValue ){
  128991. sqlite3VdbeAppendP4(v, pValue, P4_MEM);
  128992. }
  128993. }
  128994. #ifndef SQLITE_OMIT_FLOATING_POINT
  128995. if( pTab->aCol[i].affinity==SQLITE_AFF_REAL && !IsVirtual(pTab) ){
  128996. sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
  128997. }
  128998. #endif
  128999. }
  129000. /*
  129001. ** Check to see if column iCol of index pIdx references any of the
  129002. ** columns defined by aXRef and chngRowid. Return true if it does
  129003. ** and false if not. This is an optimization. False-positives are a
  129004. ** performance degradation, but false-negatives can result in a corrupt
  129005. ** index and incorrect answers.
  129006. **
  129007. ** aXRef[j] will be non-negative if column j of the original table is
  129008. ** being updated. chngRowid will be true if the rowid of the table is
  129009. ** being updated.
  129010. */
  129011. static int indexColumnIsBeingUpdated(
  129012. Index *pIdx, /* The index to check */
  129013. int iCol, /* Which column of the index to check */
  129014. int *aXRef, /* aXRef[j]>=0 if column j is being updated */
  129015. int chngRowid /* true if the rowid is being updated */
  129016. ){
  129017. i16 iIdxCol = pIdx->aiColumn[iCol];
  129018. assert( iIdxCol!=XN_ROWID ); /* Cannot index rowid */
  129019. if( iIdxCol>=0 ){
  129020. return aXRef[iIdxCol]>=0;
  129021. }
  129022. assert( iIdxCol==XN_EXPR );
  129023. assert( pIdx->aColExpr!=0 );
  129024. assert( pIdx->aColExpr->a[iCol].pExpr!=0 );
  129025. return sqlite3ExprReferencesUpdatedColumn(pIdx->aColExpr->a[iCol].pExpr,
  129026. aXRef,chngRowid);
  129027. }
  129028. /*
  129029. ** Check to see if index pIdx is a partial index whose conditional
  129030. ** expression might change values due to an UPDATE. Return true if
  129031. ** the index is subject to change and false if the index is guaranteed
  129032. ** to be unchanged. This is an optimization. False-positives are a
  129033. ** performance degradation, but false-negatives can result in a corrupt
  129034. ** index and incorrect answers.
  129035. **
  129036. ** aXRef[j] will be non-negative if column j of the original table is
  129037. ** being updated. chngRowid will be true if the rowid of the table is
  129038. ** being updated.
  129039. */
  129040. static int indexWhereClauseMightChange(
  129041. Index *pIdx, /* The index to check */
  129042. int *aXRef, /* aXRef[j]>=0 if column j is being updated */
  129043. int chngRowid /* true if the rowid is being updated */
  129044. ){
  129045. if( pIdx->pPartIdxWhere==0 ) return 0;
  129046. return sqlite3ExprReferencesUpdatedColumn(pIdx->pPartIdxWhere,
  129047. aXRef, chngRowid);
  129048. }
  129049. /*
  129050. ** Process an UPDATE statement.
  129051. **
  129052. ** UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
  129053. ** \_______/ \________/ \______/ \________________/
  129054. * onError pTabList pChanges pWhere
  129055. */
  129056. SQLITE_PRIVATE void sqlite3Update(
  129057. Parse *pParse, /* The parser context */
  129058. SrcList *pTabList, /* The table in which we should change things */
  129059. ExprList *pChanges, /* Things to be changed */
  129060. Expr *pWhere, /* The WHERE clause. May be null */
  129061. int onError, /* How to handle constraint errors */
  129062. ExprList *pOrderBy, /* ORDER BY clause. May be null */
  129063. Expr *pLimit, /* LIMIT clause. May be null */
  129064. Upsert *pUpsert /* ON CONFLICT clause, or null */
  129065. ){
  129066. int i, j, k; /* Loop counters */
  129067. Table *pTab; /* The table to be updated */
  129068. int addrTop = 0; /* VDBE instruction address of the start of the loop */
  129069. WhereInfo *pWInfo; /* Information about the WHERE clause */
  129070. Vdbe *v; /* The virtual database engine */
  129071. Index *pIdx; /* For looping over indices */
  129072. Index *pPk; /* The PRIMARY KEY index for WITHOUT ROWID tables */
  129073. int nIdx; /* Number of indices that need updating */
  129074. int nAllIdx; /* Total number of indexes */
  129075. int iBaseCur; /* Base cursor number */
  129076. int iDataCur; /* Cursor for the canonical data btree */
  129077. int iIdxCur; /* Cursor for the first index */
  129078. sqlite3 *db; /* The database structure */
  129079. int *aRegIdx = 0; /* Registers for to each index and the main table */
  129080. int *aXRef = 0; /* aXRef[i] is the index in pChanges->a[] of the
  129081. ** an expression for the i-th column of the table.
  129082. ** aXRef[i]==-1 if the i-th column is not changed. */
  129083. u8 *aToOpen; /* 1 for tables and indices to be opened */
  129084. u8 chngPk; /* PRIMARY KEY changed in a WITHOUT ROWID table */
  129085. u8 chngRowid; /* Rowid changed in a normal table */
  129086. u8 chngKey; /* Either chngPk or chngRowid */
  129087. Expr *pRowidExpr = 0; /* Expression defining the new record number */
  129088. AuthContext sContext; /* The authorization context */
  129089. NameContext sNC; /* The name-context to resolve expressions in */
  129090. int iDb; /* Database containing the table being updated */
  129091. int eOnePass; /* ONEPASS_XXX value from where.c */
  129092. int hasFK; /* True if foreign key processing is required */
  129093. int labelBreak; /* Jump here to break out of UPDATE loop */
  129094. int labelContinue; /* Jump here to continue next step of UPDATE loop */
  129095. int flags; /* Flags for sqlite3WhereBegin() */
  129096. #ifndef SQLITE_OMIT_TRIGGER
  129097. int isView; /* True when updating a view (INSTEAD OF trigger) */
  129098. Trigger *pTrigger; /* List of triggers on pTab, if required */
  129099. int tmask; /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
  129100. #endif
  129101. int newmask; /* Mask of NEW.* columns accessed by BEFORE triggers */
  129102. int iEph = 0; /* Ephemeral table holding all primary key values */
  129103. int nKey = 0; /* Number of elements in regKey for WITHOUT ROWID */
  129104. int aiCurOnePass[2]; /* The write cursors opened by WHERE_ONEPASS */
  129105. int addrOpen = 0; /* Address of OP_OpenEphemeral */
  129106. int iPk = 0; /* First of nPk cells holding PRIMARY KEY value */
  129107. i16 nPk = 0; /* Number of components of the PRIMARY KEY */
  129108. int bReplace = 0; /* True if REPLACE conflict resolution might happen */
  129109. int bFinishSeek = 1; /* The OP_FinishSeek opcode is needed */
  129110. /* Register Allocations */
  129111. int regRowCount = 0; /* A count of rows changed */
  129112. int regOldRowid = 0; /* The old rowid */
  129113. int regNewRowid = 0; /* The new rowid */
  129114. int regNew = 0; /* Content of the NEW.* table in triggers */
  129115. int regOld = 0; /* Content of OLD.* table in triggers */
  129116. int regRowSet = 0; /* Rowset of rows to be updated */
  129117. int regKey = 0; /* composite PRIMARY KEY value */
  129118. memset(&sContext, 0, sizeof(sContext));
  129119. db = pParse->db;
  129120. if( pParse->nErr || db->mallocFailed ){
  129121. goto update_cleanup;
  129122. }
  129123. assert( pTabList->nSrc==1 );
  129124. /* Locate the table which we want to update.
  129125. */
  129126. pTab = sqlite3SrcListLookup(pParse, pTabList);
  129127. if( pTab==0 ) goto update_cleanup;
  129128. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  129129. /* Figure out if we have any triggers and if the table being
  129130. ** updated is a view.
  129131. */
  129132. #ifndef SQLITE_OMIT_TRIGGER
  129133. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask);
  129134. isView = pTab->pSelect!=0;
  129135. assert( pTrigger || tmask==0 );
  129136. #else
  129137. # define pTrigger 0
  129138. # define isView 0
  129139. # define tmask 0
  129140. #endif
  129141. #ifdef SQLITE_OMIT_VIEW
  129142. # undef isView
  129143. # define isView 0
  129144. #endif
  129145. #ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
  129146. if( !isView ){
  129147. pWhere = sqlite3LimitWhere(
  129148. pParse, pTabList, pWhere, pOrderBy, pLimit, "UPDATE"
  129149. );
  129150. pOrderBy = 0;
  129151. pLimit = 0;
  129152. }
  129153. #endif
  129154. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  129155. goto update_cleanup;
  129156. }
  129157. if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
  129158. goto update_cleanup;
  129159. }
  129160. /* Allocate a cursors for the main database table and for all indices.
  129161. ** The index cursors might not be used, but if they are used they
  129162. ** need to occur right after the database cursor. So go ahead and
  129163. ** allocate enough space, just in case.
  129164. */
  129165. iBaseCur = iDataCur = pParse->nTab++;
  129166. iIdxCur = iDataCur+1;
  129167. pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
  129168. testcase( pPk!=0 && pPk!=pTab->pIndex );
  129169. for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
  129170. if( pPk==pIdx ){
  129171. iDataCur = pParse->nTab;
  129172. }
  129173. pParse->nTab++;
  129174. }
  129175. if( pUpsert ){
  129176. /* On an UPSERT, reuse the same cursors already opened by INSERT */
  129177. iDataCur = pUpsert->iDataCur;
  129178. iIdxCur = pUpsert->iIdxCur;
  129179. pParse->nTab = iBaseCur;
  129180. }
  129181. pTabList->a[0].iCursor = iDataCur;
  129182. /* Allocate space for aXRef[], aRegIdx[], and aToOpen[].
  129183. ** Initialize aXRef[] and aToOpen[] to their default values.
  129184. */
  129185. aXRef = sqlite3DbMallocRawNN(db, sizeof(int) * (pTab->nCol+nIdx+1) + nIdx+2 );
  129186. if( aXRef==0 ) goto update_cleanup;
  129187. aRegIdx = aXRef+pTab->nCol;
  129188. aToOpen = (u8*)(aRegIdx+nIdx+1);
  129189. memset(aToOpen, 1, nIdx+1);
  129190. aToOpen[nIdx+1] = 0;
  129191. for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
  129192. /* Initialize the name-context */
  129193. memset(&sNC, 0, sizeof(sNC));
  129194. sNC.pParse = pParse;
  129195. sNC.pSrcList = pTabList;
  129196. sNC.uNC.pUpsert = pUpsert;
  129197. sNC.ncFlags = NC_UUpsert;
  129198. /* Begin generating code. */
  129199. v = sqlite3GetVdbe(pParse);
  129200. if( v==0 ) goto update_cleanup;
  129201. /* Resolve the column names in all the expressions of the
  129202. ** of the UPDATE statement. Also find the column index
  129203. ** for each column to be updated in the pChanges array. For each
  129204. ** column to be updated, make sure we have authorization to change
  129205. ** that column.
  129206. */
  129207. chngRowid = chngPk = 0;
  129208. for(i=0; i<pChanges->nExpr; i++){
  129209. if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
  129210. goto update_cleanup;
  129211. }
  129212. for(j=0; j<pTab->nCol; j++){
  129213. if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zEName)==0 ){
  129214. if( j==pTab->iPKey ){
  129215. chngRowid = 1;
  129216. pRowidExpr = pChanges->a[i].pExpr;
  129217. }else if( pPk && (pTab->aCol[j].colFlags & COLFLAG_PRIMKEY)!=0 ){
  129218. chngPk = 1;
  129219. }
  129220. #ifndef SQLITE_OMIT_GENERATED_COLUMNS
  129221. else if( pTab->aCol[j].colFlags & COLFLAG_GENERATED ){
  129222. testcase( pTab->aCol[j].colFlags & COLFLAG_VIRTUAL );
  129223. testcase( pTab->aCol[j].colFlags & COLFLAG_STORED );
  129224. sqlite3ErrorMsg(pParse,
  129225. "cannot UPDATE generated column \"%s\"",
  129226. pTab->aCol[j].zName);
  129227. goto update_cleanup;
  129228. }
  129229. #endif
  129230. aXRef[j] = i;
  129231. break;
  129232. }
  129233. }
  129234. if( j>=pTab->nCol ){
  129235. if( pPk==0 && sqlite3IsRowid(pChanges->a[i].zEName) ){
  129236. j = -1;
  129237. chngRowid = 1;
  129238. pRowidExpr = pChanges->a[i].pExpr;
  129239. }else{
  129240. sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zEName);
  129241. pParse->checkSchema = 1;
  129242. goto update_cleanup;
  129243. }
  129244. }
  129245. #ifndef SQLITE_OMIT_AUTHORIZATION
  129246. {
  129247. int rc;
  129248. rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
  129249. j<0 ? "ROWID" : pTab->aCol[j].zName,
  129250. db->aDb[iDb].zDbSName);
  129251. if( rc==SQLITE_DENY ){
  129252. goto update_cleanup;
  129253. }else if( rc==SQLITE_IGNORE ){
  129254. aXRef[j] = -1;
  129255. }
  129256. }
  129257. #endif
  129258. }
  129259. assert( (chngRowid & chngPk)==0 );
  129260. assert( chngRowid==0 || chngRowid==1 );
  129261. assert( chngPk==0 || chngPk==1 );
  129262. chngKey = chngRowid + chngPk;
  129263. #ifndef SQLITE_OMIT_GENERATED_COLUMNS
  129264. /* Mark generated columns as changing if their generator expressions
  129265. ** reference any changing column. The actual aXRef[] value for
  129266. ** generated expressions is not used, other than to check to see that it
  129267. ** is non-negative, so the value of aXRef[] for generated columns can be
  129268. ** set to any non-negative number. We use 99999 so that the value is
  129269. ** obvious when looking at aXRef[] in a symbolic debugger.
  129270. */
  129271. if( pTab->tabFlags & TF_HasGenerated ){
  129272. int bProgress;
  129273. testcase( pTab->tabFlags & TF_HasVirtual );
  129274. testcase( pTab->tabFlags & TF_HasStored );
  129275. do{
  129276. bProgress = 0;
  129277. for(i=0; i<pTab->nCol; i++){
  129278. if( aXRef[i]>=0 ) continue;
  129279. if( (pTab->aCol[i].colFlags & COLFLAG_GENERATED)==0 ) continue;
  129280. if( sqlite3ExprReferencesUpdatedColumn(pTab->aCol[i].pDflt,
  129281. aXRef, chngRowid) ){
  129282. aXRef[i] = 99999;
  129283. bProgress = 1;
  129284. }
  129285. }
  129286. }while( bProgress );
  129287. }
  129288. #endif
  129289. /* The SET expressions are not actually used inside the WHERE loop.
  129290. ** So reset the colUsed mask. Unless this is a virtual table. In that
  129291. ** case, set all bits of the colUsed mask (to ensure that the virtual
  129292. ** table implementation makes all columns available).
  129293. */
  129294. pTabList->a[0].colUsed = IsVirtual(pTab) ? ALLBITS : 0;
  129295. hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngKey);
  129296. /* There is one entry in the aRegIdx[] array for each index on the table
  129297. ** being updated. Fill in aRegIdx[] with a register number that will hold
  129298. ** the key for accessing each index.
  129299. */
  129300. if( onError==OE_Replace ) bReplace = 1;
  129301. for(nAllIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nAllIdx++){
  129302. int reg;
  129303. if( chngKey || hasFK>1 || pIdx==pPk
  129304. || indexWhereClauseMightChange(pIdx,aXRef,chngRowid)
  129305. ){
  129306. reg = ++pParse->nMem;
  129307. pParse->nMem += pIdx->nColumn;
  129308. }else{
  129309. reg = 0;
  129310. for(i=0; i<pIdx->nKeyCol; i++){
  129311. if( indexColumnIsBeingUpdated(pIdx, i, aXRef, chngRowid) ){
  129312. reg = ++pParse->nMem;
  129313. pParse->nMem += pIdx->nColumn;
  129314. if( onError==OE_Default && pIdx->onError==OE_Replace ){
  129315. bReplace = 1;
  129316. }
  129317. break;
  129318. }
  129319. }
  129320. }
  129321. if( reg==0 ) aToOpen[nAllIdx+1] = 0;
  129322. aRegIdx[nAllIdx] = reg;
  129323. }
  129324. aRegIdx[nAllIdx] = ++pParse->nMem; /* Register storing the table record */
  129325. if( bReplace ){
  129326. /* If REPLACE conflict resolution might be invoked, open cursors on all
  129327. ** indexes in case they are needed to delete records. */
  129328. memset(aToOpen, 1, nIdx+1);
  129329. }
  129330. if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
  129331. sqlite3BeginWriteOperation(pParse, pTrigger || hasFK, iDb);
  129332. /* Allocate required registers. */
  129333. if( !IsVirtual(pTab) ){
  129334. /* For now, regRowSet and aRegIdx[nAllIdx] share the same register.
  129335. ** If regRowSet turns out to be needed, then aRegIdx[nAllIdx] will be
  129336. ** reallocated. aRegIdx[nAllIdx] is the register in which the main
  129337. ** table record is written. regRowSet holds the RowSet for the
  129338. ** two-pass update algorithm. */
  129339. assert( aRegIdx[nAllIdx]==pParse->nMem );
  129340. regRowSet = aRegIdx[nAllIdx];
  129341. regOldRowid = regNewRowid = ++pParse->nMem;
  129342. if( chngPk || pTrigger || hasFK ){
  129343. regOld = pParse->nMem + 1;
  129344. pParse->nMem += pTab->nCol;
  129345. }
  129346. if( chngKey || pTrigger || hasFK ){
  129347. regNewRowid = ++pParse->nMem;
  129348. }
  129349. regNew = pParse->nMem + 1;
  129350. pParse->nMem += pTab->nCol;
  129351. }
  129352. /* Start the view context. */
  129353. if( isView ){
  129354. sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
  129355. }
  129356. /* If we are trying to update a view, realize that view into
  129357. ** an ephemeral table.
  129358. */
  129359. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  129360. if( isView ){
  129361. sqlite3MaterializeView(pParse, pTab,
  129362. pWhere, pOrderBy, pLimit, iDataCur
  129363. );
  129364. pOrderBy = 0;
  129365. pLimit = 0;
  129366. }
  129367. #endif
  129368. /* Resolve the column names in all the expressions in the
  129369. ** WHERE clause.
  129370. */
  129371. if( sqlite3ResolveExprNames(&sNC, pWhere) ){
  129372. goto update_cleanup;
  129373. }
  129374. #ifndef SQLITE_OMIT_VIRTUALTABLE
  129375. /* Virtual tables must be handled separately */
  129376. if( IsVirtual(pTab) ){
  129377. updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
  129378. pWhere, onError);
  129379. goto update_cleanup;
  129380. }
  129381. #endif
  129382. /* Jump to labelBreak to abandon further processing of this UPDATE */
  129383. labelContinue = labelBreak = sqlite3VdbeMakeLabel(pParse);
  129384. /* Not an UPSERT. Normal processing. Begin by
  129385. ** initialize the count of updated rows */
  129386. if( (db->flags&SQLITE_CountRows)!=0
  129387. && !pParse->pTriggerTab
  129388. && !pParse->nested
  129389. && pUpsert==0
  129390. ){
  129391. regRowCount = ++pParse->nMem;
  129392. sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
  129393. }
  129394. if( HasRowid(pTab) ){
  129395. sqlite3VdbeAddOp3(v, OP_Null, 0, regRowSet, regOldRowid);
  129396. }else{
  129397. assert( pPk!=0 );
  129398. nPk = pPk->nKeyCol;
  129399. iPk = pParse->nMem+1;
  129400. pParse->nMem += nPk;
  129401. regKey = ++pParse->nMem;
  129402. if( pUpsert==0 ){
  129403. iEph = pParse->nTab++;
  129404. sqlite3VdbeAddOp3(v, OP_Null, 0, iPk, iPk+nPk-1);
  129405. addrOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEph, nPk);
  129406. sqlite3VdbeSetP4KeyInfo(pParse, pPk);
  129407. }
  129408. }
  129409. if( pUpsert ){
  129410. /* If this is an UPSERT, then all cursors have already been opened by
  129411. ** the outer INSERT and the data cursor should be pointing at the row
  129412. ** that is to be updated. So bypass the code that searches for the
  129413. ** row(s) to be updated.
  129414. */
  129415. pWInfo = 0;
  129416. eOnePass = ONEPASS_SINGLE;
  129417. sqlite3ExprIfFalse(pParse, pWhere, labelBreak, SQLITE_JUMPIFNULL);
  129418. bFinishSeek = 0;
  129419. }else{
  129420. /* Begin the database scan.
  129421. **
  129422. ** Do not consider a single-pass strategy for a multi-row update if
  129423. ** there are any triggers or foreign keys to process, or rows may
  129424. ** be deleted as a result of REPLACE conflict handling. Any of these
  129425. ** things might disturb a cursor being used to scan through the table
  129426. ** or index, causing a single-pass approach to malfunction. */
  129427. flags = WHERE_ONEPASS_DESIRED|WHERE_SEEK_UNIQ_TABLE;
  129428. if( !pParse->nested && !pTrigger && !hasFK && !chngKey && !bReplace ){
  129429. flags |= WHERE_ONEPASS_MULTIROW;
  129430. }
  129431. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0, flags, iIdxCur);
  129432. if( pWInfo==0 ) goto update_cleanup;
  129433. /* A one-pass strategy that might update more than one row may not
  129434. ** be used if any column of the index used for the scan is being
  129435. ** updated. Otherwise, if there is an index on "b", statements like
  129436. ** the following could create an infinite loop:
  129437. **
  129438. ** UPDATE t1 SET b=b+1 WHERE b>?
  129439. **
  129440. ** Fall back to ONEPASS_OFF if where.c has selected a ONEPASS_MULTI
  129441. ** strategy that uses an index for which one or more columns are being
  129442. ** updated. */
  129443. eOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
  129444. bFinishSeek = sqlite3WhereUsesDeferredSeek(pWInfo);
  129445. if( eOnePass!=ONEPASS_SINGLE ){
  129446. sqlite3MultiWrite(pParse);
  129447. if( eOnePass==ONEPASS_MULTI ){
  129448. int iCur = aiCurOnePass[1];
  129449. if( iCur>=0 && iCur!=iDataCur && aToOpen[iCur-iBaseCur] ){
  129450. eOnePass = ONEPASS_OFF;
  129451. }
  129452. assert( iCur!=iDataCur || !HasRowid(pTab) );
  129453. }
  129454. }
  129455. }
  129456. if( HasRowid(pTab) ){
  129457. /* Read the rowid of the current row of the WHERE scan. In ONEPASS_OFF
  129458. ** mode, write the rowid into the FIFO. In either of the one-pass modes,
  129459. ** leave it in register regOldRowid. */
  129460. sqlite3VdbeAddOp2(v, OP_Rowid, iDataCur, regOldRowid);
  129461. if( eOnePass==ONEPASS_OFF ){
  129462. /* We need to use regRowSet, so reallocate aRegIdx[nAllIdx] */
  129463. aRegIdx[nAllIdx] = ++pParse->nMem;
  129464. sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
  129465. }
  129466. }else{
  129467. /* Read the PK of the current row into an array of registers. In
  129468. ** ONEPASS_OFF mode, serialize the array into a record and store it in
  129469. ** the ephemeral table. Or, in ONEPASS_SINGLE or MULTI mode, change
  129470. ** the OP_OpenEphemeral instruction to a Noop (the ephemeral table
  129471. ** is not required) and leave the PK fields in the array of registers. */
  129472. for(i=0; i<nPk; i++){
  129473. assert( pPk->aiColumn[i]>=0 );
  129474. sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur,
  129475. pPk->aiColumn[i], iPk+i);
  129476. }
  129477. if( eOnePass ){
  129478. if( addrOpen ) sqlite3VdbeChangeToNoop(v, addrOpen);
  129479. nKey = nPk;
  129480. regKey = iPk;
  129481. }else{
  129482. sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, regKey,
  129483. sqlite3IndexAffinityStr(db, pPk), nPk);
  129484. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iEph, regKey, iPk, nPk);
  129485. }
  129486. }
  129487. if( pUpsert==0 ){
  129488. if( eOnePass!=ONEPASS_MULTI ){
  129489. sqlite3WhereEnd(pWInfo);
  129490. }
  129491. if( !isView ){
  129492. int addrOnce = 0;
  129493. /* Open every index that needs updating. */
  129494. if( eOnePass!=ONEPASS_OFF ){
  129495. if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iBaseCur] = 0;
  129496. if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iBaseCur] = 0;
  129497. }
  129498. if( eOnePass==ONEPASS_MULTI && (nIdx-(aiCurOnePass[1]>=0))>0 ){
  129499. addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
  129500. }
  129501. sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, 0, iBaseCur,
  129502. aToOpen, 0, 0);
  129503. if( addrOnce ){
  129504. sqlite3VdbeJumpHereOrPopInst(v, addrOnce);
  129505. }
  129506. }
  129507. /* Top of the update loop */
  129508. if( eOnePass!=ONEPASS_OFF ){
  129509. if( !isView && aiCurOnePass[0]!=iDataCur && aiCurOnePass[1]!=iDataCur ){
  129510. assert( pPk );
  129511. sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelBreak, regKey,nKey);
  129512. VdbeCoverage(v);
  129513. }
  129514. if( eOnePass!=ONEPASS_SINGLE ){
  129515. labelContinue = sqlite3VdbeMakeLabel(pParse);
  129516. }
  129517. sqlite3VdbeAddOp2(v, OP_IsNull, pPk ? regKey : regOldRowid, labelBreak);
  129518. VdbeCoverageIf(v, pPk==0);
  129519. VdbeCoverageIf(v, pPk!=0);
  129520. }else if( pPk ){
  129521. labelContinue = sqlite3VdbeMakeLabel(pParse);
  129522. sqlite3VdbeAddOp2(v, OP_Rewind, iEph, labelBreak); VdbeCoverage(v);
  129523. addrTop = sqlite3VdbeAddOp2(v, OP_RowData, iEph, regKey);
  129524. sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue, regKey, 0);
  129525. VdbeCoverage(v);
  129526. }else{
  129527. labelContinue = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet,labelBreak,
  129528. regOldRowid);
  129529. VdbeCoverage(v);
  129530. sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid);
  129531. VdbeCoverage(v);
  129532. }
  129533. }
  129534. /* If the rowid value will change, set register regNewRowid to
  129535. ** contain the new value. If the rowid is not being modified,
  129536. ** then regNewRowid is the same register as regOldRowid, which is
  129537. ** already populated. */
  129538. assert( chngKey || pTrigger || hasFK || regOldRowid==regNewRowid );
  129539. if( chngRowid ){
  129540. sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
  129541. sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid); VdbeCoverage(v);
  129542. }
  129543. /* Compute the old pre-UPDATE content of the row being changed, if that
  129544. ** information is needed */
  129545. if( chngPk || hasFK || pTrigger ){
  129546. u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
  129547. oldmask |= sqlite3TriggerColmask(pParse,
  129548. pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError
  129549. );
  129550. for(i=0; i<pTab->nCol; i++){
  129551. u32 colFlags = pTab->aCol[i].colFlags;
  129552. k = sqlite3TableColumnToStorage(pTab, i) + regOld;
  129553. if( oldmask==0xffffffff
  129554. || (i<32 && (oldmask & MASKBIT32(i))!=0)
  129555. || (colFlags & COLFLAG_PRIMKEY)!=0
  129556. ){
  129557. testcase( oldmask!=0xffffffff && i==31 );
  129558. sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, k);
  129559. }else{
  129560. sqlite3VdbeAddOp2(v, OP_Null, 0, k);
  129561. }
  129562. }
  129563. if( chngRowid==0 && pPk==0 ){
  129564. sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
  129565. }
  129566. }
  129567. /* Populate the array of registers beginning at regNew with the new
  129568. ** row data. This array is used to check constants, create the new
  129569. ** table and index records, and as the values for any new.* references
  129570. ** made by triggers.
  129571. **
  129572. ** If there are one or more BEFORE triggers, then do not populate the
  129573. ** registers associated with columns that are (a) not modified by
  129574. ** this UPDATE statement and (b) not accessed by new.* references. The
  129575. ** values for registers not modified by the UPDATE must be reloaded from
  129576. ** the database after the BEFORE triggers are fired anyway (as the trigger
  129577. ** may have modified them). So not loading those that are not going to
  129578. ** be used eliminates some redundant opcodes.
  129579. */
  129580. newmask = sqlite3TriggerColmask(
  129581. pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
  129582. );
  129583. for(i=0, k=regNew; i<pTab->nCol; i++, k++){
  129584. if( i==pTab->iPKey ){
  129585. sqlite3VdbeAddOp2(v, OP_Null, 0, k);
  129586. }else if( (pTab->aCol[i].colFlags & COLFLAG_GENERATED)!=0 ){
  129587. if( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL ) k--;
  129588. }else{
  129589. j = aXRef[i];
  129590. if( j>=0 ){
  129591. sqlite3ExprCode(pParse, pChanges->a[j].pExpr, k);
  129592. }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask & MASKBIT32(i)) ){
  129593. /* This branch loads the value of a column that will not be changed
  129594. ** into a register. This is done if there are no BEFORE triggers, or
  129595. ** if there are one or more BEFORE triggers that use this value via
  129596. ** a new.* reference in a trigger program.
  129597. */
  129598. testcase( i==31 );
  129599. testcase( i==32 );
  129600. sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, k);
  129601. bFinishSeek = 0;
  129602. }else{
  129603. sqlite3VdbeAddOp2(v, OP_Null, 0, k);
  129604. }
  129605. }
  129606. }
  129607. #ifndef SQLITE_OMIT_GENERATED_COLUMNS
  129608. if( pTab->tabFlags & TF_HasGenerated ){
  129609. testcase( pTab->tabFlags & TF_HasVirtual );
  129610. testcase( pTab->tabFlags & TF_HasStored );
  129611. sqlite3ComputeGeneratedColumns(pParse, regNew, pTab);
  129612. }
  129613. #endif
  129614. /* Fire any BEFORE UPDATE triggers. This happens before constraints are
  129615. ** verified. One could argue that this is wrong.
  129616. */
  129617. if( tmask&TRIGGER_BEFORE ){
  129618. sqlite3TableAffinity(v, pTab, regNew);
  129619. sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
  129620. TRIGGER_BEFORE, pTab, regOldRowid, onError, labelContinue);
  129621. /* The row-trigger may have deleted the row being updated. In this
  129622. ** case, jump to the next row. No updates or AFTER triggers are
  129623. ** required. This behavior - what happens when the row being updated
  129624. ** is deleted or renamed by a BEFORE trigger - is left undefined in the
  129625. ** documentation.
  129626. */
  129627. if( pPk ){
  129628. sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue,regKey,nKey);
  129629. VdbeCoverage(v);
  129630. }else{
  129631. sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid);
  129632. VdbeCoverage(v);
  129633. }
  129634. /* After-BEFORE-trigger-reload-loop:
  129635. ** If it did not delete it, the BEFORE trigger may still have modified
  129636. ** some of the columns of the row being updated. Load the values for
  129637. ** all columns not modified by the update statement into their registers
  129638. ** in case this has happened. Only unmodified columns are reloaded.
  129639. ** The values computed for modified columns use the values before the
  129640. ** BEFORE trigger runs. See test case trigger1-18.0 (added 2018-04-26)
  129641. ** for an example.
  129642. */
  129643. for(i=0, k=regNew; i<pTab->nCol; i++, k++){
  129644. if( pTab->aCol[i].colFlags & COLFLAG_GENERATED ){
  129645. if( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL ) k--;
  129646. }else if( aXRef[i]<0 && i!=pTab->iPKey ){
  129647. sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, k);
  129648. }
  129649. }
  129650. #ifndef SQLITE_OMIT_GENERATED_COLUMNS
  129651. if( pTab->tabFlags & TF_HasGenerated ){
  129652. testcase( pTab->tabFlags & TF_HasVirtual );
  129653. testcase( pTab->tabFlags & TF_HasStored );
  129654. sqlite3ComputeGeneratedColumns(pParse, regNew, pTab);
  129655. }
  129656. #endif
  129657. }
  129658. if( !isView ){
  129659. /* Do constraint checks. */
  129660. assert( regOldRowid>0 );
  129661. sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
  129662. regNewRowid, regOldRowid, chngKey, onError, labelContinue, &bReplace,
  129663. aXRef, 0);
  129664. /* If REPLACE conflict handling may have been used, or if the PK of the
  129665. ** row is changing, then the GenerateConstraintChecks() above may have
  129666. ** moved cursor iDataCur. Reseek it. */
  129667. if( bReplace || chngKey ){
  129668. if( pPk ){
  129669. sqlite3VdbeAddOp4Int(v, OP_NotFound,iDataCur,labelContinue,regKey,nKey);
  129670. }else{
  129671. sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue,regOldRowid);
  129672. }
  129673. VdbeCoverageNeverTaken(v);
  129674. }
  129675. /* Do FK constraint checks. */
  129676. if( hasFK ){
  129677. sqlite3FkCheck(pParse, pTab, regOldRowid, 0, aXRef, chngKey);
  129678. }
  129679. /* Delete the index entries associated with the current record. */
  129680. sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, aRegIdx, -1);
  129681. /* We must run the OP_FinishSeek opcode to resolve a prior
  129682. ** OP_DeferredSeek if there is any possibility that there have been
  129683. ** no OP_Column opcodes since the OP_DeferredSeek was issued. But
  129684. ** we want to avoid the OP_FinishSeek if possible, as running it
  129685. ** costs CPU cycles. */
  129686. if( bFinishSeek ){
  129687. sqlite3VdbeAddOp1(v, OP_FinishSeek, iDataCur);
  129688. }
  129689. /* If changing the rowid value, or if there are foreign key constraints
  129690. ** to process, delete the old record. Otherwise, add a noop OP_Delete
  129691. ** to invoke the pre-update hook.
  129692. **
  129693. ** That (regNew==regnewRowid+1) is true is also important for the
  129694. ** pre-update hook. If the caller invokes preupdate_new(), the returned
  129695. ** value is copied from memory cell (regNewRowid+1+iCol), where iCol
  129696. ** is the column index supplied by the user.
  129697. */
  129698. assert( regNew==regNewRowid+1 );
  129699. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  129700. sqlite3VdbeAddOp3(v, OP_Delete, iDataCur,
  129701. OPFLAG_ISUPDATE | ((hasFK>1 || chngKey) ? 0 : OPFLAG_ISNOOP),
  129702. regNewRowid
  129703. );
  129704. if( eOnePass==ONEPASS_MULTI ){
  129705. assert( hasFK==0 && chngKey==0 );
  129706. sqlite3VdbeChangeP5(v, OPFLAG_SAVEPOSITION);
  129707. }
  129708. if( !pParse->nested ){
  129709. sqlite3VdbeAppendP4(v, pTab, P4_TABLE);
  129710. }
  129711. #else
  129712. if( hasFK>1 || chngKey ){
  129713. sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, 0);
  129714. }
  129715. #endif
  129716. if( hasFK ){
  129717. sqlite3FkCheck(pParse, pTab, 0, regNewRowid, aXRef, chngKey);
  129718. }
  129719. /* Insert the new index entries and the new record. */
  129720. sqlite3CompleteInsertion(
  129721. pParse, pTab, iDataCur, iIdxCur, regNewRowid, aRegIdx,
  129722. OPFLAG_ISUPDATE | (eOnePass==ONEPASS_MULTI ? OPFLAG_SAVEPOSITION : 0),
  129723. 0, 0
  129724. );
  129725. /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
  129726. ** handle rows (possibly in other tables) that refer via a foreign key
  129727. ** to the row just updated. */
  129728. if( hasFK ){
  129729. sqlite3FkActions(pParse, pTab, pChanges, regOldRowid, aXRef, chngKey);
  129730. }
  129731. }
  129732. /* Increment the row counter
  129733. */
  129734. if( regRowCount ){
  129735. sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
  129736. }
  129737. sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
  129738. TRIGGER_AFTER, pTab, regOldRowid, onError, labelContinue);
  129739. /* Repeat the above with the next record to be updated, until
  129740. ** all record selected by the WHERE clause have been updated.
  129741. */
  129742. if( eOnePass==ONEPASS_SINGLE ){
  129743. /* Nothing to do at end-of-loop for a single-pass */
  129744. }else if( eOnePass==ONEPASS_MULTI ){
  129745. sqlite3VdbeResolveLabel(v, labelContinue);
  129746. sqlite3WhereEnd(pWInfo);
  129747. }else if( pPk ){
  129748. sqlite3VdbeResolveLabel(v, labelContinue);
  129749. sqlite3VdbeAddOp2(v, OP_Next, iEph, addrTop); VdbeCoverage(v);
  129750. }else{
  129751. sqlite3VdbeGoto(v, labelContinue);
  129752. }
  129753. sqlite3VdbeResolveLabel(v, labelBreak);
  129754. /* Update the sqlite_sequence table by storing the content of the
  129755. ** maximum rowid counter values recorded while inserting into
  129756. ** autoincrement tables.
  129757. */
  129758. if( pParse->nested==0 && pParse->pTriggerTab==0 && pUpsert==0 ){
  129759. sqlite3AutoincrementEnd(pParse);
  129760. }
  129761. /*
  129762. ** Return the number of rows that were changed, if we are tracking
  129763. ** that information.
  129764. */
  129765. if( regRowCount ){
  129766. sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
  129767. sqlite3VdbeSetNumCols(v, 1);
  129768. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
  129769. }
  129770. update_cleanup:
  129771. sqlite3AuthContextPop(&sContext);
  129772. sqlite3DbFree(db, aXRef); /* Also frees aRegIdx[] and aToOpen[] */
  129773. sqlite3SrcListDelete(db, pTabList);
  129774. sqlite3ExprListDelete(db, pChanges);
  129775. sqlite3ExprDelete(db, pWhere);
  129776. #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT)
  129777. sqlite3ExprListDelete(db, pOrderBy);
  129778. sqlite3ExprDelete(db, pLimit);
  129779. #endif
  129780. return;
  129781. }
  129782. /* Make sure "isView" and other macros defined above are undefined. Otherwise
  129783. ** they may interfere with compilation of other functions in this file
  129784. ** (or in another file, if this file becomes part of the amalgamation). */
  129785. #ifdef isView
  129786. #undef isView
  129787. #endif
  129788. #ifdef pTrigger
  129789. #undef pTrigger
  129790. #endif
  129791. #ifndef SQLITE_OMIT_VIRTUALTABLE
  129792. /*
  129793. ** Generate code for an UPDATE of a virtual table.
  129794. **
  129795. ** There are two possible strategies - the default and the special
  129796. ** "onepass" strategy. Onepass is only used if the virtual table
  129797. ** implementation indicates that pWhere may match at most one row.
  129798. **
  129799. ** The default strategy is to create an ephemeral table that contains
  129800. ** for each row to be changed:
  129801. **
  129802. ** (A) The original rowid of that row.
  129803. ** (B) The revised rowid for the row.
  129804. ** (C) The content of every column in the row.
  129805. **
  129806. ** Then loop through the contents of this ephemeral table executing a
  129807. ** VUpdate for each row. When finished, drop the ephemeral table.
  129808. **
  129809. ** The "onepass" strategy does not use an ephemeral table. Instead, it
  129810. ** stores the same values (A, B and C above) in a register array and
  129811. ** makes a single invocation of VUpdate.
  129812. */
  129813. static void updateVirtualTable(
  129814. Parse *pParse, /* The parsing context */
  129815. SrcList *pSrc, /* The virtual table to be modified */
  129816. Table *pTab, /* The virtual table */
  129817. ExprList *pChanges, /* The columns to change in the UPDATE statement */
  129818. Expr *pRowid, /* Expression used to recompute the rowid */
  129819. int *aXRef, /* Mapping from columns of pTab to entries in pChanges */
  129820. Expr *pWhere, /* WHERE clause of the UPDATE statement */
  129821. int onError /* ON CONFLICT strategy */
  129822. ){
  129823. Vdbe *v = pParse->pVdbe; /* Virtual machine under construction */
  129824. int ephemTab; /* Table holding the result of the SELECT */
  129825. int i; /* Loop counter */
  129826. sqlite3 *db = pParse->db; /* Database connection */
  129827. const char *pVTab = (const char*)sqlite3GetVTable(db, pTab);
  129828. WhereInfo *pWInfo;
  129829. int nArg = 2 + pTab->nCol; /* Number of arguments to VUpdate */
  129830. int regArg; /* First register in VUpdate arg array */
  129831. int regRec; /* Register in which to assemble record */
  129832. int regRowid; /* Register for ephem table rowid */
  129833. int iCsr = pSrc->a[0].iCursor; /* Cursor used for virtual table scan */
  129834. int aDummy[2]; /* Unused arg for sqlite3WhereOkOnePass() */
  129835. int eOnePass; /* True to use onepass strategy */
  129836. int addr; /* Address of OP_OpenEphemeral */
  129837. /* Allocate nArg registers in which to gather the arguments for VUpdate. Then
  129838. ** create and open the ephemeral table in which the records created from
  129839. ** these arguments will be temporarily stored. */
  129840. assert( v );
  129841. ephemTab = pParse->nTab++;
  129842. addr= sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, nArg);
  129843. regArg = pParse->nMem + 1;
  129844. pParse->nMem += nArg;
  129845. regRec = ++pParse->nMem;
  129846. regRowid = ++pParse->nMem;
  129847. /* Start scanning the virtual table */
  129848. pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0,0,WHERE_ONEPASS_DESIRED,0);
  129849. if( pWInfo==0 ) return;
  129850. /* Populate the argument registers. */
  129851. for(i=0; i<pTab->nCol; i++){
  129852. assert( (pTab->aCol[i].colFlags & COLFLAG_GENERATED)==0 );
  129853. if( aXRef[i]>=0 ){
  129854. sqlite3ExprCode(pParse, pChanges->a[aXRef[i]].pExpr, regArg+2+i);
  129855. }else{
  129856. sqlite3VdbeAddOp3(v, OP_VColumn, iCsr, i, regArg+2+i);
  129857. sqlite3VdbeChangeP5(v, OPFLAG_NOCHNG);/* Enable sqlite3_vtab_nochange() */
  129858. }
  129859. }
  129860. if( HasRowid(pTab) ){
  129861. sqlite3VdbeAddOp2(v, OP_Rowid, iCsr, regArg);
  129862. if( pRowid ){
  129863. sqlite3ExprCode(pParse, pRowid, regArg+1);
  129864. }else{
  129865. sqlite3VdbeAddOp2(v, OP_Rowid, iCsr, regArg+1);
  129866. }
  129867. }else{
  129868. Index *pPk; /* PRIMARY KEY index */
  129869. i16 iPk; /* PRIMARY KEY column */
  129870. pPk = sqlite3PrimaryKeyIndex(pTab);
  129871. assert( pPk!=0 );
  129872. assert( pPk->nKeyCol==1 );
  129873. iPk = pPk->aiColumn[0];
  129874. sqlite3VdbeAddOp3(v, OP_VColumn, iCsr, iPk, regArg);
  129875. sqlite3VdbeAddOp2(v, OP_SCopy, regArg+2+iPk, regArg+1);
  129876. }
  129877. eOnePass = sqlite3WhereOkOnePass(pWInfo, aDummy);
  129878. /* There is no ONEPASS_MULTI on virtual tables */
  129879. assert( eOnePass==ONEPASS_OFF || eOnePass==ONEPASS_SINGLE );
  129880. if( eOnePass ){
  129881. /* If using the onepass strategy, no-op out the OP_OpenEphemeral coded
  129882. ** above. */
  129883. sqlite3VdbeChangeToNoop(v, addr);
  129884. sqlite3VdbeAddOp1(v, OP_Close, iCsr);
  129885. }else{
  129886. /* Create a record from the argument register contents and insert it into
  129887. ** the ephemeral table. */
  129888. sqlite3MultiWrite(pParse);
  129889. sqlite3VdbeAddOp3(v, OP_MakeRecord, regArg, nArg, regRec);
  129890. #ifdef SQLITE_DEBUG
  129891. /* Signal an assert() within OP_MakeRecord that it is allowed to
  129892. ** accept no-change records with serial_type 10 */
  129893. sqlite3VdbeChangeP5(v, OPFLAG_NOCHNG_MAGIC);
  129894. #endif
  129895. sqlite3VdbeAddOp2(v, OP_NewRowid, ephemTab, regRowid);
  129896. sqlite3VdbeAddOp3(v, OP_Insert, ephemTab, regRec, regRowid);
  129897. }
  129898. if( eOnePass==ONEPASS_OFF ){
  129899. /* End the virtual table scan */
  129900. sqlite3WhereEnd(pWInfo);
  129901. /* Begin scannning through the ephemeral table. */
  129902. addr = sqlite3VdbeAddOp1(v, OP_Rewind, ephemTab); VdbeCoverage(v);
  129903. /* Extract arguments from the current row of the ephemeral table and
  129904. ** invoke the VUpdate method. */
  129905. for(i=0; i<nArg; i++){
  129906. sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i, regArg+i);
  129907. }
  129908. }
  129909. sqlite3VtabMakeWritable(pParse, pTab);
  129910. sqlite3VdbeAddOp4(v, OP_VUpdate, 0, nArg, regArg, pVTab, P4_VTAB);
  129911. sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
  129912. sqlite3MayAbort(pParse);
  129913. /* End of the ephemeral table scan. Or, if using the onepass strategy,
  129914. ** jump to here if the scan visited zero rows. */
  129915. if( eOnePass==ONEPASS_OFF ){
  129916. sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1); VdbeCoverage(v);
  129917. sqlite3VdbeJumpHere(v, addr);
  129918. sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
  129919. }else{
  129920. sqlite3WhereEnd(pWInfo);
  129921. }
  129922. }
  129923. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  129924. /************** End of update.c **********************************************/
  129925. /************** Begin file upsert.c ******************************************/
  129926. /*
  129927. ** 2018-04-12
  129928. **
  129929. ** The author disclaims copyright to this source code. In place of
  129930. ** a legal notice, here is a blessing:
  129931. **
  129932. ** May you do good and not evil.
  129933. ** May you find forgiveness for yourself and forgive others.
  129934. ** May you share freely, never taking more than you give.
  129935. **
  129936. *************************************************************************
  129937. ** This file contains code to implement various aspects of UPSERT
  129938. ** processing and handling of the Upsert object.
  129939. */
  129940. /* #include "sqliteInt.h" */
  129941. #ifndef SQLITE_OMIT_UPSERT
  129942. /*
  129943. ** Free a list of Upsert objects
  129944. */
  129945. SQLITE_PRIVATE void sqlite3UpsertDelete(sqlite3 *db, Upsert *p){
  129946. if( p ){
  129947. sqlite3ExprListDelete(db, p->pUpsertTarget);
  129948. sqlite3ExprDelete(db, p->pUpsertTargetWhere);
  129949. sqlite3ExprListDelete(db, p->pUpsertSet);
  129950. sqlite3ExprDelete(db, p->pUpsertWhere);
  129951. sqlite3DbFree(db, p);
  129952. }
  129953. }
  129954. /*
  129955. ** Duplicate an Upsert object.
  129956. */
  129957. SQLITE_PRIVATE Upsert *sqlite3UpsertDup(sqlite3 *db, Upsert *p){
  129958. if( p==0 ) return 0;
  129959. return sqlite3UpsertNew(db,
  129960. sqlite3ExprListDup(db, p->pUpsertTarget, 0),
  129961. sqlite3ExprDup(db, p->pUpsertTargetWhere, 0),
  129962. sqlite3ExprListDup(db, p->pUpsertSet, 0),
  129963. sqlite3ExprDup(db, p->pUpsertWhere, 0)
  129964. );
  129965. }
  129966. /*
  129967. ** Create a new Upsert object.
  129968. */
  129969. SQLITE_PRIVATE Upsert *sqlite3UpsertNew(
  129970. sqlite3 *db, /* Determines which memory allocator to use */
  129971. ExprList *pTarget, /* Target argument to ON CONFLICT, or NULL */
  129972. Expr *pTargetWhere, /* Optional WHERE clause on the target */
  129973. ExprList *pSet, /* UPDATE columns, or NULL for a DO NOTHING */
  129974. Expr *pWhere /* WHERE clause for the ON CONFLICT UPDATE */
  129975. ){
  129976. Upsert *pNew;
  129977. pNew = sqlite3DbMallocRaw(db, sizeof(Upsert));
  129978. if( pNew==0 ){
  129979. sqlite3ExprListDelete(db, pTarget);
  129980. sqlite3ExprDelete(db, pTargetWhere);
  129981. sqlite3ExprListDelete(db, pSet);
  129982. sqlite3ExprDelete(db, pWhere);
  129983. return 0;
  129984. }else{
  129985. pNew->pUpsertTarget = pTarget;
  129986. pNew->pUpsertTargetWhere = pTargetWhere;
  129987. pNew->pUpsertSet = pSet;
  129988. pNew->pUpsertWhere = pWhere;
  129989. pNew->pUpsertIdx = 0;
  129990. }
  129991. return pNew;
  129992. }
  129993. /*
  129994. ** Analyze the ON CONFLICT clause described by pUpsert. Resolve all
  129995. ** symbols in the conflict-target.
  129996. **
  129997. ** Return SQLITE_OK if everything works, or an error code is something
  129998. ** is wrong.
  129999. */
  130000. SQLITE_PRIVATE int sqlite3UpsertAnalyzeTarget(
  130001. Parse *pParse, /* The parsing context */
  130002. SrcList *pTabList, /* Table into which we are inserting */
  130003. Upsert *pUpsert /* The ON CONFLICT clauses */
  130004. ){
  130005. Table *pTab; /* That table into which we are inserting */
  130006. int rc; /* Result code */
  130007. int iCursor; /* Cursor used by pTab */
  130008. Index *pIdx; /* One of the indexes of pTab */
  130009. ExprList *pTarget; /* The conflict-target clause */
  130010. Expr *pTerm; /* One term of the conflict-target clause */
  130011. NameContext sNC; /* Context for resolving symbolic names */
  130012. Expr sCol[2]; /* Index column converted into an Expr */
  130013. assert( pTabList->nSrc==1 );
  130014. assert( pTabList->a[0].pTab!=0 );
  130015. assert( pUpsert!=0 );
  130016. assert( pUpsert->pUpsertTarget!=0 );
  130017. /* Resolve all symbolic names in the conflict-target clause, which
  130018. ** includes both the list of columns and the optional partial-index
  130019. ** WHERE clause.
  130020. */
  130021. memset(&sNC, 0, sizeof(sNC));
  130022. sNC.pParse = pParse;
  130023. sNC.pSrcList = pTabList;
  130024. rc = sqlite3ResolveExprListNames(&sNC, pUpsert->pUpsertTarget);
  130025. if( rc ) return rc;
  130026. rc = sqlite3ResolveExprNames(&sNC, pUpsert->pUpsertTargetWhere);
  130027. if( rc ) return rc;
  130028. /* Check to see if the conflict target matches the rowid. */
  130029. pTab = pTabList->a[0].pTab;
  130030. pTarget = pUpsert->pUpsertTarget;
  130031. iCursor = pTabList->a[0].iCursor;
  130032. if( HasRowid(pTab)
  130033. && pTarget->nExpr==1
  130034. && (pTerm = pTarget->a[0].pExpr)->op==TK_COLUMN
  130035. && pTerm->iColumn==XN_ROWID
  130036. ){
  130037. /* The conflict-target is the rowid of the primary table */
  130038. assert( pUpsert->pUpsertIdx==0 );
  130039. return SQLITE_OK;
  130040. }
  130041. /* Initialize sCol[0..1] to be an expression parse tree for a
  130042. ** single column of an index. The sCol[0] node will be the TK_COLLATE
  130043. ** operator and sCol[1] will be the TK_COLUMN operator. Code below
  130044. ** will populate the specific collation and column number values
  130045. ** prior to comparing against the conflict-target expression.
  130046. */
  130047. memset(sCol, 0, sizeof(sCol));
  130048. sCol[0].op = TK_COLLATE;
  130049. sCol[0].pLeft = &sCol[1];
  130050. sCol[1].op = TK_COLUMN;
  130051. sCol[1].iTable = pTabList->a[0].iCursor;
  130052. /* Check for matches against other indexes */
  130053. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  130054. int ii, jj, nn;
  130055. if( !IsUniqueIndex(pIdx) ) continue;
  130056. if( pTarget->nExpr!=pIdx->nKeyCol ) continue;
  130057. if( pIdx->pPartIdxWhere ){
  130058. if( pUpsert->pUpsertTargetWhere==0 ) continue;
  130059. if( sqlite3ExprCompare(pParse, pUpsert->pUpsertTargetWhere,
  130060. pIdx->pPartIdxWhere, iCursor)!=0 ){
  130061. continue;
  130062. }
  130063. }
  130064. nn = pIdx->nKeyCol;
  130065. for(ii=0; ii<nn; ii++){
  130066. Expr *pExpr;
  130067. sCol[0].u.zToken = (char*)pIdx->azColl[ii];
  130068. if( pIdx->aiColumn[ii]==XN_EXPR ){
  130069. assert( pIdx->aColExpr!=0 );
  130070. assert( pIdx->aColExpr->nExpr>ii );
  130071. pExpr = pIdx->aColExpr->a[ii].pExpr;
  130072. if( pExpr->op!=TK_COLLATE ){
  130073. sCol[0].pLeft = pExpr;
  130074. pExpr = &sCol[0];
  130075. }
  130076. }else{
  130077. sCol[0].pLeft = &sCol[1];
  130078. sCol[1].iColumn = pIdx->aiColumn[ii];
  130079. pExpr = &sCol[0];
  130080. }
  130081. for(jj=0; jj<nn; jj++){
  130082. if( sqlite3ExprCompare(pParse, pTarget->a[jj].pExpr, pExpr,iCursor)<2 ){
  130083. break; /* Column ii of the index matches column jj of target */
  130084. }
  130085. }
  130086. if( jj>=nn ){
  130087. /* The target contains no match for column jj of the index */
  130088. break;
  130089. }
  130090. }
  130091. if( ii<nn ){
  130092. /* Column ii of the index did not match any term of the conflict target.
  130093. ** Continue the search with the next index. */
  130094. continue;
  130095. }
  130096. pUpsert->pUpsertIdx = pIdx;
  130097. return SQLITE_OK;
  130098. }
  130099. sqlite3ErrorMsg(pParse, "ON CONFLICT clause does not match any "
  130100. "PRIMARY KEY or UNIQUE constraint");
  130101. return SQLITE_ERROR;
  130102. }
  130103. /*
  130104. ** Generate bytecode that does an UPDATE as part of an upsert.
  130105. **
  130106. ** If pIdx is NULL, then the UNIQUE constraint that failed was the IPK.
  130107. ** In this case parameter iCur is a cursor open on the table b-tree that
  130108. ** currently points to the conflicting table row. Otherwise, if pIdx
  130109. ** is not NULL, then pIdx is the constraint that failed and iCur is a
  130110. ** cursor points to the conflicting row.
  130111. */
  130112. SQLITE_PRIVATE void sqlite3UpsertDoUpdate(
  130113. Parse *pParse, /* The parsing and code-generating context */
  130114. Upsert *pUpsert, /* The ON CONFLICT clause for the upsert */
  130115. Table *pTab, /* The table being updated */
  130116. Index *pIdx, /* The UNIQUE constraint that failed */
  130117. int iCur /* Cursor for pIdx (or pTab if pIdx==NULL) */
  130118. ){
  130119. Vdbe *v = pParse->pVdbe;
  130120. sqlite3 *db = pParse->db;
  130121. SrcList *pSrc; /* FROM clause for the UPDATE */
  130122. int iDataCur;
  130123. int i;
  130124. assert( v!=0 );
  130125. assert( pUpsert!=0 );
  130126. VdbeNoopComment((v, "Begin DO UPDATE of UPSERT"));
  130127. iDataCur = pUpsert->iDataCur;
  130128. if( pIdx && iCur!=iDataCur ){
  130129. if( HasRowid(pTab) ){
  130130. int regRowid = sqlite3GetTempReg(pParse);
  130131. sqlite3VdbeAddOp2(v, OP_IdxRowid, iCur, regRowid);
  130132. sqlite3VdbeAddOp3(v, OP_SeekRowid, iDataCur, 0, regRowid);
  130133. VdbeCoverage(v);
  130134. sqlite3ReleaseTempReg(pParse, regRowid);
  130135. }else{
  130136. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  130137. int nPk = pPk->nKeyCol;
  130138. int iPk = pParse->nMem+1;
  130139. pParse->nMem += nPk;
  130140. for(i=0; i<nPk; i++){
  130141. int k;
  130142. assert( pPk->aiColumn[i]>=0 );
  130143. k = sqlite3TableColumnToIndex(pIdx, pPk->aiColumn[i]);
  130144. sqlite3VdbeAddOp3(v, OP_Column, iCur, k, iPk+i);
  130145. VdbeComment((v, "%s.%s", pIdx->zName,
  130146. pTab->aCol[pPk->aiColumn[i]].zName));
  130147. }
  130148. sqlite3VdbeVerifyAbortable(v, OE_Abort);
  130149. i = sqlite3VdbeAddOp4Int(v, OP_Found, iDataCur, 0, iPk, nPk);
  130150. VdbeCoverage(v);
  130151. sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CORRUPT, OE_Abort, 0,
  130152. "corrupt database", P4_STATIC);
  130153. sqlite3MayAbort(pParse);
  130154. sqlite3VdbeJumpHere(v, i);
  130155. }
  130156. }
  130157. /* pUpsert does not own pUpsertSrc - the outer INSERT statement does. So
  130158. ** we have to make a copy before passing it down into sqlite3Update() */
  130159. pSrc = sqlite3SrcListDup(db, pUpsert->pUpsertSrc, 0);
  130160. /* excluded.* columns of type REAL need to be converted to a hard real */
  130161. for(i=0; i<pTab->nCol; i++){
  130162. if( pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
  130163. sqlite3VdbeAddOp1(v, OP_RealAffinity, pUpsert->regData+i);
  130164. }
  130165. }
  130166. sqlite3Update(pParse, pSrc, pUpsert->pUpsertSet,
  130167. pUpsert->pUpsertWhere, OE_Abort, 0, 0, pUpsert);
  130168. pUpsert->pUpsertSet = 0; /* Will have been deleted by sqlite3Update() */
  130169. pUpsert->pUpsertWhere = 0; /* Will have been deleted by sqlite3Update() */
  130170. VdbeNoopComment((v, "End DO UPDATE of UPSERT"));
  130171. }
  130172. #endif /* SQLITE_OMIT_UPSERT */
  130173. /************** End of upsert.c **********************************************/
  130174. /************** Begin file vacuum.c ******************************************/
  130175. /*
  130176. ** 2003 April 6
  130177. **
  130178. ** The author disclaims copyright to this source code. In place of
  130179. ** a legal notice, here is a blessing:
  130180. **
  130181. ** May you do good and not evil.
  130182. ** May you find forgiveness for yourself and forgive others.
  130183. ** May you share freely, never taking more than you give.
  130184. **
  130185. *************************************************************************
  130186. ** This file contains code used to implement the VACUUM command.
  130187. **
  130188. ** Most of the code in this file may be omitted by defining the
  130189. ** SQLITE_OMIT_VACUUM macro.
  130190. */
  130191. /* #include "sqliteInt.h" */
  130192. /* #include "vdbeInt.h" */
  130193. #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
  130194. /*
  130195. ** Execute zSql on database db.
  130196. **
  130197. ** If zSql returns rows, then each row will have exactly one
  130198. ** column. (This will only happen if zSql begins with "SELECT".)
  130199. ** Take each row of result and call execSql() again recursively.
  130200. **
  130201. ** The execSqlF() routine does the same thing, except it accepts
  130202. ** a format string as its third argument
  130203. */
  130204. static int execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
  130205. sqlite3_stmt *pStmt;
  130206. int rc;
  130207. /* printf("SQL: [%s]\n", zSql); fflush(stdout); */
  130208. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  130209. if( rc!=SQLITE_OK ) return rc;
  130210. while( SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
  130211. const char *zSubSql = (const char*)sqlite3_column_text(pStmt,0);
  130212. assert( sqlite3_strnicmp(zSql,"SELECT",6)==0 );
  130213. /* The secondary SQL must be one of CREATE TABLE, CREATE INDEX,
  130214. ** or INSERT. Historically there have been attacks that first
  130215. ** corrupt the sqlite_master.sql field with other kinds of statements
  130216. ** then run VACUUM to get those statements to execute at inappropriate
  130217. ** times. */
  130218. if( zSubSql
  130219. && (strncmp(zSubSql,"CRE",3)==0 || strncmp(zSubSql,"INS",3)==0)
  130220. ){
  130221. rc = execSql(db, pzErrMsg, zSubSql);
  130222. if( rc!=SQLITE_OK ) break;
  130223. }
  130224. }
  130225. assert( rc!=SQLITE_ROW );
  130226. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  130227. if( rc ){
  130228. sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
  130229. }
  130230. (void)sqlite3_finalize(pStmt);
  130231. return rc;
  130232. }
  130233. static int execSqlF(sqlite3 *db, char **pzErrMsg, const char *zSql, ...){
  130234. char *z;
  130235. va_list ap;
  130236. int rc;
  130237. va_start(ap, zSql);
  130238. z = sqlite3VMPrintf(db, zSql, ap);
  130239. va_end(ap);
  130240. if( z==0 ) return SQLITE_NOMEM;
  130241. rc = execSql(db, pzErrMsg, z);
  130242. sqlite3DbFree(db, z);
  130243. return rc;
  130244. }
  130245. /*
  130246. ** The VACUUM command is used to clean up the database,
  130247. ** collapse free space, etc. It is modelled after the VACUUM command
  130248. ** in PostgreSQL. The VACUUM command works as follows:
  130249. **
  130250. ** (1) Create a new transient database file
  130251. ** (2) Copy all content from the database being vacuumed into
  130252. ** the new transient database file
  130253. ** (3) Copy content from the transient database back into the
  130254. ** original database.
  130255. **
  130256. ** The transient database requires temporary disk space approximately
  130257. ** equal to the size of the original database. The copy operation of
  130258. ** step (3) requires additional temporary disk space approximately equal
  130259. ** to the size of the original database for the rollback journal.
  130260. ** Hence, temporary disk space that is approximately 2x the size of the
  130261. ** original database is required. Every page of the database is written
  130262. ** approximately 3 times: Once for step (2) and twice for step (3).
  130263. ** Two writes per page are required in step (3) because the original
  130264. ** database content must be written into the rollback journal prior to
  130265. ** overwriting the database with the vacuumed content.
  130266. **
  130267. ** Only 1x temporary space and only 1x writes would be required if
  130268. ** the copy of step (3) were replaced by deleting the original database
  130269. ** and renaming the transient database as the original. But that will
  130270. ** not work if other processes are attached to the original database.
  130271. ** And a power loss in between deleting the original and renaming the
  130272. ** transient would cause the database file to appear to be deleted
  130273. ** following reboot.
  130274. */
  130275. SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse, Token *pNm, Expr *pInto){
  130276. Vdbe *v = sqlite3GetVdbe(pParse);
  130277. int iDb = 0;
  130278. if( v==0 ) goto build_vacuum_end;
  130279. if( pParse->nErr ) goto build_vacuum_end;
  130280. if( pNm ){
  130281. #ifndef SQLITE_BUG_COMPATIBLE_20160819
  130282. /* Default behavior: Report an error if the argument to VACUUM is
  130283. ** not recognized */
  130284. iDb = sqlite3TwoPartName(pParse, pNm, pNm, &pNm);
  130285. if( iDb<0 ) goto build_vacuum_end;
  130286. #else
  130287. /* When SQLITE_BUG_COMPATIBLE_20160819 is defined, unrecognized arguments
  130288. ** to VACUUM are silently ignored. This is a back-out of a bug fix that
  130289. ** occurred on 2016-08-19 (https://www.sqlite.org/src/info/083f9e6270).
  130290. ** The buggy behavior is required for binary compatibility with some
  130291. ** legacy applications. */
  130292. iDb = sqlite3FindDb(pParse->db, pNm);
  130293. if( iDb<0 ) iDb = 0;
  130294. #endif
  130295. }
  130296. if( iDb!=1 ){
  130297. int iIntoReg = 0;
  130298. if( pInto && sqlite3ResolveSelfReference(pParse,0,0,pInto,0)==0 ){
  130299. iIntoReg = ++pParse->nMem;
  130300. sqlite3ExprCode(pParse, pInto, iIntoReg);
  130301. }
  130302. sqlite3VdbeAddOp2(v, OP_Vacuum, iDb, iIntoReg);
  130303. sqlite3VdbeUsesBtree(v, iDb);
  130304. }
  130305. build_vacuum_end:
  130306. sqlite3ExprDelete(pParse->db, pInto);
  130307. return;
  130308. }
  130309. /*
  130310. ** This routine implements the OP_Vacuum opcode of the VDBE.
  130311. */
  130312. SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3RunVacuum(
  130313. char **pzErrMsg, /* Write error message here */
  130314. sqlite3 *db, /* Database connection */
  130315. int iDb, /* Which attached DB to vacuum */
  130316. sqlite3_value *pOut /* Write results here, if not NULL. VACUUM INTO */
  130317. ){
  130318. int rc = SQLITE_OK; /* Return code from service routines */
  130319. Btree *pMain; /* The database being vacuumed */
  130320. Btree *pTemp; /* The temporary database we vacuum into */
  130321. u32 saved_mDbFlags; /* Saved value of db->mDbFlags */
  130322. u64 saved_flags; /* Saved value of db->flags */
  130323. int saved_nChange; /* Saved value of db->nChange */
  130324. int saved_nTotalChange; /* Saved value of db->nTotalChange */
  130325. u32 saved_openFlags; /* Saved value of db->openFlags */
  130326. u8 saved_mTrace; /* Saved trace settings */
  130327. Db *pDb = 0; /* Database to detach at end of vacuum */
  130328. int isMemDb; /* True if vacuuming a :memory: database */
  130329. int nRes; /* Bytes of reserved space at the end of each page */
  130330. int nDb; /* Number of attached databases */
  130331. const char *zDbMain; /* Schema name of database to vacuum */
  130332. const char *zOut; /* Name of output file */
  130333. if( !db->autoCommit ){
  130334. sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
  130335. return SQLITE_ERROR; /* IMP: R-12218-18073 */
  130336. }
  130337. if( db->nVdbeActive>1 ){
  130338. sqlite3SetString(pzErrMsg, db,"cannot VACUUM - SQL statements in progress");
  130339. return SQLITE_ERROR; /* IMP: R-15610-35227 */
  130340. }
  130341. saved_openFlags = db->openFlags;
  130342. if( pOut ){
  130343. if( sqlite3_value_type(pOut)!=SQLITE_TEXT ){
  130344. sqlite3SetString(pzErrMsg, db, "non-text filename");
  130345. return SQLITE_ERROR;
  130346. }
  130347. zOut = (const char*)sqlite3_value_text(pOut);
  130348. db->openFlags &= ~SQLITE_OPEN_READONLY;
  130349. db->openFlags |= SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE;
  130350. }else{
  130351. zOut = "";
  130352. }
  130353. /* Save the current value of the database flags so that it can be
  130354. ** restored before returning. Then set the writable-schema flag, and
  130355. ** disable CHECK and foreign key constraints. */
  130356. saved_flags = db->flags;
  130357. saved_mDbFlags = db->mDbFlags;
  130358. saved_nChange = db->nChange;
  130359. saved_nTotalChange = db->nTotalChange;
  130360. saved_mTrace = db->mTrace;
  130361. db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks;
  130362. db->mDbFlags |= DBFLAG_PreferBuiltin | DBFLAG_Vacuum;
  130363. db->flags &= ~(u64)(SQLITE_ForeignKeys | SQLITE_ReverseOrder
  130364. | SQLITE_Defensive | SQLITE_CountRows);
  130365. db->mTrace = 0;
  130366. zDbMain = db->aDb[iDb].zDbSName;
  130367. pMain = db->aDb[iDb].pBt;
  130368. isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain));
  130369. /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
  130370. ** can be set to 'off' for this file, as it is not recovered if a crash
  130371. ** occurs anyway. The integrity of the database is maintained by a
  130372. ** (possibly synchronous) transaction opened on the main database before
  130373. ** sqlite3BtreeCopyFile() is called.
  130374. **
  130375. ** An optimisation would be to use a non-journaled pager.
  130376. ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
  130377. ** that actually made the VACUUM run slower. Very little journalling
  130378. ** actually occurs when doing a vacuum since the vacuum_db is initially
  130379. ** empty. Only the journal header is written. Apparently it takes more
  130380. ** time to parse and run the PRAGMA to turn journalling off than it does
  130381. ** to write the journal header file.
  130382. */
  130383. nDb = db->nDb;
  130384. rc = execSqlF(db, pzErrMsg, "ATTACH %Q AS vacuum_db", zOut);
  130385. db->openFlags = saved_openFlags;
  130386. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  130387. assert( (db->nDb-1)==nDb );
  130388. pDb = &db->aDb[nDb];
  130389. assert( strcmp(pDb->zDbSName,"vacuum_db")==0 );
  130390. pTemp = pDb->pBt;
  130391. if( pOut ){
  130392. sqlite3_file *id = sqlite3PagerFile(sqlite3BtreePager(pTemp));
  130393. i64 sz = 0;
  130394. if( id->pMethods!=0 && (sqlite3OsFileSize(id, &sz)!=SQLITE_OK || sz>0) ){
  130395. rc = SQLITE_ERROR;
  130396. sqlite3SetString(pzErrMsg, db, "output file already exists");
  130397. goto end_of_vacuum;
  130398. }
  130399. db->mDbFlags |= DBFLAG_VacuumInto;
  130400. }
  130401. nRes = sqlite3BtreeGetRequestedReserve(pMain);
  130402. sqlite3BtreeSetCacheSize(pTemp, db->aDb[iDb].pSchema->cache_size);
  130403. sqlite3BtreeSetSpillSize(pTemp, sqlite3BtreeSetSpillSize(pMain,0));
  130404. sqlite3BtreeSetPagerFlags(pTemp, PAGER_SYNCHRONOUS_OFF|PAGER_CACHESPILL);
  130405. /* Begin a transaction and take an exclusive lock on the main database
  130406. ** file. This is done before the sqlite3BtreeGetPageSize(pMain) call below,
  130407. ** to ensure that we do not try to change the page-size on a WAL database.
  130408. */
  130409. rc = execSql(db, pzErrMsg, "BEGIN");
  130410. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  130411. rc = sqlite3BtreeBeginTrans(pMain, pOut==0 ? 2 : 0, 0);
  130412. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  130413. /* Do not attempt to change the page size for a WAL database */
  130414. if( sqlite3PagerGetJournalMode(sqlite3BtreePager(pMain))
  130415. ==PAGER_JOURNALMODE_WAL ){
  130416. db->nextPagesize = 0;
  130417. }
  130418. if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0)
  130419. || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
  130420. || NEVER(db->mallocFailed)
  130421. ){
  130422. rc = SQLITE_NOMEM_BKPT;
  130423. goto end_of_vacuum;
  130424. }
  130425. #ifndef SQLITE_OMIT_AUTOVACUUM
  130426. sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
  130427. sqlite3BtreeGetAutoVacuum(pMain));
  130428. #endif
  130429. /* Query the schema of the main database. Create a mirror schema
  130430. ** in the temporary database.
  130431. */
  130432. db->init.iDb = nDb; /* force new CREATE statements into vacuum_db */
  130433. rc = execSqlF(db, pzErrMsg,
  130434. "SELECT sql FROM \"%w\".sqlite_master"
  130435. " WHERE type='table'AND name<>'sqlite_sequence'"
  130436. " AND coalesce(rootpage,1)>0",
  130437. zDbMain
  130438. );
  130439. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  130440. rc = execSqlF(db, pzErrMsg,
  130441. "SELECT sql FROM \"%w\".sqlite_master"
  130442. " WHERE type='index'",
  130443. zDbMain
  130444. );
  130445. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  130446. db->init.iDb = 0;
  130447. /* Loop through the tables in the main database. For each, do
  130448. ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy
  130449. ** the contents to the temporary database.
  130450. */
  130451. rc = execSqlF(db, pzErrMsg,
  130452. "SELECT'INSERT INTO vacuum_db.'||quote(name)"
  130453. "||' SELECT*FROM\"%w\".'||quote(name)"
  130454. "FROM vacuum_db.sqlite_master "
  130455. "WHERE type='table'AND coalesce(rootpage,1)>0",
  130456. zDbMain
  130457. );
  130458. assert( (db->mDbFlags & DBFLAG_Vacuum)!=0 );
  130459. db->mDbFlags &= ~DBFLAG_Vacuum;
  130460. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  130461. /* Copy the triggers, views, and virtual tables from the main database
  130462. ** over to the temporary database. None of these objects has any
  130463. ** associated storage, so all we have to do is copy their entries
  130464. ** from the SQLITE_MASTER table.
  130465. */
  130466. rc = execSqlF(db, pzErrMsg,
  130467. "INSERT INTO vacuum_db.sqlite_master"
  130468. " SELECT*FROM \"%w\".sqlite_master"
  130469. " WHERE type IN('view','trigger')"
  130470. " OR(type='table'AND rootpage=0)",
  130471. zDbMain
  130472. );
  130473. if( rc ) goto end_of_vacuum;
  130474. /* At this point, there is a write transaction open on both the
  130475. ** vacuum database and the main database. Assuming no error occurs,
  130476. ** both transactions are closed by this block - the main database
  130477. ** transaction by sqlite3BtreeCopyFile() and the other by an explicit
  130478. ** call to sqlite3BtreeCommit().
  130479. */
  130480. {
  130481. u32 meta;
  130482. int i;
  130483. /* This array determines which meta meta values are preserved in the
  130484. ** vacuum. Even entries are the meta value number and odd entries
  130485. ** are an increment to apply to the meta value after the vacuum.
  130486. ** The increment is used to increase the schema cookie so that other
  130487. ** connections to the same database will know to reread the schema.
  130488. */
  130489. static const unsigned char aCopy[] = {
  130490. BTREE_SCHEMA_VERSION, 1, /* Add one to the old schema cookie */
  130491. BTREE_DEFAULT_CACHE_SIZE, 0, /* Preserve the default page cache size */
  130492. BTREE_TEXT_ENCODING, 0, /* Preserve the text encoding */
  130493. BTREE_USER_VERSION, 0, /* Preserve the user version */
  130494. BTREE_APPLICATION_ID, 0, /* Preserve the application id */
  130495. };
  130496. assert( 1==sqlite3BtreeIsInTrans(pTemp) );
  130497. assert( pOut!=0 || 1==sqlite3BtreeIsInTrans(pMain) );
  130498. /* Copy Btree meta values */
  130499. for(i=0; i<ArraySize(aCopy); i+=2){
  130500. /* GetMeta() and UpdateMeta() cannot fail in this context because
  130501. ** we already have page 1 loaded into cache and marked dirty. */
  130502. sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
  130503. rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
  130504. if( NEVER(rc!=SQLITE_OK) ) goto end_of_vacuum;
  130505. }
  130506. if( pOut==0 ){
  130507. rc = sqlite3BtreeCopyFile(pMain, pTemp);
  130508. }
  130509. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  130510. rc = sqlite3BtreeCommit(pTemp);
  130511. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  130512. #ifndef SQLITE_OMIT_AUTOVACUUM
  130513. if( pOut==0 ){
  130514. sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));
  130515. }
  130516. #endif
  130517. }
  130518. assert( rc==SQLITE_OK );
  130519. if( pOut==0 ){
  130520. rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1);
  130521. }
  130522. end_of_vacuum:
  130523. /* Restore the original value of db->flags */
  130524. db->init.iDb = 0;
  130525. db->mDbFlags = saved_mDbFlags;
  130526. db->flags = saved_flags;
  130527. db->nChange = saved_nChange;
  130528. db->nTotalChange = saved_nTotalChange;
  130529. db->mTrace = saved_mTrace;
  130530. sqlite3BtreeSetPageSize(pMain, -1, 0, 1);
  130531. /* Currently there is an SQL level transaction open on the vacuum
  130532. ** database. No locks are held on any other files (since the main file
  130533. ** was committed at the btree level). So it safe to end the transaction
  130534. ** by manually setting the autoCommit flag to true and detaching the
  130535. ** vacuum database. The vacuum_db journal file is deleted when the pager
  130536. ** is closed by the DETACH.
  130537. */
  130538. db->autoCommit = 1;
  130539. if( pDb ){
  130540. sqlite3BtreeClose(pDb->pBt);
  130541. pDb->pBt = 0;
  130542. pDb->pSchema = 0;
  130543. }
  130544. /* This both clears the schemas and reduces the size of the db->aDb[]
  130545. ** array. */
  130546. sqlite3ResetAllSchemasOfConnection(db);
  130547. return rc;
  130548. }
  130549. #endif /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
  130550. /************** End of vacuum.c **********************************************/
  130551. /************** Begin file vtab.c ********************************************/
  130552. /*
  130553. ** 2006 June 10
  130554. **
  130555. ** The author disclaims copyright to this source code. In place of
  130556. ** a legal notice, here is a blessing:
  130557. **
  130558. ** May you do good and not evil.
  130559. ** May you find forgiveness for yourself and forgive others.
  130560. ** May you share freely, never taking more than you give.
  130561. **
  130562. *************************************************************************
  130563. ** This file contains code used to help implement virtual tables.
  130564. */
  130565. #ifndef SQLITE_OMIT_VIRTUALTABLE
  130566. /* #include "sqliteInt.h" */
  130567. /*
  130568. ** Before a virtual table xCreate() or xConnect() method is invoked, the
  130569. ** sqlite3.pVtabCtx member variable is set to point to an instance of
  130570. ** this struct allocated on the stack. It is used by the implementation of
  130571. ** the sqlite3_declare_vtab() and sqlite3_vtab_config() APIs, both of which
  130572. ** are invoked only from within xCreate and xConnect methods.
  130573. */
  130574. struct VtabCtx {
  130575. VTable *pVTable; /* The virtual table being constructed */
  130576. Table *pTab; /* The Table object to which the virtual table belongs */
  130577. VtabCtx *pPrior; /* Parent context (if any) */
  130578. int bDeclared; /* True after sqlite3_declare_vtab() is called */
  130579. };
  130580. /*
  130581. ** Construct and install a Module object for a virtual table. When this
  130582. ** routine is called, it is guaranteed that all appropriate locks are held
  130583. ** and the module is not already part of the connection.
  130584. **
  130585. ** If there already exists a module with zName, replace it with the new one.
  130586. ** If pModule==0, then delete the module zName if it exists.
  130587. */
  130588. SQLITE_PRIVATE Module *sqlite3VtabCreateModule(
  130589. sqlite3 *db, /* Database in which module is registered */
  130590. const char *zName, /* Name assigned to this module */
  130591. const sqlite3_module *pModule, /* The definition of the module */
  130592. void *pAux, /* Context pointer for xCreate/xConnect */
  130593. void (*xDestroy)(void *) /* Module destructor function */
  130594. ){
  130595. Module *pMod;
  130596. Module *pDel;
  130597. char *zCopy;
  130598. if( pModule==0 ){
  130599. zCopy = (char*)zName;
  130600. pMod = 0;
  130601. }else{
  130602. int nName = sqlite3Strlen30(zName);
  130603. pMod = (Module *)sqlite3Malloc(sizeof(Module) + nName + 1);
  130604. if( pMod==0 ){
  130605. sqlite3OomFault(db);
  130606. return 0;
  130607. }
  130608. zCopy = (char *)(&pMod[1]);
  130609. memcpy(zCopy, zName, nName+1);
  130610. pMod->zName = zCopy;
  130611. pMod->pModule = pModule;
  130612. pMod->pAux = pAux;
  130613. pMod->xDestroy = xDestroy;
  130614. pMod->pEpoTab = 0;
  130615. pMod->nRefModule = 1;
  130616. }
  130617. pDel = (Module *)sqlite3HashInsert(&db->aModule,zCopy,(void*)pMod);
  130618. if( pDel ){
  130619. if( pDel==pMod ){
  130620. sqlite3OomFault(db);
  130621. sqlite3DbFree(db, pDel);
  130622. pMod = 0;
  130623. }else{
  130624. sqlite3VtabEponymousTableClear(db, pDel);
  130625. sqlite3VtabModuleUnref(db, pDel);
  130626. }
  130627. }
  130628. return pMod;
  130629. }
  130630. /*
  130631. ** The actual function that does the work of creating a new module.
  130632. ** This function implements the sqlite3_create_module() and
  130633. ** sqlite3_create_module_v2() interfaces.
  130634. */
  130635. static int createModule(
  130636. sqlite3 *db, /* Database in which module is registered */
  130637. const char *zName, /* Name assigned to this module */
  130638. const sqlite3_module *pModule, /* The definition of the module */
  130639. void *pAux, /* Context pointer for xCreate/xConnect */
  130640. void (*xDestroy)(void *) /* Module destructor function */
  130641. ){
  130642. int rc = SQLITE_OK;
  130643. sqlite3_mutex_enter(db->mutex);
  130644. (void)sqlite3VtabCreateModule(db, zName, pModule, pAux, xDestroy);
  130645. rc = sqlite3ApiExit(db, rc);
  130646. if( rc!=SQLITE_OK && xDestroy ) xDestroy(pAux);
  130647. sqlite3_mutex_leave(db->mutex);
  130648. return rc;
  130649. }
  130650. /*
  130651. ** External API function used to create a new virtual-table module.
  130652. */
  130653. SQLITE_API int sqlite3_create_module(
  130654. sqlite3 *db, /* Database in which module is registered */
  130655. const char *zName, /* Name assigned to this module */
  130656. const sqlite3_module *pModule, /* The definition of the module */
  130657. void *pAux /* Context pointer for xCreate/xConnect */
  130658. ){
  130659. #ifdef SQLITE_ENABLE_API_ARMOR
  130660. if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
  130661. #endif
  130662. return createModule(db, zName, pModule, pAux, 0);
  130663. }
  130664. /*
  130665. ** External API function used to create a new virtual-table module.
  130666. */
  130667. SQLITE_API int sqlite3_create_module_v2(
  130668. sqlite3 *db, /* Database in which module is registered */
  130669. const char *zName, /* Name assigned to this module */
  130670. const sqlite3_module *pModule, /* The definition of the module */
  130671. void *pAux, /* Context pointer for xCreate/xConnect */
  130672. void (*xDestroy)(void *) /* Module destructor function */
  130673. ){
  130674. #ifdef SQLITE_ENABLE_API_ARMOR
  130675. if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
  130676. #endif
  130677. return createModule(db, zName, pModule, pAux, xDestroy);
  130678. }
  130679. /*
  130680. ** External API to drop all virtual-table modules, except those named
  130681. ** on the azNames list.
  130682. */
  130683. SQLITE_API int sqlite3_drop_modules(sqlite3 *db, const char** azNames){
  130684. HashElem *pThis, *pNext;
  130685. #ifdef SQLITE_ENABLE_API_ARMOR
  130686. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  130687. #endif
  130688. for(pThis=sqliteHashFirst(&db->aModule); pThis; pThis=pNext){
  130689. Module *pMod = (Module*)sqliteHashData(pThis);
  130690. pNext = sqliteHashNext(pThis);
  130691. if( azNames ){
  130692. int ii;
  130693. for(ii=0; azNames[ii]!=0 && strcmp(azNames[ii],pMod->zName)!=0; ii++){}
  130694. if( azNames[ii]!=0 ) continue;
  130695. }
  130696. createModule(db, pMod->zName, 0, 0, 0);
  130697. }
  130698. return SQLITE_OK;
  130699. }
  130700. /*
  130701. ** Decrement the reference count on a Module object. Destroy the
  130702. ** module when the reference count reaches zero.
  130703. */
  130704. SQLITE_PRIVATE void sqlite3VtabModuleUnref(sqlite3 *db, Module *pMod){
  130705. assert( pMod->nRefModule>0 );
  130706. pMod->nRefModule--;
  130707. if( pMod->nRefModule==0 ){
  130708. if( pMod->xDestroy ){
  130709. pMod->xDestroy(pMod->pAux);
  130710. }
  130711. assert( pMod->pEpoTab==0 );
  130712. sqlite3DbFree(db, pMod);
  130713. }
  130714. }
  130715. /*
  130716. ** Lock the virtual table so that it cannot be disconnected.
  130717. ** Locks nest. Every lock should have a corresponding unlock.
  130718. ** If an unlock is omitted, resources leaks will occur.
  130719. **
  130720. ** If a disconnect is attempted while a virtual table is locked,
  130721. ** the disconnect is deferred until all locks have been removed.
  130722. */
  130723. SQLITE_PRIVATE void sqlite3VtabLock(VTable *pVTab){
  130724. pVTab->nRef++;
  130725. }
  130726. /*
  130727. ** pTab is a pointer to a Table structure representing a virtual-table.
  130728. ** Return a pointer to the VTable object used by connection db to access
  130729. ** this virtual-table, if one has been created, or NULL otherwise.
  130730. */
  130731. SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3 *db, Table *pTab){
  130732. VTable *pVtab;
  130733. assert( IsVirtual(pTab) );
  130734. for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext);
  130735. return pVtab;
  130736. }
  130737. /*
  130738. ** Decrement the ref-count on a virtual table object. When the ref-count
  130739. ** reaches zero, call the xDisconnect() method to delete the object.
  130740. */
  130741. SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *pVTab){
  130742. sqlite3 *db = pVTab->db;
  130743. assert( db );
  130744. assert( pVTab->nRef>0 );
  130745. assert( db->magic==SQLITE_MAGIC_OPEN || db->magic==SQLITE_MAGIC_ZOMBIE );
  130746. pVTab->nRef--;
  130747. if( pVTab->nRef==0 ){
  130748. sqlite3_vtab *p = pVTab->pVtab;
  130749. sqlite3VtabModuleUnref(pVTab->db, pVTab->pMod);
  130750. if( p ){
  130751. p->pModule->xDisconnect(p);
  130752. }
  130753. sqlite3DbFree(db, pVTab);
  130754. }
  130755. }
  130756. /*
  130757. ** Table p is a virtual table. This function moves all elements in the
  130758. ** p->pVTable list to the sqlite3.pDisconnect lists of their associated
  130759. ** database connections to be disconnected at the next opportunity.
  130760. ** Except, if argument db is not NULL, then the entry associated with
  130761. ** connection db is left in the p->pVTable list.
  130762. */
  130763. static VTable *vtabDisconnectAll(sqlite3 *db, Table *p){
  130764. VTable *pRet = 0;
  130765. VTable *pVTable = p->pVTable;
  130766. p->pVTable = 0;
  130767. /* Assert that the mutex (if any) associated with the BtShared database
  130768. ** that contains table p is held by the caller. See header comments
  130769. ** above function sqlite3VtabUnlockList() for an explanation of why
  130770. ** this makes it safe to access the sqlite3.pDisconnect list of any
  130771. ** database connection that may have an entry in the p->pVTable list.
  130772. */
  130773. assert( db==0 || sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
  130774. while( pVTable ){
  130775. sqlite3 *db2 = pVTable->db;
  130776. VTable *pNext = pVTable->pNext;
  130777. assert( db2 );
  130778. if( db2==db ){
  130779. pRet = pVTable;
  130780. p->pVTable = pRet;
  130781. pRet->pNext = 0;
  130782. }else{
  130783. pVTable->pNext = db2->pDisconnect;
  130784. db2->pDisconnect = pVTable;
  130785. }
  130786. pVTable = pNext;
  130787. }
  130788. assert( !db || pRet );
  130789. return pRet;
  130790. }
  130791. /*
  130792. ** Table *p is a virtual table. This function removes the VTable object
  130793. ** for table *p associated with database connection db from the linked
  130794. ** list in p->pVTab. It also decrements the VTable ref count. This is
  130795. ** used when closing database connection db to free all of its VTable
  130796. ** objects without disturbing the rest of the Schema object (which may
  130797. ** be being used by other shared-cache connections).
  130798. */
  130799. SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p){
  130800. VTable **ppVTab;
  130801. assert( IsVirtual(p) );
  130802. assert( sqlite3BtreeHoldsAllMutexes(db) );
  130803. assert( sqlite3_mutex_held(db->mutex) );
  130804. for(ppVTab=&p->pVTable; *ppVTab; ppVTab=&(*ppVTab)->pNext){
  130805. if( (*ppVTab)->db==db ){
  130806. VTable *pVTab = *ppVTab;
  130807. *ppVTab = pVTab->pNext;
  130808. sqlite3VtabUnlock(pVTab);
  130809. break;
  130810. }
  130811. }
  130812. }
  130813. /*
  130814. ** Disconnect all the virtual table objects in the sqlite3.pDisconnect list.
  130815. **
  130816. ** This function may only be called when the mutexes associated with all
  130817. ** shared b-tree databases opened using connection db are held by the
  130818. ** caller. This is done to protect the sqlite3.pDisconnect list. The
  130819. ** sqlite3.pDisconnect list is accessed only as follows:
  130820. **
  130821. ** 1) By this function. In this case, all BtShared mutexes and the mutex
  130822. ** associated with the database handle itself must be held.
  130823. **
  130824. ** 2) By function vtabDisconnectAll(), when it adds a VTable entry to
  130825. ** the sqlite3.pDisconnect list. In this case either the BtShared mutex
  130826. ** associated with the database the virtual table is stored in is held
  130827. ** or, if the virtual table is stored in a non-sharable database, then
  130828. ** the database handle mutex is held.
  130829. **
  130830. ** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously
  130831. ** by multiple threads. It is thread-safe.
  130832. */
  130833. SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3 *db){
  130834. VTable *p = db->pDisconnect;
  130835. assert( sqlite3BtreeHoldsAllMutexes(db) );
  130836. assert( sqlite3_mutex_held(db->mutex) );
  130837. if( p ){
  130838. db->pDisconnect = 0;
  130839. sqlite3ExpirePreparedStatements(db, 0);
  130840. do {
  130841. VTable *pNext = p->pNext;
  130842. sqlite3VtabUnlock(p);
  130843. p = pNext;
  130844. }while( p );
  130845. }
  130846. }
  130847. /*
  130848. ** Clear any and all virtual-table information from the Table record.
  130849. ** This routine is called, for example, just before deleting the Table
  130850. ** record.
  130851. **
  130852. ** Since it is a virtual-table, the Table structure contains a pointer
  130853. ** to the head of a linked list of VTable structures. Each VTable
  130854. ** structure is associated with a single sqlite3* user of the schema.
  130855. ** The reference count of the VTable structure associated with database
  130856. ** connection db is decremented immediately (which may lead to the
  130857. ** structure being xDisconnected and free). Any other VTable structures
  130858. ** in the list are moved to the sqlite3.pDisconnect list of the associated
  130859. ** database connection.
  130860. */
  130861. SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table *p){
  130862. if( !db || db->pnBytesFreed==0 ) vtabDisconnectAll(0, p);
  130863. if( p->azModuleArg ){
  130864. int i;
  130865. for(i=0; i<p->nModuleArg; i++){
  130866. if( i!=1 ) sqlite3DbFree(db, p->azModuleArg[i]);
  130867. }
  130868. sqlite3DbFree(db, p->azModuleArg);
  130869. }
  130870. }
  130871. /*
  130872. ** Add a new module argument to pTable->azModuleArg[].
  130873. ** The string is not copied - the pointer is stored. The
  130874. ** string will be freed automatically when the table is
  130875. ** deleted.
  130876. */
  130877. static void addModuleArgument(Parse *pParse, Table *pTable, char *zArg){
  130878. sqlite3_int64 nBytes = sizeof(char *)*(2+pTable->nModuleArg);
  130879. char **azModuleArg;
  130880. sqlite3 *db = pParse->db;
  130881. if( pTable->nModuleArg+3>=db->aLimit[SQLITE_LIMIT_COLUMN] ){
  130882. sqlite3ErrorMsg(pParse, "too many columns on %s", pTable->zName);
  130883. }
  130884. azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
  130885. if( azModuleArg==0 ){
  130886. sqlite3DbFree(db, zArg);
  130887. }else{
  130888. int i = pTable->nModuleArg++;
  130889. azModuleArg[i] = zArg;
  130890. azModuleArg[i+1] = 0;
  130891. pTable->azModuleArg = azModuleArg;
  130892. }
  130893. }
  130894. /*
  130895. ** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
  130896. ** statement. The module name has been parsed, but the optional list
  130897. ** of parameters that follow the module name are still pending.
  130898. */
  130899. SQLITE_PRIVATE void sqlite3VtabBeginParse(
  130900. Parse *pParse, /* Parsing context */
  130901. Token *pName1, /* Name of new table, or database name */
  130902. Token *pName2, /* Name of new table or NULL */
  130903. Token *pModuleName, /* Name of the module for the virtual table */
  130904. int ifNotExists /* No error if the table already exists */
  130905. ){
  130906. Table *pTable; /* The new virtual table */
  130907. sqlite3 *db; /* Database connection */
  130908. sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, ifNotExists);
  130909. pTable = pParse->pNewTable;
  130910. if( pTable==0 ) return;
  130911. assert( 0==pTable->pIndex );
  130912. db = pParse->db;
  130913. assert( pTable->nModuleArg==0 );
  130914. addModuleArgument(pParse, pTable, sqlite3NameFromToken(db, pModuleName));
  130915. addModuleArgument(pParse, pTable, 0);
  130916. addModuleArgument(pParse, pTable, sqlite3DbStrDup(db, pTable->zName));
  130917. assert( (pParse->sNameToken.z==pName2->z && pName2->z!=0)
  130918. || (pParse->sNameToken.z==pName1->z && pName2->z==0)
  130919. );
  130920. pParse->sNameToken.n = (int)(
  130921. &pModuleName->z[pModuleName->n] - pParse->sNameToken.z
  130922. );
  130923. #ifndef SQLITE_OMIT_AUTHORIZATION
  130924. /* Creating a virtual table invokes the authorization callback twice.
  130925. ** The first invocation, to obtain permission to INSERT a row into the
  130926. ** sqlite_master table, has already been made by sqlite3StartTable().
  130927. ** The second call, to obtain permission to create the table, is made now.
  130928. */
  130929. if( pTable->azModuleArg ){
  130930. int iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
  130931. assert( iDb>=0 ); /* The database the table is being created in */
  130932. sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName,
  130933. pTable->azModuleArg[0], pParse->db->aDb[iDb].zDbSName);
  130934. }
  130935. #endif
  130936. }
  130937. /*
  130938. ** This routine takes the module argument that has been accumulating
  130939. ** in pParse->zArg[] and appends it to the list of arguments on the
  130940. ** virtual table currently under construction in pParse->pTable.
  130941. */
  130942. static void addArgumentToVtab(Parse *pParse){
  130943. if( pParse->sArg.z && pParse->pNewTable ){
  130944. const char *z = (const char*)pParse->sArg.z;
  130945. int n = pParse->sArg.n;
  130946. sqlite3 *db = pParse->db;
  130947. addModuleArgument(pParse, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
  130948. }
  130949. }
  130950. /*
  130951. ** The parser calls this routine after the CREATE VIRTUAL TABLE statement
  130952. ** has been completely parsed.
  130953. */
  130954. SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
  130955. Table *pTab = pParse->pNewTable; /* The table being constructed */
  130956. sqlite3 *db = pParse->db; /* The database connection */
  130957. if( pTab==0 ) return;
  130958. addArgumentToVtab(pParse);
  130959. pParse->sArg.z = 0;
  130960. if( pTab->nModuleArg<1 ) return;
  130961. /* If the CREATE VIRTUAL TABLE statement is being entered for the
  130962. ** first time (in other words if the virtual table is actually being
  130963. ** created now instead of just being read out of sqlite_master) then
  130964. ** do additional initialization work and store the statement text
  130965. ** in the sqlite_master table.
  130966. */
  130967. if( !db->init.busy ){
  130968. char *zStmt;
  130969. char *zWhere;
  130970. int iDb;
  130971. int iReg;
  130972. Vdbe *v;
  130973. sqlite3MayAbort(pParse);
  130974. /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
  130975. if( pEnd ){
  130976. pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;
  130977. }
  130978. zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
  130979. /* A slot for the record has already been allocated in the
  130980. ** SQLITE_MASTER table. We just need to update that slot with all
  130981. ** the information we've collected.
  130982. **
  130983. ** The VM register number pParse->regRowid holds the rowid of an
  130984. ** entry in the sqlite_master table tht was created for this vtab
  130985. ** by sqlite3StartTable().
  130986. */
  130987. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  130988. sqlite3NestedParse(pParse,
  130989. "UPDATE %Q.%s "
  130990. "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
  130991. "WHERE rowid=#%d",
  130992. db->aDb[iDb].zDbSName, MASTER_NAME,
  130993. pTab->zName,
  130994. pTab->zName,
  130995. zStmt,
  130996. pParse->regRowid
  130997. );
  130998. v = sqlite3GetVdbe(pParse);
  130999. sqlite3ChangeCookie(pParse, iDb);
  131000. sqlite3VdbeAddOp0(v, OP_Expire);
  131001. zWhere = sqlite3MPrintf(db, "name=%Q AND sql=%Q", pTab->zName, zStmt);
  131002. sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
  131003. sqlite3DbFree(db, zStmt);
  131004. iReg = ++pParse->nMem;
  131005. sqlite3VdbeLoadString(v, iReg, pTab->zName);
  131006. sqlite3VdbeAddOp2(v, OP_VCreate, iDb, iReg);
  131007. }
  131008. /* If we are rereading the sqlite_master table create the in-memory
  131009. ** record of the table. The xConnect() method is not called until
  131010. ** the first time the virtual table is used in an SQL statement. This
  131011. ** allows a schema that contains virtual tables to be loaded before
  131012. ** the required virtual table implementations are registered. */
  131013. else {
  131014. Table *pOld;
  131015. Schema *pSchema = pTab->pSchema;
  131016. const char *zName = pTab->zName;
  131017. assert( sqlite3SchemaMutexHeld(db, 0, pSchema) );
  131018. pOld = sqlite3HashInsert(&pSchema->tblHash, zName, pTab);
  131019. if( pOld ){
  131020. sqlite3OomFault(db);
  131021. assert( pTab==pOld ); /* Malloc must have failed inside HashInsert() */
  131022. return;
  131023. }
  131024. pParse->pNewTable = 0;
  131025. }
  131026. }
  131027. /*
  131028. ** The parser calls this routine when it sees the first token
  131029. ** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
  131030. */
  131031. SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){
  131032. addArgumentToVtab(pParse);
  131033. pParse->sArg.z = 0;
  131034. pParse->sArg.n = 0;
  131035. }
  131036. /*
  131037. ** The parser calls this routine for each token after the first token
  131038. ** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
  131039. */
  131040. SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){
  131041. Token *pArg = &pParse->sArg;
  131042. if( pArg->z==0 ){
  131043. pArg->z = p->z;
  131044. pArg->n = p->n;
  131045. }else{
  131046. assert(pArg->z <= p->z);
  131047. pArg->n = (int)(&p->z[p->n] - pArg->z);
  131048. }
  131049. }
  131050. /*
  131051. ** Invoke a virtual table constructor (either xCreate or xConnect). The
  131052. ** pointer to the function to invoke is passed as the fourth parameter
  131053. ** to this procedure.
  131054. */
  131055. static int vtabCallConstructor(
  131056. sqlite3 *db,
  131057. Table *pTab,
  131058. Module *pMod,
  131059. int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
  131060. char **pzErr
  131061. ){
  131062. VtabCtx sCtx;
  131063. VTable *pVTable;
  131064. int rc;
  131065. const char *const*azArg = (const char *const*)pTab->azModuleArg;
  131066. int nArg = pTab->nModuleArg;
  131067. char *zErr = 0;
  131068. char *zModuleName;
  131069. int iDb;
  131070. VtabCtx *pCtx;
  131071. /* Check that the virtual-table is not already being initialized */
  131072. for(pCtx=db->pVtabCtx; pCtx; pCtx=pCtx->pPrior){
  131073. if( pCtx->pTab==pTab ){
  131074. *pzErr = sqlite3MPrintf(db,
  131075. "vtable constructor called recursively: %s", pTab->zName
  131076. );
  131077. return SQLITE_LOCKED;
  131078. }
  131079. }
  131080. zModuleName = sqlite3DbStrDup(db, pTab->zName);
  131081. if( !zModuleName ){
  131082. return SQLITE_NOMEM_BKPT;
  131083. }
  131084. pVTable = sqlite3MallocZero(sizeof(VTable));
  131085. if( !pVTable ){
  131086. sqlite3OomFault(db);
  131087. sqlite3DbFree(db, zModuleName);
  131088. return SQLITE_NOMEM_BKPT;
  131089. }
  131090. pVTable->db = db;
  131091. pVTable->pMod = pMod;
  131092. pVTable->eVtabRisk = SQLITE_VTABRISK_Normal;
  131093. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  131094. pTab->azModuleArg[1] = db->aDb[iDb].zDbSName;
  131095. /* Invoke the virtual table constructor */
  131096. assert( &db->pVtabCtx );
  131097. assert( xConstruct );
  131098. sCtx.pTab = pTab;
  131099. sCtx.pVTable = pVTable;
  131100. sCtx.pPrior = db->pVtabCtx;
  131101. sCtx.bDeclared = 0;
  131102. db->pVtabCtx = &sCtx;
  131103. rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);
  131104. db->pVtabCtx = sCtx.pPrior;
  131105. if( rc==SQLITE_NOMEM ) sqlite3OomFault(db);
  131106. assert( sCtx.pTab==pTab );
  131107. if( SQLITE_OK!=rc ){
  131108. if( zErr==0 ){
  131109. *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
  131110. }else {
  131111. *pzErr = sqlite3MPrintf(db, "%s", zErr);
  131112. sqlite3_free(zErr);
  131113. }
  131114. sqlite3DbFree(db, pVTable);
  131115. }else if( ALWAYS(pVTable->pVtab) ){
  131116. /* Justification of ALWAYS(): A correct vtab constructor must allocate
  131117. ** the sqlite3_vtab object if successful. */
  131118. memset(pVTable->pVtab, 0, sizeof(pVTable->pVtab[0]));
  131119. pVTable->pVtab->pModule = pMod->pModule;
  131120. pMod->nRefModule++;
  131121. pVTable->nRef = 1;
  131122. if( sCtx.bDeclared==0 ){
  131123. const char *zFormat = "vtable constructor did not declare schema: %s";
  131124. *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
  131125. sqlite3VtabUnlock(pVTable);
  131126. rc = SQLITE_ERROR;
  131127. }else{
  131128. int iCol;
  131129. u16 oooHidden = 0;
  131130. /* If everything went according to plan, link the new VTable structure
  131131. ** into the linked list headed by pTab->pVTable. Then loop through the
  131132. ** columns of the table to see if any of them contain the token "hidden".
  131133. ** If so, set the Column COLFLAG_HIDDEN flag and remove the token from
  131134. ** the type string. */
  131135. pVTable->pNext = pTab->pVTable;
  131136. pTab->pVTable = pVTable;
  131137. for(iCol=0; iCol<pTab->nCol; iCol++){
  131138. char *zType = sqlite3ColumnType(&pTab->aCol[iCol], "");
  131139. int nType;
  131140. int i = 0;
  131141. nType = sqlite3Strlen30(zType);
  131142. for(i=0; i<nType; i++){
  131143. if( 0==sqlite3StrNICmp("hidden", &zType[i], 6)
  131144. && (i==0 || zType[i-1]==' ')
  131145. && (zType[i+6]=='\0' || zType[i+6]==' ')
  131146. ){
  131147. break;
  131148. }
  131149. }
  131150. if( i<nType ){
  131151. int j;
  131152. int nDel = 6 + (zType[i+6] ? 1 : 0);
  131153. for(j=i; (j+nDel)<=nType; j++){
  131154. zType[j] = zType[j+nDel];
  131155. }
  131156. if( zType[i]=='\0' && i>0 ){
  131157. assert(zType[i-1]==' ');
  131158. zType[i-1] = '\0';
  131159. }
  131160. pTab->aCol[iCol].colFlags |= COLFLAG_HIDDEN;
  131161. oooHidden = TF_OOOHidden;
  131162. }else{
  131163. pTab->tabFlags |= oooHidden;
  131164. }
  131165. }
  131166. }
  131167. }
  131168. sqlite3DbFree(db, zModuleName);
  131169. return rc;
  131170. }
  131171. /*
  131172. ** This function is invoked by the parser to call the xConnect() method
  131173. ** of the virtual table pTab. If an error occurs, an error code is returned
  131174. ** and an error left in pParse.
  131175. **
  131176. ** This call is a no-op if table pTab is not a virtual table.
  131177. */
  131178. SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
  131179. sqlite3 *db = pParse->db;
  131180. const char *zMod;
  131181. Module *pMod;
  131182. int rc;
  131183. assert( pTab );
  131184. if( !IsVirtual(pTab) || sqlite3GetVTable(db, pTab) ){
  131185. return SQLITE_OK;
  131186. }
  131187. /* Locate the required virtual table module */
  131188. zMod = pTab->azModuleArg[0];
  131189. pMod = (Module*)sqlite3HashFind(&db->aModule, zMod);
  131190. if( !pMod ){
  131191. const char *zModule = pTab->azModuleArg[0];
  131192. sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
  131193. rc = SQLITE_ERROR;
  131194. }else{
  131195. char *zErr = 0;
  131196. rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
  131197. if( rc!=SQLITE_OK ){
  131198. sqlite3ErrorMsg(pParse, "%s", zErr);
  131199. pParse->rc = rc;
  131200. }
  131201. sqlite3DbFree(db, zErr);
  131202. }
  131203. return rc;
  131204. }
  131205. /*
  131206. ** Grow the db->aVTrans[] array so that there is room for at least one
  131207. ** more v-table. Return SQLITE_NOMEM if a malloc fails, or SQLITE_OK otherwise.
  131208. */
  131209. static int growVTrans(sqlite3 *db){
  131210. const int ARRAY_INCR = 5;
  131211. /* Grow the sqlite3.aVTrans array if required */
  131212. if( (db->nVTrans%ARRAY_INCR)==0 ){
  131213. VTable **aVTrans;
  131214. sqlite3_int64 nBytes = sizeof(sqlite3_vtab*)*
  131215. ((sqlite3_int64)db->nVTrans + ARRAY_INCR);
  131216. aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
  131217. if( !aVTrans ){
  131218. return SQLITE_NOMEM_BKPT;
  131219. }
  131220. memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
  131221. db->aVTrans = aVTrans;
  131222. }
  131223. return SQLITE_OK;
  131224. }
  131225. /*
  131226. ** Add the virtual table pVTab to the array sqlite3.aVTrans[]. Space should
  131227. ** have already been reserved using growVTrans().
  131228. */
  131229. static void addToVTrans(sqlite3 *db, VTable *pVTab){
  131230. /* Add pVtab to the end of sqlite3.aVTrans */
  131231. db->aVTrans[db->nVTrans++] = pVTab;
  131232. sqlite3VtabLock(pVTab);
  131233. }
  131234. /*
  131235. ** This function is invoked by the vdbe to call the xCreate method
  131236. ** of the virtual table named zTab in database iDb.
  131237. **
  131238. ** If an error occurs, *pzErr is set to point to an English language
  131239. ** description of the error and an SQLITE_XXX error code is returned.
  131240. ** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.
  131241. */
  131242. SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
  131243. int rc = SQLITE_OK;
  131244. Table *pTab;
  131245. Module *pMod;
  131246. const char *zMod;
  131247. pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zDbSName);
  131248. assert( pTab && IsVirtual(pTab) && !pTab->pVTable );
  131249. /* Locate the required virtual table module */
  131250. zMod = pTab->azModuleArg[0];
  131251. pMod = (Module*)sqlite3HashFind(&db->aModule, zMod);
  131252. /* If the module has been registered and includes a Create method,
  131253. ** invoke it now. If the module has not been registered, return an
  131254. ** error. Otherwise, do nothing.
  131255. */
  131256. if( pMod==0 || pMod->pModule->xCreate==0 || pMod->pModule->xDestroy==0 ){
  131257. *pzErr = sqlite3MPrintf(db, "no such module: %s", zMod);
  131258. rc = SQLITE_ERROR;
  131259. }else{
  131260. rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
  131261. }
  131262. /* Justification of ALWAYS(): The xConstructor method is required to
  131263. ** create a valid sqlite3_vtab if it returns SQLITE_OK. */
  131264. if( rc==SQLITE_OK && ALWAYS(sqlite3GetVTable(db, pTab)) ){
  131265. rc = growVTrans(db);
  131266. if( rc==SQLITE_OK ){
  131267. addToVTrans(db, sqlite3GetVTable(db, pTab));
  131268. }
  131269. }
  131270. return rc;
  131271. }
  131272. /*
  131273. ** This function is used to set the schema of a virtual table. It is only
  131274. ** valid to call this function from within the xCreate() or xConnect() of a
  131275. ** virtual table module.
  131276. */
  131277. SQLITE_API int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
  131278. VtabCtx *pCtx;
  131279. int rc = SQLITE_OK;
  131280. Table *pTab;
  131281. char *zErr = 0;
  131282. Parse sParse;
  131283. #ifdef SQLITE_ENABLE_API_ARMOR
  131284. if( !sqlite3SafetyCheckOk(db) || zCreateTable==0 ){
  131285. return SQLITE_MISUSE_BKPT;
  131286. }
  131287. #endif
  131288. sqlite3_mutex_enter(db->mutex);
  131289. pCtx = db->pVtabCtx;
  131290. if( !pCtx || pCtx->bDeclared ){
  131291. sqlite3Error(db, SQLITE_MISUSE);
  131292. sqlite3_mutex_leave(db->mutex);
  131293. return SQLITE_MISUSE_BKPT;
  131294. }
  131295. pTab = pCtx->pTab;
  131296. assert( IsVirtual(pTab) );
  131297. memset(&sParse, 0, sizeof(sParse));
  131298. sParse.eParseMode = PARSE_MODE_DECLARE_VTAB;
  131299. sParse.db = db;
  131300. sParse.nQueryLoop = 1;
  131301. if( SQLITE_OK==sqlite3RunParser(&sParse, zCreateTable, &zErr)
  131302. && sParse.pNewTable
  131303. && !db->mallocFailed
  131304. && !sParse.pNewTable->pSelect
  131305. && !IsVirtual(sParse.pNewTable)
  131306. ){
  131307. if( !pTab->aCol ){
  131308. Table *pNew = sParse.pNewTable;
  131309. Index *pIdx;
  131310. pTab->aCol = pNew->aCol;
  131311. pTab->nCol = pNew->nCol;
  131312. pTab->tabFlags |= pNew->tabFlags & (TF_WithoutRowid|TF_NoVisibleRowid);
  131313. pNew->nCol = 0;
  131314. pNew->aCol = 0;
  131315. assert( pTab->pIndex==0 );
  131316. assert( HasRowid(pNew) || sqlite3PrimaryKeyIndex(pNew)!=0 );
  131317. if( !HasRowid(pNew)
  131318. && pCtx->pVTable->pMod->pModule->xUpdate!=0
  131319. && sqlite3PrimaryKeyIndex(pNew)->nKeyCol!=1
  131320. ){
  131321. /* WITHOUT ROWID virtual tables must either be read-only (xUpdate==0)
  131322. ** or else must have a single-column PRIMARY KEY */
  131323. rc = SQLITE_ERROR;
  131324. }
  131325. pIdx = pNew->pIndex;
  131326. if( pIdx ){
  131327. assert( pIdx->pNext==0 );
  131328. pTab->pIndex = pIdx;
  131329. pNew->pIndex = 0;
  131330. pIdx->pTable = pTab;
  131331. }
  131332. }
  131333. pCtx->bDeclared = 1;
  131334. }else{
  131335. sqlite3ErrorWithMsg(db, SQLITE_ERROR, (zErr ? "%s" : 0), zErr);
  131336. sqlite3DbFree(db, zErr);
  131337. rc = SQLITE_ERROR;
  131338. }
  131339. sParse.eParseMode = PARSE_MODE_NORMAL;
  131340. if( sParse.pVdbe ){
  131341. sqlite3VdbeFinalize(sParse.pVdbe);
  131342. }
  131343. sqlite3DeleteTable(db, sParse.pNewTable);
  131344. sqlite3ParserReset(&sParse);
  131345. assert( (rc&0xff)==rc );
  131346. rc = sqlite3ApiExit(db, rc);
  131347. sqlite3_mutex_leave(db->mutex);
  131348. return rc;
  131349. }
  131350. /*
  131351. ** This function is invoked by the vdbe to call the xDestroy method
  131352. ** of the virtual table named zTab in database iDb. This occurs
  131353. ** when a DROP TABLE is mentioned.
  131354. **
  131355. ** This call is a no-op if zTab is not a virtual table.
  131356. */
  131357. SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab){
  131358. int rc = SQLITE_OK;
  131359. Table *pTab;
  131360. pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zDbSName);
  131361. if( pTab!=0 && ALWAYS(pTab->pVTable!=0) ){
  131362. VTable *p;
  131363. int (*xDestroy)(sqlite3_vtab *);
  131364. for(p=pTab->pVTable; p; p=p->pNext){
  131365. assert( p->pVtab );
  131366. if( p->pVtab->nRef>0 ){
  131367. return SQLITE_LOCKED;
  131368. }
  131369. }
  131370. p = vtabDisconnectAll(db, pTab);
  131371. xDestroy = p->pMod->pModule->xDestroy;
  131372. if( xDestroy==0 ) xDestroy = p->pMod->pModule->xDisconnect;
  131373. assert( xDestroy!=0 );
  131374. pTab->nTabRef++;
  131375. rc = xDestroy(p->pVtab);
  131376. /* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */
  131377. if( rc==SQLITE_OK ){
  131378. assert( pTab->pVTable==p && p->pNext==0 );
  131379. p->pVtab = 0;
  131380. pTab->pVTable = 0;
  131381. sqlite3VtabUnlock(p);
  131382. }
  131383. sqlite3DeleteTable(db, pTab);
  131384. }
  131385. return rc;
  131386. }
  131387. /*
  131388. ** This function invokes either the xRollback or xCommit method
  131389. ** of each of the virtual tables in the sqlite3.aVTrans array. The method
  131390. ** called is identified by the second argument, "offset", which is
  131391. ** the offset of the method to call in the sqlite3_module structure.
  131392. **
  131393. ** The array is cleared after invoking the callbacks.
  131394. */
  131395. static void callFinaliser(sqlite3 *db, int offset){
  131396. int i;
  131397. if( db->aVTrans ){
  131398. VTable **aVTrans = db->aVTrans;
  131399. db->aVTrans = 0;
  131400. for(i=0; i<db->nVTrans; i++){
  131401. VTable *pVTab = aVTrans[i];
  131402. sqlite3_vtab *p = pVTab->pVtab;
  131403. if( p ){
  131404. int (*x)(sqlite3_vtab *);
  131405. x = *(int (**)(sqlite3_vtab *))((char *)p->pModule + offset);
  131406. if( x ) x(p);
  131407. }
  131408. pVTab->iSavepoint = 0;
  131409. sqlite3VtabUnlock(pVTab);
  131410. }
  131411. sqlite3DbFree(db, aVTrans);
  131412. db->nVTrans = 0;
  131413. }
  131414. }
  131415. /*
  131416. ** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans
  131417. ** array. Return the error code for the first error that occurs, or
  131418. ** SQLITE_OK if all xSync operations are successful.
  131419. **
  131420. ** If an error message is available, leave it in p->zErrMsg.
  131421. */
  131422. SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, Vdbe *p){
  131423. int i;
  131424. int rc = SQLITE_OK;
  131425. VTable **aVTrans = db->aVTrans;
  131426. db->aVTrans = 0;
  131427. for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
  131428. int (*x)(sqlite3_vtab *);
  131429. sqlite3_vtab *pVtab = aVTrans[i]->pVtab;
  131430. if( pVtab && (x = pVtab->pModule->xSync)!=0 ){
  131431. rc = x(pVtab);
  131432. sqlite3VtabImportErrmsg(p, pVtab);
  131433. }
  131434. }
  131435. db->aVTrans = aVTrans;
  131436. return rc;
  131437. }
  131438. /*
  131439. ** Invoke the xRollback method of all virtual tables in the
  131440. ** sqlite3.aVTrans array. Then clear the array itself.
  131441. */
  131442. SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){
  131443. callFinaliser(db, offsetof(sqlite3_module,xRollback));
  131444. return SQLITE_OK;
  131445. }
  131446. /*
  131447. ** Invoke the xCommit method of all virtual tables in the
  131448. ** sqlite3.aVTrans array. Then clear the array itself.
  131449. */
  131450. SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){
  131451. callFinaliser(db, offsetof(sqlite3_module,xCommit));
  131452. return SQLITE_OK;
  131453. }
  131454. /*
  131455. ** If the virtual table pVtab supports the transaction interface
  131456. ** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
  131457. ** not currently open, invoke the xBegin method now.
  131458. **
  131459. ** If the xBegin call is successful, place the sqlite3_vtab pointer
  131460. ** in the sqlite3.aVTrans array.
  131461. */
  131462. SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){
  131463. int rc = SQLITE_OK;
  131464. const sqlite3_module *pModule;
  131465. /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
  131466. ** than zero, then this function is being called from within a
  131467. ** virtual module xSync() callback. It is illegal to write to
  131468. ** virtual module tables in this case, so return SQLITE_LOCKED.
  131469. */
  131470. if( sqlite3VtabInSync(db) ){
  131471. return SQLITE_LOCKED;
  131472. }
  131473. if( !pVTab ){
  131474. return SQLITE_OK;
  131475. }
  131476. pModule = pVTab->pVtab->pModule;
  131477. if( pModule->xBegin ){
  131478. int i;
  131479. /* If pVtab is already in the aVTrans array, return early */
  131480. for(i=0; i<db->nVTrans; i++){
  131481. if( db->aVTrans[i]==pVTab ){
  131482. return SQLITE_OK;
  131483. }
  131484. }
  131485. /* Invoke the xBegin method. If successful, add the vtab to the
  131486. ** sqlite3.aVTrans[] array. */
  131487. rc = growVTrans(db);
  131488. if( rc==SQLITE_OK ){
  131489. rc = pModule->xBegin(pVTab->pVtab);
  131490. if( rc==SQLITE_OK ){
  131491. int iSvpt = db->nStatement + db->nSavepoint;
  131492. addToVTrans(db, pVTab);
  131493. if( iSvpt && pModule->xSavepoint ){
  131494. pVTab->iSavepoint = iSvpt;
  131495. rc = pModule->xSavepoint(pVTab->pVtab, iSvpt-1);
  131496. }
  131497. }
  131498. }
  131499. }
  131500. return rc;
  131501. }
  131502. /*
  131503. ** Invoke either the xSavepoint, xRollbackTo or xRelease method of all
  131504. ** virtual tables that currently have an open transaction. Pass iSavepoint
  131505. ** as the second argument to the virtual table method invoked.
  131506. **
  131507. ** If op is SAVEPOINT_BEGIN, the xSavepoint method is invoked. If it is
  131508. ** SAVEPOINT_ROLLBACK, the xRollbackTo method. Otherwise, if op is
  131509. ** SAVEPOINT_RELEASE, then the xRelease method of each virtual table with
  131510. ** an open transaction is invoked.
  131511. **
  131512. ** If any virtual table method returns an error code other than SQLITE_OK,
  131513. ** processing is abandoned and the error returned to the caller of this
  131514. ** function immediately. If all calls to virtual table methods are successful,
  131515. ** SQLITE_OK is returned.
  131516. */
  131517. SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *db, int op, int iSavepoint){
  131518. int rc = SQLITE_OK;
  131519. assert( op==SAVEPOINT_RELEASE||op==SAVEPOINT_ROLLBACK||op==SAVEPOINT_BEGIN );
  131520. assert( iSavepoint>=-1 );
  131521. if( db->aVTrans ){
  131522. int i;
  131523. for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
  131524. VTable *pVTab = db->aVTrans[i];
  131525. const sqlite3_module *pMod = pVTab->pMod->pModule;
  131526. if( pVTab->pVtab && pMod->iVersion>=2 ){
  131527. int (*xMethod)(sqlite3_vtab *, int);
  131528. sqlite3VtabLock(pVTab);
  131529. switch( op ){
  131530. case SAVEPOINT_BEGIN:
  131531. xMethod = pMod->xSavepoint;
  131532. pVTab->iSavepoint = iSavepoint+1;
  131533. break;
  131534. case SAVEPOINT_ROLLBACK:
  131535. xMethod = pMod->xRollbackTo;
  131536. break;
  131537. default:
  131538. xMethod = pMod->xRelease;
  131539. break;
  131540. }
  131541. if( xMethod && pVTab->iSavepoint>iSavepoint ){
  131542. rc = xMethod(pVTab->pVtab, iSavepoint);
  131543. }
  131544. sqlite3VtabUnlock(pVTab);
  131545. }
  131546. }
  131547. }
  131548. return rc;
  131549. }
  131550. /*
  131551. ** The first parameter (pDef) is a function implementation. The
  131552. ** second parameter (pExpr) is the first argument to this function.
  131553. ** If pExpr is a column in a virtual table, then let the virtual
  131554. ** table implementation have an opportunity to overload the function.
  131555. **
  131556. ** This routine is used to allow virtual table implementations to
  131557. ** overload MATCH, LIKE, GLOB, and REGEXP operators.
  131558. **
  131559. ** Return either the pDef argument (indicating no change) or a
  131560. ** new FuncDef structure that is marked as ephemeral using the
  131561. ** SQLITE_FUNC_EPHEM flag.
  131562. */
  131563. SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(
  131564. sqlite3 *db, /* Database connection for reporting malloc problems */
  131565. FuncDef *pDef, /* Function to possibly overload */
  131566. int nArg, /* Number of arguments to the function */
  131567. Expr *pExpr /* First argument to the function */
  131568. ){
  131569. Table *pTab;
  131570. sqlite3_vtab *pVtab;
  131571. sqlite3_module *pMod;
  131572. void (*xSFunc)(sqlite3_context*,int,sqlite3_value**) = 0;
  131573. void *pArg = 0;
  131574. FuncDef *pNew;
  131575. int rc = 0;
  131576. /* Check to see the left operand is a column in a virtual table */
  131577. if( NEVER(pExpr==0) ) return pDef;
  131578. if( pExpr->op!=TK_COLUMN ) return pDef;
  131579. pTab = pExpr->y.pTab;
  131580. if( pTab==0 ) return pDef;
  131581. if( !IsVirtual(pTab) ) return pDef;
  131582. pVtab = sqlite3GetVTable(db, pTab)->pVtab;
  131583. assert( pVtab!=0 );
  131584. assert( pVtab->pModule!=0 );
  131585. pMod = (sqlite3_module *)pVtab->pModule;
  131586. if( pMod->xFindFunction==0 ) return pDef;
  131587. /* Call the xFindFunction method on the virtual table implementation
  131588. ** to see if the implementation wants to overload this function.
  131589. **
  131590. ** Though undocumented, we have historically always invoked xFindFunction
  131591. ** with an all lower-case function name. Continue in this tradition to
  131592. ** avoid any chance of an incompatibility.
  131593. */
  131594. #ifdef SQLITE_DEBUG
  131595. {
  131596. int i;
  131597. for(i=0; pDef->zName[i]; i++){
  131598. unsigned char x = (unsigned char)pDef->zName[i];
  131599. assert( x==sqlite3UpperToLower[x] );
  131600. }
  131601. }
  131602. #endif
  131603. rc = pMod->xFindFunction(pVtab, nArg, pDef->zName, &xSFunc, &pArg);
  131604. if( rc==0 ){
  131605. return pDef;
  131606. }
  131607. /* Create a new ephemeral function definition for the overloaded
  131608. ** function */
  131609. pNew = sqlite3DbMallocZero(db, sizeof(*pNew)
  131610. + sqlite3Strlen30(pDef->zName) + 1);
  131611. if( pNew==0 ){
  131612. return pDef;
  131613. }
  131614. *pNew = *pDef;
  131615. pNew->zName = (const char*)&pNew[1];
  131616. memcpy((char*)&pNew[1], pDef->zName, sqlite3Strlen30(pDef->zName)+1);
  131617. pNew->xSFunc = xSFunc;
  131618. pNew->pUserData = pArg;
  131619. pNew->funcFlags |= SQLITE_FUNC_EPHEM;
  131620. return pNew;
  131621. }
  131622. /*
  131623. ** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
  131624. ** array so that an OP_VBegin will get generated for it. Add pTab to the
  131625. ** array if it is missing. If pTab is already in the array, this routine
  131626. ** is a no-op.
  131627. */
  131628. SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){
  131629. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  131630. int i, n;
  131631. Table **apVtabLock;
  131632. assert( IsVirtual(pTab) );
  131633. for(i=0; i<pToplevel->nVtabLock; i++){
  131634. if( pTab==pToplevel->apVtabLock[i] ) return;
  131635. }
  131636. n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]);
  131637. apVtabLock = sqlite3Realloc(pToplevel->apVtabLock, n);
  131638. if( apVtabLock ){
  131639. pToplevel->apVtabLock = apVtabLock;
  131640. pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab;
  131641. }else{
  131642. sqlite3OomFault(pToplevel->db);
  131643. }
  131644. }
  131645. /*
  131646. ** Check to see if virtual table module pMod can be have an eponymous
  131647. ** virtual table instance. If it can, create one if one does not already
  131648. ** exist. Return non-zero if the eponymous virtual table instance exists
  131649. ** when this routine returns, and return zero if it does not exist.
  131650. **
  131651. ** An eponymous virtual table instance is one that is named after its
  131652. ** module, and more importantly, does not require a CREATE VIRTUAL TABLE
  131653. ** statement in order to come into existance. Eponymous virtual table
  131654. ** instances always exist. They cannot be DROP-ed.
  131655. **
  131656. ** Any virtual table module for which xConnect and xCreate are the same
  131657. ** method can have an eponymous virtual table instance.
  131658. */
  131659. SQLITE_PRIVATE int sqlite3VtabEponymousTableInit(Parse *pParse, Module *pMod){
  131660. const sqlite3_module *pModule = pMod->pModule;
  131661. Table *pTab;
  131662. char *zErr = 0;
  131663. int rc;
  131664. sqlite3 *db = pParse->db;
  131665. if( pMod->pEpoTab ) return 1;
  131666. if( pModule->xCreate!=0 && pModule->xCreate!=pModule->xConnect ) return 0;
  131667. pTab = sqlite3DbMallocZero(db, sizeof(Table));
  131668. if( pTab==0 ) return 0;
  131669. pTab->zName = sqlite3DbStrDup(db, pMod->zName);
  131670. if( pTab->zName==0 ){
  131671. sqlite3DbFree(db, pTab);
  131672. return 0;
  131673. }
  131674. pMod->pEpoTab = pTab;
  131675. pTab->nTabRef = 1;
  131676. pTab->pSchema = db->aDb[0].pSchema;
  131677. assert( pTab->nModuleArg==0 );
  131678. pTab->iPKey = -1;
  131679. addModuleArgument(pParse, pTab, sqlite3DbStrDup(db, pTab->zName));
  131680. addModuleArgument(pParse, pTab, 0);
  131681. addModuleArgument(pParse, pTab, sqlite3DbStrDup(db, pTab->zName));
  131682. rc = vtabCallConstructor(db, pTab, pMod, pModule->xConnect, &zErr);
  131683. if( rc ){
  131684. sqlite3ErrorMsg(pParse, "%s", zErr);
  131685. sqlite3DbFree(db, zErr);
  131686. sqlite3VtabEponymousTableClear(db, pMod);
  131687. return 0;
  131688. }
  131689. return 1;
  131690. }
  131691. /*
  131692. ** Erase the eponymous virtual table instance associated with
  131693. ** virtual table module pMod, if it exists.
  131694. */
  131695. SQLITE_PRIVATE void sqlite3VtabEponymousTableClear(sqlite3 *db, Module *pMod){
  131696. Table *pTab = pMod->pEpoTab;
  131697. if( pTab!=0 ){
  131698. /* Mark the table as Ephemeral prior to deleting it, so that the
  131699. ** sqlite3DeleteTable() routine will know that it is not stored in
  131700. ** the schema. */
  131701. pTab->tabFlags |= TF_Ephemeral;
  131702. sqlite3DeleteTable(db, pTab);
  131703. pMod->pEpoTab = 0;
  131704. }
  131705. }
  131706. /*
  131707. ** Return the ON CONFLICT resolution mode in effect for the virtual
  131708. ** table update operation currently in progress.
  131709. **
  131710. ** The results of this routine are undefined unless it is called from
  131711. ** within an xUpdate method.
  131712. */
  131713. SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *db){
  131714. static const unsigned char aMap[] = {
  131715. SQLITE_ROLLBACK, SQLITE_ABORT, SQLITE_FAIL, SQLITE_IGNORE, SQLITE_REPLACE
  131716. };
  131717. #ifdef SQLITE_ENABLE_API_ARMOR
  131718. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  131719. #endif
  131720. assert( OE_Rollback==1 && OE_Abort==2 && OE_Fail==3 );
  131721. assert( OE_Ignore==4 && OE_Replace==5 );
  131722. assert( db->vtabOnConflict>=1 && db->vtabOnConflict<=5 );
  131723. return (int)aMap[db->vtabOnConflict-1];
  131724. }
  131725. /*
  131726. ** Call from within the xCreate() or xConnect() methods to provide
  131727. ** the SQLite core with additional information about the behavior
  131728. ** of the virtual table being implemented.
  131729. */
  131730. SQLITE_API int sqlite3_vtab_config(sqlite3 *db, int op, ...){
  131731. va_list ap;
  131732. int rc = SQLITE_OK;
  131733. VtabCtx *p;
  131734. #ifdef SQLITE_ENABLE_API_ARMOR
  131735. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  131736. #endif
  131737. sqlite3_mutex_enter(db->mutex);
  131738. p = db->pVtabCtx;
  131739. if( !p ){
  131740. rc = SQLITE_MISUSE_BKPT;
  131741. }else{
  131742. assert( p->pTab==0 || IsVirtual(p->pTab) );
  131743. va_start(ap, op);
  131744. switch( op ){
  131745. case SQLITE_VTAB_CONSTRAINT_SUPPORT: {
  131746. p->pVTable->bConstraint = (u8)va_arg(ap, int);
  131747. break;
  131748. }
  131749. case SQLITE_VTAB_INNOCUOUS: {
  131750. p->pVTable->eVtabRisk = SQLITE_VTABRISK_Low;
  131751. break;
  131752. }
  131753. case SQLITE_VTAB_DIRECTONLY: {
  131754. p->pVTable->eVtabRisk = SQLITE_VTABRISK_High;
  131755. break;
  131756. }
  131757. default: {
  131758. rc = SQLITE_MISUSE_BKPT;
  131759. break;
  131760. }
  131761. }
  131762. va_end(ap);
  131763. }
  131764. if( rc!=SQLITE_OK ) sqlite3Error(db, rc);
  131765. sqlite3_mutex_leave(db->mutex);
  131766. return rc;
  131767. }
  131768. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  131769. /************** End of vtab.c ************************************************/
  131770. /************** Begin file wherecode.c ***************************************/
  131771. /*
  131772. ** 2015-06-06
  131773. **
  131774. ** The author disclaims copyright to this source code. In place of
  131775. ** a legal notice, here is a blessing:
  131776. **
  131777. ** May you do good and not evil.
  131778. ** May you find forgiveness for yourself and forgive others.
  131779. ** May you share freely, never taking more than you give.
  131780. **
  131781. *************************************************************************
  131782. ** This module contains C code that generates VDBE code used to process
  131783. ** the WHERE clause of SQL statements.
  131784. **
  131785. ** This file was split off from where.c on 2015-06-06 in order to reduce the
  131786. ** size of where.c and make it easier to edit. This file contains the routines
  131787. ** that actually generate the bulk of the WHERE loop code. The original where.c
  131788. ** file retains the code that does query planning and analysis.
  131789. */
  131790. /* #include "sqliteInt.h" */
  131791. /************** Include whereInt.h in the middle of wherecode.c **************/
  131792. /************** Begin file whereInt.h ****************************************/
  131793. /*
  131794. ** 2013-11-12
  131795. **
  131796. ** The author disclaims copyright to this source code. In place of
  131797. ** a legal notice, here is a blessing:
  131798. **
  131799. ** May you do good and not evil.
  131800. ** May you find forgiveness for yourself and forgive others.
  131801. ** May you share freely, never taking more than you give.
  131802. **
  131803. *************************************************************************
  131804. **
  131805. ** This file contains structure and macro definitions for the query
  131806. ** planner logic in "where.c". These definitions are broken out into
  131807. ** a separate source file for easier editing.
  131808. */
  131809. #ifndef SQLITE_WHEREINT_H
  131810. #define SQLITE_WHEREINT_H
  131811. /*
  131812. ** Trace output macros
  131813. */
  131814. #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
  131815. /***/ extern int sqlite3WhereTrace;
  131816. #endif
  131817. #if defined(SQLITE_DEBUG) \
  131818. && (defined(SQLITE_TEST) || defined(SQLITE_ENABLE_WHERETRACE))
  131819. # define WHERETRACE(K,X) if(sqlite3WhereTrace&(K)) sqlite3DebugPrintf X
  131820. # define WHERETRACE_ENABLED 1
  131821. #else
  131822. # define WHERETRACE(K,X)
  131823. #endif
  131824. /* Forward references
  131825. */
  131826. typedef struct WhereClause WhereClause;
  131827. typedef struct WhereMaskSet WhereMaskSet;
  131828. typedef struct WhereOrInfo WhereOrInfo;
  131829. typedef struct WhereAndInfo WhereAndInfo;
  131830. typedef struct WhereLevel WhereLevel;
  131831. typedef struct WhereLoop WhereLoop;
  131832. typedef struct WherePath WherePath;
  131833. typedef struct WhereTerm WhereTerm;
  131834. typedef struct WhereLoopBuilder WhereLoopBuilder;
  131835. typedef struct WhereScan WhereScan;
  131836. typedef struct WhereOrCost WhereOrCost;
  131837. typedef struct WhereOrSet WhereOrSet;
  131838. /*
  131839. ** This object contains information needed to implement a single nested
  131840. ** loop in WHERE clause.
  131841. **
  131842. ** Contrast this object with WhereLoop. This object describes the
  131843. ** implementation of the loop. WhereLoop describes the algorithm.
  131844. ** This object contains a pointer to the WhereLoop algorithm as one of
  131845. ** its elements.
  131846. **
  131847. ** The WhereInfo object contains a single instance of this object for
  131848. ** each term in the FROM clause (which is to say, for each of the
  131849. ** nested loops as implemented). The order of WhereLevel objects determines
  131850. ** the loop nested order, with WhereInfo.a[0] being the outer loop and
  131851. ** WhereInfo.a[WhereInfo.nLevel-1] being the inner loop.
  131852. */
  131853. struct WhereLevel {
  131854. int iLeftJoin; /* Memory cell used to implement LEFT OUTER JOIN */
  131855. int iTabCur; /* The VDBE cursor used to access the table */
  131856. int iIdxCur; /* The VDBE cursor used to access pIdx */
  131857. int addrBrk; /* Jump here to break out of the loop */
  131858. int addrNxt; /* Jump here to start the next IN combination */
  131859. int addrSkip; /* Jump here for next iteration of skip-scan */
  131860. int addrCont; /* Jump here to continue with the next loop cycle */
  131861. int addrFirst; /* First instruction of interior of the loop */
  131862. int addrBody; /* Beginning of the body of this loop */
  131863. int regBignull; /* big-null flag reg. True if a NULL-scan is needed */
  131864. int addrBignull; /* Jump here for next part of big-null scan */
  131865. #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
  131866. u32 iLikeRepCntr; /* LIKE range processing counter register (times 2) */
  131867. int addrLikeRep; /* LIKE range processing address */
  131868. #endif
  131869. u8 iFrom; /* Which entry in the FROM clause */
  131870. u8 op, p3, p5; /* Opcode, P3 & P5 of the opcode that ends the loop */
  131871. int p1, p2; /* Operands of the opcode used to end the loop */
  131872. union { /* Information that depends on pWLoop->wsFlags */
  131873. struct {
  131874. int nIn; /* Number of entries in aInLoop[] */
  131875. struct InLoop {
  131876. int iCur; /* The VDBE cursor used by this IN operator */
  131877. int addrInTop; /* Top of the IN loop */
  131878. int iBase; /* Base register of multi-key index record */
  131879. int nPrefix; /* Number of prior entires in the key */
  131880. u8 eEndLoopOp; /* IN Loop terminator. OP_Next or OP_Prev */
  131881. } *aInLoop; /* Information about each nested IN operator */
  131882. } in; /* Used when pWLoop->wsFlags&WHERE_IN_ABLE */
  131883. Index *pCovidx; /* Possible covering index for WHERE_MULTI_OR */
  131884. } u;
  131885. struct WhereLoop *pWLoop; /* The selected WhereLoop object */
  131886. Bitmask notReady; /* FROM entries not usable at this level */
  131887. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  131888. int addrVisit; /* Address at which row is visited */
  131889. #endif
  131890. };
  131891. /*
  131892. ** Each instance of this object represents an algorithm for evaluating one
  131893. ** term of a join. Every term of the FROM clause will have at least
  131894. ** one corresponding WhereLoop object (unless INDEXED BY constraints
  131895. ** prevent a query solution - which is an error) and many terms of the
  131896. ** FROM clause will have multiple WhereLoop objects, each describing a
  131897. ** potential way of implementing that FROM-clause term, together with
  131898. ** dependencies and cost estimates for using the chosen algorithm.
  131899. **
  131900. ** Query planning consists of building up a collection of these WhereLoop
  131901. ** objects, then computing a particular sequence of WhereLoop objects, with
  131902. ** one WhereLoop object per FROM clause term, that satisfy all dependencies
  131903. ** and that minimize the overall cost.
  131904. */
  131905. struct WhereLoop {
  131906. Bitmask prereq; /* Bitmask of other loops that must run first */
  131907. Bitmask maskSelf; /* Bitmask identifying table iTab */
  131908. #ifdef SQLITE_DEBUG
  131909. char cId; /* Symbolic ID of this loop for debugging use */
  131910. #endif
  131911. u8 iTab; /* Position in FROM clause of table for this loop */
  131912. u8 iSortIdx; /* Sorting index number. 0==None */
  131913. LogEst rSetup; /* One-time setup cost (ex: create transient index) */
  131914. LogEst rRun; /* Cost of running each loop */
  131915. LogEst nOut; /* Estimated number of output rows */
  131916. union {
  131917. struct { /* Information for internal btree tables */
  131918. u16 nEq; /* Number of equality constraints */
  131919. u16 nBtm; /* Size of BTM vector */
  131920. u16 nTop; /* Size of TOP vector */
  131921. u16 nDistinctCol; /* Index columns used to sort for DISTINCT */
  131922. Index *pIndex; /* Index used, or NULL */
  131923. } btree;
  131924. struct { /* Information for virtual tables */
  131925. int idxNum; /* Index number */
  131926. u8 needFree; /* True if sqlite3_free(idxStr) is needed */
  131927. i8 isOrdered; /* True if satisfies ORDER BY */
  131928. u16 omitMask; /* Terms that may be omitted */
  131929. char *idxStr; /* Index identifier string */
  131930. } vtab;
  131931. } u;
  131932. u32 wsFlags; /* WHERE_* flags describing the plan */
  131933. u16 nLTerm; /* Number of entries in aLTerm[] */
  131934. u16 nSkip; /* Number of NULL aLTerm[] entries */
  131935. /**** whereLoopXfer() copies fields above ***********************/
  131936. # define WHERE_LOOP_XFER_SZ offsetof(WhereLoop,nLSlot)
  131937. u16 nLSlot; /* Number of slots allocated for aLTerm[] */
  131938. WhereTerm **aLTerm; /* WhereTerms used */
  131939. WhereLoop *pNextLoop; /* Next WhereLoop object in the WhereClause */
  131940. WhereTerm *aLTermSpace[3]; /* Initial aLTerm[] space */
  131941. };
  131942. /* This object holds the prerequisites and the cost of running a
  131943. ** subquery on one operand of an OR operator in the WHERE clause.
  131944. ** See WhereOrSet for additional information
  131945. */
  131946. struct WhereOrCost {
  131947. Bitmask prereq; /* Prerequisites */
  131948. LogEst rRun; /* Cost of running this subquery */
  131949. LogEst nOut; /* Number of outputs for this subquery */
  131950. };
  131951. /* The WhereOrSet object holds a set of possible WhereOrCosts that
  131952. ** correspond to the subquery(s) of OR-clause processing. Only the
  131953. ** best N_OR_COST elements are retained.
  131954. */
  131955. #define N_OR_COST 3
  131956. struct WhereOrSet {
  131957. u16 n; /* Number of valid a[] entries */
  131958. WhereOrCost a[N_OR_COST]; /* Set of best costs */
  131959. };
  131960. /*
  131961. ** Each instance of this object holds a sequence of WhereLoop objects
  131962. ** that implement some or all of a query plan.
  131963. **
  131964. ** Think of each WhereLoop object as a node in a graph with arcs
  131965. ** showing dependencies and costs for travelling between nodes. (That is
  131966. ** not a completely accurate description because WhereLoop costs are a
  131967. ** vector, not a scalar, and because dependencies are many-to-one, not
  131968. ** one-to-one as are graph nodes. But it is a useful visualization aid.)
  131969. ** Then a WherePath object is a path through the graph that visits some
  131970. ** or all of the WhereLoop objects once.
  131971. **
  131972. ** The "solver" works by creating the N best WherePath objects of length
  131973. ** 1. Then using those as a basis to compute the N best WherePath objects
  131974. ** of length 2. And so forth until the length of WherePaths equals the
  131975. ** number of nodes in the FROM clause. The best (lowest cost) WherePath
  131976. ** at the end is the chosen query plan.
  131977. */
  131978. struct WherePath {
  131979. Bitmask maskLoop; /* Bitmask of all WhereLoop objects in this path */
  131980. Bitmask revLoop; /* aLoop[]s that should be reversed for ORDER BY */
  131981. LogEst nRow; /* Estimated number of rows generated by this path */
  131982. LogEst rCost; /* Total cost of this path */
  131983. LogEst rUnsorted; /* Total cost of this path ignoring sorting costs */
  131984. i8 isOrdered; /* No. of ORDER BY terms satisfied. -1 for unknown */
  131985. WhereLoop **aLoop; /* Array of WhereLoop objects implementing this path */
  131986. };
  131987. /*
  131988. ** The query generator uses an array of instances of this structure to
  131989. ** help it analyze the subexpressions of the WHERE clause. Each WHERE
  131990. ** clause subexpression is separated from the others by AND operators,
  131991. ** usually, or sometimes subexpressions separated by OR.
  131992. **
  131993. ** All WhereTerms are collected into a single WhereClause structure.
  131994. ** The following identity holds:
  131995. **
  131996. ** WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
  131997. **
  131998. ** When a term is of the form:
  131999. **
  132000. ** X <op> <expr>
  132001. **
  132002. ** where X is a column name and <op> is one of certain operators,
  132003. ** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
  132004. ** cursor number and column number for X. WhereTerm.eOperator records
  132005. ** the <op> using a bitmask encoding defined by WO_xxx below. The
  132006. ** use of a bitmask encoding for the operator allows us to search
  132007. ** quickly for terms that match any of several different operators.
  132008. **
  132009. ** A WhereTerm might also be two or more subterms connected by OR:
  132010. **
  132011. ** (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
  132012. **
  132013. ** In this second case, wtFlag has the TERM_ORINFO bit set and eOperator==WO_OR
  132014. ** and the WhereTerm.u.pOrInfo field points to auxiliary information that
  132015. ** is collected about the OR clause.
  132016. **
  132017. ** If a term in the WHERE clause does not match either of the two previous
  132018. ** categories, then eOperator==0. The WhereTerm.pExpr field is still set
  132019. ** to the original subexpression content and wtFlags is set up appropriately
  132020. ** but no other fields in the WhereTerm object are meaningful.
  132021. **
  132022. ** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
  132023. ** but they do so indirectly. A single WhereMaskSet structure translates
  132024. ** cursor number into bits and the translated bit is stored in the prereq
  132025. ** fields. The translation is used in order to maximize the number of
  132026. ** bits that will fit in a Bitmask. The VDBE cursor numbers might be
  132027. ** spread out over the non-negative integers. For example, the cursor
  132028. ** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45. The WhereMaskSet
  132029. ** translates these sparse cursor numbers into consecutive integers
  132030. ** beginning with 0 in order to make the best possible use of the available
  132031. ** bits in the Bitmask. So, in the example above, the cursor numbers
  132032. ** would be mapped into integers 0 through 7.
  132033. **
  132034. ** The number of terms in a join is limited by the number of bits
  132035. ** in prereqRight and prereqAll. The default is 64 bits, hence SQLite
  132036. ** is only able to process joins with 64 or fewer tables.
  132037. */
  132038. struct WhereTerm {
  132039. Expr *pExpr; /* Pointer to the subexpression that is this term */
  132040. WhereClause *pWC; /* The clause this term is part of */
  132041. LogEst truthProb; /* Probability of truth for this expression */
  132042. u16 wtFlags; /* TERM_xxx bit flags. See below */
  132043. u16 eOperator; /* A WO_xx value describing <op> */
  132044. u8 nChild; /* Number of children that must disable us */
  132045. u8 eMatchOp; /* Op for vtab MATCH/LIKE/GLOB/REGEXP terms */
  132046. int iParent; /* Disable pWC->a[iParent] when this term disabled */
  132047. int leftCursor; /* Cursor number of X in "X <op> <expr>" */
  132048. int iField; /* Field in (?,?,?) IN (SELECT...) vector */
  132049. union {
  132050. int leftColumn; /* Column number of X in "X <op> <expr>" */
  132051. WhereOrInfo *pOrInfo; /* Extra information if (eOperator & WO_OR)!=0 */
  132052. WhereAndInfo *pAndInfo; /* Extra information if (eOperator& WO_AND)!=0 */
  132053. } u;
  132054. Bitmask prereqRight; /* Bitmask of tables used by pExpr->pRight */
  132055. Bitmask prereqAll; /* Bitmask of tables referenced by pExpr */
  132056. };
  132057. /*
  132058. ** Allowed values of WhereTerm.wtFlags
  132059. */
  132060. #define TERM_DYNAMIC 0x0001 /* Need to call sqlite3ExprDelete(db, pExpr) */
  132061. #define TERM_VIRTUAL 0x0002 /* Added by the optimizer. Do not code */
  132062. #define TERM_CODED 0x0004 /* This term is already coded */
  132063. #define TERM_COPIED 0x0008 /* Has a child */
  132064. #define TERM_ORINFO 0x0010 /* Need to free the WhereTerm.u.pOrInfo object */
  132065. #define TERM_ANDINFO 0x0020 /* Need to free the WhereTerm.u.pAndInfo obj */
  132066. #define TERM_OR_OK 0x0040 /* Used during OR-clause processing */
  132067. #ifdef SQLITE_ENABLE_STAT4
  132068. # define TERM_VNULL 0x0080 /* Manufactured x>NULL or x<=NULL term */
  132069. #else
  132070. # define TERM_VNULL 0x0000 /* Disabled if not using stat4 */
  132071. #endif
  132072. #define TERM_LIKEOPT 0x0100 /* Virtual terms from the LIKE optimization */
  132073. #define TERM_LIKECOND 0x0200 /* Conditionally this LIKE operator term */
  132074. #define TERM_LIKE 0x0400 /* The original LIKE operator */
  132075. #define TERM_IS 0x0800 /* Term.pExpr is an IS operator */
  132076. #define TERM_VARSELECT 0x1000 /* Term.pExpr contains a correlated sub-query */
  132077. #define TERM_HEURTRUTH 0x2000 /* Heuristic truthProb used */
  132078. #ifdef SQLITE_ENABLE_STAT4
  132079. # define TERM_HIGHTRUTH 0x4000 /* Term excludes few rows */
  132080. #else
  132081. # define TERM_HIGHTRUTH 0 /* Only used with STAT4 */
  132082. #endif
  132083. /*
  132084. ** An instance of the WhereScan object is used as an iterator for locating
  132085. ** terms in the WHERE clause that are useful to the query planner.
  132086. */
  132087. struct WhereScan {
  132088. WhereClause *pOrigWC; /* Original, innermost WhereClause */
  132089. WhereClause *pWC; /* WhereClause currently being scanned */
  132090. const char *zCollName; /* Required collating sequence, if not NULL */
  132091. Expr *pIdxExpr; /* Search for this index expression */
  132092. char idxaff; /* Must match this affinity, if zCollName!=NULL */
  132093. unsigned char nEquiv; /* Number of entries in aEquiv[] */
  132094. unsigned char iEquiv; /* Next unused slot in aEquiv[] */
  132095. u32 opMask; /* Acceptable operators */
  132096. int k; /* Resume scanning at this->pWC->a[this->k] */
  132097. int aiCur[11]; /* Cursors in the equivalence class */
  132098. i16 aiColumn[11]; /* Corresponding column number in the eq-class */
  132099. };
  132100. /*
  132101. ** An instance of the following structure holds all information about a
  132102. ** WHERE clause. Mostly this is a container for one or more WhereTerms.
  132103. **
  132104. ** Explanation of pOuter: For a WHERE clause of the form
  132105. **
  132106. ** a AND ((b AND c) OR (d AND e)) AND f
  132107. **
  132108. ** There are separate WhereClause objects for the whole clause and for
  132109. ** the subclauses "(b AND c)" and "(d AND e)". The pOuter field of the
  132110. ** subclauses points to the WhereClause object for the whole clause.
  132111. */
  132112. struct WhereClause {
  132113. WhereInfo *pWInfo; /* WHERE clause processing context */
  132114. WhereClause *pOuter; /* Outer conjunction */
  132115. u8 op; /* Split operator. TK_AND or TK_OR */
  132116. u8 hasOr; /* True if any a[].eOperator is WO_OR */
  132117. int nTerm; /* Number of terms */
  132118. int nSlot; /* Number of entries in a[] */
  132119. WhereTerm *a; /* Each a[] describes a term of the WHERE cluase */
  132120. #if defined(SQLITE_SMALL_STACK)
  132121. WhereTerm aStatic[1]; /* Initial static space for a[] */
  132122. #else
  132123. WhereTerm aStatic[8]; /* Initial static space for a[] */
  132124. #endif
  132125. };
  132126. /*
  132127. ** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
  132128. ** a dynamically allocated instance of the following structure.
  132129. */
  132130. struct WhereOrInfo {
  132131. WhereClause wc; /* Decomposition into subterms */
  132132. Bitmask indexable; /* Bitmask of all indexable tables in the clause */
  132133. };
  132134. /*
  132135. ** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
  132136. ** a dynamically allocated instance of the following structure.
  132137. */
  132138. struct WhereAndInfo {
  132139. WhereClause wc; /* The subexpression broken out */
  132140. };
  132141. /*
  132142. ** An instance of the following structure keeps track of a mapping
  132143. ** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
  132144. **
  132145. ** The VDBE cursor numbers are small integers contained in
  132146. ** SrcList_item.iCursor and Expr.iTable fields. For any given WHERE
  132147. ** clause, the cursor numbers might not begin with 0 and they might
  132148. ** contain gaps in the numbering sequence. But we want to make maximum
  132149. ** use of the bits in our bitmasks. This structure provides a mapping
  132150. ** from the sparse cursor numbers into consecutive integers beginning
  132151. ** with 0.
  132152. **
  132153. ** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
  132154. ** corresponds VDBE cursor number B. The A-th bit of a bitmask is 1<<A.
  132155. **
  132156. ** For example, if the WHERE clause expression used these VDBE
  132157. ** cursors: 4, 5, 8, 29, 57, 73. Then the WhereMaskSet structure
  132158. ** would map those cursor numbers into bits 0 through 5.
  132159. **
  132160. ** Note that the mapping is not necessarily ordered. In the example
  132161. ** above, the mapping might go like this: 4->3, 5->1, 8->2, 29->0,
  132162. ** 57->5, 73->4. Or one of 719 other combinations might be used. It
  132163. ** does not really matter. What is important is that sparse cursor
  132164. ** numbers all get mapped into bit numbers that begin with 0 and contain
  132165. ** no gaps.
  132166. */
  132167. struct WhereMaskSet {
  132168. int bVarSelect; /* Used by sqlite3WhereExprUsage() */
  132169. int n; /* Number of assigned cursor values */
  132170. int ix[BMS]; /* Cursor assigned to each bit */
  132171. };
  132172. /*
  132173. ** Initialize a WhereMaskSet object
  132174. */
  132175. #define initMaskSet(P) (P)->n=0
  132176. /*
  132177. ** This object is a convenience wrapper holding all information needed
  132178. ** to construct WhereLoop objects for a particular query.
  132179. */
  132180. struct WhereLoopBuilder {
  132181. WhereInfo *pWInfo; /* Information about this WHERE */
  132182. WhereClause *pWC; /* WHERE clause terms */
  132183. ExprList *pOrderBy; /* ORDER BY clause */
  132184. WhereLoop *pNew; /* Template WhereLoop */
  132185. WhereOrSet *pOrSet; /* Record best loops here, if not NULL */
  132186. #ifdef SQLITE_ENABLE_STAT4
  132187. UnpackedRecord *pRec; /* Probe for stat4 (if required) */
  132188. int nRecValid; /* Number of valid fields currently in pRec */
  132189. #endif
  132190. unsigned char bldFlags1; /* First set of SQLITE_BLDF_* flags */
  132191. unsigned char bldFlags2; /* Second set of SQLITE_BLDF_* flags */
  132192. unsigned int iPlanLimit; /* Search limiter */
  132193. };
  132194. /* Allowed values for WhereLoopBuider.bldFlags */
  132195. #define SQLITE_BLDF1_INDEXED 0x0001 /* An index is used */
  132196. #define SQLITE_BLDF1_UNIQUE 0x0002 /* All keys of a UNIQUE index used */
  132197. #define SQLITE_BLDF2_2NDPASS 0x0004 /* Second builder pass needed */
  132198. /* The WhereLoopBuilder.iPlanLimit is used to limit the number of
  132199. ** index+constraint combinations the query planner will consider for a
  132200. ** particular query. If this parameter is unlimited, then certain
  132201. ** pathological queries can spend excess time in the sqlite3WhereBegin()
  132202. ** routine. The limit is high enough that is should not impact real-world
  132203. ** queries.
  132204. **
  132205. ** SQLITE_QUERY_PLANNER_LIMIT is the baseline limit. The limit is
  132206. ** increased by SQLITE_QUERY_PLANNER_LIMIT_INCR before each term of the FROM
  132207. ** clause is processed, so that every table in a join is guaranteed to be
  132208. ** able to propose a some index+constraint combinations even if the initial
  132209. ** baseline limit was exhausted by prior tables of the join.
  132210. */
  132211. #ifndef SQLITE_QUERY_PLANNER_LIMIT
  132212. # define SQLITE_QUERY_PLANNER_LIMIT 20000
  132213. #endif
  132214. #ifndef SQLITE_QUERY_PLANNER_LIMIT_INCR
  132215. # define SQLITE_QUERY_PLANNER_LIMIT_INCR 1000
  132216. #endif
  132217. /*
  132218. ** Each instance of this object records a change to a single node
  132219. ** in an expression tree to cause that node to point to a column
  132220. ** of an index rather than an expression or a virtual column. All
  132221. ** such transformations need to be undone at the end of WHERE clause
  132222. ** processing.
  132223. */
  132224. typedef struct WhereExprMod WhereExprMod;
  132225. struct WhereExprMod {
  132226. WhereExprMod *pNext; /* Next translation on a list of them all */
  132227. Expr *pExpr; /* The Expr node that was transformed */
  132228. Expr orig; /* Original value of the Expr node */
  132229. };
  132230. /*
  132231. ** The WHERE clause processing routine has two halves. The
  132232. ** first part does the start of the WHERE loop and the second
  132233. ** half does the tail of the WHERE loop. An instance of
  132234. ** this structure is returned by the first half and passed
  132235. ** into the second half to give some continuity.
  132236. **
  132237. ** An instance of this object holds the complete state of the query
  132238. ** planner.
  132239. */
  132240. struct WhereInfo {
  132241. Parse *pParse; /* Parsing and code generating context */
  132242. SrcList *pTabList; /* List of tables in the join */
  132243. ExprList *pOrderBy; /* The ORDER BY clause or NULL */
  132244. ExprList *pResultSet; /* Result set of the query */
  132245. Expr *pWhere; /* The complete WHERE clause */
  132246. int aiCurOnePass[2]; /* OP_OpenWrite cursors for the ONEPASS opt */
  132247. int iContinue; /* Jump here to continue with next record */
  132248. int iBreak; /* Jump here to break out of the loop */
  132249. int savedNQueryLoop; /* pParse->nQueryLoop outside the WHERE loop */
  132250. u16 wctrlFlags; /* Flags originally passed to sqlite3WhereBegin() */
  132251. LogEst iLimit; /* LIMIT if wctrlFlags has WHERE_USE_LIMIT */
  132252. u8 nLevel; /* Number of nested loop */
  132253. i8 nOBSat; /* Number of ORDER BY terms satisfied by indices */
  132254. u8 eOnePass; /* ONEPASS_OFF, or _SINGLE, or _MULTI */
  132255. u8 eDistinct; /* One of the WHERE_DISTINCT_* values */
  132256. unsigned bDeferredSeek :1; /* Uses OP_DeferredSeek */
  132257. unsigned untestedTerms :1; /* Not all WHERE terms resolved by outer loop */
  132258. unsigned bOrderedInnerLoop:1;/* True if only the inner-most loop is ordered */
  132259. unsigned sorted :1; /* True if really sorted (not just grouped) */
  132260. LogEst nRowOut; /* Estimated number of output rows */
  132261. int iTop; /* The very beginning of the WHERE loop */
  132262. WhereLoop *pLoops; /* List of all WhereLoop objects */
  132263. WhereExprMod *pExprMods; /* Expression modifications */
  132264. Bitmask revMask; /* Mask of ORDER BY terms that need reversing */
  132265. WhereClause sWC; /* Decomposition of the WHERE clause */
  132266. WhereMaskSet sMaskSet; /* Map cursor numbers to bitmasks */
  132267. WhereLevel a[1]; /* Information about each nest loop in WHERE */
  132268. };
  132269. /*
  132270. ** Private interfaces - callable only by other where.c routines.
  132271. **
  132272. ** where.c:
  132273. */
  132274. SQLITE_PRIVATE Bitmask sqlite3WhereGetMask(WhereMaskSet*,int);
  132275. #ifdef WHERETRACE_ENABLED
  132276. SQLITE_PRIVATE void sqlite3WhereClausePrint(WhereClause *pWC);
  132277. SQLITE_PRIVATE void sqlite3WhereTermPrint(WhereTerm *pTerm, int iTerm);
  132278. SQLITE_PRIVATE void sqlite3WhereLoopPrint(WhereLoop *p, WhereClause *pWC);
  132279. #endif
  132280. SQLITE_PRIVATE WhereTerm *sqlite3WhereFindTerm(
  132281. WhereClause *pWC, /* The WHERE clause to be searched */
  132282. int iCur, /* Cursor number of LHS */
  132283. int iColumn, /* Column number of LHS */
  132284. Bitmask notReady, /* RHS must not overlap with this mask */
  132285. u32 op, /* Mask of WO_xx values describing operator */
  132286. Index *pIdx /* Must be compatible with this index, if not NULL */
  132287. );
  132288. /* wherecode.c: */
  132289. #ifndef SQLITE_OMIT_EXPLAIN
  132290. SQLITE_PRIVATE int sqlite3WhereExplainOneScan(
  132291. Parse *pParse, /* Parse context */
  132292. SrcList *pTabList, /* Table list this loop refers to */
  132293. WhereLevel *pLevel, /* Scan to write OP_Explain opcode for */
  132294. u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */
  132295. );
  132296. #else
  132297. # define sqlite3WhereExplainOneScan(u,v,w,x) 0
  132298. #endif /* SQLITE_OMIT_EXPLAIN */
  132299. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  132300. SQLITE_PRIVATE void sqlite3WhereAddScanStatus(
  132301. Vdbe *v, /* Vdbe to add scanstatus entry to */
  132302. SrcList *pSrclist, /* FROM clause pLvl reads data from */
  132303. WhereLevel *pLvl, /* Level to add scanstatus() entry for */
  132304. int addrExplain /* Address of OP_Explain (or 0) */
  132305. );
  132306. #else
  132307. # define sqlite3WhereAddScanStatus(a, b, c, d) ((void)d)
  132308. #endif
  132309. SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
  132310. Parse *pParse, /* Parsing context */
  132311. Vdbe *v, /* Prepared statement under construction */
  132312. WhereInfo *pWInfo, /* Complete information about the WHERE clause */
  132313. int iLevel, /* Which level of pWInfo->a[] should be coded */
  132314. WhereLevel *pLevel, /* The current level pointer */
  132315. Bitmask notReady /* Which tables are currently available */
  132316. );
  132317. /* whereexpr.c: */
  132318. SQLITE_PRIVATE void sqlite3WhereClauseInit(WhereClause*,WhereInfo*);
  132319. SQLITE_PRIVATE void sqlite3WhereClauseClear(WhereClause*);
  132320. SQLITE_PRIVATE void sqlite3WhereSplit(WhereClause*,Expr*,u8);
  132321. SQLITE_PRIVATE Bitmask sqlite3WhereExprUsage(WhereMaskSet*, Expr*);
  132322. SQLITE_PRIVATE Bitmask sqlite3WhereExprUsageNN(WhereMaskSet*, Expr*);
  132323. SQLITE_PRIVATE Bitmask sqlite3WhereExprListUsage(WhereMaskSet*, ExprList*);
  132324. SQLITE_PRIVATE void sqlite3WhereExprAnalyze(SrcList*, WhereClause*);
  132325. SQLITE_PRIVATE void sqlite3WhereTabFuncArgs(Parse*, struct SrcList_item*, WhereClause*);
  132326. /*
  132327. ** Bitmasks for the operators on WhereTerm objects. These are all
  132328. ** operators that are of interest to the query planner. An
  132329. ** OR-ed combination of these values can be used when searching for
  132330. ** particular WhereTerms within a WhereClause.
  132331. **
  132332. ** Value constraints:
  132333. ** WO_EQ == SQLITE_INDEX_CONSTRAINT_EQ
  132334. ** WO_LT == SQLITE_INDEX_CONSTRAINT_LT
  132335. ** WO_LE == SQLITE_INDEX_CONSTRAINT_LE
  132336. ** WO_GT == SQLITE_INDEX_CONSTRAINT_GT
  132337. ** WO_GE == SQLITE_INDEX_CONSTRAINT_GE
  132338. */
  132339. #define WO_IN 0x0001
  132340. #define WO_EQ 0x0002
  132341. #define WO_LT (WO_EQ<<(TK_LT-TK_EQ))
  132342. #define WO_LE (WO_EQ<<(TK_LE-TK_EQ))
  132343. #define WO_GT (WO_EQ<<(TK_GT-TK_EQ))
  132344. #define WO_GE (WO_EQ<<(TK_GE-TK_EQ))
  132345. #define WO_AUX 0x0040 /* Op useful to virtual tables only */
  132346. #define WO_IS 0x0080
  132347. #define WO_ISNULL 0x0100
  132348. #define WO_OR 0x0200 /* Two or more OR-connected terms */
  132349. #define WO_AND 0x0400 /* Two or more AND-connected terms */
  132350. #define WO_EQUIV 0x0800 /* Of the form A==B, both columns */
  132351. #define WO_NOOP 0x1000 /* This term does not restrict search space */
  132352. #define WO_ALL 0x1fff /* Mask of all possible WO_* values */
  132353. #define WO_SINGLE 0x01ff /* Mask of all non-compound WO_* values */
  132354. /*
  132355. ** These are definitions of bits in the WhereLoop.wsFlags field.
  132356. ** The particular combination of bits in each WhereLoop help to
  132357. ** determine the algorithm that WhereLoop represents.
  132358. */
  132359. #define WHERE_COLUMN_EQ 0x00000001 /* x=EXPR */
  132360. #define WHERE_COLUMN_RANGE 0x00000002 /* x<EXPR and/or x>EXPR */
  132361. #define WHERE_COLUMN_IN 0x00000004 /* x IN (...) */
  132362. #define WHERE_COLUMN_NULL 0x00000008 /* x IS NULL */
  132363. #define WHERE_CONSTRAINT 0x0000000f /* Any of the WHERE_COLUMN_xxx values */
  132364. #define WHERE_TOP_LIMIT 0x00000010 /* x<EXPR or x<=EXPR constraint */
  132365. #define WHERE_BTM_LIMIT 0x00000020 /* x>EXPR or x>=EXPR constraint */
  132366. #define WHERE_BOTH_LIMIT 0x00000030 /* Both x>EXPR and x<EXPR */
  132367. #define WHERE_IDX_ONLY 0x00000040 /* Use index only - omit table */
  132368. #define WHERE_IPK 0x00000100 /* x is the INTEGER PRIMARY KEY */
  132369. #define WHERE_INDEXED 0x00000200 /* WhereLoop.u.btree.pIndex is valid */
  132370. #define WHERE_VIRTUALTABLE 0x00000400 /* WhereLoop.u.vtab is valid */
  132371. #define WHERE_IN_ABLE 0x00000800 /* Able to support an IN operator */
  132372. #define WHERE_ONEROW 0x00001000 /* Selects no more than one row */
  132373. #define WHERE_MULTI_OR 0x00002000 /* OR using multiple indices */
  132374. #define WHERE_AUTO_INDEX 0x00004000 /* Uses an ephemeral index */
  132375. #define WHERE_SKIPSCAN 0x00008000 /* Uses the skip-scan algorithm */
  132376. #define WHERE_UNQ_WANTED 0x00010000 /* WHERE_ONEROW would have been helpful*/
  132377. #define WHERE_PARTIALIDX 0x00020000 /* The automatic index is partial */
  132378. #define WHERE_IN_EARLYOUT 0x00040000 /* Perhaps quit IN loops early */
  132379. #define WHERE_BIGNULL_SORT 0x00080000 /* Column nEq of index is BIGNULL */
  132380. #endif /* !defined(SQLITE_WHEREINT_H) */
  132381. /************** End of whereInt.h ********************************************/
  132382. /************** Continuing where we left off in wherecode.c ******************/
  132383. #ifndef SQLITE_OMIT_EXPLAIN
  132384. /*
  132385. ** Return the name of the i-th column of the pIdx index.
  132386. */
  132387. static const char *explainIndexColumnName(Index *pIdx, int i){
  132388. i = pIdx->aiColumn[i];
  132389. if( i==XN_EXPR ) return "<expr>";
  132390. if( i==XN_ROWID ) return "rowid";
  132391. return pIdx->pTable->aCol[i].zName;
  132392. }
  132393. /*
  132394. ** This routine is a helper for explainIndexRange() below
  132395. **
  132396. ** pStr holds the text of an expression that we are building up one term
  132397. ** at a time. This routine adds a new term to the end of the expression.
  132398. ** Terms are separated by AND so add the "AND" text for second and subsequent
  132399. ** terms only.
  132400. */
  132401. static void explainAppendTerm(
  132402. StrAccum *pStr, /* The text expression being built */
  132403. Index *pIdx, /* Index to read column names from */
  132404. int nTerm, /* Number of terms */
  132405. int iTerm, /* Zero-based index of first term. */
  132406. int bAnd, /* Non-zero to append " AND " */
  132407. const char *zOp /* Name of the operator */
  132408. ){
  132409. int i;
  132410. assert( nTerm>=1 );
  132411. if( bAnd ) sqlite3_str_append(pStr, " AND ", 5);
  132412. if( nTerm>1 ) sqlite3_str_append(pStr, "(", 1);
  132413. for(i=0; i<nTerm; i++){
  132414. if( i ) sqlite3_str_append(pStr, ",", 1);
  132415. sqlite3_str_appendall(pStr, explainIndexColumnName(pIdx, iTerm+i));
  132416. }
  132417. if( nTerm>1 ) sqlite3_str_append(pStr, ")", 1);
  132418. sqlite3_str_append(pStr, zOp, 1);
  132419. if( nTerm>1 ) sqlite3_str_append(pStr, "(", 1);
  132420. for(i=0; i<nTerm; i++){
  132421. if( i ) sqlite3_str_append(pStr, ",", 1);
  132422. sqlite3_str_append(pStr, "?", 1);
  132423. }
  132424. if( nTerm>1 ) sqlite3_str_append(pStr, ")", 1);
  132425. }
  132426. /*
  132427. ** Argument pLevel describes a strategy for scanning table pTab. This
  132428. ** function appends text to pStr that describes the subset of table
  132429. ** rows scanned by the strategy in the form of an SQL expression.
  132430. **
  132431. ** For example, if the query:
  132432. **
  132433. ** SELECT * FROM t1 WHERE a=1 AND b>2;
  132434. **
  132435. ** is run and there is an index on (a, b), then this function returns a
  132436. ** string similar to:
  132437. **
  132438. ** "a=? AND b>?"
  132439. */
  132440. static void explainIndexRange(StrAccum *pStr, WhereLoop *pLoop){
  132441. Index *pIndex = pLoop->u.btree.pIndex;
  132442. u16 nEq = pLoop->u.btree.nEq;
  132443. u16 nSkip = pLoop->nSkip;
  132444. int i, j;
  132445. if( nEq==0 && (pLoop->wsFlags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ) return;
  132446. sqlite3_str_append(pStr, " (", 2);
  132447. for(i=0; i<nEq; i++){
  132448. const char *z = explainIndexColumnName(pIndex, i);
  132449. if( i ) sqlite3_str_append(pStr, " AND ", 5);
  132450. sqlite3_str_appendf(pStr, i>=nSkip ? "%s=?" : "ANY(%s)", z);
  132451. }
  132452. j = i;
  132453. if( pLoop->wsFlags&WHERE_BTM_LIMIT ){
  132454. explainAppendTerm(pStr, pIndex, pLoop->u.btree.nBtm, j, i, ">");
  132455. i = 1;
  132456. }
  132457. if( pLoop->wsFlags&WHERE_TOP_LIMIT ){
  132458. explainAppendTerm(pStr, pIndex, pLoop->u.btree.nTop, j, i, "<");
  132459. }
  132460. sqlite3_str_append(pStr, ")", 1);
  132461. }
  132462. /*
  132463. ** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
  132464. ** command, or if either SQLITE_DEBUG or SQLITE_ENABLE_STMT_SCANSTATUS was
  132465. ** defined at compile-time. If it is not a no-op, a single OP_Explain opcode
  132466. ** is added to the output to describe the table scan strategy in pLevel.
  132467. **
  132468. ** If an OP_Explain opcode is added to the VM, its address is returned.
  132469. ** Otherwise, if no OP_Explain is coded, zero is returned.
  132470. */
  132471. SQLITE_PRIVATE int sqlite3WhereExplainOneScan(
  132472. Parse *pParse, /* Parse context */
  132473. SrcList *pTabList, /* Table list this loop refers to */
  132474. WhereLevel *pLevel, /* Scan to write OP_Explain opcode for */
  132475. u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */
  132476. ){
  132477. int ret = 0;
  132478. #if !defined(SQLITE_DEBUG) && !defined(SQLITE_ENABLE_STMT_SCANSTATUS)
  132479. if( sqlite3ParseToplevel(pParse)->explain==2 )
  132480. #endif
  132481. {
  132482. struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
  132483. Vdbe *v = pParse->pVdbe; /* VM being constructed */
  132484. sqlite3 *db = pParse->db; /* Database handle */
  132485. int isSearch; /* True for a SEARCH. False for SCAN. */
  132486. WhereLoop *pLoop; /* The controlling WhereLoop object */
  132487. u32 flags; /* Flags that describe this loop */
  132488. char *zMsg; /* Text to add to EQP output */
  132489. StrAccum str; /* EQP output string */
  132490. char zBuf[100]; /* Initial space for EQP output string */
  132491. pLoop = pLevel->pWLoop;
  132492. flags = pLoop->wsFlags;
  132493. if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_OR_SUBCLAUSE) ) return 0;
  132494. isSearch = (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
  132495. || ((flags&WHERE_VIRTUALTABLE)==0 && (pLoop->u.btree.nEq>0))
  132496. || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
  132497. sqlite3StrAccumInit(&str, db, zBuf, sizeof(zBuf), SQLITE_MAX_LENGTH);
  132498. sqlite3_str_appendall(&str, isSearch ? "SEARCH" : "SCAN");
  132499. if( pItem->pSelect ){
  132500. sqlite3_str_appendf(&str, " SUBQUERY %u", pItem->pSelect->selId);
  132501. }else{
  132502. sqlite3_str_appendf(&str, " TABLE %s", pItem->zName);
  132503. }
  132504. if( pItem->zAlias ){
  132505. sqlite3_str_appendf(&str, " AS %s", pItem->zAlias);
  132506. }
  132507. if( (flags & (WHERE_IPK|WHERE_VIRTUALTABLE))==0 ){
  132508. const char *zFmt = 0;
  132509. Index *pIdx;
  132510. assert( pLoop->u.btree.pIndex!=0 );
  132511. pIdx = pLoop->u.btree.pIndex;
  132512. assert( !(flags&WHERE_AUTO_INDEX) || (flags&WHERE_IDX_ONLY) );
  132513. if( !HasRowid(pItem->pTab) && IsPrimaryKeyIndex(pIdx) ){
  132514. if( isSearch ){
  132515. zFmt = "PRIMARY KEY";
  132516. }
  132517. }else if( flags & WHERE_PARTIALIDX ){
  132518. zFmt = "AUTOMATIC PARTIAL COVERING INDEX";
  132519. }else if( flags & WHERE_AUTO_INDEX ){
  132520. zFmt = "AUTOMATIC COVERING INDEX";
  132521. }else if( flags & WHERE_IDX_ONLY ){
  132522. zFmt = "COVERING INDEX %s";
  132523. }else{
  132524. zFmt = "INDEX %s";
  132525. }
  132526. if( zFmt ){
  132527. sqlite3_str_append(&str, " USING ", 7);
  132528. sqlite3_str_appendf(&str, zFmt, pIdx->zName);
  132529. explainIndexRange(&str, pLoop);
  132530. }
  132531. }else if( (flags & WHERE_IPK)!=0 && (flags & WHERE_CONSTRAINT)!=0 ){
  132532. const char *zRangeOp;
  132533. if( flags&(WHERE_COLUMN_EQ|WHERE_COLUMN_IN) ){
  132534. zRangeOp = "=";
  132535. }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
  132536. zRangeOp = ">? AND rowid<";
  132537. }else if( flags&WHERE_BTM_LIMIT ){
  132538. zRangeOp = ">";
  132539. }else{
  132540. assert( flags&WHERE_TOP_LIMIT);
  132541. zRangeOp = "<";
  132542. }
  132543. sqlite3_str_appendf(&str,
  132544. " USING INTEGER PRIMARY KEY (rowid%s?)",zRangeOp);
  132545. }
  132546. #ifndef SQLITE_OMIT_VIRTUALTABLE
  132547. else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
  132548. sqlite3_str_appendf(&str, " VIRTUAL TABLE INDEX %d:%s",
  132549. pLoop->u.vtab.idxNum, pLoop->u.vtab.idxStr);
  132550. }
  132551. #endif
  132552. #ifdef SQLITE_EXPLAIN_ESTIMATED_ROWS
  132553. if( pLoop->nOut>=10 ){
  132554. sqlite3_str_appendf(&str, " (~%llu rows)",
  132555. sqlite3LogEstToInt(pLoop->nOut));
  132556. }else{
  132557. sqlite3_str_append(&str, " (~1 row)", 9);
  132558. }
  132559. #endif
  132560. zMsg = sqlite3StrAccumFinish(&str);
  132561. sqlite3ExplainBreakpoint("",zMsg);
  132562. ret = sqlite3VdbeAddOp4(v, OP_Explain, sqlite3VdbeCurrentAddr(v),
  132563. pParse->addrExplain, 0, zMsg,P4_DYNAMIC);
  132564. }
  132565. return ret;
  132566. }
  132567. #endif /* SQLITE_OMIT_EXPLAIN */
  132568. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  132569. /*
  132570. ** Configure the VM passed as the first argument with an
  132571. ** sqlite3_stmt_scanstatus() entry corresponding to the scan used to
  132572. ** implement level pLvl. Argument pSrclist is a pointer to the FROM
  132573. ** clause that the scan reads data from.
  132574. **
  132575. ** If argument addrExplain is not 0, it must be the address of an
  132576. ** OP_Explain instruction that describes the same loop.
  132577. */
  132578. SQLITE_PRIVATE void sqlite3WhereAddScanStatus(
  132579. Vdbe *v, /* Vdbe to add scanstatus entry to */
  132580. SrcList *pSrclist, /* FROM clause pLvl reads data from */
  132581. WhereLevel *pLvl, /* Level to add scanstatus() entry for */
  132582. int addrExplain /* Address of OP_Explain (or 0) */
  132583. ){
  132584. const char *zObj = 0;
  132585. WhereLoop *pLoop = pLvl->pWLoop;
  132586. if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 && pLoop->u.btree.pIndex!=0 ){
  132587. zObj = pLoop->u.btree.pIndex->zName;
  132588. }else{
  132589. zObj = pSrclist->a[pLvl->iFrom].zName;
  132590. }
  132591. sqlite3VdbeScanStatus(
  132592. v, addrExplain, pLvl->addrBody, pLvl->addrVisit, pLoop->nOut, zObj
  132593. );
  132594. }
  132595. #endif
  132596. /*
  132597. ** Disable a term in the WHERE clause. Except, do not disable the term
  132598. ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
  132599. ** or USING clause of that join.
  132600. **
  132601. ** Consider the term t2.z='ok' in the following queries:
  132602. **
  132603. ** (1) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
  132604. ** (2) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
  132605. ** (3) SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
  132606. **
  132607. ** The t2.z='ok' is disabled in the in (2) because it originates
  132608. ** in the ON clause. The term is disabled in (3) because it is not part
  132609. ** of a LEFT OUTER JOIN. In (1), the term is not disabled.
  132610. **
  132611. ** Disabling a term causes that term to not be tested in the inner loop
  132612. ** of the join. Disabling is an optimization. When terms are satisfied
  132613. ** by indices, we disable them to prevent redundant tests in the inner
  132614. ** loop. We would get the correct results if nothing were ever disabled,
  132615. ** but joins might run a little slower. The trick is to disable as much
  132616. ** as we can without disabling too much. If we disabled in (1), we'd get
  132617. ** the wrong answer. See ticket #813.
  132618. **
  132619. ** If all the children of a term are disabled, then that term is also
  132620. ** automatically disabled. In this way, terms get disabled if derived
  132621. ** virtual terms are tested first. For example:
  132622. **
  132623. ** x GLOB 'abc*' AND x>='abc' AND x<'acd'
  132624. ** \___________/ \______/ \_____/
  132625. ** parent child1 child2
  132626. **
  132627. ** Only the parent term was in the original WHERE clause. The child1
  132628. ** and child2 terms were added by the LIKE optimization. If both of
  132629. ** the virtual child terms are valid, then testing of the parent can be
  132630. ** skipped.
  132631. **
  132632. ** Usually the parent term is marked as TERM_CODED. But if the parent
  132633. ** term was originally TERM_LIKE, then the parent gets TERM_LIKECOND instead.
  132634. ** The TERM_LIKECOND marking indicates that the term should be coded inside
  132635. ** a conditional such that is only evaluated on the second pass of a
  132636. ** LIKE-optimization loop, when scanning BLOBs instead of strings.
  132637. */
  132638. static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
  132639. int nLoop = 0;
  132640. assert( pTerm!=0 );
  132641. while( (pTerm->wtFlags & TERM_CODED)==0
  132642. && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
  132643. && (pLevel->notReady & pTerm->prereqAll)==0
  132644. ){
  132645. if( nLoop && (pTerm->wtFlags & TERM_LIKE)!=0 ){
  132646. pTerm->wtFlags |= TERM_LIKECOND;
  132647. }else{
  132648. pTerm->wtFlags |= TERM_CODED;
  132649. }
  132650. if( pTerm->iParent<0 ) break;
  132651. pTerm = &pTerm->pWC->a[pTerm->iParent];
  132652. assert( pTerm!=0 );
  132653. pTerm->nChild--;
  132654. if( pTerm->nChild!=0 ) break;
  132655. nLoop++;
  132656. }
  132657. }
  132658. /*
  132659. ** Code an OP_Affinity opcode to apply the column affinity string zAff
  132660. ** to the n registers starting at base.
  132661. **
  132662. ** As an optimization, SQLITE_AFF_BLOB and SQLITE_AFF_NONE entries (which
  132663. ** are no-ops) at the beginning and end of zAff are ignored. If all entries
  132664. ** in zAff are SQLITE_AFF_BLOB or SQLITE_AFF_NONE, then no code gets generated.
  132665. **
  132666. ** This routine makes its own copy of zAff so that the caller is free
  132667. ** to modify zAff after this routine returns.
  132668. */
  132669. static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
  132670. Vdbe *v = pParse->pVdbe;
  132671. if( zAff==0 ){
  132672. assert( pParse->db->mallocFailed );
  132673. return;
  132674. }
  132675. assert( v!=0 );
  132676. /* Adjust base and n to skip over SQLITE_AFF_BLOB and SQLITE_AFF_NONE
  132677. ** entries at the beginning and end of the affinity string.
  132678. */
  132679. assert( SQLITE_AFF_NONE<SQLITE_AFF_BLOB );
  132680. while( n>0 && zAff[0]<=SQLITE_AFF_BLOB ){
  132681. n--;
  132682. base++;
  132683. zAff++;
  132684. }
  132685. while( n>1 && zAff[n-1]<=SQLITE_AFF_BLOB ){
  132686. n--;
  132687. }
  132688. /* Code the OP_Affinity opcode if there is anything left to do. */
  132689. if( n>0 ){
  132690. sqlite3VdbeAddOp4(v, OP_Affinity, base, n, 0, zAff, n);
  132691. }
  132692. }
  132693. /*
  132694. ** Expression pRight, which is the RHS of a comparison operation, is
  132695. ** either a vector of n elements or, if n==1, a scalar expression.
  132696. ** Before the comparison operation, affinity zAff is to be applied
  132697. ** to the pRight values. This function modifies characters within the
  132698. ** affinity string to SQLITE_AFF_BLOB if either:
  132699. **
  132700. ** * the comparison will be performed with no affinity, or
  132701. ** * the affinity change in zAff is guaranteed not to change the value.
  132702. */
  132703. static void updateRangeAffinityStr(
  132704. Expr *pRight, /* RHS of comparison */
  132705. int n, /* Number of vector elements in comparison */
  132706. char *zAff /* Affinity string to modify */
  132707. ){
  132708. int i;
  132709. for(i=0; i<n; i++){
  132710. Expr *p = sqlite3VectorFieldSubexpr(pRight, i);
  132711. if( sqlite3CompareAffinity(p, zAff[i])==SQLITE_AFF_BLOB
  132712. || sqlite3ExprNeedsNoAffinityChange(p, zAff[i])
  132713. ){
  132714. zAff[i] = SQLITE_AFF_BLOB;
  132715. }
  132716. }
  132717. }
  132718. /*
  132719. ** pX is an expression of the form: (vector) IN (SELECT ...)
  132720. ** In other words, it is a vector IN operator with a SELECT clause on the
  132721. ** LHS. But not all terms in the vector are indexable and the terms might
  132722. ** not be in the correct order for indexing.
  132723. **
  132724. ** This routine makes a copy of the input pX expression and then adjusts
  132725. ** the vector on the LHS with corresponding changes to the SELECT so that
  132726. ** the vector contains only index terms and those terms are in the correct
  132727. ** order. The modified IN expression is returned. The caller is responsible
  132728. ** for deleting the returned expression.
  132729. **
  132730. ** Example:
  132731. **
  132732. ** CREATE TABLE t1(a,b,c,d,e,f);
  132733. ** CREATE INDEX t1x1 ON t1(e,c);
  132734. ** SELECT * FROM t1 WHERE (a,b,c,d,e) IN (SELECT v,w,x,y,z FROM t2)
  132735. ** \_______________________________________/
  132736. ** The pX expression
  132737. **
  132738. ** Since only columns e and c can be used with the index, in that order,
  132739. ** the modified IN expression that is returned will be:
  132740. **
  132741. ** (e,c) IN (SELECT z,x FROM t2)
  132742. **
  132743. ** The reduced pX is different from the original (obviously) and thus is
  132744. ** only used for indexing, to improve performance. The original unaltered
  132745. ** IN expression must also be run on each output row for correctness.
  132746. */
  132747. static Expr *removeUnindexableInClauseTerms(
  132748. Parse *pParse, /* The parsing context */
  132749. int iEq, /* Look at loop terms starting here */
  132750. WhereLoop *pLoop, /* The current loop */
  132751. Expr *pX /* The IN expression to be reduced */
  132752. ){
  132753. sqlite3 *db = pParse->db;
  132754. Expr *pNew;
  132755. pNew = sqlite3ExprDup(db, pX, 0);
  132756. if( db->mallocFailed==0 ){
  132757. ExprList *pOrigRhs = pNew->x.pSelect->pEList; /* Original unmodified RHS */
  132758. ExprList *pOrigLhs = pNew->pLeft->x.pList; /* Original unmodified LHS */
  132759. ExprList *pRhs = 0; /* New RHS after modifications */
  132760. ExprList *pLhs = 0; /* New LHS after mods */
  132761. int i; /* Loop counter */
  132762. Select *pSelect; /* Pointer to the SELECT on the RHS */
  132763. for(i=iEq; i<pLoop->nLTerm; i++){
  132764. if( pLoop->aLTerm[i]->pExpr==pX ){
  132765. int iField = pLoop->aLTerm[i]->iField - 1;
  132766. if( pOrigRhs->a[iField].pExpr==0 ) continue; /* Duplicate PK column */
  132767. pRhs = sqlite3ExprListAppend(pParse, pRhs, pOrigRhs->a[iField].pExpr);
  132768. pOrigRhs->a[iField].pExpr = 0;
  132769. assert( pOrigLhs->a[iField].pExpr!=0 );
  132770. pLhs = sqlite3ExprListAppend(pParse, pLhs, pOrigLhs->a[iField].pExpr);
  132771. pOrigLhs->a[iField].pExpr = 0;
  132772. }
  132773. }
  132774. sqlite3ExprListDelete(db, pOrigRhs);
  132775. sqlite3ExprListDelete(db, pOrigLhs);
  132776. pNew->pLeft->x.pList = pLhs;
  132777. pNew->x.pSelect->pEList = pRhs;
  132778. if( pLhs && pLhs->nExpr==1 ){
  132779. /* Take care here not to generate a TK_VECTOR containing only a
  132780. ** single value. Since the parser never creates such a vector, some
  132781. ** of the subroutines do not handle this case. */
  132782. Expr *p = pLhs->a[0].pExpr;
  132783. pLhs->a[0].pExpr = 0;
  132784. sqlite3ExprDelete(db, pNew->pLeft);
  132785. pNew->pLeft = p;
  132786. }
  132787. pSelect = pNew->x.pSelect;
  132788. if( pSelect->pOrderBy ){
  132789. /* If the SELECT statement has an ORDER BY clause, zero the
  132790. ** iOrderByCol variables. These are set to non-zero when an
  132791. ** ORDER BY term exactly matches one of the terms of the
  132792. ** result-set. Since the result-set of the SELECT statement may
  132793. ** have been modified or reordered, these variables are no longer
  132794. ** set correctly. Since setting them is just an optimization,
  132795. ** it's easiest just to zero them here. */
  132796. ExprList *pOrderBy = pSelect->pOrderBy;
  132797. for(i=0; i<pOrderBy->nExpr; i++){
  132798. pOrderBy->a[i].u.x.iOrderByCol = 0;
  132799. }
  132800. }
  132801. #if 0
  132802. printf("For indexing, change the IN expr:\n");
  132803. sqlite3TreeViewExpr(0, pX, 0);
  132804. printf("Into:\n");
  132805. sqlite3TreeViewExpr(0, pNew, 0);
  132806. #endif
  132807. }
  132808. return pNew;
  132809. }
  132810. /*
  132811. ** Generate code for a single equality term of the WHERE clause. An equality
  132812. ** term can be either X=expr or X IN (...). pTerm is the term to be
  132813. ** coded.
  132814. **
  132815. ** The current value for the constraint is left in a register, the index
  132816. ** of which is returned. An attempt is made store the result in iTarget but
  132817. ** this is only guaranteed for TK_ISNULL and TK_IN constraints. If the
  132818. ** constraint is a TK_EQ or TK_IS, then the current value might be left in
  132819. ** some other register and it is the caller's responsibility to compensate.
  132820. **
  132821. ** For a constraint of the form X=expr, the expression is evaluated in
  132822. ** straight-line code. For constraints of the form X IN (...)
  132823. ** this routine sets up a loop that will iterate over all values of X.
  132824. */
  132825. static int codeEqualityTerm(
  132826. Parse *pParse, /* The parsing context */
  132827. WhereTerm *pTerm, /* The term of the WHERE clause to be coded */
  132828. WhereLevel *pLevel, /* The level of the FROM clause we are working on */
  132829. int iEq, /* Index of the equality term within this level */
  132830. int bRev, /* True for reverse-order IN operations */
  132831. int iTarget /* Attempt to leave results in this register */
  132832. ){
  132833. Expr *pX = pTerm->pExpr;
  132834. Vdbe *v = pParse->pVdbe;
  132835. int iReg; /* Register holding results */
  132836. assert( pLevel->pWLoop->aLTerm[iEq]==pTerm );
  132837. assert( iTarget>0 );
  132838. if( pX->op==TK_EQ || pX->op==TK_IS ){
  132839. iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
  132840. }else if( pX->op==TK_ISNULL ){
  132841. iReg = iTarget;
  132842. sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
  132843. #ifndef SQLITE_OMIT_SUBQUERY
  132844. }else{
  132845. int eType = IN_INDEX_NOOP;
  132846. int iTab;
  132847. struct InLoop *pIn;
  132848. WhereLoop *pLoop = pLevel->pWLoop;
  132849. int i;
  132850. int nEq = 0;
  132851. int *aiMap = 0;
  132852. if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0
  132853. && pLoop->u.btree.pIndex!=0
  132854. && pLoop->u.btree.pIndex->aSortOrder[iEq]
  132855. ){
  132856. testcase( iEq==0 );
  132857. testcase( bRev );
  132858. bRev = !bRev;
  132859. }
  132860. assert( pX->op==TK_IN );
  132861. iReg = iTarget;
  132862. for(i=0; i<iEq; i++){
  132863. if( pLoop->aLTerm[i] && pLoop->aLTerm[i]->pExpr==pX ){
  132864. disableTerm(pLevel, pTerm);
  132865. return iTarget;
  132866. }
  132867. }
  132868. for(i=iEq;i<pLoop->nLTerm; i++){
  132869. assert( pLoop->aLTerm[i]!=0 );
  132870. if( pLoop->aLTerm[i]->pExpr==pX ) nEq++;
  132871. }
  132872. iTab = 0;
  132873. if( (pX->flags & EP_xIsSelect)==0 || pX->x.pSelect->pEList->nExpr==1 ){
  132874. eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0, 0, &iTab);
  132875. }else{
  132876. sqlite3 *db = pParse->db;
  132877. pX = removeUnindexableInClauseTerms(pParse, iEq, pLoop, pX);
  132878. if( !db->mallocFailed ){
  132879. aiMap = (int*)sqlite3DbMallocZero(pParse->db, sizeof(int)*nEq);
  132880. eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0, aiMap, &iTab);
  132881. pTerm->pExpr->iTable = iTab;
  132882. }
  132883. sqlite3ExprDelete(db, pX);
  132884. pX = pTerm->pExpr;
  132885. }
  132886. if( eType==IN_INDEX_INDEX_DESC ){
  132887. testcase( bRev );
  132888. bRev = !bRev;
  132889. }
  132890. sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0);
  132891. VdbeCoverageIf(v, bRev);
  132892. VdbeCoverageIf(v, !bRev);
  132893. assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 );
  132894. pLoop->wsFlags |= WHERE_IN_ABLE;
  132895. if( pLevel->u.in.nIn==0 ){
  132896. pLevel->addrNxt = sqlite3VdbeMakeLabel(pParse);
  132897. }
  132898. i = pLevel->u.in.nIn;
  132899. pLevel->u.in.nIn += nEq;
  132900. pLevel->u.in.aInLoop =
  132901. sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
  132902. sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
  132903. pIn = pLevel->u.in.aInLoop;
  132904. if( pIn ){
  132905. int iMap = 0; /* Index in aiMap[] */
  132906. pIn += i;
  132907. for(i=iEq;i<pLoop->nLTerm; i++){
  132908. if( pLoop->aLTerm[i]->pExpr==pX ){
  132909. int iOut = iReg + i - iEq;
  132910. if( eType==IN_INDEX_ROWID ){
  132911. pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iOut);
  132912. }else{
  132913. int iCol = aiMap ? aiMap[iMap++] : 0;
  132914. pIn->addrInTop = sqlite3VdbeAddOp3(v,OP_Column,iTab, iCol, iOut);
  132915. }
  132916. sqlite3VdbeAddOp1(v, OP_IsNull, iOut); VdbeCoverage(v);
  132917. if( i==iEq ){
  132918. pIn->iCur = iTab;
  132919. pIn->eEndLoopOp = bRev ? OP_Prev : OP_Next;
  132920. if( iEq>0 ){
  132921. pIn->iBase = iReg - i;
  132922. pIn->nPrefix = i;
  132923. pLoop->wsFlags |= WHERE_IN_EARLYOUT;
  132924. }else{
  132925. pIn->nPrefix = 0;
  132926. }
  132927. }else{
  132928. pIn->eEndLoopOp = OP_Noop;
  132929. }
  132930. pIn++;
  132931. }
  132932. }
  132933. }else{
  132934. pLevel->u.in.nIn = 0;
  132935. }
  132936. sqlite3DbFree(pParse->db, aiMap);
  132937. #endif
  132938. }
  132939. disableTerm(pLevel, pTerm);
  132940. return iReg;
  132941. }
  132942. /*
  132943. ** Generate code that will evaluate all == and IN constraints for an
  132944. ** index scan.
  132945. **
  132946. ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
  132947. ** Suppose the WHERE clause is this: a==5 AND b IN (1,2,3) AND c>5 AND c<10
  132948. ** The index has as many as three equality constraints, but in this
  132949. ** example, the third "c" value is an inequality. So only two
  132950. ** constraints are coded. This routine will generate code to evaluate
  132951. ** a==5 and b IN (1,2,3). The current values for a and b will be stored
  132952. ** in consecutive registers and the index of the first register is returned.
  132953. **
  132954. ** In the example above nEq==2. But this subroutine works for any value
  132955. ** of nEq including 0. If nEq==0, this routine is nearly a no-op.
  132956. ** The only thing it does is allocate the pLevel->iMem memory cell and
  132957. ** compute the affinity string.
  132958. **
  132959. ** The nExtraReg parameter is 0 or 1. It is 0 if all WHERE clause constraints
  132960. ** are == or IN and are covered by the nEq. nExtraReg is 1 if there is
  132961. ** an inequality constraint (such as the "c>=5 AND c<10" in the example) that
  132962. ** occurs after the nEq quality constraints.
  132963. **
  132964. ** This routine allocates a range of nEq+nExtraReg memory cells and returns
  132965. ** the index of the first memory cell in that range. The code that
  132966. ** calls this routine will use that memory range to store keys for
  132967. ** start and termination conditions of the loop.
  132968. ** key value of the loop. If one or more IN operators appear, then
  132969. ** this routine allocates an additional nEq memory cells for internal
  132970. ** use.
  132971. **
  132972. ** Before returning, *pzAff is set to point to a buffer containing a
  132973. ** copy of the column affinity string of the index allocated using
  132974. ** sqlite3DbMalloc(). Except, entries in the copy of the string associated
  132975. ** with equality constraints that use BLOB or NONE affinity are set to
  132976. ** SQLITE_AFF_BLOB. This is to deal with SQL such as the following:
  132977. **
  132978. ** CREATE TABLE t1(a TEXT PRIMARY KEY, b);
  132979. ** SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
  132980. **
  132981. ** In the example above, the index on t1(a) has TEXT affinity. But since
  132982. ** the right hand side of the equality constraint (t2.b) has BLOB/NONE affinity,
  132983. ** no conversion should be attempted before using a t2.b value as part of
  132984. ** a key to search the index. Hence the first byte in the returned affinity
  132985. ** string in this example would be set to SQLITE_AFF_BLOB.
  132986. */
  132987. static int codeAllEqualityTerms(
  132988. Parse *pParse, /* Parsing context */
  132989. WhereLevel *pLevel, /* Which nested loop of the FROM we are coding */
  132990. int bRev, /* Reverse the order of IN operators */
  132991. int nExtraReg, /* Number of extra registers to allocate */
  132992. char **pzAff /* OUT: Set to point to affinity string */
  132993. ){
  132994. u16 nEq; /* The number of == or IN constraints to code */
  132995. u16 nSkip; /* Number of left-most columns to skip */
  132996. Vdbe *v = pParse->pVdbe; /* The vm under construction */
  132997. Index *pIdx; /* The index being used for this loop */
  132998. WhereTerm *pTerm; /* A single constraint term */
  132999. WhereLoop *pLoop; /* The WhereLoop object */
  133000. int j; /* Loop counter */
  133001. int regBase; /* Base register */
  133002. int nReg; /* Number of registers to allocate */
  133003. char *zAff; /* Affinity string to return */
  133004. /* This module is only called on query plans that use an index. */
  133005. pLoop = pLevel->pWLoop;
  133006. assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 );
  133007. nEq = pLoop->u.btree.nEq;
  133008. nSkip = pLoop->nSkip;
  133009. pIdx = pLoop->u.btree.pIndex;
  133010. assert( pIdx!=0 );
  133011. /* Figure out how many memory cells we will need then allocate them.
  133012. */
  133013. regBase = pParse->nMem + 1;
  133014. nReg = pLoop->u.btree.nEq + nExtraReg;
  133015. pParse->nMem += nReg;
  133016. zAff = sqlite3DbStrDup(pParse->db,sqlite3IndexAffinityStr(pParse->db,pIdx));
  133017. assert( zAff!=0 || pParse->db->mallocFailed );
  133018. if( nSkip ){
  133019. int iIdxCur = pLevel->iIdxCur;
  133020. sqlite3VdbeAddOp1(v, (bRev?OP_Last:OP_Rewind), iIdxCur);
  133021. VdbeCoverageIf(v, bRev==0);
  133022. VdbeCoverageIf(v, bRev!=0);
  133023. VdbeComment((v, "begin skip-scan on %s", pIdx->zName));
  133024. j = sqlite3VdbeAddOp0(v, OP_Goto);
  133025. pLevel->addrSkip = sqlite3VdbeAddOp4Int(v, (bRev?OP_SeekLT:OP_SeekGT),
  133026. iIdxCur, 0, regBase, nSkip);
  133027. VdbeCoverageIf(v, bRev==0);
  133028. VdbeCoverageIf(v, bRev!=0);
  133029. sqlite3VdbeJumpHere(v, j);
  133030. for(j=0; j<nSkip; j++){
  133031. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, j, regBase+j);
  133032. testcase( pIdx->aiColumn[j]==XN_EXPR );
  133033. VdbeComment((v, "%s", explainIndexColumnName(pIdx, j)));
  133034. }
  133035. }
  133036. /* Evaluate the equality constraints
  133037. */
  133038. assert( zAff==0 || (int)strlen(zAff)>=nEq );
  133039. for(j=nSkip; j<nEq; j++){
  133040. int r1;
  133041. pTerm = pLoop->aLTerm[j];
  133042. assert( pTerm!=0 );
  133043. /* The following testcase is true for indices with redundant columns.
  133044. ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
  133045. testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
  133046. testcase( pTerm->wtFlags & TERM_VIRTUAL );
  133047. r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, regBase+j);
  133048. if( r1!=regBase+j ){
  133049. if( nReg==1 ){
  133050. sqlite3ReleaseTempReg(pParse, regBase);
  133051. regBase = r1;
  133052. }else{
  133053. sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
  133054. }
  133055. }
  133056. if( pTerm->eOperator & WO_IN ){
  133057. if( pTerm->pExpr->flags & EP_xIsSelect ){
  133058. /* No affinity ever needs to be (or should be) applied to a value
  133059. ** from the RHS of an "? IN (SELECT ...)" expression. The
  133060. ** sqlite3FindInIndex() routine has already ensured that the
  133061. ** affinity of the comparison has been applied to the value. */
  133062. if( zAff ) zAff[j] = SQLITE_AFF_BLOB;
  133063. }
  133064. }else if( (pTerm->eOperator & WO_ISNULL)==0 ){
  133065. Expr *pRight = pTerm->pExpr->pRight;
  133066. if( (pTerm->wtFlags & TERM_IS)==0 && sqlite3ExprCanBeNull(pRight) ){
  133067. sqlite3VdbeAddOp2(v, OP_IsNull, regBase+j, pLevel->addrBrk);
  133068. VdbeCoverage(v);
  133069. }
  133070. if( zAff ){
  133071. if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_BLOB ){
  133072. zAff[j] = SQLITE_AFF_BLOB;
  133073. }
  133074. if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
  133075. zAff[j] = SQLITE_AFF_BLOB;
  133076. }
  133077. }
  133078. }
  133079. }
  133080. *pzAff = zAff;
  133081. return regBase;
  133082. }
  133083. #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
  133084. /*
  133085. ** If the most recently coded instruction is a constant range constraint
  133086. ** (a string literal) that originated from the LIKE optimization, then
  133087. ** set P3 and P5 on the OP_String opcode so that the string will be cast
  133088. ** to a BLOB at appropriate times.
  133089. **
  133090. ** The LIKE optimization trys to evaluate "x LIKE 'abc%'" as a range
  133091. ** expression: "x>='ABC' AND x<'abd'". But this requires that the range
  133092. ** scan loop run twice, once for strings and a second time for BLOBs.
  133093. ** The OP_String opcodes on the second pass convert the upper and lower
  133094. ** bound string constants to blobs. This routine makes the necessary changes
  133095. ** to the OP_String opcodes for that to happen.
  133096. **
  133097. ** Except, of course, if SQLITE_LIKE_DOESNT_MATCH_BLOBS is defined, then
  133098. ** only the one pass through the string space is required, so this routine
  133099. ** becomes a no-op.
  133100. */
  133101. static void whereLikeOptimizationStringFixup(
  133102. Vdbe *v, /* prepared statement under construction */
  133103. WhereLevel *pLevel, /* The loop that contains the LIKE operator */
  133104. WhereTerm *pTerm /* The upper or lower bound just coded */
  133105. ){
  133106. if( pTerm->wtFlags & TERM_LIKEOPT ){
  133107. VdbeOp *pOp;
  133108. assert( pLevel->iLikeRepCntr>0 );
  133109. pOp = sqlite3VdbeGetOp(v, -1);
  133110. assert( pOp!=0 );
  133111. assert( pOp->opcode==OP_String8
  133112. || pTerm->pWC->pWInfo->pParse->db->mallocFailed );
  133113. pOp->p3 = (int)(pLevel->iLikeRepCntr>>1); /* Register holding counter */
  133114. pOp->p5 = (u8)(pLevel->iLikeRepCntr&1); /* ASC or DESC */
  133115. }
  133116. }
  133117. #else
  133118. # define whereLikeOptimizationStringFixup(A,B,C)
  133119. #endif
  133120. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  133121. /*
  133122. ** Information is passed from codeCursorHint() down to individual nodes of
  133123. ** the expression tree (by sqlite3WalkExpr()) using an instance of this
  133124. ** structure.
  133125. */
  133126. struct CCurHint {
  133127. int iTabCur; /* Cursor for the main table */
  133128. int iIdxCur; /* Cursor for the index, if pIdx!=0. Unused otherwise */
  133129. Index *pIdx; /* The index used to access the table */
  133130. };
  133131. /*
  133132. ** This function is called for every node of an expression that is a candidate
  133133. ** for a cursor hint on an index cursor. For TK_COLUMN nodes that reference
  133134. ** the table CCurHint.iTabCur, verify that the same column can be
  133135. ** accessed through the index. If it cannot, then set pWalker->eCode to 1.
  133136. */
  133137. static int codeCursorHintCheckExpr(Walker *pWalker, Expr *pExpr){
  133138. struct CCurHint *pHint = pWalker->u.pCCurHint;
  133139. assert( pHint->pIdx!=0 );
  133140. if( pExpr->op==TK_COLUMN
  133141. && pExpr->iTable==pHint->iTabCur
  133142. && sqlite3TableColumnToIndex(pHint->pIdx, pExpr->iColumn)<0
  133143. ){
  133144. pWalker->eCode = 1;
  133145. }
  133146. return WRC_Continue;
  133147. }
  133148. /*
  133149. ** Test whether or not expression pExpr, which was part of a WHERE clause,
  133150. ** should be included in the cursor-hint for a table that is on the rhs
  133151. ** of a LEFT JOIN. Set Walker.eCode to non-zero before returning if the
  133152. ** expression is not suitable.
  133153. **
  133154. ** An expression is unsuitable if it might evaluate to non NULL even if
  133155. ** a TK_COLUMN node that does affect the value of the expression is set
  133156. ** to NULL. For example:
  133157. **
  133158. ** col IS NULL
  133159. ** col IS NOT NULL
  133160. ** coalesce(col, 1)
  133161. ** CASE WHEN col THEN 0 ELSE 1 END
  133162. */
  133163. static int codeCursorHintIsOrFunction(Walker *pWalker, Expr *pExpr){
  133164. if( pExpr->op==TK_IS
  133165. || pExpr->op==TK_ISNULL || pExpr->op==TK_ISNOT
  133166. || pExpr->op==TK_NOTNULL || pExpr->op==TK_CASE
  133167. ){
  133168. pWalker->eCode = 1;
  133169. }else if( pExpr->op==TK_FUNCTION ){
  133170. int d1;
  133171. char d2[4];
  133172. if( 0==sqlite3IsLikeFunction(pWalker->pParse->db, pExpr, &d1, d2) ){
  133173. pWalker->eCode = 1;
  133174. }
  133175. }
  133176. return WRC_Continue;
  133177. }
  133178. /*
  133179. ** This function is called on every node of an expression tree used as an
  133180. ** argument to the OP_CursorHint instruction. If the node is a TK_COLUMN
  133181. ** that accesses any table other than the one identified by
  133182. ** CCurHint.iTabCur, then do the following:
  133183. **
  133184. ** 1) allocate a register and code an OP_Column instruction to read
  133185. ** the specified column into the new register, and
  133186. **
  133187. ** 2) transform the expression node to a TK_REGISTER node that reads
  133188. ** from the newly populated register.
  133189. **
  133190. ** Also, if the node is a TK_COLUMN that does access the table idenified
  133191. ** by pCCurHint.iTabCur, and an index is being used (which we will
  133192. ** know because CCurHint.pIdx!=0) then transform the TK_COLUMN into
  133193. ** an access of the index rather than the original table.
  133194. */
  133195. static int codeCursorHintFixExpr(Walker *pWalker, Expr *pExpr){
  133196. int rc = WRC_Continue;
  133197. struct CCurHint *pHint = pWalker->u.pCCurHint;
  133198. if( pExpr->op==TK_COLUMN ){
  133199. if( pExpr->iTable!=pHint->iTabCur ){
  133200. int reg = ++pWalker->pParse->nMem; /* Register for column value */
  133201. sqlite3ExprCode(pWalker->pParse, pExpr, reg);
  133202. pExpr->op = TK_REGISTER;
  133203. pExpr->iTable = reg;
  133204. }else if( pHint->pIdx!=0 ){
  133205. pExpr->iTable = pHint->iIdxCur;
  133206. pExpr->iColumn = sqlite3TableColumnToIndex(pHint->pIdx, pExpr->iColumn);
  133207. assert( pExpr->iColumn>=0 );
  133208. }
  133209. }else if( pExpr->op==TK_AGG_FUNCTION ){
  133210. /* An aggregate function in the WHERE clause of a query means this must
  133211. ** be a correlated sub-query, and expression pExpr is an aggregate from
  133212. ** the parent context. Do not walk the function arguments in this case.
  133213. **
  133214. ** todo: It should be possible to replace this node with a TK_REGISTER
  133215. ** expression, as the result of the expression must be stored in a
  133216. ** register at this point. The same holds for TK_AGG_COLUMN nodes. */
  133217. rc = WRC_Prune;
  133218. }
  133219. return rc;
  133220. }
  133221. /*
  133222. ** Insert an OP_CursorHint instruction if it is appropriate to do so.
  133223. */
  133224. static void codeCursorHint(
  133225. struct SrcList_item *pTabItem, /* FROM clause item */
  133226. WhereInfo *pWInfo, /* The where clause */
  133227. WhereLevel *pLevel, /* Which loop to provide hints for */
  133228. WhereTerm *pEndRange /* Hint this end-of-scan boundary term if not NULL */
  133229. ){
  133230. Parse *pParse = pWInfo->pParse;
  133231. sqlite3 *db = pParse->db;
  133232. Vdbe *v = pParse->pVdbe;
  133233. Expr *pExpr = 0;
  133234. WhereLoop *pLoop = pLevel->pWLoop;
  133235. int iCur;
  133236. WhereClause *pWC;
  133237. WhereTerm *pTerm;
  133238. int i, j;
  133239. struct CCurHint sHint;
  133240. Walker sWalker;
  133241. if( OptimizationDisabled(db, SQLITE_CursorHints) ) return;
  133242. iCur = pLevel->iTabCur;
  133243. assert( iCur==pWInfo->pTabList->a[pLevel->iFrom].iCursor );
  133244. sHint.iTabCur = iCur;
  133245. sHint.iIdxCur = pLevel->iIdxCur;
  133246. sHint.pIdx = pLoop->u.btree.pIndex;
  133247. memset(&sWalker, 0, sizeof(sWalker));
  133248. sWalker.pParse = pParse;
  133249. sWalker.u.pCCurHint = &sHint;
  133250. pWC = &pWInfo->sWC;
  133251. for(i=0; i<pWC->nTerm; i++){
  133252. pTerm = &pWC->a[i];
  133253. if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
  133254. if( pTerm->prereqAll & pLevel->notReady ) continue;
  133255. /* Any terms specified as part of the ON(...) clause for any LEFT
  133256. ** JOIN for which the current table is not the rhs are omitted
  133257. ** from the cursor-hint.
  133258. **
  133259. ** If this table is the rhs of a LEFT JOIN, "IS" or "IS NULL" terms
  133260. ** that were specified as part of the WHERE clause must be excluded.
  133261. ** This is to address the following:
  133262. **
  133263. ** SELECT ... t1 LEFT JOIN t2 ON (t1.a=t2.b) WHERE t2.c IS NULL;
  133264. **
  133265. ** Say there is a single row in t2 that matches (t1.a=t2.b), but its
  133266. ** t2.c values is not NULL. If the (t2.c IS NULL) constraint is
  133267. ** pushed down to the cursor, this row is filtered out, causing
  133268. ** SQLite to synthesize a row of NULL values. Which does match the
  133269. ** WHERE clause, and so the query returns a row. Which is incorrect.
  133270. **
  133271. ** For the same reason, WHERE terms such as:
  133272. **
  133273. ** WHERE 1 = (t2.c IS NULL)
  133274. **
  133275. ** are also excluded. See codeCursorHintIsOrFunction() for details.
  133276. */
  133277. if( pTabItem->fg.jointype & JT_LEFT ){
  133278. Expr *pExpr = pTerm->pExpr;
  133279. if( !ExprHasProperty(pExpr, EP_FromJoin)
  133280. || pExpr->iRightJoinTable!=pTabItem->iCursor
  133281. ){
  133282. sWalker.eCode = 0;
  133283. sWalker.xExprCallback = codeCursorHintIsOrFunction;
  133284. sqlite3WalkExpr(&sWalker, pTerm->pExpr);
  133285. if( sWalker.eCode ) continue;
  133286. }
  133287. }else{
  133288. if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) continue;
  133289. }
  133290. /* All terms in pWLoop->aLTerm[] except pEndRange are used to initialize
  133291. ** the cursor. These terms are not needed as hints for a pure range
  133292. ** scan (that has no == terms) so omit them. */
  133293. if( pLoop->u.btree.nEq==0 && pTerm!=pEndRange ){
  133294. for(j=0; j<pLoop->nLTerm && pLoop->aLTerm[j]!=pTerm; j++){}
  133295. if( j<pLoop->nLTerm ) continue;
  133296. }
  133297. /* No subqueries or non-deterministic functions allowed */
  133298. if( sqlite3ExprContainsSubquery(pTerm->pExpr) ) continue;
  133299. /* For an index scan, make sure referenced columns are actually in
  133300. ** the index. */
  133301. if( sHint.pIdx!=0 ){
  133302. sWalker.eCode = 0;
  133303. sWalker.xExprCallback = codeCursorHintCheckExpr;
  133304. sqlite3WalkExpr(&sWalker, pTerm->pExpr);
  133305. if( sWalker.eCode ) continue;
  133306. }
  133307. /* If we survive all prior tests, that means this term is worth hinting */
  133308. pExpr = sqlite3ExprAnd(pParse, pExpr, sqlite3ExprDup(db, pTerm->pExpr, 0));
  133309. }
  133310. if( pExpr!=0 ){
  133311. sWalker.xExprCallback = codeCursorHintFixExpr;
  133312. sqlite3WalkExpr(&sWalker, pExpr);
  133313. sqlite3VdbeAddOp4(v, OP_CursorHint,
  133314. (sHint.pIdx ? sHint.iIdxCur : sHint.iTabCur), 0, 0,
  133315. (const char*)pExpr, P4_EXPR);
  133316. }
  133317. }
  133318. #else
  133319. # define codeCursorHint(A,B,C,D) /* No-op */
  133320. #endif /* SQLITE_ENABLE_CURSOR_HINTS */
  133321. /*
  133322. ** Cursor iCur is open on an intkey b-tree (a table). Register iRowid contains
  133323. ** a rowid value just read from cursor iIdxCur, open on index pIdx. This
  133324. ** function generates code to do a deferred seek of cursor iCur to the
  133325. ** rowid stored in register iRowid.
  133326. **
  133327. ** Normally, this is just:
  133328. **
  133329. ** OP_DeferredSeek $iCur $iRowid
  133330. **
  133331. ** However, if the scan currently being coded is a branch of an OR-loop and
  133332. ** the statement currently being coded is a SELECT, then P3 of OP_DeferredSeek
  133333. ** is set to iIdxCur and P4 is set to point to an array of integers
  133334. ** containing one entry for each column of the table cursor iCur is open
  133335. ** on. For each table column, if the column is the i'th column of the
  133336. ** index, then the corresponding array entry is set to (i+1). If the column
  133337. ** does not appear in the index at all, the array entry is set to 0.
  133338. */
  133339. static void codeDeferredSeek(
  133340. WhereInfo *pWInfo, /* Where clause context */
  133341. Index *pIdx, /* Index scan is using */
  133342. int iCur, /* Cursor for IPK b-tree */
  133343. int iIdxCur /* Index cursor */
  133344. ){
  133345. Parse *pParse = pWInfo->pParse; /* Parse context */
  133346. Vdbe *v = pParse->pVdbe; /* Vdbe to generate code within */
  133347. assert( iIdxCur>0 );
  133348. assert( pIdx->aiColumn[pIdx->nColumn-1]==-1 );
  133349. pWInfo->bDeferredSeek = 1;
  133350. sqlite3VdbeAddOp3(v, OP_DeferredSeek, iIdxCur, 0, iCur);
  133351. if( (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)
  133352. && DbMaskAllZero(sqlite3ParseToplevel(pParse)->writeMask)
  133353. ){
  133354. int i;
  133355. Table *pTab = pIdx->pTable;
  133356. int *ai = (int*)sqlite3DbMallocZero(pParse->db, sizeof(int)*(pTab->nCol+1));
  133357. if( ai ){
  133358. ai[0] = pTab->nCol;
  133359. for(i=0; i<pIdx->nColumn-1; i++){
  133360. int x1, x2;
  133361. assert( pIdx->aiColumn[i]<pTab->nCol );
  133362. x1 = pIdx->aiColumn[i];
  133363. x2 = sqlite3TableColumnToStorage(pTab, x1);
  133364. testcase( x1!=x2 );
  133365. if( x1>=0 ) ai[x2+1] = i+1;
  133366. }
  133367. sqlite3VdbeChangeP4(v, -1, (char*)ai, P4_INTARRAY);
  133368. }
  133369. }
  133370. }
  133371. /*
  133372. ** If the expression passed as the second argument is a vector, generate
  133373. ** code to write the first nReg elements of the vector into an array
  133374. ** of registers starting with iReg.
  133375. **
  133376. ** If the expression is not a vector, then nReg must be passed 1. In
  133377. ** this case, generate code to evaluate the expression and leave the
  133378. ** result in register iReg.
  133379. */
  133380. static void codeExprOrVector(Parse *pParse, Expr *p, int iReg, int nReg){
  133381. assert( nReg>0 );
  133382. if( p && sqlite3ExprIsVector(p) ){
  133383. #ifndef SQLITE_OMIT_SUBQUERY
  133384. if( (p->flags & EP_xIsSelect) ){
  133385. Vdbe *v = pParse->pVdbe;
  133386. int iSelect;
  133387. assert( p->op==TK_SELECT );
  133388. iSelect = sqlite3CodeSubselect(pParse, p);
  133389. sqlite3VdbeAddOp3(v, OP_Copy, iSelect, iReg, nReg-1);
  133390. }else
  133391. #endif
  133392. {
  133393. int i;
  133394. ExprList *pList = p->x.pList;
  133395. assert( nReg<=pList->nExpr );
  133396. for(i=0; i<nReg; i++){
  133397. sqlite3ExprCode(pParse, pList->a[i].pExpr, iReg+i);
  133398. }
  133399. }
  133400. }else{
  133401. assert( nReg==1 );
  133402. sqlite3ExprCode(pParse, p, iReg);
  133403. }
  133404. }
  133405. /* An instance of the IdxExprTrans object carries information about a
  133406. ** mapping from an expression on table columns into a column in an index
  133407. ** down through the Walker.
  133408. */
  133409. typedef struct IdxExprTrans {
  133410. Expr *pIdxExpr; /* The index expression */
  133411. int iTabCur; /* The cursor of the corresponding table */
  133412. int iIdxCur; /* The cursor for the index */
  133413. int iIdxCol; /* The column for the index */
  133414. int iTabCol; /* The column for the table */
  133415. WhereInfo *pWInfo; /* Complete WHERE clause information */
  133416. sqlite3 *db; /* Database connection (for malloc()) */
  133417. } IdxExprTrans;
  133418. /*
  133419. ** Preserve pExpr on the WhereETrans list of the WhereInfo.
  133420. */
  133421. static void preserveExpr(IdxExprTrans *pTrans, Expr *pExpr){
  133422. WhereExprMod *pNew;
  133423. pNew = sqlite3DbMallocRaw(pTrans->db, sizeof(*pNew));
  133424. if( pNew==0 ) return;
  133425. pNew->pNext = pTrans->pWInfo->pExprMods;
  133426. pTrans->pWInfo->pExprMods = pNew;
  133427. pNew->pExpr = pExpr;
  133428. memcpy(&pNew->orig, pExpr, sizeof(*pExpr));
  133429. }
  133430. /* The walker node callback used to transform matching expressions into
  133431. ** a reference to an index column for an index on an expression.
  133432. **
  133433. ** If pExpr matches, then transform it into a reference to the index column
  133434. ** that contains the value of pExpr.
  133435. */
  133436. static int whereIndexExprTransNode(Walker *p, Expr *pExpr){
  133437. IdxExprTrans *pX = p->u.pIdxTrans;
  133438. if( sqlite3ExprCompare(0, pExpr, pX->pIdxExpr, pX->iTabCur)==0 ){
  133439. preserveExpr(pX, pExpr);
  133440. pExpr->affExpr = sqlite3ExprAffinity(pExpr);
  133441. pExpr->op = TK_COLUMN;
  133442. pExpr->iTable = pX->iIdxCur;
  133443. pExpr->iColumn = pX->iIdxCol;
  133444. pExpr->y.pTab = 0;
  133445. testcase( ExprHasProperty(pExpr, EP_Skip) );
  133446. testcase( ExprHasProperty(pExpr, EP_Unlikely) );
  133447. ExprClearProperty(pExpr, EP_Skip|EP_Unlikely);
  133448. return WRC_Prune;
  133449. }else{
  133450. return WRC_Continue;
  133451. }
  133452. }
  133453. #ifndef SQLITE_OMIT_GENERATED_COLUMNS
  133454. /* A walker node callback that translates a column reference to a table
  133455. ** into a corresponding column reference of an index.
  133456. */
  133457. static int whereIndexExprTransColumn(Walker *p, Expr *pExpr){
  133458. if( pExpr->op==TK_COLUMN ){
  133459. IdxExprTrans *pX = p->u.pIdxTrans;
  133460. if( pExpr->iTable==pX->iTabCur && pExpr->iColumn==pX->iTabCol ){
  133461. assert( pExpr->y.pTab!=0 );
  133462. preserveExpr(pX, pExpr);
  133463. pExpr->affExpr = sqlite3TableColumnAffinity(pExpr->y.pTab,pExpr->iColumn);
  133464. pExpr->iTable = pX->iIdxCur;
  133465. pExpr->iColumn = pX->iIdxCol;
  133466. pExpr->y.pTab = 0;
  133467. }
  133468. }
  133469. return WRC_Continue;
  133470. }
  133471. #endif /* SQLITE_OMIT_GENERATED_COLUMNS */
  133472. /*
  133473. ** For an indexes on expression X, locate every instance of expression X
  133474. ** in pExpr and change that subexpression into a reference to the appropriate
  133475. ** column of the index.
  133476. **
  133477. ** 2019-10-24: Updated to also translate references to a VIRTUAL column in
  133478. ** the table into references to the corresponding (stored) column of the
  133479. ** index.
  133480. */
  133481. static void whereIndexExprTrans(
  133482. Index *pIdx, /* The Index */
  133483. int iTabCur, /* Cursor of the table that is being indexed */
  133484. int iIdxCur, /* Cursor of the index itself */
  133485. WhereInfo *pWInfo /* Transform expressions in this WHERE clause */
  133486. ){
  133487. int iIdxCol; /* Column number of the index */
  133488. ExprList *aColExpr; /* Expressions that are indexed */
  133489. Table *pTab;
  133490. Walker w;
  133491. IdxExprTrans x;
  133492. aColExpr = pIdx->aColExpr;
  133493. if( aColExpr==0 && !pIdx->bHasVCol ){
  133494. /* The index does not reference any expressions or virtual columns
  133495. ** so no translations are needed. */
  133496. return;
  133497. }
  133498. pTab = pIdx->pTable;
  133499. memset(&w, 0, sizeof(w));
  133500. w.u.pIdxTrans = &x;
  133501. x.iTabCur = iTabCur;
  133502. x.iIdxCur = iIdxCur;
  133503. x.pWInfo = pWInfo;
  133504. x.db = pWInfo->pParse->db;
  133505. for(iIdxCol=0; iIdxCol<pIdx->nColumn; iIdxCol++){
  133506. i16 iRef = pIdx->aiColumn[iIdxCol];
  133507. if( iRef==XN_EXPR ){
  133508. assert( aColExpr->a[iIdxCol].pExpr!=0 );
  133509. x.pIdxExpr = aColExpr->a[iIdxCol].pExpr;
  133510. if( sqlite3ExprIsConstant(x.pIdxExpr) ) continue;
  133511. w.xExprCallback = whereIndexExprTransNode;
  133512. #ifndef SQLITE_OMIT_GENERATED_COLUMNS
  133513. }else if( iRef>=0
  133514. && (pTab->aCol[iRef].colFlags & COLFLAG_VIRTUAL)!=0
  133515. && (pTab->aCol[iRef].zColl==0
  133516. || sqlite3StrICmp(pTab->aCol[iRef].zColl, sqlite3StrBINARY)==0)
  133517. ){
  133518. /* Check to see if there are direct references to generated columns
  133519. ** that are contained in the index. Pulling the generated column
  133520. ** out of the index is an optimization only - the main table is always
  133521. ** available if the index cannot be used. To avoid unnecessary
  133522. ** complication, omit this optimization if the collating sequence for
  133523. ** the column is non-standard */
  133524. x.iTabCol = iRef;
  133525. w.xExprCallback = whereIndexExprTransColumn;
  133526. #endif /* SQLITE_OMIT_GENERATED_COLUMNS */
  133527. }else{
  133528. continue;
  133529. }
  133530. x.iIdxCol = iIdxCol;
  133531. sqlite3WalkExpr(&w, pWInfo->pWhere);
  133532. sqlite3WalkExprList(&w, pWInfo->pOrderBy);
  133533. sqlite3WalkExprList(&w, pWInfo->pResultSet);
  133534. }
  133535. }
  133536. /*
  133537. ** The pTruth expression is always true because it is the WHERE clause
  133538. ** a partial index that is driving a query loop. Look through all of the
  133539. ** WHERE clause terms on the query, and if any of those terms must be
  133540. ** true because pTruth is true, then mark those WHERE clause terms as
  133541. ** coded.
  133542. */
  133543. static void whereApplyPartialIndexConstraints(
  133544. Expr *pTruth,
  133545. int iTabCur,
  133546. WhereClause *pWC
  133547. ){
  133548. int i;
  133549. WhereTerm *pTerm;
  133550. while( pTruth->op==TK_AND ){
  133551. whereApplyPartialIndexConstraints(pTruth->pLeft, iTabCur, pWC);
  133552. pTruth = pTruth->pRight;
  133553. }
  133554. for(i=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
  133555. Expr *pExpr;
  133556. if( pTerm->wtFlags & TERM_CODED ) continue;
  133557. pExpr = pTerm->pExpr;
  133558. if( sqlite3ExprCompare(0, pExpr, pTruth, iTabCur)==0 ){
  133559. pTerm->wtFlags |= TERM_CODED;
  133560. }
  133561. }
  133562. }
  133563. /*
  133564. ** Generate code for the start of the iLevel-th loop in the WHERE clause
  133565. ** implementation described by pWInfo.
  133566. */
  133567. SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
  133568. Parse *pParse, /* Parsing context */
  133569. Vdbe *v, /* Prepared statement under construction */
  133570. WhereInfo *pWInfo, /* Complete information about the WHERE clause */
  133571. int iLevel, /* Which level of pWInfo->a[] should be coded */
  133572. WhereLevel *pLevel, /* The current level pointer */
  133573. Bitmask notReady /* Which tables are currently available */
  133574. ){
  133575. int j, k; /* Loop counters */
  133576. int iCur; /* The VDBE cursor for the table */
  133577. int addrNxt; /* Where to jump to continue with the next IN case */
  133578. int bRev; /* True if we need to scan in reverse order */
  133579. WhereLoop *pLoop; /* The WhereLoop object being coded */
  133580. WhereClause *pWC; /* Decomposition of the entire WHERE clause */
  133581. WhereTerm *pTerm; /* A WHERE clause term */
  133582. sqlite3 *db; /* Database connection */
  133583. struct SrcList_item *pTabItem; /* FROM clause term being coded */
  133584. int addrBrk; /* Jump here to break out of the loop */
  133585. int addrHalt; /* addrBrk for the outermost loop */
  133586. int addrCont; /* Jump here to continue with next cycle */
  133587. int iRowidReg = 0; /* Rowid is stored in this register, if not zero */
  133588. int iReleaseReg = 0; /* Temp register to free before returning */
  133589. Index *pIdx = 0; /* Index used by loop (if any) */
  133590. int iLoop; /* Iteration of constraint generator loop */
  133591. pWC = &pWInfo->sWC;
  133592. db = pParse->db;
  133593. pLoop = pLevel->pWLoop;
  133594. pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
  133595. iCur = pTabItem->iCursor;
  133596. pLevel->notReady = notReady & ~sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur);
  133597. bRev = (pWInfo->revMask>>iLevel)&1;
  133598. VdbeModuleComment((v, "Begin WHERE-loop%d: %s",iLevel,pTabItem->pTab->zName));
  133599. #if WHERETRACE_ENABLED /* 0x20800 */
  133600. if( sqlite3WhereTrace & 0x800 ){
  133601. sqlite3DebugPrintf("Coding level %d of %d: notReady=%llx iFrom=%d\n",
  133602. iLevel, pWInfo->nLevel, (u64)notReady, pLevel->iFrom);
  133603. sqlite3WhereLoopPrint(pLoop, pWC);
  133604. }
  133605. if( sqlite3WhereTrace & 0x20000 ){
  133606. if( iLevel==0 ){
  133607. sqlite3DebugPrintf("WHERE clause being coded:\n");
  133608. sqlite3TreeViewExpr(0, pWInfo->pWhere, 0);
  133609. }
  133610. sqlite3DebugPrintf("All WHERE-clause terms before coding:\n");
  133611. sqlite3WhereClausePrint(pWC);
  133612. }
  133613. #endif
  133614. /* Create labels for the "break" and "continue" instructions
  133615. ** for the current loop. Jump to addrBrk to break out of a loop.
  133616. ** Jump to cont to go immediately to the next iteration of the
  133617. ** loop.
  133618. **
  133619. ** When there is an IN operator, we also have a "addrNxt" label that
  133620. ** means to continue with the next IN value combination. When
  133621. ** there are no IN operators in the constraints, the "addrNxt" label
  133622. ** is the same as "addrBrk".
  133623. */
  133624. addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(pParse);
  133625. addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(pParse);
  133626. /* If this is the right table of a LEFT OUTER JOIN, allocate and
  133627. ** initialize a memory cell that records if this table matches any
  133628. ** row of the left table of the join.
  133629. */
  133630. assert( (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)
  133631. || pLevel->iFrom>0 || (pTabItem[0].fg.jointype & JT_LEFT)==0
  133632. );
  133633. if( pLevel->iFrom>0 && (pTabItem[0].fg.jointype & JT_LEFT)!=0 ){
  133634. pLevel->iLeftJoin = ++pParse->nMem;
  133635. sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
  133636. VdbeComment((v, "init LEFT JOIN no-match flag"));
  133637. }
  133638. /* Compute a safe address to jump to if we discover that the table for
  133639. ** this loop is empty and can never contribute content. */
  133640. for(j=iLevel; j>0 && pWInfo->a[j].iLeftJoin==0; j--){}
  133641. addrHalt = pWInfo->a[j].addrBrk;
  133642. /* Special case of a FROM clause subquery implemented as a co-routine */
  133643. if( pTabItem->fg.viaCoroutine ){
  133644. int regYield = pTabItem->regReturn;
  133645. sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub);
  133646. pLevel->p2 = sqlite3VdbeAddOp2(v, OP_Yield, regYield, addrBrk);
  133647. VdbeCoverage(v);
  133648. VdbeComment((v, "next row of %s", pTabItem->pTab->zName));
  133649. pLevel->op = OP_Goto;
  133650. }else
  133651. #ifndef SQLITE_OMIT_VIRTUALTABLE
  133652. if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
  133653. /* Case 1: The table is a virtual-table. Use the VFilter and VNext
  133654. ** to access the data.
  133655. */
  133656. int iReg; /* P3 Value for OP_VFilter */
  133657. int addrNotFound;
  133658. int nConstraint = pLoop->nLTerm;
  133659. int iIn; /* Counter for IN constraints */
  133660. iReg = sqlite3GetTempRange(pParse, nConstraint+2);
  133661. addrNotFound = pLevel->addrBrk;
  133662. for(j=0; j<nConstraint; j++){
  133663. int iTarget = iReg+j+2;
  133664. pTerm = pLoop->aLTerm[j];
  133665. if( NEVER(pTerm==0) ) continue;
  133666. if( pTerm->eOperator & WO_IN ){
  133667. codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, iTarget);
  133668. addrNotFound = pLevel->addrNxt;
  133669. }else{
  133670. Expr *pRight = pTerm->pExpr->pRight;
  133671. codeExprOrVector(pParse, pRight, iTarget, 1);
  133672. }
  133673. }
  133674. sqlite3VdbeAddOp2(v, OP_Integer, pLoop->u.vtab.idxNum, iReg);
  133675. sqlite3VdbeAddOp2(v, OP_Integer, nConstraint, iReg+1);
  133676. sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg,
  133677. pLoop->u.vtab.idxStr,
  133678. pLoop->u.vtab.needFree ? P4_DYNAMIC : P4_STATIC);
  133679. VdbeCoverage(v);
  133680. pLoop->u.vtab.needFree = 0;
  133681. pLevel->p1 = iCur;
  133682. pLevel->op = pWInfo->eOnePass ? OP_Noop : OP_VNext;
  133683. pLevel->p2 = sqlite3VdbeCurrentAddr(v);
  133684. iIn = pLevel->u.in.nIn;
  133685. for(j=nConstraint-1; j>=0; j--){
  133686. pTerm = pLoop->aLTerm[j];
  133687. if( (pTerm->eOperator & WO_IN)!=0 ) iIn--;
  133688. if( j<16 && (pLoop->u.vtab.omitMask>>j)&1 ){
  133689. disableTerm(pLevel, pTerm);
  133690. }else if( (pTerm->eOperator & WO_IN)!=0
  133691. && sqlite3ExprVectorSize(pTerm->pExpr->pLeft)==1
  133692. ){
  133693. Expr *pCompare; /* The comparison operator */
  133694. Expr *pRight; /* RHS of the comparison */
  133695. VdbeOp *pOp; /* Opcode to access the value of the IN constraint */
  133696. /* Reload the constraint value into reg[iReg+j+2]. The same value
  133697. ** was loaded into the same register prior to the OP_VFilter, but
  133698. ** the xFilter implementation might have changed the datatype or
  133699. ** encoding of the value in the register, so it *must* be reloaded. */
  133700. assert( pLevel->u.in.aInLoop!=0 || db->mallocFailed );
  133701. if( !db->mallocFailed ){
  133702. assert( iIn>=0 && iIn<pLevel->u.in.nIn );
  133703. pOp = sqlite3VdbeGetOp(v, pLevel->u.in.aInLoop[iIn].addrInTop);
  133704. assert( pOp->opcode==OP_Column || pOp->opcode==OP_Rowid );
  133705. assert( pOp->opcode!=OP_Column || pOp->p3==iReg+j+2 );
  133706. assert( pOp->opcode!=OP_Rowid || pOp->p2==iReg+j+2 );
  133707. testcase( pOp->opcode==OP_Rowid );
  133708. sqlite3VdbeAddOp3(v, pOp->opcode, pOp->p1, pOp->p2, pOp->p3);
  133709. }
  133710. /* Generate code that will continue to the next row if
  133711. ** the IN constraint is not satisfied */
  133712. pCompare = sqlite3PExpr(pParse, TK_EQ, 0, 0);
  133713. assert( pCompare!=0 || db->mallocFailed );
  133714. if( pCompare ){
  133715. pCompare->pLeft = pTerm->pExpr->pLeft;
  133716. pCompare->pRight = pRight = sqlite3Expr(db, TK_REGISTER, 0);
  133717. if( pRight ){
  133718. pRight->iTable = iReg+j+2;
  133719. sqlite3ExprIfFalse(
  133720. pParse, pCompare, pLevel->addrCont, SQLITE_JUMPIFNULL
  133721. );
  133722. }
  133723. pCompare->pLeft = 0;
  133724. sqlite3ExprDelete(db, pCompare);
  133725. }
  133726. }
  133727. }
  133728. assert( iIn==0 || db->mallocFailed );
  133729. /* These registers need to be preserved in case there is an IN operator
  133730. ** loop. So we could deallocate the registers here (and potentially
  133731. ** reuse them later) if (pLoop->wsFlags & WHERE_IN_ABLE)==0. But it seems
  133732. ** simpler and safer to simply not reuse the registers.
  133733. **
  133734. ** sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
  133735. */
  133736. }else
  133737. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  133738. if( (pLoop->wsFlags & WHERE_IPK)!=0
  133739. && (pLoop->wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_EQ))!=0
  133740. ){
  133741. /* Case 2: We can directly reference a single row using an
  133742. ** equality comparison against the ROWID field. Or
  133743. ** we reference multiple rows using a "rowid IN (...)"
  133744. ** construct.
  133745. */
  133746. assert( pLoop->u.btree.nEq==1 );
  133747. pTerm = pLoop->aLTerm[0];
  133748. assert( pTerm!=0 );
  133749. assert( pTerm->pExpr!=0 );
  133750. testcase( pTerm->wtFlags & TERM_VIRTUAL );
  133751. iReleaseReg = ++pParse->nMem;
  133752. iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, bRev, iReleaseReg);
  133753. if( iRowidReg!=iReleaseReg ) sqlite3ReleaseTempReg(pParse, iReleaseReg);
  133754. addrNxt = pLevel->addrNxt;
  133755. sqlite3VdbeAddOp3(v, OP_SeekRowid, iCur, addrNxt, iRowidReg);
  133756. VdbeCoverage(v);
  133757. pLevel->op = OP_Noop;
  133758. if( (pTerm->prereqAll & pLevel->notReady)==0 ){
  133759. pTerm->wtFlags |= TERM_CODED;
  133760. }
  133761. }else if( (pLoop->wsFlags & WHERE_IPK)!=0
  133762. && (pLoop->wsFlags & WHERE_COLUMN_RANGE)!=0
  133763. ){
  133764. /* Case 3: We have an inequality comparison against the ROWID field.
  133765. */
  133766. int testOp = OP_Noop;
  133767. int start;
  133768. int memEndValue = 0;
  133769. WhereTerm *pStart, *pEnd;
  133770. j = 0;
  133771. pStart = pEnd = 0;
  133772. if( pLoop->wsFlags & WHERE_BTM_LIMIT ) pStart = pLoop->aLTerm[j++];
  133773. if( pLoop->wsFlags & WHERE_TOP_LIMIT ) pEnd = pLoop->aLTerm[j++];
  133774. assert( pStart!=0 || pEnd!=0 );
  133775. if( bRev ){
  133776. pTerm = pStart;
  133777. pStart = pEnd;
  133778. pEnd = pTerm;
  133779. }
  133780. codeCursorHint(pTabItem, pWInfo, pLevel, pEnd);
  133781. if( pStart ){
  133782. Expr *pX; /* The expression that defines the start bound */
  133783. int r1, rTemp; /* Registers for holding the start boundary */
  133784. int op; /* Cursor seek operation */
  133785. /* The following constant maps TK_xx codes into corresponding
  133786. ** seek opcodes. It depends on a particular ordering of TK_xx
  133787. */
  133788. const u8 aMoveOp[] = {
  133789. /* TK_GT */ OP_SeekGT,
  133790. /* TK_LE */ OP_SeekLE,
  133791. /* TK_LT */ OP_SeekLT,
  133792. /* TK_GE */ OP_SeekGE
  133793. };
  133794. assert( TK_LE==TK_GT+1 ); /* Make sure the ordering.. */
  133795. assert( TK_LT==TK_GT+2 ); /* ... of the TK_xx values... */
  133796. assert( TK_GE==TK_GT+3 ); /* ... is correcct. */
  133797. assert( (pStart->wtFlags & TERM_VNULL)==0 );
  133798. testcase( pStart->wtFlags & TERM_VIRTUAL );
  133799. pX = pStart->pExpr;
  133800. assert( pX!=0 );
  133801. testcase( pStart->leftCursor!=iCur ); /* transitive constraints */
  133802. if( sqlite3ExprIsVector(pX->pRight) ){
  133803. r1 = rTemp = sqlite3GetTempReg(pParse);
  133804. codeExprOrVector(pParse, pX->pRight, r1, 1);
  133805. testcase( pX->op==TK_GT );
  133806. testcase( pX->op==TK_GE );
  133807. testcase( pX->op==TK_LT );
  133808. testcase( pX->op==TK_LE );
  133809. op = aMoveOp[((pX->op - TK_GT - 1) & 0x3) | 0x1];
  133810. assert( pX->op!=TK_GT || op==OP_SeekGE );
  133811. assert( pX->op!=TK_GE || op==OP_SeekGE );
  133812. assert( pX->op!=TK_LT || op==OP_SeekLE );
  133813. assert( pX->op!=TK_LE || op==OP_SeekLE );
  133814. }else{
  133815. r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
  133816. disableTerm(pLevel, pStart);
  133817. op = aMoveOp[(pX->op - TK_GT)];
  133818. }
  133819. sqlite3VdbeAddOp3(v, op, iCur, addrBrk, r1);
  133820. VdbeComment((v, "pk"));
  133821. VdbeCoverageIf(v, pX->op==TK_GT);
  133822. VdbeCoverageIf(v, pX->op==TK_LE);
  133823. VdbeCoverageIf(v, pX->op==TK_LT);
  133824. VdbeCoverageIf(v, pX->op==TK_GE);
  133825. sqlite3ReleaseTempReg(pParse, rTemp);
  133826. }else{
  133827. sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrHalt);
  133828. VdbeCoverageIf(v, bRev==0);
  133829. VdbeCoverageIf(v, bRev!=0);
  133830. }
  133831. if( pEnd ){
  133832. Expr *pX;
  133833. pX = pEnd->pExpr;
  133834. assert( pX!=0 );
  133835. assert( (pEnd->wtFlags & TERM_VNULL)==0 );
  133836. testcase( pEnd->leftCursor!=iCur ); /* Transitive constraints */
  133837. testcase( pEnd->wtFlags & TERM_VIRTUAL );
  133838. memEndValue = ++pParse->nMem;
  133839. codeExprOrVector(pParse, pX->pRight, memEndValue, 1);
  133840. if( 0==sqlite3ExprIsVector(pX->pRight)
  133841. && (pX->op==TK_LT || pX->op==TK_GT)
  133842. ){
  133843. testOp = bRev ? OP_Le : OP_Ge;
  133844. }else{
  133845. testOp = bRev ? OP_Lt : OP_Gt;
  133846. }
  133847. if( 0==sqlite3ExprIsVector(pX->pRight) ){
  133848. disableTerm(pLevel, pEnd);
  133849. }
  133850. }
  133851. start = sqlite3VdbeCurrentAddr(v);
  133852. pLevel->op = bRev ? OP_Prev : OP_Next;
  133853. pLevel->p1 = iCur;
  133854. pLevel->p2 = start;
  133855. assert( pLevel->p5==0 );
  133856. if( testOp!=OP_Noop ){
  133857. iRowidReg = ++pParse->nMem;
  133858. sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
  133859. sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
  133860. VdbeCoverageIf(v, testOp==OP_Le);
  133861. VdbeCoverageIf(v, testOp==OP_Lt);
  133862. VdbeCoverageIf(v, testOp==OP_Ge);
  133863. VdbeCoverageIf(v, testOp==OP_Gt);
  133864. sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
  133865. }
  133866. }else if( pLoop->wsFlags & WHERE_INDEXED ){
  133867. /* Case 4: A scan using an index.
  133868. **
  133869. ** The WHERE clause may contain zero or more equality
  133870. ** terms ("==" or "IN" operators) that refer to the N
  133871. ** left-most columns of the index. It may also contain
  133872. ** inequality constraints (>, <, >= or <=) on the indexed
  133873. ** column that immediately follows the N equalities. Only
  133874. ** the right-most column can be an inequality - the rest must
  133875. ** use the "==" and "IN" operators. For example, if the
  133876. ** index is on (x,y,z), then the following clauses are all
  133877. ** optimized:
  133878. **
  133879. ** x=5
  133880. ** x=5 AND y=10
  133881. ** x=5 AND y<10
  133882. ** x=5 AND y>5 AND y<10
  133883. ** x=5 AND y=5 AND z<=10
  133884. **
  133885. ** The z<10 term of the following cannot be used, only
  133886. ** the x=5 term:
  133887. **
  133888. ** x=5 AND z<10
  133889. **
  133890. ** N may be zero if there are inequality constraints.
  133891. ** If there are no inequality constraints, then N is at
  133892. ** least one.
  133893. **
  133894. ** This case is also used when there are no WHERE clause
  133895. ** constraints but an index is selected anyway, in order
  133896. ** to force the output order to conform to an ORDER BY.
  133897. */
  133898. static const u8 aStartOp[] = {
  133899. 0,
  133900. 0,
  133901. OP_Rewind, /* 2: (!start_constraints && startEq && !bRev) */
  133902. OP_Last, /* 3: (!start_constraints && startEq && bRev) */
  133903. OP_SeekGT, /* 4: (start_constraints && !startEq && !bRev) */
  133904. OP_SeekLT, /* 5: (start_constraints && !startEq && bRev) */
  133905. OP_SeekGE, /* 6: (start_constraints && startEq && !bRev) */
  133906. OP_SeekLE /* 7: (start_constraints && startEq && bRev) */
  133907. };
  133908. static const u8 aEndOp[] = {
  133909. OP_IdxGE, /* 0: (end_constraints && !bRev && !endEq) */
  133910. OP_IdxGT, /* 1: (end_constraints && !bRev && endEq) */
  133911. OP_IdxLE, /* 2: (end_constraints && bRev && !endEq) */
  133912. OP_IdxLT, /* 3: (end_constraints && bRev && endEq) */
  133913. };
  133914. u16 nEq = pLoop->u.btree.nEq; /* Number of == or IN terms */
  133915. u16 nBtm = pLoop->u.btree.nBtm; /* Length of BTM vector */
  133916. u16 nTop = pLoop->u.btree.nTop; /* Length of TOP vector */
  133917. int regBase; /* Base register holding constraint values */
  133918. WhereTerm *pRangeStart = 0; /* Inequality constraint at range start */
  133919. WhereTerm *pRangeEnd = 0; /* Inequality constraint at range end */
  133920. int startEq; /* True if range start uses ==, >= or <= */
  133921. int endEq; /* True if range end uses ==, >= or <= */
  133922. int start_constraints; /* Start of range is constrained */
  133923. int nConstraint; /* Number of constraint terms */
  133924. int iIdxCur; /* The VDBE cursor for the index */
  133925. int nExtraReg = 0; /* Number of extra registers needed */
  133926. int op; /* Instruction opcode */
  133927. char *zStartAff; /* Affinity for start of range constraint */
  133928. char *zEndAff = 0; /* Affinity for end of range constraint */
  133929. u8 bSeekPastNull = 0; /* True to seek past initial nulls */
  133930. u8 bStopAtNull = 0; /* Add condition to terminate at NULLs */
  133931. int omitTable; /* True if we use the index only */
  133932. int regBignull = 0; /* big-null flag register */
  133933. pIdx = pLoop->u.btree.pIndex;
  133934. iIdxCur = pLevel->iIdxCur;
  133935. assert( nEq>=pLoop->nSkip );
  133936. /* Find any inequality constraint terms for the start and end
  133937. ** of the range.
  133938. */
  133939. j = nEq;
  133940. if( pLoop->wsFlags & WHERE_BTM_LIMIT ){
  133941. pRangeStart = pLoop->aLTerm[j++];
  133942. nExtraReg = MAX(nExtraReg, pLoop->u.btree.nBtm);
  133943. /* Like optimization range constraints always occur in pairs */
  133944. assert( (pRangeStart->wtFlags & TERM_LIKEOPT)==0 ||
  133945. (pLoop->wsFlags & WHERE_TOP_LIMIT)!=0 );
  133946. }
  133947. if( pLoop->wsFlags & WHERE_TOP_LIMIT ){
  133948. pRangeEnd = pLoop->aLTerm[j++];
  133949. nExtraReg = MAX(nExtraReg, pLoop->u.btree.nTop);
  133950. #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
  133951. if( (pRangeEnd->wtFlags & TERM_LIKEOPT)!=0 ){
  133952. assert( pRangeStart!=0 ); /* LIKE opt constraints */
  133953. assert( pRangeStart->wtFlags & TERM_LIKEOPT ); /* occur in pairs */
  133954. pLevel->iLikeRepCntr = (u32)++pParse->nMem;
  133955. sqlite3VdbeAddOp2(v, OP_Integer, 1, (int)pLevel->iLikeRepCntr);
  133956. VdbeComment((v, "LIKE loop counter"));
  133957. pLevel->addrLikeRep = sqlite3VdbeCurrentAddr(v);
  133958. /* iLikeRepCntr actually stores 2x the counter register number. The
  133959. ** bottom bit indicates whether the search order is ASC or DESC. */
  133960. testcase( bRev );
  133961. testcase( pIdx->aSortOrder[nEq]==SQLITE_SO_DESC );
  133962. assert( (bRev & ~1)==0 );
  133963. pLevel->iLikeRepCntr <<=1;
  133964. pLevel->iLikeRepCntr |= bRev ^ (pIdx->aSortOrder[nEq]==SQLITE_SO_DESC);
  133965. }
  133966. #endif
  133967. if( pRangeStart==0 ){
  133968. j = pIdx->aiColumn[nEq];
  133969. if( (j>=0 && pIdx->pTable->aCol[j].notNull==0) || j==XN_EXPR ){
  133970. bSeekPastNull = 1;
  133971. }
  133972. }
  133973. }
  133974. assert( pRangeEnd==0 || (pRangeEnd->wtFlags & TERM_VNULL)==0 );
  133975. /* If the WHERE_BIGNULL_SORT flag is set, then index column nEq uses
  133976. ** a non-default "big-null" sort (either ASC NULLS LAST or DESC NULLS
  133977. ** FIRST). In both cases separate ordered scans are made of those
  133978. ** index entries for which the column is null and for those for which
  133979. ** it is not. For an ASC sort, the non-NULL entries are scanned first.
  133980. ** For DESC, NULL entries are scanned first.
  133981. */
  133982. if( (pLoop->wsFlags & (WHERE_TOP_LIMIT|WHERE_BTM_LIMIT))==0
  133983. && (pLoop->wsFlags & WHERE_BIGNULL_SORT)!=0
  133984. ){
  133985. assert( bSeekPastNull==0 && nExtraReg==0 && nBtm==0 && nTop==0 );
  133986. assert( pRangeEnd==0 && pRangeStart==0 );
  133987. testcase( pLoop->nSkip>0 );
  133988. nExtraReg = 1;
  133989. bSeekPastNull = 1;
  133990. pLevel->regBignull = regBignull = ++pParse->nMem;
  133991. if( pLevel->iLeftJoin ){
  133992. sqlite3VdbeAddOp2(v, OP_Integer, 0, regBignull);
  133993. }
  133994. pLevel->addrBignull = sqlite3VdbeMakeLabel(pParse);
  133995. }
  133996. /* If we are doing a reverse order scan on an ascending index, or
  133997. ** a forward order scan on a descending index, interchange the
  133998. ** start and end terms (pRangeStart and pRangeEnd).
  133999. */
  134000. if( (nEq<pIdx->nKeyCol && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC))
  134001. || (bRev && pIdx->nKeyCol==nEq)
  134002. ){
  134003. SWAP(WhereTerm *, pRangeEnd, pRangeStart);
  134004. SWAP(u8, bSeekPastNull, bStopAtNull);
  134005. SWAP(u8, nBtm, nTop);
  134006. }
  134007. /* Generate code to evaluate all constraint terms using == or IN
  134008. ** and store the values of those terms in an array of registers
  134009. ** starting at regBase.
  134010. */
  134011. codeCursorHint(pTabItem, pWInfo, pLevel, pRangeEnd);
  134012. regBase = codeAllEqualityTerms(pParse,pLevel,bRev,nExtraReg,&zStartAff);
  134013. assert( zStartAff==0 || sqlite3Strlen30(zStartAff)>=nEq );
  134014. if( zStartAff && nTop ){
  134015. zEndAff = sqlite3DbStrDup(db, &zStartAff[nEq]);
  134016. }
  134017. addrNxt = (regBignull ? pLevel->addrBignull : pLevel->addrNxt);
  134018. testcase( pRangeStart && (pRangeStart->eOperator & WO_LE)!=0 );
  134019. testcase( pRangeStart && (pRangeStart->eOperator & WO_GE)!=0 );
  134020. testcase( pRangeEnd && (pRangeEnd->eOperator & WO_LE)!=0 );
  134021. testcase( pRangeEnd && (pRangeEnd->eOperator & WO_GE)!=0 );
  134022. startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
  134023. endEq = !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
  134024. start_constraints = pRangeStart || nEq>0;
  134025. /* Seek the index cursor to the start of the range. */
  134026. nConstraint = nEq;
  134027. if( pRangeStart ){
  134028. Expr *pRight = pRangeStart->pExpr->pRight;
  134029. codeExprOrVector(pParse, pRight, regBase+nEq, nBtm);
  134030. whereLikeOptimizationStringFixup(v, pLevel, pRangeStart);
  134031. if( (pRangeStart->wtFlags & TERM_VNULL)==0
  134032. && sqlite3ExprCanBeNull(pRight)
  134033. ){
  134034. sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
  134035. VdbeCoverage(v);
  134036. }
  134037. if( zStartAff ){
  134038. updateRangeAffinityStr(pRight, nBtm, &zStartAff[nEq]);
  134039. }
  134040. nConstraint += nBtm;
  134041. testcase( pRangeStart->wtFlags & TERM_VIRTUAL );
  134042. if( sqlite3ExprIsVector(pRight)==0 ){
  134043. disableTerm(pLevel, pRangeStart);
  134044. }else{
  134045. startEq = 1;
  134046. }
  134047. bSeekPastNull = 0;
  134048. }else if( bSeekPastNull ){
  134049. startEq = 0;
  134050. sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
  134051. start_constraints = 1;
  134052. nConstraint++;
  134053. }else if( regBignull ){
  134054. sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
  134055. start_constraints = 1;
  134056. nConstraint++;
  134057. }
  134058. codeApplyAffinity(pParse, regBase, nConstraint - bSeekPastNull, zStartAff);
  134059. if( pLoop->nSkip>0 && nConstraint==pLoop->nSkip ){
  134060. /* The skip-scan logic inside the call to codeAllEqualityConstraints()
  134061. ** above has already left the cursor sitting on the correct row,
  134062. ** so no further seeking is needed */
  134063. }else{
  134064. if( pLoop->wsFlags & WHERE_IN_EARLYOUT ){
  134065. sqlite3VdbeAddOp1(v, OP_SeekHit, iIdxCur);
  134066. }
  134067. if( regBignull ){
  134068. sqlite3VdbeAddOp2(v, OP_Integer, 1, regBignull);
  134069. VdbeComment((v, "NULL-scan pass ctr"));
  134070. }
  134071. op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
  134072. assert( op!=0 );
  134073. sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
  134074. VdbeCoverage(v);
  134075. VdbeCoverageIf(v, op==OP_Rewind); testcase( op==OP_Rewind );
  134076. VdbeCoverageIf(v, op==OP_Last); testcase( op==OP_Last );
  134077. VdbeCoverageIf(v, op==OP_SeekGT); testcase( op==OP_SeekGT );
  134078. VdbeCoverageIf(v, op==OP_SeekGE); testcase( op==OP_SeekGE );
  134079. VdbeCoverageIf(v, op==OP_SeekLE); testcase( op==OP_SeekLE );
  134080. VdbeCoverageIf(v, op==OP_SeekLT); testcase( op==OP_SeekLT );
  134081. assert( bSeekPastNull==0 || bStopAtNull==0 );
  134082. if( regBignull ){
  134083. assert( bSeekPastNull==1 || bStopAtNull==1 );
  134084. assert( bSeekPastNull==!bStopAtNull );
  134085. assert( bStopAtNull==startEq );
  134086. sqlite3VdbeAddOp2(v, OP_Goto, 0, sqlite3VdbeCurrentAddr(v)+2);
  134087. op = aStartOp[(nConstraint>1)*4 + 2 + bRev];
  134088. sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase,
  134089. nConstraint-startEq);
  134090. VdbeCoverage(v);
  134091. VdbeCoverageIf(v, op==OP_Rewind); testcase( op==OP_Rewind );
  134092. VdbeCoverageIf(v, op==OP_Last); testcase( op==OP_Last );
  134093. VdbeCoverageIf(v, op==OP_SeekGE); testcase( op==OP_SeekGE );
  134094. VdbeCoverageIf(v, op==OP_SeekLE); testcase( op==OP_SeekLE );
  134095. assert( op==OP_Rewind || op==OP_Last || op==OP_SeekGE || op==OP_SeekLE);
  134096. }
  134097. }
  134098. /* Load the value for the inequality constraint at the end of the
  134099. ** range (if any).
  134100. */
  134101. nConstraint = nEq;
  134102. if( pRangeEnd ){
  134103. Expr *pRight = pRangeEnd->pExpr->pRight;
  134104. codeExprOrVector(pParse, pRight, regBase+nEq, nTop);
  134105. whereLikeOptimizationStringFixup(v, pLevel, pRangeEnd);
  134106. if( (pRangeEnd->wtFlags & TERM_VNULL)==0
  134107. && sqlite3ExprCanBeNull(pRight)
  134108. ){
  134109. sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
  134110. VdbeCoverage(v);
  134111. }
  134112. if( zEndAff ){
  134113. updateRangeAffinityStr(pRight, nTop, zEndAff);
  134114. codeApplyAffinity(pParse, regBase+nEq, nTop, zEndAff);
  134115. }else{
  134116. assert( pParse->db->mallocFailed );
  134117. }
  134118. nConstraint += nTop;
  134119. testcase( pRangeEnd->wtFlags & TERM_VIRTUAL );
  134120. if( sqlite3ExprIsVector(pRight)==0 ){
  134121. disableTerm(pLevel, pRangeEnd);
  134122. }else{
  134123. endEq = 1;
  134124. }
  134125. }else if( bStopAtNull ){
  134126. if( regBignull==0 ){
  134127. sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
  134128. endEq = 0;
  134129. }
  134130. nConstraint++;
  134131. }
  134132. sqlite3DbFree(db, zStartAff);
  134133. sqlite3DbFree(db, zEndAff);
  134134. /* Top of the loop body */
  134135. pLevel->p2 = sqlite3VdbeCurrentAddr(v);
  134136. /* Check if the index cursor is past the end of the range. */
  134137. if( nConstraint ){
  134138. if( regBignull ){
  134139. /* Except, skip the end-of-range check while doing the NULL-scan */
  134140. sqlite3VdbeAddOp2(v, OP_IfNot, regBignull, sqlite3VdbeCurrentAddr(v)+3);
  134141. VdbeComment((v, "If NULL-scan 2nd pass"));
  134142. VdbeCoverage(v);
  134143. }
  134144. op = aEndOp[bRev*2 + endEq];
  134145. sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
  134146. testcase( op==OP_IdxGT ); VdbeCoverageIf(v, op==OP_IdxGT );
  134147. testcase( op==OP_IdxGE ); VdbeCoverageIf(v, op==OP_IdxGE );
  134148. testcase( op==OP_IdxLT ); VdbeCoverageIf(v, op==OP_IdxLT );
  134149. testcase( op==OP_IdxLE ); VdbeCoverageIf(v, op==OP_IdxLE );
  134150. }
  134151. if( regBignull ){
  134152. /* During a NULL-scan, check to see if we have reached the end of
  134153. ** the NULLs */
  134154. assert( bSeekPastNull==!bStopAtNull );
  134155. assert( bSeekPastNull+bStopAtNull==1 );
  134156. assert( nConstraint+bSeekPastNull>0 );
  134157. sqlite3VdbeAddOp2(v, OP_If, regBignull, sqlite3VdbeCurrentAddr(v)+2);
  134158. VdbeComment((v, "If NULL-scan 1st pass"));
  134159. VdbeCoverage(v);
  134160. op = aEndOp[bRev*2 + bSeekPastNull];
  134161. sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase,
  134162. nConstraint+bSeekPastNull);
  134163. testcase( op==OP_IdxGT ); VdbeCoverageIf(v, op==OP_IdxGT );
  134164. testcase( op==OP_IdxGE ); VdbeCoverageIf(v, op==OP_IdxGE );
  134165. testcase( op==OP_IdxLT ); VdbeCoverageIf(v, op==OP_IdxLT );
  134166. testcase( op==OP_IdxLE ); VdbeCoverageIf(v, op==OP_IdxLE );
  134167. }
  134168. if( pLoop->wsFlags & WHERE_IN_EARLYOUT ){
  134169. sqlite3VdbeAddOp2(v, OP_SeekHit, iIdxCur, 1);
  134170. }
  134171. /* Seek the table cursor, if required */
  134172. omitTable = (pLoop->wsFlags & WHERE_IDX_ONLY)!=0
  134173. && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0;
  134174. if( omitTable ){
  134175. /* pIdx is a covering index. No need to access the main table. */
  134176. }else if( HasRowid(pIdx->pTable) ){
  134177. if( (pWInfo->wctrlFlags & WHERE_SEEK_TABLE)
  134178. || ( (pWInfo->wctrlFlags & WHERE_SEEK_UNIQ_TABLE)!=0
  134179. && (pWInfo->eOnePass==ONEPASS_SINGLE || pLoop->nLTerm==0) )
  134180. ){
  134181. iRowidReg = ++pParse->nMem;
  134182. sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
  134183. sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, iRowidReg);
  134184. VdbeCoverage(v);
  134185. }else{
  134186. codeDeferredSeek(pWInfo, pIdx, iCur, iIdxCur);
  134187. }
  134188. }else if( iCur!=iIdxCur ){
  134189. Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
  134190. iRowidReg = sqlite3GetTempRange(pParse, pPk->nKeyCol);
  134191. for(j=0; j<pPk->nKeyCol; j++){
  134192. k = sqlite3TableColumnToIndex(pIdx, pPk->aiColumn[j]);
  134193. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, iRowidReg+j);
  134194. }
  134195. sqlite3VdbeAddOp4Int(v, OP_NotFound, iCur, addrCont,
  134196. iRowidReg, pPk->nKeyCol); VdbeCoverage(v);
  134197. }
  134198. if( pLevel->iLeftJoin==0 ){
  134199. /* If pIdx is an index on one or more expressions, then look through
  134200. ** all the expressions in pWInfo and try to transform matching expressions
  134201. ** into reference to index columns. Also attempt to translate references
  134202. ** to virtual columns in the table into references to (stored) columns
  134203. ** of the index.
  134204. **
  134205. ** Do not do this for the RHS of a LEFT JOIN. This is because the
  134206. ** expression may be evaluated after OP_NullRow has been executed on
  134207. ** the cursor. In this case it is important to do the full evaluation,
  134208. ** as the result of the expression may not be NULL, even if all table
  134209. ** column values are. https://www.sqlite.org/src/info/7fa8049685b50b5a
  134210. **
  134211. ** Also, do not do this when processing one index an a multi-index
  134212. ** OR clause, since the transformation will become invalid once we
  134213. ** move forward to the next index.
  134214. ** https://sqlite.org/src/info/4e8e4857d32d401f
  134215. */
  134216. if( (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0 ){
  134217. whereIndexExprTrans(pIdx, iCur, iIdxCur, pWInfo);
  134218. }
  134219. /* If a partial index is driving the loop, try to eliminate WHERE clause
  134220. ** terms from the query that must be true due to the WHERE clause of
  134221. ** the partial index.
  134222. **
  134223. ** 2019-11-02 ticket 623eff57e76d45f6: This optimization does not work
  134224. ** for a LEFT JOIN.
  134225. */
  134226. if( pIdx->pPartIdxWhere ){
  134227. whereApplyPartialIndexConstraints(pIdx->pPartIdxWhere, iCur, pWC);
  134228. }
  134229. }else{
  134230. testcase( pIdx->pPartIdxWhere );
  134231. /* The following assert() is not a requirement, merely an observation:
  134232. ** The OR-optimization doesn't work for the right hand table of
  134233. ** a LEFT JOIN: */
  134234. assert( (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0 );
  134235. }
  134236. /* Record the instruction used to terminate the loop. */
  134237. if( pLoop->wsFlags & WHERE_ONEROW ){
  134238. pLevel->op = OP_Noop;
  134239. }else if( bRev ){
  134240. pLevel->op = OP_Prev;
  134241. }else{
  134242. pLevel->op = OP_Next;
  134243. }
  134244. pLevel->p1 = iIdxCur;
  134245. pLevel->p3 = (pLoop->wsFlags&WHERE_UNQ_WANTED)!=0 ? 1:0;
  134246. if( (pLoop->wsFlags & WHERE_CONSTRAINT)==0 ){
  134247. pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
  134248. }else{
  134249. assert( pLevel->p5==0 );
  134250. }
  134251. if( omitTable ) pIdx = 0;
  134252. }else
  134253. #ifndef SQLITE_OMIT_OR_OPTIMIZATION
  134254. if( pLoop->wsFlags & WHERE_MULTI_OR ){
  134255. /* Case 5: Two or more separately indexed terms connected by OR
  134256. **
  134257. ** Example:
  134258. **
  134259. ** CREATE TABLE t1(a,b,c,d);
  134260. ** CREATE INDEX i1 ON t1(a);
  134261. ** CREATE INDEX i2 ON t1(b);
  134262. ** CREATE INDEX i3 ON t1(c);
  134263. **
  134264. ** SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
  134265. **
  134266. ** In the example, there are three indexed terms connected by OR.
  134267. ** The top of the loop looks like this:
  134268. **
  134269. ** Null 1 # Zero the rowset in reg 1
  134270. **
  134271. ** Then, for each indexed term, the following. The arguments to
  134272. ** RowSetTest are such that the rowid of the current row is inserted
  134273. ** into the RowSet. If it is already present, control skips the
  134274. ** Gosub opcode and jumps straight to the code generated by WhereEnd().
  134275. **
  134276. ** sqlite3WhereBegin(<term>)
  134277. ** RowSetTest # Insert rowid into rowset
  134278. ** Gosub 2 A
  134279. ** sqlite3WhereEnd()
  134280. **
  134281. ** Following the above, code to terminate the loop. Label A, the target
  134282. ** of the Gosub above, jumps to the instruction right after the Goto.
  134283. **
  134284. ** Null 1 # Zero the rowset in reg 1
  134285. ** Goto B # The loop is finished.
  134286. **
  134287. ** A: <loop body> # Return data, whatever.
  134288. **
  134289. ** Return 2 # Jump back to the Gosub
  134290. **
  134291. ** B: <after the loop>
  134292. **
  134293. ** Added 2014-05-26: If the table is a WITHOUT ROWID table, then
  134294. ** use an ephemeral index instead of a RowSet to record the primary
  134295. ** keys of the rows we have already seen.
  134296. **
  134297. */
  134298. WhereClause *pOrWc; /* The OR-clause broken out into subterms */
  134299. SrcList *pOrTab; /* Shortened table list or OR-clause generation */
  134300. Index *pCov = 0; /* Potential covering index (or NULL) */
  134301. int iCovCur = pParse->nTab++; /* Cursor used for index scans (if any) */
  134302. int regReturn = ++pParse->nMem; /* Register used with OP_Gosub */
  134303. int regRowset = 0; /* Register for RowSet object */
  134304. int regRowid = 0; /* Register holding rowid */
  134305. int iLoopBody = sqlite3VdbeMakeLabel(pParse);/* Start of loop body */
  134306. int iRetInit; /* Address of regReturn init */
  134307. int untestedTerms = 0; /* Some terms not completely tested */
  134308. int ii; /* Loop counter */
  134309. u16 wctrlFlags; /* Flags for sub-WHERE clause */
  134310. Expr *pAndExpr = 0; /* An ".. AND (...)" expression */
  134311. Table *pTab = pTabItem->pTab;
  134312. pTerm = pLoop->aLTerm[0];
  134313. assert( pTerm!=0 );
  134314. assert( pTerm->eOperator & WO_OR );
  134315. assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
  134316. pOrWc = &pTerm->u.pOrInfo->wc;
  134317. pLevel->op = OP_Return;
  134318. pLevel->p1 = regReturn;
  134319. /* Set up a new SrcList in pOrTab containing the table being scanned
  134320. ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
  134321. ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
  134322. */
  134323. if( pWInfo->nLevel>1 ){
  134324. int nNotReady; /* The number of notReady tables */
  134325. struct SrcList_item *origSrc; /* Original list of tables */
  134326. nNotReady = pWInfo->nLevel - iLevel - 1;
  134327. pOrTab = sqlite3StackAllocRaw(db,
  134328. sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
  134329. if( pOrTab==0 ) return notReady;
  134330. pOrTab->nAlloc = (u8)(nNotReady + 1);
  134331. pOrTab->nSrc = pOrTab->nAlloc;
  134332. memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
  134333. origSrc = pWInfo->pTabList->a;
  134334. for(k=1; k<=nNotReady; k++){
  134335. memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
  134336. }
  134337. }else{
  134338. pOrTab = pWInfo->pTabList;
  134339. }
  134340. /* Initialize the rowset register to contain NULL. An SQL NULL is
  134341. ** equivalent to an empty rowset. Or, create an ephemeral index
  134342. ** capable of holding primary keys in the case of a WITHOUT ROWID.
  134343. **
  134344. ** Also initialize regReturn to contain the address of the instruction
  134345. ** immediately following the OP_Return at the bottom of the loop. This
  134346. ** is required in a few obscure LEFT JOIN cases where control jumps
  134347. ** over the top of the loop into the body of it. In this case the
  134348. ** correct response for the end-of-loop code (the OP_Return) is to
  134349. ** fall through to the next instruction, just as an OP_Next does if
  134350. ** called on an uninitialized cursor.
  134351. */
  134352. if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
  134353. if( HasRowid(pTab) ){
  134354. regRowset = ++pParse->nMem;
  134355. sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
  134356. }else{
  134357. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  134358. regRowset = pParse->nTab++;
  134359. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, regRowset, pPk->nKeyCol);
  134360. sqlite3VdbeSetP4KeyInfo(pParse, pPk);
  134361. }
  134362. regRowid = ++pParse->nMem;
  134363. }
  134364. iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
  134365. /* If the original WHERE clause is z of the form: (x1 OR x2 OR ...) AND y
  134366. ** Then for every term xN, evaluate as the subexpression: xN AND z
  134367. ** That way, terms in y that are factored into the disjunction will
  134368. ** be picked up by the recursive calls to sqlite3WhereBegin() below.
  134369. **
  134370. ** Actually, each subexpression is converted to "xN AND w" where w is
  134371. ** the "interesting" terms of z - terms that did not originate in the
  134372. ** ON or USING clause of a LEFT JOIN, and terms that are usable as
  134373. ** indices.
  134374. **
  134375. ** This optimization also only applies if the (x1 OR x2 OR ...) term
  134376. ** is not contained in the ON clause of a LEFT JOIN.
  134377. ** See ticket http://www.sqlite.org/src/info/f2369304e4
  134378. */
  134379. if( pWC->nTerm>1 ){
  134380. int iTerm;
  134381. for(iTerm=0; iTerm<pWC->nTerm; iTerm++){
  134382. Expr *pExpr = pWC->a[iTerm].pExpr;
  134383. if( &pWC->a[iTerm] == pTerm ) continue;
  134384. testcase( pWC->a[iTerm].wtFlags & TERM_VIRTUAL );
  134385. testcase( pWC->a[iTerm].wtFlags & TERM_CODED );
  134386. if( (pWC->a[iTerm].wtFlags & (TERM_VIRTUAL|TERM_CODED))!=0 ) continue;
  134387. if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue;
  134388. testcase( pWC->a[iTerm].wtFlags & TERM_ORINFO );
  134389. pExpr = sqlite3ExprDup(db, pExpr, 0);
  134390. pAndExpr = sqlite3ExprAnd(pParse, pAndExpr, pExpr);
  134391. }
  134392. if( pAndExpr ){
  134393. /* The extra 0x10000 bit on the opcode is masked off and does not
  134394. ** become part of the new Expr.op. However, it does make the
  134395. ** op==TK_AND comparison inside of sqlite3PExpr() false, and this
  134396. ** prevents sqlite3PExpr() from implementing AND short-circuit
  134397. ** optimization, which we do not want here. */
  134398. pAndExpr = sqlite3PExpr(pParse, TK_AND|0x10000, 0, pAndExpr);
  134399. }
  134400. }
  134401. /* Run a separate WHERE clause for each term of the OR clause. After
  134402. ** eliminating duplicates from other WHERE clauses, the action for each
  134403. ** sub-WHERE clause is to to invoke the main loop body as a subroutine.
  134404. */
  134405. wctrlFlags = WHERE_OR_SUBCLAUSE | (pWInfo->wctrlFlags & WHERE_SEEK_TABLE);
  134406. ExplainQueryPlan((pParse, 1, "MULTI-INDEX OR"));
  134407. for(ii=0; ii<pOrWc->nTerm; ii++){
  134408. WhereTerm *pOrTerm = &pOrWc->a[ii];
  134409. if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){
  134410. WhereInfo *pSubWInfo; /* Info for single OR-term scan */
  134411. Expr *pOrExpr = pOrTerm->pExpr; /* Current OR clause term */
  134412. int jmp1 = 0; /* Address of jump operation */
  134413. testcase( (pTabItem[0].fg.jointype & JT_LEFT)!=0
  134414. && !ExprHasProperty(pOrExpr, EP_FromJoin)
  134415. ); /* See TH3 vtab25.400 and ticket 614b25314c766238 */
  134416. if( pAndExpr ){
  134417. pAndExpr->pLeft = pOrExpr;
  134418. pOrExpr = pAndExpr;
  134419. }
  134420. /* Loop through table entries that match term pOrTerm. */
  134421. ExplainQueryPlan((pParse, 1, "INDEX %d", ii+1));
  134422. WHERETRACE(0xffff, ("Subplan for OR-clause:\n"));
  134423. pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0,
  134424. wctrlFlags, iCovCur);
  134425. assert( pSubWInfo || pParse->nErr || db->mallocFailed );
  134426. if( pSubWInfo ){
  134427. WhereLoop *pSubLoop;
  134428. int addrExplain = sqlite3WhereExplainOneScan(
  134429. pParse, pOrTab, &pSubWInfo->a[0], 0
  134430. );
  134431. sqlite3WhereAddScanStatus(v, pOrTab, &pSubWInfo->a[0], addrExplain);
  134432. /* This is the sub-WHERE clause body. First skip over
  134433. ** duplicate rows from prior sub-WHERE clauses, and record the
  134434. ** rowid (or PRIMARY KEY) for the current row so that the same
  134435. ** row will be skipped in subsequent sub-WHERE clauses.
  134436. */
  134437. if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
  134438. int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
  134439. if( HasRowid(pTab) ){
  134440. sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, -1, regRowid);
  134441. jmp1 = sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset, 0,
  134442. regRowid, iSet);
  134443. VdbeCoverage(v);
  134444. }else{
  134445. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  134446. int nPk = pPk->nKeyCol;
  134447. int iPk;
  134448. int r;
  134449. /* Read the PK into an array of temp registers. */
  134450. r = sqlite3GetTempRange(pParse, nPk);
  134451. for(iPk=0; iPk<nPk; iPk++){
  134452. int iCol = pPk->aiColumn[iPk];
  134453. sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, iCol,r+iPk);
  134454. }
  134455. /* Check if the temp table already contains this key. If so,
  134456. ** the row has already been included in the result set and
  134457. ** can be ignored (by jumping past the Gosub below). Otherwise,
  134458. ** insert the key into the temp table and proceed with processing
  134459. ** the row.
  134460. **
  134461. ** Use some of the same optimizations as OP_RowSetTest: If iSet
  134462. ** is zero, assume that the key cannot already be present in
  134463. ** the temp table. And if iSet is -1, assume that there is no
  134464. ** need to insert the key into the temp table, as it will never
  134465. ** be tested for. */
  134466. if( iSet ){
  134467. jmp1 = sqlite3VdbeAddOp4Int(v, OP_Found, regRowset, 0, r, nPk);
  134468. VdbeCoverage(v);
  134469. }
  134470. if( iSet>=0 ){
  134471. sqlite3VdbeAddOp3(v, OP_MakeRecord, r, nPk, regRowid);
  134472. sqlite3VdbeAddOp4Int(v, OP_IdxInsert, regRowset, regRowid,
  134473. r, nPk);
  134474. if( iSet ) sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  134475. }
  134476. /* Release the array of temp registers */
  134477. sqlite3ReleaseTempRange(pParse, r, nPk);
  134478. }
  134479. }
  134480. /* Invoke the main loop body as a subroutine */
  134481. sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
  134482. /* Jump here (skipping the main loop body subroutine) if the
  134483. ** current sub-WHERE row is a duplicate from prior sub-WHEREs. */
  134484. if( jmp1 ) sqlite3VdbeJumpHere(v, jmp1);
  134485. /* The pSubWInfo->untestedTerms flag means that this OR term
  134486. ** contained one or more AND term from a notReady table. The
  134487. ** terms from the notReady table could not be tested and will
  134488. ** need to be tested later.
  134489. */
  134490. if( pSubWInfo->untestedTerms ) untestedTerms = 1;
  134491. /* If all of the OR-connected terms are optimized using the same
  134492. ** index, and the index is opened using the same cursor number
  134493. ** by each call to sqlite3WhereBegin() made by this loop, it may
  134494. ** be possible to use that index as a covering index.
  134495. **
  134496. ** If the call to sqlite3WhereBegin() above resulted in a scan that
  134497. ** uses an index, and this is either the first OR-connected term
  134498. ** processed or the index is the same as that used by all previous
  134499. ** terms, set pCov to the candidate covering index. Otherwise, set
  134500. ** pCov to NULL to indicate that no candidate covering index will
  134501. ** be available.
  134502. */
  134503. pSubLoop = pSubWInfo->a[0].pWLoop;
  134504. assert( (pSubLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
  134505. if( (pSubLoop->wsFlags & WHERE_INDEXED)!=0
  134506. && (ii==0 || pSubLoop->u.btree.pIndex==pCov)
  134507. && (HasRowid(pTab) || !IsPrimaryKeyIndex(pSubLoop->u.btree.pIndex))
  134508. ){
  134509. assert( pSubWInfo->a[0].iIdxCur==iCovCur );
  134510. pCov = pSubLoop->u.btree.pIndex;
  134511. }else{
  134512. pCov = 0;
  134513. }
  134514. /* Finish the loop through table entries that match term pOrTerm. */
  134515. sqlite3WhereEnd(pSubWInfo);
  134516. ExplainQueryPlanPop(pParse);
  134517. }
  134518. }
  134519. }
  134520. ExplainQueryPlanPop(pParse);
  134521. pLevel->u.pCovidx = pCov;
  134522. if( pCov ) pLevel->iIdxCur = iCovCur;
  134523. if( pAndExpr ){
  134524. pAndExpr->pLeft = 0;
  134525. sqlite3ExprDelete(db, pAndExpr);
  134526. }
  134527. sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
  134528. sqlite3VdbeGoto(v, pLevel->addrBrk);
  134529. sqlite3VdbeResolveLabel(v, iLoopBody);
  134530. if( pWInfo->nLevel>1 ){ sqlite3StackFree(db, pOrTab); }
  134531. if( !untestedTerms ) disableTerm(pLevel, pTerm);
  134532. }else
  134533. #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
  134534. {
  134535. /* Case 6: There is no usable index. We must do a complete
  134536. ** scan of the entire table.
  134537. */
  134538. static const u8 aStep[] = { OP_Next, OP_Prev };
  134539. static const u8 aStart[] = { OP_Rewind, OP_Last };
  134540. assert( bRev==0 || bRev==1 );
  134541. if( pTabItem->fg.isRecursive ){
  134542. /* Tables marked isRecursive have only a single row that is stored in
  134543. ** a pseudo-cursor. No need to Rewind or Next such cursors. */
  134544. pLevel->op = OP_Noop;
  134545. }else{
  134546. codeCursorHint(pTabItem, pWInfo, pLevel, 0);
  134547. pLevel->op = aStep[bRev];
  134548. pLevel->p1 = iCur;
  134549. pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrHalt);
  134550. VdbeCoverageIf(v, bRev==0);
  134551. VdbeCoverageIf(v, bRev!=0);
  134552. pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
  134553. }
  134554. }
  134555. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  134556. pLevel->addrVisit = sqlite3VdbeCurrentAddr(v);
  134557. #endif
  134558. /* Insert code to test every subexpression that can be completely
  134559. ** computed using the current set of tables.
  134560. **
  134561. ** This loop may run between one and three times, depending on the
  134562. ** constraints to be generated. The value of stack variable iLoop
  134563. ** determines the constraints coded by each iteration, as follows:
  134564. **
  134565. ** iLoop==1: Code only expressions that are entirely covered by pIdx.
  134566. ** iLoop==2: Code remaining expressions that do not contain correlated
  134567. ** sub-queries.
  134568. ** iLoop==3: Code all remaining expressions.
  134569. **
  134570. ** An effort is made to skip unnecessary iterations of the loop.
  134571. */
  134572. iLoop = (pIdx ? 1 : 2);
  134573. do{
  134574. int iNext = 0; /* Next value for iLoop */
  134575. for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
  134576. Expr *pE;
  134577. int skipLikeAddr = 0;
  134578. testcase( pTerm->wtFlags & TERM_VIRTUAL );
  134579. testcase( pTerm->wtFlags & TERM_CODED );
  134580. if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
  134581. if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
  134582. testcase( pWInfo->untestedTerms==0
  134583. && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)!=0 );
  134584. pWInfo->untestedTerms = 1;
  134585. continue;
  134586. }
  134587. pE = pTerm->pExpr;
  134588. assert( pE!=0 );
  134589. if( (pTabItem->fg.jointype&JT_LEFT) && !ExprHasProperty(pE,EP_FromJoin) ){
  134590. continue;
  134591. }
  134592. if( iLoop==1 && !sqlite3ExprCoveredByIndex(pE, pLevel->iTabCur, pIdx) ){
  134593. iNext = 2;
  134594. continue;
  134595. }
  134596. if( iLoop<3 && (pTerm->wtFlags & TERM_VARSELECT) ){
  134597. if( iNext==0 ) iNext = 3;
  134598. continue;
  134599. }
  134600. if( (pTerm->wtFlags & TERM_LIKECOND)!=0 ){
  134601. /* If the TERM_LIKECOND flag is set, that means that the range search
  134602. ** is sufficient to guarantee that the LIKE operator is true, so we
  134603. ** can skip the call to the like(A,B) function. But this only works
  134604. ** for strings. So do not skip the call to the function on the pass
  134605. ** that compares BLOBs. */
  134606. #ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS
  134607. continue;
  134608. #else
  134609. u32 x = pLevel->iLikeRepCntr;
  134610. if( x>0 ){
  134611. skipLikeAddr = sqlite3VdbeAddOp1(v, (x&1)?OP_IfNot:OP_If,(int)(x>>1));
  134612. VdbeCoverageIf(v, (x&1)==1);
  134613. VdbeCoverageIf(v, (x&1)==0);
  134614. }
  134615. #endif
  134616. }
  134617. #ifdef WHERETRACE_ENABLED /* 0xffff */
  134618. if( sqlite3WhereTrace ){
  134619. VdbeNoopComment((v, "WhereTerm[%d] (%p) priority=%d",
  134620. pWC->nTerm-j, pTerm, iLoop));
  134621. }
  134622. if( sqlite3WhereTrace & 0x800 ){
  134623. sqlite3DebugPrintf("Coding auxiliary constraint:\n");
  134624. sqlite3WhereTermPrint(pTerm, pWC->nTerm-j);
  134625. }
  134626. #endif
  134627. sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
  134628. if( skipLikeAddr ) sqlite3VdbeJumpHere(v, skipLikeAddr);
  134629. pTerm->wtFlags |= TERM_CODED;
  134630. }
  134631. iLoop = iNext;
  134632. }while( iLoop>0 );
  134633. /* Insert code to test for implied constraints based on transitivity
  134634. ** of the "==" operator.
  134635. **
  134636. ** Example: If the WHERE clause contains "t1.a=t2.b" and "t2.b=123"
  134637. ** and we are coding the t1 loop and the t2 loop has not yet coded,
  134638. ** then we cannot use the "t1.a=t2.b" constraint, but we can code
  134639. ** the implied "t1.a=123" constraint.
  134640. */
  134641. for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
  134642. Expr *pE, sEAlt;
  134643. WhereTerm *pAlt;
  134644. if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
  134645. if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) continue;
  134646. if( (pTerm->eOperator & WO_EQUIV)==0 ) continue;
  134647. if( pTerm->leftCursor!=iCur ) continue;
  134648. if( pTabItem->fg.jointype & JT_LEFT ) continue;
  134649. pE = pTerm->pExpr;
  134650. #ifdef WHERETRACE_ENABLED /* 0x800 */
  134651. if( sqlite3WhereTrace & 0x800 ){
  134652. sqlite3DebugPrintf("Coding transitive constraint:\n");
  134653. sqlite3WhereTermPrint(pTerm, pWC->nTerm-j);
  134654. }
  134655. #endif
  134656. assert( !ExprHasProperty(pE, EP_FromJoin) );
  134657. assert( (pTerm->prereqRight & pLevel->notReady)!=0 );
  134658. pAlt = sqlite3WhereFindTerm(pWC, iCur, pTerm->u.leftColumn, notReady,
  134659. WO_EQ|WO_IN|WO_IS, 0);
  134660. if( pAlt==0 ) continue;
  134661. if( pAlt->wtFlags & (TERM_CODED) ) continue;
  134662. if( (pAlt->eOperator & WO_IN)
  134663. && (pAlt->pExpr->flags & EP_xIsSelect)
  134664. && (pAlt->pExpr->x.pSelect->pEList->nExpr>1)
  134665. ){
  134666. continue;
  134667. }
  134668. testcase( pAlt->eOperator & WO_EQ );
  134669. testcase( pAlt->eOperator & WO_IS );
  134670. testcase( pAlt->eOperator & WO_IN );
  134671. VdbeModuleComment((v, "begin transitive constraint"));
  134672. sEAlt = *pAlt->pExpr;
  134673. sEAlt.pLeft = pE->pLeft;
  134674. sqlite3ExprIfFalse(pParse, &sEAlt, addrCont, SQLITE_JUMPIFNULL);
  134675. }
  134676. /* For a LEFT OUTER JOIN, generate code that will record the fact that
  134677. ** at least one row of the right table has matched the left table.
  134678. */
  134679. if( pLevel->iLeftJoin ){
  134680. pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
  134681. sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
  134682. VdbeComment((v, "record LEFT JOIN hit"));
  134683. for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
  134684. testcase( pTerm->wtFlags & TERM_VIRTUAL );
  134685. testcase( pTerm->wtFlags & TERM_CODED );
  134686. if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
  134687. if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
  134688. assert( pWInfo->untestedTerms );
  134689. continue;
  134690. }
  134691. assert( pTerm->pExpr );
  134692. sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
  134693. pTerm->wtFlags |= TERM_CODED;
  134694. }
  134695. }
  134696. #if WHERETRACE_ENABLED /* 0x20800 */
  134697. if( sqlite3WhereTrace & 0x20000 ){
  134698. sqlite3DebugPrintf("All WHERE-clause terms after coding level %d:\n",
  134699. iLevel);
  134700. sqlite3WhereClausePrint(pWC);
  134701. }
  134702. if( sqlite3WhereTrace & 0x800 ){
  134703. sqlite3DebugPrintf("End Coding level %d: notReady=%llx\n",
  134704. iLevel, (u64)pLevel->notReady);
  134705. }
  134706. #endif
  134707. return pLevel->notReady;
  134708. }
  134709. /************** End of wherecode.c *******************************************/
  134710. /************** Begin file whereexpr.c ***************************************/
  134711. /*
  134712. ** 2015-06-08
  134713. **
  134714. ** The author disclaims copyright to this source code. In place of
  134715. ** a legal notice, here is a blessing:
  134716. **
  134717. ** May you do good and not evil.
  134718. ** May you find forgiveness for yourself and forgive others.
  134719. ** May you share freely, never taking more than you give.
  134720. **
  134721. *************************************************************************
  134722. ** This module contains C code that generates VDBE code used to process
  134723. ** the WHERE clause of SQL statements.
  134724. **
  134725. ** This file was originally part of where.c but was split out to improve
  134726. ** readability and editabiliity. This file contains utility routines for
  134727. ** analyzing Expr objects in the WHERE clause.
  134728. */
  134729. /* #include "sqliteInt.h" */
  134730. /* #include "whereInt.h" */
  134731. /* Forward declarations */
  134732. static void exprAnalyze(SrcList*, WhereClause*, int);
  134733. /*
  134734. ** Deallocate all memory associated with a WhereOrInfo object.
  134735. */
  134736. static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
  134737. sqlite3WhereClauseClear(&p->wc);
  134738. sqlite3DbFree(db, p);
  134739. }
  134740. /*
  134741. ** Deallocate all memory associated with a WhereAndInfo object.
  134742. */
  134743. static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
  134744. sqlite3WhereClauseClear(&p->wc);
  134745. sqlite3DbFree(db, p);
  134746. }
  134747. /*
  134748. ** Add a single new WhereTerm entry to the WhereClause object pWC.
  134749. ** The new WhereTerm object is constructed from Expr p and with wtFlags.
  134750. ** The index in pWC->a[] of the new WhereTerm is returned on success.
  134751. ** 0 is returned if the new WhereTerm could not be added due to a memory
  134752. ** allocation error. The memory allocation failure will be recorded in
  134753. ** the db->mallocFailed flag so that higher-level functions can detect it.
  134754. **
  134755. ** This routine will increase the size of the pWC->a[] array as necessary.
  134756. **
  134757. ** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
  134758. ** for freeing the expression p is assumed by the WhereClause object pWC.
  134759. ** This is true even if this routine fails to allocate a new WhereTerm.
  134760. **
  134761. ** WARNING: This routine might reallocate the space used to store
  134762. ** WhereTerms. All pointers to WhereTerms should be invalidated after
  134763. ** calling this routine. Such pointers may be reinitialized by referencing
  134764. ** the pWC->a[] array.
  134765. */
  134766. static int whereClauseInsert(WhereClause *pWC, Expr *p, u16 wtFlags){
  134767. WhereTerm *pTerm;
  134768. int idx;
  134769. testcase( wtFlags & TERM_VIRTUAL );
  134770. if( pWC->nTerm>=pWC->nSlot ){
  134771. WhereTerm *pOld = pWC->a;
  134772. sqlite3 *db = pWC->pWInfo->pParse->db;
  134773. pWC->a = sqlite3DbMallocRawNN(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
  134774. if( pWC->a==0 ){
  134775. if( wtFlags & TERM_DYNAMIC ){
  134776. sqlite3ExprDelete(db, p);
  134777. }
  134778. pWC->a = pOld;
  134779. return 0;
  134780. }
  134781. memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
  134782. if( pOld!=pWC->aStatic ){
  134783. sqlite3DbFree(db, pOld);
  134784. }
  134785. pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
  134786. }
  134787. pTerm = &pWC->a[idx = pWC->nTerm++];
  134788. if( p && ExprHasProperty(p, EP_Unlikely) ){
  134789. pTerm->truthProb = sqlite3LogEst(p->iTable) - 270;
  134790. }else{
  134791. pTerm->truthProb = 1;
  134792. }
  134793. pTerm->pExpr = sqlite3ExprSkipCollateAndLikely(p);
  134794. pTerm->wtFlags = wtFlags;
  134795. pTerm->pWC = pWC;
  134796. pTerm->iParent = -1;
  134797. memset(&pTerm->eOperator, 0,
  134798. sizeof(WhereTerm) - offsetof(WhereTerm,eOperator));
  134799. return idx;
  134800. }
  134801. /*
  134802. ** Return TRUE if the given operator is one of the operators that is
  134803. ** allowed for an indexable WHERE clause term. The allowed operators are
  134804. ** "=", "<", ">", "<=", ">=", "IN", "IS", and "IS NULL"
  134805. */
  134806. static int allowedOp(int op){
  134807. assert( TK_GT>TK_EQ && TK_GT<TK_GE );
  134808. assert( TK_LT>TK_EQ && TK_LT<TK_GE );
  134809. assert( TK_LE>TK_EQ && TK_LE<TK_GE );
  134810. assert( TK_GE==TK_EQ+4 );
  134811. return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL || op==TK_IS;
  134812. }
  134813. /*
  134814. ** Commute a comparison operator. Expressions of the form "X op Y"
  134815. ** are converted into "Y op X".
  134816. */
  134817. static u16 exprCommute(Parse *pParse, Expr *pExpr){
  134818. if( pExpr->pLeft->op==TK_VECTOR
  134819. || pExpr->pRight->op==TK_VECTOR
  134820. || sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft, pExpr->pRight) !=
  134821. sqlite3BinaryCompareCollSeq(pParse, pExpr->pRight, pExpr->pLeft)
  134822. ){
  134823. pExpr->flags ^= EP_Commuted;
  134824. }
  134825. SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
  134826. if( pExpr->op>=TK_GT ){
  134827. assert( TK_LT==TK_GT+2 );
  134828. assert( TK_GE==TK_LE+2 );
  134829. assert( TK_GT>TK_EQ );
  134830. assert( TK_GT<TK_LE );
  134831. assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
  134832. pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
  134833. }
  134834. return 0;
  134835. }
  134836. /*
  134837. ** Translate from TK_xx operator to WO_xx bitmask.
  134838. */
  134839. static u16 operatorMask(int op){
  134840. u16 c;
  134841. assert( allowedOp(op) );
  134842. if( op==TK_IN ){
  134843. c = WO_IN;
  134844. }else if( op==TK_ISNULL ){
  134845. c = WO_ISNULL;
  134846. }else if( op==TK_IS ){
  134847. c = WO_IS;
  134848. }else{
  134849. assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
  134850. c = (u16)(WO_EQ<<(op-TK_EQ));
  134851. }
  134852. assert( op!=TK_ISNULL || c==WO_ISNULL );
  134853. assert( op!=TK_IN || c==WO_IN );
  134854. assert( op!=TK_EQ || c==WO_EQ );
  134855. assert( op!=TK_LT || c==WO_LT );
  134856. assert( op!=TK_LE || c==WO_LE );
  134857. assert( op!=TK_GT || c==WO_GT );
  134858. assert( op!=TK_GE || c==WO_GE );
  134859. assert( op!=TK_IS || c==WO_IS );
  134860. return c;
  134861. }
  134862. #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
  134863. /*
  134864. ** Check to see if the given expression is a LIKE or GLOB operator that
  134865. ** can be optimized using inequality constraints. Return TRUE if it is
  134866. ** so and false if not.
  134867. **
  134868. ** In order for the operator to be optimizible, the RHS must be a string
  134869. ** literal that does not begin with a wildcard. The LHS must be a column
  134870. ** that may only be NULL, a string, or a BLOB, never a number. (This means
  134871. ** that virtual tables cannot participate in the LIKE optimization.) The
  134872. ** collating sequence for the column on the LHS must be appropriate for
  134873. ** the operator.
  134874. */
  134875. static int isLikeOrGlob(
  134876. Parse *pParse, /* Parsing and code generating context */
  134877. Expr *pExpr, /* Test this expression */
  134878. Expr **ppPrefix, /* Pointer to TK_STRING expression with pattern prefix */
  134879. int *pisComplete, /* True if the only wildcard is % in the last character */
  134880. int *pnoCase /* True if uppercase is equivalent to lowercase */
  134881. ){
  134882. const u8 *z = 0; /* String on RHS of LIKE operator */
  134883. Expr *pRight, *pLeft; /* Right and left size of LIKE operator */
  134884. ExprList *pList; /* List of operands to the LIKE operator */
  134885. u8 c; /* One character in z[] */
  134886. int cnt; /* Number of non-wildcard prefix characters */
  134887. u8 wc[4]; /* Wildcard characters */
  134888. sqlite3 *db = pParse->db; /* Database connection */
  134889. sqlite3_value *pVal = 0;
  134890. int op; /* Opcode of pRight */
  134891. int rc; /* Result code to return */
  134892. if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, (char*)wc) ){
  134893. return 0;
  134894. }
  134895. #ifdef SQLITE_EBCDIC
  134896. if( *pnoCase ) return 0;
  134897. #endif
  134898. pList = pExpr->x.pList;
  134899. pLeft = pList->a[1].pExpr;
  134900. pRight = sqlite3ExprSkipCollate(pList->a[0].pExpr);
  134901. op = pRight->op;
  134902. if( op==TK_VARIABLE && (db->flags & SQLITE_EnableQPSG)==0 ){
  134903. Vdbe *pReprepare = pParse->pReprepare;
  134904. int iCol = pRight->iColumn;
  134905. pVal = sqlite3VdbeGetBoundValue(pReprepare, iCol, SQLITE_AFF_BLOB);
  134906. if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
  134907. z = sqlite3_value_text(pVal);
  134908. }
  134909. sqlite3VdbeSetVarmask(pParse->pVdbe, iCol);
  134910. assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
  134911. }else if( op==TK_STRING ){
  134912. z = (u8*)pRight->u.zToken;
  134913. }
  134914. if( z ){
  134915. /* Count the number of prefix characters prior to the first wildcard */
  134916. cnt = 0;
  134917. while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
  134918. cnt++;
  134919. if( c==wc[3] && z[cnt]!=0 ) cnt++;
  134920. }
  134921. /* The optimization is possible only if (1) the pattern does not begin
  134922. ** with a wildcard and if (2) the non-wildcard prefix does not end with
  134923. ** an (illegal 0xff) character, or (3) the pattern does not consist of
  134924. ** a single escape character. The second condition is necessary so
  134925. ** that we can increment the prefix key to find an upper bound for the
  134926. ** range search. The third is because the caller assumes that the pattern
  134927. ** consists of at least one character after all escapes have been
  134928. ** removed. */
  134929. if( cnt!=0 && 255!=(u8)z[cnt-1] && (cnt>1 || z[0]!=wc[3]) ){
  134930. Expr *pPrefix;
  134931. /* A "complete" match if the pattern ends with "*" or "%" */
  134932. *pisComplete = c==wc[0] && z[cnt+1]==0;
  134933. /* Get the pattern prefix. Remove all escapes from the prefix. */
  134934. pPrefix = sqlite3Expr(db, TK_STRING, (char*)z);
  134935. if( pPrefix ){
  134936. int iFrom, iTo;
  134937. char *zNew = pPrefix->u.zToken;
  134938. zNew[cnt] = 0;
  134939. for(iFrom=iTo=0; iFrom<cnt; iFrom++){
  134940. if( zNew[iFrom]==wc[3] ) iFrom++;
  134941. zNew[iTo++] = zNew[iFrom];
  134942. }
  134943. zNew[iTo] = 0;
  134944. assert( iTo>0 );
  134945. /* If the LHS is not an ordinary column with TEXT affinity, then the
  134946. ** pattern prefix boundaries (both the start and end boundaries) must
  134947. ** not look like a number. Otherwise the pattern might be treated as
  134948. ** a number, which will invalidate the LIKE optimization.
  134949. **
  134950. ** Getting this right has been a persistent source of bugs in the
  134951. ** LIKE optimization. See, for example:
  134952. ** 2018-09-10 https://sqlite.org/src/info/c94369cae9b561b1
  134953. ** 2019-05-02 https://sqlite.org/src/info/b043a54c3de54b28
  134954. ** 2019-06-10 https://sqlite.org/src/info/fd76310a5e843e07
  134955. ** 2019-06-14 https://sqlite.org/src/info/ce8717f0885af975
  134956. ** 2019-09-03 https://sqlite.org/src/info/0f0428096f17252a
  134957. */
  134958. if( pLeft->op!=TK_COLUMN
  134959. || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT
  134960. || IsVirtual(pLeft->y.pTab) /* Value might be numeric */
  134961. ){
  134962. int isNum;
  134963. double rDummy;
  134964. isNum = sqlite3AtoF(zNew, &rDummy, iTo, SQLITE_UTF8);
  134965. if( isNum<=0 ){
  134966. if( iTo==1 && zNew[0]=='-' ){
  134967. isNum = +1;
  134968. }else{
  134969. zNew[iTo-1]++;
  134970. isNum = sqlite3AtoF(zNew, &rDummy, iTo, SQLITE_UTF8);
  134971. zNew[iTo-1]--;
  134972. }
  134973. }
  134974. if( isNum>0 ){
  134975. sqlite3ExprDelete(db, pPrefix);
  134976. sqlite3ValueFree(pVal);
  134977. return 0;
  134978. }
  134979. }
  134980. }
  134981. *ppPrefix = pPrefix;
  134982. /* If the RHS pattern is a bound parameter, make arrangements to
  134983. ** reprepare the statement when that parameter is rebound */
  134984. if( op==TK_VARIABLE ){
  134985. Vdbe *v = pParse->pVdbe;
  134986. sqlite3VdbeSetVarmask(v, pRight->iColumn);
  134987. if( *pisComplete && pRight->u.zToken[1] ){
  134988. /* If the rhs of the LIKE expression is a variable, and the current
  134989. ** value of the variable means there is no need to invoke the LIKE
  134990. ** function, then no OP_Variable will be added to the program.
  134991. ** This causes problems for the sqlite3_bind_parameter_name()
  134992. ** API. To work around them, add a dummy OP_Variable here.
  134993. */
  134994. int r1 = sqlite3GetTempReg(pParse);
  134995. sqlite3ExprCodeTarget(pParse, pRight, r1);
  134996. sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
  134997. sqlite3ReleaseTempReg(pParse, r1);
  134998. }
  134999. }
  135000. }else{
  135001. z = 0;
  135002. }
  135003. }
  135004. rc = (z!=0);
  135005. sqlite3ValueFree(pVal);
  135006. return rc;
  135007. }
  135008. #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
  135009. #ifndef SQLITE_OMIT_VIRTUALTABLE
  135010. /*
  135011. ** Check to see if the pExpr expression is a form that needs to be passed
  135012. ** to the xBestIndex method of virtual tables. Forms of interest include:
  135013. **
  135014. ** Expression Virtual Table Operator
  135015. ** ----------------------- ---------------------------------
  135016. ** 1. column MATCH expr SQLITE_INDEX_CONSTRAINT_MATCH
  135017. ** 2. column GLOB expr SQLITE_INDEX_CONSTRAINT_GLOB
  135018. ** 3. column LIKE expr SQLITE_INDEX_CONSTRAINT_LIKE
  135019. ** 4. column REGEXP expr SQLITE_INDEX_CONSTRAINT_REGEXP
  135020. ** 5. column != expr SQLITE_INDEX_CONSTRAINT_NE
  135021. ** 6. expr != column SQLITE_INDEX_CONSTRAINT_NE
  135022. ** 7. column IS NOT expr SQLITE_INDEX_CONSTRAINT_ISNOT
  135023. ** 8. expr IS NOT column SQLITE_INDEX_CONSTRAINT_ISNOT
  135024. ** 9. column IS NOT NULL SQLITE_INDEX_CONSTRAINT_ISNOTNULL
  135025. **
  135026. ** In every case, "column" must be a column of a virtual table. If there
  135027. ** is a match, set *ppLeft to the "column" expression, set *ppRight to the
  135028. ** "expr" expression (even though in forms (6) and (8) the column is on the
  135029. ** right and the expression is on the left). Also set *peOp2 to the
  135030. ** appropriate virtual table operator. The return value is 1 or 2 if there
  135031. ** is a match. The usual return is 1, but if the RHS is also a column
  135032. ** of virtual table in forms (5) or (7) then return 2.
  135033. **
  135034. ** If the expression matches none of the patterns above, return 0.
  135035. */
  135036. static int isAuxiliaryVtabOperator(
  135037. sqlite3 *db, /* Parsing context */
  135038. Expr *pExpr, /* Test this expression */
  135039. unsigned char *peOp2, /* OUT: 0 for MATCH, or else an op2 value */
  135040. Expr **ppLeft, /* Column expression to left of MATCH/op2 */
  135041. Expr **ppRight /* Expression to left of MATCH/op2 */
  135042. ){
  135043. if( pExpr->op==TK_FUNCTION ){
  135044. static const struct Op2 {
  135045. const char *zOp;
  135046. unsigned char eOp2;
  135047. } aOp[] = {
  135048. { "match", SQLITE_INDEX_CONSTRAINT_MATCH },
  135049. { "glob", SQLITE_INDEX_CONSTRAINT_GLOB },
  135050. { "like", SQLITE_INDEX_CONSTRAINT_LIKE },
  135051. { "regexp", SQLITE_INDEX_CONSTRAINT_REGEXP }
  135052. };
  135053. ExprList *pList;
  135054. Expr *pCol; /* Column reference */
  135055. int i;
  135056. pList = pExpr->x.pList;
  135057. if( pList==0 || pList->nExpr!=2 ){
  135058. return 0;
  135059. }
  135060. /* Built-in operators MATCH, GLOB, LIKE, and REGEXP attach to a
  135061. ** virtual table on their second argument, which is the same as
  135062. ** the left-hand side operand in their in-fix form.
  135063. **
  135064. ** vtab_column MATCH expression
  135065. ** MATCH(expression,vtab_column)
  135066. */
  135067. pCol = pList->a[1].pExpr;
  135068. testcase( pCol->op==TK_COLUMN && pCol->y.pTab==0 );
  135069. if( ExprIsVtab(pCol) ){
  135070. for(i=0; i<ArraySize(aOp); i++){
  135071. if( sqlite3StrICmp(pExpr->u.zToken, aOp[i].zOp)==0 ){
  135072. *peOp2 = aOp[i].eOp2;
  135073. *ppRight = pList->a[0].pExpr;
  135074. *ppLeft = pCol;
  135075. return 1;
  135076. }
  135077. }
  135078. }
  135079. /* We can also match against the first column of overloaded
  135080. ** functions where xFindFunction returns a value of at least
  135081. ** SQLITE_INDEX_CONSTRAINT_FUNCTION.
  135082. **
  135083. ** OVERLOADED(vtab_column,expression)
  135084. **
  135085. ** Historically, xFindFunction expected to see lower-case function
  135086. ** names. But for this use case, xFindFunction is expected to deal
  135087. ** with function names in an arbitrary case.
  135088. */
  135089. pCol = pList->a[0].pExpr;
  135090. testcase( pCol->op==TK_COLUMN && pCol->y.pTab==0 );
  135091. if( ExprIsVtab(pCol) ){
  135092. sqlite3_vtab *pVtab;
  135093. sqlite3_module *pMod;
  135094. void (*xNotUsed)(sqlite3_context*,int,sqlite3_value**);
  135095. void *pNotUsed;
  135096. pVtab = sqlite3GetVTable(db, pCol->y.pTab)->pVtab;
  135097. assert( pVtab!=0 );
  135098. assert( pVtab->pModule!=0 );
  135099. pMod = (sqlite3_module *)pVtab->pModule;
  135100. if( pMod->xFindFunction!=0 ){
  135101. i = pMod->xFindFunction(pVtab,2, pExpr->u.zToken, &xNotUsed, &pNotUsed);
  135102. if( i>=SQLITE_INDEX_CONSTRAINT_FUNCTION ){
  135103. *peOp2 = i;
  135104. *ppRight = pList->a[1].pExpr;
  135105. *ppLeft = pCol;
  135106. return 1;
  135107. }
  135108. }
  135109. }
  135110. }else if( pExpr->op==TK_NE || pExpr->op==TK_ISNOT || pExpr->op==TK_NOTNULL ){
  135111. int res = 0;
  135112. Expr *pLeft = pExpr->pLeft;
  135113. Expr *pRight = pExpr->pRight;
  135114. testcase( pLeft->op==TK_COLUMN && pLeft->y.pTab==0 );
  135115. if( ExprIsVtab(pLeft) ){
  135116. res++;
  135117. }
  135118. testcase( pRight && pRight->op==TK_COLUMN && pRight->y.pTab==0 );
  135119. if( pRight && ExprIsVtab(pRight) ){
  135120. res++;
  135121. SWAP(Expr*, pLeft, pRight);
  135122. }
  135123. *ppLeft = pLeft;
  135124. *ppRight = pRight;
  135125. if( pExpr->op==TK_NE ) *peOp2 = SQLITE_INDEX_CONSTRAINT_NE;
  135126. if( pExpr->op==TK_ISNOT ) *peOp2 = SQLITE_INDEX_CONSTRAINT_ISNOT;
  135127. if( pExpr->op==TK_NOTNULL ) *peOp2 = SQLITE_INDEX_CONSTRAINT_ISNOTNULL;
  135128. return res;
  135129. }
  135130. return 0;
  135131. }
  135132. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  135133. /*
  135134. ** If the pBase expression originated in the ON or USING clause of
  135135. ** a join, then transfer the appropriate markings over to derived.
  135136. */
  135137. static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
  135138. if( pDerived ){
  135139. pDerived->flags |= pBase->flags & EP_FromJoin;
  135140. pDerived->iRightJoinTable = pBase->iRightJoinTable;
  135141. }
  135142. }
  135143. /*
  135144. ** Mark term iChild as being a child of term iParent
  135145. */
  135146. static void markTermAsChild(WhereClause *pWC, int iChild, int iParent){
  135147. pWC->a[iChild].iParent = iParent;
  135148. pWC->a[iChild].truthProb = pWC->a[iParent].truthProb;
  135149. pWC->a[iParent].nChild++;
  135150. }
  135151. /*
  135152. ** Return the N-th AND-connected subterm of pTerm. Or if pTerm is not
  135153. ** a conjunction, then return just pTerm when N==0. If N is exceeds
  135154. ** the number of available subterms, return NULL.
  135155. */
  135156. static WhereTerm *whereNthSubterm(WhereTerm *pTerm, int N){
  135157. if( pTerm->eOperator!=WO_AND ){
  135158. return N==0 ? pTerm : 0;
  135159. }
  135160. if( N<pTerm->u.pAndInfo->wc.nTerm ){
  135161. return &pTerm->u.pAndInfo->wc.a[N];
  135162. }
  135163. return 0;
  135164. }
  135165. /*
  135166. ** Subterms pOne and pTwo are contained within WHERE clause pWC. The
  135167. ** two subterms are in disjunction - they are OR-ed together.
  135168. **
  135169. ** If these two terms are both of the form: "A op B" with the same
  135170. ** A and B values but different operators and if the operators are
  135171. ** compatible (if one is = and the other is <, for example) then
  135172. ** add a new virtual AND term to pWC that is the combination of the
  135173. ** two.
  135174. **
  135175. ** Some examples:
  135176. **
  135177. ** x<y OR x=y --> x<=y
  135178. ** x=y OR x=y --> x=y
  135179. ** x<=y OR x<y --> x<=y
  135180. **
  135181. ** The following is NOT generated:
  135182. **
  135183. ** x<y OR x>y --> x!=y
  135184. */
  135185. static void whereCombineDisjuncts(
  135186. SrcList *pSrc, /* the FROM clause */
  135187. WhereClause *pWC, /* The complete WHERE clause */
  135188. WhereTerm *pOne, /* First disjunct */
  135189. WhereTerm *pTwo /* Second disjunct */
  135190. ){
  135191. u16 eOp = pOne->eOperator | pTwo->eOperator;
  135192. sqlite3 *db; /* Database connection (for malloc) */
  135193. Expr *pNew; /* New virtual expression */
  135194. int op; /* Operator for the combined expression */
  135195. int idxNew; /* Index in pWC of the next virtual term */
  135196. if( (pOne->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return;
  135197. if( (pTwo->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return;
  135198. if( (eOp & (WO_EQ|WO_LT|WO_LE))!=eOp
  135199. && (eOp & (WO_EQ|WO_GT|WO_GE))!=eOp ) return;
  135200. assert( pOne->pExpr->pLeft!=0 && pOne->pExpr->pRight!=0 );
  135201. assert( pTwo->pExpr->pLeft!=0 && pTwo->pExpr->pRight!=0 );
  135202. if( sqlite3ExprCompare(0,pOne->pExpr->pLeft, pTwo->pExpr->pLeft, -1) ) return;
  135203. if( sqlite3ExprCompare(0,pOne->pExpr->pRight, pTwo->pExpr->pRight,-1) )return;
  135204. /* If we reach this point, it means the two subterms can be combined */
  135205. if( (eOp & (eOp-1))!=0 ){
  135206. if( eOp & (WO_LT|WO_LE) ){
  135207. eOp = WO_LE;
  135208. }else{
  135209. assert( eOp & (WO_GT|WO_GE) );
  135210. eOp = WO_GE;
  135211. }
  135212. }
  135213. db = pWC->pWInfo->pParse->db;
  135214. pNew = sqlite3ExprDup(db, pOne->pExpr, 0);
  135215. if( pNew==0 ) return;
  135216. for(op=TK_EQ; eOp!=(WO_EQ<<(op-TK_EQ)); op++){ assert( op<TK_GE ); }
  135217. pNew->op = op;
  135218. idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
  135219. exprAnalyze(pSrc, pWC, idxNew);
  135220. }
  135221. #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
  135222. /*
  135223. ** Analyze a term that consists of two or more OR-connected
  135224. ** subterms. So in:
  135225. **
  135226. ** ... WHERE (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
  135227. ** ^^^^^^^^^^^^^^^^^^^^
  135228. **
  135229. ** This routine analyzes terms such as the middle term in the above example.
  135230. ** A WhereOrTerm object is computed and attached to the term under
  135231. ** analysis, regardless of the outcome of the analysis. Hence:
  135232. **
  135233. ** WhereTerm.wtFlags |= TERM_ORINFO
  135234. ** WhereTerm.u.pOrInfo = a dynamically allocated WhereOrTerm object
  135235. **
  135236. ** The term being analyzed must have two or more of OR-connected subterms.
  135237. ** A single subterm might be a set of AND-connected sub-subterms.
  135238. ** Examples of terms under analysis:
  135239. **
  135240. ** (A) t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
  135241. ** (B) x=expr1 OR expr2=x OR x=expr3
  135242. ** (C) t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
  135243. ** (D) x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
  135244. ** (E) (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
  135245. ** (F) x>A OR (x=A AND y>=B)
  135246. **
  135247. ** CASE 1:
  135248. **
  135249. ** If all subterms are of the form T.C=expr for some single column of C and
  135250. ** a single table T (as shown in example B above) then create a new virtual
  135251. ** term that is an equivalent IN expression. In other words, if the term
  135252. ** being analyzed is:
  135253. **
  135254. ** x = expr1 OR expr2 = x OR x = expr3
  135255. **
  135256. ** then create a new virtual term like this:
  135257. **
  135258. ** x IN (expr1,expr2,expr3)
  135259. **
  135260. ** CASE 2:
  135261. **
  135262. ** If there are exactly two disjuncts and one side has x>A and the other side
  135263. ** has x=A (for the same x and A) then add a new virtual conjunct term to the
  135264. ** WHERE clause of the form "x>=A". Example:
  135265. **
  135266. ** x>A OR (x=A AND y>B) adds: x>=A
  135267. **
  135268. ** The added conjunct can sometimes be helpful in query planning.
  135269. **
  135270. ** CASE 3:
  135271. **
  135272. ** If all subterms are indexable by a single table T, then set
  135273. **
  135274. ** WhereTerm.eOperator = WO_OR
  135275. ** WhereTerm.u.pOrInfo->indexable |= the cursor number for table T
  135276. **
  135277. ** A subterm is "indexable" if it is of the form
  135278. ** "T.C <op> <expr>" where C is any column of table T and
  135279. ** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
  135280. ** A subterm is also indexable if it is an AND of two or more
  135281. ** subsubterms at least one of which is indexable. Indexable AND
  135282. ** subterms have their eOperator set to WO_AND and they have
  135283. ** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
  135284. **
  135285. ** From another point of view, "indexable" means that the subterm could
  135286. ** potentially be used with an index if an appropriate index exists.
  135287. ** This analysis does not consider whether or not the index exists; that
  135288. ** is decided elsewhere. This analysis only looks at whether subterms
  135289. ** appropriate for indexing exist.
  135290. **
  135291. ** All examples A through E above satisfy case 3. But if a term
  135292. ** also satisfies case 1 (such as B) we know that the optimizer will
  135293. ** always prefer case 1, so in that case we pretend that case 3 is not
  135294. ** satisfied.
  135295. **
  135296. ** It might be the case that multiple tables are indexable. For example,
  135297. ** (E) above is indexable on tables P, Q, and R.
  135298. **
  135299. ** Terms that satisfy case 3 are candidates for lookup by using
  135300. ** separate indices to find rowids for each subterm and composing
  135301. ** the union of all rowids using a RowSet object. This is similar
  135302. ** to "bitmap indices" in other database engines.
  135303. **
  135304. ** OTHERWISE:
  135305. **
  135306. ** If none of cases 1, 2, or 3 apply, then leave the eOperator set to
  135307. ** zero. This term is not useful for search.
  135308. */
  135309. static void exprAnalyzeOrTerm(
  135310. SrcList *pSrc, /* the FROM clause */
  135311. WhereClause *pWC, /* the complete WHERE clause */
  135312. int idxTerm /* Index of the OR-term to be analyzed */
  135313. ){
  135314. WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
  135315. Parse *pParse = pWInfo->pParse; /* Parser context */
  135316. sqlite3 *db = pParse->db; /* Database connection */
  135317. WhereTerm *pTerm = &pWC->a[idxTerm]; /* The term to be analyzed */
  135318. Expr *pExpr = pTerm->pExpr; /* The expression of the term */
  135319. int i; /* Loop counters */
  135320. WhereClause *pOrWc; /* Breakup of pTerm into subterms */
  135321. WhereTerm *pOrTerm; /* A Sub-term within the pOrWc */
  135322. WhereOrInfo *pOrInfo; /* Additional information associated with pTerm */
  135323. Bitmask chngToIN; /* Tables that might satisfy case 1 */
  135324. Bitmask indexable; /* Tables that are indexable, satisfying case 2 */
  135325. /*
  135326. ** Break the OR clause into its separate subterms. The subterms are
  135327. ** stored in a WhereClause structure containing within the WhereOrInfo
  135328. ** object that is attached to the original OR clause term.
  135329. */
  135330. assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
  135331. assert( pExpr->op==TK_OR );
  135332. pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
  135333. if( pOrInfo==0 ) return;
  135334. pTerm->wtFlags |= TERM_ORINFO;
  135335. pOrWc = &pOrInfo->wc;
  135336. memset(pOrWc->aStatic, 0, sizeof(pOrWc->aStatic));
  135337. sqlite3WhereClauseInit(pOrWc, pWInfo);
  135338. sqlite3WhereSplit(pOrWc, pExpr, TK_OR);
  135339. sqlite3WhereExprAnalyze(pSrc, pOrWc);
  135340. if( db->mallocFailed ) return;
  135341. assert( pOrWc->nTerm>=2 );
  135342. /*
  135343. ** Compute the set of tables that might satisfy cases 1 or 3.
  135344. */
  135345. indexable = ~(Bitmask)0;
  135346. chngToIN = ~(Bitmask)0;
  135347. for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
  135348. if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
  135349. WhereAndInfo *pAndInfo;
  135350. assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
  135351. chngToIN = 0;
  135352. pAndInfo = sqlite3DbMallocRawNN(db, sizeof(*pAndInfo));
  135353. if( pAndInfo ){
  135354. WhereClause *pAndWC;
  135355. WhereTerm *pAndTerm;
  135356. int j;
  135357. Bitmask b = 0;
  135358. pOrTerm->u.pAndInfo = pAndInfo;
  135359. pOrTerm->wtFlags |= TERM_ANDINFO;
  135360. pOrTerm->eOperator = WO_AND;
  135361. pAndWC = &pAndInfo->wc;
  135362. memset(pAndWC->aStatic, 0, sizeof(pAndWC->aStatic));
  135363. sqlite3WhereClauseInit(pAndWC, pWC->pWInfo);
  135364. sqlite3WhereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
  135365. sqlite3WhereExprAnalyze(pSrc, pAndWC);
  135366. pAndWC->pOuter = pWC;
  135367. if( !db->mallocFailed ){
  135368. for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
  135369. assert( pAndTerm->pExpr );
  135370. if( allowedOp(pAndTerm->pExpr->op)
  135371. || pAndTerm->eOperator==WO_AUX
  135372. ){
  135373. b |= sqlite3WhereGetMask(&pWInfo->sMaskSet, pAndTerm->leftCursor);
  135374. }
  135375. }
  135376. }
  135377. indexable &= b;
  135378. }
  135379. }else if( pOrTerm->wtFlags & TERM_COPIED ){
  135380. /* Skip this term for now. We revisit it when we process the
  135381. ** corresponding TERM_VIRTUAL term */
  135382. }else{
  135383. Bitmask b;
  135384. b = sqlite3WhereGetMask(&pWInfo->sMaskSet, pOrTerm->leftCursor);
  135385. if( pOrTerm->wtFlags & TERM_VIRTUAL ){
  135386. WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
  135387. b |= sqlite3WhereGetMask(&pWInfo->sMaskSet, pOther->leftCursor);
  135388. }
  135389. indexable &= b;
  135390. if( (pOrTerm->eOperator & WO_EQ)==0 ){
  135391. chngToIN = 0;
  135392. }else{
  135393. chngToIN &= b;
  135394. }
  135395. }
  135396. }
  135397. /*
  135398. ** Record the set of tables that satisfy case 3. The set might be
  135399. ** empty.
  135400. */
  135401. pOrInfo->indexable = indexable;
  135402. if( indexable ){
  135403. pTerm->eOperator = WO_OR;
  135404. pWC->hasOr = 1;
  135405. }else{
  135406. pTerm->eOperator = WO_OR;
  135407. }
  135408. /* For a two-way OR, attempt to implementation case 2.
  135409. */
  135410. if( indexable && pOrWc->nTerm==2 ){
  135411. int iOne = 0;
  135412. WhereTerm *pOne;
  135413. while( (pOne = whereNthSubterm(&pOrWc->a[0],iOne++))!=0 ){
  135414. int iTwo = 0;
  135415. WhereTerm *pTwo;
  135416. while( (pTwo = whereNthSubterm(&pOrWc->a[1],iTwo++))!=0 ){
  135417. whereCombineDisjuncts(pSrc, pWC, pOne, pTwo);
  135418. }
  135419. }
  135420. }
  135421. /*
  135422. ** chngToIN holds a set of tables that *might* satisfy case 1. But
  135423. ** we have to do some additional checking to see if case 1 really
  135424. ** is satisfied.
  135425. **
  135426. ** chngToIN will hold either 0, 1, or 2 bits. The 0-bit case means
  135427. ** that there is no possibility of transforming the OR clause into an
  135428. ** IN operator because one or more terms in the OR clause contain
  135429. ** something other than == on a column in the single table. The 1-bit
  135430. ** case means that every term of the OR clause is of the form
  135431. ** "table.column=expr" for some single table. The one bit that is set
  135432. ** will correspond to the common table. We still need to check to make
  135433. ** sure the same column is used on all terms. The 2-bit case is when
  135434. ** the all terms are of the form "table1.column=table2.column". It
  135435. ** might be possible to form an IN operator with either table1.column
  135436. ** or table2.column as the LHS if either is common to every term of
  135437. ** the OR clause.
  135438. **
  135439. ** Note that terms of the form "table.column1=table.column2" (the
  135440. ** same table on both sizes of the ==) cannot be optimized.
  135441. */
  135442. if( chngToIN ){
  135443. int okToChngToIN = 0; /* True if the conversion to IN is valid */
  135444. int iColumn = -1; /* Column index on lhs of IN operator */
  135445. int iCursor = -1; /* Table cursor common to all terms */
  135446. int j = 0; /* Loop counter */
  135447. /* Search for a table and column that appears on one side or the
  135448. ** other of the == operator in every subterm. That table and column
  135449. ** will be recorded in iCursor and iColumn. There might not be any
  135450. ** such table and column. Set okToChngToIN if an appropriate table
  135451. ** and column is found but leave okToChngToIN false if not found.
  135452. */
  135453. for(j=0; j<2 && !okToChngToIN; j++){
  135454. Expr *pLeft = 0;
  135455. pOrTerm = pOrWc->a;
  135456. for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
  135457. assert( pOrTerm->eOperator & WO_EQ );
  135458. pOrTerm->wtFlags &= ~TERM_OR_OK;
  135459. if( pOrTerm->leftCursor==iCursor ){
  135460. /* This is the 2-bit case and we are on the second iteration and
  135461. ** current term is from the first iteration. So skip this term. */
  135462. assert( j==1 );
  135463. continue;
  135464. }
  135465. if( (chngToIN & sqlite3WhereGetMask(&pWInfo->sMaskSet,
  135466. pOrTerm->leftCursor))==0 ){
  135467. /* This term must be of the form t1.a==t2.b where t2 is in the
  135468. ** chngToIN set but t1 is not. This term will be either preceded
  135469. ** or follwed by an inverted copy (t2.b==t1.a). Skip this term
  135470. ** and use its inversion. */
  135471. testcase( pOrTerm->wtFlags & TERM_COPIED );
  135472. testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
  135473. assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
  135474. continue;
  135475. }
  135476. iColumn = pOrTerm->u.leftColumn;
  135477. iCursor = pOrTerm->leftCursor;
  135478. pLeft = pOrTerm->pExpr->pLeft;
  135479. break;
  135480. }
  135481. if( i<0 ){
  135482. /* No candidate table+column was found. This can only occur
  135483. ** on the second iteration */
  135484. assert( j==1 );
  135485. assert( IsPowerOfTwo(chngToIN) );
  135486. assert( chngToIN==sqlite3WhereGetMask(&pWInfo->sMaskSet, iCursor) );
  135487. break;
  135488. }
  135489. testcase( j==1 );
  135490. /* We have found a candidate table and column. Check to see if that
  135491. ** table and column is common to every term in the OR clause */
  135492. okToChngToIN = 1;
  135493. for(; i>=0 && okToChngToIN; i--, pOrTerm++){
  135494. assert( pOrTerm->eOperator & WO_EQ );
  135495. if( pOrTerm->leftCursor!=iCursor ){
  135496. pOrTerm->wtFlags &= ~TERM_OR_OK;
  135497. }else if( pOrTerm->u.leftColumn!=iColumn || (iColumn==XN_EXPR
  135498. && sqlite3ExprCompare(pParse, pOrTerm->pExpr->pLeft, pLeft, -1)
  135499. )){
  135500. okToChngToIN = 0;
  135501. }else{
  135502. int affLeft, affRight;
  135503. /* If the right-hand side is also a column, then the affinities
  135504. ** of both right and left sides must be such that no type
  135505. ** conversions are required on the right. (Ticket #2249)
  135506. */
  135507. affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
  135508. affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
  135509. if( affRight!=0 && affRight!=affLeft ){
  135510. okToChngToIN = 0;
  135511. }else{
  135512. pOrTerm->wtFlags |= TERM_OR_OK;
  135513. }
  135514. }
  135515. }
  135516. }
  135517. /* At this point, okToChngToIN is true if original pTerm satisfies
  135518. ** case 1. In that case, construct a new virtual term that is
  135519. ** pTerm converted into an IN operator.
  135520. */
  135521. if( okToChngToIN ){
  135522. Expr *pDup; /* A transient duplicate expression */
  135523. ExprList *pList = 0; /* The RHS of the IN operator */
  135524. Expr *pLeft = 0; /* The LHS of the IN operator */
  135525. Expr *pNew; /* The complete IN operator */
  135526. for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
  135527. if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
  135528. assert( pOrTerm->eOperator & WO_EQ );
  135529. assert( pOrTerm->leftCursor==iCursor );
  135530. assert( pOrTerm->u.leftColumn==iColumn );
  135531. pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
  135532. pList = sqlite3ExprListAppend(pWInfo->pParse, pList, pDup);
  135533. pLeft = pOrTerm->pExpr->pLeft;
  135534. }
  135535. assert( pLeft!=0 );
  135536. pDup = sqlite3ExprDup(db, pLeft, 0);
  135537. pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0);
  135538. if( pNew ){
  135539. int idxNew;
  135540. transferJoinMarkings(pNew, pExpr);
  135541. assert( !ExprHasProperty(pNew, EP_xIsSelect) );
  135542. pNew->x.pList = pList;
  135543. idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
  135544. testcase( idxNew==0 );
  135545. exprAnalyze(pSrc, pWC, idxNew);
  135546. /* pTerm = &pWC->a[idxTerm]; // would be needed if pTerm where used again */
  135547. markTermAsChild(pWC, idxNew, idxTerm);
  135548. }else{
  135549. sqlite3ExprListDelete(db, pList);
  135550. }
  135551. }
  135552. }
  135553. }
  135554. #endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
  135555. /*
  135556. ** We already know that pExpr is a binary operator where both operands are
  135557. ** column references. This routine checks to see if pExpr is an equivalence
  135558. ** relation:
  135559. ** 1. The SQLITE_Transitive optimization must be enabled
  135560. ** 2. Must be either an == or an IS operator
  135561. ** 3. Not originating in the ON clause of an OUTER JOIN
  135562. ** 4. The affinities of A and B must be compatible
  135563. ** 5a. Both operands use the same collating sequence OR
  135564. ** 5b. The overall collating sequence is BINARY
  135565. ** If this routine returns TRUE, that means that the RHS can be substituted
  135566. ** for the LHS anyplace else in the WHERE clause where the LHS column occurs.
  135567. ** This is an optimization. No harm comes from returning 0. But if 1 is
  135568. ** returned when it should not be, then incorrect answers might result.
  135569. */
  135570. static int termIsEquivalence(Parse *pParse, Expr *pExpr){
  135571. char aff1, aff2;
  135572. CollSeq *pColl;
  135573. if( !OptimizationEnabled(pParse->db, SQLITE_Transitive) ) return 0;
  135574. if( pExpr->op!=TK_EQ && pExpr->op!=TK_IS ) return 0;
  135575. if( ExprHasProperty(pExpr, EP_FromJoin) ) return 0;
  135576. aff1 = sqlite3ExprAffinity(pExpr->pLeft);
  135577. aff2 = sqlite3ExprAffinity(pExpr->pRight);
  135578. if( aff1!=aff2
  135579. && (!sqlite3IsNumericAffinity(aff1) || !sqlite3IsNumericAffinity(aff2))
  135580. ){
  135581. return 0;
  135582. }
  135583. pColl = sqlite3ExprCompareCollSeq(pParse, pExpr);
  135584. if( sqlite3IsBinary(pColl) ) return 1;
  135585. return sqlite3ExprCollSeqMatch(pParse, pExpr->pLeft, pExpr->pRight);
  135586. }
  135587. /*
  135588. ** Recursively walk the expressions of a SELECT statement and generate
  135589. ** a bitmask indicating which tables are used in that expression
  135590. ** tree.
  135591. */
  135592. static Bitmask exprSelectUsage(WhereMaskSet *pMaskSet, Select *pS){
  135593. Bitmask mask = 0;
  135594. while( pS ){
  135595. SrcList *pSrc = pS->pSrc;
  135596. mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pEList);
  135597. mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pGroupBy);
  135598. mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pOrderBy);
  135599. mask |= sqlite3WhereExprUsage(pMaskSet, pS->pWhere);
  135600. mask |= sqlite3WhereExprUsage(pMaskSet, pS->pHaving);
  135601. if( ALWAYS(pSrc!=0) ){
  135602. int i;
  135603. for(i=0; i<pSrc->nSrc; i++){
  135604. mask |= exprSelectUsage(pMaskSet, pSrc->a[i].pSelect);
  135605. mask |= sqlite3WhereExprUsage(pMaskSet, pSrc->a[i].pOn);
  135606. if( pSrc->a[i].fg.isTabFunc ){
  135607. mask |= sqlite3WhereExprListUsage(pMaskSet, pSrc->a[i].u1.pFuncArg);
  135608. }
  135609. }
  135610. }
  135611. pS = pS->pPrior;
  135612. }
  135613. return mask;
  135614. }
  135615. /*
  135616. ** Expression pExpr is one operand of a comparison operator that might
  135617. ** be useful for indexing. This routine checks to see if pExpr appears
  135618. ** in any index. Return TRUE (1) if pExpr is an indexed term and return
  135619. ** FALSE (0) if not. If TRUE is returned, also set aiCurCol[0] to the cursor
  135620. ** number of the table that is indexed and aiCurCol[1] to the column number
  135621. ** of the column that is indexed, or XN_EXPR (-2) if an expression is being
  135622. ** indexed.
  135623. **
  135624. ** If pExpr is a TK_COLUMN column reference, then this routine always returns
  135625. ** true even if that particular column is not indexed, because the column
  135626. ** might be added to an automatic index later.
  135627. */
  135628. static SQLITE_NOINLINE int exprMightBeIndexed2(
  135629. SrcList *pFrom, /* The FROM clause */
  135630. Bitmask mPrereq, /* Bitmask of FROM clause terms referenced by pExpr */
  135631. int *aiCurCol, /* Write the referenced table cursor and column here */
  135632. Expr *pExpr /* An operand of a comparison operator */
  135633. ){
  135634. Index *pIdx;
  135635. int i;
  135636. int iCur;
  135637. for(i=0; mPrereq>1; i++, mPrereq>>=1){}
  135638. iCur = pFrom->a[i].iCursor;
  135639. for(pIdx=pFrom->a[i].pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  135640. if( pIdx->aColExpr==0 ) continue;
  135641. for(i=0; i<pIdx->nKeyCol; i++){
  135642. if( pIdx->aiColumn[i]!=XN_EXPR ) continue;
  135643. if( sqlite3ExprCompareSkip(pExpr, pIdx->aColExpr->a[i].pExpr, iCur)==0 ){
  135644. aiCurCol[0] = iCur;
  135645. aiCurCol[1] = XN_EXPR;
  135646. return 1;
  135647. }
  135648. }
  135649. }
  135650. return 0;
  135651. }
  135652. static int exprMightBeIndexed(
  135653. SrcList *pFrom, /* The FROM clause */
  135654. Bitmask mPrereq, /* Bitmask of FROM clause terms referenced by pExpr */
  135655. int *aiCurCol, /* Write the referenced table cursor & column here */
  135656. Expr *pExpr, /* An operand of a comparison operator */
  135657. int op /* The specific comparison operator */
  135658. ){
  135659. /* If this expression is a vector to the left or right of a
  135660. ** inequality constraint (>, <, >= or <=), perform the processing
  135661. ** on the first element of the vector. */
  135662. assert( TK_GT+1==TK_LE && TK_GT+2==TK_LT && TK_GT+3==TK_GE );
  135663. assert( TK_IS<TK_GE && TK_ISNULL<TK_GE && TK_IN<TK_GE );
  135664. assert( op<=TK_GE );
  135665. if( pExpr->op==TK_VECTOR && (op>=TK_GT && ALWAYS(op<=TK_GE)) ){
  135666. pExpr = pExpr->x.pList->a[0].pExpr;
  135667. }
  135668. if( pExpr->op==TK_COLUMN ){
  135669. aiCurCol[0] = pExpr->iTable;
  135670. aiCurCol[1] = pExpr->iColumn;
  135671. return 1;
  135672. }
  135673. if( mPrereq==0 ) return 0; /* No table references */
  135674. if( (mPrereq&(mPrereq-1))!=0 ) return 0; /* Refs more than one table */
  135675. return exprMightBeIndexed2(pFrom,mPrereq,aiCurCol,pExpr);
  135676. }
  135677. /*
  135678. ** The input to this routine is an WhereTerm structure with only the
  135679. ** "pExpr" field filled in. The job of this routine is to analyze the
  135680. ** subexpression and populate all the other fields of the WhereTerm
  135681. ** structure.
  135682. **
  135683. ** If the expression is of the form "<expr> <op> X" it gets commuted
  135684. ** to the standard form of "X <op> <expr>".
  135685. **
  135686. ** If the expression is of the form "X <op> Y" where both X and Y are
  135687. ** columns, then the original expression is unchanged and a new virtual
  135688. ** term of the form "Y <op> X" is added to the WHERE clause and
  135689. ** analyzed separately. The original term is marked with TERM_COPIED
  135690. ** and the new term is marked with TERM_DYNAMIC (because it's pExpr
  135691. ** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
  135692. ** is a commuted copy of a prior term.) The original term has nChild=1
  135693. ** and the copy has idxParent set to the index of the original term.
  135694. */
  135695. static void exprAnalyze(
  135696. SrcList *pSrc, /* the FROM clause */
  135697. WhereClause *pWC, /* the WHERE clause */
  135698. int idxTerm /* Index of the term to be analyzed */
  135699. ){
  135700. WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
  135701. WhereTerm *pTerm; /* The term to be analyzed */
  135702. WhereMaskSet *pMaskSet; /* Set of table index masks */
  135703. Expr *pExpr; /* The expression to be analyzed */
  135704. Bitmask prereqLeft; /* Prerequesites of the pExpr->pLeft */
  135705. Bitmask prereqAll; /* Prerequesites of pExpr */
  135706. Bitmask extraRight = 0; /* Extra dependencies on LEFT JOIN */
  135707. Expr *pStr1 = 0; /* RHS of LIKE/GLOB operator */
  135708. int isComplete = 0; /* RHS of LIKE/GLOB ends with wildcard */
  135709. int noCase = 0; /* uppercase equivalent to lowercase */
  135710. int op; /* Top-level operator. pExpr->op */
  135711. Parse *pParse = pWInfo->pParse; /* Parsing context */
  135712. sqlite3 *db = pParse->db; /* Database connection */
  135713. unsigned char eOp2 = 0; /* op2 value for LIKE/REGEXP/GLOB */
  135714. int nLeft; /* Number of elements on left side vector */
  135715. if( db->mallocFailed ){
  135716. return;
  135717. }
  135718. pTerm = &pWC->a[idxTerm];
  135719. pMaskSet = &pWInfo->sMaskSet;
  135720. pExpr = pTerm->pExpr;
  135721. assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE );
  135722. prereqLeft = sqlite3WhereExprUsage(pMaskSet, pExpr->pLeft);
  135723. op = pExpr->op;
  135724. if( op==TK_IN ){
  135725. assert( pExpr->pRight==0 );
  135726. if( sqlite3ExprCheckIN(pParse, pExpr) ) return;
  135727. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  135728. pTerm->prereqRight = exprSelectUsage(pMaskSet, pExpr->x.pSelect);
  135729. }else{
  135730. pTerm->prereqRight = sqlite3WhereExprListUsage(pMaskSet, pExpr->x.pList);
  135731. }
  135732. }else if( op==TK_ISNULL ){
  135733. pTerm->prereqRight = 0;
  135734. }else{
  135735. pTerm->prereqRight = sqlite3WhereExprUsage(pMaskSet, pExpr->pRight);
  135736. }
  135737. pMaskSet->bVarSelect = 0;
  135738. prereqAll = sqlite3WhereExprUsageNN(pMaskSet, pExpr);
  135739. if( pMaskSet->bVarSelect ) pTerm->wtFlags |= TERM_VARSELECT;
  135740. if( ExprHasProperty(pExpr, EP_FromJoin) ){
  135741. Bitmask x = sqlite3WhereGetMask(pMaskSet, pExpr->iRightJoinTable);
  135742. prereqAll |= x;
  135743. extraRight = x-1; /* ON clause terms may not be used with an index
  135744. ** on left table of a LEFT JOIN. Ticket #3015 */
  135745. if( (prereqAll>>1)>=x ){
  135746. sqlite3ErrorMsg(pParse, "ON clause references tables to its right");
  135747. return;
  135748. }
  135749. }
  135750. pTerm->prereqAll = prereqAll;
  135751. pTerm->leftCursor = -1;
  135752. pTerm->iParent = -1;
  135753. pTerm->eOperator = 0;
  135754. if( allowedOp(op) ){
  135755. int aiCurCol[2];
  135756. Expr *pLeft = sqlite3ExprSkipCollate(pExpr->pLeft);
  135757. Expr *pRight = sqlite3ExprSkipCollate(pExpr->pRight);
  135758. u16 opMask = (pTerm->prereqRight & prereqLeft)==0 ? WO_ALL : WO_EQUIV;
  135759. if( pTerm->iField>0 ){
  135760. assert( op==TK_IN );
  135761. assert( pLeft->op==TK_VECTOR );
  135762. pLeft = pLeft->x.pList->a[pTerm->iField-1].pExpr;
  135763. }
  135764. if( exprMightBeIndexed(pSrc, prereqLeft, aiCurCol, pLeft, op) ){
  135765. pTerm->leftCursor = aiCurCol[0];
  135766. pTerm->u.leftColumn = aiCurCol[1];
  135767. pTerm->eOperator = operatorMask(op) & opMask;
  135768. }
  135769. if( op==TK_IS ) pTerm->wtFlags |= TERM_IS;
  135770. if( pRight
  135771. && exprMightBeIndexed(pSrc, pTerm->prereqRight, aiCurCol, pRight, op)
  135772. ){
  135773. WhereTerm *pNew;
  135774. Expr *pDup;
  135775. u16 eExtraOp = 0; /* Extra bits for pNew->eOperator */
  135776. assert( pTerm->iField==0 );
  135777. if( pTerm->leftCursor>=0 ){
  135778. int idxNew;
  135779. pDup = sqlite3ExprDup(db, pExpr, 0);
  135780. if( db->mallocFailed ){
  135781. sqlite3ExprDelete(db, pDup);
  135782. return;
  135783. }
  135784. idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
  135785. if( idxNew==0 ) return;
  135786. pNew = &pWC->a[idxNew];
  135787. markTermAsChild(pWC, idxNew, idxTerm);
  135788. if( op==TK_IS ) pNew->wtFlags |= TERM_IS;
  135789. pTerm = &pWC->a[idxTerm];
  135790. pTerm->wtFlags |= TERM_COPIED;
  135791. if( termIsEquivalence(pParse, pDup) ){
  135792. pTerm->eOperator |= WO_EQUIV;
  135793. eExtraOp = WO_EQUIV;
  135794. }
  135795. }else{
  135796. pDup = pExpr;
  135797. pNew = pTerm;
  135798. }
  135799. pNew->wtFlags |= exprCommute(pParse, pDup);
  135800. pNew->leftCursor = aiCurCol[0];
  135801. pNew->u.leftColumn = aiCurCol[1];
  135802. testcase( (prereqLeft | extraRight) != prereqLeft );
  135803. pNew->prereqRight = prereqLeft | extraRight;
  135804. pNew->prereqAll = prereqAll;
  135805. pNew->eOperator = (operatorMask(pDup->op) + eExtraOp) & opMask;
  135806. }
  135807. }
  135808. #ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
  135809. /* If a term is the BETWEEN operator, create two new virtual terms
  135810. ** that define the range that the BETWEEN implements. For example:
  135811. **
  135812. ** a BETWEEN b AND c
  135813. **
  135814. ** is converted into:
  135815. **
  135816. ** (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
  135817. **
  135818. ** The two new terms are added onto the end of the WhereClause object.
  135819. ** The new terms are "dynamic" and are children of the original BETWEEN
  135820. ** term. That means that if the BETWEEN term is coded, the children are
  135821. ** skipped. Or, if the children are satisfied by an index, the original
  135822. ** BETWEEN term is skipped.
  135823. */
  135824. else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
  135825. ExprList *pList = pExpr->x.pList;
  135826. int i;
  135827. static const u8 ops[] = {TK_GE, TK_LE};
  135828. assert( pList!=0 );
  135829. assert( pList->nExpr==2 );
  135830. for(i=0; i<2; i++){
  135831. Expr *pNewExpr;
  135832. int idxNew;
  135833. pNewExpr = sqlite3PExpr(pParse, ops[i],
  135834. sqlite3ExprDup(db, pExpr->pLeft, 0),
  135835. sqlite3ExprDup(db, pList->a[i].pExpr, 0));
  135836. transferJoinMarkings(pNewExpr, pExpr);
  135837. idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
  135838. testcase( idxNew==0 );
  135839. exprAnalyze(pSrc, pWC, idxNew);
  135840. pTerm = &pWC->a[idxTerm];
  135841. markTermAsChild(pWC, idxNew, idxTerm);
  135842. }
  135843. }
  135844. #endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
  135845. #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
  135846. /* Analyze a term that is composed of two or more subterms connected by
  135847. ** an OR operator.
  135848. */
  135849. else if( pExpr->op==TK_OR ){
  135850. assert( pWC->op==TK_AND );
  135851. exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
  135852. pTerm = &pWC->a[idxTerm];
  135853. }
  135854. #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
  135855. #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
  135856. /* Add constraints to reduce the search space on a LIKE or GLOB
  135857. ** operator.
  135858. **
  135859. ** A like pattern of the form "x LIKE 'aBc%'" is changed into constraints
  135860. **
  135861. ** x>='ABC' AND x<'abd' AND x LIKE 'aBc%'
  135862. **
  135863. ** The last character of the prefix "abc" is incremented to form the
  135864. ** termination condition "abd". If case is not significant (the default
  135865. ** for LIKE) then the lower-bound is made all uppercase and the upper-
  135866. ** bound is made all lowercase so that the bounds also work when comparing
  135867. ** BLOBs.
  135868. */
  135869. if( pWC->op==TK_AND
  135870. && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
  135871. ){
  135872. Expr *pLeft; /* LHS of LIKE/GLOB operator */
  135873. Expr *pStr2; /* Copy of pStr1 - RHS of LIKE/GLOB operator */
  135874. Expr *pNewExpr1;
  135875. Expr *pNewExpr2;
  135876. int idxNew1;
  135877. int idxNew2;
  135878. const char *zCollSeqName; /* Name of collating sequence */
  135879. const u16 wtFlags = TERM_LIKEOPT | TERM_VIRTUAL | TERM_DYNAMIC;
  135880. pLeft = pExpr->x.pList->a[1].pExpr;
  135881. pStr2 = sqlite3ExprDup(db, pStr1, 0);
  135882. /* Convert the lower bound to upper-case and the upper bound to
  135883. ** lower-case (upper-case is less than lower-case in ASCII) so that
  135884. ** the range constraints also work for BLOBs
  135885. */
  135886. if( noCase && !pParse->db->mallocFailed ){
  135887. int i;
  135888. char c;
  135889. pTerm->wtFlags |= TERM_LIKE;
  135890. for(i=0; (c = pStr1->u.zToken[i])!=0; i++){
  135891. pStr1->u.zToken[i] = sqlite3Toupper(c);
  135892. pStr2->u.zToken[i] = sqlite3Tolower(c);
  135893. }
  135894. }
  135895. if( !db->mallocFailed ){
  135896. u8 c, *pC; /* Last character before the first wildcard */
  135897. pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
  135898. c = *pC;
  135899. if( noCase ){
  135900. /* The point is to increment the last character before the first
  135901. ** wildcard. But if we increment '@', that will push it into the
  135902. ** alphabetic range where case conversions will mess up the
  135903. ** inequality. To avoid this, make sure to also run the full
  135904. ** LIKE on all candidate expressions by clearing the isComplete flag
  135905. */
  135906. if( c=='A'-1 ) isComplete = 0;
  135907. c = sqlite3UpperToLower[c];
  135908. }
  135909. *pC = c + 1;
  135910. }
  135911. zCollSeqName = noCase ? "NOCASE" : sqlite3StrBINARY;
  135912. pNewExpr1 = sqlite3ExprDup(db, pLeft, 0);
  135913. pNewExpr1 = sqlite3PExpr(pParse, TK_GE,
  135914. sqlite3ExprAddCollateString(pParse,pNewExpr1,zCollSeqName),
  135915. pStr1);
  135916. transferJoinMarkings(pNewExpr1, pExpr);
  135917. idxNew1 = whereClauseInsert(pWC, pNewExpr1, wtFlags);
  135918. testcase( idxNew1==0 );
  135919. exprAnalyze(pSrc, pWC, idxNew1);
  135920. pNewExpr2 = sqlite3ExprDup(db, pLeft, 0);
  135921. pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
  135922. sqlite3ExprAddCollateString(pParse,pNewExpr2,zCollSeqName),
  135923. pStr2);
  135924. transferJoinMarkings(pNewExpr2, pExpr);
  135925. idxNew2 = whereClauseInsert(pWC, pNewExpr2, wtFlags);
  135926. testcase( idxNew2==0 );
  135927. exprAnalyze(pSrc, pWC, idxNew2);
  135928. pTerm = &pWC->a[idxTerm];
  135929. if( isComplete ){
  135930. markTermAsChild(pWC, idxNew1, idxTerm);
  135931. markTermAsChild(pWC, idxNew2, idxTerm);
  135932. }
  135933. }
  135934. #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
  135935. #ifndef SQLITE_OMIT_VIRTUALTABLE
  135936. /* Add a WO_AUX auxiliary term to the constraint set if the
  135937. ** current expression is of the form "column OP expr" where OP
  135938. ** is an operator that gets passed into virtual tables but which is
  135939. ** not normally optimized for ordinary tables. In other words, OP
  135940. ** is one of MATCH, LIKE, GLOB, REGEXP, !=, IS, IS NOT, or NOT NULL.
  135941. ** This information is used by the xBestIndex methods of
  135942. ** virtual tables. The native query optimizer does not attempt
  135943. ** to do anything with MATCH functions.
  135944. */
  135945. if( pWC->op==TK_AND ){
  135946. Expr *pRight = 0, *pLeft = 0;
  135947. int res = isAuxiliaryVtabOperator(db, pExpr, &eOp2, &pLeft, &pRight);
  135948. while( res-- > 0 ){
  135949. int idxNew;
  135950. WhereTerm *pNewTerm;
  135951. Bitmask prereqColumn, prereqExpr;
  135952. prereqExpr = sqlite3WhereExprUsage(pMaskSet, pRight);
  135953. prereqColumn = sqlite3WhereExprUsage(pMaskSet, pLeft);
  135954. if( (prereqExpr & prereqColumn)==0 ){
  135955. Expr *pNewExpr;
  135956. pNewExpr = sqlite3PExpr(pParse, TK_MATCH,
  135957. 0, sqlite3ExprDup(db, pRight, 0));
  135958. if( ExprHasProperty(pExpr, EP_FromJoin) && pNewExpr ){
  135959. ExprSetProperty(pNewExpr, EP_FromJoin);
  135960. pNewExpr->iRightJoinTable = pExpr->iRightJoinTable;
  135961. }
  135962. idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
  135963. testcase( idxNew==0 );
  135964. pNewTerm = &pWC->a[idxNew];
  135965. pNewTerm->prereqRight = prereqExpr;
  135966. pNewTerm->leftCursor = pLeft->iTable;
  135967. pNewTerm->u.leftColumn = pLeft->iColumn;
  135968. pNewTerm->eOperator = WO_AUX;
  135969. pNewTerm->eMatchOp = eOp2;
  135970. markTermAsChild(pWC, idxNew, idxTerm);
  135971. pTerm = &pWC->a[idxTerm];
  135972. pTerm->wtFlags |= TERM_COPIED;
  135973. pNewTerm->prereqAll = pTerm->prereqAll;
  135974. }
  135975. SWAP(Expr*, pLeft, pRight);
  135976. }
  135977. }
  135978. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  135979. /* If there is a vector == or IS term - e.g. "(a, b) == (?, ?)" - create
  135980. ** new terms for each component comparison - "a = ?" and "b = ?". The
  135981. ** new terms completely replace the original vector comparison, which is
  135982. ** no longer used.
  135983. **
  135984. ** This is only required if at least one side of the comparison operation
  135985. ** is not a sub-select. */
  135986. if( pWC->op==TK_AND
  135987. && (pExpr->op==TK_EQ || pExpr->op==TK_IS)
  135988. && (nLeft = sqlite3ExprVectorSize(pExpr->pLeft))>1
  135989. && sqlite3ExprVectorSize(pExpr->pRight)==nLeft
  135990. && ( (pExpr->pLeft->flags & EP_xIsSelect)==0
  135991. || (pExpr->pRight->flags & EP_xIsSelect)==0)
  135992. ){
  135993. int i;
  135994. for(i=0; i<nLeft; i++){
  135995. int idxNew;
  135996. Expr *pNew;
  135997. Expr *pLeft = sqlite3ExprForVectorField(pParse, pExpr->pLeft, i);
  135998. Expr *pRight = sqlite3ExprForVectorField(pParse, pExpr->pRight, i);
  135999. pNew = sqlite3PExpr(pParse, pExpr->op, pLeft, pRight);
  136000. transferJoinMarkings(pNew, pExpr);
  136001. idxNew = whereClauseInsert(pWC, pNew, TERM_DYNAMIC);
  136002. exprAnalyze(pSrc, pWC, idxNew);
  136003. }
  136004. pTerm = &pWC->a[idxTerm];
  136005. pTerm->wtFlags |= TERM_CODED|TERM_VIRTUAL; /* Disable the original */
  136006. pTerm->eOperator = 0;
  136007. }
  136008. /* If there is a vector IN term - e.g. "(a, b) IN (SELECT ...)" - create
  136009. ** a virtual term for each vector component. The expression object
  136010. ** used by each such virtual term is pExpr (the full vector IN(...)
  136011. ** expression). The WhereTerm.iField variable identifies the index within
  136012. ** the vector on the LHS that the virtual term represents.
  136013. **
  136014. ** This only works if the RHS is a simple SELECT (not a compound) that does
  136015. ** not use window functions.
  136016. */
  136017. if( pWC->op==TK_AND && pExpr->op==TK_IN && pTerm->iField==0
  136018. && pExpr->pLeft->op==TK_VECTOR
  136019. && pExpr->x.pSelect->pPrior==0
  136020. #ifndef SQLITE_OMIT_WINDOWFUNC
  136021. && pExpr->x.pSelect->pWin==0
  136022. #endif
  136023. ){
  136024. int i;
  136025. for(i=0; i<sqlite3ExprVectorSize(pExpr->pLeft); i++){
  136026. int idxNew;
  136027. idxNew = whereClauseInsert(pWC, pExpr, TERM_VIRTUAL);
  136028. pWC->a[idxNew].iField = i+1;
  136029. exprAnalyze(pSrc, pWC, idxNew);
  136030. markTermAsChild(pWC, idxNew, idxTerm);
  136031. }
  136032. }
  136033. #ifdef SQLITE_ENABLE_STAT4
  136034. /* When sqlite_stat4 histogram data is available an operator of the
  136035. ** form "x IS NOT NULL" can sometimes be evaluated more efficiently
  136036. ** as "x>NULL" if x is not an INTEGER PRIMARY KEY. So construct a
  136037. ** virtual term of that form.
  136038. **
  136039. ** Note that the virtual term must be tagged with TERM_VNULL.
  136040. */
  136041. if( pExpr->op==TK_NOTNULL
  136042. && pExpr->pLeft->op==TK_COLUMN
  136043. && pExpr->pLeft->iColumn>=0
  136044. && !ExprHasProperty(pExpr, EP_FromJoin)
  136045. && OptimizationEnabled(db, SQLITE_Stat4)
  136046. ){
  136047. Expr *pNewExpr;
  136048. Expr *pLeft = pExpr->pLeft;
  136049. int idxNew;
  136050. WhereTerm *pNewTerm;
  136051. pNewExpr = sqlite3PExpr(pParse, TK_GT,
  136052. sqlite3ExprDup(db, pLeft, 0),
  136053. sqlite3ExprAlloc(db, TK_NULL, 0, 0));
  136054. idxNew = whereClauseInsert(pWC, pNewExpr,
  136055. TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
  136056. if( idxNew ){
  136057. pNewTerm = &pWC->a[idxNew];
  136058. pNewTerm->prereqRight = 0;
  136059. pNewTerm->leftCursor = pLeft->iTable;
  136060. pNewTerm->u.leftColumn = pLeft->iColumn;
  136061. pNewTerm->eOperator = WO_GT;
  136062. markTermAsChild(pWC, idxNew, idxTerm);
  136063. pTerm = &pWC->a[idxTerm];
  136064. pTerm->wtFlags |= TERM_COPIED;
  136065. pNewTerm->prereqAll = pTerm->prereqAll;
  136066. }
  136067. }
  136068. #endif /* SQLITE_ENABLE_STAT4 */
  136069. /* Prevent ON clause terms of a LEFT JOIN from being used to drive
  136070. ** an index for tables to the left of the join.
  136071. */
  136072. testcase( pTerm!=&pWC->a[idxTerm] );
  136073. pTerm = &pWC->a[idxTerm];
  136074. pTerm->prereqRight |= extraRight;
  136075. }
  136076. /***************************************************************************
  136077. ** Routines with file scope above. Interface to the rest of the where.c
  136078. ** subsystem follows.
  136079. ***************************************************************************/
  136080. /*
  136081. ** This routine identifies subexpressions in the WHERE clause where
  136082. ** each subexpression is separated by the AND operator or some other
  136083. ** operator specified in the op parameter. The WhereClause structure
  136084. ** is filled with pointers to subexpressions. For example:
  136085. **
  136086. ** WHERE a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
  136087. ** \________/ \_______________/ \________________/
  136088. ** slot[0] slot[1] slot[2]
  136089. **
  136090. ** The original WHERE clause in pExpr is unaltered. All this routine
  136091. ** does is make slot[] entries point to substructure within pExpr.
  136092. **
  136093. ** In the previous sentence and in the diagram, "slot[]" refers to
  136094. ** the WhereClause.a[] array. The slot[] array grows as needed to contain
  136095. ** all terms of the WHERE clause.
  136096. */
  136097. SQLITE_PRIVATE void sqlite3WhereSplit(WhereClause *pWC, Expr *pExpr, u8 op){
  136098. Expr *pE2 = sqlite3ExprSkipCollateAndLikely(pExpr);
  136099. pWC->op = op;
  136100. if( pE2==0 ) return;
  136101. if( pE2->op!=op ){
  136102. whereClauseInsert(pWC, pExpr, 0);
  136103. }else{
  136104. sqlite3WhereSplit(pWC, pE2->pLeft, op);
  136105. sqlite3WhereSplit(pWC, pE2->pRight, op);
  136106. }
  136107. }
  136108. /*
  136109. ** Initialize a preallocated WhereClause structure.
  136110. */
  136111. SQLITE_PRIVATE void sqlite3WhereClauseInit(
  136112. WhereClause *pWC, /* The WhereClause to be initialized */
  136113. WhereInfo *pWInfo /* The WHERE processing context */
  136114. ){
  136115. pWC->pWInfo = pWInfo;
  136116. pWC->hasOr = 0;
  136117. pWC->pOuter = 0;
  136118. pWC->nTerm = 0;
  136119. pWC->nSlot = ArraySize(pWC->aStatic);
  136120. pWC->a = pWC->aStatic;
  136121. }
  136122. /*
  136123. ** Deallocate a WhereClause structure. The WhereClause structure
  136124. ** itself is not freed. This routine is the inverse of
  136125. ** sqlite3WhereClauseInit().
  136126. */
  136127. SQLITE_PRIVATE void sqlite3WhereClauseClear(WhereClause *pWC){
  136128. int i;
  136129. WhereTerm *a;
  136130. sqlite3 *db = pWC->pWInfo->pParse->db;
  136131. for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
  136132. if( a->wtFlags & TERM_DYNAMIC ){
  136133. sqlite3ExprDelete(db, a->pExpr);
  136134. }
  136135. if( a->wtFlags & TERM_ORINFO ){
  136136. whereOrInfoDelete(db, a->u.pOrInfo);
  136137. }else if( a->wtFlags & TERM_ANDINFO ){
  136138. whereAndInfoDelete(db, a->u.pAndInfo);
  136139. }
  136140. }
  136141. if( pWC->a!=pWC->aStatic ){
  136142. sqlite3DbFree(db, pWC->a);
  136143. }
  136144. }
  136145. /*
  136146. ** These routines walk (recursively) an expression tree and generate
  136147. ** a bitmask indicating which tables are used in that expression
  136148. ** tree.
  136149. */
  136150. SQLITE_PRIVATE Bitmask sqlite3WhereExprUsageNN(WhereMaskSet *pMaskSet, Expr *p){
  136151. Bitmask mask;
  136152. if( p->op==TK_COLUMN && !ExprHasProperty(p, EP_FixedCol) ){
  136153. return sqlite3WhereGetMask(pMaskSet, p->iTable);
  136154. }else if( ExprHasProperty(p, EP_TokenOnly|EP_Leaf) ){
  136155. assert( p->op!=TK_IF_NULL_ROW );
  136156. return 0;
  136157. }
  136158. mask = (p->op==TK_IF_NULL_ROW) ? sqlite3WhereGetMask(pMaskSet, p->iTable) : 0;
  136159. if( p->pLeft ) mask |= sqlite3WhereExprUsageNN(pMaskSet, p->pLeft);
  136160. if( p->pRight ){
  136161. mask |= sqlite3WhereExprUsageNN(pMaskSet, p->pRight);
  136162. assert( p->x.pList==0 );
  136163. }else if( ExprHasProperty(p, EP_xIsSelect) ){
  136164. if( ExprHasProperty(p, EP_VarSelect) ) pMaskSet->bVarSelect = 1;
  136165. mask |= exprSelectUsage(pMaskSet, p->x.pSelect);
  136166. }else if( p->x.pList ){
  136167. mask |= sqlite3WhereExprListUsage(pMaskSet, p->x.pList);
  136168. }
  136169. #ifndef SQLITE_OMIT_WINDOWFUNC
  136170. if( (p->op==TK_FUNCTION || p->op==TK_AGG_FUNCTION) && p->y.pWin ){
  136171. mask |= sqlite3WhereExprListUsage(pMaskSet, p->y.pWin->pPartition);
  136172. mask |= sqlite3WhereExprListUsage(pMaskSet, p->y.pWin->pOrderBy);
  136173. mask |= sqlite3WhereExprUsage(pMaskSet, p->y.pWin->pFilter);
  136174. }
  136175. #endif
  136176. return mask;
  136177. }
  136178. SQLITE_PRIVATE Bitmask sqlite3WhereExprUsage(WhereMaskSet *pMaskSet, Expr *p){
  136179. return p ? sqlite3WhereExprUsageNN(pMaskSet,p) : 0;
  136180. }
  136181. SQLITE_PRIVATE Bitmask sqlite3WhereExprListUsage(WhereMaskSet *pMaskSet, ExprList *pList){
  136182. int i;
  136183. Bitmask mask = 0;
  136184. if( pList ){
  136185. for(i=0; i<pList->nExpr; i++){
  136186. mask |= sqlite3WhereExprUsage(pMaskSet, pList->a[i].pExpr);
  136187. }
  136188. }
  136189. return mask;
  136190. }
  136191. /*
  136192. ** Call exprAnalyze on all terms in a WHERE clause.
  136193. **
  136194. ** Note that exprAnalyze() might add new virtual terms onto the
  136195. ** end of the WHERE clause. We do not want to analyze these new
  136196. ** virtual terms, so start analyzing at the end and work forward
  136197. ** so that the added virtual terms are never processed.
  136198. */
  136199. SQLITE_PRIVATE void sqlite3WhereExprAnalyze(
  136200. SrcList *pTabList, /* the FROM clause */
  136201. WhereClause *pWC /* the WHERE clause to be analyzed */
  136202. ){
  136203. int i;
  136204. for(i=pWC->nTerm-1; i>=0; i--){
  136205. exprAnalyze(pTabList, pWC, i);
  136206. }
  136207. }
  136208. /*
  136209. ** For table-valued-functions, transform the function arguments into
  136210. ** new WHERE clause terms.
  136211. **
  136212. ** Each function argument translates into an equality constraint against
  136213. ** a HIDDEN column in the table.
  136214. */
  136215. SQLITE_PRIVATE void sqlite3WhereTabFuncArgs(
  136216. Parse *pParse, /* Parsing context */
  136217. struct SrcList_item *pItem, /* The FROM clause term to process */
  136218. WhereClause *pWC /* Xfer function arguments to here */
  136219. ){
  136220. Table *pTab;
  136221. int j, k;
  136222. ExprList *pArgs;
  136223. Expr *pColRef;
  136224. Expr *pTerm;
  136225. if( pItem->fg.isTabFunc==0 ) return;
  136226. pTab = pItem->pTab;
  136227. assert( pTab!=0 );
  136228. pArgs = pItem->u1.pFuncArg;
  136229. if( pArgs==0 ) return;
  136230. for(j=k=0; j<pArgs->nExpr; j++){
  136231. Expr *pRhs;
  136232. while( k<pTab->nCol && (pTab->aCol[k].colFlags & COLFLAG_HIDDEN)==0 ){k++;}
  136233. if( k>=pTab->nCol ){
  136234. sqlite3ErrorMsg(pParse, "too many arguments on %s() - max %d",
  136235. pTab->zName, j);
  136236. return;
  136237. }
  136238. pColRef = sqlite3ExprAlloc(pParse->db, TK_COLUMN, 0, 0);
  136239. if( pColRef==0 ) return;
  136240. pColRef->iTable = pItem->iCursor;
  136241. pColRef->iColumn = k++;
  136242. pColRef->y.pTab = pTab;
  136243. pRhs = sqlite3PExpr(pParse, TK_UPLUS,
  136244. sqlite3ExprDup(pParse->db, pArgs->a[j].pExpr, 0), 0);
  136245. pTerm = sqlite3PExpr(pParse, TK_EQ, pColRef, pRhs);
  136246. if( pItem->fg.jointype & JT_LEFT ){
  136247. sqlite3SetJoinExpr(pTerm, pItem->iCursor);
  136248. }
  136249. whereClauseInsert(pWC, pTerm, TERM_DYNAMIC);
  136250. }
  136251. }
  136252. /************** End of whereexpr.c *******************************************/
  136253. /************** Begin file where.c *******************************************/
  136254. /*
  136255. ** 2001 September 15
  136256. **
  136257. ** The author disclaims copyright to this source code. In place of
  136258. ** a legal notice, here is a blessing:
  136259. **
  136260. ** May you do good and not evil.
  136261. ** May you find forgiveness for yourself and forgive others.
  136262. ** May you share freely, never taking more than you give.
  136263. **
  136264. *************************************************************************
  136265. ** This module contains C code that generates VDBE code used to process
  136266. ** the WHERE clause of SQL statements. This module is responsible for
  136267. ** generating the code that loops through a table looking for applicable
  136268. ** rows. Indices are selected and used to speed the search when doing
  136269. ** so is applicable. Because this module is responsible for selecting
  136270. ** indices, you might also think of this module as the "query optimizer".
  136271. */
  136272. /* #include "sqliteInt.h" */
  136273. /* #include "whereInt.h" */
  136274. /*
  136275. ** Extra information appended to the end of sqlite3_index_info but not
  136276. ** visible to the xBestIndex function, at least not directly. The
  136277. ** sqlite3_vtab_collation() interface knows how to reach it, however.
  136278. **
  136279. ** This object is not an API and can be changed from one release to the
  136280. ** next. As long as allocateIndexInfo() and sqlite3_vtab_collation()
  136281. ** agree on the structure, all will be well.
  136282. */
  136283. typedef struct HiddenIndexInfo HiddenIndexInfo;
  136284. struct HiddenIndexInfo {
  136285. WhereClause *pWC; /* The Where clause being analyzed */
  136286. Parse *pParse; /* The parsing context */
  136287. };
  136288. /* Forward declaration of methods */
  136289. static int whereLoopResize(sqlite3*, WhereLoop*, int);
  136290. /* Test variable that can be set to enable WHERE tracing */
  136291. #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
  136292. /***/ int sqlite3WhereTrace = 0;
  136293. #endif
  136294. /*
  136295. ** Return the estimated number of output rows from a WHERE clause
  136296. */
  136297. SQLITE_PRIVATE LogEst sqlite3WhereOutputRowCount(WhereInfo *pWInfo){
  136298. return pWInfo->nRowOut;
  136299. }
  136300. /*
  136301. ** Return one of the WHERE_DISTINCT_xxxxx values to indicate how this
  136302. ** WHERE clause returns outputs for DISTINCT processing.
  136303. */
  136304. SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo *pWInfo){
  136305. return pWInfo->eDistinct;
  136306. }
  136307. /*
  136308. ** Return TRUE if the WHERE clause returns rows in ORDER BY order.
  136309. ** Return FALSE if the output needs to be sorted.
  136310. */
  136311. SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo *pWInfo){
  136312. return pWInfo->nOBSat;
  136313. }
  136314. /*
  136315. ** In the ORDER BY LIMIT optimization, if the inner-most loop is known
  136316. ** to emit rows in increasing order, and if the last row emitted by the
  136317. ** inner-most loop did not fit within the sorter, then we can skip all
  136318. ** subsequent rows for the current iteration of the inner loop (because they
  136319. ** will not fit in the sorter either) and continue with the second inner
  136320. ** loop - the loop immediately outside the inner-most.
  136321. **
  136322. ** When a row does not fit in the sorter (because the sorter already
  136323. ** holds LIMIT+OFFSET rows that are smaller), then a jump is made to the
  136324. ** label returned by this function.
  136325. **
  136326. ** If the ORDER BY LIMIT optimization applies, the jump destination should
  136327. ** be the continuation for the second-inner-most loop. If the ORDER BY
  136328. ** LIMIT optimization does not apply, then the jump destination should
  136329. ** be the continuation for the inner-most loop.
  136330. **
  136331. ** It is always safe for this routine to return the continuation of the
  136332. ** inner-most loop, in the sense that a correct answer will result.
  136333. ** Returning the continuation the second inner loop is an optimization
  136334. ** that might make the code run a little faster, but should not change
  136335. ** the final answer.
  136336. */
  136337. SQLITE_PRIVATE int sqlite3WhereOrderByLimitOptLabel(WhereInfo *pWInfo){
  136338. WhereLevel *pInner;
  136339. if( !pWInfo->bOrderedInnerLoop ){
  136340. /* The ORDER BY LIMIT optimization does not apply. Jump to the
  136341. ** continuation of the inner-most loop. */
  136342. return pWInfo->iContinue;
  136343. }
  136344. pInner = &pWInfo->a[pWInfo->nLevel-1];
  136345. assert( pInner->addrNxt!=0 );
  136346. return pInner->addrNxt;
  136347. }
  136348. /*
  136349. ** Return the VDBE address or label to jump to in order to continue
  136350. ** immediately with the next row of a WHERE clause.
  136351. */
  136352. SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo *pWInfo){
  136353. assert( pWInfo->iContinue!=0 );
  136354. return pWInfo->iContinue;
  136355. }
  136356. /*
  136357. ** Return the VDBE address or label to jump to in order to break
  136358. ** out of a WHERE loop.
  136359. */
  136360. SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo *pWInfo){
  136361. return pWInfo->iBreak;
  136362. }
  136363. /*
  136364. ** Return ONEPASS_OFF (0) if an UPDATE or DELETE statement is unable to
  136365. ** operate directly on the rowids returned by a WHERE clause. Return
  136366. ** ONEPASS_SINGLE (1) if the statement can operation directly because only
  136367. ** a single row is to be changed. Return ONEPASS_MULTI (2) if the one-pass
  136368. ** optimization can be used on multiple
  136369. **
  136370. ** If the ONEPASS optimization is used (if this routine returns true)
  136371. ** then also write the indices of open cursors used by ONEPASS
  136372. ** into aiCur[0] and aiCur[1]. iaCur[0] gets the cursor of the data
  136373. ** table and iaCur[1] gets the cursor used by an auxiliary index.
  136374. ** Either value may be -1, indicating that cursor is not used.
  136375. ** Any cursors returned will have been opened for writing.
  136376. **
  136377. ** aiCur[0] and aiCur[1] both get -1 if the where-clause logic is
  136378. ** unable to use the ONEPASS optimization.
  136379. */
  136380. SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo *pWInfo, int *aiCur){
  136381. memcpy(aiCur, pWInfo->aiCurOnePass, sizeof(int)*2);
  136382. #ifdef WHERETRACE_ENABLED
  136383. if( sqlite3WhereTrace && pWInfo->eOnePass!=ONEPASS_OFF ){
  136384. sqlite3DebugPrintf("%s cursors: %d %d\n",
  136385. pWInfo->eOnePass==ONEPASS_SINGLE ? "ONEPASS_SINGLE" : "ONEPASS_MULTI",
  136386. aiCur[0], aiCur[1]);
  136387. }
  136388. #endif
  136389. return pWInfo->eOnePass;
  136390. }
  136391. /*
  136392. ** Return TRUE if the WHERE loop uses the OP_DeferredSeek opcode to move
  136393. ** the data cursor to the row selected by the index cursor.
  136394. */
  136395. SQLITE_PRIVATE int sqlite3WhereUsesDeferredSeek(WhereInfo *pWInfo){
  136396. return pWInfo->bDeferredSeek;
  136397. }
  136398. /*
  136399. ** Move the content of pSrc into pDest
  136400. */
  136401. static void whereOrMove(WhereOrSet *pDest, WhereOrSet *pSrc){
  136402. pDest->n = pSrc->n;
  136403. memcpy(pDest->a, pSrc->a, pDest->n*sizeof(pDest->a[0]));
  136404. }
  136405. /*
  136406. ** Try to insert a new prerequisite/cost entry into the WhereOrSet pSet.
  136407. **
  136408. ** The new entry might overwrite an existing entry, or it might be
  136409. ** appended, or it might be discarded. Do whatever is the right thing
  136410. ** so that pSet keeps the N_OR_COST best entries seen so far.
  136411. */
  136412. static int whereOrInsert(
  136413. WhereOrSet *pSet, /* The WhereOrSet to be updated */
  136414. Bitmask prereq, /* Prerequisites of the new entry */
  136415. LogEst rRun, /* Run-cost of the new entry */
  136416. LogEst nOut /* Number of outputs for the new entry */
  136417. ){
  136418. u16 i;
  136419. WhereOrCost *p;
  136420. for(i=pSet->n, p=pSet->a; i>0; i--, p++){
  136421. if( rRun<=p->rRun && (prereq & p->prereq)==prereq ){
  136422. goto whereOrInsert_done;
  136423. }
  136424. if( p->rRun<=rRun && (p->prereq & prereq)==p->prereq ){
  136425. return 0;
  136426. }
  136427. }
  136428. if( pSet->n<N_OR_COST ){
  136429. p = &pSet->a[pSet->n++];
  136430. p->nOut = nOut;
  136431. }else{
  136432. p = pSet->a;
  136433. for(i=1; i<pSet->n; i++){
  136434. if( p->rRun>pSet->a[i].rRun ) p = pSet->a + i;
  136435. }
  136436. if( p->rRun<=rRun ) return 0;
  136437. }
  136438. whereOrInsert_done:
  136439. p->prereq = prereq;
  136440. p->rRun = rRun;
  136441. if( p->nOut>nOut ) p->nOut = nOut;
  136442. return 1;
  136443. }
  136444. /*
  136445. ** Return the bitmask for the given cursor number. Return 0 if
  136446. ** iCursor is not in the set.
  136447. */
  136448. SQLITE_PRIVATE Bitmask sqlite3WhereGetMask(WhereMaskSet *pMaskSet, int iCursor){
  136449. int i;
  136450. assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );
  136451. for(i=0; i<pMaskSet->n; i++){
  136452. if( pMaskSet->ix[i]==iCursor ){
  136453. return MASKBIT(i);
  136454. }
  136455. }
  136456. return 0;
  136457. }
  136458. /*
  136459. ** Create a new mask for cursor iCursor.
  136460. **
  136461. ** There is one cursor per table in the FROM clause. The number of
  136462. ** tables in the FROM clause is limited by a test early in the
  136463. ** sqlite3WhereBegin() routine. So we know that the pMaskSet->ix[]
  136464. ** array will never overflow.
  136465. */
  136466. static void createMask(WhereMaskSet *pMaskSet, int iCursor){
  136467. assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
  136468. pMaskSet->ix[pMaskSet->n++] = iCursor;
  136469. }
  136470. /*
  136471. ** Advance to the next WhereTerm that matches according to the criteria
  136472. ** established when the pScan object was initialized by whereScanInit().
  136473. ** Return NULL if there are no more matching WhereTerms.
  136474. */
  136475. static WhereTerm *whereScanNext(WhereScan *pScan){
  136476. int iCur; /* The cursor on the LHS of the term */
  136477. i16 iColumn; /* The column on the LHS of the term. -1 for IPK */
  136478. Expr *pX; /* An expression being tested */
  136479. WhereClause *pWC; /* Shorthand for pScan->pWC */
  136480. WhereTerm *pTerm; /* The term being tested */
  136481. int k = pScan->k; /* Where to start scanning */
  136482. assert( pScan->iEquiv<=pScan->nEquiv );
  136483. pWC = pScan->pWC;
  136484. while(1){
  136485. iColumn = pScan->aiColumn[pScan->iEquiv-1];
  136486. iCur = pScan->aiCur[pScan->iEquiv-1];
  136487. assert( pWC!=0 );
  136488. do{
  136489. for(pTerm=pWC->a+k; k<pWC->nTerm; k++, pTerm++){
  136490. if( pTerm->leftCursor==iCur
  136491. && pTerm->u.leftColumn==iColumn
  136492. && (iColumn!=XN_EXPR
  136493. || sqlite3ExprCompareSkip(pTerm->pExpr->pLeft,
  136494. pScan->pIdxExpr,iCur)==0)
  136495. && (pScan->iEquiv<=1 || !ExprHasProperty(pTerm->pExpr, EP_FromJoin))
  136496. ){
  136497. if( (pTerm->eOperator & WO_EQUIV)!=0
  136498. && pScan->nEquiv<ArraySize(pScan->aiCur)
  136499. && (pX = sqlite3ExprSkipCollateAndLikely(pTerm->pExpr->pRight))->op
  136500. ==TK_COLUMN
  136501. ){
  136502. int j;
  136503. for(j=0; j<pScan->nEquiv; j++){
  136504. if( pScan->aiCur[j]==pX->iTable
  136505. && pScan->aiColumn[j]==pX->iColumn ){
  136506. break;
  136507. }
  136508. }
  136509. if( j==pScan->nEquiv ){
  136510. pScan->aiCur[j] = pX->iTable;
  136511. pScan->aiColumn[j] = pX->iColumn;
  136512. pScan->nEquiv++;
  136513. }
  136514. }
  136515. if( (pTerm->eOperator & pScan->opMask)!=0 ){
  136516. /* Verify the affinity and collating sequence match */
  136517. if( pScan->zCollName && (pTerm->eOperator & WO_ISNULL)==0 ){
  136518. CollSeq *pColl;
  136519. Parse *pParse = pWC->pWInfo->pParse;
  136520. pX = pTerm->pExpr;
  136521. if( !sqlite3IndexAffinityOk(pX, pScan->idxaff) ){
  136522. continue;
  136523. }
  136524. assert(pX->pLeft);
  136525. pColl = sqlite3ExprCompareCollSeq(pParse, pX);
  136526. if( pColl==0 ) pColl = pParse->db->pDfltColl;
  136527. if( sqlite3StrICmp(pColl->zName, pScan->zCollName) ){
  136528. continue;
  136529. }
  136530. }
  136531. if( (pTerm->eOperator & (WO_EQ|WO_IS))!=0
  136532. && (pX = pTerm->pExpr->pRight)->op==TK_COLUMN
  136533. && pX->iTable==pScan->aiCur[0]
  136534. && pX->iColumn==pScan->aiColumn[0]
  136535. ){
  136536. testcase( pTerm->eOperator & WO_IS );
  136537. continue;
  136538. }
  136539. pScan->pWC = pWC;
  136540. pScan->k = k+1;
  136541. return pTerm;
  136542. }
  136543. }
  136544. }
  136545. pWC = pWC->pOuter;
  136546. k = 0;
  136547. }while( pWC!=0 );
  136548. if( pScan->iEquiv>=pScan->nEquiv ) break;
  136549. pWC = pScan->pOrigWC;
  136550. k = 0;
  136551. pScan->iEquiv++;
  136552. }
  136553. return 0;
  136554. }
  136555. /*
  136556. ** This is whereScanInit() for the case of an index on an expression.
  136557. ** It is factored out into a separate tail-recursion subroutine so that
  136558. ** the normal whereScanInit() routine, which is a high-runner, does not
  136559. ** need to push registers onto the stack as part of its prologue.
  136560. */
  136561. static SQLITE_NOINLINE WhereTerm *whereScanInitIndexExpr(WhereScan *pScan){
  136562. pScan->idxaff = sqlite3ExprAffinity(pScan->pIdxExpr);
  136563. return whereScanNext(pScan);
  136564. }
  136565. /*
  136566. ** Initialize a WHERE clause scanner object. Return a pointer to the
  136567. ** first match. Return NULL if there are no matches.
  136568. **
  136569. ** The scanner will be searching the WHERE clause pWC. It will look
  136570. ** for terms of the form "X <op> <expr>" where X is column iColumn of table
  136571. ** iCur. Or if pIdx!=0 then X is column iColumn of index pIdx. pIdx
  136572. ** must be one of the indexes of table iCur.
  136573. **
  136574. ** The <op> must be one of the operators described by opMask.
  136575. **
  136576. ** If the search is for X and the WHERE clause contains terms of the
  136577. ** form X=Y then this routine might also return terms of the form
  136578. ** "Y <op> <expr>". The number of levels of transitivity is limited,
  136579. ** but is enough to handle most commonly occurring SQL statements.
  136580. **
  136581. ** If X is not the INTEGER PRIMARY KEY then X must be compatible with
  136582. ** index pIdx.
  136583. */
  136584. static WhereTerm *whereScanInit(
  136585. WhereScan *pScan, /* The WhereScan object being initialized */
  136586. WhereClause *pWC, /* The WHERE clause to be scanned */
  136587. int iCur, /* Cursor to scan for */
  136588. int iColumn, /* Column to scan for */
  136589. u32 opMask, /* Operator(s) to scan for */
  136590. Index *pIdx /* Must be compatible with this index */
  136591. ){
  136592. pScan->pOrigWC = pWC;
  136593. pScan->pWC = pWC;
  136594. pScan->pIdxExpr = 0;
  136595. pScan->idxaff = 0;
  136596. pScan->zCollName = 0;
  136597. pScan->opMask = opMask;
  136598. pScan->k = 0;
  136599. pScan->aiCur[0] = iCur;
  136600. pScan->nEquiv = 1;
  136601. pScan->iEquiv = 1;
  136602. if( pIdx ){
  136603. int j = iColumn;
  136604. iColumn = pIdx->aiColumn[j];
  136605. if( iColumn==XN_EXPR ){
  136606. pScan->pIdxExpr = pIdx->aColExpr->a[j].pExpr;
  136607. pScan->zCollName = pIdx->azColl[j];
  136608. pScan->aiColumn[0] = XN_EXPR;
  136609. return whereScanInitIndexExpr(pScan);
  136610. }else if( iColumn==pIdx->pTable->iPKey ){
  136611. iColumn = XN_ROWID;
  136612. }else if( iColumn>=0 ){
  136613. pScan->idxaff = pIdx->pTable->aCol[iColumn].affinity;
  136614. pScan->zCollName = pIdx->azColl[j];
  136615. }
  136616. }else if( iColumn==XN_EXPR ){
  136617. return 0;
  136618. }
  136619. pScan->aiColumn[0] = iColumn;
  136620. return whereScanNext(pScan);
  136621. }
  136622. /*
  136623. ** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
  136624. ** where X is a reference to the iColumn of table iCur or of index pIdx
  136625. ** if pIdx!=0 and <op> is one of the WO_xx operator codes specified by
  136626. ** the op parameter. Return a pointer to the term. Return 0 if not found.
  136627. **
  136628. ** If pIdx!=0 then it must be one of the indexes of table iCur.
  136629. ** Search for terms matching the iColumn-th column of pIdx
  136630. ** rather than the iColumn-th column of table iCur.
  136631. **
  136632. ** The term returned might by Y=<expr> if there is another constraint in
  136633. ** the WHERE clause that specifies that X=Y. Any such constraints will be
  136634. ** identified by the WO_EQUIV bit in the pTerm->eOperator field. The
  136635. ** aiCur[]/iaColumn[] arrays hold X and all its equivalents. There are 11
  136636. ** slots in aiCur[]/aiColumn[] so that means we can look for X plus up to 10
  136637. ** other equivalent values. Hence a search for X will return <expr> if X=A1
  136638. ** and A1=A2 and A2=A3 and ... and A9=A10 and A10=<expr>.
  136639. **
  136640. ** If there are multiple terms in the WHERE clause of the form "X <op> <expr>"
  136641. ** then try for the one with no dependencies on <expr> - in other words where
  136642. ** <expr> is a constant expression of some kind. Only return entries of
  136643. ** the form "X <op> Y" where Y is a column in another table if no terms of
  136644. ** the form "X <op> <const-expr>" exist. If no terms with a constant RHS
  136645. ** exist, try to return a term that does not use WO_EQUIV.
  136646. */
  136647. SQLITE_PRIVATE WhereTerm *sqlite3WhereFindTerm(
  136648. WhereClause *pWC, /* The WHERE clause to be searched */
  136649. int iCur, /* Cursor number of LHS */
  136650. int iColumn, /* Column number of LHS */
  136651. Bitmask notReady, /* RHS must not overlap with this mask */
  136652. u32 op, /* Mask of WO_xx values describing operator */
  136653. Index *pIdx /* Must be compatible with this index, if not NULL */
  136654. ){
  136655. WhereTerm *pResult = 0;
  136656. WhereTerm *p;
  136657. WhereScan scan;
  136658. p = whereScanInit(&scan, pWC, iCur, iColumn, op, pIdx);
  136659. op &= WO_EQ|WO_IS;
  136660. while( p ){
  136661. if( (p->prereqRight & notReady)==0 ){
  136662. if( p->prereqRight==0 && (p->eOperator&op)!=0 ){
  136663. testcase( p->eOperator & WO_IS );
  136664. return p;
  136665. }
  136666. if( pResult==0 ) pResult = p;
  136667. }
  136668. p = whereScanNext(&scan);
  136669. }
  136670. return pResult;
  136671. }
  136672. /*
  136673. ** This function searches pList for an entry that matches the iCol-th column
  136674. ** of index pIdx.
  136675. **
  136676. ** If such an expression is found, its index in pList->a[] is returned. If
  136677. ** no expression is found, -1 is returned.
  136678. */
  136679. static int findIndexCol(
  136680. Parse *pParse, /* Parse context */
  136681. ExprList *pList, /* Expression list to search */
  136682. int iBase, /* Cursor for table associated with pIdx */
  136683. Index *pIdx, /* Index to match column of */
  136684. int iCol /* Column of index to match */
  136685. ){
  136686. int i;
  136687. const char *zColl = pIdx->azColl[iCol];
  136688. for(i=0; i<pList->nExpr; i++){
  136689. Expr *p = sqlite3ExprSkipCollateAndLikely(pList->a[i].pExpr);
  136690. if( p->op==TK_COLUMN
  136691. && p->iColumn==pIdx->aiColumn[iCol]
  136692. && p->iTable==iBase
  136693. ){
  136694. CollSeq *pColl = sqlite3ExprNNCollSeq(pParse, pList->a[i].pExpr);
  136695. if( 0==sqlite3StrICmp(pColl->zName, zColl) ){
  136696. return i;
  136697. }
  136698. }
  136699. }
  136700. return -1;
  136701. }
  136702. /*
  136703. ** Return TRUE if the iCol-th column of index pIdx is NOT NULL
  136704. */
  136705. static int indexColumnNotNull(Index *pIdx, int iCol){
  136706. int j;
  136707. assert( pIdx!=0 );
  136708. assert( iCol>=0 && iCol<pIdx->nColumn );
  136709. j = pIdx->aiColumn[iCol];
  136710. if( j>=0 ){
  136711. return pIdx->pTable->aCol[j].notNull;
  136712. }else if( j==(-1) ){
  136713. return 1;
  136714. }else{
  136715. assert( j==(-2) );
  136716. return 0; /* Assume an indexed expression can always yield a NULL */
  136717. }
  136718. }
  136719. /*
  136720. ** Return true if the DISTINCT expression-list passed as the third argument
  136721. ** is redundant.
  136722. **
  136723. ** A DISTINCT list is redundant if any subset of the columns in the
  136724. ** DISTINCT list are collectively unique and individually non-null.
  136725. */
  136726. static int isDistinctRedundant(
  136727. Parse *pParse, /* Parsing context */
  136728. SrcList *pTabList, /* The FROM clause */
  136729. WhereClause *pWC, /* The WHERE clause */
  136730. ExprList *pDistinct /* The result set that needs to be DISTINCT */
  136731. ){
  136732. Table *pTab;
  136733. Index *pIdx;
  136734. int i;
  136735. int iBase;
  136736. /* If there is more than one table or sub-select in the FROM clause of
  136737. ** this query, then it will not be possible to show that the DISTINCT
  136738. ** clause is redundant. */
  136739. if( pTabList->nSrc!=1 ) return 0;
  136740. iBase = pTabList->a[0].iCursor;
  136741. pTab = pTabList->a[0].pTab;
  136742. /* If any of the expressions is an IPK column on table iBase, then return
  136743. ** true. Note: The (p->iTable==iBase) part of this test may be false if the
  136744. ** current SELECT is a correlated sub-query.
  136745. */
  136746. for(i=0; i<pDistinct->nExpr; i++){
  136747. Expr *p = sqlite3ExprSkipCollateAndLikely(pDistinct->a[i].pExpr);
  136748. if( p->op==TK_COLUMN && p->iTable==iBase && p->iColumn<0 ) return 1;
  136749. }
  136750. /* Loop through all indices on the table, checking each to see if it makes
  136751. ** the DISTINCT qualifier redundant. It does so if:
  136752. **
  136753. ** 1. The index is itself UNIQUE, and
  136754. **
  136755. ** 2. All of the columns in the index are either part of the pDistinct
  136756. ** list, or else the WHERE clause contains a term of the form "col=X",
  136757. ** where X is a constant value. The collation sequences of the
  136758. ** comparison and select-list expressions must match those of the index.
  136759. **
  136760. ** 3. All of those index columns for which the WHERE clause does not
  136761. ** contain a "col=X" term are subject to a NOT NULL constraint.
  136762. */
  136763. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  136764. if( !IsUniqueIndex(pIdx) ) continue;
  136765. for(i=0; i<pIdx->nKeyCol; i++){
  136766. if( 0==sqlite3WhereFindTerm(pWC, iBase, i, ~(Bitmask)0, WO_EQ, pIdx) ){
  136767. if( findIndexCol(pParse, pDistinct, iBase, pIdx, i)<0 ) break;
  136768. if( indexColumnNotNull(pIdx, i)==0 ) break;
  136769. }
  136770. }
  136771. if( i==pIdx->nKeyCol ){
  136772. /* This index implies that the DISTINCT qualifier is redundant. */
  136773. return 1;
  136774. }
  136775. }
  136776. return 0;
  136777. }
  136778. /*
  136779. ** Estimate the logarithm of the input value to base 2.
  136780. */
  136781. static LogEst estLog(LogEst N){
  136782. return N<=10 ? 0 : sqlite3LogEst(N) - 33;
  136783. }
  136784. /*
  136785. ** Convert OP_Column opcodes to OP_Copy in previously generated code.
  136786. **
  136787. ** This routine runs over generated VDBE code and translates OP_Column
  136788. ** opcodes into OP_Copy when the table is being accessed via co-routine
  136789. ** instead of via table lookup.
  136790. **
  136791. ** If the iAutoidxCur is not zero, then any OP_Rowid instructions on
  136792. ** cursor iTabCur are transformed into OP_Sequence opcode for the
  136793. ** iAutoidxCur cursor, in order to generate unique rowids for the
  136794. ** automatic index being generated.
  136795. */
  136796. static void translateColumnToCopy(
  136797. Parse *pParse, /* Parsing context */
  136798. int iStart, /* Translate from this opcode to the end */
  136799. int iTabCur, /* OP_Column/OP_Rowid references to this table */
  136800. int iRegister, /* The first column is in this register */
  136801. int iAutoidxCur /* If non-zero, cursor of autoindex being generated */
  136802. ){
  136803. Vdbe *v = pParse->pVdbe;
  136804. VdbeOp *pOp = sqlite3VdbeGetOp(v, iStart);
  136805. int iEnd = sqlite3VdbeCurrentAddr(v);
  136806. if( pParse->db->mallocFailed ) return;
  136807. for(; iStart<iEnd; iStart++, pOp++){
  136808. if( pOp->p1!=iTabCur ) continue;
  136809. if( pOp->opcode==OP_Column ){
  136810. pOp->opcode = OP_Copy;
  136811. pOp->p1 = pOp->p2 + iRegister;
  136812. pOp->p2 = pOp->p3;
  136813. pOp->p3 = 0;
  136814. }else if( pOp->opcode==OP_Rowid ){
  136815. if( iAutoidxCur ){
  136816. pOp->opcode = OP_Sequence;
  136817. pOp->p1 = iAutoidxCur;
  136818. }else{
  136819. pOp->opcode = OP_Null;
  136820. pOp->p1 = 0;
  136821. pOp->p3 = 0;
  136822. }
  136823. }
  136824. }
  136825. }
  136826. /*
  136827. ** Two routines for printing the content of an sqlite3_index_info
  136828. ** structure. Used for testing and debugging only. If neither
  136829. ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
  136830. ** are no-ops.
  136831. */
  136832. #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(WHERETRACE_ENABLED)
  136833. static void whereTraceIndexInfoInputs(sqlite3_index_info *p){
  136834. int i;
  136835. if( !sqlite3WhereTrace ) return;
  136836. for(i=0; i<p->nConstraint; i++){
  136837. sqlite3DebugPrintf(" constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
  136838. i,
  136839. p->aConstraint[i].iColumn,
  136840. p->aConstraint[i].iTermOffset,
  136841. p->aConstraint[i].op,
  136842. p->aConstraint[i].usable);
  136843. }
  136844. for(i=0; i<p->nOrderBy; i++){
  136845. sqlite3DebugPrintf(" orderby[%d]: col=%d desc=%d\n",
  136846. i,
  136847. p->aOrderBy[i].iColumn,
  136848. p->aOrderBy[i].desc);
  136849. }
  136850. }
  136851. static void whereTraceIndexInfoOutputs(sqlite3_index_info *p){
  136852. int i;
  136853. if( !sqlite3WhereTrace ) return;
  136854. for(i=0; i<p->nConstraint; i++){
  136855. sqlite3DebugPrintf(" usage[%d]: argvIdx=%d omit=%d\n",
  136856. i,
  136857. p->aConstraintUsage[i].argvIndex,
  136858. p->aConstraintUsage[i].omit);
  136859. }
  136860. sqlite3DebugPrintf(" idxNum=%d\n", p->idxNum);
  136861. sqlite3DebugPrintf(" idxStr=%s\n", p->idxStr);
  136862. sqlite3DebugPrintf(" orderByConsumed=%d\n", p->orderByConsumed);
  136863. sqlite3DebugPrintf(" estimatedCost=%g\n", p->estimatedCost);
  136864. sqlite3DebugPrintf(" estimatedRows=%lld\n", p->estimatedRows);
  136865. }
  136866. #else
  136867. #define whereTraceIndexInfoInputs(A)
  136868. #define whereTraceIndexInfoOutputs(A)
  136869. #endif
  136870. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  136871. /*
  136872. ** Return TRUE if the WHERE clause term pTerm is of a form where it
  136873. ** could be used with an index to access pSrc, assuming an appropriate
  136874. ** index existed.
  136875. */
  136876. static int termCanDriveIndex(
  136877. WhereTerm *pTerm, /* WHERE clause term to check */
  136878. struct SrcList_item *pSrc, /* Table we are trying to access */
  136879. Bitmask notReady /* Tables in outer loops of the join */
  136880. ){
  136881. char aff;
  136882. if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
  136883. if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) return 0;
  136884. if( (pSrc->fg.jointype & JT_LEFT)
  136885. && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
  136886. && (pTerm->eOperator & WO_IS)
  136887. ){
  136888. /* Cannot use an IS term from the WHERE clause as an index driver for
  136889. ** the RHS of a LEFT JOIN. Such a term can only be used if it is from
  136890. ** the ON clause. */
  136891. return 0;
  136892. }
  136893. if( (pTerm->prereqRight & notReady)!=0 ) return 0;
  136894. if( pTerm->u.leftColumn<0 ) return 0;
  136895. aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
  136896. if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
  136897. testcase( pTerm->pExpr->op==TK_IS );
  136898. return 1;
  136899. }
  136900. #endif
  136901. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  136902. /*
  136903. ** Generate code to construct the Index object for an automatic index
  136904. ** and to set up the WhereLevel object pLevel so that the code generator
  136905. ** makes use of the automatic index.
  136906. */
  136907. static void constructAutomaticIndex(
  136908. Parse *pParse, /* The parsing context */
  136909. WhereClause *pWC, /* The WHERE clause */
  136910. struct SrcList_item *pSrc, /* The FROM clause term to get the next index */
  136911. Bitmask notReady, /* Mask of cursors that are not available */
  136912. WhereLevel *pLevel /* Write new index here */
  136913. ){
  136914. int nKeyCol; /* Number of columns in the constructed index */
  136915. WhereTerm *pTerm; /* A single term of the WHERE clause */
  136916. WhereTerm *pWCEnd; /* End of pWC->a[] */
  136917. Index *pIdx; /* Object describing the transient index */
  136918. Vdbe *v; /* Prepared statement under construction */
  136919. int addrInit; /* Address of the initialization bypass jump */
  136920. Table *pTable; /* The table being indexed */
  136921. int addrTop; /* Top of the index fill loop */
  136922. int regRecord; /* Register holding an index record */
  136923. int n; /* Column counter */
  136924. int i; /* Loop counter */
  136925. int mxBitCol; /* Maximum column in pSrc->colUsed */
  136926. CollSeq *pColl; /* Collating sequence to on a column */
  136927. WhereLoop *pLoop; /* The Loop object */
  136928. char *zNotUsed; /* Extra space on the end of pIdx */
  136929. Bitmask idxCols; /* Bitmap of columns used for indexing */
  136930. Bitmask extraCols; /* Bitmap of additional columns */
  136931. u8 sentWarning = 0; /* True if a warnning has been issued */
  136932. Expr *pPartial = 0; /* Partial Index Expression */
  136933. int iContinue = 0; /* Jump here to skip excluded rows */
  136934. struct SrcList_item *pTabItem; /* FROM clause term being indexed */
  136935. int addrCounter = 0; /* Address where integer counter is initialized */
  136936. int regBase; /* Array of registers where record is assembled */
  136937. /* Generate code to skip over the creation and initialization of the
  136938. ** transient index on 2nd and subsequent iterations of the loop. */
  136939. v = pParse->pVdbe;
  136940. assert( v!=0 );
  136941. addrInit = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
  136942. /* Count the number of columns that will be added to the index
  136943. ** and used to match WHERE clause constraints */
  136944. nKeyCol = 0;
  136945. pTable = pSrc->pTab;
  136946. pWCEnd = &pWC->a[pWC->nTerm];
  136947. pLoop = pLevel->pWLoop;
  136948. idxCols = 0;
  136949. for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
  136950. Expr *pExpr = pTerm->pExpr;
  136951. assert( !ExprHasProperty(pExpr, EP_FromJoin) /* prereq always non-zero */
  136952. || pExpr->iRightJoinTable!=pSrc->iCursor /* for the right-hand */
  136953. || pLoop->prereq!=0 ); /* table of a LEFT JOIN */
  136954. if( pLoop->prereq==0
  136955. && (pTerm->wtFlags & TERM_VIRTUAL)==0
  136956. && !ExprHasProperty(pExpr, EP_FromJoin)
  136957. && sqlite3ExprIsTableConstant(pExpr, pSrc->iCursor) ){
  136958. pPartial = sqlite3ExprAnd(pParse, pPartial,
  136959. sqlite3ExprDup(pParse->db, pExpr, 0));
  136960. }
  136961. if( termCanDriveIndex(pTerm, pSrc, notReady) ){
  136962. int iCol = pTerm->u.leftColumn;
  136963. Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
  136964. testcase( iCol==BMS );
  136965. testcase( iCol==BMS-1 );
  136966. if( !sentWarning ){
  136967. sqlite3_log(SQLITE_WARNING_AUTOINDEX,
  136968. "automatic index on %s(%s)", pTable->zName,
  136969. pTable->aCol[iCol].zName);
  136970. sentWarning = 1;
  136971. }
  136972. if( (idxCols & cMask)==0 ){
  136973. if( whereLoopResize(pParse->db, pLoop, nKeyCol+1) ){
  136974. goto end_auto_index_create;
  136975. }
  136976. pLoop->aLTerm[nKeyCol++] = pTerm;
  136977. idxCols |= cMask;
  136978. }
  136979. }
  136980. }
  136981. assert( nKeyCol>0 );
  136982. pLoop->u.btree.nEq = pLoop->nLTerm = nKeyCol;
  136983. pLoop->wsFlags = WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WHERE_INDEXED
  136984. | WHERE_AUTO_INDEX;
  136985. /* Count the number of additional columns needed to create a
  136986. ** covering index. A "covering index" is an index that contains all
  136987. ** columns that are needed by the query. With a covering index, the
  136988. ** original table never needs to be accessed. Automatic indices must
  136989. ** be a covering index because the index will not be updated if the
  136990. ** original table changes and the index and table cannot both be used
  136991. ** if they go out of sync.
  136992. */
  136993. extraCols = pSrc->colUsed & (~idxCols | MASKBIT(BMS-1));
  136994. mxBitCol = MIN(BMS-1,pTable->nCol);
  136995. testcase( pTable->nCol==BMS-1 );
  136996. testcase( pTable->nCol==BMS-2 );
  136997. for(i=0; i<mxBitCol; i++){
  136998. if( extraCols & MASKBIT(i) ) nKeyCol++;
  136999. }
  137000. if( pSrc->colUsed & MASKBIT(BMS-1) ){
  137001. nKeyCol += pTable->nCol - BMS + 1;
  137002. }
  137003. /* Construct the Index object to describe this index */
  137004. pIdx = sqlite3AllocateIndexObject(pParse->db, nKeyCol+1, 0, &zNotUsed);
  137005. if( pIdx==0 ) goto end_auto_index_create;
  137006. pLoop->u.btree.pIndex = pIdx;
  137007. pIdx->zName = "auto-index";
  137008. pIdx->pTable = pTable;
  137009. n = 0;
  137010. idxCols = 0;
  137011. for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
  137012. if( termCanDriveIndex(pTerm, pSrc, notReady) ){
  137013. int iCol = pTerm->u.leftColumn;
  137014. Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
  137015. testcase( iCol==BMS-1 );
  137016. testcase( iCol==BMS );
  137017. if( (idxCols & cMask)==0 ){
  137018. Expr *pX = pTerm->pExpr;
  137019. idxCols |= cMask;
  137020. pIdx->aiColumn[n] = pTerm->u.leftColumn;
  137021. pColl = sqlite3ExprCompareCollSeq(pParse, pX);
  137022. assert( pColl!=0 || pParse->nErr>0 ); /* TH3 collate01.800 */
  137023. pIdx->azColl[n] = pColl ? pColl->zName : sqlite3StrBINARY;
  137024. n++;
  137025. }
  137026. }
  137027. }
  137028. assert( (u32)n==pLoop->u.btree.nEq );
  137029. /* Add additional columns needed to make the automatic index into
  137030. ** a covering index */
  137031. for(i=0; i<mxBitCol; i++){
  137032. if( extraCols & MASKBIT(i) ){
  137033. pIdx->aiColumn[n] = i;
  137034. pIdx->azColl[n] = sqlite3StrBINARY;
  137035. n++;
  137036. }
  137037. }
  137038. if( pSrc->colUsed & MASKBIT(BMS-1) ){
  137039. for(i=BMS-1; i<pTable->nCol; i++){
  137040. pIdx->aiColumn[n] = i;
  137041. pIdx->azColl[n] = sqlite3StrBINARY;
  137042. n++;
  137043. }
  137044. }
  137045. assert( n==nKeyCol );
  137046. pIdx->aiColumn[n] = XN_ROWID;
  137047. pIdx->azColl[n] = sqlite3StrBINARY;
  137048. /* Create the automatic index */
  137049. assert( pLevel->iIdxCur>=0 );
  137050. pLevel->iIdxCur = pParse->nTab++;
  137051. sqlite3VdbeAddOp2(v, OP_OpenAutoindex, pLevel->iIdxCur, nKeyCol+1);
  137052. sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  137053. VdbeComment((v, "for %s", pTable->zName));
  137054. /* Fill the automatic index with content */
  137055. pTabItem = &pWC->pWInfo->pTabList->a[pLevel->iFrom];
  137056. if( pTabItem->fg.viaCoroutine ){
  137057. int regYield = pTabItem->regReturn;
  137058. addrCounter = sqlite3VdbeAddOp2(v, OP_Integer, 0, 0);
  137059. sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub);
  137060. addrTop = sqlite3VdbeAddOp1(v, OP_Yield, regYield);
  137061. VdbeCoverage(v);
  137062. VdbeComment((v, "next row of %s", pTabItem->pTab->zName));
  137063. }else{
  137064. addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur); VdbeCoverage(v);
  137065. }
  137066. if( pPartial ){
  137067. iContinue = sqlite3VdbeMakeLabel(pParse);
  137068. sqlite3ExprIfFalse(pParse, pPartial, iContinue, SQLITE_JUMPIFNULL);
  137069. pLoop->wsFlags |= WHERE_PARTIALIDX;
  137070. }
  137071. regRecord = sqlite3GetTempReg(pParse);
  137072. regBase = sqlite3GenerateIndexKey(
  137073. pParse, pIdx, pLevel->iTabCur, regRecord, 0, 0, 0, 0
  137074. );
  137075. sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
  137076. sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  137077. if( pPartial ) sqlite3VdbeResolveLabel(v, iContinue);
  137078. if( pTabItem->fg.viaCoroutine ){
  137079. sqlite3VdbeChangeP2(v, addrCounter, regBase+n);
  137080. testcase( pParse->db->mallocFailed );
  137081. assert( pLevel->iIdxCur>0 );
  137082. translateColumnToCopy(pParse, addrTop, pLevel->iTabCur,
  137083. pTabItem->regResult, pLevel->iIdxCur);
  137084. sqlite3VdbeGoto(v, addrTop);
  137085. pTabItem->fg.viaCoroutine = 0;
  137086. }else{
  137087. sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1); VdbeCoverage(v);
  137088. sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
  137089. }
  137090. sqlite3VdbeJumpHere(v, addrTop);
  137091. sqlite3ReleaseTempReg(pParse, regRecord);
  137092. /* Jump here when skipping the initialization */
  137093. sqlite3VdbeJumpHere(v, addrInit);
  137094. end_auto_index_create:
  137095. sqlite3ExprDelete(pParse->db, pPartial);
  137096. }
  137097. #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
  137098. #ifndef SQLITE_OMIT_VIRTUALTABLE
  137099. /*
  137100. ** Allocate and populate an sqlite3_index_info structure. It is the
  137101. ** responsibility of the caller to eventually release the structure
  137102. ** by passing the pointer returned by this function to sqlite3_free().
  137103. */
  137104. static sqlite3_index_info *allocateIndexInfo(
  137105. Parse *pParse, /* The parsing context */
  137106. WhereClause *pWC, /* The WHERE clause being analyzed */
  137107. Bitmask mUnusable, /* Ignore terms with these prereqs */
  137108. struct SrcList_item *pSrc, /* The FROM clause term that is the vtab */
  137109. ExprList *pOrderBy, /* The ORDER BY clause */
  137110. u16 *pmNoOmit /* Mask of terms not to omit */
  137111. ){
  137112. int i, j;
  137113. int nTerm;
  137114. struct sqlite3_index_constraint *pIdxCons;
  137115. struct sqlite3_index_orderby *pIdxOrderBy;
  137116. struct sqlite3_index_constraint_usage *pUsage;
  137117. struct HiddenIndexInfo *pHidden;
  137118. WhereTerm *pTerm;
  137119. int nOrderBy;
  137120. sqlite3_index_info *pIdxInfo;
  137121. u16 mNoOmit = 0;
  137122. /* Count the number of possible WHERE clause constraints referring
  137123. ** to this virtual table */
  137124. for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
  137125. if( pTerm->leftCursor != pSrc->iCursor ) continue;
  137126. if( pTerm->prereqRight & mUnusable ) continue;
  137127. assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
  137128. testcase( pTerm->eOperator & WO_IN );
  137129. testcase( pTerm->eOperator & WO_ISNULL );
  137130. testcase( pTerm->eOperator & WO_IS );
  137131. testcase( pTerm->eOperator & WO_ALL );
  137132. if( (pTerm->eOperator & ~(WO_EQUIV))==0 ) continue;
  137133. if( pTerm->wtFlags & TERM_VNULL ) continue;
  137134. assert( pTerm->u.leftColumn>=(-1) );
  137135. nTerm++;
  137136. }
  137137. /* If the ORDER BY clause contains only columns in the current
  137138. ** virtual table then allocate space for the aOrderBy part of
  137139. ** the sqlite3_index_info structure.
  137140. */
  137141. nOrderBy = 0;
  137142. if( pOrderBy ){
  137143. int n = pOrderBy->nExpr;
  137144. for(i=0; i<n; i++){
  137145. Expr *pExpr = pOrderBy->a[i].pExpr;
  137146. if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
  137147. if( pOrderBy->a[i].sortFlags & KEYINFO_ORDER_BIGNULL ) break;
  137148. }
  137149. if( i==n){
  137150. nOrderBy = n;
  137151. }
  137152. }
  137153. /* Allocate the sqlite3_index_info structure
  137154. */
  137155. pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
  137156. + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
  137157. + sizeof(*pIdxOrderBy)*nOrderBy + sizeof(*pHidden) );
  137158. if( pIdxInfo==0 ){
  137159. sqlite3ErrorMsg(pParse, "out of memory");
  137160. return 0;
  137161. }
  137162. pHidden = (struct HiddenIndexInfo*)&pIdxInfo[1];
  137163. pIdxCons = (struct sqlite3_index_constraint*)&pHidden[1];
  137164. pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
  137165. pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
  137166. pIdxInfo->nOrderBy = nOrderBy;
  137167. pIdxInfo->aConstraint = pIdxCons;
  137168. pIdxInfo->aOrderBy = pIdxOrderBy;
  137169. pIdxInfo->aConstraintUsage = pUsage;
  137170. pHidden->pWC = pWC;
  137171. pHidden->pParse = pParse;
  137172. for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
  137173. u16 op;
  137174. if( pTerm->leftCursor != pSrc->iCursor ) continue;
  137175. if( pTerm->prereqRight & mUnusable ) continue;
  137176. assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
  137177. testcase( pTerm->eOperator & WO_IN );
  137178. testcase( pTerm->eOperator & WO_IS );
  137179. testcase( pTerm->eOperator & WO_ISNULL );
  137180. testcase( pTerm->eOperator & WO_ALL );
  137181. if( (pTerm->eOperator & ~(WO_EQUIV))==0 ) continue;
  137182. if( pTerm->wtFlags & TERM_VNULL ) continue;
  137183. /* tag-20191211-002: WHERE-clause constraints are not useful to the
  137184. ** right-hand table of a LEFT JOIN. See tag-20191211-001 for the
  137185. ** equivalent restriction for ordinary tables. */
  137186. if( (pSrc->fg.jointype & JT_LEFT)!=0
  137187. && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
  137188. ){
  137189. continue;
  137190. }
  137191. assert( pTerm->u.leftColumn>=(-1) );
  137192. pIdxCons[j].iColumn = pTerm->u.leftColumn;
  137193. pIdxCons[j].iTermOffset = i;
  137194. op = pTerm->eOperator & WO_ALL;
  137195. if( op==WO_IN ) op = WO_EQ;
  137196. if( op==WO_AUX ){
  137197. pIdxCons[j].op = pTerm->eMatchOp;
  137198. }else if( op & (WO_ISNULL|WO_IS) ){
  137199. if( op==WO_ISNULL ){
  137200. pIdxCons[j].op = SQLITE_INDEX_CONSTRAINT_ISNULL;
  137201. }else{
  137202. pIdxCons[j].op = SQLITE_INDEX_CONSTRAINT_IS;
  137203. }
  137204. }else{
  137205. pIdxCons[j].op = (u8)op;
  137206. /* The direct assignment in the previous line is possible only because
  137207. ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical. The
  137208. ** following asserts verify this fact. */
  137209. assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
  137210. assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
  137211. assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
  137212. assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
  137213. assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
  137214. assert( pTerm->eOperator&(WO_IN|WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_AUX) );
  137215. if( op & (WO_LT|WO_LE|WO_GT|WO_GE)
  137216. && sqlite3ExprIsVector(pTerm->pExpr->pRight)
  137217. ){
  137218. testcase( j!=i );
  137219. if( j<16 ) mNoOmit |= (1 << j);
  137220. if( op==WO_LT ) pIdxCons[j].op = WO_LE;
  137221. if( op==WO_GT ) pIdxCons[j].op = WO_GE;
  137222. }
  137223. }
  137224. j++;
  137225. }
  137226. pIdxInfo->nConstraint = j;
  137227. for(i=0; i<nOrderBy; i++){
  137228. Expr *pExpr = pOrderBy->a[i].pExpr;
  137229. pIdxOrderBy[i].iColumn = pExpr->iColumn;
  137230. pIdxOrderBy[i].desc = pOrderBy->a[i].sortFlags & KEYINFO_ORDER_DESC;
  137231. }
  137232. *pmNoOmit = mNoOmit;
  137233. return pIdxInfo;
  137234. }
  137235. /*
  137236. ** The table object reference passed as the second argument to this function
  137237. ** must represent a virtual table. This function invokes the xBestIndex()
  137238. ** method of the virtual table with the sqlite3_index_info object that
  137239. ** comes in as the 3rd argument to this function.
  137240. **
  137241. ** If an error occurs, pParse is populated with an error message and an
  137242. ** appropriate error code is returned. A return of SQLITE_CONSTRAINT from
  137243. ** xBestIndex is not considered an error. SQLITE_CONSTRAINT indicates that
  137244. ** the current configuration of "unusable" flags in sqlite3_index_info can
  137245. ** not result in a valid plan.
  137246. **
  137247. ** Whether or not an error is returned, it is the responsibility of the
  137248. ** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
  137249. ** that this is required.
  137250. */
  137251. static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
  137252. sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
  137253. int rc;
  137254. whereTraceIndexInfoInputs(p);
  137255. rc = pVtab->pModule->xBestIndex(pVtab, p);
  137256. whereTraceIndexInfoOutputs(p);
  137257. if( rc!=SQLITE_OK && rc!=SQLITE_CONSTRAINT ){
  137258. if( rc==SQLITE_NOMEM ){
  137259. sqlite3OomFault(pParse->db);
  137260. }else if( !pVtab->zErrMsg ){
  137261. sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
  137262. }else{
  137263. sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
  137264. }
  137265. }
  137266. sqlite3_free(pVtab->zErrMsg);
  137267. pVtab->zErrMsg = 0;
  137268. return rc;
  137269. }
  137270. #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */
  137271. #ifdef SQLITE_ENABLE_STAT4
  137272. /*
  137273. ** Estimate the location of a particular key among all keys in an
  137274. ** index. Store the results in aStat as follows:
  137275. **
  137276. ** aStat[0] Est. number of rows less than pRec
  137277. ** aStat[1] Est. number of rows equal to pRec
  137278. **
  137279. ** Return the index of the sample that is the smallest sample that
  137280. ** is greater than or equal to pRec. Note that this index is not an index
  137281. ** into the aSample[] array - it is an index into a virtual set of samples
  137282. ** based on the contents of aSample[] and the number of fields in record
  137283. ** pRec.
  137284. */
  137285. static int whereKeyStats(
  137286. Parse *pParse, /* Database connection */
  137287. Index *pIdx, /* Index to consider domain of */
  137288. UnpackedRecord *pRec, /* Vector of values to consider */
  137289. int roundUp, /* Round up if true. Round down if false */
  137290. tRowcnt *aStat /* OUT: stats written here */
  137291. ){
  137292. IndexSample *aSample = pIdx->aSample;
  137293. int iCol; /* Index of required stats in anEq[] etc. */
  137294. int i; /* Index of first sample >= pRec */
  137295. int iSample; /* Smallest sample larger than or equal to pRec */
  137296. int iMin = 0; /* Smallest sample not yet tested */
  137297. int iTest; /* Next sample to test */
  137298. int res; /* Result of comparison operation */
  137299. int nField; /* Number of fields in pRec */
  137300. tRowcnt iLower = 0; /* anLt[] + anEq[] of largest sample pRec is > */
  137301. #ifndef SQLITE_DEBUG
  137302. UNUSED_PARAMETER( pParse );
  137303. #endif
  137304. assert( pRec!=0 );
  137305. assert( pIdx->nSample>0 );
  137306. assert( pRec->nField>0 && pRec->nField<=pIdx->nSampleCol );
  137307. /* Do a binary search to find the first sample greater than or equal
  137308. ** to pRec. If pRec contains a single field, the set of samples to search
  137309. ** is simply the aSample[] array. If the samples in aSample[] contain more
  137310. ** than one fields, all fields following the first are ignored.
  137311. **
  137312. ** If pRec contains N fields, where N is more than one, then as well as the
  137313. ** samples in aSample[] (truncated to N fields), the search also has to
  137314. ** consider prefixes of those samples. For example, if the set of samples
  137315. ** in aSample is:
  137316. **
  137317. ** aSample[0] = (a, 5)
  137318. ** aSample[1] = (a, 10)
  137319. ** aSample[2] = (b, 5)
  137320. ** aSample[3] = (c, 100)
  137321. ** aSample[4] = (c, 105)
  137322. **
  137323. ** Then the search space should ideally be the samples above and the
  137324. ** unique prefixes [a], [b] and [c]. But since that is hard to organize,
  137325. ** the code actually searches this set:
  137326. **
  137327. ** 0: (a)
  137328. ** 1: (a, 5)
  137329. ** 2: (a, 10)
  137330. ** 3: (a, 10)
  137331. ** 4: (b)
  137332. ** 5: (b, 5)
  137333. ** 6: (c)
  137334. ** 7: (c, 100)
  137335. ** 8: (c, 105)
  137336. ** 9: (c, 105)
  137337. **
  137338. ** For each sample in the aSample[] array, N samples are present in the
  137339. ** effective sample array. In the above, samples 0 and 1 are based on
  137340. ** sample aSample[0]. Samples 2 and 3 on aSample[1] etc.
  137341. **
  137342. ** Often, sample i of each block of N effective samples has (i+1) fields.
  137343. ** Except, each sample may be extended to ensure that it is greater than or
  137344. ** equal to the previous sample in the array. For example, in the above,
  137345. ** sample 2 is the first sample of a block of N samples, so at first it
  137346. ** appears that it should be 1 field in size. However, that would make it
  137347. ** smaller than sample 1, so the binary search would not work. As a result,
  137348. ** it is extended to two fields. The duplicates that this creates do not
  137349. ** cause any problems.
  137350. */
  137351. nField = pRec->nField;
  137352. iCol = 0;
  137353. iSample = pIdx->nSample * nField;
  137354. do{
  137355. int iSamp; /* Index in aSample[] of test sample */
  137356. int n; /* Number of fields in test sample */
  137357. iTest = (iMin+iSample)/2;
  137358. iSamp = iTest / nField;
  137359. if( iSamp>0 ){
  137360. /* The proposed effective sample is a prefix of sample aSample[iSamp].
  137361. ** Specifically, the shortest prefix of at least (1 + iTest%nField)
  137362. ** fields that is greater than the previous effective sample. */
  137363. for(n=(iTest % nField) + 1; n<nField; n++){
  137364. if( aSample[iSamp-1].anLt[n-1]!=aSample[iSamp].anLt[n-1] ) break;
  137365. }
  137366. }else{
  137367. n = iTest + 1;
  137368. }
  137369. pRec->nField = n;
  137370. res = sqlite3VdbeRecordCompare(aSample[iSamp].n, aSample[iSamp].p, pRec);
  137371. if( res<0 ){
  137372. iLower = aSample[iSamp].anLt[n-1] + aSample[iSamp].anEq[n-1];
  137373. iMin = iTest+1;
  137374. }else if( res==0 && n<nField ){
  137375. iLower = aSample[iSamp].anLt[n-1];
  137376. iMin = iTest+1;
  137377. res = -1;
  137378. }else{
  137379. iSample = iTest;
  137380. iCol = n-1;
  137381. }
  137382. }while( res && iMin<iSample );
  137383. i = iSample / nField;
  137384. #ifdef SQLITE_DEBUG
  137385. /* The following assert statements check that the binary search code
  137386. ** above found the right answer. This block serves no purpose other
  137387. ** than to invoke the asserts. */
  137388. if( pParse->db->mallocFailed==0 ){
  137389. if( res==0 ){
  137390. /* If (res==0) is true, then pRec must be equal to sample i. */
  137391. assert( i<pIdx->nSample );
  137392. assert( iCol==nField-1 );
  137393. pRec->nField = nField;
  137394. assert( 0==sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)
  137395. || pParse->db->mallocFailed
  137396. );
  137397. }else{
  137398. /* Unless i==pIdx->nSample, indicating that pRec is larger than
  137399. ** all samples in the aSample[] array, pRec must be smaller than the
  137400. ** (iCol+1) field prefix of sample i. */
  137401. assert( i<=pIdx->nSample && i>=0 );
  137402. pRec->nField = iCol+1;
  137403. assert( i==pIdx->nSample
  137404. || sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)>0
  137405. || pParse->db->mallocFailed );
  137406. /* if i==0 and iCol==0, then record pRec is smaller than all samples
  137407. ** in the aSample[] array. Otherwise, if (iCol>0) then pRec must
  137408. ** be greater than or equal to the (iCol) field prefix of sample i.
  137409. ** If (i>0), then pRec must also be greater than sample (i-1). */
  137410. if( iCol>0 ){
  137411. pRec->nField = iCol;
  137412. assert( sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)<=0
  137413. || pParse->db->mallocFailed );
  137414. }
  137415. if( i>0 ){
  137416. pRec->nField = nField;
  137417. assert( sqlite3VdbeRecordCompare(aSample[i-1].n, aSample[i-1].p, pRec)<0
  137418. || pParse->db->mallocFailed );
  137419. }
  137420. }
  137421. }
  137422. #endif /* ifdef SQLITE_DEBUG */
  137423. if( res==0 ){
  137424. /* Record pRec is equal to sample i */
  137425. assert( iCol==nField-1 );
  137426. aStat[0] = aSample[i].anLt[iCol];
  137427. aStat[1] = aSample[i].anEq[iCol];
  137428. }else{
  137429. /* At this point, the (iCol+1) field prefix of aSample[i] is the first
  137430. ** sample that is greater than pRec. Or, if i==pIdx->nSample then pRec
  137431. ** is larger than all samples in the array. */
  137432. tRowcnt iUpper, iGap;
  137433. if( i>=pIdx->nSample ){
  137434. iUpper = sqlite3LogEstToInt(pIdx->aiRowLogEst[0]);
  137435. }else{
  137436. iUpper = aSample[i].anLt[iCol];
  137437. }
  137438. if( iLower>=iUpper ){
  137439. iGap = 0;
  137440. }else{
  137441. iGap = iUpper - iLower;
  137442. }
  137443. if( roundUp ){
  137444. iGap = (iGap*2)/3;
  137445. }else{
  137446. iGap = iGap/3;
  137447. }
  137448. aStat[0] = iLower + iGap;
  137449. aStat[1] = pIdx->aAvgEq[nField-1];
  137450. }
  137451. /* Restore the pRec->nField value before returning. */
  137452. pRec->nField = nField;
  137453. return i;
  137454. }
  137455. #endif /* SQLITE_ENABLE_STAT4 */
  137456. /*
  137457. ** If it is not NULL, pTerm is a term that provides an upper or lower
  137458. ** bound on a range scan. Without considering pTerm, it is estimated
  137459. ** that the scan will visit nNew rows. This function returns the number
  137460. ** estimated to be visited after taking pTerm into account.
  137461. **
  137462. ** If the user explicitly specified a likelihood() value for this term,
  137463. ** then the return value is the likelihood multiplied by the number of
  137464. ** input rows. Otherwise, this function assumes that an "IS NOT NULL" term
  137465. ** has a likelihood of 0.50, and any other term a likelihood of 0.25.
  137466. */
  137467. static LogEst whereRangeAdjust(WhereTerm *pTerm, LogEst nNew){
  137468. LogEst nRet = nNew;
  137469. if( pTerm ){
  137470. if( pTerm->truthProb<=0 ){
  137471. nRet += pTerm->truthProb;
  137472. }else if( (pTerm->wtFlags & TERM_VNULL)==0 ){
  137473. nRet -= 20; assert( 20==sqlite3LogEst(4) );
  137474. }
  137475. }
  137476. return nRet;
  137477. }
  137478. #ifdef SQLITE_ENABLE_STAT4
  137479. /*
  137480. ** Return the affinity for a single column of an index.
  137481. */
  137482. SQLITE_PRIVATE char sqlite3IndexColumnAffinity(sqlite3 *db, Index *pIdx, int iCol){
  137483. assert( iCol>=0 && iCol<pIdx->nColumn );
  137484. if( !pIdx->zColAff ){
  137485. if( sqlite3IndexAffinityStr(db, pIdx)==0 ) return SQLITE_AFF_BLOB;
  137486. }
  137487. assert( pIdx->zColAff[iCol]!=0 );
  137488. return pIdx->zColAff[iCol];
  137489. }
  137490. #endif
  137491. #ifdef SQLITE_ENABLE_STAT4
  137492. /*
  137493. ** This function is called to estimate the number of rows visited by a
  137494. ** range-scan on a skip-scan index. For example:
  137495. **
  137496. ** CREATE INDEX i1 ON t1(a, b, c);
  137497. ** SELECT * FROM t1 WHERE a=? AND c BETWEEN ? AND ?;
  137498. **
  137499. ** Value pLoop->nOut is currently set to the estimated number of rows
  137500. ** visited for scanning (a=? AND b=?). This function reduces that estimate
  137501. ** by some factor to account for the (c BETWEEN ? AND ?) expression based
  137502. ** on the stat4 data for the index. this scan will be peformed multiple
  137503. ** times (once for each (a,b) combination that matches a=?) is dealt with
  137504. ** by the caller.
  137505. **
  137506. ** It does this by scanning through all stat4 samples, comparing values
  137507. ** extracted from pLower and pUpper with the corresponding column in each
  137508. ** sample. If L and U are the number of samples found to be less than or
  137509. ** equal to the values extracted from pLower and pUpper respectively, and
  137510. ** N is the total number of samples, the pLoop->nOut value is adjusted
  137511. ** as follows:
  137512. **
  137513. ** nOut = nOut * ( min(U - L, 1) / N )
  137514. **
  137515. ** If pLower is NULL, or a value cannot be extracted from the term, L is
  137516. ** set to zero. If pUpper is NULL, or a value cannot be extracted from it,
  137517. ** U is set to N.
  137518. **
  137519. ** Normally, this function sets *pbDone to 1 before returning. However,
  137520. ** if no value can be extracted from either pLower or pUpper (and so the
  137521. ** estimate of the number of rows delivered remains unchanged), *pbDone
  137522. ** is left as is.
  137523. **
  137524. ** If an error occurs, an SQLite error code is returned. Otherwise,
  137525. ** SQLITE_OK.
  137526. */
  137527. static int whereRangeSkipScanEst(
  137528. Parse *pParse, /* Parsing & code generating context */
  137529. WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */
  137530. WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */
  137531. WhereLoop *pLoop, /* Update the .nOut value of this loop */
  137532. int *pbDone /* Set to true if at least one expr. value extracted */
  137533. ){
  137534. Index *p = pLoop->u.btree.pIndex;
  137535. int nEq = pLoop->u.btree.nEq;
  137536. sqlite3 *db = pParse->db;
  137537. int nLower = -1;
  137538. int nUpper = p->nSample+1;
  137539. int rc = SQLITE_OK;
  137540. u8 aff = sqlite3IndexColumnAffinity(db, p, nEq);
  137541. CollSeq *pColl;
  137542. sqlite3_value *p1 = 0; /* Value extracted from pLower */
  137543. sqlite3_value *p2 = 0; /* Value extracted from pUpper */
  137544. sqlite3_value *pVal = 0; /* Value extracted from record */
  137545. pColl = sqlite3LocateCollSeq(pParse, p->azColl[nEq]);
  137546. if( pLower ){
  137547. rc = sqlite3Stat4ValueFromExpr(pParse, pLower->pExpr->pRight, aff, &p1);
  137548. nLower = 0;
  137549. }
  137550. if( pUpper && rc==SQLITE_OK ){
  137551. rc = sqlite3Stat4ValueFromExpr(pParse, pUpper->pExpr->pRight, aff, &p2);
  137552. nUpper = p2 ? 0 : p->nSample;
  137553. }
  137554. if( p1 || p2 ){
  137555. int i;
  137556. int nDiff;
  137557. for(i=0; rc==SQLITE_OK && i<p->nSample; i++){
  137558. rc = sqlite3Stat4Column(db, p->aSample[i].p, p->aSample[i].n, nEq, &pVal);
  137559. if( rc==SQLITE_OK && p1 ){
  137560. int res = sqlite3MemCompare(p1, pVal, pColl);
  137561. if( res>=0 ) nLower++;
  137562. }
  137563. if( rc==SQLITE_OK && p2 ){
  137564. int res = sqlite3MemCompare(p2, pVal, pColl);
  137565. if( res>=0 ) nUpper++;
  137566. }
  137567. }
  137568. nDiff = (nUpper - nLower);
  137569. if( nDiff<=0 ) nDiff = 1;
  137570. /* If there is both an upper and lower bound specified, and the
  137571. ** comparisons indicate that they are close together, use the fallback
  137572. ** method (assume that the scan visits 1/64 of the rows) for estimating
  137573. ** the number of rows visited. Otherwise, estimate the number of rows
  137574. ** using the method described in the header comment for this function. */
  137575. if( nDiff!=1 || pUpper==0 || pLower==0 ){
  137576. int nAdjust = (sqlite3LogEst(p->nSample) - sqlite3LogEst(nDiff));
  137577. pLoop->nOut -= nAdjust;
  137578. *pbDone = 1;
  137579. WHERETRACE(0x10, ("range skip-scan regions: %u..%u adjust=%d est=%d\n",
  137580. nLower, nUpper, nAdjust*-1, pLoop->nOut));
  137581. }
  137582. }else{
  137583. assert( *pbDone==0 );
  137584. }
  137585. sqlite3ValueFree(p1);
  137586. sqlite3ValueFree(p2);
  137587. sqlite3ValueFree(pVal);
  137588. return rc;
  137589. }
  137590. #endif /* SQLITE_ENABLE_STAT4 */
  137591. /*
  137592. ** This function is used to estimate the number of rows that will be visited
  137593. ** by scanning an index for a range of values. The range may have an upper
  137594. ** bound, a lower bound, or both. The WHERE clause terms that set the upper
  137595. ** and lower bounds are represented by pLower and pUpper respectively. For
  137596. ** example, assuming that index p is on t1(a):
  137597. **
  137598. ** ... FROM t1 WHERE a > ? AND a < ? ...
  137599. ** |_____| |_____|
  137600. ** | |
  137601. ** pLower pUpper
  137602. **
  137603. ** If either of the upper or lower bound is not present, then NULL is passed in
  137604. ** place of the corresponding WhereTerm.
  137605. **
  137606. ** The value in (pBuilder->pNew->u.btree.nEq) is the number of the index
  137607. ** column subject to the range constraint. Or, equivalently, the number of
  137608. ** equality constraints optimized by the proposed index scan. For example,
  137609. ** assuming index p is on t1(a, b), and the SQL query is:
  137610. **
  137611. ** ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
  137612. **
  137613. ** then nEq is set to 1 (as the range restricted column, b, is the second
  137614. ** left-most column of the index). Or, if the query is:
  137615. **
  137616. ** ... FROM t1 WHERE a > ? AND a < ? ...
  137617. **
  137618. ** then nEq is set to 0.
  137619. **
  137620. ** When this function is called, *pnOut is set to the sqlite3LogEst() of the
  137621. ** number of rows that the index scan is expected to visit without
  137622. ** considering the range constraints. If nEq is 0, then *pnOut is the number of
  137623. ** rows in the index. Assuming no error occurs, *pnOut is adjusted (reduced)
  137624. ** to account for the range constraints pLower and pUpper.
  137625. **
  137626. ** In the absence of sqlite_stat4 ANALYZE data, or if such data cannot be
  137627. ** used, a single range inequality reduces the search space by a factor of 4.
  137628. ** and a pair of constraints (x>? AND x<?) reduces the expected number of
  137629. ** rows visited by a factor of 64.
  137630. */
  137631. static int whereRangeScanEst(
  137632. Parse *pParse, /* Parsing & code generating context */
  137633. WhereLoopBuilder *pBuilder,
  137634. WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */
  137635. WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */
  137636. WhereLoop *pLoop /* Modify the .nOut and maybe .rRun fields */
  137637. ){
  137638. int rc = SQLITE_OK;
  137639. int nOut = pLoop->nOut;
  137640. LogEst nNew;
  137641. #ifdef SQLITE_ENABLE_STAT4
  137642. Index *p = pLoop->u.btree.pIndex;
  137643. int nEq = pLoop->u.btree.nEq;
  137644. if( p->nSample>0 && ALWAYS(nEq<p->nSampleCol)
  137645. && OptimizationEnabled(pParse->db, SQLITE_Stat4)
  137646. ){
  137647. if( nEq==pBuilder->nRecValid ){
  137648. UnpackedRecord *pRec = pBuilder->pRec;
  137649. tRowcnt a[2];
  137650. int nBtm = pLoop->u.btree.nBtm;
  137651. int nTop = pLoop->u.btree.nTop;
  137652. /* Variable iLower will be set to the estimate of the number of rows in
  137653. ** the index that are less than the lower bound of the range query. The
  137654. ** lower bound being the concatenation of $P and $L, where $P is the
  137655. ** key-prefix formed by the nEq values matched against the nEq left-most
  137656. ** columns of the index, and $L is the value in pLower.
  137657. **
  137658. ** Or, if pLower is NULL or $L cannot be extracted from it (because it
  137659. ** is not a simple variable or literal value), the lower bound of the
  137660. ** range is $P. Due to a quirk in the way whereKeyStats() works, even
  137661. ** if $L is available, whereKeyStats() is called for both ($P) and
  137662. ** ($P:$L) and the larger of the two returned values is used.
  137663. **
  137664. ** Similarly, iUpper is to be set to the estimate of the number of rows
  137665. ** less than the upper bound of the range query. Where the upper bound
  137666. ** is either ($P) or ($P:$U). Again, even if $U is available, both values
  137667. ** of iUpper are requested of whereKeyStats() and the smaller used.
  137668. **
  137669. ** The number of rows between the two bounds is then just iUpper-iLower.
  137670. */
  137671. tRowcnt iLower; /* Rows less than the lower bound */
  137672. tRowcnt iUpper; /* Rows less than the upper bound */
  137673. int iLwrIdx = -2; /* aSample[] for the lower bound */
  137674. int iUprIdx = -1; /* aSample[] for the upper bound */
  137675. if( pRec ){
  137676. testcase( pRec->nField!=pBuilder->nRecValid );
  137677. pRec->nField = pBuilder->nRecValid;
  137678. }
  137679. /* Determine iLower and iUpper using ($P) only. */
  137680. if( nEq==0 ){
  137681. iLower = 0;
  137682. iUpper = p->nRowEst0;
  137683. }else{
  137684. /* Note: this call could be optimized away - since the same values must
  137685. ** have been requested when testing key $P in whereEqualScanEst(). */
  137686. whereKeyStats(pParse, p, pRec, 0, a);
  137687. iLower = a[0];
  137688. iUpper = a[0] + a[1];
  137689. }
  137690. assert( pLower==0 || (pLower->eOperator & (WO_GT|WO_GE))!=0 );
  137691. assert( pUpper==0 || (pUpper->eOperator & (WO_LT|WO_LE))!=0 );
  137692. assert( p->aSortOrder!=0 );
  137693. if( p->aSortOrder[nEq] ){
  137694. /* The roles of pLower and pUpper are swapped for a DESC index */
  137695. SWAP(WhereTerm*, pLower, pUpper);
  137696. SWAP(int, nBtm, nTop);
  137697. }
  137698. /* If possible, improve on the iLower estimate using ($P:$L). */
  137699. if( pLower ){
  137700. int n; /* Values extracted from pExpr */
  137701. Expr *pExpr = pLower->pExpr->pRight;
  137702. rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, nBtm, nEq, &n);
  137703. if( rc==SQLITE_OK && n ){
  137704. tRowcnt iNew;
  137705. u16 mask = WO_GT|WO_LE;
  137706. if( sqlite3ExprVectorSize(pExpr)>n ) mask = (WO_LE|WO_LT);
  137707. iLwrIdx = whereKeyStats(pParse, p, pRec, 0, a);
  137708. iNew = a[0] + ((pLower->eOperator & mask) ? a[1] : 0);
  137709. if( iNew>iLower ) iLower = iNew;
  137710. nOut--;
  137711. pLower = 0;
  137712. }
  137713. }
  137714. /* If possible, improve on the iUpper estimate using ($P:$U). */
  137715. if( pUpper ){
  137716. int n; /* Values extracted from pExpr */
  137717. Expr *pExpr = pUpper->pExpr->pRight;
  137718. rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, nTop, nEq, &n);
  137719. if( rc==SQLITE_OK && n ){
  137720. tRowcnt iNew;
  137721. u16 mask = WO_GT|WO_LE;
  137722. if( sqlite3ExprVectorSize(pExpr)>n ) mask = (WO_LE|WO_LT);
  137723. iUprIdx = whereKeyStats(pParse, p, pRec, 1, a);
  137724. iNew = a[0] + ((pUpper->eOperator & mask) ? a[1] : 0);
  137725. if( iNew<iUpper ) iUpper = iNew;
  137726. nOut--;
  137727. pUpper = 0;
  137728. }
  137729. }
  137730. pBuilder->pRec = pRec;
  137731. if( rc==SQLITE_OK ){
  137732. if( iUpper>iLower ){
  137733. nNew = sqlite3LogEst(iUpper - iLower);
  137734. /* TUNING: If both iUpper and iLower are derived from the same
  137735. ** sample, then assume they are 4x more selective. This brings
  137736. ** the estimated selectivity more in line with what it would be
  137737. ** if estimated without the use of STAT4 tables. */
  137738. if( iLwrIdx==iUprIdx ) nNew -= 20; assert( 20==sqlite3LogEst(4) );
  137739. }else{
  137740. nNew = 10; assert( 10==sqlite3LogEst(2) );
  137741. }
  137742. if( nNew<nOut ){
  137743. nOut = nNew;
  137744. }
  137745. WHERETRACE(0x10, ("STAT4 range scan: %u..%u est=%d\n",
  137746. (u32)iLower, (u32)iUpper, nOut));
  137747. }
  137748. }else{
  137749. int bDone = 0;
  137750. rc = whereRangeSkipScanEst(pParse, pLower, pUpper, pLoop, &bDone);
  137751. if( bDone ) return rc;
  137752. }
  137753. }
  137754. #else
  137755. UNUSED_PARAMETER(pParse);
  137756. UNUSED_PARAMETER(pBuilder);
  137757. assert( pLower || pUpper );
  137758. #endif
  137759. assert( pUpper==0 || (pUpper->wtFlags & TERM_VNULL)==0 );
  137760. nNew = whereRangeAdjust(pLower, nOut);
  137761. nNew = whereRangeAdjust(pUpper, nNew);
  137762. /* TUNING: If there is both an upper and lower limit and neither limit
  137763. ** has an application-defined likelihood(), assume the range is
  137764. ** reduced by an additional 75%. This means that, by default, an open-ended
  137765. ** range query (e.g. col > ?) is assumed to match 1/4 of the rows in the
  137766. ** index. While a closed range (e.g. col BETWEEN ? AND ?) is estimated to
  137767. ** match 1/64 of the index. */
  137768. if( pLower && pLower->truthProb>0 && pUpper && pUpper->truthProb>0 ){
  137769. nNew -= 20;
  137770. }
  137771. nOut -= (pLower!=0) + (pUpper!=0);
  137772. if( nNew<10 ) nNew = 10;
  137773. if( nNew<nOut ) nOut = nNew;
  137774. #if defined(WHERETRACE_ENABLED)
  137775. if( pLoop->nOut>nOut ){
  137776. WHERETRACE(0x10,("Range scan lowers nOut from %d to %d\n",
  137777. pLoop->nOut, nOut));
  137778. }
  137779. #endif
  137780. pLoop->nOut = (LogEst)nOut;
  137781. return rc;
  137782. }
  137783. #ifdef SQLITE_ENABLE_STAT4
  137784. /*
  137785. ** Estimate the number of rows that will be returned based on
  137786. ** an equality constraint x=VALUE and where that VALUE occurs in
  137787. ** the histogram data. This only works when x is the left-most
  137788. ** column of an index and sqlite_stat4 histogram data is available
  137789. ** for that index. When pExpr==NULL that means the constraint is
  137790. ** "x IS NULL" instead of "x=VALUE".
  137791. **
  137792. ** Write the estimated row count into *pnRow and return SQLITE_OK.
  137793. ** If unable to make an estimate, leave *pnRow unchanged and return
  137794. ** non-zero.
  137795. **
  137796. ** This routine can fail if it is unable to load a collating sequence
  137797. ** required for string comparison, or if unable to allocate memory
  137798. ** for a UTF conversion required for comparison. The error is stored
  137799. ** in the pParse structure.
  137800. */
  137801. static int whereEqualScanEst(
  137802. Parse *pParse, /* Parsing & code generating context */
  137803. WhereLoopBuilder *pBuilder,
  137804. Expr *pExpr, /* Expression for VALUE in the x=VALUE constraint */
  137805. tRowcnt *pnRow /* Write the revised row estimate here */
  137806. ){
  137807. Index *p = pBuilder->pNew->u.btree.pIndex;
  137808. int nEq = pBuilder->pNew->u.btree.nEq;
  137809. UnpackedRecord *pRec = pBuilder->pRec;
  137810. int rc; /* Subfunction return code */
  137811. tRowcnt a[2]; /* Statistics */
  137812. int bOk;
  137813. assert( nEq>=1 );
  137814. assert( nEq<=p->nColumn );
  137815. assert( p->aSample!=0 );
  137816. assert( p->nSample>0 );
  137817. assert( pBuilder->nRecValid<nEq );
  137818. /* If values are not available for all fields of the index to the left
  137819. ** of this one, no estimate can be made. Return SQLITE_NOTFOUND. */
  137820. if( pBuilder->nRecValid<(nEq-1) ){
  137821. return SQLITE_NOTFOUND;
  137822. }
  137823. /* This is an optimization only. The call to sqlite3Stat4ProbeSetValue()
  137824. ** below would return the same value. */
  137825. if( nEq>=p->nColumn ){
  137826. *pnRow = 1;
  137827. return SQLITE_OK;
  137828. }
  137829. rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, 1, nEq-1, &bOk);
  137830. pBuilder->pRec = pRec;
  137831. if( rc!=SQLITE_OK ) return rc;
  137832. if( bOk==0 ) return SQLITE_NOTFOUND;
  137833. pBuilder->nRecValid = nEq;
  137834. whereKeyStats(pParse, p, pRec, 0, a);
  137835. WHERETRACE(0x10,("equality scan regions %s(%d): %d\n",
  137836. p->zName, nEq-1, (int)a[1]));
  137837. *pnRow = a[1];
  137838. return rc;
  137839. }
  137840. #endif /* SQLITE_ENABLE_STAT4 */
  137841. #ifdef SQLITE_ENABLE_STAT4
  137842. /*
  137843. ** Estimate the number of rows that will be returned based on
  137844. ** an IN constraint where the right-hand side of the IN operator
  137845. ** is a list of values. Example:
  137846. **
  137847. ** WHERE x IN (1,2,3,4)
  137848. **
  137849. ** Write the estimated row count into *pnRow and return SQLITE_OK.
  137850. ** If unable to make an estimate, leave *pnRow unchanged and return
  137851. ** non-zero.
  137852. **
  137853. ** This routine can fail if it is unable to load a collating sequence
  137854. ** required for string comparison, or if unable to allocate memory
  137855. ** for a UTF conversion required for comparison. The error is stored
  137856. ** in the pParse structure.
  137857. */
  137858. static int whereInScanEst(
  137859. Parse *pParse, /* Parsing & code generating context */
  137860. WhereLoopBuilder *pBuilder,
  137861. ExprList *pList, /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
  137862. tRowcnt *pnRow /* Write the revised row estimate here */
  137863. ){
  137864. Index *p = pBuilder->pNew->u.btree.pIndex;
  137865. i64 nRow0 = sqlite3LogEstToInt(p->aiRowLogEst[0]);
  137866. int nRecValid = pBuilder->nRecValid;
  137867. int rc = SQLITE_OK; /* Subfunction return code */
  137868. tRowcnt nEst; /* Number of rows for a single term */
  137869. tRowcnt nRowEst = 0; /* New estimate of the number of rows */
  137870. int i; /* Loop counter */
  137871. assert( p->aSample!=0 );
  137872. for(i=0; rc==SQLITE_OK && i<pList->nExpr; i++){
  137873. nEst = nRow0;
  137874. rc = whereEqualScanEst(pParse, pBuilder, pList->a[i].pExpr, &nEst);
  137875. nRowEst += nEst;
  137876. pBuilder->nRecValid = nRecValid;
  137877. }
  137878. if( rc==SQLITE_OK ){
  137879. if( nRowEst > nRow0 ) nRowEst = nRow0;
  137880. *pnRow = nRowEst;
  137881. WHERETRACE(0x10,("IN row estimate: est=%d\n", nRowEst));
  137882. }
  137883. assert( pBuilder->nRecValid==nRecValid );
  137884. return rc;
  137885. }
  137886. #endif /* SQLITE_ENABLE_STAT4 */
  137887. #ifdef WHERETRACE_ENABLED
  137888. /*
  137889. ** Print the content of a WhereTerm object
  137890. */
  137891. SQLITE_PRIVATE void sqlite3WhereTermPrint(WhereTerm *pTerm, int iTerm){
  137892. if( pTerm==0 ){
  137893. sqlite3DebugPrintf("TERM-%-3d NULL\n", iTerm);
  137894. }else{
  137895. char zType[8];
  137896. char zLeft[50];
  137897. memcpy(zType, "....", 5);
  137898. if( pTerm->wtFlags & TERM_VIRTUAL ) zType[0] = 'V';
  137899. if( pTerm->eOperator & WO_EQUIV ) zType[1] = 'E';
  137900. if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) zType[2] = 'L';
  137901. if( pTerm->wtFlags & TERM_CODED ) zType[3] = 'C';
  137902. if( pTerm->eOperator & WO_SINGLE ){
  137903. sqlite3_snprintf(sizeof(zLeft),zLeft,"left={%d:%d}",
  137904. pTerm->leftCursor, pTerm->u.leftColumn);
  137905. }else if( (pTerm->eOperator & WO_OR)!=0 && pTerm->u.pOrInfo!=0 ){
  137906. sqlite3_snprintf(sizeof(zLeft),zLeft,"indexable=0x%lld",
  137907. pTerm->u.pOrInfo->indexable);
  137908. }else{
  137909. sqlite3_snprintf(sizeof(zLeft),zLeft,"left=%d", pTerm->leftCursor);
  137910. }
  137911. sqlite3DebugPrintf(
  137912. "TERM-%-3d %p %s %-12s op=%03x wtFlags=%04x",
  137913. iTerm, pTerm, zType, zLeft, pTerm->eOperator, pTerm->wtFlags);
  137914. /* The 0x10000 .wheretrace flag causes extra information to be
  137915. ** shown about each Term */
  137916. if( sqlite3WhereTrace & 0x10000 ){
  137917. sqlite3DebugPrintf(" prob=%-3d prereq=%llx,%llx",
  137918. pTerm->truthProb, (u64)pTerm->prereqAll, (u64)pTerm->prereqRight);
  137919. }
  137920. if( pTerm->iField ){
  137921. sqlite3DebugPrintf(" iField=%d", pTerm->iField);
  137922. }
  137923. if( pTerm->iParent>=0 ){
  137924. sqlite3DebugPrintf(" iParent=%d", pTerm->iParent);
  137925. }
  137926. sqlite3DebugPrintf("\n");
  137927. sqlite3TreeViewExpr(0, pTerm->pExpr, 0);
  137928. }
  137929. }
  137930. #endif
  137931. #ifdef WHERETRACE_ENABLED
  137932. /*
  137933. ** Show the complete content of a WhereClause
  137934. */
  137935. SQLITE_PRIVATE void sqlite3WhereClausePrint(WhereClause *pWC){
  137936. int i;
  137937. for(i=0; i<pWC->nTerm; i++){
  137938. sqlite3WhereTermPrint(&pWC->a[i], i);
  137939. }
  137940. }
  137941. #endif
  137942. #ifdef WHERETRACE_ENABLED
  137943. /*
  137944. ** Print a WhereLoop object for debugging purposes
  137945. */
  137946. SQLITE_PRIVATE void sqlite3WhereLoopPrint(WhereLoop *p, WhereClause *pWC){
  137947. WhereInfo *pWInfo = pWC->pWInfo;
  137948. int nb = 1+(pWInfo->pTabList->nSrc+3)/4;
  137949. struct SrcList_item *pItem = pWInfo->pTabList->a + p->iTab;
  137950. Table *pTab = pItem->pTab;
  137951. Bitmask mAll = (((Bitmask)1)<<(nb*4)) - 1;
  137952. sqlite3DebugPrintf("%c%2d.%0*llx.%0*llx", p->cId,
  137953. p->iTab, nb, p->maskSelf, nb, p->prereq & mAll);
  137954. sqlite3DebugPrintf(" %12s",
  137955. pItem->zAlias ? pItem->zAlias : pTab->zName);
  137956. if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
  137957. const char *zName;
  137958. if( p->u.btree.pIndex && (zName = p->u.btree.pIndex->zName)!=0 ){
  137959. if( strncmp(zName, "sqlite_autoindex_", 17)==0 ){
  137960. int i = sqlite3Strlen30(zName) - 1;
  137961. while( zName[i]!='_' ) i--;
  137962. zName += i;
  137963. }
  137964. sqlite3DebugPrintf(".%-16s %2d", zName, p->u.btree.nEq);
  137965. }else{
  137966. sqlite3DebugPrintf("%20s","");
  137967. }
  137968. }else{
  137969. char *z;
  137970. if( p->u.vtab.idxStr ){
  137971. z = sqlite3_mprintf("(%d,\"%s\",%#x)",
  137972. p->u.vtab.idxNum, p->u.vtab.idxStr, p->u.vtab.omitMask);
  137973. }else{
  137974. z = sqlite3_mprintf("(%d,%x)", p->u.vtab.idxNum, p->u.vtab.omitMask);
  137975. }
  137976. sqlite3DebugPrintf(" %-19s", z);
  137977. sqlite3_free(z);
  137978. }
  137979. if( p->wsFlags & WHERE_SKIPSCAN ){
  137980. sqlite3DebugPrintf(" f %05x %d-%d", p->wsFlags, p->nLTerm,p->nSkip);
  137981. }else{
  137982. sqlite3DebugPrintf(" f %05x N %d", p->wsFlags, p->nLTerm);
  137983. }
  137984. sqlite3DebugPrintf(" cost %d,%d,%d\n", p->rSetup, p->rRun, p->nOut);
  137985. if( p->nLTerm && (sqlite3WhereTrace & 0x100)!=0 ){
  137986. int i;
  137987. for(i=0; i<p->nLTerm; i++){
  137988. sqlite3WhereTermPrint(p->aLTerm[i], i);
  137989. }
  137990. }
  137991. }
  137992. #endif
  137993. /*
  137994. ** Convert bulk memory into a valid WhereLoop that can be passed
  137995. ** to whereLoopClear harmlessly.
  137996. */
  137997. static void whereLoopInit(WhereLoop *p){
  137998. p->aLTerm = p->aLTermSpace;
  137999. p->nLTerm = 0;
  138000. p->nLSlot = ArraySize(p->aLTermSpace);
  138001. p->wsFlags = 0;
  138002. }
  138003. /*
  138004. ** Clear the WhereLoop.u union. Leave WhereLoop.pLTerm intact.
  138005. */
  138006. static void whereLoopClearUnion(sqlite3 *db, WhereLoop *p){
  138007. if( p->wsFlags & (WHERE_VIRTUALTABLE|WHERE_AUTO_INDEX) ){
  138008. if( (p->wsFlags & WHERE_VIRTUALTABLE)!=0 && p->u.vtab.needFree ){
  138009. sqlite3_free(p->u.vtab.idxStr);
  138010. p->u.vtab.needFree = 0;
  138011. p->u.vtab.idxStr = 0;
  138012. }else if( (p->wsFlags & WHERE_AUTO_INDEX)!=0 && p->u.btree.pIndex!=0 ){
  138013. sqlite3DbFree(db, p->u.btree.pIndex->zColAff);
  138014. sqlite3DbFreeNN(db, p->u.btree.pIndex);
  138015. p->u.btree.pIndex = 0;
  138016. }
  138017. }
  138018. }
  138019. /*
  138020. ** Deallocate internal memory used by a WhereLoop object
  138021. */
  138022. static void whereLoopClear(sqlite3 *db, WhereLoop *p){
  138023. if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFreeNN(db, p->aLTerm);
  138024. whereLoopClearUnion(db, p);
  138025. whereLoopInit(p);
  138026. }
  138027. /*
  138028. ** Increase the memory allocation for pLoop->aLTerm[] to be at least n.
  138029. */
  138030. static int whereLoopResize(sqlite3 *db, WhereLoop *p, int n){
  138031. WhereTerm **paNew;
  138032. if( p->nLSlot>=n ) return SQLITE_OK;
  138033. n = (n+7)&~7;
  138034. paNew = sqlite3DbMallocRawNN(db, sizeof(p->aLTerm[0])*n);
  138035. if( paNew==0 ) return SQLITE_NOMEM_BKPT;
  138036. memcpy(paNew, p->aLTerm, sizeof(p->aLTerm[0])*p->nLSlot);
  138037. if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFreeNN(db, p->aLTerm);
  138038. p->aLTerm = paNew;
  138039. p->nLSlot = n;
  138040. return SQLITE_OK;
  138041. }
  138042. /*
  138043. ** Transfer content from the second pLoop into the first.
  138044. */
  138045. static int whereLoopXfer(sqlite3 *db, WhereLoop *pTo, WhereLoop *pFrom){
  138046. whereLoopClearUnion(db, pTo);
  138047. if( whereLoopResize(db, pTo, pFrom->nLTerm) ){
  138048. memset(&pTo->u, 0, sizeof(pTo->u));
  138049. return SQLITE_NOMEM_BKPT;
  138050. }
  138051. memcpy(pTo, pFrom, WHERE_LOOP_XFER_SZ);
  138052. memcpy(pTo->aLTerm, pFrom->aLTerm, pTo->nLTerm*sizeof(pTo->aLTerm[0]));
  138053. if( pFrom->wsFlags & WHERE_VIRTUALTABLE ){
  138054. pFrom->u.vtab.needFree = 0;
  138055. }else if( (pFrom->wsFlags & WHERE_AUTO_INDEX)!=0 ){
  138056. pFrom->u.btree.pIndex = 0;
  138057. }
  138058. return SQLITE_OK;
  138059. }
  138060. /*
  138061. ** Delete a WhereLoop object
  138062. */
  138063. static void whereLoopDelete(sqlite3 *db, WhereLoop *p){
  138064. whereLoopClear(db, p);
  138065. sqlite3DbFreeNN(db, p);
  138066. }
  138067. /*
  138068. ** Free a WhereInfo structure
  138069. */
  138070. static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
  138071. int i;
  138072. assert( pWInfo!=0 );
  138073. for(i=0; i<pWInfo->nLevel; i++){
  138074. WhereLevel *pLevel = &pWInfo->a[i];
  138075. if( pLevel->pWLoop && (pLevel->pWLoop->wsFlags & WHERE_IN_ABLE) ){
  138076. sqlite3DbFree(db, pLevel->u.in.aInLoop);
  138077. }
  138078. }
  138079. sqlite3WhereClauseClear(&pWInfo->sWC);
  138080. while( pWInfo->pLoops ){
  138081. WhereLoop *p = pWInfo->pLoops;
  138082. pWInfo->pLoops = p->pNextLoop;
  138083. whereLoopDelete(db, p);
  138084. }
  138085. assert( pWInfo->pExprMods==0 );
  138086. sqlite3DbFreeNN(db, pWInfo);
  138087. }
  138088. /*
  138089. ** Return TRUE if all of the following are true:
  138090. **
  138091. ** (1) X has the same or lower cost that Y
  138092. ** (2) X uses fewer WHERE clause terms than Y
  138093. ** (3) Every WHERE clause term used by X is also used by Y
  138094. ** (4) X skips at least as many columns as Y
  138095. ** (5) If X is a covering index, than Y is too
  138096. **
  138097. ** Conditions (2) and (3) mean that X is a "proper subset" of Y.
  138098. ** If X is a proper subset of Y then Y is a better choice and ought
  138099. ** to have a lower cost. This routine returns TRUE when that cost
  138100. ** relationship is inverted and needs to be adjusted. Constraint (4)
  138101. ** was added because if X uses skip-scan less than Y it still might
  138102. ** deserve a lower cost even if it is a proper subset of Y. Constraint (5)
  138103. ** was added because a covering index probably deserves to have a lower cost
  138104. ** than a non-covering index even if it is a proper subset.
  138105. */
  138106. static int whereLoopCheaperProperSubset(
  138107. const WhereLoop *pX, /* First WhereLoop to compare */
  138108. const WhereLoop *pY /* Compare against this WhereLoop */
  138109. ){
  138110. int i, j;
  138111. if( pX->nLTerm-pX->nSkip >= pY->nLTerm-pY->nSkip ){
  138112. return 0; /* X is not a subset of Y */
  138113. }
  138114. if( pY->nSkip > pX->nSkip ) return 0;
  138115. if( pX->rRun >= pY->rRun ){
  138116. if( pX->rRun > pY->rRun ) return 0; /* X costs more than Y */
  138117. if( pX->nOut > pY->nOut ) return 0; /* X costs more than Y */
  138118. }
  138119. for(i=pX->nLTerm-1; i>=0; i--){
  138120. if( pX->aLTerm[i]==0 ) continue;
  138121. for(j=pY->nLTerm-1; j>=0; j--){
  138122. if( pY->aLTerm[j]==pX->aLTerm[i] ) break;
  138123. }
  138124. if( j<0 ) return 0; /* X not a subset of Y since term X[i] not used by Y */
  138125. }
  138126. if( (pX->wsFlags&WHERE_IDX_ONLY)!=0
  138127. && (pY->wsFlags&WHERE_IDX_ONLY)==0 ){
  138128. return 0; /* Constraint (5) */
  138129. }
  138130. return 1; /* All conditions meet */
  138131. }
  138132. /*
  138133. ** Try to adjust the cost of WhereLoop pTemplate upwards or downwards so
  138134. ** that:
  138135. **
  138136. ** (1) pTemplate costs less than any other WhereLoops that are a proper
  138137. ** subset of pTemplate
  138138. **
  138139. ** (2) pTemplate costs more than any other WhereLoops for which pTemplate
  138140. ** is a proper subset.
  138141. **
  138142. ** To say "WhereLoop X is a proper subset of Y" means that X uses fewer
  138143. ** WHERE clause terms than Y and that every WHERE clause term used by X is
  138144. ** also used by Y.
  138145. */
  138146. static void whereLoopAdjustCost(const WhereLoop *p, WhereLoop *pTemplate){
  138147. if( (pTemplate->wsFlags & WHERE_INDEXED)==0 ) return;
  138148. for(; p; p=p->pNextLoop){
  138149. if( p->iTab!=pTemplate->iTab ) continue;
  138150. if( (p->wsFlags & WHERE_INDEXED)==0 ) continue;
  138151. if( whereLoopCheaperProperSubset(p, pTemplate) ){
  138152. /* Adjust pTemplate cost downward so that it is cheaper than its
  138153. ** subset p. */
  138154. WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n",
  138155. pTemplate->rRun, pTemplate->nOut, p->rRun, p->nOut-1));
  138156. pTemplate->rRun = p->rRun;
  138157. pTemplate->nOut = p->nOut - 1;
  138158. }else if( whereLoopCheaperProperSubset(pTemplate, p) ){
  138159. /* Adjust pTemplate cost upward so that it is costlier than p since
  138160. ** pTemplate is a proper subset of p */
  138161. WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n",
  138162. pTemplate->rRun, pTemplate->nOut, p->rRun, p->nOut+1));
  138163. pTemplate->rRun = p->rRun;
  138164. pTemplate->nOut = p->nOut + 1;
  138165. }
  138166. }
  138167. }
  138168. /*
  138169. ** Search the list of WhereLoops in *ppPrev looking for one that can be
  138170. ** replaced by pTemplate.
  138171. **
  138172. ** Return NULL if pTemplate does not belong on the WhereLoop list.
  138173. ** In other words if pTemplate ought to be dropped from further consideration.
  138174. **
  138175. ** If pX is a WhereLoop that pTemplate can replace, then return the
  138176. ** link that points to pX.
  138177. **
  138178. ** If pTemplate cannot replace any existing element of the list but needs
  138179. ** to be added to the list as a new entry, then return a pointer to the
  138180. ** tail of the list.
  138181. */
  138182. static WhereLoop **whereLoopFindLesser(
  138183. WhereLoop **ppPrev,
  138184. const WhereLoop *pTemplate
  138185. ){
  138186. WhereLoop *p;
  138187. for(p=(*ppPrev); p; ppPrev=&p->pNextLoop, p=*ppPrev){
  138188. if( p->iTab!=pTemplate->iTab || p->iSortIdx!=pTemplate->iSortIdx ){
  138189. /* If either the iTab or iSortIdx values for two WhereLoop are different
  138190. ** then those WhereLoops need to be considered separately. Neither is
  138191. ** a candidate to replace the other. */
  138192. continue;
  138193. }
  138194. /* In the current implementation, the rSetup value is either zero
  138195. ** or the cost of building an automatic index (NlogN) and the NlogN
  138196. ** is the same for compatible WhereLoops. */
  138197. assert( p->rSetup==0 || pTemplate->rSetup==0
  138198. || p->rSetup==pTemplate->rSetup );
  138199. /* whereLoopAddBtree() always generates and inserts the automatic index
  138200. ** case first. Hence compatible candidate WhereLoops never have a larger
  138201. ** rSetup. Call this SETUP-INVARIANT */
  138202. assert( p->rSetup>=pTemplate->rSetup );
  138203. /* Any loop using an appliation-defined index (or PRIMARY KEY or
  138204. ** UNIQUE constraint) with one or more == constraints is better
  138205. ** than an automatic index. Unless it is a skip-scan. */
  138206. if( (p->wsFlags & WHERE_AUTO_INDEX)!=0
  138207. && (pTemplate->nSkip)==0
  138208. && (pTemplate->wsFlags & WHERE_INDEXED)!=0
  138209. && (pTemplate->wsFlags & WHERE_COLUMN_EQ)!=0
  138210. && (p->prereq & pTemplate->prereq)==pTemplate->prereq
  138211. ){
  138212. break;
  138213. }
  138214. /* If existing WhereLoop p is better than pTemplate, pTemplate can be
  138215. ** discarded. WhereLoop p is better if:
  138216. ** (1) p has no more dependencies than pTemplate, and
  138217. ** (2) p has an equal or lower cost than pTemplate
  138218. */
  138219. if( (p->prereq & pTemplate->prereq)==p->prereq /* (1) */
  138220. && p->rSetup<=pTemplate->rSetup /* (2a) */
  138221. && p->rRun<=pTemplate->rRun /* (2b) */
  138222. && p->nOut<=pTemplate->nOut /* (2c) */
  138223. ){
  138224. return 0; /* Discard pTemplate */
  138225. }
  138226. /* If pTemplate is always better than p, then cause p to be overwritten
  138227. ** with pTemplate. pTemplate is better than p if:
  138228. ** (1) pTemplate has no more dependences than p, and
  138229. ** (2) pTemplate has an equal or lower cost than p.
  138230. */
  138231. if( (p->prereq & pTemplate->prereq)==pTemplate->prereq /* (1) */
  138232. && p->rRun>=pTemplate->rRun /* (2a) */
  138233. && p->nOut>=pTemplate->nOut /* (2b) */
  138234. ){
  138235. assert( p->rSetup>=pTemplate->rSetup ); /* SETUP-INVARIANT above */
  138236. break; /* Cause p to be overwritten by pTemplate */
  138237. }
  138238. }
  138239. return ppPrev;
  138240. }
  138241. /*
  138242. ** Insert or replace a WhereLoop entry using the template supplied.
  138243. **
  138244. ** An existing WhereLoop entry might be overwritten if the new template
  138245. ** is better and has fewer dependencies. Or the template will be ignored
  138246. ** and no insert will occur if an existing WhereLoop is faster and has
  138247. ** fewer dependencies than the template. Otherwise a new WhereLoop is
  138248. ** added based on the template.
  138249. **
  138250. ** If pBuilder->pOrSet is not NULL then we care about only the
  138251. ** prerequisites and rRun and nOut costs of the N best loops. That
  138252. ** information is gathered in the pBuilder->pOrSet object. This special
  138253. ** processing mode is used only for OR clause processing.
  138254. **
  138255. ** When accumulating multiple loops (when pBuilder->pOrSet is NULL) we
  138256. ** still might overwrite similar loops with the new template if the
  138257. ** new template is better. Loops may be overwritten if the following
  138258. ** conditions are met:
  138259. **
  138260. ** (1) They have the same iTab.
  138261. ** (2) They have the same iSortIdx.
  138262. ** (3) The template has same or fewer dependencies than the current loop
  138263. ** (4) The template has the same or lower cost than the current loop
  138264. */
  138265. static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){
  138266. WhereLoop **ppPrev, *p;
  138267. WhereInfo *pWInfo = pBuilder->pWInfo;
  138268. sqlite3 *db = pWInfo->pParse->db;
  138269. int rc;
  138270. /* Stop the search once we hit the query planner search limit */
  138271. if( pBuilder->iPlanLimit==0 ){
  138272. WHERETRACE(0xffffffff,("=== query planner search limit reached ===\n"));
  138273. if( pBuilder->pOrSet ) pBuilder->pOrSet->n = 0;
  138274. return SQLITE_DONE;
  138275. }
  138276. pBuilder->iPlanLimit--;
  138277. whereLoopAdjustCost(pWInfo->pLoops, pTemplate);
  138278. /* If pBuilder->pOrSet is defined, then only keep track of the costs
  138279. ** and prereqs.
  138280. */
  138281. if( pBuilder->pOrSet!=0 ){
  138282. if( pTemplate->nLTerm ){
  138283. #if WHERETRACE_ENABLED
  138284. u16 n = pBuilder->pOrSet->n;
  138285. int x =
  138286. #endif
  138287. whereOrInsert(pBuilder->pOrSet, pTemplate->prereq, pTemplate->rRun,
  138288. pTemplate->nOut);
  138289. #if WHERETRACE_ENABLED /* 0x8 */
  138290. if( sqlite3WhereTrace & 0x8 ){
  138291. sqlite3DebugPrintf(x?" or-%d: ":" or-X: ", n);
  138292. sqlite3WhereLoopPrint(pTemplate, pBuilder->pWC);
  138293. }
  138294. #endif
  138295. }
  138296. return SQLITE_OK;
  138297. }
  138298. /* Look for an existing WhereLoop to replace with pTemplate
  138299. */
  138300. ppPrev = whereLoopFindLesser(&pWInfo->pLoops, pTemplate);
  138301. if( ppPrev==0 ){
  138302. /* There already exists a WhereLoop on the list that is better
  138303. ** than pTemplate, so just ignore pTemplate */
  138304. #if WHERETRACE_ENABLED /* 0x8 */
  138305. if( sqlite3WhereTrace & 0x8 ){
  138306. sqlite3DebugPrintf(" skip: ");
  138307. sqlite3WhereLoopPrint(pTemplate, pBuilder->pWC);
  138308. }
  138309. #endif
  138310. return SQLITE_OK;
  138311. }else{
  138312. p = *ppPrev;
  138313. }
  138314. /* If we reach this point it means that either p[] should be overwritten
  138315. ** with pTemplate[] if p[] exists, or if p==NULL then allocate a new
  138316. ** WhereLoop and insert it.
  138317. */
  138318. #if WHERETRACE_ENABLED /* 0x8 */
  138319. if( sqlite3WhereTrace & 0x8 ){
  138320. if( p!=0 ){
  138321. sqlite3DebugPrintf("replace: ");
  138322. sqlite3WhereLoopPrint(p, pBuilder->pWC);
  138323. sqlite3DebugPrintf(" with: ");
  138324. }else{
  138325. sqlite3DebugPrintf(" add: ");
  138326. }
  138327. sqlite3WhereLoopPrint(pTemplate, pBuilder->pWC);
  138328. }
  138329. #endif
  138330. if( p==0 ){
  138331. /* Allocate a new WhereLoop to add to the end of the list */
  138332. *ppPrev = p = sqlite3DbMallocRawNN(db, sizeof(WhereLoop));
  138333. if( p==0 ) return SQLITE_NOMEM_BKPT;
  138334. whereLoopInit(p);
  138335. p->pNextLoop = 0;
  138336. }else{
  138337. /* We will be overwriting WhereLoop p[]. But before we do, first
  138338. ** go through the rest of the list and delete any other entries besides
  138339. ** p[] that are also supplated by pTemplate */
  138340. WhereLoop **ppTail = &p->pNextLoop;
  138341. WhereLoop *pToDel;
  138342. while( *ppTail ){
  138343. ppTail = whereLoopFindLesser(ppTail, pTemplate);
  138344. if( ppTail==0 ) break;
  138345. pToDel = *ppTail;
  138346. if( pToDel==0 ) break;
  138347. *ppTail = pToDel->pNextLoop;
  138348. #if WHERETRACE_ENABLED /* 0x8 */
  138349. if( sqlite3WhereTrace & 0x8 ){
  138350. sqlite3DebugPrintf(" delete: ");
  138351. sqlite3WhereLoopPrint(pToDel, pBuilder->pWC);
  138352. }
  138353. #endif
  138354. whereLoopDelete(db, pToDel);
  138355. }
  138356. }
  138357. rc = whereLoopXfer(db, p, pTemplate);
  138358. if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
  138359. Index *pIndex = p->u.btree.pIndex;
  138360. if( pIndex && pIndex->idxType==SQLITE_IDXTYPE_IPK ){
  138361. p->u.btree.pIndex = 0;
  138362. }
  138363. }
  138364. return rc;
  138365. }
  138366. /*
  138367. ** Adjust the WhereLoop.nOut value downward to account for terms of the
  138368. ** WHERE clause that reference the loop but which are not used by an
  138369. ** index.
  138370. *
  138371. ** For every WHERE clause term that is not used by the index
  138372. ** and which has a truth probability assigned by one of the likelihood(),
  138373. ** likely(), or unlikely() SQL functions, reduce the estimated number
  138374. ** of output rows by the probability specified.
  138375. **
  138376. ** TUNING: For every WHERE clause term that is not used by the index
  138377. ** and which does not have an assigned truth probability, heuristics
  138378. ** described below are used to try to estimate the truth probability.
  138379. ** TODO --> Perhaps this is something that could be improved by better
  138380. ** table statistics.
  138381. **
  138382. ** Heuristic 1: Estimate the truth probability as 93.75%. The 93.75%
  138383. ** value corresponds to -1 in LogEst notation, so this means decrement
  138384. ** the WhereLoop.nOut field for every such WHERE clause term.
  138385. **
  138386. ** Heuristic 2: If there exists one or more WHERE clause terms of the
  138387. ** form "x==EXPR" and EXPR is not a constant 0 or 1, then make sure the
  138388. ** final output row estimate is no greater than 1/4 of the total number
  138389. ** of rows in the table. In other words, assume that x==EXPR will filter
  138390. ** out at least 3 out of 4 rows. If EXPR is -1 or 0 or 1, then maybe the
  138391. ** "x" column is boolean or else -1 or 0 or 1 is a common default value
  138392. ** on the "x" column and so in that case only cap the output row estimate
  138393. ** at 1/2 instead of 1/4.
  138394. */
  138395. static void whereLoopOutputAdjust(
  138396. WhereClause *pWC, /* The WHERE clause */
  138397. WhereLoop *pLoop, /* The loop to adjust downward */
  138398. LogEst nRow /* Number of rows in the entire table */
  138399. ){
  138400. WhereTerm *pTerm, *pX;
  138401. Bitmask notAllowed = ~(pLoop->prereq|pLoop->maskSelf);
  138402. int i, j;
  138403. LogEst iReduce = 0; /* pLoop->nOut should not exceed nRow-iReduce */
  138404. assert( (pLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
  138405. for(i=pWC->nTerm, pTerm=pWC->a; i>0; i--, pTerm++){
  138406. assert( pTerm!=0 );
  138407. if( (pTerm->wtFlags & TERM_VIRTUAL)!=0 ) break;
  138408. if( (pTerm->prereqAll & pLoop->maskSelf)==0 ) continue;
  138409. if( (pTerm->prereqAll & notAllowed)!=0 ) continue;
  138410. for(j=pLoop->nLTerm-1; j>=0; j--){
  138411. pX = pLoop->aLTerm[j];
  138412. if( pX==0 ) continue;
  138413. if( pX==pTerm ) break;
  138414. if( pX->iParent>=0 && (&pWC->a[pX->iParent])==pTerm ) break;
  138415. }
  138416. if( j<0 ){
  138417. if( pTerm->truthProb<=0 ){
  138418. /* If a truth probability is specified using the likelihood() hints,
  138419. ** then use the probability provided by the application. */
  138420. pLoop->nOut += pTerm->truthProb;
  138421. }else{
  138422. /* In the absence of explicit truth probabilities, use heuristics to
  138423. ** guess a reasonable truth probability. */
  138424. pLoop->nOut--;
  138425. if( (pTerm->eOperator&(WO_EQ|WO_IS))!=0
  138426. && (pTerm->wtFlags & TERM_HIGHTRUTH)==0 /* tag-20200224-1 */
  138427. ){
  138428. Expr *pRight = pTerm->pExpr->pRight;
  138429. int k = 0;
  138430. testcase( pTerm->pExpr->op==TK_IS );
  138431. if( sqlite3ExprIsInteger(pRight, &k) && k>=(-1) && k<=1 ){
  138432. k = 10;
  138433. }else{
  138434. k = 20;
  138435. }
  138436. if( iReduce<k ){
  138437. pTerm->wtFlags |= TERM_HEURTRUTH;
  138438. iReduce = k;
  138439. }
  138440. }
  138441. }
  138442. }
  138443. }
  138444. if( pLoop->nOut > nRow-iReduce ) pLoop->nOut = nRow - iReduce;
  138445. }
  138446. /*
  138447. ** Term pTerm is a vector range comparison operation. The first comparison
  138448. ** in the vector can be optimized using column nEq of the index. This
  138449. ** function returns the total number of vector elements that can be used
  138450. ** as part of the range comparison.
  138451. **
  138452. ** For example, if the query is:
  138453. **
  138454. ** WHERE a = ? AND (b, c, d) > (?, ?, ?)
  138455. **
  138456. ** and the index:
  138457. **
  138458. ** CREATE INDEX ... ON (a, b, c, d, e)
  138459. **
  138460. ** then this function would be invoked with nEq=1. The value returned in
  138461. ** this case is 3.
  138462. */
  138463. static int whereRangeVectorLen(
  138464. Parse *pParse, /* Parsing context */
  138465. int iCur, /* Cursor open on pIdx */
  138466. Index *pIdx, /* The index to be used for a inequality constraint */
  138467. int nEq, /* Number of prior equality constraints on same index */
  138468. WhereTerm *pTerm /* The vector inequality constraint */
  138469. ){
  138470. int nCmp = sqlite3ExprVectorSize(pTerm->pExpr->pLeft);
  138471. int i;
  138472. nCmp = MIN(nCmp, (pIdx->nColumn - nEq));
  138473. for(i=1; i<nCmp; i++){
  138474. /* Test if comparison i of pTerm is compatible with column (i+nEq)
  138475. ** of the index. If not, exit the loop. */
  138476. char aff; /* Comparison affinity */
  138477. char idxaff = 0; /* Indexed columns affinity */
  138478. CollSeq *pColl; /* Comparison collation sequence */
  138479. Expr *pLhs = pTerm->pExpr->pLeft->x.pList->a[i].pExpr;
  138480. Expr *pRhs = pTerm->pExpr->pRight;
  138481. if( pRhs->flags & EP_xIsSelect ){
  138482. pRhs = pRhs->x.pSelect->pEList->a[i].pExpr;
  138483. }else{
  138484. pRhs = pRhs->x.pList->a[i].pExpr;
  138485. }
  138486. /* Check that the LHS of the comparison is a column reference to
  138487. ** the right column of the right source table. And that the sort
  138488. ** order of the index column is the same as the sort order of the
  138489. ** leftmost index column. */
  138490. if( pLhs->op!=TK_COLUMN
  138491. || pLhs->iTable!=iCur
  138492. || pLhs->iColumn!=pIdx->aiColumn[i+nEq]
  138493. || pIdx->aSortOrder[i+nEq]!=pIdx->aSortOrder[nEq]
  138494. ){
  138495. break;
  138496. }
  138497. testcase( pLhs->iColumn==XN_ROWID );
  138498. aff = sqlite3CompareAffinity(pRhs, sqlite3ExprAffinity(pLhs));
  138499. idxaff = sqlite3TableColumnAffinity(pIdx->pTable, pLhs->iColumn);
  138500. if( aff!=idxaff ) break;
  138501. pColl = sqlite3BinaryCompareCollSeq(pParse, pLhs, pRhs);
  138502. if( pColl==0 ) break;
  138503. if( sqlite3StrICmp(pColl->zName, pIdx->azColl[i+nEq]) ) break;
  138504. }
  138505. return i;
  138506. }
  138507. /*
  138508. ** Adjust the cost C by the costMult facter T. This only occurs if
  138509. ** compiled with -DSQLITE_ENABLE_COSTMULT
  138510. */
  138511. #ifdef SQLITE_ENABLE_COSTMULT
  138512. # define ApplyCostMultiplier(C,T) C += T
  138513. #else
  138514. # define ApplyCostMultiplier(C,T)
  138515. #endif
  138516. /*
  138517. ** We have so far matched pBuilder->pNew->u.btree.nEq terms of the
  138518. ** index pIndex. Try to match one more.
  138519. **
  138520. ** When this function is called, pBuilder->pNew->nOut contains the
  138521. ** number of rows expected to be visited by filtering using the nEq
  138522. ** terms only. If it is modified, this value is restored before this
  138523. ** function returns.
  138524. **
  138525. ** If pProbe->idxType==SQLITE_IDXTYPE_IPK, that means pIndex is
  138526. ** a fake index used for the INTEGER PRIMARY KEY.
  138527. */
  138528. static int whereLoopAddBtreeIndex(
  138529. WhereLoopBuilder *pBuilder, /* The WhereLoop factory */
  138530. struct SrcList_item *pSrc, /* FROM clause term being analyzed */
  138531. Index *pProbe, /* An index on pSrc */
  138532. LogEst nInMul /* log(Number of iterations due to IN) */
  138533. ){
  138534. WhereInfo *pWInfo = pBuilder->pWInfo; /* WHERE analyse context */
  138535. Parse *pParse = pWInfo->pParse; /* Parsing context */
  138536. sqlite3 *db = pParse->db; /* Database connection malloc context */
  138537. WhereLoop *pNew; /* Template WhereLoop under construction */
  138538. WhereTerm *pTerm; /* A WhereTerm under consideration */
  138539. int opMask; /* Valid operators for constraints */
  138540. WhereScan scan; /* Iterator for WHERE terms */
  138541. Bitmask saved_prereq; /* Original value of pNew->prereq */
  138542. u16 saved_nLTerm; /* Original value of pNew->nLTerm */
  138543. u16 saved_nEq; /* Original value of pNew->u.btree.nEq */
  138544. u16 saved_nBtm; /* Original value of pNew->u.btree.nBtm */
  138545. u16 saved_nTop; /* Original value of pNew->u.btree.nTop */
  138546. u16 saved_nSkip; /* Original value of pNew->nSkip */
  138547. u32 saved_wsFlags; /* Original value of pNew->wsFlags */
  138548. LogEst saved_nOut; /* Original value of pNew->nOut */
  138549. int rc = SQLITE_OK; /* Return code */
  138550. LogEst rSize; /* Number of rows in the table */
  138551. LogEst rLogSize; /* Logarithm of table size */
  138552. WhereTerm *pTop = 0, *pBtm = 0; /* Top and bottom range constraints */
  138553. pNew = pBuilder->pNew;
  138554. if( db->mallocFailed ) return SQLITE_NOMEM_BKPT;
  138555. WHERETRACE(0x800, ("BEGIN %s.addBtreeIdx(%s), nEq=%d, nSkip=%d\n",
  138556. pProbe->pTable->zName,pProbe->zName,
  138557. pNew->u.btree.nEq, pNew->nSkip));
  138558. assert( (pNew->wsFlags & WHERE_VIRTUALTABLE)==0 );
  138559. assert( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 );
  138560. if( pNew->wsFlags & WHERE_BTM_LIMIT ){
  138561. opMask = WO_LT|WO_LE;
  138562. }else{
  138563. assert( pNew->u.btree.nBtm==0 );
  138564. opMask = WO_EQ|WO_IN|WO_GT|WO_GE|WO_LT|WO_LE|WO_ISNULL|WO_IS;
  138565. }
  138566. if( pProbe->bUnordered ) opMask &= ~(WO_GT|WO_GE|WO_LT|WO_LE);
  138567. assert( pNew->u.btree.nEq<pProbe->nColumn );
  138568. saved_nEq = pNew->u.btree.nEq;
  138569. saved_nBtm = pNew->u.btree.nBtm;
  138570. saved_nTop = pNew->u.btree.nTop;
  138571. saved_nSkip = pNew->nSkip;
  138572. saved_nLTerm = pNew->nLTerm;
  138573. saved_wsFlags = pNew->wsFlags;
  138574. saved_prereq = pNew->prereq;
  138575. saved_nOut = pNew->nOut;
  138576. pTerm = whereScanInit(&scan, pBuilder->pWC, pSrc->iCursor, saved_nEq,
  138577. opMask, pProbe);
  138578. pNew->rSetup = 0;
  138579. rSize = pProbe->aiRowLogEst[0];
  138580. rLogSize = estLog(rSize);
  138581. for(; rc==SQLITE_OK && pTerm!=0; pTerm = whereScanNext(&scan)){
  138582. u16 eOp = pTerm->eOperator; /* Shorthand for pTerm->eOperator */
  138583. LogEst rCostIdx;
  138584. LogEst nOutUnadjusted; /* nOut before IN() and WHERE adjustments */
  138585. int nIn = 0;
  138586. #ifdef SQLITE_ENABLE_STAT4
  138587. int nRecValid = pBuilder->nRecValid;
  138588. #endif
  138589. if( (eOp==WO_ISNULL || (pTerm->wtFlags&TERM_VNULL)!=0)
  138590. && indexColumnNotNull(pProbe, saved_nEq)
  138591. ){
  138592. continue; /* ignore IS [NOT] NULL constraints on NOT NULL columns */
  138593. }
  138594. if( pTerm->prereqRight & pNew->maskSelf ) continue;
  138595. /* Do not allow the upper bound of a LIKE optimization range constraint
  138596. ** to mix with a lower range bound from some other source */
  138597. if( pTerm->wtFlags & TERM_LIKEOPT && pTerm->eOperator==WO_LT ) continue;
  138598. /* tag-20191211-001: Do not allow constraints from the WHERE clause to
  138599. ** be used by the right table of a LEFT JOIN. Only constraints in the
  138600. ** ON clause are allowed. See tag-20191211-002 for the vtab equivalent. */
  138601. if( (pSrc->fg.jointype & JT_LEFT)!=0
  138602. && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
  138603. ){
  138604. continue;
  138605. }
  138606. if( IsUniqueIndex(pProbe) && saved_nEq==pProbe->nKeyCol-1 ){
  138607. pBuilder->bldFlags1 |= SQLITE_BLDF1_UNIQUE;
  138608. }else{
  138609. pBuilder->bldFlags1 |= SQLITE_BLDF1_INDEXED;
  138610. }
  138611. pNew->wsFlags = saved_wsFlags;
  138612. pNew->u.btree.nEq = saved_nEq;
  138613. pNew->u.btree.nBtm = saved_nBtm;
  138614. pNew->u.btree.nTop = saved_nTop;
  138615. pNew->nLTerm = saved_nLTerm;
  138616. if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
  138617. pNew->aLTerm[pNew->nLTerm++] = pTerm;
  138618. pNew->prereq = (saved_prereq | pTerm->prereqRight) & ~pNew->maskSelf;
  138619. assert( nInMul==0
  138620. || (pNew->wsFlags & WHERE_COLUMN_NULL)!=0
  138621. || (pNew->wsFlags & WHERE_COLUMN_IN)!=0
  138622. || (pNew->wsFlags & WHERE_SKIPSCAN)!=0
  138623. );
  138624. if( eOp & WO_IN ){
  138625. Expr *pExpr = pTerm->pExpr;
  138626. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  138627. /* "x IN (SELECT ...)": TUNING: the SELECT returns 25 rows */
  138628. int i;
  138629. nIn = 46; assert( 46==sqlite3LogEst(25) );
  138630. /* The expression may actually be of the form (x, y) IN (SELECT...).
  138631. ** In this case there is a separate term for each of (x) and (y).
  138632. ** However, the nIn multiplier should only be applied once, not once
  138633. ** for each such term. The following loop checks that pTerm is the
  138634. ** first such term in use, and sets nIn back to 0 if it is not. */
  138635. for(i=0; i<pNew->nLTerm-1; i++){
  138636. if( pNew->aLTerm[i] && pNew->aLTerm[i]->pExpr==pExpr ) nIn = 0;
  138637. }
  138638. }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
  138639. /* "x IN (value, value, ...)" */
  138640. nIn = sqlite3LogEst(pExpr->x.pList->nExpr);
  138641. }
  138642. if( pProbe->hasStat1 ){
  138643. LogEst M, logK, safetyMargin;
  138644. /* Let:
  138645. ** N = the total number of rows in the table
  138646. ** K = the number of entries on the RHS of the IN operator
  138647. ** M = the number of rows in the table that match terms to the
  138648. ** to the left in the same index. If the IN operator is on
  138649. ** the left-most index column, M==N.
  138650. **
  138651. ** Given the definitions above, it is better to omit the IN operator
  138652. ** from the index lookup and instead do a scan of the M elements,
  138653. ** testing each scanned row against the IN operator separately, if:
  138654. **
  138655. ** M*log(K) < K*log(N)
  138656. **
  138657. ** Our estimates for M, K, and N might be inaccurate, so we build in
  138658. ** a safety margin of 2 (LogEst: 10) that favors using the IN operator
  138659. ** with the index, as using an index has better worst-case behavior.
  138660. ** If we do not have real sqlite_stat1 data, always prefer to use
  138661. ** the index.
  138662. */
  138663. M = pProbe->aiRowLogEst[saved_nEq];
  138664. logK = estLog(nIn);
  138665. safetyMargin = 10; /* TUNING: extra weight for indexed IN */
  138666. if( M + logK + safetyMargin < nIn + rLogSize ){
  138667. WHERETRACE(0x40,
  138668. ("Scan preferred over IN operator on column %d of \"%s\" (%d<%d)\n",
  138669. saved_nEq, pProbe->zName, M+logK+10, nIn+rLogSize));
  138670. continue;
  138671. }else{
  138672. WHERETRACE(0x40,
  138673. ("IN operator preferred on column %d of \"%s\" (%d>=%d)\n",
  138674. saved_nEq, pProbe->zName, M+logK+10, nIn+rLogSize));
  138675. }
  138676. }
  138677. pNew->wsFlags |= WHERE_COLUMN_IN;
  138678. }else if( eOp & (WO_EQ|WO_IS) ){
  138679. int iCol = pProbe->aiColumn[saved_nEq];
  138680. pNew->wsFlags |= WHERE_COLUMN_EQ;
  138681. assert( saved_nEq==pNew->u.btree.nEq );
  138682. if( iCol==XN_ROWID
  138683. || (iCol>=0 && nInMul==0 && saved_nEq==pProbe->nKeyCol-1)
  138684. ){
  138685. if( iCol==XN_ROWID || pProbe->uniqNotNull
  138686. || (pProbe->nKeyCol==1 && pProbe->onError && eOp==WO_EQ)
  138687. ){
  138688. pNew->wsFlags |= WHERE_ONEROW;
  138689. }else{
  138690. pNew->wsFlags |= WHERE_UNQ_WANTED;
  138691. }
  138692. }
  138693. }else if( eOp & WO_ISNULL ){
  138694. pNew->wsFlags |= WHERE_COLUMN_NULL;
  138695. }else if( eOp & (WO_GT|WO_GE) ){
  138696. testcase( eOp & WO_GT );
  138697. testcase( eOp & WO_GE );
  138698. pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_BTM_LIMIT;
  138699. pNew->u.btree.nBtm = whereRangeVectorLen(
  138700. pParse, pSrc->iCursor, pProbe, saved_nEq, pTerm
  138701. );
  138702. pBtm = pTerm;
  138703. pTop = 0;
  138704. if( pTerm->wtFlags & TERM_LIKEOPT ){
  138705. /* Range contraints that come from the LIKE optimization are
  138706. ** always used in pairs. */
  138707. pTop = &pTerm[1];
  138708. assert( (pTop-(pTerm->pWC->a))<pTerm->pWC->nTerm );
  138709. assert( pTop->wtFlags & TERM_LIKEOPT );
  138710. assert( pTop->eOperator==WO_LT );
  138711. if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
  138712. pNew->aLTerm[pNew->nLTerm++] = pTop;
  138713. pNew->wsFlags |= WHERE_TOP_LIMIT;
  138714. pNew->u.btree.nTop = 1;
  138715. }
  138716. }else{
  138717. assert( eOp & (WO_LT|WO_LE) );
  138718. testcase( eOp & WO_LT );
  138719. testcase( eOp & WO_LE );
  138720. pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_TOP_LIMIT;
  138721. pNew->u.btree.nTop = whereRangeVectorLen(
  138722. pParse, pSrc->iCursor, pProbe, saved_nEq, pTerm
  138723. );
  138724. pTop = pTerm;
  138725. pBtm = (pNew->wsFlags & WHERE_BTM_LIMIT)!=0 ?
  138726. pNew->aLTerm[pNew->nLTerm-2] : 0;
  138727. }
  138728. /* At this point pNew->nOut is set to the number of rows expected to
  138729. ** be visited by the index scan before considering term pTerm, or the
  138730. ** values of nIn and nInMul. In other words, assuming that all
  138731. ** "x IN(...)" terms are replaced with "x = ?". This block updates
  138732. ** the value of pNew->nOut to account for pTerm (but not nIn/nInMul). */
  138733. assert( pNew->nOut==saved_nOut );
  138734. if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
  138735. /* Adjust nOut using stat4 data. Or, if there is no stat4
  138736. ** data, using some other estimate. */
  138737. whereRangeScanEst(pParse, pBuilder, pBtm, pTop, pNew);
  138738. }else{
  138739. int nEq = ++pNew->u.btree.nEq;
  138740. assert( eOp & (WO_ISNULL|WO_EQ|WO_IN|WO_IS) );
  138741. assert( pNew->nOut==saved_nOut );
  138742. if( pTerm->truthProb<=0 && pProbe->aiColumn[saved_nEq]>=0 ){
  138743. assert( (eOp & WO_IN) || nIn==0 );
  138744. testcase( eOp & WO_IN );
  138745. pNew->nOut += pTerm->truthProb;
  138746. pNew->nOut -= nIn;
  138747. }else{
  138748. #ifdef SQLITE_ENABLE_STAT4
  138749. tRowcnt nOut = 0;
  138750. if( nInMul==0
  138751. && pProbe->nSample
  138752. && pNew->u.btree.nEq<=pProbe->nSampleCol
  138753. && ((eOp & WO_IN)==0 || !ExprHasProperty(pTerm->pExpr, EP_xIsSelect))
  138754. && OptimizationEnabled(db, SQLITE_Stat4)
  138755. ){
  138756. Expr *pExpr = pTerm->pExpr;
  138757. if( (eOp & (WO_EQ|WO_ISNULL|WO_IS))!=0 ){
  138758. testcase( eOp & WO_EQ );
  138759. testcase( eOp & WO_IS );
  138760. testcase( eOp & WO_ISNULL );
  138761. rc = whereEqualScanEst(pParse, pBuilder, pExpr->pRight, &nOut);
  138762. }else{
  138763. rc = whereInScanEst(pParse, pBuilder, pExpr->x.pList, &nOut);
  138764. }
  138765. if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
  138766. if( rc!=SQLITE_OK ) break; /* Jump out of the pTerm loop */
  138767. if( nOut ){
  138768. pNew->nOut = sqlite3LogEst(nOut);
  138769. if( nEq==1
  138770. /* TUNING: Mark terms as "low selectivity" if they seem likely
  138771. ** to be true for half or more of the rows in the table.
  138772. ** See tag-202002240-1 */
  138773. && pNew->nOut+10 > pProbe->aiRowLogEst[0]
  138774. ){
  138775. #if WHERETRACE_ENABLED /* 0x01 */
  138776. if( sqlite3WhereTrace & 0x01 ){
  138777. sqlite3DebugPrintf(
  138778. "STAT4 determines term has low selectivity:\n");
  138779. sqlite3WhereTermPrint(pTerm, 999);
  138780. }
  138781. #endif
  138782. pTerm->wtFlags |= TERM_HIGHTRUTH;
  138783. if( pTerm->wtFlags & TERM_HEURTRUTH ){
  138784. /* If the term has previously been used with an assumption of
  138785. ** higher selectivity, then set the flag to rerun the
  138786. ** loop computations. */
  138787. pBuilder->bldFlags2 |= SQLITE_BLDF2_2NDPASS;
  138788. }
  138789. }
  138790. if( pNew->nOut>saved_nOut ) pNew->nOut = saved_nOut;
  138791. pNew->nOut -= nIn;
  138792. }
  138793. }
  138794. if( nOut==0 )
  138795. #endif
  138796. {
  138797. pNew->nOut += (pProbe->aiRowLogEst[nEq] - pProbe->aiRowLogEst[nEq-1]);
  138798. if( eOp & WO_ISNULL ){
  138799. /* TUNING: If there is no likelihood() value, assume that a
  138800. ** "col IS NULL" expression matches twice as many rows
  138801. ** as (col=?). */
  138802. pNew->nOut += 10;
  138803. }
  138804. }
  138805. }
  138806. }
  138807. /* Set rCostIdx to the cost of visiting selected rows in index. Add
  138808. ** it to pNew->rRun, which is currently set to the cost of the index
  138809. ** seek only. Then, if this is a non-covering index, add the cost of
  138810. ** visiting the rows in the main table. */
  138811. assert( pSrc->pTab->szTabRow>0 );
  138812. rCostIdx = pNew->nOut + 1 + (15*pProbe->szIdxRow)/pSrc->pTab->szTabRow;
  138813. pNew->rRun = sqlite3LogEstAdd(rLogSize, rCostIdx);
  138814. if( (pNew->wsFlags & (WHERE_IDX_ONLY|WHERE_IPK))==0 ){
  138815. pNew->rRun = sqlite3LogEstAdd(pNew->rRun, pNew->nOut + 16);
  138816. }
  138817. ApplyCostMultiplier(pNew->rRun, pProbe->pTable->costMult);
  138818. nOutUnadjusted = pNew->nOut;
  138819. pNew->rRun += nInMul + nIn;
  138820. pNew->nOut += nInMul + nIn;
  138821. whereLoopOutputAdjust(pBuilder->pWC, pNew, rSize);
  138822. rc = whereLoopInsert(pBuilder, pNew);
  138823. if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
  138824. pNew->nOut = saved_nOut;
  138825. }else{
  138826. pNew->nOut = nOutUnadjusted;
  138827. }
  138828. if( (pNew->wsFlags & WHERE_TOP_LIMIT)==0
  138829. && pNew->u.btree.nEq<pProbe->nColumn
  138830. ){
  138831. whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nInMul+nIn);
  138832. }
  138833. pNew->nOut = saved_nOut;
  138834. #ifdef SQLITE_ENABLE_STAT4
  138835. pBuilder->nRecValid = nRecValid;
  138836. #endif
  138837. }
  138838. pNew->prereq = saved_prereq;
  138839. pNew->u.btree.nEq = saved_nEq;
  138840. pNew->u.btree.nBtm = saved_nBtm;
  138841. pNew->u.btree.nTop = saved_nTop;
  138842. pNew->nSkip = saved_nSkip;
  138843. pNew->wsFlags = saved_wsFlags;
  138844. pNew->nOut = saved_nOut;
  138845. pNew->nLTerm = saved_nLTerm;
  138846. /* Consider using a skip-scan if there are no WHERE clause constraints
  138847. ** available for the left-most terms of the index, and if the average
  138848. ** number of repeats in the left-most terms is at least 18.
  138849. **
  138850. ** The magic number 18 is selected on the basis that scanning 17 rows
  138851. ** is almost always quicker than an index seek (even though if the index
  138852. ** contains fewer than 2^17 rows we assume otherwise in other parts of
  138853. ** the code). And, even if it is not, it should not be too much slower.
  138854. ** On the other hand, the extra seeks could end up being significantly
  138855. ** more expensive. */
  138856. assert( 42==sqlite3LogEst(18) );
  138857. if( saved_nEq==saved_nSkip
  138858. && saved_nEq+1<pProbe->nKeyCol
  138859. && saved_nEq==pNew->nLTerm
  138860. && pProbe->noSkipScan==0
  138861. && pProbe->hasStat1!=0
  138862. && OptimizationEnabled(db, SQLITE_SkipScan)
  138863. && pProbe->aiRowLogEst[saved_nEq+1]>=42 /* TUNING: Minimum for skip-scan */
  138864. && (rc = whereLoopResize(db, pNew, pNew->nLTerm+1))==SQLITE_OK
  138865. ){
  138866. LogEst nIter;
  138867. pNew->u.btree.nEq++;
  138868. pNew->nSkip++;
  138869. pNew->aLTerm[pNew->nLTerm++] = 0;
  138870. pNew->wsFlags |= WHERE_SKIPSCAN;
  138871. nIter = pProbe->aiRowLogEst[saved_nEq] - pProbe->aiRowLogEst[saved_nEq+1];
  138872. pNew->nOut -= nIter;
  138873. /* TUNING: Because uncertainties in the estimates for skip-scan queries,
  138874. ** add a 1.375 fudge factor to make skip-scan slightly less likely. */
  138875. nIter += 5;
  138876. whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nIter + nInMul);
  138877. pNew->nOut = saved_nOut;
  138878. pNew->u.btree.nEq = saved_nEq;
  138879. pNew->nSkip = saved_nSkip;
  138880. pNew->wsFlags = saved_wsFlags;
  138881. }
  138882. WHERETRACE(0x800, ("END %s.addBtreeIdx(%s), nEq=%d, rc=%d\n",
  138883. pProbe->pTable->zName, pProbe->zName, saved_nEq, rc));
  138884. return rc;
  138885. }
  138886. /*
  138887. ** Return True if it is possible that pIndex might be useful in
  138888. ** implementing the ORDER BY clause in pBuilder.
  138889. **
  138890. ** Return False if pBuilder does not contain an ORDER BY clause or
  138891. ** if there is no way for pIndex to be useful in implementing that
  138892. ** ORDER BY clause.
  138893. */
  138894. static int indexMightHelpWithOrderBy(
  138895. WhereLoopBuilder *pBuilder,
  138896. Index *pIndex,
  138897. int iCursor
  138898. ){
  138899. ExprList *pOB;
  138900. ExprList *aColExpr;
  138901. int ii, jj;
  138902. if( pIndex->bUnordered ) return 0;
  138903. if( (pOB = pBuilder->pWInfo->pOrderBy)==0 ) return 0;
  138904. for(ii=0; ii<pOB->nExpr; ii++){
  138905. Expr *pExpr = sqlite3ExprSkipCollateAndLikely(pOB->a[ii].pExpr);
  138906. if( pExpr->op==TK_COLUMN && pExpr->iTable==iCursor ){
  138907. if( pExpr->iColumn<0 ) return 1;
  138908. for(jj=0; jj<pIndex->nKeyCol; jj++){
  138909. if( pExpr->iColumn==pIndex->aiColumn[jj] ) return 1;
  138910. }
  138911. }else if( (aColExpr = pIndex->aColExpr)!=0 ){
  138912. for(jj=0; jj<pIndex->nKeyCol; jj++){
  138913. if( pIndex->aiColumn[jj]!=XN_EXPR ) continue;
  138914. if( sqlite3ExprCompareSkip(pExpr,aColExpr->a[jj].pExpr,iCursor)==0 ){
  138915. return 1;
  138916. }
  138917. }
  138918. }
  138919. }
  138920. return 0;
  138921. }
  138922. /* Check to see if a partial index with pPartIndexWhere can be used
  138923. ** in the current query. Return true if it can be and false if not.
  138924. */
  138925. static int whereUsablePartialIndex(
  138926. int iTab, /* The table for which we want an index */
  138927. int isLeft, /* True if iTab is the right table of a LEFT JOIN */
  138928. WhereClause *pWC, /* The WHERE clause of the query */
  138929. Expr *pWhere /* The WHERE clause from the partial index */
  138930. ){
  138931. int i;
  138932. WhereTerm *pTerm;
  138933. Parse *pParse = pWC->pWInfo->pParse;
  138934. while( pWhere->op==TK_AND ){
  138935. if( !whereUsablePartialIndex(iTab,isLeft,pWC,pWhere->pLeft) ) return 0;
  138936. pWhere = pWhere->pRight;
  138937. }
  138938. if( pParse->db->flags & SQLITE_EnableQPSG ) pParse = 0;
  138939. for(i=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
  138940. Expr *pExpr;
  138941. pExpr = pTerm->pExpr;
  138942. if( (!ExprHasProperty(pExpr, EP_FromJoin) || pExpr->iRightJoinTable==iTab)
  138943. && (isLeft==0 || ExprHasProperty(pExpr, EP_FromJoin))
  138944. && sqlite3ExprImpliesExpr(pParse, pExpr, pWhere, iTab)
  138945. ){
  138946. return 1;
  138947. }
  138948. }
  138949. return 0;
  138950. }
  138951. /*
  138952. ** Add all WhereLoop objects for a single table of the join where the table
  138953. ** is identified by pBuilder->pNew->iTab. That table is guaranteed to be
  138954. ** a b-tree table, not a virtual table.
  138955. **
  138956. ** The costs (WhereLoop.rRun) of the b-tree loops added by this function
  138957. ** are calculated as follows:
  138958. **
  138959. ** For a full scan, assuming the table (or index) contains nRow rows:
  138960. **
  138961. ** cost = nRow * 3.0 // full-table scan
  138962. ** cost = nRow * K // scan of covering index
  138963. ** cost = nRow * (K+3.0) // scan of non-covering index
  138964. **
  138965. ** where K is a value between 1.1 and 3.0 set based on the relative
  138966. ** estimated average size of the index and table records.
  138967. **
  138968. ** For an index scan, where nVisit is the number of index rows visited
  138969. ** by the scan, and nSeek is the number of seek operations required on
  138970. ** the index b-tree:
  138971. **
  138972. ** cost = nSeek * (log(nRow) + K * nVisit) // covering index
  138973. ** cost = nSeek * (log(nRow) + (K+3.0) * nVisit) // non-covering index
  138974. **
  138975. ** Normally, nSeek is 1. nSeek values greater than 1 come about if the
  138976. ** WHERE clause includes "x IN (....)" terms used in place of "x=?". Or when
  138977. ** implicit "x IN (SELECT x FROM tbl)" terms are added for skip-scans.
  138978. **
  138979. ** The estimated values (nRow, nVisit, nSeek) often contain a large amount
  138980. ** of uncertainty. For this reason, scoring is designed to pick plans that
  138981. ** "do the least harm" if the estimates are inaccurate. For example, a
  138982. ** log(nRow) factor is omitted from a non-covering index scan in order to
  138983. ** bias the scoring in favor of using an index, since the worst-case
  138984. ** performance of using an index is far better than the worst-case performance
  138985. ** of a full table scan.
  138986. */
  138987. static int whereLoopAddBtree(
  138988. WhereLoopBuilder *pBuilder, /* WHERE clause information */
  138989. Bitmask mPrereq /* Extra prerequesites for using this table */
  138990. ){
  138991. WhereInfo *pWInfo; /* WHERE analysis context */
  138992. Index *pProbe; /* An index we are evaluating */
  138993. Index sPk; /* A fake index object for the primary key */
  138994. LogEst aiRowEstPk[2]; /* The aiRowLogEst[] value for the sPk index */
  138995. i16 aiColumnPk = -1; /* The aColumn[] value for the sPk index */
  138996. SrcList *pTabList; /* The FROM clause */
  138997. struct SrcList_item *pSrc; /* The FROM clause btree term to add */
  138998. WhereLoop *pNew; /* Template WhereLoop object */
  138999. int rc = SQLITE_OK; /* Return code */
  139000. int iSortIdx = 1; /* Index number */
  139001. int b; /* A boolean value */
  139002. LogEst rSize; /* number of rows in the table */
  139003. LogEst rLogSize; /* Logarithm of the number of rows in the table */
  139004. WhereClause *pWC; /* The parsed WHERE clause */
  139005. Table *pTab; /* Table being queried */
  139006. pNew = pBuilder->pNew;
  139007. pWInfo = pBuilder->pWInfo;
  139008. pTabList = pWInfo->pTabList;
  139009. pSrc = pTabList->a + pNew->iTab;
  139010. pTab = pSrc->pTab;
  139011. pWC = pBuilder->pWC;
  139012. assert( !IsVirtual(pSrc->pTab) );
  139013. if( pSrc->pIBIndex ){
  139014. /* An INDEXED BY clause specifies a particular index to use */
  139015. pProbe = pSrc->pIBIndex;
  139016. }else if( !HasRowid(pTab) ){
  139017. pProbe = pTab->pIndex;
  139018. }else{
  139019. /* There is no INDEXED BY clause. Create a fake Index object in local
  139020. ** variable sPk to represent the rowid primary key index. Make this
  139021. ** fake index the first in a chain of Index objects with all of the real
  139022. ** indices to follow */
  139023. Index *pFirst; /* First of real indices on the table */
  139024. memset(&sPk, 0, sizeof(Index));
  139025. sPk.nKeyCol = 1;
  139026. sPk.nColumn = 1;
  139027. sPk.aiColumn = &aiColumnPk;
  139028. sPk.aiRowLogEst = aiRowEstPk;
  139029. sPk.onError = OE_Replace;
  139030. sPk.pTable = pTab;
  139031. sPk.szIdxRow = pTab->szTabRow;
  139032. sPk.idxType = SQLITE_IDXTYPE_IPK;
  139033. aiRowEstPk[0] = pTab->nRowLogEst;
  139034. aiRowEstPk[1] = 0;
  139035. pFirst = pSrc->pTab->pIndex;
  139036. if( pSrc->fg.notIndexed==0 ){
  139037. /* The real indices of the table are only considered if the
  139038. ** NOT INDEXED qualifier is omitted from the FROM clause */
  139039. sPk.pNext = pFirst;
  139040. }
  139041. pProbe = &sPk;
  139042. }
  139043. rSize = pTab->nRowLogEst;
  139044. rLogSize = estLog(rSize);
  139045. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  139046. /* Automatic indexes */
  139047. if( !pBuilder->pOrSet /* Not part of an OR optimization */
  139048. && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0
  139049. && (pWInfo->pParse->db->flags & SQLITE_AutoIndex)!=0
  139050. && pSrc->pIBIndex==0 /* Has no INDEXED BY clause */
  139051. && !pSrc->fg.notIndexed /* Has no NOT INDEXED clause */
  139052. && HasRowid(pTab) /* Not WITHOUT ROWID table. (FIXME: Why not?) */
  139053. && !pSrc->fg.isCorrelated /* Not a correlated subquery */
  139054. && !pSrc->fg.isRecursive /* Not a recursive common table expression. */
  139055. ){
  139056. /* Generate auto-index WhereLoops */
  139057. WhereTerm *pTerm;
  139058. WhereTerm *pWCEnd = pWC->a + pWC->nTerm;
  139059. for(pTerm=pWC->a; rc==SQLITE_OK && pTerm<pWCEnd; pTerm++){
  139060. if( pTerm->prereqRight & pNew->maskSelf ) continue;
  139061. if( termCanDriveIndex(pTerm, pSrc, 0) ){
  139062. pNew->u.btree.nEq = 1;
  139063. pNew->nSkip = 0;
  139064. pNew->u.btree.pIndex = 0;
  139065. pNew->nLTerm = 1;
  139066. pNew->aLTerm[0] = pTerm;
  139067. /* TUNING: One-time cost for computing the automatic index is
  139068. ** estimated to be X*N*log2(N) where N is the number of rows in
  139069. ** the table being indexed and where X is 7 (LogEst=28) for normal
  139070. ** tables or 0.5 (LogEst=-10) for views and subqueries. The value
  139071. ** of X is smaller for views and subqueries so that the query planner
  139072. ** will be more aggressive about generating automatic indexes for
  139073. ** those objects, since there is no opportunity to add schema
  139074. ** indexes on subqueries and views. */
  139075. pNew->rSetup = rLogSize + rSize;
  139076. if( pTab->pSelect==0 && (pTab->tabFlags & TF_Ephemeral)==0 ){
  139077. pNew->rSetup += 28;
  139078. }else{
  139079. pNew->rSetup -= 10;
  139080. }
  139081. ApplyCostMultiplier(pNew->rSetup, pTab->costMult);
  139082. if( pNew->rSetup<0 ) pNew->rSetup = 0;
  139083. /* TUNING: Each index lookup yields 20 rows in the table. This
  139084. ** is more than the usual guess of 10 rows, since we have no way
  139085. ** of knowing how selective the index will ultimately be. It would
  139086. ** not be unreasonable to make this value much larger. */
  139087. pNew->nOut = 43; assert( 43==sqlite3LogEst(20) );
  139088. pNew->rRun = sqlite3LogEstAdd(rLogSize,pNew->nOut);
  139089. pNew->wsFlags = WHERE_AUTO_INDEX;
  139090. pNew->prereq = mPrereq | pTerm->prereqRight;
  139091. rc = whereLoopInsert(pBuilder, pNew);
  139092. }
  139093. }
  139094. }
  139095. #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
  139096. /* Loop over all indices. If there was an INDEXED BY clause, then only
  139097. ** consider index pProbe. */
  139098. for(; rc==SQLITE_OK && pProbe;
  139099. pProbe=(pSrc->pIBIndex ? 0 : pProbe->pNext), iSortIdx++
  139100. ){
  139101. int isLeft = (pSrc->fg.jointype & JT_OUTER)!=0;
  139102. if( pProbe->pPartIdxWhere!=0
  139103. && !whereUsablePartialIndex(pSrc->iCursor, isLeft, pWC,
  139104. pProbe->pPartIdxWhere)
  139105. ){
  139106. testcase( pNew->iTab!=pSrc->iCursor ); /* See ticket [98d973b8f5] */
  139107. continue; /* Partial index inappropriate for this query */
  139108. }
  139109. if( pProbe->bNoQuery ) continue;
  139110. rSize = pProbe->aiRowLogEst[0];
  139111. pNew->u.btree.nEq = 0;
  139112. pNew->u.btree.nBtm = 0;
  139113. pNew->u.btree.nTop = 0;
  139114. pNew->nSkip = 0;
  139115. pNew->nLTerm = 0;
  139116. pNew->iSortIdx = 0;
  139117. pNew->rSetup = 0;
  139118. pNew->prereq = mPrereq;
  139119. pNew->nOut = rSize;
  139120. pNew->u.btree.pIndex = pProbe;
  139121. b = indexMightHelpWithOrderBy(pBuilder, pProbe, pSrc->iCursor);
  139122. /* The ONEPASS_DESIRED flags never occurs together with ORDER BY */
  139123. assert( (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || b==0 );
  139124. if( pProbe->idxType==SQLITE_IDXTYPE_IPK ){
  139125. /* Integer primary key index */
  139126. pNew->wsFlags = WHERE_IPK;
  139127. /* Full table scan */
  139128. pNew->iSortIdx = b ? iSortIdx : 0;
  139129. /* TUNING: Cost of full table scan is (N*3.0). */
  139130. pNew->rRun = rSize + 16;
  139131. ApplyCostMultiplier(pNew->rRun, pTab->costMult);
  139132. whereLoopOutputAdjust(pWC, pNew, rSize);
  139133. rc = whereLoopInsert(pBuilder, pNew);
  139134. pNew->nOut = rSize;
  139135. if( rc ) break;
  139136. }else{
  139137. Bitmask m;
  139138. if( pProbe->isCovering ){
  139139. pNew->wsFlags = WHERE_IDX_ONLY | WHERE_INDEXED;
  139140. m = 0;
  139141. }else{
  139142. m = pSrc->colUsed & pProbe->colNotIdxed;
  139143. pNew->wsFlags = (m==0) ? (WHERE_IDX_ONLY|WHERE_INDEXED) : WHERE_INDEXED;
  139144. }
  139145. /* Full scan via index */
  139146. if( b
  139147. || !HasRowid(pTab)
  139148. || pProbe->pPartIdxWhere!=0
  139149. || ( m==0
  139150. && pProbe->bUnordered==0
  139151. && (pProbe->szIdxRow<pTab->szTabRow)
  139152. && (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0
  139153. && sqlite3GlobalConfig.bUseCis
  139154. && OptimizationEnabled(pWInfo->pParse->db, SQLITE_CoverIdxScan)
  139155. )
  139156. ){
  139157. pNew->iSortIdx = b ? iSortIdx : 0;
  139158. /* The cost of visiting the index rows is N*K, where K is
  139159. ** between 1.1 and 3.0, depending on the relative sizes of the
  139160. ** index and table rows. */
  139161. pNew->rRun = rSize + 1 + (15*pProbe->szIdxRow)/pTab->szTabRow;
  139162. if( m!=0 ){
  139163. /* If this is a non-covering index scan, add in the cost of
  139164. ** doing table lookups. The cost will be 3x the number of
  139165. ** lookups. Take into account WHERE clause terms that can be
  139166. ** satisfied using just the index, and that do not require a
  139167. ** table lookup. */
  139168. LogEst nLookup = rSize + 16; /* Base cost: N*3 */
  139169. int ii;
  139170. int iCur = pSrc->iCursor;
  139171. WhereClause *pWC2 = &pWInfo->sWC;
  139172. for(ii=0; ii<pWC2->nTerm; ii++){
  139173. WhereTerm *pTerm = &pWC2->a[ii];
  139174. if( !sqlite3ExprCoveredByIndex(pTerm->pExpr, iCur, pProbe) ){
  139175. break;
  139176. }
  139177. /* pTerm can be evaluated using just the index. So reduce
  139178. ** the expected number of table lookups accordingly */
  139179. if( pTerm->truthProb<=0 ){
  139180. nLookup += pTerm->truthProb;
  139181. }else{
  139182. nLookup--;
  139183. if( pTerm->eOperator & (WO_EQ|WO_IS) ) nLookup -= 19;
  139184. }
  139185. }
  139186. pNew->rRun = sqlite3LogEstAdd(pNew->rRun, nLookup);
  139187. }
  139188. ApplyCostMultiplier(pNew->rRun, pTab->costMult);
  139189. whereLoopOutputAdjust(pWC, pNew, rSize);
  139190. rc = whereLoopInsert(pBuilder, pNew);
  139191. pNew->nOut = rSize;
  139192. if( rc ) break;
  139193. }
  139194. }
  139195. pBuilder->bldFlags1 = 0;
  139196. rc = whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, 0);
  139197. if( pBuilder->bldFlags1==SQLITE_BLDF1_INDEXED ){
  139198. /* If a non-unique index is used, or if a prefix of the key for
  139199. ** unique index is used (making the index functionally non-unique)
  139200. ** then the sqlite_stat1 data becomes important for scoring the
  139201. ** plan */
  139202. pTab->tabFlags |= TF_StatsUsed;
  139203. }
  139204. #ifdef SQLITE_ENABLE_STAT4
  139205. sqlite3Stat4ProbeFree(pBuilder->pRec);
  139206. pBuilder->nRecValid = 0;
  139207. pBuilder->pRec = 0;
  139208. #endif
  139209. }
  139210. return rc;
  139211. }
  139212. #ifndef SQLITE_OMIT_VIRTUALTABLE
  139213. /*
  139214. ** Argument pIdxInfo is already populated with all constraints that may
  139215. ** be used by the virtual table identified by pBuilder->pNew->iTab. This
  139216. ** function marks a subset of those constraints usable, invokes the
  139217. ** xBestIndex method and adds the returned plan to pBuilder.
  139218. **
  139219. ** A constraint is marked usable if:
  139220. **
  139221. ** * Argument mUsable indicates that its prerequisites are available, and
  139222. **
  139223. ** * It is not one of the operators specified in the mExclude mask passed
  139224. ** as the fourth argument (which in practice is either WO_IN or 0).
  139225. **
  139226. ** Argument mPrereq is a mask of tables that must be scanned before the
  139227. ** virtual table in question. These are added to the plans prerequisites
  139228. ** before it is added to pBuilder.
  139229. **
  139230. ** Output parameter *pbIn is set to true if the plan added to pBuilder
  139231. ** uses one or more WO_IN terms, or false otherwise.
  139232. */
  139233. static int whereLoopAddVirtualOne(
  139234. WhereLoopBuilder *pBuilder,
  139235. Bitmask mPrereq, /* Mask of tables that must be used. */
  139236. Bitmask mUsable, /* Mask of usable tables */
  139237. u16 mExclude, /* Exclude terms using these operators */
  139238. sqlite3_index_info *pIdxInfo, /* Populated object for xBestIndex */
  139239. u16 mNoOmit, /* Do not omit these constraints */
  139240. int *pbIn /* OUT: True if plan uses an IN(...) op */
  139241. ){
  139242. WhereClause *pWC = pBuilder->pWC;
  139243. struct sqlite3_index_constraint *pIdxCons;
  139244. struct sqlite3_index_constraint_usage *pUsage = pIdxInfo->aConstraintUsage;
  139245. int i;
  139246. int mxTerm;
  139247. int rc = SQLITE_OK;
  139248. WhereLoop *pNew = pBuilder->pNew;
  139249. Parse *pParse = pBuilder->pWInfo->pParse;
  139250. struct SrcList_item *pSrc = &pBuilder->pWInfo->pTabList->a[pNew->iTab];
  139251. int nConstraint = pIdxInfo->nConstraint;
  139252. assert( (mUsable & mPrereq)==mPrereq );
  139253. *pbIn = 0;
  139254. pNew->prereq = mPrereq;
  139255. /* Set the usable flag on the subset of constraints identified by
  139256. ** arguments mUsable and mExclude. */
  139257. pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
  139258. for(i=0; i<nConstraint; i++, pIdxCons++){
  139259. WhereTerm *pTerm = &pWC->a[pIdxCons->iTermOffset];
  139260. pIdxCons->usable = 0;
  139261. if( (pTerm->prereqRight & mUsable)==pTerm->prereqRight
  139262. && (pTerm->eOperator & mExclude)==0
  139263. ){
  139264. pIdxCons->usable = 1;
  139265. }
  139266. }
  139267. /* Initialize the output fields of the sqlite3_index_info structure */
  139268. memset(pUsage, 0, sizeof(pUsage[0])*nConstraint);
  139269. assert( pIdxInfo->needToFreeIdxStr==0 );
  139270. pIdxInfo->idxStr = 0;
  139271. pIdxInfo->idxNum = 0;
  139272. pIdxInfo->orderByConsumed = 0;
  139273. pIdxInfo->estimatedCost = SQLITE_BIG_DBL / (double)2;
  139274. pIdxInfo->estimatedRows = 25;
  139275. pIdxInfo->idxFlags = 0;
  139276. pIdxInfo->colUsed = (sqlite3_int64)pSrc->colUsed;
  139277. /* Invoke the virtual table xBestIndex() method */
  139278. rc = vtabBestIndex(pParse, pSrc->pTab, pIdxInfo);
  139279. if( rc ){
  139280. if( rc==SQLITE_CONSTRAINT ){
  139281. /* If the xBestIndex method returns SQLITE_CONSTRAINT, that means
  139282. ** that the particular combination of parameters provided is unusable.
  139283. ** Make no entries in the loop table.
  139284. */
  139285. WHERETRACE(0xffff, (" ^^^^--- non-viable plan rejected!\n"));
  139286. return SQLITE_OK;
  139287. }
  139288. return rc;
  139289. }
  139290. mxTerm = -1;
  139291. assert( pNew->nLSlot>=nConstraint );
  139292. for(i=0; i<nConstraint; i++) pNew->aLTerm[i] = 0;
  139293. pNew->u.vtab.omitMask = 0;
  139294. pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
  139295. for(i=0; i<nConstraint; i++, pIdxCons++){
  139296. int iTerm;
  139297. if( (iTerm = pUsage[i].argvIndex - 1)>=0 ){
  139298. WhereTerm *pTerm;
  139299. int j = pIdxCons->iTermOffset;
  139300. if( iTerm>=nConstraint
  139301. || j<0
  139302. || j>=pWC->nTerm
  139303. || pNew->aLTerm[iTerm]!=0
  139304. || pIdxCons->usable==0
  139305. ){
  139306. sqlite3ErrorMsg(pParse,"%s.xBestIndex malfunction",pSrc->pTab->zName);
  139307. testcase( pIdxInfo->needToFreeIdxStr );
  139308. return SQLITE_ERROR;
  139309. }
  139310. testcase( iTerm==nConstraint-1 );
  139311. testcase( j==0 );
  139312. testcase( j==pWC->nTerm-1 );
  139313. pTerm = &pWC->a[j];
  139314. pNew->prereq |= pTerm->prereqRight;
  139315. assert( iTerm<pNew->nLSlot );
  139316. pNew->aLTerm[iTerm] = pTerm;
  139317. if( iTerm>mxTerm ) mxTerm = iTerm;
  139318. testcase( iTerm==15 );
  139319. testcase( iTerm==16 );
  139320. if( pUsage[i].omit ){
  139321. if( i<16 && ((1<<i)&mNoOmit)==0 ){
  139322. testcase( i!=iTerm );
  139323. pNew->u.vtab.omitMask |= 1<<iTerm;
  139324. }else{
  139325. testcase( i!=iTerm );
  139326. }
  139327. }
  139328. if( (pTerm->eOperator & WO_IN)!=0 ){
  139329. /* A virtual table that is constrained by an IN clause may not
  139330. ** consume the ORDER BY clause because (1) the order of IN terms
  139331. ** is not necessarily related to the order of output terms and
  139332. ** (2) Multiple outputs from a single IN value will not merge
  139333. ** together. */
  139334. pIdxInfo->orderByConsumed = 0;
  139335. pIdxInfo->idxFlags &= ~SQLITE_INDEX_SCAN_UNIQUE;
  139336. *pbIn = 1; assert( (mExclude & WO_IN)==0 );
  139337. }
  139338. }
  139339. }
  139340. pNew->nLTerm = mxTerm+1;
  139341. for(i=0; i<=mxTerm; i++){
  139342. if( pNew->aLTerm[i]==0 ){
  139343. /* The non-zero argvIdx values must be contiguous. Raise an
  139344. ** error if they are not */
  139345. sqlite3ErrorMsg(pParse,"%s.xBestIndex malfunction",pSrc->pTab->zName);
  139346. testcase( pIdxInfo->needToFreeIdxStr );
  139347. return SQLITE_ERROR;
  139348. }
  139349. }
  139350. assert( pNew->nLTerm<=pNew->nLSlot );
  139351. pNew->u.vtab.idxNum = pIdxInfo->idxNum;
  139352. pNew->u.vtab.needFree = pIdxInfo->needToFreeIdxStr;
  139353. pIdxInfo->needToFreeIdxStr = 0;
  139354. pNew->u.vtab.idxStr = pIdxInfo->idxStr;
  139355. pNew->u.vtab.isOrdered = (i8)(pIdxInfo->orderByConsumed ?
  139356. pIdxInfo->nOrderBy : 0);
  139357. pNew->rSetup = 0;
  139358. pNew->rRun = sqlite3LogEstFromDouble(pIdxInfo->estimatedCost);
  139359. pNew->nOut = sqlite3LogEst(pIdxInfo->estimatedRows);
  139360. /* Set the WHERE_ONEROW flag if the xBestIndex() method indicated
  139361. ** that the scan will visit at most one row. Clear it otherwise. */
  139362. if( pIdxInfo->idxFlags & SQLITE_INDEX_SCAN_UNIQUE ){
  139363. pNew->wsFlags |= WHERE_ONEROW;
  139364. }else{
  139365. pNew->wsFlags &= ~WHERE_ONEROW;
  139366. }
  139367. rc = whereLoopInsert(pBuilder, pNew);
  139368. if( pNew->u.vtab.needFree ){
  139369. sqlite3_free(pNew->u.vtab.idxStr);
  139370. pNew->u.vtab.needFree = 0;
  139371. }
  139372. WHERETRACE(0xffff, (" bIn=%d prereqIn=%04llx prereqOut=%04llx\n",
  139373. *pbIn, (sqlite3_uint64)mPrereq,
  139374. (sqlite3_uint64)(pNew->prereq & ~mPrereq)));
  139375. return rc;
  139376. }
  139377. /*
  139378. ** If this function is invoked from within an xBestIndex() callback, it
  139379. ** returns a pointer to a buffer containing the name of the collation
  139380. ** sequence associated with element iCons of the sqlite3_index_info.aConstraint
  139381. ** array. Or, if iCons is out of range or there is no active xBestIndex
  139382. ** call, return NULL.
  139383. */
  139384. SQLITE_API const char *sqlite3_vtab_collation(sqlite3_index_info *pIdxInfo, int iCons){
  139385. HiddenIndexInfo *pHidden = (HiddenIndexInfo*)&pIdxInfo[1];
  139386. const char *zRet = 0;
  139387. if( iCons>=0 && iCons<pIdxInfo->nConstraint ){
  139388. CollSeq *pC = 0;
  139389. int iTerm = pIdxInfo->aConstraint[iCons].iTermOffset;
  139390. Expr *pX = pHidden->pWC->a[iTerm].pExpr;
  139391. if( pX->pLeft ){
  139392. pC = sqlite3ExprCompareCollSeq(pHidden->pParse, pX);
  139393. }
  139394. zRet = (pC ? pC->zName : sqlite3StrBINARY);
  139395. }
  139396. return zRet;
  139397. }
  139398. /*
  139399. ** Add all WhereLoop objects for a table of the join identified by
  139400. ** pBuilder->pNew->iTab. That table is guaranteed to be a virtual table.
  139401. **
  139402. ** If there are no LEFT or CROSS JOIN joins in the query, both mPrereq and
  139403. ** mUnusable are set to 0. Otherwise, mPrereq is a mask of all FROM clause
  139404. ** entries that occur before the virtual table in the FROM clause and are
  139405. ** separated from it by at least one LEFT or CROSS JOIN. Similarly, the
  139406. ** mUnusable mask contains all FROM clause entries that occur after the
  139407. ** virtual table and are separated from it by at least one LEFT or
  139408. ** CROSS JOIN.
  139409. **
  139410. ** For example, if the query were:
  139411. **
  139412. ** ... FROM t1, t2 LEFT JOIN t3, t4, vt CROSS JOIN t5, t6;
  139413. **
  139414. ** then mPrereq corresponds to (t1, t2) and mUnusable to (t5, t6).
  139415. **
  139416. ** All the tables in mPrereq must be scanned before the current virtual
  139417. ** table. So any terms for which all prerequisites are satisfied by
  139418. ** mPrereq may be specified as "usable" in all calls to xBestIndex.
  139419. ** Conversely, all tables in mUnusable must be scanned after the current
  139420. ** virtual table, so any terms for which the prerequisites overlap with
  139421. ** mUnusable should always be configured as "not-usable" for xBestIndex.
  139422. */
  139423. static int whereLoopAddVirtual(
  139424. WhereLoopBuilder *pBuilder, /* WHERE clause information */
  139425. Bitmask mPrereq, /* Tables that must be scanned before this one */
  139426. Bitmask mUnusable /* Tables that must be scanned after this one */
  139427. ){
  139428. int rc = SQLITE_OK; /* Return code */
  139429. WhereInfo *pWInfo; /* WHERE analysis context */
  139430. Parse *pParse; /* The parsing context */
  139431. WhereClause *pWC; /* The WHERE clause */
  139432. struct SrcList_item *pSrc; /* The FROM clause term to search */
  139433. sqlite3_index_info *p; /* Object to pass to xBestIndex() */
  139434. int nConstraint; /* Number of constraints in p */
  139435. int bIn; /* True if plan uses IN(...) operator */
  139436. WhereLoop *pNew;
  139437. Bitmask mBest; /* Tables used by best possible plan */
  139438. u16 mNoOmit;
  139439. assert( (mPrereq & mUnusable)==0 );
  139440. pWInfo = pBuilder->pWInfo;
  139441. pParse = pWInfo->pParse;
  139442. pWC = pBuilder->pWC;
  139443. pNew = pBuilder->pNew;
  139444. pSrc = &pWInfo->pTabList->a[pNew->iTab];
  139445. assert( IsVirtual(pSrc->pTab) );
  139446. p = allocateIndexInfo(pParse, pWC, mUnusable, pSrc, pBuilder->pOrderBy,
  139447. &mNoOmit);
  139448. if( p==0 ) return SQLITE_NOMEM_BKPT;
  139449. pNew->rSetup = 0;
  139450. pNew->wsFlags = WHERE_VIRTUALTABLE;
  139451. pNew->nLTerm = 0;
  139452. pNew->u.vtab.needFree = 0;
  139453. nConstraint = p->nConstraint;
  139454. if( whereLoopResize(pParse->db, pNew, nConstraint) ){
  139455. sqlite3DbFree(pParse->db, p);
  139456. return SQLITE_NOMEM_BKPT;
  139457. }
  139458. /* First call xBestIndex() with all constraints usable. */
  139459. WHERETRACE(0x800, ("BEGIN %s.addVirtual()\n", pSrc->pTab->zName));
  139460. WHERETRACE(0x40, (" VirtualOne: all usable\n"));
  139461. rc = whereLoopAddVirtualOne(pBuilder, mPrereq, ALLBITS, 0, p, mNoOmit, &bIn);
  139462. /* If the call to xBestIndex() with all terms enabled produced a plan
  139463. ** that does not require any source tables (IOW: a plan with mBest==0)
  139464. ** and does not use an IN(...) operator, then there is no point in making
  139465. ** any further calls to xBestIndex() since they will all return the same
  139466. ** result (if the xBestIndex() implementation is sane). */
  139467. if( rc==SQLITE_OK && ((mBest = (pNew->prereq & ~mPrereq))!=0 || bIn) ){
  139468. int seenZero = 0; /* True if a plan with no prereqs seen */
  139469. int seenZeroNoIN = 0; /* Plan with no prereqs and no IN(...) seen */
  139470. Bitmask mPrev = 0;
  139471. Bitmask mBestNoIn = 0;
  139472. /* If the plan produced by the earlier call uses an IN(...) term, call
  139473. ** xBestIndex again, this time with IN(...) terms disabled. */
  139474. if( bIn ){
  139475. WHERETRACE(0x40, (" VirtualOne: all usable w/o IN\n"));
  139476. rc = whereLoopAddVirtualOne(
  139477. pBuilder, mPrereq, ALLBITS, WO_IN, p, mNoOmit, &bIn);
  139478. assert( bIn==0 );
  139479. mBestNoIn = pNew->prereq & ~mPrereq;
  139480. if( mBestNoIn==0 ){
  139481. seenZero = 1;
  139482. seenZeroNoIN = 1;
  139483. }
  139484. }
  139485. /* Call xBestIndex once for each distinct value of (prereqRight & ~mPrereq)
  139486. ** in the set of terms that apply to the current virtual table. */
  139487. while( rc==SQLITE_OK ){
  139488. int i;
  139489. Bitmask mNext = ALLBITS;
  139490. assert( mNext>0 );
  139491. for(i=0; i<nConstraint; i++){
  139492. Bitmask mThis = (
  139493. pWC->a[p->aConstraint[i].iTermOffset].prereqRight & ~mPrereq
  139494. );
  139495. if( mThis>mPrev && mThis<mNext ) mNext = mThis;
  139496. }
  139497. mPrev = mNext;
  139498. if( mNext==ALLBITS ) break;
  139499. if( mNext==mBest || mNext==mBestNoIn ) continue;
  139500. WHERETRACE(0x40, (" VirtualOne: mPrev=%04llx mNext=%04llx\n",
  139501. (sqlite3_uint64)mPrev, (sqlite3_uint64)mNext));
  139502. rc = whereLoopAddVirtualOne(
  139503. pBuilder, mPrereq, mNext|mPrereq, 0, p, mNoOmit, &bIn);
  139504. if( pNew->prereq==mPrereq ){
  139505. seenZero = 1;
  139506. if( bIn==0 ) seenZeroNoIN = 1;
  139507. }
  139508. }
  139509. /* If the calls to xBestIndex() in the above loop did not find a plan
  139510. ** that requires no source tables at all (i.e. one guaranteed to be
  139511. ** usable), make a call here with all source tables disabled */
  139512. if( rc==SQLITE_OK && seenZero==0 ){
  139513. WHERETRACE(0x40, (" VirtualOne: all disabled\n"));
  139514. rc = whereLoopAddVirtualOne(
  139515. pBuilder, mPrereq, mPrereq, 0, p, mNoOmit, &bIn);
  139516. if( bIn==0 ) seenZeroNoIN = 1;
  139517. }
  139518. /* If the calls to xBestIndex() have so far failed to find a plan
  139519. ** that requires no source tables at all and does not use an IN(...)
  139520. ** operator, make a final call to obtain one here. */
  139521. if( rc==SQLITE_OK && seenZeroNoIN==0 ){
  139522. WHERETRACE(0x40, (" VirtualOne: all disabled and w/o IN\n"));
  139523. rc = whereLoopAddVirtualOne(
  139524. pBuilder, mPrereq, mPrereq, WO_IN, p, mNoOmit, &bIn);
  139525. }
  139526. }
  139527. if( p->needToFreeIdxStr ) sqlite3_free(p->idxStr);
  139528. sqlite3DbFreeNN(pParse->db, p);
  139529. WHERETRACE(0x800, ("END %s.addVirtual(), rc=%d\n", pSrc->pTab->zName, rc));
  139530. return rc;
  139531. }
  139532. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  139533. /*
  139534. ** Add WhereLoop entries to handle OR terms. This works for either
  139535. ** btrees or virtual tables.
  139536. */
  139537. static int whereLoopAddOr(
  139538. WhereLoopBuilder *pBuilder,
  139539. Bitmask mPrereq,
  139540. Bitmask mUnusable
  139541. ){
  139542. WhereInfo *pWInfo = pBuilder->pWInfo;
  139543. WhereClause *pWC;
  139544. WhereLoop *pNew;
  139545. WhereTerm *pTerm, *pWCEnd;
  139546. int rc = SQLITE_OK;
  139547. int iCur;
  139548. WhereClause tempWC;
  139549. WhereLoopBuilder sSubBuild;
  139550. WhereOrSet sSum, sCur;
  139551. struct SrcList_item *pItem;
  139552. pWC = pBuilder->pWC;
  139553. pWCEnd = pWC->a + pWC->nTerm;
  139554. pNew = pBuilder->pNew;
  139555. memset(&sSum, 0, sizeof(sSum));
  139556. pItem = pWInfo->pTabList->a + pNew->iTab;
  139557. iCur = pItem->iCursor;
  139558. for(pTerm=pWC->a; pTerm<pWCEnd && rc==SQLITE_OK; pTerm++){
  139559. if( (pTerm->eOperator & WO_OR)!=0
  139560. && (pTerm->u.pOrInfo->indexable & pNew->maskSelf)!=0
  139561. ){
  139562. WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
  139563. WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
  139564. WhereTerm *pOrTerm;
  139565. int once = 1;
  139566. int i, j;
  139567. sSubBuild = *pBuilder;
  139568. sSubBuild.pOrderBy = 0;
  139569. sSubBuild.pOrSet = &sCur;
  139570. WHERETRACE(0x200, ("Begin processing OR-clause %p\n", pTerm));
  139571. for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
  139572. if( (pOrTerm->eOperator & WO_AND)!=0 ){
  139573. sSubBuild.pWC = &pOrTerm->u.pAndInfo->wc;
  139574. }else if( pOrTerm->leftCursor==iCur ){
  139575. tempWC.pWInfo = pWC->pWInfo;
  139576. tempWC.pOuter = pWC;
  139577. tempWC.op = TK_AND;
  139578. tempWC.nTerm = 1;
  139579. tempWC.a = pOrTerm;
  139580. sSubBuild.pWC = &tempWC;
  139581. }else{
  139582. continue;
  139583. }
  139584. sCur.n = 0;
  139585. #ifdef WHERETRACE_ENABLED
  139586. WHERETRACE(0x200, ("OR-term %d of %p has %d subterms:\n",
  139587. (int)(pOrTerm-pOrWC->a), pTerm, sSubBuild.pWC->nTerm));
  139588. if( sqlite3WhereTrace & 0x400 ){
  139589. sqlite3WhereClausePrint(sSubBuild.pWC);
  139590. }
  139591. #endif
  139592. #ifndef SQLITE_OMIT_VIRTUALTABLE
  139593. if( IsVirtual(pItem->pTab) ){
  139594. rc = whereLoopAddVirtual(&sSubBuild, mPrereq, mUnusable);
  139595. }else
  139596. #endif
  139597. {
  139598. rc = whereLoopAddBtree(&sSubBuild, mPrereq);
  139599. }
  139600. if( rc==SQLITE_OK ){
  139601. rc = whereLoopAddOr(&sSubBuild, mPrereq, mUnusable);
  139602. }
  139603. assert( rc==SQLITE_OK || rc==SQLITE_DONE || sCur.n==0 );
  139604. testcase( rc==SQLITE_DONE );
  139605. if( sCur.n==0 ){
  139606. sSum.n = 0;
  139607. break;
  139608. }else if( once ){
  139609. whereOrMove(&sSum, &sCur);
  139610. once = 0;
  139611. }else{
  139612. WhereOrSet sPrev;
  139613. whereOrMove(&sPrev, &sSum);
  139614. sSum.n = 0;
  139615. for(i=0; i<sPrev.n; i++){
  139616. for(j=0; j<sCur.n; j++){
  139617. whereOrInsert(&sSum, sPrev.a[i].prereq | sCur.a[j].prereq,
  139618. sqlite3LogEstAdd(sPrev.a[i].rRun, sCur.a[j].rRun),
  139619. sqlite3LogEstAdd(sPrev.a[i].nOut, sCur.a[j].nOut));
  139620. }
  139621. }
  139622. }
  139623. }
  139624. pNew->nLTerm = 1;
  139625. pNew->aLTerm[0] = pTerm;
  139626. pNew->wsFlags = WHERE_MULTI_OR;
  139627. pNew->rSetup = 0;
  139628. pNew->iSortIdx = 0;
  139629. memset(&pNew->u, 0, sizeof(pNew->u));
  139630. for(i=0; rc==SQLITE_OK && i<sSum.n; i++){
  139631. /* TUNING: Currently sSum.a[i].rRun is set to the sum of the costs
  139632. ** of all sub-scans required by the OR-scan. However, due to rounding
  139633. ** errors, it may be that the cost of the OR-scan is equal to its
  139634. ** most expensive sub-scan. Add the smallest possible penalty
  139635. ** (equivalent to multiplying the cost by 1.07) to ensure that
  139636. ** this does not happen. Otherwise, for WHERE clauses such as the
  139637. ** following where there is an index on "y":
  139638. **
  139639. ** WHERE likelihood(x=?, 0.99) OR y=?
  139640. **
  139641. ** the planner may elect to "OR" together a full-table scan and an
  139642. ** index lookup. And other similarly odd results. */
  139643. pNew->rRun = sSum.a[i].rRun + 1;
  139644. pNew->nOut = sSum.a[i].nOut;
  139645. pNew->prereq = sSum.a[i].prereq;
  139646. rc = whereLoopInsert(pBuilder, pNew);
  139647. }
  139648. WHERETRACE(0x200, ("End processing OR-clause %p\n", pTerm));
  139649. }
  139650. }
  139651. return rc;
  139652. }
  139653. /*
  139654. ** Add all WhereLoop objects for all tables
  139655. */
  139656. static int whereLoopAddAll(WhereLoopBuilder *pBuilder){
  139657. WhereInfo *pWInfo = pBuilder->pWInfo;
  139658. Bitmask mPrereq = 0;
  139659. Bitmask mPrior = 0;
  139660. int iTab;
  139661. SrcList *pTabList = pWInfo->pTabList;
  139662. struct SrcList_item *pItem;
  139663. struct SrcList_item *pEnd = &pTabList->a[pWInfo->nLevel];
  139664. sqlite3 *db = pWInfo->pParse->db;
  139665. int rc = SQLITE_OK;
  139666. WhereLoop *pNew;
  139667. u8 priorJointype = 0;
  139668. /* Loop over the tables in the join, from left to right */
  139669. pNew = pBuilder->pNew;
  139670. whereLoopInit(pNew);
  139671. pBuilder->iPlanLimit = SQLITE_QUERY_PLANNER_LIMIT;
  139672. for(iTab=0, pItem=pTabList->a; pItem<pEnd; iTab++, pItem++){
  139673. Bitmask mUnusable = 0;
  139674. pNew->iTab = iTab;
  139675. pBuilder->iPlanLimit += SQLITE_QUERY_PLANNER_LIMIT_INCR;
  139676. pNew->maskSelf = sqlite3WhereGetMask(&pWInfo->sMaskSet, pItem->iCursor);
  139677. if( ((pItem->fg.jointype|priorJointype) & (JT_LEFT|JT_CROSS))!=0 ){
  139678. /* This condition is true when pItem is the FROM clause term on the
  139679. ** right-hand-side of a LEFT or CROSS JOIN. */
  139680. mPrereq = mPrior;
  139681. }
  139682. priorJointype = pItem->fg.jointype;
  139683. #ifndef SQLITE_OMIT_VIRTUALTABLE
  139684. if( IsVirtual(pItem->pTab) ){
  139685. struct SrcList_item *p;
  139686. for(p=&pItem[1]; p<pEnd; p++){
  139687. if( mUnusable || (p->fg.jointype & (JT_LEFT|JT_CROSS)) ){
  139688. mUnusable |= sqlite3WhereGetMask(&pWInfo->sMaskSet, p->iCursor);
  139689. }
  139690. }
  139691. rc = whereLoopAddVirtual(pBuilder, mPrereq, mUnusable);
  139692. }else
  139693. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  139694. {
  139695. rc = whereLoopAddBtree(pBuilder, mPrereq);
  139696. }
  139697. if( rc==SQLITE_OK && pBuilder->pWC->hasOr ){
  139698. rc = whereLoopAddOr(pBuilder, mPrereq, mUnusable);
  139699. }
  139700. mPrior |= pNew->maskSelf;
  139701. if( rc || db->mallocFailed ){
  139702. if( rc==SQLITE_DONE ){
  139703. /* We hit the query planner search limit set by iPlanLimit */
  139704. sqlite3_log(SQLITE_WARNING, "abbreviated query algorithm search");
  139705. rc = SQLITE_OK;
  139706. }else{
  139707. break;
  139708. }
  139709. }
  139710. }
  139711. whereLoopClear(db, pNew);
  139712. return rc;
  139713. }
  139714. /*
  139715. ** Examine a WherePath (with the addition of the extra WhereLoop of the 6th
  139716. ** parameters) to see if it outputs rows in the requested ORDER BY
  139717. ** (or GROUP BY) without requiring a separate sort operation. Return N:
  139718. **
  139719. ** N>0: N terms of the ORDER BY clause are satisfied
  139720. ** N==0: No terms of the ORDER BY clause are satisfied
  139721. ** N<0: Unknown yet how many terms of ORDER BY might be satisfied.
  139722. **
  139723. ** Note that processing for WHERE_GROUPBY and WHERE_DISTINCTBY is not as
  139724. ** strict. With GROUP BY and DISTINCT the only requirement is that
  139725. ** equivalent rows appear immediately adjacent to one another. GROUP BY
  139726. ** and DISTINCT do not require rows to appear in any particular order as long
  139727. ** as equivalent rows are grouped together. Thus for GROUP BY and DISTINCT
  139728. ** the pOrderBy terms can be matched in any order. With ORDER BY, the
  139729. ** pOrderBy terms must be matched in strict left-to-right order.
  139730. */
  139731. static i8 wherePathSatisfiesOrderBy(
  139732. WhereInfo *pWInfo, /* The WHERE clause */
  139733. ExprList *pOrderBy, /* ORDER BY or GROUP BY or DISTINCT clause to check */
  139734. WherePath *pPath, /* The WherePath to check */
  139735. u16 wctrlFlags, /* WHERE_GROUPBY or _DISTINCTBY or _ORDERBY_LIMIT */
  139736. u16 nLoop, /* Number of entries in pPath->aLoop[] */
  139737. WhereLoop *pLast, /* Add this WhereLoop to the end of pPath->aLoop[] */
  139738. Bitmask *pRevMask /* OUT: Mask of WhereLoops to run in reverse order */
  139739. ){
  139740. u8 revSet; /* True if rev is known */
  139741. u8 rev; /* Composite sort order */
  139742. u8 revIdx; /* Index sort order */
  139743. u8 isOrderDistinct; /* All prior WhereLoops are order-distinct */
  139744. u8 distinctColumns; /* True if the loop has UNIQUE NOT NULL columns */
  139745. u8 isMatch; /* iColumn matches a term of the ORDER BY clause */
  139746. u16 eqOpMask; /* Allowed equality operators */
  139747. u16 nKeyCol; /* Number of key columns in pIndex */
  139748. u16 nColumn; /* Total number of ordered columns in the index */
  139749. u16 nOrderBy; /* Number terms in the ORDER BY clause */
  139750. int iLoop; /* Index of WhereLoop in pPath being processed */
  139751. int i, j; /* Loop counters */
  139752. int iCur; /* Cursor number for current WhereLoop */
  139753. int iColumn; /* A column number within table iCur */
  139754. WhereLoop *pLoop = 0; /* Current WhereLoop being processed. */
  139755. WhereTerm *pTerm; /* A single term of the WHERE clause */
  139756. Expr *pOBExpr; /* An expression from the ORDER BY clause */
  139757. CollSeq *pColl; /* COLLATE function from an ORDER BY clause term */
  139758. Index *pIndex; /* The index associated with pLoop */
  139759. sqlite3 *db = pWInfo->pParse->db; /* Database connection */
  139760. Bitmask obSat = 0; /* Mask of ORDER BY terms satisfied so far */
  139761. Bitmask obDone; /* Mask of all ORDER BY terms */
  139762. Bitmask orderDistinctMask; /* Mask of all well-ordered loops */
  139763. Bitmask ready; /* Mask of inner loops */
  139764. /*
  139765. ** We say the WhereLoop is "one-row" if it generates no more than one
  139766. ** row of output. A WhereLoop is one-row if all of the following are true:
  139767. ** (a) All index columns match with WHERE_COLUMN_EQ.
  139768. ** (b) The index is unique
  139769. ** Any WhereLoop with an WHERE_COLUMN_EQ constraint on the rowid is one-row.
  139770. ** Every one-row WhereLoop will have the WHERE_ONEROW bit set in wsFlags.
  139771. **
  139772. ** We say the WhereLoop is "order-distinct" if the set of columns from
  139773. ** that WhereLoop that are in the ORDER BY clause are different for every
  139774. ** row of the WhereLoop. Every one-row WhereLoop is automatically
  139775. ** order-distinct. A WhereLoop that has no columns in the ORDER BY clause
  139776. ** is not order-distinct. To be order-distinct is not quite the same as being
  139777. ** UNIQUE since a UNIQUE column or index can have multiple rows that
  139778. ** are NULL and NULL values are equivalent for the purpose of order-distinct.
  139779. ** To be order-distinct, the columns must be UNIQUE and NOT NULL.
  139780. **
  139781. ** The rowid for a table is always UNIQUE and NOT NULL so whenever the
  139782. ** rowid appears in the ORDER BY clause, the corresponding WhereLoop is
  139783. ** automatically order-distinct.
  139784. */
  139785. assert( pOrderBy!=0 );
  139786. if( nLoop && OptimizationDisabled(db, SQLITE_OrderByIdxJoin) ) return 0;
  139787. nOrderBy = pOrderBy->nExpr;
  139788. testcase( nOrderBy==BMS-1 );
  139789. if( nOrderBy>BMS-1 ) return 0; /* Cannot optimize overly large ORDER BYs */
  139790. isOrderDistinct = 1;
  139791. obDone = MASKBIT(nOrderBy)-1;
  139792. orderDistinctMask = 0;
  139793. ready = 0;
  139794. eqOpMask = WO_EQ | WO_IS | WO_ISNULL;
  139795. if( wctrlFlags & WHERE_ORDERBY_LIMIT ) eqOpMask |= WO_IN;
  139796. for(iLoop=0; isOrderDistinct && obSat<obDone && iLoop<=nLoop; iLoop++){
  139797. if( iLoop>0 ) ready |= pLoop->maskSelf;
  139798. if( iLoop<nLoop ){
  139799. pLoop = pPath->aLoop[iLoop];
  139800. if( wctrlFlags & WHERE_ORDERBY_LIMIT ) continue;
  139801. }else{
  139802. pLoop = pLast;
  139803. }
  139804. if( pLoop->wsFlags & WHERE_VIRTUALTABLE ){
  139805. if( pLoop->u.vtab.isOrdered && (wctrlFlags & WHERE_DISTINCTBY)==0 ){
  139806. obSat = obDone;
  139807. }
  139808. break;
  139809. }else if( wctrlFlags & WHERE_DISTINCTBY ){
  139810. pLoop->u.btree.nDistinctCol = 0;
  139811. }
  139812. iCur = pWInfo->pTabList->a[pLoop->iTab].iCursor;
  139813. /* Mark off any ORDER BY term X that is a column in the table of
  139814. ** the current loop for which there is term in the WHERE
  139815. ** clause of the form X IS NULL or X=? that reference only outer
  139816. ** loops.
  139817. */
  139818. for(i=0; i<nOrderBy; i++){
  139819. if( MASKBIT(i) & obSat ) continue;
  139820. pOBExpr = sqlite3ExprSkipCollateAndLikely(pOrderBy->a[i].pExpr);
  139821. if( pOBExpr->op!=TK_COLUMN ) continue;
  139822. if( pOBExpr->iTable!=iCur ) continue;
  139823. pTerm = sqlite3WhereFindTerm(&pWInfo->sWC, iCur, pOBExpr->iColumn,
  139824. ~ready, eqOpMask, 0);
  139825. if( pTerm==0 ) continue;
  139826. if( pTerm->eOperator==WO_IN ){
  139827. /* IN terms are only valid for sorting in the ORDER BY LIMIT
  139828. ** optimization, and then only if they are actually used
  139829. ** by the query plan */
  139830. assert( wctrlFlags & WHERE_ORDERBY_LIMIT );
  139831. for(j=0; j<pLoop->nLTerm && pTerm!=pLoop->aLTerm[j]; j++){}
  139832. if( j>=pLoop->nLTerm ) continue;
  139833. }
  139834. if( (pTerm->eOperator&(WO_EQ|WO_IS))!=0 && pOBExpr->iColumn>=0 ){
  139835. Parse *pParse = pWInfo->pParse;
  139836. CollSeq *pColl1 = sqlite3ExprNNCollSeq(pParse, pOrderBy->a[i].pExpr);
  139837. CollSeq *pColl2 = sqlite3ExprCompareCollSeq(pParse, pTerm->pExpr);
  139838. assert( pColl1 );
  139839. if( pColl2==0 || sqlite3StrICmp(pColl1->zName, pColl2->zName) ){
  139840. continue;
  139841. }
  139842. testcase( pTerm->pExpr->op==TK_IS );
  139843. }
  139844. obSat |= MASKBIT(i);
  139845. }
  139846. if( (pLoop->wsFlags & WHERE_ONEROW)==0 ){
  139847. if( pLoop->wsFlags & WHERE_IPK ){
  139848. pIndex = 0;
  139849. nKeyCol = 0;
  139850. nColumn = 1;
  139851. }else if( (pIndex = pLoop->u.btree.pIndex)==0 || pIndex->bUnordered ){
  139852. return 0;
  139853. }else{
  139854. nKeyCol = pIndex->nKeyCol;
  139855. nColumn = pIndex->nColumn;
  139856. assert( nColumn==nKeyCol+1 || !HasRowid(pIndex->pTable) );
  139857. assert( pIndex->aiColumn[nColumn-1]==XN_ROWID
  139858. || !HasRowid(pIndex->pTable));
  139859. isOrderDistinct = IsUniqueIndex(pIndex)
  139860. && (pLoop->wsFlags & WHERE_SKIPSCAN)==0;
  139861. }
  139862. /* Loop through all columns of the index and deal with the ones
  139863. ** that are not constrained by == or IN.
  139864. */
  139865. rev = revSet = 0;
  139866. distinctColumns = 0;
  139867. for(j=0; j<nColumn; j++){
  139868. u8 bOnce = 1; /* True to run the ORDER BY search loop */
  139869. assert( j>=pLoop->u.btree.nEq
  139870. || (pLoop->aLTerm[j]==0)==(j<pLoop->nSkip)
  139871. );
  139872. if( j<pLoop->u.btree.nEq && j>=pLoop->nSkip ){
  139873. u16 eOp = pLoop->aLTerm[j]->eOperator;
  139874. /* Skip over == and IS and ISNULL terms. (Also skip IN terms when
  139875. ** doing WHERE_ORDERBY_LIMIT processing). Except, IS and ISNULL
  139876. ** terms imply that the index is not UNIQUE NOT NULL in which case
  139877. ** the loop need to be marked as not order-distinct because it can
  139878. ** have repeated NULL rows.
  139879. **
  139880. ** If the current term is a column of an ((?,?) IN (SELECT...))
  139881. ** expression for which the SELECT returns more than one column,
  139882. ** check that it is the only column used by this loop. Otherwise,
  139883. ** if it is one of two or more, none of the columns can be
  139884. ** considered to match an ORDER BY term.
  139885. */
  139886. if( (eOp & eqOpMask)!=0 ){
  139887. if( eOp & (WO_ISNULL|WO_IS) ){
  139888. testcase( eOp & WO_ISNULL );
  139889. testcase( eOp & WO_IS );
  139890. testcase( isOrderDistinct );
  139891. isOrderDistinct = 0;
  139892. }
  139893. continue;
  139894. }else if( ALWAYS(eOp & WO_IN) ){
  139895. /* ALWAYS() justification: eOp is an equality operator due to the
  139896. ** j<pLoop->u.btree.nEq constraint above. Any equality other
  139897. ** than WO_IN is captured by the previous "if". So this one
  139898. ** always has to be WO_IN. */
  139899. Expr *pX = pLoop->aLTerm[j]->pExpr;
  139900. for(i=j+1; i<pLoop->u.btree.nEq; i++){
  139901. if( pLoop->aLTerm[i]->pExpr==pX ){
  139902. assert( (pLoop->aLTerm[i]->eOperator & WO_IN) );
  139903. bOnce = 0;
  139904. break;
  139905. }
  139906. }
  139907. }
  139908. }
  139909. /* Get the column number in the table (iColumn) and sort order
  139910. ** (revIdx) for the j-th column of the index.
  139911. */
  139912. if( pIndex ){
  139913. iColumn = pIndex->aiColumn[j];
  139914. revIdx = pIndex->aSortOrder[j] & KEYINFO_ORDER_DESC;
  139915. if( iColumn==pIndex->pTable->iPKey ) iColumn = XN_ROWID;
  139916. }else{
  139917. iColumn = XN_ROWID;
  139918. revIdx = 0;
  139919. }
  139920. /* An unconstrained column that might be NULL means that this
  139921. ** WhereLoop is not well-ordered
  139922. */
  139923. if( isOrderDistinct
  139924. && iColumn>=0
  139925. && j>=pLoop->u.btree.nEq
  139926. && pIndex->pTable->aCol[iColumn].notNull==0
  139927. ){
  139928. isOrderDistinct = 0;
  139929. }
  139930. /* Find the ORDER BY term that corresponds to the j-th column
  139931. ** of the index and mark that ORDER BY term off
  139932. */
  139933. isMatch = 0;
  139934. for(i=0; bOnce && i<nOrderBy; i++){
  139935. if( MASKBIT(i) & obSat ) continue;
  139936. pOBExpr = sqlite3ExprSkipCollateAndLikely(pOrderBy->a[i].pExpr);
  139937. testcase( wctrlFlags & WHERE_GROUPBY );
  139938. testcase( wctrlFlags & WHERE_DISTINCTBY );
  139939. if( (wctrlFlags & (WHERE_GROUPBY|WHERE_DISTINCTBY))==0 ) bOnce = 0;
  139940. if( iColumn>=XN_ROWID ){
  139941. if( pOBExpr->op!=TK_COLUMN ) continue;
  139942. if( pOBExpr->iTable!=iCur ) continue;
  139943. if( pOBExpr->iColumn!=iColumn ) continue;
  139944. }else{
  139945. Expr *pIdxExpr = pIndex->aColExpr->a[j].pExpr;
  139946. if( sqlite3ExprCompareSkip(pOBExpr, pIdxExpr, iCur) ){
  139947. continue;
  139948. }
  139949. }
  139950. if( iColumn!=XN_ROWID ){
  139951. pColl = sqlite3ExprNNCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
  139952. if( sqlite3StrICmp(pColl->zName, pIndex->azColl[j])!=0 ) continue;
  139953. }
  139954. if( wctrlFlags & WHERE_DISTINCTBY ){
  139955. pLoop->u.btree.nDistinctCol = j+1;
  139956. }
  139957. isMatch = 1;
  139958. break;
  139959. }
  139960. if( isMatch && (wctrlFlags & WHERE_GROUPBY)==0 ){
  139961. /* Make sure the sort order is compatible in an ORDER BY clause.
  139962. ** Sort order is irrelevant for a GROUP BY clause. */
  139963. if( revSet ){
  139964. if( (rev ^ revIdx)!=(pOrderBy->a[i].sortFlags&KEYINFO_ORDER_DESC) ){
  139965. isMatch = 0;
  139966. }
  139967. }else{
  139968. rev = revIdx ^ (pOrderBy->a[i].sortFlags & KEYINFO_ORDER_DESC);
  139969. if( rev ) *pRevMask |= MASKBIT(iLoop);
  139970. revSet = 1;
  139971. }
  139972. }
  139973. if( isMatch && (pOrderBy->a[i].sortFlags & KEYINFO_ORDER_BIGNULL) ){
  139974. if( j==pLoop->u.btree.nEq ){
  139975. pLoop->wsFlags |= WHERE_BIGNULL_SORT;
  139976. }else{
  139977. isMatch = 0;
  139978. }
  139979. }
  139980. if( isMatch ){
  139981. if( iColumn==XN_ROWID ){
  139982. testcase( distinctColumns==0 );
  139983. distinctColumns = 1;
  139984. }
  139985. obSat |= MASKBIT(i);
  139986. }else{
  139987. /* No match found */
  139988. if( j==0 || j<nKeyCol ){
  139989. testcase( isOrderDistinct!=0 );
  139990. isOrderDistinct = 0;
  139991. }
  139992. break;
  139993. }
  139994. } /* end Loop over all index columns */
  139995. if( distinctColumns ){
  139996. testcase( isOrderDistinct==0 );
  139997. isOrderDistinct = 1;
  139998. }
  139999. } /* end-if not one-row */
  140000. /* Mark off any other ORDER BY terms that reference pLoop */
  140001. if( isOrderDistinct ){
  140002. orderDistinctMask |= pLoop->maskSelf;
  140003. for(i=0; i<nOrderBy; i++){
  140004. Expr *p;
  140005. Bitmask mTerm;
  140006. if( MASKBIT(i) & obSat ) continue;
  140007. p = pOrderBy->a[i].pExpr;
  140008. mTerm = sqlite3WhereExprUsage(&pWInfo->sMaskSet,p);
  140009. if( mTerm==0 && !sqlite3ExprIsConstant(p) ) continue;
  140010. if( (mTerm&~orderDistinctMask)==0 ){
  140011. obSat |= MASKBIT(i);
  140012. }
  140013. }
  140014. }
  140015. } /* End the loop over all WhereLoops from outer-most down to inner-most */
  140016. if( obSat==obDone ) return (i8)nOrderBy;
  140017. if( !isOrderDistinct ){
  140018. for(i=nOrderBy-1; i>0; i--){
  140019. Bitmask m = MASKBIT(i) - 1;
  140020. if( (obSat&m)==m ) return i;
  140021. }
  140022. return 0;
  140023. }
  140024. return -1;
  140025. }
  140026. /*
  140027. ** If the WHERE_GROUPBY flag is set in the mask passed to sqlite3WhereBegin(),
  140028. ** the planner assumes that the specified pOrderBy list is actually a GROUP
  140029. ** BY clause - and so any order that groups rows as required satisfies the
  140030. ** request.
  140031. **
  140032. ** Normally, in this case it is not possible for the caller to determine
  140033. ** whether or not the rows are really being delivered in sorted order, or
  140034. ** just in some other order that provides the required grouping. However,
  140035. ** if the WHERE_SORTBYGROUP flag is also passed to sqlite3WhereBegin(), then
  140036. ** this function may be called on the returned WhereInfo object. It returns
  140037. ** true if the rows really will be sorted in the specified order, or false
  140038. ** otherwise.
  140039. **
  140040. ** For example, assuming:
  140041. **
  140042. ** CREATE INDEX i1 ON t1(x, Y);
  140043. **
  140044. ** then
  140045. **
  140046. ** SELECT * FROM t1 GROUP BY x,y ORDER BY x,y; -- IsSorted()==1
  140047. ** SELECT * FROM t1 GROUP BY y,x ORDER BY y,x; -- IsSorted()==0
  140048. */
  140049. SQLITE_PRIVATE int sqlite3WhereIsSorted(WhereInfo *pWInfo){
  140050. assert( pWInfo->wctrlFlags & WHERE_GROUPBY );
  140051. assert( pWInfo->wctrlFlags & WHERE_SORTBYGROUP );
  140052. return pWInfo->sorted;
  140053. }
  140054. #ifdef WHERETRACE_ENABLED
  140055. /* For debugging use only: */
  140056. static const char *wherePathName(WherePath *pPath, int nLoop, WhereLoop *pLast){
  140057. static char zName[65];
  140058. int i;
  140059. for(i=0; i<nLoop; i++){ zName[i] = pPath->aLoop[i]->cId; }
  140060. if( pLast ) zName[i++] = pLast->cId;
  140061. zName[i] = 0;
  140062. return zName;
  140063. }
  140064. #endif
  140065. /*
  140066. ** Return the cost of sorting nRow rows, assuming that the keys have
  140067. ** nOrderby columns and that the first nSorted columns are already in
  140068. ** order.
  140069. */
  140070. static LogEst whereSortingCost(
  140071. WhereInfo *pWInfo,
  140072. LogEst nRow,
  140073. int nOrderBy,
  140074. int nSorted
  140075. ){
  140076. /* TUNING: Estimated cost of a full external sort, where N is
  140077. ** the number of rows to sort is:
  140078. **
  140079. ** cost = (3.0 * N * log(N)).
  140080. **
  140081. ** Or, if the order-by clause has X terms but only the last Y
  140082. ** terms are out of order, then block-sorting will reduce the
  140083. ** sorting cost to:
  140084. **
  140085. ** cost = (3.0 * N * log(N)) * (Y/X)
  140086. **
  140087. ** The (Y/X) term is implemented using stack variable rScale
  140088. ** below. */
  140089. LogEst rScale, rSortCost;
  140090. assert( nOrderBy>0 && 66==sqlite3LogEst(100) );
  140091. rScale = sqlite3LogEst((nOrderBy-nSorted)*100/nOrderBy) - 66;
  140092. rSortCost = nRow + rScale + 16;
  140093. /* Multiple by log(M) where M is the number of output rows.
  140094. ** Use the LIMIT for M if it is smaller */
  140095. if( (pWInfo->wctrlFlags & WHERE_USE_LIMIT)!=0 && pWInfo->iLimit<nRow ){
  140096. nRow = pWInfo->iLimit;
  140097. }
  140098. rSortCost += estLog(nRow);
  140099. return rSortCost;
  140100. }
  140101. /*
  140102. ** Given the list of WhereLoop objects at pWInfo->pLoops, this routine
  140103. ** attempts to find the lowest cost path that visits each WhereLoop
  140104. ** once. This path is then loaded into the pWInfo->a[].pWLoop fields.
  140105. **
  140106. ** Assume that the total number of output rows that will need to be sorted
  140107. ** will be nRowEst (in the 10*log2 representation). Or, ignore sorting
  140108. ** costs if nRowEst==0.
  140109. **
  140110. ** Return SQLITE_OK on success or SQLITE_NOMEM of a memory allocation
  140111. ** error occurs.
  140112. */
  140113. static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){
  140114. int mxChoice; /* Maximum number of simultaneous paths tracked */
  140115. int nLoop; /* Number of terms in the join */
  140116. Parse *pParse; /* Parsing context */
  140117. sqlite3 *db; /* The database connection */
  140118. int iLoop; /* Loop counter over the terms of the join */
  140119. int ii, jj; /* Loop counters */
  140120. int mxI = 0; /* Index of next entry to replace */
  140121. int nOrderBy; /* Number of ORDER BY clause terms */
  140122. LogEst mxCost = 0; /* Maximum cost of a set of paths */
  140123. LogEst mxUnsorted = 0; /* Maximum unsorted cost of a set of path */
  140124. int nTo, nFrom; /* Number of valid entries in aTo[] and aFrom[] */
  140125. WherePath *aFrom; /* All nFrom paths at the previous level */
  140126. WherePath *aTo; /* The nTo best paths at the current level */
  140127. WherePath *pFrom; /* An element of aFrom[] that we are working on */
  140128. WherePath *pTo; /* An element of aTo[] that we are working on */
  140129. WhereLoop *pWLoop; /* One of the WhereLoop objects */
  140130. WhereLoop **pX; /* Used to divy up the pSpace memory */
  140131. LogEst *aSortCost = 0; /* Sorting and partial sorting costs */
  140132. char *pSpace; /* Temporary memory used by this routine */
  140133. int nSpace; /* Bytes of space allocated at pSpace */
  140134. pParse = pWInfo->pParse;
  140135. db = pParse->db;
  140136. nLoop = pWInfo->nLevel;
  140137. /* TUNING: For simple queries, only the best path is tracked.
  140138. ** For 2-way joins, the 5 best paths are followed.
  140139. ** For joins of 3 or more tables, track the 10 best paths */
  140140. mxChoice = (nLoop<=1) ? 1 : (nLoop==2 ? 5 : 10);
  140141. assert( nLoop<=pWInfo->pTabList->nSrc );
  140142. WHERETRACE(0x002, ("---- begin solver. (nRowEst=%d)\n", nRowEst));
  140143. /* If nRowEst is zero and there is an ORDER BY clause, ignore it. In this
  140144. ** case the purpose of this call is to estimate the number of rows returned
  140145. ** by the overall query. Once this estimate has been obtained, the caller
  140146. ** will invoke this function a second time, passing the estimate as the
  140147. ** nRowEst parameter. */
  140148. if( pWInfo->pOrderBy==0 || nRowEst==0 ){
  140149. nOrderBy = 0;
  140150. }else{
  140151. nOrderBy = pWInfo->pOrderBy->nExpr;
  140152. }
  140153. /* Allocate and initialize space for aTo, aFrom and aSortCost[] */
  140154. nSpace = (sizeof(WherePath)+sizeof(WhereLoop*)*nLoop)*mxChoice*2;
  140155. nSpace += sizeof(LogEst) * nOrderBy;
  140156. pSpace = sqlite3DbMallocRawNN(db, nSpace);
  140157. if( pSpace==0 ) return SQLITE_NOMEM_BKPT;
  140158. aTo = (WherePath*)pSpace;
  140159. aFrom = aTo+mxChoice;
  140160. memset(aFrom, 0, sizeof(aFrom[0]));
  140161. pX = (WhereLoop**)(aFrom+mxChoice);
  140162. for(ii=mxChoice*2, pFrom=aTo; ii>0; ii--, pFrom++, pX += nLoop){
  140163. pFrom->aLoop = pX;
  140164. }
  140165. if( nOrderBy ){
  140166. /* If there is an ORDER BY clause and it is not being ignored, set up
  140167. ** space for the aSortCost[] array. Each element of the aSortCost array
  140168. ** is either zero - meaning it has not yet been initialized - or the
  140169. ** cost of sorting nRowEst rows of data where the first X terms of
  140170. ** the ORDER BY clause are already in order, where X is the array
  140171. ** index. */
  140172. aSortCost = (LogEst*)pX;
  140173. memset(aSortCost, 0, sizeof(LogEst) * nOrderBy);
  140174. }
  140175. assert( aSortCost==0 || &pSpace[nSpace]==(char*)&aSortCost[nOrderBy] );
  140176. assert( aSortCost!=0 || &pSpace[nSpace]==(char*)pX );
  140177. /* Seed the search with a single WherePath containing zero WhereLoops.
  140178. **
  140179. ** TUNING: Do not let the number of iterations go above 28. If the cost
  140180. ** of computing an automatic index is not paid back within the first 28
  140181. ** rows, then do not use the automatic index. */
  140182. aFrom[0].nRow = MIN(pParse->nQueryLoop, 48); assert( 48==sqlite3LogEst(28) );
  140183. nFrom = 1;
  140184. assert( aFrom[0].isOrdered==0 );
  140185. if( nOrderBy ){
  140186. /* If nLoop is zero, then there are no FROM terms in the query. Since
  140187. ** in this case the query may return a maximum of one row, the results
  140188. ** are already in the requested order. Set isOrdered to nOrderBy to
  140189. ** indicate this. Or, if nLoop is greater than zero, set isOrdered to
  140190. ** -1, indicating that the result set may or may not be ordered,
  140191. ** depending on the loops added to the current plan. */
  140192. aFrom[0].isOrdered = nLoop>0 ? -1 : nOrderBy;
  140193. }
  140194. /* Compute successively longer WherePaths using the previous generation
  140195. ** of WherePaths as the basis for the next. Keep track of the mxChoice
  140196. ** best paths at each generation */
  140197. for(iLoop=0; iLoop<nLoop; iLoop++){
  140198. nTo = 0;
  140199. for(ii=0, pFrom=aFrom; ii<nFrom; ii++, pFrom++){
  140200. for(pWLoop=pWInfo->pLoops; pWLoop; pWLoop=pWLoop->pNextLoop){
  140201. LogEst nOut; /* Rows visited by (pFrom+pWLoop) */
  140202. LogEst rCost; /* Cost of path (pFrom+pWLoop) */
  140203. LogEst rUnsorted; /* Unsorted cost of (pFrom+pWLoop) */
  140204. i8 isOrdered = pFrom->isOrdered; /* isOrdered for (pFrom+pWLoop) */
  140205. Bitmask maskNew; /* Mask of src visited by (..) */
  140206. Bitmask revMask = 0; /* Mask of rev-order loops for (..) */
  140207. if( (pWLoop->prereq & ~pFrom->maskLoop)!=0 ) continue;
  140208. if( (pWLoop->maskSelf & pFrom->maskLoop)!=0 ) continue;
  140209. if( (pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 && pFrom->nRow<3 ){
  140210. /* Do not use an automatic index if the this loop is expected
  140211. ** to run less than 1.25 times. It is tempting to also exclude
  140212. ** automatic index usage on an outer loop, but sometimes an automatic
  140213. ** index is useful in the outer loop of a correlated subquery. */
  140214. assert( 10==sqlite3LogEst(2) );
  140215. continue;
  140216. }
  140217. /* At this point, pWLoop is a candidate to be the next loop.
  140218. ** Compute its cost */
  140219. rUnsorted = sqlite3LogEstAdd(pWLoop->rSetup,pWLoop->rRun + pFrom->nRow);
  140220. rUnsorted = sqlite3LogEstAdd(rUnsorted, pFrom->rUnsorted);
  140221. nOut = pFrom->nRow + pWLoop->nOut;
  140222. maskNew = pFrom->maskLoop | pWLoop->maskSelf;
  140223. if( isOrdered<0 ){
  140224. isOrdered = wherePathSatisfiesOrderBy(pWInfo,
  140225. pWInfo->pOrderBy, pFrom, pWInfo->wctrlFlags,
  140226. iLoop, pWLoop, &revMask);
  140227. }else{
  140228. revMask = pFrom->revLoop;
  140229. }
  140230. if( isOrdered>=0 && isOrdered<nOrderBy ){
  140231. if( aSortCost[isOrdered]==0 ){
  140232. aSortCost[isOrdered] = whereSortingCost(
  140233. pWInfo, nRowEst, nOrderBy, isOrdered
  140234. );
  140235. }
  140236. /* TUNING: Add a small extra penalty (5) to sorting as an
  140237. ** extra encouragment to the query planner to select a plan
  140238. ** where the rows emerge in the correct order without any sorting
  140239. ** required. */
  140240. rCost = sqlite3LogEstAdd(rUnsorted, aSortCost[isOrdered]) + 5;
  140241. WHERETRACE(0x002,
  140242. ("---- sort cost=%-3d (%d/%d) increases cost %3d to %-3d\n",
  140243. aSortCost[isOrdered], (nOrderBy-isOrdered), nOrderBy,
  140244. rUnsorted, rCost));
  140245. }else{
  140246. rCost = rUnsorted;
  140247. rUnsorted -= 2; /* TUNING: Slight bias in favor of no-sort plans */
  140248. }
  140249. /* Check to see if pWLoop should be added to the set of
  140250. ** mxChoice best-so-far paths.
  140251. **
  140252. ** First look for an existing path among best-so-far paths
  140253. ** that covers the same set of loops and has the same isOrdered
  140254. ** setting as the current path candidate.
  140255. **
  140256. ** The term "((pTo->isOrdered^isOrdered)&0x80)==0" is equivalent
  140257. ** to (pTo->isOrdered==(-1))==(isOrdered==(-1))" for the range
  140258. ** of legal values for isOrdered, -1..64.
  140259. */
  140260. for(jj=0, pTo=aTo; jj<nTo; jj++, pTo++){
  140261. if( pTo->maskLoop==maskNew
  140262. && ((pTo->isOrdered^isOrdered)&0x80)==0
  140263. ){
  140264. testcase( jj==nTo-1 );
  140265. break;
  140266. }
  140267. }
  140268. if( jj>=nTo ){
  140269. /* None of the existing best-so-far paths match the candidate. */
  140270. if( nTo>=mxChoice
  140271. && (rCost>mxCost || (rCost==mxCost && rUnsorted>=mxUnsorted))
  140272. ){
  140273. /* The current candidate is no better than any of the mxChoice
  140274. ** paths currently in the best-so-far buffer. So discard
  140275. ** this candidate as not viable. */
  140276. #ifdef WHERETRACE_ENABLED /* 0x4 */
  140277. if( sqlite3WhereTrace&0x4 ){
  140278. sqlite3DebugPrintf("Skip %s cost=%-3d,%3d,%3d order=%c\n",
  140279. wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsorted,
  140280. isOrdered>=0 ? isOrdered+'0' : '?');
  140281. }
  140282. #endif
  140283. continue;
  140284. }
  140285. /* If we reach this points it means that the new candidate path
  140286. ** needs to be added to the set of best-so-far paths. */
  140287. if( nTo<mxChoice ){
  140288. /* Increase the size of the aTo set by one */
  140289. jj = nTo++;
  140290. }else{
  140291. /* New path replaces the prior worst to keep count below mxChoice */
  140292. jj = mxI;
  140293. }
  140294. pTo = &aTo[jj];
  140295. #ifdef WHERETRACE_ENABLED /* 0x4 */
  140296. if( sqlite3WhereTrace&0x4 ){
  140297. sqlite3DebugPrintf("New %s cost=%-3d,%3d,%3d order=%c\n",
  140298. wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsorted,
  140299. isOrdered>=0 ? isOrdered+'0' : '?');
  140300. }
  140301. #endif
  140302. }else{
  140303. /* Control reaches here if best-so-far path pTo=aTo[jj] covers the
  140304. ** same set of loops and has the same isOrdered setting as the
  140305. ** candidate path. Check to see if the candidate should replace
  140306. ** pTo or if the candidate should be skipped.
  140307. **
  140308. ** The conditional is an expanded vector comparison equivalent to:
  140309. ** (pTo->rCost,pTo->nRow,pTo->rUnsorted) <= (rCost,nOut,rUnsorted)
  140310. */
  140311. if( pTo->rCost<rCost
  140312. || (pTo->rCost==rCost
  140313. && (pTo->nRow<nOut
  140314. || (pTo->nRow==nOut && pTo->rUnsorted<=rUnsorted)
  140315. )
  140316. )
  140317. ){
  140318. #ifdef WHERETRACE_ENABLED /* 0x4 */
  140319. if( sqlite3WhereTrace&0x4 ){
  140320. sqlite3DebugPrintf(
  140321. "Skip %s cost=%-3d,%3d,%3d order=%c",
  140322. wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsorted,
  140323. isOrdered>=0 ? isOrdered+'0' : '?');
  140324. sqlite3DebugPrintf(" vs %s cost=%-3d,%3d,%3d order=%c\n",
  140325. wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
  140326. pTo->rUnsorted, pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
  140327. }
  140328. #endif
  140329. /* Discard the candidate path from further consideration */
  140330. testcase( pTo->rCost==rCost );
  140331. continue;
  140332. }
  140333. testcase( pTo->rCost==rCost+1 );
  140334. /* Control reaches here if the candidate path is better than the
  140335. ** pTo path. Replace pTo with the candidate. */
  140336. #ifdef WHERETRACE_ENABLED /* 0x4 */
  140337. if( sqlite3WhereTrace&0x4 ){
  140338. sqlite3DebugPrintf(
  140339. "Update %s cost=%-3d,%3d,%3d order=%c",
  140340. wherePathName(pFrom, iLoop, pWLoop), rCost, nOut, rUnsorted,
  140341. isOrdered>=0 ? isOrdered+'0' : '?');
  140342. sqlite3DebugPrintf(" was %s cost=%-3d,%3d,%3d order=%c\n",
  140343. wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
  140344. pTo->rUnsorted, pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
  140345. }
  140346. #endif
  140347. }
  140348. /* pWLoop is a winner. Add it to the set of best so far */
  140349. pTo->maskLoop = pFrom->maskLoop | pWLoop->maskSelf;
  140350. pTo->revLoop = revMask;
  140351. pTo->nRow = nOut;
  140352. pTo->rCost = rCost;
  140353. pTo->rUnsorted = rUnsorted;
  140354. pTo->isOrdered = isOrdered;
  140355. memcpy(pTo->aLoop, pFrom->aLoop, sizeof(WhereLoop*)*iLoop);
  140356. pTo->aLoop[iLoop] = pWLoop;
  140357. if( nTo>=mxChoice ){
  140358. mxI = 0;
  140359. mxCost = aTo[0].rCost;
  140360. mxUnsorted = aTo[0].nRow;
  140361. for(jj=1, pTo=&aTo[1]; jj<mxChoice; jj++, pTo++){
  140362. if( pTo->rCost>mxCost
  140363. || (pTo->rCost==mxCost && pTo->rUnsorted>mxUnsorted)
  140364. ){
  140365. mxCost = pTo->rCost;
  140366. mxUnsorted = pTo->rUnsorted;
  140367. mxI = jj;
  140368. }
  140369. }
  140370. }
  140371. }
  140372. }
  140373. #ifdef WHERETRACE_ENABLED /* >=2 */
  140374. if( sqlite3WhereTrace & 0x02 ){
  140375. sqlite3DebugPrintf("---- after round %d ----\n", iLoop);
  140376. for(ii=0, pTo=aTo; ii<nTo; ii++, pTo++){
  140377. sqlite3DebugPrintf(" %s cost=%-3d nrow=%-3d order=%c",
  140378. wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
  140379. pTo->isOrdered>=0 ? (pTo->isOrdered+'0') : '?');
  140380. if( pTo->isOrdered>0 ){
  140381. sqlite3DebugPrintf(" rev=0x%llx\n", pTo->revLoop);
  140382. }else{
  140383. sqlite3DebugPrintf("\n");
  140384. }
  140385. }
  140386. }
  140387. #endif
  140388. /* Swap the roles of aFrom and aTo for the next generation */
  140389. pFrom = aTo;
  140390. aTo = aFrom;
  140391. aFrom = pFrom;
  140392. nFrom = nTo;
  140393. }
  140394. if( nFrom==0 ){
  140395. sqlite3ErrorMsg(pParse, "no query solution");
  140396. sqlite3DbFreeNN(db, pSpace);
  140397. return SQLITE_ERROR;
  140398. }
  140399. /* Find the lowest cost path. pFrom will be left pointing to that path */
  140400. pFrom = aFrom;
  140401. for(ii=1; ii<nFrom; ii++){
  140402. if( pFrom->rCost>aFrom[ii].rCost ) pFrom = &aFrom[ii];
  140403. }
  140404. assert( pWInfo->nLevel==nLoop );
  140405. /* Load the lowest cost path into pWInfo */
  140406. for(iLoop=0; iLoop<nLoop; iLoop++){
  140407. WhereLevel *pLevel = pWInfo->a + iLoop;
  140408. pLevel->pWLoop = pWLoop = pFrom->aLoop[iLoop];
  140409. pLevel->iFrom = pWLoop->iTab;
  140410. pLevel->iTabCur = pWInfo->pTabList->a[pLevel->iFrom].iCursor;
  140411. }
  140412. if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT)!=0
  140413. && (pWInfo->wctrlFlags & WHERE_DISTINCTBY)==0
  140414. && pWInfo->eDistinct==WHERE_DISTINCT_NOOP
  140415. && nRowEst
  140416. ){
  140417. Bitmask notUsed;
  140418. int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pResultSet, pFrom,
  140419. WHERE_DISTINCTBY, nLoop-1, pFrom->aLoop[nLoop-1], &notUsed);
  140420. if( rc==pWInfo->pResultSet->nExpr ){
  140421. pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
  140422. }
  140423. }
  140424. pWInfo->bOrderedInnerLoop = 0;
  140425. if( pWInfo->pOrderBy ){
  140426. if( pWInfo->wctrlFlags & WHERE_DISTINCTBY ){
  140427. if( pFrom->isOrdered==pWInfo->pOrderBy->nExpr ){
  140428. pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
  140429. }
  140430. }else{
  140431. pWInfo->nOBSat = pFrom->isOrdered;
  140432. pWInfo->revMask = pFrom->revLoop;
  140433. if( pWInfo->nOBSat<=0 ){
  140434. pWInfo->nOBSat = 0;
  140435. if( nLoop>0 ){
  140436. u32 wsFlags = pFrom->aLoop[nLoop-1]->wsFlags;
  140437. if( (wsFlags & WHERE_ONEROW)==0
  140438. && (wsFlags&(WHERE_IPK|WHERE_COLUMN_IN))!=(WHERE_IPK|WHERE_COLUMN_IN)
  140439. ){
  140440. Bitmask m = 0;
  140441. int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy, pFrom,
  140442. WHERE_ORDERBY_LIMIT, nLoop-1, pFrom->aLoop[nLoop-1], &m);
  140443. testcase( wsFlags & WHERE_IPK );
  140444. testcase( wsFlags & WHERE_COLUMN_IN );
  140445. if( rc==pWInfo->pOrderBy->nExpr ){
  140446. pWInfo->bOrderedInnerLoop = 1;
  140447. pWInfo->revMask = m;
  140448. }
  140449. }
  140450. }
  140451. }
  140452. }
  140453. if( (pWInfo->wctrlFlags & WHERE_SORTBYGROUP)
  140454. && pWInfo->nOBSat==pWInfo->pOrderBy->nExpr && nLoop>0
  140455. ){
  140456. Bitmask revMask = 0;
  140457. int nOrder = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy,
  140458. pFrom, 0, nLoop-1, pFrom->aLoop[nLoop-1], &revMask
  140459. );
  140460. assert( pWInfo->sorted==0 );
  140461. if( nOrder==pWInfo->pOrderBy->nExpr ){
  140462. pWInfo->sorted = 1;
  140463. pWInfo->revMask = revMask;
  140464. }
  140465. }
  140466. }
  140467. pWInfo->nRowOut = pFrom->nRow;
  140468. /* Free temporary memory and return success */
  140469. sqlite3DbFreeNN(db, pSpace);
  140470. return SQLITE_OK;
  140471. }
  140472. /*
  140473. ** Most queries use only a single table (they are not joins) and have
  140474. ** simple == constraints against indexed fields. This routine attempts
  140475. ** to plan those simple cases using much less ceremony than the
  140476. ** general-purpose query planner, and thereby yield faster sqlite3_prepare()
  140477. ** times for the common case.
  140478. **
  140479. ** Return non-zero on success, if this query can be handled by this
  140480. ** no-frills query planner. Return zero if this query needs the
  140481. ** general-purpose query planner.
  140482. */
  140483. static int whereShortCut(WhereLoopBuilder *pBuilder){
  140484. WhereInfo *pWInfo;
  140485. struct SrcList_item *pItem;
  140486. WhereClause *pWC;
  140487. WhereTerm *pTerm;
  140488. WhereLoop *pLoop;
  140489. int iCur;
  140490. int j;
  140491. Table *pTab;
  140492. Index *pIdx;
  140493. pWInfo = pBuilder->pWInfo;
  140494. if( pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE ) return 0;
  140495. assert( pWInfo->pTabList->nSrc>=1 );
  140496. pItem = pWInfo->pTabList->a;
  140497. pTab = pItem->pTab;
  140498. if( IsVirtual(pTab) ) return 0;
  140499. if( pItem->fg.isIndexedBy ) return 0;
  140500. iCur = pItem->iCursor;
  140501. pWC = &pWInfo->sWC;
  140502. pLoop = pBuilder->pNew;
  140503. pLoop->wsFlags = 0;
  140504. pLoop->nSkip = 0;
  140505. pTerm = sqlite3WhereFindTerm(pWC, iCur, -1, 0, WO_EQ|WO_IS, 0);
  140506. if( pTerm ){
  140507. testcase( pTerm->eOperator & WO_IS );
  140508. pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_IPK|WHERE_ONEROW;
  140509. pLoop->aLTerm[0] = pTerm;
  140510. pLoop->nLTerm = 1;
  140511. pLoop->u.btree.nEq = 1;
  140512. /* TUNING: Cost of a rowid lookup is 10 */
  140513. pLoop->rRun = 33; /* 33==sqlite3LogEst(10) */
  140514. }else{
  140515. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  140516. int opMask;
  140517. assert( pLoop->aLTermSpace==pLoop->aLTerm );
  140518. if( !IsUniqueIndex(pIdx)
  140519. || pIdx->pPartIdxWhere!=0
  140520. || pIdx->nKeyCol>ArraySize(pLoop->aLTermSpace)
  140521. ) continue;
  140522. opMask = pIdx->uniqNotNull ? (WO_EQ|WO_IS) : WO_EQ;
  140523. for(j=0; j<pIdx->nKeyCol; j++){
  140524. pTerm = sqlite3WhereFindTerm(pWC, iCur, j, 0, opMask, pIdx);
  140525. if( pTerm==0 ) break;
  140526. testcase( pTerm->eOperator & WO_IS );
  140527. pLoop->aLTerm[j] = pTerm;
  140528. }
  140529. if( j!=pIdx->nKeyCol ) continue;
  140530. pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_ONEROW|WHERE_INDEXED;
  140531. if( pIdx->isCovering || (pItem->colUsed & pIdx->colNotIdxed)==0 ){
  140532. pLoop->wsFlags |= WHERE_IDX_ONLY;
  140533. }
  140534. pLoop->nLTerm = j;
  140535. pLoop->u.btree.nEq = j;
  140536. pLoop->u.btree.pIndex = pIdx;
  140537. /* TUNING: Cost of a unique index lookup is 15 */
  140538. pLoop->rRun = 39; /* 39==sqlite3LogEst(15) */
  140539. break;
  140540. }
  140541. }
  140542. if( pLoop->wsFlags ){
  140543. pLoop->nOut = (LogEst)1;
  140544. pWInfo->a[0].pWLoop = pLoop;
  140545. assert( pWInfo->sMaskSet.n==1 && iCur==pWInfo->sMaskSet.ix[0] );
  140546. pLoop->maskSelf = 1; /* sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur); */
  140547. pWInfo->a[0].iTabCur = iCur;
  140548. pWInfo->nRowOut = 1;
  140549. if( pWInfo->pOrderBy ) pWInfo->nOBSat = pWInfo->pOrderBy->nExpr;
  140550. if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){
  140551. pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
  140552. }
  140553. #ifdef SQLITE_DEBUG
  140554. pLoop->cId = '0';
  140555. #endif
  140556. return 1;
  140557. }
  140558. return 0;
  140559. }
  140560. /*
  140561. ** Helper function for exprIsDeterministic().
  140562. */
  140563. static int exprNodeIsDeterministic(Walker *pWalker, Expr *pExpr){
  140564. if( pExpr->op==TK_FUNCTION && ExprHasProperty(pExpr, EP_ConstFunc)==0 ){
  140565. pWalker->eCode = 0;
  140566. return WRC_Abort;
  140567. }
  140568. return WRC_Continue;
  140569. }
  140570. /*
  140571. ** Return true if the expression contains no non-deterministic SQL
  140572. ** functions. Do not consider non-deterministic SQL functions that are
  140573. ** part of sub-select statements.
  140574. */
  140575. static int exprIsDeterministic(Expr *p){
  140576. Walker w;
  140577. memset(&w, 0, sizeof(w));
  140578. w.eCode = 1;
  140579. w.xExprCallback = exprNodeIsDeterministic;
  140580. w.xSelectCallback = sqlite3SelectWalkFail;
  140581. sqlite3WalkExpr(&w, p);
  140582. return w.eCode;
  140583. }
  140584. #ifdef WHERETRACE_ENABLED
  140585. /*
  140586. ** Display all WhereLoops in pWInfo
  140587. */
  140588. static void showAllWhereLoops(WhereInfo *pWInfo, WhereClause *pWC){
  140589. if( sqlite3WhereTrace ){ /* Display all of the WhereLoop objects */
  140590. WhereLoop *p;
  140591. int i;
  140592. static const char zLabel[] = "0123456789abcdefghijklmnopqrstuvwyxz"
  140593. "ABCDEFGHIJKLMNOPQRSTUVWYXZ";
  140594. for(p=pWInfo->pLoops, i=0; p; p=p->pNextLoop, i++){
  140595. p->cId = zLabel[i%(sizeof(zLabel)-1)];
  140596. sqlite3WhereLoopPrint(p, pWC);
  140597. }
  140598. }
  140599. }
  140600. # define WHERETRACE_ALL_LOOPS(W,C) showAllWhereLoops(W,C)
  140601. #else
  140602. # define WHERETRACE_ALL_LOOPS(W,C)
  140603. #endif
  140604. /*
  140605. ** Generate the beginning of the loop used for WHERE clause processing.
  140606. ** The return value is a pointer to an opaque structure that contains
  140607. ** information needed to terminate the loop. Later, the calling routine
  140608. ** should invoke sqlite3WhereEnd() with the return value of this function
  140609. ** in order to complete the WHERE clause processing.
  140610. **
  140611. ** If an error occurs, this routine returns NULL.
  140612. **
  140613. ** The basic idea is to do a nested loop, one loop for each table in
  140614. ** the FROM clause of a select. (INSERT and UPDATE statements are the
  140615. ** same as a SELECT with only a single table in the FROM clause.) For
  140616. ** example, if the SQL is this:
  140617. **
  140618. ** SELECT * FROM t1, t2, t3 WHERE ...;
  140619. **
  140620. ** Then the code generated is conceptually like the following:
  140621. **
  140622. ** foreach row1 in t1 do \ Code generated
  140623. ** foreach row2 in t2 do |-- by sqlite3WhereBegin()
  140624. ** foreach row3 in t3 do /
  140625. ** ...
  140626. ** end \ Code generated
  140627. ** end |-- by sqlite3WhereEnd()
  140628. ** end /
  140629. **
  140630. ** Note that the loops might not be nested in the order in which they
  140631. ** appear in the FROM clause if a different order is better able to make
  140632. ** use of indices. Note also that when the IN operator appears in
  140633. ** the WHERE clause, it might result in additional nested loops for
  140634. ** scanning through all values on the right-hand side of the IN.
  140635. **
  140636. ** There are Btree cursors associated with each table. t1 uses cursor
  140637. ** number pTabList->a[0].iCursor. t2 uses the cursor pTabList->a[1].iCursor.
  140638. ** And so forth. This routine generates code to open those VDBE cursors
  140639. ** and sqlite3WhereEnd() generates the code to close them.
  140640. **
  140641. ** The code that sqlite3WhereBegin() generates leaves the cursors named
  140642. ** in pTabList pointing at their appropriate entries. The [...] code
  140643. ** can use OP_Column and OP_Rowid opcodes on these cursors to extract
  140644. ** data from the various tables of the loop.
  140645. **
  140646. ** If the WHERE clause is empty, the foreach loops must each scan their
  140647. ** entire tables. Thus a three-way join is an O(N^3) operation. But if
  140648. ** the tables have indices and there are terms in the WHERE clause that
  140649. ** refer to those indices, a complete table scan can be avoided and the
  140650. ** code will run much faster. Most of the work of this routine is checking
  140651. ** to see if there are indices that can be used to speed up the loop.
  140652. **
  140653. ** Terms of the WHERE clause are also used to limit which rows actually
  140654. ** make it to the "..." in the middle of the loop. After each "foreach",
  140655. ** terms of the WHERE clause that use only terms in that loop and outer
  140656. ** loops are evaluated and if false a jump is made around all subsequent
  140657. ** inner loops (or around the "..." if the test occurs within the inner-
  140658. ** most loop)
  140659. **
  140660. ** OUTER JOINS
  140661. **
  140662. ** An outer join of tables t1 and t2 is conceptally coded as follows:
  140663. **
  140664. ** foreach row1 in t1 do
  140665. ** flag = 0
  140666. ** foreach row2 in t2 do
  140667. ** start:
  140668. ** ...
  140669. ** flag = 1
  140670. ** end
  140671. ** if flag==0 then
  140672. ** move the row2 cursor to a null row
  140673. ** goto start
  140674. ** fi
  140675. ** end
  140676. **
  140677. ** ORDER BY CLAUSE PROCESSING
  140678. **
  140679. ** pOrderBy is a pointer to the ORDER BY clause (or the GROUP BY clause
  140680. ** if the WHERE_GROUPBY flag is set in wctrlFlags) of a SELECT statement
  140681. ** if there is one. If there is no ORDER BY clause or if this routine
  140682. ** is called from an UPDATE or DELETE statement, then pOrderBy is NULL.
  140683. **
  140684. ** The iIdxCur parameter is the cursor number of an index. If
  140685. ** WHERE_OR_SUBCLAUSE is set, iIdxCur is the cursor number of an index
  140686. ** to use for OR clause processing. The WHERE clause should use this
  140687. ** specific cursor. If WHERE_ONEPASS_DESIRED is set, then iIdxCur is
  140688. ** the first cursor in an array of cursors for all indices. iIdxCur should
  140689. ** be used to compute the appropriate cursor depending on which index is
  140690. ** used.
  140691. */
  140692. SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
  140693. Parse *pParse, /* The parser context */
  140694. SrcList *pTabList, /* FROM clause: A list of all tables to be scanned */
  140695. Expr *pWhere, /* The WHERE clause */
  140696. ExprList *pOrderBy, /* An ORDER BY (or GROUP BY) clause, or NULL */
  140697. ExprList *pResultSet, /* Query result set. Req'd for DISTINCT */
  140698. u16 wctrlFlags, /* The WHERE_* flags defined in sqliteInt.h */
  140699. int iAuxArg /* If WHERE_OR_SUBCLAUSE is set, index cursor number
  140700. ** If WHERE_USE_LIMIT, then the limit amount */
  140701. ){
  140702. int nByteWInfo; /* Num. bytes allocated for WhereInfo struct */
  140703. int nTabList; /* Number of elements in pTabList */
  140704. WhereInfo *pWInfo; /* Will become the return value of this function */
  140705. Vdbe *v = pParse->pVdbe; /* The virtual database engine */
  140706. Bitmask notReady; /* Cursors that are not yet positioned */
  140707. WhereLoopBuilder sWLB; /* The WhereLoop builder */
  140708. WhereMaskSet *pMaskSet; /* The expression mask set */
  140709. WhereLevel *pLevel; /* A single level in pWInfo->a[] */
  140710. WhereLoop *pLoop; /* Pointer to a single WhereLoop object */
  140711. int ii; /* Loop counter */
  140712. sqlite3 *db; /* Database connection */
  140713. int rc; /* Return code */
  140714. u8 bFordelete = 0; /* OPFLAG_FORDELETE or zero, as appropriate */
  140715. assert( (wctrlFlags & WHERE_ONEPASS_MULTIROW)==0 || (
  140716. (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0
  140717. && (wctrlFlags & WHERE_OR_SUBCLAUSE)==0
  140718. ));
  140719. /* Only one of WHERE_OR_SUBCLAUSE or WHERE_USE_LIMIT */
  140720. assert( (wctrlFlags & WHERE_OR_SUBCLAUSE)==0
  140721. || (wctrlFlags & WHERE_USE_LIMIT)==0 );
  140722. /* Variable initialization */
  140723. db = pParse->db;
  140724. memset(&sWLB, 0, sizeof(sWLB));
  140725. /* An ORDER/GROUP BY clause of more than 63 terms cannot be optimized */
  140726. testcase( pOrderBy && pOrderBy->nExpr==BMS-1 );
  140727. if( pOrderBy && pOrderBy->nExpr>=BMS ) pOrderBy = 0;
  140728. sWLB.pOrderBy = pOrderBy;
  140729. /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via
  140730. ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */
  140731. if( OptimizationDisabled(db, SQLITE_DistinctOpt) ){
  140732. wctrlFlags &= ~WHERE_WANT_DISTINCT;
  140733. }
  140734. /* The number of tables in the FROM clause is limited by the number of
  140735. ** bits in a Bitmask
  140736. */
  140737. testcase( pTabList->nSrc==BMS );
  140738. if( pTabList->nSrc>BMS ){
  140739. sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
  140740. return 0;
  140741. }
  140742. /* This function normally generates a nested loop for all tables in
  140743. ** pTabList. But if the WHERE_OR_SUBCLAUSE flag is set, then we should
  140744. ** only generate code for the first table in pTabList and assume that
  140745. ** any cursors associated with subsequent tables are uninitialized.
  140746. */
  140747. nTabList = (wctrlFlags & WHERE_OR_SUBCLAUSE) ? 1 : pTabList->nSrc;
  140748. /* Allocate and initialize the WhereInfo structure that will become the
  140749. ** return value. A single allocation is used to store the WhereInfo
  140750. ** struct, the contents of WhereInfo.a[], the WhereClause structure
  140751. ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
  140752. ** field (type Bitmask) it must be aligned on an 8-byte boundary on
  140753. ** some architectures. Hence the ROUND8() below.
  140754. */
  140755. nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
  140756. pWInfo = sqlite3DbMallocRawNN(db, nByteWInfo + sizeof(WhereLoop));
  140757. if( db->mallocFailed ){
  140758. sqlite3DbFree(db, pWInfo);
  140759. pWInfo = 0;
  140760. goto whereBeginError;
  140761. }
  140762. pWInfo->pParse = pParse;
  140763. pWInfo->pTabList = pTabList;
  140764. pWInfo->pOrderBy = pOrderBy;
  140765. pWInfo->pWhere = pWhere;
  140766. pWInfo->pResultSet = pResultSet;
  140767. pWInfo->aiCurOnePass[0] = pWInfo->aiCurOnePass[1] = -1;
  140768. pWInfo->nLevel = nTabList;
  140769. pWInfo->iBreak = pWInfo->iContinue = sqlite3VdbeMakeLabel(pParse);
  140770. pWInfo->wctrlFlags = wctrlFlags;
  140771. pWInfo->iLimit = iAuxArg;
  140772. pWInfo->savedNQueryLoop = pParse->nQueryLoop;
  140773. memset(&pWInfo->nOBSat, 0,
  140774. offsetof(WhereInfo,sWC) - offsetof(WhereInfo,nOBSat));
  140775. memset(&pWInfo->a[0], 0, sizeof(WhereLoop)+nTabList*sizeof(WhereLevel));
  140776. assert( pWInfo->eOnePass==ONEPASS_OFF ); /* ONEPASS defaults to OFF */
  140777. pMaskSet = &pWInfo->sMaskSet;
  140778. sWLB.pWInfo = pWInfo;
  140779. sWLB.pWC = &pWInfo->sWC;
  140780. sWLB.pNew = (WhereLoop*)(((char*)pWInfo)+nByteWInfo);
  140781. assert( EIGHT_BYTE_ALIGNMENT(sWLB.pNew) );
  140782. whereLoopInit(sWLB.pNew);
  140783. #ifdef SQLITE_DEBUG
  140784. sWLB.pNew->cId = '*';
  140785. #endif
  140786. /* Split the WHERE clause into separate subexpressions where each
  140787. ** subexpression is separated by an AND operator.
  140788. */
  140789. initMaskSet(pMaskSet);
  140790. sqlite3WhereClauseInit(&pWInfo->sWC, pWInfo);
  140791. sqlite3WhereSplit(&pWInfo->sWC, pWhere, TK_AND);
  140792. /* Special case: No FROM clause
  140793. */
  140794. if( nTabList==0 ){
  140795. if( pOrderBy ) pWInfo->nOBSat = pOrderBy->nExpr;
  140796. if( wctrlFlags & WHERE_WANT_DISTINCT ){
  140797. pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
  140798. }
  140799. ExplainQueryPlan((pParse, 0, "SCAN CONSTANT ROW"));
  140800. }else{
  140801. /* Assign a bit from the bitmask to every term in the FROM clause.
  140802. **
  140803. ** The N-th term of the FROM clause is assigned a bitmask of 1<<N.
  140804. **
  140805. ** The rule of the previous sentence ensures thta if X is the bitmask for
  140806. ** a table T, then X-1 is the bitmask for all other tables to the left of T.
  140807. ** Knowing the bitmask for all tables to the left of a left join is
  140808. ** important. Ticket #3015.
  140809. **
  140810. ** Note that bitmasks are created for all pTabList->nSrc tables in
  140811. ** pTabList, not just the first nTabList tables. nTabList is normally
  140812. ** equal to pTabList->nSrc but might be shortened to 1 if the
  140813. ** WHERE_OR_SUBCLAUSE flag is set.
  140814. */
  140815. ii = 0;
  140816. do{
  140817. createMask(pMaskSet, pTabList->a[ii].iCursor);
  140818. sqlite3WhereTabFuncArgs(pParse, &pTabList->a[ii], &pWInfo->sWC);
  140819. }while( (++ii)<pTabList->nSrc );
  140820. #ifdef SQLITE_DEBUG
  140821. {
  140822. Bitmask mx = 0;
  140823. for(ii=0; ii<pTabList->nSrc; ii++){
  140824. Bitmask m = sqlite3WhereGetMask(pMaskSet, pTabList->a[ii].iCursor);
  140825. assert( m>=mx );
  140826. mx = m;
  140827. }
  140828. }
  140829. #endif
  140830. }
  140831. /* Analyze all of the subexpressions. */
  140832. sqlite3WhereExprAnalyze(pTabList, &pWInfo->sWC);
  140833. if( db->mallocFailed ) goto whereBeginError;
  140834. /* Special case: WHERE terms that do not refer to any tables in the join
  140835. ** (constant expressions). Evaluate each such term, and jump over all the
  140836. ** generated code if the result is not true.
  140837. **
  140838. ** Do not do this if the expression contains non-deterministic functions
  140839. ** that are not within a sub-select. This is not strictly required, but
  140840. ** preserves SQLite's legacy behaviour in the following two cases:
  140841. **
  140842. ** FROM ... WHERE random()>0; -- eval random() once per row
  140843. ** FROM ... WHERE (SELECT random())>0; -- eval random() once overall
  140844. */
  140845. for(ii=0; ii<sWLB.pWC->nTerm; ii++){
  140846. WhereTerm *pT = &sWLB.pWC->a[ii];
  140847. if( pT->wtFlags & TERM_VIRTUAL ) continue;
  140848. if( pT->prereqAll==0 && (nTabList==0 || exprIsDeterministic(pT->pExpr)) ){
  140849. sqlite3ExprIfFalse(pParse, pT->pExpr, pWInfo->iBreak, SQLITE_JUMPIFNULL);
  140850. pT->wtFlags |= TERM_CODED;
  140851. }
  140852. }
  140853. if( wctrlFlags & WHERE_WANT_DISTINCT ){
  140854. if( isDistinctRedundant(pParse, pTabList, &pWInfo->sWC, pResultSet) ){
  140855. /* The DISTINCT marking is pointless. Ignore it. */
  140856. pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
  140857. }else if( pOrderBy==0 ){
  140858. /* Try to ORDER BY the result set to make distinct processing easier */
  140859. pWInfo->wctrlFlags |= WHERE_DISTINCTBY;
  140860. pWInfo->pOrderBy = pResultSet;
  140861. }
  140862. }
  140863. /* Construct the WhereLoop objects */
  140864. #if defined(WHERETRACE_ENABLED)
  140865. if( sqlite3WhereTrace & 0xffff ){
  140866. sqlite3DebugPrintf("*** Optimizer Start *** (wctrlFlags: 0x%x",wctrlFlags);
  140867. if( wctrlFlags & WHERE_USE_LIMIT ){
  140868. sqlite3DebugPrintf(", limit: %d", iAuxArg);
  140869. }
  140870. sqlite3DebugPrintf(")\n");
  140871. if( sqlite3WhereTrace & 0x100 ){
  140872. Select sSelect;
  140873. memset(&sSelect, 0, sizeof(sSelect));
  140874. sSelect.selFlags = SF_WhereBegin;
  140875. sSelect.pSrc = pTabList;
  140876. sSelect.pWhere = pWhere;
  140877. sSelect.pOrderBy = pOrderBy;
  140878. sSelect.pEList = pResultSet;
  140879. sqlite3TreeViewSelect(0, &sSelect, 0);
  140880. }
  140881. }
  140882. if( sqlite3WhereTrace & 0x100 ){ /* Display all terms of the WHERE clause */
  140883. sqlite3DebugPrintf("---- WHERE clause at start of analysis:\n");
  140884. sqlite3WhereClausePrint(sWLB.pWC);
  140885. }
  140886. #endif
  140887. if( nTabList!=1 || whereShortCut(&sWLB)==0 ){
  140888. rc = whereLoopAddAll(&sWLB);
  140889. if( rc ) goto whereBeginError;
  140890. #ifdef SQLITE_ENABLE_STAT4
  140891. /* If one or more WhereTerm.truthProb values were used in estimating
  140892. ** loop parameters, but then those truthProb values were subsequently
  140893. ** changed based on STAT4 information while computing subsequent loops,
  140894. ** then we need to rerun the whole loop building process so that all
  140895. ** loops will be built using the revised truthProb values. */
  140896. if( sWLB.bldFlags2 & SQLITE_BLDF2_2NDPASS ){
  140897. WHERETRACE_ALL_LOOPS(pWInfo, sWLB.pWC);
  140898. WHERETRACE(0xffff,
  140899. ("**** Redo all loop computations due to"
  140900. " TERM_HIGHTRUTH changes ****\n"));
  140901. while( pWInfo->pLoops ){
  140902. WhereLoop *p = pWInfo->pLoops;
  140903. pWInfo->pLoops = p->pNextLoop;
  140904. whereLoopDelete(db, p);
  140905. }
  140906. rc = whereLoopAddAll(&sWLB);
  140907. if( rc ) goto whereBeginError;
  140908. }
  140909. #endif
  140910. WHERETRACE_ALL_LOOPS(pWInfo, sWLB.pWC);
  140911. wherePathSolver(pWInfo, 0);
  140912. if( db->mallocFailed ) goto whereBeginError;
  140913. if( pWInfo->pOrderBy ){
  140914. wherePathSolver(pWInfo, pWInfo->nRowOut+1);
  140915. if( db->mallocFailed ) goto whereBeginError;
  140916. }
  140917. }
  140918. if( pWInfo->pOrderBy==0 && (db->flags & SQLITE_ReverseOrder)!=0 ){
  140919. pWInfo->revMask = ALLBITS;
  140920. }
  140921. if( pParse->nErr || NEVER(db->mallocFailed) ){
  140922. goto whereBeginError;
  140923. }
  140924. #ifdef WHERETRACE_ENABLED
  140925. if( sqlite3WhereTrace ){
  140926. sqlite3DebugPrintf("---- Solution nRow=%d", pWInfo->nRowOut);
  140927. if( pWInfo->nOBSat>0 ){
  140928. sqlite3DebugPrintf(" ORDERBY=%d,0x%llx", pWInfo->nOBSat, pWInfo->revMask);
  140929. }
  140930. switch( pWInfo->eDistinct ){
  140931. case WHERE_DISTINCT_UNIQUE: {
  140932. sqlite3DebugPrintf(" DISTINCT=unique");
  140933. break;
  140934. }
  140935. case WHERE_DISTINCT_ORDERED: {
  140936. sqlite3DebugPrintf(" DISTINCT=ordered");
  140937. break;
  140938. }
  140939. case WHERE_DISTINCT_UNORDERED: {
  140940. sqlite3DebugPrintf(" DISTINCT=unordered");
  140941. break;
  140942. }
  140943. }
  140944. sqlite3DebugPrintf("\n");
  140945. for(ii=0; ii<pWInfo->nLevel; ii++){
  140946. sqlite3WhereLoopPrint(pWInfo->a[ii].pWLoop, sWLB.pWC);
  140947. }
  140948. }
  140949. #endif
  140950. /* Attempt to omit tables from the join that do not affect the result.
  140951. ** For a table to not affect the result, the following must be true:
  140952. **
  140953. ** 1) The query must not be an aggregate.
  140954. ** 2) The table must be the RHS of a LEFT JOIN.
  140955. ** 3) Either the query must be DISTINCT, or else the ON or USING clause
  140956. ** must contain a constraint that limits the scan of the table to
  140957. ** at most a single row.
  140958. ** 4) The table must not be referenced by any part of the query apart
  140959. ** from its own USING or ON clause.
  140960. **
  140961. ** For example, given:
  140962. **
  140963. ** CREATE TABLE t1(ipk INTEGER PRIMARY KEY, v1);
  140964. ** CREATE TABLE t2(ipk INTEGER PRIMARY KEY, v2);
  140965. ** CREATE TABLE t3(ipk INTEGER PRIMARY KEY, v3);
  140966. **
  140967. ** then table t2 can be omitted from the following:
  140968. **
  140969. ** SELECT v1, v3 FROM t1
  140970. ** LEFT JOIN t2 ON (t1.ipk=t2.ipk)
  140971. ** LEFT JOIN t3 ON (t1.ipk=t3.ipk)
  140972. **
  140973. ** or from:
  140974. **
  140975. ** SELECT DISTINCT v1, v3 FROM t1
  140976. ** LEFT JOIN t2
  140977. ** LEFT JOIN t3 ON (t1.ipk=t3.ipk)
  140978. */
  140979. notReady = ~(Bitmask)0;
  140980. if( pWInfo->nLevel>=2
  140981. && pResultSet!=0 /* guarantees condition (1) above */
  140982. && OptimizationEnabled(db, SQLITE_OmitNoopJoin)
  140983. ){
  140984. int i;
  140985. Bitmask tabUsed = sqlite3WhereExprListUsage(pMaskSet, pResultSet);
  140986. if( sWLB.pOrderBy ){
  140987. tabUsed |= sqlite3WhereExprListUsage(pMaskSet, sWLB.pOrderBy);
  140988. }
  140989. for(i=pWInfo->nLevel-1; i>=1; i--){
  140990. WhereTerm *pTerm, *pEnd;
  140991. struct SrcList_item *pItem;
  140992. pLoop = pWInfo->a[i].pWLoop;
  140993. pItem = &pWInfo->pTabList->a[pLoop->iTab];
  140994. if( (pItem->fg.jointype & JT_LEFT)==0 ) continue;
  140995. if( (wctrlFlags & WHERE_WANT_DISTINCT)==0
  140996. && (pLoop->wsFlags & WHERE_ONEROW)==0
  140997. ){
  140998. continue;
  140999. }
  141000. if( (tabUsed & pLoop->maskSelf)!=0 ) continue;
  141001. pEnd = sWLB.pWC->a + sWLB.pWC->nTerm;
  141002. for(pTerm=sWLB.pWC->a; pTerm<pEnd; pTerm++){
  141003. if( (pTerm->prereqAll & pLoop->maskSelf)!=0 ){
  141004. if( !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
  141005. || pTerm->pExpr->iRightJoinTable!=pItem->iCursor
  141006. ){
  141007. break;
  141008. }
  141009. }
  141010. }
  141011. if( pTerm<pEnd ) continue;
  141012. WHERETRACE(0xffff, ("-> drop loop %c not used\n", pLoop->cId));
  141013. notReady &= ~pLoop->maskSelf;
  141014. for(pTerm=sWLB.pWC->a; pTerm<pEnd; pTerm++){
  141015. if( (pTerm->prereqAll & pLoop->maskSelf)!=0 ){
  141016. pTerm->wtFlags |= TERM_CODED;
  141017. }
  141018. }
  141019. if( i!=pWInfo->nLevel-1 ){
  141020. int nByte = (pWInfo->nLevel-1-i) * sizeof(WhereLevel);
  141021. memmove(&pWInfo->a[i], &pWInfo->a[i+1], nByte);
  141022. }
  141023. pWInfo->nLevel--;
  141024. nTabList--;
  141025. }
  141026. }
  141027. #if defined(WHERETRACE_ENABLED)
  141028. if( sqlite3WhereTrace & 0x100 ){ /* Display all terms of the WHERE clause */
  141029. sqlite3DebugPrintf("---- WHERE clause at end of analysis:\n");
  141030. sqlite3WhereClausePrint(sWLB.pWC);
  141031. }
  141032. WHERETRACE(0xffff,("*** Optimizer Finished ***\n"));
  141033. #endif
  141034. pWInfo->pParse->nQueryLoop += pWInfo->nRowOut;
  141035. /* If the caller is an UPDATE or DELETE statement that is requesting
  141036. ** to use a one-pass algorithm, determine if this is appropriate.
  141037. **
  141038. ** A one-pass approach can be used if the caller has requested one
  141039. ** and either (a) the scan visits at most one row or (b) each
  141040. ** of the following are true:
  141041. **
  141042. ** * the caller has indicated that a one-pass approach can be used
  141043. ** with multiple rows (by setting WHERE_ONEPASS_MULTIROW), and
  141044. ** * the table is not a virtual table, and
  141045. ** * either the scan does not use the OR optimization or the caller
  141046. ** is a DELETE operation (WHERE_DUPLICATES_OK is only specified
  141047. ** for DELETE).
  141048. **
  141049. ** The last qualification is because an UPDATE statement uses
  141050. ** WhereInfo.aiCurOnePass[1] to determine whether or not it really can
  141051. ** use a one-pass approach, and this is not set accurately for scans
  141052. ** that use the OR optimization.
  141053. */
  141054. assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
  141055. if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 ){
  141056. int wsFlags = pWInfo->a[0].pWLoop->wsFlags;
  141057. int bOnerow = (wsFlags & WHERE_ONEROW)!=0;
  141058. assert( !(wsFlags & WHERE_VIRTUALTABLE) || IsVirtual(pTabList->a[0].pTab) );
  141059. if( bOnerow || (
  141060. 0!=(wctrlFlags & WHERE_ONEPASS_MULTIROW)
  141061. && !IsVirtual(pTabList->a[0].pTab)
  141062. && (0==(wsFlags & WHERE_MULTI_OR) || (wctrlFlags & WHERE_DUPLICATES_OK))
  141063. )){
  141064. pWInfo->eOnePass = bOnerow ? ONEPASS_SINGLE : ONEPASS_MULTI;
  141065. if( HasRowid(pTabList->a[0].pTab) && (wsFlags & WHERE_IDX_ONLY) ){
  141066. if( wctrlFlags & WHERE_ONEPASS_MULTIROW ){
  141067. bFordelete = OPFLAG_FORDELETE;
  141068. }
  141069. pWInfo->a[0].pWLoop->wsFlags = (wsFlags & ~WHERE_IDX_ONLY);
  141070. }
  141071. }
  141072. }
  141073. /* Open all tables in the pTabList and any indices selected for
  141074. ** searching those tables.
  141075. */
  141076. for(ii=0, pLevel=pWInfo->a; ii<nTabList; ii++, pLevel++){
  141077. Table *pTab; /* Table to open */
  141078. int iDb; /* Index of database containing table/index */
  141079. struct SrcList_item *pTabItem;
  141080. pTabItem = &pTabList->a[pLevel->iFrom];
  141081. pTab = pTabItem->pTab;
  141082. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  141083. pLoop = pLevel->pWLoop;
  141084. if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
  141085. /* Do nothing */
  141086. }else
  141087. #ifndef SQLITE_OMIT_VIRTUALTABLE
  141088. if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
  141089. const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
  141090. int iCur = pTabItem->iCursor;
  141091. sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
  141092. }else if( IsVirtual(pTab) ){
  141093. /* noop */
  141094. }else
  141095. #endif
  141096. if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
  141097. && (wctrlFlags & WHERE_OR_SUBCLAUSE)==0 ){
  141098. int op = OP_OpenRead;
  141099. if( pWInfo->eOnePass!=ONEPASS_OFF ){
  141100. op = OP_OpenWrite;
  141101. pWInfo->aiCurOnePass[0] = pTabItem->iCursor;
  141102. };
  141103. sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
  141104. assert( pTabItem->iCursor==pLevel->iTabCur );
  141105. testcase( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol==BMS-1 );
  141106. testcase( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol==BMS );
  141107. if( pWInfo->eOnePass==ONEPASS_OFF
  141108. && pTab->nCol<BMS
  141109. && (pTab->tabFlags & (TF_HasGenerated|TF_WithoutRowid))==0
  141110. ){
  141111. /* If we know that only a prefix of the record will be used,
  141112. ** it is advantageous to reduce the "column count" field in
  141113. ** the P4 operand of the OP_OpenRead/Write opcode. */
  141114. Bitmask b = pTabItem->colUsed;
  141115. int n = 0;
  141116. for(; b; b=b>>1, n++){}
  141117. sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(n), P4_INT32);
  141118. assert( n<=pTab->nCol );
  141119. }
  141120. #ifdef SQLITE_ENABLE_CURSOR_HINTS
  141121. if( pLoop->u.btree.pIndex!=0 ){
  141122. sqlite3VdbeChangeP5(v, OPFLAG_SEEKEQ|bFordelete);
  141123. }else
  141124. #endif
  141125. {
  141126. sqlite3VdbeChangeP5(v, bFordelete);
  141127. }
  141128. #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
  141129. sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, pTabItem->iCursor, 0, 0,
  141130. (const u8*)&pTabItem->colUsed, P4_INT64);
  141131. #endif
  141132. }else{
  141133. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  141134. }
  141135. if( pLoop->wsFlags & WHERE_INDEXED ){
  141136. Index *pIx = pLoop->u.btree.pIndex;
  141137. int iIndexCur;
  141138. int op = OP_OpenRead;
  141139. /* iAuxArg is always set to a positive value if ONEPASS is possible */
  141140. assert( iAuxArg!=0 || (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 );
  141141. if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIx)
  141142. && (wctrlFlags & WHERE_OR_SUBCLAUSE)!=0
  141143. ){
  141144. /* This is one term of an OR-optimization using the PRIMARY KEY of a
  141145. ** WITHOUT ROWID table. No need for a separate index */
  141146. iIndexCur = pLevel->iTabCur;
  141147. op = 0;
  141148. }else if( pWInfo->eOnePass!=ONEPASS_OFF ){
  141149. Index *pJ = pTabItem->pTab->pIndex;
  141150. iIndexCur = iAuxArg;
  141151. assert( wctrlFlags & WHERE_ONEPASS_DESIRED );
  141152. while( ALWAYS(pJ) && pJ!=pIx ){
  141153. iIndexCur++;
  141154. pJ = pJ->pNext;
  141155. }
  141156. op = OP_OpenWrite;
  141157. pWInfo->aiCurOnePass[1] = iIndexCur;
  141158. }else if( iAuxArg && (wctrlFlags & WHERE_OR_SUBCLAUSE)!=0 ){
  141159. iIndexCur = iAuxArg;
  141160. op = OP_ReopenIdx;
  141161. }else{
  141162. iIndexCur = pParse->nTab++;
  141163. }
  141164. pLevel->iIdxCur = iIndexCur;
  141165. assert( pIx->pSchema==pTab->pSchema );
  141166. assert( iIndexCur>=0 );
  141167. if( op ){
  141168. sqlite3VdbeAddOp3(v, op, iIndexCur, pIx->tnum, iDb);
  141169. sqlite3VdbeSetP4KeyInfo(pParse, pIx);
  141170. if( (pLoop->wsFlags & WHERE_CONSTRAINT)!=0
  141171. && (pLoop->wsFlags & (WHERE_COLUMN_RANGE|WHERE_SKIPSCAN))==0
  141172. && (pLoop->wsFlags & WHERE_BIGNULL_SORT)==0
  141173. && (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0
  141174. && pWInfo->eDistinct!=WHERE_DISTINCT_ORDERED
  141175. ){
  141176. sqlite3VdbeChangeP5(v, OPFLAG_SEEKEQ);
  141177. }
  141178. VdbeComment((v, "%s", pIx->zName));
  141179. #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
  141180. {
  141181. u64 colUsed = 0;
  141182. int ii, jj;
  141183. for(ii=0; ii<pIx->nColumn; ii++){
  141184. jj = pIx->aiColumn[ii];
  141185. if( jj<0 ) continue;
  141186. if( jj>63 ) jj = 63;
  141187. if( (pTabItem->colUsed & MASKBIT(jj))==0 ) continue;
  141188. colUsed |= ((u64)1)<<(ii<63 ? ii : 63);
  141189. }
  141190. sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, iIndexCur, 0, 0,
  141191. (u8*)&colUsed, P4_INT64);
  141192. }
  141193. #endif /* SQLITE_ENABLE_COLUMN_USED_MASK */
  141194. }
  141195. }
  141196. if( iDb>=0 ) sqlite3CodeVerifySchema(pParse, iDb);
  141197. }
  141198. pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
  141199. if( db->mallocFailed ) goto whereBeginError;
  141200. /* Generate the code to do the search. Each iteration of the for
  141201. ** loop below generates code for a single nested loop of the VM
  141202. ** program.
  141203. */
  141204. for(ii=0; ii<nTabList; ii++){
  141205. int addrExplain;
  141206. int wsFlags;
  141207. pLevel = &pWInfo->a[ii];
  141208. wsFlags = pLevel->pWLoop->wsFlags;
  141209. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  141210. if( (pLevel->pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 ){
  141211. constructAutomaticIndex(pParse, &pWInfo->sWC,
  141212. &pTabList->a[pLevel->iFrom], notReady, pLevel);
  141213. if( db->mallocFailed ) goto whereBeginError;
  141214. }
  141215. #endif
  141216. addrExplain = sqlite3WhereExplainOneScan(
  141217. pParse, pTabList, pLevel, wctrlFlags
  141218. );
  141219. pLevel->addrBody = sqlite3VdbeCurrentAddr(v);
  141220. notReady = sqlite3WhereCodeOneLoopStart(pParse,v,pWInfo,ii,pLevel,notReady);
  141221. pWInfo->iContinue = pLevel->addrCont;
  141222. if( (wsFlags&WHERE_MULTI_OR)==0 && (wctrlFlags&WHERE_OR_SUBCLAUSE)==0 ){
  141223. sqlite3WhereAddScanStatus(v, pTabList, pLevel, addrExplain);
  141224. }
  141225. }
  141226. /* Done. */
  141227. VdbeModuleComment((v, "Begin WHERE-core"));
  141228. return pWInfo;
  141229. /* Jump here if malloc fails */
  141230. whereBeginError:
  141231. if( pWInfo ){
  141232. pParse->nQueryLoop = pWInfo->savedNQueryLoop;
  141233. whereInfoFree(db, pWInfo);
  141234. }
  141235. return 0;
  141236. }
  141237. /*
  141238. ** Part of sqlite3WhereEnd() will rewrite opcodes to reference the
  141239. ** index rather than the main table. In SQLITE_DEBUG mode, we want
  141240. ** to trace those changes if PRAGMA vdbe_addoptrace=on. This routine
  141241. ** does that.
  141242. */
  141243. #ifndef SQLITE_DEBUG
  141244. # define OpcodeRewriteTrace(D,K,P) /* no-op */
  141245. #else
  141246. # define OpcodeRewriteTrace(D,K,P) sqlite3WhereOpcodeRewriteTrace(D,K,P)
  141247. static void sqlite3WhereOpcodeRewriteTrace(
  141248. sqlite3 *db,
  141249. int pc,
  141250. VdbeOp *pOp
  141251. ){
  141252. if( (db->flags & SQLITE_VdbeAddopTrace)==0 ) return;
  141253. sqlite3VdbePrintOp(0, pc, pOp);
  141254. }
  141255. #endif
  141256. /*
  141257. ** Generate the end of the WHERE loop. See comments on
  141258. ** sqlite3WhereBegin() for additional information.
  141259. */
  141260. SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
  141261. Parse *pParse = pWInfo->pParse;
  141262. Vdbe *v = pParse->pVdbe;
  141263. int i;
  141264. WhereLevel *pLevel;
  141265. WhereLoop *pLoop;
  141266. SrcList *pTabList = pWInfo->pTabList;
  141267. sqlite3 *db = pParse->db;
  141268. /* Generate loop termination code.
  141269. */
  141270. VdbeModuleComment((v, "End WHERE-core"));
  141271. for(i=pWInfo->nLevel-1; i>=0; i--){
  141272. int addr;
  141273. pLevel = &pWInfo->a[i];
  141274. pLoop = pLevel->pWLoop;
  141275. if( pLevel->op!=OP_Noop ){
  141276. #ifndef SQLITE_DISABLE_SKIPAHEAD_DISTINCT
  141277. int addrSeek = 0;
  141278. Index *pIdx;
  141279. int n;
  141280. if( pWInfo->eDistinct==WHERE_DISTINCT_ORDERED
  141281. && i==pWInfo->nLevel-1 /* Ticket [ef9318757b152e3] 2017-10-21 */
  141282. && (pLoop->wsFlags & WHERE_INDEXED)!=0
  141283. && (pIdx = pLoop->u.btree.pIndex)->hasStat1
  141284. && (n = pLoop->u.btree.nDistinctCol)>0
  141285. && pIdx->aiRowLogEst[n]>=36
  141286. ){
  141287. int r1 = pParse->nMem+1;
  141288. int j, op;
  141289. for(j=0; j<n; j++){
  141290. sqlite3VdbeAddOp3(v, OP_Column, pLevel->iIdxCur, j, r1+j);
  141291. }
  141292. pParse->nMem += n+1;
  141293. op = pLevel->op==OP_Prev ? OP_SeekLT : OP_SeekGT;
  141294. addrSeek = sqlite3VdbeAddOp4Int(v, op, pLevel->iIdxCur, 0, r1, n);
  141295. VdbeCoverageIf(v, op==OP_SeekLT);
  141296. VdbeCoverageIf(v, op==OP_SeekGT);
  141297. sqlite3VdbeAddOp2(v, OP_Goto, 1, pLevel->p2);
  141298. }
  141299. #endif /* SQLITE_DISABLE_SKIPAHEAD_DISTINCT */
  141300. /* The common case: Advance to the next row */
  141301. sqlite3VdbeResolveLabel(v, pLevel->addrCont);
  141302. sqlite3VdbeAddOp3(v, pLevel->op, pLevel->p1, pLevel->p2, pLevel->p3);
  141303. sqlite3VdbeChangeP5(v, pLevel->p5);
  141304. VdbeCoverage(v);
  141305. VdbeCoverageIf(v, pLevel->op==OP_Next);
  141306. VdbeCoverageIf(v, pLevel->op==OP_Prev);
  141307. VdbeCoverageIf(v, pLevel->op==OP_VNext);
  141308. if( pLevel->regBignull ){
  141309. sqlite3VdbeResolveLabel(v, pLevel->addrBignull);
  141310. sqlite3VdbeAddOp2(v, OP_DecrJumpZero, pLevel->regBignull, pLevel->p2-1);
  141311. VdbeCoverage(v);
  141312. }
  141313. #ifndef SQLITE_DISABLE_SKIPAHEAD_DISTINCT
  141314. if( addrSeek ) sqlite3VdbeJumpHere(v, addrSeek);
  141315. #endif
  141316. }else{
  141317. sqlite3VdbeResolveLabel(v, pLevel->addrCont);
  141318. }
  141319. if( pLoop->wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
  141320. struct InLoop *pIn;
  141321. int j;
  141322. sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
  141323. for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
  141324. sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
  141325. if( pIn->eEndLoopOp!=OP_Noop ){
  141326. if( pIn->nPrefix ){
  141327. assert( pLoop->wsFlags & WHERE_IN_EARLYOUT );
  141328. if( pLevel->iLeftJoin ){
  141329. /* For LEFT JOIN queries, cursor pIn->iCur may not have been
  141330. ** opened yet. This occurs for WHERE clauses such as
  141331. ** "a = ? AND b IN (...)", where the index is on (a, b). If
  141332. ** the RHS of the (a=?) is NULL, then the "b IN (...)" may
  141333. ** never have been coded, but the body of the loop run to
  141334. ** return the null-row. So, if the cursor is not open yet,
  141335. ** jump over the OP_Next or OP_Prev instruction about to
  141336. ** be coded. */
  141337. sqlite3VdbeAddOp2(v, OP_IfNotOpen, pIn->iCur,
  141338. sqlite3VdbeCurrentAddr(v) + 2 +
  141339. ((pLoop->wsFlags & WHERE_VIRTUALTABLE)==0)
  141340. );
  141341. VdbeCoverage(v);
  141342. }
  141343. if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 ){
  141344. sqlite3VdbeAddOp4Int(v, OP_IfNoHope, pLevel->iIdxCur,
  141345. sqlite3VdbeCurrentAddr(v)+2,
  141346. pIn->iBase, pIn->nPrefix);
  141347. VdbeCoverage(v);
  141348. }
  141349. }
  141350. sqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop);
  141351. VdbeCoverage(v);
  141352. VdbeCoverageIf(v, pIn->eEndLoopOp==OP_Prev);
  141353. VdbeCoverageIf(v, pIn->eEndLoopOp==OP_Next);
  141354. }
  141355. sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
  141356. }
  141357. }
  141358. sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
  141359. if( pLevel->addrSkip ){
  141360. sqlite3VdbeGoto(v, pLevel->addrSkip);
  141361. VdbeComment((v, "next skip-scan on %s", pLoop->u.btree.pIndex->zName));
  141362. sqlite3VdbeJumpHere(v, pLevel->addrSkip);
  141363. sqlite3VdbeJumpHere(v, pLevel->addrSkip-2);
  141364. }
  141365. #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
  141366. if( pLevel->addrLikeRep ){
  141367. sqlite3VdbeAddOp2(v, OP_DecrJumpZero, (int)(pLevel->iLikeRepCntr>>1),
  141368. pLevel->addrLikeRep);
  141369. VdbeCoverage(v);
  141370. }
  141371. #endif
  141372. if( pLevel->iLeftJoin ){
  141373. int ws = pLoop->wsFlags;
  141374. addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin); VdbeCoverage(v);
  141375. assert( (ws & WHERE_IDX_ONLY)==0 || (ws & WHERE_INDEXED)!=0 );
  141376. if( (ws & WHERE_IDX_ONLY)==0 ){
  141377. assert( pLevel->iTabCur==pTabList->a[pLevel->iFrom].iCursor );
  141378. sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iTabCur);
  141379. }
  141380. if( (ws & WHERE_INDEXED)
  141381. || ((ws & WHERE_MULTI_OR) && pLevel->u.pCovidx)
  141382. ){
  141383. sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
  141384. }
  141385. if( pLevel->op==OP_Return ){
  141386. sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
  141387. }else{
  141388. sqlite3VdbeGoto(v, pLevel->addrFirst);
  141389. }
  141390. sqlite3VdbeJumpHere(v, addr);
  141391. }
  141392. VdbeModuleComment((v, "End WHERE-loop%d: %s", i,
  141393. pWInfo->pTabList->a[pLevel->iFrom].pTab->zName));
  141394. }
  141395. /* The "break" point is here, just past the end of the outer loop.
  141396. ** Set it.
  141397. */
  141398. sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
  141399. assert( pWInfo->nLevel<=pTabList->nSrc );
  141400. for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
  141401. int k, last;
  141402. VdbeOp *pOp;
  141403. Index *pIdx = 0;
  141404. struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
  141405. Table *pTab = pTabItem->pTab;
  141406. assert( pTab!=0 );
  141407. pLoop = pLevel->pWLoop;
  141408. /* For a co-routine, change all OP_Column references to the table of
  141409. ** the co-routine into OP_Copy of result contained in a register.
  141410. ** OP_Rowid becomes OP_Null.
  141411. */
  141412. if( pTabItem->fg.viaCoroutine ){
  141413. testcase( pParse->db->mallocFailed );
  141414. translateColumnToCopy(pParse, pLevel->addrBody, pLevel->iTabCur,
  141415. pTabItem->regResult, 0);
  141416. continue;
  141417. }
  141418. #ifdef SQLITE_ENABLE_EARLY_CURSOR_CLOSE
  141419. /* Close all of the cursors that were opened by sqlite3WhereBegin.
  141420. ** Except, do not close cursors that will be reused by the OR optimization
  141421. ** (WHERE_OR_SUBCLAUSE). And do not close the OP_OpenWrite cursors
  141422. ** created for the ONEPASS optimization.
  141423. */
  141424. if( (pTab->tabFlags & TF_Ephemeral)==0
  141425. && pTab->pSelect==0
  141426. && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)==0
  141427. ){
  141428. int ws = pLoop->wsFlags;
  141429. if( pWInfo->eOnePass==ONEPASS_OFF && (ws & WHERE_IDX_ONLY)==0 ){
  141430. sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
  141431. }
  141432. if( (ws & WHERE_INDEXED)!=0
  141433. && (ws & (WHERE_IPK|WHERE_AUTO_INDEX))==0
  141434. && pLevel->iIdxCur!=pWInfo->aiCurOnePass[1]
  141435. ){
  141436. sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
  141437. }
  141438. }
  141439. #endif
  141440. /* If this scan uses an index, make VDBE code substitutions to read data
  141441. ** from the index instead of from the table where possible. In some cases
  141442. ** this optimization prevents the table from ever being read, which can
  141443. ** yield a significant performance boost.
  141444. **
  141445. ** Calls to the code generator in between sqlite3WhereBegin and
  141446. ** sqlite3WhereEnd will have created code that references the table
  141447. ** directly. This loop scans all that code looking for opcodes
  141448. ** that reference the table and converts them into opcodes that
  141449. ** reference the index.
  141450. */
  141451. if( pLoop->wsFlags & (WHERE_INDEXED|WHERE_IDX_ONLY) ){
  141452. pIdx = pLoop->u.btree.pIndex;
  141453. }else if( pLoop->wsFlags & WHERE_MULTI_OR ){
  141454. pIdx = pLevel->u.pCovidx;
  141455. }
  141456. if( pIdx
  141457. && (pWInfo->eOnePass==ONEPASS_OFF || !HasRowid(pIdx->pTable))
  141458. && !db->mallocFailed
  141459. ){
  141460. last = sqlite3VdbeCurrentAddr(v);
  141461. k = pLevel->addrBody;
  141462. #ifdef SQLITE_DEBUG
  141463. if( db->flags & SQLITE_VdbeAddopTrace ){
  141464. printf("TRANSLATE opcodes in range %d..%d\n", k, last-1);
  141465. }
  141466. #endif
  141467. pOp = sqlite3VdbeGetOp(v, k);
  141468. for(; k<last; k++, pOp++){
  141469. if( pOp->p1!=pLevel->iTabCur ) continue;
  141470. if( pOp->opcode==OP_Column
  141471. #ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
  141472. || pOp->opcode==OP_Offset
  141473. #endif
  141474. ){
  141475. int x = pOp->p2;
  141476. assert( pIdx->pTable==pTab );
  141477. if( !HasRowid(pTab) ){
  141478. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  141479. x = pPk->aiColumn[x];
  141480. assert( x>=0 );
  141481. }else{
  141482. testcase( x!=sqlite3StorageColumnToTable(pTab,x) );
  141483. x = sqlite3StorageColumnToTable(pTab,x);
  141484. }
  141485. x = sqlite3TableColumnToIndex(pIdx, x);
  141486. if( x>=0 ){
  141487. pOp->p2 = x;
  141488. pOp->p1 = pLevel->iIdxCur;
  141489. OpcodeRewriteTrace(db, k, pOp);
  141490. }
  141491. assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 || x>=0
  141492. || pWInfo->eOnePass );
  141493. }else if( pOp->opcode==OP_Rowid ){
  141494. pOp->p1 = pLevel->iIdxCur;
  141495. pOp->opcode = OP_IdxRowid;
  141496. OpcodeRewriteTrace(db, k, pOp);
  141497. }else if( pOp->opcode==OP_IfNullRow ){
  141498. pOp->p1 = pLevel->iIdxCur;
  141499. OpcodeRewriteTrace(db, k, pOp);
  141500. }
  141501. }
  141502. #ifdef SQLITE_DEBUG
  141503. if( db->flags & SQLITE_VdbeAddopTrace ) printf("TRANSLATE complete\n");
  141504. #endif
  141505. }
  141506. }
  141507. /* Undo all Expr node modifications */
  141508. while( pWInfo->pExprMods ){
  141509. WhereExprMod *p = pWInfo->pExprMods;
  141510. pWInfo->pExprMods = p->pNext;
  141511. memcpy(p->pExpr, &p->orig, sizeof(p->orig));
  141512. sqlite3DbFree(db, p);
  141513. }
  141514. /* Final cleanup
  141515. */
  141516. pParse->nQueryLoop = pWInfo->savedNQueryLoop;
  141517. whereInfoFree(db, pWInfo);
  141518. return;
  141519. }
  141520. /************** End of where.c ***********************************************/
  141521. /************** Begin file window.c ******************************************/
  141522. /*
  141523. ** 2018 May 08
  141524. **
  141525. ** The author disclaims copyright to this source code. In place of
  141526. ** a legal notice, here is a blessing:
  141527. **
  141528. ** May you do good and not evil.
  141529. ** May you find forgiveness for yourself and forgive others.
  141530. ** May you share freely, never taking more than you give.
  141531. **
  141532. *************************************************************************
  141533. */
  141534. /* #include "sqliteInt.h" */
  141535. #ifndef SQLITE_OMIT_WINDOWFUNC
  141536. /*
  141537. ** SELECT REWRITING
  141538. **
  141539. ** Any SELECT statement that contains one or more window functions in
  141540. ** either the select list or ORDER BY clause (the only two places window
  141541. ** functions may be used) is transformed by function sqlite3WindowRewrite()
  141542. ** in order to support window function processing. For example, with the
  141543. ** schema:
  141544. **
  141545. ** CREATE TABLE t1(a, b, c, d, e, f, g);
  141546. **
  141547. ** the statement:
  141548. **
  141549. ** SELECT a+1, max(b) OVER (PARTITION BY c ORDER BY d) FROM t1 ORDER BY e;
  141550. **
  141551. ** is transformed to:
  141552. **
  141553. ** SELECT a+1, max(b) OVER (PARTITION BY c ORDER BY d) FROM (
  141554. ** SELECT a, e, c, d, b FROM t1 ORDER BY c, d
  141555. ** ) ORDER BY e;
  141556. **
  141557. ** The flattening optimization is disabled when processing this transformed
  141558. ** SELECT statement. This allows the implementation of the window function
  141559. ** (in this case max()) to process rows sorted in order of (c, d), which
  141560. ** makes things easier for obvious reasons. More generally:
  141561. **
  141562. ** * FROM, WHERE, GROUP BY and HAVING clauses are all moved to
  141563. ** the sub-query.
  141564. **
  141565. ** * ORDER BY, LIMIT and OFFSET remain part of the parent query.
  141566. **
  141567. ** * Terminals from each of the expression trees that make up the
  141568. ** select-list and ORDER BY expressions in the parent query are
  141569. ** selected by the sub-query. For the purposes of the transformation,
  141570. ** terminals are column references and aggregate functions.
  141571. **
  141572. ** If there is more than one window function in the SELECT that uses
  141573. ** the same window declaration (the OVER bit), then a single scan may
  141574. ** be used to process more than one window function. For example:
  141575. **
  141576. ** SELECT max(b) OVER (PARTITION BY c ORDER BY d),
  141577. ** min(e) OVER (PARTITION BY c ORDER BY d)
  141578. ** FROM t1;
  141579. **
  141580. ** is transformed in the same way as the example above. However:
  141581. **
  141582. ** SELECT max(b) OVER (PARTITION BY c ORDER BY d),
  141583. ** min(e) OVER (PARTITION BY a ORDER BY b)
  141584. ** FROM t1;
  141585. **
  141586. ** Must be transformed to:
  141587. **
  141588. ** SELECT max(b) OVER (PARTITION BY c ORDER BY d) FROM (
  141589. ** SELECT e, min(e) OVER (PARTITION BY a ORDER BY b), c, d, b FROM
  141590. ** SELECT a, e, c, d, b FROM t1 ORDER BY a, b
  141591. ** ) ORDER BY c, d
  141592. ** ) ORDER BY e;
  141593. **
  141594. ** so that both min() and max() may process rows in the order defined by
  141595. ** their respective window declarations.
  141596. **
  141597. ** INTERFACE WITH SELECT.C
  141598. **
  141599. ** When processing the rewritten SELECT statement, code in select.c calls
  141600. ** sqlite3WhereBegin() to begin iterating through the results of the
  141601. ** sub-query, which is always implemented as a co-routine. It then calls
  141602. ** sqlite3WindowCodeStep() to process rows and finish the scan by calling
  141603. ** sqlite3WhereEnd().
  141604. **
  141605. ** sqlite3WindowCodeStep() generates VM code so that, for each row returned
  141606. ** by the sub-query a sub-routine (OP_Gosub) coded by select.c is invoked.
  141607. ** When the sub-routine is invoked:
  141608. **
  141609. ** * The results of all window-functions for the row are stored
  141610. ** in the associated Window.regResult registers.
  141611. **
  141612. ** * The required terminal values are stored in the current row of
  141613. ** temp table Window.iEphCsr.
  141614. **
  141615. ** In some cases, depending on the window frame and the specific window
  141616. ** functions invoked, sqlite3WindowCodeStep() caches each entire partition
  141617. ** in a temp table before returning any rows. In other cases it does not.
  141618. ** This detail is encapsulated within this file, the code generated by
  141619. ** select.c is the same in either case.
  141620. **
  141621. ** BUILT-IN WINDOW FUNCTIONS
  141622. **
  141623. ** This implementation features the following built-in window functions:
  141624. **
  141625. ** row_number()
  141626. ** rank()
  141627. ** dense_rank()
  141628. ** percent_rank()
  141629. ** cume_dist()
  141630. ** ntile(N)
  141631. ** lead(expr [, offset [, default]])
  141632. ** lag(expr [, offset [, default]])
  141633. ** first_value(expr)
  141634. ** last_value(expr)
  141635. ** nth_value(expr, N)
  141636. **
  141637. ** These are the same built-in window functions supported by Postgres.
  141638. ** Although the behaviour of aggregate window functions (functions that
  141639. ** can be used as either aggregates or window funtions) allows them to
  141640. ** be implemented using an API, built-in window functions are much more
  141641. ** esoteric. Additionally, some window functions (e.g. nth_value())
  141642. ** may only be implemented by caching the entire partition in memory.
  141643. ** As such, some built-in window functions use the same API as aggregate
  141644. ** window functions and some are implemented directly using VDBE
  141645. ** instructions. Additionally, for those functions that use the API, the
  141646. ** window frame is sometimes modified before the SELECT statement is
  141647. ** rewritten. For example, regardless of the specified window frame, the
  141648. ** row_number() function always uses:
  141649. **
  141650. ** ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
  141651. **
  141652. ** See sqlite3WindowUpdate() for details.
  141653. **
  141654. ** As well as some of the built-in window functions, aggregate window
  141655. ** functions min() and max() are implemented using VDBE instructions if
  141656. ** the start of the window frame is declared as anything other than
  141657. ** UNBOUNDED PRECEDING.
  141658. */
  141659. /*
  141660. ** Implementation of built-in window function row_number(). Assumes that the
  141661. ** window frame has been coerced to:
  141662. **
  141663. ** ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
  141664. */
  141665. static void row_numberStepFunc(
  141666. sqlite3_context *pCtx,
  141667. int nArg,
  141668. sqlite3_value **apArg
  141669. ){
  141670. i64 *p = (i64*)sqlite3_aggregate_context(pCtx, sizeof(*p));
  141671. if( p ) (*p)++;
  141672. UNUSED_PARAMETER(nArg);
  141673. UNUSED_PARAMETER(apArg);
  141674. }
  141675. static void row_numberValueFunc(sqlite3_context *pCtx){
  141676. i64 *p = (i64*)sqlite3_aggregate_context(pCtx, sizeof(*p));
  141677. sqlite3_result_int64(pCtx, (p ? *p : 0));
  141678. }
  141679. /*
  141680. ** Context object type used by rank(), dense_rank(), percent_rank() and
  141681. ** cume_dist().
  141682. */
  141683. struct CallCount {
  141684. i64 nValue;
  141685. i64 nStep;
  141686. i64 nTotal;
  141687. };
  141688. /*
  141689. ** Implementation of built-in window function dense_rank(). Assumes that
  141690. ** the window frame has been set to:
  141691. **
  141692. ** RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
  141693. */
  141694. static void dense_rankStepFunc(
  141695. sqlite3_context *pCtx,
  141696. int nArg,
  141697. sqlite3_value **apArg
  141698. ){
  141699. struct CallCount *p;
  141700. p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
  141701. if( p ) p->nStep = 1;
  141702. UNUSED_PARAMETER(nArg);
  141703. UNUSED_PARAMETER(apArg);
  141704. }
  141705. static void dense_rankValueFunc(sqlite3_context *pCtx){
  141706. struct CallCount *p;
  141707. p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
  141708. if( p ){
  141709. if( p->nStep ){
  141710. p->nValue++;
  141711. p->nStep = 0;
  141712. }
  141713. sqlite3_result_int64(pCtx, p->nValue);
  141714. }
  141715. }
  141716. /*
  141717. ** Implementation of built-in window function nth_value(). This
  141718. ** implementation is used in "slow mode" only - when the EXCLUDE clause
  141719. ** is not set to the default value "NO OTHERS".
  141720. */
  141721. struct NthValueCtx {
  141722. i64 nStep;
  141723. sqlite3_value *pValue;
  141724. };
  141725. static void nth_valueStepFunc(
  141726. sqlite3_context *pCtx,
  141727. int nArg,
  141728. sqlite3_value **apArg
  141729. ){
  141730. struct NthValueCtx *p;
  141731. p = (struct NthValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
  141732. if( p ){
  141733. i64 iVal;
  141734. switch( sqlite3_value_numeric_type(apArg[1]) ){
  141735. case SQLITE_INTEGER:
  141736. iVal = sqlite3_value_int64(apArg[1]);
  141737. break;
  141738. case SQLITE_FLOAT: {
  141739. double fVal = sqlite3_value_double(apArg[1]);
  141740. if( ((i64)fVal)!=fVal ) goto error_out;
  141741. iVal = (i64)fVal;
  141742. break;
  141743. }
  141744. default:
  141745. goto error_out;
  141746. }
  141747. if( iVal<=0 ) goto error_out;
  141748. p->nStep++;
  141749. if( iVal==p->nStep ){
  141750. p->pValue = sqlite3_value_dup(apArg[0]);
  141751. if( !p->pValue ){
  141752. sqlite3_result_error_nomem(pCtx);
  141753. }
  141754. }
  141755. }
  141756. UNUSED_PARAMETER(nArg);
  141757. UNUSED_PARAMETER(apArg);
  141758. return;
  141759. error_out:
  141760. sqlite3_result_error(
  141761. pCtx, "second argument to nth_value must be a positive integer", -1
  141762. );
  141763. }
  141764. static void nth_valueFinalizeFunc(sqlite3_context *pCtx){
  141765. struct NthValueCtx *p;
  141766. p = (struct NthValueCtx*)sqlite3_aggregate_context(pCtx, 0);
  141767. if( p && p->pValue ){
  141768. sqlite3_result_value(pCtx, p->pValue);
  141769. sqlite3_value_free(p->pValue);
  141770. p->pValue = 0;
  141771. }
  141772. }
  141773. #define nth_valueInvFunc noopStepFunc
  141774. #define nth_valueValueFunc noopValueFunc
  141775. static void first_valueStepFunc(
  141776. sqlite3_context *pCtx,
  141777. int nArg,
  141778. sqlite3_value **apArg
  141779. ){
  141780. struct NthValueCtx *p;
  141781. p = (struct NthValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
  141782. if( p && p->pValue==0 ){
  141783. p->pValue = sqlite3_value_dup(apArg[0]);
  141784. if( !p->pValue ){
  141785. sqlite3_result_error_nomem(pCtx);
  141786. }
  141787. }
  141788. UNUSED_PARAMETER(nArg);
  141789. UNUSED_PARAMETER(apArg);
  141790. }
  141791. static void first_valueFinalizeFunc(sqlite3_context *pCtx){
  141792. struct NthValueCtx *p;
  141793. p = (struct NthValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
  141794. if( p && p->pValue ){
  141795. sqlite3_result_value(pCtx, p->pValue);
  141796. sqlite3_value_free(p->pValue);
  141797. p->pValue = 0;
  141798. }
  141799. }
  141800. #define first_valueInvFunc noopStepFunc
  141801. #define first_valueValueFunc noopValueFunc
  141802. /*
  141803. ** Implementation of built-in window function rank(). Assumes that
  141804. ** the window frame has been set to:
  141805. **
  141806. ** RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
  141807. */
  141808. static void rankStepFunc(
  141809. sqlite3_context *pCtx,
  141810. int nArg,
  141811. sqlite3_value **apArg
  141812. ){
  141813. struct CallCount *p;
  141814. p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
  141815. if( p ){
  141816. p->nStep++;
  141817. if( p->nValue==0 ){
  141818. p->nValue = p->nStep;
  141819. }
  141820. }
  141821. UNUSED_PARAMETER(nArg);
  141822. UNUSED_PARAMETER(apArg);
  141823. }
  141824. static void rankValueFunc(sqlite3_context *pCtx){
  141825. struct CallCount *p;
  141826. p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
  141827. if( p ){
  141828. sqlite3_result_int64(pCtx, p->nValue);
  141829. p->nValue = 0;
  141830. }
  141831. }
  141832. /*
  141833. ** Implementation of built-in window function percent_rank(). Assumes that
  141834. ** the window frame has been set to:
  141835. **
  141836. ** GROUPS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
  141837. */
  141838. static void percent_rankStepFunc(
  141839. sqlite3_context *pCtx,
  141840. int nArg,
  141841. sqlite3_value **apArg
  141842. ){
  141843. struct CallCount *p;
  141844. UNUSED_PARAMETER(nArg); assert( nArg==0 );
  141845. UNUSED_PARAMETER(apArg);
  141846. p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
  141847. if( p ){
  141848. p->nTotal++;
  141849. }
  141850. }
  141851. static void percent_rankInvFunc(
  141852. sqlite3_context *pCtx,
  141853. int nArg,
  141854. sqlite3_value **apArg
  141855. ){
  141856. struct CallCount *p;
  141857. UNUSED_PARAMETER(nArg); assert( nArg==0 );
  141858. UNUSED_PARAMETER(apArg);
  141859. p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
  141860. p->nStep++;
  141861. }
  141862. static void percent_rankValueFunc(sqlite3_context *pCtx){
  141863. struct CallCount *p;
  141864. p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
  141865. if( p ){
  141866. p->nValue = p->nStep;
  141867. if( p->nTotal>1 ){
  141868. double r = (double)p->nValue / (double)(p->nTotal-1);
  141869. sqlite3_result_double(pCtx, r);
  141870. }else{
  141871. sqlite3_result_double(pCtx, 0.0);
  141872. }
  141873. }
  141874. }
  141875. #define percent_rankFinalizeFunc percent_rankValueFunc
  141876. /*
  141877. ** Implementation of built-in window function cume_dist(). Assumes that
  141878. ** the window frame has been set to:
  141879. **
  141880. ** GROUPS BETWEEN 1 FOLLOWING AND UNBOUNDED FOLLOWING
  141881. */
  141882. static void cume_distStepFunc(
  141883. sqlite3_context *pCtx,
  141884. int nArg,
  141885. sqlite3_value **apArg
  141886. ){
  141887. struct CallCount *p;
  141888. UNUSED_PARAMETER(nArg); assert( nArg==0 );
  141889. UNUSED_PARAMETER(apArg);
  141890. p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
  141891. if( p ){
  141892. p->nTotal++;
  141893. }
  141894. }
  141895. static void cume_distInvFunc(
  141896. sqlite3_context *pCtx,
  141897. int nArg,
  141898. sqlite3_value **apArg
  141899. ){
  141900. struct CallCount *p;
  141901. UNUSED_PARAMETER(nArg); assert( nArg==0 );
  141902. UNUSED_PARAMETER(apArg);
  141903. p = (struct CallCount*)sqlite3_aggregate_context(pCtx, sizeof(*p));
  141904. p->nStep++;
  141905. }
  141906. static void cume_distValueFunc(sqlite3_context *pCtx){
  141907. struct CallCount *p;
  141908. p = (struct CallCount*)sqlite3_aggregate_context(pCtx, 0);
  141909. if( p ){
  141910. double r = (double)(p->nStep) / (double)(p->nTotal);
  141911. sqlite3_result_double(pCtx, r);
  141912. }
  141913. }
  141914. #define cume_distFinalizeFunc cume_distValueFunc
  141915. /*
  141916. ** Context object for ntile() window function.
  141917. */
  141918. struct NtileCtx {
  141919. i64 nTotal; /* Total rows in partition */
  141920. i64 nParam; /* Parameter passed to ntile(N) */
  141921. i64 iRow; /* Current row */
  141922. };
  141923. /*
  141924. ** Implementation of ntile(). This assumes that the window frame has
  141925. ** been coerced to:
  141926. **
  141927. ** ROWS CURRENT ROW AND UNBOUNDED FOLLOWING
  141928. */
  141929. static void ntileStepFunc(
  141930. sqlite3_context *pCtx,
  141931. int nArg,
  141932. sqlite3_value **apArg
  141933. ){
  141934. struct NtileCtx *p;
  141935. assert( nArg==1 ); UNUSED_PARAMETER(nArg);
  141936. p = (struct NtileCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
  141937. if( p ){
  141938. if( p->nTotal==0 ){
  141939. p->nParam = sqlite3_value_int64(apArg[0]);
  141940. if( p->nParam<=0 ){
  141941. sqlite3_result_error(
  141942. pCtx, "argument of ntile must be a positive integer", -1
  141943. );
  141944. }
  141945. }
  141946. p->nTotal++;
  141947. }
  141948. }
  141949. static void ntileInvFunc(
  141950. sqlite3_context *pCtx,
  141951. int nArg,
  141952. sqlite3_value **apArg
  141953. ){
  141954. struct NtileCtx *p;
  141955. assert( nArg==1 ); UNUSED_PARAMETER(nArg);
  141956. UNUSED_PARAMETER(apArg);
  141957. p = (struct NtileCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
  141958. p->iRow++;
  141959. }
  141960. static void ntileValueFunc(sqlite3_context *pCtx){
  141961. struct NtileCtx *p;
  141962. p = (struct NtileCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
  141963. if( p && p->nParam>0 ){
  141964. int nSize = (p->nTotal / p->nParam);
  141965. if( nSize==0 ){
  141966. sqlite3_result_int64(pCtx, p->iRow+1);
  141967. }else{
  141968. i64 nLarge = p->nTotal - p->nParam*nSize;
  141969. i64 iSmall = nLarge*(nSize+1);
  141970. i64 iRow = p->iRow;
  141971. assert( (nLarge*(nSize+1) + (p->nParam-nLarge)*nSize)==p->nTotal );
  141972. if( iRow<iSmall ){
  141973. sqlite3_result_int64(pCtx, 1 + iRow/(nSize+1));
  141974. }else{
  141975. sqlite3_result_int64(pCtx, 1 + nLarge + (iRow-iSmall)/nSize);
  141976. }
  141977. }
  141978. }
  141979. }
  141980. #define ntileFinalizeFunc ntileValueFunc
  141981. /*
  141982. ** Context object for last_value() window function.
  141983. */
  141984. struct LastValueCtx {
  141985. sqlite3_value *pVal;
  141986. int nVal;
  141987. };
  141988. /*
  141989. ** Implementation of last_value().
  141990. */
  141991. static void last_valueStepFunc(
  141992. sqlite3_context *pCtx,
  141993. int nArg,
  141994. sqlite3_value **apArg
  141995. ){
  141996. struct LastValueCtx *p;
  141997. UNUSED_PARAMETER(nArg);
  141998. p = (struct LastValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
  141999. if( p ){
  142000. sqlite3_value_free(p->pVal);
  142001. p->pVal = sqlite3_value_dup(apArg[0]);
  142002. if( p->pVal==0 ){
  142003. sqlite3_result_error_nomem(pCtx);
  142004. }else{
  142005. p->nVal++;
  142006. }
  142007. }
  142008. }
  142009. static void last_valueInvFunc(
  142010. sqlite3_context *pCtx,
  142011. int nArg,
  142012. sqlite3_value **apArg
  142013. ){
  142014. struct LastValueCtx *p;
  142015. UNUSED_PARAMETER(nArg);
  142016. UNUSED_PARAMETER(apArg);
  142017. p = (struct LastValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
  142018. if( ALWAYS(p) ){
  142019. p->nVal--;
  142020. if( p->nVal==0 ){
  142021. sqlite3_value_free(p->pVal);
  142022. p->pVal = 0;
  142023. }
  142024. }
  142025. }
  142026. static void last_valueValueFunc(sqlite3_context *pCtx){
  142027. struct LastValueCtx *p;
  142028. p = (struct LastValueCtx*)sqlite3_aggregate_context(pCtx, 0);
  142029. if( p && p->pVal ){
  142030. sqlite3_result_value(pCtx, p->pVal);
  142031. }
  142032. }
  142033. static void last_valueFinalizeFunc(sqlite3_context *pCtx){
  142034. struct LastValueCtx *p;
  142035. p = (struct LastValueCtx*)sqlite3_aggregate_context(pCtx, sizeof(*p));
  142036. if( p && p->pVal ){
  142037. sqlite3_result_value(pCtx, p->pVal);
  142038. sqlite3_value_free(p->pVal);
  142039. p->pVal = 0;
  142040. }
  142041. }
  142042. /*
  142043. ** Static names for the built-in window function names. These static
  142044. ** names are used, rather than string literals, so that FuncDef objects
  142045. ** can be associated with a particular window function by direct
  142046. ** comparison of the zName pointer. Example:
  142047. **
  142048. ** if( pFuncDef->zName==row_valueName ){ ... }
  142049. */
  142050. static const char row_numberName[] = "row_number";
  142051. static const char dense_rankName[] = "dense_rank";
  142052. static const char rankName[] = "rank";
  142053. static const char percent_rankName[] = "percent_rank";
  142054. static const char cume_distName[] = "cume_dist";
  142055. static const char ntileName[] = "ntile";
  142056. static const char last_valueName[] = "last_value";
  142057. static const char nth_valueName[] = "nth_value";
  142058. static const char first_valueName[] = "first_value";
  142059. static const char leadName[] = "lead";
  142060. static const char lagName[] = "lag";
  142061. /*
  142062. ** No-op implementations of xStep() and xFinalize(). Used as place-holders
  142063. ** for built-in window functions that never call those interfaces.
  142064. **
  142065. ** The noopValueFunc() is called but is expected to do nothing. The
  142066. ** noopStepFunc() is never called, and so it is marked with NO_TEST to
  142067. ** let the test coverage routine know not to expect this function to be
  142068. ** invoked.
  142069. */
  142070. static void noopStepFunc( /*NO_TEST*/
  142071. sqlite3_context *p, /*NO_TEST*/
  142072. int n, /*NO_TEST*/
  142073. sqlite3_value **a /*NO_TEST*/
  142074. ){ /*NO_TEST*/
  142075. UNUSED_PARAMETER(p); /*NO_TEST*/
  142076. UNUSED_PARAMETER(n); /*NO_TEST*/
  142077. UNUSED_PARAMETER(a); /*NO_TEST*/
  142078. assert(0); /*NO_TEST*/
  142079. } /*NO_TEST*/
  142080. static void noopValueFunc(sqlite3_context *p){ UNUSED_PARAMETER(p); /*no-op*/ }
  142081. /* Window functions that use all window interfaces: xStep, xFinal,
  142082. ** xValue, and xInverse */
  142083. #define WINDOWFUNCALL(name,nArg,extra) { \
  142084. nArg, (SQLITE_UTF8|SQLITE_FUNC_WINDOW|extra), 0, 0, \
  142085. name ## StepFunc, name ## FinalizeFunc, name ## ValueFunc, \
  142086. name ## InvFunc, name ## Name, {0} \
  142087. }
  142088. /* Window functions that are implemented using bytecode and thus have
  142089. ** no-op routines for their methods */
  142090. #define WINDOWFUNCNOOP(name,nArg,extra) { \
  142091. nArg, (SQLITE_UTF8|SQLITE_FUNC_WINDOW|extra), 0, 0, \
  142092. noopStepFunc, noopValueFunc, noopValueFunc, \
  142093. noopStepFunc, name ## Name, {0} \
  142094. }
  142095. /* Window functions that use all window interfaces: xStep, the
  142096. ** same routine for xFinalize and xValue and which never call
  142097. ** xInverse. */
  142098. #define WINDOWFUNCX(name,nArg,extra) { \
  142099. nArg, (SQLITE_UTF8|SQLITE_FUNC_WINDOW|extra), 0, 0, \
  142100. name ## StepFunc, name ## ValueFunc, name ## ValueFunc, \
  142101. noopStepFunc, name ## Name, {0} \
  142102. }
  142103. /*
  142104. ** Register those built-in window functions that are not also aggregates.
  142105. */
  142106. SQLITE_PRIVATE void sqlite3WindowFunctions(void){
  142107. static FuncDef aWindowFuncs[] = {
  142108. WINDOWFUNCX(row_number, 0, 0),
  142109. WINDOWFUNCX(dense_rank, 0, 0),
  142110. WINDOWFUNCX(rank, 0, 0),
  142111. WINDOWFUNCALL(percent_rank, 0, 0),
  142112. WINDOWFUNCALL(cume_dist, 0, 0),
  142113. WINDOWFUNCALL(ntile, 1, 0),
  142114. WINDOWFUNCALL(last_value, 1, 0),
  142115. WINDOWFUNCALL(nth_value, 2, 0),
  142116. WINDOWFUNCALL(first_value, 1, 0),
  142117. WINDOWFUNCNOOP(lead, 1, 0),
  142118. WINDOWFUNCNOOP(lead, 2, 0),
  142119. WINDOWFUNCNOOP(lead, 3, 0),
  142120. WINDOWFUNCNOOP(lag, 1, 0),
  142121. WINDOWFUNCNOOP(lag, 2, 0),
  142122. WINDOWFUNCNOOP(lag, 3, 0),
  142123. };
  142124. sqlite3InsertBuiltinFuncs(aWindowFuncs, ArraySize(aWindowFuncs));
  142125. }
  142126. static Window *windowFind(Parse *pParse, Window *pList, const char *zName){
  142127. Window *p;
  142128. for(p=pList; p; p=p->pNextWin){
  142129. if( sqlite3StrICmp(p->zName, zName)==0 ) break;
  142130. }
  142131. if( p==0 ){
  142132. sqlite3ErrorMsg(pParse, "no such window: %s", zName);
  142133. }
  142134. return p;
  142135. }
  142136. /*
  142137. ** This function is called immediately after resolving the function name
  142138. ** for a window function within a SELECT statement. Argument pList is a
  142139. ** linked list of WINDOW definitions for the current SELECT statement.
  142140. ** Argument pFunc is the function definition just resolved and pWin
  142141. ** is the Window object representing the associated OVER clause. This
  142142. ** function updates the contents of pWin as follows:
  142143. **
  142144. ** * If the OVER clause refered to a named window (as in "max(x) OVER win"),
  142145. ** search list pList for a matching WINDOW definition, and update pWin
  142146. ** accordingly. If no such WINDOW clause can be found, leave an error
  142147. ** in pParse.
  142148. **
  142149. ** * If the function is a built-in window function that requires the
  142150. ** window to be coerced (see "BUILT-IN WINDOW FUNCTIONS" at the top
  142151. ** of this file), pWin is updated here.
  142152. */
  142153. SQLITE_PRIVATE void sqlite3WindowUpdate(
  142154. Parse *pParse,
  142155. Window *pList, /* List of named windows for this SELECT */
  142156. Window *pWin, /* Window frame to update */
  142157. FuncDef *pFunc /* Window function definition */
  142158. ){
  142159. if( pWin->zName && pWin->eFrmType==0 ){
  142160. Window *p = windowFind(pParse, pList, pWin->zName);
  142161. if( p==0 ) return;
  142162. pWin->pPartition = sqlite3ExprListDup(pParse->db, p->pPartition, 0);
  142163. pWin->pOrderBy = sqlite3ExprListDup(pParse->db, p->pOrderBy, 0);
  142164. pWin->pStart = sqlite3ExprDup(pParse->db, p->pStart, 0);
  142165. pWin->pEnd = sqlite3ExprDup(pParse->db, p->pEnd, 0);
  142166. pWin->eStart = p->eStart;
  142167. pWin->eEnd = p->eEnd;
  142168. pWin->eFrmType = p->eFrmType;
  142169. pWin->eExclude = p->eExclude;
  142170. }else{
  142171. sqlite3WindowChain(pParse, pWin, pList);
  142172. }
  142173. if( (pWin->eFrmType==TK_RANGE)
  142174. && (pWin->pStart || pWin->pEnd)
  142175. && (pWin->pOrderBy==0 || pWin->pOrderBy->nExpr!=1)
  142176. ){
  142177. sqlite3ErrorMsg(pParse,
  142178. "RANGE with offset PRECEDING/FOLLOWING requires one ORDER BY expression"
  142179. );
  142180. }else
  142181. if( pFunc->funcFlags & SQLITE_FUNC_WINDOW ){
  142182. sqlite3 *db = pParse->db;
  142183. if( pWin->pFilter ){
  142184. sqlite3ErrorMsg(pParse,
  142185. "FILTER clause may only be used with aggregate window functions"
  142186. );
  142187. }else{
  142188. struct WindowUpdate {
  142189. const char *zFunc;
  142190. int eFrmType;
  142191. int eStart;
  142192. int eEnd;
  142193. } aUp[] = {
  142194. { row_numberName, TK_ROWS, TK_UNBOUNDED, TK_CURRENT },
  142195. { dense_rankName, TK_RANGE, TK_UNBOUNDED, TK_CURRENT },
  142196. { rankName, TK_RANGE, TK_UNBOUNDED, TK_CURRENT },
  142197. { percent_rankName, TK_GROUPS, TK_CURRENT, TK_UNBOUNDED },
  142198. { cume_distName, TK_GROUPS, TK_FOLLOWING, TK_UNBOUNDED },
  142199. { ntileName, TK_ROWS, TK_CURRENT, TK_UNBOUNDED },
  142200. { leadName, TK_ROWS, TK_UNBOUNDED, TK_UNBOUNDED },
  142201. { lagName, TK_ROWS, TK_UNBOUNDED, TK_CURRENT },
  142202. };
  142203. int i;
  142204. for(i=0; i<ArraySize(aUp); i++){
  142205. if( pFunc->zName==aUp[i].zFunc ){
  142206. sqlite3ExprDelete(db, pWin->pStart);
  142207. sqlite3ExprDelete(db, pWin->pEnd);
  142208. pWin->pEnd = pWin->pStart = 0;
  142209. pWin->eFrmType = aUp[i].eFrmType;
  142210. pWin->eStart = aUp[i].eStart;
  142211. pWin->eEnd = aUp[i].eEnd;
  142212. pWin->eExclude = 0;
  142213. if( pWin->eStart==TK_FOLLOWING ){
  142214. pWin->pStart = sqlite3Expr(db, TK_INTEGER, "1");
  142215. }
  142216. break;
  142217. }
  142218. }
  142219. }
  142220. }
  142221. pWin->pFunc = pFunc;
  142222. }
  142223. /*
  142224. ** Context object passed through sqlite3WalkExprList() to
  142225. ** selectWindowRewriteExprCb() by selectWindowRewriteEList().
  142226. */
  142227. typedef struct WindowRewrite WindowRewrite;
  142228. struct WindowRewrite {
  142229. Window *pWin;
  142230. SrcList *pSrc;
  142231. ExprList *pSub;
  142232. Table *pTab;
  142233. Select *pSubSelect; /* Current sub-select, if any */
  142234. };
  142235. /*
  142236. ** Callback function used by selectWindowRewriteEList(). If necessary,
  142237. ** this function appends to the output expression-list and updates
  142238. ** expression (*ppExpr) in place.
  142239. */
  142240. static int selectWindowRewriteExprCb(Walker *pWalker, Expr *pExpr){
  142241. struct WindowRewrite *p = pWalker->u.pRewrite;
  142242. Parse *pParse = pWalker->pParse;
  142243. assert( p!=0 );
  142244. assert( p->pWin!=0 );
  142245. /* If this function is being called from within a scalar sub-select
  142246. ** that used by the SELECT statement being processed, only process
  142247. ** TK_COLUMN expressions that refer to it (the outer SELECT). Do
  142248. ** not process aggregates or window functions at all, as they belong
  142249. ** to the scalar sub-select. */
  142250. if( p->pSubSelect ){
  142251. if( pExpr->op!=TK_COLUMN ){
  142252. return WRC_Continue;
  142253. }else{
  142254. int nSrc = p->pSrc->nSrc;
  142255. int i;
  142256. for(i=0; i<nSrc; i++){
  142257. if( pExpr->iTable==p->pSrc->a[i].iCursor ) break;
  142258. }
  142259. if( i==nSrc ) return WRC_Continue;
  142260. }
  142261. }
  142262. switch( pExpr->op ){
  142263. case TK_FUNCTION:
  142264. if( !ExprHasProperty(pExpr, EP_WinFunc) ){
  142265. break;
  142266. }else{
  142267. Window *pWin;
  142268. for(pWin=p->pWin; pWin; pWin=pWin->pNextWin){
  142269. if( pExpr->y.pWin==pWin ){
  142270. assert( pWin->pOwner==pExpr );
  142271. return WRC_Prune;
  142272. }
  142273. }
  142274. }
  142275. /* Fall through. */
  142276. case TK_AGG_FUNCTION:
  142277. case TK_COLUMN: {
  142278. int iCol = -1;
  142279. if( p->pSub ){
  142280. int i;
  142281. for(i=0; i<p->pSub->nExpr; i++){
  142282. if( 0==sqlite3ExprCompare(0, p->pSub->a[i].pExpr, pExpr, -1) ){
  142283. iCol = i;
  142284. break;
  142285. }
  142286. }
  142287. }
  142288. if( iCol<0 ){
  142289. Expr *pDup = sqlite3ExprDup(pParse->db, pExpr, 0);
  142290. if( pDup && pDup->op==TK_AGG_FUNCTION ) pDup->op = TK_FUNCTION;
  142291. p->pSub = sqlite3ExprListAppend(pParse, p->pSub, pDup);
  142292. }
  142293. if( p->pSub ){
  142294. assert( ExprHasProperty(pExpr, EP_Static)==0 );
  142295. ExprSetProperty(pExpr, EP_Static);
  142296. sqlite3ExprDelete(pParse->db, pExpr);
  142297. ExprClearProperty(pExpr, EP_Static);
  142298. memset(pExpr, 0, sizeof(Expr));
  142299. pExpr->op = TK_COLUMN;
  142300. pExpr->iColumn = (iCol<0 ? p->pSub->nExpr-1: iCol);
  142301. pExpr->iTable = p->pWin->iEphCsr;
  142302. pExpr->y.pTab = p->pTab;
  142303. }
  142304. if( pParse->db->mallocFailed ) return WRC_Abort;
  142305. break;
  142306. }
  142307. default: /* no-op */
  142308. break;
  142309. }
  142310. return WRC_Continue;
  142311. }
  142312. static int selectWindowRewriteSelectCb(Walker *pWalker, Select *pSelect){
  142313. struct WindowRewrite *p = pWalker->u.pRewrite;
  142314. Select *pSave = p->pSubSelect;
  142315. if( pSave==pSelect ){
  142316. return WRC_Continue;
  142317. }else{
  142318. p->pSubSelect = pSelect;
  142319. sqlite3WalkSelect(pWalker, pSelect);
  142320. p->pSubSelect = pSave;
  142321. }
  142322. return WRC_Prune;
  142323. }
  142324. /*
  142325. ** Iterate through each expression in expression-list pEList. For each:
  142326. **
  142327. ** * TK_COLUMN,
  142328. ** * aggregate function, or
  142329. ** * window function with a Window object that is not a member of the
  142330. ** Window list passed as the second argument (pWin).
  142331. **
  142332. ** Append the node to output expression-list (*ppSub). And replace it
  142333. ** with a TK_COLUMN that reads the (N-1)th element of table
  142334. ** pWin->iEphCsr, where N is the number of elements in (*ppSub) after
  142335. ** appending the new one.
  142336. */
  142337. static void selectWindowRewriteEList(
  142338. Parse *pParse,
  142339. Window *pWin,
  142340. SrcList *pSrc,
  142341. ExprList *pEList, /* Rewrite expressions in this list */
  142342. Table *pTab,
  142343. ExprList **ppSub /* IN/OUT: Sub-select expression-list */
  142344. ){
  142345. Walker sWalker;
  142346. WindowRewrite sRewrite;
  142347. assert( pWin!=0 );
  142348. memset(&sWalker, 0, sizeof(Walker));
  142349. memset(&sRewrite, 0, sizeof(WindowRewrite));
  142350. sRewrite.pSub = *ppSub;
  142351. sRewrite.pWin = pWin;
  142352. sRewrite.pSrc = pSrc;
  142353. sRewrite.pTab = pTab;
  142354. sWalker.pParse = pParse;
  142355. sWalker.xExprCallback = selectWindowRewriteExprCb;
  142356. sWalker.xSelectCallback = selectWindowRewriteSelectCb;
  142357. sWalker.u.pRewrite = &sRewrite;
  142358. (void)sqlite3WalkExprList(&sWalker, pEList);
  142359. *ppSub = sRewrite.pSub;
  142360. }
  142361. /*
  142362. ** Append a copy of each expression in expression-list pAppend to
  142363. ** expression list pList. Return a pointer to the result list.
  142364. */
  142365. static ExprList *exprListAppendList(
  142366. Parse *pParse, /* Parsing context */
  142367. ExprList *pList, /* List to which to append. Might be NULL */
  142368. ExprList *pAppend, /* List of values to append. Might be NULL */
  142369. int bIntToNull
  142370. ){
  142371. if( pAppend ){
  142372. int i;
  142373. int nInit = pList ? pList->nExpr : 0;
  142374. for(i=0; i<pAppend->nExpr; i++){
  142375. Expr *pDup = sqlite3ExprDup(pParse->db, pAppend->a[i].pExpr, 0);
  142376. assert( pDup==0 || !ExprHasProperty(pDup, EP_MemToken) );
  142377. if( bIntToNull && pDup ){
  142378. int iDummy;
  142379. Expr *pSub;
  142380. for(pSub=pDup; ExprHasProperty(pSub, EP_Skip); pSub=pSub->pLeft){
  142381. assert( pSub );
  142382. }
  142383. if( sqlite3ExprIsInteger(pSub, &iDummy) ){
  142384. pSub->op = TK_NULL;
  142385. pSub->flags &= ~(EP_IntValue|EP_IsTrue|EP_IsFalse);
  142386. pSub->u.zToken = 0;
  142387. }
  142388. }
  142389. pList = sqlite3ExprListAppend(pParse, pList, pDup);
  142390. if( pList ) pList->a[nInit+i].sortFlags = pAppend->a[i].sortFlags;
  142391. }
  142392. }
  142393. return pList;
  142394. }
  142395. /*
  142396. ** When rewriting a query, if the new subquery in the FROM clause
  142397. ** contains TK_AGG_FUNCTION nodes that refer to an outer query,
  142398. ** then we have to increase the Expr->op2 values of those nodes
  142399. ** due to the extra subquery layer that was added.
  142400. **
  142401. ** See also the incrAggDepth() routine in resolve.c
  142402. */
  142403. static int sqlite3WindowExtraAggFuncDepth(Walker *pWalker, Expr *pExpr){
  142404. if( pExpr->op==TK_AGG_FUNCTION
  142405. && pExpr->op2>=pWalker->walkerDepth
  142406. ){
  142407. pExpr->op2++;
  142408. }
  142409. return WRC_Continue;
  142410. }
  142411. /*
  142412. ** If the SELECT statement passed as the second argument does not invoke
  142413. ** any SQL window functions, this function is a no-op. Otherwise, it
  142414. ** rewrites the SELECT statement so that window function xStep functions
  142415. ** are invoked in the correct order as described under "SELECT REWRITING"
  142416. ** at the top of this file.
  142417. */
  142418. SQLITE_PRIVATE int sqlite3WindowRewrite(Parse *pParse, Select *p){
  142419. int rc = SQLITE_OK;
  142420. if( p->pWin && p->pPrior==0 && (p->selFlags & SF_WinRewrite)==0 ){
  142421. Vdbe *v = sqlite3GetVdbe(pParse);
  142422. sqlite3 *db = pParse->db;
  142423. Select *pSub = 0; /* The subquery */
  142424. SrcList *pSrc = p->pSrc;
  142425. Expr *pWhere = p->pWhere;
  142426. ExprList *pGroupBy = p->pGroupBy;
  142427. Expr *pHaving = p->pHaving;
  142428. ExprList *pSort = 0;
  142429. ExprList *pSublist = 0; /* Expression list for sub-query */
  142430. Window *pMWin = p->pWin; /* Master window object */
  142431. Window *pWin; /* Window object iterator */
  142432. Table *pTab;
  142433. u32 selFlags = p->selFlags;
  142434. pTab = sqlite3DbMallocZero(db, sizeof(Table));
  142435. if( pTab==0 ){
  142436. return sqlite3ErrorToParser(db, SQLITE_NOMEM);
  142437. }
  142438. p->pSrc = 0;
  142439. p->pWhere = 0;
  142440. p->pGroupBy = 0;
  142441. p->pHaving = 0;
  142442. p->selFlags &= ~SF_Aggregate;
  142443. p->selFlags |= SF_WinRewrite;
  142444. /* Create the ORDER BY clause for the sub-select. This is the concatenation
  142445. ** of the window PARTITION and ORDER BY clauses. Then, if this makes it
  142446. ** redundant, remove the ORDER BY from the parent SELECT. */
  142447. pSort = exprListAppendList(pParse, 0, pMWin->pPartition, 1);
  142448. pSort = exprListAppendList(pParse, pSort, pMWin->pOrderBy, 1);
  142449. if( pSort && p->pOrderBy && p->pOrderBy->nExpr<=pSort->nExpr ){
  142450. int nSave = pSort->nExpr;
  142451. pSort->nExpr = p->pOrderBy->nExpr;
  142452. if( sqlite3ExprListCompare(pSort, p->pOrderBy, -1)==0 ){
  142453. sqlite3ExprListDelete(db, p->pOrderBy);
  142454. p->pOrderBy = 0;
  142455. }
  142456. pSort->nExpr = nSave;
  142457. }
  142458. /* Assign a cursor number for the ephemeral table used to buffer rows.
  142459. ** The OpenEphemeral instruction is coded later, after it is known how
  142460. ** many columns the table will have. */
  142461. pMWin->iEphCsr = pParse->nTab++;
  142462. pParse->nTab += 3;
  142463. selectWindowRewriteEList(pParse, pMWin, pSrc, p->pEList, pTab, &pSublist);
  142464. selectWindowRewriteEList(pParse, pMWin, pSrc, p->pOrderBy, pTab, &pSublist);
  142465. pMWin->nBufferCol = (pSublist ? pSublist->nExpr : 0);
  142466. /* Append the PARTITION BY and ORDER BY expressions to the to the
  142467. ** sub-select expression list. They are required to figure out where
  142468. ** boundaries for partitions and sets of peer rows lie. */
  142469. pSublist = exprListAppendList(pParse, pSublist, pMWin->pPartition, 0);
  142470. pSublist = exprListAppendList(pParse, pSublist, pMWin->pOrderBy, 0);
  142471. /* Append the arguments passed to each window function to the
  142472. ** sub-select expression list. Also allocate two registers for each
  142473. ** window function - one for the accumulator, another for interim
  142474. ** results. */
  142475. for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
  142476. ExprList *pArgs = pWin->pOwner->x.pList;
  142477. if( pWin->pFunc->funcFlags & SQLITE_FUNC_SUBTYPE ){
  142478. selectWindowRewriteEList(pParse, pMWin, pSrc, pArgs, pTab, &pSublist);
  142479. pWin->iArgCol = (pSublist ? pSublist->nExpr : 0);
  142480. pWin->bExprArgs = 1;
  142481. }else{
  142482. pWin->iArgCol = (pSublist ? pSublist->nExpr : 0);
  142483. pSublist = exprListAppendList(pParse, pSublist, pArgs, 0);
  142484. }
  142485. if( pWin->pFilter ){
  142486. Expr *pFilter = sqlite3ExprDup(db, pWin->pFilter, 0);
  142487. pSublist = sqlite3ExprListAppend(pParse, pSublist, pFilter);
  142488. }
  142489. pWin->regAccum = ++pParse->nMem;
  142490. pWin->regResult = ++pParse->nMem;
  142491. sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum);
  142492. }
  142493. /* If there is no ORDER BY or PARTITION BY clause, and the window
  142494. ** function accepts zero arguments, and there are no other columns
  142495. ** selected (e.g. "SELECT row_number() OVER () FROM t1"), it is possible
  142496. ** that pSublist is still NULL here. Add a constant expression here to
  142497. ** keep everything legal in this case.
  142498. */
  142499. if( pSublist==0 ){
  142500. pSublist = sqlite3ExprListAppend(pParse, 0,
  142501. sqlite3Expr(db, TK_INTEGER, "0")
  142502. );
  142503. }
  142504. pSub = sqlite3SelectNew(
  142505. pParse, pSublist, pSrc, pWhere, pGroupBy, pHaving, pSort, 0, 0
  142506. );
  142507. p->pSrc = sqlite3SrcListAppend(pParse, 0, 0, 0);
  142508. if( p->pSrc ){
  142509. Table *pTab2;
  142510. Walker w;
  142511. p->pSrc->a[0].pSelect = pSub;
  142512. sqlite3SrcListAssignCursors(pParse, p->pSrc);
  142513. pSub->selFlags |= SF_Expanded;
  142514. pTab2 = sqlite3ResultSetOfSelect(pParse, pSub, SQLITE_AFF_NONE);
  142515. pSub->selFlags |= (selFlags & SF_Aggregate);
  142516. if( pTab2==0 ){
  142517. /* Might actually be some other kind of error, but in that case
  142518. ** pParse->nErr will be set, so if SQLITE_NOMEM is set, we will get
  142519. ** the correct error message regardless. */
  142520. rc = SQLITE_NOMEM;
  142521. }else{
  142522. memcpy(pTab, pTab2, sizeof(Table));
  142523. pTab->tabFlags |= TF_Ephemeral;
  142524. p->pSrc->a[0].pTab = pTab;
  142525. pTab = pTab2;
  142526. memset(&w, 0, sizeof(w));
  142527. w.xExprCallback = sqlite3WindowExtraAggFuncDepth;
  142528. w.xSelectCallback = sqlite3WalkerDepthIncrease;
  142529. w.xSelectCallback2 = sqlite3WalkerDepthDecrease;
  142530. sqlite3WalkSelect(&w, pSub);
  142531. }
  142532. }else{
  142533. sqlite3SelectDelete(db, pSub);
  142534. }
  142535. if( db->mallocFailed ) rc = SQLITE_NOMEM;
  142536. sqlite3DbFree(db, pTab);
  142537. }
  142538. if( rc ){
  142539. if( pParse->nErr==0 ){
  142540. assert( pParse->db->mallocFailed );
  142541. sqlite3ErrorToParser(pParse->db, SQLITE_NOMEM);
  142542. }
  142543. sqlite3SelectReset(pParse, p);
  142544. }
  142545. return rc;
  142546. }
  142547. /*
  142548. ** Unlink the Window object from the Select to which it is attached,
  142549. ** if it is attached.
  142550. */
  142551. SQLITE_PRIVATE void sqlite3WindowUnlinkFromSelect(Window *p){
  142552. if( p->ppThis ){
  142553. *p->ppThis = p->pNextWin;
  142554. if( p->pNextWin ) p->pNextWin->ppThis = p->ppThis;
  142555. p->ppThis = 0;
  142556. }
  142557. }
  142558. /*
  142559. ** Free the Window object passed as the second argument.
  142560. */
  142561. SQLITE_PRIVATE void sqlite3WindowDelete(sqlite3 *db, Window *p){
  142562. if( p ){
  142563. sqlite3WindowUnlinkFromSelect(p);
  142564. sqlite3ExprDelete(db, p->pFilter);
  142565. sqlite3ExprListDelete(db, p->pPartition);
  142566. sqlite3ExprListDelete(db, p->pOrderBy);
  142567. sqlite3ExprDelete(db, p->pEnd);
  142568. sqlite3ExprDelete(db, p->pStart);
  142569. sqlite3DbFree(db, p->zName);
  142570. sqlite3DbFree(db, p->zBase);
  142571. sqlite3DbFree(db, p);
  142572. }
  142573. }
  142574. /*
  142575. ** Free the linked list of Window objects starting at the second argument.
  142576. */
  142577. SQLITE_PRIVATE void sqlite3WindowListDelete(sqlite3 *db, Window *p){
  142578. while( p ){
  142579. Window *pNext = p->pNextWin;
  142580. sqlite3WindowDelete(db, p);
  142581. p = pNext;
  142582. }
  142583. }
  142584. /*
  142585. ** The argument expression is an PRECEDING or FOLLOWING offset. The
  142586. ** value should be a non-negative integer. If the value is not a
  142587. ** constant, change it to NULL. The fact that it is then a non-negative
  142588. ** integer will be caught later. But it is important not to leave
  142589. ** variable values in the expression tree.
  142590. */
  142591. static Expr *sqlite3WindowOffsetExpr(Parse *pParse, Expr *pExpr){
  142592. if( 0==sqlite3ExprIsConstant(pExpr) ){
  142593. if( IN_RENAME_OBJECT ) sqlite3RenameExprUnmap(pParse, pExpr);
  142594. sqlite3ExprDelete(pParse->db, pExpr);
  142595. pExpr = sqlite3ExprAlloc(pParse->db, TK_NULL, 0, 0);
  142596. }
  142597. return pExpr;
  142598. }
  142599. /*
  142600. ** Allocate and return a new Window object describing a Window Definition.
  142601. */
  142602. SQLITE_PRIVATE Window *sqlite3WindowAlloc(
  142603. Parse *pParse, /* Parsing context */
  142604. int eType, /* Frame type. TK_RANGE, TK_ROWS, TK_GROUPS, or 0 */
  142605. int eStart, /* Start type: CURRENT, PRECEDING, FOLLOWING, UNBOUNDED */
  142606. Expr *pStart, /* Start window size if TK_PRECEDING or FOLLOWING */
  142607. int eEnd, /* End type: CURRENT, FOLLOWING, TK_UNBOUNDED, PRECEDING */
  142608. Expr *pEnd, /* End window size if TK_FOLLOWING or PRECEDING */
  142609. u8 eExclude /* EXCLUDE clause */
  142610. ){
  142611. Window *pWin = 0;
  142612. int bImplicitFrame = 0;
  142613. /* Parser assures the following: */
  142614. assert( eType==0 || eType==TK_RANGE || eType==TK_ROWS || eType==TK_GROUPS );
  142615. assert( eStart==TK_CURRENT || eStart==TK_PRECEDING
  142616. || eStart==TK_UNBOUNDED || eStart==TK_FOLLOWING );
  142617. assert( eEnd==TK_CURRENT || eEnd==TK_FOLLOWING
  142618. || eEnd==TK_UNBOUNDED || eEnd==TK_PRECEDING );
  142619. assert( (eStart==TK_PRECEDING || eStart==TK_FOLLOWING)==(pStart!=0) );
  142620. assert( (eEnd==TK_FOLLOWING || eEnd==TK_PRECEDING)==(pEnd!=0) );
  142621. if( eType==0 ){
  142622. bImplicitFrame = 1;
  142623. eType = TK_RANGE;
  142624. }
  142625. /* Additionally, the
  142626. ** starting boundary type may not occur earlier in the following list than
  142627. ** the ending boundary type:
  142628. **
  142629. ** UNBOUNDED PRECEDING
  142630. ** <expr> PRECEDING
  142631. ** CURRENT ROW
  142632. ** <expr> FOLLOWING
  142633. ** UNBOUNDED FOLLOWING
  142634. **
  142635. ** The parser ensures that "UNBOUNDED PRECEDING" cannot be used as an ending
  142636. ** boundary, and than "UNBOUNDED FOLLOWING" cannot be used as a starting
  142637. ** frame boundary.
  142638. */
  142639. if( (eStart==TK_CURRENT && eEnd==TK_PRECEDING)
  142640. || (eStart==TK_FOLLOWING && (eEnd==TK_PRECEDING || eEnd==TK_CURRENT))
  142641. ){
  142642. sqlite3ErrorMsg(pParse, "unsupported frame specification");
  142643. goto windowAllocErr;
  142644. }
  142645. pWin = (Window*)sqlite3DbMallocZero(pParse->db, sizeof(Window));
  142646. if( pWin==0 ) goto windowAllocErr;
  142647. pWin->eFrmType = eType;
  142648. pWin->eStart = eStart;
  142649. pWin->eEnd = eEnd;
  142650. if( eExclude==0 && OptimizationDisabled(pParse->db, SQLITE_WindowFunc) ){
  142651. eExclude = TK_NO;
  142652. }
  142653. pWin->eExclude = eExclude;
  142654. pWin->bImplicitFrame = bImplicitFrame;
  142655. pWin->pEnd = sqlite3WindowOffsetExpr(pParse, pEnd);
  142656. pWin->pStart = sqlite3WindowOffsetExpr(pParse, pStart);
  142657. return pWin;
  142658. windowAllocErr:
  142659. sqlite3ExprDelete(pParse->db, pEnd);
  142660. sqlite3ExprDelete(pParse->db, pStart);
  142661. return 0;
  142662. }
  142663. /*
  142664. ** Attach PARTITION and ORDER BY clauses pPartition and pOrderBy to window
  142665. ** pWin. Also, if parameter pBase is not NULL, set pWin->zBase to the
  142666. ** equivalent nul-terminated string.
  142667. */
  142668. SQLITE_PRIVATE Window *sqlite3WindowAssemble(
  142669. Parse *pParse,
  142670. Window *pWin,
  142671. ExprList *pPartition,
  142672. ExprList *pOrderBy,
  142673. Token *pBase
  142674. ){
  142675. if( pWin ){
  142676. pWin->pPartition = pPartition;
  142677. pWin->pOrderBy = pOrderBy;
  142678. if( pBase ){
  142679. pWin->zBase = sqlite3DbStrNDup(pParse->db, pBase->z, pBase->n);
  142680. }
  142681. }else{
  142682. sqlite3ExprListDelete(pParse->db, pPartition);
  142683. sqlite3ExprListDelete(pParse->db, pOrderBy);
  142684. }
  142685. return pWin;
  142686. }
  142687. /*
  142688. ** Window *pWin has just been created from a WINDOW clause. Tokne pBase
  142689. ** is the base window. Earlier windows from the same WINDOW clause are
  142690. ** stored in the linked list starting at pWin->pNextWin. This function
  142691. ** either updates *pWin according to the base specification, or else
  142692. ** leaves an error in pParse.
  142693. */
  142694. SQLITE_PRIVATE void sqlite3WindowChain(Parse *pParse, Window *pWin, Window *pList){
  142695. if( pWin->zBase ){
  142696. sqlite3 *db = pParse->db;
  142697. Window *pExist = windowFind(pParse, pList, pWin->zBase);
  142698. if( pExist ){
  142699. const char *zErr = 0;
  142700. /* Check for errors */
  142701. if( pWin->pPartition ){
  142702. zErr = "PARTITION clause";
  142703. }else if( pExist->pOrderBy && pWin->pOrderBy ){
  142704. zErr = "ORDER BY clause";
  142705. }else if( pExist->bImplicitFrame==0 ){
  142706. zErr = "frame specification";
  142707. }
  142708. if( zErr ){
  142709. sqlite3ErrorMsg(pParse,
  142710. "cannot override %s of window: %s", zErr, pWin->zBase
  142711. );
  142712. }else{
  142713. pWin->pPartition = sqlite3ExprListDup(db, pExist->pPartition, 0);
  142714. if( pExist->pOrderBy ){
  142715. assert( pWin->pOrderBy==0 );
  142716. pWin->pOrderBy = sqlite3ExprListDup(db, pExist->pOrderBy, 0);
  142717. }
  142718. sqlite3DbFree(db, pWin->zBase);
  142719. pWin->zBase = 0;
  142720. }
  142721. }
  142722. }
  142723. }
  142724. /*
  142725. ** Attach window object pWin to expression p.
  142726. */
  142727. SQLITE_PRIVATE void sqlite3WindowAttach(Parse *pParse, Expr *p, Window *pWin){
  142728. if( p ){
  142729. assert( p->op==TK_FUNCTION );
  142730. assert( pWin );
  142731. p->y.pWin = pWin;
  142732. ExprSetProperty(p, EP_WinFunc);
  142733. pWin->pOwner = p;
  142734. if( (p->flags & EP_Distinct) && pWin->eFrmType!=TK_FILTER ){
  142735. sqlite3ErrorMsg(pParse,
  142736. "DISTINCT is not supported for window functions"
  142737. );
  142738. }
  142739. }else{
  142740. sqlite3WindowDelete(pParse->db, pWin);
  142741. }
  142742. }
  142743. /*
  142744. ** Possibly link window pWin into the list at pSel->pWin (window functions
  142745. ** to be processed as part of SELECT statement pSel). The window is linked
  142746. ** in if either (a) there are no other windows already linked to this
  142747. ** SELECT, or (b) the windows already linked use a compatible window frame.
  142748. */
  142749. SQLITE_PRIVATE void sqlite3WindowLink(Select *pSel, Window *pWin){
  142750. if( pSel!=0
  142751. && (0==pSel->pWin || 0==sqlite3WindowCompare(0, pSel->pWin, pWin, 0))
  142752. ){
  142753. pWin->pNextWin = pSel->pWin;
  142754. if( pSel->pWin ){
  142755. pSel->pWin->ppThis = &pWin->pNextWin;
  142756. }
  142757. pSel->pWin = pWin;
  142758. pWin->ppThis = &pSel->pWin;
  142759. }
  142760. }
  142761. /*
  142762. ** Return 0 if the two window objects are identical, 1 if they are
  142763. ** different, or 2 if it cannot be determined if the objects are identical
  142764. ** or not. Identical window objects can be processed in a single scan.
  142765. */
  142766. SQLITE_PRIVATE int sqlite3WindowCompare(Parse *pParse, Window *p1, Window *p2, int bFilter){
  142767. int res;
  142768. if( NEVER(p1==0) || NEVER(p2==0) ) return 1;
  142769. if( p1->eFrmType!=p2->eFrmType ) return 1;
  142770. if( p1->eStart!=p2->eStart ) return 1;
  142771. if( p1->eEnd!=p2->eEnd ) return 1;
  142772. if( p1->eExclude!=p2->eExclude ) return 1;
  142773. if( sqlite3ExprCompare(pParse, p1->pStart, p2->pStart, -1) ) return 1;
  142774. if( sqlite3ExprCompare(pParse, p1->pEnd, p2->pEnd, -1) ) return 1;
  142775. if( (res = sqlite3ExprListCompare(p1->pPartition, p2->pPartition, -1)) ){
  142776. return res;
  142777. }
  142778. if( (res = sqlite3ExprListCompare(p1->pOrderBy, p2->pOrderBy, -1)) ){
  142779. return res;
  142780. }
  142781. if( bFilter ){
  142782. if( (res = sqlite3ExprCompare(pParse, p1->pFilter, p2->pFilter, -1)) ){
  142783. return res;
  142784. }
  142785. }
  142786. return 0;
  142787. }
  142788. /*
  142789. ** This is called by code in select.c before it calls sqlite3WhereBegin()
  142790. ** to begin iterating through the sub-query results. It is used to allocate
  142791. ** and initialize registers and cursors used by sqlite3WindowCodeStep().
  142792. */
  142793. SQLITE_PRIVATE void sqlite3WindowCodeInit(Parse *pParse, Select *pSelect){
  142794. int nEphExpr = pSelect->pSrc->a[0].pSelect->pEList->nExpr;
  142795. Window *pMWin = pSelect->pWin;
  142796. Window *pWin;
  142797. Vdbe *v = sqlite3GetVdbe(pParse);
  142798. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pMWin->iEphCsr, nEphExpr);
  142799. sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+1, pMWin->iEphCsr);
  142800. sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+2, pMWin->iEphCsr);
  142801. sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+3, pMWin->iEphCsr);
  142802. /* Allocate registers to use for PARTITION BY values, if any. Initialize
  142803. ** said registers to NULL. */
  142804. if( pMWin->pPartition ){
  142805. int nExpr = pMWin->pPartition->nExpr;
  142806. pMWin->regPart = pParse->nMem+1;
  142807. pParse->nMem += nExpr;
  142808. sqlite3VdbeAddOp3(v, OP_Null, 0, pMWin->regPart, pMWin->regPart+nExpr-1);
  142809. }
  142810. pMWin->regOne = ++pParse->nMem;
  142811. sqlite3VdbeAddOp2(v, OP_Integer, 1, pMWin->regOne);
  142812. if( pMWin->eExclude ){
  142813. pMWin->regStartRowid = ++pParse->nMem;
  142814. pMWin->regEndRowid = ++pParse->nMem;
  142815. pMWin->csrApp = pParse->nTab++;
  142816. sqlite3VdbeAddOp2(v, OP_Integer, 1, pMWin->regStartRowid);
  142817. sqlite3VdbeAddOp2(v, OP_Integer, 0, pMWin->regEndRowid);
  142818. sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->csrApp, pMWin->iEphCsr);
  142819. return;
  142820. }
  142821. for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
  142822. FuncDef *p = pWin->pFunc;
  142823. if( (p->funcFlags & SQLITE_FUNC_MINMAX) && pWin->eStart!=TK_UNBOUNDED ){
  142824. /* The inline versions of min() and max() require a single ephemeral
  142825. ** table and 3 registers. The registers are used as follows:
  142826. **
  142827. ** regApp+0: slot to copy min()/max() argument to for MakeRecord
  142828. ** regApp+1: integer value used to ensure keys are unique
  142829. ** regApp+2: output of MakeRecord
  142830. */
  142831. ExprList *pList = pWin->pOwner->x.pList;
  142832. KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pList, 0, 0);
  142833. pWin->csrApp = pParse->nTab++;
  142834. pWin->regApp = pParse->nMem+1;
  142835. pParse->nMem += 3;
  142836. if( pKeyInfo && pWin->pFunc->zName[1]=='i' ){
  142837. assert( pKeyInfo->aSortFlags[0]==0 );
  142838. pKeyInfo->aSortFlags[0] = KEYINFO_ORDER_DESC;
  142839. }
  142840. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pWin->csrApp, 2);
  142841. sqlite3VdbeAppendP4(v, pKeyInfo, P4_KEYINFO);
  142842. sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp+1);
  142843. }
  142844. else if( p->zName==nth_valueName || p->zName==first_valueName ){
  142845. /* Allocate two registers at pWin->regApp. These will be used to
  142846. ** store the start and end index of the current frame. */
  142847. pWin->regApp = pParse->nMem+1;
  142848. pWin->csrApp = pParse->nTab++;
  142849. pParse->nMem += 2;
  142850. sqlite3VdbeAddOp2(v, OP_OpenDup, pWin->csrApp, pMWin->iEphCsr);
  142851. }
  142852. else if( p->zName==leadName || p->zName==lagName ){
  142853. pWin->csrApp = pParse->nTab++;
  142854. sqlite3VdbeAddOp2(v, OP_OpenDup, pWin->csrApp, pMWin->iEphCsr);
  142855. }
  142856. }
  142857. }
  142858. #define WINDOW_STARTING_INT 0
  142859. #define WINDOW_ENDING_INT 1
  142860. #define WINDOW_NTH_VALUE_INT 2
  142861. #define WINDOW_STARTING_NUM 3
  142862. #define WINDOW_ENDING_NUM 4
  142863. /*
  142864. ** A "PRECEDING <expr>" (eCond==0) or "FOLLOWING <expr>" (eCond==1) or the
  142865. ** value of the second argument to nth_value() (eCond==2) has just been
  142866. ** evaluated and the result left in register reg. This function generates VM
  142867. ** code to check that the value is a non-negative integer and throws an
  142868. ** exception if it is not.
  142869. */
  142870. static void windowCheckValue(Parse *pParse, int reg, int eCond){
  142871. static const char *azErr[] = {
  142872. "frame starting offset must be a non-negative integer",
  142873. "frame ending offset must be a non-negative integer",
  142874. "second argument to nth_value must be a positive integer",
  142875. "frame starting offset must be a non-negative number",
  142876. "frame ending offset must be a non-negative number",
  142877. };
  142878. static int aOp[] = { OP_Ge, OP_Ge, OP_Gt, OP_Ge, OP_Ge };
  142879. Vdbe *v = sqlite3GetVdbe(pParse);
  142880. int regZero = sqlite3GetTempReg(pParse);
  142881. assert( eCond>=0 && eCond<ArraySize(azErr) );
  142882. sqlite3VdbeAddOp2(v, OP_Integer, 0, regZero);
  142883. if( eCond>=WINDOW_STARTING_NUM ){
  142884. int regString = sqlite3GetTempReg(pParse);
  142885. sqlite3VdbeAddOp4(v, OP_String8, 0, regString, 0, "", P4_STATIC);
  142886. sqlite3VdbeAddOp3(v, OP_Ge, regString, sqlite3VdbeCurrentAddr(v)+2, reg);
  142887. sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC|SQLITE_JUMPIFNULL);
  142888. VdbeCoverage(v);
  142889. assert( eCond==3 || eCond==4 );
  142890. VdbeCoverageIf(v, eCond==3);
  142891. VdbeCoverageIf(v, eCond==4);
  142892. }else{
  142893. sqlite3VdbeAddOp2(v, OP_MustBeInt, reg, sqlite3VdbeCurrentAddr(v)+2);
  142894. VdbeCoverage(v);
  142895. assert( eCond==0 || eCond==1 || eCond==2 );
  142896. VdbeCoverageIf(v, eCond==0);
  142897. VdbeCoverageIf(v, eCond==1);
  142898. VdbeCoverageIf(v, eCond==2);
  142899. }
  142900. sqlite3VdbeAddOp3(v, aOp[eCond], regZero, sqlite3VdbeCurrentAddr(v)+2, reg);
  142901. VdbeCoverageNeverNullIf(v, eCond==0); /* NULL case captured by */
  142902. VdbeCoverageNeverNullIf(v, eCond==1); /* the OP_MustBeInt */
  142903. VdbeCoverageNeverNullIf(v, eCond==2);
  142904. VdbeCoverageNeverNullIf(v, eCond==3); /* NULL case caught by */
  142905. VdbeCoverageNeverNullIf(v, eCond==4); /* the OP_Ge */
  142906. sqlite3MayAbort(pParse);
  142907. sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_ERROR, OE_Abort);
  142908. sqlite3VdbeAppendP4(v, (void*)azErr[eCond], P4_STATIC);
  142909. sqlite3ReleaseTempReg(pParse, regZero);
  142910. }
  142911. /*
  142912. ** Return the number of arguments passed to the window-function associated
  142913. ** with the object passed as the only argument to this function.
  142914. */
  142915. static int windowArgCount(Window *pWin){
  142916. ExprList *pList = pWin->pOwner->x.pList;
  142917. return (pList ? pList->nExpr : 0);
  142918. }
  142919. typedef struct WindowCodeArg WindowCodeArg;
  142920. typedef struct WindowCsrAndReg WindowCsrAndReg;
  142921. /*
  142922. ** See comments above struct WindowCodeArg.
  142923. */
  142924. struct WindowCsrAndReg {
  142925. int csr; /* Cursor number */
  142926. int reg; /* First in array of peer values */
  142927. };
  142928. /*
  142929. ** A single instance of this structure is allocated on the stack by
  142930. ** sqlite3WindowCodeStep() and a pointer to it passed to the various helper
  142931. ** routines. This is to reduce the number of arguments required by each
  142932. ** helper function.
  142933. **
  142934. ** regArg:
  142935. ** Each window function requires an accumulator register (just as an
  142936. ** ordinary aggregate function does). This variable is set to the first
  142937. ** in an array of accumulator registers - one for each window function
  142938. ** in the WindowCodeArg.pMWin list.
  142939. **
  142940. ** eDelete:
  142941. ** The window functions implementation sometimes caches the input rows
  142942. ** that it processes in a temporary table. If it is not zero, this
  142943. ** variable indicates when rows may be removed from the temp table (in
  142944. ** order to reduce memory requirements - it would always be safe just
  142945. ** to leave them there). Possible values for eDelete are:
  142946. **
  142947. ** WINDOW_RETURN_ROW:
  142948. ** An input row can be discarded after it is returned to the caller.
  142949. **
  142950. ** WINDOW_AGGINVERSE:
  142951. ** An input row can be discarded after the window functions xInverse()
  142952. ** callbacks have been invoked in it.
  142953. **
  142954. ** WINDOW_AGGSTEP:
  142955. ** An input row can be discarded after the window functions xStep()
  142956. ** callbacks have been invoked in it.
  142957. **
  142958. ** start,current,end
  142959. ** Consider a window-frame similar to the following:
  142960. **
  142961. ** (ORDER BY a, b GROUPS BETWEEN 2 PRECEDING AND 2 FOLLOWING)
  142962. **
  142963. ** The windows functions implmentation caches the input rows in a temp
  142964. ** table, sorted by "a, b" (it actually populates the cache lazily, and
  142965. ** aggressively removes rows once they are no longer required, but that's
  142966. ** a mere detail). It keeps three cursors open on the temp table. One
  142967. ** (current) that points to the next row to return to the query engine
  142968. ** once its window function values have been calculated. Another (end)
  142969. ** points to the next row to call the xStep() method of each window function
  142970. ** on (so that it is 2 groups ahead of current). And a third (start) that
  142971. ** points to the next row to call the xInverse() method of each window
  142972. ** function on.
  142973. **
  142974. ** Each cursor (start, current and end) consists of a VDBE cursor
  142975. ** (WindowCsrAndReg.csr) and an array of registers (starting at
  142976. ** WindowCodeArg.reg) that always contains a copy of the peer values
  142977. ** read from the corresponding cursor.
  142978. **
  142979. ** Depending on the window-frame in question, all three cursors may not
  142980. ** be required. In this case both WindowCodeArg.csr and reg are set to
  142981. ** 0.
  142982. */
  142983. struct WindowCodeArg {
  142984. Parse *pParse; /* Parse context */
  142985. Window *pMWin; /* First in list of functions being processed */
  142986. Vdbe *pVdbe; /* VDBE object */
  142987. int addrGosub; /* OP_Gosub to this address to return one row */
  142988. int regGosub; /* Register used with OP_Gosub(addrGosub) */
  142989. int regArg; /* First in array of accumulator registers */
  142990. int eDelete; /* See above */
  142991. WindowCsrAndReg start;
  142992. WindowCsrAndReg current;
  142993. WindowCsrAndReg end;
  142994. };
  142995. /*
  142996. ** Generate VM code to read the window frames peer values from cursor csr into
  142997. ** an array of registers starting at reg.
  142998. */
  142999. static void windowReadPeerValues(
  143000. WindowCodeArg *p,
  143001. int csr,
  143002. int reg
  143003. ){
  143004. Window *pMWin = p->pMWin;
  143005. ExprList *pOrderBy = pMWin->pOrderBy;
  143006. if( pOrderBy ){
  143007. Vdbe *v = sqlite3GetVdbe(p->pParse);
  143008. ExprList *pPart = pMWin->pPartition;
  143009. int iColOff = pMWin->nBufferCol + (pPart ? pPart->nExpr : 0);
  143010. int i;
  143011. for(i=0; i<pOrderBy->nExpr; i++){
  143012. sqlite3VdbeAddOp3(v, OP_Column, csr, iColOff+i, reg+i);
  143013. }
  143014. }
  143015. }
  143016. /*
  143017. ** Generate VM code to invoke either xStep() (if bInverse is 0) or
  143018. ** xInverse (if bInverse is non-zero) for each window function in the
  143019. ** linked list starting at pMWin. Or, for built-in window functions
  143020. ** that do not use the standard function API, generate the required
  143021. ** inline VM code.
  143022. **
  143023. ** If argument csr is greater than or equal to 0, then argument reg is
  143024. ** the first register in an array of registers guaranteed to be large
  143025. ** enough to hold the array of arguments for each function. In this case
  143026. ** the arguments are extracted from the current row of csr into the
  143027. ** array of registers before invoking OP_AggStep or OP_AggInverse
  143028. **
  143029. ** Or, if csr is less than zero, then the array of registers at reg is
  143030. ** already populated with all columns from the current row of the sub-query.
  143031. **
  143032. ** If argument regPartSize is non-zero, then it is a register containing the
  143033. ** number of rows in the current partition.
  143034. */
  143035. static void windowAggStep(
  143036. WindowCodeArg *p,
  143037. Window *pMWin, /* Linked list of window functions */
  143038. int csr, /* Read arguments from this cursor */
  143039. int bInverse, /* True to invoke xInverse instead of xStep */
  143040. int reg /* Array of registers */
  143041. ){
  143042. Parse *pParse = p->pParse;
  143043. Vdbe *v = sqlite3GetVdbe(pParse);
  143044. Window *pWin;
  143045. for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
  143046. FuncDef *pFunc = pWin->pFunc;
  143047. int regArg;
  143048. int nArg = pWin->bExprArgs ? 0 : windowArgCount(pWin);
  143049. int i;
  143050. assert( bInverse==0 || pWin->eStart!=TK_UNBOUNDED );
  143051. /* All OVER clauses in the same window function aggregate step must
  143052. ** be the same. */
  143053. assert( pWin==pMWin || sqlite3WindowCompare(pParse,pWin,pMWin,0)!=1 );
  143054. for(i=0; i<nArg; i++){
  143055. if( i!=1 || pFunc->zName!=nth_valueName ){
  143056. sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol+i, reg+i);
  143057. }else{
  143058. sqlite3VdbeAddOp3(v, OP_Column, pMWin->iEphCsr, pWin->iArgCol+i, reg+i);
  143059. }
  143060. }
  143061. regArg = reg;
  143062. if( pMWin->regStartRowid==0
  143063. && (pFunc->funcFlags & SQLITE_FUNC_MINMAX)
  143064. && (pWin->eStart!=TK_UNBOUNDED)
  143065. ){
  143066. int addrIsNull = sqlite3VdbeAddOp1(v, OP_IsNull, regArg);
  143067. VdbeCoverage(v);
  143068. if( bInverse==0 ){
  143069. sqlite3VdbeAddOp2(v, OP_AddImm, pWin->regApp+1, 1);
  143070. sqlite3VdbeAddOp2(v, OP_SCopy, regArg, pWin->regApp);
  143071. sqlite3VdbeAddOp3(v, OP_MakeRecord, pWin->regApp, 2, pWin->regApp+2);
  143072. sqlite3VdbeAddOp2(v, OP_IdxInsert, pWin->csrApp, pWin->regApp+2);
  143073. }else{
  143074. sqlite3VdbeAddOp4Int(v, OP_SeekGE, pWin->csrApp, 0, regArg, 1);
  143075. VdbeCoverageNeverTaken(v);
  143076. sqlite3VdbeAddOp1(v, OP_Delete, pWin->csrApp);
  143077. sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
  143078. }
  143079. sqlite3VdbeJumpHere(v, addrIsNull);
  143080. }else if( pWin->regApp ){
  143081. assert( pFunc->zName==nth_valueName
  143082. || pFunc->zName==first_valueName
  143083. );
  143084. assert( bInverse==0 || bInverse==1 );
  143085. sqlite3VdbeAddOp2(v, OP_AddImm, pWin->regApp+1-bInverse, 1);
  143086. }else if( pFunc->xSFunc!=noopStepFunc ){
  143087. int addrIf = 0;
  143088. if( pWin->pFilter ){
  143089. int regTmp;
  143090. assert( pWin->bExprArgs || !nArg ||nArg==pWin->pOwner->x.pList->nExpr );
  143091. assert( pWin->bExprArgs || nArg ||pWin->pOwner->x.pList==0 );
  143092. regTmp = sqlite3GetTempReg(pParse);
  143093. sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol+nArg,regTmp);
  143094. addrIf = sqlite3VdbeAddOp3(v, OP_IfNot, regTmp, 0, 1);
  143095. VdbeCoverage(v);
  143096. sqlite3ReleaseTempReg(pParse, regTmp);
  143097. }
  143098. if( pWin->bExprArgs ){
  143099. int iStart = sqlite3VdbeCurrentAddr(v);
  143100. VdbeOp *pOp, *pEnd;
  143101. nArg = pWin->pOwner->x.pList->nExpr;
  143102. regArg = sqlite3GetTempRange(pParse, nArg);
  143103. sqlite3ExprCodeExprList(pParse, pWin->pOwner->x.pList, regArg, 0, 0);
  143104. pEnd = sqlite3VdbeGetOp(v, -1);
  143105. for(pOp=sqlite3VdbeGetOp(v, iStart); pOp<=pEnd; pOp++){
  143106. if( pOp->opcode==OP_Column && pOp->p1==pWin->iEphCsr ){
  143107. pOp->p1 = csr;
  143108. }
  143109. }
  143110. }
  143111. if( pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
  143112. CollSeq *pColl;
  143113. assert( nArg>0 );
  143114. pColl = sqlite3ExprNNCollSeq(pParse, pWin->pOwner->x.pList->a[0].pExpr);
  143115. sqlite3VdbeAddOp4(v, OP_CollSeq, 0,0,0, (const char*)pColl, P4_COLLSEQ);
  143116. }
  143117. sqlite3VdbeAddOp3(v, bInverse? OP_AggInverse : OP_AggStep,
  143118. bInverse, regArg, pWin->regAccum);
  143119. sqlite3VdbeAppendP4(v, pFunc, P4_FUNCDEF);
  143120. sqlite3VdbeChangeP5(v, (u8)nArg);
  143121. if( pWin->bExprArgs ){
  143122. sqlite3ReleaseTempRange(pParse, regArg, nArg);
  143123. }
  143124. if( addrIf ) sqlite3VdbeJumpHere(v, addrIf);
  143125. }
  143126. }
  143127. }
  143128. /*
  143129. ** Values that may be passed as the second argument to windowCodeOp().
  143130. */
  143131. #define WINDOW_RETURN_ROW 1
  143132. #define WINDOW_AGGINVERSE 2
  143133. #define WINDOW_AGGSTEP 3
  143134. /*
  143135. ** Generate VM code to invoke either xValue() (bFin==0) or xFinalize()
  143136. ** (bFin==1) for each window function in the linked list starting at
  143137. ** pMWin. Or, for built-in window-functions that do not use the standard
  143138. ** API, generate the equivalent VM code.
  143139. */
  143140. static void windowAggFinal(WindowCodeArg *p, int bFin){
  143141. Parse *pParse = p->pParse;
  143142. Window *pMWin = p->pMWin;
  143143. Vdbe *v = sqlite3GetVdbe(pParse);
  143144. Window *pWin;
  143145. for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
  143146. if( pMWin->regStartRowid==0
  143147. && (pWin->pFunc->funcFlags & SQLITE_FUNC_MINMAX)
  143148. && (pWin->eStart!=TK_UNBOUNDED)
  143149. ){
  143150. sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regResult);
  143151. sqlite3VdbeAddOp1(v, OP_Last, pWin->csrApp);
  143152. VdbeCoverage(v);
  143153. sqlite3VdbeAddOp3(v, OP_Column, pWin->csrApp, 0, pWin->regResult);
  143154. sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
  143155. }else if( pWin->regApp ){
  143156. assert( pMWin->regStartRowid==0 );
  143157. }else{
  143158. int nArg = windowArgCount(pWin);
  143159. if( bFin ){
  143160. sqlite3VdbeAddOp2(v, OP_AggFinal, pWin->regAccum, nArg);
  143161. sqlite3VdbeAppendP4(v, pWin->pFunc, P4_FUNCDEF);
  143162. sqlite3VdbeAddOp2(v, OP_Copy, pWin->regAccum, pWin->regResult);
  143163. sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum);
  143164. }else{
  143165. sqlite3VdbeAddOp3(v, OP_AggValue,pWin->regAccum,nArg,pWin->regResult);
  143166. sqlite3VdbeAppendP4(v, pWin->pFunc, P4_FUNCDEF);
  143167. }
  143168. }
  143169. }
  143170. }
  143171. /*
  143172. ** Generate code to calculate the current values of all window functions in the
  143173. ** p->pMWin list by doing a full scan of the current window frame. Store the
  143174. ** results in the Window.regResult registers, ready to return the upper
  143175. ** layer.
  143176. */
  143177. static void windowFullScan(WindowCodeArg *p){
  143178. Window *pWin;
  143179. Parse *pParse = p->pParse;
  143180. Window *pMWin = p->pMWin;
  143181. Vdbe *v = p->pVdbe;
  143182. int regCRowid = 0; /* Current rowid value */
  143183. int regCPeer = 0; /* Current peer values */
  143184. int regRowid = 0; /* AggStep rowid value */
  143185. int regPeer = 0; /* AggStep peer values */
  143186. int nPeer;
  143187. int lblNext;
  143188. int lblBrk;
  143189. int addrNext;
  143190. int csr;
  143191. VdbeModuleComment((v, "windowFullScan begin"));
  143192. assert( pMWin!=0 );
  143193. csr = pMWin->csrApp;
  143194. nPeer = (pMWin->pOrderBy ? pMWin->pOrderBy->nExpr : 0);
  143195. lblNext = sqlite3VdbeMakeLabel(pParse);
  143196. lblBrk = sqlite3VdbeMakeLabel(pParse);
  143197. regCRowid = sqlite3GetTempReg(pParse);
  143198. regRowid = sqlite3GetTempReg(pParse);
  143199. if( nPeer ){
  143200. regCPeer = sqlite3GetTempRange(pParse, nPeer);
  143201. regPeer = sqlite3GetTempRange(pParse, nPeer);
  143202. }
  143203. sqlite3VdbeAddOp2(v, OP_Rowid, pMWin->iEphCsr, regCRowid);
  143204. windowReadPeerValues(p, pMWin->iEphCsr, regCPeer);
  143205. for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
  143206. sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum);
  143207. }
  143208. sqlite3VdbeAddOp3(v, OP_SeekGE, csr, lblBrk, pMWin->regStartRowid);
  143209. VdbeCoverage(v);
  143210. addrNext = sqlite3VdbeCurrentAddr(v);
  143211. sqlite3VdbeAddOp2(v, OP_Rowid, csr, regRowid);
  143212. sqlite3VdbeAddOp3(v, OP_Gt, pMWin->regEndRowid, lblBrk, regRowid);
  143213. VdbeCoverageNeverNull(v);
  143214. if( pMWin->eExclude==TK_CURRENT ){
  143215. sqlite3VdbeAddOp3(v, OP_Eq, regCRowid, lblNext, regRowid);
  143216. VdbeCoverageNeverNull(v);
  143217. }else if( pMWin->eExclude!=TK_NO ){
  143218. int addr;
  143219. int addrEq = 0;
  143220. KeyInfo *pKeyInfo = 0;
  143221. if( pMWin->pOrderBy ){
  143222. pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pMWin->pOrderBy, 0, 0);
  143223. }
  143224. if( pMWin->eExclude==TK_TIES ){
  143225. addrEq = sqlite3VdbeAddOp3(v, OP_Eq, regCRowid, 0, regRowid);
  143226. VdbeCoverageNeverNull(v);
  143227. }
  143228. if( pKeyInfo ){
  143229. windowReadPeerValues(p, csr, regPeer);
  143230. sqlite3VdbeAddOp3(v, OP_Compare, regPeer, regCPeer, nPeer);
  143231. sqlite3VdbeAppendP4(v, (void*)pKeyInfo, P4_KEYINFO);
  143232. addr = sqlite3VdbeCurrentAddr(v)+1;
  143233. sqlite3VdbeAddOp3(v, OP_Jump, addr, lblNext, addr);
  143234. VdbeCoverageEqNe(v);
  143235. }else{
  143236. sqlite3VdbeAddOp2(v, OP_Goto, 0, lblNext);
  143237. }
  143238. if( addrEq ) sqlite3VdbeJumpHere(v, addrEq);
  143239. }
  143240. windowAggStep(p, pMWin, csr, 0, p->regArg);
  143241. sqlite3VdbeResolveLabel(v, lblNext);
  143242. sqlite3VdbeAddOp2(v, OP_Next, csr, addrNext);
  143243. VdbeCoverage(v);
  143244. sqlite3VdbeJumpHere(v, addrNext-1);
  143245. sqlite3VdbeJumpHere(v, addrNext+1);
  143246. sqlite3ReleaseTempReg(pParse, regRowid);
  143247. sqlite3ReleaseTempReg(pParse, regCRowid);
  143248. if( nPeer ){
  143249. sqlite3ReleaseTempRange(pParse, regPeer, nPeer);
  143250. sqlite3ReleaseTempRange(pParse, regCPeer, nPeer);
  143251. }
  143252. windowAggFinal(p, 1);
  143253. VdbeModuleComment((v, "windowFullScan end"));
  143254. }
  143255. /*
  143256. ** Invoke the sub-routine at regGosub (generated by code in select.c) to
  143257. ** return the current row of Window.iEphCsr. If all window functions are
  143258. ** aggregate window functions that use the standard API, a single
  143259. ** OP_Gosub instruction is all that this routine generates. Extra VM code
  143260. ** for per-row processing is only generated for the following built-in window
  143261. ** functions:
  143262. **
  143263. ** nth_value()
  143264. ** first_value()
  143265. ** lag()
  143266. ** lead()
  143267. */
  143268. static void windowReturnOneRow(WindowCodeArg *p){
  143269. Window *pMWin = p->pMWin;
  143270. Vdbe *v = p->pVdbe;
  143271. if( pMWin->regStartRowid ){
  143272. windowFullScan(p);
  143273. }else{
  143274. Parse *pParse = p->pParse;
  143275. Window *pWin;
  143276. for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
  143277. FuncDef *pFunc = pWin->pFunc;
  143278. if( pFunc->zName==nth_valueName
  143279. || pFunc->zName==first_valueName
  143280. ){
  143281. int csr = pWin->csrApp;
  143282. int lbl = sqlite3VdbeMakeLabel(pParse);
  143283. int tmpReg = sqlite3GetTempReg(pParse);
  143284. sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regResult);
  143285. if( pFunc->zName==nth_valueName ){
  143286. sqlite3VdbeAddOp3(v, OP_Column,pMWin->iEphCsr,pWin->iArgCol+1,tmpReg);
  143287. windowCheckValue(pParse, tmpReg, 2);
  143288. }else{
  143289. sqlite3VdbeAddOp2(v, OP_Integer, 1, tmpReg);
  143290. }
  143291. sqlite3VdbeAddOp3(v, OP_Add, tmpReg, pWin->regApp, tmpReg);
  143292. sqlite3VdbeAddOp3(v, OP_Gt, pWin->regApp+1, lbl, tmpReg);
  143293. VdbeCoverageNeverNull(v);
  143294. sqlite3VdbeAddOp3(v, OP_SeekRowid, csr, 0, tmpReg);
  143295. VdbeCoverageNeverTaken(v);
  143296. sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol, pWin->regResult);
  143297. sqlite3VdbeResolveLabel(v, lbl);
  143298. sqlite3ReleaseTempReg(pParse, tmpReg);
  143299. }
  143300. else if( pFunc->zName==leadName || pFunc->zName==lagName ){
  143301. int nArg = pWin->pOwner->x.pList->nExpr;
  143302. int csr = pWin->csrApp;
  143303. int lbl = sqlite3VdbeMakeLabel(pParse);
  143304. int tmpReg = sqlite3GetTempReg(pParse);
  143305. int iEph = pMWin->iEphCsr;
  143306. if( nArg<3 ){
  143307. sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regResult);
  143308. }else{
  143309. sqlite3VdbeAddOp3(v, OP_Column, iEph,pWin->iArgCol+2,pWin->regResult);
  143310. }
  143311. sqlite3VdbeAddOp2(v, OP_Rowid, iEph, tmpReg);
  143312. if( nArg<2 ){
  143313. int val = (pFunc->zName==leadName ? 1 : -1);
  143314. sqlite3VdbeAddOp2(v, OP_AddImm, tmpReg, val);
  143315. }else{
  143316. int op = (pFunc->zName==leadName ? OP_Add : OP_Subtract);
  143317. int tmpReg2 = sqlite3GetTempReg(pParse);
  143318. sqlite3VdbeAddOp3(v, OP_Column, iEph, pWin->iArgCol+1, tmpReg2);
  143319. sqlite3VdbeAddOp3(v, op, tmpReg2, tmpReg, tmpReg);
  143320. sqlite3ReleaseTempReg(pParse, tmpReg2);
  143321. }
  143322. sqlite3VdbeAddOp3(v, OP_SeekRowid, csr, lbl, tmpReg);
  143323. VdbeCoverage(v);
  143324. sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol, pWin->regResult);
  143325. sqlite3VdbeResolveLabel(v, lbl);
  143326. sqlite3ReleaseTempReg(pParse, tmpReg);
  143327. }
  143328. }
  143329. }
  143330. sqlite3VdbeAddOp2(v, OP_Gosub, p->regGosub, p->addrGosub);
  143331. }
  143332. /*
  143333. ** Generate code to set the accumulator register for each window function
  143334. ** in the linked list passed as the second argument to NULL. And perform
  143335. ** any equivalent initialization required by any built-in window functions
  143336. ** in the list.
  143337. */
  143338. static int windowInitAccum(Parse *pParse, Window *pMWin){
  143339. Vdbe *v = sqlite3GetVdbe(pParse);
  143340. int regArg;
  143341. int nArg = 0;
  143342. Window *pWin;
  143343. for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
  143344. FuncDef *pFunc = pWin->pFunc;
  143345. assert( pWin->regAccum );
  143346. sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum);
  143347. nArg = MAX(nArg, windowArgCount(pWin));
  143348. if( pMWin->regStartRowid==0 ){
  143349. if( pFunc->zName==nth_valueName || pFunc->zName==first_valueName ){
  143350. sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp);
  143351. sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp+1);
  143352. }
  143353. if( (pFunc->funcFlags & SQLITE_FUNC_MINMAX) && pWin->csrApp ){
  143354. assert( pWin->eStart!=TK_UNBOUNDED );
  143355. sqlite3VdbeAddOp1(v, OP_ResetSorter, pWin->csrApp);
  143356. sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp+1);
  143357. }
  143358. }
  143359. }
  143360. regArg = pParse->nMem+1;
  143361. pParse->nMem += nArg;
  143362. return regArg;
  143363. }
  143364. /*
  143365. ** Return true if the current frame should be cached in the ephemeral table,
  143366. ** even if there are no xInverse() calls required.
  143367. */
  143368. static int windowCacheFrame(Window *pMWin){
  143369. Window *pWin;
  143370. if( pMWin->regStartRowid ) return 1;
  143371. for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
  143372. FuncDef *pFunc = pWin->pFunc;
  143373. if( (pFunc->zName==nth_valueName)
  143374. || (pFunc->zName==first_valueName)
  143375. || (pFunc->zName==leadName)
  143376. || (pFunc->zName==lagName)
  143377. ){
  143378. return 1;
  143379. }
  143380. }
  143381. return 0;
  143382. }
  143383. /*
  143384. ** regOld and regNew are each the first register in an array of size
  143385. ** pOrderBy->nExpr. This function generates code to compare the two
  143386. ** arrays of registers using the collation sequences and other comparison
  143387. ** parameters specified by pOrderBy.
  143388. **
  143389. ** If the two arrays are not equal, the contents of regNew is copied to
  143390. ** regOld and control falls through. Otherwise, if the contents of the arrays
  143391. ** are equal, an OP_Goto is executed. The address of the OP_Goto is returned.
  143392. */
  143393. static void windowIfNewPeer(
  143394. Parse *pParse,
  143395. ExprList *pOrderBy,
  143396. int regNew, /* First in array of new values */
  143397. int regOld, /* First in array of old values */
  143398. int addr /* Jump here */
  143399. ){
  143400. Vdbe *v = sqlite3GetVdbe(pParse);
  143401. if( pOrderBy ){
  143402. int nVal = pOrderBy->nExpr;
  143403. KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pOrderBy, 0, 0);
  143404. sqlite3VdbeAddOp3(v, OP_Compare, regOld, regNew, nVal);
  143405. sqlite3VdbeAppendP4(v, (void*)pKeyInfo, P4_KEYINFO);
  143406. sqlite3VdbeAddOp3(v, OP_Jump,
  143407. sqlite3VdbeCurrentAddr(v)+1, addr, sqlite3VdbeCurrentAddr(v)+1
  143408. );
  143409. VdbeCoverageEqNe(v);
  143410. sqlite3VdbeAddOp3(v, OP_Copy, regNew, regOld, nVal-1);
  143411. }else{
  143412. sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
  143413. }
  143414. }
  143415. /*
  143416. ** This function is called as part of generating VM programs for RANGE
  143417. ** offset PRECEDING/FOLLOWING frame boundaries. Assuming "ASC" order for
  143418. ** the ORDER BY term in the window, and that argument op is OP_Ge, it generates
  143419. ** code equivalent to:
  143420. **
  143421. ** if( csr1.peerVal + regVal >= csr2.peerVal ) goto lbl;
  143422. **
  143423. ** The value of parameter op may also be OP_Gt or OP_Le. In these cases the
  143424. ** operator in the above pseudo-code is replaced with ">" or "<=", respectively.
  143425. **
  143426. ** If the sort-order for the ORDER BY term in the window is DESC, then the
  143427. ** comparison is reversed. Instead of adding regVal to csr1.peerVal, it is
  143428. ** subtracted. And the comparison operator is inverted to - ">=" becomes "<=",
  143429. ** ">" becomes "<", and so on. So, with DESC sort order, if the argument op
  143430. ** is OP_Ge, the generated code is equivalent to:
  143431. **
  143432. ** if( csr1.peerVal - regVal <= csr2.peerVal ) goto lbl;
  143433. **
  143434. ** A special type of arithmetic is used such that if csr1.peerVal is not
  143435. ** a numeric type (real or integer), then the result of the addition addition
  143436. ** or subtraction is a a copy of csr1.peerVal.
  143437. */
  143438. static void windowCodeRangeTest(
  143439. WindowCodeArg *p,
  143440. int op, /* OP_Ge, OP_Gt, or OP_Le */
  143441. int csr1, /* Cursor number for cursor 1 */
  143442. int regVal, /* Register containing non-negative number */
  143443. int csr2, /* Cursor number for cursor 2 */
  143444. int lbl /* Jump destination if condition is true */
  143445. ){
  143446. Parse *pParse = p->pParse;
  143447. Vdbe *v = sqlite3GetVdbe(pParse);
  143448. ExprList *pOrderBy = p->pMWin->pOrderBy; /* ORDER BY clause for window */
  143449. int reg1 = sqlite3GetTempReg(pParse); /* Reg. for csr1.peerVal+regVal */
  143450. int reg2 = sqlite3GetTempReg(pParse); /* Reg. for csr2.peerVal */
  143451. int regString = ++pParse->nMem; /* Reg. for constant value '' */
  143452. int arith = OP_Add; /* OP_Add or OP_Subtract */
  143453. int addrGe; /* Jump destination */
  143454. assert( op==OP_Ge || op==OP_Gt || op==OP_Le );
  143455. assert( pOrderBy && pOrderBy->nExpr==1 );
  143456. if( pOrderBy->a[0].sortFlags & KEYINFO_ORDER_DESC ){
  143457. switch( op ){
  143458. case OP_Ge: op = OP_Le; break;
  143459. case OP_Gt: op = OP_Lt; break;
  143460. default: assert( op==OP_Le ); op = OP_Ge; break;
  143461. }
  143462. arith = OP_Subtract;
  143463. }
  143464. /* Read the peer-value from each cursor into a register */
  143465. windowReadPeerValues(p, csr1, reg1);
  143466. windowReadPeerValues(p, csr2, reg2);
  143467. VdbeModuleComment((v, "CodeRangeTest: if( R%d %s R%d %s R%d ) goto lbl",
  143468. reg1, (arith==OP_Add ? "+" : "-"), regVal,
  143469. ((op==OP_Ge) ? ">=" : (op==OP_Le) ? "<=" : (op==OP_Gt) ? ">" : "<"), reg2
  143470. ));
  143471. /* Register reg1 currently contains csr1.peerVal (the peer-value from csr1).
  143472. ** This block adds (or subtracts for DESC) the numeric value in regVal
  143473. ** from it. Or, if reg1 is not numeric (it is a NULL, a text value or a blob),
  143474. ** then leave reg1 as it is. In pseudo-code, this is implemented as:
  143475. **
  143476. ** if( reg1>='' ) goto addrGe;
  143477. ** reg1 = reg1 +/- regVal
  143478. ** addrGe:
  143479. **
  143480. ** Since all strings and blobs are greater-than-or-equal-to an empty string,
  143481. ** the add/subtract is skipped for these, as required. If reg1 is a NULL,
  143482. ** then the arithmetic is performed, but since adding or subtracting from
  143483. ** NULL is always NULL anyway, this case is handled as required too. */
  143484. sqlite3VdbeAddOp4(v, OP_String8, 0, regString, 0, "", P4_STATIC);
  143485. addrGe = sqlite3VdbeAddOp3(v, OP_Ge, regString, 0, reg1);
  143486. VdbeCoverage(v);
  143487. sqlite3VdbeAddOp3(v, arith, regVal, reg1, reg1);
  143488. sqlite3VdbeJumpHere(v, addrGe);
  143489. /* If the BIGNULL flag is set for the ORDER BY, then it is required to
  143490. ** consider NULL values to be larger than all other values, instead of
  143491. ** the usual smaller. The VDBE opcodes OP_Ge and so on do not handle this
  143492. ** (and adding that capability causes a performance regression), so
  143493. ** instead if the BIGNULL flag is set then cases where either reg1 or
  143494. ** reg2 are NULL are handled separately in the following block. The code
  143495. ** generated is equivalent to:
  143496. **
  143497. ** if( reg1 IS NULL ){
  143498. ** if( op==OP_Ge ) goto lbl;
  143499. ** if( op==OP_Gt && reg2 IS NOT NULL ) goto lbl;
  143500. ** if( op==OP_Le && reg2 IS NULL ) goto lbl;
  143501. ** }else if( reg2 IS NULL ){
  143502. ** if( op==OP_Le ) goto lbl;
  143503. ** }
  143504. **
  143505. ** Additionally, if either reg1 or reg2 are NULL but the jump to lbl is
  143506. ** not taken, control jumps over the comparison operator coded below this
  143507. ** block. */
  143508. if( pOrderBy->a[0].sortFlags & KEYINFO_ORDER_BIGNULL ){
  143509. /* This block runs if reg1 contains a NULL. */
  143510. int addr = sqlite3VdbeAddOp1(v, OP_NotNull, reg1); VdbeCoverage(v);
  143511. switch( op ){
  143512. case OP_Ge:
  143513. sqlite3VdbeAddOp2(v, OP_Goto, 0, lbl);
  143514. break;
  143515. case OP_Gt:
  143516. sqlite3VdbeAddOp2(v, OP_NotNull, reg2, lbl);
  143517. VdbeCoverage(v);
  143518. break;
  143519. case OP_Le:
  143520. sqlite3VdbeAddOp2(v, OP_IsNull, reg2, lbl);
  143521. VdbeCoverage(v);
  143522. break;
  143523. default: assert( op==OP_Lt ); /* no-op */ break;
  143524. }
  143525. sqlite3VdbeAddOp2(v, OP_Goto, 0, sqlite3VdbeCurrentAddr(v)+3);
  143526. /* This block runs if reg1 is not NULL, but reg2 is. */
  143527. sqlite3VdbeJumpHere(v, addr);
  143528. sqlite3VdbeAddOp2(v, OP_IsNull, reg2, lbl); VdbeCoverage(v);
  143529. if( op==OP_Gt || op==OP_Ge ){
  143530. sqlite3VdbeChangeP2(v, -1, sqlite3VdbeCurrentAddr(v)+1);
  143531. }
  143532. }
  143533. /* Compare registers reg2 and reg1, taking the jump if required. Note that
  143534. ** control skips over this test if the BIGNULL flag is set and either
  143535. ** reg1 or reg2 contain a NULL value. */
  143536. sqlite3VdbeAddOp3(v, op, reg2, lbl, reg1); VdbeCoverage(v);
  143537. sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
  143538. assert( op==OP_Ge || op==OP_Gt || op==OP_Lt || op==OP_Le );
  143539. testcase(op==OP_Ge); VdbeCoverageIf(v, op==OP_Ge);
  143540. testcase(op==OP_Lt); VdbeCoverageIf(v, op==OP_Lt);
  143541. testcase(op==OP_Le); VdbeCoverageIf(v, op==OP_Le);
  143542. testcase(op==OP_Gt); VdbeCoverageIf(v, op==OP_Gt);
  143543. sqlite3ReleaseTempReg(pParse, reg1);
  143544. sqlite3ReleaseTempReg(pParse, reg2);
  143545. VdbeModuleComment((v, "CodeRangeTest: end"));
  143546. }
  143547. /*
  143548. ** Helper function for sqlite3WindowCodeStep(). Each call to this function
  143549. ** generates VM code for a single RETURN_ROW, AGGSTEP or AGGINVERSE
  143550. ** operation. Refer to the header comment for sqlite3WindowCodeStep() for
  143551. ** details.
  143552. */
  143553. static int windowCodeOp(
  143554. WindowCodeArg *p, /* Context object */
  143555. int op, /* WINDOW_RETURN_ROW, AGGSTEP or AGGINVERSE */
  143556. int regCountdown, /* Register for OP_IfPos countdown */
  143557. int jumpOnEof /* Jump here if stepped cursor reaches EOF */
  143558. ){
  143559. int csr, reg;
  143560. Parse *pParse = p->pParse;
  143561. Window *pMWin = p->pMWin;
  143562. int ret = 0;
  143563. Vdbe *v = p->pVdbe;
  143564. int addrContinue = 0;
  143565. int bPeer = (pMWin->eFrmType!=TK_ROWS);
  143566. int lblDone = sqlite3VdbeMakeLabel(pParse);
  143567. int addrNextRange = 0;
  143568. /* Special case - WINDOW_AGGINVERSE is always a no-op if the frame
  143569. ** starts with UNBOUNDED PRECEDING. */
  143570. if( op==WINDOW_AGGINVERSE && pMWin->eStart==TK_UNBOUNDED ){
  143571. assert( regCountdown==0 && jumpOnEof==0 );
  143572. return 0;
  143573. }
  143574. if( regCountdown>0 ){
  143575. if( pMWin->eFrmType==TK_RANGE ){
  143576. addrNextRange = sqlite3VdbeCurrentAddr(v);
  143577. assert( op==WINDOW_AGGINVERSE || op==WINDOW_AGGSTEP );
  143578. if( op==WINDOW_AGGINVERSE ){
  143579. if( pMWin->eStart==TK_FOLLOWING ){
  143580. windowCodeRangeTest(
  143581. p, OP_Le, p->current.csr, regCountdown, p->start.csr, lblDone
  143582. );
  143583. }else{
  143584. windowCodeRangeTest(
  143585. p, OP_Ge, p->start.csr, regCountdown, p->current.csr, lblDone
  143586. );
  143587. }
  143588. }else{
  143589. windowCodeRangeTest(
  143590. p, OP_Gt, p->end.csr, regCountdown, p->current.csr, lblDone
  143591. );
  143592. }
  143593. }else{
  143594. sqlite3VdbeAddOp3(v, OP_IfPos, regCountdown, lblDone, 1);
  143595. VdbeCoverage(v);
  143596. }
  143597. }
  143598. if( op==WINDOW_RETURN_ROW && pMWin->regStartRowid==0 ){
  143599. windowAggFinal(p, 0);
  143600. }
  143601. addrContinue = sqlite3VdbeCurrentAddr(v);
  143602. /* If this is a (RANGE BETWEEN a FOLLOWING AND b FOLLOWING) or
  143603. ** (RANGE BETWEEN b PRECEDING AND a PRECEDING) frame, ensure the
  143604. ** start cursor does not advance past the end cursor within the
  143605. ** temporary table. It otherwise might, if (a>b). */
  143606. if( pMWin->eStart==pMWin->eEnd && regCountdown
  143607. && pMWin->eFrmType==TK_RANGE && op==WINDOW_AGGINVERSE
  143608. ){
  143609. int regRowid1 = sqlite3GetTempReg(pParse);
  143610. int regRowid2 = sqlite3GetTempReg(pParse);
  143611. sqlite3VdbeAddOp2(v, OP_Rowid, p->start.csr, regRowid1);
  143612. sqlite3VdbeAddOp2(v, OP_Rowid, p->end.csr, regRowid2);
  143613. sqlite3VdbeAddOp3(v, OP_Ge, regRowid2, lblDone, regRowid1);
  143614. VdbeCoverage(v);
  143615. sqlite3ReleaseTempReg(pParse, regRowid1);
  143616. sqlite3ReleaseTempReg(pParse, regRowid2);
  143617. assert( pMWin->eStart==TK_PRECEDING || pMWin->eStart==TK_FOLLOWING );
  143618. }
  143619. switch( op ){
  143620. case WINDOW_RETURN_ROW:
  143621. csr = p->current.csr;
  143622. reg = p->current.reg;
  143623. windowReturnOneRow(p);
  143624. break;
  143625. case WINDOW_AGGINVERSE:
  143626. csr = p->start.csr;
  143627. reg = p->start.reg;
  143628. if( pMWin->regStartRowid ){
  143629. assert( pMWin->regEndRowid );
  143630. sqlite3VdbeAddOp2(v, OP_AddImm, pMWin->regStartRowid, 1);
  143631. }else{
  143632. windowAggStep(p, pMWin, csr, 1, p->regArg);
  143633. }
  143634. break;
  143635. default:
  143636. assert( op==WINDOW_AGGSTEP );
  143637. csr = p->end.csr;
  143638. reg = p->end.reg;
  143639. if( pMWin->regStartRowid ){
  143640. assert( pMWin->regEndRowid );
  143641. sqlite3VdbeAddOp2(v, OP_AddImm, pMWin->regEndRowid, 1);
  143642. }else{
  143643. windowAggStep(p, pMWin, csr, 0, p->regArg);
  143644. }
  143645. break;
  143646. }
  143647. if( op==p->eDelete ){
  143648. sqlite3VdbeAddOp1(v, OP_Delete, csr);
  143649. sqlite3VdbeChangeP5(v, OPFLAG_SAVEPOSITION);
  143650. }
  143651. if( jumpOnEof ){
  143652. sqlite3VdbeAddOp2(v, OP_Next, csr, sqlite3VdbeCurrentAddr(v)+2);
  143653. VdbeCoverage(v);
  143654. ret = sqlite3VdbeAddOp0(v, OP_Goto);
  143655. }else{
  143656. sqlite3VdbeAddOp2(v, OP_Next, csr, sqlite3VdbeCurrentAddr(v)+1+bPeer);
  143657. VdbeCoverage(v);
  143658. if( bPeer ){
  143659. sqlite3VdbeAddOp2(v, OP_Goto, 0, lblDone);
  143660. }
  143661. }
  143662. if( bPeer ){
  143663. int nReg = (pMWin->pOrderBy ? pMWin->pOrderBy->nExpr : 0);
  143664. int regTmp = (nReg ? sqlite3GetTempRange(pParse, nReg) : 0);
  143665. windowReadPeerValues(p, csr, regTmp);
  143666. windowIfNewPeer(pParse, pMWin->pOrderBy, regTmp, reg, addrContinue);
  143667. sqlite3ReleaseTempRange(pParse, regTmp, nReg);
  143668. }
  143669. if( addrNextRange ){
  143670. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrNextRange);
  143671. }
  143672. sqlite3VdbeResolveLabel(v, lblDone);
  143673. return ret;
  143674. }
  143675. /*
  143676. ** Allocate and return a duplicate of the Window object indicated by the
  143677. ** third argument. Set the Window.pOwner field of the new object to
  143678. ** pOwner.
  143679. */
  143680. SQLITE_PRIVATE Window *sqlite3WindowDup(sqlite3 *db, Expr *pOwner, Window *p){
  143681. Window *pNew = 0;
  143682. if( ALWAYS(p) ){
  143683. pNew = sqlite3DbMallocZero(db, sizeof(Window));
  143684. if( pNew ){
  143685. pNew->zName = sqlite3DbStrDup(db, p->zName);
  143686. pNew->zBase = sqlite3DbStrDup(db, p->zBase);
  143687. pNew->pFilter = sqlite3ExprDup(db, p->pFilter, 0);
  143688. pNew->pFunc = p->pFunc;
  143689. pNew->pPartition = sqlite3ExprListDup(db, p->pPartition, 0);
  143690. pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, 0);
  143691. pNew->eFrmType = p->eFrmType;
  143692. pNew->eEnd = p->eEnd;
  143693. pNew->eStart = p->eStart;
  143694. pNew->eExclude = p->eExclude;
  143695. pNew->regResult = p->regResult;
  143696. pNew->regAccum = p->regAccum;
  143697. pNew->iArgCol = p->iArgCol;
  143698. pNew->iEphCsr = p->iEphCsr;
  143699. pNew->bExprArgs = p->bExprArgs;
  143700. pNew->pStart = sqlite3ExprDup(db, p->pStart, 0);
  143701. pNew->pEnd = sqlite3ExprDup(db, p->pEnd, 0);
  143702. pNew->pOwner = pOwner;
  143703. pNew->bImplicitFrame = p->bImplicitFrame;
  143704. }
  143705. }
  143706. return pNew;
  143707. }
  143708. /*
  143709. ** Return a copy of the linked list of Window objects passed as the
  143710. ** second argument.
  143711. */
  143712. SQLITE_PRIVATE Window *sqlite3WindowListDup(sqlite3 *db, Window *p){
  143713. Window *pWin;
  143714. Window *pRet = 0;
  143715. Window **pp = &pRet;
  143716. for(pWin=p; pWin; pWin=pWin->pNextWin){
  143717. *pp = sqlite3WindowDup(db, 0, pWin);
  143718. if( *pp==0 ) break;
  143719. pp = &((*pp)->pNextWin);
  143720. }
  143721. return pRet;
  143722. }
  143723. /*
  143724. ** Return true if it can be determined at compile time that expression
  143725. ** pExpr evaluates to a value that, when cast to an integer, is greater
  143726. ** than zero. False otherwise.
  143727. **
  143728. ** If an OOM error occurs, this function sets the Parse.db.mallocFailed
  143729. ** flag and returns zero.
  143730. */
  143731. static int windowExprGtZero(Parse *pParse, Expr *pExpr){
  143732. int ret = 0;
  143733. sqlite3 *db = pParse->db;
  143734. sqlite3_value *pVal = 0;
  143735. sqlite3ValueFromExpr(db, pExpr, db->enc, SQLITE_AFF_NUMERIC, &pVal);
  143736. if( pVal && sqlite3_value_int(pVal)>0 ){
  143737. ret = 1;
  143738. }
  143739. sqlite3ValueFree(pVal);
  143740. return ret;
  143741. }
  143742. /*
  143743. ** sqlite3WhereBegin() has already been called for the SELECT statement
  143744. ** passed as the second argument when this function is invoked. It generates
  143745. ** code to populate the Window.regResult register for each window function
  143746. ** and invoke the sub-routine at instruction addrGosub once for each row.
  143747. ** sqlite3WhereEnd() is always called before returning.
  143748. **
  143749. ** This function handles several different types of window frames, which
  143750. ** require slightly different processing. The following pseudo code is
  143751. ** used to implement window frames of the form:
  143752. **
  143753. ** ROWS BETWEEN <expr1> PRECEDING AND <expr2> FOLLOWING
  143754. **
  143755. ** Other window frame types use variants of the following:
  143756. **
  143757. ** ... loop started by sqlite3WhereBegin() ...
  143758. ** if( new partition ){
  143759. ** Gosub flush
  143760. ** }
  143761. ** Insert new row into eph table.
  143762. **
  143763. ** if( first row of partition ){
  143764. ** // Rewind three cursors, all open on the eph table.
  143765. ** Rewind(csrEnd);
  143766. ** Rewind(csrStart);
  143767. ** Rewind(csrCurrent);
  143768. **
  143769. ** regEnd = <expr2> // FOLLOWING expression
  143770. ** regStart = <expr1> // PRECEDING expression
  143771. ** }else{
  143772. ** // First time this branch is taken, the eph table contains two
  143773. ** // rows. The first row in the partition, which all three cursors
  143774. ** // currently point to, and the following row.
  143775. ** AGGSTEP
  143776. ** if( (regEnd--)<=0 ){
  143777. ** RETURN_ROW
  143778. ** if( (regStart--)<=0 ){
  143779. ** AGGINVERSE
  143780. ** }
  143781. ** }
  143782. ** }
  143783. ** }
  143784. ** flush:
  143785. ** AGGSTEP
  143786. ** while( 1 ){
  143787. ** RETURN ROW
  143788. ** if( csrCurrent is EOF ) break;
  143789. ** if( (regStart--)<=0 ){
  143790. ** AggInverse(csrStart)
  143791. ** Next(csrStart)
  143792. ** }
  143793. ** }
  143794. **
  143795. ** The pseudo-code above uses the following shorthand:
  143796. **
  143797. ** AGGSTEP: invoke the aggregate xStep() function for each window function
  143798. ** with arguments read from the current row of cursor csrEnd, then
  143799. ** step cursor csrEnd forward one row (i.e. sqlite3BtreeNext()).
  143800. **
  143801. ** RETURN_ROW: return a row to the caller based on the contents of the
  143802. ** current row of csrCurrent and the current state of all
  143803. ** aggregates. Then step cursor csrCurrent forward one row.
  143804. **
  143805. ** AGGINVERSE: invoke the aggregate xInverse() function for each window
  143806. ** functions with arguments read from the current row of cursor
  143807. ** csrStart. Then step csrStart forward one row.
  143808. **
  143809. ** There are two other ROWS window frames that are handled significantly
  143810. ** differently from the above - "BETWEEN <expr> PRECEDING AND <expr> PRECEDING"
  143811. ** and "BETWEEN <expr> FOLLOWING AND <expr> FOLLOWING". These are special
  143812. ** cases because they change the order in which the three cursors (csrStart,
  143813. ** csrCurrent and csrEnd) iterate through the ephemeral table. Cases that
  143814. ** use UNBOUNDED or CURRENT ROW are much simpler variations on one of these
  143815. ** three.
  143816. **
  143817. ** ROWS BETWEEN <expr1> PRECEDING AND <expr2> PRECEDING
  143818. **
  143819. ** ... loop started by sqlite3WhereBegin() ...
  143820. ** if( new partition ){
  143821. ** Gosub flush
  143822. ** }
  143823. ** Insert new row into eph table.
  143824. ** if( first row of partition ){
  143825. ** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
  143826. ** regEnd = <expr2>
  143827. ** regStart = <expr1>
  143828. ** }else{
  143829. ** if( (regEnd--)<=0 ){
  143830. ** AGGSTEP
  143831. ** }
  143832. ** RETURN_ROW
  143833. ** if( (regStart--)<=0 ){
  143834. ** AGGINVERSE
  143835. ** }
  143836. ** }
  143837. ** }
  143838. ** flush:
  143839. ** if( (regEnd--)<=0 ){
  143840. ** AGGSTEP
  143841. ** }
  143842. ** RETURN_ROW
  143843. **
  143844. **
  143845. ** ROWS BETWEEN <expr1> FOLLOWING AND <expr2> FOLLOWING
  143846. **
  143847. ** ... loop started by sqlite3WhereBegin() ...
  143848. ** if( new partition ){
  143849. ** Gosub flush
  143850. ** }
  143851. ** Insert new row into eph table.
  143852. ** if( first row of partition ){
  143853. ** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
  143854. ** regEnd = <expr2>
  143855. ** regStart = regEnd - <expr1>
  143856. ** }else{
  143857. ** AGGSTEP
  143858. ** if( (regEnd--)<=0 ){
  143859. ** RETURN_ROW
  143860. ** }
  143861. ** if( (regStart--)<=0 ){
  143862. ** AGGINVERSE
  143863. ** }
  143864. ** }
  143865. ** }
  143866. ** flush:
  143867. ** AGGSTEP
  143868. ** while( 1 ){
  143869. ** if( (regEnd--)<=0 ){
  143870. ** RETURN_ROW
  143871. ** if( eof ) break;
  143872. ** }
  143873. ** if( (regStart--)<=0 ){
  143874. ** AGGINVERSE
  143875. ** if( eof ) break
  143876. ** }
  143877. ** }
  143878. ** while( !eof csrCurrent ){
  143879. ** RETURN_ROW
  143880. ** }
  143881. **
  143882. ** For the most part, the patterns above are adapted to support UNBOUNDED by
  143883. ** assuming that it is equivalent to "infinity PRECEDING/FOLLOWING" and
  143884. ** CURRENT ROW by assuming that it is equivilent to "0 PRECEDING/FOLLOWING".
  143885. ** This is optimized of course - branches that will never be taken and
  143886. ** conditions that are always true are omitted from the VM code. The only
  143887. ** exceptional case is:
  143888. **
  143889. ** ROWS BETWEEN <expr1> FOLLOWING AND UNBOUNDED FOLLOWING
  143890. **
  143891. ** ... loop started by sqlite3WhereBegin() ...
  143892. ** if( new partition ){
  143893. ** Gosub flush
  143894. ** }
  143895. ** Insert new row into eph table.
  143896. ** if( first row of partition ){
  143897. ** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
  143898. ** regStart = <expr1>
  143899. ** }else{
  143900. ** AGGSTEP
  143901. ** }
  143902. ** }
  143903. ** flush:
  143904. ** AGGSTEP
  143905. ** while( 1 ){
  143906. ** if( (regStart--)<=0 ){
  143907. ** AGGINVERSE
  143908. ** if( eof ) break
  143909. ** }
  143910. ** RETURN_ROW
  143911. ** }
  143912. ** while( !eof csrCurrent ){
  143913. ** RETURN_ROW
  143914. ** }
  143915. **
  143916. ** Also requiring special handling are the cases:
  143917. **
  143918. ** ROWS BETWEEN <expr1> PRECEDING AND <expr2> PRECEDING
  143919. ** ROWS BETWEEN <expr1> FOLLOWING AND <expr2> FOLLOWING
  143920. **
  143921. ** when (expr1 < expr2). This is detected at runtime, not by this function.
  143922. ** To handle this case, the pseudo-code programs depicted above are modified
  143923. ** slightly to be:
  143924. **
  143925. ** ... loop started by sqlite3WhereBegin() ...
  143926. ** if( new partition ){
  143927. ** Gosub flush
  143928. ** }
  143929. ** Insert new row into eph table.
  143930. ** if( first row of partition ){
  143931. ** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
  143932. ** regEnd = <expr2>
  143933. ** regStart = <expr1>
  143934. ** if( regEnd < regStart ){
  143935. ** RETURN_ROW
  143936. ** delete eph table contents
  143937. ** continue
  143938. ** }
  143939. ** ...
  143940. **
  143941. ** The new "continue" statement in the above jumps to the next iteration
  143942. ** of the outer loop - the one started by sqlite3WhereBegin().
  143943. **
  143944. ** The various GROUPS cases are implemented using the same patterns as
  143945. ** ROWS. The VM code is modified slightly so that:
  143946. **
  143947. ** 1. The else branch in the main loop is only taken if the row just
  143948. ** added to the ephemeral table is the start of a new group. In
  143949. ** other words, it becomes:
  143950. **
  143951. ** ... loop started by sqlite3WhereBegin() ...
  143952. ** if( new partition ){
  143953. ** Gosub flush
  143954. ** }
  143955. ** Insert new row into eph table.
  143956. ** if( first row of partition ){
  143957. ** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
  143958. ** regEnd = <expr2>
  143959. ** regStart = <expr1>
  143960. ** }else if( new group ){
  143961. ** ...
  143962. ** }
  143963. ** }
  143964. **
  143965. ** 2. Instead of processing a single row, each RETURN_ROW, AGGSTEP or
  143966. ** AGGINVERSE step processes the current row of the relevant cursor and
  143967. ** all subsequent rows belonging to the same group.
  143968. **
  143969. ** RANGE window frames are a little different again. As for GROUPS, the
  143970. ** main loop runs once per group only. And RETURN_ROW, AGGSTEP and AGGINVERSE
  143971. ** deal in groups instead of rows. As for ROWS and GROUPS, there are three
  143972. ** basic cases:
  143973. **
  143974. ** RANGE BETWEEN <expr1> PRECEDING AND <expr2> FOLLOWING
  143975. **
  143976. ** ... loop started by sqlite3WhereBegin() ...
  143977. ** if( new partition ){
  143978. ** Gosub flush
  143979. ** }
  143980. ** Insert new row into eph table.
  143981. ** if( first row of partition ){
  143982. ** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
  143983. ** regEnd = <expr2>
  143984. ** regStart = <expr1>
  143985. ** }else{
  143986. ** AGGSTEP
  143987. ** while( (csrCurrent.key + regEnd) < csrEnd.key ){
  143988. ** RETURN_ROW
  143989. ** while( csrStart.key + regStart) < csrCurrent.key ){
  143990. ** AGGINVERSE
  143991. ** }
  143992. ** }
  143993. ** }
  143994. ** }
  143995. ** flush:
  143996. ** AGGSTEP
  143997. ** while( 1 ){
  143998. ** RETURN ROW
  143999. ** if( csrCurrent is EOF ) break;
  144000. ** while( csrStart.key + regStart) < csrCurrent.key ){
  144001. ** AGGINVERSE
  144002. ** }
  144003. ** }
  144004. ** }
  144005. **
  144006. ** In the above notation, "csr.key" means the current value of the ORDER BY
  144007. ** expression (there is only ever 1 for a RANGE that uses an <expr> FOLLOWING
  144008. ** or <expr PRECEDING) read from cursor csr.
  144009. **
  144010. ** RANGE BETWEEN <expr1> PRECEDING AND <expr2> PRECEDING
  144011. **
  144012. ** ... loop started by sqlite3WhereBegin() ...
  144013. ** if( new partition ){
  144014. ** Gosub flush
  144015. ** }
  144016. ** Insert new row into eph table.
  144017. ** if( first row of partition ){
  144018. ** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
  144019. ** regEnd = <expr2>
  144020. ** regStart = <expr1>
  144021. ** }else{
  144022. ** while( (csrEnd.key + regEnd) <= csrCurrent.key ){
  144023. ** AGGSTEP
  144024. ** }
  144025. ** while( (csrStart.key + regStart) < csrCurrent.key ){
  144026. ** AGGINVERSE
  144027. ** }
  144028. ** RETURN_ROW
  144029. ** }
  144030. ** }
  144031. ** flush:
  144032. ** while( (csrEnd.key + regEnd) <= csrCurrent.key ){
  144033. ** AGGSTEP
  144034. ** }
  144035. ** while( (csrStart.key + regStart) < csrCurrent.key ){
  144036. ** AGGINVERSE
  144037. ** }
  144038. ** RETURN_ROW
  144039. **
  144040. ** RANGE BETWEEN <expr1> FOLLOWING AND <expr2> FOLLOWING
  144041. **
  144042. ** ... loop started by sqlite3WhereBegin() ...
  144043. ** if( new partition ){
  144044. ** Gosub flush
  144045. ** }
  144046. ** Insert new row into eph table.
  144047. ** if( first row of partition ){
  144048. ** Rewind(csrEnd) ; Rewind(csrStart) ; Rewind(csrCurrent)
  144049. ** regEnd = <expr2>
  144050. ** regStart = <expr1>
  144051. ** }else{
  144052. ** AGGSTEP
  144053. ** while( (csrCurrent.key + regEnd) < csrEnd.key ){
  144054. ** while( (csrCurrent.key + regStart) > csrStart.key ){
  144055. ** AGGINVERSE
  144056. ** }
  144057. ** RETURN_ROW
  144058. ** }
  144059. ** }
  144060. ** }
  144061. ** flush:
  144062. ** AGGSTEP
  144063. ** while( 1 ){
  144064. ** while( (csrCurrent.key + regStart) > csrStart.key ){
  144065. ** AGGINVERSE
  144066. ** if( eof ) break "while( 1 )" loop.
  144067. ** }
  144068. ** RETURN_ROW
  144069. ** }
  144070. ** while( !eof csrCurrent ){
  144071. ** RETURN_ROW
  144072. ** }
  144073. **
  144074. ** The text above leaves out many details. Refer to the code and comments
  144075. ** below for a more complete picture.
  144076. */
  144077. SQLITE_PRIVATE void sqlite3WindowCodeStep(
  144078. Parse *pParse, /* Parse context */
  144079. Select *p, /* Rewritten SELECT statement */
  144080. WhereInfo *pWInfo, /* Context returned by sqlite3WhereBegin() */
  144081. int regGosub, /* Register for OP_Gosub */
  144082. int addrGosub /* OP_Gosub here to return each row */
  144083. ){
  144084. Window *pMWin = p->pWin;
  144085. ExprList *pOrderBy = pMWin->pOrderBy;
  144086. Vdbe *v = sqlite3GetVdbe(pParse);
  144087. int csrWrite; /* Cursor used to write to eph. table */
  144088. int csrInput = p->pSrc->a[0].iCursor; /* Cursor of sub-select */
  144089. int nInput = p->pSrc->a[0].pTab->nCol; /* Number of cols returned by sub */
  144090. int iInput; /* To iterate through sub cols */
  144091. int addrNe; /* Address of OP_Ne */
  144092. int addrGosubFlush = 0; /* Address of OP_Gosub to flush: */
  144093. int addrInteger = 0; /* Address of OP_Integer */
  144094. int addrEmpty; /* Address of OP_Rewind in flush: */
  144095. int regNew; /* Array of registers holding new input row */
  144096. int regRecord; /* regNew array in record form */
  144097. int regRowid; /* Rowid for regRecord in eph table */
  144098. int regNewPeer = 0; /* Peer values for new row (part of regNew) */
  144099. int regPeer = 0; /* Peer values for current row */
  144100. int regFlushPart = 0; /* Register for "Gosub flush_partition" */
  144101. WindowCodeArg s; /* Context object for sub-routines */
  144102. int lblWhereEnd; /* Label just before sqlite3WhereEnd() code */
  144103. int regStart = 0; /* Value of <expr> PRECEDING */
  144104. int regEnd = 0; /* Value of <expr> FOLLOWING */
  144105. assert( pMWin->eStart==TK_PRECEDING || pMWin->eStart==TK_CURRENT
  144106. || pMWin->eStart==TK_FOLLOWING || pMWin->eStart==TK_UNBOUNDED
  144107. );
  144108. assert( pMWin->eEnd==TK_FOLLOWING || pMWin->eEnd==TK_CURRENT
  144109. || pMWin->eEnd==TK_UNBOUNDED || pMWin->eEnd==TK_PRECEDING
  144110. );
  144111. assert( pMWin->eExclude==0 || pMWin->eExclude==TK_CURRENT
  144112. || pMWin->eExclude==TK_GROUP || pMWin->eExclude==TK_TIES
  144113. || pMWin->eExclude==TK_NO
  144114. );
  144115. lblWhereEnd = sqlite3VdbeMakeLabel(pParse);
  144116. /* Fill in the context object */
  144117. memset(&s, 0, sizeof(WindowCodeArg));
  144118. s.pParse = pParse;
  144119. s.pMWin = pMWin;
  144120. s.pVdbe = v;
  144121. s.regGosub = regGosub;
  144122. s.addrGosub = addrGosub;
  144123. s.current.csr = pMWin->iEphCsr;
  144124. csrWrite = s.current.csr+1;
  144125. s.start.csr = s.current.csr+2;
  144126. s.end.csr = s.current.csr+3;
  144127. /* Figure out when rows may be deleted from the ephemeral table. There
  144128. ** are four options - they may never be deleted (eDelete==0), they may
  144129. ** be deleted as soon as they are no longer part of the window frame
  144130. ** (eDelete==WINDOW_AGGINVERSE), they may be deleted as after the row
  144131. ** has been returned to the caller (WINDOW_RETURN_ROW), or they may
  144132. ** be deleted after they enter the frame (WINDOW_AGGSTEP). */
  144133. switch( pMWin->eStart ){
  144134. case TK_FOLLOWING:
  144135. if( pMWin->eFrmType!=TK_RANGE
  144136. && windowExprGtZero(pParse, pMWin->pStart)
  144137. ){
  144138. s.eDelete = WINDOW_RETURN_ROW;
  144139. }
  144140. break;
  144141. case TK_UNBOUNDED:
  144142. if( windowCacheFrame(pMWin)==0 ){
  144143. if( pMWin->eEnd==TK_PRECEDING ){
  144144. if( pMWin->eFrmType!=TK_RANGE
  144145. && windowExprGtZero(pParse, pMWin->pEnd)
  144146. ){
  144147. s.eDelete = WINDOW_AGGSTEP;
  144148. }
  144149. }else{
  144150. s.eDelete = WINDOW_RETURN_ROW;
  144151. }
  144152. }
  144153. break;
  144154. default:
  144155. s.eDelete = WINDOW_AGGINVERSE;
  144156. break;
  144157. }
  144158. /* Allocate registers for the array of values from the sub-query, the
  144159. ** samve values in record form, and the rowid used to insert said record
  144160. ** into the ephemeral table. */
  144161. regNew = pParse->nMem+1;
  144162. pParse->nMem += nInput;
  144163. regRecord = ++pParse->nMem;
  144164. regRowid = ++pParse->nMem;
  144165. /* If the window frame contains an "<expr> PRECEDING" or "<expr> FOLLOWING"
  144166. ** clause, allocate registers to store the results of evaluating each
  144167. ** <expr>. */
  144168. if( pMWin->eStart==TK_PRECEDING || pMWin->eStart==TK_FOLLOWING ){
  144169. regStart = ++pParse->nMem;
  144170. }
  144171. if( pMWin->eEnd==TK_PRECEDING || pMWin->eEnd==TK_FOLLOWING ){
  144172. regEnd = ++pParse->nMem;
  144173. }
  144174. /* If this is not a "ROWS BETWEEN ..." frame, then allocate arrays of
  144175. ** registers to store copies of the ORDER BY expressions (peer values)
  144176. ** for the main loop, and for each cursor (start, current and end). */
  144177. if( pMWin->eFrmType!=TK_ROWS ){
  144178. int nPeer = (pOrderBy ? pOrderBy->nExpr : 0);
  144179. regNewPeer = regNew + pMWin->nBufferCol;
  144180. if( pMWin->pPartition ) regNewPeer += pMWin->pPartition->nExpr;
  144181. regPeer = pParse->nMem+1; pParse->nMem += nPeer;
  144182. s.start.reg = pParse->nMem+1; pParse->nMem += nPeer;
  144183. s.current.reg = pParse->nMem+1; pParse->nMem += nPeer;
  144184. s.end.reg = pParse->nMem+1; pParse->nMem += nPeer;
  144185. }
  144186. /* Load the column values for the row returned by the sub-select
  144187. ** into an array of registers starting at regNew. Assemble them into
  144188. ** a record in register regRecord. */
  144189. for(iInput=0; iInput<nInput; iInput++){
  144190. sqlite3VdbeAddOp3(v, OP_Column, csrInput, iInput, regNew+iInput);
  144191. }
  144192. sqlite3VdbeAddOp3(v, OP_MakeRecord, regNew, nInput, regRecord);
  144193. /* An input row has just been read into an array of registers starting
  144194. ** at regNew. If the window has a PARTITION clause, this block generates
  144195. ** VM code to check if the input row is the start of a new partition.
  144196. ** If so, it does an OP_Gosub to an address to be filled in later. The
  144197. ** address of the OP_Gosub is stored in local variable addrGosubFlush. */
  144198. if( pMWin->pPartition ){
  144199. int addr;
  144200. ExprList *pPart = pMWin->pPartition;
  144201. int nPart = pPart->nExpr;
  144202. int regNewPart = regNew + pMWin->nBufferCol;
  144203. KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pPart, 0, 0);
  144204. regFlushPart = ++pParse->nMem;
  144205. addr = sqlite3VdbeAddOp3(v, OP_Compare, regNewPart, pMWin->regPart, nPart);
  144206. sqlite3VdbeAppendP4(v, (void*)pKeyInfo, P4_KEYINFO);
  144207. sqlite3VdbeAddOp3(v, OP_Jump, addr+2, addr+4, addr+2);
  144208. VdbeCoverageEqNe(v);
  144209. addrGosubFlush = sqlite3VdbeAddOp1(v, OP_Gosub, regFlushPart);
  144210. VdbeComment((v, "call flush_partition"));
  144211. sqlite3VdbeAddOp3(v, OP_Copy, regNewPart, pMWin->regPart, nPart-1);
  144212. }
  144213. /* Insert the new row into the ephemeral table */
  144214. sqlite3VdbeAddOp2(v, OP_NewRowid, csrWrite, regRowid);
  144215. sqlite3VdbeAddOp3(v, OP_Insert, csrWrite, regRecord, regRowid);
  144216. addrNe = sqlite3VdbeAddOp3(v, OP_Ne, pMWin->regOne, 0, regRowid);
  144217. VdbeCoverageNeverNull(v);
  144218. /* This block is run for the first row of each partition */
  144219. s.regArg = windowInitAccum(pParse, pMWin);
  144220. if( regStart ){
  144221. sqlite3ExprCode(pParse, pMWin->pStart, regStart);
  144222. windowCheckValue(pParse, regStart, 0 + (pMWin->eFrmType==TK_RANGE?3:0));
  144223. }
  144224. if( regEnd ){
  144225. sqlite3ExprCode(pParse, pMWin->pEnd, regEnd);
  144226. windowCheckValue(pParse, regEnd, 1 + (pMWin->eFrmType==TK_RANGE?3:0));
  144227. }
  144228. if( pMWin->eFrmType!=TK_RANGE && pMWin->eStart==pMWin->eEnd && regStart ){
  144229. int op = ((pMWin->eStart==TK_FOLLOWING) ? OP_Ge : OP_Le);
  144230. int addrGe = sqlite3VdbeAddOp3(v, op, regStart, 0, regEnd);
  144231. VdbeCoverageNeverNullIf(v, op==OP_Ge); /* NeverNull because bound <expr> */
  144232. VdbeCoverageNeverNullIf(v, op==OP_Le); /* values previously checked */
  144233. windowAggFinal(&s, 0);
  144234. sqlite3VdbeAddOp2(v, OP_Rewind, s.current.csr, 1);
  144235. VdbeCoverageNeverTaken(v);
  144236. windowReturnOneRow(&s);
  144237. sqlite3VdbeAddOp1(v, OP_ResetSorter, s.current.csr);
  144238. sqlite3VdbeAddOp2(v, OP_Goto, 0, lblWhereEnd);
  144239. sqlite3VdbeJumpHere(v, addrGe);
  144240. }
  144241. if( pMWin->eStart==TK_FOLLOWING && pMWin->eFrmType!=TK_RANGE && regEnd ){
  144242. assert( pMWin->eEnd==TK_FOLLOWING );
  144243. sqlite3VdbeAddOp3(v, OP_Subtract, regStart, regEnd, regStart);
  144244. }
  144245. if( pMWin->eStart!=TK_UNBOUNDED ){
  144246. sqlite3VdbeAddOp2(v, OP_Rewind, s.start.csr, 1);
  144247. VdbeCoverageNeverTaken(v);
  144248. }
  144249. sqlite3VdbeAddOp2(v, OP_Rewind, s.current.csr, 1);
  144250. VdbeCoverageNeverTaken(v);
  144251. sqlite3VdbeAddOp2(v, OP_Rewind, s.end.csr, 1);
  144252. VdbeCoverageNeverTaken(v);
  144253. if( regPeer && pOrderBy ){
  144254. sqlite3VdbeAddOp3(v, OP_Copy, regNewPeer, regPeer, pOrderBy->nExpr-1);
  144255. sqlite3VdbeAddOp3(v, OP_Copy, regPeer, s.start.reg, pOrderBy->nExpr-1);
  144256. sqlite3VdbeAddOp3(v, OP_Copy, regPeer, s.current.reg, pOrderBy->nExpr-1);
  144257. sqlite3VdbeAddOp3(v, OP_Copy, regPeer, s.end.reg, pOrderBy->nExpr-1);
  144258. }
  144259. sqlite3VdbeAddOp2(v, OP_Goto, 0, lblWhereEnd);
  144260. sqlite3VdbeJumpHere(v, addrNe);
  144261. /* Beginning of the block executed for the second and subsequent rows. */
  144262. if( regPeer ){
  144263. windowIfNewPeer(pParse, pOrderBy, regNewPeer, regPeer, lblWhereEnd);
  144264. }
  144265. if( pMWin->eStart==TK_FOLLOWING ){
  144266. windowCodeOp(&s, WINDOW_AGGSTEP, 0, 0);
  144267. if( pMWin->eEnd!=TK_UNBOUNDED ){
  144268. if( pMWin->eFrmType==TK_RANGE ){
  144269. int lbl = sqlite3VdbeMakeLabel(pParse);
  144270. int addrNext = sqlite3VdbeCurrentAddr(v);
  144271. windowCodeRangeTest(&s, OP_Ge, s.current.csr, regEnd, s.end.csr, lbl);
  144272. windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
  144273. windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0);
  144274. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrNext);
  144275. sqlite3VdbeResolveLabel(v, lbl);
  144276. }else{
  144277. windowCodeOp(&s, WINDOW_RETURN_ROW, regEnd, 0);
  144278. windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
  144279. }
  144280. }
  144281. }else
  144282. if( pMWin->eEnd==TK_PRECEDING ){
  144283. int bRPS = (pMWin->eStart==TK_PRECEDING && pMWin->eFrmType==TK_RANGE);
  144284. windowCodeOp(&s, WINDOW_AGGSTEP, regEnd, 0);
  144285. if( bRPS ) windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
  144286. windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0);
  144287. if( !bRPS ) windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
  144288. }else{
  144289. int addr = 0;
  144290. windowCodeOp(&s, WINDOW_AGGSTEP, 0, 0);
  144291. if( pMWin->eEnd!=TK_UNBOUNDED ){
  144292. if( pMWin->eFrmType==TK_RANGE ){
  144293. int lbl = 0;
  144294. addr = sqlite3VdbeCurrentAddr(v);
  144295. if( regEnd ){
  144296. lbl = sqlite3VdbeMakeLabel(pParse);
  144297. windowCodeRangeTest(&s, OP_Ge, s.current.csr, regEnd, s.end.csr, lbl);
  144298. }
  144299. windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0);
  144300. windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
  144301. if( regEnd ){
  144302. sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
  144303. sqlite3VdbeResolveLabel(v, lbl);
  144304. }
  144305. }else{
  144306. if( regEnd ){
  144307. addr = sqlite3VdbeAddOp3(v, OP_IfPos, regEnd, 0, 1);
  144308. VdbeCoverage(v);
  144309. }
  144310. windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0);
  144311. windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
  144312. if( regEnd ) sqlite3VdbeJumpHere(v, addr);
  144313. }
  144314. }
  144315. }
  144316. /* End of the main input loop */
  144317. sqlite3VdbeResolveLabel(v, lblWhereEnd);
  144318. sqlite3WhereEnd(pWInfo);
  144319. /* Fall through */
  144320. if( pMWin->pPartition ){
  144321. addrInteger = sqlite3VdbeAddOp2(v, OP_Integer, 0, regFlushPart);
  144322. sqlite3VdbeJumpHere(v, addrGosubFlush);
  144323. }
  144324. addrEmpty = sqlite3VdbeAddOp1(v, OP_Rewind, csrWrite);
  144325. VdbeCoverage(v);
  144326. if( pMWin->eEnd==TK_PRECEDING ){
  144327. int bRPS = (pMWin->eStart==TK_PRECEDING && pMWin->eFrmType==TK_RANGE);
  144328. windowCodeOp(&s, WINDOW_AGGSTEP, regEnd, 0);
  144329. if( bRPS ) windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
  144330. windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 0);
  144331. }else if( pMWin->eStart==TK_FOLLOWING ){
  144332. int addrStart;
  144333. int addrBreak1;
  144334. int addrBreak2;
  144335. int addrBreak3;
  144336. windowCodeOp(&s, WINDOW_AGGSTEP, 0, 0);
  144337. if( pMWin->eFrmType==TK_RANGE ){
  144338. addrStart = sqlite3VdbeCurrentAddr(v);
  144339. addrBreak2 = windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 1);
  144340. addrBreak1 = windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 1);
  144341. }else
  144342. if( pMWin->eEnd==TK_UNBOUNDED ){
  144343. addrStart = sqlite3VdbeCurrentAddr(v);
  144344. addrBreak1 = windowCodeOp(&s, WINDOW_RETURN_ROW, regStart, 1);
  144345. addrBreak2 = windowCodeOp(&s, WINDOW_AGGINVERSE, 0, 1);
  144346. }else{
  144347. assert( pMWin->eEnd==TK_FOLLOWING );
  144348. addrStart = sqlite3VdbeCurrentAddr(v);
  144349. addrBreak1 = windowCodeOp(&s, WINDOW_RETURN_ROW, regEnd, 1);
  144350. addrBreak2 = windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 1);
  144351. }
  144352. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrStart);
  144353. sqlite3VdbeJumpHere(v, addrBreak2);
  144354. addrStart = sqlite3VdbeCurrentAddr(v);
  144355. addrBreak3 = windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 1);
  144356. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrStart);
  144357. sqlite3VdbeJumpHere(v, addrBreak1);
  144358. sqlite3VdbeJumpHere(v, addrBreak3);
  144359. }else{
  144360. int addrBreak;
  144361. int addrStart;
  144362. windowCodeOp(&s, WINDOW_AGGSTEP, 0, 0);
  144363. addrStart = sqlite3VdbeCurrentAddr(v);
  144364. addrBreak = windowCodeOp(&s, WINDOW_RETURN_ROW, 0, 1);
  144365. windowCodeOp(&s, WINDOW_AGGINVERSE, regStart, 0);
  144366. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrStart);
  144367. sqlite3VdbeJumpHere(v, addrBreak);
  144368. }
  144369. sqlite3VdbeJumpHere(v, addrEmpty);
  144370. sqlite3VdbeAddOp1(v, OP_ResetSorter, s.current.csr);
  144371. if( pMWin->pPartition ){
  144372. if( pMWin->regStartRowid ){
  144373. sqlite3VdbeAddOp2(v, OP_Integer, 1, pMWin->regStartRowid);
  144374. sqlite3VdbeAddOp2(v, OP_Integer, 0, pMWin->regEndRowid);
  144375. }
  144376. sqlite3VdbeChangeP1(v, addrInteger, sqlite3VdbeCurrentAddr(v));
  144377. sqlite3VdbeAddOp1(v, OP_Return, regFlushPart);
  144378. }
  144379. }
  144380. #endif /* SQLITE_OMIT_WINDOWFUNC */
  144381. /************** End of window.c **********************************************/
  144382. /************** Begin file parse.c *******************************************/
  144383. /*
  144384. ** 2000-05-29
  144385. **
  144386. ** The author disclaims copyright to this source code. In place of
  144387. ** a legal notice, here is a blessing:
  144388. **
  144389. ** May you do good and not evil.
  144390. ** May you find forgiveness for yourself and forgive others.
  144391. ** May you share freely, never taking more than you give.
  144392. **
  144393. *************************************************************************
  144394. ** Driver template for the LEMON parser generator.
  144395. **
  144396. ** The "lemon" program processes an LALR(1) input grammar file, then uses
  144397. ** this template to construct a parser. The "lemon" program inserts text
  144398. ** at each "%%" line. Also, any "P-a-r-s-e" identifer prefix (without the
  144399. ** interstitial "-" characters) contained in this template is changed into
  144400. ** the value of the %name directive from the grammar. Otherwise, the content
  144401. ** of this template is copied straight through into the generate parser
  144402. ** source file.
  144403. **
  144404. ** The following is the concatenation of all %include directives from the
  144405. ** input grammar file:
  144406. */
  144407. /* #include <stdio.h> */
  144408. /* #include <assert.h> */
  144409. /************ Begin %include sections from the grammar ************************/
  144410. /* #include "sqliteInt.h" */
  144411. /*
  144412. ** Disable all error recovery processing in the parser push-down
  144413. ** automaton.
  144414. */
  144415. #define YYNOERRORRECOVERY 1
  144416. /*
  144417. ** Make yytestcase() the same as testcase()
  144418. */
  144419. #define yytestcase(X) testcase(X)
  144420. /*
  144421. ** Indicate that sqlite3ParserFree() will never be called with a null
  144422. ** pointer.
  144423. */
  144424. #define YYPARSEFREENEVERNULL 1
  144425. /*
  144426. ** In the amalgamation, the parse.c file generated by lemon and the
  144427. ** tokenize.c file are concatenated. In that case, sqlite3RunParser()
  144428. ** has access to the the size of the yyParser object and so the parser
  144429. ** engine can be allocated from stack. In that case, only the
  144430. ** sqlite3ParserInit() and sqlite3ParserFinalize() routines are invoked
  144431. ** and the sqlite3ParserAlloc() and sqlite3ParserFree() routines can be
  144432. ** omitted.
  144433. */
  144434. #ifdef SQLITE_AMALGAMATION
  144435. # define sqlite3Parser_ENGINEALWAYSONSTACK 1
  144436. #endif
  144437. /*
  144438. ** Alternative datatype for the argument to the malloc() routine passed
  144439. ** into sqlite3ParserAlloc(). The default is size_t.
  144440. */
  144441. #define YYMALLOCARGTYPE u64
  144442. /*
  144443. ** An instance of the following structure describes the event of a
  144444. ** TRIGGER. "a" is the event type, one of TK_UPDATE, TK_INSERT,
  144445. ** TK_DELETE, or TK_INSTEAD. If the event is of the form
  144446. **
  144447. ** UPDATE ON (a,b,c)
  144448. **
  144449. ** Then the "b" IdList records the list "a,b,c".
  144450. */
  144451. struct TrigEvent { int a; IdList * b; };
  144452. struct FrameBound { int eType; Expr *pExpr; };
  144453. /*
  144454. ** Disable lookaside memory allocation for objects that might be
  144455. ** shared across database connections.
  144456. */
  144457. static void disableLookaside(Parse *pParse){
  144458. sqlite3 *db = pParse->db;
  144459. pParse->disableLookaside++;
  144460. DisableLookaside;
  144461. }
  144462. /*
  144463. ** For a compound SELECT statement, make sure p->pPrior->pNext==p for
  144464. ** all elements in the list. And make sure list length does not exceed
  144465. ** SQLITE_LIMIT_COMPOUND_SELECT.
  144466. */
  144467. static void parserDoubleLinkSelect(Parse *pParse, Select *p){
  144468. assert( p!=0 );
  144469. if( p->pPrior ){
  144470. Select *pNext = 0, *pLoop;
  144471. int mxSelect, cnt = 0;
  144472. for(pLoop=p; pLoop; pNext=pLoop, pLoop=pLoop->pPrior, cnt++){
  144473. pLoop->pNext = pNext;
  144474. pLoop->selFlags |= SF_Compound;
  144475. }
  144476. if( (p->selFlags & SF_MultiValue)==0 &&
  144477. (mxSelect = pParse->db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT])>0 &&
  144478. cnt>mxSelect
  144479. ){
  144480. sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
  144481. }
  144482. }
  144483. }
  144484. /* Construct a new Expr object from a single identifier. Use the
  144485. ** new Expr to populate pOut. Set the span of pOut to be the identifier
  144486. ** that created the expression.
  144487. */
  144488. static Expr *tokenExpr(Parse *pParse, int op, Token t){
  144489. Expr *p = sqlite3DbMallocRawNN(pParse->db, sizeof(Expr)+t.n+1);
  144490. if( p ){
  144491. /* memset(p, 0, sizeof(Expr)); */
  144492. p->op = (u8)op;
  144493. p->affExpr = 0;
  144494. p->flags = EP_Leaf;
  144495. ExprClearVVAProperties(p);
  144496. p->iAgg = -1;
  144497. p->pLeft = p->pRight = 0;
  144498. p->x.pList = 0;
  144499. p->pAggInfo = 0;
  144500. p->y.pTab = 0;
  144501. p->op2 = 0;
  144502. p->iTable = 0;
  144503. p->iColumn = 0;
  144504. p->u.zToken = (char*)&p[1];
  144505. memcpy(p->u.zToken, t.z, t.n);
  144506. p->u.zToken[t.n] = 0;
  144507. if( sqlite3Isquote(p->u.zToken[0]) ){
  144508. sqlite3DequoteExpr(p);
  144509. }
  144510. #if SQLITE_MAX_EXPR_DEPTH>0
  144511. p->nHeight = 1;
  144512. #endif
  144513. if( IN_RENAME_OBJECT ){
  144514. return (Expr*)sqlite3RenameTokenMap(pParse, (void*)p, &t);
  144515. }
  144516. }
  144517. return p;
  144518. }
  144519. /* A routine to convert a binary TK_IS or TK_ISNOT expression into a
  144520. ** unary TK_ISNULL or TK_NOTNULL expression. */
  144521. static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){
  144522. sqlite3 *db = pParse->db;
  144523. if( pA && pY && pY->op==TK_NULL && !IN_RENAME_OBJECT ){
  144524. pA->op = (u8)op;
  144525. sqlite3ExprDelete(db, pA->pRight);
  144526. pA->pRight = 0;
  144527. }
  144528. }
  144529. /* Add a single new term to an ExprList that is used to store a
  144530. ** list of identifiers. Report an error if the ID list contains
  144531. ** a COLLATE clause or an ASC or DESC keyword, except ignore the
  144532. ** error while parsing a legacy schema.
  144533. */
  144534. static ExprList *parserAddExprIdListTerm(
  144535. Parse *pParse,
  144536. ExprList *pPrior,
  144537. Token *pIdToken,
  144538. int hasCollate,
  144539. int sortOrder
  144540. ){
  144541. ExprList *p = sqlite3ExprListAppend(pParse, pPrior, 0);
  144542. if( (hasCollate || sortOrder!=SQLITE_SO_UNDEFINED)
  144543. && pParse->db->init.busy==0
  144544. ){
  144545. sqlite3ErrorMsg(pParse, "syntax error after column name \"%.*s\"",
  144546. pIdToken->n, pIdToken->z);
  144547. }
  144548. sqlite3ExprListSetName(pParse, p, pIdToken, 1);
  144549. return p;
  144550. }
  144551. #if TK_SPAN>255
  144552. # error too many tokens in the grammar
  144553. #endif
  144554. /**************** End of %include directives **********************************/
  144555. /* These constants specify the various numeric values for terminal symbols
  144556. ** in a format understandable to "makeheaders". This section is blank unless
  144557. ** "lemon" is run with the "-m" command-line option.
  144558. ***************** Begin makeheaders token definitions *************************/
  144559. /**************** End makeheaders token definitions ***************************/
  144560. /* The next sections is a series of control #defines.
  144561. ** various aspects of the generated parser.
  144562. ** YYCODETYPE is the data type used to store the integer codes
  144563. ** that represent terminal and non-terminal symbols.
  144564. ** "unsigned char" is used if there are fewer than
  144565. ** 256 symbols. Larger types otherwise.
  144566. ** YYNOCODE is a number of type YYCODETYPE that is not used for
  144567. ** any terminal or nonterminal symbol.
  144568. ** YYFALLBACK If defined, this indicates that one or more tokens
  144569. ** (also known as: "terminal symbols") have fall-back
  144570. ** values which should be used if the original symbol
  144571. ** would not parse. This permits keywords to sometimes
  144572. ** be used as identifiers, for example.
  144573. ** YYACTIONTYPE is the data type used for "action codes" - numbers
  144574. ** that indicate what to do in response to the next
  144575. ** token.
  144576. ** sqlite3ParserTOKENTYPE is the data type used for minor type for terminal
  144577. ** symbols. Background: A "minor type" is a semantic
  144578. ** value associated with a terminal or non-terminal
  144579. ** symbols. For example, for an "ID" terminal symbol,
  144580. ** the minor type might be the name of the identifier.
  144581. ** Each non-terminal can have a different minor type.
  144582. ** Terminal symbols all have the same minor type, though.
  144583. ** This macros defines the minor type for terminal
  144584. ** symbols.
  144585. ** YYMINORTYPE is the data type used for all minor types.
  144586. ** This is typically a union of many types, one of
  144587. ** which is sqlite3ParserTOKENTYPE. The entry in the union
  144588. ** for terminal symbols is called "yy0".
  144589. ** YYSTACKDEPTH is the maximum depth of the parser's stack. If
  144590. ** zero the stack is dynamically sized using realloc()
  144591. ** sqlite3ParserARG_SDECL A static variable declaration for the %extra_argument
  144592. ** sqlite3ParserARG_PDECL A parameter declaration for the %extra_argument
  144593. ** sqlite3ParserARG_PARAM Code to pass %extra_argument as a subroutine parameter
  144594. ** sqlite3ParserARG_STORE Code to store %extra_argument into yypParser
  144595. ** sqlite3ParserARG_FETCH Code to extract %extra_argument from yypParser
  144596. ** sqlite3ParserCTX_* As sqlite3ParserARG_ except for %extra_context
  144597. ** YYERRORSYMBOL is the code number of the error symbol. If not
  144598. ** defined, then do no error processing.
  144599. ** YYNSTATE the combined number of states.
  144600. ** YYNRULE the number of rules in the grammar
  144601. ** YYNTOKEN Number of terminal symbols
  144602. ** YY_MAX_SHIFT Maximum value for shift actions
  144603. ** YY_MIN_SHIFTREDUCE Minimum value for shift-reduce actions
  144604. ** YY_MAX_SHIFTREDUCE Maximum value for shift-reduce actions
  144605. ** YY_ERROR_ACTION The yy_action[] code for syntax error
  144606. ** YY_ACCEPT_ACTION The yy_action[] code for accept
  144607. ** YY_NO_ACTION The yy_action[] code for no-op
  144608. ** YY_MIN_REDUCE Minimum value for reduce actions
  144609. ** YY_MAX_REDUCE Maximum value for reduce actions
  144610. */
  144611. #ifndef INTERFACE
  144612. # define INTERFACE 1
  144613. #endif
  144614. /************* Begin control #defines *****************************************/
  144615. #define YYCODETYPE unsigned short int
  144616. #define YYNOCODE 310
  144617. #define YYACTIONTYPE unsigned short int
  144618. #define YYWILDCARD 100
  144619. #define sqlite3ParserTOKENTYPE Token
  144620. typedef union {
  144621. int yyinit;
  144622. sqlite3ParserTOKENTYPE yy0;
  144623. SrcList* yy47;
  144624. u8 yy58;
  144625. struct FrameBound yy77;
  144626. With* yy131;
  144627. int yy192;
  144628. Expr* yy202;
  144629. struct {int value; int mask;} yy207;
  144630. struct TrigEvent yy230;
  144631. ExprList* yy242;
  144632. Window* yy303;
  144633. Upsert* yy318;
  144634. const char* yy436;
  144635. TriggerStep* yy447;
  144636. Select* yy539;
  144637. IdList* yy600;
  144638. } YYMINORTYPE;
  144639. #ifndef YYSTACKDEPTH
  144640. #define YYSTACKDEPTH 100
  144641. #endif
  144642. #define sqlite3ParserARG_SDECL
  144643. #define sqlite3ParserARG_PDECL
  144644. #define sqlite3ParserARG_PARAM
  144645. #define sqlite3ParserARG_FETCH
  144646. #define sqlite3ParserARG_STORE
  144647. #define sqlite3ParserCTX_SDECL Parse *pParse;
  144648. #define sqlite3ParserCTX_PDECL ,Parse *pParse
  144649. #define sqlite3ParserCTX_PARAM ,pParse
  144650. #define sqlite3ParserCTX_FETCH Parse *pParse=yypParser->pParse;
  144651. #define sqlite3ParserCTX_STORE yypParser->pParse=pParse;
  144652. #define YYFALLBACK 1
  144653. #define YYNSTATE 551
  144654. #define YYNRULE 385
  144655. #define YYNRULE_WITH_ACTION 325
  144656. #define YYNTOKEN 181
  144657. #define YY_MAX_SHIFT 550
  144658. #define YY_MIN_SHIFTREDUCE 801
  144659. #define YY_MAX_SHIFTREDUCE 1185
  144660. #define YY_ERROR_ACTION 1186
  144661. #define YY_ACCEPT_ACTION 1187
  144662. #define YY_NO_ACTION 1188
  144663. #define YY_MIN_REDUCE 1189
  144664. #define YY_MAX_REDUCE 1573
  144665. /************* End control #defines *******************************************/
  144666. #define YY_NLOOKAHEAD ((int)(sizeof(yy_lookahead)/sizeof(yy_lookahead[0])))
  144667. /* Define the yytestcase() macro to be a no-op if is not already defined
  144668. ** otherwise.
  144669. **
  144670. ** Applications can choose to define yytestcase() in the %include section
  144671. ** to a macro that can assist in verifying code coverage. For production
  144672. ** code the yytestcase() macro should be turned off. But it is useful
  144673. ** for testing.
  144674. */
  144675. #ifndef yytestcase
  144676. # define yytestcase(X)
  144677. #endif
  144678. /* Next are the tables used to determine what action to take based on the
  144679. ** current state and lookahead token. These tables are used to implement
  144680. ** functions that take a state number and lookahead value and return an
  144681. ** action integer.
  144682. **
  144683. ** Suppose the action integer is N. Then the action is determined as
  144684. ** follows
  144685. **
  144686. ** 0 <= N <= YY_MAX_SHIFT Shift N. That is, push the lookahead
  144687. ** token onto the stack and goto state N.
  144688. **
  144689. ** N between YY_MIN_SHIFTREDUCE Shift to an arbitrary state then
  144690. ** and YY_MAX_SHIFTREDUCE reduce by rule N-YY_MIN_SHIFTREDUCE.
  144691. **
  144692. ** N == YY_ERROR_ACTION A syntax error has occurred.
  144693. **
  144694. ** N == YY_ACCEPT_ACTION The parser accepts its input.
  144695. **
  144696. ** N == YY_NO_ACTION No such action. Denotes unused
  144697. ** slots in the yy_action[] table.
  144698. **
  144699. ** N between YY_MIN_REDUCE Reduce by rule N-YY_MIN_REDUCE
  144700. ** and YY_MAX_REDUCE
  144701. **
  144702. ** The action table is constructed as a single large table named yy_action[].
  144703. ** Given state S and lookahead X, the action is computed as either:
  144704. **
  144705. ** (A) N = yy_action[ yy_shift_ofst[S] + X ]
  144706. ** (B) N = yy_default[S]
  144707. **
  144708. ** The (A) formula is preferred. The B formula is used instead if
  144709. ** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X.
  144710. **
  144711. ** The formulas above are for computing the action when the lookahead is
  144712. ** a terminal symbol. If the lookahead is a non-terminal (as occurs after
  144713. ** a reduce action) then the yy_reduce_ofst[] array is used in place of
  144714. ** the yy_shift_ofst[] array.
  144715. **
  144716. ** The following are the tables generated in this section:
  144717. **
  144718. ** yy_action[] A single table containing all actions.
  144719. ** yy_lookahead[] A table containing the lookahead for each entry in
  144720. ** yy_action. Used to detect hash collisions.
  144721. ** yy_shift_ofst[] For each state, the offset into yy_action for
  144722. ** shifting terminals.
  144723. ** yy_reduce_ofst[] For each state, the offset into yy_action for
  144724. ** shifting non-terminals after a reduce.
  144725. ** yy_default[] Default action for each state.
  144726. **
  144727. *********** Begin parsing tables **********************************************/
  144728. #define YY_ACTTAB_COUNT (1958)
  144729. static const YYACTIONTYPE yy_action[] = {
  144730. /* 0 */ 544, 1220, 544, 449, 1258, 544, 1237, 544, 114, 111,
  144731. /* 10 */ 211, 544, 1535, 544, 1258, 521, 114, 111, 211, 390,
  144732. /* 20 */ 1230, 342, 42, 42, 42, 42, 1223, 42, 42, 71,
  144733. /* 30 */ 71, 935, 1222, 71, 71, 71, 71, 1460, 1491, 936,
  144734. /* 40 */ 818, 451, 6, 121, 122, 112, 1163, 1163, 1004, 1007,
  144735. /* 50 */ 997, 997, 119, 119, 120, 120, 120, 120, 1541, 390,
  144736. /* 60 */ 1356, 1515, 550, 2, 1191, 194, 526, 434, 143, 291,
  144737. /* 70 */ 526, 136, 526, 369, 261, 502, 272, 383, 1271, 525,
  144738. /* 80 */ 501, 491, 164, 121, 122, 112, 1163, 1163, 1004, 1007,
  144739. /* 90 */ 997, 997, 119, 119, 120, 120, 120, 120, 1356, 440,
  144740. /* 100 */ 1512, 118, 118, 118, 118, 117, 117, 116, 116, 116,
  144741. /* 110 */ 115, 422, 266, 266, 266, 266, 1496, 356, 1498, 433,
  144742. /* 120 */ 355, 1496, 515, 522, 1483, 541, 1112, 541, 1112, 390,
  144743. /* 130 */ 403, 241, 208, 114, 111, 211, 98, 290, 535, 221,
  144744. /* 140 */ 1027, 118, 118, 118, 118, 117, 117, 116, 116, 116,
  144745. /* 150 */ 115, 422, 1140, 121, 122, 112, 1163, 1163, 1004, 1007,
  144746. /* 160 */ 997, 997, 119, 119, 120, 120, 120, 120, 404, 426,
  144747. /* 170 */ 117, 117, 116, 116, 116, 115, 422, 1416, 466, 123,
  144748. /* 180 */ 118, 118, 118, 118, 117, 117, 116, 116, 116, 115,
  144749. /* 190 */ 422, 116, 116, 116, 115, 422, 538, 538, 538, 390,
  144750. /* 200 */ 503, 120, 120, 120, 120, 113, 1049, 1140, 1141, 1142,
  144751. /* 210 */ 1049, 118, 118, 118, 118, 117, 117, 116, 116, 116,
  144752. /* 220 */ 115, 422, 1459, 121, 122, 112, 1163, 1163, 1004, 1007,
  144753. /* 230 */ 997, 997, 119, 119, 120, 120, 120, 120, 390, 442,
  144754. /* 240 */ 314, 83, 461, 81, 357, 380, 1140, 80, 118, 118,
  144755. /* 250 */ 118, 118, 117, 117, 116, 116, 116, 115, 422, 179,
  144756. /* 260 */ 432, 422, 121, 122, 112, 1163, 1163, 1004, 1007, 997,
  144757. /* 270 */ 997, 119, 119, 120, 120, 120, 120, 432, 431, 266,
  144758. /* 280 */ 266, 118, 118, 118, 118, 117, 117, 116, 116, 116,
  144759. /* 290 */ 115, 422, 541, 1107, 901, 504, 1140, 114, 111, 211,
  144760. /* 300 */ 1429, 1140, 1141, 1142, 206, 489, 1107, 390, 447, 1107,
  144761. /* 310 */ 543, 328, 120, 120, 120, 120, 298, 1429, 1431, 17,
  144762. /* 320 */ 118, 118, 118, 118, 117, 117, 116, 116, 116, 115,
  144763. /* 330 */ 422, 121, 122, 112, 1163, 1163, 1004, 1007, 997, 997,
  144764. /* 340 */ 119, 119, 120, 120, 120, 120, 390, 1356, 432, 1140,
  144765. /* 350 */ 480, 1140, 1141, 1142, 994, 994, 1005, 1008, 443, 118,
  144766. /* 360 */ 118, 118, 118, 117, 117, 116, 116, 116, 115, 422,
  144767. /* 370 */ 121, 122, 112, 1163, 1163, 1004, 1007, 997, 997, 119,
  144768. /* 380 */ 119, 120, 120, 120, 120, 1052, 1052, 463, 1429, 118,
  144769. /* 390 */ 118, 118, 118, 117, 117, 116, 116, 116, 115, 422,
  144770. /* 400 */ 1140, 449, 544, 1424, 1140, 1141, 1142, 233, 964, 1140,
  144771. /* 410 */ 479, 476, 475, 171, 358, 390, 164, 405, 412, 840,
  144772. /* 420 */ 474, 164, 185, 332, 71, 71, 1241, 998, 118, 118,
  144773. /* 430 */ 118, 118, 117, 117, 116, 116, 116, 115, 422, 121,
  144774. /* 440 */ 122, 112, 1163, 1163, 1004, 1007, 997, 997, 119, 119,
  144775. /* 450 */ 120, 120, 120, 120, 390, 1140, 1141, 1142, 833, 12,
  144776. /* 460 */ 313, 507, 163, 354, 1140, 1141, 1142, 114, 111, 211,
  144777. /* 470 */ 506, 290, 535, 544, 276, 180, 290, 535, 121, 122,
  144778. /* 480 */ 112, 1163, 1163, 1004, 1007, 997, 997, 119, 119, 120,
  144779. /* 490 */ 120, 120, 120, 343, 482, 71, 71, 118, 118, 118,
  144780. /* 500 */ 118, 117, 117, 116, 116, 116, 115, 422, 1140, 209,
  144781. /* 510 */ 409, 521, 1140, 1107, 1569, 376, 252, 269, 340, 485,
  144782. /* 520 */ 335, 484, 238, 390, 511, 362, 1107, 1125, 331, 1107,
  144783. /* 530 */ 191, 407, 286, 32, 455, 441, 118, 118, 118, 118,
  144784. /* 540 */ 117, 117, 116, 116, 116, 115, 422, 121, 122, 112,
  144785. /* 550 */ 1163, 1163, 1004, 1007, 997, 997, 119, 119, 120, 120,
  144786. /* 560 */ 120, 120, 390, 1140, 1141, 1142, 985, 1140, 1141, 1142,
  144787. /* 570 */ 1140, 233, 490, 1490, 479, 476, 475, 6, 163, 544,
  144788. /* 580 */ 510, 544, 115, 422, 474, 5, 121, 122, 112, 1163,
  144789. /* 590 */ 1163, 1004, 1007, 997, 997, 119, 119, 120, 120, 120,
  144790. /* 600 */ 120, 13, 13, 13, 13, 118, 118, 118, 118, 117,
  144791. /* 610 */ 117, 116, 116, 116, 115, 422, 401, 500, 406, 544,
  144792. /* 620 */ 1484, 542, 1140, 890, 890, 1140, 1141, 1142, 1471, 1140,
  144793. /* 630 */ 275, 390, 806, 807, 808, 969, 420, 420, 420, 16,
  144794. /* 640 */ 16, 55, 55, 1240, 118, 118, 118, 118, 117, 117,
  144795. /* 650 */ 116, 116, 116, 115, 422, 121, 122, 112, 1163, 1163,
  144796. /* 660 */ 1004, 1007, 997, 997, 119, 119, 120, 120, 120, 120,
  144797. /* 670 */ 390, 1187, 1, 1, 550, 2, 1191, 1140, 1141, 1142,
  144798. /* 680 */ 194, 291, 896, 136, 1140, 1141, 1142, 895, 519, 1490,
  144799. /* 690 */ 1271, 3, 378, 6, 121, 122, 112, 1163, 1163, 1004,
  144800. /* 700 */ 1007, 997, 997, 119, 119, 120, 120, 120, 120, 856,
  144801. /* 710 */ 544, 922, 544, 118, 118, 118, 118, 117, 117, 116,
  144802. /* 720 */ 116, 116, 115, 422, 266, 266, 1090, 1567, 1140, 549,
  144803. /* 730 */ 1567, 1191, 13, 13, 13, 13, 291, 541, 136, 390,
  144804. /* 740 */ 483, 419, 418, 964, 342, 1271, 466, 408, 857, 279,
  144805. /* 750 */ 140, 221, 118, 118, 118, 118, 117, 117, 116, 116,
  144806. /* 760 */ 116, 115, 422, 121, 122, 112, 1163, 1163, 1004, 1007,
  144807. /* 770 */ 997, 997, 119, 119, 120, 120, 120, 120, 544, 266,
  144808. /* 780 */ 266, 426, 390, 1140, 1141, 1142, 1170, 828, 1170, 466,
  144809. /* 790 */ 429, 145, 541, 1144, 399, 313, 437, 301, 836, 1488,
  144810. /* 800 */ 71, 71, 410, 6, 1088, 471, 221, 100, 112, 1163,
  144811. /* 810 */ 1163, 1004, 1007, 997, 997, 119, 119, 120, 120, 120,
  144812. /* 820 */ 120, 118, 118, 118, 118, 117, 117, 116, 116, 116,
  144813. /* 830 */ 115, 422, 237, 1423, 544, 449, 426, 287, 984, 544,
  144814. /* 840 */ 236, 235, 234, 828, 97, 527, 427, 1263, 1263, 1144,
  144815. /* 850 */ 492, 306, 428, 836, 975, 544, 71, 71, 974, 1239,
  144816. /* 860 */ 544, 51, 51, 300, 118, 118, 118, 118, 117, 117,
  144817. /* 870 */ 116, 116, 116, 115, 422, 194, 103, 70, 70, 266,
  144818. /* 880 */ 266, 544, 71, 71, 266, 266, 30, 389, 342, 974,
  144819. /* 890 */ 974, 976, 541, 526, 1107, 326, 390, 541, 493, 395,
  144820. /* 900 */ 1468, 195, 528, 13, 13, 1356, 240, 1107, 277, 280,
  144821. /* 910 */ 1107, 280, 303, 455, 305, 331, 390, 31, 188, 417,
  144822. /* 920 */ 121, 122, 112, 1163, 1163, 1004, 1007, 997, 997, 119,
  144823. /* 930 */ 119, 120, 120, 120, 120, 142, 390, 363, 455, 984,
  144824. /* 940 */ 121, 122, 112, 1163, 1163, 1004, 1007, 997, 997, 119,
  144825. /* 950 */ 119, 120, 120, 120, 120, 975, 321, 1140, 324, 974,
  144826. /* 960 */ 121, 110, 112, 1163, 1163, 1004, 1007, 997, 997, 119,
  144827. /* 970 */ 119, 120, 120, 120, 120, 462, 375, 1183, 118, 118,
  144828. /* 980 */ 118, 118, 117, 117, 116, 116, 116, 115, 422, 1140,
  144829. /* 990 */ 974, 974, 976, 304, 9, 364, 244, 360, 118, 118,
  144830. /* 1000 */ 118, 118, 117, 117, 116, 116, 116, 115, 422, 312,
  144831. /* 1010 */ 544, 342, 1140, 1141, 1142, 299, 290, 535, 118, 118,
  144832. /* 1020 */ 118, 118, 117, 117, 116, 116, 116, 115, 422, 1261,
  144833. /* 1030 */ 1261, 1161, 13, 13, 278, 419, 418, 466, 390, 921,
  144834. /* 1040 */ 260, 260, 289, 1167, 1140, 1141, 1142, 189, 1169, 266,
  144835. /* 1050 */ 266, 466, 388, 541, 1184, 544, 1168, 263, 144, 487,
  144836. /* 1060 */ 920, 544, 541, 122, 112, 1163, 1163, 1004, 1007, 997,
  144837. /* 1070 */ 997, 119, 119, 120, 120, 120, 120, 71, 71, 1140,
  144838. /* 1080 */ 1170, 1270, 1170, 13, 13, 896, 1068, 1161, 544, 466,
  144839. /* 1090 */ 895, 107, 536, 1489, 4, 1266, 1107, 6, 523, 1047,
  144840. /* 1100 */ 12, 1069, 1090, 1568, 311, 453, 1568, 518, 539, 1107,
  144841. /* 1110 */ 56, 56, 1107, 1487, 421, 1356, 1070, 6, 343, 285,
  144842. /* 1120 */ 118, 118, 118, 118, 117, 117, 116, 116, 116, 115,
  144843. /* 1130 */ 422, 423, 1269, 319, 1140, 1141, 1142, 876, 266, 266,
  144844. /* 1140 */ 1275, 107, 536, 533, 4, 1486, 293, 877, 1209, 6,
  144845. /* 1150 */ 210, 541, 541, 164, 1540, 494, 414, 865, 539, 267,
  144846. /* 1160 */ 267, 1212, 396, 509, 497, 204, 266, 266, 394, 529,
  144847. /* 1170 */ 8, 984, 541, 517, 544, 920, 456, 105, 105, 541,
  144848. /* 1180 */ 1088, 423, 266, 266, 106, 415, 423, 546, 545, 266,
  144849. /* 1190 */ 266, 974, 516, 533, 1371, 541, 15, 15, 266, 266,
  144850. /* 1200 */ 454, 1118, 541, 266, 266, 1068, 1370, 513, 290, 535,
  144851. /* 1210 */ 544, 541, 512, 97, 442, 314, 541, 544, 920, 125,
  144852. /* 1220 */ 1069, 984, 974, 974, 976, 977, 27, 105, 105, 399,
  144853. /* 1230 */ 341, 1509, 44, 44, 106, 1070, 423, 546, 545, 57,
  144854. /* 1240 */ 57, 974, 341, 1509, 107, 536, 544, 4, 460, 399,
  144855. /* 1250 */ 214, 1118, 457, 294, 375, 1089, 532, 297, 544, 537,
  144856. /* 1260 */ 396, 539, 290, 535, 104, 244, 102, 524, 58, 58,
  144857. /* 1270 */ 544, 109, 974, 974, 976, 977, 27, 1514, 1129, 425,
  144858. /* 1280 */ 59, 59, 270, 237, 423, 138, 95, 373, 373, 372,
  144859. /* 1290 */ 255, 370, 60, 60, 815, 1178, 533, 544, 273, 544,
  144860. /* 1300 */ 1161, 843, 387, 386, 544, 1307, 544, 215, 210, 296,
  144861. /* 1310 */ 513, 847, 544, 265, 208, 514, 1306, 295, 274, 61,
  144862. /* 1320 */ 61, 62, 62, 436, 984, 1160, 45, 45, 46, 46,
  144863. /* 1330 */ 105, 105, 1184, 920, 47, 47, 1474, 106, 544, 423,
  144864. /* 1340 */ 546, 545, 218, 544, 974, 935, 1085, 217, 544, 377,
  144865. /* 1350 */ 395, 107, 536, 936, 4, 156, 1161, 843, 158, 544,
  144866. /* 1360 */ 49, 49, 141, 544, 38, 50, 50, 544, 539, 307,
  144867. /* 1370 */ 63, 63, 544, 1448, 216, 974, 974, 976, 977, 27,
  144868. /* 1380 */ 444, 64, 64, 544, 1447, 65, 65, 544, 524, 14,
  144869. /* 1390 */ 14, 423, 458, 544, 66, 66, 310, 544, 316, 97,
  144870. /* 1400 */ 1034, 544, 961, 533, 268, 127, 127, 544, 391, 67,
  144871. /* 1410 */ 67, 544, 978, 290, 535, 52, 52, 513, 544, 68,
  144872. /* 1420 */ 68, 1294, 512, 69, 69, 397, 165, 855, 854, 53,
  144873. /* 1430 */ 53, 984, 966, 151, 151, 243, 430, 105, 105, 199,
  144874. /* 1440 */ 152, 152, 448, 1303, 106, 243, 423, 546, 545, 1129,
  144875. /* 1450 */ 425, 974, 320, 270, 862, 863, 1034, 220, 373, 373,
  144876. /* 1460 */ 372, 255, 370, 450, 323, 815, 243, 544, 978, 544,
  144877. /* 1470 */ 107, 536, 544, 4, 544, 938, 939, 325, 215, 1046,
  144878. /* 1480 */ 296, 1046, 974, 974, 976, 977, 27, 539, 295, 76,
  144879. /* 1490 */ 76, 54, 54, 327, 72, 72, 128, 128, 1503, 1254,
  144880. /* 1500 */ 107, 536, 544, 4, 1045, 544, 1045, 531, 1238, 544,
  144881. /* 1510 */ 423, 544, 315, 334, 544, 97, 544, 539, 217, 544,
  144882. /* 1520 */ 472, 1528, 533, 239, 73, 73, 156, 129, 129, 158,
  144883. /* 1530 */ 467, 130, 130, 126, 126, 344, 150, 150, 149, 149,
  144884. /* 1540 */ 423, 134, 134, 329, 1030, 216, 97, 239, 929, 345,
  144885. /* 1550 */ 984, 243, 533, 1315, 339, 544, 105, 105, 900, 1355,
  144886. /* 1560 */ 544, 1290, 258, 106, 338, 423, 546, 545, 544, 1301,
  144887. /* 1570 */ 974, 893, 99, 536, 109, 4, 544, 133, 133, 391,
  144888. /* 1580 */ 984, 197, 131, 131, 290, 535, 105, 105, 530, 539,
  144889. /* 1590 */ 132, 132, 1361, 106, 1219, 423, 546, 545, 75, 75,
  144890. /* 1600 */ 974, 974, 974, 976, 977, 27, 544, 430, 826, 1211,
  144891. /* 1610 */ 894, 139, 423, 109, 544, 1200, 1199, 1201, 1522, 544,
  144892. /* 1620 */ 201, 544, 11, 374, 533, 1287, 347, 349, 77, 77,
  144893. /* 1630 */ 1340, 974, 974, 976, 977, 27, 74, 74, 351, 213,
  144894. /* 1640 */ 435, 43, 43, 48, 48, 302, 477, 309, 1348, 382,
  144895. /* 1650 */ 353, 452, 984, 337, 1237, 1420, 1419, 205, 105, 105,
  144896. /* 1660 */ 192, 367, 193, 534, 1525, 106, 1178, 423, 546, 545,
  144897. /* 1670 */ 247, 167, 974, 270, 1467, 200, 1465, 1175, 373, 373,
  144898. /* 1680 */ 372, 255, 370, 398, 79, 815, 83, 82, 1425, 446,
  144899. /* 1690 */ 161, 177, 169, 95, 1337, 438, 172, 173, 215, 174,
  144900. /* 1700 */ 296, 175, 35, 974, 974, 976, 977, 27, 295, 1345,
  144901. /* 1710 */ 439, 470, 223, 36, 379, 445, 1414, 381, 459, 1351,
  144902. /* 1720 */ 181, 227, 88, 465, 259, 229, 1436, 318, 186, 468,
  144903. /* 1730 */ 322, 230, 384, 1202, 231, 486, 1257, 1256, 217, 411,
  144904. /* 1740 */ 1255, 1248, 90, 847, 206, 413, 156, 505, 1539, 158,
  144905. /* 1750 */ 1226, 1538, 283, 1508, 1227, 336, 385, 284, 1225, 496,
  144906. /* 1760 */ 1537, 1298, 94, 346, 348, 216, 1247, 499, 1299, 245,
  144907. /* 1770 */ 246, 1297, 416, 350, 1494, 124, 1493, 10, 524, 361,
  144908. /* 1780 */ 1400, 101, 96, 288, 508, 253, 1135, 1208, 34, 1296,
  144909. /* 1790 */ 547, 254, 256, 257, 392, 548, 1197, 1192, 359, 391,
  144910. /* 1800 */ 1280, 1279, 196, 365, 290, 535, 366, 352, 1452, 1322,
  144911. /* 1810 */ 1321, 1453, 153, 137, 281, 154, 802, 424, 155, 1451,
  144912. /* 1820 */ 1450, 198, 292, 202, 203, 78, 212, 430, 271, 135,
  144913. /* 1830 */ 1044, 1042, 958, 168, 219, 157, 170, 879, 308, 222,
  144914. /* 1840 */ 1058, 176, 159, 962, 400, 84, 402, 178, 85, 86,
  144915. /* 1850 */ 87, 166, 160, 393, 1061, 224, 225, 1057, 146, 18,
  144916. /* 1860 */ 226, 317, 1050, 1172, 243, 464, 182, 228, 37, 183,
  144917. /* 1870 */ 817, 469, 338, 232, 330, 481, 184, 89, 845, 19,
  144918. /* 1880 */ 20, 92, 473, 478, 333, 91, 162, 858, 147, 488,
  144919. /* 1890 */ 282, 1123, 148, 1010, 928, 1093, 39, 93, 40, 495,
  144920. /* 1900 */ 1094, 187, 498, 207, 262, 264, 923, 242, 1109, 109,
  144921. /* 1910 */ 1113, 1111, 1097, 33, 21, 1117, 520, 1025, 22, 23,
  144922. /* 1920 */ 24, 1116, 25, 190, 97, 1011, 1009, 26, 1013, 1067,
  144923. /* 1930 */ 248, 7, 1066, 249, 1014, 28, 41, 889, 979, 827,
  144924. /* 1940 */ 108, 29, 250, 540, 251, 1530, 371, 368, 1131, 1130,
  144925. /* 1950 */ 1188, 1188, 1188, 1188, 1188, 1188, 1188, 1529,
  144926. };
  144927. static const YYCODETYPE yy_lookahead[] = {
  144928. /* 0 */ 189, 211, 189, 189, 218, 189, 220, 189, 267, 268,
  144929. /* 10 */ 269, 189, 210, 189, 228, 189, 267, 268, 269, 19,
  144930. /* 20 */ 218, 189, 211, 212, 211, 212, 211, 211, 212, 211,
  144931. /* 30 */ 212, 31, 211, 211, 212, 211, 212, 288, 300, 39,
  144932. /* 40 */ 21, 189, 304, 43, 44, 45, 46, 47, 48, 49,
  144933. /* 50 */ 50, 51, 52, 53, 54, 55, 56, 57, 225, 19,
  144934. /* 60 */ 189, 183, 184, 185, 186, 189, 248, 263, 236, 191,
  144935. /* 70 */ 248, 193, 248, 197, 208, 257, 262, 201, 200, 257,
  144936. /* 80 */ 200, 257, 81, 43, 44, 45, 46, 47, 48, 49,
  144937. /* 90 */ 50, 51, 52, 53, 54, 55, 56, 57, 189, 80,
  144938. /* 100 */ 189, 101, 102, 103, 104, 105, 106, 107, 108, 109,
  144939. /* 110 */ 110, 111, 234, 235, 234, 235, 305, 306, 305, 118,
  144940. /* 120 */ 307, 305, 306, 297, 298, 247, 86, 247, 88, 19,
  144941. /* 130 */ 259, 251, 252, 267, 268, 269, 26, 136, 137, 261,
  144942. /* 140 */ 121, 101, 102, 103, 104, 105, 106, 107, 108, 109,
  144943. /* 150 */ 110, 111, 59, 43, 44, 45, 46, 47, 48, 49,
  144944. /* 160 */ 50, 51, 52, 53, 54, 55, 56, 57, 259, 291,
  144945. /* 170 */ 105, 106, 107, 108, 109, 110, 111, 158, 189, 69,
  144946. /* 180 */ 101, 102, 103, 104, 105, 106, 107, 108, 109, 110,
  144947. /* 190 */ 111, 107, 108, 109, 110, 111, 205, 206, 207, 19,
  144948. /* 200 */ 19, 54, 55, 56, 57, 58, 29, 114, 115, 116,
  144949. /* 210 */ 33, 101, 102, 103, 104, 105, 106, 107, 108, 109,
  144950. /* 220 */ 110, 111, 233, 43, 44, 45, 46, 47, 48, 49,
  144951. /* 230 */ 50, 51, 52, 53, 54, 55, 56, 57, 19, 126,
  144952. /* 240 */ 127, 148, 65, 24, 214, 200, 59, 67, 101, 102,
  144953. /* 250 */ 103, 104, 105, 106, 107, 108, 109, 110, 111, 22,
  144954. /* 260 */ 189, 111, 43, 44, 45, 46, 47, 48, 49, 50,
  144955. /* 270 */ 51, 52, 53, 54, 55, 56, 57, 206, 207, 234,
  144956. /* 280 */ 235, 101, 102, 103, 104, 105, 106, 107, 108, 109,
  144957. /* 290 */ 110, 111, 247, 76, 107, 114, 59, 267, 268, 269,
  144958. /* 300 */ 189, 114, 115, 116, 162, 163, 89, 19, 263, 92,
  144959. /* 310 */ 189, 23, 54, 55, 56, 57, 189, 206, 207, 22,
  144960. /* 320 */ 101, 102, 103, 104, 105, 106, 107, 108, 109, 110,
  144961. /* 330 */ 111, 43, 44, 45, 46, 47, 48, 49, 50, 51,
  144962. /* 340 */ 52, 53, 54, 55, 56, 57, 19, 189, 277, 59,
  144963. /* 350 */ 23, 114, 115, 116, 46, 47, 48, 49, 61, 101,
  144964. /* 360 */ 102, 103, 104, 105, 106, 107, 108, 109, 110, 111,
  144965. /* 370 */ 43, 44, 45, 46, 47, 48, 49, 50, 51, 52,
  144966. /* 380 */ 53, 54, 55, 56, 57, 125, 126, 127, 277, 101,
  144967. /* 390 */ 102, 103, 104, 105, 106, 107, 108, 109, 110, 111,
  144968. /* 400 */ 59, 189, 189, 276, 114, 115, 116, 117, 73, 59,
  144969. /* 410 */ 120, 121, 122, 72, 214, 19, 81, 259, 19, 23,
  144970. /* 420 */ 130, 81, 72, 24, 211, 212, 221, 119, 101, 102,
  144971. /* 430 */ 103, 104, 105, 106, 107, 108, 109, 110, 111, 43,
  144972. /* 440 */ 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
  144973. /* 450 */ 54, 55, 56, 57, 19, 114, 115, 116, 23, 208,
  144974. /* 460 */ 125, 248, 189, 189, 114, 115, 116, 267, 268, 269,
  144975. /* 470 */ 189, 136, 137, 189, 262, 22, 136, 137, 43, 44,
  144976. /* 480 */ 45, 46, 47, 48, 49, 50, 51, 52, 53, 54,
  144977. /* 490 */ 55, 56, 57, 189, 95, 211, 212, 101, 102, 103,
  144978. /* 500 */ 104, 105, 106, 107, 108, 109, 110, 111, 59, 189,
  144979. /* 510 */ 111, 189, 59, 76, 294, 295, 117, 118, 119, 120,
  144980. /* 520 */ 121, 122, 123, 19, 87, 189, 89, 23, 129, 92,
  144981. /* 530 */ 279, 227, 248, 22, 189, 284, 101, 102, 103, 104,
  144982. /* 540 */ 105, 106, 107, 108, 109, 110, 111, 43, 44, 45,
  144983. /* 550 */ 46, 47, 48, 49, 50, 51, 52, 53, 54, 55,
  144984. /* 560 */ 56, 57, 19, 114, 115, 116, 23, 114, 115, 116,
  144985. /* 570 */ 59, 117, 299, 300, 120, 121, 122, 304, 189, 189,
  144986. /* 580 */ 143, 189, 110, 111, 130, 22, 43, 44, 45, 46,
  144987. /* 590 */ 47, 48, 49, 50, 51, 52, 53, 54, 55, 56,
  144988. /* 600 */ 57, 211, 212, 211, 212, 101, 102, 103, 104, 105,
  144989. /* 610 */ 106, 107, 108, 109, 110, 111, 226, 189, 226, 189,
  144990. /* 620 */ 298, 132, 59, 134, 135, 114, 115, 116, 189, 59,
  144991. /* 630 */ 285, 19, 7, 8, 9, 23, 205, 206, 207, 211,
  144992. /* 640 */ 212, 211, 212, 221, 101, 102, 103, 104, 105, 106,
  144993. /* 650 */ 107, 108, 109, 110, 111, 43, 44, 45, 46, 47,
  144994. /* 660 */ 48, 49, 50, 51, 52, 53, 54, 55, 56, 57,
  144995. /* 670 */ 19, 181, 182, 183, 184, 185, 186, 114, 115, 116,
  144996. /* 680 */ 189, 191, 133, 193, 114, 115, 116, 138, 299, 300,
  144997. /* 690 */ 200, 22, 201, 304, 43, 44, 45, 46, 47, 48,
  144998. /* 700 */ 49, 50, 51, 52, 53, 54, 55, 56, 57, 35,
  144999. /* 710 */ 189, 141, 189, 101, 102, 103, 104, 105, 106, 107,
  145000. /* 720 */ 108, 109, 110, 111, 234, 235, 22, 23, 59, 184,
  145001. /* 730 */ 26, 186, 211, 212, 211, 212, 191, 247, 193, 19,
  145002. /* 740 */ 66, 105, 106, 73, 189, 200, 189, 226, 74, 226,
  145003. /* 750 */ 22, 261, 101, 102, 103, 104, 105, 106, 107, 108,
  145004. /* 760 */ 109, 110, 111, 43, 44, 45, 46, 47, 48, 49,
  145005. /* 770 */ 50, 51, 52, 53, 54, 55, 56, 57, 189, 234,
  145006. /* 780 */ 235, 291, 19, 114, 115, 116, 150, 59, 152, 189,
  145007. /* 790 */ 233, 236, 247, 59, 189, 125, 126, 127, 59, 300,
  145008. /* 800 */ 211, 212, 128, 304, 100, 19, 261, 156, 45, 46,
  145009. /* 810 */ 47, 48, 49, 50, 51, 52, 53, 54, 55, 56,
  145010. /* 820 */ 57, 101, 102, 103, 104, 105, 106, 107, 108, 109,
  145011. /* 830 */ 110, 111, 46, 233, 189, 189, 291, 248, 99, 189,
  145012. /* 840 */ 125, 126, 127, 115, 26, 200, 289, 230, 231, 115,
  145013. /* 850 */ 200, 16, 189, 114, 115, 189, 211, 212, 119, 221,
  145014. /* 860 */ 189, 211, 212, 258, 101, 102, 103, 104, 105, 106,
  145015. /* 870 */ 107, 108, 109, 110, 111, 189, 156, 211, 212, 234,
  145016. /* 880 */ 235, 189, 211, 212, 234, 235, 22, 201, 189, 150,
  145017. /* 890 */ 151, 152, 247, 248, 76, 16, 19, 247, 248, 113,
  145018. /* 900 */ 189, 24, 257, 211, 212, 189, 26, 89, 262, 223,
  145019. /* 910 */ 92, 225, 77, 189, 79, 129, 19, 53, 226, 248,
  145020. /* 920 */ 43, 44, 45, 46, 47, 48, 49, 50, 51, 52,
  145021. /* 930 */ 53, 54, 55, 56, 57, 236, 19, 271, 189, 99,
  145022. /* 940 */ 43, 44, 45, 46, 47, 48, 49, 50, 51, 52,
  145023. /* 950 */ 53, 54, 55, 56, 57, 115, 77, 59, 79, 119,
  145024. /* 960 */ 43, 44, 45, 46, 47, 48, 49, 50, 51, 52,
  145025. /* 970 */ 53, 54, 55, 56, 57, 259, 22, 23, 101, 102,
  145026. /* 980 */ 103, 104, 105, 106, 107, 108, 109, 110, 111, 59,
  145027. /* 990 */ 150, 151, 152, 158, 22, 244, 24, 246, 101, 102,
  145028. /* 1000 */ 103, 104, 105, 106, 107, 108, 109, 110, 111, 285,
  145029. /* 1010 */ 189, 189, 114, 115, 116, 200, 136, 137, 101, 102,
  145030. /* 1020 */ 103, 104, 105, 106, 107, 108, 109, 110, 111, 230,
  145031. /* 1030 */ 231, 59, 211, 212, 285, 105, 106, 189, 19, 141,
  145032. /* 1040 */ 234, 235, 239, 113, 114, 115, 116, 226, 118, 234,
  145033. /* 1050 */ 235, 189, 249, 247, 100, 189, 126, 23, 236, 107,
  145034. /* 1060 */ 26, 189, 247, 44, 45, 46, 47, 48, 49, 50,
  145035. /* 1070 */ 51, 52, 53, 54, 55, 56, 57, 211, 212, 59,
  145036. /* 1080 */ 150, 233, 152, 211, 212, 133, 12, 115, 189, 189,
  145037. /* 1090 */ 138, 19, 20, 300, 22, 233, 76, 304, 226, 11,
  145038. /* 1100 */ 208, 27, 22, 23, 200, 19, 26, 87, 36, 89,
  145039. /* 1110 */ 211, 212, 92, 300, 248, 189, 42, 304, 189, 250,
  145040. /* 1120 */ 101, 102, 103, 104, 105, 106, 107, 108, 109, 110,
  145041. /* 1130 */ 111, 59, 200, 233, 114, 115, 116, 63, 234, 235,
  145042. /* 1140 */ 235, 19, 20, 71, 22, 300, 189, 73, 200, 304,
  145043. /* 1150 */ 116, 247, 247, 81, 23, 200, 227, 26, 36, 234,
  145044. /* 1160 */ 235, 203, 204, 143, 200, 26, 234, 235, 194, 200,
  145045. /* 1170 */ 48, 99, 247, 66, 189, 141, 284, 105, 106, 247,
  145046. /* 1180 */ 100, 59, 234, 235, 112, 259, 114, 115, 116, 234,
  145047. /* 1190 */ 235, 119, 85, 71, 266, 247, 211, 212, 234, 235,
  145048. /* 1200 */ 114, 94, 247, 234, 235, 12, 266, 85, 136, 137,
  145049. /* 1210 */ 189, 247, 90, 26, 126, 127, 247, 189, 26, 22,
  145050. /* 1220 */ 27, 99, 150, 151, 152, 153, 154, 105, 106, 189,
  145051. /* 1230 */ 302, 303, 211, 212, 112, 42, 114, 115, 116, 211,
  145052. /* 1240 */ 212, 119, 302, 303, 19, 20, 189, 22, 274, 189,
  145053. /* 1250 */ 15, 144, 278, 189, 22, 23, 63, 189, 189, 203,
  145054. /* 1260 */ 204, 36, 136, 137, 155, 24, 157, 143, 211, 212,
  145055. /* 1270 */ 189, 26, 150, 151, 152, 153, 154, 0, 1, 2,
  145056. /* 1280 */ 211, 212, 5, 46, 59, 161, 147, 10, 11, 12,
  145057. /* 1290 */ 13, 14, 211, 212, 17, 60, 71, 189, 258, 189,
  145058. /* 1300 */ 59, 59, 105, 106, 189, 189, 189, 30, 116, 32,
  145059. /* 1310 */ 85, 124, 189, 251, 252, 90, 189, 40, 258, 211,
  145060. /* 1320 */ 212, 211, 212, 189, 99, 26, 211, 212, 211, 212,
  145061. /* 1330 */ 105, 106, 100, 141, 211, 212, 189, 112, 189, 114,
  145062. /* 1340 */ 115, 116, 24, 189, 119, 31, 23, 70, 189, 26,
  145063. /* 1350 */ 113, 19, 20, 39, 22, 78, 115, 115, 81, 189,
  145064. /* 1360 */ 211, 212, 22, 189, 24, 211, 212, 189, 36, 189,
  145065. /* 1370 */ 211, 212, 189, 189, 97, 150, 151, 152, 153, 154,
  145066. /* 1380 */ 127, 211, 212, 189, 189, 211, 212, 189, 143, 211,
  145067. /* 1390 */ 212, 59, 189, 189, 211, 212, 23, 189, 189, 26,
  145068. /* 1400 */ 59, 189, 149, 71, 22, 211, 212, 189, 131, 211,
  145069. /* 1410 */ 212, 189, 59, 136, 137, 211, 212, 85, 189, 211,
  145070. /* 1420 */ 212, 253, 90, 211, 212, 292, 293, 118, 119, 211,
  145071. /* 1430 */ 212, 99, 23, 211, 212, 26, 159, 105, 106, 140,
  145072. /* 1440 */ 211, 212, 23, 189, 112, 26, 114, 115, 116, 1,
  145073. /* 1450 */ 2, 119, 189, 5, 7, 8, 115, 139, 10, 11,
  145074. /* 1460 */ 12, 13, 14, 23, 189, 17, 26, 189, 115, 189,
  145075. /* 1470 */ 19, 20, 189, 22, 189, 83, 84, 189, 30, 150,
  145076. /* 1480 */ 32, 152, 150, 151, 152, 153, 154, 36, 40, 211,
  145077. /* 1490 */ 212, 211, 212, 189, 211, 212, 211, 212, 309, 189,
  145078. /* 1500 */ 19, 20, 189, 22, 150, 189, 152, 231, 189, 189,
  145079. /* 1510 */ 59, 189, 23, 189, 189, 26, 189, 36, 70, 189,
  145080. /* 1520 */ 23, 139, 71, 26, 211, 212, 78, 211, 212, 81,
  145081. /* 1530 */ 281, 211, 212, 211, 212, 189, 211, 212, 211, 212,
  145082. /* 1540 */ 59, 211, 212, 23, 23, 97, 26, 26, 23, 189,
  145083. /* 1550 */ 99, 26, 71, 189, 119, 189, 105, 106, 107, 189,
  145084. /* 1560 */ 189, 189, 280, 112, 129, 114, 115, 116, 189, 189,
  145085. /* 1570 */ 119, 23, 19, 20, 26, 22, 189, 211, 212, 131,
  145086. /* 1580 */ 99, 237, 211, 212, 136, 137, 105, 106, 189, 36,
  145087. /* 1590 */ 211, 212, 189, 112, 189, 114, 115, 116, 211, 212,
  145088. /* 1600 */ 119, 150, 151, 152, 153, 154, 189, 159, 23, 189,
  145089. /* 1610 */ 23, 26, 59, 26, 189, 189, 189, 189, 189, 189,
  145090. /* 1620 */ 209, 189, 238, 187, 71, 250, 250, 250, 211, 212,
  145091. /* 1630 */ 241, 150, 151, 152, 153, 154, 211, 212, 250, 290,
  145092. /* 1640 */ 254, 211, 212, 211, 212, 254, 215, 286, 241, 241,
  145093. /* 1650 */ 254, 286, 99, 214, 220, 214, 214, 224, 105, 106,
  145094. /* 1660 */ 244, 240, 244, 273, 192, 112, 60, 114, 115, 116,
  145095. /* 1670 */ 139, 290, 119, 5, 196, 238, 196, 38, 10, 11,
  145096. /* 1680 */ 12, 13, 14, 196, 287, 17, 148, 287, 276, 113,
  145097. /* 1690 */ 43, 22, 229, 147, 241, 18, 232, 232, 30, 232,
  145098. /* 1700 */ 32, 232, 264, 150, 151, 152, 153, 154, 40, 265,
  145099. /* 1710 */ 196, 18, 195, 264, 241, 241, 241, 265, 196, 229,
  145100. /* 1720 */ 229, 195, 155, 62, 196, 195, 283, 282, 22, 216,
  145101. /* 1730 */ 196, 195, 216, 196, 195, 113, 213, 213, 70, 64,
  145102. /* 1740 */ 213, 222, 22, 124, 162, 111, 78, 142, 219, 81,
  145103. /* 1750 */ 215, 219, 275, 303, 213, 213, 216, 275, 213, 216,
  145104. /* 1760 */ 213, 256, 113, 255, 255, 97, 222, 216, 256, 196,
  145105. /* 1770 */ 91, 256, 82, 255, 308, 146, 308, 22, 143, 196,
  145106. /* 1780 */ 270, 155, 145, 272, 144, 25, 13, 199, 26, 256,
  145107. /* 1790 */ 198, 190, 190, 6, 296, 188, 188, 188, 244, 131,
  145108. /* 1800 */ 245, 245, 243, 242, 136, 137, 241, 255, 208, 260,
  145109. /* 1810 */ 260, 208, 202, 217, 217, 202, 4, 3, 202, 208,
  145110. /* 1820 */ 208, 22, 160, 209, 209, 208, 15, 159, 98, 16,
  145111. /* 1830 */ 23, 23, 137, 148, 24, 128, 140, 20, 16, 142,
  145112. /* 1840 */ 1, 140, 128, 149, 61, 53, 37, 148, 53, 53,
  145113. /* 1850 */ 53, 293, 128, 296, 114, 34, 139, 1, 5, 22,
  145114. /* 1860 */ 113, 158, 68, 75, 26, 41, 68, 139, 24, 113,
  145115. /* 1870 */ 20, 19, 129, 123, 23, 96, 22, 22, 59, 22,
  145116. /* 1880 */ 22, 147, 67, 67, 24, 22, 37, 28, 23, 22,
  145117. /* 1890 */ 67, 23, 23, 23, 114, 23, 22, 26, 22, 24,
  145118. /* 1900 */ 23, 22, 24, 139, 23, 23, 141, 34, 88, 26,
  145119. /* 1910 */ 75, 86, 23, 22, 34, 75, 24, 23, 34, 34,
  145120. /* 1920 */ 34, 93, 34, 26, 26, 23, 23, 34, 23, 23,
  145121. /* 1930 */ 26, 44, 23, 22, 11, 22, 22, 133, 23, 23,
  145122. /* 1940 */ 22, 22, 139, 26, 139, 139, 15, 23, 1, 1,
  145123. /* 1950 */ 310, 310, 310, 310, 310, 310, 310, 139, 310, 310,
  145124. /* 1960 */ 310, 310, 310, 310, 310, 310, 310, 310, 310, 310,
  145125. /* 1970 */ 310, 310, 310, 310, 310, 310, 310, 310, 310, 310,
  145126. /* 1980 */ 310, 310, 310, 310, 310, 310, 310, 310, 310, 310,
  145127. /* 1990 */ 310, 310, 310, 310, 310, 310, 310, 310, 310, 310,
  145128. /* 2000 */ 310, 310, 310, 310, 310, 310, 310, 310, 310, 310,
  145129. /* 2010 */ 310, 310, 310, 310, 310, 310, 310, 310, 310, 310,
  145130. /* 2020 */ 310, 310, 310, 310, 310, 310, 310, 310, 310, 310,
  145131. /* 2030 */ 310, 310, 310, 310, 310, 310, 310, 310, 310, 310,
  145132. /* 2040 */ 310, 310, 310, 310, 310, 310, 310, 310, 310, 310,
  145133. /* 2050 */ 310, 310, 310, 310, 310, 310, 310, 310, 310, 310,
  145134. /* 2060 */ 310, 310, 310, 310, 310, 310, 310, 310, 310, 310,
  145135. /* 2070 */ 310, 310, 310, 310, 310, 310, 310, 310, 310, 310,
  145136. /* 2080 */ 310, 310, 310, 310, 310, 310, 310, 310, 310, 310,
  145137. /* 2090 */ 310, 310, 310, 310, 310, 310, 310, 310, 310, 310,
  145138. /* 2100 */ 310, 310, 310, 310, 310, 310, 310, 310, 310, 310,
  145139. /* 2110 */ 310, 310, 310, 310, 310, 310, 310, 310, 310, 310,
  145140. /* 2120 */ 310, 310, 310, 310, 310, 310, 310, 310, 310, 310,
  145141. /* 2130 */ 310, 310, 310, 310, 310, 310, 310, 310, 310,
  145142. };
  145143. #define YY_SHIFT_COUNT (550)
  145144. #define YY_SHIFT_MIN (0)
  145145. #define YY_SHIFT_MAX (1948)
  145146. static const unsigned short int yy_shift_ofst[] = {
  145147. /* 0 */ 1448, 1277, 1668, 1072, 1072, 340, 1122, 1225, 1332, 1481,
  145148. /* 10 */ 1481, 1481, 335, 0, 0, 180, 897, 1481, 1481, 1481,
  145149. /* 20 */ 1481, 1481, 1481, 1481, 1481, 1481, 1481, 1481, 1481, 1481,
  145150. /* 30 */ 930, 930, 1020, 1020, 290, 1, 340, 340, 340, 340,
  145151. /* 40 */ 340, 340, 40, 110, 219, 288, 327, 396, 435, 504,
  145152. /* 50 */ 543, 612, 651, 720, 877, 897, 897, 897, 897, 897,
  145153. /* 60 */ 897, 897, 897, 897, 897, 897, 897, 897, 897, 897,
  145154. /* 70 */ 897, 897, 897, 917, 897, 1019, 763, 763, 1451, 1481,
  145155. /* 80 */ 1481, 1481, 1481, 1481, 1481, 1481, 1481, 1481, 1481, 1481,
  145156. /* 90 */ 1481, 1481, 1481, 1481, 1481, 1481, 1481, 1481, 1481, 1481,
  145157. /* 100 */ 1481, 1481, 1481, 1481, 1481, 1481, 1481, 1481, 1481, 1481,
  145158. /* 110 */ 1481, 1481, 1553, 1481, 1481, 1481, 1481, 1481, 1481, 1481,
  145159. /* 120 */ 1481, 1481, 1481, 1481, 1481, 1481, 147, 258, 258, 258,
  145160. /* 130 */ 258, 258, 79, 65, 84, 449, 19, 786, 449, 636,
  145161. /* 140 */ 636, 449, 880, 880, 880, 880, 113, 142, 142, 472,
  145162. /* 150 */ 150, 1958, 1958, 399, 399, 399, 93, 237, 341, 237,
  145163. /* 160 */ 237, 1074, 1074, 437, 350, 704, 1080, 449, 449, 449,
  145164. /* 170 */ 449, 449, 449, 449, 449, 449, 449, 449, 449, 449,
  145165. /* 180 */ 449, 449, 449, 449, 449, 449, 449, 449, 818, 818,
  145166. /* 190 */ 449, 1088, 217, 217, 734, 734, 1124, 1126, 1958, 1958,
  145167. /* 200 */ 1958, 739, 840, 840, 453, 454, 511, 187, 563, 570,
  145168. /* 210 */ 898, 669, 449, 449, 449, 449, 449, 449, 449, 449,
  145169. /* 220 */ 449, 670, 449, 449, 449, 449, 449, 449, 449, 449,
  145170. /* 230 */ 449, 449, 449, 449, 674, 674, 674, 449, 449, 449,
  145171. /* 240 */ 449, 1034, 449, 449, 449, 972, 1107, 449, 449, 1193,
  145172. /* 250 */ 449, 449, 449, 449, 449, 449, 449, 449, 260, 177,
  145173. /* 260 */ 489, 1241, 1241, 1241, 1241, 1192, 489, 489, 952, 1197,
  145174. /* 270 */ 625, 1235, 1139, 181, 181, 1086, 1139, 1139, 1086, 1187,
  145175. /* 280 */ 1131, 1237, 1314, 1314, 1314, 181, 1245, 1245, 1109, 1299,
  145176. /* 290 */ 549, 1340, 1606, 1531, 1531, 1639, 1639, 1531, 1538, 1576,
  145177. /* 300 */ 1669, 1647, 1546, 1677, 1677, 1677, 1677, 1531, 1693, 1546,
  145178. /* 310 */ 1546, 1576, 1669, 1647, 1647, 1546, 1531, 1693, 1567, 1661,
  145179. /* 320 */ 1531, 1693, 1706, 1531, 1693, 1531, 1693, 1706, 1622, 1622,
  145180. /* 330 */ 1622, 1675, 1720, 1720, 1706, 1622, 1619, 1622, 1675, 1622,
  145181. /* 340 */ 1622, 1582, 1706, 1634, 1634, 1706, 1605, 1649, 1605, 1649,
  145182. /* 350 */ 1605, 1649, 1605, 1649, 1531, 1679, 1679, 1690, 1690, 1629,
  145183. /* 360 */ 1635, 1755, 1531, 1626, 1629, 1637, 1640, 1546, 1760, 1762,
  145184. /* 370 */ 1773, 1773, 1787, 1787, 1787, 1958, 1958, 1958, 1958, 1958,
  145185. /* 380 */ 1958, 1958, 1958, 1958, 1958, 1958, 1958, 1958, 1958, 1958,
  145186. /* 390 */ 308, 835, 954, 1232, 879, 715, 728, 1323, 864, 1318,
  145187. /* 400 */ 1253, 1373, 297, 1409, 1419, 1440, 1489, 1497, 1520, 1242,
  145188. /* 410 */ 1309, 1447, 1435, 1341, 1521, 1525, 1392, 1548, 1329, 1354,
  145189. /* 420 */ 1585, 1587, 1353, 1382, 1812, 1814, 1799, 1662, 1811, 1730,
  145190. /* 430 */ 1813, 1807, 1808, 1695, 1685, 1707, 1810, 1696, 1817, 1697,
  145191. /* 440 */ 1822, 1839, 1701, 1694, 1714, 1783, 1809, 1699, 1792, 1795,
  145192. /* 450 */ 1796, 1797, 1724, 1740, 1821, 1717, 1856, 1853, 1837, 1747,
  145193. /* 460 */ 1703, 1794, 1838, 1798, 1788, 1824, 1728, 1756, 1844, 1850,
  145194. /* 470 */ 1852, 1743, 1750, 1854, 1815, 1855, 1857, 1851, 1858, 1816,
  145195. /* 480 */ 1819, 1860, 1779, 1859, 1863, 1823, 1849, 1865, 1734, 1867,
  145196. /* 490 */ 1868, 1869, 1870, 1871, 1872, 1874, 1875, 1877, 1876, 1878,
  145197. /* 500 */ 1764, 1881, 1882, 1780, 1873, 1879, 1765, 1883, 1880, 1884,
  145198. /* 510 */ 1885, 1886, 1820, 1835, 1825, 1887, 1840, 1828, 1888, 1889,
  145199. /* 520 */ 1891, 1892, 1897, 1898, 1893, 1894, 1883, 1902, 1903, 1905,
  145200. /* 530 */ 1906, 1904, 1909, 1911, 1923, 1913, 1914, 1915, 1916, 1918,
  145201. /* 540 */ 1919, 1917, 1804, 1803, 1805, 1806, 1818, 1924, 1931, 1947,
  145202. /* 550 */ 1948,
  145203. };
  145204. #define YY_REDUCE_COUNT (389)
  145205. #define YY_REDUCE_MIN (-262)
  145206. #define YY_REDUCE_MAX (1617)
  145207. static const short yy_reduce_ofst[] = {
  145208. /* 0 */ 490, -122, 545, 645, 650, -120, -189, -187, -184, -182,
  145209. /* 10 */ -178, -176, 45, 30, 200, -251, -134, 390, 392, 521,
  145210. /* 20 */ 523, 213, 692, 821, 284, 589, 872, 666, 671, 866,
  145211. /* 30 */ 71, 111, 273, 389, 686, 815, 904, 932, 948, 955,
  145212. /* 40 */ 964, 969, -259, -259, -259, -259, -259, -259, -259, -259,
  145213. /* 50 */ -259, -259, -259, -259, -259, -259, -259, -259, -259, -259,
  145214. /* 60 */ -259, -259, -259, -259, -259, -259, -259, -259, -259, -259,
  145215. /* 70 */ -259, -259, -259, -259, -259, -259, -259, -259, 428, 430,
  145216. /* 80 */ 899, 985, 1021, 1028, 1057, 1069, 1081, 1108, 1110, 1115,
  145217. /* 90 */ 1117, 1123, 1149, 1154, 1159, 1170, 1174, 1178, 1183, 1194,
  145218. /* 100 */ 1198, 1204, 1208, 1212, 1218, 1222, 1229, 1278, 1280, 1283,
  145219. /* 110 */ 1285, 1313, 1316, 1320, 1322, 1325, 1327, 1330, 1366, 1371,
  145220. /* 120 */ 1379, 1387, 1417, 1425, 1430, 1432, -259, -259, -259, -259,
  145221. /* 130 */ -259, -259, -259, -259, -259, 557, 974, -214, -174, -9,
  145222. /* 140 */ 431, -124, 806, 925, 806, 925, 251, 928, 940, -259,
  145223. /* 150 */ -259, -259, -259, -198, -198, -198, 127, -186, -168, 212,
  145224. /* 160 */ 646, 617, 799, -262, 555, 220, 220, 491, 605, 1040,
  145225. /* 170 */ 1060, 699, -11, 600, 848, 862, 345, -129, 724, -91,
  145226. /* 180 */ 158, 749, 716, 900, 304, 822, 929, 926, 499, 793,
  145227. /* 190 */ 322, 892, 813, 845, 958, 1056, 751, 905, 1133, 1062,
  145228. /* 200 */ 803, -210, -185, -179, -148, -167, -89, 121, 274, 281,
  145229. /* 210 */ 320, 336, 439, 663, 711, 957, 1064, 1068, 1116, 1127,
  145230. /* 220 */ 1134, -196, 1147, 1180, 1184, 1195, 1203, 1209, 1254, 1263,
  145231. /* 230 */ 1275, 1288, 1304, 1310, 205, 422, 638, 1319, 1324, 1346,
  145232. /* 240 */ 1360, 1168, 1364, 1370, 1372, 869, 1189, 1380, 1399, 1276,
  145233. /* 250 */ 1403, 121, 1405, 1420, 1426, 1427, 1428, 1429, 1249, 1282,
  145234. /* 260 */ 1344, 1375, 1376, 1377, 1388, 1168, 1344, 1344, 1384, 1411,
  145235. /* 270 */ 1436, 1349, 1389, 1386, 1391, 1361, 1407, 1408, 1365, 1431,
  145236. /* 280 */ 1433, 1434, 1439, 1441, 1442, 1396, 1416, 1418, 1390, 1421,
  145237. /* 290 */ 1437, 1472, 1381, 1478, 1480, 1397, 1400, 1487, 1412, 1444,
  145238. /* 300 */ 1438, 1463, 1453, 1464, 1465, 1467, 1469, 1514, 1517, 1473,
  145239. /* 310 */ 1474, 1452, 1449, 1490, 1491, 1475, 1522, 1526, 1443, 1445,
  145240. /* 320 */ 1528, 1530, 1513, 1534, 1536, 1537, 1539, 1516, 1523, 1524,
  145241. /* 330 */ 1527, 1519, 1529, 1532, 1540, 1541, 1535, 1542, 1544, 1545,
  145242. /* 340 */ 1547, 1450, 1543, 1477, 1482, 1551, 1505, 1508, 1512, 1509,
  145243. /* 350 */ 1515, 1518, 1533, 1552, 1573, 1466, 1468, 1549, 1550, 1555,
  145244. /* 360 */ 1554, 1510, 1583, 1511, 1556, 1559, 1561, 1565, 1588, 1592,
  145245. /* 370 */ 1601, 1602, 1607, 1608, 1609, 1498, 1557, 1558, 1610, 1600,
  145246. /* 380 */ 1603, 1611, 1612, 1613, 1596, 1597, 1614, 1615, 1617, 1616,
  145247. };
  145248. static const YYACTIONTYPE yy_default[] = {
  145249. /* 0 */ 1573, 1573, 1573, 1409, 1186, 1295, 1186, 1186, 1186, 1409,
  145250. /* 10 */ 1409, 1409, 1186, 1325, 1325, 1462, 1217, 1186, 1186, 1186,
  145251. /* 20 */ 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1408, 1186, 1186,
  145252. /* 30 */ 1186, 1186, 1492, 1492, 1186, 1186, 1186, 1186, 1186, 1186,
  145253. /* 40 */ 1186, 1186, 1186, 1334, 1186, 1186, 1186, 1186, 1186, 1186,
  145254. /* 50 */ 1410, 1411, 1186, 1186, 1186, 1461, 1463, 1426, 1344, 1343,
  145255. /* 60 */ 1342, 1341, 1444, 1312, 1339, 1332, 1336, 1404, 1405, 1403,
  145256. /* 70 */ 1407, 1411, 1410, 1186, 1335, 1375, 1389, 1374, 1186, 1186,
  145257. /* 80 */ 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186,
  145258. /* 90 */ 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186,
  145259. /* 100 */ 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186,
  145260. /* 110 */ 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186,
  145261. /* 120 */ 1186, 1186, 1186, 1186, 1186, 1186, 1383, 1388, 1394, 1387,
  145262. /* 130 */ 1384, 1377, 1376, 1378, 1379, 1186, 1207, 1259, 1186, 1186,
  145263. /* 140 */ 1186, 1186, 1480, 1479, 1186, 1186, 1217, 1369, 1368, 1380,
  145264. /* 150 */ 1381, 1391, 1390, 1469, 1527, 1526, 1427, 1186, 1186, 1186,
  145265. /* 160 */ 1186, 1186, 1186, 1492, 1186, 1186, 1186, 1186, 1186, 1186,
  145266. /* 170 */ 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186,
  145267. /* 180 */ 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1492, 1492,
  145268. /* 190 */ 1186, 1217, 1492, 1492, 1213, 1213, 1319, 1186, 1475, 1295,
  145269. /* 200 */ 1286, 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186,
  145270. /* 210 */ 1186, 1186, 1186, 1186, 1186, 1466, 1464, 1186, 1186, 1186,
  145271. /* 220 */ 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186,
  145272. /* 230 */ 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186,
  145273. /* 240 */ 1186, 1186, 1186, 1186, 1186, 1291, 1186, 1186, 1186, 1186,
  145274. /* 250 */ 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1521, 1186, 1439,
  145275. /* 260 */ 1273, 1291, 1291, 1291, 1291, 1293, 1274, 1272, 1285, 1218,
  145276. /* 270 */ 1193, 1565, 1338, 1314, 1314, 1562, 1338, 1338, 1562, 1234,
  145277. /* 280 */ 1543, 1229, 1325, 1325, 1325, 1314, 1319, 1319, 1406, 1292,
  145278. /* 290 */ 1285, 1186, 1565, 1300, 1300, 1564, 1564, 1300, 1427, 1347,
  145279. /* 300 */ 1353, 1262, 1338, 1268, 1268, 1268, 1268, 1300, 1204, 1338,
  145280. /* 310 */ 1338, 1347, 1353, 1262, 1262, 1338, 1300, 1204, 1443, 1559,
  145281. /* 320 */ 1300, 1204, 1417, 1300, 1204, 1300, 1204, 1417, 1260, 1260,
  145282. /* 330 */ 1260, 1249, 1186, 1186, 1417, 1260, 1234, 1260, 1249, 1260,
  145283. /* 340 */ 1260, 1510, 1417, 1421, 1421, 1417, 1318, 1313, 1318, 1313,
  145284. /* 350 */ 1318, 1313, 1318, 1313, 1300, 1502, 1502, 1328, 1328, 1333,
  145285. /* 360 */ 1319, 1412, 1300, 1186, 1333, 1331, 1329, 1338, 1210, 1252,
  145286. /* 370 */ 1524, 1524, 1520, 1520, 1520, 1570, 1570, 1475, 1536, 1217,
  145287. /* 380 */ 1217, 1217, 1217, 1536, 1236, 1236, 1218, 1218, 1217, 1536,
  145288. /* 390 */ 1186, 1186, 1186, 1186, 1186, 1186, 1531, 1186, 1428, 1304,
  145289. /* 400 */ 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186,
  145290. /* 410 */ 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186,
  145291. /* 420 */ 1186, 1186, 1186, 1358, 1186, 1189, 1472, 1186, 1186, 1470,
  145292. /* 430 */ 1186, 1186, 1186, 1186, 1186, 1186, 1305, 1186, 1186, 1186,
  145293. /* 440 */ 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186,
  145294. /* 450 */ 1186, 1186, 1186, 1186, 1186, 1561, 1186, 1186, 1186, 1186,
  145295. /* 460 */ 1186, 1186, 1442, 1441, 1186, 1186, 1302, 1186, 1186, 1186,
  145296. /* 470 */ 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186,
  145297. /* 480 */ 1232, 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186,
  145298. /* 490 */ 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186,
  145299. /* 500 */ 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1330, 1186, 1186,
  145300. /* 510 */ 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186,
  145301. /* 520 */ 1186, 1186, 1507, 1320, 1186, 1186, 1552, 1186, 1186, 1186,
  145302. /* 530 */ 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186, 1186,
  145303. /* 540 */ 1186, 1547, 1276, 1360, 1186, 1359, 1363, 1186, 1198, 1186,
  145304. /* 550 */ 1186,
  145305. };
  145306. /********** End of lemon-generated parsing tables *****************************/
  145307. /* The next table maps tokens (terminal symbols) into fallback tokens.
  145308. ** If a construct like the following:
  145309. **
  145310. ** %fallback ID X Y Z.
  145311. **
  145312. ** appears in the grammar, then ID becomes a fallback token for X, Y,
  145313. ** and Z. Whenever one of the tokens X, Y, or Z is input to the parser
  145314. ** but it does not parse, the type of the token is changed to ID and
  145315. ** the parse is retried before an error is thrown.
  145316. **
  145317. ** This feature can be used, for example, to cause some keywords in a language
  145318. ** to revert to identifiers if they keyword does not apply in the context where
  145319. ** it appears.
  145320. */
  145321. #ifdef YYFALLBACK
  145322. static const YYCODETYPE yyFallback[] = {
  145323. 0, /* $ => nothing */
  145324. 0, /* SEMI => nothing */
  145325. 59, /* EXPLAIN => ID */
  145326. 59, /* QUERY => ID */
  145327. 59, /* PLAN => ID */
  145328. 59, /* BEGIN => ID */
  145329. 0, /* TRANSACTION => nothing */
  145330. 59, /* DEFERRED => ID */
  145331. 59, /* IMMEDIATE => ID */
  145332. 59, /* EXCLUSIVE => ID */
  145333. 0, /* COMMIT => nothing */
  145334. 59, /* END => ID */
  145335. 59, /* ROLLBACK => ID */
  145336. 59, /* SAVEPOINT => ID */
  145337. 59, /* RELEASE => ID */
  145338. 0, /* TO => nothing */
  145339. 0, /* TABLE => nothing */
  145340. 0, /* CREATE => nothing */
  145341. 59, /* IF => ID */
  145342. 0, /* NOT => nothing */
  145343. 0, /* EXISTS => nothing */
  145344. 59, /* TEMP => ID */
  145345. 0, /* LP => nothing */
  145346. 0, /* RP => nothing */
  145347. 0, /* AS => nothing */
  145348. 59, /* WITHOUT => ID */
  145349. 0, /* COMMA => nothing */
  145350. 59, /* ABORT => ID */
  145351. 59, /* ACTION => ID */
  145352. 59, /* AFTER => ID */
  145353. 59, /* ANALYZE => ID */
  145354. 59, /* ASC => ID */
  145355. 59, /* ATTACH => ID */
  145356. 59, /* BEFORE => ID */
  145357. 59, /* BY => ID */
  145358. 59, /* CASCADE => ID */
  145359. 59, /* CAST => ID */
  145360. 59, /* CONFLICT => ID */
  145361. 59, /* DATABASE => ID */
  145362. 59, /* DESC => ID */
  145363. 59, /* DETACH => ID */
  145364. 59, /* EACH => ID */
  145365. 59, /* FAIL => ID */
  145366. 0, /* OR => nothing */
  145367. 0, /* AND => nothing */
  145368. 0, /* IS => nothing */
  145369. 59, /* MATCH => ID */
  145370. 59, /* LIKE_KW => ID */
  145371. 0, /* BETWEEN => nothing */
  145372. 0, /* IN => nothing */
  145373. 0, /* ISNULL => nothing */
  145374. 0, /* NOTNULL => nothing */
  145375. 0, /* NE => nothing */
  145376. 0, /* EQ => nothing */
  145377. 0, /* GT => nothing */
  145378. 0, /* LE => nothing */
  145379. 0, /* LT => nothing */
  145380. 0, /* GE => nothing */
  145381. 0, /* ESCAPE => nothing */
  145382. 0, /* ID => nothing */
  145383. 59, /* COLUMNKW => ID */
  145384. 59, /* DO => ID */
  145385. 59, /* FOR => ID */
  145386. 59, /* IGNORE => ID */
  145387. 59, /* INITIALLY => ID */
  145388. 59, /* INSTEAD => ID */
  145389. 59, /* NO => ID */
  145390. 59, /* KEY => ID */
  145391. 59, /* OF => ID */
  145392. 59, /* OFFSET => ID */
  145393. 59, /* PRAGMA => ID */
  145394. 59, /* RAISE => ID */
  145395. 59, /* RECURSIVE => ID */
  145396. 59, /* REPLACE => ID */
  145397. 59, /* RESTRICT => ID */
  145398. 59, /* ROW => ID */
  145399. 59, /* ROWS => ID */
  145400. 59, /* TRIGGER => ID */
  145401. 59, /* VACUUM => ID */
  145402. 59, /* VIEW => ID */
  145403. 59, /* VIRTUAL => ID */
  145404. 59, /* WITH => ID */
  145405. 59, /* NULLS => ID */
  145406. 59, /* FIRST => ID */
  145407. 59, /* LAST => ID */
  145408. 59, /* CURRENT => ID */
  145409. 59, /* FOLLOWING => ID */
  145410. 59, /* PARTITION => ID */
  145411. 59, /* PRECEDING => ID */
  145412. 59, /* RANGE => ID */
  145413. 59, /* UNBOUNDED => ID */
  145414. 59, /* EXCLUDE => ID */
  145415. 59, /* GROUPS => ID */
  145416. 59, /* OTHERS => ID */
  145417. 59, /* TIES => ID */
  145418. 59, /* GENERATED => ID */
  145419. 59, /* ALWAYS => ID */
  145420. 59, /* REINDEX => ID */
  145421. 59, /* RENAME => ID */
  145422. 59, /* CTIME_KW => ID */
  145423. 0, /* ANY => nothing */
  145424. 0, /* BITAND => nothing */
  145425. 0, /* BITOR => nothing */
  145426. 0, /* LSHIFT => nothing */
  145427. 0, /* RSHIFT => nothing */
  145428. 0, /* PLUS => nothing */
  145429. 0, /* MINUS => nothing */
  145430. 0, /* STAR => nothing */
  145431. 0, /* SLASH => nothing */
  145432. 0, /* REM => nothing */
  145433. 0, /* CONCAT => nothing */
  145434. 0, /* COLLATE => nothing */
  145435. 0, /* BITNOT => nothing */
  145436. 0, /* ON => nothing */
  145437. 0, /* INDEXED => nothing */
  145438. 0, /* STRING => nothing */
  145439. 0, /* JOIN_KW => nothing */
  145440. 0, /* CONSTRAINT => nothing */
  145441. 0, /* DEFAULT => nothing */
  145442. 0, /* NULL => nothing */
  145443. 0, /* PRIMARY => nothing */
  145444. 0, /* UNIQUE => nothing */
  145445. 0, /* CHECK => nothing */
  145446. 0, /* REFERENCES => nothing */
  145447. 0, /* AUTOINCR => nothing */
  145448. 0, /* INSERT => nothing */
  145449. 0, /* DELETE => nothing */
  145450. 0, /* UPDATE => nothing */
  145451. 0, /* SET => nothing */
  145452. 0, /* DEFERRABLE => nothing */
  145453. 0, /* FOREIGN => nothing */
  145454. 0, /* DROP => nothing */
  145455. 0, /* UNION => nothing */
  145456. 0, /* ALL => nothing */
  145457. 0, /* EXCEPT => nothing */
  145458. 0, /* INTERSECT => nothing */
  145459. 0, /* SELECT => nothing */
  145460. 0, /* VALUES => nothing */
  145461. 0, /* DISTINCT => nothing */
  145462. 0, /* DOT => nothing */
  145463. 0, /* FROM => nothing */
  145464. 0, /* JOIN => nothing */
  145465. 0, /* USING => nothing */
  145466. 0, /* ORDER => nothing */
  145467. 0, /* GROUP => nothing */
  145468. 0, /* HAVING => nothing */
  145469. 0, /* LIMIT => nothing */
  145470. 0, /* WHERE => nothing */
  145471. 0, /* INTO => nothing */
  145472. 0, /* NOTHING => nothing */
  145473. 0, /* FLOAT => nothing */
  145474. 0, /* BLOB => nothing */
  145475. 0, /* INTEGER => nothing */
  145476. 0, /* VARIABLE => nothing */
  145477. 0, /* CASE => nothing */
  145478. 0, /* WHEN => nothing */
  145479. 0, /* THEN => nothing */
  145480. 0, /* ELSE => nothing */
  145481. 0, /* INDEX => nothing */
  145482. 0, /* ALTER => nothing */
  145483. 0, /* ADD => nothing */
  145484. 0, /* WINDOW => nothing */
  145485. 0, /* OVER => nothing */
  145486. 0, /* FILTER => nothing */
  145487. 0, /* COLUMN => nothing */
  145488. 0, /* AGG_FUNCTION => nothing */
  145489. 0, /* AGG_COLUMN => nothing */
  145490. 0, /* TRUEFALSE => nothing */
  145491. 0, /* ISNOT => nothing */
  145492. 0, /* FUNCTION => nothing */
  145493. 0, /* UMINUS => nothing */
  145494. 0, /* UPLUS => nothing */
  145495. 0, /* TRUTH => nothing */
  145496. 0, /* REGISTER => nothing */
  145497. 0, /* VECTOR => nothing */
  145498. 0, /* SELECT_COLUMN => nothing */
  145499. 0, /* IF_NULL_ROW => nothing */
  145500. 0, /* ASTERISK => nothing */
  145501. 0, /* SPAN => nothing */
  145502. 0, /* SPACE => nothing */
  145503. 0, /* ILLEGAL => nothing */
  145504. };
  145505. #endif /* YYFALLBACK */
  145506. /* The following structure represents a single element of the
  145507. ** parser's stack. Information stored includes:
  145508. **
  145509. ** + The state number for the parser at this level of the stack.
  145510. **
  145511. ** + The value of the token stored at this level of the stack.
  145512. ** (In other words, the "major" token.)
  145513. **
  145514. ** + The semantic value stored at this level of the stack. This is
  145515. ** the information used by the action routines in the grammar.
  145516. ** It is sometimes called the "minor" token.
  145517. **
  145518. ** After the "shift" half of a SHIFTREDUCE action, the stateno field
  145519. ** actually contains the reduce action for the second half of the
  145520. ** SHIFTREDUCE.
  145521. */
  145522. struct yyStackEntry {
  145523. YYACTIONTYPE stateno; /* The state-number, or reduce action in SHIFTREDUCE */
  145524. YYCODETYPE major; /* The major token value. This is the code
  145525. ** number for the token at this stack level */
  145526. YYMINORTYPE minor; /* The user-supplied minor token value. This
  145527. ** is the value of the token */
  145528. };
  145529. typedef struct yyStackEntry yyStackEntry;
  145530. /* The state of the parser is completely contained in an instance of
  145531. ** the following structure */
  145532. struct yyParser {
  145533. yyStackEntry *yytos; /* Pointer to top element of the stack */
  145534. #ifdef YYTRACKMAXSTACKDEPTH
  145535. int yyhwm; /* High-water mark of the stack */
  145536. #endif
  145537. #ifndef YYNOERRORRECOVERY
  145538. int yyerrcnt; /* Shifts left before out of the error */
  145539. #endif
  145540. sqlite3ParserARG_SDECL /* A place to hold %extra_argument */
  145541. sqlite3ParserCTX_SDECL /* A place to hold %extra_context */
  145542. #if YYSTACKDEPTH<=0
  145543. int yystksz; /* Current side of the stack */
  145544. yyStackEntry *yystack; /* The parser's stack */
  145545. yyStackEntry yystk0; /* First stack entry */
  145546. #else
  145547. yyStackEntry yystack[YYSTACKDEPTH]; /* The parser's stack */
  145548. yyStackEntry *yystackEnd; /* Last entry in the stack */
  145549. #endif
  145550. };
  145551. typedef struct yyParser yyParser;
  145552. #ifndef NDEBUG
  145553. /* #include <stdio.h> */
  145554. static FILE *yyTraceFILE = 0;
  145555. static char *yyTracePrompt = 0;
  145556. #endif /* NDEBUG */
  145557. #ifndef NDEBUG
  145558. /*
  145559. ** Turn parser tracing on by giving a stream to which to write the trace
  145560. ** and a prompt to preface each trace message. Tracing is turned off
  145561. ** by making either argument NULL
  145562. **
  145563. ** Inputs:
  145564. ** <ul>
  145565. ** <li> A FILE* to which trace output should be written.
  145566. ** If NULL, then tracing is turned off.
  145567. ** <li> A prefix string written at the beginning of every
  145568. ** line of trace output. If NULL, then tracing is
  145569. ** turned off.
  145570. ** </ul>
  145571. **
  145572. ** Outputs:
  145573. ** None.
  145574. */
  145575. SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
  145576. yyTraceFILE = TraceFILE;
  145577. yyTracePrompt = zTracePrompt;
  145578. if( yyTraceFILE==0 ) yyTracePrompt = 0;
  145579. else if( yyTracePrompt==0 ) yyTraceFILE = 0;
  145580. }
  145581. #endif /* NDEBUG */
  145582. #if defined(YYCOVERAGE) || !defined(NDEBUG)
  145583. /* For tracing shifts, the names of all terminals and nonterminals
  145584. ** are required. The following table supplies these names */
  145585. static const char *const yyTokenName[] = {
  145586. /* 0 */ "$",
  145587. /* 1 */ "SEMI",
  145588. /* 2 */ "EXPLAIN",
  145589. /* 3 */ "QUERY",
  145590. /* 4 */ "PLAN",
  145591. /* 5 */ "BEGIN",
  145592. /* 6 */ "TRANSACTION",
  145593. /* 7 */ "DEFERRED",
  145594. /* 8 */ "IMMEDIATE",
  145595. /* 9 */ "EXCLUSIVE",
  145596. /* 10 */ "COMMIT",
  145597. /* 11 */ "END",
  145598. /* 12 */ "ROLLBACK",
  145599. /* 13 */ "SAVEPOINT",
  145600. /* 14 */ "RELEASE",
  145601. /* 15 */ "TO",
  145602. /* 16 */ "TABLE",
  145603. /* 17 */ "CREATE",
  145604. /* 18 */ "IF",
  145605. /* 19 */ "NOT",
  145606. /* 20 */ "EXISTS",
  145607. /* 21 */ "TEMP",
  145608. /* 22 */ "LP",
  145609. /* 23 */ "RP",
  145610. /* 24 */ "AS",
  145611. /* 25 */ "WITHOUT",
  145612. /* 26 */ "COMMA",
  145613. /* 27 */ "ABORT",
  145614. /* 28 */ "ACTION",
  145615. /* 29 */ "AFTER",
  145616. /* 30 */ "ANALYZE",
  145617. /* 31 */ "ASC",
  145618. /* 32 */ "ATTACH",
  145619. /* 33 */ "BEFORE",
  145620. /* 34 */ "BY",
  145621. /* 35 */ "CASCADE",
  145622. /* 36 */ "CAST",
  145623. /* 37 */ "CONFLICT",
  145624. /* 38 */ "DATABASE",
  145625. /* 39 */ "DESC",
  145626. /* 40 */ "DETACH",
  145627. /* 41 */ "EACH",
  145628. /* 42 */ "FAIL",
  145629. /* 43 */ "OR",
  145630. /* 44 */ "AND",
  145631. /* 45 */ "IS",
  145632. /* 46 */ "MATCH",
  145633. /* 47 */ "LIKE_KW",
  145634. /* 48 */ "BETWEEN",
  145635. /* 49 */ "IN",
  145636. /* 50 */ "ISNULL",
  145637. /* 51 */ "NOTNULL",
  145638. /* 52 */ "NE",
  145639. /* 53 */ "EQ",
  145640. /* 54 */ "GT",
  145641. /* 55 */ "LE",
  145642. /* 56 */ "LT",
  145643. /* 57 */ "GE",
  145644. /* 58 */ "ESCAPE",
  145645. /* 59 */ "ID",
  145646. /* 60 */ "COLUMNKW",
  145647. /* 61 */ "DO",
  145648. /* 62 */ "FOR",
  145649. /* 63 */ "IGNORE",
  145650. /* 64 */ "INITIALLY",
  145651. /* 65 */ "INSTEAD",
  145652. /* 66 */ "NO",
  145653. /* 67 */ "KEY",
  145654. /* 68 */ "OF",
  145655. /* 69 */ "OFFSET",
  145656. /* 70 */ "PRAGMA",
  145657. /* 71 */ "RAISE",
  145658. /* 72 */ "RECURSIVE",
  145659. /* 73 */ "REPLACE",
  145660. /* 74 */ "RESTRICT",
  145661. /* 75 */ "ROW",
  145662. /* 76 */ "ROWS",
  145663. /* 77 */ "TRIGGER",
  145664. /* 78 */ "VACUUM",
  145665. /* 79 */ "VIEW",
  145666. /* 80 */ "VIRTUAL",
  145667. /* 81 */ "WITH",
  145668. /* 82 */ "NULLS",
  145669. /* 83 */ "FIRST",
  145670. /* 84 */ "LAST",
  145671. /* 85 */ "CURRENT",
  145672. /* 86 */ "FOLLOWING",
  145673. /* 87 */ "PARTITION",
  145674. /* 88 */ "PRECEDING",
  145675. /* 89 */ "RANGE",
  145676. /* 90 */ "UNBOUNDED",
  145677. /* 91 */ "EXCLUDE",
  145678. /* 92 */ "GROUPS",
  145679. /* 93 */ "OTHERS",
  145680. /* 94 */ "TIES",
  145681. /* 95 */ "GENERATED",
  145682. /* 96 */ "ALWAYS",
  145683. /* 97 */ "REINDEX",
  145684. /* 98 */ "RENAME",
  145685. /* 99 */ "CTIME_KW",
  145686. /* 100 */ "ANY",
  145687. /* 101 */ "BITAND",
  145688. /* 102 */ "BITOR",
  145689. /* 103 */ "LSHIFT",
  145690. /* 104 */ "RSHIFT",
  145691. /* 105 */ "PLUS",
  145692. /* 106 */ "MINUS",
  145693. /* 107 */ "STAR",
  145694. /* 108 */ "SLASH",
  145695. /* 109 */ "REM",
  145696. /* 110 */ "CONCAT",
  145697. /* 111 */ "COLLATE",
  145698. /* 112 */ "BITNOT",
  145699. /* 113 */ "ON",
  145700. /* 114 */ "INDEXED",
  145701. /* 115 */ "STRING",
  145702. /* 116 */ "JOIN_KW",
  145703. /* 117 */ "CONSTRAINT",
  145704. /* 118 */ "DEFAULT",
  145705. /* 119 */ "NULL",
  145706. /* 120 */ "PRIMARY",
  145707. /* 121 */ "UNIQUE",
  145708. /* 122 */ "CHECK",
  145709. /* 123 */ "REFERENCES",
  145710. /* 124 */ "AUTOINCR",
  145711. /* 125 */ "INSERT",
  145712. /* 126 */ "DELETE",
  145713. /* 127 */ "UPDATE",
  145714. /* 128 */ "SET",
  145715. /* 129 */ "DEFERRABLE",
  145716. /* 130 */ "FOREIGN",
  145717. /* 131 */ "DROP",
  145718. /* 132 */ "UNION",
  145719. /* 133 */ "ALL",
  145720. /* 134 */ "EXCEPT",
  145721. /* 135 */ "INTERSECT",
  145722. /* 136 */ "SELECT",
  145723. /* 137 */ "VALUES",
  145724. /* 138 */ "DISTINCT",
  145725. /* 139 */ "DOT",
  145726. /* 140 */ "FROM",
  145727. /* 141 */ "JOIN",
  145728. /* 142 */ "USING",
  145729. /* 143 */ "ORDER",
  145730. /* 144 */ "GROUP",
  145731. /* 145 */ "HAVING",
  145732. /* 146 */ "LIMIT",
  145733. /* 147 */ "WHERE",
  145734. /* 148 */ "INTO",
  145735. /* 149 */ "NOTHING",
  145736. /* 150 */ "FLOAT",
  145737. /* 151 */ "BLOB",
  145738. /* 152 */ "INTEGER",
  145739. /* 153 */ "VARIABLE",
  145740. /* 154 */ "CASE",
  145741. /* 155 */ "WHEN",
  145742. /* 156 */ "THEN",
  145743. /* 157 */ "ELSE",
  145744. /* 158 */ "INDEX",
  145745. /* 159 */ "ALTER",
  145746. /* 160 */ "ADD",
  145747. /* 161 */ "WINDOW",
  145748. /* 162 */ "OVER",
  145749. /* 163 */ "FILTER",
  145750. /* 164 */ "COLUMN",
  145751. /* 165 */ "AGG_FUNCTION",
  145752. /* 166 */ "AGG_COLUMN",
  145753. /* 167 */ "TRUEFALSE",
  145754. /* 168 */ "ISNOT",
  145755. /* 169 */ "FUNCTION",
  145756. /* 170 */ "UMINUS",
  145757. /* 171 */ "UPLUS",
  145758. /* 172 */ "TRUTH",
  145759. /* 173 */ "REGISTER",
  145760. /* 174 */ "VECTOR",
  145761. /* 175 */ "SELECT_COLUMN",
  145762. /* 176 */ "IF_NULL_ROW",
  145763. /* 177 */ "ASTERISK",
  145764. /* 178 */ "SPAN",
  145765. /* 179 */ "SPACE",
  145766. /* 180 */ "ILLEGAL",
  145767. /* 181 */ "input",
  145768. /* 182 */ "cmdlist",
  145769. /* 183 */ "ecmd",
  145770. /* 184 */ "cmdx",
  145771. /* 185 */ "explain",
  145772. /* 186 */ "cmd",
  145773. /* 187 */ "transtype",
  145774. /* 188 */ "trans_opt",
  145775. /* 189 */ "nm",
  145776. /* 190 */ "savepoint_opt",
  145777. /* 191 */ "create_table",
  145778. /* 192 */ "create_table_args",
  145779. /* 193 */ "createkw",
  145780. /* 194 */ "temp",
  145781. /* 195 */ "ifnotexists",
  145782. /* 196 */ "dbnm",
  145783. /* 197 */ "columnlist",
  145784. /* 198 */ "conslist_opt",
  145785. /* 199 */ "table_options",
  145786. /* 200 */ "select",
  145787. /* 201 */ "columnname",
  145788. /* 202 */ "carglist",
  145789. /* 203 */ "typetoken",
  145790. /* 204 */ "typename",
  145791. /* 205 */ "signed",
  145792. /* 206 */ "plus_num",
  145793. /* 207 */ "minus_num",
  145794. /* 208 */ "scanpt",
  145795. /* 209 */ "scantok",
  145796. /* 210 */ "ccons",
  145797. /* 211 */ "term",
  145798. /* 212 */ "expr",
  145799. /* 213 */ "onconf",
  145800. /* 214 */ "sortorder",
  145801. /* 215 */ "autoinc",
  145802. /* 216 */ "eidlist_opt",
  145803. /* 217 */ "refargs",
  145804. /* 218 */ "defer_subclause",
  145805. /* 219 */ "generated",
  145806. /* 220 */ "refarg",
  145807. /* 221 */ "refact",
  145808. /* 222 */ "init_deferred_pred_opt",
  145809. /* 223 */ "conslist",
  145810. /* 224 */ "tconscomma",
  145811. /* 225 */ "tcons",
  145812. /* 226 */ "sortlist",
  145813. /* 227 */ "eidlist",
  145814. /* 228 */ "defer_subclause_opt",
  145815. /* 229 */ "orconf",
  145816. /* 230 */ "resolvetype",
  145817. /* 231 */ "raisetype",
  145818. /* 232 */ "ifexists",
  145819. /* 233 */ "fullname",
  145820. /* 234 */ "selectnowith",
  145821. /* 235 */ "oneselect",
  145822. /* 236 */ "wqlist",
  145823. /* 237 */ "multiselect_op",
  145824. /* 238 */ "distinct",
  145825. /* 239 */ "selcollist",
  145826. /* 240 */ "from",
  145827. /* 241 */ "where_opt",
  145828. /* 242 */ "groupby_opt",
  145829. /* 243 */ "having_opt",
  145830. /* 244 */ "orderby_opt",
  145831. /* 245 */ "limit_opt",
  145832. /* 246 */ "window_clause",
  145833. /* 247 */ "values",
  145834. /* 248 */ "nexprlist",
  145835. /* 249 */ "sclp",
  145836. /* 250 */ "as",
  145837. /* 251 */ "seltablist",
  145838. /* 252 */ "stl_prefix",
  145839. /* 253 */ "joinop",
  145840. /* 254 */ "indexed_opt",
  145841. /* 255 */ "on_opt",
  145842. /* 256 */ "using_opt",
  145843. /* 257 */ "exprlist",
  145844. /* 258 */ "xfullname",
  145845. /* 259 */ "idlist",
  145846. /* 260 */ "nulls",
  145847. /* 261 */ "with",
  145848. /* 262 */ "setlist",
  145849. /* 263 */ "insert_cmd",
  145850. /* 264 */ "idlist_opt",
  145851. /* 265 */ "upsert",
  145852. /* 266 */ "filter_over",
  145853. /* 267 */ "likeop",
  145854. /* 268 */ "between_op",
  145855. /* 269 */ "in_op",
  145856. /* 270 */ "paren_exprlist",
  145857. /* 271 */ "case_operand",
  145858. /* 272 */ "case_exprlist",
  145859. /* 273 */ "case_else",
  145860. /* 274 */ "uniqueflag",
  145861. /* 275 */ "collate",
  145862. /* 276 */ "vinto",
  145863. /* 277 */ "nmnum",
  145864. /* 278 */ "trigger_decl",
  145865. /* 279 */ "trigger_cmd_list",
  145866. /* 280 */ "trigger_time",
  145867. /* 281 */ "trigger_event",
  145868. /* 282 */ "foreach_clause",
  145869. /* 283 */ "when_clause",
  145870. /* 284 */ "trigger_cmd",
  145871. /* 285 */ "trnm",
  145872. /* 286 */ "tridxby",
  145873. /* 287 */ "database_kw_opt",
  145874. /* 288 */ "key_opt",
  145875. /* 289 */ "add_column_fullname",
  145876. /* 290 */ "kwcolumn_opt",
  145877. /* 291 */ "create_vtab",
  145878. /* 292 */ "vtabarglist",
  145879. /* 293 */ "vtabarg",
  145880. /* 294 */ "vtabargtoken",
  145881. /* 295 */ "lp",
  145882. /* 296 */ "anylist",
  145883. /* 297 */ "windowdefn_list",
  145884. /* 298 */ "windowdefn",
  145885. /* 299 */ "window",
  145886. /* 300 */ "frame_opt",
  145887. /* 301 */ "part_opt",
  145888. /* 302 */ "filter_clause",
  145889. /* 303 */ "over_clause",
  145890. /* 304 */ "range_or_rows",
  145891. /* 305 */ "frame_bound",
  145892. /* 306 */ "frame_bound_s",
  145893. /* 307 */ "frame_bound_e",
  145894. /* 308 */ "frame_exclude_opt",
  145895. /* 309 */ "frame_exclude",
  145896. };
  145897. #endif /* defined(YYCOVERAGE) || !defined(NDEBUG) */
  145898. #ifndef NDEBUG
  145899. /* For tracing reduce actions, the names of all rules are required.
  145900. */
  145901. static const char *const yyRuleName[] = {
  145902. /* 0 */ "explain ::= EXPLAIN",
  145903. /* 1 */ "explain ::= EXPLAIN QUERY PLAN",
  145904. /* 2 */ "cmdx ::= cmd",
  145905. /* 3 */ "cmd ::= BEGIN transtype trans_opt",
  145906. /* 4 */ "transtype ::=",
  145907. /* 5 */ "transtype ::= DEFERRED",
  145908. /* 6 */ "transtype ::= IMMEDIATE",
  145909. /* 7 */ "transtype ::= EXCLUSIVE",
  145910. /* 8 */ "cmd ::= COMMIT|END trans_opt",
  145911. /* 9 */ "cmd ::= ROLLBACK trans_opt",
  145912. /* 10 */ "cmd ::= SAVEPOINT nm",
  145913. /* 11 */ "cmd ::= RELEASE savepoint_opt nm",
  145914. /* 12 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm",
  145915. /* 13 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm",
  145916. /* 14 */ "createkw ::= CREATE",
  145917. /* 15 */ "ifnotexists ::=",
  145918. /* 16 */ "ifnotexists ::= IF NOT EXISTS",
  145919. /* 17 */ "temp ::= TEMP",
  145920. /* 18 */ "temp ::=",
  145921. /* 19 */ "create_table_args ::= LP columnlist conslist_opt RP table_options",
  145922. /* 20 */ "create_table_args ::= AS select",
  145923. /* 21 */ "table_options ::=",
  145924. /* 22 */ "table_options ::= WITHOUT nm",
  145925. /* 23 */ "columnname ::= nm typetoken",
  145926. /* 24 */ "typetoken ::=",
  145927. /* 25 */ "typetoken ::= typename LP signed RP",
  145928. /* 26 */ "typetoken ::= typename LP signed COMMA signed RP",
  145929. /* 27 */ "typename ::= typename ID|STRING",
  145930. /* 28 */ "scanpt ::=",
  145931. /* 29 */ "scantok ::=",
  145932. /* 30 */ "ccons ::= CONSTRAINT nm",
  145933. /* 31 */ "ccons ::= DEFAULT scantok term",
  145934. /* 32 */ "ccons ::= DEFAULT LP expr RP",
  145935. /* 33 */ "ccons ::= DEFAULT PLUS scantok term",
  145936. /* 34 */ "ccons ::= DEFAULT MINUS scantok term",
  145937. /* 35 */ "ccons ::= DEFAULT scantok ID|INDEXED",
  145938. /* 36 */ "ccons ::= NOT NULL onconf",
  145939. /* 37 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
  145940. /* 38 */ "ccons ::= UNIQUE onconf",
  145941. /* 39 */ "ccons ::= CHECK LP expr RP",
  145942. /* 40 */ "ccons ::= REFERENCES nm eidlist_opt refargs",
  145943. /* 41 */ "ccons ::= defer_subclause",
  145944. /* 42 */ "ccons ::= COLLATE ID|STRING",
  145945. /* 43 */ "generated ::= LP expr RP",
  145946. /* 44 */ "generated ::= LP expr RP ID",
  145947. /* 45 */ "autoinc ::=",
  145948. /* 46 */ "autoinc ::= AUTOINCR",
  145949. /* 47 */ "refargs ::=",
  145950. /* 48 */ "refargs ::= refargs refarg",
  145951. /* 49 */ "refarg ::= MATCH nm",
  145952. /* 50 */ "refarg ::= ON INSERT refact",
  145953. /* 51 */ "refarg ::= ON DELETE refact",
  145954. /* 52 */ "refarg ::= ON UPDATE refact",
  145955. /* 53 */ "refact ::= SET NULL",
  145956. /* 54 */ "refact ::= SET DEFAULT",
  145957. /* 55 */ "refact ::= CASCADE",
  145958. /* 56 */ "refact ::= RESTRICT",
  145959. /* 57 */ "refact ::= NO ACTION",
  145960. /* 58 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
  145961. /* 59 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
  145962. /* 60 */ "init_deferred_pred_opt ::=",
  145963. /* 61 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
  145964. /* 62 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
  145965. /* 63 */ "conslist_opt ::=",
  145966. /* 64 */ "tconscomma ::= COMMA",
  145967. /* 65 */ "tcons ::= CONSTRAINT nm",
  145968. /* 66 */ "tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf",
  145969. /* 67 */ "tcons ::= UNIQUE LP sortlist RP onconf",
  145970. /* 68 */ "tcons ::= CHECK LP expr RP onconf",
  145971. /* 69 */ "tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt",
  145972. /* 70 */ "defer_subclause_opt ::=",
  145973. /* 71 */ "onconf ::=",
  145974. /* 72 */ "onconf ::= ON CONFLICT resolvetype",
  145975. /* 73 */ "orconf ::=",
  145976. /* 74 */ "orconf ::= OR resolvetype",
  145977. /* 75 */ "resolvetype ::= IGNORE",
  145978. /* 76 */ "resolvetype ::= REPLACE",
  145979. /* 77 */ "cmd ::= DROP TABLE ifexists fullname",
  145980. /* 78 */ "ifexists ::= IF EXISTS",
  145981. /* 79 */ "ifexists ::=",
  145982. /* 80 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select",
  145983. /* 81 */ "cmd ::= DROP VIEW ifexists fullname",
  145984. /* 82 */ "cmd ::= select",
  145985. /* 83 */ "select ::= WITH wqlist selectnowith",
  145986. /* 84 */ "select ::= WITH RECURSIVE wqlist selectnowith",
  145987. /* 85 */ "select ::= selectnowith",
  145988. /* 86 */ "selectnowith ::= selectnowith multiselect_op oneselect",
  145989. /* 87 */ "multiselect_op ::= UNION",
  145990. /* 88 */ "multiselect_op ::= UNION ALL",
  145991. /* 89 */ "multiselect_op ::= EXCEPT|INTERSECT",
  145992. /* 90 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
  145993. /* 91 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt window_clause orderby_opt limit_opt",
  145994. /* 92 */ "values ::= VALUES LP nexprlist RP",
  145995. /* 93 */ "values ::= values COMMA LP nexprlist RP",
  145996. /* 94 */ "distinct ::= DISTINCT",
  145997. /* 95 */ "distinct ::= ALL",
  145998. /* 96 */ "distinct ::=",
  145999. /* 97 */ "sclp ::=",
  146000. /* 98 */ "selcollist ::= sclp scanpt expr scanpt as",
  146001. /* 99 */ "selcollist ::= sclp scanpt STAR",
  146002. /* 100 */ "selcollist ::= sclp scanpt nm DOT STAR",
  146003. /* 101 */ "as ::= AS nm",
  146004. /* 102 */ "as ::=",
  146005. /* 103 */ "from ::=",
  146006. /* 104 */ "from ::= FROM seltablist",
  146007. /* 105 */ "stl_prefix ::= seltablist joinop",
  146008. /* 106 */ "stl_prefix ::=",
  146009. /* 107 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt",
  146010. /* 108 */ "seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt",
  146011. /* 109 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt",
  146012. /* 110 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt",
  146013. /* 111 */ "dbnm ::=",
  146014. /* 112 */ "dbnm ::= DOT nm",
  146015. /* 113 */ "fullname ::= nm",
  146016. /* 114 */ "fullname ::= nm DOT nm",
  146017. /* 115 */ "xfullname ::= nm",
  146018. /* 116 */ "xfullname ::= nm DOT nm",
  146019. /* 117 */ "xfullname ::= nm DOT nm AS nm",
  146020. /* 118 */ "xfullname ::= nm AS nm",
  146021. /* 119 */ "joinop ::= COMMA|JOIN",
  146022. /* 120 */ "joinop ::= JOIN_KW JOIN",
  146023. /* 121 */ "joinop ::= JOIN_KW nm JOIN",
  146024. /* 122 */ "joinop ::= JOIN_KW nm nm JOIN",
  146025. /* 123 */ "on_opt ::= ON expr",
  146026. /* 124 */ "on_opt ::=",
  146027. /* 125 */ "indexed_opt ::=",
  146028. /* 126 */ "indexed_opt ::= INDEXED BY nm",
  146029. /* 127 */ "indexed_opt ::= NOT INDEXED",
  146030. /* 128 */ "using_opt ::= USING LP idlist RP",
  146031. /* 129 */ "using_opt ::=",
  146032. /* 130 */ "orderby_opt ::=",
  146033. /* 131 */ "orderby_opt ::= ORDER BY sortlist",
  146034. /* 132 */ "sortlist ::= sortlist COMMA expr sortorder nulls",
  146035. /* 133 */ "sortlist ::= expr sortorder nulls",
  146036. /* 134 */ "sortorder ::= ASC",
  146037. /* 135 */ "sortorder ::= DESC",
  146038. /* 136 */ "sortorder ::=",
  146039. /* 137 */ "nulls ::= NULLS FIRST",
  146040. /* 138 */ "nulls ::= NULLS LAST",
  146041. /* 139 */ "nulls ::=",
  146042. /* 140 */ "groupby_opt ::=",
  146043. /* 141 */ "groupby_opt ::= GROUP BY nexprlist",
  146044. /* 142 */ "having_opt ::=",
  146045. /* 143 */ "having_opt ::= HAVING expr",
  146046. /* 144 */ "limit_opt ::=",
  146047. /* 145 */ "limit_opt ::= LIMIT expr",
  146048. /* 146 */ "limit_opt ::= LIMIT expr OFFSET expr",
  146049. /* 147 */ "limit_opt ::= LIMIT expr COMMA expr",
  146050. /* 148 */ "cmd ::= with DELETE FROM xfullname indexed_opt where_opt",
  146051. /* 149 */ "where_opt ::=",
  146052. /* 150 */ "where_opt ::= WHERE expr",
  146053. /* 151 */ "cmd ::= with UPDATE orconf xfullname indexed_opt SET setlist where_opt",
  146054. /* 152 */ "setlist ::= setlist COMMA nm EQ expr",
  146055. /* 153 */ "setlist ::= setlist COMMA LP idlist RP EQ expr",
  146056. /* 154 */ "setlist ::= nm EQ expr",
  146057. /* 155 */ "setlist ::= LP idlist RP EQ expr",
  146058. /* 156 */ "cmd ::= with insert_cmd INTO xfullname idlist_opt select upsert",
  146059. /* 157 */ "cmd ::= with insert_cmd INTO xfullname idlist_opt DEFAULT VALUES",
  146060. /* 158 */ "upsert ::=",
  146061. /* 159 */ "upsert ::= ON CONFLICT LP sortlist RP where_opt DO UPDATE SET setlist where_opt",
  146062. /* 160 */ "upsert ::= ON CONFLICT LP sortlist RP where_opt DO NOTHING",
  146063. /* 161 */ "upsert ::= ON CONFLICT DO NOTHING",
  146064. /* 162 */ "insert_cmd ::= INSERT orconf",
  146065. /* 163 */ "insert_cmd ::= REPLACE",
  146066. /* 164 */ "idlist_opt ::=",
  146067. /* 165 */ "idlist_opt ::= LP idlist RP",
  146068. /* 166 */ "idlist ::= idlist COMMA nm",
  146069. /* 167 */ "idlist ::= nm",
  146070. /* 168 */ "expr ::= LP expr RP",
  146071. /* 169 */ "expr ::= ID|INDEXED",
  146072. /* 170 */ "expr ::= JOIN_KW",
  146073. /* 171 */ "expr ::= nm DOT nm",
  146074. /* 172 */ "expr ::= nm DOT nm DOT nm",
  146075. /* 173 */ "term ::= NULL|FLOAT|BLOB",
  146076. /* 174 */ "term ::= STRING",
  146077. /* 175 */ "term ::= INTEGER",
  146078. /* 176 */ "expr ::= VARIABLE",
  146079. /* 177 */ "expr ::= expr COLLATE ID|STRING",
  146080. /* 178 */ "expr ::= CAST LP expr AS typetoken RP",
  146081. /* 179 */ "expr ::= ID|INDEXED LP distinct exprlist RP",
  146082. /* 180 */ "expr ::= ID|INDEXED LP STAR RP",
  146083. /* 181 */ "expr ::= ID|INDEXED LP distinct exprlist RP filter_over",
  146084. /* 182 */ "expr ::= ID|INDEXED LP STAR RP filter_over",
  146085. /* 183 */ "term ::= CTIME_KW",
  146086. /* 184 */ "expr ::= LP nexprlist COMMA expr RP",
  146087. /* 185 */ "expr ::= expr AND expr",
  146088. /* 186 */ "expr ::= expr OR expr",
  146089. /* 187 */ "expr ::= expr LT|GT|GE|LE expr",
  146090. /* 188 */ "expr ::= expr EQ|NE expr",
  146091. /* 189 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
  146092. /* 190 */ "expr ::= expr PLUS|MINUS expr",
  146093. /* 191 */ "expr ::= expr STAR|SLASH|REM expr",
  146094. /* 192 */ "expr ::= expr CONCAT expr",
  146095. /* 193 */ "likeop ::= NOT LIKE_KW|MATCH",
  146096. /* 194 */ "expr ::= expr likeop expr",
  146097. /* 195 */ "expr ::= expr likeop expr ESCAPE expr",
  146098. /* 196 */ "expr ::= expr ISNULL|NOTNULL",
  146099. /* 197 */ "expr ::= expr NOT NULL",
  146100. /* 198 */ "expr ::= expr IS expr",
  146101. /* 199 */ "expr ::= expr IS NOT expr",
  146102. /* 200 */ "expr ::= NOT expr",
  146103. /* 201 */ "expr ::= BITNOT expr",
  146104. /* 202 */ "expr ::= PLUS|MINUS expr",
  146105. /* 203 */ "between_op ::= BETWEEN",
  146106. /* 204 */ "between_op ::= NOT BETWEEN",
  146107. /* 205 */ "expr ::= expr between_op expr AND expr",
  146108. /* 206 */ "in_op ::= IN",
  146109. /* 207 */ "in_op ::= NOT IN",
  146110. /* 208 */ "expr ::= expr in_op LP exprlist RP",
  146111. /* 209 */ "expr ::= LP select RP",
  146112. /* 210 */ "expr ::= expr in_op LP select RP",
  146113. /* 211 */ "expr ::= expr in_op nm dbnm paren_exprlist",
  146114. /* 212 */ "expr ::= EXISTS LP select RP",
  146115. /* 213 */ "expr ::= CASE case_operand case_exprlist case_else END",
  146116. /* 214 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
  146117. /* 215 */ "case_exprlist ::= WHEN expr THEN expr",
  146118. /* 216 */ "case_else ::= ELSE expr",
  146119. /* 217 */ "case_else ::=",
  146120. /* 218 */ "case_operand ::= expr",
  146121. /* 219 */ "case_operand ::=",
  146122. /* 220 */ "exprlist ::=",
  146123. /* 221 */ "nexprlist ::= nexprlist COMMA expr",
  146124. /* 222 */ "nexprlist ::= expr",
  146125. /* 223 */ "paren_exprlist ::=",
  146126. /* 224 */ "paren_exprlist ::= LP exprlist RP",
  146127. /* 225 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt",
  146128. /* 226 */ "uniqueflag ::= UNIQUE",
  146129. /* 227 */ "uniqueflag ::=",
  146130. /* 228 */ "eidlist_opt ::=",
  146131. /* 229 */ "eidlist_opt ::= LP eidlist RP",
  146132. /* 230 */ "eidlist ::= eidlist COMMA nm collate sortorder",
  146133. /* 231 */ "eidlist ::= nm collate sortorder",
  146134. /* 232 */ "collate ::=",
  146135. /* 233 */ "collate ::= COLLATE ID|STRING",
  146136. /* 234 */ "cmd ::= DROP INDEX ifexists fullname",
  146137. /* 235 */ "cmd ::= VACUUM vinto",
  146138. /* 236 */ "cmd ::= VACUUM nm vinto",
  146139. /* 237 */ "vinto ::= INTO expr",
  146140. /* 238 */ "vinto ::=",
  146141. /* 239 */ "cmd ::= PRAGMA nm dbnm",
  146142. /* 240 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
  146143. /* 241 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
  146144. /* 242 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
  146145. /* 243 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
  146146. /* 244 */ "plus_num ::= PLUS INTEGER|FLOAT",
  146147. /* 245 */ "minus_num ::= MINUS INTEGER|FLOAT",
  146148. /* 246 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
  146149. /* 247 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
  146150. /* 248 */ "trigger_time ::= BEFORE|AFTER",
  146151. /* 249 */ "trigger_time ::= INSTEAD OF",
  146152. /* 250 */ "trigger_time ::=",
  146153. /* 251 */ "trigger_event ::= DELETE|INSERT",
  146154. /* 252 */ "trigger_event ::= UPDATE",
  146155. /* 253 */ "trigger_event ::= UPDATE OF idlist",
  146156. /* 254 */ "when_clause ::=",
  146157. /* 255 */ "when_clause ::= WHEN expr",
  146158. /* 256 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
  146159. /* 257 */ "trigger_cmd_list ::= trigger_cmd SEMI",
  146160. /* 258 */ "trnm ::= nm DOT nm",
  146161. /* 259 */ "tridxby ::= INDEXED BY nm",
  146162. /* 260 */ "tridxby ::= NOT INDEXED",
  146163. /* 261 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt scanpt",
  146164. /* 262 */ "trigger_cmd ::= scanpt insert_cmd INTO trnm idlist_opt select upsert scanpt",
  146165. /* 263 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt scanpt",
  146166. /* 264 */ "trigger_cmd ::= scanpt select scanpt",
  146167. /* 265 */ "expr ::= RAISE LP IGNORE RP",
  146168. /* 266 */ "expr ::= RAISE LP raisetype COMMA nm RP",
  146169. /* 267 */ "raisetype ::= ROLLBACK",
  146170. /* 268 */ "raisetype ::= ABORT",
  146171. /* 269 */ "raisetype ::= FAIL",
  146172. /* 270 */ "cmd ::= DROP TRIGGER ifexists fullname",
  146173. /* 271 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
  146174. /* 272 */ "cmd ::= DETACH database_kw_opt expr",
  146175. /* 273 */ "key_opt ::=",
  146176. /* 274 */ "key_opt ::= KEY expr",
  146177. /* 275 */ "cmd ::= REINDEX",
  146178. /* 276 */ "cmd ::= REINDEX nm dbnm",
  146179. /* 277 */ "cmd ::= ANALYZE",
  146180. /* 278 */ "cmd ::= ANALYZE nm dbnm",
  146181. /* 279 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
  146182. /* 280 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist",
  146183. /* 281 */ "add_column_fullname ::= fullname",
  146184. /* 282 */ "cmd ::= ALTER TABLE fullname RENAME kwcolumn_opt nm TO nm",
  146185. /* 283 */ "cmd ::= create_vtab",
  146186. /* 284 */ "cmd ::= create_vtab LP vtabarglist RP",
  146187. /* 285 */ "create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm",
  146188. /* 286 */ "vtabarg ::=",
  146189. /* 287 */ "vtabargtoken ::= ANY",
  146190. /* 288 */ "vtabargtoken ::= lp anylist RP",
  146191. /* 289 */ "lp ::= LP",
  146192. /* 290 */ "with ::= WITH wqlist",
  146193. /* 291 */ "with ::= WITH RECURSIVE wqlist",
  146194. /* 292 */ "wqlist ::= nm eidlist_opt AS LP select RP",
  146195. /* 293 */ "wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP",
  146196. /* 294 */ "windowdefn_list ::= windowdefn",
  146197. /* 295 */ "windowdefn_list ::= windowdefn_list COMMA windowdefn",
  146198. /* 296 */ "windowdefn ::= nm AS LP window RP",
  146199. /* 297 */ "window ::= PARTITION BY nexprlist orderby_opt frame_opt",
  146200. /* 298 */ "window ::= nm PARTITION BY nexprlist orderby_opt frame_opt",
  146201. /* 299 */ "window ::= ORDER BY sortlist frame_opt",
  146202. /* 300 */ "window ::= nm ORDER BY sortlist frame_opt",
  146203. /* 301 */ "window ::= frame_opt",
  146204. /* 302 */ "window ::= nm frame_opt",
  146205. /* 303 */ "frame_opt ::=",
  146206. /* 304 */ "frame_opt ::= range_or_rows frame_bound_s frame_exclude_opt",
  146207. /* 305 */ "frame_opt ::= range_or_rows BETWEEN frame_bound_s AND frame_bound_e frame_exclude_opt",
  146208. /* 306 */ "range_or_rows ::= RANGE|ROWS|GROUPS",
  146209. /* 307 */ "frame_bound_s ::= frame_bound",
  146210. /* 308 */ "frame_bound_s ::= UNBOUNDED PRECEDING",
  146211. /* 309 */ "frame_bound_e ::= frame_bound",
  146212. /* 310 */ "frame_bound_e ::= UNBOUNDED FOLLOWING",
  146213. /* 311 */ "frame_bound ::= expr PRECEDING|FOLLOWING",
  146214. /* 312 */ "frame_bound ::= CURRENT ROW",
  146215. /* 313 */ "frame_exclude_opt ::=",
  146216. /* 314 */ "frame_exclude_opt ::= EXCLUDE frame_exclude",
  146217. /* 315 */ "frame_exclude ::= NO OTHERS",
  146218. /* 316 */ "frame_exclude ::= CURRENT ROW",
  146219. /* 317 */ "frame_exclude ::= GROUP|TIES",
  146220. /* 318 */ "window_clause ::= WINDOW windowdefn_list",
  146221. /* 319 */ "filter_over ::= filter_clause over_clause",
  146222. /* 320 */ "filter_over ::= over_clause",
  146223. /* 321 */ "filter_over ::= filter_clause",
  146224. /* 322 */ "over_clause ::= OVER LP window RP",
  146225. /* 323 */ "over_clause ::= OVER nm",
  146226. /* 324 */ "filter_clause ::= FILTER LP WHERE expr RP",
  146227. /* 325 */ "input ::= cmdlist",
  146228. /* 326 */ "cmdlist ::= cmdlist ecmd",
  146229. /* 327 */ "cmdlist ::= ecmd",
  146230. /* 328 */ "ecmd ::= SEMI",
  146231. /* 329 */ "ecmd ::= cmdx SEMI",
  146232. /* 330 */ "ecmd ::= explain cmdx SEMI",
  146233. /* 331 */ "trans_opt ::=",
  146234. /* 332 */ "trans_opt ::= TRANSACTION",
  146235. /* 333 */ "trans_opt ::= TRANSACTION nm",
  146236. /* 334 */ "savepoint_opt ::= SAVEPOINT",
  146237. /* 335 */ "savepoint_opt ::=",
  146238. /* 336 */ "cmd ::= create_table create_table_args",
  146239. /* 337 */ "columnlist ::= columnlist COMMA columnname carglist",
  146240. /* 338 */ "columnlist ::= columnname carglist",
  146241. /* 339 */ "nm ::= ID|INDEXED",
  146242. /* 340 */ "nm ::= STRING",
  146243. /* 341 */ "nm ::= JOIN_KW",
  146244. /* 342 */ "typetoken ::= typename",
  146245. /* 343 */ "typename ::= ID|STRING",
  146246. /* 344 */ "signed ::= plus_num",
  146247. /* 345 */ "signed ::= minus_num",
  146248. /* 346 */ "carglist ::= carglist ccons",
  146249. /* 347 */ "carglist ::=",
  146250. /* 348 */ "ccons ::= NULL onconf",
  146251. /* 349 */ "ccons ::= GENERATED ALWAYS AS generated",
  146252. /* 350 */ "ccons ::= AS generated",
  146253. /* 351 */ "conslist_opt ::= COMMA conslist",
  146254. /* 352 */ "conslist ::= conslist tconscomma tcons",
  146255. /* 353 */ "conslist ::= tcons",
  146256. /* 354 */ "tconscomma ::=",
  146257. /* 355 */ "defer_subclause_opt ::= defer_subclause",
  146258. /* 356 */ "resolvetype ::= raisetype",
  146259. /* 357 */ "selectnowith ::= oneselect",
  146260. /* 358 */ "oneselect ::= values",
  146261. /* 359 */ "sclp ::= selcollist COMMA",
  146262. /* 360 */ "as ::= ID|STRING",
  146263. /* 361 */ "expr ::= term",
  146264. /* 362 */ "likeop ::= LIKE_KW|MATCH",
  146265. /* 363 */ "exprlist ::= nexprlist",
  146266. /* 364 */ "nmnum ::= plus_num",
  146267. /* 365 */ "nmnum ::= nm",
  146268. /* 366 */ "nmnum ::= ON",
  146269. /* 367 */ "nmnum ::= DELETE",
  146270. /* 368 */ "nmnum ::= DEFAULT",
  146271. /* 369 */ "plus_num ::= INTEGER|FLOAT",
  146272. /* 370 */ "foreach_clause ::=",
  146273. /* 371 */ "foreach_clause ::= FOR EACH ROW",
  146274. /* 372 */ "trnm ::= nm",
  146275. /* 373 */ "tridxby ::=",
  146276. /* 374 */ "database_kw_opt ::= DATABASE",
  146277. /* 375 */ "database_kw_opt ::=",
  146278. /* 376 */ "kwcolumn_opt ::=",
  146279. /* 377 */ "kwcolumn_opt ::= COLUMNKW",
  146280. /* 378 */ "vtabarglist ::= vtabarg",
  146281. /* 379 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
  146282. /* 380 */ "vtabarg ::= vtabarg vtabargtoken",
  146283. /* 381 */ "anylist ::=",
  146284. /* 382 */ "anylist ::= anylist LP anylist RP",
  146285. /* 383 */ "anylist ::= anylist ANY",
  146286. /* 384 */ "with ::=",
  146287. };
  146288. #endif /* NDEBUG */
  146289. #if YYSTACKDEPTH<=0
  146290. /*
  146291. ** Try to increase the size of the parser stack. Return the number
  146292. ** of errors. Return 0 on success.
  146293. */
  146294. static int yyGrowStack(yyParser *p){
  146295. int newSize;
  146296. int idx;
  146297. yyStackEntry *pNew;
  146298. newSize = p->yystksz*2 + 100;
  146299. idx = p->yytos ? (int)(p->yytos - p->yystack) : 0;
  146300. if( p->yystack==&p->yystk0 ){
  146301. pNew = malloc(newSize*sizeof(pNew[0]));
  146302. if( pNew ) pNew[0] = p->yystk0;
  146303. }else{
  146304. pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
  146305. }
  146306. if( pNew ){
  146307. p->yystack = pNew;
  146308. p->yytos = &p->yystack[idx];
  146309. #ifndef NDEBUG
  146310. if( yyTraceFILE ){
  146311. fprintf(yyTraceFILE,"%sStack grows from %d to %d entries.\n",
  146312. yyTracePrompt, p->yystksz, newSize);
  146313. }
  146314. #endif
  146315. p->yystksz = newSize;
  146316. }
  146317. return pNew==0;
  146318. }
  146319. #endif
  146320. /* Datatype of the argument to the memory allocated passed as the
  146321. ** second argument to sqlite3ParserAlloc() below. This can be changed by
  146322. ** putting an appropriate #define in the %include section of the input
  146323. ** grammar.
  146324. */
  146325. #ifndef YYMALLOCARGTYPE
  146326. # define YYMALLOCARGTYPE size_t
  146327. #endif
  146328. /* Initialize a new parser that has already been allocated.
  146329. */
  146330. SQLITE_PRIVATE void sqlite3ParserInit(void *yypRawParser sqlite3ParserCTX_PDECL){
  146331. yyParser *yypParser = (yyParser*)yypRawParser;
  146332. sqlite3ParserCTX_STORE
  146333. #ifdef YYTRACKMAXSTACKDEPTH
  146334. yypParser->yyhwm = 0;
  146335. #endif
  146336. #if YYSTACKDEPTH<=0
  146337. yypParser->yytos = NULL;
  146338. yypParser->yystack = NULL;
  146339. yypParser->yystksz = 0;
  146340. if( yyGrowStack(yypParser) ){
  146341. yypParser->yystack = &yypParser->yystk0;
  146342. yypParser->yystksz = 1;
  146343. }
  146344. #endif
  146345. #ifndef YYNOERRORRECOVERY
  146346. yypParser->yyerrcnt = -1;
  146347. #endif
  146348. yypParser->yytos = yypParser->yystack;
  146349. yypParser->yystack[0].stateno = 0;
  146350. yypParser->yystack[0].major = 0;
  146351. #if YYSTACKDEPTH>0
  146352. yypParser->yystackEnd = &yypParser->yystack[YYSTACKDEPTH-1];
  146353. #endif
  146354. }
  146355. #ifndef sqlite3Parser_ENGINEALWAYSONSTACK
  146356. /*
  146357. ** This function allocates a new parser.
  146358. ** The only argument is a pointer to a function which works like
  146359. ** malloc.
  146360. **
  146361. ** Inputs:
  146362. ** A pointer to the function used to allocate memory.
  146363. **
  146364. ** Outputs:
  146365. ** A pointer to a parser. This pointer is used in subsequent calls
  146366. ** to sqlite3Parser and sqlite3ParserFree.
  146367. */
  146368. SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(YYMALLOCARGTYPE) sqlite3ParserCTX_PDECL){
  146369. yyParser *yypParser;
  146370. yypParser = (yyParser*)(*mallocProc)( (YYMALLOCARGTYPE)sizeof(yyParser) );
  146371. if( yypParser ){
  146372. sqlite3ParserCTX_STORE
  146373. sqlite3ParserInit(yypParser sqlite3ParserCTX_PARAM);
  146374. }
  146375. return (void*)yypParser;
  146376. }
  146377. #endif /* sqlite3Parser_ENGINEALWAYSONSTACK */
  146378. /* The following function deletes the "minor type" or semantic value
  146379. ** associated with a symbol. The symbol can be either a terminal
  146380. ** or nonterminal. "yymajor" is the symbol code, and "yypminor" is
  146381. ** a pointer to the value to be deleted. The code used to do the
  146382. ** deletions is derived from the %destructor and/or %token_destructor
  146383. ** directives of the input grammar.
  146384. */
  146385. static void yy_destructor(
  146386. yyParser *yypParser, /* The parser */
  146387. YYCODETYPE yymajor, /* Type code for object to destroy */
  146388. YYMINORTYPE *yypminor /* The object to be destroyed */
  146389. ){
  146390. sqlite3ParserARG_FETCH
  146391. sqlite3ParserCTX_FETCH
  146392. switch( yymajor ){
  146393. /* Here is inserted the actions which take place when a
  146394. ** terminal or non-terminal is destroyed. This can happen
  146395. ** when the symbol is popped from the stack during a
  146396. ** reduce or during error processing or when a parser is
  146397. ** being destroyed before it is finished parsing.
  146398. **
  146399. ** Note: during a reduce, the only symbols destroyed are those
  146400. ** which appear on the RHS of the rule, but which are *not* used
  146401. ** inside the C code.
  146402. */
  146403. /********* Begin destructor definitions ***************************************/
  146404. case 200: /* select */
  146405. case 234: /* selectnowith */
  146406. case 235: /* oneselect */
  146407. case 247: /* values */
  146408. {
  146409. sqlite3SelectDelete(pParse->db, (yypminor->yy539));
  146410. }
  146411. break;
  146412. case 211: /* term */
  146413. case 212: /* expr */
  146414. case 241: /* where_opt */
  146415. case 243: /* having_opt */
  146416. case 255: /* on_opt */
  146417. case 271: /* case_operand */
  146418. case 273: /* case_else */
  146419. case 276: /* vinto */
  146420. case 283: /* when_clause */
  146421. case 288: /* key_opt */
  146422. case 302: /* filter_clause */
  146423. {
  146424. sqlite3ExprDelete(pParse->db, (yypminor->yy202));
  146425. }
  146426. break;
  146427. case 216: /* eidlist_opt */
  146428. case 226: /* sortlist */
  146429. case 227: /* eidlist */
  146430. case 239: /* selcollist */
  146431. case 242: /* groupby_opt */
  146432. case 244: /* orderby_opt */
  146433. case 248: /* nexprlist */
  146434. case 249: /* sclp */
  146435. case 257: /* exprlist */
  146436. case 262: /* setlist */
  146437. case 270: /* paren_exprlist */
  146438. case 272: /* case_exprlist */
  146439. case 301: /* part_opt */
  146440. {
  146441. sqlite3ExprListDelete(pParse->db, (yypminor->yy242));
  146442. }
  146443. break;
  146444. case 233: /* fullname */
  146445. case 240: /* from */
  146446. case 251: /* seltablist */
  146447. case 252: /* stl_prefix */
  146448. case 258: /* xfullname */
  146449. {
  146450. sqlite3SrcListDelete(pParse->db, (yypminor->yy47));
  146451. }
  146452. break;
  146453. case 236: /* wqlist */
  146454. {
  146455. sqlite3WithDelete(pParse->db, (yypminor->yy131));
  146456. }
  146457. break;
  146458. case 246: /* window_clause */
  146459. case 297: /* windowdefn_list */
  146460. {
  146461. sqlite3WindowListDelete(pParse->db, (yypminor->yy303));
  146462. }
  146463. break;
  146464. case 256: /* using_opt */
  146465. case 259: /* idlist */
  146466. case 264: /* idlist_opt */
  146467. {
  146468. sqlite3IdListDelete(pParse->db, (yypminor->yy600));
  146469. }
  146470. break;
  146471. case 266: /* filter_over */
  146472. case 298: /* windowdefn */
  146473. case 299: /* window */
  146474. case 300: /* frame_opt */
  146475. case 303: /* over_clause */
  146476. {
  146477. sqlite3WindowDelete(pParse->db, (yypminor->yy303));
  146478. }
  146479. break;
  146480. case 279: /* trigger_cmd_list */
  146481. case 284: /* trigger_cmd */
  146482. {
  146483. sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy447));
  146484. }
  146485. break;
  146486. case 281: /* trigger_event */
  146487. {
  146488. sqlite3IdListDelete(pParse->db, (yypminor->yy230).b);
  146489. }
  146490. break;
  146491. case 305: /* frame_bound */
  146492. case 306: /* frame_bound_s */
  146493. case 307: /* frame_bound_e */
  146494. {
  146495. sqlite3ExprDelete(pParse->db, (yypminor->yy77).pExpr);
  146496. }
  146497. break;
  146498. /********* End destructor definitions *****************************************/
  146499. default: break; /* If no destructor action specified: do nothing */
  146500. }
  146501. }
  146502. /*
  146503. ** Pop the parser's stack once.
  146504. **
  146505. ** If there is a destructor routine associated with the token which
  146506. ** is popped from the stack, then call it.
  146507. */
  146508. static void yy_pop_parser_stack(yyParser *pParser){
  146509. yyStackEntry *yytos;
  146510. assert( pParser->yytos!=0 );
  146511. assert( pParser->yytos > pParser->yystack );
  146512. yytos = pParser->yytos--;
  146513. #ifndef NDEBUG
  146514. if( yyTraceFILE ){
  146515. fprintf(yyTraceFILE,"%sPopping %s\n",
  146516. yyTracePrompt,
  146517. yyTokenName[yytos->major]);
  146518. }
  146519. #endif
  146520. yy_destructor(pParser, yytos->major, &yytos->minor);
  146521. }
  146522. /*
  146523. ** Clear all secondary memory allocations from the parser
  146524. */
  146525. SQLITE_PRIVATE void sqlite3ParserFinalize(void *p){
  146526. yyParser *pParser = (yyParser*)p;
  146527. while( pParser->yytos>pParser->yystack ) yy_pop_parser_stack(pParser);
  146528. #if YYSTACKDEPTH<=0
  146529. if( pParser->yystack!=&pParser->yystk0 ) free(pParser->yystack);
  146530. #endif
  146531. }
  146532. #ifndef sqlite3Parser_ENGINEALWAYSONSTACK
  146533. /*
  146534. ** Deallocate and destroy a parser. Destructors are called for
  146535. ** all stack elements before shutting the parser down.
  146536. **
  146537. ** If the YYPARSEFREENEVERNULL macro exists (for example because it
  146538. ** is defined in a %include section of the input grammar) then it is
  146539. ** assumed that the input pointer is never NULL.
  146540. */
  146541. SQLITE_PRIVATE void sqlite3ParserFree(
  146542. void *p, /* The parser to be deleted */
  146543. void (*freeProc)(void*) /* Function used to reclaim memory */
  146544. ){
  146545. #ifndef YYPARSEFREENEVERNULL
  146546. if( p==0 ) return;
  146547. #endif
  146548. sqlite3ParserFinalize(p);
  146549. (*freeProc)(p);
  146550. }
  146551. #endif /* sqlite3Parser_ENGINEALWAYSONSTACK */
  146552. /*
  146553. ** Return the peak depth of the stack for a parser.
  146554. */
  146555. #ifdef YYTRACKMAXSTACKDEPTH
  146556. SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){
  146557. yyParser *pParser = (yyParser*)p;
  146558. return pParser->yyhwm;
  146559. }
  146560. #endif
  146561. /* This array of booleans keeps track of the parser statement
  146562. ** coverage. The element yycoverage[X][Y] is set when the parser
  146563. ** is in state X and has a lookahead token Y. In a well-tested
  146564. ** systems, every element of this matrix should end up being set.
  146565. */
  146566. #if defined(YYCOVERAGE)
  146567. static unsigned char yycoverage[YYNSTATE][YYNTOKEN];
  146568. #endif
  146569. /*
  146570. ** Write into out a description of every state/lookahead combination that
  146571. **
  146572. ** (1) has not been used by the parser, and
  146573. ** (2) is not a syntax error.
  146574. **
  146575. ** Return the number of missed state/lookahead combinations.
  146576. */
  146577. #if defined(YYCOVERAGE)
  146578. SQLITE_PRIVATE int sqlite3ParserCoverage(FILE *out){
  146579. int stateno, iLookAhead, i;
  146580. int nMissed = 0;
  146581. for(stateno=0; stateno<YYNSTATE; stateno++){
  146582. i = yy_shift_ofst[stateno];
  146583. for(iLookAhead=0; iLookAhead<YYNTOKEN; iLookAhead++){
  146584. if( yy_lookahead[i+iLookAhead]!=iLookAhead ) continue;
  146585. if( yycoverage[stateno][iLookAhead]==0 ) nMissed++;
  146586. if( out ){
  146587. fprintf(out,"State %d lookahead %s %s\n", stateno,
  146588. yyTokenName[iLookAhead],
  146589. yycoverage[stateno][iLookAhead] ? "ok" : "missed");
  146590. }
  146591. }
  146592. }
  146593. return nMissed;
  146594. }
  146595. #endif
  146596. /*
  146597. ** Find the appropriate action for a parser given the terminal
  146598. ** look-ahead token iLookAhead.
  146599. */
  146600. static YYACTIONTYPE yy_find_shift_action(
  146601. YYCODETYPE iLookAhead, /* The look-ahead token */
  146602. YYACTIONTYPE stateno /* Current state number */
  146603. ){
  146604. int i;
  146605. if( stateno>YY_MAX_SHIFT ) return stateno;
  146606. assert( stateno <= YY_SHIFT_COUNT );
  146607. #if defined(YYCOVERAGE)
  146608. yycoverage[stateno][iLookAhead] = 1;
  146609. #endif
  146610. do{
  146611. i = yy_shift_ofst[stateno];
  146612. assert( i>=0 );
  146613. assert( i<=YY_ACTTAB_COUNT );
  146614. assert( i+YYNTOKEN<=(int)YY_NLOOKAHEAD );
  146615. assert( iLookAhead!=YYNOCODE );
  146616. assert( iLookAhead < YYNTOKEN );
  146617. i += iLookAhead;
  146618. assert( i<(int)YY_NLOOKAHEAD );
  146619. if( yy_lookahead[i]!=iLookAhead ){
  146620. #ifdef YYFALLBACK
  146621. YYCODETYPE iFallback; /* Fallback token */
  146622. assert( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0]) );
  146623. iFallback = yyFallback[iLookAhead];
  146624. if( iFallback!=0 ){
  146625. #ifndef NDEBUG
  146626. if( yyTraceFILE ){
  146627. fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
  146628. yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
  146629. }
  146630. #endif
  146631. assert( yyFallback[iFallback]==0 ); /* Fallback loop must terminate */
  146632. iLookAhead = iFallback;
  146633. continue;
  146634. }
  146635. #endif
  146636. #ifdef YYWILDCARD
  146637. {
  146638. int j = i - iLookAhead + YYWILDCARD;
  146639. assert( j<(int)(sizeof(yy_lookahead)/sizeof(yy_lookahead[0])) );
  146640. if( yy_lookahead[j]==YYWILDCARD && iLookAhead>0 ){
  146641. #ifndef NDEBUG
  146642. if( yyTraceFILE ){
  146643. fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
  146644. yyTracePrompt, yyTokenName[iLookAhead],
  146645. yyTokenName[YYWILDCARD]);
  146646. }
  146647. #endif /* NDEBUG */
  146648. return yy_action[j];
  146649. }
  146650. }
  146651. #endif /* YYWILDCARD */
  146652. return yy_default[stateno];
  146653. }else{
  146654. assert( i>=0 && i<sizeof(yy_action)/sizeof(yy_action[0]) );
  146655. return yy_action[i];
  146656. }
  146657. }while(1);
  146658. }
  146659. /*
  146660. ** Find the appropriate action for a parser given the non-terminal
  146661. ** look-ahead token iLookAhead.
  146662. */
  146663. static YYACTIONTYPE yy_find_reduce_action(
  146664. YYACTIONTYPE stateno, /* Current state number */
  146665. YYCODETYPE iLookAhead /* The look-ahead token */
  146666. ){
  146667. int i;
  146668. #ifdef YYERRORSYMBOL
  146669. if( stateno>YY_REDUCE_COUNT ){
  146670. return yy_default[stateno];
  146671. }
  146672. #else
  146673. assert( stateno<=YY_REDUCE_COUNT );
  146674. #endif
  146675. i = yy_reduce_ofst[stateno];
  146676. assert( iLookAhead!=YYNOCODE );
  146677. i += iLookAhead;
  146678. #ifdef YYERRORSYMBOL
  146679. if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
  146680. return yy_default[stateno];
  146681. }
  146682. #else
  146683. assert( i>=0 && i<YY_ACTTAB_COUNT );
  146684. assert( yy_lookahead[i]==iLookAhead );
  146685. #endif
  146686. return yy_action[i];
  146687. }
  146688. /*
  146689. ** The following routine is called if the stack overflows.
  146690. */
  146691. static void yyStackOverflow(yyParser *yypParser){
  146692. sqlite3ParserARG_FETCH
  146693. sqlite3ParserCTX_FETCH
  146694. #ifndef NDEBUG
  146695. if( yyTraceFILE ){
  146696. fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
  146697. }
  146698. #endif
  146699. while( yypParser->yytos>yypParser->yystack ) yy_pop_parser_stack(yypParser);
  146700. /* Here code is inserted which will execute if the parser
  146701. ** stack every overflows */
  146702. /******** Begin %stack_overflow code ******************************************/
  146703. sqlite3ErrorMsg(pParse, "parser stack overflow");
  146704. /******** End %stack_overflow code ********************************************/
  146705. sqlite3ParserARG_STORE /* Suppress warning about unused %extra_argument var */
  146706. sqlite3ParserCTX_STORE
  146707. }
  146708. /*
  146709. ** Print tracing information for a SHIFT action
  146710. */
  146711. #ifndef NDEBUG
  146712. static void yyTraceShift(yyParser *yypParser, int yyNewState, const char *zTag){
  146713. if( yyTraceFILE ){
  146714. if( yyNewState<YYNSTATE ){
  146715. fprintf(yyTraceFILE,"%s%s '%s', go to state %d\n",
  146716. yyTracePrompt, zTag, yyTokenName[yypParser->yytos->major],
  146717. yyNewState);
  146718. }else{
  146719. fprintf(yyTraceFILE,"%s%s '%s', pending reduce %d\n",
  146720. yyTracePrompt, zTag, yyTokenName[yypParser->yytos->major],
  146721. yyNewState - YY_MIN_REDUCE);
  146722. }
  146723. }
  146724. }
  146725. #else
  146726. # define yyTraceShift(X,Y,Z)
  146727. #endif
  146728. /*
  146729. ** Perform a shift action.
  146730. */
  146731. static void yy_shift(
  146732. yyParser *yypParser, /* The parser to be shifted */
  146733. YYACTIONTYPE yyNewState, /* The new state to shift in */
  146734. YYCODETYPE yyMajor, /* The major token to shift in */
  146735. sqlite3ParserTOKENTYPE yyMinor /* The minor token to shift in */
  146736. ){
  146737. yyStackEntry *yytos;
  146738. yypParser->yytos++;
  146739. #ifdef YYTRACKMAXSTACKDEPTH
  146740. if( (int)(yypParser->yytos - yypParser->yystack)>yypParser->yyhwm ){
  146741. yypParser->yyhwm++;
  146742. assert( yypParser->yyhwm == (int)(yypParser->yytos - yypParser->yystack) );
  146743. }
  146744. #endif
  146745. #if YYSTACKDEPTH>0
  146746. if( yypParser->yytos>yypParser->yystackEnd ){
  146747. yypParser->yytos--;
  146748. yyStackOverflow(yypParser);
  146749. return;
  146750. }
  146751. #else
  146752. if( yypParser->yytos>=&yypParser->yystack[yypParser->yystksz] ){
  146753. if( yyGrowStack(yypParser) ){
  146754. yypParser->yytos--;
  146755. yyStackOverflow(yypParser);
  146756. return;
  146757. }
  146758. }
  146759. #endif
  146760. if( yyNewState > YY_MAX_SHIFT ){
  146761. yyNewState += YY_MIN_REDUCE - YY_MIN_SHIFTREDUCE;
  146762. }
  146763. yytos = yypParser->yytos;
  146764. yytos->stateno = yyNewState;
  146765. yytos->major = yyMajor;
  146766. yytos->minor.yy0 = yyMinor;
  146767. yyTraceShift(yypParser, yyNewState, "Shift");
  146768. }
  146769. /* For rule J, yyRuleInfoLhs[J] contains the symbol on the left-hand side
  146770. ** of that rule */
  146771. static const YYCODETYPE yyRuleInfoLhs[] = {
  146772. 185, /* (0) explain ::= EXPLAIN */
  146773. 185, /* (1) explain ::= EXPLAIN QUERY PLAN */
  146774. 184, /* (2) cmdx ::= cmd */
  146775. 186, /* (3) cmd ::= BEGIN transtype trans_opt */
  146776. 187, /* (4) transtype ::= */
  146777. 187, /* (5) transtype ::= DEFERRED */
  146778. 187, /* (6) transtype ::= IMMEDIATE */
  146779. 187, /* (7) transtype ::= EXCLUSIVE */
  146780. 186, /* (8) cmd ::= COMMIT|END trans_opt */
  146781. 186, /* (9) cmd ::= ROLLBACK trans_opt */
  146782. 186, /* (10) cmd ::= SAVEPOINT nm */
  146783. 186, /* (11) cmd ::= RELEASE savepoint_opt nm */
  146784. 186, /* (12) cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
  146785. 191, /* (13) create_table ::= createkw temp TABLE ifnotexists nm dbnm */
  146786. 193, /* (14) createkw ::= CREATE */
  146787. 195, /* (15) ifnotexists ::= */
  146788. 195, /* (16) ifnotexists ::= IF NOT EXISTS */
  146789. 194, /* (17) temp ::= TEMP */
  146790. 194, /* (18) temp ::= */
  146791. 192, /* (19) create_table_args ::= LP columnlist conslist_opt RP table_options */
  146792. 192, /* (20) create_table_args ::= AS select */
  146793. 199, /* (21) table_options ::= */
  146794. 199, /* (22) table_options ::= WITHOUT nm */
  146795. 201, /* (23) columnname ::= nm typetoken */
  146796. 203, /* (24) typetoken ::= */
  146797. 203, /* (25) typetoken ::= typename LP signed RP */
  146798. 203, /* (26) typetoken ::= typename LP signed COMMA signed RP */
  146799. 204, /* (27) typename ::= typename ID|STRING */
  146800. 208, /* (28) scanpt ::= */
  146801. 209, /* (29) scantok ::= */
  146802. 210, /* (30) ccons ::= CONSTRAINT nm */
  146803. 210, /* (31) ccons ::= DEFAULT scantok term */
  146804. 210, /* (32) ccons ::= DEFAULT LP expr RP */
  146805. 210, /* (33) ccons ::= DEFAULT PLUS scantok term */
  146806. 210, /* (34) ccons ::= DEFAULT MINUS scantok term */
  146807. 210, /* (35) ccons ::= DEFAULT scantok ID|INDEXED */
  146808. 210, /* (36) ccons ::= NOT NULL onconf */
  146809. 210, /* (37) ccons ::= PRIMARY KEY sortorder onconf autoinc */
  146810. 210, /* (38) ccons ::= UNIQUE onconf */
  146811. 210, /* (39) ccons ::= CHECK LP expr RP */
  146812. 210, /* (40) ccons ::= REFERENCES nm eidlist_opt refargs */
  146813. 210, /* (41) ccons ::= defer_subclause */
  146814. 210, /* (42) ccons ::= COLLATE ID|STRING */
  146815. 219, /* (43) generated ::= LP expr RP */
  146816. 219, /* (44) generated ::= LP expr RP ID */
  146817. 215, /* (45) autoinc ::= */
  146818. 215, /* (46) autoinc ::= AUTOINCR */
  146819. 217, /* (47) refargs ::= */
  146820. 217, /* (48) refargs ::= refargs refarg */
  146821. 220, /* (49) refarg ::= MATCH nm */
  146822. 220, /* (50) refarg ::= ON INSERT refact */
  146823. 220, /* (51) refarg ::= ON DELETE refact */
  146824. 220, /* (52) refarg ::= ON UPDATE refact */
  146825. 221, /* (53) refact ::= SET NULL */
  146826. 221, /* (54) refact ::= SET DEFAULT */
  146827. 221, /* (55) refact ::= CASCADE */
  146828. 221, /* (56) refact ::= RESTRICT */
  146829. 221, /* (57) refact ::= NO ACTION */
  146830. 218, /* (58) defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */
  146831. 218, /* (59) defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
  146832. 222, /* (60) init_deferred_pred_opt ::= */
  146833. 222, /* (61) init_deferred_pred_opt ::= INITIALLY DEFERRED */
  146834. 222, /* (62) init_deferred_pred_opt ::= INITIALLY IMMEDIATE */
  146835. 198, /* (63) conslist_opt ::= */
  146836. 224, /* (64) tconscomma ::= COMMA */
  146837. 225, /* (65) tcons ::= CONSTRAINT nm */
  146838. 225, /* (66) tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf */
  146839. 225, /* (67) tcons ::= UNIQUE LP sortlist RP onconf */
  146840. 225, /* (68) tcons ::= CHECK LP expr RP onconf */
  146841. 225, /* (69) tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt */
  146842. 228, /* (70) defer_subclause_opt ::= */
  146843. 213, /* (71) onconf ::= */
  146844. 213, /* (72) onconf ::= ON CONFLICT resolvetype */
  146845. 229, /* (73) orconf ::= */
  146846. 229, /* (74) orconf ::= OR resolvetype */
  146847. 230, /* (75) resolvetype ::= IGNORE */
  146848. 230, /* (76) resolvetype ::= REPLACE */
  146849. 186, /* (77) cmd ::= DROP TABLE ifexists fullname */
  146850. 232, /* (78) ifexists ::= IF EXISTS */
  146851. 232, /* (79) ifexists ::= */
  146852. 186, /* (80) cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select */
  146853. 186, /* (81) cmd ::= DROP VIEW ifexists fullname */
  146854. 186, /* (82) cmd ::= select */
  146855. 200, /* (83) select ::= WITH wqlist selectnowith */
  146856. 200, /* (84) select ::= WITH RECURSIVE wqlist selectnowith */
  146857. 200, /* (85) select ::= selectnowith */
  146858. 234, /* (86) selectnowith ::= selectnowith multiselect_op oneselect */
  146859. 237, /* (87) multiselect_op ::= UNION */
  146860. 237, /* (88) multiselect_op ::= UNION ALL */
  146861. 237, /* (89) multiselect_op ::= EXCEPT|INTERSECT */
  146862. 235, /* (90) oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
  146863. 235, /* (91) oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt window_clause orderby_opt limit_opt */
  146864. 247, /* (92) values ::= VALUES LP nexprlist RP */
  146865. 247, /* (93) values ::= values COMMA LP nexprlist RP */
  146866. 238, /* (94) distinct ::= DISTINCT */
  146867. 238, /* (95) distinct ::= ALL */
  146868. 238, /* (96) distinct ::= */
  146869. 249, /* (97) sclp ::= */
  146870. 239, /* (98) selcollist ::= sclp scanpt expr scanpt as */
  146871. 239, /* (99) selcollist ::= sclp scanpt STAR */
  146872. 239, /* (100) selcollist ::= sclp scanpt nm DOT STAR */
  146873. 250, /* (101) as ::= AS nm */
  146874. 250, /* (102) as ::= */
  146875. 240, /* (103) from ::= */
  146876. 240, /* (104) from ::= FROM seltablist */
  146877. 252, /* (105) stl_prefix ::= seltablist joinop */
  146878. 252, /* (106) stl_prefix ::= */
  146879. 251, /* (107) seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
  146880. 251, /* (108) seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt */
  146881. 251, /* (109) seltablist ::= stl_prefix LP select RP as on_opt using_opt */
  146882. 251, /* (110) seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
  146883. 196, /* (111) dbnm ::= */
  146884. 196, /* (112) dbnm ::= DOT nm */
  146885. 233, /* (113) fullname ::= nm */
  146886. 233, /* (114) fullname ::= nm DOT nm */
  146887. 258, /* (115) xfullname ::= nm */
  146888. 258, /* (116) xfullname ::= nm DOT nm */
  146889. 258, /* (117) xfullname ::= nm DOT nm AS nm */
  146890. 258, /* (118) xfullname ::= nm AS nm */
  146891. 253, /* (119) joinop ::= COMMA|JOIN */
  146892. 253, /* (120) joinop ::= JOIN_KW JOIN */
  146893. 253, /* (121) joinop ::= JOIN_KW nm JOIN */
  146894. 253, /* (122) joinop ::= JOIN_KW nm nm JOIN */
  146895. 255, /* (123) on_opt ::= ON expr */
  146896. 255, /* (124) on_opt ::= */
  146897. 254, /* (125) indexed_opt ::= */
  146898. 254, /* (126) indexed_opt ::= INDEXED BY nm */
  146899. 254, /* (127) indexed_opt ::= NOT INDEXED */
  146900. 256, /* (128) using_opt ::= USING LP idlist RP */
  146901. 256, /* (129) using_opt ::= */
  146902. 244, /* (130) orderby_opt ::= */
  146903. 244, /* (131) orderby_opt ::= ORDER BY sortlist */
  146904. 226, /* (132) sortlist ::= sortlist COMMA expr sortorder nulls */
  146905. 226, /* (133) sortlist ::= expr sortorder nulls */
  146906. 214, /* (134) sortorder ::= ASC */
  146907. 214, /* (135) sortorder ::= DESC */
  146908. 214, /* (136) sortorder ::= */
  146909. 260, /* (137) nulls ::= NULLS FIRST */
  146910. 260, /* (138) nulls ::= NULLS LAST */
  146911. 260, /* (139) nulls ::= */
  146912. 242, /* (140) groupby_opt ::= */
  146913. 242, /* (141) groupby_opt ::= GROUP BY nexprlist */
  146914. 243, /* (142) having_opt ::= */
  146915. 243, /* (143) having_opt ::= HAVING expr */
  146916. 245, /* (144) limit_opt ::= */
  146917. 245, /* (145) limit_opt ::= LIMIT expr */
  146918. 245, /* (146) limit_opt ::= LIMIT expr OFFSET expr */
  146919. 245, /* (147) limit_opt ::= LIMIT expr COMMA expr */
  146920. 186, /* (148) cmd ::= with DELETE FROM xfullname indexed_opt where_opt */
  146921. 241, /* (149) where_opt ::= */
  146922. 241, /* (150) where_opt ::= WHERE expr */
  146923. 186, /* (151) cmd ::= with UPDATE orconf xfullname indexed_opt SET setlist where_opt */
  146924. 262, /* (152) setlist ::= setlist COMMA nm EQ expr */
  146925. 262, /* (153) setlist ::= setlist COMMA LP idlist RP EQ expr */
  146926. 262, /* (154) setlist ::= nm EQ expr */
  146927. 262, /* (155) setlist ::= LP idlist RP EQ expr */
  146928. 186, /* (156) cmd ::= with insert_cmd INTO xfullname idlist_opt select upsert */
  146929. 186, /* (157) cmd ::= with insert_cmd INTO xfullname idlist_opt DEFAULT VALUES */
  146930. 265, /* (158) upsert ::= */
  146931. 265, /* (159) upsert ::= ON CONFLICT LP sortlist RP where_opt DO UPDATE SET setlist where_opt */
  146932. 265, /* (160) upsert ::= ON CONFLICT LP sortlist RP where_opt DO NOTHING */
  146933. 265, /* (161) upsert ::= ON CONFLICT DO NOTHING */
  146934. 263, /* (162) insert_cmd ::= INSERT orconf */
  146935. 263, /* (163) insert_cmd ::= REPLACE */
  146936. 264, /* (164) idlist_opt ::= */
  146937. 264, /* (165) idlist_opt ::= LP idlist RP */
  146938. 259, /* (166) idlist ::= idlist COMMA nm */
  146939. 259, /* (167) idlist ::= nm */
  146940. 212, /* (168) expr ::= LP expr RP */
  146941. 212, /* (169) expr ::= ID|INDEXED */
  146942. 212, /* (170) expr ::= JOIN_KW */
  146943. 212, /* (171) expr ::= nm DOT nm */
  146944. 212, /* (172) expr ::= nm DOT nm DOT nm */
  146945. 211, /* (173) term ::= NULL|FLOAT|BLOB */
  146946. 211, /* (174) term ::= STRING */
  146947. 211, /* (175) term ::= INTEGER */
  146948. 212, /* (176) expr ::= VARIABLE */
  146949. 212, /* (177) expr ::= expr COLLATE ID|STRING */
  146950. 212, /* (178) expr ::= CAST LP expr AS typetoken RP */
  146951. 212, /* (179) expr ::= ID|INDEXED LP distinct exprlist RP */
  146952. 212, /* (180) expr ::= ID|INDEXED LP STAR RP */
  146953. 212, /* (181) expr ::= ID|INDEXED LP distinct exprlist RP filter_over */
  146954. 212, /* (182) expr ::= ID|INDEXED LP STAR RP filter_over */
  146955. 211, /* (183) term ::= CTIME_KW */
  146956. 212, /* (184) expr ::= LP nexprlist COMMA expr RP */
  146957. 212, /* (185) expr ::= expr AND expr */
  146958. 212, /* (186) expr ::= expr OR expr */
  146959. 212, /* (187) expr ::= expr LT|GT|GE|LE expr */
  146960. 212, /* (188) expr ::= expr EQ|NE expr */
  146961. 212, /* (189) expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */
  146962. 212, /* (190) expr ::= expr PLUS|MINUS expr */
  146963. 212, /* (191) expr ::= expr STAR|SLASH|REM expr */
  146964. 212, /* (192) expr ::= expr CONCAT expr */
  146965. 267, /* (193) likeop ::= NOT LIKE_KW|MATCH */
  146966. 212, /* (194) expr ::= expr likeop expr */
  146967. 212, /* (195) expr ::= expr likeop expr ESCAPE expr */
  146968. 212, /* (196) expr ::= expr ISNULL|NOTNULL */
  146969. 212, /* (197) expr ::= expr NOT NULL */
  146970. 212, /* (198) expr ::= expr IS expr */
  146971. 212, /* (199) expr ::= expr IS NOT expr */
  146972. 212, /* (200) expr ::= NOT expr */
  146973. 212, /* (201) expr ::= BITNOT expr */
  146974. 212, /* (202) expr ::= PLUS|MINUS expr */
  146975. 268, /* (203) between_op ::= BETWEEN */
  146976. 268, /* (204) between_op ::= NOT BETWEEN */
  146977. 212, /* (205) expr ::= expr between_op expr AND expr */
  146978. 269, /* (206) in_op ::= IN */
  146979. 269, /* (207) in_op ::= NOT IN */
  146980. 212, /* (208) expr ::= expr in_op LP exprlist RP */
  146981. 212, /* (209) expr ::= LP select RP */
  146982. 212, /* (210) expr ::= expr in_op LP select RP */
  146983. 212, /* (211) expr ::= expr in_op nm dbnm paren_exprlist */
  146984. 212, /* (212) expr ::= EXISTS LP select RP */
  146985. 212, /* (213) expr ::= CASE case_operand case_exprlist case_else END */
  146986. 272, /* (214) case_exprlist ::= case_exprlist WHEN expr THEN expr */
  146987. 272, /* (215) case_exprlist ::= WHEN expr THEN expr */
  146988. 273, /* (216) case_else ::= ELSE expr */
  146989. 273, /* (217) case_else ::= */
  146990. 271, /* (218) case_operand ::= expr */
  146991. 271, /* (219) case_operand ::= */
  146992. 257, /* (220) exprlist ::= */
  146993. 248, /* (221) nexprlist ::= nexprlist COMMA expr */
  146994. 248, /* (222) nexprlist ::= expr */
  146995. 270, /* (223) paren_exprlist ::= */
  146996. 270, /* (224) paren_exprlist ::= LP exprlist RP */
  146997. 186, /* (225) cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt */
  146998. 274, /* (226) uniqueflag ::= UNIQUE */
  146999. 274, /* (227) uniqueflag ::= */
  147000. 216, /* (228) eidlist_opt ::= */
  147001. 216, /* (229) eidlist_opt ::= LP eidlist RP */
  147002. 227, /* (230) eidlist ::= eidlist COMMA nm collate sortorder */
  147003. 227, /* (231) eidlist ::= nm collate sortorder */
  147004. 275, /* (232) collate ::= */
  147005. 275, /* (233) collate ::= COLLATE ID|STRING */
  147006. 186, /* (234) cmd ::= DROP INDEX ifexists fullname */
  147007. 186, /* (235) cmd ::= VACUUM vinto */
  147008. 186, /* (236) cmd ::= VACUUM nm vinto */
  147009. 276, /* (237) vinto ::= INTO expr */
  147010. 276, /* (238) vinto ::= */
  147011. 186, /* (239) cmd ::= PRAGMA nm dbnm */
  147012. 186, /* (240) cmd ::= PRAGMA nm dbnm EQ nmnum */
  147013. 186, /* (241) cmd ::= PRAGMA nm dbnm LP nmnum RP */
  147014. 186, /* (242) cmd ::= PRAGMA nm dbnm EQ minus_num */
  147015. 186, /* (243) cmd ::= PRAGMA nm dbnm LP minus_num RP */
  147016. 206, /* (244) plus_num ::= PLUS INTEGER|FLOAT */
  147017. 207, /* (245) minus_num ::= MINUS INTEGER|FLOAT */
  147018. 186, /* (246) cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
  147019. 278, /* (247) trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
  147020. 280, /* (248) trigger_time ::= BEFORE|AFTER */
  147021. 280, /* (249) trigger_time ::= INSTEAD OF */
  147022. 280, /* (250) trigger_time ::= */
  147023. 281, /* (251) trigger_event ::= DELETE|INSERT */
  147024. 281, /* (252) trigger_event ::= UPDATE */
  147025. 281, /* (253) trigger_event ::= UPDATE OF idlist */
  147026. 283, /* (254) when_clause ::= */
  147027. 283, /* (255) when_clause ::= WHEN expr */
  147028. 279, /* (256) trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
  147029. 279, /* (257) trigger_cmd_list ::= trigger_cmd SEMI */
  147030. 285, /* (258) trnm ::= nm DOT nm */
  147031. 286, /* (259) tridxby ::= INDEXED BY nm */
  147032. 286, /* (260) tridxby ::= NOT INDEXED */
  147033. 284, /* (261) trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt scanpt */
  147034. 284, /* (262) trigger_cmd ::= scanpt insert_cmd INTO trnm idlist_opt select upsert scanpt */
  147035. 284, /* (263) trigger_cmd ::= DELETE FROM trnm tridxby where_opt scanpt */
  147036. 284, /* (264) trigger_cmd ::= scanpt select scanpt */
  147037. 212, /* (265) expr ::= RAISE LP IGNORE RP */
  147038. 212, /* (266) expr ::= RAISE LP raisetype COMMA nm RP */
  147039. 231, /* (267) raisetype ::= ROLLBACK */
  147040. 231, /* (268) raisetype ::= ABORT */
  147041. 231, /* (269) raisetype ::= FAIL */
  147042. 186, /* (270) cmd ::= DROP TRIGGER ifexists fullname */
  147043. 186, /* (271) cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
  147044. 186, /* (272) cmd ::= DETACH database_kw_opt expr */
  147045. 288, /* (273) key_opt ::= */
  147046. 288, /* (274) key_opt ::= KEY expr */
  147047. 186, /* (275) cmd ::= REINDEX */
  147048. 186, /* (276) cmd ::= REINDEX nm dbnm */
  147049. 186, /* (277) cmd ::= ANALYZE */
  147050. 186, /* (278) cmd ::= ANALYZE nm dbnm */
  147051. 186, /* (279) cmd ::= ALTER TABLE fullname RENAME TO nm */
  147052. 186, /* (280) cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist */
  147053. 289, /* (281) add_column_fullname ::= fullname */
  147054. 186, /* (282) cmd ::= ALTER TABLE fullname RENAME kwcolumn_opt nm TO nm */
  147055. 186, /* (283) cmd ::= create_vtab */
  147056. 186, /* (284) cmd ::= create_vtab LP vtabarglist RP */
  147057. 291, /* (285) create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
  147058. 293, /* (286) vtabarg ::= */
  147059. 294, /* (287) vtabargtoken ::= ANY */
  147060. 294, /* (288) vtabargtoken ::= lp anylist RP */
  147061. 295, /* (289) lp ::= LP */
  147062. 261, /* (290) with ::= WITH wqlist */
  147063. 261, /* (291) with ::= WITH RECURSIVE wqlist */
  147064. 236, /* (292) wqlist ::= nm eidlist_opt AS LP select RP */
  147065. 236, /* (293) wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP */
  147066. 297, /* (294) windowdefn_list ::= windowdefn */
  147067. 297, /* (295) windowdefn_list ::= windowdefn_list COMMA windowdefn */
  147068. 298, /* (296) windowdefn ::= nm AS LP window RP */
  147069. 299, /* (297) window ::= PARTITION BY nexprlist orderby_opt frame_opt */
  147070. 299, /* (298) window ::= nm PARTITION BY nexprlist orderby_opt frame_opt */
  147071. 299, /* (299) window ::= ORDER BY sortlist frame_opt */
  147072. 299, /* (300) window ::= nm ORDER BY sortlist frame_opt */
  147073. 299, /* (301) window ::= frame_opt */
  147074. 299, /* (302) window ::= nm frame_opt */
  147075. 300, /* (303) frame_opt ::= */
  147076. 300, /* (304) frame_opt ::= range_or_rows frame_bound_s frame_exclude_opt */
  147077. 300, /* (305) frame_opt ::= range_or_rows BETWEEN frame_bound_s AND frame_bound_e frame_exclude_opt */
  147078. 304, /* (306) range_or_rows ::= RANGE|ROWS|GROUPS */
  147079. 306, /* (307) frame_bound_s ::= frame_bound */
  147080. 306, /* (308) frame_bound_s ::= UNBOUNDED PRECEDING */
  147081. 307, /* (309) frame_bound_e ::= frame_bound */
  147082. 307, /* (310) frame_bound_e ::= UNBOUNDED FOLLOWING */
  147083. 305, /* (311) frame_bound ::= expr PRECEDING|FOLLOWING */
  147084. 305, /* (312) frame_bound ::= CURRENT ROW */
  147085. 308, /* (313) frame_exclude_opt ::= */
  147086. 308, /* (314) frame_exclude_opt ::= EXCLUDE frame_exclude */
  147087. 309, /* (315) frame_exclude ::= NO OTHERS */
  147088. 309, /* (316) frame_exclude ::= CURRENT ROW */
  147089. 309, /* (317) frame_exclude ::= GROUP|TIES */
  147090. 246, /* (318) window_clause ::= WINDOW windowdefn_list */
  147091. 266, /* (319) filter_over ::= filter_clause over_clause */
  147092. 266, /* (320) filter_over ::= over_clause */
  147093. 266, /* (321) filter_over ::= filter_clause */
  147094. 303, /* (322) over_clause ::= OVER LP window RP */
  147095. 303, /* (323) over_clause ::= OVER nm */
  147096. 302, /* (324) filter_clause ::= FILTER LP WHERE expr RP */
  147097. 181, /* (325) input ::= cmdlist */
  147098. 182, /* (326) cmdlist ::= cmdlist ecmd */
  147099. 182, /* (327) cmdlist ::= ecmd */
  147100. 183, /* (328) ecmd ::= SEMI */
  147101. 183, /* (329) ecmd ::= cmdx SEMI */
  147102. 183, /* (330) ecmd ::= explain cmdx SEMI */
  147103. 188, /* (331) trans_opt ::= */
  147104. 188, /* (332) trans_opt ::= TRANSACTION */
  147105. 188, /* (333) trans_opt ::= TRANSACTION nm */
  147106. 190, /* (334) savepoint_opt ::= SAVEPOINT */
  147107. 190, /* (335) savepoint_opt ::= */
  147108. 186, /* (336) cmd ::= create_table create_table_args */
  147109. 197, /* (337) columnlist ::= columnlist COMMA columnname carglist */
  147110. 197, /* (338) columnlist ::= columnname carglist */
  147111. 189, /* (339) nm ::= ID|INDEXED */
  147112. 189, /* (340) nm ::= STRING */
  147113. 189, /* (341) nm ::= JOIN_KW */
  147114. 203, /* (342) typetoken ::= typename */
  147115. 204, /* (343) typename ::= ID|STRING */
  147116. 205, /* (344) signed ::= plus_num */
  147117. 205, /* (345) signed ::= minus_num */
  147118. 202, /* (346) carglist ::= carglist ccons */
  147119. 202, /* (347) carglist ::= */
  147120. 210, /* (348) ccons ::= NULL onconf */
  147121. 210, /* (349) ccons ::= GENERATED ALWAYS AS generated */
  147122. 210, /* (350) ccons ::= AS generated */
  147123. 198, /* (351) conslist_opt ::= COMMA conslist */
  147124. 223, /* (352) conslist ::= conslist tconscomma tcons */
  147125. 223, /* (353) conslist ::= tcons */
  147126. 224, /* (354) tconscomma ::= */
  147127. 228, /* (355) defer_subclause_opt ::= defer_subclause */
  147128. 230, /* (356) resolvetype ::= raisetype */
  147129. 234, /* (357) selectnowith ::= oneselect */
  147130. 235, /* (358) oneselect ::= values */
  147131. 249, /* (359) sclp ::= selcollist COMMA */
  147132. 250, /* (360) as ::= ID|STRING */
  147133. 212, /* (361) expr ::= term */
  147134. 267, /* (362) likeop ::= LIKE_KW|MATCH */
  147135. 257, /* (363) exprlist ::= nexprlist */
  147136. 277, /* (364) nmnum ::= plus_num */
  147137. 277, /* (365) nmnum ::= nm */
  147138. 277, /* (366) nmnum ::= ON */
  147139. 277, /* (367) nmnum ::= DELETE */
  147140. 277, /* (368) nmnum ::= DEFAULT */
  147141. 206, /* (369) plus_num ::= INTEGER|FLOAT */
  147142. 282, /* (370) foreach_clause ::= */
  147143. 282, /* (371) foreach_clause ::= FOR EACH ROW */
  147144. 285, /* (372) trnm ::= nm */
  147145. 286, /* (373) tridxby ::= */
  147146. 287, /* (374) database_kw_opt ::= DATABASE */
  147147. 287, /* (375) database_kw_opt ::= */
  147148. 290, /* (376) kwcolumn_opt ::= */
  147149. 290, /* (377) kwcolumn_opt ::= COLUMNKW */
  147150. 292, /* (378) vtabarglist ::= vtabarg */
  147151. 292, /* (379) vtabarglist ::= vtabarglist COMMA vtabarg */
  147152. 293, /* (380) vtabarg ::= vtabarg vtabargtoken */
  147153. 296, /* (381) anylist ::= */
  147154. 296, /* (382) anylist ::= anylist LP anylist RP */
  147155. 296, /* (383) anylist ::= anylist ANY */
  147156. 261, /* (384) with ::= */
  147157. };
  147158. /* For rule J, yyRuleInfoNRhs[J] contains the negative of the number
  147159. ** of symbols on the right-hand side of that rule. */
  147160. static const signed char yyRuleInfoNRhs[] = {
  147161. -1, /* (0) explain ::= EXPLAIN */
  147162. -3, /* (1) explain ::= EXPLAIN QUERY PLAN */
  147163. -1, /* (2) cmdx ::= cmd */
  147164. -3, /* (3) cmd ::= BEGIN transtype trans_opt */
  147165. 0, /* (4) transtype ::= */
  147166. -1, /* (5) transtype ::= DEFERRED */
  147167. -1, /* (6) transtype ::= IMMEDIATE */
  147168. -1, /* (7) transtype ::= EXCLUSIVE */
  147169. -2, /* (8) cmd ::= COMMIT|END trans_opt */
  147170. -2, /* (9) cmd ::= ROLLBACK trans_opt */
  147171. -2, /* (10) cmd ::= SAVEPOINT nm */
  147172. -3, /* (11) cmd ::= RELEASE savepoint_opt nm */
  147173. -5, /* (12) cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
  147174. -6, /* (13) create_table ::= createkw temp TABLE ifnotexists nm dbnm */
  147175. -1, /* (14) createkw ::= CREATE */
  147176. 0, /* (15) ifnotexists ::= */
  147177. -3, /* (16) ifnotexists ::= IF NOT EXISTS */
  147178. -1, /* (17) temp ::= TEMP */
  147179. 0, /* (18) temp ::= */
  147180. -5, /* (19) create_table_args ::= LP columnlist conslist_opt RP table_options */
  147181. -2, /* (20) create_table_args ::= AS select */
  147182. 0, /* (21) table_options ::= */
  147183. -2, /* (22) table_options ::= WITHOUT nm */
  147184. -2, /* (23) columnname ::= nm typetoken */
  147185. 0, /* (24) typetoken ::= */
  147186. -4, /* (25) typetoken ::= typename LP signed RP */
  147187. -6, /* (26) typetoken ::= typename LP signed COMMA signed RP */
  147188. -2, /* (27) typename ::= typename ID|STRING */
  147189. 0, /* (28) scanpt ::= */
  147190. 0, /* (29) scantok ::= */
  147191. -2, /* (30) ccons ::= CONSTRAINT nm */
  147192. -3, /* (31) ccons ::= DEFAULT scantok term */
  147193. -4, /* (32) ccons ::= DEFAULT LP expr RP */
  147194. -4, /* (33) ccons ::= DEFAULT PLUS scantok term */
  147195. -4, /* (34) ccons ::= DEFAULT MINUS scantok term */
  147196. -3, /* (35) ccons ::= DEFAULT scantok ID|INDEXED */
  147197. -3, /* (36) ccons ::= NOT NULL onconf */
  147198. -5, /* (37) ccons ::= PRIMARY KEY sortorder onconf autoinc */
  147199. -2, /* (38) ccons ::= UNIQUE onconf */
  147200. -4, /* (39) ccons ::= CHECK LP expr RP */
  147201. -4, /* (40) ccons ::= REFERENCES nm eidlist_opt refargs */
  147202. -1, /* (41) ccons ::= defer_subclause */
  147203. -2, /* (42) ccons ::= COLLATE ID|STRING */
  147204. -3, /* (43) generated ::= LP expr RP */
  147205. -4, /* (44) generated ::= LP expr RP ID */
  147206. 0, /* (45) autoinc ::= */
  147207. -1, /* (46) autoinc ::= AUTOINCR */
  147208. 0, /* (47) refargs ::= */
  147209. -2, /* (48) refargs ::= refargs refarg */
  147210. -2, /* (49) refarg ::= MATCH nm */
  147211. -3, /* (50) refarg ::= ON INSERT refact */
  147212. -3, /* (51) refarg ::= ON DELETE refact */
  147213. -3, /* (52) refarg ::= ON UPDATE refact */
  147214. -2, /* (53) refact ::= SET NULL */
  147215. -2, /* (54) refact ::= SET DEFAULT */
  147216. -1, /* (55) refact ::= CASCADE */
  147217. -1, /* (56) refact ::= RESTRICT */
  147218. -2, /* (57) refact ::= NO ACTION */
  147219. -3, /* (58) defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */
  147220. -2, /* (59) defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
  147221. 0, /* (60) init_deferred_pred_opt ::= */
  147222. -2, /* (61) init_deferred_pred_opt ::= INITIALLY DEFERRED */
  147223. -2, /* (62) init_deferred_pred_opt ::= INITIALLY IMMEDIATE */
  147224. 0, /* (63) conslist_opt ::= */
  147225. -1, /* (64) tconscomma ::= COMMA */
  147226. -2, /* (65) tcons ::= CONSTRAINT nm */
  147227. -7, /* (66) tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf */
  147228. -5, /* (67) tcons ::= UNIQUE LP sortlist RP onconf */
  147229. -5, /* (68) tcons ::= CHECK LP expr RP onconf */
  147230. -10, /* (69) tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt */
  147231. 0, /* (70) defer_subclause_opt ::= */
  147232. 0, /* (71) onconf ::= */
  147233. -3, /* (72) onconf ::= ON CONFLICT resolvetype */
  147234. 0, /* (73) orconf ::= */
  147235. -2, /* (74) orconf ::= OR resolvetype */
  147236. -1, /* (75) resolvetype ::= IGNORE */
  147237. -1, /* (76) resolvetype ::= REPLACE */
  147238. -4, /* (77) cmd ::= DROP TABLE ifexists fullname */
  147239. -2, /* (78) ifexists ::= IF EXISTS */
  147240. 0, /* (79) ifexists ::= */
  147241. -9, /* (80) cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select */
  147242. -4, /* (81) cmd ::= DROP VIEW ifexists fullname */
  147243. -1, /* (82) cmd ::= select */
  147244. -3, /* (83) select ::= WITH wqlist selectnowith */
  147245. -4, /* (84) select ::= WITH RECURSIVE wqlist selectnowith */
  147246. -1, /* (85) select ::= selectnowith */
  147247. -3, /* (86) selectnowith ::= selectnowith multiselect_op oneselect */
  147248. -1, /* (87) multiselect_op ::= UNION */
  147249. -2, /* (88) multiselect_op ::= UNION ALL */
  147250. -1, /* (89) multiselect_op ::= EXCEPT|INTERSECT */
  147251. -9, /* (90) oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
  147252. -10, /* (91) oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt window_clause orderby_opt limit_opt */
  147253. -4, /* (92) values ::= VALUES LP nexprlist RP */
  147254. -5, /* (93) values ::= values COMMA LP nexprlist RP */
  147255. -1, /* (94) distinct ::= DISTINCT */
  147256. -1, /* (95) distinct ::= ALL */
  147257. 0, /* (96) distinct ::= */
  147258. 0, /* (97) sclp ::= */
  147259. -5, /* (98) selcollist ::= sclp scanpt expr scanpt as */
  147260. -3, /* (99) selcollist ::= sclp scanpt STAR */
  147261. -5, /* (100) selcollist ::= sclp scanpt nm DOT STAR */
  147262. -2, /* (101) as ::= AS nm */
  147263. 0, /* (102) as ::= */
  147264. 0, /* (103) from ::= */
  147265. -2, /* (104) from ::= FROM seltablist */
  147266. -2, /* (105) stl_prefix ::= seltablist joinop */
  147267. 0, /* (106) stl_prefix ::= */
  147268. -7, /* (107) seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
  147269. -9, /* (108) seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt */
  147270. -7, /* (109) seltablist ::= stl_prefix LP select RP as on_opt using_opt */
  147271. -7, /* (110) seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
  147272. 0, /* (111) dbnm ::= */
  147273. -2, /* (112) dbnm ::= DOT nm */
  147274. -1, /* (113) fullname ::= nm */
  147275. -3, /* (114) fullname ::= nm DOT nm */
  147276. -1, /* (115) xfullname ::= nm */
  147277. -3, /* (116) xfullname ::= nm DOT nm */
  147278. -5, /* (117) xfullname ::= nm DOT nm AS nm */
  147279. -3, /* (118) xfullname ::= nm AS nm */
  147280. -1, /* (119) joinop ::= COMMA|JOIN */
  147281. -2, /* (120) joinop ::= JOIN_KW JOIN */
  147282. -3, /* (121) joinop ::= JOIN_KW nm JOIN */
  147283. -4, /* (122) joinop ::= JOIN_KW nm nm JOIN */
  147284. -2, /* (123) on_opt ::= ON expr */
  147285. 0, /* (124) on_opt ::= */
  147286. 0, /* (125) indexed_opt ::= */
  147287. -3, /* (126) indexed_opt ::= INDEXED BY nm */
  147288. -2, /* (127) indexed_opt ::= NOT INDEXED */
  147289. -4, /* (128) using_opt ::= USING LP idlist RP */
  147290. 0, /* (129) using_opt ::= */
  147291. 0, /* (130) orderby_opt ::= */
  147292. -3, /* (131) orderby_opt ::= ORDER BY sortlist */
  147293. -5, /* (132) sortlist ::= sortlist COMMA expr sortorder nulls */
  147294. -3, /* (133) sortlist ::= expr sortorder nulls */
  147295. -1, /* (134) sortorder ::= ASC */
  147296. -1, /* (135) sortorder ::= DESC */
  147297. 0, /* (136) sortorder ::= */
  147298. -2, /* (137) nulls ::= NULLS FIRST */
  147299. -2, /* (138) nulls ::= NULLS LAST */
  147300. 0, /* (139) nulls ::= */
  147301. 0, /* (140) groupby_opt ::= */
  147302. -3, /* (141) groupby_opt ::= GROUP BY nexprlist */
  147303. 0, /* (142) having_opt ::= */
  147304. -2, /* (143) having_opt ::= HAVING expr */
  147305. 0, /* (144) limit_opt ::= */
  147306. -2, /* (145) limit_opt ::= LIMIT expr */
  147307. -4, /* (146) limit_opt ::= LIMIT expr OFFSET expr */
  147308. -4, /* (147) limit_opt ::= LIMIT expr COMMA expr */
  147309. -6, /* (148) cmd ::= with DELETE FROM xfullname indexed_opt where_opt */
  147310. 0, /* (149) where_opt ::= */
  147311. -2, /* (150) where_opt ::= WHERE expr */
  147312. -8, /* (151) cmd ::= with UPDATE orconf xfullname indexed_opt SET setlist where_opt */
  147313. -5, /* (152) setlist ::= setlist COMMA nm EQ expr */
  147314. -7, /* (153) setlist ::= setlist COMMA LP idlist RP EQ expr */
  147315. -3, /* (154) setlist ::= nm EQ expr */
  147316. -5, /* (155) setlist ::= LP idlist RP EQ expr */
  147317. -7, /* (156) cmd ::= with insert_cmd INTO xfullname idlist_opt select upsert */
  147318. -7, /* (157) cmd ::= with insert_cmd INTO xfullname idlist_opt DEFAULT VALUES */
  147319. 0, /* (158) upsert ::= */
  147320. -11, /* (159) upsert ::= ON CONFLICT LP sortlist RP where_opt DO UPDATE SET setlist where_opt */
  147321. -8, /* (160) upsert ::= ON CONFLICT LP sortlist RP where_opt DO NOTHING */
  147322. -4, /* (161) upsert ::= ON CONFLICT DO NOTHING */
  147323. -2, /* (162) insert_cmd ::= INSERT orconf */
  147324. -1, /* (163) insert_cmd ::= REPLACE */
  147325. 0, /* (164) idlist_opt ::= */
  147326. -3, /* (165) idlist_opt ::= LP idlist RP */
  147327. -3, /* (166) idlist ::= idlist COMMA nm */
  147328. -1, /* (167) idlist ::= nm */
  147329. -3, /* (168) expr ::= LP expr RP */
  147330. -1, /* (169) expr ::= ID|INDEXED */
  147331. -1, /* (170) expr ::= JOIN_KW */
  147332. -3, /* (171) expr ::= nm DOT nm */
  147333. -5, /* (172) expr ::= nm DOT nm DOT nm */
  147334. -1, /* (173) term ::= NULL|FLOAT|BLOB */
  147335. -1, /* (174) term ::= STRING */
  147336. -1, /* (175) term ::= INTEGER */
  147337. -1, /* (176) expr ::= VARIABLE */
  147338. -3, /* (177) expr ::= expr COLLATE ID|STRING */
  147339. -6, /* (178) expr ::= CAST LP expr AS typetoken RP */
  147340. -5, /* (179) expr ::= ID|INDEXED LP distinct exprlist RP */
  147341. -4, /* (180) expr ::= ID|INDEXED LP STAR RP */
  147342. -6, /* (181) expr ::= ID|INDEXED LP distinct exprlist RP filter_over */
  147343. -5, /* (182) expr ::= ID|INDEXED LP STAR RP filter_over */
  147344. -1, /* (183) term ::= CTIME_KW */
  147345. -5, /* (184) expr ::= LP nexprlist COMMA expr RP */
  147346. -3, /* (185) expr ::= expr AND expr */
  147347. -3, /* (186) expr ::= expr OR expr */
  147348. -3, /* (187) expr ::= expr LT|GT|GE|LE expr */
  147349. -3, /* (188) expr ::= expr EQ|NE expr */
  147350. -3, /* (189) expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */
  147351. -3, /* (190) expr ::= expr PLUS|MINUS expr */
  147352. -3, /* (191) expr ::= expr STAR|SLASH|REM expr */
  147353. -3, /* (192) expr ::= expr CONCAT expr */
  147354. -2, /* (193) likeop ::= NOT LIKE_KW|MATCH */
  147355. -3, /* (194) expr ::= expr likeop expr */
  147356. -5, /* (195) expr ::= expr likeop expr ESCAPE expr */
  147357. -2, /* (196) expr ::= expr ISNULL|NOTNULL */
  147358. -3, /* (197) expr ::= expr NOT NULL */
  147359. -3, /* (198) expr ::= expr IS expr */
  147360. -4, /* (199) expr ::= expr IS NOT expr */
  147361. -2, /* (200) expr ::= NOT expr */
  147362. -2, /* (201) expr ::= BITNOT expr */
  147363. -2, /* (202) expr ::= PLUS|MINUS expr */
  147364. -1, /* (203) between_op ::= BETWEEN */
  147365. -2, /* (204) between_op ::= NOT BETWEEN */
  147366. -5, /* (205) expr ::= expr between_op expr AND expr */
  147367. -1, /* (206) in_op ::= IN */
  147368. -2, /* (207) in_op ::= NOT IN */
  147369. -5, /* (208) expr ::= expr in_op LP exprlist RP */
  147370. -3, /* (209) expr ::= LP select RP */
  147371. -5, /* (210) expr ::= expr in_op LP select RP */
  147372. -5, /* (211) expr ::= expr in_op nm dbnm paren_exprlist */
  147373. -4, /* (212) expr ::= EXISTS LP select RP */
  147374. -5, /* (213) expr ::= CASE case_operand case_exprlist case_else END */
  147375. -5, /* (214) case_exprlist ::= case_exprlist WHEN expr THEN expr */
  147376. -4, /* (215) case_exprlist ::= WHEN expr THEN expr */
  147377. -2, /* (216) case_else ::= ELSE expr */
  147378. 0, /* (217) case_else ::= */
  147379. -1, /* (218) case_operand ::= expr */
  147380. 0, /* (219) case_operand ::= */
  147381. 0, /* (220) exprlist ::= */
  147382. -3, /* (221) nexprlist ::= nexprlist COMMA expr */
  147383. -1, /* (222) nexprlist ::= expr */
  147384. 0, /* (223) paren_exprlist ::= */
  147385. -3, /* (224) paren_exprlist ::= LP exprlist RP */
  147386. -12, /* (225) cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt */
  147387. -1, /* (226) uniqueflag ::= UNIQUE */
  147388. 0, /* (227) uniqueflag ::= */
  147389. 0, /* (228) eidlist_opt ::= */
  147390. -3, /* (229) eidlist_opt ::= LP eidlist RP */
  147391. -5, /* (230) eidlist ::= eidlist COMMA nm collate sortorder */
  147392. -3, /* (231) eidlist ::= nm collate sortorder */
  147393. 0, /* (232) collate ::= */
  147394. -2, /* (233) collate ::= COLLATE ID|STRING */
  147395. -4, /* (234) cmd ::= DROP INDEX ifexists fullname */
  147396. -2, /* (235) cmd ::= VACUUM vinto */
  147397. -3, /* (236) cmd ::= VACUUM nm vinto */
  147398. -2, /* (237) vinto ::= INTO expr */
  147399. 0, /* (238) vinto ::= */
  147400. -3, /* (239) cmd ::= PRAGMA nm dbnm */
  147401. -5, /* (240) cmd ::= PRAGMA nm dbnm EQ nmnum */
  147402. -6, /* (241) cmd ::= PRAGMA nm dbnm LP nmnum RP */
  147403. -5, /* (242) cmd ::= PRAGMA nm dbnm EQ minus_num */
  147404. -6, /* (243) cmd ::= PRAGMA nm dbnm LP minus_num RP */
  147405. -2, /* (244) plus_num ::= PLUS INTEGER|FLOAT */
  147406. -2, /* (245) minus_num ::= MINUS INTEGER|FLOAT */
  147407. -5, /* (246) cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
  147408. -11, /* (247) trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
  147409. -1, /* (248) trigger_time ::= BEFORE|AFTER */
  147410. -2, /* (249) trigger_time ::= INSTEAD OF */
  147411. 0, /* (250) trigger_time ::= */
  147412. -1, /* (251) trigger_event ::= DELETE|INSERT */
  147413. -1, /* (252) trigger_event ::= UPDATE */
  147414. -3, /* (253) trigger_event ::= UPDATE OF idlist */
  147415. 0, /* (254) when_clause ::= */
  147416. -2, /* (255) when_clause ::= WHEN expr */
  147417. -3, /* (256) trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
  147418. -2, /* (257) trigger_cmd_list ::= trigger_cmd SEMI */
  147419. -3, /* (258) trnm ::= nm DOT nm */
  147420. -3, /* (259) tridxby ::= INDEXED BY nm */
  147421. -2, /* (260) tridxby ::= NOT INDEXED */
  147422. -8, /* (261) trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt scanpt */
  147423. -8, /* (262) trigger_cmd ::= scanpt insert_cmd INTO trnm idlist_opt select upsert scanpt */
  147424. -6, /* (263) trigger_cmd ::= DELETE FROM trnm tridxby where_opt scanpt */
  147425. -3, /* (264) trigger_cmd ::= scanpt select scanpt */
  147426. -4, /* (265) expr ::= RAISE LP IGNORE RP */
  147427. -6, /* (266) expr ::= RAISE LP raisetype COMMA nm RP */
  147428. -1, /* (267) raisetype ::= ROLLBACK */
  147429. -1, /* (268) raisetype ::= ABORT */
  147430. -1, /* (269) raisetype ::= FAIL */
  147431. -4, /* (270) cmd ::= DROP TRIGGER ifexists fullname */
  147432. -6, /* (271) cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
  147433. -3, /* (272) cmd ::= DETACH database_kw_opt expr */
  147434. 0, /* (273) key_opt ::= */
  147435. -2, /* (274) key_opt ::= KEY expr */
  147436. -1, /* (275) cmd ::= REINDEX */
  147437. -3, /* (276) cmd ::= REINDEX nm dbnm */
  147438. -1, /* (277) cmd ::= ANALYZE */
  147439. -3, /* (278) cmd ::= ANALYZE nm dbnm */
  147440. -6, /* (279) cmd ::= ALTER TABLE fullname RENAME TO nm */
  147441. -7, /* (280) cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist */
  147442. -1, /* (281) add_column_fullname ::= fullname */
  147443. -8, /* (282) cmd ::= ALTER TABLE fullname RENAME kwcolumn_opt nm TO nm */
  147444. -1, /* (283) cmd ::= create_vtab */
  147445. -4, /* (284) cmd ::= create_vtab LP vtabarglist RP */
  147446. -8, /* (285) create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
  147447. 0, /* (286) vtabarg ::= */
  147448. -1, /* (287) vtabargtoken ::= ANY */
  147449. -3, /* (288) vtabargtoken ::= lp anylist RP */
  147450. -1, /* (289) lp ::= LP */
  147451. -2, /* (290) with ::= WITH wqlist */
  147452. -3, /* (291) with ::= WITH RECURSIVE wqlist */
  147453. -6, /* (292) wqlist ::= nm eidlist_opt AS LP select RP */
  147454. -8, /* (293) wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP */
  147455. -1, /* (294) windowdefn_list ::= windowdefn */
  147456. -3, /* (295) windowdefn_list ::= windowdefn_list COMMA windowdefn */
  147457. -5, /* (296) windowdefn ::= nm AS LP window RP */
  147458. -5, /* (297) window ::= PARTITION BY nexprlist orderby_opt frame_opt */
  147459. -6, /* (298) window ::= nm PARTITION BY nexprlist orderby_opt frame_opt */
  147460. -4, /* (299) window ::= ORDER BY sortlist frame_opt */
  147461. -5, /* (300) window ::= nm ORDER BY sortlist frame_opt */
  147462. -1, /* (301) window ::= frame_opt */
  147463. -2, /* (302) window ::= nm frame_opt */
  147464. 0, /* (303) frame_opt ::= */
  147465. -3, /* (304) frame_opt ::= range_or_rows frame_bound_s frame_exclude_opt */
  147466. -6, /* (305) frame_opt ::= range_or_rows BETWEEN frame_bound_s AND frame_bound_e frame_exclude_opt */
  147467. -1, /* (306) range_or_rows ::= RANGE|ROWS|GROUPS */
  147468. -1, /* (307) frame_bound_s ::= frame_bound */
  147469. -2, /* (308) frame_bound_s ::= UNBOUNDED PRECEDING */
  147470. -1, /* (309) frame_bound_e ::= frame_bound */
  147471. -2, /* (310) frame_bound_e ::= UNBOUNDED FOLLOWING */
  147472. -2, /* (311) frame_bound ::= expr PRECEDING|FOLLOWING */
  147473. -2, /* (312) frame_bound ::= CURRENT ROW */
  147474. 0, /* (313) frame_exclude_opt ::= */
  147475. -2, /* (314) frame_exclude_opt ::= EXCLUDE frame_exclude */
  147476. -2, /* (315) frame_exclude ::= NO OTHERS */
  147477. -2, /* (316) frame_exclude ::= CURRENT ROW */
  147478. -1, /* (317) frame_exclude ::= GROUP|TIES */
  147479. -2, /* (318) window_clause ::= WINDOW windowdefn_list */
  147480. -2, /* (319) filter_over ::= filter_clause over_clause */
  147481. -1, /* (320) filter_over ::= over_clause */
  147482. -1, /* (321) filter_over ::= filter_clause */
  147483. -4, /* (322) over_clause ::= OVER LP window RP */
  147484. -2, /* (323) over_clause ::= OVER nm */
  147485. -5, /* (324) filter_clause ::= FILTER LP WHERE expr RP */
  147486. -1, /* (325) input ::= cmdlist */
  147487. -2, /* (326) cmdlist ::= cmdlist ecmd */
  147488. -1, /* (327) cmdlist ::= ecmd */
  147489. -1, /* (328) ecmd ::= SEMI */
  147490. -2, /* (329) ecmd ::= cmdx SEMI */
  147491. -3, /* (330) ecmd ::= explain cmdx SEMI */
  147492. 0, /* (331) trans_opt ::= */
  147493. -1, /* (332) trans_opt ::= TRANSACTION */
  147494. -2, /* (333) trans_opt ::= TRANSACTION nm */
  147495. -1, /* (334) savepoint_opt ::= SAVEPOINT */
  147496. 0, /* (335) savepoint_opt ::= */
  147497. -2, /* (336) cmd ::= create_table create_table_args */
  147498. -4, /* (337) columnlist ::= columnlist COMMA columnname carglist */
  147499. -2, /* (338) columnlist ::= columnname carglist */
  147500. -1, /* (339) nm ::= ID|INDEXED */
  147501. -1, /* (340) nm ::= STRING */
  147502. -1, /* (341) nm ::= JOIN_KW */
  147503. -1, /* (342) typetoken ::= typename */
  147504. -1, /* (343) typename ::= ID|STRING */
  147505. -1, /* (344) signed ::= plus_num */
  147506. -1, /* (345) signed ::= minus_num */
  147507. -2, /* (346) carglist ::= carglist ccons */
  147508. 0, /* (347) carglist ::= */
  147509. -2, /* (348) ccons ::= NULL onconf */
  147510. -4, /* (349) ccons ::= GENERATED ALWAYS AS generated */
  147511. -2, /* (350) ccons ::= AS generated */
  147512. -2, /* (351) conslist_opt ::= COMMA conslist */
  147513. -3, /* (352) conslist ::= conslist tconscomma tcons */
  147514. -1, /* (353) conslist ::= tcons */
  147515. 0, /* (354) tconscomma ::= */
  147516. -1, /* (355) defer_subclause_opt ::= defer_subclause */
  147517. -1, /* (356) resolvetype ::= raisetype */
  147518. -1, /* (357) selectnowith ::= oneselect */
  147519. -1, /* (358) oneselect ::= values */
  147520. -2, /* (359) sclp ::= selcollist COMMA */
  147521. -1, /* (360) as ::= ID|STRING */
  147522. -1, /* (361) expr ::= term */
  147523. -1, /* (362) likeop ::= LIKE_KW|MATCH */
  147524. -1, /* (363) exprlist ::= nexprlist */
  147525. -1, /* (364) nmnum ::= plus_num */
  147526. -1, /* (365) nmnum ::= nm */
  147527. -1, /* (366) nmnum ::= ON */
  147528. -1, /* (367) nmnum ::= DELETE */
  147529. -1, /* (368) nmnum ::= DEFAULT */
  147530. -1, /* (369) plus_num ::= INTEGER|FLOAT */
  147531. 0, /* (370) foreach_clause ::= */
  147532. -3, /* (371) foreach_clause ::= FOR EACH ROW */
  147533. -1, /* (372) trnm ::= nm */
  147534. 0, /* (373) tridxby ::= */
  147535. -1, /* (374) database_kw_opt ::= DATABASE */
  147536. 0, /* (375) database_kw_opt ::= */
  147537. 0, /* (376) kwcolumn_opt ::= */
  147538. -1, /* (377) kwcolumn_opt ::= COLUMNKW */
  147539. -1, /* (378) vtabarglist ::= vtabarg */
  147540. -3, /* (379) vtabarglist ::= vtabarglist COMMA vtabarg */
  147541. -2, /* (380) vtabarg ::= vtabarg vtabargtoken */
  147542. 0, /* (381) anylist ::= */
  147543. -4, /* (382) anylist ::= anylist LP anylist RP */
  147544. -2, /* (383) anylist ::= anylist ANY */
  147545. 0, /* (384) with ::= */
  147546. };
  147547. static void yy_accept(yyParser*); /* Forward Declaration */
  147548. /*
  147549. ** Perform a reduce action and the shift that must immediately
  147550. ** follow the reduce.
  147551. **
  147552. ** The yyLookahead and yyLookaheadToken parameters provide reduce actions
  147553. ** access to the lookahead token (if any). The yyLookahead will be YYNOCODE
  147554. ** if the lookahead token has already been consumed. As this procedure is
  147555. ** only called from one place, optimizing compilers will in-line it, which
  147556. ** means that the extra parameters have no performance impact.
  147557. */
  147558. static YYACTIONTYPE yy_reduce(
  147559. yyParser *yypParser, /* The parser */
  147560. unsigned int yyruleno, /* Number of the rule by which to reduce */
  147561. int yyLookahead, /* Lookahead token, or YYNOCODE if none */
  147562. sqlite3ParserTOKENTYPE yyLookaheadToken /* Value of the lookahead token */
  147563. sqlite3ParserCTX_PDECL /* %extra_context */
  147564. ){
  147565. int yygoto; /* The next state */
  147566. YYACTIONTYPE yyact; /* The next action */
  147567. yyStackEntry *yymsp; /* The top of the parser's stack */
  147568. int yysize; /* Amount to pop the stack */
  147569. sqlite3ParserARG_FETCH
  147570. (void)yyLookahead;
  147571. (void)yyLookaheadToken;
  147572. yymsp = yypParser->yytos;
  147573. #ifndef NDEBUG
  147574. if( yyTraceFILE && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
  147575. yysize = yyRuleInfoNRhs[yyruleno];
  147576. if( yysize ){
  147577. fprintf(yyTraceFILE, "%sReduce %d [%s]%s, pop back to state %d.\n",
  147578. yyTracePrompt,
  147579. yyruleno, yyRuleName[yyruleno],
  147580. yyruleno<YYNRULE_WITH_ACTION ? "" : " without external action",
  147581. yymsp[yysize].stateno);
  147582. }else{
  147583. fprintf(yyTraceFILE, "%sReduce %d [%s]%s.\n",
  147584. yyTracePrompt, yyruleno, yyRuleName[yyruleno],
  147585. yyruleno<YYNRULE_WITH_ACTION ? "" : " without external action");
  147586. }
  147587. }
  147588. #endif /* NDEBUG */
  147589. /* Check that the stack is large enough to grow by a single entry
  147590. ** if the RHS of the rule is empty. This ensures that there is room
  147591. ** enough on the stack to push the LHS value */
  147592. if( yyRuleInfoNRhs[yyruleno]==0 ){
  147593. #ifdef YYTRACKMAXSTACKDEPTH
  147594. if( (int)(yypParser->yytos - yypParser->yystack)>yypParser->yyhwm ){
  147595. yypParser->yyhwm++;
  147596. assert( yypParser->yyhwm == (int)(yypParser->yytos - yypParser->yystack));
  147597. }
  147598. #endif
  147599. #if YYSTACKDEPTH>0
  147600. if( yypParser->yytos>=yypParser->yystackEnd ){
  147601. yyStackOverflow(yypParser);
  147602. /* The call to yyStackOverflow() above pops the stack until it is
  147603. ** empty, causing the main parser loop to exit. So the return value
  147604. ** is never used and does not matter. */
  147605. return 0;
  147606. }
  147607. #else
  147608. if( yypParser->yytos>=&yypParser->yystack[yypParser->yystksz-1] ){
  147609. if( yyGrowStack(yypParser) ){
  147610. yyStackOverflow(yypParser);
  147611. /* The call to yyStackOverflow() above pops the stack until it is
  147612. ** empty, causing the main parser loop to exit. So the return value
  147613. ** is never used and does not matter. */
  147614. return 0;
  147615. }
  147616. yymsp = yypParser->yytos;
  147617. }
  147618. #endif
  147619. }
  147620. switch( yyruleno ){
  147621. /* Beginning here are the reduction cases. A typical example
  147622. ** follows:
  147623. ** case 0:
  147624. ** #line <lineno> <grammarfile>
  147625. ** { ... } // User supplied code
  147626. ** #line <lineno> <thisfile>
  147627. ** break;
  147628. */
  147629. /********** Begin reduce actions **********************************************/
  147630. YYMINORTYPE yylhsminor;
  147631. case 0: /* explain ::= EXPLAIN */
  147632. { pParse->explain = 1; }
  147633. break;
  147634. case 1: /* explain ::= EXPLAIN QUERY PLAN */
  147635. { pParse->explain = 2; }
  147636. break;
  147637. case 2: /* cmdx ::= cmd */
  147638. { sqlite3FinishCoding(pParse); }
  147639. break;
  147640. case 3: /* cmd ::= BEGIN transtype trans_opt */
  147641. {sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy192);}
  147642. break;
  147643. case 4: /* transtype ::= */
  147644. {yymsp[1].minor.yy192 = TK_DEFERRED;}
  147645. break;
  147646. case 5: /* transtype ::= DEFERRED */
  147647. case 6: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==6);
  147648. case 7: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==7);
  147649. case 306: /* range_or_rows ::= RANGE|ROWS|GROUPS */ yytestcase(yyruleno==306);
  147650. {yymsp[0].minor.yy192 = yymsp[0].major; /*A-overwrites-X*/}
  147651. break;
  147652. case 8: /* cmd ::= COMMIT|END trans_opt */
  147653. case 9: /* cmd ::= ROLLBACK trans_opt */ yytestcase(yyruleno==9);
  147654. {sqlite3EndTransaction(pParse,yymsp[-1].major);}
  147655. break;
  147656. case 10: /* cmd ::= SAVEPOINT nm */
  147657. {
  147658. sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0);
  147659. }
  147660. break;
  147661. case 11: /* cmd ::= RELEASE savepoint_opt nm */
  147662. {
  147663. sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0);
  147664. }
  147665. break;
  147666. case 12: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
  147667. {
  147668. sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0);
  147669. }
  147670. break;
  147671. case 13: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */
  147672. {
  147673. sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy192,0,0,yymsp[-2].minor.yy192);
  147674. }
  147675. break;
  147676. case 14: /* createkw ::= CREATE */
  147677. {disableLookaside(pParse);}
  147678. break;
  147679. case 15: /* ifnotexists ::= */
  147680. case 18: /* temp ::= */ yytestcase(yyruleno==18);
  147681. case 21: /* table_options ::= */ yytestcase(yyruleno==21);
  147682. case 45: /* autoinc ::= */ yytestcase(yyruleno==45);
  147683. case 60: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==60);
  147684. case 70: /* defer_subclause_opt ::= */ yytestcase(yyruleno==70);
  147685. case 79: /* ifexists ::= */ yytestcase(yyruleno==79);
  147686. case 96: /* distinct ::= */ yytestcase(yyruleno==96);
  147687. case 232: /* collate ::= */ yytestcase(yyruleno==232);
  147688. {yymsp[1].minor.yy192 = 0;}
  147689. break;
  147690. case 16: /* ifnotexists ::= IF NOT EXISTS */
  147691. {yymsp[-2].minor.yy192 = 1;}
  147692. break;
  147693. case 17: /* temp ::= TEMP */
  147694. case 46: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==46);
  147695. {yymsp[0].minor.yy192 = 1;}
  147696. break;
  147697. case 19: /* create_table_args ::= LP columnlist conslist_opt RP table_options */
  147698. {
  147699. sqlite3EndTable(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,yymsp[0].minor.yy192,0);
  147700. }
  147701. break;
  147702. case 20: /* create_table_args ::= AS select */
  147703. {
  147704. sqlite3EndTable(pParse,0,0,0,yymsp[0].minor.yy539);
  147705. sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy539);
  147706. }
  147707. break;
  147708. case 22: /* table_options ::= WITHOUT nm */
  147709. {
  147710. if( yymsp[0].minor.yy0.n==5 && sqlite3_strnicmp(yymsp[0].minor.yy0.z,"rowid",5)==0 ){
  147711. yymsp[-1].minor.yy192 = TF_WithoutRowid | TF_NoVisibleRowid;
  147712. }else{
  147713. yymsp[-1].minor.yy192 = 0;
  147714. sqlite3ErrorMsg(pParse, "unknown table option: %.*s", yymsp[0].minor.yy0.n, yymsp[0].minor.yy0.z);
  147715. }
  147716. }
  147717. break;
  147718. case 23: /* columnname ::= nm typetoken */
  147719. {sqlite3AddColumn(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
  147720. break;
  147721. case 24: /* typetoken ::= */
  147722. case 63: /* conslist_opt ::= */ yytestcase(yyruleno==63);
  147723. case 102: /* as ::= */ yytestcase(yyruleno==102);
  147724. {yymsp[1].minor.yy0.n = 0; yymsp[1].minor.yy0.z = 0;}
  147725. break;
  147726. case 25: /* typetoken ::= typename LP signed RP */
  147727. {
  147728. yymsp[-3].minor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z);
  147729. }
  147730. break;
  147731. case 26: /* typetoken ::= typename LP signed COMMA signed RP */
  147732. {
  147733. yymsp[-5].minor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z);
  147734. }
  147735. break;
  147736. case 27: /* typename ::= typename ID|STRING */
  147737. {yymsp[-1].minor.yy0.n=yymsp[0].minor.yy0.n+(int)(yymsp[0].minor.yy0.z-yymsp[-1].minor.yy0.z);}
  147738. break;
  147739. case 28: /* scanpt ::= */
  147740. {
  147741. assert( yyLookahead!=YYNOCODE );
  147742. yymsp[1].minor.yy436 = yyLookaheadToken.z;
  147743. }
  147744. break;
  147745. case 29: /* scantok ::= */
  147746. {
  147747. assert( yyLookahead!=YYNOCODE );
  147748. yymsp[1].minor.yy0 = yyLookaheadToken;
  147749. }
  147750. break;
  147751. case 30: /* ccons ::= CONSTRAINT nm */
  147752. case 65: /* tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==65);
  147753. {pParse->constraintName = yymsp[0].minor.yy0;}
  147754. break;
  147755. case 31: /* ccons ::= DEFAULT scantok term */
  147756. {sqlite3AddDefaultValue(pParse,yymsp[0].minor.yy202,yymsp[-1].minor.yy0.z,&yymsp[-1].minor.yy0.z[yymsp[-1].minor.yy0.n]);}
  147757. break;
  147758. case 32: /* ccons ::= DEFAULT LP expr RP */
  147759. {sqlite3AddDefaultValue(pParse,yymsp[-1].minor.yy202,yymsp[-2].minor.yy0.z+1,yymsp[0].minor.yy0.z);}
  147760. break;
  147761. case 33: /* ccons ::= DEFAULT PLUS scantok term */
  147762. {sqlite3AddDefaultValue(pParse,yymsp[0].minor.yy202,yymsp[-2].minor.yy0.z,&yymsp[-1].minor.yy0.z[yymsp[-1].minor.yy0.n]);}
  147763. break;
  147764. case 34: /* ccons ::= DEFAULT MINUS scantok term */
  147765. {
  147766. Expr *p = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy202, 0);
  147767. sqlite3AddDefaultValue(pParse,p,yymsp[-2].minor.yy0.z,&yymsp[-1].minor.yy0.z[yymsp[-1].minor.yy0.n]);
  147768. }
  147769. break;
  147770. case 35: /* ccons ::= DEFAULT scantok ID|INDEXED */
  147771. {
  147772. Expr *p = tokenExpr(pParse, TK_STRING, yymsp[0].minor.yy0);
  147773. if( p ){
  147774. sqlite3ExprIdToTrueFalse(p);
  147775. testcase( p->op==TK_TRUEFALSE && sqlite3ExprTruthValue(p) );
  147776. }
  147777. sqlite3AddDefaultValue(pParse,p,yymsp[0].minor.yy0.z,yymsp[0].minor.yy0.z+yymsp[0].minor.yy0.n);
  147778. }
  147779. break;
  147780. case 36: /* ccons ::= NOT NULL onconf */
  147781. {sqlite3AddNotNull(pParse, yymsp[0].minor.yy192);}
  147782. break;
  147783. case 37: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
  147784. {sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy192,yymsp[0].minor.yy192,yymsp[-2].minor.yy192);}
  147785. break;
  147786. case 38: /* ccons ::= UNIQUE onconf */
  147787. {sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy192,0,0,0,0,
  147788. SQLITE_IDXTYPE_UNIQUE);}
  147789. break;
  147790. case 39: /* ccons ::= CHECK LP expr RP */
  147791. {sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy202);}
  147792. break;
  147793. case 40: /* ccons ::= REFERENCES nm eidlist_opt refargs */
  147794. {sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy242,yymsp[0].minor.yy192);}
  147795. break;
  147796. case 41: /* ccons ::= defer_subclause */
  147797. {sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy192);}
  147798. break;
  147799. case 42: /* ccons ::= COLLATE ID|STRING */
  147800. {sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
  147801. break;
  147802. case 43: /* generated ::= LP expr RP */
  147803. {sqlite3AddGenerated(pParse,yymsp[-1].minor.yy202,0);}
  147804. break;
  147805. case 44: /* generated ::= LP expr RP ID */
  147806. {sqlite3AddGenerated(pParse,yymsp[-2].minor.yy202,&yymsp[0].minor.yy0);}
  147807. break;
  147808. case 47: /* refargs ::= */
  147809. { yymsp[1].minor.yy192 = OE_None*0x0101; /* EV: R-19803-45884 */}
  147810. break;
  147811. case 48: /* refargs ::= refargs refarg */
  147812. { yymsp[-1].minor.yy192 = (yymsp[-1].minor.yy192 & ~yymsp[0].minor.yy207.mask) | yymsp[0].minor.yy207.value; }
  147813. break;
  147814. case 49: /* refarg ::= MATCH nm */
  147815. { yymsp[-1].minor.yy207.value = 0; yymsp[-1].minor.yy207.mask = 0x000000; }
  147816. break;
  147817. case 50: /* refarg ::= ON INSERT refact */
  147818. { yymsp[-2].minor.yy207.value = 0; yymsp[-2].minor.yy207.mask = 0x000000; }
  147819. break;
  147820. case 51: /* refarg ::= ON DELETE refact */
  147821. { yymsp[-2].minor.yy207.value = yymsp[0].minor.yy192; yymsp[-2].minor.yy207.mask = 0x0000ff; }
  147822. break;
  147823. case 52: /* refarg ::= ON UPDATE refact */
  147824. { yymsp[-2].minor.yy207.value = yymsp[0].minor.yy192<<8; yymsp[-2].minor.yy207.mask = 0x00ff00; }
  147825. break;
  147826. case 53: /* refact ::= SET NULL */
  147827. { yymsp[-1].minor.yy192 = OE_SetNull; /* EV: R-33326-45252 */}
  147828. break;
  147829. case 54: /* refact ::= SET DEFAULT */
  147830. { yymsp[-1].minor.yy192 = OE_SetDflt; /* EV: R-33326-45252 */}
  147831. break;
  147832. case 55: /* refact ::= CASCADE */
  147833. { yymsp[0].minor.yy192 = OE_Cascade; /* EV: R-33326-45252 */}
  147834. break;
  147835. case 56: /* refact ::= RESTRICT */
  147836. { yymsp[0].minor.yy192 = OE_Restrict; /* EV: R-33326-45252 */}
  147837. break;
  147838. case 57: /* refact ::= NO ACTION */
  147839. { yymsp[-1].minor.yy192 = OE_None; /* EV: R-33326-45252 */}
  147840. break;
  147841. case 58: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */
  147842. {yymsp[-2].minor.yy192 = 0;}
  147843. break;
  147844. case 59: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
  147845. case 74: /* orconf ::= OR resolvetype */ yytestcase(yyruleno==74);
  147846. case 162: /* insert_cmd ::= INSERT orconf */ yytestcase(yyruleno==162);
  147847. {yymsp[-1].minor.yy192 = yymsp[0].minor.yy192;}
  147848. break;
  147849. case 61: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */
  147850. case 78: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==78);
  147851. case 204: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==204);
  147852. case 207: /* in_op ::= NOT IN */ yytestcase(yyruleno==207);
  147853. case 233: /* collate ::= COLLATE ID|STRING */ yytestcase(yyruleno==233);
  147854. {yymsp[-1].minor.yy192 = 1;}
  147855. break;
  147856. case 62: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */
  147857. {yymsp[-1].minor.yy192 = 0;}
  147858. break;
  147859. case 64: /* tconscomma ::= COMMA */
  147860. {pParse->constraintName.n = 0;}
  147861. break;
  147862. case 66: /* tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf */
  147863. {sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy242,yymsp[0].minor.yy192,yymsp[-2].minor.yy192,0);}
  147864. break;
  147865. case 67: /* tcons ::= UNIQUE LP sortlist RP onconf */
  147866. {sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy242,yymsp[0].minor.yy192,0,0,0,0,
  147867. SQLITE_IDXTYPE_UNIQUE);}
  147868. break;
  147869. case 68: /* tcons ::= CHECK LP expr RP onconf */
  147870. {sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy202);}
  147871. break;
  147872. case 69: /* tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt */
  147873. {
  147874. sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy242, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy242, yymsp[-1].minor.yy192);
  147875. sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy192);
  147876. }
  147877. break;
  147878. case 71: /* onconf ::= */
  147879. case 73: /* orconf ::= */ yytestcase(yyruleno==73);
  147880. {yymsp[1].minor.yy192 = OE_Default;}
  147881. break;
  147882. case 72: /* onconf ::= ON CONFLICT resolvetype */
  147883. {yymsp[-2].minor.yy192 = yymsp[0].minor.yy192;}
  147884. break;
  147885. case 75: /* resolvetype ::= IGNORE */
  147886. {yymsp[0].minor.yy192 = OE_Ignore;}
  147887. break;
  147888. case 76: /* resolvetype ::= REPLACE */
  147889. case 163: /* insert_cmd ::= REPLACE */ yytestcase(yyruleno==163);
  147890. {yymsp[0].minor.yy192 = OE_Replace;}
  147891. break;
  147892. case 77: /* cmd ::= DROP TABLE ifexists fullname */
  147893. {
  147894. sqlite3DropTable(pParse, yymsp[0].minor.yy47, 0, yymsp[-1].minor.yy192);
  147895. }
  147896. break;
  147897. case 80: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select */
  147898. {
  147899. sqlite3CreateView(pParse, &yymsp[-8].minor.yy0, &yymsp[-4].minor.yy0, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy242, yymsp[0].minor.yy539, yymsp[-7].minor.yy192, yymsp[-5].minor.yy192);
  147900. }
  147901. break;
  147902. case 81: /* cmd ::= DROP VIEW ifexists fullname */
  147903. {
  147904. sqlite3DropTable(pParse, yymsp[0].minor.yy47, 1, yymsp[-1].minor.yy192);
  147905. }
  147906. break;
  147907. case 82: /* cmd ::= select */
  147908. {
  147909. SelectDest dest = {SRT_Output, 0, 0, 0, 0, 0};
  147910. sqlite3Select(pParse, yymsp[0].minor.yy539, &dest);
  147911. sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy539);
  147912. }
  147913. break;
  147914. case 83: /* select ::= WITH wqlist selectnowith */
  147915. {
  147916. Select *p = yymsp[0].minor.yy539;
  147917. if( p ){
  147918. p->pWith = yymsp[-1].minor.yy131;
  147919. parserDoubleLinkSelect(pParse, p);
  147920. }else{
  147921. sqlite3WithDelete(pParse->db, yymsp[-1].minor.yy131);
  147922. }
  147923. yymsp[-2].minor.yy539 = p;
  147924. }
  147925. break;
  147926. case 84: /* select ::= WITH RECURSIVE wqlist selectnowith */
  147927. {
  147928. Select *p = yymsp[0].minor.yy539;
  147929. if( p ){
  147930. p->pWith = yymsp[-1].minor.yy131;
  147931. parserDoubleLinkSelect(pParse, p);
  147932. }else{
  147933. sqlite3WithDelete(pParse->db, yymsp[-1].minor.yy131);
  147934. }
  147935. yymsp[-3].minor.yy539 = p;
  147936. }
  147937. break;
  147938. case 85: /* select ::= selectnowith */
  147939. {
  147940. Select *p = yymsp[0].minor.yy539;
  147941. if( p ){
  147942. parserDoubleLinkSelect(pParse, p);
  147943. }
  147944. yymsp[0].minor.yy539 = p; /*A-overwrites-X*/
  147945. }
  147946. break;
  147947. case 86: /* selectnowith ::= selectnowith multiselect_op oneselect */
  147948. {
  147949. Select *pRhs = yymsp[0].minor.yy539;
  147950. Select *pLhs = yymsp[-2].minor.yy539;
  147951. if( pRhs && pRhs->pPrior ){
  147952. SrcList *pFrom;
  147953. Token x;
  147954. x.n = 0;
  147955. parserDoubleLinkSelect(pParse, pRhs);
  147956. pFrom = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&x,pRhs,0,0);
  147957. pRhs = sqlite3SelectNew(pParse,0,pFrom,0,0,0,0,0,0);
  147958. }
  147959. if( pRhs ){
  147960. pRhs->op = (u8)yymsp[-1].minor.yy192;
  147961. pRhs->pPrior = pLhs;
  147962. if( ALWAYS(pLhs) ) pLhs->selFlags &= ~SF_MultiValue;
  147963. pRhs->selFlags &= ~SF_MultiValue;
  147964. if( yymsp[-1].minor.yy192!=TK_ALL ) pParse->hasCompound = 1;
  147965. }else{
  147966. sqlite3SelectDelete(pParse->db, pLhs);
  147967. }
  147968. yymsp[-2].minor.yy539 = pRhs;
  147969. }
  147970. break;
  147971. case 87: /* multiselect_op ::= UNION */
  147972. case 89: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==89);
  147973. {yymsp[0].minor.yy192 = yymsp[0].major; /*A-overwrites-OP*/}
  147974. break;
  147975. case 88: /* multiselect_op ::= UNION ALL */
  147976. {yymsp[-1].minor.yy192 = TK_ALL;}
  147977. break;
  147978. case 90: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
  147979. {
  147980. yymsp[-8].minor.yy539 = sqlite3SelectNew(pParse,yymsp[-6].minor.yy242,yymsp[-5].minor.yy47,yymsp[-4].minor.yy202,yymsp[-3].minor.yy242,yymsp[-2].minor.yy202,yymsp[-1].minor.yy242,yymsp[-7].minor.yy192,yymsp[0].minor.yy202);
  147981. }
  147982. break;
  147983. case 91: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt window_clause orderby_opt limit_opt */
  147984. {
  147985. yymsp[-9].minor.yy539 = sqlite3SelectNew(pParse,yymsp[-7].minor.yy242,yymsp[-6].minor.yy47,yymsp[-5].minor.yy202,yymsp[-4].minor.yy242,yymsp[-3].minor.yy202,yymsp[-1].minor.yy242,yymsp[-8].minor.yy192,yymsp[0].minor.yy202);
  147986. if( yymsp[-9].minor.yy539 ){
  147987. yymsp[-9].minor.yy539->pWinDefn = yymsp[-2].minor.yy303;
  147988. }else{
  147989. sqlite3WindowListDelete(pParse->db, yymsp[-2].minor.yy303);
  147990. }
  147991. }
  147992. break;
  147993. case 92: /* values ::= VALUES LP nexprlist RP */
  147994. {
  147995. yymsp[-3].minor.yy539 = sqlite3SelectNew(pParse,yymsp[-1].minor.yy242,0,0,0,0,0,SF_Values,0);
  147996. }
  147997. break;
  147998. case 93: /* values ::= values COMMA LP nexprlist RP */
  147999. {
  148000. Select *pRight, *pLeft = yymsp[-4].minor.yy539;
  148001. pRight = sqlite3SelectNew(pParse,yymsp[-1].minor.yy242,0,0,0,0,0,SF_Values|SF_MultiValue,0);
  148002. if( ALWAYS(pLeft) ) pLeft->selFlags &= ~SF_MultiValue;
  148003. if( pRight ){
  148004. pRight->op = TK_ALL;
  148005. pRight->pPrior = pLeft;
  148006. yymsp[-4].minor.yy539 = pRight;
  148007. }else{
  148008. yymsp[-4].minor.yy539 = pLeft;
  148009. }
  148010. }
  148011. break;
  148012. case 94: /* distinct ::= DISTINCT */
  148013. {yymsp[0].minor.yy192 = SF_Distinct;}
  148014. break;
  148015. case 95: /* distinct ::= ALL */
  148016. {yymsp[0].minor.yy192 = SF_All;}
  148017. break;
  148018. case 97: /* sclp ::= */
  148019. case 130: /* orderby_opt ::= */ yytestcase(yyruleno==130);
  148020. case 140: /* groupby_opt ::= */ yytestcase(yyruleno==140);
  148021. case 220: /* exprlist ::= */ yytestcase(yyruleno==220);
  148022. case 223: /* paren_exprlist ::= */ yytestcase(yyruleno==223);
  148023. case 228: /* eidlist_opt ::= */ yytestcase(yyruleno==228);
  148024. {yymsp[1].minor.yy242 = 0;}
  148025. break;
  148026. case 98: /* selcollist ::= sclp scanpt expr scanpt as */
  148027. {
  148028. yymsp[-4].minor.yy242 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy242, yymsp[-2].minor.yy202);
  148029. if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yymsp[-4].minor.yy242, &yymsp[0].minor.yy0, 1);
  148030. sqlite3ExprListSetSpan(pParse,yymsp[-4].minor.yy242,yymsp[-3].minor.yy436,yymsp[-1].minor.yy436);
  148031. }
  148032. break;
  148033. case 99: /* selcollist ::= sclp scanpt STAR */
  148034. {
  148035. Expr *p = sqlite3Expr(pParse->db, TK_ASTERISK, 0);
  148036. yymsp[-2].minor.yy242 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy242, p);
  148037. }
  148038. break;
  148039. case 100: /* selcollist ::= sclp scanpt nm DOT STAR */
  148040. {
  148041. Expr *pRight = sqlite3PExpr(pParse, TK_ASTERISK, 0, 0);
  148042. Expr *pLeft = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-2].minor.yy0, 1);
  148043. Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight);
  148044. yymsp[-4].minor.yy242 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy242, pDot);
  148045. }
  148046. break;
  148047. case 101: /* as ::= AS nm */
  148048. case 112: /* dbnm ::= DOT nm */ yytestcase(yyruleno==112);
  148049. case 244: /* plus_num ::= PLUS INTEGER|FLOAT */ yytestcase(yyruleno==244);
  148050. case 245: /* minus_num ::= MINUS INTEGER|FLOAT */ yytestcase(yyruleno==245);
  148051. {yymsp[-1].minor.yy0 = yymsp[0].minor.yy0;}
  148052. break;
  148053. case 103: /* from ::= */
  148054. {yymsp[1].minor.yy47 = sqlite3DbMallocZero(pParse->db, sizeof(*yymsp[1].minor.yy47));}
  148055. break;
  148056. case 104: /* from ::= FROM seltablist */
  148057. {
  148058. yymsp[-1].minor.yy47 = yymsp[0].minor.yy47;
  148059. sqlite3SrcListShiftJoinType(yymsp[-1].minor.yy47);
  148060. }
  148061. break;
  148062. case 105: /* stl_prefix ::= seltablist joinop */
  148063. {
  148064. if( ALWAYS(yymsp[-1].minor.yy47 && yymsp[-1].minor.yy47->nSrc>0) ) yymsp[-1].minor.yy47->a[yymsp[-1].minor.yy47->nSrc-1].fg.jointype = (u8)yymsp[0].minor.yy192;
  148065. }
  148066. break;
  148067. case 106: /* stl_prefix ::= */
  148068. {yymsp[1].minor.yy47 = 0;}
  148069. break;
  148070. case 107: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
  148071. {
  148072. yymsp[-6].minor.yy47 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy47,&yymsp[-5].minor.yy0,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,0,yymsp[-1].minor.yy202,yymsp[0].minor.yy600);
  148073. sqlite3SrcListIndexedBy(pParse, yymsp[-6].minor.yy47, &yymsp[-2].minor.yy0);
  148074. }
  148075. break;
  148076. case 108: /* seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt */
  148077. {
  148078. yymsp[-8].minor.yy47 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-8].minor.yy47,&yymsp[-7].minor.yy0,&yymsp[-6].minor.yy0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy202,yymsp[0].minor.yy600);
  148079. sqlite3SrcListFuncArgs(pParse, yymsp[-8].minor.yy47, yymsp[-4].minor.yy242);
  148080. }
  148081. break;
  148082. case 109: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
  148083. {
  148084. yymsp[-6].minor.yy47 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy47,0,0,&yymsp[-2].minor.yy0,yymsp[-4].minor.yy539,yymsp[-1].minor.yy202,yymsp[0].minor.yy600);
  148085. }
  148086. break;
  148087. case 110: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
  148088. {
  148089. if( yymsp[-6].minor.yy47==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy202==0 && yymsp[0].minor.yy600==0 ){
  148090. yymsp[-6].minor.yy47 = yymsp[-4].minor.yy47;
  148091. }else if( yymsp[-4].minor.yy47->nSrc==1 ){
  148092. yymsp[-6].minor.yy47 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy47,0,0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy202,yymsp[0].minor.yy600);
  148093. if( yymsp[-6].minor.yy47 ){
  148094. struct SrcList_item *pNew = &yymsp[-6].minor.yy47->a[yymsp[-6].minor.yy47->nSrc-1];
  148095. struct SrcList_item *pOld = yymsp[-4].minor.yy47->a;
  148096. pNew->zName = pOld->zName;
  148097. pNew->zDatabase = pOld->zDatabase;
  148098. pNew->pSelect = pOld->pSelect;
  148099. if( pOld->fg.isTabFunc ){
  148100. pNew->u1.pFuncArg = pOld->u1.pFuncArg;
  148101. pOld->u1.pFuncArg = 0;
  148102. pOld->fg.isTabFunc = 0;
  148103. pNew->fg.isTabFunc = 1;
  148104. }
  148105. pOld->zName = pOld->zDatabase = 0;
  148106. pOld->pSelect = 0;
  148107. }
  148108. sqlite3SrcListDelete(pParse->db, yymsp[-4].minor.yy47);
  148109. }else{
  148110. Select *pSubquery;
  148111. sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy47);
  148112. pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy47,0,0,0,0,SF_NestedFrom,0);
  148113. yymsp[-6].minor.yy47 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy47,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy202,yymsp[0].minor.yy600);
  148114. }
  148115. }
  148116. break;
  148117. case 111: /* dbnm ::= */
  148118. case 125: /* indexed_opt ::= */ yytestcase(yyruleno==125);
  148119. {yymsp[1].minor.yy0.z=0; yymsp[1].minor.yy0.n=0;}
  148120. break;
  148121. case 113: /* fullname ::= nm */
  148122. {
  148123. yylhsminor.yy47 = sqlite3SrcListAppend(pParse,0,&yymsp[0].minor.yy0,0);
  148124. if( IN_RENAME_OBJECT && yylhsminor.yy47 ) sqlite3RenameTokenMap(pParse, yylhsminor.yy47->a[0].zName, &yymsp[0].minor.yy0);
  148125. }
  148126. yymsp[0].minor.yy47 = yylhsminor.yy47;
  148127. break;
  148128. case 114: /* fullname ::= nm DOT nm */
  148129. {
  148130. yylhsminor.yy47 = sqlite3SrcListAppend(pParse,0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);
  148131. if( IN_RENAME_OBJECT && yylhsminor.yy47 ) sqlite3RenameTokenMap(pParse, yylhsminor.yy47->a[0].zName, &yymsp[0].minor.yy0);
  148132. }
  148133. yymsp[-2].minor.yy47 = yylhsminor.yy47;
  148134. break;
  148135. case 115: /* xfullname ::= nm */
  148136. {yymsp[0].minor.yy47 = sqlite3SrcListAppend(pParse,0,&yymsp[0].minor.yy0,0); /*A-overwrites-X*/}
  148137. break;
  148138. case 116: /* xfullname ::= nm DOT nm */
  148139. {yymsp[-2].minor.yy47 = sqlite3SrcListAppend(pParse,0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/}
  148140. break;
  148141. case 117: /* xfullname ::= nm DOT nm AS nm */
  148142. {
  148143. yymsp[-4].minor.yy47 = sqlite3SrcListAppend(pParse,0,&yymsp[-4].minor.yy0,&yymsp[-2].minor.yy0); /*A-overwrites-X*/
  148144. if( yymsp[-4].minor.yy47 ) yymsp[-4].minor.yy47->a[0].zAlias = sqlite3NameFromToken(pParse->db, &yymsp[0].minor.yy0);
  148145. }
  148146. break;
  148147. case 118: /* xfullname ::= nm AS nm */
  148148. {
  148149. yymsp[-2].minor.yy47 = sqlite3SrcListAppend(pParse,0,&yymsp[-2].minor.yy0,0); /*A-overwrites-X*/
  148150. if( yymsp[-2].minor.yy47 ) yymsp[-2].minor.yy47->a[0].zAlias = sqlite3NameFromToken(pParse->db, &yymsp[0].minor.yy0);
  148151. }
  148152. break;
  148153. case 119: /* joinop ::= COMMA|JOIN */
  148154. { yymsp[0].minor.yy192 = JT_INNER; }
  148155. break;
  148156. case 120: /* joinop ::= JOIN_KW JOIN */
  148157. {yymsp[-1].minor.yy192 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); /*X-overwrites-A*/}
  148158. break;
  148159. case 121: /* joinop ::= JOIN_KW nm JOIN */
  148160. {yymsp[-2].minor.yy192 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); /*X-overwrites-A*/}
  148161. break;
  148162. case 122: /* joinop ::= JOIN_KW nm nm JOIN */
  148163. {yymsp[-3].minor.yy192 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0);/*X-overwrites-A*/}
  148164. break;
  148165. case 123: /* on_opt ::= ON expr */
  148166. case 143: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==143);
  148167. case 150: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==150);
  148168. case 216: /* case_else ::= ELSE expr */ yytestcase(yyruleno==216);
  148169. case 237: /* vinto ::= INTO expr */ yytestcase(yyruleno==237);
  148170. {yymsp[-1].minor.yy202 = yymsp[0].minor.yy202;}
  148171. break;
  148172. case 124: /* on_opt ::= */
  148173. case 142: /* having_opt ::= */ yytestcase(yyruleno==142);
  148174. case 144: /* limit_opt ::= */ yytestcase(yyruleno==144);
  148175. case 149: /* where_opt ::= */ yytestcase(yyruleno==149);
  148176. case 217: /* case_else ::= */ yytestcase(yyruleno==217);
  148177. case 219: /* case_operand ::= */ yytestcase(yyruleno==219);
  148178. case 238: /* vinto ::= */ yytestcase(yyruleno==238);
  148179. {yymsp[1].minor.yy202 = 0;}
  148180. break;
  148181. case 126: /* indexed_opt ::= INDEXED BY nm */
  148182. {yymsp[-2].minor.yy0 = yymsp[0].minor.yy0;}
  148183. break;
  148184. case 127: /* indexed_opt ::= NOT INDEXED */
  148185. {yymsp[-1].minor.yy0.z=0; yymsp[-1].minor.yy0.n=1;}
  148186. break;
  148187. case 128: /* using_opt ::= USING LP idlist RP */
  148188. {yymsp[-3].minor.yy600 = yymsp[-1].minor.yy600;}
  148189. break;
  148190. case 129: /* using_opt ::= */
  148191. case 164: /* idlist_opt ::= */ yytestcase(yyruleno==164);
  148192. {yymsp[1].minor.yy600 = 0;}
  148193. break;
  148194. case 131: /* orderby_opt ::= ORDER BY sortlist */
  148195. case 141: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==141);
  148196. {yymsp[-2].minor.yy242 = yymsp[0].minor.yy242;}
  148197. break;
  148198. case 132: /* sortlist ::= sortlist COMMA expr sortorder nulls */
  148199. {
  148200. yymsp[-4].minor.yy242 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy242,yymsp[-2].minor.yy202);
  148201. sqlite3ExprListSetSortOrder(yymsp[-4].minor.yy242,yymsp[-1].minor.yy192,yymsp[0].minor.yy192);
  148202. }
  148203. break;
  148204. case 133: /* sortlist ::= expr sortorder nulls */
  148205. {
  148206. yymsp[-2].minor.yy242 = sqlite3ExprListAppend(pParse,0,yymsp[-2].minor.yy202); /*A-overwrites-Y*/
  148207. sqlite3ExprListSetSortOrder(yymsp[-2].minor.yy242,yymsp[-1].minor.yy192,yymsp[0].minor.yy192);
  148208. }
  148209. break;
  148210. case 134: /* sortorder ::= ASC */
  148211. {yymsp[0].minor.yy192 = SQLITE_SO_ASC;}
  148212. break;
  148213. case 135: /* sortorder ::= DESC */
  148214. {yymsp[0].minor.yy192 = SQLITE_SO_DESC;}
  148215. break;
  148216. case 136: /* sortorder ::= */
  148217. case 139: /* nulls ::= */ yytestcase(yyruleno==139);
  148218. {yymsp[1].minor.yy192 = SQLITE_SO_UNDEFINED;}
  148219. break;
  148220. case 137: /* nulls ::= NULLS FIRST */
  148221. {yymsp[-1].minor.yy192 = SQLITE_SO_ASC;}
  148222. break;
  148223. case 138: /* nulls ::= NULLS LAST */
  148224. {yymsp[-1].minor.yy192 = SQLITE_SO_DESC;}
  148225. break;
  148226. case 145: /* limit_opt ::= LIMIT expr */
  148227. {yymsp[-1].minor.yy202 = sqlite3PExpr(pParse,TK_LIMIT,yymsp[0].minor.yy202,0);}
  148228. break;
  148229. case 146: /* limit_opt ::= LIMIT expr OFFSET expr */
  148230. {yymsp[-3].minor.yy202 = sqlite3PExpr(pParse,TK_LIMIT,yymsp[-2].minor.yy202,yymsp[0].minor.yy202);}
  148231. break;
  148232. case 147: /* limit_opt ::= LIMIT expr COMMA expr */
  148233. {yymsp[-3].minor.yy202 = sqlite3PExpr(pParse,TK_LIMIT,yymsp[0].minor.yy202,yymsp[-2].minor.yy202);}
  148234. break;
  148235. case 148: /* cmd ::= with DELETE FROM xfullname indexed_opt where_opt */
  148236. {
  148237. sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy47, &yymsp[-1].minor.yy0);
  148238. sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy47,yymsp[0].minor.yy202,0,0);
  148239. }
  148240. break;
  148241. case 151: /* cmd ::= with UPDATE orconf xfullname indexed_opt SET setlist where_opt */
  148242. {
  148243. sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy47, &yymsp[-3].minor.yy0);
  148244. sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy242,"set list");
  148245. sqlite3Update(pParse,yymsp[-4].minor.yy47,yymsp[-1].minor.yy242,yymsp[0].minor.yy202,yymsp[-5].minor.yy192,0,0,0);
  148246. }
  148247. break;
  148248. case 152: /* setlist ::= setlist COMMA nm EQ expr */
  148249. {
  148250. yymsp[-4].minor.yy242 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy242, yymsp[0].minor.yy202);
  148251. sqlite3ExprListSetName(pParse, yymsp[-4].minor.yy242, &yymsp[-2].minor.yy0, 1);
  148252. }
  148253. break;
  148254. case 153: /* setlist ::= setlist COMMA LP idlist RP EQ expr */
  148255. {
  148256. yymsp[-6].minor.yy242 = sqlite3ExprListAppendVector(pParse, yymsp[-6].minor.yy242, yymsp[-3].minor.yy600, yymsp[0].minor.yy202);
  148257. }
  148258. break;
  148259. case 154: /* setlist ::= nm EQ expr */
  148260. {
  148261. yylhsminor.yy242 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy202);
  148262. sqlite3ExprListSetName(pParse, yylhsminor.yy242, &yymsp[-2].minor.yy0, 1);
  148263. }
  148264. yymsp[-2].minor.yy242 = yylhsminor.yy242;
  148265. break;
  148266. case 155: /* setlist ::= LP idlist RP EQ expr */
  148267. {
  148268. yymsp[-4].minor.yy242 = sqlite3ExprListAppendVector(pParse, 0, yymsp[-3].minor.yy600, yymsp[0].minor.yy202);
  148269. }
  148270. break;
  148271. case 156: /* cmd ::= with insert_cmd INTO xfullname idlist_opt select upsert */
  148272. {
  148273. sqlite3Insert(pParse, yymsp[-3].minor.yy47, yymsp[-1].minor.yy539, yymsp[-2].minor.yy600, yymsp[-5].minor.yy192, yymsp[0].minor.yy318);
  148274. }
  148275. break;
  148276. case 157: /* cmd ::= with insert_cmd INTO xfullname idlist_opt DEFAULT VALUES */
  148277. {
  148278. sqlite3Insert(pParse, yymsp[-3].minor.yy47, 0, yymsp[-2].minor.yy600, yymsp[-5].minor.yy192, 0);
  148279. }
  148280. break;
  148281. case 158: /* upsert ::= */
  148282. { yymsp[1].minor.yy318 = 0; }
  148283. break;
  148284. case 159: /* upsert ::= ON CONFLICT LP sortlist RP where_opt DO UPDATE SET setlist where_opt */
  148285. { yymsp[-10].minor.yy318 = sqlite3UpsertNew(pParse->db,yymsp[-7].minor.yy242,yymsp[-5].minor.yy202,yymsp[-1].minor.yy242,yymsp[0].minor.yy202);}
  148286. break;
  148287. case 160: /* upsert ::= ON CONFLICT LP sortlist RP where_opt DO NOTHING */
  148288. { yymsp[-7].minor.yy318 = sqlite3UpsertNew(pParse->db,yymsp[-4].minor.yy242,yymsp[-2].minor.yy202,0,0); }
  148289. break;
  148290. case 161: /* upsert ::= ON CONFLICT DO NOTHING */
  148291. { yymsp[-3].minor.yy318 = sqlite3UpsertNew(pParse->db,0,0,0,0); }
  148292. break;
  148293. case 165: /* idlist_opt ::= LP idlist RP */
  148294. {yymsp[-2].minor.yy600 = yymsp[-1].minor.yy600;}
  148295. break;
  148296. case 166: /* idlist ::= idlist COMMA nm */
  148297. {yymsp[-2].minor.yy600 = sqlite3IdListAppend(pParse,yymsp[-2].minor.yy600,&yymsp[0].minor.yy0);}
  148298. break;
  148299. case 167: /* idlist ::= nm */
  148300. {yymsp[0].minor.yy600 = sqlite3IdListAppend(pParse,0,&yymsp[0].minor.yy0); /*A-overwrites-Y*/}
  148301. break;
  148302. case 168: /* expr ::= LP expr RP */
  148303. {yymsp[-2].minor.yy202 = yymsp[-1].minor.yy202;}
  148304. break;
  148305. case 169: /* expr ::= ID|INDEXED */
  148306. case 170: /* expr ::= JOIN_KW */ yytestcase(yyruleno==170);
  148307. {yymsp[0].minor.yy202=tokenExpr(pParse,TK_ID,yymsp[0].minor.yy0); /*A-overwrites-X*/}
  148308. break;
  148309. case 171: /* expr ::= nm DOT nm */
  148310. {
  148311. Expr *temp1 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-2].minor.yy0, 1);
  148312. Expr *temp2 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[0].minor.yy0, 1);
  148313. if( IN_RENAME_OBJECT ){
  148314. sqlite3RenameTokenMap(pParse, (void*)temp2, &yymsp[0].minor.yy0);
  148315. sqlite3RenameTokenMap(pParse, (void*)temp1, &yymsp[-2].minor.yy0);
  148316. }
  148317. yylhsminor.yy202 = sqlite3PExpr(pParse, TK_DOT, temp1, temp2);
  148318. }
  148319. yymsp[-2].minor.yy202 = yylhsminor.yy202;
  148320. break;
  148321. case 172: /* expr ::= nm DOT nm DOT nm */
  148322. {
  148323. Expr *temp1 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-4].minor.yy0, 1);
  148324. Expr *temp2 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[-2].minor.yy0, 1);
  148325. Expr *temp3 = sqlite3ExprAlloc(pParse->db, TK_ID, &yymsp[0].minor.yy0, 1);
  148326. Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3);
  148327. if( IN_RENAME_OBJECT ){
  148328. sqlite3RenameTokenMap(pParse, (void*)temp3, &yymsp[0].minor.yy0);
  148329. sqlite3RenameTokenMap(pParse, (void*)temp2, &yymsp[-2].minor.yy0);
  148330. }
  148331. yylhsminor.yy202 = sqlite3PExpr(pParse, TK_DOT, temp1, temp4);
  148332. }
  148333. yymsp[-4].minor.yy202 = yylhsminor.yy202;
  148334. break;
  148335. case 173: /* term ::= NULL|FLOAT|BLOB */
  148336. case 174: /* term ::= STRING */ yytestcase(yyruleno==174);
  148337. {yymsp[0].minor.yy202=tokenExpr(pParse,yymsp[0].major,yymsp[0].minor.yy0); /*A-overwrites-X*/}
  148338. break;
  148339. case 175: /* term ::= INTEGER */
  148340. {
  148341. yylhsminor.yy202 = sqlite3ExprAlloc(pParse->db, TK_INTEGER, &yymsp[0].minor.yy0, 1);
  148342. }
  148343. yymsp[0].minor.yy202 = yylhsminor.yy202;
  148344. break;
  148345. case 176: /* expr ::= VARIABLE */
  148346. {
  148347. if( !(yymsp[0].minor.yy0.z[0]=='#' && sqlite3Isdigit(yymsp[0].minor.yy0.z[1])) ){
  148348. u32 n = yymsp[0].minor.yy0.n;
  148349. yymsp[0].minor.yy202 = tokenExpr(pParse, TK_VARIABLE, yymsp[0].minor.yy0);
  148350. sqlite3ExprAssignVarNumber(pParse, yymsp[0].minor.yy202, n);
  148351. }else{
  148352. /* When doing a nested parse, one can include terms in an expression
  148353. ** that look like this: #1 #2 ... These terms refer to registers
  148354. ** in the virtual machine. #N is the N-th register. */
  148355. Token t = yymsp[0].minor.yy0; /*A-overwrites-X*/
  148356. assert( t.n>=2 );
  148357. if( pParse->nested==0 ){
  148358. sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &t);
  148359. yymsp[0].minor.yy202 = 0;
  148360. }else{
  148361. yymsp[0].minor.yy202 = sqlite3PExpr(pParse, TK_REGISTER, 0, 0);
  148362. if( yymsp[0].minor.yy202 ) sqlite3GetInt32(&t.z[1], &yymsp[0].minor.yy202->iTable);
  148363. }
  148364. }
  148365. }
  148366. break;
  148367. case 177: /* expr ::= expr COLLATE ID|STRING */
  148368. {
  148369. yymsp[-2].minor.yy202 = sqlite3ExprAddCollateToken(pParse, yymsp[-2].minor.yy202, &yymsp[0].minor.yy0, 1);
  148370. }
  148371. break;
  148372. case 178: /* expr ::= CAST LP expr AS typetoken RP */
  148373. {
  148374. yymsp[-5].minor.yy202 = sqlite3ExprAlloc(pParse->db, TK_CAST, &yymsp[-1].minor.yy0, 1);
  148375. sqlite3ExprAttachSubtrees(pParse->db, yymsp[-5].minor.yy202, yymsp[-3].minor.yy202, 0);
  148376. }
  148377. break;
  148378. case 179: /* expr ::= ID|INDEXED LP distinct exprlist RP */
  148379. {
  148380. yylhsminor.yy202 = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy242, &yymsp[-4].minor.yy0, yymsp[-2].minor.yy192);
  148381. }
  148382. yymsp[-4].minor.yy202 = yylhsminor.yy202;
  148383. break;
  148384. case 180: /* expr ::= ID|INDEXED LP STAR RP */
  148385. {
  148386. yylhsminor.yy202 = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0, 0);
  148387. }
  148388. yymsp[-3].minor.yy202 = yylhsminor.yy202;
  148389. break;
  148390. case 181: /* expr ::= ID|INDEXED LP distinct exprlist RP filter_over */
  148391. {
  148392. yylhsminor.yy202 = sqlite3ExprFunction(pParse, yymsp[-2].minor.yy242, &yymsp[-5].minor.yy0, yymsp[-3].minor.yy192);
  148393. sqlite3WindowAttach(pParse, yylhsminor.yy202, yymsp[0].minor.yy303);
  148394. }
  148395. yymsp[-5].minor.yy202 = yylhsminor.yy202;
  148396. break;
  148397. case 182: /* expr ::= ID|INDEXED LP STAR RP filter_over */
  148398. {
  148399. yylhsminor.yy202 = sqlite3ExprFunction(pParse, 0, &yymsp[-4].minor.yy0, 0);
  148400. sqlite3WindowAttach(pParse, yylhsminor.yy202, yymsp[0].minor.yy303);
  148401. }
  148402. yymsp[-4].minor.yy202 = yylhsminor.yy202;
  148403. break;
  148404. case 183: /* term ::= CTIME_KW */
  148405. {
  148406. yylhsminor.yy202 = sqlite3ExprFunction(pParse, 0, &yymsp[0].minor.yy0, 0);
  148407. }
  148408. yymsp[0].minor.yy202 = yylhsminor.yy202;
  148409. break;
  148410. case 184: /* expr ::= LP nexprlist COMMA expr RP */
  148411. {
  148412. ExprList *pList = sqlite3ExprListAppend(pParse, yymsp[-3].minor.yy242, yymsp[-1].minor.yy202);
  148413. yymsp[-4].minor.yy202 = sqlite3PExpr(pParse, TK_VECTOR, 0, 0);
  148414. if( yymsp[-4].minor.yy202 ){
  148415. yymsp[-4].minor.yy202->x.pList = pList;
  148416. if( ALWAYS(pList->nExpr) ){
  148417. yymsp[-4].minor.yy202->flags |= pList->a[0].pExpr->flags & EP_Propagate;
  148418. }
  148419. }else{
  148420. sqlite3ExprListDelete(pParse->db, pList);
  148421. }
  148422. }
  148423. break;
  148424. case 185: /* expr ::= expr AND expr */
  148425. {yymsp[-2].minor.yy202=sqlite3ExprAnd(pParse,yymsp[-2].minor.yy202,yymsp[0].minor.yy202);}
  148426. break;
  148427. case 186: /* expr ::= expr OR expr */
  148428. case 187: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==187);
  148429. case 188: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==188);
  148430. case 189: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==189);
  148431. case 190: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==190);
  148432. case 191: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==191);
  148433. case 192: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==192);
  148434. {yymsp[-2].minor.yy202=sqlite3PExpr(pParse,yymsp[-1].major,yymsp[-2].minor.yy202,yymsp[0].minor.yy202);}
  148435. break;
  148436. case 193: /* likeop ::= NOT LIKE_KW|MATCH */
  148437. {yymsp[-1].minor.yy0=yymsp[0].minor.yy0; yymsp[-1].minor.yy0.n|=0x80000000; /*yymsp[-1].minor.yy0-overwrite-yymsp[0].minor.yy0*/}
  148438. break;
  148439. case 194: /* expr ::= expr likeop expr */
  148440. {
  148441. ExprList *pList;
  148442. int bNot = yymsp[-1].minor.yy0.n & 0x80000000;
  148443. yymsp[-1].minor.yy0.n &= 0x7fffffff;
  148444. pList = sqlite3ExprListAppend(pParse,0, yymsp[0].minor.yy202);
  148445. pList = sqlite3ExprListAppend(pParse,pList, yymsp[-2].minor.yy202);
  148446. yymsp[-2].minor.yy202 = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy0, 0);
  148447. if( bNot ) yymsp[-2].minor.yy202 = sqlite3PExpr(pParse, TK_NOT, yymsp[-2].minor.yy202, 0);
  148448. if( yymsp[-2].minor.yy202 ) yymsp[-2].minor.yy202->flags |= EP_InfixFunc;
  148449. }
  148450. break;
  148451. case 195: /* expr ::= expr likeop expr ESCAPE expr */
  148452. {
  148453. ExprList *pList;
  148454. int bNot = yymsp[-3].minor.yy0.n & 0x80000000;
  148455. yymsp[-3].minor.yy0.n &= 0x7fffffff;
  148456. pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy202);
  148457. pList = sqlite3ExprListAppend(pParse,pList, yymsp[-4].minor.yy202);
  148458. pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy202);
  148459. yymsp[-4].minor.yy202 = sqlite3ExprFunction(pParse, pList, &yymsp[-3].minor.yy0, 0);
  148460. if( bNot ) yymsp[-4].minor.yy202 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy202, 0);
  148461. if( yymsp[-4].minor.yy202 ) yymsp[-4].minor.yy202->flags |= EP_InfixFunc;
  148462. }
  148463. break;
  148464. case 196: /* expr ::= expr ISNULL|NOTNULL */
  148465. {yymsp[-1].minor.yy202 = sqlite3PExpr(pParse,yymsp[0].major,yymsp[-1].minor.yy202,0);}
  148466. break;
  148467. case 197: /* expr ::= expr NOT NULL */
  148468. {yymsp[-2].minor.yy202 = sqlite3PExpr(pParse,TK_NOTNULL,yymsp[-2].minor.yy202,0);}
  148469. break;
  148470. case 198: /* expr ::= expr IS expr */
  148471. {
  148472. yymsp[-2].minor.yy202 = sqlite3PExpr(pParse,TK_IS,yymsp[-2].minor.yy202,yymsp[0].minor.yy202);
  148473. binaryToUnaryIfNull(pParse, yymsp[0].minor.yy202, yymsp[-2].minor.yy202, TK_ISNULL);
  148474. }
  148475. break;
  148476. case 199: /* expr ::= expr IS NOT expr */
  148477. {
  148478. yymsp[-3].minor.yy202 = sqlite3PExpr(pParse,TK_ISNOT,yymsp[-3].minor.yy202,yymsp[0].minor.yy202);
  148479. binaryToUnaryIfNull(pParse, yymsp[0].minor.yy202, yymsp[-3].minor.yy202, TK_NOTNULL);
  148480. }
  148481. break;
  148482. case 200: /* expr ::= NOT expr */
  148483. case 201: /* expr ::= BITNOT expr */ yytestcase(yyruleno==201);
  148484. {yymsp[-1].minor.yy202 = sqlite3PExpr(pParse, yymsp[-1].major, yymsp[0].minor.yy202, 0);/*A-overwrites-B*/}
  148485. break;
  148486. case 202: /* expr ::= PLUS|MINUS expr */
  148487. {
  148488. yymsp[-1].minor.yy202 = sqlite3PExpr(pParse, yymsp[-1].major==TK_PLUS ? TK_UPLUS : TK_UMINUS, yymsp[0].minor.yy202, 0);
  148489. /*A-overwrites-B*/
  148490. }
  148491. break;
  148492. case 203: /* between_op ::= BETWEEN */
  148493. case 206: /* in_op ::= IN */ yytestcase(yyruleno==206);
  148494. {yymsp[0].minor.yy192 = 0;}
  148495. break;
  148496. case 205: /* expr ::= expr between_op expr AND expr */
  148497. {
  148498. ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy202);
  148499. pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy202);
  148500. yymsp[-4].minor.yy202 = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy202, 0);
  148501. if( yymsp[-4].minor.yy202 ){
  148502. yymsp[-4].minor.yy202->x.pList = pList;
  148503. }else{
  148504. sqlite3ExprListDelete(pParse->db, pList);
  148505. }
  148506. if( yymsp[-3].minor.yy192 ) yymsp[-4].minor.yy202 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy202, 0);
  148507. }
  148508. break;
  148509. case 208: /* expr ::= expr in_op LP exprlist RP */
  148510. {
  148511. if( yymsp[-1].minor.yy242==0 ){
  148512. /* Expressions of the form
  148513. **
  148514. ** expr1 IN ()
  148515. ** expr1 NOT IN ()
  148516. **
  148517. ** simplify to constants 0 (false) and 1 (true), respectively,
  148518. ** regardless of the value of expr1.
  148519. */
  148520. sqlite3ExprUnmapAndDelete(pParse, yymsp[-4].minor.yy202);
  148521. yymsp[-4].minor.yy202 = sqlite3Expr(pParse->db, TK_INTEGER, yymsp[-3].minor.yy192 ? "1" : "0");
  148522. }else if( yymsp[-1].minor.yy242->nExpr==1 && sqlite3ExprIsConstant(yymsp[-1].minor.yy242->a[0].pExpr) ){
  148523. Expr *pRHS = yymsp[-1].minor.yy242->a[0].pExpr;
  148524. yymsp[-1].minor.yy242->a[0].pExpr = 0;
  148525. sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy242);
  148526. pRHS = sqlite3PExpr(pParse, TK_UPLUS, pRHS, 0);
  148527. yymsp[-4].minor.yy202 = sqlite3PExpr(pParse, TK_EQ, yymsp[-4].minor.yy202, pRHS);
  148528. if( yymsp[-3].minor.yy192 ) yymsp[-4].minor.yy202 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy202, 0);
  148529. }else{
  148530. yymsp[-4].minor.yy202 = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy202, 0);
  148531. if( yymsp[-4].minor.yy202 ){
  148532. yymsp[-4].minor.yy202->x.pList = yymsp[-1].minor.yy242;
  148533. sqlite3ExprSetHeightAndFlags(pParse, yymsp[-4].minor.yy202);
  148534. }else{
  148535. sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy242);
  148536. }
  148537. if( yymsp[-3].minor.yy192 ) yymsp[-4].minor.yy202 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy202, 0);
  148538. }
  148539. }
  148540. break;
  148541. case 209: /* expr ::= LP select RP */
  148542. {
  148543. yymsp[-2].minor.yy202 = sqlite3PExpr(pParse, TK_SELECT, 0, 0);
  148544. sqlite3PExprAddSelect(pParse, yymsp[-2].minor.yy202, yymsp[-1].minor.yy539);
  148545. }
  148546. break;
  148547. case 210: /* expr ::= expr in_op LP select RP */
  148548. {
  148549. yymsp[-4].minor.yy202 = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy202, 0);
  148550. sqlite3PExprAddSelect(pParse, yymsp[-4].minor.yy202, yymsp[-1].minor.yy539);
  148551. if( yymsp[-3].minor.yy192 ) yymsp[-4].minor.yy202 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy202, 0);
  148552. }
  148553. break;
  148554. case 211: /* expr ::= expr in_op nm dbnm paren_exprlist */
  148555. {
  148556. SrcList *pSrc = sqlite3SrcListAppend(pParse, 0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0);
  148557. Select *pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0);
  148558. if( yymsp[0].minor.yy242 ) sqlite3SrcListFuncArgs(pParse, pSelect ? pSrc : 0, yymsp[0].minor.yy242);
  148559. yymsp[-4].minor.yy202 = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy202, 0);
  148560. sqlite3PExprAddSelect(pParse, yymsp[-4].minor.yy202, pSelect);
  148561. if( yymsp[-3].minor.yy192 ) yymsp[-4].minor.yy202 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy202, 0);
  148562. }
  148563. break;
  148564. case 212: /* expr ::= EXISTS LP select RP */
  148565. {
  148566. Expr *p;
  148567. p = yymsp[-3].minor.yy202 = sqlite3PExpr(pParse, TK_EXISTS, 0, 0);
  148568. sqlite3PExprAddSelect(pParse, p, yymsp[-1].minor.yy539);
  148569. }
  148570. break;
  148571. case 213: /* expr ::= CASE case_operand case_exprlist case_else END */
  148572. {
  148573. yymsp[-4].minor.yy202 = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy202, 0);
  148574. if( yymsp[-4].minor.yy202 ){
  148575. yymsp[-4].minor.yy202->x.pList = yymsp[-1].minor.yy202 ? sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy242,yymsp[-1].minor.yy202) : yymsp[-2].minor.yy242;
  148576. sqlite3ExprSetHeightAndFlags(pParse, yymsp[-4].minor.yy202);
  148577. }else{
  148578. sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy242);
  148579. sqlite3ExprDelete(pParse->db, yymsp[-1].minor.yy202);
  148580. }
  148581. }
  148582. break;
  148583. case 214: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
  148584. {
  148585. yymsp[-4].minor.yy242 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy242, yymsp[-2].minor.yy202);
  148586. yymsp[-4].minor.yy242 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy242, yymsp[0].minor.yy202);
  148587. }
  148588. break;
  148589. case 215: /* case_exprlist ::= WHEN expr THEN expr */
  148590. {
  148591. yymsp[-3].minor.yy242 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy202);
  148592. yymsp[-3].minor.yy242 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy242, yymsp[0].minor.yy202);
  148593. }
  148594. break;
  148595. case 218: /* case_operand ::= expr */
  148596. {yymsp[0].minor.yy202 = yymsp[0].minor.yy202; /*A-overwrites-X*/}
  148597. break;
  148598. case 221: /* nexprlist ::= nexprlist COMMA expr */
  148599. {yymsp[-2].minor.yy242 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy242,yymsp[0].minor.yy202);}
  148600. break;
  148601. case 222: /* nexprlist ::= expr */
  148602. {yymsp[0].minor.yy242 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy202); /*A-overwrites-Y*/}
  148603. break;
  148604. case 224: /* paren_exprlist ::= LP exprlist RP */
  148605. case 229: /* eidlist_opt ::= LP eidlist RP */ yytestcase(yyruleno==229);
  148606. {yymsp[-2].minor.yy242 = yymsp[-1].minor.yy242;}
  148607. break;
  148608. case 225: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt */
  148609. {
  148610. sqlite3CreateIndex(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0,
  148611. sqlite3SrcListAppend(pParse,0,&yymsp[-4].minor.yy0,0), yymsp[-2].minor.yy242, yymsp[-10].minor.yy192,
  148612. &yymsp[-11].minor.yy0, yymsp[0].minor.yy202, SQLITE_SO_ASC, yymsp[-8].minor.yy192, SQLITE_IDXTYPE_APPDEF);
  148613. if( IN_RENAME_OBJECT && pParse->pNewIndex ){
  148614. sqlite3RenameTokenMap(pParse, pParse->pNewIndex->zName, &yymsp[-4].minor.yy0);
  148615. }
  148616. }
  148617. break;
  148618. case 226: /* uniqueflag ::= UNIQUE */
  148619. case 268: /* raisetype ::= ABORT */ yytestcase(yyruleno==268);
  148620. {yymsp[0].minor.yy192 = OE_Abort;}
  148621. break;
  148622. case 227: /* uniqueflag ::= */
  148623. {yymsp[1].minor.yy192 = OE_None;}
  148624. break;
  148625. case 230: /* eidlist ::= eidlist COMMA nm collate sortorder */
  148626. {
  148627. yymsp[-4].minor.yy242 = parserAddExprIdListTerm(pParse, yymsp[-4].minor.yy242, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy192, yymsp[0].minor.yy192);
  148628. }
  148629. break;
  148630. case 231: /* eidlist ::= nm collate sortorder */
  148631. {
  148632. yymsp[-2].minor.yy242 = parserAddExprIdListTerm(pParse, 0, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy192, yymsp[0].minor.yy192); /*A-overwrites-Y*/
  148633. }
  148634. break;
  148635. case 234: /* cmd ::= DROP INDEX ifexists fullname */
  148636. {sqlite3DropIndex(pParse, yymsp[0].minor.yy47, yymsp[-1].minor.yy192);}
  148637. break;
  148638. case 235: /* cmd ::= VACUUM vinto */
  148639. {sqlite3Vacuum(pParse,0,yymsp[0].minor.yy202);}
  148640. break;
  148641. case 236: /* cmd ::= VACUUM nm vinto */
  148642. {sqlite3Vacuum(pParse,&yymsp[-1].minor.yy0,yymsp[0].minor.yy202);}
  148643. break;
  148644. case 239: /* cmd ::= PRAGMA nm dbnm */
  148645. {sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
  148646. break;
  148647. case 240: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
  148648. {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
  148649. break;
  148650. case 241: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
  148651. {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
  148652. break;
  148653. case 242: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
  148654. {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
  148655. break;
  148656. case 243: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
  148657. {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}
  148658. break;
  148659. case 246: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
  148660. {
  148661. Token all;
  148662. all.z = yymsp[-3].minor.yy0.z;
  148663. all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
  148664. sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy447, &all);
  148665. }
  148666. break;
  148667. case 247: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
  148668. {
  148669. sqlite3BeginTrigger(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0, yymsp[-5].minor.yy192, yymsp[-4].minor.yy230.a, yymsp[-4].minor.yy230.b, yymsp[-2].minor.yy47, yymsp[0].minor.yy202, yymsp[-10].minor.yy192, yymsp[-8].minor.yy192);
  148670. yymsp[-10].minor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0); /*A-overwrites-T*/
  148671. }
  148672. break;
  148673. case 248: /* trigger_time ::= BEFORE|AFTER */
  148674. { yymsp[0].minor.yy192 = yymsp[0].major; /*A-overwrites-X*/ }
  148675. break;
  148676. case 249: /* trigger_time ::= INSTEAD OF */
  148677. { yymsp[-1].minor.yy192 = TK_INSTEAD;}
  148678. break;
  148679. case 250: /* trigger_time ::= */
  148680. { yymsp[1].minor.yy192 = TK_BEFORE; }
  148681. break;
  148682. case 251: /* trigger_event ::= DELETE|INSERT */
  148683. case 252: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==252);
  148684. {yymsp[0].minor.yy230.a = yymsp[0].major; /*A-overwrites-X*/ yymsp[0].minor.yy230.b = 0;}
  148685. break;
  148686. case 253: /* trigger_event ::= UPDATE OF idlist */
  148687. {yymsp[-2].minor.yy230.a = TK_UPDATE; yymsp[-2].minor.yy230.b = yymsp[0].minor.yy600;}
  148688. break;
  148689. case 254: /* when_clause ::= */
  148690. case 273: /* key_opt ::= */ yytestcase(yyruleno==273);
  148691. { yymsp[1].minor.yy202 = 0; }
  148692. break;
  148693. case 255: /* when_clause ::= WHEN expr */
  148694. case 274: /* key_opt ::= KEY expr */ yytestcase(yyruleno==274);
  148695. { yymsp[-1].minor.yy202 = yymsp[0].minor.yy202; }
  148696. break;
  148697. case 256: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
  148698. {
  148699. assert( yymsp[-2].minor.yy447!=0 );
  148700. yymsp[-2].minor.yy447->pLast->pNext = yymsp[-1].minor.yy447;
  148701. yymsp[-2].minor.yy447->pLast = yymsp[-1].minor.yy447;
  148702. }
  148703. break;
  148704. case 257: /* trigger_cmd_list ::= trigger_cmd SEMI */
  148705. {
  148706. assert( yymsp[-1].minor.yy447!=0 );
  148707. yymsp[-1].minor.yy447->pLast = yymsp[-1].minor.yy447;
  148708. }
  148709. break;
  148710. case 258: /* trnm ::= nm DOT nm */
  148711. {
  148712. yymsp[-2].minor.yy0 = yymsp[0].minor.yy0;
  148713. sqlite3ErrorMsg(pParse,
  148714. "qualified table names are not allowed on INSERT, UPDATE, and DELETE "
  148715. "statements within triggers");
  148716. }
  148717. break;
  148718. case 259: /* tridxby ::= INDEXED BY nm */
  148719. {
  148720. sqlite3ErrorMsg(pParse,
  148721. "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
  148722. "within triggers");
  148723. }
  148724. break;
  148725. case 260: /* tridxby ::= NOT INDEXED */
  148726. {
  148727. sqlite3ErrorMsg(pParse,
  148728. "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
  148729. "within triggers");
  148730. }
  148731. break;
  148732. case 261: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt scanpt */
  148733. {yylhsminor.yy447 = sqlite3TriggerUpdateStep(pParse, &yymsp[-5].minor.yy0, yymsp[-2].minor.yy242, yymsp[-1].minor.yy202, yymsp[-6].minor.yy192, yymsp[-7].minor.yy0.z, yymsp[0].minor.yy436);}
  148734. yymsp[-7].minor.yy447 = yylhsminor.yy447;
  148735. break;
  148736. case 262: /* trigger_cmd ::= scanpt insert_cmd INTO trnm idlist_opt select upsert scanpt */
  148737. {
  148738. yylhsminor.yy447 = sqlite3TriggerInsertStep(pParse,&yymsp[-4].minor.yy0,yymsp[-3].minor.yy600,yymsp[-2].minor.yy539,yymsp[-6].minor.yy192,yymsp[-1].minor.yy318,yymsp[-7].minor.yy436,yymsp[0].minor.yy436);/*yylhsminor.yy447-overwrites-yymsp[-6].minor.yy192*/
  148739. }
  148740. yymsp[-7].minor.yy447 = yylhsminor.yy447;
  148741. break;
  148742. case 263: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt scanpt */
  148743. {yylhsminor.yy447 = sqlite3TriggerDeleteStep(pParse, &yymsp[-3].minor.yy0, yymsp[-1].minor.yy202, yymsp[-5].minor.yy0.z, yymsp[0].minor.yy436);}
  148744. yymsp[-5].minor.yy447 = yylhsminor.yy447;
  148745. break;
  148746. case 264: /* trigger_cmd ::= scanpt select scanpt */
  148747. {yylhsminor.yy447 = sqlite3TriggerSelectStep(pParse->db, yymsp[-1].minor.yy539, yymsp[-2].minor.yy436, yymsp[0].minor.yy436); /*yylhsminor.yy447-overwrites-yymsp[-1].minor.yy539*/}
  148748. yymsp[-2].minor.yy447 = yylhsminor.yy447;
  148749. break;
  148750. case 265: /* expr ::= RAISE LP IGNORE RP */
  148751. {
  148752. yymsp[-3].minor.yy202 = sqlite3PExpr(pParse, TK_RAISE, 0, 0);
  148753. if( yymsp[-3].minor.yy202 ){
  148754. yymsp[-3].minor.yy202->affExpr = OE_Ignore;
  148755. }
  148756. }
  148757. break;
  148758. case 266: /* expr ::= RAISE LP raisetype COMMA nm RP */
  148759. {
  148760. yymsp[-5].minor.yy202 = sqlite3ExprAlloc(pParse->db, TK_RAISE, &yymsp[-1].minor.yy0, 1);
  148761. if( yymsp[-5].minor.yy202 ) {
  148762. yymsp[-5].minor.yy202->affExpr = (char)yymsp[-3].minor.yy192;
  148763. }
  148764. }
  148765. break;
  148766. case 267: /* raisetype ::= ROLLBACK */
  148767. {yymsp[0].minor.yy192 = OE_Rollback;}
  148768. break;
  148769. case 269: /* raisetype ::= FAIL */
  148770. {yymsp[0].minor.yy192 = OE_Fail;}
  148771. break;
  148772. case 270: /* cmd ::= DROP TRIGGER ifexists fullname */
  148773. {
  148774. sqlite3DropTrigger(pParse,yymsp[0].minor.yy47,yymsp[-1].minor.yy192);
  148775. }
  148776. break;
  148777. case 271: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
  148778. {
  148779. sqlite3Attach(pParse, yymsp[-3].minor.yy202, yymsp[-1].minor.yy202, yymsp[0].minor.yy202);
  148780. }
  148781. break;
  148782. case 272: /* cmd ::= DETACH database_kw_opt expr */
  148783. {
  148784. sqlite3Detach(pParse, yymsp[0].minor.yy202);
  148785. }
  148786. break;
  148787. case 275: /* cmd ::= REINDEX */
  148788. {sqlite3Reindex(pParse, 0, 0);}
  148789. break;
  148790. case 276: /* cmd ::= REINDEX nm dbnm */
  148791. {sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
  148792. break;
  148793. case 277: /* cmd ::= ANALYZE */
  148794. {sqlite3Analyze(pParse, 0, 0);}
  148795. break;
  148796. case 278: /* cmd ::= ANALYZE nm dbnm */
  148797. {sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
  148798. break;
  148799. case 279: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
  148800. {
  148801. sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy47,&yymsp[0].minor.yy0);
  148802. }
  148803. break;
  148804. case 280: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist */
  148805. {
  148806. yymsp[-1].minor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-1].minor.yy0.z) + pParse->sLastToken.n;
  148807. sqlite3AlterFinishAddColumn(pParse, &yymsp[-1].minor.yy0);
  148808. }
  148809. break;
  148810. case 281: /* add_column_fullname ::= fullname */
  148811. {
  148812. disableLookaside(pParse);
  148813. sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy47);
  148814. }
  148815. break;
  148816. case 282: /* cmd ::= ALTER TABLE fullname RENAME kwcolumn_opt nm TO nm */
  148817. {
  148818. sqlite3AlterRenameColumn(pParse, yymsp[-5].minor.yy47, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0);
  148819. }
  148820. break;
  148821. case 283: /* cmd ::= create_vtab */
  148822. {sqlite3VtabFinishParse(pParse,0);}
  148823. break;
  148824. case 284: /* cmd ::= create_vtab LP vtabarglist RP */
  148825. {sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
  148826. break;
  148827. case 285: /* create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
  148828. {
  148829. sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0, yymsp[-4].minor.yy192);
  148830. }
  148831. break;
  148832. case 286: /* vtabarg ::= */
  148833. {sqlite3VtabArgInit(pParse);}
  148834. break;
  148835. case 287: /* vtabargtoken ::= ANY */
  148836. case 288: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==288);
  148837. case 289: /* lp ::= LP */ yytestcase(yyruleno==289);
  148838. {sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
  148839. break;
  148840. case 290: /* with ::= WITH wqlist */
  148841. case 291: /* with ::= WITH RECURSIVE wqlist */ yytestcase(yyruleno==291);
  148842. { sqlite3WithPush(pParse, yymsp[0].minor.yy131, 1); }
  148843. break;
  148844. case 292: /* wqlist ::= nm eidlist_opt AS LP select RP */
  148845. {
  148846. yymsp[-5].minor.yy131 = sqlite3WithAdd(pParse, 0, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy242, yymsp[-1].minor.yy539); /*A-overwrites-X*/
  148847. }
  148848. break;
  148849. case 293: /* wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP */
  148850. {
  148851. yymsp[-7].minor.yy131 = sqlite3WithAdd(pParse, yymsp[-7].minor.yy131, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy242, yymsp[-1].minor.yy539);
  148852. }
  148853. break;
  148854. case 294: /* windowdefn_list ::= windowdefn */
  148855. { yylhsminor.yy303 = yymsp[0].minor.yy303; }
  148856. yymsp[0].minor.yy303 = yylhsminor.yy303;
  148857. break;
  148858. case 295: /* windowdefn_list ::= windowdefn_list COMMA windowdefn */
  148859. {
  148860. assert( yymsp[0].minor.yy303!=0 );
  148861. sqlite3WindowChain(pParse, yymsp[0].minor.yy303, yymsp[-2].minor.yy303);
  148862. yymsp[0].minor.yy303->pNextWin = yymsp[-2].minor.yy303;
  148863. yylhsminor.yy303 = yymsp[0].minor.yy303;
  148864. }
  148865. yymsp[-2].minor.yy303 = yylhsminor.yy303;
  148866. break;
  148867. case 296: /* windowdefn ::= nm AS LP window RP */
  148868. {
  148869. if( ALWAYS(yymsp[-1].minor.yy303) ){
  148870. yymsp[-1].minor.yy303->zName = sqlite3DbStrNDup(pParse->db, yymsp[-4].minor.yy0.z, yymsp[-4].minor.yy0.n);
  148871. }
  148872. yylhsminor.yy303 = yymsp[-1].minor.yy303;
  148873. }
  148874. yymsp[-4].minor.yy303 = yylhsminor.yy303;
  148875. break;
  148876. case 297: /* window ::= PARTITION BY nexprlist orderby_opt frame_opt */
  148877. {
  148878. yymsp[-4].minor.yy303 = sqlite3WindowAssemble(pParse, yymsp[0].minor.yy303, yymsp[-2].minor.yy242, yymsp[-1].minor.yy242, 0);
  148879. }
  148880. break;
  148881. case 298: /* window ::= nm PARTITION BY nexprlist orderby_opt frame_opt */
  148882. {
  148883. yylhsminor.yy303 = sqlite3WindowAssemble(pParse, yymsp[0].minor.yy303, yymsp[-2].minor.yy242, yymsp[-1].minor.yy242, &yymsp[-5].minor.yy0);
  148884. }
  148885. yymsp[-5].minor.yy303 = yylhsminor.yy303;
  148886. break;
  148887. case 299: /* window ::= ORDER BY sortlist frame_opt */
  148888. {
  148889. yymsp[-3].minor.yy303 = sqlite3WindowAssemble(pParse, yymsp[0].minor.yy303, 0, yymsp[-1].minor.yy242, 0);
  148890. }
  148891. break;
  148892. case 300: /* window ::= nm ORDER BY sortlist frame_opt */
  148893. {
  148894. yylhsminor.yy303 = sqlite3WindowAssemble(pParse, yymsp[0].minor.yy303, 0, yymsp[-1].minor.yy242, &yymsp[-4].minor.yy0);
  148895. }
  148896. yymsp[-4].minor.yy303 = yylhsminor.yy303;
  148897. break;
  148898. case 301: /* window ::= frame_opt */
  148899. case 320: /* filter_over ::= over_clause */ yytestcase(yyruleno==320);
  148900. {
  148901. yylhsminor.yy303 = yymsp[0].minor.yy303;
  148902. }
  148903. yymsp[0].minor.yy303 = yylhsminor.yy303;
  148904. break;
  148905. case 302: /* window ::= nm frame_opt */
  148906. {
  148907. yylhsminor.yy303 = sqlite3WindowAssemble(pParse, yymsp[0].minor.yy303, 0, 0, &yymsp[-1].minor.yy0);
  148908. }
  148909. yymsp[-1].minor.yy303 = yylhsminor.yy303;
  148910. break;
  148911. case 303: /* frame_opt ::= */
  148912. {
  148913. yymsp[1].minor.yy303 = sqlite3WindowAlloc(pParse, 0, TK_UNBOUNDED, 0, TK_CURRENT, 0, 0);
  148914. }
  148915. break;
  148916. case 304: /* frame_opt ::= range_or_rows frame_bound_s frame_exclude_opt */
  148917. {
  148918. yylhsminor.yy303 = sqlite3WindowAlloc(pParse, yymsp[-2].minor.yy192, yymsp[-1].minor.yy77.eType, yymsp[-1].minor.yy77.pExpr, TK_CURRENT, 0, yymsp[0].minor.yy58);
  148919. }
  148920. yymsp[-2].minor.yy303 = yylhsminor.yy303;
  148921. break;
  148922. case 305: /* frame_opt ::= range_or_rows BETWEEN frame_bound_s AND frame_bound_e frame_exclude_opt */
  148923. {
  148924. yylhsminor.yy303 = sqlite3WindowAlloc(pParse, yymsp[-5].minor.yy192, yymsp[-3].minor.yy77.eType, yymsp[-3].minor.yy77.pExpr, yymsp[-1].minor.yy77.eType, yymsp[-1].minor.yy77.pExpr, yymsp[0].minor.yy58);
  148925. }
  148926. yymsp[-5].minor.yy303 = yylhsminor.yy303;
  148927. break;
  148928. case 307: /* frame_bound_s ::= frame_bound */
  148929. case 309: /* frame_bound_e ::= frame_bound */ yytestcase(yyruleno==309);
  148930. {yylhsminor.yy77 = yymsp[0].minor.yy77;}
  148931. yymsp[0].minor.yy77 = yylhsminor.yy77;
  148932. break;
  148933. case 308: /* frame_bound_s ::= UNBOUNDED PRECEDING */
  148934. case 310: /* frame_bound_e ::= UNBOUNDED FOLLOWING */ yytestcase(yyruleno==310);
  148935. case 312: /* frame_bound ::= CURRENT ROW */ yytestcase(yyruleno==312);
  148936. {yylhsminor.yy77.eType = yymsp[-1].major; yylhsminor.yy77.pExpr = 0;}
  148937. yymsp[-1].minor.yy77 = yylhsminor.yy77;
  148938. break;
  148939. case 311: /* frame_bound ::= expr PRECEDING|FOLLOWING */
  148940. {yylhsminor.yy77.eType = yymsp[0].major; yylhsminor.yy77.pExpr = yymsp[-1].minor.yy202;}
  148941. yymsp[-1].minor.yy77 = yylhsminor.yy77;
  148942. break;
  148943. case 313: /* frame_exclude_opt ::= */
  148944. {yymsp[1].minor.yy58 = 0;}
  148945. break;
  148946. case 314: /* frame_exclude_opt ::= EXCLUDE frame_exclude */
  148947. {yymsp[-1].minor.yy58 = yymsp[0].minor.yy58;}
  148948. break;
  148949. case 315: /* frame_exclude ::= NO OTHERS */
  148950. case 316: /* frame_exclude ::= CURRENT ROW */ yytestcase(yyruleno==316);
  148951. {yymsp[-1].minor.yy58 = yymsp[-1].major; /*A-overwrites-X*/}
  148952. break;
  148953. case 317: /* frame_exclude ::= GROUP|TIES */
  148954. {yymsp[0].minor.yy58 = yymsp[0].major; /*A-overwrites-X*/}
  148955. break;
  148956. case 318: /* window_clause ::= WINDOW windowdefn_list */
  148957. { yymsp[-1].minor.yy303 = yymsp[0].minor.yy303; }
  148958. break;
  148959. case 319: /* filter_over ::= filter_clause over_clause */
  148960. {
  148961. yymsp[0].minor.yy303->pFilter = yymsp[-1].minor.yy202;
  148962. yylhsminor.yy303 = yymsp[0].minor.yy303;
  148963. }
  148964. yymsp[-1].minor.yy303 = yylhsminor.yy303;
  148965. break;
  148966. case 321: /* filter_over ::= filter_clause */
  148967. {
  148968. yylhsminor.yy303 = (Window*)sqlite3DbMallocZero(pParse->db, sizeof(Window));
  148969. if( yylhsminor.yy303 ){
  148970. yylhsminor.yy303->eFrmType = TK_FILTER;
  148971. yylhsminor.yy303->pFilter = yymsp[0].minor.yy202;
  148972. }else{
  148973. sqlite3ExprDelete(pParse->db, yymsp[0].minor.yy202);
  148974. }
  148975. }
  148976. yymsp[0].minor.yy303 = yylhsminor.yy303;
  148977. break;
  148978. case 322: /* over_clause ::= OVER LP window RP */
  148979. {
  148980. yymsp[-3].minor.yy303 = yymsp[-1].minor.yy303;
  148981. assert( yymsp[-3].minor.yy303!=0 );
  148982. }
  148983. break;
  148984. case 323: /* over_clause ::= OVER nm */
  148985. {
  148986. yymsp[-1].minor.yy303 = (Window*)sqlite3DbMallocZero(pParse->db, sizeof(Window));
  148987. if( yymsp[-1].minor.yy303 ){
  148988. yymsp[-1].minor.yy303->zName = sqlite3DbStrNDup(pParse->db, yymsp[0].minor.yy0.z, yymsp[0].minor.yy0.n);
  148989. }
  148990. }
  148991. break;
  148992. case 324: /* filter_clause ::= FILTER LP WHERE expr RP */
  148993. { yymsp[-4].minor.yy202 = yymsp[-1].minor.yy202; }
  148994. break;
  148995. default:
  148996. /* (325) input ::= cmdlist */ yytestcase(yyruleno==325);
  148997. /* (326) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==326);
  148998. /* (327) cmdlist ::= ecmd (OPTIMIZED OUT) */ assert(yyruleno!=327);
  148999. /* (328) ecmd ::= SEMI */ yytestcase(yyruleno==328);
  149000. /* (329) ecmd ::= cmdx SEMI */ yytestcase(yyruleno==329);
  149001. /* (330) ecmd ::= explain cmdx SEMI (NEVER REDUCES) */ assert(yyruleno!=330);
  149002. /* (331) trans_opt ::= */ yytestcase(yyruleno==331);
  149003. /* (332) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==332);
  149004. /* (333) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==333);
  149005. /* (334) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==334);
  149006. /* (335) savepoint_opt ::= */ yytestcase(yyruleno==335);
  149007. /* (336) cmd ::= create_table create_table_args */ yytestcase(yyruleno==336);
  149008. /* (337) columnlist ::= columnlist COMMA columnname carglist */ yytestcase(yyruleno==337);
  149009. /* (338) columnlist ::= columnname carglist */ yytestcase(yyruleno==338);
  149010. /* (339) nm ::= ID|INDEXED */ yytestcase(yyruleno==339);
  149011. /* (340) nm ::= STRING */ yytestcase(yyruleno==340);
  149012. /* (341) nm ::= JOIN_KW */ yytestcase(yyruleno==341);
  149013. /* (342) typetoken ::= typename */ yytestcase(yyruleno==342);
  149014. /* (343) typename ::= ID|STRING */ yytestcase(yyruleno==343);
  149015. /* (344) signed ::= plus_num (OPTIMIZED OUT) */ assert(yyruleno!=344);
  149016. /* (345) signed ::= minus_num (OPTIMIZED OUT) */ assert(yyruleno!=345);
  149017. /* (346) carglist ::= carglist ccons */ yytestcase(yyruleno==346);
  149018. /* (347) carglist ::= */ yytestcase(yyruleno==347);
  149019. /* (348) ccons ::= NULL onconf */ yytestcase(yyruleno==348);
  149020. /* (349) ccons ::= GENERATED ALWAYS AS generated */ yytestcase(yyruleno==349);
  149021. /* (350) ccons ::= AS generated */ yytestcase(yyruleno==350);
  149022. /* (351) conslist_opt ::= COMMA conslist */ yytestcase(yyruleno==351);
  149023. /* (352) conslist ::= conslist tconscomma tcons */ yytestcase(yyruleno==352);
  149024. /* (353) conslist ::= tcons (OPTIMIZED OUT) */ assert(yyruleno!=353);
  149025. /* (354) tconscomma ::= */ yytestcase(yyruleno==354);
  149026. /* (355) defer_subclause_opt ::= defer_subclause (OPTIMIZED OUT) */ assert(yyruleno!=355);
  149027. /* (356) resolvetype ::= raisetype (OPTIMIZED OUT) */ assert(yyruleno!=356);
  149028. /* (357) selectnowith ::= oneselect (OPTIMIZED OUT) */ assert(yyruleno!=357);
  149029. /* (358) oneselect ::= values */ yytestcase(yyruleno==358);
  149030. /* (359) sclp ::= selcollist COMMA */ yytestcase(yyruleno==359);
  149031. /* (360) as ::= ID|STRING */ yytestcase(yyruleno==360);
  149032. /* (361) expr ::= term (OPTIMIZED OUT) */ assert(yyruleno!=361);
  149033. /* (362) likeop ::= LIKE_KW|MATCH */ yytestcase(yyruleno==362);
  149034. /* (363) exprlist ::= nexprlist */ yytestcase(yyruleno==363);
  149035. /* (364) nmnum ::= plus_num (OPTIMIZED OUT) */ assert(yyruleno!=364);
  149036. /* (365) nmnum ::= nm (OPTIMIZED OUT) */ assert(yyruleno!=365);
  149037. /* (366) nmnum ::= ON */ yytestcase(yyruleno==366);
  149038. /* (367) nmnum ::= DELETE */ yytestcase(yyruleno==367);
  149039. /* (368) nmnum ::= DEFAULT */ yytestcase(yyruleno==368);
  149040. /* (369) plus_num ::= INTEGER|FLOAT */ yytestcase(yyruleno==369);
  149041. /* (370) foreach_clause ::= */ yytestcase(yyruleno==370);
  149042. /* (371) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==371);
  149043. /* (372) trnm ::= nm */ yytestcase(yyruleno==372);
  149044. /* (373) tridxby ::= */ yytestcase(yyruleno==373);
  149045. /* (374) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==374);
  149046. /* (375) database_kw_opt ::= */ yytestcase(yyruleno==375);
  149047. /* (376) kwcolumn_opt ::= */ yytestcase(yyruleno==376);
  149048. /* (377) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==377);
  149049. /* (378) vtabarglist ::= vtabarg */ yytestcase(yyruleno==378);
  149050. /* (379) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==379);
  149051. /* (380) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==380);
  149052. /* (381) anylist ::= */ yytestcase(yyruleno==381);
  149053. /* (382) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==382);
  149054. /* (383) anylist ::= anylist ANY */ yytestcase(yyruleno==383);
  149055. /* (384) with ::= */ yytestcase(yyruleno==384);
  149056. break;
  149057. /********** End reduce actions ************************************************/
  149058. };
  149059. assert( yyruleno<sizeof(yyRuleInfoLhs)/sizeof(yyRuleInfoLhs[0]) );
  149060. yygoto = yyRuleInfoLhs[yyruleno];
  149061. yysize = yyRuleInfoNRhs[yyruleno];
  149062. yyact = yy_find_reduce_action(yymsp[yysize].stateno,(YYCODETYPE)yygoto);
  149063. /* There are no SHIFTREDUCE actions on nonterminals because the table
  149064. ** generator has simplified them to pure REDUCE actions. */
  149065. assert( !(yyact>YY_MAX_SHIFT && yyact<=YY_MAX_SHIFTREDUCE) );
  149066. /* It is not possible for a REDUCE to be followed by an error */
  149067. assert( yyact!=YY_ERROR_ACTION );
  149068. yymsp += yysize+1;
  149069. yypParser->yytos = yymsp;
  149070. yymsp->stateno = (YYACTIONTYPE)yyact;
  149071. yymsp->major = (YYCODETYPE)yygoto;
  149072. yyTraceShift(yypParser, yyact, "... then shift");
  149073. return yyact;
  149074. }
  149075. /*
  149076. ** The following code executes when the parse fails
  149077. */
  149078. #ifndef YYNOERRORRECOVERY
  149079. static void yy_parse_failed(
  149080. yyParser *yypParser /* The parser */
  149081. ){
  149082. sqlite3ParserARG_FETCH
  149083. sqlite3ParserCTX_FETCH
  149084. #ifndef NDEBUG
  149085. if( yyTraceFILE ){
  149086. fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
  149087. }
  149088. #endif
  149089. while( yypParser->yytos>yypParser->yystack ) yy_pop_parser_stack(yypParser);
  149090. /* Here code is inserted which will be executed whenever the
  149091. ** parser fails */
  149092. /************ Begin %parse_failure code ***************************************/
  149093. /************ End %parse_failure code *****************************************/
  149094. sqlite3ParserARG_STORE /* Suppress warning about unused %extra_argument variable */
  149095. sqlite3ParserCTX_STORE
  149096. }
  149097. #endif /* YYNOERRORRECOVERY */
  149098. /*
  149099. ** The following code executes when a syntax error first occurs.
  149100. */
  149101. static void yy_syntax_error(
  149102. yyParser *yypParser, /* The parser */
  149103. int yymajor, /* The major type of the error token */
  149104. sqlite3ParserTOKENTYPE yyminor /* The minor type of the error token */
  149105. ){
  149106. sqlite3ParserARG_FETCH
  149107. sqlite3ParserCTX_FETCH
  149108. #define TOKEN yyminor
  149109. /************ Begin %syntax_error code ****************************************/
  149110. UNUSED_PARAMETER(yymajor); /* Silence some compiler warnings */
  149111. if( TOKEN.z[0] ){
  149112. sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
  149113. }else{
  149114. sqlite3ErrorMsg(pParse, "incomplete input");
  149115. }
  149116. /************ End %syntax_error code ******************************************/
  149117. sqlite3ParserARG_STORE /* Suppress warning about unused %extra_argument variable */
  149118. sqlite3ParserCTX_STORE
  149119. }
  149120. /*
  149121. ** The following is executed when the parser accepts
  149122. */
  149123. static void yy_accept(
  149124. yyParser *yypParser /* The parser */
  149125. ){
  149126. sqlite3ParserARG_FETCH
  149127. sqlite3ParserCTX_FETCH
  149128. #ifndef NDEBUG
  149129. if( yyTraceFILE ){
  149130. fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
  149131. }
  149132. #endif
  149133. #ifndef YYNOERRORRECOVERY
  149134. yypParser->yyerrcnt = -1;
  149135. #endif
  149136. assert( yypParser->yytos==yypParser->yystack );
  149137. /* Here code is inserted which will be executed whenever the
  149138. ** parser accepts */
  149139. /*********** Begin %parse_accept code *****************************************/
  149140. /*********** End %parse_accept code *******************************************/
  149141. sqlite3ParserARG_STORE /* Suppress warning about unused %extra_argument variable */
  149142. sqlite3ParserCTX_STORE
  149143. }
  149144. /* The main parser program.
  149145. ** The first argument is a pointer to a structure obtained from
  149146. ** "sqlite3ParserAlloc" which describes the current state of the parser.
  149147. ** The second argument is the major token number. The third is
  149148. ** the minor token. The fourth optional argument is whatever the
  149149. ** user wants (and specified in the grammar) and is available for
  149150. ** use by the action routines.
  149151. **
  149152. ** Inputs:
  149153. ** <ul>
  149154. ** <li> A pointer to the parser (an opaque structure.)
  149155. ** <li> The major token number.
  149156. ** <li> The minor token number.
  149157. ** <li> An option argument of a grammar-specified type.
  149158. ** </ul>
  149159. **
  149160. ** Outputs:
  149161. ** None.
  149162. */
  149163. SQLITE_PRIVATE void sqlite3Parser(
  149164. void *yyp, /* The parser */
  149165. int yymajor, /* The major token code number */
  149166. sqlite3ParserTOKENTYPE yyminor /* The value for the token */
  149167. sqlite3ParserARG_PDECL /* Optional %extra_argument parameter */
  149168. ){
  149169. YYMINORTYPE yyminorunion;
  149170. YYACTIONTYPE yyact; /* The parser action. */
  149171. #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
  149172. int yyendofinput; /* True if we are at the end of input */
  149173. #endif
  149174. #ifdef YYERRORSYMBOL
  149175. int yyerrorhit = 0; /* True if yymajor has invoked an error */
  149176. #endif
  149177. yyParser *yypParser = (yyParser*)yyp; /* The parser */
  149178. sqlite3ParserCTX_FETCH
  149179. sqlite3ParserARG_STORE
  149180. assert( yypParser->yytos!=0 );
  149181. #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
  149182. yyendofinput = (yymajor==0);
  149183. #endif
  149184. yyact = yypParser->yytos->stateno;
  149185. #ifndef NDEBUG
  149186. if( yyTraceFILE ){
  149187. if( yyact < YY_MIN_REDUCE ){
  149188. fprintf(yyTraceFILE,"%sInput '%s' in state %d\n",
  149189. yyTracePrompt,yyTokenName[yymajor],yyact);
  149190. }else{
  149191. fprintf(yyTraceFILE,"%sInput '%s' with pending reduce %d\n",
  149192. yyTracePrompt,yyTokenName[yymajor],yyact-YY_MIN_REDUCE);
  149193. }
  149194. }
  149195. #endif
  149196. do{
  149197. assert( yyact==yypParser->yytos->stateno );
  149198. yyact = yy_find_shift_action((YYCODETYPE)yymajor,yyact);
  149199. if( yyact >= YY_MIN_REDUCE ){
  149200. yyact = yy_reduce(yypParser,yyact-YY_MIN_REDUCE,yymajor,
  149201. yyminor sqlite3ParserCTX_PARAM);
  149202. }else if( yyact <= YY_MAX_SHIFTREDUCE ){
  149203. yy_shift(yypParser,yyact,(YYCODETYPE)yymajor,yyminor);
  149204. #ifndef YYNOERRORRECOVERY
  149205. yypParser->yyerrcnt--;
  149206. #endif
  149207. break;
  149208. }else if( yyact==YY_ACCEPT_ACTION ){
  149209. yypParser->yytos--;
  149210. yy_accept(yypParser);
  149211. return;
  149212. }else{
  149213. assert( yyact == YY_ERROR_ACTION );
  149214. yyminorunion.yy0 = yyminor;
  149215. #ifdef YYERRORSYMBOL
  149216. int yymx;
  149217. #endif
  149218. #ifndef NDEBUG
  149219. if( yyTraceFILE ){
  149220. fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
  149221. }
  149222. #endif
  149223. #ifdef YYERRORSYMBOL
  149224. /* A syntax error has occurred.
  149225. ** The response to an error depends upon whether or not the
  149226. ** grammar defines an error token "ERROR".
  149227. **
  149228. ** This is what we do if the grammar does define ERROR:
  149229. **
  149230. ** * Call the %syntax_error function.
  149231. **
  149232. ** * Begin popping the stack until we enter a state where
  149233. ** it is legal to shift the error symbol, then shift
  149234. ** the error symbol.
  149235. **
  149236. ** * Set the error count to three.
  149237. **
  149238. ** * Begin accepting and shifting new tokens. No new error
  149239. ** processing will occur until three tokens have been
  149240. ** shifted successfully.
  149241. **
  149242. */
  149243. if( yypParser->yyerrcnt<0 ){
  149244. yy_syntax_error(yypParser,yymajor,yyminor);
  149245. }
  149246. yymx = yypParser->yytos->major;
  149247. if( yymx==YYERRORSYMBOL || yyerrorhit ){
  149248. #ifndef NDEBUG
  149249. if( yyTraceFILE ){
  149250. fprintf(yyTraceFILE,"%sDiscard input token %s\n",
  149251. yyTracePrompt,yyTokenName[yymajor]);
  149252. }
  149253. #endif
  149254. yy_destructor(yypParser, (YYCODETYPE)yymajor, &yyminorunion);
  149255. yymajor = YYNOCODE;
  149256. }else{
  149257. while( yypParser->yytos >= yypParser->yystack
  149258. && (yyact = yy_find_reduce_action(
  149259. yypParser->yytos->stateno,
  149260. YYERRORSYMBOL)) > YY_MAX_SHIFTREDUCE
  149261. ){
  149262. yy_pop_parser_stack(yypParser);
  149263. }
  149264. if( yypParser->yytos < yypParser->yystack || yymajor==0 ){
  149265. yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
  149266. yy_parse_failed(yypParser);
  149267. #ifndef YYNOERRORRECOVERY
  149268. yypParser->yyerrcnt = -1;
  149269. #endif
  149270. yymajor = YYNOCODE;
  149271. }else if( yymx!=YYERRORSYMBOL ){
  149272. yy_shift(yypParser,yyact,YYERRORSYMBOL,yyminor);
  149273. }
  149274. }
  149275. yypParser->yyerrcnt = 3;
  149276. yyerrorhit = 1;
  149277. if( yymajor==YYNOCODE ) break;
  149278. yyact = yypParser->yytos->stateno;
  149279. #elif defined(YYNOERRORRECOVERY)
  149280. /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to
  149281. ** do any kind of error recovery. Instead, simply invoke the syntax
  149282. ** error routine and continue going as if nothing had happened.
  149283. **
  149284. ** Applications can set this macro (for example inside %include) if
  149285. ** they intend to abandon the parse upon the first syntax error seen.
  149286. */
  149287. yy_syntax_error(yypParser,yymajor, yyminor);
  149288. yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
  149289. break;
  149290. #else /* YYERRORSYMBOL is not defined */
  149291. /* This is what we do if the grammar does not define ERROR:
  149292. **
  149293. ** * Report an error message, and throw away the input token.
  149294. **
  149295. ** * If the input token is $, then fail the parse.
  149296. **
  149297. ** As before, subsequent error messages are suppressed until
  149298. ** three input tokens have been successfully shifted.
  149299. */
  149300. if( yypParser->yyerrcnt<=0 ){
  149301. yy_syntax_error(yypParser,yymajor, yyminor);
  149302. }
  149303. yypParser->yyerrcnt = 3;
  149304. yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
  149305. if( yyendofinput ){
  149306. yy_parse_failed(yypParser);
  149307. #ifndef YYNOERRORRECOVERY
  149308. yypParser->yyerrcnt = -1;
  149309. #endif
  149310. }
  149311. break;
  149312. #endif
  149313. }
  149314. }while( yypParser->yytos>yypParser->yystack );
  149315. #ifndef NDEBUG
  149316. if( yyTraceFILE ){
  149317. yyStackEntry *i;
  149318. char cDiv = '[';
  149319. fprintf(yyTraceFILE,"%sReturn. Stack=",yyTracePrompt);
  149320. for(i=&yypParser->yystack[1]; i<=yypParser->yytos; i++){
  149321. fprintf(yyTraceFILE,"%c%s", cDiv, yyTokenName[i->major]);
  149322. cDiv = ' ';
  149323. }
  149324. fprintf(yyTraceFILE,"]\n");
  149325. }
  149326. #endif
  149327. return;
  149328. }
  149329. /*
  149330. ** Return the fallback token corresponding to canonical token iToken, or
  149331. ** 0 if iToken has no fallback.
  149332. */
  149333. SQLITE_PRIVATE int sqlite3ParserFallback(int iToken){
  149334. #ifdef YYFALLBACK
  149335. assert( iToken<(int)(sizeof(yyFallback)/sizeof(yyFallback[0])) );
  149336. return yyFallback[iToken];
  149337. #else
  149338. (void)iToken;
  149339. return 0;
  149340. #endif
  149341. }
  149342. /************** End of parse.c ***********************************************/
  149343. /************** Begin file tokenize.c ****************************************/
  149344. /*
  149345. ** 2001 September 15
  149346. **
  149347. ** The author disclaims copyright to this source code. In place of
  149348. ** a legal notice, here is a blessing:
  149349. **
  149350. ** May you do good and not evil.
  149351. ** May you find forgiveness for yourself and forgive others.
  149352. ** May you share freely, never taking more than you give.
  149353. **
  149354. *************************************************************************
  149355. ** An tokenizer for SQL
  149356. **
  149357. ** This file contains C code that splits an SQL input string up into
  149358. ** individual tokens and sends those tokens one-by-one over to the
  149359. ** parser for analysis.
  149360. */
  149361. /* #include "sqliteInt.h" */
  149362. /* #include <stdlib.h> */
  149363. /* Character classes for tokenizing
  149364. **
  149365. ** In the sqlite3GetToken() function, a switch() on aiClass[c] is implemented
  149366. ** using a lookup table, whereas a switch() directly on c uses a binary search.
  149367. ** The lookup table is much faster. To maximize speed, and to ensure that
  149368. ** a lookup table is used, all of the classes need to be small integers and
  149369. ** all of them need to be used within the switch.
  149370. */
  149371. #define CC_X 0 /* The letter 'x', or start of BLOB literal */
  149372. #define CC_KYWD 1 /* Alphabetics or '_'. Usable in a keyword */
  149373. #define CC_ID 2 /* unicode characters usable in IDs */
  149374. #define CC_DIGIT 3 /* Digits */
  149375. #define CC_DOLLAR 4 /* '$' */
  149376. #define CC_VARALPHA 5 /* '@', '#', ':'. Alphabetic SQL variables */
  149377. #define CC_VARNUM 6 /* '?'. Numeric SQL variables */
  149378. #define CC_SPACE 7 /* Space characters */
  149379. #define CC_QUOTE 8 /* '"', '\'', or '`'. String literals, quoted ids */
  149380. #define CC_QUOTE2 9 /* '['. [...] style quoted ids */
  149381. #define CC_PIPE 10 /* '|'. Bitwise OR or concatenate */
  149382. #define CC_MINUS 11 /* '-'. Minus or SQL-style comment */
  149383. #define CC_LT 12 /* '<'. Part of < or <= or <> */
  149384. #define CC_GT 13 /* '>'. Part of > or >= */
  149385. #define CC_EQ 14 /* '='. Part of = or == */
  149386. #define CC_BANG 15 /* '!'. Part of != */
  149387. #define CC_SLASH 16 /* '/'. / or c-style comment */
  149388. #define CC_LP 17 /* '(' */
  149389. #define CC_RP 18 /* ')' */
  149390. #define CC_SEMI 19 /* ';' */
  149391. #define CC_PLUS 20 /* '+' */
  149392. #define CC_STAR 21 /* '*' */
  149393. #define CC_PERCENT 22 /* '%' */
  149394. #define CC_COMMA 23 /* ',' */
  149395. #define CC_AND 24 /* '&' */
  149396. #define CC_TILDA 25 /* '~' */
  149397. #define CC_DOT 26 /* '.' */
  149398. #define CC_ILLEGAL 27 /* Illegal character */
  149399. #define CC_NUL 28 /* 0x00 */
  149400. static const unsigned char aiClass[] = {
  149401. #ifdef SQLITE_ASCII
  149402. /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xa xb xc xd xe xf */
  149403. /* 0x */ 28, 27, 27, 27, 27, 27, 27, 27, 27, 7, 7, 27, 7, 7, 27, 27,
  149404. /* 1x */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  149405. /* 2x */ 7, 15, 8, 5, 4, 22, 24, 8, 17, 18, 21, 20, 23, 11, 26, 16,
  149406. /* 3x */ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 5, 19, 12, 14, 13, 6,
  149407. /* 4x */ 5, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  149408. /* 5x */ 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 9, 27, 27, 27, 1,
  149409. /* 6x */ 8, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  149410. /* 7x */ 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 27, 10, 27, 25, 27,
  149411. /* 8x */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  149412. /* 9x */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  149413. /* Ax */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  149414. /* Bx */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  149415. /* Cx */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  149416. /* Dx */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  149417. /* Ex */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  149418. /* Fx */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2
  149419. #endif
  149420. #ifdef SQLITE_EBCDIC
  149421. /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xa xb xc xd xe xf */
  149422. /* 0x */ 27, 27, 27, 27, 27, 7, 27, 27, 27, 27, 27, 27, 7, 7, 27, 27,
  149423. /* 1x */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  149424. /* 2x */ 27, 27, 27, 27, 27, 7, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  149425. /* 3x */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  149426. /* 4x */ 7, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 26, 12, 17, 20, 10,
  149427. /* 5x */ 24, 27, 27, 27, 27, 27, 27, 27, 27, 27, 15, 4, 21, 18, 19, 27,
  149428. /* 6x */ 11, 16, 27, 27, 27, 27, 27, 27, 27, 27, 27, 23, 22, 1, 13, 6,
  149429. /* 7x */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 8, 5, 5, 5, 8, 14, 8,
  149430. /* 8x */ 27, 1, 1, 1, 1, 1, 1, 1, 1, 1, 27, 27, 27, 27, 27, 27,
  149431. /* 9x */ 27, 1, 1, 1, 1, 1, 1, 1, 1, 1, 27, 27, 27, 27, 27, 27,
  149432. /* Ax */ 27, 25, 1, 1, 1, 1, 1, 0, 1, 1, 27, 27, 27, 27, 27, 27,
  149433. /* Bx */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 9, 27, 27, 27, 27, 27,
  149434. /* Cx */ 27, 1, 1, 1, 1, 1, 1, 1, 1, 1, 27, 27, 27, 27, 27, 27,
  149435. /* Dx */ 27, 1, 1, 1, 1, 1, 1, 1, 1, 1, 27, 27, 27, 27, 27, 27,
  149436. /* Ex */ 27, 27, 1, 1, 1, 1, 1, 0, 1, 1, 27, 27, 27, 27, 27, 27,
  149437. /* Fx */ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 27, 27, 27, 27, 27, 27,
  149438. #endif
  149439. };
  149440. /*
  149441. ** The charMap() macro maps alphabetic characters (only) into their
  149442. ** lower-case ASCII equivalent. On ASCII machines, this is just
  149443. ** an upper-to-lower case map. On EBCDIC machines we also need
  149444. ** to adjust the encoding. The mapping is only valid for alphabetics
  149445. ** which are the only characters for which this feature is used.
  149446. **
  149447. ** Used by keywordhash.h
  149448. */
  149449. #ifdef SQLITE_ASCII
  149450. # define charMap(X) sqlite3UpperToLower[(unsigned char)X]
  149451. #endif
  149452. #ifdef SQLITE_EBCDIC
  149453. # define charMap(X) ebcdicToAscii[(unsigned char)X]
  149454. const unsigned char ebcdicToAscii[] = {
  149455. /* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
  149456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */
  149457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */
  149458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */
  149459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 3x */
  149460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 4x */
  149461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 5x */
  149462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 95, 0, 0, /* 6x */
  149463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 7x */
  149464. 0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* 8x */
  149465. 0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* 9x */
  149466. 0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ax */
  149467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */
  149468. 0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* Cx */
  149469. 0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* Dx */
  149470. 0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ex */
  149471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Fx */
  149472. };
  149473. #endif
  149474. /*
  149475. ** The sqlite3KeywordCode function looks up an identifier to determine if
  149476. ** it is a keyword. If it is a keyword, the token code of that keyword is
  149477. ** returned. If the input is not a keyword, TK_ID is returned.
  149478. **
  149479. ** The implementation of this routine was generated by a program,
  149480. ** mkkeywordhash.c, located in the tool subdirectory of the distribution.
  149481. ** The output of the mkkeywordhash.c program is written into a file
  149482. ** named keywordhash.h and then included into this source file by
  149483. ** the #include below.
  149484. */
  149485. /************** Include keywordhash.h in the middle of tokenize.c ************/
  149486. /************** Begin file keywordhash.h *************************************/
  149487. /***** This file contains automatically generated code ******
  149488. **
  149489. ** The code in this file has been automatically generated by
  149490. **
  149491. ** sqlite/tool/mkkeywordhash.c
  149492. **
  149493. ** The code in this file implements a function that determines whether
  149494. ** or not a given identifier is really an SQL keyword. The same thing
  149495. ** might be implemented more directly using a hand-written hash table.
  149496. ** But by using this automatically generated code, the size of the code
  149497. ** is substantially reduced. This is important for embedded applications
  149498. ** on platforms with limited memory.
  149499. */
  149500. /* Hash score: 227 */
  149501. /* zKWText[] encodes 984 bytes of keyword text in 648 bytes */
  149502. /* REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT */
  149503. /* ABLEFTHENDEFERRABLELSEXCLUDELETEMPORARYISNULLSAVEPOINTERSECT */
  149504. /* IESNOTNULLIKEXCEPTRANSACTIONATURALTERAISEXCLUSIVEXISTS */
  149505. /* CONSTRAINTOFFSETRIGGERANGENERATEDETACHAVINGLOBEGINNEREFERENCES */
  149506. /* UNIQUERYWITHOUTERELEASEATTACHBETWEENOTHINGROUPSCASCADEFAULT */
  149507. /* CASECOLLATECREATECURRENT_DATEIMMEDIATEJOINSERTMATCHPLANALYZE */
  149508. /* PRAGMABORTUPDATEVALUESVIRTUALWAYSWHENWHERECURSIVEAFTERENAMEAND */
  149509. /* EFERREDISTINCTAUTOINCREMENTCASTCOLUMNCOMMITCONFLICTCROSS */
  149510. /* CURRENT_TIMESTAMPARTITIONDROPRECEDINGFAILASTFILTEREPLACEFIRST */
  149511. /* FOLLOWINGFROMFULLIMITIFORDERESTRICTOTHERSOVERIGHTROLLBACKROWS */
  149512. /* UNBOUNDEDUNIONUSINGVACUUMVIEWINDOWBYINITIALLYPRIMARY */
  149513. static const char zKWText[647] = {
  149514. 'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H',
  149515. 'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G',
  149516. 'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A',
  149517. 'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F',
  149518. 'E','R','R','A','B','L','E','L','S','E','X','C','L','U','D','E','L','E',
  149519. 'T','E','M','P','O','R','A','R','Y','I','S','N','U','L','L','S','A','V',
  149520. 'E','P','O','I','N','T','E','R','S','E','C','T','I','E','S','N','O','T',
  149521. 'N','U','L','L','I','K','E','X','C','E','P','T','R','A','N','S','A','C',
  149522. 'T','I','O','N','A','T','U','R','A','L','T','E','R','A','I','S','E','X',
  149523. 'C','L','U','S','I','V','E','X','I','S','T','S','C','O','N','S','T','R',
  149524. 'A','I','N','T','O','F','F','S','E','T','R','I','G','G','E','R','A','N',
  149525. 'G','E','N','E','R','A','T','E','D','E','T','A','C','H','A','V','I','N',
  149526. 'G','L','O','B','E','G','I','N','N','E','R','E','F','E','R','E','N','C',
  149527. 'E','S','U','N','I','Q','U','E','R','Y','W','I','T','H','O','U','T','E',
  149528. 'R','E','L','E','A','S','E','A','T','T','A','C','H','B','E','T','W','E',
  149529. 'E','N','O','T','H','I','N','G','R','O','U','P','S','C','A','S','C','A',
  149530. 'D','E','F','A','U','L','T','C','A','S','E','C','O','L','L','A','T','E',
  149531. 'C','R','E','A','T','E','C','U','R','R','E','N','T','_','D','A','T','E',
  149532. 'I','M','M','E','D','I','A','T','E','J','O','I','N','S','E','R','T','M',
  149533. 'A','T','C','H','P','L','A','N','A','L','Y','Z','E','P','R','A','G','M',
  149534. 'A','B','O','R','T','U','P','D','A','T','E','V','A','L','U','E','S','V',
  149535. 'I','R','T','U','A','L','W','A','Y','S','W','H','E','N','W','H','E','R',
  149536. 'E','C','U','R','S','I','V','E','A','F','T','E','R','E','N','A','M','E',
  149537. 'A','N','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T','A',
  149538. 'U','T','O','I','N','C','R','E','M','E','N','T','C','A','S','T','C','O',
  149539. 'L','U','M','N','C','O','M','M','I','T','C','O','N','F','L','I','C','T',
  149540. 'C','R','O','S','S','C','U','R','R','E','N','T','_','T','I','M','E','S',
  149541. 'T','A','M','P','A','R','T','I','T','I','O','N','D','R','O','P','R','E',
  149542. 'C','E','D','I','N','G','F','A','I','L','A','S','T','F','I','L','T','E',
  149543. 'R','E','P','L','A','C','E','F','I','R','S','T','F','O','L','L','O','W',
  149544. 'I','N','G','F','R','O','M','F','U','L','L','I','M','I','T','I','F','O',
  149545. 'R','D','E','R','E','S','T','R','I','C','T','O','T','H','E','R','S','O',
  149546. 'V','E','R','I','G','H','T','R','O','L','L','B','A','C','K','R','O','W',
  149547. 'S','U','N','B','O','U','N','D','E','D','U','N','I','O','N','U','S','I',
  149548. 'N','G','V','A','C','U','U','M','V','I','E','W','I','N','D','O','W','B',
  149549. 'Y','I','N','I','T','I','A','L','L','Y','P','R','I','M','A','R','Y',
  149550. };
  149551. /* aKWHash[i] is the hash value for the i-th keyword */
  149552. static const unsigned char aKWHash[127] = {
  149553. 84, 102, 132, 82, 114, 29, 0, 0, 91, 0, 85, 72, 0,
  149554. 53, 35, 86, 15, 0, 42, 94, 54, 126, 133, 19, 0, 0,
  149555. 138, 0, 40, 128, 0, 22, 104, 0, 9, 0, 0, 122, 80,
  149556. 0, 78, 6, 0, 65, 99, 145, 0, 134, 112, 0, 0, 48,
  149557. 0, 100, 24, 0, 17, 0, 27, 70, 23, 26, 5, 60, 140,
  149558. 107, 121, 0, 73, 101, 71, 143, 61, 119, 74, 0, 49, 0,
  149559. 11, 41, 0, 110, 0, 0, 0, 106, 10, 108, 113, 124, 14,
  149560. 50, 123, 0, 89, 0, 18, 120, 142, 56, 129, 137, 88, 83,
  149561. 37, 30, 125, 0, 0, 105, 51, 130, 127, 0, 34, 0, 0,
  149562. 44, 0, 95, 38, 39, 0, 20, 45, 116, 90,
  149563. };
  149564. /* aKWNext[] forms the hash collision chain. If aKWHash[i]==0
  149565. ** then the i-th keyword has no more hash collisions. Otherwise,
  149566. ** the next keyword with the same hash is aKWHash[i]-1. */
  149567. static const unsigned char aKWNext[145] = {
  149568. 0, 0, 0, 0, 4, 0, 43, 0, 0, 103, 111, 0, 0,
  149569. 0, 2, 0, 0, 141, 0, 0, 0, 13, 0, 0, 0, 0,
  149570. 139, 0, 0, 118, 52, 0, 0, 135, 12, 0, 0, 62, 0,
  149571. 136, 0, 131, 0, 0, 36, 0, 0, 28, 77, 0, 0, 0,
  149572. 0, 59, 0, 47, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  149573. 0, 69, 0, 0, 0, 0, 0, 144, 3, 0, 58, 0, 1,
  149574. 75, 0, 0, 0, 31, 0, 0, 0, 0, 0, 0, 64, 66,
  149575. 63, 0, 0, 0, 0, 46, 0, 16, 0, 115, 0, 0, 0,
  149576. 0, 0, 0, 0, 0, 0, 0, 81, 97, 0, 8, 0, 109,
  149577. 21, 7, 67, 0, 79, 93, 117, 0, 0, 68, 0, 0, 96,
  149578. 0, 55, 0, 76, 0, 92, 32, 33, 57, 25, 0, 98, 0,
  149579. 0, 87,
  149580. };
  149581. /* aKWLen[i] is the length (in bytes) of the i-th keyword */
  149582. static const unsigned char aKWLen[145] = {
  149583. 7, 7, 5, 4, 6, 4, 5, 3, 6, 7, 3, 6, 6,
  149584. 7, 7, 3, 8, 2, 6, 5, 4, 4, 3, 10, 4, 7,
  149585. 6, 9, 4, 2, 6, 5, 9, 9, 4, 7, 3, 2, 4,
  149586. 4, 6, 11, 6, 2, 7, 5, 5, 9, 6, 10, 4, 6,
  149587. 2, 3, 7, 5, 9, 6, 6, 4, 5, 5, 10, 6, 5,
  149588. 7, 4, 5, 7, 6, 7, 7, 6, 5, 7, 3, 7, 4,
  149589. 7, 6, 12, 9, 4, 6, 5, 4, 7, 6, 5, 6, 6,
  149590. 7, 6, 4, 5, 9, 5, 6, 3, 8, 8, 2, 13, 2,
  149591. 2, 4, 6, 6, 8, 5, 17, 12, 7, 9, 4, 9, 4,
  149592. 4, 6, 7, 5, 9, 4, 4, 5, 2, 5, 8, 6, 4,
  149593. 5, 8, 4, 3, 9, 5, 5, 6, 4, 6, 2, 2, 9,
  149594. 3, 7,
  149595. };
  149596. /* aKWOffset[i] is the index into zKWText[] of the start of
  149597. ** the text for the i-th keyword. */
  149598. static const unsigned short int aKWOffset[145] = {
  149599. 0, 2, 2, 8, 9, 14, 16, 20, 23, 25, 25, 29, 33,
  149600. 36, 41, 46, 48, 53, 54, 59, 62, 65, 67, 69, 78, 81,
  149601. 86, 90, 90, 94, 99, 101, 105, 111, 119, 123, 123, 123, 126,
  149602. 129, 132, 137, 142, 146, 147, 152, 156, 160, 168, 174, 181, 184,
  149603. 184, 187, 189, 195, 198, 206, 211, 216, 219, 222, 226, 236, 239,
  149604. 244, 244, 248, 252, 259, 265, 271, 277, 277, 283, 284, 288, 295,
  149605. 299, 306, 312, 324, 333, 335, 341, 346, 348, 355, 360, 365, 371,
  149606. 377, 382, 388, 392, 395, 404, 408, 414, 416, 423, 424, 431, 433,
  149607. 435, 444, 448, 454, 460, 468, 473, 473, 473, 489, 498, 501, 510,
  149608. 513, 517, 522, 529, 534, 543, 547, 550, 555, 557, 561, 569, 575,
  149609. 578, 583, 591, 591, 595, 604, 609, 614, 620, 623, 626, 629, 631,
  149610. 636, 640,
  149611. };
  149612. /* aKWCode[i] is the parser symbol code for the i-th keyword */
  149613. static const unsigned char aKWCode[145] = {
  149614. TK_REINDEX, TK_INDEXED, TK_INDEX, TK_DESC, TK_ESCAPE,
  149615. TK_EACH, TK_CHECK, TK_KEY, TK_BEFORE, TK_FOREIGN,
  149616. TK_FOR, TK_IGNORE, TK_LIKE_KW, TK_EXPLAIN, TK_INSTEAD,
  149617. TK_ADD, TK_DATABASE, TK_AS, TK_SELECT, TK_TABLE,
  149618. TK_JOIN_KW, TK_THEN, TK_END, TK_DEFERRABLE, TK_ELSE,
  149619. TK_EXCLUDE, TK_DELETE, TK_TEMP, TK_TEMP, TK_OR,
  149620. TK_ISNULL, TK_NULLS, TK_SAVEPOINT, TK_INTERSECT, TK_TIES,
  149621. TK_NOTNULL, TK_NOT, TK_NO, TK_NULL, TK_LIKE_KW,
  149622. TK_EXCEPT, TK_TRANSACTION,TK_ACTION, TK_ON, TK_JOIN_KW,
  149623. TK_ALTER, TK_RAISE, TK_EXCLUSIVE, TK_EXISTS, TK_CONSTRAINT,
  149624. TK_INTO, TK_OFFSET, TK_OF, TK_SET, TK_TRIGGER,
  149625. TK_RANGE, TK_GENERATED, TK_DETACH, TK_HAVING, TK_LIKE_KW,
  149626. TK_BEGIN, TK_JOIN_KW, TK_REFERENCES, TK_UNIQUE, TK_QUERY,
  149627. TK_WITHOUT, TK_WITH, TK_JOIN_KW, TK_RELEASE, TK_ATTACH,
  149628. TK_BETWEEN, TK_NOTHING, TK_GROUPS, TK_GROUP, TK_CASCADE,
  149629. TK_ASC, TK_DEFAULT, TK_CASE, TK_COLLATE, TK_CREATE,
  149630. TK_CTIME_KW, TK_IMMEDIATE, TK_JOIN, TK_INSERT, TK_MATCH,
  149631. TK_PLAN, TK_ANALYZE, TK_PRAGMA, TK_ABORT, TK_UPDATE,
  149632. TK_VALUES, TK_VIRTUAL, TK_ALWAYS, TK_WHEN, TK_WHERE,
  149633. TK_RECURSIVE, TK_AFTER, TK_RENAME, TK_AND, TK_DEFERRED,
  149634. TK_DISTINCT, TK_IS, TK_AUTOINCR, TK_TO, TK_IN,
  149635. TK_CAST, TK_COLUMNKW, TK_COMMIT, TK_CONFLICT, TK_JOIN_KW,
  149636. TK_CTIME_KW, TK_CTIME_KW, TK_CURRENT, TK_PARTITION, TK_DROP,
  149637. TK_PRECEDING, TK_FAIL, TK_LAST, TK_FILTER, TK_REPLACE,
  149638. TK_FIRST, TK_FOLLOWING, TK_FROM, TK_JOIN_KW, TK_LIMIT,
  149639. TK_IF, TK_ORDER, TK_RESTRICT, TK_OTHERS, TK_OVER,
  149640. TK_JOIN_KW, TK_ROLLBACK, TK_ROWS, TK_ROW, TK_UNBOUNDED,
  149641. TK_UNION, TK_USING, TK_VACUUM, TK_VIEW, TK_WINDOW,
  149642. TK_DO, TK_BY, TK_INITIALLY, TK_ALL, TK_PRIMARY,
  149643. };
  149644. /* Hash table decoded:
  149645. ** 0: INSERT
  149646. ** 1: IS
  149647. ** 2: ROLLBACK TRIGGER
  149648. ** 3: IMMEDIATE
  149649. ** 4: PARTITION
  149650. ** 5: TEMP
  149651. ** 6:
  149652. ** 7:
  149653. ** 8: VALUES WITHOUT
  149654. ** 9:
  149655. ** 10: MATCH
  149656. ** 11: NOTHING
  149657. ** 12:
  149658. ** 13: OF
  149659. ** 14: TIES IGNORE
  149660. ** 15: PLAN
  149661. ** 16: INSTEAD INDEXED
  149662. ** 17:
  149663. ** 18: TRANSACTION RIGHT
  149664. ** 19: WHEN
  149665. ** 20: SET HAVING
  149666. ** 21: IF
  149667. ** 22: ROWS
  149668. ** 23: SELECT
  149669. ** 24:
  149670. ** 25:
  149671. ** 26: VACUUM SAVEPOINT
  149672. ** 27:
  149673. ** 28: LIKE UNION VIRTUAL REFERENCES
  149674. ** 29: RESTRICT
  149675. ** 30:
  149676. ** 31: THEN REGEXP
  149677. ** 32: TO
  149678. ** 33:
  149679. ** 34: BEFORE
  149680. ** 35:
  149681. ** 36:
  149682. ** 37: FOLLOWING COLLATE CASCADE
  149683. ** 38: CREATE
  149684. ** 39:
  149685. ** 40: CASE REINDEX
  149686. ** 41: EACH
  149687. ** 42:
  149688. ** 43: QUERY
  149689. ** 44: AND ADD
  149690. ** 45: PRIMARY ANALYZE
  149691. ** 46:
  149692. ** 47: ROW ASC DETACH
  149693. ** 48: CURRENT_TIME CURRENT_DATE
  149694. ** 49:
  149695. ** 50:
  149696. ** 51: EXCLUSIVE TEMPORARY
  149697. ** 52:
  149698. ** 53: DEFERRED
  149699. ** 54: DEFERRABLE
  149700. ** 55:
  149701. ** 56: DATABASE
  149702. ** 57:
  149703. ** 58: DELETE VIEW GENERATED
  149704. ** 59: ATTACH
  149705. ** 60: END
  149706. ** 61: EXCLUDE
  149707. ** 62: ESCAPE DESC
  149708. ** 63: GLOB
  149709. ** 64: WINDOW ELSE
  149710. ** 65: COLUMN
  149711. ** 66: FIRST
  149712. ** 67:
  149713. ** 68: GROUPS ALL
  149714. ** 69: DISTINCT DROP KEY
  149715. ** 70: BETWEEN
  149716. ** 71: INITIALLY
  149717. ** 72: BEGIN
  149718. ** 73: FILTER CHECK ACTION
  149719. ** 74: GROUP INDEX
  149720. ** 75:
  149721. ** 76: EXISTS DEFAULT
  149722. ** 77:
  149723. ** 78: FOR CURRENT_TIMESTAMP
  149724. ** 79: EXCEPT
  149725. ** 80:
  149726. ** 81: CROSS
  149727. ** 82:
  149728. ** 83:
  149729. ** 84:
  149730. ** 85: CAST
  149731. ** 86: FOREIGN AUTOINCREMENT
  149732. ** 87: COMMIT
  149733. ** 88: CURRENT AFTER ALTER
  149734. ** 89: FULL FAIL CONFLICT
  149735. ** 90: EXPLAIN
  149736. ** 91: CONSTRAINT
  149737. ** 92: FROM ALWAYS
  149738. ** 93:
  149739. ** 94: ABORT
  149740. ** 95:
  149741. ** 96: AS DO
  149742. ** 97: REPLACE WITH RELEASE
  149743. ** 98: BY RENAME
  149744. ** 99: RANGE RAISE
  149745. ** 100: OTHERS
  149746. ** 101: USING NULLS
  149747. ** 102: PRAGMA
  149748. ** 103: JOIN ISNULL OFFSET
  149749. ** 104: NOT
  149750. ** 105: OR LAST LEFT
  149751. ** 106: LIMIT
  149752. ** 107:
  149753. ** 108:
  149754. ** 109: IN
  149755. ** 110: INTO
  149756. ** 111: OVER RECURSIVE
  149757. ** 112: ORDER OUTER
  149758. ** 113:
  149759. ** 114: INTERSECT UNBOUNDED
  149760. ** 115:
  149761. ** 116:
  149762. ** 117: ON
  149763. ** 118:
  149764. ** 119: WHERE
  149765. ** 120: NO INNER
  149766. ** 121: NULL
  149767. ** 122:
  149768. ** 123: TABLE
  149769. ** 124: NATURAL NOTNULL
  149770. ** 125: PRECEDING
  149771. ** 126: UPDATE UNIQUE
  149772. */
  149773. /* Check to see if z[0..n-1] is a keyword. If it is, write the
  149774. ** parser symbol code for that keyword into *pType. Always
  149775. ** return the integer n (the length of the token). */
  149776. static int keywordCode(const char *z, int n, int *pType){
  149777. int i, j;
  149778. const char *zKW;
  149779. if( n>=2 ){
  149780. i = ((charMap(z[0])*4) ^ (charMap(z[n-1])*3) ^ n) % 127;
  149781. for(i=((int)aKWHash[i])-1; i>=0; i=((int)aKWNext[i])-1){
  149782. if( aKWLen[i]!=n ) continue;
  149783. zKW = &zKWText[aKWOffset[i]];
  149784. #ifdef SQLITE_ASCII
  149785. if( (z[0]&~0x20)!=zKW[0] ) continue;
  149786. if( (z[1]&~0x20)!=zKW[1] ) continue;
  149787. j = 2;
  149788. while( j<n && (z[j]&~0x20)==zKW[j] ){ j++; }
  149789. #endif
  149790. #ifdef SQLITE_EBCDIC
  149791. if( toupper(z[0])!=zKW[0] ) continue;
  149792. if( toupper(z[1])!=zKW[1] ) continue;
  149793. j = 2;
  149794. while( j<n && toupper(z[j])==zKW[j] ){ j++; }
  149795. #endif
  149796. if( j<n ) continue;
  149797. testcase( i==0 ); /* REINDEX */
  149798. testcase( i==1 ); /* INDEXED */
  149799. testcase( i==2 ); /* INDEX */
  149800. testcase( i==3 ); /* DESC */
  149801. testcase( i==4 ); /* ESCAPE */
  149802. testcase( i==5 ); /* EACH */
  149803. testcase( i==6 ); /* CHECK */
  149804. testcase( i==7 ); /* KEY */
  149805. testcase( i==8 ); /* BEFORE */
  149806. testcase( i==9 ); /* FOREIGN */
  149807. testcase( i==10 ); /* FOR */
  149808. testcase( i==11 ); /* IGNORE */
  149809. testcase( i==12 ); /* REGEXP */
  149810. testcase( i==13 ); /* EXPLAIN */
  149811. testcase( i==14 ); /* INSTEAD */
  149812. testcase( i==15 ); /* ADD */
  149813. testcase( i==16 ); /* DATABASE */
  149814. testcase( i==17 ); /* AS */
  149815. testcase( i==18 ); /* SELECT */
  149816. testcase( i==19 ); /* TABLE */
  149817. testcase( i==20 ); /* LEFT */
  149818. testcase( i==21 ); /* THEN */
  149819. testcase( i==22 ); /* END */
  149820. testcase( i==23 ); /* DEFERRABLE */
  149821. testcase( i==24 ); /* ELSE */
  149822. testcase( i==25 ); /* EXCLUDE */
  149823. testcase( i==26 ); /* DELETE */
  149824. testcase( i==27 ); /* TEMPORARY */
  149825. testcase( i==28 ); /* TEMP */
  149826. testcase( i==29 ); /* OR */
  149827. testcase( i==30 ); /* ISNULL */
  149828. testcase( i==31 ); /* NULLS */
  149829. testcase( i==32 ); /* SAVEPOINT */
  149830. testcase( i==33 ); /* INTERSECT */
  149831. testcase( i==34 ); /* TIES */
  149832. testcase( i==35 ); /* NOTNULL */
  149833. testcase( i==36 ); /* NOT */
  149834. testcase( i==37 ); /* NO */
  149835. testcase( i==38 ); /* NULL */
  149836. testcase( i==39 ); /* LIKE */
  149837. testcase( i==40 ); /* EXCEPT */
  149838. testcase( i==41 ); /* TRANSACTION */
  149839. testcase( i==42 ); /* ACTION */
  149840. testcase( i==43 ); /* ON */
  149841. testcase( i==44 ); /* NATURAL */
  149842. testcase( i==45 ); /* ALTER */
  149843. testcase( i==46 ); /* RAISE */
  149844. testcase( i==47 ); /* EXCLUSIVE */
  149845. testcase( i==48 ); /* EXISTS */
  149846. testcase( i==49 ); /* CONSTRAINT */
  149847. testcase( i==50 ); /* INTO */
  149848. testcase( i==51 ); /* OFFSET */
  149849. testcase( i==52 ); /* OF */
  149850. testcase( i==53 ); /* SET */
  149851. testcase( i==54 ); /* TRIGGER */
  149852. testcase( i==55 ); /* RANGE */
  149853. testcase( i==56 ); /* GENERATED */
  149854. testcase( i==57 ); /* DETACH */
  149855. testcase( i==58 ); /* HAVING */
  149856. testcase( i==59 ); /* GLOB */
  149857. testcase( i==60 ); /* BEGIN */
  149858. testcase( i==61 ); /* INNER */
  149859. testcase( i==62 ); /* REFERENCES */
  149860. testcase( i==63 ); /* UNIQUE */
  149861. testcase( i==64 ); /* QUERY */
  149862. testcase( i==65 ); /* WITHOUT */
  149863. testcase( i==66 ); /* WITH */
  149864. testcase( i==67 ); /* OUTER */
  149865. testcase( i==68 ); /* RELEASE */
  149866. testcase( i==69 ); /* ATTACH */
  149867. testcase( i==70 ); /* BETWEEN */
  149868. testcase( i==71 ); /* NOTHING */
  149869. testcase( i==72 ); /* GROUPS */
  149870. testcase( i==73 ); /* GROUP */
  149871. testcase( i==74 ); /* CASCADE */
  149872. testcase( i==75 ); /* ASC */
  149873. testcase( i==76 ); /* DEFAULT */
  149874. testcase( i==77 ); /* CASE */
  149875. testcase( i==78 ); /* COLLATE */
  149876. testcase( i==79 ); /* CREATE */
  149877. testcase( i==80 ); /* CURRENT_DATE */
  149878. testcase( i==81 ); /* IMMEDIATE */
  149879. testcase( i==82 ); /* JOIN */
  149880. testcase( i==83 ); /* INSERT */
  149881. testcase( i==84 ); /* MATCH */
  149882. testcase( i==85 ); /* PLAN */
  149883. testcase( i==86 ); /* ANALYZE */
  149884. testcase( i==87 ); /* PRAGMA */
  149885. testcase( i==88 ); /* ABORT */
  149886. testcase( i==89 ); /* UPDATE */
  149887. testcase( i==90 ); /* VALUES */
  149888. testcase( i==91 ); /* VIRTUAL */
  149889. testcase( i==92 ); /* ALWAYS */
  149890. testcase( i==93 ); /* WHEN */
  149891. testcase( i==94 ); /* WHERE */
  149892. testcase( i==95 ); /* RECURSIVE */
  149893. testcase( i==96 ); /* AFTER */
  149894. testcase( i==97 ); /* RENAME */
  149895. testcase( i==98 ); /* AND */
  149896. testcase( i==99 ); /* DEFERRED */
  149897. testcase( i==100 ); /* DISTINCT */
  149898. testcase( i==101 ); /* IS */
  149899. testcase( i==102 ); /* AUTOINCREMENT */
  149900. testcase( i==103 ); /* TO */
  149901. testcase( i==104 ); /* IN */
  149902. testcase( i==105 ); /* CAST */
  149903. testcase( i==106 ); /* COLUMN */
  149904. testcase( i==107 ); /* COMMIT */
  149905. testcase( i==108 ); /* CONFLICT */
  149906. testcase( i==109 ); /* CROSS */
  149907. testcase( i==110 ); /* CURRENT_TIMESTAMP */
  149908. testcase( i==111 ); /* CURRENT_TIME */
  149909. testcase( i==112 ); /* CURRENT */
  149910. testcase( i==113 ); /* PARTITION */
  149911. testcase( i==114 ); /* DROP */
  149912. testcase( i==115 ); /* PRECEDING */
  149913. testcase( i==116 ); /* FAIL */
  149914. testcase( i==117 ); /* LAST */
  149915. testcase( i==118 ); /* FILTER */
  149916. testcase( i==119 ); /* REPLACE */
  149917. testcase( i==120 ); /* FIRST */
  149918. testcase( i==121 ); /* FOLLOWING */
  149919. testcase( i==122 ); /* FROM */
  149920. testcase( i==123 ); /* FULL */
  149921. testcase( i==124 ); /* LIMIT */
  149922. testcase( i==125 ); /* IF */
  149923. testcase( i==126 ); /* ORDER */
  149924. testcase( i==127 ); /* RESTRICT */
  149925. testcase( i==128 ); /* OTHERS */
  149926. testcase( i==129 ); /* OVER */
  149927. testcase( i==130 ); /* RIGHT */
  149928. testcase( i==131 ); /* ROLLBACK */
  149929. testcase( i==132 ); /* ROWS */
  149930. testcase( i==133 ); /* ROW */
  149931. testcase( i==134 ); /* UNBOUNDED */
  149932. testcase( i==135 ); /* UNION */
  149933. testcase( i==136 ); /* USING */
  149934. testcase( i==137 ); /* VACUUM */
  149935. testcase( i==138 ); /* VIEW */
  149936. testcase( i==139 ); /* WINDOW */
  149937. testcase( i==140 ); /* DO */
  149938. testcase( i==141 ); /* BY */
  149939. testcase( i==142 ); /* INITIALLY */
  149940. testcase( i==143 ); /* ALL */
  149941. testcase( i==144 ); /* PRIMARY */
  149942. *pType = aKWCode[i];
  149943. break;
  149944. }
  149945. }
  149946. return n;
  149947. }
  149948. SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
  149949. int id = TK_ID;
  149950. keywordCode((char*)z, n, &id);
  149951. return id;
  149952. }
  149953. #define SQLITE_N_KEYWORD 145
  149954. SQLITE_API int sqlite3_keyword_name(int i,const char **pzName,int *pnName){
  149955. if( i<0 || i>=SQLITE_N_KEYWORD ) return SQLITE_ERROR;
  149956. *pzName = zKWText + aKWOffset[i];
  149957. *pnName = aKWLen[i];
  149958. return SQLITE_OK;
  149959. }
  149960. SQLITE_API int sqlite3_keyword_count(void){ return SQLITE_N_KEYWORD; }
  149961. SQLITE_API int sqlite3_keyword_check(const char *zName, int nName){
  149962. return TK_ID!=sqlite3KeywordCode((const u8*)zName, nName);
  149963. }
  149964. /************** End of keywordhash.h *****************************************/
  149965. /************** Continuing where we left off in tokenize.c *******************/
  149966. /*
  149967. ** If X is a character that can be used in an identifier then
  149968. ** IdChar(X) will be true. Otherwise it is false.
  149969. **
  149970. ** For ASCII, any character with the high-order bit set is
  149971. ** allowed in an identifier. For 7-bit characters,
  149972. ** sqlite3IsIdChar[X] must be 1.
  149973. **
  149974. ** For EBCDIC, the rules are more complex but have the same
  149975. ** end result.
  149976. **
  149977. ** Ticket #1066. the SQL standard does not allow '$' in the
  149978. ** middle of identifiers. But many SQL implementations do.
  149979. ** SQLite will allow '$' in identifiers for compatibility.
  149980. ** But the feature is undocumented.
  149981. */
  149982. #ifdef SQLITE_ASCII
  149983. #define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
  149984. #endif
  149985. #ifdef SQLITE_EBCDIC
  149986. SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = {
  149987. /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
  149988. 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 4x */
  149989. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, /* 5x */
  149990. 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, /* 6x */
  149991. 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, /* 7x */
  149992. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0, /* 8x */
  149993. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, /* 9x */
  149994. 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, /* Ax */
  149995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */
  149996. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Cx */
  149997. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Dx */
  149998. 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Ex */
  149999. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, /* Fx */
  150000. };
  150001. #define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
  150002. #endif
  150003. /* Make the IdChar function accessible from ctime.c and alter.c */
  150004. SQLITE_PRIVATE int sqlite3IsIdChar(u8 c){ return IdChar(c); }
  150005. #ifndef SQLITE_OMIT_WINDOWFUNC
  150006. /*
  150007. ** Return the id of the next token in string (*pz). Before returning, set
  150008. ** (*pz) to point to the byte following the parsed token.
  150009. */
  150010. static int getToken(const unsigned char **pz){
  150011. const unsigned char *z = *pz;
  150012. int t; /* Token type to return */
  150013. do {
  150014. z += sqlite3GetToken(z, &t);
  150015. }while( t==TK_SPACE );
  150016. if( t==TK_ID
  150017. || t==TK_STRING
  150018. || t==TK_JOIN_KW
  150019. || t==TK_WINDOW
  150020. || t==TK_OVER
  150021. || sqlite3ParserFallback(t)==TK_ID
  150022. ){
  150023. t = TK_ID;
  150024. }
  150025. *pz = z;
  150026. return t;
  150027. }
  150028. /*
  150029. ** The following three functions are called immediately after the tokenizer
  150030. ** reads the keywords WINDOW, OVER and FILTER, respectively, to determine
  150031. ** whether the token should be treated as a keyword or an SQL identifier.
  150032. ** This cannot be handled by the usual lemon %fallback method, due to
  150033. ** the ambiguity in some constructions. e.g.
  150034. **
  150035. ** SELECT sum(x) OVER ...
  150036. **
  150037. ** In the above, "OVER" might be a keyword, or it might be an alias for the
  150038. ** sum(x) expression. If a "%fallback ID OVER" directive were added to
  150039. ** grammar, then SQLite would always treat "OVER" as an alias, making it
  150040. ** impossible to call a window-function without a FILTER clause.
  150041. **
  150042. ** WINDOW is treated as a keyword if:
  150043. **
  150044. ** * the following token is an identifier, or a keyword that can fallback
  150045. ** to being an identifier, and
  150046. ** * the token after than one is TK_AS.
  150047. **
  150048. ** OVER is a keyword if:
  150049. **
  150050. ** * the previous token was TK_RP, and
  150051. ** * the next token is either TK_LP or an identifier.
  150052. **
  150053. ** FILTER is a keyword if:
  150054. **
  150055. ** * the previous token was TK_RP, and
  150056. ** * the next token is TK_LP.
  150057. */
  150058. static int analyzeWindowKeyword(const unsigned char *z){
  150059. int t;
  150060. t = getToken(&z);
  150061. if( t!=TK_ID ) return TK_ID;
  150062. t = getToken(&z);
  150063. if( t!=TK_AS ) return TK_ID;
  150064. return TK_WINDOW;
  150065. }
  150066. static int analyzeOverKeyword(const unsigned char *z, int lastToken){
  150067. if( lastToken==TK_RP ){
  150068. int t = getToken(&z);
  150069. if( t==TK_LP || t==TK_ID ) return TK_OVER;
  150070. }
  150071. return TK_ID;
  150072. }
  150073. static int analyzeFilterKeyword(const unsigned char *z, int lastToken){
  150074. if( lastToken==TK_RP && getToken(&z)==TK_LP ){
  150075. return TK_FILTER;
  150076. }
  150077. return TK_ID;
  150078. }
  150079. #endif /* SQLITE_OMIT_WINDOWFUNC */
  150080. /*
  150081. ** Return the length (in bytes) of the token that begins at z[0].
  150082. ** Store the token type in *tokenType before returning.
  150083. */
  150084. SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
  150085. int i, c;
  150086. switch( aiClass[*z] ){ /* Switch on the character-class of the first byte
  150087. ** of the token. See the comment on the CC_ defines
  150088. ** above. */
  150089. case CC_SPACE: {
  150090. testcase( z[0]==' ' );
  150091. testcase( z[0]=='\t' );
  150092. testcase( z[0]=='\n' );
  150093. testcase( z[0]=='\f' );
  150094. testcase( z[0]=='\r' );
  150095. for(i=1; sqlite3Isspace(z[i]); i++){}
  150096. *tokenType = TK_SPACE;
  150097. return i;
  150098. }
  150099. case CC_MINUS: {
  150100. if( z[1]=='-' ){
  150101. for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
  150102. *tokenType = TK_SPACE; /* IMP: R-22934-25134 */
  150103. return i;
  150104. }
  150105. *tokenType = TK_MINUS;
  150106. return 1;
  150107. }
  150108. case CC_LP: {
  150109. *tokenType = TK_LP;
  150110. return 1;
  150111. }
  150112. case CC_RP: {
  150113. *tokenType = TK_RP;
  150114. return 1;
  150115. }
  150116. case CC_SEMI: {
  150117. *tokenType = TK_SEMI;
  150118. return 1;
  150119. }
  150120. case CC_PLUS: {
  150121. *tokenType = TK_PLUS;
  150122. return 1;
  150123. }
  150124. case CC_STAR: {
  150125. *tokenType = TK_STAR;
  150126. return 1;
  150127. }
  150128. case CC_SLASH: {
  150129. if( z[1]!='*' || z[2]==0 ){
  150130. *tokenType = TK_SLASH;
  150131. return 1;
  150132. }
  150133. for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
  150134. if( c ) i++;
  150135. *tokenType = TK_SPACE; /* IMP: R-22934-25134 */
  150136. return i;
  150137. }
  150138. case CC_PERCENT: {
  150139. *tokenType = TK_REM;
  150140. return 1;
  150141. }
  150142. case CC_EQ: {
  150143. *tokenType = TK_EQ;
  150144. return 1 + (z[1]=='=');
  150145. }
  150146. case CC_LT: {
  150147. if( (c=z[1])=='=' ){
  150148. *tokenType = TK_LE;
  150149. return 2;
  150150. }else if( c=='>' ){
  150151. *tokenType = TK_NE;
  150152. return 2;
  150153. }else if( c=='<' ){
  150154. *tokenType = TK_LSHIFT;
  150155. return 2;
  150156. }else{
  150157. *tokenType = TK_LT;
  150158. return 1;
  150159. }
  150160. }
  150161. case CC_GT: {
  150162. if( (c=z[1])=='=' ){
  150163. *tokenType = TK_GE;
  150164. return 2;
  150165. }else if( c=='>' ){
  150166. *tokenType = TK_RSHIFT;
  150167. return 2;
  150168. }else{
  150169. *tokenType = TK_GT;
  150170. return 1;
  150171. }
  150172. }
  150173. case CC_BANG: {
  150174. if( z[1]!='=' ){
  150175. *tokenType = TK_ILLEGAL;
  150176. return 1;
  150177. }else{
  150178. *tokenType = TK_NE;
  150179. return 2;
  150180. }
  150181. }
  150182. case CC_PIPE: {
  150183. if( z[1]!='|' ){
  150184. *tokenType = TK_BITOR;
  150185. return 1;
  150186. }else{
  150187. *tokenType = TK_CONCAT;
  150188. return 2;
  150189. }
  150190. }
  150191. case CC_COMMA: {
  150192. *tokenType = TK_COMMA;
  150193. return 1;
  150194. }
  150195. case CC_AND: {
  150196. *tokenType = TK_BITAND;
  150197. return 1;
  150198. }
  150199. case CC_TILDA: {
  150200. *tokenType = TK_BITNOT;
  150201. return 1;
  150202. }
  150203. case CC_QUOTE: {
  150204. int delim = z[0];
  150205. testcase( delim=='`' );
  150206. testcase( delim=='\'' );
  150207. testcase( delim=='"' );
  150208. for(i=1; (c=z[i])!=0; i++){
  150209. if( c==delim ){
  150210. if( z[i+1]==delim ){
  150211. i++;
  150212. }else{
  150213. break;
  150214. }
  150215. }
  150216. }
  150217. if( c=='\'' ){
  150218. *tokenType = TK_STRING;
  150219. return i+1;
  150220. }else if( c!=0 ){
  150221. *tokenType = TK_ID;
  150222. return i+1;
  150223. }else{
  150224. *tokenType = TK_ILLEGAL;
  150225. return i;
  150226. }
  150227. }
  150228. case CC_DOT: {
  150229. #ifndef SQLITE_OMIT_FLOATING_POINT
  150230. if( !sqlite3Isdigit(z[1]) )
  150231. #endif
  150232. {
  150233. *tokenType = TK_DOT;
  150234. return 1;
  150235. }
  150236. /* If the next character is a digit, this is a floating point
  150237. ** number that begins with ".". Fall thru into the next case */
  150238. }
  150239. case CC_DIGIT: {
  150240. testcase( z[0]=='0' ); testcase( z[0]=='1' ); testcase( z[0]=='2' );
  150241. testcase( z[0]=='3' ); testcase( z[0]=='4' ); testcase( z[0]=='5' );
  150242. testcase( z[0]=='6' ); testcase( z[0]=='7' ); testcase( z[0]=='8' );
  150243. testcase( z[0]=='9' );
  150244. *tokenType = TK_INTEGER;
  150245. #ifndef SQLITE_OMIT_HEX_INTEGER
  150246. if( z[0]=='0' && (z[1]=='x' || z[1]=='X') && sqlite3Isxdigit(z[2]) ){
  150247. for(i=3; sqlite3Isxdigit(z[i]); i++){}
  150248. return i;
  150249. }
  150250. #endif
  150251. for(i=0; sqlite3Isdigit(z[i]); i++){}
  150252. #ifndef SQLITE_OMIT_FLOATING_POINT
  150253. if( z[i]=='.' ){
  150254. i++;
  150255. while( sqlite3Isdigit(z[i]) ){ i++; }
  150256. *tokenType = TK_FLOAT;
  150257. }
  150258. if( (z[i]=='e' || z[i]=='E') &&
  150259. ( sqlite3Isdigit(z[i+1])
  150260. || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2]))
  150261. )
  150262. ){
  150263. i += 2;
  150264. while( sqlite3Isdigit(z[i]) ){ i++; }
  150265. *tokenType = TK_FLOAT;
  150266. }
  150267. #endif
  150268. while( IdChar(z[i]) ){
  150269. *tokenType = TK_ILLEGAL;
  150270. i++;
  150271. }
  150272. return i;
  150273. }
  150274. case CC_QUOTE2: {
  150275. for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
  150276. *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
  150277. return i;
  150278. }
  150279. case CC_VARNUM: {
  150280. *tokenType = TK_VARIABLE;
  150281. for(i=1; sqlite3Isdigit(z[i]); i++){}
  150282. return i;
  150283. }
  150284. case CC_DOLLAR:
  150285. case CC_VARALPHA: {
  150286. int n = 0;
  150287. testcase( z[0]=='$' ); testcase( z[0]=='@' );
  150288. testcase( z[0]==':' ); testcase( z[0]=='#' );
  150289. *tokenType = TK_VARIABLE;
  150290. for(i=1; (c=z[i])!=0; i++){
  150291. if( IdChar(c) ){
  150292. n++;
  150293. #ifndef SQLITE_OMIT_TCL_VARIABLE
  150294. }else if( c=='(' && n>0 ){
  150295. do{
  150296. i++;
  150297. }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' );
  150298. if( c==')' ){
  150299. i++;
  150300. }else{
  150301. *tokenType = TK_ILLEGAL;
  150302. }
  150303. break;
  150304. }else if( c==':' && z[i+1]==':' ){
  150305. i++;
  150306. #endif
  150307. }else{
  150308. break;
  150309. }
  150310. }
  150311. if( n==0 ) *tokenType = TK_ILLEGAL;
  150312. return i;
  150313. }
  150314. case CC_KYWD: {
  150315. for(i=1; aiClass[z[i]]<=CC_KYWD; i++){}
  150316. if( IdChar(z[i]) ){
  150317. /* This token started out using characters that can appear in keywords,
  150318. ** but z[i] is a character not allowed within keywords, so this must
  150319. ** be an identifier instead */
  150320. i++;
  150321. break;
  150322. }
  150323. *tokenType = TK_ID;
  150324. return keywordCode((char*)z, i, tokenType);
  150325. }
  150326. case CC_X: {
  150327. #ifndef SQLITE_OMIT_BLOB_LITERAL
  150328. testcase( z[0]=='x' ); testcase( z[0]=='X' );
  150329. if( z[1]=='\'' ){
  150330. *tokenType = TK_BLOB;
  150331. for(i=2; sqlite3Isxdigit(z[i]); i++){}
  150332. if( z[i]!='\'' || i%2 ){
  150333. *tokenType = TK_ILLEGAL;
  150334. while( z[i] && z[i]!='\'' ){ i++; }
  150335. }
  150336. if( z[i] ) i++;
  150337. return i;
  150338. }
  150339. #endif
  150340. /* If it is not a BLOB literal, then it must be an ID, since no
  150341. ** SQL keywords start with the letter 'x'. Fall through */
  150342. }
  150343. case CC_ID: {
  150344. i = 1;
  150345. break;
  150346. }
  150347. case CC_NUL: {
  150348. *tokenType = TK_ILLEGAL;
  150349. return 0;
  150350. }
  150351. default: {
  150352. *tokenType = TK_ILLEGAL;
  150353. return 1;
  150354. }
  150355. }
  150356. while( IdChar(z[i]) ){ i++; }
  150357. *tokenType = TK_ID;
  150358. return i;
  150359. }
  150360. /*
  150361. ** Run the parser on the given SQL string. The parser structure is
  150362. ** passed in. An SQLITE_ status code is returned. If an error occurs
  150363. ** then an and attempt is made to write an error message into
  150364. ** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that
  150365. ** error message.
  150366. */
  150367. SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
  150368. int nErr = 0; /* Number of errors encountered */
  150369. void *pEngine; /* The LEMON-generated LALR(1) parser */
  150370. int n = 0; /* Length of the next token token */
  150371. int tokenType; /* type of the next token */
  150372. int lastTokenParsed = -1; /* type of the previous token */
  150373. sqlite3 *db = pParse->db; /* The database connection */
  150374. int mxSqlLen; /* Max length of an SQL string */
  150375. #ifdef sqlite3Parser_ENGINEALWAYSONSTACK
  150376. yyParser sEngine; /* Space to hold the Lemon-generated Parser object */
  150377. #endif
  150378. VVA_ONLY( u8 startedWithOom = db->mallocFailed );
  150379. assert( zSql!=0 );
  150380. mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
  150381. if( db->nVdbeActive==0 ){
  150382. AtomicStore(&db->u1.isInterrupted, 0);
  150383. }
  150384. pParse->rc = SQLITE_OK;
  150385. pParse->zTail = zSql;
  150386. assert( pzErrMsg!=0 );
  150387. #ifdef SQLITE_DEBUG
  150388. if( db->flags & SQLITE_ParserTrace ){
  150389. printf("parser: [[[%s]]]\n", zSql);
  150390. sqlite3ParserTrace(stdout, "parser: ");
  150391. }else{
  150392. sqlite3ParserTrace(0, 0);
  150393. }
  150394. #endif
  150395. #ifdef sqlite3Parser_ENGINEALWAYSONSTACK
  150396. pEngine = &sEngine;
  150397. sqlite3ParserInit(pEngine, pParse);
  150398. #else
  150399. pEngine = sqlite3ParserAlloc(sqlite3Malloc, pParse);
  150400. if( pEngine==0 ){
  150401. sqlite3OomFault(db);
  150402. return SQLITE_NOMEM_BKPT;
  150403. }
  150404. #endif
  150405. assert( pParse->pNewTable==0 );
  150406. assert( pParse->pNewTrigger==0 );
  150407. assert( pParse->nVar==0 );
  150408. assert( pParse->pVList==0 );
  150409. pParse->pParentParse = db->pParse;
  150410. db->pParse = pParse;
  150411. while( 1 ){
  150412. n = sqlite3GetToken((u8*)zSql, &tokenType);
  150413. mxSqlLen -= n;
  150414. if( mxSqlLen<0 ){
  150415. pParse->rc = SQLITE_TOOBIG;
  150416. break;
  150417. }
  150418. #ifndef SQLITE_OMIT_WINDOWFUNC
  150419. if( tokenType>=TK_WINDOW ){
  150420. assert( tokenType==TK_SPACE || tokenType==TK_OVER || tokenType==TK_FILTER
  150421. || tokenType==TK_ILLEGAL || tokenType==TK_WINDOW
  150422. );
  150423. #else
  150424. if( tokenType>=TK_SPACE ){
  150425. assert( tokenType==TK_SPACE || tokenType==TK_ILLEGAL );
  150426. #endif /* SQLITE_OMIT_WINDOWFUNC */
  150427. if( AtomicLoad(&db->u1.isInterrupted) ){
  150428. pParse->rc = SQLITE_INTERRUPT;
  150429. break;
  150430. }
  150431. if( tokenType==TK_SPACE ){
  150432. zSql += n;
  150433. continue;
  150434. }
  150435. if( zSql[0]==0 ){
  150436. /* Upon reaching the end of input, call the parser two more times
  150437. ** with tokens TK_SEMI and 0, in that order. */
  150438. if( lastTokenParsed==TK_SEMI ){
  150439. tokenType = 0;
  150440. }else if( lastTokenParsed==0 ){
  150441. break;
  150442. }else{
  150443. tokenType = TK_SEMI;
  150444. }
  150445. n = 0;
  150446. #ifndef SQLITE_OMIT_WINDOWFUNC
  150447. }else if( tokenType==TK_WINDOW ){
  150448. assert( n==6 );
  150449. tokenType = analyzeWindowKeyword((const u8*)&zSql[6]);
  150450. }else if( tokenType==TK_OVER ){
  150451. assert( n==4 );
  150452. tokenType = analyzeOverKeyword((const u8*)&zSql[4], lastTokenParsed);
  150453. }else if( tokenType==TK_FILTER ){
  150454. assert( n==6 );
  150455. tokenType = analyzeFilterKeyword((const u8*)&zSql[6], lastTokenParsed);
  150456. #endif /* SQLITE_OMIT_WINDOWFUNC */
  150457. }else{
  150458. sqlite3ErrorMsg(pParse, "unrecognized token: \"%.*s\"", n, zSql);
  150459. break;
  150460. }
  150461. }
  150462. pParse->sLastToken.z = zSql;
  150463. pParse->sLastToken.n = n;
  150464. sqlite3Parser(pEngine, tokenType, pParse->sLastToken);
  150465. lastTokenParsed = tokenType;
  150466. zSql += n;
  150467. assert( db->mallocFailed==0 || pParse->rc!=SQLITE_OK || startedWithOom );
  150468. if( pParse->rc!=SQLITE_OK ) break;
  150469. }
  150470. assert( nErr==0 );
  150471. #ifdef YYTRACKMAXSTACKDEPTH
  150472. sqlite3_mutex_enter(sqlite3MallocMutex());
  150473. sqlite3StatusHighwater(SQLITE_STATUS_PARSER_STACK,
  150474. sqlite3ParserStackPeak(pEngine)
  150475. );
  150476. sqlite3_mutex_leave(sqlite3MallocMutex());
  150477. #endif /* YYDEBUG */
  150478. #ifdef sqlite3Parser_ENGINEALWAYSONSTACK
  150479. sqlite3ParserFinalize(pEngine);
  150480. #else
  150481. sqlite3ParserFree(pEngine, sqlite3_free);
  150482. #endif
  150483. if( db->mallocFailed ){
  150484. pParse->rc = SQLITE_NOMEM_BKPT;
  150485. }
  150486. if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
  150487. pParse->zErrMsg = sqlite3MPrintf(db, "%s", sqlite3ErrStr(pParse->rc));
  150488. }
  150489. assert( pzErrMsg!=0 );
  150490. if( pParse->zErrMsg ){
  150491. *pzErrMsg = pParse->zErrMsg;
  150492. sqlite3_log(pParse->rc, "%s in \"%s\"",
  150493. *pzErrMsg, pParse->zTail);
  150494. pParse->zErrMsg = 0;
  150495. nErr++;
  150496. }
  150497. pParse->zTail = zSql;
  150498. if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
  150499. sqlite3VdbeDelete(pParse->pVdbe);
  150500. pParse->pVdbe = 0;
  150501. }
  150502. #ifndef SQLITE_OMIT_SHARED_CACHE
  150503. if( pParse->nested==0 ){
  150504. sqlite3DbFree(db, pParse->aTableLock);
  150505. pParse->aTableLock = 0;
  150506. pParse->nTableLock = 0;
  150507. }
  150508. #endif
  150509. #ifndef SQLITE_OMIT_VIRTUALTABLE
  150510. sqlite3_free(pParse->apVtabLock);
  150511. #endif
  150512. if( !IN_SPECIAL_PARSE ){
  150513. /* If the pParse->declareVtab flag is set, do not delete any table
  150514. ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
  150515. ** will take responsibility for freeing the Table structure.
  150516. */
  150517. sqlite3DeleteTable(db, pParse->pNewTable);
  150518. }
  150519. if( !IN_RENAME_OBJECT ){
  150520. sqlite3DeleteTrigger(db, pParse->pNewTrigger);
  150521. }
  150522. if( pParse->pWithToFree ) sqlite3WithDelete(db, pParse->pWithToFree);
  150523. sqlite3DbFree(db, pParse->pVList);
  150524. while( pParse->pAinc ){
  150525. AutoincInfo *p = pParse->pAinc;
  150526. pParse->pAinc = p->pNext;
  150527. sqlite3DbFreeNN(db, p);
  150528. }
  150529. while( pParse->pZombieTab ){
  150530. Table *p = pParse->pZombieTab;
  150531. pParse->pZombieTab = p->pNextZombie;
  150532. sqlite3DeleteTable(db, p);
  150533. }
  150534. db->pParse = pParse->pParentParse;
  150535. pParse->pParentParse = 0;
  150536. assert( nErr==0 || pParse->rc!=SQLITE_OK );
  150537. return nErr;
  150538. }
  150539. #ifdef SQLITE_ENABLE_NORMALIZE
  150540. /*
  150541. ** Insert a single space character into pStr if the current string
  150542. ** ends with an identifier
  150543. */
  150544. static void addSpaceSeparator(sqlite3_str *pStr){
  150545. if( pStr->nChar && sqlite3IsIdChar(pStr->zText[pStr->nChar-1]) ){
  150546. sqlite3_str_append(pStr, " ", 1);
  150547. }
  150548. }
  150549. /*
  150550. ** Compute a normalization of the SQL given by zSql[0..nSql-1]. Return
  150551. ** the normalization in space obtained from sqlite3DbMalloc(). Or return
  150552. ** NULL if anything goes wrong or if zSql is NULL.
  150553. */
  150554. SQLITE_PRIVATE char *sqlite3Normalize(
  150555. Vdbe *pVdbe, /* VM being reprepared */
  150556. const char *zSql /* The original SQL string */
  150557. ){
  150558. sqlite3 *db; /* The database connection */
  150559. int i; /* Next unread byte of zSql[] */
  150560. int n; /* length of current token */
  150561. int tokenType; /* type of current token */
  150562. int prevType = 0; /* Previous non-whitespace token */
  150563. int nParen; /* Number of nested levels of parentheses */
  150564. int iStartIN; /* Start of RHS of IN operator in z[] */
  150565. int nParenAtIN; /* Value of nParent at start of RHS of IN operator */
  150566. u32 j; /* Bytes of normalized SQL generated so far */
  150567. sqlite3_str *pStr; /* The normalized SQL string under construction */
  150568. db = sqlite3VdbeDb(pVdbe);
  150569. tokenType = -1;
  150570. nParen = iStartIN = nParenAtIN = 0;
  150571. pStr = sqlite3_str_new(db);
  150572. assert( pStr!=0 ); /* sqlite3_str_new() never returns NULL */
  150573. for(i=0; zSql[i] && pStr->accError==0; i+=n){
  150574. if( tokenType!=TK_SPACE ){
  150575. prevType = tokenType;
  150576. }
  150577. n = sqlite3GetToken((unsigned char*)zSql+i, &tokenType);
  150578. if( NEVER(n<=0) ) break;
  150579. switch( tokenType ){
  150580. case TK_SPACE: {
  150581. break;
  150582. }
  150583. case TK_NULL: {
  150584. if( prevType==TK_IS || prevType==TK_NOT ){
  150585. sqlite3_str_append(pStr, " NULL", 5);
  150586. break;
  150587. }
  150588. /* Fall through */
  150589. }
  150590. case TK_STRING:
  150591. case TK_INTEGER:
  150592. case TK_FLOAT:
  150593. case TK_VARIABLE:
  150594. case TK_BLOB: {
  150595. sqlite3_str_append(pStr, "?", 1);
  150596. break;
  150597. }
  150598. case TK_LP: {
  150599. nParen++;
  150600. if( prevType==TK_IN ){
  150601. iStartIN = pStr->nChar;
  150602. nParenAtIN = nParen;
  150603. }
  150604. sqlite3_str_append(pStr, "(", 1);
  150605. break;
  150606. }
  150607. case TK_RP: {
  150608. if( iStartIN>0 && nParen==nParenAtIN ){
  150609. assert( pStr->nChar>=(u32)iStartIN );
  150610. pStr->nChar = iStartIN+1;
  150611. sqlite3_str_append(pStr, "?,?,?", 5);
  150612. iStartIN = 0;
  150613. }
  150614. nParen--;
  150615. sqlite3_str_append(pStr, ")", 1);
  150616. break;
  150617. }
  150618. case TK_ID: {
  150619. iStartIN = 0;
  150620. j = pStr->nChar;
  150621. if( sqlite3Isquote(zSql[i]) ){
  150622. char *zId = sqlite3DbStrNDup(db, zSql+i, n);
  150623. int nId;
  150624. int eType = 0;
  150625. if( zId==0 ) break;
  150626. sqlite3Dequote(zId);
  150627. if( zSql[i]=='"' && sqlite3VdbeUsesDoubleQuotedString(pVdbe, zId) ){
  150628. sqlite3_str_append(pStr, "?", 1);
  150629. sqlite3DbFree(db, zId);
  150630. break;
  150631. }
  150632. nId = sqlite3Strlen30(zId);
  150633. if( sqlite3GetToken((u8*)zId, &eType)==nId && eType==TK_ID ){
  150634. addSpaceSeparator(pStr);
  150635. sqlite3_str_append(pStr, zId, nId);
  150636. }else{
  150637. sqlite3_str_appendf(pStr, "\"%w\"", zId);
  150638. }
  150639. sqlite3DbFree(db, zId);
  150640. }else{
  150641. addSpaceSeparator(pStr);
  150642. sqlite3_str_append(pStr, zSql+i, n);
  150643. }
  150644. while( j<pStr->nChar ){
  150645. pStr->zText[j] = sqlite3Tolower(pStr->zText[j]);
  150646. j++;
  150647. }
  150648. break;
  150649. }
  150650. case TK_SELECT: {
  150651. iStartIN = 0;
  150652. /* fall through */
  150653. }
  150654. default: {
  150655. if( sqlite3IsIdChar(zSql[i]) ) addSpaceSeparator(pStr);
  150656. j = pStr->nChar;
  150657. sqlite3_str_append(pStr, zSql+i, n);
  150658. while( j<pStr->nChar ){
  150659. pStr->zText[j] = sqlite3Toupper(pStr->zText[j]);
  150660. j++;
  150661. }
  150662. break;
  150663. }
  150664. }
  150665. }
  150666. if( tokenType!=TK_SEMI ) sqlite3_str_append(pStr, ";", 1);
  150667. return sqlite3_str_finish(pStr);
  150668. }
  150669. #endif /* SQLITE_ENABLE_NORMALIZE */
  150670. /************** End of tokenize.c ********************************************/
  150671. /************** Begin file complete.c ****************************************/
  150672. /*
  150673. ** 2001 September 15
  150674. **
  150675. ** The author disclaims copyright to this source code. In place of
  150676. ** a legal notice, here is a blessing:
  150677. **
  150678. ** May you do good and not evil.
  150679. ** May you find forgiveness for yourself and forgive others.
  150680. ** May you share freely, never taking more than you give.
  150681. **
  150682. *************************************************************************
  150683. ** An tokenizer for SQL
  150684. **
  150685. ** This file contains C code that implements the sqlite3_complete() API.
  150686. ** This code used to be part of the tokenizer.c source file. But by
  150687. ** separating it out, the code will be automatically omitted from
  150688. ** static links that do not use it.
  150689. */
  150690. /* #include "sqliteInt.h" */
  150691. #ifndef SQLITE_OMIT_COMPLETE
  150692. /*
  150693. ** This is defined in tokenize.c. We just have to import the definition.
  150694. */
  150695. #ifndef SQLITE_AMALGAMATION
  150696. #ifdef SQLITE_ASCII
  150697. #define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
  150698. #endif
  150699. #ifdef SQLITE_EBCDIC
  150700. SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];
  150701. #define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
  150702. #endif
  150703. #endif /* SQLITE_AMALGAMATION */
  150704. /*
  150705. ** Token types used by the sqlite3_complete() routine. See the header
  150706. ** comments on that procedure for additional information.
  150707. */
  150708. #define tkSEMI 0
  150709. #define tkWS 1
  150710. #define tkOTHER 2
  150711. #ifndef SQLITE_OMIT_TRIGGER
  150712. #define tkEXPLAIN 3
  150713. #define tkCREATE 4
  150714. #define tkTEMP 5
  150715. #define tkTRIGGER 6
  150716. #define tkEND 7
  150717. #endif
  150718. /*
  150719. ** Return TRUE if the given SQL string ends in a semicolon.
  150720. **
  150721. ** Special handling is require for CREATE TRIGGER statements.
  150722. ** Whenever the CREATE TRIGGER keywords are seen, the statement
  150723. ** must end with ";END;".
  150724. **
  150725. ** This implementation uses a state machine with 8 states:
  150726. **
  150727. ** (0) INVALID We have not yet seen a non-whitespace character.
  150728. **
  150729. ** (1) START At the beginning or end of an SQL statement. This routine
  150730. ** returns 1 if it ends in the START state and 0 if it ends
  150731. ** in any other state.
  150732. **
  150733. ** (2) NORMAL We are in the middle of statement which ends with a single
  150734. ** semicolon.
  150735. **
  150736. ** (3) EXPLAIN The keyword EXPLAIN has been seen at the beginning of
  150737. ** a statement.
  150738. **
  150739. ** (4) CREATE The keyword CREATE has been seen at the beginning of a
  150740. ** statement, possibly preceded by EXPLAIN and/or followed by
  150741. ** TEMP or TEMPORARY
  150742. **
  150743. ** (5) TRIGGER We are in the middle of a trigger definition that must be
  150744. ** ended by a semicolon, the keyword END, and another semicolon.
  150745. **
  150746. ** (6) SEMI We've seen the first semicolon in the ";END;" that occurs at
  150747. ** the end of a trigger definition.
  150748. **
  150749. ** (7) END We've seen the ";END" of the ";END;" that occurs at the end
  150750. ** of a trigger definition.
  150751. **
  150752. ** Transitions between states above are determined by tokens extracted
  150753. ** from the input. The following tokens are significant:
  150754. **
  150755. ** (0) tkSEMI A semicolon.
  150756. ** (1) tkWS Whitespace.
  150757. ** (2) tkOTHER Any other SQL token.
  150758. ** (3) tkEXPLAIN The "explain" keyword.
  150759. ** (4) tkCREATE The "create" keyword.
  150760. ** (5) tkTEMP The "temp" or "temporary" keyword.
  150761. ** (6) tkTRIGGER The "trigger" keyword.
  150762. ** (7) tkEND The "end" keyword.
  150763. **
  150764. ** Whitespace never causes a state transition and is always ignored.
  150765. ** This means that a SQL string of all whitespace is invalid.
  150766. **
  150767. ** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
  150768. ** to recognize the end of a trigger can be omitted. All we have to do
  150769. ** is look for a semicolon that is not part of an string or comment.
  150770. */
  150771. SQLITE_API int sqlite3_complete(const char *zSql){
  150772. u8 state = 0; /* Current state, using numbers defined in header comment */
  150773. u8 token; /* Value of the next token */
  150774. #ifndef SQLITE_OMIT_TRIGGER
  150775. /* A complex statement machine used to detect the end of a CREATE TRIGGER
  150776. ** statement. This is the normal case.
  150777. */
  150778. static const u8 trans[8][8] = {
  150779. /* Token: */
  150780. /* State: ** SEMI WS OTHER EXPLAIN CREATE TEMP TRIGGER END */
  150781. /* 0 INVALID: */ { 1, 0, 2, 3, 4, 2, 2, 2, },
  150782. /* 1 START: */ { 1, 1, 2, 3, 4, 2, 2, 2, },
  150783. /* 2 NORMAL: */ { 1, 2, 2, 2, 2, 2, 2, 2, },
  150784. /* 3 EXPLAIN: */ { 1, 3, 3, 2, 4, 2, 2, 2, },
  150785. /* 4 CREATE: */ { 1, 4, 2, 2, 2, 4, 5, 2, },
  150786. /* 5 TRIGGER: */ { 6, 5, 5, 5, 5, 5, 5, 5, },
  150787. /* 6 SEMI: */ { 6, 6, 5, 5, 5, 5, 5, 7, },
  150788. /* 7 END: */ { 1, 7, 5, 5, 5, 5, 5, 5, },
  150789. };
  150790. #else
  150791. /* If triggers are not supported by this compile then the statement machine
  150792. ** used to detect the end of a statement is much simpler
  150793. */
  150794. static const u8 trans[3][3] = {
  150795. /* Token: */
  150796. /* State: ** SEMI WS OTHER */
  150797. /* 0 INVALID: */ { 1, 0, 2, },
  150798. /* 1 START: */ { 1, 1, 2, },
  150799. /* 2 NORMAL: */ { 1, 2, 2, },
  150800. };
  150801. #endif /* SQLITE_OMIT_TRIGGER */
  150802. #ifdef SQLITE_ENABLE_API_ARMOR
  150803. if( zSql==0 ){
  150804. (void)SQLITE_MISUSE_BKPT;
  150805. return 0;
  150806. }
  150807. #endif
  150808. while( *zSql ){
  150809. switch( *zSql ){
  150810. case ';': { /* A semicolon */
  150811. token = tkSEMI;
  150812. break;
  150813. }
  150814. case ' ':
  150815. case '\r':
  150816. case '\t':
  150817. case '\n':
  150818. case '\f': { /* White space is ignored */
  150819. token = tkWS;
  150820. break;
  150821. }
  150822. case '/': { /* C-style comments */
  150823. if( zSql[1]!='*' ){
  150824. token = tkOTHER;
  150825. break;
  150826. }
  150827. zSql += 2;
  150828. while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
  150829. if( zSql[0]==0 ) return 0;
  150830. zSql++;
  150831. token = tkWS;
  150832. break;
  150833. }
  150834. case '-': { /* SQL-style comments from "--" to end of line */
  150835. if( zSql[1]!='-' ){
  150836. token = tkOTHER;
  150837. break;
  150838. }
  150839. while( *zSql && *zSql!='\n' ){ zSql++; }
  150840. if( *zSql==0 ) return state==1;
  150841. token = tkWS;
  150842. break;
  150843. }
  150844. case '[': { /* Microsoft-style identifiers in [...] */
  150845. zSql++;
  150846. while( *zSql && *zSql!=']' ){ zSql++; }
  150847. if( *zSql==0 ) return 0;
  150848. token = tkOTHER;
  150849. break;
  150850. }
  150851. case '`': /* Grave-accent quoted symbols used by MySQL */
  150852. case '"': /* single- and double-quoted strings */
  150853. case '\'': {
  150854. int c = *zSql;
  150855. zSql++;
  150856. while( *zSql && *zSql!=c ){ zSql++; }
  150857. if( *zSql==0 ) return 0;
  150858. token = tkOTHER;
  150859. break;
  150860. }
  150861. default: {
  150862. #ifdef SQLITE_EBCDIC
  150863. unsigned char c;
  150864. #endif
  150865. if( IdChar((u8)*zSql) ){
  150866. /* Keywords and unquoted identifiers */
  150867. int nId;
  150868. for(nId=1; IdChar(zSql[nId]); nId++){}
  150869. #ifdef SQLITE_OMIT_TRIGGER
  150870. token = tkOTHER;
  150871. #else
  150872. switch( *zSql ){
  150873. case 'c': case 'C': {
  150874. if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
  150875. token = tkCREATE;
  150876. }else{
  150877. token = tkOTHER;
  150878. }
  150879. break;
  150880. }
  150881. case 't': case 'T': {
  150882. if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
  150883. token = tkTRIGGER;
  150884. }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
  150885. token = tkTEMP;
  150886. }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
  150887. token = tkTEMP;
  150888. }else{
  150889. token = tkOTHER;
  150890. }
  150891. break;
  150892. }
  150893. case 'e': case 'E': {
  150894. if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
  150895. token = tkEND;
  150896. }else
  150897. #ifndef SQLITE_OMIT_EXPLAIN
  150898. if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
  150899. token = tkEXPLAIN;
  150900. }else
  150901. #endif
  150902. {
  150903. token = tkOTHER;
  150904. }
  150905. break;
  150906. }
  150907. default: {
  150908. token = tkOTHER;
  150909. break;
  150910. }
  150911. }
  150912. #endif /* SQLITE_OMIT_TRIGGER */
  150913. zSql += nId-1;
  150914. }else{
  150915. /* Operators and special symbols */
  150916. token = tkOTHER;
  150917. }
  150918. break;
  150919. }
  150920. }
  150921. state = trans[state][token];
  150922. zSql++;
  150923. }
  150924. return state==1;
  150925. }
  150926. #ifndef SQLITE_OMIT_UTF16
  150927. /*
  150928. ** This routine is the same as the sqlite3_complete() routine described
  150929. ** above, except that the parameter is required to be UTF-16 encoded, not
  150930. ** UTF-8.
  150931. */
  150932. SQLITE_API int sqlite3_complete16(const void *zSql){
  150933. sqlite3_value *pVal;
  150934. char const *zSql8;
  150935. int rc;
  150936. #ifndef SQLITE_OMIT_AUTOINIT
  150937. rc = sqlite3_initialize();
  150938. if( rc ) return rc;
  150939. #endif
  150940. pVal = sqlite3ValueNew(0);
  150941. sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
  150942. zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
  150943. if( zSql8 ){
  150944. rc = sqlite3_complete(zSql8);
  150945. }else{
  150946. rc = SQLITE_NOMEM_BKPT;
  150947. }
  150948. sqlite3ValueFree(pVal);
  150949. return rc & 0xff;
  150950. }
  150951. #endif /* SQLITE_OMIT_UTF16 */
  150952. #endif /* SQLITE_OMIT_COMPLETE */
  150953. /************** End of complete.c ********************************************/
  150954. /************** Begin file main.c ********************************************/
  150955. /*
  150956. ** 2001 September 15
  150957. **
  150958. ** The author disclaims copyright to this source code. In place of
  150959. ** a legal notice, here is a blessing:
  150960. **
  150961. ** May you do good and not evil.
  150962. ** May you find forgiveness for yourself and forgive others.
  150963. ** May you share freely, never taking more than you give.
  150964. **
  150965. *************************************************************************
  150966. ** Main file for the SQLite library. The routines in this file
  150967. ** implement the programmer interface to the library. Routines in
  150968. ** other files are for internal use by SQLite and should not be
  150969. ** accessed by users of the library.
  150970. */
  150971. /* #include "sqliteInt.h" */
  150972. #ifdef SQLITE_ENABLE_FTS3
  150973. /************** Include fts3.h in the middle of main.c ***********************/
  150974. /************** Begin file fts3.h ********************************************/
  150975. /*
  150976. ** 2006 Oct 10
  150977. **
  150978. ** The author disclaims copyright to this source code. In place of
  150979. ** a legal notice, here is a blessing:
  150980. **
  150981. ** May you do good and not evil.
  150982. ** May you find forgiveness for yourself and forgive others.
  150983. ** May you share freely, never taking more than you give.
  150984. **
  150985. ******************************************************************************
  150986. **
  150987. ** This header file is used by programs that want to link against the
  150988. ** FTS3 library. All it does is declare the sqlite3Fts3Init() interface.
  150989. */
  150990. /* #include "sqlite3.h" */
  150991. #if 0
  150992. extern "C" {
  150993. #endif /* __cplusplus */
  150994. SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db);
  150995. #if 0
  150996. } /* extern "C" */
  150997. #endif /* __cplusplus */
  150998. /************** End of fts3.h ************************************************/
  150999. /************** Continuing where we left off in main.c ***********************/
  151000. #endif
  151001. #ifdef SQLITE_ENABLE_RTREE
  151002. /************** Include rtree.h in the middle of main.c **********************/
  151003. /************** Begin file rtree.h *******************************************/
  151004. /*
  151005. ** 2008 May 26
  151006. **
  151007. ** The author disclaims copyright to this source code. In place of
  151008. ** a legal notice, here is a blessing:
  151009. **
  151010. ** May you do good and not evil.
  151011. ** May you find forgiveness for yourself and forgive others.
  151012. ** May you share freely, never taking more than you give.
  151013. **
  151014. ******************************************************************************
  151015. **
  151016. ** This header file is used by programs that want to link against the
  151017. ** RTREE library. All it does is declare the sqlite3RtreeInit() interface.
  151018. */
  151019. /* #include "sqlite3.h" */
  151020. #ifdef SQLITE_OMIT_VIRTUALTABLE
  151021. # undef SQLITE_ENABLE_RTREE
  151022. #endif
  151023. #if 0
  151024. extern "C" {
  151025. #endif /* __cplusplus */
  151026. SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db);
  151027. #if 0
  151028. } /* extern "C" */
  151029. #endif /* __cplusplus */
  151030. /************** End of rtree.h ***********************************************/
  151031. /************** Continuing where we left off in main.c ***********************/
  151032. #endif
  151033. #if defined(SQLITE_ENABLE_ICU) || defined(SQLITE_ENABLE_ICU_COLLATIONS)
  151034. /************** Include sqliteicu.h in the middle of main.c ******************/
  151035. /************** Begin file sqliteicu.h ***************************************/
  151036. /*
  151037. ** 2008 May 26
  151038. **
  151039. ** The author disclaims copyright to this source code. In place of
  151040. ** a legal notice, here is a blessing:
  151041. **
  151042. ** May you do good and not evil.
  151043. ** May you find forgiveness for yourself and forgive others.
  151044. ** May you share freely, never taking more than you give.
  151045. **
  151046. ******************************************************************************
  151047. **
  151048. ** This header file is used by programs that want to link against the
  151049. ** ICU extension. All it does is declare the sqlite3IcuInit() interface.
  151050. */
  151051. /* #include "sqlite3.h" */
  151052. #if 0
  151053. extern "C" {
  151054. #endif /* __cplusplus */
  151055. SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db);
  151056. #if 0
  151057. } /* extern "C" */
  151058. #endif /* __cplusplus */
  151059. /************** End of sqliteicu.h *******************************************/
  151060. /************** Continuing where we left off in main.c ***********************/
  151061. #endif
  151062. /*
  151063. ** This is an extension initializer that is a no-op and always
  151064. ** succeeds, except that it fails if the fault-simulation is set
  151065. ** to 500.
  151066. */
  151067. static int sqlite3TestExtInit(sqlite3 *db){
  151068. (void)db;
  151069. return sqlite3FaultSim(500);
  151070. }
  151071. /*
  151072. ** Forward declarations of external module initializer functions
  151073. ** for modules that need them.
  151074. */
  151075. #ifdef SQLITE_ENABLE_FTS1
  151076. SQLITE_PRIVATE int sqlite3Fts1Init(sqlite3*);
  151077. #endif
  151078. #ifdef SQLITE_ENABLE_FTS2
  151079. SQLITE_PRIVATE int sqlite3Fts2Init(sqlite3*);
  151080. #endif
  151081. #ifdef SQLITE_ENABLE_FTS5
  151082. SQLITE_PRIVATE int sqlite3Fts5Init(sqlite3*);
  151083. #endif
  151084. #ifdef SQLITE_ENABLE_JSON1
  151085. SQLITE_PRIVATE int sqlite3Json1Init(sqlite3*);
  151086. #endif
  151087. #ifdef SQLITE_ENABLE_STMTVTAB
  151088. SQLITE_PRIVATE int sqlite3StmtVtabInit(sqlite3*);
  151089. #endif
  151090. /*
  151091. ** An array of pointers to extension initializer functions for
  151092. ** built-in extensions.
  151093. */
  151094. static int (*const sqlite3BuiltinExtensions[])(sqlite3*) = {
  151095. #ifdef SQLITE_ENABLE_FTS1
  151096. sqlite3Fts1Init,
  151097. #endif
  151098. #ifdef SQLITE_ENABLE_FTS2
  151099. sqlite3Fts2Init,
  151100. #endif
  151101. #ifdef SQLITE_ENABLE_FTS3
  151102. sqlite3Fts3Init,
  151103. #endif
  151104. #ifdef SQLITE_ENABLE_FTS5
  151105. sqlite3Fts5Init,
  151106. #endif
  151107. #if defined(SQLITE_ENABLE_ICU) || defined(SQLITE_ENABLE_ICU_COLLATIONS)
  151108. sqlite3IcuInit,
  151109. #endif
  151110. #ifdef SQLITE_ENABLE_RTREE
  151111. sqlite3RtreeInit,
  151112. #endif
  151113. #ifdef SQLITE_ENABLE_DBPAGE_VTAB
  151114. sqlite3DbpageRegister,
  151115. #endif
  151116. #ifdef SQLITE_ENABLE_DBSTAT_VTAB
  151117. sqlite3DbstatRegister,
  151118. #endif
  151119. sqlite3TestExtInit,
  151120. #ifdef SQLITE_ENABLE_JSON1
  151121. sqlite3Json1Init,
  151122. #endif
  151123. #ifdef SQLITE_ENABLE_STMTVTAB
  151124. sqlite3StmtVtabInit,
  151125. #endif
  151126. #ifdef SQLITE_ENABLE_BYTECODE_VTAB
  151127. sqlite3VdbeBytecodeVtabInit,
  151128. #endif
  151129. };
  151130. #ifndef SQLITE_AMALGAMATION
  151131. /* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant
  151132. ** contains the text of SQLITE_VERSION macro.
  151133. */
  151134. SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
  151135. #endif
  151136. /* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns
  151137. ** a pointer to the to the sqlite3_version[] string constant.
  151138. */
  151139. SQLITE_API const char *sqlite3_libversion(void){ return sqlite3_version; }
  151140. /* IMPLEMENTATION-OF: R-25063-23286 The sqlite3_sourceid() function returns a
  151141. ** pointer to a string constant whose value is the same as the
  151142. ** SQLITE_SOURCE_ID C preprocessor macro. Except if SQLite is built using
  151143. ** an edited copy of the amalgamation, then the last four characters of
  151144. ** the hash might be different from SQLITE_SOURCE_ID.
  151145. */
  151146. /* SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; } */
  151147. /* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function
  151148. ** returns an integer equal to SQLITE_VERSION_NUMBER.
  151149. */
  151150. SQLITE_API int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
  151151. /* IMPLEMENTATION-OF: R-20790-14025 The sqlite3_threadsafe() function returns
  151152. ** zero if and only if SQLite was compiled with mutexing code omitted due to
  151153. ** the SQLITE_THREADSAFE compile-time option being set to 0.
  151154. */
  151155. SQLITE_API int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
  151156. /*
  151157. ** When compiling the test fixture or with debugging enabled (on Win32),
  151158. ** this variable being set to non-zero will cause OSTRACE macros to emit
  151159. ** extra diagnostic information.
  151160. */
  151161. #ifdef SQLITE_HAVE_OS_TRACE
  151162. # ifndef SQLITE_DEBUG_OS_TRACE
  151163. # define SQLITE_DEBUG_OS_TRACE 0
  151164. # endif
  151165. int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
  151166. #endif
  151167. #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
  151168. /*
  151169. ** If the following function pointer is not NULL and if
  151170. ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
  151171. ** I/O active are written using this function. These messages
  151172. ** are intended for debugging activity only.
  151173. */
  151174. SQLITE_API void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...) = 0;
  151175. #endif
  151176. /*
  151177. ** If the following global variable points to a string which is the
  151178. ** name of a directory, then that directory will be used to store
  151179. ** temporary files.
  151180. **
  151181. ** See also the "PRAGMA temp_store_directory" SQL command.
  151182. */
  151183. SQLITE_API char *sqlite3_temp_directory = 0;
  151184. /*
  151185. ** If the following global variable points to a string which is the
  151186. ** name of a directory, then that directory will be used to store
  151187. ** all database files specified with a relative pathname.
  151188. **
  151189. ** See also the "PRAGMA data_store_directory" SQL command.
  151190. */
  151191. SQLITE_API char *sqlite3_data_directory = 0;
  151192. /*
  151193. ** Initialize SQLite.
  151194. **
  151195. ** This routine must be called to initialize the memory allocation,
  151196. ** VFS, and mutex subsystems prior to doing any serious work with
  151197. ** SQLite. But as long as you do not compile with SQLITE_OMIT_AUTOINIT
  151198. ** this routine will be called automatically by key routines such as
  151199. ** sqlite3_open().
  151200. **
  151201. ** This routine is a no-op except on its very first call for the process,
  151202. ** or for the first call after a call to sqlite3_shutdown.
  151203. **
  151204. ** The first thread to call this routine runs the initialization to
  151205. ** completion. If subsequent threads call this routine before the first
  151206. ** thread has finished the initialization process, then the subsequent
  151207. ** threads must block until the first thread finishes with the initialization.
  151208. **
  151209. ** The first thread might call this routine recursively. Recursive
  151210. ** calls to this routine should not block, of course. Otherwise the
  151211. ** initialization process would never complete.
  151212. **
  151213. ** Let X be the first thread to enter this routine. Let Y be some other
  151214. ** thread. Then while the initial invocation of this routine by X is
  151215. ** incomplete, it is required that:
  151216. **
  151217. ** * Calls to this routine from Y must block until the outer-most
  151218. ** call by X completes.
  151219. **
  151220. ** * Recursive calls to this routine from thread X return immediately
  151221. ** without blocking.
  151222. */
  151223. SQLITE_API int sqlite3_initialize(void){
  151224. MUTEX_LOGIC( sqlite3_mutex *pMaster; ) /* The main static mutex */
  151225. int rc; /* Result code */
  151226. #ifdef SQLITE_EXTRA_INIT
  151227. int bRunExtraInit = 0; /* Extra initialization needed */
  151228. #endif
  151229. #ifdef SQLITE_OMIT_WSD
  151230. rc = sqlite3_wsd_init(4096, 24);
  151231. if( rc!=SQLITE_OK ){
  151232. return rc;
  151233. }
  151234. #endif
  151235. /* If the following assert() fails on some obscure processor/compiler
  151236. ** combination, the work-around is to set the correct pointer
  151237. ** size at compile-time using -DSQLITE_PTRSIZE=n compile-time option */
  151238. assert( SQLITE_PTRSIZE==sizeof(char*) );
  151239. /* If SQLite is already completely initialized, then this call
  151240. ** to sqlite3_initialize() should be a no-op. But the initialization
  151241. ** must be complete. So isInit must not be set until the very end
  151242. ** of this routine.
  151243. */
  151244. if( sqlite3GlobalConfig.isInit ){
  151245. sqlite3MemoryBarrier();
  151246. return SQLITE_OK;
  151247. }
  151248. /* Make sure the mutex subsystem is initialized. If unable to
  151249. ** initialize the mutex subsystem, return early with the error.
  151250. ** If the system is so sick that we are unable to allocate a mutex,
  151251. ** there is not much SQLite is going to be able to do.
  151252. **
  151253. ** The mutex subsystem must take care of serializing its own
  151254. ** initialization.
  151255. */
  151256. rc = sqlite3MutexInit();
  151257. if( rc ) return rc;
  151258. /* Initialize the malloc() system and the recursive pInitMutex mutex.
  151259. ** This operation is protected by the STATIC_MASTER mutex. Note that
  151260. ** MutexAlloc() is called for a static mutex prior to initializing the
  151261. ** malloc subsystem - this implies that the allocation of a static
  151262. ** mutex must not require support from the malloc subsystem.
  151263. */
  151264. MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
  151265. sqlite3_mutex_enter(pMaster);
  151266. sqlite3GlobalConfig.isMutexInit = 1;
  151267. if( !sqlite3GlobalConfig.isMallocInit ){
  151268. rc = sqlite3MallocInit();
  151269. }
  151270. if( rc==SQLITE_OK ){
  151271. sqlite3GlobalConfig.isMallocInit = 1;
  151272. if( !sqlite3GlobalConfig.pInitMutex ){
  151273. sqlite3GlobalConfig.pInitMutex =
  151274. sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
  151275. if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
  151276. rc = SQLITE_NOMEM_BKPT;
  151277. }
  151278. }
  151279. }
  151280. if( rc==SQLITE_OK ){
  151281. sqlite3GlobalConfig.nRefInitMutex++;
  151282. }
  151283. sqlite3_mutex_leave(pMaster);
  151284. /* If rc is not SQLITE_OK at this point, then either the malloc
  151285. ** subsystem could not be initialized or the system failed to allocate
  151286. ** the pInitMutex mutex. Return an error in either case. */
  151287. if( rc!=SQLITE_OK ){
  151288. return rc;
  151289. }
  151290. /* Do the rest of the initialization under the recursive mutex so
  151291. ** that we will be able to handle recursive calls into
  151292. ** sqlite3_initialize(). The recursive calls normally come through
  151293. ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
  151294. ** recursive calls might also be possible.
  151295. **
  151296. ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls
  151297. ** to the xInit method, so the xInit method need not be threadsafe.
  151298. **
  151299. ** The following mutex is what serializes access to the appdef pcache xInit
  151300. ** methods. The sqlite3_pcache_methods.xInit() all is embedded in the
  151301. ** call to sqlite3PcacheInitialize().
  151302. */
  151303. sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
  151304. if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
  151305. sqlite3GlobalConfig.inProgress = 1;
  151306. #ifdef SQLITE_ENABLE_SQLLOG
  151307. {
  151308. extern void sqlite3_init_sqllog(void);
  151309. sqlite3_init_sqllog();
  151310. }
  151311. #endif
  151312. memset(&sqlite3BuiltinFunctions, 0, sizeof(sqlite3BuiltinFunctions));
  151313. sqlite3RegisterBuiltinFunctions();
  151314. if( sqlite3GlobalConfig.isPCacheInit==0 ){
  151315. rc = sqlite3PcacheInitialize();
  151316. }
  151317. if( rc==SQLITE_OK ){
  151318. sqlite3GlobalConfig.isPCacheInit = 1;
  151319. rc = sqlite3OsInit();
  151320. }
  151321. #ifdef SQLITE_ENABLE_DESERIALIZE
  151322. if( rc==SQLITE_OK ){
  151323. rc = sqlite3MemdbInit();
  151324. }
  151325. #endif
  151326. if( rc==SQLITE_OK ){
  151327. sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage,
  151328. sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
  151329. sqlite3MemoryBarrier();
  151330. sqlite3GlobalConfig.isInit = 1;
  151331. #ifdef SQLITE_EXTRA_INIT
  151332. bRunExtraInit = 1;
  151333. #endif
  151334. }
  151335. sqlite3GlobalConfig.inProgress = 0;
  151336. }
  151337. sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
  151338. /* Go back under the static mutex and clean up the recursive
  151339. ** mutex to prevent a resource leak.
  151340. */
  151341. sqlite3_mutex_enter(pMaster);
  151342. sqlite3GlobalConfig.nRefInitMutex--;
  151343. if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
  151344. assert( sqlite3GlobalConfig.nRefInitMutex==0 );
  151345. sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
  151346. sqlite3GlobalConfig.pInitMutex = 0;
  151347. }
  151348. sqlite3_mutex_leave(pMaster);
  151349. /* The following is just a sanity check to make sure SQLite has
  151350. ** been compiled correctly. It is important to run this code, but
  151351. ** we don't want to run it too often and soak up CPU cycles for no
  151352. ** reason. So we run it once during initialization.
  151353. */
  151354. #ifndef NDEBUG
  151355. #ifndef SQLITE_OMIT_FLOATING_POINT
  151356. /* This section of code's only "output" is via assert() statements. */
  151357. if( rc==SQLITE_OK ){
  151358. u64 x = (((u64)1)<<63)-1;
  151359. double y;
  151360. assert(sizeof(x)==8);
  151361. assert(sizeof(x)==sizeof(y));
  151362. memcpy(&y, &x, 8);
  151363. assert( sqlite3IsNaN(y) );
  151364. }
  151365. #endif
  151366. #endif
  151367. /* Do extra initialization steps requested by the SQLITE_EXTRA_INIT
  151368. ** compile-time option.
  151369. */
  151370. #ifdef SQLITE_EXTRA_INIT
  151371. if( bRunExtraInit ){
  151372. int SQLITE_EXTRA_INIT(const char*);
  151373. rc = SQLITE_EXTRA_INIT(0);
  151374. }
  151375. #endif
  151376. return rc;
  151377. }
  151378. /*
  151379. ** Undo the effects of sqlite3_initialize(). Must not be called while
  151380. ** there are outstanding database connections or memory allocations or
  151381. ** while any part of SQLite is otherwise in use in any thread. This
  151382. ** routine is not threadsafe. But it is safe to invoke this routine
  151383. ** on when SQLite is already shut down. If SQLite is already shut down
  151384. ** when this routine is invoked, then this routine is a harmless no-op.
  151385. */
  151386. SQLITE_API int sqlite3_shutdown(void){
  151387. #ifdef SQLITE_OMIT_WSD
  151388. int rc = sqlite3_wsd_init(4096, 24);
  151389. if( rc!=SQLITE_OK ){
  151390. return rc;
  151391. }
  151392. #endif
  151393. if( sqlite3GlobalConfig.isInit ){
  151394. #ifdef SQLITE_EXTRA_SHUTDOWN
  151395. void SQLITE_EXTRA_SHUTDOWN(void);
  151396. SQLITE_EXTRA_SHUTDOWN();
  151397. #endif
  151398. sqlite3_os_end();
  151399. sqlite3_reset_auto_extension();
  151400. sqlite3GlobalConfig.isInit = 0;
  151401. }
  151402. if( sqlite3GlobalConfig.isPCacheInit ){
  151403. sqlite3PcacheShutdown();
  151404. sqlite3GlobalConfig.isPCacheInit = 0;
  151405. }
  151406. if( sqlite3GlobalConfig.isMallocInit ){
  151407. sqlite3MallocEnd();
  151408. sqlite3GlobalConfig.isMallocInit = 0;
  151409. #ifndef SQLITE_OMIT_SHUTDOWN_DIRECTORIES
  151410. /* The heap subsystem has now been shutdown and these values are supposed
  151411. ** to be NULL or point to memory that was obtained from sqlite3_malloc(),
  151412. ** which would rely on that heap subsystem; therefore, make sure these
  151413. ** values cannot refer to heap memory that was just invalidated when the
  151414. ** heap subsystem was shutdown. This is only done if the current call to
  151415. ** this function resulted in the heap subsystem actually being shutdown.
  151416. */
  151417. sqlite3_data_directory = 0;
  151418. sqlite3_temp_directory = 0;
  151419. #endif
  151420. }
  151421. if( sqlite3GlobalConfig.isMutexInit ){
  151422. sqlite3MutexEnd();
  151423. sqlite3GlobalConfig.isMutexInit = 0;
  151424. }
  151425. return SQLITE_OK;
  151426. }
  151427. /*
  151428. ** This API allows applications to modify the global configuration of
  151429. ** the SQLite library at run-time.
  151430. **
  151431. ** This routine should only be called when there are no outstanding
  151432. ** database connections or memory allocations. This routine is not
  151433. ** threadsafe. Failure to heed these warnings can lead to unpredictable
  151434. ** behavior.
  151435. */
  151436. SQLITE_API int sqlite3_config(int op, ...){
  151437. va_list ap;
  151438. int rc = SQLITE_OK;
  151439. /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
  151440. ** the SQLite library is in use. */
  151441. if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT;
  151442. va_start(ap, op);
  151443. switch( op ){
  151444. /* Mutex configuration options are only available in a threadsafe
  151445. ** compile.
  151446. */
  151447. #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-54466-46756 */
  151448. case SQLITE_CONFIG_SINGLETHREAD: {
  151449. /* EVIDENCE-OF: R-02748-19096 This option sets the threading mode to
  151450. ** Single-thread. */
  151451. sqlite3GlobalConfig.bCoreMutex = 0; /* Disable mutex on core */
  151452. sqlite3GlobalConfig.bFullMutex = 0; /* Disable mutex on connections */
  151453. break;
  151454. }
  151455. #endif
  151456. #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-20520-54086 */
  151457. case SQLITE_CONFIG_MULTITHREAD: {
  151458. /* EVIDENCE-OF: R-14374-42468 This option sets the threading mode to
  151459. ** Multi-thread. */
  151460. sqlite3GlobalConfig.bCoreMutex = 1; /* Enable mutex on core */
  151461. sqlite3GlobalConfig.bFullMutex = 0; /* Disable mutex on connections */
  151462. break;
  151463. }
  151464. #endif
  151465. #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-59593-21810 */
  151466. case SQLITE_CONFIG_SERIALIZED: {
  151467. /* EVIDENCE-OF: R-41220-51800 This option sets the threading mode to
  151468. ** Serialized. */
  151469. sqlite3GlobalConfig.bCoreMutex = 1; /* Enable mutex on core */
  151470. sqlite3GlobalConfig.bFullMutex = 1; /* Enable mutex on connections */
  151471. break;
  151472. }
  151473. #endif
  151474. #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-63666-48755 */
  151475. case SQLITE_CONFIG_MUTEX: {
  151476. /* Specify an alternative mutex implementation */
  151477. sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
  151478. break;
  151479. }
  151480. #endif
  151481. #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-14450-37597 */
  151482. case SQLITE_CONFIG_GETMUTEX: {
  151483. /* Retrieve the current mutex implementation */
  151484. *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
  151485. break;
  151486. }
  151487. #endif
  151488. case SQLITE_CONFIG_MALLOC: {
  151489. /* EVIDENCE-OF: R-55594-21030 The SQLITE_CONFIG_MALLOC option takes a
  151490. ** single argument which is a pointer to an instance of the
  151491. ** sqlite3_mem_methods structure. The argument specifies alternative
  151492. ** low-level memory allocation routines to be used in place of the memory
  151493. ** allocation routines built into SQLite. */
  151494. sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
  151495. break;
  151496. }
  151497. case SQLITE_CONFIG_GETMALLOC: {
  151498. /* EVIDENCE-OF: R-51213-46414 The SQLITE_CONFIG_GETMALLOC option takes a
  151499. ** single argument which is a pointer to an instance of the
  151500. ** sqlite3_mem_methods structure. The sqlite3_mem_methods structure is
  151501. ** filled with the currently defined memory allocation routines. */
  151502. if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
  151503. *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
  151504. break;
  151505. }
  151506. case SQLITE_CONFIG_MEMSTATUS: {
  151507. /* EVIDENCE-OF: R-61275-35157 The SQLITE_CONFIG_MEMSTATUS option takes
  151508. ** single argument of type int, interpreted as a boolean, which enables
  151509. ** or disables the collection of memory allocation statistics. */
  151510. sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
  151511. break;
  151512. }
  151513. case SQLITE_CONFIG_SMALL_MALLOC: {
  151514. sqlite3GlobalConfig.bSmallMalloc = va_arg(ap, int);
  151515. break;
  151516. }
  151517. case SQLITE_CONFIG_PAGECACHE: {
  151518. /* EVIDENCE-OF: R-18761-36601 There are three arguments to
  151519. ** SQLITE_CONFIG_PAGECACHE: A pointer to 8-byte aligned memory (pMem),
  151520. ** the size of each page cache line (sz), and the number of cache lines
  151521. ** (N). */
  151522. sqlite3GlobalConfig.pPage = va_arg(ap, void*);
  151523. sqlite3GlobalConfig.szPage = va_arg(ap, int);
  151524. sqlite3GlobalConfig.nPage = va_arg(ap, int);
  151525. break;
  151526. }
  151527. case SQLITE_CONFIG_PCACHE_HDRSZ: {
  151528. /* EVIDENCE-OF: R-39100-27317 The SQLITE_CONFIG_PCACHE_HDRSZ option takes
  151529. ** a single parameter which is a pointer to an integer and writes into
  151530. ** that integer the number of extra bytes per page required for each page
  151531. ** in SQLITE_CONFIG_PAGECACHE. */
  151532. *va_arg(ap, int*) =
  151533. sqlite3HeaderSizeBtree() +
  151534. sqlite3HeaderSizePcache() +
  151535. sqlite3HeaderSizePcache1();
  151536. break;
  151537. }
  151538. case SQLITE_CONFIG_PCACHE: {
  151539. /* no-op */
  151540. break;
  151541. }
  151542. case SQLITE_CONFIG_GETPCACHE: {
  151543. /* now an error */
  151544. rc = SQLITE_ERROR;
  151545. break;
  151546. }
  151547. case SQLITE_CONFIG_PCACHE2: {
  151548. /* EVIDENCE-OF: R-63325-48378 The SQLITE_CONFIG_PCACHE2 option takes a
  151549. ** single argument which is a pointer to an sqlite3_pcache_methods2
  151550. ** object. This object specifies the interface to a custom page cache
  151551. ** implementation. */
  151552. sqlite3GlobalConfig.pcache2 = *va_arg(ap, sqlite3_pcache_methods2*);
  151553. break;
  151554. }
  151555. case SQLITE_CONFIG_GETPCACHE2: {
  151556. /* EVIDENCE-OF: R-22035-46182 The SQLITE_CONFIG_GETPCACHE2 option takes a
  151557. ** single argument which is a pointer to an sqlite3_pcache_methods2
  151558. ** object. SQLite copies of the current page cache implementation into
  151559. ** that object. */
  151560. if( sqlite3GlobalConfig.pcache2.xInit==0 ){
  151561. sqlite3PCacheSetDefault();
  151562. }
  151563. *va_arg(ap, sqlite3_pcache_methods2*) = sqlite3GlobalConfig.pcache2;
  151564. break;
  151565. }
  151566. /* EVIDENCE-OF: R-06626-12911 The SQLITE_CONFIG_HEAP option is only
  151567. ** available if SQLite is compiled with either SQLITE_ENABLE_MEMSYS3 or
  151568. ** SQLITE_ENABLE_MEMSYS5 and returns SQLITE_ERROR if invoked otherwise. */
  151569. #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
  151570. case SQLITE_CONFIG_HEAP: {
  151571. /* EVIDENCE-OF: R-19854-42126 There are three arguments to
  151572. ** SQLITE_CONFIG_HEAP: An 8-byte aligned pointer to the memory, the
  151573. ** number of bytes in the memory buffer, and the minimum allocation size.
  151574. */
  151575. sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
  151576. sqlite3GlobalConfig.nHeap = va_arg(ap, int);
  151577. sqlite3GlobalConfig.mnReq = va_arg(ap, int);
  151578. if( sqlite3GlobalConfig.mnReq<1 ){
  151579. sqlite3GlobalConfig.mnReq = 1;
  151580. }else if( sqlite3GlobalConfig.mnReq>(1<<12) ){
  151581. /* cap min request size at 2^12 */
  151582. sqlite3GlobalConfig.mnReq = (1<<12);
  151583. }
  151584. if( sqlite3GlobalConfig.pHeap==0 ){
  151585. /* EVIDENCE-OF: R-49920-60189 If the first pointer (the memory pointer)
  151586. ** is NULL, then SQLite reverts to using its default memory allocator
  151587. ** (the system malloc() implementation), undoing any prior invocation of
  151588. ** SQLITE_CONFIG_MALLOC.
  151589. **
  151590. ** Setting sqlite3GlobalConfig.m to all zeros will cause malloc to
  151591. ** revert to its default implementation when sqlite3_initialize() is run
  151592. */
  151593. memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
  151594. }else{
  151595. /* EVIDENCE-OF: R-61006-08918 If the memory pointer is not NULL then the
  151596. ** alternative memory allocator is engaged to handle all of SQLites
  151597. ** memory allocation needs. */
  151598. #ifdef SQLITE_ENABLE_MEMSYS3
  151599. sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
  151600. #endif
  151601. #ifdef SQLITE_ENABLE_MEMSYS5
  151602. sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
  151603. #endif
  151604. }
  151605. break;
  151606. }
  151607. #endif
  151608. case SQLITE_CONFIG_LOOKASIDE: {
  151609. sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
  151610. sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
  151611. break;
  151612. }
  151613. /* Record a pointer to the logger function and its first argument.
  151614. ** The default is NULL. Logging is disabled if the function pointer is
  151615. ** NULL.
  151616. */
  151617. case SQLITE_CONFIG_LOG: {
  151618. /* MSVC is picky about pulling func ptrs from va lists.
  151619. ** http://support.microsoft.com/kb/47961
  151620. ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
  151621. */
  151622. typedef void(*LOGFUNC_t)(void*,int,const char*);
  151623. sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t);
  151624. sqlite3GlobalConfig.pLogArg = va_arg(ap, void*);
  151625. break;
  151626. }
  151627. /* EVIDENCE-OF: R-55548-33817 The compile-time setting for URI filenames
  151628. ** can be changed at start-time using the
  151629. ** sqlite3_config(SQLITE_CONFIG_URI,1) or
  151630. ** sqlite3_config(SQLITE_CONFIG_URI,0) configuration calls.
  151631. */
  151632. case SQLITE_CONFIG_URI: {
  151633. /* EVIDENCE-OF: R-25451-61125 The SQLITE_CONFIG_URI option takes a single
  151634. ** argument of type int. If non-zero, then URI handling is globally
  151635. ** enabled. If the parameter is zero, then URI handling is globally
  151636. ** disabled. */
  151637. sqlite3GlobalConfig.bOpenUri = va_arg(ap, int);
  151638. break;
  151639. }
  151640. case SQLITE_CONFIG_COVERING_INDEX_SCAN: {
  151641. /* EVIDENCE-OF: R-36592-02772 The SQLITE_CONFIG_COVERING_INDEX_SCAN
  151642. ** option takes a single integer argument which is interpreted as a
  151643. ** boolean in order to enable or disable the use of covering indices for
  151644. ** full table scans in the query optimizer. */
  151645. sqlite3GlobalConfig.bUseCis = va_arg(ap, int);
  151646. break;
  151647. }
  151648. #ifdef SQLITE_ENABLE_SQLLOG
  151649. case SQLITE_CONFIG_SQLLOG: {
  151650. typedef void(*SQLLOGFUNC_t)(void*, sqlite3*, const char*, int);
  151651. sqlite3GlobalConfig.xSqllog = va_arg(ap, SQLLOGFUNC_t);
  151652. sqlite3GlobalConfig.pSqllogArg = va_arg(ap, void *);
  151653. break;
  151654. }
  151655. #endif
  151656. case SQLITE_CONFIG_MMAP_SIZE: {
  151657. /* EVIDENCE-OF: R-58063-38258 SQLITE_CONFIG_MMAP_SIZE takes two 64-bit
  151658. ** integer (sqlite3_int64) values that are the default mmap size limit
  151659. ** (the default setting for PRAGMA mmap_size) and the maximum allowed
  151660. ** mmap size limit. */
  151661. sqlite3_int64 szMmap = va_arg(ap, sqlite3_int64);
  151662. sqlite3_int64 mxMmap = va_arg(ap, sqlite3_int64);
  151663. /* EVIDENCE-OF: R-53367-43190 If either argument to this option is
  151664. ** negative, then that argument is changed to its compile-time default.
  151665. **
  151666. ** EVIDENCE-OF: R-34993-45031 The maximum allowed mmap size will be
  151667. ** silently truncated if necessary so that it does not exceed the
  151668. ** compile-time maximum mmap size set by the SQLITE_MAX_MMAP_SIZE
  151669. ** compile-time option.
  151670. */
  151671. if( mxMmap<0 || mxMmap>SQLITE_MAX_MMAP_SIZE ){
  151672. mxMmap = SQLITE_MAX_MMAP_SIZE;
  151673. }
  151674. if( szMmap<0 ) szMmap = SQLITE_DEFAULT_MMAP_SIZE;
  151675. if( szMmap>mxMmap) szMmap = mxMmap;
  151676. sqlite3GlobalConfig.mxMmap = mxMmap;
  151677. sqlite3GlobalConfig.szMmap = szMmap;
  151678. break;
  151679. }
  151680. #if SQLITE_OS_WIN && defined(SQLITE_WIN32_MALLOC) /* IMP: R-04780-55815 */
  151681. case SQLITE_CONFIG_WIN32_HEAPSIZE: {
  151682. /* EVIDENCE-OF: R-34926-03360 SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit
  151683. ** unsigned integer value that specifies the maximum size of the created
  151684. ** heap. */
  151685. sqlite3GlobalConfig.nHeap = va_arg(ap, int);
  151686. break;
  151687. }
  151688. #endif
  151689. case SQLITE_CONFIG_PMASZ: {
  151690. sqlite3GlobalConfig.szPma = va_arg(ap, unsigned int);
  151691. break;
  151692. }
  151693. case SQLITE_CONFIG_STMTJRNL_SPILL: {
  151694. sqlite3GlobalConfig.nStmtSpill = va_arg(ap, int);
  151695. break;
  151696. }
  151697. #ifdef SQLITE_ENABLE_SORTER_REFERENCES
  151698. case SQLITE_CONFIG_SORTERREF_SIZE: {
  151699. int iVal = va_arg(ap, int);
  151700. if( iVal<0 ){
  151701. iVal = SQLITE_DEFAULT_SORTERREF_SIZE;
  151702. }
  151703. sqlite3GlobalConfig.szSorterRef = (u32)iVal;
  151704. break;
  151705. }
  151706. #endif /* SQLITE_ENABLE_SORTER_REFERENCES */
  151707. #ifdef SQLITE_ENABLE_DESERIALIZE
  151708. case SQLITE_CONFIG_MEMDB_MAXSIZE: {
  151709. sqlite3GlobalConfig.mxMemdbSize = va_arg(ap, sqlite3_int64);
  151710. break;
  151711. }
  151712. #endif /* SQLITE_ENABLE_DESERIALIZE */
  151713. default: {
  151714. rc = SQLITE_ERROR;
  151715. break;
  151716. }
  151717. }
  151718. va_end(ap);
  151719. return rc;
  151720. }
  151721. /*
  151722. ** Set up the lookaside buffers for a database connection.
  151723. ** Return SQLITE_OK on success.
  151724. ** If lookaside is already active, return SQLITE_BUSY.
  151725. **
  151726. ** The sz parameter is the number of bytes in each lookaside slot.
  151727. ** The cnt parameter is the number of slots. If pStart is NULL the
  151728. ** space for the lookaside memory is obtained from sqlite3_malloc().
  151729. ** If pStart is not NULL then it is sz*cnt bytes of memory to use for
  151730. ** the lookaside memory.
  151731. */
  151732. static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
  151733. #ifndef SQLITE_OMIT_LOOKASIDE
  151734. void *pStart;
  151735. sqlite3_int64 szAlloc = sz*(sqlite3_int64)cnt;
  151736. int nBig; /* Number of full-size slots */
  151737. int nSm; /* Number smaller LOOKASIDE_SMALL-byte slots */
  151738. if( sqlite3LookasideUsed(db,0)>0 ){
  151739. return SQLITE_BUSY;
  151740. }
  151741. /* Free any existing lookaside buffer for this handle before
  151742. ** allocating a new one so we don't have to have space for
  151743. ** both at the same time.
  151744. */
  151745. if( db->lookaside.bMalloced ){
  151746. sqlite3_free(db->lookaside.pStart);
  151747. }
  151748. /* The size of a lookaside slot after ROUNDDOWN8 needs to be larger
  151749. ** than a pointer to be useful.
  151750. */
  151751. sz = ROUNDDOWN8(sz); /* IMP: R-33038-09382 */
  151752. if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
  151753. if( cnt<0 ) cnt = 0;
  151754. if( sz==0 || cnt==0 ){
  151755. sz = 0;
  151756. pStart = 0;
  151757. }else if( pBuf==0 ){
  151758. sqlite3BeginBenignMalloc();
  151759. pStart = sqlite3Malloc( szAlloc ); /* IMP: R-61949-35727 */
  151760. sqlite3EndBenignMalloc();
  151761. if( pStart ) szAlloc = sqlite3MallocSize(pStart);
  151762. }else{
  151763. pStart = pBuf;
  151764. }
  151765. #ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE
  151766. if( sz>=LOOKASIDE_SMALL*3 ){
  151767. nBig = szAlloc/(3*LOOKASIDE_SMALL+sz);
  151768. nSm = (szAlloc - sz*nBig)/LOOKASIDE_SMALL;
  151769. }else if( sz>=LOOKASIDE_SMALL*2 ){
  151770. nBig = szAlloc/(LOOKASIDE_SMALL+sz);
  151771. nSm = (szAlloc - sz*nBig)/LOOKASIDE_SMALL;
  151772. }else
  151773. #endif /* SQLITE_OMIT_TWOSIZE_LOOKASIDE */
  151774. if( sz>0 ){
  151775. nBig = szAlloc/sz;
  151776. nSm = 0;
  151777. }else{
  151778. nBig = nSm = 0;
  151779. }
  151780. db->lookaside.pStart = pStart;
  151781. db->lookaside.pInit = 0;
  151782. db->lookaside.pFree = 0;
  151783. db->lookaside.sz = (u16)sz;
  151784. db->lookaside.szTrue = (u16)sz;
  151785. if( pStart ){
  151786. int i;
  151787. LookasideSlot *p;
  151788. assert( sz > (int)sizeof(LookasideSlot*) );
  151789. p = (LookasideSlot*)pStart;
  151790. for(i=0; i<nBig; i++){
  151791. p->pNext = db->lookaside.pInit;
  151792. db->lookaside.pInit = p;
  151793. p = (LookasideSlot*)&((u8*)p)[sz];
  151794. }
  151795. #ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE
  151796. db->lookaside.pSmallInit = 0;
  151797. db->lookaside.pSmallFree = 0;
  151798. db->lookaside.pMiddle = p;
  151799. for(i=0; i<nSm; i++){
  151800. p->pNext = db->lookaside.pSmallInit;
  151801. db->lookaside.pSmallInit = p;
  151802. p = (LookasideSlot*)&((u8*)p)[LOOKASIDE_SMALL];
  151803. }
  151804. #endif /* SQLITE_OMIT_TWOSIZE_LOOKASIDE */
  151805. assert( ((uptr)p)<=szAlloc + (uptr)pStart );
  151806. db->lookaside.pEnd = p;
  151807. db->lookaside.bDisable = 0;
  151808. db->lookaside.bMalloced = pBuf==0 ?1:0;
  151809. db->lookaside.nSlot = nBig+nSm;
  151810. }else{
  151811. db->lookaside.pStart = db;
  151812. #ifndef SQLITE_OMIT_TWOSIZE_LOOKASIDE
  151813. db->lookaside.pSmallInit = 0;
  151814. db->lookaside.pSmallFree = 0;
  151815. db->lookaside.pMiddle = db;
  151816. #endif /* SQLITE_OMIT_TWOSIZE_LOOKASIDE */
  151817. db->lookaside.pEnd = db;
  151818. db->lookaside.bDisable = 1;
  151819. db->lookaside.sz = 0;
  151820. db->lookaside.bMalloced = 0;
  151821. db->lookaside.nSlot = 0;
  151822. }
  151823. assert( sqlite3LookasideUsed(db,0)==0 );
  151824. #endif /* SQLITE_OMIT_LOOKASIDE */
  151825. return SQLITE_OK;
  151826. }
  151827. /*
  151828. ** Return the mutex associated with a database connection.
  151829. */
  151830. SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){
  151831. #ifdef SQLITE_ENABLE_API_ARMOR
  151832. if( !sqlite3SafetyCheckOk(db) ){
  151833. (void)SQLITE_MISUSE_BKPT;
  151834. return 0;
  151835. }
  151836. #endif
  151837. return db->mutex;
  151838. }
  151839. /*
  151840. ** Free up as much memory as we can from the given database
  151841. ** connection.
  151842. */
  151843. SQLITE_API int sqlite3_db_release_memory(sqlite3 *db){
  151844. int i;
  151845. #ifdef SQLITE_ENABLE_API_ARMOR
  151846. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  151847. #endif
  151848. sqlite3_mutex_enter(db->mutex);
  151849. sqlite3BtreeEnterAll(db);
  151850. for(i=0; i<db->nDb; i++){
  151851. Btree *pBt = db->aDb[i].pBt;
  151852. if( pBt ){
  151853. Pager *pPager = sqlite3BtreePager(pBt);
  151854. sqlite3PagerShrink(pPager);
  151855. }
  151856. }
  151857. sqlite3BtreeLeaveAll(db);
  151858. sqlite3_mutex_leave(db->mutex);
  151859. return SQLITE_OK;
  151860. }
  151861. /*
  151862. ** Flush any dirty pages in the pager-cache for any attached database
  151863. ** to disk.
  151864. */
  151865. SQLITE_API int sqlite3_db_cacheflush(sqlite3 *db){
  151866. int i;
  151867. int rc = SQLITE_OK;
  151868. int bSeenBusy = 0;
  151869. #ifdef SQLITE_ENABLE_API_ARMOR
  151870. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  151871. #endif
  151872. sqlite3_mutex_enter(db->mutex);
  151873. sqlite3BtreeEnterAll(db);
  151874. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  151875. Btree *pBt = db->aDb[i].pBt;
  151876. if( pBt && sqlite3BtreeIsInTrans(pBt) ){
  151877. Pager *pPager = sqlite3BtreePager(pBt);
  151878. rc = sqlite3PagerFlush(pPager);
  151879. if( rc==SQLITE_BUSY ){
  151880. bSeenBusy = 1;
  151881. rc = SQLITE_OK;
  151882. }
  151883. }
  151884. }
  151885. sqlite3BtreeLeaveAll(db);
  151886. sqlite3_mutex_leave(db->mutex);
  151887. return ((rc==SQLITE_OK && bSeenBusy) ? SQLITE_BUSY : rc);
  151888. }
  151889. /*
  151890. ** Configuration settings for an individual database connection
  151891. */
  151892. SQLITE_API int sqlite3_db_config(sqlite3 *db, int op, ...){
  151893. va_list ap;
  151894. int rc;
  151895. va_start(ap, op);
  151896. switch( op ){
  151897. case SQLITE_DBCONFIG_MAINDBNAME: {
  151898. /* IMP: R-06824-28531 */
  151899. /* IMP: R-36257-52125 */
  151900. db->aDb[0].zDbSName = va_arg(ap,char*);
  151901. rc = SQLITE_OK;
  151902. break;
  151903. }
  151904. case SQLITE_DBCONFIG_LOOKASIDE: {
  151905. void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */
  151906. int sz = va_arg(ap, int); /* IMP: R-47871-25994 */
  151907. int cnt = va_arg(ap, int); /* IMP: R-04460-53386 */
  151908. rc = setupLookaside(db, pBuf, sz, cnt);
  151909. break;
  151910. }
  151911. default: {
  151912. static const struct {
  151913. int op; /* The opcode */
  151914. u32 mask; /* Mask of the bit in sqlite3.flags to set/clear */
  151915. } aFlagOp[] = {
  151916. { SQLITE_DBCONFIG_ENABLE_FKEY, SQLITE_ForeignKeys },
  151917. { SQLITE_DBCONFIG_ENABLE_TRIGGER, SQLITE_EnableTrigger },
  151918. { SQLITE_DBCONFIG_ENABLE_VIEW, SQLITE_EnableView },
  151919. { SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER, SQLITE_Fts3Tokenizer },
  151920. { SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION, SQLITE_LoadExtension },
  151921. { SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE, SQLITE_NoCkptOnClose },
  151922. { SQLITE_DBCONFIG_ENABLE_QPSG, SQLITE_EnableQPSG },
  151923. { SQLITE_DBCONFIG_TRIGGER_EQP, SQLITE_TriggerEQP },
  151924. { SQLITE_DBCONFIG_RESET_DATABASE, SQLITE_ResetDatabase },
  151925. { SQLITE_DBCONFIG_DEFENSIVE, SQLITE_Defensive },
  151926. { SQLITE_DBCONFIG_WRITABLE_SCHEMA, SQLITE_WriteSchema|
  151927. SQLITE_NoSchemaError },
  151928. { SQLITE_DBCONFIG_LEGACY_ALTER_TABLE, SQLITE_LegacyAlter },
  151929. { SQLITE_DBCONFIG_DQS_DDL, SQLITE_DqsDDL },
  151930. { SQLITE_DBCONFIG_DQS_DML, SQLITE_DqsDML },
  151931. { SQLITE_DBCONFIG_LEGACY_FILE_FORMAT, SQLITE_LegacyFileFmt },
  151932. { SQLITE_DBCONFIG_TRUSTED_SCHEMA, SQLITE_TrustedSchema },
  151933. };
  151934. unsigned int i;
  151935. rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
  151936. for(i=0; i<ArraySize(aFlagOp); i++){
  151937. if( aFlagOp[i].op==op ){
  151938. int onoff = va_arg(ap, int);
  151939. int *pRes = va_arg(ap, int*);
  151940. u64 oldFlags = db->flags;
  151941. if( onoff>0 ){
  151942. db->flags |= aFlagOp[i].mask;
  151943. }else if( onoff==0 ){
  151944. db->flags &= ~(u64)aFlagOp[i].mask;
  151945. }
  151946. if( oldFlags!=db->flags ){
  151947. sqlite3ExpirePreparedStatements(db, 0);
  151948. }
  151949. if( pRes ){
  151950. *pRes = (db->flags & aFlagOp[i].mask)!=0;
  151951. }
  151952. rc = SQLITE_OK;
  151953. break;
  151954. }
  151955. }
  151956. break;
  151957. }
  151958. }
  151959. va_end(ap);
  151960. return rc;
  151961. }
  151962. /*
  151963. ** This is the default collating function named "BINARY" which is always
  151964. ** available.
  151965. */
  151966. static int binCollFunc(
  151967. void *NotUsed,
  151968. int nKey1, const void *pKey1,
  151969. int nKey2, const void *pKey2
  151970. ){
  151971. int rc, n;
  151972. UNUSED_PARAMETER(NotUsed);
  151973. n = nKey1<nKey2 ? nKey1 : nKey2;
  151974. /* EVIDENCE-OF: R-65033-28449 The built-in BINARY collation compares
  151975. ** strings byte by byte using the memcmp() function from the standard C
  151976. ** library. */
  151977. assert( pKey1 && pKey2 );
  151978. rc = memcmp(pKey1, pKey2, n);
  151979. if( rc==0 ){
  151980. rc = nKey1 - nKey2;
  151981. }
  151982. return rc;
  151983. }
  151984. /*
  151985. ** This is the collating function named "RTRIM" which is always
  151986. ** available. Ignore trailing spaces.
  151987. */
  151988. static int rtrimCollFunc(
  151989. void *pUser,
  151990. int nKey1, const void *pKey1,
  151991. int nKey2, const void *pKey2
  151992. ){
  151993. const u8 *pK1 = (const u8*)pKey1;
  151994. const u8 *pK2 = (const u8*)pKey2;
  151995. while( nKey1 && pK1[nKey1-1]==' ' ) nKey1--;
  151996. while( nKey2 && pK2[nKey2-1]==' ' ) nKey2--;
  151997. return binCollFunc(pUser, nKey1, pKey1, nKey2, pKey2);
  151998. }
  151999. /*
  152000. ** Return true if CollSeq is the default built-in BINARY.
  152001. */
  152002. SQLITE_PRIVATE int sqlite3IsBinary(const CollSeq *p){
  152003. assert( p==0 || p->xCmp!=binCollFunc || strcmp(p->zName,"BINARY")==0 );
  152004. return p==0 || p->xCmp==binCollFunc;
  152005. }
  152006. /*
  152007. ** Another built-in collating sequence: NOCASE.
  152008. **
  152009. ** This collating sequence is intended to be used for "case independent
  152010. ** comparison". SQLite's knowledge of upper and lower case equivalents
  152011. ** extends only to the 26 characters used in the English language.
  152012. **
  152013. ** At the moment there is only a UTF-8 implementation.
  152014. */
  152015. static int nocaseCollatingFunc(
  152016. void *NotUsed,
  152017. int nKey1, const void *pKey1,
  152018. int nKey2, const void *pKey2
  152019. ){
  152020. int r = sqlite3StrNICmp(
  152021. (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
  152022. UNUSED_PARAMETER(NotUsed);
  152023. if( 0==r ){
  152024. r = nKey1-nKey2;
  152025. }
  152026. return r;
  152027. }
  152028. /*
  152029. ** Return the ROWID of the most recent insert
  152030. */
  152031. SQLITE_API sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
  152032. #ifdef SQLITE_ENABLE_API_ARMOR
  152033. if( !sqlite3SafetyCheckOk(db) ){
  152034. (void)SQLITE_MISUSE_BKPT;
  152035. return 0;
  152036. }
  152037. #endif
  152038. return db->lastRowid;
  152039. }
  152040. /*
  152041. ** Set the value returned by the sqlite3_last_insert_rowid() API function.
  152042. */
  152043. SQLITE_API void sqlite3_set_last_insert_rowid(sqlite3 *db, sqlite3_int64 iRowid){
  152044. #ifdef SQLITE_ENABLE_API_ARMOR
  152045. if( !sqlite3SafetyCheckOk(db) ){
  152046. (void)SQLITE_MISUSE_BKPT;
  152047. return;
  152048. }
  152049. #endif
  152050. sqlite3_mutex_enter(db->mutex);
  152051. db->lastRowid = iRowid;
  152052. sqlite3_mutex_leave(db->mutex);
  152053. }
  152054. /*
  152055. ** Return the number of changes in the most recent call to sqlite3_exec().
  152056. */
  152057. SQLITE_API int sqlite3_changes(sqlite3 *db){
  152058. #ifdef SQLITE_ENABLE_API_ARMOR
  152059. if( !sqlite3SafetyCheckOk(db) ){
  152060. (void)SQLITE_MISUSE_BKPT;
  152061. return 0;
  152062. }
  152063. #endif
  152064. return db->nChange;
  152065. }
  152066. /*
  152067. ** Return the number of changes since the database handle was opened.
  152068. */
  152069. SQLITE_API int sqlite3_total_changes(sqlite3 *db){
  152070. #ifdef SQLITE_ENABLE_API_ARMOR
  152071. if( !sqlite3SafetyCheckOk(db) ){
  152072. (void)SQLITE_MISUSE_BKPT;
  152073. return 0;
  152074. }
  152075. #endif
  152076. return db->nTotalChange;
  152077. }
  152078. /*
  152079. ** Close all open savepoints. This function only manipulates fields of the
  152080. ** database handle object, it does not close any savepoints that may be open
  152081. ** at the b-tree/pager level.
  152082. */
  152083. SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *db){
  152084. while( db->pSavepoint ){
  152085. Savepoint *pTmp = db->pSavepoint;
  152086. db->pSavepoint = pTmp->pNext;
  152087. sqlite3DbFree(db, pTmp);
  152088. }
  152089. db->nSavepoint = 0;
  152090. db->nStatement = 0;
  152091. db->isTransactionSavepoint = 0;
  152092. }
  152093. /*
  152094. ** Invoke the destructor function associated with FuncDef p, if any. Except,
  152095. ** if this is not the last copy of the function, do not invoke it. Multiple
  152096. ** copies of a single function are created when create_function() is called
  152097. ** with SQLITE_ANY as the encoding.
  152098. */
  152099. static void functionDestroy(sqlite3 *db, FuncDef *p){
  152100. FuncDestructor *pDestructor = p->u.pDestructor;
  152101. if( pDestructor ){
  152102. pDestructor->nRef--;
  152103. if( pDestructor->nRef==0 ){
  152104. pDestructor->xDestroy(pDestructor->pUserData);
  152105. sqlite3DbFree(db, pDestructor);
  152106. }
  152107. }
  152108. }
  152109. /*
  152110. ** Disconnect all sqlite3_vtab objects that belong to database connection
  152111. ** db. This is called when db is being closed.
  152112. */
  152113. static void disconnectAllVtab(sqlite3 *db){
  152114. #ifndef SQLITE_OMIT_VIRTUALTABLE
  152115. int i;
  152116. HashElem *p;
  152117. sqlite3BtreeEnterAll(db);
  152118. for(i=0; i<db->nDb; i++){
  152119. Schema *pSchema = db->aDb[i].pSchema;
  152120. if( pSchema ){
  152121. for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
  152122. Table *pTab = (Table *)sqliteHashData(p);
  152123. if( IsVirtual(pTab) ) sqlite3VtabDisconnect(db, pTab);
  152124. }
  152125. }
  152126. }
  152127. for(p=sqliteHashFirst(&db->aModule); p; p=sqliteHashNext(p)){
  152128. Module *pMod = (Module *)sqliteHashData(p);
  152129. if( pMod->pEpoTab ){
  152130. sqlite3VtabDisconnect(db, pMod->pEpoTab);
  152131. }
  152132. }
  152133. sqlite3VtabUnlockList(db);
  152134. sqlite3BtreeLeaveAll(db);
  152135. #else
  152136. UNUSED_PARAMETER(db);
  152137. #endif
  152138. }
  152139. /*
  152140. ** Return TRUE if database connection db has unfinalized prepared
  152141. ** statements or unfinished sqlite3_backup objects.
  152142. */
  152143. static int connectionIsBusy(sqlite3 *db){
  152144. int j;
  152145. assert( sqlite3_mutex_held(db->mutex) );
  152146. if( db->pVdbe ) return 1;
  152147. for(j=0; j<db->nDb; j++){
  152148. Btree *pBt = db->aDb[j].pBt;
  152149. if( pBt && sqlite3BtreeIsInBackup(pBt) ) return 1;
  152150. }
  152151. return 0;
  152152. }
  152153. /*
  152154. ** Close an existing SQLite database
  152155. */
  152156. static int sqlite3Close(sqlite3 *db, int forceZombie){
  152157. if( !db ){
  152158. /* EVIDENCE-OF: R-63257-11740 Calling sqlite3_close() or
  152159. ** sqlite3_close_v2() with a NULL pointer argument is a harmless no-op. */
  152160. return SQLITE_OK;
  152161. }
  152162. if( !sqlite3SafetyCheckSickOrOk(db) ){
  152163. return SQLITE_MISUSE_BKPT;
  152164. }
  152165. sqlite3_mutex_enter(db->mutex);
  152166. if( db->mTrace & SQLITE_TRACE_CLOSE ){
  152167. db->xTrace(SQLITE_TRACE_CLOSE, db->pTraceArg, db, 0);
  152168. }
  152169. /* Force xDisconnect calls on all virtual tables */
  152170. disconnectAllVtab(db);
  152171. /* If a transaction is open, the disconnectAllVtab() call above
  152172. ** will not have called the xDisconnect() method on any virtual
  152173. ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
  152174. ** call will do so. We need to do this before the check for active
  152175. ** SQL statements below, as the v-table implementation may be storing
  152176. ** some prepared statements internally.
  152177. */
  152178. sqlite3VtabRollback(db);
  152179. /* Legacy behavior (sqlite3_close() behavior) is to return
  152180. ** SQLITE_BUSY if the connection can not be closed immediately.
  152181. */
  152182. if( !forceZombie && connectionIsBusy(db) ){
  152183. sqlite3ErrorWithMsg(db, SQLITE_BUSY, "unable to close due to unfinalized "
  152184. "statements or unfinished backups");
  152185. sqlite3_mutex_leave(db->mutex);
  152186. return SQLITE_BUSY;
  152187. }
  152188. #ifdef SQLITE_ENABLE_SQLLOG
  152189. if( sqlite3GlobalConfig.xSqllog ){
  152190. /* Closing the handle. Fourth parameter is passed the value 2. */
  152191. sqlite3GlobalConfig.xSqllog(sqlite3GlobalConfig.pSqllogArg, db, 0, 2);
  152192. }
  152193. #endif
  152194. /* Convert the connection into a zombie and then close it.
  152195. */
  152196. db->magic = SQLITE_MAGIC_ZOMBIE;
  152197. sqlite3LeaveMutexAndCloseZombie(db);
  152198. return SQLITE_OK;
  152199. }
  152200. /*
  152201. ** Two variations on the public interface for closing a database
  152202. ** connection. The sqlite3_close() version returns SQLITE_BUSY and
  152203. ** leaves the connection option if there are unfinalized prepared
  152204. ** statements or unfinished sqlite3_backups. The sqlite3_close_v2()
  152205. ** version forces the connection to become a zombie if there are
  152206. ** unclosed resources, and arranges for deallocation when the last
  152207. ** prepare statement or sqlite3_backup closes.
  152208. */
  152209. SQLITE_API int sqlite3_close(sqlite3 *db){ return sqlite3Close(db,0); }
  152210. SQLITE_API int sqlite3_close_v2(sqlite3 *db){ return sqlite3Close(db,1); }
  152211. /*
  152212. ** Close the mutex on database connection db.
  152213. **
  152214. ** Furthermore, if database connection db is a zombie (meaning that there
  152215. ** has been a prior call to sqlite3_close(db) or sqlite3_close_v2(db)) and
  152216. ** every sqlite3_stmt has now been finalized and every sqlite3_backup has
  152217. ** finished, then free all resources.
  152218. */
  152219. SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3 *db){
  152220. HashElem *i; /* Hash table iterator */
  152221. int j;
  152222. /* If there are outstanding sqlite3_stmt or sqlite3_backup objects
  152223. ** or if the connection has not yet been closed by sqlite3_close_v2(),
  152224. ** then just leave the mutex and return.
  152225. */
  152226. if( db->magic!=SQLITE_MAGIC_ZOMBIE || connectionIsBusy(db) ){
  152227. sqlite3_mutex_leave(db->mutex);
  152228. return;
  152229. }
  152230. /* If we reach this point, it means that the database connection has
  152231. ** closed all sqlite3_stmt and sqlite3_backup objects and has been
  152232. ** passed to sqlite3_close (meaning that it is a zombie). Therefore,
  152233. ** go ahead and free all resources.
  152234. */
  152235. /* If a transaction is open, roll it back. This also ensures that if
  152236. ** any database schemas have been modified by an uncommitted transaction
  152237. ** they are reset. And that the required b-tree mutex is held to make
  152238. ** the pager rollback and schema reset an atomic operation. */
  152239. sqlite3RollbackAll(db, SQLITE_OK);
  152240. /* Free any outstanding Savepoint structures. */
  152241. sqlite3CloseSavepoints(db);
  152242. /* Close all database connections */
  152243. for(j=0; j<db->nDb; j++){
  152244. struct Db *pDb = &db->aDb[j];
  152245. if( pDb->pBt ){
  152246. sqlite3BtreeClose(pDb->pBt);
  152247. pDb->pBt = 0;
  152248. if( j!=1 ){
  152249. pDb->pSchema = 0;
  152250. }
  152251. }
  152252. }
  152253. /* Clear the TEMP schema separately and last */
  152254. if( db->aDb[1].pSchema ){
  152255. sqlite3SchemaClear(db->aDb[1].pSchema);
  152256. }
  152257. sqlite3VtabUnlockList(db);
  152258. /* Free up the array of auxiliary databases */
  152259. sqlite3CollapseDatabaseArray(db);
  152260. assert( db->nDb<=2 );
  152261. assert( db->aDb==db->aDbStatic );
  152262. /* Tell the code in notify.c that the connection no longer holds any
  152263. ** locks and does not require any further unlock-notify callbacks.
  152264. */
  152265. sqlite3ConnectionClosed(db);
  152266. for(i=sqliteHashFirst(&db->aFunc); i; i=sqliteHashNext(i)){
  152267. FuncDef *pNext, *p;
  152268. p = sqliteHashData(i);
  152269. do{
  152270. functionDestroy(db, p);
  152271. pNext = p->pNext;
  152272. sqlite3DbFree(db, p);
  152273. p = pNext;
  152274. }while( p );
  152275. }
  152276. sqlite3HashClear(&db->aFunc);
  152277. for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
  152278. CollSeq *pColl = (CollSeq *)sqliteHashData(i);
  152279. /* Invoke any destructors registered for collation sequence user data. */
  152280. for(j=0; j<3; j++){
  152281. if( pColl[j].xDel ){
  152282. pColl[j].xDel(pColl[j].pUser);
  152283. }
  152284. }
  152285. sqlite3DbFree(db, pColl);
  152286. }
  152287. sqlite3HashClear(&db->aCollSeq);
  152288. #ifndef SQLITE_OMIT_VIRTUALTABLE
  152289. for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
  152290. Module *pMod = (Module *)sqliteHashData(i);
  152291. sqlite3VtabEponymousTableClear(db, pMod);
  152292. sqlite3VtabModuleUnref(db, pMod);
  152293. }
  152294. sqlite3HashClear(&db->aModule);
  152295. #endif
  152296. sqlite3Error(db, SQLITE_OK); /* Deallocates any cached error strings. */
  152297. sqlite3ValueFree(db->pErr);
  152298. sqlite3CloseExtensions(db);
  152299. #if SQLITE_USER_AUTHENTICATION
  152300. sqlite3_free(db->auth.zAuthUser);
  152301. sqlite3_free(db->auth.zAuthPW);
  152302. #endif
  152303. db->magic = SQLITE_MAGIC_ERROR;
  152304. /* The temp-database schema is allocated differently from the other schema
  152305. ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
  152306. ** So it needs to be freed here. Todo: Why not roll the temp schema into
  152307. ** the same sqliteMalloc() as the one that allocates the database
  152308. ** structure?
  152309. */
  152310. sqlite3DbFree(db, db->aDb[1].pSchema);
  152311. sqlite3_mutex_leave(db->mutex);
  152312. db->magic = SQLITE_MAGIC_CLOSED;
  152313. sqlite3_mutex_free(db->mutex);
  152314. assert( sqlite3LookasideUsed(db,0)==0 );
  152315. if( db->lookaside.bMalloced ){
  152316. sqlite3_free(db->lookaside.pStart);
  152317. }
  152318. sqlite3_free(db);
  152319. }
  152320. /*
  152321. ** Rollback all database files. If tripCode is not SQLITE_OK, then
  152322. ** any write cursors are invalidated ("tripped" - as in "tripping a circuit
  152323. ** breaker") and made to return tripCode if there are any further
  152324. ** attempts to use that cursor. Read cursors remain open and valid
  152325. ** but are "saved" in case the table pages are moved around.
  152326. */
  152327. SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db, int tripCode){
  152328. int i;
  152329. int inTrans = 0;
  152330. int schemaChange;
  152331. assert( sqlite3_mutex_held(db->mutex) );
  152332. sqlite3BeginBenignMalloc();
  152333. /* Obtain all b-tree mutexes before making any calls to BtreeRollback().
  152334. ** This is important in case the transaction being rolled back has
  152335. ** modified the database schema. If the b-tree mutexes are not taken
  152336. ** here, then another shared-cache connection might sneak in between
  152337. ** the database rollback and schema reset, which can cause false
  152338. ** corruption reports in some cases. */
  152339. sqlite3BtreeEnterAll(db);
  152340. schemaChange = (db->mDbFlags & DBFLAG_SchemaChange)!=0 && db->init.busy==0;
  152341. for(i=0; i<db->nDb; i++){
  152342. Btree *p = db->aDb[i].pBt;
  152343. if( p ){
  152344. if( sqlite3BtreeIsInTrans(p) ){
  152345. inTrans = 1;
  152346. }
  152347. sqlite3BtreeRollback(p, tripCode, !schemaChange);
  152348. }
  152349. }
  152350. sqlite3VtabRollback(db);
  152351. sqlite3EndBenignMalloc();
  152352. if( schemaChange ){
  152353. sqlite3ExpirePreparedStatements(db, 0);
  152354. sqlite3ResetAllSchemasOfConnection(db);
  152355. }
  152356. sqlite3BtreeLeaveAll(db);
  152357. /* Any deferred constraint violations have now been resolved. */
  152358. db->nDeferredCons = 0;
  152359. db->nDeferredImmCons = 0;
  152360. db->flags &= ~(u64)SQLITE_DeferFKs;
  152361. /* If one has been configured, invoke the rollback-hook callback */
  152362. if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
  152363. db->xRollbackCallback(db->pRollbackArg);
  152364. }
  152365. }
  152366. /*
  152367. ** Return a static string containing the name corresponding to the error code
  152368. ** specified in the argument.
  152369. */
  152370. #if defined(SQLITE_NEED_ERR_NAME)
  152371. SQLITE_PRIVATE const char *sqlite3ErrName(int rc){
  152372. const char *zName = 0;
  152373. int i, origRc = rc;
  152374. for(i=0; i<2 && zName==0; i++, rc &= 0xff){
  152375. switch( rc ){
  152376. case SQLITE_OK: zName = "SQLITE_OK"; break;
  152377. case SQLITE_ERROR: zName = "SQLITE_ERROR"; break;
  152378. case SQLITE_ERROR_SNAPSHOT: zName = "SQLITE_ERROR_SNAPSHOT"; break;
  152379. case SQLITE_INTERNAL: zName = "SQLITE_INTERNAL"; break;
  152380. case SQLITE_PERM: zName = "SQLITE_PERM"; break;
  152381. case SQLITE_ABORT: zName = "SQLITE_ABORT"; break;
  152382. case SQLITE_ABORT_ROLLBACK: zName = "SQLITE_ABORT_ROLLBACK"; break;
  152383. case SQLITE_BUSY: zName = "SQLITE_BUSY"; break;
  152384. case SQLITE_BUSY_RECOVERY: zName = "SQLITE_BUSY_RECOVERY"; break;
  152385. case SQLITE_BUSY_SNAPSHOT: zName = "SQLITE_BUSY_SNAPSHOT"; break;
  152386. case SQLITE_LOCKED: zName = "SQLITE_LOCKED"; break;
  152387. case SQLITE_LOCKED_SHAREDCACHE: zName = "SQLITE_LOCKED_SHAREDCACHE";break;
  152388. case SQLITE_NOMEM: zName = "SQLITE_NOMEM"; break;
  152389. case SQLITE_READONLY: zName = "SQLITE_READONLY"; break;
  152390. case SQLITE_READONLY_RECOVERY: zName = "SQLITE_READONLY_RECOVERY"; break;
  152391. case SQLITE_READONLY_CANTINIT: zName = "SQLITE_READONLY_CANTINIT"; break;
  152392. case SQLITE_READONLY_ROLLBACK: zName = "SQLITE_READONLY_ROLLBACK"; break;
  152393. case SQLITE_READONLY_DBMOVED: zName = "SQLITE_READONLY_DBMOVED"; break;
  152394. case SQLITE_READONLY_DIRECTORY: zName = "SQLITE_READONLY_DIRECTORY";break;
  152395. case SQLITE_INTERRUPT: zName = "SQLITE_INTERRUPT"; break;
  152396. case SQLITE_IOERR: zName = "SQLITE_IOERR"; break;
  152397. case SQLITE_IOERR_READ: zName = "SQLITE_IOERR_READ"; break;
  152398. case SQLITE_IOERR_SHORT_READ: zName = "SQLITE_IOERR_SHORT_READ"; break;
  152399. case SQLITE_IOERR_WRITE: zName = "SQLITE_IOERR_WRITE"; break;
  152400. case SQLITE_IOERR_FSYNC: zName = "SQLITE_IOERR_FSYNC"; break;
  152401. case SQLITE_IOERR_DIR_FSYNC: zName = "SQLITE_IOERR_DIR_FSYNC"; break;
  152402. case SQLITE_IOERR_TRUNCATE: zName = "SQLITE_IOERR_TRUNCATE"; break;
  152403. case SQLITE_IOERR_FSTAT: zName = "SQLITE_IOERR_FSTAT"; break;
  152404. case SQLITE_IOERR_UNLOCK: zName = "SQLITE_IOERR_UNLOCK"; break;
  152405. case SQLITE_IOERR_RDLOCK: zName = "SQLITE_IOERR_RDLOCK"; break;
  152406. case SQLITE_IOERR_DELETE: zName = "SQLITE_IOERR_DELETE"; break;
  152407. case SQLITE_IOERR_NOMEM: zName = "SQLITE_IOERR_NOMEM"; break;
  152408. case SQLITE_IOERR_ACCESS: zName = "SQLITE_IOERR_ACCESS"; break;
  152409. case SQLITE_IOERR_CHECKRESERVEDLOCK:
  152410. zName = "SQLITE_IOERR_CHECKRESERVEDLOCK"; break;
  152411. case SQLITE_IOERR_LOCK: zName = "SQLITE_IOERR_LOCK"; break;
  152412. case SQLITE_IOERR_CLOSE: zName = "SQLITE_IOERR_CLOSE"; break;
  152413. case SQLITE_IOERR_DIR_CLOSE: zName = "SQLITE_IOERR_DIR_CLOSE"; break;
  152414. case SQLITE_IOERR_SHMOPEN: zName = "SQLITE_IOERR_SHMOPEN"; break;
  152415. case SQLITE_IOERR_SHMSIZE: zName = "SQLITE_IOERR_SHMSIZE"; break;
  152416. case SQLITE_IOERR_SHMLOCK: zName = "SQLITE_IOERR_SHMLOCK"; break;
  152417. case SQLITE_IOERR_SHMMAP: zName = "SQLITE_IOERR_SHMMAP"; break;
  152418. case SQLITE_IOERR_SEEK: zName = "SQLITE_IOERR_SEEK"; break;
  152419. case SQLITE_IOERR_DELETE_NOENT: zName = "SQLITE_IOERR_DELETE_NOENT";break;
  152420. case SQLITE_IOERR_MMAP: zName = "SQLITE_IOERR_MMAP"; break;
  152421. case SQLITE_IOERR_GETTEMPPATH: zName = "SQLITE_IOERR_GETTEMPPATH"; break;
  152422. case SQLITE_IOERR_CONVPATH: zName = "SQLITE_IOERR_CONVPATH"; break;
  152423. case SQLITE_CORRUPT: zName = "SQLITE_CORRUPT"; break;
  152424. case SQLITE_CORRUPT_VTAB: zName = "SQLITE_CORRUPT_VTAB"; break;
  152425. case SQLITE_NOTFOUND: zName = "SQLITE_NOTFOUND"; break;
  152426. case SQLITE_FULL: zName = "SQLITE_FULL"; break;
  152427. case SQLITE_CANTOPEN: zName = "SQLITE_CANTOPEN"; break;
  152428. case SQLITE_CANTOPEN_NOTEMPDIR: zName = "SQLITE_CANTOPEN_NOTEMPDIR";break;
  152429. case SQLITE_CANTOPEN_ISDIR: zName = "SQLITE_CANTOPEN_ISDIR"; break;
  152430. case SQLITE_CANTOPEN_FULLPATH: zName = "SQLITE_CANTOPEN_FULLPATH"; break;
  152431. case SQLITE_CANTOPEN_CONVPATH: zName = "SQLITE_CANTOPEN_CONVPATH"; break;
  152432. case SQLITE_CANTOPEN_SYMLINK: zName = "SQLITE_CANTOPEN_SYMLINK"; break;
  152433. case SQLITE_PROTOCOL: zName = "SQLITE_PROTOCOL"; break;
  152434. case SQLITE_EMPTY: zName = "SQLITE_EMPTY"; break;
  152435. case SQLITE_SCHEMA: zName = "SQLITE_SCHEMA"; break;
  152436. case SQLITE_TOOBIG: zName = "SQLITE_TOOBIG"; break;
  152437. case SQLITE_CONSTRAINT: zName = "SQLITE_CONSTRAINT"; break;
  152438. case SQLITE_CONSTRAINT_UNIQUE: zName = "SQLITE_CONSTRAINT_UNIQUE"; break;
  152439. case SQLITE_CONSTRAINT_TRIGGER: zName = "SQLITE_CONSTRAINT_TRIGGER";break;
  152440. case SQLITE_CONSTRAINT_FOREIGNKEY:
  152441. zName = "SQLITE_CONSTRAINT_FOREIGNKEY"; break;
  152442. case SQLITE_CONSTRAINT_CHECK: zName = "SQLITE_CONSTRAINT_CHECK"; break;
  152443. case SQLITE_CONSTRAINT_PRIMARYKEY:
  152444. zName = "SQLITE_CONSTRAINT_PRIMARYKEY"; break;
  152445. case SQLITE_CONSTRAINT_NOTNULL: zName = "SQLITE_CONSTRAINT_NOTNULL";break;
  152446. case SQLITE_CONSTRAINT_COMMITHOOK:
  152447. zName = "SQLITE_CONSTRAINT_COMMITHOOK"; break;
  152448. case SQLITE_CONSTRAINT_VTAB: zName = "SQLITE_CONSTRAINT_VTAB"; break;
  152449. case SQLITE_CONSTRAINT_FUNCTION:
  152450. zName = "SQLITE_CONSTRAINT_FUNCTION"; break;
  152451. case SQLITE_CONSTRAINT_ROWID: zName = "SQLITE_CONSTRAINT_ROWID"; break;
  152452. case SQLITE_MISMATCH: zName = "SQLITE_MISMATCH"; break;
  152453. case SQLITE_MISUSE: zName = "SQLITE_MISUSE"; break;
  152454. case SQLITE_NOLFS: zName = "SQLITE_NOLFS"; break;
  152455. case SQLITE_AUTH: zName = "SQLITE_AUTH"; break;
  152456. case SQLITE_FORMAT: zName = "SQLITE_FORMAT"; break;
  152457. case SQLITE_RANGE: zName = "SQLITE_RANGE"; break;
  152458. case SQLITE_NOTADB: zName = "SQLITE_NOTADB"; break;
  152459. case SQLITE_ROW: zName = "SQLITE_ROW"; break;
  152460. case SQLITE_NOTICE: zName = "SQLITE_NOTICE"; break;
  152461. case SQLITE_NOTICE_RECOVER_WAL: zName = "SQLITE_NOTICE_RECOVER_WAL";break;
  152462. case SQLITE_NOTICE_RECOVER_ROLLBACK:
  152463. zName = "SQLITE_NOTICE_RECOVER_ROLLBACK"; break;
  152464. case SQLITE_WARNING: zName = "SQLITE_WARNING"; break;
  152465. case SQLITE_WARNING_AUTOINDEX: zName = "SQLITE_WARNING_AUTOINDEX"; break;
  152466. case SQLITE_DONE: zName = "SQLITE_DONE"; break;
  152467. }
  152468. }
  152469. if( zName==0 ){
  152470. static char zBuf[50];
  152471. sqlite3_snprintf(sizeof(zBuf), zBuf, "SQLITE_UNKNOWN(%d)", origRc);
  152472. zName = zBuf;
  152473. }
  152474. return zName;
  152475. }
  152476. #endif
  152477. /*
  152478. ** Return a static string that describes the kind of error specified in the
  152479. ** argument.
  152480. */
  152481. SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
  152482. static const char* const aMsg[] = {
  152483. /* SQLITE_OK */ "not an error",
  152484. /* SQLITE_ERROR */ "SQL logic error",
  152485. /* SQLITE_INTERNAL */ 0,
  152486. /* SQLITE_PERM */ "access permission denied",
  152487. /* SQLITE_ABORT */ "query aborted",
  152488. /* SQLITE_BUSY */ "database is locked",
  152489. /* SQLITE_LOCKED */ "database table is locked",
  152490. /* SQLITE_NOMEM */ "out of memory",
  152491. /* SQLITE_READONLY */ "attempt to write a readonly database",
  152492. /* SQLITE_INTERRUPT */ "interrupted",
  152493. /* SQLITE_IOERR */ "disk I/O error",
  152494. /* SQLITE_CORRUPT */ "database disk image is malformed",
  152495. /* SQLITE_NOTFOUND */ "unknown operation",
  152496. /* SQLITE_FULL */ "database or disk is full",
  152497. /* SQLITE_CANTOPEN */ "unable to open database file",
  152498. /* SQLITE_PROTOCOL */ "locking protocol",
  152499. /* SQLITE_EMPTY */ 0,
  152500. /* SQLITE_SCHEMA */ "database schema has changed",
  152501. /* SQLITE_TOOBIG */ "string or blob too big",
  152502. /* SQLITE_CONSTRAINT */ "constraint failed",
  152503. /* SQLITE_MISMATCH */ "datatype mismatch",
  152504. /* SQLITE_MISUSE */ "bad parameter or other API misuse",
  152505. #ifdef SQLITE_DISABLE_LFS
  152506. /* SQLITE_NOLFS */ "large file support is disabled",
  152507. #else
  152508. /* SQLITE_NOLFS */ 0,
  152509. #endif
  152510. /* SQLITE_AUTH */ "authorization denied",
  152511. /* SQLITE_FORMAT */ 0,
  152512. /* SQLITE_RANGE */ "column index out of range",
  152513. /* SQLITE_NOTADB */ "file is not a database",
  152514. /* SQLITE_NOTICE */ "notification message",
  152515. /* SQLITE_WARNING */ "warning message",
  152516. };
  152517. const char *zErr = "unknown error";
  152518. switch( rc ){
  152519. case SQLITE_ABORT_ROLLBACK: {
  152520. zErr = "abort due to ROLLBACK";
  152521. break;
  152522. }
  152523. case SQLITE_ROW: {
  152524. zErr = "another row available";
  152525. break;
  152526. }
  152527. case SQLITE_DONE: {
  152528. zErr = "no more rows available";
  152529. break;
  152530. }
  152531. default: {
  152532. rc &= 0xff;
  152533. if( ALWAYS(rc>=0) && rc<ArraySize(aMsg) && aMsg[rc]!=0 ){
  152534. zErr = aMsg[rc];
  152535. }
  152536. break;
  152537. }
  152538. }
  152539. return zErr;
  152540. }
  152541. /*
  152542. ** This routine implements a busy callback that sleeps and tries
  152543. ** again until a timeout value is reached. The timeout value is
  152544. ** an integer number of milliseconds passed in as the first
  152545. ** argument.
  152546. **
  152547. ** Return non-zero to retry the lock. Return zero to stop trying
  152548. ** and cause SQLite to return SQLITE_BUSY.
  152549. */
  152550. static int sqliteDefaultBusyCallback(
  152551. void *ptr, /* Database connection */
  152552. int count /* Number of times table has been busy */
  152553. ){
  152554. #if SQLITE_OS_WIN || HAVE_USLEEP
  152555. /* This case is for systems that have support for sleeping for fractions of
  152556. ** a second. Examples: All windows systems, unix systems with usleep() */
  152557. static const u8 delays[] =
  152558. { 1, 2, 5, 10, 15, 20, 25, 25, 25, 50, 50, 100 };
  152559. static const u8 totals[] =
  152560. { 0, 1, 3, 8, 18, 33, 53, 78, 103, 128, 178, 228 };
  152561. # define NDELAY ArraySize(delays)
  152562. sqlite3 *db = (sqlite3 *)ptr;
  152563. int tmout = db->busyTimeout;
  152564. int delay, prior;
  152565. assert( count>=0 );
  152566. if( count < NDELAY ){
  152567. delay = delays[count];
  152568. prior = totals[count];
  152569. }else{
  152570. delay = delays[NDELAY-1];
  152571. prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
  152572. }
  152573. if( prior + delay > tmout ){
  152574. delay = tmout - prior;
  152575. if( delay<=0 ) return 0;
  152576. }
  152577. sqlite3OsSleep(db->pVfs, delay*1000);
  152578. return 1;
  152579. #else
  152580. /* This case for unix systems that lack usleep() support. Sleeping
  152581. ** must be done in increments of whole seconds */
  152582. sqlite3 *db = (sqlite3 *)ptr;
  152583. int tmout = ((sqlite3 *)ptr)->busyTimeout;
  152584. if( (count+1)*1000 > tmout ){
  152585. return 0;
  152586. }
  152587. sqlite3OsSleep(db->pVfs, 1000000);
  152588. return 1;
  152589. #endif
  152590. }
  152591. /*
  152592. ** Invoke the given busy handler.
  152593. **
  152594. ** This routine is called when an operation failed to acquire a
  152595. ** lock on VFS file pFile.
  152596. **
  152597. ** If this routine returns non-zero, the lock is retried. If it
  152598. ** returns 0, the operation aborts with an SQLITE_BUSY error.
  152599. */
  152600. SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){
  152601. int rc;
  152602. if( p->xBusyHandler==0 || p->nBusy<0 ) return 0;
  152603. rc = p->xBusyHandler(p->pBusyArg, p->nBusy);
  152604. if( rc==0 ){
  152605. p->nBusy = -1;
  152606. }else{
  152607. p->nBusy++;
  152608. }
  152609. return rc;
  152610. }
  152611. /*
  152612. ** This routine sets the busy callback for an Sqlite database to the
  152613. ** given callback function with the given argument.
  152614. */
  152615. SQLITE_API int sqlite3_busy_handler(
  152616. sqlite3 *db,
  152617. int (*xBusy)(void*,int),
  152618. void *pArg
  152619. ){
  152620. #ifdef SQLITE_ENABLE_API_ARMOR
  152621. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  152622. #endif
  152623. sqlite3_mutex_enter(db->mutex);
  152624. db->busyHandler.xBusyHandler = xBusy;
  152625. db->busyHandler.pBusyArg = pArg;
  152626. db->busyHandler.nBusy = 0;
  152627. db->busyTimeout = 0;
  152628. sqlite3_mutex_leave(db->mutex);
  152629. return SQLITE_OK;
  152630. }
  152631. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  152632. /*
  152633. ** This routine sets the progress callback for an Sqlite database to the
  152634. ** given callback function with the given argument. The progress callback will
  152635. ** be invoked every nOps opcodes.
  152636. */
  152637. SQLITE_API void sqlite3_progress_handler(
  152638. sqlite3 *db,
  152639. int nOps,
  152640. int (*xProgress)(void*),
  152641. void *pArg
  152642. ){
  152643. #ifdef SQLITE_ENABLE_API_ARMOR
  152644. if( !sqlite3SafetyCheckOk(db) ){
  152645. (void)SQLITE_MISUSE_BKPT;
  152646. return;
  152647. }
  152648. #endif
  152649. sqlite3_mutex_enter(db->mutex);
  152650. if( nOps>0 ){
  152651. db->xProgress = xProgress;
  152652. db->nProgressOps = (unsigned)nOps;
  152653. db->pProgressArg = pArg;
  152654. }else{
  152655. db->xProgress = 0;
  152656. db->nProgressOps = 0;
  152657. db->pProgressArg = 0;
  152658. }
  152659. sqlite3_mutex_leave(db->mutex);
  152660. }
  152661. #endif
  152662. /*
  152663. ** This routine installs a default busy handler that waits for the
  152664. ** specified number of milliseconds before returning 0.
  152665. */
  152666. SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){
  152667. #ifdef SQLITE_ENABLE_API_ARMOR
  152668. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  152669. #endif
  152670. if( ms>0 ){
  152671. sqlite3_busy_handler(db, (int(*)(void*,int))sqliteDefaultBusyCallback,
  152672. (void*)db);
  152673. db->busyTimeout = ms;
  152674. }else{
  152675. sqlite3_busy_handler(db, 0, 0);
  152676. }
  152677. return SQLITE_OK;
  152678. }
  152679. /*
  152680. ** Cause any pending operation to stop at its earliest opportunity.
  152681. */
  152682. SQLITE_API void sqlite3_interrupt(sqlite3 *db){
  152683. #ifdef SQLITE_ENABLE_API_ARMOR
  152684. if( !sqlite3SafetyCheckOk(db) && (db==0 || db->magic!=SQLITE_MAGIC_ZOMBIE) ){
  152685. (void)SQLITE_MISUSE_BKPT;
  152686. return;
  152687. }
  152688. #endif
  152689. AtomicStore(&db->u1.isInterrupted, 1);
  152690. }
  152691. /*
  152692. ** This function is exactly the same as sqlite3_create_function(), except
  152693. ** that it is designed to be called by internal code. The difference is
  152694. ** that if a malloc() fails in sqlite3_create_function(), an error code
  152695. ** is returned and the mallocFailed flag cleared.
  152696. */
  152697. SQLITE_PRIVATE int sqlite3CreateFunc(
  152698. sqlite3 *db,
  152699. const char *zFunctionName,
  152700. int nArg,
  152701. int enc,
  152702. void *pUserData,
  152703. void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
  152704. void (*xStep)(sqlite3_context*,int,sqlite3_value **),
  152705. void (*xFinal)(sqlite3_context*),
  152706. void (*xValue)(sqlite3_context*),
  152707. void (*xInverse)(sqlite3_context*,int,sqlite3_value **),
  152708. FuncDestructor *pDestructor
  152709. ){
  152710. FuncDef *p;
  152711. int nName;
  152712. int extraFlags;
  152713. assert( sqlite3_mutex_held(db->mutex) );
  152714. assert( xValue==0 || xSFunc==0 );
  152715. if( zFunctionName==0 /* Must have a valid name */
  152716. || (xSFunc!=0 && xFinal!=0) /* Not both xSFunc and xFinal */
  152717. || ((xFinal==0)!=(xStep==0)) /* Both or neither of xFinal and xStep */
  152718. || ((xValue==0)!=(xInverse==0)) /* Both or neither of xValue, xInverse */
  152719. || (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG)
  152720. || (255<(nName = sqlite3Strlen30( zFunctionName)))
  152721. ){
  152722. return SQLITE_MISUSE_BKPT;
  152723. }
  152724. assert( SQLITE_FUNC_CONSTANT==SQLITE_DETERMINISTIC );
  152725. assert( SQLITE_FUNC_DIRECT==SQLITE_DIRECTONLY );
  152726. extraFlags = enc & (SQLITE_DETERMINISTIC|SQLITE_DIRECTONLY|
  152727. SQLITE_SUBTYPE|SQLITE_INNOCUOUS);
  152728. enc &= (SQLITE_FUNC_ENCMASK|SQLITE_ANY);
  152729. /* The SQLITE_INNOCUOUS flag is the same bit as SQLITE_FUNC_UNSAFE. But
  152730. ** the meaning is inverted. So flip the bit. */
  152731. assert( SQLITE_FUNC_UNSAFE==SQLITE_INNOCUOUS );
  152732. extraFlags ^= SQLITE_FUNC_UNSAFE;
  152733. #ifndef SQLITE_OMIT_UTF16
  152734. /* If SQLITE_UTF16 is specified as the encoding type, transform this
  152735. ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
  152736. ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
  152737. **
  152738. ** If SQLITE_ANY is specified, add three versions of the function
  152739. ** to the hash table.
  152740. */
  152741. if( enc==SQLITE_UTF16 ){
  152742. enc = SQLITE_UTF16NATIVE;
  152743. }else if( enc==SQLITE_ANY ){
  152744. int rc;
  152745. rc = sqlite3CreateFunc(db, zFunctionName, nArg,
  152746. (SQLITE_UTF8|extraFlags)^SQLITE_FUNC_UNSAFE,
  152747. pUserData, xSFunc, xStep, xFinal, xValue, xInverse, pDestructor);
  152748. if( rc==SQLITE_OK ){
  152749. rc = sqlite3CreateFunc(db, zFunctionName, nArg,
  152750. (SQLITE_UTF16LE|extraFlags)^SQLITE_FUNC_UNSAFE,
  152751. pUserData, xSFunc, xStep, xFinal, xValue, xInverse, pDestructor);
  152752. }
  152753. if( rc!=SQLITE_OK ){
  152754. return rc;
  152755. }
  152756. enc = SQLITE_UTF16BE;
  152757. }
  152758. #else
  152759. enc = SQLITE_UTF8;
  152760. #endif
  152761. /* Check if an existing function is being overridden or deleted. If so,
  152762. ** and there are active VMs, then return SQLITE_BUSY. If a function
  152763. ** is being overridden/deleted but there are no active VMs, allow the
  152764. ** operation to continue but invalidate all precompiled statements.
  152765. */
  152766. p = sqlite3FindFunction(db, zFunctionName, nArg, (u8)enc, 0);
  152767. if( p && (p->funcFlags & SQLITE_FUNC_ENCMASK)==(u32)enc && p->nArg==nArg ){
  152768. if( db->nVdbeActive ){
  152769. sqlite3ErrorWithMsg(db, SQLITE_BUSY,
  152770. "unable to delete/modify user-function due to active statements");
  152771. assert( !db->mallocFailed );
  152772. return SQLITE_BUSY;
  152773. }else{
  152774. sqlite3ExpirePreparedStatements(db, 0);
  152775. }
  152776. }
  152777. p = sqlite3FindFunction(db, zFunctionName, nArg, (u8)enc, 1);
  152778. assert(p || db->mallocFailed);
  152779. if( !p ){
  152780. return SQLITE_NOMEM_BKPT;
  152781. }
  152782. /* If an older version of the function with a configured destructor is
  152783. ** being replaced invoke the destructor function here. */
  152784. functionDestroy(db, p);
  152785. if( pDestructor ){
  152786. pDestructor->nRef++;
  152787. }
  152788. p->u.pDestructor = pDestructor;
  152789. p->funcFlags = (p->funcFlags & SQLITE_FUNC_ENCMASK) | extraFlags;
  152790. testcase( p->funcFlags & SQLITE_DETERMINISTIC );
  152791. testcase( p->funcFlags & SQLITE_DIRECTONLY );
  152792. p->xSFunc = xSFunc ? xSFunc : xStep;
  152793. p->xFinalize = xFinal;
  152794. p->xValue = xValue;
  152795. p->xInverse = xInverse;
  152796. p->pUserData = pUserData;
  152797. p->nArg = (u16)nArg;
  152798. return SQLITE_OK;
  152799. }
  152800. /*
  152801. ** Worker function used by utf-8 APIs that create new functions:
  152802. **
  152803. ** sqlite3_create_function()
  152804. ** sqlite3_create_function_v2()
  152805. ** sqlite3_create_window_function()
  152806. */
  152807. static int createFunctionApi(
  152808. sqlite3 *db,
  152809. const char *zFunc,
  152810. int nArg,
  152811. int enc,
  152812. void *p,
  152813. void (*xSFunc)(sqlite3_context*,int,sqlite3_value**),
  152814. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  152815. void (*xFinal)(sqlite3_context*),
  152816. void (*xValue)(sqlite3_context*),
  152817. void (*xInverse)(sqlite3_context*,int,sqlite3_value**),
  152818. void(*xDestroy)(void*)
  152819. ){
  152820. int rc = SQLITE_ERROR;
  152821. FuncDestructor *pArg = 0;
  152822. #ifdef SQLITE_ENABLE_API_ARMOR
  152823. if( !sqlite3SafetyCheckOk(db) ){
  152824. return SQLITE_MISUSE_BKPT;
  152825. }
  152826. #endif
  152827. sqlite3_mutex_enter(db->mutex);
  152828. if( xDestroy ){
  152829. pArg = (FuncDestructor *)sqlite3Malloc(sizeof(FuncDestructor));
  152830. if( !pArg ){
  152831. sqlite3OomFault(db);
  152832. xDestroy(p);
  152833. goto out;
  152834. }
  152835. pArg->nRef = 0;
  152836. pArg->xDestroy = xDestroy;
  152837. pArg->pUserData = p;
  152838. }
  152839. rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p,
  152840. xSFunc, xStep, xFinal, xValue, xInverse, pArg
  152841. );
  152842. if( pArg && pArg->nRef==0 ){
  152843. assert( rc!=SQLITE_OK );
  152844. xDestroy(p);
  152845. sqlite3_free(pArg);
  152846. }
  152847. out:
  152848. rc = sqlite3ApiExit(db, rc);
  152849. sqlite3_mutex_leave(db->mutex);
  152850. return rc;
  152851. }
  152852. /*
  152853. ** Create new user functions.
  152854. */
  152855. SQLITE_API int sqlite3_create_function(
  152856. sqlite3 *db,
  152857. const char *zFunc,
  152858. int nArg,
  152859. int enc,
  152860. void *p,
  152861. void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
  152862. void (*xStep)(sqlite3_context*,int,sqlite3_value **),
  152863. void (*xFinal)(sqlite3_context*)
  152864. ){
  152865. return createFunctionApi(db, zFunc, nArg, enc, p, xSFunc, xStep,
  152866. xFinal, 0, 0, 0);
  152867. }
  152868. SQLITE_API int sqlite3_create_function_v2(
  152869. sqlite3 *db,
  152870. const char *zFunc,
  152871. int nArg,
  152872. int enc,
  152873. void *p,
  152874. void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
  152875. void (*xStep)(sqlite3_context*,int,sqlite3_value **),
  152876. void (*xFinal)(sqlite3_context*),
  152877. void (*xDestroy)(void *)
  152878. ){
  152879. return createFunctionApi(db, zFunc, nArg, enc, p, xSFunc, xStep,
  152880. xFinal, 0, 0, xDestroy);
  152881. }
  152882. SQLITE_API int sqlite3_create_window_function(
  152883. sqlite3 *db,
  152884. const char *zFunc,
  152885. int nArg,
  152886. int enc,
  152887. void *p,
  152888. void (*xStep)(sqlite3_context*,int,sqlite3_value **),
  152889. void (*xFinal)(sqlite3_context*),
  152890. void (*xValue)(sqlite3_context*),
  152891. void (*xInverse)(sqlite3_context*,int,sqlite3_value **),
  152892. void (*xDestroy)(void *)
  152893. ){
  152894. return createFunctionApi(db, zFunc, nArg, enc, p, 0, xStep,
  152895. xFinal, xValue, xInverse, xDestroy);
  152896. }
  152897. #ifndef SQLITE_OMIT_UTF16
  152898. SQLITE_API int sqlite3_create_function16(
  152899. sqlite3 *db,
  152900. const void *zFunctionName,
  152901. int nArg,
  152902. int eTextRep,
  152903. void *p,
  152904. void (*xSFunc)(sqlite3_context*,int,sqlite3_value**),
  152905. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  152906. void (*xFinal)(sqlite3_context*)
  152907. ){
  152908. int rc;
  152909. char *zFunc8;
  152910. #ifdef SQLITE_ENABLE_API_ARMOR
  152911. if( !sqlite3SafetyCheckOk(db) || zFunctionName==0 ) return SQLITE_MISUSE_BKPT;
  152912. #endif
  152913. sqlite3_mutex_enter(db->mutex);
  152914. assert( !db->mallocFailed );
  152915. zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);
  152916. rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xSFunc,xStep,xFinal,0,0,0);
  152917. sqlite3DbFree(db, zFunc8);
  152918. rc = sqlite3ApiExit(db, rc);
  152919. sqlite3_mutex_leave(db->mutex);
  152920. return rc;
  152921. }
  152922. #endif
  152923. /*
  152924. ** The following is the implementation of an SQL function that always
  152925. ** fails with an error message stating that the function is used in the
  152926. ** wrong context. The sqlite3_overload_function() API might construct
  152927. ** SQL function that use this routine so that the functions will exist
  152928. ** for name resolution but are actually overloaded by the xFindFunction
  152929. ** method of virtual tables.
  152930. */
  152931. static void sqlite3InvalidFunction(
  152932. sqlite3_context *context, /* The function calling context */
  152933. int NotUsed, /* Number of arguments to the function */
  152934. sqlite3_value **NotUsed2 /* Value of each argument */
  152935. ){
  152936. const char *zName = (const char*)sqlite3_user_data(context);
  152937. char *zErr;
  152938. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  152939. zErr = sqlite3_mprintf(
  152940. "unable to use function %s in the requested context", zName);
  152941. sqlite3_result_error(context, zErr, -1);
  152942. sqlite3_free(zErr);
  152943. }
  152944. /*
  152945. ** Declare that a function has been overloaded by a virtual table.
  152946. **
  152947. ** If the function already exists as a regular global function, then
  152948. ** this routine is a no-op. If the function does not exist, then create
  152949. ** a new one that always throws a run-time error.
  152950. **
  152951. ** When virtual tables intend to provide an overloaded function, they
  152952. ** should call this routine to make sure the global function exists.
  152953. ** A global function must exist in order for name resolution to work
  152954. ** properly.
  152955. */
  152956. SQLITE_API int sqlite3_overload_function(
  152957. sqlite3 *db,
  152958. const char *zName,
  152959. int nArg
  152960. ){
  152961. int rc;
  152962. char *zCopy;
  152963. #ifdef SQLITE_ENABLE_API_ARMOR
  152964. if( !sqlite3SafetyCheckOk(db) || zName==0 || nArg<-2 ){
  152965. return SQLITE_MISUSE_BKPT;
  152966. }
  152967. #endif
  152968. sqlite3_mutex_enter(db->mutex);
  152969. rc = sqlite3FindFunction(db, zName, nArg, SQLITE_UTF8, 0)!=0;
  152970. sqlite3_mutex_leave(db->mutex);
  152971. if( rc ) return SQLITE_OK;
  152972. zCopy = sqlite3_mprintf(zName);
  152973. if( zCopy==0 ) return SQLITE_NOMEM;
  152974. return sqlite3_create_function_v2(db, zName, nArg, SQLITE_UTF8,
  152975. zCopy, sqlite3InvalidFunction, 0, 0, sqlite3_free);
  152976. }
  152977. #ifndef SQLITE_OMIT_TRACE
  152978. /*
  152979. ** Register a trace function. The pArg from the previously registered trace
  152980. ** is returned.
  152981. **
  152982. ** A NULL trace function means that no tracing is executes. A non-NULL
  152983. ** trace is a pointer to a function that is invoked at the start of each
  152984. ** SQL statement.
  152985. */
  152986. #ifndef SQLITE_OMIT_DEPRECATED
  152987. SQLITE_API void *sqlite3_trace(sqlite3 *db, void(*xTrace)(void*,const char*), void *pArg){
  152988. void *pOld;
  152989. #ifdef SQLITE_ENABLE_API_ARMOR
  152990. if( !sqlite3SafetyCheckOk(db) ){
  152991. (void)SQLITE_MISUSE_BKPT;
  152992. return 0;
  152993. }
  152994. #endif
  152995. sqlite3_mutex_enter(db->mutex);
  152996. pOld = db->pTraceArg;
  152997. db->mTrace = xTrace ? SQLITE_TRACE_LEGACY : 0;
  152998. db->xTrace = (int(*)(u32,void*,void*,void*))xTrace;
  152999. db->pTraceArg = pArg;
  153000. sqlite3_mutex_leave(db->mutex);
  153001. return pOld;
  153002. }
  153003. #endif /* SQLITE_OMIT_DEPRECATED */
  153004. /* Register a trace callback using the version-2 interface.
  153005. */
  153006. SQLITE_API int sqlite3_trace_v2(
  153007. sqlite3 *db, /* Trace this connection */
  153008. unsigned mTrace, /* Mask of events to be traced */
  153009. int(*xTrace)(unsigned,void*,void*,void*), /* Callback to invoke */
  153010. void *pArg /* Context */
  153011. ){
  153012. #ifdef SQLITE_ENABLE_API_ARMOR
  153013. if( !sqlite3SafetyCheckOk(db) ){
  153014. return SQLITE_MISUSE_BKPT;
  153015. }
  153016. #endif
  153017. sqlite3_mutex_enter(db->mutex);
  153018. if( mTrace==0 ) xTrace = 0;
  153019. if( xTrace==0 ) mTrace = 0;
  153020. db->mTrace = mTrace;
  153021. db->xTrace = xTrace;
  153022. db->pTraceArg = pArg;
  153023. sqlite3_mutex_leave(db->mutex);
  153024. return SQLITE_OK;
  153025. }
  153026. #ifndef SQLITE_OMIT_DEPRECATED
  153027. /*
  153028. ** Register a profile function. The pArg from the previously registered
  153029. ** profile function is returned.
  153030. **
  153031. ** A NULL profile function means that no profiling is executes. A non-NULL
  153032. ** profile is a pointer to a function that is invoked at the conclusion of
  153033. ** each SQL statement that is run.
  153034. */
  153035. SQLITE_API void *sqlite3_profile(
  153036. sqlite3 *db,
  153037. void (*xProfile)(void*,const char*,sqlite_uint64),
  153038. void *pArg
  153039. ){
  153040. void *pOld;
  153041. #ifdef SQLITE_ENABLE_API_ARMOR
  153042. if( !sqlite3SafetyCheckOk(db) ){
  153043. (void)SQLITE_MISUSE_BKPT;
  153044. return 0;
  153045. }
  153046. #endif
  153047. sqlite3_mutex_enter(db->mutex);
  153048. pOld = db->pProfileArg;
  153049. db->xProfile = xProfile;
  153050. db->pProfileArg = pArg;
  153051. db->mTrace &= SQLITE_TRACE_NONLEGACY_MASK;
  153052. if( db->xProfile ) db->mTrace |= SQLITE_TRACE_XPROFILE;
  153053. sqlite3_mutex_leave(db->mutex);
  153054. return pOld;
  153055. }
  153056. #endif /* SQLITE_OMIT_DEPRECATED */
  153057. #endif /* SQLITE_OMIT_TRACE */
  153058. /*
  153059. ** Register a function to be invoked when a transaction commits.
  153060. ** If the invoked function returns non-zero, then the commit becomes a
  153061. ** rollback.
  153062. */
  153063. SQLITE_API void *sqlite3_commit_hook(
  153064. sqlite3 *db, /* Attach the hook to this database */
  153065. int (*xCallback)(void*), /* Function to invoke on each commit */
  153066. void *pArg /* Argument to the function */
  153067. ){
  153068. void *pOld;
  153069. #ifdef SQLITE_ENABLE_API_ARMOR
  153070. if( !sqlite3SafetyCheckOk(db) ){
  153071. (void)SQLITE_MISUSE_BKPT;
  153072. return 0;
  153073. }
  153074. #endif
  153075. sqlite3_mutex_enter(db->mutex);
  153076. pOld = db->pCommitArg;
  153077. db->xCommitCallback = xCallback;
  153078. db->pCommitArg = pArg;
  153079. sqlite3_mutex_leave(db->mutex);
  153080. return pOld;
  153081. }
  153082. /*
  153083. ** Register a callback to be invoked each time a row is updated,
  153084. ** inserted or deleted using this database connection.
  153085. */
  153086. SQLITE_API void *sqlite3_update_hook(
  153087. sqlite3 *db, /* Attach the hook to this database */
  153088. void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
  153089. void *pArg /* Argument to the function */
  153090. ){
  153091. void *pRet;
  153092. #ifdef SQLITE_ENABLE_API_ARMOR
  153093. if( !sqlite3SafetyCheckOk(db) ){
  153094. (void)SQLITE_MISUSE_BKPT;
  153095. return 0;
  153096. }
  153097. #endif
  153098. sqlite3_mutex_enter(db->mutex);
  153099. pRet = db->pUpdateArg;
  153100. db->xUpdateCallback = xCallback;
  153101. db->pUpdateArg = pArg;
  153102. sqlite3_mutex_leave(db->mutex);
  153103. return pRet;
  153104. }
  153105. /*
  153106. ** Register a callback to be invoked each time a transaction is rolled
  153107. ** back by this database connection.
  153108. */
  153109. SQLITE_API void *sqlite3_rollback_hook(
  153110. sqlite3 *db, /* Attach the hook to this database */
  153111. void (*xCallback)(void*), /* Callback function */
  153112. void *pArg /* Argument to the function */
  153113. ){
  153114. void *pRet;
  153115. #ifdef SQLITE_ENABLE_API_ARMOR
  153116. if( !sqlite3SafetyCheckOk(db) ){
  153117. (void)SQLITE_MISUSE_BKPT;
  153118. return 0;
  153119. }
  153120. #endif
  153121. sqlite3_mutex_enter(db->mutex);
  153122. pRet = db->pRollbackArg;
  153123. db->xRollbackCallback = xCallback;
  153124. db->pRollbackArg = pArg;
  153125. sqlite3_mutex_leave(db->mutex);
  153126. return pRet;
  153127. }
  153128. #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
  153129. /*
  153130. ** Register a callback to be invoked each time a row is updated,
  153131. ** inserted or deleted using this database connection.
  153132. */
  153133. SQLITE_API void *sqlite3_preupdate_hook(
  153134. sqlite3 *db, /* Attach the hook to this database */
  153135. void(*xCallback)( /* Callback function */
  153136. void*,sqlite3*,int,char const*,char const*,sqlite3_int64,sqlite3_int64),
  153137. void *pArg /* First callback argument */
  153138. ){
  153139. void *pRet;
  153140. sqlite3_mutex_enter(db->mutex);
  153141. pRet = db->pPreUpdateArg;
  153142. db->xPreUpdateCallback = xCallback;
  153143. db->pPreUpdateArg = pArg;
  153144. sqlite3_mutex_leave(db->mutex);
  153145. return pRet;
  153146. }
  153147. #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
  153148. #ifndef SQLITE_OMIT_WAL
  153149. /*
  153150. ** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
  153151. ** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
  153152. ** is greater than sqlite3.pWalArg cast to an integer (the value configured by
  153153. ** wal_autocheckpoint()).
  153154. */
  153155. SQLITE_PRIVATE int sqlite3WalDefaultHook(
  153156. void *pClientData, /* Argument */
  153157. sqlite3 *db, /* Connection */
  153158. const char *zDb, /* Database */
  153159. int nFrame /* Size of WAL */
  153160. ){
  153161. if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){
  153162. sqlite3BeginBenignMalloc();
  153163. sqlite3_wal_checkpoint(db, zDb);
  153164. sqlite3EndBenignMalloc();
  153165. }
  153166. return SQLITE_OK;
  153167. }
  153168. #endif /* SQLITE_OMIT_WAL */
  153169. /*
  153170. ** Configure an sqlite3_wal_hook() callback to automatically checkpoint
  153171. ** a database after committing a transaction if there are nFrame or
  153172. ** more frames in the log file. Passing zero or a negative value as the
  153173. ** nFrame parameter disables automatic checkpoints entirely.
  153174. **
  153175. ** The callback registered by this function replaces any existing callback
  153176. ** registered using sqlite3_wal_hook(). Likewise, registering a callback
  153177. ** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
  153178. ** configured by this function.
  153179. */
  153180. SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){
  153181. #ifdef SQLITE_OMIT_WAL
  153182. UNUSED_PARAMETER(db);
  153183. UNUSED_PARAMETER(nFrame);
  153184. #else
  153185. #ifdef SQLITE_ENABLE_API_ARMOR
  153186. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  153187. #endif
  153188. if( nFrame>0 ){
  153189. sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame));
  153190. }else{
  153191. sqlite3_wal_hook(db, 0, 0);
  153192. }
  153193. #endif
  153194. return SQLITE_OK;
  153195. }
  153196. /*
  153197. ** Register a callback to be invoked each time a transaction is written
  153198. ** into the write-ahead-log by this database connection.
  153199. */
  153200. SQLITE_API void *sqlite3_wal_hook(
  153201. sqlite3 *db, /* Attach the hook to this db handle */
  153202. int(*xCallback)(void *, sqlite3*, const char*, int),
  153203. void *pArg /* First argument passed to xCallback() */
  153204. ){
  153205. #ifndef SQLITE_OMIT_WAL
  153206. void *pRet;
  153207. #ifdef SQLITE_ENABLE_API_ARMOR
  153208. if( !sqlite3SafetyCheckOk(db) ){
  153209. (void)SQLITE_MISUSE_BKPT;
  153210. return 0;
  153211. }
  153212. #endif
  153213. sqlite3_mutex_enter(db->mutex);
  153214. pRet = db->pWalArg;
  153215. db->xWalCallback = xCallback;
  153216. db->pWalArg = pArg;
  153217. sqlite3_mutex_leave(db->mutex);
  153218. return pRet;
  153219. #else
  153220. return 0;
  153221. #endif
  153222. }
  153223. /*
  153224. ** Checkpoint database zDb.
  153225. */
  153226. SQLITE_API int sqlite3_wal_checkpoint_v2(
  153227. sqlite3 *db, /* Database handle */
  153228. const char *zDb, /* Name of attached database (or NULL) */
  153229. int eMode, /* SQLITE_CHECKPOINT_* value */
  153230. int *pnLog, /* OUT: Size of WAL log in frames */
  153231. int *pnCkpt /* OUT: Total number of frames checkpointed */
  153232. ){
  153233. #ifdef SQLITE_OMIT_WAL
  153234. return SQLITE_OK;
  153235. #else
  153236. int rc; /* Return code */
  153237. int iDb = SQLITE_MAX_ATTACHED; /* sqlite3.aDb[] index of db to checkpoint */
  153238. #ifdef SQLITE_ENABLE_API_ARMOR
  153239. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  153240. #endif
  153241. /* Initialize the output variables to -1 in case an error occurs. */
  153242. if( pnLog ) *pnLog = -1;
  153243. if( pnCkpt ) *pnCkpt = -1;
  153244. assert( SQLITE_CHECKPOINT_PASSIVE==0 );
  153245. assert( SQLITE_CHECKPOINT_FULL==1 );
  153246. assert( SQLITE_CHECKPOINT_RESTART==2 );
  153247. assert( SQLITE_CHECKPOINT_TRUNCATE==3 );
  153248. if( eMode<SQLITE_CHECKPOINT_PASSIVE || eMode>SQLITE_CHECKPOINT_TRUNCATE ){
  153249. /* EVIDENCE-OF: R-03996-12088 The M parameter must be a valid checkpoint
  153250. ** mode: */
  153251. return SQLITE_MISUSE;
  153252. }
  153253. sqlite3_mutex_enter(db->mutex);
  153254. if( zDb && zDb[0] ){
  153255. iDb = sqlite3FindDbName(db, zDb);
  153256. }
  153257. if( iDb<0 ){
  153258. rc = SQLITE_ERROR;
  153259. sqlite3ErrorWithMsg(db, SQLITE_ERROR, "unknown database: %s", zDb);
  153260. }else{
  153261. db->busyHandler.nBusy = 0;
  153262. rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt);
  153263. sqlite3Error(db, rc);
  153264. }
  153265. rc = sqlite3ApiExit(db, rc);
  153266. /* If there are no active statements, clear the interrupt flag at this
  153267. ** point. */
  153268. if( db->nVdbeActive==0 ){
  153269. AtomicStore(&db->u1.isInterrupted, 0);
  153270. }
  153271. sqlite3_mutex_leave(db->mutex);
  153272. return rc;
  153273. #endif
  153274. }
  153275. /*
  153276. ** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
  153277. ** to contains a zero-length string, all attached databases are
  153278. ** checkpointed.
  153279. */
  153280. SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){
  153281. /* EVIDENCE-OF: R-41613-20553 The sqlite3_wal_checkpoint(D,X) is equivalent to
  153282. ** sqlite3_wal_checkpoint_v2(D,X,SQLITE_CHECKPOINT_PASSIVE,0,0). */
  153283. return sqlite3_wal_checkpoint_v2(db,zDb,SQLITE_CHECKPOINT_PASSIVE,0,0);
  153284. }
  153285. #ifndef SQLITE_OMIT_WAL
  153286. /*
  153287. ** Run a checkpoint on database iDb. This is a no-op if database iDb is
  153288. ** not currently open in WAL mode.
  153289. **
  153290. ** If a transaction is open on the database being checkpointed, this
  153291. ** function returns SQLITE_LOCKED and a checkpoint is not attempted. If
  153292. ** an error occurs while running the checkpoint, an SQLite error code is
  153293. ** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
  153294. **
  153295. ** The mutex on database handle db should be held by the caller. The mutex
  153296. ** associated with the specific b-tree being checkpointed is taken by
  153297. ** this function while the checkpoint is running.
  153298. **
  153299. ** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are
  153300. ** checkpointed. If an error is encountered it is returned immediately -
  153301. ** no attempt is made to checkpoint any remaining databases.
  153302. **
  153303. ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL, RESTART
  153304. ** or TRUNCATE.
  153305. */
  153306. SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){
  153307. int rc = SQLITE_OK; /* Return code */
  153308. int i; /* Used to iterate through attached dbs */
  153309. int bBusy = 0; /* True if SQLITE_BUSY has been encountered */
  153310. assert( sqlite3_mutex_held(db->mutex) );
  153311. assert( !pnLog || *pnLog==-1 );
  153312. assert( !pnCkpt || *pnCkpt==-1 );
  153313. for(i=0; i<db->nDb && rc==SQLITE_OK; i++){
  153314. if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){
  153315. rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt);
  153316. pnLog = 0;
  153317. pnCkpt = 0;
  153318. if( rc==SQLITE_BUSY ){
  153319. bBusy = 1;
  153320. rc = SQLITE_OK;
  153321. }
  153322. }
  153323. }
  153324. return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc;
  153325. }
  153326. #endif /* SQLITE_OMIT_WAL */
  153327. /*
  153328. ** This function returns true if main-memory should be used instead of
  153329. ** a temporary file for transient pager files and statement journals.
  153330. ** The value returned depends on the value of db->temp_store (runtime
  153331. ** parameter) and the compile time value of SQLITE_TEMP_STORE. The
  153332. ** following table describes the relationship between these two values
  153333. ** and this functions return value.
  153334. **
  153335. ** SQLITE_TEMP_STORE db->temp_store Location of temporary database
  153336. ** ----------------- -------------- ------------------------------
  153337. ** 0 any file (return 0)
  153338. ** 1 1 file (return 0)
  153339. ** 1 2 memory (return 1)
  153340. ** 1 0 file (return 0)
  153341. ** 2 1 file (return 0)
  153342. ** 2 2 memory (return 1)
  153343. ** 2 0 memory (return 1)
  153344. ** 3 any memory (return 1)
  153345. */
  153346. SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *db){
  153347. #if SQLITE_TEMP_STORE==1
  153348. return ( db->temp_store==2 );
  153349. #endif
  153350. #if SQLITE_TEMP_STORE==2
  153351. return ( db->temp_store!=1 );
  153352. #endif
  153353. #if SQLITE_TEMP_STORE==3
  153354. UNUSED_PARAMETER(db);
  153355. return 1;
  153356. #endif
  153357. #if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
  153358. UNUSED_PARAMETER(db);
  153359. return 0;
  153360. #endif
  153361. }
  153362. /*
  153363. ** Return UTF-8 encoded English language explanation of the most recent
  153364. ** error.
  153365. */
  153366. SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){
  153367. const char *z;
  153368. if( !db ){
  153369. return sqlite3ErrStr(SQLITE_NOMEM_BKPT);
  153370. }
  153371. if( !sqlite3SafetyCheckSickOrOk(db) ){
  153372. return sqlite3ErrStr(SQLITE_MISUSE_BKPT);
  153373. }
  153374. sqlite3_mutex_enter(db->mutex);
  153375. if( db->mallocFailed ){
  153376. z = sqlite3ErrStr(SQLITE_NOMEM_BKPT);
  153377. }else{
  153378. testcase( db->pErr==0 );
  153379. z = db->errCode ? (char*)sqlite3_value_text(db->pErr) : 0;
  153380. assert( !db->mallocFailed );
  153381. if( z==0 ){
  153382. z = sqlite3ErrStr(db->errCode);
  153383. }
  153384. }
  153385. sqlite3_mutex_leave(db->mutex);
  153386. return z;
  153387. }
  153388. #ifndef SQLITE_OMIT_UTF16
  153389. /*
  153390. ** Return UTF-16 encoded English language explanation of the most recent
  153391. ** error.
  153392. */
  153393. SQLITE_API const void *sqlite3_errmsg16(sqlite3 *db){
  153394. static const u16 outOfMem[] = {
  153395. 'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
  153396. };
  153397. static const u16 misuse[] = {
  153398. 'b', 'a', 'd', ' ', 'p', 'a', 'r', 'a', 'm', 'e', 't', 'e', 'r', ' ',
  153399. 'o', 'r', ' ', 'o', 't', 'h', 'e', 'r', ' ', 'A', 'P', 'I', ' ',
  153400. 'm', 'i', 's', 'u', 's', 'e', 0
  153401. };
  153402. const void *z;
  153403. if( !db ){
  153404. return (void *)outOfMem;
  153405. }
  153406. if( !sqlite3SafetyCheckSickOrOk(db) ){
  153407. return (void *)misuse;
  153408. }
  153409. sqlite3_mutex_enter(db->mutex);
  153410. if( db->mallocFailed ){
  153411. z = (void *)outOfMem;
  153412. }else{
  153413. z = sqlite3_value_text16(db->pErr);
  153414. if( z==0 ){
  153415. sqlite3ErrorWithMsg(db, db->errCode, sqlite3ErrStr(db->errCode));
  153416. z = sqlite3_value_text16(db->pErr);
  153417. }
  153418. /* A malloc() may have failed within the call to sqlite3_value_text16()
  153419. ** above. If this is the case, then the db->mallocFailed flag needs to
  153420. ** be cleared before returning. Do this directly, instead of via
  153421. ** sqlite3ApiExit(), to avoid setting the database handle error message.
  153422. */
  153423. sqlite3OomClear(db);
  153424. }
  153425. sqlite3_mutex_leave(db->mutex);
  153426. return z;
  153427. }
  153428. #endif /* SQLITE_OMIT_UTF16 */
  153429. /*
  153430. ** Return the most recent error code generated by an SQLite routine. If NULL is
  153431. ** passed to this function, we assume a malloc() failed during sqlite3_open().
  153432. */
  153433. SQLITE_API int sqlite3_errcode(sqlite3 *db){
  153434. if( db && !sqlite3SafetyCheckSickOrOk(db) ){
  153435. return SQLITE_MISUSE_BKPT;
  153436. }
  153437. if( !db || db->mallocFailed ){
  153438. return SQLITE_NOMEM_BKPT;
  153439. }
  153440. return db->errCode & db->errMask;
  153441. }
  153442. SQLITE_API int sqlite3_extended_errcode(sqlite3 *db){
  153443. if( db && !sqlite3SafetyCheckSickOrOk(db) ){
  153444. return SQLITE_MISUSE_BKPT;
  153445. }
  153446. if( !db || db->mallocFailed ){
  153447. return SQLITE_NOMEM_BKPT;
  153448. }
  153449. return db->errCode;
  153450. }
  153451. SQLITE_API int sqlite3_system_errno(sqlite3 *db){
  153452. return db ? db->iSysErrno : 0;
  153453. }
  153454. /*
  153455. ** Return a string that describes the kind of error specified in the
  153456. ** argument. For now, this simply calls the internal sqlite3ErrStr()
  153457. ** function.
  153458. */
  153459. SQLITE_API const char *sqlite3_errstr(int rc){
  153460. return sqlite3ErrStr(rc);
  153461. }
  153462. /*
  153463. ** Create a new collating function for database "db". The name is zName
  153464. ** and the encoding is enc.
  153465. */
  153466. static int createCollation(
  153467. sqlite3* db,
  153468. const char *zName,
  153469. u8 enc,
  153470. void* pCtx,
  153471. int(*xCompare)(void*,int,const void*,int,const void*),
  153472. void(*xDel)(void*)
  153473. ){
  153474. CollSeq *pColl;
  153475. int enc2;
  153476. assert( sqlite3_mutex_held(db->mutex) );
  153477. /* If SQLITE_UTF16 is specified as the encoding type, transform this
  153478. ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
  153479. ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
  153480. */
  153481. enc2 = enc;
  153482. testcase( enc2==SQLITE_UTF16 );
  153483. testcase( enc2==SQLITE_UTF16_ALIGNED );
  153484. if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
  153485. enc2 = SQLITE_UTF16NATIVE;
  153486. }
  153487. if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
  153488. return SQLITE_MISUSE_BKPT;
  153489. }
  153490. /* Check if this call is removing or replacing an existing collation
  153491. ** sequence. If so, and there are active VMs, return busy. If there
  153492. ** are no active VMs, invalidate any pre-compiled statements.
  153493. */
  153494. pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
  153495. if( pColl && pColl->xCmp ){
  153496. if( db->nVdbeActive ){
  153497. sqlite3ErrorWithMsg(db, SQLITE_BUSY,
  153498. "unable to delete/modify collation sequence due to active statements");
  153499. return SQLITE_BUSY;
  153500. }
  153501. sqlite3ExpirePreparedStatements(db, 0);
  153502. /* If collation sequence pColl was created directly by a call to
  153503. ** sqlite3_create_collation, and not generated by synthCollSeq(),
  153504. ** then any copies made by synthCollSeq() need to be invalidated.
  153505. ** Also, collation destructor - CollSeq.xDel() - function may need
  153506. ** to be called.
  153507. */
  153508. if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
  153509. CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName);
  153510. int j;
  153511. for(j=0; j<3; j++){
  153512. CollSeq *p = &aColl[j];
  153513. if( p->enc==pColl->enc ){
  153514. if( p->xDel ){
  153515. p->xDel(p->pUser);
  153516. }
  153517. p->xCmp = 0;
  153518. }
  153519. }
  153520. }
  153521. }
  153522. pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
  153523. if( pColl==0 ) return SQLITE_NOMEM_BKPT;
  153524. pColl->xCmp = xCompare;
  153525. pColl->pUser = pCtx;
  153526. pColl->xDel = xDel;
  153527. pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
  153528. sqlite3Error(db, SQLITE_OK);
  153529. return SQLITE_OK;
  153530. }
  153531. /*
  153532. ** This array defines hard upper bounds on limit values. The
  153533. ** initializer must be kept in sync with the SQLITE_LIMIT_*
  153534. ** #defines in sqlite3.h.
  153535. */
  153536. static const int aHardLimit[] = {
  153537. SQLITE_MAX_LENGTH,
  153538. SQLITE_MAX_SQL_LENGTH,
  153539. SQLITE_MAX_COLUMN,
  153540. SQLITE_MAX_EXPR_DEPTH,
  153541. SQLITE_MAX_COMPOUND_SELECT,
  153542. SQLITE_MAX_VDBE_OP,
  153543. SQLITE_MAX_FUNCTION_ARG,
  153544. SQLITE_MAX_ATTACHED,
  153545. SQLITE_MAX_LIKE_PATTERN_LENGTH,
  153546. SQLITE_MAX_VARIABLE_NUMBER, /* IMP: R-38091-32352 */
  153547. SQLITE_MAX_TRIGGER_DEPTH,
  153548. SQLITE_MAX_WORKER_THREADS,
  153549. };
  153550. /*
  153551. ** Make sure the hard limits are set to reasonable values
  153552. */
  153553. #if SQLITE_MAX_LENGTH<100
  153554. # error SQLITE_MAX_LENGTH must be at least 100
  153555. #endif
  153556. #if SQLITE_MAX_SQL_LENGTH<100
  153557. # error SQLITE_MAX_SQL_LENGTH must be at least 100
  153558. #endif
  153559. #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
  153560. # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
  153561. #endif
  153562. #if SQLITE_MAX_COMPOUND_SELECT<2
  153563. # error SQLITE_MAX_COMPOUND_SELECT must be at least 2
  153564. #endif
  153565. #if SQLITE_MAX_VDBE_OP<40
  153566. # error SQLITE_MAX_VDBE_OP must be at least 40
  153567. #endif
  153568. #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>127
  153569. # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 127
  153570. #endif
  153571. #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>125
  153572. # error SQLITE_MAX_ATTACHED must be between 0 and 125
  153573. #endif
  153574. #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
  153575. # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
  153576. #endif
  153577. #if SQLITE_MAX_COLUMN>32767
  153578. # error SQLITE_MAX_COLUMN must not exceed 32767
  153579. #endif
  153580. #if SQLITE_MAX_TRIGGER_DEPTH<1
  153581. # error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
  153582. #endif
  153583. #if SQLITE_MAX_WORKER_THREADS<0 || SQLITE_MAX_WORKER_THREADS>50
  153584. # error SQLITE_MAX_WORKER_THREADS must be between 0 and 50
  153585. #endif
  153586. /*
  153587. ** Change the value of a limit. Report the old value.
  153588. ** If an invalid limit index is supplied, report -1.
  153589. ** Make no changes but still report the old value if the
  153590. ** new limit is negative.
  153591. **
  153592. ** A new lower limit does not shrink existing constructs.
  153593. ** It merely prevents new constructs that exceed the limit
  153594. ** from forming.
  153595. */
  153596. SQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
  153597. int oldLimit;
  153598. #ifdef SQLITE_ENABLE_API_ARMOR
  153599. if( !sqlite3SafetyCheckOk(db) ){
  153600. (void)SQLITE_MISUSE_BKPT;
  153601. return -1;
  153602. }
  153603. #endif
  153604. /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME
  153605. ** there is a hard upper bound set at compile-time by a C preprocessor
  153606. ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to
  153607. ** "_MAX_".)
  153608. */
  153609. assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH );
  153610. assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH );
  153611. assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN );
  153612. assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH );
  153613. assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT);
  153614. assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP );
  153615. assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG );
  153616. assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED );
  153617. assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]==
  153618. SQLITE_MAX_LIKE_PATTERN_LENGTH );
  153619. assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER);
  153620. assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH );
  153621. assert( aHardLimit[SQLITE_LIMIT_WORKER_THREADS]==SQLITE_MAX_WORKER_THREADS );
  153622. assert( SQLITE_LIMIT_WORKER_THREADS==(SQLITE_N_LIMIT-1) );
  153623. if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
  153624. return -1;
  153625. }
  153626. oldLimit = db->aLimit[limitId];
  153627. if( newLimit>=0 ){ /* IMP: R-52476-28732 */
  153628. if( newLimit>aHardLimit[limitId] ){
  153629. newLimit = aHardLimit[limitId]; /* IMP: R-51463-25634 */
  153630. }
  153631. db->aLimit[limitId] = newLimit;
  153632. }
  153633. return oldLimit; /* IMP: R-53341-35419 */
  153634. }
  153635. /*
  153636. ** This function is used to parse both URIs and non-URI filenames passed by the
  153637. ** user to API functions sqlite3_open() or sqlite3_open_v2(), and for database
  153638. ** URIs specified as part of ATTACH statements.
  153639. **
  153640. ** The first argument to this function is the name of the VFS to use (or
  153641. ** a NULL to signify the default VFS) if the URI does not contain a "vfs=xxx"
  153642. ** query parameter. The second argument contains the URI (or non-URI filename)
  153643. ** itself. When this function is called the *pFlags variable should contain
  153644. ** the default flags to open the database handle with. The value stored in
  153645. ** *pFlags may be updated before returning if the URI filename contains
  153646. ** "cache=xxx" or "mode=xxx" query parameters.
  153647. **
  153648. ** If successful, SQLITE_OK is returned. In this case *ppVfs is set to point to
  153649. ** the VFS that should be used to open the database file. *pzFile is set to
  153650. ** point to a buffer containing the name of the file to open. The value
  153651. ** stored in *pzFile is a database name acceptable to sqlite3_uri_parameter()
  153652. ** and is in the same format as names created using sqlite3_create_filename().
  153653. ** The caller must invoke sqlite3_free_filename() (not sqlite3_free()!) on
  153654. ** the value returned in *pzFile to avoid a memory leak.
  153655. **
  153656. ** If an error occurs, then an SQLite error code is returned and *pzErrMsg
  153657. ** may be set to point to a buffer containing an English language error
  153658. ** message. It is the responsibility of the caller to eventually release
  153659. ** this buffer by calling sqlite3_free().
  153660. */
  153661. SQLITE_PRIVATE int sqlite3ParseUri(
  153662. const char *zDefaultVfs, /* VFS to use if no "vfs=xxx" query option */
  153663. const char *zUri, /* Nul-terminated URI to parse */
  153664. unsigned int *pFlags, /* IN/OUT: SQLITE_OPEN_XXX flags */
  153665. sqlite3_vfs **ppVfs, /* OUT: VFS to use */
  153666. char **pzFile, /* OUT: Filename component of URI */
  153667. char **pzErrMsg /* OUT: Error message (if rc!=SQLITE_OK) */
  153668. ){
  153669. int rc = SQLITE_OK;
  153670. unsigned int flags = *pFlags;
  153671. const char *zVfs = zDefaultVfs;
  153672. char *zFile;
  153673. char c;
  153674. int nUri = sqlite3Strlen30(zUri);
  153675. assert( *pzErrMsg==0 );
  153676. if( ((flags & SQLITE_OPEN_URI) /* IMP: R-48725-32206 */
  153677. || sqlite3GlobalConfig.bOpenUri) /* IMP: R-51689-46548 */
  153678. && nUri>=5 && memcmp(zUri, "file:", 5)==0 /* IMP: R-57884-37496 */
  153679. ){
  153680. char *zOpt;
  153681. int eState; /* Parser state when parsing URI */
  153682. int iIn; /* Input character index */
  153683. int iOut = 0; /* Output character index */
  153684. u64 nByte = nUri+8; /* Bytes of space to allocate */
  153685. /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen
  153686. ** method that there may be extra parameters following the file-name. */
  153687. flags |= SQLITE_OPEN_URI;
  153688. for(iIn=0; iIn<nUri; iIn++) nByte += (zUri[iIn]=='&');
  153689. zFile = sqlite3_malloc64(nByte);
  153690. if( !zFile ) return SQLITE_NOMEM_BKPT;
  153691. memset(zFile, 0, 4); /* 4-byte of 0x00 is the start of DB name marker */
  153692. zFile += 4;
  153693. iIn = 5;
  153694. #ifdef SQLITE_ALLOW_URI_AUTHORITY
  153695. if( strncmp(zUri+5, "///", 3)==0 ){
  153696. iIn = 7;
  153697. /* The following condition causes URIs with five leading / characters
  153698. ** like file://///host/path to be converted into UNCs like //host/path.
  153699. ** The correct URI for that UNC has only two or four leading / characters
  153700. ** file://host/path or file:////host/path. But 5 leading slashes is a
  153701. ** common error, we are told, so we handle it as a special case. */
  153702. if( strncmp(zUri+7, "///", 3)==0 ){ iIn++; }
  153703. }else if( strncmp(zUri+5, "//localhost/", 12)==0 ){
  153704. iIn = 16;
  153705. }
  153706. #else
  153707. /* Discard the scheme and authority segments of the URI. */
  153708. if( zUri[5]=='/' && zUri[6]=='/' ){
  153709. iIn = 7;
  153710. while( zUri[iIn] && zUri[iIn]!='/' ) iIn++;
  153711. if( iIn!=7 && (iIn!=16 || memcmp("localhost", &zUri[7], 9)) ){
  153712. *pzErrMsg = sqlite3_mprintf("invalid uri authority: %.*s",
  153713. iIn-7, &zUri[7]);
  153714. rc = SQLITE_ERROR;
  153715. goto parse_uri_out;
  153716. }
  153717. }
  153718. #endif
  153719. /* Copy the filename and any query parameters into the zFile buffer.
  153720. ** Decode %HH escape codes along the way.
  153721. **
  153722. ** Within this loop, variable eState may be set to 0, 1 or 2, depending
  153723. ** on the parsing context. As follows:
  153724. **
  153725. ** 0: Parsing file-name.
  153726. ** 1: Parsing name section of a name=value query parameter.
  153727. ** 2: Parsing value section of a name=value query parameter.
  153728. */
  153729. eState = 0;
  153730. while( (c = zUri[iIn])!=0 && c!='#' ){
  153731. iIn++;
  153732. if( c=='%'
  153733. && sqlite3Isxdigit(zUri[iIn])
  153734. && sqlite3Isxdigit(zUri[iIn+1])
  153735. ){
  153736. int octet = (sqlite3HexToInt(zUri[iIn++]) << 4);
  153737. octet += sqlite3HexToInt(zUri[iIn++]);
  153738. assert( octet>=0 && octet<256 );
  153739. if( octet==0 ){
  153740. #ifndef SQLITE_ENABLE_URI_00_ERROR
  153741. /* This branch is taken when "%00" appears within the URI. In this
  153742. ** case we ignore all text in the remainder of the path, name or
  153743. ** value currently being parsed. So ignore the current character
  153744. ** and skip to the next "?", "=" or "&", as appropriate. */
  153745. while( (c = zUri[iIn])!=0 && c!='#'
  153746. && (eState!=0 || c!='?')
  153747. && (eState!=1 || (c!='=' && c!='&'))
  153748. && (eState!=2 || c!='&')
  153749. ){
  153750. iIn++;
  153751. }
  153752. continue;
  153753. #else
  153754. /* If ENABLE_URI_00_ERROR is defined, "%00" in a URI is an error. */
  153755. *pzErrMsg = sqlite3_mprintf("unexpected %%00 in uri");
  153756. rc = SQLITE_ERROR;
  153757. goto parse_uri_out;
  153758. #endif
  153759. }
  153760. c = octet;
  153761. }else if( eState==1 && (c=='&' || c=='=') ){
  153762. if( zFile[iOut-1]==0 ){
  153763. /* An empty option name. Ignore this option altogether. */
  153764. while( zUri[iIn] && zUri[iIn]!='#' && zUri[iIn-1]!='&' ) iIn++;
  153765. continue;
  153766. }
  153767. if( c=='&' ){
  153768. zFile[iOut++] = '\0';
  153769. }else{
  153770. eState = 2;
  153771. }
  153772. c = 0;
  153773. }else if( (eState==0 && c=='?') || (eState==2 && c=='&') ){
  153774. c = 0;
  153775. eState = 1;
  153776. }
  153777. zFile[iOut++] = c;
  153778. }
  153779. if( eState==1 ) zFile[iOut++] = '\0';
  153780. memset(zFile+iOut, 0, 4); /* end-of-options + empty journal filenames */
  153781. /* Check if there were any options specified that should be interpreted
  153782. ** here. Options that are interpreted here include "vfs" and those that
  153783. ** correspond to flags that may be passed to the sqlite3_open_v2()
  153784. ** method. */
  153785. zOpt = &zFile[sqlite3Strlen30(zFile)+1];
  153786. while( zOpt[0] ){
  153787. int nOpt = sqlite3Strlen30(zOpt);
  153788. char *zVal = &zOpt[nOpt+1];
  153789. int nVal = sqlite3Strlen30(zVal);
  153790. if( nOpt==3 && memcmp("vfs", zOpt, 3)==0 ){
  153791. zVfs = zVal;
  153792. }else{
  153793. struct OpenMode {
  153794. const char *z;
  153795. int mode;
  153796. } *aMode = 0;
  153797. char *zModeType = 0;
  153798. int mask = 0;
  153799. int limit = 0;
  153800. if( nOpt==5 && memcmp("cache", zOpt, 5)==0 ){
  153801. static struct OpenMode aCacheMode[] = {
  153802. { "shared", SQLITE_OPEN_SHAREDCACHE },
  153803. { "private", SQLITE_OPEN_PRIVATECACHE },
  153804. { 0, 0 }
  153805. };
  153806. mask = SQLITE_OPEN_SHAREDCACHE|SQLITE_OPEN_PRIVATECACHE;
  153807. aMode = aCacheMode;
  153808. limit = mask;
  153809. zModeType = "cache";
  153810. }
  153811. if( nOpt==4 && memcmp("mode", zOpt, 4)==0 ){
  153812. static struct OpenMode aOpenMode[] = {
  153813. { "ro", SQLITE_OPEN_READONLY },
  153814. { "rw", SQLITE_OPEN_READWRITE },
  153815. { "rwc", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE },
  153816. { "memory", SQLITE_OPEN_MEMORY },
  153817. { 0, 0 }
  153818. };
  153819. mask = SQLITE_OPEN_READONLY | SQLITE_OPEN_READWRITE
  153820. | SQLITE_OPEN_CREATE | SQLITE_OPEN_MEMORY;
  153821. aMode = aOpenMode;
  153822. limit = mask & flags;
  153823. zModeType = "access";
  153824. }
  153825. if( aMode ){
  153826. int i;
  153827. int mode = 0;
  153828. for(i=0; aMode[i].z; i++){
  153829. const char *z = aMode[i].z;
  153830. if( nVal==sqlite3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){
  153831. mode = aMode[i].mode;
  153832. break;
  153833. }
  153834. }
  153835. if( mode==0 ){
  153836. *pzErrMsg = sqlite3_mprintf("no such %s mode: %s", zModeType, zVal);
  153837. rc = SQLITE_ERROR;
  153838. goto parse_uri_out;
  153839. }
  153840. if( (mode & ~SQLITE_OPEN_MEMORY)>limit ){
  153841. *pzErrMsg = sqlite3_mprintf("%s mode not allowed: %s",
  153842. zModeType, zVal);
  153843. rc = SQLITE_PERM;
  153844. goto parse_uri_out;
  153845. }
  153846. flags = (flags & ~mask) | mode;
  153847. }
  153848. }
  153849. zOpt = &zVal[nVal+1];
  153850. }
  153851. }else{
  153852. zFile = sqlite3_malloc64(nUri+8);
  153853. if( !zFile ) return SQLITE_NOMEM_BKPT;
  153854. memset(zFile, 0, 4);
  153855. zFile += 4;
  153856. if( nUri ){
  153857. memcpy(zFile, zUri, nUri);
  153858. }
  153859. memset(zFile+nUri, 0, 4);
  153860. flags &= ~SQLITE_OPEN_URI;
  153861. }
  153862. *ppVfs = sqlite3_vfs_find(zVfs);
  153863. if( *ppVfs==0 ){
  153864. *pzErrMsg = sqlite3_mprintf("no such vfs: %s", zVfs);
  153865. rc = SQLITE_ERROR;
  153866. }
  153867. parse_uri_out:
  153868. if( rc!=SQLITE_OK ){
  153869. sqlite3_free_filename(zFile);
  153870. zFile = 0;
  153871. }
  153872. *pFlags = flags;
  153873. *pzFile = zFile;
  153874. return rc;
  153875. }
  153876. /*
  153877. ** This routine does the core work of extracting URI parameters from a
  153878. ** database filename for the sqlite3_uri_parameter() interface.
  153879. */
  153880. static const char *uriParameter(const char *zFilename, const char *zParam){
  153881. zFilename += sqlite3Strlen30(zFilename) + 1;
  153882. while( zFilename[0] ){
  153883. int x = strcmp(zFilename, zParam);
  153884. zFilename += sqlite3Strlen30(zFilename) + 1;
  153885. if( x==0 ) return zFilename;
  153886. zFilename += sqlite3Strlen30(zFilename) + 1;
  153887. }
  153888. return 0;
  153889. }
  153890. /*
  153891. ** This routine does the work of opening a database on behalf of
  153892. ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"
  153893. ** is UTF-8 encoded.
  153894. */
  153895. static int openDatabase(
  153896. const char *zFilename, /* Database filename UTF-8 encoded */
  153897. sqlite3 **ppDb, /* OUT: Returned database handle */
  153898. unsigned int flags, /* Operational flags */
  153899. const char *zVfs /* Name of the VFS to use */
  153900. ){
  153901. sqlite3 *db; /* Store allocated handle here */
  153902. int rc; /* Return code */
  153903. int isThreadsafe; /* True for threadsafe connections */
  153904. char *zOpen = 0; /* Filename argument to pass to BtreeOpen() */
  153905. char *zErrMsg = 0; /* Error message from sqlite3ParseUri() */
  153906. int i; /* Loop counter */
  153907. #ifdef SQLITE_ENABLE_API_ARMOR
  153908. if( ppDb==0 ) return SQLITE_MISUSE_BKPT;
  153909. #endif
  153910. *ppDb = 0;
  153911. #ifndef SQLITE_OMIT_AUTOINIT
  153912. rc = sqlite3_initialize();
  153913. if( rc ) return rc;
  153914. #endif
  153915. if( sqlite3GlobalConfig.bCoreMutex==0 ){
  153916. isThreadsafe = 0;
  153917. }else if( flags & SQLITE_OPEN_NOMUTEX ){
  153918. isThreadsafe = 0;
  153919. }else if( flags & SQLITE_OPEN_FULLMUTEX ){
  153920. isThreadsafe = 1;
  153921. }else{
  153922. isThreadsafe = sqlite3GlobalConfig.bFullMutex;
  153923. }
  153924. if( flags & SQLITE_OPEN_PRIVATECACHE ){
  153925. flags &= ~SQLITE_OPEN_SHAREDCACHE;
  153926. }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
  153927. flags |= SQLITE_OPEN_SHAREDCACHE;
  153928. }
  153929. /* Remove harmful bits from the flags parameter
  153930. **
  153931. ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
  153932. ** dealt with in the previous code block. Besides these, the only
  153933. ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
  153934. ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE,
  153935. ** SQLITE_OPEN_PRIVATECACHE, and some reserved bits. Silently mask
  153936. ** off all other flags.
  153937. */
  153938. flags &= ~( SQLITE_OPEN_DELETEONCLOSE |
  153939. SQLITE_OPEN_EXCLUSIVE |
  153940. SQLITE_OPEN_MAIN_DB |
  153941. SQLITE_OPEN_TEMP_DB |
  153942. SQLITE_OPEN_TRANSIENT_DB |
  153943. SQLITE_OPEN_MAIN_JOURNAL |
  153944. SQLITE_OPEN_TEMP_JOURNAL |
  153945. SQLITE_OPEN_SUBJOURNAL |
  153946. SQLITE_OPEN_MASTER_JOURNAL |
  153947. SQLITE_OPEN_NOMUTEX |
  153948. SQLITE_OPEN_FULLMUTEX |
  153949. SQLITE_OPEN_WAL
  153950. );
  153951. /* Allocate the sqlite data structure */
  153952. db = sqlite3MallocZero( sizeof(sqlite3) );
  153953. if( db==0 ) goto opendb_out;
  153954. if( isThreadsafe
  153955. #ifdef SQLITE_ENABLE_MULTITHREADED_CHECKS
  153956. || sqlite3GlobalConfig.bCoreMutex
  153957. #endif
  153958. ){
  153959. db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
  153960. if( db->mutex==0 ){
  153961. sqlite3_free(db);
  153962. db = 0;
  153963. goto opendb_out;
  153964. }
  153965. if( isThreadsafe==0 ){
  153966. sqlite3MutexWarnOnContention(db->mutex);
  153967. }
  153968. }
  153969. sqlite3_mutex_enter(db->mutex);
  153970. db->errMask = 0xff;
  153971. db->nDb = 2;
  153972. db->magic = SQLITE_MAGIC_BUSY;
  153973. db->aDb = db->aDbStatic;
  153974. db->lookaside.bDisable = 1;
  153975. db->lookaside.sz = 0;
  153976. assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
  153977. memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
  153978. db->aLimit[SQLITE_LIMIT_WORKER_THREADS] = SQLITE_DEFAULT_WORKER_THREADS;
  153979. db->autoCommit = 1;
  153980. db->nextAutovac = -1;
  153981. db->szMmap = sqlite3GlobalConfig.szMmap;
  153982. db->nextPagesize = 0;
  153983. db->nMaxSorterMmap = 0x7FFFFFFF;
  153984. db->flags |= SQLITE_ShortColNames
  153985. | SQLITE_EnableTrigger
  153986. | SQLITE_EnableView
  153987. | SQLITE_CacheSpill
  153988. #if !defined(SQLITE_TRUSTED_SCHEMA) || SQLITE_TRUSTED_SCHEMA+0!=0
  153989. | SQLITE_TrustedSchema
  153990. #endif
  153991. /* The SQLITE_DQS compile-time option determines the default settings
  153992. ** for SQLITE_DBCONFIG_DQS_DDL and SQLITE_DBCONFIG_DQS_DML.
  153993. **
  153994. ** SQLITE_DQS SQLITE_DBCONFIG_DQS_DDL SQLITE_DBCONFIG_DQS_DML
  153995. ** ---------- ----------------------- -----------------------
  153996. ** undefined on on
  153997. ** 3 on on
  153998. ** 2 on off
  153999. ** 1 off on
  154000. ** 0 off off
  154001. **
  154002. ** Legacy behavior is 3 (double-quoted string literals are allowed anywhere)
  154003. ** and so that is the default. But developers are encouranged to use
  154004. ** -DSQLITE_DQS=0 (best) or -DSQLITE_DQS=1 (second choice) if possible.
  154005. */
  154006. #if !defined(SQLITE_DQS)
  154007. # define SQLITE_DQS 3
  154008. #endif
  154009. #if (SQLITE_DQS&1)==1
  154010. | SQLITE_DqsDML
  154011. #endif
  154012. #if (SQLITE_DQS&2)==2
  154013. | SQLITE_DqsDDL
  154014. #endif
  154015. #if !defined(SQLITE_DEFAULT_AUTOMATIC_INDEX) || SQLITE_DEFAULT_AUTOMATIC_INDEX
  154016. | SQLITE_AutoIndex
  154017. #endif
  154018. #if SQLITE_DEFAULT_CKPTFULLFSYNC
  154019. | SQLITE_CkptFullFSync
  154020. #endif
  154021. #if SQLITE_DEFAULT_FILE_FORMAT<4
  154022. | SQLITE_LegacyFileFmt
  154023. #endif
  154024. #ifdef SQLITE_ENABLE_LOAD_EXTENSION
  154025. | SQLITE_LoadExtension
  154026. #endif
  154027. #if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
  154028. | SQLITE_RecTriggers
  154029. #endif
  154030. #if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS
  154031. | SQLITE_ForeignKeys
  154032. #endif
  154033. #if defined(SQLITE_REVERSE_UNORDERED_SELECTS)
  154034. | SQLITE_ReverseOrder
  154035. #endif
  154036. #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
  154037. | SQLITE_CellSizeCk
  154038. #endif
  154039. #if defined(SQLITE_ENABLE_FTS3_TOKENIZER)
  154040. | SQLITE_Fts3Tokenizer
  154041. #endif
  154042. #if defined(SQLITE_ENABLE_QPSG)
  154043. | SQLITE_EnableQPSG
  154044. #endif
  154045. #if defined(SQLITE_DEFAULT_DEFENSIVE)
  154046. | SQLITE_Defensive
  154047. #endif
  154048. #if defined(SQLITE_DEFAULT_LEGACY_ALTER_TABLE)
  154049. | SQLITE_LegacyAlter
  154050. #endif
  154051. ;
  154052. sqlite3HashInit(&db->aCollSeq);
  154053. #ifndef SQLITE_OMIT_VIRTUALTABLE
  154054. sqlite3HashInit(&db->aModule);
  154055. #endif
  154056. /* Add the default collation sequence BINARY. BINARY works for both UTF-8
  154057. ** and UTF-16, so add a version for each to avoid any unnecessary
  154058. ** conversions. The only error that can occur here is a malloc() failure.
  154059. **
  154060. ** EVIDENCE-OF: R-52786-44878 SQLite defines three built-in collating
  154061. ** functions:
  154062. */
  154063. createCollation(db, sqlite3StrBINARY, SQLITE_UTF8, 0, binCollFunc, 0);
  154064. createCollation(db, sqlite3StrBINARY, SQLITE_UTF16BE, 0, binCollFunc, 0);
  154065. createCollation(db, sqlite3StrBINARY, SQLITE_UTF16LE, 0, binCollFunc, 0);
  154066. createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);
  154067. createCollation(db, "RTRIM", SQLITE_UTF8, 0, rtrimCollFunc, 0);
  154068. if( db->mallocFailed ){
  154069. goto opendb_out;
  154070. }
  154071. /* Parse the filename/URI argument
  154072. **
  154073. ** Only allow sensible combinations of bits in the flags argument.
  154074. ** Throw an error if any non-sense combination is used. If we
  154075. ** do not block illegal combinations here, it could trigger
  154076. ** assert() statements in deeper layers. Sensible combinations
  154077. ** are:
  154078. **
  154079. ** 1: SQLITE_OPEN_READONLY
  154080. ** 2: SQLITE_OPEN_READWRITE
  154081. ** 6: SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
  154082. */
  154083. db->openFlags = flags;
  154084. assert( SQLITE_OPEN_READONLY == 0x01 );
  154085. assert( SQLITE_OPEN_READWRITE == 0x02 );
  154086. assert( SQLITE_OPEN_CREATE == 0x04 );
  154087. testcase( (1<<(flags&7))==0x02 ); /* READONLY */
  154088. testcase( (1<<(flags&7))==0x04 ); /* READWRITE */
  154089. testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */
  154090. if( ((1<<(flags&7)) & 0x46)==0 ){
  154091. rc = SQLITE_MISUSE_BKPT; /* IMP: R-18321-05872 */
  154092. }else{
  154093. rc = sqlite3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg);
  154094. }
  154095. if( rc!=SQLITE_OK ){
  154096. if( rc==SQLITE_NOMEM ) sqlite3OomFault(db);
  154097. sqlite3ErrorWithMsg(db, rc, zErrMsg ? "%s" : 0, zErrMsg);
  154098. sqlite3_free(zErrMsg);
  154099. goto opendb_out;
  154100. }
  154101. /* Open the backend database driver */
  154102. rc = sqlite3BtreeOpen(db->pVfs, zOpen, db, &db->aDb[0].pBt, 0,
  154103. flags | SQLITE_OPEN_MAIN_DB);
  154104. if( rc!=SQLITE_OK ){
  154105. if( rc==SQLITE_IOERR_NOMEM ){
  154106. rc = SQLITE_NOMEM_BKPT;
  154107. }
  154108. sqlite3Error(db, rc);
  154109. goto opendb_out;
  154110. }
  154111. sqlite3BtreeEnter(db->aDb[0].pBt);
  154112. db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
  154113. if( !db->mallocFailed ){
  154114. sqlite3SetTextEncoding(db, SCHEMA_ENC(db));
  154115. }
  154116. sqlite3BtreeLeave(db->aDb[0].pBt);
  154117. db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
  154118. /* The default safety_level for the main database is FULL; for the temp
  154119. ** database it is OFF. This matches the pager layer defaults.
  154120. */
  154121. db->aDb[0].zDbSName = "main";
  154122. db->aDb[0].safety_level = SQLITE_DEFAULT_SYNCHRONOUS+1;
  154123. db->aDb[1].zDbSName = "temp";
  154124. db->aDb[1].safety_level = PAGER_SYNCHRONOUS_OFF;
  154125. db->magic = SQLITE_MAGIC_OPEN;
  154126. if( db->mallocFailed ){
  154127. goto opendb_out;
  154128. }
  154129. /* Register all built-in functions, but do not attempt to read the
  154130. ** database schema yet. This is delayed until the first time the database
  154131. ** is accessed.
  154132. */
  154133. sqlite3Error(db, SQLITE_OK);
  154134. sqlite3RegisterPerConnectionBuiltinFunctions(db);
  154135. rc = sqlite3_errcode(db);
  154136. /* Load compiled-in extensions */
  154137. for(i=0; rc==SQLITE_OK && i<ArraySize(sqlite3BuiltinExtensions); i++){
  154138. rc = sqlite3BuiltinExtensions[i](db);
  154139. }
  154140. /* Load automatic extensions - extensions that have been registered
  154141. ** using the sqlite3_automatic_extension() API.
  154142. */
  154143. if( rc==SQLITE_OK ){
  154144. sqlite3AutoLoadExtensions(db);
  154145. rc = sqlite3_errcode(db);
  154146. if( rc!=SQLITE_OK ){
  154147. goto opendb_out;
  154148. }
  154149. }
  154150. #ifdef SQLITE_ENABLE_INTERNAL_FUNCTIONS
  154151. /* Testing use only!!! The -DSQLITE_ENABLE_INTERNAL_FUNCTIONS=1 compile-time
  154152. ** option gives access to internal functions by default.
  154153. ** Testing use only!!! */
  154154. db->mDbFlags |= DBFLAG_InternalFunc;
  154155. #endif
  154156. /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
  154157. ** mode. -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
  154158. ** mode. Doing nothing at all also makes NORMAL the default.
  154159. */
  154160. #ifdef SQLITE_DEFAULT_LOCKING_MODE
  154161. db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
  154162. sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
  154163. SQLITE_DEFAULT_LOCKING_MODE);
  154164. #endif
  154165. if( rc ) sqlite3Error(db, rc);
  154166. /* Enable the lookaside-malloc subsystem */
  154167. setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
  154168. sqlite3GlobalConfig.nLookaside);
  154169. sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT);
  154170. opendb_out:
  154171. if( db ){
  154172. assert( db->mutex!=0 || isThreadsafe==0
  154173. || sqlite3GlobalConfig.bFullMutex==0 );
  154174. sqlite3_mutex_leave(db->mutex);
  154175. }
  154176. rc = sqlite3_errcode(db);
  154177. assert( db!=0 || rc==SQLITE_NOMEM );
  154178. if( rc==SQLITE_NOMEM ){
  154179. sqlite3_close(db);
  154180. db = 0;
  154181. }else if( rc!=SQLITE_OK ){
  154182. db->magic = SQLITE_MAGIC_SICK;
  154183. }
  154184. *ppDb = db;
  154185. #ifdef SQLITE_ENABLE_SQLLOG
  154186. if( sqlite3GlobalConfig.xSqllog ){
  154187. /* Opening a db handle. Fourth parameter is passed 0. */
  154188. void *pArg = sqlite3GlobalConfig.pSqllogArg;
  154189. sqlite3GlobalConfig.xSqllog(pArg, db, zFilename, 0);
  154190. }
  154191. #endif
  154192. sqlite3_free_filename(zOpen);
  154193. return rc & 0xff;
  154194. }
  154195. /*
  154196. ** Open a new database handle.
  154197. */
  154198. SQLITE_API int sqlite3_open(
  154199. const char *zFilename,
  154200. sqlite3 **ppDb
  154201. ){
  154202. return openDatabase(zFilename, ppDb,
  154203. SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
  154204. }
  154205. SQLITE_API int sqlite3_open_v2(
  154206. const char *filename, /* Database filename (UTF-8) */
  154207. sqlite3 **ppDb, /* OUT: SQLite db handle */
  154208. int flags, /* Flags */
  154209. const char *zVfs /* Name of VFS module to use */
  154210. ){
  154211. return openDatabase(filename, ppDb, (unsigned int)flags, zVfs);
  154212. }
  154213. #ifndef SQLITE_OMIT_UTF16
  154214. /*
  154215. ** Open a new database handle.
  154216. */
  154217. SQLITE_API int sqlite3_open16(
  154218. const void *zFilename,
  154219. sqlite3 **ppDb
  154220. ){
  154221. char const *zFilename8; /* zFilename encoded in UTF-8 instead of UTF-16 */
  154222. sqlite3_value *pVal;
  154223. int rc;
  154224. #ifdef SQLITE_ENABLE_API_ARMOR
  154225. if( ppDb==0 ) return SQLITE_MISUSE_BKPT;
  154226. #endif
  154227. *ppDb = 0;
  154228. #ifndef SQLITE_OMIT_AUTOINIT
  154229. rc = sqlite3_initialize();
  154230. if( rc ) return rc;
  154231. #endif
  154232. if( zFilename==0 ) zFilename = "\000\000";
  154233. pVal = sqlite3ValueNew(0);
  154234. sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
  154235. zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
  154236. if( zFilename8 ){
  154237. rc = openDatabase(zFilename8, ppDb,
  154238. SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
  154239. assert( *ppDb || rc==SQLITE_NOMEM );
  154240. if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
  154241. SCHEMA_ENC(*ppDb) = ENC(*ppDb) = SQLITE_UTF16NATIVE;
  154242. }
  154243. }else{
  154244. rc = SQLITE_NOMEM_BKPT;
  154245. }
  154246. sqlite3ValueFree(pVal);
  154247. return rc & 0xff;
  154248. }
  154249. #endif /* SQLITE_OMIT_UTF16 */
  154250. /*
  154251. ** Register a new collation sequence with the database handle db.
  154252. */
  154253. SQLITE_API int sqlite3_create_collation(
  154254. sqlite3* db,
  154255. const char *zName,
  154256. int enc,
  154257. void* pCtx,
  154258. int(*xCompare)(void*,int,const void*,int,const void*)
  154259. ){
  154260. return sqlite3_create_collation_v2(db, zName, enc, pCtx, xCompare, 0);
  154261. }
  154262. /*
  154263. ** Register a new collation sequence with the database handle db.
  154264. */
  154265. SQLITE_API int sqlite3_create_collation_v2(
  154266. sqlite3* db,
  154267. const char *zName,
  154268. int enc,
  154269. void* pCtx,
  154270. int(*xCompare)(void*,int,const void*,int,const void*),
  154271. void(*xDel)(void*)
  154272. ){
  154273. int rc;
  154274. #ifdef SQLITE_ENABLE_API_ARMOR
  154275. if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
  154276. #endif
  154277. sqlite3_mutex_enter(db->mutex);
  154278. assert( !db->mallocFailed );
  154279. rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, xDel);
  154280. rc = sqlite3ApiExit(db, rc);
  154281. sqlite3_mutex_leave(db->mutex);
  154282. return rc;
  154283. }
  154284. #ifndef SQLITE_OMIT_UTF16
  154285. /*
  154286. ** Register a new collation sequence with the database handle db.
  154287. */
  154288. SQLITE_API int sqlite3_create_collation16(
  154289. sqlite3* db,
  154290. const void *zName,
  154291. int enc,
  154292. void* pCtx,
  154293. int(*xCompare)(void*,int,const void*,int,const void*)
  154294. ){
  154295. int rc = SQLITE_OK;
  154296. char *zName8;
  154297. #ifdef SQLITE_ENABLE_API_ARMOR
  154298. if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
  154299. #endif
  154300. sqlite3_mutex_enter(db->mutex);
  154301. assert( !db->mallocFailed );
  154302. zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);
  154303. if( zName8 ){
  154304. rc = createCollation(db, zName8, (u8)enc, pCtx, xCompare, 0);
  154305. sqlite3DbFree(db, zName8);
  154306. }
  154307. rc = sqlite3ApiExit(db, rc);
  154308. sqlite3_mutex_leave(db->mutex);
  154309. return rc;
  154310. }
  154311. #endif /* SQLITE_OMIT_UTF16 */
  154312. /*
  154313. ** Register a collation sequence factory callback with the database handle
  154314. ** db. Replace any previously installed collation sequence factory.
  154315. */
  154316. SQLITE_API int sqlite3_collation_needed(
  154317. sqlite3 *db,
  154318. void *pCollNeededArg,
  154319. void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
  154320. ){
  154321. #ifdef SQLITE_ENABLE_API_ARMOR
  154322. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  154323. #endif
  154324. sqlite3_mutex_enter(db->mutex);
  154325. db->xCollNeeded = xCollNeeded;
  154326. db->xCollNeeded16 = 0;
  154327. db->pCollNeededArg = pCollNeededArg;
  154328. sqlite3_mutex_leave(db->mutex);
  154329. return SQLITE_OK;
  154330. }
  154331. #ifndef SQLITE_OMIT_UTF16
  154332. /*
  154333. ** Register a collation sequence factory callback with the database handle
  154334. ** db. Replace any previously installed collation sequence factory.
  154335. */
  154336. SQLITE_API int sqlite3_collation_needed16(
  154337. sqlite3 *db,
  154338. void *pCollNeededArg,
  154339. void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
  154340. ){
  154341. #ifdef SQLITE_ENABLE_API_ARMOR
  154342. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  154343. #endif
  154344. sqlite3_mutex_enter(db->mutex);
  154345. db->xCollNeeded = 0;
  154346. db->xCollNeeded16 = xCollNeeded16;
  154347. db->pCollNeededArg = pCollNeededArg;
  154348. sqlite3_mutex_leave(db->mutex);
  154349. return SQLITE_OK;
  154350. }
  154351. #endif /* SQLITE_OMIT_UTF16 */
  154352. #ifndef SQLITE_OMIT_DEPRECATED
  154353. /*
  154354. ** This function is now an anachronism. It used to be used to recover from a
  154355. ** malloc() failure, but SQLite now does this automatically.
  154356. */
  154357. SQLITE_API int sqlite3_global_recover(void){
  154358. return SQLITE_OK;
  154359. }
  154360. #endif
  154361. /*
  154362. ** Test to see whether or not the database connection is in autocommit
  154363. ** mode. Return TRUE if it is and FALSE if not. Autocommit mode is on
  154364. ** by default. Autocommit is disabled by a BEGIN statement and reenabled
  154365. ** by the next COMMIT or ROLLBACK.
  154366. */
  154367. SQLITE_API int sqlite3_get_autocommit(sqlite3 *db){
  154368. #ifdef SQLITE_ENABLE_API_ARMOR
  154369. if( !sqlite3SafetyCheckOk(db) ){
  154370. (void)SQLITE_MISUSE_BKPT;
  154371. return 0;
  154372. }
  154373. #endif
  154374. return db->autoCommit;
  154375. }
  154376. /*
  154377. ** The following routines are substitutes for constants SQLITE_CORRUPT,
  154378. ** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_NOMEM and possibly other error
  154379. ** constants. They serve two purposes:
  154380. **
  154381. ** 1. Serve as a convenient place to set a breakpoint in a debugger
  154382. ** to detect when version error conditions occurs.
  154383. **
  154384. ** 2. Invoke sqlite3_log() to provide the source code location where
  154385. ** a low-level error is first detected.
  154386. */
  154387. SQLITE_PRIVATE int sqlite3ReportError(int iErr, int lineno, const char *zType){
  154388. sqlite3_log(iErr, "%s at line %d of [%.10s]",
  154389. zType, lineno, 20+sqlite3_sourceid());
  154390. return iErr;
  154391. }
  154392. SQLITE_PRIVATE int sqlite3CorruptError(int lineno){
  154393. testcase( sqlite3GlobalConfig.xLog!=0 );
  154394. return sqlite3ReportError(SQLITE_CORRUPT, lineno, "database corruption");
  154395. }
  154396. SQLITE_PRIVATE int sqlite3MisuseError(int lineno){
  154397. testcase( sqlite3GlobalConfig.xLog!=0 );
  154398. return sqlite3ReportError(SQLITE_MISUSE, lineno, "misuse");
  154399. }
  154400. SQLITE_PRIVATE int sqlite3CantopenError(int lineno){
  154401. testcase( sqlite3GlobalConfig.xLog!=0 );
  154402. return sqlite3ReportError(SQLITE_CANTOPEN, lineno, "cannot open file");
  154403. }
  154404. #if defined(SQLITE_DEBUG) || defined(SQLITE_ENABLE_CORRUPT_PGNO)
  154405. SQLITE_PRIVATE int sqlite3CorruptPgnoError(int lineno, Pgno pgno){
  154406. char zMsg[100];
  154407. sqlite3_snprintf(sizeof(zMsg), zMsg, "database corruption page %d", pgno);
  154408. testcase( sqlite3GlobalConfig.xLog!=0 );
  154409. return sqlite3ReportError(SQLITE_CORRUPT, lineno, zMsg);
  154410. }
  154411. #endif
  154412. #ifdef SQLITE_DEBUG
  154413. SQLITE_PRIVATE int sqlite3NomemError(int lineno){
  154414. testcase( sqlite3GlobalConfig.xLog!=0 );
  154415. return sqlite3ReportError(SQLITE_NOMEM, lineno, "OOM");
  154416. }
  154417. SQLITE_PRIVATE int sqlite3IoerrnomemError(int lineno){
  154418. testcase( sqlite3GlobalConfig.xLog!=0 );
  154419. return sqlite3ReportError(SQLITE_IOERR_NOMEM, lineno, "I/O OOM error");
  154420. }
  154421. #endif
  154422. #ifndef SQLITE_OMIT_DEPRECATED
  154423. /*
  154424. ** This is a convenience routine that makes sure that all thread-specific
  154425. ** data for this thread has been deallocated.
  154426. **
  154427. ** SQLite no longer uses thread-specific data so this routine is now a
  154428. ** no-op. It is retained for historical compatibility.
  154429. */
  154430. SQLITE_API void sqlite3_thread_cleanup(void){
  154431. }
  154432. #endif
  154433. /*
  154434. ** Return meta information about a specific column of a database table.
  154435. ** See comment in sqlite3.h (sqlite.h.in) for details.
  154436. */
  154437. SQLITE_API int sqlite3_table_column_metadata(
  154438. sqlite3 *db, /* Connection handle */
  154439. const char *zDbName, /* Database name or NULL */
  154440. const char *zTableName, /* Table name */
  154441. const char *zColumnName, /* Column name */
  154442. char const **pzDataType, /* OUTPUT: Declared data type */
  154443. char const **pzCollSeq, /* OUTPUT: Collation sequence name */
  154444. int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */
  154445. int *pPrimaryKey, /* OUTPUT: True if column part of PK */
  154446. int *pAutoinc /* OUTPUT: True if column is auto-increment */
  154447. ){
  154448. int rc;
  154449. char *zErrMsg = 0;
  154450. Table *pTab = 0;
  154451. Column *pCol = 0;
  154452. int iCol = 0;
  154453. char const *zDataType = 0;
  154454. char const *zCollSeq = 0;
  154455. int notnull = 0;
  154456. int primarykey = 0;
  154457. int autoinc = 0;
  154458. #ifdef SQLITE_ENABLE_API_ARMOR
  154459. if( !sqlite3SafetyCheckOk(db) || zTableName==0 ){
  154460. return SQLITE_MISUSE_BKPT;
  154461. }
  154462. #endif
  154463. /* Ensure the database schema has been loaded */
  154464. sqlite3_mutex_enter(db->mutex);
  154465. sqlite3BtreeEnterAll(db);
  154466. rc = sqlite3Init(db, &zErrMsg);
  154467. if( SQLITE_OK!=rc ){
  154468. goto error_out;
  154469. }
  154470. /* Locate the table in question */
  154471. pTab = sqlite3FindTable(db, zTableName, zDbName);
  154472. if( !pTab || pTab->pSelect ){
  154473. pTab = 0;
  154474. goto error_out;
  154475. }
  154476. /* Find the column for which info is requested */
  154477. if( zColumnName==0 ){
  154478. /* Query for existance of table only */
  154479. }else{
  154480. for(iCol=0; iCol<pTab->nCol; iCol++){
  154481. pCol = &pTab->aCol[iCol];
  154482. if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
  154483. break;
  154484. }
  154485. }
  154486. if( iCol==pTab->nCol ){
  154487. if( HasRowid(pTab) && sqlite3IsRowid(zColumnName) ){
  154488. iCol = pTab->iPKey;
  154489. pCol = iCol>=0 ? &pTab->aCol[iCol] : 0;
  154490. }else{
  154491. pTab = 0;
  154492. goto error_out;
  154493. }
  154494. }
  154495. }
  154496. /* The following block stores the meta information that will be returned
  154497. ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
  154498. ** and autoinc. At this point there are two possibilities:
  154499. **
  154500. ** 1. The specified column name was rowid", "oid" or "_rowid_"
  154501. ** and there is no explicitly declared IPK column.
  154502. **
  154503. ** 2. The table is not a view and the column name identified an
  154504. ** explicitly declared column. Copy meta information from *pCol.
  154505. */
  154506. if( pCol ){
  154507. zDataType = sqlite3ColumnType(pCol,0);
  154508. zCollSeq = pCol->zColl;
  154509. notnull = pCol->notNull!=0;
  154510. primarykey = (pCol->colFlags & COLFLAG_PRIMKEY)!=0;
  154511. autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
  154512. }else{
  154513. zDataType = "INTEGER";
  154514. primarykey = 1;
  154515. }
  154516. if( !zCollSeq ){
  154517. zCollSeq = sqlite3StrBINARY;
  154518. }
  154519. error_out:
  154520. sqlite3BtreeLeaveAll(db);
  154521. /* Whether the function call succeeded or failed, set the output parameters
  154522. ** to whatever their local counterparts contain. If an error did occur,
  154523. ** this has the effect of zeroing all output parameters.
  154524. */
  154525. if( pzDataType ) *pzDataType = zDataType;
  154526. if( pzCollSeq ) *pzCollSeq = zCollSeq;
  154527. if( pNotNull ) *pNotNull = notnull;
  154528. if( pPrimaryKey ) *pPrimaryKey = primarykey;
  154529. if( pAutoinc ) *pAutoinc = autoinc;
  154530. if( SQLITE_OK==rc && !pTab ){
  154531. sqlite3DbFree(db, zErrMsg);
  154532. zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
  154533. zColumnName);
  154534. rc = SQLITE_ERROR;
  154535. }
  154536. sqlite3ErrorWithMsg(db, rc, (zErrMsg?"%s":0), zErrMsg);
  154537. sqlite3DbFree(db, zErrMsg);
  154538. rc = sqlite3ApiExit(db, rc);
  154539. sqlite3_mutex_leave(db->mutex);
  154540. return rc;
  154541. }
  154542. /*
  154543. ** Sleep for a little while. Return the amount of time slept.
  154544. */
  154545. SQLITE_API int sqlite3_sleep(int ms){
  154546. sqlite3_vfs *pVfs;
  154547. int rc;
  154548. pVfs = sqlite3_vfs_find(0);
  154549. if( pVfs==0 ) return 0;
  154550. /* This function works in milliseconds, but the underlying OsSleep()
  154551. ** API uses microseconds. Hence the 1000's.
  154552. */
  154553. rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
  154554. return rc;
  154555. }
  154556. /*
  154557. ** Enable or disable the extended result codes.
  154558. */
  154559. SQLITE_API int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
  154560. #ifdef SQLITE_ENABLE_API_ARMOR
  154561. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  154562. #endif
  154563. sqlite3_mutex_enter(db->mutex);
  154564. db->errMask = onoff ? 0xffffffff : 0xff;
  154565. sqlite3_mutex_leave(db->mutex);
  154566. return SQLITE_OK;
  154567. }
  154568. /*
  154569. ** Invoke the xFileControl method on a particular database.
  154570. */
  154571. SQLITE_API int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
  154572. int rc = SQLITE_ERROR;
  154573. Btree *pBtree;
  154574. #ifdef SQLITE_ENABLE_API_ARMOR
  154575. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  154576. #endif
  154577. sqlite3_mutex_enter(db->mutex);
  154578. pBtree = sqlite3DbNameToBtree(db, zDbName);
  154579. if( pBtree ){
  154580. Pager *pPager;
  154581. sqlite3_file *fd;
  154582. sqlite3BtreeEnter(pBtree);
  154583. pPager = sqlite3BtreePager(pBtree);
  154584. assert( pPager!=0 );
  154585. fd = sqlite3PagerFile(pPager);
  154586. assert( fd!=0 );
  154587. if( op==SQLITE_FCNTL_FILE_POINTER ){
  154588. *(sqlite3_file**)pArg = fd;
  154589. rc = SQLITE_OK;
  154590. }else if( op==SQLITE_FCNTL_VFS_POINTER ){
  154591. *(sqlite3_vfs**)pArg = sqlite3PagerVfs(pPager);
  154592. rc = SQLITE_OK;
  154593. }else if( op==SQLITE_FCNTL_JOURNAL_POINTER ){
  154594. *(sqlite3_file**)pArg = sqlite3PagerJrnlFile(pPager);
  154595. rc = SQLITE_OK;
  154596. }else if( op==SQLITE_FCNTL_DATA_VERSION ){
  154597. *(unsigned int*)pArg = sqlite3PagerDataVersion(pPager);
  154598. rc = SQLITE_OK;
  154599. }else if( op==SQLITE_FCNTL_RESERVE_BYTES ){
  154600. int iNew = *(int*)pArg;
  154601. *(int*)pArg = sqlite3BtreeGetRequestedReserve(pBtree);
  154602. if( iNew>=0 && iNew<=255 ){
  154603. sqlite3BtreeSetPageSize(pBtree, 0, iNew, 0);
  154604. }
  154605. rc = SQLITE_OK;
  154606. }else{
  154607. rc = sqlite3OsFileControl(fd, op, pArg);
  154608. }
  154609. sqlite3BtreeLeave(pBtree);
  154610. }
  154611. sqlite3_mutex_leave(db->mutex);
  154612. return rc;
  154613. }
  154614. /*
  154615. ** Interface to the testing logic.
  154616. */
  154617. SQLITE_API int sqlite3_test_control(int op, ...){
  154618. int rc = 0;
  154619. #ifdef SQLITE_UNTESTABLE
  154620. UNUSED_PARAMETER(op);
  154621. #else
  154622. va_list ap;
  154623. va_start(ap, op);
  154624. switch( op ){
  154625. /*
  154626. ** Save the current state of the PRNG.
  154627. */
  154628. case SQLITE_TESTCTRL_PRNG_SAVE: {
  154629. sqlite3PrngSaveState();
  154630. break;
  154631. }
  154632. /*
  154633. ** Restore the state of the PRNG to the last state saved using
  154634. ** PRNG_SAVE. If PRNG_SAVE has never before been called, then
  154635. ** this verb acts like PRNG_RESET.
  154636. */
  154637. case SQLITE_TESTCTRL_PRNG_RESTORE: {
  154638. sqlite3PrngRestoreState();
  154639. break;
  154640. }
  154641. /* sqlite3_test_control(SQLITE_TESTCTRL_PRNG_SEED, int x, sqlite3 *db);
  154642. **
  154643. ** Control the seed for the pseudo-random number generator (PRNG) that
  154644. ** is built into SQLite. Cases:
  154645. **
  154646. ** x!=0 && db!=0 Seed the PRNG to the current value of the
  154647. ** schema cookie in the main database for db, or
  154648. ** x if the schema cookie is zero. This case
  154649. ** is convenient to use with database fuzzers
  154650. ** as it allows the fuzzer some control over the
  154651. ** the PRNG seed.
  154652. **
  154653. ** x!=0 && db==0 Seed the PRNG to the value of x.
  154654. **
  154655. ** x==0 && db==0 Revert to default behavior of using the
  154656. ** xRandomness method on the primary VFS.
  154657. **
  154658. ** This test-control also resets the PRNG so that the new seed will
  154659. ** be used for the next call to sqlite3_randomness().
  154660. */
  154661. #ifndef SQLITE_OMIT_WSD
  154662. case SQLITE_TESTCTRL_PRNG_SEED: {
  154663. int x = va_arg(ap, int);
  154664. int y;
  154665. sqlite3 *db = va_arg(ap, sqlite3*);
  154666. assert( db==0 || db->aDb[0].pSchema!=0 );
  154667. if( db && (y = db->aDb[0].pSchema->schema_cookie)!=0 ){ x = y; }
  154668. sqlite3Config.iPrngSeed = x;
  154669. sqlite3_randomness(0,0);
  154670. break;
  154671. }
  154672. #endif
  154673. /*
  154674. ** sqlite3_test_control(BITVEC_TEST, size, program)
  154675. **
  154676. ** Run a test against a Bitvec object of size. The program argument
  154677. ** is an array of integers that defines the test. Return -1 on a
  154678. ** memory allocation error, 0 on success, or non-zero for an error.
  154679. ** See the sqlite3BitvecBuiltinTest() for additional information.
  154680. */
  154681. case SQLITE_TESTCTRL_BITVEC_TEST: {
  154682. int sz = va_arg(ap, int);
  154683. int *aProg = va_arg(ap, int*);
  154684. rc = sqlite3BitvecBuiltinTest(sz, aProg);
  154685. break;
  154686. }
  154687. /*
  154688. ** sqlite3_test_control(FAULT_INSTALL, xCallback)
  154689. **
  154690. ** Arrange to invoke xCallback() whenever sqlite3FaultSim() is called,
  154691. ** if xCallback is not NULL.
  154692. **
  154693. ** As a test of the fault simulator mechanism itself, sqlite3FaultSim(0)
  154694. ** is called immediately after installing the new callback and the return
  154695. ** value from sqlite3FaultSim(0) becomes the return from
  154696. ** sqlite3_test_control().
  154697. */
  154698. case SQLITE_TESTCTRL_FAULT_INSTALL: {
  154699. /* MSVC is picky about pulling func ptrs from va lists.
  154700. ** http://support.microsoft.com/kb/47961
  154701. ** sqlite3GlobalConfig.xTestCallback = va_arg(ap, int(*)(int));
  154702. */
  154703. typedef int(*TESTCALLBACKFUNC_t)(int);
  154704. sqlite3GlobalConfig.xTestCallback = va_arg(ap, TESTCALLBACKFUNC_t);
  154705. rc = sqlite3FaultSim(0);
  154706. break;
  154707. }
  154708. /*
  154709. ** sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
  154710. **
  154711. ** Register hooks to call to indicate which malloc() failures
  154712. ** are benign.
  154713. */
  154714. case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
  154715. typedef void (*void_function)(void);
  154716. void_function xBenignBegin;
  154717. void_function xBenignEnd;
  154718. xBenignBegin = va_arg(ap, void_function);
  154719. xBenignEnd = va_arg(ap, void_function);
  154720. sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
  154721. break;
  154722. }
  154723. /*
  154724. ** sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
  154725. **
  154726. ** Set the PENDING byte to the value in the argument, if X>0.
  154727. ** Make no changes if X==0. Return the value of the pending byte
  154728. ** as it existing before this routine was called.
  154729. **
  154730. ** IMPORTANT: Changing the PENDING byte from 0x40000000 results in
  154731. ** an incompatible database file format. Changing the PENDING byte
  154732. ** while any database connection is open results in undefined and
  154733. ** deleterious behavior.
  154734. */
  154735. case SQLITE_TESTCTRL_PENDING_BYTE: {
  154736. rc = PENDING_BYTE;
  154737. #ifndef SQLITE_OMIT_WSD
  154738. {
  154739. unsigned int newVal = va_arg(ap, unsigned int);
  154740. if( newVal ) sqlite3PendingByte = newVal;
  154741. }
  154742. #endif
  154743. break;
  154744. }
  154745. /*
  154746. ** sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
  154747. **
  154748. ** This action provides a run-time test to see whether or not
  154749. ** assert() was enabled at compile-time. If X is true and assert()
  154750. ** is enabled, then the return value is true. If X is true and
  154751. ** assert() is disabled, then the return value is zero. If X is
  154752. ** false and assert() is enabled, then the assertion fires and the
  154753. ** process aborts. If X is false and assert() is disabled, then the
  154754. ** return value is zero.
  154755. */
  154756. case SQLITE_TESTCTRL_ASSERT: {
  154757. volatile int x = 0;
  154758. assert( /*side-effects-ok*/ (x = va_arg(ap,int))!=0 );
  154759. rc = x;
  154760. break;
  154761. }
  154762. /*
  154763. ** sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
  154764. **
  154765. ** This action provides a run-time test to see how the ALWAYS and
  154766. ** NEVER macros were defined at compile-time.
  154767. **
  154768. ** The return value is ALWAYS(X) if X is true, or 0 if X is false.
  154769. **
  154770. ** The recommended test is X==2. If the return value is 2, that means
  154771. ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
  154772. ** default setting. If the return value is 1, then ALWAYS() is either
  154773. ** hard-coded to true or else it asserts if its argument is false.
  154774. ** The first behavior (hard-coded to true) is the case if
  154775. ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
  154776. ** behavior (assert if the argument to ALWAYS() is false) is the case if
  154777. ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
  154778. **
  154779. ** The run-time test procedure might look something like this:
  154780. **
  154781. ** if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
  154782. ** // ALWAYS() and NEVER() are no-op pass-through macros
  154783. ** }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
  154784. ** // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
  154785. ** }else{
  154786. ** // ALWAYS(x) is a constant 1. NEVER(x) is a constant 0.
  154787. ** }
  154788. */
  154789. case SQLITE_TESTCTRL_ALWAYS: {
  154790. int x = va_arg(ap,int);
  154791. rc = x ? ALWAYS(x) : 0;
  154792. break;
  154793. }
  154794. /*
  154795. ** sqlite3_test_control(SQLITE_TESTCTRL_BYTEORDER);
  154796. **
  154797. ** The integer returned reveals the byte-order of the computer on which
  154798. ** SQLite is running:
  154799. **
  154800. ** 1 big-endian, determined at run-time
  154801. ** 10 little-endian, determined at run-time
  154802. ** 432101 big-endian, determined at compile-time
  154803. ** 123410 little-endian, determined at compile-time
  154804. */
  154805. case SQLITE_TESTCTRL_BYTEORDER: {
  154806. rc = SQLITE_BYTEORDER*100 + SQLITE_LITTLEENDIAN*10 + SQLITE_BIGENDIAN;
  154807. break;
  154808. }
  154809. /* sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
  154810. **
  154811. ** Enable or disable various optimizations for testing purposes. The
  154812. ** argument N is a bitmask of optimizations to be disabled. For normal
  154813. ** operation N should be 0. The idea is that a test program (like the
  154814. ** SQL Logic Test or SLT test module) can run the same SQL multiple times
  154815. ** with various optimizations disabled to verify that the same answer
  154816. ** is obtained in every case.
  154817. */
  154818. case SQLITE_TESTCTRL_OPTIMIZATIONS: {
  154819. sqlite3 *db = va_arg(ap, sqlite3*);
  154820. db->dbOptFlags = (u16)(va_arg(ap, int) & 0xffff);
  154821. break;
  154822. }
  154823. /* sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, int onoff);
  154824. **
  154825. ** If parameter onoff is non-zero, subsequent calls to localtime()
  154826. ** and its variants fail. If onoff is zero, undo this setting.
  154827. */
  154828. case SQLITE_TESTCTRL_LOCALTIME_FAULT: {
  154829. sqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int);
  154830. break;
  154831. }
  154832. /* sqlite3_test_control(SQLITE_TESTCTRL_INTERNAL_FUNCTIONS, sqlite3*);
  154833. **
  154834. ** Toggle the ability to use internal functions on or off for
  154835. ** the database connection given in the argument.
  154836. */
  154837. case SQLITE_TESTCTRL_INTERNAL_FUNCTIONS: {
  154838. sqlite3 *db = va_arg(ap, sqlite3*);
  154839. db->mDbFlags ^= DBFLAG_InternalFunc;
  154840. break;
  154841. }
  154842. /* sqlite3_test_control(SQLITE_TESTCTRL_NEVER_CORRUPT, int);
  154843. **
  154844. ** Set or clear a flag that indicates that the database file is always well-
  154845. ** formed and never corrupt. This flag is clear by default, indicating that
  154846. ** database files might have arbitrary corruption. Setting the flag during
  154847. ** testing causes certain assert() statements in the code to be activated
  154848. ** that demonstrat invariants on well-formed database files.
  154849. */
  154850. case SQLITE_TESTCTRL_NEVER_CORRUPT: {
  154851. sqlite3GlobalConfig.neverCorrupt = va_arg(ap, int);
  154852. break;
  154853. }
  154854. /* sqlite3_test_control(SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS, int);
  154855. **
  154856. ** Set or clear a flag that causes SQLite to verify that type, name,
  154857. ** and tbl_name fields of the sqlite_master table. This is normally
  154858. ** on, but it is sometimes useful to turn it off for testing.
  154859. */
  154860. case SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS: {
  154861. sqlite3GlobalConfig.bExtraSchemaChecks = va_arg(ap, int);
  154862. break;
  154863. }
  154864. /* Set the threshold at which OP_Once counters reset back to zero.
  154865. ** By default this is 0x7ffffffe (over 2 billion), but that value is
  154866. ** too big to test in a reasonable amount of time, so this control is
  154867. ** provided to set a small and easily reachable reset value.
  154868. */
  154869. case SQLITE_TESTCTRL_ONCE_RESET_THRESHOLD: {
  154870. sqlite3GlobalConfig.iOnceResetThreshold = va_arg(ap, int);
  154871. break;
  154872. }
  154873. /* sqlite3_test_control(SQLITE_TESTCTRL_VDBE_COVERAGE, xCallback, ptr);
  154874. **
  154875. ** Set the VDBE coverage callback function to xCallback with context
  154876. ** pointer ptr.
  154877. */
  154878. case SQLITE_TESTCTRL_VDBE_COVERAGE: {
  154879. #ifdef SQLITE_VDBE_COVERAGE
  154880. typedef void (*branch_callback)(void*,unsigned int,
  154881. unsigned char,unsigned char);
  154882. sqlite3GlobalConfig.xVdbeBranch = va_arg(ap,branch_callback);
  154883. sqlite3GlobalConfig.pVdbeBranchArg = va_arg(ap,void*);
  154884. #endif
  154885. break;
  154886. }
  154887. /* sqlite3_test_control(SQLITE_TESTCTRL_SORTER_MMAP, db, nMax); */
  154888. case SQLITE_TESTCTRL_SORTER_MMAP: {
  154889. sqlite3 *db = va_arg(ap, sqlite3*);
  154890. db->nMaxSorterMmap = va_arg(ap, int);
  154891. break;
  154892. }
  154893. /* sqlite3_test_control(SQLITE_TESTCTRL_ISINIT);
  154894. **
  154895. ** Return SQLITE_OK if SQLite has been initialized and SQLITE_ERROR if
  154896. ** not.
  154897. */
  154898. case SQLITE_TESTCTRL_ISINIT: {
  154899. if( sqlite3GlobalConfig.isInit==0 ) rc = SQLITE_ERROR;
  154900. break;
  154901. }
  154902. /* sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, db, dbName, onOff, tnum);
  154903. **
  154904. ** This test control is used to create imposter tables. "db" is a pointer
  154905. ** to the database connection. dbName is the database name (ex: "main" or
  154906. ** "temp") which will receive the imposter. "onOff" turns imposter mode on
  154907. ** or off. "tnum" is the root page of the b-tree to which the imposter
  154908. ** table should connect.
  154909. **
  154910. ** Enable imposter mode only when the schema has already been parsed. Then
  154911. ** run a single CREATE TABLE statement to construct the imposter table in
  154912. ** the parsed schema. Then turn imposter mode back off again.
  154913. **
  154914. ** If onOff==0 and tnum>0 then reset the schema for all databases, causing
  154915. ** the schema to be reparsed the next time it is needed. This has the
  154916. ** effect of erasing all imposter tables.
  154917. */
  154918. case SQLITE_TESTCTRL_IMPOSTER: {
  154919. sqlite3 *db = va_arg(ap, sqlite3*);
  154920. sqlite3_mutex_enter(db->mutex);
  154921. db->init.iDb = sqlite3FindDbName(db, va_arg(ap,const char*));
  154922. db->init.busy = db->init.imposterTable = va_arg(ap,int);
  154923. db->init.newTnum = va_arg(ap,int);
  154924. if( db->init.busy==0 && db->init.newTnum>0 ){
  154925. sqlite3ResetAllSchemasOfConnection(db);
  154926. }
  154927. sqlite3_mutex_leave(db->mutex);
  154928. break;
  154929. }
  154930. #if defined(YYCOVERAGE)
  154931. /* sqlite3_test_control(SQLITE_TESTCTRL_PARSER_COVERAGE, FILE *out)
  154932. **
  154933. ** This test control (only available when SQLite is compiled with
  154934. ** -DYYCOVERAGE) writes a report onto "out" that shows all
  154935. ** state/lookahead combinations in the parser state machine
  154936. ** which are never exercised. If any state is missed, make the
  154937. ** return code SQLITE_ERROR.
  154938. */
  154939. case SQLITE_TESTCTRL_PARSER_COVERAGE: {
  154940. FILE *out = va_arg(ap, FILE*);
  154941. if( sqlite3ParserCoverage(out) ) rc = SQLITE_ERROR;
  154942. break;
  154943. }
  154944. #endif /* defined(YYCOVERAGE) */
  154945. /* sqlite3_test_control(SQLITE_TESTCTRL_RESULT_INTREAL, sqlite3_context*);
  154946. **
  154947. ** This test-control causes the most recent sqlite3_result_int64() value
  154948. ** to be interpreted as a MEM_IntReal instead of as an MEM_Int. Normally,
  154949. ** MEM_IntReal values only arise during an INSERT operation of integer
  154950. ** values into a REAL column, so they can be challenging to test. This
  154951. ** test-control enables us to write an intreal() SQL function that can
  154952. ** inject an intreal() value at arbitrary places in an SQL statement,
  154953. ** for testing purposes.
  154954. */
  154955. case SQLITE_TESTCTRL_RESULT_INTREAL: {
  154956. sqlite3_context *pCtx = va_arg(ap, sqlite3_context*);
  154957. sqlite3ResultIntReal(pCtx);
  154958. break;
  154959. }
  154960. }
  154961. va_end(ap);
  154962. #endif /* SQLITE_UNTESTABLE */
  154963. return rc;
  154964. }
  154965. /*
  154966. ** The Pager stores the Database filename, Journal filename, and WAL filename
  154967. ** consecutively in memory, in that order. The database filename is prefixed
  154968. ** by four zero bytes. Locate the start of the database filename by searching
  154969. ** backwards for the first byte following four consecutive zero bytes.
  154970. **
  154971. ** This only works if the filename passed in was obtained from the Pager.
  154972. */
  154973. static const char *databaseName(const char *zName){
  154974. while( zName[-1]!=0 || zName[-2]!=0 || zName[-3]!=0 || zName[-4]!=0 ){
  154975. zName--;
  154976. }
  154977. return zName;
  154978. }
  154979. /*
  154980. ** Append text z[] to the end of p[]. Return a pointer to the first
  154981. ** character after then zero terminator on the new text in p[].
  154982. */
  154983. static char *appendText(char *p, const char *z){
  154984. size_t n = strlen(z);
  154985. memcpy(p, z, n+1);
  154986. return p+n+1;
  154987. }
  154988. /*
  154989. ** Allocate memory to hold names for a database, journal file, WAL file,
  154990. ** and query parameters. The pointer returned is valid for use by
  154991. ** sqlite3_filename_database() and sqlite3_uri_parameter() and related
  154992. ** functions.
  154993. **
  154994. ** Memory layout must be compatible with that generated by the pager
  154995. ** and expected by sqlite3_uri_parameter() and databaseName().
  154996. */
  154997. SQLITE_API char *sqlite3_create_filename(
  154998. const char *zDatabase,
  154999. const char *zJournal,
  155000. const char *zWal,
  155001. int nParam,
  155002. const char **azParam
  155003. ){
  155004. sqlite3_int64 nByte;
  155005. int i;
  155006. char *pResult, *p;
  155007. nByte = strlen(zDatabase) + strlen(zJournal) + strlen(zWal) + 10;
  155008. for(i=0; i<nParam*2; i++){
  155009. nByte += strlen(azParam[i])+1;
  155010. }
  155011. pResult = p = sqlite3_malloc64( nByte );
  155012. if( p==0 ) return 0;
  155013. memset(p, 0, 4);
  155014. p += 4;
  155015. p = appendText(p, zDatabase);
  155016. for(i=0; i<nParam*2; i++){
  155017. p = appendText(p, azParam[i]);
  155018. }
  155019. *(p++) = 0;
  155020. p = appendText(p, zJournal);
  155021. p = appendText(p, zWal);
  155022. *(p++) = 0;
  155023. *(p++) = 0;
  155024. assert( (sqlite3_int64)(p - pResult)==nByte );
  155025. return pResult + 4;
  155026. }
  155027. /*
  155028. ** Free memory obtained from sqlite3_create_filename(). It is a severe
  155029. ** error to call this routine with any parameter other than a pointer
  155030. ** previously obtained from sqlite3_create_filename() or a NULL pointer.
  155031. */
  155032. SQLITE_API void sqlite3_free_filename(char *p){
  155033. if( p==0 ) return;
  155034. p = (char*)databaseName(p);
  155035. sqlite3_free(p - 4);
  155036. }
  155037. /*
  155038. ** This is a utility routine, useful to VFS implementations, that checks
  155039. ** to see if a database file was a URI that contained a specific query
  155040. ** parameter, and if so obtains the value of the query parameter.
  155041. **
  155042. ** The zFilename argument is the filename pointer passed into the xOpen()
  155043. ** method of a VFS implementation. The zParam argument is the name of the
  155044. ** query parameter we seek. This routine returns the value of the zParam
  155045. ** parameter if it exists. If the parameter does not exist, this routine
  155046. ** returns a NULL pointer.
  155047. */
  155048. SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam){
  155049. if( zFilename==0 || zParam==0 ) return 0;
  155050. zFilename = databaseName(zFilename);
  155051. return uriParameter(zFilename, zParam);
  155052. }
  155053. /*
  155054. ** Return a pointer to the name of Nth query parameter of the filename.
  155055. */
  155056. SQLITE_API const char *sqlite3_uri_key(const char *zFilename, int N){
  155057. if( zFilename==0 || N<0 ) return 0;
  155058. zFilename = databaseName(zFilename);
  155059. zFilename += sqlite3Strlen30(zFilename) + 1;
  155060. while( zFilename[0] && (N--)>0 ){
  155061. zFilename += sqlite3Strlen30(zFilename) + 1;
  155062. zFilename += sqlite3Strlen30(zFilename) + 1;
  155063. }
  155064. return zFilename[0] ? zFilename : 0;
  155065. }
  155066. /*
  155067. ** Return a boolean value for a query parameter.
  155068. */
  155069. SQLITE_API int sqlite3_uri_boolean(const char *zFilename, const char *zParam, int bDflt){
  155070. const char *z = sqlite3_uri_parameter(zFilename, zParam);
  155071. bDflt = bDflt!=0;
  155072. return z ? sqlite3GetBoolean(z, bDflt) : bDflt;
  155073. }
  155074. /*
  155075. ** Return a 64-bit integer value for a query parameter.
  155076. */
  155077. SQLITE_API sqlite3_int64 sqlite3_uri_int64(
  155078. const char *zFilename, /* Filename as passed to xOpen */
  155079. const char *zParam, /* URI parameter sought */
  155080. sqlite3_int64 bDflt /* return if parameter is missing */
  155081. ){
  155082. const char *z = sqlite3_uri_parameter(zFilename, zParam);
  155083. sqlite3_int64 v;
  155084. if( z && sqlite3DecOrHexToI64(z, &v)==0 ){
  155085. bDflt = v;
  155086. }
  155087. return bDflt;
  155088. }
  155089. /*
  155090. ** Translate a filename that was handed to a VFS routine into the corresponding
  155091. ** database, journal, or WAL file.
  155092. **
  155093. ** It is an error to pass this routine a filename string that was not
  155094. ** passed into the VFS from the SQLite core. Doing so is similar to
  155095. ** passing free() a pointer that was not obtained from malloc() - it is
  155096. ** an error that we cannot easily detect but that will likely cause memory
  155097. ** corruption.
  155098. */
  155099. SQLITE_API const char *sqlite3_filename_database(const char *zFilename){
  155100. return databaseName(zFilename);
  155101. }
  155102. SQLITE_API const char *sqlite3_filename_journal(const char *zFilename){
  155103. zFilename = databaseName(zFilename);
  155104. zFilename += sqlite3Strlen30(zFilename) + 1;
  155105. while( zFilename[0] ){
  155106. zFilename += sqlite3Strlen30(zFilename) + 1;
  155107. zFilename += sqlite3Strlen30(zFilename) + 1;
  155108. }
  155109. return zFilename + 1;
  155110. }
  155111. SQLITE_API const char *sqlite3_filename_wal(const char *zFilename){
  155112. #ifdef SQLITE_OMIT_WAL
  155113. return 0;
  155114. #else
  155115. zFilename = sqlite3_filename_journal(zFilename);
  155116. zFilename += sqlite3Strlen30(zFilename) + 1;
  155117. return zFilename;
  155118. #endif
  155119. }
  155120. /*
  155121. ** Return the Btree pointer identified by zDbName. Return NULL if not found.
  155122. */
  155123. SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3 *db, const char *zDbName){
  155124. int iDb = zDbName ? sqlite3FindDbName(db, zDbName) : 0;
  155125. return iDb<0 ? 0 : db->aDb[iDb].pBt;
  155126. }
  155127. /*
  155128. ** Return the filename of the database associated with a database
  155129. ** connection.
  155130. */
  155131. SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName){
  155132. Btree *pBt;
  155133. #ifdef SQLITE_ENABLE_API_ARMOR
  155134. if( !sqlite3SafetyCheckOk(db) ){
  155135. (void)SQLITE_MISUSE_BKPT;
  155136. return 0;
  155137. }
  155138. #endif
  155139. pBt = sqlite3DbNameToBtree(db, zDbName);
  155140. return pBt ? sqlite3BtreeGetFilename(pBt) : 0;
  155141. }
  155142. /*
  155143. ** Return 1 if database is read-only or 0 if read/write. Return -1 if
  155144. ** no such database exists.
  155145. */
  155146. SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName){
  155147. Btree *pBt;
  155148. #ifdef SQLITE_ENABLE_API_ARMOR
  155149. if( !sqlite3SafetyCheckOk(db) ){
  155150. (void)SQLITE_MISUSE_BKPT;
  155151. return -1;
  155152. }
  155153. #endif
  155154. pBt = sqlite3DbNameToBtree(db, zDbName);
  155155. return pBt ? sqlite3BtreeIsReadonly(pBt) : -1;
  155156. }
  155157. #ifdef SQLITE_ENABLE_SNAPSHOT
  155158. /*
  155159. ** Obtain a snapshot handle for the snapshot of database zDb currently
  155160. ** being read by handle db.
  155161. */
  155162. SQLITE_API int sqlite3_snapshot_get(
  155163. sqlite3 *db,
  155164. const char *zDb,
  155165. sqlite3_snapshot **ppSnapshot
  155166. ){
  155167. int rc = SQLITE_ERROR;
  155168. #ifndef SQLITE_OMIT_WAL
  155169. #ifdef SQLITE_ENABLE_API_ARMOR
  155170. if( !sqlite3SafetyCheckOk(db) ){
  155171. return SQLITE_MISUSE_BKPT;
  155172. }
  155173. #endif
  155174. sqlite3_mutex_enter(db->mutex);
  155175. if( db->autoCommit==0 ){
  155176. int iDb = sqlite3FindDbName(db, zDb);
  155177. if( iDb==0 || iDb>1 ){
  155178. Btree *pBt = db->aDb[iDb].pBt;
  155179. if( 0==sqlite3BtreeIsInTrans(pBt) ){
  155180. rc = sqlite3BtreeBeginTrans(pBt, 0, 0);
  155181. if( rc==SQLITE_OK ){
  155182. rc = sqlite3PagerSnapshotGet(sqlite3BtreePager(pBt), ppSnapshot);
  155183. }
  155184. }
  155185. }
  155186. }
  155187. sqlite3_mutex_leave(db->mutex);
  155188. #endif /* SQLITE_OMIT_WAL */
  155189. return rc;
  155190. }
  155191. /*
  155192. ** Open a read-transaction on the snapshot idendified by pSnapshot.
  155193. */
  155194. SQLITE_API int sqlite3_snapshot_open(
  155195. sqlite3 *db,
  155196. const char *zDb,
  155197. sqlite3_snapshot *pSnapshot
  155198. ){
  155199. int rc = SQLITE_ERROR;
  155200. #ifndef SQLITE_OMIT_WAL
  155201. #ifdef SQLITE_ENABLE_API_ARMOR
  155202. if( !sqlite3SafetyCheckOk(db) ){
  155203. return SQLITE_MISUSE_BKPT;
  155204. }
  155205. #endif
  155206. sqlite3_mutex_enter(db->mutex);
  155207. if( db->autoCommit==0 ){
  155208. int iDb;
  155209. iDb = sqlite3FindDbName(db, zDb);
  155210. if( iDb==0 || iDb>1 ){
  155211. Btree *pBt = db->aDb[iDb].pBt;
  155212. if( sqlite3BtreeIsInTrans(pBt)==0 ){
  155213. Pager *pPager = sqlite3BtreePager(pBt);
  155214. int bUnlock = 0;
  155215. if( sqlite3BtreeIsInReadTrans(pBt) ){
  155216. if( db->nVdbeActive==0 ){
  155217. rc = sqlite3PagerSnapshotCheck(pPager, pSnapshot);
  155218. if( rc==SQLITE_OK ){
  155219. bUnlock = 1;
  155220. rc = sqlite3BtreeCommit(pBt);
  155221. }
  155222. }
  155223. }else{
  155224. rc = SQLITE_OK;
  155225. }
  155226. if( rc==SQLITE_OK ){
  155227. rc = sqlite3PagerSnapshotOpen(pPager, pSnapshot);
  155228. }
  155229. if( rc==SQLITE_OK ){
  155230. rc = sqlite3BtreeBeginTrans(pBt, 0, 0);
  155231. sqlite3PagerSnapshotOpen(pPager, 0);
  155232. }
  155233. if( bUnlock ){
  155234. sqlite3PagerSnapshotUnlock(pPager);
  155235. }
  155236. }
  155237. }
  155238. }
  155239. sqlite3_mutex_leave(db->mutex);
  155240. #endif /* SQLITE_OMIT_WAL */
  155241. return rc;
  155242. }
  155243. /*
  155244. ** Recover as many snapshots as possible from the wal file associated with
  155245. ** schema zDb of database db.
  155246. */
  155247. SQLITE_API int sqlite3_snapshot_recover(sqlite3 *db, const char *zDb){
  155248. int rc = SQLITE_ERROR;
  155249. int iDb;
  155250. #ifndef SQLITE_OMIT_WAL
  155251. #ifdef SQLITE_ENABLE_API_ARMOR
  155252. if( !sqlite3SafetyCheckOk(db) ){
  155253. return SQLITE_MISUSE_BKPT;
  155254. }
  155255. #endif
  155256. sqlite3_mutex_enter(db->mutex);
  155257. iDb = sqlite3FindDbName(db, zDb);
  155258. if( iDb==0 || iDb>1 ){
  155259. Btree *pBt = db->aDb[iDb].pBt;
  155260. if( 0==sqlite3BtreeIsInReadTrans(pBt) ){
  155261. rc = sqlite3BtreeBeginTrans(pBt, 0, 0);
  155262. if( rc==SQLITE_OK ){
  155263. rc = sqlite3PagerSnapshotRecover(sqlite3BtreePager(pBt));
  155264. sqlite3BtreeCommit(pBt);
  155265. }
  155266. }
  155267. }
  155268. sqlite3_mutex_leave(db->mutex);
  155269. #endif /* SQLITE_OMIT_WAL */
  155270. return rc;
  155271. }
  155272. /*
  155273. ** Free a snapshot handle obtained from sqlite3_snapshot_get().
  155274. */
  155275. SQLITE_API void sqlite3_snapshot_free(sqlite3_snapshot *pSnapshot){
  155276. sqlite3_free(pSnapshot);
  155277. }
  155278. #endif /* SQLITE_ENABLE_SNAPSHOT */
  155279. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  155280. /*
  155281. ** Given the name of a compile-time option, return true if that option
  155282. ** was used and false if not.
  155283. **
  155284. ** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix
  155285. ** is not required for a match.
  155286. */
  155287. SQLITE_API int sqlite3_compileoption_used(const char *zOptName){
  155288. int i, n;
  155289. int nOpt;
  155290. const char **azCompileOpt;
  155291. #if SQLITE_ENABLE_API_ARMOR
  155292. if( zOptName==0 ){
  155293. (void)SQLITE_MISUSE_BKPT;
  155294. return 0;
  155295. }
  155296. #endif
  155297. azCompileOpt = sqlite3CompileOptions(&nOpt);
  155298. if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7;
  155299. n = sqlite3Strlen30(zOptName);
  155300. /* Since nOpt is normally in single digits, a linear search is
  155301. ** adequate. No need for a binary search. */
  155302. for(i=0; i<nOpt; i++){
  155303. if( sqlite3StrNICmp(zOptName, azCompileOpt[i], n)==0
  155304. && sqlite3IsIdChar((unsigned char)azCompileOpt[i][n])==0
  155305. ){
  155306. return 1;
  155307. }
  155308. }
  155309. return 0;
  155310. }
  155311. /*
  155312. ** Return the N-th compile-time option string. If N is out of range,
  155313. ** return a NULL pointer.
  155314. */
  155315. SQLITE_API const char *sqlite3_compileoption_get(int N){
  155316. int nOpt;
  155317. const char **azCompileOpt;
  155318. azCompileOpt = sqlite3CompileOptions(&nOpt);
  155319. if( N>=0 && N<nOpt ){
  155320. return azCompileOpt[N];
  155321. }
  155322. return 0;
  155323. }
  155324. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  155325. /************** End of main.c ************************************************/
  155326. /************** Begin file notify.c ******************************************/
  155327. /*
  155328. ** 2009 March 3
  155329. **
  155330. ** The author disclaims copyright to this source code. In place of
  155331. ** a legal notice, here is a blessing:
  155332. **
  155333. ** May you do good and not evil.
  155334. ** May you find forgiveness for yourself and forgive others.
  155335. ** May you share freely, never taking more than you give.
  155336. **
  155337. *************************************************************************
  155338. **
  155339. ** This file contains the implementation of the sqlite3_unlock_notify()
  155340. ** API method and its associated functionality.
  155341. */
  155342. /* #include "sqliteInt.h" */
  155343. /* #include "btreeInt.h" */
  155344. /* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */
  155345. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  155346. /*
  155347. ** Public interfaces:
  155348. **
  155349. ** sqlite3ConnectionBlocked()
  155350. ** sqlite3ConnectionUnlocked()
  155351. ** sqlite3ConnectionClosed()
  155352. ** sqlite3_unlock_notify()
  155353. */
  155354. #define assertMutexHeld() \
  155355. assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) )
  155356. /*
  155357. ** Head of a linked list of all sqlite3 objects created by this process
  155358. ** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection
  155359. ** is not NULL. This variable may only accessed while the STATIC_MASTER
  155360. ** mutex is held.
  155361. */
  155362. static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0;
  155363. #ifndef NDEBUG
  155364. /*
  155365. ** This function is a complex assert() that verifies the following
  155366. ** properties of the blocked connections list:
  155367. **
  155368. ** 1) Each entry in the list has a non-NULL value for either
  155369. ** pUnlockConnection or pBlockingConnection, or both.
  155370. **
  155371. ** 2) All entries in the list that share a common value for
  155372. ** xUnlockNotify are grouped together.
  155373. **
  155374. ** 3) If the argument db is not NULL, then none of the entries in the
  155375. ** blocked connections list have pUnlockConnection or pBlockingConnection
  155376. ** set to db. This is used when closing connection db.
  155377. */
  155378. static void checkListProperties(sqlite3 *db){
  155379. sqlite3 *p;
  155380. for(p=sqlite3BlockedList; p; p=p->pNextBlocked){
  155381. int seen = 0;
  155382. sqlite3 *p2;
  155383. /* Verify property (1) */
  155384. assert( p->pUnlockConnection || p->pBlockingConnection );
  155385. /* Verify property (2) */
  155386. for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){
  155387. if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1;
  155388. assert( p2->xUnlockNotify==p->xUnlockNotify || !seen );
  155389. assert( db==0 || p->pUnlockConnection!=db );
  155390. assert( db==0 || p->pBlockingConnection!=db );
  155391. }
  155392. }
  155393. }
  155394. #else
  155395. # define checkListProperties(x)
  155396. #endif
  155397. /*
  155398. ** Remove connection db from the blocked connections list. If connection
  155399. ** db is not currently a part of the list, this function is a no-op.
  155400. */
  155401. static void removeFromBlockedList(sqlite3 *db){
  155402. sqlite3 **pp;
  155403. assertMutexHeld();
  155404. for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){
  155405. if( *pp==db ){
  155406. *pp = (*pp)->pNextBlocked;
  155407. break;
  155408. }
  155409. }
  155410. }
  155411. /*
  155412. ** Add connection db to the blocked connections list. It is assumed
  155413. ** that it is not already a part of the list.
  155414. */
  155415. static void addToBlockedList(sqlite3 *db){
  155416. sqlite3 **pp;
  155417. assertMutexHeld();
  155418. for(
  155419. pp=&sqlite3BlockedList;
  155420. *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify;
  155421. pp=&(*pp)->pNextBlocked
  155422. );
  155423. db->pNextBlocked = *pp;
  155424. *pp = db;
  155425. }
  155426. /*
  155427. ** Obtain the STATIC_MASTER mutex.
  155428. */
  155429. static void enterMutex(void){
  155430. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  155431. checkListProperties(0);
  155432. }
  155433. /*
  155434. ** Release the STATIC_MASTER mutex.
  155435. */
  155436. static void leaveMutex(void){
  155437. assertMutexHeld();
  155438. checkListProperties(0);
  155439. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  155440. }
  155441. /*
  155442. ** Register an unlock-notify callback.
  155443. **
  155444. ** This is called after connection "db" has attempted some operation
  155445. ** but has received an SQLITE_LOCKED error because another connection
  155446. ** (call it pOther) in the same process was busy using the same shared
  155447. ** cache. pOther is found by looking at db->pBlockingConnection.
  155448. **
  155449. ** If there is no blocking connection, the callback is invoked immediately,
  155450. ** before this routine returns.
  155451. **
  155452. ** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate
  155453. ** a deadlock.
  155454. **
  155455. ** Otherwise, make arrangements to invoke xNotify when pOther drops
  155456. ** its locks.
  155457. **
  155458. ** Each call to this routine overrides any prior callbacks registered
  155459. ** on the same "db". If xNotify==0 then any prior callbacks are immediately
  155460. ** cancelled.
  155461. */
  155462. SQLITE_API int sqlite3_unlock_notify(
  155463. sqlite3 *db,
  155464. void (*xNotify)(void **, int),
  155465. void *pArg
  155466. ){
  155467. int rc = SQLITE_OK;
  155468. sqlite3_mutex_enter(db->mutex);
  155469. enterMutex();
  155470. if( xNotify==0 ){
  155471. removeFromBlockedList(db);
  155472. db->pBlockingConnection = 0;
  155473. db->pUnlockConnection = 0;
  155474. db->xUnlockNotify = 0;
  155475. db->pUnlockArg = 0;
  155476. }else if( 0==db->pBlockingConnection ){
  155477. /* The blocking transaction has been concluded. Or there never was a
  155478. ** blocking transaction. In either case, invoke the notify callback
  155479. ** immediately.
  155480. */
  155481. xNotify(&pArg, 1);
  155482. }else{
  155483. sqlite3 *p;
  155484. for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){}
  155485. if( p ){
  155486. rc = SQLITE_LOCKED; /* Deadlock detected. */
  155487. }else{
  155488. db->pUnlockConnection = db->pBlockingConnection;
  155489. db->xUnlockNotify = xNotify;
  155490. db->pUnlockArg = pArg;
  155491. removeFromBlockedList(db);
  155492. addToBlockedList(db);
  155493. }
  155494. }
  155495. leaveMutex();
  155496. assert( !db->mallocFailed );
  155497. sqlite3ErrorWithMsg(db, rc, (rc?"database is deadlocked":0));
  155498. sqlite3_mutex_leave(db->mutex);
  155499. return rc;
  155500. }
  155501. /*
  155502. ** This function is called while stepping or preparing a statement
  155503. ** associated with connection db. The operation will return SQLITE_LOCKED
  155504. ** to the user because it requires a lock that will not be available
  155505. ** until connection pBlocker concludes its current transaction.
  155506. */
  155507. SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){
  155508. enterMutex();
  155509. if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){
  155510. addToBlockedList(db);
  155511. }
  155512. db->pBlockingConnection = pBlocker;
  155513. leaveMutex();
  155514. }
  155515. /*
  155516. ** This function is called when
  155517. ** the transaction opened by database db has just finished. Locks held
  155518. ** by database connection db have been released.
  155519. **
  155520. ** This function loops through each entry in the blocked connections
  155521. ** list and does the following:
  155522. **
  155523. ** 1) If the sqlite3.pBlockingConnection member of a list entry is
  155524. ** set to db, then set pBlockingConnection=0.
  155525. **
  155526. ** 2) If the sqlite3.pUnlockConnection member of a list entry is
  155527. ** set to db, then invoke the configured unlock-notify callback and
  155528. ** set pUnlockConnection=0.
  155529. **
  155530. ** 3) If the two steps above mean that pBlockingConnection==0 and
  155531. ** pUnlockConnection==0, remove the entry from the blocked connections
  155532. ** list.
  155533. */
  155534. SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){
  155535. void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */
  155536. int nArg = 0; /* Number of entries in aArg[] */
  155537. sqlite3 **pp; /* Iterator variable */
  155538. void **aArg; /* Arguments to the unlock callback */
  155539. void **aDyn = 0; /* Dynamically allocated space for aArg[] */
  155540. void *aStatic[16]; /* Starter space for aArg[]. No malloc required */
  155541. aArg = aStatic;
  155542. enterMutex(); /* Enter STATIC_MASTER mutex */
  155543. /* This loop runs once for each entry in the blocked-connections list. */
  155544. for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){
  155545. sqlite3 *p = *pp;
  155546. /* Step 1. */
  155547. if( p->pBlockingConnection==db ){
  155548. p->pBlockingConnection = 0;
  155549. }
  155550. /* Step 2. */
  155551. if( p->pUnlockConnection==db ){
  155552. assert( p->xUnlockNotify );
  155553. if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){
  155554. xUnlockNotify(aArg, nArg);
  155555. nArg = 0;
  155556. }
  155557. sqlite3BeginBenignMalloc();
  155558. assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) );
  155559. assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn );
  155560. if( (!aDyn && nArg==(int)ArraySize(aStatic))
  155561. || (aDyn && nArg==(int)(sqlite3MallocSize(aDyn)/sizeof(void*)))
  155562. ){
  155563. /* The aArg[] array needs to grow. */
  155564. void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2);
  155565. if( pNew ){
  155566. memcpy(pNew, aArg, nArg*sizeof(void *));
  155567. sqlite3_free(aDyn);
  155568. aDyn = aArg = pNew;
  155569. }else{
  155570. /* This occurs when the array of context pointers that need to
  155571. ** be passed to the unlock-notify callback is larger than the
  155572. ** aStatic[] array allocated on the stack and the attempt to
  155573. ** allocate a larger array from the heap has failed.
  155574. **
  155575. ** This is a difficult situation to handle. Returning an error
  155576. ** code to the caller is insufficient, as even if an error code
  155577. ** is returned the transaction on connection db will still be
  155578. ** closed and the unlock-notify callbacks on blocked connections
  155579. ** will go unissued. This might cause the application to wait
  155580. ** indefinitely for an unlock-notify callback that will never
  155581. ** arrive.
  155582. **
  155583. ** Instead, invoke the unlock-notify callback with the context
  155584. ** array already accumulated. We can then clear the array and
  155585. ** begin accumulating any further context pointers without
  155586. ** requiring any dynamic allocation. This is sub-optimal because
  155587. ** it means that instead of one callback with a large array of
  155588. ** context pointers the application will receive two or more
  155589. ** callbacks with smaller arrays of context pointers, which will
  155590. ** reduce the applications ability to prioritize multiple
  155591. ** connections. But it is the best that can be done under the
  155592. ** circumstances.
  155593. */
  155594. xUnlockNotify(aArg, nArg);
  155595. nArg = 0;
  155596. }
  155597. }
  155598. sqlite3EndBenignMalloc();
  155599. aArg[nArg++] = p->pUnlockArg;
  155600. xUnlockNotify = p->xUnlockNotify;
  155601. p->pUnlockConnection = 0;
  155602. p->xUnlockNotify = 0;
  155603. p->pUnlockArg = 0;
  155604. }
  155605. /* Step 3. */
  155606. if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){
  155607. /* Remove connection p from the blocked connections list. */
  155608. *pp = p->pNextBlocked;
  155609. p->pNextBlocked = 0;
  155610. }else{
  155611. pp = &p->pNextBlocked;
  155612. }
  155613. }
  155614. if( nArg!=0 ){
  155615. xUnlockNotify(aArg, nArg);
  155616. }
  155617. sqlite3_free(aDyn);
  155618. leaveMutex(); /* Leave STATIC_MASTER mutex */
  155619. }
  155620. /*
  155621. ** This is called when the database connection passed as an argument is
  155622. ** being closed. The connection is removed from the blocked list.
  155623. */
  155624. SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){
  155625. sqlite3ConnectionUnlocked(db);
  155626. enterMutex();
  155627. removeFromBlockedList(db);
  155628. checkListProperties(db);
  155629. leaveMutex();
  155630. }
  155631. #endif
  155632. /************** End of notify.c **********************************************/
  155633. /************** Begin file fts3.c ********************************************/
  155634. /*
  155635. ** 2006 Oct 10
  155636. **
  155637. ** The author disclaims copyright to this source code. In place of
  155638. ** a legal notice, here is a blessing:
  155639. **
  155640. ** May you do good and not evil.
  155641. ** May you find forgiveness for yourself and forgive others.
  155642. ** May you share freely, never taking more than you give.
  155643. **
  155644. ******************************************************************************
  155645. **
  155646. ** This is an SQLite module implementing full-text search.
  155647. */
  155648. /*
  155649. ** The code in this file is only compiled if:
  155650. **
  155651. ** * The FTS3 module is being built as an extension
  155652. ** (in which case SQLITE_CORE is not defined), or
  155653. **
  155654. ** * The FTS3 module is being built into the core of
  155655. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  155656. */
  155657. /* The full-text index is stored in a series of b+tree (-like)
  155658. ** structures called segments which map terms to doclists. The
  155659. ** structures are like b+trees in layout, but are constructed from the
  155660. ** bottom up in optimal fashion and are not updatable. Since trees
  155661. ** are built from the bottom up, things will be described from the
  155662. ** bottom up.
  155663. **
  155664. **
  155665. **** Varints ****
  155666. ** The basic unit of encoding is a variable-length integer called a
  155667. ** varint. We encode variable-length integers in little-endian order
  155668. ** using seven bits * per byte as follows:
  155669. **
  155670. ** KEY:
  155671. ** A = 0xxxxxxx 7 bits of data and one flag bit
  155672. ** B = 1xxxxxxx 7 bits of data and one flag bit
  155673. **
  155674. ** 7 bits - A
  155675. ** 14 bits - BA
  155676. ** 21 bits - BBA
  155677. ** and so on.
  155678. **
  155679. ** This is similar in concept to how sqlite encodes "varints" but
  155680. ** the encoding is not the same. SQLite varints are big-endian
  155681. ** are are limited to 9 bytes in length whereas FTS3 varints are
  155682. ** little-endian and can be up to 10 bytes in length (in theory).
  155683. **
  155684. ** Example encodings:
  155685. **
  155686. ** 1: 0x01
  155687. ** 127: 0x7f
  155688. ** 128: 0x81 0x00
  155689. **
  155690. **
  155691. **** Document lists ****
  155692. ** A doclist (document list) holds a docid-sorted list of hits for a
  155693. ** given term. Doclists hold docids and associated token positions.
  155694. ** A docid is the unique integer identifier for a single document.
  155695. ** A position is the index of a word within the document. The first
  155696. ** word of the document has a position of 0.
  155697. **
  155698. ** FTS3 used to optionally store character offsets using a compile-time
  155699. ** option. But that functionality is no longer supported.
  155700. **
  155701. ** A doclist is stored like this:
  155702. **
  155703. ** array {
  155704. ** varint docid; (delta from previous doclist)
  155705. ** array { (position list for column 0)
  155706. ** varint position; (2 more than the delta from previous position)
  155707. ** }
  155708. ** array {
  155709. ** varint POS_COLUMN; (marks start of position list for new column)
  155710. ** varint column; (index of new column)
  155711. ** array {
  155712. ** varint position; (2 more than the delta from previous position)
  155713. ** }
  155714. ** }
  155715. ** varint POS_END; (marks end of positions for this document.
  155716. ** }
  155717. **
  155718. ** Here, array { X } means zero or more occurrences of X, adjacent in
  155719. ** memory. A "position" is an index of a token in the token stream
  155720. ** generated by the tokenizer. Note that POS_END and POS_COLUMN occur
  155721. ** in the same logical place as the position element, and act as sentinals
  155722. ** ending a position list array. POS_END is 0. POS_COLUMN is 1.
  155723. ** The positions numbers are not stored literally but rather as two more
  155724. ** than the difference from the prior position, or the just the position plus
  155725. ** 2 for the first position. Example:
  155726. **
  155727. ** label: A B C D E F G H I J K
  155728. ** value: 123 5 9 1 1 14 35 0 234 72 0
  155729. **
  155730. ** The 123 value is the first docid. For column zero in this document
  155731. ** there are two matches at positions 3 and 10 (5-2 and 9-2+3). The 1
  155732. ** at D signals the start of a new column; the 1 at E indicates that the
  155733. ** new column is column number 1. There are two positions at 12 and 45
  155734. ** (14-2 and 35-2+12). The 0 at H indicate the end-of-document. The
  155735. ** 234 at I is the delta to next docid (357). It has one position 70
  155736. ** (72-2) and then terminates with the 0 at K.
  155737. **
  155738. ** A "position-list" is the list of positions for multiple columns for
  155739. ** a single docid. A "column-list" is the set of positions for a single
  155740. ** column. Hence, a position-list consists of one or more column-lists,
  155741. ** a document record consists of a docid followed by a position-list and
  155742. ** a doclist consists of one or more document records.
  155743. **
  155744. ** A bare doclist omits the position information, becoming an
  155745. ** array of varint-encoded docids.
  155746. **
  155747. **** Segment leaf nodes ****
  155748. ** Segment leaf nodes store terms and doclists, ordered by term. Leaf
  155749. ** nodes are written using LeafWriter, and read using LeafReader (to
  155750. ** iterate through a single leaf node's data) and LeavesReader (to
  155751. ** iterate through a segment's entire leaf layer). Leaf nodes have
  155752. ** the format:
  155753. **
  155754. ** varint iHeight; (height from leaf level, always 0)
  155755. ** varint nTerm; (length of first term)
  155756. ** char pTerm[nTerm]; (content of first term)
  155757. ** varint nDoclist; (length of term's associated doclist)
  155758. ** char pDoclist[nDoclist]; (content of doclist)
  155759. ** array {
  155760. ** (further terms are delta-encoded)
  155761. ** varint nPrefix; (length of prefix shared with previous term)
  155762. ** varint nSuffix; (length of unshared suffix)
  155763. ** char pTermSuffix[nSuffix];(unshared suffix of next term)
  155764. ** varint nDoclist; (length of term's associated doclist)
  155765. ** char pDoclist[nDoclist]; (content of doclist)
  155766. ** }
  155767. **
  155768. ** Here, array { X } means zero or more occurrences of X, adjacent in
  155769. ** memory.
  155770. **
  155771. ** Leaf nodes are broken into blocks which are stored contiguously in
  155772. ** the %_segments table in sorted order. This means that when the end
  155773. ** of a node is reached, the next term is in the node with the next
  155774. ** greater node id.
  155775. **
  155776. ** New data is spilled to a new leaf node when the current node
  155777. ** exceeds LEAF_MAX bytes (default 2048). New data which itself is
  155778. ** larger than STANDALONE_MIN (default 1024) is placed in a standalone
  155779. ** node (a leaf node with a single term and doclist). The goal of
  155780. ** these settings is to pack together groups of small doclists while
  155781. ** making it efficient to directly access large doclists. The
  155782. ** assumption is that large doclists represent terms which are more
  155783. ** likely to be query targets.
  155784. **
  155785. ** TODO(shess) It may be useful for blocking decisions to be more
  155786. ** dynamic. For instance, it may make more sense to have a 2.5k leaf
  155787. ** node rather than splitting into 2k and .5k nodes. My intuition is
  155788. ** that this might extend through 2x or 4x the pagesize.
  155789. **
  155790. **
  155791. **** Segment interior nodes ****
  155792. ** Segment interior nodes store blockids for subtree nodes and terms
  155793. ** to describe what data is stored by the each subtree. Interior
  155794. ** nodes are written using InteriorWriter, and read using
  155795. ** InteriorReader. InteriorWriters are created as needed when
  155796. ** SegmentWriter creates new leaf nodes, or when an interior node
  155797. ** itself grows too big and must be split. The format of interior
  155798. ** nodes:
  155799. **
  155800. ** varint iHeight; (height from leaf level, always >0)
  155801. ** varint iBlockid; (block id of node's leftmost subtree)
  155802. ** optional {
  155803. ** varint nTerm; (length of first term)
  155804. ** char pTerm[nTerm]; (content of first term)
  155805. ** array {
  155806. ** (further terms are delta-encoded)
  155807. ** varint nPrefix; (length of shared prefix with previous term)
  155808. ** varint nSuffix; (length of unshared suffix)
  155809. ** char pTermSuffix[nSuffix]; (unshared suffix of next term)
  155810. ** }
  155811. ** }
  155812. **
  155813. ** Here, optional { X } means an optional element, while array { X }
  155814. ** means zero or more occurrences of X, adjacent in memory.
  155815. **
  155816. ** An interior node encodes n terms separating n+1 subtrees. The
  155817. ** subtree blocks are contiguous, so only the first subtree's blockid
  155818. ** is encoded. The subtree at iBlockid will contain all terms less
  155819. ** than the first term encoded (or all terms if no term is encoded).
  155820. ** Otherwise, for terms greater than or equal to pTerm[i] but less
  155821. ** than pTerm[i+1], the subtree for that term will be rooted at
  155822. ** iBlockid+i. Interior nodes only store enough term data to
  155823. ** distinguish adjacent children (if the rightmost term of the left
  155824. ** child is "something", and the leftmost term of the right child is
  155825. ** "wicked", only "w" is stored).
  155826. **
  155827. ** New data is spilled to a new interior node at the same height when
  155828. ** the current node exceeds INTERIOR_MAX bytes (default 2048).
  155829. ** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
  155830. ** interior nodes and making the tree too skinny. The interior nodes
  155831. ** at a given height are naturally tracked by interior nodes at
  155832. ** height+1, and so on.
  155833. **
  155834. **
  155835. **** Segment directory ****
  155836. ** The segment directory in table %_segdir stores meta-information for
  155837. ** merging and deleting segments, and also the root node of the
  155838. ** segment's tree.
  155839. **
  155840. ** The root node is the top node of the segment's tree after encoding
  155841. ** the entire segment, restricted to ROOT_MAX bytes (default 1024).
  155842. ** This could be either a leaf node or an interior node. If the top
  155843. ** node requires more than ROOT_MAX bytes, it is flushed to %_segments
  155844. ** and a new root interior node is generated (which should always fit
  155845. ** within ROOT_MAX because it only needs space for 2 varints, the
  155846. ** height and the blockid of the previous root).
  155847. **
  155848. ** The meta-information in the segment directory is:
  155849. ** level - segment level (see below)
  155850. ** idx - index within level
  155851. ** - (level,idx uniquely identify a segment)
  155852. ** start_block - first leaf node
  155853. ** leaves_end_block - last leaf node
  155854. ** end_block - last block (including interior nodes)
  155855. ** root - contents of root node
  155856. **
  155857. ** If the root node is a leaf node, then start_block,
  155858. ** leaves_end_block, and end_block are all 0.
  155859. **
  155860. **
  155861. **** Segment merging ****
  155862. ** To amortize update costs, segments are grouped into levels and
  155863. ** merged in batches. Each increase in level represents exponentially
  155864. ** more documents.
  155865. **
  155866. ** New documents (actually, document updates) are tokenized and
  155867. ** written individually (using LeafWriter) to a level 0 segment, with
  155868. ** incrementing idx. When idx reaches MERGE_COUNT (default 16), all
  155869. ** level 0 segments are merged into a single level 1 segment. Level 1
  155870. ** is populated like level 0, and eventually MERGE_COUNT level 1
  155871. ** segments are merged to a single level 2 segment (representing
  155872. ** MERGE_COUNT^2 updates), and so on.
  155873. **
  155874. ** A segment merge traverses all segments at a given level in
  155875. ** parallel, performing a straightforward sorted merge. Since segment
  155876. ** leaf nodes are written in to the %_segments table in order, this
  155877. ** merge traverses the underlying sqlite disk structures efficiently.
  155878. ** After the merge, all segment blocks from the merged level are
  155879. ** deleted.
  155880. **
  155881. ** MERGE_COUNT controls how often we merge segments. 16 seems to be
  155882. ** somewhat of a sweet spot for insertion performance. 32 and 64 show
  155883. ** very similar performance numbers to 16 on insertion, though they're
  155884. ** a tiny bit slower (perhaps due to more overhead in merge-time
  155885. ** sorting). 8 is about 20% slower than 16, 4 about 50% slower than
  155886. ** 16, 2 about 66% slower than 16.
  155887. **
  155888. ** At query time, high MERGE_COUNT increases the number of segments
  155889. ** which need to be scanned and merged. For instance, with 100k docs
  155890. ** inserted:
  155891. **
  155892. ** MERGE_COUNT segments
  155893. ** 16 25
  155894. ** 8 12
  155895. ** 4 10
  155896. ** 2 6
  155897. **
  155898. ** This appears to have only a moderate impact on queries for very
  155899. ** frequent terms (which are somewhat dominated by segment merge
  155900. ** costs), and infrequent and non-existent terms still seem to be fast
  155901. ** even with many segments.
  155902. **
  155903. ** TODO(shess) That said, it would be nice to have a better query-side
  155904. ** argument for MERGE_COUNT of 16. Also, it is possible/likely that
  155905. ** optimizations to things like doclist merging will swing the sweet
  155906. ** spot around.
  155907. **
  155908. **
  155909. **
  155910. **** Handling of deletions and updates ****
  155911. ** Since we're using a segmented structure, with no docid-oriented
  155912. ** index into the term index, we clearly cannot simply update the term
  155913. ** index when a document is deleted or updated. For deletions, we
  155914. ** write an empty doclist (varint(docid) varint(POS_END)), for updates
  155915. ** we simply write the new doclist. Segment merges overwrite older
  155916. ** data for a particular docid with newer data, so deletes or updates
  155917. ** will eventually overtake the earlier data and knock it out. The
  155918. ** query logic likewise merges doclists so that newer data knocks out
  155919. ** older data.
  155920. */
  155921. /************** Include fts3Int.h in the middle of fts3.c ********************/
  155922. /************** Begin file fts3Int.h *****************************************/
  155923. /*
  155924. ** 2009 Nov 12
  155925. **
  155926. ** The author disclaims copyright to this source code. In place of
  155927. ** a legal notice, here is a blessing:
  155928. **
  155929. ** May you do good and not evil.
  155930. ** May you find forgiveness for yourself and forgive others.
  155931. ** May you share freely, never taking more than you give.
  155932. **
  155933. ******************************************************************************
  155934. **
  155935. */
  155936. #ifndef _FTSINT_H
  155937. #define _FTSINT_H
  155938. #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
  155939. # define NDEBUG 1
  155940. #endif
  155941. /* FTS3/FTS4 require virtual tables */
  155942. #ifdef SQLITE_OMIT_VIRTUALTABLE
  155943. # undef SQLITE_ENABLE_FTS3
  155944. # undef SQLITE_ENABLE_FTS4
  155945. #endif
  155946. /*
  155947. ** FTS4 is really an extension for FTS3. It is enabled using the
  155948. ** SQLITE_ENABLE_FTS3 macro. But to avoid confusion we also all
  155949. ** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
  155950. */
  155951. #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
  155952. # define SQLITE_ENABLE_FTS3
  155953. #endif
  155954. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  155955. /* If not building as part of the core, include sqlite3ext.h. */
  155956. #ifndef SQLITE_CORE
  155957. /* # include "sqlite3ext.h" */
  155958. SQLITE_EXTENSION_INIT3
  155959. #endif
  155960. /* #include "sqlite3.h" */
  155961. /************** Include fts3_tokenizer.h in the middle of fts3Int.h **********/
  155962. /************** Begin file fts3_tokenizer.h **********************************/
  155963. /*
  155964. ** 2006 July 10
  155965. **
  155966. ** The author disclaims copyright to this source code.
  155967. **
  155968. *************************************************************************
  155969. ** Defines the interface to tokenizers used by fulltext-search. There
  155970. ** are three basic components:
  155971. **
  155972. ** sqlite3_tokenizer_module is a singleton defining the tokenizer
  155973. ** interface functions. This is essentially the class structure for
  155974. ** tokenizers.
  155975. **
  155976. ** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
  155977. ** including customization information defined at creation time.
  155978. **
  155979. ** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
  155980. ** tokens from a particular input.
  155981. */
  155982. #ifndef _FTS3_TOKENIZER_H_
  155983. #define _FTS3_TOKENIZER_H_
  155984. /* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
  155985. ** If tokenizers are to be allowed to call sqlite3_*() functions, then
  155986. ** we will need a way to register the API consistently.
  155987. */
  155988. /* #include "sqlite3.h" */
  155989. /*
  155990. ** Structures used by the tokenizer interface. When a new tokenizer
  155991. ** implementation is registered, the caller provides a pointer to
  155992. ** an sqlite3_tokenizer_module containing pointers to the callback
  155993. ** functions that make up an implementation.
  155994. **
  155995. ** When an fts3 table is created, it passes any arguments passed to
  155996. ** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
  155997. ** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
  155998. ** implementation. The xCreate() function in turn returns an
  155999. ** sqlite3_tokenizer structure representing the specific tokenizer to
  156000. ** be used for the fts3 table (customized by the tokenizer clause arguments).
  156001. **
  156002. ** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
  156003. ** method is called. It returns an sqlite3_tokenizer_cursor object
  156004. ** that may be used to tokenize a specific input buffer based on
  156005. ** the tokenization rules supplied by a specific sqlite3_tokenizer
  156006. ** object.
  156007. */
  156008. typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
  156009. typedef struct sqlite3_tokenizer sqlite3_tokenizer;
  156010. typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
  156011. struct sqlite3_tokenizer_module {
  156012. /*
  156013. ** Structure version. Should always be set to 0 or 1.
  156014. */
  156015. int iVersion;
  156016. /*
  156017. ** Create a new tokenizer. The values in the argv[] array are the
  156018. ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
  156019. ** TABLE statement that created the fts3 table. For example, if
  156020. ** the following SQL is executed:
  156021. **
  156022. ** CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
  156023. **
  156024. ** then argc is set to 2, and the argv[] array contains pointers
  156025. ** to the strings "arg1" and "arg2".
  156026. **
  156027. ** This method should return either SQLITE_OK (0), or an SQLite error
  156028. ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
  156029. ** to point at the newly created tokenizer structure. The generic
  156030. ** sqlite3_tokenizer.pModule variable should not be initialized by
  156031. ** this callback. The caller will do so.
  156032. */
  156033. int (*xCreate)(
  156034. int argc, /* Size of argv array */
  156035. const char *const*argv, /* Tokenizer argument strings */
  156036. sqlite3_tokenizer **ppTokenizer /* OUT: Created tokenizer */
  156037. );
  156038. /*
  156039. ** Destroy an existing tokenizer. The fts3 module calls this method
  156040. ** exactly once for each successful call to xCreate().
  156041. */
  156042. int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
  156043. /*
  156044. ** Create a tokenizer cursor to tokenize an input buffer. The caller
  156045. ** is responsible for ensuring that the input buffer remains valid
  156046. ** until the cursor is closed (using the xClose() method).
  156047. */
  156048. int (*xOpen)(
  156049. sqlite3_tokenizer *pTokenizer, /* Tokenizer object */
  156050. const char *pInput, int nBytes, /* Input buffer */
  156051. sqlite3_tokenizer_cursor **ppCursor /* OUT: Created tokenizer cursor */
  156052. );
  156053. /*
  156054. ** Destroy an existing tokenizer cursor. The fts3 module calls this
  156055. ** method exactly once for each successful call to xOpen().
  156056. */
  156057. int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
  156058. /*
  156059. ** Retrieve the next token from the tokenizer cursor pCursor. This
  156060. ** method should either return SQLITE_OK and set the values of the
  156061. ** "OUT" variables identified below, or SQLITE_DONE to indicate that
  156062. ** the end of the buffer has been reached, or an SQLite error code.
  156063. **
  156064. ** *ppToken should be set to point at a buffer containing the
  156065. ** normalized version of the token (i.e. after any case-folding and/or
  156066. ** stemming has been performed). *pnBytes should be set to the length
  156067. ** of this buffer in bytes. The input text that generated the token is
  156068. ** identified by the byte offsets returned in *piStartOffset and
  156069. ** *piEndOffset. *piStartOffset should be set to the index of the first
  156070. ** byte of the token in the input buffer. *piEndOffset should be set
  156071. ** to the index of the first byte just past the end of the token in
  156072. ** the input buffer.
  156073. **
  156074. ** The buffer *ppToken is set to point at is managed by the tokenizer
  156075. ** implementation. It is only required to be valid until the next call
  156076. ** to xNext() or xClose().
  156077. */
  156078. /* TODO(shess) current implementation requires pInput to be
  156079. ** nul-terminated. This should either be fixed, or pInput/nBytes
  156080. ** should be converted to zInput.
  156081. */
  156082. int (*xNext)(
  156083. sqlite3_tokenizer_cursor *pCursor, /* Tokenizer cursor */
  156084. const char **ppToken, int *pnBytes, /* OUT: Normalized text for token */
  156085. int *piStartOffset, /* OUT: Byte offset of token in input buffer */
  156086. int *piEndOffset, /* OUT: Byte offset of end of token in input buffer */
  156087. int *piPosition /* OUT: Number of tokens returned before this one */
  156088. );
  156089. /***********************************************************************
  156090. ** Methods below this point are only available if iVersion>=1.
  156091. */
  156092. /*
  156093. ** Configure the language id of a tokenizer cursor.
  156094. */
  156095. int (*xLanguageid)(sqlite3_tokenizer_cursor *pCsr, int iLangid);
  156096. };
  156097. struct sqlite3_tokenizer {
  156098. const sqlite3_tokenizer_module *pModule; /* The module for this tokenizer */
  156099. /* Tokenizer implementations will typically add additional fields */
  156100. };
  156101. struct sqlite3_tokenizer_cursor {
  156102. sqlite3_tokenizer *pTokenizer; /* Tokenizer for this cursor. */
  156103. /* Tokenizer implementations will typically add additional fields */
  156104. };
  156105. int fts3_global_term_cnt(int iTerm, int iCol);
  156106. int fts3_term_cnt(int iTerm, int iCol);
  156107. #endif /* _FTS3_TOKENIZER_H_ */
  156108. /************** End of fts3_tokenizer.h **************************************/
  156109. /************** Continuing where we left off in fts3Int.h ********************/
  156110. /************** Include fts3_hash.h in the middle of fts3Int.h ***************/
  156111. /************** Begin file fts3_hash.h ***************************************/
  156112. /*
  156113. ** 2001 September 22
  156114. **
  156115. ** The author disclaims copyright to this source code. In place of
  156116. ** a legal notice, here is a blessing:
  156117. **
  156118. ** May you do good and not evil.
  156119. ** May you find forgiveness for yourself and forgive others.
  156120. ** May you share freely, never taking more than you give.
  156121. **
  156122. *************************************************************************
  156123. ** This is the header file for the generic hash-table implementation
  156124. ** used in SQLite. We've modified it slightly to serve as a standalone
  156125. ** hash table implementation for the full-text indexing module.
  156126. **
  156127. */
  156128. #ifndef _FTS3_HASH_H_
  156129. #define _FTS3_HASH_H_
  156130. /* Forward declarations of structures. */
  156131. typedef struct Fts3Hash Fts3Hash;
  156132. typedef struct Fts3HashElem Fts3HashElem;
  156133. /* A complete hash table is an instance of the following structure.
  156134. ** The internals of this structure are intended to be opaque -- client
  156135. ** code should not attempt to access or modify the fields of this structure
  156136. ** directly. Change this structure only by using the routines below.
  156137. ** However, many of the "procedures" and "functions" for modifying and
  156138. ** accessing this structure are really macros, so we can't really make
  156139. ** this structure opaque.
  156140. */
  156141. struct Fts3Hash {
  156142. char keyClass; /* HASH_INT, _POINTER, _STRING, _BINARY */
  156143. char copyKey; /* True if copy of key made on insert */
  156144. int count; /* Number of entries in this table */
  156145. Fts3HashElem *first; /* The first element of the array */
  156146. int htsize; /* Number of buckets in the hash table */
  156147. struct _fts3ht { /* the hash table */
  156148. int count; /* Number of entries with this hash */
  156149. Fts3HashElem *chain; /* Pointer to first entry with this hash */
  156150. } *ht;
  156151. };
  156152. /* Each element in the hash table is an instance of the following
  156153. ** structure. All elements are stored on a single doubly-linked list.
  156154. **
  156155. ** Again, this structure is intended to be opaque, but it can't really
  156156. ** be opaque because it is used by macros.
  156157. */
  156158. struct Fts3HashElem {
  156159. Fts3HashElem *next, *prev; /* Next and previous elements in the table */
  156160. void *data; /* Data associated with this element */
  156161. void *pKey; int nKey; /* Key associated with this element */
  156162. };
  156163. /*
  156164. ** There are 2 different modes of operation for a hash table:
  156165. **
  156166. ** FTS3_HASH_STRING pKey points to a string that is nKey bytes long
  156167. ** (including the null-terminator, if any). Case
  156168. ** is respected in comparisons.
  156169. **
  156170. ** FTS3_HASH_BINARY pKey points to binary data nKey bytes long.
  156171. ** memcmp() is used to compare keys.
  156172. **
  156173. ** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.
  156174. */
  156175. #define FTS3_HASH_STRING 1
  156176. #define FTS3_HASH_BINARY 2
  156177. /*
  156178. ** Access routines. To delete, insert a NULL pointer.
  156179. */
  156180. SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey);
  156181. SQLITE_PRIVATE void *sqlite3Fts3HashInsert(Fts3Hash*, const void *pKey, int nKey, void *pData);
  156182. SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash*, const void *pKey, int nKey);
  156183. SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash*);
  156184. SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const void *, int);
  156185. /*
  156186. ** Shorthand for the functions above
  156187. */
  156188. #define fts3HashInit sqlite3Fts3HashInit
  156189. #define fts3HashInsert sqlite3Fts3HashInsert
  156190. #define fts3HashFind sqlite3Fts3HashFind
  156191. #define fts3HashClear sqlite3Fts3HashClear
  156192. #define fts3HashFindElem sqlite3Fts3HashFindElem
  156193. /*
  156194. ** Macros for looping over all elements of a hash table. The idiom is
  156195. ** like this:
  156196. **
  156197. ** Fts3Hash h;
  156198. ** Fts3HashElem *p;
  156199. ** ...
  156200. ** for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
  156201. ** SomeStructure *pData = fts3HashData(p);
  156202. ** // do something with pData
  156203. ** }
  156204. */
  156205. #define fts3HashFirst(H) ((H)->first)
  156206. #define fts3HashNext(E) ((E)->next)
  156207. #define fts3HashData(E) ((E)->data)
  156208. #define fts3HashKey(E) ((E)->pKey)
  156209. #define fts3HashKeysize(E) ((E)->nKey)
  156210. /*
  156211. ** Number of entries in a hash table
  156212. */
  156213. #define fts3HashCount(H) ((H)->count)
  156214. #endif /* _FTS3_HASH_H_ */
  156215. /************** End of fts3_hash.h *******************************************/
  156216. /************** Continuing where we left off in fts3Int.h ********************/
  156217. /*
  156218. ** This constant determines the maximum depth of an FTS expression tree
  156219. ** that the library will create and use. FTS uses recursion to perform
  156220. ** various operations on the query tree, so the disadvantage of a large
  156221. ** limit is that it may allow very large queries to use large amounts
  156222. ** of stack space (perhaps causing a stack overflow).
  156223. */
  156224. #ifndef SQLITE_FTS3_MAX_EXPR_DEPTH
  156225. # define SQLITE_FTS3_MAX_EXPR_DEPTH 12
  156226. #endif
  156227. /*
  156228. ** This constant controls how often segments are merged. Once there are
  156229. ** FTS3_MERGE_COUNT segments of level N, they are merged into a single
  156230. ** segment of level N+1.
  156231. */
  156232. #define FTS3_MERGE_COUNT 16
  156233. /*
  156234. ** This is the maximum amount of data (in bytes) to store in the
  156235. ** Fts3Table.pendingTerms hash table. Normally, the hash table is
  156236. ** populated as documents are inserted/updated/deleted in a transaction
  156237. ** and used to create a new segment when the transaction is committed.
  156238. ** However if this limit is reached midway through a transaction, a new
  156239. ** segment is created and the hash table cleared immediately.
  156240. */
  156241. #define FTS3_MAX_PENDING_DATA (1*1024*1024)
  156242. /*
  156243. ** Macro to return the number of elements in an array. SQLite has a
  156244. ** similar macro called ArraySize(). Use a different name to avoid
  156245. ** a collision when building an amalgamation with built-in FTS3.
  156246. */
  156247. #define SizeofArray(X) ((int)(sizeof(X)/sizeof(X[0])))
  156248. #ifndef MIN
  156249. # define MIN(x,y) ((x)<(y)?(x):(y))
  156250. #endif
  156251. #ifndef MAX
  156252. # define MAX(x,y) ((x)>(y)?(x):(y))
  156253. #endif
  156254. /*
  156255. ** Maximum length of a varint encoded integer. The varint format is different
  156256. ** from that used by SQLite, so the maximum length is 10, not 9.
  156257. */
  156258. #define FTS3_VARINT_MAX 10
  156259. #define FTS3_BUFFER_PADDING 8
  156260. /*
  156261. ** FTS4 virtual tables may maintain multiple indexes - one index of all terms
  156262. ** in the document set and zero or more prefix indexes. All indexes are stored
  156263. ** as one or more b+-trees in the %_segments and %_segdir tables.
  156264. **
  156265. ** It is possible to determine which index a b+-tree belongs to based on the
  156266. ** value stored in the "%_segdir.level" column. Given this value L, the index
  156267. ** that the b+-tree belongs to is (L<<10). In other words, all b+-trees with
  156268. ** level values between 0 and 1023 (inclusive) belong to index 0, all levels
  156269. ** between 1024 and 2047 to index 1, and so on.
  156270. **
  156271. ** It is considered impossible for an index to use more than 1024 levels. In
  156272. ** theory though this may happen, but only after at least
  156273. ** (FTS3_MERGE_COUNT^1024) separate flushes of the pending-terms tables.
  156274. */
  156275. #define FTS3_SEGDIR_MAXLEVEL 1024
  156276. #define FTS3_SEGDIR_MAXLEVEL_STR "1024"
  156277. /*
  156278. ** The testcase() macro is only used by the amalgamation. If undefined,
  156279. ** make it a no-op.
  156280. */
  156281. #ifndef testcase
  156282. # define testcase(X)
  156283. #endif
  156284. /*
  156285. ** Terminator values for position-lists and column-lists.
  156286. */
  156287. #define POS_COLUMN (1) /* Column-list terminator */
  156288. #define POS_END (0) /* Position-list terminator */
  156289. /*
  156290. ** The assert_fts3_nc() macro is similar to the assert() macro, except that it
  156291. ** is used for assert() conditions that are true only if it can be
  156292. ** guranteed that the database is not corrupt.
  156293. */
  156294. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  156295. SQLITE_API extern int sqlite3_fts3_may_be_corrupt;
  156296. # define assert_fts3_nc(x) assert(sqlite3_fts3_may_be_corrupt || (x))
  156297. #else
  156298. # define assert_fts3_nc(x) assert(x)
  156299. #endif
  156300. /*
  156301. ** This section provides definitions to allow the
  156302. ** FTS3 extension to be compiled outside of the
  156303. ** amalgamation.
  156304. */
  156305. #ifndef SQLITE_AMALGAMATION
  156306. /*
  156307. ** Macros indicating that conditional expressions are always true or
  156308. ** false.
  156309. */
  156310. #ifdef SQLITE_COVERAGE_TEST
  156311. # define ALWAYS(x) (1)
  156312. # define NEVER(X) (0)
  156313. #elif defined(SQLITE_DEBUG)
  156314. # define ALWAYS(x) sqlite3Fts3Always((x)!=0)
  156315. # define NEVER(x) sqlite3Fts3Never((x)!=0)
  156316. SQLITE_PRIVATE int sqlite3Fts3Always(int b);
  156317. SQLITE_PRIVATE int sqlite3Fts3Never(int b);
  156318. #else
  156319. # define ALWAYS(x) (x)
  156320. # define NEVER(x) (x)
  156321. #endif
  156322. /*
  156323. ** Internal types used by SQLite.
  156324. */
  156325. typedef unsigned char u8; /* 1-byte (or larger) unsigned integer */
  156326. typedef short int i16; /* 2-byte (or larger) signed integer */
  156327. typedef unsigned int u32; /* 4-byte unsigned integer */
  156328. typedef sqlite3_uint64 u64; /* 8-byte unsigned integer */
  156329. typedef sqlite3_int64 i64; /* 8-byte signed integer */
  156330. /*
  156331. ** Macro used to suppress compiler warnings for unused parameters.
  156332. */
  156333. #define UNUSED_PARAMETER(x) (void)(x)
  156334. /*
  156335. ** Activate assert() only if SQLITE_TEST is enabled.
  156336. */
  156337. #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
  156338. # define NDEBUG 1
  156339. #endif
  156340. /*
  156341. ** The TESTONLY macro is used to enclose variable declarations or
  156342. ** other bits of code that are needed to support the arguments
  156343. ** within testcase() and assert() macros.
  156344. */
  156345. #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
  156346. # define TESTONLY(X) X
  156347. #else
  156348. # define TESTONLY(X)
  156349. #endif
  156350. #define LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32))
  156351. #define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
  156352. #endif /* SQLITE_AMALGAMATION */
  156353. #ifdef SQLITE_DEBUG
  156354. SQLITE_PRIVATE int sqlite3Fts3Corrupt(void);
  156355. # define FTS_CORRUPT_VTAB sqlite3Fts3Corrupt()
  156356. #else
  156357. # define FTS_CORRUPT_VTAB SQLITE_CORRUPT_VTAB
  156358. #endif
  156359. typedef struct Fts3Table Fts3Table;
  156360. typedef struct Fts3Cursor Fts3Cursor;
  156361. typedef struct Fts3Expr Fts3Expr;
  156362. typedef struct Fts3Phrase Fts3Phrase;
  156363. typedef struct Fts3PhraseToken Fts3PhraseToken;
  156364. typedef struct Fts3Doclist Fts3Doclist;
  156365. typedef struct Fts3SegFilter Fts3SegFilter;
  156366. typedef struct Fts3DeferredToken Fts3DeferredToken;
  156367. typedef struct Fts3SegReader Fts3SegReader;
  156368. typedef struct Fts3MultiSegReader Fts3MultiSegReader;
  156369. typedef struct MatchinfoBuffer MatchinfoBuffer;
  156370. /*
  156371. ** A connection to a fulltext index is an instance of the following
  156372. ** structure. The xCreate and xConnect methods create an instance
  156373. ** of this structure and xDestroy and xDisconnect free that instance.
  156374. ** All other methods receive a pointer to the structure as one of their
  156375. ** arguments.
  156376. */
  156377. struct Fts3Table {
  156378. sqlite3_vtab base; /* Base class used by SQLite core */
  156379. sqlite3 *db; /* The database connection */
  156380. const char *zDb; /* logical database name */
  156381. const char *zName; /* virtual table name */
  156382. int nColumn; /* number of named columns in virtual table */
  156383. char **azColumn; /* column names. malloced */
  156384. u8 *abNotindexed; /* True for 'notindexed' columns */
  156385. sqlite3_tokenizer *pTokenizer; /* tokenizer for inserts and queries */
  156386. char *zContentTbl; /* content=xxx option, or NULL */
  156387. char *zLanguageid; /* languageid=xxx option, or NULL */
  156388. int nAutoincrmerge; /* Value configured by 'automerge' */
  156389. u32 nLeafAdd; /* Number of leaf blocks added this trans */
  156390. int bLock; /* Used to prevent recursive content= tbls */
  156391. /* Precompiled statements used by the implementation. Each of these
  156392. ** statements is run and reset within a single virtual table API call.
  156393. */
  156394. sqlite3_stmt *aStmt[40];
  156395. sqlite3_stmt *pSeekStmt; /* Cache for fts3CursorSeekStmt() */
  156396. char *zReadExprlist;
  156397. char *zWriteExprlist;
  156398. int nNodeSize; /* Soft limit for node size */
  156399. u8 bFts4; /* True for FTS4, false for FTS3 */
  156400. u8 bHasStat; /* True if %_stat table exists (2==unknown) */
  156401. u8 bHasDocsize; /* True if %_docsize table exists */
  156402. u8 bDescIdx; /* True if doclists are in reverse order */
  156403. u8 bIgnoreSavepoint; /* True to ignore xSavepoint invocations */
  156404. int nPgsz; /* Page size for host database */
  156405. char *zSegmentsTbl; /* Name of %_segments table */
  156406. sqlite3_blob *pSegments; /* Blob handle open on %_segments table */
  156407. /*
  156408. ** The following array of hash tables is used to buffer pending index
  156409. ** updates during transactions. All pending updates buffered at any one
  156410. ** time must share a common language-id (see the FTS4 langid= feature).
  156411. ** The current language id is stored in variable iPrevLangid.
  156412. **
  156413. ** A single FTS4 table may have multiple full-text indexes. For each index
  156414. ** there is an entry in the aIndex[] array. Index 0 is an index of all the
  156415. ** terms that appear in the document set. Each subsequent index in aIndex[]
  156416. ** is an index of prefixes of a specific length.
  156417. **
  156418. ** Variable nPendingData contains an estimate the memory consumed by the
  156419. ** pending data structures, including hash table overhead, but not including
  156420. ** malloc overhead. When nPendingData exceeds nMaxPendingData, all hash
  156421. ** tables are flushed to disk. Variable iPrevDocid is the docid of the most
  156422. ** recently inserted record.
  156423. */
  156424. int nIndex; /* Size of aIndex[] */
  156425. struct Fts3Index {
  156426. int nPrefix; /* Prefix length (0 for main terms index) */
  156427. Fts3Hash hPending; /* Pending terms table for this index */
  156428. } *aIndex;
  156429. int nMaxPendingData; /* Max pending data before flush to disk */
  156430. int nPendingData; /* Current bytes of pending data */
  156431. sqlite_int64 iPrevDocid; /* Docid of most recently inserted document */
  156432. int iPrevLangid; /* Langid of recently inserted document */
  156433. int bPrevDelete; /* True if last operation was a delete */
  156434. #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
  156435. /* State variables used for validating that the transaction control
  156436. ** methods of the virtual table are called at appropriate times. These
  156437. ** values do not contribute to FTS functionality; they are used for
  156438. ** verifying the operation of the SQLite core.
  156439. */
  156440. int inTransaction; /* True after xBegin but before xCommit/xRollback */
  156441. int mxSavepoint; /* Largest valid xSavepoint integer */
  156442. #endif
  156443. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  156444. /* True to disable the incremental doclist optimization. This is controled
  156445. ** by special insert command 'test-no-incr-doclist'. */
  156446. int bNoIncrDoclist;
  156447. /* Number of segments in a level */
  156448. int nMergeCount;
  156449. #endif
  156450. };
  156451. /* Macro to find the number of segments to merge */
  156452. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  156453. # define MergeCount(P) ((P)->nMergeCount)
  156454. #else
  156455. # define MergeCount(P) FTS3_MERGE_COUNT
  156456. #endif
  156457. /*
  156458. ** When the core wants to read from the virtual table, it creates a
  156459. ** virtual table cursor (an instance of the following structure) using
  156460. ** the xOpen method. Cursors are destroyed using the xClose method.
  156461. */
  156462. struct Fts3Cursor {
  156463. sqlite3_vtab_cursor base; /* Base class used by SQLite core */
  156464. i16 eSearch; /* Search strategy (see below) */
  156465. u8 isEof; /* True if at End Of Results */
  156466. u8 isRequireSeek; /* True if must seek pStmt to %_content row */
  156467. u8 bSeekStmt; /* True if pStmt is a seek */
  156468. sqlite3_stmt *pStmt; /* Prepared statement in use by the cursor */
  156469. Fts3Expr *pExpr; /* Parsed MATCH query string */
  156470. int iLangid; /* Language being queried for */
  156471. int nPhrase; /* Number of matchable phrases in query */
  156472. Fts3DeferredToken *pDeferred; /* Deferred search tokens, if any */
  156473. sqlite3_int64 iPrevId; /* Previous id read from aDoclist */
  156474. char *pNextId; /* Pointer into the body of aDoclist */
  156475. char *aDoclist; /* List of docids for full-text queries */
  156476. int nDoclist; /* Size of buffer at aDoclist */
  156477. u8 bDesc; /* True to sort in descending order */
  156478. int eEvalmode; /* An FTS3_EVAL_XX constant */
  156479. int nRowAvg; /* Average size of database rows, in pages */
  156480. sqlite3_int64 nDoc; /* Documents in table */
  156481. i64 iMinDocid; /* Minimum docid to return */
  156482. i64 iMaxDocid; /* Maximum docid to return */
  156483. int isMatchinfoNeeded; /* True when aMatchinfo[] needs filling in */
  156484. MatchinfoBuffer *pMIBuffer; /* Buffer for matchinfo data */
  156485. };
  156486. #define FTS3_EVAL_FILTER 0
  156487. #define FTS3_EVAL_NEXT 1
  156488. #define FTS3_EVAL_MATCHINFO 2
  156489. /*
  156490. ** The Fts3Cursor.eSearch member is always set to one of the following.
  156491. ** Actualy, Fts3Cursor.eSearch can be greater than or equal to
  156492. ** FTS3_FULLTEXT_SEARCH. If so, then Fts3Cursor.eSearch - 2 is the index
  156493. ** of the column to be searched. For example, in
  156494. **
  156495. ** CREATE VIRTUAL TABLE ex1 USING fts3(a,b,c,d);
  156496. ** SELECT docid FROM ex1 WHERE b MATCH 'one two three';
  156497. **
  156498. ** Because the LHS of the MATCH operator is 2nd column "b",
  156499. ** Fts3Cursor.eSearch will be set to FTS3_FULLTEXT_SEARCH+1. (+0 for a,
  156500. ** +1 for b, +2 for c, +3 for d.) If the LHS of MATCH were "ex1"
  156501. ** indicating that all columns should be searched,
  156502. ** then eSearch would be set to FTS3_FULLTEXT_SEARCH+4.
  156503. */
  156504. #define FTS3_FULLSCAN_SEARCH 0 /* Linear scan of %_content table */
  156505. #define FTS3_DOCID_SEARCH 1 /* Lookup by rowid on %_content table */
  156506. #define FTS3_FULLTEXT_SEARCH 2 /* Full-text index search */
  156507. /*
  156508. ** The lower 16-bits of the sqlite3_index_info.idxNum value set by
  156509. ** the xBestIndex() method contains the Fts3Cursor.eSearch value described
  156510. ** above. The upper 16-bits contain a combination of the following
  156511. ** bits, used to describe extra constraints on full-text searches.
  156512. */
  156513. #define FTS3_HAVE_LANGID 0x00010000 /* languageid=? */
  156514. #define FTS3_HAVE_DOCID_GE 0x00020000 /* docid>=? */
  156515. #define FTS3_HAVE_DOCID_LE 0x00040000 /* docid<=? */
  156516. struct Fts3Doclist {
  156517. char *aAll; /* Array containing doclist (or NULL) */
  156518. int nAll; /* Size of a[] in bytes */
  156519. char *pNextDocid; /* Pointer to next docid */
  156520. sqlite3_int64 iDocid; /* Current docid (if pList!=0) */
  156521. int bFreeList; /* True if pList should be sqlite3_free()d */
  156522. char *pList; /* Pointer to position list following iDocid */
  156523. int nList; /* Length of position list */
  156524. };
  156525. /*
  156526. ** A "phrase" is a sequence of one or more tokens that must match in
  156527. ** sequence. A single token is the base case and the most common case.
  156528. ** For a sequence of tokens contained in double-quotes (i.e. "one two three")
  156529. ** nToken will be the number of tokens in the string.
  156530. */
  156531. struct Fts3PhraseToken {
  156532. char *z; /* Text of the token */
  156533. int n; /* Number of bytes in buffer z */
  156534. int isPrefix; /* True if token ends with a "*" character */
  156535. int bFirst; /* True if token must appear at position 0 */
  156536. /* Variables above this point are populated when the expression is
  156537. ** parsed (by code in fts3_expr.c). Below this point the variables are
  156538. ** used when evaluating the expression. */
  156539. Fts3DeferredToken *pDeferred; /* Deferred token object for this token */
  156540. Fts3MultiSegReader *pSegcsr; /* Segment-reader for this token */
  156541. };
  156542. struct Fts3Phrase {
  156543. /* Cache of doclist for this phrase. */
  156544. Fts3Doclist doclist;
  156545. int bIncr; /* True if doclist is loaded incrementally */
  156546. int iDoclistToken;
  156547. /* Used by sqlite3Fts3EvalPhrasePoslist() if this is a descendent of an
  156548. ** OR condition. */
  156549. char *pOrPoslist;
  156550. i64 iOrDocid;
  156551. /* Variables below this point are populated by fts3_expr.c when parsing
  156552. ** a MATCH expression. Everything above is part of the evaluation phase.
  156553. */
  156554. int nToken; /* Number of tokens in the phrase */
  156555. int iColumn; /* Index of column this phrase must match */
  156556. Fts3PhraseToken aToken[1]; /* One entry for each token in the phrase */
  156557. };
  156558. /*
  156559. ** A tree of these objects forms the RHS of a MATCH operator.
  156560. **
  156561. ** If Fts3Expr.eType is FTSQUERY_PHRASE and isLoaded is true, then aDoclist
  156562. ** points to a malloced buffer, size nDoclist bytes, containing the results
  156563. ** of this phrase query in FTS3 doclist format. As usual, the initial
  156564. ** "Length" field found in doclists stored on disk is omitted from this
  156565. ** buffer.
  156566. **
  156567. ** Variable aMI is used only for FTSQUERY_NEAR nodes to store the global
  156568. ** matchinfo data. If it is not NULL, it points to an array of size nCol*3,
  156569. ** where nCol is the number of columns in the queried FTS table. The array
  156570. ** is populated as follows:
  156571. **
  156572. ** aMI[iCol*3 + 0] = Undefined
  156573. ** aMI[iCol*3 + 1] = Number of occurrences
  156574. ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
  156575. **
  156576. ** The aMI array is allocated using sqlite3_malloc(). It should be freed
  156577. ** when the expression node is.
  156578. */
  156579. struct Fts3Expr {
  156580. int eType; /* One of the FTSQUERY_XXX values defined below */
  156581. int nNear; /* Valid if eType==FTSQUERY_NEAR */
  156582. Fts3Expr *pParent; /* pParent->pLeft==this or pParent->pRight==this */
  156583. Fts3Expr *pLeft; /* Left operand */
  156584. Fts3Expr *pRight; /* Right operand */
  156585. Fts3Phrase *pPhrase; /* Valid if eType==FTSQUERY_PHRASE */
  156586. /* The following are used by the fts3_eval.c module. */
  156587. sqlite3_int64 iDocid; /* Current docid */
  156588. u8 bEof; /* True this expression is at EOF already */
  156589. u8 bStart; /* True if iDocid is valid */
  156590. u8 bDeferred; /* True if this expression is entirely deferred */
  156591. /* The following are used by the fts3_snippet.c module. */
  156592. int iPhrase; /* Index of this phrase in matchinfo() results */
  156593. u32 *aMI; /* See above */
  156594. };
  156595. /*
  156596. ** Candidate values for Fts3Query.eType. Note that the order of the first
  156597. ** four values is in order of precedence when parsing expressions. For
  156598. ** example, the following:
  156599. **
  156600. ** "a OR b AND c NOT d NEAR e"
  156601. **
  156602. ** is equivalent to:
  156603. **
  156604. ** "a OR (b AND (c NOT (d NEAR e)))"
  156605. */
  156606. #define FTSQUERY_NEAR 1
  156607. #define FTSQUERY_NOT 2
  156608. #define FTSQUERY_AND 3
  156609. #define FTSQUERY_OR 4
  156610. #define FTSQUERY_PHRASE 5
  156611. /* fts3_write.c */
  156612. SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(sqlite3_vtab*,int,sqlite3_value**,sqlite3_int64*);
  156613. SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *);
  156614. SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *);
  156615. SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *);
  156616. SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(int, int, sqlite3_int64,
  156617. sqlite3_int64, sqlite3_int64, const char *, int, Fts3SegReader**);
  156618. SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
  156619. Fts3Table*,int,const char*,int,int,Fts3SegReader**);
  156620. SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *);
  156621. SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table*, int, int, int, sqlite3_stmt **);
  156622. SQLITE_PRIVATE int sqlite3Fts3ReadBlock(Fts3Table*, sqlite3_int64, char **, int*, int*);
  156623. SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(Fts3Table *, sqlite3_stmt **);
  156624. SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(Fts3Table *, sqlite3_int64, sqlite3_stmt **);
  156625. #ifndef SQLITE_DISABLE_FTS4_DEFERRED
  156626. SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *);
  156627. SQLITE_PRIVATE int sqlite3Fts3DeferToken(Fts3Cursor *, Fts3PhraseToken *, int);
  156628. SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *);
  156629. SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *);
  156630. SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(Fts3DeferredToken *, char **, int *);
  156631. #else
  156632. # define sqlite3Fts3FreeDeferredTokens(x)
  156633. # define sqlite3Fts3DeferToken(x,y,z) SQLITE_OK
  156634. # define sqlite3Fts3CacheDeferredDoclists(x) SQLITE_OK
  156635. # define sqlite3Fts3FreeDeferredDoclists(x)
  156636. # define sqlite3Fts3DeferredTokenList(x,y,z) SQLITE_OK
  156637. #endif
  156638. SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *);
  156639. SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *, int *);
  156640. /* Special values interpreted by sqlite3SegReaderCursor() */
  156641. #define FTS3_SEGCURSOR_PENDING -1
  156642. #define FTS3_SEGCURSOR_ALL -2
  156643. SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(Fts3Table*, Fts3MultiSegReader*, Fts3SegFilter*);
  156644. SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(Fts3Table *, Fts3MultiSegReader *);
  156645. SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(Fts3MultiSegReader *);
  156646. SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(Fts3Table *,
  156647. int, int, int, const char *, int, int, int, Fts3MultiSegReader *);
  156648. /* Flags allowed as part of the 4th argument to SegmentReaderIterate() */
  156649. #define FTS3_SEGMENT_REQUIRE_POS 0x00000001
  156650. #define FTS3_SEGMENT_IGNORE_EMPTY 0x00000002
  156651. #define FTS3_SEGMENT_COLUMN_FILTER 0x00000004
  156652. #define FTS3_SEGMENT_PREFIX 0x00000008
  156653. #define FTS3_SEGMENT_SCAN 0x00000010
  156654. #define FTS3_SEGMENT_FIRST 0x00000020
  156655. /* Type passed as 4th argument to SegmentReaderIterate() */
  156656. struct Fts3SegFilter {
  156657. const char *zTerm;
  156658. int nTerm;
  156659. int iCol;
  156660. int flags;
  156661. };
  156662. struct Fts3MultiSegReader {
  156663. /* Used internally by sqlite3Fts3SegReaderXXX() calls */
  156664. Fts3SegReader **apSegment; /* Array of Fts3SegReader objects */
  156665. int nSegment; /* Size of apSegment array */
  156666. int nAdvance; /* How many seg-readers to advance */
  156667. Fts3SegFilter *pFilter; /* Pointer to filter object */
  156668. char *aBuffer; /* Buffer to merge doclists in */
  156669. int nBuffer; /* Allocated size of aBuffer[] in bytes */
  156670. int iColFilter; /* If >=0, filter for this column */
  156671. int bRestart;
  156672. /* Used by fts3.c only. */
  156673. int nCost; /* Cost of running iterator */
  156674. int bLookup; /* True if a lookup of a single entry. */
  156675. /* Output values. Valid only after Fts3SegReaderStep() returns SQLITE_ROW. */
  156676. char *zTerm; /* Pointer to term buffer */
  156677. int nTerm; /* Size of zTerm in bytes */
  156678. char *aDoclist; /* Pointer to doclist buffer */
  156679. int nDoclist; /* Size of aDoclist[] in bytes */
  156680. };
  156681. SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table*,int,int);
  156682. #define fts3GetVarint32(p, piVal) ( \
  156683. (*(u8*)(p)&0x80) ? sqlite3Fts3GetVarint32(p, piVal) : (*piVal=*(u8*)(p), 1) \
  156684. )
  156685. /* fts3.c */
  156686. SQLITE_PRIVATE void sqlite3Fts3ErrMsg(char**,const char*,...);
  156687. SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *, sqlite3_int64);
  156688. SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *, sqlite_int64 *);
  156689. SQLITE_PRIVATE int sqlite3Fts3GetVarintU(const char *, sqlite_uint64 *);
  156690. SQLITE_PRIVATE int sqlite3Fts3GetVarintBounded(const char*,const char*,sqlite3_int64*);
  156691. SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *, int *);
  156692. SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64);
  156693. SQLITE_PRIVATE void sqlite3Fts3Dequote(char *);
  156694. SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(int,char*,int,char**,sqlite3_int64*,int*,u8*);
  156695. SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(Fts3Cursor *, Fts3Expr *, u32 *);
  156696. SQLITE_PRIVATE int sqlite3Fts3FirstFilter(sqlite3_int64, char *, int, char *);
  156697. SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int*, Fts3Table*);
  156698. SQLITE_PRIVATE int sqlite3Fts3EvalTestDeferred(Fts3Cursor *pCsr, int *pRc);
  156699. SQLITE_PRIVATE int sqlite3Fts3ReadInt(const char *z, int *pnOut);
  156700. /* fts3_tokenizer.c */
  156701. SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *, int *);
  156702. SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, Fts3Hash *, const char *);
  156703. SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(Fts3Hash *pHash, const char *,
  156704. sqlite3_tokenizer **, char **
  156705. );
  156706. SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char);
  156707. /* fts3_snippet.c */
  156708. SQLITE_PRIVATE void sqlite3Fts3Offsets(sqlite3_context*, Fts3Cursor*);
  156709. SQLITE_PRIVATE void sqlite3Fts3Snippet(sqlite3_context *, Fts3Cursor *, const char *,
  156710. const char *, const char *, int, int
  156711. );
  156712. SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *, Fts3Cursor *, const char *);
  156713. SQLITE_PRIVATE void sqlite3Fts3MIBufferFree(MatchinfoBuffer *p);
  156714. /* fts3_expr.c */
  156715. SQLITE_PRIVATE int sqlite3Fts3ExprParse(sqlite3_tokenizer *, int,
  156716. char **, int, int, int, const char *, int, Fts3Expr **, char **
  156717. );
  156718. SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *);
  156719. #ifdef SQLITE_TEST
  156720. SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db, Fts3Hash*);
  156721. SQLITE_PRIVATE int sqlite3Fts3InitTerm(sqlite3 *db);
  156722. #endif
  156723. SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(sqlite3_tokenizer *, int, const char *, int,
  156724. sqlite3_tokenizer_cursor **
  156725. );
  156726. /* fts3_aux.c */
  156727. SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db);
  156728. SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *);
  156729. SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
  156730. Fts3Table*, Fts3MultiSegReader*, int, const char*, int);
  156731. SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
  156732. Fts3Table *, Fts3MultiSegReader *, sqlite3_int64 *, char **, int *);
  156733. SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(Fts3Cursor *, Fts3Expr *, int iCol, char **);
  156734. SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(Fts3Cursor *, Fts3MultiSegReader *, int *);
  156735. SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr);
  156736. /* fts3_tokenize_vtab.c */
  156737. SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3*, Fts3Hash *);
  156738. /* fts3_unicode2.c (functions generated by parsing unicode text files) */
  156739. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  156740. SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int, int);
  156741. SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int);
  156742. SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int);
  156743. #endif
  156744. #endif /* !SQLITE_CORE || SQLITE_ENABLE_FTS3 */
  156745. #endif /* _FTSINT_H */
  156746. /************** End of fts3Int.h *********************************************/
  156747. /************** Continuing where we left off in fts3.c ***********************/
  156748. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  156749. #if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
  156750. # define SQLITE_CORE 1
  156751. #endif
  156752. /* #include <assert.h> */
  156753. /* #include <stdlib.h> */
  156754. /* #include <stddef.h> */
  156755. /* #include <stdio.h> */
  156756. /* #include <string.h> */
  156757. /* #include <stdarg.h> */
  156758. /* #include "fts3.h" */
  156759. #ifndef SQLITE_CORE
  156760. /* # include "sqlite3ext.h" */
  156761. SQLITE_EXTENSION_INIT1
  156762. #endif
  156763. static int fts3EvalNext(Fts3Cursor *pCsr);
  156764. static int fts3EvalStart(Fts3Cursor *pCsr);
  156765. static int fts3TermSegReaderCursor(
  156766. Fts3Cursor *, const char *, int, int, Fts3MultiSegReader **);
  156767. #ifndef SQLITE_AMALGAMATION
  156768. # if defined(SQLITE_DEBUG)
  156769. SQLITE_PRIVATE int sqlite3Fts3Always(int b) { assert( b ); return b; }
  156770. SQLITE_PRIVATE int sqlite3Fts3Never(int b) { assert( !b ); return b; }
  156771. # endif
  156772. #endif
  156773. /*
  156774. ** This variable is set to false when running tests for which the on disk
  156775. ** structures should not be corrupt. Otherwise, true. If it is false, extra
  156776. ** assert() conditions in the fts3 code are activated - conditions that are
  156777. ** only true if it is guaranteed that the fts3 database is not corrupt.
  156778. */
  156779. SQLITE_API int sqlite3_fts3_may_be_corrupt = 1;
  156780. /*
  156781. ** Write a 64-bit variable-length integer to memory starting at p[0].
  156782. ** The length of data written will be between 1 and FTS3_VARINT_MAX bytes.
  156783. ** The number of bytes written is returned.
  156784. */
  156785. SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){
  156786. unsigned char *q = (unsigned char *) p;
  156787. sqlite_uint64 vu = v;
  156788. do{
  156789. *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
  156790. vu >>= 7;
  156791. }while( vu!=0 );
  156792. q[-1] &= 0x7f; /* turn off high bit in final byte */
  156793. assert( q - (unsigned char *)p <= FTS3_VARINT_MAX );
  156794. return (int) (q - (unsigned char *)p);
  156795. }
  156796. #define GETVARINT_STEP(v, ptr, shift, mask1, mask2, var, ret) \
  156797. v = (v & mask1) | ( (*(const unsigned char*)(ptr++)) << shift ); \
  156798. if( (v & mask2)==0 ){ var = v; return ret; }
  156799. #define GETVARINT_INIT(v, ptr, shift, mask1, mask2, var, ret) \
  156800. v = (*ptr++); \
  156801. if( (v & mask2)==0 ){ var = v; return ret; }
  156802. SQLITE_PRIVATE int sqlite3Fts3GetVarintU(const char *pBuf, sqlite_uint64 *v){
  156803. const unsigned char *p = (const unsigned char*)pBuf;
  156804. const unsigned char *pStart = p;
  156805. u32 a;
  156806. u64 b;
  156807. int shift;
  156808. GETVARINT_INIT(a, p, 0, 0x00, 0x80, *v, 1);
  156809. GETVARINT_STEP(a, p, 7, 0x7F, 0x4000, *v, 2);
  156810. GETVARINT_STEP(a, p, 14, 0x3FFF, 0x200000, *v, 3);
  156811. GETVARINT_STEP(a, p, 21, 0x1FFFFF, 0x10000000, *v, 4);
  156812. b = (a & 0x0FFFFFFF );
  156813. for(shift=28; shift<=63; shift+=7){
  156814. u64 c = *p++;
  156815. b += (c&0x7F) << shift;
  156816. if( (c & 0x80)==0 ) break;
  156817. }
  156818. *v = b;
  156819. return (int)(p - pStart);
  156820. }
  156821. /*
  156822. ** Read a 64-bit variable-length integer from memory starting at p[0].
  156823. ** Return the number of bytes read, or 0 on error.
  156824. ** The value is stored in *v.
  156825. */
  156826. SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *pBuf, sqlite_int64 *v){
  156827. return sqlite3Fts3GetVarintU(pBuf, (sqlite3_uint64*)v);
  156828. }
  156829. /*
  156830. ** Read a 64-bit variable-length integer from memory starting at p[0] and
  156831. ** not extending past pEnd[-1].
  156832. ** Return the number of bytes read, or 0 on error.
  156833. ** The value is stored in *v.
  156834. */
  156835. SQLITE_PRIVATE int sqlite3Fts3GetVarintBounded(
  156836. const char *pBuf,
  156837. const char *pEnd,
  156838. sqlite_int64 *v
  156839. ){
  156840. const unsigned char *p = (const unsigned char*)pBuf;
  156841. const unsigned char *pStart = p;
  156842. const unsigned char *pX = (const unsigned char*)pEnd;
  156843. u64 b = 0;
  156844. int shift;
  156845. for(shift=0; shift<=63; shift+=7){
  156846. u64 c = p<pX ? *p : 0;
  156847. p++;
  156848. b += (c&0x7F) << shift;
  156849. if( (c & 0x80)==0 ) break;
  156850. }
  156851. *v = b;
  156852. return (int)(p - pStart);
  156853. }
  156854. /*
  156855. ** Similar to sqlite3Fts3GetVarint(), except that the output is truncated to
  156856. ** a non-negative 32-bit integer before it is returned.
  156857. */
  156858. SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *p, int *pi){
  156859. const unsigned char *ptr = (const unsigned char*)p;
  156860. u32 a;
  156861. #ifndef fts3GetVarint32
  156862. GETVARINT_INIT(a, ptr, 0, 0x00, 0x80, *pi, 1);
  156863. #else
  156864. a = (*ptr++);
  156865. assert( a & 0x80 );
  156866. #endif
  156867. GETVARINT_STEP(a, ptr, 7, 0x7F, 0x4000, *pi, 2);
  156868. GETVARINT_STEP(a, ptr, 14, 0x3FFF, 0x200000, *pi, 3);
  156869. GETVARINT_STEP(a, ptr, 21, 0x1FFFFF, 0x10000000, *pi, 4);
  156870. a = (a & 0x0FFFFFFF );
  156871. *pi = (int)(a | ((u32)(*ptr & 0x07) << 28));
  156872. assert( 0==(a & 0x80000000) );
  156873. assert( *pi>=0 );
  156874. return 5;
  156875. }
  156876. /*
  156877. ** Return the number of bytes required to encode v as a varint
  156878. */
  156879. SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64 v){
  156880. int i = 0;
  156881. do{
  156882. i++;
  156883. v >>= 7;
  156884. }while( v!=0 );
  156885. return i;
  156886. }
  156887. /*
  156888. ** Convert an SQL-style quoted string into a normal string by removing
  156889. ** the quote characters. The conversion is done in-place. If the
  156890. ** input does not begin with a quote character, then this routine
  156891. ** is a no-op.
  156892. **
  156893. ** Examples:
  156894. **
  156895. ** "abc" becomes abc
  156896. ** 'xyz' becomes xyz
  156897. ** [pqr] becomes pqr
  156898. ** `mno` becomes mno
  156899. **
  156900. */
  156901. SQLITE_PRIVATE void sqlite3Fts3Dequote(char *z){
  156902. char quote; /* Quote character (if any ) */
  156903. quote = z[0];
  156904. if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
  156905. int iIn = 1; /* Index of next byte to read from input */
  156906. int iOut = 0; /* Index of next byte to write to output */
  156907. /* If the first byte was a '[', then the close-quote character is a ']' */
  156908. if( quote=='[' ) quote = ']';
  156909. while( z[iIn] ){
  156910. if( z[iIn]==quote ){
  156911. if( z[iIn+1]!=quote ) break;
  156912. z[iOut++] = quote;
  156913. iIn += 2;
  156914. }else{
  156915. z[iOut++] = z[iIn++];
  156916. }
  156917. }
  156918. z[iOut] = '\0';
  156919. }
  156920. }
  156921. /*
  156922. ** Read a single varint from the doclist at *pp and advance *pp to point
  156923. ** to the first byte past the end of the varint. Add the value of the varint
  156924. ** to *pVal.
  156925. */
  156926. static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){
  156927. sqlite3_int64 iVal;
  156928. *pp += sqlite3Fts3GetVarint(*pp, &iVal);
  156929. *pVal += iVal;
  156930. }
  156931. /*
  156932. ** When this function is called, *pp points to the first byte following a
  156933. ** varint that is part of a doclist (or position-list, or any other list
  156934. ** of varints). This function moves *pp to point to the start of that varint,
  156935. ** and sets *pVal by the varint value.
  156936. **
  156937. ** Argument pStart points to the first byte of the doclist that the
  156938. ** varint is part of.
  156939. */
  156940. static void fts3GetReverseVarint(
  156941. char **pp,
  156942. char *pStart,
  156943. sqlite3_int64 *pVal
  156944. ){
  156945. sqlite3_int64 iVal;
  156946. char *p;
  156947. /* Pointer p now points at the first byte past the varint we are
  156948. ** interested in. So, unless the doclist is corrupt, the 0x80 bit is
  156949. ** clear on character p[-1]. */
  156950. for(p = (*pp)-2; p>=pStart && *p&0x80; p--);
  156951. p++;
  156952. *pp = p;
  156953. sqlite3Fts3GetVarint(p, &iVal);
  156954. *pVal = iVal;
  156955. }
  156956. /*
  156957. ** The xDisconnect() virtual table method.
  156958. */
  156959. static int fts3DisconnectMethod(sqlite3_vtab *pVtab){
  156960. Fts3Table *p = (Fts3Table *)pVtab;
  156961. int i;
  156962. assert( p->nPendingData==0 );
  156963. assert( p->pSegments==0 );
  156964. /* Free any prepared statements held */
  156965. sqlite3_finalize(p->pSeekStmt);
  156966. for(i=0; i<SizeofArray(p->aStmt); i++){
  156967. sqlite3_finalize(p->aStmt[i]);
  156968. }
  156969. sqlite3_free(p->zSegmentsTbl);
  156970. sqlite3_free(p->zReadExprlist);
  156971. sqlite3_free(p->zWriteExprlist);
  156972. sqlite3_free(p->zContentTbl);
  156973. sqlite3_free(p->zLanguageid);
  156974. /* Invoke the tokenizer destructor to free the tokenizer. */
  156975. p->pTokenizer->pModule->xDestroy(p->pTokenizer);
  156976. sqlite3_free(p);
  156977. return SQLITE_OK;
  156978. }
  156979. /*
  156980. ** Write an error message into *pzErr
  156981. */
  156982. SQLITE_PRIVATE void sqlite3Fts3ErrMsg(char **pzErr, const char *zFormat, ...){
  156983. va_list ap;
  156984. sqlite3_free(*pzErr);
  156985. va_start(ap, zFormat);
  156986. *pzErr = sqlite3_vmprintf(zFormat, ap);
  156987. va_end(ap);
  156988. }
  156989. /*
  156990. ** Construct one or more SQL statements from the format string given
  156991. ** and then evaluate those statements. The success code is written
  156992. ** into *pRc.
  156993. **
  156994. ** If *pRc is initially non-zero then this routine is a no-op.
  156995. */
  156996. static void fts3DbExec(
  156997. int *pRc, /* Success code */
  156998. sqlite3 *db, /* Database in which to run SQL */
  156999. const char *zFormat, /* Format string for SQL */
  157000. ... /* Arguments to the format string */
  157001. ){
  157002. va_list ap;
  157003. char *zSql;
  157004. if( *pRc ) return;
  157005. va_start(ap, zFormat);
  157006. zSql = sqlite3_vmprintf(zFormat, ap);
  157007. va_end(ap);
  157008. if( zSql==0 ){
  157009. *pRc = SQLITE_NOMEM;
  157010. }else{
  157011. *pRc = sqlite3_exec(db, zSql, 0, 0, 0);
  157012. sqlite3_free(zSql);
  157013. }
  157014. }
  157015. /*
  157016. ** The xDestroy() virtual table method.
  157017. */
  157018. static int fts3DestroyMethod(sqlite3_vtab *pVtab){
  157019. Fts3Table *p = (Fts3Table *)pVtab;
  157020. int rc = SQLITE_OK; /* Return code */
  157021. const char *zDb = p->zDb; /* Name of database (e.g. "main", "temp") */
  157022. sqlite3 *db = p->db; /* Database handle */
  157023. /* Drop the shadow tables */
  157024. fts3DbExec(&rc, db,
  157025. "DROP TABLE IF EXISTS %Q.'%q_segments';"
  157026. "DROP TABLE IF EXISTS %Q.'%q_segdir';"
  157027. "DROP TABLE IF EXISTS %Q.'%q_docsize';"
  157028. "DROP TABLE IF EXISTS %Q.'%q_stat';"
  157029. "%s DROP TABLE IF EXISTS %Q.'%q_content';",
  157030. zDb, p->zName,
  157031. zDb, p->zName,
  157032. zDb, p->zName,
  157033. zDb, p->zName,
  157034. (p->zContentTbl ? "--" : ""), zDb,p->zName
  157035. );
  157036. /* If everything has worked, invoke fts3DisconnectMethod() to free the
  157037. ** memory associated with the Fts3Table structure and return SQLITE_OK.
  157038. ** Otherwise, return an SQLite error code.
  157039. */
  157040. return (rc==SQLITE_OK ? fts3DisconnectMethod(pVtab) : rc);
  157041. }
  157042. /*
  157043. ** Invoke sqlite3_declare_vtab() to declare the schema for the FTS3 table
  157044. ** passed as the first argument. This is done as part of the xConnect()
  157045. ** and xCreate() methods.
  157046. **
  157047. ** If *pRc is non-zero when this function is called, it is a no-op.
  157048. ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
  157049. ** before returning.
  157050. */
  157051. static void fts3DeclareVtab(int *pRc, Fts3Table *p){
  157052. if( *pRc==SQLITE_OK ){
  157053. int i; /* Iterator variable */
  157054. int rc; /* Return code */
  157055. char *zSql; /* SQL statement passed to declare_vtab() */
  157056. char *zCols; /* List of user defined columns */
  157057. const char *zLanguageid;
  157058. zLanguageid = (p->zLanguageid ? p->zLanguageid : "__langid");
  157059. sqlite3_vtab_config(p->db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
  157060. /* Create a list of user columns for the virtual table */
  157061. zCols = sqlite3_mprintf("%Q, ", p->azColumn[0]);
  157062. for(i=1; zCols && i<p->nColumn; i++){
  157063. zCols = sqlite3_mprintf("%z%Q, ", zCols, p->azColumn[i]);
  157064. }
  157065. /* Create the whole "CREATE TABLE" statement to pass to SQLite */
  157066. zSql = sqlite3_mprintf(
  157067. "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN, %Q HIDDEN)",
  157068. zCols, p->zName, zLanguageid
  157069. );
  157070. if( !zCols || !zSql ){
  157071. rc = SQLITE_NOMEM;
  157072. }else{
  157073. rc = sqlite3_declare_vtab(p->db, zSql);
  157074. }
  157075. sqlite3_free(zSql);
  157076. sqlite3_free(zCols);
  157077. *pRc = rc;
  157078. }
  157079. }
  157080. /*
  157081. ** Create the %_stat table if it does not already exist.
  157082. */
  157083. SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int *pRc, Fts3Table *p){
  157084. fts3DbExec(pRc, p->db,
  157085. "CREATE TABLE IF NOT EXISTS %Q.'%q_stat'"
  157086. "(id INTEGER PRIMARY KEY, value BLOB);",
  157087. p->zDb, p->zName
  157088. );
  157089. if( (*pRc)==SQLITE_OK ) p->bHasStat = 1;
  157090. }
  157091. /*
  157092. ** Create the backing store tables (%_content, %_segments and %_segdir)
  157093. ** required by the FTS3 table passed as the only argument. This is done
  157094. ** as part of the vtab xCreate() method.
  157095. **
  157096. ** If the p->bHasDocsize boolean is true (indicating that this is an
  157097. ** FTS4 table, not an FTS3 table) then also create the %_docsize and
  157098. ** %_stat tables required by FTS4.
  157099. */
  157100. static int fts3CreateTables(Fts3Table *p){
  157101. int rc = SQLITE_OK; /* Return code */
  157102. int i; /* Iterator variable */
  157103. sqlite3 *db = p->db; /* The database connection */
  157104. if( p->zContentTbl==0 ){
  157105. const char *zLanguageid = p->zLanguageid;
  157106. char *zContentCols; /* Columns of %_content table */
  157107. /* Create a list of user columns for the content table */
  157108. zContentCols = sqlite3_mprintf("docid INTEGER PRIMARY KEY");
  157109. for(i=0; zContentCols && i<p->nColumn; i++){
  157110. char *z = p->azColumn[i];
  157111. zContentCols = sqlite3_mprintf("%z, 'c%d%q'", zContentCols, i, z);
  157112. }
  157113. if( zLanguageid && zContentCols ){
  157114. zContentCols = sqlite3_mprintf("%z, langid", zContentCols, zLanguageid);
  157115. }
  157116. if( zContentCols==0 ) rc = SQLITE_NOMEM;
  157117. /* Create the content table */
  157118. fts3DbExec(&rc, db,
  157119. "CREATE TABLE %Q.'%q_content'(%s)",
  157120. p->zDb, p->zName, zContentCols
  157121. );
  157122. sqlite3_free(zContentCols);
  157123. }
  157124. /* Create other tables */
  157125. fts3DbExec(&rc, db,
  157126. "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);",
  157127. p->zDb, p->zName
  157128. );
  157129. fts3DbExec(&rc, db,
  157130. "CREATE TABLE %Q.'%q_segdir'("
  157131. "level INTEGER,"
  157132. "idx INTEGER,"
  157133. "start_block INTEGER,"
  157134. "leaves_end_block INTEGER,"
  157135. "end_block INTEGER,"
  157136. "root BLOB,"
  157137. "PRIMARY KEY(level, idx)"
  157138. ");",
  157139. p->zDb, p->zName
  157140. );
  157141. if( p->bHasDocsize ){
  157142. fts3DbExec(&rc, db,
  157143. "CREATE TABLE %Q.'%q_docsize'(docid INTEGER PRIMARY KEY, size BLOB);",
  157144. p->zDb, p->zName
  157145. );
  157146. }
  157147. assert( p->bHasStat==p->bFts4 );
  157148. if( p->bHasStat ){
  157149. sqlite3Fts3CreateStatTable(&rc, p);
  157150. }
  157151. return rc;
  157152. }
  157153. /*
  157154. ** Store the current database page-size in bytes in p->nPgsz.
  157155. **
  157156. ** If *pRc is non-zero when this function is called, it is a no-op.
  157157. ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
  157158. ** before returning.
  157159. */
  157160. static void fts3DatabasePageSize(int *pRc, Fts3Table *p){
  157161. if( *pRc==SQLITE_OK ){
  157162. int rc; /* Return code */
  157163. char *zSql; /* SQL text "PRAGMA %Q.page_size" */
  157164. sqlite3_stmt *pStmt; /* Compiled "PRAGMA %Q.page_size" statement */
  157165. zSql = sqlite3_mprintf("PRAGMA %Q.page_size", p->zDb);
  157166. if( !zSql ){
  157167. rc = SQLITE_NOMEM;
  157168. }else{
  157169. rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0);
  157170. if( rc==SQLITE_OK ){
  157171. sqlite3_step(pStmt);
  157172. p->nPgsz = sqlite3_column_int(pStmt, 0);
  157173. rc = sqlite3_finalize(pStmt);
  157174. }else if( rc==SQLITE_AUTH ){
  157175. p->nPgsz = 1024;
  157176. rc = SQLITE_OK;
  157177. }
  157178. }
  157179. assert( p->nPgsz>0 || rc!=SQLITE_OK );
  157180. sqlite3_free(zSql);
  157181. *pRc = rc;
  157182. }
  157183. }
  157184. /*
  157185. ** "Special" FTS4 arguments are column specifications of the following form:
  157186. **
  157187. ** <key> = <value>
  157188. **
  157189. ** There may not be whitespace surrounding the "=" character. The <value>
  157190. ** term may be quoted, but the <key> may not.
  157191. */
  157192. static int fts3IsSpecialColumn(
  157193. const char *z,
  157194. int *pnKey,
  157195. char **pzValue
  157196. ){
  157197. char *zValue;
  157198. const char *zCsr = z;
  157199. while( *zCsr!='=' ){
  157200. if( *zCsr=='\0' ) return 0;
  157201. zCsr++;
  157202. }
  157203. *pnKey = (int)(zCsr-z);
  157204. zValue = sqlite3_mprintf("%s", &zCsr[1]);
  157205. if( zValue ){
  157206. sqlite3Fts3Dequote(zValue);
  157207. }
  157208. *pzValue = zValue;
  157209. return 1;
  157210. }
  157211. /*
  157212. ** Append the output of a printf() style formatting to an existing string.
  157213. */
  157214. static void fts3Appendf(
  157215. int *pRc, /* IN/OUT: Error code */
  157216. char **pz, /* IN/OUT: Pointer to string buffer */
  157217. const char *zFormat, /* Printf format string to append */
  157218. ... /* Arguments for printf format string */
  157219. ){
  157220. if( *pRc==SQLITE_OK ){
  157221. va_list ap;
  157222. char *z;
  157223. va_start(ap, zFormat);
  157224. z = sqlite3_vmprintf(zFormat, ap);
  157225. va_end(ap);
  157226. if( z && *pz ){
  157227. char *z2 = sqlite3_mprintf("%s%s", *pz, z);
  157228. sqlite3_free(z);
  157229. z = z2;
  157230. }
  157231. if( z==0 ) *pRc = SQLITE_NOMEM;
  157232. sqlite3_free(*pz);
  157233. *pz = z;
  157234. }
  157235. }
  157236. /*
  157237. ** Return a copy of input string zInput enclosed in double-quotes (") and
  157238. ** with all double quote characters escaped. For example:
  157239. **
  157240. ** fts3QuoteId("un \"zip\"") -> "un \"\"zip\"\""
  157241. **
  157242. ** The pointer returned points to memory obtained from sqlite3_malloc(). It
  157243. ** is the callers responsibility to call sqlite3_free() to release this
  157244. ** memory.
  157245. */
  157246. static char *fts3QuoteId(char const *zInput){
  157247. sqlite3_int64 nRet;
  157248. char *zRet;
  157249. nRet = 2 + (int)strlen(zInput)*2 + 1;
  157250. zRet = sqlite3_malloc64(nRet);
  157251. if( zRet ){
  157252. int i;
  157253. char *z = zRet;
  157254. *(z++) = '"';
  157255. for(i=0; zInput[i]; i++){
  157256. if( zInput[i]=='"' ) *(z++) = '"';
  157257. *(z++) = zInput[i];
  157258. }
  157259. *(z++) = '"';
  157260. *(z++) = '\0';
  157261. }
  157262. return zRet;
  157263. }
  157264. /*
  157265. ** Return a list of comma separated SQL expressions and a FROM clause that
  157266. ** could be used in a SELECT statement such as the following:
  157267. **
  157268. ** SELECT <list of expressions> FROM %_content AS x ...
  157269. **
  157270. ** to return the docid, followed by each column of text data in order
  157271. ** from left to write. If parameter zFunc is not NULL, then instead of
  157272. ** being returned directly each column of text data is passed to an SQL
  157273. ** function named zFunc first. For example, if zFunc is "unzip" and the
  157274. ** table has the three user-defined columns "a", "b", and "c", the following
  157275. ** string is returned:
  157276. **
  157277. ** "docid, unzip(x.'a'), unzip(x.'b'), unzip(x.'c') FROM %_content AS x"
  157278. **
  157279. ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
  157280. ** is the responsibility of the caller to eventually free it.
  157281. **
  157282. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
  157283. ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
  157284. ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
  157285. ** no error occurs, *pRc is left unmodified.
  157286. */
  157287. static char *fts3ReadExprList(Fts3Table *p, const char *zFunc, int *pRc){
  157288. char *zRet = 0;
  157289. char *zFree = 0;
  157290. char *zFunction;
  157291. int i;
  157292. if( p->zContentTbl==0 ){
  157293. if( !zFunc ){
  157294. zFunction = "";
  157295. }else{
  157296. zFree = zFunction = fts3QuoteId(zFunc);
  157297. }
  157298. fts3Appendf(pRc, &zRet, "docid");
  157299. for(i=0; i<p->nColumn; i++){
  157300. fts3Appendf(pRc, &zRet, ",%s(x.'c%d%q')", zFunction, i, p->azColumn[i]);
  157301. }
  157302. if( p->zLanguageid ){
  157303. fts3Appendf(pRc, &zRet, ", x.%Q", "langid");
  157304. }
  157305. sqlite3_free(zFree);
  157306. }else{
  157307. fts3Appendf(pRc, &zRet, "rowid");
  157308. for(i=0; i<p->nColumn; i++){
  157309. fts3Appendf(pRc, &zRet, ", x.'%q'", p->azColumn[i]);
  157310. }
  157311. if( p->zLanguageid ){
  157312. fts3Appendf(pRc, &zRet, ", x.%Q", p->zLanguageid);
  157313. }
  157314. }
  157315. fts3Appendf(pRc, &zRet, " FROM '%q'.'%q%s' AS x",
  157316. p->zDb,
  157317. (p->zContentTbl ? p->zContentTbl : p->zName),
  157318. (p->zContentTbl ? "" : "_content")
  157319. );
  157320. return zRet;
  157321. }
  157322. /*
  157323. ** Return a list of N comma separated question marks, where N is the number
  157324. ** of columns in the %_content table (one for the docid plus one for each
  157325. ** user-defined text column).
  157326. **
  157327. ** If argument zFunc is not NULL, then all but the first question mark
  157328. ** is preceded by zFunc and an open bracket, and followed by a closed
  157329. ** bracket. For example, if zFunc is "zip" and the FTS3 table has three
  157330. ** user-defined text columns, the following string is returned:
  157331. **
  157332. ** "?, zip(?), zip(?), zip(?)"
  157333. **
  157334. ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
  157335. ** is the responsibility of the caller to eventually free it.
  157336. **
  157337. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
  157338. ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
  157339. ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
  157340. ** no error occurs, *pRc is left unmodified.
  157341. */
  157342. static char *fts3WriteExprList(Fts3Table *p, const char *zFunc, int *pRc){
  157343. char *zRet = 0;
  157344. char *zFree = 0;
  157345. char *zFunction;
  157346. int i;
  157347. if( !zFunc ){
  157348. zFunction = "";
  157349. }else{
  157350. zFree = zFunction = fts3QuoteId(zFunc);
  157351. }
  157352. fts3Appendf(pRc, &zRet, "?");
  157353. for(i=0; i<p->nColumn; i++){
  157354. fts3Appendf(pRc, &zRet, ",%s(?)", zFunction);
  157355. }
  157356. if( p->zLanguageid ){
  157357. fts3Appendf(pRc, &zRet, ", ?");
  157358. }
  157359. sqlite3_free(zFree);
  157360. return zRet;
  157361. }
  157362. /*
  157363. ** Buffer z contains a positive integer value encoded as utf-8 text.
  157364. ** Decode this value and store it in *pnOut, returning the number of bytes
  157365. ** consumed. If an overflow error occurs return a negative value.
  157366. */
  157367. SQLITE_PRIVATE int sqlite3Fts3ReadInt(const char *z, int *pnOut){
  157368. u64 iVal = 0;
  157369. int i;
  157370. for(i=0; z[i]>='0' && z[i]<='9'; i++){
  157371. iVal = iVal*10 + (z[i] - '0');
  157372. if( iVal>0x7FFFFFFF ) return -1;
  157373. }
  157374. *pnOut = (int)iVal;
  157375. return i;
  157376. }
  157377. /*
  157378. ** This function interprets the string at (*pp) as a non-negative integer
  157379. ** value. It reads the integer and sets *pnOut to the value read, then
  157380. ** sets *pp to point to the byte immediately following the last byte of
  157381. ** the integer value.
  157382. **
  157383. ** Only decimal digits ('0'..'9') may be part of an integer value.
  157384. **
  157385. ** If *pp does not being with a decimal digit SQLITE_ERROR is returned and
  157386. ** the output value undefined. Otherwise SQLITE_OK is returned.
  157387. **
  157388. ** This function is used when parsing the "prefix=" FTS4 parameter.
  157389. */
  157390. static int fts3GobbleInt(const char **pp, int *pnOut){
  157391. const int MAX_NPREFIX = 10000000;
  157392. int nInt = 0; /* Output value */
  157393. int nByte;
  157394. nByte = sqlite3Fts3ReadInt(*pp, &nInt);
  157395. if( nInt>MAX_NPREFIX ){
  157396. nInt = 0;
  157397. }
  157398. if( nByte==0 ){
  157399. return SQLITE_ERROR;
  157400. }
  157401. *pnOut = nInt;
  157402. *pp += nByte;
  157403. return SQLITE_OK;
  157404. }
  157405. /*
  157406. ** This function is called to allocate an array of Fts3Index structures
  157407. ** representing the indexes maintained by the current FTS table. FTS tables
  157408. ** always maintain the main "terms" index, but may also maintain one or
  157409. ** more "prefix" indexes, depending on the value of the "prefix=" parameter
  157410. ** (if any) specified as part of the CREATE VIRTUAL TABLE statement.
  157411. **
  157412. ** Argument zParam is passed the value of the "prefix=" option if one was
  157413. ** specified, or NULL otherwise.
  157414. **
  157415. ** If no error occurs, SQLITE_OK is returned and *apIndex set to point to
  157416. ** the allocated array. *pnIndex is set to the number of elements in the
  157417. ** array. If an error does occur, an SQLite error code is returned.
  157418. **
  157419. ** Regardless of whether or not an error is returned, it is the responsibility
  157420. ** of the caller to call sqlite3_free() on the output array to free it.
  157421. */
  157422. static int fts3PrefixParameter(
  157423. const char *zParam, /* ABC in prefix=ABC parameter to parse */
  157424. int *pnIndex, /* OUT: size of *apIndex[] array */
  157425. struct Fts3Index **apIndex /* OUT: Array of indexes for this table */
  157426. ){
  157427. struct Fts3Index *aIndex; /* Allocated array */
  157428. int nIndex = 1; /* Number of entries in array */
  157429. if( zParam && zParam[0] ){
  157430. const char *p;
  157431. nIndex++;
  157432. for(p=zParam; *p; p++){
  157433. if( *p==',' ) nIndex++;
  157434. }
  157435. }
  157436. aIndex = sqlite3_malloc64(sizeof(struct Fts3Index) * nIndex);
  157437. *apIndex = aIndex;
  157438. if( !aIndex ){
  157439. return SQLITE_NOMEM;
  157440. }
  157441. memset(aIndex, 0, sizeof(struct Fts3Index) * nIndex);
  157442. if( zParam ){
  157443. const char *p = zParam;
  157444. int i;
  157445. for(i=1; i<nIndex; i++){
  157446. int nPrefix = 0;
  157447. if( fts3GobbleInt(&p, &nPrefix) ) return SQLITE_ERROR;
  157448. assert( nPrefix>=0 );
  157449. if( nPrefix==0 ){
  157450. nIndex--;
  157451. i--;
  157452. }else{
  157453. aIndex[i].nPrefix = nPrefix;
  157454. }
  157455. p++;
  157456. }
  157457. }
  157458. *pnIndex = nIndex;
  157459. return SQLITE_OK;
  157460. }
  157461. /*
  157462. ** This function is called when initializing an FTS4 table that uses the
  157463. ** content=xxx option. It determines the number of and names of the columns
  157464. ** of the new FTS4 table.
  157465. **
  157466. ** The third argument passed to this function is the value passed to the
  157467. ** config=xxx option (i.e. "xxx"). This function queries the database for
  157468. ** a table of that name. If found, the output variables are populated
  157469. ** as follows:
  157470. **
  157471. ** *pnCol: Set to the number of columns table xxx has,
  157472. **
  157473. ** *pnStr: Set to the total amount of space required to store a copy
  157474. ** of each columns name, including the nul-terminator.
  157475. **
  157476. ** *pazCol: Set to point to an array of *pnCol strings. Each string is
  157477. ** the name of the corresponding column in table xxx. The array
  157478. ** and its contents are allocated using a single allocation. It
  157479. ** is the responsibility of the caller to free this allocation
  157480. ** by eventually passing the *pazCol value to sqlite3_free().
  157481. **
  157482. ** If the table cannot be found, an error code is returned and the output
  157483. ** variables are undefined. Or, if an OOM is encountered, SQLITE_NOMEM is
  157484. ** returned (and the output variables are undefined).
  157485. */
  157486. static int fts3ContentColumns(
  157487. sqlite3 *db, /* Database handle */
  157488. const char *zDb, /* Name of db (i.e. "main", "temp" etc.) */
  157489. const char *zTbl, /* Name of content table */
  157490. const char ***pazCol, /* OUT: Malloc'd array of column names */
  157491. int *pnCol, /* OUT: Size of array *pazCol */
  157492. int *pnStr, /* OUT: Bytes of string content */
  157493. char **pzErr /* OUT: error message */
  157494. ){
  157495. int rc = SQLITE_OK; /* Return code */
  157496. char *zSql; /* "SELECT *" statement on zTbl */
  157497. sqlite3_stmt *pStmt = 0; /* Compiled version of zSql */
  157498. zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", zDb, zTbl);
  157499. if( !zSql ){
  157500. rc = SQLITE_NOMEM;
  157501. }else{
  157502. rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
  157503. if( rc!=SQLITE_OK ){
  157504. sqlite3Fts3ErrMsg(pzErr, "%s", sqlite3_errmsg(db));
  157505. }
  157506. }
  157507. sqlite3_free(zSql);
  157508. if( rc==SQLITE_OK ){
  157509. const char **azCol; /* Output array */
  157510. sqlite3_int64 nStr = 0; /* Size of all column names (incl. 0x00) */
  157511. int nCol; /* Number of table columns */
  157512. int i; /* Used to iterate through columns */
  157513. /* Loop through the returned columns. Set nStr to the number of bytes of
  157514. ** space required to store a copy of each column name, including the
  157515. ** nul-terminator byte. */
  157516. nCol = sqlite3_column_count(pStmt);
  157517. for(i=0; i<nCol; i++){
  157518. const char *zCol = sqlite3_column_name(pStmt, i);
  157519. nStr += strlen(zCol) + 1;
  157520. }
  157521. /* Allocate and populate the array to return. */
  157522. azCol = (const char **)sqlite3_malloc64(sizeof(char *) * nCol + nStr);
  157523. if( azCol==0 ){
  157524. rc = SQLITE_NOMEM;
  157525. }else{
  157526. char *p = (char *)&azCol[nCol];
  157527. for(i=0; i<nCol; i++){
  157528. const char *zCol = sqlite3_column_name(pStmt, i);
  157529. int n = (int)strlen(zCol)+1;
  157530. memcpy(p, zCol, n);
  157531. azCol[i] = p;
  157532. p += n;
  157533. }
  157534. }
  157535. sqlite3_finalize(pStmt);
  157536. /* Set the output variables. */
  157537. *pnCol = nCol;
  157538. *pnStr = nStr;
  157539. *pazCol = azCol;
  157540. }
  157541. return rc;
  157542. }
  157543. /*
  157544. ** This function is the implementation of both the xConnect and xCreate
  157545. ** methods of the FTS3 virtual table.
  157546. **
  157547. ** The argv[] array contains the following:
  157548. **
  157549. ** argv[0] -> module name ("fts3" or "fts4")
  157550. ** argv[1] -> database name
  157551. ** argv[2] -> table name
  157552. ** argv[...] -> "column name" and other module argument fields.
  157553. */
  157554. static int fts3InitVtab(
  157555. int isCreate, /* True for xCreate, false for xConnect */
  157556. sqlite3 *db, /* The SQLite database connection */
  157557. void *pAux, /* Hash table containing tokenizers */
  157558. int argc, /* Number of elements in argv array */
  157559. const char * const *argv, /* xCreate/xConnect argument array */
  157560. sqlite3_vtab **ppVTab, /* Write the resulting vtab structure here */
  157561. char **pzErr /* Write any error message here */
  157562. ){
  157563. Fts3Hash *pHash = (Fts3Hash *)pAux;
  157564. Fts3Table *p = 0; /* Pointer to allocated vtab */
  157565. int rc = SQLITE_OK; /* Return code */
  157566. int i; /* Iterator variable */
  157567. sqlite3_int64 nByte; /* Size of allocation used for *p */
  157568. int iCol; /* Column index */
  157569. int nString = 0; /* Bytes required to hold all column names */
  157570. int nCol = 0; /* Number of columns in the FTS table */
  157571. char *zCsr; /* Space for holding column names */
  157572. int nDb; /* Bytes required to hold database name */
  157573. int nName; /* Bytes required to hold table name */
  157574. int isFts4 = (argv[0][3]=='4'); /* True for FTS4, false for FTS3 */
  157575. const char **aCol; /* Array of column names */
  157576. sqlite3_tokenizer *pTokenizer = 0; /* Tokenizer for this table */
  157577. int nIndex = 0; /* Size of aIndex[] array */
  157578. struct Fts3Index *aIndex = 0; /* Array of indexes for this table */
  157579. /* The results of parsing supported FTS4 key=value options: */
  157580. int bNoDocsize = 0; /* True to omit %_docsize table */
  157581. int bDescIdx = 0; /* True to store descending indexes */
  157582. char *zPrefix = 0; /* Prefix parameter value (or NULL) */
  157583. char *zCompress = 0; /* compress=? parameter (or NULL) */
  157584. char *zUncompress = 0; /* uncompress=? parameter (or NULL) */
  157585. char *zContent = 0; /* content=? parameter (or NULL) */
  157586. char *zLanguageid = 0; /* languageid=? parameter (or NULL) */
  157587. char **azNotindexed = 0; /* The set of notindexed= columns */
  157588. int nNotindexed = 0; /* Size of azNotindexed[] array */
  157589. assert( strlen(argv[0])==4 );
  157590. assert( (sqlite3_strnicmp(argv[0], "fts4", 4)==0 && isFts4)
  157591. || (sqlite3_strnicmp(argv[0], "fts3", 4)==0 && !isFts4)
  157592. );
  157593. nDb = (int)strlen(argv[1]) + 1;
  157594. nName = (int)strlen(argv[2]) + 1;
  157595. nByte = sizeof(const char *) * (argc-2);
  157596. aCol = (const char **)sqlite3_malloc64(nByte);
  157597. if( aCol ){
  157598. memset((void*)aCol, 0, nByte);
  157599. azNotindexed = (char **)sqlite3_malloc64(nByte);
  157600. }
  157601. if( azNotindexed ){
  157602. memset(azNotindexed, 0, nByte);
  157603. }
  157604. if( !aCol || !azNotindexed ){
  157605. rc = SQLITE_NOMEM;
  157606. goto fts3_init_out;
  157607. }
  157608. /* Loop through all of the arguments passed by the user to the FTS3/4
  157609. ** module (i.e. all the column names and special arguments). This loop
  157610. ** does the following:
  157611. **
  157612. ** + Figures out the number of columns the FTSX table will have, and
  157613. ** the number of bytes of space that must be allocated to store copies
  157614. ** of the column names.
  157615. **
  157616. ** + If there is a tokenizer specification included in the arguments,
  157617. ** initializes the tokenizer pTokenizer.
  157618. */
  157619. for(i=3; rc==SQLITE_OK && i<argc; i++){
  157620. char const *z = argv[i];
  157621. int nKey;
  157622. char *zVal;
  157623. /* Check if this is a tokenizer specification */
  157624. if( !pTokenizer
  157625. && strlen(z)>8
  157626. && 0==sqlite3_strnicmp(z, "tokenize", 8)
  157627. && 0==sqlite3Fts3IsIdChar(z[8])
  157628. ){
  157629. rc = sqlite3Fts3InitTokenizer(pHash, &z[9], &pTokenizer, pzErr);
  157630. }
  157631. /* Check if it is an FTS4 special argument. */
  157632. else if( isFts4 && fts3IsSpecialColumn(z, &nKey, &zVal) ){
  157633. struct Fts4Option {
  157634. const char *zOpt;
  157635. int nOpt;
  157636. } aFts4Opt[] = {
  157637. { "matchinfo", 9 }, /* 0 -> MATCHINFO */
  157638. { "prefix", 6 }, /* 1 -> PREFIX */
  157639. { "compress", 8 }, /* 2 -> COMPRESS */
  157640. { "uncompress", 10 }, /* 3 -> UNCOMPRESS */
  157641. { "order", 5 }, /* 4 -> ORDER */
  157642. { "content", 7 }, /* 5 -> CONTENT */
  157643. { "languageid", 10 }, /* 6 -> LANGUAGEID */
  157644. { "notindexed", 10 } /* 7 -> NOTINDEXED */
  157645. };
  157646. int iOpt;
  157647. if( !zVal ){
  157648. rc = SQLITE_NOMEM;
  157649. }else{
  157650. for(iOpt=0; iOpt<SizeofArray(aFts4Opt); iOpt++){
  157651. struct Fts4Option *pOp = &aFts4Opt[iOpt];
  157652. if( nKey==pOp->nOpt && !sqlite3_strnicmp(z, pOp->zOpt, pOp->nOpt) ){
  157653. break;
  157654. }
  157655. }
  157656. switch( iOpt ){
  157657. case 0: /* MATCHINFO */
  157658. if( strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "fts3", 4) ){
  157659. sqlite3Fts3ErrMsg(pzErr, "unrecognized matchinfo: %s", zVal);
  157660. rc = SQLITE_ERROR;
  157661. }
  157662. bNoDocsize = 1;
  157663. break;
  157664. case 1: /* PREFIX */
  157665. sqlite3_free(zPrefix);
  157666. zPrefix = zVal;
  157667. zVal = 0;
  157668. break;
  157669. case 2: /* COMPRESS */
  157670. sqlite3_free(zCompress);
  157671. zCompress = zVal;
  157672. zVal = 0;
  157673. break;
  157674. case 3: /* UNCOMPRESS */
  157675. sqlite3_free(zUncompress);
  157676. zUncompress = zVal;
  157677. zVal = 0;
  157678. break;
  157679. case 4: /* ORDER */
  157680. if( (strlen(zVal)!=3 || sqlite3_strnicmp(zVal, "asc", 3))
  157681. && (strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "desc", 4))
  157682. ){
  157683. sqlite3Fts3ErrMsg(pzErr, "unrecognized order: %s", zVal);
  157684. rc = SQLITE_ERROR;
  157685. }
  157686. bDescIdx = (zVal[0]=='d' || zVal[0]=='D');
  157687. break;
  157688. case 5: /* CONTENT */
  157689. sqlite3_free(zContent);
  157690. zContent = zVal;
  157691. zVal = 0;
  157692. break;
  157693. case 6: /* LANGUAGEID */
  157694. assert( iOpt==6 );
  157695. sqlite3_free(zLanguageid);
  157696. zLanguageid = zVal;
  157697. zVal = 0;
  157698. break;
  157699. case 7: /* NOTINDEXED */
  157700. azNotindexed[nNotindexed++] = zVal;
  157701. zVal = 0;
  157702. break;
  157703. default:
  157704. assert( iOpt==SizeofArray(aFts4Opt) );
  157705. sqlite3Fts3ErrMsg(pzErr, "unrecognized parameter: %s", z);
  157706. rc = SQLITE_ERROR;
  157707. break;
  157708. }
  157709. sqlite3_free(zVal);
  157710. }
  157711. }
  157712. /* Otherwise, the argument is a column name. */
  157713. else {
  157714. nString += (int)(strlen(z) + 1);
  157715. aCol[nCol++] = z;
  157716. }
  157717. }
  157718. /* If a content=xxx option was specified, the following:
  157719. **
  157720. ** 1. Ignore any compress= and uncompress= options.
  157721. **
  157722. ** 2. If no column names were specified as part of the CREATE VIRTUAL
  157723. ** TABLE statement, use all columns from the content table.
  157724. */
  157725. if( rc==SQLITE_OK && zContent ){
  157726. sqlite3_free(zCompress);
  157727. sqlite3_free(zUncompress);
  157728. zCompress = 0;
  157729. zUncompress = 0;
  157730. if( nCol==0 ){
  157731. sqlite3_free((void*)aCol);
  157732. aCol = 0;
  157733. rc = fts3ContentColumns(db, argv[1], zContent,&aCol,&nCol,&nString,pzErr);
  157734. /* If a languageid= option was specified, remove the language id
  157735. ** column from the aCol[] array. */
  157736. if( rc==SQLITE_OK && zLanguageid ){
  157737. int j;
  157738. for(j=0; j<nCol; j++){
  157739. if( sqlite3_stricmp(zLanguageid, aCol[j])==0 ){
  157740. int k;
  157741. for(k=j; k<nCol; k++) aCol[k] = aCol[k+1];
  157742. nCol--;
  157743. break;
  157744. }
  157745. }
  157746. }
  157747. }
  157748. }
  157749. if( rc!=SQLITE_OK ) goto fts3_init_out;
  157750. if( nCol==0 ){
  157751. assert( nString==0 );
  157752. aCol[0] = "content";
  157753. nString = 8;
  157754. nCol = 1;
  157755. }
  157756. if( pTokenizer==0 ){
  157757. rc = sqlite3Fts3InitTokenizer(pHash, "simple", &pTokenizer, pzErr);
  157758. if( rc!=SQLITE_OK ) goto fts3_init_out;
  157759. }
  157760. assert( pTokenizer );
  157761. rc = fts3PrefixParameter(zPrefix, &nIndex, &aIndex);
  157762. if( rc==SQLITE_ERROR ){
  157763. assert( zPrefix );
  157764. sqlite3Fts3ErrMsg(pzErr, "error parsing prefix parameter: %s", zPrefix);
  157765. }
  157766. if( rc!=SQLITE_OK ) goto fts3_init_out;
  157767. /* Allocate and populate the Fts3Table structure. */
  157768. nByte = sizeof(Fts3Table) + /* Fts3Table */
  157769. nCol * sizeof(char *) + /* azColumn */
  157770. nIndex * sizeof(struct Fts3Index) + /* aIndex */
  157771. nCol * sizeof(u8) + /* abNotindexed */
  157772. nName + /* zName */
  157773. nDb + /* zDb */
  157774. nString; /* Space for azColumn strings */
  157775. p = (Fts3Table*)sqlite3_malloc64(nByte);
  157776. if( p==0 ){
  157777. rc = SQLITE_NOMEM;
  157778. goto fts3_init_out;
  157779. }
  157780. memset(p, 0, nByte);
  157781. p->db = db;
  157782. p->nColumn = nCol;
  157783. p->nPendingData = 0;
  157784. p->azColumn = (char **)&p[1];
  157785. p->pTokenizer = pTokenizer;
  157786. p->nMaxPendingData = FTS3_MAX_PENDING_DATA;
  157787. p->bHasDocsize = (isFts4 && bNoDocsize==0);
  157788. p->bHasStat = (u8)isFts4;
  157789. p->bFts4 = (u8)isFts4;
  157790. p->bDescIdx = (u8)bDescIdx;
  157791. p->nAutoincrmerge = 0xff; /* 0xff means setting unknown */
  157792. p->zContentTbl = zContent;
  157793. p->zLanguageid = zLanguageid;
  157794. zContent = 0;
  157795. zLanguageid = 0;
  157796. TESTONLY( p->inTransaction = -1 );
  157797. TESTONLY( p->mxSavepoint = -1 );
  157798. p->aIndex = (struct Fts3Index *)&p->azColumn[nCol];
  157799. memcpy(p->aIndex, aIndex, sizeof(struct Fts3Index) * nIndex);
  157800. p->nIndex = nIndex;
  157801. for(i=0; i<nIndex; i++){
  157802. fts3HashInit(&p->aIndex[i].hPending, FTS3_HASH_STRING, 1);
  157803. }
  157804. p->abNotindexed = (u8 *)&p->aIndex[nIndex];
  157805. /* Fill in the zName and zDb fields of the vtab structure. */
  157806. zCsr = (char *)&p->abNotindexed[nCol];
  157807. p->zName = zCsr;
  157808. memcpy(zCsr, argv[2], nName);
  157809. zCsr += nName;
  157810. p->zDb = zCsr;
  157811. memcpy(zCsr, argv[1], nDb);
  157812. zCsr += nDb;
  157813. /* Fill in the azColumn array */
  157814. for(iCol=0; iCol<nCol; iCol++){
  157815. char *z;
  157816. int n = 0;
  157817. z = (char *)sqlite3Fts3NextToken(aCol[iCol], &n);
  157818. if( n>0 ){
  157819. memcpy(zCsr, z, n);
  157820. }
  157821. zCsr[n] = '\0';
  157822. sqlite3Fts3Dequote(zCsr);
  157823. p->azColumn[iCol] = zCsr;
  157824. zCsr += n+1;
  157825. assert( zCsr <= &((char *)p)[nByte] );
  157826. }
  157827. /* Fill in the abNotindexed array */
  157828. for(iCol=0; iCol<nCol; iCol++){
  157829. int n = (int)strlen(p->azColumn[iCol]);
  157830. for(i=0; i<nNotindexed; i++){
  157831. char *zNot = azNotindexed[i];
  157832. if( zNot && n==(int)strlen(zNot)
  157833. && 0==sqlite3_strnicmp(p->azColumn[iCol], zNot, n)
  157834. ){
  157835. p->abNotindexed[iCol] = 1;
  157836. sqlite3_free(zNot);
  157837. azNotindexed[i] = 0;
  157838. }
  157839. }
  157840. }
  157841. for(i=0; i<nNotindexed; i++){
  157842. if( azNotindexed[i] ){
  157843. sqlite3Fts3ErrMsg(pzErr, "no such column: %s", azNotindexed[i]);
  157844. rc = SQLITE_ERROR;
  157845. }
  157846. }
  157847. if( rc==SQLITE_OK && (zCompress==0)!=(zUncompress==0) ){
  157848. char const *zMiss = (zCompress==0 ? "compress" : "uncompress");
  157849. rc = SQLITE_ERROR;
  157850. sqlite3Fts3ErrMsg(pzErr, "missing %s parameter in fts4 constructor", zMiss);
  157851. }
  157852. p->zReadExprlist = fts3ReadExprList(p, zUncompress, &rc);
  157853. p->zWriteExprlist = fts3WriteExprList(p, zCompress, &rc);
  157854. if( rc!=SQLITE_OK ) goto fts3_init_out;
  157855. /* If this is an xCreate call, create the underlying tables in the
  157856. ** database. TODO: For xConnect(), it could verify that said tables exist.
  157857. */
  157858. if( isCreate ){
  157859. rc = fts3CreateTables(p);
  157860. }
  157861. /* Check to see if a legacy fts3 table has been "upgraded" by the
  157862. ** addition of a %_stat table so that it can use incremental merge.
  157863. */
  157864. if( !isFts4 && !isCreate ){
  157865. p->bHasStat = 2;
  157866. }
  157867. /* Figure out the page-size for the database. This is required in order to
  157868. ** estimate the cost of loading large doclists from the database. */
  157869. fts3DatabasePageSize(&rc, p);
  157870. p->nNodeSize = p->nPgsz-35;
  157871. #if defined(SQLITE_DEBUG)||defined(SQLITE_TEST)
  157872. p->nMergeCount = FTS3_MERGE_COUNT;
  157873. #endif
  157874. /* Declare the table schema to SQLite. */
  157875. fts3DeclareVtab(&rc, p);
  157876. fts3_init_out:
  157877. sqlite3_free(zPrefix);
  157878. sqlite3_free(aIndex);
  157879. sqlite3_free(zCompress);
  157880. sqlite3_free(zUncompress);
  157881. sqlite3_free(zContent);
  157882. sqlite3_free(zLanguageid);
  157883. for(i=0; i<nNotindexed; i++) sqlite3_free(azNotindexed[i]);
  157884. sqlite3_free((void *)aCol);
  157885. sqlite3_free((void *)azNotindexed);
  157886. if( rc!=SQLITE_OK ){
  157887. if( p ){
  157888. fts3DisconnectMethod((sqlite3_vtab *)p);
  157889. }else if( pTokenizer ){
  157890. pTokenizer->pModule->xDestroy(pTokenizer);
  157891. }
  157892. }else{
  157893. assert( p->pSegments==0 );
  157894. *ppVTab = &p->base;
  157895. }
  157896. return rc;
  157897. }
  157898. /*
  157899. ** The xConnect() and xCreate() methods for the virtual table. All the
  157900. ** work is done in function fts3InitVtab().
  157901. */
  157902. static int fts3ConnectMethod(
  157903. sqlite3 *db, /* Database connection */
  157904. void *pAux, /* Pointer to tokenizer hash table */
  157905. int argc, /* Number of elements in argv array */
  157906. const char * const *argv, /* xCreate/xConnect argument array */
  157907. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  157908. char **pzErr /* OUT: sqlite3_malloc'd error message */
  157909. ){
  157910. return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
  157911. }
  157912. static int fts3CreateMethod(
  157913. sqlite3 *db, /* Database connection */
  157914. void *pAux, /* Pointer to tokenizer hash table */
  157915. int argc, /* Number of elements in argv array */
  157916. const char * const *argv, /* xCreate/xConnect argument array */
  157917. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  157918. char **pzErr /* OUT: sqlite3_malloc'd error message */
  157919. ){
  157920. return fts3InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
  157921. }
  157922. /*
  157923. ** Set the pIdxInfo->estimatedRows variable to nRow. Unless this
  157924. ** extension is currently being used by a version of SQLite too old to
  157925. ** support estimatedRows. In that case this function is a no-op.
  157926. */
  157927. static void fts3SetEstimatedRows(sqlite3_index_info *pIdxInfo, i64 nRow){
  157928. #if SQLITE_VERSION_NUMBER>=3008002
  157929. if( sqlite3_libversion_number()>=3008002 ){
  157930. pIdxInfo->estimatedRows = nRow;
  157931. }
  157932. #endif
  157933. }
  157934. /*
  157935. ** Set the SQLITE_INDEX_SCAN_UNIQUE flag in pIdxInfo->flags. Unless this
  157936. ** extension is currently being used by a version of SQLite too old to
  157937. ** support index-info flags. In that case this function is a no-op.
  157938. */
  157939. static void fts3SetUniqueFlag(sqlite3_index_info *pIdxInfo){
  157940. #if SQLITE_VERSION_NUMBER>=3008012
  157941. if( sqlite3_libversion_number()>=3008012 ){
  157942. pIdxInfo->idxFlags |= SQLITE_INDEX_SCAN_UNIQUE;
  157943. }
  157944. #endif
  157945. }
  157946. /*
  157947. ** Implementation of the xBestIndex method for FTS3 tables. There
  157948. ** are three possible strategies, in order of preference:
  157949. **
  157950. ** 1. Direct lookup by rowid or docid.
  157951. ** 2. Full-text search using a MATCH operator on a non-docid column.
  157952. ** 3. Linear scan of %_content table.
  157953. */
  157954. static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
  157955. Fts3Table *p = (Fts3Table *)pVTab;
  157956. int i; /* Iterator variable */
  157957. int iCons = -1; /* Index of constraint to use */
  157958. int iLangidCons = -1; /* Index of langid=x constraint, if present */
  157959. int iDocidGe = -1; /* Index of docid>=x constraint, if present */
  157960. int iDocidLe = -1; /* Index of docid<=x constraint, if present */
  157961. int iIdx;
  157962. if( p->bLock ){
  157963. return SQLITE_ERROR;
  157964. }
  157965. /* By default use a full table scan. This is an expensive option,
  157966. ** so search through the constraints to see if a more efficient
  157967. ** strategy is possible.
  157968. */
  157969. pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
  157970. pInfo->estimatedCost = 5000000;
  157971. for(i=0; i<pInfo->nConstraint; i++){
  157972. int bDocid; /* True if this constraint is on docid */
  157973. struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i];
  157974. if( pCons->usable==0 ){
  157975. if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH ){
  157976. /* There exists an unusable MATCH constraint. This means that if
  157977. ** the planner does elect to use the results of this call as part
  157978. ** of the overall query plan the user will see an "unable to use
  157979. ** function MATCH in the requested context" error. To discourage
  157980. ** this, return a very high cost here. */
  157981. pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
  157982. pInfo->estimatedCost = 1e50;
  157983. fts3SetEstimatedRows(pInfo, ((sqlite3_int64)1) << 50);
  157984. return SQLITE_OK;
  157985. }
  157986. continue;
  157987. }
  157988. bDocid = (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1);
  157989. /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */
  157990. if( iCons<0 && pCons->op==SQLITE_INDEX_CONSTRAINT_EQ && bDocid ){
  157991. pInfo->idxNum = FTS3_DOCID_SEARCH;
  157992. pInfo->estimatedCost = 1.0;
  157993. iCons = i;
  157994. }
  157995. /* A MATCH constraint. Use a full-text search.
  157996. **
  157997. ** If there is more than one MATCH constraint available, use the first
  157998. ** one encountered. If there is both a MATCH constraint and a direct
  157999. ** rowid/docid lookup, prefer the MATCH strategy. This is done even
  158000. ** though the rowid/docid lookup is faster than a MATCH query, selecting
  158001. ** it would lead to an "unable to use function MATCH in the requested
  158002. ** context" error.
  158003. */
  158004. if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH
  158005. && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn
  158006. ){
  158007. pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn;
  158008. pInfo->estimatedCost = 2.0;
  158009. iCons = i;
  158010. }
  158011. /* Equality constraint on the langid column */
  158012. if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ
  158013. && pCons->iColumn==p->nColumn + 2
  158014. ){
  158015. iLangidCons = i;
  158016. }
  158017. if( bDocid ){
  158018. switch( pCons->op ){
  158019. case SQLITE_INDEX_CONSTRAINT_GE:
  158020. case SQLITE_INDEX_CONSTRAINT_GT:
  158021. iDocidGe = i;
  158022. break;
  158023. case SQLITE_INDEX_CONSTRAINT_LE:
  158024. case SQLITE_INDEX_CONSTRAINT_LT:
  158025. iDocidLe = i;
  158026. break;
  158027. }
  158028. }
  158029. }
  158030. /* If using a docid=? or rowid=? strategy, set the UNIQUE flag. */
  158031. if( pInfo->idxNum==FTS3_DOCID_SEARCH ) fts3SetUniqueFlag(pInfo);
  158032. iIdx = 1;
  158033. if( iCons>=0 ){
  158034. pInfo->aConstraintUsage[iCons].argvIndex = iIdx++;
  158035. pInfo->aConstraintUsage[iCons].omit = 1;
  158036. }
  158037. if( iLangidCons>=0 ){
  158038. pInfo->idxNum |= FTS3_HAVE_LANGID;
  158039. pInfo->aConstraintUsage[iLangidCons].argvIndex = iIdx++;
  158040. }
  158041. if( iDocidGe>=0 ){
  158042. pInfo->idxNum |= FTS3_HAVE_DOCID_GE;
  158043. pInfo->aConstraintUsage[iDocidGe].argvIndex = iIdx++;
  158044. }
  158045. if( iDocidLe>=0 ){
  158046. pInfo->idxNum |= FTS3_HAVE_DOCID_LE;
  158047. pInfo->aConstraintUsage[iDocidLe].argvIndex = iIdx++;
  158048. }
  158049. /* Regardless of the strategy selected, FTS can deliver rows in rowid (or
  158050. ** docid) order. Both ascending and descending are possible.
  158051. */
  158052. if( pInfo->nOrderBy==1 ){
  158053. struct sqlite3_index_orderby *pOrder = &pInfo->aOrderBy[0];
  158054. if( pOrder->iColumn<0 || pOrder->iColumn==p->nColumn+1 ){
  158055. if( pOrder->desc ){
  158056. pInfo->idxStr = "DESC";
  158057. }else{
  158058. pInfo->idxStr = "ASC";
  158059. }
  158060. pInfo->orderByConsumed = 1;
  158061. }
  158062. }
  158063. assert( p->pSegments==0 );
  158064. return SQLITE_OK;
  158065. }
  158066. /*
  158067. ** Implementation of xOpen method.
  158068. */
  158069. static int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
  158070. sqlite3_vtab_cursor *pCsr; /* Allocated cursor */
  158071. UNUSED_PARAMETER(pVTab);
  158072. /* Allocate a buffer large enough for an Fts3Cursor structure. If the
  158073. ** allocation succeeds, zero it and return SQLITE_OK. Otherwise,
  158074. ** if the allocation fails, return SQLITE_NOMEM.
  158075. */
  158076. *ppCsr = pCsr = (sqlite3_vtab_cursor *)sqlite3_malloc(sizeof(Fts3Cursor));
  158077. if( !pCsr ){
  158078. return SQLITE_NOMEM;
  158079. }
  158080. memset(pCsr, 0, sizeof(Fts3Cursor));
  158081. return SQLITE_OK;
  158082. }
  158083. /*
  158084. ** Finalize the statement handle at pCsr->pStmt.
  158085. **
  158086. ** Or, if that statement handle is one created by fts3CursorSeekStmt(),
  158087. ** and the Fts3Table.pSeekStmt slot is currently NULL, save the statement
  158088. ** pointer there instead of finalizing it.
  158089. */
  158090. static void fts3CursorFinalizeStmt(Fts3Cursor *pCsr){
  158091. if( pCsr->bSeekStmt ){
  158092. Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
  158093. if( p->pSeekStmt==0 ){
  158094. p->pSeekStmt = pCsr->pStmt;
  158095. sqlite3_reset(pCsr->pStmt);
  158096. pCsr->pStmt = 0;
  158097. }
  158098. pCsr->bSeekStmt = 0;
  158099. }
  158100. sqlite3_finalize(pCsr->pStmt);
  158101. }
  158102. /*
  158103. ** Free all resources currently held by the cursor passed as the only
  158104. ** argument.
  158105. */
  158106. static void fts3ClearCursor(Fts3Cursor *pCsr){
  158107. fts3CursorFinalizeStmt(pCsr);
  158108. sqlite3Fts3FreeDeferredTokens(pCsr);
  158109. sqlite3_free(pCsr->aDoclist);
  158110. sqlite3Fts3MIBufferFree(pCsr->pMIBuffer);
  158111. sqlite3Fts3ExprFree(pCsr->pExpr);
  158112. memset(&(&pCsr->base)[1], 0, sizeof(Fts3Cursor)-sizeof(sqlite3_vtab_cursor));
  158113. }
  158114. /*
  158115. ** Close the cursor. For additional information see the documentation
  158116. ** on the xClose method of the virtual table interface.
  158117. */
  158118. static int fts3CloseMethod(sqlite3_vtab_cursor *pCursor){
  158119. Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
  158120. assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
  158121. fts3ClearCursor(pCsr);
  158122. assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
  158123. sqlite3_free(pCsr);
  158124. return SQLITE_OK;
  158125. }
  158126. /*
  158127. ** If pCsr->pStmt has not been prepared (i.e. if pCsr->pStmt==0), then
  158128. ** compose and prepare an SQL statement of the form:
  158129. **
  158130. ** "SELECT <columns> FROM %_content WHERE rowid = ?"
  158131. **
  158132. ** (or the equivalent for a content=xxx table) and set pCsr->pStmt to
  158133. ** it. If an error occurs, return an SQLite error code.
  158134. */
  158135. static int fts3CursorSeekStmt(Fts3Cursor *pCsr){
  158136. int rc = SQLITE_OK;
  158137. if( pCsr->pStmt==0 ){
  158138. Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
  158139. char *zSql;
  158140. if( p->pSeekStmt ){
  158141. pCsr->pStmt = p->pSeekStmt;
  158142. p->pSeekStmt = 0;
  158143. }else{
  158144. zSql = sqlite3_mprintf("SELECT %s WHERE rowid = ?", p->zReadExprlist);
  158145. if( !zSql ) return SQLITE_NOMEM;
  158146. p->bLock++;
  158147. rc = sqlite3_prepare_v3(
  158148. p->db, zSql,-1,SQLITE_PREPARE_PERSISTENT,&pCsr->pStmt,0
  158149. );
  158150. p->bLock--;
  158151. sqlite3_free(zSql);
  158152. }
  158153. if( rc==SQLITE_OK ) pCsr->bSeekStmt = 1;
  158154. }
  158155. return rc;
  158156. }
  158157. /*
  158158. ** Position the pCsr->pStmt statement so that it is on the row
  158159. ** of the %_content table that contains the last match. Return
  158160. ** SQLITE_OK on success.
  158161. */
  158162. static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){
  158163. int rc = SQLITE_OK;
  158164. if( pCsr->isRequireSeek ){
  158165. rc = fts3CursorSeekStmt(pCsr);
  158166. if( rc==SQLITE_OK ){
  158167. Fts3Table *pTab = (Fts3Table*)pCsr->base.pVtab;
  158168. pTab->bLock++;
  158169. sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId);
  158170. pCsr->isRequireSeek = 0;
  158171. if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){
  158172. pTab->bLock--;
  158173. return SQLITE_OK;
  158174. }else{
  158175. pTab->bLock--;
  158176. rc = sqlite3_reset(pCsr->pStmt);
  158177. if( rc==SQLITE_OK && ((Fts3Table *)pCsr->base.pVtab)->zContentTbl==0 ){
  158178. /* If no row was found and no error has occurred, then the %_content
  158179. ** table is missing a row that is present in the full-text index.
  158180. ** The data structures are corrupt. */
  158181. rc = FTS_CORRUPT_VTAB;
  158182. pCsr->isEof = 1;
  158183. }
  158184. }
  158185. }
  158186. }
  158187. if( rc!=SQLITE_OK && pContext ){
  158188. sqlite3_result_error_code(pContext, rc);
  158189. }
  158190. return rc;
  158191. }
  158192. /*
  158193. ** This function is used to process a single interior node when searching
  158194. ** a b-tree for a term or term prefix. The node data is passed to this
  158195. ** function via the zNode/nNode parameters. The term to search for is
  158196. ** passed in zTerm/nTerm.
  158197. **
  158198. ** If piFirst is not NULL, then this function sets *piFirst to the blockid
  158199. ** of the child node that heads the sub-tree that may contain the term.
  158200. **
  158201. ** If piLast is not NULL, then *piLast is set to the right-most child node
  158202. ** that heads a sub-tree that may contain a term for which zTerm/nTerm is
  158203. ** a prefix.
  158204. **
  158205. ** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.
  158206. */
  158207. static int fts3ScanInteriorNode(
  158208. const char *zTerm, /* Term to select leaves for */
  158209. int nTerm, /* Size of term zTerm in bytes */
  158210. const char *zNode, /* Buffer containing segment interior node */
  158211. int nNode, /* Size of buffer at zNode */
  158212. sqlite3_int64 *piFirst, /* OUT: Selected child node */
  158213. sqlite3_int64 *piLast /* OUT: Selected child node */
  158214. ){
  158215. int rc = SQLITE_OK; /* Return code */
  158216. const char *zCsr = zNode; /* Cursor to iterate through node */
  158217. const char *zEnd = &zCsr[nNode];/* End of interior node buffer */
  158218. char *zBuffer = 0; /* Buffer to load terms into */
  158219. i64 nAlloc = 0; /* Size of allocated buffer */
  158220. int isFirstTerm = 1; /* True when processing first term on page */
  158221. sqlite3_int64 iChild; /* Block id of child node to descend to */
  158222. int nBuffer = 0; /* Total term size */
  158223. /* Skip over the 'height' varint that occurs at the start of every
  158224. ** interior node. Then load the blockid of the left-child of the b-tree
  158225. ** node into variable iChild.
  158226. **
  158227. ** Even if the data structure on disk is corrupted, this (reading two
  158228. ** varints from the buffer) does not risk an overread. If zNode is a
  158229. ** root node, then the buffer comes from a SELECT statement. SQLite does
  158230. ** not make this guarantee explicitly, but in practice there are always
  158231. ** either more than 20 bytes of allocated space following the nNode bytes of
  158232. ** contents, or two zero bytes. Or, if the node is read from the %_segments
  158233. ** table, then there are always 20 bytes of zeroed padding following the
  158234. ** nNode bytes of content (see sqlite3Fts3ReadBlock() for details).
  158235. */
  158236. zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
  158237. zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
  158238. if( zCsr>zEnd ){
  158239. return FTS_CORRUPT_VTAB;
  158240. }
  158241. while( zCsr<zEnd && (piFirst || piLast) ){
  158242. int cmp; /* memcmp() result */
  158243. int nSuffix; /* Size of term suffix */
  158244. int nPrefix = 0; /* Size of term prefix */
  158245. /* Load the next term on the node into zBuffer. Use realloc() to expand
  158246. ** the size of zBuffer if required. */
  158247. if( !isFirstTerm ){
  158248. zCsr += fts3GetVarint32(zCsr, &nPrefix);
  158249. if( nPrefix>nBuffer ){
  158250. rc = FTS_CORRUPT_VTAB;
  158251. goto finish_scan;
  158252. }
  158253. }
  158254. isFirstTerm = 0;
  158255. zCsr += fts3GetVarint32(zCsr, &nSuffix);
  158256. assert( nPrefix>=0 && nSuffix>=0 );
  158257. if( nPrefix>zCsr-zNode || nSuffix>zEnd-zCsr || nSuffix==0 ){
  158258. rc = FTS_CORRUPT_VTAB;
  158259. goto finish_scan;
  158260. }
  158261. if( (i64)nPrefix+nSuffix>nAlloc ){
  158262. char *zNew;
  158263. nAlloc = ((i64)nPrefix+nSuffix) * 2;
  158264. zNew = (char *)sqlite3_realloc64(zBuffer, nAlloc);
  158265. if( !zNew ){
  158266. rc = SQLITE_NOMEM;
  158267. goto finish_scan;
  158268. }
  158269. zBuffer = zNew;
  158270. }
  158271. assert( zBuffer );
  158272. memcpy(&zBuffer[nPrefix], zCsr, nSuffix);
  158273. nBuffer = nPrefix + nSuffix;
  158274. zCsr += nSuffix;
  158275. /* Compare the term we are searching for with the term just loaded from
  158276. ** the interior node. If the specified term is greater than or equal
  158277. ** to the term from the interior node, then all terms on the sub-tree
  158278. ** headed by node iChild are smaller than zTerm. No need to search
  158279. ** iChild.
  158280. **
  158281. ** If the interior node term is larger than the specified term, then
  158282. ** the tree headed by iChild may contain the specified term.
  158283. */
  158284. cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer));
  158285. if( piFirst && (cmp<0 || (cmp==0 && nBuffer>nTerm)) ){
  158286. *piFirst = iChild;
  158287. piFirst = 0;
  158288. }
  158289. if( piLast && cmp<0 ){
  158290. *piLast = iChild;
  158291. piLast = 0;
  158292. }
  158293. iChild++;
  158294. };
  158295. if( piFirst ) *piFirst = iChild;
  158296. if( piLast ) *piLast = iChild;
  158297. finish_scan:
  158298. sqlite3_free(zBuffer);
  158299. return rc;
  158300. }
  158301. /*
  158302. ** The buffer pointed to by argument zNode (size nNode bytes) contains an
  158303. ** interior node of a b-tree segment. The zTerm buffer (size nTerm bytes)
  158304. ** contains a term. This function searches the sub-tree headed by the zNode
  158305. ** node for the range of leaf nodes that may contain the specified term
  158306. ** or terms for which the specified term is a prefix.
  158307. **
  158308. ** If piLeaf is not NULL, then *piLeaf is set to the blockid of the
  158309. ** left-most leaf node in the tree that may contain the specified term.
  158310. ** If piLeaf2 is not NULL, then *piLeaf2 is set to the blockid of the
  158311. ** right-most leaf node that may contain a term for which the specified
  158312. ** term is a prefix.
  158313. **
  158314. ** It is possible that the range of returned leaf nodes does not contain
  158315. ** the specified term or any terms for which it is a prefix. However, if the
  158316. ** segment does contain any such terms, they are stored within the identified
  158317. ** range. Because this function only inspects interior segment nodes (and
  158318. ** never loads leaf nodes into memory), it is not possible to be sure.
  158319. **
  158320. ** If an error occurs, an error code other than SQLITE_OK is returned.
  158321. */
  158322. static int fts3SelectLeaf(
  158323. Fts3Table *p, /* Virtual table handle */
  158324. const char *zTerm, /* Term to select leaves for */
  158325. int nTerm, /* Size of term zTerm in bytes */
  158326. const char *zNode, /* Buffer containing segment interior node */
  158327. int nNode, /* Size of buffer at zNode */
  158328. sqlite3_int64 *piLeaf, /* Selected leaf node */
  158329. sqlite3_int64 *piLeaf2 /* Selected leaf node */
  158330. ){
  158331. int rc = SQLITE_OK; /* Return code */
  158332. int iHeight; /* Height of this node in tree */
  158333. assert( piLeaf || piLeaf2 );
  158334. fts3GetVarint32(zNode, &iHeight);
  158335. rc = fts3ScanInteriorNode(zTerm, nTerm, zNode, nNode, piLeaf, piLeaf2);
  158336. assert_fts3_nc( !piLeaf2 || !piLeaf || rc!=SQLITE_OK || (*piLeaf<=*piLeaf2) );
  158337. if( rc==SQLITE_OK && iHeight>1 ){
  158338. char *zBlob = 0; /* Blob read from %_segments table */
  158339. int nBlob = 0; /* Size of zBlob in bytes */
  158340. if( piLeaf && piLeaf2 && (*piLeaf!=*piLeaf2) ){
  158341. rc = sqlite3Fts3ReadBlock(p, *piLeaf, &zBlob, &nBlob, 0);
  158342. if( rc==SQLITE_OK ){
  158343. rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, 0);
  158344. }
  158345. sqlite3_free(zBlob);
  158346. piLeaf = 0;
  158347. zBlob = 0;
  158348. }
  158349. if( rc==SQLITE_OK ){
  158350. rc = sqlite3Fts3ReadBlock(p, piLeaf?*piLeaf:*piLeaf2, &zBlob, &nBlob, 0);
  158351. }
  158352. if( rc==SQLITE_OK ){
  158353. int iNewHeight = 0;
  158354. fts3GetVarint32(zBlob, &iNewHeight);
  158355. if( iNewHeight>=iHeight ){
  158356. rc = FTS_CORRUPT_VTAB;
  158357. }else{
  158358. rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, piLeaf2);
  158359. }
  158360. }
  158361. sqlite3_free(zBlob);
  158362. }
  158363. return rc;
  158364. }
  158365. /*
  158366. ** This function is used to create delta-encoded serialized lists of FTS3
  158367. ** varints. Each call to this function appends a single varint to a list.
  158368. */
  158369. static void fts3PutDeltaVarint(
  158370. char **pp, /* IN/OUT: Output pointer */
  158371. sqlite3_int64 *piPrev, /* IN/OUT: Previous value written to list */
  158372. sqlite3_int64 iVal /* Write this value to the list */
  158373. ){
  158374. assert( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) );
  158375. *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev);
  158376. *piPrev = iVal;
  158377. }
  158378. /*
  158379. ** When this function is called, *ppPoslist is assumed to point to the
  158380. ** start of a position-list. After it returns, *ppPoslist points to the
  158381. ** first byte after the position-list.
  158382. **
  158383. ** A position list is list of positions (delta encoded) and columns for
  158384. ** a single document record of a doclist. So, in other words, this
  158385. ** routine advances *ppPoslist so that it points to the next docid in
  158386. ** the doclist, or to the first byte past the end of the doclist.
  158387. **
  158388. ** If pp is not NULL, then the contents of the position list are copied
  158389. ** to *pp. *pp is set to point to the first byte past the last byte copied
  158390. ** before this function returns.
  158391. */
  158392. static void fts3PoslistCopy(char **pp, char **ppPoslist){
  158393. char *pEnd = *ppPoslist;
  158394. char c = 0;
  158395. /* The end of a position list is marked by a zero encoded as an FTS3
  158396. ** varint. A single POS_END (0) byte. Except, if the 0 byte is preceded by
  158397. ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail
  158398. ** of some other, multi-byte, value.
  158399. **
  158400. ** The following while-loop moves pEnd to point to the first byte that is not
  158401. ** immediately preceded by a byte with the 0x80 bit set. Then increments
  158402. ** pEnd once more so that it points to the byte immediately following the
  158403. ** last byte in the position-list.
  158404. */
  158405. while( *pEnd | c ){
  158406. c = *pEnd++ & 0x80;
  158407. testcase( c!=0 && (*pEnd)==0 );
  158408. }
  158409. pEnd++; /* Advance past the POS_END terminator byte */
  158410. if( pp ){
  158411. int n = (int)(pEnd - *ppPoslist);
  158412. char *p = *pp;
  158413. memcpy(p, *ppPoslist, n);
  158414. p += n;
  158415. *pp = p;
  158416. }
  158417. *ppPoslist = pEnd;
  158418. }
  158419. /*
  158420. ** When this function is called, *ppPoslist is assumed to point to the
  158421. ** start of a column-list. After it returns, *ppPoslist points to the
  158422. ** to the terminator (POS_COLUMN or POS_END) byte of the column-list.
  158423. **
  158424. ** A column-list is list of delta-encoded positions for a single column
  158425. ** within a single document within a doclist.
  158426. **
  158427. ** The column-list is terminated either by a POS_COLUMN varint (1) or
  158428. ** a POS_END varint (0). This routine leaves *ppPoslist pointing to
  158429. ** the POS_COLUMN or POS_END that terminates the column-list.
  158430. **
  158431. ** If pp is not NULL, then the contents of the column-list are copied
  158432. ** to *pp. *pp is set to point to the first byte past the last byte copied
  158433. ** before this function returns. The POS_COLUMN or POS_END terminator
  158434. ** is not copied into *pp.
  158435. */
  158436. static void fts3ColumnlistCopy(char **pp, char **ppPoslist){
  158437. char *pEnd = *ppPoslist;
  158438. char c = 0;
  158439. /* A column-list is terminated by either a 0x01 or 0x00 byte that is
  158440. ** not part of a multi-byte varint.
  158441. */
  158442. while( 0xFE & (*pEnd | c) ){
  158443. c = *pEnd++ & 0x80;
  158444. testcase( c!=0 && ((*pEnd)&0xfe)==0 );
  158445. }
  158446. if( pp ){
  158447. int n = (int)(pEnd - *ppPoslist);
  158448. char *p = *pp;
  158449. memcpy(p, *ppPoslist, n);
  158450. p += n;
  158451. *pp = p;
  158452. }
  158453. *ppPoslist = pEnd;
  158454. }
  158455. /*
  158456. ** Value used to signify the end of an position-list. This must be
  158457. ** as large or larger than any value that might appear on the
  158458. ** position-list, even a position list that has been corrupted.
  158459. */
  158460. #define POSITION_LIST_END LARGEST_INT64
  158461. /*
  158462. ** This function is used to help parse position-lists. When this function is
  158463. ** called, *pp may point to the start of the next varint in the position-list
  158464. ** being parsed, or it may point to 1 byte past the end of the position-list
  158465. ** (in which case **pp will be a terminator bytes POS_END (0) or
  158466. ** (1)).
  158467. **
  158468. ** If *pp points past the end of the current position-list, set *pi to
  158469. ** POSITION_LIST_END and return. Otherwise, read the next varint from *pp,
  158470. ** increment the current value of *pi by the value read, and set *pp to
  158471. ** point to the next value before returning.
  158472. **
  158473. ** Before calling this routine *pi must be initialized to the value of
  158474. ** the previous position, or zero if we are reading the first position
  158475. ** in the position-list. Because positions are delta-encoded, the value
  158476. ** of the previous position is needed in order to compute the value of
  158477. ** the next position.
  158478. */
  158479. static void fts3ReadNextPos(
  158480. char **pp, /* IN/OUT: Pointer into position-list buffer */
  158481. sqlite3_int64 *pi /* IN/OUT: Value read from position-list */
  158482. ){
  158483. if( (**pp)&0xFE ){
  158484. int iVal;
  158485. *pp += fts3GetVarint32((*pp), &iVal);
  158486. *pi += iVal;
  158487. *pi -= 2;
  158488. }else{
  158489. *pi = POSITION_LIST_END;
  158490. }
  158491. }
  158492. /*
  158493. ** If parameter iCol is not 0, write an POS_COLUMN (1) byte followed by
  158494. ** the value of iCol encoded as a varint to *pp. This will start a new
  158495. ** column list.
  158496. **
  158497. ** Set *pp to point to the byte just after the last byte written before
  158498. ** returning (do not modify it if iCol==0). Return the total number of bytes
  158499. ** written (0 if iCol==0).
  158500. */
  158501. static int fts3PutColNumber(char **pp, int iCol){
  158502. int n = 0; /* Number of bytes written */
  158503. if( iCol ){
  158504. char *p = *pp; /* Output pointer */
  158505. n = 1 + sqlite3Fts3PutVarint(&p[1], iCol);
  158506. *p = 0x01;
  158507. *pp = &p[n];
  158508. }
  158509. return n;
  158510. }
  158511. /*
  158512. ** Compute the union of two position lists. The output written
  158513. ** into *pp contains all positions of both *pp1 and *pp2 in sorted
  158514. ** order and with any duplicates removed. All pointers are
  158515. ** updated appropriately. The caller is responsible for insuring
  158516. ** that there is enough space in *pp to hold the complete output.
  158517. */
  158518. static int fts3PoslistMerge(
  158519. char **pp, /* Output buffer */
  158520. char **pp1, /* Left input list */
  158521. char **pp2 /* Right input list */
  158522. ){
  158523. char *p = *pp;
  158524. char *p1 = *pp1;
  158525. char *p2 = *pp2;
  158526. while( *p1 || *p2 ){
  158527. int iCol1; /* The current column index in pp1 */
  158528. int iCol2; /* The current column index in pp2 */
  158529. if( *p1==POS_COLUMN ){
  158530. fts3GetVarint32(&p1[1], &iCol1);
  158531. if( iCol1==0 ) return FTS_CORRUPT_VTAB;
  158532. }
  158533. else if( *p1==POS_END ) iCol1 = 0x7fffffff;
  158534. else iCol1 = 0;
  158535. if( *p2==POS_COLUMN ){
  158536. fts3GetVarint32(&p2[1], &iCol2);
  158537. if( iCol2==0 ) return FTS_CORRUPT_VTAB;
  158538. }
  158539. else if( *p2==POS_END ) iCol2 = 0x7fffffff;
  158540. else iCol2 = 0;
  158541. if( iCol1==iCol2 ){
  158542. sqlite3_int64 i1 = 0; /* Last position from pp1 */
  158543. sqlite3_int64 i2 = 0; /* Last position from pp2 */
  158544. sqlite3_int64 iPrev = 0;
  158545. int n = fts3PutColNumber(&p, iCol1);
  158546. p1 += n;
  158547. p2 += n;
  158548. /* At this point, both p1 and p2 point to the start of column-lists
  158549. ** for the same column (the column with index iCol1 and iCol2).
  158550. ** A column-list is a list of non-negative delta-encoded varints, each
  158551. ** incremented by 2 before being stored. Each list is terminated by a
  158552. ** POS_END (0) or POS_COLUMN (1). The following block merges the two lists
  158553. ** and writes the results to buffer p. p is left pointing to the byte
  158554. ** after the list written. No terminator (POS_END or POS_COLUMN) is
  158555. ** written to the output.
  158556. */
  158557. fts3GetDeltaVarint(&p1, &i1);
  158558. fts3GetDeltaVarint(&p2, &i2);
  158559. do {
  158560. fts3PutDeltaVarint(&p, &iPrev, (i1<i2) ? i1 : i2);
  158561. iPrev -= 2;
  158562. if( i1==i2 ){
  158563. fts3ReadNextPos(&p1, &i1);
  158564. fts3ReadNextPos(&p2, &i2);
  158565. }else if( i1<i2 ){
  158566. fts3ReadNextPos(&p1, &i1);
  158567. }else{
  158568. fts3ReadNextPos(&p2, &i2);
  158569. }
  158570. }while( i1!=POSITION_LIST_END || i2!=POSITION_LIST_END );
  158571. }else if( iCol1<iCol2 ){
  158572. p1 += fts3PutColNumber(&p, iCol1);
  158573. fts3ColumnlistCopy(&p, &p1);
  158574. }else{
  158575. p2 += fts3PutColNumber(&p, iCol2);
  158576. fts3ColumnlistCopy(&p, &p2);
  158577. }
  158578. }
  158579. *p++ = POS_END;
  158580. *pp = p;
  158581. *pp1 = p1 + 1;
  158582. *pp2 = p2 + 1;
  158583. return SQLITE_OK;
  158584. }
  158585. /*
  158586. ** This function is used to merge two position lists into one. When it is
  158587. ** called, *pp1 and *pp2 must both point to position lists. A position-list is
  158588. ** the part of a doclist that follows each document id. For example, if a row
  158589. ** contains:
  158590. **
  158591. ** 'a b c'|'x y z'|'a b b a'
  158592. **
  158593. ** Then the position list for this row for token 'b' would consist of:
  158594. **
  158595. ** 0x02 0x01 0x02 0x03 0x03 0x00
  158596. **
  158597. ** When this function returns, both *pp1 and *pp2 are left pointing to the
  158598. ** byte following the 0x00 terminator of their respective position lists.
  158599. **
  158600. ** If isSaveLeft is 0, an entry is added to the output position list for
  158601. ** each position in *pp2 for which there exists one or more positions in
  158602. ** *pp1 so that (pos(*pp2)>pos(*pp1) && pos(*pp2)-pos(*pp1)<=nToken). i.e.
  158603. ** when the *pp1 token appears before the *pp2 token, but not more than nToken
  158604. ** slots before it.
  158605. **
  158606. ** e.g. nToken==1 searches for adjacent positions.
  158607. */
  158608. static int fts3PoslistPhraseMerge(
  158609. char **pp, /* IN/OUT: Preallocated output buffer */
  158610. int nToken, /* Maximum difference in token positions */
  158611. int isSaveLeft, /* Save the left position */
  158612. int isExact, /* If *pp1 is exactly nTokens before *pp2 */
  158613. char **pp1, /* IN/OUT: Left input list */
  158614. char **pp2 /* IN/OUT: Right input list */
  158615. ){
  158616. char *p = *pp;
  158617. char *p1 = *pp1;
  158618. char *p2 = *pp2;
  158619. int iCol1 = 0;
  158620. int iCol2 = 0;
  158621. /* Never set both isSaveLeft and isExact for the same invocation. */
  158622. assert( isSaveLeft==0 || isExact==0 );
  158623. assert( p!=0 && *p1!=0 && *p2!=0 );
  158624. if( *p1==POS_COLUMN ){
  158625. p1++;
  158626. p1 += fts3GetVarint32(p1, &iCol1);
  158627. }
  158628. if( *p2==POS_COLUMN ){
  158629. p2++;
  158630. p2 += fts3GetVarint32(p2, &iCol2);
  158631. }
  158632. while( 1 ){
  158633. if( iCol1==iCol2 ){
  158634. char *pSave = p;
  158635. sqlite3_int64 iPrev = 0;
  158636. sqlite3_int64 iPos1 = 0;
  158637. sqlite3_int64 iPos2 = 0;
  158638. if( iCol1 ){
  158639. *p++ = POS_COLUMN;
  158640. p += sqlite3Fts3PutVarint(p, iCol1);
  158641. }
  158642. fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
  158643. fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
  158644. if( iPos1<0 || iPos2<0 ) break;
  158645. while( 1 ){
  158646. if( iPos2==iPos1+nToken
  158647. || (isExact==0 && iPos2>iPos1 && iPos2<=iPos1+nToken)
  158648. ){
  158649. sqlite3_int64 iSave;
  158650. iSave = isSaveLeft ? iPos1 : iPos2;
  158651. fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2;
  158652. pSave = 0;
  158653. assert( p );
  158654. }
  158655. if( (!isSaveLeft && iPos2<=(iPos1+nToken)) || iPos2<=iPos1 ){
  158656. if( (*p2&0xFE)==0 ) break;
  158657. fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
  158658. }else{
  158659. if( (*p1&0xFE)==0 ) break;
  158660. fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
  158661. }
  158662. }
  158663. if( pSave ){
  158664. assert( pp && p );
  158665. p = pSave;
  158666. }
  158667. fts3ColumnlistCopy(0, &p1);
  158668. fts3ColumnlistCopy(0, &p2);
  158669. assert( (*p1&0xFE)==0 && (*p2&0xFE)==0 );
  158670. if( 0==*p1 || 0==*p2 ) break;
  158671. p1++;
  158672. p1 += fts3GetVarint32(p1, &iCol1);
  158673. p2++;
  158674. p2 += fts3GetVarint32(p2, &iCol2);
  158675. }
  158676. /* Advance pointer p1 or p2 (whichever corresponds to the smaller of
  158677. ** iCol1 and iCol2) so that it points to either the 0x00 that marks the
  158678. ** end of the position list, or the 0x01 that precedes the next
  158679. ** column-number in the position list.
  158680. */
  158681. else if( iCol1<iCol2 ){
  158682. fts3ColumnlistCopy(0, &p1);
  158683. if( 0==*p1 ) break;
  158684. p1++;
  158685. p1 += fts3GetVarint32(p1, &iCol1);
  158686. }else{
  158687. fts3ColumnlistCopy(0, &p2);
  158688. if( 0==*p2 ) break;
  158689. p2++;
  158690. p2 += fts3GetVarint32(p2, &iCol2);
  158691. }
  158692. }
  158693. fts3PoslistCopy(0, &p2);
  158694. fts3PoslistCopy(0, &p1);
  158695. *pp1 = p1;
  158696. *pp2 = p2;
  158697. if( *pp==p ){
  158698. return 0;
  158699. }
  158700. *p++ = 0x00;
  158701. *pp = p;
  158702. return 1;
  158703. }
  158704. /*
  158705. ** Merge two position-lists as required by the NEAR operator. The argument
  158706. ** position lists correspond to the left and right phrases of an expression
  158707. ** like:
  158708. **
  158709. ** "phrase 1" NEAR "phrase number 2"
  158710. **
  158711. ** Position list *pp1 corresponds to the left-hand side of the NEAR
  158712. ** expression and *pp2 to the right. As usual, the indexes in the position
  158713. ** lists are the offsets of the last token in each phrase (tokens "1" and "2"
  158714. ** in the example above).
  158715. **
  158716. ** The output position list - written to *pp - is a copy of *pp2 with those
  158717. ** entries that are not sufficiently NEAR entries in *pp1 removed.
  158718. */
  158719. static int fts3PoslistNearMerge(
  158720. char **pp, /* Output buffer */
  158721. char *aTmp, /* Temporary buffer space */
  158722. int nRight, /* Maximum difference in token positions */
  158723. int nLeft, /* Maximum difference in token positions */
  158724. char **pp1, /* IN/OUT: Left input list */
  158725. char **pp2 /* IN/OUT: Right input list */
  158726. ){
  158727. char *p1 = *pp1;
  158728. char *p2 = *pp2;
  158729. char *pTmp1 = aTmp;
  158730. char *pTmp2;
  158731. char *aTmp2;
  158732. int res = 1;
  158733. fts3PoslistPhraseMerge(&pTmp1, nRight, 0, 0, pp1, pp2);
  158734. aTmp2 = pTmp2 = pTmp1;
  158735. *pp1 = p1;
  158736. *pp2 = p2;
  158737. fts3PoslistPhraseMerge(&pTmp2, nLeft, 1, 0, pp2, pp1);
  158738. if( pTmp1!=aTmp && pTmp2!=aTmp2 ){
  158739. fts3PoslistMerge(pp, &aTmp, &aTmp2);
  158740. }else if( pTmp1!=aTmp ){
  158741. fts3PoslistCopy(pp, &aTmp);
  158742. }else if( pTmp2!=aTmp2 ){
  158743. fts3PoslistCopy(pp, &aTmp2);
  158744. }else{
  158745. res = 0;
  158746. }
  158747. return res;
  158748. }
  158749. /*
  158750. ** An instance of this function is used to merge together the (potentially
  158751. ** large number of) doclists for each term that matches a prefix query.
  158752. ** See function fts3TermSelectMerge() for details.
  158753. */
  158754. typedef struct TermSelect TermSelect;
  158755. struct TermSelect {
  158756. char *aaOutput[16]; /* Malloc'd output buffers */
  158757. int anOutput[16]; /* Size each output buffer in bytes */
  158758. };
  158759. /*
  158760. ** This function is used to read a single varint from a buffer. Parameter
  158761. ** pEnd points 1 byte past the end of the buffer. When this function is
  158762. ** called, if *pp points to pEnd or greater, then the end of the buffer
  158763. ** has been reached. In this case *pp is set to 0 and the function returns.
  158764. **
  158765. ** If *pp does not point to or past pEnd, then a single varint is read
  158766. ** from *pp. *pp is then set to point 1 byte past the end of the read varint.
  158767. **
  158768. ** If bDescIdx is false, the value read is added to *pVal before returning.
  158769. ** If it is true, the value read is subtracted from *pVal before this
  158770. ** function returns.
  158771. */
  158772. static void fts3GetDeltaVarint3(
  158773. char **pp, /* IN/OUT: Point to read varint from */
  158774. char *pEnd, /* End of buffer */
  158775. int bDescIdx, /* True if docids are descending */
  158776. sqlite3_int64 *pVal /* IN/OUT: Integer value */
  158777. ){
  158778. if( *pp>=pEnd ){
  158779. *pp = 0;
  158780. }else{
  158781. u64 iVal;
  158782. *pp += sqlite3Fts3GetVarintU(*pp, &iVal);
  158783. if( bDescIdx ){
  158784. *pVal = (i64)((u64)*pVal - iVal);
  158785. }else{
  158786. *pVal = (i64)((u64)*pVal + iVal);
  158787. }
  158788. }
  158789. }
  158790. /*
  158791. ** This function is used to write a single varint to a buffer. The varint
  158792. ** is written to *pp. Before returning, *pp is set to point 1 byte past the
  158793. ** end of the value written.
  158794. **
  158795. ** If *pbFirst is zero when this function is called, the value written to
  158796. ** the buffer is that of parameter iVal.
  158797. **
  158798. ** If *pbFirst is non-zero when this function is called, then the value
  158799. ** written is either (iVal-*piPrev) (if bDescIdx is zero) or (*piPrev-iVal)
  158800. ** (if bDescIdx is non-zero).
  158801. **
  158802. ** Before returning, this function always sets *pbFirst to 1 and *piPrev
  158803. ** to the value of parameter iVal.
  158804. */
  158805. static void fts3PutDeltaVarint3(
  158806. char **pp, /* IN/OUT: Output pointer */
  158807. int bDescIdx, /* True for descending docids */
  158808. sqlite3_int64 *piPrev, /* IN/OUT: Previous value written to list */
  158809. int *pbFirst, /* IN/OUT: True after first int written */
  158810. sqlite3_int64 iVal /* Write this value to the list */
  158811. ){
  158812. sqlite3_uint64 iWrite;
  158813. if( bDescIdx==0 || *pbFirst==0 ){
  158814. assert_fts3_nc( *pbFirst==0 || iVal>=*piPrev );
  158815. iWrite = (u64)iVal - (u64)*piPrev;
  158816. }else{
  158817. assert_fts3_nc( *piPrev>=iVal );
  158818. iWrite = (u64)*piPrev - (u64)iVal;
  158819. }
  158820. assert( *pbFirst || *piPrev==0 );
  158821. assert_fts3_nc( *pbFirst==0 || iWrite>0 );
  158822. *pp += sqlite3Fts3PutVarint(*pp, iWrite);
  158823. *piPrev = iVal;
  158824. *pbFirst = 1;
  158825. }
  158826. /*
  158827. ** This macro is used by various functions that merge doclists. The two
  158828. ** arguments are 64-bit docid values. If the value of the stack variable
  158829. ** bDescDoclist is 0 when this macro is invoked, then it returns (i1-i2).
  158830. ** Otherwise, (i2-i1).
  158831. **
  158832. ** Using this makes it easier to write code that can merge doclists that are
  158833. ** sorted in either ascending or descending order.
  158834. */
  158835. /* #define DOCID_CMP(i1, i2) ((bDescDoclist?-1:1) * (i64)((u64)i1-i2)) */
  158836. #define DOCID_CMP(i1, i2) ((bDescDoclist?-1:1) * (i1>i2?1:((i1==i2)?0:-1)))
  158837. /*
  158838. ** This function does an "OR" merge of two doclists (output contains all
  158839. ** positions contained in either argument doclist). If the docids in the
  158840. ** input doclists are sorted in ascending order, parameter bDescDoclist
  158841. ** should be false. If they are sorted in ascending order, it should be
  158842. ** passed a non-zero value.
  158843. **
  158844. ** If no error occurs, *paOut is set to point at an sqlite3_malloc'd buffer
  158845. ** containing the output doclist and SQLITE_OK is returned. In this case
  158846. ** *pnOut is set to the number of bytes in the output doclist.
  158847. **
  158848. ** If an error occurs, an SQLite error code is returned. The output values
  158849. ** are undefined in this case.
  158850. */
  158851. static int fts3DoclistOrMerge(
  158852. int bDescDoclist, /* True if arguments are desc */
  158853. char *a1, int n1, /* First doclist */
  158854. char *a2, int n2, /* Second doclist */
  158855. char **paOut, int *pnOut /* OUT: Malloc'd doclist */
  158856. ){
  158857. int rc = SQLITE_OK;
  158858. sqlite3_int64 i1 = 0;
  158859. sqlite3_int64 i2 = 0;
  158860. sqlite3_int64 iPrev = 0;
  158861. char *pEnd1 = &a1[n1];
  158862. char *pEnd2 = &a2[n2];
  158863. char *p1 = a1;
  158864. char *p2 = a2;
  158865. char *p;
  158866. char *aOut;
  158867. int bFirstOut = 0;
  158868. *paOut = 0;
  158869. *pnOut = 0;
  158870. /* Allocate space for the output. Both the input and output doclists
  158871. ** are delta encoded. If they are in ascending order (bDescDoclist==0),
  158872. ** then the first docid in each list is simply encoded as a varint. For
  158873. ** each subsequent docid, the varint stored is the difference between the
  158874. ** current and previous docid (a positive number - since the list is in
  158875. ** ascending order).
  158876. **
  158877. ** The first docid written to the output is therefore encoded using the
  158878. ** same number of bytes as it is in whichever of the input lists it is
  158879. ** read from. And each subsequent docid read from the same input list
  158880. ** consumes either the same or less bytes as it did in the input (since
  158881. ** the difference between it and the previous value in the output must
  158882. ** be a positive value less than or equal to the delta value read from
  158883. ** the input list). The same argument applies to all but the first docid
  158884. ** read from the 'other' list. And to the contents of all position lists
  158885. ** that will be copied and merged from the input to the output.
  158886. **
  158887. ** However, if the first docid copied to the output is a negative number,
  158888. ** then the encoding of the first docid from the 'other' input list may
  158889. ** be larger in the output than it was in the input (since the delta value
  158890. ** may be a larger positive integer than the actual docid).
  158891. **
  158892. ** The space required to store the output is therefore the sum of the
  158893. ** sizes of the two inputs, plus enough space for exactly one of the input
  158894. ** docids to grow.
  158895. **
  158896. ** A symetric argument may be made if the doclists are in descending
  158897. ** order.
  158898. */
  158899. aOut = sqlite3_malloc64((i64)n1+n2+FTS3_VARINT_MAX-1+FTS3_BUFFER_PADDING);
  158900. if( !aOut ) return SQLITE_NOMEM;
  158901. p = aOut;
  158902. fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
  158903. fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
  158904. while( p1 || p2 ){
  158905. sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
  158906. if( p2 && p1 && iDiff==0 ){
  158907. fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
  158908. rc = fts3PoslistMerge(&p, &p1, &p2);
  158909. if( rc ) break;
  158910. fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
  158911. fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
  158912. }else if( !p2 || (p1 && iDiff<0) ){
  158913. fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
  158914. fts3PoslistCopy(&p, &p1);
  158915. fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
  158916. }else{
  158917. fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i2);
  158918. fts3PoslistCopy(&p, &p2);
  158919. fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
  158920. }
  158921. assert( (p-aOut)<=((p1?(p1-a1):n1)+(p2?(p2-a2):n2)+FTS3_VARINT_MAX-1) );
  158922. }
  158923. if( rc!=SQLITE_OK ){
  158924. sqlite3_free(aOut);
  158925. p = aOut = 0;
  158926. }else{
  158927. assert( (p-aOut)<=n1+n2+FTS3_VARINT_MAX-1 );
  158928. memset(&aOut[(p-aOut)], 0, FTS3_BUFFER_PADDING);
  158929. }
  158930. *paOut = aOut;
  158931. *pnOut = (int)(p-aOut);
  158932. return rc;
  158933. }
  158934. /*
  158935. ** This function does a "phrase" merge of two doclists. In a phrase merge,
  158936. ** the output contains a copy of each position from the right-hand input
  158937. ** doclist for which there is a position in the left-hand input doclist
  158938. ** exactly nDist tokens before it.
  158939. **
  158940. ** If the docids in the input doclists are sorted in ascending order,
  158941. ** parameter bDescDoclist should be false. If they are sorted in ascending
  158942. ** order, it should be passed a non-zero value.
  158943. **
  158944. ** The right-hand input doclist is overwritten by this function.
  158945. */
  158946. static int fts3DoclistPhraseMerge(
  158947. int bDescDoclist, /* True if arguments are desc */
  158948. int nDist, /* Distance from left to right (1=adjacent) */
  158949. char *aLeft, int nLeft, /* Left doclist */
  158950. char **paRight, int *pnRight /* IN/OUT: Right/output doclist */
  158951. ){
  158952. sqlite3_int64 i1 = 0;
  158953. sqlite3_int64 i2 = 0;
  158954. sqlite3_int64 iPrev = 0;
  158955. char *aRight = *paRight;
  158956. char *pEnd1 = &aLeft[nLeft];
  158957. char *pEnd2 = &aRight[*pnRight];
  158958. char *p1 = aLeft;
  158959. char *p2 = aRight;
  158960. char *p;
  158961. int bFirstOut = 0;
  158962. char *aOut;
  158963. assert( nDist>0 );
  158964. if( bDescDoclist ){
  158965. aOut = sqlite3_malloc64((sqlite3_int64)*pnRight + FTS3_VARINT_MAX);
  158966. if( aOut==0 ) return SQLITE_NOMEM;
  158967. }else{
  158968. aOut = aRight;
  158969. }
  158970. p = aOut;
  158971. fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
  158972. fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
  158973. while( p1 && p2 ){
  158974. sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
  158975. if( iDiff==0 ){
  158976. char *pSave = p;
  158977. sqlite3_int64 iPrevSave = iPrev;
  158978. int bFirstOutSave = bFirstOut;
  158979. fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
  158980. if( 0==fts3PoslistPhraseMerge(&p, nDist, 0, 1, &p1, &p2) ){
  158981. p = pSave;
  158982. iPrev = iPrevSave;
  158983. bFirstOut = bFirstOutSave;
  158984. }
  158985. fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
  158986. fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
  158987. }else if( iDiff<0 ){
  158988. fts3PoslistCopy(0, &p1);
  158989. fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
  158990. }else{
  158991. fts3PoslistCopy(0, &p2);
  158992. fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
  158993. }
  158994. }
  158995. *pnRight = (int)(p - aOut);
  158996. if( bDescDoclist ){
  158997. sqlite3_free(aRight);
  158998. *paRight = aOut;
  158999. }
  159000. return SQLITE_OK;
  159001. }
  159002. /*
  159003. ** Argument pList points to a position list nList bytes in size. This
  159004. ** function checks to see if the position list contains any entries for
  159005. ** a token in position 0 (of any column). If so, it writes argument iDelta
  159006. ** to the output buffer pOut, followed by a position list consisting only
  159007. ** of the entries from pList at position 0, and terminated by an 0x00 byte.
  159008. ** The value returned is the number of bytes written to pOut (if any).
  159009. */
  159010. SQLITE_PRIVATE int sqlite3Fts3FirstFilter(
  159011. sqlite3_int64 iDelta, /* Varint that may be written to pOut */
  159012. char *pList, /* Position list (no 0x00 term) */
  159013. int nList, /* Size of pList in bytes */
  159014. char *pOut /* Write output here */
  159015. ){
  159016. int nOut = 0;
  159017. int bWritten = 0; /* True once iDelta has been written */
  159018. char *p = pList;
  159019. char *pEnd = &pList[nList];
  159020. if( *p!=0x01 ){
  159021. if( *p==0x02 ){
  159022. nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
  159023. pOut[nOut++] = 0x02;
  159024. bWritten = 1;
  159025. }
  159026. fts3ColumnlistCopy(0, &p);
  159027. }
  159028. while( p<pEnd ){
  159029. sqlite3_int64 iCol;
  159030. p++;
  159031. p += sqlite3Fts3GetVarint(p, &iCol);
  159032. if( *p==0x02 ){
  159033. if( bWritten==0 ){
  159034. nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
  159035. bWritten = 1;
  159036. }
  159037. pOut[nOut++] = 0x01;
  159038. nOut += sqlite3Fts3PutVarint(&pOut[nOut], iCol);
  159039. pOut[nOut++] = 0x02;
  159040. }
  159041. fts3ColumnlistCopy(0, &p);
  159042. }
  159043. if( bWritten ){
  159044. pOut[nOut++] = 0x00;
  159045. }
  159046. return nOut;
  159047. }
  159048. /*
  159049. ** Merge all doclists in the TermSelect.aaOutput[] array into a single
  159050. ** doclist stored in TermSelect.aaOutput[0]. If successful, delete all
  159051. ** other doclists (except the aaOutput[0] one) and return SQLITE_OK.
  159052. **
  159053. ** If an OOM error occurs, return SQLITE_NOMEM. In this case it is
  159054. ** the responsibility of the caller to free any doclists left in the
  159055. ** TermSelect.aaOutput[] array.
  159056. */
  159057. static int fts3TermSelectFinishMerge(Fts3Table *p, TermSelect *pTS){
  159058. char *aOut = 0;
  159059. int nOut = 0;
  159060. int i;
  159061. /* Loop through the doclists in the aaOutput[] array. Merge them all
  159062. ** into a single doclist.
  159063. */
  159064. for(i=0; i<SizeofArray(pTS->aaOutput); i++){
  159065. if( pTS->aaOutput[i] ){
  159066. if( !aOut ){
  159067. aOut = pTS->aaOutput[i];
  159068. nOut = pTS->anOutput[i];
  159069. pTS->aaOutput[i] = 0;
  159070. }else{
  159071. int nNew;
  159072. char *aNew;
  159073. int rc = fts3DoclistOrMerge(p->bDescIdx,
  159074. pTS->aaOutput[i], pTS->anOutput[i], aOut, nOut, &aNew, &nNew
  159075. );
  159076. if( rc!=SQLITE_OK ){
  159077. sqlite3_free(aOut);
  159078. return rc;
  159079. }
  159080. sqlite3_free(pTS->aaOutput[i]);
  159081. sqlite3_free(aOut);
  159082. pTS->aaOutput[i] = 0;
  159083. aOut = aNew;
  159084. nOut = nNew;
  159085. }
  159086. }
  159087. }
  159088. pTS->aaOutput[0] = aOut;
  159089. pTS->anOutput[0] = nOut;
  159090. return SQLITE_OK;
  159091. }
  159092. /*
  159093. ** Merge the doclist aDoclist/nDoclist into the TermSelect object passed
  159094. ** as the first argument. The merge is an "OR" merge (see function
  159095. ** fts3DoclistOrMerge() for details).
  159096. **
  159097. ** This function is called with the doclist for each term that matches
  159098. ** a queried prefix. It merges all these doclists into one, the doclist
  159099. ** for the specified prefix. Since there can be a very large number of
  159100. ** doclists to merge, the merging is done pair-wise using the TermSelect
  159101. ** object.
  159102. **
  159103. ** This function returns SQLITE_OK if the merge is successful, or an
  159104. ** SQLite error code (SQLITE_NOMEM) if an error occurs.
  159105. */
  159106. static int fts3TermSelectMerge(
  159107. Fts3Table *p, /* FTS table handle */
  159108. TermSelect *pTS, /* TermSelect object to merge into */
  159109. char *aDoclist, /* Pointer to doclist */
  159110. int nDoclist /* Size of aDoclist in bytes */
  159111. ){
  159112. if( pTS->aaOutput[0]==0 ){
  159113. /* If this is the first term selected, copy the doclist to the output
  159114. ** buffer using memcpy().
  159115. **
  159116. ** Add FTS3_VARINT_MAX bytes of unused space to the end of the
  159117. ** allocation. This is so as to ensure that the buffer is big enough
  159118. ** to hold the current doclist AND'd with any other doclist. If the
  159119. ** doclists are stored in order=ASC order, this padding would not be
  159120. ** required (since the size of [doclistA AND doclistB] is always less
  159121. ** than or equal to the size of [doclistA] in that case). But this is
  159122. ** not true for order=DESC. For example, a doclist containing (1, -1)
  159123. ** may be smaller than (-1), as in the first example the -1 may be stored
  159124. ** as a single-byte delta, whereas in the second it must be stored as a
  159125. ** FTS3_VARINT_MAX byte varint.
  159126. **
  159127. ** Similar padding is added in the fts3DoclistOrMerge() function.
  159128. */
  159129. pTS->aaOutput[0] = sqlite3_malloc(nDoclist + FTS3_VARINT_MAX + 1);
  159130. pTS->anOutput[0] = nDoclist;
  159131. if( pTS->aaOutput[0] ){
  159132. memcpy(pTS->aaOutput[0], aDoclist, nDoclist);
  159133. memset(&pTS->aaOutput[0][nDoclist], 0, FTS3_VARINT_MAX);
  159134. }else{
  159135. return SQLITE_NOMEM;
  159136. }
  159137. }else{
  159138. char *aMerge = aDoclist;
  159139. int nMerge = nDoclist;
  159140. int iOut;
  159141. for(iOut=0; iOut<SizeofArray(pTS->aaOutput); iOut++){
  159142. if( pTS->aaOutput[iOut]==0 ){
  159143. assert( iOut>0 );
  159144. pTS->aaOutput[iOut] = aMerge;
  159145. pTS->anOutput[iOut] = nMerge;
  159146. break;
  159147. }else{
  159148. char *aNew;
  159149. int nNew;
  159150. int rc = fts3DoclistOrMerge(p->bDescIdx, aMerge, nMerge,
  159151. pTS->aaOutput[iOut], pTS->anOutput[iOut], &aNew, &nNew
  159152. );
  159153. if( rc!=SQLITE_OK ){
  159154. if( aMerge!=aDoclist ) sqlite3_free(aMerge);
  159155. return rc;
  159156. }
  159157. if( aMerge!=aDoclist ) sqlite3_free(aMerge);
  159158. sqlite3_free(pTS->aaOutput[iOut]);
  159159. pTS->aaOutput[iOut] = 0;
  159160. aMerge = aNew;
  159161. nMerge = nNew;
  159162. if( (iOut+1)==SizeofArray(pTS->aaOutput) ){
  159163. pTS->aaOutput[iOut] = aMerge;
  159164. pTS->anOutput[iOut] = nMerge;
  159165. }
  159166. }
  159167. }
  159168. }
  159169. return SQLITE_OK;
  159170. }
  159171. /*
  159172. ** Append SegReader object pNew to the end of the pCsr->apSegment[] array.
  159173. */
  159174. static int fts3SegReaderCursorAppend(
  159175. Fts3MultiSegReader *pCsr,
  159176. Fts3SegReader *pNew
  159177. ){
  159178. if( (pCsr->nSegment%16)==0 ){
  159179. Fts3SegReader **apNew;
  159180. sqlite3_int64 nByte = (pCsr->nSegment + 16)*sizeof(Fts3SegReader*);
  159181. apNew = (Fts3SegReader **)sqlite3_realloc64(pCsr->apSegment, nByte);
  159182. if( !apNew ){
  159183. sqlite3Fts3SegReaderFree(pNew);
  159184. return SQLITE_NOMEM;
  159185. }
  159186. pCsr->apSegment = apNew;
  159187. }
  159188. pCsr->apSegment[pCsr->nSegment++] = pNew;
  159189. return SQLITE_OK;
  159190. }
  159191. /*
  159192. ** Add seg-reader objects to the Fts3MultiSegReader object passed as the
  159193. ** 8th argument.
  159194. **
  159195. ** This function returns SQLITE_OK if successful, or an SQLite error code
  159196. ** otherwise.
  159197. */
  159198. static int fts3SegReaderCursor(
  159199. Fts3Table *p, /* FTS3 table handle */
  159200. int iLangid, /* Language id */
  159201. int iIndex, /* Index to search (from 0 to p->nIndex-1) */
  159202. int iLevel, /* Level of segments to scan */
  159203. const char *zTerm, /* Term to query for */
  159204. int nTerm, /* Size of zTerm in bytes */
  159205. int isPrefix, /* True for a prefix search */
  159206. int isScan, /* True to scan from zTerm to EOF */
  159207. Fts3MultiSegReader *pCsr /* Cursor object to populate */
  159208. ){
  159209. int rc = SQLITE_OK; /* Error code */
  159210. sqlite3_stmt *pStmt = 0; /* Statement to iterate through segments */
  159211. int rc2; /* Result of sqlite3_reset() */
  159212. /* If iLevel is less than 0 and this is not a scan, include a seg-reader
  159213. ** for the pending-terms. If this is a scan, then this call must be being
  159214. ** made by an fts4aux module, not an FTS table. In this case calling
  159215. ** Fts3SegReaderPending might segfault, as the data structures used by
  159216. ** fts4aux are not completely populated. So it's easiest to filter these
  159217. ** calls out here. */
  159218. if( iLevel<0 && p->aIndex && p->iPrevLangid==iLangid ){
  159219. Fts3SegReader *pSeg = 0;
  159220. rc = sqlite3Fts3SegReaderPending(p, iIndex, zTerm, nTerm, isPrefix||isScan, &pSeg);
  159221. if( rc==SQLITE_OK && pSeg ){
  159222. rc = fts3SegReaderCursorAppend(pCsr, pSeg);
  159223. }
  159224. }
  159225. if( iLevel!=FTS3_SEGCURSOR_PENDING ){
  159226. if( rc==SQLITE_OK ){
  159227. rc = sqlite3Fts3AllSegdirs(p, iLangid, iIndex, iLevel, &pStmt);
  159228. }
  159229. while( rc==SQLITE_OK && SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
  159230. Fts3SegReader *pSeg = 0;
  159231. /* Read the values returned by the SELECT into local variables. */
  159232. sqlite3_int64 iStartBlock = sqlite3_column_int64(pStmt, 1);
  159233. sqlite3_int64 iLeavesEndBlock = sqlite3_column_int64(pStmt, 2);
  159234. sqlite3_int64 iEndBlock = sqlite3_column_int64(pStmt, 3);
  159235. int nRoot = sqlite3_column_bytes(pStmt, 4);
  159236. char const *zRoot = sqlite3_column_blob(pStmt, 4);
  159237. /* If zTerm is not NULL, and this segment is not stored entirely on its
  159238. ** root node, the range of leaves scanned can be reduced. Do this. */
  159239. if( iStartBlock && zTerm && zRoot ){
  159240. sqlite3_int64 *pi = (isPrefix ? &iLeavesEndBlock : 0);
  159241. rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &iStartBlock, pi);
  159242. if( rc!=SQLITE_OK ) goto finished;
  159243. if( isPrefix==0 && isScan==0 ) iLeavesEndBlock = iStartBlock;
  159244. }
  159245. rc = sqlite3Fts3SegReaderNew(pCsr->nSegment+1,
  159246. (isPrefix==0 && isScan==0),
  159247. iStartBlock, iLeavesEndBlock,
  159248. iEndBlock, zRoot, nRoot, &pSeg
  159249. );
  159250. if( rc!=SQLITE_OK ) goto finished;
  159251. rc = fts3SegReaderCursorAppend(pCsr, pSeg);
  159252. }
  159253. }
  159254. finished:
  159255. rc2 = sqlite3_reset(pStmt);
  159256. if( rc==SQLITE_DONE ) rc = rc2;
  159257. return rc;
  159258. }
  159259. /*
  159260. ** Set up a cursor object for iterating through a full-text index or a
  159261. ** single level therein.
  159262. */
  159263. SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(
  159264. Fts3Table *p, /* FTS3 table handle */
  159265. int iLangid, /* Language-id to search */
  159266. int iIndex, /* Index to search (from 0 to p->nIndex-1) */
  159267. int iLevel, /* Level of segments to scan */
  159268. const char *zTerm, /* Term to query for */
  159269. int nTerm, /* Size of zTerm in bytes */
  159270. int isPrefix, /* True for a prefix search */
  159271. int isScan, /* True to scan from zTerm to EOF */
  159272. Fts3MultiSegReader *pCsr /* Cursor object to populate */
  159273. ){
  159274. assert( iIndex>=0 && iIndex<p->nIndex );
  159275. assert( iLevel==FTS3_SEGCURSOR_ALL
  159276. || iLevel==FTS3_SEGCURSOR_PENDING
  159277. || iLevel>=0
  159278. );
  159279. assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
  159280. assert( FTS3_SEGCURSOR_ALL<0 && FTS3_SEGCURSOR_PENDING<0 );
  159281. assert( isPrefix==0 || isScan==0 );
  159282. memset(pCsr, 0, sizeof(Fts3MultiSegReader));
  159283. return fts3SegReaderCursor(
  159284. p, iLangid, iIndex, iLevel, zTerm, nTerm, isPrefix, isScan, pCsr
  159285. );
  159286. }
  159287. /*
  159288. ** In addition to its current configuration, have the Fts3MultiSegReader
  159289. ** passed as the 4th argument also scan the doclist for term zTerm/nTerm.
  159290. **
  159291. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  159292. */
  159293. static int fts3SegReaderCursorAddZero(
  159294. Fts3Table *p, /* FTS virtual table handle */
  159295. int iLangid,
  159296. const char *zTerm, /* Term to scan doclist of */
  159297. int nTerm, /* Number of bytes in zTerm */
  159298. Fts3MultiSegReader *pCsr /* Fts3MultiSegReader to modify */
  159299. ){
  159300. return fts3SegReaderCursor(p,
  159301. iLangid, 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0,pCsr
  159302. );
  159303. }
  159304. /*
  159305. ** Open an Fts3MultiSegReader to scan the doclist for term zTerm/nTerm. Or,
  159306. ** if isPrefix is true, to scan the doclist for all terms for which
  159307. ** zTerm/nTerm is a prefix. If successful, return SQLITE_OK and write
  159308. ** a pointer to the new Fts3MultiSegReader to *ppSegcsr. Otherwise, return
  159309. ** an SQLite error code.
  159310. **
  159311. ** It is the responsibility of the caller to free this object by eventually
  159312. ** passing it to fts3SegReaderCursorFree()
  159313. **
  159314. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  159315. ** Output parameter *ppSegcsr is set to 0 if an error occurs.
  159316. */
  159317. static int fts3TermSegReaderCursor(
  159318. Fts3Cursor *pCsr, /* Virtual table cursor handle */
  159319. const char *zTerm, /* Term to query for */
  159320. int nTerm, /* Size of zTerm in bytes */
  159321. int isPrefix, /* True for a prefix search */
  159322. Fts3MultiSegReader **ppSegcsr /* OUT: Allocated seg-reader cursor */
  159323. ){
  159324. Fts3MultiSegReader *pSegcsr; /* Object to allocate and return */
  159325. int rc = SQLITE_NOMEM; /* Return code */
  159326. pSegcsr = sqlite3_malloc(sizeof(Fts3MultiSegReader));
  159327. if( pSegcsr ){
  159328. int i;
  159329. int bFound = 0; /* True once an index has been found */
  159330. Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
  159331. if( isPrefix ){
  159332. for(i=1; bFound==0 && i<p->nIndex; i++){
  159333. if( p->aIndex[i].nPrefix==nTerm ){
  159334. bFound = 1;
  159335. rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
  159336. i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0, pSegcsr
  159337. );
  159338. pSegcsr->bLookup = 1;
  159339. }
  159340. }
  159341. for(i=1; bFound==0 && i<p->nIndex; i++){
  159342. if( p->aIndex[i].nPrefix==nTerm+1 ){
  159343. bFound = 1;
  159344. rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
  159345. i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 1, 0, pSegcsr
  159346. );
  159347. if( rc==SQLITE_OK ){
  159348. rc = fts3SegReaderCursorAddZero(
  159349. p, pCsr->iLangid, zTerm, nTerm, pSegcsr
  159350. );
  159351. }
  159352. }
  159353. }
  159354. }
  159355. if( bFound==0 ){
  159356. rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
  159357. 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, isPrefix, 0, pSegcsr
  159358. );
  159359. pSegcsr->bLookup = !isPrefix;
  159360. }
  159361. }
  159362. *ppSegcsr = pSegcsr;
  159363. return rc;
  159364. }
  159365. /*
  159366. ** Free an Fts3MultiSegReader allocated by fts3TermSegReaderCursor().
  159367. */
  159368. static void fts3SegReaderCursorFree(Fts3MultiSegReader *pSegcsr){
  159369. sqlite3Fts3SegReaderFinish(pSegcsr);
  159370. sqlite3_free(pSegcsr);
  159371. }
  159372. /*
  159373. ** This function retrieves the doclist for the specified term (or term
  159374. ** prefix) from the database.
  159375. */
  159376. static int fts3TermSelect(
  159377. Fts3Table *p, /* Virtual table handle */
  159378. Fts3PhraseToken *pTok, /* Token to query for */
  159379. int iColumn, /* Column to query (or -ve for all columns) */
  159380. int *pnOut, /* OUT: Size of buffer at *ppOut */
  159381. char **ppOut /* OUT: Malloced result buffer */
  159382. ){
  159383. int rc; /* Return code */
  159384. Fts3MultiSegReader *pSegcsr; /* Seg-reader cursor for this term */
  159385. TermSelect tsc; /* Object for pair-wise doclist merging */
  159386. Fts3SegFilter filter; /* Segment term filter configuration */
  159387. pSegcsr = pTok->pSegcsr;
  159388. memset(&tsc, 0, sizeof(TermSelect));
  159389. filter.flags = FTS3_SEGMENT_IGNORE_EMPTY | FTS3_SEGMENT_REQUIRE_POS
  159390. | (pTok->isPrefix ? FTS3_SEGMENT_PREFIX : 0)
  159391. | (pTok->bFirst ? FTS3_SEGMENT_FIRST : 0)
  159392. | (iColumn<p->nColumn ? FTS3_SEGMENT_COLUMN_FILTER : 0);
  159393. filter.iCol = iColumn;
  159394. filter.zTerm = pTok->z;
  159395. filter.nTerm = pTok->n;
  159396. rc = sqlite3Fts3SegReaderStart(p, pSegcsr, &filter);
  159397. while( SQLITE_OK==rc
  159398. && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pSegcsr))
  159399. ){
  159400. rc = fts3TermSelectMerge(p, &tsc, pSegcsr->aDoclist, pSegcsr->nDoclist);
  159401. }
  159402. if( rc==SQLITE_OK ){
  159403. rc = fts3TermSelectFinishMerge(p, &tsc);
  159404. }
  159405. if( rc==SQLITE_OK ){
  159406. *ppOut = tsc.aaOutput[0];
  159407. *pnOut = tsc.anOutput[0];
  159408. }else{
  159409. int i;
  159410. for(i=0; i<SizeofArray(tsc.aaOutput); i++){
  159411. sqlite3_free(tsc.aaOutput[i]);
  159412. }
  159413. }
  159414. fts3SegReaderCursorFree(pSegcsr);
  159415. pTok->pSegcsr = 0;
  159416. return rc;
  159417. }
  159418. /*
  159419. ** This function counts the total number of docids in the doclist stored
  159420. ** in buffer aList[], size nList bytes.
  159421. **
  159422. ** If the isPoslist argument is true, then it is assumed that the doclist
  159423. ** contains a position-list following each docid. Otherwise, it is assumed
  159424. ** that the doclist is simply a list of docids stored as delta encoded
  159425. ** varints.
  159426. */
  159427. static int fts3DoclistCountDocids(char *aList, int nList){
  159428. int nDoc = 0; /* Return value */
  159429. if( aList ){
  159430. char *aEnd = &aList[nList]; /* Pointer to one byte after EOF */
  159431. char *p = aList; /* Cursor */
  159432. while( p<aEnd ){
  159433. nDoc++;
  159434. while( (*p++)&0x80 ); /* Skip docid varint */
  159435. fts3PoslistCopy(0, &p); /* Skip over position list */
  159436. }
  159437. }
  159438. return nDoc;
  159439. }
  159440. /*
  159441. ** Advance the cursor to the next row in the %_content table that
  159442. ** matches the search criteria. For a MATCH search, this will be
  159443. ** the next row that matches. For a full-table scan, this will be
  159444. ** simply the next row in the %_content table. For a docid lookup,
  159445. ** this routine simply sets the EOF flag.
  159446. **
  159447. ** Return SQLITE_OK if nothing goes wrong. SQLITE_OK is returned
  159448. ** even if we reach end-of-file. The fts3EofMethod() will be called
  159449. ** subsequently to determine whether or not an EOF was hit.
  159450. */
  159451. static int fts3NextMethod(sqlite3_vtab_cursor *pCursor){
  159452. int rc;
  159453. Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
  159454. if( pCsr->eSearch==FTS3_DOCID_SEARCH || pCsr->eSearch==FTS3_FULLSCAN_SEARCH ){
  159455. Fts3Table *pTab = (Fts3Table*)pCursor->pVtab;
  159456. pTab->bLock++;
  159457. if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){
  159458. pCsr->isEof = 1;
  159459. rc = sqlite3_reset(pCsr->pStmt);
  159460. }else{
  159461. pCsr->iPrevId = sqlite3_column_int64(pCsr->pStmt, 0);
  159462. rc = SQLITE_OK;
  159463. }
  159464. pTab->bLock--;
  159465. }else{
  159466. rc = fts3EvalNext((Fts3Cursor *)pCursor);
  159467. }
  159468. assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
  159469. return rc;
  159470. }
  159471. /*
  159472. ** If the numeric type of argument pVal is "integer", then return it
  159473. ** converted to a 64-bit signed integer. Otherwise, return a copy of
  159474. ** the second parameter, iDefault.
  159475. */
  159476. static sqlite3_int64 fts3DocidRange(sqlite3_value *pVal, i64 iDefault){
  159477. if( pVal ){
  159478. int eType = sqlite3_value_numeric_type(pVal);
  159479. if( eType==SQLITE_INTEGER ){
  159480. return sqlite3_value_int64(pVal);
  159481. }
  159482. }
  159483. return iDefault;
  159484. }
  159485. /*
  159486. ** This is the xFilter interface for the virtual table. See
  159487. ** the virtual table xFilter method documentation for additional
  159488. ** information.
  159489. **
  159490. ** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against
  159491. ** the %_content table.
  159492. **
  159493. ** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry
  159494. ** in the %_content table.
  159495. **
  159496. ** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index. The
  159497. ** column on the left-hand side of the MATCH operator is column
  159498. ** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed. argv[0] is the right-hand
  159499. ** side of the MATCH operator.
  159500. */
  159501. static int fts3FilterMethod(
  159502. sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
  159503. int idxNum, /* Strategy index */
  159504. const char *idxStr, /* Unused */
  159505. int nVal, /* Number of elements in apVal */
  159506. sqlite3_value **apVal /* Arguments for the indexing scheme */
  159507. ){
  159508. int rc = SQLITE_OK;
  159509. char *zSql; /* SQL statement used to access %_content */
  159510. int eSearch;
  159511. Fts3Table *p = (Fts3Table *)pCursor->pVtab;
  159512. Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
  159513. sqlite3_value *pCons = 0; /* The MATCH or rowid constraint, if any */
  159514. sqlite3_value *pLangid = 0; /* The "langid = ?" constraint, if any */
  159515. sqlite3_value *pDocidGe = 0; /* The "docid >= ?" constraint, if any */
  159516. sqlite3_value *pDocidLe = 0; /* The "docid <= ?" constraint, if any */
  159517. int iIdx;
  159518. UNUSED_PARAMETER(idxStr);
  159519. UNUSED_PARAMETER(nVal);
  159520. if( p->bLock ){
  159521. return SQLITE_ERROR;
  159522. }
  159523. eSearch = (idxNum & 0x0000FFFF);
  159524. assert( eSearch>=0 && eSearch<=(FTS3_FULLTEXT_SEARCH+p->nColumn) );
  159525. assert( p->pSegments==0 );
  159526. /* Collect arguments into local variables */
  159527. iIdx = 0;
  159528. if( eSearch!=FTS3_FULLSCAN_SEARCH ) pCons = apVal[iIdx++];
  159529. if( idxNum & FTS3_HAVE_LANGID ) pLangid = apVal[iIdx++];
  159530. if( idxNum & FTS3_HAVE_DOCID_GE ) pDocidGe = apVal[iIdx++];
  159531. if( idxNum & FTS3_HAVE_DOCID_LE ) pDocidLe = apVal[iIdx++];
  159532. assert( iIdx==nVal );
  159533. /* In case the cursor has been used before, clear it now. */
  159534. fts3ClearCursor(pCsr);
  159535. /* Set the lower and upper bounds on docids to return */
  159536. pCsr->iMinDocid = fts3DocidRange(pDocidGe, SMALLEST_INT64);
  159537. pCsr->iMaxDocid = fts3DocidRange(pDocidLe, LARGEST_INT64);
  159538. if( idxStr ){
  159539. pCsr->bDesc = (idxStr[0]=='D');
  159540. }else{
  159541. pCsr->bDesc = p->bDescIdx;
  159542. }
  159543. pCsr->eSearch = (i16)eSearch;
  159544. if( eSearch!=FTS3_DOCID_SEARCH && eSearch!=FTS3_FULLSCAN_SEARCH ){
  159545. int iCol = eSearch-FTS3_FULLTEXT_SEARCH;
  159546. const char *zQuery = (const char *)sqlite3_value_text(pCons);
  159547. if( zQuery==0 && sqlite3_value_type(pCons)!=SQLITE_NULL ){
  159548. return SQLITE_NOMEM;
  159549. }
  159550. pCsr->iLangid = 0;
  159551. if( pLangid ) pCsr->iLangid = sqlite3_value_int(pLangid);
  159552. assert( p->base.zErrMsg==0 );
  159553. rc = sqlite3Fts3ExprParse(p->pTokenizer, pCsr->iLangid,
  159554. p->azColumn, p->bFts4, p->nColumn, iCol, zQuery, -1, &pCsr->pExpr,
  159555. &p->base.zErrMsg
  159556. );
  159557. if( rc!=SQLITE_OK ){
  159558. return rc;
  159559. }
  159560. rc = fts3EvalStart(pCsr);
  159561. sqlite3Fts3SegmentsClose(p);
  159562. if( rc!=SQLITE_OK ) return rc;
  159563. pCsr->pNextId = pCsr->aDoclist;
  159564. pCsr->iPrevId = 0;
  159565. }
  159566. /* Compile a SELECT statement for this cursor. For a full-table-scan, the
  159567. ** statement loops through all rows of the %_content table. For a
  159568. ** full-text query or docid lookup, the statement retrieves a single
  159569. ** row by docid.
  159570. */
  159571. if( eSearch==FTS3_FULLSCAN_SEARCH ){
  159572. if( pDocidGe || pDocidLe ){
  159573. zSql = sqlite3_mprintf(
  159574. "SELECT %s WHERE rowid BETWEEN %lld AND %lld ORDER BY rowid %s",
  159575. p->zReadExprlist, pCsr->iMinDocid, pCsr->iMaxDocid,
  159576. (pCsr->bDesc ? "DESC" : "ASC")
  159577. );
  159578. }else{
  159579. zSql = sqlite3_mprintf("SELECT %s ORDER BY rowid %s",
  159580. p->zReadExprlist, (pCsr->bDesc ? "DESC" : "ASC")
  159581. );
  159582. }
  159583. if( zSql ){
  159584. p->bLock++;
  159585. rc = sqlite3_prepare_v3(
  159586. p->db,zSql,-1,SQLITE_PREPARE_PERSISTENT,&pCsr->pStmt,0
  159587. );
  159588. p->bLock--;
  159589. sqlite3_free(zSql);
  159590. }else{
  159591. rc = SQLITE_NOMEM;
  159592. }
  159593. }else if( eSearch==FTS3_DOCID_SEARCH ){
  159594. rc = fts3CursorSeekStmt(pCsr);
  159595. if( rc==SQLITE_OK ){
  159596. rc = sqlite3_bind_value(pCsr->pStmt, 1, pCons);
  159597. }
  159598. }
  159599. if( rc!=SQLITE_OK ) return rc;
  159600. return fts3NextMethod(pCursor);
  159601. }
  159602. /*
  159603. ** This is the xEof method of the virtual table. SQLite calls this
  159604. ** routine to find out if it has reached the end of a result set.
  159605. */
  159606. static int fts3EofMethod(sqlite3_vtab_cursor *pCursor){
  159607. Fts3Cursor *pCsr = (Fts3Cursor*)pCursor;
  159608. if( pCsr->isEof ){
  159609. fts3ClearCursor(pCsr);
  159610. pCsr->isEof = 1;
  159611. }
  159612. return pCsr->isEof;
  159613. }
  159614. /*
  159615. ** This is the xRowid method. The SQLite core calls this routine to
  159616. ** retrieve the rowid for the current row of the result set. fts3
  159617. ** exposes %_content.docid as the rowid for the virtual table. The
  159618. ** rowid should be written to *pRowid.
  159619. */
  159620. static int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
  159621. Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
  159622. *pRowid = pCsr->iPrevId;
  159623. return SQLITE_OK;
  159624. }
  159625. /*
  159626. ** This is the xColumn method, called by SQLite to request a value from
  159627. ** the row that the supplied cursor currently points to.
  159628. **
  159629. ** If:
  159630. **
  159631. ** (iCol < p->nColumn) -> The value of the iCol'th user column.
  159632. ** (iCol == p->nColumn) -> Magic column with the same name as the table.
  159633. ** (iCol == p->nColumn+1) -> Docid column
  159634. ** (iCol == p->nColumn+2) -> Langid column
  159635. */
  159636. static int fts3ColumnMethod(
  159637. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  159638. sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
  159639. int iCol /* Index of column to read value from */
  159640. ){
  159641. int rc = SQLITE_OK; /* Return Code */
  159642. Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
  159643. Fts3Table *p = (Fts3Table *)pCursor->pVtab;
  159644. /* The column value supplied by SQLite must be in range. */
  159645. assert( iCol>=0 && iCol<=p->nColumn+2 );
  159646. switch( iCol-p->nColumn ){
  159647. case 0:
  159648. /* The special 'table-name' column */
  159649. sqlite3_result_pointer(pCtx, pCsr, "fts3cursor", 0);
  159650. break;
  159651. case 1:
  159652. /* The docid column */
  159653. sqlite3_result_int64(pCtx, pCsr->iPrevId);
  159654. break;
  159655. case 2:
  159656. if( pCsr->pExpr ){
  159657. sqlite3_result_int64(pCtx, pCsr->iLangid);
  159658. break;
  159659. }else if( p->zLanguageid==0 ){
  159660. sqlite3_result_int(pCtx, 0);
  159661. break;
  159662. }else{
  159663. iCol = p->nColumn;
  159664. /* fall-through */
  159665. }
  159666. default:
  159667. /* A user column. Or, if this is a full-table scan, possibly the
  159668. ** language-id column. Seek the cursor. */
  159669. rc = fts3CursorSeek(0, pCsr);
  159670. if( rc==SQLITE_OK && sqlite3_data_count(pCsr->pStmt)-1>iCol ){
  159671. sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1));
  159672. }
  159673. break;
  159674. }
  159675. assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
  159676. return rc;
  159677. }
  159678. /*
  159679. ** This function is the implementation of the xUpdate callback used by
  159680. ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
  159681. ** inserted, updated or deleted.
  159682. */
  159683. static int fts3UpdateMethod(
  159684. sqlite3_vtab *pVtab, /* Virtual table handle */
  159685. int nArg, /* Size of argument array */
  159686. sqlite3_value **apVal, /* Array of arguments */
  159687. sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */
  159688. ){
  159689. return sqlite3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid);
  159690. }
  159691. /*
  159692. ** Implementation of xSync() method. Flush the contents of the pending-terms
  159693. ** hash-table to the database.
  159694. */
  159695. static int fts3SyncMethod(sqlite3_vtab *pVtab){
  159696. /* Following an incremental-merge operation, assuming that the input
  159697. ** segments are not completely consumed (the usual case), they are updated
  159698. ** in place to remove the entries that have already been merged. This
  159699. ** involves updating the leaf block that contains the smallest unmerged
  159700. ** entry and each block (if any) between the leaf and the root node. So
  159701. ** if the height of the input segment b-trees is N, and input segments
  159702. ** are merged eight at a time, updating the input segments at the end
  159703. ** of an incremental-merge requires writing (8*(1+N)) blocks. N is usually
  159704. ** small - often between 0 and 2. So the overhead of the incremental
  159705. ** merge is somewhere between 8 and 24 blocks. To avoid this overhead
  159706. ** dwarfing the actual productive work accomplished, the incremental merge
  159707. ** is only attempted if it will write at least 64 leaf blocks. Hence
  159708. ** nMinMerge.
  159709. **
  159710. ** Of course, updating the input segments also involves deleting a bunch
  159711. ** of blocks from the segments table. But this is not considered overhead
  159712. ** as it would also be required by a crisis-merge that used the same input
  159713. ** segments.
  159714. */
  159715. const u32 nMinMerge = 64; /* Minimum amount of incr-merge work to do */
  159716. Fts3Table *p = (Fts3Table*)pVtab;
  159717. int rc;
  159718. i64 iLastRowid = sqlite3_last_insert_rowid(p->db);
  159719. rc = sqlite3Fts3PendingTermsFlush(p);
  159720. if( rc==SQLITE_OK
  159721. && p->nLeafAdd>(nMinMerge/16)
  159722. && p->nAutoincrmerge && p->nAutoincrmerge!=0xff
  159723. ){
  159724. int mxLevel = 0; /* Maximum relative level value in db */
  159725. int A; /* Incr-merge parameter A */
  159726. rc = sqlite3Fts3MaxLevel(p, &mxLevel);
  159727. assert( rc==SQLITE_OK || mxLevel==0 );
  159728. A = p->nLeafAdd * mxLevel;
  159729. A += (A/2);
  159730. if( A>(int)nMinMerge ) rc = sqlite3Fts3Incrmerge(p, A, p->nAutoincrmerge);
  159731. }
  159732. sqlite3Fts3SegmentsClose(p);
  159733. sqlite3_set_last_insert_rowid(p->db, iLastRowid);
  159734. return rc;
  159735. }
  159736. /*
  159737. ** If it is currently unknown whether or not the FTS table has an %_stat
  159738. ** table (if p->bHasStat==2), attempt to determine this (set p->bHasStat
  159739. ** to 0 or 1). Return SQLITE_OK if successful, or an SQLite error code
  159740. ** if an error occurs.
  159741. */
  159742. static int fts3SetHasStat(Fts3Table *p){
  159743. int rc = SQLITE_OK;
  159744. if( p->bHasStat==2 ){
  159745. char *zTbl = sqlite3_mprintf("%s_stat", p->zName);
  159746. if( zTbl ){
  159747. int res = sqlite3_table_column_metadata(p->db, p->zDb, zTbl, 0,0,0,0,0,0);
  159748. sqlite3_free(zTbl);
  159749. p->bHasStat = (res==SQLITE_OK);
  159750. }else{
  159751. rc = SQLITE_NOMEM;
  159752. }
  159753. }
  159754. return rc;
  159755. }
  159756. /*
  159757. ** Implementation of xBegin() method.
  159758. */
  159759. static int fts3BeginMethod(sqlite3_vtab *pVtab){
  159760. Fts3Table *p = (Fts3Table*)pVtab;
  159761. UNUSED_PARAMETER(pVtab);
  159762. assert( p->pSegments==0 );
  159763. assert( p->nPendingData==0 );
  159764. assert( p->inTransaction!=1 );
  159765. TESTONLY( p->inTransaction = 1 );
  159766. TESTONLY( p->mxSavepoint = -1; );
  159767. p->nLeafAdd = 0;
  159768. return fts3SetHasStat(p);
  159769. }
  159770. /*
  159771. ** Implementation of xCommit() method. This is a no-op. The contents of
  159772. ** the pending-terms hash-table have already been flushed into the database
  159773. ** by fts3SyncMethod().
  159774. */
  159775. static int fts3CommitMethod(sqlite3_vtab *pVtab){
  159776. TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
  159777. UNUSED_PARAMETER(pVtab);
  159778. assert( p->nPendingData==0 );
  159779. assert( p->inTransaction!=0 );
  159780. assert( p->pSegments==0 );
  159781. TESTONLY( p->inTransaction = 0 );
  159782. TESTONLY( p->mxSavepoint = -1; );
  159783. return SQLITE_OK;
  159784. }
  159785. /*
  159786. ** Implementation of xRollback(). Discard the contents of the pending-terms
  159787. ** hash-table. Any changes made to the database are reverted by SQLite.
  159788. */
  159789. static int fts3RollbackMethod(sqlite3_vtab *pVtab){
  159790. Fts3Table *p = (Fts3Table*)pVtab;
  159791. sqlite3Fts3PendingTermsClear(p);
  159792. assert( p->inTransaction!=0 );
  159793. TESTONLY( p->inTransaction = 0 );
  159794. TESTONLY( p->mxSavepoint = -1; );
  159795. return SQLITE_OK;
  159796. }
  159797. /*
  159798. ** When called, *ppPoslist must point to the byte immediately following the
  159799. ** end of a position-list. i.e. ( (*ppPoslist)[-1]==POS_END ). This function
  159800. ** moves *ppPoslist so that it instead points to the first byte of the
  159801. ** same position list.
  159802. */
  159803. static void fts3ReversePoslist(char *pStart, char **ppPoslist){
  159804. char *p = &(*ppPoslist)[-2];
  159805. char c = 0;
  159806. /* Skip backwards passed any trailing 0x00 bytes added by NearTrim() */
  159807. while( p>pStart && (c=*p--)==0 );
  159808. /* Search backwards for a varint with value zero (the end of the previous
  159809. ** poslist). This is an 0x00 byte preceded by some byte that does not
  159810. ** have the 0x80 bit set. */
  159811. while( p>pStart && (*p & 0x80) | c ){
  159812. c = *p--;
  159813. }
  159814. assert( p==pStart || c==0 );
  159815. /* At this point p points to that preceding byte without the 0x80 bit
  159816. ** set. So to find the start of the poslist, skip forward 2 bytes then
  159817. ** over a varint.
  159818. **
  159819. ** Normally. The other case is that p==pStart and the poslist to return
  159820. ** is the first in the doclist. In this case do not skip forward 2 bytes.
  159821. ** The second part of the if condition (c==0 && *ppPoslist>&p[2])
  159822. ** is required for cases where the first byte of a doclist and the
  159823. ** doclist is empty. For example, if the first docid is 10, a doclist
  159824. ** that begins with:
  159825. **
  159826. ** 0x0A 0x00 <next docid delta varint>
  159827. */
  159828. if( p>pStart || (c==0 && *ppPoslist>&p[2]) ){ p = &p[2]; }
  159829. while( *p++&0x80 );
  159830. *ppPoslist = p;
  159831. }
  159832. /*
  159833. ** Helper function used by the implementation of the overloaded snippet(),
  159834. ** offsets() and optimize() SQL functions.
  159835. **
  159836. ** If the value passed as the third argument is a blob of size
  159837. ** sizeof(Fts3Cursor*), then the blob contents are copied to the
  159838. ** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error
  159839. ** message is written to context pContext and SQLITE_ERROR returned. The
  159840. ** string passed via zFunc is used as part of the error message.
  159841. */
  159842. static int fts3FunctionArg(
  159843. sqlite3_context *pContext, /* SQL function call context */
  159844. const char *zFunc, /* Function name */
  159845. sqlite3_value *pVal, /* argv[0] passed to function */
  159846. Fts3Cursor **ppCsr /* OUT: Store cursor handle here */
  159847. ){
  159848. int rc;
  159849. *ppCsr = (Fts3Cursor*)sqlite3_value_pointer(pVal, "fts3cursor");
  159850. if( (*ppCsr)!=0 ){
  159851. rc = SQLITE_OK;
  159852. }else{
  159853. char *zErr = sqlite3_mprintf("illegal first argument to %s", zFunc);
  159854. sqlite3_result_error(pContext, zErr, -1);
  159855. sqlite3_free(zErr);
  159856. rc = SQLITE_ERROR;
  159857. }
  159858. return rc;
  159859. }
  159860. /*
  159861. ** Implementation of the snippet() function for FTS3
  159862. */
  159863. static void fts3SnippetFunc(
  159864. sqlite3_context *pContext, /* SQLite function call context */
  159865. int nVal, /* Size of apVal[] array */
  159866. sqlite3_value **apVal /* Array of arguments */
  159867. ){
  159868. Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
  159869. const char *zStart = "<b>";
  159870. const char *zEnd = "</b>";
  159871. const char *zEllipsis = "<b>...</b>";
  159872. int iCol = -1;
  159873. int nToken = 15; /* Default number of tokens in snippet */
  159874. /* There must be at least one argument passed to this function (otherwise
  159875. ** the non-overloaded version would have been called instead of this one).
  159876. */
  159877. assert( nVal>=1 );
  159878. if( nVal>6 ){
  159879. sqlite3_result_error(pContext,
  159880. "wrong number of arguments to function snippet()", -1);
  159881. return;
  159882. }
  159883. if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return;
  159884. switch( nVal ){
  159885. case 6: nToken = sqlite3_value_int(apVal[5]);
  159886. case 5: iCol = sqlite3_value_int(apVal[4]);
  159887. case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]);
  159888. case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]);
  159889. case 2: zStart = (const char*)sqlite3_value_text(apVal[1]);
  159890. }
  159891. if( !zEllipsis || !zEnd || !zStart ){
  159892. sqlite3_result_error_nomem(pContext);
  159893. }else if( nToken==0 ){
  159894. sqlite3_result_text(pContext, "", -1, SQLITE_STATIC);
  159895. }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
  159896. sqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken);
  159897. }
  159898. }
  159899. /*
  159900. ** Implementation of the offsets() function for FTS3
  159901. */
  159902. static void fts3OffsetsFunc(
  159903. sqlite3_context *pContext, /* SQLite function call context */
  159904. int nVal, /* Size of argument array */
  159905. sqlite3_value **apVal /* Array of arguments */
  159906. ){
  159907. Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
  159908. UNUSED_PARAMETER(nVal);
  159909. assert( nVal==1 );
  159910. if( fts3FunctionArg(pContext, "offsets", apVal[0], &pCsr) ) return;
  159911. assert( pCsr );
  159912. if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
  159913. sqlite3Fts3Offsets(pContext, pCsr);
  159914. }
  159915. }
  159916. /*
  159917. ** Implementation of the special optimize() function for FTS3. This
  159918. ** function merges all segments in the database to a single segment.
  159919. ** Example usage is:
  159920. **
  159921. ** SELECT optimize(t) FROM t LIMIT 1;
  159922. **
  159923. ** where 't' is the name of an FTS3 table.
  159924. */
  159925. static void fts3OptimizeFunc(
  159926. sqlite3_context *pContext, /* SQLite function call context */
  159927. int nVal, /* Size of argument array */
  159928. sqlite3_value **apVal /* Array of arguments */
  159929. ){
  159930. int rc; /* Return code */
  159931. Fts3Table *p; /* Virtual table handle */
  159932. Fts3Cursor *pCursor; /* Cursor handle passed through apVal[0] */
  159933. UNUSED_PARAMETER(nVal);
  159934. assert( nVal==1 );
  159935. if( fts3FunctionArg(pContext, "optimize", apVal[0], &pCursor) ) return;
  159936. p = (Fts3Table *)pCursor->base.pVtab;
  159937. assert( p );
  159938. rc = sqlite3Fts3Optimize(p);
  159939. switch( rc ){
  159940. case SQLITE_OK:
  159941. sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
  159942. break;
  159943. case SQLITE_DONE:
  159944. sqlite3_result_text(pContext, "Index already optimal", -1, SQLITE_STATIC);
  159945. break;
  159946. default:
  159947. sqlite3_result_error_code(pContext, rc);
  159948. break;
  159949. }
  159950. }
  159951. /*
  159952. ** Implementation of the matchinfo() function for FTS3
  159953. */
  159954. static void fts3MatchinfoFunc(
  159955. sqlite3_context *pContext, /* SQLite function call context */
  159956. int nVal, /* Size of argument array */
  159957. sqlite3_value **apVal /* Array of arguments */
  159958. ){
  159959. Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
  159960. assert( nVal==1 || nVal==2 );
  159961. if( SQLITE_OK==fts3FunctionArg(pContext, "matchinfo", apVal[0], &pCsr) ){
  159962. const char *zArg = 0;
  159963. if( nVal>1 ){
  159964. zArg = (const char *)sqlite3_value_text(apVal[1]);
  159965. }
  159966. sqlite3Fts3Matchinfo(pContext, pCsr, zArg);
  159967. }
  159968. }
  159969. /*
  159970. ** This routine implements the xFindFunction method for the FTS3
  159971. ** virtual table.
  159972. */
  159973. static int fts3FindFunctionMethod(
  159974. sqlite3_vtab *pVtab, /* Virtual table handle */
  159975. int nArg, /* Number of SQL function arguments */
  159976. const char *zName, /* Name of SQL function */
  159977. void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
  159978. void **ppArg /* Unused */
  159979. ){
  159980. struct Overloaded {
  159981. const char *zName;
  159982. void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
  159983. } aOverload[] = {
  159984. { "snippet", fts3SnippetFunc },
  159985. { "offsets", fts3OffsetsFunc },
  159986. { "optimize", fts3OptimizeFunc },
  159987. { "matchinfo", fts3MatchinfoFunc },
  159988. };
  159989. int i; /* Iterator variable */
  159990. UNUSED_PARAMETER(pVtab);
  159991. UNUSED_PARAMETER(nArg);
  159992. UNUSED_PARAMETER(ppArg);
  159993. for(i=0; i<SizeofArray(aOverload); i++){
  159994. if( strcmp(zName, aOverload[i].zName)==0 ){
  159995. *pxFunc = aOverload[i].xFunc;
  159996. return 1;
  159997. }
  159998. }
  159999. /* No function of the specified name was found. Return 0. */
  160000. return 0;
  160001. }
  160002. /*
  160003. ** Implementation of FTS3 xRename method. Rename an fts3 table.
  160004. */
  160005. static int fts3RenameMethod(
  160006. sqlite3_vtab *pVtab, /* Virtual table handle */
  160007. const char *zName /* New name of table */
  160008. ){
  160009. Fts3Table *p = (Fts3Table *)pVtab;
  160010. sqlite3 *db = p->db; /* Database connection */
  160011. int rc; /* Return Code */
  160012. /* At this point it must be known if the %_stat table exists or not.
  160013. ** So bHasStat may not be 2. */
  160014. rc = fts3SetHasStat(p);
  160015. /* As it happens, the pending terms table is always empty here. This is
  160016. ** because an "ALTER TABLE RENAME TABLE" statement inside a transaction
  160017. ** always opens a savepoint transaction. And the xSavepoint() method
  160018. ** flushes the pending terms table. But leave the (no-op) call to
  160019. ** PendingTermsFlush() in in case that changes.
  160020. */
  160021. assert( p->nPendingData==0 );
  160022. if( rc==SQLITE_OK ){
  160023. rc = sqlite3Fts3PendingTermsFlush(p);
  160024. }
  160025. if( p->zContentTbl==0 ){
  160026. fts3DbExec(&rc, db,
  160027. "ALTER TABLE %Q.'%q_content' RENAME TO '%q_content';",
  160028. p->zDb, p->zName, zName
  160029. );
  160030. }
  160031. if( p->bHasDocsize ){
  160032. fts3DbExec(&rc, db,
  160033. "ALTER TABLE %Q.'%q_docsize' RENAME TO '%q_docsize';",
  160034. p->zDb, p->zName, zName
  160035. );
  160036. }
  160037. if( p->bHasStat ){
  160038. fts3DbExec(&rc, db,
  160039. "ALTER TABLE %Q.'%q_stat' RENAME TO '%q_stat';",
  160040. p->zDb, p->zName, zName
  160041. );
  160042. }
  160043. fts3DbExec(&rc, db,
  160044. "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';",
  160045. p->zDb, p->zName, zName
  160046. );
  160047. fts3DbExec(&rc, db,
  160048. "ALTER TABLE %Q.'%q_segdir' RENAME TO '%q_segdir';",
  160049. p->zDb, p->zName, zName
  160050. );
  160051. return rc;
  160052. }
  160053. /*
  160054. ** The xSavepoint() method.
  160055. **
  160056. ** Flush the contents of the pending-terms table to disk.
  160057. */
  160058. static int fts3SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
  160059. int rc = SQLITE_OK;
  160060. UNUSED_PARAMETER(iSavepoint);
  160061. assert( ((Fts3Table *)pVtab)->inTransaction );
  160062. assert( ((Fts3Table *)pVtab)->mxSavepoint <= iSavepoint );
  160063. TESTONLY( ((Fts3Table *)pVtab)->mxSavepoint = iSavepoint );
  160064. if( ((Fts3Table *)pVtab)->bIgnoreSavepoint==0 ){
  160065. rc = fts3SyncMethod(pVtab);
  160066. }
  160067. return rc;
  160068. }
  160069. /*
  160070. ** The xRelease() method.
  160071. **
  160072. ** This is a no-op.
  160073. */
  160074. static int fts3ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
  160075. TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
  160076. UNUSED_PARAMETER(iSavepoint);
  160077. UNUSED_PARAMETER(pVtab);
  160078. assert( p->inTransaction );
  160079. assert( p->mxSavepoint >= iSavepoint );
  160080. TESTONLY( p->mxSavepoint = iSavepoint-1 );
  160081. return SQLITE_OK;
  160082. }
  160083. /*
  160084. ** The xRollbackTo() method.
  160085. **
  160086. ** Discard the contents of the pending terms table.
  160087. */
  160088. static int fts3RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
  160089. Fts3Table *p = (Fts3Table*)pVtab;
  160090. UNUSED_PARAMETER(iSavepoint);
  160091. assert( p->inTransaction );
  160092. TESTONLY( p->mxSavepoint = iSavepoint );
  160093. sqlite3Fts3PendingTermsClear(p);
  160094. return SQLITE_OK;
  160095. }
  160096. /*
  160097. ** Return true if zName is the extension on one of the shadow tables used
  160098. ** by this module.
  160099. */
  160100. static int fts3ShadowName(const char *zName){
  160101. static const char *azName[] = {
  160102. "content", "docsize", "segdir", "segments", "stat",
  160103. };
  160104. unsigned int i;
  160105. for(i=0; i<sizeof(azName)/sizeof(azName[0]); i++){
  160106. if( sqlite3_stricmp(zName, azName[i])==0 ) return 1;
  160107. }
  160108. return 0;
  160109. }
  160110. static const sqlite3_module fts3Module = {
  160111. /* iVersion */ 3,
  160112. /* xCreate */ fts3CreateMethod,
  160113. /* xConnect */ fts3ConnectMethod,
  160114. /* xBestIndex */ fts3BestIndexMethod,
  160115. /* xDisconnect */ fts3DisconnectMethod,
  160116. /* xDestroy */ fts3DestroyMethod,
  160117. /* xOpen */ fts3OpenMethod,
  160118. /* xClose */ fts3CloseMethod,
  160119. /* xFilter */ fts3FilterMethod,
  160120. /* xNext */ fts3NextMethod,
  160121. /* xEof */ fts3EofMethod,
  160122. /* xColumn */ fts3ColumnMethod,
  160123. /* xRowid */ fts3RowidMethod,
  160124. /* xUpdate */ fts3UpdateMethod,
  160125. /* xBegin */ fts3BeginMethod,
  160126. /* xSync */ fts3SyncMethod,
  160127. /* xCommit */ fts3CommitMethod,
  160128. /* xRollback */ fts3RollbackMethod,
  160129. /* xFindFunction */ fts3FindFunctionMethod,
  160130. /* xRename */ fts3RenameMethod,
  160131. /* xSavepoint */ fts3SavepointMethod,
  160132. /* xRelease */ fts3ReleaseMethod,
  160133. /* xRollbackTo */ fts3RollbackToMethod,
  160134. /* xShadowName */ fts3ShadowName,
  160135. };
  160136. /*
  160137. ** This function is registered as the module destructor (called when an
  160138. ** FTS3 enabled database connection is closed). It frees the memory
  160139. ** allocated for the tokenizer hash table.
  160140. */
  160141. static void hashDestroy(void *p){
  160142. Fts3Hash *pHash = (Fts3Hash *)p;
  160143. sqlite3Fts3HashClear(pHash);
  160144. sqlite3_free(pHash);
  160145. }
  160146. /*
  160147. ** The fts3 built-in tokenizers - "simple", "porter" and "icu"- are
  160148. ** implemented in files fts3_tokenizer1.c, fts3_porter.c and fts3_icu.c
  160149. ** respectively. The following three forward declarations are for functions
  160150. ** declared in these files used to retrieve the respective implementations.
  160151. **
  160152. ** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
  160153. ** to by the argument to point to the "simple" tokenizer implementation.
  160154. ** And so on.
  160155. */
  160156. SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  160157. SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  160158. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  160159. SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const**ppModule);
  160160. #endif
  160161. #ifdef SQLITE_ENABLE_ICU
  160162. SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  160163. #endif
  160164. /*
  160165. ** Initialize the fts3 extension. If this extension is built as part
  160166. ** of the sqlite library, then this function is called directly by
  160167. ** SQLite. If fts3 is built as a dynamically loadable extension, this
  160168. ** function is called by the sqlite3_extension_init() entry point.
  160169. */
  160170. SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){
  160171. int rc = SQLITE_OK;
  160172. Fts3Hash *pHash = 0;
  160173. const sqlite3_tokenizer_module *pSimple = 0;
  160174. const sqlite3_tokenizer_module *pPorter = 0;
  160175. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  160176. const sqlite3_tokenizer_module *pUnicode = 0;
  160177. #endif
  160178. #ifdef SQLITE_ENABLE_ICU
  160179. const sqlite3_tokenizer_module *pIcu = 0;
  160180. sqlite3Fts3IcuTokenizerModule(&pIcu);
  160181. #endif
  160182. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  160183. sqlite3Fts3UnicodeTokenizer(&pUnicode);
  160184. #endif
  160185. #ifdef SQLITE_TEST
  160186. rc = sqlite3Fts3InitTerm(db);
  160187. if( rc!=SQLITE_OK ) return rc;
  160188. #endif
  160189. rc = sqlite3Fts3InitAux(db);
  160190. if( rc!=SQLITE_OK ) return rc;
  160191. sqlite3Fts3SimpleTokenizerModule(&pSimple);
  160192. sqlite3Fts3PorterTokenizerModule(&pPorter);
  160193. /* Allocate and initialize the hash-table used to store tokenizers. */
  160194. pHash = sqlite3_malloc(sizeof(Fts3Hash));
  160195. if( !pHash ){
  160196. rc = SQLITE_NOMEM;
  160197. }else{
  160198. sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
  160199. }
  160200. /* Load the built-in tokenizers into the hash table */
  160201. if( rc==SQLITE_OK ){
  160202. if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
  160203. || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter)
  160204. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  160205. || sqlite3Fts3HashInsert(pHash, "unicode61", 10, (void *)pUnicode)
  160206. #endif
  160207. #ifdef SQLITE_ENABLE_ICU
  160208. || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
  160209. #endif
  160210. ){
  160211. rc = SQLITE_NOMEM;
  160212. }
  160213. }
  160214. #ifdef SQLITE_TEST
  160215. if( rc==SQLITE_OK ){
  160216. rc = sqlite3Fts3ExprInitTestInterface(db, pHash);
  160217. }
  160218. #endif
  160219. /* Create the virtual table wrapper around the hash-table and overload
  160220. ** the four scalar functions. If this is successful, register the
  160221. ** module with sqlite.
  160222. */
  160223. if( SQLITE_OK==rc
  160224. && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
  160225. && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
  160226. && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", 1))
  160227. && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 1))
  160228. && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 2))
  160229. && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", 1))
  160230. ){
  160231. rc = sqlite3_create_module_v2(
  160232. db, "fts3", &fts3Module, (void *)pHash, hashDestroy
  160233. );
  160234. if( rc==SQLITE_OK ){
  160235. rc = sqlite3_create_module_v2(
  160236. db, "fts4", &fts3Module, (void *)pHash, 0
  160237. );
  160238. }
  160239. if( rc==SQLITE_OK ){
  160240. rc = sqlite3Fts3InitTok(db, (void *)pHash);
  160241. }
  160242. return rc;
  160243. }
  160244. /* An error has occurred. Delete the hash table and return the error code. */
  160245. assert( rc!=SQLITE_OK );
  160246. if( pHash ){
  160247. sqlite3Fts3HashClear(pHash);
  160248. sqlite3_free(pHash);
  160249. }
  160250. return rc;
  160251. }
  160252. /*
  160253. ** Allocate an Fts3MultiSegReader for each token in the expression headed
  160254. ** by pExpr.
  160255. **
  160256. ** An Fts3SegReader object is a cursor that can seek or scan a range of
  160257. ** entries within a single segment b-tree. An Fts3MultiSegReader uses multiple
  160258. ** Fts3SegReader objects internally to provide an interface to seek or scan
  160259. ** within the union of all segments of a b-tree. Hence the name.
  160260. **
  160261. ** If the allocated Fts3MultiSegReader just seeks to a single entry in a
  160262. ** segment b-tree (if the term is not a prefix or it is a prefix for which
  160263. ** there exists prefix b-tree of the right length) then it may be traversed
  160264. ** and merged incrementally. Otherwise, it has to be merged into an in-memory
  160265. ** doclist and then traversed.
  160266. */
  160267. static void fts3EvalAllocateReaders(
  160268. Fts3Cursor *pCsr, /* FTS cursor handle */
  160269. Fts3Expr *pExpr, /* Allocate readers for this expression */
  160270. int *pnToken, /* OUT: Total number of tokens in phrase. */
  160271. int *pnOr, /* OUT: Total number of OR nodes in expr. */
  160272. int *pRc /* IN/OUT: Error code */
  160273. ){
  160274. if( pExpr && SQLITE_OK==*pRc ){
  160275. if( pExpr->eType==FTSQUERY_PHRASE ){
  160276. int i;
  160277. int nToken = pExpr->pPhrase->nToken;
  160278. *pnToken += nToken;
  160279. for(i=0; i<nToken; i++){
  160280. Fts3PhraseToken *pToken = &pExpr->pPhrase->aToken[i];
  160281. int rc = fts3TermSegReaderCursor(pCsr,
  160282. pToken->z, pToken->n, pToken->isPrefix, &pToken->pSegcsr
  160283. );
  160284. if( rc!=SQLITE_OK ){
  160285. *pRc = rc;
  160286. return;
  160287. }
  160288. }
  160289. assert( pExpr->pPhrase->iDoclistToken==0 );
  160290. pExpr->pPhrase->iDoclistToken = -1;
  160291. }else{
  160292. *pnOr += (pExpr->eType==FTSQUERY_OR);
  160293. fts3EvalAllocateReaders(pCsr, pExpr->pLeft, pnToken, pnOr, pRc);
  160294. fts3EvalAllocateReaders(pCsr, pExpr->pRight, pnToken, pnOr, pRc);
  160295. }
  160296. }
  160297. }
  160298. /*
  160299. ** Arguments pList/nList contain the doclist for token iToken of phrase p.
  160300. ** It is merged into the main doclist stored in p->doclist.aAll/nAll.
  160301. **
  160302. ** This function assumes that pList points to a buffer allocated using
  160303. ** sqlite3_malloc(). This function takes responsibility for eventually
  160304. ** freeing the buffer.
  160305. **
  160306. ** SQLITE_OK is returned if successful, or SQLITE_NOMEM if an error occurs.
  160307. */
  160308. static int fts3EvalPhraseMergeToken(
  160309. Fts3Table *pTab, /* FTS Table pointer */
  160310. Fts3Phrase *p, /* Phrase to merge pList/nList into */
  160311. int iToken, /* Token pList/nList corresponds to */
  160312. char *pList, /* Pointer to doclist */
  160313. int nList /* Number of bytes in pList */
  160314. ){
  160315. int rc = SQLITE_OK;
  160316. assert( iToken!=p->iDoclistToken );
  160317. if( pList==0 ){
  160318. sqlite3_free(p->doclist.aAll);
  160319. p->doclist.aAll = 0;
  160320. p->doclist.nAll = 0;
  160321. }
  160322. else if( p->iDoclistToken<0 ){
  160323. p->doclist.aAll = pList;
  160324. p->doclist.nAll = nList;
  160325. }
  160326. else if( p->doclist.aAll==0 ){
  160327. sqlite3_free(pList);
  160328. }
  160329. else {
  160330. char *pLeft;
  160331. char *pRight;
  160332. int nLeft;
  160333. int nRight;
  160334. int nDiff;
  160335. if( p->iDoclistToken<iToken ){
  160336. pLeft = p->doclist.aAll;
  160337. nLeft = p->doclist.nAll;
  160338. pRight = pList;
  160339. nRight = nList;
  160340. nDiff = iToken - p->iDoclistToken;
  160341. }else{
  160342. pRight = p->doclist.aAll;
  160343. nRight = p->doclist.nAll;
  160344. pLeft = pList;
  160345. nLeft = nList;
  160346. nDiff = p->iDoclistToken - iToken;
  160347. }
  160348. rc = fts3DoclistPhraseMerge(
  160349. pTab->bDescIdx, nDiff, pLeft, nLeft, &pRight, &nRight
  160350. );
  160351. sqlite3_free(pLeft);
  160352. p->doclist.aAll = pRight;
  160353. p->doclist.nAll = nRight;
  160354. }
  160355. if( iToken>p->iDoclistToken ) p->iDoclistToken = iToken;
  160356. return rc;
  160357. }
  160358. /*
  160359. ** Load the doclist for phrase p into p->doclist.aAll/nAll. The loaded doclist
  160360. ** does not take deferred tokens into account.
  160361. **
  160362. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  160363. */
  160364. static int fts3EvalPhraseLoad(
  160365. Fts3Cursor *pCsr, /* FTS Cursor handle */
  160366. Fts3Phrase *p /* Phrase object */
  160367. ){
  160368. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  160369. int iToken;
  160370. int rc = SQLITE_OK;
  160371. for(iToken=0; rc==SQLITE_OK && iToken<p->nToken; iToken++){
  160372. Fts3PhraseToken *pToken = &p->aToken[iToken];
  160373. assert( pToken->pDeferred==0 || pToken->pSegcsr==0 );
  160374. if( pToken->pSegcsr ){
  160375. int nThis = 0;
  160376. char *pThis = 0;
  160377. rc = fts3TermSelect(pTab, pToken, p->iColumn, &nThis, &pThis);
  160378. if( rc==SQLITE_OK ){
  160379. rc = fts3EvalPhraseMergeToken(pTab, p, iToken, pThis, nThis);
  160380. }
  160381. }
  160382. assert( pToken->pSegcsr==0 );
  160383. }
  160384. return rc;
  160385. }
  160386. #ifndef SQLITE_DISABLE_FTS4_DEFERRED
  160387. /*
  160388. ** This function is called on each phrase after the position lists for
  160389. ** any deferred tokens have been loaded into memory. It updates the phrases
  160390. ** current position list to include only those positions that are really
  160391. ** instances of the phrase (after considering deferred tokens). If this
  160392. ** means that the phrase does not appear in the current row, doclist.pList
  160393. ** and doclist.nList are both zeroed.
  160394. **
  160395. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  160396. */
  160397. static int fts3EvalDeferredPhrase(Fts3Cursor *pCsr, Fts3Phrase *pPhrase){
  160398. int iToken; /* Used to iterate through phrase tokens */
  160399. char *aPoslist = 0; /* Position list for deferred tokens */
  160400. int nPoslist = 0; /* Number of bytes in aPoslist */
  160401. int iPrev = -1; /* Token number of previous deferred token */
  160402. assert( pPhrase->doclist.bFreeList==0 );
  160403. for(iToken=0; iToken<pPhrase->nToken; iToken++){
  160404. Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
  160405. Fts3DeferredToken *pDeferred = pToken->pDeferred;
  160406. if( pDeferred ){
  160407. char *pList;
  160408. int nList;
  160409. int rc = sqlite3Fts3DeferredTokenList(pDeferred, &pList, &nList);
  160410. if( rc!=SQLITE_OK ) return rc;
  160411. if( pList==0 ){
  160412. sqlite3_free(aPoslist);
  160413. pPhrase->doclist.pList = 0;
  160414. pPhrase->doclist.nList = 0;
  160415. return SQLITE_OK;
  160416. }else if( aPoslist==0 ){
  160417. aPoslist = pList;
  160418. nPoslist = nList;
  160419. }else{
  160420. char *aOut = pList;
  160421. char *p1 = aPoslist;
  160422. char *p2 = aOut;
  160423. assert( iPrev>=0 );
  160424. fts3PoslistPhraseMerge(&aOut, iToken-iPrev, 0, 1, &p1, &p2);
  160425. sqlite3_free(aPoslist);
  160426. aPoslist = pList;
  160427. nPoslist = (int)(aOut - aPoslist);
  160428. if( nPoslist==0 ){
  160429. sqlite3_free(aPoslist);
  160430. pPhrase->doclist.pList = 0;
  160431. pPhrase->doclist.nList = 0;
  160432. return SQLITE_OK;
  160433. }
  160434. }
  160435. iPrev = iToken;
  160436. }
  160437. }
  160438. if( iPrev>=0 ){
  160439. int nMaxUndeferred = pPhrase->iDoclistToken;
  160440. if( nMaxUndeferred<0 ){
  160441. pPhrase->doclist.pList = aPoslist;
  160442. pPhrase->doclist.nList = nPoslist;
  160443. pPhrase->doclist.iDocid = pCsr->iPrevId;
  160444. pPhrase->doclist.bFreeList = 1;
  160445. }else{
  160446. int nDistance;
  160447. char *p1;
  160448. char *p2;
  160449. char *aOut;
  160450. if( nMaxUndeferred>iPrev ){
  160451. p1 = aPoslist;
  160452. p2 = pPhrase->doclist.pList;
  160453. nDistance = nMaxUndeferred - iPrev;
  160454. }else{
  160455. p1 = pPhrase->doclist.pList;
  160456. p2 = aPoslist;
  160457. nDistance = iPrev - nMaxUndeferred;
  160458. }
  160459. aOut = (char *)sqlite3_malloc(nPoslist+8);
  160460. if( !aOut ){
  160461. sqlite3_free(aPoslist);
  160462. return SQLITE_NOMEM;
  160463. }
  160464. pPhrase->doclist.pList = aOut;
  160465. if( fts3PoslistPhraseMerge(&aOut, nDistance, 0, 1, &p1, &p2) ){
  160466. pPhrase->doclist.bFreeList = 1;
  160467. pPhrase->doclist.nList = (int)(aOut - pPhrase->doclist.pList);
  160468. }else{
  160469. sqlite3_free(aOut);
  160470. pPhrase->doclist.pList = 0;
  160471. pPhrase->doclist.nList = 0;
  160472. }
  160473. sqlite3_free(aPoslist);
  160474. }
  160475. }
  160476. return SQLITE_OK;
  160477. }
  160478. #endif /* SQLITE_DISABLE_FTS4_DEFERRED */
  160479. /*
  160480. ** Maximum number of tokens a phrase may have to be considered for the
  160481. ** incremental doclists strategy.
  160482. */
  160483. #define MAX_INCR_PHRASE_TOKENS 4
  160484. /*
  160485. ** This function is called for each Fts3Phrase in a full-text query
  160486. ** expression to initialize the mechanism for returning rows. Once this
  160487. ** function has been called successfully on an Fts3Phrase, it may be
  160488. ** used with fts3EvalPhraseNext() to iterate through the matching docids.
  160489. **
  160490. ** If parameter bOptOk is true, then the phrase may (or may not) use the
  160491. ** incremental loading strategy. Otherwise, the entire doclist is loaded into
  160492. ** memory within this call.
  160493. **
  160494. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  160495. */
  160496. static int fts3EvalPhraseStart(Fts3Cursor *pCsr, int bOptOk, Fts3Phrase *p){
  160497. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  160498. int rc = SQLITE_OK; /* Error code */
  160499. int i;
  160500. /* Determine if doclists may be loaded from disk incrementally. This is
  160501. ** possible if the bOptOk argument is true, the FTS doclists will be
  160502. ** scanned in forward order, and the phrase consists of
  160503. ** MAX_INCR_PHRASE_TOKENS or fewer tokens, none of which are are "^first"
  160504. ** tokens or prefix tokens that cannot use a prefix-index. */
  160505. int bHaveIncr = 0;
  160506. int bIncrOk = (bOptOk
  160507. && pCsr->bDesc==pTab->bDescIdx
  160508. && p->nToken<=MAX_INCR_PHRASE_TOKENS && p->nToken>0
  160509. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  160510. && pTab->bNoIncrDoclist==0
  160511. #endif
  160512. );
  160513. for(i=0; bIncrOk==1 && i<p->nToken; i++){
  160514. Fts3PhraseToken *pToken = &p->aToken[i];
  160515. if( pToken->bFirst || (pToken->pSegcsr!=0 && !pToken->pSegcsr->bLookup) ){
  160516. bIncrOk = 0;
  160517. }
  160518. if( pToken->pSegcsr ) bHaveIncr = 1;
  160519. }
  160520. if( bIncrOk && bHaveIncr ){
  160521. /* Use the incremental approach. */
  160522. int iCol = (p->iColumn >= pTab->nColumn ? -1 : p->iColumn);
  160523. for(i=0; rc==SQLITE_OK && i<p->nToken; i++){
  160524. Fts3PhraseToken *pToken = &p->aToken[i];
  160525. Fts3MultiSegReader *pSegcsr = pToken->pSegcsr;
  160526. if( pSegcsr ){
  160527. rc = sqlite3Fts3MsrIncrStart(pTab, pSegcsr, iCol, pToken->z, pToken->n);
  160528. }
  160529. }
  160530. p->bIncr = 1;
  160531. }else{
  160532. /* Load the full doclist for the phrase into memory. */
  160533. rc = fts3EvalPhraseLoad(pCsr, p);
  160534. p->bIncr = 0;
  160535. }
  160536. assert( rc!=SQLITE_OK || p->nToken<1 || p->aToken[0].pSegcsr==0 || p->bIncr );
  160537. return rc;
  160538. }
  160539. /*
  160540. ** This function is used to iterate backwards (from the end to start)
  160541. ** through doclists. It is used by this module to iterate through phrase
  160542. ** doclists in reverse and by the fts3_write.c module to iterate through
  160543. ** pending-terms lists when writing to databases with "order=desc".
  160544. **
  160545. ** The doclist may be sorted in ascending (parameter bDescIdx==0) or
  160546. ** descending (parameter bDescIdx==1) order of docid. Regardless, this
  160547. ** function iterates from the end of the doclist to the beginning.
  160548. */
  160549. SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(
  160550. int bDescIdx, /* True if the doclist is desc */
  160551. char *aDoclist, /* Pointer to entire doclist */
  160552. int nDoclist, /* Length of aDoclist in bytes */
  160553. char **ppIter, /* IN/OUT: Iterator pointer */
  160554. sqlite3_int64 *piDocid, /* IN/OUT: Docid pointer */
  160555. int *pnList, /* OUT: List length pointer */
  160556. u8 *pbEof /* OUT: End-of-file flag */
  160557. ){
  160558. char *p = *ppIter;
  160559. assert( nDoclist>0 );
  160560. assert( *pbEof==0 );
  160561. assert( p || *piDocid==0 );
  160562. assert( !p || (p>aDoclist && p<&aDoclist[nDoclist]) );
  160563. if( p==0 ){
  160564. sqlite3_int64 iDocid = 0;
  160565. char *pNext = 0;
  160566. char *pDocid = aDoclist;
  160567. char *pEnd = &aDoclist[nDoclist];
  160568. int iMul = 1;
  160569. while( pDocid<pEnd ){
  160570. sqlite3_int64 iDelta;
  160571. pDocid += sqlite3Fts3GetVarint(pDocid, &iDelta);
  160572. iDocid += (iMul * iDelta);
  160573. pNext = pDocid;
  160574. fts3PoslistCopy(0, &pDocid);
  160575. while( pDocid<pEnd && *pDocid==0 ) pDocid++;
  160576. iMul = (bDescIdx ? -1 : 1);
  160577. }
  160578. *pnList = (int)(pEnd - pNext);
  160579. *ppIter = pNext;
  160580. *piDocid = iDocid;
  160581. }else{
  160582. int iMul = (bDescIdx ? -1 : 1);
  160583. sqlite3_int64 iDelta;
  160584. fts3GetReverseVarint(&p, aDoclist, &iDelta);
  160585. *piDocid -= (iMul * iDelta);
  160586. if( p==aDoclist ){
  160587. *pbEof = 1;
  160588. }else{
  160589. char *pSave = p;
  160590. fts3ReversePoslist(aDoclist, &p);
  160591. *pnList = (int)(pSave - p);
  160592. }
  160593. *ppIter = p;
  160594. }
  160595. }
  160596. /*
  160597. ** Iterate forwards through a doclist.
  160598. */
  160599. SQLITE_PRIVATE void sqlite3Fts3DoclistNext(
  160600. int bDescIdx, /* True if the doclist is desc */
  160601. char *aDoclist, /* Pointer to entire doclist */
  160602. int nDoclist, /* Length of aDoclist in bytes */
  160603. char **ppIter, /* IN/OUT: Iterator pointer */
  160604. sqlite3_int64 *piDocid, /* IN/OUT: Docid pointer */
  160605. u8 *pbEof /* OUT: End-of-file flag */
  160606. ){
  160607. char *p = *ppIter;
  160608. assert( nDoclist>0 );
  160609. assert( *pbEof==0 );
  160610. assert( p || *piDocid==0 );
  160611. assert( !p || (p>=aDoclist && p<=&aDoclist[nDoclist]) );
  160612. if( p==0 ){
  160613. p = aDoclist;
  160614. p += sqlite3Fts3GetVarint(p, piDocid);
  160615. }else{
  160616. fts3PoslistCopy(0, &p);
  160617. while( p<&aDoclist[nDoclist] && *p==0 ) p++;
  160618. if( p>=&aDoclist[nDoclist] ){
  160619. *pbEof = 1;
  160620. }else{
  160621. sqlite3_int64 iVar;
  160622. p += sqlite3Fts3GetVarint(p, &iVar);
  160623. *piDocid += ((bDescIdx ? -1 : 1) * iVar);
  160624. }
  160625. }
  160626. *ppIter = p;
  160627. }
  160628. /*
  160629. ** Advance the iterator pDL to the next entry in pDL->aAll/nAll. Set *pbEof
  160630. ** to true if EOF is reached.
  160631. */
  160632. static void fts3EvalDlPhraseNext(
  160633. Fts3Table *pTab,
  160634. Fts3Doclist *pDL,
  160635. u8 *pbEof
  160636. ){
  160637. char *pIter; /* Used to iterate through aAll */
  160638. char *pEnd; /* 1 byte past end of aAll */
  160639. if( pDL->pNextDocid ){
  160640. pIter = pDL->pNextDocid;
  160641. assert( pDL->aAll!=0 || pIter==0 );
  160642. }else{
  160643. pIter = pDL->aAll;
  160644. }
  160645. if( pIter==0 || pIter>=(pEnd = pDL->aAll + pDL->nAll) ){
  160646. /* We have already reached the end of this doclist. EOF. */
  160647. *pbEof = 1;
  160648. }else{
  160649. sqlite3_int64 iDelta;
  160650. pIter += sqlite3Fts3GetVarint(pIter, &iDelta);
  160651. if( pTab->bDescIdx==0 || pDL->pNextDocid==0 ){
  160652. pDL->iDocid += iDelta;
  160653. }else{
  160654. pDL->iDocid -= iDelta;
  160655. }
  160656. pDL->pList = pIter;
  160657. fts3PoslistCopy(0, &pIter);
  160658. pDL->nList = (int)(pIter - pDL->pList);
  160659. /* pIter now points just past the 0x00 that terminates the position-
  160660. ** list for document pDL->iDocid. However, if this position-list was
  160661. ** edited in place by fts3EvalNearTrim(), then pIter may not actually
  160662. ** point to the start of the next docid value. The following line deals
  160663. ** with this case by advancing pIter past the zero-padding added by
  160664. ** fts3EvalNearTrim(). */
  160665. while( pIter<pEnd && *pIter==0 ) pIter++;
  160666. pDL->pNextDocid = pIter;
  160667. assert( pIter>=&pDL->aAll[pDL->nAll] || *pIter );
  160668. *pbEof = 0;
  160669. }
  160670. }
  160671. /*
  160672. ** Helper type used by fts3EvalIncrPhraseNext() and incrPhraseTokenNext().
  160673. */
  160674. typedef struct TokenDoclist TokenDoclist;
  160675. struct TokenDoclist {
  160676. int bIgnore;
  160677. sqlite3_int64 iDocid;
  160678. char *pList;
  160679. int nList;
  160680. };
  160681. /*
  160682. ** Token pToken is an incrementally loaded token that is part of a
  160683. ** multi-token phrase. Advance it to the next matching document in the
  160684. ** database and populate output variable *p with the details of the new
  160685. ** entry. Or, if the iterator has reached EOF, set *pbEof to true.
  160686. **
  160687. ** If an error occurs, return an SQLite error code. Otherwise, return
  160688. ** SQLITE_OK.
  160689. */
  160690. static int incrPhraseTokenNext(
  160691. Fts3Table *pTab, /* Virtual table handle */
  160692. Fts3Phrase *pPhrase, /* Phrase to advance token of */
  160693. int iToken, /* Specific token to advance */
  160694. TokenDoclist *p, /* OUT: Docid and doclist for new entry */
  160695. u8 *pbEof /* OUT: True if iterator is at EOF */
  160696. ){
  160697. int rc = SQLITE_OK;
  160698. if( pPhrase->iDoclistToken==iToken ){
  160699. assert( p->bIgnore==0 );
  160700. assert( pPhrase->aToken[iToken].pSegcsr==0 );
  160701. fts3EvalDlPhraseNext(pTab, &pPhrase->doclist, pbEof);
  160702. p->pList = pPhrase->doclist.pList;
  160703. p->nList = pPhrase->doclist.nList;
  160704. p->iDocid = pPhrase->doclist.iDocid;
  160705. }else{
  160706. Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
  160707. assert( pToken->pDeferred==0 );
  160708. assert( pToken->pSegcsr || pPhrase->iDoclistToken>=0 );
  160709. if( pToken->pSegcsr ){
  160710. assert( p->bIgnore==0 );
  160711. rc = sqlite3Fts3MsrIncrNext(
  160712. pTab, pToken->pSegcsr, &p->iDocid, &p->pList, &p->nList
  160713. );
  160714. if( p->pList==0 ) *pbEof = 1;
  160715. }else{
  160716. p->bIgnore = 1;
  160717. }
  160718. }
  160719. return rc;
  160720. }
  160721. /*
  160722. ** The phrase iterator passed as the second argument:
  160723. **
  160724. ** * features at least one token that uses an incremental doclist, and
  160725. **
  160726. ** * does not contain any deferred tokens.
  160727. **
  160728. ** Advance it to the next matching documnent in the database and populate
  160729. ** the Fts3Doclist.pList and nList fields.
  160730. **
  160731. ** If there is no "next" entry and no error occurs, then *pbEof is set to
  160732. ** 1 before returning. Otherwise, if no error occurs and the iterator is
  160733. ** successfully advanced, *pbEof is set to 0.
  160734. **
  160735. ** If an error occurs, return an SQLite error code. Otherwise, return
  160736. ** SQLITE_OK.
  160737. */
  160738. static int fts3EvalIncrPhraseNext(
  160739. Fts3Cursor *pCsr, /* FTS Cursor handle */
  160740. Fts3Phrase *p, /* Phrase object to advance to next docid */
  160741. u8 *pbEof /* OUT: Set to 1 if EOF */
  160742. ){
  160743. int rc = SQLITE_OK;
  160744. Fts3Doclist *pDL = &p->doclist;
  160745. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  160746. u8 bEof = 0;
  160747. /* This is only called if it is guaranteed that the phrase has at least
  160748. ** one incremental token. In which case the bIncr flag is set. */
  160749. assert( p->bIncr==1 );
  160750. if( p->nToken==1 ){
  160751. rc = sqlite3Fts3MsrIncrNext(pTab, p->aToken[0].pSegcsr,
  160752. &pDL->iDocid, &pDL->pList, &pDL->nList
  160753. );
  160754. if( pDL->pList==0 ) bEof = 1;
  160755. }else{
  160756. int bDescDoclist = pCsr->bDesc;
  160757. struct TokenDoclist a[MAX_INCR_PHRASE_TOKENS];
  160758. memset(a, 0, sizeof(a));
  160759. assert( p->nToken<=MAX_INCR_PHRASE_TOKENS );
  160760. assert( p->iDoclistToken<MAX_INCR_PHRASE_TOKENS );
  160761. while( bEof==0 ){
  160762. int bMaxSet = 0;
  160763. sqlite3_int64 iMax = 0; /* Largest docid for all iterators */
  160764. int i; /* Used to iterate through tokens */
  160765. /* Advance the iterator for each token in the phrase once. */
  160766. for(i=0; rc==SQLITE_OK && i<p->nToken && bEof==0; i++){
  160767. rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
  160768. if( a[i].bIgnore==0 && (bMaxSet==0 || DOCID_CMP(iMax, a[i].iDocid)<0) ){
  160769. iMax = a[i].iDocid;
  160770. bMaxSet = 1;
  160771. }
  160772. }
  160773. assert( rc!=SQLITE_OK || (p->nToken>=1 && a[p->nToken-1].bIgnore==0) );
  160774. assert( rc!=SQLITE_OK || bMaxSet );
  160775. /* Keep advancing iterators until they all point to the same document */
  160776. for(i=0; i<p->nToken; i++){
  160777. while( rc==SQLITE_OK && bEof==0
  160778. && a[i].bIgnore==0 && DOCID_CMP(a[i].iDocid, iMax)<0
  160779. ){
  160780. rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
  160781. if( DOCID_CMP(a[i].iDocid, iMax)>0 ){
  160782. iMax = a[i].iDocid;
  160783. i = 0;
  160784. }
  160785. }
  160786. }
  160787. /* Check if the current entries really are a phrase match */
  160788. if( bEof==0 ){
  160789. int nList = 0;
  160790. int nByte = a[p->nToken-1].nList;
  160791. char *aDoclist = sqlite3_malloc(nByte+FTS3_BUFFER_PADDING);
  160792. if( !aDoclist ) return SQLITE_NOMEM;
  160793. memcpy(aDoclist, a[p->nToken-1].pList, nByte+1);
  160794. memset(&aDoclist[nByte], 0, FTS3_BUFFER_PADDING);
  160795. for(i=0; i<(p->nToken-1); i++){
  160796. if( a[i].bIgnore==0 ){
  160797. char *pL = a[i].pList;
  160798. char *pR = aDoclist;
  160799. char *pOut = aDoclist;
  160800. int nDist = p->nToken-1-i;
  160801. int res = fts3PoslistPhraseMerge(&pOut, nDist, 0, 1, &pL, &pR);
  160802. if( res==0 ) break;
  160803. nList = (int)(pOut - aDoclist);
  160804. }
  160805. }
  160806. if( i==(p->nToken-1) ){
  160807. pDL->iDocid = iMax;
  160808. pDL->pList = aDoclist;
  160809. pDL->nList = nList;
  160810. pDL->bFreeList = 1;
  160811. break;
  160812. }
  160813. sqlite3_free(aDoclist);
  160814. }
  160815. }
  160816. }
  160817. *pbEof = bEof;
  160818. return rc;
  160819. }
  160820. /*
  160821. ** Attempt to move the phrase iterator to point to the next matching docid.
  160822. ** If an error occurs, return an SQLite error code. Otherwise, return
  160823. ** SQLITE_OK.
  160824. **
  160825. ** If there is no "next" entry and no error occurs, then *pbEof is set to
  160826. ** 1 before returning. Otherwise, if no error occurs and the iterator is
  160827. ** successfully advanced, *pbEof is set to 0.
  160828. */
  160829. static int fts3EvalPhraseNext(
  160830. Fts3Cursor *pCsr, /* FTS Cursor handle */
  160831. Fts3Phrase *p, /* Phrase object to advance to next docid */
  160832. u8 *pbEof /* OUT: Set to 1 if EOF */
  160833. ){
  160834. int rc = SQLITE_OK;
  160835. Fts3Doclist *pDL = &p->doclist;
  160836. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  160837. if( p->bIncr ){
  160838. rc = fts3EvalIncrPhraseNext(pCsr, p, pbEof);
  160839. }else if( pCsr->bDesc!=pTab->bDescIdx && pDL->nAll ){
  160840. sqlite3Fts3DoclistPrev(pTab->bDescIdx, pDL->aAll, pDL->nAll,
  160841. &pDL->pNextDocid, &pDL->iDocid, &pDL->nList, pbEof
  160842. );
  160843. pDL->pList = pDL->pNextDocid;
  160844. }else{
  160845. fts3EvalDlPhraseNext(pTab, pDL, pbEof);
  160846. }
  160847. return rc;
  160848. }
  160849. /*
  160850. **
  160851. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  160852. ** Otherwise, fts3EvalPhraseStart() is called on all phrases within the
  160853. ** expression. Also the Fts3Expr.bDeferred variable is set to true for any
  160854. ** expressions for which all descendent tokens are deferred.
  160855. **
  160856. ** If parameter bOptOk is zero, then it is guaranteed that the
  160857. ** Fts3Phrase.doclist.aAll/nAll variables contain the entire doclist for
  160858. ** each phrase in the expression (subject to deferred token processing).
  160859. ** Or, if bOptOk is non-zero, then one or more tokens within the expression
  160860. ** may be loaded incrementally, meaning doclist.aAll/nAll is not available.
  160861. **
  160862. ** If an error occurs within this function, *pRc is set to an SQLite error
  160863. ** code before returning.
  160864. */
  160865. static void fts3EvalStartReaders(
  160866. Fts3Cursor *pCsr, /* FTS Cursor handle */
  160867. Fts3Expr *pExpr, /* Expression to initialize phrases in */
  160868. int *pRc /* IN/OUT: Error code */
  160869. ){
  160870. if( pExpr && SQLITE_OK==*pRc ){
  160871. if( pExpr->eType==FTSQUERY_PHRASE ){
  160872. int nToken = pExpr->pPhrase->nToken;
  160873. if( nToken ){
  160874. int i;
  160875. for(i=0; i<nToken; i++){
  160876. if( pExpr->pPhrase->aToken[i].pDeferred==0 ) break;
  160877. }
  160878. pExpr->bDeferred = (i==nToken);
  160879. }
  160880. *pRc = fts3EvalPhraseStart(pCsr, 1, pExpr->pPhrase);
  160881. }else{
  160882. fts3EvalStartReaders(pCsr, pExpr->pLeft, pRc);
  160883. fts3EvalStartReaders(pCsr, pExpr->pRight, pRc);
  160884. pExpr->bDeferred = (pExpr->pLeft->bDeferred && pExpr->pRight->bDeferred);
  160885. }
  160886. }
  160887. }
  160888. /*
  160889. ** An array of the following structures is assembled as part of the process
  160890. ** of selecting tokens to defer before the query starts executing (as part
  160891. ** of the xFilter() method). There is one element in the array for each
  160892. ** token in the FTS expression.
  160893. **
  160894. ** Tokens are divided into AND/NEAR clusters. All tokens in a cluster belong
  160895. ** to phrases that are connected only by AND and NEAR operators (not OR or
  160896. ** NOT). When determining tokens to defer, each AND/NEAR cluster is considered
  160897. ** separately. The root of a tokens AND/NEAR cluster is stored in
  160898. ** Fts3TokenAndCost.pRoot.
  160899. */
  160900. typedef struct Fts3TokenAndCost Fts3TokenAndCost;
  160901. struct Fts3TokenAndCost {
  160902. Fts3Phrase *pPhrase; /* The phrase the token belongs to */
  160903. int iToken; /* Position of token in phrase */
  160904. Fts3PhraseToken *pToken; /* The token itself */
  160905. Fts3Expr *pRoot; /* Root of NEAR/AND cluster */
  160906. int nOvfl; /* Number of overflow pages to load doclist */
  160907. int iCol; /* The column the token must match */
  160908. };
  160909. /*
  160910. ** This function is used to populate an allocated Fts3TokenAndCost array.
  160911. **
  160912. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  160913. ** Otherwise, if an error occurs during execution, *pRc is set to an
  160914. ** SQLite error code.
  160915. */
  160916. static void fts3EvalTokenCosts(
  160917. Fts3Cursor *pCsr, /* FTS Cursor handle */
  160918. Fts3Expr *pRoot, /* Root of current AND/NEAR cluster */
  160919. Fts3Expr *pExpr, /* Expression to consider */
  160920. Fts3TokenAndCost **ppTC, /* Write new entries to *(*ppTC)++ */
  160921. Fts3Expr ***ppOr, /* Write new OR root to *(*ppOr)++ */
  160922. int *pRc /* IN/OUT: Error code */
  160923. ){
  160924. if( *pRc==SQLITE_OK ){
  160925. if( pExpr->eType==FTSQUERY_PHRASE ){
  160926. Fts3Phrase *pPhrase = pExpr->pPhrase;
  160927. int i;
  160928. for(i=0; *pRc==SQLITE_OK && i<pPhrase->nToken; i++){
  160929. Fts3TokenAndCost *pTC = (*ppTC)++;
  160930. pTC->pPhrase = pPhrase;
  160931. pTC->iToken = i;
  160932. pTC->pRoot = pRoot;
  160933. pTC->pToken = &pPhrase->aToken[i];
  160934. pTC->iCol = pPhrase->iColumn;
  160935. *pRc = sqlite3Fts3MsrOvfl(pCsr, pTC->pToken->pSegcsr, &pTC->nOvfl);
  160936. }
  160937. }else if( pExpr->eType!=FTSQUERY_NOT ){
  160938. assert( pExpr->eType==FTSQUERY_OR
  160939. || pExpr->eType==FTSQUERY_AND
  160940. || pExpr->eType==FTSQUERY_NEAR
  160941. );
  160942. assert( pExpr->pLeft && pExpr->pRight );
  160943. if( pExpr->eType==FTSQUERY_OR ){
  160944. pRoot = pExpr->pLeft;
  160945. **ppOr = pRoot;
  160946. (*ppOr)++;
  160947. }
  160948. fts3EvalTokenCosts(pCsr, pRoot, pExpr->pLeft, ppTC, ppOr, pRc);
  160949. if( pExpr->eType==FTSQUERY_OR ){
  160950. pRoot = pExpr->pRight;
  160951. **ppOr = pRoot;
  160952. (*ppOr)++;
  160953. }
  160954. fts3EvalTokenCosts(pCsr, pRoot, pExpr->pRight, ppTC, ppOr, pRc);
  160955. }
  160956. }
  160957. }
  160958. /*
  160959. ** Determine the average document (row) size in pages. If successful,
  160960. ** write this value to *pnPage and return SQLITE_OK. Otherwise, return
  160961. ** an SQLite error code.
  160962. **
  160963. ** The average document size in pages is calculated by first calculating
  160964. ** determining the average size in bytes, B. If B is less than the amount
  160965. ** of data that will fit on a single leaf page of an intkey table in
  160966. ** this database, then the average docsize is 1. Otherwise, it is 1 plus
  160967. ** the number of overflow pages consumed by a record B bytes in size.
  160968. */
  160969. static int fts3EvalAverageDocsize(Fts3Cursor *pCsr, int *pnPage){
  160970. int rc = SQLITE_OK;
  160971. if( pCsr->nRowAvg==0 ){
  160972. /* The average document size, which is required to calculate the cost
  160973. ** of each doclist, has not yet been determined. Read the required
  160974. ** data from the %_stat table to calculate it.
  160975. **
  160976. ** Entry 0 of the %_stat table is a blob containing (nCol+1) FTS3
  160977. ** varints, where nCol is the number of columns in the FTS3 table.
  160978. ** The first varint is the number of documents currently stored in
  160979. ** the table. The following nCol varints contain the total amount of
  160980. ** data stored in all rows of each column of the table, from left
  160981. ** to right.
  160982. */
  160983. Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
  160984. sqlite3_stmt *pStmt;
  160985. sqlite3_int64 nDoc = 0;
  160986. sqlite3_int64 nByte = 0;
  160987. const char *pEnd;
  160988. const char *a;
  160989. rc = sqlite3Fts3SelectDoctotal(p, &pStmt);
  160990. if( rc!=SQLITE_OK ) return rc;
  160991. a = sqlite3_column_blob(pStmt, 0);
  160992. testcase( a==0 ); /* If %_stat.value set to X'' */
  160993. if( a ){
  160994. pEnd = &a[sqlite3_column_bytes(pStmt, 0)];
  160995. a += sqlite3Fts3GetVarintBounded(a, pEnd, &nDoc);
  160996. while( a<pEnd ){
  160997. a += sqlite3Fts3GetVarintBounded(a, pEnd, &nByte);
  160998. }
  160999. }
  161000. if( nDoc==0 || nByte==0 ){
  161001. sqlite3_reset(pStmt);
  161002. return FTS_CORRUPT_VTAB;
  161003. }
  161004. pCsr->nDoc = nDoc;
  161005. pCsr->nRowAvg = (int)(((nByte / nDoc) + p->nPgsz) / p->nPgsz);
  161006. assert( pCsr->nRowAvg>0 );
  161007. rc = sqlite3_reset(pStmt);
  161008. }
  161009. *pnPage = pCsr->nRowAvg;
  161010. return rc;
  161011. }
  161012. /*
  161013. ** This function is called to select the tokens (if any) that will be
  161014. ** deferred. The array aTC[] has already been populated when this is
  161015. ** called.
  161016. **
  161017. ** This function is called once for each AND/NEAR cluster in the
  161018. ** expression. Each invocation determines which tokens to defer within
  161019. ** the cluster with root node pRoot. See comments above the definition
  161020. ** of struct Fts3TokenAndCost for more details.
  161021. **
  161022. ** If no error occurs, SQLITE_OK is returned and sqlite3Fts3DeferToken()
  161023. ** called on each token to defer. Otherwise, an SQLite error code is
  161024. ** returned.
  161025. */
  161026. static int fts3EvalSelectDeferred(
  161027. Fts3Cursor *pCsr, /* FTS Cursor handle */
  161028. Fts3Expr *pRoot, /* Consider tokens with this root node */
  161029. Fts3TokenAndCost *aTC, /* Array of expression tokens and costs */
  161030. int nTC /* Number of entries in aTC[] */
  161031. ){
  161032. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  161033. int nDocSize = 0; /* Number of pages per doc loaded */
  161034. int rc = SQLITE_OK; /* Return code */
  161035. int ii; /* Iterator variable for various purposes */
  161036. int nOvfl = 0; /* Total overflow pages used by doclists */
  161037. int nToken = 0; /* Total number of tokens in cluster */
  161038. int nMinEst = 0; /* The minimum count for any phrase so far. */
  161039. int nLoad4 = 1; /* (Phrases that will be loaded)^4. */
  161040. /* Tokens are never deferred for FTS tables created using the content=xxx
  161041. ** option. The reason being that it is not guaranteed that the content
  161042. ** table actually contains the same data as the index. To prevent this from
  161043. ** causing any problems, the deferred token optimization is completely
  161044. ** disabled for content=xxx tables. */
  161045. if( pTab->zContentTbl ){
  161046. return SQLITE_OK;
  161047. }
  161048. /* Count the tokens in this AND/NEAR cluster. If none of the doclists
  161049. ** associated with the tokens spill onto overflow pages, or if there is
  161050. ** only 1 token, exit early. No tokens to defer in this case. */
  161051. for(ii=0; ii<nTC; ii++){
  161052. if( aTC[ii].pRoot==pRoot ){
  161053. nOvfl += aTC[ii].nOvfl;
  161054. nToken++;
  161055. }
  161056. }
  161057. if( nOvfl==0 || nToken<2 ) return SQLITE_OK;
  161058. /* Obtain the average docsize (in pages). */
  161059. rc = fts3EvalAverageDocsize(pCsr, &nDocSize);
  161060. assert( rc!=SQLITE_OK || nDocSize>0 );
  161061. /* Iterate through all tokens in this AND/NEAR cluster, in ascending order
  161062. ** of the number of overflow pages that will be loaded by the pager layer
  161063. ** to retrieve the entire doclist for the token from the full-text index.
  161064. ** Load the doclists for tokens that are either:
  161065. **
  161066. ** a. The cheapest token in the entire query (i.e. the one visited by the
  161067. ** first iteration of this loop), or
  161068. **
  161069. ** b. Part of a multi-token phrase.
  161070. **
  161071. ** After each token doclist is loaded, merge it with the others from the
  161072. ** same phrase and count the number of documents that the merged doclist
  161073. ** contains. Set variable "nMinEst" to the smallest number of documents in
  161074. ** any phrase doclist for which 1 or more token doclists have been loaded.
  161075. ** Let nOther be the number of other phrases for which it is certain that
  161076. ** one or more tokens will not be deferred.
  161077. **
  161078. ** Then, for each token, defer it if loading the doclist would result in
  161079. ** loading N or more overflow pages into memory, where N is computed as:
  161080. **
  161081. ** (nMinEst + 4^nOther - 1) / (4^nOther)
  161082. */
  161083. for(ii=0; ii<nToken && rc==SQLITE_OK; ii++){
  161084. int iTC; /* Used to iterate through aTC[] array. */
  161085. Fts3TokenAndCost *pTC = 0; /* Set to cheapest remaining token. */
  161086. /* Set pTC to point to the cheapest remaining token. */
  161087. for(iTC=0; iTC<nTC; iTC++){
  161088. if( aTC[iTC].pToken && aTC[iTC].pRoot==pRoot
  161089. && (!pTC || aTC[iTC].nOvfl<pTC->nOvfl)
  161090. ){
  161091. pTC = &aTC[iTC];
  161092. }
  161093. }
  161094. assert( pTC );
  161095. if( ii && pTC->nOvfl>=((nMinEst+(nLoad4/4)-1)/(nLoad4/4))*nDocSize ){
  161096. /* The number of overflow pages to load for this (and therefore all
  161097. ** subsequent) tokens is greater than the estimated number of pages
  161098. ** that will be loaded if all subsequent tokens are deferred.
  161099. */
  161100. Fts3PhraseToken *pToken = pTC->pToken;
  161101. rc = sqlite3Fts3DeferToken(pCsr, pToken, pTC->iCol);
  161102. fts3SegReaderCursorFree(pToken->pSegcsr);
  161103. pToken->pSegcsr = 0;
  161104. }else{
  161105. /* Set nLoad4 to the value of (4^nOther) for the next iteration of the
  161106. ** for-loop. Except, limit the value to 2^24 to prevent it from
  161107. ** overflowing the 32-bit integer it is stored in. */
  161108. if( ii<12 ) nLoad4 = nLoad4*4;
  161109. if( ii==0 || (pTC->pPhrase->nToken>1 && ii!=nToken-1) ){
  161110. /* Either this is the cheapest token in the entire query, or it is
  161111. ** part of a multi-token phrase. Either way, the entire doclist will
  161112. ** (eventually) be loaded into memory. It may as well be now. */
  161113. Fts3PhraseToken *pToken = pTC->pToken;
  161114. int nList = 0;
  161115. char *pList = 0;
  161116. rc = fts3TermSelect(pTab, pToken, pTC->iCol, &nList, &pList);
  161117. assert( rc==SQLITE_OK || pList==0 );
  161118. if( rc==SQLITE_OK ){
  161119. rc = fts3EvalPhraseMergeToken(
  161120. pTab, pTC->pPhrase, pTC->iToken,pList,nList
  161121. );
  161122. }
  161123. if( rc==SQLITE_OK ){
  161124. int nCount;
  161125. nCount = fts3DoclistCountDocids(
  161126. pTC->pPhrase->doclist.aAll, pTC->pPhrase->doclist.nAll
  161127. );
  161128. if( ii==0 || nCount<nMinEst ) nMinEst = nCount;
  161129. }
  161130. }
  161131. }
  161132. pTC->pToken = 0;
  161133. }
  161134. return rc;
  161135. }
  161136. /*
  161137. ** This function is called from within the xFilter method. It initializes
  161138. ** the full-text query currently stored in pCsr->pExpr. To iterate through
  161139. ** the results of a query, the caller does:
  161140. **
  161141. ** fts3EvalStart(pCsr);
  161142. ** while( 1 ){
  161143. ** fts3EvalNext(pCsr);
  161144. ** if( pCsr->bEof ) break;
  161145. ** ... return row pCsr->iPrevId to the caller ...
  161146. ** }
  161147. */
  161148. static int fts3EvalStart(Fts3Cursor *pCsr){
  161149. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  161150. int rc = SQLITE_OK;
  161151. int nToken = 0;
  161152. int nOr = 0;
  161153. /* Allocate a MultiSegReader for each token in the expression. */
  161154. fts3EvalAllocateReaders(pCsr, pCsr->pExpr, &nToken, &nOr, &rc);
  161155. /* Determine which, if any, tokens in the expression should be deferred. */
  161156. #ifndef SQLITE_DISABLE_FTS4_DEFERRED
  161157. if( rc==SQLITE_OK && nToken>1 && pTab->bFts4 ){
  161158. Fts3TokenAndCost *aTC;
  161159. Fts3Expr **apOr;
  161160. aTC = (Fts3TokenAndCost *)sqlite3_malloc64(
  161161. sizeof(Fts3TokenAndCost) * nToken
  161162. + sizeof(Fts3Expr *) * nOr * 2
  161163. );
  161164. apOr = (Fts3Expr **)&aTC[nToken];
  161165. if( !aTC ){
  161166. rc = SQLITE_NOMEM;
  161167. }else{
  161168. int ii;
  161169. Fts3TokenAndCost *pTC = aTC;
  161170. Fts3Expr **ppOr = apOr;
  161171. fts3EvalTokenCosts(pCsr, 0, pCsr->pExpr, &pTC, &ppOr, &rc);
  161172. nToken = (int)(pTC-aTC);
  161173. nOr = (int)(ppOr-apOr);
  161174. if( rc==SQLITE_OK ){
  161175. rc = fts3EvalSelectDeferred(pCsr, 0, aTC, nToken);
  161176. for(ii=0; rc==SQLITE_OK && ii<nOr; ii++){
  161177. rc = fts3EvalSelectDeferred(pCsr, apOr[ii], aTC, nToken);
  161178. }
  161179. }
  161180. sqlite3_free(aTC);
  161181. }
  161182. }
  161183. #endif
  161184. fts3EvalStartReaders(pCsr, pCsr->pExpr, &rc);
  161185. return rc;
  161186. }
  161187. /*
  161188. ** Invalidate the current position list for phrase pPhrase.
  161189. */
  161190. static void fts3EvalInvalidatePoslist(Fts3Phrase *pPhrase){
  161191. if( pPhrase->doclist.bFreeList ){
  161192. sqlite3_free(pPhrase->doclist.pList);
  161193. }
  161194. pPhrase->doclist.pList = 0;
  161195. pPhrase->doclist.nList = 0;
  161196. pPhrase->doclist.bFreeList = 0;
  161197. }
  161198. /*
  161199. ** This function is called to edit the position list associated with
  161200. ** the phrase object passed as the fifth argument according to a NEAR
  161201. ** condition. For example:
  161202. **
  161203. ** abc NEAR/5 "def ghi"
  161204. **
  161205. ** Parameter nNear is passed the NEAR distance of the expression (5 in
  161206. ** the example above). When this function is called, *paPoslist points to
  161207. ** the position list, and *pnToken is the number of phrase tokens in, the
  161208. ** phrase on the other side of the NEAR operator to pPhrase. For example,
  161209. ** if pPhrase refers to the "def ghi" phrase, then *paPoslist points to
  161210. ** the position list associated with phrase "abc".
  161211. **
  161212. ** All positions in the pPhrase position list that are not sufficiently
  161213. ** close to a position in the *paPoslist position list are removed. If this
  161214. ** leaves 0 positions, zero is returned. Otherwise, non-zero.
  161215. **
  161216. ** Before returning, *paPoslist is set to point to the position lsit
  161217. ** associated with pPhrase. And *pnToken is set to the number of tokens in
  161218. ** pPhrase.
  161219. */
  161220. static int fts3EvalNearTrim(
  161221. int nNear, /* NEAR distance. As in "NEAR/nNear". */
  161222. char *aTmp, /* Temporary space to use */
  161223. char **paPoslist, /* IN/OUT: Position list */
  161224. int *pnToken, /* IN/OUT: Tokens in phrase of *paPoslist */
  161225. Fts3Phrase *pPhrase /* The phrase object to trim the doclist of */
  161226. ){
  161227. int nParam1 = nNear + pPhrase->nToken;
  161228. int nParam2 = nNear + *pnToken;
  161229. int nNew;
  161230. char *p2;
  161231. char *pOut;
  161232. int res;
  161233. assert( pPhrase->doclist.pList );
  161234. p2 = pOut = pPhrase->doclist.pList;
  161235. res = fts3PoslistNearMerge(
  161236. &pOut, aTmp, nParam1, nParam2, paPoslist, &p2
  161237. );
  161238. if( res ){
  161239. nNew = (int)(pOut - pPhrase->doclist.pList) - 1;
  161240. assert( pPhrase->doclist.pList[nNew]=='\0' );
  161241. assert( nNew<=pPhrase->doclist.nList && nNew>0 );
  161242. memset(&pPhrase->doclist.pList[nNew], 0, pPhrase->doclist.nList - nNew);
  161243. pPhrase->doclist.nList = nNew;
  161244. *paPoslist = pPhrase->doclist.pList;
  161245. *pnToken = pPhrase->nToken;
  161246. }
  161247. return res;
  161248. }
  161249. /*
  161250. ** This function is a no-op if *pRc is other than SQLITE_OK when it is called.
  161251. ** Otherwise, it advances the expression passed as the second argument to
  161252. ** point to the next matching row in the database. Expressions iterate through
  161253. ** matching rows in docid order. Ascending order if Fts3Cursor.bDesc is zero,
  161254. ** or descending if it is non-zero.
  161255. **
  161256. ** If an error occurs, *pRc is set to an SQLite error code. Otherwise, if
  161257. ** successful, the following variables in pExpr are set:
  161258. **
  161259. ** Fts3Expr.bEof (non-zero if EOF - there is no next row)
  161260. ** Fts3Expr.iDocid (valid if bEof==0. The docid of the next row)
  161261. **
  161262. ** If the expression is of type FTSQUERY_PHRASE, and the expression is not
  161263. ** at EOF, then the following variables are populated with the position list
  161264. ** for the phrase for the visited row:
  161265. **
  161266. ** FTs3Expr.pPhrase->doclist.nList (length of pList in bytes)
  161267. ** FTs3Expr.pPhrase->doclist.pList (pointer to position list)
  161268. **
  161269. ** It says above that this function advances the expression to the next
  161270. ** matching row. This is usually true, but there are the following exceptions:
  161271. **
  161272. ** 1. Deferred tokens are not taken into account. If a phrase consists
  161273. ** entirely of deferred tokens, it is assumed to match every row in
  161274. ** the db. In this case the position-list is not populated at all.
  161275. **
  161276. ** Or, if a phrase contains one or more deferred tokens and one or
  161277. ** more non-deferred tokens, then the expression is advanced to the
  161278. ** next possible match, considering only non-deferred tokens. In other
  161279. ** words, if the phrase is "A B C", and "B" is deferred, the expression
  161280. ** is advanced to the next row that contains an instance of "A * C",
  161281. ** where "*" may match any single token. The position list in this case
  161282. ** is populated as for "A * C" before returning.
  161283. **
  161284. ** 2. NEAR is treated as AND. If the expression is "x NEAR y", it is
  161285. ** advanced to point to the next row that matches "x AND y".
  161286. **
  161287. ** See sqlite3Fts3EvalTestDeferred() for details on testing if a row is
  161288. ** really a match, taking into account deferred tokens and NEAR operators.
  161289. */
  161290. static void fts3EvalNextRow(
  161291. Fts3Cursor *pCsr, /* FTS Cursor handle */
  161292. Fts3Expr *pExpr, /* Expr. to advance to next matching row */
  161293. int *pRc /* IN/OUT: Error code */
  161294. ){
  161295. if( *pRc==SQLITE_OK ){
  161296. int bDescDoclist = pCsr->bDesc; /* Used by DOCID_CMP() macro */
  161297. assert( pExpr->bEof==0 );
  161298. pExpr->bStart = 1;
  161299. switch( pExpr->eType ){
  161300. case FTSQUERY_NEAR:
  161301. case FTSQUERY_AND: {
  161302. Fts3Expr *pLeft = pExpr->pLeft;
  161303. Fts3Expr *pRight = pExpr->pRight;
  161304. assert( !pLeft->bDeferred || !pRight->bDeferred );
  161305. if( pLeft->bDeferred ){
  161306. /* LHS is entirely deferred. So we assume it matches every row.
  161307. ** Advance the RHS iterator to find the next row visited. */
  161308. fts3EvalNextRow(pCsr, pRight, pRc);
  161309. pExpr->iDocid = pRight->iDocid;
  161310. pExpr->bEof = pRight->bEof;
  161311. }else if( pRight->bDeferred ){
  161312. /* RHS is entirely deferred. So we assume it matches every row.
  161313. ** Advance the LHS iterator to find the next row visited. */
  161314. fts3EvalNextRow(pCsr, pLeft, pRc);
  161315. pExpr->iDocid = pLeft->iDocid;
  161316. pExpr->bEof = pLeft->bEof;
  161317. }else{
  161318. /* Neither the RHS or LHS are deferred. */
  161319. fts3EvalNextRow(pCsr, pLeft, pRc);
  161320. fts3EvalNextRow(pCsr, pRight, pRc);
  161321. while( !pLeft->bEof && !pRight->bEof && *pRc==SQLITE_OK ){
  161322. sqlite3_int64 iDiff = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
  161323. if( iDiff==0 ) break;
  161324. if( iDiff<0 ){
  161325. fts3EvalNextRow(pCsr, pLeft, pRc);
  161326. }else{
  161327. fts3EvalNextRow(pCsr, pRight, pRc);
  161328. }
  161329. }
  161330. pExpr->iDocid = pLeft->iDocid;
  161331. pExpr->bEof = (pLeft->bEof || pRight->bEof);
  161332. if( pExpr->eType==FTSQUERY_NEAR && pExpr->bEof ){
  161333. assert( pRight->eType==FTSQUERY_PHRASE );
  161334. if( pRight->pPhrase->doclist.aAll ){
  161335. Fts3Doclist *pDl = &pRight->pPhrase->doclist;
  161336. while( *pRc==SQLITE_OK && pRight->bEof==0 ){
  161337. memset(pDl->pList, 0, pDl->nList);
  161338. fts3EvalNextRow(pCsr, pRight, pRc);
  161339. }
  161340. }
  161341. if( pLeft->pPhrase && pLeft->pPhrase->doclist.aAll ){
  161342. Fts3Doclist *pDl = &pLeft->pPhrase->doclist;
  161343. while( *pRc==SQLITE_OK && pLeft->bEof==0 ){
  161344. memset(pDl->pList, 0, pDl->nList);
  161345. fts3EvalNextRow(pCsr, pLeft, pRc);
  161346. }
  161347. }
  161348. pRight->bEof = pLeft->bEof = 1;
  161349. }
  161350. }
  161351. break;
  161352. }
  161353. case FTSQUERY_OR: {
  161354. Fts3Expr *pLeft = pExpr->pLeft;
  161355. Fts3Expr *pRight = pExpr->pRight;
  161356. sqlite3_int64 iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
  161357. assert( pLeft->bStart || pLeft->iDocid==pRight->iDocid );
  161358. assert( pRight->bStart || pLeft->iDocid==pRight->iDocid );
  161359. if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
  161360. fts3EvalNextRow(pCsr, pLeft, pRc);
  161361. }else if( pLeft->bEof || iCmp>0 ){
  161362. fts3EvalNextRow(pCsr, pRight, pRc);
  161363. }else{
  161364. fts3EvalNextRow(pCsr, pLeft, pRc);
  161365. fts3EvalNextRow(pCsr, pRight, pRc);
  161366. }
  161367. pExpr->bEof = (pLeft->bEof && pRight->bEof);
  161368. iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
  161369. if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
  161370. pExpr->iDocid = pLeft->iDocid;
  161371. }else{
  161372. pExpr->iDocid = pRight->iDocid;
  161373. }
  161374. break;
  161375. }
  161376. case FTSQUERY_NOT: {
  161377. Fts3Expr *pLeft = pExpr->pLeft;
  161378. Fts3Expr *pRight = pExpr->pRight;
  161379. if( pRight->bStart==0 ){
  161380. fts3EvalNextRow(pCsr, pRight, pRc);
  161381. assert( *pRc!=SQLITE_OK || pRight->bStart );
  161382. }
  161383. fts3EvalNextRow(pCsr, pLeft, pRc);
  161384. if( pLeft->bEof==0 ){
  161385. while( !*pRc
  161386. && !pRight->bEof
  161387. && DOCID_CMP(pLeft->iDocid, pRight->iDocid)>0
  161388. ){
  161389. fts3EvalNextRow(pCsr, pRight, pRc);
  161390. }
  161391. }
  161392. pExpr->iDocid = pLeft->iDocid;
  161393. pExpr->bEof = pLeft->bEof;
  161394. break;
  161395. }
  161396. default: {
  161397. Fts3Phrase *pPhrase = pExpr->pPhrase;
  161398. fts3EvalInvalidatePoslist(pPhrase);
  161399. *pRc = fts3EvalPhraseNext(pCsr, pPhrase, &pExpr->bEof);
  161400. pExpr->iDocid = pPhrase->doclist.iDocid;
  161401. break;
  161402. }
  161403. }
  161404. }
  161405. }
  161406. /*
  161407. ** If *pRc is not SQLITE_OK, or if pExpr is not the root node of a NEAR
  161408. ** cluster, then this function returns 1 immediately.
  161409. **
  161410. ** Otherwise, it checks if the current row really does match the NEAR
  161411. ** expression, using the data currently stored in the position lists
  161412. ** (Fts3Expr->pPhrase.doclist.pList/nList) for each phrase in the expression.
  161413. **
  161414. ** If the current row is a match, the position list associated with each
  161415. ** phrase in the NEAR expression is edited in place to contain only those
  161416. ** phrase instances sufficiently close to their peers to satisfy all NEAR
  161417. ** constraints. In this case it returns 1. If the NEAR expression does not
  161418. ** match the current row, 0 is returned. The position lists may or may not
  161419. ** be edited if 0 is returned.
  161420. */
  161421. static int fts3EvalNearTest(Fts3Expr *pExpr, int *pRc){
  161422. int res = 1;
  161423. /* The following block runs if pExpr is the root of a NEAR query.
  161424. ** For example, the query:
  161425. **
  161426. ** "w" NEAR "x" NEAR "y" NEAR "z"
  161427. **
  161428. ** which is represented in tree form as:
  161429. **
  161430. ** |
  161431. ** +--NEAR--+ <-- root of NEAR query
  161432. ** | |
  161433. ** +--NEAR--+ "z"
  161434. ** | |
  161435. ** +--NEAR--+ "y"
  161436. ** | |
  161437. ** "w" "x"
  161438. **
  161439. ** The right-hand child of a NEAR node is always a phrase. The
  161440. ** left-hand child may be either a phrase or a NEAR node. There are
  161441. ** no exceptions to this - it's the way the parser in fts3_expr.c works.
  161442. */
  161443. if( *pRc==SQLITE_OK
  161444. && pExpr->eType==FTSQUERY_NEAR
  161445. && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
  161446. ){
  161447. Fts3Expr *p;
  161448. sqlite3_int64 nTmp = 0; /* Bytes of temp space */
  161449. char *aTmp; /* Temp space for PoslistNearMerge() */
  161450. /* Allocate temporary working space. */
  161451. for(p=pExpr; p->pLeft; p=p->pLeft){
  161452. assert( p->pRight->pPhrase->doclist.nList>0 );
  161453. nTmp += p->pRight->pPhrase->doclist.nList;
  161454. }
  161455. nTmp += p->pPhrase->doclist.nList;
  161456. aTmp = sqlite3_malloc64(nTmp*2);
  161457. if( !aTmp ){
  161458. *pRc = SQLITE_NOMEM;
  161459. res = 0;
  161460. }else{
  161461. char *aPoslist = p->pPhrase->doclist.pList;
  161462. int nToken = p->pPhrase->nToken;
  161463. for(p=p->pParent;res && p && p->eType==FTSQUERY_NEAR; p=p->pParent){
  161464. Fts3Phrase *pPhrase = p->pRight->pPhrase;
  161465. int nNear = p->nNear;
  161466. res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
  161467. }
  161468. aPoslist = pExpr->pRight->pPhrase->doclist.pList;
  161469. nToken = pExpr->pRight->pPhrase->nToken;
  161470. for(p=pExpr->pLeft; p && res; p=p->pLeft){
  161471. int nNear;
  161472. Fts3Phrase *pPhrase;
  161473. assert( p->pParent && p->pParent->pLeft==p );
  161474. nNear = p->pParent->nNear;
  161475. pPhrase = (
  161476. p->eType==FTSQUERY_NEAR ? p->pRight->pPhrase : p->pPhrase
  161477. );
  161478. res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
  161479. }
  161480. }
  161481. sqlite3_free(aTmp);
  161482. }
  161483. return res;
  161484. }
  161485. /*
  161486. ** This function is a helper function for sqlite3Fts3EvalTestDeferred().
  161487. ** Assuming no error occurs or has occurred, It returns non-zero if the
  161488. ** expression passed as the second argument matches the row that pCsr
  161489. ** currently points to, or zero if it does not.
  161490. **
  161491. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  161492. ** If an error occurs during execution of this function, *pRc is set to
  161493. ** the appropriate SQLite error code. In this case the returned value is
  161494. ** undefined.
  161495. */
  161496. static int fts3EvalTestExpr(
  161497. Fts3Cursor *pCsr, /* FTS cursor handle */
  161498. Fts3Expr *pExpr, /* Expr to test. May or may not be root. */
  161499. int *pRc /* IN/OUT: Error code */
  161500. ){
  161501. int bHit = 1; /* Return value */
  161502. if( *pRc==SQLITE_OK ){
  161503. switch( pExpr->eType ){
  161504. case FTSQUERY_NEAR:
  161505. case FTSQUERY_AND:
  161506. bHit = (
  161507. fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
  161508. && fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
  161509. && fts3EvalNearTest(pExpr, pRc)
  161510. );
  161511. /* If the NEAR expression does not match any rows, zero the doclist for
  161512. ** all phrases involved in the NEAR. This is because the snippet(),
  161513. ** offsets() and matchinfo() functions are not supposed to recognize
  161514. ** any instances of phrases that are part of unmatched NEAR queries.
  161515. ** For example if this expression:
  161516. **
  161517. ** ... MATCH 'a OR (b NEAR c)'
  161518. **
  161519. ** is matched against a row containing:
  161520. **
  161521. ** 'a b d e'
  161522. **
  161523. ** then any snippet() should ony highlight the "a" term, not the "b"
  161524. ** (as "b" is part of a non-matching NEAR clause).
  161525. */
  161526. if( bHit==0
  161527. && pExpr->eType==FTSQUERY_NEAR
  161528. && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
  161529. ){
  161530. Fts3Expr *p;
  161531. for(p=pExpr; p->pPhrase==0; p=p->pLeft){
  161532. if( p->pRight->iDocid==pCsr->iPrevId ){
  161533. fts3EvalInvalidatePoslist(p->pRight->pPhrase);
  161534. }
  161535. }
  161536. if( p->iDocid==pCsr->iPrevId ){
  161537. fts3EvalInvalidatePoslist(p->pPhrase);
  161538. }
  161539. }
  161540. break;
  161541. case FTSQUERY_OR: {
  161542. int bHit1 = fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc);
  161543. int bHit2 = fts3EvalTestExpr(pCsr, pExpr->pRight, pRc);
  161544. bHit = bHit1 || bHit2;
  161545. break;
  161546. }
  161547. case FTSQUERY_NOT:
  161548. bHit = (
  161549. fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
  161550. && !fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
  161551. );
  161552. break;
  161553. default: {
  161554. #ifndef SQLITE_DISABLE_FTS4_DEFERRED
  161555. if( pCsr->pDeferred
  161556. && (pExpr->iDocid==pCsr->iPrevId || pExpr->bDeferred)
  161557. ){
  161558. Fts3Phrase *pPhrase = pExpr->pPhrase;
  161559. assert( pExpr->bDeferred || pPhrase->doclist.bFreeList==0 );
  161560. if( pExpr->bDeferred ){
  161561. fts3EvalInvalidatePoslist(pPhrase);
  161562. }
  161563. *pRc = fts3EvalDeferredPhrase(pCsr, pPhrase);
  161564. bHit = (pPhrase->doclist.pList!=0);
  161565. pExpr->iDocid = pCsr->iPrevId;
  161566. }else
  161567. #endif
  161568. {
  161569. bHit = (pExpr->bEof==0 && pExpr->iDocid==pCsr->iPrevId);
  161570. }
  161571. break;
  161572. }
  161573. }
  161574. }
  161575. return bHit;
  161576. }
  161577. /*
  161578. ** This function is called as the second part of each xNext operation when
  161579. ** iterating through the results of a full-text query. At this point the
  161580. ** cursor points to a row that matches the query expression, with the
  161581. ** following caveats:
  161582. **
  161583. ** * Up until this point, "NEAR" operators in the expression have been
  161584. ** treated as "AND".
  161585. **
  161586. ** * Deferred tokens have not yet been considered.
  161587. **
  161588. ** If *pRc is not SQLITE_OK when this function is called, it immediately
  161589. ** returns 0. Otherwise, it tests whether or not after considering NEAR
  161590. ** operators and deferred tokens the current row is still a match for the
  161591. ** expression. It returns 1 if both of the following are true:
  161592. **
  161593. ** 1. *pRc is SQLITE_OK when this function returns, and
  161594. **
  161595. ** 2. After scanning the current FTS table row for the deferred tokens,
  161596. ** it is determined that the row does *not* match the query.
  161597. **
  161598. ** Or, if no error occurs and it seems the current row does match the FTS
  161599. ** query, return 0.
  161600. */
  161601. SQLITE_PRIVATE int sqlite3Fts3EvalTestDeferred(Fts3Cursor *pCsr, int *pRc){
  161602. int rc = *pRc;
  161603. int bMiss = 0;
  161604. if( rc==SQLITE_OK ){
  161605. /* If there are one or more deferred tokens, load the current row into
  161606. ** memory and scan it to determine the position list for each deferred
  161607. ** token. Then, see if this row is really a match, considering deferred
  161608. ** tokens and NEAR operators (neither of which were taken into account
  161609. ** earlier, by fts3EvalNextRow()).
  161610. */
  161611. if( pCsr->pDeferred ){
  161612. rc = fts3CursorSeek(0, pCsr);
  161613. if( rc==SQLITE_OK ){
  161614. rc = sqlite3Fts3CacheDeferredDoclists(pCsr);
  161615. }
  161616. }
  161617. bMiss = (0==fts3EvalTestExpr(pCsr, pCsr->pExpr, &rc));
  161618. /* Free the position-lists accumulated for each deferred token above. */
  161619. sqlite3Fts3FreeDeferredDoclists(pCsr);
  161620. *pRc = rc;
  161621. }
  161622. return (rc==SQLITE_OK && bMiss);
  161623. }
  161624. /*
  161625. ** Advance to the next document that matches the FTS expression in
  161626. ** Fts3Cursor.pExpr.
  161627. */
  161628. static int fts3EvalNext(Fts3Cursor *pCsr){
  161629. int rc = SQLITE_OK; /* Return Code */
  161630. Fts3Expr *pExpr = pCsr->pExpr;
  161631. assert( pCsr->isEof==0 );
  161632. if( pExpr==0 ){
  161633. pCsr->isEof = 1;
  161634. }else{
  161635. do {
  161636. if( pCsr->isRequireSeek==0 ){
  161637. sqlite3_reset(pCsr->pStmt);
  161638. }
  161639. assert( sqlite3_data_count(pCsr->pStmt)==0 );
  161640. fts3EvalNextRow(pCsr, pExpr, &rc);
  161641. pCsr->isEof = pExpr->bEof;
  161642. pCsr->isRequireSeek = 1;
  161643. pCsr->isMatchinfoNeeded = 1;
  161644. pCsr->iPrevId = pExpr->iDocid;
  161645. }while( pCsr->isEof==0 && sqlite3Fts3EvalTestDeferred(pCsr, &rc) );
  161646. }
  161647. /* Check if the cursor is past the end of the docid range specified
  161648. ** by Fts3Cursor.iMinDocid/iMaxDocid. If so, set the EOF flag. */
  161649. if( rc==SQLITE_OK && (
  161650. (pCsr->bDesc==0 && pCsr->iPrevId>pCsr->iMaxDocid)
  161651. || (pCsr->bDesc!=0 && pCsr->iPrevId<pCsr->iMinDocid)
  161652. )){
  161653. pCsr->isEof = 1;
  161654. }
  161655. return rc;
  161656. }
  161657. /*
  161658. ** Restart interation for expression pExpr so that the next call to
  161659. ** fts3EvalNext() visits the first row. Do not allow incremental
  161660. ** loading or merging of phrase doclists for this iteration.
  161661. **
  161662. ** If *pRc is other than SQLITE_OK when this function is called, it is
  161663. ** a no-op. If an error occurs within this function, *pRc is set to an
  161664. ** SQLite error code before returning.
  161665. */
  161666. static void fts3EvalRestart(
  161667. Fts3Cursor *pCsr,
  161668. Fts3Expr *pExpr,
  161669. int *pRc
  161670. ){
  161671. if( pExpr && *pRc==SQLITE_OK ){
  161672. Fts3Phrase *pPhrase = pExpr->pPhrase;
  161673. if( pPhrase ){
  161674. fts3EvalInvalidatePoslist(pPhrase);
  161675. if( pPhrase->bIncr ){
  161676. int i;
  161677. for(i=0; i<pPhrase->nToken; i++){
  161678. Fts3PhraseToken *pToken = &pPhrase->aToken[i];
  161679. assert( pToken->pDeferred==0 );
  161680. if( pToken->pSegcsr ){
  161681. sqlite3Fts3MsrIncrRestart(pToken->pSegcsr);
  161682. }
  161683. }
  161684. *pRc = fts3EvalPhraseStart(pCsr, 0, pPhrase);
  161685. }
  161686. pPhrase->doclist.pNextDocid = 0;
  161687. pPhrase->doclist.iDocid = 0;
  161688. pPhrase->pOrPoslist = 0;
  161689. }
  161690. pExpr->iDocid = 0;
  161691. pExpr->bEof = 0;
  161692. pExpr->bStart = 0;
  161693. fts3EvalRestart(pCsr, pExpr->pLeft, pRc);
  161694. fts3EvalRestart(pCsr, pExpr->pRight, pRc);
  161695. }
  161696. }
  161697. /*
  161698. ** After allocating the Fts3Expr.aMI[] array for each phrase in the
  161699. ** expression rooted at pExpr, the cursor iterates through all rows matched
  161700. ** by pExpr, calling this function for each row. This function increments
  161701. ** the values in Fts3Expr.aMI[] according to the position-list currently
  161702. ** found in Fts3Expr.pPhrase->doclist.pList for each of the phrase
  161703. ** expression nodes.
  161704. */
  161705. static void fts3EvalUpdateCounts(Fts3Expr *pExpr, int nCol){
  161706. if( pExpr ){
  161707. Fts3Phrase *pPhrase = pExpr->pPhrase;
  161708. if( pPhrase && pPhrase->doclist.pList ){
  161709. int iCol = 0;
  161710. char *p = pPhrase->doclist.pList;
  161711. do{
  161712. u8 c = 0;
  161713. int iCnt = 0;
  161714. while( 0xFE & (*p | c) ){
  161715. if( (c&0x80)==0 ) iCnt++;
  161716. c = *p++ & 0x80;
  161717. }
  161718. /* aMI[iCol*3 + 1] = Number of occurrences
  161719. ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
  161720. */
  161721. pExpr->aMI[iCol*3 + 1] += iCnt;
  161722. pExpr->aMI[iCol*3 + 2] += (iCnt>0);
  161723. if( *p==0x00 ) break;
  161724. p++;
  161725. p += fts3GetVarint32(p, &iCol);
  161726. }while( iCol<nCol );
  161727. }
  161728. fts3EvalUpdateCounts(pExpr->pLeft, nCol);
  161729. fts3EvalUpdateCounts(pExpr->pRight, nCol);
  161730. }
  161731. }
  161732. /*
  161733. ** Expression pExpr must be of type FTSQUERY_PHRASE.
  161734. **
  161735. ** If it is not already allocated and populated, this function allocates and
  161736. ** populates the Fts3Expr.aMI[] array for expression pExpr. If pExpr is part
  161737. ** of a NEAR expression, then it also allocates and populates the same array
  161738. ** for all other phrases that are part of the NEAR expression.
  161739. **
  161740. ** SQLITE_OK is returned if the aMI[] array is successfully allocated and
  161741. ** populated. Otherwise, if an error occurs, an SQLite error code is returned.
  161742. */
  161743. static int fts3EvalGatherStats(
  161744. Fts3Cursor *pCsr, /* Cursor object */
  161745. Fts3Expr *pExpr /* FTSQUERY_PHRASE expression */
  161746. ){
  161747. int rc = SQLITE_OK; /* Return code */
  161748. assert( pExpr->eType==FTSQUERY_PHRASE );
  161749. if( pExpr->aMI==0 ){
  161750. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  161751. Fts3Expr *pRoot; /* Root of NEAR expression */
  161752. Fts3Expr *p; /* Iterator used for several purposes */
  161753. sqlite3_int64 iPrevId = pCsr->iPrevId;
  161754. sqlite3_int64 iDocid;
  161755. u8 bEof;
  161756. /* Find the root of the NEAR expression */
  161757. pRoot = pExpr;
  161758. while( pRoot->pParent && pRoot->pParent->eType==FTSQUERY_NEAR ){
  161759. pRoot = pRoot->pParent;
  161760. }
  161761. iDocid = pRoot->iDocid;
  161762. bEof = pRoot->bEof;
  161763. assert( pRoot->bStart );
  161764. /* Allocate space for the aMSI[] array of each FTSQUERY_PHRASE node */
  161765. for(p=pRoot; p; p=p->pLeft){
  161766. Fts3Expr *pE = (p->eType==FTSQUERY_PHRASE?p:p->pRight);
  161767. assert( pE->aMI==0 );
  161768. pE->aMI = (u32 *)sqlite3_malloc64(pTab->nColumn * 3 * sizeof(u32));
  161769. if( !pE->aMI ) return SQLITE_NOMEM;
  161770. memset(pE->aMI, 0, pTab->nColumn * 3 * sizeof(u32));
  161771. }
  161772. fts3EvalRestart(pCsr, pRoot, &rc);
  161773. while( pCsr->isEof==0 && rc==SQLITE_OK ){
  161774. do {
  161775. /* Ensure the %_content statement is reset. */
  161776. if( pCsr->isRequireSeek==0 ) sqlite3_reset(pCsr->pStmt);
  161777. assert( sqlite3_data_count(pCsr->pStmt)==0 );
  161778. /* Advance to the next document */
  161779. fts3EvalNextRow(pCsr, pRoot, &rc);
  161780. pCsr->isEof = pRoot->bEof;
  161781. pCsr->isRequireSeek = 1;
  161782. pCsr->isMatchinfoNeeded = 1;
  161783. pCsr->iPrevId = pRoot->iDocid;
  161784. }while( pCsr->isEof==0
  161785. && pRoot->eType==FTSQUERY_NEAR
  161786. && sqlite3Fts3EvalTestDeferred(pCsr, &rc)
  161787. );
  161788. if( rc==SQLITE_OK && pCsr->isEof==0 ){
  161789. fts3EvalUpdateCounts(pRoot, pTab->nColumn);
  161790. }
  161791. }
  161792. pCsr->isEof = 0;
  161793. pCsr->iPrevId = iPrevId;
  161794. if( bEof ){
  161795. pRoot->bEof = bEof;
  161796. }else{
  161797. /* Caution: pRoot may iterate through docids in ascending or descending
  161798. ** order. For this reason, even though it seems more defensive, the
  161799. ** do loop can not be written:
  161800. **
  161801. ** do {...} while( pRoot->iDocid<iDocid && rc==SQLITE_OK );
  161802. */
  161803. fts3EvalRestart(pCsr, pRoot, &rc);
  161804. do {
  161805. fts3EvalNextRow(pCsr, pRoot, &rc);
  161806. assert( pRoot->bEof==0 );
  161807. }while( pRoot->iDocid!=iDocid && rc==SQLITE_OK );
  161808. }
  161809. }
  161810. return rc;
  161811. }
  161812. /*
  161813. ** This function is used by the matchinfo() module to query a phrase
  161814. ** expression node for the following information:
  161815. **
  161816. ** 1. The total number of occurrences of the phrase in each column of
  161817. ** the FTS table (considering all rows), and
  161818. **
  161819. ** 2. For each column, the number of rows in the table for which the
  161820. ** column contains at least one instance of the phrase.
  161821. **
  161822. ** If no error occurs, SQLITE_OK is returned and the values for each column
  161823. ** written into the array aiOut as follows:
  161824. **
  161825. ** aiOut[iCol*3 + 1] = Number of occurrences
  161826. ** aiOut[iCol*3 + 2] = Number of rows containing at least one instance
  161827. **
  161828. ** Caveats:
  161829. **
  161830. ** * If a phrase consists entirely of deferred tokens, then all output
  161831. ** values are set to the number of documents in the table. In other
  161832. ** words we assume that very common tokens occur exactly once in each
  161833. ** column of each row of the table.
  161834. **
  161835. ** * If a phrase contains some deferred tokens (and some non-deferred
  161836. ** tokens), count the potential occurrence identified by considering
  161837. ** the non-deferred tokens instead of actual phrase occurrences.
  161838. **
  161839. ** * If the phrase is part of a NEAR expression, then only phrase instances
  161840. ** that meet the NEAR constraint are included in the counts.
  161841. */
  161842. SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(
  161843. Fts3Cursor *pCsr, /* FTS cursor handle */
  161844. Fts3Expr *pExpr, /* Phrase expression */
  161845. u32 *aiOut /* Array to write results into (see above) */
  161846. ){
  161847. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  161848. int rc = SQLITE_OK;
  161849. int iCol;
  161850. if( pExpr->bDeferred && pExpr->pParent->eType!=FTSQUERY_NEAR ){
  161851. assert( pCsr->nDoc>0 );
  161852. for(iCol=0; iCol<pTab->nColumn; iCol++){
  161853. aiOut[iCol*3 + 1] = (u32)pCsr->nDoc;
  161854. aiOut[iCol*3 + 2] = (u32)pCsr->nDoc;
  161855. }
  161856. }else{
  161857. rc = fts3EvalGatherStats(pCsr, pExpr);
  161858. if( rc==SQLITE_OK ){
  161859. assert( pExpr->aMI );
  161860. for(iCol=0; iCol<pTab->nColumn; iCol++){
  161861. aiOut[iCol*3 + 1] = pExpr->aMI[iCol*3 + 1];
  161862. aiOut[iCol*3 + 2] = pExpr->aMI[iCol*3 + 2];
  161863. }
  161864. }
  161865. }
  161866. return rc;
  161867. }
  161868. /*
  161869. ** The expression pExpr passed as the second argument to this function
  161870. ** must be of type FTSQUERY_PHRASE.
  161871. **
  161872. ** The returned value is either NULL or a pointer to a buffer containing
  161873. ** a position-list indicating the occurrences of the phrase in column iCol
  161874. ** of the current row.
  161875. **
  161876. ** More specifically, the returned buffer contains 1 varint for each
  161877. ** occurrence of the phrase in the column, stored using the normal (delta+2)
  161878. ** compression and is terminated by either an 0x01 or 0x00 byte. For example,
  161879. ** if the requested column contains "a b X c d X X" and the position-list
  161880. ** for 'X' is requested, the buffer returned may contain:
  161881. **
  161882. ** 0x04 0x05 0x03 0x01 or 0x04 0x05 0x03 0x00
  161883. **
  161884. ** This function works regardless of whether or not the phrase is deferred,
  161885. ** incremental, or neither.
  161886. */
  161887. SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(
  161888. Fts3Cursor *pCsr, /* FTS3 cursor object */
  161889. Fts3Expr *pExpr, /* Phrase to return doclist for */
  161890. int iCol, /* Column to return position list for */
  161891. char **ppOut /* OUT: Pointer to position list */
  161892. ){
  161893. Fts3Phrase *pPhrase = pExpr->pPhrase;
  161894. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  161895. char *pIter;
  161896. int iThis;
  161897. sqlite3_int64 iDocid;
  161898. /* If this phrase is applies specifically to some column other than
  161899. ** column iCol, return a NULL pointer. */
  161900. *ppOut = 0;
  161901. assert( iCol>=0 && iCol<pTab->nColumn );
  161902. if( (pPhrase->iColumn<pTab->nColumn && pPhrase->iColumn!=iCol) ){
  161903. return SQLITE_OK;
  161904. }
  161905. iDocid = pExpr->iDocid;
  161906. pIter = pPhrase->doclist.pList;
  161907. if( iDocid!=pCsr->iPrevId || pExpr->bEof ){
  161908. int rc = SQLITE_OK;
  161909. int bDescDoclist = pTab->bDescIdx; /* For DOCID_CMP macro */
  161910. int bOr = 0;
  161911. u8 bTreeEof = 0;
  161912. Fts3Expr *p; /* Used to iterate from pExpr to root */
  161913. Fts3Expr *pNear; /* Most senior NEAR ancestor (or pExpr) */
  161914. int bMatch;
  161915. /* Check if this phrase descends from an OR expression node. If not,
  161916. ** return NULL. Otherwise, the entry that corresponds to docid
  161917. ** pCsr->iPrevId may lie earlier in the doclist buffer. Or, if the
  161918. ** tree that the node is part of has been marked as EOF, but the node
  161919. ** itself is not EOF, then it may point to an earlier entry. */
  161920. pNear = pExpr;
  161921. for(p=pExpr->pParent; p; p=p->pParent){
  161922. if( p->eType==FTSQUERY_OR ) bOr = 1;
  161923. if( p->eType==FTSQUERY_NEAR ) pNear = p;
  161924. if( p->bEof ) bTreeEof = 1;
  161925. }
  161926. if( bOr==0 ) return SQLITE_OK;
  161927. /* This is the descendent of an OR node. In this case we cannot use
  161928. ** an incremental phrase. Load the entire doclist for the phrase
  161929. ** into memory in this case. */
  161930. if( pPhrase->bIncr ){
  161931. int bEofSave = pNear->bEof;
  161932. fts3EvalRestart(pCsr, pNear, &rc);
  161933. while( rc==SQLITE_OK && !pNear->bEof ){
  161934. fts3EvalNextRow(pCsr, pNear, &rc);
  161935. if( bEofSave==0 && pNear->iDocid==iDocid ) break;
  161936. }
  161937. assert( rc!=SQLITE_OK || pPhrase->bIncr==0 );
  161938. }
  161939. if( bTreeEof ){
  161940. while( rc==SQLITE_OK && !pNear->bEof ){
  161941. fts3EvalNextRow(pCsr, pNear, &rc);
  161942. }
  161943. }
  161944. if( rc!=SQLITE_OK ) return rc;
  161945. bMatch = 1;
  161946. for(p=pNear; p; p=p->pLeft){
  161947. u8 bEof = 0;
  161948. Fts3Expr *pTest = p;
  161949. Fts3Phrase *pPh;
  161950. assert( pTest->eType==FTSQUERY_NEAR || pTest->eType==FTSQUERY_PHRASE );
  161951. if( pTest->eType==FTSQUERY_NEAR ) pTest = pTest->pRight;
  161952. assert( pTest->eType==FTSQUERY_PHRASE );
  161953. pPh = pTest->pPhrase;
  161954. pIter = pPh->pOrPoslist;
  161955. iDocid = pPh->iOrDocid;
  161956. if( pCsr->bDesc==bDescDoclist ){
  161957. bEof = !pPh->doclist.nAll ||
  161958. (pIter >= (pPh->doclist.aAll + pPh->doclist.nAll));
  161959. while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)<0 ) && bEof==0 ){
  161960. sqlite3Fts3DoclistNext(
  161961. bDescDoclist, pPh->doclist.aAll, pPh->doclist.nAll,
  161962. &pIter, &iDocid, &bEof
  161963. );
  161964. }
  161965. }else{
  161966. bEof = !pPh->doclist.nAll || (pIter && pIter<=pPh->doclist.aAll);
  161967. while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)>0 ) && bEof==0 ){
  161968. int dummy;
  161969. sqlite3Fts3DoclistPrev(
  161970. bDescDoclist, pPh->doclist.aAll, pPh->doclist.nAll,
  161971. &pIter, &iDocid, &dummy, &bEof
  161972. );
  161973. }
  161974. }
  161975. pPh->pOrPoslist = pIter;
  161976. pPh->iOrDocid = iDocid;
  161977. if( bEof || iDocid!=pCsr->iPrevId ) bMatch = 0;
  161978. }
  161979. if( bMatch ){
  161980. pIter = pPhrase->pOrPoslist;
  161981. }else{
  161982. pIter = 0;
  161983. }
  161984. }
  161985. if( pIter==0 ) return SQLITE_OK;
  161986. if( *pIter==0x01 ){
  161987. pIter++;
  161988. pIter += fts3GetVarint32(pIter, &iThis);
  161989. }else{
  161990. iThis = 0;
  161991. }
  161992. while( iThis<iCol ){
  161993. fts3ColumnlistCopy(0, &pIter);
  161994. if( *pIter==0x00 ) return SQLITE_OK;
  161995. pIter++;
  161996. pIter += fts3GetVarint32(pIter, &iThis);
  161997. }
  161998. if( *pIter==0x00 ){
  161999. pIter = 0;
  162000. }
  162001. *ppOut = ((iCol==iThis)?pIter:0);
  162002. return SQLITE_OK;
  162003. }
  162004. /*
  162005. ** Free all components of the Fts3Phrase structure that were allocated by
  162006. ** the eval module. Specifically, this means to free:
  162007. **
  162008. ** * the contents of pPhrase->doclist, and
  162009. ** * any Fts3MultiSegReader objects held by phrase tokens.
  162010. */
  162011. SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *pPhrase){
  162012. if( pPhrase ){
  162013. int i;
  162014. sqlite3_free(pPhrase->doclist.aAll);
  162015. fts3EvalInvalidatePoslist(pPhrase);
  162016. memset(&pPhrase->doclist, 0, sizeof(Fts3Doclist));
  162017. for(i=0; i<pPhrase->nToken; i++){
  162018. fts3SegReaderCursorFree(pPhrase->aToken[i].pSegcsr);
  162019. pPhrase->aToken[i].pSegcsr = 0;
  162020. }
  162021. }
  162022. }
  162023. /*
  162024. ** Return SQLITE_CORRUPT_VTAB.
  162025. */
  162026. #ifdef SQLITE_DEBUG
  162027. SQLITE_PRIVATE int sqlite3Fts3Corrupt(){
  162028. return SQLITE_CORRUPT_VTAB;
  162029. }
  162030. #endif
  162031. #if !SQLITE_CORE
  162032. /*
  162033. ** Initialize API pointer table, if required.
  162034. */
  162035. #ifdef _WIN32
  162036. __declspec(dllexport)
  162037. #endif
  162038. SQLITE_API int sqlite3_fts3_init(
  162039. sqlite3 *db,
  162040. char **pzErrMsg,
  162041. const sqlite3_api_routines *pApi
  162042. ){
  162043. SQLITE_EXTENSION_INIT2(pApi)
  162044. return sqlite3Fts3Init(db);
  162045. }
  162046. #endif
  162047. #endif
  162048. /************** End of fts3.c ************************************************/
  162049. /************** Begin file fts3_aux.c ****************************************/
  162050. /*
  162051. ** 2011 Jan 27
  162052. **
  162053. ** The author disclaims copyright to this source code. In place of
  162054. ** a legal notice, here is a blessing:
  162055. **
  162056. ** May you do good and not evil.
  162057. ** May you find forgiveness for yourself and forgive others.
  162058. ** May you share freely, never taking more than you give.
  162059. **
  162060. ******************************************************************************
  162061. **
  162062. */
  162063. /* #include "fts3Int.h" */
  162064. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  162065. /* #include <string.h> */
  162066. /* #include <assert.h> */
  162067. typedef struct Fts3auxTable Fts3auxTable;
  162068. typedef struct Fts3auxCursor Fts3auxCursor;
  162069. struct Fts3auxTable {
  162070. sqlite3_vtab base; /* Base class used by SQLite core */
  162071. Fts3Table *pFts3Tab;
  162072. };
  162073. struct Fts3auxCursor {
  162074. sqlite3_vtab_cursor base; /* Base class used by SQLite core */
  162075. Fts3MultiSegReader csr; /* Must be right after "base" */
  162076. Fts3SegFilter filter;
  162077. char *zStop;
  162078. int nStop; /* Byte-length of string zStop */
  162079. int iLangid; /* Language id to query */
  162080. int isEof; /* True if cursor is at EOF */
  162081. sqlite3_int64 iRowid; /* Current rowid */
  162082. int iCol; /* Current value of 'col' column */
  162083. int nStat; /* Size of aStat[] array */
  162084. struct Fts3auxColstats {
  162085. sqlite3_int64 nDoc; /* 'documents' values for current csr row */
  162086. sqlite3_int64 nOcc; /* 'occurrences' values for current csr row */
  162087. } *aStat;
  162088. };
  162089. /*
  162090. ** Schema of the terms table.
  162091. */
  162092. #define FTS3_AUX_SCHEMA \
  162093. "CREATE TABLE x(term, col, documents, occurrences, languageid HIDDEN)"
  162094. /*
  162095. ** This function does all the work for both the xConnect and xCreate methods.
  162096. ** These tables have no persistent representation of their own, so xConnect
  162097. ** and xCreate are identical operations.
  162098. */
  162099. static int fts3auxConnectMethod(
  162100. sqlite3 *db, /* Database connection */
  162101. void *pUnused, /* Unused */
  162102. int argc, /* Number of elements in argv array */
  162103. const char * const *argv, /* xCreate/xConnect argument array */
  162104. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  162105. char **pzErr /* OUT: sqlite3_malloc'd error message */
  162106. ){
  162107. char const *zDb; /* Name of database (e.g. "main") */
  162108. char const *zFts3; /* Name of fts3 table */
  162109. int nDb; /* Result of strlen(zDb) */
  162110. int nFts3; /* Result of strlen(zFts3) */
  162111. sqlite3_int64 nByte; /* Bytes of space to allocate here */
  162112. int rc; /* value returned by declare_vtab() */
  162113. Fts3auxTable *p; /* Virtual table object to return */
  162114. UNUSED_PARAMETER(pUnused);
  162115. /* The user should invoke this in one of two forms:
  162116. **
  162117. ** CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table);
  162118. ** CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table-db, fts4-table);
  162119. */
  162120. if( argc!=4 && argc!=5 ) goto bad_args;
  162121. zDb = argv[1];
  162122. nDb = (int)strlen(zDb);
  162123. if( argc==5 ){
  162124. if( nDb==4 && 0==sqlite3_strnicmp("temp", zDb, 4) ){
  162125. zDb = argv[3];
  162126. nDb = (int)strlen(zDb);
  162127. zFts3 = argv[4];
  162128. }else{
  162129. goto bad_args;
  162130. }
  162131. }else{
  162132. zFts3 = argv[3];
  162133. }
  162134. nFts3 = (int)strlen(zFts3);
  162135. rc = sqlite3_declare_vtab(db, FTS3_AUX_SCHEMA);
  162136. if( rc!=SQLITE_OK ) return rc;
  162137. nByte = sizeof(Fts3auxTable) + sizeof(Fts3Table) + nDb + nFts3 + 2;
  162138. p = (Fts3auxTable *)sqlite3_malloc64(nByte);
  162139. if( !p ) return SQLITE_NOMEM;
  162140. memset(p, 0, nByte);
  162141. p->pFts3Tab = (Fts3Table *)&p[1];
  162142. p->pFts3Tab->zDb = (char *)&p->pFts3Tab[1];
  162143. p->pFts3Tab->zName = &p->pFts3Tab->zDb[nDb+1];
  162144. p->pFts3Tab->db = db;
  162145. p->pFts3Tab->nIndex = 1;
  162146. memcpy((char *)p->pFts3Tab->zDb, zDb, nDb);
  162147. memcpy((char *)p->pFts3Tab->zName, zFts3, nFts3);
  162148. sqlite3Fts3Dequote((char *)p->pFts3Tab->zName);
  162149. *ppVtab = (sqlite3_vtab *)p;
  162150. return SQLITE_OK;
  162151. bad_args:
  162152. sqlite3Fts3ErrMsg(pzErr, "invalid arguments to fts4aux constructor");
  162153. return SQLITE_ERROR;
  162154. }
  162155. /*
  162156. ** This function does the work for both the xDisconnect and xDestroy methods.
  162157. ** These tables have no persistent representation of their own, so xDisconnect
  162158. ** and xDestroy are identical operations.
  162159. */
  162160. static int fts3auxDisconnectMethod(sqlite3_vtab *pVtab){
  162161. Fts3auxTable *p = (Fts3auxTable *)pVtab;
  162162. Fts3Table *pFts3 = p->pFts3Tab;
  162163. int i;
  162164. /* Free any prepared statements held */
  162165. for(i=0; i<SizeofArray(pFts3->aStmt); i++){
  162166. sqlite3_finalize(pFts3->aStmt[i]);
  162167. }
  162168. sqlite3_free(pFts3->zSegmentsTbl);
  162169. sqlite3_free(p);
  162170. return SQLITE_OK;
  162171. }
  162172. #define FTS4AUX_EQ_CONSTRAINT 1
  162173. #define FTS4AUX_GE_CONSTRAINT 2
  162174. #define FTS4AUX_LE_CONSTRAINT 4
  162175. /*
  162176. ** xBestIndex - Analyze a WHERE and ORDER BY clause.
  162177. */
  162178. static int fts3auxBestIndexMethod(
  162179. sqlite3_vtab *pVTab,
  162180. sqlite3_index_info *pInfo
  162181. ){
  162182. int i;
  162183. int iEq = -1;
  162184. int iGe = -1;
  162185. int iLe = -1;
  162186. int iLangid = -1;
  162187. int iNext = 1; /* Next free argvIndex value */
  162188. UNUSED_PARAMETER(pVTab);
  162189. /* This vtab delivers always results in "ORDER BY term ASC" order. */
  162190. if( pInfo->nOrderBy==1
  162191. && pInfo->aOrderBy[0].iColumn==0
  162192. && pInfo->aOrderBy[0].desc==0
  162193. ){
  162194. pInfo->orderByConsumed = 1;
  162195. }
  162196. /* Search for equality and range constraints on the "term" column.
  162197. ** And equality constraints on the hidden "languageid" column. */
  162198. for(i=0; i<pInfo->nConstraint; i++){
  162199. if( pInfo->aConstraint[i].usable ){
  162200. int op = pInfo->aConstraint[i].op;
  162201. int iCol = pInfo->aConstraint[i].iColumn;
  162202. if( iCol==0 ){
  162203. if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iEq = i;
  162204. if( op==SQLITE_INDEX_CONSTRAINT_LT ) iLe = i;
  162205. if( op==SQLITE_INDEX_CONSTRAINT_LE ) iLe = i;
  162206. if( op==SQLITE_INDEX_CONSTRAINT_GT ) iGe = i;
  162207. if( op==SQLITE_INDEX_CONSTRAINT_GE ) iGe = i;
  162208. }
  162209. if( iCol==4 ){
  162210. if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iLangid = i;
  162211. }
  162212. }
  162213. }
  162214. if( iEq>=0 ){
  162215. pInfo->idxNum = FTS4AUX_EQ_CONSTRAINT;
  162216. pInfo->aConstraintUsage[iEq].argvIndex = iNext++;
  162217. pInfo->estimatedCost = 5;
  162218. }else{
  162219. pInfo->idxNum = 0;
  162220. pInfo->estimatedCost = 20000;
  162221. if( iGe>=0 ){
  162222. pInfo->idxNum += FTS4AUX_GE_CONSTRAINT;
  162223. pInfo->aConstraintUsage[iGe].argvIndex = iNext++;
  162224. pInfo->estimatedCost /= 2;
  162225. }
  162226. if( iLe>=0 ){
  162227. pInfo->idxNum += FTS4AUX_LE_CONSTRAINT;
  162228. pInfo->aConstraintUsage[iLe].argvIndex = iNext++;
  162229. pInfo->estimatedCost /= 2;
  162230. }
  162231. }
  162232. if( iLangid>=0 ){
  162233. pInfo->aConstraintUsage[iLangid].argvIndex = iNext++;
  162234. pInfo->estimatedCost--;
  162235. }
  162236. return SQLITE_OK;
  162237. }
  162238. /*
  162239. ** xOpen - Open a cursor.
  162240. */
  162241. static int fts3auxOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
  162242. Fts3auxCursor *pCsr; /* Pointer to cursor object to return */
  162243. UNUSED_PARAMETER(pVTab);
  162244. pCsr = (Fts3auxCursor *)sqlite3_malloc(sizeof(Fts3auxCursor));
  162245. if( !pCsr ) return SQLITE_NOMEM;
  162246. memset(pCsr, 0, sizeof(Fts3auxCursor));
  162247. *ppCsr = (sqlite3_vtab_cursor *)pCsr;
  162248. return SQLITE_OK;
  162249. }
  162250. /*
  162251. ** xClose - Close a cursor.
  162252. */
  162253. static int fts3auxCloseMethod(sqlite3_vtab_cursor *pCursor){
  162254. Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
  162255. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  162256. sqlite3Fts3SegmentsClose(pFts3);
  162257. sqlite3Fts3SegReaderFinish(&pCsr->csr);
  162258. sqlite3_free((void *)pCsr->filter.zTerm);
  162259. sqlite3_free(pCsr->zStop);
  162260. sqlite3_free(pCsr->aStat);
  162261. sqlite3_free(pCsr);
  162262. return SQLITE_OK;
  162263. }
  162264. static int fts3auxGrowStatArray(Fts3auxCursor *pCsr, int nSize){
  162265. if( nSize>pCsr->nStat ){
  162266. struct Fts3auxColstats *aNew;
  162267. aNew = (struct Fts3auxColstats *)sqlite3_realloc64(pCsr->aStat,
  162268. sizeof(struct Fts3auxColstats) * nSize
  162269. );
  162270. if( aNew==0 ) return SQLITE_NOMEM;
  162271. memset(&aNew[pCsr->nStat], 0,
  162272. sizeof(struct Fts3auxColstats) * (nSize - pCsr->nStat)
  162273. );
  162274. pCsr->aStat = aNew;
  162275. pCsr->nStat = nSize;
  162276. }
  162277. return SQLITE_OK;
  162278. }
  162279. /*
  162280. ** xNext - Advance the cursor to the next row, if any.
  162281. */
  162282. static int fts3auxNextMethod(sqlite3_vtab_cursor *pCursor){
  162283. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  162284. Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
  162285. int rc;
  162286. /* Increment our pretend rowid value. */
  162287. pCsr->iRowid++;
  162288. for(pCsr->iCol++; pCsr->iCol<pCsr->nStat; pCsr->iCol++){
  162289. if( pCsr->aStat[pCsr->iCol].nDoc>0 ) return SQLITE_OK;
  162290. }
  162291. rc = sqlite3Fts3SegReaderStep(pFts3, &pCsr->csr);
  162292. if( rc==SQLITE_ROW ){
  162293. int i = 0;
  162294. int nDoclist = pCsr->csr.nDoclist;
  162295. char *aDoclist = pCsr->csr.aDoclist;
  162296. int iCol;
  162297. int eState = 0;
  162298. if( pCsr->zStop ){
  162299. int n = (pCsr->nStop<pCsr->csr.nTerm) ? pCsr->nStop : pCsr->csr.nTerm;
  162300. int mc = memcmp(pCsr->zStop, pCsr->csr.zTerm, n);
  162301. if( mc<0 || (mc==0 && pCsr->csr.nTerm>pCsr->nStop) ){
  162302. pCsr->isEof = 1;
  162303. return SQLITE_OK;
  162304. }
  162305. }
  162306. if( fts3auxGrowStatArray(pCsr, 2) ) return SQLITE_NOMEM;
  162307. memset(pCsr->aStat, 0, sizeof(struct Fts3auxColstats) * pCsr->nStat);
  162308. iCol = 0;
  162309. while( i<nDoclist ){
  162310. sqlite3_int64 v = 0;
  162311. i += sqlite3Fts3GetVarint(&aDoclist[i], &v);
  162312. switch( eState ){
  162313. /* State 0. In this state the integer just read was a docid. */
  162314. case 0:
  162315. pCsr->aStat[0].nDoc++;
  162316. eState = 1;
  162317. iCol = 0;
  162318. break;
  162319. /* State 1. In this state we are expecting either a 1, indicating
  162320. ** that the following integer will be a column number, or the
  162321. ** start of a position list for column 0.
  162322. **
  162323. ** The only difference between state 1 and state 2 is that if the
  162324. ** integer encountered in state 1 is not 0 or 1, then we need to
  162325. ** increment the column 0 "nDoc" count for this term.
  162326. */
  162327. case 1:
  162328. assert( iCol==0 );
  162329. if( v>1 ){
  162330. pCsr->aStat[1].nDoc++;
  162331. }
  162332. eState = 2;
  162333. /* fall through */
  162334. case 2:
  162335. if( v==0 ){ /* 0x00. Next integer will be a docid. */
  162336. eState = 0;
  162337. }else if( v==1 ){ /* 0x01. Next integer will be a column number. */
  162338. eState = 3;
  162339. }else{ /* 2 or greater. A position. */
  162340. pCsr->aStat[iCol+1].nOcc++;
  162341. pCsr->aStat[0].nOcc++;
  162342. }
  162343. break;
  162344. /* State 3. The integer just read is a column number. */
  162345. default: assert( eState==3 );
  162346. iCol = (int)v;
  162347. if( fts3auxGrowStatArray(pCsr, iCol+2) ) return SQLITE_NOMEM;
  162348. pCsr->aStat[iCol+1].nDoc++;
  162349. eState = 2;
  162350. break;
  162351. }
  162352. }
  162353. pCsr->iCol = 0;
  162354. rc = SQLITE_OK;
  162355. }else{
  162356. pCsr->isEof = 1;
  162357. }
  162358. return rc;
  162359. }
  162360. /*
  162361. ** xFilter - Initialize a cursor to point at the start of its data.
  162362. */
  162363. static int fts3auxFilterMethod(
  162364. sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
  162365. int idxNum, /* Strategy index */
  162366. const char *idxStr, /* Unused */
  162367. int nVal, /* Number of elements in apVal */
  162368. sqlite3_value **apVal /* Arguments for the indexing scheme */
  162369. ){
  162370. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  162371. Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
  162372. int rc;
  162373. int isScan = 0;
  162374. int iLangVal = 0; /* Language id to query */
  162375. int iEq = -1; /* Index of term=? value in apVal */
  162376. int iGe = -1; /* Index of term>=? value in apVal */
  162377. int iLe = -1; /* Index of term<=? value in apVal */
  162378. int iLangid = -1; /* Index of languageid=? value in apVal */
  162379. int iNext = 0;
  162380. UNUSED_PARAMETER(nVal);
  162381. UNUSED_PARAMETER(idxStr);
  162382. assert( idxStr==0 );
  162383. assert( idxNum==FTS4AUX_EQ_CONSTRAINT || idxNum==0
  162384. || idxNum==FTS4AUX_LE_CONSTRAINT || idxNum==FTS4AUX_GE_CONSTRAINT
  162385. || idxNum==(FTS4AUX_LE_CONSTRAINT|FTS4AUX_GE_CONSTRAINT)
  162386. );
  162387. if( idxNum==FTS4AUX_EQ_CONSTRAINT ){
  162388. iEq = iNext++;
  162389. }else{
  162390. isScan = 1;
  162391. if( idxNum & FTS4AUX_GE_CONSTRAINT ){
  162392. iGe = iNext++;
  162393. }
  162394. if( idxNum & FTS4AUX_LE_CONSTRAINT ){
  162395. iLe = iNext++;
  162396. }
  162397. }
  162398. if( iNext<nVal ){
  162399. iLangid = iNext++;
  162400. }
  162401. /* In case this cursor is being reused, close and zero it. */
  162402. testcase(pCsr->filter.zTerm);
  162403. sqlite3Fts3SegReaderFinish(&pCsr->csr);
  162404. sqlite3_free((void *)pCsr->filter.zTerm);
  162405. sqlite3_free(pCsr->aStat);
  162406. memset(&pCsr->csr, 0, ((u8*)&pCsr[1]) - (u8*)&pCsr->csr);
  162407. pCsr->filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
  162408. if( isScan ) pCsr->filter.flags |= FTS3_SEGMENT_SCAN;
  162409. if( iEq>=0 || iGe>=0 ){
  162410. const unsigned char *zStr = sqlite3_value_text(apVal[0]);
  162411. assert( (iEq==0 && iGe==-1) || (iEq==-1 && iGe==0) );
  162412. if( zStr ){
  162413. pCsr->filter.zTerm = sqlite3_mprintf("%s", zStr);
  162414. if( pCsr->filter.zTerm==0 ) return SQLITE_NOMEM;
  162415. pCsr->filter.nTerm = (int)strlen(pCsr->filter.zTerm);
  162416. }
  162417. }
  162418. if( iLe>=0 ){
  162419. pCsr->zStop = sqlite3_mprintf("%s", sqlite3_value_text(apVal[iLe]));
  162420. if( pCsr->zStop==0 ) return SQLITE_NOMEM;
  162421. pCsr->nStop = (int)strlen(pCsr->zStop);
  162422. }
  162423. if( iLangid>=0 ){
  162424. iLangVal = sqlite3_value_int(apVal[iLangid]);
  162425. /* If the user specified a negative value for the languageid, use zero
  162426. ** instead. This works, as the "languageid=?" constraint will also
  162427. ** be tested by the VDBE layer. The test will always be false (since
  162428. ** this module will not return a row with a negative languageid), and
  162429. ** so the overall query will return zero rows. */
  162430. if( iLangVal<0 ) iLangVal = 0;
  162431. }
  162432. pCsr->iLangid = iLangVal;
  162433. rc = sqlite3Fts3SegReaderCursor(pFts3, iLangVal, 0, FTS3_SEGCURSOR_ALL,
  162434. pCsr->filter.zTerm, pCsr->filter.nTerm, 0, isScan, &pCsr->csr
  162435. );
  162436. if( rc==SQLITE_OK ){
  162437. rc = sqlite3Fts3SegReaderStart(pFts3, &pCsr->csr, &pCsr->filter);
  162438. }
  162439. if( rc==SQLITE_OK ) rc = fts3auxNextMethod(pCursor);
  162440. return rc;
  162441. }
  162442. /*
  162443. ** xEof - Return true if the cursor is at EOF, or false otherwise.
  162444. */
  162445. static int fts3auxEofMethod(sqlite3_vtab_cursor *pCursor){
  162446. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  162447. return pCsr->isEof;
  162448. }
  162449. /*
  162450. ** xColumn - Return a column value.
  162451. */
  162452. static int fts3auxColumnMethod(
  162453. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  162454. sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
  162455. int iCol /* Index of column to read value from */
  162456. ){
  162457. Fts3auxCursor *p = (Fts3auxCursor *)pCursor;
  162458. assert( p->isEof==0 );
  162459. switch( iCol ){
  162460. case 0: /* term */
  162461. sqlite3_result_text(pCtx, p->csr.zTerm, p->csr.nTerm, SQLITE_TRANSIENT);
  162462. break;
  162463. case 1: /* col */
  162464. if( p->iCol ){
  162465. sqlite3_result_int(pCtx, p->iCol-1);
  162466. }else{
  162467. sqlite3_result_text(pCtx, "*", -1, SQLITE_STATIC);
  162468. }
  162469. break;
  162470. case 2: /* documents */
  162471. sqlite3_result_int64(pCtx, p->aStat[p->iCol].nDoc);
  162472. break;
  162473. case 3: /* occurrences */
  162474. sqlite3_result_int64(pCtx, p->aStat[p->iCol].nOcc);
  162475. break;
  162476. default: /* languageid */
  162477. assert( iCol==4 );
  162478. sqlite3_result_int(pCtx, p->iLangid);
  162479. break;
  162480. }
  162481. return SQLITE_OK;
  162482. }
  162483. /*
  162484. ** xRowid - Return the current rowid for the cursor.
  162485. */
  162486. static int fts3auxRowidMethod(
  162487. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  162488. sqlite_int64 *pRowid /* OUT: Rowid value */
  162489. ){
  162490. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  162491. *pRowid = pCsr->iRowid;
  162492. return SQLITE_OK;
  162493. }
  162494. /*
  162495. ** Register the fts3aux module with database connection db. Return SQLITE_OK
  162496. ** if successful or an error code if sqlite3_create_module() fails.
  162497. */
  162498. SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db){
  162499. static const sqlite3_module fts3aux_module = {
  162500. 0, /* iVersion */
  162501. fts3auxConnectMethod, /* xCreate */
  162502. fts3auxConnectMethod, /* xConnect */
  162503. fts3auxBestIndexMethod, /* xBestIndex */
  162504. fts3auxDisconnectMethod, /* xDisconnect */
  162505. fts3auxDisconnectMethod, /* xDestroy */
  162506. fts3auxOpenMethod, /* xOpen */
  162507. fts3auxCloseMethod, /* xClose */
  162508. fts3auxFilterMethod, /* xFilter */
  162509. fts3auxNextMethod, /* xNext */
  162510. fts3auxEofMethod, /* xEof */
  162511. fts3auxColumnMethod, /* xColumn */
  162512. fts3auxRowidMethod, /* xRowid */
  162513. 0, /* xUpdate */
  162514. 0, /* xBegin */
  162515. 0, /* xSync */
  162516. 0, /* xCommit */
  162517. 0, /* xRollback */
  162518. 0, /* xFindFunction */
  162519. 0, /* xRename */
  162520. 0, /* xSavepoint */
  162521. 0, /* xRelease */
  162522. 0, /* xRollbackTo */
  162523. 0 /* xShadowName */
  162524. };
  162525. int rc; /* Return code */
  162526. rc = sqlite3_create_module(db, "fts4aux", &fts3aux_module, 0);
  162527. return rc;
  162528. }
  162529. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  162530. /************** End of fts3_aux.c ********************************************/
  162531. /************** Begin file fts3_expr.c ***************************************/
  162532. /*
  162533. ** 2008 Nov 28
  162534. **
  162535. ** The author disclaims copyright to this source code. In place of
  162536. ** a legal notice, here is a blessing:
  162537. **
  162538. ** May you do good and not evil.
  162539. ** May you find forgiveness for yourself and forgive others.
  162540. ** May you share freely, never taking more than you give.
  162541. **
  162542. ******************************************************************************
  162543. **
  162544. ** This module contains code that implements a parser for fts3 query strings
  162545. ** (the right-hand argument to the MATCH operator). Because the supported
  162546. ** syntax is relatively simple, the whole tokenizer/parser system is
  162547. ** hand-coded.
  162548. */
  162549. /* #include "fts3Int.h" */
  162550. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  162551. /*
  162552. ** By default, this module parses the legacy syntax that has been
  162553. ** traditionally used by fts3. Or, if SQLITE_ENABLE_FTS3_PARENTHESIS
  162554. ** is defined, then it uses the new syntax. The differences between
  162555. ** the new and the old syntaxes are:
  162556. **
  162557. ** a) The new syntax supports parenthesis. The old does not.
  162558. **
  162559. ** b) The new syntax supports the AND and NOT operators. The old does not.
  162560. **
  162561. ** c) The old syntax supports the "-" token qualifier. This is not
  162562. ** supported by the new syntax (it is replaced by the NOT operator).
  162563. **
  162564. ** d) When using the old syntax, the OR operator has a greater precedence
  162565. ** than an implicit AND. When using the new, both implicity and explicit
  162566. ** AND operators have a higher precedence than OR.
  162567. **
  162568. ** If compiled with SQLITE_TEST defined, then this module exports the
  162569. ** symbol "int sqlite3_fts3_enable_parentheses". Setting this variable
  162570. ** to zero causes the module to use the old syntax. If it is set to
  162571. ** non-zero the new syntax is activated. This is so both syntaxes can
  162572. ** be tested using a single build of testfixture.
  162573. **
  162574. ** The following describes the syntax supported by the fts3 MATCH
  162575. ** operator in a similar format to that used by the lemon parser
  162576. ** generator. This module does not use actually lemon, it uses a
  162577. ** custom parser.
  162578. **
  162579. ** query ::= andexpr (OR andexpr)*.
  162580. **
  162581. ** andexpr ::= notexpr (AND? notexpr)*.
  162582. **
  162583. ** notexpr ::= nearexpr (NOT nearexpr|-TOKEN)*.
  162584. ** notexpr ::= LP query RP.
  162585. **
  162586. ** nearexpr ::= phrase (NEAR distance_opt nearexpr)*.
  162587. **
  162588. ** distance_opt ::= .
  162589. ** distance_opt ::= / INTEGER.
  162590. **
  162591. ** phrase ::= TOKEN.
  162592. ** phrase ::= COLUMN:TOKEN.
  162593. ** phrase ::= "TOKEN TOKEN TOKEN...".
  162594. */
  162595. #ifdef SQLITE_TEST
  162596. SQLITE_API int sqlite3_fts3_enable_parentheses = 0;
  162597. #else
  162598. # ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
  162599. # define sqlite3_fts3_enable_parentheses 1
  162600. # else
  162601. # define sqlite3_fts3_enable_parentheses 0
  162602. # endif
  162603. #endif
  162604. /*
  162605. ** Default span for NEAR operators.
  162606. */
  162607. #define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10
  162608. /* #include <string.h> */
  162609. /* #include <assert.h> */
  162610. /*
  162611. ** isNot:
  162612. ** This variable is used by function getNextNode(). When getNextNode() is
  162613. ** called, it sets ParseContext.isNot to true if the 'next node' is a
  162614. ** FTSQUERY_PHRASE with a unary "-" attached to it. i.e. "mysql" in the
  162615. ** FTS3 query "sqlite -mysql". Otherwise, ParseContext.isNot is set to
  162616. ** zero.
  162617. */
  162618. typedef struct ParseContext ParseContext;
  162619. struct ParseContext {
  162620. sqlite3_tokenizer *pTokenizer; /* Tokenizer module */
  162621. int iLangid; /* Language id used with tokenizer */
  162622. const char **azCol; /* Array of column names for fts3 table */
  162623. int bFts4; /* True to allow FTS4-only syntax */
  162624. int nCol; /* Number of entries in azCol[] */
  162625. int iDefaultCol; /* Default column to query */
  162626. int isNot; /* True if getNextNode() sees a unary - */
  162627. sqlite3_context *pCtx; /* Write error message here */
  162628. int nNest; /* Number of nested brackets */
  162629. };
  162630. /*
  162631. ** This function is equivalent to the standard isspace() function.
  162632. **
  162633. ** The standard isspace() can be awkward to use safely, because although it
  162634. ** is defined to accept an argument of type int, its behavior when passed
  162635. ** an integer that falls outside of the range of the unsigned char type
  162636. ** is undefined (and sometimes, "undefined" means segfault). This wrapper
  162637. ** is defined to accept an argument of type char, and always returns 0 for
  162638. ** any values that fall outside of the range of the unsigned char type (i.e.
  162639. ** negative values).
  162640. */
  162641. static int fts3isspace(char c){
  162642. return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
  162643. }
  162644. /*
  162645. ** Allocate nByte bytes of memory using sqlite3_malloc(). If successful,
  162646. ** zero the memory before returning a pointer to it. If unsuccessful,
  162647. ** return NULL.
  162648. */
  162649. static void *fts3MallocZero(sqlite3_int64 nByte){
  162650. void *pRet = sqlite3_malloc64(nByte);
  162651. if( pRet ) memset(pRet, 0, nByte);
  162652. return pRet;
  162653. }
  162654. SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(
  162655. sqlite3_tokenizer *pTokenizer,
  162656. int iLangid,
  162657. const char *z,
  162658. int n,
  162659. sqlite3_tokenizer_cursor **ppCsr
  162660. ){
  162661. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  162662. sqlite3_tokenizer_cursor *pCsr = 0;
  162663. int rc;
  162664. rc = pModule->xOpen(pTokenizer, z, n, &pCsr);
  162665. assert( rc==SQLITE_OK || pCsr==0 );
  162666. if( rc==SQLITE_OK ){
  162667. pCsr->pTokenizer = pTokenizer;
  162668. if( pModule->iVersion>=1 ){
  162669. rc = pModule->xLanguageid(pCsr, iLangid);
  162670. if( rc!=SQLITE_OK ){
  162671. pModule->xClose(pCsr);
  162672. pCsr = 0;
  162673. }
  162674. }
  162675. }
  162676. *ppCsr = pCsr;
  162677. return rc;
  162678. }
  162679. /*
  162680. ** Function getNextNode(), which is called by fts3ExprParse(), may itself
  162681. ** call fts3ExprParse(). So this forward declaration is required.
  162682. */
  162683. static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *);
  162684. /*
  162685. ** Extract the next token from buffer z (length n) using the tokenizer
  162686. ** and other information (column names etc.) in pParse. Create an Fts3Expr
  162687. ** structure of type FTSQUERY_PHRASE containing a phrase consisting of this
  162688. ** single token and set *ppExpr to point to it. If the end of the buffer is
  162689. ** reached before a token is found, set *ppExpr to zero. It is the
  162690. ** responsibility of the caller to eventually deallocate the allocated
  162691. ** Fts3Expr structure (if any) by passing it to sqlite3_free().
  162692. **
  162693. ** Return SQLITE_OK if successful, or SQLITE_NOMEM if a memory allocation
  162694. ** fails.
  162695. */
  162696. static int getNextToken(
  162697. ParseContext *pParse, /* fts3 query parse context */
  162698. int iCol, /* Value for Fts3Phrase.iColumn */
  162699. const char *z, int n, /* Input string */
  162700. Fts3Expr **ppExpr, /* OUT: expression */
  162701. int *pnConsumed /* OUT: Number of bytes consumed */
  162702. ){
  162703. sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
  162704. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  162705. int rc;
  162706. sqlite3_tokenizer_cursor *pCursor;
  162707. Fts3Expr *pRet = 0;
  162708. int i = 0;
  162709. /* Set variable i to the maximum number of bytes of input to tokenize. */
  162710. for(i=0; i<n; i++){
  162711. if( sqlite3_fts3_enable_parentheses && (z[i]=='(' || z[i]==')') ) break;
  162712. if( z[i]=='"' ) break;
  162713. }
  162714. *pnConsumed = i;
  162715. rc = sqlite3Fts3OpenTokenizer(pTokenizer, pParse->iLangid, z, i, &pCursor);
  162716. if( rc==SQLITE_OK ){
  162717. const char *zToken;
  162718. int nToken = 0, iStart = 0, iEnd = 0, iPosition = 0;
  162719. sqlite3_int64 nByte; /* total space to allocate */
  162720. rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition);
  162721. if( rc==SQLITE_OK ){
  162722. nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken;
  162723. pRet = (Fts3Expr *)fts3MallocZero(nByte);
  162724. if( !pRet ){
  162725. rc = SQLITE_NOMEM;
  162726. }else{
  162727. pRet->eType = FTSQUERY_PHRASE;
  162728. pRet->pPhrase = (Fts3Phrase *)&pRet[1];
  162729. pRet->pPhrase->nToken = 1;
  162730. pRet->pPhrase->iColumn = iCol;
  162731. pRet->pPhrase->aToken[0].n = nToken;
  162732. pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1];
  162733. memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken);
  162734. if( iEnd<n && z[iEnd]=='*' ){
  162735. pRet->pPhrase->aToken[0].isPrefix = 1;
  162736. iEnd++;
  162737. }
  162738. while( 1 ){
  162739. if( !sqlite3_fts3_enable_parentheses
  162740. && iStart>0 && z[iStart-1]=='-'
  162741. ){
  162742. pParse->isNot = 1;
  162743. iStart--;
  162744. }else if( pParse->bFts4 && iStart>0 && z[iStart-1]=='^' ){
  162745. pRet->pPhrase->aToken[0].bFirst = 1;
  162746. iStart--;
  162747. }else{
  162748. break;
  162749. }
  162750. }
  162751. }
  162752. *pnConsumed = iEnd;
  162753. }else if( i && rc==SQLITE_DONE ){
  162754. rc = SQLITE_OK;
  162755. }
  162756. pModule->xClose(pCursor);
  162757. }
  162758. *ppExpr = pRet;
  162759. return rc;
  162760. }
  162761. /*
  162762. ** Enlarge a memory allocation. If an out-of-memory allocation occurs,
  162763. ** then free the old allocation.
  162764. */
  162765. static void *fts3ReallocOrFree(void *pOrig, sqlite3_int64 nNew){
  162766. void *pRet = sqlite3_realloc64(pOrig, nNew);
  162767. if( !pRet ){
  162768. sqlite3_free(pOrig);
  162769. }
  162770. return pRet;
  162771. }
  162772. /*
  162773. ** Buffer zInput, length nInput, contains the contents of a quoted string
  162774. ** that appeared as part of an fts3 query expression. Neither quote character
  162775. ** is included in the buffer. This function attempts to tokenize the entire
  162776. ** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE
  162777. ** containing the results.
  162778. **
  162779. ** If successful, SQLITE_OK is returned and *ppExpr set to point at the
  162780. ** allocated Fts3Expr structure. Otherwise, either SQLITE_NOMEM (out of memory
  162781. ** error) or SQLITE_ERROR (tokenization error) is returned and *ppExpr set
  162782. ** to 0.
  162783. */
  162784. static int getNextString(
  162785. ParseContext *pParse, /* fts3 query parse context */
  162786. const char *zInput, int nInput, /* Input string */
  162787. Fts3Expr **ppExpr /* OUT: expression */
  162788. ){
  162789. sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
  162790. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  162791. int rc;
  162792. Fts3Expr *p = 0;
  162793. sqlite3_tokenizer_cursor *pCursor = 0;
  162794. char *zTemp = 0;
  162795. int nTemp = 0;
  162796. const int nSpace = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
  162797. int nToken = 0;
  162798. /* The final Fts3Expr data structure, including the Fts3Phrase,
  162799. ** Fts3PhraseToken structures token buffers are all stored as a single
  162800. ** allocation so that the expression can be freed with a single call to
  162801. ** sqlite3_free(). Setting this up requires a two pass approach.
  162802. **
  162803. ** The first pass, in the block below, uses a tokenizer cursor to iterate
  162804. ** through the tokens in the expression. This pass uses fts3ReallocOrFree()
  162805. ** to assemble data in two dynamic buffers:
  162806. **
  162807. ** Buffer p: Points to the Fts3Expr structure, followed by the Fts3Phrase
  162808. ** structure, followed by the array of Fts3PhraseToken
  162809. ** structures. This pass only populates the Fts3PhraseToken array.
  162810. **
  162811. ** Buffer zTemp: Contains copies of all tokens.
  162812. **
  162813. ** The second pass, in the block that begins "if( rc==SQLITE_DONE )" below,
  162814. ** appends buffer zTemp to buffer p, and fills in the Fts3Expr and Fts3Phrase
  162815. ** structures.
  162816. */
  162817. rc = sqlite3Fts3OpenTokenizer(
  162818. pTokenizer, pParse->iLangid, zInput, nInput, &pCursor);
  162819. if( rc==SQLITE_OK ){
  162820. int ii;
  162821. for(ii=0; rc==SQLITE_OK; ii++){
  162822. const char *zByte;
  162823. int nByte = 0, iBegin = 0, iEnd = 0, iPos = 0;
  162824. rc = pModule->xNext(pCursor, &zByte, &nByte, &iBegin, &iEnd, &iPos);
  162825. if( rc==SQLITE_OK ){
  162826. Fts3PhraseToken *pToken;
  162827. p = fts3ReallocOrFree(p, nSpace + ii*sizeof(Fts3PhraseToken));
  162828. if( !p ) goto no_mem;
  162829. zTemp = fts3ReallocOrFree(zTemp, nTemp + nByte);
  162830. if( !zTemp ) goto no_mem;
  162831. assert( nToken==ii );
  162832. pToken = &((Fts3Phrase *)(&p[1]))->aToken[ii];
  162833. memset(pToken, 0, sizeof(Fts3PhraseToken));
  162834. memcpy(&zTemp[nTemp], zByte, nByte);
  162835. nTemp += nByte;
  162836. pToken->n = nByte;
  162837. pToken->isPrefix = (iEnd<nInput && zInput[iEnd]=='*');
  162838. pToken->bFirst = (iBegin>0 && zInput[iBegin-1]=='^');
  162839. nToken = ii+1;
  162840. }
  162841. }
  162842. pModule->xClose(pCursor);
  162843. pCursor = 0;
  162844. }
  162845. if( rc==SQLITE_DONE ){
  162846. int jj;
  162847. char *zBuf = 0;
  162848. p = fts3ReallocOrFree(p, nSpace + nToken*sizeof(Fts3PhraseToken) + nTemp);
  162849. if( !p ) goto no_mem;
  162850. memset(p, 0, (char *)&(((Fts3Phrase *)&p[1])->aToken[0])-(char *)p);
  162851. p->eType = FTSQUERY_PHRASE;
  162852. p->pPhrase = (Fts3Phrase *)&p[1];
  162853. p->pPhrase->iColumn = pParse->iDefaultCol;
  162854. p->pPhrase->nToken = nToken;
  162855. zBuf = (char *)&p->pPhrase->aToken[nToken];
  162856. if( zTemp ){
  162857. memcpy(zBuf, zTemp, nTemp);
  162858. sqlite3_free(zTemp);
  162859. }else{
  162860. assert( nTemp==0 );
  162861. }
  162862. for(jj=0; jj<p->pPhrase->nToken; jj++){
  162863. p->pPhrase->aToken[jj].z = zBuf;
  162864. zBuf += p->pPhrase->aToken[jj].n;
  162865. }
  162866. rc = SQLITE_OK;
  162867. }
  162868. *ppExpr = p;
  162869. return rc;
  162870. no_mem:
  162871. if( pCursor ){
  162872. pModule->xClose(pCursor);
  162873. }
  162874. sqlite3_free(zTemp);
  162875. sqlite3_free(p);
  162876. *ppExpr = 0;
  162877. return SQLITE_NOMEM;
  162878. }
  162879. /*
  162880. ** The output variable *ppExpr is populated with an allocated Fts3Expr
  162881. ** structure, or set to 0 if the end of the input buffer is reached.
  162882. **
  162883. ** Returns an SQLite error code. SQLITE_OK if everything works, SQLITE_NOMEM
  162884. ** if a malloc failure occurs, or SQLITE_ERROR if a parse error is encountered.
  162885. ** If SQLITE_ERROR is returned, pContext is populated with an error message.
  162886. */
  162887. static int getNextNode(
  162888. ParseContext *pParse, /* fts3 query parse context */
  162889. const char *z, int n, /* Input string */
  162890. Fts3Expr **ppExpr, /* OUT: expression */
  162891. int *pnConsumed /* OUT: Number of bytes consumed */
  162892. ){
  162893. static const struct Fts3Keyword {
  162894. char *z; /* Keyword text */
  162895. unsigned char n; /* Length of the keyword */
  162896. unsigned char parenOnly; /* Only valid in paren mode */
  162897. unsigned char eType; /* Keyword code */
  162898. } aKeyword[] = {
  162899. { "OR" , 2, 0, FTSQUERY_OR },
  162900. { "AND", 3, 1, FTSQUERY_AND },
  162901. { "NOT", 3, 1, FTSQUERY_NOT },
  162902. { "NEAR", 4, 0, FTSQUERY_NEAR }
  162903. };
  162904. int ii;
  162905. int iCol;
  162906. int iColLen;
  162907. int rc;
  162908. Fts3Expr *pRet = 0;
  162909. const char *zInput = z;
  162910. int nInput = n;
  162911. pParse->isNot = 0;
  162912. /* Skip over any whitespace before checking for a keyword, an open or
  162913. ** close bracket, or a quoted string.
  162914. */
  162915. while( nInput>0 && fts3isspace(*zInput) ){
  162916. nInput--;
  162917. zInput++;
  162918. }
  162919. if( nInput==0 ){
  162920. return SQLITE_DONE;
  162921. }
  162922. /* See if we are dealing with a keyword. */
  162923. for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){
  162924. const struct Fts3Keyword *pKey = &aKeyword[ii];
  162925. if( (pKey->parenOnly & ~sqlite3_fts3_enable_parentheses)!=0 ){
  162926. continue;
  162927. }
  162928. if( nInput>=pKey->n && 0==memcmp(zInput, pKey->z, pKey->n) ){
  162929. int nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;
  162930. int nKey = pKey->n;
  162931. char cNext;
  162932. /* If this is a "NEAR" keyword, check for an explicit nearness. */
  162933. if( pKey->eType==FTSQUERY_NEAR ){
  162934. assert( nKey==4 );
  162935. if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){
  162936. nKey += 1+sqlite3Fts3ReadInt(&zInput[nKey+1], &nNear);
  162937. }
  162938. }
  162939. /* At this point this is probably a keyword. But for that to be true,
  162940. ** the next byte must contain either whitespace, an open or close
  162941. ** parenthesis, a quote character, or EOF.
  162942. */
  162943. cNext = zInput[nKey];
  162944. if( fts3isspace(cNext)
  162945. || cNext=='"' || cNext=='(' || cNext==')' || cNext==0
  162946. ){
  162947. pRet = (Fts3Expr *)fts3MallocZero(sizeof(Fts3Expr));
  162948. if( !pRet ){
  162949. return SQLITE_NOMEM;
  162950. }
  162951. pRet->eType = pKey->eType;
  162952. pRet->nNear = nNear;
  162953. *ppExpr = pRet;
  162954. *pnConsumed = (int)((zInput - z) + nKey);
  162955. return SQLITE_OK;
  162956. }
  162957. /* Turns out that wasn't a keyword after all. This happens if the
  162958. ** user has supplied a token such as "ORacle". Continue.
  162959. */
  162960. }
  162961. }
  162962. /* See if we are dealing with a quoted phrase. If this is the case, then
  162963. ** search for the closing quote and pass the whole string to getNextString()
  162964. ** for processing. This is easy to do, as fts3 has no syntax for escaping
  162965. ** a quote character embedded in a string.
  162966. */
  162967. if( *zInput=='"' ){
  162968. for(ii=1; ii<nInput && zInput[ii]!='"'; ii++);
  162969. *pnConsumed = (int)((zInput - z) + ii + 1);
  162970. if( ii==nInput ){
  162971. return SQLITE_ERROR;
  162972. }
  162973. return getNextString(pParse, &zInput[1], ii-1, ppExpr);
  162974. }
  162975. if( sqlite3_fts3_enable_parentheses ){
  162976. if( *zInput=='(' ){
  162977. int nConsumed = 0;
  162978. pParse->nNest++;
  162979. rc = fts3ExprParse(pParse, zInput+1, nInput-1, ppExpr, &nConsumed);
  162980. *pnConsumed = (int)(zInput - z) + 1 + nConsumed;
  162981. return rc;
  162982. }else if( *zInput==')' ){
  162983. pParse->nNest--;
  162984. *pnConsumed = (int)((zInput - z) + 1);
  162985. *ppExpr = 0;
  162986. return SQLITE_DONE;
  162987. }
  162988. }
  162989. /* If control flows to this point, this must be a regular token, or
  162990. ** the end of the input. Read a regular token using the sqlite3_tokenizer
  162991. ** interface. Before doing so, figure out if there is an explicit
  162992. ** column specifier for the token.
  162993. **
  162994. ** TODO: Strangely, it is not possible to associate a column specifier
  162995. ** with a quoted phrase, only with a single token. Not sure if this was
  162996. ** an implementation artifact or an intentional decision when fts3 was
  162997. ** first implemented. Whichever it was, this module duplicates the
  162998. ** limitation.
  162999. */
  163000. iCol = pParse->iDefaultCol;
  163001. iColLen = 0;
  163002. for(ii=0; ii<pParse->nCol; ii++){
  163003. const char *zStr = pParse->azCol[ii];
  163004. int nStr = (int)strlen(zStr);
  163005. if( nInput>nStr && zInput[nStr]==':'
  163006. && sqlite3_strnicmp(zStr, zInput, nStr)==0
  163007. ){
  163008. iCol = ii;
  163009. iColLen = (int)((zInput - z) + nStr + 1);
  163010. break;
  163011. }
  163012. }
  163013. rc = getNextToken(pParse, iCol, &z[iColLen], n-iColLen, ppExpr, pnConsumed);
  163014. *pnConsumed += iColLen;
  163015. return rc;
  163016. }
  163017. /*
  163018. ** The argument is an Fts3Expr structure for a binary operator (any type
  163019. ** except an FTSQUERY_PHRASE). Return an integer value representing the
  163020. ** precedence of the operator. Lower values have a higher precedence (i.e.
  163021. ** group more tightly). For example, in the C language, the == operator
  163022. ** groups more tightly than ||, and would therefore have a higher precedence.
  163023. **
  163024. ** When using the new fts3 query syntax (when SQLITE_ENABLE_FTS3_PARENTHESIS
  163025. ** is defined), the order of the operators in precedence from highest to
  163026. ** lowest is:
  163027. **
  163028. ** NEAR
  163029. ** NOT
  163030. ** AND (including implicit ANDs)
  163031. ** OR
  163032. **
  163033. ** Note that when using the old query syntax, the OR operator has a higher
  163034. ** precedence than the AND operator.
  163035. */
  163036. static int opPrecedence(Fts3Expr *p){
  163037. assert( p->eType!=FTSQUERY_PHRASE );
  163038. if( sqlite3_fts3_enable_parentheses ){
  163039. return p->eType;
  163040. }else if( p->eType==FTSQUERY_NEAR ){
  163041. return 1;
  163042. }else if( p->eType==FTSQUERY_OR ){
  163043. return 2;
  163044. }
  163045. assert( p->eType==FTSQUERY_AND );
  163046. return 3;
  163047. }
  163048. /*
  163049. ** Argument ppHead contains a pointer to the current head of a query
  163050. ** expression tree being parsed. pPrev is the expression node most recently
  163051. ** inserted into the tree. This function adds pNew, which is always a binary
  163052. ** operator node, into the expression tree based on the relative precedence
  163053. ** of pNew and the existing nodes of the tree. This may result in the head
  163054. ** of the tree changing, in which case *ppHead is set to the new root node.
  163055. */
  163056. static void insertBinaryOperator(
  163057. Fts3Expr **ppHead, /* Pointer to the root node of a tree */
  163058. Fts3Expr *pPrev, /* Node most recently inserted into the tree */
  163059. Fts3Expr *pNew /* New binary node to insert into expression tree */
  163060. ){
  163061. Fts3Expr *pSplit = pPrev;
  163062. while( pSplit->pParent && opPrecedence(pSplit->pParent)<=opPrecedence(pNew) ){
  163063. pSplit = pSplit->pParent;
  163064. }
  163065. if( pSplit->pParent ){
  163066. assert( pSplit->pParent->pRight==pSplit );
  163067. pSplit->pParent->pRight = pNew;
  163068. pNew->pParent = pSplit->pParent;
  163069. }else{
  163070. *ppHead = pNew;
  163071. }
  163072. pNew->pLeft = pSplit;
  163073. pSplit->pParent = pNew;
  163074. }
  163075. /*
  163076. ** Parse the fts3 query expression found in buffer z, length n. This function
  163077. ** returns either when the end of the buffer is reached or an unmatched
  163078. ** closing bracket - ')' - is encountered.
  163079. **
  163080. ** If successful, SQLITE_OK is returned, *ppExpr is set to point to the
  163081. ** parsed form of the expression and *pnConsumed is set to the number of
  163082. ** bytes read from buffer z. Otherwise, *ppExpr is set to 0 and SQLITE_NOMEM
  163083. ** (out of memory error) or SQLITE_ERROR (parse error) is returned.
  163084. */
  163085. static int fts3ExprParse(
  163086. ParseContext *pParse, /* fts3 query parse context */
  163087. const char *z, int n, /* Text of MATCH query */
  163088. Fts3Expr **ppExpr, /* OUT: Parsed query structure */
  163089. int *pnConsumed /* OUT: Number of bytes consumed */
  163090. ){
  163091. Fts3Expr *pRet = 0;
  163092. Fts3Expr *pPrev = 0;
  163093. Fts3Expr *pNotBranch = 0; /* Only used in legacy parse mode */
  163094. int nIn = n;
  163095. const char *zIn = z;
  163096. int rc = SQLITE_OK;
  163097. int isRequirePhrase = 1;
  163098. while( rc==SQLITE_OK ){
  163099. Fts3Expr *p = 0;
  163100. int nByte = 0;
  163101. rc = getNextNode(pParse, zIn, nIn, &p, &nByte);
  163102. assert( nByte>0 || (rc!=SQLITE_OK && p==0) );
  163103. if( rc==SQLITE_OK ){
  163104. if( p ){
  163105. int isPhrase;
  163106. if( !sqlite3_fts3_enable_parentheses
  163107. && p->eType==FTSQUERY_PHRASE && pParse->isNot
  163108. ){
  163109. /* Create an implicit NOT operator. */
  163110. Fts3Expr *pNot = fts3MallocZero(sizeof(Fts3Expr));
  163111. if( !pNot ){
  163112. sqlite3Fts3ExprFree(p);
  163113. rc = SQLITE_NOMEM;
  163114. goto exprparse_out;
  163115. }
  163116. pNot->eType = FTSQUERY_NOT;
  163117. pNot->pRight = p;
  163118. p->pParent = pNot;
  163119. if( pNotBranch ){
  163120. pNot->pLeft = pNotBranch;
  163121. pNotBranch->pParent = pNot;
  163122. }
  163123. pNotBranch = pNot;
  163124. p = pPrev;
  163125. }else{
  163126. int eType = p->eType;
  163127. isPhrase = (eType==FTSQUERY_PHRASE || p->pLeft);
  163128. /* The isRequirePhrase variable is set to true if a phrase or
  163129. ** an expression contained in parenthesis is required. If a
  163130. ** binary operator (AND, OR, NOT or NEAR) is encounted when
  163131. ** isRequirePhrase is set, this is a syntax error.
  163132. */
  163133. if( !isPhrase && isRequirePhrase ){
  163134. sqlite3Fts3ExprFree(p);
  163135. rc = SQLITE_ERROR;
  163136. goto exprparse_out;
  163137. }
  163138. if( isPhrase && !isRequirePhrase ){
  163139. /* Insert an implicit AND operator. */
  163140. Fts3Expr *pAnd;
  163141. assert( pRet && pPrev );
  163142. pAnd = fts3MallocZero(sizeof(Fts3Expr));
  163143. if( !pAnd ){
  163144. sqlite3Fts3ExprFree(p);
  163145. rc = SQLITE_NOMEM;
  163146. goto exprparse_out;
  163147. }
  163148. pAnd->eType = FTSQUERY_AND;
  163149. insertBinaryOperator(&pRet, pPrev, pAnd);
  163150. pPrev = pAnd;
  163151. }
  163152. /* This test catches attempts to make either operand of a NEAR
  163153. ** operator something other than a phrase. For example, either of
  163154. ** the following:
  163155. **
  163156. ** (bracketed expression) NEAR phrase
  163157. ** phrase NEAR (bracketed expression)
  163158. **
  163159. ** Return an error in either case.
  163160. */
  163161. if( pPrev && (
  163162. (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE)
  163163. || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR)
  163164. )){
  163165. sqlite3Fts3ExprFree(p);
  163166. rc = SQLITE_ERROR;
  163167. goto exprparse_out;
  163168. }
  163169. if( isPhrase ){
  163170. if( pRet ){
  163171. assert( pPrev && pPrev->pLeft && pPrev->pRight==0 );
  163172. pPrev->pRight = p;
  163173. p->pParent = pPrev;
  163174. }else{
  163175. pRet = p;
  163176. }
  163177. }else{
  163178. insertBinaryOperator(&pRet, pPrev, p);
  163179. }
  163180. isRequirePhrase = !isPhrase;
  163181. }
  163182. pPrev = p;
  163183. }
  163184. assert( nByte>0 );
  163185. }
  163186. assert( rc!=SQLITE_OK || (nByte>0 && nByte<=nIn) );
  163187. nIn -= nByte;
  163188. zIn += nByte;
  163189. }
  163190. if( rc==SQLITE_DONE && pRet && isRequirePhrase ){
  163191. rc = SQLITE_ERROR;
  163192. }
  163193. if( rc==SQLITE_DONE ){
  163194. rc = SQLITE_OK;
  163195. if( !sqlite3_fts3_enable_parentheses && pNotBranch ){
  163196. if( !pRet ){
  163197. rc = SQLITE_ERROR;
  163198. }else{
  163199. Fts3Expr *pIter = pNotBranch;
  163200. while( pIter->pLeft ){
  163201. pIter = pIter->pLeft;
  163202. }
  163203. pIter->pLeft = pRet;
  163204. pRet->pParent = pIter;
  163205. pRet = pNotBranch;
  163206. }
  163207. }
  163208. }
  163209. *pnConsumed = n - nIn;
  163210. exprparse_out:
  163211. if( rc!=SQLITE_OK ){
  163212. sqlite3Fts3ExprFree(pRet);
  163213. sqlite3Fts3ExprFree(pNotBranch);
  163214. pRet = 0;
  163215. }
  163216. *ppExpr = pRet;
  163217. return rc;
  163218. }
  163219. /*
  163220. ** Return SQLITE_ERROR if the maximum depth of the expression tree passed
  163221. ** as the only argument is more than nMaxDepth.
  163222. */
  163223. static int fts3ExprCheckDepth(Fts3Expr *p, int nMaxDepth){
  163224. int rc = SQLITE_OK;
  163225. if( p ){
  163226. if( nMaxDepth<0 ){
  163227. rc = SQLITE_TOOBIG;
  163228. }else{
  163229. rc = fts3ExprCheckDepth(p->pLeft, nMaxDepth-1);
  163230. if( rc==SQLITE_OK ){
  163231. rc = fts3ExprCheckDepth(p->pRight, nMaxDepth-1);
  163232. }
  163233. }
  163234. }
  163235. return rc;
  163236. }
  163237. /*
  163238. ** This function attempts to transform the expression tree at (*pp) to
  163239. ** an equivalent but more balanced form. The tree is modified in place.
  163240. ** If successful, SQLITE_OK is returned and (*pp) set to point to the
  163241. ** new root expression node.
  163242. **
  163243. ** nMaxDepth is the maximum allowable depth of the balanced sub-tree.
  163244. **
  163245. ** Otherwise, if an error occurs, an SQLite error code is returned and
  163246. ** expression (*pp) freed.
  163247. */
  163248. static int fts3ExprBalance(Fts3Expr **pp, int nMaxDepth){
  163249. int rc = SQLITE_OK; /* Return code */
  163250. Fts3Expr *pRoot = *pp; /* Initial root node */
  163251. Fts3Expr *pFree = 0; /* List of free nodes. Linked by pParent. */
  163252. int eType = pRoot->eType; /* Type of node in this tree */
  163253. if( nMaxDepth==0 ){
  163254. rc = SQLITE_ERROR;
  163255. }
  163256. if( rc==SQLITE_OK ){
  163257. if( (eType==FTSQUERY_AND || eType==FTSQUERY_OR) ){
  163258. Fts3Expr **apLeaf;
  163259. apLeaf = (Fts3Expr **)sqlite3_malloc64(sizeof(Fts3Expr *) * nMaxDepth);
  163260. if( 0==apLeaf ){
  163261. rc = SQLITE_NOMEM;
  163262. }else{
  163263. memset(apLeaf, 0, sizeof(Fts3Expr *) * nMaxDepth);
  163264. }
  163265. if( rc==SQLITE_OK ){
  163266. int i;
  163267. Fts3Expr *p;
  163268. /* Set $p to point to the left-most leaf in the tree of eType nodes. */
  163269. for(p=pRoot; p->eType==eType; p=p->pLeft){
  163270. assert( p->pParent==0 || p->pParent->pLeft==p );
  163271. assert( p->pLeft && p->pRight );
  163272. }
  163273. /* This loop runs once for each leaf in the tree of eType nodes. */
  163274. while( 1 ){
  163275. int iLvl;
  163276. Fts3Expr *pParent = p->pParent; /* Current parent of p */
  163277. assert( pParent==0 || pParent->pLeft==p );
  163278. p->pParent = 0;
  163279. if( pParent ){
  163280. pParent->pLeft = 0;
  163281. }else{
  163282. pRoot = 0;
  163283. }
  163284. rc = fts3ExprBalance(&p, nMaxDepth-1);
  163285. if( rc!=SQLITE_OK ) break;
  163286. for(iLvl=0; p && iLvl<nMaxDepth; iLvl++){
  163287. if( apLeaf[iLvl]==0 ){
  163288. apLeaf[iLvl] = p;
  163289. p = 0;
  163290. }else{
  163291. assert( pFree );
  163292. pFree->pLeft = apLeaf[iLvl];
  163293. pFree->pRight = p;
  163294. pFree->pLeft->pParent = pFree;
  163295. pFree->pRight->pParent = pFree;
  163296. p = pFree;
  163297. pFree = pFree->pParent;
  163298. p->pParent = 0;
  163299. apLeaf[iLvl] = 0;
  163300. }
  163301. }
  163302. if( p ){
  163303. sqlite3Fts3ExprFree(p);
  163304. rc = SQLITE_TOOBIG;
  163305. break;
  163306. }
  163307. /* If that was the last leaf node, break out of the loop */
  163308. if( pParent==0 ) break;
  163309. /* Set $p to point to the next leaf in the tree of eType nodes */
  163310. for(p=pParent->pRight; p->eType==eType; p=p->pLeft);
  163311. /* Remove pParent from the original tree. */
  163312. assert( pParent->pParent==0 || pParent->pParent->pLeft==pParent );
  163313. pParent->pRight->pParent = pParent->pParent;
  163314. if( pParent->pParent ){
  163315. pParent->pParent->pLeft = pParent->pRight;
  163316. }else{
  163317. assert( pParent==pRoot );
  163318. pRoot = pParent->pRight;
  163319. }
  163320. /* Link pParent into the free node list. It will be used as an
  163321. ** internal node of the new tree. */
  163322. pParent->pParent = pFree;
  163323. pFree = pParent;
  163324. }
  163325. if( rc==SQLITE_OK ){
  163326. p = 0;
  163327. for(i=0; i<nMaxDepth; i++){
  163328. if( apLeaf[i] ){
  163329. if( p==0 ){
  163330. p = apLeaf[i];
  163331. p->pParent = 0;
  163332. }else{
  163333. assert( pFree!=0 );
  163334. pFree->pRight = p;
  163335. pFree->pLeft = apLeaf[i];
  163336. pFree->pLeft->pParent = pFree;
  163337. pFree->pRight->pParent = pFree;
  163338. p = pFree;
  163339. pFree = pFree->pParent;
  163340. p->pParent = 0;
  163341. }
  163342. }
  163343. }
  163344. pRoot = p;
  163345. }else{
  163346. /* An error occurred. Delete the contents of the apLeaf[] array
  163347. ** and pFree list. Everything else is cleaned up by the call to
  163348. ** sqlite3Fts3ExprFree(pRoot) below. */
  163349. Fts3Expr *pDel;
  163350. for(i=0; i<nMaxDepth; i++){
  163351. sqlite3Fts3ExprFree(apLeaf[i]);
  163352. }
  163353. while( (pDel=pFree)!=0 ){
  163354. pFree = pDel->pParent;
  163355. sqlite3_free(pDel);
  163356. }
  163357. }
  163358. assert( pFree==0 );
  163359. sqlite3_free( apLeaf );
  163360. }
  163361. }else if( eType==FTSQUERY_NOT ){
  163362. Fts3Expr *pLeft = pRoot->pLeft;
  163363. Fts3Expr *pRight = pRoot->pRight;
  163364. pRoot->pLeft = 0;
  163365. pRoot->pRight = 0;
  163366. pLeft->pParent = 0;
  163367. pRight->pParent = 0;
  163368. rc = fts3ExprBalance(&pLeft, nMaxDepth-1);
  163369. if( rc==SQLITE_OK ){
  163370. rc = fts3ExprBalance(&pRight, nMaxDepth-1);
  163371. }
  163372. if( rc!=SQLITE_OK ){
  163373. sqlite3Fts3ExprFree(pRight);
  163374. sqlite3Fts3ExprFree(pLeft);
  163375. }else{
  163376. assert( pLeft && pRight );
  163377. pRoot->pLeft = pLeft;
  163378. pLeft->pParent = pRoot;
  163379. pRoot->pRight = pRight;
  163380. pRight->pParent = pRoot;
  163381. }
  163382. }
  163383. }
  163384. if( rc!=SQLITE_OK ){
  163385. sqlite3Fts3ExprFree(pRoot);
  163386. pRoot = 0;
  163387. }
  163388. *pp = pRoot;
  163389. return rc;
  163390. }
  163391. /*
  163392. ** This function is similar to sqlite3Fts3ExprParse(), with the following
  163393. ** differences:
  163394. **
  163395. ** 1. It does not do expression rebalancing.
  163396. ** 2. It does not check that the expression does not exceed the
  163397. ** maximum allowable depth.
  163398. ** 3. Even if it fails, *ppExpr may still be set to point to an
  163399. ** expression tree. It should be deleted using sqlite3Fts3ExprFree()
  163400. ** in this case.
  163401. */
  163402. static int fts3ExprParseUnbalanced(
  163403. sqlite3_tokenizer *pTokenizer, /* Tokenizer module */
  163404. int iLangid, /* Language id for tokenizer */
  163405. char **azCol, /* Array of column names for fts3 table */
  163406. int bFts4, /* True to allow FTS4-only syntax */
  163407. int nCol, /* Number of entries in azCol[] */
  163408. int iDefaultCol, /* Default column to query */
  163409. const char *z, int n, /* Text of MATCH query */
  163410. Fts3Expr **ppExpr /* OUT: Parsed query structure */
  163411. ){
  163412. int nParsed;
  163413. int rc;
  163414. ParseContext sParse;
  163415. memset(&sParse, 0, sizeof(ParseContext));
  163416. sParse.pTokenizer = pTokenizer;
  163417. sParse.iLangid = iLangid;
  163418. sParse.azCol = (const char **)azCol;
  163419. sParse.nCol = nCol;
  163420. sParse.iDefaultCol = iDefaultCol;
  163421. sParse.bFts4 = bFts4;
  163422. if( z==0 ){
  163423. *ppExpr = 0;
  163424. return SQLITE_OK;
  163425. }
  163426. if( n<0 ){
  163427. n = (int)strlen(z);
  163428. }
  163429. rc = fts3ExprParse(&sParse, z, n, ppExpr, &nParsed);
  163430. assert( rc==SQLITE_OK || *ppExpr==0 );
  163431. /* Check for mismatched parenthesis */
  163432. if( rc==SQLITE_OK && sParse.nNest ){
  163433. rc = SQLITE_ERROR;
  163434. }
  163435. return rc;
  163436. }
  163437. /*
  163438. ** Parameters z and n contain a pointer to and length of a buffer containing
  163439. ** an fts3 query expression, respectively. This function attempts to parse the
  163440. ** query expression and create a tree of Fts3Expr structures representing the
  163441. ** parsed expression. If successful, *ppExpr is set to point to the head
  163442. ** of the parsed expression tree and SQLITE_OK is returned. If an error
  163443. ** occurs, either SQLITE_NOMEM (out-of-memory error) or SQLITE_ERROR (parse
  163444. ** error) is returned and *ppExpr is set to 0.
  163445. **
  163446. ** If parameter n is a negative number, then z is assumed to point to a
  163447. ** nul-terminated string and the length is determined using strlen().
  163448. **
  163449. ** The first parameter, pTokenizer, is passed the fts3 tokenizer module to
  163450. ** use to normalize query tokens while parsing the expression. The azCol[]
  163451. ** array, which is assumed to contain nCol entries, should contain the names
  163452. ** of each column in the target fts3 table, in order from left to right.
  163453. ** Column names must be nul-terminated strings.
  163454. **
  163455. ** The iDefaultCol parameter should be passed the index of the table column
  163456. ** that appears on the left-hand-side of the MATCH operator (the default
  163457. ** column to match against for tokens for which a column name is not explicitly
  163458. ** specified as part of the query string), or -1 if tokens may by default
  163459. ** match any table column.
  163460. */
  163461. SQLITE_PRIVATE int sqlite3Fts3ExprParse(
  163462. sqlite3_tokenizer *pTokenizer, /* Tokenizer module */
  163463. int iLangid, /* Language id for tokenizer */
  163464. char **azCol, /* Array of column names for fts3 table */
  163465. int bFts4, /* True to allow FTS4-only syntax */
  163466. int nCol, /* Number of entries in azCol[] */
  163467. int iDefaultCol, /* Default column to query */
  163468. const char *z, int n, /* Text of MATCH query */
  163469. Fts3Expr **ppExpr, /* OUT: Parsed query structure */
  163470. char **pzErr /* OUT: Error message (sqlite3_malloc) */
  163471. ){
  163472. int rc = fts3ExprParseUnbalanced(
  163473. pTokenizer, iLangid, azCol, bFts4, nCol, iDefaultCol, z, n, ppExpr
  163474. );
  163475. /* Rebalance the expression. And check that its depth does not exceed
  163476. ** SQLITE_FTS3_MAX_EXPR_DEPTH. */
  163477. if( rc==SQLITE_OK && *ppExpr ){
  163478. rc = fts3ExprBalance(ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
  163479. if( rc==SQLITE_OK ){
  163480. rc = fts3ExprCheckDepth(*ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
  163481. }
  163482. }
  163483. if( rc!=SQLITE_OK ){
  163484. sqlite3Fts3ExprFree(*ppExpr);
  163485. *ppExpr = 0;
  163486. if( rc==SQLITE_TOOBIG ){
  163487. sqlite3Fts3ErrMsg(pzErr,
  163488. "FTS expression tree is too large (maximum depth %d)",
  163489. SQLITE_FTS3_MAX_EXPR_DEPTH
  163490. );
  163491. rc = SQLITE_ERROR;
  163492. }else if( rc==SQLITE_ERROR ){
  163493. sqlite3Fts3ErrMsg(pzErr, "malformed MATCH expression: [%s]", z);
  163494. }
  163495. }
  163496. return rc;
  163497. }
  163498. /*
  163499. ** Free a single node of an expression tree.
  163500. */
  163501. static void fts3FreeExprNode(Fts3Expr *p){
  163502. assert( p->eType==FTSQUERY_PHRASE || p->pPhrase==0 );
  163503. sqlite3Fts3EvalPhraseCleanup(p->pPhrase);
  163504. sqlite3_free(p->aMI);
  163505. sqlite3_free(p);
  163506. }
  163507. /*
  163508. ** Free a parsed fts3 query expression allocated by sqlite3Fts3ExprParse().
  163509. **
  163510. ** This function would be simpler if it recursively called itself. But
  163511. ** that would mean passing a sufficiently large expression to ExprParse()
  163512. ** could cause a stack overflow.
  163513. */
  163514. SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *pDel){
  163515. Fts3Expr *p;
  163516. assert( pDel==0 || pDel->pParent==0 );
  163517. for(p=pDel; p && (p->pLeft||p->pRight); p=(p->pLeft ? p->pLeft : p->pRight)){
  163518. assert( p->pParent==0 || p==p->pParent->pRight || p==p->pParent->pLeft );
  163519. }
  163520. while( p ){
  163521. Fts3Expr *pParent = p->pParent;
  163522. fts3FreeExprNode(p);
  163523. if( pParent && p==pParent->pLeft && pParent->pRight ){
  163524. p = pParent->pRight;
  163525. while( p && (p->pLeft || p->pRight) ){
  163526. assert( p==p->pParent->pRight || p==p->pParent->pLeft );
  163527. p = (p->pLeft ? p->pLeft : p->pRight);
  163528. }
  163529. }else{
  163530. p = pParent;
  163531. }
  163532. }
  163533. }
  163534. /****************************************************************************
  163535. *****************************************************************************
  163536. ** Everything after this point is just test code.
  163537. */
  163538. #ifdef SQLITE_TEST
  163539. /* #include <stdio.h> */
  163540. /*
  163541. ** Return a pointer to a buffer containing a text representation of the
  163542. ** expression passed as the first argument. The buffer is obtained from
  163543. ** sqlite3_malloc(). It is the responsibility of the caller to use
  163544. ** sqlite3_free() to release the memory. If an OOM condition is encountered,
  163545. ** NULL is returned.
  163546. **
  163547. ** If the second argument is not NULL, then its contents are prepended to
  163548. ** the returned expression text and then freed using sqlite3_free().
  163549. */
  163550. static char *exprToString(Fts3Expr *pExpr, char *zBuf){
  163551. if( pExpr==0 ){
  163552. return sqlite3_mprintf("");
  163553. }
  163554. switch( pExpr->eType ){
  163555. case FTSQUERY_PHRASE: {
  163556. Fts3Phrase *pPhrase = pExpr->pPhrase;
  163557. int i;
  163558. zBuf = sqlite3_mprintf(
  163559. "%zPHRASE %d 0", zBuf, pPhrase->iColumn);
  163560. for(i=0; zBuf && i<pPhrase->nToken; i++){
  163561. zBuf = sqlite3_mprintf("%z %.*s%s", zBuf,
  163562. pPhrase->aToken[i].n, pPhrase->aToken[i].z,
  163563. (pPhrase->aToken[i].isPrefix?"+":"")
  163564. );
  163565. }
  163566. return zBuf;
  163567. }
  163568. case FTSQUERY_NEAR:
  163569. zBuf = sqlite3_mprintf("%zNEAR/%d ", zBuf, pExpr->nNear);
  163570. break;
  163571. case FTSQUERY_NOT:
  163572. zBuf = sqlite3_mprintf("%zNOT ", zBuf);
  163573. break;
  163574. case FTSQUERY_AND:
  163575. zBuf = sqlite3_mprintf("%zAND ", zBuf);
  163576. break;
  163577. case FTSQUERY_OR:
  163578. zBuf = sqlite3_mprintf("%zOR ", zBuf);
  163579. break;
  163580. }
  163581. if( zBuf ) zBuf = sqlite3_mprintf("%z{", zBuf);
  163582. if( zBuf ) zBuf = exprToString(pExpr->pLeft, zBuf);
  163583. if( zBuf ) zBuf = sqlite3_mprintf("%z} {", zBuf);
  163584. if( zBuf ) zBuf = exprToString(pExpr->pRight, zBuf);
  163585. if( zBuf ) zBuf = sqlite3_mprintf("%z}", zBuf);
  163586. return zBuf;
  163587. }
  163588. /*
  163589. ** This is the implementation of a scalar SQL function used to test the
  163590. ** expression parser. It should be called as follows:
  163591. **
  163592. ** fts3_exprtest(<tokenizer>, <expr>, <column 1>, ...);
  163593. **
  163594. ** The first argument, <tokenizer>, is the name of the fts3 tokenizer used
  163595. ** to parse the query expression (see README.tokenizers). The second argument
  163596. ** is the query expression to parse. Each subsequent argument is the name
  163597. ** of a column of the fts3 table that the query expression may refer to.
  163598. ** For example:
  163599. **
  163600. ** SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2');
  163601. */
  163602. static void fts3ExprTestCommon(
  163603. int bRebalance,
  163604. sqlite3_context *context,
  163605. int argc,
  163606. sqlite3_value **argv
  163607. ){
  163608. sqlite3_tokenizer *pTokenizer = 0;
  163609. int rc;
  163610. char **azCol = 0;
  163611. const char *zExpr;
  163612. int nExpr;
  163613. int nCol;
  163614. int ii;
  163615. Fts3Expr *pExpr;
  163616. char *zBuf = 0;
  163617. Fts3Hash *pHash = (Fts3Hash*)sqlite3_user_data(context);
  163618. const char *zTokenizer = 0;
  163619. char *zErr = 0;
  163620. if( argc<3 ){
  163621. sqlite3_result_error(context,
  163622. "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1
  163623. );
  163624. return;
  163625. }
  163626. zTokenizer = (const char*)sqlite3_value_text(argv[0]);
  163627. rc = sqlite3Fts3InitTokenizer(pHash, zTokenizer, &pTokenizer, &zErr);
  163628. if( rc!=SQLITE_OK ){
  163629. if( rc==SQLITE_NOMEM ){
  163630. sqlite3_result_error_nomem(context);
  163631. }else{
  163632. sqlite3_result_error(context, zErr, -1);
  163633. }
  163634. sqlite3_free(zErr);
  163635. return;
  163636. }
  163637. zExpr = (const char *)sqlite3_value_text(argv[1]);
  163638. nExpr = sqlite3_value_bytes(argv[1]);
  163639. nCol = argc-2;
  163640. azCol = (char **)sqlite3_malloc64(nCol*sizeof(char *));
  163641. if( !azCol ){
  163642. sqlite3_result_error_nomem(context);
  163643. goto exprtest_out;
  163644. }
  163645. for(ii=0; ii<nCol; ii++){
  163646. azCol[ii] = (char *)sqlite3_value_text(argv[ii+2]);
  163647. }
  163648. if( bRebalance ){
  163649. char *zDummy = 0;
  163650. rc = sqlite3Fts3ExprParse(
  163651. pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr, &zDummy
  163652. );
  163653. assert( rc==SQLITE_OK || pExpr==0 );
  163654. sqlite3_free(zDummy);
  163655. }else{
  163656. rc = fts3ExprParseUnbalanced(
  163657. pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr
  163658. );
  163659. }
  163660. if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM ){
  163661. sqlite3Fts3ExprFree(pExpr);
  163662. sqlite3_result_error(context, "Error parsing expression", -1);
  163663. }else if( rc==SQLITE_NOMEM || !(zBuf = exprToString(pExpr, 0)) ){
  163664. sqlite3_result_error_nomem(context);
  163665. }else{
  163666. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  163667. sqlite3_free(zBuf);
  163668. }
  163669. sqlite3Fts3ExprFree(pExpr);
  163670. exprtest_out:
  163671. if( pTokenizer ){
  163672. rc = pTokenizer->pModule->xDestroy(pTokenizer);
  163673. }
  163674. sqlite3_free(azCol);
  163675. }
  163676. static void fts3ExprTest(
  163677. sqlite3_context *context,
  163678. int argc,
  163679. sqlite3_value **argv
  163680. ){
  163681. fts3ExprTestCommon(0, context, argc, argv);
  163682. }
  163683. static void fts3ExprTestRebalance(
  163684. sqlite3_context *context,
  163685. int argc,
  163686. sqlite3_value **argv
  163687. ){
  163688. fts3ExprTestCommon(1, context, argc, argv);
  163689. }
  163690. /*
  163691. ** Register the query expression parser test function fts3_exprtest()
  163692. ** with database connection db.
  163693. */
  163694. SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db, Fts3Hash *pHash){
  163695. int rc = sqlite3_create_function(
  163696. db, "fts3_exprtest", -1, SQLITE_UTF8, (void*)pHash, fts3ExprTest, 0, 0
  163697. );
  163698. if( rc==SQLITE_OK ){
  163699. rc = sqlite3_create_function(db, "fts3_exprtest_rebalance",
  163700. -1, SQLITE_UTF8, (void*)pHash, fts3ExprTestRebalance, 0, 0
  163701. );
  163702. }
  163703. return rc;
  163704. }
  163705. #endif
  163706. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  163707. /************** End of fts3_expr.c *******************************************/
  163708. /************** Begin file fts3_hash.c ***************************************/
  163709. /*
  163710. ** 2001 September 22
  163711. **
  163712. ** The author disclaims copyright to this source code. In place of
  163713. ** a legal notice, here is a blessing:
  163714. **
  163715. ** May you do good and not evil.
  163716. ** May you find forgiveness for yourself and forgive others.
  163717. ** May you share freely, never taking more than you give.
  163718. **
  163719. *************************************************************************
  163720. ** This is the implementation of generic hash-tables used in SQLite.
  163721. ** We've modified it slightly to serve as a standalone hash table
  163722. ** implementation for the full-text indexing module.
  163723. */
  163724. /*
  163725. ** The code in this file is only compiled if:
  163726. **
  163727. ** * The FTS3 module is being built as an extension
  163728. ** (in which case SQLITE_CORE is not defined), or
  163729. **
  163730. ** * The FTS3 module is being built into the core of
  163731. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  163732. */
  163733. /* #include "fts3Int.h" */
  163734. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  163735. /* #include <assert.h> */
  163736. /* #include <stdlib.h> */
  163737. /* #include <string.h> */
  163738. /* #include "fts3_hash.h" */
  163739. /*
  163740. ** Malloc and Free functions
  163741. */
  163742. static void *fts3HashMalloc(sqlite3_int64 n){
  163743. void *p = sqlite3_malloc64(n);
  163744. if( p ){
  163745. memset(p, 0, n);
  163746. }
  163747. return p;
  163748. }
  163749. static void fts3HashFree(void *p){
  163750. sqlite3_free(p);
  163751. }
  163752. /* Turn bulk memory into a hash table object by initializing the
  163753. ** fields of the Hash structure.
  163754. **
  163755. ** "pNew" is a pointer to the hash table that is to be initialized.
  163756. ** keyClass is one of the constants
  163757. ** FTS3_HASH_BINARY or FTS3_HASH_STRING. The value of keyClass
  163758. ** determines what kind of key the hash table will use. "copyKey" is
  163759. ** true if the hash table should make its own private copy of keys and
  163760. ** false if it should just use the supplied pointer.
  163761. */
  163762. SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey){
  163763. assert( pNew!=0 );
  163764. assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );
  163765. pNew->keyClass = keyClass;
  163766. pNew->copyKey = copyKey;
  163767. pNew->first = 0;
  163768. pNew->count = 0;
  163769. pNew->htsize = 0;
  163770. pNew->ht = 0;
  163771. }
  163772. /* Remove all entries from a hash table. Reclaim all memory.
  163773. ** Call this routine to delete a hash table or to reset a hash table
  163774. ** to the empty state.
  163775. */
  163776. SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash *pH){
  163777. Fts3HashElem *elem; /* For looping over all elements of the table */
  163778. assert( pH!=0 );
  163779. elem = pH->first;
  163780. pH->first = 0;
  163781. fts3HashFree(pH->ht);
  163782. pH->ht = 0;
  163783. pH->htsize = 0;
  163784. while( elem ){
  163785. Fts3HashElem *next_elem = elem->next;
  163786. if( pH->copyKey && elem->pKey ){
  163787. fts3HashFree(elem->pKey);
  163788. }
  163789. fts3HashFree(elem);
  163790. elem = next_elem;
  163791. }
  163792. pH->count = 0;
  163793. }
  163794. /*
  163795. ** Hash and comparison functions when the mode is FTS3_HASH_STRING
  163796. */
  163797. static int fts3StrHash(const void *pKey, int nKey){
  163798. const char *z = (const char *)pKey;
  163799. unsigned h = 0;
  163800. if( nKey<=0 ) nKey = (int) strlen(z);
  163801. while( nKey > 0 ){
  163802. h = (h<<3) ^ h ^ *z++;
  163803. nKey--;
  163804. }
  163805. return (int)(h & 0x7fffffff);
  163806. }
  163807. static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
  163808. if( n1!=n2 ) return 1;
  163809. return strncmp((const char*)pKey1,(const char*)pKey2,n1);
  163810. }
  163811. /*
  163812. ** Hash and comparison functions when the mode is FTS3_HASH_BINARY
  163813. */
  163814. static int fts3BinHash(const void *pKey, int nKey){
  163815. int h = 0;
  163816. const char *z = (const char *)pKey;
  163817. while( nKey-- > 0 ){
  163818. h = (h<<3) ^ h ^ *(z++);
  163819. }
  163820. return h & 0x7fffffff;
  163821. }
  163822. static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
  163823. if( n1!=n2 ) return 1;
  163824. return memcmp(pKey1,pKey2,n1);
  163825. }
  163826. /*
  163827. ** Return a pointer to the appropriate hash function given the key class.
  163828. **
  163829. ** The C syntax in this function definition may be unfamilar to some
  163830. ** programmers, so we provide the following additional explanation:
  163831. **
  163832. ** The name of the function is "ftsHashFunction". The function takes a
  163833. ** single parameter "keyClass". The return value of ftsHashFunction()
  163834. ** is a pointer to another function. Specifically, the return value
  163835. ** of ftsHashFunction() is a pointer to a function that takes two parameters
  163836. ** with types "const void*" and "int" and returns an "int".
  163837. */
  163838. static int (*ftsHashFunction(int keyClass))(const void*,int){
  163839. if( keyClass==FTS3_HASH_STRING ){
  163840. return &fts3StrHash;
  163841. }else{
  163842. assert( keyClass==FTS3_HASH_BINARY );
  163843. return &fts3BinHash;
  163844. }
  163845. }
  163846. /*
  163847. ** Return a pointer to the appropriate hash function given the key class.
  163848. **
  163849. ** For help in interpreted the obscure C code in the function definition,
  163850. ** see the header comment on the previous function.
  163851. */
  163852. static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){
  163853. if( keyClass==FTS3_HASH_STRING ){
  163854. return &fts3StrCompare;
  163855. }else{
  163856. assert( keyClass==FTS3_HASH_BINARY );
  163857. return &fts3BinCompare;
  163858. }
  163859. }
  163860. /* Link an element into the hash table
  163861. */
  163862. static void fts3HashInsertElement(
  163863. Fts3Hash *pH, /* The complete hash table */
  163864. struct _fts3ht *pEntry, /* The entry into which pNew is inserted */
  163865. Fts3HashElem *pNew /* The element to be inserted */
  163866. ){
  163867. Fts3HashElem *pHead; /* First element already in pEntry */
  163868. pHead = pEntry->chain;
  163869. if( pHead ){
  163870. pNew->next = pHead;
  163871. pNew->prev = pHead->prev;
  163872. if( pHead->prev ){ pHead->prev->next = pNew; }
  163873. else { pH->first = pNew; }
  163874. pHead->prev = pNew;
  163875. }else{
  163876. pNew->next = pH->first;
  163877. if( pH->first ){ pH->first->prev = pNew; }
  163878. pNew->prev = 0;
  163879. pH->first = pNew;
  163880. }
  163881. pEntry->count++;
  163882. pEntry->chain = pNew;
  163883. }
  163884. /* Resize the hash table so that it cantains "new_size" buckets.
  163885. ** "new_size" must be a power of 2. The hash table might fail
  163886. ** to resize if sqliteMalloc() fails.
  163887. **
  163888. ** Return non-zero if a memory allocation error occurs.
  163889. */
  163890. static int fts3Rehash(Fts3Hash *pH, int new_size){
  163891. struct _fts3ht *new_ht; /* The new hash table */
  163892. Fts3HashElem *elem, *next_elem; /* For looping over existing elements */
  163893. int (*xHash)(const void*,int); /* The hash function */
  163894. assert( (new_size & (new_size-1))==0 );
  163895. new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );
  163896. if( new_ht==0 ) return 1;
  163897. fts3HashFree(pH->ht);
  163898. pH->ht = new_ht;
  163899. pH->htsize = new_size;
  163900. xHash = ftsHashFunction(pH->keyClass);
  163901. for(elem=pH->first, pH->first=0; elem; elem = next_elem){
  163902. int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
  163903. next_elem = elem->next;
  163904. fts3HashInsertElement(pH, &new_ht[h], elem);
  163905. }
  163906. return 0;
  163907. }
  163908. /* This function (for internal use only) locates an element in an
  163909. ** hash table that matches the given key. The hash for this key has
  163910. ** already been computed and is passed as the 4th parameter.
  163911. */
  163912. static Fts3HashElem *fts3FindElementByHash(
  163913. const Fts3Hash *pH, /* The pH to be searched */
  163914. const void *pKey, /* The key we are searching for */
  163915. int nKey,
  163916. int h /* The hash for this key. */
  163917. ){
  163918. Fts3HashElem *elem; /* Used to loop thru the element list */
  163919. int count; /* Number of elements left to test */
  163920. int (*xCompare)(const void*,int,const void*,int); /* comparison function */
  163921. if( pH->ht ){
  163922. struct _fts3ht *pEntry = &pH->ht[h];
  163923. elem = pEntry->chain;
  163924. count = pEntry->count;
  163925. xCompare = ftsCompareFunction(pH->keyClass);
  163926. while( count-- && elem ){
  163927. if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){
  163928. return elem;
  163929. }
  163930. elem = elem->next;
  163931. }
  163932. }
  163933. return 0;
  163934. }
  163935. /* Remove a single entry from the hash table given a pointer to that
  163936. ** element and a hash on the element's key.
  163937. */
  163938. static void fts3RemoveElementByHash(
  163939. Fts3Hash *pH, /* The pH containing "elem" */
  163940. Fts3HashElem* elem, /* The element to be removed from the pH */
  163941. int h /* Hash value for the element */
  163942. ){
  163943. struct _fts3ht *pEntry;
  163944. if( elem->prev ){
  163945. elem->prev->next = elem->next;
  163946. }else{
  163947. pH->first = elem->next;
  163948. }
  163949. if( elem->next ){
  163950. elem->next->prev = elem->prev;
  163951. }
  163952. pEntry = &pH->ht[h];
  163953. if( pEntry->chain==elem ){
  163954. pEntry->chain = elem->next;
  163955. }
  163956. pEntry->count--;
  163957. if( pEntry->count<=0 ){
  163958. pEntry->chain = 0;
  163959. }
  163960. if( pH->copyKey && elem->pKey ){
  163961. fts3HashFree(elem->pKey);
  163962. }
  163963. fts3HashFree( elem );
  163964. pH->count--;
  163965. if( pH->count<=0 ){
  163966. assert( pH->first==0 );
  163967. assert( pH->count==0 );
  163968. fts3HashClear(pH);
  163969. }
  163970. }
  163971. SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(
  163972. const Fts3Hash *pH,
  163973. const void *pKey,
  163974. int nKey
  163975. ){
  163976. int h; /* A hash on key */
  163977. int (*xHash)(const void*,int); /* The hash function */
  163978. if( pH==0 || pH->ht==0 ) return 0;
  163979. xHash = ftsHashFunction(pH->keyClass);
  163980. assert( xHash!=0 );
  163981. h = (*xHash)(pKey,nKey);
  163982. assert( (pH->htsize & (pH->htsize-1))==0 );
  163983. return fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
  163984. }
  163985. /*
  163986. ** Attempt to locate an element of the hash table pH with a key
  163987. ** that matches pKey,nKey. Return the data for this element if it is
  163988. ** found, or NULL if there is no match.
  163989. */
  163990. SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash *pH, const void *pKey, int nKey){
  163991. Fts3HashElem *pElem; /* The element that matches key (if any) */
  163992. pElem = sqlite3Fts3HashFindElem(pH, pKey, nKey);
  163993. return pElem ? pElem->data : 0;
  163994. }
  163995. /* Insert an element into the hash table pH. The key is pKey,nKey
  163996. ** and the data is "data".
  163997. **
  163998. ** If no element exists with a matching key, then a new
  163999. ** element is created. A copy of the key is made if the copyKey
  164000. ** flag is set. NULL is returned.
  164001. **
  164002. ** If another element already exists with the same key, then the
  164003. ** new data replaces the old data and the old data is returned.
  164004. ** The key is not copied in this instance. If a malloc fails, then
  164005. ** the new data is returned and the hash table is unchanged.
  164006. **
  164007. ** If the "data" parameter to this function is NULL, then the
  164008. ** element corresponding to "key" is removed from the hash table.
  164009. */
  164010. SQLITE_PRIVATE void *sqlite3Fts3HashInsert(
  164011. Fts3Hash *pH, /* The hash table to insert into */
  164012. const void *pKey, /* The key */
  164013. int nKey, /* Number of bytes in the key */
  164014. void *data /* The data */
  164015. ){
  164016. int hraw; /* Raw hash value of the key */
  164017. int h; /* the hash of the key modulo hash table size */
  164018. Fts3HashElem *elem; /* Used to loop thru the element list */
  164019. Fts3HashElem *new_elem; /* New element added to the pH */
  164020. int (*xHash)(const void*,int); /* The hash function */
  164021. assert( pH!=0 );
  164022. xHash = ftsHashFunction(pH->keyClass);
  164023. assert( xHash!=0 );
  164024. hraw = (*xHash)(pKey, nKey);
  164025. assert( (pH->htsize & (pH->htsize-1))==0 );
  164026. h = hraw & (pH->htsize-1);
  164027. elem = fts3FindElementByHash(pH,pKey,nKey,h);
  164028. if( elem ){
  164029. void *old_data = elem->data;
  164030. if( data==0 ){
  164031. fts3RemoveElementByHash(pH,elem,h);
  164032. }else{
  164033. elem->data = data;
  164034. }
  164035. return old_data;
  164036. }
  164037. if( data==0 ) return 0;
  164038. if( (pH->htsize==0 && fts3Rehash(pH,8))
  164039. || (pH->count>=pH->htsize && fts3Rehash(pH, pH->htsize*2))
  164040. ){
  164041. pH->count = 0;
  164042. return data;
  164043. }
  164044. assert( pH->htsize>0 );
  164045. new_elem = (Fts3HashElem*)fts3HashMalloc( sizeof(Fts3HashElem) );
  164046. if( new_elem==0 ) return data;
  164047. if( pH->copyKey && pKey!=0 ){
  164048. new_elem->pKey = fts3HashMalloc( nKey );
  164049. if( new_elem->pKey==0 ){
  164050. fts3HashFree(new_elem);
  164051. return data;
  164052. }
  164053. memcpy((void*)new_elem->pKey, pKey, nKey);
  164054. }else{
  164055. new_elem->pKey = (void*)pKey;
  164056. }
  164057. new_elem->nKey = nKey;
  164058. pH->count++;
  164059. assert( pH->htsize>0 );
  164060. assert( (pH->htsize & (pH->htsize-1))==0 );
  164061. h = hraw & (pH->htsize-1);
  164062. fts3HashInsertElement(pH, &pH->ht[h], new_elem);
  164063. new_elem->data = data;
  164064. return 0;
  164065. }
  164066. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  164067. /************** End of fts3_hash.c *******************************************/
  164068. /************** Begin file fts3_porter.c *************************************/
  164069. /*
  164070. ** 2006 September 30
  164071. **
  164072. ** The author disclaims copyright to this source code. In place of
  164073. ** a legal notice, here is a blessing:
  164074. **
  164075. ** May you do good and not evil.
  164076. ** May you find forgiveness for yourself and forgive others.
  164077. ** May you share freely, never taking more than you give.
  164078. **
  164079. *************************************************************************
  164080. ** Implementation of the full-text-search tokenizer that implements
  164081. ** a Porter stemmer.
  164082. */
  164083. /*
  164084. ** The code in this file is only compiled if:
  164085. **
  164086. ** * The FTS3 module is being built as an extension
  164087. ** (in which case SQLITE_CORE is not defined), or
  164088. **
  164089. ** * The FTS3 module is being built into the core of
  164090. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  164091. */
  164092. /* #include "fts3Int.h" */
  164093. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  164094. /* #include <assert.h> */
  164095. /* #include <stdlib.h> */
  164096. /* #include <stdio.h> */
  164097. /* #include <string.h> */
  164098. /* #include "fts3_tokenizer.h" */
  164099. /*
  164100. ** Class derived from sqlite3_tokenizer
  164101. */
  164102. typedef struct porter_tokenizer {
  164103. sqlite3_tokenizer base; /* Base class */
  164104. } porter_tokenizer;
  164105. /*
  164106. ** Class derived from sqlite3_tokenizer_cursor
  164107. */
  164108. typedef struct porter_tokenizer_cursor {
  164109. sqlite3_tokenizer_cursor base;
  164110. const char *zInput; /* input we are tokenizing */
  164111. int nInput; /* size of the input */
  164112. int iOffset; /* current position in zInput */
  164113. int iToken; /* index of next token to be returned */
  164114. char *zToken; /* storage for current token */
  164115. int nAllocated; /* space allocated to zToken buffer */
  164116. } porter_tokenizer_cursor;
  164117. /*
  164118. ** Create a new tokenizer instance.
  164119. */
  164120. static int porterCreate(
  164121. int argc, const char * const *argv,
  164122. sqlite3_tokenizer **ppTokenizer
  164123. ){
  164124. porter_tokenizer *t;
  164125. UNUSED_PARAMETER(argc);
  164126. UNUSED_PARAMETER(argv);
  164127. t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));
  164128. if( t==NULL ) return SQLITE_NOMEM;
  164129. memset(t, 0, sizeof(*t));
  164130. *ppTokenizer = &t->base;
  164131. return SQLITE_OK;
  164132. }
  164133. /*
  164134. ** Destroy a tokenizer
  164135. */
  164136. static int porterDestroy(sqlite3_tokenizer *pTokenizer){
  164137. sqlite3_free(pTokenizer);
  164138. return SQLITE_OK;
  164139. }
  164140. /*
  164141. ** Prepare to begin tokenizing a particular string. The input
  164142. ** string to be tokenized is zInput[0..nInput-1]. A cursor
  164143. ** used to incrementally tokenize this string is returned in
  164144. ** *ppCursor.
  164145. */
  164146. static int porterOpen(
  164147. sqlite3_tokenizer *pTokenizer, /* The tokenizer */
  164148. const char *zInput, int nInput, /* String to be tokenized */
  164149. sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
  164150. ){
  164151. porter_tokenizer_cursor *c;
  164152. UNUSED_PARAMETER(pTokenizer);
  164153. c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
  164154. if( c==NULL ) return SQLITE_NOMEM;
  164155. c->zInput = zInput;
  164156. if( zInput==0 ){
  164157. c->nInput = 0;
  164158. }else if( nInput<0 ){
  164159. c->nInput = (int)strlen(zInput);
  164160. }else{
  164161. c->nInput = nInput;
  164162. }
  164163. c->iOffset = 0; /* start tokenizing at the beginning */
  164164. c->iToken = 0;
  164165. c->zToken = NULL; /* no space allocated, yet. */
  164166. c->nAllocated = 0;
  164167. *ppCursor = &c->base;
  164168. return SQLITE_OK;
  164169. }
  164170. /*
  164171. ** Close a tokenization cursor previously opened by a call to
  164172. ** porterOpen() above.
  164173. */
  164174. static int porterClose(sqlite3_tokenizer_cursor *pCursor){
  164175. porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
  164176. sqlite3_free(c->zToken);
  164177. sqlite3_free(c);
  164178. return SQLITE_OK;
  164179. }
  164180. /*
  164181. ** Vowel or consonant
  164182. */
  164183. static const char cType[] = {
  164184. 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
  164185. 1, 1, 1, 2, 1
  164186. };
  164187. /*
  164188. ** isConsonant() and isVowel() determine if their first character in
  164189. ** the string they point to is a consonant or a vowel, according
  164190. ** to Porter ruls.
  164191. **
  164192. ** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
  164193. ** 'Y' is a consonant unless it follows another consonant,
  164194. ** in which case it is a vowel.
  164195. **
  164196. ** In these routine, the letters are in reverse order. So the 'y' rule
  164197. ** is that 'y' is a consonant unless it is followed by another
  164198. ** consonent.
  164199. */
  164200. static int isVowel(const char*);
  164201. static int isConsonant(const char *z){
  164202. int j;
  164203. char x = *z;
  164204. if( x==0 ) return 0;
  164205. assert( x>='a' && x<='z' );
  164206. j = cType[x-'a'];
  164207. if( j<2 ) return j;
  164208. return z[1]==0 || isVowel(z + 1);
  164209. }
  164210. static int isVowel(const char *z){
  164211. int j;
  164212. char x = *z;
  164213. if( x==0 ) return 0;
  164214. assert( x>='a' && x<='z' );
  164215. j = cType[x-'a'];
  164216. if( j<2 ) return 1-j;
  164217. return isConsonant(z + 1);
  164218. }
  164219. /*
  164220. ** Let any sequence of one or more vowels be represented by V and let
  164221. ** C be sequence of one or more consonants. Then every word can be
  164222. ** represented as:
  164223. **
  164224. ** [C] (VC){m} [V]
  164225. **
  164226. ** In prose: A word is an optional consonant followed by zero or
  164227. ** vowel-consonant pairs followed by an optional vowel. "m" is the
  164228. ** number of vowel consonant pairs. This routine computes the value
  164229. ** of m for the first i bytes of a word.
  164230. **
  164231. ** Return true if the m-value for z is 1 or more. In other words,
  164232. ** return true if z contains at least one vowel that is followed
  164233. ** by a consonant.
  164234. **
  164235. ** In this routine z[] is in reverse order. So we are really looking
  164236. ** for an instance of a consonant followed by a vowel.
  164237. */
  164238. static int m_gt_0(const char *z){
  164239. while( isVowel(z) ){ z++; }
  164240. if( *z==0 ) return 0;
  164241. while( isConsonant(z) ){ z++; }
  164242. return *z!=0;
  164243. }
  164244. /* Like mgt0 above except we are looking for a value of m which is
  164245. ** exactly 1
  164246. */
  164247. static int m_eq_1(const char *z){
  164248. while( isVowel(z) ){ z++; }
  164249. if( *z==0 ) return 0;
  164250. while( isConsonant(z) ){ z++; }
  164251. if( *z==0 ) return 0;
  164252. while( isVowel(z) ){ z++; }
  164253. if( *z==0 ) return 1;
  164254. while( isConsonant(z) ){ z++; }
  164255. return *z==0;
  164256. }
  164257. /* Like mgt0 above except we are looking for a value of m>1 instead
  164258. ** or m>0
  164259. */
  164260. static int m_gt_1(const char *z){
  164261. while( isVowel(z) ){ z++; }
  164262. if( *z==0 ) return 0;
  164263. while( isConsonant(z) ){ z++; }
  164264. if( *z==0 ) return 0;
  164265. while( isVowel(z) ){ z++; }
  164266. if( *z==0 ) return 0;
  164267. while( isConsonant(z) ){ z++; }
  164268. return *z!=0;
  164269. }
  164270. /*
  164271. ** Return TRUE if there is a vowel anywhere within z[0..n-1]
  164272. */
  164273. static int hasVowel(const char *z){
  164274. while( isConsonant(z) ){ z++; }
  164275. return *z!=0;
  164276. }
  164277. /*
  164278. ** Return TRUE if the word ends in a double consonant.
  164279. **
  164280. ** The text is reversed here. So we are really looking at
  164281. ** the first two characters of z[].
  164282. */
  164283. static int doubleConsonant(const char *z){
  164284. return isConsonant(z) && z[0]==z[1];
  164285. }
  164286. /*
  164287. ** Return TRUE if the word ends with three letters which
  164288. ** are consonant-vowel-consonent and where the final consonant
  164289. ** is not 'w', 'x', or 'y'.
  164290. **
  164291. ** The word is reversed here. So we are really checking the
  164292. ** first three letters and the first one cannot be in [wxy].
  164293. */
  164294. static int star_oh(const char *z){
  164295. return
  164296. isConsonant(z) &&
  164297. z[0]!='w' && z[0]!='x' && z[0]!='y' &&
  164298. isVowel(z+1) &&
  164299. isConsonant(z+2);
  164300. }
  164301. /*
  164302. ** If the word ends with zFrom and xCond() is true for the stem
  164303. ** of the word that preceeds the zFrom ending, then change the
  164304. ** ending to zTo.
  164305. **
  164306. ** The input word *pz and zFrom are both in reverse order. zTo
  164307. ** is in normal order.
  164308. **
  164309. ** Return TRUE if zFrom matches. Return FALSE if zFrom does not
  164310. ** match. Not that TRUE is returned even if xCond() fails and
  164311. ** no substitution occurs.
  164312. */
  164313. static int stem(
  164314. char **pz, /* The word being stemmed (Reversed) */
  164315. const char *zFrom, /* If the ending matches this... (Reversed) */
  164316. const char *zTo, /* ... change the ending to this (not reversed) */
  164317. int (*xCond)(const char*) /* Condition that must be true */
  164318. ){
  164319. char *z = *pz;
  164320. while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
  164321. if( *zFrom!=0 ) return 0;
  164322. if( xCond && !xCond(z) ) return 1;
  164323. while( *zTo ){
  164324. *(--z) = *(zTo++);
  164325. }
  164326. *pz = z;
  164327. return 1;
  164328. }
  164329. /*
  164330. ** This is the fallback stemmer used when the porter stemmer is
  164331. ** inappropriate. The input word is copied into the output with
  164332. ** US-ASCII case folding. If the input word is too long (more
  164333. ** than 20 bytes if it contains no digits or more than 6 bytes if
  164334. ** it contains digits) then word is truncated to 20 or 6 bytes
  164335. ** by taking 10 or 3 bytes from the beginning and end.
  164336. */
  164337. static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
  164338. int i, mx, j;
  164339. int hasDigit = 0;
  164340. for(i=0; i<nIn; i++){
  164341. char c = zIn[i];
  164342. if( c>='A' && c<='Z' ){
  164343. zOut[i] = c - 'A' + 'a';
  164344. }else{
  164345. if( c>='0' && c<='9' ) hasDigit = 1;
  164346. zOut[i] = c;
  164347. }
  164348. }
  164349. mx = hasDigit ? 3 : 10;
  164350. if( nIn>mx*2 ){
  164351. for(j=mx, i=nIn-mx; i<nIn; i++, j++){
  164352. zOut[j] = zOut[i];
  164353. }
  164354. i = j;
  164355. }
  164356. zOut[i] = 0;
  164357. *pnOut = i;
  164358. }
  164359. /*
  164360. ** Stem the input word zIn[0..nIn-1]. Store the output in zOut.
  164361. ** zOut is at least big enough to hold nIn bytes. Write the actual
  164362. ** size of the output word (exclusive of the '\0' terminator) into *pnOut.
  164363. **
  164364. ** Any upper-case characters in the US-ASCII character set ([A-Z])
  164365. ** are converted to lower case. Upper-case UTF characters are
  164366. ** unchanged.
  164367. **
  164368. ** Words that are longer than about 20 bytes are stemmed by retaining
  164369. ** a few bytes from the beginning and the end of the word. If the
  164370. ** word contains digits, 3 bytes are taken from the beginning and
  164371. ** 3 bytes from the end. For long words without digits, 10 bytes
  164372. ** are taken from each end. US-ASCII case folding still applies.
  164373. **
  164374. ** If the input word contains not digits but does characters not
  164375. ** in [a-zA-Z] then no stemming is attempted and this routine just
  164376. ** copies the input into the input into the output with US-ASCII
  164377. ** case folding.
  164378. **
  164379. ** Stemming never increases the length of the word. So there is
  164380. ** no chance of overflowing the zOut buffer.
  164381. */
  164382. static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
  164383. int i, j;
  164384. char zReverse[28];
  164385. char *z, *z2;
  164386. if( nIn<3 || nIn>=(int)sizeof(zReverse)-7 ){
  164387. /* The word is too big or too small for the porter stemmer.
  164388. ** Fallback to the copy stemmer */
  164389. copy_stemmer(zIn, nIn, zOut, pnOut);
  164390. return;
  164391. }
  164392. for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
  164393. char c = zIn[i];
  164394. if( c>='A' && c<='Z' ){
  164395. zReverse[j] = c + 'a' - 'A';
  164396. }else if( c>='a' && c<='z' ){
  164397. zReverse[j] = c;
  164398. }else{
  164399. /* The use of a character not in [a-zA-Z] means that we fallback
  164400. ** to the copy stemmer */
  164401. copy_stemmer(zIn, nIn, zOut, pnOut);
  164402. return;
  164403. }
  164404. }
  164405. memset(&zReverse[sizeof(zReverse)-5], 0, 5);
  164406. z = &zReverse[j+1];
  164407. /* Step 1a */
  164408. if( z[0]=='s' ){
  164409. if(
  164410. !stem(&z, "sess", "ss", 0) &&
  164411. !stem(&z, "sei", "i", 0) &&
  164412. !stem(&z, "ss", "ss", 0)
  164413. ){
  164414. z++;
  164415. }
  164416. }
  164417. /* Step 1b */
  164418. z2 = z;
  164419. if( stem(&z, "dee", "ee", m_gt_0) ){
  164420. /* Do nothing. The work was all in the test */
  164421. }else if(
  164422. (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
  164423. && z!=z2
  164424. ){
  164425. if( stem(&z, "ta", "ate", 0) ||
  164426. stem(&z, "lb", "ble", 0) ||
  164427. stem(&z, "zi", "ize", 0) ){
  164428. /* Do nothing. The work was all in the test */
  164429. }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
  164430. z++;
  164431. }else if( m_eq_1(z) && star_oh(z) ){
  164432. *(--z) = 'e';
  164433. }
  164434. }
  164435. /* Step 1c */
  164436. if( z[0]=='y' && hasVowel(z+1) ){
  164437. z[0] = 'i';
  164438. }
  164439. /* Step 2 */
  164440. switch( z[1] ){
  164441. case 'a':
  164442. if( !stem(&z, "lanoita", "ate", m_gt_0) ){
  164443. stem(&z, "lanoit", "tion", m_gt_0);
  164444. }
  164445. break;
  164446. case 'c':
  164447. if( !stem(&z, "icne", "ence", m_gt_0) ){
  164448. stem(&z, "icna", "ance", m_gt_0);
  164449. }
  164450. break;
  164451. case 'e':
  164452. stem(&z, "rezi", "ize", m_gt_0);
  164453. break;
  164454. case 'g':
  164455. stem(&z, "igol", "log", m_gt_0);
  164456. break;
  164457. case 'l':
  164458. if( !stem(&z, "ilb", "ble", m_gt_0)
  164459. && !stem(&z, "illa", "al", m_gt_0)
  164460. && !stem(&z, "iltne", "ent", m_gt_0)
  164461. && !stem(&z, "ile", "e", m_gt_0)
  164462. ){
  164463. stem(&z, "ilsuo", "ous", m_gt_0);
  164464. }
  164465. break;
  164466. case 'o':
  164467. if( !stem(&z, "noitazi", "ize", m_gt_0)
  164468. && !stem(&z, "noita", "ate", m_gt_0)
  164469. ){
  164470. stem(&z, "rota", "ate", m_gt_0);
  164471. }
  164472. break;
  164473. case 's':
  164474. if( !stem(&z, "msila", "al", m_gt_0)
  164475. && !stem(&z, "ssenevi", "ive", m_gt_0)
  164476. && !stem(&z, "ssenluf", "ful", m_gt_0)
  164477. ){
  164478. stem(&z, "ssensuo", "ous", m_gt_0);
  164479. }
  164480. break;
  164481. case 't':
  164482. if( !stem(&z, "itila", "al", m_gt_0)
  164483. && !stem(&z, "itivi", "ive", m_gt_0)
  164484. ){
  164485. stem(&z, "itilib", "ble", m_gt_0);
  164486. }
  164487. break;
  164488. }
  164489. /* Step 3 */
  164490. switch( z[0] ){
  164491. case 'e':
  164492. if( !stem(&z, "etaci", "ic", m_gt_0)
  164493. && !stem(&z, "evita", "", m_gt_0)
  164494. ){
  164495. stem(&z, "ezila", "al", m_gt_0);
  164496. }
  164497. break;
  164498. case 'i':
  164499. stem(&z, "itici", "ic", m_gt_0);
  164500. break;
  164501. case 'l':
  164502. if( !stem(&z, "laci", "ic", m_gt_0) ){
  164503. stem(&z, "luf", "", m_gt_0);
  164504. }
  164505. break;
  164506. case 's':
  164507. stem(&z, "ssen", "", m_gt_0);
  164508. break;
  164509. }
  164510. /* Step 4 */
  164511. switch( z[1] ){
  164512. case 'a':
  164513. if( z[0]=='l' && m_gt_1(z+2) ){
  164514. z += 2;
  164515. }
  164516. break;
  164517. case 'c':
  164518. if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e') && m_gt_1(z+4) ){
  164519. z += 4;
  164520. }
  164521. break;
  164522. case 'e':
  164523. if( z[0]=='r' && m_gt_1(z+2) ){
  164524. z += 2;
  164525. }
  164526. break;
  164527. case 'i':
  164528. if( z[0]=='c' && m_gt_1(z+2) ){
  164529. z += 2;
  164530. }
  164531. break;
  164532. case 'l':
  164533. if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
  164534. z += 4;
  164535. }
  164536. break;
  164537. case 'n':
  164538. if( z[0]=='t' ){
  164539. if( z[2]=='a' ){
  164540. if( m_gt_1(z+3) ){
  164541. z += 3;
  164542. }
  164543. }else if( z[2]=='e' ){
  164544. if( !stem(&z, "tneme", "", m_gt_1)
  164545. && !stem(&z, "tnem", "", m_gt_1)
  164546. ){
  164547. stem(&z, "tne", "", m_gt_1);
  164548. }
  164549. }
  164550. }
  164551. break;
  164552. case 'o':
  164553. if( z[0]=='u' ){
  164554. if( m_gt_1(z+2) ){
  164555. z += 2;
  164556. }
  164557. }else if( z[3]=='s' || z[3]=='t' ){
  164558. stem(&z, "noi", "", m_gt_1);
  164559. }
  164560. break;
  164561. case 's':
  164562. if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
  164563. z += 3;
  164564. }
  164565. break;
  164566. case 't':
  164567. if( !stem(&z, "eta", "", m_gt_1) ){
  164568. stem(&z, "iti", "", m_gt_1);
  164569. }
  164570. break;
  164571. case 'u':
  164572. if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
  164573. z += 3;
  164574. }
  164575. break;
  164576. case 'v':
  164577. case 'z':
  164578. if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
  164579. z += 3;
  164580. }
  164581. break;
  164582. }
  164583. /* Step 5a */
  164584. if( z[0]=='e' ){
  164585. if( m_gt_1(z+1) ){
  164586. z++;
  164587. }else if( m_eq_1(z+1) && !star_oh(z+1) ){
  164588. z++;
  164589. }
  164590. }
  164591. /* Step 5b */
  164592. if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
  164593. z++;
  164594. }
  164595. /* z[] is now the stemmed word in reverse order. Flip it back
  164596. ** around into forward order and return.
  164597. */
  164598. *pnOut = i = (int)strlen(z);
  164599. zOut[i] = 0;
  164600. while( *z ){
  164601. zOut[--i] = *(z++);
  164602. }
  164603. }
  164604. /*
  164605. ** Characters that can be part of a token. We assume any character
  164606. ** whose value is greater than 0x80 (any UTF character) can be
  164607. ** part of a token. In other words, delimiters all must have
  164608. ** values of 0x7f or lower.
  164609. */
  164610. static const char porterIdChar[] = {
  164611. /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
  164612. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */
  164613. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */
  164614. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */
  164615. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */
  164616. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */
  164617. };
  164618. #define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))
  164619. /*
  164620. ** Extract the next token from a tokenization cursor. The cursor must
  164621. ** have been opened by a prior call to porterOpen().
  164622. */
  164623. static int porterNext(
  164624. sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by porterOpen */
  164625. const char **pzToken, /* OUT: *pzToken is the token text */
  164626. int *pnBytes, /* OUT: Number of bytes in token */
  164627. int *piStartOffset, /* OUT: Starting offset of token */
  164628. int *piEndOffset, /* OUT: Ending offset of token */
  164629. int *piPosition /* OUT: Position integer of token */
  164630. ){
  164631. porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
  164632. const char *z = c->zInput;
  164633. while( c->iOffset<c->nInput ){
  164634. int iStartOffset, ch;
  164635. /* Scan past delimiter characters */
  164636. while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
  164637. c->iOffset++;
  164638. }
  164639. /* Count non-delimiter characters. */
  164640. iStartOffset = c->iOffset;
  164641. while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
  164642. c->iOffset++;
  164643. }
  164644. if( c->iOffset>iStartOffset ){
  164645. int n = c->iOffset-iStartOffset;
  164646. if( n>c->nAllocated ){
  164647. char *pNew;
  164648. c->nAllocated = n+20;
  164649. pNew = sqlite3_realloc(c->zToken, c->nAllocated);
  164650. if( !pNew ) return SQLITE_NOMEM;
  164651. c->zToken = pNew;
  164652. }
  164653. porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
  164654. *pzToken = c->zToken;
  164655. *piStartOffset = iStartOffset;
  164656. *piEndOffset = c->iOffset;
  164657. *piPosition = c->iToken++;
  164658. return SQLITE_OK;
  164659. }
  164660. }
  164661. return SQLITE_DONE;
  164662. }
  164663. /*
  164664. ** The set of routines that implement the porter-stemmer tokenizer
  164665. */
  164666. static const sqlite3_tokenizer_module porterTokenizerModule = {
  164667. 0,
  164668. porterCreate,
  164669. porterDestroy,
  164670. porterOpen,
  164671. porterClose,
  164672. porterNext,
  164673. 0
  164674. };
  164675. /*
  164676. ** Allocate a new porter tokenizer. Return a pointer to the new
  164677. ** tokenizer in *ppModule
  164678. */
  164679. SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(
  164680. sqlite3_tokenizer_module const**ppModule
  164681. ){
  164682. *ppModule = &porterTokenizerModule;
  164683. }
  164684. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  164685. /************** End of fts3_porter.c *****************************************/
  164686. /************** Begin file fts3_tokenizer.c **********************************/
  164687. /*
  164688. ** 2007 June 22
  164689. **
  164690. ** The author disclaims copyright to this source code. In place of
  164691. ** a legal notice, here is a blessing:
  164692. **
  164693. ** May you do good and not evil.
  164694. ** May you find forgiveness for yourself and forgive others.
  164695. ** May you share freely, never taking more than you give.
  164696. **
  164697. ******************************************************************************
  164698. **
  164699. ** This is part of an SQLite module implementing full-text search.
  164700. ** This particular file implements the generic tokenizer interface.
  164701. */
  164702. /*
  164703. ** The code in this file is only compiled if:
  164704. **
  164705. ** * The FTS3 module is being built as an extension
  164706. ** (in which case SQLITE_CORE is not defined), or
  164707. **
  164708. ** * The FTS3 module is being built into the core of
  164709. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  164710. */
  164711. /* #include "fts3Int.h" */
  164712. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  164713. /* #include <assert.h> */
  164714. /* #include <string.h> */
  164715. /*
  164716. ** Return true if the two-argument version of fts3_tokenizer()
  164717. ** has been activated via a prior call to sqlite3_db_config(db,
  164718. ** SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER, 1, 0);
  164719. */
  164720. static int fts3TokenizerEnabled(sqlite3_context *context){
  164721. sqlite3 *db = sqlite3_context_db_handle(context);
  164722. int isEnabled = 0;
  164723. sqlite3_db_config(db,SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER,-1,&isEnabled);
  164724. return isEnabled;
  164725. }
  164726. /*
  164727. ** Implementation of the SQL scalar function for accessing the underlying
  164728. ** hash table. This function may be called as follows:
  164729. **
  164730. ** SELECT <function-name>(<key-name>);
  164731. ** SELECT <function-name>(<key-name>, <pointer>);
  164732. **
  164733. ** where <function-name> is the name passed as the second argument
  164734. ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
  164735. **
  164736. ** If the <pointer> argument is specified, it must be a blob value
  164737. ** containing a pointer to be stored as the hash data corresponding
  164738. ** to the string <key-name>. If <pointer> is not specified, then
  164739. ** the string <key-name> must already exist in the has table. Otherwise,
  164740. ** an error is returned.
  164741. **
  164742. ** Whether or not the <pointer> argument is specified, the value returned
  164743. ** is a blob containing the pointer stored as the hash data corresponding
  164744. ** to string <key-name> (after the hash-table is updated, if applicable).
  164745. */
  164746. static void fts3TokenizerFunc(
  164747. sqlite3_context *context,
  164748. int argc,
  164749. sqlite3_value **argv
  164750. ){
  164751. Fts3Hash *pHash;
  164752. void *pPtr = 0;
  164753. const unsigned char *zName;
  164754. int nName;
  164755. assert( argc==1 || argc==2 );
  164756. pHash = (Fts3Hash *)sqlite3_user_data(context);
  164757. zName = sqlite3_value_text(argv[0]);
  164758. nName = sqlite3_value_bytes(argv[0])+1;
  164759. if( argc==2 ){
  164760. if( fts3TokenizerEnabled(context) || sqlite3_value_frombind(argv[1]) ){
  164761. void *pOld;
  164762. int n = sqlite3_value_bytes(argv[1]);
  164763. if( zName==0 || n!=sizeof(pPtr) ){
  164764. sqlite3_result_error(context, "argument type mismatch", -1);
  164765. return;
  164766. }
  164767. pPtr = *(void **)sqlite3_value_blob(argv[1]);
  164768. pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
  164769. if( pOld==pPtr ){
  164770. sqlite3_result_error(context, "out of memory", -1);
  164771. }
  164772. }else{
  164773. sqlite3_result_error(context, "fts3tokenize disabled", -1);
  164774. return;
  164775. }
  164776. }else{
  164777. if( zName ){
  164778. pPtr = sqlite3Fts3HashFind(pHash, zName, nName);
  164779. }
  164780. if( !pPtr ){
  164781. char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
  164782. sqlite3_result_error(context, zErr, -1);
  164783. sqlite3_free(zErr);
  164784. return;
  164785. }
  164786. }
  164787. if( fts3TokenizerEnabled(context) || sqlite3_value_frombind(argv[0]) ){
  164788. sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
  164789. }
  164790. }
  164791. SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char c){
  164792. static const char isFtsIdChar[] = {
  164793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */
  164794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */
  164795. 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */
  164796. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */
  164797. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */
  164798. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */
  164799. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */
  164800. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */
  164801. };
  164802. return (c&0x80 || isFtsIdChar[(int)(c)]);
  164803. }
  164804. SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *zStr, int *pn){
  164805. const char *z1;
  164806. const char *z2 = 0;
  164807. /* Find the start of the next token. */
  164808. z1 = zStr;
  164809. while( z2==0 ){
  164810. char c = *z1;
  164811. switch( c ){
  164812. case '\0': return 0; /* No more tokens here */
  164813. case '\'':
  164814. case '"':
  164815. case '`': {
  164816. z2 = z1;
  164817. while( *++z2 && (*z2!=c || *++z2==c) );
  164818. break;
  164819. }
  164820. case '[':
  164821. z2 = &z1[1];
  164822. while( *z2 && z2[0]!=']' ) z2++;
  164823. if( *z2 ) z2++;
  164824. break;
  164825. default:
  164826. if( sqlite3Fts3IsIdChar(*z1) ){
  164827. z2 = &z1[1];
  164828. while( sqlite3Fts3IsIdChar(*z2) ) z2++;
  164829. }else{
  164830. z1++;
  164831. }
  164832. }
  164833. }
  164834. *pn = (int)(z2-z1);
  164835. return z1;
  164836. }
  164837. SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(
  164838. Fts3Hash *pHash, /* Tokenizer hash table */
  164839. const char *zArg, /* Tokenizer name */
  164840. sqlite3_tokenizer **ppTok, /* OUT: Tokenizer (if applicable) */
  164841. char **pzErr /* OUT: Set to malloced error message */
  164842. ){
  164843. int rc;
  164844. char *z = (char *)zArg;
  164845. int n = 0;
  164846. char *zCopy;
  164847. char *zEnd; /* Pointer to nul-term of zCopy */
  164848. sqlite3_tokenizer_module *m;
  164849. zCopy = sqlite3_mprintf("%s", zArg);
  164850. if( !zCopy ) return SQLITE_NOMEM;
  164851. zEnd = &zCopy[strlen(zCopy)];
  164852. z = (char *)sqlite3Fts3NextToken(zCopy, &n);
  164853. if( z==0 ){
  164854. assert( n==0 );
  164855. z = zCopy;
  164856. }
  164857. z[n] = '\0';
  164858. sqlite3Fts3Dequote(z);
  164859. m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash,z,(int)strlen(z)+1);
  164860. if( !m ){
  164861. sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer: %s", z);
  164862. rc = SQLITE_ERROR;
  164863. }else{
  164864. char const **aArg = 0;
  164865. int iArg = 0;
  164866. z = &z[n+1];
  164867. while( z<zEnd && (NULL!=(z = (char *)sqlite3Fts3NextToken(z, &n))) ){
  164868. sqlite3_int64 nNew = sizeof(char *)*(iArg+1);
  164869. char const **aNew = (const char **)sqlite3_realloc64((void *)aArg, nNew);
  164870. if( !aNew ){
  164871. sqlite3_free(zCopy);
  164872. sqlite3_free((void *)aArg);
  164873. return SQLITE_NOMEM;
  164874. }
  164875. aArg = aNew;
  164876. aArg[iArg++] = z;
  164877. z[n] = '\0';
  164878. sqlite3Fts3Dequote(z);
  164879. z = &z[n+1];
  164880. }
  164881. rc = m->xCreate(iArg, aArg, ppTok);
  164882. assert( rc!=SQLITE_OK || *ppTok );
  164883. if( rc!=SQLITE_OK ){
  164884. sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer");
  164885. }else{
  164886. (*ppTok)->pModule = m;
  164887. }
  164888. sqlite3_free((void *)aArg);
  164889. }
  164890. sqlite3_free(zCopy);
  164891. return rc;
  164892. }
  164893. #ifdef SQLITE_TEST
  164894. #if defined(INCLUDE_SQLITE_TCL_H)
  164895. # include "sqlite_tcl.h"
  164896. #else
  164897. # include "tcl.h"
  164898. #endif
  164899. /* #include <string.h> */
  164900. /*
  164901. ** Implementation of a special SQL scalar function for testing tokenizers
  164902. ** designed to be used in concert with the Tcl testing framework. This
  164903. ** function must be called with two or more arguments:
  164904. **
  164905. ** SELECT <function-name>(<key-name>, ..., <input-string>);
  164906. **
  164907. ** where <function-name> is the name passed as the second argument
  164908. ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')
  164909. ** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').
  164910. **
  164911. ** The return value is a string that may be interpreted as a Tcl
  164912. ** list. For each token in the <input-string>, three elements are
  164913. ** added to the returned list. The first is the token position, the
  164914. ** second is the token text (folded, stemmed, etc.) and the third is the
  164915. ** substring of <input-string> associated with the token. For example,
  164916. ** using the built-in "simple" tokenizer:
  164917. **
  164918. ** SELECT fts_tokenizer_test('simple', 'I don't see how');
  164919. **
  164920. ** will return the string:
  164921. **
  164922. ** "{0 i I 1 dont don't 2 see see 3 how how}"
  164923. **
  164924. */
  164925. static void testFunc(
  164926. sqlite3_context *context,
  164927. int argc,
  164928. sqlite3_value **argv
  164929. ){
  164930. Fts3Hash *pHash;
  164931. sqlite3_tokenizer_module *p;
  164932. sqlite3_tokenizer *pTokenizer = 0;
  164933. sqlite3_tokenizer_cursor *pCsr = 0;
  164934. const char *zErr = 0;
  164935. const char *zName;
  164936. int nName;
  164937. const char *zInput;
  164938. int nInput;
  164939. const char *azArg[64];
  164940. const char *zToken;
  164941. int nToken = 0;
  164942. int iStart = 0;
  164943. int iEnd = 0;
  164944. int iPos = 0;
  164945. int i;
  164946. Tcl_Obj *pRet;
  164947. if( argc<2 ){
  164948. sqlite3_result_error(context, "insufficient arguments", -1);
  164949. return;
  164950. }
  164951. nName = sqlite3_value_bytes(argv[0]);
  164952. zName = (const char *)sqlite3_value_text(argv[0]);
  164953. nInput = sqlite3_value_bytes(argv[argc-1]);
  164954. zInput = (const char *)sqlite3_value_text(argv[argc-1]);
  164955. pHash = (Fts3Hash *)sqlite3_user_data(context);
  164956. p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
  164957. if( !p ){
  164958. char *zErr2 = sqlite3_mprintf("unknown tokenizer: %s", zName);
  164959. sqlite3_result_error(context, zErr2, -1);
  164960. sqlite3_free(zErr2);
  164961. return;
  164962. }
  164963. pRet = Tcl_NewObj();
  164964. Tcl_IncrRefCount(pRet);
  164965. for(i=1; i<argc-1; i++){
  164966. azArg[i-1] = (const char *)sqlite3_value_text(argv[i]);
  164967. }
  164968. if( SQLITE_OK!=p->xCreate(argc-2, azArg, &pTokenizer) ){
  164969. zErr = "error in xCreate()";
  164970. goto finish;
  164971. }
  164972. pTokenizer->pModule = p;
  164973. if( sqlite3Fts3OpenTokenizer(pTokenizer, 0, zInput, nInput, &pCsr) ){
  164974. zErr = "error in xOpen()";
  164975. goto finish;
  164976. }
  164977. while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
  164978. Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
  164979. Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
  164980. zToken = &zInput[iStart];
  164981. nToken = iEnd-iStart;
  164982. Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
  164983. }
  164984. if( SQLITE_OK!=p->xClose(pCsr) ){
  164985. zErr = "error in xClose()";
  164986. goto finish;
  164987. }
  164988. if( SQLITE_OK!=p->xDestroy(pTokenizer) ){
  164989. zErr = "error in xDestroy()";
  164990. goto finish;
  164991. }
  164992. finish:
  164993. if( zErr ){
  164994. sqlite3_result_error(context, zErr, -1);
  164995. }else{
  164996. sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
  164997. }
  164998. Tcl_DecrRefCount(pRet);
  164999. }
  165000. static
  165001. int registerTokenizer(
  165002. sqlite3 *db,
  165003. char *zName,
  165004. const sqlite3_tokenizer_module *p
  165005. ){
  165006. int rc;
  165007. sqlite3_stmt *pStmt;
  165008. const char zSql[] = "SELECT fts3_tokenizer(?, ?)";
  165009. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  165010. if( rc!=SQLITE_OK ){
  165011. return rc;
  165012. }
  165013. sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
  165014. sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
  165015. sqlite3_step(pStmt);
  165016. return sqlite3_finalize(pStmt);
  165017. }
  165018. static
  165019. int queryTokenizer(
  165020. sqlite3 *db,
  165021. char *zName,
  165022. const sqlite3_tokenizer_module **pp
  165023. ){
  165024. int rc;
  165025. sqlite3_stmt *pStmt;
  165026. const char zSql[] = "SELECT fts3_tokenizer(?)";
  165027. *pp = 0;
  165028. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  165029. if( rc!=SQLITE_OK ){
  165030. return rc;
  165031. }
  165032. sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
  165033. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  165034. if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB
  165035. && sqlite3_column_bytes(pStmt, 0)==sizeof(*pp)
  165036. ){
  165037. memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
  165038. }
  165039. }
  165040. return sqlite3_finalize(pStmt);
  165041. }
  165042. SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  165043. /*
  165044. ** Implementation of the scalar function fts3_tokenizer_internal_test().
  165045. ** This function is used for testing only, it is not included in the
  165046. ** build unless SQLITE_TEST is defined.
  165047. **
  165048. ** The purpose of this is to test that the fts3_tokenizer() function
  165049. ** can be used as designed by the C-code in the queryTokenizer and
  165050. ** registerTokenizer() functions above. These two functions are repeated
  165051. ** in the README.tokenizer file as an example, so it is important to
  165052. ** test them.
  165053. **
  165054. ** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar
  165055. ** function with no arguments. An assert() will fail if a problem is
  165056. ** detected. i.e.:
  165057. **
  165058. ** SELECT fts3_tokenizer_internal_test();
  165059. **
  165060. */
  165061. static void intTestFunc(
  165062. sqlite3_context *context,
  165063. int argc,
  165064. sqlite3_value **argv
  165065. ){
  165066. int rc;
  165067. const sqlite3_tokenizer_module *p1;
  165068. const sqlite3_tokenizer_module *p2;
  165069. sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);
  165070. UNUSED_PARAMETER(argc);
  165071. UNUSED_PARAMETER(argv);
  165072. /* Test the query function */
  165073. sqlite3Fts3SimpleTokenizerModule(&p1);
  165074. rc = queryTokenizer(db, "simple", &p2);
  165075. assert( rc==SQLITE_OK );
  165076. assert( p1==p2 );
  165077. rc = queryTokenizer(db, "nosuchtokenizer", &p2);
  165078. assert( rc==SQLITE_ERROR );
  165079. assert( p2==0 );
  165080. assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );
  165081. /* Test the storage function */
  165082. if( fts3TokenizerEnabled(context) ){
  165083. rc = registerTokenizer(db, "nosuchtokenizer", p1);
  165084. assert( rc==SQLITE_OK );
  165085. rc = queryTokenizer(db, "nosuchtokenizer", &p2);
  165086. assert( rc==SQLITE_OK );
  165087. assert( p2==p1 );
  165088. }
  165089. sqlite3_result_text(context, "ok", -1, SQLITE_STATIC);
  165090. }
  165091. #endif
  165092. /*
  165093. ** Set up SQL objects in database db used to access the contents of
  165094. ** the hash table pointed to by argument pHash. The hash table must
  165095. ** been initialized to use string keys, and to take a private copy
  165096. ** of the key when a value is inserted. i.e. by a call similar to:
  165097. **
  165098. ** sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
  165099. **
  165100. ** This function adds a scalar function (see header comment above
  165101. ** fts3TokenizerFunc() in this file for details) and, if ENABLE_TABLE is
  165102. ** defined at compilation time, a temporary virtual table (see header
  165103. ** comment above struct HashTableVtab) to the database schema. Both
  165104. ** provide read/write access to the contents of *pHash.
  165105. **
  165106. ** The third argument to this function, zName, is used as the name
  165107. ** of both the scalar and, if created, the virtual table.
  165108. */
  165109. SQLITE_PRIVATE int sqlite3Fts3InitHashTable(
  165110. sqlite3 *db,
  165111. Fts3Hash *pHash,
  165112. const char *zName
  165113. ){
  165114. int rc = SQLITE_OK;
  165115. void *p = (void *)pHash;
  165116. const int any = SQLITE_UTF8|SQLITE_DIRECTONLY;
  165117. #ifdef SQLITE_TEST
  165118. char *zTest = 0;
  165119. char *zTest2 = 0;
  165120. void *pdb = (void *)db;
  165121. zTest = sqlite3_mprintf("%s_test", zName);
  165122. zTest2 = sqlite3_mprintf("%s_internal_test", zName);
  165123. if( !zTest || !zTest2 ){
  165124. rc = SQLITE_NOMEM;
  165125. }
  165126. #endif
  165127. if( SQLITE_OK==rc ){
  165128. rc = sqlite3_create_function(db, zName, 1, any, p, fts3TokenizerFunc, 0, 0);
  165129. }
  165130. if( SQLITE_OK==rc ){
  165131. rc = sqlite3_create_function(db, zName, 2, any, p, fts3TokenizerFunc, 0, 0);
  165132. }
  165133. #ifdef SQLITE_TEST
  165134. if( SQLITE_OK==rc ){
  165135. rc = sqlite3_create_function(db, zTest, -1, any, p, testFunc, 0, 0);
  165136. }
  165137. if( SQLITE_OK==rc ){
  165138. rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0);
  165139. }
  165140. #endif
  165141. #ifdef SQLITE_TEST
  165142. sqlite3_free(zTest);
  165143. sqlite3_free(zTest2);
  165144. #endif
  165145. return rc;
  165146. }
  165147. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  165148. /************** End of fts3_tokenizer.c **************************************/
  165149. /************** Begin file fts3_tokenizer1.c *********************************/
  165150. /*
  165151. ** 2006 Oct 10
  165152. **
  165153. ** The author disclaims copyright to this source code. In place of
  165154. ** a legal notice, here is a blessing:
  165155. **
  165156. ** May you do good and not evil.
  165157. ** May you find forgiveness for yourself and forgive others.
  165158. ** May you share freely, never taking more than you give.
  165159. **
  165160. ******************************************************************************
  165161. **
  165162. ** Implementation of the "simple" full-text-search tokenizer.
  165163. */
  165164. /*
  165165. ** The code in this file is only compiled if:
  165166. **
  165167. ** * The FTS3 module is being built as an extension
  165168. ** (in which case SQLITE_CORE is not defined), or
  165169. **
  165170. ** * The FTS3 module is being built into the core of
  165171. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  165172. */
  165173. /* #include "fts3Int.h" */
  165174. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  165175. /* #include <assert.h> */
  165176. /* #include <stdlib.h> */
  165177. /* #include <stdio.h> */
  165178. /* #include <string.h> */
  165179. /* #include "fts3_tokenizer.h" */
  165180. typedef struct simple_tokenizer {
  165181. sqlite3_tokenizer base;
  165182. char delim[128]; /* flag ASCII delimiters */
  165183. } simple_tokenizer;
  165184. typedef struct simple_tokenizer_cursor {
  165185. sqlite3_tokenizer_cursor base;
  165186. const char *pInput; /* input we are tokenizing */
  165187. int nBytes; /* size of the input */
  165188. int iOffset; /* current position in pInput */
  165189. int iToken; /* index of next token to be returned */
  165190. char *pToken; /* storage for current token */
  165191. int nTokenAllocated; /* space allocated to zToken buffer */
  165192. } simple_tokenizer_cursor;
  165193. static int simpleDelim(simple_tokenizer *t, unsigned char c){
  165194. return c<0x80 && t->delim[c];
  165195. }
  165196. static int fts3_isalnum(int x){
  165197. return (x>='0' && x<='9') || (x>='A' && x<='Z') || (x>='a' && x<='z');
  165198. }
  165199. /*
  165200. ** Create a new tokenizer instance.
  165201. */
  165202. static int simpleCreate(
  165203. int argc, const char * const *argv,
  165204. sqlite3_tokenizer **ppTokenizer
  165205. ){
  165206. simple_tokenizer *t;
  165207. t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));
  165208. if( t==NULL ) return SQLITE_NOMEM;
  165209. memset(t, 0, sizeof(*t));
  165210. /* TODO(shess) Delimiters need to remain the same from run to run,
  165211. ** else we need to reindex. One solution would be a meta-table to
  165212. ** track such information in the database, then we'd only want this
  165213. ** information on the initial create.
  165214. */
  165215. if( argc>1 ){
  165216. int i, n = (int)strlen(argv[1]);
  165217. for(i=0; i<n; i++){
  165218. unsigned char ch = argv[1][i];
  165219. /* We explicitly don't support UTF-8 delimiters for now. */
  165220. if( ch>=0x80 ){
  165221. sqlite3_free(t);
  165222. return SQLITE_ERROR;
  165223. }
  165224. t->delim[ch] = 1;
  165225. }
  165226. } else {
  165227. /* Mark non-alphanumeric ASCII characters as delimiters */
  165228. int i;
  165229. for(i=1; i<0x80; i++){
  165230. t->delim[i] = !fts3_isalnum(i) ? -1 : 0;
  165231. }
  165232. }
  165233. *ppTokenizer = &t->base;
  165234. return SQLITE_OK;
  165235. }
  165236. /*
  165237. ** Destroy a tokenizer
  165238. */
  165239. static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
  165240. sqlite3_free(pTokenizer);
  165241. return SQLITE_OK;
  165242. }
  165243. /*
  165244. ** Prepare to begin tokenizing a particular string. The input
  165245. ** string to be tokenized is pInput[0..nBytes-1]. A cursor
  165246. ** used to incrementally tokenize this string is returned in
  165247. ** *ppCursor.
  165248. */
  165249. static int simpleOpen(
  165250. sqlite3_tokenizer *pTokenizer, /* The tokenizer */
  165251. const char *pInput, int nBytes, /* String to be tokenized */
  165252. sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
  165253. ){
  165254. simple_tokenizer_cursor *c;
  165255. UNUSED_PARAMETER(pTokenizer);
  165256. c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
  165257. if( c==NULL ) return SQLITE_NOMEM;
  165258. c->pInput = pInput;
  165259. if( pInput==0 ){
  165260. c->nBytes = 0;
  165261. }else if( nBytes<0 ){
  165262. c->nBytes = (int)strlen(pInput);
  165263. }else{
  165264. c->nBytes = nBytes;
  165265. }
  165266. c->iOffset = 0; /* start tokenizing at the beginning */
  165267. c->iToken = 0;
  165268. c->pToken = NULL; /* no space allocated, yet. */
  165269. c->nTokenAllocated = 0;
  165270. *ppCursor = &c->base;
  165271. return SQLITE_OK;
  165272. }
  165273. /*
  165274. ** Close a tokenization cursor previously opened by a call to
  165275. ** simpleOpen() above.
  165276. */
  165277. static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
  165278. simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
  165279. sqlite3_free(c->pToken);
  165280. sqlite3_free(c);
  165281. return SQLITE_OK;
  165282. }
  165283. /*
  165284. ** Extract the next token from a tokenization cursor. The cursor must
  165285. ** have been opened by a prior call to simpleOpen().
  165286. */
  165287. static int simpleNext(
  165288. sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by simpleOpen */
  165289. const char **ppToken, /* OUT: *ppToken is the token text */
  165290. int *pnBytes, /* OUT: Number of bytes in token */
  165291. int *piStartOffset, /* OUT: Starting offset of token */
  165292. int *piEndOffset, /* OUT: Ending offset of token */
  165293. int *piPosition /* OUT: Position integer of token */
  165294. ){
  165295. simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
  165296. simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
  165297. unsigned char *p = (unsigned char *)c->pInput;
  165298. while( c->iOffset<c->nBytes ){
  165299. int iStartOffset;
  165300. /* Scan past delimiter characters */
  165301. while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
  165302. c->iOffset++;
  165303. }
  165304. /* Count non-delimiter characters. */
  165305. iStartOffset = c->iOffset;
  165306. while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
  165307. c->iOffset++;
  165308. }
  165309. if( c->iOffset>iStartOffset ){
  165310. int i, n = c->iOffset-iStartOffset;
  165311. if( n>c->nTokenAllocated ){
  165312. char *pNew;
  165313. c->nTokenAllocated = n+20;
  165314. pNew = sqlite3_realloc(c->pToken, c->nTokenAllocated);
  165315. if( !pNew ) return SQLITE_NOMEM;
  165316. c->pToken = pNew;
  165317. }
  165318. for(i=0; i<n; i++){
  165319. /* TODO(shess) This needs expansion to handle UTF-8
  165320. ** case-insensitivity.
  165321. */
  165322. unsigned char ch = p[iStartOffset+i];
  165323. c->pToken[i] = (char)((ch>='A' && ch<='Z') ? ch-'A'+'a' : ch);
  165324. }
  165325. *ppToken = c->pToken;
  165326. *pnBytes = n;
  165327. *piStartOffset = iStartOffset;
  165328. *piEndOffset = c->iOffset;
  165329. *piPosition = c->iToken++;
  165330. return SQLITE_OK;
  165331. }
  165332. }
  165333. return SQLITE_DONE;
  165334. }
  165335. /*
  165336. ** The set of routines that implement the simple tokenizer
  165337. */
  165338. static const sqlite3_tokenizer_module simpleTokenizerModule = {
  165339. 0,
  165340. simpleCreate,
  165341. simpleDestroy,
  165342. simpleOpen,
  165343. simpleClose,
  165344. simpleNext,
  165345. 0,
  165346. };
  165347. /*
  165348. ** Allocate a new simple tokenizer. Return a pointer to the new
  165349. ** tokenizer in *ppModule
  165350. */
  165351. SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(
  165352. sqlite3_tokenizer_module const**ppModule
  165353. ){
  165354. *ppModule = &simpleTokenizerModule;
  165355. }
  165356. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  165357. /************** End of fts3_tokenizer1.c *************************************/
  165358. /************** Begin file fts3_tokenize_vtab.c ******************************/
  165359. /*
  165360. ** 2013 Apr 22
  165361. **
  165362. ** The author disclaims copyright to this source code. In place of
  165363. ** a legal notice, here is a blessing:
  165364. **
  165365. ** May you do good and not evil.
  165366. ** May you find forgiveness for yourself and forgive others.
  165367. ** May you share freely, never taking more than you give.
  165368. **
  165369. ******************************************************************************
  165370. **
  165371. ** This file contains code for the "fts3tokenize" virtual table module.
  165372. ** An fts3tokenize virtual table is created as follows:
  165373. **
  165374. ** CREATE VIRTUAL TABLE <tbl> USING fts3tokenize(
  165375. ** <tokenizer-name>, <arg-1>, ...
  165376. ** );
  165377. **
  165378. ** The table created has the following schema:
  165379. **
  165380. ** CREATE TABLE <tbl>(input, token, start, end, position)
  165381. **
  165382. ** When queried, the query must include a WHERE clause of type:
  165383. **
  165384. ** input = <string>
  165385. **
  165386. ** The virtual table module tokenizes this <string>, using the FTS3
  165387. ** tokenizer specified by the arguments to the CREATE VIRTUAL TABLE
  165388. ** statement and returns one row for each token in the result. With
  165389. ** fields set as follows:
  165390. **
  165391. ** input: Always set to a copy of <string>
  165392. ** token: A token from the input.
  165393. ** start: Byte offset of the token within the input <string>.
  165394. ** end: Byte offset of the byte immediately following the end of the
  165395. ** token within the input string.
  165396. ** pos: Token offset of token within input.
  165397. **
  165398. */
  165399. /* #include "fts3Int.h" */
  165400. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  165401. /* #include <string.h> */
  165402. /* #include <assert.h> */
  165403. typedef struct Fts3tokTable Fts3tokTable;
  165404. typedef struct Fts3tokCursor Fts3tokCursor;
  165405. /*
  165406. ** Virtual table structure.
  165407. */
  165408. struct Fts3tokTable {
  165409. sqlite3_vtab base; /* Base class used by SQLite core */
  165410. const sqlite3_tokenizer_module *pMod;
  165411. sqlite3_tokenizer *pTok;
  165412. };
  165413. /*
  165414. ** Virtual table cursor structure.
  165415. */
  165416. struct Fts3tokCursor {
  165417. sqlite3_vtab_cursor base; /* Base class used by SQLite core */
  165418. char *zInput; /* Input string */
  165419. sqlite3_tokenizer_cursor *pCsr; /* Cursor to iterate through zInput */
  165420. int iRowid; /* Current 'rowid' value */
  165421. const char *zToken; /* Current 'token' value */
  165422. int nToken; /* Size of zToken in bytes */
  165423. int iStart; /* Current 'start' value */
  165424. int iEnd; /* Current 'end' value */
  165425. int iPos; /* Current 'pos' value */
  165426. };
  165427. /*
  165428. ** Query FTS for the tokenizer implementation named zName.
  165429. */
  165430. static int fts3tokQueryTokenizer(
  165431. Fts3Hash *pHash,
  165432. const char *zName,
  165433. const sqlite3_tokenizer_module **pp,
  165434. char **pzErr
  165435. ){
  165436. sqlite3_tokenizer_module *p;
  165437. int nName = (int)strlen(zName);
  165438. p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
  165439. if( !p ){
  165440. sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer: %s", zName);
  165441. return SQLITE_ERROR;
  165442. }
  165443. *pp = p;
  165444. return SQLITE_OK;
  165445. }
  165446. /*
  165447. ** The second argument, argv[], is an array of pointers to nul-terminated
  165448. ** strings. This function makes a copy of the array and strings into a
  165449. ** single block of memory. It then dequotes any of the strings that appear
  165450. ** to be quoted.
  165451. **
  165452. ** If successful, output parameter *pazDequote is set to point at the
  165453. ** array of dequoted strings and SQLITE_OK is returned. The caller is
  165454. ** responsible for eventually calling sqlite3_free() to free the array
  165455. ** in this case. Or, if an error occurs, an SQLite error code is returned.
  165456. ** The final value of *pazDequote is undefined in this case.
  165457. */
  165458. static int fts3tokDequoteArray(
  165459. int argc, /* Number of elements in argv[] */
  165460. const char * const *argv, /* Input array */
  165461. char ***pazDequote /* Output array */
  165462. ){
  165463. int rc = SQLITE_OK; /* Return code */
  165464. if( argc==0 ){
  165465. *pazDequote = 0;
  165466. }else{
  165467. int i;
  165468. int nByte = 0;
  165469. char **azDequote;
  165470. for(i=0; i<argc; i++){
  165471. nByte += (int)(strlen(argv[i]) + 1);
  165472. }
  165473. *pazDequote = azDequote = sqlite3_malloc64(sizeof(char *)*argc + nByte);
  165474. if( azDequote==0 ){
  165475. rc = SQLITE_NOMEM;
  165476. }else{
  165477. char *pSpace = (char *)&azDequote[argc];
  165478. for(i=0; i<argc; i++){
  165479. int n = (int)strlen(argv[i]);
  165480. azDequote[i] = pSpace;
  165481. memcpy(pSpace, argv[i], n+1);
  165482. sqlite3Fts3Dequote(pSpace);
  165483. pSpace += (n+1);
  165484. }
  165485. }
  165486. }
  165487. return rc;
  165488. }
  165489. /*
  165490. ** Schema of the tokenizer table.
  165491. */
  165492. #define FTS3_TOK_SCHEMA "CREATE TABLE x(input, token, start, end, position)"
  165493. /*
  165494. ** This function does all the work for both the xConnect and xCreate methods.
  165495. ** These tables have no persistent representation of their own, so xConnect
  165496. ** and xCreate are identical operations.
  165497. **
  165498. ** argv[0]: module name
  165499. ** argv[1]: database name
  165500. ** argv[2]: table name
  165501. ** argv[3]: first argument (tokenizer name)
  165502. */
  165503. static int fts3tokConnectMethod(
  165504. sqlite3 *db, /* Database connection */
  165505. void *pHash, /* Hash table of tokenizers */
  165506. int argc, /* Number of elements in argv array */
  165507. const char * const *argv, /* xCreate/xConnect argument array */
  165508. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  165509. char **pzErr /* OUT: sqlite3_malloc'd error message */
  165510. ){
  165511. Fts3tokTable *pTab = 0;
  165512. const sqlite3_tokenizer_module *pMod = 0;
  165513. sqlite3_tokenizer *pTok = 0;
  165514. int rc;
  165515. char **azDequote = 0;
  165516. int nDequote;
  165517. rc = sqlite3_declare_vtab(db, FTS3_TOK_SCHEMA);
  165518. if( rc!=SQLITE_OK ) return rc;
  165519. nDequote = argc-3;
  165520. rc = fts3tokDequoteArray(nDequote, &argv[3], &azDequote);
  165521. if( rc==SQLITE_OK ){
  165522. const char *zModule;
  165523. if( nDequote<1 ){
  165524. zModule = "simple";
  165525. }else{
  165526. zModule = azDequote[0];
  165527. }
  165528. rc = fts3tokQueryTokenizer((Fts3Hash*)pHash, zModule, &pMod, pzErr);
  165529. }
  165530. assert( (rc==SQLITE_OK)==(pMod!=0) );
  165531. if( rc==SQLITE_OK ){
  165532. const char * const *azArg = (const char * const *)&azDequote[1];
  165533. rc = pMod->xCreate((nDequote>1 ? nDequote-1 : 0), azArg, &pTok);
  165534. }
  165535. if( rc==SQLITE_OK ){
  165536. pTab = (Fts3tokTable *)sqlite3_malloc(sizeof(Fts3tokTable));
  165537. if( pTab==0 ){
  165538. rc = SQLITE_NOMEM;
  165539. }
  165540. }
  165541. if( rc==SQLITE_OK ){
  165542. memset(pTab, 0, sizeof(Fts3tokTable));
  165543. pTab->pMod = pMod;
  165544. pTab->pTok = pTok;
  165545. *ppVtab = &pTab->base;
  165546. }else{
  165547. if( pTok ){
  165548. pMod->xDestroy(pTok);
  165549. }
  165550. }
  165551. sqlite3_free(azDequote);
  165552. return rc;
  165553. }
  165554. /*
  165555. ** This function does the work for both the xDisconnect and xDestroy methods.
  165556. ** These tables have no persistent representation of their own, so xDisconnect
  165557. ** and xDestroy are identical operations.
  165558. */
  165559. static int fts3tokDisconnectMethod(sqlite3_vtab *pVtab){
  165560. Fts3tokTable *pTab = (Fts3tokTable *)pVtab;
  165561. pTab->pMod->xDestroy(pTab->pTok);
  165562. sqlite3_free(pTab);
  165563. return SQLITE_OK;
  165564. }
  165565. /*
  165566. ** xBestIndex - Analyze a WHERE and ORDER BY clause.
  165567. */
  165568. static int fts3tokBestIndexMethod(
  165569. sqlite3_vtab *pVTab,
  165570. sqlite3_index_info *pInfo
  165571. ){
  165572. int i;
  165573. UNUSED_PARAMETER(pVTab);
  165574. for(i=0; i<pInfo->nConstraint; i++){
  165575. if( pInfo->aConstraint[i].usable
  165576. && pInfo->aConstraint[i].iColumn==0
  165577. && pInfo->aConstraint[i].op==SQLITE_INDEX_CONSTRAINT_EQ
  165578. ){
  165579. pInfo->idxNum = 1;
  165580. pInfo->aConstraintUsage[i].argvIndex = 1;
  165581. pInfo->aConstraintUsage[i].omit = 1;
  165582. pInfo->estimatedCost = 1;
  165583. return SQLITE_OK;
  165584. }
  165585. }
  165586. pInfo->idxNum = 0;
  165587. assert( pInfo->estimatedCost>1000000.0 );
  165588. return SQLITE_OK;
  165589. }
  165590. /*
  165591. ** xOpen - Open a cursor.
  165592. */
  165593. static int fts3tokOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
  165594. Fts3tokCursor *pCsr;
  165595. UNUSED_PARAMETER(pVTab);
  165596. pCsr = (Fts3tokCursor *)sqlite3_malloc(sizeof(Fts3tokCursor));
  165597. if( pCsr==0 ){
  165598. return SQLITE_NOMEM;
  165599. }
  165600. memset(pCsr, 0, sizeof(Fts3tokCursor));
  165601. *ppCsr = (sqlite3_vtab_cursor *)pCsr;
  165602. return SQLITE_OK;
  165603. }
  165604. /*
  165605. ** Reset the tokenizer cursor passed as the only argument. As if it had
  165606. ** just been returned by fts3tokOpenMethod().
  165607. */
  165608. static void fts3tokResetCursor(Fts3tokCursor *pCsr){
  165609. if( pCsr->pCsr ){
  165610. Fts3tokTable *pTab = (Fts3tokTable *)(pCsr->base.pVtab);
  165611. pTab->pMod->xClose(pCsr->pCsr);
  165612. pCsr->pCsr = 0;
  165613. }
  165614. sqlite3_free(pCsr->zInput);
  165615. pCsr->zInput = 0;
  165616. pCsr->zToken = 0;
  165617. pCsr->nToken = 0;
  165618. pCsr->iStart = 0;
  165619. pCsr->iEnd = 0;
  165620. pCsr->iPos = 0;
  165621. pCsr->iRowid = 0;
  165622. }
  165623. /*
  165624. ** xClose - Close a cursor.
  165625. */
  165626. static int fts3tokCloseMethod(sqlite3_vtab_cursor *pCursor){
  165627. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  165628. fts3tokResetCursor(pCsr);
  165629. sqlite3_free(pCsr);
  165630. return SQLITE_OK;
  165631. }
  165632. /*
  165633. ** xNext - Advance the cursor to the next row, if any.
  165634. */
  165635. static int fts3tokNextMethod(sqlite3_vtab_cursor *pCursor){
  165636. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  165637. Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
  165638. int rc; /* Return code */
  165639. pCsr->iRowid++;
  165640. rc = pTab->pMod->xNext(pCsr->pCsr,
  165641. &pCsr->zToken, &pCsr->nToken,
  165642. &pCsr->iStart, &pCsr->iEnd, &pCsr->iPos
  165643. );
  165644. if( rc!=SQLITE_OK ){
  165645. fts3tokResetCursor(pCsr);
  165646. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  165647. }
  165648. return rc;
  165649. }
  165650. /*
  165651. ** xFilter - Initialize a cursor to point at the start of its data.
  165652. */
  165653. static int fts3tokFilterMethod(
  165654. sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
  165655. int idxNum, /* Strategy index */
  165656. const char *idxStr, /* Unused */
  165657. int nVal, /* Number of elements in apVal */
  165658. sqlite3_value **apVal /* Arguments for the indexing scheme */
  165659. ){
  165660. int rc = SQLITE_ERROR;
  165661. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  165662. Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
  165663. UNUSED_PARAMETER(idxStr);
  165664. UNUSED_PARAMETER(nVal);
  165665. fts3tokResetCursor(pCsr);
  165666. if( idxNum==1 ){
  165667. const char *zByte = (const char *)sqlite3_value_text(apVal[0]);
  165668. int nByte = sqlite3_value_bytes(apVal[0]);
  165669. pCsr->zInput = sqlite3_malloc64(nByte+1);
  165670. if( pCsr->zInput==0 ){
  165671. rc = SQLITE_NOMEM;
  165672. }else{
  165673. if( nByte>0 ) memcpy(pCsr->zInput, zByte, nByte);
  165674. pCsr->zInput[nByte] = 0;
  165675. rc = pTab->pMod->xOpen(pTab->pTok, pCsr->zInput, nByte, &pCsr->pCsr);
  165676. if( rc==SQLITE_OK ){
  165677. pCsr->pCsr->pTokenizer = pTab->pTok;
  165678. }
  165679. }
  165680. }
  165681. if( rc!=SQLITE_OK ) return rc;
  165682. return fts3tokNextMethod(pCursor);
  165683. }
  165684. /*
  165685. ** xEof - Return true if the cursor is at EOF, or false otherwise.
  165686. */
  165687. static int fts3tokEofMethod(sqlite3_vtab_cursor *pCursor){
  165688. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  165689. return (pCsr->zToken==0);
  165690. }
  165691. /*
  165692. ** xColumn - Return a column value.
  165693. */
  165694. static int fts3tokColumnMethod(
  165695. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  165696. sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
  165697. int iCol /* Index of column to read value from */
  165698. ){
  165699. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  165700. /* CREATE TABLE x(input, token, start, end, position) */
  165701. switch( iCol ){
  165702. case 0:
  165703. sqlite3_result_text(pCtx, pCsr->zInput, -1, SQLITE_TRANSIENT);
  165704. break;
  165705. case 1:
  165706. sqlite3_result_text(pCtx, pCsr->zToken, pCsr->nToken, SQLITE_TRANSIENT);
  165707. break;
  165708. case 2:
  165709. sqlite3_result_int(pCtx, pCsr->iStart);
  165710. break;
  165711. case 3:
  165712. sqlite3_result_int(pCtx, pCsr->iEnd);
  165713. break;
  165714. default:
  165715. assert( iCol==4 );
  165716. sqlite3_result_int(pCtx, pCsr->iPos);
  165717. break;
  165718. }
  165719. return SQLITE_OK;
  165720. }
  165721. /*
  165722. ** xRowid - Return the current rowid for the cursor.
  165723. */
  165724. static int fts3tokRowidMethod(
  165725. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  165726. sqlite_int64 *pRowid /* OUT: Rowid value */
  165727. ){
  165728. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  165729. *pRowid = (sqlite3_int64)pCsr->iRowid;
  165730. return SQLITE_OK;
  165731. }
  165732. /*
  165733. ** Register the fts3tok module with database connection db. Return SQLITE_OK
  165734. ** if successful or an error code if sqlite3_create_module() fails.
  165735. */
  165736. SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3 *db, Fts3Hash *pHash){
  165737. static const sqlite3_module fts3tok_module = {
  165738. 0, /* iVersion */
  165739. fts3tokConnectMethod, /* xCreate */
  165740. fts3tokConnectMethod, /* xConnect */
  165741. fts3tokBestIndexMethod, /* xBestIndex */
  165742. fts3tokDisconnectMethod, /* xDisconnect */
  165743. fts3tokDisconnectMethod, /* xDestroy */
  165744. fts3tokOpenMethod, /* xOpen */
  165745. fts3tokCloseMethod, /* xClose */
  165746. fts3tokFilterMethod, /* xFilter */
  165747. fts3tokNextMethod, /* xNext */
  165748. fts3tokEofMethod, /* xEof */
  165749. fts3tokColumnMethod, /* xColumn */
  165750. fts3tokRowidMethod, /* xRowid */
  165751. 0, /* xUpdate */
  165752. 0, /* xBegin */
  165753. 0, /* xSync */
  165754. 0, /* xCommit */
  165755. 0, /* xRollback */
  165756. 0, /* xFindFunction */
  165757. 0, /* xRename */
  165758. 0, /* xSavepoint */
  165759. 0, /* xRelease */
  165760. 0, /* xRollbackTo */
  165761. 0 /* xShadowName */
  165762. };
  165763. int rc; /* Return code */
  165764. rc = sqlite3_create_module(db, "fts3tokenize", &fts3tok_module, (void*)pHash);
  165765. return rc;
  165766. }
  165767. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  165768. /************** End of fts3_tokenize_vtab.c **********************************/
  165769. /************** Begin file fts3_write.c **************************************/
  165770. /*
  165771. ** 2009 Oct 23
  165772. **
  165773. ** The author disclaims copyright to this source code. In place of
  165774. ** a legal notice, here is a blessing:
  165775. **
  165776. ** May you do good and not evil.
  165777. ** May you find forgiveness for yourself and forgive others.
  165778. ** May you share freely, never taking more than you give.
  165779. **
  165780. ******************************************************************************
  165781. **
  165782. ** This file is part of the SQLite FTS3 extension module. Specifically,
  165783. ** this file contains code to insert, update and delete rows from FTS3
  165784. ** tables. It also contains code to merge FTS3 b-tree segments. Some
  165785. ** of the sub-routines used to merge segments are also used by the query
  165786. ** code in fts3.c.
  165787. */
  165788. /* #include "fts3Int.h" */
  165789. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  165790. /* #include <string.h> */
  165791. /* #include <assert.h> */
  165792. /* #include <stdlib.h> */
  165793. /* #include <stdio.h> */
  165794. #define FTS_MAX_APPENDABLE_HEIGHT 16
  165795. /*
  165796. ** When full-text index nodes are loaded from disk, the buffer that they
  165797. ** are loaded into has the following number of bytes of padding at the end
  165798. ** of it. i.e. if a full-text index node is 900 bytes in size, then a buffer
  165799. ** of 920 bytes is allocated for it.
  165800. **
  165801. ** This means that if we have a pointer into a buffer containing node data,
  165802. ** it is always safe to read up to two varints from it without risking an
  165803. ** overread, even if the node data is corrupted.
  165804. */
  165805. #define FTS3_NODE_PADDING (FTS3_VARINT_MAX*2)
  165806. /*
  165807. ** Under certain circumstances, b-tree nodes (doclists) can be loaded into
  165808. ** memory incrementally instead of all at once. This can be a big performance
  165809. ** win (reduced IO and CPU) if SQLite stops calling the virtual table xNext()
  165810. ** method before retrieving all query results (as may happen, for example,
  165811. ** if a query has a LIMIT clause).
  165812. **
  165813. ** Incremental loading is used for b-tree nodes FTS3_NODE_CHUNK_THRESHOLD
  165814. ** bytes and larger. Nodes are loaded in chunks of FTS3_NODE_CHUNKSIZE bytes.
  165815. ** The code is written so that the hard lower-limit for each of these values
  165816. ** is 1. Clearly such small values would be inefficient, but can be useful
  165817. ** for testing purposes.
  165818. **
  165819. ** If this module is built with SQLITE_TEST defined, these constants may
  165820. ** be overridden at runtime for testing purposes. File fts3_test.c contains
  165821. ** a Tcl interface to read and write the values.
  165822. */
  165823. #ifdef SQLITE_TEST
  165824. int test_fts3_node_chunksize = (4*1024);
  165825. int test_fts3_node_chunk_threshold = (4*1024)*4;
  165826. # define FTS3_NODE_CHUNKSIZE test_fts3_node_chunksize
  165827. # define FTS3_NODE_CHUNK_THRESHOLD test_fts3_node_chunk_threshold
  165828. #else
  165829. # define FTS3_NODE_CHUNKSIZE (4*1024)
  165830. # define FTS3_NODE_CHUNK_THRESHOLD (FTS3_NODE_CHUNKSIZE*4)
  165831. #endif
  165832. /*
  165833. ** The values that may be meaningfully bound to the :1 parameter in
  165834. ** statements SQL_REPLACE_STAT and SQL_SELECT_STAT.
  165835. */
  165836. #define FTS_STAT_DOCTOTAL 0
  165837. #define FTS_STAT_INCRMERGEHINT 1
  165838. #define FTS_STAT_AUTOINCRMERGE 2
  165839. /*
  165840. ** If FTS_LOG_MERGES is defined, call sqlite3_log() to report each automatic
  165841. ** and incremental merge operation that takes place. This is used for
  165842. ** debugging FTS only, it should not usually be turned on in production
  165843. ** systems.
  165844. */
  165845. #ifdef FTS3_LOG_MERGES
  165846. static void fts3LogMerge(int nMerge, sqlite3_int64 iAbsLevel){
  165847. sqlite3_log(SQLITE_OK, "%d-way merge from level %d", nMerge, (int)iAbsLevel);
  165848. }
  165849. #else
  165850. #define fts3LogMerge(x, y)
  165851. #endif
  165852. typedef struct PendingList PendingList;
  165853. typedef struct SegmentNode SegmentNode;
  165854. typedef struct SegmentWriter SegmentWriter;
  165855. /*
  165856. ** An instance of the following data structure is used to build doclists
  165857. ** incrementally. See function fts3PendingListAppend() for details.
  165858. */
  165859. struct PendingList {
  165860. int nData;
  165861. char *aData;
  165862. int nSpace;
  165863. sqlite3_int64 iLastDocid;
  165864. sqlite3_int64 iLastCol;
  165865. sqlite3_int64 iLastPos;
  165866. };
  165867. /*
  165868. ** Each cursor has a (possibly empty) linked list of the following objects.
  165869. */
  165870. struct Fts3DeferredToken {
  165871. Fts3PhraseToken *pToken; /* Pointer to corresponding expr token */
  165872. int iCol; /* Column token must occur in */
  165873. Fts3DeferredToken *pNext; /* Next in list of deferred tokens */
  165874. PendingList *pList; /* Doclist is assembled here */
  165875. };
  165876. /*
  165877. ** An instance of this structure is used to iterate through the terms on
  165878. ** a contiguous set of segment b-tree leaf nodes. Although the details of
  165879. ** this structure are only manipulated by code in this file, opaque handles
  165880. ** of type Fts3SegReader* are also used by code in fts3.c to iterate through
  165881. ** terms when querying the full-text index. See functions:
  165882. **
  165883. ** sqlite3Fts3SegReaderNew()
  165884. ** sqlite3Fts3SegReaderFree()
  165885. ** sqlite3Fts3SegReaderIterate()
  165886. **
  165887. ** Methods used to manipulate Fts3SegReader structures:
  165888. **
  165889. ** fts3SegReaderNext()
  165890. ** fts3SegReaderFirstDocid()
  165891. ** fts3SegReaderNextDocid()
  165892. */
  165893. struct Fts3SegReader {
  165894. int iIdx; /* Index within level, or 0x7FFFFFFF for PT */
  165895. u8 bLookup; /* True for a lookup only */
  165896. u8 rootOnly; /* True for a root-only reader */
  165897. sqlite3_int64 iStartBlock; /* Rowid of first leaf block to traverse */
  165898. sqlite3_int64 iLeafEndBlock; /* Rowid of final leaf block to traverse */
  165899. sqlite3_int64 iEndBlock; /* Rowid of final block in segment (or 0) */
  165900. sqlite3_int64 iCurrentBlock; /* Current leaf block (or 0) */
  165901. char *aNode; /* Pointer to node data (or NULL) */
  165902. int nNode; /* Size of buffer at aNode (or 0) */
  165903. int nPopulate; /* If >0, bytes of buffer aNode[] loaded */
  165904. sqlite3_blob *pBlob; /* If not NULL, blob handle to read node */
  165905. Fts3HashElem **ppNextElem;
  165906. /* Variables set by fts3SegReaderNext(). These may be read directly
  165907. ** by the caller. They are valid from the time SegmentReaderNew() returns
  165908. ** until SegmentReaderNext() returns something other than SQLITE_OK
  165909. ** (i.e. SQLITE_DONE).
  165910. */
  165911. int nTerm; /* Number of bytes in current term */
  165912. char *zTerm; /* Pointer to current term */
  165913. int nTermAlloc; /* Allocated size of zTerm buffer */
  165914. char *aDoclist; /* Pointer to doclist of current entry */
  165915. int nDoclist; /* Size of doclist in current entry */
  165916. /* The following variables are used by fts3SegReaderNextDocid() to iterate
  165917. ** through the current doclist (aDoclist/nDoclist).
  165918. */
  165919. char *pOffsetList;
  165920. int nOffsetList; /* For descending pending seg-readers only */
  165921. sqlite3_int64 iDocid;
  165922. };
  165923. #define fts3SegReaderIsPending(p) ((p)->ppNextElem!=0)
  165924. #define fts3SegReaderIsRootOnly(p) ((p)->rootOnly!=0)
  165925. /*
  165926. ** An instance of this structure is used to create a segment b-tree in the
  165927. ** database. The internal details of this type are only accessed by the
  165928. ** following functions:
  165929. **
  165930. ** fts3SegWriterAdd()
  165931. ** fts3SegWriterFlush()
  165932. ** fts3SegWriterFree()
  165933. */
  165934. struct SegmentWriter {
  165935. SegmentNode *pTree; /* Pointer to interior tree structure */
  165936. sqlite3_int64 iFirst; /* First slot in %_segments written */
  165937. sqlite3_int64 iFree; /* Next free slot in %_segments */
  165938. char *zTerm; /* Pointer to previous term buffer */
  165939. int nTerm; /* Number of bytes in zTerm */
  165940. int nMalloc; /* Size of malloc'd buffer at zMalloc */
  165941. char *zMalloc; /* Malloc'd space (possibly) used for zTerm */
  165942. int nSize; /* Size of allocation at aData */
  165943. int nData; /* Bytes of data in aData */
  165944. char *aData; /* Pointer to block from malloc() */
  165945. i64 nLeafData; /* Number of bytes of leaf data written */
  165946. };
  165947. /*
  165948. ** Type SegmentNode is used by the following three functions to create
  165949. ** the interior part of the segment b+-tree structures (everything except
  165950. ** the leaf nodes). These functions and type are only ever used by code
  165951. ** within the fts3SegWriterXXX() family of functions described above.
  165952. **
  165953. ** fts3NodeAddTerm()
  165954. ** fts3NodeWrite()
  165955. ** fts3NodeFree()
  165956. **
  165957. ** When a b+tree is written to the database (either as a result of a merge
  165958. ** or the pending-terms table being flushed), leaves are written into the
  165959. ** database file as soon as they are completely populated. The interior of
  165960. ** the tree is assembled in memory and written out only once all leaves have
  165961. ** been populated and stored. This is Ok, as the b+-tree fanout is usually
  165962. ** very large, meaning that the interior of the tree consumes relatively
  165963. ** little memory.
  165964. */
  165965. struct SegmentNode {
  165966. SegmentNode *pParent; /* Parent node (or NULL for root node) */
  165967. SegmentNode *pRight; /* Pointer to right-sibling */
  165968. SegmentNode *pLeftmost; /* Pointer to left-most node of this depth */
  165969. int nEntry; /* Number of terms written to node so far */
  165970. char *zTerm; /* Pointer to previous term buffer */
  165971. int nTerm; /* Number of bytes in zTerm */
  165972. int nMalloc; /* Size of malloc'd buffer at zMalloc */
  165973. char *zMalloc; /* Malloc'd space (possibly) used for zTerm */
  165974. int nData; /* Bytes of valid data so far */
  165975. char *aData; /* Node data */
  165976. };
  165977. /*
  165978. ** Valid values for the second argument to fts3SqlStmt().
  165979. */
  165980. #define SQL_DELETE_CONTENT 0
  165981. #define SQL_IS_EMPTY 1
  165982. #define SQL_DELETE_ALL_CONTENT 2
  165983. #define SQL_DELETE_ALL_SEGMENTS 3
  165984. #define SQL_DELETE_ALL_SEGDIR 4
  165985. #define SQL_DELETE_ALL_DOCSIZE 5
  165986. #define SQL_DELETE_ALL_STAT 6
  165987. #define SQL_SELECT_CONTENT_BY_ROWID 7
  165988. #define SQL_NEXT_SEGMENT_INDEX 8
  165989. #define SQL_INSERT_SEGMENTS 9
  165990. #define SQL_NEXT_SEGMENTS_ID 10
  165991. #define SQL_INSERT_SEGDIR 11
  165992. #define SQL_SELECT_LEVEL 12
  165993. #define SQL_SELECT_LEVEL_RANGE 13
  165994. #define SQL_SELECT_LEVEL_COUNT 14
  165995. #define SQL_SELECT_SEGDIR_MAX_LEVEL 15
  165996. #define SQL_DELETE_SEGDIR_LEVEL 16
  165997. #define SQL_DELETE_SEGMENTS_RANGE 17
  165998. #define SQL_CONTENT_INSERT 18
  165999. #define SQL_DELETE_DOCSIZE 19
  166000. #define SQL_REPLACE_DOCSIZE 20
  166001. #define SQL_SELECT_DOCSIZE 21
  166002. #define SQL_SELECT_STAT 22
  166003. #define SQL_REPLACE_STAT 23
  166004. #define SQL_SELECT_ALL_PREFIX_LEVEL 24
  166005. #define SQL_DELETE_ALL_TERMS_SEGDIR 25
  166006. #define SQL_DELETE_SEGDIR_RANGE 26
  166007. #define SQL_SELECT_ALL_LANGID 27
  166008. #define SQL_FIND_MERGE_LEVEL 28
  166009. #define SQL_MAX_LEAF_NODE_ESTIMATE 29
  166010. #define SQL_DELETE_SEGDIR_ENTRY 30
  166011. #define SQL_SHIFT_SEGDIR_ENTRY 31
  166012. #define SQL_SELECT_SEGDIR 32
  166013. #define SQL_CHOMP_SEGDIR 33
  166014. #define SQL_SEGMENT_IS_APPENDABLE 34
  166015. #define SQL_SELECT_INDEXES 35
  166016. #define SQL_SELECT_MXLEVEL 36
  166017. #define SQL_SELECT_LEVEL_RANGE2 37
  166018. #define SQL_UPDATE_LEVEL_IDX 38
  166019. #define SQL_UPDATE_LEVEL 39
  166020. /*
  166021. ** This function is used to obtain an SQLite prepared statement handle
  166022. ** for the statement identified by the second argument. If successful,
  166023. ** *pp is set to the requested statement handle and SQLITE_OK returned.
  166024. ** Otherwise, an SQLite error code is returned and *pp is set to 0.
  166025. **
  166026. ** If argument apVal is not NULL, then it must point to an array with
  166027. ** at least as many entries as the requested statement has bound
  166028. ** parameters. The values are bound to the statements parameters before
  166029. ** returning.
  166030. */
  166031. static int fts3SqlStmt(
  166032. Fts3Table *p, /* Virtual table handle */
  166033. int eStmt, /* One of the SQL_XXX constants above */
  166034. sqlite3_stmt **pp, /* OUT: Statement handle */
  166035. sqlite3_value **apVal /* Values to bind to statement */
  166036. ){
  166037. const char *azSql[] = {
  166038. /* 0 */ "DELETE FROM %Q.'%q_content' WHERE rowid = ?",
  166039. /* 1 */ "SELECT NOT EXISTS(SELECT docid FROM %Q.'%q_content' WHERE rowid!=?)",
  166040. /* 2 */ "DELETE FROM %Q.'%q_content'",
  166041. /* 3 */ "DELETE FROM %Q.'%q_segments'",
  166042. /* 4 */ "DELETE FROM %Q.'%q_segdir'",
  166043. /* 5 */ "DELETE FROM %Q.'%q_docsize'",
  166044. /* 6 */ "DELETE FROM %Q.'%q_stat'",
  166045. /* 7 */ "SELECT %s WHERE rowid=?",
  166046. /* 8 */ "SELECT (SELECT max(idx) FROM %Q.'%q_segdir' WHERE level = ?) + 1",
  166047. /* 9 */ "REPLACE INTO %Q.'%q_segments'(blockid, block) VALUES(?, ?)",
  166048. /* 10 */ "SELECT coalesce((SELECT max(blockid) FROM %Q.'%q_segments') + 1, 1)",
  166049. /* 11 */ "REPLACE INTO %Q.'%q_segdir' VALUES(?,?,?,?,?,?)",
  166050. /* Return segments in order from oldest to newest.*/
  166051. /* 12 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
  166052. "FROM %Q.'%q_segdir' WHERE level = ? ORDER BY idx ASC",
  166053. /* 13 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
  166054. "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?"
  166055. "ORDER BY level DESC, idx ASC",
  166056. /* 14 */ "SELECT count(*) FROM %Q.'%q_segdir' WHERE level = ?",
  166057. /* 15 */ "SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
  166058. /* 16 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ?",
  166059. /* 17 */ "DELETE FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ?",
  166060. /* 18 */ "INSERT INTO %Q.'%q_content' VALUES(%s)",
  166061. /* 19 */ "DELETE FROM %Q.'%q_docsize' WHERE docid = ?",
  166062. /* 20 */ "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)",
  166063. /* 21 */ "SELECT size FROM %Q.'%q_docsize' WHERE docid=?",
  166064. /* 22 */ "SELECT value FROM %Q.'%q_stat' WHERE id=?",
  166065. /* 23 */ "REPLACE INTO %Q.'%q_stat' VALUES(?,?)",
  166066. /* 24 */ "",
  166067. /* 25 */ "",
  166068. /* 26 */ "DELETE FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
  166069. /* 27 */ "SELECT ? UNION SELECT level / (1024 * ?) FROM %Q.'%q_segdir'",
  166070. /* This statement is used to determine which level to read the input from
  166071. ** when performing an incremental merge. It returns the absolute level number
  166072. ** of the oldest level in the db that contains at least ? segments. Or,
  166073. ** if no level in the FTS index contains more than ? segments, the statement
  166074. ** returns zero rows. */
  166075. /* 28 */ "SELECT level, count(*) AS cnt FROM %Q.'%q_segdir' "
  166076. " GROUP BY level HAVING cnt>=?"
  166077. " ORDER BY (level %% 1024) ASC, 2 DESC LIMIT 1",
  166078. /* Estimate the upper limit on the number of leaf nodes in a new segment
  166079. ** created by merging the oldest :2 segments from absolute level :1. See
  166080. ** function sqlite3Fts3Incrmerge() for details. */
  166081. /* 29 */ "SELECT 2 * total(1 + leaves_end_block - start_block) "
  166082. " FROM %Q.'%q_segdir' WHERE level = ? AND idx < ?",
  166083. /* SQL_DELETE_SEGDIR_ENTRY
  166084. ** Delete the %_segdir entry on absolute level :1 with index :2. */
  166085. /* 30 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
  166086. /* SQL_SHIFT_SEGDIR_ENTRY
  166087. ** Modify the idx value for the segment with idx=:3 on absolute level :2
  166088. ** to :1. */
  166089. /* 31 */ "UPDATE %Q.'%q_segdir' SET idx = ? WHERE level=? AND idx=?",
  166090. /* SQL_SELECT_SEGDIR
  166091. ** Read a single entry from the %_segdir table. The entry from absolute
  166092. ** level :1 with index value :2. */
  166093. /* 32 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
  166094. "FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
  166095. /* SQL_CHOMP_SEGDIR
  166096. ** Update the start_block (:1) and root (:2) fields of the %_segdir
  166097. ** entry located on absolute level :3 with index :4. */
  166098. /* 33 */ "UPDATE %Q.'%q_segdir' SET start_block = ?, root = ?"
  166099. "WHERE level = ? AND idx = ?",
  166100. /* SQL_SEGMENT_IS_APPENDABLE
  166101. ** Return a single row if the segment with end_block=? is appendable. Or
  166102. ** no rows otherwise. */
  166103. /* 34 */ "SELECT 1 FROM %Q.'%q_segments' WHERE blockid=? AND block IS NULL",
  166104. /* SQL_SELECT_INDEXES
  166105. ** Return the list of valid segment indexes for absolute level ? */
  166106. /* 35 */ "SELECT idx FROM %Q.'%q_segdir' WHERE level=? ORDER BY 1 ASC",
  166107. /* SQL_SELECT_MXLEVEL
  166108. ** Return the largest relative level in the FTS index or indexes. */
  166109. /* 36 */ "SELECT max( level %% 1024 ) FROM %Q.'%q_segdir'",
  166110. /* Return segments in order from oldest to newest.*/
  166111. /* 37 */ "SELECT level, idx, end_block "
  166112. "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ? "
  166113. "ORDER BY level DESC, idx ASC",
  166114. /* Update statements used while promoting segments */
  166115. /* 38 */ "UPDATE OR FAIL %Q.'%q_segdir' SET level=-1,idx=? "
  166116. "WHERE level=? AND idx=?",
  166117. /* 39 */ "UPDATE OR FAIL %Q.'%q_segdir' SET level=? WHERE level=-1"
  166118. };
  166119. int rc = SQLITE_OK;
  166120. sqlite3_stmt *pStmt;
  166121. assert( SizeofArray(azSql)==SizeofArray(p->aStmt) );
  166122. assert( eStmt<SizeofArray(azSql) && eStmt>=0 );
  166123. pStmt = p->aStmt[eStmt];
  166124. if( !pStmt ){
  166125. int f = SQLITE_PREPARE_PERSISTENT|SQLITE_PREPARE_NO_VTAB;
  166126. char *zSql;
  166127. if( eStmt==SQL_CONTENT_INSERT ){
  166128. zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName, p->zWriteExprlist);
  166129. }else if( eStmt==SQL_SELECT_CONTENT_BY_ROWID ){
  166130. f &= ~SQLITE_PREPARE_NO_VTAB;
  166131. zSql = sqlite3_mprintf(azSql[eStmt], p->zReadExprlist);
  166132. }else{
  166133. zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName);
  166134. }
  166135. if( !zSql ){
  166136. rc = SQLITE_NOMEM;
  166137. }else{
  166138. rc = sqlite3_prepare_v3(p->db, zSql, -1, f, &pStmt, NULL);
  166139. sqlite3_free(zSql);
  166140. assert( rc==SQLITE_OK || pStmt==0 );
  166141. p->aStmt[eStmt] = pStmt;
  166142. }
  166143. }
  166144. if( apVal ){
  166145. int i;
  166146. int nParam = sqlite3_bind_parameter_count(pStmt);
  166147. for(i=0; rc==SQLITE_OK && i<nParam; i++){
  166148. rc = sqlite3_bind_value(pStmt, i+1, apVal[i]);
  166149. }
  166150. }
  166151. *pp = pStmt;
  166152. return rc;
  166153. }
  166154. static int fts3SelectDocsize(
  166155. Fts3Table *pTab, /* FTS3 table handle */
  166156. sqlite3_int64 iDocid, /* Docid to bind for SQL_SELECT_DOCSIZE */
  166157. sqlite3_stmt **ppStmt /* OUT: Statement handle */
  166158. ){
  166159. sqlite3_stmt *pStmt = 0; /* Statement requested from fts3SqlStmt() */
  166160. int rc; /* Return code */
  166161. rc = fts3SqlStmt(pTab, SQL_SELECT_DOCSIZE, &pStmt, 0);
  166162. if( rc==SQLITE_OK ){
  166163. sqlite3_bind_int64(pStmt, 1, iDocid);
  166164. rc = sqlite3_step(pStmt);
  166165. if( rc!=SQLITE_ROW || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB ){
  166166. rc = sqlite3_reset(pStmt);
  166167. if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
  166168. pStmt = 0;
  166169. }else{
  166170. rc = SQLITE_OK;
  166171. }
  166172. }
  166173. *ppStmt = pStmt;
  166174. return rc;
  166175. }
  166176. SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(
  166177. Fts3Table *pTab, /* Fts3 table handle */
  166178. sqlite3_stmt **ppStmt /* OUT: Statement handle */
  166179. ){
  166180. sqlite3_stmt *pStmt = 0;
  166181. int rc;
  166182. rc = fts3SqlStmt(pTab, SQL_SELECT_STAT, &pStmt, 0);
  166183. if( rc==SQLITE_OK ){
  166184. sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
  166185. if( sqlite3_step(pStmt)!=SQLITE_ROW
  166186. || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB
  166187. ){
  166188. rc = sqlite3_reset(pStmt);
  166189. if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
  166190. pStmt = 0;
  166191. }
  166192. }
  166193. *ppStmt = pStmt;
  166194. return rc;
  166195. }
  166196. SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(
  166197. Fts3Table *pTab, /* Fts3 table handle */
  166198. sqlite3_int64 iDocid, /* Docid to read size data for */
  166199. sqlite3_stmt **ppStmt /* OUT: Statement handle */
  166200. ){
  166201. return fts3SelectDocsize(pTab, iDocid, ppStmt);
  166202. }
  166203. /*
  166204. ** Similar to fts3SqlStmt(). Except, after binding the parameters in
  166205. ** array apVal[] to the SQL statement identified by eStmt, the statement
  166206. ** is executed.
  166207. **
  166208. ** Returns SQLITE_OK if the statement is successfully executed, or an
  166209. ** SQLite error code otherwise.
  166210. */
  166211. static void fts3SqlExec(
  166212. int *pRC, /* Result code */
  166213. Fts3Table *p, /* The FTS3 table */
  166214. int eStmt, /* Index of statement to evaluate */
  166215. sqlite3_value **apVal /* Parameters to bind */
  166216. ){
  166217. sqlite3_stmt *pStmt;
  166218. int rc;
  166219. if( *pRC ) return;
  166220. rc = fts3SqlStmt(p, eStmt, &pStmt, apVal);
  166221. if( rc==SQLITE_OK ){
  166222. sqlite3_step(pStmt);
  166223. rc = sqlite3_reset(pStmt);
  166224. }
  166225. *pRC = rc;
  166226. }
  166227. /*
  166228. ** This function ensures that the caller has obtained an exclusive
  166229. ** shared-cache table-lock on the %_segdir table. This is required before
  166230. ** writing data to the fts3 table. If this lock is not acquired first, then
  166231. ** the caller may end up attempting to take this lock as part of committing
  166232. ** a transaction, causing SQLite to return SQLITE_LOCKED or
  166233. ** LOCKED_SHAREDCACHEto a COMMIT command.
  166234. **
  166235. ** It is best to avoid this because if FTS3 returns any error when
  166236. ** committing a transaction, the whole transaction will be rolled back.
  166237. ** And this is not what users expect when they get SQLITE_LOCKED_SHAREDCACHE.
  166238. ** It can still happen if the user locks the underlying tables directly
  166239. ** instead of accessing them via FTS.
  166240. */
  166241. static int fts3Writelock(Fts3Table *p){
  166242. int rc = SQLITE_OK;
  166243. if( p->nPendingData==0 ){
  166244. sqlite3_stmt *pStmt;
  166245. rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pStmt, 0);
  166246. if( rc==SQLITE_OK ){
  166247. sqlite3_bind_null(pStmt, 1);
  166248. sqlite3_step(pStmt);
  166249. rc = sqlite3_reset(pStmt);
  166250. }
  166251. }
  166252. return rc;
  166253. }
  166254. /*
  166255. ** FTS maintains a separate indexes for each language-id (a 32-bit integer).
  166256. ** Within each language id, a separate index is maintained to store the
  166257. ** document terms, and each configured prefix size (configured the FTS
  166258. ** "prefix=" option). And each index consists of multiple levels ("relative
  166259. ** levels").
  166260. **
  166261. ** All three of these values (the language id, the specific index and the
  166262. ** level within the index) are encoded in 64-bit integer values stored
  166263. ** in the %_segdir table on disk. This function is used to convert three
  166264. ** separate component values into the single 64-bit integer value that
  166265. ** can be used to query the %_segdir table.
  166266. **
  166267. ** Specifically, each language-id/index combination is allocated 1024
  166268. ** 64-bit integer level values ("absolute levels"). The main terms index
  166269. ** for language-id 0 is allocate values 0-1023. The first prefix index
  166270. ** (if any) for language-id 0 is allocated values 1024-2047. And so on.
  166271. ** Language 1 indexes are allocated immediately following language 0.
  166272. **
  166273. ** So, for a system with nPrefix prefix indexes configured, the block of
  166274. ** absolute levels that corresponds to language-id iLangid and index
  166275. ** iIndex starts at absolute level ((iLangid * (nPrefix+1) + iIndex) * 1024).
  166276. */
  166277. static sqlite3_int64 getAbsoluteLevel(
  166278. Fts3Table *p, /* FTS3 table handle */
  166279. int iLangid, /* Language id */
  166280. int iIndex, /* Index in p->aIndex[] */
  166281. int iLevel /* Level of segments */
  166282. ){
  166283. sqlite3_int64 iBase; /* First absolute level for iLangid/iIndex */
  166284. assert_fts3_nc( iLangid>=0 );
  166285. assert( p->nIndex>0 );
  166286. assert( iIndex>=0 && iIndex<p->nIndex );
  166287. iBase = ((sqlite3_int64)iLangid * p->nIndex + iIndex) * FTS3_SEGDIR_MAXLEVEL;
  166288. return iBase + iLevel;
  166289. }
  166290. /*
  166291. ** Set *ppStmt to a statement handle that may be used to iterate through
  166292. ** all rows in the %_segdir table, from oldest to newest. If successful,
  166293. ** return SQLITE_OK. If an error occurs while preparing the statement,
  166294. ** return an SQLite error code.
  166295. **
  166296. ** There is only ever one instance of this SQL statement compiled for
  166297. ** each FTS3 table.
  166298. **
  166299. ** The statement returns the following columns from the %_segdir table:
  166300. **
  166301. ** 0: idx
  166302. ** 1: start_block
  166303. ** 2: leaves_end_block
  166304. ** 3: end_block
  166305. ** 4: root
  166306. */
  166307. SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(
  166308. Fts3Table *p, /* FTS3 table */
  166309. int iLangid, /* Language being queried */
  166310. int iIndex, /* Index for p->aIndex[] */
  166311. int iLevel, /* Level to select (relative level) */
  166312. sqlite3_stmt **ppStmt /* OUT: Compiled statement */
  166313. ){
  166314. int rc;
  166315. sqlite3_stmt *pStmt = 0;
  166316. assert( iLevel==FTS3_SEGCURSOR_ALL || iLevel>=0 );
  166317. assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
  166318. assert( iIndex>=0 && iIndex<p->nIndex );
  166319. if( iLevel<0 ){
  166320. /* "SELECT * FROM %_segdir WHERE level BETWEEN ? AND ? ORDER BY ..." */
  166321. rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE, &pStmt, 0);
  166322. if( rc==SQLITE_OK ){
  166323. sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
  166324. sqlite3_bind_int64(pStmt, 2,
  166325. getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
  166326. );
  166327. }
  166328. }else{
  166329. /* "SELECT * FROM %_segdir WHERE level = ? ORDER BY ..." */
  166330. rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
  166331. if( rc==SQLITE_OK ){
  166332. sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex,iLevel));
  166333. }
  166334. }
  166335. *ppStmt = pStmt;
  166336. return rc;
  166337. }
  166338. /*
  166339. ** Append a single varint to a PendingList buffer. SQLITE_OK is returned
  166340. ** if successful, or an SQLite error code otherwise.
  166341. **
  166342. ** This function also serves to allocate the PendingList structure itself.
  166343. ** For example, to create a new PendingList structure containing two
  166344. ** varints:
  166345. **
  166346. ** PendingList *p = 0;
  166347. ** fts3PendingListAppendVarint(&p, 1);
  166348. ** fts3PendingListAppendVarint(&p, 2);
  166349. */
  166350. static int fts3PendingListAppendVarint(
  166351. PendingList **pp, /* IN/OUT: Pointer to PendingList struct */
  166352. sqlite3_int64 i /* Value to append to data */
  166353. ){
  166354. PendingList *p = *pp;
  166355. /* Allocate or grow the PendingList as required. */
  166356. if( !p ){
  166357. p = sqlite3_malloc(sizeof(*p) + 100);
  166358. if( !p ){
  166359. return SQLITE_NOMEM;
  166360. }
  166361. p->nSpace = 100;
  166362. p->aData = (char *)&p[1];
  166363. p->nData = 0;
  166364. }
  166365. else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){
  166366. int nNew = p->nSpace * 2;
  166367. p = sqlite3_realloc(p, sizeof(*p) + nNew);
  166368. if( !p ){
  166369. sqlite3_free(*pp);
  166370. *pp = 0;
  166371. return SQLITE_NOMEM;
  166372. }
  166373. p->nSpace = nNew;
  166374. p->aData = (char *)&p[1];
  166375. }
  166376. /* Append the new serialized varint to the end of the list. */
  166377. p->nData += sqlite3Fts3PutVarint(&p->aData[p->nData], i);
  166378. p->aData[p->nData] = '\0';
  166379. *pp = p;
  166380. return SQLITE_OK;
  166381. }
  166382. /*
  166383. ** Add a docid/column/position entry to a PendingList structure. Non-zero
  166384. ** is returned if the structure is sqlite3_realloced as part of adding
  166385. ** the entry. Otherwise, zero.
  166386. **
  166387. ** If an OOM error occurs, *pRc is set to SQLITE_NOMEM before returning.
  166388. ** Zero is always returned in this case. Otherwise, if no OOM error occurs,
  166389. ** it is set to SQLITE_OK.
  166390. */
  166391. static int fts3PendingListAppend(
  166392. PendingList **pp, /* IN/OUT: PendingList structure */
  166393. sqlite3_int64 iDocid, /* Docid for entry to add */
  166394. sqlite3_int64 iCol, /* Column for entry to add */
  166395. sqlite3_int64 iPos, /* Position of term for entry to add */
  166396. int *pRc /* OUT: Return code */
  166397. ){
  166398. PendingList *p = *pp;
  166399. int rc = SQLITE_OK;
  166400. assert( !p || p->iLastDocid<=iDocid );
  166401. if( !p || p->iLastDocid!=iDocid ){
  166402. u64 iDelta = (u64)iDocid - (u64)(p ? p->iLastDocid : 0);
  166403. if( p ){
  166404. assert( p->nData<p->nSpace );
  166405. assert( p->aData[p->nData]==0 );
  166406. p->nData++;
  166407. }
  166408. if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iDelta)) ){
  166409. goto pendinglistappend_out;
  166410. }
  166411. p->iLastCol = -1;
  166412. p->iLastPos = 0;
  166413. p->iLastDocid = iDocid;
  166414. }
  166415. if( iCol>0 && p->iLastCol!=iCol ){
  166416. if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, 1))
  166417. || SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iCol))
  166418. ){
  166419. goto pendinglistappend_out;
  166420. }
  166421. p->iLastCol = iCol;
  166422. p->iLastPos = 0;
  166423. }
  166424. if( iCol>=0 ){
  166425. assert( iPos>p->iLastPos || (iPos==0 && p->iLastPos==0) );
  166426. rc = fts3PendingListAppendVarint(&p, 2+iPos-p->iLastPos);
  166427. if( rc==SQLITE_OK ){
  166428. p->iLastPos = iPos;
  166429. }
  166430. }
  166431. pendinglistappend_out:
  166432. *pRc = rc;
  166433. if( p!=*pp ){
  166434. *pp = p;
  166435. return 1;
  166436. }
  166437. return 0;
  166438. }
  166439. /*
  166440. ** Free a PendingList object allocated by fts3PendingListAppend().
  166441. */
  166442. static void fts3PendingListDelete(PendingList *pList){
  166443. sqlite3_free(pList);
  166444. }
  166445. /*
  166446. ** Add an entry to one of the pending-terms hash tables.
  166447. */
  166448. static int fts3PendingTermsAddOne(
  166449. Fts3Table *p,
  166450. int iCol,
  166451. int iPos,
  166452. Fts3Hash *pHash, /* Pending terms hash table to add entry to */
  166453. const char *zToken,
  166454. int nToken
  166455. ){
  166456. PendingList *pList;
  166457. int rc = SQLITE_OK;
  166458. pList = (PendingList *)fts3HashFind(pHash, zToken, nToken);
  166459. if( pList ){
  166460. p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem));
  166461. }
  166462. if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){
  166463. if( pList==fts3HashInsert(pHash, zToken, nToken, pList) ){
  166464. /* Malloc failed while inserting the new entry. This can only
  166465. ** happen if there was no previous entry for this token.
  166466. */
  166467. assert( 0==fts3HashFind(pHash, zToken, nToken) );
  166468. sqlite3_free(pList);
  166469. rc = SQLITE_NOMEM;
  166470. }
  166471. }
  166472. if( rc==SQLITE_OK ){
  166473. p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem));
  166474. }
  166475. return rc;
  166476. }
  166477. /*
  166478. ** Tokenize the nul-terminated string zText and add all tokens to the
  166479. ** pending-terms hash-table. The docid used is that currently stored in
  166480. ** p->iPrevDocid, and the column is specified by argument iCol.
  166481. **
  166482. ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
  166483. */
  166484. static int fts3PendingTermsAdd(
  166485. Fts3Table *p, /* Table into which text will be inserted */
  166486. int iLangid, /* Language id to use */
  166487. const char *zText, /* Text of document to be inserted */
  166488. int iCol, /* Column into which text is being inserted */
  166489. u32 *pnWord /* IN/OUT: Incr. by number tokens inserted */
  166490. ){
  166491. int rc;
  166492. int iStart = 0;
  166493. int iEnd = 0;
  166494. int iPos = 0;
  166495. int nWord = 0;
  166496. char const *zToken;
  166497. int nToken = 0;
  166498. sqlite3_tokenizer *pTokenizer = p->pTokenizer;
  166499. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  166500. sqlite3_tokenizer_cursor *pCsr;
  166501. int (*xNext)(sqlite3_tokenizer_cursor *pCursor,
  166502. const char**,int*,int*,int*,int*);
  166503. assert( pTokenizer && pModule );
  166504. /* If the user has inserted a NULL value, this function may be called with
  166505. ** zText==0. In this case, add zero token entries to the hash table and
  166506. ** return early. */
  166507. if( zText==0 ){
  166508. *pnWord = 0;
  166509. return SQLITE_OK;
  166510. }
  166511. rc = sqlite3Fts3OpenTokenizer(pTokenizer, iLangid, zText, -1, &pCsr);
  166512. if( rc!=SQLITE_OK ){
  166513. return rc;
  166514. }
  166515. xNext = pModule->xNext;
  166516. while( SQLITE_OK==rc
  166517. && SQLITE_OK==(rc = xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos))
  166518. ){
  166519. int i;
  166520. if( iPos>=nWord ) nWord = iPos+1;
  166521. /* Positions cannot be negative; we use -1 as a terminator internally.
  166522. ** Tokens must have a non-zero length.
  166523. */
  166524. if( iPos<0 || !zToken || nToken<=0 ){
  166525. rc = SQLITE_ERROR;
  166526. break;
  166527. }
  166528. /* Add the term to the terms index */
  166529. rc = fts3PendingTermsAddOne(
  166530. p, iCol, iPos, &p->aIndex[0].hPending, zToken, nToken
  166531. );
  166532. /* Add the term to each of the prefix indexes that it is not too
  166533. ** short for. */
  166534. for(i=1; rc==SQLITE_OK && i<p->nIndex; i++){
  166535. struct Fts3Index *pIndex = &p->aIndex[i];
  166536. if( nToken<pIndex->nPrefix ) continue;
  166537. rc = fts3PendingTermsAddOne(
  166538. p, iCol, iPos, &pIndex->hPending, zToken, pIndex->nPrefix
  166539. );
  166540. }
  166541. }
  166542. pModule->xClose(pCsr);
  166543. *pnWord += nWord;
  166544. return (rc==SQLITE_DONE ? SQLITE_OK : rc);
  166545. }
  166546. /*
  166547. ** Calling this function indicates that subsequent calls to
  166548. ** fts3PendingTermsAdd() are to add term/position-list pairs for the
  166549. ** contents of the document with docid iDocid.
  166550. */
  166551. static int fts3PendingTermsDocid(
  166552. Fts3Table *p, /* Full-text table handle */
  166553. int bDelete, /* True if this op is a delete */
  166554. int iLangid, /* Language id of row being written */
  166555. sqlite_int64 iDocid /* Docid of row being written */
  166556. ){
  166557. assert( iLangid>=0 );
  166558. assert( bDelete==1 || bDelete==0 );
  166559. /* TODO(shess) Explore whether partially flushing the buffer on
  166560. ** forced-flush would provide better performance. I suspect that if
  166561. ** we ordered the doclists by size and flushed the largest until the
  166562. ** buffer was half empty, that would let the less frequent terms
  166563. ** generate longer doclists.
  166564. */
  166565. if( iDocid<p->iPrevDocid
  166566. || (iDocid==p->iPrevDocid && p->bPrevDelete==0)
  166567. || p->iPrevLangid!=iLangid
  166568. || p->nPendingData>p->nMaxPendingData
  166569. ){
  166570. int rc = sqlite3Fts3PendingTermsFlush(p);
  166571. if( rc!=SQLITE_OK ) return rc;
  166572. }
  166573. p->iPrevDocid = iDocid;
  166574. p->iPrevLangid = iLangid;
  166575. p->bPrevDelete = bDelete;
  166576. return SQLITE_OK;
  166577. }
  166578. /*
  166579. ** Discard the contents of the pending-terms hash tables.
  166580. */
  166581. SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *p){
  166582. int i;
  166583. for(i=0; i<p->nIndex; i++){
  166584. Fts3HashElem *pElem;
  166585. Fts3Hash *pHash = &p->aIndex[i].hPending;
  166586. for(pElem=fts3HashFirst(pHash); pElem; pElem=fts3HashNext(pElem)){
  166587. PendingList *pList = (PendingList *)fts3HashData(pElem);
  166588. fts3PendingListDelete(pList);
  166589. }
  166590. fts3HashClear(pHash);
  166591. }
  166592. p->nPendingData = 0;
  166593. }
  166594. /*
  166595. ** This function is called by the xUpdate() method as part of an INSERT
  166596. ** operation. It adds entries for each term in the new record to the
  166597. ** pendingTerms hash table.
  166598. **
  166599. ** Argument apVal is the same as the similarly named argument passed to
  166600. ** fts3InsertData(). Parameter iDocid is the docid of the new row.
  166601. */
  166602. static int fts3InsertTerms(
  166603. Fts3Table *p,
  166604. int iLangid,
  166605. sqlite3_value **apVal,
  166606. u32 *aSz
  166607. ){
  166608. int i; /* Iterator variable */
  166609. for(i=2; i<p->nColumn+2; i++){
  166610. int iCol = i-2;
  166611. if( p->abNotindexed[iCol]==0 ){
  166612. const char *zText = (const char *)sqlite3_value_text(apVal[i]);
  166613. int rc = fts3PendingTermsAdd(p, iLangid, zText, iCol, &aSz[iCol]);
  166614. if( rc!=SQLITE_OK ){
  166615. return rc;
  166616. }
  166617. aSz[p->nColumn] += sqlite3_value_bytes(apVal[i]);
  166618. }
  166619. }
  166620. return SQLITE_OK;
  166621. }
  166622. /*
  166623. ** This function is called by the xUpdate() method for an INSERT operation.
  166624. ** The apVal parameter is passed a copy of the apVal argument passed by
  166625. ** SQLite to the xUpdate() method. i.e:
  166626. **
  166627. ** apVal[0] Not used for INSERT.
  166628. ** apVal[1] rowid
  166629. ** apVal[2] Left-most user-defined column
  166630. ** ...
  166631. ** apVal[p->nColumn+1] Right-most user-defined column
  166632. ** apVal[p->nColumn+2] Hidden column with same name as table
  166633. ** apVal[p->nColumn+3] Hidden "docid" column (alias for rowid)
  166634. ** apVal[p->nColumn+4] Hidden languageid column
  166635. */
  166636. static int fts3InsertData(
  166637. Fts3Table *p, /* Full-text table */
  166638. sqlite3_value **apVal, /* Array of values to insert */
  166639. sqlite3_int64 *piDocid /* OUT: Docid for row just inserted */
  166640. ){
  166641. int rc; /* Return code */
  166642. sqlite3_stmt *pContentInsert; /* INSERT INTO %_content VALUES(...) */
  166643. if( p->zContentTbl ){
  166644. sqlite3_value *pRowid = apVal[p->nColumn+3];
  166645. if( sqlite3_value_type(pRowid)==SQLITE_NULL ){
  166646. pRowid = apVal[1];
  166647. }
  166648. if( sqlite3_value_type(pRowid)!=SQLITE_INTEGER ){
  166649. return SQLITE_CONSTRAINT;
  166650. }
  166651. *piDocid = sqlite3_value_int64(pRowid);
  166652. return SQLITE_OK;
  166653. }
  166654. /* Locate the statement handle used to insert data into the %_content
  166655. ** table. The SQL for this statement is:
  166656. **
  166657. ** INSERT INTO %_content VALUES(?, ?, ?, ...)
  166658. **
  166659. ** The statement features N '?' variables, where N is the number of user
  166660. ** defined columns in the FTS3 table, plus one for the docid field.
  166661. */
  166662. rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]);
  166663. if( rc==SQLITE_OK && p->zLanguageid ){
  166664. rc = sqlite3_bind_int(
  166665. pContentInsert, p->nColumn+2,
  166666. sqlite3_value_int(apVal[p->nColumn+4])
  166667. );
  166668. }
  166669. if( rc!=SQLITE_OK ) return rc;
  166670. /* There is a quirk here. The users INSERT statement may have specified
  166671. ** a value for the "rowid" field, for the "docid" field, or for both.
  166672. ** Which is a problem, since "rowid" and "docid" are aliases for the
  166673. ** same value. For example:
  166674. **
  166675. ** INSERT INTO fts3tbl(rowid, docid) VALUES(1, 2);
  166676. **
  166677. ** In FTS3, this is an error. It is an error to specify non-NULL values
  166678. ** for both docid and some other rowid alias.
  166679. */
  166680. if( SQLITE_NULL!=sqlite3_value_type(apVal[3+p->nColumn]) ){
  166681. if( SQLITE_NULL==sqlite3_value_type(apVal[0])
  166682. && SQLITE_NULL!=sqlite3_value_type(apVal[1])
  166683. ){
  166684. /* A rowid/docid conflict. */
  166685. return SQLITE_ERROR;
  166686. }
  166687. rc = sqlite3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]);
  166688. if( rc!=SQLITE_OK ) return rc;
  166689. }
  166690. /* Execute the statement to insert the record. Set *piDocid to the
  166691. ** new docid value.
  166692. */
  166693. sqlite3_step(pContentInsert);
  166694. rc = sqlite3_reset(pContentInsert);
  166695. *piDocid = sqlite3_last_insert_rowid(p->db);
  166696. return rc;
  166697. }
  166698. /*
  166699. ** Remove all data from the FTS3 table. Clear the hash table containing
  166700. ** pending terms.
  166701. */
  166702. static int fts3DeleteAll(Fts3Table *p, int bContent){
  166703. int rc = SQLITE_OK; /* Return code */
  166704. /* Discard the contents of the pending-terms hash table. */
  166705. sqlite3Fts3PendingTermsClear(p);
  166706. /* Delete everything from the shadow tables. Except, leave %_content as
  166707. ** is if bContent is false. */
  166708. assert( p->zContentTbl==0 || bContent==0 );
  166709. if( bContent ) fts3SqlExec(&rc, p, SQL_DELETE_ALL_CONTENT, 0);
  166710. fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGMENTS, 0);
  166711. fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
  166712. if( p->bHasDocsize ){
  166713. fts3SqlExec(&rc, p, SQL_DELETE_ALL_DOCSIZE, 0);
  166714. }
  166715. if( p->bHasStat ){
  166716. fts3SqlExec(&rc, p, SQL_DELETE_ALL_STAT, 0);
  166717. }
  166718. return rc;
  166719. }
  166720. /*
  166721. **
  166722. */
  166723. static int langidFromSelect(Fts3Table *p, sqlite3_stmt *pSelect){
  166724. int iLangid = 0;
  166725. if( p->zLanguageid ) iLangid = sqlite3_column_int(pSelect, p->nColumn+1);
  166726. return iLangid;
  166727. }
  166728. /*
  166729. ** The first element in the apVal[] array is assumed to contain the docid
  166730. ** (an integer) of a row about to be deleted. Remove all terms from the
  166731. ** full-text index.
  166732. */
  166733. static void fts3DeleteTerms(
  166734. int *pRC, /* Result code */
  166735. Fts3Table *p, /* The FTS table to delete from */
  166736. sqlite3_value *pRowid, /* The docid to be deleted */
  166737. u32 *aSz, /* Sizes of deleted document written here */
  166738. int *pbFound /* OUT: Set to true if row really does exist */
  166739. ){
  166740. int rc;
  166741. sqlite3_stmt *pSelect;
  166742. assert( *pbFound==0 );
  166743. if( *pRC ) return;
  166744. rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pSelect, &pRowid);
  166745. if( rc==SQLITE_OK ){
  166746. if( SQLITE_ROW==sqlite3_step(pSelect) ){
  166747. int i;
  166748. int iLangid = langidFromSelect(p, pSelect);
  166749. i64 iDocid = sqlite3_column_int64(pSelect, 0);
  166750. rc = fts3PendingTermsDocid(p, 1, iLangid, iDocid);
  166751. for(i=1; rc==SQLITE_OK && i<=p->nColumn; i++){
  166752. int iCol = i-1;
  166753. if( p->abNotindexed[iCol]==0 ){
  166754. const char *zText = (const char *)sqlite3_column_text(pSelect, i);
  166755. rc = fts3PendingTermsAdd(p, iLangid, zText, -1, &aSz[iCol]);
  166756. aSz[p->nColumn] += sqlite3_column_bytes(pSelect, i);
  166757. }
  166758. }
  166759. if( rc!=SQLITE_OK ){
  166760. sqlite3_reset(pSelect);
  166761. *pRC = rc;
  166762. return;
  166763. }
  166764. *pbFound = 1;
  166765. }
  166766. rc = sqlite3_reset(pSelect);
  166767. }else{
  166768. sqlite3_reset(pSelect);
  166769. }
  166770. *pRC = rc;
  166771. }
  166772. /*
  166773. ** Forward declaration to account for the circular dependency between
  166774. ** functions fts3SegmentMerge() and fts3AllocateSegdirIdx().
  166775. */
  166776. static int fts3SegmentMerge(Fts3Table *, int, int, int);
  166777. /*
  166778. ** This function allocates a new level iLevel index in the segdir table.
  166779. ** Usually, indexes are allocated within a level sequentially starting
  166780. ** with 0, so the allocated index is one greater than the value returned
  166781. ** by:
  166782. **
  166783. ** SELECT max(idx) FROM %_segdir WHERE level = :iLevel
  166784. **
  166785. ** However, if there are already FTS3_MERGE_COUNT indexes at the requested
  166786. ** level, they are merged into a single level (iLevel+1) segment and the
  166787. ** allocated index is 0.
  166788. **
  166789. ** If successful, *piIdx is set to the allocated index slot and SQLITE_OK
  166790. ** returned. Otherwise, an SQLite error code is returned.
  166791. */
  166792. static int fts3AllocateSegdirIdx(
  166793. Fts3Table *p,
  166794. int iLangid, /* Language id */
  166795. int iIndex, /* Index for p->aIndex */
  166796. int iLevel,
  166797. int *piIdx
  166798. ){
  166799. int rc; /* Return Code */
  166800. sqlite3_stmt *pNextIdx; /* Query for next idx at level iLevel */
  166801. int iNext = 0; /* Result of query pNextIdx */
  166802. assert( iLangid>=0 );
  166803. assert( p->nIndex>=1 );
  166804. /* Set variable iNext to the next available segdir index at level iLevel. */
  166805. rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0);
  166806. if( rc==SQLITE_OK ){
  166807. sqlite3_bind_int64(
  166808. pNextIdx, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
  166809. );
  166810. if( SQLITE_ROW==sqlite3_step(pNextIdx) ){
  166811. iNext = sqlite3_column_int(pNextIdx, 0);
  166812. }
  166813. rc = sqlite3_reset(pNextIdx);
  166814. }
  166815. if( rc==SQLITE_OK ){
  166816. /* If iNext is FTS3_MERGE_COUNT, indicating that level iLevel is already
  166817. ** full, merge all segments in level iLevel into a single iLevel+1
  166818. ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise,
  166819. ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext.
  166820. */
  166821. if( iNext>=MergeCount(p) ){
  166822. fts3LogMerge(16, getAbsoluteLevel(p, iLangid, iIndex, iLevel));
  166823. rc = fts3SegmentMerge(p, iLangid, iIndex, iLevel);
  166824. *piIdx = 0;
  166825. }else{
  166826. *piIdx = iNext;
  166827. }
  166828. }
  166829. return rc;
  166830. }
  166831. /*
  166832. ** The %_segments table is declared as follows:
  166833. **
  166834. ** CREATE TABLE %_segments(blockid INTEGER PRIMARY KEY, block BLOB)
  166835. **
  166836. ** This function reads data from a single row of the %_segments table. The
  166837. ** specific row is identified by the iBlockid parameter. If paBlob is not
  166838. ** NULL, then a buffer is allocated using sqlite3_malloc() and populated
  166839. ** with the contents of the blob stored in the "block" column of the
  166840. ** identified table row is. Whether or not paBlob is NULL, *pnBlob is set
  166841. ** to the size of the blob in bytes before returning.
  166842. **
  166843. ** If an error occurs, or the table does not contain the specified row,
  166844. ** an SQLite error code is returned. Otherwise, SQLITE_OK is returned. If
  166845. ** paBlob is non-NULL, then it is the responsibility of the caller to
  166846. ** eventually free the returned buffer.
  166847. **
  166848. ** This function may leave an open sqlite3_blob* handle in the
  166849. ** Fts3Table.pSegments variable. This handle is reused by subsequent calls
  166850. ** to this function. The handle may be closed by calling the
  166851. ** sqlite3Fts3SegmentsClose() function. Reusing a blob handle is a handy
  166852. ** performance improvement, but the blob handle should always be closed
  166853. ** before control is returned to the user (to prevent a lock being held
  166854. ** on the database file for longer than necessary). Thus, any virtual table
  166855. ** method (xFilter etc.) that may directly or indirectly call this function
  166856. ** must call sqlite3Fts3SegmentsClose() before returning.
  166857. */
  166858. SQLITE_PRIVATE int sqlite3Fts3ReadBlock(
  166859. Fts3Table *p, /* FTS3 table handle */
  166860. sqlite3_int64 iBlockid, /* Access the row with blockid=$iBlockid */
  166861. char **paBlob, /* OUT: Blob data in malloc'd buffer */
  166862. int *pnBlob, /* OUT: Size of blob data */
  166863. int *pnLoad /* OUT: Bytes actually loaded */
  166864. ){
  166865. int rc; /* Return code */
  166866. /* pnBlob must be non-NULL. paBlob may be NULL or non-NULL. */
  166867. assert( pnBlob );
  166868. if( p->pSegments ){
  166869. rc = sqlite3_blob_reopen(p->pSegments, iBlockid);
  166870. }else{
  166871. if( 0==p->zSegmentsTbl ){
  166872. p->zSegmentsTbl = sqlite3_mprintf("%s_segments", p->zName);
  166873. if( 0==p->zSegmentsTbl ) return SQLITE_NOMEM;
  166874. }
  166875. rc = sqlite3_blob_open(
  166876. p->db, p->zDb, p->zSegmentsTbl, "block", iBlockid, 0, &p->pSegments
  166877. );
  166878. }
  166879. if( rc==SQLITE_OK ){
  166880. int nByte = sqlite3_blob_bytes(p->pSegments);
  166881. *pnBlob = nByte;
  166882. if( paBlob ){
  166883. char *aByte = sqlite3_malloc(nByte + FTS3_NODE_PADDING);
  166884. if( !aByte ){
  166885. rc = SQLITE_NOMEM;
  166886. }else{
  166887. if( pnLoad && nByte>(FTS3_NODE_CHUNK_THRESHOLD) ){
  166888. nByte = FTS3_NODE_CHUNKSIZE;
  166889. *pnLoad = nByte;
  166890. }
  166891. rc = sqlite3_blob_read(p->pSegments, aByte, nByte, 0);
  166892. memset(&aByte[nByte], 0, FTS3_NODE_PADDING);
  166893. if( rc!=SQLITE_OK ){
  166894. sqlite3_free(aByte);
  166895. aByte = 0;
  166896. }
  166897. }
  166898. *paBlob = aByte;
  166899. }
  166900. }else if( rc==SQLITE_ERROR ){
  166901. rc = FTS_CORRUPT_VTAB;
  166902. }
  166903. return rc;
  166904. }
  166905. /*
  166906. ** Close the blob handle at p->pSegments, if it is open. See comments above
  166907. ** the sqlite3Fts3ReadBlock() function for details.
  166908. */
  166909. SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *p){
  166910. sqlite3_blob_close(p->pSegments);
  166911. p->pSegments = 0;
  166912. }
  166913. static int fts3SegReaderIncrRead(Fts3SegReader *pReader){
  166914. int nRead; /* Number of bytes to read */
  166915. int rc; /* Return code */
  166916. nRead = MIN(pReader->nNode - pReader->nPopulate, FTS3_NODE_CHUNKSIZE);
  166917. rc = sqlite3_blob_read(
  166918. pReader->pBlob,
  166919. &pReader->aNode[pReader->nPopulate],
  166920. nRead,
  166921. pReader->nPopulate
  166922. );
  166923. if( rc==SQLITE_OK ){
  166924. pReader->nPopulate += nRead;
  166925. memset(&pReader->aNode[pReader->nPopulate], 0, FTS3_NODE_PADDING);
  166926. if( pReader->nPopulate==pReader->nNode ){
  166927. sqlite3_blob_close(pReader->pBlob);
  166928. pReader->pBlob = 0;
  166929. pReader->nPopulate = 0;
  166930. }
  166931. }
  166932. return rc;
  166933. }
  166934. static int fts3SegReaderRequire(Fts3SegReader *pReader, char *pFrom, int nByte){
  166935. int rc = SQLITE_OK;
  166936. assert( !pReader->pBlob
  166937. || (pFrom>=pReader->aNode && pFrom<&pReader->aNode[pReader->nNode])
  166938. );
  166939. while( pReader->pBlob && rc==SQLITE_OK
  166940. && (pFrom - pReader->aNode + nByte)>pReader->nPopulate
  166941. ){
  166942. rc = fts3SegReaderIncrRead(pReader);
  166943. }
  166944. return rc;
  166945. }
  166946. /*
  166947. ** Set an Fts3SegReader cursor to point at EOF.
  166948. */
  166949. static void fts3SegReaderSetEof(Fts3SegReader *pSeg){
  166950. if( !fts3SegReaderIsRootOnly(pSeg) ){
  166951. sqlite3_free(pSeg->aNode);
  166952. sqlite3_blob_close(pSeg->pBlob);
  166953. pSeg->pBlob = 0;
  166954. }
  166955. pSeg->aNode = 0;
  166956. }
  166957. /*
  166958. ** Move the iterator passed as the first argument to the next term in the
  166959. ** segment. If successful, SQLITE_OK is returned. If there is no next term,
  166960. ** SQLITE_DONE. Otherwise, an SQLite error code.
  166961. */
  166962. static int fts3SegReaderNext(
  166963. Fts3Table *p,
  166964. Fts3SegReader *pReader,
  166965. int bIncr
  166966. ){
  166967. int rc; /* Return code of various sub-routines */
  166968. char *pNext; /* Cursor variable */
  166969. int nPrefix; /* Number of bytes in term prefix */
  166970. int nSuffix; /* Number of bytes in term suffix */
  166971. if( !pReader->aDoclist ){
  166972. pNext = pReader->aNode;
  166973. }else{
  166974. pNext = &pReader->aDoclist[pReader->nDoclist];
  166975. }
  166976. if( !pNext || pNext>=&pReader->aNode[pReader->nNode] ){
  166977. if( fts3SegReaderIsPending(pReader) ){
  166978. Fts3HashElem *pElem = *(pReader->ppNextElem);
  166979. sqlite3_free(pReader->aNode);
  166980. pReader->aNode = 0;
  166981. if( pElem ){
  166982. char *aCopy;
  166983. PendingList *pList = (PendingList *)fts3HashData(pElem);
  166984. int nCopy = pList->nData+1;
  166985. pReader->zTerm = (char *)fts3HashKey(pElem);
  166986. pReader->nTerm = fts3HashKeysize(pElem);
  166987. aCopy = (char*)sqlite3_malloc(nCopy);
  166988. if( !aCopy ) return SQLITE_NOMEM;
  166989. memcpy(aCopy, pList->aData, nCopy);
  166990. pReader->nNode = pReader->nDoclist = nCopy;
  166991. pReader->aNode = pReader->aDoclist = aCopy;
  166992. pReader->ppNextElem++;
  166993. assert( pReader->aNode );
  166994. }
  166995. return SQLITE_OK;
  166996. }
  166997. fts3SegReaderSetEof(pReader);
  166998. /* If iCurrentBlock>=iLeafEndBlock, this is an EOF condition. All leaf
  166999. ** blocks have already been traversed. */
  167000. #ifdef CORRUPT_DB
  167001. assert( pReader->iCurrentBlock<=pReader->iLeafEndBlock || CORRUPT_DB );
  167002. #endif
  167003. if( pReader->iCurrentBlock>=pReader->iLeafEndBlock ){
  167004. return SQLITE_OK;
  167005. }
  167006. rc = sqlite3Fts3ReadBlock(
  167007. p, ++pReader->iCurrentBlock, &pReader->aNode, &pReader->nNode,
  167008. (bIncr ? &pReader->nPopulate : 0)
  167009. );
  167010. if( rc!=SQLITE_OK ) return rc;
  167011. assert( pReader->pBlob==0 );
  167012. if( bIncr && pReader->nPopulate<pReader->nNode ){
  167013. pReader->pBlob = p->pSegments;
  167014. p->pSegments = 0;
  167015. }
  167016. pNext = pReader->aNode;
  167017. }
  167018. assert( !fts3SegReaderIsPending(pReader) );
  167019. rc = fts3SegReaderRequire(pReader, pNext, FTS3_VARINT_MAX*2);
  167020. if( rc!=SQLITE_OK ) return rc;
  167021. /* Because of the FTS3_NODE_PADDING bytes of padding, the following is
  167022. ** safe (no risk of overread) even if the node data is corrupted. */
  167023. pNext += fts3GetVarint32(pNext, &nPrefix);
  167024. pNext += fts3GetVarint32(pNext, &nSuffix);
  167025. if( nSuffix<=0
  167026. || (&pReader->aNode[pReader->nNode] - pNext)<nSuffix
  167027. || nPrefix>pReader->nTerm
  167028. ){
  167029. return FTS_CORRUPT_VTAB;
  167030. }
  167031. /* Both nPrefix and nSuffix were read by fts3GetVarint32() and so are
  167032. ** between 0 and 0x7FFFFFFF. But the sum of the two may cause integer
  167033. ** overflow - hence the (i64) casts. */
  167034. if( (i64)nPrefix+nSuffix>(i64)pReader->nTermAlloc ){
  167035. i64 nNew = ((i64)nPrefix+nSuffix)*2;
  167036. char *zNew = sqlite3_realloc64(pReader->zTerm, nNew);
  167037. if( !zNew ){
  167038. return SQLITE_NOMEM;
  167039. }
  167040. pReader->zTerm = zNew;
  167041. pReader->nTermAlloc = nNew;
  167042. }
  167043. rc = fts3SegReaderRequire(pReader, pNext, nSuffix+FTS3_VARINT_MAX);
  167044. if( rc!=SQLITE_OK ) return rc;
  167045. memcpy(&pReader->zTerm[nPrefix], pNext, nSuffix);
  167046. pReader->nTerm = nPrefix+nSuffix;
  167047. pNext += nSuffix;
  167048. pNext += fts3GetVarint32(pNext, &pReader->nDoclist);
  167049. pReader->aDoclist = pNext;
  167050. pReader->pOffsetList = 0;
  167051. /* Check that the doclist does not appear to extend past the end of the
  167052. ** b-tree node. And that the final byte of the doclist is 0x00. If either
  167053. ** of these statements is untrue, then the data structure is corrupt.
  167054. */
  167055. if( pReader->nDoclist > pReader->nNode-(pReader->aDoclist-pReader->aNode)
  167056. || (pReader->nPopulate==0 && pReader->aDoclist[pReader->nDoclist-1])
  167057. || pReader->nDoclist==0
  167058. ){
  167059. return FTS_CORRUPT_VTAB;
  167060. }
  167061. return SQLITE_OK;
  167062. }
  167063. /*
  167064. ** Set the SegReader to point to the first docid in the doclist associated
  167065. ** with the current term.
  167066. */
  167067. static int fts3SegReaderFirstDocid(Fts3Table *pTab, Fts3SegReader *pReader){
  167068. int rc = SQLITE_OK;
  167069. assert( pReader->aDoclist );
  167070. assert( !pReader->pOffsetList );
  167071. if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
  167072. u8 bEof = 0;
  167073. pReader->iDocid = 0;
  167074. pReader->nOffsetList = 0;
  167075. sqlite3Fts3DoclistPrev(0,
  167076. pReader->aDoclist, pReader->nDoclist, &pReader->pOffsetList,
  167077. &pReader->iDocid, &pReader->nOffsetList, &bEof
  167078. );
  167079. }else{
  167080. rc = fts3SegReaderRequire(pReader, pReader->aDoclist, FTS3_VARINT_MAX);
  167081. if( rc==SQLITE_OK ){
  167082. int n = sqlite3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid);
  167083. pReader->pOffsetList = &pReader->aDoclist[n];
  167084. }
  167085. }
  167086. return rc;
  167087. }
  167088. /*
  167089. ** Advance the SegReader to point to the next docid in the doclist
  167090. ** associated with the current term.
  167091. **
  167092. ** If arguments ppOffsetList and pnOffsetList are not NULL, then
  167093. ** *ppOffsetList is set to point to the first column-offset list
  167094. ** in the doclist entry (i.e. immediately past the docid varint).
  167095. ** *pnOffsetList is set to the length of the set of column-offset
  167096. ** lists, not including the nul-terminator byte. For example:
  167097. */
  167098. static int fts3SegReaderNextDocid(
  167099. Fts3Table *pTab,
  167100. Fts3SegReader *pReader, /* Reader to advance to next docid */
  167101. char **ppOffsetList, /* OUT: Pointer to current position-list */
  167102. int *pnOffsetList /* OUT: Length of *ppOffsetList in bytes */
  167103. ){
  167104. int rc = SQLITE_OK;
  167105. char *p = pReader->pOffsetList;
  167106. char c = 0;
  167107. assert( p );
  167108. if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
  167109. /* A pending-terms seg-reader for an FTS4 table that uses order=desc.
  167110. ** Pending-terms doclists are always built up in ascending order, so
  167111. ** we have to iterate through them backwards here. */
  167112. u8 bEof = 0;
  167113. if( ppOffsetList ){
  167114. *ppOffsetList = pReader->pOffsetList;
  167115. *pnOffsetList = pReader->nOffsetList - 1;
  167116. }
  167117. sqlite3Fts3DoclistPrev(0,
  167118. pReader->aDoclist, pReader->nDoclist, &p, &pReader->iDocid,
  167119. &pReader->nOffsetList, &bEof
  167120. );
  167121. if( bEof ){
  167122. pReader->pOffsetList = 0;
  167123. }else{
  167124. pReader->pOffsetList = p;
  167125. }
  167126. }else{
  167127. char *pEnd = &pReader->aDoclist[pReader->nDoclist];
  167128. /* Pointer p currently points at the first byte of an offset list. The
  167129. ** following block advances it to point one byte past the end of
  167130. ** the same offset list. */
  167131. while( 1 ){
  167132. /* The following line of code (and the "p++" below the while() loop) is
  167133. ** normally all that is required to move pointer p to the desired
  167134. ** position. The exception is if this node is being loaded from disk
  167135. ** incrementally and pointer "p" now points to the first byte past
  167136. ** the populated part of pReader->aNode[].
  167137. */
  167138. while( *p | c ) c = *p++ & 0x80;
  167139. assert( *p==0 );
  167140. if( pReader->pBlob==0 || p<&pReader->aNode[pReader->nPopulate] ) break;
  167141. rc = fts3SegReaderIncrRead(pReader);
  167142. if( rc!=SQLITE_OK ) return rc;
  167143. }
  167144. p++;
  167145. /* If required, populate the output variables with a pointer to and the
  167146. ** size of the previous offset-list.
  167147. */
  167148. if( ppOffsetList ){
  167149. *ppOffsetList = pReader->pOffsetList;
  167150. *pnOffsetList = (int)(p - pReader->pOffsetList - 1);
  167151. }
  167152. /* List may have been edited in place by fts3EvalNearTrim() */
  167153. while( p<pEnd && *p==0 ) p++;
  167154. /* If there are no more entries in the doclist, set pOffsetList to
  167155. ** NULL. Otherwise, set Fts3SegReader.iDocid to the next docid and
  167156. ** Fts3SegReader.pOffsetList to point to the next offset list before
  167157. ** returning.
  167158. */
  167159. if( p>=pEnd ){
  167160. pReader->pOffsetList = 0;
  167161. }else{
  167162. rc = fts3SegReaderRequire(pReader, p, FTS3_VARINT_MAX);
  167163. if( rc==SQLITE_OK ){
  167164. u64 iDelta;
  167165. pReader->pOffsetList = p + sqlite3Fts3GetVarintU(p, &iDelta);
  167166. if( pTab->bDescIdx ){
  167167. pReader->iDocid = (i64)((u64)pReader->iDocid - iDelta);
  167168. }else{
  167169. pReader->iDocid = (i64)((u64)pReader->iDocid + iDelta);
  167170. }
  167171. }
  167172. }
  167173. }
  167174. return rc;
  167175. }
  167176. SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(
  167177. Fts3Cursor *pCsr,
  167178. Fts3MultiSegReader *pMsr,
  167179. int *pnOvfl
  167180. ){
  167181. Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
  167182. int nOvfl = 0;
  167183. int ii;
  167184. int rc = SQLITE_OK;
  167185. int pgsz = p->nPgsz;
  167186. assert( p->bFts4 );
  167187. assert( pgsz>0 );
  167188. for(ii=0; rc==SQLITE_OK && ii<pMsr->nSegment; ii++){
  167189. Fts3SegReader *pReader = pMsr->apSegment[ii];
  167190. if( !fts3SegReaderIsPending(pReader)
  167191. && !fts3SegReaderIsRootOnly(pReader)
  167192. ){
  167193. sqlite3_int64 jj;
  167194. for(jj=pReader->iStartBlock; jj<=pReader->iLeafEndBlock; jj++){
  167195. int nBlob;
  167196. rc = sqlite3Fts3ReadBlock(p, jj, 0, &nBlob, 0);
  167197. if( rc!=SQLITE_OK ) break;
  167198. if( (nBlob+35)>pgsz ){
  167199. nOvfl += (nBlob + 34)/pgsz;
  167200. }
  167201. }
  167202. }
  167203. }
  167204. *pnOvfl = nOvfl;
  167205. return rc;
  167206. }
  167207. /*
  167208. ** Free all allocations associated with the iterator passed as the
  167209. ** second argument.
  167210. */
  167211. SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *pReader){
  167212. if( pReader ){
  167213. if( !fts3SegReaderIsPending(pReader) ){
  167214. sqlite3_free(pReader->zTerm);
  167215. }
  167216. if( !fts3SegReaderIsRootOnly(pReader) ){
  167217. sqlite3_free(pReader->aNode);
  167218. }
  167219. sqlite3_blob_close(pReader->pBlob);
  167220. }
  167221. sqlite3_free(pReader);
  167222. }
  167223. /*
  167224. ** Allocate a new SegReader object.
  167225. */
  167226. SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(
  167227. int iAge, /* Segment "age". */
  167228. int bLookup, /* True for a lookup only */
  167229. sqlite3_int64 iStartLeaf, /* First leaf to traverse */
  167230. sqlite3_int64 iEndLeaf, /* Final leaf to traverse */
  167231. sqlite3_int64 iEndBlock, /* Final block of segment */
  167232. const char *zRoot, /* Buffer containing root node */
  167233. int nRoot, /* Size of buffer containing root node */
  167234. Fts3SegReader **ppReader /* OUT: Allocated Fts3SegReader */
  167235. ){
  167236. Fts3SegReader *pReader; /* Newly allocated SegReader object */
  167237. int nExtra = 0; /* Bytes to allocate segment root node */
  167238. assert( zRoot!=0 || nRoot==0 );
  167239. #ifdef CORRUPT_DB
  167240. assert( zRoot!=0 || CORRUPT_DB );
  167241. #endif
  167242. if( iStartLeaf==0 ){
  167243. if( iEndLeaf!=0 ) return FTS_CORRUPT_VTAB;
  167244. nExtra = nRoot + FTS3_NODE_PADDING;
  167245. }
  167246. pReader = (Fts3SegReader *)sqlite3_malloc(sizeof(Fts3SegReader) + nExtra);
  167247. if( !pReader ){
  167248. return SQLITE_NOMEM;
  167249. }
  167250. memset(pReader, 0, sizeof(Fts3SegReader));
  167251. pReader->iIdx = iAge;
  167252. pReader->bLookup = bLookup!=0;
  167253. pReader->iStartBlock = iStartLeaf;
  167254. pReader->iLeafEndBlock = iEndLeaf;
  167255. pReader->iEndBlock = iEndBlock;
  167256. if( nExtra ){
  167257. /* The entire segment is stored in the root node. */
  167258. pReader->aNode = (char *)&pReader[1];
  167259. pReader->rootOnly = 1;
  167260. pReader->nNode = nRoot;
  167261. if( nRoot ) memcpy(pReader->aNode, zRoot, nRoot);
  167262. memset(&pReader->aNode[nRoot], 0, FTS3_NODE_PADDING);
  167263. }else{
  167264. pReader->iCurrentBlock = iStartLeaf-1;
  167265. }
  167266. *ppReader = pReader;
  167267. return SQLITE_OK;
  167268. }
  167269. /*
  167270. ** This is a comparison function used as a qsort() callback when sorting
  167271. ** an array of pending terms by term. This occurs as part of flushing
  167272. ** the contents of the pending-terms hash table to the database.
  167273. */
  167274. static int SQLITE_CDECL fts3CompareElemByTerm(
  167275. const void *lhs,
  167276. const void *rhs
  167277. ){
  167278. char *z1 = fts3HashKey(*(Fts3HashElem **)lhs);
  167279. char *z2 = fts3HashKey(*(Fts3HashElem **)rhs);
  167280. int n1 = fts3HashKeysize(*(Fts3HashElem **)lhs);
  167281. int n2 = fts3HashKeysize(*(Fts3HashElem **)rhs);
  167282. int n = (n1<n2 ? n1 : n2);
  167283. int c = memcmp(z1, z2, n);
  167284. if( c==0 ){
  167285. c = n1 - n2;
  167286. }
  167287. return c;
  167288. }
  167289. /*
  167290. ** This function is used to allocate an Fts3SegReader that iterates through
  167291. ** a subset of the terms stored in the Fts3Table.pendingTerms array.
  167292. **
  167293. ** If the isPrefixIter parameter is zero, then the returned SegReader iterates
  167294. ** through each term in the pending-terms table. Or, if isPrefixIter is
  167295. ** non-zero, it iterates through each term and its prefixes. For example, if
  167296. ** the pending terms hash table contains the terms "sqlite", "mysql" and
  167297. ** "firebird", then the iterator visits the following 'terms' (in the order
  167298. ** shown):
  167299. **
  167300. ** f fi fir fire fireb firebi firebir firebird
  167301. ** m my mys mysq mysql
  167302. ** s sq sql sqli sqlit sqlite
  167303. **
  167304. ** Whereas if isPrefixIter is zero, the terms visited are:
  167305. **
  167306. ** firebird mysql sqlite
  167307. */
  167308. SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
  167309. Fts3Table *p, /* Virtual table handle */
  167310. int iIndex, /* Index for p->aIndex */
  167311. const char *zTerm, /* Term to search for */
  167312. int nTerm, /* Size of buffer zTerm */
  167313. int bPrefix, /* True for a prefix iterator */
  167314. Fts3SegReader **ppReader /* OUT: SegReader for pending-terms */
  167315. ){
  167316. Fts3SegReader *pReader = 0; /* Fts3SegReader object to return */
  167317. Fts3HashElem *pE; /* Iterator variable */
  167318. Fts3HashElem **aElem = 0; /* Array of term hash entries to scan */
  167319. int nElem = 0; /* Size of array at aElem */
  167320. int rc = SQLITE_OK; /* Return Code */
  167321. Fts3Hash *pHash;
  167322. pHash = &p->aIndex[iIndex].hPending;
  167323. if( bPrefix ){
  167324. int nAlloc = 0; /* Size of allocated array at aElem */
  167325. for(pE=fts3HashFirst(pHash); pE; pE=fts3HashNext(pE)){
  167326. char *zKey = (char *)fts3HashKey(pE);
  167327. int nKey = fts3HashKeysize(pE);
  167328. if( nTerm==0 || (nKey>=nTerm && 0==memcmp(zKey, zTerm, nTerm)) ){
  167329. if( nElem==nAlloc ){
  167330. Fts3HashElem **aElem2;
  167331. nAlloc += 16;
  167332. aElem2 = (Fts3HashElem **)sqlite3_realloc(
  167333. aElem, nAlloc*sizeof(Fts3HashElem *)
  167334. );
  167335. if( !aElem2 ){
  167336. rc = SQLITE_NOMEM;
  167337. nElem = 0;
  167338. break;
  167339. }
  167340. aElem = aElem2;
  167341. }
  167342. aElem[nElem++] = pE;
  167343. }
  167344. }
  167345. /* If more than one term matches the prefix, sort the Fts3HashElem
  167346. ** objects in term order using qsort(). This uses the same comparison
  167347. ** callback as is used when flushing terms to disk.
  167348. */
  167349. if( nElem>1 ){
  167350. qsort(aElem, nElem, sizeof(Fts3HashElem *), fts3CompareElemByTerm);
  167351. }
  167352. }else{
  167353. /* The query is a simple term lookup that matches at most one term in
  167354. ** the index. All that is required is a straight hash-lookup.
  167355. **
  167356. ** Because the stack address of pE may be accessed via the aElem pointer
  167357. ** below, the "Fts3HashElem *pE" must be declared so that it is valid
  167358. ** within this entire function, not just this "else{...}" block.
  167359. */
  167360. pE = fts3HashFindElem(pHash, zTerm, nTerm);
  167361. if( pE ){
  167362. aElem = &pE;
  167363. nElem = 1;
  167364. }
  167365. }
  167366. if( nElem>0 ){
  167367. sqlite3_int64 nByte;
  167368. nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *);
  167369. pReader = (Fts3SegReader *)sqlite3_malloc64(nByte);
  167370. if( !pReader ){
  167371. rc = SQLITE_NOMEM;
  167372. }else{
  167373. memset(pReader, 0, nByte);
  167374. pReader->iIdx = 0x7FFFFFFF;
  167375. pReader->ppNextElem = (Fts3HashElem **)&pReader[1];
  167376. memcpy(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *));
  167377. }
  167378. }
  167379. if( bPrefix ){
  167380. sqlite3_free(aElem);
  167381. }
  167382. *ppReader = pReader;
  167383. return rc;
  167384. }
  167385. /*
  167386. ** Compare the entries pointed to by two Fts3SegReader structures.
  167387. ** Comparison is as follows:
  167388. **
  167389. ** 1) EOF is greater than not EOF.
  167390. **
  167391. ** 2) The current terms (if any) are compared using memcmp(). If one
  167392. ** term is a prefix of another, the longer term is considered the
  167393. ** larger.
  167394. **
  167395. ** 3) By segment age. An older segment is considered larger.
  167396. */
  167397. static int fts3SegReaderCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
  167398. int rc;
  167399. if( pLhs->aNode && pRhs->aNode ){
  167400. int rc2 = pLhs->nTerm - pRhs->nTerm;
  167401. if( rc2<0 ){
  167402. rc = memcmp(pLhs->zTerm, pRhs->zTerm, pLhs->nTerm);
  167403. }else{
  167404. rc = memcmp(pLhs->zTerm, pRhs->zTerm, pRhs->nTerm);
  167405. }
  167406. if( rc==0 ){
  167407. rc = rc2;
  167408. }
  167409. }else{
  167410. rc = (pLhs->aNode==0) - (pRhs->aNode==0);
  167411. }
  167412. if( rc==0 ){
  167413. rc = pRhs->iIdx - pLhs->iIdx;
  167414. }
  167415. assert( rc!=0 );
  167416. return rc;
  167417. }
  167418. /*
  167419. ** A different comparison function for SegReader structures. In this
  167420. ** version, it is assumed that each SegReader points to an entry in
  167421. ** a doclist for identical terms. Comparison is made as follows:
  167422. **
  167423. ** 1) EOF (end of doclist in this case) is greater than not EOF.
  167424. **
  167425. ** 2) By current docid.
  167426. **
  167427. ** 3) By segment age. An older segment is considered larger.
  167428. */
  167429. static int fts3SegReaderDoclistCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
  167430. int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
  167431. if( rc==0 ){
  167432. if( pLhs->iDocid==pRhs->iDocid ){
  167433. rc = pRhs->iIdx - pLhs->iIdx;
  167434. }else{
  167435. rc = (pLhs->iDocid > pRhs->iDocid) ? 1 : -1;
  167436. }
  167437. }
  167438. assert( pLhs->aNode && pRhs->aNode );
  167439. return rc;
  167440. }
  167441. static int fts3SegReaderDoclistCmpRev(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
  167442. int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
  167443. if( rc==0 ){
  167444. if( pLhs->iDocid==pRhs->iDocid ){
  167445. rc = pRhs->iIdx - pLhs->iIdx;
  167446. }else{
  167447. rc = (pLhs->iDocid < pRhs->iDocid) ? 1 : -1;
  167448. }
  167449. }
  167450. assert( pLhs->aNode && pRhs->aNode );
  167451. return rc;
  167452. }
  167453. /*
  167454. ** Compare the term that the Fts3SegReader object passed as the first argument
  167455. ** points to with the term specified by arguments zTerm and nTerm.
  167456. **
  167457. ** If the pSeg iterator is already at EOF, return 0. Otherwise, return
  167458. ** -ve if the pSeg term is less than zTerm/nTerm, 0 if the two terms are
  167459. ** equal, or +ve if the pSeg term is greater than zTerm/nTerm.
  167460. */
  167461. static int fts3SegReaderTermCmp(
  167462. Fts3SegReader *pSeg, /* Segment reader object */
  167463. const char *zTerm, /* Term to compare to */
  167464. int nTerm /* Size of term zTerm in bytes */
  167465. ){
  167466. int res = 0;
  167467. if( pSeg->aNode ){
  167468. if( pSeg->nTerm>nTerm ){
  167469. res = memcmp(pSeg->zTerm, zTerm, nTerm);
  167470. }else{
  167471. res = memcmp(pSeg->zTerm, zTerm, pSeg->nTerm);
  167472. }
  167473. if( res==0 ){
  167474. res = pSeg->nTerm-nTerm;
  167475. }
  167476. }
  167477. return res;
  167478. }
  167479. /*
  167480. ** Argument apSegment is an array of nSegment elements. It is known that
  167481. ** the final (nSegment-nSuspect) members are already in sorted order
  167482. ** (according to the comparison function provided). This function shuffles
  167483. ** the array around until all entries are in sorted order.
  167484. */
  167485. static void fts3SegReaderSort(
  167486. Fts3SegReader **apSegment, /* Array to sort entries of */
  167487. int nSegment, /* Size of apSegment array */
  167488. int nSuspect, /* Unsorted entry count */
  167489. int (*xCmp)(Fts3SegReader *, Fts3SegReader *) /* Comparison function */
  167490. ){
  167491. int i; /* Iterator variable */
  167492. assert( nSuspect<=nSegment );
  167493. if( nSuspect==nSegment ) nSuspect--;
  167494. for(i=nSuspect-1; i>=0; i--){
  167495. int j;
  167496. for(j=i; j<(nSegment-1); j++){
  167497. Fts3SegReader *pTmp;
  167498. if( xCmp(apSegment[j], apSegment[j+1])<0 ) break;
  167499. pTmp = apSegment[j+1];
  167500. apSegment[j+1] = apSegment[j];
  167501. apSegment[j] = pTmp;
  167502. }
  167503. }
  167504. #ifndef NDEBUG
  167505. /* Check that the list really is sorted now. */
  167506. for(i=0; i<(nSuspect-1); i++){
  167507. assert( xCmp(apSegment[i], apSegment[i+1])<0 );
  167508. }
  167509. #endif
  167510. }
  167511. /*
  167512. ** Insert a record into the %_segments table.
  167513. */
  167514. static int fts3WriteSegment(
  167515. Fts3Table *p, /* Virtual table handle */
  167516. sqlite3_int64 iBlock, /* Block id for new block */
  167517. char *z, /* Pointer to buffer containing block data */
  167518. int n /* Size of buffer z in bytes */
  167519. ){
  167520. sqlite3_stmt *pStmt;
  167521. int rc = fts3SqlStmt(p, SQL_INSERT_SEGMENTS, &pStmt, 0);
  167522. if( rc==SQLITE_OK ){
  167523. sqlite3_bind_int64(pStmt, 1, iBlock);
  167524. sqlite3_bind_blob(pStmt, 2, z, n, SQLITE_STATIC);
  167525. sqlite3_step(pStmt);
  167526. rc = sqlite3_reset(pStmt);
  167527. sqlite3_bind_null(pStmt, 2);
  167528. }
  167529. return rc;
  167530. }
  167531. /*
  167532. ** Find the largest relative level number in the table. If successful, set
  167533. ** *pnMax to this value and return SQLITE_OK. Otherwise, if an error occurs,
  167534. ** set *pnMax to zero and return an SQLite error code.
  167535. */
  167536. SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *p, int *pnMax){
  167537. int rc;
  167538. int mxLevel = 0;
  167539. sqlite3_stmt *pStmt = 0;
  167540. rc = fts3SqlStmt(p, SQL_SELECT_MXLEVEL, &pStmt, 0);
  167541. if( rc==SQLITE_OK ){
  167542. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  167543. mxLevel = sqlite3_column_int(pStmt, 0);
  167544. }
  167545. rc = sqlite3_reset(pStmt);
  167546. }
  167547. *pnMax = mxLevel;
  167548. return rc;
  167549. }
  167550. /*
  167551. ** Insert a record into the %_segdir table.
  167552. */
  167553. static int fts3WriteSegdir(
  167554. Fts3Table *p, /* Virtual table handle */
  167555. sqlite3_int64 iLevel, /* Value for "level" field (absolute level) */
  167556. int iIdx, /* Value for "idx" field */
  167557. sqlite3_int64 iStartBlock, /* Value for "start_block" field */
  167558. sqlite3_int64 iLeafEndBlock, /* Value for "leaves_end_block" field */
  167559. sqlite3_int64 iEndBlock, /* Value for "end_block" field */
  167560. sqlite3_int64 nLeafData, /* Bytes of leaf data in segment */
  167561. char *zRoot, /* Blob value for "root" field */
  167562. int nRoot /* Number of bytes in buffer zRoot */
  167563. ){
  167564. sqlite3_stmt *pStmt;
  167565. int rc = fts3SqlStmt(p, SQL_INSERT_SEGDIR, &pStmt, 0);
  167566. if( rc==SQLITE_OK ){
  167567. sqlite3_bind_int64(pStmt, 1, iLevel);
  167568. sqlite3_bind_int(pStmt, 2, iIdx);
  167569. sqlite3_bind_int64(pStmt, 3, iStartBlock);
  167570. sqlite3_bind_int64(pStmt, 4, iLeafEndBlock);
  167571. if( nLeafData==0 ){
  167572. sqlite3_bind_int64(pStmt, 5, iEndBlock);
  167573. }else{
  167574. char *zEnd = sqlite3_mprintf("%lld %lld", iEndBlock, nLeafData);
  167575. if( !zEnd ) return SQLITE_NOMEM;
  167576. sqlite3_bind_text(pStmt, 5, zEnd, -1, sqlite3_free);
  167577. }
  167578. sqlite3_bind_blob(pStmt, 6, zRoot, nRoot, SQLITE_STATIC);
  167579. sqlite3_step(pStmt);
  167580. rc = sqlite3_reset(pStmt);
  167581. sqlite3_bind_null(pStmt, 6);
  167582. }
  167583. return rc;
  167584. }
  167585. /*
  167586. ** Return the size of the common prefix (if any) shared by zPrev and
  167587. ** zNext, in bytes. For example,
  167588. **
  167589. ** fts3PrefixCompress("abc", 3, "abcdef", 6) // returns 3
  167590. ** fts3PrefixCompress("abX", 3, "abcdef", 6) // returns 2
  167591. ** fts3PrefixCompress("abX", 3, "Xbcdef", 6) // returns 0
  167592. */
  167593. static int fts3PrefixCompress(
  167594. const char *zPrev, /* Buffer containing previous term */
  167595. int nPrev, /* Size of buffer zPrev in bytes */
  167596. const char *zNext, /* Buffer containing next term */
  167597. int nNext /* Size of buffer zNext in bytes */
  167598. ){
  167599. int n;
  167600. UNUSED_PARAMETER(nNext);
  167601. for(n=0; n<nPrev && zPrev[n]==zNext[n]; n++);
  167602. return n;
  167603. }
  167604. /*
  167605. ** Add term zTerm to the SegmentNode. It is guaranteed that zTerm is larger
  167606. ** (according to memcmp) than the previous term.
  167607. */
  167608. static int fts3NodeAddTerm(
  167609. Fts3Table *p, /* Virtual table handle */
  167610. SegmentNode **ppTree, /* IN/OUT: SegmentNode handle */
  167611. int isCopyTerm, /* True if zTerm/nTerm is transient */
  167612. const char *zTerm, /* Pointer to buffer containing term */
  167613. int nTerm /* Size of term in bytes */
  167614. ){
  167615. SegmentNode *pTree = *ppTree;
  167616. int rc;
  167617. SegmentNode *pNew;
  167618. /* First try to append the term to the current node. Return early if
  167619. ** this is possible.
  167620. */
  167621. if( pTree ){
  167622. int nData = pTree->nData; /* Current size of node in bytes */
  167623. int nReq = nData; /* Required space after adding zTerm */
  167624. int nPrefix; /* Number of bytes of prefix compression */
  167625. int nSuffix; /* Suffix length */
  167626. nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm);
  167627. nSuffix = nTerm-nPrefix;
  167628. /* If nSuffix is zero or less, then zTerm/nTerm must be a prefix of
  167629. ** pWriter->zTerm/pWriter->nTerm. i.e. must be equal to or less than when
  167630. ** compared with BINARY collation. This indicates corruption. */
  167631. if( nSuffix<=0 ) return FTS_CORRUPT_VTAB;
  167632. nReq += sqlite3Fts3VarintLen(nPrefix)+sqlite3Fts3VarintLen(nSuffix)+nSuffix;
  167633. if( nReq<=p->nNodeSize || !pTree->zTerm ){
  167634. if( nReq>p->nNodeSize ){
  167635. /* An unusual case: this is the first term to be added to the node
  167636. ** and the static node buffer (p->nNodeSize bytes) is not large
  167637. ** enough. Use a separately malloced buffer instead This wastes
  167638. ** p->nNodeSize bytes, but since this scenario only comes about when
  167639. ** the database contain two terms that share a prefix of almost 2KB,
  167640. ** this is not expected to be a serious problem.
  167641. */
  167642. assert( pTree->aData==(char *)&pTree[1] );
  167643. pTree->aData = (char *)sqlite3_malloc(nReq);
  167644. if( !pTree->aData ){
  167645. return SQLITE_NOMEM;
  167646. }
  167647. }
  167648. if( pTree->zTerm ){
  167649. /* There is no prefix-length field for first term in a node */
  167650. nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nPrefix);
  167651. }
  167652. nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nSuffix);
  167653. memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix);
  167654. pTree->nData = nData + nSuffix;
  167655. pTree->nEntry++;
  167656. if( isCopyTerm ){
  167657. if( pTree->nMalloc<nTerm ){
  167658. char *zNew = sqlite3_realloc(pTree->zMalloc, nTerm*2);
  167659. if( !zNew ){
  167660. return SQLITE_NOMEM;
  167661. }
  167662. pTree->nMalloc = nTerm*2;
  167663. pTree->zMalloc = zNew;
  167664. }
  167665. pTree->zTerm = pTree->zMalloc;
  167666. memcpy(pTree->zTerm, zTerm, nTerm);
  167667. pTree->nTerm = nTerm;
  167668. }else{
  167669. pTree->zTerm = (char *)zTerm;
  167670. pTree->nTerm = nTerm;
  167671. }
  167672. return SQLITE_OK;
  167673. }
  167674. }
  167675. /* If control flows to here, it was not possible to append zTerm to the
  167676. ** current node. Create a new node (a right-sibling of the current node).
  167677. ** If this is the first node in the tree, the term is added to it.
  167678. **
  167679. ** Otherwise, the term is not added to the new node, it is left empty for
  167680. ** now. Instead, the term is inserted into the parent of pTree. If pTree
  167681. ** has no parent, one is created here.
  167682. */
  167683. pNew = (SegmentNode *)sqlite3_malloc(sizeof(SegmentNode) + p->nNodeSize);
  167684. if( !pNew ){
  167685. return SQLITE_NOMEM;
  167686. }
  167687. memset(pNew, 0, sizeof(SegmentNode));
  167688. pNew->nData = 1 + FTS3_VARINT_MAX;
  167689. pNew->aData = (char *)&pNew[1];
  167690. if( pTree ){
  167691. SegmentNode *pParent = pTree->pParent;
  167692. rc = fts3NodeAddTerm(p, &pParent, isCopyTerm, zTerm, nTerm);
  167693. if( pTree->pParent==0 ){
  167694. pTree->pParent = pParent;
  167695. }
  167696. pTree->pRight = pNew;
  167697. pNew->pLeftmost = pTree->pLeftmost;
  167698. pNew->pParent = pParent;
  167699. pNew->zMalloc = pTree->zMalloc;
  167700. pNew->nMalloc = pTree->nMalloc;
  167701. pTree->zMalloc = 0;
  167702. }else{
  167703. pNew->pLeftmost = pNew;
  167704. rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm);
  167705. }
  167706. *ppTree = pNew;
  167707. return rc;
  167708. }
  167709. /*
  167710. ** Helper function for fts3NodeWrite().
  167711. */
  167712. static int fts3TreeFinishNode(
  167713. SegmentNode *pTree,
  167714. int iHeight,
  167715. sqlite3_int64 iLeftChild
  167716. ){
  167717. int nStart;
  167718. assert( iHeight>=1 && iHeight<128 );
  167719. nStart = FTS3_VARINT_MAX - sqlite3Fts3VarintLen(iLeftChild);
  167720. pTree->aData[nStart] = (char)iHeight;
  167721. sqlite3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild);
  167722. return nStart;
  167723. }
  167724. /*
  167725. ** Write the buffer for the segment node pTree and all of its peers to the
  167726. ** database. Then call this function recursively to write the parent of
  167727. ** pTree and its peers to the database.
  167728. **
  167729. ** Except, if pTree is a root node, do not write it to the database. Instead,
  167730. ** set output variables *paRoot and *pnRoot to contain the root node.
  167731. **
  167732. ** If successful, SQLITE_OK is returned and output variable *piLast is
  167733. ** set to the largest blockid written to the database (or zero if no
  167734. ** blocks were written to the db). Otherwise, an SQLite error code is
  167735. ** returned.
  167736. */
  167737. static int fts3NodeWrite(
  167738. Fts3Table *p, /* Virtual table handle */
  167739. SegmentNode *pTree, /* SegmentNode handle */
  167740. int iHeight, /* Height of this node in tree */
  167741. sqlite3_int64 iLeaf, /* Block id of first leaf node */
  167742. sqlite3_int64 iFree, /* Block id of next free slot in %_segments */
  167743. sqlite3_int64 *piLast, /* OUT: Block id of last entry written */
  167744. char **paRoot, /* OUT: Data for root node */
  167745. int *pnRoot /* OUT: Size of root node in bytes */
  167746. ){
  167747. int rc = SQLITE_OK;
  167748. if( !pTree->pParent ){
  167749. /* Root node of the tree. */
  167750. int nStart = fts3TreeFinishNode(pTree, iHeight, iLeaf);
  167751. *piLast = iFree-1;
  167752. *pnRoot = pTree->nData - nStart;
  167753. *paRoot = &pTree->aData[nStart];
  167754. }else{
  167755. SegmentNode *pIter;
  167756. sqlite3_int64 iNextFree = iFree;
  167757. sqlite3_int64 iNextLeaf = iLeaf;
  167758. for(pIter=pTree->pLeftmost; pIter && rc==SQLITE_OK; pIter=pIter->pRight){
  167759. int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf);
  167760. int nWrite = pIter->nData - nStart;
  167761. rc = fts3WriteSegment(p, iNextFree, &pIter->aData[nStart], nWrite);
  167762. iNextFree++;
  167763. iNextLeaf += (pIter->nEntry+1);
  167764. }
  167765. if( rc==SQLITE_OK ){
  167766. assert( iNextLeaf==iFree );
  167767. rc = fts3NodeWrite(
  167768. p, pTree->pParent, iHeight+1, iFree, iNextFree, piLast, paRoot, pnRoot
  167769. );
  167770. }
  167771. }
  167772. return rc;
  167773. }
  167774. /*
  167775. ** Free all memory allocations associated with the tree pTree.
  167776. */
  167777. static void fts3NodeFree(SegmentNode *pTree){
  167778. if( pTree ){
  167779. SegmentNode *p = pTree->pLeftmost;
  167780. fts3NodeFree(p->pParent);
  167781. while( p ){
  167782. SegmentNode *pRight = p->pRight;
  167783. if( p->aData!=(char *)&p[1] ){
  167784. sqlite3_free(p->aData);
  167785. }
  167786. assert( pRight==0 || p->zMalloc==0 );
  167787. sqlite3_free(p->zMalloc);
  167788. sqlite3_free(p);
  167789. p = pRight;
  167790. }
  167791. }
  167792. }
  167793. /*
  167794. ** Add a term to the segment being constructed by the SegmentWriter object
  167795. ** *ppWriter. When adding the first term to a segment, *ppWriter should
  167796. ** be passed NULL. This function will allocate a new SegmentWriter object
  167797. ** and return it via the input/output variable *ppWriter in this case.
  167798. **
  167799. ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
  167800. */
  167801. static int fts3SegWriterAdd(
  167802. Fts3Table *p, /* Virtual table handle */
  167803. SegmentWriter **ppWriter, /* IN/OUT: SegmentWriter handle */
  167804. int isCopyTerm, /* True if buffer zTerm must be copied */
  167805. const char *zTerm, /* Pointer to buffer containing term */
  167806. int nTerm, /* Size of term in bytes */
  167807. const char *aDoclist, /* Pointer to buffer containing doclist */
  167808. int nDoclist /* Size of doclist in bytes */
  167809. ){
  167810. int nPrefix; /* Size of term prefix in bytes */
  167811. int nSuffix; /* Size of term suffix in bytes */
  167812. int nReq; /* Number of bytes required on leaf page */
  167813. int nData;
  167814. SegmentWriter *pWriter = *ppWriter;
  167815. if( !pWriter ){
  167816. int rc;
  167817. sqlite3_stmt *pStmt;
  167818. /* Allocate the SegmentWriter structure */
  167819. pWriter = (SegmentWriter *)sqlite3_malloc(sizeof(SegmentWriter));
  167820. if( !pWriter ) return SQLITE_NOMEM;
  167821. memset(pWriter, 0, sizeof(SegmentWriter));
  167822. *ppWriter = pWriter;
  167823. /* Allocate a buffer in which to accumulate data */
  167824. pWriter->aData = (char *)sqlite3_malloc(p->nNodeSize);
  167825. if( !pWriter->aData ) return SQLITE_NOMEM;
  167826. pWriter->nSize = p->nNodeSize;
  167827. /* Find the next free blockid in the %_segments table */
  167828. rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0);
  167829. if( rc!=SQLITE_OK ) return rc;
  167830. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  167831. pWriter->iFree = sqlite3_column_int64(pStmt, 0);
  167832. pWriter->iFirst = pWriter->iFree;
  167833. }
  167834. rc = sqlite3_reset(pStmt);
  167835. if( rc!=SQLITE_OK ) return rc;
  167836. }
  167837. nData = pWriter->nData;
  167838. nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm);
  167839. nSuffix = nTerm-nPrefix;
  167840. /* If nSuffix is zero or less, then zTerm/nTerm must be a prefix of
  167841. ** pWriter->zTerm/pWriter->nTerm. i.e. must be equal to or less than when
  167842. ** compared with BINARY collation. This indicates corruption. */
  167843. if( nSuffix<=0 ) return FTS_CORRUPT_VTAB;
  167844. /* Figure out how many bytes are required by this new entry */
  167845. nReq = sqlite3Fts3VarintLen(nPrefix) + /* varint containing prefix size */
  167846. sqlite3Fts3VarintLen(nSuffix) + /* varint containing suffix size */
  167847. nSuffix + /* Term suffix */
  167848. sqlite3Fts3VarintLen(nDoclist) + /* Size of doclist */
  167849. nDoclist; /* Doclist data */
  167850. if( nData>0 && nData+nReq>p->nNodeSize ){
  167851. int rc;
  167852. /* The current leaf node is full. Write it out to the database. */
  167853. if( pWriter->iFree==LARGEST_INT64 ) return FTS_CORRUPT_VTAB;
  167854. rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData);
  167855. if( rc!=SQLITE_OK ) return rc;
  167856. p->nLeafAdd++;
  167857. /* Add the current term to the interior node tree. The term added to
  167858. ** the interior tree must:
  167859. **
  167860. ** a) be greater than the largest term on the leaf node just written
  167861. ** to the database (still available in pWriter->zTerm), and
  167862. **
  167863. ** b) be less than or equal to the term about to be added to the new
  167864. ** leaf node (zTerm/nTerm).
  167865. **
  167866. ** In other words, it must be the prefix of zTerm 1 byte longer than
  167867. ** the common prefix (if any) of zTerm and pWriter->zTerm.
  167868. */
  167869. assert( nPrefix<nTerm );
  167870. rc = fts3NodeAddTerm(p, &pWriter->pTree, isCopyTerm, zTerm, nPrefix+1);
  167871. if( rc!=SQLITE_OK ) return rc;
  167872. nData = 0;
  167873. pWriter->nTerm = 0;
  167874. nPrefix = 0;
  167875. nSuffix = nTerm;
  167876. nReq = 1 + /* varint containing prefix size */
  167877. sqlite3Fts3VarintLen(nTerm) + /* varint containing suffix size */
  167878. nTerm + /* Term suffix */
  167879. sqlite3Fts3VarintLen(nDoclist) + /* Size of doclist */
  167880. nDoclist; /* Doclist data */
  167881. }
  167882. /* Increase the total number of bytes written to account for the new entry. */
  167883. pWriter->nLeafData += nReq;
  167884. /* If the buffer currently allocated is too small for this entry, realloc
  167885. ** the buffer to make it large enough.
  167886. */
  167887. if( nReq>pWriter->nSize ){
  167888. char *aNew = sqlite3_realloc(pWriter->aData, nReq);
  167889. if( !aNew ) return SQLITE_NOMEM;
  167890. pWriter->aData = aNew;
  167891. pWriter->nSize = nReq;
  167892. }
  167893. assert( nData+nReq<=pWriter->nSize );
  167894. /* Append the prefix-compressed term and doclist to the buffer. */
  167895. nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix);
  167896. nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix);
  167897. assert( nSuffix>0 );
  167898. memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix);
  167899. nData += nSuffix;
  167900. nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist);
  167901. assert( nDoclist>0 );
  167902. memcpy(&pWriter->aData[nData], aDoclist, nDoclist);
  167903. pWriter->nData = nData + nDoclist;
  167904. /* Save the current term so that it can be used to prefix-compress the next.
  167905. ** If the isCopyTerm parameter is true, then the buffer pointed to by
  167906. ** zTerm is transient, so take a copy of the term data. Otherwise, just
  167907. ** store a copy of the pointer.
  167908. */
  167909. if( isCopyTerm ){
  167910. if( nTerm>pWriter->nMalloc ){
  167911. char *zNew = sqlite3_realloc(pWriter->zMalloc, nTerm*2);
  167912. if( !zNew ){
  167913. return SQLITE_NOMEM;
  167914. }
  167915. pWriter->nMalloc = nTerm*2;
  167916. pWriter->zMalloc = zNew;
  167917. pWriter->zTerm = zNew;
  167918. }
  167919. assert( pWriter->zTerm==pWriter->zMalloc );
  167920. assert( nTerm>0 );
  167921. memcpy(pWriter->zTerm, zTerm, nTerm);
  167922. }else{
  167923. pWriter->zTerm = (char *)zTerm;
  167924. }
  167925. pWriter->nTerm = nTerm;
  167926. return SQLITE_OK;
  167927. }
  167928. /*
  167929. ** Flush all data associated with the SegmentWriter object pWriter to the
  167930. ** database. This function must be called after all terms have been added
  167931. ** to the segment using fts3SegWriterAdd(). If successful, SQLITE_OK is
  167932. ** returned. Otherwise, an SQLite error code.
  167933. */
  167934. static int fts3SegWriterFlush(
  167935. Fts3Table *p, /* Virtual table handle */
  167936. SegmentWriter *pWriter, /* SegmentWriter to flush to the db */
  167937. sqlite3_int64 iLevel, /* Value for 'level' column of %_segdir */
  167938. int iIdx /* Value for 'idx' column of %_segdir */
  167939. ){
  167940. int rc; /* Return code */
  167941. if( pWriter->pTree ){
  167942. sqlite3_int64 iLast = 0; /* Largest block id written to database */
  167943. sqlite3_int64 iLastLeaf; /* Largest leaf block id written to db */
  167944. char *zRoot = NULL; /* Pointer to buffer containing root node */
  167945. int nRoot = 0; /* Size of buffer zRoot */
  167946. iLastLeaf = pWriter->iFree;
  167947. rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, pWriter->nData);
  167948. if( rc==SQLITE_OK ){
  167949. rc = fts3NodeWrite(p, pWriter->pTree, 1,
  167950. pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot);
  167951. }
  167952. if( rc==SQLITE_OK ){
  167953. rc = fts3WriteSegdir(p, iLevel, iIdx,
  167954. pWriter->iFirst, iLastLeaf, iLast, pWriter->nLeafData, zRoot, nRoot);
  167955. }
  167956. }else{
  167957. /* The entire tree fits on the root node. Write it to the segdir table. */
  167958. rc = fts3WriteSegdir(p, iLevel, iIdx,
  167959. 0, 0, 0, pWriter->nLeafData, pWriter->aData, pWriter->nData);
  167960. }
  167961. p->nLeafAdd++;
  167962. return rc;
  167963. }
  167964. /*
  167965. ** Release all memory held by the SegmentWriter object passed as the
  167966. ** first argument.
  167967. */
  167968. static void fts3SegWriterFree(SegmentWriter *pWriter){
  167969. if( pWriter ){
  167970. sqlite3_free(pWriter->aData);
  167971. sqlite3_free(pWriter->zMalloc);
  167972. fts3NodeFree(pWriter->pTree);
  167973. sqlite3_free(pWriter);
  167974. }
  167975. }
  167976. /*
  167977. ** The first value in the apVal[] array is assumed to contain an integer.
  167978. ** This function tests if there exist any documents with docid values that
  167979. ** are different from that integer. i.e. if deleting the document with docid
  167980. ** pRowid would mean the FTS3 table were empty.
  167981. **
  167982. ** If successful, *pisEmpty is set to true if the table is empty except for
  167983. ** document pRowid, or false otherwise, and SQLITE_OK is returned. If an
  167984. ** error occurs, an SQLite error code is returned.
  167985. */
  167986. static int fts3IsEmpty(Fts3Table *p, sqlite3_value *pRowid, int *pisEmpty){
  167987. sqlite3_stmt *pStmt;
  167988. int rc;
  167989. if( p->zContentTbl ){
  167990. /* If using the content=xxx option, assume the table is never empty */
  167991. *pisEmpty = 0;
  167992. rc = SQLITE_OK;
  167993. }else{
  167994. rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, &pRowid);
  167995. if( rc==SQLITE_OK ){
  167996. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  167997. *pisEmpty = sqlite3_column_int(pStmt, 0);
  167998. }
  167999. rc = sqlite3_reset(pStmt);
  168000. }
  168001. }
  168002. return rc;
  168003. }
  168004. /*
  168005. ** Set *pnMax to the largest segment level in the database for the index
  168006. ** iIndex.
  168007. **
  168008. ** Segment levels are stored in the 'level' column of the %_segdir table.
  168009. **
  168010. ** Return SQLITE_OK if successful, or an SQLite error code if not.
  168011. */
  168012. static int fts3SegmentMaxLevel(
  168013. Fts3Table *p,
  168014. int iLangid,
  168015. int iIndex,
  168016. sqlite3_int64 *pnMax
  168017. ){
  168018. sqlite3_stmt *pStmt;
  168019. int rc;
  168020. assert( iIndex>=0 && iIndex<p->nIndex );
  168021. /* Set pStmt to the compiled version of:
  168022. **
  168023. ** SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
  168024. **
  168025. ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
  168026. */
  168027. rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
  168028. if( rc!=SQLITE_OK ) return rc;
  168029. sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
  168030. sqlite3_bind_int64(pStmt, 2,
  168031. getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
  168032. );
  168033. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  168034. *pnMax = sqlite3_column_int64(pStmt, 0);
  168035. }
  168036. return sqlite3_reset(pStmt);
  168037. }
  168038. /*
  168039. ** iAbsLevel is an absolute level that may be assumed to exist within
  168040. ** the database. This function checks if it is the largest level number
  168041. ** within its index. Assuming no error occurs, *pbMax is set to 1 if
  168042. ** iAbsLevel is indeed the largest level, or 0 otherwise, and SQLITE_OK
  168043. ** is returned. If an error occurs, an error code is returned and the
  168044. ** final value of *pbMax is undefined.
  168045. */
  168046. static int fts3SegmentIsMaxLevel(Fts3Table *p, i64 iAbsLevel, int *pbMax){
  168047. /* Set pStmt to the compiled version of:
  168048. **
  168049. ** SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
  168050. **
  168051. ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
  168052. */
  168053. sqlite3_stmt *pStmt;
  168054. int rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
  168055. if( rc!=SQLITE_OK ) return rc;
  168056. sqlite3_bind_int64(pStmt, 1, iAbsLevel+1);
  168057. sqlite3_bind_int64(pStmt, 2,
  168058. (((u64)iAbsLevel/FTS3_SEGDIR_MAXLEVEL)+1) * FTS3_SEGDIR_MAXLEVEL
  168059. );
  168060. *pbMax = 0;
  168061. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  168062. *pbMax = sqlite3_column_type(pStmt, 0)==SQLITE_NULL;
  168063. }
  168064. return sqlite3_reset(pStmt);
  168065. }
  168066. /*
  168067. ** Delete all entries in the %_segments table associated with the segment
  168068. ** opened with seg-reader pSeg. This function does not affect the contents
  168069. ** of the %_segdir table.
  168070. */
  168071. static int fts3DeleteSegment(
  168072. Fts3Table *p, /* FTS table handle */
  168073. Fts3SegReader *pSeg /* Segment to delete */
  168074. ){
  168075. int rc = SQLITE_OK; /* Return code */
  168076. if( pSeg->iStartBlock ){
  168077. sqlite3_stmt *pDelete; /* SQL statement to delete rows */
  168078. rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0);
  168079. if( rc==SQLITE_OK ){
  168080. sqlite3_bind_int64(pDelete, 1, pSeg->iStartBlock);
  168081. sqlite3_bind_int64(pDelete, 2, pSeg->iEndBlock);
  168082. sqlite3_step(pDelete);
  168083. rc = sqlite3_reset(pDelete);
  168084. }
  168085. }
  168086. return rc;
  168087. }
  168088. /*
  168089. ** This function is used after merging multiple segments into a single large
  168090. ** segment to delete the old, now redundant, segment b-trees. Specifically,
  168091. ** it:
  168092. **
  168093. ** 1) Deletes all %_segments entries for the segments associated with
  168094. ** each of the SegReader objects in the array passed as the third
  168095. ** argument, and
  168096. **
  168097. ** 2) deletes all %_segdir entries with level iLevel, or all %_segdir
  168098. ** entries regardless of level if (iLevel<0).
  168099. **
  168100. ** SQLITE_OK is returned if successful, otherwise an SQLite error code.
  168101. */
  168102. static int fts3DeleteSegdir(
  168103. Fts3Table *p, /* Virtual table handle */
  168104. int iLangid, /* Language id */
  168105. int iIndex, /* Index for p->aIndex */
  168106. int iLevel, /* Level of %_segdir entries to delete */
  168107. Fts3SegReader **apSegment, /* Array of SegReader objects */
  168108. int nReader /* Size of array apSegment */
  168109. ){
  168110. int rc = SQLITE_OK; /* Return Code */
  168111. int i; /* Iterator variable */
  168112. sqlite3_stmt *pDelete = 0; /* SQL statement to delete rows */
  168113. for(i=0; rc==SQLITE_OK && i<nReader; i++){
  168114. rc = fts3DeleteSegment(p, apSegment[i]);
  168115. }
  168116. if( rc!=SQLITE_OK ){
  168117. return rc;
  168118. }
  168119. assert( iLevel>=0 || iLevel==FTS3_SEGCURSOR_ALL );
  168120. if( iLevel==FTS3_SEGCURSOR_ALL ){
  168121. rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_RANGE, &pDelete, 0);
  168122. if( rc==SQLITE_OK ){
  168123. sqlite3_bind_int64(pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
  168124. sqlite3_bind_int64(pDelete, 2,
  168125. getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
  168126. );
  168127. }
  168128. }else{
  168129. rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pDelete, 0);
  168130. if( rc==SQLITE_OK ){
  168131. sqlite3_bind_int64(
  168132. pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
  168133. );
  168134. }
  168135. }
  168136. if( rc==SQLITE_OK ){
  168137. sqlite3_step(pDelete);
  168138. rc = sqlite3_reset(pDelete);
  168139. }
  168140. return rc;
  168141. }
  168142. /*
  168143. ** When this function is called, buffer *ppList (size *pnList bytes) contains
  168144. ** a position list that may (or may not) feature multiple columns. This
  168145. ** function adjusts the pointer *ppList and the length *pnList so that they
  168146. ** identify the subset of the position list that corresponds to column iCol.
  168147. **
  168148. ** If there are no entries in the input position list for column iCol, then
  168149. ** *pnList is set to zero before returning.
  168150. **
  168151. ** If parameter bZero is non-zero, then any part of the input list following
  168152. ** the end of the output list is zeroed before returning.
  168153. */
  168154. static void fts3ColumnFilter(
  168155. int iCol, /* Column to filter on */
  168156. int bZero, /* Zero out anything following *ppList */
  168157. char **ppList, /* IN/OUT: Pointer to position list */
  168158. int *pnList /* IN/OUT: Size of buffer *ppList in bytes */
  168159. ){
  168160. char *pList = *ppList;
  168161. int nList = *pnList;
  168162. char *pEnd = &pList[nList];
  168163. int iCurrent = 0;
  168164. char *p = pList;
  168165. assert( iCol>=0 );
  168166. while( 1 ){
  168167. char c = 0;
  168168. while( p<pEnd && (c | *p)&0xFE ) c = *p++ & 0x80;
  168169. if( iCol==iCurrent ){
  168170. nList = (int)(p - pList);
  168171. break;
  168172. }
  168173. nList -= (int)(p - pList);
  168174. pList = p;
  168175. if( nList<=0 ){
  168176. break;
  168177. }
  168178. p = &pList[1];
  168179. p += fts3GetVarint32(p, &iCurrent);
  168180. }
  168181. if( bZero && (pEnd - &pList[nList])>0){
  168182. memset(&pList[nList], 0, pEnd - &pList[nList]);
  168183. }
  168184. *ppList = pList;
  168185. *pnList = nList;
  168186. }
  168187. /*
  168188. ** Cache data in the Fts3MultiSegReader.aBuffer[] buffer (overwriting any
  168189. ** existing data). Grow the buffer if required.
  168190. **
  168191. ** If successful, return SQLITE_OK. Otherwise, if an OOM error is encountered
  168192. ** trying to resize the buffer, return SQLITE_NOMEM.
  168193. */
  168194. static int fts3MsrBufferData(
  168195. Fts3MultiSegReader *pMsr, /* Multi-segment-reader handle */
  168196. char *pList,
  168197. int nList
  168198. ){
  168199. if( nList>pMsr->nBuffer ){
  168200. char *pNew;
  168201. pMsr->nBuffer = nList*2;
  168202. pNew = (char *)sqlite3_realloc(pMsr->aBuffer, pMsr->nBuffer);
  168203. if( !pNew ) return SQLITE_NOMEM;
  168204. pMsr->aBuffer = pNew;
  168205. }
  168206. assert( nList>0 );
  168207. memcpy(pMsr->aBuffer, pList, nList);
  168208. return SQLITE_OK;
  168209. }
  168210. SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
  168211. Fts3Table *p, /* Virtual table handle */
  168212. Fts3MultiSegReader *pMsr, /* Multi-segment-reader handle */
  168213. sqlite3_int64 *piDocid, /* OUT: Docid value */
  168214. char **paPoslist, /* OUT: Pointer to position list */
  168215. int *pnPoslist /* OUT: Size of position list in bytes */
  168216. ){
  168217. int nMerge = pMsr->nAdvance;
  168218. Fts3SegReader **apSegment = pMsr->apSegment;
  168219. int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
  168220. p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
  168221. );
  168222. if( nMerge==0 ){
  168223. *paPoslist = 0;
  168224. return SQLITE_OK;
  168225. }
  168226. while( 1 ){
  168227. Fts3SegReader *pSeg;
  168228. pSeg = pMsr->apSegment[0];
  168229. if( pSeg->pOffsetList==0 ){
  168230. *paPoslist = 0;
  168231. break;
  168232. }else{
  168233. int rc;
  168234. char *pList;
  168235. int nList;
  168236. int j;
  168237. sqlite3_int64 iDocid = apSegment[0]->iDocid;
  168238. rc = fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
  168239. j = 1;
  168240. while( rc==SQLITE_OK
  168241. && j<nMerge
  168242. && apSegment[j]->pOffsetList
  168243. && apSegment[j]->iDocid==iDocid
  168244. ){
  168245. rc = fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
  168246. j++;
  168247. }
  168248. if( rc!=SQLITE_OK ) return rc;
  168249. fts3SegReaderSort(pMsr->apSegment, nMerge, j, xCmp);
  168250. if( nList>0 && fts3SegReaderIsPending(apSegment[0]) ){
  168251. rc = fts3MsrBufferData(pMsr, pList, nList+1);
  168252. if( rc!=SQLITE_OK ) return rc;
  168253. assert( (pMsr->aBuffer[nList] & 0xFE)==0x00 );
  168254. pList = pMsr->aBuffer;
  168255. }
  168256. if( pMsr->iColFilter>=0 ){
  168257. fts3ColumnFilter(pMsr->iColFilter, 1, &pList, &nList);
  168258. }
  168259. if( nList>0 ){
  168260. *paPoslist = pList;
  168261. *piDocid = iDocid;
  168262. *pnPoslist = nList;
  168263. break;
  168264. }
  168265. }
  168266. }
  168267. return SQLITE_OK;
  168268. }
  168269. static int fts3SegReaderStart(
  168270. Fts3Table *p, /* Virtual table handle */
  168271. Fts3MultiSegReader *pCsr, /* Cursor object */
  168272. const char *zTerm, /* Term searched for (or NULL) */
  168273. int nTerm /* Length of zTerm in bytes */
  168274. ){
  168275. int i;
  168276. int nSeg = pCsr->nSegment;
  168277. /* If the Fts3SegFilter defines a specific term (or term prefix) to search
  168278. ** for, then advance each segment iterator until it points to a term of
  168279. ** equal or greater value than the specified term. This prevents many
  168280. ** unnecessary merge/sort operations for the case where single segment
  168281. ** b-tree leaf nodes contain more than one term.
  168282. */
  168283. for(i=0; pCsr->bRestart==0 && i<pCsr->nSegment; i++){
  168284. int res = 0;
  168285. Fts3SegReader *pSeg = pCsr->apSegment[i];
  168286. do {
  168287. int rc = fts3SegReaderNext(p, pSeg, 0);
  168288. if( rc!=SQLITE_OK ) return rc;
  168289. }while( zTerm && (res = fts3SegReaderTermCmp(pSeg, zTerm, nTerm))<0 );
  168290. if( pSeg->bLookup && res!=0 ){
  168291. fts3SegReaderSetEof(pSeg);
  168292. }
  168293. }
  168294. fts3SegReaderSort(pCsr->apSegment, nSeg, nSeg, fts3SegReaderCmp);
  168295. return SQLITE_OK;
  168296. }
  168297. SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(
  168298. Fts3Table *p, /* Virtual table handle */
  168299. Fts3MultiSegReader *pCsr, /* Cursor object */
  168300. Fts3SegFilter *pFilter /* Restrictions on range of iteration */
  168301. ){
  168302. pCsr->pFilter = pFilter;
  168303. return fts3SegReaderStart(p, pCsr, pFilter->zTerm, pFilter->nTerm);
  168304. }
  168305. SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
  168306. Fts3Table *p, /* Virtual table handle */
  168307. Fts3MultiSegReader *pCsr, /* Cursor object */
  168308. int iCol, /* Column to match on. */
  168309. const char *zTerm, /* Term to iterate through a doclist for */
  168310. int nTerm /* Number of bytes in zTerm */
  168311. ){
  168312. int i;
  168313. int rc;
  168314. int nSegment = pCsr->nSegment;
  168315. int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
  168316. p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
  168317. );
  168318. assert( pCsr->pFilter==0 );
  168319. assert( zTerm && nTerm>0 );
  168320. /* Advance each segment iterator until it points to the term zTerm/nTerm. */
  168321. rc = fts3SegReaderStart(p, pCsr, zTerm, nTerm);
  168322. if( rc!=SQLITE_OK ) return rc;
  168323. /* Determine how many of the segments actually point to zTerm/nTerm. */
  168324. for(i=0; i<nSegment; i++){
  168325. Fts3SegReader *pSeg = pCsr->apSegment[i];
  168326. if( !pSeg->aNode || fts3SegReaderTermCmp(pSeg, zTerm, nTerm) ){
  168327. break;
  168328. }
  168329. }
  168330. pCsr->nAdvance = i;
  168331. /* Advance each of the segments to point to the first docid. */
  168332. for(i=0; i<pCsr->nAdvance; i++){
  168333. rc = fts3SegReaderFirstDocid(p, pCsr->apSegment[i]);
  168334. if( rc!=SQLITE_OK ) return rc;
  168335. }
  168336. fts3SegReaderSort(pCsr->apSegment, i, i, xCmp);
  168337. assert( iCol<0 || iCol<p->nColumn );
  168338. pCsr->iColFilter = iCol;
  168339. return SQLITE_OK;
  168340. }
  168341. /*
  168342. ** This function is called on a MultiSegReader that has been started using
  168343. ** sqlite3Fts3MsrIncrStart(). One or more calls to MsrIncrNext() may also
  168344. ** have been made. Calling this function puts the MultiSegReader in such
  168345. ** a state that if the next two calls are:
  168346. **
  168347. ** sqlite3Fts3SegReaderStart()
  168348. ** sqlite3Fts3SegReaderStep()
  168349. **
  168350. ** then the entire doclist for the term is available in
  168351. ** MultiSegReader.aDoclist/nDoclist.
  168352. */
  168353. SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr){
  168354. int i; /* Used to iterate through segment-readers */
  168355. assert( pCsr->zTerm==0 );
  168356. assert( pCsr->nTerm==0 );
  168357. assert( pCsr->aDoclist==0 );
  168358. assert( pCsr->nDoclist==0 );
  168359. pCsr->nAdvance = 0;
  168360. pCsr->bRestart = 1;
  168361. for(i=0; i<pCsr->nSegment; i++){
  168362. pCsr->apSegment[i]->pOffsetList = 0;
  168363. pCsr->apSegment[i]->nOffsetList = 0;
  168364. pCsr->apSegment[i]->iDocid = 0;
  168365. }
  168366. return SQLITE_OK;
  168367. }
  168368. SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(
  168369. Fts3Table *p, /* Virtual table handle */
  168370. Fts3MultiSegReader *pCsr /* Cursor object */
  168371. ){
  168372. int rc = SQLITE_OK;
  168373. int isIgnoreEmpty = (pCsr->pFilter->flags & FTS3_SEGMENT_IGNORE_EMPTY);
  168374. int isRequirePos = (pCsr->pFilter->flags & FTS3_SEGMENT_REQUIRE_POS);
  168375. int isColFilter = (pCsr->pFilter->flags & FTS3_SEGMENT_COLUMN_FILTER);
  168376. int isPrefix = (pCsr->pFilter->flags & FTS3_SEGMENT_PREFIX);
  168377. int isScan = (pCsr->pFilter->flags & FTS3_SEGMENT_SCAN);
  168378. int isFirst = (pCsr->pFilter->flags & FTS3_SEGMENT_FIRST);
  168379. Fts3SegReader **apSegment = pCsr->apSegment;
  168380. int nSegment = pCsr->nSegment;
  168381. Fts3SegFilter *pFilter = pCsr->pFilter;
  168382. int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
  168383. p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
  168384. );
  168385. if( pCsr->nSegment==0 ) return SQLITE_OK;
  168386. do {
  168387. int nMerge;
  168388. int i;
  168389. /* Advance the first pCsr->nAdvance entries in the apSegment[] array
  168390. ** forward. Then sort the list in order of current term again.
  168391. */
  168392. for(i=0; i<pCsr->nAdvance; i++){
  168393. Fts3SegReader *pSeg = apSegment[i];
  168394. if( pSeg->bLookup ){
  168395. fts3SegReaderSetEof(pSeg);
  168396. }else{
  168397. rc = fts3SegReaderNext(p, pSeg, 0);
  168398. }
  168399. if( rc!=SQLITE_OK ) return rc;
  168400. }
  168401. fts3SegReaderSort(apSegment, nSegment, pCsr->nAdvance, fts3SegReaderCmp);
  168402. pCsr->nAdvance = 0;
  168403. /* If all the seg-readers are at EOF, we're finished. return SQLITE_OK. */
  168404. assert( rc==SQLITE_OK );
  168405. if( apSegment[0]->aNode==0 ) break;
  168406. pCsr->nTerm = apSegment[0]->nTerm;
  168407. pCsr->zTerm = apSegment[0]->zTerm;
  168408. /* If this is a prefix-search, and if the term that apSegment[0] points
  168409. ** to does not share a suffix with pFilter->zTerm/nTerm, then all
  168410. ** required callbacks have been made. In this case exit early.
  168411. **
  168412. ** Similarly, if this is a search for an exact match, and the first term
  168413. ** of segment apSegment[0] is not a match, exit early.
  168414. */
  168415. if( pFilter->zTerm && !isScan ){
  168416. if( pCsr->nTerm<pFilter->nTerm
  168417. || (!isPrefix && pCsr->nTerm>pFilter->nTerm)
  168418. || memcmp(pCsr->zTerm, pFilter->zTerm, pFilter->nTerm)
  168419. ){
  168420. break;
  168421. }
  168422. }
  168423. nMerge = 1;
  168424. while( nMerge<nSegment
  168425. && apSegment[nMerge]->aNode
  168426. && apSegment[nMerge]->nTerm==pCsr->nTerm
  168427. && 0==memcmp(pCsr->zTerm, apSegment[nMerge]->zTerm, pCsr->nTerm)
  168428. ){
  168429. nMerge++;
  168430. }
  168431. assert( isIgnoreEmpty || (isRequirePos && !isColFilter) );
  168432. if( nMerge==1
  168433. && !isIgnoreEmpty
  168434. && !isFirst
  168435. && (p->bDescIdx==0 || fts3SegReaderIsPending(apSegment[0])==0)
  168436. ){
  168437. pCsr->nDoclist = apSegment[0]->nDoclist;
  168438. if( fts3SegReaderIsPending(apSegment[0]) ){
  168439. rc = fts3MsrBufferData(pCsr, apSegment[0]->aDoclist, pCsr->nDoclist);
  168440. pCsr->aDoclist = pCsr->aBuffer;
  168441. }else{
  168442. pCsr->aDoclist = apSegment[0]->aDoclist;
  168443. }
  168444. if( rc==SQLITE_OK ) rc = SQLITE_ROW;
  168445. }else{
  168446. int nDoclist = 0; /* Size of doclist */
  168447. sqlite3_int64 iPrev = 0; /* Previous docid stored in doclist */
  168448. /* The current term of the first nMerge entries in the array
  168449. ** of Fts3SegReader objects is the same. The doclists must be merged
  168450. ** and a single term returned with the merged doclist.
  168451. */
  168452. for(i=0; i<nMerge; i++){
  168453. fts3SegReaderFirstDocid(p, apSegment[i]);
  168454. }
  168455. fts3SegReaderSort(apSegment, nMerge, nMerge, xCmp);
  168456. while( apSegment[0]->pOffsetList ){
  168457. int j; /* Number of segments that share a docid */
  168458. char *pList = 0;
  168459. int nList = 0;
  168460. int nByte;
  168461. sqlite3_int64 iDocid = apSegment[0]->iDocid;
  168462. fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
  168463. j = 1;
  168464. while( j<nMerge
  168465. && apSegment[j]->pOffsetList
  168466. && apSegment[j]->iDocid==iDocid
  168467. ){
  168468. fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
  168469. j++;
  168470. }
  168471. if( isColFilter ){
  168472. fts3ColumnFilter(pFilter->iCol, 0, &pList, &nList);
  168473. }
  168474. if( !isIgnoreEmpty || nList>0 ){
  168475. /* Calculate the 'docid' delta value to write into the merged
  168476. ** doclist. */
  168477. sqlite3_int64 iDelta;
  168478. if( p->bDescIdx && nDoclist>0 ){
  168479. if( iPrev<=iDocid ) return FTS_CORRUPT_VTAB;
  168480. iDelta = (i64)((u64)iPrev - (u64)iDocid);
  168481. }else{
  168482. if( nDoclist>0 && iPrev>=iDocid ) return FTS_CORRUPT_VTAB;
  168483. iDelta = (i64)((u64)iDocid - (u64)iPrev);
  168484. }
  168485. nByte = sqlite3Fts3VarintLen(iDelta) + (isRequirePos?nList+1:0);
  168486. if( nDoclist+nByte>pCsr->nBuffer ){
  168487. char *aNew;
  168488. pCsr->nBuffer = (nDoclist+nByte)*2;
  168489. aNew = sqlite3_realloc(pCsr->aBuffer, pCsr->nBuffer);
  168490. if( !aNew ){
  168491. return SQLITE_NOMEM;
  168492. }
  168493. pCsr->aBuffer = aNew;
  168494. }
  168495. if( isFirst ){
  168496. char *a = &pCsr->aBuffer[nDoclist];
  168497. int nWrite;
  168498. nWrite = sqlite3Fts3FirstFilter(iDelta, pList, nList, a);
  168499. if( nWrite ){
  168500. iPrev = iDocid;
  168501. nDoclist += nWrite;
  168502. }
  168503. }else{
  168504. nDoclist += sqlite3Fts3PutVarint(&pCsr->aBuffer[nDoclist], iDelta);
  168505. iPrev = iDocid;
  168506. if( isRequirePos ){
  168507. memcpy(&pCsr->aBuffer[nDoclist], pList, nList);
  168508. nDoclist += nList;
  168509. pCsr->aBuffer[nDoclist++] = '\0';
  168510. }
  168511. }
  168512. }
  168513. fts3SegReaderSort(apSegment, nMerge, j, xCmp);
  168514. }
  168515. if( nDoclist>0 ){
  168516. pCsr->aDoclist = pCsr->aBuffer;
  168517. pCsr->nDoclist = nDoclist;
  168518. rc = SQLITE_ROW;
  168519. }
  168520. }
  168521. pCsr->nAdvance = nMerge;
  168522. }while( rc==SQLITE_OK );
  168523. return rc;
  168524. }
  168525. SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(
  168526. Fts3MultiSegReader *pCsr /* Cursor object */
  168527. ){
  168528. if( pCsr ){
  168529. int i;
  168530. for(i=0; i<pCsr->nSegment; i++){
  168531. sqlite3Fts3SegReaderFree(pCsr->apSegment[i]);
  168532. }
  168533. sqlite3_free(pCsr->apSegment);
  168534. sqlite3_free(pCsr->aBuffer);
  168535. pCsr->nSegment = 0;
  168536. pCsr->apSegment = 0;
  168537. pCsr->aBuffer = 0;
  168538. }
  168539. }
  168540. /*
  168541. ** Decode the "end_block" field, selected by column iCol of the SELECT
  168542. ** statement passed as the first argument.
  168543. **
  168544. ** The "end_block" field may contain either an integer, or a text field
  168545. ** containing the text representation of two non-negative integers separated
  168546. ** by one or more space (0x20) characters. In the first case, set *piEndBlock
  168547. ** to the integer value and *pnByte to zero before returning. In the second,
  168548. ** set *piEndBlock to the first value and *pnByte to the second.
  168549. */
  168550. static void fts3ReadEndBlockField(
  168551. sqlite3_stmt *pStmt,
  168552. int iCol,
  168553. i64 *piEndBlock,
  168554. i64 *pnByte
  168555. ){
  168556. const unsigned char *zText = sqlite3_column_text(pStmt, iCol);
  168557. if( zText ){
  168558. int i;
  168559. int iMul = 1;
  168560. u64 iVal = 0;
  168561. for(i=0; zText[i]>='0' && zText[i]<='9'; i++){
  168562. iVal = iVal*10 + (zText[i] - '0');
  168563. }
  168564. *piEndBlock = (i64)iVal;
  168565. while( zText[i]==' ' ) i++;
  168566. iVal = 0;
  168567. if( zText[i]=='-' ){
  168568. i++;
  168569. iMul = -1;
  168570. }
  168571. for(/* no-op */; zText[i]>='0' && zText[i]<='9'; i++){
  168572. iVal = iVal*10 + (zText[i] - '0');
  168573. }
  168574. *pnByte = ((i64)iVal * (i64)iMul);
  168575. }
  168576. }
  168577. /*
  168578. ** A segment of size nByte bytes has just been written to absolute level
  168579. ** iAbsLevel. Promote any segments that should be promoted as a result.
  168580. */
  168581. static int fts3PromoteSegments(
  168582. Fts3Table *p, /* FTS table handle */
  168583. sqlite3_int64 iAbsLevel, /* Absolute level just updated */
  168584. sqlite3_int64 nByte /* Size of new segment at iAbsLevel */
  168585. ){
  168586. int rc = SQLITE_OK;
  168587. sqlite3_stmt *pRange;
  168588. rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE2, &pRange, 0);
  168589. if( rc==SQLITE_OK ){
  168590. int bOk = 0;
  168591. i64 iLast = (iAbsLevel/FTS3_SEGDIR_MAXLEVEL + 1) * FTS3_SEGDIR_MAXLEVEL - 1;
  168592. i64 nLimit = (nByte*3)/2;
  168593. /* Loop through all entries in the %_segdir table corresponding to
  168594. ** segments in this index on levels greater than iAbsLevel. If there is
  168595. ** at least one such segment, and it is possible to determine that all
  168596. ** such segments are smaller than nLimit bytes in size, they will be
  168597. ** promoted to level iAbsLevel. */
  168598. sqlite3_bind_int64(pRange, 1, iAbsLevel+1);
  168599. sqlite3_bind_int64(pRange, 2, iLast);
  168600. while( SQLITE_ROW==sqlite3_step(pRange) ){
  168601. i64 nSize = 0, dummy;
  168602. fts3ReadEndBlockField(pRange, 2, &dummy, &nSize);
  168603. if( nSize<=0 || nSize>nLimit ){
  168604. /* If nSize==0, then the %_segdir.end_block field does not not
  168605. ** contain a size value. This happens if it was written by an
  168606. ** old version of FTS. In this case it is not possible to determine
  168607. ** the size of the segment, and so segment promotion does not
  168608. ** take place. */
  168609. bOk = 0;
  168610. break;
  168611. }
  168612. bOk = 1;
  168613. }
  168614. rc = sqlite3_reset(pRange);
  168615. if( bOk ){
  168616. int iIdx = 0;
  168617. sqlite3_stmt *pUpdate1 = 0;
  168618. sqlite3_stmt *pUpdate2 = 0;
  168619. if( rc==SQLITE_OK ){
  168620. rc = fts3SqlStmt(p, SQL_UPDATE_LEVEL_IDX, &pUpdate1, 0);
  168621. }
  168622. if( rc==SQLITE_OK ){
  168623. rc = fts3SqlStmt(p, SQL_UPDATE_LEVEL, &pUpdate2, 0);
  168624. }
  168625. if( rc==SQLITE_OK ){
  168626. /* Loop through all %_segdir entries for segments in this index with
  168627. ** levels equal to or greater than iAbsLevel. As each entry is visited,
  168628. ** updated it to set (level = -1) and (idx = N), where N is 0 for the
  168629. ** oldest segment in the range, 1 for the next oldest, and so on.
  168630. **
  168631. ** In other words, move all segments being promoted to level -1,
  168632. ** setting the "idx" fields as appropriate to keep them in the same
  168633. ** order. The contents of level -1 (which is never used, except
  168634. ** transiently here), will be moved back to level iAbsLevel below. */
  168635. sqlite3_bind_int64(pRange, 1, iAbsLevel);
  168636. while( SQLITE_ROW==sqlite3_step(pRange) ){
  168637. sqlite3_bind_int(pUpdate1, 1, iIdx++);
  168638. sqlite3_bind_int(pUpdate1, 2, sqlite3_column_int(pRange, 0));
  168639. sqlite3_bind_int(pUpdate1, 3, sqlite3_column_int(pRange, 1));
  168640. sqlite3_step(pUpdate1);
  168641. rc = sqlite3_reset(pUpdate1);
  168642. if( rc!=SQLITE_OK ){
  168643. sqlite3_reset(pRange);
  168644. break;
  168645. }
  168646. }
  168647. }
  168648. if( rc==SQLITE_OK ){
  168649. rc = sqlite3_reset(pRange);
  168650. }
  168651. /* Move level -1 to level iAbsLevel */
  168652. if( rc==SQLITE_OK ){
  168653. sqlite3_bind_int64(pUpdate2, 1, iAbsLevel);
  168654. sqlite3_step(pUpdate2);
  168655. rc = sqlite3_reset(pUpdate2);
  168656. }
  168657. }
  168658. }
  168659. return rc;
  168660. }
  168661. /*
  168662. ** Merge all level iLevel segments in the database into a single
  168663. ** iLevel+1 segment. Or, if iLevel<0, merge all segments into a
  168664. ** single segment with a level equal to the numerically largest level
  168665. ** currently present in the database.
  168666. **
  168667. ** If this function is called with iLevel<0, but there is only one
  168668. ** segment in the database, SQLITE_DONE is returned immediately.
  168669. ** Otherwise, if successful, SQLITE_OK is returned. If an error occurs,
  168670. ** an SQLite error code is returned.
  168671. */
  168672. static int fts3SegmentMerge(
  168673. Fts3Table *p,
  168674. int iLangid, /* Language id to merge */
  168675. int iIndex, /* Index in p->aIndex[] to merge */
  168676. int iLevel /* Level to merge */
  168677. ){
  168678. int rc; /* Return code */
  168679. int iIdx = 0; /* Index of new segment */
  168680. sqlite3_int64 iNewLevel = 0; /* Level/index to create new segment at */
  168681. SegmentWriter *pWriter = 0; /* Used to write the new, merged, segment */
  168682. Fts3SegFilter filter; /* Segment term filter condition */
  168683. Fts3MultiSegReader csr; /* Cursor to iterate through level(s) */
  168684. int bIgnoreEmpty = 0; /* True to ignore empty segments */
  168685. i64 iMaxLevel = 0; /* Max level number for this index/langid */
  168686. assert( iLevel==FTS3_SEGCURSOR_ALL
  168687. || iLevel==FTS3_SEGCURSOR_PENDING
  168688. || iLevel>=0
  168689. );
  168690. assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
  168691. assert( iIndex>=0 && iIndex<p->nIndex );
  168692. rc = sqlite3Fts3SegReaderCursor(p, iLangid, iIndex, iLevel, 0, 0, 1, 0, &csr);
  168693. if( rc!=SQLITE_OK || csr.nSegment==0 ) goto finished;
  168694. if( iLevel!=FTS3_SEGCURSOR_PENDING ){
  168695. rc = fts3SegmentMaxLevel(p, iLangid, iIndex, &iMaxLevel);
  168696. if( rc!=SQLITE_OK ) goto finished;
  168697. }
  168698. if( iLevel==FTS3_SEGCURSOR_ALL ){
  168699. /* This call is to merge all segments in the database to a single
  168700. ** segment. The level of the new segment is equal to the numerically
  168701. ** greatest segment level currently present in the database for this
  168702. ** index. The idx of the new segment is always 0. */
  168703. if( csr.nSegment==1 && 0==fts3SegReaderIsPending(csr.apSegment[0]) ){
  168704. rc = SQLITE_DONE;
  168705. goto finished;
  168706. }
  168707. iNewLevel = iMaxLevel;
  168708. bIgnoreEmpty = 1;
  168709. }else{
  168710. /* This call is to merge all segments at level iLevel. find the next
  168711. ** available segment index at level iLevel+1. The call to
  168712. ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to
  168713. ** a single iLevel+2 segment if necessary. */
  168714. assert( FTS3_SEGCURSOR_PENDING==-1 );
  168715. iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, iLevel+1);
  168716. rc = fts3AllocateSegdirIdx(p, iLangid, iIndex, iLevel+1, &iIdx);
  168717. bIgnoreEmpty = (iLevel!=FTS3_SEGCURSOR_PENDING) && (iNewLevel>iMaxLevel);
  168718. }
  168719. if( rc!=SQLITE_OK ) goto finished;
  168720. assert( csr.nSegment>0 );
  168721. assert_fts3_nc( iNewLevel>=getAbsoluteLevel(p, iLangid, iIndex, 0) );
  168722. assert_fts3_nc(
  168723. iNewLevel<getAbsoluteLevel(p, iLangid, iIndex,FTS3_SEGDIR_MAXLEVEL)
  168724. );
  168725. memset(&filter, 0, sizeof(Fts3SegFilter));
  168726. filter.flags = FTS3_SEGMENT_REQUIRE_POS;
  168727. filter.flags |= (bIgnoreEmpty ? FTS3_SEGMENT_IGNORE_EMPTY : 0);
  168728. rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
  168729. while( SQLITE_OK==rc ){
  168730. rc = sqlite3Fts3SegReaderStep(p, &csr);
  168731. if( rc!=SQLITE_ROW ) break;
  168732. rc = fts3SegWriterAdd(p, &pWriter, 1,
  168733. csr.zTerm, csr.nTerm, csr.aDoclist, csr.nDoclist);
  168734. }
  168735. if( rc!=SQLITE_OK ) goto finished;
  168736. assert_fts3_nc( pWriter || bIgnoreEmpty );
  168737. if( iLevel!=FTS3_SEGCURSOR_PENDING ){
  168738. rc = fts3DeleteSegdir(
  168739. p, iLangid, iIndex, iLevel, csr.apSegment, csr.nSegment
  168740. );
  168741. if( rc!=SQLITE_OK ) goto finished;
  168742. }
  168743. if( pWriter ){
  168744. rc = fts3SegWriterFlush(p, pWriter, iNewLevel, iIdx);
  168745. if( rc==SQLITE_OK ){
  168746. if( iLevel==FTS3_SEGCURSOR_PENDING || iNewLevel<iMaxLevel ){
  168747. rc = fts3PromoteSegments(p, iNewLevel, pWriter->nLeafData);
  168748. }
  168749. }
  168750. }
  168751. finished:
  168752. fts3SegWriterFree(pWriter);
  168753. sqlite3Fts3SegReaderFinish(&csr);
  168754. return rc;
  168755. }
  168756. /*
  168757. ** Flush the contents of pendingTerms to level 0 segments.
  168758. */
  168759. SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *p){
  168760. int rc = SQLITE_OK;
  168761. int i;
  168762. for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
  168763. rc = fts3SegmentMerge(p, p->iPrevLangid, i, FTS3_SEGCURSOR_PENDING);
  168764. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  168765. }
  168766. sqlite3Fts3PendingTermsClear(p);
  168767. /* Determine the auto-incr-merge setting if unknown. If enabled,
  168768. ** estimate the number of leaf blocks of content to be written
  168769. */
  168770. if( rc==SQLITE_OK && p->bHasStat
  168771. && p->nAutoincrmerge==0xff && p->nLeafAdd>0
  168772. ){
  168773. sqlite3_stmt *pStmt = 0;
  168774. rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
  168775. if( rc==SQLITE_OK ){
  168776. sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
  168777. rc = sqlite3_step(pStmt);
  168778. if( rc==SQLITE_ROW ){
  168779. p->nAutoincrmerge = sqlite3_column_int(pStmt, 0);
  168780. if( p->nAutoincrmerge==1 ) p->nAutoincrmerge = 8;
  168781. }else if( rc==SQLITE_DONE ){
  168782. p->nAutoincrmerge = 0;
  168783. }
  168784. rc = sqlite3_reset(pStmt);
  168785. }
  168786. }
  168787. return rc;
  168788. }
  168789. /*
  168790. ** Encode N integers as varints into a blob.
  168791. */
  168792. static void fts3EncodeIntArray(
  168793. int N, /* The number of integers to encode */
  168794. u32 *a, /* The integer values */
  168795. char *zBuf, /* Write the BLOB here */
  168796. int *pNBuf /* Write number of bytes if zBuf[] used here */
  168797. ){
  168798. int i, j;
  168799. for(i=j=0; i<N; i++){
  168800. j += sqlite3Fts3PutVarint(&zBuf[j], (sqlite3_int64)a[i]);
  168801. }
  168802. *pNBuf = j;
  168803. }
  168804. /*
  168805. ** Decode a blob of varints into N integers
  168806. */
  168807. static void fts3DecodeIntArray(
  168808. int N, /* The number of integers to decode */
  168809. u32 *a, /* Write the integer values */
  168810. const char *zBuf, /* The BLOB containing the varints */
  168811. int nBuf /* size of the BLOB */
  168812. ){
  168813. int i = 0;
  168814. if( nBuf && (zBuf[nBuf-1]&0x80)==0 ){
  168815. int j;
  168816. for(i=j=0; i<N && j<nBuf; i++){
  168817. sqlite3_int64 x;
  168818. j += sqlite3Fts3GetVarint(&zBuf[j], &x);
  168819. a[i] = (u32)(x & 0xffffffff);
  168820. }
  168821. }
  168822. while( i<N ) a[i++] = 0;
  168823. }
  168824. /*
  168825. ** Insert the sizes (in tokens) for each column of the document
  168826. ** with docid equal to p->iPrevDocid. The sizes are encoded as
  168827. ** a blob of varints.
  168828. */
  168829. static void fts3InsertDocsize(
  168830. int *pRC, /* Result code */
  168831. Fts3Table *p, /* Table into which to insert */
  168832. u32 *aSz /* Sizes of each column, in tokens */
  168833. ){
  168834. char *pBlob; /* The BLOB encoding of the document size */
  168835. int nBlob; /* Number of bytes in the BLOB */
  168836. sqlite3_stmt *pStmt; /* Statement used to insert the encoding */
  168837. int rc; /* Result code from subfunctions */
  168838. if( *pRC ) return;
  168839. pBlob = sqlite3_malloc64( 10*(sqlite3_int64)p->nColumn );
  168840. if( pBlob==0 ){
  168841. *pRC = SQLITE_NOMEM;
  168842. return;
  168843. }
  168844. fts3EncodeIntArray(p->nColumn, aSz, pBlob, &nBlob);
  168845. rc = fts3SqlStmt(p, SQL_REPLACE_DOCSIZE, &pStmt, 0);
  168846. if( rc ){
  168847. sqlite3_free(pBlob);
  168848. *pRC = rc;
  168849. return;
  168850. }
  168851. sqlite3_bind_int64(pStmt, 1, p->iPrevDocid);
  168852. sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, sqlite3_free);
  168853. sqlite3_step(pStmt);
  168854. *pRC = sqlite3_reset(pStmt);
  168855. }
  168856. /*
  168857. ** Record 0 of the %_stat table contains a blob consisting of N varints,
  168858. ** where N is the number of user defined columns in the fts3 table plus
  168859. ** two. If nCol is the number of user defined columns, then values of the
  168860. ** varints are set as follows:
  168861. **
  168862. ** Varint 0: Total number of rows in the table.
  168863. **
  168864. ** Varint 1..nCol: For each column, the total number of tokens stored in
  168865. ** the column for all rows of the table.
  168866. **
  168867. ** Varint 1+nCol: The total size, in bytes, of all text values in all
  168868. ** columns of all rows of the table.
  168869. **
  168870. */
  168871. static void fts3UpdateDocTotals(
  168872. int *pRC, /* The result code */
  168873. Fts3Table *p, /* Table being updated */
  168874. u32 *aSzIns, /* Size increases */
  168875. u32 *aSzDel, /* Size decreases */
  168876. int nChng /* Change in the number of documents */
  168877. ){
  168878. char *pBlob; /* Storage for BLOB written into %_stat */
  168879. int nBlob; /* Size of BLOB written into %_stat */
  168880. u32 *a; /* Array of integers that becomes the BLOB */
  168881. sqlite3_stmt *pStmt; /* Statement for reading and writing */
  168882. int i; /* Loop counter */
  168883. int rc; /* Result code from subfunctions */
  168884. const int nStat = p->nColumn+2;
  168885. if( *pRC ) return;
  168886. a = sqlite3_malloc64( (sizeof(u32)+10)*(sqlite3_int64)nStat );
  168887. if( a==0 ){
  168888. *pRC = SQLITE_NOMEM;
  168889. return;
  168890. }
  168891. pBlob = (char*)&a[nStat];
  168892. rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
  168893. if( rc ){
  168894. sqlite3_free(a);
  168895. *pRC = rc;
  168896. return;
  168897. }
  168898. sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
  168899. if( sqlite3_step(pStmt)==SQLITE_ROW ){
  168900. fts3DecodeIntArray(nStat, a,
  168901. sqlite3_column_blob(pStmt, 0),
  168902. sqlite3_column_bytes(pStmt, 0));
  168903. }else{
  168904. memset(a, 0, sizeof(u32)*(nStat) );
  168905. }
  168906. rc = sqlite3_reset(pStmt);
  168907. if( rc!=SQLITE_OK ){
  168908. sqlite3_free(a);
  168909. *pRC = rc;
  168910. return;
  168911. }
  168912. if( nChng<0 && a[0]<(u32)(-nChng) ){
  168913. a[0] = 0;
  168914. }else{
  168915. a[0] += nChng;
  168916. }
  168917. for(i=0; i<p->nColumn+1; i++){
  168918. u32 x = a[i+1];
  168919. if( x+aSzIns[i] < aSzDel[i] ){
  168920. x = 0;
  168921. }else{
  168922. x = x + aSzIns[i] - aSzDel[i];
  168923. }
  168924. a[i+1] = x;
  168925. }
  168926. fts3EncodeIntArray(nStat, a, pBlob, &nBlob);
  168927. rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
  168928. if( rc ){
  168929. sqlite3_free(a);
  168930. *pRC = rc;
  168931. return;
  168932. }
  168933. sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
  168934. sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, SQLITE_STATIC);
  168935. sqlite3_step(pStmt);
  168936. *pRC = sqlite3_reset(pStmt);
  168937. sqlite3_bind_null(pStmt, 2);
  168938. sqlite3_free(a);
  168939. }
  168940. /*
  168941. ** Merge the entire database so that there is one segment for each
  168942. ** iIndex/iLangid combination.
  168943. */
  168944. static int fts3DoOptimize(Fts3Table *p, int bReturnDone){
  168945. int bSeenDone = 0;
  168946. int rc;
  168947. sqlite3_stmt *pAllLangid = 0;
  168948. rc = sqlite3Fts3PendingTermsFlush(p);
  168949. if( rc==SQLITE_OK ){
  168950. rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
  168951. }
  168952. if( rc==SQLITE_OK ){
  168953. int rc2;
  168954. sqlite3_bind_int(pAllLangid, 1, p->iPrevLangid);
  168955. sqlite3_bind_int(pAllLangid, 2, p->nIndex);
  168956. while( sqlite3_step(pAllLangid)==SQLITE_ROW ){
  168957. int i;
  168958. int iLangid = sqlite3_column_int(pAllLangid, 0);
  168959. for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
  168960. rc = fts3SegmentMerge(p, iLangid, i, FTS3_SEGCURSOR_ALL);
  168961. if( rc==SQLITE_DONE ){
  168962. bSeenDone = 1;
  168963. rc = SQLITE_OK;
  168964. }
  168965. }
  168966. }
  168967. rc2 = sqlite3_reset(pAllLangid);
  168968. if( rc==SQLITE_OK ) rc = rc2;
  168969. }
  168970. sqlite3Fts3SegmentsClose(p);
  168971. return (rc==SQLITE_OK && bReturnDone && bSeenDone) ? SQLITE_DONE : rc;
  168972. }
  168973. /*
  168974. ** This function is called when the user executes the following statement:
  168975. **
  168976. ** INSERT INTO <tbl>(<tbl>) VALUES('rebuild');
  168977. **
  168978. ** The entire FTS index is discarded and rebuilt. If the table is one
  168979. ** created using the content=xxx option, then the new index is based on
  168980. ** the current contents of the xxx table. Otherwise, it is rebuilt based
  168981. ** on the contents of the %_content table.
  168982. */
  168983. static int fts3DoRebuild(Fts3Table *p){
  168984. int rc; /* Return Code */
  168985. rc = fts3DeleteAll(p, 0);
  168986. if( rc==SQLITE_OK ){
  168987. u32 *aSz = 0;
  168988. u32 *aSzIns = 0;
  168989. u32 *aSzDel = 0;
  168990. sqlite3_stmt *pStmt = 0;
  168991. int nEntry = 0;
  168992. /* Compose and prepare an SQL statement to loop through the content table */
  168993. char *zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
  168994. if( !zSql ){
  168995. rc = SQLITE_NOMEM;
  168996. }else{
  168997. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  168998. sqlite3_free(zSql);
  168999. }
  169000. if( rc==SQLITE_OK ){
  169001. sqlite3_int64 nByte = sizeof(u32) * ((sqlite3_int64)p->nColumn+1)*3;
  169002. aSz = (u32 *)sqlite3_malloc64(nByte);
  169003. if( aSz==0 ){
  169004. rc = SQLITE_NOMEM;
  169005. }else{
  169006. memset(aSz, 0, nByte);
  169007. aSzIns = &aSz[p->nColumn+1];
  169008. aSzDel = &aSzIns[p->nColumn+1];
  169009. }
  169010. }
  169011. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  169012. int iCol;
  169013. int iLangid = langidFromSelect(p, pStmt);
  169014. rc = fts3PendingTermsDocid(p, 0, iLangid, sqlite3_column_int64(pStmt, 0));
  169015. memset(aSz, 0, sizeof(aSz[0]) * (p->nColumn+1));
  169016. for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
  169017. if( p->abNotindexed[iCol]==0 ){
  169018. const char *z = (const char *) sqlite3_column_text(pStmt, iCol+1);
  169019. rc = fts3PendingTermsAdd(p, iLangid, z, iCol, &aSz[iCol]);
  169020. aSz[p->nColumn] += sqlite3_column_bytes(pStmt, iCol+1);
  169021. }
  169022. }
  169023. if( p->bHasDocsize ){
  169024. fts3InsertDocsize(&rc, p, aSz);
  169025. }
  169026. if( rc!=SQLITE_OK ){
  169027. sqlite3_finalize(pStmt);
  169028. pStmt = 0;
  169029. }else{
  169030. nEntry++;
  169031. for(iCol=0; iCol<=p->nColumn; iCol++){
  169032. aSzIns[iCol] += aSz[iCol];
  169033. }
  169034. }
  169035. }
  169036. if( p->bFts4 ){
  169037. fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nEntry);
  169038. }
  169039. sqlite3_free(aSz);
  169040. if( pStmt ){
  169041. int rc2 = sqlite3_finalize(pStmt);
  169042. if( rc==SQLITE_OK ){
  169043. rc = rc2;
  169044. }
  169045. }
  169046. }
  169047. return rc;
  169048. }
  169049. /*
  169050. ** This function opens a cursor used to read the input data for an
  169051. ** incremental merge operation. Specifically, it opens a cursor to scan
  169052. ** the oldest nSeg segments (idx=0 through idx=(nSeg-1)) in absolute
  169053. ** level iAbsLevel.
  169054. */
  169055. static int fts3IncrmergeCsr(
  169056. Fts3Table *p, /* FTS3 table handle */
  169057. sqlite3_int64 iAbsLevel, /* Absolute level to open */
  169058. int nSeg, /* Number of segments to merge */
  169059. Fts3MultiSegReader *pCsr /* Cursor object to populate */
  169060. ){
  169061. int rc; /* Return Code */
  169062. sqlite3_stmt *pStmt = 0; /* Statement used to read %_segdir entry */
  169063. sqlite3_int64 nByte; /* Bytes allocated at pCsr->apSegment[] */
  169064. /* Allocate space for the Fts3MultiSegReader.aCsr[] array */
  169065. memset(pCsr, 0, sizeof(*pCsr));
  169066. nByte = sizeof(Fts3SegReader *) * nSeg;
  169067. pCsr->apSegment = (Fts3SegReader **)sqlite3_malloc64(nByte);
  169068. if( pCsr->apSegment==0 ){
  169069. rc = SQLITE_NOMEM;
  169070. }else{
  169071. memset(pCsr->apSegment, 0, nByte);
  169072. rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
  169073. }
  169074. if( rc==SQLITE_OK ){
  169075. int i;
  169076. int rc2;
  169077. sqlite3_bind_int64(pStmt, 1, iAbsLevel);
  169078. assert( pCsr->nSegment==0 );
  169079. for(i=0; rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW && i<nSeg; i++){
  169080. rc = sqlite3Fts3SegReaderNew(i, 0,
  169081. sqlite3_column_int64(pStmt, 1), /* segdir.start_block */
  169082. sqlite3_column_int64(pStmt, 2), /* segdir.leaves_end_block */
  169083. sqlite3_column_int64(pStmt, 3), /* segdir.end_block */
  169084. sqlite3_column_blob(pStmt, 4), /* segdir.root */
  169085. sqlite3_column_bytes(pStmt, 4), /* segdir.root */
  169086. &pCsr->apSegment[i]
  169087. );
  169088. pCsr->nSegment++;
  169089. }
  169090. rc2 = sqlite3_reset(pStmt);
  169091. if( rc==SQLITE_OK ) rc = rc2;
  169092. }
  169093. return rc;
  169094. }
  169095. typedef struct IncrmergeWriter IncrmergeWriter;
  169096. typedef struct NodeWriter NodeWriter;
  169097. typedef struct Blob Blob;
  169098. typedef struct NodeReader NodeReader;
  169099. /*
  169100. ** An instance of the following structure is used as a dynamic buffer
  169101. ** to build up nodes or other blobs of data in.
  169102. **
  169103. ** The function blobGrowBuffer() is used to extend the allocation.
  169104. */
  169105. struct Blob {
  169106. char *a; /* Pointer to allocation */
  169107. int n; /* Number of valid bytes of data in a[] */
  169108. int nAlloc; /* Allocated size of a[] (nAlloc>=n) */
  169109. };
  169110. /*
  169111. ** This structure is used to build up buffers containing segment b-tree
  169112. ** nodes (blocks).
  169113. */
  169114. struct NodeWriter {
  169115. sqlite3_int64 iBlock; /* Current block id */
  169116. Blob key; /* Last key written to the current block */
  169117. Blob block; /* Current block image */
  169118. };
  169119. /*
  169120. ** An object of this type contains the state required to create or append
  169121. ** to an appendable b-tree segment.
  169122. */
  169123. struct IncrmergeWriter {
  169124. int nLeafEst; /* Space allocated for leaf blocks */
  169125. int nWork; /* Number of leaf pages flushed */
  169126. sqlite3_int64 iAbsLevel; /* Absolute level of input segments */
  169127. int iIdx; /* Index of *output* segment in iAbsLevel+1 */
  169128. sqlite3_int64 iStart; /* Block number of first allocated block */
  169129. sqlite3_int64 iEnd; /* Block number of last allocated block */
  169130. sqlite3_int64 nLeafData; /* Bytes of leaf page data so far */
  169131. u8 bNoLeafData; /* If true, store 0 for segment size */
  169132. NodeWriter aNodeWriter[FTS_MAX_APPENDABLE_HEIGHT];
  169133. };
  169134. /*
  169135. ** An object of the following type is used to read data from a single
  169136. ** FTS segment node. See the following functions:
  169137. **
  169138. ** nodeReaderInit()
  169139. ** nodeReaderNext()
  169140. ** nodeReaderRelease()
  169141. */
  169142. struct NodeReader {
  169143. const char *aNode;
  169144. int nNode;
  169145. int iOff; /* Current offset within aNode[] */
  169146. /* Output variables. Containing the current node entry. */
  169147. sqlite3_int64 iChild; /* Pointer to child node */
  169148. Blob term; /* Current term */
  169149. const char *aDoclist; /* Pointer to doclist */
  169150. int nDoclist; /* Size of doclist in bytes */
  169151. };
  169152. /*
  169153. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  169154. ** Otherwise, if the allocation at pBlob->a is not already at least nMin
  169155. ** bytes in size, extend (realloc) it to be so.
  169156. **
  169157. ** If an OOM error occurs, set *pRc to SQLITE_NOMEM and leave pBlob->a
  169158. ** unmodified. Otherwise, if the allocation succeeds, update pBlob->nAlloc
  169159. ** to reflect the new size of the pBlob->a[] buffer.
  169160. */
  169161. static void blobGrowBuffer(Blob *pBlob, int nMin, int *pRc){
  169162. if( *pRc==SQLITE_OK && nMin>pBlob->nAlloc ){
  169163. int nAlloc = nMin;
  169164. char *a = (char *)sqlite3_realloc(pBlob->a, nAlloc);
  169165. if( a ){
  169166. pBlob->nAlloc = nAlloc;
  169167. pBlob->a = a;
  169168. }else{
  169169. *pRc = SQLITE_NOMEM;
  169170. }
  169171. }
  169172. }
  169173. /*
  169174. ** Attempt to advance the node-reader object passed as the first argument to
  169175. ** the next entry on the node.
  169176. **
  169177. ** Return an error code if an error occurs (SQLITE_NOMEM is possible).
  169178. ** Otherwise return SQLITE_OK. If there is no next entry on the node
  169179. ** (e.g. because the current entry is the last) set NodeReader->aNode to
  169180. ** NULL to indicate EOF. Otherwise, populate the NodeReader structure output
  169181. ** variables for the new entry.
  169182. */
  169183. static int nodeReaderNext(NodeReader *p){
  169184. int bFirst = (p->term.n==0); /* True for first term on the node */
  169185. int nPrefix = 0; /* Bytes to copy from previous term */
  169186. int nSuffix = 0; /* Bytes to append to the prefix */
  169187. int rc = SQLITE_OK; /* Return code */
  169188. assert( p->aNode );
  169189. if( p->iChild && bFirst==0 ) p->iChild++;
  169190. if( p->iOff>=p->nNode ){
  169191. /* EOF */
  169192. p->aNode = 0;
  169193. }else{
  169194. if( bFirst==0 ){
  169195. p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nPrefix);
  169196. }
  169197. p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nSuffix);
  169198. if( nPrefix>p->term.n || nSuffix>p->nNode-p->iOff || nSuffix==0 ){
  169199. return FTS_CORRUPT_VTAB;
  169200. }
  169201. blobGrowBuffer(&p->term, nPrefix+nSuffix, &rc);
  169202. if( rc==SQLITE_OK ){
  169203. memcpy(&p->term.a[nPrefix], &p->aNode[p->iOff], nSuffix);
  169204. p->term.n = nPrefix+nSuffix;
  169205. p->iOff += nSuffix;
  169206. if( p->iChild==0 ){
  169207. p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &p->nDoclist);
  169208. if( (p->nNode-p->iOff)<p->nDoclist ){
  169209. return FTS_CORRUPT_VTAB;
  169210. }
  169211. p->aDoclist = &p->aNode[p->iOff];
  169212. p->iOff += p->nDoclist;
  169213. }
  169214. }
  169215. }
  169216. assert_fts3_nc( p->iOff<=p->nNode );
  169217. return rc;
  169218. }
  169219. /*
  169220. ** Release all dynamic resources held by node-reader object *p.
  169221. */
  169222. static void nodeReaderRelease(NodeReader *p){
  169223. sqlite3_free(p->term.a);
  169224. }
  169225. /*
  169226. ** Initialize a node-reader object to read the node in buffer aNode/nNode.
  169227. **
  169228. ** If successful, SQLITE_OK is returned and the NodeReader object set to
  169229. ** point to the first entry on the node (if any). Otherwise, an SQLite
  169230. ** error code is returned.
  169231. */
  169232. static int nodeReaderInit(NodeReader *p, const char *aNode, int nNode){
  169233. memset(p, 0, sizeof(NodeReader));
  169234. p->aNode = aNode;
  169235. p->nNode = nNode;
  169236. /* Figure out if this is a leaf or an internal node. */
  169237. if( aNode && aNode[0] ){
  169238. /* An internal node. */
  169239. p->iOff = 1 + sqlite3Fts3GetVarint(&p->aNode[1], &p->iChild);
  169240. }else{
  169241. p->iOff = 1;
  169242. }
  169243. return aNode ? nodeReaderNext(p) : SQLITE_OK;
  169244. }
  169245. /*
  169246. ** This function is called while writing an FTS segment each time a leaf o
  169247. ** node is finished and written to disk. The key (zTerm/nTerm) is guaranteed
  169248. ** to be greater than the largest key on the node just written, but smaller
  169249. ** than or equal to the first key that will be written to the next leaf
  169250. ** node.
  169251. **
  169252. ** The block id of the leaf node just written to disk may be found in
  169253. ** (pWriter->aNodeWriter[0].iBlock) when this function is called.
  169254. */
  169255. static int fts3IncrmergePush(
  169256. Fts3Table *p, /* Fts3 table handle */
  169257. IncrmergeWriter *pWriter, /* Writer object */
  169258. const char *zTerm, /* Term to write to internal node */
  169259. int nTerm /* Bytes at zTerm */
  169260. ){
  169261. sqlite3_int64 iPtr = pWriter->aNodeWriter[0].iBlock;
  169262. int iLayer;
  169263. assert( nTerm>0 );
  169264. for(iLayer=1; ALWAYS(iLayer<FTS_MAX_APPENDABLE_HEIGHT); iLayer++){
  169265. sqlite3_int64 iNextPtr = 0;
  169266. NodeWriter *pNode = &pWriter->aNodeWriter[iLayer];
  169267. int rc = SQLITE_OK;
  169268. int nPrefix;
  169269. int nSuffix;
  169270. int nSpace;
  169271. /* Figure out how much space the key will consume if it is written to
  169272. ** the current node of layer iLayer. Due to the prefix compression,
  169273. ** the space required changes depending on which node the key is to
  169274. ** be added to. */
  169275. nPrefix = fts3PrefixCompress(pNode->key.a, pNode->key.n, zTerm, nTerm);
  169276. nSuffix = nTerm - nPrefix;
  169277. if(nSuffix<=0 ) return FTS_CORRUPT_VTAB;
  169278. nSpace = sqlite3Fts3VarintLen(nPrefix);
  169279. nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
  169280. if( pNode->key.n==0 || (pNode->block.n + nSpace)<=p->nNodeSize ){
  169281. /* If the current node of layer iLayer contains zero keys, or if adding
  169282. ** the key to it will not cause it to grow to larger than nNodeSize
  169283. ** bytes in size, write the key here. */
  169284. Blob *pBlk = &pNode->block;
  169285. if( pBlk->n==0 ){
  169286. blobGrowBuffer(pBlk, p->nNodeSize, &rc);
  169287. if( rc==SQLITE_OK ){
  169288. pBlk->a[0] = (char)iLayer;
  169289. pBlk->n = 1 + sqlite3Fts3PutVarint(&pBlk->a[1], iPtr);
  169290. }
  169291. }
  169292. blobGrowBuffer(pBlk, pBlk->n + nSpace, &rc);
  169293. blobGrowBuffer(&pNode->key, nTerm, &rc);
  169294. if( rc==SQLITE_OK ){
  169295. if( pNode->key.n ){
  169296. pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nPrefix);
  169297. }
  169298. pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nSuffix);
  169299. memcpy(&pBlk->a[pBlk->n], &zTerm[nPrefix], nSuffix);
  169300. pBlk->n += nSuffix;
  169301. memcpy(pNode->key.a, zTerm, nTerm);
  169302. pNode->key.n = nTerm;
  169303. }
  169304. }else{
  169305. /* Otherwise, flush the current node of layer iLayer to disk.
  169306. ** Then allocate a new, empty sibling node. The key will be written
  169307. ** into the parent of this node. */
  169308. rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
  169309. assert( pNode->block.nAlloc>=p->nNodeSize );
  169310. pNode->block.a[0] = (char)iLayer;
  169311. pNode->block.n = 1 + sqlite3Fts3PutVarint(&pNode->block.a[1], iPtr+1);
  169312. iNextPtr = pNode->iBlock;
  169313. pNode->iBlock++;
  169314. pNode->key.n = 0;
  169315. }
  169316. if( rc!=SQLITE_OK || iNextPtr==0 ) return rc;
  169317. iPtr = iNextPtr;
  169318. }
  169319. assert( 0 );
  169320. return 0;
  169321. }
  169322. /*
  169323. ** Append a term and (optionally) doclist to the FTS segment node currently
  169324. ** stored in blob *pNode. The node need not contain any terms, but the
  169325. ** header must be written before this function is called.
  169326. **
  169327. ** A node header is a single 0x00 byte for a leaf node, or a height varint
  169328. ** followed by the left-hand-child varint for an internal node.
  169329. **
  169330. ** The term to be appended is passed via arguments zTerm/nTerm. For a
  169331. ** leaf node, the doclist is passed as aDoclist/nDoclist. For an internal
  169332. ** node, both aDoclist and nDoclist must be passed 0.
  169333. **
  169334. ** If the size of the value in blob pPrev is zero, then this is the first
  169335. ** term written to the node. Otherwise, pPrev contains a copy of the
  169336. ** previous term. Before this function returns, it is updated to contain a
  169337. ** copy of zTerm/nTerm.
  169338. **
  169339. ** It is assumed that the buffer associated with pNode is already large
  169340. ** enough to accommodate the new entry. The buffer associated with pPrev
  169341. ** is extended by this function if requrired.
  169342. **
  169343. ** If an error (i.e. OOM condition) occurs, an SQLite error code is
  169344. ** returned. Otherwise, SQLITE_OK.
  169345. */
  169346. static int fts3AppendToNode(
  169347. Blob *pNode, /* Current node image to append to */
  169348. Blob *pPrev, /* Buffer containing previous term written */
  169349. const char *zTerm, /* New term to write */
  169350. int nTerm, /* Size of zTerm in bytes */
  169351. const char *aDoclist, /* Doclist (or NULL) to write */
  169352. int nDoclist /* Size of aDoclist in bytes */
  169353. ){
  169354. int rc = SQLITE_OK; /* Return code */
  169355. int bFirst = (pPrev->n==0); /* True if this is the first term written */
  169356. int nPrefix; /* Size of term prefix in bytes */
  169357. int nSuffix; /* Size of term suffix in bytes */
  169358. /* Node must have already been started. There must be a doclist for a
  169359. ** leaf node, and there must not be a doclist for an internal node. */
  169360. assert( pNode->n>0 );
  169361. assert_fts3_nc( (pNode->a[0]=='\0')==(aDoclist!=0) );
  169362. blobGrowBuffer(pPrev, nTerm, &rc);
  169363. if( rc!=SQLITE_OK ) return rc;
  169364. nPrefix = fts3PrefixCompress(pPrev->a, pPrev->n, zTerm, nTerm);
  169365. nSuffix = nTerm - nPrefix;
  169366. if( nSuffix<=0 ) return FTS_CORRUPT_VTAB;
  169367. memcpy(pPrev->a, zTerm, nTerm);
  169368. pPrev->n = nTerm;
  169369. if( bFirst==0 ){
  169370. pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nPrefix);
  169371. }
  169372. pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nSuffix);
  169373. memcpy(&pNode->a[pNode->n], &zTerm[nPrefix], nSuffix);
  169374. pNode->n += nSuffix;
  169375. if( aDoclist ){
  169376. pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nDoclist);
  169377. memcpy(&pNode->a[pNode->n], aDoclist, nDoclist);
  169378. pNode->n += nDoclist;
  169379. }
  169380. assert( pNode->n<=pNode->nAlloc );
  169381. return SQLITE_OK;
  169382. }
  169383. /*
  169384. ** Append the current term and doclist pointed to by cursor pCsr to the
  169385. ** appendable b-tree segment opened for writing by pWriter.
  169386. **
  169387. ** Return SQLITE_OK if successful, or an SQLite error code otherwise.
  169388. */
  169389. static int fts3IncrmergeAppend(
  169390. Fts3Table *p, /* Fts3 table handle */
  169391. IncrmergeWriter *pWriter, /* Writer object */
  169392. Fts3MultiSegReader *pCsr /* Cursor containing term and doclist */
  169393. ){
  169394. const char *zTerm = pCsr->zTerm;
  169395. int nTerm = pCsr->nTerm;
  169396. const char *aDoclist = pCsr->aDoclist;
  169397. int nDoclist = pCsr->nDoclist;
  169398. int rc = SQLITE_OK; /* Return code */
  169399. int nSpace; /* Total space in bytes required on leaf */
  169400. int nPrefix; /* Size of prefix shared with previous term */
  169401. int nSuffix; /* Size of suffix (nTerm - nPrefix) */
  169402. NodeWriter *pLeaf; /* Object used to write leaf nodes */
  169403. pLeaf = &pWriter->aNodeWriter[0];
  169404. nPrefix = fts3PrefixCompress(pLeaf->key.a, pLeaf->key.n, zTerm, nTerm);
  169405. nSuffix = nTerm - nPrefix;
  169406. nSpace = sqlite3Fts3VarintLen(nPrefix);
  169407. nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
  169408. nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
  169409. /* If the current block is not empty, and if adding this term/doclist
  169410. ** to the current block would make it larger than Fts3Table.nNodeSize
  169411. ** bytes, write this block out to the database. */
  169412. if( pLeaf->block.n>0 && (pLeaf->block.n + nSpace)>p->nNodeSize ){
  169413. rc = fts3WriteSegment(p, pLeaf->iBlock, pLeaf->block.a, pLeaf->block.n);
  169414. pWriter->nWork++;
  169415. /* Add the current term to the parent node. The term added to the
  169416. ** parent must:
  169417. **
  169418. ** a) be greater than the largest term on the leaf node just written
  169419. ** to the database (still available in pLeaf->key), and
  169420. **
  169421. ** b) be less than or equal to the term about to be added to the new
  169422. ** leaf node (zTerm/nTerm).
  169423. **
  169424. ** In other words, it must be the prefix of zTerm 1 byte longer than
  169425. ** the common prefix (if any) of zTerm and pWriter->zTerm.
  169426. */
  169427. if( rc==SQLITE_OK ){
  169428. rc = fts3IncrmergePush(p, pWriter, zTerm, nPrefix+1);
  169429. }
  169430. /* Advance to the next output block */
  169431. pLeaf->iBlock++;
  169432. pLeaf->key.n = 0;
  169433. pLeaf->block.n = 0;
  169434. nSuffix = nTerm;
  169435. nSpace = 1;
  169436. nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
  169437. nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
  169438. }
  169439. pWriter->nLeafData += nSpace;
  169440. blobGrowBuffer(&pLeaf->block, pLeaf->block.n + nSpace, &rc);
  169441. if( rc==SQLITE_OK ){
  169442. if( pLeaf->block.n==0 ){
  169443. pLeaf->block.n = 1;
  169444. pLeaf->block.a[0] = '\0';
  169445. }
  169446. rc = fts3AppendToNode(
  169447. &pLeaf->block, &pLeaf->key, zTerm, nTerm, aDoclist, nDoclist
  169448. );
  169449. }
  169450. return rc;
  169451. }
  169452. /*
  169453. ** This function is called to release all dynamic resources held by the
  169454. ** merge-writer object pWriter, and if no error has occurred, to flush
  169455. ** all outstanding node buffers held by pWriter to disk.
  169456. **
  169457. ** If *pRc is not SQLITE_OK when this function is called, then no attempt
  169458. ** is made to write any data to disk. Instead, this function serves only
  169459. ** to release outstanding resources.
  169460. **
  169461. ** Otherwise, if *pRc is initially SQLITE_OK and an error occurs while
  169462. ** flushing buffers to disk, *pRc is set to an SQLite error code before
  169463. ** returning.
  169464. */
  169465. static void fts3IncrmergeRelease(
  169466. Fts3Table *p, /* FTS3 table handle */
  169467. IncrmergeWriter *pWriter, /* Merge-writer object */
  169468. int *pRc /* IN/OUT: Error code */
  169469. ){
  169470. int i; /* Used to iterate through non-root layers */
  169471. int iRoot; /* Index of root in pWriter->aNodeWriter */
  169472. NodeWriter *pRoot; /* NodeWriter for root node */
  169473. int rc = *pRc; /* Error code */
  169474. /* Set iRoot to the index in pWriter->aNodeWriter[] of the output segment
  169475. ** root node. If the segment fits entirely on a single leaf node, iRoot
  169476. ** will be set to 0. If the root node is the parent of the leaves, iRoot
  169477. ** will be 1. And so on. */
  169478. for(iRoot=FTS_MAX_APPENDABLE_HEIGHT-1; iRoot>=0; iRoot--){
  169479. NodeWriter *pNode = &pWriter->aNodeWriter[iRoot];
  169480. if( pNode->block.n>0 ) break;
  169481. assert( *pRc || pNode->block.nAlloc==0 );
  169482. assert( *pRc || pNode->key.nAlloc==0 );
  169483. sqlite3_free(pNode->block.a);
  169484. sqlite3_free(pNode->key.a);
  169485. }
  169486. /* Empty output segment. This is a no-op. */
  169487. if( iRoot<0 ) return;
  169488. /* The entire output segment fits on a single node. Normally, this means
  169489. ** the node would be stored as a blob in the "root" column of the %_segdir
  169490. ** table. However, this is not permitted in this case. The problem is that
  169491. ** space has already been reserved in the %_segments table, and so the
  169492. ** start_block and end_block fields of the %_segdir table must be populated.
  169493. ** And, by design or by accident, released versions of FTS cannot handle
  169494. ** segments that fit entirely on the root node with start_block!=0.
  169495. **
  169496. ** Instead, create a synthetic root node that contains nothing but a
  169497. ** pointer to the single content node. So that the segment consists of a
  169498. ** single leaf and a single interior (root) node.
  169499. **
  169500. ** Todo: Better might be to defer allocating space in the %_segments
  169501. ** table until we are sure it is needed.
  169502. */
  169503. if( iRoot==0 ){
  169504. Blob *pBlock = &pWriter->aNodeWriter[1].block;
  169505. blobGrowBuffer(pBlock, 1 + FTS3_VARINT_MAX, &rc);
  169506. if( rc==SQLITE_OK ){
  169507. pBlock->a[0] = 0x01;
  169508. pBlock->n = 1 + sqlite3Fts3PutVarint(
  169509. &pBlock->a[1], pWriter->aNodeWriter[0].iBlock
  169510. );
  169511. }
  169512. iRoot = 1;
  169513. }
  169514. pRoot = &pWriter->aNodeWriter[iRoot];
  169515. /* Flush all currently outstanding nodes to disk. */
  169516. for(i=0; i<iRoot; i++){
  169517. NodeWriter *pNode = &pWriter->aNodeWriter[i];
  169518. if( pNode->block.n>0 && rc==SQLITE_OK ){
  169519. rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
  169520. }
  169521. sqlite3_free(pNode->block.a);
  169522. sqlite3_free(pNode->key.a);
  169523. }
  169524. /* Write the %_segdir record. */
  169525. if( rc==SQLITE_OK ){
  169526. rc = fts3WriteSegdir(p,
  169527. pWriter->iAbsLevel+1, /* level */
  169528. pWriter->iIdx, /* idx */
  169529. pWriter->iStart, /* start_block */
  169530. pWriter->aNodeWriter[0].iBlock, /* leaves_end_block */
  169531. pWriter->iEnd, /* end_block */
  169532. (pWriter->bNoLeafData==0 ? pWriter->nLeafData : 0), /* end_block */
  169533. pRoot->block.a, pRoot->block.n /* root */
  169534. );
  169535. }
  169536. sqlite3_free(pRoot->block.a);
  169537. sqlite3_free(pRoot->key.a);
  169538. *pRc = rc;
  169539. }
  169540. /*
  169541. ** Compare the term in buffer zLhs (size in bytes nLhs) with that in
  169542. ** zRhs (size in bytes nRhs) using memcmp. If one term is a prefix of
  169543. ** the other, it is considered to be smaller than the other.
  169544. **
  169545. ** Return -ve if zLhs is smaller than zRhs, 0 if it is equal, or +ve
  169546. ** if it is greater.
  169547. */
  169548. static int fts3TermCmp(
  169549. const char *zLhs, int nLhs, /* LHS of comparison */
  169550. const char *zRhs, int nRhs /* RHS of comparison */
  169551. ){
  169552. int nCmp = MIN(nLhs, nRhs);
  169553. int res;
  169554. res = (nCmp ? memcmp(zLhs, zRhs, nCmp) : 0);
  169555. if( res==0 ) res = nLhs - nRhs;
  169556. return res;
  169557. }
  169558. /*
  169559. ** Query to see if the entry in the %_segments table with blockid iEnd is
  169560. ** NULL. If no error occurs and the entry is NULL, set *pbRes 1 before
  169561. ** returning. Otherwise, set *pbRes to 0.
  169562. **
  169563. ** Or, if an error occurs while querying the database, return an SQLite
  169564. ** error code. The final value of *pbRes is undefined in this case.
  169565. **
  169566. ** This is used to test if a segment is an "appendable" segment. If it
  169567. ** is, then a NULL entry has been inserted into the %_segments table
  169568. ** with blockid %_segdir.end_block.
  169569. */
  169570. static int fts3IsAppendable(Fts3Table *p, sqlite3_int64 iEnd, int *pbRes){
  169571. int bRes = 0; /* Result to set *pbRes to */
  169572. sqlite3_stmt *pCheck = 0; /* Statement to query database with */
  169573. int rc; /* Return code */
  169574. rc = fts3SqlStmt(p, SQL_SEGMENT_IS_APPENDABLE, &pCheck, 0);
  169575. if( rc==SQLITE_OK ){
  169576. sqlite3_bind_int64(pCheck, 1, iEnd);
  169577. if( SQLITE_ROW==sqlite3_step(pCheck) ) bRes = 1;
  169578. rc = sqlite3_reset(pCheck);
  169579. }
  169580. *pbRes = bRes;
  169581. return rc;
  169582. }
  169583. /*
  169584. ** This function is called when initializing an incremental-merge operation.
  169585. ** It checks if the existing segment with index value iIdx at absolute level
  169586. ** (iAbsLevel+1) can be appended to by the incremental merge. If it can, the
  169587. ** merge-writer object *pWriter is initialized to write to it.
  169588. **
  169589. ** An existing segment can be appended to by an incremental merge if:
  169590. **
  169591. ** * It was initially created as an appendable segment (with all required
  169592. ** space pre-allocated), and
  169593. **
  169594. ** * The first key read from the input (arguments zKey and nKey) is
  169595. ** greater than the largest key currently stored in the potential
  169596. ** output segment.
  169597. */
  169598. static int fts3IncrmergeLoad(
  169599. Fts3Table *p, /* Fts3 table handle */
  169600. sqlite3_int64 iAbsLevel, /* Absolute level of input segments */
  169601. int iIdx, /* Index of candidate output segment */
  169602. const char *zKey, /* First key to write */
  169603. int nKey, /* Number of bytes in nKey */
  169604. IncrmergeWriter *pWriter /* Populate this object */
  169605. ){
  169606. int rc; /* Return code */
  169607. sqlite3_stmt *pSelect = 0; /* SELECT to read %_segdir entry */
  169608. rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pSelect, 0);
  169609. if( rc==SQLITE_OK ){
  169610. sqlite3_int64 iStart = 0; /* Value of %_segdir.start_block */
  169611. sqlite3_int64 iLeafEnd = 0; /* Value of %_segdir.leaves_end_block */
  169612. sqlite3_int64 iEnd = 0; /* Value of %_segdir.end_block */
  169613. const char *aRoot = 0; /* Pointer to %_segdir.root buffer */
  169614. int nRoot = 0; /* Size of aRoot[] in bytes */
  169615. int rc2; /* Return code from sqlite3_reset() */
  169616. int bAppendable = 0; /* Set to true if segment is appendable */
  169617. /* Read the %_segdir entry for index iIdx absolute level (iAbsLevel+1) */
  169618. sqlite3_bind_int64(pSelect, 1, iAbsLevel+1);
  169619. sqlite3_bind_int(pSelect, 2, iIdx);
  169620. if( sqlite3_step(pSelect)==SQLITE_ROW ){
  169621. iStart = sqlite3_column_int64(pSelect, 1);
  169622. iLeafEnd = sqlite3_column_int64(pSelect, 2);
  169623. fts3ReadEndBlockField(pSelect, 3, &iEnd, &pWriter->nLeafData);
  169624. if( pWriter->nLeafData<0 ){
  169625. pWriter->nLeafData = pWriter->nLeafData * -1;
  169626. }
  169627. pWriter->bNoLeafData = (pWriter->nLeafData==0);
  169628. nRoot = sqlite3_column_bytes(pSelect, 4);
  169629. aRoot = sqlite3_column_blob(pSelect, 4);
  169630. if( aRoot==0 ){
  169631. sqlite3_reset(pSelect);
  169632. return nRoot ? SQLITE_NOMEM : FTS_CORRUPT_VTAB;
  169633. }
  169634. }else{
  169635. return sqlite3_reset(pSelect);
  169636. }
  169637. /* Check for the zero-length marker in the %_segments table */
  169638. rc = fts3IsAppendable(p, iEnd, &bAppendable);
  169639. /* Check that zKey/nKey is larger than the largest key the candidate */
  169640. if( rc==SQLITE_OK && bAppendable ){
  169641. char *aLeaf = 0;
  169642. int nLeaf = 0;
  169643. rc = sqlite3Fts3ReadBlock(p, iLeafEnd, &aLeaf, &nLeaf, 0);
  169644. if( rc==SQLITE_OK ){
  169645. NodeReader reader;
  169646. for(rc = nodeReaderInit(&reader, aLeaf, nLeaf);
  169647. rc==SQLITE_OK && reader.aNode;
  169648. rc = nodeReaderNext(&reader)
  169649. ){
  169650. assert( reader.aNode );
  169651. }
  169652. if( fts3TermCmp(zKey, nKey, reader.term.a, reader.term.n)<=0 ){
  169653. bAppendable = 0;
  169654. }
  169655. nodeReaderRelease(&reader);
  169656. }
  169657. sqlite3_free(aLeaf);
  169658. }
  169659. if( rc==SQLITE_OK && bAppendable ){
  169660. /* It is possible to append to this segment. Set up the IncrmergeWriter
  169661. ** object to do so. */
  169662. int i;
  169663. int nHeight = (int)aRoot[0];
  169664. NodeWriter *pNode;
  169665. if( nHeight<1 || nHeight>FTS_MAX_APPENDABLE_HEIGHT ){
  169666. sqlite3_reset(pSelect);
  169667. return FTS_CORRUPT_VTAB;
  169668. }
  169669. pWriter->nLeafEst = (int)((iEnd - iStart) + 1)/FTS_MAX_APPENDABLE_HEIGHT;
  169670. pWriter->iStart = iStart;
  169671. pWriter->iEnd = iEnd;
  169672. pWriter->iAbsLevel = iAbsLevel;
  169673. pWriter->iIdx = iIdx;
  169674. for(i=nHeight+1; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
  169675. pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
  169676. }
  169677. pNode = &pWriter->aNodeWriter[nHeight];
  169678. pNode->iBlock = pWriter->iStart + pWriter->nLeafEst*nHeight;
  169679. blobGrowBuffer(&pNode->block,
  169680. MAX(nRoot, p->nNodeSize)+FTS3_NODE_PADDING, &rc
  169681. );
  169682. if( rc==SQLITE_OK ){
  169683. memcpy(pNode->block.a, aRoot, nRoot);
  169684. pNode->block.n = nRoot;
  169685. memset(&pNode->block.a[nRoot], 0, FTS3_NODE_PADDING);
  169686. }
  169687. for(i=nHeight; i>=0 && rc==SQLITE_OK; i--){
  169688. NodeReader reader;
  169689. pNode = &pWriter->aNodeWriter[i];
  169690. if( pNode->block.a){
  169691. rc = nodeReaderInit(&reader, pNode->block.a, pNode->block.n);
  169692. while( reader.aNode && rc==SQLITE_OK ) rc = nodeReaderNext(&reader);
  169693. blobGrowBuffer(&pNode->key, reader.term.n, &rc);
  169694. if( rc==SQLITE_OK ){
  169695. memcpy(pNode->key.a, reader.term.a, reader.term.n);
  169696. pNode->key.n = reader.term.n;
  169697. if( i>0 ){
  169698. char *aBlock = 0;
  169699. int nBlock = 0;
  169700. pNode = &pWriter->aNodeWriter[i-1];
  169701. pNode->iBlock = reader.iChild;
  169702. rc = sqlite3Fts3ReadBlock(p, reader.iChild, &aBlock, &nBlock, 0);
  169703. blobGrowBuffer(&pNode->block,
  169704. MAX(nBlock, p->nNodeSize)+FTS3_NODE_PADDING, &rc
  169705. );
  169706. if( rc==SQLITE_OK ){
  169707. memcpy(pNode->block.a, aBlock, nBlock);
  169708. pNode->block.n = nBlock;
  169709. memset(&pNode->block.a[nBlock], 0, FTS3_NODE_PADDING);
  169710. }
  169711. sqlite3_free(aBlock);
  169712. }
  169713. }
  169714. }
  169715. nodeReaderRelease(&reader);
  169716. }
  169717. }
  169718. rc2 = sqlite3_reset(pSelect);
  169719. if( rc==SQLITE_OK ) rc = rc2;
  169720. }
  169721. return rc;
  169722. }
  169723. /*
  169724. ** Determine the largest segment index value that exists within absolute
  169725. ** level iAbsLevel+1. If no error occurs, set *piIdx to this value plus
  169726. ** one before returning SQLITE_OK. Or, if there are no segments at all
  169727. ** within level iAbsLevel, set *piIdx to zero.
  169728. **
  169729. ** If an error occurs, return an SQLite error code. The final value of
  169730. ** *piIdx is undefined in this case.
  169731. */
  169732. static int fts3IncrmergeOutputIdx(
  169733. Fts3Table *p, /* FTS Table handle */
  169734. sqlite3_int64 iAbsLevel, /* Absolute index of input segments */
  169735. int *piIdx /* OUT: Next free index at iAbsLevel+1 */
  169736. ){
  169737. int rc;
  169738. sqlite3_stmt *pOutputIdx = 0; /* SQL used to find output index */
  169739. rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pOutputIdx, 0);
  169740. if( rc==SQLITE_OK ){
  169741. sqlite3_bind_int64(pOutputIdx, 1, iAbsLevel+1);
  169742. sqlite3_step(pOutputIdx);
  169743. *piIdx = sqlite3_column_int(pOutputIdx, 0);
  169744. rc = sqlite3_reset(pOutputIdx);
  169745. }
  169746. return rc;
  169747. }
  169748. /*
  169749. ** Allocate an appendable output segment on absolute level iAbsLevel+1
  169750. ** with idx value iIdx.
  169751. **
  169752. ** In the %_segdir table, a segment is defined by the values in three
  169753. ** columns:
  169754. **
  169755. ** start_block
  169756. ** leaves_end_block
  169757. ** end_block
  169758. **
  169759. ** When an appendable segment is allocated, it is estimated that the
  169760. ** maximum number of leaf blocks that may be required is the sum of the
  169761. ** number of leaf blocks consumed by the input segments, plus the number
  169762. ** of input segments, multiplied by two. This value is stored in stack
  169763. ** variable nLeafEst.
  169764. **
  169765. ** A total of 16*nLeafEst blocks are allocated when an appendable segment
  169766. ** is created ((1 + end_block - start_block)==16*nLeafEst). The contiguous
  169767. ** array of leaf nodes starts at the first block allocated. The array
  169768. ** of interior nodes that are parents of the leaf nodes start at block
  169769. ** (start_block + (1 + end_block - start_block) / 16). And so on.
  169770. **
  169771. ** In the actual code below, the value "16" is replaced with the
  169772. ** pre-processor macro FTS_MAX_APPENDABLE_HEIGHT.
  169773. */
  169774. static int fts3IncrmergeWriter(
  169775. Fts3Table *p, /* Fts3 table handle */
  169776. sqlite3_int64 iAbsLevel, /* Absolute level of input segments */
  169777. int iIdx, /* Index of new output segment */
  169778. Fts3MultiSegReader *pCsr, /* Cursor that data will be read from */
  169779. IncrmergeWriter *pWriter /* Populate this object */
  169780. ){
  169781. int rc; /* Return Code */
  169782. int i; /* Iterator variable */
  169783. int nLeafEst = 0; /* Blocks allocated for leaf nodes */
  169784. sqlite3_stmt *pLeafEst = 0; /* SQL used to determine nLeafEst */
  169785. sqlite3_stmt *pFirstBlock = 0; /* SQL used to determine first block */
  169786. /* Calculate nLeafEst. */
  169787. rc = fts3SqlStmt(p, SQL_MAX_LEAF_NODE_ESTIMATE, &pLeafEst, 0);
  169788. if( rc==SQLITE_OK ){
  169789. sqlite3_bind_int64(pLeafEst, 1, iAbsLevel);
  169790. sqlite3_bind_int64(pLeafEst, 2, pCsr->nSegment);
  169791. if( SQLITE_ROW==sqlite3_step(pLeafEst) ){
  169792. nLeafEst = sqlite3_column_int(pLeafEst, 0);
  169793. }
  169794. rc = sqlite3_reset(pLeafEst);
  169795. }
  169796. if( rc!=SQLITE_OK ) return rc;
  169797. /* Calculate the first block to use in the output segment */
  169798. rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pFirstBlock, 0);
  169799. if( rc==SQLITE_OK ){
  169800. if( SQLITE_ROW==sqlite3_step(pFirstBlock) ){
  169801. pWriter->iStart = sqlite3_column_int64(pFirstBlock, 0);
  169802. pWriter->iEnd = pWriter->iStart - 1;
  169803. pWriter->iEnd += nLeafEst * FTS_MAX_APPENDABLE_HEIGHT;
  169804. }
  169805. rc = sqlite3_reset(pFirstBlock);
  169806. }
  169807. if( rc!=SQLITE_OK ) return rc;
  169808. /* Insert the marker in the %_segments table to make sure nobody tries
  169809. ** to steal the space just allocated. This is also used to identify
  169810. ** appendable segments. */
  169811. rc = fts3WriteSegment(p, pWriter->iEnd, 0, 0);
  169812. if( rc!=SQLITE_OK ) return rc;
  169813. pWriter->iAbsLevel = iAbsLevel;
  169814. pWriter->nLeafEst = nLeafEst;
  169815. pWriter->iIdx = iIdx;
  169816. /* Set up the array of NodeWriter objects */
  169817. for(i=0; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
  169818. pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
  169819. }
  169820. return SQLITE_OK;
  169821. }
  169822. /*
  169823. ** Remove an entry from the %_segdir table. This involves running the
  169824. ** following two statements:
  169825. **
  169826. ** DELETE FROM %_segdir WHERE level = :iAbsLevel AND idx = :iIdx
  169827. ** UPDATE %_segdir SET idx = idx - 1 WHERE level = :iAbsLevel AND idx > :iIdx
  169828. **
  169829. ** The DELETE statement removes the specific %_segdir level. The UPDATE
  169830. ** statement ensures that the remaining segments have contiguously allocated
  169831. ** idx values.
  169832. */
  169833. static int fts3RemoveSegdirEntry(
  169834. Fts3Table *p, /* FTS3 table handle */
  169835. sqlite3_int64 iAbsLevel, /* Absolute level to delete from */
  169836. int iIdx /* Index of %_segdir entry to delete */
  169837. ){
  169838. int rc; /* Return code */
  169839. sqlite3_stmt *pDelete = 0; /* DELETE statement */
  169840. rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_ENTRY, &pDelete, 0);
  169841. if( rc==SQLITE_OK ){
  169842. sqlite3_bind_int64(pDelete, 1, iAbsLevel);
  169843. sqlite3_bind_int(pDelete, 2, iIdx);
  169844. sqlite3_step(pDelete);
  169845. rc = sqlite3_reset(pDelete);
  169846. }
  169847. return rc;
  169848. }
  169849. /*
  169850. ** One or more segments have just been removed from absolute level iAbsLevel.
  169851. ** Update the 'idx' values of the remaining segments in the level so that
  169852. ** the idx values are a contiguous sequence starting from 0.
  169853. */
  169854. static int fts3RepackSegdirLevel(
  169855. Fts3Table *p, /* FTS3 table handle */
  169856. sqlite3_int64 iAbsLevel /* Absolute level to repack */
  169857. ){
  169858. int rc; /* Return code */
  169859. int *aIdx = 0; /* Array of remaining idx values */
  169860. int nIdx = 0; /* Valid entries in aIdx[] */
  169861. int nAlloc = 0; /* Allocated size of aIdx[] */
  169862. int i; /* Iterator variable */
  169863. sqlite3_stmt *pSelect = 0; /* Select statement to read idx values */
  169864. sqlite3_stmt *pUpdate = 0; /* Update statement to modify idx values */
  169865. rc = fts3SqlStmt(p, SQL_SELECT_INDEXES, &pSelect, 0);
  169866. if( rc==SQLITE_OK ){
  169867. int rc2;
  169868. sqlite3_bind_int64(pSelect, 1, iAbsLevel);
  169869. while( SQLITE_ROW==sqlite3_step(pSelect) ){
  169870. if( nIdx>=nAlloc ){
  169871. int *aNew;
  169872. nAlloc += 16;
  169873. aNew = sqlite3_realloc(aIdx, nAlloc*sizeof(int));
  169874. if( !aNew ){
  169875. rc = SQLITE_NOMEM;
  169876. break;
  169877. }
  169878. aIdx = aNew;
  169879. }
  169880. aIdx[nIdx++] = sqlite3_column_int(pSelect, 0);
  169881. }
  169882. rc2 = sqlite3_reset(pSelect);
  169883. if( rc==SQLITE_OK ) rc = rc2;
  169884. }
  169885. if( rc==SQLITE_OK ){
  169886. rc = fts3SqlStmt(p, SQL_SHIFT_SEGDIR_ENTRY, &pUpdate, 0);
  169887. }
  169888. if( rc==SQLITE_OK ){
  169889. sqlite3_bind_int64(pUpdate, 2, iAbsLevel);
  169890. }
  169891. assert( p->bIgnoreSavepoint==0 );
  169892. p->bIgnoreSavepoint = 1;
  169893. for(i=0; rc==SQLITE_OK && i<nIdx; i++){
  169894. if( aIdx[i]!=i ){
  169895. sqlite3_bind_int(pUpdate, 3, aIdx[i]);
  169896. sqlite3_bind_int(pUpdate, 1, i);
  169897. sqlite3_step(pUpdate);
  169898. rc = sqlite3_reset(pUpdate);
  169899. }
  169900. }
  169901. p->bIgnoreSavepoint = 0;
  169902. sqlite3_free(aIdx);
  169903. return rc;
  169904. }
  169905. static void fts3StartNode(Blob *pNode, int iHeight, sqlite3_int64 iChild){
  169906. pNode->a[0] = (char)iHeight;
  169907. if( iChild ){
  169908. assert( pNode->nAlloc>=1+sqlite3Fts3VarintLen(iChild) );
  169909. pNode->n = 1 + sqlite3Fts3PutVarint(&pNode->a[1], iChild);
  169910. }else{
  169911. assert( pNode->nAlloc>=1 );
  169912. pNode->n = 1;
  169913. }
  169914. }
  169915. /*
  169916. ** The first two arguments are a pointer to and the size of a segment b-tree
  169917. ** node. The node may be a leaf or an internal node.
  169918. **
  169919. ** This function creates a new node image in blob object *pNew by copying
  169920. ** all terms that are greater than or equal to zTerm/nTerm (for leaf nodes)
  169921. ** or greater than zTerm/nTerm (for internal nodes) from aNode/nNode.
  169922. */
  169923. static int fts3TruncateNode(
  169924. const char *aNode, /* Current node image */
  169925. int nNode, /* Size of aNode in bytes */
  169926. Blob *pNew, /* OUT: Write new node image here */
  169927. const char *zTerm, /* Omit all terms smaller than this */
  169928. int nTerm, /* Size of zTerm in bytes */
  169929. sqlite3_int64 *piBlock /* OUT: Block number in next layer down */
  169930. ){
  169931. NodeReader reader; /* Reader object */
  169932. Blob prev = {0, 0, 0}; /* Previous term written to new node */
  169933. int rc = SQLITE_OK; /* Return code */
  169934. int bLeaf; /* True for a leaf node */
  169935. if( nNode<1 ) return FTS_CORRUPT_VTAB;
  169936. bLeaf = aNode[0]=='\0';
  169937. /* Allocate required output space */
  169938. blobGrowBuffer(pNew, nNode, &rc);
  169939. if( rc!=SQLITE_OK ) return rc;
  169940. pNew->n = 0;
  169941. /* Populate new node buffer */
  169942. for(rc = nodeReaderInit(&reader, aNode, nNode);
  169943. rc==SQLITE_OK && reader.aNode;
  169944. rc = nodeReaderNext(&reader)
  169945. ){
  169946. if( pNew->n==0 ){
  169947. int res = fts3TermCmp(reader.term.a, reader.term.n, zTerm, nTerm);
  169948. if( res<0 || (bLeaf==0 && res==0) ) continue;
  169949. fts3StartNode(pNew, (int)aNode[0], reader.iChild);
  169950. *piBlock = reader.iChild;
  169951. }
  169952. rc = fts3AppendToNode(
  169953. pNew, &prev, reader.term.a, reader.term.n,
  169954. reader.aDoclist, reader.nDoclist
  169955. );
  169956. if( rc!=SQLITE_OK ) break;
  169957. }
  169958. if( pNew->n==0 ){
  169959. fts3StartNode(pNew, (int)aNode[0], reader.iChild);
  169960. *piBlock = reader.iChild;
  169961. }
  169962. assert( pNew->n<=pNew->nAlloc );
  169963. nodeReaderRelease(&reader);
  169964. sqlite3_free(prev.a);
  169965. return rc;
  169966. }
  169967. /*
  169968. ** Remove all terms smaller than zTerm/nTerm from segment iIdx in absolute
  169969. ** level iAbsLevel. This may involve deleting entries from the %_segments
  169970. ** table, and modifying existing entries in both the %_segments and %_segdir
  169971. ** tables.
  169972. **
  169973. ** SQLITE_OK is returned if the segment is updated successfully. Or an
  169974. ** SQLite error code otherwise.
  169975. */
  169976. static int fts3TruncateSegment(
  169977. Fts3Table *p, /* FTS3 table handle */
  169978. sqlite3_int64 iAbsLevel, /* Absolute level of segment to modify */
  169979. int iIdx, /* Index within level of segment to modify */
  169980. const char *zTerm, /* Remove terms smaller than this */
  169981. int nTerm /* Number of bytes in buffer zTerm */
  169982. ){
  169983. int rc = SQLITE_OK; /* Return code */
  169984. Blob root = {0,0,0}; /* New root page image */
  169985. Blob block = {0,0,0}; /* Buffer used for any other block */
  169986. sqlite3_int64 iBlock = 0; /* Block id */
  169987. sqlite3_int64 iNewStart = 0; /* New value for iStartBlock */
  169988. sqlite3_int64 iOldStart = 0; /* Old value for iStartBlock */
  169989. sqlite3_stmt *pFetch = 0; /* Statement used to fetch segdir */
  169990. rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pFetch, 0);
  169991. if( rc==SQLITE_OK ){
  169992. int rc2; /* sqlite3_reset() return code */
  169993. sqlite3_bind_int64(pFetch, 1, iAbsLevel);
  169994. sqlite3_bind_int(pFetch, 2, iIdx);
  169995. if( SQLITE_ROW==sqlite3_step(pFetch) ){
  169996. const char *aRoot = sqlite3_column_blob(pFetch, 4);
  169997. int nRoot = sqlite3_column_bytes(pFetch, 4);
  169998. iOldStart = sqlite3_column_int64(pFetch, 1);
  169999. rc = fts3TruncateNode(aRoot, nRoot, &root, zTerm, nTerm, &iBlock);
  170000. }
  170001. rc2 = sqlite3_reset(pFetch);
  170002. if( rc==SQLITE_OK ) rc = rc2;
  170003. }
  170004. while( rc==SQLITE_OK && iBlock ){
  170005. char *aBlock = 0;
  170006. int nBlock = 0;
  170007. iNewStart = iBlock;
  170008. rc = sqlite3Fts3ReadBlock(p, iBlock, &aBlock, &nBlock, 0);
  170009. if( rc==SQLITE_OK ){
  170010. rc = fts3TruncateNode(aBlock, nBlock, &block, zTerm, nTerm, &iBlock);
  170011. }
  170012. if( rc==SQLITE_OK ){
  170013. rc = fts3WriteSegment(p, iNewStart, block.a, block.n);
  170014. }
  170015. sqlite3_free(aBlock);
  170016. }
  170017. /* Variable iNewStart now contains the first valid leaf node. */
  170018. if( rc==SQLITE_OK && iNewStart ){
  170019. sqlite3_stmt *pDel = 0;
  170020. rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDel, 0);
  170021. if( rc==SQLITE_OK ){
  170022. sqlite3_bind_int64(pDel, 1, iOldStart);
  170023. sqlite3_bind_int64(pDel, 2, iNewStart-1);
  170024. sqlite3_step(pDel);
  170025. rc = sqlite3_reset(pDel);
  170026. }
  170027. }
  170028. if( rc==SQLITE_OK ){
  170029. sqlite3_stmt *pChomp = 0;
  170030. rc = fts3SqlStmt(p, SQL_CHOMP_SEGDIR, &pChomp, 0);
  170031. if( rc==SQLITE_OK ){
  170032. sqlite3_bind_int64(pChomp, 1, iNewStart);
  170033. sqlite3_bind_blob(pChomp, 2, root.a, root.n, SQLITE_STATIC);
  170034. sqlite3_bind_int64(pChomp, 3, iAbsLevel);
  170035. sqlite3_bind_int(pChomp, 4, iIdx);
  170036. sqlite3_step(pChomp);
  170037. rc = sqlite3_reset(pChomp);
  170038. sqlite3_bind_null(pChomp, 2);
  170039. }
  170040. }
  170041. sqlite3_free(root.a);
  170042. sqlite3_free(block.a);
  170043. return rc;
  170044. }
  170045. /*
  170046. ** This function is called after an incrmental-merge operation has run to
  170047. ** merge (or partially merge) two or more segments from absolute level
  170048. ** iAbsLevel.
  170049. **
  170050. ** Each input segment is either removed from the db completely (if all of
  170051. ** its data was copied to the output segment by the incrmerge operation)
  170052. ** or modified in place so that it no longer contains those entries that
  170053. ** have been duplicated in the output segment.
  170054. */
  170055. static int fts3IncrmergeChomp(
  170056. Fts3Table *p, /* FTS table handle */
  170057. sqlite3_int64 iAbsLevel, /* Absolute level containing segments */
  170058. Fts3MultiSegReader *pCsr, /* Chomp all segments opened by this cursor */
  170059. int *pnRem /* Number of segments not deleted */
  170060. ){
  170061. int i;
  170062. int nRem = 0;
  170063. int rc = SQLITE_OK;
  170064. for(i=pCsr->nSegment-1; i>=0 && rc==SQLITE_OK; i--){
  170065. Fts3SegReader *pSeg = 0;
  170066. int j;
  170067. /* Find the Fts3SegReader object with Fts3SegReader.iIdx==i. It is hiding
  170068. ** somewhere in the pCsr->apSegment[] array. */
  170069. for(j=0; ALWAYS(j<pCsr->nSegment); j++){
  170070. pSeg = pCsr->apSegment[j];
  170071. if( pSeg->iIdx==i ) break;
  170072. }
  170073. assert( j<pCsr->nSegment && pSeg->iIdx==i );
  170074. if( pSeg->aNode==0 ){
  170075. /* Seg-reader is at EOF. Remove the entire input segment. */
  170076. rc = fts3DeleteSegment(p, pSeg);
  170077. if( rc==SQLITE_OK ){
  170078. rc = fts3RemoveSegdirEntry(p, iAbsLevel, pSeg->iIdx);
  170079. }
  170080. *pnRem = 0;
  170081. }else{
  170082. /* The incremental merge did not copy all the data from this
  170083. ** segment to the upper level. The segment is modified in place
  170084. ** so that it contains no keys smaller than zTerm/nTerm. */
  170085. const char *zTerm = pSeg->zTerm;
  170086. int nTerm = pSeg->nTerm;
  170087. rc = fts3TruncateSegment(p, iAbsLevel, pSeg->iIdx, zTerm, nTerm);
  170088. nRem++;
  170089. }
  170090. }
  170091. if( rc==SQLITE_OK && nRem!=pCsr->nSegment ){
  170092. rc = fts3RepackSegdirLevel(p, iAbsLevel);
  170093. }
  170094. *pnRem = nRem;
  170095. return rc;
  170096. }
  170097. /*
  170098. ** Store an incr-merge hint in the database.
  170099. */
  170100. static int fts3IncrmergeHintStore(Fts3Table *p, Blob *pHint){
  170101. sqlite3_stmt *pReplace = 0;
  170102. int rc; /* Return code */
  170103. rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pReplace, 0);
  170104. if( rc==SQLITE_OK ){
  170105. sqlite3_bind_int(pReplace, 1, FTS_STAT_INCRMERGEHINT);
  170106. sqlite3_bind_blob(pReplace, 2, pHint->a, pHint->n, SQLITE_STATIC);
  170107. sqlite3_step(pReplace);
  170108. rc = sqlite3_reset(pReplace);
  170109. sqlite3_bind_null(pReplace, 2);
  170110. }
  170111. return rc;
  170112. }
  170113. /*
  170114. ** Load an incr-merge hint from the database. The incr-merge hint, if one
  170115. ** exists, is stored in the rowid==1 row of the %_stat table.
  170116. **
  170117. ** If successful, populate blob *pHint with the value read from the %_stat
  170118. ** table and return SQLITE_OK. Otherwise, if an error occurs, return an
  170119. ** SQLite error code.
  170120. */
  170121. static int fts3IncrmergeHintLoad(Fts3Table *p, Blob *pHint){
  170122. sqlite3_stmt *pSelect = 0;
  170123. int rc;
  170124. pHint->n = 0;
  170125. rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pSelect, 0);
  170126. if( rc==SQLITE_OK ){
  170127. int rc2;
  170128. sqlite3_bind_int(pSelect, 1, FTS_STAT_INCRMERGEHINT);
  170129. if( SQLITE_ROW==sqlite3_step(pSelect) ){
  170130. const char *aHint = sqlite3_column_blob(pSelect, 0);
  170131. int nHint = sqlite3_column_bytes(pSelect, 0);
  170132. if( aHint ){
  170133. blobGrowBuffer(pHint, nHint, &rc);
  170134. if( rc==SQLITE_OK ){
  170135. memcpy(pHint->a, aHint, nHint);
  170136. pHint->n = nHint;
  170137. }
  170138. }
  170139. }
  170140. rc2 = sqlite3_reset(pSelect);
  170141. if( rc==SQLITE_OK ) rc = rc2;
  170142. }
  170143. return rc;
  170144. }
  170145. /*
  170146. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  170147. ** Otherwise, append an entry to the hint stored in blob *pHint. Each entry
  170148. ** consists of two varints, the absolute level number of the input segments
  170149. ** and the number of input segments.
  170150. **
  170151. ** If successful, leave *pRc set to SQLITE_OK and return. If an error occurs,
  170152. ** set *pRc to an SQLite error code before returning.
  170153. */
  170154. static void fts3IncrmergeHintPush(
  170155. Blob *pHint, /* Hint blob to append to */
  170156. i64 iAbsLevel, /* First varint to store in hint */
  170157. int nInput, /* Second varint to store in hint */
  170158. int *pRc /* IN/OUT: Error code */
  170159. ){
  170160. blobGrowBuffer(pHint, pHint->n + 2*FTS3_VARINT_MAX, pRc);
  170161. if( *pRc==SQLITE_OK ){
  170162. pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], iAbsLevel);
  170163. pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], (i64)nInput);
  170164. }
  170165. }
  170166. /*
  170167. ** Read the last entry (most recently pushed) from the hint blob *pHint
  170168. ** and then remove the entry. Write the two values read to *piAbsLevel and
  170169. ** *pnInput before returning.
  170170. **
  170171. ** If no error occurs, return SQLITE_OK. If the hint blob in *pHint does
  170172. ** not contain at least two valid varints, return SQLITE_CORRUPT_VTAB.
  170173. */
  170174. static int fts3IncrmergeHintPop(Blob *pHint, i64 *piAbsLevel, int *pnInput){
  170175. const int nHint = pHint->n;
  170176. int i;
  170177. i = pHint->n-1;
  170178. if( (pHint->a[i] & 0x80) ) return FTS_CORRUPT_VTAB;
  170179. while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
  170180. if( i==0 ) return FTS_CORRUPT_VTAB;
  170181. i--;
  170182. while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
  170183. pHint->n = i;
  170184. i += sqlite3Fts3GetVarint(&pHint->a[i], piAbsLevel);
  170185. i += fts3GetVarint32(&pHint->a[i], pnInput);
  170186. assert( i<=nHint );
  170187. if( i!=nHint ) return FTS_CORRUPT_VTAB;
  170188. return SQLITE_OK;
  170189. }
  170190. /*
  170191. ** Attempt an incremental merge that writes nMerge leaf blocks.
  170192. **
  170193. ** Incremental merges happen nMin segments at a time. The segments
  170194. ** to be merged are the nMin oldest segments (the ones with the smallest
  170195. ** values for the _segdir.idx field) in the highest level that contains
  170196. ** at least nMin segments. Multiple merges might occur in an attempt to
  170197. ** write the quota of nMerge leaf blocks.
  170198. */
  170199. SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table *p, int nMerge, int nMin){
  170200. int rc; /* Return code */
  170201. int nRem = nMerge; /* Number of leaf pages yet to be written */
  170202. Fts3MultiSegReader *pCsr; /* Cursor used to read input data */
  170203. Fts3SegFilter *pFilter; /* Filter used with cursor pCsr */
  170204. IncrmergeWriter *pWriter; /* Writer object */
  170205. int nSeg = 0; /* Number of input segments */
  170206. sqlite3_int64 iAbsLevel = 0; /* Absolute level number to work on */
  170207. Blob hint = {0, 0, 0}; /* Hint read from %_stat table */
  170208. int bDirtyHint = 0; /* True if blob 'hint' has been modified */
  170209. /* Allocate space for the cursor, filter and writer objects */
  170210. const int nAlloc = sizeof(*pCsr) + sizeof(*pFilter) + sizeof(*pWriter);
  170211. pWriter = (IncrmergeWriter *)sqlite3_malloc(nAlloc);
  170212. if( !pWriter ) return SQLITE_NOMEM;
  170213. pFilter = (Fts3SegFilter *)&pWriter[1];
  170214. pCsr = (Fts3MultiSegReader *)&pFilter[1];
  170215. rc = fts3IncrmergeHintLoad(p, &hint);
  170216. while( rc==SQLITE_OK && nRem>0 ){
  170217. const i64 nMod = FTS3_SEGDIR_MAXLEVEL * p->nIndex;
  170218. sqlite3_stmt *pFindLevel = 0; /* SQL used to determine iAbsLevel */
  170219. int bUseHint = 0; /* True if attempting to append */
  170220. int iIdx = 0; /* Largest idx in level (iAbsLevel+1) */
  170221. /* Search the %_segdir table for the absolute level with the smallest
  170222. ** relative level number that contains at least nMin segments, if any.
  170223. ** If one is found, set iAbsLevel to the absolute level number and
  170224. ** nSeg to nMin. If no level with at least nMin segments can be found,
  170225. ** set nSeg to -1.
  170226. */
  170227. rc = fts3SqlStmt(p, SQL_FIND_MERGE_LEVEL, &pFindLevel, 0);
  170228. sqlite3_bind_int(pFindLevel, 1, MAX(2, nMin));
  170229. if( sqlite3_step(pFindLevel)==SQLITE_ROW ){
  170230. iAbsLevel = sqlite3_column_int64(pFindLevel, 0);
  170231. nSeg = sqlite3_column_int(pFindLevel, 1);
  170232. assert( nSeg>=2 );
  170233. }else{
  170234. nSeg = -1;
  170235. }
  170236. rc = sqlite3_reset(pFindLevel);
  170237. /* If the hint read from the %_stat table is not empty, check if the
  170238. ** last entry in it specifies a relative level smaller than or equal
  170239. ** to the level identified by the block above (if any). If so, this
  170240. ** iteration of the loop will work on merging at the hinted level.
  170241. */
  170242. if( rc==SQLITE_OK && hint.n ){
  170243. int nHint = hint.n;
  170244. sqlite3_int64 iHintAbsLevel = 0; /* Hint level */
  170245. int nHintSeg = 0; /* Hint number of segments */
  170246. rc = fts3IncrmergeHintPop(&hint, &iHintAbsLevel, &nHintSeg);
  170247. if( nSeg<0 || (iAbsLevel % nMod) >= (iHintAbsLevel % nMod) ){
  170248. /* Based on the scan in the block above, it is known that there
  170249. ** are no levels with a relative level smaller than that of
  170250. ** iAbsLevel with more than nSeg segments, or if nSeg is -1,
  170251. ** no levels with more than nMin segments. Use this to limit the
  170252. ** value of nHintSeg to avoid a large memory allocation in case the
  170253. ** merge-hint is corrupt*/
  170254. iAbsLevel = iHintAbsLevel;
  170255. nSeg = MIN(MAX(nMin,nSeg), nHintSeg);
  170256. bUseHint = 1;
  170257. bDirtyHint = 1;
  170258. }else{
  170259. /* This undoes the effect of the HintPop() above - so that no entry
  170260. ** is removed from the hint blob. */
  170261. hint.n = nHint;
  170262. }
  170263. }
  170264. /* If nSeg is less that zero, then there is no level with at least
  170265. ** nMin segments and no hint in the %_stat table. No work to do.
  170266. ** Exit early in this case. */
  170267. if( nSeg<=0 ) break;
  170268. assert( nMod<=0x7FFFFFFF );
  170269. if( iAbsLevel<0 || iAbsLevel>(nMod<<32) ){
  170270. rc = FTS_CORRUPT_VTAB;
  170271. break;
  170272. }
  170273. /* Open a cursor to iterate through the contents of the oldest nSeg
  170274. ** indexes of absolute level iAbsLevel. If this cursor is opened using
  170275. ** the 'hint' parameters, it is possible that there are less than nSeg
  170276. ** segments available in level iAbsLevel. In this case, no work is
  170277. ** done on iAbsLevel - fall through to the next iteration of the loop
  170278. ** to start work on some other level. */
  170279. memset(pWriter, 0, nAlloc);
  170280. pFilter->flags = FTS3_SEGMENT_REQUIRE_POS;
  170281. if( rc==SQLITE_OK ){
  170282. rc = fts3IncrmergeOutputIdx(p, iAbsLevel, &iIdx);
  170283. assert( bUseHint==1 || bUseHint==0 );
  170284. if( iIdx==0 || (bUseHint && iIdx==1) ){
  170285. int bIgnore = 0;
  170286. rc = fts3SegmentIsMaxLevel(p, iAbsLevel+1, &bIgnore);
  170287. if( bIgnore ){
  170288. pFilter->flags |= FTS3_SEGMENT_IGNORE_EMPTY;
  170289. }
  170290. }
  170291. }
  170292. if( rc==SQLITE_OK ){
  170293. rc = fts3IncrmergeCsr(p, iAbsLevel, nSeg, pCsr);
  170294. }
  170295. if( SQLITE_OK==rc && pCsr->nSegment==nSeg
  170296. && SQLITE_OK==(rc = sqlite3Fts3SegReaderStart(p, pCsr, pFilter))
  170297. ){
  170298. int bEmpty = 0;
  170299. rc = sqlite3Fts3SegReaderStep(p, pCsr);
  170300. if( rc==SQLITE_OK ){
  170301. bEmpty = 1;
  170302. }else if( rc!=SQLITE_ROW ){
  170303. sqlite3Fts3SegReaderFinish(pCsr);
  170304. break;
  170305. }
  170306. if( bUseHint && iIdx>0 ){
  170307. const char *zKey = pCsr->zTerm;
  170308. int nKey = pCsr->nTerm;
  170309. rc = fts3IncrmergeLoad(p, iAbsLevel, iIdx-1, zKey, nKey, pWriter);
  170310. }else{
  170311. rc = fts3IncrmergeWriter(p, iAbsLevel, iIdx, pCsr, pWriter);
  170312. }
  170313. if( rc==SQLITE_OK && pWriter->nLeafEst ){
  170314. fts3LogMerge(nSeg, iAbsLevel);
  170315. if( bEmpty==0 ){
  170316. do {
  170317. rc = fts3IncrmergeAppend(p, pWriter, pCsr);
  170318. if( rc==SQLITE_OK ) rc = sqlite3Fts3SegReaderStep(p, pCsr);
  170319. if( pWriter->nWork>=nRem && rc==SQLITE_ROW ) rc = SQLITE_OK;
  170320. }while( rc==SQLITE_ROW );
  170321. }
  170322. /* Update or delete the input segments */
  170323. if( rc==SQLITE_OK ){
  170324. nRem -= (1 + pWriter->nWork);
  170325. rc = fts3IncrmergeChomp(p, iAbsLevel, pCsr, &nSeg);
  170326. if( nSeg!=0 ){
  170327. bDirtyHint = 1;
  170328. fts3IncrmergeHintPush(&hint, iAbsLevel, nSeg, &rc);
  170329. }
  170330. }
  170331. }
  170332. if( nSeg!=0 ){
  170333. pWriter->nLeafData = pWriter->nLeafData * -1;
  170334. }
  170335. fts3IncrmergeRelease(p, pWriter, &rc);
  170336. if( nSeg==0 && pWriter->bNoLeafData==0 ){
  170337. fts3PromoteSegments(p, iAbsLevel+1, pWriter->nLeafData);
  170338. }
  170339. }
  170340. sqlite3Fts3SegReaderFinish(pCsr);
  170341. }
  170342. /* Write the hint values into the %_stat table for the next incr-merger */
  170343. if( bDirtyHint && rc==SQLITE_OK ){
  170344. rc = fts3IncrmergeHintStore(p, &hint);
  170345. }
  170346. sqlite3_free(pWriter);
  170347. sqlite3_free(hint.a);
  170348. return rc;
  170349. }
  170350. /*
  170351. ** Convert the text beginning at *pz into an integer and return
  170352. ** its value. Advance *pz to point to the first character past
  170353. ** the integer.
  170354. **
  170355. ** This function used for parameters to merge= and incrmerge=
  170356. ** commands.
  170357. */
  170358. static int fts3Getint(const char **pz){
  170359. const char *z = *pz;
  170360. int i = 0;
  170361. while( (*z)>='0' && (*z)<='9' && i<214748363 ) i = 10*i + *(z++) - '0';
  170362. *pz = z;
  170363. return i;
  170364. }
  170365. /*
  170366. ** Process statements of the form:
  170367. **
  170368. ** INSERT INTO table(table) VALUES('merge=A,B');
  170369. **
  170370. ** A and B are integers that decode to be the number of leaf pages
  170371. ** written for the merge, and the minimum number of segments on a level
  170372. ** before it will be selected for a merge, respectively.
  170373. */
  170374. static int fts3DoIncrmerge(
  170375. Fts3Table *p, /* FTS3 table handle */
  170376. const char *zParam /* Nul-terminated string containing "A,B" */
  170377. ){
  170378. int rc;
  170379. int nMin = (MergeCount(p) / 2);
  170380. int nMerge = 0;
  170381. const char *z = zParam;
  170382. /* Read the first integer value */
  170383. nMerge = fts3Getint(&z);
  170384. /* If the first integer value is followed by a ',', read the second
  170385. ** integer value. */
  170386. if( z[0]==',' && z[1]!='\0' ){
  170387. z++;
  170388. nMin = fts3Getint(&z);
  170389. }
  170390. if( z[0]!='\0' || nMin<2 ){
  170391. rc = SQLITE_ERROR;
  170392. }else{
  170393. rc = SQLITE_OK;
  170394. if( !p->bHasStat ){
  170395. assert( p->bFts4==0 );
  170396. sqlite3Fts3CreateStatTable(&rc, p);
  170397. }
  170398. if( rc==SQLITE_OK ){
  170399. rc = sqlite3Fts3Incrmerge(p, nMerge, nMin);
  170400. }
  170401. sqlite3Fts3SegmentsClose(p);
  170402. }
  170403. return rc;
  170404. }
  170405. /*
  170406. ** Process statements of the form:
  170407. **
  170408. ** INSERT INTO table(table) VALUES('automerge=X');
  170409. **
  170410. ** where X is an integer. X==0 means to turn automerge off. X!=0 means
  170411. ** turn it on. The setting is persistent.
  170412. */
  170413. static int fts3DoAutoincrmerge(
  170414. Fts3Table *p, /* FTS3 table handle */
  170415. const char *zParam /* Nul-terminated string containing boolean */
  170416. ){
  170417. int rc = SQLITE_OK;
  170418. sqlite3_stmt *pStmt = 0;
  170419. p->nAutoincrmerge = fts3Getint(&zParam);
  170420. if( p->nAutoincrmerge==1 || p->nAutoincrmerge>MergeCount(p) ){
  170421. p->nAutoincrmerge = 8;
  170422. }
  170423. if( !p->bHasStat ){
  170424. assert( p->bFts4==0 );
  170425. sqlite3Fts3CreateStatTable(&rc, p);
  170426. if( rc ) return rc;
  170427. }
  170428. rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
  170429. if( rc ) return rc;
  170430. sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
  170431. sqlite3_bind_int(pStmt, 2, p->nAutoincrmerge);
  170432. sqlite3_step(pStmt);
  170433. rc = sqlite3_reset(pStmt);
  170434. return rc;
  170435. }
  170436. /*
  170437. ** Return a 64-bit checksum for the FTS index entry specified by the
  170438. ** arguments to this function.
  170439. */
  170440. static u64 fts3ChecksumEntry(
  170441. const char *zTerm, /* Pointer to buffer containing term */
  170442. int nTerm, /* Size of zTerm in bytes */
  170443. int iLangid, /* Language id for current row */
  170444. int iIndex, /* Index (0..Fts3Table.nIndex-1) */
  170445. i64 iDocid, /* Docid for current row. */
  170446. int iCol, /* Column number */
  170447. int iPos /* Position */
  170448. ){
  170449. int i;
  170450. u64 ret = (u64)iDocid;
  170451. ret += (ret<<3) + iLangid;
  170452. ret += (ret<<3) + iIndex;
  170453. ret += (ret<<3) + iCol;
  170454. ret += (ret<<3) + iPos;
  170455. for(i=0; i<nTerm; i++) ret += (ret<<3) + zTerm[i];
  170456. return ret;
  170457. }
  170458. /*
  170459. ** Return a checksum of all entries in the FTS index that correspond to
  170460. ** language id iLangid. The checksum is calculated by XORing the checksums
  170461. ** of each individual entry (see fts3ChecksumEntry()) together.
  170462. **
  170463. ** If successful, the checksum value is returned and *pRc set to SQLITE_OK.
  170464. ** Otherwise, if an error occurs, *pRc is set to an SQLite error code. The
  170465. ** return value is undefined in this case.
  170466. */
  170467. static u64 fts3ChecksumIndex(
  170468. Fts3Table *p, /* FTS3 table handle */
  170469. int iLangid, /* Language id to return cksum for */
  170470. int iIndex, /* Index to cksum (0..p->nIndex-1) */
  170471. int *pRc /* OUT: Return code */
  170472. ){
  170473. Fts3SegFilter filter;
  170474. Fts3MultiSegReader csr;
  170475. int rc;
  170476. u64 cksum = 0;
  170477. assert( *pRc==SQLITE_OK );
  170478. memset(&filter, 0, sizeof(filter));
  170479. memset(&csr, 0, sizeof(csr));
  170480. filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
  170481. filter.flags |= FTS3_SEGMENT_SCAN;
  170482. rc = sqlite3Fts3SegReaderCursor(
  170483. p, iLangid, iIndex, FTS3_SEGCURSOR_ALL, 0, 0, 0, 1,&csr
  170484. );
  170485. if( rc==SQLITE_OK ){
  170486. rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
  170487. }
  170488. if( rc==SQLITE_OK ){
  170489. while( SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, &csr)) ){
  170490. char *pCsr = csr.aDoclist;
  170491. char *pEnd = &pCsr[csr.nDoclist];
  170492. i64 iDocid = 0;
  170493. i64 iCol = 0;
  170494. u64 iPos = 0;
  170495. pCsr += sqlite3Fts3GetVarint(pCsr, &iDocid);
  170496. while( pCsr<pEnd ){
  170497. u64 iVal = 0;
  170498. pCsr += sqlite3Fts3GetVarintU(pCsr, &iVal);
  170499. if( pCsr<pEnd ){
  170500. if( iVal==0 || iVal==1 ){
  170501. iCol = 0;
  170502. iPos = 0;
  170503. if( iVal ){
  170504. pCsr += sqlite3Fts3GetVarint(pCsr, &iCol);
  170505. }else{
  170506. pCsr += sqlite3Fts3GetVarintU(pCsr, &iVal);
  170507. if( p->bDescIdx ){
  170508. iDocid = (i64)((u64)iDocid - iVal);
  170509. }else{
  170510. iDocid = (i64)((u64)iDocid + iVal);
  170511. }
  170512. }
  170513. }else{
  170514. iPos += (iVal - 2);
  170515. cksum = cksum ^ fts3ChecksumEntry(
  170516. csr.zTerm, csr.nTerm, iLangid, iIndex, iDocid,
  170517. (int)iCol, (int)iPos
  170518. );
  170519. }
  170520. }
  170521. }
  170522. }
  170523. }
  170524. sqlite3Fts3SegReaderFinish(&csr);
  170525. *pRc = rc;
  170526. return cksum;
  170527. }
  170528. /*
  170529. ** Check if the contents of the FTS index match the current contents of the
  170530. ** content table. If no error occurs and the contents do match, set *pbOk
  170531. ** to true and return SQLITE_OK. Or if the contents do not match, set *pbOk
  170532. ** to false before returning.
  170533. **
  170534. ** If an error occurs (e.g. an OOM or IO error), return an SQLite error
  170535. ** code. The final value of *pbOk is undefined in this case.
  170536. */
  170537. static int fts3IntegrityCheck(Fts3Table *p, int *pbOk){
  170538. int rc = SQLITE_OK; /* Return code */
  170539. u64 cksum1 = 0; /* Checksum based on FTS index contents */
  170540. u64 cksum2 = 0; /* Checksum based on %_content contents */
  170541. sqlite3_stmt *pAllLangid = 0; /* Statement to return all language-ids */
  170542. /* This block calculates the checksum according to the FTS index. */
  170543. rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
  170544. if( rc==SQLITE_OK ){
  170545. int rc2;
  170546. sqlite3_bind_int(pAllLangid, 1, p->iPrevLangid);
  170547. sqlite3_bind_int(pAllLangid, 2, p->nIndex);
  170548. while( rc==SQLITE_OK && sqlite3_step(pAllLangid)==SQLITE_ROW ){
  170549. int iLangid = sqlite3_column_int(pAllLangid, 0);
  170550. int i;
  170551. for(i=0; i<p->nIndex; i++){
  170552. cksum1 = cksum1 ^ fts3ChecksumIndex(p, iLangid, i, &rc);
  170553. }
  170554. }
  170555. rc2 = sqlite3_reset(pAllLangid);
  170556. if( rc==SQLITE_OK ) rc = rc2;
  170557. }
  170558. /* This block calculates the checksum according to the %_content table */
  170559. if( rc==SQLITE_OK ){
  170560. sqlite3_tokenizer_module const *pModule = p->pTokenizer->pModule;
  170561. sqlite3_stmt *pStmt = 0;
  170562. char *zSql;
  170563. zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
  170564. if( !zSql ){
  170565. rc = SQLITE_NOMEM;
  170566. }else{
  170567. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  170568. sqlite3_free(zSql);
  170569. }
  170570. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  170571. i64 iDocid = sqlite3_column_int64(pStmt, 0);
  170572. int iLang = langidFromSelect(p, pStmt);
  170573. int iCol;
  170574. for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
  170575. if( p->abNotindexed[iCol]==0 ){
  170576. const char *zText = (const char *)sqlite3_column_text(pStmt, iCol+1);
  170577. sqlite3_tokenizer_cursor *pT = 0;
  170578. rc = sqlite3Fts3OpenTokenizer(p->pTokenizer, iLang, zText, -1, &pT);
  170579. while( rc==SQLITE_OK ){
  170580. char const *zToken; /* Buffer containing token */
  170581. int nToken = 0; /* Number of bytes in token */
  170582. int iDum1 = 0, iDum2 = 0; /* Dummy variables */
  170583. int iPos = 0; /* Position of token in zText */
  170584. rc = pModule->xNext(pT, &zToken, &nToken, &iDum1, &iDum2, &iPos);
  170585. if( rc==SQLITE_OK ){
  170586. int i;
  170587. cksum2 = cksum2 ^ fts3ChecksumEntry(
  170588. zToken, nToken, iLang, 0, iDocid, iCol, iPos
  170589. );
  170590. for(i=1; i<p->nIndex; i++){
  170591. if( p->aIndex[i].nPrefix<=nToken ){
  170592. cksum2 = cksum2 ^ fts3ChecksumEntry(
  170593. zToken, p->aIndex[i].nPrefix, iLang, i, iDocid, iCol, iPos
  170594. );
  170595. }
  170596. }
  170597. }
  170598. }
  170599. if( pT ) pModule->xClose(pT);
  170600. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  170601. }
  170602. }
  170603. }
  170604. sqlite3_finalize(pStmt);
  170605. }
  170606. *pbOk = (cksum1==cksum2);
  170607. return rc;
  170608. }
  170609. /*
  170610. ** Run the integrity-check. If no error occurs and the current contents of
  170611. ** the FTS index are correct, return SQLITE_OK. Or, if the contents of the
  170612. ** FTS index are incorrect, return SQLITE_CORRUPT_VTAB.
  170613. **
  170614. ** Or, if an error (e.g. an OOM or IO error) occurs, return an SQLite
  170615. ** error code.
  170616. **
  170617. ** The integrity-check works as follows. For each token and indexed token
  170618. ** prefix in the document set, a 64-bit checksum is calculated (by code
  170619. ** in fts3ChecksumEntry()) based on the following:
  170620. **
  170621. ** + The index number (0 for the main index, 1 for the first prefix
  170622. ** index etc.),
  170623. ** + The token (or token prefix) text itself,
  170624. ** + The language-id of the row it appears in,
  170625. ** + The docid of the row it appears in,
  170626. ** + The column it appears in, and
  170627. ** + The tokens position within that column.
  170628. **
  170629. ** The checksums for all entries in the index are XORed together to create
  170630. ** a single checksum for the entire index.
  170631. **
  170632. ** The integrity-check code calculates the same checksum in two ways:
  170633. **
  170634. ** 1. By scanning the contents of the FTS index, and
  170635. ** 2. By scanning and tokenizing the content table.
  170636. **
  170637. ** If the two checksums are identical, the integrity-check is deemed to have
  170638. ** passed.
  170639. */
  170640. static int fts3DoIntegrityCheck(
  170641. Fts3Table *p /* FTS3 table handle */
  170642. ){
  170643. int rc;
  170644. int bOk = 0;
  170645. rc = fts3IntegrityCheck(p, &bOk);
  170646. if( rc==SQLITE_OK && bOk==0 ) rc = FTS_CORRUPT_VTAB;
  170647. return rc;
  170648. }
  170649. /*
  170650. ** Handle a 'special' INSERT of the form:
  170651. **
  170652. ** "INSERT INTO tbl(tbl) VALUES(<expr>)"
  170653. **
  170654. ** Argument pVal contains the result of <expr>. Currently the only
  170655. ** meaningful value to insert is the text 'optimize'.
  170656. */
  170657. static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){
  170658. int rc = SQLITE_ERROR; /* Return Code */
  170659. const char *zVal = (const char *)sqlite3_value_text(pVal);
  170660. int nVal = sqlite3_value_bytes(pVal);
  170661. if( !zVal ){
  170662. return SQLITE_NOMEM;
  170663. }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, "optimize", 8) ){
  170664. rc = fts3DoOptimize(p, 0);
  170665. }else if( nVal==7 && 0==sqlite3_strnicmp(zVal, "rebuild", 7) ){
  170666. rc = fts3DoRebuild(p);
  170667. }else if( nVal==15 && 0==sqlite3_strnicmp(zVal, "integrity-check", 15) ){
  170668. rc = fts3DoIntegrityCheck(p);
  170669. }else if( nVal>6 && 0==sqlite3_strnicmp(zVal, "merge=", 6) ){
  170670. rc = fts3DoIncrmerge(p, &zVal[6]);
  170671. }else if( nVal>10 && 0==sqlite3_strnicmp(zVal, "automerge=", 10) ){
  170672. rc = fts3DoAutoincrmerge(p, &zVal[10]);
  170673. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  170674. }else{
  170675. int v;
  170676. if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){
  170677. v = atoi(&zVal[9]);
  170678. if( v>=24 && v<=p->nPgsz-35 ) p->nNodeSize = v;
  170679. rc = SQLITE_OK;
  170680. }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){
  170681. v = atoi(&zVal[11]);
  170682. if( v>=64 && v<=FTS3_MAX_PENDING_DATA ) p->nMaxPendingData = v;
  170683. rc = SQLITE_OK;
  170684. }else if( nVal>21 && 0==sqlite3_strnicmp(zVal,"test-no-incr-doclist=",21) ){
  170685. p->bNoIncrDoclist = atoi(&zVal[21]);
  170686. rc = SQLITE_OK;
  170687. }else if( nVal>11 && 0==sqlite3_strnicmp(zVal,"mergecount=",11) ){
  170688. v = atoi(&zVal[11]);
  170689. if( v>=4 && v<=FTS3_MERGE_COUNT && (v&1)==0 ) p->nMergeCount = v;
  170690. rc = SQLITE_OK;
  170691. }
  170692. #endif
  170693. }
  170694. return rc;
  170695. }
  170696. #ifndef SQLITE_DISABLE_FTS4_DEFERRED
  170697. /*
  170698. ** Delete all cached deferred doclists. Deferred doclists are cached
  170699. ** (allocated) by the sqlite3Fts3CacheDeferredDoclists() function.
  170700. */
  170701. SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *pCsr){
  170702. Fts3DeferredToken *pDef;
  170703. for(pDef=pCsr->pDeferred; pDef; pDef=pDef->pNext){
  170704. fts3PendingListDelete(pDef->pList);
  170705. pDef->pList = 0;
  170706. }
  170707. }
  170708. /*
  170709. ** Free all entries in the pCsr->pDeffered list. Entries are added to
  170710. ** this list using sqlite3Fts3DeferToken().
  170711. */
  170712. SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *pCsr){
  170713. Fts3DeferredToken *pDef;
  170714. Fts3DeferredToken *pNext;
  170715. for(pDef=pCsr->pDeferred; pDef; pDef=pNext){
  170716. pNext = pDef->pNext;
  170717. fts3PendingListDelete(pDef->pList);
  170718. sqlite3_free(pDef);
  170719. }
  170720. pCsr->pDeferred = 0;
  170721. }
  170722. /*
  170723. ** Generate deferred-doclists for all tokens in the pCsr->pDeferred list
  170724. ** based on the row that pCsr currently points to.
  170725. **
  170726. ** A deferred-doclist is like any other doclist with position information
  170727. ** included, except that it only contains entries for a single row of the
  170728. ** table, not for all rows.
  170729. */
  170730. SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *pCsr){
  170731. int rc = SQLITE_OK; /* Return code */
  170732. if( pCsr->pDeferred ){
  170733. int i; /* Used to iterate through table columns */
  170734. sqlite3_int64 iDocid; /* Docid of the row pCsr points to */
  170735. Fts3DeferredToken *pDef; /* Used to iterate through deferred tokens */
  170736. Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
  170737. sqlite3_tokenizer *pT = p->pTokenizer;
  170738. sqlite3_tokenizer_module const *pModule = pT->pModule;
  170739. assert( pCsr->isRequireSeek==0 );
  170740. iDocid = sqlite3_column_int64(pCsr->pStmt, 0);
  170741. for(i=0; i<p->nColumn && rc==SQLITE_OK; i++){
  170742. if( p->abNotindexed[i]==0 ){
  170743. const char *zText = (const char *)sqlite3_column_text(pCsr->pStmt, i+1);
  170744. sqlite3_tokenizer_cursor *pTC = 0;
  170745. rc = sqlite3Fts3OpenTokenizer(pT, pCsr->iLangid, zText, -1, &pTC);
  170746. while( rc==SQLITE_OK ){
  170747. char const *zToken; /* Buffer containing token */
  170748. int nToken = 0; /* Number of bytes in token */
  170749. int iDum1 = 0, iDum2 = 0; /* Dummy variables */
  170750. int iPos = 0; /* Position of token in zText */
  170751. rc = pModule->xNext(pTC, &zToken, &nToken, &iDum1, &iDum2, &iPos);
  170752. for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
  170753. Fts3PhraseToken *pPT = pDef->pToken;
  170754. if( (pDef->iCol>=p->nColumn || pDef->iCol==i)
  170755. && (pPT->bFirst==0 || iPos==0)
  170756. && (pPT->n==nToken || (pPT->isPrefix && pPT->n<nToken))
  170757. && (0==memcmp(zToken, pPT->z, pPT->n))
  170758. ){
  170759. fts3PendingListAppend(&pDef->pList, iDocid, i, iPos, &rc);
  170760. }
  170761. }
  170762. }
  170763. if( pTC ) pModule->xClose(pTC);
  170764. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  170765. }
  170766. }
  170767. for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
  170768. if( pDef->pList ){
  170769. rc = fts3PendingListAppendVarint(&pDef->pList, 0);
  170770. }
  170771. }
  170772. }
  170773. return rc;
  170774. }
  170775. SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(
  170776. Fts3DeferredToken *p,
  170777. char **ppData,
  170778. int *pnData
  170779. ){
  170780. char *pRet;
  170781. int nSkip;
  170782. sqlite3_int64 dummy;
  170783. *ppData = 0;
  170784. *pnData = 0;
  170785. if( p->pList==0 ){
  170786. return SQLITE_OK;
  170787. }
  170788. pRet = (char *)sqlite3_malloc(p->pList->nData);
  170789. if( !pRet ) return SQLITE_NOMEM;
  170790. nSkip = sqlite3Fts3GetVarint(p->pList->aData, &dummy);
  170791. *pnData = p->pList->nData - nSkip;
  170792. *ppData = pRet;
  170793. memcpy(pRet, &p->pList->aData[nSkip], *pnData);
  170794. return SQLITE_OK;
  170795. }
  170796. /*
  170797. ** Add an entry for token pToken to the pCsr->pDeferred list.
  170798. */
  170799. SQLITE_PRIVATE int sqlite3Fts3DeferToken(
  170800. Fts3Cursor *pCsr, /* Fts3 table cursor */
  170801. Fts3PhraseToken *pToken, /* Token to defer */
  170802. int iCol /* Column that token must appear in (or -1) */
  170803. ){
  170804. Fts3DeferredToken *pDeferred;
  170805. pDeferred = sqlite3_malloc(sizeof(*pDeferred));
  170806. if( !pDeferred ){
  170807. return SQLITE_NOMEM;
  170808. }
  170809. memset(pDeferred, 0, sizeof(*pDeferred));
  170810. pDeferred->pToken = pToken;
  170811. pDeferred->pNext = pCsr->pDeferred;
  170812. pDeferred->iCol = iCol;
  170813. pCsr->pDeferred = pDeferred;
  170814. assert( pToken->pDeferred==0 );
  170815. pToken->pDeferred = pDeferred;
  170816. return SQLITE_OK;
  170817. }
  170818. #endif
  170819. /*
  170820. ** SQLite value pRowid contains the rowid of a row that may or may not be
  170821. ** present in the FTS3 table. If it is, delete it and adjust the contents
  170822. ** of subsiduary data structures accordingly.
  170823. */
  170824. static int fts3DeleteByRowid(
  170825. Fts3Table *p,
  170826. sqlite3_value *pRowid,
  170827. int *pnChng, /* IN/OUT: Decrement if row is deleted */
  170828. u32 *aSzDel
  170829. ){
  170830. int rc = SQLITE_OK; /* Return code */
  170831. int bFound = 0; /* True if *pRowid really is in the table */
  170832. fts3DeleteTerms(&rc, p, pRowid, aSzDel, &bFound);
  170833. if( bFound && rc==SQLITE_OK ){
  170834. int isEmpty = 0; /* Deleting *pRowid leaves the table empty */
  170835. rc = fts3IsEmpty(p, pRowid, &isEmpty);
  170836. if( rc==SQLITE_OK ){
  170837. if( isEmpty ){
  170838. /* Deleting this row means the whole table is empty. In this case
  170839. ** delete the contents of all three tables and throw away any
  170840. ** data in the pendingTerms hash table. */
  170841. rc = fts3DeleteAll(p, 1);
  170842. *pnChng = 0;
  170843. memset(aSzDel, 0, sizeof(u32) * (p->nColumn+1) * 2);
  170844. }else{
  170845. *pnChng = *pnChng - 1;
  170846. if( p->zContentTbl==0 ){
  170847. fts3SqlExec(&rc, p, SQL_DELETE_CONTENT, &pRowid);
  170848. }
  170849. if( p->bHasDocsize ){
  170850. fts3SqlExec(&rc, p, SQL_DELETE_DOCSIZE, &pRowid);
  170851. }
  170852. }
  170853. }
  170854. }
  170855. return rc;
  170856. }
  170857. /*
  170858. ** This function does the work for the xUpdate method of FTS3 virtual
  170859. ** tables. The schema of the virtual table being:
  170860. **
  170861. ** CREATE TABLE <table name>(
  170862. ** <user columns>,
  170863. ** <table name> HIDDEN,
  170864. ** docid HIDDEN,
  170865. ** <langid> HIDDEN
  170866. ** );
  170867. **
  170868. **
  170869. */
  170870. SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(
  170871. sqlite3_vtab *pVtab, /* FTS3 vtab object */
  170872. int nArg, /* Size of argument array */
  170873. sqlite3_value **apVal, /* Array of arguments */
  170874. sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */
  170875. ){
  170876. Fts3Table *p = (Fts3Table *)pVtab;
  170877. int rc = SQLITE_OK; /* Return Code */
  170878. u32 *aSzIns = 0; /* Sizes of inserted documents */
  170879. u32 *aSzDel = 0; /* Sizes of deleted documents */
  170880. int nChng = 0; /* Net change in number of documents */
  170881. int bInsertDone = 0;
  170882. /* At this point it must be known if the %_stat table exists or not.
  170883. ** So bHasStat may not be 2. */
  170884. assert( p->bHasStat==0 || p->bHasStat==1 );
  170885. assert( p->pSegments==0 );
  170886. assert(
  170887. nArg==1 /* DELETE operations */
  170888. || nArg==(2 + p->nColumn + 3) /* INSERT or UPDATE operations */
  170889. );
  170890. /* Check for a "special" INSERT operation. One of the form:
  170891. **
  170892. ** INSERT INTO xyz(xyz) VALUES('command');
  170893. */
  170894. if( nArg>1
  170895. && sqlite3_value_type(apVal[0])==SQLITE_NULL
  170896. && sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL
  170897. ){
  170898. rc = fts3SpecialInsert(p, apVal[p->nColumn+2]);
  170899. goto update_out;
  170900. }
  170901. if( nArg>1 && sqlite3_value_int(apVal[2 + p->nColumn + 2])<0 ){
  170902. rc = SQLITE_CONSTRAINT;
  170903. goto update_out;
  170904. }
  170905. /* Allocate space to hold the change in document sizes */
  170906. aSzDel = sqlite3_malloc64(sizeof(aSzDel[0])*((sqlite3_int64)p->nColumn+1)*2);
  170907. if( aSzDel==0 ){
  170908. rc = SQLITE_NOMEM;
  170909. goto update_out;
  170910. }
  170911. aSzIns = &aSzDel[p->nColumn+1];
  170912. memset(aSzDel, 0, sizeof(aSzDel[0])*(p->nColumn+1)*2);
  170913. rc = fts3Writelock(p);
  170914. if( rc!=SQLITE_OK ) goto update_out;
  170915. /* If this is an INSERT operation, or an UPDATE that modifies the rowid
  170916. ** value, then this operation requires constraint handling.
  170917. **
  170918. ** If the on-conflict mode is REPLACE, this means that the existing row
  170919. ** should be deleted from the database before inserting the new row. Or,
  170920. ** if the on-conflict mode is other than REPLACE, then this method must
  170921. ** detect the conflict and return SQLITE_CONSTRAINT before beginning to
  170922. ** modify the database file.
  170923. */
  170924. if( nArg>1 && p->zContentTbl==0 ){
  170925. /* Find the value object that holds the new rowid value. */
  170926. sqlite3_value *pNewRowid = apVal[3+p->nColumn];
  170927. if( sqlite3_value_type(pNewRowid)==SQLITE_NULL ){
  170928. pNewRowid = apVal[1];
  170929. }
  170930. if( sqlite3_value_type(pNewRowid)!=SQLITE_NULL && (
  170931. sqlite3_value_type(apVal[0])==SQLITE_NULL
  170932. || sqlite3_value_int64(apVal[0])!=sqlite3_value_int64(pNewRowid)
  170933. )){
  170934. /* The new rowid is not NULL (in this case the rowid will be
  170935. ** automatically assigned and there is no chance of a conflict), and
  170936. ** the statement is either an INSERT or an UPDATE that modifies the
  170937. ** rowid column. So if the conflict mode is REPLACE, then delete any
  170938. ** existing row with rowid=pNewRowid.
  170939. **
  170940. ** Or, if the conflict mode is not REPLACE, insert the new record into
  170941. ** the %_content table. If we hit the duplicate rowid constraint (or any
  170942. ** other error) while doing so, return immediately.
  170943. **
  170944. ** This branch may also run if pNewRowid contains a value that cannot
  170945. ** be losslessly converted to an integer. In this case, the eventual
  170946. ** call to fts3InsertData() (either just below or further on in this
  170947. ** function) will return SQLITE_MISMATCH. If fts3DeleteByRowid is
  170948. ** invoked, it will delete zero rows (since no row will have
  170949. ** docid=$pNewRowid if $pNewRowid is not an integer value).
  170950. */
  170951. if( sqlite3_vtab_on_conflict(p->db)==SQLITE_REPLACE ){
  170952. rc = fts3DeleteByRowid(p, pNewRowid, &nChng, aSzDel);
  170953. }else{
  170954. rc = fts3InsertData(p, apVal, pRowid);
  170955. bInsertDone = 1;
  170956. }
  170957. }
  170958. }
  170959. if( rc!=SQLITE_OK ){
  170960. goto update_out;
  170961. }
  170962. /* If this is a DELETE or UPDATE operation, remove the old record. */
  170963. if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
  170964. assert( sqlite3_value_type(apVal[0])==SQLITE_INTEGER );
  170965. rc = fts3DeleteByRowid(p, apVal[0], &nChng, aSzDel);
  170966. }
  170967. /* If this is an INSERT or UPDATE operation, insert the new record. */
  170968. if( nArg>1 && rc==SQLITE_OK ){
  170969. int iLangid = sqlite3_value_int(apVal[2 + p->nColumn + 2]);
  170970. if( bInsertDone==0 ){
  170971. rc = fts3InsertData(p, apVal, pRowid);
  170972. if( rc==SQLITE_CONSTRAINT && p->zContentTbl==0 ){
  170973. rc = FTS_CORRUPT_VTAB;
  170974. }
  170975. }
  170976. if( rc==SQLITE_OK ){
  170977. rc = fts3PendingTermsDocid(p, 0, iLangid, *pRowid);
  170978. }
  170979. if( rc==SQLITE_OK ){
  170980. assert( p->iPrevDocid==*pRowid );
  170981. rc = fts3InsertTerms(p, iLangid, apVal, aSzIns);
  170982. }
  170983. if( p->bHasDocsize ){
  170984. fts3InsertDocsize(&rc, p, aSzIns);
  170985. }
  170986. nChng++;
  170987. }
  170988. if( p->bFts4 ){
  170989. fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nChng);
  170990. }
  170991. update_out:
  170992. sqlite3_free(aSzDel);
  170993. sqlite3Fts3SegmentsClose(p);
  170994. return rc;
  170995. }
  170996. /*
  170997. ** Flush any data in the pending-terms hash table to disk. If successful,
  170998. ** merge all segments in the database (including the new segment, if
  170999. ** there was any data to flush) into a single segment.
  171000. */
  171001. SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *p){
  171002. int rc;
  171003. rc = sqlite3_exec(p->db, "SAVEPOINT fts3", 0, 0, 0);
  171004. if( rc==SQLITE_OK ){
  171005. rc = fts3DoOptimize(p, 1);
  171006. if( rc==SQLITE_OK || rc==SQLITE_DONE ){
  171007. int rc2 = sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
  171008. if( rc2!=SQLITE_OK ) rc = rc2;
  171009. }else{
  171010. sqlite3_exec(p->db, "ROLLBACK TO fts3", 0, 0, 0);
  171011. sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
  171012. }
  171013. }
  171014. sqlite3Fts3SegmentsClose(p);
  171015. return rc;
  171016. }
  171017. #endif
  171018. /************** End of fts3_write.c ******************************************/
  171019. /************** Begin file fts3_snippet.c ************************************/
  171020. /*
  171021. ** 2009 Oct 23
  171022. **
  171023. ** The author disclaims copyright to this source code. In place of
  171024. ** a legal notice, here is a blessing:
  171025. **
  171026. ** May you do good and not evil.
  171027. ** May you find forgiveness for yourself and forgive others.
  171028. ** May you share freely, never taking more than you give.
  171029. **
  171030. ******************************************************************************
  171031. */
  171032. /* #include "fts3Int.h" */
  171033. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  171034. /* #include <string.h> */
  171035. /* #include <assert.h> */
  171036. /*
  171037. ** Characters that may appear in the second argument to matchinfo().
  171038. */
  171039. #define FTS3_MATCHINFO_NPHRASE 'p' /* 1 value */
  171040. #define FTS3_MATCHINFO_NCOL 'c' /* 1 value */
  171041. #define FTS3_MATCHINFO_NDOC 'n' /* 1 value */
  171042. #define FTS3_MATCHINFO_AVGLENGTH 'a' /* nCol values */
  171043. #define FTS3_MATCHINFO_LENGTH 'l' /* nCol values */
  171044. #define FTS3_MATCHINFO_LCS 's' /* nCol values */
  171045. #define FTS3_MATCHINFO_HITS 'x' /* 3*nCol*nPhrase values */
  171046. #define FTS3_MATCHINFO_LHITS 'y' /* nCol*nPhrase values */
  171047. #define FTS3_MATCHINFO_LHITS_BM 'b' /* nCol*nPhrase values */
  171048. /*
  171049. ** The default value for the second argument to matchinfo().
  171050. */
  171051. #define FTS3_MATCHINFO_DEFAULT "pcx"
  171052. /*
  171053. ** Used as an fts3ExprIterate() context when loading phrase doclists to
  171054. ** Fts3Expr.aDoclist[]/nDoclist.
  171055. */
  171056. typedef struct LoadDoclistCtx LoadDoclistCtx;
  171057. struct LoadDoclistCtx {
  171058. Fts3Cursor *pCsr; /* FTS3 Cursor */
  171059. int nPhrase; /* Number of phrases seen so far */
  171060. int nToken; /* Number of tokens seen so far */
  171061. };
  171062. /*
  171063. ** The following types are used as part of the implementation of the
  171064. ** fts3BestSnippet() routine.
  171065. */
  171066. typedef struct SnippetIter SnippetIter;
  171067. typedef struct SnippetPhrase SnippetPhrase;
  171068. typedef struct SnippetFragment SnippetFragment;
  171069. struct SnippetIter {
  171070. Fts3Cursor *pCsr; /* Cursor snippet is being generated from */
  171071. int iCol; /* Extract snippet from this column */
  171072. int nSnippet; /* Requested snippet length (in tokens) */
  171073. int nPhrase; /* Number of phrases in query */
  171074. SnippetPhrase *aPhrase; /* Array of size nPhrase */
  171075. int iCurrent; /* First token of current snippet */
  171076. };
  171077. struct SnippetPhrase {
  171078. int nToken; /* Number of tokens in phrase */
  171079. char *pList; /* Pointer to start of phrase position list */
  171080. int iHead; /* Next value in position list */
  171081. char *pHead; /* Position list data following iHead */
  171082. int iTail; /* Next value in trailing position list */
  171083. char *pTail; /* Position list data following iTail */
  171084. };
  171085. struct SnippetFragment {
  171086. int iCol; /* Column snippet is extracted from */
  171087. int iPos; /* Index of first token in snippet */
  171088. u64 covered; /* Mask of query phrases covered */
  171089. u64 hlmask; /* Mask of snippet terms to highlight */
  171090. };
  171091. /*
  171092. ** This type is used as an fts3ExprIterate() context object while
  171093. ** accumulating the data returned by the matchinfo() function.
  171094. */
  171095. typedef struct MatchInfo MatchInfo;
  171096. struct MatchInfo {
  171097. Fts3Cursor *pCursor; /* FTS3 Cursor */
  171098. int nCol; /* Number of columns in table */
  171099. int nPhrase; /* Number of matchable phrases in query */
  171100. sqlite3_int64 nDoc; /* Number of docs in database */
  171101. char flag;
  171102. u32 *aMatchinfo; /* Pre-allocated buffer */
  171103. };
  171104. /*
  171105. ** An instance of this structure is used to manage a pair of buffers, each
  171106. ** (nElem * sizeof(u32)) bytes in size. See the MatchinfoBuffer code below
  171107. ** for details.
  171108. */
  171109. struct MatchinfoBuffer {
  171110. u8 aRef[3];
  171111. int nElem;
  171112. int bGlobal; /* Set if global data is loaded */
  171113. char *zMatchinfo;
  171114. u32 aMatchinfo[1];
  171115. };
  171116. /*
  171117. ** The snippet() and offsets() functions both return text values. An instance
  171118. ** of the following structure is used to accumulate those values while the
  171119. ** functions are running. See fts3StringAppend() for details.
  171120. */
  171121. typedef struct StrBuffer StrBuffer;
  171122. struct StrBuffer {
  171123. char *z; /* Pointer to buffer containing string */
  171124. int n; /* Length of z in bytes (excl. nul-term) */
  171125. int nAlloc; /* Allocated size of buffer z in bytes */
  171126. };
  171127. /*************************************************************************
  171128. ** Start of MatchinfoBuffer code.
  171129. */
  171130. /*
  171131. ** Allocate a two-slot MatchinfoBuffer object.
  171132. */
  171133. static MatchinfoBuffer *fts3MIBufferNew(size_t nElem, const char *zMatchinfo){
  171134. MatchinfoBuffer *pRet;
  171135. sqlite3_int64 nByte = sizeof(u32) * (2*(sqlite3_int64)nElem + 1)
  171136. + sizeof(MatchinfoBuffer);
  171137. sqlite3_int64 nStr = strlen(zMatchinfo);
  171138. pRet = sqlite3_malloc64(nByte + nStr+1);
  171139. if( pRet ){
  171140. memset(pRet, 0, nByte);
  171141. pRet->aMatchinfo[0] = (u8*)(&pRet->aMatchinfo[1]) - (u8*)pRet;
  171142. pRet->aMatchinfo[1+nElem] = pRet->aMatchinfo[0]
  171143. + sizeof(u32)*((int)nElem+1);
  171144. pRet->nElem = (int)nElem;
  171145. pRet->zMatchinfo = ((char*)pRet) + nByte;
  171146. memcpy(pRet->zMatchinfo, zMatchinfo, nStr+1);
  171147. pRet->aRef[0] = 1;
  171148. }
  171149. return pRet;
  171150. }
  171151. static void fts3MIBufferFree(void *p){
  171152. MatchinfoBuffer *pBuf = (MatchinfoBuffer*)((u8*)p - ((u32*)p)[-1]);
  171153. assert( (u32*)p==&pBuf->aMatchinfo[1]
  171154. || (u32*)p==&pBuf->aMatchinfo[pBuf->nElem+2]
  171155. );
  171156. if( (u32*)p==&pBuf->aMatchinfo[1] ){
  171157. pBuf->aRef[1] = 0;
  171158. }else{
  171159. pBuf->aRef[2] = 0;
  171160. }
  171161. if( pBuf->aRef[0]==0 && pBuf->aRef[1]==0 && pBuf->aRef[2]==0 ){
  171162. sqlite3_free(pBuf);
  171163. }
  171164. }
  171165. static void (*fts3MIBufferAlloc(MatchinfoBuffer *p, u32 **paOut))(void*){
  171166. void (*xRet)(void*) = 0;
  171167. u32 *aOut = 0;
  171168. if( p->aRef[1]==0 ){
  171169. p->aRef[1] = 1;
  171170. aOut = &p->aMatchinfo[1];
  171171. xRet = fts3MIBufferFree;
  171172. }
  171173. else if( p->aRef[2]==0 ){
  171174. p->aRef[2] = 1;
  171175. aOut = &p->aMatchinfo[p->nElem+2];
  171176. xRet = fts3MIBufferFree;
  171177. }else{
  171178. aOut = (u32*)sqlite3_malloc64(p->nElem * sizeof(u32));
  171179. if( aOut ){
  171180. xRet = sqlite3_free;
  171181. if( p->bGlobal ) memcpy(aOut, &p->aMatchinfo[1], p->nElem*sizeof(u32));
  171182. }
  171183. }
  171184. *paOut = aOut;
  171185. return xRet;
  171186. }
  171187. static void fts3MIBufferSetGlobal(MatchinfoBuffer *p){
  171188. p->bGlobal = 1;
  171189. memcpy(&p->aMatchinfo[2+p->nElem], &p->aMatchinfo[1], p->nElem*sizeof(u32));
  171190. }
  171191. /*
  171192. ** Free a MatchinfoBuffer object allocated using fts3MIBufferNew()
  171193. */
  171194. SQLITE_PRIVATE void sqlite3Fts3MIBufferFree(MatchinfoBuffer *p){
  171195. if( p ){
  171196. assert( p->aRef[0]==1 );
  171197. p->aRef[0] = 0;
  171198. if( p->aRef[0]==0 && p->aRef[1]==0 && p->aRef[2]==0 ){
  171199. sqlite3_free(p);
  171200. }
  171201. }
  171202. }
  171203. /*
  171204. ** End of MatchinfoBuffer code.
  171205. *************************************************************************/
  171206. /*
  171207. ** This function is used to help iterate through a position-list. A position
  171208. ** list is a list of unique integers, sorted from smallest to largest. Each
  171209. ** element of the list is represented by an FTS3 varint that takes the value
  171210. ** of the difference between the current element and the previous one plus
  171211. ** two. For example, to store the position-list:
  171212. **
  171213. ** 4 9 113
  171214. **
  171215. ** the three varints:
  171216. **
  171217. ** 6 7 106
  171218. **
  171219. ** are encoded.
  171220. **
  171221. ** When this function is called, *pp points to the start of an element of
  171222. ** the list. *piPos contains the value of the previous entry in the list.
  171223. ** After it returns, *piPos contains the value of the next element of the
  171224. ** list and *pp is advanced to the following varint.
  171225. */
  171226. static void fts3GetDeltaPosition(char **pp, int *piPos){
  171227. int iVal;
  171228. *pp += fts3GetVarint32(*pp, &iVal);
  171229. *piPos += (iVal-2);
  171230. }
  171231. /*
  171232. ** Helper function for fts3ExprIterate() (see below).
  171233. */
  171234. static int fts3ExprIterate2(
  171235. Fts3Expr *pExpr, /* Expression to iterate phrases of */
  171236. int *piPhrase, /* Pointer to phrase counter */
  171237. int (*x)(Fts3Expr*,int,void*), /* Callback function to invoke for phrases */
  171238. void *pCtx /* Second argument to pass to callback */
  171239. ){
  171240. int rc; /* Return code */
  171241. int eType = pExpr->eType; /* Type of expression node pExpr */
  171242. if( eType!=FTSQUERY_PHRASE ){
  171243. assert( pExpr->pLeft && pExpr->pRight );
  171244. rc = fts3ExprIterate2(pExpr->pLeft, piPhrase, x, pCtx);
  171245. if( rc==SQLITE_OK && eType!=FTSQUERY_NOT ){
  171246. rc = fts3ExprIterate2(pExpr->pRight, piPhrase, x, pCtx);
  171247. }
  171248. }else{
  171249. rc = x(pExpr, *piPhrase, pCtx);
  171250. (*piPhrase)++;
  171251. }
  171252. return rc;
  171253. }
  171254. /*
  171255. ** Iterate through all phrase nodes in an FTS3 query, except those that
  171256. ** are part of a sub-tree that is the right-hand-side of a NOT operator.
  171257. ** For each phrase node found, the supplied callback function is invoked.
  171258. **
  171259. ** If the callback function returns anything other than SQLITE_OK,
  171260. ** the iteration is abandoned and the error code returned immediately.
  171261. ** Otherwise, SQLITE_OK is returned after a callback has been made for
  171262. ** all eligible phrase nodes.
  171263. */
  171264. static int fts3ExprIterate(
  171265. Fts3Expr *pExpr, /* Expression to iterate phrases of */
  171266. int (*x)(Fts3Expr*,int,void*), /* Callback function to invoke for phrases */
  171267. void *pCtx /* Second argument to pass to callback */
  171268. ){
  171269. int iPhrase = 0; /* Variable used as the phrase counter */
  171270. return fts3ExprIterate2(pExpr, &iPhrase, x, pCtx);
  171271. }
  171272. /*
  171273. ** This is an fts3ExprIterate() callback used while loading the doclists
  171274. ** for each phrase into Fts3Expr.aDoclist[]/nDoclist. See also
  171275. ** fts3ExprLoadDoclists().
  171276. */
  171277. static int fts3ExprLoadDoclistsCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
  171278. int rc = SQLITE_OK;
  171279. Fts3Phrase *pPhrase = pExpr->pPhrase;
  171280. LoadDoclistCtx *p = (LoadDoclistCtx *)ctx;
  171281. UNUSED_PARAMETER(iPhrase);
  171282. p->nPhrase++;
  171283. p->nToken += pPhrase->nToken;
  171284. return rc;
  171285. }
  171286. /*
  171287. ** Load the doclists for each phrase in the query associated with FTS3 cursor
  171288. ** pCsr.
  171289. **
  171290. ** If pnPhrase is not NULL, then *pnPhrase is set to the number of matchable
  171291. ** phrases in the expression (all phrases except those directly or
  171292. ** indirectly descended from the right-hand-side of a NOT operator). If
  171293. ** pnToken is not NULL, then it is set to the number of tokens in all
  171294. ** matchable phrases of the expression.
  171295. */
  171296. static int fts3ExprLoadDoclists(
  171297. Fts3Cursor *pCsr, /* Fts3 cursor for current query */
  171298. int *pnPhrase, /* OUT: Number of phrases in query */
  171299. int *pnToken /* OUT: Number of tokens in query */
  171300. ){
  171301. int rc; /* Return Code */
  171302. LoadDoclistCtx sCtx = {0,0,0}; /* Context for fts3ExprIterate() */
  171303. sCtx.pCsr = pCsr;
  171304. rc = fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb, (void *)&sCtx);
  171305. if( pnPhrase ) *pnPhrase = sCtx.nPhrase;
  171306. if( pnToken ) *pnToken = sCtx.nToken;
  171307. return rc;
  171308. }
  171309. static int fts3ExprPhraseCountCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
  171310. (*(int *)ctx)++;
  171311. pExpr->iPhrase = iPhrase;
  171312. return SQLITE_OK;
  171313. }
  171314. static int fts3ExprPhraseCount(Fts3Expr *pExpr){
  171315. int nPhrase = 0;
  171316. (void)fts3ExprIterate(pExpr, fts3ExprPhraseCountCb, (void *)&nPhrase);
  171317. return nPhrase;
  171318. }
  171319. /*
  171320. ** Advance the position list iterator specified by the first two
  171321. ** arguments so that it points to the first element with a value greater
  171322. ** than or equal to parameter iNext.
  171323. */
  171324. static void fts3SnippetAdvance(char **ppIter, int *piIter, int iNext){
  171325. char *pIter = *ppIter;
  171326. if( pIter ){
  171327. int iIter = *piIter;
  171328. while( iIter<iNext ){
  171329. if( 0==(*pIter & 0xFE) ){
  171330. iIter = -1;
  171331. pIter = 0;
  171332. break;
  171333. }
  171334. fts3GetDeltaPosition(&pIter, &iIter);
  171335. }
  171336. *piIter = iIter;
  171337. *ppIter = pIter;
  171338. }
  171339. }
  171340. /*
  171341. ** Advance the snippet iterator to the next candidate snippet.
  171342. */
  171343. static int fts3SnippetNextCandidate(SnippetIter *pIter){
  171344. int i; /* Loop counter */
  171345. if( pIter->iCurrent<0 ){
  171346. /* The SnippetIter object has just been initialized. The first snippet
  171347. ** candidate always starts at offset 0 (even if this candidate has a
  171348. ** score of 0.0).
  171349. */
  171350. pIter->iCurrent = 0;
  171351. /* Advance the 'head' iterator of each phrase to the first offset that
  171352. ** is greater than or equal to (iNext+nSnippet).
  171353. */
  171354. for(i=0; i<pIter->nPhrase; i++){
  171355. SnippetPhrase *pPhrase = &pIter->aPhrase[i];
  171356. fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, pIter->nSnippet);
  171357. }
  171358. }else{
  171359. int iStart;
  171360. int iEnd = 0x7FFFFFFF;
  171361. for(i=0; i<pIter->nPhrase; i++){
  171362. SnippetPhrase *pPhrase = &pIter->aPhrase[i];
  171363. if( pPhrase->pHead && pPhrase->iHead<iEnd ){
  171364. iEnd = pPhrase->iHead;
  171365. }
  171366. }
  171367. if( iEnd==0x7FFFFFFF ){
  171368. return 1;
  171369. }
  171370. pIter->iCurrent = iStart = iEnd - pIter->nSnippet + 1;
  171371. for(i=0; i<pIter->nPhrase; i++){
  171372. SnippetPhrase *pPhrase = &pIter->aPhrase[i];
  171373. fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, iEnd+1);
  171374. fts3SnippetAdvance(&pPhrase->pTail, &pPhrase->iTail, iStart);
  171375. }
  171376. }
  171377. return 0;
  171378. }
  171379. /*
  171380. ** Retrieve information about the current candidate snippet of snippet
  171381. ** iterator pIter.
  171382. */
  171383. static void fts3SnippetDetails(
  171384. SnippetIter *pIter, /* Snippet iterator */
  171385. u64 mCovered, /* Bitmask of phrases already covered */
  171386. int *piToken, /* OUT: First token of proposed snippet */
  171387. int *piScore, /* OUT: "Score" for this snippet */
  171388. u64 *pmCover, /* OUT: Bitmask of phrases covered */
  171389. u64 *pmHighlight /* OUT: Bitmask of terms to highlight */
  171390. ){
  171391. int iStart = pIter->iCurrent; /* First token of snippet */
  171392. int iScore = 0; /* Score of this snippet */
  171393. int i; /* Loop counter */
  171394. u64 mCover = 0; /* Mask of phrases covered by this snippet */
  171395. u64 mHighlight = 0; /* Mask of tokens to highlight in snippet */
  171396. for(i=0; i<pIter->nPhrase; i++){
  171397. SnippetPhrase *pPhrase = &pIter->aPhrase[i];
  171398. if( pPhrase->pTail ){
  171399. char *pCsr = pPhrase->pTail;
  171400. int iCsr = pPhrase->iTail;
  171401. while( iCsr<(iStart+pIter->nSnippet) && iCsr>=iStart ){
  171402. int j;
  171403. u64 mPhrase = (u64)1 << (i%64);
  171404. u64 mPos = (u64)1 << (iCsr - iStart);
  171405. assert( iCsr>=iStart && (iCsr - iStart)<=64 );
  171406. assert( i>=0 );
  171407. if( (mCover|mCovered)&mPhrase ){
  171408. iScore++;
  171409. }else{
  171410. iScore += 1000;
  171411. }
  171412. mCover |= mPhrase;
  171413. for(j=0; j<pPhrase->nToken; j++){
  171414. mHighlight |= (mPos>>j);
  171415. }
  171416. if( 0==(*pCsr & 0x0FE) ) break;
  171417. fts3GetDeltaPosition(&pCsr, &iCsr);
  171418. }
  171419. }
  171420. }
  171421. /* Set the output variables before returning. */
  171422. *piToken = iStart;
  171423. *piScore = iScore;
  171424. *pmCover = mCover;
  171425. *pmHighlight = mHighlight;
  171426. }
  171427. /*
  171428. ** This function is an fts3ExprIterate() callback used by fts3BestSnippet().
  171429. ** Each invocation populates an element of the SnippetIter.aPhrase[] array.
  171430. */
  171431. static int fts3SnippetFindPositions(Fts3Expr *pExpr, int iPhrase, void *ctx){
  171432. SnippetIter *p = (SnippetIter *)ctx;
  171433. SnippetPhrase *pPhrase = &p->aPhrase[iPhrase];
  171434. char *pCsr;
  171435. int rc;
  171436. pPhrase->nToken = pExpr->pPhrase->nToken;
  171437. rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pCsr);
  171438. assert( rc==SQLITE_OK || pCsr==0 );
  171439. if( pCsr ){
  171440. int iFirst = 0;
  171441. pPhrase->pList = pCsr;
  171442. fts3GetDeltaPosition(&pCsr, &iFirst);
  171443. if( iFirst<0 ){
  171444. rc = FTS_CORRUPT_VTAB;
  171445. }else{
  171446. pPhrase->pHead = pCsr;
  171447. pPhrase->pTail = pCsr;
  171448. pPhrase->iHead = iFirst;
  171449. pPhrase->iTail = iFirst;
  171450. }
  171451. }else{
  171452. assert( rc!=SQLITE_OK || (
  171453. pPhrase->pList==0 && pPhrase->pHead==0 && pPhrase->pTail==0
  171454. ));
  171455. }
  171456. return rc;
  171457. }
  171458. /*
  171459. ** Select the fragment of text consisting of nFragment contiguous tokens
  171460. ** from column iCol that represent the "best" snippet. The best snippet
  171461. ** is the snippet with the highest score, where scores are calculated
  171462. ** by adding:
  171463. **
  171464. ** (a) +1 point for each occurrence of a matchable phrase in the snippet.
  171465. **
  171466. ** (b) +1000 points for the first occurrence of each matchable phrase in
  171467. ** the snippet for which the corresponding mCovered bit is not set.
  171468. **
  171469. ** The selected snippet parameters are stored in structure *pFragment before
  171470. ** returning. The score of the selected snippet is stored in *piScore
  171471. ** before returning.
  171472. */
  171473. static int fts3BestSnippet(
  171474. int nSnippet, /* Desired snippet length */
  171475. Fts3Cursor *pCsr, /* Cursor to create snippet for */
  171476. int iCol, /* Index of column to create snippet from */
  171477. u64 mCovered, /* Mask of phrases already covered */
  171478. u64 *pmSeen, /* IN/OUT: Mask of phrases seen */
  171479. SnippetFragment *pFragment, /* OUT: Best snippet found */
  171480. int *piScore /* OUT: Score of snippet pFragment */
  171481. ){
  171482. int rc; /* Return Code */
  171483. int nList; /* Number of phrases in expression */
  171484. SnippetIter sIter; /* Iterates through snippet candidates */
  171485. sqlite3_int64 nByte; /* Number of bytes of space to allocate */
  171486. int iBestScore = -1; /* Best snippet score found so far */
  171487. int i; /* Loop counter */
  171488. memset(&sIter, 0, sizeof(sIter));
  171489. /* Iterate through the phrases in the expression to count them. The same
  171490. ** callback makes sure the doclists are loaded for each phrase.
  171491. */
  171492. rc = fts3ExprLoadDoclists(pCsr, &nList, 0);
  171493. if( rc!=SQLITE_OK ){
  171494. return rc;
  171495. }
  171496. /* Now that it is known how many phrases there are, allocate and zero
  171497. ** the required space using malloc().
  171498. */
  171499. nByte = sizeof(SnippetPhrase) * nList;
  171500. sIter.aPhrase = (SnippetPhrase *)sqlite3_malloc64(nByte);
  171501. if( !sIter.aPhrase ){
  171502. return SQLITE_NOMEM;
  171503. }
  171504. memset(sIter.aPhrase, 0, nByte);
  171505. /* Initialize the contents of the SnippetIter object. Then iterate through
  171506. ** the set of phrases in the expression to populate the aPhrase[] array.
  171507. */
  171508. sIter.pCsr = pCsr;
  171509. sIter.iCol = iCol;
  171510. sIter.nSnippet = nSnippet;
  171511. sIter.nPhrase = nList;
  171512. sIter.iCurrent = -1;
  171513. rc = fts3ExprIterate(pCsr->pExpr, fts3SnippetFindPositions, (void*)&sIter);
  171514. if( rc==SQLITE_OK ){
  171515. /* Set the *pmSeen output variable. */
  171516. for(i=0; i<nList; i++){
  171517. if( sIter.aPhrase[i].pHead ){
  171518. *pmSeen |= (u64)1 << (i%64);
  171519. }
  171520. }
  171521. /* Loop through all candidate snippets. Store the best snippet in
  171522. ** *pFragment. Store its associated 'score' in iBestScore.
  171523. */
  171524. pFragment->iCol = iCol;
  171525. while( !fts3SnippetNextCandidate(&sIter) ){
  171526. int iPos;
  171527. int iScore;
  171528. u64 mCover;
  171529. u64 mHighlite;
  171530. fts3SnippetDetails(&sIter, mCovered, &iPos, &iScore, &mCover,&mHighlite);
  171531. assert( iScore>=0 );
  171532. if( iScore>iBestScore ){
  171533. pFragment->iPos = iPos;
  171534. pFragment->hlmask = mHighlite;
  171535. pFragment->covered = mCover;
  171536. iBestScore = iScore;
  171537. }
  171538. }
  171539. *piScore = iBestScore;
  171540. }
  171541. sqlite3_free(sIter.aPhrase);
  171542. return rc;
  171543. }
  171544. /*
  171545. ** Append a string to the string-buffer passed as the first argument.
  171546. **
  171547. ** If nAppend is negative, then the length of the string zAppend is
  171548. ** determined using strlen().
  171549. */
  171550. static int fts3StringAppend(
  171551. StrBuffer *pStr, /* Buffer to append to */
  171552. const char *zAppend, /* Pointer to data to append to buffer */
  171553. int nAppend /* Size of zAppend in bytes (or -1) */
  171554. ){
  171555. if( nAppend<0 ){
  171556. nAppend = (int)strlen(zAppend);
  171557. }
  171558. /* If there is insufficient space allocated at StrBuffer.z, use realloc()
  171559. ** to grow the buffer until so that it is big enough to accomadate the
  171560. ** appended data.
  171561. */
  171562. if( pStr->n+nAppend+1>=pStr->nAlloc ){
  171563. sqlite3_int64 nAlloc = pStr->nAlloc+(sqlite3_int64)nAppend+100;
  171564. char *zNew = sqlite3_realloc64(pStr->z, nAlloc);
  171565. if( !zNew ){
  171566. return SQLITE_NOMEM;
  171567. }
  171568. pStr->z = zNew;
  171569. pStr->nAlloc = nAlloc;
  171570. }
  171571. assert( pStr->z!=0 && (pStr->nAlloc >= pStr->n+nAppend+1) );
  171572. /* Append the data to the string buffer. */
  171573. memcpy(&pStr->z[pStr->n], zAppend, nAppend);
  171574. pStr->n += nAppend;
  171575. pStr->z[pStr->n] = '\0';
  171576. return SQLITE_OK;
  171577. }
  171578. /*
  171579. ** The fts3BestSnippet() function often selects snippets that end with a
  171580. ** query term. That is, the final term of the snippet is always a term
  171581. ** that requires highlighting. For example, if 'X' is a highlighted term
  171582. ** and '.' is a non-highlighted term, BestSnippet() may select:
  171583. **
  171584. ** ........X.....X
  171585. **
  171586. ** This function "shifts" the beginning of the snippet forward in the
  171587. ** document so that there are approximately the same number of
  171588. ** non-highlighted terms to the right of the final highlighted term as there
  171589. ** are to the left of the first highlighted term. For example, to this:
  171590. **
  171591. ** ....X.....X....
  171592. **
  171593. ** This is done as part of extracting the snippet text, not when selecting
  171594. ** the snippet. Snippet selection is done based on doclists only, so there
  171595. ** is no way for fts3BestSnippet() to know whether or not the document
  171596. ** actually contains terms that follow the final highlighted term.
  171597. */
  171598. static int fts3SnippetShift(
  171599. Fts3Table *pTab, /* FTS3 table snippet comes from */
  171600. int iLangid, /* Language id to use in tokenizing */
  171601. int nSnippet, /* Number of tokens desired for snippet */
  171602. const char *zDoc, /* Document text to extract snippet from */
  171603. int nDoc, /* Size of buffer zDoc in bytes */
  171604. int *piPos, /* IN/OUT: First token of snippet */
  171605. u64 *pHlmask /* IN/OUT: Mask of tokens to highlight */
  171606. ){
  171607. u64 hlmask = *pHlmask; /* Local copy of initial highlight-mask */
  171608. if( hlmask ){
  171609. int nLeft; /* Tokens to the left of first highlight */
  171610. int nRight; /* Tokens to the right of last highlight */
  171611. int nDesired; /* Ideal number of tokens to shift forward */
  171612. for(nLeft=0; !(hlmask & ((u64)1 << nLeft)); nLeft++);
  171613. for(nRight=0; !(hlmask & ((u64)1 << (nSnippet-1-nRight))); nRight++);
  171614. assert( (nSnippet-1-nRight)<=63 && (nSnippet-1-nRight)>=0 );
  171615. nDesired = (nLeft-nRight)/2;
  171616. /* Ideally, the start of the snippet should be pushed forward in the
  171617. ** document nDesired tokens. This block checks if there are actually
  171618. ** nDesired tokens to the right of the snippet. If so, *piPos and
  171619. ** *pHlMask are updated to shift the snippet nDesired tokens to the
  171620. ** right. Otherwise, the snippet is shifted by the number of tokens
  171621. ** available.
  171622. */
  171623. if( nDesired>0 ){
  171624. int nShift; /* Number of tokens to shift snippet by */
  171625. int iCurrent = 0; /* Token counter */
  171626. int rc; /* Return Code */
  171627. sqlite3_tokenizer_module *pMod;
  171628. sqlite3_tokenizer_cursor *pC;
  171629. pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
  171630. /* Open a cursor on zDoc/nDoc. Check if there are (nSnippet+nDesired)
  171631. ** or more tokens in zDoc/nDoc.
  171632. */
  171633. rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, iLangid, zDoc, nDoc, &pC);
  171634. if( rc!=SQLITE_OK ){
  171635. return rc;
  171636. }
  171637. while( rc==SQLITE_OK && iCurrent<(nSnippet+nDesired) ){
  171638. const char *ZDUMMY; int DUMMY1 = 0, DUMMY2 = 0, DUMMY3 = 0;
  171639. rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &DUMMY2, &DUMMY3, &iCurrent);
  171640. }
  171641. pMod->xClose(pC);
  171642. if( rc!=SQLITE_OK && rc!=SQLITE_DONE ){ return rc; }
  171643. nShift = (rc==SQLITE_DONE)+iCurrent-nSnippet;
  171644. assert( nShift<=nDesired );
  171645. if( nShift>0 ){
  171646. *piPos += nShift;
  171647. *pHlmask = hlmask >> nShift;
  171648. }
  171649. }
  171650. }
  171651. return SQLITE_OK;
  171652. }
  171653. /*
  171654. ** Extract the snippet text for fragment pFragment from cursor pCsr and
  171655. ** append it to string buffer pOut.
  171656. */
  171657. static int fts3SnippetText(
  171658. Fts3Cursor *pCsr, /* FTS3 Cursor */
  171659. SnippetFragment *pFragment, /* Snippet to extract */
  171660. int iFragment, /* Fragment number */
  171661. int isLast, /* True for final fragment in snippet */
  171662. int nSnippet, /* Number of tokens in extracted snippet */
  171663. const char *zOpen, /* String inserted before highlighted term */
  171664. const char *zClose, /* String inserted after highlighted term */
  171665. const char *zEllipsis, /* String inserted between snippets */
  171666. StrBuffer *pOut /* Write output here */
  171667. ){
  171668. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  171669. int rc; /* Return code */
  171670. const char *zDoc; /* Document text to extract snippet from */
  171671. int nDoc; /* Size of zDoc in bytes */
  171672. int iCurrent = 0; /* Current token number of document */
  171673. int iEnd = 0; /* Byte offset of end of current token */
  171674. int isShiftDone = 0; /* True after snippet is shifted */
  171675. int iPos = pFragment->iPos; /* First token of snippet */
  171676. u64 hlmask = pFragment->hlmask; /* Highlight-mask for snippet */
  171677. int iCol = pFragment->iCol+1; /* Query column to extract text from */
  171678. sqlite3_tokenizer_module *pMod; /* Tokenizer module methods object */
  171679. sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor open on zDoc/nDoc */
  171680. zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol);
  171681. if( zDoc==0 ){
  171682. if( sqlite3_column_type(pCsr->pStmt, iCol)!=SQLITE_NULL ){
  171683. return SQLITE_NOMEM;
  171684. }
  171685. return SQLITE_OK;
  171686. }
  171687. nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol);
  171688. /* Open a token cursor on the document. */
  171689. pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
  171690. rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid, zDoc,nDoc,&pC);
  171691. if( rc!=SQLITE_OK ){
  171692. return rc;
  171693. }
  171694. while( rc==SQLITE_OK ){
  171695. const char *ZDUMMY; /* Dummy argument used with tokenizer */
  171696. int DUMMY1 = -1; /* Dummy argument used with tokenizer */
  171697. int iBegin = 0; /* Offset in zDoc of start of token */
  171698. int iFin = 0; /* Offset in zDoc of end of token */
  171699. int isHighlight = 0; /* True for highlighted terms */
  171700. /* Variable DUMMY1 is initialized to a negative value above. Elsewhere
  171701. ** in the FTS code the variable that the third argument to xNext points to
  171702. ** is initialized to zero before the first (*but not necessarily
  171703. ** subsequent*) call to xNext(). This is done for a particular application
  171704. ** that needs to know whether or not the tokenizer is being used for
  171705. ** snippet generation or for some other purpose.
  171706. **
  171707. ** Extreme care is required when writing code to depend on this
  171708. ** initialization. It is not a documented part of the tokenizer interface.
  171709. ** If a tokenizer is used directly by any code outside of FTS, this
  171710. ** convention might not be respected. */
  171711. rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iBegin, &iFin, &iCurrent);
  171712. if( rc!=SQLITE_OK ){
  171713. if( rc==SQLITE_DONE ){
  171714. /* Special case - the last token of the snippet is also the last token
  171715. ** of the column. Append any punctuation that occurred between the end
  171716. ** of the previous token and the end of the document to the output.
  171717. ** Then break out of the loop. */
  171718. rc = fts3StringAppend(pOut, &zDoc[iEnd], -1);
  171719. }
  171720. break;
  171721. }
  171722. if( iCurrent<iPos ){ continue; }
  171723. if( !isShiftDone ){
  171724. int n = nDoc - iBegin;
  171725. rc = fts3SnippetShift(
  171726. pTab, pCsr->iLangid, nSnippet, &zDoc[iBegin], n, &iPos, &hlmask
  171727. );
  171728. isShiftDone = 1;
  171729. /* Now that the shift has been done, check if the initial "..." are
  171730. ** required. They are required if (a) this is not the first fragment,
  171731. ** or (b) this fragment does not begin at position 0 of its column.
  171732. */
  171733. if( rc==SQLITE_OK ){
  171734. if( iPos>0 || iFragment>0 ){
  171735. rc = fts3StringAppend(pOut, zEllipsis, -1);
  171736. }else if( iBegin ){
  171737. rc = fts3StringAppend(pOut, zDoc, iBegin);
  171738. }
  171739. }
  171740. if( rc!=SQLITE_OK || iCurrent<iPos ) continue;
  171741. }
  171742. if( iCurrent>=(iPos+nSnippet) ){
  171743. if( isLast ){
  171744. rc = fts3StringAppend(pOut, zEllipsis, -1);
  171745. }
  171746. break;
  171747. }
  171748. /* Set isHighlight to true if this term should be highlighted. */
  171749. isHighlight = (hlmask & ((u64)1 << (iCurrent-iPos)))!=0;
  171750. if( iCurrent>iPos ) rc = fts3StringAppend(pOut, &zDoc[iEnd], iBegin-iEnd);
  171751. if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zOpen, -1);
  171752. if( rc==SQLITE_OK ) rc = fts3StringAppend(pOut, &zDoc[iBegin], iFin-iBegin);
  171753. if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zClose, -1);
  171754. iEnd = iFin;
  171755. }
  171756. pMod->xClose(pC);
  171757. return rc;
  171758. }
  171759. /*
  171760. ** This function is used to count the entries in a column-list (a
  171761. ** delta-encoded list of term offsets within a single column of a single
  171762. ** row). When this function is called, *ppCollist should point to the
  171763. ** beginning of the first varint in the column-list (the varint that
  171764. ** contains the position of the first matching term in the column data).
  171765. ** Before returning, *ppCollist is set to point to the first byte after
  171766. ** the last varint in the column-list (either the 0x00 signifying the end
  171767. ** of the position-list, or the 0x01 that precedes the column number of
  171768. ** the next column in the position-list).
  171769. **
  171770. ** The number of elements in the column-list is returned.
  171771. */
  171772. static int fts3ColumnlistCount(char **ppCollist){
  171773. char *pEnd = *ppCollist;
  171774. char c = 0;
  171775. int nEntry = 0;
  171776. /* A column-list is terminated by either a 0x01 or 0x00. */
  171777. while( 0xFE & (*pEnd | c) ){
  171778. c = *pEnd++ & 0x80;
  171779. if( !c ) nEntry++;
  171780. }
  171781. *ppCollist = pEnd;
  171782. return nEntry;
  171783. }
  171784. /*
  171785. ** This function gathers 'y' or 'b' data for a single phrase.
  171786. */
  171787. static int fts3ExprLHits(
  171788. Fts3Expr *pExpr, /* Phrase expression node */
  171789. MatchInfo *p /* Matchinfo context */
  171790. ){
  171791. Fts3Table *pTab = (Fts3Table *)p->pCursor->base.pVtab;
  171792. int iStart;
  171793. Fts3Phrase *pPhrase = pExpr->pPhrase;
  171794. char *pIter = pPhrase->doclist.pList;
  171795. int iCol = 0;
  171796. assert( p->flag==FTS3_MATCHINFO_LHITS_BM || p->flag==FTS3_MATCHINFO_LHITS );
  171797. if( p->flag==FTS3_MATCHINFO_LHITS ){
  171798. iStart = pExpr->iPhrase * p->nCol;
  171799. }else{
  171800. iStart = pExpr->iPhrase * ((p->nCol + 31) / 32);
  171801. }
  171802. if( pIter ) while( 1 ){
  171803. int nHit = fts3ColumnlistCount(&pIter);
  171804. if( (pPhrase->iColumn>=pTab->nColumn || pPhrase->iColumn==iCol) ){
  171805. if( p->flag==FTS3_MATCHINFO_LHITS ){
  171806. p->aMatchinfo[iStart + iCol] = (u32)nHit;
  171807. }else if( nHit ){
  171808. p->aMatchinfo[iStart + (iCol+1)/32] |= (1 << (iCol&0x1F));
  171809. }
  171810. }
  171811. assert( *pIter==0x00 || *pIter==0x01 );
  171812. if( *pIter!=0x01 ) break;
  171813. pIter++;
  171814. pIter += fts3GetVarint32(pIter, &iCol);
  171815. if( iCol>=p->nCol ) return FTS_CORRUPT_VTAB;
  171816. }
  171817. return SQLITE_OK;
  171818. }
  171819. /*
  171820. ** Gather the results for matchinfo directives 'y' and 'b'.
  171821. */
  171822. static int fts3ExprLHitGather(
  171823. Fts3Expr *pExpr,
  171824. MatchInfo *p
  171825. ){
  171826. int rc = SQLITE_OK;
  171827. assert( (pExpr->pLeft==0)==(pExpr->pRight==0) );
  171828. if( pExpr->bEof==0 && pExpr->iDocid==p->pCursor->iPrevId ){
  171829. if( pExpr->pLeft ){
  171830. rc = fts3ExprLHitGather(pExpr->pLeft, p);
  171831. if( rc==SQLITE_OK ) rc = fts3ExprLHitGather(pExpr->pRight, p);
  171832. }else{
  171833. rc = fts3ExprLHits(pExpr, p);
  171834. }
  171835. }
  171836. return rc;
  171837. }
  171838. /*
  171839. ** fts3ExprIterate() callback used to collect the "global" matchinfo stats
  171840. ** for a single query.
  171841. **
  171842. ** fts3ExprIterate() callback to load the 'global' elements of a
  171843. ** FTS3_MATCHINFO_HITS matchinfo array. The global stats are those elements
  171844. ** of the matchinfo array that are constant for all rows returned by the
  171845. ** current query.
  171846. **
  171847. ** Argument pCtx is actually a pointer to a struct of type MatchInfo. This
  171848. ** function populates Matchinfo.aMatchinfo[] as follows:
  171849. **
  171850. ** for(iCol=0; iCol<nCol; iCol++){
  171851. ** aMatchinfo[3*iPhrase*nCol + 3*iCol + 1] = X;
  171852. ** aMatchinfo[3*iPhrase*nCol + 3*iCol + 2] = Y;
  171853. ** }
  171854. **
  171855. ** where X is the number of matches for phrase iPhrase is column iCol of all
  171856. ** rows of the table. Y is the number of rows for which column iCol contains
  171857. ** at least one instance of phrase iPhrase.
  171858. **
  171859. ** If the phrase pExpr consists entirely of deferred tokens, then all X and
  171860. ** Y values are set to nDoc, where nDoc is the number of documents in the
  171861. ** file system. This is done because the full-text index doclist is required
  171862. ** to calculate these values properly, and the full-text index doclist is
  171863. ** not available for deferred tokens.
  171864. */
  171865. static int fts3ExprGlobalHitsCb(
  171866. Fts3Expr *pExpr, /* Phrase expression node */
  171867. int iPhrase, /* Phrase number (numbered from zero) */
  171868. void *pCtx /* Pointer to MatchInfo structure */
  171869. ){
  171870. MatchInfo *p = (MatchInfo *)pCtx;
  171871. return sqlite3Fts3EvalPhraseStats(
  171872. p->pCursor, pExpr, &p->aMatchinfo[3*iPhrase*p->nCol]
  171873. );
  171874. }
  171875. /*
  171876. ** fts3ExprIterate() callback used to collect the "local" part of the
  171877. ** FTS3_MATCHINFO_HITS array. The local stats are those elements of the
  171878. ** array that are different for each row returned by the query.
  171879. */
  171880. static int fts3ExprLocalHitsCb(
  171881. Fts3Expr *pExpr, /* Phrase expression node */
  171882. int iPhrase, /* Phrase number */
  171883. void *pCtx /* Pointer to MatchInfo structure */
  171884. ){
  171885. int rc = SQLITE_OK;
  171886. MatchInfo *p = (MatchInfo *)pCtx;
  171887. int iStart = iPhrase * p->nCol * 3;
  171888. int i;
  171889. for(i=0; i<p->nCol && rc==SQLITE_OK; i++){
  171890. char *pCsr;
  171891. rc = sqlite3Fts3EvalPhrasePoslist(p->pCursor, pExpr, i, &pCsr);
  171892. if( pCsr ){
  171893. p->aMatchinfo[iStart+i*3] = fts3ColumnlistCount(&pCsr);
  171894. }else{
  171895. p->aMatchinfo[iStart+i*3] = 0;
  171896. }
  171897. }
  171898. return rc;
  171899. }
  171900. static int fts3MatchinfoCheck(
  171901. Fts3Table *pTab,
  171902. char cArg,
  171903. char **pzErr
  171904. ){
  171905. if( (cArg==FTS3_MATCHINFO_NPHRASE)
  171906. || (cArg==FTS3_MATCHINFO_NCOL)
  171907. || (cArg==FTS3_MATCHINFO_NDOC && pTab->bFts4)
  171908. || (cArg==FTS3_MATCHINFO_AVGLENGTH && pTab->bFts4)
  171909. || (cArg==FTS3_MATCHINFO_LENGTH && pTab->bHasDocsize)
  171910. || (cArg==FTS3_MATCHINFO_LCS)
  171911. || (cArg==FTS3_MATCHINFO_HITS)
  171912. || (cArg==FTS3_MATCHINFO_LHITS)
  171913. || (cArg==FTS3_MATCHINFO_LHITS_BM)
  171914. ){
  171915. return SQLITE_OK;
  171916. }
  171917. sqlite3Fts3ErrMsg(pzErr, "unrecognized matchinfo request: %c", cArg);
  171918. return SQLITE_ERROR;
  171919. }
  171920. static size_t fts3MatchinfoSize(MatchInfo *pInfo, char cArg){
  171921. size_t nVal; /* Number of integers output by cArg */
  171922. switch( cArg ){
  171923. case FTS3_MATCHINFO_NDOC:
  171924. case FTS3_MATCHINFO_NPHRASE:
  171925. case FTS3_MATCHINFO_NCOL:
  171926. nVal = 1;
  171927. break;
  171928. case FTS3_MATCHINFO_AVGLENGTH:
  171929. case FTS3_MATCHINFO_LENGTH:
  171930. case FTS3_MATCHINFO_LCS:
  171931. nVal = pInfo->nCol;
  171932. break;
  171933. case FTS3_MATCHINFO_LHITS:
  171934. nVal = pInfo->nCol * pInfo->nPhrase;
  171935. break;
  171936. case FTS3_MATCHINFO_LHITS_BM:
  171937. nVal = pInfo->nPhrase * ((pInfo->nCol + 31) / 32);
  171938. break;
  171939. default:
  171940. assert( cArg==FTS3_MATCHINFO_HITS );
  171941. nVal = pInfo->nCol * pInfo->nPhrase * 3;
  171942. break;
  171943. }
  171944. return nVal;
  171945. }
  171946. static int fts3MatchinfoSelectDoctotal(
  171947. Fts3Table *pTab,
  171948. sqlite3_stmt **ppStmt,
  171949. sqlite3_int64 *pnDoc,
  171950. const char **paLen,
  171951. const char **ppEnd
  171952. ){
  171953. sqlite3_stmt *pStmt;
  171954. const char *a;
  171955. const char *pEnd;
  171956. sqlite3_int64 nDoc;
  171957. int n;
  171958. if( !*ppStmt ){
  171959. int rc = sqlite3Fts3SelectDoctotal(pTab, ppStmt);
  171960. if( rc!=SQLITE_OK ) return rc;
  171961. }
  171962. pStmt = *ppStmt;
  171963. assert( sqlite3_data_count(pStmt)==1 );
  171964. n = sqlite3_column_bytes(pStmt, 0);
  171965. a = sqlite3_column_blob(pStmt, 0);
  171966. if( a==0 ){
  171967. return FTS_CORRUPT_VTAB;
  171968. }
  171969. pEnd = a + n;
  171970. a += sqlite3Fts3GetVarintBounded(a, pEnd, &nDoc);
  171971. if( nDoc<=0 || a>pEnd ){
  171972. return FTS_CORRUPT_VTAB;
  171973. }
  171974. *pnDoc = nDoc;
  171975. if( paLen ) *paLen = a;
  171976. if( ppEnd ) *ppEnd = pEnd;
  171977. return SQLITE_OK;
  171978. }
  171979. /*
  171980. ** An instance of the following structure is used to store state while
  171981. ** iterating through a multi-column position-list corresponding to the
  171982. ** hits for a single phrase on a single row in order to calculate the
  171983. ** values for a matchinfo() FTS3_MATCHINFO_LCS request.
  171984. */
  171985. typedef struct LcsIterator LcsIterator;
  171986. struct LcsIterator {
  171987. Fts3Expr *pExpr; /* Pointer to phrase expression */
  171988. int iPosOffset; /* Tokens count up to end of this phrase */
  171989. char *pRead; /* Cursor used to iterate through aDoclist */
  171990. int iPos; /* Current position */
  171991. };
  171992. /*
  171993. ** If LcsIterator.iCol is set to the following value, the iterator has
  171994. ** finished iterating through all offsets for all columns.
  171995. */
  171996. #define LCS_ITERATOR_FINISHED 0x7FFFFFFF;
  171997. static int fts3MatchinfoLcsCb(
  171998. Fts3Expr *pExpr, /* Phrase expression node */
  171999. int iPhrase, /* Phrase number (numbered from zero) */
  172000. void *pCtx /* Pointer to MatchInfo structure */
  172001. ){
  172002. LcsIterator *aIter = (LcsIterator *)pCtx;
  172003. aIter[iPhrase].pExpr = pExpr;
  172004. return SQLITE_OK;
  172005. }
  172006. /*
  172007. ** Advance the iterator passed as an argument to the next position. Return
  172008. ** 1 if the iterator is at EOF or if it now points to the start of the
  172009. ** position list for the next column.
  172010. */
  172011. static int fts3LcsIteratorAdvance(LcsIterator *pIter){
  172012. char *pRead = pIter->pRead;
  172013. sqlite3_int64 iRead;
  172014. int rc = 0;
  172015. pRead += sqlite3Fts3GetVarint(pRead, &iRead);
  172016. if( iRead==0 || iRead==1 ){
  172017. pRead = 0;
  172018. rc = 1;
  172019. }else{
  172020. pIter->iPos += (int)(iRead-2);
  172021. }
  172022. pIter->pRead = pRead;
  172023. return rc;
  172024. }
  172025. /*
  172026. ** This function implements the FTS3_MATCHINFO_LCS matchinfo() flag.
  172027. **
  172028. ** If the call is successful, the longest-common-substring lengths for each
  172029. ** column are written into the first nCol elements of the pInfo->aMatchinfo[]
  172030. ** array before returning. SQLITE_OK is returned in this case.
  172031. **
  172032. ** Otherwise, if an error occurs, an SQLite error code is returned and the
  172033. ** data written to the first nCol elements of pInfo->aMatchinfo[] is
  172034. ** undefined.
  172035. */
  172036. static int fts3MatchinfoLcs(Fts3Cursor *pCsr, MatchInfo *pInfo){
  172037. LcsIterator *aIter;
  172038. int i;
  172039. int iCol;
  172040. int nToken = 0;
  172041. int rc = SQLITE_OK;
  172042. /* Allocate and populate the array of LcsIterator objects. The array
  172043. ** contains one element for each matchable phrase in the query.
  172044. **/
  172045. aIter = sqlite3_malloc64(sizeof(LcsIterator) * pCsr->nPhrase);
  172046. if( !aIter ) return SQLITE_NOMEM;
  172047. memset(aIter, 0, sizeof(LcsIterator) * pCsr->nPhrase);
  172048. (void)fts3ExprIterate(pCsr->pExpr, fts3MatchinfoLcsCb, (void*)aIter);
  172049. for(i=0; i<pInfo->nPhrase; i++){
  172050. LcsIterator *pIter = &aIter[i];
  172051. nToken -= pIter->pExpr->pPhrase->nToken;
  172052. pIter->iPosOffset = nToken;
  172053. }
  172054. for(iCol=0; iCol<pInfo->nCol; iCol++){
  172055. int nLcs = 0; /* LCS value for this column */
  172056. int nLive = 0; /* Number of iterators in aIter not at EOF */
  172057. for(i=0; i<pInfo->nPhrase; i++){
  172058. LcsIterator *pIt = &aIter[i];
  172059. rc = sqlite3Fts3EvalPhrasePoslist(pCsr, pIt->pExpr, iCol, &pIt->pRead);
  172060. if( rc!=SQLITE_OK ) goto matchinfo_lcs_out;
  172061. if( pIt->pRead ){
  172062. pIt->iPos = pIt->iPosOffset;
  172063. fts3LcsIteratorAdvance(pIt);
  172064. if( pIt->pRead==0 ){
  172065. rc = FTS_CORRUPT_VTAB;
  172066. goto matchinfo_lcs_out;
  172067. }
  172068. nLive++;
  172069. }
  172070. }
  172071. while( nLive>0 ){
  172072. LcsIterator *pAdv = 0; /* The iterator to advance by one position */
  172073. int nThisLcs = 0; /* LCS for the current iterator positions */
  172074. for(i=0; i<pInfo->nPhrase; i++){
  172075. LcsIterator *pIter = &aIter[i];
  172076. if( pIter->pRead==0 ){
  172077. /* This iterator is already at EOF for this column. */
  172078. nThisLcs = 0;
  172079. }else{
  172080. if( pAdv==0 || pIter->iPos<pAdv->iPos ){
  172081. pAdv = pIter;
  172082. }
  172083. if( nThisLcs==0 || pIter->iPos==pIter[-1].iPos ){
  172084. nThisLcs++;
  172085. }else{
  172086. nThisLcs = 1;
  172087. }
  172088. if( nThisLcs>nLcs ) nLcs = nThisLcs;
  172089. }
  172090. }
  172091. if( fts3LcsIteratorAdvance(pAdv) ) nLive--;
  172092. }
  172093. pInfo->aMatchinfo[iCol] = nLcs;
  172094. }
  172095. matchinfo_lcs_out:
  172096. sqlite3_free(aIter);
  172097. return rc;
  172098. }
  172099. /*
  172100. ** Populate the buffer pInfo->aMatchinfo[] with an array of integers to
  172101. ** be returned by the matchinfo() function. Argument zArg contains the
  172102. ** format string passed as the second argument to matchinfo (or the
  172103. ** default value "pcx" if no second argument was specified). The format
  172104. ** string has already been validated and the pInfo->aMatchinfo[] array
  172105. ** is guaranteed to be large enough for the output.
  172106. **
  172107. ** If bGlobal is true, then populate all fields of the matchinfo() output.
  172108. ** If it is false, then assume that those fields that do not change between
  172109. ** rows (i.e. FTS3_MATCHINFO_NPHRASE, NCOL, NDOC, AVGLENGTH and part of HITS)
  172110. ** have already been populated.
  172111. **
  172112. ** Return SQLITE_OK if successful, or an SQLite error code if an error
  172113. ** occurs. If a value other than SQLITE_OK is returned, the state the
  172114. ** pInfo->aMatchinfo[] buffer is left in is undefined.
  172115. */
  172116. static int fts3MatchinfoValues(
  172117. Fts3Cursor *pCsr, /* FTS3 cursor object */
  172118. int bGlobal, /* True to grab the global stats */
  172119. MatchInfo *pInfo, /* Matchinfo context object */
  172120. const char *zArg /* Matchinfo format string */
  172121. ){
  172122. int rc = SQLITE_OK;
  172123. int i;
  172124. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  172125. sqlite3_stmt *pSelect = 0;
  172126. for(i=0; rc==SQLITE_OK && zArg[i]; i++){
  172127. pInfo->flag = zArg[i];
  172128. switch( zArg[i] ){
  172129. case FTS3_MATCHINFO_NPHRASE:
  172130. if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nPhrase;
  172131. break;
  172132. case FTS3_MATCHINFO_NCOL:
  172133. if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nCol;
  172134. break;
  172135. case FTS3_MATCHINFO_NDOC:
  172136. if( bGlobal ){
  172137. sqlite3_int64 nDoc = 0;
  172138. rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, 0, 0);
  172139. pInfo->aMatchinfo[0] = (u32)nDoc;
  172140. }
  172141. break;
  172142. case FTS3_MATCHINFO_AVGLENGTH:
  172143. if( bGlobal ){
  172144. sqlite3_int64 nDoc; /* Number of rows in table */
  172145. const char *a; /* Aggregate column length array */
  172146. const char *pEnd; /* First byte past end of length array */
  172147. rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, &a, &pEnd);
  172148. if( rc==SQLITE_OK ){
  172149. int iCol;
  172150. for(iCol=0; iCol<pInfo->nCol; iCol++){
  172151. u32 iVal;
  172152. sqlite3_int64 nToken;
  172153. a += sqlite3Fts3GetVarint(a, &nToken);
  172154. if( a>pEnd ){
  172155. rc = SQLITE_CORRUPT_VTAB;
  172156. break;
  172157. }
  172158. iVal = (u32)(((u32)(nToken&0xffffffff)+nDoc/2)/nDoc);
  172159. pInfo->aMatchinfo[iCol] = iVal;
  172160. }
  172161. }
  172162. }
  172163. break;
  172164. case FTS3_MATCHINFO_LENGTH: {
  172165. sqlite3_stmt *pSelectDocsize = 0;
  172166. rc = sqlite3Fts3SelectDocsize(pTab, pCsr->iPrevId, &pSelectDocsize);
  172167. if( rc==SQLITE_OK ){
  172168. int iCol;
  172169. const char *a = sqlite3_column_blob(pSelectDocsize, 0);
  172170. const char *pEnd = a + sqlite3_column_bytes(pSelectDocsize, 0);
  172171. for(iCol=0; iCol<pInfo->nCol; iCol++){
  172172. sqlite3_int64 nToken;
  172173. a += sqlite3Fts3GetVarintBounded(a, pEnd, &nToken);
  172174. if( a>pEnd ){
  172175. rc = SQLITE_CORRUPT_VTAB;
  172176. break;
  172177. }
  172178. pInfo->aMatchinfo[iCol] = (u32)nToken;
  172179. }
  172180. }
  172181. sqlite3_reset(pSelectDocsize);
  172182. break;
  172183. }
  172184. case FTS3_MATCHINFO_LCS:
  172185. rc = fts3ExprLoadDoclists(pCsr, 0, 0);
  172186. if( rc==SQLITE_OK ){
  172187. rc = fts3MatchinfoLcs(pCsr, pInfo);
  172188. }
  172189. break;
  172190. case FTS3_MATCHINFO_LHITS_BM:
  172191. case FTS3_MATCHINFO_LHITS: {
  172192. size_t nZero = fts3MatchinfoSize(pInfo, zArg[i]) * sizeof(u32);
  172193. memset(pInfo->aMatchinfo, 0, nZero);
  172194. rc = fts3ExprLHitGather(pCsr->pExpr, pInfo);
  172195. break;
  172196. }
  172197. default: {
  172198. Fts3Expr *pExpr;
  172199. assert( zArg[i]==FTS3_MATCHINFO_HITS );
  172200. pExpr = pCsr->pExpr;
  172201. rc = fts3ExprLoadDoclists(pCsr, 0, 0);
  172202. if( rc!=SQLITE_OK ) break;
  172203. if( bGlobal ){
  172204. if( pCsr->pDeferred ){
  172205. rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &pInfo->nDoc,0,0);
  172206. if( rc!=SQLITE_OK ) break;
  172207. }
  172208. rc = fts3ExprIterate(pExpr, fts3ExprGlobalHitsCb,(void*)pInfo);
  172209. sqlite3Fts3EvalTestDeferred(pCsr, &rc);
  172210. if( rc!=SQLITE_OK ) break;
  172211. }
  172212. (void)fts3ExprIterate(pExpr, fts3ExprLocalHitsCb,(void*)pInfo);
  172213. break;
  172214. }
  172215. }
  172216. pInfo->aMatchinfo += fts3MatchinfoSize(pInfo, zArg[i]);
  172217. }
  172218. sqlite3_reset(pSelect);
  172219. return rc;
  172220. }
  172221. /*
  172222. ** Populate pCsr->aMatchinfo[] with data for the current row. The
  172223. ** 'matchinfo' data is an array of 32-bit unsigned integers (C type u32).
  172224. */
  172225. static void fts3GetMatchinfo(
  172226. sqlite3_context *pCtx, /* Return results here */
  172227. Fts3Cursor *pCsr, /* FTS3 Cursor object */
  172228. const char *zArg /* Second argument to matchinfo() function */
  172229. ){
  172230. MatchInfo sInfo;
  172231. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  172232. int rc = SQLITE_OK;
  172233. int bGlobal = 0; /* Collect 'global' stats as well as local */
  172234. u32 *aOut = 0;
  172235. void (*xDestroyOut)(void*) = 0;
  172236. memset(&sInfo, 0, sizeof(MatchInfo));
  172237. sInfo.pCursor = pCsr;
  172238. sInfo.nCol = pTab->nColumn;
  172239. /* If there is cached matchinfo() data, but the format string for the
  172240. ** cache does not match the format string for this request, discard
  172241. ** the cached data. */
  172242. if( pCsr->pMIBuffer && strcmp(pCsr->pMIBuffer->zMatchinfo, zArg) ){
  172243. sqlite3Fts3MIBufferFree(pCsr->pMIBuffer);
  172244. pCsr->pMIBuffer = 0;
  172245. }
  172246. /* If Fts3Cursor.pMIBuffer is NULL, then this is the first time the
  172247. ** matchinfo function has been called for this query. In this case
  172248. ** allocate the array used to accumulate the matchinfo data and
  172249. ** initialize those elements that are constant for every row.
  172250. */
  172251. if( pCsr->pMIBuffer==0 ){
  172252. size_t nMatchinfo = 0; /* Number of u32 elements in match-info */
  172253. int i; /* Used to iterate through zArg */
  172254. /* Determine the number of phrases in the query */
  172255. pCsr->nPhrase = fts3ExprPhraseCount(pCsr->pExpr);
  172256. sInfo.nPhrase = pCsr->nPhrase;
  172257. /* Determine the number of integers in the buffer returned by this call. */
  172258. for(i=0; zArg[i]; i++){
  172259. char *zErr = 0;
  172260. if( fts3MatchinfoCheck(pTab, zArg[i], &zErr) ){
  172261. sqlite3_result_error(pCtx, zErr, -1);
  172262. sqlite3_free(zErr);
  172263. return;
  172264. }
  172265. nMatchinfo += fts3MatchinfoSize(&sInfo, zArg[i]);
  172266. }
  172267. /* Allocate space for Fts3Cursor.aMatchinfo[] and Fts3Cursor.zMatchinfo. */
  172268. pCsr->pMIBuffer = fts3MIBufferNew(nMatchinfo, zArg);
  172269. if( !pCsr->pMIBuffer ) rc = SQLITE_NOMEM;
  172270. pCsr->isMatchinfoNeeded = 1;
  172271. bGlobal = 1;
  172272. }
  172273. if( rc==SQLITE_OK ){
  172274. xDestroyOut = fts3MIBufferAlloc(pCsr->pMIBuffer, &aOut);
  172275. if( xDestroyOut==0 ){
  172276. rc = SQLITE_NOMEM;
  172277. }
  172278. }
  172279. if( rc==SQLITE_OK ){
  172280. sInfo.aMatchinfo = aOut;
  172281. sInfo.nPhrase = pCsr->nPhrase;
  172282. rc = fts3MatchinfoValues(pCsr, bGlobal, &sInfo, zArg);
  172283. if( bGlobal ){
  172284. fts3MIBufferSetGlobal(pCsr->pMIBuffer);
  172285. }
  172286. }
  172287. if( rc!=SQLITE_OK ){
  172288. sqlite3_result_error_code(pCtx, rc);
  172289. if( xDestroyOut ) xDestroyOut(aOut);
  172290. }else{
  172291. int n = pCsr->pMIBuffer->nElem * sizeof(u32);
  172292. sqlite3_result_blob(pCtx, aOut, n, xDestroyOut);
  172293. }
  172294. }
  172295. /*
  172296. ** Implementation of snippet() function.
  172297. */
  172298. SQLITE_PRIVATE void sqlite3Fts3Snippet(
  172299. sqlite3_context *pCtx, /* SQLite function call context */
  172300. Fts3Cursor *pCsr, /* Cursor object */
  172301. const char *zStart, /* Snippet start text - "<b>" */
  172302. const char *zEnd, /* Snippet end text - "</b>" */
  172303. const char *zEllipsis, /* Snippet ellipsis text - "<b>...</b>" */
  172304. int iCol, /* Extract snippet from this column */
  172305. int nToken /* Approximate number of tokens in snippet */
  172306. ){
  172307. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  172308. int rc = SQLITE_OK;
  172309. int i;
  172310. StrBuffer res = {0, 0, 0};
  172311. /* The returned text includes up to four fragments of text extracted from
  172312. ** the data in the current row. The first iteration of the for(...) loop
  172313. ** below attempts to locate a single fragment of text nToken tokens in
  172314. ** size that contains at least one instance of all phrases in the query
  172315. ** expression that appear in the current row. If such a fragment of text
  172316. ** cannot be found, the second iteration of the loop attempts to locate
  172317. ** a pair of fragments, and so on.
  172318. */
  172319. int nSnippet = 0; /* Number of fragments in this snippet */
  172320. SnippetFragment aSnippet[4]; /* Maximum of 4 fragments per snippet */
  172321. int nFToken = -1; /* Number of tokens in each fragment */
  172322. if( !pCsr->pExpr ){
  172323. sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
  172324. return;
  172325. }
  172326. /* Limit the snippet length to 64 tokens. */
  172327. if( nToken<-64 ) nToken = -64;
  172328. if( nToken>+64 ) nToken = +64;
  172329. for(nSnippet=1; 1; nSnippet++){
  172330. int iSnip; /* Loop counter 0..nSnippet-1 */
  172331. u64 mCovered = 0; /* Bitmask of phrases covered by snippet */
  172332. u64 mSeen = 0; /* Bitmask of phrases seen by BestSnippet() */
  172333. if( nToken>=0 ){
  172334. nFToken = (nToken+nSnippet-1) / nSnippet;
  172335. }else{
  172336. nFToken = -1 * nToken;
  172337. }
  172338. for(iSnip=0; iSnip<nSnippet; iSnip++){
  172339. int iBestScore = -1; /* Best score of columns checked so far */
  172340. int iRead; /* Used to iterate through columns */
  172341. SnippetFragment *pFragment = &aSnippet[iSnip];
  172342. memset(pFragment, 0, sizeof(*pFragment));
  172343. /* Loop through all columns of the table being considered for snippets.
  172344. ** If the iCol argument to this function was negative, this means all
  172345. ** columns of the FTS3 table. Otherwise, only column iCol is considered.
  172346. */
  172347. for(iRead=0; iRead<pTab->nColumn; iRead++){
  172348. SnippetFragment sF = {0, 0, 0, 0};
  172349. int iS = 0;
  172350. if( iCol>=0 && iRead!=iCol ) continue;
  172351. /* Find the best snippet of nFToken tokens in column iRead. */
  172352. rc = fts3BestSnippet(nFToken, pCsr, iRead, mCovered, &mSeen, &sF, &iS);
  172353. if( rc!=SQLITE_OK ){
  172354. goto snippet_out;
  172355. }
  172356. if( iS>iBestScore ){
  172357. *pFragment = sF;
  172358. iBestScore = iS;
  172359. }
  172360. }
  172361. mCovered |= pFragment->covered;
  172362. }
  172363. /* If all query phrases seen by fts3BestSnippet() are present in at least
  172364. ** one of the nSnippet snippet fragments, break out of the loop.
  172365. */
  172366. assert( (mCovered&mSeen)==mCovered );
  172367. if( mSeen==mCovered || nSnippet==SizeofArray(aSnippet) ) break;
  172368. }
  172369. assert( nFToken>0 );
  172370. for(i=0; i<nSnippet && rc==SQLITE_OK; i++){
  172371. rc = fts3SnippetText(pCsr, &aSnippet[i],
  172372. i, (i==nSnippet-1), nFToken, zStart, zEnd, zEllipsis, &res
  172373. );
  172374. }
  172375. snippet_out:
  172376. sqlite3Fts3SegmentsClose(pTab);
  172377. if( rc!=SQLITE_OK ){
  172378. sqlite3_result_error_code(pCtx, rc);
  172379. sqlite3_free(res.z);
  172380. }else{
  172381. sqlite3_result_text(pCtx, res.z, -1, sqlite3_free);
  172382. }
  172383. }
  172384. typedef struct TermOffset TermOffset;
  172385. typedef struct TermOffsetCtx TermOffsetCtx;
  172386. struct TermOffset {
  172387. char *pList; /* Position-list */
  172388. int iPos; /* Position just read from pList */
  172389. int iOff; /* Offset of this term from read positions */
  172390. };
  172391. struct TermOffsetCtx {
  172392. Fts3Cursor *pCsr;
  172393. int iCol; /* Column of table to populate aTerm for */
  172394. int iTerm;
  172395. sqlite3_int64 iDocid;
  172396. TermOffset *aTerm;
  172397. };
  172398. /*
  172399. ** This function is an fts3ExprIterate() callback used by sqlite3Fts3Offsets().
  172400. */
  172401. static int fts3ExprTermOffsetInit(Fts3Expr *pExpr, int iPhrase, void *ctx){
  172402. TermOffsetCtx *p = (TermOffsetCtx *)ctx;
  172403. int nTerm; /* Number of tokens in phrase */
  172404. int iTerm; /* For looping through nTerm phrase terms */
  172405. char *pList; /* Pointer to position list for phrase */
  172406. int iPos = 0; /* First position in position-list */
  172407. int rc;
  172408. UNUSED_PARAMETER(iPhrase);
  172409. rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pList);
  172410. nTerm = pExpr->pPhrase->nToken;
  172411. if( pList ){
  172412. fts3GetDeltaPosition(&pList, &iPos);
  172413. assert_fts3_nc( iPos>=0 );
  172414. }
  172415. for(iTerm=0; iTerm<nTerm; iTerm++){
  172416. TermOffset *pT = &p->aTerm[p->iTerm++];
  172417. pT->iOff = nTerm-iTerm-1;
  172418. pT->pList = pList;
  172419. pT->iPos = iPos;
  172420. }
  172421. return rc;
  172422. }
  172423. /*
  172424. ** Implementation of offsets() function.
  172425. */
  172426. SQLITE_PRIVATE void sqlite3Fts3Offsets(
  172427. sqlite3_context *pCtx, /* SQLite function call context */
  172428. Fts3Cursor *pCsr /* Cursor object */
  172429. ){
  172430. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  172431. sqlite3_tokenizer_module const *pMod = pTab->pTokenizer->pModule;
  172432. int rc; /* Return Code */
  172433. int nToken; /* Number of tokens in query */
  172434. int iCol; /* Column currently being processed */
  172435. StrBuffer res = {0, 0, 0}; /* Result string */
  172436. TermOffsetCtx sCtx; /* Context for fts3ExprTermOffsetInit() */
  172437. if( !pCsr->pExpr ){
  172438. sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
  172439. return;
  172440. }
  172441. memset(&sCtx, 0, sizeof(sCtx));
  172442. assert( pCsr->isRequireSeek==0 );
  172443. /* Count the number of terms in the query */
  172444. rc = fts3ExprLoadDoclists(pCsr, 0, &nToken);
  172445. if( rc!=SQLITE_OK ) goto offsets_out;
  172446. /* Allocate the array of TermOffset iterators. */
  172447. sCtx.aTerm = (TermOffset *)sqlite3_malloc64(sizeof(TermOffset)*nToken);
  172448. if( 0==sCtx.aTerm ){
  172449. rc = SQLITE_NOMEM;
  172450. goto offsets_out;
  172451. }
  172452. sCtx.iDocid = pCsr->iPrevId;
  172453. sCtx.pCsr = pCsr;
  172454. /* Loop through the table columns, appending offset information to
  172455. ** string-buffer res for each column.
  172456. */
  172457. for(iCol=0; iCol<pTab->nColumn; iCol++){
  172458. sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor */
  172459. const char *ZDUMMY; /* Dummy argument used with xNext() */
  172460. int NDUMMY = 0; /* Dummy argument used with xNext() */
  172461. int iStart = 0;
  172462. int iEnd = 0;
  172463. int iCurrent = 0;
  172464. const char *zDoc;
  172465. int nDoc;
  172466. /* Initialize the contents of sCtx.aTerm[] for column iCol. There is
  172467. ** no way that this operation can fail, so the return code from
  172468. ** fts3ExprIterate() can be discarded.
  172469. */
  172470. sCtx.iCol = iCol;
  172471. sCtx.iTerm = 0;
  172472. (void)fts3ExprIterate(pCsr->pExpr, fts3ExprTermOffsetInit, (void*)&sCtx);
  172473. /* Retreive the text stored in column iCol. If an SQL NULL is stored
  172474. ** in column iCol, jump immediately to the next iteration of the loop.
  172475. ** If an OOM occurs while retrieving the data (this can happen if SQLite
  172476. ** needs to transform the data from utf-16 to utf-8), return SQLITE_NOMEM
  172477. ** to the caller.
  172478. */
  172479. zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol+1);
  172480. nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
  172481. if( zDoc==0 ){
  172482. if( sqlite3_column_type(pCsr->pStmt, iCol+1)==SQLITE_NULL ){
  172483. continue;
  172484. }
  172485. rc = SQLITE_NOMEM;
  172486. goto offsets_out;
  172487. }
  172488. /* Initialize a tokenizer iterator to iterate through column iCol. */
  172489. rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid,
  172490. zDoc, nDoc, &pC
  172491. );
  172492. if( rc!=SQLITE_OK ) goto offsets_out;
  172493. rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
  172494. while( rc==SQLITE_OK ){
  172495. int i; /* Used to loop through terms */
  172496. int iMinPos = 0x7FFFFFFF; /* Position of next token */
  172497. TermOffset *pTerm = 0; /* TermOffset associated with next token */
  172498. for(i=0; i<nToken; i++){
  172499. TermOffset *pT = &sCtx.aTerm[i];
  172500. if( pT->pList && (pT->iPos-pT->iOff)<iMinPos ){
  172501. iMinPos = pT->iPos-pT->iOff;
  172502. pTerm = pT;
  172503. }
  172504. }
  172505. if( !pTerm ){
  172506. /* All offsets for this column have been gathered. */
  172507. rc = SQLITE_DONE;
  172508. }else{
  172509. assert_fts3_nc( iCurrent<=iMinPos );
  172510. if( 0==(0xFE&*pTerm->pList) ){
  172511. pTerm->pList = 0;
  172512. }else{
  172513. fts3GetDeltaPosition(&pTerm->pList, &pTerm->iPos);
  172514. }
  172515. while( rc==SQLITE_OK && iCurrent<iMinPos ){
  172516. rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
  172517. }
  172518. if( rc==SQLITE_OK ){
  172519. char aBuffer[64];
  172520. sqlite3_snprintf(sizeof(aBuffer), aBuffer,
  172521. "%d %d %d %d ", iCol, pTerm-sCtx.aTerm, iStart, iEnd-iStart
  172522. );
  172523. rc = fts3StringAppend(&res, aBuffer, -1);
  172524. }else if( rc==SQLITE_DONE && pTab->zContentTbl==0 ){
  172525. rc = FTS_CORRUPT_VTAB;
  172526. }
  172527. }
  172528. }
  172529. if( rc==SQLITE_DONE ){
  172530. rc = SQLITE_OK;
  172531. }
  172532. pMod->xClose(pC);
  172533. if( rc!=SQLITE_OK ) goto offsets_out;
  172534. }
  172535. offsets_out:
  172536. sqlite3_free(sCtx.aTerm);
  172537. assert( rc!=SQLITE_DONE );
  172538. sqlite3Fts3SegmentsClose(pTab);
  172539. if( rc!=SQLITE_OK ){
  172540. sqlite3_result_error_code(pCtx, rc);
  172541. sqlite3_free(res.z);
  172542. }else{
  172543. sqlite3_result_text(pCtx, res.z, res.n-1, sqlite3_free);
  172544. }
  172545. return;
  172546. }
  172547. /*
  172548. ** Implementation of matchinfo() function.
  172549. */
  172550. SQLITE_PRIVATE void sqlite3Fts3Matchinfo(
  172551. sqlite3_context *pContext, /* Function call context */
  172552. Fts3Cursor *pCsr, /* FTS3 table cursor */
  172553. const char *zArg /* Second arg to matchinfo() function */
  172554. ){
  172555. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  172556. const char *zFormat;
  172557. if( zArg ){
  172558. zFormat = zArg;
  172559. }else{
  172560. zFormat = FTS3_MATCHINFO_DEFAULT;
  172561. }
  172562. if( !pCsr->pExpr ){
  172563. sqlite3_result_blob(pContext, "", 0, SQLITE_STATIC);
  172564. return;
  172565. }else{
  172566. /* Retrieve matchinfo() data. */
  172567. fts3GetMatchinfo(pContext, pCsr, zFormat);
  172568. sqlite3Fts3SegmentsClose(pTab);
  172569. }
  172570. }
  172571. #endif
  172572. /************** End of fts3_snippet.c ****************************************/
  172573. /************** Begin file fts3_unicode.c ************************************/
  172574. /*
  172575. ** 2012 May 24
  172576. **
  172577. ** The author disclaims copyright to this source code. In place of
  172578. ** a legal notice, here is a blessing:
  172579. **
  172580. ** May you do good and not evil.
  172581. ** May you find forgiveness for yourself and forgive others.
  172582. ** May you share freely, never taking more than you give.
  172583. **
  172584. ******************************************************************************
  172585. **
  172586. ** Implementation of the "unicode" full-text-search tokenizer.
  172587. */
  172588. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  172589. /* #include "fts3Int.h" */
  172590. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  172591. /* #include <assert.h> */
  172592. /* #include <stdlib.h> */
  172593. /* #include <stdio.h> */
  172594. /* #include <string.h> */
  172595. /* #include "fts3_tokenizer.h" */
  172596. /*
  172597. ** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied
  172598. ** from the sqlite3 source file utf.c. If this file is compiled as part
  172599. ** of the amalgamation, they are not required.
  172600. */
  172601. #ifndef SQLITE_AMALGAMATION
  172602. static const unsigned char sqlite3Utf8Trans1[] = {
  172603. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  172604. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  172605. 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
  172606. 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
  172607. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  172608. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  172609. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  172610. 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
  172611. };
  172612. #define READ_UTF8(zIn, zTerm, c) \
  172613. c = *(zIn++); \
  172614. if( c>=0xc0 ){ \
  172615. c = sqlite3Utf8Trans1[c-0xc0]; \
  172616. while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \
  172617. c = (c<<6) + (0x3f & *(zIn++)); \
  172618. } \
  172619. if( c<0x80 \
  172620. || (c&0xFFFFF800)==0xD800 \
  172621. || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \
  172622. }
  172623. #define WRITE_UTF8(zOut, c) { \
  172624. if( c<0x00080 ){ \
  172625. *zOut++ = (u8)(c&0xFF); \
  172626. } \
  172627. else if( c<0x00800 ){ \
  172628. *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); \
  172629. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  172630. } \
  172631. else if( c<0x10000 ){ \
  172632. *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); \
  172633. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
  172634. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  172635. }else{ \
  172636. *zOut++ = 0xF0 + (u8)((c>>18) & 0x07); \
  172637. *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); \
  172638. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
  172639. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  172640. } \
  172641. }
  172642. #endif /* ifndef SQLITE_AMALGAMATION */
  172643. typedef struct unicode_tokenizer unicode_tokenizer;
  172644. typedef struct unicode_cursor unicode_cursor;
  172645. struct unicode_tokenizer {
  172646. sqlite3_tokenizer base;
  172647. int eRemoveDiacritic;
  172648. int nException;
  172649. int *aiException;
  172650. };
  172651. struct unicode_cursor {
  172652. sqlite3_tokenizer_cursor base;
  172653. const unsigned char *aInput; /* Input text being tokenized */
  172654. int nInput; /* Size of aInput[] in bytes */
  172655. int iOff; /* Current offset within aInput[] */
  172656. int iToken; /* Index of next token to be returned */
  172657. char *zToken; /* storage for current token */
  172658. int nAlloc; /* space allocated at zToken */
  172659. };
  172660. /*
  172661. ** Destroy a tokenizer allocated by unicodeCreate().
  172662. */
  172663. static int unicodeDestroy(sqlite3_tokenizer *pTokenizer){
  172664. if( pTokenizer ){
  172665. unicode_tokenizer *p = (unicode_tokenizer *)pTokenizer;
  172666. sqlite3_free(p->aiException);
  172667. sqlite3_free(p);
  172668. }
  172669. return SQLITE_OK;
  172670. }
  172671. /*
  172672. ** As part of a tokenchars= or separators= option, the CREATE VIRTUAL TABLE
  172673. ** statement has specified that the tokenizer for this table shall consider
  172674. ** all characters in string zIn/nIn to be separators (if bAlnum==0) or
  172675. ** token characters (if bAlnum==1).
  172676. **
  172677. ** For each codepoint in the zIn/nIn string, this function checks if the
  172678. ** sqlite3FtsUnicodeIsalnum() function already returns the desired result.
  172679. ** If so, no action is taken. Otherwise, the codepoint is added to the
  172680. ** unicode_tokenizer.aiException[] array. For the purposes of tokenization,
  172681. ** the return value of sqlite3FtsUnicodeIsalnum() is inverted for all
  172682. ** codepoints in the aiException[] array.
  172683. **
  172684. ** If a standalone diacritic mark (one that sqlite3FtsUnicodeIsdiacritic()
  172685. ** identifies as a diacritic) occurs in the zIn/nIn string it is ignored.
  172686. ** It is not possible to change the behavior of the tokenizer with respect
  172687. ** to these codepoints.
  172688. */
  172689. static int unicodeAddExceptions(
  172690. unicode_tokenizer *p, /* Tokenizer to add exceptions to */
  172691. int bAlnum, /* Replace Isalnum() return value with this */
  172692. const char *zIn, /* Array of characters to make exceptions */
  172693. int nIn /* Length of z in bytes */
  172694. ){
  172695. const unsigned char *z = (const unsigned char *)zIn;
  172696. const unsigned char *zTerm = &z[nIn];
  172697. unsigned int iCode;
  172698. int nEntry = 0;
  172699. assert( bAlnum==0 || bAlnum==1 );
  172700. while( z<zTerm ){
  172701. READ_UTF8(z, zTerm, iCode);
  172702. assert( (sqlite3FtsUnicodeIsalnum((int)iCode) & 0xFFFFFFFE)==0 );
  172703. if( sqlite3FtsUnicodeIsalnum((int)iCode)!=bAlnum
  172704. && sqlite3FtsUnicodeIsdiacritic((int)iCode)==0
  172705. ){
  172706. nEntry++;
  172707. }
  172708. }
  172709. if( nEntry ){
  172710. int *aNew; /* New aiException[] array */
  172711. int nNew; /* Number of valid entries in array aNew[] */
  172712. aNew = sqlite3_realloc64(p->aiException,(p->nException+nEntry)*sizeof(int));
  172713. if( aNew==0 ) return SQLITE_NOMEM;
  172714. nNew = p->nException;
  172715. z = (const unsigned char *)zIn;
  172716. while( z<zTerm ){
  172717. READ_UTF8(z, zTerm, iCode);
  172718. if( sqlite3FtsUnicodeIsalnum((int)iCode)!=bAlnum
  172719. && sqlite3FtsUnicodeIsdiacritic((int)iCode)==0
  172720. ){
  172721. int i, j;
  172722. for(i=0; i<nNew && aNew[i]<(int)iCode; i++);
  172723. for(j=nNew; j>i; j--) aNew[j] = aNew[j-1];
  172724. aNew[i] = (int)iCode;
  172725. nNew++;
  172726. }
  172727. }
  172728. p->aiException = aNew;
  172729. p->nException = nNew;
  172730. }
  172731. return SQLITE_OK;
  172732. }
  172733. /*
  172734. ** Return true if the p->aiException[] array contains the value iCode.
  172735. */
  172736. static int unicodeIsException(unicode_tokenizer *p, int iCode){
  172737. if( p->nException>0 ){
  172738. int *a = p->aiException;
  172739. int iLo = 0;
  172740. int iHi = p->nException-1;
  172741. while( iHi>=iLo ){
  172742. int iTest = (iHi + iLo) / 2;
  172743. if( iCode==a[iTest] ){
  172744. return 1;
  172745. }else if( iCode>a[iTest] ){
  172746. iLo = iTest+1;
  172747. }else{
  172748. iHi = iTest-1;
  172749. }
  172750. }
  172751. }
  172752. return 0;
  172753. }
  172754. /*
  172755. ** Return true if, for the purposes of tokenization, codepoint iCode is
  172756. ** considered a token character (not a separator).
  172757. */
  172758. static int unicodeIsAlnum(unicode_tokenizer *p, int iCode){
  172759. assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
  172760. return sqlite3FtsUnicodeIsalnum(iCode) ^ unicodeIsException(p, iCode);
  172761. }
  172762. /*
  172763. ** Create a new tokenizer instance.
  172764. */
  172765. static int unicodeCreate(
  172766. int nArg, /* Size of array argv[] */
  172767. const char * const *azArg, /* Tokenizer creation arguments */
  172768. sqlite3_tokenizer **pp /* OUT: New tokenizer handle */
  172769. ){
  172770. unicode_tokenizer *pNew; /* New tokenizer object */
  172771. int i;
  172772. int rc = SQLITE_OK;
  172773. pNew = (unicode_tokenizer *) sqlite3_malloc(sizeof(unicode_tokenizer));
  172774. if( pNew==NULL ) return SQLITE_NOMEM;
  172775. memset(pNew, 0, sizeof(unicode_tokenizer));
  172776. pNew->eRemoveDiacritic = 1;
  172777. for(i=0; rc==SQLITE_OK && i<nArg; i++){
  172778. const char *z = azArg[i];
  172779. int n = (int)strlen(z);
  172780. if( n==19 && memcmp("remove_diacritics=1", z, 19)==0 ){
  172781. pNew->eRemoveDiacritic = 1;
  172782. }
  172783. else if( n==19 && memcmp("remove_diacritics=0", z, 19)==0 ){
  172784. pNew->eRemoveDiacritic = 0;
  172785. }
  172786. else if( n==19 && memcmp("remove_diacritics=2", z, 19)==0 ){
  172787. pNew->eRemoveDiacritic = 2;
  172788. }
  172789. else if( n>=11 && memcmp("tokenchars=", z, 11)==0 ){
  172790. rc = unicodeAddExceptions(pNew, 1, &z[11], n-11);
  172791. }
  172792. else if( n>=11 && memcmp("separators=", z, 11)==0 ){
  172793. rc = unicodeAddExceptions(pNew, 0, &z[11], n-11);
  172794. }
  172795. else{
  172796. /* Unrecognized argument */
  172797. rc = SQLITE_ERROR;
  172798. }
  172799. }
  172800. if( rc!=SQLITE_OK ){
  172801. unicodeDestroy((sqlite3_tokenizer *)pNew);
  172802. pNew = 0;
  172803. }
  172804. *pp = (sqlite3_tokenizer *)pNew;
  172805. return rc;
  172806. }
  172807. /*
  172808. ** Prepare to begin tokenizing a particular string. The input
  172809. ** string to be tokenized is pInput[0..nBytes-1]. A cursor
  172810. ** used to incrementally tokenize this string is returned in
  172811. ** *ppCursor.
  172812. */
  172813. static int unicodeOpen(
  172814. sqlite3_tokenizer *p, /* The tokenizer */
  172815. const char *aInput, /* Input string */
  172816. int nInput, /* Size of string aInput in bytes */
  172817. sqlite3_tokenizer_cursor **pp /* OUT: New cursor object */
  172818. ){
  172819. unicode_cursor *pCsr;
  172820. pCsr = (unicode_cursor *)sqlite3_malloc(sizeof(unicode_cursor));
  172821. if( pCsr==0 ){
  172822. return SQLITE_NOMEM;
  172823. }
  172824. memset(pCsr, 0, sizeof(unicode_cursor));
  172825. pCsr->aInput = (const unsigned char *)aInput;
  172826. if( aInput==0 ){
  172827. pCsr->nInput = 0;
  172828. }else if( nInput<0 ){
  172829. pCsr->nInput = (int)strlen(aInput);
  172830. }else{
  172831. pCsr->nInput = nInput;
  172832. }
  172833. *pp = &pCsr->base;
  172834. UNUSED_PARAMETER(p);
  172835. return SQLITE_OK;
  172836. }
  172837. /*
  172838. ** Close a tokenization cursor previously opened by a call to
  172839. ** simpleOpen() above.
  172840. */
  172841. static int unicodeClose(sqlite3_tokenizer_cursor *pCursor){
  172842. unicode_cursor *pCsr = (unicode_cursor *) pCursor;
  172843. sqlite3_free(pCsr->zToken);
  172844. sqlite3_free(pCsr);
  172845. return SQLITE_OK;
  172846. }
  172847. /*
  172848. ** Extract the next token from a tokenization cursor. The cursor must
  172849. ** have been opened by a prior call to simpleOpen().
  172850. */
  172851. static int unicodeNext(
  172852. sqlite3_tokenizer_cursor *pC, /* Cursor returned by simpleOpen */
  172853. const char **paToken, /* OUT: Token text */
  172854. int *pnToken, /* OUT: Number of bytes at *paToken */
  172855. int *piStart, /* OUT: Starting offset of token */
  172856. int *piEnd, /* OUT: Ending offset of token */
  172857. int *piPos /* OUT: Position integer of token */
  172858. ){
  172859. unicode_cursor *pCsr = (unicode_cursor *)pC;
  172860. unicode_tokenizer *p = ((unicode_tokenizer *)pCsr->base.pTokenizer);
  172861. unsigned int iCode = 0;
  172862. char *zOut;
  172863. const unsigned char *z = &pCsr->aInput[pCsr->iOff];
  172864. const unsigned char *zStart = z;
  172865. const unsigned char *zEnd;
  172866. const unsigned char *zTerm = &pCsr->aInput[pCsr->nInput];
  172867. /* Scan past any delimiter characters before the start of the next token.
  172868. ** Return SQLITE_DONE early if this takes us all the way to the end of
  172869. ** the input. */
  172870. while( z<zTerm ){
  172871. READ_UTF8(z, zTerm, iCode);
  172872. if( unicodeIsAlnum(p, (int)iCode) ) break;
  172873. zStart = z;
  172874. }
  172875. if( zStart>=zTerm ) return SQLITE_DONE;
  172876. zOut = pCsr->zToken;
  172877. do {
  172878. int iOut;
  172879. /* Grow the output buffer if required. */
  172880. if( (zOut-pCsr->zToken)>=(pCsr->nAlloc-4) ){
  172881. char *zNew = sqlite3_realloc64(pCsr->zToken, pCsr->nAlloc+64);
  172882. if( !zNew ) return SQLITE_NOMEM;
  172883. zOut = &zNew[zOut - pCsr->zToken];
  172884. pCsr->zToken = zNew;
  172885. pCsr->nAlloc += 64;
  172886. }
  172887. /* Write the folded case of the last character read to the output */
  172888. zEnd = z;
  172889. iOut = sqlite3FtsUnicodeFold((int)iCode, p->eRemoveDiacritic);
  172890. if( iOut ){
  172891. WRITE_UTF8(zOut, iOut);
  172892. }
  172893. /* If the cursor is not at EOF, read the next character */
  172894. if( z>=zTerm ) break;
  172895. READ_UTF8(z, zTerm, iCode);
  172896. }while( unicodeIsAlnum(p, (int)iCode)
  172897. || sqlite3FtsUnicodeIsdiacritic((int)iCode)
  172898. );
  172899. /* Set the output variables and return. */
  172900. pCsr->iOff = (int)(z - pCsr->aInput);
  172901. *paToken = pCsr->zToken;
  172902. *pnToken = (int)(zOut - pCsr->zToken);
  172903. *piStart = (int)(zStart - pCsr->aInput);
  172904. *piEnd = (int)(zEnd - pCsr->aInput);
  172905. *piPos = pCsr->iToken++;
  172906. return SQLITE_OK;
  172907. }
  172908. /*
  172909. ** Set *ppModule to a pointer to the sqlite3_tokenizer_module
  172910. ** structure for the unicode tokenizer.
  172911. */
  172912. SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const **ppModule){
  172913. static const sqlite3_tokenizer_module module = {
  172914. 0,
  172915. unicodeCreate,
  172916. unicodeDestroy,
  172917. unicodeOpen,
  172918. unicodeClose,
  172919. unicodeNext,
  172920. 0,
  172921. };
  172922. *ppModule = &module;
  172923. }
  172924. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  172925. #endif /* ifndef SQLITE_DISABLE_FTS3_UNICODE */
  172926. /************** End of fts3_unicode.c ****************************************/
  172927. /************** Begin file fts3_unicode2.c ***********************************/
  172928. /*
  172929. ** 2012-05-25
  172930. **
  172931. ** The author disclaims copyright to this source code. In place of
  172932. ** a legal notice, here is a blessing:
  172933. **
  172934. ** May you do good and not evil.
  172935. ** May you find forgiveness for yourself and forgive others.
  172936. ** May you share freely, never taking more than you give.
  172937. **
  172938. ******************************************************************************
  172939. */
  172940. /*
  172941. ** DO NOT EDIT THIS MACHINE GENERATED FILE.
  172942. */
  172943. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  172944. #if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
  172945. /* #include <assert.h> */
  172946. /*
  172947. ** Return true if the argument corresponds to a unicode codepoint
  172948. ** classified as either a letter or a number. Otherwise false.
  172949. **
  172950. ** The results are undefined if the value passed to this function
  172951. ** is less than zero.
  172952. */
  172953. SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int c){
  172954. /* Each unsigned integer in the following array corresponds to a contiguous
  172955. ** range of unicode codepoints that are not either letters or numbers (i.e.
  172956. ** codepoints for which this function should return 0).
  172957. **
  172958. ** The most significant 22 bits in each 32-bit value contain the first
  172959. ** codepoint in the range. The least significant 10 bits are used to store
  172960. ** the size of the range (always at least 1). In other words, the value
  172961. ** ((C<<22) + N) represents a range of N codepoints starting with codepoint
  172962. ** C. It is not possible to represent a range larger than 1023 codepoints
  172963. ** using this format.
  172964. */
  172965. static const unsigned int aEntry[] = {
  172966. 0x00000030, 0x0000E807, 0x00016C06, 0x0001EC2F, 0x0002AC07,
  172967. 0x0002D001, 0x0002D803, 0x0002EC01, 0x0002FC01, 0x00035C01,
  172968. 0x0003DC01, 0x000B0804, 0x000B480E, 0x000B9407, 0x000BB401,
  172969. 0x000BBC81, 0x000DD401, 0x000DF801, 0x000E1002, 0x000E1C01,
  172970. 0x000FD801, 0x00120808, 0x00156806, 0x00162402, 0x00163C01,
  172971. 0x00164437, 0x0017CC02, 0x00180005, 0x00181816, 0x00187802,
  172972. 0x00192C15, 0x0019A804, 0x0019C001, 0x001B5001, 0x001B580F,
  172973. 0x001B9C07, 0x001BF402, 0x001C000E, 0x001C3C01, 0x001C4401,
  172974. 0x001CC01B, 0x001E980B, 0x001FAC09, 0x001FD804, 0x00205804,
  172975. 0x00206C09, 0x00209403, 0x0020A405, 0x0020C00F, 0x00216403,
  172976. 0x00217801, 0x0023901B, 0x00240004, 0x0024E803, 0x0024F812,
  172977. 0x00254407, 0x00258804, 0x0025C001, 0x00260403, 0x0026F001,
  172978. 0x0026F807, 0x00271C02, 0x00272C03, 0x00275C01, 0x00278802,
  172979. 0x0027C802, 0x0027E802, 0x00280403, 0x0028F001, 0x0028F805,
  172980. 0x00291C02, 0x00292C03, 0x00294401, 0x0029C002, 0x0029D401,
  172981. 0x002A0403, 0x002AF001, 0x002AF808, 0x002B1C03, 0x002B2C03,
  172982. 0x002B8802, 0x002BC002, 0x002C0403, 0x002CF001, 0x002CF807,
  172983. 0x002D1C02, 0x002D2C03, 0x002D5802, 0x002D8802, 0x002DC001,
  172984. 0x002E0801, 0x002EF805, 0x002F1803, 0x002F2804, 0x002F5C01,
  172985. 0x002FCC08, 0x00300403, 0x0030F807, 0x00311803, 0x00312804,
  172986. 0x00315402, 0x00318802, 0x0031FC01, 0x00320802, 0x0032F001,
  172987. 0x0032F807, 0x00331803, 0x00332804, 0x00335402, 0x00338802,
  172988. 0x00340802, 0x0034F807, 0x00351803, 0x00352804, 0x00355C01,
  172989. 0x00358802, 0x0035E401, 0x00360802, 0x00372801, 0x00373C06,
  172990. 0x00375801, 0x00376008, 0x0037C803, 0x0038C401, 0x0038D007,
  172991. 0x0038FC01, 0x00391C09, 0x00396802, 0x003AC401, 0x003AD006,
  172992. 0x003AEC02, 0x003B2006, 0x003C041F, 0x003CD00C, 0x003DC417,
  172993. 0x003E340B, 0x003E6424, 0x003EF80F, 0x003F380D, 0x0040AC14,
  172994. 0x00412806, 0x00415804, 0x00417803, 0x00418803, 0x00419C07,
  172995. 0x0041C404, 0x0042080C, 0x00423C01, 0x00426806, 0x0043EC01,
  172996. 0x004D740C, 0x004E400A, 0x00500001, 0x0059B402, 0x005A0001,
  172997. 0x005A6C02, 0x005BAC03, 0x005C4803, 0x005CC805, 0x005D4802,
  172998. 0x005DC802, 0x005ED023, 0x005F6004, 0x005F7401, 0x0060000F,
  172999. 0x0062A401, 0x0064800C, 0x0064C00C, 0x00650001, 0x00651002,
  173000. 0x0066C011, 0x00672002, 0x00677822, 0x00685C05, 0x00687802,
  173001. 0x0069540A, 0x0069801D, 0x0069FC01, 0x006A8007, 0x006AA006,
  173002. 0x006C0005, 0x006CD011, 0x006D6823, 0x006E0003, 0x006E840D,
  173003. 0x006F980E, 0x006FF004, 0x00709014, 0x0070EC05, 0x0071F802,
  173004. 0x00730008, 0x00734019, 0x0073B401, 0x0073C803, 0x00770027,
  173005. 0x0077F004, 0x007EF401, 0x007EFC03, 0x007F3403, 0x007F7403,
  173006. 0x007FB403, 0x007FF402, 0x00800065, 0x0081A806, 0x0081E805,
  173007. 0x00822805, 0x0082801A, 0x00834021, 0x00840002, 0x00840C04,
  173008. 0x00842002, 0x00845001, 0x00845803, 0x00847806, 0x00849401,
  173009. 0x00849C01, 0x0084A401, 0x0084B801, 0x0084E802, 0x00850005,
  173010. 0x00852804, 0x00853C01, 0x00864264, 0x00900027, 0x0091000B,
  173011. 0x0092704E, 0x00940200, 0x009C0475, 0x009E53B9, 0x00AD400A,
  173012. 0x00B39406, 0x00B3BC03, 0x00B3E404, 0x00B3F802, 0x00B5C001,
  173013. 0x00B5FC01, 0x00B7804F, 0x00B8C00C, 0x00BA001A, 0x00BA6C59,
  173014. 0x00BC00D6, 0x00BFC00C, 0x00C00005, 0x00C02019, 0x00C0A807,
  173015. 0x00C0D802, 0x00C0F403, 0x00C26404, 0x00C28001, 0x00C3EC01,
  173016. 0x00C64002, 0x00C6580A, 0x00C70024, 0x00C8001F, 0x00C8A81E,
  173017. 0x00C94001, 0x00C98020, 0x00CA2827, 0x00CB003F, 0x00CC0100,
  173018. 0x01370040, 0x02924037, 0x0293F802, 0x02983403, 0x0299BC10,
  173019. 0x029A7C01, 0x029BC008, 0x029C0017, 0x029C8002, 0x029E2402,
  173020. 0x02A00801, 0x02A01801, 0x02A02C01, 0x02A08C09, 0x02A0D804,
  173021. 0x02A1D004, 0x02A20002, 0x02A2D011, 0x02A33802, 0x02A38012,
  173022. 0x02A3E003, 0x02A4980A, 0x02A51C0D, 0x02A57C01, 0x02A60004,
  173023. 0x02A6CC1B, 0x02A77802, 0x02A8A40E, 0x02A90C01, 0x02A93002,
  173024. 0x02A97004, 0x02A9DC03, 0x02A9EC01, 0x02AAC001, 0x02AAC803,
  173025. 0x02AADC02, 0x02AAF802, 0x02AB0401, 0x02AB7802, 0x02ABAC07,
  173026. 0x02ABD402, 0x02AF8C0B, 0x03600001, 0x036DFC02, 0x036FFC02,
  173027. 0x037FFC01, 0x03EC7801, 0x03ECA401, 0x03EEC810, 0x03F4F802,
  173028. 0x03F7F002, 0x03F8001A, 0x03F88007, 0x03F8C023, 0x03F95013,
  173029. 0x03F9A004, 0x03FBFC01, 0x03FC040F, 0x03FC6807, 0x03FCEC06,
  173030. 0x03FD6C0B, 0x03FF8007, 0x03FFA007, 0x03FFE405, 0x04040003,
  173031. 0x0404DC09, 0x0405E411, 0x0406400C, 0x0407402E, 0x040E7C01,
  173032. 0x040F4001, 0x04215C01, 0x04247C01, 0x0424FC01, 0x04280403,
  173033. 0x04281402, 0x04283004, 0x0428E003, 0x0428FC01, 0x04294009,
  173034. 0x0429FC01, 0x042CE407, 0x04400003, 0x0440E016, 0x04420003,
  173035. 0x0442C012, 0x04440003, 0x04449C0E, 0x04450004, 0x04460003,
  173036. 0x0446CC0E, 0x04471404, 0x045AAC0D, 0x0491C004, 0x05BD442E,
  173037. 0x05BE3C04, 0x074000F6, 0x07440027, 0x0744A4B5, 0x07480046,
  173038. 0x074C0057, 0x075B0401, 0x075B6C01, 0x075BEC01, 0x075C5401,
  173039. 0x075CD401, 0x075D3C01, 0x075DBC01, 0x075E2401, 0x075EA401,
  173040. 0x075F0C01, 0x07BBC002, 0x07C0002C, 0x07C0C064, 0x07C2800F,
  173041. 0x07C2C40E, 0x07C3040F, 0x07C3440F, 0x07C4401F, 0x07C4C03C,
  173042. 0x07C5C02B, 0x07C7981D, 0x07C8402B, 0x07C90009, 0x07C94002,
  173043. 0x07CC0021, 0x07CCC006, 0x07CCDC46, 0x07CE0014, 0x07CE8025,
  173044. 0x07CF1805, 0x07CF8011, 0x07D0003F, 0x07D10001, 0x07D108B6,
  173045. 0x07D3E404, 0x07D4003E, 0x07D50004, 0x07D54018, 0x07D7EC46,
  173046. 0x07D9140B, 0x07DA0046, 0x07DC0074, 0x38000401, 0x38008060,
  173047. 0x380400F0,
  173048. };
  173049. static const unsigned int aAscii[4] = {
  173050. 0xFFFFFFFF, 0xFC00FFFF, 0xF8000001, 0xF8000001,
  173051. };
  173052. if( (unsigned int)c<128 ){
  173053. return ( (aAscii[c >> 5] & ((unsigned int)1 << (c & 0x001F)))==0 );
  173054. }else if( (unsigned int)c<(1<<22) ){
  173055. unsigned int key = (((unsigned int)c)<<10) | 0x000003FF;
  173056. int iRes = 0;
  173057. int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
  173058. int iLo = 0;
  173059. while( iHi>=iLo ){
  173060. int iTest = (iHi + iLo) / 2;
  173061. if( key >= aEntry[iTest] ){
  173062. iRes = iTest;
  173063. iLo = iTest+1;
  173064. }else{
  173065. iHi = iTest-1;
  173066. }
  173067. }
  173068. assert( aEntry[0]<key );
  173069. assert( key>=aEntry[iRes] );
  173070. return (((unsigned int)c) >= ((aEntry[iRes]>>10) + (aEntry[iRes]&0x3FF)));
  173071. }
  173072. return 1;
  173073. }
  173074. /*
  173075. ** If the argument is a codepoint corresponding to a lowercase letter
  173076. ** in the ASCII range with a diacritic added, return the codepoint
  173077. ** of the ASCII letter only. For example, if passed 235 - "LATIN
  173078. ** SMALL LETTER E WITH DIAERESIS" - return 65 ("LATIN SMALL LETTER
  173079. ** E"). The resuls of passing a codepoint that corresponds to an
  173080. ** uppercase letter are undefined.
  173081. */
  173082. static int remove_diacritic(int c, int bComplex){
  173083. unsigned short aDia[] = {
  173084. 0, 1797, 1848, 1859, 1891, 1928, 1940, 1995,
  173085. 2024, 2040, 2060, 2110, 2168, 2206, 2264, 2286,
  173086. 2344, 2383, 2472, 2488, 2516, 2596, 2668, 2732,
  173087. 2782, 2842, 2894, 2954, 2984, 3000, 3028, 3336,
  173088. 3456, 3696, 3712, 3728, 3744, 3766, 3832, 3896,
  173089. 3912, 3928, 3944, 3968, 4008, 4040, 4056, 4106,
  173090. 4138, 4170, 4202, 4234, 4266, 4296, 4312, 4344,
  173091. 4408, 4424, 4442, 4472, 4488, 4504, 6148, 6198,
  173092. 6264, 6280, 6360, 6429, 6505, 6529, 61448, 61468,
  173093. 61512, 61534, 61592, 61610, 61642, 61672, 61688, 61704,
  173094. 61726, 61784, 61800, 61816, 61836, 61880, 61896, 61914,
  173095. 61948, 61998, 62062, 62122, 62154, 62184, 62200, 62218,
  173096. 62252, 62302, 62364, 62410, 62442, 62478, 62536, 62554,
  173097. 62584, 62604, 62640, 62648, 62656, 62664, 62730, 62766,
  173098. 62830, 62890, 62924, 62974, 63032, 63050, 63082, 63118,
  173099. 63182, 63242, 63274, 63310, 63368, 63390,
  173100. };
  173101. #define HIBIT ((unsigned char)0x80)
  173102. unsigned char aChar[] = {
  173103. '\0', 'a', 'c', 'e', 'i', 'n',
  173104. 'o', 'u', 'y', 'y', 'a', 'c',
  173105. 'd', 'e', 'e', 'g', 'h', 'i',
  173106. 'j', 'k', 'l', 'n', 'o', 'r',
  173107. 's', 't', 'u', 'u', 'w', 'y',
  173108. 'z', 'o', 'u', 'a', 'i', 'o',
  173109. 'u', 'u'|HIBIT, 'a'|HIBIT, 'g', 'k', 'o',
  173110. 'o'|HIBIT, 'j', 'g', 'n', 'a'|HIBIT, 'a',
  173111. 'e', 'i', 'o', 'r', 'u', 's',
  173112. 't', 'h', 'a', 'e', 'o'|HIBIT, 'o',
  173113. 'o'|HIBIT, 'y', '\0', '\0', '\0', '\0',
  173114. '\0', '\0', '\0', '\0', 'a', 'b',
  173115. 'c'|HIBIT, 'd', 'd', 'e'|HIBIT, 'e', 'e'|HIBIT,
  173116. 'f', 'g', 'h', 'h', 'i', 'i'|HIBIT,
  173117. 'k', 'l', 'l'|HIBIT, 'l', 'm', 'n',
  173118. 'o'|HIBIT, 'p', 'r', 'r'|HIBIT, 'r', 's',
  173119. 's'|HIBIT, 't', 'u', 'u'|HIBIT, 'v', 'w',
  173120. 'w', 'x', 'y', 'z', 'h', 't',
  173121. 'w', 'y', 'a', 'a'|HIBIT, 'a'|HIBIT, 'a'|HIBIT,
  173122. 'e', 'e'|HIBIT, 'e'|HIBIT, 'i', 'o', 'o'|HIBIT,
  173123. 'o'|HIBIT, 'o'|HIBIT, 'u', 'u'|HIBIT, 'u'|HIBIT, 'y',
  173124. };
  173125. unsigned int key = (((unsigned int)c)<<3) | 0x00000007;
  173126. int iRes = 0;
  173127. int iHi = sizeof(aDia)/sizeof(aDia[0]) - 1;
  173128. int iLo = 0;
  173129. while( iHi>=iLo ){
  173130. int iTest = (iHi + iLo) / 2;
  173131. if( key >= aDia[iTest] ){
  173132. iRes = iTest;
  173133. iLo = iTest+1;
  173134. }else{
  173135. iHi = iTest-1;
  173136. }
  173137. }
  173138. assert( key>=aDia[iRes] );
  173139. if( bComplex==0 && (aChar[iRes] & 0x80) ) return c;
  173140. return (c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : ((int)aChar[iRes] & 0x7F);
  173141. }
  173142. /*
  173143. ** Return true if the argument interpreted as a unicode codepoint
  173144. ** is a diacritical modifier character.
  173145. */
  173146. SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int c){
  173147. unsigned int mask0 = 0x08029FDF;
  173148. unsigned int mask1 = 0x000361F8;
  173149. if( c<768 || c>817 ) return 0;
  173150. return (c < 768+32) ?
  173151. (mask0 & ((unsigned int)1 << (c-768))) :
  173152. (mask1 & ((unsigned int)1 << (c-768-32)));
  173153. }
  173154. /*
  173155. ** Interpret the argument as a unicode codepoint. If the codepoint
  173156. ** is an upper case character that has a lower case equivalent,
  173157. ** return the codepoint corresponding to the lower case version.
  173158. ** Otherwise, return a copy of the argument.
  173159. **
  173160. ** The results are undefined if the value passed to this function
  173161. ** is less than zero.
  173162. */
  173163. SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int c, int eRemoveDiacritic){
  173164. /* Each entry in the following array defines a rule for folding a range
  173165. ** of codepoints to lower case. The rule applies to a range of nRange
  173166. ** codepoints starting at codepoint iCode.
  173167. **
  173168. ** If the least significant bit in flags is clear, then the rule applies
  173169. ** to all nRange codepoints (i.e. all nRange codepoints are upper case and
  173170. ** need to be folded). Or, if it is set, then the rule only applies to
  173171. ** every second codepoint in the range, starting with codepoint C.
  173172. **
  173173. ** The 7 most significant bits in flags are an index into the aiOff[]
  173174. ** array. If a specific codepoint C does require folding, then its lower
  173175. ** case equivalent is ((C + aiOff[flags>>1]) & 0xFFFF).
  173176. **
  173177. ** The contents of this array are generated by parsing the CaseFolding.txt
  173178. ** file distributed as part of the "Unicode Character Database". See
  173179. ** http://www.unicode.org for details.
  173180. */
  173181. static const struct TableEntry {
  173182. unsigned short iCode;
  173183. unsigned char flags;
  173184. unsigned char nRange;
  173185. } aEntry[] = {
  173186. {65, 14, 26}, {181, 64, 1}, {192, 14, 23},
  173187. {216, 14, 7}, {256, 1, 48}, {306, 1, 6},
  173188. {313, 1, 16}, {330, 1, 46}, {376, 116, 1},
  173189. {377, 1, 6}, {383, 104, 1}, {385, 50, 1},
  173190. {386, 1, 4}, {390, 44, 1}, {391, 0, 1},
  173191. {393, 42, 2}, {395, 0, 1}, {398, 32, 1},
  173192. {399, 38, 1}, {400, 40, 1}, {401, 0, 1},
  173193. {403, 42, 1}, {404, 46, 1}, {406, 52, 1},
  173194. {407, 48, 1}, {408, 0, 1}, {412, 52, 1},
  173195. {413, 54, 1}, {415, 56, 1}, {416, 1, 6},
  173196. {422, 60, 1}, {423, 0, 1}, {425, 60, 1},
  173197. {428, 0, 1}, {430, 60, 1}, {431, 0, 1},
  173198. {433, 58, 2}, {435, 1, 4}, {439, 62, 1},
  173199. {440, 0, 1}, {444, 0, 1}, {452, 2, 1},
  173200. {453, 0, 1}, {455, 2, 1}, {456, 0, 1},
  173201. {458, 2, 1}, {459, 1, 18}, {478, 1, 18},
  173202. {497, 2, 1}, {498, 1, 4}, {502, 122, 1},
  173203. {503, 134, 1}, {504, 1, 40}, {544, 110, 1},
  173204. {546, 1, 18}, {570, 70, 1}, {571, 0, 1},
  173205. {573, 108, 1}, {574, 68, 1}, {577, 0, 1},
  173206. {579, 106, 1}, {580, 28, 1}, {581, 30, 1},
  173207. {582, 1, 10}, {837, 36, 1}, {880, 1, 4},
  173208. {886, 0, 1}, {902, 18, 1}, {904, 16, 3},
  173209. {908, 26, 1}, {910, 24, 2}, {913, 14, 17},
  173210. {931, 14, 9}, {962, 0, 1}, {975, 4, 1},
  173211. {976, 140, 1}, {977, 142, 1}, {981, 146, 1},
  173212. {982, 144, 1}, {984, 1, 24}, {1008, 136, 1},
  173213. {1009, 138, 1}, {1012, 130, 1}, {1013, 128, 1},
  173214. {1015, 0, 1}, {1017, 152, 1}, {1018, 0, 1},
  173215. {1021, 110, 3}, {1024, 34, 16}, {1040, 14, 32},
  173216. {1120, 1, 34}, {1162, 1, 54}, {1216, 6, 1},
  173217. {1217, 1, 14}, {1232, 1, 88}, {1329, 22, 38},
  173218. {4256, 66, 38}, {4295, 66, 1}, {4301, 66, 1},
  173219. {7680, 1, 150}, {7835, 132, 1}, {7838, 96, 1},
  173220. {7840, 1, 96}, {7944, 150, 8}, {7960, 150, 6},
  173221. {7976, 150, 8}, {7992, 150, 8}, {8008, 150, 6},
  173222. {8025, 151, 8}, {8040, 150, 8}, {8072, 150, 8},
  173223. {8088, 150, 8}, {8104, 150, 8}, {8120, 150, 2},
  173224. {8122, 126, 2}, {8124, 148, 1}, {8126, 100, 1},
  173225. {8136, 124, 4}, {8140, 148, 1}, {8152, 150, 2},
  173226. {8154, 120, 2}, {8168, 150, 2}, {8170, 118, 2},
  173227. {8172, 152, 1}, {8184, 112, 2}, {8186, 114, 2},
  173228. {8188, 148, 1}, {8486, 98, 1}, {8490, 92, 1},
  173229. {8491, 94, 1}, {8498, 12, 1}, {8544, 8, 16},
  173230. {8579, 0, 1}, {9398, 10, 26}, {11264, 22, 47},
  173231. {11360, 0, 1}, {11362, 88, 1}, {11363, 102, 1},
  173232. {11364, 90, 1}, {11367, 1, 6}, {11373, 84, 1},
  173233. {11374, 86, 1}, {11375, 80, 1}, {11376, 82, 1},
  173234. {11378, 0, 1}, {11381, 0, 1}, {11390, 78, 2},
  173235. {11392, 1, 100}, {11499, 1, 4}, {11506, 0, 1},
  173236. {42560, 1, 46}, {42624, 1, 24}, {42786, 1, 14},
  173237. {42802, 1, 62}, {42873, 1, 4}, {42877, 76, 1},
  173238. {42878, 1, 10}, {42891, 0, 1}, {42893, 74, 1},
  173239. {42896, 1, 4}, {42912, 1, 10}, {42922, 72, 1},
  173240. {65313, 14, 26},
  173241. };
  173242. static const unsigned short aiOff[] = {
  173243. 1, 2, 8, 15, 16, 26, 28, 32,
  173244. 37, 38, 40, 48, 63, 64, 69, 71,
  173245. 79, 80, 116, 202, 203, 205, 206, 207,
  173246. 209, 210, 211, 213, 214, 217, 218, 219,
  173247. 775, 7264, 10792, 10795, 23228, 23256, 30204, 54721,
  173248. 54753, 54754, 54756, 54787, 54793, 54809, 57153, 57274,
  173249. 57921, 58019, 58363, 61722, 65268, 65341, 65373, 65406,
  173250. 65408, 65410, 65415, 65424, 65436, 65439, 65450, 65462,
  173251. 65472, 65476, 65478, 65480, 65482, 65488, 65506, 65511,
  173252. 65514, 65521, 65527, 65528, 65529,
  173253. };
  173254. int ret = c;
  173255. assert( sizeof(unsigned short)==2 && sizeof(unsigned char)==1 );
  173256. if( c<128 ){
  173257. if( c>='A' && c<='Z' ) ret = c + ('a' - 'A');
  173258. }else if( c<65536 ){
  173259. const struct TableEntry *p;
  173260. int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
  173261. int iLo = 0;
  173262. int iRes = -1;
  173263. assert( c>aEntry[0].iCode );
  173264. while( iHi>=iLo ){
  173265. int iTest = (iHi + iLo) / 2;
  173266. int cmp = (c - aEntry[iTest].iCode);
  173267. if( cmp>=0 ){
  173268. iRes = iTest;
  173269. iLo = iTest+1;
  173270. }else{
  173271. iHi = iTest-1;
  173272. }
  173273. }
  173274. assert( iRes>=0 && c>=aEntry[iRes].iCode );
  173275. p = &aEntry[iRes];
  173276. if( c<(p->iCode + p->nRange) && 0==(0x01 & p->flags & (p->iCode ^ c)) ){
  173277. ret = (c + (aiOff[p->flags>>1])) & 0x0000FFFF;
  173278. assert( ret>0 );
  173279. }
  173280. if( eRemoveDiacritic ){
  173281. ret = remove_diacritic(ret, eRemoveDiacritic==2);
  173282. }
  173283. }
  173284. else if( c>=66560 && c<66600 ){
  173285. ret = c + 40;
  173286. }
  173287. return ret;
  173288. }
  173289. #endif /* defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4) */
  173290. #endif /* !defined(SQLITE_DISABLE_FTS3_UNICODE) */
  173291. /************** End of fts3_unicode2.c ***************************************/
  173292. /************** Begin file json1.c *******************************************/
  173293. /*
  173294. ** 2015-08-12
  173295. **
  173296. ** The author disclaims copyright to this source code. In place of
  173297. ** a legal notice, here is a blessing:
  173298. **
  173299. ** May you do good and not evil.
  173300. ** May you find forgiveness for yourself and forgive others.
  173301. ** May you share freely, never taking more than you give.
  173302. **
  173303. ******************************************************************************
  173304. **
  173305. ** This SQLite extension implements JSON functions. The interface is
  173306. ** modeled after MySQL JSON functions:
  173307. **
  173308. ** https://dev.mysql.com/doc/refman/5.7/en/json.html
  173309. **
  173310. ** For the time being, all JSON is stored as pure text. (We might add
  173311. ** a JSONB type in the future which stores a binary encoding of JSON in
  173312. ** a BLOB, but there is no support for JSONB in the current implementation.
  173313. ** This implementation parses JSON text at 250 MB/s, so it is hard to see
  173314. ** how JSONB might improve on that.)
  173315. */
  173316. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_JSON1)
  173317. #if !defined(SQLITEINT_H)
  173318. /* #include "sqlite3ext.h" */
  173319. #endif
  173320. SQLITE_EXTENSION_INIT1
  173321. /* #include <assert.h> */
  173322. /* #include <string.h> */
  173323. /* #include <stdlib.h> */
  173324. /* #include <stdarg.h> */
  173325. /* Mark a function parameter as unused, to suppress nuisance compiler
  173326. ** warnings. */
  173327. #ifndef UNUSED_PARAM
  173328. # define UNUSED_PARAM(X) (void)(X)
  173329. #endif
  173330. #ifndef LARGEST_INT64
  173331. # define LARGEST_INT64 (0xffffffff|(((sqlite3_int64)0x7fffffff)<<32))
  173332. # define SMALLEST_INT64 (((sqlite3_int64)-1) - LARGEST_INT64)
  173333. #endif
  173334. /*
  173335. ** Versions of isspace(), isalnum() and isdigit() to which it is safe
  173336. ** to pass signed char values.
  173337. */
  173338. #ifdef sqlite3Isdigit
  173339. /* Use the SQLite core versions if this routine is part of the
  173340. ** SQLite amalgamation */
  173341. # define safe_isdigit(x) sqlite3Isdigit(x)
  173342. # define safe_isalnum(x) sqlite3Isalnum(x)
  173343. # define safe_isxdigit(x) sqlite3Isxdigit(x)
  173344. #else
  173345. /* Use the standard library for separate compilation */
  173346. #include <ctype.h> /* amalgamator: keep */
  173347. # define safe_isdigit(x) isdigit((unsigned char)(x))
  173348. # define safe_isalnum(x) isalnum((unsigned char)(x))
  173349. # define safe_isxdigit(x) isxdigit((unsigned char)(x))
  173350. #endif
  173351. /*
  173352. ** Growing our own isspace() routine this way is twice as fast as
  173353. ** the library isspace() function, resulting in a 7% overall performance
  173354. ** increase for the parser. (Ubuntu14.10 gcc 4.8.4 x64 with -Os).
  173355. */
  173356. static const char jsonIsSpace[] = {
  173357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0,
  173358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  173359. 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  173360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  173361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  173362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  173363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  173364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  173365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  173366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  173367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  173368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  173369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  173370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  173371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  173372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  173373. };
  173374. #define safe_isspace(x) (jsonIsSpace[(unsigned char)x])
  173375. #ifndef SQLITE_AMALGAMATION
  173376. /* Unsigned integer types. These are already defined in the sqliteInt.h,
  173377. ** but the definitions need to be repeated for separate compilation. */
  173378. typedef sqlite3_uint64 u64;
  173379. typedef unsigned int u32;
  173380. typedef unsigned short int u16;
  173381. typedef unsigned char u8;
  173382. #endif
  173383. /* Objects */
  173384. typedef struct JsonString JsonString;
  173385. typedef struct JsonNode JsonNode;
  173386. typedef struct JsonParse JsonParse;
  173387. /* An instance of this object represents a JSON string
  173388. ** under construction. Really, this is a generic string accumulator
  173389. ** that can be and is used to create strings other than JSON.
  173390. */
  173391. struct JsonString {
  173392. sqlite3_context *pCtx; /* Function context - put error messages here */
  173393. char *zBuf; /* Append JSON content here */
  173394. u64 nAlloc; /* Bytes of storage available in zBuf[] */
  173395. u64 nUsed; /* Bytes of zBuf[] currently used */
  173396. u8 bStatic; /* True if zBuf is static space */
  173397. u8 bErr; /* True if an error has been encountered */
  173398. char zSpace[100]; /* Initial static space */
  173399. };
  173400. /* JSON type values
  173401. */
  173402. #define JSON_NULL 0
  173403. #define JSON_TRUE 1
  173404. #define JSON_FALSE 2
  173405. #define JSON_INT 3
  173406. #define JSON_REAL 4
  173407. #define JSON_STRING 5
  173408. #define JSON_ARRAY 6
  173409. #define JSON_OBJECT 7
  173410. /* The "subtype" set for JSON values */
  173411. #define JSON_SUBTYPE 74 /* Ascii for "J" */
  173412. /*
  173413. ** Names of the various JSON types:
  173414. */
  173415. static const char * const jsonType[] = {
  173416. "null", "true", "false", "integer", "real", "text", "array", "object"
  173417. };
  173418. /* Bit values for the JsonNode.jnFlag field
  173419. */
  173420. #define JNODE_RAW 0x01 /* Content is raw, not JSON encoded */
  173421. #define JNODE_ESCAPE 0x02 /* Content is text with \ escapes */
  173422. #define JNODE_REMOVE 0x04 /* Do not output */
  173423. #define JNODE_REPLACE 0x08 /* Replace with JsonNode.u.iReplace */
  173424. #define JNODE_PATCH 0x10 /* Patch with JsonNode.u.pPatch */
  173425. #define JNODE_APPEND 0x20 /* More ARRAY/OBJECT entries at u.iAppend */
  173426. #define JNODE_LABEL 0x40 /* Is a label of an object */
  173427. /* A single node of parsed JSON
  173428. */
  173429. struct JsonNode {
  173430. u8 eType; /* One of the JSON_ type values */
  173431. u8 jnFlags; /* JNODE flags */
  173432. u32 n; /* Bytes of content, or number of sub-nodes */
  173433. union {
  173434. const char *zJContent; /* Content for INT, REAL, and STRING */
  173435. u32 iAppend; /* More terms for ARRAY and OBJECT */
  173436. u32 iKey; /* Key for ARRAY objects in json_tree() */
  173437. u32 iReplace; /* Replacement content for JNODE_REPLACE */
  173438. JsonNode *pPatch; /* Node chain of patch for JNODE_PATCH */
  173439. } u;
  173440. };
  173441. /* A completely parsed JSON string
  173442. */
  173443. struct JsonParse {
  173444. u32 nNode; /* Number of slots of aNode[] used */
  173445. u32 nAlloc; /* Number of slots of aNode[] allocated */
  173446. JsonNode *aNode; /* Array of nodes containing the parse */
  173447. const char *zJson; /* Original JSON string */
  173448. u32 *aUp; /* Index of parent of each node */
  173449. u8 oom; /* Set to true if out of memory */
  173450. u8 nErr; /* Number of errors seen */
  173451. u16 iDepth; /* Nesting depth */
  173452. int nJson; /* Length of the zJson string in bytes */
  173453. u32 iHold; /* Replace cache line with the lowest iHold value */
  173454. };
  173455. /*
  173456. ** Maximum nesting depth of JSON for this implementation.
  173457. **
  173458. ** This limit is needed to avoid a stack overflow in the recursive
  173459. ** descent parser. A depth of 2000 is far deeper than any sane JSON
  173460. ** should go.
  173461. */
  173462. #define JSON_MAX_DEPTH 2000
  173463. /**************************************************************************
  173464. ** Utility routines for dealing with JsonString objects
  173465. **************************************************************************/
  173466. /* Set the JsonString object to an empty string
  173467. */
  173468. static void jsonZero(JsonString *p){
  173469. p->zBuf = p->zSpace;
  173470. p->nAlloc = sizeof(p->zSpace);
  173471. p->nUsed = 0;
  173472. p->bStatic = 1;
  173473. }
  173474. /* Initialize the JsonString object
  173475. */
  173476. static void jsonInit(JsonString *p, sqlite3_context *pCtx){
  173477. p->pCtx = pCtx;
  173478. p->bErr = 0;
  173479. jsonZero(p);
  173480. }
  173481. /* Free all allocated memory and reset the JsonString object back to its
  173482. ** initial state.
  173483. */
  173484. static void jsonReset(JsonString *p){
  173485. if( !p->bStatic ) sqlite3_free(p->zBuf);
  173486. jsonZero(p);
  173487. }
  173488. /* Report an out-of-memory (OOM) condition
  173489. */
  173490. static void jsonOom(JsonString *p){
  173491. p->bErr = 1;
  173492. sqlite3_result_error_nomem(p->pCtx);
  173493. jsonReset(p);
  173494. }
  173495. /* Enlarge pJson->zBuf so that it can hold at least N more bytes.
  173496. ** Return zero on success. Return non-zero on an OOM error
  173497. */
  173498. static int jsonGrow(JsonString *p, u32 N){
  173499. u64 nTotal = N<p->nAlloc ? p->nAlloc*2 : p->nAlloc+N+10;
  173500. char *zNew;
  173501. if( p->bStatic ){
  173502. if( p->bErr ) return 1;
  173503. zNew = sqlite3_malloc64(nTotal);
  173504. if( zNew==0 ){
  173505. jsonOom(p);
  173506. return SQLITE_NOMEM;
  173507. }
  173508. memcpy(zNew, p->zBuf, (size_t)p->nUsed);
  173509. p->zBuf = zNew;
  173510. p->bStatic = 0;
  173511. }else{
  173512. zNew = sqlite3_realloc64(p->zBuf, nTotal);
  173513. if( zNew==0 ){
  173514. jsonOom(p);
  173515. return SQLITE_NOMEM;
  173516. }
  173517. p->zBuf = zNew;
  173518. }
  173519. p->nAlloc = nTotal;
  173520. return SQLITE_OK;
  173521. }
  173522. /* Append N bytes from zIn onto the end of the JsonString string.
  173523. */
  173524. static void jsonAppendRaw(JsonString *p, const char *zIn, u32 N){
  173525. if( N==0 ) return;
  173526. if( (N+p->nUsed >= p->nAlloc) && jsonGrow(p,N)!=0 ) return;
  173527. memcpy(p->zBuf+p->nUsed, zIn, N);
  173528. p->nUsed += N;
  173529. }
  173530. /* Append formatted text (not to exceed N bytes) to the JsonString.
  173531. */
  173532. static void jsonPrintf(int N, JsonString *p, const char *zFormat, ...){
  173533. va_list ap;
  173534. if( (p->nUsed + N >= p->nAlloc) && jsonGrow(p, N) ) return;
  173535. va_start(ap, zFormat);
  173536. sqlite3_vsnprintf(N, p->zBuf+p->nUsed, zFormat, ap);
  173537. va_end(ap);
  173538. p->nUsed += (int)strlen(p->zBuf+p->nUsed);
  173539. }
  173540. /* Append a single character
  173541. */
  173542. static void jsonAppendChar(JsonString *p, char c){
  173543. if( p->nUsed>=p->nAlloc && jsonGrow(p,1)!=0 ) return;
  173544. p->zBuf[p->nUsed++] = c;
  173545. }
  173546. /* Append a comma separator to the output buffer, if the previous
  173547. ** character is not '[' or '{'.
  173548. */
  173549. static void jsonAppendSeparator(JsonString *p){
  173550. char c;
  173551. if( p->nUsed==0 ) return;
  173552. c = p->zBuf[p->nUsed-1];
  173553. if( c!='[' && c!='{' ) jsonAppendChar(p, ',');
  173554. }
  173555. /* Append the N-byte string in zIn to the end of the JsonString string
  173556. ** under construction. Enclose the string in "..." and escape
  173557. ** any double-quotes or backslash characters contained within the
  173558. ** string.
  173559. */
  173560. static void jsonAppendString(JsonString *p, const char *zIn, u32 N){
  173561. u32 i;
  173562. if( (N+p->nUsed+2 >= p->nAlloc) && jsonGrow(p,N+2)!=0 ) return;
  173563. p->zBuf[p->nUsed++] = '"';
  173564. for(i=0; i<N; i++){
  173565. unsigned char c = ((unsigned const char*)zIn)[i];
  173566. if( c=='"' || c=='\\' ){
  173567. json_simple_escape:
  173568. if( (p->nUsed+N+3-i > p->nAlloc) && jsonGrow(p,N+3-i)!=0 ) return;
  173569. p->zBuf[p->nUsed++] = '\\';
  173570. }else if( c<=0x1f ){
  173571. static const char aSpecial[] = {
  173572. 0, 0, 0, 0, 0, 0, 0, 0, 'b', 't', 'n', 0, 'f', 'r', 0, 0,
  173573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
  173574. };
  173575. assert( sizeof(aSpecial)==32 );
  173576. assert( aSpecial['\b']=='b' );
  173577. assert( aSpecial['\f']=='f' );
  173578. assert( aSpecial['\n']=='n' );
  173579. assert( aSpecial['\r']=='r' );
  173580. assert( aSpecial['\t']=='t' );
  173581. if( aSpecial[c] ){
  173582. c = aSpecial[c];
  173583. goto json_simple_escape;
  173584. }
  173585. if( (p->nUsed+N+7+i > p->nAlloc) && jsonGrow(p,N+7-i)!=0 ) return;
  173586. p->zBuf[p->nUsed++] = '\\';
  173587. p->zBuf[p->nUsed++] = 'u';
  173588. p->zBuf[p->nUsed++] = '0';
  173589. p->zBuf[p->nUsed++] = '0';
  173590. p->zBuf[p->nUsed++] = '0' + (c>>4);
  173591. c = "0123456789abcdef"[c&0xf];
  173592. }
  173593. p->zBuf[p->nUsed++] = c;
  173594. }
  173595. p->zBuf[p->nUsed++] = '"';
  173596. assert( p->nUsed<p->nAlloc );
  173597. }
  173598. /*
  173599. ** Append a function parameter value to the JSON string under
  173600. ** construction.
  173601. */
  173602. static void jsonAppendValue(
  173603. JsonString *p, /* Append to this JSON string */
  173604. sqlite3_value *pValue /* Value to append */
  173605. ){
  173606. switch( sqlite3_value_type(pValue) ){
  173607. case SQLITE_NULL: {
  173608. jsonAppendRaw(p, "null", 4);
  173609. break;
  173610. }
  173611. case SQLITE_INTEGER:
  173612. case SQLITE_FLOAT: {
  173613. const char *z = (const char*)sqlite3_value_text(pValue);
  173614. u32 n = (u32)sqlite3_value_bytes(pValue);
  173615. jsonAppendRaw(p, z, n);
  173616. break;
  173617. }
  173618. case SQLITE_TEXT: {
  173619. const char *z = (const char*)sqlite3_value_text(pValue);
  173620. u32 n = (u32)sqlite3_value_bytes(pValue);
  173621. if( sqlite3_value_subtype(pValue)==JSON_SUBTYPE ){
  173622. jsonAppendRaw(p, z, n);
  173623. }else{
  173624. jsonAppendString(p, z, n);
  173625. }
  173626. break;
  173627. }
  173628. default: {
  173629. if( p->bErr==0 ){
  173630. sqlite3_result_error(p->pCtx, "JSON cannot hold BLOB values", -1);
  173631. p->bErr = 2;
  173632. jsonReset(p);
  173633. }
  173634. break;
  173635. }
  173636. }
  173637. }
  173638. /* Make the JSON in p the result of the SQL function.
  173639. */
  173640. static void jsonResult(JsonString *p){
  173641. if( p->bErr==0 ){
  173642. sqlite3_result_text64(p->pCtx, p->zBuf, p->nUsed,
  173643. p->bStatic ? SQLITE_TRANSIENT : sqlite3_free,
  173644. SQLITE_UTF8);
  173645. jsonZero(p);
  173646. }
  173647. assert( p->bStatic );
  173648. }
  173649. /**************************************************************************
  173650. ** Utility routines for dealing with JsonNode and JsonParse objects
  173651. **************************************************************************/
  173652. /*
  173653. ** Return the number of consecutive JsonNode slots need to represent
  173654. ** the parsed JSON at pNode. The minimum answer is 1. For ARRAY and
  173655. ** OBJECT types, the number might be larger.
  173656. **
  173657. ** Appended elements are not counted. The value returned is the number
  173658. ** by which the JsonNode counter should increment in order to go to the
  173659. ** next peer value.
  173660. */
  173661. static u32 jsonNodeSize(JsonNode *pNode){
  173662. return pNode->eType>=JSON_ARRAY ? pNode->n+1 : 1;
  173663. }
  173664. /*
  173665. ** Reclaim all memory allocated by a JsonParse object. But do not
  173666. ** delete the JsonParse object itself.
  173667. */
  173668. static void jsonParseReset(JsonParse *pParse){
  173669. sqlite3_free(pParse->aNode);
  173670. pParse->aNode = 0;
  173671. pParse->nNode = 0;
  173672. pParse->nAlloc = 0;
  173673. sqlite3_free(pParse->aUp);
  173674. pParse->aUp = 0;
  173675. }
  173676. /*
  173677. ** Free a JsonParse object that was obtained from sqlite3_malloc().
  173678. */
  173679. static void jsonParseFree(JsonParse *pParse){
  173680. jsonParseReset(pParse);
  173681. sqlite3_free(pParse);
  173682. }
  173683. /*
  173684. ** Convert the JsonNode pNode into a pure JSON string and
  173685. ** append to pOut. Subsubstructure is also included. Return
  173686. ** the number of JsonNode objects that are encoded.
  173687. */
  173688. static void jsonRenderNode(
  173689. JsonNode *pNode, /* The node to render */
  173690. JsonString *pOut, /* Write JSON here */
  173691. sqlite3_value **aReplace /* Replacement values */
  173692. ){
  173693. if( pNode->jnFlags & (JNODE_REPLACE|JNODE_PATCH) ){
  173694. if( pNode->jnFlags & JNODE_REPLACE ){
  173695. jsonAppendValue(pOut, aReplace[pNode->u.iReplace]);
  173696. return;
  173697. }
  173698. pNode = pNode->u.pPatch;
  173699. }
  173700. switch( pNode->eType ){
  173701. default: {
  173702. assert( pNode->eType==JSON_NULL );
  173703. jsonAppendRaw(pOut, "null", 4);
  173704. break;
  173705. }
  173706. case JSON_TRUE: {
  173707. jsonAppendRaw(pOut, "true", 4);
  173708. break;
  173709. }
  173710. case JSON_FALSE: {
  173711. jsonAppendRaw(pOut, "false", 5);
  173712. break;
  173713. }
  173714. case JSON_STRING: {
  173715. if( pNode->jnFlags & JNODE_RAW ){
  173716. jsonAppendString(pOut, pNode->u.zJContent, pNode->n);
  173717. break;
  173718. }
  173719. /* Fall through into the next case */
  173720. }
  173721. case JSON_REAL:
  173722. case JSON_INT: {
  173723. jsonAppendRaw(pOut, pNode->u.zJContent, pNode->n);
  173724. break;
  173725. }
  173726. case JSON_ARRAY: {
  173727. u32 j = 1;
  173728. jsonAppendChar(pOut, '[');
  173729. for(;;){
  173730. while( j<=pNode->n ){
  173731. if( (pNode[j].jnFlags & JNODE_REMOVE)==0 ){
  173732. jsonAppendSeparator(pOut);
  173733. jsonRenderNode(&pNode[j], pOut, aReplace);
  173734. }
  173735. j += jsonNodeSize(&pNode[j]);
  173736. }
  173737. if( (pNode->jnFlags & JNODE_APPEND)==0 ) break;
  173738. pNode = &pNode[pNode->u.iAppend];
  173739. j = 1;
  173740. }
  173741. jsonAppendChar(pOut, ']');
  173742. break;
  173743. }
  173744. case JSON_OBJECT: {
  173745. u32 j = 1;
  173746. jsonAppendChar(pOut, '{');
  173747. for(;;){
  173748. while( j<=pNode->n ){
  173749. if( (pNode[j+1].jnFlags & JNODE_REMOVE)==0 ){
  173750. jsonAppendSeparator(pOut);
  173751. jsonRenderNode(&pNode[j], pOut, aReplace);
  173752. jsonAppendChar(pOut, ':');
  173753. jsonRenderNode(&pNode[j+1], pOut, aReplace);
  173754. }
  173755. j += 1 + jsonNodeSize(&pNode[j+1]);
  173756. }
  173757. if( (pNode->jnFlags & JNODE_APPEND)==0 ) break;
  173758. pNode = &pNode[pNode->u.iAppend];
  173759. j = 1;
  173760. }
  173761. jsonAppendChar(pOut, '}');
  173762. break;
  173763. }
  173764. }
  173765. }
  173766. /*
  173767. ** Return a JsonNode and all its descendents as a JSON string.
  173768. */
  173769. static void jsonReturnJson(
  173770. JsonNode *pNode, /* Node to return */
  173771. sqlite3_context *pCtx, /* Return value for this function */
  173772. sqlite3_value **aReplace /* Array of replacement values */
  173773. ){
  173774. JsonString s;
  173775. jsonInit(&s, pCtx);
  173776. jsonRenderNode(pNode, &s, aReplace);
  173777. jsonResult(&s);
  173778. sqlite3_result_subtype(pCtx, JSON_SUBTYPE);
  173779. }
  173780. /*
  173781. ** Translate a single byte of Hex into an integer.
  173782. ** This routine only works if h really is a valid hexadecimal
  173783. ** character: 0..9a..fA..F
  173784. */
  173785. static u8 jsonHexToInt(int h){
  173786. assert( (h>='0' && h<='9') || (h>='a' && h<='f') || (h>='A' && h<='F') );
  173787. #ifdef SQLITE_EBCDIC
  173788. h += 9*(1&~(h>>4));
  173789. #else
  173790. h += 9*(1&(h>>6));
  173791. #endif
  173792. return (u8)(h & 0xf);
  173793. }
  173794. /*
  173795. ** Convert a 4-byte hex string into an integer
  173796. */
  173797. static u32 jsonHexToInt4(const char *z){
  173798. u32 v;
  173799. assert( safe_isxdigit(z[0]) );
  173800. assert( safe_isxdigit(z[1]) );
  173801. assert( safe_isxdigit(z[2]) );
  173802. assert( safe_isxdigit(z[3]) );
  173803. v = (jsonHexToInt(z[0])<<12)
  173804. + (jsonHexToInt(z[1])<<8)
  173805. + (jsonHexToInt(z[2])<<4)
  173806. + jsonHexToInt(z[3]);
  173807. return v;
  173808. }
  173809. /*
  173810. ** Make the JsonNode the return value of the function.
  173811. */
  173812. static void jsonReturn(
  173813. JsonNode *pNode, /* Node to return */
  173814. sqlite3_context *pCtx, /* Return value for this function */
  173815. sqlite3_value **aReplace /* Array of replacement values */
  173816. ){
  173817. switch( pNode->eType ){
  173818. default: {
  173819. assert( pNode->eType==JSON_NULL );
  173820. sqlite3_result_null(pCtx);
  173821. break;
  173822. }
  173823. case JSON_TRUE: {
  173824. sqlite3_result_int(pCtx, 1);
  173825. break;
  173826. }
  173827. case JSON_FALSE: {
  173828. sqlite3_result_int(pCtx, 0);
  173829. break;
  173830. }
  173831. case JSON_INT: {
  173832. sqlite3_int64 i = 0;
  173833. const char *z = pNode->u.zJContent;
  173834. if( z[0]=='-' ){ z++; }
  173835. while( z[0]>='0' && z[0]<='9' ){
  173836. unsigned v = *(z++) - '0';
  173837. if( i>=LARGEST_INT64/10 ){
  173838. if( i>LARGEST_INT64/10 ) goto int_as_real;
  173839. if( z[0]>='0' && z[0]<='9' ) goto int_as_real;
  173840. if( v==9 ) goto int_as_real;
  173841. if( v==8 ){
  173842. if( pNode->u.zJContent[0]=='-' ){
  173843. sqlite3_result_int64(pCtx, SMALLEST_INT64);
  173844. goto int_done;
  173845. }else{
  173846. goto int_as_real;
  173847. }
  173848. }
  173849. }
  173850. i = i*10 + v;
  173851. }
  173852. if( pNode->u.zJContent[0]=='-' ){ i = -i; }
  173853. sqlite3_result_int64(pCtx, i);
  173854. int_done:
  173855. break;
  173856. int_as_real: /* fall through to real */;
  173857. }
  173858. case JSON_REAL: {
  173859. double r;
  173860. #ifdef SQLITE_AMALGAMATION
  173861. const char *z = pNode->u.zJContent;
  173862. sqlite3AtoF(z, &r, sqlite3Strlen30(z), SQLITE_UTF8);
  173863. #else
  173864. r = strtod(pNode->u.zJContent, 0);
  173865. #endif
  173866. sqlite3_result_double(pCtx, r);
  173867. break;
  173868. }
  173869. case JSON_STRING: {
  173870. #if 0 /* Never happens because JNODE_RAW is only set by json_set(),
  173871. ** json_insert() and json_replace() and those routines do not
  173872. ** call jsonReturn() */
  173873. if( pNode->jnFlags & JNODE_RAW ){
  173874. sqlite3_result_text(pCtx, pNode->u.zJContent, pNode->n,
  173875. SQLITE_TRANSIENT);
  173876. }else
  173877. #endif
  173878. assert( (pNode->jnFlags & JNODE_RAW)==0 );
  173879. if( (pNode->jnFlags & JNODE_ESCAPE)==0 ){
  173880. /* JSON formatted without any backslash-escapes */
  173881. sqlite3_result_text(pCtx, pNode->u.zJContent+1, pNode->n-2,
  173882. SQLITE_TRANSIENT);
  173883. }else{
  173884. /* Translate JSON formatted string into raw text */
  173885. u32 i;
  173886. u32 n = pNode->n;
  173887. const char *z = pNode->u.zJContent;
  173888. char *zOut;
  173889. u32 j;
  173890. zOut = sqlite3_malloc( n+1 );
  173891. if( zOut==0 ){
  173892. sqlite3_result_error_nomem(pCtx);
  173893. break;
  173894. }
  173895. for(i=1, j=0; i<n-1; i++){
  173896. char c = z[i];
  173897. if( c!='\\' ){
  173898. zOut[j++] = c;
  173899. }else{
  173900. c = z[++i];
  173901. if( c=='u' ){
  173902. u32 v = jsonHexToInt4(z+i+1);
  173903. i += 4;
  173904. if( v==0 ) break;
  173905. if( v<=0x7f ){
  173906. zOut[j++] = (char)v;
  173907. }else if( v<=0x7ff ){
  173908. zOut[j++] = (char)(0xc0 | (v>>6));
  173909. zOut[j++] = 0x80 | (v&0x3f);
  173910. }else{
  173911. u32 vlo;
  173912. if( (v&0xfc00)==0xd800
  173913. && i<n-6
  173914. && z[i+1]=='\\'
  173915. && z[i+2]=='u'
  173916. && ((vlo = jsonHexToInt4(z+i+3))&0xfc00)==0xdc00
  173917. ){
  173918. /* We have a surrogate pair */
  173919. v = ((v&0x3ff)<<10) + (vlo&0x3ff) + 0x10000;
  173920. i += 6;
  173921. zOut[j++] = 0xf0 | (v>>18);
  173922. zOut[j++] = 0x80 | ((v>>12)&0x3f);
  173923. zOut[j++] = 0x80 | ((v>>6)&0x3f);
  173924. zOut[j++] = 0x80 | (v&0x3f);
  173925. }else{
  173926. zOut[j++] = 0xe0 | (v>>12);
  173927. zOut[j++] = 0x80 | ((v>>6)&0x3f);
  173928. zOut[j++] = 0x80 | (v&0x3f);
  173929. }
  173930. }
  173931. }else{
  173932. if( c=='b' ){
  173933. c = '\b';
  173934. }else if( c=='f' ){
  173935. c = '\f';
  173936. }else if( c=='n' ){
  173937. c = '\n';
  173938. }else if( c=='r' ){
  173939. c = '\r';
  173940. }else if( c=='t' ){
  173941. c = '\t';
  173942. }
  173943. zOut[j++] = c;
  173944. }
  173945. }
  173946. }
  173947. zOut[j] = 0;
  173948. sqlite3_result_text(pCtx, zOut, j, sqlite3_free);
  173949. }
  173950. break;
  173951. }
  173952. case JSON_ARRAY:
  173953. case JSON_OBJECT: {
  173954. jsonReturnJson(pNode, pCtx, aReplace);
  173955. break;
  173956. }
  173957. }
  173958. }
  173959. /* Forward reference */
  173960. static int jsonParseAddNode(JsonParse*,u32,u32,const char*);
  173961. /*
  173962. ** A macro to hint to the compiler that a function should not be
  173963. ** inlined.
  173964. */
  173965. #if defined(__GNUC__)
  173966. # define JSON_NOINLINE __attribute__((noinline))
  173967. #elif defined(_MSC_VER) && _MSC_VER>=1310
  173968. # define JSON_NOINLINE __declspec(noinline)
  173969. #else
  173970. # define JSON_NOINLINE
  173971. #endif
  173972. static JSON_NOINLINE int jsonParseAddNodeExpand(
  173973. JsonParse *pParse, /* Append the node to this object */
  173974. u32 eType, /* Node type */
  173975. u32 n, /* Content size or sub-node count */
  173976. const char *zContent /* Content */
  173977. ){
  173978. u32 nNew;
  173979. JsonNode *pNew;
  173980. assert( pParse->nNode>=pParse->nAlloc );
  173981. if( pParse->oom ) return -1;
  173982. nNew = pParse->nAlloc*2 + 10;
  173983. pNew = sqlite3_realloc64(pParse->aNode, sizeof(JsonNode)*nNew);
  173984. if( pNew==0 ){
  173985. pParse->oom = 1;
  173986. return -1;
  173987. }
  173988. pParse->nAlloc = nNew;
  173989. pParse->aNode = pNew;
  173990. assert( pParse->nNode<pParse->nAlloc );
  173991. return jsonParseAddNode(pParse, eType, n, zContent);
  173992. }
  173993. /*
  173994. ** Create a new JsonNode instance based on the arguments and append that
  173995. ** instance to the JsonParse. Return the index in pParse->aNode[] of the
  173996. ** new node, or -1 if a memory allocation fails.
  173997. */
  173998. static int jsonParseAddNode(
  173999. JsonParse *pParse, /* Append the node to this object */
  174000. u32 eType, /* Node type */
  174001. u32 n, /* Content size or sub-node count */
  174002. const char *zContent /* Content */
  174003. ){
  174004. JsonNode *p;
  174005. if( pParse->nNode>=pParse->nAlloc ){
  174006. return jsonParseAddNodeExpand(pParse, eType, n, zContent);
  174007. }
  174008. p = &pParse->aNode[pParse->nNode];
  174009. p->eType = (u8)eType;
  174010. p->jnFlags = 0;
  174011. p->n = n;
  174012. p->u.zJContent = zContent;
  174013. return pParse->nNode++;
  174014. }
  174015. /*
  174016. ** Return true if z[] begins with 4 (or more) hexadecimal digits
  174017. */
  174018. static int jsonIs4Hex(const char *z){
  174019. int i;
  174020. for(i=0; i<4; i++) if( !safe_isxdigit(z[i]) ) return 0;
  174021. return 1;
  174022. }
  174023. /*
  174024. ** Parse a single JSON value which begins at pParse->zJson[i]. Return the
  174025. ** index of the first character past the end of the value parsed.
  174026. **
  174027. ** Return negative for a syntax error. Special cases: return -2 if the
  174028. ** first non-whitespace character is '}' and return -3 if the first
  174029. ** non-whitespace character is ']'.
  174030. */
  174031. static int jsonParseValue(JsonParse *pParse, u32 i){
  174032. char c;
  174033. u32 j;
  174034. int iThis;
  174035. int x;
  174036. JsonNode *pNode;
  174037. const char *z = pParse->zJson;
  174038. while( safe_isspace(z[i]) ){ i++; }
  174039. if( (c = z[i])=='{' ){
  174040. /* Parse object */
  174041. iThis = jsonParseAddNode(pParse, JSON_OBJECT, 0, 0);
  174042. if( iThis<0 ) return -1;
  174043. for(j=i+1;;j++){
  174044. while( safe_isspace(z[j]) ){ j++; }
  174045. if( ++pParse->iDepth > JSON_MAX_DEPTH ) return -1;
  174046. x = jsonParseValue(pParse, j);
  174047. if( x<0 ){
  174048. pParse->iDepth--;
  174049. if( x==(-2) && pParse->nNode==(u32)iThis+1 ) return j+1;
  174050. return -1;
  174051. }
  174052. if( pParse->oom ) return -1;
  174053. pNode = &pParse->aNode[pParse->nNode-1];
  174054. if( pNode->eType!=JSON_STRING ) return -1;
  174055. pNode->jnFlags |= JNODE_LABEL;
  174056. j = x;
  174057. while( safe_isspace(z[j]) ){ j++; }
  174058. if( z[j]!=':' ) return -1;
  174059. j++;
  174060. x = jsonParseValue(pParse, j);
  174061. pParse->iDepth--;
  174062. if( x<0 ) return -1;
  174063. j = x;
  174064. while( safe_isspace(z[j]) ){ j++; }
  174065. c = z[j];
  174066. if( c==',' ) continue;
  174067. if( c!='}' ) return -1;
  174068. break;
  174069. }
  174070. pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1;
  174071. return j+1;
  174072. }else if( c=='[' ){
  174073. /* Parse array */
  174074. iThis = jsonParseAddNode(pParse, JSON_ARRAY, 0, 0);
  174075. if( iThis<0 ) return -1;
  174076. for(j=i+1;;j++){
  174077. while( safe_isspace(z[j]) ){ j++; }
  174078. if( ++pParse->iDepth > JSON_MAX_DEPTH ) return -1;
  174079. x = jsonParseValue(pParse, j);
  174080. pParse->iDepth--;
  174081. if( x<0 ){
  174082. if( x==(-3) && pParse->nNode==(u32)iThis+1 ) return j+1;
  174083. return -1;
  174084. }
  174085. j = x;
  174086. while( safe_isspace(z[j]) ){ j++; }
  174087. c = z[j];
  174088. if( c==',' ) continue;
  174089. if( c!=']' ) return -1;
  174090. break;
  174091. }
  174092. pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1;
  174093. return j+1;
  174094. }else if( c=='"' ){
  174095. /* Parse string */
  174096. u8 jnFlags = 0;
  174097. j = i+1;
  174098. for(;;){
  174099. c = z[j];
  174100. if( (c & ~0x1f)==0 ){
  174101. /* Control characters are not allowed in strings */
  174102. return -1;
  174103. }
  174104. if( c=='\\' ){
  174105. c = z[++j];
  174106. if( c=='"' || c=='\\' || c=='/' || c=='b' || c=='f'
  174107. || c=='n' || c=='r' || c=='t'
  174108. || (c=='u' && jsonIs4Hex(z+j+1)) ){
  174109. jnFlags = JNODE_ESCAPE;
  174110. }else{
  174111. return -1;
  174112. }
  174113. }else if( c=='"' ){
  174114. break;
  174115. }
  174116. j++;
  174117. }
  174118. jsonParseAddNode(pParse, JSON_STRING, j+1-i, &z[i]);
  174119. if( !pParse->oom ) pParse->aNode[pParse->nNode-1].jnFlags = jnFlags;
  174120. return j+1;
  174121. }else if( c=='n'
  174122. && strncmp(z+i,"null",4)==0
  174123. && !safe_isalnum(z[i+4]) ){
  174124. jsonParseAddNode(pParse, JSON_NULL, 0, 0);
  174125. return i+4;
  174126. }else if( c=='t'
  174127. && strncmp(z+i,"true",4)==0
  174128. && !safe_isalnum(z[i+4]) ){
  174129. jsonParseAddNode(pParse, JSON_TRUE, 0, 0);
  174130. return i+4;
  174131. }else if( c=='f'
  174132. && strncmp(z+i,"false",5)==0
  174133. && !safe_isalnum(z[i+5]) ){
  174134. jsonParseAddNode(pParse, JSON_FALSE, 0, 0);
  174135. return i+5;
  174136. }else if( c=='-' || (c>='0' && c<='9') ){
  174137. /* Parse number */
  174138. u8 seenDP = 0;
  174139. u8 seenE = 0;
  174140. assert( '-' < '0' );
  174141. if( c<='0' ){
  174142. j = c=='-' ? i+1 : i;
  174143. if( z[j]=='0' && z[j+1]>='0' && z[j+1]<='9' ) return -1;
  174144. }
  174145. j = i+1;
  174146. for(;; j++){
  174147. c = z[j];
  174148. if( c>='0' && c<='9' ) continue;
  174149. if( c=='.' ){
  174150. if( z[j-1]=='-' ) return -1;
  174151. if( seenDP ) return -1;
  174152. seenDP = 1;
  174153. continue;
  174154. }
  174155. if( c=='e' || c=='E' ){
  174156. if( z[j-1]<'0' ) return -1;
  174157. if( seenE ) return -1;
  174158. seenDP = seenE = 1;
  174159. c = z[j+1];
  174160. if( c=='+' || c=='-' ){
  174161. j++;
  174162. c = z[j+1];
  174163. }
  174164. if( c<'0' || c>'9' ) return -1;
  174165. continue;
  174166. }
  174167. break;
  174168. }
  174169. if( z[j-1]<'0' ) return -1;
  174170. jsonParseAddNode(pParse, seenDP ? JSON_REAL : JSON_INT,
  174171. j - i, &z[i]);
  174172. return j;
  174173. }else if( c=='}' ){
  174174. return -2; /* End of {...} */
  174175. }else if( c==']' ){
  174176. return -3; /* End of [...] */
  174177. }else if( c==0 ){
  174178. return 0; /* End of file */
  174179. }else{
  174180. return -1; /* Syntax error */
  174181. }
  174182. }
  174183. /*
  174184. ** Parse a complete JSON string. Return 0 on success or non-zero if there
  174185. ** are any errors. If an error occurs, free all memory associated with
  174186. ** pParse.
  174187. **
  174188. ** pParse is uninitialized when this routine is called.
  174189. */
  174190. static int jsonParse(
  174191. JsonParse *pParse, /* Initialize and fill this JsonParse object */
  174192. sqlite3_context *pCtx, /* Report errors here */
  174193. const char *zJson /* Input JSON text to be parsed */
  174194. ){
  174195. int i;
  174196. memset(pParse, 0, sizeof(*pParse));
  174197. if( zJson==0 ) return 1;
  174198. pParse->zJson = zJson;
  174199. i = jsonParseValue(pParse, 0);
  174200. if( pParse->oom ) i = -1;
  174201. if( i>0 ){
  174202. assert( pParse->iDepth==0 );
  174203. while( safe_isspace(zJson[i]) ) i++;
  174204. if( zJson[i] ) i = -1;
  174205. }
  174206. if( i<=0 ){
  174207. if( pCtx!=0 ){
  174208. if( pParse->oom ){
  174209. sqlite3_result_error_nomem(pCtx);
  174210. }else{
  174211. sqlite3_result_error(pCtx, "malformed JSON", -1);
  174212. }
  174213. }
  174214. jsonParseReset(pParse);
  174215. return 1;
  174216. }
  174217. return 0;
  174218. }
  174219. /* Mark node i of pParse as being a child of iParent. Call recursively
  174220. ** to fill in all the descendants of node i.
  174221. */
  174222. static void jsonParseFillInParentage(JsonParse *pParse, u32 i, u32 iParent){
  174223. JsonNode *pNode = &pParse->aNode[i];
  174224. u32 j;
  174225. pParse->aUp[i] = iParent;
  174226. switch( pNode->eType ){
  174227. case JSON_ARRAY: {
  174228. for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j)){
  174229. jsonParseFillInParentage(pParse, i+j, i);
  174230. }
  174231. break;
  174232. }
  174233. case JSON_OBJECT: {
  174234. for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j+1)+1){
  174235. pParse->aUp[i+j] = i;
  174236. jsonParseFillInParentage(pParse, i+j+1, i);
  174237. }
  174238. break;
  174239. }
  174240. default: {
  174241. break;
  174242. }
  174243. }
  174244. }
  174245. /*
  174246. ** Compute the parentage of all nodes in a completed parse.
  174247. */
  174248. static int jsonParseFindParents(JsonParse *pParse){
  174249. u32 *aUp;
  174250. assert( pParse->aUp==0 );
  174251. aUp = pParse->aUp = sqlite3_malloc64( sizeof(u32)*pParse->nNode );
  174252. if( aUp==0 ){
  174253. pParse->oom = 1;
  174254. return SQLITE_NOMEM;
  174255. }
  174256. jsonParseFillInParentage(pParse, 0, 0);
  174257. return SQLITE_OK;
  174258. }
  174259. /*
  174260. ** Magic number used for the JSON parse cache in sqlite3_get_auxdata()
  174261. */
  174262. #define JSON_CACHE_ID (-429938) /* First cache entry */
  174263. #define JSON_CACHE_SZ 4 /* Max number of cache entries */
  174264. /*
  174265. ** Obtain a complete parse of the JSON found in the first argument
  174266. ** of the argv array. Use the sqlite3_get_auxdata() cache for this
  174267. ** parse if it is available. If the cache is not available or if it
  174268. ** is no longer valid, parse the JSON again and return the new parse,
  174269. ** and also register the new parse so that it will be available for
  174270. ** future sqlite3_get_auxdata() calls.
  174271. */
  174272. static JsonParse *jsonParseCached(
  174273. sqlite3_context *pCtx,
  174274. sqlite3_value **argv,
  174275. sqlite3_context *pErrCtx
  174276. ){
  174277. const char *zJson = (const char*)sqlite3_value_text(argv[0]);
  174278. int nJson = sqlite3_value_bytes(argv[0]);
  174279. JsonParse *p;
  174280. JsonParse *pMatch = 0;
  174281. int iKey;
  174282. int iMinKey = 0;
  174283. u32 iMinHold = 0xffffffff;
  174284. u32 iMaxHold = 0;
  174285. if( zJson==0 ) return 0;
  174286. for(iKey=0; iKey<JSON_CACHE_SZ; iKey++){
  174287. p = (JsonParse*)sqlite3_get_auxdata(pCtx, JSON_CACHE_ID+iKey);
  174288. if( p==0 ){
  174289. iMinKey = iKey;
  174290. break;
  174291. }
  174292. if( pMatch==0
  174293. && p->nJson==nJson
  174294. && memcmp(p->zJson,zJson,nJson)==0
  174295. ){
  174296. p->nErr = 0;
  174297. pMatch = p;
  174298. }else if( p->iHold<iMinHold ){
  174299. iMinHold = p->iHold;
  174300. iMinKey = iKey;
  174301. }
  174302. if( p->iHold>iMaxHold ){
  174303. iMaxHold = p->iHold;
  174304. }
  174305. }
  174306. if( pMatch ){
  174307. pMatch->nErr = 0;
  174308. pMatch->iHold = iMaxHold+1;
  174309. return pMatch;
  174310. }
  174311. p = sqlite3_malloc64( sizeof(*p) + nJson + 1 );
  174312. if( p==0 ){
  174313. sqlite3_result_error_nomem(pCtx);
  174314. return 0;
  174315. }
  174316. memset(p, 0, sizeof(*p));
  174317. p->zJson = (char*)&p[1];
  174318. memcpy((char*)p->zJson, zJson, nJson+1);
  174319. if( jsonParse(p, pErrCtx, p->zJson) ){
  174320. sqlite3_free(p);
  174321. return 0;
  174322. }
  174323. p->nJson = nJson;
  174324. p->iHold = iMaxHold+1;
  174325. sqlite3_set_auxdata(pCtx, JSON_CACHE_ID+iMinKey, p,
  174326. (void(*)(void*))jsonParseFree);
  174327. return (JsonParse*)sqlite3_get_auxdata(pCtx, JSON_CACHE_ID+iMinKey);
  174328. }
  174329. /*
  174330. ** Compare the OBJECT label at pNode against zKey,nKey. Return true on
  174331. ** a match.
  174332. */
  174333. static int jsonLabelCompare(JsonNode *pNode, const char *zKey, u32 nKey){
  174334. if( pNode->jnFlags & JNODE_RAW ){
  174335. if( pNode->n!=nKey ) return 0;
  174336. return strncmp(pNode->u.zJContent, zKey, nKey)==0;
  174337. }else{
  174338. if( pNode->n!=nKey+2 ) return 0;
  174339. return strncmp(pNode->u.zJContent+1, zKey, nKey)==0;
  174340. }
  174341. }
  174342. /* forward declaration */
  174343. static JsonNode *jsonLookupAppend(JsonParse*,const char*,int*,const char**);
  174344. /*
  174345. ** Search along zPath to find the node specified. Return a pointer
  174346. ** to that node, or NULL if zPath is malformed or if there is no such
  174347. ** node.
  174348. **
  174349. ** If pApnd!=0, then try to append new nodes to complete zPath if it is
  174350. ** possible to do so and if no existing node corresponds to zPath. If
  174351. ** new nodes are appended *pApnd is set to 1.
  174352. */
  174353. static JsonNode *jsonLookupStep(
  174354. JsonParse *pParse, /* The JSON to search */
  174355. u32 iRoot, /* Begin the search at this node */
  174356. const char *zPath, /* The path to search */
  174357. int *pApnd, /* Append nodes to complete path if not NULL */
  174358. const char **pzErr /* Make *pzErr point to any syntax error in zPath */
  174359. ){
  174360. u32 i, j, nKey;
  174361. const char *zKey;
  174362. JsonNode *pRoot = &pParse->aNode[iRoot];
  174363. if( zPath[0]==0 ) return pRoot;
  174364. if( pRoot->jnFlags & JNODE_REPLACE ) return 0;
  174365. if( zPath[0]=='.' ){
  174366. if( pRoot->eType!=JSON_OBJECT ) return 0;
  174367. zPath++;
  174368. if( zPath[0]=='"' ){
  174369. zKey = zPath + 1;
  174370. for(i=1; zPath[i] && zPath[i]!='"'; i++){}
  174371. nKey = i-1;
  174372. if( zPath[i] ){
  174373. i++;
  174374. }else{
  174375. *pzErr = zPath;
  174376. return 0;
  174377. }
  174378. }else{
  174379. zKey = zPath;
  174380. for(i=0; zPath[i] && zPath[i]!='.' && zPath[i]!='['; i++){}
  174381. nKey = i;
  174382. }
  174383. if( nKey==0 ){
  174384. *pzErr = zPath;
  174385. return 0;
  174386. }
  174387. j = 1;
  174388. for(;;){
  174389. while( j<=pRoot->n ){
  174390. if( jsonLabelCompare(pRoot+j, zKey, nKey) ){
  174391. return jsonLookupStep(pParse, iRoot+j+1, &zPath[i], pApnd, pzErr);
  174392. }
  174393. j++;
  174394. j += jsonNodeSize(&pRoot[j]);
  174395. }
  174396. if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break;
  174397. iRoot += pRoot->u.iAppend;
  174398. pRoot = &pParse->aNode[iRoot];
  174399. j = 1;
  174400. }
  174401. if( pApnd ){
  174402. u32 iStart, iLabel;
  174403. JsonNode *pNode;
  174404. iStart = jsonParseAddNode(pParse, JSON_OBJECT, 2, 0);
  174405. iLabel = jsonParseAddNode(pParse, JSON_STRING, nKey, zKey);
  174406. zPath += i;
  174407. pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr);
  174408. if( pParse->oom ) return 0;
  174409. if( pNode ){
  174410. pRoot = &pParse->aNode[iRoot];
  174411. pRoot->u.iAppend = iStart - iRoot;
  174412. pRoot->jnFlags |= JNODE_APPEND;
  174413. pParse->aNode[iLabel].jnFlags |= JNODE_RAW;
  174414. }
  174415. return pNode;
  174416. }
  174417. }else if( zPath[0]=='[' ){
  174418. i = 0;
  174419. j = 1;
  174420. while( safe_isdigit(zPath[j]) ){
  174421. i = i*10 + zPath[j] - '0';
  174422. j++;
  174423. }
  174424. if( j<2 || zPath[j]!=']' ){
  174425. if( zPath[1]=='#' ){
  174426. JsonNode *pBase = pRoot;
  174427. int iBase = iRoot;
  174428. if( pRoot->eType!=JSON_ARRAY ) return 0;
  174429. for(;;){
  174430. while( j<=pBase->n ){
  174431. if( (pBase[j].jnFlags & JNODE_REMOVE)==0 ) i++;
  174432. j += jsonNodeSize(&pBase[j]);
  174433. }
  174434. if( (pBase->jnFlags & JNODE_APPEND)==0 ) break;
  174435. iBase += pBase->u.iAppend;
  174436. pBase = &pParse->aNode[iBase];
  174437. j = 1;
  174438. }
  174439. j = 2;
  174440. if( zPath[2]=='-' && safe_isdigit(zPath[3]) ){
  174441. unsigned int x = 0;
  174442. j = 3;
  174443. do{
  174444. x = x*10 + zPath[j] - '0';
  174445. j++;
  174446. }while( safe_isdigit(zPath[j]) );
  174447. if( x>i ) return 0;
  174448. i -= x;
  174449. }
  174450. if( zPath[j]!=']' ){
  174451. *pzErr = zPath;
  174452. return 0;
  174453. }
  174454. }else{
  174455. *pzErr = zPath;
  174456. return 0;
  174457. }
  174458. }
  174459. if( pRoot->eType!=JSON_ARRAY ) return 0;
  174460. zPath += j + 1;
  174461. j = 1;
  174462. for(;;){
  174463. while( j<=pRoot->n && (i>0 || (pRoot[j].jnFlags & JNODE_REMOVE)!=0) ){
  174464. if( (pRoot[j].jnFlags & JNODE_REMOVE)==0 ) i--;
  174465. j += jsonNodeSize(&pRoot[j]);
  174466. }
  174467. if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break;
  174468. iRoot += pRoot->u.iAppend;
  174469. pRoot = &pParse->aNode[iRoot];
  174470. j = 1;
  174471. }
  174472. if( j<=pRoot->n ){
  174473. return jsonLookupStep(pParse, iRoot+j, zPath, pApnd, pzErr);
  174474. }
  174475. if( i==0 && pApnd ){
  174476. u32 iStart;
  174477. JsonNode *pNode;
  174478. iStart = jsonParseAddNode(pParse, JSON_ARRAY, 1, 0);
  174479. pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr);
  174480. if( pParse->oom ) return 0;
  174481. if( pNode ){
  174482. pRoot = &pParse->aNode[iRoot];
  174483. pRoot->u.iAppend = iStart - iRoot;
  174484. pRoot->jnFlags |= JNODE_APPEND;
  174485. }
  174486. return pNode;
  174487. }
  174488. }else{
  174489. *pzErr = zPath;
  174490. }
  174491. return 0;
  174492. }
  174493. /*
  174494. ** Append content to pParse that will complete zPath. Return a pointer
  174495. ** to the inserted node, or return NULL if the append fails.
  174496. */
  174497. static JsonNode *jsonLookupAppend(
  174498. JsonParse *pParse, /* Append content to the JSON parse */
  174499. const char *zPath, /* Description of content to append */
  174500. int *pApnd, /* Set this flag to 1 */
  174501. const char **pzErr /* Make this point to any syntax error */
  174502. ){
  174503. *pApnd = 1;
  174504. if( zPath[0]==0 ){
  174505. jsonParseAddNode(pParse, JSON_NULL, 0, 0);
  174506. return pParse->oom ? 0 : &pParse->aNode[pParse->nNode-1];
  174507. }
  174508. if( zPath[0]=='.' ){
  174509. jsonParseAddNode(pParse, JSON_OBJECT, 0, 0);
  174510. }else if( strncmp(zPath,"[0]",3)==0 ){
  174511. jsonParseAddNode(pParse, JSON_ARRAY, 0, 0);
  174512. }else{
  174513. return 0;
  174514. }
  174515. if( pParse->oom ) return 0;
  174516. return jsonLookupStep(pParse, pParse->nNode-1, zPath, pApnd, pzErr);
  174517. }
  174518. /*
  174519. ** Return the text of a syntax error message on a JSON path. Space is
  174520. ** obtained from sqlite3_malloc().
  174521. */
  174522. static char *jsonPathSyntaxError(const char *zErr){
  174523. return sqlite3_mprintf("JSON path error near '%q'", zErr);
  174524. }
  174525. /*
  174526. ** Do a node lookup using zPath. Return a pointer to the node on success.
  174527. ** Return NULL if not found or if there is an error.
  174528. **
  174529. ** On an error, write an error message into pCtx and increment the
  174530. ** pParse->nErr counter.
  174531. **
  174532. ** If pApnd!=NULL then try to append missing nodes and set *pApnd = 1 if
  174533. ** nodes are appended.
  174534. */
  174535. static JsonNode *jsonLookup(
  174536. JsonParse *pParse, /* The JSON to search */
  174537. const char *zPath, /* The path to search */
  174538. int *pApnd, /* Append nodes to complete path if not NULL */
  174539. sqlite3_context *pCtx /* Report errors here, if not NULL */
  174540. ){
  174541. const char *zErr = 0;
  174542. JsonNode *pNode = 0;
  174543. char *zMsg;
  174544. if( zPath==0 ) return 0;
  174545. if( zPath[0]!='$' ){
  174546. zErr = zPath;
  174547. goto lookup_err;
  174548. }
  174549. zPath++;
  174550. pNode = jsonLookupStep(pParse, 0, zPath, pApnd, &zErr);
  174551. if( zErr==0 ) return pNode;
  174552. lookup_err:
  174553. pParse->nErr++;
  174554. assert( zErr!=0 && pCtx!=0 );
  174555. zMsg = jsonPathSyntaxError(zErr);
  174556. if( zMsg ){
  174557. sqlite3_result_error(pCtx, zMsg, -1);
  174558. sqlite3_free(zMsg);
  174559. }else{
  174560. sqlite3_result_error_nomem(pCtx);
  174561. }
  174562. return 0;
  174563. }
  174564. /*
  174565. ** Report the wrong number of arguments for json_insert(), json_replace()
  174566. ** or json_set().
  174567. */
  174568. static void jsonWrongNumArgs(
  174569. sqlite3_context *pCtx,
  174570. const char *zFuncName
  174571. ){
  174572. char *zMsg = sqlite3_mprintf("json_%s() needs an odd number of arguments",
  174573. zFuncName);
  174574. sqlite3_result_error(pCtx, zMsg, -1);
  174575. sqlite3_free(zMsg);
  174576. }
  174577. /*
  174578. ** Mark all NULL entries in the Object passed in as JNODE_REMOVE.
  174579. */
  174580. static void jsonRemoveAllNulls(JsonNode *pNode){
  174581. int i, n;
  174582. assert( pNode->eType==JSON_OBJECT );
  174583. n = pNode->n;
  174584. for(i=2; i<=n; i += jsonNodeSize(&pNode[i])+1){
  174585. switch( pNode[i].eType ){
  174586. case JSON_NULL:
  174587. pNode[i].jnFlags |= JNODE_REMOVE;
  174588. break;
  174589. case JSON_OBJECT:
  174590. jsonRemoveAllNulls(&pNode[i]);
  174591. break;
  174592. }
  174593. }
  174594. }
  174595. /****************************************************************************
  174596. ** SQL functions used for testing and debugging
  174597. ****************************************************************************/
  174598. #ifdef SQLITE_DEBUG
  174599. /*
  174600. ** The json_parse(JSON) function returns a string which describes
  174601. ** a parse of the JSON provided. Or it returns NULL if JSON is not
  174602. ** well-formed.
  174603. */
  174604. static void jsonParseFunc(
  174605. sqlite3_context *ctx,
  174606. int argc,
  174607. sqlite3_value **argv
  174608. ){
  174609. JsonString s; /* Output string - not real JSON */
  174610. JsonParse x; /* The parse */
  174611. u32 i;
  174612. assert( argc==1 );
  174613. if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
  174614. jsonParseFindParents(&x);
  174615. jsonInit(&s, ctx);
  174616. for(i=0; i<x.nNode; i++){
  174617. const char *zType;
  174618. if( x.aNode[i].jnFlags & JNODE_LABEL ){
  174619. assert( x.aNode[i].eType==JSON_STRING );
  174620. zType = "label";
  174621. }else{
  174622. zType = jsonType[x.aNode[i].eType];
  174623. }
  174624. jsonPrintf(100, &s,"node %3u: %7s n=%-4d up=%-4d",
  174625. i, zType, x.aNode[i].n, x.aUp[i]);
  174626. if( x.aNode[i].u.zJContent!=0 ){
  174627. jsonAppendRaw(&s, " ", 1);
  174628. jsonAppendRaw(&s, x.aNode[i].u.zJContent, x.aNode[i].n);
  174629. }
  174630. jsonAppendRaw(&s, "\n", 1);
  174631. }
  174632. jsonParseReset(&x);
  174633. jsonResult(&s);
  174634. }
  174635. /*
  174636. ** The json_test1(JSON) function return true (1) if the input is JSON
  174637. ** text generated by another json function. It returns (0) if the input
  174638. ** is not known to be JSON.
  174639. */
  174640. static void jsonTest1Func(
  174641. sqlite3_context *ctx,
  174642. int argc,
  174643. sqlite3_value **argv
  174644. ){
  174645. UNUSED_PARAM(argc);
  174646. sqlite3_result_int(ctx, sqlite3_value_subtype(argv[0])==JSON_SUBTYPE);
  174647. }
  174648. #endif /* SQLITE_DEBUG */
  174649. /****************************************************************************
  174650. ** Scalar SQL function implementations
  174651. ****************************************************************************/
  174652. /*
  174653. ** Implementation of the json_QUOTE(VALUE) function. Return a JSON value
  174654. ** corresponding to the SQL value input. Mostly this means putting
  174655. ** double-quotes around strings and returning the unquoted string "null"
  174656. ** when given a NULL input.
  174657. */
  174658. static void jsonQuoteFunc(
  174659. sqlite3_context *ctx,
  174660. int argc,
  174661. sqlite3_value **argv
  174662. ){
  174663. JsonString jx;
  174664. UNUSED_PARAM(argc);
  174665. jsonInit(&jx, ctx);
  174666. jsonAppendValue(&jx, argv[0]);
  174667. jsonResult(&jx);
  174668. sqlite3_result_subtype(ctx, JSON_SUBTYPE);
  174669. }
  174670. /*
  174671. ** Implementation of the json_array(VALUE,...) function. Return a JSON
  174672. ** array that contains all values given in arguments. Or if any argument
  174673. ** is a BLOB, throw an error.
  174674. */
  174675. static void jsonArrayFunc(
  174676. sqlite3_context *ctx,
  174677. int argc,
  174678. sqlite3_value **argv
  174679. ){
  174680. int i;
  174681. JsonString jx;
  174682. jsonInit(&jx, ctx);
  174683. jsonAppendChar(&jx, '[');
  174684. for(i=0; i<argc; i++){
  174685. jsonAppendSeparator(&jx);
  174686. jsonAppendValue(&jx, argv[i]);
  174687. }
  174688. jsonAppendChar(&jx, ']');
  174689. jsonResult(&jx);
  174690. sqlite3_result_subtype(ctx, JSON_SUBTYPE);
  174691. }
  174692. /*
  174693. ** json_array_length(JSON)
  174694. ** json_array_length(JSON, PATH)
  174695. **
  174696. ** Return the number of elements in the top-level JSON array.
  174697. ** Return 0 if the input is not a well-formed JSON array.
  174698. */
  174699. static void jsonArrayLengthFunc(
  174700. sqlite3_context *ctx,
  174701. int argc,
  174702. sqlite3_value **argv
  174703. ){
  174704. JsonParse *p; /* The parse */
  174705. sqlite3_int64 n = 0;
  174706. u32 i;
  174707. JsonNode *pNode;
  174708. p = jsonParseCached(ctx, argv, ctx);
  174709. if( p==0 ) return;
  174710. assert( p->nNode );
  174711. if( argc==2 ){
  174712. const char *zPath = (const char*)sqlite3_value_text(argv[1]);
  174713. pNode = jsonLookup(p, zPath, 0, ctx);
  174714. }else{
  174715. pNode = p->aNode;
  174716. }
  174717. if( pNode==0 ){
  174718. return;
  174719. }
  174720. if( pNode->eType==JSON_ARRAY ){
  174721. assert( (pNode->jnFlags & JNODE_APPEND)==0 );
  174722. for(i=1; i<=pNode->n; n++){
  174723. i += jsonNodeSize(&pNode[i]);
  174724. }
  174725. }
  174726. sqlite3_result_int64(ctx, n);
  174727. }
  174728. /*
  174729. ** json_extract(JSON, PATH, ...)
  174730. **
  174731. ** Return the element described by PATH. Return NULL if there is no
  174732. ** PATH element. If there are multiple PATHs, then return a JSON array
  174733. ** with the result from each path. Throw an error if the JSON or any PATH
  174734. ** is malformed.
  174735. */
  174736. static void jsonExtractFunc(
  174737. sqlite3_context *ctx,
  174738. int argc,
  174739. sqlite3_value **argv
  174740. ){
  174741. JsonParse *p; /* The parse */
  174742. JsonNode *pNode;
  174743. const char *zPath;
  174744. JsonString jx;
  174745. int i;
  174746. if( argc<2 ) return;
  174747. p = jsonParseCached(ctx, argv, ctx);
  174748. if( p==0 ) return;
  174749. jsonInit(&jx, ctx);
  174750. jsonAppendChar(&jx, '[');
  174751. for(i=1; i<argc; i++){
  174752. zPath = (const char*)sqlite3_value_text(argv[i]);
  174753. pNode = jsonLookup(p, zPath, 0, ctx);
  174754. if( p->nErr ) break;
  174755. if( argc>2 ){
  174756. jsonAppendSeparator(&jx);
  174757. if( pNode ){
  174758. jsonRenderNode(pNode, &jx, 0);
  174759. }else{
  174760. jsonAppendRaw(&jx, "null", 4);
  174761. }
  174762. }else if( pNode ){
  174763. jsonReturn(pNode, ctx, 0);
  174764. }
  174765. }
  174766. if( argc>2 && i==argc ){
  174767. jsonAppendChar(&jx, ']');
  174768. jsonResult(&jx);
  174769. sqlite3_result_subtype(ctx, JSON_SUBTYPE);
  174770. }
  174771. jsonReset(&jx);
  174772. }
  174773. /* This is the RFC 7396 MergePatch algorithm.
  174774. */
  174775. static JsonNode *jsonMergePatch(
  174776. JsonParse *pParse, /* The JSON parser that contains the TARGET */
  174777. u32 iTarget, /* Node of the TARGET in pParse */
  174778. JsonNode *pPatch /* The PATCH */
  174779. ){
  174780. u32 i, j;
  174781. u32 iRoot;
  174782. JsonNode *pTarget;
  174783. if( pPatch->eType!=JSON_OBJECT ){
  174784. return pPatch;
  174785. }
  174786. assert( iTarget>=0 && iTarget<pParse->nNode );
  174787. pTarget = &pParse->aNode[iTarget];
  174788. assert( (pPatch->jnFlags & JNODE_APPEND)==0 );
  174789. if( pTarget->eType!=JSON_OBJECT ){
  174790. jsonRemoveAllNulls(pPatch);
  174791. return pPatch;
  174792. }
  174793. iRoot = iTarget;
  174794. for(i=1; i<pPatch->n; i += jsonNodeSize(&pPatch[i+1])+1){
  174795. u32 nKey;
  174796. const char *zKey;
  174797. assert( pPatch[i].eType==JSON_STRING );
  174798. assert( pPatch[i].jnFlags & JNODE_LABEL );
  174799. nKey = pPatch[i].n;
  174800. zKey = pPatch[i].u.zJContent;
  174801. assert( (pPatch[i].jnFlags & JNODE_RAW)==0 );
  174802. for(j=1; j<pTarget->n; j += jsonNodeSize(&pTarget[j+1])+1 ){
  174803. assert( pTarget[j].eType==JSON_STRING );
  174804. assert( pTarget[j].jnFlags & JNODE_LABEL );
  174805. assert( (pPatch[i].jnFlags & JNODE_RAW)==0 );
  174806. if( pTarget[j].n==nKey && strncmp(pTarget[j].u.zJContent,zKey,nKey)==0 ){
  174807. if( pTarget[j+1].jnFlags & (JNODE_REMOVE|JNODE_PATCH) ) break;
  174808. if( pPatch[i+1].eType==JSON_NULL ){
  174809. pTarget[j+1].jnFlags |= JNODE_REMOVE;
  174810. }else{
  174811. JsonNode *pNew = jsonMergePatch(pParse, iTarget+j+1, &pPatch[i+1]);
  174812. if( pNew==0 ) return 0;
  174813. pTarget = &pParse->aNode[iTarget];
  174814. if( pNew!=&pTarget[j+1] ){
  174815. pTarget[j+1].u.pPatch = pNew;
  174816. pTarget[j+1].jnFlags |= JNODE_PATCH;
  174817. }
  174818. }
  174819. break;
  174820. }
  174821. }
  174822. if( j>=pTarget->n && pPatch[i+1].eType!=JSON_NULL ){
  174823. int iStart, iPatch;
  174824. iStart = jsonParseAddNode(pParse, JSON_OBJECT, 2, 0);
  174825. jsonParseAddNode(pParse, JSON_STRING, nKey, zKey);
  174826. iPatch = jsonParseAddNode(pParse, JSON_TRUE, 0, 0);
  174827. if( pParse->oom ) return 0;
  174828. jsonRemoveAllNulls(pPatch);
  174829. pTarget = &pParse->aNode[iTarget];
  174830. pParse->aNode[iRoot].jnFlags |= JNODE_APPEND;
  174831. pParse->aNode[iRoot].u.iAppend = iStart - iRoot;
  174832. iRoot = iStart;
  174833. pParse->aNode[iPatch].jnFlags |= JNODE_PATCH;
  174834. pParse->aNode[iPatch].u.pPatch = &pPatch[i+1];
  174835. }
  174836. }
  174837. return pTarget;
  174838. }
  174839. /*
  174840. ** Implementation of the json_mergepatch(JSON1,JSON2) function. Return a JSON
  174841. ** object that is the result of running the RFC 7396 MergePatch() algorithm
  174842. ** on the two arguments.
  174843. */
  174844. static void jsonPatchFunc(
  174845. sqlite3_context *ctx,
  174846. int argc,
  174847. sqlite3_value **argv
  174848. ){
  174849. JsonParse x; /* The JSON that is being patched */
  174850. JsonParse y; /* The patch */
  174851. JsonNode *pResult; /* The result of the merge */
  174852. UNUSED_PARAM(argc);
  174853. if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
  174854. if( jsonParse(&y, ctx, (const char*)sqlite3_value_text(argv[1])) ){
  174855. jsonParseReset(&x);
  174856. return;
  174857. }
  174858. pResult = jsonMergePatch(&x, 0, y.aNode);
  174859. assert( pResult!=0 || x.oom );
  174860. if( pResult ){
  174861. jsonReturnJson(pResult, ctx, 0);
  174862. }else{
  174863. sqlite3_result_error_nomem(ctx);
  174864. }
  174865. jsonParseReset(&x);
  174866. jsonParseReset(&y);
  174867. }
  174868. /*
  174869. ** Implementation of the json_object(NAME,VALUE,...) function. Return a JSON
  174870. ** object that contains all name/value given in arguments. Or if any name
  174871. ** is not a string or if any value is a BLOB, throw an error.
  174872. */
  174873. static void jsonObjectFunc(
  174874. sqlite3_context *ctx,
  174875. int argc,
  174876. sqlite3_value **argv
  174877. ){
  174878. int i;
  174879. JsonString jx;
  174880. const char *z;
  174881. u32 n;
  174882. if( argc&1 ){
  174883. sqlite3_result_error(ctx, "json_object() requires an even number "
  174884. "of arguments", -1);
  174885. return;
  174886. }
  174887. jsonInit(&jx, ctx);
  174888. jsonAppendChar(&jx, '{');
  174889. for(i=0; i<argc; i+=2){
  174890. if( sqlite3_value_type(argv[i])!=SQLITE_TEXT ){
  174891. sqlite3_result_error(ctx, "json_object() labels must be TEXT", -1);
  174892. jsonReset(&jx);
  174893. return;
  174894. }
  174895. jsonAppendSeparator(&jx);
  174896. z = (const char*)sqlite3_value_text(argv[i]);
  174897. n = (u32)sqlite3_value_bytes(argv[i]);
  174898. jsonAppendString(&jx, z, n);
  174899. jsonAppendChar(&jx, ':');
  174900. jsonAppendValue(&jx, argv[i+1]);
  174901. }
  174902. jsonAppendChar(&jx, '}');
  174903. jsonResult(&jx);
  174904. sqlite3_result_subtype(ctx, JSON_SUBTYPE);
  174905. }
  174906. /*
  174907. ** json_remove(JSON, PATH, ...)
  174908. **
  174909. ** Remove the named elements from JSON and return the result. malformed
  174910. ** JSON or PATH arguments result in an error.
  174911. */
  174912. static void jsonRemoveFunc(
  174913. sqlite3_context *ctx,
  174914. int argc,
  174915. sqlite3_value **argv
  174916. ){
  174917. JsonParse x; /* The parse */
  174918. JsonNode *pNode;
  174919. const char *zPath;
  174920. u32 i;
  174921. if( argc<1 ) return;
  174922. if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
  174923. assert( x.nNode );
  174924. for(i=1; i<(u32)argc; i++){
  174925. zPath = (const char*)sqlite3_value_text(argv[i]);
  174926. if( zPath==0 ) goto remove_done;
  174927. pNode = jsonLookup(&x, zPath, 0, ctx);
  174928. if( x.nErr ) goto remove_done;
  174929. if( pNode ) pNode->jnFlags |= JNODE_REMOVE;
  174930. }
  174931. if( (x.aNode[0].jnFlags & JNODE_REMOVE)==0 ){
  174932. jsonReturnJson(x.aNode, ctx, 0);
  174933. }
  174934. remove_done:
  174935. jsonParseReset(&x);
  174936. }
  174937. /*
  174938. ** json_replace(JSON, PATH, VALUE, ...)
  174939. **
  174940. ** Replace the value at PATH with VALUE. If PATH does not already exist,
  174941. ** this routine is a no-op. If JSON or PATH is malformed, throw an error.
  174942. */
  174943. static void jsonReplaceFunc(
  174944. sqlite3_context *ctx,
  174945. int argc,
  174946. sqlite3_value **argv
  174947. ){
  174948. JsonParse x; /* The parse */
  174949. JsonNode *pNode;
  174950. const char *zPath;
  174951. u32 i;
  174952. if( argc<1 ) return;
  174953. if( (argc&1)==0 ) {
  174954. jsonWrongNumArgs(ctx, "replace");
  174955. return;
  174956. }
  174957. if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
  174958. assert( x.nNode );
  174959. for(i=1; i<(u32)argc; i+=2){
  174960. zPath = (const char*)sqlite3_value_text(argv[i]);
  174961. pNode = jsonLookup(&x, zPath, 0, ctx);
  174962. if( x.nErr ) goto replace_err;
  174963. if( pNode ){
  174964. pNode->jnFlags |= (u8)JNODE_REPLACE;
  174965. pNode->u.iReplace = i + 1;
  174966. }
  174967. }
  174968. if( x.aNode[0].jnFlags & JNODE_REPLACE ){
  174969. sqlite3_result_value(ctx, argv[x.aNode[0].u.iReplace]);
  174970. }else{
  174971. jsonReturnJson(x.aNode, ctx, argv);
  174972. }
  174973. replace_err:
  174974. jsonParseReset(&x);
  174975. }
  174976. /*
  174977. ** json_set(JSON, PATH, VALUE, ...)
  174978. **
  174979. ** Set the value at PATH to VALUE. Create the PATH if it does not already
  174980. ** exist. Overwrite existing values that do exist.
  174981. ** If JSON or PATH is malformed, throw an error.
  174982. **
  174983. ** json_insert(JSON, PATH, VALUE, ...)
  174984. **
  174985. ** Create PATH and initialize it to VALUE. If PATH already exists, this
  174986. ** routine is a no-op. If JSON or PATH is malformed, throw an error.
  174987. */
  174988. static void jsonSetFunc(
  174989. sqlite3_context *ctx,
  174990. int argc,
  174991. sqlite3_value **argv
  174992. ){
  174993. JsonParse x; /* The parse */
  174994. JsonNode *pNode;
  174995. const char *zPath;
  174996. u32 i;
  174997. int bApnd;
  174998. int bIsSet = *(int*)sqlite3_user_data(ctx);
  174999. if( argc<1 ) return;
  175000. if( (argc&1)==0 ) {
  175001. jsonWrongNumArgs(ctx, bIsSet ? "set" : "insert");
  175002. return;
  175003. }
  175004. if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
  175005. assert( x.nNode );
  175006. for(i=1; i<(u32)argc; i+=2){
  175007. zPath = (const char*)sqlite3_value_text(argv[i]);
  175008. bApnd = 0;
  175009. pNode = jsonLookup(&x, zPath, &bApnd, ctx);
  175010. if( x.oom ){
  175011. sqlite3_result_error_nomem(ctx);
  175012. goto jsonSetDone;
  175013. }else if( x.nErr ){
  175014. goto jsonSetDone;
  175015. }else if( pNode && (bApnd || bIsSet) ){
  175016. pNode->jnFlags |= (u8)JNODE_REPLACE;
  175017. pNode->u.iReplace = i + 1;
  175018. }
  175019. }
  175020. if( x.aNode[0].jnFlags & JNODE_REPLACE ){
  175021. sqlite3_result_value(ctx, argv[x.aNode[0].u.iReplace]);
  175022. }else{
  175023. jsonReturnJson(x.aNode, ctx, argv);
  175024. }
  175025. jsonSetDone:
  175026. jsonParseReset(&x);
  175027. }
  175028. /*
  175029. ** json_type(JSON)
  175030. ** json_type(JSON, PATH)
  175031. **
  175032. ** Return the top-level "type" of a JSON string. Throw an error if
  175033. ** either the JSON or PATH inputs are not well-formed.
  175034. */
  175035. static void jsonTypeFunc(
  175036. sqlite3_context *ctx,
  175037. int argc,
  175038. sqlite3_value **argv
  175039. ){
  175040. JsonParse *p; /* The parse */
  175041. const char *zPath;
  175042. JsonNode *pNode;
  175043. p = jsonParseCached(ctx, argv, ctx);
  175044. if( p==0 ) return;
  175045. if( argc==2 ){
  175046. zPath = (const char*)sqlite3_value_text(argv[1]);
  175047. pNode = jsonLookup(p, zPath, 0, ctx);
  175048. }else{
  175049. pNode = p->aNode;
  175050. }
  175051. if( pNode ){
  175052. sqlite3_result_text(ctx, jsonType[pNode->eType], -1, SQLITE_STATIC);
  175053. }
  175054. }
  175055. /*
  175056. ** json_valid(JSON)
  175057. **
  175058. ** Return 1 if JSON is a well-formed JSON string according to RFC-7159.
  175059. ** Return 0 otherwise.
  175060. */
  175061. static void jsonValidFunc(
  175062. sqlite3_context *ctx,
  175063. int argc,
  175064. sqlite3_value **argv
  175065. ){
  175066. JsonParse *p; /* The parse */
  175067. UNUSED_PARAM(argc);
  175068. p = jsonParseCached(ctx, argv, 0);
  175069. sqlite3_result_int(ctx, p!=0);
  175070. }
  175071. /****************************************************************************
  175072. ** Aggregate SQL function implementations
  175073. ****************************************************************************/
  175074. /*
  175075. ** json_group_array(VALUE)
  175076. **
  175077. ** Return a JSON array composed of all values in the aggregate.
  175078. */
  175079. static void jsonArrayStep(
  175080. sqlite3_context *ctx,
  175081. int argc,
  175082. sqlite3_value **argv
  175083. ){
  175084. JsonString *pStr;
  175085. UNUSED_PARAM(argc);
  175086. pStr = (JsonString*)sqlite3_aggregate_context(ctx, sizeof(*pStr));
  175087. if( pStr ){
  175088. if( pStr->zBuf==0 ){
  175089. jsonInit(pStr, ctx);
  175090. jsonAppendChar(pStr, '[');
  175091. }else if( pStr->nUsed>1 ){
  175092. jsonAppendChar(pStr, ',');
  175093. pStr->pCtx = ctx;
  175094. }
  175095. jsonAppendValue(pStr, argv[0]);
  175096. }
  175097. }
  175098. static void jsonArrayCompute(sqlite3_context *ctx, int isFinal){
  175099. JsonString *pStr;
  175100. pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0);
  175101. if( pStr ){
  175102. pStr->pCtx = ctx;
  175103. jsonAppendChar(pStr, ']');
  175104. if( pStr->bErr ){
  175105. if( pStr->bErr==1 ) sqlite3_result_error_nomem(ctx);
  175106. assert( pStr->bStatic );
  175107. }else if( isFinal ){
  175108. sqlite3_result_text(ctx, pStr->zBuf, (int)pStr->nUsed,
  175109. pStr->bStatic ? SQLITE_TRANSIENT : sqlite3_free);
  175110. pStr->bStatic = 1;
  175111. }else{
  175112. sqlite3_result_text(ctx, pStr->zBuf, (int)pStr->nUsed, SQLITE_TRANSIENT);
  175113. pStr->nUsed--;
  175114. }
  175115. }else{
  175116. sqlite3_result_text(ctx, "[]", 2, SQLITE_STATIC);
  175117. }
  175118. sqlite3_result_subtype(ctx, JSON_SUBTYPE);
  175119. }
  175120. static void jsonArrayValue(sqlite3_context *ctx){
  175121. jsonArrayCompute(ctx, 0);
  175122. }
  175123. static void jsonArrayFinal(sqlite3_context *ctx){
  175124. jsonArrayCompute(ctx, 1);
  175125. }
  175126. #ifndef SQLITE_OMIT_WINDOWFUNC
  175127. /*
  175128. ** This method works for both json_group_array() and json_group_object().
  175129. ** It works by removing the first element of the group by searching forward
  175130. ** to the first comma (",") that is not within a string and deleting all
  175131. ** text through that comma.
  175132. */
  175133. static void jsonGroupInverse(
  175134. sqlite3_context *ctx,
  175135. int argc,
  175136. sqlite3_value **argv
  175137. ){
  175138. unsigned int i;
  175139. int inStr = 0;
  175140. int nNest = 0;
  175141. char *z;
  175142. char c;
  175143. JsonString *pStr;
  175144. UNUSED_PARAM(argc);
  175145. UNUSED_PARAM(argv);
  175146. pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0);
  175147. #ifdef NEVER
  175148. /* pStr is always non-NULL since jsonArrayStep() or jsonObjectStep() will
  175149. ** always have been called to initalize it */
  175150. if( NEVER(!pStr) ) return;
  175151. #endif
  175152. z = pStr->zBuf;
  175153. for(i=1; (c = z[i])!=',' || inStr || nNest; i++){
  175154. if( i>=pStr->nUsed ){
  175155. pStr->nUsed = 1;
  175156. return;
  175157. }
  175158. if( c=='"' ){
  175159. inStr = !inStr;
  175160. }else if( c=='\\' ){
  175161. i++;
  175162. }else if( !inStr ){
  175163. if( c=='{' || c=='[' ) nNest++;
  175164. if( c=='}' || c==']' ) nNest--;
  175165. }
  175166. }
  175167. pStr->nUsed -= i;
  175168. memmove(&z[1], &z[i+1], (size_t)pStr->nUsed-1);
  175169. }
  175170. #else
  175171. # define jsonGroupInverse 0
  175172. #endif
  175173. /*
  175174. ** json_group_obj(NAME,VALUE)
  175175. **
  175176. ** Return a JSON object composed of all names and values in the aggregate.
  175177. */
  175178. static void jsonObjectStep(
  175179. sqlite3_context *ctx,
  175180. int argc,
  175181. sqlite3_value **argv
  175182. ){
  175183. JsonString *pStr;
  175184. const char *z;
  175185. u32 n;
  175186. UNUSED_PARAM(argc);
  175187. pStr = (JsonString*)sqlite3_aggregate_context(ctx, sizeof(*pStr));
  175188. if( pStr ){
  175189. if( pStr->zBuf==0 ){
  175190. jsonInit(pStr, ctx);
  175191. jsonAppendChar(pStr, '{');
  175192. }else if( pStr->nUsed>1 ){
  175193. jsonAppendChar(pStr, ',');
  175194. pStr->pCtx = ctx;
  175195. }
  175196. z = (const char*)sqlite3_value_text(argv[0]);
  175197. n = (u32)sqlite3_value_bytes(argv[0]);
  175198. jsonAppendString(pStr, z, n);
  175199. jsonAppendChar(pStr, ':');
  175200. jsonAppendValue(pStr, argv[1]);
  175201. }
  175202. }
  175203. static void jsonObjectCompute(sqlite3_context *ctx, int isFinal){
  175204. JsonString *pStr;
  175205. pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0);
  175206. if( pStr ){
  175207. jsonAppendChar(pStr, '}');
  175208. if( pStr->bErr ){
  175209. if( pStr->bErr==1 ) sqlite3_result_error_nomem(ctx);
  175210. assert( pStr->bStatic );
  175211. }else if( isFinal ){
  175212. sqlite3_result_text(ctx, pStr->zBuf, (int)pStr->nUsed,
  175213. pStr->bStatic ? SQLITE_TRANSIENT : sqlite3_free);
  175214. pStr->bStatic = 1;
  175215. }else{
  175216. sqlite3_result_text(ctx, pStr->zBuf, (int)pStr->nUsed, SQLITE_TRANSIENT);
  175217. pStr->nUsed--;
  175218. }
  175219. }else{
  175220. sqlite3_result_text(ctx, "{}", 2, SQLITE_STATIC);
  175221. }
  175222. sqlite3_result_subtype(ctx, JSON_SUBTYPE);
  175223. }
  175224. static void jsonObjectValue(sqlite3_context *ctx){
  175225. jsonObjectCompute(ctx, 0);
  175226. }
  175227. static void jsonObjectFinal(sqlite3_context *ctx){
  175228. jsonObjectCompute(ctx, 1);
  175229. }
  175230. #ifndef SQLITE_OMIT_VIRTUALTABLE
  175231. /****************************************************************************
  175232. ** The json_each virtual table
  175233. ****************************************************************************/
  175234. typedef struct JsonEachCursor JsonEachCursor;
  175235. struct JsonEachCursor {
  175236. sqlite3_vtab_cursor base; /* Base class - must be first */
  175237. u32 iRowid; /* The rowid */
  175238. u32 iBegin; /* The first node of the scan */
  175239. u32 i; /* Index in sParse.aNode[] of current row */
  175240. u32 iEnd; /* EOF when i equals or exceeds this value */
  175241. u8 eType; /* Type of top-level element */
  175242. u8 bRecursive; /* True for json_tree(). False for json_each() */
  175243. char *zJson; /* Input JSON */
  175244. char *zRoot; /* Path by which to filter zJson */
  175245. JsonParse sParse; /* Parse of the input JSON */
  175246. };
  175247. /* Constructor for the json_each virtual table */
  175248. static int jsonEachConnect(
  175249. sqlite3 *db,
  175250. void *pAux,
  175251. int argc, const char *const*argv,
  175252. sqlite3_vtab **ppVtab,
  175253. char **pzErr
  175254. ){
  175255. sqlite3_vtab *pNew;
  175256. int rc;
  175257. /* Column numbers */
  175258. #define JEACH_KEY 0
  175259. #define JEACH_VALUE 1
  175260. #define JEACH_TYPE 2
  175261. #define JEACH_ATOM 3
  175262. #define JEACH_ID 4
  175263. #define JEACH_PARENT 5
  175264. #define JEACH_FULLKEY 6
  175265. #define JEACH_PATH 7
  175266. /* The xBestIndex method assumes that the JSON and ROOT columns are
  175267. ** the last two columns in the table. Should this ever changes, be
  175268. ** sure to update the xBestIndex method. */
  175269. #define JEACH_JSON 8
  175270. #define JEACH_ROOT 9
  175271. UNUSED_PARAM(pzErr);
  175272. UNUSED_PARAM(argv);
  175273. UNUSED_PARAM(argc);
  175274. UNUSED_PARAM(pAux);
  175275. rc = sqlite3_declare_vtab(db,
  175276. "CREATE TABLE x(key,value,type,atom,id,parent,fullkey,path,"
  175277. "json HIDDEN,root HIDDEN)");
  175278. if( rc==SQLITE_OK ){
  175279. pNew = *ppVtab = sqlite3_malloc( sizeof(*pNew) );
  175280. if( pNew==0 ) return SQLITE_NOMEM;
  175281. memset(pNew, 0, sizeof(*pNew));
  175282. sqlite3_vtab_config(db, SQLITE_VTAB_INNOCUOUS);
  175283. }
  175284. return rc;
  175285. }
  175286. /* destructor for json_each virtual table */
  175287. static int jsonEachDisconnect(sqlite3_vtab *pVtab){
  175288. sqlite3_free(pVtab);
  175289. return SQLITE_OK;
  175290. }
  175291. /* constructor for a JsonEachCursor object for json_each(). */
  175292. static int jsonEachOpenEach(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
  175293. JsonEachCursor *pCur;
  175294. UNUSED_PARAM(p);
  175295. pCur = sqlite3_malloc( sizeof(*pCur) );
  175296. if( pCur==0 ) return SQLITE_NOMEM;
  175297. memset(pCur, 0, sizeof(*pCur));
  175298. *ppCursor = &pCur->base;
  175299. return SQLITE_OK;
  175300. }
  175301. /* constructor for a JsonEachCursor object for json_tree(). */
  175302. static int jsonEachOpenTree(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
  175303. int rc = jsonEachOpenEach(p, ppCursor);
  175304. if( rc==SQLITE_OK ){
  175305. JsonEachCursor *pCur = (JsonEachCursor*)*ppCursor;
  175306. pCur->bRecursive = 1;
  175307. }
  175308. return rc;
  175309. }
  175310. /* Reset a JsonEachCursor back to its original state. Free any memory
  175311. ** held. */
  175312. static void jsonEachCursorReset(JsonEachCursor *p){
  175313. sqlite3_free(p->zJson);
  175314. sqlite3_free(p->zRoot);
  175315. jsonParseReset(&p->sParse);
  175316. p->iRowid = 0;
  175317. p->i = 0;
  175318. p->iEnd = 0;
  175319. p->eType = 0;
  175320. p->zJson = 0;
  175321. p->zRoot = 0;
  175322. }
  175323. /* Destructor for a jsonEachCursor object */
  175324. static int jsonEachClose(sqlite3_vtab_cursor *cur){
  175325. JsonEachCursor *p = (JsonEachCursor*)cur;
  175326. jsonEachCursorReset(p);
  175327. sqlite3_free(cur);
  175328. return SQLITE_OK;
  175329. }
  175330. /* Return TRUE if the jsonEachCursor object has been advanced off the end
  175331. ** of the JSON object */
  175332. static int jsonEachEof(sqlite3_vtab_cursor *cur){
  175333. JsonEachCursor *p = (JsonEachCursor*)cur;
  175334. return p->i >= p->iEnd;
  175335. }
  175336. /* Advance the cursor to the next element for json_tree() */
  175337. static int jsonEachNext(sqlite3_vtab_cursor *cur){
  175338. JsonEachCursor *p = (JsonEachCursor*)cur;
  175339. if( p->bRecursive ){
  175340. if( p->sParse.aNode[p->i].jnFlags & JNODE_LABEL ) p->i++;
  175341. p->i++;
  175342. p->iRowid++;
  175343. if( p->i<p->iEnd ){
  175344. u32 iUp = p->sParse.aUp[p->i];
  175345. JsonNode *pUp = &p->sParse.aNode[iUp];
  175346. p->eType = pUp->eType;
  175347. if( pUp->eType==JSON_ARRAY ){
  175348. if( iUp==p->i-1 ){
  175349. pUp->u.iKey = 0;
  175350. }else{
  175351. pUp->u.iKey++;
  175352. }
  175353. }
  175354. }
  175355. }else{
  175356. switch( p->eType ){
  175357. case JSON_ARRAY: {
  175358. p->i += jsonNodeSize(&p->sParse.aNode[p->i]);
  175359. p->iRowid++;
  175360. break;
  175361. }
  175362. case JSON_OBJECT: {
  175363. p->i += 1 + jsonNodeSize(&p->sParse.aNode[p->i+1]);
  175364. p->iRowid++;
  175365. break;
  175366. }
  175367. default: {
  175368. p->i = p->iEnd;
  175369. break;
  175370. }
  175371. }
  175372. }
  175373. return SQLITE_OK;
  175374. }
  175375. /* Append the name of the path for element i to pStr
  175376. */
  175377. static void jsonEachComputePath(
  175378. JsonEachCursor *p, /* The cursor */
  175379. JsonString *pStr, /* Write the path here */
  175380. u32 i /* Path to this element */
  175381. ){
  175382. JsonNode *pNode, *pUp;
  175383. u32 iUp;
  175384. if( i==0 ){
  175385. jsonAppendChar(pStr, '$');
  175386. return;
  175387. }
  175388. iUp = p->sParse.aUp[i];
  175389. jsonEachComputePath(p, pStr, iUp);
  175390. pNode = &p->sParse.aNode[i];
  175391. pUp = &p->sParse.aNode[iUp];
  175392. if( pUp->eType==JSON_ARRAY ){
  175393. jsonPrintf(30, pStr, "[%d]", pUp->u.iKey);
  175394. }else{
  175395. assert( pUp->eType==JSON_OBJECT );
  175396. if( (pNode->jnFlags & JNODE_LABEL)==0 ) pNode--;
  175397. assert( pNode->eType==JSON_STRING );
  175398. assert( pNode->jnFlags & JNODE_LABEL );
  175399. jsonPrintf(pNode->n+1, pStr, ".%.*s", pNode->n-2, pNode->u.zJContent+1);
  175400. }
  175401. }
  175402. /* Return the value of a column */
  175403. static int jsonEachColumn(
  175404. sqlite3_vtab_cursor *cur, /* The cursor */
  175405. sqlite3_context *ctx, /* First argument to sqlite3_result_...() */
  175406. int i /* Which column to return */
  175407. ){
  175408. JsonEachCursor *p = (JsonEachCursor*)cur;
  175409. JsonNode *pThis = &p->sParse.aNode[p->i];
  175410. switch( i ){
  175411. case JEACH_KEY: {
  175412. if( p->i==0 ) break;
  175413. if( p->eType==JSON_OBJECT ){
  175414. jsonReturn(pThis, ctx, 0);
  175415. }else if( p->eType==JSON_ARRAY ){
  175416. u32 iKey;
  175417. if( p->bRecursive ){
  175418. if( p->iRowid==0 ) break;
  175419. iKey = p->sParse.aNode[p->sParse.aUp[p->i]].u.iKey;
  175420. }else{
  175421. iKey = p->iRowid;
  175422. }
  175423. sqlite3_result_int64(ctx, (sqlite3_int64)iKey);
  175424. }
  175425. break;
  175426. }
  175427. case JEACH_VALUE: {
  175428. if( pThis->jnFlags & JNODE_LABEL ) pThis++;
  175429. jsonReturn(pThis, ctx, 0);
  175430. break;
  175431. }
  175432. case JEACH_TYPE: {
  175433. if( pThis->jnFlags & JNODE_LABEL ) pThis++;
  175434. sqlite3_result_text(ctx, jsonType[pThis->eType], -1, SQLITE_STATIC);
  175435. break;
  175436. }
  175437. case JEACH_ATOM: {
  175438. if( pThis->jnFlags & JNODE_LABEL ) pThis++;
  175439. if( pThis->eType>=JSON_ARRAY ) break;
  175440. jsonReturn(pThis, ctx, 0);
  175441. break;
  175442. }
  175443. case JEACH_ID: {
  175444. sqlite3_result_int64(ctx,
  175445. (sqlite3_int64)p->i + ((pThis->jnFlags & JNODE_LABEL)!=0));
  175446. break;
  175447. }
  175448. case JEACH_PARENT: {
  175449. if( p->i>p->iBegin && p->bRecursive ){
  175450. sqlite3_result_int64(ctx, (sqlite3_int64)p->sParse.aUp[p->i]);
  175451. }
  175452. break;
  175453. }
  175454. case JEACH_FULLKEY: {
  175455. JsonString x;
  175456. jsonInit(&x, ctx);
  175457. if( p->bRecursive ){
  175458. jsonEachComputePath(p, &x, p->i);
  175459. }else{
  175460. if( p->zRoot ){
  175461. jsonAppendRaw(&x, p->zRoot, (int)strlen(p->zRoot));
  175462. }else{
  175463. jsonAppendChar(&x, '$');
  175464. }
  175465. if( p->eType==JSON_ARRAY ){
  175466. jsonPrintf(30, &x, "[%d]", p->iRowid);
  175467. }else if( p->eType==JSON_OBJECT ){
  175468. jsonPrintf(pThis->n, &x, ".%.*s", pThis->n-2, pThis->u.zJContent+1);
  175469. }
  175470. }
  175471. jsonResult(&x);
  175472. break;
  175473. }
  175474. case JEACH_PATH: {
  175475. if( p->bRecursive ){
  175476. JsonString x;
  175477. jsonInit(&x, ctx);
  175478. jsonEachComputePath(p, &x, p->sParse.aUp[p->i]);
  175479. jsonResult(&x);
  175480. break;
  175481. }
  175482. /* For json_each() path and root are the same so fall through
  175483. ** into the root case */
  175484. }
  175485. default: {
  175486. const char *zRoot = p->zRoot;
  175487. if( zRoot==0 ) zRoot = "$";
  175488. sqlite3_result_text(ctx, zRoot, -1, SQLITE_STATIC);
  175489. break;
  175490. }
  175491. case JEACH_JSON: {
  175492. assert( i==JEACH_JSON );
  175493. sqlite3_result_text(ctx, p->sParse.zJson, -1, SQLITE_STATIC);
  175494. break;
  175495. }
  175496. }
  175497. return SQLITE_OK;
  175498. }
  175499. /* Return the current rowid value */
  175500. static int jsonEachRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
  175501. JsonEachCursor *p = (JsonEachCursor*)cur;
  175502. *pRowid = p->iRowid;
  175503. return SQLITE_OK;
  175504. }
  175505. /* The query strategy is to look for an equality constraint on the json
  175506. ** column. Without such a constraint, the table cannot operate. idxNum is
  175507. ** 1 if the constraint is found, 3 if the constraint and zRoot are found,
  175508. ** and 0 otherwise.
  175509. */
  175510. static int jsonEachBestIndex(
  175511. sqlite3_vtab *tab,
  175512. sqlite3_index_info *pIdxInfo
  175513. ){
  175514. int i; /* Loop counter or computed array index */
  175515. int aIdx[2]; /* Index of constraints for JSON and ROOT */
  175516. int unusableMask = 0; /* Mask of unusable JSON and ROOT constraints */
  175517. int idxMask = 0; /* Mask of usable == constraints JSON and ROOT */
  175518. const struct sqlite3_index_constraint *pConstraint;
  175519. /* This implementation assumes that JSON and ROOT are the last two
  175520. ** columns in the table */
  175521. assert( JEACH_ROOT == JEACH_JSON+1 );
  175522. UNUSED_PARAM(tab);
  175523. aIdx[0] = aIdx[1] = -1;
  175524. pConstraint = pIdxInfo->aConstraint;
  175525. for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
  175526. int iCol;
  175527. int iMask;
  175528. if( pConstraint->iColumn < JEACH_JSON ) continue;
  175529. iCol = pConstraint->iColumn - JEACH_JSON;
  175530. assert( iCol==0 || iCol==1 );
  175531. iMask = 1 << iCol;
  175532. if( pConstraint->usable==0 ){
  175533. unusableMask |= iMask;
  175534. }else if( pConstraint->op==SQLITE_INDEX_CONSTRAINT_EQ ){
  175535. aIdx[iCol] = i;
  175536. idxMask |= iMask;
  175537. }
  175538. }
  175539. if( (unusableMask & ~idxMask)!=0 ){
  175540. /* If there are any unusable constraints on JSON or ROOT, then reject
  175541. ** this entire plan */
  175542. return SQLITE_CONSTRAINT;
  175543. }
  175544. if( aIdx[0]<0 ){
  175545. /* No JSON input. Leave estimatedCost at the huge value that it was
  175546. ** initialized to to discourage the query planner from selecting this
  175547. ** plan. */
  175548. pIdxInfo->idxNum = 0;
  175549. }else{
  175550. pIdxInfo->estimatedCost = 1.0;
  175551. i = aIdx[0];
  175552. pIdxInfo->aConstraintUsage[i].argvIndex = 1;
  175553. pIdxInfo->aConstraintUsage[i].omit = 1;
  175554. if( aIdx[1]<0 ){
  175555. pIdxInfo->idxNum = 1; /* Only JSON supplied. Plan 1 */
  175556. }else{
  175557. i = aIdx[1];
  175558. pIdxInfo->aConstraintUsage[i].argvIndex = 2;
  175559. pIdxInfo->aConstraintUsage[i].omit = 1;
  175560. pIdxInfo->idxNum = 3; /* Both JSON and ROOT are supplied. Plan 3 */
  175561. }
  175562. }
  175563. return SQLITE_OK;
  175564. }
  175565. /* Start a search on a new JSON string */
  175566. static int jsonEachFilter(
  175567. sqlite3_vtab_cursor *cur,
  175568. int idxNum, const char *idxStr,
  175569. int argc, sqlite3_value **argv
  175570. ){
  175571. JsonEachCursor *p = (JsonEachCursor*)cur;
  175572. const char *z;
  175573. const char *zRoot = 0;
  175574. sqlite3_int64 n;
  175575. UNUSED_PARAM(idxStr);
  175576. UNUSED_PARAM(argc);
  175577. jsonEachCursorReset(p);
  175578. if( idxNum==0 ) return SQLITE_OK;
  175579. z = (const char*)sqlite3_value_text(argv[0]);
  175580. if( z==0 ) return SQLITE_OK;
  175581. n = sqlite3_value_bytes(argv[0]);
  175582. p->zJson = sqlite3_malloc64( n+1 );
  175583. if( p->zJson==0 ) return SQLITE_NOMEM;
  175584. memcpy(p->zJson, z, (size_t)n+1);
  175585. if( jsonParse(&p->sParse, 0, p->zJson) ){
  175586. int rc = SQLITE_NOMEM;
  175587. if( p->sParse.oom==0 ){
  175588. sqlite3_free(cur->pVtab->zErrMsg);
  175589. cur->pVtab->zErrMsg = sqlite3_mprintf("malformed JSON");
  175590. if( cur->pVtab->zErrMsg ) rc = SQLITE_ERROR;
  175591. }
  175592. jsonEachCursorReset(p);
  175593. return rc;
  175594. }else if( p->bRecursive && jsonParseFindParents(&p->sParse) ){
  175595. jsonEachCursorReset(p);
  175596. return SQLITE_NOMEM;
  175597. }else{
  175598. JsonNode *pNode = 0;
  175599. if( idxNum==3 ){
  175600. const char *zErr = 0;
  175601. zRoot = (const char*)sqlite3_value_text(argv[1]);
  175602. if( zRoot==0 ) return SQLITE_OK;
  175603. n = sqlite3_value_bytes(argv[1]);
  175604. p->zRoot = sqlite3_malloc64( n+1 );
  175605. if( p->zRoot==0 ) return SQLITE_NOMEM;
  175606. memcpy(p->zRoot, zRoot, (size_t)n+1);
  175607. if( zRoot[0]!='$' ){
  175608. zErr = zRoot;
  175609. }else{
  175610. pNode = jsonLookupStep(&p->sParse, 0, p->zRoot+1, 0, &zErr);
  175611. }
  175612. if( zErr ){
  175613. sqlite3_free(cur->pVtab->zErrMsg);
  175614. cur->pVtab->zErrMsg = jsonPathSyntaxError(zErr);
  175615. jsonEachCursorReset(p);
  175616. return cur->pVtab->zErrMsg ? SQLITE_ERROR : SQLITE_NOMEM;
  175617. }else if( pNode==0 ){
  175618. return SQLITE_OK;
  175619. }
  175620. }else{
  175621. pNode = p->sParse.aNode;
  175622. }
  175623. p->iBegin = p->i = (int)(pNode - p->sParse.aNode);
  175624. p->eType = pNode->eType;
  175625. if( p->eType>=JSON_ARRAY ){
  175626. pNode->u.iKey = 0;
  175627. p->iEnd = p->i + pNode->n + 1;
  175628. if( p->bRecursive ){
  175629. p->eType = p->sParse.aNode[p->sParse.aUp[p->i]].eType;
  175630. if( p->i>0 && (p->sParse.aNode[p->i-1].jnFlags & JNODE_LABEL)!=0 ){
  175631. p->i--;
  175632. }
  175633. }else{
  175634. p->i++;
  175635. }
  175636. }else{
  175637. p->iEnd = p->i+1;
  175638. }
  175639. }
  175640. return SQLITE_OK;
  175641. }
  175642. /* The methods of the json_each virtual table */
  175643. static sqlite3_module jsonEachModule = {
  175644. 0, /* iVersion */
  175645. 0, /* xCreate */
  175646. jsonEachConnect, /* xConnect */
  175647. jsonEachBestIndex, /* xBestIndex */
  175648. jsonEachDisconnect, /* xDisconnect */
  175649. 0, /* xDestroy */
  175650. jsonEachOpenEach, /* xOpen - open a cursor */
  175651. jsonEachClose, /* xClose - close a cursor */
  175652. jsonEachFilter, /* xFilter - configure scan constraints */
  175653. jsonEachNext, /* xNext - advance a cursor */
  175654. jsonEachEof, /* xEof - check for end of scan */
  175655. jsonEachColumn, /* xColumn - read data */
  175656. jsonEachRowid, /* xRowid - read data */
  175657. 0, /* xUpdate */
  175658. 0, /* xBegin */
  175659. 0, /* xSync */
  175660. 0, /* xCommit */
  175661. 0, /* xRollback */
  175662. 0, /* xFindMethod */
  175663. 0, /* xRename */
  175664. 0, /* xSavepoint */
  175665. 0, /* xRelease */
  175666. 0, /* xRollbackTo */
  175667. 0 /* xShadowName */
  175668. };
  175669. /* The methods of the json_tree virtual table. */
  175670. static sqlite3_module jsonTreeModule = {
  175671. 0, /* iVersion */
  175672. 0, /* xCreate */
  175673. jsonEachConnect, /* xConnect */
  175674. jsonEachBestIndex, /* xBestIndex */
  175675. jsonEachDisconnect, /* xDisconnect */
  175676. 0, /* xDestroy */
  175677. jsonEachOpenTree, /* xOpen - open a cursor */
  175678. jsonEachClose, /* xClose - close a cursor */
  175679. jsonEachFilter, /* xFilter - configure scan constraints */
  175680. jsonEachNext, /* xNext - advance a cursor */
  175681. jsonEachEof, /* xEof - check for end of scan */
  175682. jsonEachColumn, /* xColumn - read data */
  175683. jsonEachRowid, /* xRowid - read data */
  175684. 0, /* xUpdate */
  175685. 0, /* xBegin */
  175686. 0, /* xSync */
  175687. 0, /* xCommit */
  175688. 0, /* xRollback */
  175689. 0, /* xFindMethod */
  175690. 0, /* xRename */
  175691. 0, /* xSavepoint */
  175692. 0, /* xRelease */
  175693. 0, /* xRollbackTo */
  175694. 0 /* xShadowName */
  175695. };
  175696. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  175697. /****************************************************************************
  175698. ** The following routines are the only publically visible identifiers in this
  175699. ** file. Call the following routines in order to register the various SQL
  175700. ** functions and the virtual table implemented by this file.
  175701. ****************************************************************************/
  175702. SQLITE_PRIVATE int sqlite3Json1Init(sqlite3 *db){
  175703. int rc = SQLITE_OK;
  175704. unsigned int i;
  175705. static const struct {
  175706. const char *zName;
  175707. int nArg;
  175708. int flag;
  175709. void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
  175710. } aFunc[] = {
  175711. { "json", 1, 0, jsonRemoveFunc },
  175712. { "json_array", -1, 0, jsonArrayFunc },
  175713. { "json_array_length", 1, 0, jsonArrayLengthFunc },
  175714. { "json_array_length", 2, 0, jsonArrayLengthFunc },
  175715. { "json_extract", -1, 0, jsonExtractFunc },
  175716. { "json_insert", -1, 0, jsonSetFunc },
  175717. { "json_object", -1, 0, jsonObjectFunc },
  175718. { "json_patch", 2, 0, jsonPatchFunc },
  175719. { "json_quote", 1, 0, jsonQuoteFunc },
  175720. { "json_remove", -1, 0, jsonRemoveFunc },
  175721. { "json_replace", -1, 0, jsonReplaceFunc },
  175722. { "json_set", -1, 1, jsonSetFunc },
  175723. { "json_type", 1, 0, jsonTypeFunc },
  175724. { "json_type", 2, 0, jsonTypeFunc },
  175725. { "json_valid", 1, 0, jsonValidFunc },
  175726. #if SQLITE_DEBUG
  175727. /* DEBUG and TESTING functions */
  175728. { "json_parse", 1, 0, jsonParseFunc },
  175729. { "json_test1", 1, 0, jsonTest1Func },
  175730. #endif
  175731. };
  175732. static const struct {
  175733. const char *zName;
  175734. int nArg;
  175735. void (*xStep)(sqlite3_context*,int,sqlite3_value**);
  175736. void (*xFinal)(sqlite3_context*);
  175737. void (*xValue)(sqlite3_context*);
  175738. } aAgg[] = {
  175739. { "json_group_array", 1,
  175740. jsonArrayStep, jsonArrayFinal, jsonArrayValue },
  175741. { "json_group_object", 2,
  175742. jsonObjectStep, jsonObjectFinal, jsonObjectValue },
  175743. };
  175744. #ifndef SQLITE_OMIT_VIRTUALTABLE
  175745. static const struct {
  175746. const char *zName;
  175747. sqlite3_module *pModule;
  175748. } aMod[] = {
  175749. { "json_each", &jsonEachModule },
  175750. { "json_tree", &jsonTreeModule },
  175751. };
  175752. #endif
  175753. static const int enc =
  175754. SQLITE_UTF8 |
  175755. SQLITE_DETERMINISTIC |
  175756. SQLITE_INNOCUOUS;
  175757. for(i=0; i<sizeof(aFunc)/sizeof(aFunc[0]) && rc==SQLITE_OK; i++){
  175758. rc = sqlite3_create_function(db, aFunc[i].zName, aFunc[i].nArg, enc,
  175759. (void*)&aFunc[i].flag,
  175760. aFunc[i].xFunc, 0, 0);
  175761. }
  175762. #ifndef SQLITE_OMIT_WINDOWFUNC
  175763. for(i=0; i<sizeof(aAgg)/sizeof(aAgg[0]) && rc==SQLITE_OK; i++){
  175764. rc = sqlite3_create_window_function(db, aAgg[i].zName, aAgg[i].nArg,
  175765. SQLITE_SUBTYPE | enc, 0,
  175766. aAgg[i].xStep, aAgg[i].xFinal,
  175767. aAgg[i].xValue, jsonGroupInverse, 0);
  175768. }
  175769. #endif
  175770. #ifndef SQLITE_OMIT_VIRTUALTABLE
  175771. for(i=0; i<sizeof(aMod)/sizeof(aMod[0]) && rc==SQLITE_OK; i++){
  175772. rc = sqlite3_create_module(db, aMod[i].zName, aMod[i].pModule, 0);
  175773. }
  175774. #endif
  175775. return rc;
  175776. }
  175777. #ifndef SQLITE_CORE
  175778. #ifdef _WIN32
  175779. __declspec(dllexport)
  175780. #endif
  175781. SQLITE_API int sqlite3_json_init(
  175782. sqlite3 *db,
  175783. char **pzErrMsg,
  175784. const sqlite3_api_routines *pApi
  175785. ){
  175786. SQLITE_EXTENSION_INIT2(pApi);
  175787. (void)pzErrMsg; /* Unused parameter */
  175788. return sqlite3Json1Init(db);
  175789. }
  175790. #endif
  175791. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_JSON1) */
  175792. /************** End of json1.c ***********************************************/
  175793. /************** Begin file rtree.c *******************************************/
  175794. /*
  175795. ** 2001 September 15
  175796. **
  175797. ** The author disclaims copyright to this source code. In place of
  175798. ** a legal notice, here is a blessing:
  175799. **
  175800. ** May you do good and not evil.
  175801. ** May you find forgiveness for yourself and forgive others.
  175802. ** May you share freely, never taking more than you give.
  175803. **
  175804. *************************************************************************
  175805. ** This file contains code for implementations of the r-tree and r*-tree
  175806. ** algorithms packaged as an SQLite virtual table module.
  175807. */
  175808. /*
  175809. ** Database Format of R-Tree Tables
  175810. ** --------------------------------
  175811. **
  175812. ** The data structure for a single virtual r-tree table is stored in three
  175813. ** native SQLite tables declared as follows. In each case, the '%' character
  175814. ** in the table name is replaced with the user-supplied name of the r-tree
  175815. ** table.
  175816. **
  175817. ** CREATE TABLE %_node(nodeno INTEGER PRIMARY KEY, data BLOB)
  175818. ** CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)
  175819. ** CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER, ...)
  175820. **
  175821. ** The data for each node of the r-tree structure is stored in the %_node
  175822. ** table. For each node that is not the root node of the r-tree, there is
  175823. ** an entry in the %_parent table associating the node with its parent.
  175824. ** And for each row of data in the table, there is an entry in the %_rowid
  175825. ** table that maps from the entries rowid to the id of the node that it
  175826. ** is stored on. If the r-tree contains auxiliary columns, those are stored
  175827. ** on the end of the %_rowid table.
  175828. **
  175829. ** The root node of an r-tree always exists, even if the r-tree table is
  175830. ** empty. The nodeno of the root node is always 1. All other nodes in the
  175831. ** table must be the same size as the root node. The content of each node
  175832. ** is formatted as follows:
  175833. **
  175834. ** 1. If the node is the root node (node 1), then the first 2 bytes
  175835. ** of the node contain the tree depth as a big-endian integer.
  175836. ** For non-root nodes, the first 2 bytes are left unused.
  175837. **
  175838. ** 2. The next 2 bytes contain the number of entries currently
  175839. ** stored in the node.
  175840. **
  175841. ** 3. The remainder of the node contains the node entries. Each entry
  175842. ** consists of a single 8-byte integer followed by an even number
  175843. ** of 4-byte coordinates. For leaf nodes the integer is the rowid
  175844. ** of a record. For internal nodes it is the node number of a
  175845. ** child page.
  175846. */
  175847. #if !defined(SQLITE_CORE) \
  175848. || (defined(SQLITE_ENABLE_RTREE) && !defined(SQLITE_OMIT_VIRTUALTABLE))
  175849. #ifndef SQLITE_CORE
  175850. /* #include "sqlite3ext.h" */
  175851. SQLITE_EXTENSION_INIT1
  175852. #else
  175853. /* #include "sqlite3.h" */
  175854. #endif
  175855. SQLITE_PRIVATE int sqlite3GetToken(const unsigned char*,int*); /* In the SQLite core */
  175856. #ifndef SQLITE_AMALGAMATION
  175857. #include "sqlite3rtree.h"
  175858. typedef sqlite3_int64 i64;
  175859. typedef sqlite3_uint64 u64;
  175860. typedef unsigned char u8;
  175861. typedef unsigned short u16;
  175862. typedef unsigned int u32;
  175863. #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
  175864. # define NDEBUG 1
  175865. #endif
  175866. #if defined(NDEBUG) && defined(SQLITE_DEBUG)
  175867. # undef NDEBUG
  175868. #endif
  175869. #endif
  175870. /* #include <string.h> */
  175871. /* #include <stdio.h> */
  175872. /* #include <assert.h> */
  175873. /* The following macro is used to suppress compiler warnings.
  175874. */
  175875. #ifndef UNUSED_PARAMETER
  175876. # define UNUSED_PARAMETER(x) (void)(x)
  175877. #endif
  175878. typedef struct Rtree Rtree;
  175879. typedef struct RtreeCursor RtreeCursor;
  175880. typedef struct RtreeNode RtreeNode;
  175881. typedef struct RtreeCell RtreeCell;
  175882. typedef struct RtreeConstraint RtreeConstraint;
  175883. typedef struct RtreeMatchArg RtreeMatchArg;
  175884. typedef struct RtreeGeomCallback RtreeGeomCallback;
  175885. typedef union RtreeCoord RtreeCoord;
  175886. typedef struct RtreeSearchPoint RtreeSearchPoint;
  175887. /* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
  175888. #define RTREE_MAX_DIMENSIONS 5
  175889. /* Maximum number of auxiliary columns */
  175890. #define RTREE_MAX_AUX_COLUMN 100
  175891. /* Size of hash table Rtree.aHash. This hash table is not expected to
  175892. ** ever contain very many entries, so a fixed number of buckets is
  175893. ** used.
  175894. */
  175895. #define HASHSIZE 97
  175896. /* The xBestIndex method of this virtual table requires an estimate of
  175897. ** the number of rows in the virtual table to calculate the costs of
  175898. ** various strategies. If possible, this estimate is loaded from the
  175899. ** sqlite_stat1 table (with RTREE_MIN_ROWEST as a hard-coded minimum).
  175900. ** Otherwise, if no sqlite_stat1 entry is available, use
  175901. ** RTREE_DEFAULT_ROWEST.
  175902. */
  175903. #define RTREE_DEFAULT_ROWEST 1048576
  175904. #define RTREE_MIN_ROWEST 100
  175905. /*
  175906. ** An rtree virtual-table object.
  175907. */
  175908. struct Rtree {
  175909. sqlite3_vtab base; /* Base class. Must be first */
  175910. sqlite3 *db; /* Host database connection */
  175911. int iNodeSize; /* Size in bytes of each node in the node table */
  175912. u8 nDim; /* Number of dimensions */
  175913. u8 nDim2; /* Twice the number of dimensions */
  175914. u8 eCoordType; /* RTREE_COORD_REAL32 or RTREE_COORD_INT32 */
  175915. u8 nBytesPerCell; /* Bytes consumed per cell */
  175916. u8 inWrTrans; /* True if inside write transaction */
  175917. u8 nAux; /* # of auxiliary columns in %_rowid */
  175918. u8 nAuxNotNull; /* Number of initial not-null aux columns */
  175919. #ifdef SQLITE_DEBUG
  175920. u8 bCorrupt; /* Shadow table corruption detected */
  175921. #endif
  175922. int iDepth; /* Current depth of the r-tree structure */
  175923. char *zDb; /* Name of database containing r-tree table */
  175924. char *zName; /* Name of r-tree table */
  175925. u32 nBusy; /* Current number of users of this structure */
  175926. i64 nRowEst; /* Estimated number of rows in this table */
  175927. u32 nCursor; /* Number of open cursors */
  175928. u32 nNodeRef; /* Number RtreeNodes with positive nRef */
  175929. char *zReadAuxSql; /* SQL for statement to read aux data */
  175930. /* List of nodes removed during a CondenseTree operation. List is
  175931. ** linked together via the pointer normally used for hash chains -
  175932. ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree
  175933. ** headed by the node (leaf nodes have RtreeNode.iNode==0).
  175934. */
  175935. RtreeNode *pDeleted;
  175936. int iReinsertHeight; /* Height of sub-trees Reinsert() has run on */
  175937. /* Blob I/O on xxx_node */
  175938. sqlite3_blob *pNodeBlob;
  175939. /* Statements to read/write/delete a record from xxx_node */
  175940. sqlite3_stmt *pWriteNode;
  175941. sqlite3_stmt *pDeleteNode;
  175942. /* Statements to read/write/delete a record from xxx_rowid */
  175943. sqlite3_stmt *pReadRowid;
  175944. sqlite3_stmt *pWriteRowid;
  175945. sqlite3_stmt *pDeleteRowid;
  175946. /* Statements to read/write/delete a record from xxx_parent */
  175947. sqlite3_stmt *pReadParent;
  175948. sqlite3_stmt *pWriteParent;
  175949. sqlite3_stmt *pDeleteParent;
  175950. /* Statement for writing to the "aux:" fields, if there are any */
  175951. sqlite3_stmt *pWriteAux;
  175952. RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */
  175953. };
  175954. /* Possible values for Rtree.eCoordType: */
  175955. #define RTREE_COORD_REAL32 0
  175956. #define RTREE_COORD_INT32 1
  175957. /*
  175958. ** If SQLITE_RTREE_INT_ONLY is defined, then this virtual table will
  175959. ** only deal with integer coordinates. No floating point operations
  175960. ** will be done.
  175961. */
  175962. #ifdef SQLITE_RTREE_INT_ONLY
  175963. typedef sqlite3_int64 RtreeDValue; /* High accuracy coordinate */
  175964. typedef int RtreeValue; /* Low accuracy coordinate */
  175965. # define RTREE_ZERO 0
  175966. #else
  175967. typedef double RtreeDValue; /* High accuracy coordinate */
  175968. typedef float RtreeValue; /* Low accuracy coordinate */
  175969. # define RTREE_ZERO 0.0
  175970. #endif
  175971. /*
  175972. ** Set the Rtree.bCorrupt flag
  175973. */
  175974. #ifdef SQLITE_DEBUG
  175975. # define RTREE_IS_CORRUPT(X) ((X)->bCorrupt = 1)
  175976. #else
  175977. # define RTREE_IS_CORRUPT(X)
  175978. #endif
  175979. /*
  175980. ** When doing a search of an r-tree, instances of the following structure
  175981. ** record intermediate results from the tree walk.
  175982. **
  175983. ** The id is always a node-id. For iLevel>=1 the id is the node-id of
  175984. ** the node that the RtreeSearchPoint represents. When iLevel==0, however,
  175985. ** the id is of the parent node and the cell that RtreeSearchPoint
  175986. ** represents is the iCell-th entry in the parent node.
  175987. */
  175988. struct RtreeSearchPoint {
  175989. RtreeDValue rScore; /* The score for this node. Smallest goes first. */
  175990. sqlite3_int64 id; /* Node ID */
  175991. u8 iLevel; /* 0=entries. 1=leaf node. 2+ for higher */
  175992. u8 eWithin; /* PARTLY_WITHIN or FULLY_WITHIN */
  175993. u8 iCell; /* Cell index within the node */
  175994. };
  175995. /*
  175996. ** The minimum number of cells allowed for a node is a third of the
  175997. ** maximum. In Gutman's notation:
  175998. **
  175999. ** m = M/3
  176000. **
  176001. ** If an R*-tree "Reinsert" operation is required, the same number of
  176002. ** cells are removed from the overfull node and reinserted into the tree.
  176003. */
  176004. #define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
  176005. #define RTREE_REINSERT(p) RTREE_MINCELLS(p)
  176006. #define RTREE_MAXCELLS 51
  176007. /*
  176008. ** The smallest possible node-size is (512-64)==448 bytes. And the largest
  176009. ** supported cell size is 48 bytes (8 byte rowid + ten 4 byte coordinates).
  176010. ** Therefore all non-root nodes must contain at least 3 entries. Since
  176011. ** 3^40 is greater than 2^64, an r-tree structure always has a depth of
  176012. ** 40 or less.
  176013. */
  176014. #define RTREE_MAX_DEPTH 40
  176015. /*
  176016. ** Number of entries in the cursor RtreeNode cache. The first entry is
  176017. ** used to cache the RtreeNode for RtreeCursor.sPoint. The remaining
  176018. ** entries cache the RtreeNode for the first elements of the priority queue.
  176019. */
  176020. #define RTREE_CACHE_SZ 5
  176021. /*
  176022. ** An rtree cursor object.
  176023. */
  176024. struct RtreeCursor {
  176025. sqlite3_vtab_cursor base; /* Base class. Must be first */
  176026. u8 atEOF; /* True if at end of search */
  176027. u8 bPoint; /* True if sPoint is valid */
  176028. u8 bAuxValid; /* True if pReadAux is valid */
  176029. int iStrategy; /* Copy of idxNum search parameter */
  176030. int nConstraint; /* Number of entries in aConstraint */
  176031. RtreeConstraint *aConstraint; /* Search constraints. */
  176032. int nPointAlloc; /* Number of slots allocated for aPoint[] */
  176033. int nPoint; /* Number of slots used in aPoint[] */
  176034. int mxLevel; /* iLevel value for root of the tree */
  176035. RtreeSearchPoint *aPoint; /* Priority queue for search points */
  176036. sqlite3_stmt *pReadAux; /* Statement to read aux-data */
  176037. RtreeSearchPoint sPoint; /* Cached next search point */
  176038. RtreeNode *aNode[RTREE_CACHE_SZ]; /* Rtree node cache */
  176039. u32 anQueue[RTREE_MAX_DEPTH+1]; /* Number of queued entries by iLevel */
  176040. };
  176041. /* Return the Rtree of a RtreeCursor */
  176042. #define RTREE_OF_CURSOR(X) ((Rtree*)((X)->base.pVtab))
  176043. /*
  176044. ** A coordinate can be either a floating point number or a integer. All
  176045. ** coordinates within a single R-Tree are always of the same time.
  176046. */
  176047. union RtreeCoord {
  176048. RtreeValue f; /* Floating point value */
  176049. int i; /* Integer value */
  176050. u32 u; /* Unsigned for byte-order conversions */
  176051. };
  176052. /*
  176053. ** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
  176054. ** formatted as a RtreeDValue (double or int64). This macro assumes that local
  176055. ** variable pRtree points to the Rtree structure associated with the
  176056. ** RtreeCoord.
  176057. */
  176058. #ifdef SQLITE_RTREE_INT_ONLY
  176059. # define DCOORD(coord) ((RtreeDValue)coord.i)
  176060. #else
  176061. # define DCOORD(coord) ( \
  176062. (pRtree->eCoordType==RTREE_COORD_REAL32) ? \
  176063. ((double)coord.f) : \
  176064. ((double)coord.i) \
  176065. )
  176066. #endif
  176067. /*
  176068. ** A search constraint.
  176069. */
  176070. struct RtreeConstraint {
  176071. int iCoord; /* Index of constrained coordinate */
  176072. int op; /* Constraining operation */
  176073. union {
  176074. RtreeDValue rValue; /* Constraint value. */
  176075. int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*);
  176076. int (*xQueryFunc)(sqlite3_rtree_query_info*);
  176077. } u;
  176078. sqlite3_rtree_query_info *pInfo; /* xGeom and xQueryFunc argument */
  176079. };
  176080. /* Possible values for RtreeConstraint.op */
  176081. #define RTREE_EQ 0x41 /* A */
  176082. #define RTREE_LE 0x42 /* B */
  176083. #define RTREE_LT 0x43 /* C */
  176084. #define RTREE_GE 0x44 /* D */
  176085. #define RTREE_GT 0x45 /* E */
  176086. #define RTREE_MATCH 0x46 /* F: Old-style sqlite3_rtree_geometry_callback() */
  176087. #define RTREE_QUERY 0x47 /* G: New-style sqlite3_rtree_query_callback() */
  176088. /* Special operators available only on cursors. Needs to be consecutive
  176089. ** with the normal values above, but must be less than RTREE_MATCH. These
  176090. ** are used in the cursor for contraints such as x=NULL (RTREE_FALSE) or
  176091. ** x<'xyz' (RTREE_TRUE) */
  176092. #define RTREE_TRUE 0x3f /* ? */
  176093. #define RTREE_FALSE 0x40 /* @ */
  176094. /*
  176095. ** An rtree structure node.
  176096. */
  176097. struct RtreeNode {
  176098. RtreeNode *pParent; /* Parent node */
  176099. i64 iNode; /* The node number */
  176100. int nRef; /* Number of references to this node */
  176101. int isDirty; /* True if the node needs to be written to disk */
  176102. u8 *zData; /* Content of the node, as should be on disk */
  176103. RtreeNode *pNext; /* Next node in this hash collision chain */
  176104. };
  176105. /* Return the number of cells in a node */
  176106. #define NCELL(pNode) readInt16(&(pNode)->zData[2])
  176107. /*
  176108. ** A single cell from a node, deserialized
  176109. */
  176110. struct RtreeCell {
  176111. i64 iRowid; /* Node or entry ID */
  176112. RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2]; /* Bounding box coordinates */
  176113. };
  176114. /*
  176115. ** This object becomes the sqlite3_user_data() for the SQL functions
  176116. ** that are created by sqlite3_rtree_geometry_callback() and
  176117. ** sqlite3_rtree_query_callback() and which appear on the right of MATCH
  176118. ** operators in order to constrain a search.
  176119. **
  176120. ** xGeom and xQueryFunc are the callback functions. Exactly one of
  176121. ** xGeom and xQueryFunc fields is non-NULL, depending on whether the
  176122. ** SQL function was created using sqlite3_rtree_geometry_callback() or
  176123. ** sqlite3_rtree_query_callback().
  176124. **
  176125. ** This object is deleted automatically by the destructor mechanism in
  176126. ** sqlite3_create_function_v2().
  176127. */
  176128. struct RtreeGeomCallback {
  176129. int (*xGeom)(sqlite3_rtree_geometry*, int, RtreeDValue*, int*);
  176130. int (*xQueryFunc)(sqlite3_rtree_query_info*);
  176131. void (*xDestructor)(void*);
  176132. void *pContext;
  176133. };
  176134. /*
  176135. ** An instance of this structure (in the form of a BLOB) is returned by
  176136. ** the SQL functions that sqlite3_rtree_geometry_callback() and
  176137. ** sqlite3_rtree_query_callback() create, and is read as the right-hand
  176138. ** operand to the MATCH operator of an R-Tree.
  176139. */
  176140. struct RtreeMatchArg {
  176141. u32 iSize; /* Size of this object */
  176142. RtreeGeomCallback cb; /* Info about the callback functions */
  176143. int nParam; /* Number of parameters to the SQL function */
  176144. sqlite3_value **apSqlParam; /* Original SQL parameter values */
  176145. RtreeDValue aParam[1]; /* Values for parameters to the SQL function */
  176146. };
  176147. #ifndef MAX
  176148. # define MAX(x,y) ((x) < (y) ? (y) : (x))
  176149. #endif
  176150. #ifndef MIN
  176151. # define MIN(x,y) ((x) > (y) ? (y) : (x))
  176152. #endif
  176153. /* What version of GCC is being used. 0 means GCC is not being used .
  176154. ** Note that the GCC_VERSION macro will also be set correctly when using
  176155. ** clang, since clang works hard to be gcc compatible. So the gcc
  176156. ** optimizations will also work when compiling with clang.
  176157. */
  176158. #ifndef GCC_VERSION
  176159. #if defined(__GNUC__) && !defined(SQLITE_DISABLE_INTRINSIC)
  176160. # define GCC_VERSION (__GNUC__*1000000+__GNUC_MINOR__*1000+__GNUC_PATCHLEVEL__)
  176161. #else
  176162. # define GCC_VERSION 0
  176163. #endif
  176164. #endif
  176165. /* The testcase() macro should already be defined in the amalgamation. If
  176166. ** it is not, make it a no-op.
  176167. */
  176168. #ifndef SQLITE_AMALGAMATION
  176169. # define testcase(X)
  176170. #endif
  176171. /*
  176172. ** Macros to determine whether the machine is big or little endian,
  176173. ** and whether or not that determination is run-time or compile-time.
  176174. **
  176175. ** For best performance, an attempt is made to guess at the byte-order
  176176. ** using C-preprocessor macros. If that is unsuccessful, or if
  176177. ** -DSQLITE_RUNTIME_BYTEORDER=1 is set, then byte-order is determined
  176178. ** at run-time.
  176179. */
  176180. #ifndef SQLITE_BYTEORDER
  176181. #if defined(i386) || defined(__i386__) || defined(_M_IX86) || \
  176182. defined(__x86_64) || defined(__x86_64__) || defined(_M_X64) || \
  176183. defined(_M_AMD64) || defined(_M_ARM) || defined(__x86) || \
  176184. defined(__arm__)
  176185. # define SQLITE_BYTEORDER 1234
  176186. #elif defined(sparc) || defined(__ppc__)
  176187. # define SQLITE_BYTEORDER 4321
  176188. #else
  176189. # define SQLITE_BYTEORDER 0 /* 0 means "unknown at compile-time" */
  176190. #endif
  176191. #endif
  176192. /* What version of MSVC is being used. 0 means MSVC is not being used */
  176193. #ifndef MSVC_VERSION
  176194. #if defined(_MSC_VER) && !defined(SQLITE_DISABLE_INTRINSIC)
  176195. # define MSVC_VERSION _MSC_VER
  176196. #else
  176197. # define MSVC_VERSION 0
  176198. #endif
  176199. #endif
  176200. /*
  176201. ** Functions to deserialize a 16 bit integer, 32 bit real number and
  176202. ** 64 bit integer. The deserialized value is returned.
  176203. */
  176204. static int readInt16(u8 *p){
  176205. return (p[0]<<8) + p[1];
  176206. }
  176207. static void readCoord(u8 *p, RtreeCoord *pCoord){
  176208. assert( ((((char*)p) - (char*)0)&3)==0 ); /* p is always 4-byte aligned */
  176209. #if SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
  176210. pCoord->u = _byteswap_ulong(*(u32*)p);
  176211. #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
  176212. pCoord->u = __builtin_bswap32(*(u32*)p);
  176213. #elif SQLITE_BYTEORDER==4321
  176214. pCoord->u = *(u32*)p;
  176215. #else
  176216. pCoord->u = (
  176217. (((u32)p[0]) << 24) +
  176218. (((u32)p[1]) << 16) +
  176219. (((u32)p[2]) << 8) +
  176220. (((u32)p[3]) << 0)
  176221. );
  176222. #endif
  176223. }
  176224. static i64 readInt64(u8 *p){
  176225. #if SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
  176226. u64 x;
  176227. memcpy(&x, p, 8);
  176228. return (i64)_byteswap_uint64(x);
  176229. #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
  176230. u64 x;
  176231. memcpy(&x, p, 8);
  176232. return (i64)__builtin_bswap64(x);
  176233. #elif SQLITE_BYTEORDER==4321
  176234. i64 x;
  176235. memcpy(&x, p, 8);
  176236. return x;
  176237. #else
  176238. return (i64)(
  176239. (((u64)p[0]) << 56) +
  176240. (((u64)p[1]) << 48) +
  176241. (((u64)p[2]) << 40) +
  176242. (((u64)p[3]) << 32) +
  176243. (((u64)p[4]) << 24) +
  176244. (((u64)p[5]) << 16) +
  176245. (((u64)p[6]) << 8) +
  176246. (((u64)p[7]) << 0)
  176247. );
  176248. #endif
  176249. }
  176250. /*
  176251. ** Functions to serialize a 16 bit integer, 32 bit real number and
  176252. ** 64 bit integer. The value returned is the number of bytes written
  176253. ** to the argument buffer (always 2, 4 and 8 respectively).
  176254. */
  176255. static void writeInt16(u8 *p, int i){
  176256. p[0] = (i>> 8)&0xFF;
  176257. p[1] = (i>> 0)&0xFF;
  176258. }
  176259. static int writeCoord(u8 *p, RtreeCoord *pCoord){
  176260. u32 i;
  176261. assert( ((((char*)p) - (char*)0)&3)==0 ); /* p is always 4-byte aligned */
  176262. assert( sizeof(RtreeCoord)==4 );
  176263. assert( sizeof(u32)==4 );
  176264. #if SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
  176265. i = __builtin_bswap32(pCoord->u);
  176266. memcpy(p, &i, 4);
  176267. #elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
  176268. i = _byteswap_ulong(pCoord->u);
  176269. memcpy(p, &i, 4);
  176270. #elif SQLITE_BYTEORDER==4321
  176271. i = pCoord->u;
  176272. memcpy(p, &i, 4);
  176273. #else
  176274. i = pCoord->u;
  176275. p[0] = (i>>24)&0xFF;
  176276. p[1] = (i>>16)&0xFF;
  176277. p[2] = (i>> 8)&0xFF;
  176278. p[3] = (i>> 0)&0xFF;
  176279. #endif
  176280. return 4;
  176281. }
  176282. static int writeInt64(u8 *p, i64 i){
  176283. #if SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
  176284. i = (i64)__builtin_bswap64((u64)i);
  176285. memcpy(p, &i, 8);
  176286. #elif SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
  176287. i = (i64)_byteswap_uint64((u64)i);
  176288. memcpy(p, &i, 8);
  176289. #elif SQLITE_BYTEORDER==4321
  176290. memcpy(p, &i, 8);
  176291. #else
  176292. p[0] = (i>>56)&0xFF;
  176293. p[1] = (i>>48)&0xFF;
  176294. p[2] = (i>>40)&0xFF;
  176295. p[3] = (i>>32)&0xFF;
  176296. p[4] = (i>>24)&0xFF;
  176297. p[5] = (i>>16)&0xFF;
  176298. p[6] = (i>> 8)&0xFF;
  176299. p[7] = (i>> 0)&0xFF;
  176300. #endif
  176301. return 8;
  176302. }
  176303. /*
  176304. ** Increment the reference count of node p.
  176305. */
  176306. static void nodeReference(RtreeNode *p){
  176307. if( p ){
  176308. assert( p->nRef>0 );
  176309. p->nRef++;
  176310. }
  176311. }
  176312. /*
  176313. ** Clear the content of node p (set all bytes to 0x00).
  176314. */
  176315. static void nodeZero(Rtree *pRtree, RtreeNode *p){
  176316. memset(&p->zData[2], 0, pRtree->iNodeSize-2);
  176317. p->isDirty = 1;
  176318. }
  176319. /*
  176320. ** Given a node number iNode, return the corresponding key to use
  176321. ** in the Rtree.aHash table.
  176322. */
  176323. static unsigned int nodeHash(i64 iNode){
  176324. return ((unsigned)iNode) % HASHSIZE;
  176325. }
  176326. /*
  176327. ** Search the node hash table for node iNode. If found, return a pointer
  176328. ** to it. Otherwise, return 0.
  176329. */
  176330. static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
  176331. RtreeNode *p;
  176332. for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
  176333. return p;
  176334. }
  176335. /*
  176336. ** Add node pNode to the node hash table.
  176337. */
  176338. static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
  176339. int iHash;
  176340. assert( pNode->pNext==0 );
  176341. iHash = nodeHash(pNode->iNode);
  176342. pNode->pNext = pRtree->aHash[iHash];
  176343. pRtree->aHash[iHash] = pNode;
  176344. }
  176345. /*
  176346. ** Remove node pNode from the node hash table.
  176347. */
  176348. static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
  176349. RtreeNode **pp;
  176350. if( pNode->iNode!=0 ){
  176351. pp = &pRtree->aHash[nodeHash(pNode->iNode)];
  176352. for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
  176353. *pp = pNode->pNext;
  176354. pNode->pNext = 0;
  176355. }
  176356. }
  176357. /*
  176358. ** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
  176359. ** indicating that node has not yet been assigned a node number. It is
  176360. ** assigned a node number when nodeWrite() is called to write the
  176361. ** node contents out to the database.
  176362. */
  176363. static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent){
  176364. RtreeNode *pNode;
  176365. pNode = (RtreeNode *)sqlite3_malloc64(sizeof(RtreeNode) + pRtree->iNodeSize);
  176366. if( pNode ){
  176367. memset(pNode, 0, sizeof(RtreeNode) + pRtree->iNodeSize);
  176368. pNode->zData = (u8 *)&pNode[1];
  176369. pNode->nRef = 1;
  176370. pRtree->nNodeRef++;
  176371. pNode->pParent = pParent;
  176372. pNode->isDirty = 1;
  176373. nodeReference(pParent);
  176374. }
  176375. return pNode;
  176376. }
  176377. /*
  176378. ** Clear the Rtree.pNodeBlob object
  176379. */
  176380. static void nodeBlobReset(Rtree *pRtree){
  176381. if( pRtree->pNodeBlob && pRtree->inWrTrans==0 && pRtree->nCursor==0 ){
  176382. sqlite3_blob *pBlob = pRtree->pNodeBlob;
  176383. pRtree->pNodeBlob = 0;
  176384. sqlite3_blob_close(pBlob);
  176385. }
  176386. }
  176387. /*
  176388. ** Check to see if pNode is the same as pParent or any of the parents
  176389. ** of pParent.
  176390. */
  176391. static int nodeInParentChain(const RtreeNode *pNode, const RtreeNode *pParent){
  176392. do{
  176393. if( pNode==pParent ) return 1;
  176394. pParent = pParent->pParent;
  176395. }while( pParent );
  176396. return 0;
  176397. }
  176398. /*
  176399. ** Obtain a reference to an r-tree node.
  176400. */
  176401. static int nodeAcquire(
  176402. Rtree *pRtree, /* R-tree structure */
  176403. i64 iNode, /* Node number to load */
  176404. RtreeNode *pParent, /* Either the parent node or NULL */
  176405. RtreeNode **ppNode /* OUT: Acquired node */
  176406. ){
  176407. int rc = SQLITE_OK;
  176408. RtreeNode *pNode = 0;
  176409. /* Check if the requested node is already in the hash table. If so,
  176410. ** increase its reference count and return it.
  176411. */
  176412. if( (pNode = nodeHashLookup(pRtree, iNode))!=0 ){
  176413. if( pParent && !pNode->pParent ){
  176414. if( nodeInParentChain(pNode, pParent) ){
  176415. RTREE_IS_CORRUPT(pRtree);
  176416. return SQLITE_CORRUPT_VTAB;
  176417. }
  176418. pParent->nRef++;
  176419. pNode->pParent = pParent;
  176420. }else if( pParent && pNode->pParent && pParent!=pNode->pParent ){
  176421. RTREE_IS_CORRUPT(pRtree);
  176422. return SQLITE_CORRUPT_VTAB;
  176423. }
  176424. pNode->nRef++;
  176425. *ppNode = pNode;
  176426. return SQLITE_OK;
  176427. }
  176428. if( pRtree->pNodeBlob ){
  176429. sqlite3_blob *pBlob = pRtree->pNodeBlob;
  176430. pRtree->pNodeBlob = 0;
  176431. rc = sqlite3_blob_reopen(pBlob, iNode);
  176432. pRtree->pNodeBlob = pBlob;
  176433. if( rc ){
  176434. nodeBlobReset(pRtree);
  176435. if( rc==SQLITE_NOMEM ) return SQLITE_NOMEM;
  176436. }
  176437. }
  176438. if( pRtree->pNodeBlob==0 ){
  176439. char *zTab = sqlite3_mprintf("%s_node", pRtree->zName);
  176440. if( zTab==0 ) return SQLITE_NOMEM;
  176441. rc = sqlite3_blob_open(pRtree->db, pRtree->zDb, zTab, "data", iNode, 0,
  176442. &pRtree->pNodeBlob);
  176443. sqlite3_free(zTab);
  176444. }
  176445. if( rc ){
  176446. nodeBlobReset(pRtree);
  176447. *ppNode = 0;
  176448. /* If unable to open an sqlite3_blob on the desired row, that can only
  176449. ** be because the shadow tables hold erroneous data. */
  176450. if( rc==SQLITE_ERROR ){
  176451. rc = SQLITE_CORRUPT_VTAB;
  176452. RTREE_IS_CORRUPT(pRtree);
  176453. }
  176454. }else if( pRtree->iNodeSize==sqlite3_blob_bytes(pRtree->pNodeBlob) ){
  176455. pNode = (RtreeNode *)sqlite3_malloc64(sizeof(RtreeNode)+pRtree->iNodeSize);
  176456. if( !pNode ){
  176457. rc = SQLITE_NOMEM;
  176458. }else{
  176459. pNode->pParent = pParent;
  176460. pNode->zData = (u8 *)&pNode[1];
  176461. pNode->nRef = 1;
  176462. pRtree->nNodeRef++;
  176463. pNode->iNode = iNode;
  176464. pNode->isDirty = 0;
  176465. pNode->pNext = 0;
  176466. rc = sqlite3_blob_read(pRtree->pNodeBlob, pNode->zData,
  176467. pRtree->iNodeSize, 0);
  176468. }
  176469. }
  176470. /* If the root node was just loaded, set pRtree->iDepth to the height
  176471. ** of the r-tree structure. A height of zero means all data is stored on
  176472. ** the root node. A height of one means the children of the root node
  176473. ** are the leaves, and so on. If the depth as specified on the root node
  176474. ** is greater than RTREE_MAX_DEPTH, the r-tree structure must be corrupt.
  176475. */
  176476. if( pNode && iNode==1 ){
  176477. pRtree->iDepth = readInt16(pNode->zData);
  176478. if( pRtree->iDepth>RTREE_MAX_DEPTH ){
  176479. rc = SQLITE_CORRUPT_VTAB;
  176480. RTREE_IS_CORRUPT(pRtree);
  176481. }
  176482. }
  176483. /* If no error has occurred so far, check if the "number of entries"
  176484. ** field on the node is too large. If so, set the return code to
  176485. ** SQLITE_CORRUPT_VTAB.
  176486. */
  176487. if( pNode && rc==SQLITE_OK ){
  176488. if( NCELL(pNode)>((pRtree->iNodeSize-4)/pRtree->nBytesPerCell) ){
  176489. rc = SQLITE_CORRUPT_VTAB;
  176490. RTREE_IS_CORRUPT(pRtree);
  176491. }
  176492. }
  176493. if( rc==SQLITE_OK ){
  176494. if( pNode!=0 ){
  176495. nodeReference(pParent);
  176496. nodeHashInsert(pRtree, pNode);
  176497. }else{
  176498. rc = SQLITE_CORRUPT_VTAB;
  176499. RTREE_IS_CORRUPT(pRtree);
  176500. }
  176501. *ppNode = pNode;
  176502. }else{
  176503. if( pNode ){
  176504. pRtree->nNodeRef--;
  176505. sqlite3_free(pNode);
  176506. }
  176507. *ppNode = 0;
  176508. }
  176509. return rc;
  176510. }
  176511. /*
  176512. ** Overwrite cell iCell of node pNode with the contents of pCell.
  176513. */
  176514. static void nodeOverwriteCell(
  176515. Rtree *pRtree, /* The overall R-Tree */
  176516. RtreeNode *pNode, /* The node into which the cell is to be written */
  176517. RtreeCell *pCell, /* The cell to write */
  176518. int iCell /* Index into pNode into which pCell is written */
  176519. ){
  176520. int ii;
  176521. u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
  176522. p += writeInt64(p, pCell->iRowid);
  176523. for(ii=0; ii<pRtree->nDim2; ii++){
  176524. p += writeCoord(p, &pCell->aCoord[ii]);
  176525. }
  176526. pNode->isDirty = 1;
  176527. }
  176528. /*
  176529. ** Remove the cell with index iCell from node pNode.
  176530. */
  176531. static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
  176532. u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
  176533. u8 *pSrc = &pDst[pRtree->nBytesPerCell];
  176534. int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
  176535. memmove(pDst, pSrc, nByte);
  176536. writeInt16(&pNode->zData[2], NCELL(pNode)-1);
  176537. pNode->isDirty = 1;
  176538. }
  176539. /*
  176540. ** Insert the contents of cell pCell into node pNode. If the insert
  176541. ** is successful, return SQLITE_OK.
  176542. **
  176543. ** If there is not enough free space in pNode, return SQLITE_FULL.
  176544. */
  176545. static int nodeInsertCell(
  176546. Rtree *pRtree, /* The overall R-Tree */
  176547. RtreeNode *pNode, /* Write new cell into this node */
  176548. RtreeCell *pCell /* The cell to be inserted */
  176549. ){
  176550. int nCell; /* Current number of cells in pNode */
  176551. int nMaxCell; /* Maximum number of cells for pNode */
  176552. nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
  176553. nCell = NCELL(pNode);
  176554. assert( nCell<=nMaxCell );
  176555. if( nCell<nMaxCell ){
  176556. nodeOverwriteCell(pRtree, pNode, pCell, nCell);
  176557. writeInt16(&pNode->zData[2], nCell+1);
  176558. pNode->isDirty = 1;
  176559. }
  176560. return (nCell==nMaxCell);
  176561. }
  176562. /*
  176563. ** If the node is dirty, write it out to the database.
  176564. */
  176565. static int nodeWrite(Rtree *pRtree, RtreeNode *pNode){
  176566. int rc = SQLITE_OK;
  176567. if( pNode->isDirty ){
  176568. sqlite3_stmt *p = pRtree->pWriteNode;
  176569. if( pNode->iNode ){
  176570. sqlite3_bind_int64(p, 1, pNode->iNode);
  176571. }else{
  176572. sqlite3_bind_null(p, 1);
  176573. }
  176574. sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
  176575. sqlite3_step(p);
  176576. pNode->isDirty = 0;
  176577. rc = sqlite3_reset(p);
  176578. sqlite3_bind_null(p, 2);
  176579. if( pNode->iNode==0 && rc==SQLITE_OK ){
  176580. pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
  176581. nodeHashInsert(pRtree, pNode);
  176582. }
  176583. }
  176584. return rc;
  176585. }
  176586. /*
  176587. ** Release a reference to a node. If the node is dirty and the reference
  176588. ** count drops to zero, the node data is written to the database.
  176589. */
  176590. static int nodeRelease(Rtree *pRtree, RtreeNode *pNode){
  176591. int rc = SQLITE_OK;
  176592. if( pNode ){
  176593. assert( pNode->nRef>0 );
  176594. assert( pRtree->nNodeRef>0 );
  176595. pNode->nRef--;
  176596. if( pNode->nRef==0 ){
  176597. pRtree->nNodeRef--;
  176598. if( pNode->iNode==1 ){
  176599. pRtree->iDepth = -1;
  176600. }
  176601. if( pNode->pParent ){
  176602. rc = nodeRelease(pRtree, pNode->pParent);
  176603. }
  176604. if( rc==SQLITE_OK ){
  176605. rc = nodeWrite(pRtree, pNode);
  176606. }
  176607. nodeHashDelete(pRtree, pNode);
  176608. sqlite3_free(pNode);
  176609. }
  176610. }
  176611. return rc;
  176612. }
  176613. /*
  176614. ** Return the 64-bit integer value associated with cell iCell of
  176615. ** node pNode. If pNode is a leaf node, this is a rowid. If it is
  176616. ** an internal node, then the 64-bit integer is a child page number.
  176617. */
  176618. static i64 nodeGetRowid(
  176619. Rtree *pRtree, /* The overall R-Tree */
  176620. RtreeNode *pNode, /* The node from which to extract the ID */
  176621. int iCell /* The cell index from which to extract the ID */
  176622. ){
  176623. assert( iCell<NCELL(pNode) );
  176624. return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
  176625. }
  176626. /*
  176627. ** Return coordinate iCoord from cell iCell in node pNode.
  176628. */
  176629. static void nodeGetCoord(
  176630. Rtree *pRtree, /* The overall R-Tree */
  176631. RtreeNode *pNode, /* The node from which to extract a coordinate */
  176632. int iCell, /* The index of the cell within the node */
  176633. int iCoord, /* Which coordinate to extract */
  176634. RtreeCoord *pCoord /* OUT: Space to write result to */
  176635. ){
  176636. readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
  176637. }
  176638. /*
  176639. ** Deserialize cell iCell of node pNode. Populate the structure pointed
  176640. ** to by pCell with the results.
  176641. */
  176642. static void nodeGetCell(
  176643. Rtree *pRtree, /* The overall R-Tree */
  176644. RtreeNode *pNode, /* The node containing the cell to be read */
  176645. int iCell, /* Index of the cell within the node */
  176646. RtreeCell *pCell /* OUT: Write the cell contents here */
  176647. ){
  176648. u8 *pData;
  176649. RtreeCoord *pCoord;
  176650. int ii = 0;
  176651. pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
  176652. pData = pNode->zData + (12 + pRtree->nBytesPerCell*iCell);
  176653. pCoord = pCell->aCoord;
  176654. do{
  176655. readCoord(pData, &pCoord[ii]);
  176656. readCoord(pData+4, &pCoord[ii+1]);
  176657. pData += 8;
  176658. ii += 2;
  176659. }while( ii<pRtree->nDim2 );
  176660. }
  176661. /* Forward declaration for the function that does the work of
  176662. ** the virtual table module xCreate() and xConnect() methods.
  176663. */
  176664. static int rtreeInit(
  176665. sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int
  176666. );
  176667. /*
  176668. ** Rtree virtual table module xCreate method.
  176669. */
  176670. static int rtreeCreate(
  176671. sqlite3 *db,
  176672. void *pAux,
  176673. int argc, const char *const*argv,
  176674. sqlite3_vtab **ppVtab,
  176675. char **pzErr
  176676. ){
  176677. return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
  176678. }
  176679. /*
  176680. ** Rtree virtual table module xConnect method.
  176681. */
  176682. static int rtreeConnect(
  176683. sqlite3 *db,
  176684. void *pAux,
  176685. int argc, const char *const*argv,
  176686. sqlite3_vtab **ppVtab,
  176687. char **pzErr
  176688. ){
  176689. return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
  176690. }
  176691. /*
  176692. ** Increment the r-tree reference count.
  176693. */
  176694. static void rtreeReference(Rtree *pRtree){
  176695. pRtree->nBusy++;
  176696. }
  176697. /*
  176698. ** Decrement the r-tree reference count. When the reference count reaches
  176699. ** zero the structure is deleted.
  176700. */
  176701. static void rtreeRelease(Rtree *pRtree){
  176702. pRtree->nBusy--;
  176703. if( pRtree->nBusy==0 ){
  176704. pRtree->inWrTrans = 0;
  176705. assert( pRtree->nCursor==0 );
  176706. nodeBlobReset(pRtree);
  176707. assert( pRtree->nNodeRef==0 || pRtree->bCorrupt );
  176708. sqlite3_finalize(pRtree->pWriteNode);
  176709. sqlite3_finalize(pRtree->pDeleteNode);
  176710. sqlite3_finalize(pRtree->pReadRowid);
  176711. sqlite3_finalize(pRtree->pWriteRowid);
  176712. sqlite3_finalize(pRtree->pDeleteRowid);
  176713. sqlite3_finalize(pRtree->pReadParent);
  176714. sqlite3_finalize(pRtree->pWriteParent);
  176715. sqlite3_finalize(pRtree->pDeleteParent);
  176716. sqlite3_finalize(pRtree->pWriteAux);
  176717. sqlite3_free(pRtree->zReadAuxSql);
  176718. sqlite3_free(pRtree);
  176719. }
  176720. }
  176721. /*
  176722. ** Rtree virtual table module xDisconnect method.
  176723. */
  176724. static int rtreeDisconnect(sqlite3_vtab *pVtab){
  176725. rtreeRelease((Rtree *)pVtab);
  176726. return SQLITE_OK;
  176727. }
  176728. /*
  176729. ** Rtree virtual table module xDestroy method.
  176730. */
  176731. static int rtreeDestroy(sqlite3_vtab *pVtab){
  176732. Rtree *pRtree = (Rtree *)pVtab;
  176733. int rc;
  176734. char *zCreate = sqlite3_mprintf(
  176735. "DROP TABLE '%q'.'%q_node';"
  176736. "DROP TABLE '%q'.'%q_rowid';"
  176737. "DROP TABLE '%q'.'%q_parent';",
  176738. pRtree->zDb, pRtree->zName,
  176739. pRtree->zDb, pRtree->zName,
  176740. pRtree->zDb, pRtree->zName
  176741. );
  176742. if( !zCreate ){
  176743. rc = SQLITE_NOMEM;
  176744. }else{
  176745. nodeBlobReset(pRtree);
  176746. rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
  176747. sqlite3_free(zCreate);
  176748. }
  176749. if( rc==SQLITE_OK ){
  176750. rtreeRelease(pRtree);
  176751. }
  176752. return rc;
  176753. }
  176754. /*
  176755. ** Rtree virtual table module xOpen method.
  176756. */
  176757. static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
  176758. int rc = SQLITE_NOMEM;
  176759. Rtree *pRtree = (Rtree *)pVTab;
  176760. RtreeCursor *pCsr;
  176761. pCsr = (RtreeCursor *)sqlite3_malloc64(sizeof(RtreeCursor));
  176762. if( pCsr ){
  176763. memset(pCsr, 0, sizeof(RtreeCursor));
  176764. pCsr->base.pVtab = pVTab;
  176765. rc = SQLITE_OK;
  176766. pRtree->nCursor++;
  176767. }
  176768. *ppCursor = (sqlite3_vtab_cursor *)pCsr;
  176769. return rc;
  176770. }
  176771. /*
  176772. ** Reset a cursor back to its initial state.
  176773. */
  176774. static void resetCursor(RtreeCursor *pCsr){
  176775. Rtree *pRtree = (Rtree *)(pCsr->base.pVtab);
  176776. int ii;
  176777. sqlite3_stmt *pStmt;
  176778. if( pCsr->aConstraint ){
  176779. int i; /* Used to iterate through constraint array */
  176780. for(i=0; i<pCsr->nConstraint; i++){
  176781. sqlite3_rtree_query_info *pInfo = pCsr->aConstraint[i].pInfo;
  176782. if( pInfo ){
  176783. if( pInfo->xDelUser ) pInfo->xDelUser(pInfo->pUser);
  176784. sqlite3_free(pInfo);
  176785. }
  176786. }
  176787. sqlite3_free(pCsr->aConstraint);
  176788. pCsr->aConstraint = 0;
  176789. }
  176790. for(ii=0; ii<RTREE_CACHE_SZ; ii++) nodeRelease(pRtree, pCsr->aNode[ii]);
  176791. sqlite3_free(pCsr->aPoint);
  176792. pStmt = pCsr->pReadAux;
  176793. memset(pCsr, 0, sizeof(RtreeCursor));
  176794. pCsr->base.pVtab = (sqlite3_vtab*)pRtree;
  176795. pCsr->pReadAux = pStmt;
  176796. }
  176797. /*
  176798. ** Rtree virtual table module xClose method.
  176799. */
  176800. static int rtreeClose(sqlite3_vtab_cursor *cur){
  176801. Rtree *pRtree = (Rtree *)(cur->pVtab);
  176802. RtreeCursor *pCsr = (RtreeCursor *)cur;
  176803. assert( pRtree->nCursor>0 );
  176804. resetCursor(pCsr);
  176805. sqlite3_finalize(pCsr->pReadAux);
  176806. sqlite3_free(pCsr);
  176807. pRtree->nCursor--;
  176808. nodeBlobReset(pRtree);
  176809. return SQLITE_OK;
  176810. }
  176811. /*
  176812. ** Rtree virtual table module xEof method.
  176813. **
  176814. ** Return non-zero if the cursor does not currently point to a valid
  176815. ** record (i.e if the scan has finished), or zero otherwise.
  176816. */
  176817. static int rtreeEof(sqlite3_vtab_cursor *cur){
  176818. RtreeCursor *pCsr = (RtreeCursor *)cur;
  176819. return pCsr->atEOF;
  176820. }
  176821. /*
  176822. ** Convert raw bits from the on-disk RTree record into a coordinate value.
  176823. ** The on-disk format is big-endian and needs to be converted for little-
  176824. ** endian platforms. The on-disk record stores integer coordinates if
  176825. ** eInt is true and it stores 32-bit floating point records if eInt is
  176826. ** false. a[] is the four bytes of the on-disk record to be decoded.
  176827. ** Store the results in "r".
  176828. **
  176829. ** There are five versions of this macro. The last one is generic. The
  176830. ** other four are various architectures-specific optimizations.
  176831. */
  176832. #if SQLITE_BYTEORDER==1234 && MSVC_VERSION>=1300
  176833. #define RTREE_DECODE_COORD(eInt, a, r) { \
  176834. RtreeCoord c; /* Coordinate decoded */ \
  176835. c.u = _byteswap_ulong(*(u32*)a); \
  176836. r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
  176837. }
  176838. #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4003000
  176839. #define RTREE_DECODE_COORD(eInt, a, r) { \
  176840. RtreeCoord c; /* Coordinate decoded */ \
  176841. c.u = __builtin_bswap32(*(u32*)a); \
  176842. r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
  176843. }
  176844. #elif SQLITE_BYTEORDER==1234
  176845. #define RTREE_DECODE_COORD(eInt, a, r) { \
  176846. RtreeCoord c; /* Coordinate decoded */ \
  176847. memcpy(&c.u,a,4); \
  176848. c.u = ((c.u>>24)&0xff)|((c.u>>8)&0xff00)| \
  176849. ((c.u&0xff)<<24)|((c.u&0xff00)<<8); \
  176850. r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
  176851. }
  176852. #elif SQLITE_BYTEORDER==4321
  176853. #define RTREE_DECODE_COORD(eInt, a, r) { \
  176854. RtreeCoord c; /* Coordinate decoded */ \
  176855. memcpy(&c.u,a,4); \
  176856. r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
  176857. }
  176858. #else
  176859. #define RTREE_DECODE_COORD(eInt, a, r) { \
  176860. RtreeCoord c; /* Coordinate decoded */ \
  176861. c.u = ((u32)a[0]<<24) + ((u32)a[1]<<16) \
  176862. +((u32)a[2]<<8) + a[3]; \
  176863. r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
  176864. }
  176865. #endif
  176866. /*
  176867. ** Check the RTree node or entry given by pCellData and p against the MATCH
  176868. ** constraint pConstraint.
  176869. */
  176870. static int rtreeCallbackConstraint(
  176871. RtreeConstraint *pConstraint, /* The constraint to test */
  176872. int eInt, /* True if RTree holding integer coordinates */
  176873. u8 *pCellData, /* Raw cell content */
  176874. RtreeSearchPoint *pSearch, /* Container of this cell */
  176875. sqlite3_rtree_dbl *prScore, /* OUT: score for the cell */
  176876. int *peWithin /* OUT: visibility of the cell */
  176877. ){
  176878. sqlite3_rtree_query_info *pInfo = pConstraint->pInfo; /* Callback info */
  176879. int nCoord = pInfo->nCoord; /* No. of coordinates */
  176880. int rc; /* Callback return code */
  176881. RtreeCoord c; /* Translator union */
  176882. sqlite3_rtree_dbl aCoord[RTREE_MAX_DIMENSIONS*2]; /* Decoded coordinates */
  176883. assert( pConstraint->op==RTREE_MATCH || pConstraint->op==RTREE_QUERY );
  176884. assert( nCoord==2 || nCoord==4 || nCoord==6 || nCoord==8 || nCoord==10 );
  176885. if( pConstraint->op==RTREE_QUERY && pSearch->iLevel==1 ){
  176886. pInfo->iRowid = readInt64(pCellData);
  176887. }
  176888. pCellData += 8;
  176889. #ifndef SQLITE_RTREE_INT_ONLY
  176890. if( eInt==0 ){
  176891. switch( nCoord ){
  176892. case 10: readCoord(pCellData+36, &c); aCoord[9] = c.f;
  176893. readCoord(pCellData+32, &c); aCoord[8] = c.f;
  176894. case 8: readCoord(pCellData+28, &c); aCoord[7] = c.f;
  176895. readCoord(pCellData+24, &c); aCoord[6] = c.f;
  176896. case 6: readCoord(pCellData+20, &c); aCoord[5] = c.f;
  176897. readCoord(pCellData+16, &c); aCoord[4] = c.f;
  176898. case 4: readCoord(pCellData+12, &c); aCoord[3] = c.f;
  176899. readCoord(pCellData+8, &c); aCoord[2] = c.f;
  176900. default: readCoord(pCellData+4, &c); aCoord[1] = c.f;
  176901. readCoord(pCellData, &c); aCoord[0] = c.f;
  176902. }
  176903. }else
  176904. #endif
  176905. {
  176906. switch( nCoord ){
  176907. case 10: readCoord(pCellData+36, &c); aCoord[9] = c.i;
  176908. readCoord(pCellData+32, &c); aCoord[8] = c.i;
  176909. case 8: readCoord(pCellData+28, &c); aCoord[7] = c.i;
  176910. readCoord(pCellData+24, &c); aCoord[6] = c.i;
  176911. case 6: readCoord(pCellData+20, &c); aCoord[5] = c.i;
  176912. readCoord(pCellData+16, &c); aCoord[4] = c.i;
  176913. case 4: readCoord(pCellData+12, &c); aCoord[3] = c.i;
  176914. readCoord(pCellData+8, &c); aCoord[2] = c.i;
  176915. default: readCoord(pCellData+4, &c); aCoord[1] = c.i;
  176916. readCoord(pCellData, &c); aCoord[0] = c.i;
  176917. }
  176918. }
  176919. if( pConstraint->op==RTREE_MATCH ){
  176920. int eWithin = 0;
  176921. rc = pConstraint->u.xGeom((sqlite3_rtree_geometry*)pInfo,
  176922. nCoord, aCoord, &eWithin);
  176923. if( eWithin==0 ) *peWithin = NOT_WITHIN;
  176924. *prScore = RTREE_ZERO;
  176925. }else{
  176926. pInfo->aCoord = aCoord;
  176927. pInfo->iLevel = pSearch->iLevel - 1;
  176928. pInfo->rScore = pInfo->rParentScore = pSearch->rScore;
  176929. pInfo->eWithin = pInfo->eParentWithin = pSearch->eWithin;
  176930. rc = pConstraint->u.xQueryFunc(pInfo);
  176931. if( pInfo->eWithin<*peWithin ) *peWithin = pInfo->eWithin;
  176932. if( pInfo->rScore<*prScore || *prScore<RTREE_ZERO ){
  176933. *prScore = pInfo->rScore;
  176934. }
  176935. }
  176936. return rc;
  176937. }
  176938. /*
  176939. ** Check the internal RTree node given by pCellData against constraint p.
  176940. ** If this constraint cannot be satisfied by any child within the node,
  176941. ** set *peWithin to NOT_WITHIN.
  176942. */
  176943. static void rtreeNonleafConstraint(
  176944. RtreeConstraint *p, /* The constraint to test */
  176945. int eInt, /* True if RTree holds integer coordinates */
  176946. u8 *pCellData, /* Raw cell content as appears on disk */
  176947. int *peWithin /* Adjust downward, as appropriate */
  176948. ){
  176949. sqlite3_rtree_dbl val; /* Coordinate value convert to a double */
  176950. /* p->iCoord might point to either a lower or upper bound coordinate
  176951. ** in a coordinate pair. But make pCellData point to the lower bound.
  176952. */
  176953. pCellData += 8 + 4*(p->iCoord&0xfe);
  176954. assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
  176955. || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_TRUE
  176956. || p->op==RTREE_FALSE );
  176957. assert( ((((char*)pCellData) - (char*)0)&3)==0 ); /* 4-byte aligned */
  176958. switch( p->op ){
  176959. case RTREE_TRUE: return; /* Always satisfied */
  176960. case RTREE_FALSE: break; /* Never satisfied */
  176961. case RTREE_LE:
  176962. case RTREE_LT:
  176963. case RTREE_EQ:
  176964. RTREE_DECODE_COORD(eInt, pCellData, val);
  176965. /* val now holds the lower bound of the coordinate pair */
  176966. if( p->u.rValue>=val ) return;
  176967. if( p->op!=RTREE_EQ ) break; /* RTREE_LE and RTREE_LT end here */
  176968. /* Fall through for the RTREE_EQ case */
  176969. default: /* RTREE_GT or RTREE_GE, or fallthrough of RTREE_EQ */
  176970. pCellData += 4;
  176971. RTREE_DECODE_COORD(eInt, pCellData, val);
  176972. /* val now holds the upper bound of the coordinate pair */
  176973. if( p->u.rValue<=val ) return;
  176974. }
  176975. *peWithin = NOT_WITHIN;
  176976. }
  176977. /*
  176978. ** Check the leaf RTree cell given by pCellData against constraint p.
  176979. ** If this constraint is not satisfied, set *peWithin to NOT_WITHIN.
  176980. ** If the constraint is satisfied, leave *peWithin unchanged.
  176981. **
  176982. ** The constraint is of the form: xN op $val
  176983. **
  176984. ** The op is given by p->op. The xN is p->iCoord-th coordinate in
  176985. ** pCellData. $val is given by p->u.rValue.
  176986. */
  176987. static void rtreeLeafConstraint(
  176988. RtreeConstraint *p, /* The constraint to test */
  176989. int eInt, /* True if RTree holds integer coordinates */
  176990. u8 *pCellData, /* Raw cell content as appears on disk */
  176991. int *peWithin /* Adjust downward, as appropriate */
  176992. ){
  176993. RtreeDValue xN; /* Coordinate value converted to a double */
  176994. assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
  176995. || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_TRUE
  176996. || p->op==RTREE_FALSE );
  176997. pCellData += 8 + p->iCoord*4;
  176998. assert( ((((char*)pCellData) - (char*)0)&3)==0 ); /* 4-byte aligned */
  176999. RTREE_DECODE_COORD(eInt, pCellData, xN);
  177000. switch( p->op ){
  177001. case RTREE_TRUE: return; /* Always satisfied */
  177002. case RTREE_FALSE: break; /* Never satisfied */
  177003. case RTREE_LE: if( xN <= p->u.rValue ) return; break;
  177004. case RTREE_LT: if( xN < p->u.rValue ) return; break;
  177005. case RTREE_GE: if( xN >= p->u.rValue ) return; break;
  177006. case RTREE_GT: if( xN > p->u.rValue ) return; break;
  177007. default: if( xN == p->u.rValue ) return; break;
  177008. }
  177009. *peWithin = NOT_WITHIN;
  177010. }
  177011. /*
  177012. ** One of the cells in node pNode is guaranteed to have a 64-bit
  177013. ** integer value equal to iRowid. Return the index of this cell.
  177014. */
  177015. static int nodeRowidIndex(
  177016. Rtree *pRtree,
  177017. RtreeNode *pNode,
  177018. i64 iRowid,
  177019. int *piIndex
  177020. ){
  177021. int ii;
  177022. int nCell = NCELL(pNode);
  177023. assert( nCell<200 );
  177024. for(ii=0; ii<nCell; ii++){
  177025. if( nodeGetRowid(pRtree, pNode, ii)==iRowid ){
  177026. *piIndex = ii;
  177027. return SQLITE_OK;
  177028. }
  177029. }
  177030. RTREE_IS_CORRUPT(pRtree);
  177031. return SQLITE_CORRUPT_VTAB;
  177032. }
  177033. /*
  177034. ** Return the index of the cell containing a pointer to node pNode
  177035. ** in its parent. If pNode is the root node, return -1.
  177036. */
  177037. static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode, int *piIndex){
  177038. RtreeNode *pParent = pNode->pParent;
  177039. if( pParent ){
  177040. return nodeRowidIndex(pRtree, pParent, pNode->iNode, piIndex);
  177041. }
  177042. *piIndex = -1;
  177043. return SQLITE_OK;
  177044. }
  177045. /*
  177046. ** Compare two search points. Return negative, zero, or positive if the first
  177047. ** is less than, equal to, or greater than the second.
  177048. **
  177049. ** The rScore is the primary key. Smaller rScore values come first.
  177050. ** If the rScore is a tie, then use iLevel as the tie breaker with smaller
  177051. ** iLevel values coming first. In this way, if rScore is the same for all
  177052. ** SearchPoints, then iLevel becomes the deciding factor and the result
  177053. ** is a depth-first search, which is the desired default behavior.
  177054. */
  177055. static int rtreeSearchPointCompare(
  177056. const RtreeSearchPoint *pA,
  177057. const RtreeSearchPoint *pB
  177058. ){
  177059. if( pA->rScore<pB->rScore ) return -1;
  177060. if( pA->rScore>pB->rScore ) return +1;
  177061. if( pA->iLevel<pB->iLevel ) return -1;
  177062. if( pA->iLevel>pB->iLevel ) return +1;
  177063. return 0;
  177064. }
  177065. /*
  177066. ** Interchange two search points in a cursor.
  177067. */
  177068. static void rtreeSearchPointSwap(RtreeCursor *p, int i, int j){
  177069. RtreeSearchPoint t = p->aPoint[i];
  177070. assert( i<j );
  177071. p->aPoint[i] = p->aPoint[j];
  177072. p->aPoint[j] = t;
  177073. i++; j++;
  177074. if( i<RTREE_CACHE_SZ ){
  177075. if( j>=RTREE_CACHE_SZ ){
  177076. nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]);
  177077. p->aNode[i] = 0;
  177078. }else{
  177079. RtreeNode *pTemp = p->aNode[i];
  177080. p->aNode[i] = p->aNode[j];
  177081. p->aNode[j] = pTemp;
  177082. }
  177083. }
  177084. }
  177085. /*
  177086. ** Return the search point with the lowest current score.
  177087. */
  177088. static RtreeSearchPoint *rtreeSearchPointFirst(RtreeCursor *pCur){
  177089. return pCur->bPoint ? &pCur->sPoint : pCur->nPoint ? pCur->aPoint : 0;
  177090. }
  177091. /*
  177092. ** Get the RtreeNode for the search point with the lowest score.
  177093. */
  177094. static RtreeNode *rtreeNodeOfFirstSearchPoint(RtreeCursor *pCur, int *pRC){
  177095. sqlite3_int64 id;
  177096. int ii = 1 - pCur->bPoint;
  177097. assert( ii==0 || ii==1 );
  177098. assert( pCur->bPoint || pCur->nPoint );
  177099. if( pCur->aNode[ii]==0 ){
  177100. assert( pRC!=0 );
  177101. id = ii ? pCur->aPoint[0].id : pCur->sPoint.id;
  177102. *pRC = nodeAcquire(RTREE_OF_CURSOR(pCur), id, 0, &pCur->aNode[ii]);
  177103. }
  177104. return pCur->aNode[ii];
  177105. }
  177106. /*
  177107. ** Push a new element onto the priority queue
  177108. */
  177109. static RtreeSearchPoint *rtreeEnqueue(
  177110. RtreeCursor *pCur, /* The cursor */
  177111. RtreeDValue rScore, /* Score for the new search point */
  177112. u8 iLevel /* Level for the new search point */
  177113. ){
  177114. int i, j;
  177115. RtreeSearchPoint *pNew;
  177116. if( pCur->nPoint>=pCur->nPointAlloc ){
  177117. int nNew = pCur->nPointAlloc*2 + 8;
  177118. pNew = sqlite3_realloc64(pCur->aPoint, nNew*sizeof(pCur->aPoint[0]));
  177119. if( pNew==0 ) return 0;
  177120. pCur->aPoint = pNew;
  177121. pCur->nPointAlloc = nNew;
  177122. }
  177123. i = pCur->nPoint++;
  177124. pNew = pCur->aPoint + i;
  177125. pNew->rScore = rScore;
  177126. pNew->iLevel = iLevel;
  177127. assert( iLevel<=RTREE_MAX_DEPTH );
  177128. while( i>0 ){
  177129. RtreeSearchPoint *pParent;
  177130. j = (i-1)/2;
  177131. pParent = pCur->aPoint + j;
  177132. if( rtreeSearchPointCompare(pNew, pParent)>=0 ) break;
  177133. rtreeSearchPointSwap(pCur, j, i);
  177134. i = j;
  177135. pNew = pParent;
  177136. }
  177137. return pNew;
  177138. }
  177139. /*
  177140. ** Allocate a new RtreeSearchPoint and return a pointer to it. Return
  177141. ** NULL if malloc fails.
  177142. */
  177143. static RtreeSearchPoint *rtreeSearchPointNew(
  177144. RtreeCursor *pCur, /* The cursor */
  177145. RtreeDValue rScore, /* Score for the new search point */
  177146. u8 iLevel /* Level for the new search point */
  177147. ){
  177148. RtreeSearchPoint *pNew, *pFirst;
  177149. pFirst = rtreeSearchPointFirst(pCur);
  177150. pCur->anQueue[iLevel]++;
  177151. if( pFirst==0
  177152. || pFirst->rScore>rScore
  177153. || (pFirst->rScore==rScore && pFirst->iLevel>iLevel)
  177154. ){
  177155. if( pCur->bPoint ){
  177156. int ii;
  177157. pNew = rtreeEnqueue(pCur, rScore, iLevel);
  177158. if( pNew==0 ) return 0;
  177159. ii = (int)(pNew - pCur->aPoint) + 1;
  177160. if( ii<RTREE_CACHE_SZ ){
  177161. assert( pCur->aNode[ii]==0 );
  177162. pCur->aNode[ii] = pCur->aNode[0];
  177163. }else{
  177164. nodeRelease(RTREE_OF_CURSOR(pCur), pCur->aNode[0]);
  177165. }
  177166. pCur->aNode[0] = 0;
  177167. *pNew = pCur->sPoint;
  177168. }
  177169. pCur->sPoint.rScore = rScore;
  177170. pCur->sPoint.iLevel = iLevel;
  177171. pCur->bPoint = 1;
  177172. return &pCur->sPoint;
  177173. }else{
  177174. return rtreeEnqueue(pCur, rScore, iLevel);
  177175. }
  177176. }
  177177. #if 0
  177178. /* Tracing routines for the RtreeSearchPoint queue */
  177179. static void tracePoint(RtreeSearchPoint *p, int idx, RtreeCursor *pCur){
  177180. if( idx<0 ){ printf(" s"); }else{ printf("%2d", idx); }
  177181. printf(" %d.%05lld.%02d %g %d",
  177182. p->iLevel, p->id, p->iCell, p->rScore, p->eWithin
  177183. );
  177184. idx++;
  177185. if( idx<RTREE_CACHE_SZ ){
  177186. printf(" %p\n", pCur->aNode[idx]);
  177187. }else{
  177188. printf("\n");
  177189. }
  177190. }
  177191. static void traceQueue(RtreeCursor *pCur, const char *zPrefix){
  177192. int ii;
  177193. printf("=== %9s ", zPrefix);
  177194. if( pCur->bPoint ){
  177195. tracePoint(&pCur->sPoint, -1, pCur);
  177196. }
  177197. for(ii=0; ii<pCur->nPoint; ii++){
  177198. if( ii>0 || pCur->bPoint ) printf(" ");
  177199. tracePoint(&pCur->aPoint[ii], ii, pCur);
  177200. }
  177201. }
  177202. # define RTREE_QUEUE_TRACE(A,B) traceQueue(A,B)
  177203. #else
  177204. # define RTREE_QUEUE_TRACE(A,B) /* no-op */
  177205. #endif
  177206. /* Remove the search point with the lowest current score.
  177207. */
  177208. static void rtreeSearchPointPop(RtreeCursor *p){
  177209. int i, j, k, n;
  177210. i = 1 - p->bPoint;
  177211. assert( i==0 || i==1 );
  177212. if( p->aNode[i] ){
  177213. nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]);
  177214. p->aNode[i] = 0;
  177215. }
  177216. if( p->bPoint ){
  177217. p->anQueue[p->sPoint.iLevel]--;
  177218. p->bPoint = 0;
  177219. }else if( p->nPoint ){
  177220. p->anQueue[p->aPoint[0].iLevel]--;
  177221. n = --p->nPoint;
  177222. p->aPoint[0] = p->aPoint[n];
  177223. if( n<RTREE_CACHE_SZ-1 ){
  177224. p->aNode[1] = p->aNode[n+1];
  177225. p->aNode[n+1] = 0;
  177226. }
  177227. i = 0;
  177228. while( (j = i*2+1)<n ){
  177229. k = j+1;
  177230. if( k<n && rtreeSearchPointCompare(&p->aPoint[k], &p->aPoint[j])<0 ){
  177231. if( rtreeSearchPointCompare(&p->aPoint[k], &p->aPoint[i])<0 ){
  177232. rtreeSearchPointSwap(p, i, k);
  177233. i = k;
  177234. }else{
  177235. break;
  177236. }
  177237. }else{
  177238. if( rtreeSearchPointCompare(&p->aPoint[j], &p->aPoint[i])<0 ){
  177239. rtreeSearchPointSwap(p, i, j);
  177240. i = j;
  177241. }else{
  177242. break;
  177243. }
  177244. }
  177245. }
  177246. }
  177247. }
  177248. /*
  177249. ** Continue the search on cursor pCur until the front of the queue
  177250. ** contains an entry suitable for returning as a result-set row,
  177251. ** or until the RtreeSearchPoint queue is empty, indicating that the
  177252. ** query has completed.
  177253. */
  177254. static int rtreeStepToLeaf(RtreeCursor *pCur){
  177255. RtreeSearchPoint *p;
  177256. Rtree *pRtree = RTREE_OF_CURSOR(pCur);
  177257. RtreeNode *pNode;
  177258. int eWithin;
  177259. int rc = SQLITE_OK;
  177260. int nCell;
  177261. int nConstraint = pCur->nConstraint;
  177262. int ii;
  177263. int eInt;
  177264. RtreeSearchPoint x;
  177265. eInt = pRtree->eCoordType==RTREE_COORD_INT32;
  177266. while( (p = rtreeSearchPointFirst(pCur))!=0 && p->iLevel>0 ){
  177267. u8 *pCellData;
  177268. pNode = rtreeNodeOfFirstSearchPoint(pCur, &rc);
  177269. if( rc ) return rc;
  177270. nCell = NCELL(pNode);
  177271. assert( nCell<200 );
  177272. pCellData = pNode->zData + (4+pRtree->nBytesPerCell*p->iCell);
  177273. while( p->iCell<nCell ){
  177274. sqlite3_rtree_dbl rScore = (sqlite3_rtree_dbl)-1;
  177275. eWithin = FULLY_WITHIN;
  177276. for(ii=0; ii<nConstraint; ii++){
  177277. RtreeConstraint *pConstraint = pCur->aConstraint + ii;
  177278. if( pConstraint->op>=RTREE_MATCH ){
  177279. rc = rtreeCallbackConstraint(pConstraint, eInt, pCellData, p,
  177280. &rScore, &eWithin);
  177281. if( rc ) return rc;
  177282. }else if( p->iLevel==1 ){
  177283. rtreeLeafConstraint(pConstraint, eInt, pCellData, &eWithin);
  177284. }else{
  177285. rtreeNonleafConstraint(pConstraint, eInt, pCellData, &eWithin);
  177286. }
  177287. if( eWithin==NOT_WITHIN ){
  177288. p->iCell++;
  177289. pCellData += pRtree->nBytesPerCell;
  177290. break;
  177291. }
  177292. }
  177293. if( eWithin==NOT_WITHIN ) continue;
  177294. p->iCell++;
  177295. x.iLevel = p->iLevel - 1;
  177296. if( x.iLevel ){
  177297. x.id = readInt64(pCellData);
  177298. for(ii=0; ii<pCur->nPoint; ii++){
  177299. if( pCur->aPoint[ii].id==x.id ){
  177300. RTREE_IS_CORRUPT(pRtree);
  177301. return SQLITE_CORRUPT_VTAB;
  177302. }
  177303. }
  177304. x.iCell = 0;
  177305. }else{
  177306. x.id = p->id;
  177307. x.iCell = p->iCell - 1;
  177308. }
  177309. if( p->iCell>=nCell ){
  177310. RTREE_QUEUE_TRACE(pCur, "POP-S:");
  177311. rtreeSearchPointPop(pCur);
  177312. }
  177313. if( rScore<RTREE_ZERO ) rScore = RTREE_ZERO;
  177314. p = rtreeSearchPointNew(pCur, rScore, x.iLevel);
  177315. if( p==0 ) return SQLITE_NOMEM;
  177316. p->eWithin = (u8)eWithin;
  177317. p->id = x.id;
  177318. p->iCell = x.iCell;
  177319. RTREE_QUEUE_TRACE(pCur, "PUSH-S:");
  177320. break;
  177321. }
  177322. if( p->iCell>=nCell ){
  177323. RTREE_QUEUE_TRACE(pCur, "POP-Se:");
  177324. rtreeSearchPointPop(pCur);
  177325. }
  177326. }
  177327. pCur->atEOF = p==0;
  177328. return SQLITE_OK;
  177329. }
  177330. /*
  177331. ** Rtree virtual table module xNext method.
  177332. */
  177333. static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
  177334. RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
  177335. int rc = SQLITE_OK;
  177336. /* Move to the next entry that matches the configured constraints. */
  177337. RTREE_QUEUE_TRACE(pCsr, "POP-Nx:");
  177338. if( pCsr->bAuxValid ){
  177339. pCsr->bAuxValid = 0;
  177340. sqlite3_reset(pCsr->pReadAux);
  177341. }
  177342. rtreeSearchPointPop(pCsr);
  177343. rc = rtreeStepToLeaf(pCsr);
  177344. return rc;
  177345. }
  177346. /*
  177347. ** Rtree virtual table module xRowid method.
  177348. */
  177349. static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
  177350. RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
  177351. RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);
  177352. int rc = SQLITE_OK;
  177353. RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
  177354. if( rc==SQLITE_OK && p ){
  177355. *pRowid = nodeGetRowid(RTREE_OF_CURSOR(pCsr), pNode, p->iCell);
  177356. }
  177357. return rc;
  177358. }
  177359. /*
  177360. ** Rtree virtual table module xColumn method.
  177361. */
  177362. static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
  177363. Rtree *pRtree = (Rtree *)cur->pVtab;
  177364. RtreeCursor *pCsr = (RtreeCursor *)cur;
  177365. RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);
  177366. RtreeCoord c;
  177367. int rc = SQLITE_OK;
  177368. RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
  177369. if( rc ) return rc;
  177370. if( p==0 ) return SQLITE_OK;
  177371. if( i==0 ){
  177372. sqlite3_result_int64(ctx, nodeGetRowid(pRtree, pNode, p->iCell));
  177373. }else if( i<=pRtree->nDim2 ){
  177374. nodeGetCoord(pRtree, pNode, p->iCell, i-1, &c);
  177375. #ifndef SQLITE_RTREE_INT_ONLY
  177376. if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
  177377. sqlite3_result_double(ctx, c.f);
  177378. }else
  177379. #endif
  177380. {
  177381. assert( pRtree->eCoordType==RTREE_COORD_INT32 );
  177382. sqlite3_result_int(ctx, c.i);
  177383. }
  177384. }else{
  177385. if( !pCsr->bAuxValid ){
  177386. if( pCsr->pReadAux==0 ){
  177387. rc = sqlite3_prepare_v3(pRtree->db, pRtree->zReadAuxSql, -1, 0,
  177388. &pCsr->pReadAux, 0);
  177389. if( rc ) return rc;
  177390. }
  177391. sqlite3_bind_int64(pCsr->pReadAux, 1,
  177392. nodeGetRowid(pRtree, pNode, p->iCell));
  177393. rc = sqlite3_step(pCsr->pReadAux);
  177394. if( rc==SQLITE_ROW ){
  177395. pCsr->bAuxValid = 1;
  177396. }else{
  177397. sqlite3_reset(pCsr->pReadAux);
  177398. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  177399. return rc;
  177400. }
  177401. }
  177402. sqlite3_result_value(ctx,
  177403. sqlite3_column_value(pCsr->pReadAux, i - pRtree->nDim2 + 1));
  177404. }
  177405. return SQLITE_OK;
  177406. }
  177407. /*
  177408. ** Use nodeAcquire() to obtain the leaf node containing the record with
  177409. ** rowid iRowid. If successful, set *ppLeaf to point to the node and
  177410. ** return SQLITE_OK. If there is no such record in the table, set
  177411. ** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
  177412. ** to zero and return an SQLite error code.
  177413. */
  177414. static int findLeafNode(
  177415. Rtree *pRtree, /* RTree to search */
  177416. i64 iRowid, /* The rowid searching for */
  177417. RtreeNode **ppLeaf, /* Write the node here */
  177418. sqlite3_int64 *piNode /* Write the node-id here */
  177419. ){
  177420. int rc;
  177421. *ppLeaf = 0;
  177422. sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
  177423. if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
  177424. i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
  177425. if( piNode ) *piNode = iNode;
  177426. rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
  177427. sqlite3_reset(pRtree->pReadRowid);
  177428. }else{
  177429. rc = sqlite3_reset(pRtree->pReadRowid);
  177430. }
  177431. return rc;
  177432. }
  177433. /*
  177434. ** This function is called to configure the RtreeConstraint object passed
  177435. ** as the second argument for a MATCH constraint. The value passed as the
  177436. ** first argument to this function is the right-hand operand to the MATCH
  177437. ** operator.
  177438. */
  177439. static int deserializeGeometry(sqlite3_value *pValue, RtreeConstraint *pCons){
  177440. RtreeMatchArg *pBlob, *pSrc; /* BLOB returned by geometry function */
  177441. sqlite3_rtree_query_info *pInfo; /* Callback information */
  177442. pSrc = sqlite3_value_pointer(pValue, "RtreeMatchArg");
  177443. if( pSrc==0 ) return SQLITE_ERROR;
  177444. pInfo = (sqlite3_rtree_query_info*)
  177445. sqlite3_malloc64( sizeof(*pInfo)+pSrc->iSize );
  177446. if( !pInfo ) return SQLITE_NOMEM;
  177447. memset(pInfo, 0, sizeof(*pInfo));
  177448. pBlob = (RtreeMatchArg*)&pInfo[1];
  177449. memcpy(pBlob, pSrc, pSrc->iSize);
  177450. pInfo->pContext = pBlob->cb.pContext;
  177451. pInfo->nParam = pBlob->nParam;
  177452. pInfo->aParam = pBlob->aParam;
  177453. pInfo->apSqlParam = pBlob->apSqlParam;
  177454. if( pBlob->cb.xGeom ){
  177455. pCons->u.xGeom = pBlob->cb.xGeom;
  177456. }else{
  177457. pCons->op = RTREE_QUERY;
  177458. pCons->u.xQueryFunc = pBlob->cb.xQueryFunc;
  177459. }
  177460. pCons->pInfo = pInfo;
  177461. return SQLITE_OK;
  177462. }
  177463. /*
  177464. ** Rtree virtual table module xFilter method.
  177465. */
  177466. static int rtreeFilter(
  177467. sqlite3_vtab_cursor *pVtabCursor,
  177468. int idxNum, const char *idxStr,
  177469. int argc, sqlite3_value **argv
  177470. ){
  177471. Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
  177472. RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
  177473. RtreeNode *pRoot = 0;
  177474. int ii;
  177475. int rc = SQLITE_OK;
  177476. int iCell = 0;
  177477. rtreeReference(pRtree);
  177478. /* Reset the cursor to the same state as rtreeOpen() leaves it in. */
  177479. resetCursor(pCsr);
  177480. pCsr->iStrategy = idxNum;
  177481. if( idxNum==1 ){
  177482. /* Special case - lookup by rowid. */
  177483. RtreeNode *pLeaf; /* Leaf on which the required cell resides */
  177484. RtreeSearchPoint *p; /* Search point for the leaf */
  177485. i64 iRowid = sqlite3_value_int64(argv[0]);
  177486. i64 iNode = 0;
  177487. int eType = sqlite3_value_numeric_type(argv[0]);
  177488. if( eType==SQLITE_INTEGER
  177489. || (eType==SQLITE_FLOAT && sqlite3_value_double(argv[0])==iRowid)
  177490. ){
  177491. rc = findLeafNode(pRtree, iRowid, &pLeaf, &iNode);
  177492. }else{
  177493. rc = SQLITE_OK;
  177494. pLeaf = 0;
  177495. }
  177496. if( rc==SQLITE_OK && pLeaf!=0 ){
  177497. p = rtreeSearchPointNew(pCsr, RTREE_ZERO, 0);
  177498. assert( p!=0 ); /* Always returns pCsr->sPoint */
  177499. pCsr->aNode[0] = pLeaf;
  177500. p->id = iNode;
  177501. p->eWithin = PARTLY_WITHIN;
  177502. rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &iCell);
  177503. p->iCell = (u8)iCell;
  177504. RTREE_QUEUE_TRACE(pCsr, "PUSH-F1:");
  177505. }else{
  177506. pCsr->atEOF = 1;
  177507. }
  177508. }else{
  177509. /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array
  177510. ** with the configured constraints.
  177511. */
  177512. rc = nodeAcquire(pRtree, 1, 0, &pRoot);
  177513. if( rc==SQLITE_OK && argc>0 ){
  177514. pCsr->aConstraint = sqlite3_malloc64(sizeof(RtreeConstraint)*argc);
  177515. pCsr->nConstraint = argc;
  177516. if( !pCsr->aConstraint ){
  177517. rc = SQLITE_NOMEM;
  177518. }else{
  177519. memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*argc);
  177520. memset(pCsr->anQueue, 0, sizeof(u32)*(pRtree->iDepth + 1));
  177521. assert( (idxStr==0 && argc==0)
  177522. || (idxStr && (int)strlen(idxStr)==argc*2) );
  177523. for(ii=0; ii<argc; ii++){
  177524. RtreeConstraint *p = &pCsr->aConstraint[ii];
  177525. int eType = sqlite3_value_numeric_type(argv[ii]);
  177526. p->op = idxStr[ii*2];
  177527. p->iCoord = idxStr[ii*2+1]-'0';
  177528. if( p->op>=RTREE_MATCH ){
  177529. /* A MATCH operator. The right-hand-side must be a blob that
  177530. ** can be cast into an RtreeMatchArg object. One created using
  177531. ** an sqlite3_rtree_geometry_callback() SQL user function.
  177532. */
  177533. rc = deserializeGeometry(argv[ii], p);
  177534. if( rc!=SQLITE_OK ){
  177535. break;
  177536. }
  177537. p->pInfo->nCoord = pRtree->nDim2;
  177538. p->pInfo->anQueue = pCsr->anQueue;
  177539. p->pInfo->mxLevel = pRtree->iDepth + 1;
  177540. }else if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
  177541. #ifdef SQLITE_RTREE_INT_ONLY
  177542. p->u.rValue = sqlite3_value_int64(argv[ii]);
  177543. #else
  177544. p->u.rValue = sqlite3_value_double(argv[ii]);
  177545. #endif
  177546. }else{
  177547. p->u.rValue = RTREE_ZERO;
  177548. if( eType==SQLITE_NULL ){
  177549. p->op = RTREE_FALSE;
  177550. }else if( p->op==RTREE_LT || p->op==RTREE_LE ){
  177551. p->op = RTREE_TRUE;
  177552. }else{
  177553. p->op = RTREE_FALSE;
  177554. }
  177555. }
  177556. }
  177557. }
  177558. }
  177559. if( rc==SQLITE_OK ){
  177560. RtreeSearchPoint *pNew;
  177561. pNew = rtreeSearchPointNew(pCsr, RTREE_ZERO, (u8)(pRtree->iDepth+1));
  177562. if( pNew==0 ) return SQLITE_NOMEM;
  177563. pNew->id = 1;
  177564. pNew->iCell = 0;
  177565. pNew->eWithin = PARTLY_WITHIN;
  177566. assert( pCsr->bPoint==1 );
  177567. pCsr->aNode[0] = pRoot;
  177568. pRoot = 0;
  177569. RTREE_QUEUE_TRACE(pCsr, "PUSH-Fm:");
  177570. rc = rtreeStepToLeaf(pCsr);
  177571. }
  177572. }
  177573. nodeRelease(pRtree, pRoot);
  177574. rtreeRelease(pRtree);
  177575. return rc;
  177576. }
  177577. /*
  177578. ** Rtree virtual table module xBestIndex method. There are three
  177579. ** table scan strategies to choose from (in order from most to
  177580. ** least desirable):
  177581. **
  177582. ** idxNum idxStr Strategy
  177583. ** ------------------------------------------------
  177584. ** 1 Unused Direct lookup by rowid.
  177585. ** 2 See below R-tree query or full-table scan.
  177586. ** ------------------------------------------------
  177587. **
  177588. ** If strategy 1 is used, then idxStr is not meaningful. If strategy
  177589. ** 2 is used, idxStr is formatted to contain 2 bytes for each
  177590. ** constraint used. The first two bytes of idxStr correspond to
  177591. ** the constraint in sqlite3_index_info.aConstraintUsage[] with
  177592. ** (argvIndex==1) etc.
  177593. **
  177594. ** The first of each pair of bytes in idxStr identifies the constraint
  177595. ** operator as follows:
  177596. **
  177597. ** Operator Byte Value
  177598. ** ----------------------
  177599. ** = 0x41 ('A')
  177600. ** <= 0x42 ('B')
  177601. ** < 0x43 ('C')
  177602. ** >= 0x44 ('D')
  177603. ** > 0x45 ('E')
  177604. ** MATCH 0x46 ('F')
  177605. ** ----------------------
  177606. **
  177607. ** The second of each pair of bytes identifies the coordinate column
  177608. ** to which the constraint applies. The leftmost coordinate column
  177609. ** is 'a', the second from the left 'b' etc.
  177610. */
  177611. static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
  177612. Rtree *pRtree = (Rtree*)tab;
  177613. int rc = SQLITE_OK;
  177614. int ii;
  177615. int bMatch = 0; /* True if there exists a MATCH constraint */
  177616. i64 nRow; /* Estimated rows returned by this scan */
  177617. int iIdx = 0;
  177618. char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
  177619. memset(zIdxStr, 0, sizeof(zIdxStr));
  177620. /* Check if there exists a MATCH constraint - even an unusable one. If there
  177621. ** is, do not consider the lookup-by-rowid plan as using such a plan would
  177622. ** require the VDBE to evaluate the MATCH constraint, which is not currently
  177623. ** possible. */
  177624. for(ii=0; ii<pIdxInfo->nConstraint; ii++){
  177625. if( pIdxInfo->aConstraint[ii].op==SQLITE_INDEX_CONSTRAINT_MATCH ){
  177626. bMatch = 1;
  177627. }
  177628. }
  177629. assert( pIdxInfo->idxStr==0 );
  177630. for(ii=0; ii<pIdxInfo->nConstraint && iIdx<(int)(sizeof(zIdxStr)-1); ii++){
  177631. struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
  177632. if( bMatch==0 && p->usable
  177633. && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ
  177634. ){
  177635. /* We have an equality constraint on the rowid. Use strategy 1. */
  177636. int jj;
  177637. for(jj=0; jj<ii; jj++){
  177638. pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
  177639. pIdxInfo->aConstraintUsage[jj].omit = 0;
  177640. }
  177641. pIdxInfo->idxNum = 1;
  177642. pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
  177643. pIdxInfo->aConstraintUsage[jj].omit = 1;
  177644. /* This strategy involves a two rowid lookups on an B-Tree structures
  177645. ** and then a linear search of an R-Tree node. This should be
  177646. ** considered almost as quick as a direct rowid lookup (for which
  177647. ** sqlite uses an internal cost of 0.0). It is expected to return
  177648. ** a single row.
  177649. */
  177650. pIdxInfo->estimatedCost = 30.0;
  177651. pIdxInfo->estimatedRows = 1;
  177652. pIdxInfo->idxFlags = SQLITE_INDEX_SCAN_UNIQUE;
  177653. return SQLITE_OK;
  177654. }
  177655. if( p->usable
  177656. && ((p->iColumn>0 && p->iColumn<=pRtree->nDim2)
  177657. || p->op==SQLITE_INDEX_CONSTRAINT_MATCH)
  177658. ){
  177659. u8 op;
  177660. switch( p->op ){
  177661. case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
  177662. case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
  177663. case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
  177664. case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
  177665. case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
  177666. case SQLITE_INDEX_CONSTRAINT_MATCH: op = RTREE_MATCH; break;
  177667. default: op = 0; break;
  177668. }
  177669. if( op ){
  177670. zIdxStr[iIdx++] = op;
  177671. zIdxStr[iIdx++] = (char)(p->iColumn - 1 + '0');
  177672. pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
  177673. pIdxInfo->aConstraintUsage[ii].omit = 1;
  177674. }
  177675. }
  177676. }
  177677. pIdxInfo->idxNum = 2;
  177678. pIdxInfo->needToFreeIdxStr = 1;
  177679. if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
  177680. return SQLITE_NOMEM;
  177681. }
  177682. nRow = pRtree->nRowEst >> (iIdx/2);
  177683. pIdxInfo->estimatedCost = (double)6.0 * (double)nRow;
  177684. pIdxInfo->estimatedRows = nRow;
  177685. return rc;
  177686. }
  177687. /*
  177688. ** Return the N-dimensional volumn of the cell stored in *p.
  177689. */
  177690. static RtreeDValue cellArea(Rtree *pRtree, RtreeCell *p){
  177691. RtreeDValue area = (RtreeDValue)1;
  177692. assert( pRtree->nDim>=1 && pRtree->nDim<=5 );
  177693. #ifndef SQLITE_RTREE_INT_ONLY
  177694. if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
  177695. switch( pRtree->nDim ){
  177696. case 5: area = p->aCoord[9].f - p->aCoord[8].f;
  177697. case 4: area *= p->aCoord[7].f - p->aCoord[6].f;
  177698. case 3: area *= p->aCoord[5].f - p->aCoord[4].f;
  177699. case 2: area *= p->aCoord[3].f - p->aCoord[2].f;
  177700. default: area *= p->aCoord[1].f - p->aCoord[0].f;
  177701. }
  177702. }else
  177703. #endif
  177704. {
  177705. switch( pRtree->nDim ){
  177706. case 5: area = (i64)p->aCoord[9].i - (i64)p->aCoord[8].i;
  177707. case 4: area *= (i64)p->aCoord[7].i - (i64)p->aCoord[6].i;
  177708. case 3: area *= (i64)p->aCoord[5].i - (i64)p->aCoord[4].i;
  177709. case 2: area *= (i64)p->aCoord[3].i - (i64)p->aCoord[2].i;
  177710. default: area *= (i64)p->aCoord[1].i - (i64)p->aCoord[0].i;
  177711. }
  177712. }
  177713. return area;
  177714. }
  177715. /*
  177716. ** Return the margin length of cell p. The margin length is the sum
  177717. ** of the objects size in each dimension.
  177718. */
  177719. static RtreeDValue cellMargin(Rtree *pRtree, RtreeCell *p){
  177720. RtreeDValue margin = 0;
  177721. int ii = pRtree->nDim2 - 2;
  177722. do{
  177723. margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
  177724. ii -= 2;
  177725. }while( ii>=0 );
  177726. return margin;
  177727. }
  177728. /*
  177729. ** Store the union of cells p1 and p2 in p1.
  177730. */
  177731. static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
  177732. int ii = 0;
  177733. if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
  177734. do{
  177735. p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
  177736. p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
  177737. ii += 2;
  177738. }while( ii<pRtree->nDim2 );
  177739. }else{
  177740. do{
  177741. p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
  177742. p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
  177743. ii += 2;
  177744. }while( ii<pRtree->nDim2 );
  177745. }
  177746. }
  177747. /*
  177748. ** Return true if the area covered by p2 is a subset of the area covered
  177749. ** by p1. False otherwise.
  177750. */
  177751. static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
  177752. int ii;
  177753. int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
  177754. for(ii=0; ii<pRtree->nDim2; ii+=2){
  177755. RtreeCoord *a1 = &p1->aCoord[ii];
  177756. RtreeCoord *a2 = &p2->aCoord[ii];
  177757. if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f))
  177758. || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i))
  177759. ){
  177760. return 0;
  177761. }
  177762. }
  177763. return 1;
  177764. }
  177765. /*
  177766. ** Return the amount cell p would grow by if it were unioned with pCell.
  177767. */
  177768. static RtreeDValue cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
  177769. RtreeDValue area;
  177770. RtreeCell cell;
  177771. memcpy(&cell, p, sizeof(RtreeCell));
  177772. area = cellArea(pRtree, &cell);
  177773. cellUnion(pRtree, &cell, pCell);
  177774. return (cellArea(pRtree, &cell)-area);
  177775. }
  177776. static RtreeDValue cellOverlap(
  177777. Rtree *pRtree,
  177778. RtreeCell *p,
  177779. RtreeCell *aCell,
  177780. int nCell
  177781. ){
  177782. int ii;
  177783. RtreeDValue overlap = RTREE_ZERO;
  177784. for(ii=0; ii<nCell; ii++){
  177785. int jj;
  177786. RtreeDValue o = (RtreeDValue)1;
  177787. for(jj=0; jj<pRtree->nDim2; jj+=2){
  177788. RtreeDValue x1, x2;
  177789. x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
  177790. x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
  177791. if( x2<x1 ){
  177792. o = (RtreeDValue)0;
  177793. break;
  177794. }else{
  177795. o = o * (x2-x1);
  177796. }
  177797. }
  177798. overlap += o;
  177799. }
  177800. return overlap;
  177801. }
  177802. /*
  177803. ** This function implements the ChooseLeaf algorithm from Gutman[84].
  177804. ** ChooseSubTree in r*tree terminology.
  177805. */
  177806. static int ChooseLeaf(
  177807. Rtree *pRtree, /* Rtree table */
  177808. RtreeCell *pCell, /* Cell to insert into rtree */
  177809. int iHeight, /* Height of sub-tree rooted at pCell */
  177810. RtreeNode **ppLeaf /* OUT: Selected leaf page */
  177811. ){
  177812. int rc;
  177813. int ii;
  177814. RtreeNode *pNode = 0;
  177815. rc = nodeAcquire(pRtree, 1, 0, &pNode);
  177816. for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
  177817. int iCell;
  177818. sqlite3_int64 iBest = 0;
  177819. RtreeDValue fMinGrowth = RTREE_ZERO;
  177820. RtreeDValue fMinArea = RTREE_ZERO;
  177821. int nCell = NCELL(pNode);
  177822. RtreeCell cell;
  177823. RtreeNode *pChild;
  177824. RtreeCell *aCell = 0;
  177825. /* Select the child node which will be enlarged the least if pCell
  177826. ** is inserted into it. Resolve ties by choosing the entry with
  177827. ** the smallest area.
  177828. */
  177829. for(iCell=0; iCell<nCell; iCell++){
  177830. int bBest = 0;
  177831. RtreeDValue growth;
  177832. RtreeDValue area;
  177833. nodeGetCell(pRtree, pNode, iCell, &cell);
  177834. growth = cellGrowth(pRtree, &cell, pCell);
  177835. area = cellArea(pRtree, &cell);
  177836. if( iCell==0||growth<fMinGrowth||(growth==fMinGrowth && area<fMinArea) ){
  177837. bBest = 1;
  177838. }
  177839. if( bBest ){
  177840. fMinGrowth = growth;
  177841. fMinArea = area;
  177842. iBest = cell.iRowid;
  177843. }
  177844. }
  177845. sqlite3_free(aCell);
  177846. rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
  177847. nodeRelease(pRtree, pNode);
  177848. pNode = pChild;
  177849. }
  177850. *ppLeaf = pNode;
  177851. return rc;
  177852. }
  177853. /*
  177854. ** A cell with the same content as pCell has just been inserted into
  177855. ** the node pNode. This function updates the bounding box cells in
  177856. ** all ancestor elements.
  177857. */
  177858. static int AdjustTree(
  177859. Rtree *pRtree, /* Rtree table */
  177860. RtreeNode *pNode, /* Adjust ancestry of this node. */
  177861. RtreeCell *pCell /* This cell was just inserted */
  177862. ){
  177863. RtreeNode *p = pNode;
  177864. int cnt = 0;
  177865. while( p->pParent ){
  177866. RtreeNode *pParent = p->pParent;
  177867. RtreeCell cell;
  177868. int iCell;
  177869. if( (++cnt)>1000 || nodeParentIndex(pRtree, p, &iCell) ){
  177870. RTREE_IS_CORRUPT(pRtree);
  177871. return SQLITE_CORRUPT_VTAB;
  177872. }
  177873. nodeGetCell(pRtree, pParent, iCell, &cell);
  177874. if( !cellContains(pRtree, &cell, pCell) ){
  177875. cellUnion(pRtree, &cell, pCell);
  177876. nodeOverwriteCell(pRtree, pParent, &cell, iCell);
  177877. }
  177878. p = pParent;
  177879. }
  177880. return SQLITE_OK;
  177881. }
  177882. /*
  177883. ** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
  177884. */
  177885. static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
  177886. sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
  177887. sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
  177888. sqlite3_step(pRtree->pWriteRowid);
  177889. return sqlite3_reset(pRtree->pWriteRowid);
  177890. }
  177891. /*
  177892. ** Write mapping (iNode->iPar) to the <rtree>_parent table.
  177893. */
  177894. static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
  177895. sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
  177896. sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
  177897. sqlite3_step(pRtree->pWriteParent);
  177898. return sqlite3_reset(pRtree->pWriteParent);
  177899. }
  177900. static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
  177901. /*
  177902. ** Arguments aIdx, aDistance and aSpare all point to arrays of size
  177903. ** nIdx. The aIdx array contains the set of integers from 0 to
  177904. ** (nIdx-1) in no particular order. This function sorts the values
  177905. ** in aIdx according to the indexed values in aDistance. For
  177906. ** example, assuming the inputs:
  177907. **
  177908. ** aIdx = { 0, 1, 2, 3 }
  177909. ** aDistance = { 5.0, 2.0, 7.0, 6.0 }
  177910. **
  177911. ** this function sets the aIdx array to contain:
  177912. **
  177913. ** aIdx = { 0, 1, 2, 3 }
  177914. **
  177915. ** The aSpare array is used as temporary working space by the
  177916. ** sorting algorithm.
  177917. */
  177918. static void SortByDistance(
  177919. int *aIdx,
  177920. int nIdx,
  177921. RtreeDValue *aDistance,
  177922. int *aSpare
  177923. ){
  177924. if( nIdx>1 ){
  177925. int iLeft = 0;
  177926. int iRight = 0;
  177927. int nLeft = nIdx/2;
  177928. int nRight = nIdx-nLeft;
  177929. int *aLeft = aIdx;
  177930. int *aRight = &aIdx[nLeft];
  177931. SortByDistance(aLeft, nLeft, aDistance, aSpare);
  177932. SortByDistance(aRight, nRight, aDistance, aSpare);
  177933. memcpy(aSpare, aLeft, sizeof(int)*nLeft);
  177934. aLeft = aSpare;
  177935. while( iLeft<nLeft || iRight<nRight ){
  177936. if( iLeft==nLeft ){
  177937. aIdx[iLeft+iRight] = aRight[iRight];
  177938. iRight++;
  177939. }else if( iRight==nRight ){
  177940. aIdx[iLeft+iRight] = aLeft[iLeft];
  177941. iLeft++;
  177942. }else{
  177943. RtreeDValue fLeft = aDistance[aLeft[iLeft]];
  177944. RtreeDValue fRight = aDistance[aRight[iRight]];
  177945. if( fLeft<fRight ){
  177946. aIdx[iLeft+iRight] = aLeft[iLeft];
  177947. iLeft++;
  177948. }else{
  177949. aIdx[iLeft+iRight] = aRight[iRight];
  177950. iRight++;
  177951. }
  177952. }
  177953. }
  177954. #if 0
  177955. /* Check that the sort worked */
  177956. {
  177957. int jj;
  177958. for(jj=1; jj<nIdx; jj++){
  177959. RtreeDValue left = aDistance[aIdx[jj-1]];
  177960. RtreeDValue right = aDistance[aIdx[jj]];
  177961. assert( left<=right );
  177962. }
  177963. }
  177964. #endif
  177965. }
  177966. }
  177967. /*
  177968. ** Arguments aIdx, aCell and aSpare all point to arrays of size
  177969. ** nIdx. The aIdx array contains the set of integers from 0 to
  177970. ** (nIdx-1) in no particular order. This function sorts the values
  177971. ** in aIdx according to dimension iDim of the cells in aCell. The
  177972. ** minimum value of dimension iDim is considered first, the
  177973. ** maximum used to break ties.
  177974. **
  177975. ** The aSpare array is used as temporary working space by the
  177976. ** sorting algorithm.
  177977. */
  177978. static void SortByDimension(
  177979. Rtree *pRtree,
  177980. int *aIdx,
  177981. int nIdx,
  177982. int iDim,
  177983. RtreeCell *aCell,
  177984. int *aSpare
  177985. ){
  177986. if( nIdx>1 ){
  177987. int iLeft = 0;
  177988. int iRight = 0;
  177989. int nLeft = nIdx/2;
  177990. int nRight = nIdx-nLeft;
  177991. int *aLeft = aIdx;
  177992. int *aRight = &aIdx[nLeft];
  177993. SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
  177994. SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
  177995. memcpy(aSpare, aLeft, sizeof(int)*nLeft);
  177996. aLeft = aSpare;
  177997. while( iLeft<nLeft || iRight<nRight ){
  177998. RtreeDValue xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
  177999. RtreeDValue xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
  178000. RtreeDValue xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
  178001. RtreeDValue xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
  178002. if( (iLeft!=nLeft) && ((iRight==nRight)
  178003. || (xleft1<xright1)
  178004. || (xleft1==xright1 && xleft2<xright2)
  178005. )){
  178006. aIdx[iLeft+iRight] = aLeft[iLeft];
  178007. iLeft++;
  178008. }else{
  178009. aIdx[iLeft+iRight] = aRight[iRight];
  178010. iRight++;
  178011. }
  178012. }
  178013. #if 0
  178014. /* Check that the sort worked */
  178015. {
  178016. int jj;
  178017. for(jj=1; jj<nIdx; jj++){
  178018. RtreeDValue xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
  178019. RtreeDValue xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
  178020. RtreeDValue xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
  178021. RtreeDValue xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
  178022. assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
  178023. }
  178024. }
  178025. #endif
  178026. }
  178027. }
  178028. /*
  178029. ** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
  178030. */
  178031. static int splitNodeStartree(
  178032. Rtree *pRtree,
  178033. RtreeCell *aCell,
  178034. int nCell,
  178035. RtreeNode *pLeft,
  178036. RtreeNode *pRight,
  178037. RtreeCell *pBboxLeft,
  178038. RtreeCell *pBboxRight
  178039. ){
  178040. int **aaSorted;
  178041. int *aSpare;
  178042. int ii;
  178043. int iBestDim = 0;
  178044. int iBestSplit = 0;
  178045. RtreeDValue fBestMargin = RTREE_ZERO;
  178046. sqlite3_int64 nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
  178047. aaSorted = (int **)sqlite3_malloc64(nByte);
  178048. if( !aaSorted ){
  178049. return SQLITE_NOMEM;
  178050. }
  178051. aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
  178052. memset(aaSorted, 0, nByte);
  178053. for(ii=0; ii<pRtree->nDim; ii++){
  178054. int jj;
  178055. aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
  178056. for(jj=0; jj<nCell; jj++){
  178057. aaSorted[ii][jj] = jj;
  178058. }
  178059. SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
  178060. }
  178061. for(ii=0; ii<pRtree->nDim; ii++){
  178062. RtreeDValue margin = RTREE_ZERO;
  178063. RtreeDValue fBestOverlap = RTREE_ZERO;
  178064. RtreeDValue fBestArea = RTREE_ZERO;
  178065. int iBestLeft = 0;
  178066. int nLeft;
  178067. for(
  178068. nLeft=RTREE_MINCELLS(pRtree);
  178069. nLeft<=(nCell-RTREE_MINCELLS(pRtree));
  178070. nLeft++
  178071. ){
  178072. RtreeCell left;
  178073. RtreeCell right;
  178074. int kk;
  178075. RtreeDValue overlap;
  178076. RtreeDValue area;
  178077. memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
  178078. memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
  178079. for(kk=1; kk<(nCell-1); kk++){
  178080. if( kk<nLeft ){
  178081. cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
  178082. }else{
  178083. cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
  178084. }
  178085. }
  178086. margin += cellMargin(pRtree, &left);
  178087. margin += cellMargin(pRtree, &right);
  178088. overlap = cellOverlap(pRtree, &left, &right, 1);
  178089. area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
  178090. if( (nLeft==RTREE_MINCELLS(pRtree))
  178091. || (overlap<fBestOverlap)
  178092. || (overlap==fBestOverlap && area<fBestArea)
  178093. ){
  178094. iBestLeft = nLeft;
  178095. fBestOverlap = overlap;
  178096. fBestArea = area;
  178097. }
  178098. }
  178099. if( ii==0 || margin<fBestMargin ){
  178100. iBestDim = ii;
  178101. fBestMargin = margin;
  178102. iBestSplit = iBestLeft;
  178103. }
  178104. }
  178105. memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
  178106. memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
  178107. for(ii=0; ii<nCell; ii++){
  178108. RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
  178109. RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
  178110. RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
  178111. nodeInsertCell(pRtree, pTarget, pCell);
  178112. cellUnion(pRtree, pBbox, pCell);
  178113. }
  178114. sqlite3_free(aaSorted);
  178115. return SQLITE_OK;
  178116. }
  178117. static int updateMapping(
  178118. Rtree *pRtree,
  178119. i64 iRowid,
  178120. RtreeNode *pNode,
  178121. int iHeight
  178122. ){
  178123. int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
  178124. xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
  178125. if( iHeight>0 ){
  178126. RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
  178127. if( pChild ){
  178128. nodeRelease(pRtree, pChild->pParent);
  178129. nodeReference(pNode);
  178130. pChild->pParent = pNode;
  178131. }
  178132. }
  178133. return xSetMapping(pRtree, iRowid, pNode->iNode);
  178134. }
  178135. static int SplitNode(
  178136. Rtree *pRtree,
  178137. RtreeNode *pNode,
  178138. RtreeCell *pCell,
  178139. int iHeight
  178140. ){
  178141. int i;
  178142. int newCellIsRight = 0;
  178143. int rc = SQLITE_OK;
  178144. int nCell = NCELL(pNode);
  178145. RtreeCell *aCell;
  178146. int *aiUsed;
  178147. RtreeNode *pLeft = 0;
  178148. RtreeNode *pRight = 0;
  178149. RtreeCell leftbbox;
  178150. RtreeCell rightbbox;
  178151. /* Allocate an array and populate it with a copy of pCell and
  178152. ** all cells from node pLeft. Then zero the original node.
  178153. */
  178154. aCell = sqlite3_malloc64((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
  178155. if( !aCell ){
  178156. rc = SQLITE_NOMEM;
  178157. goto splitnode_out;
  178158. }
  178159. aiUsed = (int *)&aCell[nCell+1];
  178160. memset(aiUsed, 0, sizeof(int)*(nCell+1));
  178161. for(i=0; i<nCell; i++){
  178162. nodeGetCell(pRtree, pNode, i, &aCell[i]);
  178163. }
  178164. nodeZero(pRtree, pNode);
  178165. memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
  178166. nCell++;
  178167. if( pNode->iNode==1 ){
  178168. pRight = nodeNew(pRtree, pNode);
  178169. pLeft = nodeNew(pRtree, pNode);
  178170. pRtree->iDepth++;
  178171. pNode->isDirty = 1;
  178172. writeInt16(pNode->zData, pRtree->iDepth);
  178173. }else{
  178174. pLeft = pNode;
  178175. pRight = nodeNew(pRtree, pLeft->pParent);
  178176. pLeft->nRef++;
  178177. }
  178178. if( !pLeft || !pRight ){
  178179. rc = SQLITE_NOMEM;
  178180. goto splitnode_out;
  178181. }
  178182. memset(pLeft->zData, 0, pRtree->iNodeSize);
  178183. memset(pRight->zData, 0, pRtree->iNodeSize);
  178184. rc = splitNodeStartree(pRtree, aCell, nCell, pLeft, pRight,
  178185. &leftbbox, &rightbbox);
  178186. if( rc!=SQLITE_OK ){
  178187. goto splitnode_out;
  178188. }
  178189. /* Ensure both child nodes have node numbers assigned to them by calling
  178190. ** nodeWrite(). Node pRight always needs a node number, as it was created
  178191. ** by nodeNew() above. But node pLeft sometimes already has a node number.
  178192. ** In this case avoid the all to nodeWrite().
  178193. */
  178194. if( SQLITE_OK!=(rc = nodeWrite(pRtree, pRight))
  178195. || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
  178196. ){
  178197. goto splitnode_out;
  178198. }
  178199. rightbbox.iRowid = pRight->iNode;
  178200. leftbbox.iRowid = pLeft->iNode;
  178201. if( pNode->iNode==1 ){
  178202. rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
  178203. if( rc!=SQLITE_OK ){
  178204. goto splitnode_out;
  178205. }
  178206. }else{
  178207. RtreeNode *pParent = pLeft->pParent;
  178208. int iCell;
  178209. rc = nodeParentIndex(pRtree, pLeft, &iCell);
  178210. if( rc==SQLITE_OK ){
  178211. nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
  178212. rc = AdjustTree(pRtree, pParent, &leftbbox);
  178213. }
  178214. if( rc!=SQLITE_OK ){
  178215. goto splitnode_out;
  178216. }
  178217. }
  178218. if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
  178219. goto splitnode_out;
  178220. }
  178221. for(i=0; i<NCELL(pRight); i++){
  178222. i64 iRowid = nodeGetRowid(pRtree, pRight, i);
  178223. rc = updateMapping(pRtree, iRowid, pRight, iHeight);
  178224. if( iRowid==pCell->iRowid ){
  178225. newCellIsRight = 1;
  178226. }
  178227. if( rc!=SQLITE_OK ){
  178228. goto splitnode_out;
  178229. }
  178230. }
  178231. if( pNode->iNode==1 ){
  178232. for(i=0; i<NCELL(pLeft); i++){
  178233. i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
  178234. rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
  178235. if( rc!=SQLITE_OK ){
  178236. goto splitnode_out;
  178237. }
  178238. }
  178239. }else if( newCellIsRight==0 ){
  178240. rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
  178241. }
  178242. if( rc==SQLITE_OK ){
  178243. rc = nodeRelease(pRtree, pRight);
  178244. pRight = 0;
  178245. }
  178246. if( rc==SQLITE_OK ){
  178247. rc = nodeRelease(pRtree, pLeft);
  178248. pLeft = 0;
  178249. }
  178250. splitnode_out:
  178251. nodeRelease(pRtree, pRight);
  178252. nodeRelease(pRtree, pLeft);
  178253. sqlite3_free(aCell);
  178254. return rc;
  178255. }
  178256. /*
  178257. ** If node pLeaf is not the root of the r-tree and its pParent pointer is
  178258. ** still NULL, load all ancestor nodes of pLeaf into memory and populate
  178259. ** the pLeaf->pParent chain all the way up to the root node.
  178260. **
  178261. ** This operation is required when a row is deleted (or updated - an update
  178262. ** is implemented as a delete followed by an insert). SQLite provides the
  178263. ** rowid of the row to delete, which can be used to find the leaf on which
  178264. ** the entry resides (argument pLeaf). Once the leaf is located, this
  178265. ** function is called to determine its ancestry.
  178266. */
  178267. static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
  178268. int rc = SQLITE_OK;
  178269. RtreeNode *pChild = pLeaf;
  178270. while( rc==SQLITE_OK && pChild->iNode!=1 && pChild->pParent==0 ){
  178271. int rc2 = SQLITE_OK; /* sqlite3_reset() return code */
  178272. sqlite3_bind_int64(pRtree->pReadParent, 1, pChild->iNode);
  178273. rc = sqlite3_step(pRtree->pReadParent);
  178274. if( rc==SQLITE_ROW ){
  178275. RtreeNode *pTest; /* Used to test for reference loops */
  178276. i64 iNode; /* Node number of parent node */
  178277. /* Before setting pChild->pParent, test that we are not creating a
  178278. ** loop of references (as we would if, say, pChild==pParent). We don't
  178279. ** want to do this as it leads to a memory leak when trying to delete
  178280. ** the referenced counted node structures.
  178281. */
  178282. iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
  178283. for(pTest=pLeaf; pTest && pTest->iNode!=iNode; pTest=pTest->pParent);
  178284. if( !pTest ){
  178285. rc2 = nodeAcquire(pRtree, iNode, 0, &pChild->pParent);
  178286. }
  178287. }
  178288. rc = sqlite3_reset(pRtree->pReadParent);
  178289. if( rc==SQLITE_OK ) rc = rc2;
  178290. if( rc==SQLITE_OK && !pChild->pParent ){
  178291. RTREE_IS_CORRUPT(pRtree);
  178292. rc = SQLITE_CORRUPT_VTAB;
  178293. }
  178294. pChild = pChild->pParent;
  178295. }
  178296. return rc;
  178297. }
  178298. static int deleteCell(Rtree *, RtreeNode *, int, int);
  178299. static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
  178300. int rc;
  178301. int rc2;
  178302. RtreeNode *pParent = 0;
  178303. int iCell;
  178304. assert( pNode->nRef==1 );
  178305. /* Remove the entry in the parent cell. */
  178306. rc = nodeParentIndex(pRtree, pNode, &iCell);
  178307. if( rc==SQLITE_OK ){
  178308. pParent = pNode->pParent;
  178309. pNode->pParent = 0;
  178310. rc = deleteCell(pRtree, pParent, iCell, iHeight+1);
  178311. }
  178312. rc2 = nodeRelease(pRtree, pParent);
  178313. if( rc==SQLITE_OK ){
  178314. rc = rc2;
  178315. }
  178316. if( rc!=SQLITE_OK ){
  178317. return rc;
  178318. }
  178319. /* Remove the xxx_node entry. */
  178320. sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
  178321. sqlite3_step(pRtree->pDeleteNode);
  178322. if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
  178323. return rc;
  178324. }
  178325. /* Remove the xxx_parent entry. */
  178326. sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
  178327. sqlite3_step(pRtree->pDeleteParent);
  178328. if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
  178329. return rc;
  178330. }
  178331. /* Remove the node from the in-memory hash table and link it into
  178332. ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
  178333. */
  178334. nodeHashDelete(pRtree, pNode);
  178335. pNode->iNode = iHeight;
  178336. pNode->pNext = pRtree->pDeleted;
  178337. pNode->nRef++;
  178338. pRtree->pDeleted = pNode;
  178339. return SQLITE_OK;
  178340. }
  178341. static int fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
  178342. RtreeNode *pParent = pNode->pParent;
  178343. int rc = SQLITE_OK;
  178344. if( pParent ){
  178345. int ii;
  178346. int nCell = NCELL(pNode);
  178347. RtreeCell box; /* Bounding box for pNode */
  178348. nodeGetCell(pRtree, pNode, 0, &box);
  178349. for(ii=1; ii<nCell; ii++){
  178350. RtreeCell cell;
  178351. nodeGetCell(pRtree, pNode, ii, &cell);
  178352. cellUnion(pRtree, &box, &cell);
  178353. }
  178354. box.iRowid = pNode->iNode;
  178355. rc = nodeParentIndex(pRtree, pNode, &ii);
  178356. if( rc==SQLITE_OK ){
  178357. nodeOverwriteCell(pRtree, pParent, &box, ii);
  178358. rc = fixBoundingBox(pRtree, pParent);
  178359. }
  178360. }
  178361. return rc;
  178362. }
  178363. /*
  178364. ** Delete the cell at index iCell of node pNode. After removing the
  178365. ** cell, adjust the r-tree data structure if required.
  178366. */
  178367. static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
  178368. RtreeNode *pParent;
  178369. int rc;
  178370. if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
  178371. return rc;
  178372. }
  178373. /* Remove the cell from the node. This call just moves bytes around
  178374. ** the in-memory node image, so it cannot fail.
  178375. */
  178376. nodeDeleteCell(pRtree, pNode, iCell);
  178377. /* If the node is not the tree root and now has less than the minimum
  178378. ** number of cells, remove it from the tree. Otherwise, update the
  178379. ** cell in the parent node so that it tightly contains the updated
  178380. ** node.
  178381. */
  178382. pParent = pNode->pParent;
  178383. assert( pParent || pNode->iNode==1 );
  178384. if( pParent ){
  178385. if( NCELL(pNode)<RTREE_MINCELLS(pRtree) ){
  178386. rc = removeNode(pRtree, pNode, iHeight);
  178387. }else{
  178388. rc = fixBoundingBox(pRtree, pNode);
  178389. }
  178390. }
  178391. return rc;
  178392. }
  178393. static int Reinsert(
  178394. Rtree *pRtree,
  178395. RtreeNode *pNode,
  178396. RtreeCell *pCell,
  178397. int iHeight
  178398. ){
  178399. int *aOrder;
  178400. int *aSpare;
  178401. RtreeCell *aCell;
  178402. RtreeDValue *aDistance;
  178403. int nCell;
  178404. RtreeDValue aCenterCoord[RTREE_MAX_DIMENSIONS];
  178405. int iDim;
  178406. int ii;
  178407. int rc = SQLITE_OK;
  178408. int n;
  178409. memset(aCenterCoord, 0, sizeof(RtreeDValue)*RTREE_MAX_DIMENSIONS);
  178410. nCell = NCELL(pNode)+1;
  178411. n = (nCell+1)&(~1);
  178412. /* Allocate the buffers used by this operation. The allocation is
  178413. ** relinquished before this function returns.
  178414. */
  178415. aCell = (RtreeCell *)sqlite3_malloc64(n * (
  178416. sizeof(RtreeCell) + /* aCell array */
  178417. sizeof(int) + /* aOrder array */
  178418. sizeof(int) + /* aSpare array */
  178419. sizeof(RtreeDValue) /* aDistance array */
  178420. ));
  178421. if( !aCell ){
  178422. return SQLITE_NOMEM;
  178423. }
  178424. aOrder = (int *)&aCell[n];
  178425. aSpare = (int *)&aOrder[n];
  178426. aDistance = (RtreeDValue *)&aSpare[n];
  178427. for(ii=0; ii<nCell; ii++){
  178428. if( ii==(nCell-1) ){
  178429. memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
  178430. }else{
  178431. nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
  178432. }
  178433. aOrder[ii] = ii;
  178434. for(iDim=0; iDim<pRtree->nDim; iDim++){
  178435. aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]);
  178436. aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]);
  178437. }
  178438. }
  178439. for(iDim=0; iDim<pRtree->nDim; iDim++){
  178440. aCenterCoord[iDim] = (aCenterCoord[iDim]/(nCell*(RtreeDValue)2));
  178441. }
  178442. for(ii=0; ii<nCell; ii++){
  178443. aDistance[ii] = RTREE_ZERO;
  178444. for(iDim=0; iDim<pRtree->nDim; iDim++){
  178445. RtreeDValue coord = (DCOORD(aCell[ii].aCoord[iDim*2+1]) -
  178446. DCOORD(aCell[ii].aCoord[iDim*2]));
  178447. aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
  178448. }
  178449. }
  178450. SortByDistance(aOrder, nCell, aDistance, aSpare);
  178451. nodeZero(pRtree, pNode);
  178452. for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
  178453. RtreeCell *p = &aCell[aOrder[ii]];
  178454. nodeInsertCell(pRtree, pNode, p);
  178455. if( p->iRowid==pCell->iRowid ){
  178456. if( iHeight==0 ){
  178457. rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
  178458. }else{
  178459. rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
  178460. }
  178461. }
  178462. }
  178463. if( rc==SQLITE_OK ){
  178464. rc = fixBoundingBox(pRtree, pNode);
  178465. }
  178466. for(; rc==SQLITE_OK && ii<nCell; ii++){
  178467. /* Find a node to store this cell in. pNode->iNode currently contains
  178468. ** the height of the sub-tree headed by the cell.
  178469. */
  178470. RtreeNode *pInsert;
  178471. RtreeCell *p = &aCell[aOrder[ii]];
  178472. rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
  178473. if( rc==SQLITE_OK ){
  178474. int rc2;
  178475. rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
  178476. rc2 = nodeRelease(pRtree, pInsert);
  178477. if( rc==SQLITE_OK ){
  178478. rc = rc2;
  178479. }
  178480. }
  178481. }
  178482. sqlite3_free(aCell);
  178483. return rc;
  178484. }
  178485. /*
  178486. ** Insert cell pCell into node pNode. Node pNode is the head of a
  178487. ** subtree iHeight high (leaf nodes have iHeight==0).
  178488. */
  178489. static int rtreeInsertCell(
  178490. Rtree *pRtree,
  178491. RtreeNode *pNode,
  178492. RtreeCell *pCell,
  178493. int iHeight
  178494. ){
  178495. int rc = SQLITE_OK;
  178496. if( iHeight>0 ){
  178497. RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
  178498. if( pChild ){
  178499. nodeRelease(pRtree, pChild->pParent);
  178500. nodeReference(pNode);
  178501. pChild->pParent = pNode;
  178502. }
  178503. }
  178504. if( nodeInsertCell(pRtree, pNode, pCell) ){
  178505. if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
  178506. rc = SplitNode(pRtree, pNode, pCell, iHeight);
  178507. }else{
  178508. pRtree->iReinsertHeight = iHeight;
  178509. rc = Reinsert(pRtree, pNode, pCell, iHeight);
  178510. }
  178511. }else{
  178512. rc = AdjustTree(pRtree, pNode, pCell);
  178513. if( rc==SQLITE_OK ){
  178514. if( iHeight==0 ){
  178515. rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
  178516. }else{
  178517. rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
  178518. }
  178519. }
  178520. }
  178521. return rc;
  178522. }
  178523. static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
  178524. int ii;
  178525. int rc = SQLITE_OK;
  178526. int nCell = NCELL(pNode);
  178527. for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
  178528. RtreeNode *pInsert;
  178529. RtreeCell cell;
  178530. nodeGetCell(pRtree, pNode, ii, &cell);
  178531. /* Find a node to store this cell in. pNode->iNode currently contains
  178532. ** the height of the sub-tree headed by the cell.
  178533. */
  178534. rc = ChooseLeaf(pRtree, &cell, (int)pNode->iNode, &pInsert);
  178535. if( rc==SQLITE_OK ){
  178536. int rc2;
  178537. rc = rtreeInsertCell(pRtree, pInsert, &cell, (int)pNode->iNode);
  178538. rc2 = nodeRelease(pRtree, pInsert);
  178539. if( rc==SQLITE_OK ){
  178540. rc = rc2;
  178541. }
  178542. }
  178543. }
  178544. return rc;
  178545. }
  178546. /*
  178547. ** Select a currently unused rowid for a new r-tree record.
  178548. */
  178549. static int rtreeNewRowid(Rtree *pRtree, i64 *piRowid){
  178550. int rc;
  178551. sqlite3_bind_null(pRtree->pWriteRowid, 1);
  178552. sqlite3_bind_null(pRtree->pWriteRowid, 2);
  178553. sqlite3_step(pRtree->pWriteRowid);
  178554. rc = sqlite3_reset(pRtree->pWriteRowid);
  178555. *piRowid = sqlite3_last_insert_rowid(pRtree->db);
  178556. return rc;
  178557. }
  178558. /*
  178559. ** Remove the entry with rowid=iDelete from the r-tree structure.
  178560. */
  178561. static int rtreeDeleteRowid(Rtree *pRtree, sqlite3_int64 iDelete){
  178562. int rc; /* Return code */
  178563. RtreeNode *pLeaf = 0; /* Leaf node containing record iDelete */
  178564. int iCell; /* Index of iDelete cell in pLeaf */
  178565. RtreeNode *pRoot = 0; /* Root node of rtree structure */
  178566. /* Obtain a reference to the root node to initialize Rtree.iDepth */
  178567. rc = nodeAcquire(pRtree, 1, 0, &pRoot);
  178568. /* Obtain a reference to the leaf node that contains the entry
  178569. ** about to be deleted.
  178570. */
  178571. if( rc==SQLITE_OK ){
  178572. rc = findLeafNode(pRtree, iDelete, &pLeaf, 0);
  178573. }
  178574. #ifdef CORRUPT_DB
  178575. assert( pLeaf!=0 || rc!=SQLITE_OK || CORRUPT_DB );
  178576. #endif
  178577. /* Delete the cell in question from the leaf node. */
  178578. if( rc==SQLITE_OK && pLeaf ){
  178579. int rc2;
  178580. rc = nodeRowidIndex(pRtree, pLeaf, iDelete, &iCell);
  178581. if( rc==SQLITE_OK ){
  178582. rc = deleteCell(pRtree, pLeaf, iCell, 0);
  178583. }
  178584. rc2 = nodeRelease(pRtree, pLeaf);
  178585. if( rc==SQLITE_OK ){
  178586. rc = rc2;
  178587. }
  178588. }
  178589. /* Delete the corresponding entry in the <rtree>_rowid table. */
  178590. if( rc==SQLITE_OK ){
  178591. sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
  178592. sqlite3_step(pRtree->pDeleteRowid);
  178593. rc = sqlite3_reset(pRtree->pDeleteRowid);
  178594. }
  178595. /* Check if the root node now has exactly one child. If so, remove
  178596. ** it, schedule the contents of the child for reinsertion and
  178597. ** reduce the tree height by one.
  178598. **
  178599. ** This is equivalent to copying the contents of the child into
  178600. ** the root node (the operation that Gutman's paper says to perform
  178601. ** in this scenario).
  178602. */
  178603. if( rc==SQLITE_OK && pRtree->iDepth>0 && NCELL(pRoot)==1 ){
  178604. int rc2;
  178605. RtreeNode *pChild = 0;
  178606. i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
  178607. rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
  178608. if( rc==SQLITE_OK ){
  178609. rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
  178610. }
  178611. rc2 = nodeRelease(pRtree, pChild);
  178612. if( rc==SQLITE_OK ) rc = rc2;
  178613. if( rc==SQLITE_OK ){
  178614. pRtree->iDepth--;
  178615. writeInt16(pRoot->zData, pRtree->iDepth);
  178616. pRoot->isDirty = 1;
  178617. }
  178618. }
  178619. /* Re-insert the contents of any underfull nodes removed from the tree. */
  178620. for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
  178621. if( rc==SQLITE_OK ){
  178622. rc = reinsertNodeContent(pRtree, pLeaf);
  178623. }
  178624. pRtree->pDeleted = pLeaf->pNext;
  178625. pRtree->nNodeRef--;
  178626. sqlite3_free(pLeaf);
  178627. }
  178628. /* Release the reference to the root node. */
  178629. if( rc==SQLITE_OK ){
  178630. rc = nodeRelease(pRtree, pRoot);
  178631. }else{
  178632. nodeRelease(pRtree, pRoot);
  178633. }
  178634. return rc;
  178635. }
  178636. /*
  178637. ** Rounding constants for float->double conversion.
  178638. */
  178639. #define RNDTOWARDS (1.0 - 1.0/8388608.0) /* Round towards zero */
  178640. #define RNDAWAY (1.0 + 1.0/8388608.0) /* Round away from zero */
  178641. #if !defined(SQLITE_RTREE_INT_ONLY)
  178642. /*
  178643. ** Convert an sqlite3_value into an RtreeValue (presumably a float)
  178644. ** while taking care to round toward negative or positive, respectively.
  178645. */
  178646. static RtreeValue rtreeValueDown(sqlite3_value *v){
  178647. double d = sqlite3_value_double(v);
  178648. float f = (float)d;
  178649. if( f>d ){
  178650. f = (float)(d*(d<0 ? RNDAWAY : RNDTOWARDS));
  178651. }
  178652. return f;
  178653. }
  178654. static RtreeValue rtreeValueUp(sqlite3_value *v){
  178655. double d = sqlite3_value_double(v);
  178656. float f = (float)d;
  178657. if( f<d ){
  178658. f = (float)(d*(d<0 ? RNDTOWARDS : RNDAWAY));
  178659. }
  178660. return f;
  178661. }
  178662. #endif /* !defined(SQLITE_RTREE_INT_ONLY) */
  178663. /*
  178664. ** A constraint has failed while inserting a row into an rtree table.
  178665. ** Assuming no OOM error occurs, this function sets the error message
  178666. ** (at pRtree->base.zErrMsg) to an appropriate value and returns
  178667. ** SQLITE_CONSTRAINT.
  178668. **
  178669. ** Parameter iCol is the index of the leftmost column involved in the
  178670. ** constraint failure. If it is 0, then the constraint that failed is
  178671. ** the unique constraint on the id column. Otherwise, it is the rtree
  178672. ** (c1<=c2) constraint on columns iCol and iCol+1 that has failed.
  178673. **
  178674. ** If an OOM occurs, SQLITE_NOMEM is returned instead of SQLITE_CONSTRAINT.
  178675. */
  178676. static int rtreeConstraintError(Rtree *pRtree, int iCol){
  178677. sqlite3_stmt *pStmt = 0;
  178678. char *zSql;
  178679. int rc;
  178680. assert( iCol==0 || iCol%2 );
  178681. zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", pRtree->zDb, pRtree->zName);
  178682. if( zSql ){
  178683. rc = sqlite3_prepare_v2(pRtree->db, zSql, -1, &pStmt, 0);
  178684. }else{
  178685. rc = SQLITE_NOMEM;
  178686. }
  178687. sqlite3_free(zSql);
  178688. if( rc==SQLITE_OK ){
  178689. if( iCol==0 ){
  178690. const char *zCol = sqlite3_column_name(pStmt, 0);
  178691. pRtree->base.zErrMsg = sqlite3_mprintf(
  178692. "UNIQUE constraint failed: %s.%s", pRtree->zName, zCol
  178693. );
  178694. }else{
  178695. const char *zCol1 = sqlite3_column_name(pStmt, iCol);
  178696. const char *zCol2 = sqlite3_column_name(pStmt, iCol+1);
  178697. pRtree->base.zErrMsg = sqlite3_mprintf(
  178698. "rtree constraint failed: %s.(%s<=%s)", pRtree->zName, zCol1, zCol2
  178699. );
  178700. }
  178701. }
  178702. sqlite3_finalize(pStmt);
  178703. return (rc==SQLITE_OK ? SQLITE_CONSTRAINT : rc);
  178704. }
  178705. /*
  178706. ** The xUpdate method for rtree module virtual tables.
  178707. */
  178708. static int rtreeUpdate(
  178709. sqlite3_vtab *pVtab,
  178710. int nData,
  178711. sqlite3_value **aData,
  178712. sqlite_int64 *pRowid
  178713. ){
  178714. Rtree *pRtree = (Rtree *)pVtab;
  178715. int rc = SQLITE_OK;
  178716. RtreeCell cell; /* New cell to insert if nData>1 */
  178717. int bHaveRowid = 0; /* Set to 1 after new rowid is determined */
  178718. if( pRtree->nNodeRef ){
  178719. /* Unable to write to the btree while another cursor is reading from it,
  178720. ** since the write might do a rebalance which would disrupt the read
  178721. ** cursor. */
  178722. return SQLITE_LOCKED_VTAB;
  178723. }
  178724. rtreeReference(pRtree);
  178725. assert(nData>=1);
  178726. cell.iRowid = 0; /* Used only to suppress a compiler warning */
  178727. /* Constraint handling. A write operation on an r-tree table may return
  178728. ** SQLITE_CONSTRAINT for two reasons:
  178729. **
  178730. ** 1. A duplicate rowid value, or
  178731. ** 2. The supplied data violates the "x2>=x1" constraint.
  178732. **
  178733. ** In the first case, if the conflict-handling mode is REPLACE, then
  178734. ** the conflicting row can be removed before proceeding. In the second
  178735. ** case, SQLITE_CONSTRAINT must be returned regardless of the
  178736. ** conflict-handling mode specified by the user.
  178737. */
  178738. if( nData>1 ){
  178739. int ii;
  178740. int nn = nData - 4;
  178741. if( nn > pRtree->nDim2 ) nn = pRtree->nDim2;
  178742. /* Populate the cell.aCoord[] array. The first coordinate is aData[3].
  178743. **
  178744. ** NB: nData can only be less than nDim*2+3 if the rtree is mis-declared
  178745. ** with "column" that are interpreted as table constraints.
  178746. ** Example: CREATE VIRTUAL TABLE bad USING rtree(x,y,CHECK(y>5));
  178747. ** This problem was discovered after years of use, so we silently ignore
  178748. ** these kinds of misdeclared tables to avoid breaking any legacy.
  178749. */
  178750. #ifndef SQLITE_RTREE_INT_ONLY
  178751. if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
  178752. for(ii=0; ii<nn; ii+=2){
  178753. cell.aCoord[ii].f = rtreeValueDown(aData[ii+3]);
  178754. cell.aCoord[ii+1].f = rtreeValueUp(aData[ii+4]);
  178755. if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
  178756. rc = rtreeConstraintError(pRtree, ii+1);
  178757. goto constraint;
  178758. }
  178759. }
  178760. }else
  178761. #endif
  178762. {
  178763. for(ii=0; ii<nn; ii+=2){
  178764. cell.aCoord[ii].i = sqlite3_value_int(aData[ii+3]);
  178765. cell.aCoord[ii+1].i = sqlite3_value_int(aData[ii+4]);
  178766. if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
  178767. rc = rtreeConstraintError(pRtree, ii+1);
  178768. goto constraint;
  178769. }
  178770. }
  178771. }
  178772. /* If a rowid value was supplied, check if it is already present in
  178773. ** the table. If so, the constraint has failed. */
  178774. if( sqlite3_value_type(aData[2])!=SQLITE_NULL ){
  178775. cell.iRowid = sqlite3_value_int64(aData[2]);
  178776. if( sqlite3_value_type(aData[0])==SQLITE_NULL
  178777. || sqlite3_value_int64(aData[0])!=cell.iRowid
  178778. ){
  178779. int steprc;
  178780. sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
  178781. steprc = sqlite3_step(pRtree->pReadRowid);
  178782. rc = sqlite3_reset(pRtree->pReadRowid);
  178783. if( SQLITE_ROW==steprc ){
  178784. if( sqlite3_vtab_on_conflict(pRtree->db)==SQLITE_REPLACE ){
  178785. rc = rtreeDeleteRowid(pRtree, cell.iRowid);
  178786. }else{
  178787. rc = rtreeConstraintError(pRtree, 0);
  178788. goto constraint;
  178789. }
  178790. }
  178791. }
  178792. bHaveRowid = 1;
  178793. }
  178794. }
  178795. /* If aData[0] is not an SQL NULL value, it is the rowid of a
  178796. ** record to delete from the r-tree table. The following block does
  178797. ** just that.
  178798. */
  178799. if( sqlite3_value_type(aData[0])!=SQLITE_NULL ){
  178800. rc = rtreeDeleteRowid(pRtree, sqlite3_value_int64(aData[0]));
  178801. }
  178802. /* If the aData[] array contains more than one element, elements
  178803. ** (aData[2]..aData[argc-1]) contain a new record to insert into
  178804. ** the r-tree structure.
  178805. */
  178806. if( rc==SQLITE_OK && nData>1 ){
  178807. /* Insert the new record into the r-tree */
  178808. RtreeNode *pLeaf = 0;
  178809. /* Figure out the rowid of the new row. */
  178810. if( bHaveRowid==0 ){
  178811. rc = rtreeNewRowid(pRtree, &cell.iRowid);
  178812. }
  178813. *pRowid = cell.iRowid;
  178814. if( rc==SQLITE_OK ){
  178815. rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
  178816. }
  178817. if( rc==SQLITE_OK ){
  178818. int rc2;
  178819. pRtree->iReinsertHeight = -1;
  178820. rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
  178821. rc2 = nodeRelease(pRtree, pLeaf);
  178822. if( rc==SQLITE_OK ){
  178823. rc = rc2;
  178824. }
  178825. }
  178826. if( rc==SQLITE_OK && pRtree->nAux ){
  178827. sqlite3_stmt *pUp = pRtree->pWriteAux;
  178828. int jj;
  178829. sqlite3_bind_int64(pUp, 1, *pRowid);
  178830. for(jj=0; jj<pRtree->nAux; jj++){
  178831. sqlite3_bind_value(pUp, jj+2, aData[pRtree->nDim2+3+jj]);
  178832. }
  178833. sqlite3_step(pUp);
  178834. rc = sqlite3_reset(pUp);
  178835. }
  178836. }
  178837. constraint:
  178838. rtreeRelease(pRtree);
  178839. return rc;
  178840. }
  178841. /*
  178842. ** Called when a transaction starts.
  178843. */
  178844. static int rtreeBeginTransaction(sqlite3_vtab *pVtab){
  178845. Rtree *pRtree = (Rtree *)pVtab;
  178846. assert( pRtree->inWrTrans==0 );
  178847. pRtree->inWrTrans++;
  178848. return SQLITE_OK;
  178849. }
  178850. /*
  178851. ** Called when a transaction completes (either by COMMIT or ROLLBACK).
  178852. ** The sqlite3_blob object should be released at this point.
  178853. */
  178854. static int rtreeEndTransaction(sqlite3_vtab *pVtab){
  178855. Rtree *pRtree = (Rtree *)pVtab;
  178856. pRtree->inWrTrans = 0;
  178857. nodeBlobReset(pRtree);
  178858. return SQLITE_OK;
  178859. }
  178860. /*
  178861. ** The xRename method for rtree module virtual tables.
  178862. */
  178863. static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
  178864. Rtree *pRtree = (Rtree *)pVtab;
  178865. int rc = SQLITE_NOMEM;
  178866. char *zSql = sqlite3_mprintf(
  178867. "ALTER TABLE %Q.'%q_node' RENAME TO \"%w_node\";"
  178868. "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
  178869. "ALTER TABLE %Q.'%q_rowid' RENAME TO \"%w_rowid\";"
  178870. , pRtree->zDb, pRtree->zName, zNewName
  178871. , pRtree->zDb, pRtree->zName, zNewName
  178872. , pRtree->zDb, pRtree->zName, zNewName
  178873. );
  178874. if( zSql ){
  178875. nodeBlobReset(pRtree);
  178876. rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
  178877. sqlite3_free(zSql);
  178878. }
  178879. return rc;
  178880. }
  178881. /*
  178882. ** The xSavepoint method.
  178883. **
  178884. ** This module does not need to do anything to support savepoints. However,
  178885. ** it uses this hook to close any open blob handle. This is done because a
  178886. ** DROP TABLE command - which fortunately always opens a savepoint - cannot
  178887. ** succeed if there are any open blob handles. i.e. if the blob handle were
  178888. ** not closed here, the following would fail:
  178889. **
  178890. ** BEGIN;
  178891. ** INSERT INTO rtree...
  178892. ** DROP TABLE <tablename>; -- Would fail with SQLITE_LOCKED
  178893. ** COMMIT;
  178894. */
  178895. static int rtreeSavepoint(sqlite3_vtab *pVtab, int iSavepoint){
  178896. Rtree *pRtree = (Rtree *)pVtab;
  178897. u8 iwt = pRtree->inWrTrans;
  178898. UNUSED_PARAMETER(iSavepoint);
  178899. pRtree->inWrTrans = 0;
  178900. nodeBlobReset(pRtree);
  178901. pRtree->inWrTrans = iwt;
  178902. return SQLITE_OK;
  178903. }
  178904. /*
  178905. ** This function populates the pRtree->nRowEst variable with an estimate
  178906. ** of the number of rows in the virtual table. If possible, this is based
  178907. ** on sqlite_stat1 data. Otherwise, use RTREE_DEFAULT_ROWEST.
  178908. */
  178909. static int rtreeQueryStat1(sqlite3 *db, Rtree *pRtree){
  178910. const char *zFmt = "SELECT stat FROM %Q.sqlite_stat1 WHERE tbl = '%q_rowid'";
  178911. char *zSql;
  178912. sqlite3_stmt *p;
  178913. int rc;
  178914. i64 nRow = 0;
  178915. rc = sqlite3_table_column_metadata(
  178916. db, pRtree->zDb, "sqlite_stat1",0,0,0,0,0,0
  178917. );
  178918. if( rc!=SQLITE_OK ){
  178919. pRtree->nRowEst = RTREE_DEFAULT_ROWEST;
  178920. return rc==SQLITE_ERROR ? SQLITE_OK : rc;
  178921. }
  178922. zSql = sqlite3_mprintf(zFmt, pRtree->zDb, pRtree->zName);
  178923. if( zSql==0 ){
  178924. rc = SQLITE_NOMEM;
  178925. }else{
  178926. rc = sqlite3_prepare_v2(db, zSql, -1, &p, 0);
  178927. if( rc==SQLITE_OK ){
  178928. if( sqlite3_step(p)==SQLITE_ROW ) nRow = sqlite3_column_int64(p, 0);
  178929. rc = sqlite3_finalize(p);
  178930. }else if( rc!=SQLITE_NOMEM ){
  178931. rc = SQLITE_OK;
  178932. }
  178933. if( rc==SQLITE_OK ){
  178934. if( nRow==0 ){
  178935. pRtree->nRowEst = RTREE_DEFAULT_ROWEST;
  178936. }else{
  178937. pRtree->nRowEst = MAX(nRow, RTREE_MIN_ROWEST);
  178938. }
  178939. }
  178940. sqlite3_free(zSql);
  178941. }
  178942. return rc;
  178943. }
  178944. /*
  178945. ** Return true if zName is the extension on one of the shadow tables used
  178946. ** by this module.
  178947. */
  178948. static int rtreeShadowName(const char *zName){
  178949. static const char *azName[] = {
  178950. "node", "parent", "rowid"
  178951. };
  178952. unsigned int i;
  178953. for(i=0; i<sizeof(azName)/sizeof(azName[0]); i++){
  178954. if( sqlite3_stricmp(zName, azName[i])==0 ) return 1;
  178955. }
  178956. return 0;
  178957. }
  178958. static sqlite3_module rtreeModule = {
  178959. 3, /* iVersion */
  178960. rtreeCreate, /* xCreate - create a table */
  178961. rtreeConnect, /* xConnect - connect to an existing table */
  178962. rtreeBestIndex, /* xBestIndex - Determine search strategy */
  178963. rtreeDisconnect, /* xDisconnect - Disconnect from a table */
  178964. rtreeDestroy, /* xDestroy - Drop a table */
  178965. rtreeOpen, /* xOpen - open a cursor */
  178966. rtreeClose, /* xClose - close a cursor */
  178967. rtreeFilter, /* xFilter - configure scan constraints */
  178968. rtreeNext, /* xNext - advance a cursor */
  178969. rtreeEof, /* xEof */
  178970. rtreeColumn, /* xColumn - read data */
  178971. rtreeRowid, /* xRowid - read data */
  178972. rtreeUpdate, /* xUpdate - write data */
  178973. rtreeBeginTransaction, /* xBegin - begin transaction */
  178974. rtreeEndTransaction, /* xSync - sync transaction */
  178975. rtreeEndTransaction, /* xCommit - commit transaction */
  178976. rtreeEndTransaction, /* xRollback - rollback transaction */
  178977. 0, /* xFindFunction - function overloading */
  178978. rtreeRename, /* xRename - rename the table */
  178979. rtreeSavepoint, /* xSavepoint */
  178980. 0, /* xRelease */
  178981. 0, /* xRollbackTo */
  178982. rtreeShadowName /* xShadowName */
  178983. };
  178984. static int rtreeSqlInit(
  178985. Rtree *pRtree,
  178986. sqlite3 *db,
  178987. const char *zDb,
  178988. const char *zPrefix,
  178989. int isCreate
  178990. ){
  178991. int rc = SQLITE_OK;
  178992. #define N_STATEMENT 8
  178993. static const char *azSql[N_STATEMENT] = {
  178994. /* Write the xxx_node table */
  178995. "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(?1, ?2)",
  178996. "DELETE FROM '%q'.'%q_node' WHERE nodeno = ?1",
  178997. /* Read and write the xxx_rowid table */
  178998. "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = ?1",
  178999. "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(?1, ?2)",
  179000. "DELETE FROM '%q'.'%q_rowid' WHERE rowid = ?1",
  179001. /* Read and write the xxx_parent table */
  179002. "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = ?1",
  179003. "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(?1, ?2)",
  179004. "DELETE FROM '%q'.'%q_parent' WHERE nodeno = ?1"
  179005. };
  179006. sqlite3_stmt **appStmt[N_STATEMENT];
  179007. int i;
  179008. const int f = SQLITE_PREPARE_PERSISTENT|SQLITE_PREPARE_NO_VTAB;
  179009. pRtree->db = db;
  179010. if( isCreate ){
  179011. char *zCreate;
  179012. sqlite3_str *p = sqlite3_str_new(db);
  179013. int ii;
  179014. sqlite3_str_appendf(p,
  179015. "CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY,nodeno",
  179016. zDb, zPrefix);
  179017. for(ii=0; ii<pRtree->nAux; ii++){
  179018. sqlite3_str_appendf(p,",a%d",ii);
  179019. }
  179020. sqlite3_str_appendf(p,
  179021. ");CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY,data);",
  179022. zDb, zPrefix);
  179023. sqlite3_str_appendf(p,
  179024. "CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY,parentnode);",
  179025. zDb, zPrefix);
  179026. sqlite3_str_appendf(p,
  179027. "INSERT INTO \"%w\".\"%w_node\"VALUES(1,zeroblob(%d))",
  179028. zDb, zPrefix, pRtree->iNodeSize);
  179029. zCreate = sqlite3_str_finish(p);
  179030. if( !zCreate ){
  179031. return SQLITE_NOMEM;
  179032. }
  179033. rc = sqlite3_exec(db, zCreate, 0, 0, 0);
  179034. sqlite3_free(zCreate);
  179035. if( rc!=SQLITE_OK ){
  179036. return rc;
  179037. }
  179038. }
  179039. appStmt[0] = &pRtree->pWriteNode;
  179040. appStmt[1] = &pRtree->pDeleteNode;
  179041. appStmt[2] = &pRtree->pReadRowid;
  179042. appStmt[3] = &pRtree->pWriteRowid;
  179043. appStmt[4] = &pRtree->pDeleteRowid;
  179044. appStmt[5] = &pRtree->pReadParent;
  179045. appStmt[6] = &pRtree->pWriteParent;
  179046. appStmt[7] = &pRtree->pDeleteParent;
  179047. rc = rtreeQueryStat1(db, pRtree);
  179048. for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
  179049. char *zSql;
  179050. const char *zFormat;
  179051. if( i!=3 || pRtree->nAux==0 ){
  179052. zFormat = azSql[i];
  179053. }else {
  179054. /* An UPSERT is very slightly slower than REPLACE, but it is needed
  179055. ** if there are auxiliary columns */
  179056. zFormat = "INSERT INTO\"%w\".\"%w_rowid\"(rowid,nodeno)VALUES(?1,?2)"
  179057. "ON CONFLICT(rowid)DO UPDATE SET nodeno=excluded.nodeno";
  179058. }
  179059. zSql = sqlite3_mprintf(zFormat, zDb, zPrefix);
  179060. if( zSql ){
  179061. rc = sqlite3_prepare_v3(db, zSql, -1, f, appStmt[i], 0);
  179062. }else{
  179063. rc = SQLITE_NOMEM;
  179064. }
  179065. sqlite3_free(zSql);
  179066. }
  179067. if( pRtree->nAux ){
  179068. pRtree->zReadAuxSql = sqlite3_mprintf(
  179069. "SELECT * FROM \"%w\".\"%w_rowid\" WHERE rowid=?1",
  179070. zDb, zPrefix);
  179071. if( pRtree->zReadAuxSql==0 ){
  179072. rc = SQLITE_NOMEM;
  179073. }else{
  179074. sqlite3_str *p = sqlite3_str_new(db);
  179075. int ii;
  179076. char *zSql;
  179077. sqlite3_str_appendf(p, "UPDATE \"%w\".\"%w_rowid\"SET ", zDb, zPrefix);
  179078. for(ii=0; ii<pRtree->nAux; ii++){
  179079. if( ii ) sqlite3_str_append(p, ",", 1);
  179080. if( ii<pRtree->nAuxNotNull ){
  179081. sqlite3_str_appendf(p,"a%d=coalesce(?%d,a%d)",ii,ii+2,ii);
  179082. }else{
  179083. sqlite3_str_appendf(p,"a%d=?%d",ii,ii+2);
  179084. }
  179085. }
  179086. sqlite3_str_appendf(p, " WHERE rowid=?1");
  179087. zSql = sqlite3_str_finish(p);
  179088. if( zSql==0 ){
  179089. rc = SQLITE_NOMEM;
  179090. }else{
  179091. rc = sqlite3_prepare_v3(db, zSql, -1, f, &pRtree->pWriteAux, 0);
  179092. sqlite3_free(zSql);
  179093. }
  179094. }
  179095. }
  179096. return rc;
  179097. }
  179098. /*
  179099. ** The second argument to this function contains the text of an SQL statement
  179100. ** that returns a single integer value. The statement is compiled and executed
  179101. ** using database connection db. If successful, the integer value returned
  179102. ** is written to *piVal and SQLITE_OK returned. Otherwise, an SQLite error
  179103. ** code is returned and the value of *piVal after returning is not defined.
  179104. */
  179105. static int getIntFromStmt(sqlite3 *db, const char *zSql, int *piVal){
  179106. int rc = SQLITE_NOMEM;
  179107. if( zSql ){
  179108. sqlite3_stmt *pStmt = 0;
  179109. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  179110. if( rc==SQLITE_OK ){
  179111. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  179112. *piVal = sqlite3_column_int(pStmt, 0);
  179113. }
  179114. rc = sqlite3_finalize(pStmt);
  179115. }
  179116. }
  179117. return rc;
  179118. }
  179119. /*
  179120. ** This function is called from within the xConnect() or xCreate() method to
  179121. ** determine the node-size used by the rtree table being created or connected
  179122. ** to. If successful, pRtree->iNodeSize is populated and SQLITE_OK returned.
  179123. ** Otherwise, an SQLite error code is returned.
  179124. **
  179125. ** If this function is being called as part of an xConnect(), then the rtree
  179126. ** table already exists. In this case the node-size is determined by inspecting
  179127. ** the root node of the tree.
  179128. **
  179129. ** Otherwise, for an xCreate(), use 64 bytes less than the database page-size.
  179130. ** This ensures that each node is stored on a single database page. If the
  179131. ** database page-size is so large that more than RTREE_MAXCELLS entries
  179132. ** would fit in a single node, use a smaller node-size.
  179133. */
  179134. static int getNodeSize(
  179135. sqlite3 *db, /* Database handle */
  179136. Rtree *pRtree, /* Rtree handle */
  179137. int isCreate, /* True for xCreate, false for xConnect */
  179138. char **pzErr /* OUT: Error message, if any */
  179139. ){
  179140. int rc;
  179141. char *zSql;
  179142. if( isCreate ){
  179143. int iPageSize = 0;
  179144. zSql = sqlite3_mprintf("PRAGMA %Q.page_size", pRtree->zDb);
  179145. rc = getIntFromStmt(db, zSql, &iPageSize);
  179146. if( rc==SQLITE_OK ){
  179147. pRtree->iNodeSize = iPageSize-64;
  179148. if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
  179149. pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
  179150. }
  179151. }else{
  179152. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  179153. }
  179154. }else{
  179155. zSql = sqlite3_mprintf(
  179156. "SELECT length(data) FROM '%q'.'%q_node' WHERE nodeno = 1",
  179157. pRtree->zDb, pRtree->zName
  179158. );
  179159. rc = getIntFromStmt(db, zSql, &pRtree->iNodeSize);
  179160. if( rc!=SQLITE_OK ){
  179161. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  179162. }else if( pRtree->iNodeSize<(512-64) ){
  179163. rc = SQLITE_CORRUPT_VTAB;
  179164. RTREE_IS_CORRUPT(pRtree);
  179165. *pzErr = sqlite3_mprintf("undersize RTree blobs in \"%q_node\"",
  179166. pRtree->zName);
  179167. }
  179168. }
  179169. sqlite3_free(zSql);
  179170. return rc;
  179171. }
  179172. /*
  179173. ** Return the length of a token
  179174. */
  179175. static int rtreeTokenLength(const char *z){
  179176. int dummy = 0;
  179177. return sqlite3GetToken((const unsigned char*)z,&dummy);
  179178. }
  179179. /*
  179180. ** This function is the implementation of both the xConnect and xCreate
  179181. ** methods of the r-tree virtual table.
  179182. **
  179183. ** argv[0] -> module name
  179184. ** argv[1] -> database name
  179185. ** argv[2] -> table name
  179186. ** argv[...] -> column names...
  179187. */
  179188. static int rtreeInit(
  179189. sqlite3 *db, /* Database connection */
  179190. void *pAux, /* One of the RTREE_COORD_* constants */
  179191. int argc, const char *const*argv, /* Parameters to CREATE TABLE statement */
  179192. sqlite3_vtab **ppVtab, /* OUT: New virtual table */
  179193. char **pzErr, /* OUT: Error message, if any */
  179194. int isCreate /* True for xCreate, false for xConnect */
  179195. ){
  179196. int rc = SQLITE_OK;
  179197. Rtree *pRtree;
  179198. int nDb; /* Length of string argv[1] */
  179199. int nName; /* Length of string argv[2] */
  179200. int eCoordType = (pAux ? RTREE_COORD_INT32 : RTREE_COORD_REAL32);
  179201. sqlite3_str *pSql;
  179202. char *zSql;
  179203. int ii = 4;
  179204. int iErr;
  179205. const char *aErrMsg[] = {
  179206. 0, /* 0 */
  179207. "Wrong number of columns for an rtree table", /* 1 */
  179208. "Too few columns for an rtree table", /* 2 */
  179209. "Too many columns for an rtree table", /* 3 */
  179210. "Auxiliary rtree columns must be last" /* 4 */
  179211. };
  179212. assert( RTREE_MAX_AUX_COLUMN<256 ); /* Aux columns counted by a u8 */
  179213. if( argc<6 || argc>RTREE_MAX_AUX_COLUMN+3 ){
  179214. *pzErr = sqlite3_mprintf("%s", aErrMsg[2 + (argc>=6)]);
  179215. return SQLITE_ERROR;
  179216. }
  179217. sqlite3_vtab_config(db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
  179218. /* Allocate the sqlite3_vtab structure */
  179219. nDb = (int)strlen(argv[1]);
  179220. nName = (int)strlen(argv[2]);
  179221. pRtree = (Rtree *)sqlite3_malloc64(sizeof(Rtree)+nDb+nName+2);
  179222. if( !pRtree ){
  179223. return SQLITE_NOMEM;
  179224. }
  179225. memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
  179226. pRtree->nBusy = 1;
  179227. pRtree->base.pModule = &rtreeModule;
  179228. pRtree->zDb = (char *)&pRtree[1];
  179229. pRtree->zName = &pRtree->zDb[nDb+1];
  179230. pRtree->eCoordType = (u8)eCoordType;
  179231. memcpy(pRtree->zDb, argv[1], nDb);
  179232. memcpy(pRtree->zName, argv[2], nName);
  179233. /* Create/Connect to the underlying relational database schema. If
  179234. ** that is successful, call sqlite3_declare_vtab() to configure
  179235. ** the r-tree table schema.
  179236. */
  179237. pSql = sqlite3_str_new(db);
  179238. sqlite3_str_appendf(pSql, "CREATE TABLE x(%.*s INT",
  179239. rtreeTokenLength(argv[3]), argv[3]);
  179240. for(ii=4; ii<argc; ii++){
  179241. const char *zArg = argv[ii];
  179242. if( zArg[0]=='+' ){
  179243. pRtree->nAux++;
  179244. sqlite3_str_appendf(pSql, ",%.*s", rtreeTokenLength(zArg+1), zArg+1);
  179245. }else if( pRtree->nAux>0 ){
  179246. break;
  179247. }else{
  179248. static const char *azFormat[] = {",%.*s REAL", ",%.*s INT"};
  179249. pRtree->nDim2++;
  179250. sqlite3_str_appendf(pSql, azFormat[eCoordType],
  179251. rtreeTokenLength(zArg), zArg);
  179252. }
  179253. }
  179254. sqlite3_str_appendf(pSql, ");");
  179255. zSql = sqlite3_str_finish(pSql);
  179256. if( !zSql ){
  179257. rc = SQLITE_NOMEM;
  179258. }else if( ii<argc ){
  179259. *pzErr = sqlite3_mprintf("%s", aErrMsg[4]);
  179260. rc = SQLITE_ERROR;
  179261. }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
  179262. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  179263. }
  179264. sqlite3_free(zSql);
  179265. if( rc ) goto rtreeInit_fail;
  179266. pRtree->nDim = pRtree->nDim2/2;
  179267. if( pRtree->nDim<1 ){
  179268. iErr = 2;
  179269. }else if( pRtree->nDim2>RTREE_MAX_DIMENSIONS*2 ){
  179270. iErr = 3;
  179271. }else if( pRtree->nDim2 % 2 ){
  179272. iErr = 1;
  179273. }else{
  179274. iErr = 0;
  179275. }
  179276. if( iErr ){
  179277. *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
  179278. goto rtreeInit_fail;
  179279. }
  179280. pRtree->nBytesPerCell = 8 + pRtree->nDim2*4;
  179281. /* Figure out the node size to use. */
  179282. rc = getNodeSize(db, pRtree, isCreate, pzErr);
  179283. if( rc ) goto rtreeInit_fail;
  179284. rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate);
  179285. if( rc ){
  179286. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  179287. goto rtreeInit_fail;
  179288. }
  179289. *ppVtab = (sqlite3_vtab *)pRtree;
  179290. return SQLITE_OK;
  179291. rtreeInit_fail:
  179292. if( rc==SQLITE_OK ) rc = SQLITE_ERROR;
  179293. assert( *ppVtab==0 );
  179294. assert( pRtree->nBusy==1 );
  179295. rtreeRelease(pRtree);
  179296. return rc;
  179297. }
  179298. /*
  179299. ** Implementation of a scalar function that decodes r-tree nodes to
  179300. ** human readable strings. This can be used for debugging and analysis.
  179301. **
  179302. ** The scalar function takes two arguments: (1) the number of dimensions
  179303. ** to the rtree (between 1 and 5, inclusive) and (2) a blob of data containing
  179304. ** an r-tree node. For a two-dimensional r-tree structure called "rt", to
  179305. ** deserialize all nodes, a statement like:
  179306. **
  179307. ** SELECT rtreenode(2, data) FROM rt_node;
  179308. **
  179309. ** The human readable string takes the form of a Tcl list with one
  179310. ** entry for each cell in the r-tree node. Each entry is itself a
  179311. ** list, containing the 8-byte rowid/pageno followed by the
  179312. ** <num-dimension>*2 coordinates.
  179313. */
  179314. static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
  179315. RtreeNode node;
  179316. Rtree tree;
  179317. int ii;
  179318. int nData;
  179319. int errCode;
  179320. sqlite3_str *pOut;
  179321. UNUSED_PARAMETER(nArg);
  179322. memset(&node, 0, sizeof(RtreeNode));
  179323. memset(&tree, 0, sizeof(Rtree));
  179324. tree.nDim = (u8)sqlite3_value_int(apArg[0]);
  179325. if( tree.nDim<1 || tree.nDim>5 ) return;
  179326. tree.nDim2 = tree.nDim*2;
  179327. tree.nBytesPerCell = 8 + 8 * tree.nDim;
  179328. node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
  179329. nData = sqlite3_value_bytes(apArg[1]);
  179330. if( nData<4 ) return;
  179331. if( nData<NCELL(&node)*tree.nBytesPerCell ) return;
  179332. pOut = sqlite3_str_new(0);
  179333. for(ii=0; ii<NCELL(&node); ii++){
  179334. RtreeCell cell;
  179335. int jj;
  179336. nodeGetCell(&tree, &node, ii, &cell);
  179337. if( ii>0 ) sqlite3_str_append(pOut, " ", 1);
  179338. sqlite3_str_appendf(pOut, "{%lld", cell.iRowid);
  179339. for(jj=0; jj<tree.nDim2; jj++){
  179340. #ifndef SQLITE_RTREE_INT_ONLY
  179341. sqlite3_str_appendf(pOut, " %g", (double)cell.aCoord[jj].f);
  179342. #else
  179343. sqlite3_str_appendf(pOut, " %d", cell.aCoord[jj].i);
  179344. #endif
  179345. }
  179346. sqlite3_str_append(pOut, "}", 1);
  179347. }
  179348. errCode = sqlite3_str_errcode(pOut);
  179349. sqlite3_result_text(ctx, sqlite3_str_finish(pOut), -1, sqlite3_free);
  179350. sqlite3_result_error_code(ctx, errCode);
  179351. }
  179352. /* This routine implements an SQL function that returns the "depth" parameter
  179353. ** from the front of a blob that is an r-tree node. For example:
  179354. **
  179355. ** SELECT rtreedepth(data) FROM rt_node WHERE nodeno=1;
  179356. **
  179357. ** The depth value is 0 for all nodes other than the root node, and the root
  179358. ** node always has nodeno=1, so the example above is the primary use for this
  179359. ** routine. This routine is intended for testing and analysis only.
  179360. */
  179361. static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
  179362. UNUSED_PARAMETER(nArg);
  179363. if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB
  179364. || sqlite3_value_bytes(apArg[0])<2
  179365. ){
  179366. sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1);
  179367. }else{
  179368. u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
  179369. sqlite3_result_int(ctx, readInt16(zBlob));
  179370. }
  179371. }
  179372. /*
  179373. ** Context object passed between the various routines that make up the
  179374. ** implementation of integrity-check function rtreecheck().
  179375. */
  179376. typedef struct RtreeCheck RtreeCheck;
  179377. struct RtreeCheck {
  179378. sqlite3 *db; /* Database handle */
  179379. const char *zDb; /* Database containing rtree table */
  179380. const char *zTab; /* Name of rtree table */
  179381. int bInt; /* True for rtree_i32 table */
  179382. int nDim; /* Number of dimensions for this rtree tbl */
  179383. sqlite3_stmt *pGetNode; /* Statement used to retrieve nodes */
  179384. sqlite3_stmt *aCheckMapping[2]; /* Statements to query %_parent/%_rowid */
  179385. int nLeaf; /* Number of leaf cells in table */
  179386. int nNonLeaf; /* Number of non-leaf cells in table */
  179387. int rc; /* Return code */
  179388. char *zReport; /* Message to report */
  179389. int nErr; /* Number of lines in zReport */
  179390. };
  179391. #define RTREE_CHECK_MAX_ERROR 100
  179392. /*
  179393. ** Reset SQL statement pStmt. If the sqlite3_reset() call returns an error,
  179394. ** and RtreeCheck.rc==SQLITE_OK, set RtreeCheck.rc to the error code.
  179395. */
  179396. static void rtreeCheckReset(RtreeCheck *pCheck, sqlite3_stmt *pStmt){
  179397. int rc = sqlite3_reset(pStmt);
  179398. if( pCheck->rc==SQLITE_OK ) pCheck->rc = rc;
  179399. }
  179400. /*
  179401. ** The second and subsequent arguments to this function are a format string
  179402. ** and printf style arguments. This function formats the string and attempts
  179403. ** to compile it as an SQL statement.
  179404. **
  179405. ** If successful, a pointer to the new SQL statement is returned. Otherwise,
  179406. ** NULL is returned and an error code left in RtreeCheck.rc.
  179407. */
  179408. static sqlite3_stmt *rtreeCheckPrepare(
  179409. RtreeCheck *pCheck, /* RtreeCheck object */
  179410. const char *zFmt, ... /* Format string and trailing args */
  179411. ){
  179412. va_list ap;
  179413. char *z;
  179414. sqlite3_stmt *pRet = 0;
  179415. va_start(ap, zFmt);
  179416. z = sqlite3_vmprintf(zFmt, ap);
  179417. if( pCheck->rc==SQLITE_OK ){
  179418. if( z==0 ){
  179419. pCheck->rc = SQLITE_NOMEM;
  179420. }else{
  179421. pCheck->rc = sqlite3_prepare_v2(pCheck->db, z, -1, &pRet, 0);
  179422. }
  179423. }
  179424. sqlite3_free(z);
  179425. va_end(ap);
  179426. return pRet;
  179427. }
  179428. /*
  179429. ** The second and subsequent arguments to this function are a printf()
  179430. ** style format string and arguments. This function formats the string and
  179431. ** appends it to the report being accumuated in pCheck.
  179432. */
  179433. static void rtreeCheckAppendMsg(RtreeCheck *pCheck, const char *zFmt, ...){
  179434. va_list ap;
  179435. va_start(ap, zFmt);
  179436. if( pCheck->rc==SQLITE_OK && pCheck->nErr<RTREE_CHECK_MAX_ERROR ){
  179437. char *z = sqlite3_vmprintf(zFmt, ap);
  179438. if( z==0 ){
  179439. pCheck->rc = SQLITE_NOMEM;
  179440. }else{
  179441. pCheck->zReport = sqlite3_mprintf("%z%s%z",
  179442. pCheck->zReport, (pCheck->zReport ? "\n" : ""), z
  179443. );
  179444. if( pCheck->zReport==0 ){
  179445. pCheck->rc = SQLITE_NOMEM;
  179446. }
  179447. }
  179448. pCheck->nErr++;
  179449. }
  179450. va_end(ap);
  179451. }
  179452. /*
  179453. ** This function is a no-op if there is already an error code stored
  179454. ** in the RtreeCheck object indicated by the first argument. NULL is
  179455. ** returned in this case.
  179456. **
  179457. ** Otherwise, the contents of rtree table node iNode are loaded from
  179458. ** the database and copied into a buffer obtained from sqlite3_malloc().
  179459. ** If no error occurs, a pointer to the buffer is returned and (*pnNode)
  179460. ** is set to the size of the buffer in bytes.
  179461. **
  179462. ** Or, if an error does occur, NULL is returned and an error code left
  179463. ** in the RtreeCheck object. The final value of *pnNode is undefined in
  179464. ** this case.
  179465. */
  179466. static u8 *rtreeCheckGetNode(RtreeCheck *pCheck, i64 iNode, int *pnNode){
  179467. u8 *pRet = 0; /* Return value */
  179468. if( pCheck->rc==SQLITE_OK && pCheck->pGetNode==0 ){
  179469. pCheck->pGetNode = rtreeCheckPrepare(pCheck,
  179470. "SELECT data FROM %Q.'%q_node' WHERE nodeno=?",
  179471. pCheck->zDb, pCheck->zTab
  179472. );
  179473. }
  179474. if( pCheck->rc==SQLITE_OK ){
  179475. sqlite3_bind_int64(pCheck->pGetNode, 1, iNode);
  179476. if( sqlite3_step(pCheck->pGetNode)==SQLITE_ROW ){
  179477. int nNode = sqlite3_column_bytes(pCheck->pGetNode, 0);
  179478. const u8 *pNode = (const u8*)sqlite3_column_blob(pCheck->pGetNode, 0);
  179479. pRet = sqlite3_malloc64(nNode);
  179480. if( pRet==0 ){
  179481. pCheck->rc = SQLITE_NOMEM;
  179482. }else{
  179483. memcpy(pRet, pNode, nNode);
  179484. *pnNode = nNode;
  179485. }
  179486. }
  179487. rtreeCheckReset(pCheck, pCheck->pGetNode);
  179488. if( pCheck->rc==SQLITE_OK && pRet==0 ){
  179489. rtreeCheckAppendMsg(pCheck, "Node %lld missing from database", iNode);
  179490. }
  179491. }
  179492. return pRet;
  179493. }
  179494. /*
  179495. ** This function is used to check that the %_parent (if bLeaf==0) or %_rowid
  179496. ** (if bLeaf==1) table contains a specified entry. The schemas of the
  179497. ** two tables are:
  179498. **
  179499. ** CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)
  179500. ** CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER, ...)
  179501. **
  179502. ** In both cases, this function checks that there exists an entry with
  179503. ** IPK value iKey and the second column set to iVal.
  179504. **
  179505. */
  179506. static void rtreeCheckMapping(
  179507. RtreeCheck *pCheck, /* RtreeCheck object */
  179508. int bLeaf, /* True for a leaf cell, false for interior */
  179509. i64 iKey, /* Key for mapping */
  179510. i64 iVal /* Expected value for mapping */
  179511. ){
  179512. int rc;
  179513. sqlite3_stmt *pStmt;
  179514. const char *azSql[2] = {
  179515. "SELECT parentnode FROM %Q.'%q_parent' WHERE nodeno=?1",
  179516. "SELECT nodeno FROM %Q.'%q_rowid' WHERE rowid=?1"
  179517. };
  179518. assert( bLeaf==0 || bLeaf==1 );
  179519. if( pCheck->aCheckMapping[bLeaf]==0 ){
  179520. pCheck->aCheckMapping[bLeaf] = rtreeCheckPrepare(pCheck,
  179521. azSql[bLeaf], pCheck->zDb, pCheck->zTab
  179522. );
  179523. }
  179524. if( pCheck->rc!=SQLITE_OK ) return;
  179525. pStmt = pCheck->aCheckMapping[bLeaf];
  179526. sqlite3_bind_int64(pStmt, 1, iKey);
  179527. rc = sqlite3_step(pStmt);
  179528. if( rc==SQLITE_DONE ){
  179529. rtreeCheckAppendMsg(pCheck, "Mapping (%lld -> %lld) missing from %s table",
  179530. iKey, iVal, (bLeaf ? "%_rowid" : "%_parent")
  179531. );
  179532. }else if( rc==SQLITE_ROW ){
  179533. i64 ii = sqlite3_column_int64(pStmt, 0);
  179534. if( ii!=iVal ){
  179535. rtreeCheckAppendMsg(pCheck,
  179536. "Found (%lld -> %lld) in %s table, expected (%lld -> %lld)",
  179537. iKey, ii, (bLeaf ? "%_rowid" : "%_parent"), iKey, iVal
  179538. );
  179539. }
  179540. }
  179541. rtreeCheckReset(pCheck, pStmt);
  179542. }
  179543. /*
  179544. ** Argument pCell points to an array of coordinates stored on an rtree page.
  179545. ** This function checks that the coordinates are internally consistent (no
  179546. ** x1>x2 conditions) and adds an error message to the RtreeCheck object
  179547. ** if they are not.
  179548. **
  179549. ** Additionally, if pParent is not NULL, then it is assumed to point to
  179550. ** the array of coordinates on the parent page that bound the page
  179551. ** containing pCell. In this case it is also verified that the two
  179552. ** sets of coordinates are mutually consistent and an error message added
  179553. ** to the RtreeCheck object if they are not.
  179554. */
  179555. static void rtreeCheckCellCoord(
  179556. RtreeCheck *pCheck,
  179557. i64 iNode, /* Node id to use in error messages */
  179558. int iCell, /* Cell number to use in error messages */
  179559. u8 *pCell, /* Pointer to cell coordinates */
  179560. u8 *pParent /* Pointer to parent coordinates */
  179561. ){
  179562. RtreeCoord c1, c2;
  179563. RtreeCoord p1, p2;
  179564. int i;
  179565. for(i=0; i<pCheck->nDim; i++){
  179566. readCoord(&pCell[4*2*i], &c1);
  179567. readCoord(&pCell[4*(2*i + 1)], &c2);
  179568. /* printf("%e, %e\n", c1.u.f, c2.u.f); */
  179569. if( pCheck->bInt ? c1.i>c2.i : c1.f>c2.f ){
  179570. rtreeCheckAppendMsg(pCheck,
  179571. "Dimension %d of cell %d on node %lld is corrupt", i, iCell, iNode
  179572. );
  179573. }
  179574. if( pParent ){
  179575. readCoord(&pParent[4*2*i], &p1);
  179576. readCoord(&pParent[4*(2*i + 1)], &p2);
  179577. if( (pCheck->bInt ? c1.i<p1.i : c1.f<p1.f)
  179578. || (pCheck->bInt ? c2.i>p2.i : c2.f>p2.f)
  179579. ){
  179580. rtreeCheckAppendMsg(pCheck,
  179581. "Dimension %d of cell %d on node %lld is corrupt relative to parent"
  179582. , i, iCell, iNode
  179583. );
  179584. }
  179585. }
  179586. }
  179587. }
  179588. /*
  179589. ** Run rtreecheck() checks on node iNode, which is at depth iDepth within
  179590. ** the r-tree structure. Argument aParent points to the array of coordinates
  179591. ** that bound node iNode on the parent node.
  179592. **
  179593. ** If any problems are discovered, an error message is appended to the
  179594. ** report accumulated in the RtreeCheck object.
  179595. */
  179596. static void rtreeCheckNode(
  179597. RtreeCheck *pCheck,
  179598. int iDepth, /* Depth of iNode (0==leaf) */
  179599. u8 *aParent, /* Buffer containing parent coords */
  179600. i64 iNode /* Node to check */
  179601. ){
  179602. u8 *aNode = 0;
  179603. int nNode = 0;
  179604. assert( iNode==1 || aParent!=0 );
  179605. assert( pCheck->nDim>0 );
  179606. aNode = rtreeCheckGetNode(pCheck, iNode, &nNode);
  179607. if( aNode ){
  179608. if( nNode<4 ){
  179609. rtreeCheckAppendMsg(pCheck,
  179610. "Node %lld is too small (%d bytes)", iNode, nNode
  179611. );
  179612. }else{
  179613. int nCell; /* Number of cells on page */
  179614. int i; /* Used to iterate through cells */
  179615. if( aParent==0 ){
  179616. iDepth = readInt16(aNode);
  179617. if( iDepth>RTREE_MAX_DEPTH ){
  179618. rtreeCheckAppendMsg(pCheck, "Rtree depth out of range (%d)", iDepth);
  179619. sqlite3_free(aNode);
  179620. return;
  179621. }
  179622. }
  179623. nCell = readInt16(&aNode[2]);
  179624. if( (4 + nCell*(8 + pCheck->nDim*2*4))>nNode ){
  179625. rtreeCheckAppendMsg(pCheck,
  179626. "Node %lld is too small for cell count of %d (%d bytes)",
  179627. iNode, nCell, nNode
  179628. );
  179629. }else{
  179630. for(i=0; i<nCell; i++){
  179631. u8 *pCell = &aNode[4 + i*(8 + pCheck->nDim*2*4)];
  179632. i64 iVal = readInt64(pCell);
  179633. rtreeCheckCellCoord(pCheck, iNode, i, &pCell[8], aParent);
  179634. if( iDepth>0 ){
  179635. rtreeCheckMapping(pCheck, 0, iVal, iNode);
  179636. rtreeCheckNode(pCheck, iDepth-1, &pCell[8], iVal);
  179637. pCheck->nNonLeaf++;
  179638. }else{
  179639. rtreeCheckMapping(pCheck, 1, iVal, iNode);
  179640. pCheck->nLeaf++;
  179641. }
  179642. }
  179643. }
  179644. }
  179645. sqlite3_free(aNode);
  179646. }
  179647. }
  179648. /*
  179649. ** The second argument to this function must be either "_rowid" or
  179650. ** "_parent". This function checks that the number of entries in the
  179651. ** %_rowid or %_parent table is exactly nExpect. If not, it adds
  179652. ** an error message to the report in the RtreeCheck object indicated
  179653. ** by the first argument.
  179654. */
  179655. static void rtreeCheckCount(RtreeCheck *pCheck, const char *zTbl, i64 nExpect){
  179656. if( pCheck->rc==SQLITE_OK ){
  179657. sqlite3_stmt *pCount;
  179658. pCount = rtreeCheckPrepare(pCheck, "SELECT count(*) FROM %Q.'%q%s'",
  179659. pCheck->zDb, pCheck->zTab, zTbl
  179660. );
  179661. if( pCount ){
  179662. if( sqlite3_step(pCount)==SQLITE_ROW ){
  179663. i64 nActual = sqlite3_column_int64(pCount, 0);
  179664. if( nActual!=nExpect ){
  179665. rtreeCheckAppendMsg(pCheck, "Wrong number of entries in %%%s table"
  179666. " - expected %lld, actual %lld" , zTbl, nExpect, nActual
  179667. );
  179668. }
  179669. }
  179670. pCheck->rc = sqlite3_finalize(pCount);
  179671. }
  179672. }
  179673. }
  179674. /*
  179675. ** This function does the bulk of the work for the rtree integrity-check.
  179676. ** It is called by rtreecheck(), which is the SQL function implementation.
  179677. */
  179678. static int rtreeCheckTable(
  179679. sqlite3 *db, /* Database handle to access db through */
  179680. const char *zDb, /* Name of db ("main", "temp" etc.) */
  179681. const char *zTab, /* Name of rtree table to check */
  179682. char **pzReport /* OUT: sqlite3_malloc'd report text */
  179683. ){
  179684. RtreeCheck check; /* Common context for various routines */
  179685. sqlite3_stmt *pStmt = 0; /* Used to find column count of rtree table */
  179686. int bEnd = 0; /* True if transaction should be closed */
  179687. int nAux = 0; /* Number of extra columns. */
  179688. /* Initialize the context object */
  179689. memset(&check, 0, sizeof(check));
  179690. check.db = db;
  179691. check.zDb = zDb;
  179692. check.zTab = zTab;
  179693. /* If there is not already an open transaction, open one now. This is
  179694. ** to ensure that the queries run as part of this integrity-check operate
  179695. ** on a consistent snapshot. */
  179696. if( sqlite3_get_autocommit(db) ){
  179697. check.rc = sqlite3_exec(db, "BEGIN", 0, 0, 0);
  179698. bEnd = 1;
  179699. }
  179700. /* Find the number of auxiliary columns */
  179701. if( check.rc==SQLITE_OK ){
  179702. pStmt = rtreeCheckPrepare(&check, "SELECT * FROM %Q.'%q_rowid'", zDb, zTab);
  179703. if( pStmt ){
  179704. nAux = sqlite3_column_count(pStmt) - 2;
  179705. sqlite3_finalize(pStmt);
  179706. }
  179707. check.rc = SQLITE_OK;
  179708. }
  179709. /* Find number of dimensions in the rtree table. */
  179710. pStmt = rtreeCheckPrepare(&check, "SELECT * FROM %Q.%Q", zDb, zTab);
  179711. if( pStmt ){
  179712. int rc;
  179713. check.nDim = (sqlite3_column_count(pStmt) - 1 - nAux) / 2;
  179714. if( check.nDim<1 ){
  179715. rtreeCheckAppendMsg(&check, "Schema corrupt or not an rtree");
  179716. }else if( SQLITE_ROW==sqlite3_step(pStmt) ){
  179717. check.bInt = (sqlite3_column_type(pStmt, 1)==SQLITE_INTEGER);
  179718. }
  179719. rc = sqlite3_finalize(pStmt);
  179720. if( rc!=SQLITE_CORRUPT ) check.rc = rc;
  179721. }
  179722. /* Do the actual integrity-check */
  179723. if( check.nDim>=1 ){
  179724. if( check.rc==SQLITE_OK ){
  179725. rtreeCheckNode(&check, 0, 0, 1);
  179726. }
  179727. rtreeCheckCount(&check, "_rowid", check.nLeaf);
  179728. rtreeCheckCount(&check, "_parent", check.nNonLeaf);
  179729. }
  179730. /* Finalize SQL statements used by the integrity-check */
  179731. sqlite3_finalize(check.pGetNode);
  179732. sqlite3_finalize(check.aCheckMapping[0]);
  179733. sqlite3_finalize(check.aCheckMapping[1]);
  179734. /* If one was opened, close the transaction */
  179735. if( bEnd ){
  179736. int rc = sqlite3_exec(db, "END", 0, 0, 0);
  179737. if( check.rc==SQLITE_OK ) check.rc = rc;
  179738. }
  179739. *pzReport = check.zReport;
  179740. return check.rc;
  179741. }
  179742. /*
  179743. ** Usage:
  179744. **
  179745. ** rtreecheck(<rtree-table>);
  179746. ** rtreecheck(<database>, <rtree-table>);
  179747. **
  179748. ** Invoking this SQL function runs an integrity-check on the named rtree
  179749. ** table. The integrity-check verifies the following:
  179750. **
  179751. ** 1. For each cell in the r-tree structure (%_node table), that:
  179752. **
  179753. ** a) for each dimension, (coord1 <= coord2).
  179754. **
  179755. ** b) unless the cell is on the root node, that the cell is bounded
  179756. ** by the parent cell on the parent node.
  179757. **
  179758. ** c) for leaf nodes, that there is an entry in the %_rowid
  179759. ** table corresponding to the cell's rowid value that
  179760. ** points to the correct node.
  179761. **
  179762. ** d) for cells on non-leaf nodes, that there is an entry in the
  179763. ** %_parent table mapping from the cell's child node to the
  179764. ** node that it resides on.
  179765. **
  179766. ** 2. That there are the same number of entries in the %_rowid table
  179767. ** as there are leaf cells in the r-tree structure, and that there
  179768. ** is a leaf cell that corresponds to each entry in the %_rowid table.
  179769. **
  179770. ** 3. That there are the same number of entries in the %_parent table
  179771. ** as there are non-leaf cells in the r-tree structure, and that
  179772. ** there is a non-leaf cell that corresponds to each entry in the
  179773. ** %_parent table.
  179774. */
  179775. static void rtreecheck(
  179776. sqlite3_context *ctx,
  179777. int nArg,
  179778. sqlite3_value **apArg
  179779. ){
  179780. if( nArg!=1 && nArg!=2 ){
  179781. sqlite3_result_error(ctx,
  179782. "wrong number of arguments to function rtreecheck()", -1
  179783. );
  179784. }else{
  179785. int rc;
  179786. char *zReport = 0;
  179787. const char *zDb = (const char*)sqlite3_value_text(apArg[0]);
  179788. const char *zTab;
  179789. if( nArg==1 ){
  179790. zTab = zDb;
  179791. zDb = "main";
  179792. }else{
  179793. zTab = (const char*)sqlite3_value_text(apArg[1]);
  179794. }
  179795. rc = rtreeCheckTable(sqlite3_context_db_handle(ctx), zDb, zTab, &zReport);
  179796. if( rc==SQLITE_OK ){
  179797. sqlite3_result_text(ctx, zReport ? zReport : "ok", -1, SQLITE_TRANSIENT);
  179798. }else{
  179799. sqlite3_result_error_code(ctx, rc);
  179800. }
  179801. sqlite3_free(zReport);
  179802. }
  179803. }
  179804. /* Conditionally include the geopoly code */
  179805. #ifdef SQLITE_ENABLE_GEOPOLY
  179806. /************** Include geopoly.c in the middle of rtree.c *******************/
  179807. /************** Begin file geopoly.c *****************************************/
  179808. /*
  179809. ** 2018-05-25
  179810. **
  179811. ** The author disclaims copyright to this source code. In place of
  179812. ** a legal notice, here is a blessing:
  179813. **
  179814. ** May you do good and not evil.
  179815. ** May you find forgiveness for yourself and forgive others.
  179816. ** May you share freely, never taking more than you give.
  179817. **
  179818. ******************************************************************************
  179819. **
  179820. ** This file implements an alternative R-Tree virtual table that
  179821. ** uses polygons to express the boundaries of 2-dimensional objects.
  179822. **
  179823. ** This file is #include-ed onto the end of "rtree.c" so that it has
  179824. ** access to all of the R-Tree internals.
  179825. */
  179826. /* #include <stdlib.h> */
  179827. /* Enable -DGEOPOLY_ENABLE_DEBUG for debugging facilities */
  179828. #ifdef GEOPOLY_ENABLE_DEBUG
  179829. static int geo_debug = 0;
  179830. # define GEODEBUG(X) if(geo_debug)printf X
  179831. #else
  179832. # define GEODEBUG(X)
  179833. #endif
  179834. #ifndef JSON_NULL /* The following stuff repeats things found in json1 */
  179835. /*
  179836. ** Versions of isspace(), isalnum() and isdigit() to which it is safe
  179837. ** to pass signed char values.
  179838. */
  179839. #ifdef sqlite3Isdigit
  179840. /* Use the SQLite core versions if this routine is part of the
  179841. ** SQLite amalgamation */
  179842. # define safe_isdigit(x) sqlite3Isdigit(x)
  179843. # define safe_isalnum(x) sqlite3Isalnum(x)
  179844. # define safe_isxdigit(x) sqlite3Isxdigit(x)
  179845. #else
  179846. /* Use the standard library for separate compilation */
  179847. #include <ctype.h> /* amalgamator: keep */
  179848. # define safe_isdigit(x) isdigit((unsigned char)(x))
  179849. # define safe_isalnum(x) isalnum((unsigned char)(x))
  179850. # define safe_isxdigit(x) isxdigit((unsigned char)(x))
  179851. #endif
  179852. /*
  179853. ** Growing our own isspace() routine this way is twice as fast as
  179854. ** the library isspace() function.
  179855. */
  179856. static const char geopolyIsSpace[] = {
  179857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0,
  179858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  179859. 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  179860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  179861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  179862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  179863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  179864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  179865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  179866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  179867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  179868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  179869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  179870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  179871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  179872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  179873. };
  179874. #define safe_isspace(x) (geopolyIsSpace[(unsigned char)x])
  179875. #endif /* JSON NULL - back to original code */
  179876. /* Compiler and version */
  179877. #ifndef GCC_VERSION
  179878. #if defined(__GNUC__) && !defined(SQLITE_DISABLE_INTRINSIC)
  179879. # define GCC_VERSION (__GNUC__*1000000+__GNUC_MINOR__*1000+__GNUC_PATCHLEVEL__)
  179880. #else
  179881. # define GCC_VERSION 0
  179882. #endif
  179883. #endif
  179884. #ifndef MSVC_VERSION
  179885. #if defined(_MSC_VER) && !defined(SQLITE_DISABLE_INTRINSIC)
  179886. # define MSVC_VERSION _MSC_VER
  179887. #else
  179888. # define MSVC_VERSION 0
  179889. #endif
  179890. #endif
  179891. /* Datatype for coordinates
  179892. */
  179893. typedef float GeoCoord;
  179894. /*
  179895. ** Internal representation of a polygon.
  179896. **
  179897. ** The polygon consists of a sequence of vertexes. There is a line
  179898. ** segment between each pair of vertexes, and one final segment from
  179899. ** the last vertex back to the first. (This differs from the GeoJSON
  179900. ** standard in which the final vertex is a repeat of the first.)
  179901. **
  179902. ** The polygon follows the right-hand rule. The area to the right of
  179903. ** each segment is "outside" and the area to the left is "inside".
  179904. **
  179905. ** The on-disk representation consists of a 4-byte header followed by
  179906. ** the values. The 4-byte header is:
  179907. **
  179908. ** encoding (1 byte) 0=big-endian, 1=little-endian
  179909. ** nvertex (3 bytes) Number of vertexes as a big-endian integer
  179910. **
  179911. ** Enough space is allocated for 4 coordinates, to work around over-zealous
  179912. ** warnings coming from some compiler (notably, clang). In reality, the size
  179913. ** of each GeoPoly memory allocate is adjusted as necessary so that the
  179914. ** GeoPoly.a[] array at the end is the appropriate size.
  179915. */
  179916. typedef struct GeoPoly GeoPoly;
  179917. struct GeoPoly {
  179918. int nVertex; /* Number of vertexes */
  179919. unsigned char hdr[4]; /* Header for on-disk representation */
  179920. GeoCoord a[8]; /* 2*nVertex values. X (longitude) first, then Y */
  179921. };
  179922. /* The size of a memory allocation needed for a GeoPoly object sufficient
  179923. ** to hold N coordinate pairs.
  179924. */
  179925. #define GEOPOLY_SZ(N) (sizeof(GeoPoly) + sizeof(GeoCoord)*2*((N)-4))
  179926. /* Macros to access coordinates of a GeoPoly.
  179927. ** We have to use these macros, rather than just say p->a[i] in order
  179928. ** to silence (incorrect) UBSAN warnings if the array index is too large.
  179929. */
  179930. #define GeoX(P,I) (((GeoCoord*)(P)->a)[(I)*2])
  179931. #define GeoY(P,I) (((GeoCoord*)(P)->a)[(I)*2+1])
  179932. /*
  179933. ** State of a parse of a GeoJSON input.
  179934. */
  179935. typedef struct GeoParse GeoParse;
  179936. struct GeoParse {
  179937. const unsigned char *z; /* Unparsed input */
  179938. int nVertex; /* Number of vertexes in a[] */
  179939. int nAlloc; /* Space allocated to a[] */
  179940. int nErr; /* Number of errors encountered */
  179941. GeoCoord *a; /* Array of vertexes. From sqlite3_malloc64() */
  179942. };
  179943. /* Do a 4-byte byte swap */
  179944. static void geopolySwab32(unsigned char *a){
  179945. unsigned char t = a[0];
  179946. a[0] = a[3];
  179947. a[3] = t;
  179948. t = a[1];
  179949. a[1] = a[2];
  179950. a[2] = t;
  179951. }
  179952. /* Skip whitespace. Return the next non-whitespace character. */
  179953. static char geopolySkipSpace(GeoParse *p){
  179954. while( safe_isspace(p->z[0]) ) p->z++;
  179955. return p->z[0];
  179956. }
  179957. /* Parse out a number. Write the value into *pVal if pVal!=0.
  179958. ** return non-zero on success and zero if the next token is not a number.
  179959. */
  179960. static int geopolyParseNumber(GeoParse *p, GeoCoord *pVal){
  179961. char c = geopolySkipSpace(p);
  179962. const unsigned char *z = p->z;
  179963. int j = 0;
  179964. int seenDP = 0;
  179965. int seenE = 0;
  179966. if( c=='-' ){
  179967. j = 1;
  179968. c = z[j];
  179969. }
  179970. if( c=='0' && z[j+1]>='0' && z[j+1]<='9' ) return 0;
  179971. for(;; j++){
  179972. c = z[j];
  179973. if( safe_isdigit(c) ) continue;
  179974. if( c=='.' ){
  179975. if( z[j-1]=='-' ) return 0;
  179976. if( seenDP ) return 0;
  179977. seenDP = 1;
  179978. continue;
  179979. }
  179980. if( c=='e' || c=='E' ){
  179981. if( z[j-1]<'0' ) return 0;
  179982. if( seenE ) return -1;
  179983. seenDP = seenE = 1;
  179984. c = z[j+1];
  179985. if( c=='+' || c=='-' ){
  179986. j++;
  179987. c = z[j+1];
  179988. }
  179989. if( c<'0' || c>'9' ) return 0;
  179990. continue;
  179991. }
  179992. break;
  179993. }
  179994. if( z[j-1]<'0' ) return 0;
  179995. if( pVal ){
  179996. #ifdef SQLITE_AMALGAMATION
  179997. /* The sqlite3AtoF() routine is much much faster than atof(), if it
  179998. ** is available */
  179999. double r;
  180000. (void)sqlite3AtoF((const char*)p->z, &r, j, SQLITE_UTF8);
  180001. *pVal = r;
  180002. #else
  180003. *pVal = (GeoCoord)atof((const char*)p->z);
  180004. #endif
  180005. }
  180006. p->z += j;
  180007. return 1;
  180008. }
  180009. /*
  180010. ** If the input is a well-formed JSON array of coordinates with at least
  180011. ** four coordinates and where each coordinate is itself a two-value array,
  180012. ** then convert the JSON into a GeoPoly object and return a pointer to
  180013. ** that object.
  180014. **
  180015. ** If any error occurs, return NULL.
  180016. */
  180017. static GeoPoly *geopolyParseJson(const unsigned char *z, int *pRc){
  180018. GeoParse s;
  180019. int rc = SQLITE_OK;
  180020. memset(&s, 0, sizeof(s));
  180021. s.z = z;
  180022. if( geopolySkipSpace(&s)=='[' ){
  180023. s.z++;
  180024. while( geopolySkipSpace(&s)=='[' ){
  180025. int ii = 0;
  180026. char c;
  180027. s.z++;
  180028. if( s.nVertex>=s.nAlloc ){
  180029. GeoCoord *aNew;
  180030. s.nAlloc = s.nAlloc*2 + 16;
  180031. aNew = sqlite3_realloc64(s.a, s.nAlloc*sizeof(GeoCoord)*2 );
  180032. if( aNew==0 ){
  180033. rc = SQLITE_NOMEM;
  180034. s.nErr++;
  180035. break;
  180036. }
  180037. s.a = aNew;
  180038. }
  180039. while( geopolyParseNumber(&s, ii<=1 ? &s.a[s.nVertex*2+ii] : 0) ){
  180040. ii++;
  180041. if( ii==2 ) s.nVertex++;
  180042. c = geopolySkipSpace(&s);
  180043. s.z++;
  180044. if( c==',' ) continue;
  180045. if( c==']' && ii>=2 ) break;
  180046. s.nErr++;
  180047. rc = SQLITE_ERROR;
  180048. goto parse_json_err;
  180049. }
  180050. if( geopolySkipSpace(&s)==',' ){
  180051. s.z++;
  180052. continue;
  180053. }
  180054. break;
  180055. }
  180056. if( geopolySkipSpace(&s)==']'
  180057. && s.nVertex>=4
  180058. && s.a[0]==s.a[s.nVertex*2-2]
  180059. && s.a[1]==s.a[s.nVertex*2-1]
  180060. && (s.z++, geopolySkipSpace(&s)==0)
  180061. ){
  180062. GeoPoly *pOut;
  180063. int x = 1;
  180064. s.nVertex--; /* Remove the redundant vertex at the end */
  180065. pOut = sqlite3_malloc64( GEOPOLY_SZ((sqlite3_int64)s.nVertex) );
  180066. x = 1;
  180067. if( pOut==0 ) goto parse_json_err;
  180068. pOut->nVertex = s.nVertex;
  180069. memcpy(pOut->a, s.a, s.nVertex*2*sizeof(GeoCoord));
  180070. pOut->hdr[0] = *(unsigned char*)&x;
  180071. pOut->hdr[1] = (s.nVertex>>16)&0xff;
  180072. pOut->hdr[2] = (s.nVertex>>8)&0xff;
  180073. pOut->hdr[3] = s.nVertex&0xff;
  180074. sqlite3_free(s.a);
  180075. if( pRc ) *pRc = SQLITE_OK;
  180076. return pOut;
  180077. }else{
  180078. s.nErr++;
  180079. rc = SQLITE_ERROR;
  180080. }
  180081. }
  180082. parse_json_err:
  180083. if( pRc ) *pRc = rc;
  180084. sqlite3_free(s.a);
  180085. return 0;
  180086. }
  180087. /*
  180088. ** Given a function parameter, try to interpret it as a polygon, either
  180089. ** in the binary format or JSON text. Compute a GeoPoly object and
  180090. ** return a pointer to that object. Or if the input is not a well-formed
  180091. ** polygon, put an error message in sqlite3_context and return NULL.
  180092. */
  180093. static GeoPoly *geopolyFuncParam(
  180094. sqlite3_context *pCtx, /* Context for error messages */
  180095. sqlite3_value *pVal, /* The value to decode */
  180096. int *pRc /* Write error here */
  180097. ){
  180098. GeoPoly *p = 0;
  180099. int nByte;
  180100. if( sqlite3_value_type(pVal)==SQLITE_BLOB
  180101. && (nByte = sqlite3_value_bytes(pVal))>=(4+6*sizeof(GeoCoord))
  180102. ){
  180103. const unsigned char *a = sqlite3_value_blob(pVal);
  180104. int nVertex;
  180105. nVertex = (a[1]<<16) + (a[2]<<8) + a[3];
  180106. if( (a[0]==0 || a[0]==1)
  180107. && (nVertex*2*sizeof(GeoCoord) + 4)==(unsigned int)nByte
  180108. ){
  180109. p = sqlite3_malloc64( sizeof(*p) + (nVertex-1)*2*sizeof(GeoCoord) );
  180110. if( p==0 ){
  180111. if( pRc ) *pRc = SQLITE_NOMEM;
  180112. if( pCtx ) sqlite3_result_error_nomem(pCtx);
  180113. }else{
  180114. int x = 1;
  180115. p->nVertex = nVertex;
  180116. memcpy(p->hdr, a, nByte);
  180117. if( a[0] != *(unsigned char*)&x ){
  180118. int ii;
  180119. for(ii=0; ii<nVertex; ii++){
  180120. geopolySwab32((unsigned char*)&GeoX(p,ii));
  180121. geopolySwab32((unsigned char*)&GeoY(p,ii));
  180122. }
  180123. p->hdr[0] ^= 1;
  180124. }
  180125. }
  180126. }
  180127. if( pRc ) *pRc = SQLITE_OK;
  180128. return p;
  180129. }else if( sqlite3_value_type(pVal)==SQLITE_TEXT ){
  180130. const unsigned char *zJson = sqlite3_value_text(pVal);
  180131. if( zJson==0 ){
  180132. if( pRc ) *pRc = SQLITE_NOMEM;
  180133. return 0;
  180134. }
  180135. return geopolyParseJson(zJson, pRc);
  180136. }else{
  180137. if( pRc ) *pRc = SQLITE_ERROR;
  180138. return 0;
  180139. }
  180140. }
  180141. /*
  180142. ** Implementation of the geopoly_blob(X) function.
  180143. **
  180144. ** If the input is a well-formed Geopoly BLOB or JSON string
  180145. ** then return the BLOB representation of the polygon. Otherwise
  180146. ** return NULL.
  180147. */
  180148. static void geopolyBlobFunc(
  180149. sqlite3_context *context,
  180150. int argc,
  180151. sqlite3_value **argv
  180152. ){
  180153. GeoPoly *p = geopolyFuncParam(context, argv[0], 0);
  180154. if( p ){
  180155. sqlite3_result_blob(context, p->hdr,
  180156. 4+8*p->nVertex, SQLITE_TRANSIENT);
  180157. sqlite3_free(p);
  180158. }
  180159. }
  180160. /*
  180161. ** SQL function: geopoly_json(X)
  180162. **
  180163. ** Interpret X as a polygon and render it as a JSON array
  180164. ** of coordinates. Or, if X is not a valid polygon, return NULL.
  180165. */
  180166. static void geopolyJsonFunc(
  180167. sqlite3_context *context,
  180168. int argc,
  180169. sqlite3_value **argv
  180170. ){
  180171. GeoPoly *p = geopolyFuncParam(context, argv[0], 0);
  180172. if( p ){
  180173. sqlite3 *db = sqlite3_context_db_handle(context);
  180174. sqlite3_str *x = sqlite3_str_new(db);
  180175. int i;
  180176. sqlite3_str_append(x, "[", 1);
  180177. for(i=0; i<p->nVertex; i++){
  180178. sqlite3_str_appendf(x, "[%!g,%!g],", GeoX(p,i), GeoY(p,i));
  180179. }
  180180. sqlite3_str_appendf(x, "[%!g,%!g]]", GeoX(p,0), GeoY(p,0));
  180181. sqlite3_result_text(context, sqlite3_str_finish(x), -1, sqlite3_free);
  180182. sqlite3_free(p);
  180183. }
  180184. }
  180185. /*
  180186. ** SQL function: geopoly_svg(X, ....)
  180187. **
  180188. ** Interpret X as a polygon and render it as a SVG <polyline>.
  180189. ** Additional arguments are added as attributes to the <polyline>.
  180190. */
  180191. static void geopolySvgFunc(
  180192. sqlite3_context *context,
  180193. int argc,
  180194. sqlite3_value **argv
  180195. ){
  180196. GeoPoly *p;
  180197. if( argc<1 ) return;
  180198. p = geopolyFuncParam(context, argv[0], 0);
  180199. if( p ){
  180200. sqlite3 *db = sqlite3_context_db_handle(context);
  180201. sqlite3_str *x = sqlite3_str_new(db);
  180202. int i;
  180203. char cSep = '\'';
  180204. sqlite3_str_appendf(x, "<polyline points=");
  180205. for(i=0; i<p->nVertex; i++){
  180206. sqlite3_str_appendf(x, "%c%g,%g", cSep, GeoX(p,i), GeoY(p,i));
  180207. cSep = ' ';
  180208. }
  180209. sqlite3_str_appendf(x, " %g,%g'", GeoX(p,0), GeoY(p,0));
  180210. for(i=1; i<argc; i++){
  180211. const char *z = (const char*)sqlite3_value_text(argv[i]);
  180212. if( z && z[0] ){
  180213. sqlite3_str_appendf(x, " %s", z);
  180214. }
  180215. }
  180216. sqlite3_str_appendf(x, "></polyline>");
  180217. sqlite3_result_text(context, sqlite3_str_finish(x), -1, sqlite3_free);
  180218. sqlite3_free(p);
  180219. }
  180220. }
  180221. /*
  180222. ** SQL Function: geopoly_xform(poly, A, B, C, D, E, F)
  180223. **
  180224. ** Transform and/or translate a polygon as follows:
  180225. **
  180226. ** x1 = A*x0 + B*y0 + E
  180227. ** y1 = C*x0 + D*y0 + F
  180228. **
  180229. ** For a translation:
  180230. **
  180231. ** geopoly_xform(poly, 1, 0, 0, 1, x-offset, y-offset)
  180232. **
  180233. ** Rotate by R around the point (0,0):
  180234. **
  180235. ** geopoly_xform(poly, cos(R), sin(R), -sin(R), cos(R), 0, 0)
  180236. */
  180237. static void geopolyXformFunc(
  180238. sqlite3_context *context,
  180239. int argc,
  180240. sqlite3_value **argv
  180241. ){
  180242. GeoPoly *p = geopolyFuncParam(context, argv[0], 0);
  180243. double A = sqlite3_value_double(argv[1]);
  180244. double B = sqlite3_value_double(argv[2]);
  180245. double C = sqlite3_value_double(argv[3]);
  180246. double D = sqlite3_value_double(argv[4]);
  180247. double E = sqlite3_value_double(argv[5]);
  180248. double F = sqlite3_value_double(argv[6]);
  180249. GeoCoord x1, y1, x0, y0;
  180250. int ii;
  180251. if( p ){
  180252. for(ii=0; ii<p->nVertex; ii++){
  180253. x0 = GeoX(p,ii);
  180254. y0 = GeoY(p,ii);
  180255. x1 = (GeoCoord)(A*x0 + B*y0 + E);
  180256. y1 = (GeoCoord)(C*x0 + D*y0 + F);
  180257. GeoX(p,ii) = x1;
  180258. GeoY(p,ii) = y1;
  180259. }
  180260. sqlite3_result_blob(context, p->hdr,
  180261. 4+8*p->nVertex, SQLITE_TRANSIENT);
  180262. sqlite3_free(p);
  180263. }
  180264. }
  180265. /*
  180266. ** Compute the area enclosed by the polygon.
  180267. **
  180268. ** This routine can also be used to detect polygons that rotate in
  180269. ** the wrong direction. Polygons are suppose to be counter-clockwise (CCW).
  180270. ** This routine returns a negative value for clockwise (CW) polygons.
  180271. */
  180272. static double geopolyArea(GeoPoly *p){
  180273. double rArea = 0.0;
  180274. int ii;
  180275. for(ii=0; ii<p->nVertex-1; ii++){
  180276. rArea += (GeoX(p,ii) - GeoX(p,ii+1)) /* (x0 - x1) */
  180277. * (GeoY(p,ii) + GeoY(p,ii+1)) /* (y0 + y1) */
  180278. * 0.5;
  180279. }
  180280. rArea += (GeoX(p,ii) - GeoX(p,0)) /* (xN - x0) */
  180281. * (GeoY(p,ii) + GeoY(p,0)) /* (yN + y0) */
  180282. * 0.5;
  180283. return rArea;
  180284. }
  180285. /*
  180286. ** Implementation of the geopoly_area(X) function.
  180287. **
  180288. ** If the input is a well-formed Geopoly BLOB then return the area
  180289. ** enclosed by the polygon. If the polygon circulates clockwise instead
  180290. ** of counterclockwise (as it should) then return the negative of the
  180291. ** enclosed area. Otherwise return NULL.
  180292. */
  180293. static void geopolyAreaFunc(
  180294. sqlite3_context *context,
  180295. int argc,
  180296. sqlite3_value **argv
  180297. ){
  180298. GeoPoly *p = geopolyFuncParam(context, argv[0], 0);
  180299. if( p ){
  180300. sqlite3_result_double(context, geopolyArea(p));
  180301. sqlite3_free(p);
  180302. }
  180303. }
  180304. /*
  180305. ** Implementation of the geopoly_ccw(X) function.
  180306. **
  180307. ** If the rotation of polygon X is clockwise (incorrect) instead of
  180308. ** counter-clockwise (the correct winding order according to RFC7946)
  180309. ** then reverse the order of the vertexes in polygon X.
  180310. **
  180311. ** In other words, this routine returns a CCW polygon regardless of the
  180312. ** winding order of its input.
  180313. **
  180314. ** Use this routine to sanitize historical inputs that that sometimes
  180315. ** contain polygons that wind in the wrong direction.
  180316. */
  180317. static void geopolyCcwFunc(
  180318. sqlite3_context *context,
  180319. int argc,
  180320. sqlite3_value **argv
  180321. ){
  180322. GeoPoly *p = geopolyFuncParam(context, argv[0], 0);
  180323. if( p ){
  180324. if( geopolyArea(p)<0.0 ){
  180325. int ii, jj;
  180326. for(ii=1, jj=p->nVertex-1; ii<jj; ii++, jj--){
  180327. GeoCoord t = GeoX(p,ii);
  180328. GeoX(p,ii) = GeoX(p,jj);
  180329. GeoX(p,jj) = t;
  180330. t = GeoY(p,ii);
  180331. GeoY(p,ii) = GeoY(p,jj);
  180332. GeoY(p,jj) = t;
  180333. }
  180334. }
  180335. sqlite3_result_blob(context, p->hdr,
  180336. 4+8*p->nVertex, SQLITE_TRANSIENT);
  180337. sqlite3_free(p);
  180338. }
  180339. }
  180340. #define GEOPOLY_PI 3.1415926535897932385
  180341. /* Fast approximation for sine(X) for X between -0.5*pi and 2*pi
  180342. */
  180343. static double geopolySine(double r){
  180344. assert( r>=-0.5*GEOPOLY_PI && r<=2.0*GEOPOLY_PI );
  180345. if( r>=1.5*GEOPOLY_PI ){
  180346. r -= 2.0*GEOPOLY_PI;
  180347. }
  180348. if( r>=0.5*GEOPOLY_PI ){
  180349. return -geopolySine(r-GEOPOLY_PI);
  180350. }else{
  180351. double r2 = r*r;
  180352. double r3 = r2*r;
  180353. double r5 = r3*r2;
  180354. return 0.9996949*r - 0.1656700*r3 + 0.0075134*r5;
  180355. }
  180356. }
  180357. /*
  180358. ** Function: geopoly_regular(X,Y,R,N)
  180359. **
  180360. ** Construct a simple, convex, regular polygon centered at X, Y
  180361. ** with circumradius R and with N sides.
  180362. */
  180363. static void geopolyRegularFunc(
  180364. sqlite3_context *context,
  180365. int argc,
  180366. sqlite3_value **argv
  180367. ){
  180368. double x = sqlite3_value_double(argv[0]);
  180369. double y = sqlite3_value_double(argv[1]);
  180370. double r = sqlite3_value_double(argv[2]);
  180371. int n = sqlite3_value_int(argv[3]);
  180372. int i;
  180373. GeoPoly *p;
  180374. if( n<3 || r<=0.0 ) return;
  180375. if( n>1000 ) n = 1000;
  180376. p = sqlite3_malloc64( sizeof(*p) + (n-1)*2*sizeof(GeoCoord) );
  180377. if( p==0 ){
  180378. sqlite3_result_error_nomem(context);
  180379. return;
  180380. }
  180381. i = 1;
  180382. p->hdr[0] = *(unsigned char*)&i;
  180383. p->hdr[1] = 0;
  180384. p->hdr[2] = (n>>8)&0xff;
  180385. p->hdr[3] = n&0xff;
  180386. for(i=0; i<n; i++){
  180387. double rAngle = 2.0*GEOPOLY_PI*i/n;
  180388. GeoX(p,i) = x - r*geopolySine(rAngle-0.5*GEOPOLY_PI);
  180389. GeoY(p,i) = y + r*geopolySine(rAngle);
  180390. }
  180391. sqlite3_result_blob(context, p->hdr, 4+8*n, SQLITE_TRANSIENT);
  180392. sqlite3_free(p);
  180393. }
  180394. /*
  180395. ** If pPoly is a polygon, compute its bounding box. Then:
  180396. **
  180397. ** (1) if aCoord!=0 store the bounding box in aCoord, returning NULL
  180398. ** (2) otherwise, compute a GeoPoly for the bounding box and return the
  180399. ** new GeoPoly
  180400. **
  180401. ** If pPoly is NULL but aCoord is not NULL, then compute a new GeoPoly from
  180402. ** the bounding box in aCoord and return a pointer to that GeoPoly.
  180403. */
  180404. static GeoPoly *geopolyBBox(
  180405. sqlite3_context *context, /* For recording the error */
  180406. sqlite3_value *pPoly, /* The polygon */
  180407. RtreeCoord *aCoord, /* Results here */
  180408. int *pRc /* Error code here */
  180409. ){
  180410. GeoPoly *pOut = 0;
  180411. GeoPoly *p;
  180412. float mnX, mxX, mnY, mxY;
  180413. if( pPoly==0 && aCoord!=0 ){
  180414. p = 0;
  180415. mnX = aCoord[0].f;
  180416. mxX = aCoord[1].f;
  180417. mnY = aCoord[2].f;
  180418. mxY = aCoord[3].f;
  180419. goto geopolyBboxFill;
  180420. }else{
  180421. p = geopolyFuncParam(context, pPoly, pRc);
  180422. }
  180423. if( p ){
  180424. int ii;
  180425. mnX = mxX = GeoX(p,0);
  180426. mnY = mxY = GeoY(p,0);
  180427. for(ii=1; ii<p->nVertex; ii++){
  180428. double r = GeoX(p,ii);
  180429. if( r<mnX ) mnX = (float)r;
  180430. else if( r>mxX ) mxX = (float)r;
  180431. r = GeoY(p,ii);
  180432. if( r<mnY ) mnY = (float)r;
  180433. else if( r>mxY ) mxY = (float)r;
  180434. }
  180435. if( pRc ) *pRc = SQLITE_OK;
  180436. if( aCoord==0 ){
  180437. geopolyBboxFill:
  180438. pOut = sqlite3_realloc64(p, GEOPOLY_SZ(4));
  180439. if( pOut==0 ){
  180440. sqlite3_free(p);
  180441. if( context ) sqlite3_result_error_nomem(context);
  180442. if( pRc ) *pRc = SQLITE_NOMEM;
  180443. return 0;
  180444. }
  180445. pOut->nVertex = 4;
  180446. ii = 1;
  180447. pOut->hdr[0] = *(unsigned char*)&ii;
  180448. pOut->hdr[1] = 0;
  180449. pOut->hdr[2] = 0;
  180450. pOut->hdr[3] = 4;
  180451. GeoX(pOut,0) = mnX;
  180452. GeoY(pOut,0) = mnY;
  180453. GeoX(pOut,1) = mxX;
  180454. GeoY(pOut,1) = mnY;
  180455. GeoX(pOut,2) = mxX;
  180456. GeoY(pOut,2) = mxY;
  180457. GeoX(pOut,3) = mnX;
  180458. GeoY(pOut,3) = mxY;
  180459. }else{
  180460. sqlite3_free(p);
  180461. aCoord[0].f = mnX;
  180462. aCoord[1].f = mxX;
  180463. aCoord[2].f = mnY;
  180464. aCoord[3].f = mxY;
  180465. }
  180466. }
  180467. return pOut;
  180468. }
  180469. /*
  180470. ** Implementation of the geopoly_bbox(X) SQL function.
  180471. */
  180472. static void geopolyBBoxFunc(
  180473. sqlite3_context *context,
  180474. int argc,
  180475. sqlite3_value **argv
  180476. ){
  180477. GeoPoly *p = geopolyBBox(context, argv[0], 0, 0);
  180478. if( p ){
  180479. sqlite3_result_blob(context, p->hdr,
  180480. 4+8*p->nVertex, SQLITE_TRANSIENT);
  180481. sqlite3_free(p);
  180482. }
  180483. }
  180484. /*
  180485. ** State vector for the geopoly_group_bbox() aggregate function.
  180486. */
  180487. typedef struct GeoBBox GeoBBox;
  180488. struct GeoBBox {
  180489. int isInit;
  180490. RtreeCoord a[4];
  180491. };
  180492. /*
  180493. ** Implementation of the geopoly_group_bbox(X) aggregate SQL function.
  180494. */
  180495. static void geopolyBBoxStep(
  180496. sqlite3_context *context,
  180497. int argc,
  180498. sqlite3_value **argv
  180499. ){
  180500. RtreeCoord a[4];
  180501. int rc = SQLITE_OK;
  180502. (void)geopolyBBox(context, argv[0], a, &rc);
  180503. if( rc==SQLITE_OK ){
  180504. GeoBBox *pBBox;
  180505. pBBox = (GeoBBox*)sqlite3_aggregate_context(context, sizeof(*pBBox));
  180506. if( pBBox==0 ) return;
  180507. if( pBBox->isInit==0 ){
  180508. pBBox->isInit = 1;
  180509. memcpy(pBBox->a, a, sizeof(RtreeCoord)*4);
  180510. }else{
  180511. if( a[0].f < pBBox->a[0].f ) pBBox->a[0] = a[0];
  180512. if( a[1].f > pBBox->a[1].f ) pBBox->a[1] = a[1];
  180513. if( a[2].f < pBBox->a[2].f ) pBBox->a[2] = a[2];
  180514. if( a[3].f > pBBox->a[3].f ) pBBox->a[3] = a[3];
  180515. }
  180516. }
  180517. }
  180518. static void geopolyBBoxFinal(
  180519. sqlite3_context *context
  180520. ){
  180521. GeoPoly *p;
  180522. GeoBBox *pBBox;
  180523. pBBox = (GeoBBox*)sqlite3_aggregate_context(context, 0);
  180524. if( pBBox==0 ) return;
  180525. p = geopolyBBox(context, 0, pBBox->a, 0);
  180526. if( p ){
  180527. sqlite3_result_blob(context, p->hdr,
  180528. 4+8*p->nVertex, SQLITE_TRANSIENT);
  180529. sqlite3_free(p);
  180530. }
  180531. }
  180532. /*
  180533. ** Determine if point (x0,y0) is beneath line segment (x1,y1)->(x2,y2).
  180534. ** Returns:
  180535. **
  180536. ** +2 x0,y0 is on the line segement
  180537. **
  180538. ** +1 x0,y0 is beneath line segment
  180539. **
  180540. ** 0 x0,y0 is not on or beneath the line segment or the line segment
  180541. ** is vertical and x0,y0 is not on the line segment
  180542. **
  180543. ** The left-most coordinate min(x1,x2) is not considered to be part of
  180544. ** the line segment for the purposes of this analysis.
  180545. */
  180546. static int pointBeneathLine(
  180547. double x0, double y0,
  180548. double x1, double y1,
  180549. double x2, double y2
  180550. ){
  180551. double y;
  180552. if( x0==x1 && y0==y1 ) return 2;
  180553. if( x1<x2 ){
  180554. if( x0<=x1 || x0>x2 ) return 0;
  180555. }else if( x1>x2 ){
  180556. if( x0<=x2 || x0>x1 ) return 0;
  180557. }else{
  180558. /* Vertical line segment */
  180559. if( x0!=x1 ) return 0;
  180560. if( y0<y1 && y0<y2 ) return 0;
  180561. if( y0>y1 && y0>y2 ) return 0;
  180562. return 2;
  180563. }
  180564. y = y1 + (y2-y1)*(x0-x1)/(x2-x1);
  180565. if( y0==y ) return 2;
  180566. if( y0<y ) return 1;
  180567. return 0;
  180568. }
  180569. /*
  180570. ** SQL function: geopoly_contains_point(P,X,Y)
  180571. **
  180572. ** Return +2 if point X,Y is within polygon P.
  180573. ** Return +1 if point X,Y is on the polygon boundary.
  180574. ** Return 0 if point X,Y is outside the polygon
  180575. */
  180576. static void geopolyContainsPointFunc(
  180577. sqlite3_context *context,
  180578. int argc,
  180579. sqlite3_value **argv
  180580. ){
  180581. GeoPoly *p1 = geopolyFuncParam(context, argv[0], 0);
  180582. double x0 = sqlite3_value_double(argv[1]);
  180583. double y0 = sqlite3_value_double(argv[2]);
  180584. int v = 0;
  180585. int cnt = 0;
  180586. int ii;
  180587. if( p1==0 ) return;
  180588. for(ii=0; ii<p1->nVertex-1; ii++){
  180589. v = pointBeneathLine(x0,y0,GeoX(p1,ii), GeoY(p1,ii),
  180590. GeoX(p1,ii+1),GeoY(p1,ii+1));
  180591. if( v==2 ) break;
  180592. cnt += v;
  180593. }
  180594. if( v!=2 ){
  180595. v = pointBeneathLine(x0,y0,GeoX(p1,ii), GeoY(p1,ii),
  180596. GeoX(p1,0), GeoY(p1,0));
  180597. }
  180598. if( v==2 ){
  180599. sqlite3_result_int(context, 1);
  180600. }else if( ((v+cnt)&1)==0 ){
  180601. sqlite3_result_int(context, 0);
  180602. }else{
  180603. sqlite3_result_int(context, 2);
  180604. }
  180605. sqlite3_free(p1);
  180606. }
  180607. /* Forward declaration */
  180608. static int geopolyOverlap(GeoPoly *p1, GeoPoly *p2);
  180609. /*
  180610. ** SQL function: geopoly_within(P1,P2)
  180611. **
  180612. ** Return +2 if P1 and P2 are the same polygon
  180613. ** Return +1 if P2 is contained within P1
  180614. ** Return 0 if any part of P2 is on the outside of P1
  180615. **
  180616. */
  180617. static void geopolyWithinFunc(
  180618. sqlite3_context *context,
  180619. int argc,
  180620. sqlite3_value **argv
  180621. ){
  180622. GeoPoly *p1 = geopolyFuncParam(context, argv[0], 0);
  180623. GeoPoly *p2 = geopolyFuncParam(context, argv[1], 0);
  180624. if( p1 && p2 ){
  180625. int x = geopolyOverlap(p1, p2);
  180626. if( x<0 ){
  180627. sqlite3_result_error_nomem(context);
  180628. }else{
  180629. sqlite3_result_int(context, x==2 ? 1 : x==4 ? 2 : 0);
  180630. }
  180631. }
  180632. sqlite3_free(p1);
  180633. sqlite3_free(p2);
  180634. }
  180635. /* Objects used by the overlap algorihm. */
  180636. typedef struct GeoEvent GeoEvent;
  180637. typedef struct GeoSegment GeoSegment;
  180638. typedef struct GeoOverlap GeoOverlap;
  180639. struct GeoEvent {
  180640. double x; /* X coordinate at which event occurs */
  180641. int eType; /* 0 for ADD, 1 for REMOVE */
  180642. GeoSegment *pSeg; /* The segment to be added or removed */
  180643. GeoEvent *pNext; /* Next event in the sorted list */
  180644. };
  180645. struct GeoSegment {
  180646. double C, B; /* y = C*x + B */
  180647. double y; /* Current y value */
  180648. float y0; /* Initial y value */
  180649. unsigned char side; /* 1 for p1, 2 for p2 */
  180650. unsigned int idx; /* Which segment within the side */
  180651. GeoSegment *pNext; /* Next segment in a list sorted by y */
  180652. };
  180653. struct GeoOverlap {
  180654. GeoEvent *aEvent; /* Array of all events */
  180655. GeoSegment *aSegment; /* Array of all segments */
  180656. int nEvent; /* Number of events */
  180657. int nSegment; /* Number of segments */
  180658. };
  180659. /*
  180660. ** Add a single segment and its associated events.
  180661. */
  180662. static void geopolyAddOneSegment(
  180663. GeoOverlap *p,
  180664. GeoCoord x0,
  180665. GeoCoord y0,
  180666. GeoCoord x1,
  180667. GeoCoord y1,
  180668. unsigned char side,
  180669. unsigned int idx
  180670. ){
  180671. GeoSegment *pSeg;
  180672. GeoEvent *pEvent;
  180673. if( x0==x1 ) return; /* Ignore vertical segments */
  180674. if( x0>x1 ){
  180675. GeoCoord t = x0;
  180676. x0 = x1;
  180677. x1 = t;
  180678. t = y0;
  180679. y0 = y1;
  180680. y1 = t;
  180681. }
  180682. pSeg = p->aSegment + p->nSegment;
  180683. p->nSegment++;
  180684. pSeg->C = (y1-y0)/(x1-x0);
  180685. pSeg->B = y1 - x1*pSeg->C;
  180686. pSeg->y0 = y0;
  180687. pSeg->side = side;
  180688. pSeg->idx = idx;
  180689. pEvent = p->aEvent + p->nEvent;
  180690. p->nEvent++;
  180691. pEvent->x = x0;
  180692. pEvent->eType = 0;
  180693. pEvent->pSeg = pSeg;
  180694. pEvent = p->aEvent + p->nEvent;
  180695. p->nEvent++;
  180696. pEvent->x = x1;
  180697. pEvent->eType = 1;
  180698. pEvent->pSeg = pSeg;
  180699. }
  180700. /*
  180701. ** Insert all segments and events for polygon pPoly.
  180702. */
  180703. static void geopolyAddSegments(
  180704. GeoOverlap *p, /* Add segments to this Overlap object */
  180705. GeoPoly *pPoly, /* Take all segments from this polygon */
  180706. unsigned char side /* The side of pPoly */
  180707. ){
  180708. unsigned int i;
  180709. GeoCoord *x;
  180710. for(i=0; i<(unsigned)pPoly->nVertex-1; i++){
  180711. x = &GeoX(pPoly,i);
  180712. geopolyAddOneSegment(p, x[0], x[1], x[2], x[3], side, i);
  180713. }
  180714. x = &GeoX(pPoly,i);
  180715. geopolyAddOneSegment(p, x[0], x[1], pPoly->a[0], pPoly->a[1], side, i);
  180716. }
  180717. /*
  180718. ** Merge two lists of sorted events by X coordinate
  180719. */
  180720. static GeoEvent *geopolyEventMerge(GeoEvent *pLeft, GeoEvent *pRight){
  180721. GeoEvent head, *pLast;
  180722. head.pNext = 0;
  180723. pLast = &head;
  180724. while( pRight && pLeft ){
  180725. if( pRight->x <= pLeft->x ){
  180726. pLast->pNext = pRight;
  180727. pLast = pRight;
  180728. pRight = pRight->pNext;
  180729. }else{
  180730. pLast->pNext = pLeft;
  180731. pLast = pLeft;
  180732. pLeft = pLeft->pNext;
  180733. }
  180734. }
  180735. pLast->pNext = pRight ? pRight : pLeft;
  180736. return head.pNext;
  180737. }
  180738. /*
  180739. ** Sort an array of nEvent event objects into a list.
  180740. */
  180741. static GeoEvent *geopolySortEventsByX(GeoEvent *aEvent, int nEvent){
  180742. int mx = 0;
  180743. int i, j;
  180744. GeoEvent *p;
  180745. GeoEvent *a[50];
  180746. for(i=0; i<nEvent; i++){
  180747. p = &aEvent[i];
  180748. p->pNext = 0;
  180749. for(j=0; j<mx && a[j]; j++){
  180750. p = geopolyEventMerge(a[j], p);
  180751. a[j] = 0;
  180752. }
  180753. a[j] = p;
  180754. if( j>=mx ) mx = j+1;
  180755. }
  180756. p = 0;
  180757. for(i=0; i<mx; i++){
  180758. p = geopolyEventMerge(a[i], p);
  180759. }
  180760. return p;
  180761. }
  180762. /*
  180763. ** Merge two lists of sorted segments by Y, and then by C.
  180764. */
  180765. static GeoSegment *geopolySegmentMerge(GeoSegment *pLeft, GeoSegment *pRight){
  180766. GeoSegment head, *pLast;
  180767. head.pNext = 0;
  180768. pLast = &head;
  180769. while( pRight && pLeft ){
  180770. double r = pRight->y - pLeft->y;
  180771. if( r==0.0 ) r = pRight->C - pLeft->C;
  180772. if( r<0.0 ){
  180773. pLast->pNext = pRight;
  180774. pLast = pRight;
  180775. pRight = pRight->pNext;
  180776. }else{
  180777. pLast->pNext = pLeft;
  180778. pLast = pLeft;
  180779. pLeft = pLeft->pNext;
  180780. }
  180781. }
  180782. pLast->pNext = pRight ? pRight : pLeft;
  180783. return head.pNext;
  180784. }
  180785. /*
  180786. ** Sort a list of GeoSegments in order of increasing Y and in the event of
  180787. ** a tie, increasing C (slope).
  180788. */
  180789. static GeoSegment *geopolySortSegmentsByYAndC(GeoSegment *pList){
  180790. int mx = 0;
  180791. int i;
  180792. GeoSegment *p;
  180793. GeoSegment *a[50];
  180794. while( pList ){
  180795. p = pList;
  180796. pList = pList->pNext;
  180797. p->pNext = 0;
  180798. for(i=0; i<mx && a[i]; i++){
  180799. p = geopolySegmentMerge(a[i], p);
  180800. a[i] = 0;
  180801. }
  180802. a[i] = p;
  180803. if( i>=mx ) mx = i+1;
  180804. }
  180805. p = 0;
  180806. for(i=0; i<mx; i++){
  180807. p = geopolySegmentMerge(a[i], p);
  180808. }
  180809. return p;
  180810. }
  180811. /*
  180812. ** Determine the overlap between two polygons
  180813. */
  180814. static int geopolyOverlap(GeoPoly *p1, GeoPoly *p2){
  180815. sqlite3_int64 nVertex = p1->nVertex + p2->nVertex + 2;
  180816. GeoOverlap *p;
  180817. sqlite3_int64 nByte;
  180818. GeoEvent *pThisEvent;
  180819. double rX;
  180820. int rc = 0;
  180821. int needSort = 0;
  180822. GeoSegment *pActive = 0;
  180823. GeoSegment *pSeg;
  180824. unsigned char aOverlap[4];
  180825. nByte = sizeof(GeoEvent)*nVertex*2
  180826. + sizeof(GeoSegment)*nVertex
  180827. + sizeof(GeoOverlap);
  180828. p = sqlite3_malloc64( nByte );
  180829. if( p==0 ) return -1;
  180830. p->aEvent = (GeoEvent*)&p[1];
  180831. p->aSegment = (GeoSegment*)&p->aEvent[nVertex*2];
  180832. p->nEvent = p->nSegment = 0;
  180833. geopolyAddSegments(p, p1, 1);
  180834. geopolyAddSegments(p, p2, 2);
  180835. pThisEvent = geopolySortEventsByX(p->aEvent, p->nEvent);
  180836. rX = pThisEvent->x==0.0 ? -1.0 : 0.0;
  180837. memset(aOverlap, 0, sizeof(aOverlap));
  180838. while( pThisEvent ){
  180839. if( pThisEvent->x!=rX ){
  180840. GeoSegment *pPrev = 0;
  180841. int iMask = 0;
  180842. GEODEBUG(("Distinct X: %g\n", pThisEvent->x));
  180843. rX = pThisEvent->x;
  180844. if( needSort ){
  180845. GEODEBUG(("SORT\n"));
  180846. pActive = geopolySortSegmentsByYAndC(pActive);
  180847. needSort = 0;
  180848. }
  180849. for(pSeg=pActive; pSeg; pSeg=pSeg->pNext){
  180850. if( pPrev ){
  180851. if( pPrev->y!=pSeg->y ){
  180852. GEODEBUG(("MASK: %d\n", iMask));
  180853. aOverlap[iMask] = 1;
  180854. }
  180855. }
  180856. iMask ^= pSeg->side;
  180857. pPrev = pSeg;
  180858. }
  180859. pPrev = 0;
  180860. for(pSeg=pActive; pSeg; pSeg=pSeg->pNext){
  180861. double y = pSeg->C*rX + pSeg->B;
  180862. GEODEBUG(("Segment %d.%d %g->%g\n", pSeg->side, pSeg->idx, pSeg->y, y));
  180863. pSeg->y = y;
  180864. if( pPrev ){
  180865. if( pPrev->y>pSeg->y && pPrev->side!=pSeg->side ){
  180866. rc = 1;
  180867. GEODEBUG(("Crossing: %d.%d and %d.%d\n",
  180868. pPrev->side, pPrev->idx,
  180869. pSeg->side, pSeg->idx));
  180870. goto geopolyOverlapDone;
  180871. }else if( pPrev->y!=pSeg->y ){
  180872. GEODEBUG(("MASK: %d\n", iMask));
  180873. aOverlap[iMask] = 1;
  180874. }
  180875. }
  180876. iMask ^= pSeg->side;
  180877. pPrev = pSeg;
  180878. }
  180879. }
  180880. GEODEBUG(("%s %d.%d C=%g B=%g\n",
  180881. pThisEvent->eType ? "RM " : "ADD",
  180882. pThisEvent->pSeg->side, pThisEvent->pSeg->idx,
  180883. pThisEvent->pSeg->C,
  180884. pThisEvent->pSeg->B));
  180885. if( pThisEvent->eType==0 ){
  180886. /* Add a segment */
  180887. pSeg = pThisEvent->pSeg;
  180888. pSeg->y = pSeg->y0;
  180889. pSeg->pNext = pActive;
  180890. pActive = pSeg;
  180891. needSort = 1;
  180892. }else{
  180893. /* Remove a segment */
  180894. if( pActive==pThisEvent->pSeg ){
  180895. pActive = pActive->pNext;
  180896. }else{
  180897. for(pSeg=pActive; pSeg; pSeg=pSeg->pNext){
  180898. if( pSeg->pNext==pThisEvent->pSeg ){
  180899. pSeg->pNext = pSeg->pNext->pNext;
  180900. break;
  180901. }
  180902. }
  180903. }
  180904. }
  180905. pThisEvent = pThisEvent->pNext;
  180906. }
  180907. if( aOverlap[3]==0 ){
  180908. rc = 0;
  180909. }else if( aOverlap[1]!=0 && aOverlap[2]==0 ){
  180910. rc = 3;
  180911. }else if( aOverlap[1]==0 && aOverlap[2]!=0 ){
  180912. rc = 2;
  180913. }else if( aOverlap[1]==0 && aOverlap[2]==0 ){
  180914. rc = 4;
  180915. }else{
  180916. rc = 1;
  180917. }
  180918. geopolyOverlapDone:
  180919. sqlite3_free(p);
  180920. return rc;
  180921. }
  180922. /*
  180923. ** SQL function: geopoly_overlap(P1,P2)
  180924. **
  180925. ** Determine whether or not P1 and P2 overlap. Return value:
  180926. **
  180927. ** 0 The two polygons are disjoint
  180928. ** 1 They overlap
  180929. ** 2 P1 is completely contained within P2
  180930. ** 3 P2 is completely contained within P1
  180931. ** 4 P1 and P2 are the same polygon
  180932. ** NULL Either P1 or P2 or both are not valid polygons
  180933. */
  180934. static void geopolyOverlapFunc(
  180935. sqlite3_context *context,
  180936. int argc,
  180937. sqlite3_value **argv
  180938. ){
  180939. GeoPoly *p1 = geopolyFuncParam(context, argv[0], 0);
  180940. GeoPoly *p2 = geopolyFuncParam(context, argv[1], 0);
  180941. if( p1 && p2 ){
  180942. int x = geopolyOverlap(p1, p2);
  180943. if( x<0 ){
  180944. sqlite3_result_error_nomem(context);
  180945. }else{
  180946. sqlite3_result_int(context, x);
  180947. }
  180948. }
  180949. sqlite3_free(p1);
  180950. sqlite3_free(p2);
  180951. }
  180952. /*
  180953. ** Enable or disable debugging output
  180954. */
  180955. static void geopolyDebugFunc(
  180956. sqlite3_context *context,
  180957. int argc,
  180958. sqlite3_value **argv
  180959. ){
  180960. #ifdef GEOPOLY_ENABLE_DEBUG
  180961. geo_debug = sqlite3_value_int(argv[0]);
  180962. #endif
  180963. }
  180964. /*
  180965. ** This function is the implementation of both the xConnect and xCreate
  180966. ** methods of the geopoly virtual table.
  180967. **
  180968. ** argv[0] -> module name
  180969. ** argv[1] -> database name
  180970. ** argv[2] -> table name
  180971. ** argv[...] -> column names...
  180972. */
  180973. static int geopolyInit(
  180974. sqlite3 *db, /* Database connection */
  180975. void *pAux, /* One of the RTREE_COORD_* constants */
  180976. int argc, const char *const*argv, /* Parameters to CREATE TABLE statement */
  180977. sqlite3_vtab **ppVtab, /* OUT: New virtual table */
  180978. char **pzErr, /* OUT: Error message, if any */
  180979. int isCreate /* True for xCreate, false for xConnect */
  180980. ){
  180981. int rc = SQLITE_OK;
  180982. Rtree *pRtree;
  180983. sqlite3_int64 nDb; /* Length of string argv[1] */
  180984. sqlite3_int64 nName; /* Length of string argv[2] */
  180985. sqlite3_str *pSql;
  180986. char *zSql;
  180987. int ii;
  180988. sqlite3_vtab_config(db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
  180989. /* Allocate the sqlite3_vtab structure */
  180990. nDb = strlen(argv[1]);
  180991. nName = strlen(argv[2]);
  180992. pRtree = (Rtree *)sqlite3_malloc64(sizeof(Rtree)+nDb+nName+2);
  180993. if( !pRtree ){
  180994. return SQLITE_NOMEM;
  180995. }
  180996. memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
  180997. pRtree->nBusy = 1;
  180998. pRtree->base.pModule = &rtreeModule;
  180999. pRtree->zDb = (char *)&pRtree[1];
  181000. pRtree->zName = &pRtree->zDb[nDb+1];
  181001. pRtree->eCoordType = RTREE_COORD_REAL32;
  181002. pRtree->nDim = 2;
  181003. pRtree->nDim2 = 4;
  181004. memcpy(pRtree->zDb, argv[1], nDb);
  181005. memcpy(pRtree->zName, argv[2], nName);
  181006. /* Create/Connect to the underlying relational database schema. If
  181007. ** that is successful, call sqlite3_declare_vtab() to configure
  181008. ** the r-tree table schema.
  181009. */
  181010. pSql = sqlite3_str_new(db);
  181011. sqlite3_str_appendf(pSql, "CREATE TABLE x(_shape");
  181012. pRtree->nAux = 1; /* Add one for _shape */
  181013. pRtree->nAuxNotNull = 1; /* The _shape column is always not-null */
  181014. for(ii=3; ii<argc; ii++){
  181015. pRtree->nAux++;
  181016. sqlite3_str_appendf(pSql, ",%s", argv[ii]);
  181017. }
  181018. sqlite3_str_appendf(pSql, ");");
  181019. zSql = sqlite3_str_finish(pSql);
  181020. if( !zSql ){
  181021. rc = SQLITE_NOMEM;
  181022. }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
  181023. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  181024. }
  181025. sqlite3_free(zSql);
  181026. if( rc ) goto geopolyInit_fail;
  181027. pRtree->nBytesPerCell = 8 + pRtree->nDim2*4;
  181028. /* Figure out the node size to use. */
  181029. rc = getNodeSize(db, pRtree, isCreate, pzErr);
  181030. if( rc ) goto geopolyInit_fail;
  181031. rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate);
  181032. if( rc ){
  181033. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  181034. goto geopolyInit_fail;
  181035. }
  181036. *ppVtab = (sqlite3_vtab *)pRtree;
  181037. return SQLITE_OK;
  181038. geopolyInit_fail:
  181039. if( rc==SQLITE_OK ) rc = SQLITE_ERROR;
  181040. assert( *ppVtab==0 );
  181041. assert( pRtree->nBusy==1 );
  181042. rtreeRelease(pRtree);
  181043. return rc;
  181044. }
  181045. /*
  181046. ** GEOPOLY virtual table module xCreate method.
  181047. */
  181048. static int geopolyCreate(
  181049. sqlite3 *db,
  181050. void *pAux,
  181051. int argc, const char *const*argv,
  181052. sqlite3_vtab **ppVtab,
  181053. char **pzErr
  181054. ){
  181055. return geopolyInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
  181056. }
  181057. /*
  181058. ** GEOPOLY virtual table module xConnect method.
  181059. */
  181060. static int geopolyConnect(
  181061. sqlite3 *db,
  181062. void *pAux,
  181063. int argc, const char *const*argv,
  181064. sqlite3_vtab **ppVtab,
  181065. char **pzErr
  181066. ){
  181067. return geopolyInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
  181068. }
  181069. /*
  181070. ** GEOPOLY virtual table module xFilter method.
  181071. **
  181072. ** Query plans:
  181073. **
  181074. ** 1 rowid lookup
  181075. ** 2 search for objects overlapping the same bounding box
  181076. ** that contains polygon argv[0]
  181077. ** 3 search for objects overlapping the same bounding box
  181078. ** that contains polygon argv[0]
  181079. ** 4 full table scan
  181080. */
  181081. static int geopolyFilter(
  181082. sqlite3_vtab_cursor *pVtabCursor, /* The cursor to initialize */
  181083. int idxNum, /* Query plan */
  181084. const char *idxStr, /* Not Used */
  181085. int argc, sqlite3_value **argv /* Parameters to the query plan */
  181086. ){
  181087. Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
  181088. RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
  181089. RtreeNode *pRoot = 0;
  181090. int rc = SQLITE_OK;
  181091. int iCell = 0;
  181092. rtreeReference(pRtree);
  181093. /* Reset the cursor to the same state as rtreeOpen() leaves it in. */
  181094. resetCursor(pCsr);
  181095. pCsr->iStrategy = idxNum;
  181096. if( idxNum==1 ){
  181097. /* Special case - lookup by rowid. */
  181098. RtreeNode *pLeaf; /* Leaf on which the required cell resides */
  181099. RtreeSearchPoint *p; /* Search point for the leaf */
  181100. i64 iRowid = sqlite3_value_int64(argv[0]);
  181101. i64 iNode = 0;
  181102. rc = findLeafNode(pRtree, iRowid, &pLeaf, &iNode);
  181103. if( rc==SQLITE_OK && pLeaf!=0 ){
  181104. p = rtreeSearchPointNew(pCsr, RTREE_ZERO, 0);
  181105. assert( p!=0 ); /* Always returns pCsr->sPoint */
  181106. pCsr->aNode[0] = pLeaf;
  181107. p->id = iNode;
  181108. p->eWithin = PARTLY_WITHIN;
  181109. rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &iCell);
  181110. p->iCell = (u8)iCell;
  181111. RTREE_QUEUE_TRACE(pCsr, "PUSH-F1:");
  181112. }else{
  181113. pCsr->atEOF = 1;
  181114. }
  181115. }else{
  181116. /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array
  181117. ** with the configured constraints.
  181118. */
  181119. rc = nodeAcquire(pRtree, 1, 0, &pRoot);
  181120. if( rc==SQLITE_OK && idxNum<=3 ){
  181121. RtreeCoord bbox[4];
  181122. RtreeConstraint *p;
  181123. assert( argc==1 );
  181124. geopolyBBox(0, argv[0], bbox, &rc);
  181125. if( rc ){
  181126. goto geopoly_filter_end;
  181127. }
  181128. pCsr->aConstraint = p = sqlite3_malloc(sizeof(RtreeConstraint)*4);
  181129. pCsr->nConstraint = 4;
  181130. if( p==0 ){
  181131. rc = SQLITE_NOMEM;
  181132. }else{
  181133. memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*4);
  181134. memset(pCsr->anQueue, 0, sizeof(u32)*(pRtree->iDepth + 1));
  181135. if( idxNum==2 ){
  181136. /* Overlap query */
  181137. p->op = 'B';
  181138. p->iCoord = 0;
  181139. p->u.rValue = bbox[1].f;
  181140. p++;
  181141. p->op = 'D';
  181142. p->iCoord = 1;
  181143. p->u.rValue = bbox[0].f;
  181144. p++;
  181145. p->op = 'B';
  181146. p->iCoord = 2;
  181147. p->u.rValue = bbox[3].f;
  181148. p++;
  181149. p->op = 'D';
  181150. p->iCoord = 3;
  181151. p->u.rValue = bbox[2].f;
  181152. }else{
  181153. /* Within query */
  181154. p->op = 'D';
  181155. p->iCoord = 0;
  181156. p->u.rValue = bbox[0].f;
  181157. p++;
  181158. p->op = 'B';
  181159. p->iCoord = 1;
  181160. p->u.rValue = bbox[1].f;
  181161. p++;
  181162. p->op = 'D';
  181163. p->iCoord = 2;
  181164. p->u.rValue = bbox[2].f;
  181165. p++;
  181166. p->op = 'B';
  181167. p->iCoord = 3;
  181168. p->u.rValue = bbox[3].f;
  181169. }
  181170. }
  181171. }
  181172. if( rc==SQLITE_OK ){
  181173. RtreeSearchPoint *pNew;
  181174. pNew = rtreeSearchPointNew(pCsr, RTREE_ZERO, (u8)(pRtree->iDepth+1));
  181175. if( pNew==0 ){
  181176. rc = SQLITE_NOMEM;
  181177. goto geopoly_filter_end;
  181178. }
  181179. pNew->id = 1;
  181180. pNew->iCell = 0;
  181181. pNew->eWithin = PARTLY_WITHIN;
  181182. assert( pCsr->bPoint==1 );
  181183. pCsr->aNode[0] = pRoot;
  181184. pRoot = 0;
  181185. RTREE_QUEUE_TRACE(pCsr, "PUSH-Fm:");
  181186. rc = rtreeStepToLeaf(pCsr);
  181187. }
  181188. }
  181189. geopoly_filter_end:
  181190. nodeRelease(pRtree, pRoot);
  181191. rtreeRelease(pRtree);
  181192. return rc;
  181193. }
  181194. /*
  181195. ** Rtree virtual table module xBestIndex method. There are three
  181196. ** table scan strategies to choose from (in order from most to
  181197. ** least desirable):
  181198. **
  181199. ** idxNum idxStr Strategy
  181200. ** ------------------------------------------------
  181201. ** 1 "rowid" Direct lookup by rowid.
  181202. ** 2 "rtree" R-tree overlap query using geopoly_overlap()
  181203. ** 3 "rtree" R-tree within query using geopoly_within()
  181204. ** 4 "fullscan" full-table scan.
  181205. ** ------------------------------------------------
  181206. */
  181207. static int geopolyBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
  181208. int ii;
  181209. int iRowidTerm = -1;
  181210. int iFuncTerm = -1;
  181211. int idxNum = 0;
  181212. for(ii=0; ii<pIdxInfo->nConstraint; ii++){
  181213. struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
  181214. if( !p->usable ) continue;
  181215. if( p->iColumn<0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
  181216. iRowidTerm = ii;
  181217. break;
  181218. }
  181219. if( p->iColumn==0 && p->op>=SQLITE_INDEX_CONSTRAINT_FUNCTION ){
  181220. /* p->op==SQLITE_INDEX_CONSTRAINT_FUNCTION for geopoly_overlap()
  181221. ** p->op==(SQLITE_INDEX_CONTRAINT_FUNCTION+1) for geopoly_within().
  181222. ** See geopolyFindFunction() */
  181223. iFuncTerm = ii;
  181224. idxNum = p->op - SQLITE_INDEX_CONSTRAINT_FUNCTION + 2;
  181225. }
  181226. }
  181227. if( iRowidTerm>=0 ){
  181228. pIdxInfo->idxNum = 1;
  181229. pIdxInfo->idxStr = "rowid";
  181230. pIdxInfo->aConstraintUsage[iRowidTerm].argvIndex = 1;
  181231. pIdxInfo->aConstraintUsage[iRowidTerm].omit = 1;
  181232. pIdxInfo->estimatedCost = 30.0;
  181233. pIdxInfo->estimatedRows = 1;
  181234. pIdxInfo->idxFlags = SQLITE_INDEX_SCAN_UNIQUE;
  181235. return SQLITE_OK;
  181236. }
  181237. if( iFuncTerm>=0 ){
  181238. pIdxInfo->idxNum = idxNum;
  181239. pIdxInfo->idxStr = "rtree";
  181240. pIdxInfo->aConstraintUsage[iFuncTerm].argvIndex = 1;
  181241. pIdxInfo->aConstraintUsage[iFuncTerm].omit = 0;
  181242. pIdxInfo->estimatedCost = 300.0;
  181243. pIdxInfo->estimatedRows = 10;
  181244. return SQLITE_OK;
  181245. }
  181246. pIdxInfo->idxNum = 4;
  181247. pIdxInfo->idxStr = "fullscan";
  181248. pIdxInfo->estimatedCost = 3000000.0;
  181249. pIdxInfo->estimatedRows = 100000;
  181250. return SQLITE_OK;
  181251. }
  181252. /*
  181253. ** GEOPOLY virtual table module xColumn method.
  181254. */
  181255. static int geopolyColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
  181256. Rtree *pRtree = (Rtree *)cur->pVtab;
  181257. RtreeCursor *pCsr = (RtreeCursor *)cur;
  181258. RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);
  181259. int rc = SQLITE_OK;
  181260. RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
  181261. if( rc ) return rc;
  181262. if( p==0 ) return SQLITE_OK;
  181263. if( i==0 && sqlite3_vtab_nochange(ctx) ) return SQLITE_OK;
  181264. if( i<=pRtree->nAux ){
  181265. if( !pCsr->bAuxValid ){
  181266. if( pCsr->pReadAux==0 ){
  181267. rc = sqlite3_prepare_v3(pRtree->db, pRtree->zReadAuxSql, -1, 0,
  181268. &pCsr->pReadAux, 0);
  181269. if( rc ) return rc;
  181270. }
  181271. sqlite3_bind_int64(pCsr->pReadAux, 1,
  181272. nodeGetRowid(pRtree, pNode, p->iCell));
  181273. rc = sqlite3_step(pCsr->pReadAux);
  181274. if( rc==SQLITE_ROW ){
  181275. pCsr->bAuxValid = 1;
  181276. }else{
  181277. sqlite3_reset(pCsr->pReadAux);
  181278. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  181279. return rc;
  181280. }
  181281. }
  181282. sqlite3_result_value(ctx, sqlite3_column_value(pCsr->pReadAux, i+2));
  181283. }
  181284. return SQLITE_OK;
  181285. }
  181286. /*
  181287. ** The xUpdate method for GEOPOLY module virtual tables.
  181288. **
  181289. ** For DELETE:
  181290. **
  181291. ** argv[0] = the rowid to be deleted
  181292. **
  181293. ** For INSERT:
  181294. **
  181295. ** argv[0] = SQL NULL
  181296. ** argv[1] = rowid to insert, or an SQL NULL to select automatically
  181297. ** argv[2] = _shape column
  181298. ** argv[3] = first application-defined column....
  181299. **
  181300. ** For UPDATE:
  181301. **
  181302. ** argv[0] = rowid to modify. Never NULL
  181303. ** argv[1] = rowid after the change. Never NULL
  181304. ** argv[2] = new value for _shape
  181305. ** argv[3] = new value for first application-defined column....
  181306. */
  181307. static int geopolyUpdate(
  181308. sqlite3_vtab *pVtab,
  181309. int nData,
  181310. sqlite3_value **aData,
  181311. sqlite_int64 *pRowid
  181312. ){
  181313. Rtree *pRtree = (Rtree *)pVtab;
  181314. int rc = SQLITE_OK;
  181315. RtreeCell cell; /* New cell to insert if nData>1 */
  181316. i64 oldRowid; /* The old rowid */
  181317. int oldRowidValid; /* True if oldRowid is valid */
  181318. i64 newRowid; /* The new rowid */
  181319. int newRowidValid; /* True if newRowid is valid */
  181320. int coordChange = 0; /* Change in coordinates */
  181321. if( pRtree->nNodeRef ){
  181322. /* Unable to write to the btree while another cursor is reading from it,
  181323. ** since the write might do a rebalance which would disrupt the read
  181324. ** cursor. */
  181325. return SQLITE_LOCKED_VTAB;
  181326. }
  181327. rtreeReference(pRtree);
  181328. assert(nData>=1);
  181329. oldRowidValid = sqlite3_value_type(aData[0])!=SQLITE_NULL;;
  181330. oldRowid = oldRowidValid ? sqlite3_value_int64(aData[0]) : 0;
  181331. newRowidValid = nData>1 && sqlite3_value_type(aData[1])!=SQLITE_NULL;
  181332. newRowid = newRowidValid ? sqlite3_value_int64(aData[1]) : 0;
  181333. cell.iRowid = newRowid;
  181334. if( nData>1 /* not a DELETE */
  181335. && (!oldRowidValid /* INSERT */
  181336. || !sqlite3_value_nochange(aData[2]) /* UPDATE _shape */
  181337. || oldRowid!=newRowid) /* Rowid change */
  181338. ){
  181339. geopolyBBox(0, aData[2], cell.aCoord, &rc);
  181340. if( rc ){
  181341. if( rc==SQLITE_ERROR ){
  181342. pVtab->zErrMsg =
  181343. sqlite3_mprintf("_shape does not contain a valid polygon");
  181344. }
  181345. goto geopoly_update_end;
  181346. }
  181347. coordChange = 1;
  181348. /* If a rowid value was supplied, check if it is already present in
  181349. ** the table. If so, the constraint has failed. */
  181350. if( newRowidValid && (!oldRowidValid || oldRowid!=newRowid) ){
  181351. int steprc;
  181352. sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
  181353. steprc = sqlite3_step(pRtree->pReadRowid);
  181354. rc = sqlite3_reset(pRtree->pReadRowid);
  181355. if( SQLITE_ROW==steprc ){
  181356. if( sqlite3_vtab_on_conflict(pRtree->db)==SQLITE_REPLACE ){
  181357. rc = rtreeDeleteRowid(pRtree, cell.iRowid);
  181358. }else{
  181359. rc = rtreeConstraintError(pRtree, 0);
  181360. }
  181361. }
  181362. }
  181363. }
  181364. /* If aData[0] is not an SQL NULL value, it is the rowid of a
  181365. ** record to delete from the r-tree table. The following block does
  181366. ** just that.
  181367. */
  181368. if( rc==SQLITE_OK && (nData==1 || (coordChange && oldRowidValid)) ){
  181369. rc = rtreeDeleteRowid(pRtree, oldRowid);
  181370. }
  181371. /* If the aData[] array contains more than one element, elements
  181372. ** (aData[2]..aData[argc-1]) contain a new record to insert into
  181373. ** the r-tree structure.
  181374. */
  181375. if( rc==SQLITE_OK && nData>1 && coordChange ){
  181376. /* Insert the new record into the r-tree */
  181377. RtreeNode *pLeaf = 0;
  181378. if( !newRowidValid ){
  181379. rc = rtreeNewRowid(pRtree, &cell.iRowid);
  181380. }
  181381. *pRowid = cell.iRowid;
  181382. if( rc==SQLITE_OK ){
  181383. rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
  181384. }
  181385. if( rc==SQLITE_OK ){
  181386. int rc2;
  181387. pRtree->iReinsertHeight = -1;
  181388. rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
  181389. rc2 = nodeRelease(pRtree, pLeaf);
  181390. if( rc==SQLITE_OK ){
  181391. rc = rc2;
  181392. }
  181393. }
  181394. }
  181395. /* Change the data */
  181396. if( rc==SQLITE_OK && nData>1 ){
  181397. sqlite3_stmt *pUp = pRtree->pWriteAux;
  181398. int jj;
  181399. int nChange = 0;
  181400. sqlite3_bind_int64(pUp, 1, cell.iRowid);
  181401. assert( pRtree->nAux>=1 );
  181402. if( sqlite3_value_nochange(aData[2]) ){
  181403. sqlite3_bind_null(pUp, 2);
  181404. }else{
  181405. GeoPoly *p = 0;
  181406. if( sqlite3_value_type(aData[2])==SQLITE_TEXT
  181407. && (p = geopolyFuncParam(0, aData[2], &rc))!=0
  181408. && rc==SQLITE_OK
  181409. ){
  181410. sqlite3_bind_blob(pUp, 2, p->hdr, 4+8*p->nVertex, SQLITE_TRANSIENT);
  181411. }else{
  181412. sqlite3_bind_value(pUp, 2, aData[2]);
  181413. }
  181414. sqlite3_free(p);
  181415. nChange = 1;
  181416. }
  181417. for(jj=1; jj<pRtree->nAux; jj++){
  181418. nChange++;
  181419. sqlite3_bind_value(pUp, jj+2, aData[jj+2]);
  181420. }
  181421. if( nChange ){
  181422. sqlite3_step(pUp);
  181423. rc = sqlite3_reset(pUp);
  181424. }
  181425. }
  181426. geopoly_update_end:
  181427. rtreeRelease(pRtree);
  181428. return rc;
  181429. }
  181430. /*
  181431. ** Report that geopoly_overlap() is an overloaded function suitable
  181432. ** for use in xBestIndex.
  181433. */
  181434. static int geopolyFindFunction(
  181435. sqlite3_vtab *pVtab,
  181436. int nArg,
  181437. const char *zName,
  181438. void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
  181439. void **ppArg
  181440. ){
  181441. if( sqlite3_stricmp(zName, "geopoly_overlap")==0 ){
  181442. *pxFunc = geopolyOverlapFunc;
  181443. *ppArg = 0;
  181444. return SQLITE_INDEX_CONSTRAINT_FUNCTION;
  181445. }
  181446. if( sqlite3_stricmp(zName, "geopoly_within")==0 ){
  181447. *pxFunc = geopolyWithinFunc;
  181448. *ppArg = 0;
  181449. return SQLITE_INDEX_CONSTRAINT_FUNCTION+1;
  181450. }
  181451. return 0;
  181452. }
  181453. static sqlite3_module geopolyModule = {
  181454. 3, /* iVersion */
  181455. geopolyCreate, /* xCreate - create a table */
  181456. geopolyConnect, /* xConnect - connect to an existing table */
  181457. geopolyBestIndex, /* xBestIndex - Determine search strategy */
  181458. rtreeDisconnect, /* xDisconnect - Disconnect from a table */
  181459. rtreeDestroy, /* xDestroy - Drop a table */
  181460. rtreeOpen, /* xOpen - open a cursor */
  181461. rtreeClose, /* xClose - close a cursor */
  181462. geopolyFilter, /* xFilter - configure scan constraints */
  181463. rtreeNext, /* xNext - advance a cursor */
  181464. rtreeEof, /* xEof */
  181465. geopolyColumn, /* xColumn - read data */
  181466. rtreeRowid, /* xRowid - read data */
  181467. geopolyUpdate, /* xUpdate - write data */
  181468. rtreeBeginTransaction, /* xBegin - begin transaction */
  181469. rtreeEndTransaction, /* xSync - sync transaction */
  181470. rtreeEndTransaction, /* xCommit - commit transaction */
  181471. rtreeEndTransaction, /* xRollback - rollback transaction */
  181472. geopolyFindFunction, /* xFindFunction - function overloading */
  181473. rtreeRename, /* xRename - rename the table */
  181474. rtreeSavepoint, /* xSavepoint */
  181475. 0, /* xRelease */
  181476. 0, /* xRollbackTo */
  181477. rtreeShadowName /* xShadowName */
  181478. };
  181479. static int sqlite3_geopoly_init(sqlite3 *db){
  181480. int rc = SQLITE_OK;
  181481. static const struct {
  181482. void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
  181483. signed char nArg;
  181484. unsigned char bPure;
  181485. const char *zName;
  181486. } aFunc[] = {
  181487. { geopolyAreaFunc, 1, 1, "geopoly_area" },
  181488. { geopolyBlobFunc, 1, 1, "geopoly_blob" },
  181489. { geopolyJsonFunc, 1, 1, "geopoly_json" },
  181490. { geopolySvgFunc, -1, 1, "geopoly_svg" },
  181491. { geopolyWithinFunc, 2, 1, "geopoly_within" },
  181492. { geopolyContainsPointFunc, 3, 1, "geopoly_contains_point" },
  181493. { geopolyOverlapFunc, 2, 1, "geopoly_overlap" },
  181494. { geopolyDebugFunc, 1, 0, "geopoly_debug" },
  181495. { geopolyBBoxFunc, 1, 1, "geopoly_bbox" },
  181496. { geopolyXformFunc, 7, 1, "geopoly_xform" },
  181497. { geopolyRegularFunc, 4, 1, "geopoly_regular" },
  181498. { geopolyCcwFunc, 1, 1, "geopoly_ccw" },
  181499. };
  181500. static const struct {
  181501. void (*xStep)(sqlite3_context*,int,sqlite3_value**);
  181502. void (*xFinal)(sqlite3_context*);
  181503. const char *zName;
  181504. } aAgg[] = {
  181505. { geopolyBBoxStep, geopolyBBoxFinal, "geopoly_group_bbox" },
  181506. };
  181507. int i;
  181508. for(i=0; i<sizeof(aFunc)/sizeof(aFunc[0]) && rc==SQLITE_OK; i++){
  181509. int enc;
  181510. if( aFunc[i].bPure ){
  181511. enc = SQLITE_UTF8|SQLITE_DETERMINISTIC|SQLITE_INNOCUOUS;
  181512. }else{
  181513. enc = SQLITE_UTF8|SQLITE_DIRECTONLY;
  181514. }
  181515. rc = sqlite3_create_function(db, aFunc[i].zName, aFunc[i].nArg,
  181516. enc, 0,
  181517. aFunc[i].xFunc, 0, 0);
  181518. }
  181519. for(i=0; i<sizeof(aAgg)/sizeof(aAgg[0]) && rc==SQLITE_OK; i++){
  181520. rc = sqlite3_create_function(db, aAgg[i].zName, 1,
  181521. SQLITE_UTF8|SQLITE_DETERMINISTIC|SQLITE_INNOCUOUS, 0,
  181522. 0, aAgg[i].xStep, aAgg[i].xFinal);
  181523. }
  181524. if( rc==SQLITE_OK ){
  181525. rc = sqlite3_create_module_v2(db, "geopoly", &geopolyModule, 0, 0);
  181526. }
  181527. return rc;
  181528. }
  181529. /************** End of geopoly.c *********************************************/
  181530. /************** Continuing where we left off in rtree.c **********************/
  181531. #endif
  181532. /*
  181533. ** Register the r-tree module with database handle db. This creates the
  181534. ** virtual table module "rtree" and the debugging/analysis scalar
  181535. ** function "rtreenode".
  181536. */
  181537. SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){
  181538. const int utf8 = SQLITE_UTF8;
  181539. int rc;
  181540. rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
  181541. if( rc==SQLITE_OK ){
  181542. rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
  181543. }
  181544. if( rc==SQLITE_OK ){
  181545. rc = sqlite3_create_function(db, "rtreecheck", -1, utf8, 0,rtreecheck, 0,0);
  181546. }
  181547. if( rc==SQLITE_OK ){
  181548. #ifdef SQLITE_RTREE_INT_ONLY
  181549. void *c = (void *)RTREE_COORD_INT32;
  181550. #else
  181551. void *c = (void *)RTREE_COORD_REAL32;
  181552. #endif
  181553. rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
  181554. }
  181555. if( rc==SQLITE_OK ){
  181556. void *c = (void *)RTREE_COORD_INT32;
  181557. rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
  181558. }
  181559. #ifdef SQLITE_ENABLE_GEOPOLY
  181560. if( rc==SQLITE_OK ){
  181561. rc = sqlite3_geopoly_init(db);
  181562. }
  181563. #endif
  181564. return rc;
  181565. }
  181566. /*
  181567. ** This routine deletes the RtreeGeomCallback object that was attached
  181568. ** one of the SQL functions create by sqlite3_rtree_geometry_callback()
  181569. ** or sqlite3_rtree_query_callback(). In other words, this routine is the
  181570. ** destructor for an RtreeGeomCallback objecct. This routine is called when
  181571. ** the corresponding SQL function is deleted.
  181572. */
  181573. static void rtreeFreeCallback(void *p){
  181574. RtreeGeomCallback *pInfo = (RtreeGeomCallback*)p;
  181575. if( pInfo->xDestructor ) pInfo->xDestructor(pInfo->pContext);
  181576. sqlite3_free(p);
  181577. }
  181578. /*
  181579. ** This routine frees the BLOB that is returned by geomCallback().
  181580. */
  181581. static void rtreeMatchArgFree(void *pArg){
  181582. int i;
  181583. RtreeMatchArg *p = (RtreeMatchArg*)pArg;
  181584. for(i=0; i<p->nParam; i++){
  181585. sqlite3_value_free(p->apSqlParam[i]);
  181586. }
  181587. sqlite3_free(p);
  181588. }
  181589. /*
  181590. ** Each call to sqlite3_rtree_geometry_callback() or
  181591. ** sqlite3_rtree_query_callback() creates an ordinary SQLite
  181592. ** scalar function that is implemented by this routine.
  181593. **
  181594. ** All this function does is construct an RtreeMatchArg object that
  181595. ** contains the geometry-checking callback routines and a list of
  181596. ** parameters to this function, then return that RtreeMatchArg object
  181597. ** as a BLOB.
  181598. **
  181599. ** The R-Tree MATCH operator will read the returned BLOB, deserialize
  181600. ** the RtreeMatchArg object, and use the RtreeMatchArg object to figure
  181601. ** out which elements of the R-Tree should be returned by the query.
  181602. */
  181603. static void geomCallback(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){
  181604. RtreeGeomCallback *pGeomCtx = (RtreeGeomCallback *)sqlite3_user_data(ctx);
  181605. RtreeMatchArg *pBlob;
  181606. sqlite3_int64 nBlob;
  181607. int memErr = 0;
  181608. nBlob = sizeof(RtreeMatchArg) + (nArg-1)*sizeof(RtreeDValue)
  181609. + nArg*sizeof(sqlite3_value*);
  181610. pBlob = (RtreeMatchArg *)sqlite3_malloc64(nBlob);
  181611. if( !pBlob ){
  181612. sqlite3_result_error_nomem(ctx);
  181613. }else{
  181614. int i;
  181615. pBlob->iSize = nBlob;
  181616. pBlob->cb = pGeomCtx[0];
  181617. pBlob->apSqlParam = (sqlite3_value**)&pBlob->aParam[nArg];
  181618. pBlob->nParam = nArg;
  181619. for(i=0; i<nArg; i++){
  181620. pBlob->apSqlParam[i] = sqlite3_value_dup(aArg[i]);
  181621. if( pBlob->apSqlParam[i]==0 ) memErr = 1;
  181622. #ifdef SQLITE_RTREE_INT_ONLY
  181623. pBlob->aParam[i] = sqlite3_value_int64(aArg[i]);
  181624. #else
  181625. pBlob->aParam[i] = sqlite3_value_double(aArg[i]);
  181626. #endif
  181627. }
  181628. if( memErr ){
  181629. sqlite3_result_error_nomem(ctx);
  181630. rtreeMatchArgFree(pBlob);
  181631. }else{
  181632. sqlite3_result_pointer(ctx, pBlob, "RtreeMatchArg", rtreeMatchArgFree);
  181633. }
  181634. }
  181635. }
  181636. /*
  181637. ** Register a new geometry function for use with the r-tree MATCH operator.
  181638. */
  181639. SQLITE_API int sqlite3_rtree_geometry_callback(
  181640. sqlite3 *db, /* Register SQL function on this connection */
  181641. const char *zGeom, /* Name of the new SQL function */
  181642. int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*), /* Callback */
  181643. void *pContext /* Extra data associated with the callback */
  181644. ){
  181645. RtreeGeomCallback *pGeomCtx; /* Context object for new user-function */
  181646. /* Allocate and populate the context object. */
  181647. pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
  181648. if( !pGeomCtx ) return SQLITE_NOMEM;
  181649. pGeomCtx->xGeom = xGeom;
  181650. pGeomCtx->xQueryFunc = 0;
  181651. pGeomCtx->xDestructor = 0;
  181652. pGeomCtx->pContext = pContext;
  181653. return sqlite3_create_function_v2(db, zGeom, -1, SQLITE_ANY,
  181654. (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback
  181655. );
  181656. }
  181657. /*
  181658. ** Register a new 2nd-generation geometry function for use with the
  181659. ** r-tree MATCH operator.
  181660. */
  181661. SQLITE_API int sqlite3_rtree_query_callback(
  181662. sqlite3 *db, /* Register SQL function on this connection */
  181663. const char *zQueryFunc, /* Name of new SQL function */
  181664. int (*xQueryFunc)(sqlite3_rtree_query_info*), /* Callback */
  181665. void *pContext, /* Extra data passed into the callback */
  181666. void (*xDestructor)(void*) /* Destructor for the extra data */
  181667. ){
  181668. RtreeGeomCallback *pGeomCtx; /* Context object for new user-function */
  181669. /* Allocate and populate the context object. */
  181670. pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
  181671. if( !pGeomCtx ) return SQLITE_NOMEM;
  181672. pGeomCtx->xGeom = 0;
  181673. pGeomCtx->xQueryFunc = xQueryFunc;
  181674. pGeomCtx->xDestructor = xDestructor;
  181675. pGeomCtx->pContext = pContext;
  181676. return sqlite3_create_function_v2(db, zQueryFunc, -1, SQLITE_ANY,
  181677. (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback
  181678. );
  181679. }
  181680. #if !SQLITE_CORE
  181681. #ifdef _WIN32
  181682. __declspec(dllexport)
  181683. #endif
  181684. SQLITE_API int sqlite3_rtree_init(
  181685. sqlite3 *db,
  181686. char **pzErrMsg,
  181687. const sqlite3_api_routines *pApi
  181688. ){
  181689. SQLITE_EXTENSION_INIT2(pApi)
  181690. return sqlite3RtreeInit(db);
  181691. }
  181692. #endif
  181693. #endif
  181694. /************** End of rtree.c ***********************************************/
  181695. /************** Begin file icu.c *********************************************/
  181696. /*
  181697. ** 2007 May 6
  181698. **
  181699. ** The author disclaims copyright to this source code. In place of
  181700. ** a legal notice, here is a blessing:
  181701. **
  181702. ** May you do good and not evil.
  181703. ** May you find forgiveness for yourself and forgive others.
  181704. ** May you share freely, never taking more than you give.
  181705. **
  181706. *************************************************************************
  181707. ** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $
  181708. **
  181709. ** This file implements an integration between the ICU library
  181710. ** ("International Components for Unicode", an open-source library
  181711. ** for handling unicode data) and SQLite. The integration uses
  181712. ** ICU to provide the following to SQLite:
  181713. **
  181714. ** * An implementation of the SQL regexp() function (and hence REGEXP
  181715. ** operator) using the ICU uregex_XX() APIs.
  181716. **
  181717. ** * Implementations of the SQL scalar upper() and lower() functions
  181718. ** for case mapping.
  181719. **
  181720. ** * Integration of ICU and SQLite collation sequences.
  181721. **
  181722. ** * An implementation of the LIKE operator that uses ICU to
  181723. ** provide case-independent matching.
  181724. */
  181725. #if !defined(SQLITE_CORE) \
  181726. || defined(SQLITE_ENABLE_ICU) \
  181727. || defined(SQLITE_ENABLE_ICU_COLLATIONS)
  181728. /* Include ICU headers */
  181729. #include <unicode/utypes.h>
  181730. #include <unicode/uregex.h>
  181731. #include <unicode/ustring.h>
  181732. #include <unicode/ucol.h>
  181733. /* #include <assert.h> */
  181734. #ifndef SQLITE_CORE
  181735. /* #include "sqlite3ext.h" */
  181736. SQLITE_EXTENSION_INIT1
  181737. #else
  181738. /* #include "sqlite3.h" */
  181739. #endif
  181740. /*
  181741. ** This function is called when an ICU function called from within
  181742. ** the implementation of an SQL scalar function returns an error.
  181743. **
  181744. ** The scalar function context passed as the first argument is
  181745. ** loaded with an error message based on the following two args.
  181746. */
  181747. static void icuFunctionError(
  181748. sqlite3_context *pCtx, /* SQLite scalar function context */
  181749. const char *zName, /* Name of ICU function that failed */
  181750. UErrorCode e /* Error code returned by ICU function */
  181751. ){
  181752. char zBuf[128];
  181753. sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e));
  181754. zBuf[127] = '\0';
  181755. sqlite3_result_error(pCtx, zBuf, -1);
  181756. }
  181757. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
  181758. /*
  181759. ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
  181760. ** operator.
  181761. */
  181762. #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
  181763. # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
  181764. #endif
  181765. /*
  181766. ** Version of sqlite3_free() that is always a function, never a macro.
  181767. */
  181768. static void xFree(void *p){
  181769. sqlite3_free(p);
  181770. }
  181771. /*
  181772. ** This lookup table is used to help decode the first byte of
  181773. ** a multi-byte UTF8 character. It is copied here from SQLite source
  181774. ** code file utf8.c.
  181775. */
  181776. static const unsigned char icuUtf8Trans1[] = {
  181777. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  181778. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  181779. 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
  181780. 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
  181781. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  181782. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  181783. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  181784. 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
  181785. };
  181786. #define SQLITE_ICU_READ_UTF8(zIn, c) \
  181787. c = *(zIn++); \
  181788. if( c>=0xc0 ){ \
  181789. c = icuUtf8Trans1[c-0xc0]; \
  181790. while( (*zIn & 0xc0)==0x80 ){ \
  181791. c = (c<<6) + (0x3f & *(zIn++)); \
  181792. } \
  181793. }
  181794. #define SQLITE_ICU_SKIP_UTF8(zIn) \
  181795. assert( *zIn ); \
  181796. if( *(zIn++)>=0xc0 ){ \
  181797. while( (*zIn & 0xc0)==0x80 ){zIn++;} \
  181798. }
  181799. /*
  181800. ** Compare two UTF-8 strings for equality where the first string is
  181801. ** a "LIKE" expression. Return true (1) if they are the same and
  181802. ** false (0) if they are different.
  181803. */
  181804. static int icuLikeCompare(
  181805. const uint8_t *zPattern, /* LIKE pattern */
  181806. const uint8_t *zString, /* The UTF-8 string to compare against */
  181807. const UChar32 uEsc /* The escape character */
  181808. ){
  181809. static const uint32_t MATCH_ONE = (uint32_t)'_';
  181810. static const uint32_t MATCH_ALL = (uint32_t)'%';
  181811. int prevEscape = 0; /* True if the previous character was uEsc */
  181812. while( 1 ){
  181813. /* Read (and consume) the next character from the input pattern. */
  181814. uint32_t uPattern;
  181815. SQLITE_ICU_READ_UTF8(zPattern, uPattern);
  181816. if( uPattern==0 ) break;
  181817. /* There are now 4 possibilities:
  181818. **
  181819. ** 1. uPattern is an unescaped match-all character "%",
  181820. ** 2. uPattern is an unescaped match-one character "_",
  181821. ** 3. uPattern is an unescaped escape character, or
  181822. ** 4. uPattern is to be handled as an ordinary character
  181823. */
  181824. if( uPattern==MATCH_ALL && !prevEscape && uPattern!=(uint32_t)uEsc ){
  181825. /* Case 1. */
  181826. uint8_t c;
  181827. /* Skip any MATCH_ALL or MATCH_ONE characters that follow a
  181828. ** MATCH_ALL. For each MATCH_ONE, skip one character in the
  181829. ** test string.
  181830. */
  181831. while( (c=*zPattern) == MATCH_ALL || c == MATCH_ONE ){
  181832. if( c==MATCH_ONE ){
  181833. if( *zString==0 ) return 0;
  181834. SQLITE_ICU_SKIP_UTF8(zString);
  181835. }
  181836. zPattern++;
  181837. }
  181838. if( *zPattern==0 ) return 1;
  181839. while( *zString ){
  181840. if( icuLikeCompare(zPattern, zString, uEsc) ){
  181841. return 1;
  181842. }
  181843. SQLITE_ICU_SKIP_UTF8(zString);
  181844. }
  181845. return 0;
  181846. }else if( uPattern==MATCH_ONE && !prevEscape && uPattern!=(uint32_t)uEsc ){
  181847. /* Case 2. */
  181848. if( *zString==0 ) return 0;
  181849. SQLITE_ICU_SKIP_UTF8(zString);
  181850. }else if( uPattern==(uint32_t)uEsc && !prevEscape ){
  181851. /* Case 3. */
  181852. prevEscape = 1;
  181853. }else{
  181854. /* Case 4. */
  181855. uint32_t uString;
  181856. SQLITE_ICU_READ_UTF8(zString, uString);
  181857. uString = (uint32_t)u_foldCase((UChar32)uString, U_FOLD_CASE_DEFAULT);
  181858. uPattern = (uint32_t)u_foldCase((UChar32)uPattern, U_FOLD_CASE_DEFAULT);
  181859. if( uString!=uPattern ){
  181860. return 0;
  181861. }
  181862. prevEscape = 0;
  181863. }
  181864. }
  181865. return *zString==0;
  181866. }
  181867. /*
  181868. ** Implementation of the like() SQL function. This function implements
  181869. ** the build-in LIKE operator. The first argument to the function is the
  181870. ** pattern and the second argument is the string. So, the SQL statements:
  181871. **
  181872. ** A LIKE B
  181873. **
  181874. ** is implemented as like(B, A). If there is an escape character E,
  181875. **
  181876. ** A LIKE B ESCAPE E
  181877. **
  181878. ** is mapped to like(B, A, E).
  181879. */
  181880. static void icuLikeFunc(
  181881. sqlite3_context *context,
  181882. int argc,
  181883. sqlite3_value **argv
  181884. ){
  181885. const unsigned char *zA = sqlite3_value_text(argv[0]);
  181886. const unsigned char *zB = sqlite3_value_text(argv[1]);
  181887. UChar32 uEsc = 0;
  181888. /* Limit the length of the LIKE or GLOB pattern to avoid problems
  181889. ** of deep recursion and N*N behavior in patternCompare().
  181890. */
  181891. if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
  181892. sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
  181893. return;
  181894. }
  181895. if( argc==3 ){
  181896. /* The escape character string must consist of a single UTF-8 character.
  181897. ** Otherwise, return an error.
  181898. */
  181899. int nE= sqlite3_value_bytes(argv[2]);
  181900. const unsigned char *zE = sqlite3_value_text(argv[2]);
  181901. int i = 0;
  181902. if( zE==0 ) return;
  181903. U8_NEXT(zE, i, nE, uEsc);
  181904. if( i!=nE){
  181905. sqlite3_result_error(context,
  181906. "ESCAPE expression must be a single character", -1);
  181907. return;
  181908. }
  181909. }
  181910. if( zA && zB ){
  181911. sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));
  181912. }
  181913. }
  181914. /*
  181915. ** Function to delete compiled regexp objects. Registered as
  181916. ** a destructor function with sqlite3_set_auxdata().
  181917. */
  181918. static void icuRegexpDelete(void *p){
  181919. URegularExpression *pExpr = (URegularExpression *)p;
  181920. uregex_close(pExpr);
  181921. }
  181922. /*
  181923. ** Implementation of SQLite REGEXP operator. This scalar function takes
  181924. ** two arguments. The first is a regular expression pattern to compile
  181925. ** the second is a string to match against that pattern. If either
  181926. ** argument is an SQL NULL, then NULL Is returned. Otherwise, the result
  181927. ** is 1 if the string matches the pattern, or 0 otherwise.
  181928. **
  181929. ** SQLite maps the regexp() function to the regexp() operator such
  181930. ** that the following two are equivalent:
  181931. **
  181932. ** zString REGEXP zPattern
  181933. ** regexp(zPattern, zString)
  181934. **
  181935. ** Uses the following ICU regexp APIs:
  181936. **
  181937. ** uregex_open()
  181938. ** uregex_matches()
  181939. ** uregex_close()
  181940. */
  181941. static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
  181942. UErrorCode status = U_ZERO_ERROR;
  181943. URegularExpression *pExpr;
  181944. UBool res;
  181945. const UChar *zString = sqlite3_value_text16(apArg[1]);
  181946. (void)nArg; /* Unused parameter */
  181947. /* If the left hand side of the regexp operator is NULL,
  181948. ** then the result is also NULL.
  181949. */
  181950. if( !zString ){
  181951. return;
  181952. }
  181953. pExpr = sqlite3_get_auxdata(p, 0);
  181954. if( !pExpr ){
  181955. const UChar *zPattern = sqlite3_value_text16(apArg[0]);
  181956. if( !zPattern ){
  181957. return;
  181958. }
  181959. pExpr = uregex_open(zPattern, -1, 0, 0, &status);
  181960. if( U_SUCCESS(status) ){
  181961. sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
  181962. }else{
  181963. assert(!pExpr);
  181964. icuFunctionError(p, "uregex_open", status);
  181965. return;
  181966. }
  181967. }
  181968. /* Configure the text that the regular expression operates on. */
  181969. uregex_setText(pExpr, zString, -1, &status);
  181970. if( !U_SUCCESS(status) ){
  181971. icuFunctionError(p, "uregex_setText", status);
  181972. return;
  181973. }
  181974. /* Attempt the match */
  181975. res = uregex_matches(pExpr, 0, &status);
  181976. if( !U_SUCCESS(status) ){
  181977. icuFunctionError(p, "uregex_matches", status);
  181978. return;
  181979. }
  181980. /* Set the text that the regular expression operates on to a NULL
  181981. ** pointer. This is not really necessary, but it is tidier than
  181982. ** leaving the regular expression object configured with an invalid
  181983. ** pointer after this function returns.
  181984. */
  181985. uregex_setText(pExpr, 0, 0, &status);
  181986. /* Return 1 or 0. */
  181987. sqlite3_result_int(p, res ? 1 : 0);
  181988. }
  181989. /*
  181990. ** Implementations of scalar functions for case mapping - upper() and
  181991. ** lower(). Function upper() converts its input to upper-case (ABC).
  181992. ** Function lower() converts to lower-case (abc).
  181993. **
  181994. ** ICU provides two types of case mapping, "general" case mapping and
  181995. ** "language specific". Refer to ICU documentation for the differences
  181996. ** between the two.
  181997. **
  181998. ** To utilise "general" case mapping, the upper() or lower() scalar
  181999. ** functions are invoked with one argument:
  182000. **
  182001. ** upper('ABC') -> 'abc'
  182002. ** lower('abc') -> 'ABC'
  182003. **
  182004. ** To access ICU "language specific" case mapping, upper() or lower()
  182005. ** should be invoked with two arguments. The second argument is the name
  182006. ** of the locale to use. Passing an empty string ("") or SQL NULL value
  182007. ** as the second argument is the same as invoking the 1 argument version
  182008. ** of upper() or lower().
  182009. **
  182010. ** lower('I', 'en_us') -> 'i'
  182011. ** lower('I', 'tr_tr') -> '\u131' (small dotless i)
  182012. **
  182013. ** http://www.icu-project.org/userguide/posix.html#case_mappings
  182014. */
  182015. static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
  182016. const UChar *zInput; /* Pointer to input string */
  182017. UChar *zOutput = 0; /* Pointer to output buffer */
  182018. int nInput; /* Size of utf-16 input string in bytes */
  182019. int nOut; /* Size of output buffer in bytes */
  182020. int cnt;
  182021. int bToUpper; /* True for toupper(), false for tolower() */
  182022. UErrorCode status;
  182023. const char *zLocale = 0;
  182024. assert(nArg==1 || nArg==2);
  182025. bToUpper = (sqlite3_user_data(p)!=0);
  182026. if( nArg==2 ){
  182027. zLocale = (const char *)sqlite3_value_text(apArg[1]);
  182028. }
  182029. zInput = sqlite3_value_text16(apArg[0]);
  182030. if( !zInput ){
  182031. return;
  182032. }
  182033. nOut = nInput = sqlite3_value_bytes16(apArg[0]);
  182034. if( nOut==0 ){
  182035. sqlite3_result_text16(p, "", 0, SQLITE_STATIC);
  182036. return;
  182037. }
  182038. for(cnt=0; cnt<2; cnt++){
  182039. UChar *zNew = sqlite3_realloc(zOutput, nOut);
  182040. if( zNew==0 ){
  182041. sqlite3_free(zOutput);
  182042. sqlite3_result_error_nomem(p);
  182043. return;
  182044. }
  182045. zOutput = zNew;
  182046. status = U_ZERO_ERROR;
  182047. if( bToUpper ){
  182048. nOut = 2*u_strToUpper(zOutput,nOut/2,zInput,nInput/2,zLocale,&status);
  182049. }else{
  182050. nOut = 2*u_strToLower(zOutput,nOut/2,zInput,nInput/2,zLocale,&status);
  182051. }
  182052. if( U_SUCCESS(status) ){
  182053. sqlite3_result_text16(p, zOutput, nOut, xFree);
  182054. }else if( status==U_BUFFER_OVERFLOW_ERROR ){
  182055. assert( cnt==0 );
  182056. continue;
  182057. }else{
  182058. icuFunctionError(p, bToUpper ? "u_strToUpper" : "u_strToLower", status);
  182059. }
  182060. return;
  182061. }
  182062. assert( 0 ); /* Unreachable */
  182063. }
  182064. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU) */
  182065. /*
  182066. ** Collation sequence destructor function. The pCtx argument points to
  182067. ** a UCollator structure previously allocated using ucol_open().
  182068. */
  182069. static void icuCollationDel(void *pCtx){
  182070. UCollator *p = (UCollator *)pCtx;
  182071. ucol_close(p);
  182072. }
  182073. /*
  182074. ** Collation sequence comparison function. The pCtx argument points to
  182075. ** a UCollator structure previously allocated using ucol_open().
  182076. */
  182077. static int icuCollationColl(
  182078. void *pCtx,
  182079. int nLeft,
  182080. const void *zLeft,
  182081. int nRight,
  182082. const void *zRight
  182083. ){
  182084. UCollationResult res;
  182085. UCollator *p = (UCollator *)pCtx;
  182086. res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);
  182087. switch( res ){
  182088. case UCOL_LESS: return -1;
  182089. case UCOL_GREATER: return +1;
  182090. case UCOL_EQUAL: return 0;
  182091. }
  182092. assert(!"Unexpected return value from ucol_strcoll()");
  182093. return 0;
  182094. }
  182095. /*
  182096. ** Implementation of the scalar function icu_load_collation().
  182097. **
  182098. ** This scalar function is used to add ICU collation based collation
  182099. ** types to an SQLite database connection. It is intended to be called
  182100. ** as follows:
  182101. **
  182102. ** SELECT icu_load_collation(<locale>, <collation-name>);
  182103. **
  182104. ** Where <locale> is a string containing an ICU locale identifier (i.e.
  182105. ** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
  182106. ** collation sequence to create.
  182107. */
  182108. static void icuLoadCollation(
  182109. sqlite3_context *p,
  182110. int nArg,
  182111. sqlite3_value **apArg
  182112. ){
  182113. sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);
  182114. UErrorCode status = U_ZERO_ERROR;
  182115. const char *zLocale; /* Locale identifier - (eg. "jp_JP") */
  182116. const char *zName; /* SQL Collation sequence name (eg. "japanese") */
  182117. UCollator *pUCollator; /* ICU library collation object */
  182118. int rc; /* Return code from sqlite3_create_collation_x() */
  182119. assert(nArg==2);
  182120. (void)nArg; /* Unused parameter */
  182121. zLocale = (const char *)sqlite3_value_text(apArg[0]);
  182122. zName = (const char *)sqlite3_value_text(apArg[1]);
  182123. if( !zLocale || !zName ){
  182124. return;
  182125. }
  182126. pUCollator = ucol_open(zLocale, &status);
  182127. if( !U_SUCCESS(status) ){
  182128. icuFunctionError(p, "ucol_open", status);
  182129. return;
  182130. }
  182131. assert(p);
  182132. rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator,
  182133. icuCollationColl, icuCollationDel
  182134. );
  182135. if( rc!=SQLITE_OK ){
  182136. ucol_close(pUCollator);
  182137. sqlite3_result_error(p, "Error registering collation function", -1);
  182138. }
  182139. }
  182140. /*
  182141. ** Register the ICU extension functions with database db.
  182142. */
  182143. SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){
  182144. # define SQLITEICU_EXTRAFLAGS (SQLITE_DETERMINISTIC|SQLITE_INNOCUOUS)
  182145. static const struct IcuScalar {
  182146. const char *zName; /* Function name */
  182147. unsigned char nArg; /* Number of arguments */
  182148. unsigned int enc; /* Optimal text encoding */
  182149. unsigned char iContext; /* sqlite3_user_data() context */
  182150. void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
  182151. } scalars[] = {
  182152. {"icu_load_collation",2,SQLITE_UTF8|SQLITE_DIRECTONLY,1, icuLoadCollation},
  182153. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
  182154. {"regexp", 2, SQLITE_ANY|SQLITEICU_EXTRAFLAGS, 0, icuRegexpFunc},
  182155. {"lower", 1, SQLITE_UTF16|SQLITEICU_EXTRAFLAGS, 0, icuCaseFunc16},
  182156. {"lower", 2, SQLITE_UTF16|SQLITEICU_EXTRAFLAGS, 0, icuCaseFunc16},
  182157. {"upper", 1, SQLITE_UTF16|SQLITEICU_EXTRAFLAGS, 1, icuCaseFunc16},
  182158. {"upper", 2, SQLITE_UTF16|SQLITEICU_EXTRAFLAGS, 1, icuCaseFunc16},
  182159. {"lower", 1, SQLITE_UTF8|SQLITEICU_EXTRAFLAGS, 0, icuCaseFunc16},
  182160. {"lower", 2, SQLITE_UTF8|SQLITEICU_EXTRAFLAGS, 0, icuCaseFunc16},
  182161. {"upper", 1, SQLITE_UTF8|SQLITEICU_EXTRAFLAGS, 1, icuCaseFunc16},
  182162. {"upper", 2, SQLITE_UTF8|SQLITEICU_EXTRAFLAGS, 1, icuCaseFunc16},
  182163. {"like", 2, SQLITE_UTF8|SQLITEICU_EXTRAFLAGS, 0, icuLikeFunc},
  182164. {"like", 3, SQLITE_UTF8|SQLITEICU_EXTRAFLAGS, 0, icuLikeFunc},
  182165. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU) */
  182166. };
  182167. int rc = SQLITE_OK;
  182168. int i;
  182169. for(i=0; rc==SQLITE_OK && i<(int)(sizeof(scalars)/sizeof(scalars[0])); i++){
  182170. const struct IcuScalar *p = &scalars[i];
  182171. rc = sqlite3_create_function(
  182172. db, p->zName, p->nArg, p->enc,
  182173. p->iContext ? (void*)db : (void*)0,
  182174. p->xFunc, 0, 0
  182175. );
  182176. }
  182177. return rc;
  182178. }
  182179. #if !SQLITE_CORE
  182180. #ifdef _WIN32
  182181. __declspec(dllexport)
  182182. #endif
  182183. SQLITE_API int sqlite3_icu_init(
  182184. sqlite3 *db,
  182185. char **pzErrMsg,
  182186. const sqlite3_api_routines *pApi
  182187. ){
  182188. SQLITE_EXTENSION_INIT2(pApi)
  182189. return sqlite3IcuInit(db);
  182190. }
  182191. #endif
  182192. #endif
  182193. /************** End of icu.c *************************************************/
  182194. /************** Begin file fts3_icu.c ****************************************/
  182195. /*
  182196. ** 2007 June 22
  182197. **
  182198. ** The author disclaims copyright to this source code. In place of
  182199. ** a legal notice, here is a blessing:
  182200. **
  182201. ** May you do good and not evil.
  182202. ** May you find forgiveness for yourself and forgive others.
  182203. ** May you share freely, never taking more than you give.
  182204. **
  182205. *************************************************************************
  182206. ** This file implements a tokenizer for fts3 based on the ICU library.
  182207. */
  182208. /* #include "fts3Int.h" */
  182209. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  182210. #ifdef SQLITE_ENABLE_ICU
  182211. /* #include <assert.h> */
  182212. /* #include <string.h> */
  182213. /* #include "fts3_tokenizer.h" */
  182214. #include <unicode/ubrk.h>
  182215. /* #include <unicode/ucol.h> */
  182216. /* #include <unicode/ustring.h> */
  182217. #include <unicode/utf16.h>
  182218. typedef struct IcuTokenizer IcuTokenizer;
  182219. typedef struct IcuCursor IcuCursor;
  182220. struct IcuTokenizer {
  182221. sqlite3_tokenizer base;
  182222. char *zLocale;
  182223. };
  182224. struct IcuCursor {
  182225. sqlite3_tokenizer_cursor base;
  182226. UBreakIterator *pIter; /* ICU break-iterator object */
  182227. int nChar; /* Number of UChar elements in pInput */
  182228. UChar *aChar; /* Copy of input using utf-16 encoding */
  182229. int *aOffset; /* Offsets of each character in utf-8 input */
  182230. int nBuffer;
  182231. char *zBuffer;
  182232. int iToken;
  182233. };
  182234. /*
  182235. ** Create a new tokenizer instance.
  182236. */
  182237. static int icuCreate(
  182238. int argc, /* Number of entries in argv[] */
  182239. const char * const *argv, /* Tokenizer creation arguments */
  182240. sqlite3_tokenizer **ppTokenizer /* OUT: Created tokenizer */
  182241. ){
  182242. IcuTokenizer *p;
  182243. int n = 0;
  182244. if( argc>0 ){
  182245. n = strlen(argv[0])+1;
  182246. }
  182247. p = (IcuTokenizer *)sqlite3_malloc64(sizeof(IcuTokenizer)+n);
  182248. if( !p ){
  182249. return SQLITE_NOMEM;
  182250. }
  182251. memset(p, 0, sizeof(IcuTokenizer));
  182252. if( n ){
  182253. p->zLocale = (char *)&p[1];
  182254. memcpy(p->zLocale, argv[0], n);
  182255. }
  182256. *ppTokenizer = (sqlite3_tokenizer *)p;
  182257. return SQLITE_OK;
  182258. }
  182259. /*
  182260. ** Destroy a tokenizer
  182261. */
  182262. static int icuDestroy(sqlite3_tokenizer *pTokenizer){
  182263. IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
  182264. sqlite3_free(p);
  182265. return SQLITE_OK;
  182266. }
  182267. /*
  182268. ** Prepare to begin tokenizing a particular string. The input
  182269. ** string to be tokenized is pInput[0..nBytes-1]. A cursor
  182270. ** used to incrementally tokenize this string is returned in
  182271. ** *ppCursor.
  182272. */
  182273. static int icuOpen(
  182274. sqlite3_tokenizer *pTokenizer, /* The tokenizer */
  182275. const char *zInput, /* Input string */
  182276. int nInput, /* Length of zInput in bytes */
  182277. sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
  182278. ){
  182279. IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
  182280. IcuCursor *pCsr;
  182281. const int32_t opt = U_FOLD_CASE_DEFAULT;
  182282. UErrorCode status = U_ZERO_ERROR;
  182283. int nChar;
  182284. UChar32 c;
  182285. int iInput = 0;
  182286. int iOut = 0;
  182287. *ppCursor = 0;
  182288. if( zInput==0 ){
  182289. nInput = 0;
  182290. zInput = "";
  182291. }else if( nInput<0 ){
  182292. nInput = strlen(zInput);
  182293. }
  182294. nChar = nInput+1;
  182295. pCsr = (IcuCursor *)sqlite3_malloc64(
  182296. sizeof(IcuCursor) + /* IcuCursor */
  182297. ((nChar+3)&~3) * sizeof(UChar) + /* IcuCursor.aChar[] */
  182298. (nChar+1) * sizeof(int) /* IcuCursor.aOffset[] */
  182299. );
  182300. if( !pCsr ){
  182301. return SQLITE_NOMEM;
  182302. }
  182303. memset(pCsr, 0, sizeof(IcuCursor));
  182304. pCsr->aChar = (UChar *)&pCsr[1];
  182305. pCsr->aOffset = (int *)&pCsr->aChar[(nChar+3)&~3];
  182306. pCsr->aOffset[iOut] = iInput;
  182307. U8_NEXT(zInput, iInput, nInput, c);
  182308. while( c>0 ){
  182309. int isError = 0;
  182310. c = u_foldCase(c, opt);
  182311. U16_APPEND(pCsr->aChar, iOut, nChar, c, isError);
  182312. if( isError ){
  182313. sqlite3_free(pCsr);
  182314. return SQLITE_ERROR;
  182315. }
  182316. pCsr->aOffset[iOut] = iInput;
  182317. if( iInput<nInput ){
  182318. U8_NEXT(zInput, iInput, nInput, c);
  182319. }else{
  182320. c = 0;
  182321. }
  182322. }
  182323. pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status);
  182324. if( !U_SUCCESS(status) ){
  182325. sqlite3_free(pCsr);
  182326. return SQLITE_ERROR;
  182327. }
  182328. pCsr->nChar = iOut;
  182329. ubrk_first(pCsr->pIter);
  182330. *ppCursor = (sqlite3_tokenizer_cursor *)pCsr;
  182331. return SQLITE_OK;
  182332. }
  182333. /*
  182334. ** Close a tokenization cursor previously opened by a call to icuOpen().
  182335. */
  182336. static int icuClose(sqlite3_tokenizer_cursor *pCursor){
  182337. IcuCursor *pCsr = (IcuCursor *)pCursor;
  182338. ubrk_close(pCsr->pIter);
  182339. sqlite3_free(pCsr->zBuffer);
  182340. sqlite3_free(pCsr);
  182341. return SQLITE_OK;
  182342. }
  182343. /*
  182344. ** Extract the next token from a tokenization cursor.
  182345. */
  182346. static int icuNext(
  182347. sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by simpleOpen */
  182348. const char **ppToken, /* OUT: *ppToken is the token text */
  182349. int *pnBytes, /* OUT: Number of bytes in token */
  182350. int *piStartOffset, /* OUT: Starting offset of token */
  182351. int *piEndOffset, /* OUT: Ending offset of token */
  182352. int *piPosition /* OUT: Position integer of token */
  182353. ){
  182354. IcuCursor *pCsr = (IcuCursor *)pCursor;
  182355. int iStart = 0;
  182356. int iEnd = 0;
  182357. int nByte = 0;
  182358. while( iStart==iEnd ){
  182359. UChar32 c;
  182360. iStart = ubrk_current(pCsr->pIter);
  182361. iEnd = ubrk_next(pCsr->pIter);
  182362. if( iEnd==UBRK_DONE ){
  182363. return SQLITE_DONE;
  182364. }
  182365. while( iStart<iEnd ){
  182366. int iWhite = iStart;
  182367. U16_NEXT(pCsr->aChar, iWhite, pCsr->nChar, c);
  182368. if( u_isspace(c) ){
  182369. iStart = iWhite;
  182370. }else{
  182371. break;
  182372. }
  182373. }
  182374. assert(iStart<=iEnd);
  182375. }
  182376. do {
  182377. UErrorCode status = U_ZERO_ERROR;
  182378. if( nByte ){
  182379. char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte);
  182380. if( !zNew ){
  182381. return SQLITE_NOMEM;
  182382. }
  182383. pCsr->zBuffer = zNew;
  182384. pCsr->nBuffer = nByte;
  182385. }
  182386. u_strToUTF8(
  182387. pCsr->zBuffer, pCsr->nBuffer, &nByte, /* Output vars */
  182388. &pCsr->aChar[iStart], iEnd-iStart, /* Input vars */
  182389. &status /* Output success/failure */
  182390. );
  182391. } while( nByte>pCsr->nBuffer );
  182392. *ppToken = pCsr->zBuffer;
  182393. *pnBytes = nByte;
  182394. *piStartOffset = pCsr->aOffset[iStart];
  182395. *piEndOffset = pCsr->aOffset[iEnd];
  182396. *piPosition = pCsr->iToken++;
  182397. return SQLITE_OK;
  182398. }
  182399. /*
  182400. ** The set of routines that implement the simple tokenizer
  182401. */
  182402. static const sqlite3_tokenizer_module icuTokenizerModule = {
  182403. 0, /* iVersion */
  182404. icuCreate, /* xCreate */
  182405. icuDestroy, /* xCreate */
  182406. icuOpen, /* xOpen */
  182407. icuClose, /* xClose */
  182408. icuNext, /* xNext */
  182409. 0, /* xLanguageid */
  182410. };
  182411. /*
  182412. ** Set *ppModule to point at the implementation of the ICU tokenizer.
  182413. */
  182414. SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
  182415. sqlite3_tokenizer_module const**ppModule
  182416. ){
  182417. *ppModule = &icuTokenizerModule;
  182418. }
  182419. #endif /* defined(SQLITE_ENABLE_ICU) */
  182420. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  182421. /************** End of fts3_icu.c ********************************************/
  182422. /************** Begin file sqlite3rbu.c **************************************/
  182423. /*
  182424. ** 2014 August 30
  182425. **
  182426. ** The author disclaims copyright to this source code. In place of
  182427. ** a legal notice, here is a blessing:
  182428. **
  182429. ** May you do good and not evil.
  182430. ** May you find forgiveness for yourself and forgive others.
  182431. ** May you share freely, never taking more than you give.
  182432. **
  182433. *************************************************************************
  182434. **
  182435. **
  182436. ** OVERVIEW
  182437. **
  182438. ** The RBU extension requires that the RBU update be packaged as an
  182439. ** SQLite database. The tables it expects to find are described in
  182440. ** sqlite3rbu.h. Essentially, for each table xyz in the target database
  182441. ** that the user wishes to write to, a corresponding data_xyz table is
  182442. ** created in the RBU database and populated with one row for each row to
  182443. ** update, insert or delete from the target table.
  182444. **
  182445. ** The update proceeds in three stages:
  182446. **
  182447. ** 1) The database is updated. The modified database pages are written
  182448. ** to a *-oal file. A *-oal file is just like a *-wal file, except
  182449. ** that it is named "<database>-oal" instead of "<database>-wal".
  182450. ** Because regular SQLite clients do not look for file named
  182451. ** "<database>-oal", they go on using the original database in
  182452. ** rollback mode while the *-oal file is being generated.
  182453. **
  182454. ** During this stage RBU does not update the database by writing
  182455. ** directly to the target tables. Instead it creates "imposter"
  182456. ** tables using the SQLITE_TESTCTRL_IMPOSTER interface that it uses
  182457. ** to update each b-tree individually. All updates required by each
  182458. ** b-tree are completed before moving on to the next, and all
  182459. ** updates are done in sorted key order.
  182460. **
  182461. ** 2) The "<database>-oal" file is moved to the equivalent "<database>-wal"
  182462. ** location using a call to rename(2). Before doing this the RBU
  182463. ** module takes an EXCLUSIVE lock on the database file, ensuring
  182464. ** that there are no other active readers.
  182465. **
  182466. ** Once the EXCLUSIVE lock is released, any other database readers
  182467. ** detect the new *-wal file and read the database in wal mode. At
  182468. ** this point they see the new version of the database - including
  182469. ** the updates made as part of the RBU update.
  182470. **
  182471. ** 3) The new *-wal file is checkpointed. This proceeds in the same way
  182472. ** as a regular database checkpoint, except that a single frame is
  182473. ** checkpointed each time sqlite3rbu_step() is called. If the RBU
  182474. ** handle is closed before the entire *-wal file is checkpointed,
  182475. ** the checkpoint progress is saved in the RBU database and the
  182476. ** checkpoint can be resumed by another RBU client at some point in
  182477. ** the future.
  182478. **
  182479. ** POTENTIAL PROBLEMS
  182480. **
  182481. ** The rename() call might not be portable. And RBU is not currently
  182482. ** syncing the directory after renaming the file.
  182483. **
  182484. ** When state is saved, any commit to the *-oal file and the commit to
  182485. ** the RBU update database are not atomic. So if the power fails at the
  182486. ** wrong moment they might get out of sync. As the main database will be
  182487. ** committed before the RBU update database this will likely either just
  182488. ** pass unnoticed, or result in SQLITE_CONSTRAINT errors (due to UNIQUE
  182489. ** constraint violations).
  182490. **
  182491. ** If some client does modify the target database mid RBU update, or some
  182492. ** other error occurs, the RBU extension will keep throwing errors. It's
  182493. ** not really clear how to get out of this state. The system could just
  182494. ** by delete the RBU update database and *-oal file and have the device
  182495. ** download the update again and start over.
  182496. **
  182497. ** At present, for an UPDATE, both the new.* and old.* records are
  182498. ** collected in the rbu_xyz table. And for both UPDATEs and DELETEs all
  182499. ** fields are collected. This means we're probably writing a lot more
  182500. ** data to disk when saving the state of an ongoing update to the RBU
  182501. ** update database than is strictly necessary.
  182502. **
  182503. */
  182504. /* #include <assert.h> */
  182505. /* #include <string.h> */
  182506. /* #include <stdio.h> */
  182507. /* #include "sqlite3.h" */
  182508. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RBU)
  182509. /************** Include sqlite3rbu.h in the middle of sqlite3rbu.c ***********/
  182510. /************** Begin file sqlite3rbu.h **************************************/
  182511. /*
  182512. ** 2014 August 30
  182513. **
  182514. ** The author disclaims copyright to this source code. In place of
  182515. ** a legal notice, here is a blessing:
  182516. **
  182517. ** May you do good and not evil.
  182518. ** May you find forgiveness for yourself and forgive others.
  182519. ** May you share freely, never taking more than you give.
  182520. **
  182521. *************************************************************************
  182522. **
  182523. ** This file contains the public interface for the RBU extension.
  182524. */
  182525. /*
  182526. ** SUMMARY
  182527. **
  182528. ** Writing a transaction containing a large number of operations on
  182529. ** b-tree indexes that are collectively larger than the available cache
  182530. ** memory can be very inefficient.
  182531. **
  182532. ** The problem is that in order to update a b-tree, the leaf page (at least)
  182533. ** containing the entry being inserted or deleted must be modified. If the
  182534. ** working set of leaves is larger than the available cache memory, then a
  182535. ** single leaf that is modified more than once as part of the transaction
  182536. ** may be loaded from or written to the persistent media multiple times.
  182537. ** Additionally, because the index updates are likely to be applied in
  182538. ** random order, access to pages within the database is also likely to be in
  182539. ** random order, which is itself quite inefficient.
  182540. **
  182541. ** One way to improve the situation is to sort the operations on each index
  182542. ** by index key before applying them to the b-tree. This leads to an IO
  182543. ** pattern that resembles a single linear scan through the index b-tree,
  182544. ** and all but guarantees each modified leaf page is loaded and stored
  182545. ** exactly once. SQLite uses this trick to improve the performance of
  182546. ** CREATE INDEX commands. This extension allows it to be used to improve
  182547. ** the performance of large transactions on existing databases.
  182548. **
  182549. ** Additionally, this extension allows the work involved in writing the
  182550. ** large transaction to be broken down into sub-transactions performed
  182551. ** sequentially by separate processes. This is useful if the system cannot
  182552. ** guarantee that a single update process will run for long enough to apply
  182553. ** the entire update, for example because the update is being applied on a
  182554. ** mobile device that is frequently rebooted. Even after the writer process
  182555. ** has committed one or more sub-transactions, other database clients continue
  182556. ** to read from the original database snapshot. In other words, partially
  182557. ** applied transactions are not visible to other clients.
  182558. **
  182559. ** "RBU" stands for "Resumable Bulk Update". As in a large database update
  182560. ** transmitted via a wireless network to a mobile device. A transaction
  182561. ** applied using this extension is hence refered to as an "RBU update".
  182562. **
  182563. **
  182564. ** LIMITATIONS
  182565. **
  182566. ** An "RBU update" transaction is subject to the following limitations:
  182567. **
  182568. ** * The transaction must consist of INSERT, UPDATE and DELETE operations
  182569. ** only.
  182570. **
  182571. ** * INSERT statements may not use any default values.
  182572. **
  182573. ** * UPDATE and DELETE statements must identify their target rows by
  182574. ** non-NULL PRIMARY KEY values. Rows with NULL values stored in PRIMARY
  182575. ** KEY fields may not be updated or deleted. If the table being written
  182576. ** has no PRIMARY KEY, affected rows must be identified by rowid.
  182577. **
  182578. ** * UPDATE statements may not modify PRIMARY KEY columns.
  182579. **
  182580. ** * No triggers will be fired.
  182581. **
  182582. ** * No foreign key violations are detected or reported.
  182583. **
  182584. ** * CHECK constraints are not enforced.
  182585. **
  182586. ** * No constraint handling mode except for "OR ROLLBACK" is supported.
  182587. **
  182588. **
  182589. ** PREPARATION
  182590. **
  182591. ** An "RBU update" is stored as a separate SQLite database. A database
  182592. ** containing an RBU update is an "RBU database". For each table in the
  182593. ** target database to be updated, the RBU database should contain a table
  182594. ** named "data_<target name>" containing the same set of columns as the
  182595. ** target table, and one more - "rbu_control". The data_% table should
  182596. ** have no PRIMARY KEY or UNIQUE constraints, but each column should have
  182597. ** the same type as the corresponding column in the target database.
  182598. ** The "rbu_control" column should have no type at all. For example, if
  182599. ** the target database contains:
  182600. **
  182601. ** CREATE TABLE t1(a INTEGER PRIMARY KEY, b TEXT, c UNIQUE);
  182602. **
  182603. ** Then the RBU database should contain:
  182604. **
  182605. ** CREATE TABLE data_t1(a INTEGER, b TEXT, c, rbu_control);
  182606. **
  182607. ** The order of the columns in the data_% table does not matter.
  182608. **
  182609. ** Instead of a regular table, the RBU database may also contain virtual
  182610. ** tables or view named using the data_<target> naming scheme.
  182611. **
  182612. ** Instead of the plain data_<target> naming scheme, RBU database tables
  182613. ** may also be named data<integer>_<target>, where <integer> is any sequence
  182614. ** of zero or more numeric characters (0-9). This can be significant because
  182615. ** tables within the RBU database are always processed in order sorted by
  182616. ** name. By judicious selection of the <integer> portion of the names
  182617. ** of the RBU tables the user can therefore control the order in which they
  182618. ** are processed. This can be useful, for example, to ensure that "external
  182619. ** content" FTS4 tables are updated before their underlying content tables.
  182620. **
  182621. ** If the target database table is a virtual table or a table that has no
  182622. ** PRIMARY KEY declaration, the data_% table must also contain a column
  182623. ** named "rbu_rowid". This column is mapped to the tables implicit primary
  182624. ** key column - "rowid". Virtual tables for which the "rowid" column does
  182625. ** not function like a primary key value cannot be updated using RBU. For
  182626. ** example, if the target db contains either of the following:
  182627. **
  182628. ** CREATE VIRTUAL TABLE x1 USING fts3(a, b);
  182629. ** CREATE TABLE x1(a, b)
  182630. **
  182631. ** then the RBU database should contain:
  182632. **
  182633. ** CREATE TABLE data_x1(a, b, rbu_rowid, rbu_control);
  182634. **
  182635. ** All non-hidden columns (i.e. all columns matched by "SELECT *") of the
  182636. ** target table must be present in the input table. For virtual tables,
  182637. ** hidden columns are optional - they are updated by RBU if present in
  182638. ** the input table, or not otherwise. For example, to write to an fts4
  182639. ** table with a hidden languageid column such as:
  182640. **
  182641. ** CREATE VIRTUAL TABLE ft1 USING fts4(a, b, languageid='langid');
  182642. **
  182643. ** Either of the following input table schemas may be used:
  182644. **
  182645. ** CREATE TABLE data_ft1(a, b, langid, rbu_rowid, rbu_control);
  182646. ** CREATE TABLE data_ft1(a, b, rbu_rowid, rbu_control);
  182647. **
  182648. ** For each row to INSERT into the target database as part of the RBU
  182649. ** update, the corresponding data_% table should contain a single record
  182650. ** with the "rbu_control" column set to contain integer value 0. The
  182651. ** other columns should be set to the values that make up the new record
  182652. ** to insert.
  182653. **
  182654. ** If the target database table has an INTEGER PRIMARY KEY, it is not
  182655. ** possible to insert a NULL value into the IPK column. Attempting to
  182656. ** do so results in an SQLITE_MISMATCH error.
  182657. **
  182658. ** For each row to DELETE from the target database as part of the RBU
  182659. ** update, the corresponding data_% table should contain a single record
  182660. ** with the "rbu_control" column set to contain integer value 1. The
  182661. ** real primary key values of the row to delete should be stored in the
  182662. ** corresponding columns of the data_% table. The values stored in the
  182663. ** other columns are not used.
  182664. **
  182665. ** For each row to UPDATE from the target database as part of the RBU
  182666. ** update, the corresponding data_% table should contain a single record
  182667. ** with the "rbu_control" column set to contain a value of type text.
  182668. ** The real primary key values identifying the row to update should be
  182669. ** stored in the corresponding columns of the data_% table row, as should
  182670. ** the new values of all columns being update. The text value in the
  182671. ** "rbu_control" column must contain the same number of characters as
  182672. ** there are columns in the target database table, and must consist entirely
  182673. ** of 'x' and '.' characters (or in some special cases 'd' - see below). For
  182674. ** each column that is being updated, the corresponding character is set to
  182675. ** 'x'. For those that remain as they are, the corresponding character of the
  182676. ** rbu_control value should be set to '.'. For example, given the tables
  182677. ** above, the update statement:
  182678. **
  182679. ** UPDATE t1 SET c = 'usa' WHERE a = 4;
  182680. **
  182681. ** is represented by the data_t1 row created by:
  182682. **
  182683. ** INSERT INTO data_t1(a, b, c, rbu_control) VALUES(4, NULL, 'usa', '..x');
  182684. **
  182685. ** Instead of an 'x' character, characters of the rbu_control value specified
  182686. ** for UPDATEs may also be set to 'd'. In this case, instead of updating the
  182687. ** target table with the value stored in the corresponding data_% column, the
  182688. ** user-defined SQL function "rbu_delta()" is invoked and the result stored in
  182689. ** the target table column. rbu_delta() is invoked with two arguments - the
  182690. ** original value currently stored in the target table column and the
  182691. ** value specified in the data_xxx table.
  182692. **
  182693. ** For example, this row:
  182694. **
  182695. ** INSERT INTO data_t1(a, b, c, rbu_control) VALUES(4, NULL, 'usa', '..d');
  182696. **
  182697. ** is similar to an UPDATE statement such as:
  182698. **
  182699. ** UPDATE t1 SET c = rbu_delta(c, 'usa') WHERE a = 4;
  182700. **
  182701. ** Finally, if an 'f' character appears in place of a 'd' or 's' in an
  182702. ** ota_control string, the contents of the data_xxx table column is assumed
  182703. ** to be a "fossil delta" - a patch to be applied to a blob value in the
  182704. ** format used by the fossil source-code management system. In this case
  182705. ** the existing value within the target database table must be of type BLOB.
  182706. ** It is replaced by the result of applying the specified fossil delta to
  182707. ** itself.
  182708. **
  182709. ** If the target database table is a virtual table or a table with no PRIMARY
  182710. ** KEY, the rbu_control value should not include a character corresponding
  182711. ** to the rbu_rowid value. For example, this:
  182712. **
  182713. ** INSERT INTO data_ft1(a, b, rbu_rowid, rbu_control)
  182714. ** VALUES(NULL, 'usa', 12, '.x');
  182715. **
  182716. ** causes a result similar to:
  182717. **
  182718. ** UPDATE ft1 SET b = 'usa' WHERE rowid = 12;
  182719. **
  182720. ** The data_xxx tables themselves should have no PRIMARY KEY declarations.
  182721. ** However, RBU is more efficient if reading the rows in from each data_xxx
  182722. ** table in "rowid" order is roughly the same as reading them sorted by
  182723. ** the PRIMARY KEY of the corresponding target database table. In other
  182724. ** words, rows should be sorted using the destination table PRIMARY KEY
  182725. ** fields before they are inserted into the data_xxx tables.
  182726. **
  182727. ** USAGE
  182728. **
  182729. ** The API declared below allows an application to apply an RBU update
  182730. ** stored on disk to an existing target database. Essentially, the
  182731. ** application:
  182732. **
  182733. ** 1) Opens an RBU handle using the sqlite3rbu_open() function.
  182734. **
  182735. ** 2) Registers any required virtual table modules with the database
  182736. ** handle returned by sqlite3rbu_db(). Also, if required, register
  182737. ** the rbu_delta() implementation.
  182738. **
  182739. ** 3) Calls the sqlite3rbu_step() function one or more times on
  182740. ** the new handle. Each call to sqlite3rbu_step() performs a single
  182741. ** b-tree operation, so thousands of calls may be required to apply
  182742. ** a complete update.
  182743. **
  182744. ** 4) Calls sqlite3rbu_close() to close the RBU update handle. If
  182745. ** sqlite3rbu_step() has been called enough times to completely
  182746. ** apply the update to the target database, then the RBU database
  182747. ** is marked as fully applied. Otherwise, the state of the RBU
  182748. ** update application is saved in the RBU database for later
  182749. ** resumption.
  182750. **
  182751. ** See comments below for more detail on APIs.
  182752. **
  182753. ** If an update is only partially applied to the target database by the
  182754. ** time sqlite3rbu_close() is called, various state information is saved
  182755. ** within the RBU database. This allows subsequent processes to automatically
  182756. ** resume the RBU update from where it left off.
  182757. **
  182758. ** To remove all RBU extension state information, returning an RBU database
  182759. ** to its original contents, it is sufficient to drop all tables that begin
  182760. ** with the prefix "rbu_"
  182761. **
  182762. ** DATABASE LOCKING
  182763. **
  182764. ** An RBU update may not be applied to a database in WAL mode. Attempting
  182765. ** to do so is an error (SQLITE_ERROR).
  182766. **
  182767. ** While an RBU handle is open, a SHARED lock may be held on the target
  182768. ** database file. This means it is possible for other clients to read the
  182769. ** database, but not to write it.
  182770. **
  182771. ** If an RBU update is started and then suspended before it is completed,
  182772. ** then an external client writes to the database, then attempting to resume
  182773. ** the suspended RBU update is also an error (SQLITE_BUSY).
  182774. */
  182775. #ifndef _SQLITE3RBU_H
  182776. #define _SQLITE3RBU_H
  182777. /* #include "sqlite3.h" ** Required for error code definitions ** */
  182778. #if 0
  182779. extern "C" {
  182780. #endif
  182781. typedef struct sqlite3rbu sqlite3rbu;
  182782. /*
  182783. ** Open an RBU handle.
  182784. **
  182785. ** Argument zTarget is the path to the target database. Argument zRbu is
  182786. ** the path to the RBU database. Each call to this function must be matched
  182787. ** by a call to sqlite3rbu_close(). When opening the databases, RBU passes
  182788. ** the SQLITE_CONFIG_URI flag to sqlite3_open_v2(). So if either zTarget
  182789. ** or zRbu begin with "file:", it will be interpreted as an SQLite
  182790. ** database URI, not a regular file name.
  182791. **
  182792. ** If the zState argument is passed a NULL value, the RBU extension stores
  182793. ** the current state of the update (how many rows have been updated, which
  182794. ** indexes are yet to be updated etc.) within the RBU database itself. This
  182795. ** can be convenient, as it means that the RBU application does not need to
  182796. ** organize removing a separate state file after the update is concluded.
  182797. ** Or, if zState is non-NULL, it must be a path to a database file in which
  182798. ** the RBU extension can store the state of the update.
  182799. **
  182800. ** When resuming an RBU update, the zState argument must be passed the same
  182801. ** value as when the RBU update was started.
  182802. **
  182803. ** Once the RBU update is finished, the RBU extension does not
  182804. ** automatically remove any zState database file, even if it created it.
  182805. **
  182806. ** By default, RBU uses the default VFS to access the files on disk. To
  182807. ** use a VFS other than the default, an SQLite "file:" URI containing a
  182808. ** "vfs=..." option may be passed as the zTarget option.
  182809. **
  182810. ** IMPORTANT NOTE FOR ZIPVFS USERS: The RBU extension works with all of
  182811. ** SQLite's built-in VFSs, including the multiplexor VFS. However it does
  182812. ** not work out of the box with zipvfs. Refer to the comment describing
  182813. ** the zipvfs_create_vfs() API below for details on using RBU with zipvfs.
  182814. */
  182815. SQLITE_API sqlite3rbu *sqlite3rbu_open(
  182816. const char *zTarget,
  182817. const char *zRbu,
  182818. const char *zState
  182819. );
  182820. /*
  182821. ** Open an RBU handle to perform an RBU vacuum on database file zTarget.
  182822. ** An RBU vacuum is similar to SQLite's built-in VACUUM command, except
  182823. ** that it can be suspended and resumed like an RBU update.
  182824. **
  182825. ** The second argument to this function identifies a database in which
  182826. ** to store the state of the RBU vacuum operation if it is suspended. The
  182827. ** first time sqlite3rbu_vacuum() is called, to start an RBU vacuum
  182828. ** operation, the state database should either not exist or be empty
  182829. ** (contain no tables). If an RBU vacuum is suspended by calling
  182830. ** sqlite3rbu_close() on the RBU handle before sqlite3rbu_step() has
  182831. ** returned SQLITE_DONE, the vacuum state is stored in the state database.
  182832. ** The vacuum can be resumed by calling this function to open a new RBU
  182833. ** handle specifying the same target and state databases.
  182834. **
  182835. ** If the second argument passed to this function is NULL, then the
  182836. ** name of the state database is "<database>-vacuum", where <database>
  182837. ** is the name of the target database file. In this case, on UNIX, if the
  182838. ** state database is not already present in the file-system, it is created
  182839. ** with the same permissions as the target db is made.
  182840. **
  182841. ** With an RBU vacuum, it is an SQLITE_MISUSE error if the name of the
  182842. ** state database ends with "-vactmp". This name is reserved for internal
  182843. ** use.
  182844. **
  182845. ** This function does not delete the state database after an RBU vacuum
  182846. ** is completed, even if it created it. However, if the call to
  182847. ** sqlite3rbu_close() returns any value other than SQLITE_OK, the contents
  182848. ** of the state tables within the state database are zeroed. This way,
  182849. ** the next call to sqlite3rbu_vacuum() opens a handle that starts a
  182850. ** new RBU vacuum operation.
  182851. **
  182852. ** As with sqlite3rbu_open(), Zipvfs users should rever to the comment
  182853. ** describing the sqlite3rbu_create_vfs() API function below for
  182854. ** a description of the complications associated with using RBU with
  182855. ** zipvfs databases.
  182856. */
  182857. SQLITE_API sqlite3rbu *sqlite3rbu_vacuum(
  182858. const char *zTarget,
  182859. const char *zState
  182860. );
  182861. /*
  182862. ** Configure a limit for the amount of temp space that may be used by
  182863. ** the RBU handle passed as the first argument. The new limit is specified
  182864. ** in bytes by the second parameter. If it is positive, the limit is updated.
  182865. ** If the second parameter to this function is passed zero, then the limit
  182866. ** is removed entirely. If the second parameter is negative, the limit is
  182867. ** not modified (this is useful for querying the current limit).
  182868. **
  182869. ** In all cases the returned value is the current limit in bytes (zero
  182870. ** indicates unlimited).
  182871. **
  182872. ** If the temp space limit is exceeded during operation, an SQLITE_FULL
  182873. ** error is returned.
  182874. */
  182875. SQLITE_API sqlite3_int64 sqlite3rbu_temp_size_limit(sqlite3rbu*, sqlite3_int64);
  182876. /*
  182877. ** Return the current amount of temp file space, in bytes, currently used by
  182878. ** the RBU handle passed as the only argument.
  182879. */
  182880. SQLITE_API sqlite3_int64 sqlite3rbu_temp_size(sqlite3rbu*);
  182881. /*
  182882. ** Internally, each RBU connection uses a separate SQLite database
  182883. ** connection to access the target and rbu update databases. This
  182884. ** API allows the application direct access to these database handles.
  182885. **
  182886. ** The first argument passed to this function must be a valid, open, RBU
  182887. ** handle. The second argument should be passed zero to access the target
  182888. ** database handle, or non-zero to access the rbu update database handle.
  182889. ** Accessing the underlying database handles may be useful in the
  182890. ** following scenarios:
  182891. **
  182892. ** * If any target tables are virtual tables, it may be necessary to
  182893. ** call sqlite3_create_module() on the target database handle to
  182894. ** register the required virtual table implementations.
  182895. **
  182896. ** * If the data_xxx tables in the RBU source database are virtual
  182897. ** tables, the application may need to call sqlite3_create_module() on
  182898. ** the rbu update db handle to any required virtual table
  182899. ** implementations.
  182900. **
  182901. ** * If the application uses the "rbu_delta()" feature described above,
  182902. ** it must use sqlite3_create_function() or similar to register the
  182903. ** rbu_delta() implementation with the target database handle.
  182904. **
  182905. ** If an error has occurred, either while opening or stepping the RBU object,
  182906. ** this function may return NULL. The error code and message may be collected
  182907. ** when sqlite3rbu_close() is called.
  182908. **
  182909. ** Database handles returned by this function remain valid until the next
  182910. ** call to any sqlite3rbu_xxx() function other than sqlite3rbu_db().
  182911. */
  182912. SQLITE_API sqlite3 *sqlite3rbu_db(sqlite3rbu*, int bRbu);
  182913. /*
  182914. ** Do some work towards applying the RBU update to the target db.
  182915. **
  182916. ** Return SQLITE_DONE if the update has been completely applied, or
  182917. ** SQLITE_OK if no error occurs but there remains work to do to apply
  182918. ** the RBU update. If an error does occur, some other error code is
  182919. ** returned.
  182920. **
  182921. ** Once a call to sqlite3rbu_step() has returned a value other than
  182922. ** SQLITE_OK, all subsequent calls on the same RBU handle are no-ops
  182923. ** that immediately return the same value.
  182924. */
  182925. SQLITE_API int sqlite3rbu_step(sqlite3rbu *pRbu);
  182926. /*
  182927. ** Force RBU to save its state to disk.
  182928. **
  182929. ** If a power failure or application crash occurs during an update, following
  182930. ** system recovery RBU may resume the update from the point at which the state
  182931. ** was last saved. In other words, from the most recent successful call to
  182932. ** sqlite3rbu_close() or this function.
  182933. **
  182934. ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
  182935. */
  182936. SQLITE_API int sqlite3rbu_savestate(sqlite3rbu *pRbu);
  182937. /*
  182938. ** Close an RBU handle.
  182939. **
  182940. ** If the RBU update has been completely applied, mark the RBU database
  182941. ** as fully applied. Otherwise, assuming no error has occurred, save the
  182942. ** current state of the RBU update appliation to the RBU database.
  182943. **
  182944. ** If an error has already occurred as part of an sqlite3rbu_step()
  182945. ** or sqlite3rbu_open() call, or if one occurs within this function, an
  182946. ** SQLite error code is returned. Additionally, if pzErrmsg is not NULL,
  182947. ** *pzErrmsg may be set to point to a buffer containing a utf-8 formatted
  182948. ** English language error message. It is the responsibility of the caller to
  182949. ** eventually free any such buffer using sqlite3_free().
  182950. **
  182951. ** Otherwise, if no error occurs, this function returns SQLITE_OK if the
  182952. ** update has been partially applied, or SQLITE_DONE if it has been
  182953. ** completely applied.
  182954. */
  182955. SQLITE_API int sqlite3rbu_close(sqlite3rbu *pRbu, char **pzErrmsg);
  182956. /*
  182957. ** Return the total number of key-value operations (inserts, deletes or
  182958. ** updates) that have been performed on the target database since the
  182959. ** current RBU update was started.
  182960. */
  182961. SQLITE_API sqlite3_int64 sqlite3rbu_progress(sqlite3rbu *pRbu);
  182962. /*
  182963. ** Obtain permyriadage (permyriadage is to 10000 as percentage is to 100)
  182964. ** progress indications for the two stages of an RBU update. This API may
  182965. ** be useful for driving GUI progress indicators and similar.
  182966. **
  182967. ** An RBU update is divided into two stages:
  182968. **
  182969. ** * Stage 1, in which changes are accumulated in an oal/wal file, and
  182970. ** * Stage 2, in which the contents of the wal file are copied into the
  182971. ** main database.
  182972. **
  182973. ** The update is visible to non-RBU clients during stage 2. During stage 1
  182974. ** non-RBU reader clients may see the original database.
  182975. **
  182976. ** If this API is called during stage 2 of the update, output variable
  182977. ** (*pnOne) is set to 10000 to indicate that stage 1 has finished and (*pnTwo)
  182978. ** to a value between 0 and 10000 to indicate the permyriadage progress of
  182979. ** stage 2. A value of 5000 indicates that stage 2 is half finished,
  182980. ** 9000 indicates that it is 90% finished, and so on.
  182981. **
  182982. ** If this API is called during stage 1 of the update, output variable
  182983. ** (*pnTwo) is set to 0 to indicate that stage 2 has not yet started. The
  182984. ** value to which (*pnOne) is set depends on whether or not the RBU
  182985. ** database contains an "rbu_count" table. The rbu_count table, if it
  182986. ** exists, must contain the same columns as the following:
  182987. **
  182988. ** CREATE TABLE rbu_count(tbl TEXT PRIMARY KEY, cnt INTEGER) WITHOUT ROWID;
  182989. **
  182990. ** There must be one row in the table for each source (data_xxx) table within
  182991. ** the RBU database. The 'tbl' column should contain the name of the source
  182992. ** table. The 'cnt' column should contain the number of rows within the
  182993. ** source table.
  182994. **
  182995. ** If the rbu_count table is present and populated correctly and this
  182996. ** API is called during stage 1, the *pnOne output variable is set to the
  182997. ** permyriadage progress of the same stage. If the rbu_count table does
  182998. ** not exist, then (*pnOne) is set to -1 during stage 1. If the rbu_count
  182999. ** table exists but is not correctly populated, the value of the *pnOne
  183000. ** output variable during stage 1 is undefined.
  183001. */
  183002. SQLITE_API void sqlite3rbu_bp_progress(sqlite3rbu *pRbu, int *pnOne, int*pnTwo);
  183003. /*
  183004. ** Obtain an indication as to the current stage of an RBU update or vacuum.
  183005. ** This function always returns one of the SQLITE_RBU_STATE_XXX constants
  183006. ** defined in this file. Return values should be interpreted as follows:
  183007. **
  183008. ** SQLITE_RBU_STATE_OAL:
  183009. ** RBU is currently building a *-oal file. The next call to sqlite3rbu_step()
  183010. ** may either add further data to the *-oal file, or compute data that will
  183011. ** be added by a subsequent call.
  183012. **
  183013. ** SQLITE_RBU_STATE_MOVE:
  183014. ** RBU has finished building the *-oal file. The next call to sqlite3rbu_step()
  183015. ** will move the *-oal file to the equivalent *-wal path. If the current
  183016. ** operation is an RBU update, then the updated version of the database
  183017. ** file will become visible to ordinary SQLite clients following the next
  183018. ** call to sqlite3rbu_step().
  183019. **
  183020. ** SQLITE_RBU_STATE_CHECKPOINT:
  183021. ** RBU is currently performing an incremental checkpoint. The next call to
  183022. ** sqlite3rbu_step() will copy a page of data from the *-wal file into
  183023. ** the target database file.
  183024. **
  183025. ** SQLITE_RBU_STATE_DONE:
  183026. ** The RBU operation has finished. Any subsequent calls to sqlite3rbu_step()
  183027. ** will immediately return SQLITE_DONE.
  183028. **
  183029. ** SQLITE_RBU_STATE_ERROR:
  183030. ** An error has occurred. Any subsequent calls to sqlite3rbu_step() will
  183031. ** immediately return the SQLite error code associated with the error.
  183032. */
  183033. #define SQLITE_RBU_STATE_OAL 1
  183034. #define SQLITE_RBU_STATE_MOVE 2
  183035. #define SQLITE_RBU_STATE_CHECKPOINT 3
  183036. #define SQLITE_RBU_STATE_DONE 4
  183037. #define SQLITE_RBU_STATE_ERROR 5
  183038. SQLITE_API int sqlite3rbu_state(sqlite3rbu *pRbu);
  183039. /*
  183040. ** Create an RBU VFS named zName that accesses the underlying file-system
  183041. ** via existing VFS zParent. Or, if the zParent parameter is passed NULL,
  183042. ** then the new RBU VFS uses the default system VFS to access the file-system.
  183043. ** The new object is registered as a non-default VFS with SQLite before
  183044. ** returning.
  183045. **
  183046. ** Part of the RBU implementation uses a custom VFS object. Usually, this
  183047. ** object is created and deleted automatically by RBU.
  183048. **
  183049. ** The exception is for applications that also use zipvfs. In this case,
  183050. ** the custom VFS must be explicitly created by the user before the RBU
  183051. ** handle is opened. The RBU VFS should be installed so that the zipvfs
  183052. ** VFS uses the RBU VFS, which in turn uses any other VFS layers in use
  183053. ** (for example multiplexor) to access the file-system. For example,
  183054. ** to assemble an RBU enabled VFS stack that uses both zipvfs and
  183055. ** multiplexor (error checking omitted):
  183056. **
  183057. ** // Create a VFS named "multiplex" (not the default).
  183058. ** sqlite3_multiplex_initialize(0, 0);
  183059. **
  183060. ** // Create an rbu VFS named "rbu" that uses multiplexor. If the
  183061. ** // second argument were replaced with NULL, the "rbu" VFS would
  183062. ** // access the file-system via the system default VFS, bypassing the
  183063. ** // multiplexor.
  183064. ** sqlite3rbu_create_vfs("rbu", "multiplex");
  183065. **
  183066. ** // Create a zipvfs VFS named "zipvfs" that uses rbu.
  183067. ** zipvfs_create_vfs_v3("zipvfs", "rbu", 0, xCompressorAlgorithmDetector);
  183068. **
  183069. ** // Make zipvfs the default VFS.
  183070. ** sqlite3_vfs_register(sqlite3_vfs_find("zipvfs"), 1);
  183071. **
  183072. ** Because the default VFS created above includes a RBU functionality, it
  183073. ** may be used by RBU clients. Attempting to use RBU with a zipvfs VFS stack
  183074. ** that does not include the RBU layer results in an error.
  183075. **
  183076. ** The overhead of adding the "rbu" VFS to the system is negligible for
  183077. ** non-RBU users. There is no harm in an application accessing the
  183078. ** file-system via "rbu" all the time, even if it only uses RBU functionality
  183079. ** occasionally.
  183080. */
  183081. SQLITE_API int sqlite3rbu_create_vfs(const char *zName, const char *zParent);
  183082. /*
  183083. ** Deregister and destroy an RBU vfs created by an earlier call to
  183084. ** sqlite3rbu_create_vfs().
  183085. **
  183086. ** VFS objects are not reference counted. If a VFS object is destroyed
  183087. ** before all database handles that use it have been closed, the results
  183088. ** are undefined.
  183089. */
  183090. SQLITE_API void sqlite3rbu_destroy_vfs(const char *zName);
  183091. #if 0
  183092. } /* end of the 'extern "C"' block */
  183093. #endif
  183094. #endif /* _SQLITE3RBU_H */
  183095. /************** End of sqlite3rbu.h ******************************************/
  183096. /************** Continuing where we left off in sqlite3rbu.c *****************/
  183097. #if defined(_WIN32_WCE)
  183098. /* #include "windows.h" */
  183099. #endif
  183100. /* Maximum number of prepared UPDATE statements held by this module */
  183101. #define SQLITE_RBU_UPDATE_CACHESIZE 16
  183102. /* Delta checksums disabled by default. Compile with -DRBU_ENABLE_DELTA_CKSUM
  183103. ** to enable checksum verification.
  183104. */
  183105. #ifndef RBU_ENABLE_DELTA_CKSUM
  183106. # define RBU_ENABLE_DELTA_CKSUM 0
  183107. #endif
  183108. /*
  183109. ** Swap two objects of type TYPE.
  183110. */
  183111. #if !defined(SQLITE_AMALGAMATION)
  183112. # define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
  183113. #endif
  183114. /*
  183115. ** The rbu_state table is used to save the state of a partially applied
  183116. ** update so that it can be resumed later. The table consists of integer
  183117. ** keys mapped to values as follows:
  183118. **
  183119. ** RBU_STATE_STAGE:
  183120. ** May be set to integer values 1, 2, 4 or 5. As follows:
  183121. ** 1: the *-rbu file is currently under construction.
  183122. ** 2: the *-rbu file has been constructed, but not yet moved
  183123. ** to the *-wal path.
  183124. ** 4: the checkpoint is underway.
  183125. ** 5: the rbu update has been checkpointed.
  183126. **
  183127. ** RBU_STATE_TBL:
  183128. ** Only valid if STAGE==1. The target database name of the table
  183129. ** currently being written.
  183130. **
  183131. ** RBU_STATE_IDX:
  183132. ** Only valid if STAGE==1. The target database name of the index
  183133. ** currently being written, or NULL if the main table is currently being
  183134. ** updated.
  183135. **
  183136. ** RBU_STATE_ROW:
  183137. ** Only valid if STAGE==1. Number of rows already processed for the current
  183138. ** table/index.
  183139. **
  183140. ** RBU_STATE_PROGRESS:
  183141. ** Trbul number of sqlite3rbu_step() calls made so far as part of this
  183142. ** rbu update.
  183143. **
  183144. ** RBU_STATE_CKPT:
  183145. ** Valid if STAGE==4. The 64-bit checksum associated with the wal-index
  183146. ** header created by recovering the *-wal file. This is used to detect
  183147. ** cases when another client appends frames to the *-wal file in the
  183148. ** middle of an incremental checkpoint (an incremental checkpoint cannot
  183149. ** be continued if this happens).
  183150. **
  183151. ** RBU_STATE_COOKIE:
  183152. ** Valid if STAGE==1. The current change-counter cookie value in the
  183153. ** target db file.
  183154. **
  183155. ** RBU_STATE_OALSZ:
  183156. ** Valid if STAGE==1. The size in bytes of the *-oal file.
  183157. **
  183158. ** RBU_STATE_DATATBL:
  183159. ** Only valid if STAGE==1. The RBU database name of the table
  183160. ** currently being read.
  183161. */
  183162. #define RBU_STATE_STAGE 1
  183163. #define RBU_STATE_TBL 2
  183164. #define RBU_STATE_IDX 3
  183165. #define RBU_STATE_ROW 4
  183166. #define RBU_STATE_PROGRESS 5
  183167. #define RBU_STATE_CKPT 6
  183168. #define RBU_STATE_COOKIE 7
  183169. #define RBU_STATE_OALSZ 8
  183170. #define RBU_STATE_PHASEONESTEP 9
  183171. #define RBU_STATE_DATATBL 10
  183172. #define RBU_STAGE_OAL 1
  183173. #define RBU_STAGE_MOVE 2
  183174. #define RBU_STAGE_CAPTURE 3
  183175. #define RBU_STAGE_CKPT 4
  183176. #define RBU_STAGE_DONE 5
  183177. #define RBU_CREATE_STATE \
  183178. "CREATE TABLE IF NOT EXISTS %s.rbu_state(k INTEGER PRIMARY KEY, v)"
  183179. typedef struct RbuFrame RbuFrame;
  183180. typedef struct RbuObjIter RbuObjIter;
  183181. typedef struct RbuState RbuState;
  183182. typedef struct RbuSpan RbuSpan;
  183183. typedef struct rbu_vfs rbu_vfs;
  183184. typedef struct rbu_file rbu_file;
  183185. typedef struct RbuUpdateStmt RbuUpdateStmt;
  183186. #if !defined(SQLITE_AMALGAMATION)
  183187. typedef unsigned int u32;
  183188. typedef unsigned short u16;
  183189. typedef unsigned char u8;
  183190. typedef sqlite3_int64 i64;
  183191. #endif
  183192. /*
  183193. ** These values must match the values defined in wal.c for the equivalent
  183194. ** locks. These are not magic numbers as they are part of the SQLite file
  183195. ** format.
  183196. */
  183197. #define WAL_LOCK_WRITE 0
  183198. #define WAL_LOCK_CKPT 1
  183199. #define WAL_LOCK_READ0 3
  183200. #define SQLITE_FCNTL_RBUCNT 5149216
  183201. /*
  183202. ** A structure to store values read from the rbu_state table in memory.
  183203. */
  183204. struct RbuState {
  183205. int eStage;
  183206. char *zTbl;
  183207. char *zDataTbl;
  183208. char *zIdx;
  183209. i64 iWalCksum;
  183210. int nRow;
  183211. i64 nProgress;
  183212. u32 iCookie;
  183213. i64 iOalSz;
  183214. i64 nPhaseOneStep;
  183215. };
  183216. struct RbuUpdateStmt {
  183217. char *zMask; /* Copy of update mask used with pUpdate */
  183218. sqlite3_stmt *pUpdate; /* Last update statement (or NULL) */
  183219. RbuUpdateStmt *pNext;
  183220. };
  183221. struct RbuSpan {
  183222. const char *zSpan;
  183223. int nSpan;
  183224. };
  183225. /*
  183226. ** An iterator of this type is used to iterate through all objects in
  183227. ** the target database that require updating. For each such table, the
  183228. ** iterator visits, in order:
  183229. **
  183230. ** * the table itself,
  183231. ** * each index of the table (zero or more points to visit), and
  183232. ** * a special "cleanup table" state.
  183233. **
  183234. ** abIndexed:
  183235. ** If the table has no indexes on it, abIndexed is set to NULL. Otherwise,
  183236. ** it points to an array of flags nTblCol elements in size. The flag is
  183237. ** set for each column that is either a part of the PK or a part of an
  183238. ** index. Or clear otherwise.
  183239. **
  183240. ** If there are one or more partial indexes on the table, all fields of
  183241. ** this array set set to 1. This is because in that case, the module has
  183242. ** no way to tell which fields will be required to add and remove entries
  183243. ** from the partial indexes.
  183244. **
  183245. */
  183246. struct RbuObjIter {
  183247. sqlite3_stmt *pTblIter; /* Iterate through tables */
  183248. sqlite3_stmt *pIdxIter; /* Index iterator */
  183249. int nTblCol; /* Size of azTblCol[] array */
  183250. char **azTblCol; /* Array of unquoted target column names */
  183251. char **azTblType; /* Array of target column types */
  183252. int *aiSrcOrder; /* src table col -> target table col */
  183253. u8 *abTblPk; /* Array of flags, set on target PK columns */
  183254. u8 *abNotNull; /* Array of flags, set on NOT NULL columns */
  183255. u8 *abIndexed; /* Array of flags, set on indexed & PK cols */
  183256. int eType; /* Table type - an RBU_PK_XXX value */
  183257. /* Output variables. zTbl==0 implies EOF. */
  183258. int bCleanup; /* True in "cleanup" state */
  183259. const char *zTbl; /* Name of target db table */
  183260. const char *zDataTbl; /* Name of rbu db table (or null) */
  183261. const char *zIdx; /* Name of target db index (or null) */
  183262. int iTnum; /* Root page of current object */
  183263. int iPkTnum; /* If eType==EXTERNAL, root of PK index */
  183264. int bUnique; /* Current index is unique */
  183265. int nIndex; /* Number of aux. indexes on table zTbl */
  183266. /* Statements created by rbuObjIterPrepareAll() */
  183267. int nCol; /* Number of columns in current object */
  183268. sqlite3_stmt *pSelect; /* Source data */
  183269. sqlite3_stmt *pInsert; /* Statement for INSERT operations */
  183270. sqlite3_stmt *pDelete; /* Statement for DELETE ops */
  183271. sqlite3_stmt *pTmpInsert; /* Insert into rbu_tmp_$zDataTbl */
  183272. int nIdxCol;
  183273. RbuSpan *aIdxCol;
  183274. char *zIdxSql;
  183275. /* Last UPDATE used (for PK b-tree updates only), or NULL. */
  183276. RbuUpdateStmt *pRbuUpdate;
  183277. };
  183278. /*
  183279. ** Values for RbuObjIter.eType
  183280. **
  183281. ** 0: Table does not exist (error)
  183282. ** 1: Table has an implicit rowid.
  183283. ** 2: Table has an explicit IPK column.
  183284. ** 3: Table has an external PK index.
  183285. ** 4: Table is WITHOUT ROWID.
  183286. ** 5: Table is a virtual table.
  183287. */
  183288. #define RBU_PK_NOTABLE 0
  183289. #define RBU_PK_NONE 1
  183290. #define RBU_PK_IPK 2
  183291. #define RBU_PK_EXTERNAL 3
  183292. #define RBU_PK_WITHOUT_ROWID 4
  183293. #define RBU_PK_VTAB 5
  183294. /*
  183295. ** Within the RBU_STAGE_OAL stage, each call to sqlite3rbu_step() performs
  183296. ** one of the following operations.
  183297. */
  183298. #define RBU_INSERT 1 /* Insert on a main table b-tree */
  183299. #define RBU_DELETE 2 /* Delete a row from a main table b-tree */
  183300. #define RBU_REPLACE 3 /* Delete and then insert a row */
  183301. #define RBU_IDX_DELETE 4 /* Delete a row from an aux. index b-tree */
  183302. #define RBU_IDX_INSERT 5 /* Insert on an aux. index b-tree */
  183303. #define RBU_UPDATE 6 /* Update a row in a main table b-tree */
  183304. /*
  183305. ** A single step of an incremental checkpoint - frame iWalFrame of the wal
  183306. ** file should be copied to page iDbPage of the database file.
  183307. */
  183308. struct RbuFrame {
  183309. u32 iDbPage;
  183310. u32 iWalFrame;
  183311. };
  183312. /*
  183313. ** RBU handle.
  183314. **
  183315. ** nPhaseOneStep:
  183316. ** If the RBU database contains an rbu_count table, this value is set to
  183317. ** a running estimate of the number of b-tree operations required to
  183318. ** finish populating the *-oal file. This allows the sqlite3_bp_progress()
  183319. ** API to calculate the permyriadage progress of populating the *-oal file
  183320. ** using the formula:
  183321. **
  183322. ** permyriadage = (10000 * nProgress) / nPhaseOneStep
  183323. **
  183324. ** nPhaseOneStep is initialized to the sum of:
  183325. **
  183326. ** nRow * (nIndex + 1)
  183327. **
  183328. ** for all source tables in the RBU database, where nRow is the number
  183329. ** of rows in the source table and nIndex the number of indexes on the
  183330. ** corresponding target database table.
  183331. **
  183332. ** This estimate is accurate if the RBU update consists entirely of
  183333. ** INSERT operations. However, it is inaccurate if:
  183334. **
  183335. ** * the RBU update contains any UPDATE operations. If the PK specified
  183336. ** for an UPDATE operation does not exist in the target table, then
  183337. ** no b-tree operations are required on index b-trees. Or if the
  183338. ** specified PK does exist, then (nIndex*2) such operations are
  183339. ** required (one delete and one insert on each index b-tree).
  183340. **
  183341. ** * the RBU update contains any DELETE operations for which the specified
  183342. ** PK does not exist. In this case no operations are required on index
  183343. ** b-trees.
  183344. **
  183345. ** * the RBU update contains REPLACE operations. These are similar to
  183346. ** UPDATE operations.
  183347. **
  183348. ** nPhaseOneStep is updated to account for the conditions above during the
  183349. ** first pass of each source table. The updated nPhaseOneStep value is
  183350. ** stored in the rbu_state table if the RBU update is suspended.
  183351. */
  183352. struct sqlite3rbu {
  183353. int eStage; /* Value of RBU_STATE_STAGE field */
  183354. sqlite3 *dbMain; /* target database handle */
  183355. sqlite3 *dbRbu; /* rbu database handle */
  183356. char *zTarget; /* Path to target db */
  183357. char *zRbu; /* Path to rbu db */
  183358. char *zState; /* Path to state db (or NULL if zRbu) */
  183359. char zStateDb[5]; /* Db name for state ("stat" or "main") */
  183360. int rc; /* Value returned by last rbu_step() call */
  183361. char *zErrmsg; /* Error message if rc!=SQLITE_OK */
  183362. int nStep; /* Rows processed for current object */
  183363. int nProgress; /* Rows processed for all objects */
  183364. RbuObjIter objiter; /* Iterator for skipping through tbl/idx */
  183365. const char *zVfsName; /* Name of automatically created rbu vfs */
  183366. rbu_file *pTargetFd; /* File handle open on target db */
  183367. int nPagePerSector; /* Pages per sector for pTargetFd */
  183368. i64 iOalSz;
  183369. i64 nPhaseOneStep;
  183370. /* The following state variables are used as part of the incremental
  183371. ** checkpoint stage (eStage==RBU_STAGE_CKPT). See comments surrounding
  183372. ** function rbuSetupCheckpoint() for details. */
  183373. u32 iMaxFrame; /* Largest iWalFrame value in aFrame[] */
  183374. u32 mLock;
  183375. int nFrame; /* Entries in aFrame[] array */
  183376. int nFrameAlloc; /* Allocated size of aFrame[] array */
  183377. RbuFrame *aFrame;
  183378. int pgsz;
  183379. u8 *aBuf;
  183380. i64 iWalCksum;
  183381. i64 szTemp; /* Current size of all temp files in use */
  183382. i64 szTempLimit; /* Total size limit for temp files */
  183383. /* Used in RBU vacuum mode only */
  183384. int nRbu; /* Number of RBU VFS in the stack */
  183385. rbu_file *pRbuFd; /* Fd for main db of dbRbu */
  183386. };
  183387. /*
  183388. ** An rbu VFS is implemented using an instance of this structure.
  183389. **
  183390. ** Variable pRbu is only non-NULL for automatically created RBU VFS objects.
  183391. ** It is NULL for RBU VFS objects created explicitly using
  183392. ** sqlite3rbu_create_vfs(). It is used to track the total amount of temp
  183393. ** space used by the RBU handle.
  183394. */
  183395. struct rbu_vfs {
  183396. sqlite3_vfs base; /* rbu VFS shim methods */
  183397. sqlite3_vfs *pRealVfs; /* Underlying VFS */
  183398. sqlite3_mutex *mutex; /* Mutex to protect pMain */
  183399. sqlite3rbu *pRbu; /* Owner RBU object */
  183400. rbu_file *pMain; /* List of main db files */
  183401. rbu_file *pMainRbu; /* List of main db files with pRbu!=0 */
  183402. };
  183403. /*
  183404. ** Each file opened by an rbu VFS is represented by an instance of
  183405. ** the following structure.
  183406. **
  183407. ** If this is a temporary file (pRbu!=0 && flags&DELETE_ON_CLOSE), variable
  183408. ** "sz" is set to the current size of the database file.
  183409. */
  183410. struct rbu_file {
  183411. sqlite3_file base; /* sqlite3_file methods */
  183412. sqlite3_file *pReal; /* Underlying file handle */
  183413. rbu_vfs *pRbuVfs; /* Pointer to the rbu_vfs object */
  183414. sqlite3rbu *pRbu; /* Pointer to rbu object (rbu target only) */
  183415. i64 sz; /* Size of file in bytes (temp only) */
  183416. int openFlags; /* Flags this file was opened with */
  183417. u32 iCookie; /* Cookie value for main db files */
  183418. u8 iWriteVer; /* "write-version" value for main db files */
  183419. u8 bNolock; /* True to fail EXCLUSIVE locks */
  183420. int nShm; /* Number of entries in apShm[] array */
  183421. char **apShm; /* Array of mmap'd *-shm regions */
  183422. char *zDel; /* Delete this when closing file */
  183423. const char *zWal; /* Wal filename for this main db file */
  183424. rbu_file *pWalFd; /* Wal file descriptor for this main db */
  183425. rbu_file *pMainNext; /* Next MAIN_DB file */
  183426. rbu_file *pMainRbuNext; /* Next MAIN_DB file with pRbu!=0 */
  183427. };
  183428. /*
  183429. ** True for an RBU vacuum handle, or false otherwise.
  183430. */
  183431. #define rbuIsVacuum(p) ((p)->zTarget==0)
  183432. /*************************************************************************
  183433. ** The following three functions, found below:
  183434. **
  183435. ** rbuDeltaGetInt()
  183436. ** rbuDeltaChecksum()
  183437. ** rbuDeltaApply()
  183438. **
  183439. ** are lifted from the fossil source code (http://fossil-scm.org). They
  183440. ** are used to implement the scalar SQL function rbu_fossil_delta().
  183441. */
  183442. /*
  183443. ** Read bytes from *pz and convert them into a positive integer. When
  183444. ** finished, leave *pz pointing to the first character past the end of
  183445. ** the integer. The *pLen parameter holds the length of the string
  183446. ** in *pz and is decremented once for each character in the integer.
  183447. */
  183448. static unsigned int rbuDeltaGetInt(const char **pz, int *pLen){
  183449. static const signed char zValue[] = {
  183450. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  183451. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  183452. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  183453. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1,
  183454. -1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
  183455. 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, -1, -1, -1, -1, 36,
  183456. -1, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51,
  183457. 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, -1, -1, -1, 63, -1,
  183458. };
  183459. unsigned int v = 0;
  183460. int c;
  183461. unsigned char *z = (unsigned char*)*pz;
  183462. unsigned char *zStart = z;
  183463. while( (c = zValue[0x7f&*(z++)])>=0 ){
  183464. v = (v<<6) + c;
  183465. }
  183466. z--;
  183467. *pLen -= z - zStart;
  183468. *pz = (char*)z;
  183469. return v;
  183470. }
  183471. #if RBU_ENABLE_DELTA_CKSUM
  183472. /*
  183473. ** Compute a 32-bit checksum on the N-byte buffer. Return the result.
  183474. */
  183475. static unsigned int rbuDeltaChecksum(const char *zIn, size_t N){
  183476. const unsigned char *z = (const unsigned char *)zIn;
  183477. unsigned sum0 = 0;
  183478. unsigned sum1 = 0;
  183479. unsigned sum2 = 0;
  183480. unsigned sum3 = 0;
  183481. while(N >= 16){
  183482. sum0 += ((unsigned)z[0] + z[4] + z[8] + z[12]);
  183483. sum1 += ((unsigned)z[1] + z[5] + z[9] + z[13]);
  183484. sum2 += ((unsigned)z[2] + z[6] + z[10]+ z[14]);
  183485. sum3 += ((unsigned)z[3] + z[7] + z[11]+ z[15]);
  183486. z += 16;
  183487. N -= 16;
  183488. }
  183489. while(N >= 4){
  183490. sum0 += z[0];
  183491. sum1 += z[1];
  183492. sum2 += z[2];
  183493. sum3 += z[3];
  183494. z += 4;
  183495. N -= 4;
  183496. }
  183497. sum3 += (sum2 << 8) + (sum1 << 16) + (sum0 << 24);
  183498. switch(N){
  183499. case 3: sum3 += (z[2] << 8);
  183500. case 2: sum3 += (z[1] << 16);
  183501. case 1: sum3 += (z[0] << 24);
  183502. default: ;
  183503. }
  183504. return sum3;
  183505. }
  183506. #endif
  183507. /*
  183508. ** Apply a delta.
  183509. **
  183510. ** The output buffer should be big enough to hold the whole output
  183511. ** file and a NUL terminator at the end. The delta_output_size()
  183512. ** routine will determine this size for you.
  183513. **
  183514. ** The delta string should be null-terminated. But the delta string
  183515. ** may contain embedded NUL characters (if the input and output are
  183516. ** binary files) so we also have to pass in the length of the delta in
  183517. ** the lenDelta parameter.
  183518. **
  183519. ** This function returns the size of the output file in bytes (excluding
  183520. ** the final NUL terminator character). Except, if the delta string is
  183521. ** malformed or intended for use with a source file other than zSrc,
  183522. ** then this routine returns -1.
  183523. **
  183524. ** Refer to the delta_create() documentation above for a description
  183525. ** of the delta file format.
  183526. */
  183527. static int rbuDeltaApply(
  183528. const char *zSrc, /* The source or pattern file */
  183529. int lenSrc, /* Length of the source file */
  183530. const char *zDelta, /* Delta to apply to the pattern */
  183531. int lenDelta, /* Length of the delta */
  183532. char *zOut /* Write the output into this preallocated buffer */
  183533. ){
  183534. unsigned int limit;
  183535. unsigned int total = 0;
  183536. #if RBU_ENABLE_DELTA_CKSUM
  183537. char *zOrigOut = zOut;
  183538. #endif
  183539. limit = rbuDeltaGetInt(&zDelta, &lenDelta);
  183540. if( *zDelta!='\n' ){
  183541. /* ERROR: size integer not terminated by "\n" */
  183542. return -1;
  183543. }
  183544. zDelta++; lenDelta--;
  183545. while( *zDelta && lenDelta>0 ){
  183546. unsigned int cnt, ofst;
  183547. cnt = rbuDeltaGetInt(&zDelta, &lenDelta);
  183548. switch( zDelta[0] ){
  183549. case '@': {
  183550. zDelta++; lenDelta--;
  183551. ofst = rbuDeltaGetInt(&zDelta, &lenDelta);
  183552. if( lenDelta>0 && zDelta[0]!=',' ){
  183553. /* ERROR: copy command not terminated by ',' */
  183554. return -1;
  183555. }
  183556. zDelta++; lenDelta--;
  183557. total += cnt;
  183558. if( total>limit ){
  183559. /* ERROR: copy exceeds output file size */
  183560. return -1;
  183561. }
  183562. if( (int)(ofst+cnt) > lenSrc ){
  183563. /* ERROR: copy extends past end of input */
  183564. return -1;
  183565. }
  183566. memcpy(zOut, &zSrc[ofst], cnt);
  183567. zOut += cnt;
  183568. break;
  183569. }
  183570. case ':': {
  183571. zDelta++; lenDelta--;
  183572. total += cnt;
  183573. if( total>limit ){
  183574. /* ERROR: insert command gives an output larger than predicted */
  183575. return -1;
  183576. }
  183577. if( (int)cnt>lenDelta ){
  183578. /* ERROR: insert count exceeds size of delta */
  183579. return -1;
  183580. }
  183581. memcpy(zOut, zDelta, cnt);
  183582. zOut += cnt;
  183583. zDelta += cnt;
  183584. lenDelta -= cnt;
  183585. break;
  183586. }
  183587. case ';': {
  183588. zDelta++; lenDelta--;
  183589. zOut[0] = 0;
  183590. #if RBU_ENABLE_DELTA_CKSUM
  183591. if( cnt!=rbuDeltaChecksum(zOrigOut, total) ){
  183592. /* ERROR: bad checksum */
  183593. return -1;
  183594. }
  183595. #endif
  183596. if( total!=limit ){
  183597. /* ERROR: generated size does not match predicted size */
  183598. return -1;
  183599. }
  183600. return total;
  183601. }
  183602. default: {
  183603. /* ERROR: unknown delta operator */
  183604. return -1;
  183605. }
  183606. }
  183607. }
  183608. /* ERROR: unterminated delta */
  183609. return -1;
  183610. }
  183611. static int rbuDeltaOutputSize(const char *zDelta, int lenDelta){
  183612. int size;
  183613. size = rbuDeltaGetInt(&zDelta, &lenDelta);
  183614. if( *zDelta!='\n' ){
  183615. /* ERROR: size integer not terminated by "\n" */
  183616. return -1;
  183617. }
  183618. return size;
  183619. }
  183620. /*
  183621. ** End of code taken from fossil.
  183622. *************************************************************************/
  183623. /*
  183624. ** Implementation of SQL scalar function rbu_fossil_delta().
  183625. **
  183626. ** This function applies a fossil delta patch to a blob. Exactly two
  183627. ** arguments must be passed to this function. The first is the blob to
  183628. ** patch and the second the patch to apply. If no error occurs, this
  183629. ** function returns the patched blob.
  183630. */
  183631. static void rbuFossilDeltaFunc(
  183632. sqlite3_context *context,
  183633. int argc,
  183634. sqlite3_value **argv
  183635. ){
  183636. const char *aDelta;
  183637. int nDelta;
  183638. const char *aOrig;
  183639. int nOrig;
  183640. int nOut;
  183641. int nOut2;
  183642. char *aOut;
  183643. assert( argc==2 );
  183644. nOrig = sqlite3_value_bytes(argv[0]);
  183645. aOrig = (const char*)sqlite3_value_blob(argv[0]);
  183646. nDelta = sqlite3_value_bytes(argv[1]);
  183647. aDelta = (const char*)sqlite3_value_blob(argv[1]);
  183648. /* Figure out the size of the output */
  183649. nOut = rbuDeltaOutputSize(aDelta, nDelta);
  183650. if( nOut<0 ){
  183651. sqlite3_result_error(context, "corrupt fossil delta", -1);
  183652. return;
  183653. }
  183654. aOut = sqlite3_malloc(nOut+1);
  183655. if( aOut==0 ){
  183656. sqlite3_result_error_nomem(context);
  183657. }else{
  183658. nOut2 = rbuDeltaApply(aOrig, nOrig, aDelta, nDelta, aOut);
  183659. if( nOut2!=nOut ){
  183660. sqlite3_free(aOut);
  183661. sqlite3_result_error(context, "corrupt fossil delta", -1);
  183662. }else{
  183663. sqlite3_result_blob(context, aOut, nOut, sqlite3_free);
  183664. }
  183665. }
  183666. }
  183667. /*
  183668. ** Prepare the SQL statement in buffer zSql against database handle db.
  183669. ** If successful, set *ppStmt to point to the new statement and return
  183670. ** SQLITE_OK.
  183671. **
  183672. ** Otherwise, if an error does occur, set *ppStmt to NULL and return
  183673. ** an SQLite error code. Additionally, set output variable *pzErrmsg to
  183674. ** point to a buffer containing an error message. It is the responsibility
  183675. ** of the caller to (eventually) free this buffer using sqlite3_free().
  183676. */
  183677. static int prepareAndCollectError(
  183678. sqlite3 *db,
  183679. sqlite3_stmt **ppStmt,
  183680. char **pzErrmsg,
  183681. const char *zSql
  183682. ){
  183683. int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
  183684. if( rc!=SQLITE_OK ){
  183685. *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  183686. *ppStmt = 0;
  183687. }
  183688. return rc;
  183689. }
  183690. /*
  183691. ** Reset the SQL statement passed as the first argument. Return a copy
  183692. ** of the value returned by sqlite3_reset().
  183693. **
  183694. ** If an error has occurred, then set *pzErrmsg to point to a buffer
  183695. ** containing an error message. It is the responsibility of the caller
  183696. ** to eventually free this buffer using sqlite3_free().
  183697. */
  183698. static int resetAndCollectError(sqlite3_stmt *pStmt, char **pzErrmsg){
  183699. int rc = sqlite3_reset(pStmt);
  183700. if( rc!=SQLITE_OK ){
  183701. *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(sqlite3_db_handle(pStmt)));
  183702. }
  183703. return rc;
  183704. }
  183705. /*
  183706. ** Unless it is NULL, argument zSql points to a buffer allocated using
  183707. ** sqlite3_malloc containing an SQL statement. This function prepares the SQL
  183708. ** statement against database db and frees the buffer. If statement
  183709. ** compilation is successful, *ppStmt is set to point to the new statement
  183710. ** handle and SQLITE_OK is returned.
  183711. **
  183712. ** Otherwise, if an error occurs, *ppStmt is set to NULL and an error code
  183713. ** returned. In this case, *pzErrmsg may also be set to point to an error
  183714. ** message. It is the responsibility of the caller to free this error message
  183715. ** buffer using sqlite3_free().
  183716. **
  183717. ** If argument zSql is NULL, this function assumes that an OOM has occurred.
  183718. ** In this case SQLITE_NOMEM is returned and *ppStmt set to NULL.
  183719. */
  183720. static int prepareFreeAndCollectError(
  183721. sqlite3 *db,
  183722. sqlite3_stmt **ppStmt,
  183723. char **pzErrmsg,
  183724. char *zSql
  183725. ){
  183726. int rc;
  183727. assert( *pzErrmsg==0 );
  183728. if( zSql==0 ){
  183729. rc = SQLITE_NOMEM;
  183730. *ppStmt = 0;
  183731. }else{
  183732. rc = prepareAndCollectError(db, ppStmt, pzErrmsg, zSql);
  183733. sqlite3_free(zSql);
  183734. }
  183735. return rc;
  183736. }
  183737. /*
  183738. ** Free the RbuObjIter.azTblCol[] and RbuObjIter.abTblPk[] arrays allocated
  183739. ** by an earlier call to rbuObjIterCacheTableInfo().
  183740. */
  183741. static void rbuObjIterFreeCols(RbuObjIter *pIter){
  183742. int i;
  183743. for(i=0; i<pIter->nTblCol; i++){
  183744. sqlite3_free(pIter->azTblCol[i]);
  183745. sqlite3_free(pIter->azTblType[i]);
  183746. }
  183747. sqlite3_free(pIter->azTblCol);
  183748. pIter->azTblCol = 0;
  183749. pIter->azTblType = 0;
  183750. pIter->aiSrcOrder = 0;
  183751. pIter->abTblPk = 0;
  183752. pIter->abNotNull = 0;
  183753. pIter->nTblCol = 0;
  183754. pIter->eType = 0; /* Invalid value */
  183755. }
  183756. /*
  183757. ** Finalize all statements and free all allocations that are specific to
  183758. ** the current object (table/index pair).
  183759. */
  183760. static void rbuObjIterClearStatements(RbuObjIter *pIter){
  183761. RbuUpdateStmt *pUp;
  183762. sqlite3_finalize(pIter->pSelect);
  183763. sqlite3_finalize(pIter->pInsert);
  183764. sqlite3_finalize(pIter->pDelete);
  183765. sqlite3_finalize(pIter->pTmpInsert);
  183766. pUp = pIter->pRbuUpdate;
  183767. while( pUp ){
  183768. RbuUpdateStmt *pTmp = pUp->pNext;
  183769. sqlite3_finalize(pUp->pUpdate);
  183770. sqlite3_free(pUp);
  183771. pUp = pTmp;
  183772. }
  183773. sqlite3_free(pIter->aIdxCol);
  183774. sqlite3_free(pIter->zIdxSql);
  183775. pIter->pSelect = 0;
  183776. pIter->pInsert = 0;
  183777. pIter->pDelete = 0;
  183778. pIter->pRbuUpdate = 0;
  183779. pIter->pTmpInsert = 0;
  183780. pIter->nCol = 0;
  183781. pIter->nIdxCol = 0;
  183782. pIter->aIdxCol = 0;
  183783. pIter->zIdxSql = 0;
  183784. }
  183785. /*
  183786. ** Clean up any resources allocated as part of the iterator object passed
  183787. ** as the only argument.
  183788. */
  183789. static void rbuObjIterFinalize(RbuObjIter *pIter){
  183790. rbuObjIterClearStatements(pIter);
  183791. sqlite3_finalize(pIter->pTblIter);
  183792. sqlite3_finalize(pIter->pIdxIter);
  183793. rbuObjIterFreeCols(pIter);
  183794. memset(pIter, 0, sizeof(RbuObjIter));
  183795. }
  183796. /*
  183797. ** Advance the iterator to the next position.
  183798. **
  183799. ** If no error occurs, SQLITE_OK is returned and the iterator is left
  183800. ** pointing to the next entry. Otherwise, an error code and message is
  183801. ** left in the RBU handle passed as the first argument. A copy of the
  183802. ** error code is returned.
  183803. */
  183804. static int rbuObjIterNext(sqlite3rbu *p, RbuObjIter *pIter){
  183805. int rc = p->rc;
  183806. if( rc==SQLITE_OK ){
  183807. /* Free any SQLite statements used while processing the previous object */
  183808. rbuObjIterClearStatements(pIter);
  183809. if( pIter->zIdx==0 ){
  183810. rc = sqlite3_exec(p->dbMain,
  183811. "DROP TRIGGER IF EXISTS temp.rbu_insert_tr;"
  183812. "DROP TRIGGER IF EXISTS temp.rbu_update1_tr;"
  183813. "DROP TRIGGER IF EXISTS temp.rbu_update2_tr;"
  183814. "DROP TRIGGER IF EXISTS temp.rbu_delete_tr;"
  183815. , 0, 0, &p->zErrmsg
  183816. );
  183817. }
  183818. if( rc==SQLITE_OK ){
  183819. if( pIter->bCleanup ){
  183820. rbuObjIterFreeCols(pIter);
  183821. pIter->bCleanup = 0;
  183822. rc = sqlite3_step(pIter->pTblIter);
  183823. if( rc!=SQLITE_ROW ){
  183824. rc = resetAndCollectError(pIter->pTblIter, &p->zErrmsg);
  183825. pIter->zTbl = 0;
  183826. }else{
  183827. pIter->zTbl = (const char*)sqlite3_column_text(pIter->pTblIter, 0);
  183828. pIter->zDataTbl = (const char*)sqlite3_column_text(pIter->pTblIter,1);
  183829. rc = (pIter->zDataTbl && pIter->zTbl) ? SQLITE_OK : SQLITE_NOMEM;
  183830. }
  183831. }else{
  183832. if( pIter->zIdx==0 ){
  183833. sqlite3_stmt *pIdx = pIter->pIdxIter;
  183834. rc = sqlite3_bind_text(pIdx, 1, pIter->zTbl, -1, SQLITE_STATIC);
  183835. }
  183836. if( rc==SQLITE_OK ){
  183837. rc = sqlite3_step(pIter->pIdxIter);
  183838. if( rc!=SQLITE_ROW ){
  183839. rc = resetAndCollectError(pIter->pIdxIter, &p->zErrmsg);
  183840. pIter->bCleanup = 1;
  183841. pIter->zIdx = 0;
  183842. }else{
  183843. pIter->zIdx = (const char*)sqlite3_column_text(pIter->pIdxIter, 0);
  183844. pIter->iTnum = sqlite3_column_int(pIter->pIdxIter, 1);
  183845. pIter->bUnique = sqlite3_column_int(pIter->pIdxIter, 2);
  183846. rc = pIter->zIdx ? SQLITE_OK : SQLITE_NOMEM;
  183847. }
  183848. }
  183849. }
  183850. }
  183851. }
  183852. if( rc!=SQLITE_OK ){
  183853. rbuObjIterFinalize(pIter);
  183854. p->rc = rc;
  183855. }
  183856. return rc;
  183857. }
  183858. /*
  183859. ** The implementation of the rbu_target_name() SQL function. This function
  183860. ** accepts one or two arguments. The first argument is the name of a table -
  183861. ** the name of a table in the RBU database. The second, if it is present, is 1
  183862. ** for a view or 0 for a table.
  183863. **
  183864. ** For a non-vacuum RBU handle, if the table name matches the pattern:
  183865. **
  183866. ** data[0-9]_<name>
  183867. **
  183868. ** where <name> is any sequence of 1 or more characters, <name> is returned.
  183869. ** Otherwise, if the only argument does not match the above pattern, an SQL
  183870. ** NULL is returned.
  183871. **
  183872. ** "data_t1" -> "t1"
  183873. ** "data0123_t2" -> "t2"
  183874. ** "dataAB_t3" -> NULL
  183875. **
  183876. ** For an rbu vacuum handle, a copy of the first argument is returned if
  183877. ** the second argument is either missing or 0 (not a view).
  183878. */
  183879. static void rbuTargetNameFunc(
  183880. sqlite3_context *pCtx,
  183881. int argc,
  183882. sqlite3_value **argv
  183883. ){
  183884. sqlite3rbu *p = sqlite3_user_data(pCtx);
  183885. const char *zIn;
  183886. assert( argc==1 || argc==2 );
  183887. zIn = (const char*)sqlite3_value_text(argv[0]);
  183888. if( zIn ){
  183889. if( rbuIsVacuum(p) ){
  183890. assert( argc==2 || argc==1 );
  183891. if( argc==1 || 0==sqlite3_value_int(argv[1]) ){
  183892. sqlite3_result_text(pCtx, zIn, -1, SQLITE_STATIC);
  183893. }
  183894. }else{
  183895. if( strlen(zIn)>4 && memcmp("data", zIn, 4)==0 ){
  183896. int i;
  183897. for(i=4; zIn[i]>='0' && zIn[i]<='9'; i++);
  183898. if( zIn[i]=='_' && zIn[i+1] ){
  183899. sqlite3_result_text(pCtx, &zIn[i+1], -1, SQLITE_STATIC);
  183900. }
  183901. }
  183902. }
  183903. }
  183904. }
  183905. /*
  183906. ** Initialize the iterator structure passed as the second argument.
  183907. **
  183908. ** If no error occurs, SQLITE_OK is returned and the iterator is left
  183909. ** pointing to the first entry. Otherwise, an error code and message is
  183910. ** left in the RBU handle passed as the first argument. A copy of the
  183911. ** error code is returned.
  183912. */
  183913. static int rbuObjIterFirst(sqlite3rbu *p, RbuObjIter *pIter){
  183914. int rc;
  183915. memset(pIter, 0, sizeof(RbuObjIter));
  183916. rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pTblIter, &p->zErrmsg,
  183917. sqlite3_mprintf(
  183918. "SELECT rbu_target_name(name, type='view') AS target, name "
  183919. "FROM sqlite_master "
  183920. "WHERE type IN ('table', 'view') AND target IS NOT NULL "
  183921. " %s "
  183922. "ORDER BY name"
  183923. , rbuIsVacuum(p) ? "AND rootpage!=0 AND rootpage IS NOT NULL" : ""));
  183924. if( rc==SQLITE_OK ){
  183925. rc = prepareAndCollectError(p->dbMain, &pIter->pIdxIter, &p->zErrmsg,
  183926. "SELECT name, rootpage, sql IS NULL OR substr(8, 6)=='UNIQUE' "
  183927. " FROM main.sqlite_master "
  183928. " WHERE type='index' AND tbl_name = ?"
  183929. );
  183930. }
  183931. pIter->bCleanup = 1;
  183932. p->rc = rc;
  183933. return rbuObjIterNext(p, pIter);
  183934. }
  183935. /*
  183936. ** This is a wrapper around "sqlite3_mprintf(zFmt, ...)". If an OOM occurs,
  183937. ** an error code is stored in the RBU handle passed as the first argument.
  183938. **
  183939. ** If an error has already occurred (p->rc is already set to something other
  183940. ** than SQLITE_OK), then this function returns NULL without modifying the
  183941. ** stored error code. In this case it still calls sqlite3_free() on any
  183942. ** printf() parameters associated with %z conversions.
  183943. */
  183944. static char *rbuMPrintf(sqlite3rbu *p, const char *zFmt, ...){
  183945. char *zSql = 0;
  183946. va_list ap;
  183947. va_start(ap, zFmt);
  183948. zSql = sqlite3_vmprintf(zFmt, ap);
  183949. if( p->rc==SQLITE_OK ){
  183950. if( zSql==0 ) p->rc = SQLITE_NOMEM;
  183951. }else{
  183952. sqlite3_free(zSql);
  183953. zSql = 0;
  183954. }
  183955. va_end(ap);
  183956. return zSql;
  183957. }
  183958. /*
  183959. ** Argument zFmt is a sqlite3_mprintf() style format string. The trailing
  183960. ** arguments are the usual subsitution values. This function performs
  183961. ** the printf() style substitutions and executes the result as an SQL
  183962. ** statement on the RBU handles database.
  183963. **
  183964. ** If an error occurs, an error code and error message is stored in the
  183965. ** RBU handle. If an error has already occurred when this function is
  183966. ** called, it is a no-op.
  183967. */
  183968. static int rbuMPrintfExec(sqlite3rbu *p, sqlite3 *db, const char *zFmt, ...){
  183969. va_list ap;
  183970. char *zSql;
  183971. va_start(ap, zFmt);
  183972. zSql = sqlite3_vmprintf(zFmt, ap);
  183973. if( p->rc==SQLITE_OK ){
  183974. if( zSql==0 ){
  183975. p->rc = SQLITE_NOMEM;
  183976. }else{
  183977. p->rc = sqlite3_exec(db, zSql, 0, 0, &p->zErrmsg);
  183978. }
  183979. }
  183980. sqlite3_free(zSql);
  183981. va_end(ap);
  183982. return p->rc;
  183983. }
  183984. /*
  183985. ** Attempt to allocate and return a pointer to a zeroed block of nByte
  183986. ** bytes.
  183987. **
  183988. ** If an error (i.e. an OOM condition) occurs, return NULL and leave an
  183989. ** error code in the rbu handle passed as the first argument. Or, if an
  183990. ** error has already occurred when this function is called, return NULL
  183991. ** immediately without attempting the allocation or modifying the stored
  183992. ** error code.
  183993. */
  183994. static void *rbuMalloc(sqlite3rbu *p, sqlite3_int64 nByte){
  183995. void *pRet = 0;
  183996. if( p->rc==SQLITE_OK ){
  183997. assert( nByte>0 );
  183998. pRet = sqlite3_malloc64(nByte);
  183999. if( pRet==0 ){
  184000. p->rc = SQLITE_NOMEM;
  184001. }else{
  184002. memset(pRet, 0, nByte);
  184003. }
  184004. }
  184005. return pRet;
  184006. }
  184007. /*
  184008. ** Allocate and zero the pIter->azTblCol[] and abTblPk[] arrays so that
  184009. ** there is room for at least nCol elements. If an OOM occurs, store an
  184010. ** error code in the RBU handle passed as the first argument.
  184011. */
  184012. static void rbuAllocateIterArrays(sqlite3rbu *p, RbuObjIter *pIter, int nCol){
  184013. sqlite3_int64 nByte = (2*sizeof(char*) + sizeof(int) + 3*sizeof(u8)) * nCol;
  184014. char **azNew;
  184015. azNew = (char**)rbuMalloc(p, nByte);
  184016. if( azNew ){
  184017. pIter->azTblCol = azNew;
  184018. pIter->azTblType = &azNew[nCol];
  184019. pIter->aiSrcOrder = (int*)&pIter->azTblType[nCol];
  184020. pIter->abTblPk = (u8*)&pIter->aiSrcOrder[nCol];
  184021. pIter->abNotNull = (u8*)&pIter->abTblPk[nCol];
  184022. pIter->abIndexed = (u8*)&pIter->abNotNull[nCol];
  184023. }
  184024. }
  184025. /*
  184026. ** The first argument must be a nul-terminated string. This function
  184027. ** returns a copy of the string in memory obtained from sqlite3_malloc().
  184028. ** It is the responsibility of the caller to eventually free this memory
  184029. ** using sqlite3_free().
  184030. **
  184031. ** If an OOM condition is encountered when attempting to allocate memory,
  184032. ** output variable (*pRc) is set to SQLITE_NOMEM before returning. Otherwise,
  184033. ** if the allocation succeeds, (*pRc) is left unchanged.
  184034. */
  184035. static char *rbuStrndup(const char *zStr, int *pRc){
  184036. char *zRet = 0;
  184037. if( *pRc==SQLITE_OK ){
  184038. if( zStr ){
  184039. size_t nCopy = strlen(zStr) + 1;
  184040. zRet = (char*)sqlite3_malloc64(nCopy);
  184041. if( zRet ){
  184042. memcpy(zRet, zStr, nCopy);
  184043. }else{
  184044. *pRc = SQLITE_NOMEM;
  184045. }
  184046. }
  184047. }
  184048. return zRet;
  184049. }
  184050. /*
  184051. ** Finalize the statement passed as the second argument.
  184052. **
  184053. ** If the sqlite3_finalize() call indicates that an error occurs, and the
  184054. ** rbu handle error code is not already set, set the error code and error
  184055. ** message accordingly.
  184056. */
  184057. static void rbuFinalize(sqlite3rbu *p, sqlite3_stmt *pStmt){
  184058. sqlite3 *db = sqlite3_db_handle(pStmt);
  184059. int rc = sqlite3_finalize(pStmt);
  184060. if( p->rc==SQLITE_OK && rc!=SQLITE_OK ){
  184061. p->rc = rc;
  184062. p->zErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  184063. }
  184064. }
  184065. /* Determine the type of a table.
  184066. **
  184067. ** peType is of type (int*), a pointer to an output parameter of type
  184068. ** (int). This call sets the output parameter as follows, depending
  184069. ** on the type of the table specified by parameters dbName and zTbl.
  184070. **
  184071. ** RBU_PK_NOTABLE: No such table.
  184072. ** RBU_PK_NONE: Table has an implicit rowid.
  184073. ** RBU_PK_IPK: Table has an explicit IPK column.
  184074. ** RBU_PK_EXTERNAL: Table has an external PK index.
  184075. ** RBU_PK_WITHOUT_ROWID: Table is WITHOUT ROWID.
  184076. ** RBU_PK_VTAB: Table is a virtual table.
  184077. **
  184078. ** Argument *piPk is also of type (int*), and also points to an output
  184079. ** parameter. Unless the table has an external primary key index
  184080. ** (i.e. unless *peType is set to 3), then *piPk is set to zero. Or,
  184081. ** if the table does have an external primary key index, then *piPk
  184082. ** is set to the root page number of the primary key index before
  184083. ** returning.
  184084. **
  184085. ** ALGORITHM:
  184086. **
  184087. ** if( no entry exists in sqlite_master ){
  184088. ** return RBU_PK_NOTABLE
  184089. ** }else if( sql for the entry starts with "CREATE VIRTUAL" ){
  184090. ** return RBU_PK_VTAB
  184091. ** }else if( "PRAGMA index_list()" for the table contains a "pk" index ){
  184092. ** if( the index that is the pk exists in sqlite_master ){
  184093. ** *piPK = rootpage of that index.
  184094. ** return RBU_PK_EXTERNAL
  184095. ** }else{
  184096. ** return RBU_PK_WITHOUT_ROWID
  184097. ** }
  184098. ** }else if( "PRAGMA table_info()" lists one or more "pk" columns ){
  184099. ** return RBU_PK_IPK
  184100. ** }else{
  184101. ** return RBU_PK_NONE
  184102. ** }
  184103. */
  184104. static void rbuTableType(
  184105. sqlite3rbu *p,
  184106. const char *zTab,
  184107. int *peType,
  184108. int *piTnum,
  184109. int *piPk
  184110. ){
  184111. /*
  184112. ** 0) SELECT count(*) FROM sqlite_master where name=%Q AND IsVirtual(%Q)
  184113. ** 1) PRAGMA index_list = ?
  184114. ** 2) SELECT count(*) FROM sqlite_master where name=%Q
  184115. ** 3) PRAGMA table_info = ?
  184116. */
  184117. sqlite3_stmt *aStmt[4] = {0, 0, 0, 0};
  184118. *peType = RBU_PK_NOTABLE;
  184119. *piPk = 0;
  184120. assert( p->rc==SQLITE_OK );
  184121. p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[0], &p->zErrmsg,
  184122. sqlite3_mprintf(
  184123. "SELECT (sql LIKE 'create virtual%%'), rootpage"
  184124. " FROM sqlite_master"
  184125. " WHERE name=%Q", zTab
  184126. ));
  184127. if( p->rc!=SQLITE_OK || sqlite3_step(aStmt[0])!=SQLITE_ROW ){
  184128. /* Either an error, or no such table. */
  184129. goto rbuTableType_end;
  184130. }
  184131. if( sqlite3_column_int(aStmt[0], 0) ){
  184132. *peType = RBU_PK_VTAB; /* virtual table */
  184133. goto rbuTableType_end;
  184134. }
  184135. *piTnum = sqlite3_column_int(aStmt[0], 1);
  184136. p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[1], &p->zErrmsg,
  184137. sqlite3_mprintf("PRAGMA index_list=%Q",zTab)
  184138. );
  184139. if( p->rc ) goto rbuTableType_end;
  184140. while( sqlite3_step(aStmt[1])==SQLITE_ROW ){
  184141. const u8 *zOrig = sqlite3_column_text(aStmt[1], 3);
  184142. const u8 *zIdx = sqlite3_column_text(aStmt[1], 1);
  184143. if( zOrig && zIdx && zOrig[0]=='p' ){
  184144. p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[2], &p->zErrmsg,
  184145. sqlite3_mprintf(
  184146. "SELECT rootpage FROM sqlite_master WHERE name = %Q", zIdx
  184147. ));
  184148. if( p->rc==SQLITE_OK ){
  184149. if( sqlite3_step(aStmt[2])==SQLITE_ROW ){
  184150. *piPk = sqlite3_column_int(aStmt[2], 0);
  184151. *peType = RBU_PK_EXTERNAL;
  184152. }else{
  184153. *peType = RBU_PK_WITHOUT_ROWID;
  184154. }
  184155. }
  184156. goto rbuTableType_end;
  184157. }
  184158. }
  184159. p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[3], &p->zErrmsg,
  184160. sqlite3_mprintf("PRAGMA table_info=%Q",zTab)
  184161. );
  184162. if( p->rc==SQLITE_OK ){
  184163. while( sqlite3_step(aStmt[3])==SQLITE_ROW ){
  184164. if( sqlite3_column_int(aStmt[3],5)>0 ){
  184165. *peType = RBU_PK_IPK; /* explicit IPK column */
  184166. goto rbuTableType_end;
  184167. }
  184168. }
  184169. *peType = RBU_PK_NONE;
  184170. }
  184171. rbuTableType_end: {
  184172. unsigned int i;
  184173. for(i=0; i<sizeof(aStmt)/sizeof(aStmt[0]); i++){
  184174. rbuFinalize(p, aStmt[i]);
  184175. }
  184176. }
  184177. }
  184178. /*
  184179. ** This is a helper function for rbuObjIterCacheTableInfo(). It populates
  184180. ** the pIter->abIndexed[] array.
  184181. */
  184182. static void rbuObjIterCacheIndexedCols(sqlite3rbu *p, RbuObjIter *pIter){
  184183. sqlite3_stmt *pList = 0;
  184184. int bIndex = 0;
  184185. if( p->rc==SQLITE_OK ){
  184186. memcpy(pIter->abIndexed, pIter->abTblPk, sizeof(u8)*pIter->nTblCol);
  184187. p->rc = prepareFreeAndCollectError(p->dbMain, &pList, &p->zErrmsg,
  184188. sqlite3_mprintf("PRAGMA main.index_list = %Q", pIter->zTbl)
  184189. );
  184190. }
  184191. pIter->nIndex = 0;
  184192. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pList) ){
  184193. const char *zIdx = (const char*)sqlite3_column_text(pList, 1);
  184194. int bPartial = sqlite3_column_int(pList, 4);
  184195. sqlite3_stmt *pXInfo = 0;
  184196. if( zIdx==0 ) break;
  184197. if( bPartial ){
  184198. memset(pIter->abIndexed, 0x01, sizeof(u8)*pIter->nTblCol);
  184199. }
  184200. p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
  184201. sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx)
  184202. );
  184203. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
  184204. int iCid = sqlite3_column_int(pXInfo, 1);
  184205. if( iCid>=0 ) pIter->abIndexed[iCid] = 1;
  184206. if( iCid==-2 ){
  184207. memset(pIter->abIndexed, 0x01, sizeof(u8)*pIter->nTblCol);
  184208. }
  184209. }
  184210. rbuFinalize(p, pXInfo);
  184211. bIndex = 1;
  184212. pIter->nIndex++;
  184213. }
  184214. if( pIter->eType==RBU_PK_WITHOUT_ROWID ){
  184215. /* "PRAGMA index_list" includes the main PK b-tree */
  184216. pIter->nIndex--;
  184217. }
  184218. rbuFinalize(p, pList);
  184219. if( bIndex==0 ) pIter->abIndexed = 0;
  184220. }
  184221. /*
  184222. ** If they are not already populated, populate the pIter->azTblCol[],
  184223. ** pIter->abTblPk[], pIter->nTblCol and pIter->bRowid variables according to
  184224. ** the table (not index) that the iterator currently points to.
  184225. **
  184226. ** Return SQLITE_OK if successful, or an SQLite error code otherwise. If
  184227. ** an error does occur, an error code and error message are also left in
  184228. ** the RBU handle.
  184229. */
  184230. static int rbuObjIterCacheTableInfo(sqlite3rbu *p, RbuObjIter *pIter){
  184231. if( pIter->azTblCol==0 ){
  184232. sqlite3_stmt *pStmt = 0;
  184233. int nCol = 0;
  184234. int i; /* for() loop iterator variable */
  184235. int bRbuRowid = 0; /* If input table has column "rbu_rowid" */
  184236. int iOrder = 0;
  184237. int iTnum = 0;
  184238. /* Figure out the type of table this step will deal with. */
  184239. assert( pIter->eType==0 );
  184240. rbuTableType(p, pIter->zTbl, &pIter->eType, &iTnum, &pIter->iPkTnum);
  184241. if( p->rc==SQLITE_OK && pIter->eType==RBU_PK_NOTABLE ){
  184242. p->rc = SQLITE_ERROR;
  184243. p->zErrmsg = sqlite3_mprintf("no such table: %s", pIter->zTbl);
  184244. }
  184245. if( p->rc ) return p->rc;
  184246. if( pIter->zIdx==0 ) pIter->iTnum = iTnum;
  184247. assert( pIter->eType==RBU_PK_NONE || pIter->eType==RBU_PK_IPK
  184248. || pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_WITHOUT_ROWID
  184249. || pIter->eType==RBU_PK_VTAB
  184250. );
  184251. /* Populate the azTblCol[] and nTblCol variables based on the columns
  184252. ** of the input table. Ignore any input table columns that begin with
  184253. ** "rbu_". */
  184254. p->rc = prepareFreeAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
  184255. sqlite3_mprintf("SELECT * FROM '%q'", pIter->zDataTbl)
  184256. );
  184257. if( p->rc==SQLITE_OK ){
  184258. nCol = sqlite3_column_count(pStmt);
  184259. rbuAllocateIterArrays(p, pIter, nCol);
  184260. }
  184261. for(i=0; p->rc==SQLITE_OK && i<nCol; i++){
  184262. const char *zName = (const char*)sqlite3_column_name(pStmt, i);
  184263. if( sqlite3_strnicmp("rbu_", zName, 4) ){
  184264. char *zCopy = rbuStrndup(zName, &p->rc);
  184265. pIter->aiSrcOrder[pIter->nTblCol] = pIter->nTblCol;
  184266. pIter->azTblCol[pIter->nTblCol++] = zCopy;
  184267. }
  184268. else if( 0==sqlite3_stricmp("rbu_rowid", zName) ){
  184269. bRbuRowid = 1;
  184270. }
  184271. }
  184272. sqlite3_finalize(pStmt);
  184273. pStmt = 0;
  184274. if( p->rc==SQLITE_OK
  184275. && rbuIsVacuum(p)==0
  184276. && bRbuRowid!=(pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE)
  184277. ){
  184278. p->rc = SQLITE_ERROR;
  184279. p->zErrmsg = sqlite3_mprintf(
  184280. "table %q %s rbu_rowid column", pIter->zDataTbl,
  184281. (bRbuRowid ? "may not have" : "requires")
  184282. );
  184283. }
  184284. /* Check that all non-HIDDEN columns in the destination table are also
  184285. ** present in the input table. Populate the abTblPk[], azTblType[] and
  184286. ** aiTblOrder[] arrays at the same time. */
  184287. if( p->rc==SQLITE_OK ){
  184288. p->rc = prepareFreeAndCollectError(p->dbMain, &pStmt, &p->zErrmsg,
  184289. sqlite3_mprintf("PRAGMA table_info(%Q)", pIter->zTbl)
  184290. );
  184291. }
  184292. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  184293. const char *zName = (const char*)sqlite3_column_text(pStmt, 1);
  184294. if( zName==0 ) break; /* An OOM - finalize() below returns S_NOMEM */
  184295. for(i=iOrder; i<pIter->nTblCol; i++){
  184296. if( 0==strcmp(zName, pIter->azTblCol[i]) ) break;
  184297. }
  184298. if( i==pIter->nTblCol ){
  184299. p->rc = SQLITE_ERROR;
  184300. p->zErrmsg = sqlite3_mprintf("column missing from %q: %s",
  184301. pIter->zDataTbl, zName
  184302. );
  184303. }else{
  184304. int iPk = sqlite3_column_int(pStmt, 5);
  184305. int bNotNull = sqlite3_column_int(pStmt, 3);
  184306. const char *zType = (const char*)sqlite3_column_text(pStmt, 2);
  184307. if( i!=iOrder ){
  184308. SWAP(int, pIter->aiSrcOrder[i], pIter->aiSrcOrder[iOrder]);
  184309. SWAP(char*, pIter->azTblCol[i], pIter->azTblCol[iOrder]);
  184310. }
  184311. pIter->azTblType[iOrder] = rbuStrndup(zType, &p->rc);
  184312. assert( iPk>=0 );
  184313. pIter->abTblPk[iOrder] = (u8)iPk;
  184314. pIter->abNotNull[iOrder] = (u8)bNotNull || (iPk!=0);
  184315. iOrder++;
  184316. }
  184317. }
  184318. rbuFinalize(p, pStmt);
  184319. rbuObjIterCacheIndexedCols(p, pIter);
  184320. assert( pIter->eType!=RBU_PK_VTAB || pIter->abIndexed==0 );
  184321. assert( pIter->eType!=RBU_PK_VTAB || pIter->nIndex==0 );
  184322. }
  184323. return p->rc;
  184324. }
  184325. /*
  184326. ** This function constructs and returns a pointer to a nul-terminated
  184327. ** string containing some SQL clause or list based on one or more of the
  184328. ** column names currently stored in the pIter->azTblCol[] array.
  184329. */
  184330. static char *rbuObjIterGetCollist(
  184331. sqlite3rbu *p, /* RBU object */
  184332. RbuObjIter *pIter /* Object iterator for column names */
  184333. ){
  184334. char *zList = 0;
  184335. const char *zSep = "";
  184336. int i;
  184337. for(i=0; i<pIter->nTblCol; i++){
  184338. const char *z = pIter->azTblCol[i];
  184339. zList = rbuMPrintf(p, "%z%s\"%w\"", zList, zSep, z);
  184340. zSep = ", ";
  184341. }
  184342. return zList;
  184343. }
  184344. /*
  184345. ** Return a comma separated list of the quoted PRIMARY KEY column names,
  184346. ** in order, for the current table. Before each column name, add the text
  184347. ** zPre. After each column name, add the zPost text. Use zSeparator as
  184348. ** the separator text (usually ", ").
  184349. */
  184350. static char *rbuObjIterGetPkList(
  184351. sqlite3rbu *p, /* RBU object */
  184352. RbuObjIter *pIter, /* Object iterator for column names */
  184353. const char *zPre, /* Before each quoted column name */
  184354. const char *zSeparator, /* Separator to use between columns */
  184355. const char *zPost /* After each quoted column name */
  184356. ){
  184357. int iPk = 1;
  184358. char *zRet = 0;
  184359. const char *zSep = "";
  184360. while( 1 ){
  184361. int i;
  184362. for(i=0; i<pIter->nTblCol; i++){
  184363. if( (int)pIter->abTblPk[i]==iPk ){
  184364. const char *zCol = pIter->azTblCol[i];
  184365. zRet = rbuMPrintf(p, "%z%s%s\"%w\"%s", zRet, zSep, zPre, zCol, zPost);
  184366. zSep = zSeparator;
  184367. break;
  184368. }
  184369. }
  184370. if( i==pIter->nTblCol ) break;
  184371. iPk++;
  184372. }
  184373. return zRet;
  184374. }
  184375. /*
  184376. ** This function is called as part of restarting an RBU vacuum within
  184377. ** stage 1 of the process (while the *-oal file is being built) while
  184378. ** updating a table (not an index). The table may be a rowid table or
  184379. ** a WITHOUT ROWID table. It queries the target database to find the
  184380. ** largest key that has already been written to the target table and
  184381. ** constructs a WHERE clause that can be used to extract the remaining
  184382. ** rows from the source table. For a rowid table, the WHERE clause
  184383. ** is of the form:
  184384. **
  184385. ** "WHERE _rowid_ > ?"
  184386. **
  184387. ** and for WITHOUT ROWID tables:
  184388. **
  184389. ** "WHERE (key1, key2) > (?, ?)"
  184390. **
  184391. ** Instead of "?" placeholders, the actual WHERE clauses created by
  184392. ** this function contain literal SQL values.
  184393. */
  184394. static char *rbuVacuumTableStart(
  184395. sqlite3rbu *p, /* RBU handle */
  184396. RbuObjIter *pIter, /* RBU iterator object */
  184397. int bRowid, /* True for a rowid table */
  184398. const char *zWrite /* Target table name prefix */
  184399. ){
  184400. sqlite3_stmt *pMax = 0;
  184401. char *zRet = 0;
  184402. if( bRowid ){
  184403. p->rc = prepareFreeAndCollectError(p->dbMain, &pMax, &p->zErrmsg,
  184404. sqlite3_mprintf(
  184405. "SELECT max(_rowid_) FROM \"%s%w\"", zWrite, pIter->zTbl
  184406. )
  184407. );
  184408. if( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pMax) ){
  184409. sqlite3_int64 iMax = sqlite3_column_int64(pMax, 0);
  184410. zRet = rbuMPrintf(p, " WHERE _rowid_ > %lld ", iMax);
  184411. }
  184412. rbuFinalize(p, pMax);
  184413. }else{
  184414. char *zOrder = rbuObjIterGetPkList(p, pIter, "", ", ", " DESC");
  184415. char *zSelect = rbuObjIterGetPkList(p, pIter, "quote(", "||','||", ")");
  184416. char *zList = rbuObjIterGetPkList(p, pIter, "", ", ", "");
  184417. if( p->rc==SQLITE_OK ){
  184418. p->rc = prepareFreeAndCollectError(p->dbMain, &pMax, &p->zErrmsg,
  184419. sqlite3_mprintf(
  184420. "SELECT %s FROM \"%s%w\" ORDER BY %s LIMIT 1",
  184421. zSelect, zWrite, pIter->zTbl, zOrder
  184422. )
  184423. );
  184424. if( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pMax) ){
  184425. const char *zVal = (const char*)sqlite3_column_text(pMax, 0);
  184426. zRet = rbuMPrintf(p, " WHERE (%s) > (%s) ", zList, zVal);
  184427. }
  184428. rbuFinalize(p, pMax);
  184429. }
  184430. sqlite3_free(zOrder);
  184431. sqlite3_free(zSelect);
  184432. sqlite3_free(zList);
  184433. }
  184434. return zRet;
  184435. }
  184436. /*
  184437. ** This function is called as part of restating an RBU vacuum when the
  184438. ** current operation is writing content to an index. If possible, it
  184439. ** queries the target index b-tree for the largest key already written to
  184440. ** it, then composes and returns an expression that can be used in a WHERE
  184441. ** clause to select the remaining required rows from the source table.
  184442. ** It is only possible to return such an expression if:
  184443. **
  184444. ** * The index contains no DESC columns, and
  184445. ** * The last key written to the index before the operation was
  184446. ** suspended does not contain any NULL values.
  184447. **
  184448. ** The expression is of the form:
  184449. **
  184450. ** (index-field1, index-field2, ...) > (?, ?, ...)
  184451. **
  184452. ** except that the "?" placeholders are replaced with literal values.
  184453. **
  184454. ** If the expression cannot be created, NULL is returned. In this case,
  184455. ** the caller has to use an OFFSET clause to extract only the required
  184456. ** rows from the sourct table, just as it does for an RBU update operation.
  184457. */
  184458. char *rbuVacuumIndexStart(
  184459. sqlite3rbu *p, /* RBU handle */
  184460. RbuObjIter *pIter /* RBU iterator object */
  184461. ){
  184462. char *zOrder = 0;
  184463. char *zLhs = 0;
  184464. char *zSelect = 0;
  184465. char *zVector = 0;
  184466. char *zRet = 0;
  184467. int bFailed = 0;
  184468. const char *zSep = "";
  184469. int iCol = 0;
  184470. sqlite3_stmt *pXInfo = 0;
  184471. p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
  184472. sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", pIter->zIdx)
  184473. );
  184474. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
  184475. int iCid = sqlite3_column_int(pXInfo, 1);
  184476. const char *zCollate = (const char*)sqlite3_column_text(pXInfo, 4);
  184477. const char *zCol;
  184478. if( sqlite3_column_int(pXInfo, 3) ){
  184479. bFailed = 1;
  184480. break;
  184481. }
  184482. if( iCid<0 ){
  184483. if( pIter->eType==RBU_PK_IPK ){
  184484. int i;
  184485. for(i=0; pIter->abTblPk[i]==0; i++);
  184486. assert( i<pIter->nTblCol );
  184487. zCol = pIter->azTblCol[i];
  184488. }else{
  184489. zCol = "_rowid_";
  184490. }
  184491. }else{
  184492. zCol = pIter->azTblCol[iCid];
  184493. }
  184494. zLhs = rbuMPrintf(p, "%z%s \"%w\" COLLATE %Q",
  184495. zLhs, zSep, zCol, zCollate
  184496. );
  184497. zOrder = rbuMPrintf(p, "%z%s \"rbu_imp_%d%w\" COLLATE %Q DESC",
  184498. zOrder, zSep, iCol, zCol, zCollate
  184499. );
  184500. zSelect = rbuMPrintf(p, "%z%s quote(\"rbu_imp_%d%w\")",
  184501. zSelect, zSep, iCol, zCol
  184502. );
  184503. zSep = ", ";
  184504. iCol++;
  184505. }
  184506. rbuFinalize(p, pXInfo);
  184507. if( bFailed ) goto index_start_out;
  184508. if( p->rc==SQLITE_OK ){
  184509. sqlite3_stmt *pSel = 0;
  184510. p->rc = prepareFreeAndCollectError(p->dbMain, &pSel, &p->zErrmsg,
  184511. sqlite3_mprintf("SELECT %s FROM \"rbu_imp_%w\" ORDER BY %s LIMIT 1",
  184512. zSelect, pIter->zTbl, zOrder
  184513. )
  184514. );
  184515. if( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSel) ){
  184516. zSep = "";
  184517. for(iCol=0; iCol<pIter->nCol; iCol++){
  184518. const char *zQuoted = (const char*)sqlite3_column_text(pSel, iCol);
  184519. if( zQuoted[0]=='N' ){
  184520. bFailed = 1;
  184521. break;
  184522. }
  184523. zVector = rbuMPrintf(p, "%z%s%s", zVector, zSep, zQuoted);
  184524. zSep = ", ";
  184525. }
  184526. if( !bFailed ){
  184527. zRet = rbuMPrintf(p, "(%s) > (%s)", zLhs, zVector);
  184528. }
  184529. }
  184530. rbuFinalize(p, pSel);
  184531. }
  184532. index_start_out:
  184533. sqlite3_free(zOrder);
  184534. sqlite3_free(zSelect);
  184535. sqlite3_free(zVector);
  184536. sqlite3_free(zLhs);
  184537. return zRet;
  184538. }
  184539. /*
  184540. ** This function is used to create a SELECT list (the list of SQL
  184541. ** expressions that follows a SELECT keyword) for a SELECT statement
  184542. ** used to read from an data_xxx or rbu_tmp_xxx table while updating the
  184543. ** index object currently indicated by the iterator object passed as the
  184544. ** second argument. A "PRAGMA index_xinfo = <idxname>" statement is used
  184545. ** to obtain the required information.
  184546. **
  184547. ** If the index is of the following form:
  184548. **
  184549. ** CREATE INDEX i1 ON t1(c, b COLLATE nocase);
  184550. **
  184551. ** and "t1" is a table with an explicit INTEGER PRIMARY KEY column
  184552. ** "ipk", the returned string is:
  184553. **
  184554. ** "`c` COLLATE 'BINARY', `b` COLLATE 'NOCASE', `ipk` COLLATE 'BINARY'"
  184555. **
  184556. ** As well as the returned string, three other malloc'd strings are
  184557. ** returned via output parameters. As follows:
  184558. **
  184559. ** pzImposterCols: ...
  184560. ** pzImposterPk: ...
  184561. ** pzWhere: ...
  184562. */
  184563. static char *rbuObjIterGetIndexCols(
  184564. sqlite3rbu *p, /* RBU object */
  184565. RbuObjIter *pIter, /* Object iterator for column names */
  184566. char **pzImposterCols, /* OUT: Columns for imposter table */
  184567. char **pzImposterPk, /* OUT: Imposter PK clause */
  184568. char **pzWhere, /* OUT: WHERE clause */
  184569. int *pnBind /* OUT: Trbul number of columns */
  184570. ){
  184571. int rc = p->rc; /* Error code */
  184572. int rc2; /* sqlite3_finalize() return code */
  184573. char *zRet = 0; /* String to return */
  184574. char *zImpCols = 0; /* String to return via *pzImposterCols */
  184575. char *zImpPK = 0; /* String to return via *pzImposterPK */
  184576. char *zWhere = 0; /* String to return via *pzWhere */
  184577. int nBind = 0; /* Value to return via *pnBind */
  184578. const char *zCom = ""; /* Set to ", " later on */
  184579. const char *zAnd = ""; /* Set to " AND " later on */
  184580. sqlite3_stmt *pXInfo = 0; /* PRAGMA index_xinfo = ? */
  184581. if( rc==SQLITE_OK ){
  184582. assert( p->zErrmsg==0 );
  184583. rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
  184584. sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", pIter->zIdx)
  184585. );
  184586. }
  184587. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
  184588. int iCid = sqlite3_column_int(pXInfo, 1);
  184589. int bDesc = sqlite3_column_int(pXInfo, 3);
  184590. const char *zCollate = (const char*)sqlite3_column_text(pXInfo, 4);
  184591. const char *zCol = 0;
  184592. const char *zType;
  184593. if( iCid==-2 ){
  184594. int iSeq = sqlite3_column_int(pXInfo, 0);
  184595. zRet = sqlite3_mprintf("%z%s(%.*s) COLLATE %Q", zRet, zCom,
  184596. pIter->aIdxCol[iSeq].nSpan, pIter->aIdxCol[iSeq].zSpan, zCollate
  184597. );
  184598. zType = "";
  184599. }else {
  184600. if( iCid<0 ){
  184601. /* An integer primary key. If the table has an explicit IPK, use
  184602. ** its name. Otherwise, use "rbu_rowid". */
  184603. if( pIter->eType==RBU_PK_IPK ){
  184604. int i;
  184605. for(i=0; pIter->abTblPk[i]==0; i++);
  184606. assert( i<pIter->nTblCol );
  184607. zCol = pIter->azTblCol[i];
  184608. }else if( rbuIsVacuum(p) ){
  184609. zCol = "_rowid_";
  184610. }else{
  184611. zCol = "rbu_rowid";
  184612. }
  184613. zType = "INTEGER";
  184614. }else{
  184615. zCol = pIter->azTblCol[iCid];
  184616. zType = pIter->azTblType[iCid];
  184617. }
  184618. zRet = sqlite3_mprintf("%z%s\"%w\" COLLATE %Q", zRet, zCom,zCol,zCollate);
  184619. }
  184620. if( pIter->bUnique==0 || sqlite3_column_int(pXInfo, 5) ){
  184621. const char *zOrder = (bDesc ? " DESC" : "");
  184622. zImpPK = sqlite3_mprintf("%z%s\"rbu_imp_%d%w\"%s",
  184623. zImpPK, zCom, nBind, zCol, zOrder
  184624. );
  184625. }
  184626. zImpCols = sqlite3_mprintf("%z%s\"rbu_imp_%d%w\" %s COLLATE %Q",
  184627. zImpCols, zCom, nBind, zCol, zType, zCollate
  184628. );
  184629. zWhere = sqlite3_mprintf(
  184630. "%z%s\"rbu_imp_%d%w\" IS ?", zWhere, zAnd, nBind, zCol
  184631. );
  184632. if( zRet==0 || zImpPK==0 || zImpCols==0 || zWhere==0 ) rc = SQLITE_NOMEM;
  184633. zCom = ", ";
  184634. zAnd = " AND ";
  184635. nBind++;
  184636. }
  184637. rc2 = sqlite3_finalize(pXInfo);
  184638. if( rc==SQLITE_OK ) rc = rc2;
  184639. if( rc!=SQLITE_OK ){
  184640. sqlite3_free(zRet);
  184641. sqlite3_free(zImpCols);
  184642. sqlite3_free(zImpPK);
  184643. sqlite3_free(zWhere);
  184644. zRet = 0;
  184645. zImpCols = 0;
  184646. zImpPK = 0;
  184647. zWhere = 0;
  184648. p->rc = rc;
  184649. }
  184650. *pzImposterCols = zImpCols;
  184651. *pzImposterPk = zImpPK;
  184652. *pzWhere = zWhere;
  184653. *pnBind = nBind;
  184654. return zRet;
  184655. }
  184656. /*
  184657. ** Assuming the current table columns are "a", "b" and "c", and the zObj
  184658. ** paramter is passed "old", return a string of the form:
  184659. **
  184660. ** "old.a, old.b, old.b"
  184661. **
  184662. ** With the column names escaped.
  184663. **
  184664. ** For tables with implicit rowids - RBU_PK_EXTERNAL and RBU_PK_NONE, append
  184665. ** the text ", old._rowid_" to the returned value.
  184666. */
  184667. static char *rbuObjIterGetOldlist(
  184668. sqlite3rbu *p,
  184669. RbuObjIter *pIter,
  184670. const char *zObj
  184671. ){
  184672. char *zList = 0;
  184673. if( p->rc==SQLITE_OK && pIter->abIndexed ){
  184674. const char *zS = "";
  184675. int i;
  184676. for(i=0; i<pIter->nTblCol; i++){
  184677. if( pIter->abIndexed[i] ){
  184678. const char *zCol = pIter->azTblCol[i];
  184679. zList = sqlite3_mprintf("%z%s%s.\"%w\"", zList, zS, zObj, zCol);
  184680. }else{
  184681. zList = sqlite3_mprintf("%z%sNULL", zList, zS);
  184682. }
  184683. zS = ", ";
  184684. if( zList==0 ){
  184685. p->rc = SQLITE_NOMEM;
  184686. break;
  184687. }
  184688. }
  184689. /* For a table with implicit rowids, append "old._rowid_" to the list. */
  184690. if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
  184691. zList = rbuMPrintf(p, "%z, %s._rowid_", zList, zObj);
  184692. }
  184693. }
  184694. return zList;
  184695. }
  184696. /*
  184697. ** Return an expression that can be used in a WHERE clause to match the
  184698. ** primary key of the current table. For example, if the table is:
  184699. **
  184700. ** CREATE TABLE t1(a, b, c, PRIMARY KEY(b, c));
  184701. **
  184702. ** Return the string:
  184703. **
  184704. ** "b = ?1 AND c = ?2"
  184705. */
  184706. static char *rbuObjIterGetWhere(
  184707. sqlite3rbu *p,
  184708. RbuObjIter *pIter
  184709. ){
  184710. char *zList = 0;
  184711. if( pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE ){
  184712. zList = rbuMPrintf(p, "_rowid_ = ?%d", pIter->nTblCol+1);
  184713. }else if( pIter->eType==RBU_PK_EXTERNAL ){
  184714. const char *zSep = "";
  184715. int i;
  184716. for(i=0; i<pIter->nTblCol; i++){
  184717. if( pIter->abTblPk[i] ){
  184718. zList = rbuMPrintf(p, "%z%sc%d=?%d", zList, zSep, i, i+1);
  184719. zSep = " AND ";
  184720. }
  184721. }
  184722. zList = rbuMPrintf(p,
  184723. "_rowid_ = (SELECT id FROM rbu_imposter2 WHERE %z)", zList
  184724. );
  184725. }else{
  184726. const char *zSep = "";
  184727. int i;
  184728. for(i=0; i<pIter->nTblCol; i++){
  184729. if( pIter->abTblPk[i] ){
  184730. const char *zCol = pIter->azTblCol[i];
  184731. zList = rbuMPrintf(p, "%z%s\"%w\"=?%d", zList, zSep, zCol, i+1);
  184732. zSep = " AND ";
  184733. }
  184734. }
  184735. }
  184736. return zList;
  184737. }
  184738. /*
  184739. ** The SELECT statement iterating through the keys for the current object
  184740. ** (p->objiter.pSelect) currently points to a valid row. However, there
  184741. ** is something wrong with the rbu_control value in the rbu_control value
  184742. ** stored in the (p->nCol+1)'th column. Set the error code and error message
  184743. ** of the RBU handle to something reflecting this.
  184744. */
  184745. static void rbuBadControlError(sqlite3rbu *p){
  184746. p->rc = SQLITE_ERROR;
  184747. p->zErrmsg = sqlite3_mprintf("invalid rbu_control value");
  184748. }
  184749. /*
  184750. ** Return a nul-terminated string containing the comma separated list of
  184751. ** assignments that should be included following the "SET" keyword of
  184752. ** an UPDATE statement used to update the table object that the iterator
  184753. ** passed as the second argument currently points to if the rbu_control
  184754. ** column of the data_xxx table entry is set to zMask.
  184755. **
  184756. ** The memory for the returned string is obtained from sqlite3_malloc().
  184757. ** It is the responsibility of the caller to eventually free it using
  184758. ** sqlite3_free().
  184759. **
  184760. ** If an OOM error is encountered when allocating space for the new
  184761. ** string, an error code is left in the rbu handle passed as the first
  184762. ** argument and NULL is returned. Or, if an error has already occurred
  184763. ** when this function is called, NULL is returned immediately, without
  184764. ** attempting the allocation or modifying the stored error code.
  184765. */
  184766. static char *rbuObjIterGetSetlist(
  184767. sqlite3rbu *p,
  184768. RbuObjIter *pIter,
  184769. const char *zMask
  184770. ){
  184771. char *zList = 0;
  184772. if( p->rc==SQLITE_OK ){
  184773. int i;
  184774. if( (int)strlen(zMask)!=pIter->nTblCol ){
  184775. rbuBadControlError(p);
  184776. }else{
  184777. const char *zSep = "";
  184778. for(i=0; i<pIter->nTblCol; i++){
  184779. char c = zMask[pIter->aiSrcOrder[i]];
  184780. if( c=='x' ){
  184781. zList = rbuMPrintf(p, "%z%s\"%w\"=?%d",
  184782. zList, zSep, pIter->azTblCol[i], i+1
  184783. );
  184784. zSep = ", ";
  184785. }
  184786. else if( c=='d' ){
  184787. zList = rbuMPrintf(p, "%z%s\"%w\"=rbu_delta(\"%w\", ?%d)",
  184788. zList, zSep, pIter->azTblCol[i], pIter->azTblCol[i], i+1
  184789. );
  184790. zSep = ", ";
  184791. }
  184792. else if( c=='f' ){
  184793. zList = rbuMPrintf(p, "%z%s\"%w\"=rbu_fossil_delta(\"%w\", ?%d)",
  184794. zList, zSep, pIter->azTblCol[i], pIter->azTblCol[i], i+1
  184795. );
  184796. zSep = ", ";
  184797. }
  184798. }
  184799. }
  184800. }
  184801. return zList;
  184802. }
  184803. /*
  184804. ** Return a nul-terminated string consisting of nByte comma separated
  184805. ** "?" expressions. For example, if nByte is 3, return a pointer to
  184806. ** a buffer containing the string "?,?,?".
  184807. **
  184808. ** The memory for the returned string is obtained from sqlite3_malloc().
  184809. ** It is the responsibility of the caller to eventually free it using
  184810. ** sqlite3_free().
  184811. **
  184812. ** If an OOM error is encountered when allocating space for the new
  184813. ** string, an error code is left in the rbu handle passed as the first
  184814. ** argument and NULL is returned. Or, if an error has already occurred
  184815. ** when this function is called, NULL is returned immediately, without
  184816. ** attempting the allocation or modifying the stored error code.
  184817. */
  184818. static char *rbuObjIterGetBindlist(sqlite3rbu *p, int nBind){
  184819. char *zRet = 0;
  184820. sqlite3_int64 nByte = 2*(sqlite3_int64)nBind + 1;
  184821. zRet = (char*)rbuMalloc(p, nByte);
  184822. if( zRet ){
  184823. int i;
  184824. for(i=0; i<nBind; i++){
  184825. zRet[i*2] = '?';
  184826. zRet[i*2+1] = (i+1==nBind) ? '\0' : ',';
  184827. }
  184828. }
  184829. return zRet;
  184830. }
  184831. /*
  184832. ** The iterator currently points to a table (not index) of type
  184833. ** RBU_PK_WITHOUT_ROWID. This function creates the PRIMARY KEY
  184834. ** declaration for the corresponding imposter table. For example,
  184835. ** if the iterator points to a table created as:
  184836. **
  184837. ** CREATE TABLE t1(a, b, c, PRIMARY KEY(b, a DESC)) WITHOUT ROWID
  184838. **
  184839. ** this function returns:
  184840. **
  184841. ** PRIMARY KEY("b", "a" DESC)
  184842. */
  184843. static char *rbuWithoutRowidPK(sqlite3rbu *p, RbuObjIter *pIter){
  184844. char *z = 0;
  184845. assert( pIter->zIdx==0 );
  184846. if( p->rc==SQLITE_OK ){
  184847. const char *zSep = "PRIMARY KEY(";
  184848. sqlite3_stmt *pXList = 0; /* PRAGMA index_list = (pIter->zTbl) */
  184849. sqlite3_stmt *pXInfo = 0; /* PRAGMA index_xinfo = <pk-index> */
  184850. p->rc = prepareFreeAndCollectError(p->dbMain, &pXList, &p->zErrmsg,
  184851. sqlite3_mprintf("PRAGMA main.index_list = %Q", pIter->zTbl)
  184852. );
  184853. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXList) ){
  184854. const char *zOrig = (const char*)sqlite3_column_text(pXList,3);
  184855. if( zOrig && strcmp(zOrig, "pk")==0 ){
  184856. const char *zIdx = (const char*)sqlite3_column_text(pXList,1);
  184857. if( zIdx ){
  184858. p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
  184859. sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx)
  184860. );
  184861. }
  184862. break;
  184863. }
  184864. }
  184865. rbuFinalize(p, pXList);
  184866. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
  184867. if( sqlite3_column_int(pXInfo, 5) ){
  184868. /* int iCid = sqlite3_column_int(pXInfo, 0); */
  184869. const char *zCol = (const char*)sqlite3_column_text(pXInfo, 2);
  184870. const char *zDesc = sqlite3_column_int(pXInfo, 3) ? " DESC" : "";
  184871. z = rbuMPrintf(p, "%z%s\"%w\"%s", z, zSep, zCol, zDesc);
  184872. zSep = ", ";
  184873. }
  184874. }
  184875. z = rbuMPrintf(p, "%z)", z);
  184876. rbuFinalize(p, pXInfo);
  184877. }
  184878. return z;
  184879. }
  184880. /*
  184881. ** This function creates the second imposter table used when writing to
  184882. ** a table b-tree where the table has an external primary key. If the
  184883. ** iterator passed as the second argument does not currently point to
  184884. ** a table (not index) with an external primary key, this function is a
  184885. ** no-op.
  184886. **
  184887. ** Assuming the iterator does point to a table with an external PK, this
  184888. ** function creates a WITHOUT ROWID imposter table named "rbu_imposter2"
  184889. ** used to access that PK index. For example, if the target table is
  184890. ** declared as follows:
  184891. **
  184892. ** CREATE TABLE t1(a, b TEXT, c REAL, PRIMARY KEY(b, c));
  184893. **
  184894. ** then the imposter table schema is:
  184895. **
  184896. ** CREATE TABLE rbu_imposter2(c1 TEXT, c2 REAL, id INTEGER) WITHOUT ROWID;
  184897. **
  184898. */
  184899. static void rbuCreateImposterTable2(sqlite3rbu *p, RbuObjIter *pIter){
  184900. if( p->rc==SQLITE_OK && pIter->eType==RBU_PK_EXTERNAL ){
  184901. int tnum = pIter->iPkTnum; /* Root page of PK index */
  184902. sqlite3_stmt *pQuery = 0; /* SELECT name ... WHERE rootpage = $tnum */
  184903. const char *zIdx = 0; /* Name of PK index */
  184904. sqlite3_stmt *pXInfo = 0; /* PRAGMA main.index_xinfo = $zIdx */
  184905. const char *zComma = "";
  184906. char *zCols = 0; /* Used to build up list of table cols */
  184907. char *zPk = 0; /* Used to build up table PK declaration */
  184908. /* Figure out the name of the primary key index for the current table.
  184909. ** This is needed for the argument to "PRAGMA index_xinfo". Set
  184910. ** zIdx to point to a nul-terminated string containing this name. */
  184911. p->rc = prepareAndCollectError(p->dbMain, &pQuery, &p->zErrmsg,
  184912. "SELECT name FROM sqlite_master WHERE rootpage = ?"
  184913. );
  184914. if( p->rc==SQLITE_OK ){
  184915. sqlite3_bind_int(pQuery, 1, tnum);
  184916. if( SQLITE_ROW==sqlite3_step(pQuery) ){
  184917. zIdx = (const char*)sqlite3_column_text(pQuery, 0);
  184918. }
  184919. }
  184920. if( zIdx ){
  184921. p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
  184922. sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx)
  184923. );
  184924. }
  184925. rbuFinalize(p, pQuery);
  184926. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
  184927. int bKey = sqlite3_column_int(pXInfo, 5);
  184928. if( bKey ){
  184929. int iCid = sqlite3_column_int(pXInfo, 1);
  184930. int bDesc = sqlite3_column_int(pXInfo, 3);
  184931. const char *zCollate = (const char*)sqlite3_column_text(pXInfo, 4);
  184932. zCols = rbuMPrintf(p, "%z%sc%d %s COLLATE %Q", zCols, zComma,
  184933. iCid, pIter->azTblType[iCid], zCollate
  184934. );
  184935. zPk = rbuMPrintf(p, "%z%sc%d%s", zPk, zComma, iCid, bDesc?" DESC":"");
  184936. zComma = ", ";
  184937. }
  184938. }
  184939. zCols = rbuMPrintf(p, "%z, id INTEGER", zCols);
  184940. rbuFinalize(p, pXInfo);
  184941. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1, tnum);
  184942. rbuMPrintfExec(p, p->dbMain,
  184943. "CREATE TABLE rbu_imposter2(%z, PRIMARY KEY(%z)) WITHOUT ROWID",
  184944. zCols, zPk
  184945. );
  184946. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
  184947. }
  184948. }
  184949. /*
  184950. ** If an error has already occurred when this function is called, it
  184951. ** immediately returns zero (without doing any work). Or, if an error
  184952. ** occurs during the execution of this function, it sets the error code
  184953. ** in the sqlite3rbu object indicated by the first argument and returns
  184954. ** zero.
  184955. **
  184956. ** The iterator passed as the second argument is guaranteed to point to
  184957. ** a table (not an index) when this function is called. This function
  184958. ** attempts to create any imposter table required to write to the main
  184959. ** table b-tree of the table before returning. Non-zero is returned if
  184960. ** an imposter table are created, or zero otherwise.
  184961. **
  184962. ** An imposter table is required in all cases except RBU_PK_VTAB. Only
  184963. ** virtual tables are written to directly. The imposter table has the
  184964. ** same schema as the actual target table (less any UNIQUE constraints).
  184965. ** More precisely, the "same schema" means the same columns, types,
  184966. ** collation sequences. For tables that do not have an external PRIMARY
  184967. ** KEY, it also means the same PRIMARY KEY declaration.
  184968. */
  184969. static void rbuCreateImposterTable(sqlite3rbu *p, RbuObjIter *pIter){
  184970. if( p->rc==SQLITE_OK && pIter->eType!=RBU_PK_VTAB ){
  184971. int tnum = pIter->iTnum;
  184972. const char *zComma = "";
  184973. char *zSql = 0;
  184974. int iCol;
  184975. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 1);
  184976. for(iCol=0; p->rc==SQLITE_OK && iCol<pIter->nTblCol; iCol++){
  184977. const char *zPk = "";
  184978. const char *zCol = pIter->azTblCol[iCol];
  184979. const char *zColl = 0;
  184980. p->rc = sqlite3_table_column_metadata(
  184981. p->dbMain, "main", pIter->zTbl, zCol, 0, &zColl, 0, 0, 0
  184982. );
  184983. if( pIter->eType==RBU_PK_IPK && pIter->abTblPk[iCol] ){
  184984. /* If the target table column is an "INTEGER PRIMARY KEY", add
  184985. ** "PRIMARY KEY" to the imposter table column declaration. */
  184986. zPk = "PRIMARY KEY ";
  184987. }
  184988. zSql = rbuMPrintf(p, "%z%s\"%w\" %s %sCOLLATE %Q%s",
  184989. zSql, zComma, zCol, pIter->azTblType[iCol], zPk, zColl,
  184990. (pIter->abNotNull[iCol] ? " NOT NULL" : "")
  184991. );
  184992. zComma = ", ";
  184993. }
  184994. if( pIter->eType==RBU_PK_WITHOUT_ROWID ){
  184995. char *zPk = rbuWithoutRowidPK(p, pIter);
  184996. if( zPk ){
  184997. zSql = rbuMPrintf(p, "%z, %z", zSql, zPk);
  184998. }
  184999. }
  185000. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1, tnum);
  185001. rbuMPrintfExec(p, p->dbMain, "CREATE TABLE \"rbu_imp_%w\"(%z)%s",
  185002. pIter->zTbl, zSql,
  185003. (pIter->eType==RBU_PK_WITHOUT_ROWID ? " WITHOUT ROWID" : "")
  185004. );
  185005. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
  185006. }
  185007. }
  185008. /*
  185009. ** Prepare a statement used to insert rows into the "rbu_tmp_xxx" table.
  185010. ** Specifically a statement of the form:
  185011. **
  185012. ** INSERT INTO rbu_tmp_xxx VALUES(?, ?, ? ...);
  185013. **
  185014. ** The number of bound variables is equal to the number of columns in
  185015. ** the target table, plus one (for the rbu_control column), plus one more
  185016. ** (for the rbu_rowid column) if the target table is an implicit IPK or
  185017. ** virtual table.
  185018. */
  185019. static void rbuObjIterPrepareTmpInsert(
  185020. sqlite3rbu *p,
  185021. RbuObjIter *pIter,
  185022. const char *zCollist,
  185023. const char *zRbuRowid
  185024. ){
  185025. int bRbuRowid = (pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE);
  185026. char *zBind = rbuObjIterGetBindlist(p, pIter->nTblCol + 1 + bRbuRowid);
  185027. if( zBind ){
  185028. assert( pIter->pTmpInsert==0 );
  185029. p->rc = prepareFreeAndCollectError(
  185030. p->dbRbu, &pIter->pTmpInsert, &p->zErrmsg, sqlite3_mprintf(
  185031. "INSERT INTO %s.'rbu_tmp_%q'(rbu_control,%s%s) VALUES(%z)",
  185032. p->zStateDb, pIter->zDataTbl, zCollist, zRbuRowid, zBind
  185033. ));
  185034. }
  185035. }
  185036. static void rbuTmpInsertFunc(
  185037. sqlite3_context *pCtx,
  185038. int nVal,
  185039. sqlite3_value **apVal
  185040. ){
  185041. sqlite3rbu *p = sqlite3_user_data(pCtx);
  185042. int rc = SQLITE_OK;
  185043. int i;
  185044. assert( sqlite3_value_int(apVal[0])!=0
  185045. || p->objiter.eType==RBU_PK_EXTERNAL
  185046. || p->objiter.eType==RBU_PK_NONE
  185047. );
  185048. if( sqlite3_value_int(apVal[0])!=0 ){
  185049. p->nPhaseOneStep += p->objiter.nIndex;
  185050. }
  185051. for(i=0; rc==SQLITE_OK && i<nVal; i++){
  185052. rc = sqlite3_bind_value(p->objiter.pTmpInsert, i+1, apVal[i]);
  185053. }
  185054. if( rc==SQLITE_OK ){
  185055. sqlite3_step(p->objiter.pTmpInsert);
  185056. rc = sqlite3_reset(p->objiter.pTmpInsert);
  185057. }
  185058. if( rc!=SQLITE_OK ){
  185059. sqlite3_result_error_code(pCtx, rc);
  185060. }
  185061. }
  185062. static char *rbuObjIterGetIndexWhere(sqlite3rbu *p, RbuObjIter *pIter){
  185063. sqlite3_stmt *pStmt = 0;
  185064. int rc = p->rc;
  185065. char *zRet = 0;
  185066. assert( pIter->zIdxSql==0 && pIter->nIdxCol==0 && pIter->aIdxCol==0 );
  185067. if( rc==SQLITE_OK ){
  185068. rc = prepareAndCollectError(p->dbMain, &pStmt, &p->zErrmsg,
  185069. "SELECT trim(sql) FROM sqlite_master WHERE type='index' AND name=?"
  185070. );
  185071. }
  185072. if( rc==SQLITE_OK ){
  185073. int rc2;
  185074. rc = sqlite3_bind_text(pStmt, 1, pIter->zIdx, -1, SQLITE_STATIC);
  185075. if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  185076. char *zSql = (char*)sqlite3_column_text(pStmt, 0);
  185077. if( zSql ){
  185078. pIter->zIdxSql = zSql = rbuStrndup(zSql, &rc);
  185079. }
  185080. if( zSql ){
  185081. int nParen = 0; /* Number of open parenthesis */
  185082. int i;
  185083. int iIdxCol = 0;
  185084. int nIdxAlloc = 0;
  185085. for(i=0; zSql[i]; i++){
  185086. char c = zSql[i];
  185087. /* If necessary, grow the pIter->aIdxCol[] array */
  185088. if( iIdxCol==nIdxAlloc ){
  185089. RbuSpan *aIdxCol = (RbuSpan*)sqlite3_realloc(
  185090. pIter->aIdxCol, (nIdxAlloc+16)*sizeof(RbuSpan)
  185091. );
  185092. if( aIdxCol==0 ){
  185093. rc = SQLITE_NOMEM;
  185094. break;
  185095. }
  185096. pIter->aIdxCol = aIdxCol;
  185097. nIdxAlloc += 16;
  185098. }
  185099. if( c=='(' ){
  185100. if( nParen==0 ){
  185101. assert( iIdxCol==0 );
  185102. pIter->aIdxCol[0].zSpan = &zSql[i+1];
  185103. }
  185104. nParen++;
  185105. }
  185106. else if( c==')' ){
  185107. nParen--;
  185108. if( nParen==0 ){
  185109. int nSpan = &zSql[i] - pIter->aIdxCol[iIdxCol].zSpan;
  185110. pIter->aIdxCol[iIdxCol++].nSpan = nSpan;
  185111. i++;
  185112. break;
  185113. }
  185114. }else if( c==',' && nParen==1 ){
  185115. int nSpan = &zSql[i] - pIter->aIdxCol[iIdxCol].zSpan;
  185116. pIter->aIdxCol[iIdxCol++].nSpan = nSpan;
  185117. pIter->aIdxCol[iIdxCol].zSpan = &zSql[i+1];
  185118. }else if( c=='"' || c=='\'' || c=='`' ){
  185119. for(i++; 1; i++){
  185120. if( zSql[i]==c ){
  185121. if( zSql[i+1]!=c ) break;
  185122. i++;
  185123. }
  185124. }
  185125. }else if( c=='[' ){
  185126. for(i++; 1; i++){
  185127. if( zSql[i]==']' ) break;
  185128. }
  185129. }else if( c=='-' && zSql[i+1]=='-' ){
  185130. for(i=i+2; zSql[i] && zSql[i]!='\n'; i++);
  185131. if( zSql[i]=='\0' ) break;
  185132. }else if( c=='/' && zSql[i+1]=='*' ){
  185133. for(i=i+2; zSql[i] && (zSql[i]!='*' || zSql[i+1]!='/'); i++);
  185134. if( zSql[i]=='\0' ) break;
  185135. i++;
  185136. }
  185137. }
  185138. if( zSql[i] ){
  185139. zRet = rbuStrndup(&zSql[i], &rc);
  185140. }
  185141. pIter->nIdxCol = iIdxCol;
  185142. }
  185143. }
  185144. rc2 = sqlite3_finalize(pStmt);
  185145. if( rc==SQLITE_OK ) rc = rc2;
  185146. }
  185147. p->rc = rc;
  185148. return zRet;
  185149. }
  185150. /*
  185151. ** Ensure that the SQLite statement handles required to update the
  185152. ** target database object currently indicated by the iterator passed
  185153. ** as the second argument are available.
  185154. */
  185155. static int rbuObjIterPrepareAll(
  185156. sqlite3rbu *p,
  185157. RbuObjIter *pIter,
  185158. int nOffset /* Add "LIMIT -1 OFFSET $nOffset" to SELECT */
  185159. ){
  185160. assert( pIter->bCleanup==0 );
  185161. if( pIter->pSelect==0 && rbuObjIterCacheTableInfo(p, pIter)==SQLITE_OK ){
  185162. const int tnum = pIter->iTnum;
  185163. char *zCollist = 0; /* List of indexed columns */
  185164. char **pz = &p->zErrmsg;
  185165. const char *zIdx = pIter->zIdx;
  185166. char *zLimit = 0;
  185167. if( nOffset ){
  185168. zLimit = sqlite3_mprintf(" LIMIT -1 OFFSET %d", nOffset);
  185169. if( !zLimit ) p->rc = SQLITE_NOMEM;
  185170. }
  185171. if( zIdx ){
  185172. const char *zTbl = pIter->zTbl;
  185173. char *zImposterCols = 0; /* Columns for imposter table */
  185174. char *zImposterPK = 0; /* Primary key declaration for imposter */
  185175. char *zWhere = 0; /* WHERE clause on PK columns */
  185176. char *zBind = 0;
  185177. char *zPart = 0;
  185178. int nBind = 0;
  185179. assert( pIter->eType!=RBU_PK_VTAB );
  185180. zPart = rbuObjIterGetIndexWhere(p, pIter);
  185181. zCollist = rbuObjIterGetIndexCols(
  185182. p, pIter, &zImposterCols, &zImposterPK, &zWhere, &nBind
  185183. );
  185184. zBind = rbuObjIterGetBindlist(p, nBind);
  185185. /* Create the imposter table used to write to this index. */
  185186. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 1);
  185187. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1,tnum);
  185188. rbuMPrintfExec(p, p->dbMain,
  185189. "CREATE TABLE \"rbu_imp_%w\"( %s, PRIMARY KEY( %s ) ) WITHOUT ROWID",
  185190. zTbl, zImposterCols, zImposterPK
  185191. );
  185192. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
  185193. /* Create the statement to insert index entries */
  185194. pIter->nCol = nBind;
  185195. if( p->rc==SQLITE_OK ){
  185196. p->rc = prepareFreeAndCollectError(
  185197. p->dbMain, &pIter->pInsert, &p->zErrmsg,
  185198. sqlite3_mprintf("INSERT INTO \"rbu_imp_%w\" VALUES(%s)", zTbl, zBind)
  185199. );
  185200. }
  185201. /* And to delete index entries */
  185202. if( rbuIsVacuum(p)==0 && p->rc==SQLITE_OK ){
  185203. p->rc = prepareFreeAndCollectError(
  185204. p->dbMain, &pIter->pDelete, &p->zErrmsg,
  185205. sqlite3_mprintf("DELETE FROM \"rbu_imp_%w\" WHERE %s", zTbl, zWhere)
  185206. );
  185207. }
  185208. /* Create the SELECT statement to read keys in sorted order */
  185209. if( p->rc==SQLITE_OK ){
  185210. char *zSql;
  185211. if( rbuIsVacuum(p) ){
  185212. char *zStart = 0;
  185213. if( nOffset ){
  185214. zStart = rbuVacuumIndexStart(p, pIter);
  185215. if( zStart ){
  185216. sqlite3_free(zLimit);
  185217. zLimit = 0;
  185218. }
  185219. }
  185220. zSql = sqlite3_mprintf(
  185221. "SELECT %s, 0 AS rbu_control FROM '%q' %s %s %s ORDER BY %s%s",
  185222. zCollist,
  185223. pIter->zDataTbl,
  185224. zPart,
  185225. (zStart ? (zPart ? "AND" : "WHERE") : ""), zStart,
  185226. zCollist, zLimit
  185227. );
  185228. sqlite3_free(zStart);
  185229. }else
  185230. if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
  185231. zSql = sqlite3_mprintf(
  185232. "SELECT %s, rbu_control FROM %s.'rbu_tmp_%q' %s ORDER BY %s%s",
  185233. zCollist, p->zStateDb, pIter->zDataTbl,
  185234. zPart, zCollist, zLimit
  185235. );
  185236. }else{
  185237. zSql = sqlite3_mprintf(
  185238. "SELECT %s, rbu_control FROM %s.'rbu_tmp_%q' %s "
  185239. "UNION ALL "
  185240. "SELECT %s, rbu_control FROM '%q' "
  185241. "%s %s typeof(rbu_control)='integer' AND rbu_control!=1 "
  185242. "ORDER BY %s%s",
  185243. zCollist, p->zStateDb, pIter->zDataTbl, zPart,
  185244. zCollist, pIter->zDataTbl,
  185245. zPart,
  185246. (zPart ? "AND" : "WHERE"),
  185247. zCollist, zLimit
  185248. );
  185249. }
  185250. if( p->rc==SQLITE_OK ){
  185251. p->rc = prepareFreeAndCollectError(p->dbRbu,&pIter->pSelect,pz,zSql);
  185252. }else{
  185253. sqlite3_free(zSql);
  185254. }
  185255. }
  185256. sqlite3_free(zImposterCols);
  185257. sqlite3_free(zImposterPK);
  185258. sqlite3_free(zWhere);
  185259. sqlite3_free(zBind);
  185260. sqlite3_free(zPart);
  185261. }else{
  185262. int bRbuRowid = (pIter->eType==RBU_PK_VTAB)
  185263. ||(pIter->eType==RBU_PK_NONE)
  185264. ||(pIter->eType==RBU_PK_EXTERNAL && rbuIsVacuum(p));
  185265. const char *zTbl = pIter->zTbl; /* Table this step applies to */
  185266. const char *zWrite; /* Imposter table name */
  185267. char *zBindings = rbuObjIterGetBindlist(p, pIter->nTblCol + bRbuRowid);
  185268. char *zWhere = rbuObjIterGetWhere(p, pIter);
  185269. char *zOldlist = rbuObjIterGetOldlist(p, pIter, "old");
  185270. char *zNewlist = rbuObjIterGetOldlist(p, pIter, "new");
  185271. zCollist = rbuObjIterGetCollist(p, pIter);
  185272. pIter->nCol = pIter->nTblCol;
  185273. /* Create the imposter table or tables (if required). */
  185274. rbuCreateImposterTable(p, pIter);
  185275. rbuCreateImposterTable2(p, pIter);
  185276. zWrite = (pIter->eType==RBU_PK_VTAB ? "" : "rbu_imp_");
  185277. /* Create the INSERT statement to write to the target PK b-tree */
  185278. if( p->rc==SQLITE_OK ){
  185279. p->rc = prepareFreeAndCollectError(p->dbMain, &pIter->pInsert, pz,
  185280. sqlite3_mprintf(
  185281. "INSERT INTO \"%s%w\"(%s%s) VALUES(%s)",
  185282. zWrite, zTbl, zCollist, (bRbuRowid ? ", _rowid_" : ""), zBindings
  185283. )
  185284. );
  185285. }
  185286. /* Create the DELETE statement to write to the target PK b-tree.
  185287. ** Because it only performs INSERT operations, this is not required for
  185288. ** an rbu vacuum handle. */
  185289. if( rbuIsVacuum(p)==0 && p->rc==SQLITE_OK ){
  185290. p->rc = prepareFreeAndCollectError(p->dbMain, &pIter->pDelete, pz,
  185291. sqlite3_mprintf(
  185292. "DELETE FROM \"%s%w\" WHERE %s", zWrite, zTbl, zWhere
  185293. )
  185294. );
  185295. }
  185296. if( rbuIsVacuum(p)==0 && pIter->abIndexed ){
  185297. const char *zRbuRowid = "";
  185298. if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
  185299. zRbuRowid = ", rbu_rowid";
  185300. }
  185301. /* Create the rbu_tmp_xxx table and the triggers to populate it. */
  185302. rbuMPrintfExec(p, p->dbRbu,
  185303. "CREATE TABLE IF NOT EXISTS %s.'rbu_tmp_%q' AS "
  185304. "SELECT *%s FROM '%q' WHERE 0;"
  185305. , p->zStateDb, pIter->zDataTbl
  185306. , (pIter->eType==RBU_PK_EXTERNAL ? ", 0 AS rbu_rowid" : "")
  185307. , pIter->zDataTbl
  185308. );
  185309. rbuMPrintfExec(p, p->dbMain,
  185310. "CREATE TEMP TRIGGER rbu_delete_tr BEFORE DELETE ON \"%s%w\" "
  185311. "BEGIN "
  185312. " SELECT rbu_tmp_insert(3, %s);"
  185313. "END;"
  185314. "CREATE TEMP TRIGGER rbu_update1_tr BEFORE UPDATE ON \"%s%w\" "
  185315. "BEGIN "
  185316. " SELECT rbu_tmp_insert(3, %s);"
  185317. "END;"
  185318. "CREATE TEMP TRIGGER rbu_update2_tr AFTER UPDATE ON \"%s%w\" "
  185319. "BEGIN "
  185320. " SELECT rbu_tmp_insert(4, %s);"
  185321. "END;",
  185322. zWrite, zTbl, zOldlist,
  185323. zWrite, zTbl, zOldlist,
  185324. zWrite, zTbl, zNewlist
  185325. );
  185326. if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
  185327. rbuMPrintfExec(p, p->dbMain,
  185328. "CREATE TEMP TRIGGER rbu_insert_tr AFTER INSERT ON \"%s%w\" "
  185329. "BEGIN "
  185330. " SELECT rbu_tmp_insert(0, %s);"
  185331. "END;",
  185332. zWrite, zTbl, zNewlist
  185333. );
  185334. }
  185335. rbuObjIterPrepareTmpInsert(p, pIter, zCollist, zRbuRowid);
  185336. }
  185337. /* Create the SELECT statement to read keys from data_xxx */
  185338. if( p->rc==SQLITE_OK ){
  185339. const char *zRbuRowid = "";
  185340. char *zStart = 0;
  185341. char *zOrder = 0;
  185342. if( bRbuRowid ){
  185343. zRbuRowid = rbuIsVacuum(p) ? ",_rowid_ " : ",rbu_rowid";
  185344. }
  185345. if( rbuIsVacuum(p) ){
  185346. if( nOffset ){
  185347. zStart = rbuVacuumTableStart(p, pIter, bRbuRowid, zWrite);
  185348. if( zStart ){
  185349. sqlite3_free(zLimit);
  185350. zLimit = 0;
  185351. }
  185352. }
  185353. if( bRbuRowid ){
  185354. zOrder = rbuMPrintf(p, "_rowid_");
  185355. }else{
  185356. zOrder = rbuObjIterGetPkList(p, pIter, "", ", ", "");
  185357. }
  185358. }
  185359. if( p->rc==SQLITE_OK ){
  185360. p->rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pSelect, pz,
  185361. sqlite3_mprintf(
  185362. "SELECT %s,%s rbu_control%s FROM '%q'%s %s %s %s",
  185363. zCollist,
  185364. (rbuIsVacuum(p) ? "0 AS " : ""),
  185365. zRbuRowid,
  185366. pIter->zDataTbl, (zStart ? zStart : ""),
  185367. (zOrder ? "ORDER BY" : ""), zOrder,
  185368. zLimit
  185369. )
  185370. );
  185371. }
  185372. sqlite3_free(zStart);
  185373. sqlite3_free(zOrder);
  185374. }
  185375. sqlite3_free(zWhere);
  185376. sqlite3_free(zOldlist);
  185377. sqlite3_free(zNewlist);
  185378. sqlite3_free(zBindings);
  185379. }
  185380. sqlite3_free(zCollist);
  185381. sqlite3_free(zLimit);
  185382. }
  185383. return p->rc;
  185384. }
  185385. /*
  185386. ** Set output variable *ppStmt to point to an UPDATE statement that may
  185387. ** be used to update the imposter table for the main table b-tree of the
  185388. ** table object that pIter currently points to, assuming that the
  185389. ** rbu_control column of the data_xyz table contains zMask.
  185390. **
  185391. ** If the zMask string does not specify any columns to update, then this
  185392. ** is not an error. Output variable *ppStmt is set to NULL in this case.
  185393. */
  185394. static int rbuGetUpdateStmt(
  185395. sqlite3rbu *p, /* RBU handle */
  185396. RbuObjIter *pIter, /* Object iterator */
  185397. const char *zMask, /* rbu_control value ('x.x.') */
  185398. sqlite3_stmt **ppStmt /* OUT: UPDATE statement handle */
  185399. ){
  185400. RbuUpdateStmt **pp;
  185401. RbuUpdateStmt *pUp = 0;
  185402. int nUp = 0;
  185403. /* In case an error occurs */
  185404. *ppStmt = 0;
  185405. /* Search for an existing statement. If one is found, shift it to the front
  185406. ** of the LRU queue and return immediately. Otherwise, leave nUp pointing
  185407. ** to the number of statements currently in the cache and pUp to the
  185408. ** last object in the list. */
  185409. for(pp=&pIter->pRbuUpdate; *pp; pp=&((*pp)->pNext)){
  185410. pUp = *pp;
  185411. if( strcmp(pUp->zMask, zMask)==0 ){
  185412. *pp = pUp->pNext;
  185413. pUp->pNext = pIter->pRbuUpdate;
  185414. pIter->pRbuUpdate = pUp;
  185415. *ppStmt = pUp->pUpdate;
  185416. return SQLITE_OK;
  185417. }
  185418. nUp++;
  185419. }
  185420. assert( pUp==0 || pUp->pNext==0 );
  185421. if( nUp>=SQLITE_RBU_UPDATE_CACHESIZE ){
  185422. for(pp=&pIter->pRbuUpdate; *pp!=pUp; pp=&((*pp)->pNext));
  185423. *pp = 0;
  185424. sqlite3_finalize(pUp->pUpdate);
  185425. pUp->pUpdate = 0;
  185426. }else{
  185427. pUp = (RbuUpdateStmt*)rbuMalloc(p, sizeof(RbuUpdateStmt)+pIter->nTblCol+1);
  185428. }
  185429. if( pUp ){
  185430. char *zWhere = rbuObjIterGetWhere(p, pIter);
  185431. char *zSet = rbuObjIterGetSetlist(p, pIter, zMask);
  185432. char *zUpdate = 0;
  185433. pUp->zMask = (char*)&pUp[1];
  185434. memcpy(pUp->zMask, zMask, pIter->nTblCol);
  185435. pUp->pNext = pIter->pRbuUpdate;
  185436. pIter->pRbuUpdate = pUp;
  185437. if( zSet ){
  185438. const char *zPrefix = "";
  185439. if( pIter->eType!=RBU_PK_VTAB ) zPrefix = "rbu_imp_";
  185440. zUpdate = sqlite3_mprintf("UPDATE \"%s%w\" SET %s WHERE %s",
  185441. zPrefix, pIter->zTbl, zSet, zWhere
  185442. );
  185443. p->rc = prepareFreeAndCollectError(
  185444. p->dbMain, &pUp->pUpdate, &p->zErrmsg, zUpdate
  185445. );
  185446. *ppStmt = pUp->pUpdate;
  185447. }
  185448. sqlite3_free(zWhere);
  185449. sqlite3_free(zSet);
  185450. }
  185451. return p->rc;
  185452. }
  185453. static sqlite3 *rbuOpenDbhandle(
  185454. sqlite3rbu *p,
  185455. const char *zName,
  185456. int bUseVfs
  185457. ){
  185458. sqlite3 *db = 0;
  185459. if( p->rc==SQLITE_OK ){
  185460. const int flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_URI;
  185461. p->rc = sqlite3_open_v2(zName, &db, flags, bUseVfs ? p->zVfsName : 0);
  185462. if( p->rc ){
  185463. p->zErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  185464. sqlite3_close(db);
  185465. db = 0;
  185466. }
  185467. }
  185468. return db;
  185469. }
  185470. /*
  185471. ** Free an RbuState object allocated by rbuLoadState().
  185472. */
  185473. static void rbuFreeState(RbuState *p){
  185474. if( p ){
  185475. sqlite3_free(p->zTbl);
  185476. sqlite3_free(p->zDataTbl);
  185477. sqlite3_free(p->zIdx);
  185478. sqlite3_free(p);
  185479. }
  185480. }
  185481. /*
  185482. ** Allocate an RbuState object and load the contents of the rbu_state
  185483. ** table into it. Return a pointer to the new object. It is the
  185484. ** responsibility of the caller to eventually free the object using
  185485. ** sqlite3_free().
  185486. **
  185487. ** If an error occurs, leave an error code and message in the rbu handle
  185488. ** and return NULL.
  185489. */
  185490. static RbuState *rbuLoadState(sqlite3rbu *p){
  185491. RbuState *pRet = 0;
  185492. sqlite3_stmt *pStmt = 0;
  185493. int rc;
  185494. int rc2;
  185495. pRet = (RbuState*)rbuMalloc(p, sizeof(RbuState));
  185496. if( pRet==0 ) return 0;
  185497. rc = prepareFreeAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
  185498. sqlite3_mprintf("SELECT k, v FROM %s.rbu_state", p->zStateDb)
  185499. );
  185500. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  185501. switch( sqlite3_column_int(pStmt, 0) ){
  185502. case RBU_STATE_STAGE:
  185503. pRet->eStage = sqlite3_column_int(pStmt, 1);
  185504. if( pRet->eStage!=RBU_STAGE_OAL
  185505. && pRet->eStage!=RBU_STAGE_MOVE
  185506. && pRet->eStage!=RBU_STAGE_CKPT
  185507. ){
  185508. p->rc = SQLITE_CORRUPT;
  185509. }
  185510. break;
  185511. case RBU_STATE_TBL:
  185512. pRet->zTbl = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc);
  185513. break;
  185514. case RBU_STATE_IDX:
  185515. pRet->zIdx = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc);
  185516. break;
  185517. case RBU_STATE_ROW:
  185518. pRet->nRow = sqlite3_column_int(pStmt, 1);
  185519. break;
  185520. case RBU_STATE_PROGRESS:
  185521. pRet->nProgress = sqlite3_column_int64(pStmt, 1);
  185522. break;
  185523. case RBU_STATE_CKPT:
  185524. pRet->iWalCksum = sqlite3_column_int64(pStmt, 1);
  185525. break;
  185526. case RBU_STATE_COOKIE:
  185527. pRet->iCookie = (u32)sqlite3_column_int64(pStmt, 1);
  185528. break;
  185529. case RBU_STATE_OALSZ:
  185530. pRet->iOalSz = (u32)sqlite3_column_int64(pStmt, 1);
  185531. break;
  185532. case RBU_STATE_PHASEONESTEP:
  185533. pRet->nPhaseOneStep = sqlite3_column_int64(pStmt, 1);
  185534. break;
  185535. case RBU_STATE_DATATBL:
  185536. pRet->zDataTbl = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc);
  185537. break;
  185538. default:
  185539. rc = SQLITE_CORRUPT;
  185540. break;
  185541. }
  185542. }
  185543. rc2 = sqlite3_finalize(pStmt);
  185544. if( rc==SQLITE_OK ) rc = rc2;
  185545. p->rc = rc;
  185546. return pRet;
  185547. }
  185548. /*
  185549. ** Open the database handle and attach the RBU database as "rbu". If an
  185550. ** error occurs, leave an error code and message in the RBU handle.
  185551. */
  185552. static void rbuOpenDatabase(sqlite3rbu *p, int *pbRetry){
  185553. assert( p->rc || (p->dbMain==0 && p->dbRbu==0) );
  185554. assert( p->rc || rbuIsVacuum(p) || p->zTarget!=0 );
  185555. /* Open the RBU database */
  185556. p->dbRbu = rbuOpenDbhandle(p, p->zRbu, 1);
  185557. if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){
  185558. sqlite3_file_control(p->dbRbu, "main", SQLITE_FCNTL_RBUCNT, (void*)p);
  185559. if( p->zState==0 ){
  185560. const char *zFile = sqlite3_db_filename(p->dbRbu, "main");
  185561. p->zState = rbuMPrintf(p, "file://%s-vacuum?modeof=%s", zFile, zFile);
  185562. }
  185563. }
  185564. /* If using separate RBU and state databases, attach the state database to
  185565. ** the RBU db handle now. */
  185566. if( p->zState ){
  185567. rbuMPrintfExec(p, p->dbRbu, "ATTACH %Q AS stat", p->zState);
  185568. memcpy(p->zStateDb, "stat", 4);
  185569. }else{
  185570. memcpy(p->zStateDb, "main", 4);
  185571. }
  185572. #if 0
  185573. if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){
  185574. p->rc = sqlite3_exec(p->dbRbu, "BEGIN", 0, 0, 0);
  185575. }
  185576. #endif
  185577. /* If it has not already been created, create the rbu_state table */
  185578. rbuMPrintfExec(p, p->dbRbu, RBU_CREATE_STATE, p->zStateDb);
  185579. #if 0
  185580. if( rbuIsVacuum(p) ){
  185581. if( p->rc==SQLITE_OK ){
  185582. int rc2;
  185583. int bOk = 0;
  185584. sqlite3_stmt *pCnt = 0;
  185585. p->rc = prepareAndCollectError(p->dbRbu, &pCnt, &p->zErrmsg,
  185586. "SELECT count(*) FROM stat.sqlite_master"
  185587. );
  185588. if( p->rc==SQLITE_OK
  185589. && sqlite3_step(pCnt)==SQLITE_ROW
  185590. && 1==sqlite3_column_int(pCnt, 0)
  185591. ){
  185592. bOk = 1;
  185593. }
  185594. rc2 = sqlite3_finalize(pCnt);
  185595. if( p->rc==SQLITE_OK ) p->rc = rc2;
  185596. if( p->rc==SQLITE_OK && bOk==0 ){
  185597. p->rc = SQLITE_ERROR;
  185598. p->zErrmsg = sqlite3_mprintf("invalid state database");
  185599. }
  185600. if( p->rc==SQLITE_OK ){
  185601. p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, 0);
  185602. }
  185603. }
  185604. }
  185605. #endif
  185606. if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){
  185607. int bOpen = 0;
  185608. int rc;
  185609. p->nRbu = 0;
  185610. p->pRbuFd = 0;
  185611. rc = sqlite3_file_control(p->dbRbu, "main", SQLITE_FCNTL_RBUCNT, (void*)p);
  185612. if( rc!=SQLITE_NOTFOUND ) p->rc = rc;
  185613. if( p->eStage>=RBU_STAGE_MOVE ){
  185614. bOpen = 1;
  185615. }else{
  185616. RbuState *pState = rbuLoadState(p);
  185617. if( pState ){
  185618. bOpen = (pState->eStage>=RBU_STAGE_MOVE);
  185619. rbuFreeState(pState);
  185620. }
  185621. }
  185622. if( bOpen ) p->dbMain = rbuOpenDbhandle(p, p->zRbu, p->nRbu<=1);
  185623. }
  185624. p->eStage = 0;
  185625. if( p->rc==SQLITE_OK && p->dbMain==0 ){
  185626. if( !rbuIsVacuum(p) ){
  185627. p->dbMain = rbuOpenDbhandle(p, p->zTarget, 1);
  185628. }else if( p->pRbuFd->pWalFd ){
  185629. if( pbRetry ){
  185630. p->pRbuFd->bNolock = 0;
  185631. sqlite3_close(p->dbRbu);
  185632. sqlite3_close(p->dbMain);
  185633. p->dbMain = 0;
  185634. p->dbRbu = 0;
  185635. *pbRetry = 1;
  185636. return;
  185637. }
  185638. p->rc = SQLITE_ERROR;
  185639. p->zErrmsg = sqlite3_mprintf("cannot vacuum wal mode database");
  185640. }else{
  185641. char *zTarget;
  185642. char *zExtra = 0;
  185643. if( strlen(p->zRbu)>=5 && 0==memcmp("file:", p->zRbu, 5) ){
  185644. zExtra = &p->zRbu[5];
  185645. while( *zExtra ){
  185646. if( *zExtra++=='?' ) break;
  185647. }
  185648. if( *zExtra=='\0' ) zExtra = 0;
  185649. }
  185650. zTarget = sqlite3_mprintf("file:%s-vactmp?rbu_memory=1%s%s",
  185651. sqlite3_db_filename(p->dbRbu, "main"),
  185652. (zExtra==0 ? "" : "&"), (zExtra==0 ? "" : zExtra)
  185653. );
  185654. if( zTarget==0 ){
  185655. p->rc = SQLITE_NOMEM;
  185656. return;
  185657. }
  185658. p->dbMain = rbuOpenDbhandle(p, zTarget, p->nRbu<=1);
  185659. sqlite3_free(zTarget);
  185660. }
  185661. }
  185662. if( p->rc==SQLITE_OK ){
  185663. p->rc = sqlite3_create_function(p->dbMain,
  185664. "rbu_tmp_insert", -1, SQLITE_UTF8, (void*)p, rbuTmpInsertFunc, 0, 0
  185665. );
  185666. }
  185667. if( p->rc==SQLITE_OK ){
  185668. p->rc = sqlite3_create_function(p->dbMain,
  185669. "rbu_fossil_delta", 2, SQLITE_UTF8, 0, rbuFossilDeltaFunc, 0, 0
  185670. );
  185671. }
  185672. if( p->rc==SQLITE_OK ){
  185673. p->rc = sqlite3_create_function(p->dbRbu,
  185674. "rbu_target_name", -1, SQLITE_UTF8, (void*)p, rbuTargetNameFunc, 0, 0
  185675. );
  185676. }
  185677. if( p->rc==SQLITE_OK ){
  185678. p->rc = sqlite3_file_control(p->dbMain, "main", SQLITE_FCNTL_RBU, (void*)p);
  185679. }
  185680. rbuMPrintfExec(p, p->dbMain, "SELECT * FROM sqlite_master");
  185681. /* Mark the database file just opened as an RBU target database. If
  185682. ** this call returns SQLITE_NOTFOUND, then the RBU vfs is not in use.
  185683. ** This is an error. */
  185684. if( p->rc==SQLITE_OK ){
  185685. p->rc = sqlite3_file_control(p->dbMain, "main", SQLITE_FCNTL_RBU, (void*)p);
  185686. }
  185687. if( p->rc==SQLITE_NOTFOUND ){
  185688. p->rc = SQLITE_ERROR;
  185689. p->zErrmsg = sqlite3_mprintf("rbu vfs not found");
  185690. }
  185691. }
  185692. /*
  185693. ** This routine is a copy of the sqlite3FileSuffix3() routine from the core.
  185694. ** It is a no-op unless SQLITE_ENABLE_8_3_NAMES is defined.
  185695. **
  185696. ** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
  185697. ** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
  185698. ** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
  185699. ** three characters, then shorten the suffix on z[] to be the last three
  185700. ** characters of the original suffix.
  185701. **
  185702. ** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
  185703. ** do the suffix shortening regardless of URI parameter.
  185704. **
  185705. ** Examples:
  185706. **
  185707. ** test.db-journal => test.nal
  185708. ** test.db-wal => test.wal
  185709. ** test.db-shm => test.shm
  185710. ** test.db-mj7f3319fa => test.9fa
  185711. */
  185712. static void rbuFileSuffix3(const char *zBase, char *z){
  185713. #ifdef SQLITE_ENABLE_8_3_NAMES
  185714. #if SQLITE_ENABLE_8_3_NAMES<2
  185715. if( sqlite3_uri_boolean(zBase, "8_3_names", 0) )
  185716. #endif
  185717. {
  185718. int i, sz;
  185719. sz = (int)strlen(z)&0xffffff;
  185720. for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
  185721. if( z[i]=='.' && sz>i+4 ) memmove(&z[i+1], &z[sz-3], 4);
  185722. }
  185723. #endif
  185724. }
  185725. /*
  185726. ** Return the current wal-index header checksum for the target database
  185727. ** as a 64-bit integer.
  185728. **
  185729. ** The checksum is store in the first page of xShmMap memory as an 8-byte
  185730. ** blob starting at byte offset 40.
  185731. */
  185732. static i64 rbuShmChecksum(sqlite3rbu *p){
  185733. i64 iRet = 0;
  185734. if( p->rc==SQLITE_OK ){
  185735. sqlite3_file *pDb = p->pTargetFd->pReal;
  185736. u32 volatile *ptr;
  185737. p->rc = pDb->pMethods->xShmMap(pDb, 0, 32*1024, 0, (void volatile**)&ptr);
  185738. if( p->rc==SQLITE_OK ){
  185739. iRet = ((i64)ptr[10] << 32) + ptr[11];
  185740. }
  185741. }
  185742. return iRet;
  185743. }
  185744. /*
  185745. ** This function is called as part of initializing or reinitializing an
  185746. ** incremental checkpoint.
  185747. **
  185748. ** It populates the sqlite3rbu.aFrame[] array with the set of
  185749. ** (wal frame -> db page) copy operations required to checkpoint the
  185750. ** current wal file, and obtains the set of shm locks required to safely
  185751. ** perform the copy operations directly on the file-system.
  185752. **
  185753. ** If argument pState is not NULL, then the incremental checkpoint is
  185754. ** being resumed. In this case, if the checksum of the wal-index-header
  185755. ** following recovery is not the same as the checksum saved in the RbuState
  185756. ** object, then the rbu handle is set to DONE state. This occurs if some
  185757. ** other client appends a transaction to the wal file in the middle of
  185758. ** an incremental checkpoint.
  185759. */
  185760. static void rbuSetupCheckpoint(sqlite3rbu *p, RbuState *pState){
  185761. /* If pState is NULL, then the wal file may not have been opened and
  185762. ** recovered. Running a read-statement here to ensure that doing so
  185763. ** does not interfere with the "capture" process below. */
  185764. if( pState==0 ){
  185765. p->eStage = 0;
  185766. if( p->rc==SQLITE_OK ){
  185767. p->rc = sqlite3_exec(p->dbMain, "SELECT * FROM sqlite_master", 0, 0, 0);
  185768. }
  185769. }
  185770. /* Assuming no error has occurred, run a "restart" checkpoint with the
  185771. ** sqlite3rbu.eStage variable set to CAPTURE. This turns on the following
  185772. ** special behaviour in the rbu VFS:
  185773. **
  185774. ** * If the exclusive shm WRITER or READ0 lock cannot be obtained,
  185775. ** the checkpoint fails with SQLITE_BUSY (normally SQLite would
  185776. ** proceed with running a passive checkpoint instead of failing).
  185777. **
  185778. ** * Attempts to read from the *-wal file or write to the database file
  185779. ** do not perform any IO. Instead, the frame/page combinations that
  185780. ** would be read/written are recorded in the sqlite3rbu.aFrame[]
  185781. ** array.
  185782. **
  185783. ** * Calls to xShmLock(UNLOCK) to release the exclusive shm WRITER,
  185784. ** READ0 and CHECKPOINT locks taken as part of the checkpoint are
  185785. ** no-ops. These locks will not be released until the connection
  185786. ** is closed.
  185787. **
  185788. ** * Attempting to xSync() the database file causes an SQLITE_INTERNAL
  185789. ** error.
  185790. **
  185791. ** As a result, unless an error (i.e. OOM or SQLITE_BUSY) occurs, the
  185792. ** checkpoint below fails with SQLITE_INTERNAL, and leaves the aFrame[]
  185793. ** array populated with a set of (frame -> page) mappings. Because the
  185794. ** WRITER, CHECKPOINT and READ0 locks are still held, it is safe to copy
  185795. ** data from the wal file into the database file according to the
  185796. ** contents of aFrame[].
  185797. */
  185798. if( p->rc==SQLITE_OK ){
  185799. int rc2;
  185800. p->eStage = RBU_STAGE_CAPTURE;
  185801. rc2 = sqlite3_exec(p->dbMain, "PRAGMA main.wal_checkpoint=restart", 0, 0,0);
  185802. if( rc2!=SQLITE_INTERNAL ) p->rc = rc2;
  185803. }
  185804. if( p->rc==SQLITE_OK && p->nFrame>0 ){
  185805. p->eStage = RBU_STAGE_CKPT;
  185806. p->nStep = (pState ? pState->nRow : 0);
  185807. p->aBuf = rbuMalloc(p, p->pgsz);
  185808. p->iWalCksum = rbuShmChecksum(p);
  185809. }
  185810. if( p->rc==SQLITE_OK ){
  185811. if( p->nFrame==0 || (pState && pState->iWalCksum!=p->iWalCksum) ){
  185812. p->rc = SQLITE_DONE;
  185813. p->eStage = RBU_STAGE_DONE;
  185814. }else{
  185815. int nSectorSize;
  185816. sqlite3_file *pDb = p->pTargetFd->pReal;
  185817. sqlite3_file *pWal = p->pTargetFd->pWalFd->pReal;
  185818. assert( p->nPagePerSector==0 );
  185819. nSectorSize = pDb->pMethods->xSectorSize(pDb);
  185820. if( nSectorSize>p->pgsz ){
  185821. p->nPagePerSector = nSectorSize / p->pgsz;
  185822. }else{
  185823. p->nPagePerSector = 1;
  185824. }
  185825. /* Call xSync() on the wal file. This causes SQLite to sync the
  185826. ** directory in which the target database and the wal file reside, in
  185827. ** case it has not been synced since the rename() call in
  185828. ** rbuMoveOalFile(). */
  185829. p->rc = pWal->pMethods->xSync(pWal, SQLITE_SYNC_NORMAL);
  185830. }
  185831. }
  185832. }
  185833. /*
  185834. ** Called when iAmt bytes are read from offset iOff of the wal file while
  185835. ** the rbu object is in capture mode. Record the frame number of the frame
  185836. ** being read in the aFrame[] array.
  185837. */
  185838. static int rbuCaptureWalRead(sqlite3rbu *pRbu, i64 iOff, int iAmt){
  185839. const u32 mReq = (1<<WAL_LOCK_WRITE)|(1<<WAL_LOCK_CKPT)|(1<<WAL_LOCK_READ0);
  185840. u32 iFrame;
  185841. if( pRbu->mLock!=mReq ){
  185842. pRbu->rc = SQLITE_BUSY;
  185843. return SQLITE_INTERNAL;
  185844. }
  185845. pRbu->pgsz = iAmt;
  185846. if( pRbu->nFrame==pRbu->nFrameAlloc ){
  185847. int nNew = (pRbu->nFrameAlloc ? pRbu->nFrameAlloc : 64) * 2;
  185848. RbuFrame *aNew;
  185849. aNew = (RbuFrame*)sqlite3_realloc64(pRbu->aFrame, nNew * sizeof(RbuFrame));
  185850. if( aNew==0 ) return SQLITE_NOMEM;
  185851. pRbu->aFrame = aNew;
  185852. pRbu->nFrameAlloc = nNew;
  185853. }
  185854. iFrame = (u32)((iOff-32) / (i64)(iAmt+24)) + 1;
  185855. if( pRbu->iMaxFrame<iFrame ) pRbu->iMaxFrame = iFrame;
  185856. pRbu->aFrame[pRbu->nFrame].iWalFrame = iFrame;
  185857. pRbu->aFrame[pRbu->nFrame].iDbPage = 0;
  185858. pRbu->nFrame++;
  185859. return SQLITE_OK;
  185860. }
  185861. /*
  185862. ** Called when a page of data is written to offset iOff of the database
  185863. ** file while the rbu handle is in capture mode. Record the page number
  185864. ** of the page being written in the aFrame[] array.
  185865. */
  185866. static int rbuCaptureDbWrite(sqlite3rbu *pRbu, i64 iOff){
  185867. pRbu->aFrame[pRbu->nFrame-1].iDbPage = (u32)(iOff / pRbu->pgsz) + 1;
  185868. return SQLITE_OK;
  185869. }
  185870. /*
  185871. ** This is called as part of an incremental checkpoint operation. Copy
  185872. ** a single frame of data from the wal file into the database file, as
  185873. ** indicated by the RbuFrame object.
  185874. */
  185875. static void rbuCheckpointFrame(sqlite3rbu *p, RbuFrame *pFrame){
  185876. sqlite3_file *pWal = p->pTargetFd->pWalFd->pReal;
  185877. sqlite3_file *pDb = p->pTargetFd->pReal;
  185878. i64 iOff;
  185879. assert( p->rc==SQLITE_OK );
  185880. iOff = (i64)(pFrame->iWalFrame-1) * (p->pgsz + 24) + 32 + 24;
  185881. p->rc = pWal->pMethods->xRead(pWal, p->aBuf, p->pgsz, iOff);
  185882. if( p->rc ) return;
  185883. iOff = (i64)(pFrame->iDbPage-1) * p->pgsz;
  185884. p->rc = pDb->pMethods->xWrite(pDb, p->aBuf, p->pgsz, iOff);
  185885. }
  185886. /*
  185887. ** Take an EXCLUSIVE lock on the database file.
  185888. */
  185889. static void rbuLockDatabase(sqlite3rbu *p){
  185890. sqlite3_file *pReal = p->pTargetFd->pReal;
  185891. assert( p->rc==SQLITE_OK );
  185892. p->rc = pReal->pMethods->xLock(pReal, SQLITE_LOCK_SHARED);
  185893. if( p->rc==SQLITE_OK ){
  185894. p->rc = pReal->pMethods->xLock(pReal, SQLITE_LOCK_EXCLUSIVE);
  185895. }
  185896. }
  185897. #if defined(_WIN32_WCE)
  185898. static LPWSTR rbuWinUtf8ToUnicode(const char *zFilename){
  185899. int nChar;
  185900. LPWSTR zWideFilename;
  185901. nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
  185902. if( nChar==0 ){
  185903. return 0;
  185904. }
  185905. zWideFilename = sqlite3_malloc64( nChar*sizeof(zWideFilename[0]) );
  185906. if( zWideFilename==0 ){
  185907. return 0;
  185908. }
  185909. memset(zWideFilename, 0, nChar*sizeof(zWideFilename[0]));
  185910. nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename,
  185911. nChar);
  185912. if( nChar==0 ){
  185913. sqlite3_free(zWideFilename);
  185914. zWideFilename = 0;
  185915. }
  185916. return zWideFilename;
  185917. }
  185918. #endif
  185919. /*
  185920. ** The RBU handle is currently in RBU_STAGE_OAL state, with a SHARED lock
  185921. ** on the database file. This proc moves the *-oal file to the *-wal path,
  185922. ** then reopens the database file (this time in vanilla, non-oal, WAL mode).
  185923. ** If an error occurs, leave an error code and error message in the rbu
  185924. ** handle.
  185925. */
  185926. static void rbuMoveOalFile(sqlite3rbu *p){
  185927. const char *zBase = sqlite3_db_filename(p->dbMain, "main");
  185928. const char *zMove = zBase;
  185929. char *zOal;
  185930. char *zWal;
  185931. if( rbuIsVacuum(p) ){
  185932. zMove = sqlite3_db_filename(p->dbRbu, "main");
  185933. }
  185934. zOal = sqlite3_mprintf("%s-oal", zMove);
  185935. zWal = sqlite3_mprintf("%s-wal", zMove);
  185936. assert( p->eStage==RBU_STAGE_MOVE );
  185937. assert( p->rc==SQLITE_OK && p->zErrmsg==0 );
  185938. if( zWal==0 || zOal==0 ){
  185939. p->rc = SQLITE_NOMEM;
  185940. }else{
  185941. /* Move the *-oal file to *-wal. At this point connection p->db is
  185942. ** holding a SHARED lock on the target database file (because it is
  185943. ** in WAL mode). So no other connection may be writing the db.
  185944. **
  185945. ** In order to ensure that there are no database readers, an EXCLUSIVE
  185946. ** lock is obtained here before the *-oal is moved to *-wal.
  185947. */
  185948. rbuLockDatabase(p);
  185949. if( p->rc==SQLITE_OK ){
  185950. rbuFileSuffix3(zBase, zWal);
  185951. rbuFileSuffix3(zBase, zOal);
  185952. /* Re-open the databases. */
  185953. rbuObjIterFinalize(&p->objiter);
  185954. sqlite3_close(p->dbRbu);
  185955. sqlite3_close(p->dbMain);
  185956. p->dbMain = 0;
  185957. p->dbRbu = 0;
  185958. #if defined(_WIN32_WCE)
  185959. {
  185960. LPWSTR zWideOal;
  185961. LPWSTR zWideWal;
  185962. zWideOal = rbuWinUtf8ToUnicode(zOal);
  185963. if( zWideOal ){
  185964. zWideWal = rbuWinUtf8ToUnicode(zWal);
  185965. if( zWideWal ){
  185966. if( MoveFileW(zWideOal, zWideWal) ){
  185967. p->rc = SQLITE_OK;
  185968. }else{
  185969. p->rc = SQLITE_IOERR;
  185970. }
  185971. sqlite3_free(zWideWal);
  185972. }else{
  185973. p->rc = SQLITE_IOERR_NOMEM;
  185974. }
  185975. sqlite3_free(zWideOal);
  185976. }else{
  185977. p->rc = SQLITE_IOERR_NOMEM;
  185978. }
  185979. }
  185980. #else
  185981. p->rc = rename(zOal, zWal) ? SQLITE_IOERR : SQLITE_OK;
  185982. #endif
  185983. if( p->rc==SQLITE_OK ){
  185984. rbuOpenDatabase(p, 0);
  185985. rbuSetupCheckpoint(p, 0);
  185986. }
  185987. }
  185988. }
  185989. sqlite3_free(zWal);
  185990. sqlite3_free(zOal);
  185991. }
  185992. /*
  185993. ** The SELECT statement iterating through the keys for the current object
  185994. ** (p->objiter.pSelect) currently points to a valid row. This function
  185995. ** determines the type of operation requested by this row and returns
  185996. ** one of the following values to indicate the result:
  185997. **
  185998. ** * RBU_INSERT
  185999. ** * RBU_DELETE
  186000. ** * RBU_IDX_DELETE
  186001. ** * RBU_UPDATE
  186002. **
  186003. ** If RBU_UPDATE is returned, then output variable *pzMask is set to
  186004. ** point to the text value indicating the columns to update.
  186005. **
  186006. ** If the rbu_control field contains an invalid value, an error code and
  186007. ** message are left in the RBU handle and zero returned.
  186008. */
  186009. static int rbuStepType(sqlite3rbu *p, const char **pzMask){
  186010. int iCol = p->objiter.nCol; /* Index of rbu_control column */
  186011. int res = 0; /* Return value */
  186012. switch( sqlite3_column_type(p->objiter.pSelect, iCol) ){
  186013. case SQLITE_INTEGER: {
  186014. int iVal = sqlite3_column_int(p->objiter.pSelect, iCol);
  186015. switch( iVal ){
  186016. case 0: res = RBU_INSERT; break;
  186017. case 1: res = RBU_DELETE; break;
  186018. case 2: res = RBU_REPLACE; break;
  186019. case 3: res = RBU_IDX_DELETE; break;
  186020. case 4: res = RBU_IDX_INSERT; break;
  186021. }
  186022. break;
  186023. }
  186024. case SQLITE_TEXT: {
  186025. const unsigned char *z = sqlite3_column_text(p->objiter.pSelect, iCol);
  186026. if( z==0 ){
  186027. p->rc = SQLITE_NOMEM;
  186028. }else{
  186029. *pzMask = (const char*)z;
  186030. }
  186031. res = RBU_UPDATE;
  186032. break;
  186033. }
  186034. default:
  186035. break;
  186036. }
  186037. if( res==0 ){
  186038. rbuBadControlError(p);
  186039. }
  186040. return res;
  186041. }
  186042. #ifdef SQLITE_DEBUG
  186043. /*
  186044. ** Assert that column iCol of statement pStmt is named zName.
  186045. */
  186046. static void assertColumnName(sqlite3_stmt *pStmt, int iCol, const char *zName){
  186047. const char *zCol = sqlite3_column_name(pStmt, iCol);
  186048. assert( 0==sqlite3_stricmp(zName, zCol) );
  186049. }
  186050. #else
  186051. # define assertColumnName(x,y,z)
  186052. #endif
  186053. /*
  186054. ** Argument eType must be one of RBU_INSERT, RBU_DELETE, RBU_IDX_INSERT or
  186055. ** RBU_IDX_DELETE. This function performs the work of a single
  186056. ** sqlite3rbu_step() call for the type of operation specified by eType.
  186057. */
  186058. static void rbuStepOneOp(sqlite3rbu *p, int eType){
  186059. RbuObjIter *pIter = &p->objiter;
  186060. sqlite3_value *pVal;
  186061. sqlite3_stmt *pWriter;
  186062. int i;
  186063. assert( p->rc==SQLITE_OK );
  186064. assert( eType!=RBU_DELETE || pIter->zIdx==0 );
  186065. assert( eType==RBU_DELETE || eType==RBU_IDX_DELETE
  186066. || eType==RBU_INSERT || eType==RBU_IDX_INSERT
  186067. );
  186068. /* If this is a delete, decrement nPhaseOneStep by nIndex. If the DELETE
  186069. ** statement below does actually delete a row, nPhaseOneStep will be
  186070. ** incremented by the same amount when SQL function rbu_tmp_insert()
  186071. ** is invoked by the trigger. */
  186072. if( eType==RBU_DELETE ){
  186073. p->nPhaseOneStep -= p->objiter.nIndex;
  186074. }
  186075. if( eType==RBU_IDX_DELETE || eType==RBU_DELETE ){
  186076. pWriter = pIter->pDelete;
  186077. }else{
  186078. pWriter = pIter->pInsert;
  186079. }
  186080. for(i=0; i<pIter->nCol; i++){
  186081. /* If this is an INSERT into a table b-tree and the table has an
  186082. ** explicit INTEGER PRIMARY KEY, check that this is not an attempt
  186083. ** to write a NULL into the IPK column. That is not permitted. */
  186084. if( eType==RBU_INSERT
  186085. && pIter->zIdx==0 && pIter->eType==RBU_PK_IPK && pIter->abTblPk[i]
  186086. && sqlite3_column_type(pIter->pSelect, i)==SQLITE_NULL
  186087. ){
  186088. p->rc = SQLITE_MISMATCH;
  186089. p->zErrmsg = sqlite3_mprintf("datatype mismatch");
  186090. return;
  186091. }
  186092. if( eType==RBU_DELETE && pIter->abTblPk[i]==0 ){
  186093. continue;
  186094. }
  186095. pVal = sqlite3_column_value(pIter->pSelect, i);
  186096. p->rc = sqlite3_bind_value(pWriter, i+1, pVal);
  186097. if( p->rc ) return;
  186098. }
  186099. if( pIter->zIdx==0 ){
  186100. if( pIter->eType==RBU_PK_VTAB
  186101. || pIter->eType==RBU_PK_NONE
  186102. || (pIter->eType==RBU_PK_EXTERNAL && rbuIsVacuum(p))
  186103. ){
  186104. /* For a virtual table, or a table with no primary key, the
  186105. ** SELECT statement is:
  186106. **
  186107. ** SELECT <cols>, rbu_control, rbu_rowid FROM ....
  186108. **
  186109. ** Hence column_value(pIter->nCol+1).
  186110. */
  186111. assertColumnName(pIter->pSelect, pIter->nCol+1,
  186112. rbuIsVacuum(p) ? "rowid" : "rbu_rowid"
  186113. );
  186114. pVal = sqlite3_column_value(pIter->pSelect, pIter->nCol+1);
  186115. p->rc = sqlite3_bind_value(pWriter, pIter->nCol+1, pVal);
  186116. }
  186117. }
  186118. if( p->rc==SQLITE_OK ){
  186119. sqlite3_step(pWriter);
  186120. p->rc = resetAndCollectError(pWriter, &p->zErrmsg);
  186121. }
  186122. }
  186123. /*
  186124. ** This function does the work for an sqlite3rbu_step() call.
  186125. **
  186126. ** The object-iterator (p->objiter) currently points to a valid object,
  186127. ** and the input cursor (p->objiter.pSelect) currently points to a valid
  186128. ** input row. Perform whatever processing is required and return.
  186129. **
  186130. ** If no error occurs, SQLITE_OK is returned. Otherwise, an error code
  186131. ** and message is left in the RBU handle and a copy of the error code
  186132. ** returned.
  186133. */
  186134. static int rbuStep(sqlite3rbu *p){
  186135. RbuObjIter *pIter = &p->objiter;
  186136. const char *zMask = 0;
  186137. int eType = rbuStepType(p, &zMask);
  186138. if( eType ){
  186139. assert( eType==RBU_INSERT || eType==RBU_DELETE
  186140. || eType==RBU_REPLACE || eType==RBU_IDX_DELETE
  186141. || eType==RBU_IDX_INSERT || eType==RBU_UPDATE
  186142. );
  186143. assert( eType!=RBU_UPDATE || pIter->zIdx==0 );
  186144. if( pIter->zIdx==0 && (eType==RBU_IDX_DELETE || eType==RBU_IDX_INSERT) ){
  186145. rbuBadControlError(p);
  186146. }
  186147. else if( eType==RBU_REPLACE ){
  186148. if( pIter->zIdx==0 ){
  186149. p->nPhaseOneStep += p->objiter.nIndex;
  186150. rbuStepOneOp(p, RBU_DELETE);
  186151. }
  186152. if( p->rc==SQLITE_OK ) rbuStepOneOp(p, RBU_INSERT);
  186153. }
  186154. else if( eType!=RBU_UPDATE ){
  186155. rbuStepOneOp(p, eType);
  186156. }
  186157. else{
  186158. sqlite3_value *pVal;
  186159. sqlite3_stmt *pUpdate = 0;
  186160. assert( eType==RBU_UPDATE );
  186161. p->nPhaseOneStep -= p->objiter.nIndex;
  186162. rbuGetUpdateStmt(p, pIter, zMask, &pUpdate);
  186163. if( pUpdate ){
  186164. int i;
  186165. for(i=0; p->rc==SQLITE_OK && i<pIter->nCol; i++){
  186166. char c = zMask[pIter->aiSrcOrder[i]];
  186167. pVal = sqlite3_column_value(pIter->pSelect, i);
  186168. if( pIter->abTblPk[i] || c!='.' ){
  186169. p->rc = sqlite3_bind_value(pUpdate, i+1, pVal);
  186170. }
  186171. }
  186172. if( p->rc==SQLITE_OK
  186173. && (pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE)
  186174. ){
  186175. /* Bind the rbu_rowid value to column _rowid_ */
  186176. assertColumnName(pIter->pSelect, pIter->nCol+1, "rbu_rowid");
  186177. pVal = sqlite3_column_value(pIter->pSelect, pIter->nCol+1);
  186178. p->rc = sqlite3_bind_value(pUpdate, pIter->nCol+1, pVal);
  186179. }
  186180. if( p->rc==SQLITE_OK ){
  186181. sqlite3_step(pUpdate);
  186182. p->rc = resetAndCollectError(pUpdate, &p->zErrmsg);
  186183. }
  186184. }
  186185. }
  186186. }
  186187. return p->rc;
  186188. }
  186189. /*
  186190. ** Increment the schema cookie of the main database opened by p->dbMain.
  186191. **
  186192. ** Or, if this is an RBU vacuum, set the schema cookie of the main db
  186193. ** opened by p->dbMain to one more than the schema cookie of the main
  186194. ** db opened by p->dbRbu.
  186195. */
  186196. static void rbuIncrSchemaCookie(sqlite3rbu *p){
  186197. if( p->rc==SQLITE_OK ){
  186198. sqlite3 *dbread = (rbuIsVacuum(p) ? p->dbRbu : p->dbMain);
  186199. int iCookie = 1000000;
  186200. sqlite3_stmt *pStmt;
  186201. p->rc = prepareAndCollectError(dbread, &pStmt, &p->zErrmsg,
  186202. "PRAGMA schema_version"
  186203. );
  186204. if( p->rc==SQLITE_OK ){
  186205. /* Coverage: it may be that this sqlite3_step() cannot fail. There
  186206. ** is already a transaction open, so the prepared statement cannot
  186207. ** throw an SQLITE_SCHEMA exception. The only database page the
  186208. ** statement reads is page 1, which is guaranteed to be in the cache.
  186209. ** And no memory allocations are required. */
  186210. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  186211. iCookie = sqlite3_column_int(pStmt, 0);
  186212. }
  186213. rbuFinalize(p, pStmt);
  186214. }
  186215. if( p->rc==SQLITE_OK ){
  186216. rbuMPrintfExec(p, p->dbMain, "PRAGMA schema_version = %d", iCookie+1);
  186217. }
  186218. }
  186219. }
  186220. /*
  186221. ** Update the contents of the rbu_state table within the rbu database. The
  186222. ** value stored in the RBU_STATE_STAGE column is eStage. All other values
  186223. ** are determined by inspecting the rbu handle passed as the first argument.
  186224. */
  186225. static void rbuSaveState(sqlite3rbu *p, int eStage){
  186226. if( p->rc==SQLITE_OK || p->rc==SQLITE_DONE ){
  186227. sqlite3_stmt *pInsert = 0;
  186228. rbu_file *pFd = (rbuIsVacuum(p) ? p->pRbuFd : p->pTargetFd);
  186229. int rc;
  186230. assert( p->zErrmsg==0 );
  186231. rc = prepareFreeAndCollectError(p->dbRbu, &pInsert, &p->zErrmsg,
  186232. sqlite3_mprintf(
  186233. "INSERT OR REPLACE INTO %s.rbu_state(k, v) VALUES "
  186234. "(%d, %d), "
  186235. "(%d, %Q), "
  186236. "(%d, %Q), "
  186237. "(%d, %d), "
  186238. "(%d, %d), "
  186239. "(%d, %lld), "
  186240. "(%d, %lld), "
  186241. "(%d, %lld), "
  186242. "(%d, %lld), "
  186243. "(%d, %Q) ",
  186244. p->zStateDb,
  186245. RBU_STATE_STAGE, eStage,
  186246. RBU_STATE_TBL, p->objiter.zTbl,
  186247. RBU_STATE_IDX, p->objiter.zIdx,
  186248. RBU_STATE_ROW, p->nStep,
  186249. RBU_STATE_PROGRESS, p->nProgress,
  186250. RBU_STATE_CKPT, p->iWalCksum,
  186251. RBU_STATE_COOKIE, (i64)pFd->iCookie,
  186252. RBU_STATE_OALSZ, p->iOalSz,
  186253. RBU_STATE_PHASEONESTEP, p->nPhaseOneStep,
  186254. RBU_STATE_DATATBL, p->objiter.zDataTbl
  186255. )
  186256. );
  186257. assert( pInsert==0 || rc==SQLITE_OK );
  186258. if( rc==SQLITE_OK ){
  186259. sqlite3_step(pInsert);
  186260. rc = sqlite3_finalize(pInsert);
  186261. }
  186262. if( rc!=SQLITE_OK ) p->rc = rc;
  186263. }
  186264. }
  186265. /*
  186266. ** The second argument passed to this function is the name of a PRAGMA
  186267. ** setting - "page_size", "auto_vacuum", "user_version" or "application_id".
  186268. ** This function executes the following on sqlite3rbu.dbRbu:
  186269. **
  186270. ** "PRAGMA main.$zPragma"
  186271. **
  186272. ** where $zPragma is the string passed as the second argument, then
  186273. ** on sqlite3rbu.dbMain:
  186274. **
  186275. ** "PRAGMA main.$zPragma = $val"
  186276. **
  186277. ** where $val is the value returned by the first PRAGMA invocation.
  186278. **
  186279. ** In short, it copies the value of the specified PRAGMA setting from
  186280. ** dbRbu to dbMain.
  186281. */
  186282. static void rbuCopyPragma(sqlite3rbu *p, const char *zPragma){
  186283. if( p->rc==SQLITE_OK ){
  186284. sqlite3_stmt *pPragma = 0;
  186285. p->rc = prepareFreeAndCollectError(p->dbRbu, &pPragma, &p->zErrmsg,
  186286. sqlite3_mprintf("PRAGMA main.%s", zPragma)
  186287. );
  186288. if( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPragma) ){
  186289. p->rc = rbuMPrintfExec(p, p->dbMain, "PRAGMA main.%s = %d",
  186290. zPragma, sqlite3_column_int(pPragma, 0)
  186291. );
  186292. }
  186293. rbuFinalize(p, pPragma);
  186294. }
  186295. }
  186296. /*
  186297. ** The RBU handle passed as the only argument has just been opened and
  186298. ** the state database is empty. If this RBU handle was opened for an
  186299. ** RBU vacuum operation, create the schema in the target db.
  186300. */
  186301. static void rbuCreateTargetSchema(sqlite3rbu *p){
  186302. sqlite3_stmt *pSql = 0;
  186303. sqlite3_stmt *pInsert = 0;
  186304. assert( rbuIsVacuum(p) );
  186305. p->rc = sqlite3_exec(p->dbMain, "PRAGMA writable_schema=1", 0,0, &p->zErrmsg);
  186306. if( p->rc==SQLITE_OK ){
  186307. p->rc = prepareAndCollectError(p->dbRbu, &pSql, &p->zErrmsg,
  186308. "SELECT sql FROM sqlite_master WHERE sql!='' AND rootpage!=0"
  186309. " AND name!='sqlite_sequence' "
  186310. " ORDER BY type DESC"
  186311. );
  186312. }
  186313. while( p->rc==SQLITE_OK && sqlite3_step(pSql)==SQLITE_ROW ){
  186314. const char *zSql = (const char*)sqlite3_column_text(pSql, 0);
  186315. p->rc = sqlite3_exec(p->dbMain, zSql, 0, 0, &p->zErrmsg);
  186316. }
  186317. rbuFinalize(p, pSql);
  186318. if( p->rc!=SQLITE_OK ) return;
  186319. if( p->rc==SQLITE_OK ){
  186320. p->rc = prepareAndCollectError(p->dbRbu, &pSql, &p->zErrmsg,
  186321. "SELECT * FROM sqlite_master WHERE rootpage=0 OR rootpage IS NULL"
  186322. );
  186323. }
  186324. if( p->rc==SQLITE_OK ){
  186325. p->rc = prepareAndCollectError(p->dbMain, &pInsert, &p->zErrmsg,
  186326. "INSERT INTO sqlite_master VALUES(?,?,?,?,?)"
  186327. );
  186328. }
  186329. while( p->rc==SQLITE_OK && sqlite3_step(pSql)==SQLITE_ROW ){
  186330. int i;
  186331. for(i=0; i<5; i++){
  186332. sqlite3_bind_value(pInsert, i+1, sqlite3_column_value(pSql, i));
  186333. }
  186334. sqlite3_step(pInsert);
  186335. p->rc = sqlite3_reset(pInsert);
  186336. }
  186337. if( p->rc==SQLITE_OK ){
  186338. p->rc = sqlite3_exec(p->dbMain, "PRAGMA writable_schema=0",0,0,&p->zErrmsg);
  186339. }
  186340. rbuFinalize(p, pSql);
  186341. rbuFinalize(p, pInsert);
  186342. }
  186343. /*
  186344. ** Step the RBU object.
  186345. */
  186346. SQLITE_API int sqlite3rbu_step(sqlite3rbu *p){
  186347. if( p ){
  186348. switch( p->eStage ){
  186349. case RBU_STAGE_OAL: {
  186350. RbuObjIter *pIter = &p->objiter;
  186351. /* If this is an RBU vacuum operation and the state table was empty
  186352. ** when this handle was opened, create the target database schema. */
  186353. if( rbuIsVacuum(p) && p->nProgress==0 && p->rc==SQLITE_OK ){
  186354. rbuCreateTargetSchema(p);
  186355. rbuCopyPragma(p, "user_version");
  186356. rbuCopyPragma(p, "application_id");
  186357. }
  186358. while( p->rc==SQLITE_OK && pIter->zTbl ){
  186359. if( pIter->bCleanup ){
  186360. /* Clean up the rbu_tmp_xxx table for the previous table. It
  186361. ** cannot be dropped as there are currently active SQL statements.
  186362. ** But the contents can be deleted. */
  186363. if( rbuIsVacuum(p)==0 && pIter->abIndexed ){
  186364. rbuMPrintfExec(p, p->dbRbu,
  186365. "DELETE FROM %s.'rbu_tmp_%q'", p->zStateDb, pIter->zDataTbl
  186366. );
  186367. }
  186368. }else{
  186369. rbuObjIterPrepareAll(p, pIter, 0);
  186370. /* Advance to the next row to process. */
  186371. if( p->rc==SQLITE_OK ){
  186372. int rc = sqlite3_step(pIter->pSelect);
  186373. if( rc==SQLITE_ROW ){
  186374. p->nProgress++;
  186375. p->nStep++;
  186376. return rbuStep(p);
  186377. }
  186378. p->rc = sqlite3_reset(pIter->pSelect);
  186379. p->nStep = 0;
  186380. }
  186381. }
  186382. rbuObjIterNext(p, pIter);
  186383. }
  186384. if( p->rc==SQLITE_OK ){
  186385. assert( pIter->zTbl==0 );
  186386. rbuSaveState(p, RBU_STAGE_MOVE);
  186387. rbuIncrSchemaCookie(p);
  186388. if( p->rc==SQLITE_OK ){
  186389. p->rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, &p->zErrmsg);
  186390. }
  186391. if( p->rc==SQLITE_OK ){
  186392. p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, &p->zErrmsg);
  186393. }
  186394. p->eStage = RBU_STAGE_MOVE;
  186395. }
  186396. break;
  186397. }
  186398. case RBU_STAGE_MOVE: {
  186399. if( p->rc==SQLITE_OK ){
  186400. rbuMoveOalFile(p);
  186401. p->nProgress++;
  186402. }
  186403. break;
  186404. }
  186405. case RBU_STAGE_CKPT: {
  186406. if( p->rc==SQLITE_OK ){
  186407. if( p->nStep>=p->nFrame ){
  186408. sqlite3_file *pDb = p->pTargetFd->pReal;
  186409. /* Sync the db file */
  186410. p->rc = pDb->pMethods->xSync(pDb, SQLITE_SYNC_NORMAL);
  186411. /* Update nBackfill */
  186412. if( p->rc==SQLITE_OK ){
  186413. void volatile *ptr;
  186414. p->rc = pDb->pMethods->xShmMap(pDb, 0, 32*1024, 0, &ptr);
  186415. if( p->rc==SQLITE_OK ){
  186416. ((u32 volatile*)ptr)[24] = p->iMaxFrame;
  186417. }
  186418. }
  186419. if( p->rc==SQLITE_OK ){
  186420. p->eStage = RBU_STAGE_DONE;
  186421. p->rc = SQLITE_DONE;
  186422. }
  186423. }else{
  186424. /* At one point the following block copied a single frame from the
  186425. ** wal file to the database file. So that one call to sqlite3rbu_step()
  186426. ** checkpointed a single frame.
  186427. **
  186428. ** However, if the sector-size is larger than the page-size, and the
  186429. ** application calls sqlite3rbu_savestate() or close() immediately
  186430. ** after this step, then rbu_step() again, then a power failure occurs,
  186431. ** then the database page written here may be damaged. Work around
  186432. ** this by checkpointing frames until the next page in the aFrame[]
  186433. ** lies on a different disk sector to the current one. */
  186434. u32 iSector;
  186435. do{
  186436. RbuFrame *pFrame = &p->aFrame[p->nStep];
  186437. iSector = (pFrame->iDbPage-1) / p->nPagePerSector;
  186438. rbuCheckpointFrame(p, pFrame);
  186439. p->nStep++;
  186440. }while( p->nStep<p->nFrame
  186441. && iSector==((p->aFrame[p->nStep].iDbPage-1) / p->nPagePerSector)
  186442. && p->rc==SQLITE_OK
  186443. );
  186444. }
  186445. p->nProgress++;
  186446. }
  186447. break;
  186448. }
  186449. default:
  186450. break;
  186451. }
  186452. return p->rc;
  186453. }else{
  186454. return SQLITE_NOMEM;
  186455. }
  186456. }
  186457. /*
  186458. ** Compare strings z1 and z2, returning 0 if they are identical, or non-zero
  186459. ** otherwise. Either or both argument may be NULL. Two NULL values are
  186460. ** considered equal, and NULL is considered distinct from all other values.
  186461. */
  186462. static int rbuStrCompare(const char *z1, const char *z2){
  186463. if( z1==0 && z2==0 ) return 0;
  186464. if( z1==0 || z2==0 ) return 1;
  186465. return (sqlite3_stricmp(z1, z2)!=0);
  186466. }
  186467. /*
  186468. ** This function is called as part of sqlite3rbu_open() when initializing
  186469. ** an rbu handle in OAL stage. If the rbu update has not started (i.e.
  186470. ** the rbu_state table was empty) it is a no-op. Otherwise, it arranges
  186471. ** things so that the next call to sqlite3rbu_step() continues on from
  186472. ** where the previous rbu handle left off.
  186473. **
  186474. ** If an error occurs, an error code and error message are left in the
  186475. ** rbu handle passed as the first argument.
  186476. */
  186477. static void rbuSetupOal(sqlite3rbu *p, RbuState *pState){
  186478. assert( p->rc==SQLITE_OK );
  186479. if( pState->zTbl ){
  186480. RbuObjIter *pIter = &p->objiter;
  186481. int rc = SQLITE_OK;
  186482. while( rc==SQLITE_OK && pIter->zTbl && (pIter->bCleanup
  186483. || rbuStrCompare(pIter->zIdx, pState->zIdx)
  186484. || (pState->zDataTbl==0 && rbuStrCompare(pIter->zTbl, pState->zTbl))
  186485. || (pState->zDataTbl && rbuStrCompare(pIter->zDataTbl, pState->zDataTbl))
  186486. )){
  186487. rc = rbuObjIterNext(p, pIter);
  186488. }
  186489. if( rc==SQLITE_OK && !pIter->zTbl ){
  186490. rc = SQLITE_ERROR;
  186491. p->zErrmsg = sqlite3_mprintf("rbu_state mismatch error");
  186492. }
  186493. if( rc==SQLITE_OK ){
  186494. p->nStep = pState->nRow;
  186495. rc = rbuObjIterPrepareAll(p, &p->objiter, p->nStep);
  186496. }
  186497. p->rc = rc;
  186498. }
  186499. }
  186500. /*
  186501. ** If there is a "*-oal" file in the file-system corresponding to the
  186502. ** target database in the file-system, delete it. If an error occurs,
  186503. ** leave an error code and error message in the rbu handle.
  186504. */
  186505. static void rbuDeleteOalFile(sqlite3rbu *p){
  186506. char *zOal = rbuMPrintf(p, "%s-oal", p->zTarget);
  186507. if( zOal ){
  186508. sqlite3_vfs *pVfs = sqlite3_vfs_find(0);
  186509. assert( pVfs && p->rc==SQLITE_OK && p->zErrmsg==0 );
  186510. pVfs->xDelete(pVfs, zOal, 0);
  186511. sqlite3_free(zOal);
  186512. }
  186513. }
  186514. /*
  186515. ** Allocate a private rbu VFS for the rbu handle passed as the only
  186516. ** argument. This VFS will be used unless the call to sqlite3rbu_open()
  186517. ** specified a URI with a vfs=? option in place of a target database
  186518. ** file name.
  186519. */
  186520. static void rbuCreateVfs(sqlite3rbu *p){
  186521. int rnd;
  186522. char zRnd[64];
  186523. assert( p->rc==SQLITE_OK );
  186524. sqlite3_randomness(sizeof(int), (void*)&rnd);
  186525. sqlite3_snprintf(sizeof(zRnd), zRnd, "rbu_vfs_%d", rnd);
  186526. p->rc = sqlite3rbu_create_vfs(zRnd, 0);
  186527. if( p->rc==SQLITE_OK ){
  186528. sqlite3_vfs *pVfs = sqlite3_vfs_find(zRnd);
  186529. assert( pVfs );
  186530. p->zVfsName = pVfs->zName;
  186531. ((rbu_vfs*)pVfs)->pRbu = p;
  186532. }
  186533. }
  186534. /*
  186535. ** Destroy the private VFS created for the rbu handle passed as the only
  186536. ** argument by an earlier call to rbuCreateVfs().
  186537. */
  186538. static void rbuDeleteVfs(sqlite3rbu *p){
  186539. if( p->zVfsName ){
  186540. sqlite3rbu_destroy_vfs(p->zVfsName);
  186541. p->zVfsName = 0;
  186542. }
  186543. }
  186544. /*
  186545. ** This user-defined SQL function is invoked with a single argument - the
  186546. ** name of a table expected to appear in the target database. It returns
  186547. ** the number of auxilliary indexes on the table.
  186548. */
  186549. static void rbuIndexCntFunc(
  186550. sqlite3_context *pCtx,
  186551. int nVal,
  186552. sqlite3_value **apVal
  186553. ){
  186554. sqlite3rbu *p = (sqlite3rbu*)sqlite3_user_data(pCtx);
  186555. sqlite3_stmt *pStmt = 0;
  186556. char *zErrmsg = 0;
  186557. int rc;
  186558. sqlite3 *db = (rbuIsVacuum(p) ? p->dbRbu : p->dbMain);
  186559. assert( nVal==1 );
  186560. rc = prepareFreeAndCollectError(db, &pStmt, &zErrmsg,
  186561. sqlite3_mprintf("SELECT count(*) FROM sqlite_master "
  186562. "WHERE type='index' AND tbl_name = %Q", sqlite3_value_text(apVal[0]))
  186563. );
  186564. if( rc!=SQLITE_OK ){
  186565. sqlite3_result_error(pCtx, zErrmsg, -1);
  186566. }else{
  186567. int nIndex = 0;
  186568. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  186569. nIndex = sqlite3_column_int(pStmt, 0);
  186570. }
  186571. rc = sqlite3_finalize(pStmt);
  186572. if( rc==SQLITE_OK ){
  186573. sqlite3_result_int(pCtx, nIndex);
  186574. }else{
  186575. sqlite3_result_error(pCtx, sqlite3_errmsg(db), -1);
  186576. }
  186577. }
  186578. sqlite3_free(zErrmsg);
  186579. }
  186580. /*
  186581. ** If the RBU database contains the rbu_count table, use it to initialize
  186582. ** the sqlite3rbu.nPhaseOneStep variable. The schema of the rbu_count table
  186583. ** is assumed to contain the same columns as:
  186584. **
  186585. ** CREATE TABLE rbu_count(tbl TEXT PRIMARY KEY, cnt INTEGER) WITHOUT ROWID;
  186586. **
  186587. ** There should be one row in the table for each data_xxx table in the
  186588. ** database. The 'tbl' column should contain the name of a data_xxx table,
  186589. ** and the cnt column the number of rows it contains.
  186590. **
  186591. ** sqlite3rbu.nPhaseOneStep is initialized to the sum of (1 + nIndex) * cnt
  186592. ** for all rows in the rbu_count table, where nIndex is the number of
  186593. ** indexes on the corresponding target database table.
  186594. */
  186595. static void rbuInitPhaseOneSteps(sqlite3rbu *p){
  186596. if( p->rc==SQLITE_OK ){
  186597. sqlite3_stmt *pStmt = 0;
  186598. int bExists = 0; /* True if rbu_count exists */
  186599. p->nPhaseOneStep = -1;
  186600. p->rc = sqlite3_create_function(p->dbRbu,
  186601. "rbu_index_cnt", 1, SQLITE_UTF8, (void*)p, rbuIndexCntFunc, 0, 0
  186602. );
  186603. /* Check for the rbu_count table. If it does not exist, or if an error
  186604. ** occurs, nPhaseOneStep will be left set to -1. */
  186605. if( p->rc==SQLITE_OK ){
  186606. p->rc = prepareAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
  186607. "SELECT 1 FROM sqlite_master WHERE tbl_name = 'rbu_count'"
  186608. );
  186609. }
  186610. if( p->rc==SQLITE_OK ){
  186611. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  186612. bExists = 1;
  186613. }
  186614. p->rc = sqlite3_finalize(pStmt);
  186615. }
  186616. if( p->rc==SQLITE_OK && bExists ){
  186617. p->rc = prepareAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
  186618. "SELECT sum(cnt * (1 + rbu_index_cnt(rbu_target_name(tbl))))"
  186619. "FROM rbu_count"
  186620. );
  186621. if( p->rc==SQLITE_OK ){
  186622. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  186623. p->nPhaseOneStep = sqlite3_column_int64(pStmt, 0);
  186624. }
  186625. p->rc = sqlite3_finalize(pStmt);
  186626. }
  186627. }
  186628. }
  186629. }
  186630. static sqlite3rbu *openRbuHandle(
  186631. const char *zTarget,
  186632. const char *zRbu,
  186633. const char *zState
  186634. ){
  186635. sqlite3rbu *p;
  186636. size_t nTarget = zTarget ? strlen(zTarget) : 0;
  186637. size_t nRbu = strlen(zRbu);
  186638. size_t nByte = sizeof(sqlite3rbu) + nTarget+1 + nRbu+1;
  186639. p = (sqlite3rbu*)sqlite3_malloc64(nByte);
  186640. if( p ){
  186641. RbuState *pState = 0;
  186642. /* Create the custom VFS. */
  186643. memset(p, 0, sizeof(sqlite3rbu));
  186644. rbuCreateVfs(p);
  186645. /* Open the target, RBU and state databases */
  186646. if( p->rc==SQLITE_OK ){
  186647. char *pCsr = (char*)&p[1];
  186648. int bRetry = 0;
  186649. if( zTarget ){
  186650. p->zTarget = pCsr;
  186651. memcpy(p->zTarget, zTarget, nTarget+1);
  186652. pCsr += nTarget+1;
  186653. }
  186654. p->zRbu = pCsr;
  186655. memcpy(p->zRbu, zRbu, nRbu+1);
  186656. pCsr += nRbu+1;
  186657. if( zState ){
  186658. p->zState = rbuMPrintf(p, "%s", zState);
  186659. }
  186660. /* If the first attempt to open the database file fails and the bRetry
  186661. ** flag it set, this means that the db was not opened because it seemed
  186662. ** to be a wal-mode db. But, this may have happened due to an earlier
  186663. ** RBU vacuum operation leaving an old wal file in the directory.
  186664. ** If this is the case, it will have been checkpointed and deleted
  186665. ** when the handle was closed and a second attempt to open the
  186666. ** database may succeed. */
  186667. rbuOpenDatabase(p, &bRetry);
  186668. if( bRetry ){
  186669. rbuOpenDatabase(p, 0);
  186670. }
  186671. }
  186672. if( p->rc==SQLITE_OK ){
  186673. pState = rbuLoadState(p);
  186674. assert( pState || p->rc!=SQLITE_OK );
  186675. if( p->rc==SQLITE_OK ){
  186676. if( pState->eStage==0 ){
  186677. rbuDeleteOalFile(p);
  186678. rbuInitPhaseOneSteps(p);
  186679. p->eStage = RBU_STAGE_OAL;
  186680. }else{
  186681. p->eStage = pState->eStage;
  186682. p->nPhaseOneStep = pState->nPhaseOneStep;
  186683. }
  186684. p->nProgress = pState->nProgress;
  186685. p->iOalSz = pState->iOalSz;
  186686. }
  186687. }
  186688. assert( p->rc!=SQLITE_OK || p->eStage!=0 );
  186689. if( p->rc==SQLITE_OK && p->pTargetFd->pWalFd ){
  186690. if( p->eStage==RBU_STAGE_OAL ){
  186691. p->rc = SQLITE_ERROR;
  186692. p->zErrmsg = sqlite3_mprintf("cannot update wal mode database");
  186693. }else if( p->eStage==RBU_STAGE_MOVE ){
  186694. p->eStage = RBU_STAGE_CKPT;
  186695. p->nStep = 0;
  186696. }
  186697. }
  186698. if( p->rc==SQLITE_OK
  186699. && (p->eStage==RBU_STAGE_OAL || p->eStage==RBU_STAGE_MOVE)
  186700. && pState->eStage!=0
  186701. ){
  186702. rbu_file *pFd = (rbuIsVacuum(p) ? p->pRbuFd : p->pTargetFd);
  186703. if( pFd->iCookie!=pState->iCookie ){
  186704. /* At this point (pTargetFd->iCookie) contains the value of the
  186705. ** change-counter cookie (the thing that gets incremented when a
  186706. ** transaction is committed in rollback mode) currently stored on
  186707. ** page 1 of the database file. */
  186708. p->rc = SQLITE_BUSY;
  186709. p->zErrmsg = sqlite3_mprintf("database modified during rbu %s",
  186710. (rbuIsVacuum(p) ? "vacuum" : "update")
  186711. );
  186712. }
  186713. }
  186714. if( p->rc==SQLITE_OK ){
  186715. if( p->eStage==RBU_STAGE_OAL ){
  186716. sqlite3 *db = p->dbMain;
  186717. p->rc = sqlite3_exec(p->dbRbu, "BEGIN", 0, 0, &p->zErrmsg);
  186718. /* Point the object iterator at the first object */
  186719. if( p->rc==SQLITE_OK ){
  186720. p->rc = rbuObjIterFirst(p, &p->objiter);
  186721. }
  186722. /* If the RBU database contains no data_xxx tables, declare the RBU
  186723. ** update finished. */
  186724. if( p->rc==SQLITE_OK && p->objiter.zTbl==0 ){
  186725. p->rc = SQLITE_DONE;
  186726. p->eStage = RBU_STAGE_DONE;
  186727. }else{
  186728. if( p->rc==SQLITE_OK && pState->eStage==0 && rbuIsVacuum(p) ){
  186729. rbuCopyPragma(p, "page_size");
  186730. rbuCopyPragma(p, "auto_vacuum");
  186731. }
  186732. /* Open transactions both databases. The *-oal file is opened or
  186733. ** created at this point. */
  186734. if( p->rc==SQLITE_OK ){
  186735. p->rc = sqlite3_exec(db, "BEGIN IMMEDIATE", 0, 0, &p->zErrmsg);
  186736. }
  186737. /* Check if the main database is a zipvfs db. If it is, set the upper
  186738. ** level pager to use "journal_mode=off". This prevents it from
  186739. ** generating a large journal using a temp file. */
  186740. if( p->rc==SQLITE_OK ){
  186741. int frc = sqlite3_file_control(db, "main", SQLITE_FCNTL_ZIPVFS, 0);
  186742. if( frc==SQLITE_OK ){
  186743. p->rc = sqlite3_exec(
  186744. db, "PRAGMA journal_mode=off",0,0,&p->zErrmsg);
  186745. }
  186746. }
  186747. if( p->rc==SQLITE_OK ){
  186748. rbuSetupOal(p, pState);
  186749. }
  186750. }
  186751. }else if( p->eStage==RBU_STAGE_MOVE ){
  186752. /* no-op */
  186753. }else if( p->eStage==RBU_STAGE_CKPT ){
  186754. rbuSetupCheckpoint(p, pState);
  186755. }else if( p->eStage==RBU_STAGE_DONE ){
  186756. p->rc = SQLITE_DONE;
  186757. }else{
  186758. p->rc = SQLITE_CORRUPT;
  186759. }
  186760. }
  186761. rbuFreeState(pState);
  186762. }
  186763. return p;
  186764. }
  186765. /*
  186766. ** Allocate and return an RBU handle with all fields zeroed except for the
  186767. ** error code, which is set to SQLITE_MISUSE.
  186768. */
  186769. static sqlite3rbu *rbuMisuseError(void){
  186770. sqlite3rbu *pRet;
  186771. pRet = sqlite3_malloc64(sizeof(sqlite3rbu));
  186772. if( pRet ){
  186773. memset(pRet, 0, sizeof(sqlite3rbu));
  186774. pRet->rc = SQLITE_MISUSE;
  186775. }
  186776. return pRet;
  186777. }
  186778. /*
  186779. ** Open and return a new RBU handle.
  186780. */
  186781. SQLITE_API sqlite3rbu *sqlite3rbu_open(
  186782. const char *zTarget,
  186783. const char *zRbu,
  186784. const char *zState
  186785. ){
  186786. if( zTarget==0 || zRbu==0 ){ return rbuMisuseError(); }
  186787. /* TODO: Check that zTarget and zRbu are non-NULL */
  186788. return openRbuHandle(zTarget, zRbu, zState);
  186789. }
  186790. /*
  186791. ** Open a handle to begin or resume an RBU VACUUM operation.
  186792. */
  186793. SQLITE_API sqlite3rbu *sqlite3rbu_vacuum(
  186794. const char *zTarget,
  186795. const char *zState
  186796. ){
  186797. if( zTarget==0 ){ return rbuMisuseError(); }
  186798. if( zState ){
  186799. int n = strlen(zState);
  186800. if( n>=7 && 0==memcmp("-vactmp", &zState[n-7], 7) ){
  186801. return rbuMisuseError();
  186802. }
  186803. }
  186804. /* TODO: Check that both arguments are non-NULL */
  186805. return openRbuHandle(0, zTarget, zState);
  186806. }
  186807. /*
  186808. ** Return the database handle used by pRbu.
  186809. */
  186810. SQLITE_API sqlite3 *sqlite3rbu_db(sqlite3rbu *pRbu, int bRbu){
  186811. sqlite3 *db = 0;
  186812. if( pRbu ){
  186813. db = (bRbu ? pRbu->dbRbu : pRbu->dbMain);
  186814. }
  186815. return db;
  186816. }
  186817. /*
  186818. ** If the error code currently stored in the RBU handle is SQLITE_CONSTRAINT,
  186819. ** then edit any error message string so as to remove all occurrences of
  186820. ** the pattern "rbu_imp_[0-9]*".
  186821. */
  186822. static void rbuEditErrmsg(sqlite3rbu *p){
  186823. if( p->rc==SQLITE_CONSTRAINT && p->zErrmsg ){
  186824. unsigned int i;
  186825. size_t nErrmsg = strlen(p->zErrmsg);
  186826. for(i=0; i<(nErrmsg-8); i++){
  186827. if( memcmp(&p->zErrmsg[i], "rbu_imp_", 8)==0 ){
  186828. int nDel = 8;
  186829. while( p->zErrmsg[i+nDel]>='0' && p->zErrmsg[i+nDel]<='9' ) nDel++;
  186830. memmove(&p->zErrmsg[i], &p->zErrmsg[i+nDel], nErrmsg + 1 - i - nDel);
  186831. nErrmsg -= nDel;
  186832. }
  186833. }
  186834. }
  186835. }
  186836. /*
  186837. ** Close the RBU handle.
  186838. */
  186839. SQLITE_API int sqlite3rbu_close(sqlite3rbu *p, char **pzErrmsg){
  186840. int rc;
  186841. if( p ){
  186842. /* Commit the transaction to the *-oal file. */
  186843. if( p->rc==SQLITE_OK && p->eStage==RBU_STAGE_OAL ){
  186844. p->rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, &p->zErrmsg);
  186845. }
  186846. /* Sync the db file if currently doing an incremental checkpoint */
  186847. if( p->rc==SQLITE_OK && p->eStage==RBU_STAGE_CKPT ){
  186848. sqlite3_file *pDb = p->pTargetFd->pReal;
  186849. p->rc = pDb->pMethods->xSync(pDb, SQLITE_SYNC_NORMAL);
  186850. }
  186851. rbuSaveState(p, p->eStage);
  186852. if( p->rc==SQLITE_OK && p->eStage==RBU_STAGE_OAL ){
  186853. p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, &p->zErrmsg);
  186854. }
  186855. /* Close any open statement handles. */
  186856. rbuObjIterFinalize(&p->objiter);
  186857. /* If this is an RBU vacuum handle and the vacuum has either finished
  186858. ** successfully or encountered an error, delete the contents of the
  186859. ** state table. This causes the next call to sqlite3rbu_vacuum()
  186860. ** specifying the current target and state databases to start a new
  186861. ** vacuum from scratch. */
  186862. if( rbuIsVacuum(p) && p->rc!=SQLITE_OK && p->dbRbu ){
  186863. int rc2 = sqlite3_exec(p->dbRbu, "DELETE FROM stat.rbu_state", 0, 0, 0);
  186864. if( p->rc==SQLITE_DONE && rc2!=SQLITE_OK ) p->rc = rc2;
  186865. }
  186866. /* Close the open database handle and VFS object. */
  186867. sqlite3_close(p->dbRbu);
  186868. sqlite3_close(p->dbMain);
  186869. assert( p->szTemp==0 );
  186870. rbuDeleteVfs(p);
  186871. sqlite3_free(p->aBuf);
  186872. sqlite3_free(p->aFrame);
  186873. rbuEditErrmsg(p);
  186874. rc = p->rc;
  186875. if( pzErrmsg ){
  186876. *pzErrmsg = p->zErrmsg;
  186877. }else{
  186878. sqlite3_free(p->zErrmsg);
  186879. }
  186880. sqlite3_free(p->zState);
  186881. sqlite3_free(p);
  186882. }else{
  186883. rc = SQLITE_NOMEM;
  186884. *pzErrmsg = 0;
  186885. }
  186886. return rc;
  186887. }
  186888. /*
  186889. ** Return the total number of key-value operations (inserts, deletes or
  186890. ** updates) that have been performed on the target database since the
  186891. ** current RBU update was started.
  186892. */
  186893. SQLITE_API sqlite3_int64 sqlite3rbu_progress(sqlite3rbu *pRbu){
  186894. return pRbu->nProgress;
  186895. }
  186896. /*
  186897. ** Return permyriadage progress indications for the two main stages of
  186898. ** an RBU update.
  186899. */
  186900. SQLITE_API void sqlite3rbu_bp_progress(sqlite3rbu *p, int *pnOne, int *pnTwo){
  186901. const int MAX_PROGRESS = 10000;
  186902. switch( p->eStage ){
  186903. case RBU_STAGE_OAL:
  186904. if( p->nPhaseOneStep>0 ){
  186905. *pnOne = (int)(MAX_PROGRESS * (i64)p->nProgress/(i64)p->nPhaseOneStep);
  186906. }else{
  186907. *pnOne = -1;
  186908. }
  186909. *pnTwo = 0;
  186910. break;
  186911. case RBU_STAGE_MOVE:
  186912. *pnOne = MAX_PROGRESS;
  186913. *pnTwo = 0;
  186914. break;
  186915. case RBU_STAGE_CKPT:
  186916. *pnOne = MAX_PROGRESS;
  186917. *pnTwo = (int)(MAX_PROGRESS * (i64)p->nStep / (i64)p->nFrame);
  186918. break;
  186919. case RBU_STAGE_DONE:
  186920. *pnOne = MAX_PROGRESS;
  186921. *pnTwo = MAX_PROGRESS;
  186922. break;
  186923. default:
  186924. assert( 0 );
  186925. }
  186926. }
  186927. /*
  186928. ** Return the current state of the RBU vacuum or update operation.
  186929. */
  186930. SQLITE_API int sqlite3rbu_state(sqlite3rbu *p){
  186931. int aRes[] = {
  186932. 0, SQLITE_RBU_STATE_OAL, SQLITE_RBU_STATE_MOVE,
  186933. 0, SQLITE_RBU_STATE_CHECKPOINT, SQLITE_RBU_STATE_DONE
  186934. };
  186935. assert( RBU_STAGE_OAL==1 );
  186936. assert( RBU_STAGE_MOVE==2 );
  186937. assert( RBU_STAGE_CKPT==4 );
  186938. assert( RBU_STAGE_DONE==5 );
  186939. assert( aRes[RBU_STAGE_OAL]==SQLITE_RBU_STATE_OAL );
  186940. assert( aRes[RBU_STAGE_MOVE]==SQLITE_RBU_STATE_MOVE );
  186941. assert( aRes[RBU_STAGE_CKPT]==SQLITE_RBU_STATE_CHECKPOINT );
  186942. assert( aRes[RBU_STAGE_DONE]==SQLITE_RBU_STATE_DONE );
  186943. if( p->rc!=SQLITE_OK && p->rc!=SQLITE_DONE ){
  186944. return SQLITE_RBU_STATE_ERROR;
  186945. }else{
  186946. assert( p->rc!=SQLITE_DONE || p->eStage==RBU_STAGE_DONE );
  186947. assert( p->eStage==RBU_STAGE_OAL
  186948. || p->eStage==RBU_STAGE_MOVE
  186949. || p->eStage==RBU_STAGE_CKPT
  186950. || p->eStage==RBU_STAGE_DONE
  186951. );
  186952. return aRes[p->eStage];
  186953. }
  186954. }
  186955. SQLITE_API int sqlite3rbu_savestate(sqlite3rbu *p){
  186956. int rc = p->rc;
  186957. if( rc==SQLITE_DONE ) return SQLITE_OK;
  186958. assert( p->eStage>=RBU_STAGE_OAL && p->eStage<=RBU_STAGE_DONE );
  186959. if( p->eStage==RBU_STAGE_OAL ){
  186960. assert( rc!=SQLITE_DONE );
  186961. if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, 0);
  186962. }
  186963. /* Sync the db file */
  186964. if( rc==SQLITE_OK && p->eStage==RBU_STAGE_CKPT ){
  186965. sqlite3_file *pDb = p->pTargetFd->pReal;
  186966. rc = pDb->pMethods->xSync(pDb, SQLITE_SYNC_NORMAL);
  186967. }
  186968. p->rc = rc;
  186969. rbuSaveState(p, p->eStage);
  186970. rc = p->rc;
  186971. if( p->eStage==RBU_STAGE_OAL ){
  186972. assert( rc!=SQLITE_DONE );
  186973. if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, 0);
  186974. if( rc==SQLITE_OK ){
  186975. const char *zBegin = rbuIsVacuum(p) ? "BEGIN" : "BEGIN IMMEDIATE";
  186976. rc = sqlite3_exec(p->dbRbu, zBegin, 0, 0, 0);
  186977. }
  186978. if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbMain, "BEGIN IMMEDIATE", 0, 0,0);
  186979. }
  186980. p->rc = rc;
  186981. return rc;
  186982. }
  186983. /**************************************************************************
  186984. ** Beginning of RBU VFS shim methods. The VFS shim modifies the behaviour
  186985. ** of a standard VFS in the following ways:
  186986. **
  186987. ** 1. Whenever the first page of a main database file is read or
  186988. ** written, the value of the change-counter cookie is stored in
  186989. ** rbu_file.iCookie. Similarly, the value of the "write-version"
  186990. ** database header field is stored in rbu_file.iWriteVer. This ensures
  186991. ** that the values are always trustworthy within an open transaction.
  186992. **
  186993. ** 2. Whenever an SQLITE_OPEN_WAL file is opened, the (rbu_file.pWalFd)
  186994. ** member variable of the associated database file descriptor is set
  186995. ** to point to the new file. A mutex protected linked list of all main
  186996. ** db fds opened using a particular RBU VFS is maintained at
  186997. ** rbu_vfs.pMain to facilitate this.
  186998. **
  186999. ** 3. Using a new file-control "SQLITE_FCNTL_RBU", a main db rbu_file
  187000. ** object can be marked as the target database of an RBU update. This
  187001. ** turns on the following extra special behaviour:
  187002. **
  187003. ** 3a. If xAccess() is called to check if there exists a *-wal file
  187004. ** associated with an RBU target database currently in RBU_STAGE_OAL
  187005. ** stage (preparing the *-oal file), the following special handling
  187006. ** applies:
  187007. **
  187008. ** * if the *-wal file does exist, return SQLITE_CANTOPEN. An RBU
  187009. ** target database may not be in wal mode already.
  187010. **
  187011. ** * if the *-wal file does not exist, set the output parameter to
  187012. ** non-zero (to tell SQLite that it does exist) anyway.
  187013. **
  187014. ** Then, when xOpen() is called to open the *-wal file associated with
  187015. ** the RBU target in RBU_STAGE_OAL stage, instead of opening the *-wal
  187016. ** file, the rbu vfs opens the corresponding *-oal file instead.
  187017. **
  187018. ** 3b. The *-shm pages returned by xShmMap() for a target db file in
  187019. ** RBU_STAGE_OAL mode are actually stored in heap memory. This is to
  187020. ** avoid creating a *-shm file on disk. Additionally, xShmLock() calls
  187021. ** are no-ops on target database files in RBU_STAGE_OAL mode. This is
  187022. ** because assert() statements in some VFS implementations fail if
  187023. ** xShmLock() is called before xShmMap().
  187024. **
  187025. ** 3c. If an EXCLUSIVE lock is attempted on a target database file in any
  187026. ** mode except RBU_STAGE_DONE (all work completed and checkpointed), it
  187027. ** fails with an SQLITE_BUSY error. This is to stop RBU connections
  187028. ** from automatically checkpointing a *-wal (or *-oal) file from within
  187029. ** sqlite3_close().
  187030. **
  187031. ** 3d. In RBU_STAGE_CAPTURE mode, all xRead() calls on the wal file, and
  187032. ** all xWrite() calls on the target database file perform no IO.
  187033. ** Instead the frame and page numbers that would be read and written
  187034. ** are recorded. Additionally, successful attempts to obtain exclusive
  187035. ** xShmLock() WRITER, CHECKPOINTER and READ0 locks on the target
  187036. ** database file are recorded. xShmLock() calls to unlock the same
  187037. ** locks are no-ops (so that once obtained, these locks are never
  187038. ** relinquished). Finally, calls to xSync() on the target database
  187039. ** file fail with SQLITE_INTERNAL errors.
  187040. */
  187041. static void rbuUnlockShm(rbu_file *p){
  187042. assert( p->openFlags & SQLITE_OPEN_MAIN_DB );
  187043. if( p->pRbu ){
  187044. int (*xShmLock)(sqlite3_file*,int,int,int) = p->pReal->pMethods->xShmLock;
  187045. int i;
  187046. for(i=0; i<SQLITE_SHM_NLOCK;i++){
  187047. if( (1<<i) & p->pRbu->mLock ){
  187048. xShmLock(p->pReal, i, 1, SQLITE_SHM_UNLOCK|SQLITE_SHM_EXCLUSIVE);
  187049. }
  187050. }
  187051. p->pRbu->mLock = 0;
  187052. }
  187053. }
  187054. /*
  187055. */
  187056. static int rbuUpdateTempSize(rbu_file *pFd, sqlite3_int64 nNew){
  187057. sqlite3rbu *pRbu = pFd->pRbu;
  187058. i64 nDiff = nNew - pFd->sz;
  187059. pRbu->szTemp += nDiff;
  187060. pFd->sz = nNew;
  187061. assert( pRbu->szTemp>=0 );
  187062. if( pRbu->szTempLimit && pRbu->szTemp>pRbu->szTempLimit ) return SQLITE_FULL;
  187063. return SQLITE_OK;
  187064. }
  187065. /*
  187066. ** Add an item to the main-db lists, if it is not already present.
  187067. **
  187068. ** There are two main-db lists. One for all file descriptors, and one
  187069. ** for all file descriptors with rbu_file.pDb!=0. If the argument has
  187070. ** rbu_file.pDb!=0, then it is assumed to already be present on the
  187071. ** main list and is only added to the pDb!=0 list.
  187072. */
  187073. static void rbuMainlistAdd(rbu_file *p){
  187074. rbu_vfs *pRbuVfs = p->pRbuVfs;
  187075. rbu_file *pIter;
  187076. assert( (p->openFlags & SQLITE_OPEN_MAIN_DB) );
  187077. sqlite3_mutex_enter(pRbuVfs->mutex);
  187078. if( p->pRbu==0 ){
  187079. for(pIter=pRbuVfs->pMain; pIter; pIter=pIter->pMainNext);
  187080. p->pMainNext = pRbuVfs->pMain;
  187081. pRbuVfs->pMain = p;
  187082. }else{
  187083. for(pIter=pRbuVfs->pMainRbu; pIter && pIter!=p; pIter=pIter->pMainRbuNext){}
  187084. if( pIter==0 ){
  187085. p->pMainRbuNext = pRbuVfs->pMainRbu;
  187086. pRbuVfs->pMainRbu = p;
  187087. }
  187088. }
  187089. sqlite3_mutex_leave(pRbuVfs->mutex);
  187090. }
  187091. /*
  187092. ** Remove an item from the main-db lists.
  187093. */
  187094. static void rbuMainlistRemove(rbu_file *p){
  187095. rbu_file **pp;
  187096. sqlite3_mutex_enter(p->pRbuVfs->mutex);
  187097. for(pp=&p->pRbuVfs->pMain; *pp && *pp!=p; pp=&((*pp)->pMainNext)){}
  187098. if( *pp ) *pp = p->pMainNext;
  187099. p->pMainNext = 0;
  187100. for(pp=&p->pRbuVfs->pMainRbu; *pp && *pp!=p; pp=&((*pp)->pMainRbuNext)){}
  187101. if( *pp ) *pp = p->pMainRbuNext;
  187102. p->pMainRbuNext = 0;
  187103. sqlite3_mutex_leave(p->pRbuVfs->mutex);
  187104. }
  187105. /*
  187106. ** Given that zWal points to a buffer containing a wal file name passed to
  187107. ** either the xOpen() or xAccess() VFS method, search the main-db list for
  187108. ** a file-handle opened by the same database connection on the corresponding
  187109. ** database file.
  187110. **
  187111. ** If parameter bRbu is true, only search for file-descriptors with
  187112. ** rbu_file.pDb!=0.
  187113. */
  187114. static rbu_file *rbuFindMaindb(rbu_vfs *pRbuVfs, const char *zWal, int bRbu){
  187115. rbu_file *pDb;
  187116. sqlite3_mutex_enter(pRbuVfs->mutex);
  187117. if( bRbu ){
  187118. for(pDb=pRbuVfs->pMainRbu; pDb && pDb->zWal!=zWal; pDb=pDb->pMainRbuNext){}
  187119. }else{
  187120. for(pDb=pRbuVfs->pMain; pDb && pDb->zWal!=zWal; pDb=pDb->pMainNext){}
  187121. }
  187122. sqlite3_mutex_leave(pRbuVfs->mutex);
  187123. return pDb;
  187124. }
  187125. /*
  187126. ** Close an rbu file.
  187127. */
  187128. static int rbuVfsClose(sqlite3_file *pFile){
  187129. rbu_file *p = (rbu_file*)pFile;
  187130. int rc;
  187131. int i;
  187132. /* Free the contents of the apShm[] array. And the array itself. */
  187133. for(i=0; i<p->nShm; i++){
  187134. sqlite3_free(p->apShm[i]);
  187135. }
  187136. sqlite3_free(p->apShm);
  187137. p->apShm = 0;
  187138. sqlite3_free(p->zDel);
  187139. if( p->openFlags & SQLITE_OPEN_MAIN_DB ){
  187140. rbuMainlistRemove(p);
  187141. rbuUnlockShm(p);
  187142. p->pReal->pMethods->xShmUnmap(p->pReal, 0);
  187143. }
  187144. else if( (p->openFlags & SQLITE_OPEN_DELETEONCLOSE) && p->pRbu ){
  187145. rbuUpdateTempSize(p, 0);
  187146. }
  187147. assert( p->pMainNext==0 && p->pRbuVfs->pMain!=p );
  187148. /* Close the underlying file handle */
  187149. rc = p->pReal->pMethods->xClose(p->pReal);
  187150. return rc;
  187151. }
  187152. /*
  187153. ** Read and return an unsigned 32-bit big-endian integer from the buffer
  187154. ** passed as the only argument.
  187155. */
  187156. static u32 rbuGetU32(u8 *aBuf){
  187157. return ((u32)aBuf[0] << 24)
  187158. + ((u32)aBuf[1] << 16)
  187159. + ((u32)aBuf[2] << 8)
  187160. + ((u32)aBuf[3]);
  187161. }
  187162. /*
  187163. ** Write an unsigned 32-bit value in big-endian format to the supplied
  187164. ** buffer.
  187165. */
  187166. static void rbuPutU32(u8 *aBuf, u32 iVal){
  187167. aBuf[0] = (iVal >> 24) & 0xFF;
  187168. aBuf[1] = (iVal >> 16) & 0xFF;
  187169. aBuf[2] = (iVal >> 8) & 0xFF;
  187170. aBuf[3] = (iVal >> 0) & 0xFF;
  187171. }
  187172. static void rbuPutU16(u8 *aBuf, u16 iVal){
  187173. aBuf[0] = (iVal >> 8) & 0xFF;
  187174. aBuf[1] = (iVal >> 0) & 0xFF;
  187175. }
  187176. /*
  187177. ** Read data from an rbuVfs-file.
  187178. */
  187179. static int rbuVfsRead(
  187180. sqlite3_file *pFile,
  187181. void *zBuf,
  187182. int iAmt,
  187183. sqlite_int64 iOfst
  187184. ){
  187185. rbu_file *p = (rbu_file*)pFile;
  187186. sqlite3rbu *pRbu = p->pRbu;
  187187. int rc;
  187188. if( pRbu && pRbu->eStage==RBU_STAGE_CAPTURE ){
  187189. assert( p->openFlags & SQLITE_OPEN_WAL );
  187190. rc = rbuCaptureWalRead(p->pRbu, iOfst, iAmt);
  187191. }else{
  187192. if( pRbu && pRbu->eStage==RBU_STAGE_OAL
  187193. && (p->openFlags & SQLITE_OPEN_WAL)
  187194. && iOfst>=pRbu->iOalSz
  187195. ){
  187196. rc = SQLITE_OK;
  187197. memset(zBuf, 0, iAmt);
  187198. }else{
  187199. rc = p->pReal->pMethods->xRead(p->pReal, zBuf, iAmt, iOfst);
  187200. #if 1
  187201. /* If this is being called to read the first page of the target
  187202. ** database as part of an rbu vacuum operation, synthesize the
  187203. ** contents of the first page if it does not yet exist. Otherwise,
  187204. ** SQLite will not check for a *-wal file. */
  187205. if( pRbu && rbuIsVacuum(pRbu)
  187206. && rc==SQLITE_IOERR_SHORT_READ && iOfst==0
  187207. && (p->openFlags & SQLITE_OPEN_MAIN_DB)
  187208. && pRbu->rc==SQLITE_OK
  187209. ){
  187210. sqlite3_file *pFd = (sqlite3_file*)pRbu->pRbuFd;
  187211. rc = pFd->pMethods->xRead(pFd, zBuf, iAmt, iOfst);
  187212. if( rc==SQLITE_OK ){
  187213. u8 *aBuf = (u8*)zBuf;
  187214. u32 iRoot = rbuGetU32(&aBuf[52]) ? 1 : 0;
  187215. rbuPutU32(&aBuf[52], iRoot); /* largest root page number */
  187216. rbuPutU32(&aBuf[36], 0); /* number of free pages */
  187217. rbuPutU32(&aBuf[32], 0); /* first page on free list trunk */
  187218. rbuPutU32(&aBuf[28], 1); /* size of db file in pages */
  187219. rbuPutU32(&aBuf[24], pRbu->pRbuFd->iCookie+1); /* Change counter */
  187220. if( iAmt>100 ){
  187221. memset(&aBuf[100], 0, iAmt-100);
  187222. rbuPutU16(&aBuf[105], iAmt & 0xFFFF);
  187223. aBuf[100] = 0x0D;
  187224. }
  187225. }
  187226. }
  187227. #endif
  187228. }
  187229. if( rc==SQLITE_OK && iOfst==0 && (p->openFlags & SQLITE_OPEN_MAIN_DB) ){
  187230. /* These look like magic numbers. But they are stable, as they are part
  187231. ** of the definition of the SQLite file format, which may not change. */
  187232. u8 *pBuf = (u8*)zBuf;
  187233. p->iCookie = rbuGetU32(&pBuf[24]);
  187234. p->iWriteVer = pBuf[19];
  187235. }
  187236. }
  187237. return rc;
  187238. }
  187239. /*
  187240. ** Write data to an rbuVfs-file.
  187241. */
  187242. static int rbuVfsWrite(
  187243. sqlite3_file *pFile,
  187244. const void *zBuf,
  187245. int iAmt,
  187246. sqlite_int64 iOfst
  187247. ){
  187248. rbu_file *p = (rbu_file*)pFile;
  187249. sqlite3rbu *pRbu = p->pRbu;
  187250. int rc;
  187251. if( pRbu && pRbu->eStage==RBU_STAGE_CAPTURE ){
  187252. assert( p->openFlags & SQLITE_OPEN_MAIN_DB );
  187253. rc = rbuCaptureDbWrite(p->pRbu, iOfst);
  187254. }else{
  187255. if( pRbu ){
  187256. if( pRbu->eStage==RBU_STAGE_OAL
  187257. && (p->openFlags & SQLITE_OPEN_WAL)
  187258. && iOfst>=pRbu->iOalSz
  187259. ){
  187260. pRbu->iOalSz = iAmt + iOfst;
  187261. }else if( p->openFlags & SQLITE_OPEN_DELETEONCLOSE ){
  187262. i64 szNew = iAmt+iOfst;
  187263. if( szNew>p->sz ){
  187264. rc = rbuUpdateTempSize(p, szNew);
  187265. if( rc!=SQLITE_OK ) return rc;
  187266. }
  187267. }
  187268. }
  187269. rc = p->pReal->pMethods->xWrite(p->pReal, zBuf, iAmt, iOfst);
  187270. if( rc==SQLITE_OK && iOfst==0 && (p->openFlags & SQLITE_OPEN_MAIN_DB) ){
  187271. /* These look like magic numbers. But they are stable, as they are part
  187272. ** of the definition of the SQLite file format, which may not change. */
  187273. u8 *pBuf = (u8*)zBuf;
  187274. p->iCookie = rbuGetU32(&pBuf[24]);
  187275. p->iWriteVer = pBuf[19];
  187276. }
  187277. }
  187278. return rc;
  187279. }
  187280. /*
  187281. ** Truncate an rbuVfs-file.
  187282. */
  187283. static int rbuVfsTruncate(sqlite3_file *pFile, sqlite_int64 size){
  187284. rbu_file *p = (rbu_file*)pFile;
  187285. if( (p->openFlags & SQLITE_OPEN_DELETEONCLOSE) && p->pRbu ){
  187286. int rc = rbuUpdateTempSize(p, size);
  187287. if( rc!=SQLITE_OK ) return rc;
  187288. }
  187289. return p->pReal->pMethods->xTruncate(p->pReal, size);
  187290. }
  187291. /*
  187292. ** Sync an rbuVfs-file.
  187293. */
  187294. static int rbuVfsSync(sqlite3_file *pFile, int flags){
  187295. rbu_file *p = (rbu_file *)pFile;
  187296. if( p->pRbu && p->pRbu->eStage==RBU_STAGE_CAPTURE ){
  187297. if( p->openFlags & SQLITE_OPEN_MAIN_DB ){
  187298. return SQLITE_INTERNAL;
  187299. }
  187300. return SQLITE_OK;
  187301. }
  187302. return p->pReal->pMethods->xSync(p->pReal, flags);
  187303. }
  187304. /*
  187305. ** Return the current file-size of an rbuVfs-file.
  187306. */
  187307. static int rbuVfsFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){
  187308. rbu_file *p = (rbu_file *)pFile;
  187309. int rc;
  187310. rc = p->pReal->pMethods->xFileSize(p->pReal, pSize);
  187311. /* If this is an RBU vacuum operation and this is the target database,
  187312. ** pretend that it has at least one page. Otherwise, SQLite will not
  187313. ** check for the existance of a *-wal file. rbuVfsRead() contains
  187314. ** similar logic. */
  187315. if( rc==SQLITE_OK && *pSize==0
  187316. && p->pRbu && rbuIsVacuum(p->pRbu)
  187317. && (p->openFlags & SQLITE_OPEN_MAIN_DB)
  187318. ){
  187319. *pSize = 1024;
  187320. }
  187321. return rc;
  187322. }
  187323. /*
  187324. ** Lock an rbuVfs-file.
  187325. */
  187326. static int rbuVfsLock(sqlite3_file *pFile, int eLock){
  187327. rbu_file *p = (rbu_file*)pFile;
  187328. sqlite3rbu *pRbu = p->pRbu;
  187329. int rc = SQLITE_OK;
  187330. assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
  187331. if( eLock==SQLITE_LOCK_EXCLUSIVE
  187332. && (p->bNolock || (pRbu && pRbu->eStage!=RBU_STAGE_DONE))
  187333. ){
  187334. /* Do not allow EXCLUSIVE locks. Preventing SQLite from taking this
  187335. ** prevents it from checkpointing the database from sqlite3_close(). */
  187336. rc = SQLITE_BUSY;
  187337. }else{
  187338. rc = p->pReal->pMethods->xLock(p->pReal, eLock);
  187339. }
  187340. return rc;
  187341. }
  187342. /*
  187343. ** Unlock an rbuVfs-file.
  187344. */
  187345. static int rbuVfsUnlock(sqlite3_file *pFile, int eLock){
  187346. rbu_file *p = (rbu_file *)pFile;
  187347. return p->pReal->pMethods->xUnlock(p->pReal, eLock);
  187348. }
  187349. /*
  187350. ** Check if another file-handle holds a RESERVED lock on an rbuVfs-file.
  187351. */
  187352. static int rbuVfsCheckReservedLock(sqlite3_file *pFile, int *pResOut){
  187353. rbu_file *p = (rbu_file *)pFile;
  187354. return p->pReal->pMethods->xCheckReservedLock(p->pReal, pResOut);
  187355. }
  187356. /*
  187357. ** File control method. For custom operations on an rbuVfs-file.
  187358. */
  187359. static int rbuVfsFileControl(sqlite3_file *pFile, int op, void *pArg){
  187360. rbu_file *p = (rbu_file *)pFile;
  187361. int (*xControl)(sqlite3_file*,int,void*) = p->pReal->pMethods->xFileControl;
  187362. int rc;
  187363. assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB)
  187364. || p->openFlags & (SQLITE_OPEN_TRANSIENT_DB|SQLITE_OPEN_TEMP_JOURNAL)
  187365. );
  187366. if( op==SQLITE_FCNTL_RBU ){
  187367. sqlite3rbu *pRbu = (sqlite3rbu*)pArg;
  187368. /* First try to find another RBU vfs lower down in the vfs stack. If
  187369. ** one is found, this vfs will operate in pass-through mode. The lower
  187370. ** level vfs will do the special RBU handling. */
  187371. rc = xControl(p->pReal, op, pArg);
  187372. if( rc==SQLITE_NOTFOUND ){
  187373. /* Now search for a zipvfs instance lower down in the VFS stack. If
  187374. ** one is found, this is an error. */
  187375. void *dummy = 0;
  187376. rc = xControl(p->pReal, SQLITE_FCNTL_ZIPVFS, &dummy);
  187377. if( rc==SQLITE_OK ){
  187378. rc = SQLITE_ERROR;
  187379. pRbu->zErrmsg = sqlite3_mprintf("rbu/zipvfs setup error");
  187380. }else if( rc==SQLITE_NOTFOUND ){
  187381. pRbu->pTargetFd = p;
  187382. p->pRbu = pRbu;
  187383. rbuMainlistAdd(p);
  187384. if( p->pWalFd ) p->pWalFd->pRbu = pRbu;
  187385. rc = SQLITE_OK;
  187386. }
  187387. }
  187388. return rc;
  187389. }
  187390. else if( op==SQLITE_FCNTL_RBUCNT ){
  187391. sqlite3rbu *pRbu = (sqlite3rbu*)pArg;
  187392. pRbu->nRbu++;
  187393. pRbu->pRbuFd = p;
  187394. p->bNolock = 1;
  187395. }
  187396. rc = xControl(p->pReal, op, pArg);
  187397. if( rc==SQLITE_OK && op==SQLITE_FCNTL_VFSNAME ){
  187398. rbu_vfs *pRbuVfs = p->pRbuVfs;
  187399. char *zIn = *(char**)pArg;
  187400. char *zOut = sqlite3_mprintf("rbu(%s)/%z", pRbuVfs->base.zName, zIn);
  187401. *(char**)pArg = zOut;
  187402. if( zOut==0 ) rc = SQLITE_NOMEM;
  187403. }
  187404. return rc;
  187405. }
  187406. /*
  187407. ** Return the sector-size in bytes for an rbuVfs-file.
  187408. */
  187409. static int rbuVfsSectorSize(sqlite3_file *pFile){
  187410. rbu_file *p = (rbu_file *)pFile;
  187411. return p->pReal->pMethods->xSectorSize(p->pReal);
  187412. }
  187413. /*
  187414. ** Return the device characteristic flags supported by an rbuVfs-file.
  187415. */
  187416. static int rbuVfsDeviceCharacteristics(sqlite3_file *pFile){
  187417. rbu_file *p = (rbu_file *)pFile;
  187418. return p->pReal->pMethods->xDeviceCharacteristics(p->pReal);
  187419. }
  187420. /*
  187421. ** Take or release a shared-memory lock.
  187422. */
  187423. static int rbuVfsShmLock(sqlite3_file *pFile, int ofst, int n, int flags){
  187424. rbu_file *p = (rbu_file*)pFile;
  187425. sqlite3rbu *pRbu = p->pRbu;
  187426. int rc = SQLITE_OK;
  187427. #ifdef SQLITE_AMALGAMATION
  187428. assert( WAL_CKPT_LOCK==1 );
  187429. #endif
  187430. assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
  187431. if( pRbu && (pRbu->eStage==RBU_STAGE_OAL || pRbu->eStage==RBU_STAGE_MOVE) ){
  187432. /* Magic number 1 is the WAL_CKPT_LOCK lock. Preventing SQLite from
  187433. ** taking this lock also prevents any checkpoints from occurring.
  187434. ** todo: really, it's not clear why this might occur, as
  187435. ** wal_autocheckpoint ought to be turned off. */
  187436. if( ofst==WAL_LOCK_CKPT && n==1 ) rc = SQLITE_BUSY;
  187437. }else{
  187438. int bCapture = 0;
  187439. if( pRbu && pRbu->eStage==RBU_STAGE_CAPTURE ){
  187440. bCapture = 1;
  187441. }
  187442. if( bCapture==0 || 0==(flags & SQLITE_SHM_UNLOCK) ){
  187443. rc = p->pReal->pMethods->xShmLock(p->pReal, ofst, n, flags);
  187444. if( bCapture && rc==SQLITE_OK ){
  187445. pRbu->mLock |= (1 << ofst);
  187446. }
  187447. }
  187448. }
  187449. return rc;
  187450. }
  187451. /*
  187452. ** Obtain a pointer to a mapping of a single 32KiB page of the *-shm file.
  187453. */
  187454. static int rbuVfsShmMap(
  187455. sqlite3_file *pFile,
  187456. int iRegion,
  187457. int szRegion,
  187458. int isWrite,
  187459. void volatile **pp
  187460. ){
  187461. rbu_file *p = (rbu_file*)pFile;
  187462. int rc = SQLITE_OK;
  187463. int eStage = (p->pRbu ? p->pRbu->eStage : 0);
  187464. /* If not in RBU_STAGE_OAL, allow this call to pass through. Or, if this
  187465. ** rbu is in the RBU_STAGE_OAL state, use heap memory for *-shm space
  187466. ** instead of a file on disk. */
  187467. assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
  187468. if( eStage==RBU_STAGE_OAL ){
  187469. sqlite3_int64 nByte = (iRegion+1) * sizeof(char*);
  187470. char **apNew = (char**)sqlite3_realloc64(p->apShm, nByte);
  187471. /* This is an RBU connection that uses its own heap memory for the
  187472. ** pages of the *-shm file. Since no other process can have run
  187473. ** recovery, the connection must request *-shm pages in order
  187474. ** from start to finish. */
  187475. assert( iRegion==p->nShm );
  187476. if( apNew==0 ){
  187477. rc = SQLITE_NOMEM;
  187478. }else{
  187479. memset(&apNew[p->nShm], 0, sizeof(char*) * (1 + iRegion - p->nShm));
  187480. p->apShm = apNew;
  187481. p->nShm = iRegion+1;
  187482. }
  187483. if( rc==SQLITE_OK ){
  187484. char *pNew = (char*)sqlite3_malloc64(szRegion);
  187485. if( pNew==0 ){
  187486. rc = SQLITE_NOMEM;
  187487. }else{
  187488. memset(pNew, 0, szRegion);
  187489. p->apShm[iRegion] = pNew;
  187490. }
  187491. }
  187492. if( rc==SQLITE_OK ){
  187493. *pp = p->apShm[iRegion];
  187494. }else{
  187495. *pp = 0;
  187496. }
  187497. }else{
  187498. assert( p->apShm==0 );
  187499. rc = p->pReal->pMethods->xShmMap(p->pReal, iRegion, szRegion, isWrite, pp);
  187500. }
  187501. return rc;
  187502. }
  187503. /*
  187504. ** Memory barrier.
  187505. */
  187506. static void rbuVfsShmBarrier(sqlite3_file *pFile){
  187507. rbu_file *p = (rbu_file *)pFile;
  187508. p->pReal->pMethods->xShmBarrier(p->pReal);
  187509. }
  187510. /*
  187511. ** The xShmUnmap method.
  187512. */
  187513. static int rbuVfsShmUnmap(sqlite3_file *pFile, int delFlag){
  187514. rbu_file *p = (rbu_file*)pFile;
  187515. int rc = SQLITE_OK;
  187516. int eStage = (p->pRbu ? p->pRbu->eStage : 0);
  187517. assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
  187518. if( eStage==RBU_STAGE_OAL || eStage==RBU_STAGE_MOVE ){
  187519. /* no-op */
  187520. }else{
  187521. /* Release the checkpointer and writer locks */
  187522. rbuUnlockShm(p);
  187523. rc = p->pReal->pMethods->xShmUnmap(p->pReal, delFlag);
  187524. }
  187525. return rc;
  187526. }
  187527. /*
  187528. ** Open an rbu file handle.
  187529. */
  187530. static int rbuVfsOpen(
  187531. sqlite3_vfs *pVfs,
  187532. const char *zName,
  187533. sqlite3_file *pFile,
  187534. int flags,
  187535. int *pOutFlags
  187536. ){
  187537. static sqlite3_io_methods rbuvfs_io_methods = {
  187538. 2, /* iVersion */
  187539. rbuVfsClose, /* xClose */
  187540. rbuVfsRead, /* xRead */
  187541. rbuVfsWrite, /* xWrite */
  187542. rbuVfsTruncate, /* xTruncate */
  187543. rbuVfsSync, /* xSync */
  187544. rbuVfsFileSize, /* xFileSize */
  187545. rbuVfsLock, /* xLock */
  187546. rbuVfsUnlock, /* xUnlock */
  187547. rbuVfsCheckReservedLock, /* xCheckReservedLock */
  187548. rbuVfsFileControl, /* xFileControl */
  187549. rbuVfsSectorSize, /* xSectorSize */
  187550. rbuVfsDeviceCharacteristics, /* xDeviceCharacteristics */
  187551. rbuVfsShmMap, /* xShmMap */
  187552. rbuVfsShmLock, /* xShmLock */
  187553. rbuVfsShmBarrier, /* xShmBarrier */
  187554. rbuVfsShmUnmap, /* xShmUnmap */
  187555. 0, 0 /* xFetch, xUnfetch */
  187556. };
  187557. rbu_vfs *pRbuVfs = (rbu_vfs*)pVfs;
  187558. sqlite3_vfs *pRealVfs = pRbuVfs->pRealVfs;
  187559. rbu_file *pFd = (rbu_file *)pFile;
  187560. int rc = SQLITE_OK;
  187561. const char *zOpen = zName;
  187562. int oflags = flags;
  187563. memset(pFd, 0, sizeof(rbu_file));
  187564. pFd->pReal = (sqlite3_file*)&pFd[1];
  187565. pFd->pRbuVfs = pRbuVfs;
  187566. pFd->openFlags = flags;
  187567. if( zName ){
  187568. if( flags & SQLITE_OPEN_MAIN_DB ){
  187569. /* A main database has just been opened. The following block sets
  187570. ** (pFd->zWal) to point to a buffer owned by SQLite that contains
  187571. ** the name of the *-wal file this db connection will use. SQLite
  187572. ** happens to pass a pointer to this buffer when using xAccess()
  187573. ** or xOpen() to operate on the *-wal file. */
  187574. pFd->zWal = sqlite3_filename_wal(zName);
  187575. }
  187576. else if( flags & SQLITE_OPEN_WAL ){
  187577. rbu_file *pDb = rbuFindMaindb(pRbuVfs, zName, 0);
  187578. if( pDb ){
  187579. if( pDb->pRbu && pDb->pRbu->eStage==RBU_STAGE_OAL ){
  187580. /* This call is to open a *-wal file. Intead, open the *-oal. This
  187581. ** code ensures that the string passed to xOpen() is terminated by a
  187582. ** pair of '\0' bytes in case the VFS attempts to extract a URI
  187583. ** parameter from it. */
  187584. const char *zBase = zName;
  187585. size_t nCopy;
  187586. char *zCopy;
  187587. if( rbuIsVacuum(pDb->pRbu) ){
  187588. zBase = sqlite3_db_filename(pDb->pRbu->dbRbu, "main");
  187589. zBase = sqlite3_filename_wal(zBase);
  187590. }
  187591. nCopy = strlen(zBase);
  187592. zCopy = sqlite3_malloc64(nCopy+2);
  187593. if( zCopy ){
  187594. memcpy(zCopy, zBase, nCopy);
  187595. zCopy[nCopy-3] = 'o';
  187596. zCopy[nCopy] = '\0';
  187597. zCopy[nCopy+1] = '\0';
  187598. zOpen = (const char*)(pFd->zDel = zCopy);
  187599. }else{
  187600. rc = SQLITE_NOMEM;
  187601. }
  187602. pFd->pRbu = pDb->pRbu;
  187603. }
  187604. pDb->pWalFd = pFd;
  187605. }
  187606. }
  187607. }else{
  187608. pFd->pRbu = pRbuVfs->pRbu;
  187609. }
  187610. if( oflags & SQLITE_OPEN_MAIN_DB
  187611. && sqlite3_uri_boolean(zName, "rbu_memory", 0)
  187612. ){
  187613. assert( oflags & SQLITE_OPEN_MAIN_DB );
  187614. oflags = SQLITE_OPEN_TEMP_DB | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
  187615. SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
  187616. zOpen = 0;
  187617. }
  187618. if( rc==SQLITE_OK ){
  187619. rc = pRealVfs->xOpen(pRealVfs, zOpen, pFd->pReal, oflags, pOutFlags);
  187620. }
  187621. if( pFd->pReal->pMethods ){
  187622. /* The xOpen() operation has succeeded. Set the sqlite3_file.pMethods
  187623. ** pointer and, if the file is a main database file, link it into the
  187624. ** mutex protected linked list of all such files. */
  187625. pFile->pMethods = &rbuvfs_io_methods;
  187626. if( flags & SQLITE_OPEN_MAIN_DB ){
  187627. rbuMainlistAdd(pFd);
  187628. }
  187629. }else{
  187630. sqlite3_free(pFd->zDel);
  187631. }
  187632. return rc;
  187633. }
  187634. /*
  187635. ** Delete the file located at zPath.
  187636. */
  187637. static int rbuVfsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
  187638. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  187639. return pRealVfs->xDelete(pRealVfs, zPath, dirSync);
  187640. }
  187641. /*
  187642. ** Test for access permissions. Return true if the requested permission
  187643. ** is available, or false otherwise.
  187644. */
  187645. static int rbuVfsAccess(
  187646. sqlite3_vfs *pVfs,
  187647. const char *zPath,
  187648. int flags,
  187649. int *pResOut
  187650. ){
  187651. rbu_vfs *pRbuVfs = (rbu_vfs*)pVfs;
  187652. sqlite3_vfs *pRealVfs = pRbuVfs->pRealVfs;
  187653. int rc;
  187654. rc = pRealVfs->xAccess(pRealVfs, zPath, flags, pResOut);
  187655. /* If this call is to check if a *-wal file associated with an RBU target
  187656. ** database connection exists, and the RBU update is in RBU_STAGE_OAL,
  187657. ** the following special handling is activated:
  187658. **
  187659. ** a) if the *-wal file does exist, return SQLITE_CANTOPEN. This
  187660. ** ensures that the RBU extension never tries to update a database
  187661. ** in wal mode, even if the first page of the database file has
  187662. ** been damaged.
  187663. **
  187664. ** b) if the *-wal file does not exist, claim that it does anyway,
  187665. ** causing SQLite to call xOpen() to open it. This call will also
  187666. ** be intercepted (see the rbuVfsOpen() function) and the *-oal
  187667. ** file opened instead.
  187668. */
  187669. if( rc==SQLITE_OK && flags==SQLITE_ACCESS_EXISTS ){
  187670. rbu_file *pDb = rbuFindMaindb(pRbuVfs, zPath, 1);
  187671. if( pDb && pDb->pRbu->eStage==RBU_STAGE_OAL ){
  187672. assert( pDb->pRbu );
  187673. if( *pResOut ){
  187674. rc = SQLITE_CANTOPEN;
  187675. }else{
  187676. sqlite3_int64 sz = 0;
  187677. rc = rbuVfsFileSize(&pDb->base, &sz);
  187678. *pResOut = (sz>0);
  187679. }
  187680. }
  187681. }
  187682. return rc;
  187683. }
  187684. /*
  187685. ** Populate buffer zOut with the full canonical pathname corresponding
  187686. ** to the pathname in zPath. zOut is guaranteed to point to a buffer
  187687. ** of at least (DEVSYM_MAX_PATHNAME+1) bytes.
  187688. */
  187689. static int rbuVfsFullPathname(
  187690. sqlite3_vfs *pVfs,
  187691. const char *zPath,
  187692. int nOut,
  187693. char *zOut
  187694. ){
  187695. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  187696. return pRealVfs->xFullPathname(pRealVfs, zPath, nOut, zOut);
  187697. }
  187698. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  187699. /*
  187700. ** Open the dynamic library located at zPath and return a handle.
  187701. */
  187702. static void *rbuVfsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
  187703. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  187704. return pRealVfs->xDlOpen(pRealVfs, zPath);
  187705. }
  187706. /*
  187707. ** Populate the buffer zErrMsg (size nByte bytes) with a human readable
  187708. ** utf-8 string describing the most recent error encountered associated
  187709. ** with dynamic libraries.
  187710. */
  187711. static void rbuVfsDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){
  187712. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  187713. pRealVfs->xDlError(pRealVfs, nByte, zErrMsg);
  187714. }
  187715. /*
  187716. ** Return a pointer to the symbol zSymbol in the dynamic library pHandle.
  187717. */
  187718. static void (*rbuVfsDlSym(
  187719. sqlite3_vfs *pVfs,
  187720. void *pArg,
  187721. const char *zSym
  187722. ))(void){
  187723. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  187724. return pRealVfs->xDlSym(pRealVfs, pArg, zSym);
  187725. }
  187726. /*
  187727. ** Close the dynamic library handle pHandle.
  187728. */
  187729. static void rbuVfsDlClose(sqlite3_vfs *pVfs, void *pHandle){
  187730. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  187731. pRealVfs->xDlClose(pRealVfs, pHandle);
  187732. }
  187733. #endif /* SQLITE_OMIT_LOAD_EXTENSION */
  187734. /*
  187735. ** Populate the buffer pointed to by zBufOut with nByte bytes of
  187736. ** random data.
  187737. */
  187738. static int rbuVfsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
  187739. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  187740. return pRealVfs->xRandomness(pRealVfs, nByte, zBufOut);
  187741. }
  187742. /*
  187743. ** Sleep for nMicro microseconds. Return the number of microseconds
  187744. ** actually slept.
  187745. */
  187746. static int rbuVfsSleep(sqlite3_vfs *pVfs, int nMicro){
  187747. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  187748. return pRealVfs->xSleep(pRealVfs, nMicro);
  187749. }
  187750. /*
  187751. ** Return the current time as a Julian Day number in *pTimeOut.
  187752. */
  187753. static int rbuVfsCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){
  187754. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  187755. return pRealVfs->xCurrentTime(pRealVfs, pTimeOut);
  187756. }
  187757. /*
  187758. ** No-op.
  187759. */
  187760. static int rbuVfsGetLastError(sqlite3_vfs *pVfs, int a, char *b){
  187761. return 0;
  187762. }
  187763. /*
  187764. ** Deregister and destroy an RBU vfs created by an earlier call to
  187765. ** sqlite3rbu_create_vfs().
  187766. */
  187767. SQLITE_API void sqlite3rbu_destroy_vfs(const char *zName){
  187768. sqlite3_vfs *pVfs = sqlite3_vfs_find(zName);
  187769. if( pVfs && pVfs->xOpen==rbuVfsOpen ){
  187770. sqlite3_mutex_free(((rbu_vfs*)pVfs)->mutex);
  187771. sqlite3_vfs_unregister(pVfs);
  187772. sqlite3_free(pVfs);
  187773. }
  187774. }
  187775. /*
  187776. ** Create an RBU VFS named zName that accesses the underlying file-system
  187777. ** via existing VFS zParent. The new object is registered as a non-default
  187778. ** VFS with SQLite before returning.
  187779. */
  187780. SQLITE_API int sqlite3rbu_create_vfs(const char *zName, const char *zParent){
  187781. /* Template for VFS */
  187782. static sqlite3_vfs vfs_template = {
  187783. 1, /* iVersion */
  187784. 0, /* szOsFile */
  187785. 0, /* mxPathname */
  187786. 0, /* pNext */
  187787. 0, /* zName */
  187788. 0, /* pAppData */
  187789. rbuVfsOpen, /* xOpen */
  187790. rbuVfsDelete, /* xDelete */
  187791. rbuVfsAccess, /* xAccess */
  187792. rbuVfsFullPathname, /* xFullPathname */
  187793. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  187794. rbuVfsDlOpen, /* xDlOpen */
  187795. rbuVfsDlError, /* xDlError */
  187796. rbuVfsDlSym, /* xDlSym */
  187797. rbuVfsDlClose, /* xDlClose */
  187798. #else
  187799. 0, 0, 0, 0,
  187800. #endif
  187801. rbuVfsRandomness, /* xRandomness */
  187802. rbuVfsSleep, /* xSleep */
  187803. rbuVfsCurrentTime, /* xCurrentTime */
  187804. rbuVfsGetLastError, /* xGetLastError */
  187805. 0, /* xCurrentTimeInt64 (version 2) */
  187806. 0, 0, 0 /* Unimplemented version 3 methods */
  187807. };
  187808. rbu_vfs *pNew = 0; /* Newly allocated VFS */
  187809. int rc = SQLITE_OK;
  187810. size_t nName;
  187811. size_t nByte;
  187812. nName = strlen(zName);
  187813. nByte = sizeof(rbu_vfs) + nName + 1;
  187814. pNew = (rbu_vfs*)sqlite3_malloc64(nByte);
  187815. if( pNew==0 ){
  187816. rc = SQLITE_NOMEM;
  187817. }else{
  187818. sqlite3_vfs *pParent; /* Parent VFS */
  187819. memset(pNew, 0, nByte);
  187820. pParent = sqlite3_vfs_find(zParent);
  187821. if( pParent==0 ){
  187822. rc = SQLITE_NOTFOUND;
  187823. }else{
  187824. char *zSpace;
  187825. memcpy(&pNew->base, &vfs_template, sizeof(sqlite3_vfs));
  187826. pNew->base.mxPathname = pParent->mxPathname;
  187827. pNew->base.szOsFile = sizeof(rbu_file) + pParent->szOsFile;
  187828. pNew->pRealVfs = pParent;
  187829. pNew->base.zName = (const char*)(zSpace = (char*)&pNew[1]);
  187830. memcpy(zSpace, zName, nName);
  187831. /* Allocate the mutex and register the new VFS (not as the default) */
  187832. pNew->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_RECURSIVE);
  187833. if( pNew->mutex==0 ){
  187834. rc = SQLITE_NOMEM;
  187835. }else{
  187836. rc = sqlite3_vfs_register(&pNew->base, 0);
  187837. }
  187838. }
  187839. if( rc!=SQLITE_OK ){
  187840. sqlite3_mutex_free(pNew->mutex);
  187841. sqlite3_free(pNew);
  187842. }
  187843. }
  187844. return rc;
  187845. }
  187846. /*
  187847. ** Configure the aggregate temp file size limit for this RBU handle.
  187848. */
  187849. SQLITE_API sqlite3_int64 sqlite3rbu_temp_size_limit(sqlite3rbu *pRbu, sqlite3_int64 n){
  187850. if( n>=0 ){
  187851. pRbu->szTempLimit = n;
  187852. }
  187853. return pRbu->szTempLimit;
  187854. }
  187855. SQLITE_API sqlite3_int64 sqlite3rbu_temp_size(sqlite3rbu *pRbu){
  187856. return pRbu->szTemp;
  187857. }
  187858. /**************************************************************************/
  187859. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RBU) */
  187860. /************** End of sqlite3rbu.c ******************************************/
  187861. /************** Begin file dbstat.c ******************************************/
  187862. /*
  187863. ** 2010 July 12
  187864. **
  187865. ** The author disclaims copyright to this source code. In place of
  187866. ** a legal notice, here is a blessing:
  187867. **
  187868. ** May you do good and not evil.
  187869. ** May you find forgiveness for yourself and forgive others.
  187870. ** May you share freely, never taking more than you give.
  187871. **
  187872. ******************************************************************************
  187873. **
  187874. ** This file contains an implementation of the "dbstat" virtual table.
  187875. **
  187876. ** The dbstat virtual table is used to extract low-level storage
  187877. ** information from an SQLite database in order to implement the
  187878. ** "sqlite3_analyzer" utility. See the ../tool/spaceanal.tcl script
  187879. ** for an example implementation.
  187880. **
  187881. ** Additional information is available on the "dbstat.html" page of the
  187882. ** official SQLite documentation.
  187883. */
  187884. /* #include "sqliteInt.h" ** Requires access to internal data structures ** */
  187885. #if (defined(SQLITE_ENABLE_DBSTAT_VTAB) || defined(SQLITE_TEST)) \
  187886. && !defined(SQLITE_OMIT_VIRTUALTABLE)
  187887. /*
  187888. ** Page paths:
  187889. **
  187890. ** The value of the 'path' column describes the path taken from the
  187891. ** root-node of the b-tree structure to each page. The value of the
  187892. ** root-node path is '/'.
  187893. **
  187894. ** The value of the path for the left-most child page of the root of
  187895. ** a b-tree is '/000/'. (Btrees store content ordered from left to right
  187896. ** so the pages to the left have smaller keys than the pages to the right.)
  187897. ** The next to left-most child of the root page is
  187898. ** '/001', and so on, each sibling page identified by a 3-digit hex
  187899. ** value. The children of the 451st left-most sibling have paths such
  187900. ** as '/1c2/000/, '/1c2/001/' etc.
  187901. **
  187902. ** Overflow pages are specified by appending a '+' character and a
  187903. ** six-digit hexadecimal value to the path to the cell they are linked
  187904. ** from. For example, the three overflow pages in a chain linked from
  187905. ** the left-most cell of the 450th child of the root page are identified
  187906. ** by the paths:
  187907. **
  187908. ** '/1c2/000+000000' // First page in overflow chain
  187909. ** '/1c2/000+000001' // Second page in overflow chain
  187910. ** '/1c2/000+000002' // Third page in overflow chain
  187911. **
  187912. ** If the paths are sorted using the BINARY collation sequence, then
  187913. ** the overflow pages associated with a cell will appear earlier in the
  187914. ** sort-order than its child page:
  187915. **
  187916. ** '/1c2/000/' // Left-most child of 451st child of root
  187917. */
  187918. static const char zDbstatSchema[] =
  187919. "CREATE TABLE x("
  187920. " name TEXT," /* 0 Name of table or index */
  187921. " path TEXT," /* 1 Path to page from root (NULL for agg) */
  187922. " pageno INTEGER," /* 2 Page number (page count for aggregates) */
  187923. " pagetype TEXT," /* 3 'internal', 'leaf', 'overflow', or NULL */
  187924. " ncell INTEGER," /* 4 Cells on page (0 for overflow) */
  187925. " payload INTEGER," /* 5 Bytes of payload on this page */
  187926. " unused INTEGER," /* 6 Bytes of unused space on this page */
  187927. " mx_payload INTEGER," /* 7 Largest payload size of all cells */
  187928. " pgoffset INTEGER," /* 8 Offset of page in file (NULL for agg) */
  187929. " pgsize INTEGER," /* 9 Size of the page (sum for aggregate) */
  187930. " schema TEXT HIDDEN," /* 10 Database schema being analyzed */
  187931. " aggregate BOOLEAN HIDDEN" /* 11 aggregate info for each table */
  187932. ")"
  187933. ;
  187934. /* Forward reference to data structured used in this module */
  187935. typedef struct StatTable StatTable;
  187936. typedef struct StatCursor StatCursor;
  187937. typedef struct StatPage StatPage;
  187938. typedef struct StatCell StatCell;
  187939. /* Size information for a single cell within a btree page */
  187940. struct StatCell {
  187941. int nLocal; /* Bytes of local payload */
  187942. u32 iChildPg; /* Child node (or 0 if this is a leaf) */
  187943. int nOvfl; /* Entries in aOvfl[] */
  187944. u32 *aOvfl; /* Array of overflow page numbers */
  187945. int nLastOvfl; /* Bytes of payload on final overflow page */
  187946. int iOvfl; /* Iterates through aOvfl[] */
  187947. };
  187948. /* Size information for a single btree page */
  187949. struct StatPage {
  187950. u32 iPgno; /* Page number */
  187951. DbPage *pPg; /* Page content */
  187952. int iCell; /* Current cell */
  187953. char *zPath; /* Path to this page */
  187954. /* Variables populated by statDecodePage(): */
  187955. u8 flags; /* Copy of flags byte */
  187956. int nCell; /* Number of cells on page */
  187957. int nUnused; /* Number of unused bytes on page */
  187958. StatCell *aCell; /* Array of parsed cells */
  187959. u32 iRightChildPg; /* Right-child page number (or 0) */
  187960. int nMxPayload; /* Largest payload of any cell on the page */
  187961. };
  187962. /* The cursor for scanning the dbstat virtual table */
  187963. struct StatCursor {
  187964. sqlite3_vtab_cursor base; /* base class. MUST BE FIRST! */
  187965. sqlite3_stmt *pStmt; /* Iterates through set of root pages */
  187966. u8 isEof; /* After pStmt has returned SQLITE_DONE */
  187967. u8 isAgg; /* Aggregate results for each table */
  187968. int iDb; /* Schema used for this query */
  187969. StatPage aPage[32]; /* Pages in path to current page */
  187970. int iPage; /* Current entry in aPage[] */
  187971. /* Values to return. */
  187972. u32 iPageno; /* Value of 'pageno' column */
  187973. char *zName; /* Value of 'name' column */
  187974. char *zPath; /* Value of 'path' column */
  187975. char *zPagetype; /* Value of 'pagetype' column */
  187976. int nPage; /* Number of pages in current btree */
  187977. int nCell; /* Value of 'ncell' column */
  187978. int nMxPayload; /* Value of 'mx_payload' column */
  187979. i64 nUnused; /* Value of 'unused' column */
  187980. i64 nPayload; /* Value of 'payload' column */
  187981. i64 iOffset; /* Value of 'pgOffset' column */
  187982. i64 szPage; /* Value of 'pgSize' column */
  187983. };
  187984. /* An instance of the DBSTAT virtual table */
  187985. struct StatTable {
  187986. sqlite3_vtab base; /* base class. MUST BE FIRST! */
  187987. sqlite3 *db; /* Database connection that owns this vtab */
  187988. int iDb; /* Index of database to analyze */
  187989. };
  187990. #ifndef get2byte
  187991. # define get2byte(x) ((x)[0]<<8 | (x)[1])
  187992. #endif
  187993. /*
  187994. ** Connect to or create a new DBSTAT virtual table.
  187995. */
  187996. static int statConnect(
  187997. sqlite3 *db,
  187998. void *pAux,
  187999. int argc, const char *const*argv,
  188000. sqlite3_vtab **ppVtab,
  188001. char **pzErr
  188002. ){
  188003. StatTable *pTab = 0;
  188004. int rc = SQLITE_OK;
  188005. int iDb;
  188006. if( argc>=4 ){
  188007. Token nm;
  188008. sqlite3TokenInit(&nm, (char*)argv[3]);
  188009. iDb = sqlite3FindDb(db, &nm);
  188010. if( iDb<0 ){
  188011. *pzErr = sqlite3_mprintf("no such database: %s", argv[3]);
  188012. return SQLITE_ERROR;
  188013. }
  188014. }else{
  188015. iDb = 0;
  188016. }
  188017. sqlite3_vtab_config(db, SQLITE_VTAB_DIRECTONLY);
  188018. rc = sqlite3_declare_vtab(db, zDbstatSchema);
  188019. if( rc==SQLITE_OK ){
  188020. pTab = (StatTable *)sqlite3_malloc64(sizeof(StatTable));
  188021. if( pTab==0 ) rc = SQLITE_NOMEM_BKPT;
  188022. }
  188023. assert( rc==SQLITE_OK || pTab==0 );
  188024. if( rc==SQLITE_OK ){
  188025. memset(pTab, 0, sizeof(StatTable));
  188026. pTab->db = db;
  188027. pTab->iDb = iDb;
  188028. }
  188029. *ppVtab = (sqlite3_vtab*)pTab;
  188030. return rc;
  188031. }
  188032. /*
  188033. ** Disconnect from or destroy the DBSTAT virtual table.
  188034. */
  188035. static int statDisconnect(sqlite3_vtab *pVtab){
  188036. sqlite3_free(pVtab);
  188037. return SQLITE_OK;
  188038. }
  188039. /*
  188040. ** Compute the best query strategy and return the result in idxNum.
  188041. **
  188042. ** idxNum-Bit Meaning
  188043. ** ---------- ----------------------------------------------
  188044. ** 0x01 There is a schema=? term in the WHERE clause
  188045. ** 0x02 There is a name=? term in the WHERE clause
  188046. ** 0x04 There is an aggregate=? term in the WHERE clause
  188047. ** 0x08 Output should be ordered by name and path
  188048. */
  188049. static int statBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
  188050. int i;
  188051. int iSchema = -1;
  188052. int iName = -1;
  188053. int iAgg = -1;
  188054. /* Look for a valid schema=? constraint. If found, change the idxNum to
  188055. ** 1 and request the value of that constraint be sent to xFilter. And
  188056. ** lower the cost estimate to encourage the constrained version to be
  188057. ** used.
  188058. */
  188059. for(i=0; i<pIdxInfo->nConstraint; i++){
  188060. if( pIdxInfo->aConstraint[i].op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
  188061. if( pIdxInfo->aConstraint[i].usable==0 ){
  188062. /* Force DBSTAT table should always be the right-most table in a join */
  188063. return SQLITE_CONSTRAINT;
  188064. }
  188065. switch( pIdxInfo->aConstraint[i].iColumn ){
  188066. case 0: { /* name */
  188067. iName = i;
  188068. break;
  188069. }
  188070. case 10: { /* schema */
  188071. iSchema = i;
  188072. break;
  188073. }
  188074. case 11: { /* aggregate */
  188075. iAgg = i;
  188076. break;
  188077. }
  188078. }
  188079. }
  188080. i = 0;
  188081. if( iSchema>=0 ){
  188082. pIdxInfo->aConstraintUsage[iSchema].argvIndex = ++i;
  188083. pIdxInfo->aConstraintUsage[iSchema].omit = 1;
  188084. pIdxInfo->idxNum |= 0x01;
  188085. }
  188086. if( iName>=0 ){
  188087. pIdxInfo->aConstraintUsage[iName].argvIndex = ++i;
  188088. pIdxInfo->idxNum |= 0x02;
  188089. }
  188090. if( iAgg>=0 ){
  188091. pIdxInfo->aConstraintUsage[iAgg].argvIndex = ++i;
  188092. pIdxInfo->idxNum |= 0x04;
  188093. }
  188094. pIdxInfo->estimatedCost = 1.0;
  188095. /* Records are always returned in ascending order of (name, path).
  188096. ** If this will satisfy the client, set the orderByConsumed flag so that
  188097. ** SQLite does not do an external sort.
  188098. */
  188099. if( ( pIdxInfo->nOrderBy==1
  188100. && pIdxInfo->aOrderBy[0].iColumn==0
  188101. && pIdxInfo->aOrderBy[0].desc==0
  188102. ) ||
  188103. ( pIdxInfo->nOrderBy==2
  188104. && pIdxInfo->aOrderBy[0].iColumn==0
  188105. && pIdxInfo->aOrderBy[0].desc==0
  188106. && pIdxInfo->aOrderBy[1].iColumn==1
  188107. && pIdxInfo->aOrderBy[1].desc==0
  188108. )
  188109. ){
  188110. pIdxInfo->orderByConsumed = 1;
  188111. pIdxInfo->idxNum |= 0x08;
  188112. }
  188113. return SQLITE_OK;
  188114. }
  188115. /*
  188116. ** Open a new DBSTAT cursor.
  188117. */
  188118. static int statOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
  188119. StatTable *pTab = (StatTable *)pVTab;
  188120. StatCursor *pCsr;
  188121. pCsr = (StatCursor *)sqlite3_malloc64(sizeof(StatCursor));
  188122. if( pCsr==0 ){
  188123. return SQLITE_NOMEM_BKPT;
  188124. }else{
  188125. memset(pCsr, 0, sizeof(StatCursor));
  188126. pCsr->base.pVtab = pVTab;
  188127. pCsr->iDb = pTab->iDb;
  188128. }
  188129. *ppCursor = (sqlite3_vtab_cursor *)pCsr;
  188130. return SQLITE_OK;
  188131. }
  188132. static void statClearCells(StatPage *p){
  188133. int i;
  188134. if( p->aCell ){
  188135. for(i=0; i<p->nCell; i++){
  188136. sqlite3_free(p->aCell[i].aOvfl);
  188137. }
  188138. sqlite3_free(p->aCell);
  188139. }
  188140. p->nCell = 0;
  188141. p->aCell = 0;
  188142. }
  188143. static void statClearPage(StatPage *p){
  188144. statClearCells(p);
  188145. sqlite3PagerUnref(p->pPg);
  188146. sqlite3_free(p->zPath);
  188147. memset(p, 0, sizeof(StatPage));
  188148. }
  188149. static void statResetCsr(StatCursor *pCsr){
  188150. int i;
  188151. sqlite3_reset(pCsr->pStmt);
  188152. for(i=0; i<ArraySize(pCsr->aPage); i++){
  188153. statClearPage(&pCsr->aPage[i]);
  188154. }
  188155. pCsr->iPage = 0;
  188156. sqlite3_free(pCsr->zPath);
  188157. pCsr->zPath = 0;
  188158. pCsr->isEof = 0;
  188159. }
  188160. /* Resize the space-used counters inside of the cursor */
  188161. static void statResetCounts(StatCursor *pCsr){
  188162. pCsr->nCell = 0;
  188163. pCsr->nMxPayload = 0;
  188164. pCsr->nUnused = 0;
  188165. pCsr->nPayload = 0;
  188166. pCsr->szPage = 0;
  188167. pCsr->nPage = 0;
  188168. }
  188169. /*
  188170. ** Close a DBSTAT cursor.
  188171. */
  188172. static int statClose(sqlite3_vtab_cursor *pCursor){
  188173. StatCursor *pCsr = (StatCursor *)pCursor;
  188174. statResetCsr(pCsr);
  188175. sqlite3_finalize(pCsr->pStmt);
  188176. sqlite3_free(pCsr);
  188177. return SQLITE_OK;
  188178. }
  188179. /*
  188180. ** For a single cell on a btree page, compute the number of bytes of
  188181. ** content (payload) stored on that page. That is to say, compute the
  188182. ** number of bytes of content not found on overflow pages.
  188183. */
  188184. static int getLocalPayload(
  188185. int nUsable, /* Usable bytes per page */
  188186. u8 flags, /* Page flags */
  188187. int nTotal /* Total record (payload) size */
  188188. ){
  188189. int nLocal;
  188190. int nMinLocal;
  188191. int nMaxLocal;
  188192. if( flags==0x0D ){ /* Table leaf node */
  188193. nMinLocal = (nUsable - 12) * 32 / 255 - 23;
  188194. nMaxLocal = nUsable - 35;
  188195. }else{ /* Index interior and leaf nodes */
  188196. nMinLocal = (nUsable - 12) * 32 / 255 - 23;
  188197. nMaxLocal = (nUsable - 12) * 64 / 255 - 23;
  188198. }
  188199. nLocal = nMinLocal + (nTotal - nMinLocal) % (nUsable - 4);
  188200. if( nLocal>nMaxLocal ) nLocal = nMinLocal;
  188201. return nLocal;
  188202. }
  188203. /* Populate the StatPage object with information about the all
  188204. ** cells found on the page currently under analysis.
  188205. */
  188206. static int statDecodePage(Btree *pBt, StatPage *p){
  188207. int nUnused;
  188208. int iOff;
  188209. int nHdr;
  188210. int isLeaf;
  188211. int szPage;
  188212. u8 *aData = sqlite3PagerGetData(p->pPg);
  188213. u8 *aHdr = &aData[p->iPgno==1 ? 100 : 0];
  188214. p->flags = aHdr[0];
  188215. if( p->flags==0x0A || p->flags==0x0D ){
  188216. isLeaf = 1;
  188217. nHdr = 8;
  188218. }else if( p->flags==0x05 || p->flags==0x02 ){
  188219. isLeaf = 0;
  188220. nHdr = 12;
  188221. }else{
  188222. goto statPageIsCorrupt;
  188223. }
  188224. if( p->iPgno==1 ) nHdr += 100;
  188225. p->nCell = get2byte(&aHdr[3]);
  188226. p->nMxPayload = 0;
  188227. szPage = sqlite3BtreeGetPageSize(pBt);
  188228. nUnused = get2byte(&aHdr[5]) - nHdr - 2*p->nCell;
  188229. nUnused += (int)aHdr[7];
  188230. iOff = get2byte(&aHdr[1]);
  188231. while( iOff ){
  188232. int iNext;
  188233. if( iOff>=szPage ) goto statPageIsCorrupt;
  188234. nUnused += get2byte(&aData[iOff+2]);
  188235. iNext = get2byte(&aData[iOff]);
  188236. if( iNext<iOff+4 && iNext>0 ) goto statPageIsCorrupt;
  188237. iOff = iNext;
  188238. }
  188239. p->nUnused = nUnused;
  188240. p->iRightChildPg = isLeaf ? 0 : sqlite3Get4byte(&aHdr[8]);
  188241. if( p->nCell ){
  188242. int i; /* Used to iterate through cells */
  188243. int nUsable; /* Usable bytes per page */
  188244. sqlite3BtreeEnter(pBt);
  188245. nUsable = szPage - sqlite3BtreeGetReserveNoMutex(pBt);
  188246. sqlite3BtreeLeave(pBt);
  188247. p->aCell = sqlite3_malloc64((p->nCell+1) * sizeof(StatCell));
  188248. if( p->aCell==0 ) return SQLITE_NOMEM_BKPT;
  188249. memset(p->aCell, 0, (p->nCell+1) * sizeof(StatCell));
  188250. for(i=0; i<p->nCell; i++){
  188251. StatCell *pCell = &p->aCell[i];
  188252. iOff = get2byte(&aData[nHdr+i*2]);
  188253. if( iOff<nHdr || iOff>=szPage ) goto statPageIsCorrupt;
  188254. if( !isLeaf ){
  188255. pCell->iChildPg = sqlite3Get4byte(&aData[iOff]);
  188256. iOff += 4;
  188257. }
  188258. if( p->flags==0x05 ){
  188259. /* A table interior node. nPayload==0. */
  188260. }else{
  188261. u32 nPayload; /* Bytes of payload total (local+overflow) */
  188262. int nLocal; /* Bytes of payload stored locally */
  188263. iOff += getVarint32(&aData[iOff], nPayload);
  188264. if( p->flags==0x0D ){
  188265. u64 dummy;
  188266. iOff += sqlite3GetVarint(&aData[iOff], &dummy);
  188267. }
  188268. if( nPayload>(u32)p->nMxPayload ) p->nMxPayload = nPayload;
  188269. nLocal = getLocalPayload(nUsable, p->flags, nPayload);
  188270. if( nLocal<0 ) goto statPageIsCorrupt;
  188271. pCell->nLocal = nLocal;
  188272. assert( nPayload>=(u32)nLocal );
  188273. assert( nLocal<=(nUsable-35) );
  188274. if( nPayload>(u32)nLocal ){
  188275. int j;
  188276. int nOvfl = ((nPayload - nLocal) + nUsable-4 - 1) / (nUsable - 4);
  188277. if( iOff+nLocal>nUsable || nPayload>0x7fffffff ){
  188278. goto statPageIsCorrupt;
  188279. }
  188280. pCell->nLastOvfl = (nPayload-nLocal) - (nOvfl-1) * (nUsable-4);
  188281. pCell->nOvfl = nOvfl;
  188282. pCell->aOvfl = sqlite3_malloc64(sizeof(u32)*nOvfl);
  188283. if( pCell->aOvfl==0 ) return SQLITE_NOMEM_BKPT;
  188284. pCell->aOvfl[0] = sqlite3Get4byte(&aData[iOff+nLocal]);
  188285. for(j=1; j<nOvfl; j++){
  188286. int rc;
  188287. u32 iPrev = pCell->aOvfl[j-1];
  188288. DbPage *pPg = 0;
  188289. rc = sqlite3PagerGet(sqlite3BtreePager(pBt), iPrev, &pPg, 0);
  188290. if( rc!=SQLITE_OK ){
  188291. assert( pPg==0 );
  188292. return rc;
  188293. }
  188294. pCell->aOvfl[j] = sqlite3Get4byte(sqlite3PagerGetData(pPg));
  188295. sqlite3PagerUnref(pPg);
  188296. }
  188297. }
  188298. }
  188299. }
  188300. }
  188301. return SQLITE_OK;
  188302. statPageIsCorrupt:
  188303. p->flags = 0;
  188304. statClearCells(p);
  188305. return SQLITE_OK;
  188306. }
  188307. /*
  188308. ** Populate the pCsr->iOffset and pCsr->szPage member variables. Based on
  188309. ** the current value of pCsr->iPageno.
  188310. */
  188311. static void statSizeAndOffset(StatCursor *pCsr){
  188312. StatTable *pTab = (StatTable *)((sqlite3_vtab_cursor *)pCsr)->pVtab;
  188313. Btree *pBt = pTab->db->aDb[pTab->iDb].pBt;
  188314. Pager *pPager = sqlite3BtreePager(pBt);
  188315. sqlite3_file *fd;
  188316. sqlite3_int64 x[2];
  188317. /* If connected to a ZIPVFS backend, find the page size and
  188318. ** offset from ZIPVFS.
  188319. */
  188320. fd = sqlite3PagerFile(pPager);
  188321. x[0] = pCsr->iPageno;
  188322. if( sqlite3OsFileControl(fd, 230440, &x)==SQLITE_OK ){
  188323. pCsr->iOffset = x[0];
  188324. pCsr->szPage += x[1];
  188325. }else{
  188326. /* Not ZIPVFS: The default page size and offset */
  188327. pCsr->szPage += sqlite3BtreeGetPageSize(pBt);
  188328. pCsr->iOffset = (i64)pCsr->szPage * (pCsr->iPageno - 1);
  188329. }
  188330. }
  188331. /*
  188332. ** Move a DBSTAT cursor to the next entry. Normally, the next
  188333. ** entry will be the next page, but in aggregated mode (pCsr->isAgg!=0),
  188334. ** the next entry is the next btree.
  188335. */
  188336. static int statNext(sqlite3_vtab_cursor *pCursor){
  188337. int rc;
  188338. int nPayload;
  188339. char *z;
  188340. StatCursor *pCsr = (StatCursor *)pCursor;
  188341. StatTable *pTab = (StatTable *)pCursor->pVtab;
  188342. Btree *pBt = pTab->db->aDb[pCsr->iDb].pBt;
  188343. Pager *pPager = sqlite3BtreePager(pBt);
  188344. sqlite3_free(pCsr->zPath);
  188345. pCsr->zPath = 0;
  188346. statNextRestart:
  188347. if( pCsr->aPage[0].pPg==0 ){
  188348. /* Start measuring space on the next btree */
  188349. statResetCounts(pCsr);
  188350. rc = sqlite3_step(pCsr->pStmt);
  188351. if( rc==SQLITE_ROW ){
  188352. int nPage;
  188353. u32 iRoot = (u32)sqlite3_column_int64(pCsr->pStmt, 1);
  188354. sqlite3PagerPagecount(pPager, &nPage);
  188355. if( nPage==0 ){
  188356. pCsr->isEof = 1;
  188357. return sqlite3_reset(pCsr->pStmt);
  188358. }
  188359. rc = sqlite3PagerGet(pPager, iRoot, &pCsr->aPage[0].pPg, 0);
  188360. pCsr->aPage[0].iPgno = iRoot;
  188361. pCsr->aPage[0].iCell = 0;
  188362. if( !pCsr->isAgg ){
  188363. pCsr->aPage[0].zPath = z = sqlite3_mprintf("/");
  188364. if( z==0 ) rc = SQLITE_NOMEM_BKPT;
  188365. }
  188366. pCsr->iPage = 0;
  188367. pCsr->nPage = 1;
  188368. }else{
  188369. pCsr->isEof = 1;
  188370. return sqlite3_reset(pCsr->pStmt);
  188371. }
  188372. }else{
  188373. /* Continue analyzing the btree previously started */
  188374. StatPage *p = &pCsr->aPage[pCsr->iPage];
  188375. if( !pCsr->isAgg ) statResetCounts(pCsr);
  188376. while( p->iCell<p->nCell ){
  188377. StatCell *pCell = &p->aCell[p->iCell];
  188378. while( pCell->iOvfl<pCell->nOvfl ){
  188379. int nUsable, iOvfl;
  188380. sqlite3BtreeEnter(pBt);
  188381. nUsable = sqlite3BtreeGetPageSize(pBt) -
  188382. sqlite3BtreeGetReserveNoMutex(pBt);
  188383. sqlite3BtreeLeave(pBt);
  188384. pCsr->nPage++;
  188385. statSizeAndOffset(pCsr);
  188386. if( pCell->iOvfl<pCell->nOvfl-1 ){
  188387. pCsr->nPayload += nUsable - 4;
  188388. }else{
  188389. pCsr->nPayload += pCell->nLastOvfl;
  188390. pCsr->nUnused += nUsable - 4 - pCell->nLastOvfl;
  188391. }
  188392. iOvfl = pCell->iOvfl;
  188393. pCell->iOvfl++;
  188394. if( !pCsr->isAgg ){
  188395. pCsr->zName = (char *)sqlite3_column_text(pCsr->pStmt, 0);
  188396. pCsr->iPageno = pCell->aOvfl[iOvfl];
  188397. pCsr->zPagetype = "overflow";
  188398. pCsr->zPath = z = sqlite3_mprintf(
  188399. "%s%.3x+%.6x", p->zPath, p->iCell, iOvfl
  188400. );
  188401. return z==0 ? SQLITE_NOMEM_BKPT : SQLITE_OK;
  188402. }
  188403. }
  188404. if( p->iRightChildPg ) break;
  188405. p->iCell++;
  188406. }
  188407. if( !p->iRightChildPg || p->iCell>p->nCell ){
  188408. statClearPage(p);
  188409. if( pCsr->iPage>0 ){
  188410. pCsr->iPage--;
  188411. }else if( pCsr->isAgg ){
  188412. /* label-statNext-done: When computing aggregate space usage over
  188413. ** an entire btree, this is the exit point from this function */
  188414. return SQLITE_OK;
  188415. }
  188416. goto statNextRestart; /* Tail recursion */
  188417. }
  188418. pCsr->iPage++;
  188419. if( pCsr->iPage>=ArraySize(pCsr->aPage) ){
  188420. statResetCsr(pCsr);
  188421. return SQLITE_CORRUPT_BKPT;
  188422. }
  188423. assert( p==&pCsr->aPage[pCsr->iPage-1] );
  188424. if( p->iCell==p->nCell ){
  188425. p[1].iPgno = p->iRightChildPg;
  188426. }else{
  188427. p[1].iPgno = p->aCell[p->iCell].iChildPg;
  188428. }
  188429. rc = sqlite3PagerGet(pPager, p[1].iPgno, &p[1].pPg, 0);
  188430. pCsr->nPage++;
  188431. p[1].iCell = 0;
  188432. if( !pCsr->isAgg ){
  188433. p[1].zPath = z = sqlite3_mprintf("%s%.3x/", p->zPath, p->iCell);
  188434. if( z==0 ) rc = SQLITE_NOMEM_BKPT;
  188435. }
  188436. p->iCell++;
  188437. }
  188438. /* Populate the StatCursor fields with the values to be returned
  188439. ** by the xColumn() and xRowid() methods.
  188440. */
  188441. if( rc==SQLITE_OK ){
  188442. int i;
  188443. StatPage *p = &pCsr->aPage[pCsr->iPage];
  188444. pCsr->zName = (char *)sqlite3_column_text(pCsr->pStmt, 0);
  188445. pCsr->iPageno = p->iPgno;
  188446. rc = statDecodePage(pBt, p);
  188447. if( rc==SQLITE_OK ){
  188448. statSizeAndOffset(pCsr);
  188449. switch( p->flags ){
  188450. case 0x05: /* table internal */
  188451. case 0x02: /* index internal */
  188452. pCsr->zPagetype = "internal";
  188453. break;
  188454. case 0x0D: /* table leaf */
  188455. case 0x0A: /* index leaf */
  188456. pCsr->zPagetype = "leaf";
  188457. break;
  188458. default:
  188459. pCsr->zPagetype = "corrupted";
  188460. break;
  188461. }
  188462. pCsr->nCell += p->nCell;
  188463. pCsr->nUnused += p->nUnused;
  188464. if( p->nMxPayload>pCsr->nMxPayload ) pCsr->nMxPayload = p->nMxPayload;
  188465. if( !pCsr->isAgg ){
  188466. pCsr->zPath = z = sqlite3_mprintf("%s", p->zPath);
  188467. if( z==0 ) rc = SQLITE_NOMEM_BKPT;
  188468. }
  188469. nPayload = 0;
  188470. for(i=0; i<p->nCell; i++){
  188471. nPayload += p->aCell[i].nLocal;
  188472. }
  188473. pCsr->nPayload += nPayload;
  188474. /* If computing aggregate space usage by btree, continue with the
  188475. ** next page. The loop will exit via the return at label-statNext-done
  188476. */
  188477. if( pCsr->isAgg ) goto statNextRestart;
  188478. }
  188479. }
  188480. return rc;
  188481. }
  188482. static int statEof(sqlite3_vtab_cursor *pCursor){
  188483. StatCursor *pCsr = (StatCursor *)pCursor;
  188484. return pCsr->isEof;
  188485. }
  188486. /* Initialize a cursor according to the query plan idxNum using the
  188487. ** arguments in argv[0]. See statBestIndex() for a description of the
  188488. ** meaning of the bits in idxNum.
  188489. */
  188490. static int statFilter(
  188491. sqlite3_vtab_cursor *pCursor,
  188492. int idxNum, const char *idxStr,
  188493. int argc, sqlite3_value **argv
  188494. ){
  188495. StatCursor *pCsr = (StatCursor *)pCursor;
  188496. StatTable *pTab = (StatTable*)(pCursor->pVtab);
  188497. sqlite3_str *pSql; /* Query of btrees to analyze */
  188498. char *zSql; /* String value of pSql */
  188499. int iArg = 0; /* Count of argv[] parameters used so far */
  188500. int rc = SQLITE_OK; /* Result of this operation */
  188501. const char *zName = 0; /* Only provide analysis of this table */
  188502. statResetCsr(pCsr);
  188503. sqlite3_finalize(pCsr->pStmt);
  188504. pCsr->pStmt = 0;
  188505. if( idxNum & 0x01 ){
  188506. /* schema=? constraint is present. Get its value */
  188507. const char *zDbase = (const char*)sqlite3_value_text(argv[iArg++]);
  188508. pCsr->iDb = sqlite3FindDbName(pTab->db, zDbase);
  188509. if( pCsr->iDb<0 ){
  188510. pCsr->iDb = 0;
  188511. pCsr->isEof = 1;
  188512. return SQLITE_OK;
  188513. }
  188514. }else{
  188515. pCsr->iDb = pTab->iDb;
  188516. }
  188517. if( idxNum & 0x02 ){
  188518. /* name=? constraint is present */
  188519. zName = (const char*)sqlite3_value_text(argv[iArg++]);
  188520. }
  188521. if( idxNum & 0x04 ){
  188522. /* aggregate=? constraint is present */
  188523. pCsr->isAgg = sqlite3_value_double(argv[iArg++])!=0.0;
  188524. }else{
  188525. pCsr->isAgg = 0;
  188526. }
  188527. pSql = sqlite3_str_new(pTab->db);
  188528. sqlite3_str_appendf(pSql,
  188529. "SELECT * FROM ("
  188530. "SELECT 'sqlite_master' AS name,1 AS rootpage,'table' AS type"
  188531. " UNION ALL "
  188532. "SELECT name,rootpage,type"
  188533. " FROM \"%w\".sqlite_master WHERE rootpage!=0)",
  188534. pTab->db->aDb[pCsr->iDb].zDbSName);
  188535. if( zName ){
  188536. sqlite3_str_appendf(pSql, "WHERE name=%Q", zName);
  188537. }
  188538. if( idxNum & 0x08 ){
  188539. sqlite3_str_appendf(pSql, " ORDER BY name");
  188540. }
  188541. zSql = sqlite3_str_finish(pSql);
  188542. if( zSql==0 ){
  188543. return SQLITE_NOMEM_BKPT;
  188544. }else{
  188545. rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pCsr->pStmt, 0);
  188546. sqlite3_free(zSql);
  188547. }
  188548. if( rc==SQLITE_OK ){
  188549. rc = statNext(pCursor);
  188550. }
  188551. return rc;
  188552. }
  188553. static int statColumn(
  188554. sqlite3_vtab_cursor *pCursor,
  188555. sqlite3_context *ctx,
  188556. int i
  188557. ){
  188558. StatCursor *pCsr = (StatCursor *)pCursor;
  188559. switch( i ){
  188560. case 0: /* name */
  188561. sqlite3_result_text(ctx, pCsr->zName, -1, SQLITE_TRANSIENT);
  188562. break;
  188563. case 1: /* path */
  188564. if( !pCsr->isAgg ){
  188565. sqlite3_result_text(ctx, pCsr->zPath, -1, SQLITE_TRANSIENT);
  188566. }
  188567. break;
  188568. case 2: /* pageno */
  188569. if( pCsr->isAgg ){
  188570. sqlite3_result_int64(ctx, pCsr->nPage);
  188571. }else{
  188572. sqlite3_result_int64(ctx, pCsr->iPageno);
  188573. }
  188574. break;
  188575. case 3: /* pagetype */
  188576. if( !pCsr->isAgg ){
  188577. sqlite3_result_text(ctx, pCsr->zPagetype, -1, SQLITE_STATIC);
  188578. }
  188579. break;
  188580. case 4: /* ncell */
  188581. sqlite3_result_int(ctx, pCsr->nCell);
  188582. break;
  188583. case 5: /* payload */
  188584. sqlite3_result_int(ctx, pCsr->nPayload);
  188585. break;
  188586. case 6: /* unused */
  188587. sqlite3_result_int(ctx, pCsr->nUnused);
  188588. break;
  188589. case 7: /* mx_payload */
  188590. sqlite3_result_int(ctx, pCsr->nMxPayload);
  188591. break;
  188592. case 8: /* pgoffset */
  188593. if( !pCsr->isAgg ){
  188594. sqlite3_result_int64(ctx, pCsr->iOffset);
  188595. }
  188596. break;
  188597. case 9: /* pgsize */
  188598. sqlite3_result_int(ctx, pCsr->szPage);
  188599. break;
  188600. case 10: { /* schema */
  188601. sqlite3 *db = sqlite3_context_db_handle(ctx);
  188602. int iDb = pCsr->iDb;
  188603. sqlite3_result_text(ctx, db->aDb[iDb].zDbSName, -1, SQLITE_STATIC);
  188604. break;
  188605. }
  188606. default: { /* aggregate */
  188607. sqlite3_result_int(ctx, pCsr->isAgg);
  188608. break;
  188609. }
  188610. }
  188611. return SQLITE_OK;
  188612. }
  188613. static int statRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
  188614. StatCursor *pCsr = (StatCursor *)pCursor;
  188615. *pRowid = pCsr->iPageno;
  188616. return SQLITE_OK;
  188617. }
  188618. /*
  188619. ** Invoke this routine to register the "dbstat" virtual table module
  188620. */
  188621. SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3 *db){
  188622. static sqlite3_module dbstat_module = {
  188623. 0, /* iVersion */
  188624. statConnect, /* xCreate */
  188625. statConnect, /* xConnect */
  188626. statBestIndex, /* xBestIndex */
  188627. statDisconnect, /* xDisconnect */
  188628. statDisconnect, /* xDestroy */
  188629. statOpen, /* xOpen - open a cursor */
  188630. statClose, /* xClose - close a cursor */
  188631. statFilter, /* xFilter - configure scan constraints */
  188632. statNext, /* xNext - advance a cursor */
  188633. statEof, /* xEof - check for end of scan */
  188634. statColumn, /* xColumn - read data */
  188635. statRowid, /* xRowid - read data */
  188636. 0, /* xUpdate */
  188637. 0, /* xBegin */
  188638. 0, /* xSync */
  188639. 0, /* xCommit */
  188640. 0, /* xRollback */
  188641. 0, /* xFindMethod */
  188642. 0, /* xRename */
  188643. 0, /* xSavepoint */
  188644. 0, /* xRelease */
  188645. 0, /* xRollbackTo */
  188646. 0 /* xShadowName */
  188647. };
  188648. return sqlite3_create_module(db, "dbstat", &dbstat_module, 0);
  188649. }
  188650. #elif defined(SQLITE_ENABLE_DBSTAT_VTAB)
  188651. SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3 *db){ return SQLITE_OK; }
  188652. #endif /* SQLITE_ENABLE_DBSTAT_VTAB */
  188653. /************** End of dbstat.c **********************************************/
  188654. /************** Begin file dbpage.c ******************************************/
  188655. /*
  188656. ** 2017-10-11
  188657. **
  188658. ** The author disclaims copyright to this source code. In place of
  188659. ** a legal notice, here is a blessing:
  188660. **
  188661. ** May you do good and not evil.
  188662. ** May you find forgiveness for yourself and forgive others.
  188663. ** May you share freely, never taking more than you give.
  188664. **
  188665. ******************************************************************************
  188666. **
  188667. ** This file contains an implementation of the "sqlite_dbpage" virtual table.
  188668. **
  188669. ** The sqlite_dbpage virtual table is used to read or write whole raw
  188670. ** pages of the database file. The pager interface is used so that
  188671. ** uncommitted changes and changes recorded in the WAL file are correctly
  188672. ** retrieved.
  188673. **
  188674. ** Usage example:
  188675. **
  188676. ** SELECT data FROM sqlite_dbpage('aux1') WHERE pgno=123;
  188677. **
  188678. ** This is an eponymous virtual table so it does not need to be created before
  188679. ** use. The optional argument to the sqlite_dbpage() table name is the
  188680. ** schema for the database file that is to be read. The default schema is
  188681. ** "main".
  188682. **
  188683. ** The data field of sqlite_dbpage table can be updated. The new
  188684. ** value must be a BLOB which is the correct page size, otherwise the
  188685. ** update fails. Rows may not be deleted or inserted.
  188686. */
  188687. /* #include "sqliteInt.h" ** Requires access to internal data structures ** */
  188688. #if (defined(SQLITE_ENABLE_DBPAGE_VTAB) || defined(SQLITE_TEST)) \
  188689. && !defined(SQLITE_OMIT_VIRTUALTABLE)
  188690. typedef struct DbpageTable DbpageTable;
  188691. typedef struct DbpageCursor DbpageCursor;
  188692. struct DbpageCursor {
  188693. sqlite3_vtab_cursor base; /* Base class. Must be first */
  188694. int pgno; /* Current page number */
  188695. int mxPgno; /* Last page to visit on this scan */
  188696. Pager *pPager; /* Pager being read/written */
  188697. DbPage *pPage1; /* Page 1 of the database */
  188698. int iDb; /* Index of database to analyze */
  188699. int szPage; /* Size of each page in bytes */
  188700. };
  188701. struct DbpageTable {
  188702. sqlite3_vtab base; /* Base class. Must be first */
  188703. sqlite3 *db; /* The database */
  188704. };
  188705. /* Columns */
  188706. #define DBPAGE_COLUMN_PGNO 0
  188707. #define DBPAGE_COLUMN_DATA 1
  188708. #define DBPAGE_COLUMN_SCHEMA 2
  188709. /*
  188710. ** Connect to or create a dbpagevfs virtual table.
  188711. */
  188712. static int dbpageConnect(
  188713. sqlite3 *db,
  188714. void *pAux,
  188715. int argc, const char *const*argv,
  188716. sqlite3_vtab **ppVtab,
  188717. char **pzErr
  188718. ){
  188719. DbpageTable *pTab = 0;
  188720. int rc = SQLITE_OK;
  188721. sqlite3_vtab_config(db, SQLITE_VTAB_DIRECTONLY);
  188722. rc = sqlite3_declare_vtab(db,
  188723. "CREATE TABLE x(pgno INTEGER PRIMARY KEY, data BLOB, schema HIDDEN)");
  188724. if( rc==SQLITE_OK ){
  188725. pTab = (DbpageTable *)sqlite3_malloc64(sizeof(DbpageTable));
  188726. if( pTab==0 ) rc = SQLITE_NOMEM_BKPT;
  188727. }
  188728. assert( rc==SQLITE_OK || pTab==0 );
  188729. if( rc==SQLITE_OK ){
  188730. memset(pTab, 0, sizeof(DbpageTable));
  188731. pTab->db = db;
  188732. }
  188733. *ppVtab = (sqlite3_vtab*)pTab;
  188734. return rc;
  188735. }
  188736. /*
  188737. ** Disconnect from or destroy a dbpagevfs virtual table.
  188738. */
  188739. static int dbpageDisconnect(sqlite3_vtab *pVtab){
  188740. sqlite3_free(pVtab);
  188741. return SQLITE_OK;
  188742. }
  188743. /*
  188744. ** idxNum:
  188745. **
  188746. ** 0 schema=main, full table scan
  188747. ** 1 schema=main, pgno=?1
  188748. ** 2 schema=?1, full table scan
  188749. ** 3 schema=?1, pgno=?2
  188750. */
  188751. static int dbpageBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
  188752. int i;
  188753. int iPlan = 0;
  188754. /* If there is a schema= constraint, it must be honored. Report a
  188755. ** ridiculously large estimated cost if the schema= constraint is
  188756. ** unavailable
  188757. */
  188758. for(i=0; i<pIdxInfo->nConstraint; i++){
  188759. struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[i];
  188760. if( p->iColumn!=DBPAGE_COLUMN_SCHEMA ) continue;
  188761. if( p->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
  188762. if( !p->usable ){
  188763. /* No solution. */
  188764. return SQLITE_CONSTRAINT;
  188765. }
  188766. iPlan = 2;
  188767. pIdxInfo->aConstraintUsage[i].argvIndex = 1;
  188768. pIdxInfo->aConstraintUsage[i].omit = 1;
  188769. break;
  188770. }
  188771. /* If we reach this point, it means that either there is no schema=
  188772. ** constraint (in which case we use the "main" schema) or else the
  188773. ** schema constraint was accepted. Lower the estimated cost accordingly
  188774. */
  188775. pIdxInfo->estimatedCost = 1.0e6;
  188776. /* Check for constraints against pgno */
  188777. for(i=0; i<pIdxInfo->nConstraint; i++){
  188778. struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[i];
  188779. if( p->usable && p->iColumn<=0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
  188780. pIdxInfo->estimatedRows = 1;
  188781. pIdxInfo->idxFlags = SQLITE_INDEX_SCAN_UNIQUE;
  188782. pIdxInfo->estimatedCost = 1.0;
  188783. pIdxInfo->aConstraintUsage[i].argvIndex = iPlan ? 2 : 1;
  188784. pIdxInfo->aConstraintUsage[i].omit = 1;
  188785. iPlan |= 1;
  188786. break;
  188787. }
  188788. }
  188789. pIdxInfo->idxNum = iPlan;
  188790. if( pIdxInfo->nOrderBy>=1
  188791. && pIdxInfo->aOrderBy[0].iColumn<=0
  188792. && pIdxInfo->aOrderBy[0].desc==0
  188793. ){
  188794. pIdxInfo->orderByConsumed = 1;
  188795. }
  188796. return SQLITE_OK;
  188797. }
  188798. /*
  188799. ** Open a new dbpagevfs cursor.
  188800. */
  188801. static int dbpageOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
  188802. DbpageCursor *pCsr;
  188803. pCsr = (DbpageCursor *)sqlite3_malloc64(sizeof(DbpageCursor));
  188804. if( pCsr==0 ){
  188805. return SQLITE_NOMEM_BKPT;
  188806. }else{
  188807. memset(pCsr, 0, sizeof(DbpageCursor));
  188808. pCsr->base.pVtab = pVTab;
  188809. pCsr->pgno = -1;
  188810. }
  188811. *ppCursor = (sqlite3_vtab_cursor *)pCsr;
  188812. return SQLITE_OK;
  188813. }
  188814. /*
  188815. ** Close a dbpagevfs cursor.
  188816. */
  188817. static int dbpageClose(sqlite3_vtab_cursor *pCursor){
  188818. DbpageCursor *pCsr = (DbpageCursor *)pCursor;
  188819. if( pCsr->pPage1 ) sqlite3PagerUnrefPageOne(pCsr->pPage1);
  188820. sqlite3_free(pCsr);
  188821. return SQLITE_OK;
  188822. }
  188823. /*
  188824. ** Move a dbpagevfs cursor to the next entry in the file.
  188825. */
  188826. static int dbpageNext(sqlite3_vtab_cursor *pCursor){
  188827. int rc = SQLITE_OK;
  188828. DbpageCursor *pCsr = (DbpageCursor *)pCursor;
  188829. pCsr->pgno++;
  188830. return rc;
  188831. }
  188832. static int dbpageEof(sqlite3_vtab_cursor *pCursor){
  188833. DbpageCursor *pCsr = (DbpageCursor *)pCursor;
  188834. return pCsr->pgno > pCsr->mxPgno;
  188835. }
  188836. /*
  188837. ** idxNum:
  188838. **
  188839. ** 0 schema=main, full table scan
  188840. ** 1 schema=main, pgno=?1
  188841. ** 2 schema=?1, full table scan
  188842. ** 3 schema=?1, pgno=?2
  188843. **
  188844. ** idxStr is not used
  188845. */
  188846. static int dbpageFilter(
  188847. sqlite3_vtab_cursor *pCursor,
  188848. int idxNum, const char *idxStr,
  188849. int argc, sqlite3_value **argv
  188850. ){
  188851. DbpageCursor *pCsr = (DbpageCursor *)pCursor;
  188852. DbpageTable *pTab = (DbpageTable *)pCursor->pVtab;
  188853. int rc;
  188854. sqlite3 *db = pTab->db;
  188855. Btree *pBt;
  188856. /* Default setting is no rows of result */
  188857. pCsr->pgno = 1;
  188858. pCsr->mxPgno = 0;
  188859. if( idxNum & 2 ){
  188860. const char *zSchema;
  188861. assert( argc>=1 );
  188862. zSchema = (const char*)sqlite3_value_text(argv[0]);
  188863. pCsr->iDb = sqlite3FindDbName(db, zSchema);
  188864. if( pCsr->iDb<0 ) return SQLITE_OK;
  188865. }else{
  188866. pCsr->iDb = 0;
  188867. }
  188868. pBt = db->aDb[pCsr->iDb].pBt;
  188869. if( pBt==0 ) return SQLITE_OK;
  188870. pCsr->pPager = sqlite3BtreePager(pBt);
  188871. pCsr->szPage = sqlite3BtreeGetPageSize(pBt);
  188872. pCsr->mxPgno = sqlite3BtreeLastPage(pBt);
  188873. if( idxNum & 1 ){
  188874. assert( argc>(idxNum>>1) );
  188875. pCsr->pgno = sqlite3_value_int(argv[idxNum>>1]);
  188876. if( pCsr->pgno<1 || pCsr->pgno>pCsr->mxPgno ){
  188877. pCsr->pgno = 1;
  188878. pCsr->mxPgno = 0;
  188879. }else{
  188880. pCsr->mxPgno = pCsr->pgno;
  188881. }
  188882. }else{
  188883. assert( pCsr->pgno==1 );
  188884. }
  188885. if( pCsr->pPage1 ) sqlite3PagerUnrefPageOne(pCsr->pPage1);
  188886. rc = sqlite3PagerGet(pCsr->pPager, 1, &pCsr->pPage1, 0);
  188887. return rc;
  188888. }
  188889. static int dbpageColumn(
  188890. sqlite3_vtab_cursor *pCursor,
  188891. sqlite3_context *ctx,
  188892. int i
  188893. ){
  188894. DbpageCursor *pCsr = (DbpageCursor *)pCursor;
  188895. int rc = SQLITE_OK;
  188896. switch( i ){
  188897. case 0: { /* pgno */
  188898. sqlite3_result_int(ctx, pCsr->pgno);
  188899. break;
  188900. }
  188901. case 1: { /* data */
  188902. DbPage *pDbPage = 0;
  188903. rc = sqlite3PagerGet(pCsr->pPager, pCsr->pgno, (DbPage**)&pDbPage, 0);
  188904. if( rc==SQLITE_OK ){
  188905. sqlite3_result_blob(ctx, sqlite3PagerGetData(pDbPage), pCsr->szPage,
  188906. SQLITE_TRANSIENT);
  188907. }
  188908. sqlite3PagerUnref(pDbPage);
  188909. break;
  188910. }
  188911. default: { /* schema */
  188912. sqlite3 *db = sqlite3_context_db_handle(ctx);
  188913. sqlite3_result_text(ctx, db->aDb[pCsr->iDb].zDbSName, -1, SQLITE_STATIC);
  188914. break;
  188915. }
  188916. }
  188917. return SQLITE_OK;
  188918. }
  188919. static int dbpageRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
  188920. DbpageCursor *pCsr = (DbpageCursor *)pCursor;
  188921. *pRowid = pCsr->pgno;
  188922. return SQLITE_OK;
  188923. }
  188924. static int dbpageUpdate(
  188925. sqlite3_vtab *pVtab,
  188926. int argc,
  188927. sqlite3_value **argv,
  188928. sqlite_int64 *pRowid
  188929. ){
  188930. DbpageTable *pTab = (DbpageTable *)pVtab;
  188931. Pgno pgno;
  188932. DbPage *pDbPage = 0;
  188933. int rc = SQLITE_OK;
  188934. char *zErr = 0;
  188935. const char *zSchema;
  188936. int iDb;
  188937. Btree *pBt;
  188938. Pager *pPager;
  188939. int szPage;
  188940. if( pTab->db->flags & SQLITE_Defensive ){
  188941. zErr = "read-only";
  188942. goto update_fail;
  188943. }
  188944. if( argc==1 ){
  188945. zErr = "cannot delete";
  188946. goto update_fail;
  188947. }
  188948. pgno = sqlite3_value_int(argv[0]);
  188949. if( (Pgno)sqlite3_value_int(argv[1])!=pgno ){
  188950. zErr = "cannot insert";
  188951. goto update_fail;
  188952. }
  188953. zSchema = (const char*)sqlite3_value_text(argv[4]);
  188954. iDb = zSchema ? sqlite3FindDbName(pTab->db, zSchema) : -1;
  188955. if( iDb<0 ){
  188956. zErr = "no such schema";
  188957. goto update_fail;
  188958. }
  188959. pBt = pTab->db->aDb[iDb].pBt;
  188960. if( pgno<1 || pBt==0 || pgno>(int)sqlite3BtreeLastPage(pBt) ){
  188961. zErr = "bad page number";
  188962. goto update_fail;
  188963. }
  188964. szPage = sqlite3BtreeGetPageSize(pBt);
  188965. if( sqlite3_value_type(argv[3])!=SQLITE_BLOB
  188966. || sqlite3_value_bytes(argv[3])!=szPage
  188967. ){
  188968. zErr = "bad page value";
  188969. goto update_fail;
  188970. }
  188971. pPager = sqlite3BtreePager(pBt);
  188972. rc = sqlite3PagerGet(pPager, pgno, (DbPage**)&pDbPage, 0);
  188973. if( rc==SQLITE_OK ){
  188974. rc = sqlite3PagerWrite(pDbPage);
  188975. if( rc==SQLITE_OK ){
  188976. memcpy(sqlite3PagerGetData(pDbPage),
  188977. sqlite3_value_blob(argv[3]),
  188978. szPage);
  188979. }
  188980. }
  188981. sqlite3PagerUnref(pDbPage);
  188982. return rc;
  188983. update_fail:
  188984. sqlite3_free(pVtab->zErrMsg);
  188985. pVtab->zErrMsg = sqlite3_mprintf("%s", zErr);
  188986. return SQLITE_ERROR;
  188987. }
  188988. /* Since we do not know in advance which database files will be
  188989. ** written by the sqlite_dbpage virtual table, start a write transaction
  188990. ** on them all.
  188991. */
  188992. static int dbpageBegin(sqlite3_vtab *pVtab){
  188993. DbpageTable *pTab = (DbpageTable *)pVtab;
  188994. sqlite3 *db = pTab->db;
  188995. int i;
  188996. for(i=0; i<db->nDb; i++){
  188997. Btree *pBt = db->aDb[i].pBt;
  188998. if( pBt ) sqlite3BtreeBeginTrans(pBt, 1, 0);
  188999. }
  189000. return SQLITE_OK;
  189001. }
  189002. /*
  189003. ** Invoke this routine to register the "dbpage" virtual table module
  189004. */
  189005. SQLITE_PRIVATE int sqlite3DbpageRegister(sqlite3 *db){
  189006. static sqlite3_module dbpage_module = {
  189007. 0, /* iVersion */
  189008. dbpageConnect, /* xCreate */
  189009. dbpageConnect, /* xConnect */
  189010. dbpageBestIndex, /* xBestIndex */
  189011. dbpageDisconnect, /* xDisconnect */
  189012. dbpageDisconnect, /* xDestroy */
  189013. dbpageOpen, /* xOpen - open a cursor */
  189014. dbpageClose, /* xClose - close a cursor */
  189015. dbpageFilter, /* xFilter - configure scan constraints */
  189016. dbpageNext, /* xNext - advance a cursor */
  189017. dbpageEof, /* xEof - check for end of scan */
  189018. dbpageColumn, /* xColumn - read data */
  189019. dbpageRowid, /* xRowid - read data */
  189020. dbpageUpdate, /* xUpdate */
  189021. dbpageBegin, /* xBegin */
  189022. 0, /* xSync */
  189023. 0, /* xCommit */
  189024. 0, /* xRollback */
  189025. 0, /* xFindMethod */
  189026. 0, /* xRename */
  189027. 0, /* xSavepoint */
  189028. 0, /* xRelease */
  189029. 0, /* xRollbackTo */
  189030. 0 /* xShadowName */
  189031. };
  189032. return sqlite3_create_module(db, "sqlite_dbpage", &dbpage_module, 0);
  189033. }
  189034. #elif defined(SQLITE_ENABLE_DBPAGE_VTAB)
  189035. SQLITE_PRIVATE int sqlite3DbpageRegister(sqlite3 *db){ return SQLITE_OK; }
  189036. #endif /* SQLITE_ENABLE_DBSTAT_VTAB */
  189037. /************** End of dbpage.c **********************************************/
  189038. /************** Begin file sqlite3session.c **********************************/
  189039. #if defined(SQLITE_ENABLE_SESSION) && defined(SQLITE_ENABLE_PREUPDATE_HOOK)
  189040. /* #include "sqlite3session.h" */
  189041. /* #include <assert.h> */
  189042. /* #include <string.h> */
  189043. #ifndef SQLITE_AMALGAMATION
  189044. /* # include "sqliteInt.h" */
  189045. /* # include "vdbeInt.h" */
  189046. #endif
  189047. typedef struct SessionTable SessionTable;
  189048. typedef struct SessionChange SessionChange;
  189049. typedef struct SessionBuffer SessionBuffer;
  189050. typedef struct SessionInput SessionInput;
  189051. /*
  189052. ** Minimum chunk size used by streaming versions of functions.
  189053. */
  189054. #ifndef SESSIONS_STRM_CHUNK_SIZE
  189055. # ifdef SQLITE_TEST
  189056. # define SESSIONS_STRM_CHUNK_SIZE 64
  189057. # else
  189058. # define SESSIONS_STRM_CHUNK_SIZE 1024
  189059. # endif
  189060. #endif
  189061. static int sessions_strm_chunk_size = SESSIONS_STRM_CHUNK_SIZE;
  189062. typedef struct SessionHook SessionHook;
  189063. struct SessionHook {
  189064. void *pCtx;
  189065. int (*xOld)(void*,int,sqlite3_value**);
  189066. int (*xNew)(void*,int,sqlite3_value**);
  189067. int (*xCount)(void*);
  189068. int (*xDepth)(void*);
  189069. };
  189070. /*
  189071. ** Session handle structure.
  189072. */
  189073. struct sqlite3_session {
  189074. sqlite3 *db; /* Database handle session is attached to */
  189075. char *zDb; /* Name of database session is attached to */
  189076. int bEnable; /* True if currently recording */
  189077. int bIndirect; /* True if all changes are indirect */
  189078. int bAutoAttach; /* True to auto-attach tables */
  189079. int rc; /* Non-zero if an error has occurred */
  189080. void *pFilterCtx; /* First argument to pass to xTableFilter */
  189081. int (*xTableFilter)(void *pCtx, const char *zTab);
  189082. sqlite3_value *pZeroBlob; /* Value containing X'' */
  189083. sqlite3_session *pNext; /* Next session object on same db. */
  189084. SessionTable *pTable; /* List of attached tables */
  189085. SessionHook hook; /* APIs to grab new and old data with */
  189086. };
  189087. /*
  189088. ** Instances of this structure are used to build strings or binary records.
  189089. */
  189090. struct SessionBuffer {
  189091. u8 *aBuf; /* Pointer to changeset buffer */
  189092. int nBuf; /* Size of buffer aBuf */
  189093. int nAlloc; /* Size of allocation containing aBuf */
  189094. };
  189095. /*
  189096. ** An object of this type is used internally as an abstraction for
  189097. ** input data. Input data may be supplied either as a single large buffer
  189098. ** (e.g. sqlite3changeset_start()) or using a stream function (e.g.
  189099. ** sqlite3changeset_start_strm()).
  189100. */
  189101. struct SessionInput {
  189102. int bNoDiscard; /* If true, do not discard in InputBuffer() */
  189103. int iCurrent; /* Offset in aData[] of current change */
  189104. int iNext; /* Offset in aData[] of next change */
  189105. u8 *aData; /* Pointer to buffer containing changeset */
  189106. int nData; /* Number of bytes in aData */
  189107. SessionBuffer buf; /* Current read buffer */
  189108. int (*xInput)(void*, void*, int*); /* Input stream call (or NULL) */
  189109. void *pIn; /* First argument to xInput */
  189110. int bEof; /* Set to true after xInput finished */
  189111. };
  189112. /*
  189113. ** Structure for changeset iterators.
  189114. */
  189115. struct sqlite3_changeset_iter {
  189116. SessionInput in; /* Input buffer or stream */
  189117. SessionBuffer tblhdr; /* Buffer to hold apValue/zTab/abPK/ */
  189118. int bPatchset; /* True if this is a patchset */
  189119. int bInvert; /* True to invert changeset */
  189120. int rc; /* Iterator error code */
  189121. sqlite3_stmt *pConflict; /* Points to conflicting row, if any */
  189122. char *zTab; /* Current table */
  189123. int nCol; /* Number of columns in zTab */
  189124. int op; /* Current operation */
  189125. int bIndirect; /* True if current change was indirect */
  189126. u8 *abPK; /* Primary key array */
  189127. sqlite3_value **apValue; /* old.* and new.* values */
  189128. };
  189129. /*
  189130. ** Each session object maintains a set of the following structures, one
  189131. ** for each table the session object is monitoring. The structures are
  189132. ** stored in a linked list starting at sqlite3_session.pTable.
  189133. **
  189134. ** The keys of the SessionTable.aChange[] hash table are all rows that have
  189135. ** been modified in any way since the session object was attached to the
  189136. ** table.
  189137. **
  189138. ** The data associated with each hash-table entry is a structure containing
  189139. ** a subset of the initial values that the modified row contained at the
  189140. ** start of the session. Or no initial values if the row was inserted.
  189141. */
  189142. struct SessionTable {
  189143. SessionTable *pNext;
  189144. char *zName; /* Local name of table */
  189145. int nCol; /* Number of columns in table zName */
  189146. int bStat1; /* True if this is sqlite_stat1 */
  189147. const char **azCol; /* Column names */
  189148. u8 *abPK; /* Array of primary key flags */
  189149. int nEntry; /* Total number of entries in hash table */
  189150. int nChange; /* Size of apChange[] array */
  189151. SessionChange **apChange; /* Hash table buckets */
  189152. };
  189153. /*
  189154. ** RECORD FORMAT:
  189155. **
  189156. ** The following record format is similar to (but not compatible with) that
  189157. ** used in SQLite database files. This format is used as part of the
  189158. ** change-set binary format, and so must be architecture independent.
  189159. **
  189160. ** Unlike the SQLite database record format, each field is self-contained -
  189161. ** there is no separation of header and data. Each field begins with a
  189162. ** single byte describing its type, as follows:
  189163. **
  189164. ** 0x00: Undefined value.
  189165. ** 0x01: Integer value.
  189166. ** 0x02: Real value.
  189167. ** 0x03: Text value.
  189168. ** 0x04: Blob value.
  189169. ** 0x05: SQL NULL value.
  189170. **
  189171. ** Note that the above match the definitions of SQLITE_INTEGER, SQLITE_TEXT
  189172. ** and so on in sqlite3.h. For undefined and NULL values, the field consists
  189173. ** only of the single type byte. For other types of values, the type byte
  189174. ** is followed by:
  189175. **
  189176. ** Text values:
  189177. ** A varint containing the number of bytes in the value (encoded using
  189178. ** UTF-8). Followed by a buffer containing the UTF-8 representation
  189179. ** of the text value. There is no nul terminator.
  189180. **
  189181. ** Blob values:
  189182. ** A varint containing the number of bytes in the value, followed by
  189183. ** a buffer containing the value itself.
  189184. **
  189185. ** Integer values:
  189186. ** An 8-byte big-endian integer value.
  189187. **
  189188. ** Real values:
  189189. ** An 8-byte big-endian IEEE 754-2008 real value.
  189190. **
  189191. ** Varint values are encoded in the same way as varints in the SQLite
  189192. ** record format.
  189193. **
  189194. ** CHANGESET FORMAT:
  189195. **
  189196. ** A changeset is a collection of DELETE, UPDATE and INSERT operations on
  189197. ** one or more tables. Operations on a single table are grouped together,
  189198. ** but may occur in any order (i.e. deletes, updates and inserts are all
  189199. ** mixed together).
  189200. **
  189201. ** Each group of changes begins with a table header:
  189202. **
  189203. ** 1 byte: Constant 0x54 (capital 'T')
  189204. ** Varint: Number of columns in the table.
  189205. ** nCol bytes: 0x01 for PK columns, 0x00 otherwise.
  189206. ** N bytes: Unqualified table name (encoded using UTF-8). Nul-terminated.
  189207. **
  189208. ** Followed by one or more changes to the table.
  189209. **
  189210. ** 1 byte: Either SQLITE_INSERT (0x12), UPDATE (0x17) or DELETE (0x09).
  189211. ** 1 byte: The "indirect-change" flag.
  189212. ** old.* record: (delete and update only)
  189213. ** new.* record: (insert and update only)
  189214. **
  189215. ** The "old.*" and "new.*" records, if present, are N field records in the
  189216. ** format described above under "RECORD FORMAT", where N is the number of
  189217. ** columns in the table. The i'th field of each record is associated with
  189218. ** the i'th column of the table, counting from left to right in the order
  189219. ** in which columns were declared in the CREATE TABLE statement.
  189220. **
  189221. ** The new.* record that is part of each INSERT change contains the values
  189222. ** that make up the new row. Similarly, the old.* record that is part of each
  189223. ** DELETE change contains the values that made up the row that was deleted
  189224. ** from the database. In the changeset format, the records that are part
  189225. ** of INSERT or DELETE changes never contain any undefined (type byte 0x00)
  189226. ** fields.
  189227. **
  189228. ** Within the old.* record associated with an UPDATE change, all fields
  189229. ** associated with table columns that are not PRIMARY KEY columns and are
  189230. ** not modified by the UPDATE change are set to "undefined". Other fields
  189231. ** are set to the values that made up the row before the UPDATE that the
  189232. ** change records took place. Within the new.* record, fields associated
  189233. ** with table columns modified by the UPDATE change contain the new
  189234. ** values. Fields associated with table columns that are not modified
  189235. ** are set to "undefined".
  189236. **
  189237. ** PATCHSET FORMAT:
  189238. **
  189239. ** A patchset is also a collection of changes. It is similar to a changeset,
  189240. ** but leaves undefined those fields that are not useful if no conflict
  189241. ** resolution is required when applying the changeset.
  189242. **
  189243. ** Each group of changes begins with a table header:
  189244. **
  189245. ** 1 byte: Constant 0x50 (capital 'P')
  189246. ** Varint: Number of columns in the table.
  189247. ** nCol bytes: 0x01 for PK columns, 0x00 otherwise.
  189248. ** N bytes: Unqualified table name (encoded using UTF-8). Nul-terminated.
  189249. **
  189250. ** Followed by one or more changes to the table.
  189251. **
  189252. ** 1 byte: Either SQLITE_INSERT (0x12), UPDATE (0x17) or DELETE (0x09).
  189253. ** 1 byte: The "indirect-change" flag.
  189254. ** single record: (PK fields for DELETE, PK and modified fields for UPDATE,
  189255. ** full record for INSERT).
  189256. **
  189257. ** As in the changeset format, each field of the single record that is part
  189258. ** of a patchset change is associated with the correspondingly positioned
  189259. ** table column, counting from left to right within the CREATE TABLE
  189260. ** statement.
  189261. **
  189262. ** For a DELETE change, all fields within the record except those associated
  189263. ** with PRIMARY KEY columns are omitted. The PRIMARY KEY fields contain the
  189264. ** values identifying the row to delete.
  189265. **
  189266. ** For an UPDATE change, all fields except those associated with PRIMARY KEY
  189267. ** columns and columns that are modified by the UPDATE are set to "undefined".
  189268. ** PRIMARY KEY fields contain the values identifying the table row to update,
  189269. ** and fields associated with modified columns contain the new column values.
  189270. **
  189271. ** The records associated with INSERT changes are in the same format as for
  189272. ** changesets. It is not possible for a record associated with an INSERT
  189273. ** change to contain a field set to "undefined".
  189274. **
  189275. ** REBASE BLOB FORMAT:
  189276. **
  189277. ** A rebase blob may be output by sqlite3changeset_apply_v2() and its
  189278. ** streaming equivalent for use with the sqlite3_rebaser APIs to rebase
  189279. ** existing changesets. A rebase blob contains one entry for each conflict
  189280. ** resolved using either the OMIT or REPLACE strategies within the apply_v2()
  189281. ** call.
  189282. **
  189283. ** The format used for a rebase blob is very similar to that used for
  189284. ** changesets. All entries related to a single table are grouped together.
  189285. **
  189286. ** Each group of entries begins with a table header in changeset format:
  189287. **
  189288. ** 1 byte: Constant 0x54 (capital 'T')
  189289. ** Varint: Number of columns in the table.
  189290. ** nCol bytes: 0x01 for PK columns, 0x00 otherwise.
  189291. ** N bytes: Unqualified table name (encoded using UTF-8). Nul-terminated.
  189292. **
  189293. ** Followed by one or more entries associated with the table.
  189294. **
  189295. ** 1 byte: Either SQLITE_INSERT (0x12), DELETE (0x09).
  189296. ** 1 byte: Flag. 0x01 for REPLACE, 0x00 for OMIT.
  189297. ** record: (in the record format defined above).
  189298. **
  189299. ** In a rebase blob, the first field is set to SQLITE_INSERT if the change
  189300. ** that caused the conflict was an INSERT or UPDATE, or to SQLITE_DELETE if
  189301. ** it was a DELETE. The second field is set to 0x01 if the conflict
  189302. ** resolution strategy was REPLACE, or 0x00 if it was OMIT.
  189303. **
  189304. ** If the change that caused the conflict was a DELETE, then the single
  189305. ** record is a copy of the old.* record from the original changeset. If it
  189306. ** was an INSERT, then the single record is a copy of the new.* record. If
  189307. ** the conflicting change was an UPDATE, then the single record is a copy
  189308. ** of the new.* record with the PK fields filled in based on the original
  189309. ** old.* record.
  189310. */
  189311. /*
  189312. ** For each row modified during a session, there exists a single instance of
  189313. ** this structure stored in a SessionTable.aChange[] hash table.
  189314. */
  189315. struct SessionChange {
  189316. int op; /* One of UPDATE, DELETE, INSERT */
  189317. int bIndirect; /* True if this change is "indirect" */
  189318. int nRecord; /* Number of bytes in buffer aRecord[] */
  189319. u8 *aRecord; /* Buffer containing old.* record */
  189320. SessionChange *pNext; /* For hash-table collisions */
  189321. };
  189322. /*
  189323. ** Write a varint with value iVal into the buffer at aBuf. Return the
  189324. ** number of bytes written.
  189325. */
  189326. static int sessionVarintPut(u8 *aBuf, int iVal){
  189327. return putVarint32(aBuf, iVal);
  189328. }
  189329. /*
  189330. ** Return the number of bytes required to store value iVal as a varint.
  189331. */
  189332. static int sessionVarintLen(int iVal){
  189333. return sqlite3VarintLen(iVal);
  189334. }
  189335. /*
  189336. ** Read a varint value from aBuf[] into *piVal. Return the number of
  189337. ** bytes read.
  189338. */
  189339. static int sessionVarintGet(u8 *aBuf, int *piVal){
  189340. return getVarint32(aBuf, *piVal);
  189341. }
  189342. /* Load an unaligned and unsigned 32-bit integer */
  189343. #define SESSION_UINT32(x) (((u32)(x)[0]<<24)|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
  189344. /*
  189345. ** Read a 64-bit big-endian integer value from buffer aRec[]. Return
  189346. ** the value read.
  189347. */
  189348. static sqlite3_int64 sessionGetI64(u8 *aRec){
  189349. u64 x = SESSION_UINT32(aRec);
  189350. u32 y = SESSION_UINT32(aRec+4);
  189351. x = (x<<32) + y;
  189352. return (sqlite3_int64)x;
  189353. }
  189354. /*
  189355. ** Write a 64-bit big-endian integer value to the buffer aBuf[].
  189356. */
  189357. static void sessionPutI64(u8 *aBuf, sqlite3_int64 i){
  189358. aBuf[0] = (i>>56) & 0xFF;
  189359. aBuf[1] = (i>>48) & 0xFF;
  189360. aBuf[2] = (i>>40) & 0xFF;
  189361. aBuf[3] = (i>>32) & 0xFF;
  189362. aBuf[4] = (i>>24) & 0xFF;
  189363. aBuf[5] = (i>>16) & 0xFF;
  189364. aBuf[6] = (i>> 8) & 0xFF;
  189365. aBuf[7] = (i>> 0) & 0xFF;
  189366. }
  189367. /*
  189368. ** This function is used to serialize the contents of value pValue (see
  189369. ** comment titled "RECORD FORMAT" above).
  189370. **
  189371. ** If it is non-NULL, the serialized form of the value is written to
  189372. ** buffer aBuf. *pnWrite is set to the number of bytes written before
  189373. ** returning. Or, if aBuf is NULL, the only thing this function does is
  189374. ** set *pnWrite.
  189375. **
  189376. ** If no error occurs, SQLITE_OK is returned. Or, if an OOM error occurs
  189377. ** within a call to sqlite3_value_text() (may fail if the db is utf-16))
  189378. ** SQLITE_NOMEM is returned.
  189379. */
  189380. static int sessionSerializeValue(
  189381. u8 *aBuf, /* If non-NULL, write serialized value here */
  189382. sqlite3_value *pValue, /* Value to serialize */
  189383. sqlite3_int64 *pnWrite /* IN/OUT: Increment by bytes written */
  189384. ){
  189385. int nByte; /* Size of serialized value in bytes */
  189386. if( pValue ){
  189387. int eType; /* Value type (SQLITE_NULL, TEXT etc.) */
  189388. eType = sqlite3_value_type(pValue);
  189389. if( aBuf ) aBuf[0] = eType;
  189390. switch( eType ){
  189391. case SQLITE_NULL:
  189392. nByte = 1;
  189393. break;
  189394. case SQLITE_INTEGER:
  189395. case SQLITE_FLOAT:
  189396. if( aBuf ){
  189397. /* TODO: SQLite does something special to deal with mixed-endian
  189398. ** floating point values (e.g. ARM7). This code probably should
  189399. ** too. */
  189400. u64 i;
  189401. if( eType==SQLITE_INTEGER ){
  189402. i = (u64)sqlite3_value_int64(pValue);
  189403. }else{
  189404. double r;
  189405. assert( sizeof(double)==8 && sizeof(u64)==8 );
  189406. r = sqlite3_value_double(pValue);
  189407. memcpy(&i, &r, 8);
  189408. }
  189409. sessionPutI64(&aBuf[1], i);
  189410. }
  189411. nByte = 9;
  189412. break;
  189413. default: {
  189414. u8 *z;
  189415. int n;
  189416. int nVarint;
  189417. assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
  189418. if( eType==SQLITE_TEXT ){
  189419. z = (u8 *)sqlite3_value_text(pValue);
  189420. }else{
  189421. z = (u8 *)sqlite3_value_blob(pValue);
  189422. }
  189423. n = sqlite3_value_bytes(pValue);
  189424. if( z==0 && (eType!=SQLITE_BLOB || n>0) ) return SQLITE_NOMEM;
  189425. nVarint = sessionVarintLen(n);
  189426. if( aBuf ){
  189427. sessionVarintPut(&aBuf[1], n);
  189428. if( n ) memcpy(&aBuf[nVarint + 1], z, n);
  189429. }
  189430. nByte = 1 + nVarint + n;
  189431. break;
  189432. }
  189433. }
  189434. }else{
  189435. nByte = 1;
  189436. if( aBuf ) aBuf[0] = '\0';
  189437. }
  189438. if( pnWrite ) *pnWrite += nByte;
  189439. return SQLITE_OK;
  189440. }
  189441. /*
  189442. ** This macro is used to calculate hash key values for data structures. In
  189443. ** order to use this macro, the entire data structure must be represented
  189444. ** as a series of unsigned integers. In order to calculate a hash-key value
  189445. ** for a data structure represented as three such integers, the macro may
  189446. ** then be used as follows:
  189447. **
  189448. ** int hash_key_value;
  189449. ** hash_key_value = HASH_APPEND(0, <value 1>);
  189450. ** hash_key_value = HASH_APPEND(hash_key_value, <value 2>);
  189451. ** hash_key_value = HASH_APPEND(hash_key_value, <value 3>);
  189452. **
  189453. ** In practice, the data structures this macro is used for are the primary
  189454. ** key values of modified rows.
  189455. */
  189456. #define HASH_APPEND(hash, add) ((hash) << 3) ^ (hash) ^ (unsigned int)(add)
  189457. /*
  189458. ** Append the hash of the 64-bit integer passed as the second argument to the
  189459. ** hash-key value passed as the first. Return the new hash-key value.
  189460. */
  189461. static unsigned int sessionHashAppendI64(unsigned int h, i64 i){
  189462. h = HASH_APPEND(h, i & 0xFFFFFFFF);
  189463. return HASH_APPEND(h, (i>>32)&0xFFFFFFFF);
  189464. }
  189465. /*
  189466. ** Append the hash of the blob passed via the second and third arguments to
  189467. ** the hash-key value passed as the first. Return the new hash-key value.
  189468. */
  189469. static unsigned int sessionHashAppendBlob(unsigned int h, int n, const u8 *z){
  189470. int i;
  189471. for(i=0; i<n; i++) h = HASH_APPEND(h, z[i]);
  189472. return h;
  189473. }
  189474. /*
  189475. ** Append the hash of the data type passed as the second argument to the
  189476. ** hash-key value passed as the first. Return the new hash-key value.
  189477. */
  189478. static unsigned int sessionHashAppendType(unsigned int h, int eType){
  189479. return HASH_APPEND(h, eType);
  189480. }
  189481. /*
  189482. ** This function may only be called from within a pre-update callback.
  189483. ** It calculates a hash based on the primary key values of the old.* or
  189484. ** new.* row currently available and, assuming no error occurs, writes it to
  189485. ** *piHash before returning. If the primary key contains one or more NULL
  189486. ** values, *pbNullPK is set to true before returning.
  189487. **
  189488. ** If an error occurs, an SQLite error code is returned and the final values
  189489. ** of *piHash asn *pbNullPK are undefined. Otherwise, SQLITE_OK is returned
  189490. ** and the output variables are set as described above.
  189491. */
  189492. static int sessionPreupdateHash(
  189493. sqlite3_session *pSession, /* Session object that owns pTab */
  189494. SessionTable *pTab, /* Session table handle */
  189495. int bNew, /* True to hash the new.* PK */
  189496. int *piHash, /* OUT: Hash value */
  189497. int *pbNullPK /* OUT: True if there are NULL values in PK */
  189498. ){
  189499. unsigned int h = 0; /* Hash value to return */
  189500. int i; /* Used to iterate through columns */
  189501. assert( *pbNullPK==0 );
  189502. assert( pTab->nCol==pSession->hook.xCount(pSession->hook.pCtx) );
  189503. for(i=0; i<pTab->nCol; i++){
  189504. if( pTab->abPK[i] ){
  189505. int rc;
  189506. int eType;
  189507. sqlite3_value *pVal;
  189508. if( bNew ){
  189509. rc = pSession->hook.xNew(pSession->hook.pCtx, i, &pVal);
  189510. }else{
  189511. rc = pSession->hook.xOld(pSession->hook.pCtx, i, &pVal);
  189512. }
  189513. if( rc!=SQLITE_OK ) return rc;
  189514. eType = sqlite3_value_type(pVal);
  189515. h = sessionHashAppendType(h, eType);
  189516. if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
  189517. i64 iVal;
  189518. if( eType==SQLITE_INTEGER ){
  189519. iVal = sqlite3_value_int64(pVal);
  189520. }else{
  189521. double rVal = sqlite3_value_double(pVal);
  189522. assert( sizeof(iVal)==8 && sizeof(rVal)==8 );
  189523. memcpy(&iVal, &rVal, 8);
  189524. }
  189525. h = sessionHashAppendI64(h, iVal);
  189526. }else if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
  189527. const u8 *z;
  189528. int n;
  189529. if( eType==SQLITE_TEXT ){
  189530. z = (const u8 *)sqlite3_value_text(pVal);
  189531. }else{
  189532. z = (const u8 *)sqlite3_value_blob(pVal);
  189533. }
  189534. n = sqlite3_value_bytes(pVal);
  189535. if( !z && (eType!=SQLITE_BLOB || n>0) ) return SQLITE_NOMEM;
  189536. h = sessionHashAppendBlob(h, n, z);
  189537. }else{
  189538. assert( eType==SQLITE_NULL );
  189539. assert( pTab->bStat1==0 || i!=1 );
  189540. *pbNullPK = 1;
  189541. }
  189542. }
  189543. }
  189544. *piHash = (h % pTab->nChange);
  189545. return SQLITE_OK;
  189546. }
  189547. /*
  189548. ** The buffer that the argument points to contains a serialized SQL value.
  189549. ** Return the number of bytes of space occupied by the value (including
  189550. ** the type byte).
  189551. */
  189552. static int sessionSerialLen(u8 *a){
  189553. int e = *a;
  189554. int n;
  189555. if( e==0 || e==0xFF ) return 1;
  189556. if( e==SQLITE_NULL ) return 1;
  189557. if( e==SQLITE_INTEGER || e==SQLITE_FLOAT ) return 9;
  189558. return sessionVarintGet(&a[1], &n) + 1 + n;
  189559. }
  189560. /*
  189561. ** Based on the primary key values stored in change aRecord, calculate a
  189562. ** hash key. Assume the has table has nBucket buckets. The hash keys
  189563. ** calculated by this function are compatible with those calculated by
  189564. ** sessionPreupdateHash().
  189565. **
  189566. ** The bPkOnly argument is non-zero if the record at aRecord[] is from
  189567. ** a patchset DELETE. In this case the non-PK fields are omitted entirely.
  189568. */
  189569. static unsigned int sessionChangeHash(
  189570. SessionTable *pTab, /* Table handle */
  189571. int bPkOnly, /* Record consists of PK fields only */
  189572. u8 *aRecord, /* Change record */
  189573. int nBucket /* Assume this many buckets in hash table */
  189574. ){
  189575. unsigned int h = 0; /* Value to return */
  189576. int i; /* Used to iterate through columns */
  189577. u8 *a = aRecord; /* Used to iterate through change record */
  189578. for(i=0; i<pTab->nCol; i++){
  189579. int eType = *a;
  189580. int isPK = pTab->abPK[i];
  189581. if( bPkOnly && isPK==0 ) continue;
  189582. /* It is not possible for eType to be SQLITE_NULL here. The session
  189583. ** module does not record changes for rows with NULL values stored in
  189584. ** primary key columns. */
  189585. assert( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT
  189586. || eType==SQLITE_TEXT || eType==SQLITE_BLOB
  189587. || eType==SQLITE_NULL || eType==0
  189588. );
  189589. assert( !isPK || (eType!=0 && eType!=SQLITE_NULL) );
  189590. if( isPK ){
  189591. a++;
  189592. h = sessionHashAppendType(h, eType);
  189593. if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
  189594. h = sessionHashAppendI64(h, sessionGetI64(a));
  189595. a += 8;
  189596. }else{
  189597. int n;
  189598. a += sessionVarintGet(a, &n);
  189599. h = sessionHashAppendBlob(h, n, a);
  189600. a += n;
  189601. }
  189602. }else{
  189603. a += sessionSerialLen(a);
  189604. }
  189605. }
  189606. return (h % nBucket);
  189607. }
  189608. /*
  189609. ** Arguments aLeft and aRight are pointers to change records for table pTab.
  189610. ** This function returns true if the two records apply to the same row (i.e.
  189611. ** have the same values stored in the primary key columns), or false
  189612. ** otherwise.
  189613. */
  189614. static int sessionChangeEqual(
  189615. SessionTable *pTab, /* Table used for PK definition */
  189616. int bLeftPkOnly, /* True if aLeft[] contains PK fields only */
  189617. u8 *aLeft, /* Change record */
  189618. int bRightPkOnly, /* True if aRight[] contains PK fields only */
  189619. u8 *aRight /* Change record */
  189620. ){
  189621. u8 *a1 = aLeft; /* Cursor to iterate through aLeft */
  189622. u8 *a2 = aRight; /* Cursor to iterate through aRight */
  189623. int iCol; /* Used to iterate through table columns */
  189624. for(iCol=0; iCol<pTab->nCol; iCol++){
  189625. if( pTab->abPK[iCol] ){
  189626. int n1 = sessionSerialLen(a1);
  189627. int n2 = sessionSerialLen(a2);
  189628. if( n1!=n2 || memcmp(a1, a2, n1) ){
  189629. return 0;
  189630. }
  189631. a1 += n1;
  189632. a2 += n2;
  189633. }else{
  189634. if( bLeftPkOnly==0 ) a1 += sessionSerialLen(a1);
  189635. if( bRightPkOnly==0 ) a2 += sessionSerialLen(a2);
  189636. }
  189637. }
  189638. return 1;
  189639. }
  189640. /*
  189641. ** Arguments aLeft and aRight both point to buffers containing change
  189642. ** records with nCol columns. This function "merges" the two records into
  189643. ** a single records which is written to the buffer at *paOut. *paOut is
  189644. ** then set to point to one byte after the last byte written before
  189645. ** returning.
  189646. **
  189647. ** The merging of records is done as follows: For each column, if the
  189648. ** aRight record contains a value for the column, copy the value from
  189649. ** their. Otherwise, if aLeft contains a value, copy it. If neither
  189650. ** record contains a value for a given column, then neither does the
  189651. ** output record.
  189652. */
  189653. static void sessionMergeRecord(
  189654. u8 **paOut,
  189655. int nCol,
  189656. u8 *aLeft,
  189657. u8 *aRight
  189658. ){
  189659. u8 *a1 = aLeft; /* Cursor used to iterate through aLeft */
  189660. u8 *a2 = aRight; /* Cursor used to iterate through aRight */
  189661. u8 *aOut = *paOut; /* Output cursor */
  189662. int iCol; /* Used to iterate from 0 to nCol */
  189663. for(iCol=0; iCol<nCol; iCol++){
  189664. int n1 = sessionSerialLen(a1);
  189665. int n2 = sessionSerialLen(a2);
  189666. if( *a2 ){
  189667. memcpy(aOut, a2, n2);
  189668. aOut += n2;
  189669. }else{
  189670. memcpy(aOut, a1, n1);
  189671. aOut += n1;
  189672. }
  189673. a1 += n1;
  189674. a2 += n2;
  189675. }
  189676. *paOut = aOut;
  189677. }
  189678. /*
  189679. ** This is a helper function used by sessionMergeUpdate().
  189680. **
  189681. ** When this function is called, both *paOne and *paTwo point to a value
  189682. ** within a change record. Before it returns, both have been advanced so
  189683. ** as to point to the next value in the record.
  189684. **
  189685. ** If, when this function is called, *paTwo points to a valid value (i.e.
  189686. ** *paTwo[0] is not 0x00 - the "no value" placeholder), a copy of the *paTwo
  189687. ** pointer is returned and *pnVal is set to the number of bytes in the
  189688. ** serialized value. Otherwise, a copy of *paOne is returned and *pnVal
  189689. ** set to the number of bytes in the value at *paOne. If *paOne points
  189690. ** to the "no value" placeholder, *pnVal is set to 1. In other words:
  189691. **
  189692. ** if( *paTwo is valid ) return *paTwo;
  189693. ** return *paOne;
  189694. **
  189695. */
  189696. static u8 *sessionMergeValue(
  189697. u8 **paOne, /* IN/OUT: Left-hand buffer pointer */
  189698. u8 **paTwo, /* IN/OUT: Right-hand buffer pointer */
  189699. int *pnVal /* OUT: Bytes in returned value */
  189700. ){
  189701. u8 *a1 = *paOne;
  189702. u8 *a2 = *paTwo;
  189703. u8 *pRet = 0;
  189704. int n1;
  189705. assert( a1 );
  189706. if( a2 ){
  189707. int n2 = sessionSerialLen(a2);
  189708. if( *a2 ){
  189709. *pnVal = n2;
  189710. pRet = a2;
  189711. }
  189712. *paTwo = &a2[n2];
  189713. }
  189714. n1 = sessionSerialLen(a1);
  189715. if( pRet==0 ){
  189716. *pnVal = n1;
  189717. pRet = a1;
  189718. }
  189719. *paOne = &a1[n1];
  189720. return pRet;
  189721. }
  189722. /*
  189723. ** This function is used by changeset_concat() to merge two UPDATE changes
  189724. ** on the same row.
  189725. */
  189726. static int sessionMergeUpdate(
  189727. u8 **paOut, /* IN/OUT: Pointer to output buffer */
  189728. SessionTable *pTab, /* Table change pertains to */
  189729. int bPatchset, /* True if records are patchset records */
  189730. u8 *aOldRecord1, /* old.* record for first change */
  189731. u8 *aOldRecord2, /* old.* record for second change */
  189732. u8 *aNewRecord1, /* new.* record for first change */
  189733. u8 *aNewRecord2 /* new.* record for second change */
  189734. ){
  189735. u8 *aOld1 = aOldRecord1;
  189736. u8 *aOld2 = aOldRecord2;
  189737. u8 *aNew1 = aNewRecord1;
  189738. u8 *aNew2 = aNewRecord2;
  189739. u8 *aOut = *paOut;
  189740. int i;
  189741. if( bPatchset==0 ){
  189742. int bRequired = 0;
  189743. assert( aOldRecord1 && aNewRecord1 );
  189744. /* Write the old.* vector first. */
  189745. for(i=0; i<pTab->nCol; i++){
  189746. int nOld;
  189747. u8 *aOld;
  189748. int nNew;
  189749. u8 *aNew;
  189750. aOld = sessionMergeValue(&aOld1, &aOld2, &nOld);
  189751. aNew = sessionMergeValue(&aNew1, &aNew2, &nNew);
  189752. if( pTab->abPK[i] || nOld!=nNew || memcmp(aOld, aNew, nNew) ){
  189753. if( pTab->abPK[i]==0 ) bRequired = 1;
  189754. memcpy(aOut, aOld, nOld);
  189755. aOut += nOld;
  189756. }else{
  189757. *(aOut++) = '\0';
  189758. }
  189759. }
  189760. if( !bRequired ) return 0;
  189761. }
  189762. /* Write the new.* vector */
  189763. aOld1 = aOldRecord1;
  189764. aOld2 = aOldRecord2;
  189765. aNew1 = aNewRecord1;
  189766. aNew2 = aNewRecord2;
  189767. for(i=0; i<pTab->nCol; i++){
  189768. int nOld;
  189769. u8 *aOld;
  189770. int nNew;
  189771. u8 *aNew;
  189772. aOld = sessionMergeValue(&aOld1, &aOld2, &nOld);
  189773. aNew = sessionMergeValue(&aNew1, &aNew2, &nNew);
  189774. if( bPatchset==0
  189775. && (pTab->abPK[i] || (nOld==nNew && 0==memcmp(aOld, aNew, nNew)))
  189776. ){
  189777. *(aOut++) = '\0';
  189778. }else{
  189779. memcpy(aOut, aNew, nNew);
  189780. aOut += nNew;
  189781. }
  189782. }
  189783. *paOut = aOut;
  189784. return 1;
  189785. }
  189786. /*
  189787. ** This function is only called from within a pre-update-hook callback.
  189788. ** It determines if the current pre-update-hook change affects the same row
  189789. ** as the change stored in argument pChange. If so, it returns true. Otherwise
  189790. ** if the pre-update-hook does not affect the same row as pChange, it returns
  189791. ** false.
  189792. */
  189793. static int sessionPreupdateEqual(
  189794. sqlite3_session *pSession, /* Session object that owns SessionTable */
  189795. SessionTable *pTab, /* Table associated with change */
  189796. SessionChange *pChange, /* Change to compare to */
  189797. int op /* Current pre-update operation */
  189798. ){
  189799. int iCol; /* Used to iterate through columns */
  189800. u8 *a = pChange->aRecord; /* Cursor used to scan change record */
  189801. assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
  189802. for(iCol=0; iCol<pTab->nCol; iCol++){
  189803. if( !pTab->abPK[iCol] ){
  189804. a += sessionSerialLen(a);
  189805. }else{
  189806. sqlite3_value *pVal; /* Value returned by preupdate_new/old */
  189807. int rc; /* Error code from preupdate_new/old */
  189808. int eType = *a++; /* Type of value from change record */
  189809. /* The following calls to preupdate_new() and preupdate_old() can not
  189810. ** fail. This is because they cache their return values, and by the
  189811. ** time control flows to here they have already been called once from
  189812. ** within sessionPreupdateHash(). The first two asserts below verify
  189813. ** this (that the method has already been called). */
  189814. if( op==SQLITE_INSERT ){
  189815. /* assert( db->pPreUpdate->pNewUnpacked || db->pPreUpdate->aNew ); */
  189816. rc = pSession->hook.xNew(pSession->hook.pCtx, iCol, &pVal);
  189817. }else{
  189818. /* assert( db->pPreUpdate->pUnpacked ); */
  189819. rc = pSession->hook.xOld(pSession->hook.pCtx, iCol, &pVal);
  189820. }
  189821. assert( rc==SQLITE_OK );
  189822. if( sqlite3_value_type(pVal)!=eType ) return 0;
  189823. /* A SessionChange object never has a NULL value in a PK column */
  189824. assert( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT
  189825. || eType==SQLITE_BLOB || eType==SQLITE_TEXT
  189826. );
  189827. if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
  189828. i64 iVal = sessionGetI64(a);
  189829. a += 8;
  189830. if( eType==SQLITE_INTEGER ){
  189831. if( sqlite3_value_int64(pVal)!=iVal ) return 0;
  189832. }else{
  189833. double rVal;
  189834. assert( sizeof(iVal)==8 && sizeof(rVal)==8 );
  189835. memcpy(&rVal, &iVal, 8);
  189836. if( sqlite3_value_double(pVal)!=rVal ) return 0;
  189837. }
  189838. }else{
  189839. int n;
  189840. const u8 *z;
  189841. a += sessionVarintGet(a, &n);
  189842. if( sqlite3_value_bytes(pVal)!=n ) return 0;
  189843. if( eType==SQLITE_TEXT ){
  189844. z = sqlite3_value_text(pVal);
  189845. }else{
  189846. z = sqlite3_value_blob(pVal);
  189847. }
  189848. if( n>0 && memcmp(a, z, n) ) return 0;
  189849. a += n;
  189850. }
  189851. }
  189852. }
  189853. return 1;
  189854. }
  189855. /*
  189856. ** If required, grow the hash table used to store changes on table pTab
  189857. ** (part of the session pSession). If a fatal OOM error occurs, set the
  189858. ** session object to failed and return SQLITE_ERROR. Otherwise, return
  189859. ** SQLITE_OK.
  189860. **
  189861. ** It is possible that a non-fatal OOM error occurs in this function. In
  189862. ** that case the hash-table does not grow, but SQLITE_OK is returned anyway.
  189863. ** Growing the hash table in this case is a performance optimization only,
  189864. ** it is not required for correct operation.
  189865. */
  189866. static int sessionGrowHash(int bPatchset, SessionTable *pTab){
  189867. if( pTab->nChange==0 || pTab->nEntry>=(pTab->nChange/2) ){
  189868. int i;
  189869. SessionChange **apNew;
  189870. sqlite3_int64 nNew = 2*(sqlite3_int64)(pTab->nChange ? pTab->nChange : 128);
  189871. apNew = (SessionChange **)sqlite3_malloc64(sizeof(SessionChange *) * nNew);
  189872. if( apNew==0 ){
  189873. if( pTab->nChange==0 ){
  189874. return SQLITE_ERROR;
  189875. }
  189876. return SQLITE_OK;
  189877. }
  189878. memset(apNew, 0, sizeof(SessionChange *) * nNew);
  189879. for(i=0; i<pTab->nChange; i++){
  189880. SessionChange *p;
  189881. SessionChange *pNext;
  189882. for(p=pTab->apChange[i]; p; p=pNext){
  189883. int bPkOnly = (p->op==SQLITE_DELETE && bPatchset);
  189884. int iHash = sessionChangeHash(pTab, bPkOnly, p->aRecord, nNew);
  189885. pNext = p->pNext;
  189886. p->pNext = apNew[iHash];
  189887. apNew[iHash] = p;
  189888. }
  189889. }
  189890. sqlite3_free(pTab->apChange);
  189891. pTab->nChange = nNew;
  189892. pTab->apChange = apNew;
  189893. }
  189894. return SQLITE_OK;
  189895. }
  189896. /*
  189897. ** This function queries the database for the names of the columns of table
  189898. ** zThis, in schema zDb.
  189899. **
  189900. ** Otherwise, if they are not NULL, variable *pnCol is set to the number
  189901. ** of columns in the database table and variable *pzTab is set to point to a
  189902. ** nul-terminated copy of the table name. *pazCol (if not NULL) is set to
  189903. ** point to an array of pointers to column names. And *pabPK (again, if not
  189904. ** NULL) is set to point to an array of booleans - true if the corresponding
  189905. ** column is part of the primary key.
  189906. **
  189907. ** For example, if the table is declared as:
  189908. **
  189909. ** CREATE TABLE tbl1(w, x, y, z, PRIMARY KEY(w, z));
  189910. **
  189911. ** Then the four output variables are populated as follows:
  189912. **
  189913. ** *pnCol = 4
  189914. ** *pzTab = "tbl1"
  189915. ** *pazCol = {"w", "x", "y", "z"}
  189916. ** *pabPK = {1, 0, 0, 1}
  189917. **
  189918. ** All returned buffers are part of the same single allocation, which must
  189919. ** be freed using sqlite3_free() by the caller
  189920. */
  189921. static int sessionTableInfo(
  189922. sqlite3 *db, /* Database connection */
  189923. const char *zDb, /* Name of attached database (e.g. "main") */
  189924. const char *zThis, /* Table name */
  189925. int *pnCol, /* OUT: number of columns */
  189926. const char **pzTab, /* OUT: Copy of zThis */
  189927. const char ***pazCol, /* OUT: Array of column names for table */
  189928. u8 **pabPK /* OUT: Array of booleans - true for PK col */
  189929. ){
  189930. char *zPragma;
  189931. sqlite3_stmt *pStmt;
  189932. int rc;
  189933. sqlite3_int64 nByte;
  189934. int nDbCol = 0;
  189935. int nThis;
  189936. int i;
  189937. u8 *pAlloc = 0;
  189938. char **azCol = 0;
  189939. u8 *abPK = 0;
  189940. assert( pazCol && pabPK );
  189941. nThis = sqlite3Strlen30(zThis);
  189942. if( nThis==12 && 0==sqlite3_stricmp("sqlite_stat1", zThis) ){
  189943. rc = sqlite3_table_column_metadata(db, zDb, zThis, 0, 0, 0, 0, 0, 0);
  189944. if( rc==SQLITE_OK ){
  189945. /* For sqlite_stat1, pretend that (tbl,idx) is the PRIMARY KEY. */
  189946. zPragma = sqlite3_mprintf(
  189947. "SELECT 0, 'tbl', '', 0, '', 1 UNION ALL "
  189948. "SELECT 1, 'idx', '', 0, '', 2 UNION ALL "
  189949. "SELECT 2, 'stat', '', 0, '', 0"
  189950. );
  189951. }else if( rc==SQLITE_ERROR ){
  189952. zPragma = sqlite3_mprintf("");
  189953. }else{
  189954. return rc;
  189955. }
  189956. }else{
  189957. zPragma = sqlite3_mprintf("PRAGMA '%q'.table_info('%q')", zDb, zThis);
  189958. }
  189959. if( !zPragma ) return SQLITE_NOMEM;
  189960. rc = sqlite3_prepare_v2(db, zPragma, -1, &pStmt, 0);
  189961. sqlite3_free(zPragma);
  189962. if( rc!=SQLITE_OK ) return rc;
  189963. nByte = nThis + 1;
  189964. while( SQLITE_ROW==sqlite3_step(pStmt) ){
  189965. nByte += sqlite3_column_bytes(pStmt, 1);
  189966. nDbCol++;
  189967. }
  189968. rc = sqlite3_reset(pStmt);
  189969. if( rc==SQLITE_OK ){
  189970. nByte += nDbCol * (sizeof(const char *) + sizeof(u8) + 1);
  189971. pAlloc = sqlite3_malloc64(nByte);
  189972. if( pAlloc==0 ){
  189973. rc = SQLITE_NOMEM;
  189974. }
  189975. }
  189976. if( rc==SQLITE_OK ){
  189977. azCol = (char **)pAlloc;
  189978. pAlloc = (u8 *)&azCol[nDbCol];
  189979. abPK = (u8 *)pAlloc;
  189980. pAlloc = &abPK[nDbCol];
  189981. if( pzTab ){
  189982. memcpy(pAlloc, zThis, nThis+1);
  189983. *pzTab = (char *)pAlloc;
  189984. pAlloc += nThis+1;
  189985. }
  189986. i = 0;
  189987. while( SQLITE_ROW==sqlite3_step(pStmt) ){
  189988. int nName = sqlite3_column_bytes(pStmt, 1);
  189989. const unsigned char *zName = sqlite3_column_text(pStmt, 1);
  189990. if( zName==0 ) break;
  189991. memcpy(pAlloc, zName, nName+1);
  189992. azCol[i] = (char *)pAlloc;
  189993. pAlloc += nName+1;
  189994. abPK[i] = sqlite3_column_int(pStmt, 5);
  189995. i++;
  189996. }
  189997. rc = sqlite3_reset(pStmt);
  189998. }
  189999. /* If successful, populate the output variables. Otherwise, zero them and
  190000. ** free any allocation made. An error code will be returned in this case.
  190001. */
  190002. if( rc==SQLITE_OK ){
  190003. *pazCol = (const char **)azCol;
  190004. *pabPK = abPK;
  190005. *pnCol = nDbCol;
  190006. }else{
  190007. *pazCol = 0;
  190008. *pabPK = 0;
  190009. *pnCol = 0;
  190010. if( pzTab ) *pzTab = 0;
  190011. sqlite3_free(azCol);
  190012. }
  190013. sqlite3_finalize(pStmt);
  190014. return rc;
  190015. }
  190016. /*
  190017. ** This function is only called from within a pre-update handler for a
  190018. ** write to table pTab, part of session pSession. If this is the first
  190019. ** write to this table, initalize the SessionTable.nCol, azCol[] and
  190020. ** abPK[] arrays accordingly.
  190021. **
  190022. ** If an error occurs, an error code is stored in sqlite3_session.rc and
  190023. ** non-zero returned. Or, if no error occurs but the table has no primary
  190024. ** key, sqlite3_session.rc is left set to SQLITE_OK and non-zero returned to
  190025. ** indicate that updates on this table should be ignored. SessionTable.abPK
  190026. ** is set to NULL in this case.
  190027. */
  190028. static int sessionInitTable(sqlite3_session *pSession, SessionTable *pTab){
  190029. if( pTab->nCol==0 ){
  190030. u8 *abPK;
  190031. assert( pTab->azCol==0 || pTab->abPK==0 );
  190032. pSession->rc = sessionTableInfo(pSession->db, pSession->zDb,
  190033. pTab->zName, &pTab->nCol, 0, &pTab->azCol, &abPK
  190034. );
  190035. if( pSession->rc==SQLITE_OK ){
  190036. int i;
  190037. for(i=0; i<pTab->nCol; i++){
  190038. if( abPK[i] ){
  190039. pTab->abPK = abPK;
  190040. break;
  190041. }
  190042. }
  190043. if( 0==sqlite3_stricmp("sqlite_stat1", pTab->zName) ){
  190044. pTab->bStat1 = 1;
  190045. }
  190046. }
  190047. }
  190048. return (pSession->rc || pTab->abPK==0);
  190049. }
  190050. /*
  190051. ** Versions of the four methods in object SessionHook for use with the
  190052. ** sqlite_stat1 table. The purpose of this is to substitute a zero-length
  190053. ** blob each time a NULL value is read from the "idx" column of the
  190054. ** sqlite_stat1 table.
  190055. */
  190056. typedef struct SessionStat1Ctx SessionStat1Ctx;
  190057. struct SessionStat1Ctx {
  190058. SessionHook hook;
  190059. sqlite3_session *pSession;
  190060. };
  190061. static int sessionStat1Old(void *pCtx, int iCol, sqlite3_value **ppVal){
  190062. SessionStat1Ctx *p = (SessionStat1Ctx*)pCtx;
  190063. sqlite3_value *pVal = 0;
  190064. int rc = p->hook.xOld(p->hook.pCtx, iCol, &pVal);
  190065. if( rc==SQLITE_OK && iCol==1 && sqlite3_value_type(pVal)==SQLITE_NULL ){
  190066. pVal = p->pSession->pZeroBlob;
  190067. }
  190068. *ppVal = pVal;
  190069. return rc;
  190070. }
  190071. static int sessionStat1New(void *pCtx, int iCol, sqlite3_value **ppVal){
  190072. SessionStat1Ctx *p = (SessionStat1Ctx*)pCtx;
  190073. sqlite3_value *pVal = 0;
  190074. int rc = p->hook.xNew(p->hook.pCtx, iCol, &pVal);
  190075. if( rc==SQLITE_OK && iCol==1 && sqlite3_value_type(pVal)==SQLITE_NULL ){
  190076. pVal = p->pSession->pZeroBlob;
  190077. }
  190078. *ppVal = pVal;
  190079. return rc;
  190080. }
  190081. static int sessionStat1Count(void *pCtx){
  190082. SessionStat1Ctx *p = (SessionStat1Ctx*)pCtx;
  190083. return p->hook.xCount(p->hook.pCtx);
  190084. }
  190085. static int sessionStat1Depth(void *pCtx){
  190086. SessionStat1Ctx *p = (SessionStat1Ctx*)pCtx;
  190087. return p->hook.xDepth(p->hook.pCtx);
  190088. }
  190089. /*
  190090. ** This function is only called from with a pre-update-hook reporting a
  190091. ** change on table pTab (attached to session pSession). The type of change
  190092. ** (UPDATE, INSERT, DELETE) is specified by the first argument.
  190093. **
  190094. ** Unless one is already present or an error occurs, an entry is added
  190095. ** to the changed-rows hash table associated with table pTab.
  190096. */
  190097. static void sessionPreupdateOneChange(
  190098. int op, /* One of SQLITE_UPDATE, INSERT, DELETE */
  190099. sqlite3_session *pSession, /* Session object pTab is attached to */
  190100. SessionTable *pTab /* Table that change applies to */
  190101. ){
  190102. int iHash;
  190103. int bNull = 0;
  190104. int rc = SQLITE_OK;
  190105. SessionStat1Ctx stat1 = {{0,0,0,0,0},0};
  190106. if( pSession->rc ) return;
  190107. /* Load table details if required */
  190108. if( sessionInitTable(pSession, pTab) ) return;
  190109. /* Check the number of columns in this xPreUpdate call matches the
  190110. ** number of columns in the table. */
  190111. if( pTab->nCol!=pSession->hook.xCount(pSession->hook.pCtx) ){
  190112. pSession->rc = SQLITE_SCHEMA;
  190113. return;
  190114. }
  190115. /* Grow the hash table if required */
  190116. if( sessionGrowHash(0, pTab) ){
  190117. pSession->rc = SQLITE_NOMEM;
  190118. return;
  190119. }
  190120. if( pTab->bStat1 ){
  190121. stat1.hook = pSession->hook;
  190122. stat1.pSession = pSession;
  190123. pSession->hook.pCtx = (void*)&stat1;
  190124. pSession->hook.xNew = sessionStat1New;
  190125. pSession->hook.xOld = sessionStat1Old;
  190126. pSession->hook.xCount = sessionStat1Count;
  190127. pSession->hook.xDepth = sessionStat1Depth;
  190128. if( pSession->pZeroBlob==0 ){
  190129. sqlite3_value *p = sqlite3ValueNew(0);
  190130. if( p==0 ){
  190131. rc = SQLITE_NOMEM;
  190132. goto error_out;
  190133. }
  190134. sqlite3ValueSetStr(p, 0, "", 0, SQLITE_STATIC);
  190135. pSession->pZeroBlob = p;
  190136. }
  190137. }
  190138. /* Calculate the hash-key for this change. If the primary key of the row
  190139. ** includes a NULL value, exit early. Such changes are ignored by the
  190140. ** session module. */
  190141. rc = sessionPreupdateHash(pSession, pTab, op==SQLITE_INSERT, &iHash, &bNull);
  190142. if( rc!=SQLITE_OK ) goto error_out;
  190143. if( bNull==0 ){
  190144. /* Search the hash table for an existing record for this row. */
  190145. SessionChange *pC;
  190146. for(pC=pTab->apChange[iHash]; pC; pC=pC->pNext){
  190147. if( sessionPreupdateEqual(pSession, pTab, pC, op) ) break;
  190148. }
  190149. if( pC==0 ){
  190150. /* Create a new change object containing all the old values (if
  190151. ** this is an SQLITE_UPDATE or SQLITE_DELETE), or just the PK
  190152. ** values (if this is an INSERT). */
  190153. SessionChange *pChange; /* New change object */
  190154. sqlite3_int64 nByte; /* Number of bytes to allocate */
  190155. int i; /* Used to iterate through columns */
  190156. assert( rc==SQLITE_OK );
  190157. pTab->nEntry++;
  190158. /* Figure out how large an allocation is required */
  190159. nByte = sizeof(SessionChange);
  190160. for(i=0; i<pTab->nCol; i++){
  190161. sqlite3_value *p = 0;
  190162. if( op!=SQLITE_INSERT ){
  190163. TESTONLY(int trc = ) pSession->hook.xOld(pSession->hook.pCtx, i, &p);
  190164. assert( trc==SQLITE_OK );
  190165. }else if( pTab->abPK[i] ){
  190166. TESTONLY(int trc = ) pSession->hook.xNew(pSession->hook.pCtx, i, &p);
  190167. assert( trc==SQLITE_OK );
  190168. }
  190169. /* This may fail if SQLite value p contains a utf-16 string that must
  190170. ** be converted to utf-8 and an OOM error occurs while doing so. */
  190171. rc = sessionSerializeValue(0, p, &nByte);
  190172. if( rc!=SQLITE_OK ) goto error_out;
  190173. }
  190174. /* Allocate the change object */
  190175. pChange = (SessionChange *)sqlite3_malloc64(nByte);
  190176. if( !pChange ){
  190177. rc = SQLITE_NOMEM;
  190178. goto error_out;
  190179. }else{
  190180. memset(pChange, 0, sizeof(SessionChange));
  190181. pChange->aRecord = (u8 *)&pChange[1];
  190182. }
  190183. /* Populate the change object. None of the preupdate_old(),
  190184. ** preupdate_new() or SerializeValue() calls below may fail as all
  190185. ** required values and encodings have already been cached in memory.
  190186. ** It is not possible for an OOM to occur in this block. */
  190187. nByte = 0;
  190188. for(i=0; i<pTab->nCol; i++){
  190189. sqlite3_value *p = 0;
  190190. if( op!=SQLITE_INSERT ){
  190191. pSession->hook.xOld(pSession->hook.pCtx, i, &p);
  190192. }else if( pTab->abPK[i] ){
  190193. pSession->hook.xNew(pSession->hook.pCtx, i, &p);
  190194. }
  190195. sessionSerializeValue(&pChange->aRecord[nByte], p, &nByte);
  190196. }
  190197. /* Add the change to the hash-table */
  190198. if( pSession->bIndirect || pSession->hook.xDepth(pSession->hook.pCtx) ){
  190199. pChange->bIndirect = 1;
  190200. }
  190201. pChange->nRecord = nByte;
  190202. pChange->op = op;
  190203. pChange->pNext = pTab->apChange[iHash];
  190204. pTab->apChange[iHash] = pChange;
  190205. }else if( pC->bIndirect ){
  190206. /* If the existing change is considered "indirect", but this current
  190207. ** change is "direct", mark the change object as direct. */
  190208. if( pSession->hook.xDepth(pSession->hook.pCtx)==0
  190209. && pSession->bIndirect==0
  190210. ){
  190211. pC->bIndirect = 0;
  190212. }
  190213. }
  190214. }
  190215. /* If an error has occurred, mark the session object as failed. */
  190216. error_out:
  190217. if( pTab->bStat1 ){
  190218. pSession->hook = stat1.hook;
  190219. }
  190220. if( rc!=SQLITE_OK ){
  190221. pSession->rc = rc;
  190222. }
  190223. }
  190224. static int sessionFindTable(
  190225. sqlite3_session *pSession,
  190226. const char *zName,
  190227. SessionTable **ppTab
  190228. ){
  190229. int rc = SQLITE_OK;
  190230. int nName = sqlite3Strlen30(zName);
  190231. SessionTable *pRet;
  190232. /* Search for an existing table */
  190233. for(pRet=pSession->pTable; pRet; pRet=pRet->pNext){
  190234. if( 0==sqlite3_strnicmp(pRet->zName, zName, nName+1) ) break;
  190235. }
  190236. if( pRet==0 && pSession->bAutoAttach ){
  190237. /* If there is a table-filter configured, invoke it. If it returns 0,
  190238. ** do not automatically add the new table. */
  190239. if( pSession->xTableFilter==0
  190240. || pSession->xTableFilter(pSession->pFilterCtx, zName)
  190241. ){
  190242. rc = sqlite3session_attach(pSession, zName);
  190243. if( rc==SQLITE_OK ){
  190244. for(pRet=pSession->pTable; pRet->pNext; pRet=pRet->pNext);
  190245. assert( 0==sqlite3_strnicmp(pRet->zName, zName, nName+1) );
  190246. }
  190247. }
  190248. }
  190249. assert( rc==SQLITE_OK || pRet==0 );
  190250. *ppTab = pRet;
  190251. return rc;
  190252. }
  190253. /*
  190254. ** The 'pre-update' hook registered by this module with SQLite databases.
  190255. */
  190256. static void xPreUpdate(
  190257. void *pCtx, /* Copy of third arg to preupdate_hook() */
  190258. sqlite3 *db, /* Database handle */
  190259. int op, /* SQLITE_UPDATE, DELETE or INSERT */
  190260. char const *zDb, /* Database name */
  190261. char const *zName, /* Table name */
  190262. sqlite3_int64 iKey1, /* Rowid of row about to be deleted/updated */
  190263. sqlite3_int64 iKey2 /* New rowid value (for a rowid UPDATE) */
  190264. ){
  190265. sqlite3_session *pSession;
  190266. int nDb = sqlite3Strlen30(zDb);
  190267. assert( sqlite3_mutex_held(db->mutex) );
  190268. for(pSession=(sqlite3_session *)pCtx; pSession; pSession=pSession->pNext){
  190269. SessionTable *pTab;
  190270. /* If this session is attached to a different database ("main", "temp"
  190271. ** etc.), or if it is not currently enabled, there is nothing to do. Skip
  190272. ** to the next session object attached to this database. */
  190273. if( pSession->bEnable==0 ) continue;
  190274. if( pSession->rc ) continue;
  190275. if( sqlite3_strnicmp(zDb, pSession->zDb, nDb+1) ) continue;
  190276. pSession->rc = sessionFindTable(pSession, zName, &pTab);
  190277. if( pTab ){
  190278. assert( pSession->rc==SQLITE_OK );
  190279. sessionPreupdateOneChange(op, pSession, pTab);
  190280. if( op==SQLITE_UPDATE ){
  190281. sessionPreupdateOneChange(SQLITE_INSERT, pSession, pTab);
  190282. }
  190283. }
  190284. }
  190285. }
  190286. /*
  190287. ** The pre-update hook implementations.
  190288. */
  190289. static int sessionPreupdateOld(void *pCtx, int iVal, sqlite3_value **ppVal){
  190290. return sqlite3_preupdate_old((sqlite3*)pCtx, iVal, ppVal);
  190291. }
  190292. static int sessionPreupdateNew(void *pCtx, int iVal, sqlite3_value **ppVal){
  190293. return sqlite3_preupdate_new((sqlite3*)pCtx, iVal, ppVal);
  190294. }
  190295. static int sessionPreupdateCount(void *pCtx){
  190296. return sqlite3_preupdate_count((sqlite3*)pCtx);
  190297. }
  190298. static int sessionPreupdateDepth(void *pCtx){
  190299. return sqlite3_preupdate_depth((sqlite3*)pCtx);
  190300. }
  190301. /*
  190302. ** Install the pre-update hooks on the session object passed as the only
  190303. ** argument.
  190304. */
  190305. static void sessionPreupdateHooks(
  190306. sqlite3_session *pSession
  190307. ){
  190308. pSession->hook.pCtx = (void*)pSession->db;
  190309. pSession->hook.xOld = sessionPreupdateOld;
  190310. pSession->hook.xNew = sessionPreupdateNew;
  190311. pSession->hook.xCount = sessionPreupdateCount;
  190312. pSession->hook.xDepth = sessionPreupdateDepth;
  190313. }
  190314. typedef struct SessionDiffCtx SessionDiffCtx;
  190315. struct SessionDiffCtx {
  190316. sqlite3_stmt *pStmt;
  190317. int nOldOff;
  190318. };
  190319. /*
  190320. ** The diff hook implementations.
  190321. */
  190322. static int sessionDiffOld(void *pCtx, int iVal, sqlite3_value **ppVal){
  190323. SessionDiffCtx *p = (SessionDiffCtx*)pCtx;
  190324. *ppVal = sqlite3_column_value(p->pStmt, iVal+p->nOldOff);
  190325. return SQLITE_OK;
  190326. }
  190327. static int sessionDiffNew(void *pCtx, int iVal, sqlite3_value **ppVal){
  190328. SessionDiffCtx *p = (SessionDiffCtx*)pCtx;
  190329. *ppVal = sqlite3_column_value(p->pStmt, iVal);
  190330. return SQLITE_OK;
  190331. }
  190332. static int sessionDiffCount(void *pCtx){
  190333. SessionDiffCtx *p = (SessionDiffCtx*)pCtx;
  190334. return p->nOldOff ? p->nOldOff : sqlite3_column_count(p->pStmt);
  190335. }
  190336. static int sessionDiffDepth(void *pCtx){
  190337. return 0;
  190338. }
  190339. /*
  190340. ** Install the diff hooks on the session object passed as the only
  190341. ** argument.
  190342. */
  190343. static void sessionDiffHooks(
  190344. sqlite3_session *pSession,
  190345. SessionDiffCtx *pDiffCtx
  190346. ){
  190347. pSession->hook.pCtx = (void*)pDiffCtx;
  190348. pSession->hook.xOld = sessionDiffOld;
  190349. pSession->hook.xNew = sessionDiffNew;
  190350. pSession->hook.xCount = sessionDiffCount;
  190351. pSession->hook.xDepth = sessionDiffDepth;
  190352. }
  190353. static char *sessionExprComparePK(
  190354. int nCol,
  190355. const char *zDb1, const char *zDb2,
  190356. const char *zTab,
  190357. const char **azCol, u8 *abPK
  190358. ){
  190359. int i;
  190360. const char *zSep = "";
  190361. char *zRet = 0;
  190362. for(i=0; i<nCol; i++){
  190363. if( abPK[i] ){
  190364. zRet = sqlite3_mprintf("%z%s\"%w\".\"%w\".\"%w\"=\"%w\".\"%w\".\"%w\"",
  190365. zRet, zSep, zDb1, zTab, azCol[i], zDb2, zTab, azCol[i]
  190366. );
  190367. zSep = " AND ";
  190368. if( zRet==0 ) break;
  190369. }
  190370. }
  190371. return zRet;
  190372. }
  190373. static char *sessionExprCompareOther(
  190374. int nCol,
  190375. const char *zDb1, const char *zDb2,
  190376. const char *zTab,
  190377. const char **azCol, u8 *abPK
  190378. ){
  190379. int i;
  190380. const char *zSep = "";
  190381. char *zRet = 0;
  190382. int bHave = 0;
  190383. for(i=0; i<nCol; i++){
  190384. if( abPK[i]==0 ){
  190385. bHave = 1;
  190386. zRet = sqlite3_mprintf(
  190387. "%z%s\"%w\".\"%w\".\"%w\" IS NOT \"%w\".\"%w\".\"%w\"",
  190388. zRet, zSep, zDb1, zTab, azCol[i], zDb2, zTab, azCol[i]
  190389. );
  190390. zSep = " OR ";
  190391. if( zRet==0 ) break;
  190392. }
  190393. }
  190394. if( bHave==0 ){
  190395. assert( zRet==0 );
  190396. zRet = sqlite3_mprintf("0");
  190397. }
  190398. return zRet;
  190399. }
  190400. static char *sessionSelectFindNew(
  190401. int nCol,
  190402. const char *zDb1, /* Pick rows in this db only */
  190403. const char *zDb2, /* But not in this one */
  190404. const char *zTbl, /* Table name */
  190405. const char *zExpr
  190406. ){
  190407. char *zRet = sqlite3_mprintf(
  190408. "SELECT * FROM \"%w\".\"%w\" WHERE NOT EXISTS ("
  190409. " SELECT 1 FROM \"%w\".\"%w\" WHERE %s"
  190410. ")",
  190411. zDb1, zTbl, zDb2, zTbl, zExpr
  190412. );
  190413. return zRet;
  190414. }
  190415. static int sessionDiffFindNew(
  190416. int op,
  190417. sqlite3_session *pSession,
  190418. SessionTable *pTab,
  190419. const char *zDb1,
  190420. const char *zDb2,
  190421. char *zExpr
  190422. ){
  190423. int rc = SQLITE_OK;
  190424. char *zStmt = sessionSelectFindNew(pTab->nCol, zDb1, zDb2, pTab->zName,zExpr);
  190425. if( zStmt==0 ){
  190426. rc = SQLITE_NOMEM;
  190427. }else{
  190428. sqlite3_stmt *pStmt;
  190429. rc = sqlite3_prepare(pSession->db, zStmt, -1, &pStmt, 0);
  190430. if( rc==SQLITE_OK ){
  190431. SessionDiffCtx *pDiffCtx = (SessionDiffCtx*)pSession->hook.pCtx;
  190432. pDiffCtx->pStmt = pStmt;
  190433. pDiffCtx->nOldOff = 0;
  190434. while( SQLITE_ROW==sqlite3_step(pStmt) ){
  190435. sessionPreupdateOneChange(op, pSession, pTab);
  190436. }
  190437. rc = sqlite3_finalize(pStmt);
  190438. }
  190439. sqlite3_free(zStmt);
  190440. }
  190441. return rc;
  190442. }
  190443. static int sessionDiffFindModified(
  190444. sqlite3_session *pSession,
  190445. SessionTable *pTab,
  190446. const char *zFrom,
  190447. const char *zExpr
  190448. ){
  190449. int rc = SQLITE_OK;
  190450. char *zExpr2 = sessionExprCompareOther(pTab->nCol,
  190451. pSession->zDb, zFrom, pTab->zName, pTab->azCol, pTab->abPK
  190452. );
  190453. if( zExpr2==0 ){
  190454. rc = SQLITE_NOMEM;
  190455. }else{
  190456. char *zStmt = sqlite3_mprintf(
  190457. "SELECT * FROM \"%w\".\"%w\", \"%w\".\"%w\" WHERE %s AND (%z)",
  190458. pSession->zDb, pTab->zName, zFrom, pTab->zName, zExpr, zExpr2
  190459. );
  190460. if( zStmt==0 ){
  190461. rc = SQLITE_NOMEM;
  190462. }else{
  190463. sqlite3_stmt *pStmt;
  190464. rc = sqlite3_prepare(pSession->db, zStmt, -1, &pStmt, 0);
  190465. if( rc==SQLITE_OK ){
  190466. SessionDiffCtx *pDiffCtx = (SessionDiffCtx*)pSession->hook.pCtx;
  190467. pDiffCtx->pStmt = pStmt;
  190468. pDiffCtx->nOldOff = pTab->nCol;
  190469. while( SQLITE_ROW==sqlite3_step(pStmt) ){
  190470. sessionPreupdateOneChange(SQLITE_UPDATE, pSession, pTab);
  190471. }
  190472. rc = sqlite3_finalize(pStmt);
  190473. }
  190474. sqlite3_free(zStmt);
  190475. }
  190476. }
  190477. return rc;
  190478. }
  190479. SQLITE_API int sqlite3session_diff(
  190480. sqlite3_session *pSession,
  190481. const char *zFrom,
  190482. const char *zTbl,
  190483. char **pzErrMsg
  190484. ){
  190485. const char *zDb = pSession->zDb;
  190486. int rc = pSession->rc;
  190487. SessionDiffCtx d;
  190488. memset(&d, 0, sizeof(d));
  190489. sessionDiffHooks(pSession, &d);
  190490. sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
  190491. if( pzErrMsg ) *pzErrMsg = 0;
  190492. if( rc==SQLITE_OK ){
  190493. char *zExpr = 0;
  190494. sqlite3 *db = pSession->db;
  190495. SessionTable *pTo; /* Table zTbl */
  190496. /* Locate and if necessary initialize the target table object */
  190497. rc = sessionFindTable(pSession, zTbl, &pTo);
  190498. if( pTo==0 ) goto diff_out;
  190499. if( sessionInitTable(pSession, pTo) ){
  190500. rc = pSession->rc;
  190501. goto diff_out;
  190502. }
  190503. /* Check the table schemas match */
  190504. if( rc==SQLITE_OK ){
  190505. int bHasPk = 0;
  190506. int bMismatch = 0;
  190507. int nCol; /* Columns in zFrom.zTbl */
  190508. u8 *abPK;
  190509. const char **azCol = 0;
  190510. rc = sessionTableInfo(db, zFrom, zTbl, &nCol, 0, &azCol, &abPK);
  190511. if( rc==SQLITE_OK ){
  190512. if( pTo->nCol!=nCol ){
  190513. bMismatch = 1;
  190514. }else{
  190515. int i;
  190516. for(i=0; i<nCol; i++){
  190517. if( pTo->abPK[i]!=abPK[i] ) bMismatch = 1;
  190518. if( sqlite3_stricmp(azCol[i], pTo->azCol[i]) ) bMismatch = 1;
  190519. if( abPK[i] ) bHasPk = 1;
  190520. }
  190521. }
  190522. }
  190523. sqlite3_free((char*)azCol);
  190524. if( bMismatch ){
  190525. if( pzErrMsg ){
  190526. *pzErrMsg = sqlite3_mprintf("table schemas do not match");
  190527. }
  190528. rc = SQLITE_SCHEMA;
  190529. }
  190530. if( bHasPk==0 ){
  190531. /* Ignore tables with no primary keys */
  190532. goto diff_out;
  190533. }
  190534. }
  190535. if( rc==SQLITE_OK ){
  190536. zExpr = sessionExprComparePK(pTo->nCol,
  190537. zDb, zFrom, pTo->zName, pTo->azCol, pTo->abPK
  190538. );
  190539. }
  190540. /* Find new rows */
  190541. if( rc==SQLITE_OK ){
  190542. rc = sessionDiffFindNew(SQLITE_INSERT, pSession, pTo, zDb, zFrom, zExpr);
  190543. }
  190544. /* Find old rows */
  190545. if( rc==SQLITE_OK ){
  190546. rc = sessionDiffFindNew(SQLITE_DELETE, pSession, pTo, zFrom, zDb, zExpr);
  190547. }
  190548. /* Find modified rows */
  190549. if( rc==SQLITE_OK ){
  190550. rc = sessionDiffFindModified(pSession, pTo, zFrom, zExpr);
  190551. }
  190552. sqlite3_free(zExpr);
  190553. }
  190554. diff_out:
  190555. sessionPreupdateHooks(pSession);
  190556. sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
  190557. return rc;
  190558. }
  190559. /*
  190560. ** Create a session object. This session object will record changes to
  190561. ** database zDb attached to connection db.
  190562. */
  190563. SQLITE_API int sqlite3session_create(
  190564. sqlite3 *db, /* Database handle */
  190565. const char *zDb, /* Name of db (e.g. "main") */
  190566. sqlite3_session **ppSession /* OUT: New session object */
  190567. ){
  190568. sqlite3_session *pNew; /* Newly allocated session object */
  190569. sqlite3_session *pOld; /* Session object already attached to db */
  190570. int nDb = sqlite3Strlen30(zDb); /* Length of zDb in bytes */
  190571. /* Zero the output value in case an error occurs. */
  190572. *ppSession = 0;
  190573. /* Allocate and populate the new session object. */
  190574. pNew = (sqlite3_session *)sqlite3_malloc64(sizeof(sqlite3_session) + nDb + 1);
  190575. if( !pNew ) return SQLITE_NOMEM;
  190576. memset(pNew, 0, sizeof(sqlite3_session));
  190577. pNew->db = db;
  190578. pNew->zDb = (char *)&pNew[1];
  190579. pNew->bEnable = 1;
  190580. memcpy(pNew->zDb, zDb, nDb+1);
  190581. sessionPreupdateHooks(pNew);
  190582. /* Add the new session object to the linked list of session objects
  190583. ** attached to database handle $db. Do this under the cover of the db
  190584. ** handle mutex. */
  190585. sqlite3_mutex_enter(sqlite3_db_mutex(db));
  190586. pOld = (sqlite3_session*)sqlite3_preupdate_hook(db, xPreUpdate, (void*)pNew);
  190587. pNew->pNext = pOld;
  190588. sqlite3_mutex_leave(sqlite3_db_mutex(db));
  190589. *ppSession = pNew;
  190590. return SQLITE_OK;
  190591. }
  190592. /*
  190593. ** Free the list of table objects passed as the first argument. The contents
  190594. ** of the changed-rows hash tables are also deleted.
  190595. */
  190596. static void sessionDeleteTable(SessionTable *pList){
  190597. SessionTable *pNext;
  190598. SessionTable *pTab;
  190599. for(pTab=pList; pTab; pTab=pNext){
  190600. int i;
  190601. pNext = pTab->pNext;
  190602. for(i=0; i<pTab->nChange; i++){
  190603. SessionChange *p;
  190604. SessionChange *pNextChange;
  190605. for(p=pTab->apChange[i]; p; p=pNextChange){
  190606. pNextChange = p->pNext;
  190607. sqlite3_free(p);
  190608. }
  190609. }
  190610. sqlite3_free((char*)pTab->azCol); /* cast works around VC++ bug */
  190611. sqlite3_free(pTab->apChange);
  190612. sqlite3_free(pTab);
  190613. }
  190614. }
  190615. /*
  190616. ** Delete a session object previously allocated using sqlite3session_create().
  190617. */
  190618. SQLITE_API void sqlite3session_delete(sqlite3_session *pSession){
  190619. sqlite3 *db = pSession->db;
  190620. sqlite3_session *pHead;
  190621. sqlite3_session **pp;
  190622. /* Unlink the session from the linked list of sessions attached to the
  190623. ** database handle. Hold the db mutex while doing so. */
  190624. sqlite3_mutex_enter(sqlite3_db_mutex(db));
  190625. pHead = (sqlite3_session*)sqlite3_preupdate_hook(db, 0, 0);
  190626. for(pp=&pHead; ALWAYS((*pp)!=0); pp=&((*pp)->pNext)){
  190627. if( (*pp)==pSession ){
  190628. *pp = (*pp)->pNext;
  190629. if( pHead ) sqlite3_preupdate_hook(db, xPreUpdate, (void*)pHead);
  190630. break;
  190631. }
  190632. }
  190633. sqlite3_mutex_leave(sqlite3_db_mutex(db));
  190634. sqlite3ValueFree(pSession->pZeroBlob);
  190635. /* Delete all attached table objects. And the contents of their
  190636. ** associated hash-tables. */
  190637. sessionDeleteTable(pSession->pTable);
  190638. /* Free the session object itself. */
  190639. sqlite3_free(pSession);
  190640. }
  190641. /*
  190642. ** Set a table filter on a Session Object.
  190643. */
  190644. SQLITE_API void sqlite3session_table_filter(
  190645. sqlite3_session *pSession,
  190646. int(*xFilter)(void*, const char*),
  190647. void *pCtx /* First argument passed to xFilter */
  190648. ){
  190649. pSession->bAutoAttach = 1;
  190650. pSession->pFilterCtx = pCtx;
  190651. pSession->xTableFilter = xFilter;
  190652. }
  190653. /*
  190654. ** Attach a table to a session. All subsequent changes made to the table
  190655. ** while the session object is enabled will be recorded.
  190656. **
  190657. ** Only tables that have a PRIMARY KEY defined may be attached. It does
  190658. ** not matter if the PRIMARY KEY is an "INTEGER PRIMARY KEY" (rowid alias)
  190659. ** or not.
  190660. */
  190661. SQLITE_API int sqlite3session_attach(
  190662. sqlite3_session *pSession, /* Session object */
  190663. const char *zName /* Table name */
  190664. ){
  190665. int rc = SQLITE_OK;
  190666. sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
  190667. if( !zName ){
  190668. pSession->bAutoAttach = 1;
  190669. }else{
  190670. SessionTable *pTab; /* New table object (if required) */
  190671. int nName; /* Number of bytes in string zName */
  190672. /* First search for an existing entry. If one is found, this call is
  190673. ** a no-op. Return early. */
  190674. nName = sqlite3Strlen30(zName);
  190675. for(pTab=pSession->pTable; pTab; pTab=pTab->pNext){
  190676. if( 0==sqlite3_strnicmp(pTab->zName, zName, nName+1) ) break;
  190677. }
  190678. if( !pTab ){
  190679. /* Allocate new SessionTable object. */
  190680. pTab = (SessionTable *)sqlite3_malloc64(sizeof(SessionTable) + nName + 1);
  190681. if( !pTab ){
  190682. rc = SQLITE_NOMEM;
  190683. }else{
  190684. /* Populate the new SessionTable object and link it into the list.
  190685. ** The new object must be linked onto the end of the list, not
  190686. ** simply added to the start of it in order to ensure that tables
  190687. ** appear in the correct order when a changeset or patchset is
  190688. ** eventually generated. */
  190689. SessionTable **ppTab;
  190690. memset(pTab, 0, sizeof(SessionTable));
  190691. pTab->zName = (char *)&pTab[1];
  190692. memcpy(pTab->zName, zName, nName+1);
  190693. for(ppTab=&pSession->pTable; *ppTab; ppTab=&(*ppTab)->pNext);
  190694. *ppTab = pTab;
  190695. }
  190696. }
  190697. }
  190698. sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
  190699. return rc;
  190700. }
  190701. /*
  190702. ** Ensure that there is room in the buffer to append nByte bytes of data.
  190703. ** If not, use sqlite3_realloc() to grow the buffer so that there is.
  190704. **
  190705. ** If successful, return zero. Otherwise, if an OOM condition is encountered,
  190706. ** set *pRc to SQLITE_NOMEM and return non-zero.
  190707. */
  190708. static int sessionBufferGrow(SessionBuffer *p, size_t nByte, int *pRc){
  190709. if( *pRc==SQLITE_OK && (size_t)(p->nAlloc-p->nBuf)<nByte ){
  190710. u8 *aNew;
  190711. i64 nNew = p->nAlloc ? p->nAlloc : 128;
  190712. do {
  190713. nNew = nNew*2;
  190714. }while( (size_t)(nNew-p->nBuf)<nByte );
  190715. aNew = (u8 *)sqlite3_realloc64(p->aBuf, nNew);
  190716. if( 0==aNew ){
  190717. *pRc = SQLITE_NOMEM;
  190718. }else{
  190719. p->aBuf = aNew;
  190720. p->nAlloc = nNew;
  190721. }
  190722. }
  190723. return (*pRc!=SQLITE_OK);
  190724. }
  190725. /*
  190726. ** Append the value passed as the second argument to the buffer passed
  190727. ** as the first.
  190728. **
  190729. ** This function is a no-op if *pRc is non-zero when it is called.
  190730. ** Otherwise, if an error occurs, *pRc is set to an SQLite error code
  190731. ** before returning.
  190732. */
  190733. static void sessionAppendValue(SessionBuffer *p, sqlite3_value *pVal, int *pRc){
  190734. int rc = *pRc;
  190735. if( rc==SQLITE_OK ){
  190736. sqlite3_int64 nByte = 0;
  190737. rc = sessionSerializeValue(0, pVal, &nByte);
  190738. sessionBufferGrow(p, nByte, &rc);
  190739. if( rc==SQLITE_OK ){
  190740. rc = sessionSerializeValue(&p->aBuf[p->nBuf], pVal, 0);
  190741. p->nBuf += nByte;
  190742. }else{
  190743. *pRc = rc;
  190744. }
  190745. }
  190746. }
  190747. /*
  190748. ** This function is a no-op if *pRc is other than SQLITE_OK when it is
  190749. ** called. Otherwise, append a single byte to the buffer.
  190750. **
  190751. ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
  190752. ** returning.
  190753. */
  190754. static void sessionAppendByte(SessionBuffer *p, u8 v, int *pRc){
  190755. if( 0==sessionBufferGrow(p, 1, pRc) ){
  190756. p->aBuf[p->nBuf++] = v;
  190757. }
  190758. }
  190759. /*
  190760. ** This function is a no-op if *pRc is other than SQLITE_OK when it is
  190761. ** called. Otherwise, append a single varint to the buffer.
  190762. **
  190763. ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
  190764. ** returning.
  190765. */
  190766. static void sessionAppendVarint(SessionBuffer *p, int v, int *pRc){
  190767. if( 0==sessionBufferGrow(p, 9, pRc) ){
  190768. p->nBuf += sessionVarintPut(&p->aBuf[p->nBuf], v);
  190769. }
  190770. }
  190771. /*
  190772. ** This function is a no-op if *pRc is other than SQLITE_OK when it is
  190773. ** called. Otherwise, append a blob of data to the buffer.
  190774. **
  190775. ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
  190776. ** returning.
  190777. */
  190778. static void sessionAppendBlob(
  190779. SessionBuffer *p,
  190780. const u8 *aBlob,
  190781. int nBlob,
  190782. int *pRc
  190783. ){
  190784. if( nBlob>0 && 0==sessionBufferGrow(p, nBlob, pRc) ){
  190785. memcpy(&p->aBuf[p->nBuf], aBlob, nBlob);
  190786. p->nBuf += nBlob;
  190787. }
  190788. }
  190789. /*
  190790. ** This function is a no-op if *pRc is other than SQLITE_OK when it is
  190791. ** called. Otherwise, append a string to the buffer. All bytes in the string
  190792. ** up to (but not including) the nul-terminator are written to the buffer.
  190793. **
  190794. ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
  190795. ** returning.
  190796. */
  190797. static void sessionAppendStr(
  190798. SessionBuffer *p,
  190799. const char *zStr,
  190800. int *pRc
  190801. ){
  190802. int nStr = sqlite3Strlen30(zStr);
  190803. if( 0==sessionBufferGrow(p, nStr, pRc) ){
  190804. memcpy(&p->aBuf[p->nBuf], zStr, nStr);
  190805. p->nBuf += nStr;
  190806. }
  190807. }
  190808. /*
  190809. ** This function is a no-op if *pRc is other than SQLITE_OK when it is
  190810. ** called. Otherwise, append the string representation of integer iVal
  190811. ** to the buffer. No nul-terminator is written.
  190812. **
  190813. ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
  190814. ** returning.
  190815. */
  190816. static void sessionAppendInteger(
  190817. SessionBuffer *p, /* Buffer to append to */
  190818. int iVal, /* Value to write the string rep. of */
  190819. int *pRc /* IN/OUT: Error code */
  190820. ){
  190821. char aBuf[24];
  190822. sqlite3_snprintf(sizeof(aBuf)-1, aBuf, "%d", iVal);
  190823. sessionAppendStr(p, aBuf, pRc);
  190824. }
  190825. /*
  190826. ** This function is a no-op if *pRc is other than SQLITE_OK when it is
  190827. ** called. Otherwise, append the string zStr enclosed in quotes (") and
  190828. ** with any embedded quote characters escaped to the buffer. No
  190829. ** nul-terminator byte is written.
  190830. **
  190831. ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
  190832. ** returning.
  190833. */
  190834. static void sessionAppendIdent(
  190835. SessionBuffer *p, /* Buffer to a append to */
  190836. const char *zStr, /* String to quote, escape and append */
  190837. int *pRc /* IN/OUT: Error code */
  190838. ){
  190839. int nStr = sqlite3Strlen30(zStr)*2 + 2 + 1;
  190840. if( 0==sessionBufferGrow(p, nStr, pRc) ){
  190841. char *zOut = (char *)&p->aBuf[p->nBuf];
  190842. const char *zIn = zStr;
  190843. *zOut++ = '"';
  190844. while( *zIn ){
  190845. if( *zIn=='"' ) *zOut++ = '"';
  190846. *zOut++ = *(zIn++);
  190847. }
  190848. *zOut++ = '"';
  190849. p->nBuf = (int)((u8 *)zOut - p->aBuf);
  190850. }
  190851. }
  190852. /*
  190853. ** This function is a no-op if *pRc is other than SQLITE_OK when it is
  190854. ** called. Otherwse, it appends the serialized version of the value stored
  190855. ** in column iCol of the row that SQL statement pStmt currently points
  190856. ** to to the buffer.
  190857. */
  190858. static void sessionAppendCol(
  190859. SessionBuffer *p, /* Buffer to append to */
  190860. sqlite3_stmt *pStmt, /* Handle pointing to row containing value */
  190861. int iCol, /* Column to read value from */
  190862. int *pRc /* IN/OUT: Error code */
  190863. ){
  190864. if( *pRc==SQLITE_OK ){
  190865. int eType = sqlite3_column_type(pStmt, iCol);
  190866. sessionAppendByte(p, (u8)eType, pRc);
  190867. if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
  190868. sqlite3_int64 i;
  190869. u8 aBuf[8];
  190870. if( eType==SQLITE_INTEGER ){
  190871. i = sqlite3_column_int64(pStmt, iCol);
  190872. }else{
  190873. double r = sqlite3_column_double(pStmt, iCol);
  190874. memcpy(&i, &r, 8);
  190875. }
  190876. sessionPutI64(aBuf, i);
  190877. sessionAppendBlob(p, aBuf, 8, pRc);
  190878. }
  190879. if( eType==SQLITE_BLOB || eType==SQLITE_TEXT ){
  190880. u8 *z;
  190881. int nByte;
  190882. if( eType==SQLITE_BLOB ){
  190883. z = (u8 *)sqlite3_column_blob(pStmt, iCol);
  190884. }else{
  190885. z = (u8 *)sqlite3_column_text(pStmt, iCol);
  190886. }
  190887. nByte = sqlite3_column_bytes(pStmt, iCol);
  190888. if( z || (eType==SQLITE_BLOB && nByte==0) ){
  190889. sessionAppendVarint(p, nByte, pRc);
  190890. sessionAppendBlob(p, z, nByte, pRc);
  190891. }else{
  190892. *pRc = SQLITE_NOMEM;
  190893. }
  190894. }
  190895. }
  190896. }
  190897. /*
  190898. **
  190899. ** This function appends an update change to the buffer (see the comments
  190900. ** under "CHANGESET FORMAT" at the top of the file). An update change
  190901. ** consists of:
  190902. **
  190903. ** 1 byte: SQLITE_UPDATE (0x17)
  190904. ** n bytes: old.* record (see RECORD FORMAT)
  190905. ** m bytes: new.* record (see RECORD FORMAT)
  190906. **
  190907. ** The SessionChange object passed as the third argument contains the
  190908. ** values that were stored in the row when the session began (the old.*
  190909. ** values). The statement handle passed as the second argument points
  190910. ** at the current version of the row (the new.* values).
  190911. **
  190912. ** If all of the old.* values are equal to their corresponding new.* value
  190913. ** (i.e. nothing has changed), then no data at all is appended to the buffer.
  190914. **
  190915. ** Otherwise, the old.* record contains all primary key values and the
  190916. ** original values of any fields that have been modified. The new.* record
  190917. ** contains the new values of only those fields that have been modified.
  190918. */
  190919. static int sessionAppendUpdate(
  190920. SessionBuffer *pBuf, /* Buffer to append to */
  190921. int bPatchset, /* True for "patchset", 0 for "changeset" */
  190922. sqlite3_stmt *pStmt, /* Statement handle pointing at new row */
  190923. SessionChange *p, /* Object containing old values */
  190924. u8 *abPK /* Boolean array - true for PK columns */
  190925. ){
  190926. int rc = SQLITE_OK;
  190927. SessionBuffer buf2 = {0,0,0}; /* Buffer to accumulate new.* record in */
  190928. int bNoop = 1; /* Set to zero if any values are modified */
  190929. int nRewind = pBuf->nBuf; /* Set to zero if any values are modified */
  190930. int i; /* Used to iterate through columns */
  190931. u8 *pCsr = p->aRecord; /* Used to iterate through old.* values */
  190932. sessionAppendByte(pBuf, SQLITE_UPDATE, &rc);
  190933. sessionAppendByte(pBuf, p->bIndirect, &rc);
  190934. for(i=0; i<sqlite3_column_count(pStmt); i++){
  190935. int bChanged = 0;
  190936. int nAdvance;
  190937. int eType = *pCsr;
  190938. switch( eType ){
  190939. case SQLITE_NULL:
  190940. nAdvance = 1;
  190941. if( sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
  190942. bChanged = 1;
  190943. }
  190944. break;
  190945. case SQLITE_FLOAT:
  190946. case SQLITE_INTEGER: {
  190947. nAdvance = 9;
  190948. if( eType==sqlite3_column_type(pStmt, i) ){
  190949. sqlite3_int64 iVal = sessionGetI64(&pCsr[1]);
  190950. if( eType==SQLITE_INTEGER ){
  190951. if( iVal==sqlite3_column_int64(pStmt, i) ) break;
  190952. }else{
  190953. double dVal;
  190954. memcpy(&dVal, &iVal, 8);
  190955. if( dVal==sqlite3_column_double(pStmt, i) ) break;
  190956. }
  190957. }
  190958. bChanged = 1;
  190959. break;
  190960. }
  190961. default: {
  190962. int n;
  190963. int nHdr = 1 + sessionVarintGet(&pCsr[1], &n);
  190964. assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
  190965. nAdvance = nHdr + n;
  190966. if( eType==sqlite3_column_type(pStmt, i)
  190967. && n==sqlite3_column_bytes(pStmt, i)
  190968. && (n==0 || 0==memcmp(&pCsr[nHdr], sqlite3_column_blob(pStmt, i), n))
  190969. ){
  190970. break;
  190971. }
  190972. bChanged = 1;
  190973. }
  190974. }
  190975. /* If at least one field has been modified, this is not a no-op. */
  190976. if( bChanged ) bNoop = 0;
  190977. /* Add a field to the old.* record. This is omitted if this modules is
  190978. ** currently generating a patchset. */
  190979. if( bPatchset==0 ){
  190980. if( bChanged || abPK[i] ){
  190981. sessionAppendBlob(pBuf, pCsr, nAdvance, &rc);
  190982. }else{
  190983. sessionAppendByte(pBuf, 0, &rc);
  190984. }
  190985. }
  190986. /* Add a field to the new.* record. Or the only record if currently
  190987. ** generating a patchset. */
  190988. if( bChanged || (bPatchset && abPK[i]) ){
  190989. sessionAppendCol(&buf2, pStmt, i, &rc);
  190990. }else{
  190991. sessionAppendByte(&buf2, 0, &rc);
  190992. }
  190993. pCsr += nAdvance;
  190994. }
  190995. if( bNoop ){
  190996. pBuf->nBuf = nRewind;
  190997. }else{
  190998. sessionAppendBlob(pBuf, buf2.aBuf, buf2.nBuf, &rc);
  190999. }
  191000. sqlite3_free(buf2.aBuf);
  191001. return rc;
  191002. }
  191003. /*
  191004. ** Append a DELETE change to the buffer passed as the first argument. Use
  191005. ** the changeset format if argument bPatchset is zero, or the patchset
  191006. ** format otherwise.
  191007. */
  191008. static int sessionAppendDelete(
  191009. SessionBuffer *pBuf, /* Buffer to append to */
  191010. int bPatchset, /* True for "patchset", 0 for "changeset" */
  191011. SessionChange *p, /* Object containing old values */
  191012. int nCol, /* Number of columns in table */
  191013. u8 *abPK /* Boolean array - true for PK columns */
  191014. ){
  191015. int rc = SQLITE_OK;
  191016. sessionAppendByte(pBuf, SQLITE_DELETE, &rc);
  191017. sessionAppendByte(pBuf, p->bIndirect, &rc);
  191018. if( bPatchset==0 ){
  191019. sessionAppendBlob(pBuf, p->aRecord, p->nRecord, &rc);
  191020. }else{
  191021. int i;
  191022. u8 *a = p->aRecord;
  191023. for(i=0; i<nCol; i++){
  191024. u8 *pStart = a;
  191025. int eType = *a++;
  191026. switch( eType ){
  191027. case 0:
  191028. case SQLITE_NULL:
  191029. assert( abPK[i]==0 );
  191030. break;
  191031. case SQLITE_FLOAT:
  191032. case SQLITE_INTEGER:
  191033. a += 8;
  191034. break;
  191035. default: {
  191036. int n;
  191037. a += sessionVarintGet(a, &n);
  191038. a += n;
  191039. break;
  191040. }
  191041. }
  191042. if( abPK[i] ){
  191043. sessionAppendBlob(pBuf, pStart, (int)(a-pStart), &rc);
  191044. }
  191045. }
  191046. assert( (a - p->aRecord)==p->nRecord );
  191047. }
  191048. return rc;
  191049. }
  191050. /*
  191051. ** Formulate and prepare a SELECT statement to retrieve a row from table
  191052. ** zTab in database zDb based on its primary key. i.e.
  191053. **
  191054. ** SELECT * FROM zDb.zTab WHERE pk1 = ? AND pk2 = ? AND ...
  191055. */
  191056. static int sessionSelectStmt(
  191057. sqlite3 *db, /* Database handle */
  191058. const char *zDb, /* Database name */
  191059. const char *zTab, /* Table name */
  191060. int nCol, /* Number of columns in table */
  191061. const char **azCol, /* Names of table columns */
  191062. u8 *abPK, /* PRIMARY KEY array */
  191063. sqlite3_stmt **ppStmt /* OUT: Prepared SELECT statement */
  191064. ){
  191065. int rc = SQLITE_OK;
  191066. char *zSql = 0;
  191067. int nSql = -1;
  191068. if( 0==sqlite3_stricmp("sqlite_stat1", zTab) ){
  191069. zSql = sqlite3_mprintf(
  191070. "SELECT tbl, ?2, stat FROM %Q.sqlite_stat1 WHERE tbl IS ?1 AND "
  191071. "idx IS (CASE WHEN ?2=X'' THEN NULL ELSE ?2 END)", zDb
  191072. );
  191073. if( zSql==0 ) rc = SQLITE_NOMEM;
  191074. }else{
  191075. int i;
  191076. const char *zSep = "";
  191077. SessionBuffer buf = {0, 0, 0};
  191078. sessionAppendStr(&buf, "SELECT * FROM ", &rc);
  191079. sessionAppendIdent(&buf, zDb, &rc);
  191080. sessionAppendStr(&buf, ".", &rc);
  191081. sessionAppendIdent(&buf, zTab, &rc);
  191082. sessionAppendStr(&buf, " WHERE ", &rc);
  191083. for(i=0; i<nCol; i++){
  191084. if( abPK[i] ){
  191085. sessionAppendStr(&buf, zSep, &rc);
  191086. sessionAppendIdent(&buf, azCol[i], &rc);
  191087. sessionAppendStr(&buf, " IS ?", &rc);
  191088. sessionAppendInteger(&buf, i+1, &rc);
  191089. zSep = " AND ";
  191090. }
  191091. }
  191092. zSql = (char*)buf.aBuf;
  191093. nSql = buf.nBuf;
  191094. }
  191095. if( rc==SQLITE_OK ){
  191096. rc = sqlite3_prepare_v2(db, zSql, nSql, ppStmt, 0);
  191097. }
  191098. sqlite3_free(zSql);
  191099. return rc;
  191100. }
  191101. /*
  191102. ** Bind the PRIMARY KEY values from the change passed in argument pChange
  191103. ** to the SELECT statement passed as the first argument. The SELECT statement
  191104. ** is as prepared by function sessionSelectStmt().
  191105. **
  191106. ** Return SQLITE_OK if all PK values are successfully bound, or an SQLite
  191107. ** error code (e.g. SQLITE_NOMEM) otherwise.
  191108. */
  191109. static int sessionSelectBind(
  191110. sqlite3_stmt *pSelect, /* SELECT from sessionSelectStmt() */
  191111. int nCol, /* Number of columns in table */
  191112. u8 *abPK, /* PRIMARY KEY array */
  191113. SessionChange *pChange /* Change structure */
  191114. ){
  191115. int i;
  191116. int rc = SQLITE_OK;
  191117. u8 *a = pChange->aRecord;
  191118. for(i=0; i<nCol && rc==SQLITE_OK; i++){
  191119. int eType = *a++;
  191120. switch( eType ){
  191121. case 0:
  191122. case SQLITE_NULL:
  191123. assert( abPK[i]==0 );
  191124. break;
  191125. case SQLITE_INTEGER: {
  191126. if( abPK[i] ){
  191127. i64 iVal = sessionGetI64(a);
  191128. rc = sqlite3_bind_int64(pSelect, i+1, iVal);
  191129. }
  191130. a += 8;
  191131. break;
  191132. }
  191133. case SQLITE_FLOAT: {
  191134. if( abPK[i] ){
  191135. double rVal;
  191136. i64 iVal = sessionGetI64(a);
  191137. memcpy(&rVal, &iVal, 8);
  191138. rc = sqlite3_bind_double(pSelect, i+1, rVal);
  191139. }
  191140. a += 8;
  191141. break;
  191142. }
  191143. case SQLITE_TEXT: {
  191144. int n;
  191145. a += sessionVarintGet(a, &n);
  191146. if( abPK[i] ){
  191147. rc = sqlite3_bind_text(pSelect, i+1, (char *)a, n, SQLITE_TRANSIENT);
  191148. }
  191149. a += n;
  191150. break;
  191151. }
  191152. default: {
  191153. int n;
  191154. assert( eType==SQLITE_BLOB );
  191155. a += sessionVarintGet(a, &n);
  191156. if( abPK[i] ){
  191157. rc = sqlite3_bind_blob(pSelect, i+1, a, n, SQLITE_TRANSIENT);
  191158. }
  191159. a += n;
  191160. break;
  191161. }
  191162. }
  191163. }
  191164. return rc;
  191165. }
  191166. /*
  191167. ** This function is a no-op if *pRc is set to other than SQLITE_OK when it
  191168. ** is called. Otherwise, append a serialized table header (part of the binary
  191169. ** changeset format) to buffer *pBuf. If an error occurs, set *pRc to an
  191170. ** SQLite error code before returning.
  191171. */
  191172. static void sessionAppendTableHdr(
  191173. SessionBuffer *pBuf, /* Append header to this buffer */
  191174. int bPatchset, /* Use the patchset format if true */
  191175. SessionTable *pTab, /* Table object to append header for */
  191176. int *pRc /* IN/OUT: Error code */
  191177. ){
  191178. /* Write a table header */
  191179. sessionAppendByte(pBuf, (bPatchset ? 'P' : 'T'), pRc);
  191180. sessionAppendVarint(pBuf, pTab->nCol, pRc);
  191181. sessionAppendBlob(pBuf, pTab->abPK, pTab->nCol, pRc);
  191182. sessionAppendBlob(pBuf, (u8 *)pTab->zName, (int)strlen(pTab->zName)+1, pRc);
  191183. }
  191184. /*
  191185. ** Generate either a changeset (if argument bPatchset is zero) or a patchset
  191186. ** (if it is non-zero) based on the current contents of the session object
  191187. ** passed as the first argument.
  191188. **
  191189. ** If no error occurs, SQLITE_OK is returned and the new changeset/patchset
  191190. ** stored in output variables *pnChangeset and *ppChangeset. Or, if an error
  191191. ** occurs, an SQLite error code is returned and both output variables set
  191192. ** to 0.
  191193. */
  191194. static int sessionGenerateChangeset(
  191195. sqlite3_session *pSession, /* Session object */
  191196. int bPatchset, /* True for patchset, false for changeset */
  191197. int (*xOutput)(void *pOut, const void *pData, int nData),
  191198. void *pOut, /* First argument for xOutput */
  191199. int *pnChangeset, /* OUT: Size of buffer at *ppChangeset */
  191200. void **ppChangeset /* OUT: Buffer containing changeset */
  191201. ){
  191202. sqlite3 *db = pSession->db; /* Source database handle */
  191203. SessionTable *pTab; /* Used to iterate through attached tables */
  191204. SessionBuffer buf = {0,0,0}; /* Buffer in which to accumlate changeset */
  191205. int rc; /* Return code */
  191206. assert( xOutput==0 || (pnChangeset==0 && ppChangeset==0 ) );
  191207. /* Zero the output variables in case an error occurs. If this session
  191208. ** object is already in the error state (sqlite3_session.rc != SQLITE_OK),
  191209. ** this call will be a no-op. */
  191210. if( xOutput==0 ){
  191211. *pnChangeset = 0;
  191212. *ppChangeset = 0;
  191213. }
  191214. if( pSession->rc ) return pSession->rc;
  191215. rc = sqlite3_exec(pSession->db, "SAVEPOINT changeset", 0, 0, 0);
  191216. if( rc!=SQLITE_OK ) return rc;
  191217. sqlite3_mutex_enter(sqlite3_db_mutex(db));
  191218. for(pTab=pSession->pTable; rc==SQLITE_OK && pTab; pTab=pTab->pNext){
  191219. if( pTab->nEntry ){
  191220. const char *zName = pTab->zName;
  191221. int nCol; /* Number of columns in table */
  191222. u8 *abPK; /* Primary key array */
  191223. const char **azCol = 0; /* Table columns */
  191224. int i; /* Used to iterate through hash buckets */
  191225. sqlite3_stmt *pSel = 0; /* SELECT statement to query table pTab */
  191226. int nRewind = buf.nBuf; /* Initial size of write buffer */
  191227. int nNoop; /* Size of buffer after writing tbl header */
  191228. /* Check the table schema is still Ok. */
  191229. rc = sessionTableInfo(db, pSession->zDb, zName, &nCol, 0, &azCol, &abPK);
  191230. if( !rc && (pTab->nCol!=nCol || memcmp(abPK, pTab->abPK, nCol)) ){
  191231. rc = SQLITE_SCHEMA;
  191232. }
  191233. /* Write a table header */
  191234. sessionAppendTableHdr(&buf, bPatchset, pTab, &rc);
  191235. /* Build and compile a statement to execute: */
  191236. if( rc==SQLITE_OK ){
  191237. rc = sessionSelectStmt(
  191238. db, pSession->zDb, zName, nCol, azCol, abPK, &pSel);
  191239. }
  191240. nNoop = buf.nBuf;
  191241. for(i=0; i<pTab->nChange && rc==SQLITE_OK; i++){
  191242. SessionChange *p; /* Used to iterate through changes */
  191243. for(p=pTab->apChange[i]; rc==SQLITE_OK && p; p=p->pNext){
  191244. rc = sessionSelectBind(pSel, nCol, abPK, p);
  191245. if( rc!=SQLITE_OK ) continue;
  191246. if( sqlite3_step(pSel)==SQLITE_ROW ){
  191247. if( p->op==SQLITE_INSERT ){
  191248. int iCol;
  191249. sessionAppendByte(&buf, SQLITE_INSERT, &rc);
  191250. sessionAppendByte(&buf, p->bIndirect, &rc);
  191251. for(iCol=0; iCol<nCol; iCol++){
  191252. sessionAppendCol(&buf, pSel, iCol, &rc);
  191253. }
  191254. }else{
  191255. rc = sessionAppendUpdate(&buf, bPatchset, pSel, p, abPK);
  191256. }
  191257. }else if( p->op!=SQLITE_INSERT ){
  191258. rc = sessionAppendDelete(&buf, bPatchset, p, nCol, abPK);
  191259. }
  191260. if( rc==SQLITE_OK ){
  191261. rc = sqlite3_reset(pSel);
  191262. }
  191263. /* If the buffer is now larger than sessions_strm_chunk_size, pass
  191264. ** its contents to the xOutput() callback. */
  191265. if( xOutput
  191266. && rc==SQLITE_OK
  191267. && buf.nBuf>nNoop
  191268. && buf.nBuf>sessions_strm_chunk_size
  191269. ){
  191270. rc = xOutput(pOut, (void*)buf.aBuf, buf.nBuf);
  191271. nNoop = -1;
  191272. buf.nBuf = 0;
  191273. }
  191274. }
  191275. }
  191276. sqlite3_finalize(pSel);
  191277. if( buf.nBuf==nNoop ){
  191278. buf.nBuf = nRewind;
  191279. }
  191280. sqlite3_free((char*)azCol); /* cast works around VC++ bug */
  191281. }
  191282. }
  191283. if( rc==SQLITE_OK ){
  191284. if( xOutput==0 ){
  191285. *pnChangeset = buf.nBuf;
  191286. *ppChangeset = buf.aBuf;
  191287. buf.aBuf = 0;
  191288. }else if( buf.nBuf>0 ){
  191289. rc = xOutput(pOut, (void*)buf.aBuf, buf.nBuf);
  191290. }
  191291. }
  191292. sqlite3_free(buf.aBuf);
  191293. sqlite3_exec(db, "RELEASE changeset", 0, 0, 0);
  191294. sqlite3_mutex_leave(sqlite3_db_mutex(db));
  191295. return rc;
  191296. }
  191297. /*
  191298. ** Obtain a changeset object containing all changes recorded by the
  191299. ** session object passed as the first argument.
  191300. **
  191301. ** It is the responsibility of the caller to eventually free the buffer
  191302. ** using sqlite3_free().
  191303. */
  191304. SQLITE_API int sqlite3session_changeset(
  191305. sqlite3_session *pSession, /* Session object */
  191306. int *pnChangeset, /* OUT: Size of buffer at *ppChangeset */
  191307. void **ppChangeset /* OUT: Buffer containing changeset */
  191308. ){
  191309. return sessionGenerateChangeset(pSession, 0, 0, 0, pnChangeset, ppChangeset);
  191310. }
  191311. /*
  191312. ** Streaming version of sqlite3session_changeset().
  191313. */
  191314. SQLITE_API int sqlite3session_changeset_strm(
  191315. sqlite3_session *pSession,
  191316. int (*xOutput)(void *pOut, const void *pData, int nData),
  191317. void *pOut
  191318. ){
  191319. return sessionGenerateChangeset(pSession, 0, xOutput, pOut, 0, 0);
  191320. }
  191321. /*
  191322. ** Streaming version of sqlite3session_patchset().
  191323. */
  191324. SQLITE_API int sqlite3session_patchset_strm(
  191325. sqlite3_session *pSession,
  191326. int (*xOutput)(void *pOut, const void *pData, int nData),
  191327. void *pOut
  191328. ){
  191329. return sessionGenerateChangeset(pSession, 1, xOutput, pOut, 0, 0);
  191330. }
  191331. /*
  191332. ** Obtain a patchset object containing all changes recorded by the
  191333. ** session object passed as the first argument.
  191334. **
  191335. ** It is the responsibility of the caller to eventually free the buffer
  191336. ** using sqlite3_free().
  191337. */
  191338. SQLITE_API int sqlite3session_patchset(
  191339. sqlite3_session *pSession, /* Session object */
  191340. int *pnPatchset, /* OUT: Size of buffer at *ppChangeset */
  191341. void **ppPatchset /* OUT: Buffer containing changeset */
  191342. ){
  191343. return sessionGenerateChangeset(pSession, 1, 0, 0, pnPatchset, ppPatchset);
  191344. }
  191345. /*
  191346. ** Enable or disable the session object passed as the first argument.
  191347. */
  191348. SQLITE_API int sqlite3session_enable(sqlite3_session *pSession, int bEnable){
  191349. int ret;
  191350. sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
  191351. if( bEnable>=0 ){
  191352. pSession->bEnable = bEnable;
  191353. }
  191354. ret = pSession->bEnable;
  191355. sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
  191356. return ret;
  191357. }
  191358. /*
  191359. ** Enable or disable the session object passed as the first argument.
  191360. */
  191361. SQLITE_API int sqlite3session_indirect(sqlite3_session *pSession, int bIndirect){
  191362. int ret;
  191363. sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
  191364. if( bIndirect>=0 ){
  191365. pSession->bIndirect = bIndirect;
  191366. }
  191367. ret = pSession->bIndirect;
  191368. sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
  191369. return ret;
  191370. }
  191371. /*
  191372. ** Return true if there have been no changes to monitored tables recorded
  191373. ** by the session object passed as the only argument.
  191374. */
  191375. SQLITE_API int sqlite3session_isempty(sqlite3_session *pSession){
  191376. int ret = 0;
  191377. SessionTable *pTab;
  191378. sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
  191379. for(pTab=pSession->pTable; pTab && ret==0; pTab=pTab->pNext){
  191380. ret = (pTab->nEntry>0);
  191381. }
  191382. sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
  191383. return (ret==0);
  191384. }
  191385. /*
  191386. ** Do the work for either sqlite3changeset_start() or start_strm().
  191387. */
  191388. static int sessionChangesetStart(
  191389. sqlite3_changeset_iter **pp, /* OUT: Changeset iterator handle */
  191390. int (*xInput)(void *pIn, void *pData, int *pnData),
  191391. void *pIn,
  191392. int nChangeset, /* Size of buffer pChangeset in bytes */
  191393. void *pChangeset, /* Pointer to buffer containing changeset */
  191394. int bInvert /* True to invert changeset */
  191395. ){
  191396. sqlite3_changeset_iter *pRet; /* Iterator to return */
  191397. int nByte; /* Number of bytes to allocate for iterator */
  191398. assert( xInput==0 || (pChangeset==0 && nChangeset==0) );
  191399. /* Zero the output variable in case an error occurs. */
  191400. *pp = 0;
  191401. /* Allocate and initialize the iterator structure. */
  191402. nByte = sizeof(sqlite3_changeset_iter);
  191403. pRet = (sqlite3_changeset_iter *)sqlite3_malloc(nByte);
  191404. if( !pRet ) return SQLITE_NOMEM;
  191405. memset(pRet, 0, sizeof(sqlite3_changeset_iter));
  191406. pRet->in.aData = (u8 *)pChangeset;
  191407. pRet->in.nData = nChangeset;
  191408. pRet->in.xInput = xInput;
  191409. pRet->in.pIn = pIn;
  191410. pRet->in.bEof = (xInput ? 0 : 1);
  191411. pRet->bInvert = bInvert;
  191412. /* Populate the output variable and return success. */
  191413. *pp = pRet;
  191414. return SQLITE_OK;
  191415. }
  191416. /*
  191417. ** Create an iterator used to iterate through the contents of a changeset.
  191418. */
  191419. SQLITE_API int sqlite3changeset_start(
  191420. sqlite3_changeset_iter **pp, /* OUT: Changeset iterator handle */
  191421. int nChangeset, /* Size of buffer pChangeset in bytes */
  191422. void *pChangeset /* Pointer to buffer containing changeset */
  191423. ){
  191424. return sessionChangesetStart(pp, 0, 0, nChangeset, pChangeset, 0);
  191425. }
  191426. SQLITE_API int sqlite3changeset_start_v2(
  191427. sqlite3_changeset_iter **pp, /* OUT: Changeset iterator handle */
  191428. int nChangeset, /* Size of buffer pChangeset in bytes */
  191429. void *pChangeset, /* Pointer to buffer containing changeset */
  191430. int flags
  191431. ){
  191432. int bInvert = !!(flags & SQLITE_CHANGESETSTART_INVERT);
  191433. return sessionChangesetStart(pp, 0, 0, nChangeset, pChangeset, bInvert);
  191434. }
  191435. /*
  191436. ** Streaming version of sqlite3changeset_start().
  191437. */
  191438. SQLITE_API int sqlite3changeset_start_strm(
  191439. sqlite3_changeset_iter **pp, /* OUT: Changeset iterator handle */
  191440. int (*xInput)(void *pIn, void *pData, int *pnData),
  191441. void *pIn
  191442. ){
  191443. return sessionChangesetStart(pp, xInput, pIn, 0, 0, 0);
  191444. }
  191445. SQLITE_API int sqlite3changeset_start_v2_strm(
  191446. sqlite3_changeset_iter **pp, /* OUT: Changeset iterator handle */
  191447. int (*xInput)(void *pIn, void *pData, int *pnData),
  191448. void *pIn,
  191449. int flags
  191450. ){
  191451. int bInvert = !!(flags & SQLITE_CHANGESETSTART_INVERT);
  191452. return sessionChangesetStart(pp, xInput, pIn, 0, 0, bInvert);
  191453. }
  191454. /*
  191455. ** If the SessionInput object passed as the only argument is a streaming
  191456. ** object and the buffer is full, discard some data to free up space.
  191457. */
  191458. static void sessionDiscardData(SessionInput *pIn){
  191459. if( pIn->xInput && pIn->iNext>=sessions_strm_chunk_size ){
  191460. int nMove = pIn->buf.nBuf - pIn->iNext;
  191461. assert( nMove>=0 );
  191462. if( nMove>0 ){
  191463. memmove(pIn->buf.aBuf, &pIn->buf.aBuf[pIn->iNext], nMove);
  191464. }
  191465. pIn->buf.nBuf -= pIn->iNext;
  191466. pIn->iNext = 0;
  191467. pIn->nData = pIn->buf.nBuf;
  191468. }
  191469. }
  191470. /*
  191471. ** Ensure that there are at least nByte bytes available in the buffer. Or,
  191472. ** if there are not nByte bytes remaining in the input, that all available
  191473. ** data is in the buffer.
  191474. **
  191475. ** Return an SQLite error code if an error occurs, or SQLITE_OK otherwise.
  191476. */
  191477. static int sessionInputBuffer(SessionInput *pIn, int nByte){
  191478. int rc = SQLITE_OK;
  191479. if( pIn->xInput ){
  191480. while( !pIn->bEof && (pIn->iNext+nByte)>=pIn->nData && rc==SQLITE_OK ){
  191481. int nNew = sessions_strm_chunk_size;
  191482. if( pIn->bNoDiscard==0 ) sessionDiscardData(pIn);
  191483. if( SQLITE_OK==sessionBufferGrow(&pIn->buf, nNew, &rc) ){
  191484. rc = pIn->xInput(pIn->pIn, &pIn->buf.aBuf[pIn->buf.nBuf], &nNew);
  191485. if( nNew==0 ){
  191486. pIn->bEof = 1;
  191487. }else{
  191488. pIn->buf.nBuf += nNew;
  191489. }
  191490. }
  191491. pIn->aData = pIn->buf.aBuf;
  191492. pIn->nData = pIn->buf.nBuf;
  191493. }
  191494. }
  191495. return rc;
  191496. }
  191497. /*
  191498. ** When this function is called, *ppRec points to the start of a record
  191499. ** that contains nCol values. This function advances the pointer *ppRec
  191500. ** until it points to the byte immediately following that record.
  191501. */
  191502. static void sessionSkipRecord(
  191503. u8 **ppRec, /* IN/OUT: Record pointer */
  191504. int nCol /* Number of values in record */
  191505. ){
  191506. u8 *aRec = *ppRec;
  191507. int i;
  191508. for(i=0; i<nCol; i++){
  191509. int eType = *aRec++;
  191510. if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
  191511. int nByte;
  191512. aRec += sessionVarintGet((u8*)aRec, &nByte);
  191513. aRec += nByte;
  191514. }else if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
  191515. aRec += 8;
  191516. }
  191517. }
  191518. *ppRec = aRec;
  191519. }
  191520. /*
  191521. ** This function sets the value of the sqlite3_value object passed as the
  191522. ** first argument to a copy of the string or blob held in the aData[]
  191523. ** buffer. SQLITE_OK is returned if successful, or SQLITE_NOMEM if an OOM
  191524. ** error occurs.
  191525. */
  191526. static int sessionValueSetStr(
  191527. sqlite3_value *pVal, /* Set the value of this object */
  191528. u8 *aData, /* Buffer containing string or blob data */
  191529. int nData, /* Size of buffer aData[] in bytes */
  191530. u8 enc /* String encoding (0 for blobs) */
  191531. ){
  191532. /* In theory this code could just pass SQLITE_TRANSIENT as the final
  191533. ** argument to sqlite3ValueSetStr() and have the copy created
  191534. ** automatically. But doing so makes it difficult to detect any OOM
  191535. ** error. Hence the code to create the copy externally. */
  191536. u8 *aCopy = sqlite3_malloc64((sqlite3_int64)nData+1);
  191537. if( aCopy==0 ) return SQLITE_NOMEM;
  191538. memcpy(aCopy, aData, nData);
  191539. sqlite3ValueSetStr(pVal, nData, (char*)aCopy, enc, sqlite3_free);
  191540. return SQLITE_OK;
  191541. }
  191542. /*
  191543. ** Deserialize a single record from a buffer in memory. See "RECORD FORMAT"
  191544. ** for details.
  191545. **
  191546. ** When this function is called, *paChange points to the start of the record
  191547. ** to deserialize. Assuming no error occurs, *paChange is set to point to
  191548. ** one byte after the end of the same record before this function returns.
  191549. ** If the argument abPK is NULL, then the record contains nCol values. Or,
  191550. ** if abPK is other than NULL, then the record contains only the PK fields
  191551. ** (in other words, it is a patchset DELETE record).
  191552. **
  191553. ** If successful, each element of the apOut[] array (allocated by the caller)
  191554. ** is set to point to an sqlite3_value object containing the value read
  191555. ** from the corresponding position in the record. If that value is not
  191556. ** included in the record (i.e. because the record is part of an UPDATE change
  191557. ** and the field was not modified), the corresponding element of apOut[] is
  191558. ** set to NULL.
  191559. **
  191560. ** It is the responsibility of the caller to free all sqlite_value structures
  191561. ** using sqlite3_free().
  191562. **
  191563. ** If an error occurs, an SQLite error code (e.g. SQLITE_NOMEM) is returned.
  191564. ** The apOut[] array may have been partially populated in this case.
  191565. */
  191566. static int sessionReadRecord(
  191567. SessionInput *pIn, /* Input data */
  191568. int nCol, /* Number of values in record */
  191569. u8 *abPK, /* Array of primary key flags, or NULL */
  191570. sqlite3_value **apOut /* Write values to this array */
  191571. ){
  191572. int i; /* Used to iterate through columns */
  191573. int rc = SQLITE_OK;
  191574. for(i=0; i<nCol && rc==SQLITE_OK; i++){
  191575. int eType = 0; /* Type of value (SQLITE_NULL, TEXT etc.) */
  191576. if( abPK && abPK[i]==0 ) continue;
  191577. rc = sessionInputBuffer(pIn, 9);
  191578. if( rc==SQLITE_OK ){
  191579. if( pIn->iNext>=pIn->nData ){
  191580. rc = SQLITE_CORRUPT_BKPT;
  191581. }else{
  191582. eType = pIn->aData[pIn->iNext++];
  191583. assert( apOut[i]==0 );
  191584. if( eType ){
  191585. apOut[i] = sqlite3ValueNew(0);
  191586. if( !apOut[i] ) rc = SQLITE_NOMEM;
  191587. }
  191588. }
  191589. }
  191590. if( rc==SQLITE_OK ){
  191591. u8 *aVal = &pIn->aData[pIn->iNext];
  191592. if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
  191593. int nByte;
  191594. pIn->iNext += sessionVarintGet(aVal, &nByte);
  191595. rc = sessionInputBuffer(pIn, nByte);
  191596. if( rc==SQLITE_OK ){
  191597. if( nByte<0 || nByte>pIn->nData-pIn->iNext ){
  191598. rc = SQLITE_CORRUPT_BKPT;
  191599. }else{
  191600. u8 enc = (eType==SQLITE_TEXT ? SQLITE_UTF8 : 0);
  191601. rc = sessionValueSetStr(apOut[i],&pIn->aData[pIn->iNext],nByte,enc);
  191602. pIn->iNext += nByte;
  191603. }
  191604. }
  191605. }
  191606. if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
  191607. sqlite3_int64 v = sessionGetI64(aVal);
  191608. if( eType==SQLITE_INTEGER ){
  191609. sqlite3VdbeMemSetInt64(apOut[i], v);
  191610. }else{
  191611. double d;
  191612. memcpy(&d, &v, 8);
  191613. sqlite3VdbeMemSetDouble(apOut[i], d);
  191614. }
  191615. pIn->iNext += 8;
  191616. }
  191617. }
  191618. }
  191619. return rc;
  191620. }
  191621. /*
  191622. ** The input pointer currently points to the second byte of a table-header.
  191623. ** Specifically, to the following:
  191624. **
  191625. ** + number of columns in table (varint)
  191626. ** + array of PK flags (1 byte per column),
  191627. ** + table name (nul terminated).
  191628. **
  191629. ** This function ensures that all of the above is present in the input
  191630. ** buffer (i.e. that it can be accessed without any calls to xInput()).
  191631. ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
  191632. ** The input pointer is not moved.
  191633. */
  191634. static int sessionChangesetBufferTblhdr(SessionInput *pIn, int *pnByte){
  191635. int rc = SQLITE_OK;
  191636. int nCol = 0;
  191637. int nRead = 0;
  191638. rc = sessionInputBuffer(pIn, 9);
  191639. if( rc==SQLITE_OK ){
  191640. nRead += sessionVarintGet(&pIn->aData[pIn->iNext + nRead], &nCol);
  191641. /* The hard upper limit for the number of columns in an SQLite
  191642. ** database table is, according to sqliteLimit.h, 32676. So
  191643. ** consider any table-header that purports to have more than 65536
  191644. ** columns to be corrupt. This is convenient because otherwise,
  191645. ** if the (nCol>65536) condition below were omitted, a sufficiently
  191646. ** large value for nCol may cause nRead to wrap around and become
  191647. ** negative. Leading to a crash. */
  191648. if( nCol<0 || nCol>65536 ){
  191649. rc = SQLITE_CORRUPT_BKPT;
  191650. }else{
  191651. rc = sessionInputBuffer(pIn, nRead+nCol+100);
  191652. nRead += nCol;
  191653. }
  191654. }
  191655. while( rc==SQLITE_OK ){
  191656. while( (pIn->iNext + nRead)<pIn->nData && pIn->aData[pIn->iNext + nRead] ){
  191657. nRead++;
  191658. }
  191659. if( (pIn->iNext + nRead)<pIn->nData ) break;
  191660. rc = sessionInputBuffer(pIn, nRead + 100);
  191661. }
  191662. *pnByte = nRead+1;
  191663. return rc;
  191664. }
  191665. /*
  191666. ** The input pointer currently points to the first byte of the first field
  191667. ** of a record consisting of nCol columns. This function ensures the entire
  191668. ** record is buffered. It does not move the input pointer.
  191669. **
  191670. ** If successful, SQLITE_OK is returned and *pnByte is set to the size of
  191671. ** the record in bytes. Otherwise, an SQLite error code is returned. The
  191672. ** final value of *pnByte is undefined in this case.
  191673. */
  191674. static int sessionChangesetBufferRecord(
  191675. SessionInput *pIn, /* Input data */
  191676. int nCol, /* Number of columns in record */
  191677. int *pnByte /* OUT: Size of record in bytes */
  191678. ){
  191679. int rc = SQLITE_OK;
  191680. int nByte = 0;
  191681. int i;
  191682. for(i=0; rc==SQLITE_OK && i<nCol; i++){
  191683. int eType;
  191684. rc = sessionInputBuffer(pIn, nByte + 10);
  191685. if( rc==SQLITE_OK ){
  191686. eType = pIn->aData[pIn->iNext + nByte++];
  191687. if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
  191688. int n;
  191689. nByte += sessionVarintGet(&pIn->aData[pIn->iNext+nByte], &n);
  191690. nByte += n;
  191691. rc = sessionInputBuffer(pIn, nByte);
  191692. }else if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
  191693. nByte += 8;
  191694. }
  191695. }
  191696. }
  191697. *pnByte = nByte;
  191698. return rc;
  191699. }
  191700. /*
  191701. ** The input pointer currently points to the second byte of a table-header.
  191702. ** Specifically, to the following:
  191703. **
  191704. ** + number of columns in table (varint)
  191705. ** + array of PK flags (1 byte per column),
  191706. ** + table name (nul terminated).
  191707. **
  191708. ** This function decodes the table-header and populates the p->nCol,
  191709. ** p->zTab and p->abPK[] variables accordingly. The p->apValue[] array is
  191710. ** also allocated or resized according to the new value of p->nCol. The
  191711. ** input pointer is left pointing to the byte following the table header.
  191712. **
  191713. ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code
  191714. ** is returned and the final values of the various fields enumerated above
  191715. ** are undefined.
  191716. */
  191717. static int sessionChangesetReadTblhdr(sqlite3_changeset_iter *p){
  191718. int rc;
  191719. int nCopy;
  191720. assert( p->rc==SQLITE_OK );
  191721. rc = sessionChangesetBufferTblhdr(&p->in, &nCopy);
  191722. if( rc==SQLITE_OK ){
  191723. int nByte;
  191724. int nVarint;
  191725. nVarint = sessionVarintGet(&p->in.aData[p->in.iNext], &p->nCol);
  191726. if( p->nCol>0 ){
  191727. nCopy -= nVarint;
  191728. p->in.iNext += nVarint;
  191729. nByte = p->nCol * sizeof(sqlite3_value*) * 2 + nCopy;
  191730. p->tblhdr.nBuf = 0;
  191731. sessionBufferGrow(&p->tblhdr, nByte, &rc);
  191732. }else{
  191733. rc = SQLITE_CORRUPT_BKPT;
  191734. }
  191735. }
  191736. if( rc==SQLITE_OK ){
  191737. size_t iPK = sizeof(sqlite3_value*)*p->nCol*2;
  191738. memset(p->tblhdr.aBuf, 0, iPK);
  191739. memcpy(&p->tblhdr.aBuf[iPK], &p->in.aData[p->in.iNext], nCopy);
  191740. p->in.iNext += nCopy;
  191741. }
  191742. p->apValue = (sqlite3_value**)p->tblhdr.aBuf;
  191743. p->abPK = (u8*)&p->apValue[p->nCol*2];
  191744. p->zTab = (char*)&p->abPK[p->nCol];
  191745. return (p->rc = rc);
  191746. }
  191747. /*
  191748. ** Advance the changeset iterator to the next change.
  191749. **
  191750. ** If both paRec and pnRec are NULL, then this function works like the public
  191751. ** API sqlite3changeset_next(). If SQLITE_ROW is returned, then the
  191752. ** sqlite3changeset_new() and old() APIs may be used to query for values.
  191753. **
  191754. ** Otherwise, if paRec and pnRec are not NULL, then a pointer to the change
  191755. ** record is written to *paRec before returning and the number of bytes in
  191756. ** the record to *pnRec.
  191757. **
  191758. ** Either way, this function returns SQLITE_ROW if the iterator is
  191759. ** successfully advanced to the next change in the changeset, an SQLite
  191760. ** error code if an error occurs, or SQLITE_DONE if there are no further
  191761. ** changes in the changeset.
  191762. */
  191763. static int sessionChangesetNext(
  191764. sqlite3_changeset_iter *p, /* Changeset iterator */
  191765. u8 **paRec, /* If non-NULL, store record pointer here */
  191766. int *pnRec, /* If non-NULL, store size of record here */
  191767. int *pbNew /* If non-NULL, true if new table */
  191768. ){
  191769. int i;
  191770. u8 op;
  191771. assert( (paRec==0 && pnRec==0) || (paRec && pnRec) );
  191772. /* If the iterator is in the error-state, return immediately. */
  191773. if( p->rc!=SQLITE_OK ) return p->rc;
  191774. /* Free the current contents of p->apValue[], if any. */
  191775. if( p->apValue ){
  191776. for(i=0; i<p->nCol*2; i++){
  191777. sqlite3ValueFree(p->apValue[i]);
  191778. }
  191779. memset(p->apValue, 0, sizeof(sqlite3_value*)*p->nCol*2);
  191780. }
  191781. /* Make sure the buffer contains at least 10 bytes of input data, or all
  191782. ** remaining data if there are less than 10 bytes available. This is
  191783. ** sufficient either for the 'T' or 'P' byte and the varint that follows
  191784. ** it, or for the two single byte values otherwise. */
  191785. p->rc = sessionInputBuffer(&p->in, 2);
  191786. if( p->rc!=SQLITE_OK ) return p->rc;
  191787. /* If the iterator is already at the end of the changeset, return DONE. */
  191788. if( p->in.iNext>=p->in.nData ){
  191789. return SQLITE_DONE;
  191790. }
  191791. sessionDiscardData(&p->in);
  191792. p->in.iCurrent = p->in.iNext;
  191793. op = p->in.aData[p->in.iNext++];
  191794. while( op=='T' || op=='P' ){
  191795. if( pbNew ) *pbNew = 1;
  191796. p->bPatchset = (op=='P');
  191797. if( sessionChangesetReadTblhdr(p) ) return p->rc;
  191798. if( (p->rc = sessionInputBuffer(&p->in, 2)) ) return p->rc;
  191799. p->in.iCurrent = p->in.iNext;
  191800. if( p->in.iNext>=p->in.nData ) return SQLITE_DONE;
  191801. op = p->in.aData[p->in.iNext++];
  191802. }
  191803. if( p->zTab==0 || (p->bPatchset && p->bInvert) ){
  191804. /* The first record in the changeset is not a table header. Must be a
  191805. ** corrupt changeset. */
  191806. assert( p->in.iNext==1 || p->zTab );
  191807. return (p->rc = SQLITE_CORRUPT_BKPT);
  191808. }
  191809. p->op = op;
  191810. p->bIndirect = p->in.aData[p->in.iNext++];
  191811. if( p->op!=SQLITE_UPDATE && p->op!=SQLITE_DELETE && p->op!=SQLITE_INSERT ){
  191812. return (p->rc = SQLITE_CORRUPT_BKPT);
  191813. }
  191814. if( paRec ){
  191815. int nVal; /* Number of values to buffer */
  191816. if( p->bPatchset==0 && op==SQLITE_UPDATE ){
  191817. nVal = p->nCol * 2;
  191818. }else if( p->bPatchset && op==SQLITE_DELETE ){
  191819. nVal = 0;
  191820. for(i=0; i<p->nCol; i++) if( p->abPK[i] ) nVal++;
  191821. }else{
  191822. nVal = p->nCol;
  191823. }
  191824. p->rc = sessionChangesetBufferRecord(&p->in, nVal, pnRec);
  191825. if( p->rc!=SQLITE_OK ) return p->rc;
  191826. *paRec = &p->in.aData[p->in.iNext];
  191827. p->in.iNext += *pnRec;
  191828. }else{
  191829. sqlite3_value **apOld = (p->bInvert ? &p->apValue[p->nCol] : p->apValue);
  191830. sqlite3_value **apNew = (p->bInvert ? p->apValue : &p->apValue[p->nCol]);
  191831. /* If this is an UPDATE or DELETE, read the old.* record. */
  191832. if( p->op!=SQLITE_INSERT && (p->bPatchset==0 || p->op==SQLITE_DELETE) ){
  191833. u8 *abPK = p->bPatchset ? p->abPK : 0;
  191834. p->rc = sessionReadRecord(&p->in, p->nCol, abPK, apOld);
  191835. if( p->rc!=SQLITE_OK ) return p->rc;
  191836. }
  191837. /* If this is an INSERT or UPDATE, read the new.* record. */
  191838. if( p->op!=SQLITE_DELETE ){
  191839. p->rc = sessionReadRecord(&p->in, p->nCol, 0, apNew);
  191840. if( p->rc!=SQLITE_OK ) return p->rc;
  191841. }
  191842. if( (p->bPatchset || p->bInvert) && p->op==SQLITE_UPDATE ){
  191843. /* If this is an UPDATE that is part of a patchset, then all PK and
  191844. ** modified fields are present in the new.* record. The old.* record
  191845. ** is currently completely empty. This block shifts the PK fields from
  191846. ** new.* to old.*, to accommodate the code that reads these arrays. */
  191847. for(i=0; i<p->nCol; i++){
  191848. assert( p->bPatchset==0 || p->apValue[i]==0 );
  191849. if( p->abPK[i] ){
  191850. assert( p->apValue[i]==0 );
  191851. p->apValue[i] = p->apValue[i+p->nCol];
  191852. if( p->apValue[i]==0 ) return (p->rc = SQLITE_CORRUPT_BKPT);
  191853. p->apValue[i+p->nCol] = 0;
  191854. }
  191855. }
  191856. }else if( p->bInvert ){
  191857. if( p->op==SQLITE_INSERT ) p->op = SQLITE_DELETE;
  191858. else if( p->op==SQLITE_DELETE ) p->op = SQLITE_INSERT;
  191859. }
  191860. }
  191861. return SQLITE_ROW;
  191862. }
  191863. /*
  191864. ** Advance an iterator created by sqlite3changeset_start() to the next
  191865. ** change in the changeset. This function may return SQLITE_ROW, SQLITE_DONE
  191866. ** or SQLITE_CORRUPT.
  191867. **
  191868. ** This function may not be called on iterators passed to a conflict handler
  191869. ** callback by changeset_apply().
  191870. */
  191871. SQLITE_API int sqlite3changeset_next(sqlite3_changeset_iter *p){
  191872. return sessionChangesetNext(p, 0, 0, 0);
  191873. }
  191874. /*
  191875. ** The following function extracts information on the current change
  191876. ** from a changeset iterator. It may only be called after changeset_next()
  191877. ** has returned SQLITE_ROW.
  191878. */
  191879. SQLITE_API int sqlite3changeset_op(
  191880. sqlite3_changeset_iter *pIter, /* Iterator handle */
  191881. const char **pzTab, /* OUT: Pointer to table name */
  191882. int *pnCol, /* OUT: Number of columns in table */
  191883. int *pOp, /* OUT: SQLITE_INSERT, DELETE or UPDATE */
  191884. int *pbIndirect /* OUT: True if change is indirect */
  191885. ){
  191886. *pOp = pIter->op;
  191887. *pnCol = pIter->nCol;
  191888. *pzTab = pIter->zTab;
  191889. if( pbIndirect ) *pbIndirect = pIter->bIndirect;
  191890. return SQLITE_OK;
  191891. }
  191892. /*
  191893. ** Return information regarding the PRIMARY KEY and number of columns in
  191894. ** the database table affected by the change that pIter currently points
  191895. ** to. This function may only be called after changeset_next() returns
  191896. ** SQLITE_ROW.
  191897. */
  191898. SQLITE_API int sqlite3changeset_pk(
  191899. sqlite3_changeset_iter *pIter, /* Iterator object */
  191900. unsigned char **pabPK, /* OUT: Array of boolean - true for PK cols */
  191901. int *pnCol /* OUT: Number of entries in output array */
  191902. ){
  191903. *pabPK = pIter->abPK;
  191904. if( pnCol ) *pnCol = pIter->nCol;
  191905. return SQLITE_OK;
  191906. }
  191907. /*
  191908. ** This function may only be called while the iterator is pointing to an
  191909. ** SQLITE_UPDATE or SQLITE_DELETE change (see sqlite3changeset_op()).
  191910. ** Otherwise, SQLITE_MISUSE is returned.
  191911. **
  191912. ** It sets *ppValue to point to an sqlite3_value structure containing the
  191913. ** iVal'th value in the old.* record. Or, if that particular value is not
  191914. ** included in the record (because the change is an UPDATE and the field
  191915. ** was not modified and is not a PK column), set *ppValue to NULL.
  191916. **
  191917. ** If value iVal is out-of-range, SQLITE_RANGE is returned and *ppValue is
  191918. ** not modified. Otherwise, SQLITE_OK.
  191919. */
  191920. SQLITE_API int sqlite3changeset_old(
  191921. sqlite3_changeset_iter *pIter, /* Changeset iterator */
  191922. int iVal, /* Index of old.* value to retrieve */
  191923. sqlite3_value **ppValue /* OUT: Old value (or NULL pointer) */
  191924. ){
  191925. if( pIter->op!=SQLITE_UPDATE && pIter->op!=SQLITE_DELETE ){
  191926. return SQLITE_MISUSE;
  191927. }
  191928. if( iVal<0 || iVal>=pIter->nCol ){
  191929. return SQLITE_RANGE;
  191930. }
  191931. *ppValue = pIter->apValue[iVal];
  191932. return SQLITE_OK;
  191933. }
  191934. /*
  191935. ** This function may only be called while the iterator is pointing to an
  191936. ** SQLITE_UPDATE or SQLITE_INSERT change (see sqlite3changeset_op()).
  191937. ** Otherwise, SQLITE_MISUSE is returned.
  191938. **
  191939. ** It sets *ppValue to point to an sqlite3_value structure containing the
  191940. ** iVal'th value in the new.* record. Or, if that particular value is not
  191941. ** included in the record (because the change is an UPDATE and the field
  191942. ** was not modified), set *ppValue to NULL.
  191943. **
  191944. ** If value iVal is out-of-range, SQLITE_RANGE is returned and *ppValue is
  191945. ** not modified. Otherwise, SQLITE_OK.
  191946. */
  191947. SQLITE_API int sqlite3changeset_new(
  191948. sqlite3_changeset_iter *pIter, /* Changeset iterator */
  191949. int iVal, /* Index of new.* value to retrieve */
  191950. sqlite3_value **ppValue /* OUT: New value (or NULL pointer) */
  191951. ){
  191952. if( pIter->op!=SQLITE_UPDATE && pIter->op!=SQLITE_INSERT ){
  191953. return SQLITE_MISUSE;
  191954. }
  191955. if( iVal<0 || iVal>=pIter->nCol ){
  191956. return SQLITE_RANGE;
  191957. }
  191958. *ppValue = pIter->apValue[pIter->nCol+iVal];
  191959. return SQLITE_OK;
  191960. }
  191961. /*
  191962. ** The following two macros are used internally. They are similar to the
  191963. ** sqlite3changeset_new() and sqlite3changeset_old() functions, except that
  191964. ** they omit all error checking and return a pointer to the requested value.
  191965. */
  191966. #define sessionChangesetNew(pIter, iVal) (pIter)->apValue[(pIter)->nCol+(iVal)]
  191967. #define sessionChangesetOld(pIter, iVal) (pIter)->apValue[(iVal)]
  191968. /*
  191969. ** This function may only be called with a changeset iterator that has been
  191970. ** passed to an SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT
  191971. ** conflict-handler function. Otherwise, SQLITE_MISUSE is returned.
  191972. **
  191973. ** If successful, *ppValue is set to point to an sqlite3_value structure
  191974. ** containing the iVal'th value of the conflicting record.
  191975. **
  191976. ** If value iVal is out-of-range or some other error occurs, an SQLite error
  191977. ** code is returned. Otherwise, SQLITE_OK.
  191978. */
  191979. SQLITE_API int sqlite3changeset_conflict(
  191980. sqlite3_changeset_iter *pIter, /* Changeset iterator */
  191981. int iVal, /* Index of conflict record value to fetch */
  191982. sqlite3_value **ppValue /* OUT: Value from conflicting row */
  191983. ){
  191984. if( !pIter->pConflict ){
  191985. return SQLITE_MISUSE;
  191986. }
  191987. if( iVal<0 || iVal>=pIter->nCol ){
  191988. return SQLITE_RANGE;
  191989. }
  191990. *ppValue = sqlite3_column_value(pIter->pConflict, iVal);
  191991. return SQLITE_OK;
  191992. }
  191993. /*
  191994. ** This function may only be called with an iterator passed to an
  191995. ** SQLITE_CHANGESET_FOREIGN_KEY conflict handler callback. In this case
  191996. ** it sets the output variable to the total number of known foreign key
  191997. ** violations in the destination database and returns SQLITE_OK.
  191998. **
  191999. ** In all other cases this function returns SQLITE_MISUSE.
  192000. */
  192001. SQLITE_API int sqlite3changeset_fk_conflicts(
  192002. sqlite3_changeset_iter *pIter, /* Changeset iterator */
  192003. int *pnOut /* OUT: Number of FK violations */
  192004. ){
  192005. if( pIter->pConflict || pIter->apValue ){
  192006. return SQLITE_MISUSE;
  192007. }
  192008. *pnOut = pIter->nCol;
  192009. return SQLITE_OK;
  192010. }
  192011. /*
  192012. ** Finalize an iterator allocated with sqlite3changeset_start().
  192013. **
  192014. ** This function may not be called on iterators passed to a conflict handler
  192015. ** callback by changeset_apply().
  192016. */
  192017. SQLITE_API int sqlite3changeset_finalize(sqlite3_changeset_iter *p){
  192018. int rc = SQLITE_OK;
  192019. if( p ){
  192020. int i; /* Used to iterate through p->apValue[] */
  192021. rc = p->rc;
  192022. if( p->apValue ){
  192023. for(i=0; i<p->nCol*2; i++) sqlite3ValueFree(p->apValue[i]);
  192024. }
  192025. sqlite3_free(p->tblhdr.aBuf);
  192026. sqlite3_free(p->in.buf.aBuf);
  192027. sqlite3_free(p);
  192028. }
  192029. return rc;
  192030. }
  192031. static int sessionChangesetInvert(
  192032. SessionInput *pInput, /* Input changeset */
  192033. int (*xOutput)(void *pOut, const void *pData, int nData),
  192034. void *pOut,
  192035. int *pnInverted, /* OUT: Number of bytes in output changeset */
  192036. void **ppInverted /* OUT: Inverse of pChangeset */
  192037. ){
  192038. int rc = SQLITE_OK; /* Return value */
  192039. SessionBuffer sOut; /* Output buffer */
  192040. int nCol = 0; /* Number of cols in current table */
  192041. u8 *abPK = 0; /* PK array for current table */
  192042. sqlite3_value **apVal = 0; /* Space for values for UPDATE inversion */
  192043. SessionBuffer sPK = {0, 0, 0}; /* PK array for current table */
  192044. /* Initialize the output buffer */
  192045. memset(&sOut, 0, sizeof(SessionBuffer));
  192046. /* Zero the output variables in case an error occurs. */
  192047. if( ppInverted ){
  192048. *ppInverted = 0;
  192049. *pnInverted = 0;
  192050. }
  192051. while( 1 ){
  192052. u8 eType;
  192053. /* Test for EOF. */
  192054. if( (rc = sessionInputBuffer(pInput, 2)) ) goto finished_invert;
  192055. if( pInput->iNext>=pInput->nData ) break;
  192056. eType = pInput->aData[pInput->iNext];
  192057. switch( eType ){
  192058. case 'T': {
  192059. /* A 'table' record consists of:
  192060. **
  192061. ** * A constant 'T' character,
  192062. ** * Number of columns in said table (a varint),
  192063. ** * An array of nCol bytes (sPK),
  192064. ** * A nul-terminated table name.
  192065. */
  192066. int nByte;
  192067. int nVar;
  192068. pInput->iNext++;
  192069. if( (rc = sessionChangesetBufferTblhdr(pInput, &nByte)) ){
  192070. goto finished_invert;
  192071. }
  192072. nVar = sessionVarintGet(&pInput->aData[pInput->iNext], &nCol);
  192073. sPK.nBuf = 0;
  192074. sessionAppendBlob(&sPK, &pInput->aData[pInput->iNext+nVar], nCol, &rc);
  192075. sessionAppendByte(&sOut, eType, &rc);
  192076. sessionAppendBlob(&sOut, &pInput->aData[pInput->iNext], nByte, &rc);
  192077. if( rc ) goto finished_invert;
  192078. pInput->iNext += nByte;
  192079. sqlite3_free(apVal);
  192080. apVal = 0;
  192081. abPK = sPK.aBuf;
  192082. break;
  192083. }
  192084. case SQLITE_INSERT:
  192085. case SQLITE_DELETE: {
  192086. int nByte;
  192087. int bIndirect = pInput->aData[pInput->iNext+1];
  192088. int eType2 = (eType==SQLITE_DELETE ? SQLITE_INSERT : SQLITE_DELETE);
  192089. pInput->iNext += 2;
  192090. assert( rc==SQLITE_OK );
  192091. rc = sessionChangesetBufferRecord(pInput, nCol, &nByte);
  192092. sessionAppendByte(&sOut, eType2, &rc);
  192093. sessionAppendByte(&sOut, bIndirect, &rc);
  192094. sessionAppendBlob(&sOut, &pInput->aData[pInput->iNext], nByte, &rc);
  192095. pInput->iNext += nByte;
  192096. if( rc ) goto finished_invert;
  192097. break;
  192098. }
  192099. case SQLITE_UPDATE: {
  192100. int iCol;
  192101. if( 0==apVal ){
  192102. apVal = (sqlite3_value **)sqlite3_malloc64(sizeof(apVal[0])*nCol*2);
  192103. if( 0==apVal ){
  192104. rc = SQLITE_NOMEM;
  192105. goto finished_invert;
  192106. }
  192107. memset(apVal, 0, sizeof(apVal[0])*nCol*2);
  192108. }
  192109. /* Write the header for the new UPDATE change. Same as the original. */
  192110. sessionAppendByte(&sOut, eType, &rc);
  192111. sessionAppendByte(&sOut, pInput->aData[pInput->iNext+1], &rc);
  192112. /* Read the old.* and new.* records for the update change. */
  192113. pInput->iNext += 2;
  192114. rc = sessionReadRecord(pInput, nCol, 0, &apVal[0]);
  192115. if( rc==SQLITE_OK ){
  192116. rc = sessionReadRecord(pInput, nCol, 0, &apVal[nCol]);
  192117. }
  192118. /* Write the new old.* record. Consists of the PK columns from the
  192119. ** original old.* record, and the other values from the original
  192120. ** new.* record. */
  192121. for(iCol=0; iCol<nCol; iCol++){
  192122. sqlite3_value *pVal = apVal[iCol + (abPK[iCol] ? 0 : nCol)];
  192123. sessionAppendValue(&sOut, pVal, &rc);
  192124. }
  192125. /* Write the new new.* record. Consists of a copy of all values
  192126. ** from the original old.* record, except for the PK columns, which
  192127. ** are set to "undefined". */
  192128. for(iCol=0; iCol<nCol; iCol++){
  192129. sqlite3_value *pVal = (abPK[iCol] ? 0 : apVal[iCol]);
  192130. sessionAppendValue(&sOut, pVal, &rc);
  192131. }
  192132. for(iCol=0; iCol<nCol*2; iCol++){
  192133. sqlite3ValueFree(apVal[iCol]);
  192134. }
  192135. memset(apVal, 0, sizeof(apVal[0])*nCol*2);
  192136. if( rc!=SQLITE_OK ){
  192137. goto finished_invert;
  192138. }
  192139. break;
  192140. }
  192141. default:
  192142. rc = SQLITE_CORRUPT_BKPT;
  192143. goto finished_invert;
  192144. }
  192145. assert( rc==SQLITE_OK );
  192146. if( xOutput && sOut.nBuf>=sessions_strm_chunk_size ){
  192147. rc = xOutput(pOut, sOut.aBuf, sOut.nBuf);
  192148. sOut.nBuf = 0;
  192149. if( rc!=SQLITE_OK ) goto finished_invert;
  192150. }
  192151. }
  192152. assert( rc==SQLITE_OK );
  192153. if( pnInverted ){
  192154. *pnInverted = sOut.nBuf;
  192155. *ppInverted = sOut.aBuf;
  192156. sOut.aBuf = 0;
  192157. }else if( sOut.nBuf>0 ){
  192158. rc = xOutput(pOut, sOut.aBuf, sOut.nBuf);
  192159. }
  192160. finished_invert:
  192161. sqlite3_free(sOut.aBuf);
  192162. sqlite3_free(apVal);
  192163. sqlite3_free(sPK.aBuf);
  192164. return rc;
  192165. }
  192166. /*
  192167. ** Invert a changeset object.
  192168. */
  192169. SQLITE_API int sqlite3changeset_invert(
  192170. int nChangeset, /* Number of bytes in input */
  192171. const void *pChangeset, /* Input changeset */
  192172. int *pnInverted, /* OUT: Number of bytes in output changeset */
  192173. void **ppInverted /* OUT: Inverse of pChangeset */
  192174. ){
  192175. SessionInput sInput;
  192176. /* Set up the input stream */
  192177. memset(&sInput, 0, sizeof(SessionInput));
  192178. sInput.nData = nChangeset;
  192179. sInput.aData = (u8*)pChangeset;
  192180. return sessionChangesetInvert(&sInput, 0, 0, pnInverted, ppInverted);
  192181. }
  192182. /*
  192183. ** Streaming version of sqlite3changeset_invert().
  192184. */
  192185. SQLITE_API int sqlite3changeset_invert_strm(
  192186. int (*xInput)(void *pIn, void *pData, int *pnData),
  192187. void *pIn,
  192188. int (*xOutput)(void *pOut, const void *pData, int nData),
  192189. void *pOut
  192190. ){
  192191. SessionInput sInput;
  192192. int rc;
  192193. /* Set up the input stream */
  192194. memset(&sInput, 0, sizeof(SessionInput));
  192195. sInput.xInput = xInput;
  192196. sInput.pIn = pIn;
  192197. rc = sessionChangesetInvert(&sInput, xOutput, pOut, 0, 0);
  192198. sqlite3_free(sInput.buf.aBuf);
  192199. return rc;
  192200. }
  192201. typedef struct SessionApplyCtx SessionApplyCtx;
  192202. struct SessionApplyCtx {
  192203. sqlite3 *db;
  192204. sqlite3_stmt *pDelete; /* DELETE statement */
  192205. sqlite3_stmt *pUpdate; /* UPDATE statement */
  192206. sqlite3_stmt *pInsert; /* INSERT statement */
  192207. sqlite3_stmt *pSelect; /* SELECT statement */
  192208. int nCol; /* Size of azCol[] and abPK[] arrays */
  192209. const char **azCol; /* Array of column names */
  192210. u8 *abPK; /* Boolean array - true if column is in PK */
  192211. int bStat1; /* True if table is sqlite_stat1 */
  192212. int bDeferConstraints; /* True to defer constraints */
  192213. SessionBuffer constraints; /* Deferred constraints are stored here */
  192214. SessionBuffer rebase; /* Rebase information (if any) here */
  192215. u8 bRebaseStarted; /* If table header is already in rebase */
  192216. u8 bRebase; /* True to collect rebase information */
  192217. };
  192218. /*
  192219. ** Formulate a statement to DELETE a row from database db. Assuming a table
  192220. ** structure like this:
  192221. **
  192222. ** CREATE TABLE x(a, b, c, d, PRIMARY KEY(a, c));
  192223. **
  192224. ** The DELETE statement looks like this:
  192225. **
  192226. ** DELETE FROM x WHERE a = :1 AND c = :3 AND (:5 OR b IS :2 AND d IS :4)
  192227. **
  192228. ** Variable :5 (nCol+1) is a boolean. It should be set to 0 if we require
  192229. ** matching b and d values, or 1 otherwise. The second case comes up if the
  192230. ** conflict handler is invoked with NOTFOUND and returns CHANGESET_REPLACE.
  192231. **
  192232. ** If successful, SQLITE_OK is returned and SessionApplyCtx.pDelete is left
  192233. ** pointing to the prepared version of the SQL statement.
  192234. */
  192235. static int sessionDeleteRow(
  192236. sqlite3 *db, /* Database handle */
  192237. const char *zTab, /* Table name */
  192238. SessionApplyCtx *p /* Session changeset-apply context */
  192239. ){
  192240. int i;
  192241. const char *zSep = "";
  192242. int rc = SQLITE_OK;
  192243. SessionBuffer buf = {0, 0, 0};
  192244. int nPk = 0;
  192245. sessionAppendStr(&buf, "DELETE FROM main.", &rc);
  192246. sessionAppendIdent(&buf, zTab, &rc);
  192247. sessionAppendStr(&buf, " WHERE ", &rc);
  192248. for(i=0; i<p->nCol; i++){
  192249. if( p->abPK[i] ){
  192250. nPk++;
  192251. sessionAppendStr(&buf, zSep, &rc);
  192252. sessionAppendIdent(&buf, p->azCol[i], &rc);
  192253. sessionAppendStr(&buf, " = ?", &rc);
  192254. sessionAppendInteger(&buf, i+1, &rc);
  192255. zSep = " AND ";
  192256. }
  192257. }
  192258. if( nPk<p->nCol ){
  192259. sessionAppendStr(&buf, " AND (?", &rc);
  192260. sessionAppendInteger(&buf, p->nCol+1, &rc);
  192261. sessionAppendStr(&buf, " OR ", &rc);
  192262. zSep = "";
  192263. for(i=0; i<p->nCol; i++){
  192264. if( !p->abPK[i] ){
  192265. sessionAppendStr(&buf, zSep, &rc);
  192266. sessionAppendIdent(&buf, p->azCol[i], &rc);
  192267. sessionAppendStr(&buf, " IS ?", &rc);
  192268. sessionAppendInteger(&buf, i+1, &rc);
  192269. zSep = "AND ";
  192270. }
  192271. }
  192272. sessionAppendStr(&buf, ")", &rc);
  192273. }
  192274. if( rc==SQLITE_OK ){
  192275. rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pDelete, 0);
  192276. }
  192277. sqlite3_free(buf.aBuf);
  192278. return rc;
  192279. }
  192280. /*
  192281. ** Formulate and prepare a statement to UPDATE a row from database db.
  192282. ** Assuming a table structure like this:
  192283. **
  192284. ** CREATE TABLE x(a, b, c, d, PRIMARY KEY(a, c));
  192285. **
  192286. ** The UPDATE statement looks like this:
  192287. **
  192288. ** UPDATE x SET
  192289. ** a = CASE WHEN ?2 THEN ?3 ELSE a END,
  192290. ** b = CASE WHEN ?5 THEN ?6 ELSE b END,
  192291. ** c = CASE WHEN ?8 THEN ?9 ELSE c END,
  192292. ** d = CASE WHEN ?11 THEN ?12 ELSE d END
  192293. ** WHERE a = ?1 AND c = ?7 AND (?13 OR
  192294. ** (?5==0 OR b IS ?4) AND (?11==0 OR d IS ?10) AND
  192295. ** )
  192296. **
  192297. ** For each column in the table, there are three variables to bind:
  192298. **
  192299. ** ?(i*3+1) The old.* value of the column, if any.
  192300. ** ?(i*3+2) A boolean flag indicating that the value is being modified.
  192301. ** ?(i*3+3) The new.* value of the column, if any.
  192302. **
  192303. ** Also, a boolean flag that, if set to true, causes the statement to update
  192304. ** a row even if the non-PK values do not match. This is required if the
  192305. ** conflict-handler is invoked with CHANGESET_DATA and returns
  192306. ** CHANGESET_REPLACE. This is variable "?(nCol*3+1)".
  192307. **
  192308. ** If successful, SQLITE_OK is returned and SessionApplyCtx.pUpdate is left
  192309. ** pointing to the prepared version of the SQL statement.
  192310. */
  192311. static int sessionUpdateRow(
  192312. sqlite3 *db, /* Database handle */
  192313. const char *zTab, /* Table name */
  192314. SessionApplyCtx *p /* Session changeset-apply context */
  192315. ){
  192316. int rc = SQLITE_OK;
  192317. int i;
  192318. const char *zSep = "";
  192319. SessionBuffer buf = {0, 0, 0};
  192320. /* Append "UPDATE tbl SET " */
  192321. sessionAppendStr(&buf, "UPDATE main.", &rc);
  192322. sessionAppendIdent(&buf, zTab, &rc);
  192323. sessionAppendStr(&buf, " SET ", &rc);
  192324. /* Append the assignments */
  192325. for(i=0; i<p->nCol; i++){
  192326. sessionAppendStr(&buf, zSep, &rc);
  192327. sessionAppendIdent(&buf, p->azCol[i], &rc);
  192328. sessionAppendStr(&buf, " = CASE WHEN ?", &rc);
  192329. sessionAppendInteger(&buf, i*3+2, &rc);
  192330. sessionAppendStr(&buf, " THEN ?", &rc);
  192331. sessionAppendInteger(&buf, i*3+3, &rc);
  192332. sessionAppendStr(&buf, " ELSE ", &rc);
  192333. sessionAppendIdent(&buf, p->azCol[i], &rc);
  192334. sessionAppendStr(&buf, " END", &rc);
  192335. zSep = ", ";
  192336. }
  192337. /* Append the PK part of the WHERE clause */
  192338. sessionAppendStr(&buf, " WHERE ", &rc);
  192339. for(i=0; i<p->nCol; i++){
  192340. if( p->abPK[i] ){
  192341. sessionAppendIdent(&buf, p->azCol[i], &rc);
  192342. sessionAppendStr(&buf, " = ?", &rc);
  192343. sessionAppendInteger(&buf, i*3+1, &rc);
  192344. sessionAppendStr(&buf, " AND ", &rc);
  192345. }
  192346. }
  192347. /* Append the non-PK part of the WHERE clause */
  192348. sessionAppendStr(&buf, " (?", &rc);
  192349. sessionAppendInteger(&buf, p->nCol*3+1, &rc);
  192350. sessionAppendStr(&buf, " OR 1", &rc);
  192351. for(i=0; i<p->nCol; i++){
  192352. if( !p->abPK[i] ){
  192353. sessionAppendStr(&buf, " AND (?", &rc);
  192354. sessionAppendInteger(&buf, i*3+2, &rc);
  192355. sessionAppendStr(&buf, "=0 OR ", &rc);
  192356. sessionAppendIdent(&buf, p->azCol[i], &rc);
  192357. sessionAppendStr(&buf, " IS ?", &rc);
  192358. sessionAppendInteger(&buf, i*3+1, &rc);
  192359. sessionAppendStr(&buf, ")", &rc);
  192360. }
  192361. }
  192362. sessionAppendStr(&buf, ")", &rc);
  192363. if( rc==SQLITE_OK ){
  192364. rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pUpdate, 0);
  192365. }
  192366. sqlite3_free(buf.aBuf);
  192367. return rc;
  192368. }
  192369. /*
  192370. ** Formulate and prepare an SQL statement to query table zTab by primary
  192371. ** key. Assuming the following table structure:
  192372. **
  192373. ** CREATE TABLE x(a, b, c, d, PRIMARY KEY(a, c));
  192374. **
  192375. ** The SELECT statement looks like this:
  192376. **
  192377. ** SELECT * FROM x WHERE a = ?1 AND c = ?3
  192378. **
  192379. ** If successful, SQLITE_OK is returned and SessionApplyCtx.pSelect is left
  192380. ** pointing to the prepared version of the SQL statement.
  192381. */
  192382. static int sessionSelectRow(
  192383. sqlite3 *db, /* Database handle */
  192384. const char *zTab, /* Table name */
  192385. SessionApplyCtx *p /* Session changeset-apply context */
  192386. ){
  192387. return sessionSelectStmt(
  192388. db, "main", zTab, p->nCol, p->azCol, p->abPK, &p->pSelect);
  192389. }
  192390. /*
  192391. ** Formulate and prepare an INSERT statement to add a record to table zTab.
  192392. ** For example:
  192393. **
  192394. ** INSERT INTO main."zTab" VALUES(?1, ?2, ?3 ...);
  192395. **
  192396. ** If successful, SQLITE_OK is returned and SessionApplyCtx.pInsert is left
  192397. ** pointing to the prepared version of the SQL statement.
  192398. */
  192399. static int sessionInsertRow(
  192400. sqlite3 *db, /* Database handle */
  192401. const char *zTab, /* Table name */
  192402. SessionApplyCtx *p /* Session changeset-apply context */
  192403. ){
  192404. int rc = SQLITE_OK;
  192405. int i;
  192406. SessionBuffer buf = {0, 0, 0};
  192407. sessionAppendStr(&buf, "INSERT INTO main.", &rc);
  192408. sessionAppendIdent(&buf, zTab, &rc);
  192409. sessionAppendStr(&buf, "(", &rc);
  192410. for(i=0; i<p->nCol; i++){
  192411. if( i!=0 ) sessionAppendStr(&buf, ", ", &rc);
  192412. sessionAppendIdent(&buf, p->azCol[i], &rc);
  192413. }
  192414. sessionAppendStr(&buf, ") VALUES(?", &rc);
  192415. for(i=1; i<p->nCol; i++){
  192416. sessionAppendStr(&buf, ", ?", &rc);
  192417. }
  192418. sessionAppendStr(&buf, ")", &rc);
  192419. if( rc==SQLITE_OK ){
  192420. rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pInsert, 0);
  192421. }
  192422. sqlite3_free(buf.aBuf);
  192423. return rc;
  192424. }
  192425. static int sessionPrepare(sqlite3 *db, sqlite3_stmt **pp, const char *zSql){
  192426. return sqlite3_prepare_v2(db, zSql, -1, pp, 0);
  192427. }
  192428. /*
  192429. ** Prepare statements for applying changes to the sqlite_stat1 table.
  192430. ** These are similar to those created by sessionSelectRow(),
  192431. ** sessionInsertRow(), sessionUpdateRow() and sessionDeleteRow() for
  192432. ** other tables.
  192433. */
  192434. static int sessionStat1Sql(sqlite3 *db, SessionApplyCtx *p){
  192435. int rc = sessionSelectRow(db, "sqlite_stat1", p);
  192436. if( rc==SQLITE_OK ){
  192437. rc = sessionPrepare(db, &p->pInsert,
  192438. "INSERT INTO main.sqlite_stat1 VALUES(?1, "
  192439. "CASE WHEN length(?2)=0 AND typeof(?2)='blob' THEN NULL ELSE ?2 END, "
  192440. "?3)"
  192441. );
  192442. }
  192443. if( rc==SQLITE_OK ){
  192444. rc = sessionPrepare(db, &p->pUpdate,
  192445. "UPDATE main.sqlite_stat1 SET "
  192446. "tbl = CASE WHEN ?2 THEN ?3 ELSE tbl END, "
  192447. "idx = CASE WHEN ?5 THEN ?6 ELSE idx END, "
  192448. "stat = CASE WHEN ?8 THEN ?9 ELSE stat END "
  192449. "WHERE tbl=?1 AND idx IS "
  192450. "CASE WHEN length(?4)=0 AND typeof(?4)='blob' THEN NULL ELSE ?4 END "
  192451. "AND (?10 OR ?8=0 OR stat IS ?7)"
  192452. );
  192453. }
  192454. if( rc==SQLITE_OK ){
  192455. rc = sessionPrepare(db, &p->pDelete,
  192456. "DELETE FROM main.sqlite_stat1 WHERE tbl=?1 AND idx IS "
  192457. "CASE WHEN length(?2)=0 AND typeof(?2)='blob' THEN NULL ELSE ?2 END "
  192458. "AND (?4 OR stat IS ?3)"
  192459. );
  192460. }
  192461. return rc;
  192462. }
  192463. /*
  192464. ** A wrapper around sqlite3_bind_value() that detects an extra problem.
  192465. ** See comments in the body of this function for details.
  192466. */
  192467. static int sessionBindValue(
  192468. sqlite3_stmt *pStmt, /* Statement to bind value to */
  192469. int i, /* Parameter number to bind to */
  192470. sqlite3_value *pVal /* Value to bind */
  192471. ){
  192472. int eType = sqlite3_value_type(pVal);
  192473. /* COVERAGE: The (pVal->z==0) branch is never true using current versions
  192474. ** of SQLite. If a malloc fails in an sqlite3_value_xxx() function, either
  192475. ** the (pVal->z) variable remains as it was or the type of the value is
  192476. ** set to SQLITE_NULL. */
  192477. if( (eType==SQLITE_TEXT || eType==SQLITE_BLOB) && pVal->z==0 ){
  192478. /* This condition occurs when an earlier OOM in a call to
  192479. ** sqlite3_value_text() or sqlite3_value_blob() (perhaps from within
  192480. ** a conflict-handler) has zeroed the pVal->z pointer. Return NOMEM. */
  192481. return SQLITE_NOMEM;
  192482. }
  192483. return sqlite3_bind_value(pStmt, i, pVal);
  192484. }
  192485. /*
  192486. ** Iterator pIter must point to an SQLITE_INSERT entry. This function
  192487. ** transfers new.* values from the current iterator entry to statement
  192488. ** pStmt. The table being inserted into has nCol columns.
  192489. **
  192490. ** New.* value $i from the iterator is bound to variable ($i+1) of
  192491. ** statement pStmt. If parameter abPK is NULL, all values from 0 to (nCol-1)
  192492. ** are transfered to the statement. Otherwise, if abPK is not NULL, it points
  192493. ** to an array nCol elements in size. In this case only those values for
  192494. ** which abPK[$i] is true are read from the iterator and bound to the
  192495. ** statement.
  192496. **
  192497. ** An SQLite error code is returned if an error occurs. Otherwise, SQLITE_OK.
  192498. */
  192499. static int sessionBindRow(
  192500. sqlite3_changeset_iter *pIter, /* Iterator to read values from */
  192501. int(*xValue)(sqlite3_changeset_iter *, int, sqlite3_value **),
  192502. int nCol, /* Number of columns */
  192503. u8 *abPK, /* If not NULL, bind only if true */
  192504. sqlite3_stmt *pStmt /* Bind values to this statement */
  192505. ){
  192506. int i;
  192507. int rc = SQLITE_OK;
  192508. /* Neither sqlite3changeset_old or sqlite3changeset_new can fail if the
  192509. ** argument iterator points to a suitable entry. Make sure that xValue
  192510. ** is one of these to guarantee that it is safe to ignore the return
  192511. ** in the code below. */
  192512. assert( xValue==sqlite3changeset_old || xValue==sqlite3changeset_new );
  192513. for(i=0; rc==SQLITE_OK && i<nCol; i++){
  192514. if( !abPK || abPK[i] ){
  192515. sqlite3_value *pVal;
  192516. (void)xValue(pIter, i, &pVal);
  192517. if( pVal==0 ){
  192518. /* The value in the changeset was "undefined". This indicates a
  192519. ** corrupt changeset blob. */
  192520. rc = SQLITE_CORRUPT_BKPT;
  192521. }else{
  192522. rc = sessionBindValue(pStmt, i+1, pVal);
  192523. }
  192524. }
  192525. }
  192526. return rc;
  192527. }
  192528. /*
  192529. ** SQL statement pSelect is as generated by the sessionSelectRow() function.
  192530. ** This function binds the primary key values from the change that changeset
  192531. ** iterator pIter points to to the SELECT and attempts to seek to the table
  192532. ** entry. If a row is found, the SELECT statement left pointing at the row
  192533. ** and SQLITE_ROW is returned. Otherwise, if no row is found and no error
  192534. ** has occured, the statement is reset and SQLITE_OK is returned. If an
  192535. ** error occurs, the statement is reset and an SQLite error code is returned.
  192536. **
  192537. ** If this function returns SQLITE_ROW, the caller must eventually reset()
  192538. ** statement pSelect. If any other value is returned, the statement does
  192539. ** not require a reset().
  192540. **
  192541. ** If the iterator currently points to an INSERT record, bind values from the
  192542. ** new.* record to the SELECT statement. Or, if it points to a DELETE or
  192543. ** UPDATE, bind values from the old.* record.
  192544. */
  192545. static int sessionSeekToRow(
  192546. sqlite3 *db, /* Database handle */
  192547. sqlite3_changeset_iter *pIter, /* Changeset iterator */
  192548. u8 *abPK, /* Primary key flags array */
  192549. sqlite3_stmt *pSelect /* SELECT statement from sessionSelectRow() */
  192550. ){
  192551. int rc; /* Return code */
  192552. int nCol; /* Number of columns in table */
  192553. int op; /* Changset operation (SQLITE_UPDATE etc.) */
  192554. const char *zDummy; /* Unused */
  192555. sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0);
  192556. rc = sessionBindRow(pIter,
  192557. op==SQLITE_INSERT ? sqlite3changeset_new : sqlite3changeset_old,
  192558. nCol, abPK, pSelect
  192559. );
  192560. if( rc==SQLITE_OK ){
  192561. rc = sqlite3_step(pSelect);
  192562. if( rc!=SQLITE_ROW ) rc = sqlite3_reset(pSelect);
  192563. }
  192564. return rc;
  192565. }
  192566. /*
  192567. ** This function is called from within sqlite3changeset_apply_v2() when
  192568. ** a conflict is encountered and resolved using conflict resolution
  192569. ** mode eType (either SQLITE_CHANGESET_OMIT or SQLITE_CHANGESET_REPLACE)..
  192570. ** It adds a conflict resolution record to the buffer in
  192571. ** SessionApplyCtx.rebase, which will eventually be returned to the caller
  192572. ** of apply_v2() as the "rebase" buffer.
  192573. **
  192574. ** Return SQLITE_OK if successful, or an SQLite error code otherwise.
  192575. */
  192576. static int sessionRebaseAdd(
  192577. SessionApplyCtx *p, /* Apply context */
  192578. int eType, /* Conflict resolution (OMIT or REPLACE) */
  192579. sqlite3_changeset_iter *pIter /* Iterator pointing at current change */
  192580. ){
  192581. int rc = SQLITE_OK;
  192582. if( p->bRebase ){
  192583. int i;
  192584. int eOp = pIter->op;
  192585. if( p->bRebaseStarted==0 ){
  192586. /* Append a table-header to the rebase buffer */
  192587. const char *zTab = pIter->zTab;
  192588. sessionAppendByte(&p->rebase, 'T', &rc);
  192589. sessionAppendVarint(&p->rebase, p->nCol, &rc);
  192590. sessionAppendBlob(&p->rebase, p->abPK, p->nCol, &rc);
  192591. sessionAppendBlob(&p->rebase, (u8*)zTab, (int)strlen(zTab)+1, &rc);
  192592. p->bRebaseStarted = 1;
  192593. }
  192594. assert( eType==SQLITE_CHANGESET_REPLACE||eType==SQLITE_CHANGESET_OMIT );
  192595. assert( eOp==SQLITE_DELETE || eOp==SQLITE_INSERT || eOp==SQLITE_UPDATE );
  192596. sessionAppendByte(&p->rebase,
  192597. (eOp==SQLITE_DELETE ? SQLITE_DELETE : SQLITE_INSERT), &rc
  192598. );
  192599. sessionAppendByte(&p->rebase, (eType==SQLITE_CHANGESET_REPLACE), &rc);
  192600. for(i=0; i<p->nCol; i++){
  192601. sqlite3_value *pVal = 0;
  192602. if( eOp==SQLITE_DELETE || (eOp==SQLITE_UPDATE && p->abPK[i]) ){
  192603. sqlite3changeset_old(pIter, i, &pVal);
  192604. }else{
  192605. sqlite3changeset_new(pIter, i, &pVal);
  192606. }
  192607. sessionAppendValue(&p->rebase, pVal, &rc);
  192608. }
  192609. }
  192610. return rc;
  192611. }
  192612. /*
  192613. ** Invoke the conflict handler for the change that the changeset iterator
  192614. ** currently points to.
  192615. **
  192616. ** Argument eType must be either CHANGESET_DATA or CHANGESET_CONFLICT.
  192617. ** If argument pbReplace is NULL, then the type of conflict handler invoked
  192618. ** depends solely on eType, as follows:
  192619. **
  192620. ** eType value Value passed to xConflict
  192621. ** -------------------------------------------------
  192622. ** CHANGESET_DATA CHANGESET_NOTFOUND
  192623. ** CHANGESET_CONFLICT CHANGESET_CONSTRAINT
  192624. **
  192625. ** Or, if pbReplace is not NULL, then an attempt is made to find an existing
  192626. ** record with the same primary key as the record about to be deleted, updated
  192627. ** or inserted. If such a record can be found, it is available to the conflict
  192628. ** handler as the "conflicting" record. In this case the type of conflict
  192629. ** handler invoked is as follows:
  192630. **
  192631. ** eType value PK Record found? Value passed to xConflict
  192632. ** ----------------------------------------------------------------
  192633. ** CHANGESET_DATA Yes CHANGESET_DATA
  192634. ** CHANGESET_DATA No CHANGESET_NOTFOUND
  192635. ** CHANGESET_CONFLICT Yes CHANGESET_CONFLICT
  192636. ** CHANGESET_CONFLICT No CHANGESET_CONSTRAINT
  192637. **
  192638. ** If pbReplace is not NULL, and a record with a matching PK is found, and
  192639. ** the conflict handler function returns SQLITE_CHANGESET_REPLACE, *pbReplace
  192640. ** is set to non-zero before returning SQLITE_OK.
  192641. **
  192642. ** If the conflict handler returns SQLITE_CHANGESET_ABORT, SQLITE_ABORT is
  192643. ** returned. Or, if the conflict handler returns an invalid value,
  192644. ** SQLITE_MISUSE. If the conflict handler returns SQLITE_CHANGESET_OMIT,
  192645. ** this function returns SQLITE_OK.
  192646. */
  192647. static int sessionConflictHandler(
  192648. int eType, /* Either CHANGESET_DATA or CONFLICT */
  192649. SessionApplyCtx *p, /* changeset_apply() context */
  192650. sqlite3_changeset_iter *pIter, /* Changeset iterator */
  192651. int(*xConflict)(void *, int, sqlite3_changeset_iter*),
  192652. void *pCtx, /* First argument for conflict handler */
  192653. int *pbReplace /* OUT: Set to true if PK row is found */
  192654. ){
  192655. int res = 0; /* Value returned by conflict handler */
  192656. int rc;
  192657. int nCol;
  192658. int op;
  192659. const char *zDummy;
  192660. sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0);
  192661. assert( eType==SQLITE_CHANGESET_CONFLICT || eType==SQLITE_CHANGESET_DATA );
  192662. assert( SQLITE_CHANGESET_CONFLICT+1==SQLITE_CHANGESET_CONSTRAINT );
  192663. assert( SQLITE_CHANGESET_DATA+1==SQLITE_CHANGESET_NOTFOUND );
  192664. /* Bind the new.* PRIMARY KEY values to the SELECT statement. */
  192665. if( pbReplace ){
  192666. rc = sessionSeekToRow(p->db, pIter, p->abPK, p->pSelect);
  192667. }else{
  192668. rc = SQLITE_OK;
  192669. }
  192670. if( rc==SQLITE_ROW ){
  192671. /* There exists another row with the new.* primary key. */
  192672. pIter->pConflict = p->pSelect;
  192673. res = xConflict(pCtx, eType, pIter);
  192674. pIter->pConflict = 0;
  192675. rc = sqlite3_reset(p->pSelect);
  192676. }else if( rc==SQLITE_OK ){
  192677. if( p->bDeferConstraints && eType==SQLITE_CHANGESET_CONFLICT ){
  192678. /* Instead of invoking the conflict handler, append the change blob
  192679. ** to the SessionApplyCtx.constraints buffer. */
  192680. u8 *aBlob = &pIter->in.aData[pIter->in.iCurrent];
  192681. int nBlob = pIter->in.iNext - pIter->in.iCurrent;
  192682. sessionAppendBlob(&p->constraints, aBlob, nBlob, &rc);
  192683. return SQLITE_OK;
  192684. }else{
  192685. /* No other row with the new.* primary key. */
  192686. res = xConflict(pCtx, eType+1, pIter);
  192687. if( res==SQLITE_CHANGESET_REPLACE ) rc = SQLITE_MISUSE;
  192688. }
  192689. }
  192690. if( rc==SQLITE_OK ){
  192691. switch( res ){
  192692. case SQLITE_CHANGESET_REPLACE:
  192693. assert( pbReplace );
  192694. *pbReplace = 1;
  192695. break;
  192696. case SQLITE_CHANGESET_OMIT:
  192697. break;
  192698. case SQLITE_CHANGESET_ABORT:
  192699. rc = SQLITE_ABORT;
  192700. break;
  192701. default:
  192702. rc = SQLITE_MISUSE;
  192703. break;
  192704. }
  192705. if( rc==SQLITE_OK ){
  192706. rc = sessionRebaseAdd(p, res, pIter);
  192707. }
  192708. }
  192709. return rc;
  192710. }
  192711. /*
  192712. ** Attempt to apply the change that the iterator passed as the first argument
  192713. ** currently points to to the database. If a conflict is encountered, invoke
  192714. ** the conflict handler callback.
  192715. **
  192716. ** If argument pbRetry is NULL, then ignore any CHANGESET_DATA conflict. If
  192717. ** one is encountered, update or delete the row with the matching primary key
  192718. ** instead. Or, if pbRetry is not NULL and a CHANGESET_DATA conflict occurs,
  192719. ** invoke the conflict handler. If it returns CHANGESET_REPLACE, set *pbRetry
  192720. ** to true before returning. In this case the caller will invoke this function
  192721. ** again, this time with pbRetry set to NULL.
  192722. **
  192723. ** If argument pbReplace is NULL and a CHANGESET_CONFLICT conflict is
  192724. ** encountered invoke the conflict handler with CHANGESET_CONSTRAINT instead.
  192725. ** Or, if pbReplace is not NULL, invoke it with CHANGESET_CONFLICT. If such
  192726. ** an invocation returns SQLITE_CHANGESET_REPLACE, set *pbReplace to true
  192727. ** before retrying. In this case the caller attempts to remove the conflicting
  192728. ** row before invoking this function again, this time with pbReplace set
  192729. ** to NULL.
  192730. **
  192731. ** If any conflict handler returns SQLITE_CHANGESET_ABORT, this function
  192732. ** returns SQLITE_ABORT. Otherwise, if no error occurs, SQLITE_OK is
  192733. ** returned.
  192734. */
  192735. static int sessionApplyOneOp(
  192736. sqlite3_changeset_iter *pIter, /* Changeset iterator */
  192737. SessionApplyCtx *p, /* changeset_apply() context */
  192738. int(*xConflict)(void *, int, sqlite3_changeset_iter *),
  192739. void *pCtx, /* First argument for the conflict handler */
  192740. int *pbReplace, /* OUT: True to remove PK row and retry */
  192741. int *pbRetry /* OUT: True to retry. */
  192742. ){
  192743. const char *zDummy;
  192744. int op;
  192745. int nCol;
  192746. int rc = SQLITE_OK;
  192747. assert( p->pDelete && p->pUpdate && p->pInsert && p->pSelect );
  192748. assert( p->azCol && p->abPK );
  192749. assert( !pbReplace || *pbReplace==0 );
  192750. sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0);
  192751. if( op==SQLITE_DELETE ){
  192752. /* Bind values to the DELETE statement. If conflict handling is required,
  192753. ** bind values for all columns and set bound variable (nCol+1) to true.
  192754. ** Or, if conflict handling is not required, bind just the PK column
  192755. ** values and, if it exists, set (nCol+1) to false. Conflict handling
  192756. ** is not required if:
  192757. **
  192758. ** * this is a patchset, or
  192759. ** * (pbRetry==0), or
  192760. ** * all columns of the table are PK columns (in this case there is
  192761. ** no (nCol+1) variable to bind to).
  192762. */
  192763. u8 *abPK = (pIter->bPatchset ? p->abPK : 0);
  192764. rc = sessionBindRow(pIter, sqlite3changeset_old, nCol, abPK, p->pDelete);
  192765. if( rc==SQLITE_OK && sqlite3_bind_parameter_count(p->pDelete)>nCol ){
  192766. rc = sqlite3_bind_int(p->pDelete, nCol+1, (pbRetry==0 || abPK));
  192767. }
  192768. if( rc!=SQLITE_OK ) return rc;
  192769. sqlite3_step(p->pDelete);
  192770. rc = sqlite3_reset(p->pDelete);
  192771. if( rc==SQLITE_OK && sqlite3_changes(p->db)==0 ){
  192772. rc = sessionConflictHandler(
  192773. SQLITE_CHANGESET_DATA, p, pIter, xConflict, pCtx, pbRetry
  192774. );
  192775. }else if( (rc&0xff)==SQLITE_CONSTRAINT ){
  192776. rc = sessionConflictHandler(
  192777. SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, 0
  192778. );
  192779. }
  192780. }else if( op==SQLITE_UPDATE ){
  192781. int i;
  192782. /* Bind values to the UPDATE statement. */
  192783. for(i=0; rc==SQLITE_OK && i<nCol; i++){
  192784. sqlite3_value *pOld = sessionChangesetOld(pIter, i);
  192785. sqlite3_value *pNew = sessionChangesetNew(pIter, i);
  192786. sqlite3_bind_int(p->pUpdate, i*3+2, !!pNew);
  192787. if( pOld ){
  192788. rc = sessionBindValue(p->pUpdate, i*3+1, pOld);
  192789. }
  192790. if( rc==SQLITE_OK && pNew ){
  192791. rc = sessionBindValue(p->pUpdate, i*3+3, pNew);
  192792. }
  192793. }
  192794. if( rc==SQLITE_OK ){
  192795. sqlite3_bind_int(p->pUpdate, nCol*3+1, pbRetry==0 || pIter->bPatchset);
  192796. }
  192797. if( rc!=SQLITE_OK ) return rc;
  192798. /* Attempt the UPDATE. In the case of a NOTFOUND or DATA conflict,
  192799. ** the result will be SQLITE_OK with 0 rows modified. */
  192800. sqlite3_step(p->pUpdate);
  192801. rc = sqlite3_reset(p->pUpdate);
  192802. if( rc==SQLITE_OK && sqlite3_changes(p->db)==0 ){
  192803. /* A NOTFOUND or DATA error. Search the table to see if it contains
  192804. ** a row with a matching primary key. If so, this is a DATA conflict.
  192805. ** Otherwise, if there is no primary key match, it is a NOTFOUND. */
  192806. rc = sessionConflictHandler(
  192807. SQLITE_CHANGESET_DATA, p, pIter, xConflict, pCtx, pbRetry
  192808. );
  192809. }else if( (rc&0xff)==SQLITE_CONSTRAINT ){
  192810. /* This is always a CONSTRAINT conflict. */
  192811. rc = sessionConflictHandler(
  192812. SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, 0
  192813. );
  192814. }
  192815. }else{
  192816. assert( op==SQLITE_INSERT );
  192817. if( p->bStat1 ){
  192818. /* Check if there is a conflicting row. For sqlite_stat1, this needs
  192819. ** to be done using a SELECT, as there is no PRIMARY KEY in the
  192820. ** database schema to throw an exception if a duplicate is inserted. */
  192821. rc = sessionSeekToRow(p->db, pIter, p->abPK, p->pSelect);
  192822. if( rc==SQLITE_ROW ){
  192823. rc = SQLITE_CONSTRAINT;
  192824. sqlite3_reset(p->pSelect);
  192825. }
  192826. }
  192827. if( rc==SQLITE_OK ){
  192828. rc = sessionBindRow(pIter, sqlite3changeset_new, nCol, 0, p->pInsert);
  192829. if( rc!=SQLITE_OK ) return rc;
  192830. sqlite3_step(p->pInsert);
  192831. rc = sqlite3_reset(p->pInsert);
  192832. }
  192833. if( (rc&0xff)==SQLITE_CONSTRAINT ){
  192834. rc = sessionConflictHandler(
  192835. SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, pbReplace
  192836. );
  192837. }
  192838. }
  192839. return rc;
  192840. }
  192841. /*
  192842. ** Attempt to apply the change that the iterator passed as the first argument
  192843. ** currently points to to the database. If a conflict is encountered, invoke
  192844. ** the conflict handler callback.
  192845. **
  192846. ** The difference between this function and sessionApplyOne() is that this
  192847. ** function handles the case where the conflict-handler is invoked and
  192848. ** returns SQLITE_CHANGESET_REPLACE - indicating that the change should be
  192849. ** retried in some manner.
  192850. */
  192851. static int sessionApplyOneWithRetry(
  192852. sqlite3 *db, /* Apply change to "main" db of this handle */
  192853. sqlite3_changeset_iter *pIter, /* Changeset iterator to read change from */
  192854. SessionApplyCtx *pApply, /* Apply context */
  192855. int(*xConflict)(void*, int, sqlite3_changeset_iter*),
  192856. void *pCtx /* First argument passed to xConflict */
  192857. ){
  192858. int bReplace = 0;
  192859. int bRetry = 0;
  192860. int rc;
  192861. rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, &bReplace, &bRetry);
  192862. if( rc==SQLITE_OK ){
  192863. /* If the bRetry flag is set, the change has not been applied due to an
  192864. ** SQLITE_CHANGESET_DATA problem (i.e. this is an UPDATE or DELETE and
  192865. ** a row with the correct PK is present in the db, but one or more other
  192866. ** fields do not contain the expected values) and the conflict handler
  192867. ** returned SQLITE_CHANGESET_REPLACE. In this case retry the operation,
  192868. ** but pass NULL as the final argument so that sessionApplyOneOp() ignores
  192869. ** the SQLITE_CHANGESET_DATA problem. */
  192870. if( bRetry ){
  192871. assert( pIter->op==SQLITE_UPDATE || pIter->op==SQLITE_DELETE );
  192872. rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, 0, 0);
  192873. }
  192874. /* If the bReplace flag is set, the change is an INSERT that has not
  192875. ** been performed because the database already contains a row with the
  192876. ** specified primary key and the conflict handler returned
  192877. ** SQLITE_CHANGESET_REPLACE. In this case remove the conflicting row
  192878. ** before reattempting the INSERT. */
  192879. else if( bReplace ){
  192880. assert( pIter->op==SQLITE_INSERT );
  192881. rc = sqlite3_exec(db, "SAVEPOINT replace_op", 0, 0, 0);
  192882. if( rc==SQLITE_OK ){
  192883. rc = sessionBindRow(pIter,
  192884. sqlite3changeset_new, pApply->nCol, pApply->abPK, pApply->pDelete);
  192885. sqlite3_bind_int(pApply->pDelete, pApply->nCol+1, 1);
  192886. }
  192887. if( rc==SQLITE_OK ){
  192888. sqlite3_step(pApply->pDelete);
  192889. rc = sqlite3_reset(pApply->pDelete);
  192890. }
  192891. if( rc==SQLITE_OK ){
  192892. rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, 0, 0);
  192893. }
  192894. if( rc==SQLITE_OK ){
  192895. rc = sqlite3_exec(db, "RELEASE replace_op", 0, 0, 0);
  192896. }
  192897. }
  192898. }
  192899. return rc;
  192900. }
  192901. /*
  192902. ** Retry the changes accumulated in the pApply->constraints buffer.
  192903. */
  192904. static int sessionRetryConstraints(
  192905. sqlite3 *db,
  192906. int bPatchset,
  192907. const char *zTab,
  192908. SessionApplyCtx *pApply,
  192909. int(*xConflict)(void*, int, sqlite3_changeset_iter*),
  192910. void *pCtx /* First argument passed to xConflict */
  192911. ){
  192912. int rc = SQLITE_OK;
  192913. while( pApply->constraints.nBuf ){
  192914. sqlite3_changeset_iter *pIter2 = 0;
  192915. SessionBuffer cons = pApply->constraints;
  192916. memset(&pApply->constraints, 0, sizeof(SessionBuffer));
  192917. rc = sessionChangesetStart(&pIter2, 0, 0, cons.nBuf, cons.aBuf, 0);
  192918. if( rc==SQLITE_OK ){
  192919. size_t nByte = 2*pApply->nCol*sizeof(sqlite3_value*);
  192920. int rc2;
  192921. pIter2->bPatchset = bPatchset;
  192922. pIter2->zTab = (char*)zTab;
  192923. pIter2->nCol = pApply->nCol;
  192924. pIter2->abPK = pApply->abPK;
  192925. sessionBufferGrow(&pIter2->tblhdr, nByte, &rc);
  192926. pIter2->apValue = (sqlite3_value**)pIter2->tblhdr.aBuf;
  192927. if( rc==SQLITE_OK ) memset(pIter2->apValue, 0, nByte);
  192928. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3changeset_next(pIter2) ){
  192929. rc = sessionApplyOneWithRetry(db, pIter2, pApply, xConflict, pCtx);
  192930. }
  192931. rc2 = sqlite3changeset_finalize(pIter2);
  192932. if( rc==SQLITE_OK ) rc = rc2;
  192933. }
  192934. assert( pApply->bDeferConstraints || pApply->constraints.nBuf==0 );
  192935. sqlite3_free(cons.aBuf);
  192936. if( rc!=SQLITE_OK ) break;
  192937. if( pApply->constraints.nBuf>=cons.nBuf ){
  192938. /* No progress was made on the last round. */
  192939. pApply->bDeferConstraints = 0;
  192940. }
  192941. }
  192942. return rc;
  192943. }
  192944. /*
  192945. ** Argument pIter is a changeset iterator that has been initialized, but
  192946. ** not yet passed to sqlite3changeset_next(). This function applies the
  192947. ** changeset to the main database attached to handle "db". The supplied
  192948. ** conflict handler callback is invoked to resolve any conflicts encountered
  192949. ** while applying the change.
  192950. */
  192951. static int sessionChangesetApply(
  192952. sqlite3 *db, /* Apply change to "main" db of this handle */
  192953. sqlite3_changeset_iter *pIter, /* Changeset to apply */
  192954. int(*xFilter)(
  192955. void *pCtx, /* Copy of sixth arg to _apply() */
  192956. const char *zTab /* Table name */
  192957. ),
  192958. int(*xConflict)(
  192959. void *pCtx, /* Copy of fifth arg to _apply() */
  192960. int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
  192961. sqlite3_changeset_iter *p /* Handle describing change and conflict */
  192962. ),
  192963. void *pCtx, /* First argument passed to xConflict */
  192964. void **ppRebase, int *pnRebase, /* OUT: Rebase information */
  192965. int flags /* SESSION_APPLY_XXX flags */
  192966. ){
  192967. int schemaMismatch = 0;
  192968. int rc = SQLITE_OK; /* Return code */
  192969. const char *zTab = 0; /* Name of current table */
  192970. int nTab = 0; /* Result of sqlite3Strlen30(zTab) */
  192971. SessionApplyCtx sApply; /* changeset_apply() context object */
  192972. int bPatchset;
  192973. assert( xConflict!=0 );
  192974. pIter->in.bNoDiscard = 1;
  192975. memset(&sApply, 0, sizeof(sApply));
  192976. sApply.bRebase = (ppRebase && pnRebase);
  192977. sqlite3_mutex_enter(sqlite3_db_mutex(db));
  192978. if( (flags & SQLITE_CHANGESETAPPLY_NOSAVEPOINT)==0 ){
  192979. rc = sqlite3_exec(db, "SAVEPOINT changeset_apply", 0, 0, 0);
  192980. }
  192981. if( rc==SQLITE_OK ){
  192982. rc = sqlite3_exec(db, "PRAGMA defer_foreign_keys = 1", 0, 0, 0);
  192983. }
  192984. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3changeset_next(pIter) ){
  192985. int nCol;
  192986. int op;
  192987. const char *zNew;
  192988. sqlite3changeset_op(pIter, &zNew, &nCol, &op, 0);
  192989. if( zTab==0 || sqlite3_strnicmp(zNew, zTab, nTab+1) ){
  192990. u8 *abPK;
  192991. rc = sessionRetryConstraints(
  192992. db, pIter->bPatchset, zTab, &sApply, xConflict, pCtx
  192993. );
  192994. if( rc!=SQLITE_OK ) break;
  192995. sqlite3_free((char*)sApply.azCol); /* cast works around VC++ bug */
  192996. sqlite3_finalize(sApply.pDelete);
  192997. sqlite3_finalize(sApply.pUpdate);
  192998. sqlite3_finalize(sApply.pInsert);
  192999. sqlite3_finalize(sApply.pSelect);
  193000. sApply.db = db;
  193001. sApply.pDelete = 0;
  193002. sApply.pUpdate = 0;
  193003. sApply.pInsert = 0;
  193004. sApply.pSelect = 0;
  193005. sApply.nCol = 0;
  193006. sApply.azCol = 0;
  193007. sApply.abPK = 0;
  193008. sApply.bStat1 = 0;
  193009. sApply.bDeferConstraints = 1;
  193010. sApply.bRebaseStarted = 0;
  193011. memset(&sApply.constraints, 0, sizeof(SessionBuffer));
  193012. /* If an xFilter() callback was specified, invoke it now. If the
  193013. ** xFilter callback returns zero, skip this table. If it returns
  193014. ** non-zero, proceed. */
  193015. schemaMismatch = (xFilter && (0==xFilter(pCtx, zNew)));
  193016. if( schemaMismatch ){
  193017. zTab = sqlite3_mprintf("%s", zNew);
  193018. if( zTab==0 ){
  193019. rc = SQLITE_NOMEM;
  193020. break;
  193021. }
  193022. nTab = (int)strlen(zTab);
  193023. sApply.azCol = (const char **)zTab;
  193024. }else{
  193025. int nMinCol = 0;
  193026. int i;
  193027. sqlite3changeset_pk(pIter, &abPK, 0);
  193028. rc = sessionTableInfo(
  193029. db, "main", zNew, &sApply.nCol, &zTab, &sApply.azCol, &sApply.abPK
  193030. );
  193031. if( rc!=SQLITE_OK ) break;
  193032. for(i=0; i<sApply.nCol; i++){
  193033. if( sApply.abPK[i] ) nMinCol = i+1;
  193034. }
  193035. if( sApply.nCol==0 ){
  193036. schemaMismatch = 1;
  193037. sqlite3_log(SQLITE_SCHEMA,
  193038. "sqlite3changeset_apply(): no such table: %s", zTab
  193039. );
  193040. }
  193041. else if( sApply.nCol<nCol ){
  193042. schemaMismatch = 1;
  193043. sqlite3_log(SQLITE_SCHEMA,
  193044. "sqlite3changeset_apply(): table %s has %d columns, "
  193045. "expected %d or more",
  193046. zTab, sApply.nCol, nCol
  193047. );
  193048. }
  193049. else if( nCol<nMinCol || memcmp(sApply.abPK, abPK, nCol)!=0 ){
  193050. schemaMismatch = 1;
  193051. sqlite3_log(SQLITE_SCHEMA, "sqlite3changeset_apply(): "
  193052. "primary key mismatch for table %s", zTab
  193053. );
  193054. }
  193055. else{
  193056. sApply.nCol = nCol;
  193057. if( 0==sqlite3_stricmp(zTab, "sqlite_stat1") ){
  193058. if( (rc = sessionStat1Sql(db, &sApply) ) ){
  193059. break;
  193060. }
  193061. sApply.bStat1 = 1;
  193062. }else{
  193063. if((rc = sessionSelectRow(db, zTab, &sApply))
  193064. || (rc = sessionUpdateRow(db, zTab, &sApply))
  193065. || (rc = sessionDeleteRow(db, zTab, &sApply))
  193066. || (rc = sessionInsertRow(db, zTab, &sApply))
  193067. ){
  193068. break;
  193069. }
  193070. sApply.bStat1 = 0;
  193071. }
  193072. }
  193073. nTab = sqlite3Strlen30(zTab);
  193074. }
  193075. }
  193076. /* If there is a schema mismatch on the current table, proceed to the
  193077. ** next change. A log message has already been issued. */
  193078. if( schemaMismatch ) continue;
  193079. rc = sessionApplyOneWithRetry(db, pIter, &sApply, xConflict, pCtx);
  193080. }
  193081. bPatchset = pIter->bPatchset;
  193082. if( rc==SQLITE_OK ){
  193083. rc = sqlite3changeset_finalize(pIter);
  193084. }else{
  193085. sqlite3changeset_finalize(pIter);
  193086. }
  193087. if( rc==SQLITE_OK ){
  193088. rc = sessionRetryConstraints(db, bPatchset, zTab, &sApply, xConflict, pCtx);
  193089. }
  193090. if( rc==SQLITE_OK ){
  193091. int nFk, notUsed;
  193092. sqlite3_db_status(db, SQLITE_DBSTATUS_DEFERRED_FKS, &nFk, &notUsed, 0);
  193093. if( nFk!=0 ){
  193094. int res = SQLITE_CHANGESET_ABORT;
  193095. sqlite3_changeset_iter sIter;
  193096. memset(&sIter, 0, sizeof(sIter));
  193097. sIter.nCol = nFk;
  193098. res = xConflict(pCtx, SQLITE_CHANGESET_FOREIGN_KEY, &sIter);
  193099. if( res!=SQLITE_CHANGESET_OMIT ){
  193100. rc = SQLITE_CONSTRAINT;
  193101. }
  193102. }
  193103. }
  193104. sqlite3_exec(db, "PRAGMA defer_foreign_keys = 0", 0, 0, 0);
  193105. if( (flags & SQLITE_CHANGESETAPPLY_NOSAVEPOINT)==0 ){
  193106. if( rc==SQLITE_OK ){
  193107. rc = sqlite3_exec(db, "RELEASE changeset_apply", 0, 0, 0);
  193108. }else{
  193109. sqlite3_exec(db, "ROLLBACK TO changeset_apply", 0, 0, 0);
  193110. sqlite3_exec(db, "RELEASE changeset_apply", 0, 0, 0);
  193111. }
  193112. }
  193113. assert( sApply.bRebase || sApply.rebase.nBuf==0 );
  193114. if( rc==SQLITE_OK && bPatchset==0 && sApply.bRebase ){
  193115. *ppRebase = (void*)sApply.rebase.aBuf;
  193116. *pnRebase = sApply.rebase.nBuf;
  193117. sApply.rebase.aBuf = 0;
  193118. }
  193119. sqlite3_finalize(sApply.pInsert);
  193120. sqlite3_finalize(sApply.pDelete);
  193121. sqlite3_finalize(sApply.pUpdate);
  193122. sqlite3_finalize(sApply.pSelect);
  193123. sqlite3_free((char*)sApply.azCol); /* cast works around VC++ bug */
  193124. sqlite3_free((char*)sApply.constraints.aBuf);
  193125. sqlite3_free((char*)sApply.rebase.aBuf);
  193126. sqlite3_mutex_leave(sqlite3_db_mutex(db));
  193127. return rc;
  193128. }
  193129. /*
  193130. ** Apply the changeset passed via pChangeset/nChangeset to the main
  193131. ** database attached to handle "db".
  193132. */
  193133. SQLITE_API int sqlite3changeset_apply_v2(
  193134. sqlite3 *db, /* Apply change to "main" db of this handle */
  193135. int nChangeset, /* Size of changeset in bytes */
  193136. void *pChangeset, /* Changeset blob */
  193137. int(*xFilter)(
  193138. void *pCtx, /* Copy of sixth arg to _apply() */
  193139. const char *zTab /* Table name */
  193140. ),
  193141. int(*xConflict)(
  193142. void *pCtx, /* Copy of sixth arg to _apply() */
  193143. int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
  193144. sqlite3_changeset_iter *p /* Handle describing change and conflict */
  193145. ),
  193146. void *pCtx, /* First argument passed to xConflict */
  193147. void **ppRebase, int *pnRebase,
  193148. int flags
  193149. ){
  193150. sqlite3_changeset_iter *pIter; /* Iterator to skip through changeset */
  193151. int bInverse = !!(flags & SQLITE_CHANGESETAPPLY_INVERT);
  193152. int rc = sessionChangesetStart(&pIter, 0, 0, nChangeset, pChangeset,bInverse);
  193153. if( rc==SQLITE_OK ){
  193154. rc = sessionChangesetApply(
  193155. db, pIter, xFilter, xConflict, pCtx, ppRebase, pnRebase, flags
  193156. );
  193157. }
  193158. return rc;
  193159. }
  193160. /*
  193161. ** Apply the changeset passed via pChangeset/nChangeset to the main database
  193162. ** attached to handle "db". Invoke the supplied conflict handler callback
  193163. ** to resolve any conflicts encountered while applying the change.
  193164. */
  193165. SQLITE_API int sqlite3changeset_apply(
  193166. sqlite3 *db, /* Apply change to "main" db of this handle */
  193167. int nChangeset, /* Size of changeset in bytes */
  193168. void *pChangeset, /* Changeset blob */
  193169. int(*xFilter)(
  193170. void *pCtx, /* Copy of sixth arg to _apply() */
  193171. const char *zTab /* Table name */
  193172. ),
  193173. int(*xConflict)(
  193174. void *pCtx, /* Copy of fifth arg to _apply() */
  193175. int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
  193176. sqlite3_changeset_iter *p /* Handle describing change and conflict */
  193177. ),
  193178. void *pCtx /* First argument passed to xConflict */
  193179. ){
  193180. return sqlite3changeset_apply_v2(
  193181. db, nChangeset, pChangeset, xFilter, xConflict, pCtx, 0, 0, 0
  193182. );
  193183. }
  193184. /*
  193185. ** Apply the changeset passed via xInput/pIn to the main database
  193186. ** attached to handle "db". Invoke the supplied conflict handler callback
  193187. ** to resolve any conflicts encountered while applying the change.
  193188. */
  193189. SQLITE_API int sqlite3changeset_apply_v2_strm(
  193190. sqlite3 *db, /* Apply change to "main" db of this handle */
  193191. int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */
  193192. void *pIn, /* First arg for xInput */
  193193. int(*xFilter)(
  193194. void *pCtx, /* Copy of sixth arg to _apply() */
  193195. const char *zTab /* Table name */
  193196. ),
  193197. int(*xConflict)(
  193198. void *pCtx, /* Copy of sixth arg to _apply() */
  193199. int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
  193200. sqlite3_changeset_iter *p /* Handle describing change and conflict */
  193201. ),
  193202. void *pCtx, /* First argument passed to xConflict */
  193203. void **ppRebase, int *pnRebase,
  193204. int flags
  193205. ){
  193206. sqlite3_changeset_iter *pIter; /* Iterator to skip through changeset */
  193207. int bInverse = !!(flags & SQLITE_CHANGESETAPPLY_INVERT);
  193208. int rc = sessionChangesetStart(&pIter, xInput, pIn, 0, 0, bInverse);
  193209. if( rc==SQLITE_OK ){
  193210. rc = sessionChangesetApply(
  193211. db, pIter, xFilter, xConflict, pCtx, ppRebase, pnRebase, flags
  193212. );
  193213. }
  193214. return rc;
  193215. }
  193216. SQLITE_API int sqlite3changeset_apply_strm(
  193217. sqlite3 *db, /* Apply change to "main" db of this handle */
  193218. int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */
  193219. void *pIn, /* First arg for xInput */
  193220. int(*xFilter)(
  193221. void *pCtx, /* Copy of sixth arg to _apply() */
  193222. const char *zTab /* Table name */
  193223. ),
  193224. int(*xConflict)(
  193225. void *pCtx, /* Copy of sixth arg to _apply() */
  193226. int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
  193227. sqlite3_changeset_iter *p /* Handle describing change and conflict */
  193228. ),
  193229. void *pCtx /* First argument passed to xConflict */
  193230. ){
  193231. return sqlite3changeset_apply_v2_strm(
  193232. db, xInput, pIn, xFilter, xConflict, pCtx, 0, 0, 0
  193233. );
  193234. }
  193235. /*
  193236. ** sqlite3_changegroup handle.
  193237. */
  193238. struct sqlite3_changegroup {
  193239. int rc; /* Error code */
  193240. int bPatch; /* True to accumulate patchsets */
  193241. SessionTable *pList; /* List of tables in current patch */
  193242. };
  193243. /*
  193244. ** This function is called to merge two changes to the same row together as
  193245. ** part of an sqlite3changeset_concat() operation. A new change object is
  193246. ** allocated and a pointer to it stored in *ppNew.
  193247. */
  193248. static int sessionChangeMerge(
  193249. SessionTable *pTab, /* Table structure */
  193250. int bRebase, /* True for a rebase hash-table */
  193251. int bPatchset, /* True for patchsets */
  193252. SessionChange *pExist, /* Existing change */
  193253. int op2, /* Second change operation */
  193254. int bIndirect, /* True if second change is indirect */
  193255. u8 *aRec, /* Second change record */
  193256. int nRec, /* Number of bytes in aRec */
  193257. SessionChange **ppNew /* OUT: Merged change */
  193258. ){
  193259. SessionChange *pNew = 0;
  193260. int rc = SQLITE_OK;
  193261. if( !pExist ){
  193262. pNew = (SessionChange *)sqlite3_malloc64(sizeof(SessionChange) + nRec);
  193263. if( !pNew ){
  193264. return SQLITE_NOMEM;
  193265. }
  193266. memset(pNew, 0, sizeof(SessionChange));
  193267. pNew->op = op2;
  193268. pNew->bIndirect = bIndirect;
  193269. pNew->aRecord = (u8*)&pNew[1];
  193270. if( bIndirect==0 || bRebase==0 ){
  193271. pNew->nRecord = nRec;
  193272. memcpy(pNew->aRecord, aRec, nRec);
  193273. }else{
  193274. int i;
  193275. u8 *pIn = aRec;
  193276. u8 *pOut = pNew->aRecord;
  193277. for(i=0; i<pTab->nCol; i++){
  193278. int nIn = sessionSerialLen(pIn);
  193279. if( *pIn==0 ){
  193280. *pOut++ = 0;
  193281. }else if( pTab->abPK[i]==0 ){
  193282. *pOut++ = 0xFF;
  193283. }else{
  193284. memcpy(pOut, pIn, nIn);
  193285. pOut += nIn;
  193286. }
  193287. pIn += nIn;
  193288. }
  193289. pNew->nRecord = pOut - pNew->aRecord;
  193290. }
  193291. }else if( bRebase ){
  193292. if( pExist->op==SQLITE_DELETE && pExist->bIndirect ){
  193293. *ppNew = pExist;
  193294. }else{
  193295. sqlite3_int64 nByte = nRec + pExist->nRecord + sizeof(SessionChange);
  193296. pNew = (SessionChange*)sqlite3_malloc64(nByte);
  193297. if( pNew==0 ){
  193298. rc = SQLITE_NOMEM;
  193299. }else{
  193300. int i;
  193301. u8 *a1 = pExist->aRecord;
  193302. u8 *a2 = aRec;
  193303. u8 *pOut;
  193304. memset(pNew, 0, nByte);
  193305. pNew->bIndirect = bIndirect || pExist->bIndirect;
  193306. pNew->op = op2;
  193307. pOut = pNew->aRecord = (u8*)&pNew[1];
  193308. for(i=0; i<pTab->nCol; i++){
  193309. int n1 = sessionSerialLen(a1);
  193310. int n2 = sessionSerialLen(a2);
  193311. if( *a1==0xFF || (pTab->abPK[i]==0 && bIndirect) ){
  193312. *pOut++ = 0xFF;
  193313. }else if( *a2==0 ){
  193314. memcpy(pOut, a1, n1);
  193315. pOut += n1;
  193316. }else{
  193317. memcpy(pOut, a2, n2);
  193318. pOut += n2;
  193319. }
  193320. a1 += n1;
  193321. a2 += n2;
  193322. }
  193323. pNew->nRecord = pOut - pNew->aRecord;
  193324. }
  193325. sqlite3_free(pExist);
  193326. }
  193327. }else{
  193328. int op1 = pExist->op;
  193329. /*
  193330. ** op1=INSERT, op2=INSERT -> Unsupported. Discard op2.
  193331. ** op1=INSERT, op2=UPDATE -> INSERT.
  193332. ** op1=INSERT, op2=DELETE -> (none)
  193333. **
  193334. ** op1=UPDATE, op2=INSERT -> Unsupported. Discard op2.
  193335. ** op1=UPDATE, op2=UPDATE -> UPDATE.
  193336. ** op1=UPDATE, op2=DELETE -> DELETE.
  193337. **
  193338. ** op1=DELETE, op2=INSERT -> UPDATE.
  193339. ** op1=DELETE, op2=UPDATE -> Unsupported. Discard op2.
  193340. ** op1=DELETE, op2=DELETE -> Unsupported. Discard op2.
  193341. */
  193342. if( (op1==SQLITE_INSERT && op2==SQLITE_INSERT)
  193343. || (op1==SQLITE_UPDATE && op2==SQLITE_INSERT)
  193344. || (op1==SQLITE_DELETE && op2==SQLITE_UPDATE)
  193345. || (op1==SQLITE_DELETE && op2==SQLITE_DELETE)
  193346. ){
  193347. pNew = pExist;
  193348. }else if( op1==SQLITE_INSERT && op2==SQLITE_DELETE ){
  193349. sqlite3_free(pExist);
  193350. assert( pNew==0 );
  193351. }else{
  193352. u8 *aExist = pExist->aRecord;
  193353. sqlite3_int64 nByte;
  193354. u8 *aCsr;
  193355. /* Allocate a new SessionChange object. Ensure that the aRecord[]
  193356. ** buffer of the new object is large enough to hold any record that
  193357. ** may be generated by combining the input records. */
  193358. nByte = sizeof(SessionChange) + pExist->nRecord + nRec;
  193359. pNew = (SessionChange *)sqlite3_malloc64(nByte);
  193360. if( !pNew ){
  193361. sqlite3_free(pExist);
  193362. return SQLITE_NOMEM;
  193363. }
  193364. memset(pNew, 0, sizeof(SessionChange));
  193365. pNew->bIndirect = (bIndirect && pExist->bIndirect);
  193366. aCsr = pNew->aRecord = (u8 *)&pNew[1];
  193367. if( op1==SQLITE_INSERT ){ /* INSERT + UPDATE */
  193368. u8 *a1 = aRec;
  193369. assert( op2==SQLITE_UPDATE );
  193370. pNew->op = SQLITE_INSERT;
  193371. if( bPatchset==0 ) sessionSkipRecord(&a1, pTab->nCol);
  193372. sessionMergeRecord(&aCsr, pTab->nCol, aExist, a1);
  193373. }else if( op1==SQLITE_DELETE ){ /* DELETE + INSERT */
  193374. assert( op2==SQLITE_INSERT );
  193375. pNew->op = SQLITE_UPDATE;
  193376. if( bPatchset ){
  193377. memcpy(aCsr, aRec, nRec);
  193378. aCsr += nRec;
  193379. }else{
  193380. if( 0==sessionMergeUpdate(&aCsr, pTab, bPatchset, aExist, 0,aRec,0) ){
  193381. sqlite3_free(pNew);
  193382. pNew = 0;
  193383. }
  193384. }
  193385. }else if( op2==SQLITE_UPDATE ){ /* UPDATE + UPDATE */
  193386. u8 *a1 = aExist;
  193387. u8 *a2 = aRec;
  193388. assert( op1==SQLITE_UPDATE );
  193389. if( bPatchset==0 ){
  193390. sessionSkipRecord(&a1, pTab->nCol);
  193391. sessionSkipRecord(&a2, pTab->nCol);
  193392. }
  193393. pNew->op = SQLITE_UPDATE;
  193394. if( 0==sessionMergeUpdate(&aCsr, pTab, bPatchset, aRec, aExist,a1,a2) ){
  193395. sqlite3_free(pNew);
  193396. pNew = 0;
  193397. }
  193398. }else{ /* UPDATE + DELETE */
  193399. assert( op1==SQLITE_UPDATE && op2==SQLITE_DELETE );
  193400. pNew->op = SQLITE_DELETE;
  193401. if( bPatchset ){
  193402. memcpy(aCsr, aRec, nRec);
  193403. aCsr += nRec;
  193404. }else{
  193405. sessionMergeRecord(&aCsr, pTab->nCol, aRec, aExist);
  193406. }
  193407. }
  193408. if( pNew ){
  193409. pNew->nRecord = (int)(aCsr - pNew->aRecord);
  193410. }
  193411. sqlite3_free(pExist);
  193412. }
  193413. }
  193414. *ppNew = pNew;
  193415. return rc;
  193416. }
  193417. /*
  193418. ** Add all changes in the changeset traversed by the iterator passed as
  193419. ** the first argument to the changegroup hash tables.
  193420. */
  193421. static int sessionChangesetToHash(
  193422. sqlite3_changeset_iter *pIter, /* Iterator to read from */
  193423. sqlite3_changegroup *pGrp, /* Changegroup object to add changeset to */
  193424. int bRebase /* True if hash table is for rebasing */
  193425. ){
  193426. u8 *aRec;
  193427. int nRec;
  193428. int rc = SQLITE_OK;
  193429. SessionTable *pTab = 0;
  193430. while( SQLITE_ROW==sessionChangesetNext(pIter, &aRec, &nRec, 0) ){
  193431. const char *zNew;
  193432. int nCol;
  193433. int op;
  193434. int iHash;
  193435. int bIndirect;
  193436. SessionChange *pChange;
  193437. SessionChange *pExist = 0;
  193438. SessionChange **pp;
  193439. if( pGrp->pList==0 ){
  193440. pGrp->bPatch = pIter->bPatchset;
  193441. }else if( pIter->bPatchset!=pGrp->bPatch ){
  193442. rc = SQLITE_ERROR;
  193443. break;
  193444. }
  193445. sqlite3changeset_op(pIter, &zNew, &nCol, &op, &bIndirect);
  193446. if( !pTab || sqlite3_stricmp(zNew, pTab->zName) ){
  193447. /* Search the list for a matching table */
  193448. int nNew = (int)strlen(zNew);
  193449. u8 *abPK;
  193450. sqlite3changeset_pk(pIter, &abPK, 0);
  193451. for(pTab = pGrp->pList; pTab; pTab=pTab->pNext){
  193452. if( 0==sqlite3_strnicmp(pTab->zName, zNew, nNew+1) ) break;
  193453. }
  193454. if( !pTab ){
  193455. SessionTable **ppTab;
  193456. pTab = sqlite3_malloc64(sizeof(SessionTable) + nCol + nNew+1);
  193457. if( !pTab ){
  193458. rc = SQLITE_NOMEM;
  193459. break;
  193460. }
  193461. memset(pTab, 0, sizeof(SessionTable));
  193462. pTab->nCol = nCol;
  193463. pTab->abPK = (u8*)&pTab[1];
  193464. memcpy(pTab->abPK, abPK, nCol);
  193465. pTab->zName = (char*)&pTab->abPK[nCol];
  193466. memcpy(pTab->zName, zNew, nNew+1);
  193467. /* The new object must be linked on to the end of the list, not
  193468. ** simply added to the start of it. This is to ensure that the
  193469. ** tables within the output of sqlite3changegroup_output() are in
  193470. ** the right order. */
  193471. for(ppTab=&pGrp->pList; *ppTab; ppTab=&(*ppTab)->pNext);
  193472. *ppTab = pTab;
  193473. }else if( pTab->nCol!=nCol || memcmp(pTab->abPK, abPK, nCol) ){
  193474. rc = SQLITE_SCHEMA;
  193475. break;
  193476. }
  193477. }
  193478. if( sessionGrowHash(pIter->bPatchset, pTab) ){
  193479. rc = SQLITE_NOMEM;
  193480. break;
  193481. }
  193482. iHash = sessionChangeHash(
  193483. pTab, (pIter->bPatchset && op==SQLITE_DELETE), aRec, pTab->nChange
  193484. );
  193485. /* Search for existing entry. If found, remove it from the hash table.
  193486. ** Code below may link it back in.
  193487. */
  193488. for(pp=&pTab->apChange[iHash]; *pp; pp=&(*pp)->pNext){
  193489. int bPkOnly1 = 0;
  193490. int bPkOnly2 = 0;
  193491. if( pIter->bPatchset ){
  193492. bPkOnly1 = (*pp)->op==SQLITE_DELETE;
  193493. bPkOnly2 = op==SQLITE_DELETE;
  193494. }
  193495. if( sessionChangeEqual(pTab, bPkOnly1, (*pp)->aRecord, bPkOnly2, aRec) ){
  193496. pExist = *pp;
  193497. *pp = (*pp)->pNext;
  193498. pTab->nEntry--;
  193499. break;
  193500. }
  193501. }
  193502. rc = sessionChangeMerge(pTab, bRebase,
  193503. pIter->bPatchset, pExist, op, bIndirect, aRec, nRec, &pChange
  193504. );
  193505. if( rc ) break;
  193506. if( pChange ){
  193507. pChange->pNext = pTab->apChange[iHash];
  193508. pTab->apChange[iHash] = pChange;
  193509. pTab->nEntry++;
  193510. }
  193511. }
  193512. if( rc==SQLITE_OK ) rc = pIter->rc;
  193513. return rc;
  193514. }
  193515. /*
  193516. ** Serialize a changeset (or patchset) based on all changesets (or patchsets)
  193517. ** added to the changegroup object passed as the first argument.
  193518. **
  193519. ** If xOutput is not NULL, then the changeset/patchset is returned to the
  193520. ** user via one or more calls to xOutput, as with the other streaming
  193521. ** interfaces.
  193522. **
  193523. ** Or, if xOutput is NULL, then (*ppOut) is populated with a pointer to a
  193524. ** buffer containing the output changeset before this function returns. In
  193525. ** this case (*pnOut) is set to the size of the output buffer in bytes. It
  193526. ** is the responsibility of the caller to free the output buffer using
  193527. ** sqlite3_free() when it is no longer required.
  193528. **
  193529. ** If successful, SQLITE_OK is returned. Or, if an error occurs, an SQLite
  193530. ** error code. If an error occurs and xOutput is NULL, (*ppOut) and (*pnOut)
  193531. ** are both set to 0 before returning.
  193532. */
  193533. static int sessionChangegroupOutput(
  193534. sqlite3_changegroup *pGrp,
  193535. int (*xOutput)(void *pOut, const void *pData, int nData),
  193536. void *pOut,
  193537. int *pnOut,
  193538. void **ppOut
  193539. ){
  193540. int rc = SQLITE_OK;
  193541. SessionBuffer buf = {0, 0, 0};
  193542. SessionTable *pTab;
  193543. assert( xOutput==0 || (ppOut==0 && pnOut==0) );
  193544. /* Create the serialized output changeset based on the contents of the
  193545. ** hash tables attached to the SessionTable objects in list p->pList.
  193546. */
  193547. for(pTab=pGrp->pList; rc==SQLITE_OK && pTab; pTab=pTab->pNext){
  193548. int i;
  193549. if( pTab->nEntry==0 ) continue;
  193550. sessionAppendTableHdr(&buf, pGrp->bPatch, pTab, &rc);
  193551. for(i=0; i<pTab->nChange; i++){
  193552. SessionChange *p;
  193553. for(p=pTab->apChange[i]; p; p=p->pNext){
  193554. sessionAppendByte(&buf, p->op, &rc);
  193555. sessionAppendByte(&buf, p->bIndirect, &rc);
  193556. sessionAppendBlob(&buf, p->aRecord, p->nRecord, &rc);
  193557. if( rc==SQLITE_OK && xOutput && buf.nBuf>=sessions_strm_chunk_size ){
  193558. rc = xOutput(pOut, buf.aBuf, buf.nBuf);
  193559. buf.nBuf = 0;
  193560. }
  193561. }
  193562. }
  193563. }
  193564. if( rc==SQLITE_OK ){
  193565. if( xOutput ){
  193566. if( buf.nBuf>0 ) rc = xOutput(pOut, buf.aBuf, buf.nBuf);
  193567. }else{
  193568. *ppOut = buf.aBuf;
  193569. *pnOut = buf.nBuf;
  193570. buf.aBuf = 0;
  193571. }
  193572. }
  193573. sqlite3_free(buf.aBuf);
  193574. return rc;
  193575. }
  193576. /*
  193577. ** Allocate a new, empty, sqlite3_changegroup.
  193578. */
  193579. SQLITE_API int sqlite3changegroup_new(sqlite3_changegroup **pp){
  193580. int rc = SQLITE_OK; /* Return code */
  193581. sqlite3_changegroup *p; /* New object */
  193582. p = (sqlite3_changegroup*)sqlite3_malloc(sizeof(sqlite3_changegroup));
  193583. if( p==0 ){
  193584. rc = SQLITE_NOMEM;
  193585. }else{
  193586. memset(p, 0, sizeof(sqlite3_changegroup));
  193587. }
  193588. *pp = p;
  193589. return rc;
  193590. }
  193591. /*
  193592. ** Add the changeset currently stored in buffer pData, size nData bytes,
  193593. ** to changeset-group p.
  193594. */
  193595. SQLITE_API int sqlite3changegroup_add(sqlite3_changegroup *pGrp, int nData, void *pData){
  193596. sqlite3_changeset_iter *pIter; /* Iterator opened on pData/nData */
  193597. int rc; /* Return code */
  193598. rc = sqlite3changeset_start(&pIter, nData, pData);
  193599. if( rc==SQLITE_OK ){
  193600. rc = sessionChangesetToHash(pIter, pGrp, 0);
  193601. }
  193602. sqlite3changeset_finalize(pIter);
  193603. return rc;
  193604. }
  193605. /*
  193606. ** Obtain a buffer containing a changeset representing the concatenation
  193607. ** of all changesets added to the group so far.
  193608. */
  193609. SQLITE_API int sqlite3changegroup_output(
  193610. sqlite3_changegroup *pGrp,
  193611. int *pnData,
  193612. void **ppData
  193613. ){
  193614. return sessionChangegroupOutput(pGrp, 0, 0, pnData, ppData);
  193615. }
  193616. /*
  193617. ** Streaming versions of changegroup_add().
  193618. */
  193619. SQLITE_API int sqlite3changegroup_add_strm(
  193620. sqlite3_changegroup *pGrp,
  193621. int (*xInput)(void *pIn, void *pData, int *pnData),
  193622. void *pIn
  193623. ){
  193624. sqlite3_changeset_iter *pIter; /* Iterator opened on pData/nData */
  193625. int rc; /* Return code */
  193626. rc = sqlite3changeset_start_strm(&pIter, xInput, pIn);
  193627. if( rc==SQLITE_OK ){
  193628. rc = sessionChangesetToHash(pIter, pGrp, 0);
  193629. }
  193630. sqlite3changeset_finalize(pIter);
  193631. return rc;
  193632. }
  193633. /*
  193634. ** Streaming versions of changegroup_output().
  193635. */
  193636. SQLITE_API int sqlite3changegroup_output_strm(
  193637. sqlite3_changegroup *pGrp,
  193638. int (*xOutput)(void *pOut, const void *pData, int nData),
  193639. void *pOut
  193640. ){
  193641. return sessionChangegroupOutput(pGrp, xOutput, pOut, 0, 0);
  193642. }
  193643. /*
  193644. ** Delete a changegroup object.
  193645. */
  193646. SQLITE_API void sqlite3changegroup_delete(sqlite3_changegroup *pGrp){
  193647. if( pGrp ){
  193648. sessionDeleteTable(pGrp->pList);
  193649. sqlite3_free(pGrp);
  193650. }
  193651. }
  193652. /*
  193653. ** Combine two changesets together.
  193654. */
  193655. SQLITE_API int sqlite3changeset_concat(
  193656. int nLeft, /* Number of bytes in lhs input */
  193657. void *pLeft, /* Lhs input changeset */
  193658. int nRight /* Number of bytes in rhs input */,
  193659. void *pRight, /* Rhs input changeset */
  193660. int *pnOut, /* OUT: Number of bytes in output changeset */
  193661. void **ppOut /* OUT: changeset (left <concat> right) */
  193662. ){
  193663. sqlite3_changegroup *pGrp;
  193664. int rc;
  193665. rc = sqlite3changegroup_new(&pGrp);
  193666. if( rc==SQLITE_OK ){
  193667. rc = sqlite3changegroup_add(pGrp, nLeft, pLeft);
  193668. }
  193669. if( rc==SQLITE_OK ){
  193670. rc = sqlite3changegroup_add(pGrp, nRight, pRight);
  193671. }
  193672. if( rc==SQLITE_OK ){
  193673. rc = sqlite3changegroup_output(pGrp, pnOut, ppOut);
  193674. }
  193675. sqlite3changegroup_delete(pGrp);
  193676. return rc;
  193677. }
  193678. /*
  193679. ** Streaming version of sqlite3changeset_concat().
  193680. */
  193681. SQLITE_API int sqlite3changeset_concat_strm(
  193682. int (*xInputA)(void *pIn, void *pData, int *pnData),
  193683. void *pInA,
  193684. int (*xInputB)(void *pIn, void *pData, int *pnData),
  193685. void *pInB,
  193686. int (*xOutput)(void *pOut, const void *pData, int nData),
  193687. void *pOut
  193688. ){
  193689. sqlite3_changegroup *pGrp;
  193690. int rc;
  193691. rc = sqlite3changegroup_new(&pGrp);
  193692. if( rc==SQLITE_OK ){
  193693. rc = sqlite3changegroup_add_strm(pGrp, xInputA, pInA);
  193694. }
  193695. if( rc==SQLITE_OK ){
  193696. rc = sqlite3changegroup_add_strm(pGrp, xInputB, pInB);
  193697. }
  193698. if( rc==SQLITE_OK ){
  193699. rc = sqlite3changegroup_output_strm(pGrp, xOutput, pOut);
  193700. }
  193701. sqlite3changegroup_delete(pGrp);
  193702. return rc;
  193703. }
  193704. /*
  193705. ** Changeset rebaser handle.
  193706. */
  193707. struct sqlite3_rebaser {
  193708. sqlite3_changegroup grp; /* Hash table */
  193709. };
  193710. /*
  193711. ** Buffers a1 and a2 must both contain a sessions module record nCol
  193712. ** fields in size. This function appends an nCol sessions module
  193713. ** record to buffer pBuf that is a copy of a1, except that for
  193714. ** each field that is undefined in a1[], swap in the field from a2[].
  193715. */
  193716. static void sessionAppendRecordMerge(
  193717. SessionBuffer *pBuf, /* Buffer to append to */
  193718. int nCol, /* Number of columns in each record */
  193719. u8 *a1, int n1, /* Record 1 */
  193720. u8 *a2, int n2, /* Record 2 */
  193721. int *pRc /* IN/OUT: error code */
  193722. ){
  193723. sessionBufferGrow(pBuf, n1+n2, pRc);
  193724. if( *pRc==SQLITE_OK ){
  193725. int i;
  193726. u8 *pOut = &pBuf->aBuf[pBuf->nBuf];
  193727. for(i=0; i<nCol; i++){
  193728. int nn1 = sessionSerialLen(a1);
  193729. int nn2 = sessionSerialLen(a2);
  193730. if( *a1==0 || *a1==0xFF ){
  193731. memcpy(pOut, a2, nn2);
  193732. pOut += nn2;
  193733. }else{
  193734. memcpy(pOut, a1, nn1);
  193735. pOut += nn1;
  193736. }
  193737. a1 += nn1;
  193738. a2 += nn2;
  193739. }
  193740. pBuf->nBuf = pOut-pBuf->aBuf;
  193741. assert( pBuf->nBuf<=pBuf->nAlloc );
  193742. }
  193743. }
  193744. /*
  193745. ** This function is called when rebasing a local UPDATE change against one
  193746. ** or more remote UPDATE changes. The aRec/nRec buffer contains the current
  193747. ** old.* and new.* records for the change. The rebase buffer (a single
  193748. ** record) is in aChange/nChange. The rebased change is appended to buffer
  193749. ** pBuf.
  193750. **
  193751. ** Rebasing the UPDATE involves:
  193752. **
  193753. ** * Removing any changes to fields for which the corresponding field
  193754. ** in the rebase buffer is set to "replaced" (type 0xFF). If this
  193755. ** means the UPDATE change updates no fields, nothing is appended
  193756. ** to the output buffer.
  193757. **
  193758. ** * For each field modified by the local change for which the
  193759. ** corresponding field in the rebase buffer is not "undefined" (0x00)
  193760. ** or "replaced" (0xFF), the old.* value is replaced by the value
  193761. ** in the rebase buffer.
  193762. */
  193763. static void sessionAppendPartialUpdate(
  193764. SessionBuffer *pBuf, /* Append record here */
  193765. sqlite3_changeset_iter *pIter, /* Iterator pointed at local change */
  193766. u8 *aRec, int nRec, /* Local change */
  193767. u8 *aChange, int nChange, /* Record to rebase against */
  193768. int *pRc /* IN/OUT: Return Code */
  193769. ){
  193770. sessionBufferGrow(pBuf, 2+nRec+nChange, pRc);
  193771. if( *pRc==SQLITE_OK ){
  193772. int bData = 0;
  193773. u8 *pOut = &pBuf->aBuf[pBuf->nBuf];
  193774. int i;
  193775. u8 *a1 = aRec;
  193776. u8 *a2 = aChange;
  193777. *pOut++ = SQLITE_UPDATE;
  193778. *pOut++ = pIter->bIndirect;
  193779. for(i=0; i<pIter->nCol; i++){
  193780. int n1 = sessionSerialLen(a1);
  193781. int n2 = sessionSerialLen(a2);
  193782. if( pIter->abPK[i] || a2[0]==0 ){
  193783. if( !pIter->abPK[i] ) bData = 1;
  193784. memcpy(pOut, a1, n1);
  193785. pOut += n1;
  193786. }else if( a2[0]!=0xFF ){
  193787. bData = 1;
  193788. memcpy(pOut, a2, n2);
  193789. pOut += n2;
  193790. }else{
  193791. *pOut++ = '\0';
  193792. }
  193793. a1 += n1;
  193794. a2 += n2;
  193795. }
  193796. if( bData ){
  193797. a2 = aChange;
  193798. for(i=0; i<pIter->nCol; i++){
  193799. int n1 = sessionSerialLen(a1);
  193800. int n2 = sessionSerialLen(a2);
  193801. if( pIter->abPK[i] || a2[0]!=0xFF ){
  193802. memcpy(pOut, a1, n1);
  193803. pOut += n1;
  193804. }else{
  193805. *pOut++ = '\0';
  193806. }
  193807. a1 += n1;
  193808. a2 += n2;
  193809. }
  193810. pBuf->nBuf = (pOut - pBuf->aBuf);
  193811. }
  193812. }
  193813. }
  193814. /*
  193815. ** pIter is configured to iterate through a changeset. This function rebases
  193816. ** that changeset according to the current configuration of the rebaser
  193817. ** object passed as the first argument. If no error occurs and argument xOutput
  193818. ** is not NULL, then the changeset is returned to the caller by invoking
  193819. ** xOutput zero or more times and SQLITE_OK returned. Or, if xOutput is NULL,
  193820. ** then (*ppOut) is set to point to a buffer containing the rebased changeset
  193821. ** before this function returns. In this case (*pnOut) is set to the size of
  193822. ** the buffer in bytes. It is the responsibility of the caller to eventually
  193823. ** free the (*ppOut) buffer using sqlite3_free().
  193824. **
  193825. ** If an error occurs, an SQLite error code is returned. If ppOut and
  193826. ** pnOut are not NULL, then the two output parameters are set to 0 before
  193827. ** returning.
  193828. */
  193829. static int sessionRebase(
  193830. sqlite3_rebaser *p, /* Rebaser hash table */
  193831. sqlite3_changeset_iter *pIter, /* Input data */
  193832. int (*xOutput)(void *pOut, const void *pData, int nData),
  193833. void *pOut, /* Context for xOutput callback */
  193834. int *pnOut, /* OUT: Number of bytes in output changeset */
  193835. void **ppOut /* OUT: Inverse of pChangeset */
  193836. ){
  193837. int rc = SQLITE_OK;
  193838. u8 *aRec = 0;
  193839. int nRec = 0;
  193840. int bNew = 0;
  193841. SessionTable *pTab = 0;
  193842. SessionBuffer sOut = {0,0,0};
  193843. while( SQLITE_ROW==sessionChangesetNext(pIter, &aRec, &nRec, &bNew) ){
  193844. SessionChange *pChange = 0;
  193845. int bDone = 0;
  193846. if( bNew ){
  193847. const char *zTab = pIter->zTab;
  193848. for(pTab=p->grp.pList; pTab; pTab=pTab->pNext){
  193849. if( 0==sqlite3_stricmp(pTab->zName, zTab) ) break;
  193850. }
  193851. bNew = 0;
  193852. /* A patchset may not be rebased */
  193853. if( pIter->bPatchset ){
  193854. rc = SQLITE_ERROR;
  193855. }
  193856. /* Append a table header to the output for this new table */
  193857. sessionAppendByte(&sOut, pIter->bPatchset ? 'P' : 'T', &rc);
  193858. sessionAppendVarint(&sOut, pIter->nCol, &rc);
  193859. sessionAppendBlob(&sOut, pIter->abPK, pIter->nCol, &rc);
  193860. sessionAppendBlob(&sOut,(u8*)pIter->zTab,(int)strlen(pIter->zTab)+1,&rc);
  193861. }
  193862. if( pTab && rc==SQLITE_OK ){
  193863. int iHash = sessionChangeHash(pTab, 0, aRec, pTab->nChange);
  193864. for(pChange=pTab->apChange[iHash]; pChange; pChange=pChange->pNext){
  193865. if( sessionChangeEqual(pTab, 0, aRec, 0, pChange->aRecord) ){
  193866. break;
  193867. }
  193868. }
  193869. }
  193870. if( pChange ){
  193871. assert( pChange->op==SQLITE_DELETE || pChange->op==SQLITE_INSERT );
  193872. switch( pIter->op ){
  193873. case SQLITE_INSERT:
  193874. if( pChange->op==SQLITE_INSERT ){
  193875. bDone = 1;
  193876. if( pChange->bIndirect==0 ){
  193877. sessionAppendByte(&sOut, SQLITE_UPDATE, &rc);
  193878. sessionAppendByte(&sOut, pIter->bIndirect, &rc);
  193879. sessionAppendBlob(&sOut, pChange->aRecord, pChange->nRecord, &rc);
  193880. sessionAppendBlob(&sOut, aRec, nRec, &rc);
  193881. }
  193882. }
  193883. break;
  193884. case SQLITE_UPDATE:
  193885. bDone = 1;
  193886. if( pChange->op==SQLITE_DELETE ){
  193887. if( pChange->bIndirect==0 ){
  193888. u8 *pCsr = aRec;
  193889. sessionSkipRecord(&pCsr, pIter->nCol);
  193890. sessionAppendByte(&sOut, SQLITE_INSERT, &rc);
  193891. sessionAppendByte(&sOut, pIter->bIndirect, &rc);
  193892. sessionAppendRecordMerge(&sOut, pIter->nCol,
  193893. pCsr, nRec-(pCsr-aRec),
  193894. pChange->aRecord, pChange->nRecord, &rc
  193895. );
  193896. }
  193897. }else{
  193898. sessionAppendPartialUpdate(&sOut, pIter,
  193899. aRec, nRec, pChange->aRecord, pChange->nRecord, &rc
  193900. );
  193901. }
  193902. break;
  193903. default:
  193904. assert( pIter->op==SQLITE_DELETE );
  193905. bDone = 1;
  193906. if( pChange->op==SQLITE_INSERT ){
  193907. sessionAppendByte(&sOut, SQLITE_DELETE, &rc);
  193908. sessionAppendByte(&sOut, pIter->bIndirect, &rc);
  193909. sessionAppendRecordMerge(&sOut, pIter->nCol,
  193910. pChange->aRecord, pChange->nRecord, aRec, nRec, &rc
  193911. );
  193912. }
  193913. break;
  193914. }
  193915. }
  193916. if( bDone==0 ){
  193917. sessionAppendByte(&sOut, pIter->op, &rc);
  193918. sessionAppendByte(&sOut, pIter->bIndirect, &rc);
  193919. sessionAppendBlob(&sOut, aRec, nRec, &rc);
  193920. }
  193921. if( rc==SQLITE_OK && xOutput && sOut.nBuf>sessions_strm_chunk_size ){
  193922. rc = xOutput(pOut, sOut.aBuf, sOut.nBuf);
  193923. sOut.nBuf = 0;
  193924. }
  193925. if( rc ) break;
  193926. }
  193927. if( rc!=SQLITE_OK ){
  193928. sqlite3_free(sOut.aBuf);
  193929. memset(&sOut, 0, sizeof(sOut));
  193930. }
  193931. if( rc==SQLITE_OK ){
  193932. if( xOutput ){
  193933. if( sOut.nBuf>0 ){
  193934. rc = xOutput(pOut, sOut.aBuf, sOut.nBuf);
  193935. }
  193936. }else{
  193937. *ppOut = (void*)sOut.aBuf;
  193938. *pnOut = sOut.nBuf;
  193939. sOut.aBuf = 0;
  193940. }
  193941. }
  193942. sqlite3_free(sOut.aBuf);
  193943. return rc;
  193944. }
  193945. /*
  193946. ** Create a new rebaser object.
  193947. */
  193948. SQLITE_API int sqlite3rebaser_create(sqlite3_rebaser **ppNew){
  193949. int rc = SQLITE_OK;
  193950. sqlite3_rebaser *pNew;
  193951. pNew = sqlite3_malloc(sizeof(sqlite3_rebaser));
  193952. if( pNew==0 ){
  193953. rc = SQLITE_NOMEM;
  193954. }else{
  193955. memset(pNew, 0, sizeof(sqlite3_rebaser));
  193956. }
  193957. *ppNew = pNew;
  193958. return rc;
  193959. }
  193960. /*
  193961. ** Call this one or more times to configure a rebaser.
  193962. */
  193963. SQLITE_API int sqlite3rebaser_configure(
  193964. sqlite3_rebaser *p,
  193965. int nRebase, const void *pRebase
  193966. ){
  193967. sqlite3_changeset_iter *pIter = 0; /* Iterator opened on pData/nData */
  193968. int rc; /* Return code */
  193969. rc = sqlite3changeset_start(&pIter, nRebase, (void*)pRebase);
  193970. if( rc==SQLITE_OK ){
  193971. rc = sessionChangesetToHash(pIter, &p->grp, 1);
  193972. }
  193973. sqlite3changeset_finalize(pIter);
  193974. return rc;
  193975. }
  193976. /*
  193977. ** Rebase a changeset according to current rebaser configuration
  193978. */
  193979. SQLITE_API int sqlite3rebaser_rebase(
  193980. sqlite3_rebaser *p,
  193981. int nIn, const void *pIn,
  193982. int *pnOut, void **ppOut
  193983. ){
  193984. sqlite3_changeset_iter *pIter = 0; /* Iterator to skip through input */
  193985. int rc = sqlite3changeset_start(&pIter, nIn, (void*)pIn);
  193986. if( rc==SQLITE_OK ){
  193987. rc = sessionRebase(p, pIter, 0, 0, pnOut, ppOut);
  193988. sqlite3changeset_finalize(pIter);
  193989. }
  193990. return rc;
  193991. }
  193992. /*
  193993. ** Rebase a changeset according to current rebaser configuration
  193994. */
  193995. SQLITE_API int sqlite3rebaser_rebase_strm(
  193996. sqlite3_rebaser *p,
  193997. int (*xInput)(void *pIn, void *pData, int *pnData),
  193998. void *pIn,
  193999. int (*xOutput)(void *pOut, const void *pData, int nData),
  194000. void *pOut
  194001. ){
  194002. sqlite3_changeset_iter *pIter = 0; /* Iterator to skip through input */
  194003. int rc = sqlite3changeset_start_strm(&pIter, xInput, pIn);
  194004. if( rc==SQLITE_OK ){
  194005. rc = sessionRebase(p, pIter, xOutput, pOut, 0, 0);
  194006. sqlite3changeset_finalize(pIter);
  194007. }
  194008. return rc;
  194009. }
  194010. /*
  194011. ** Destroy a rebaser object
  194012. */
  194013. SQLITE_API void sqlite3rebaser_delete(sqlite3_rebaser *p){
  194014. if( p ){
  194015. sessionDeleteTable(p->grp.pList);
  194016. sqlite3_free(p);
  194017. }
  194018. }
  194019. /*
  194020. ** Global configuration
  194021. */
  194022. SQLITE_API int sqlite3session_config(int op, void *pArg){
  194023. int rc = SQLITE_OK;
  194024. switch( op ){
  194025. case SQLITE_SESSION_CONFIG_STRMSIZE: {
  194026. int *pInt = (int*)pArg;
  194027. if( *pInt>0 ){
  194028. sessions_strm_chunk_size = *pInt;
  194029. }
  194030. *pInt = sessions_strm_chunk_size;
  194031. break;
  194032. }
  194033. default:
  194034. rc = SQLITE_MISUSE;
  194035. break;
  194036. }
  194037. return rc;
  194038. }
  194039. #endif /* SQLITE_ENABLE_SESSION && SQLITE_ENABLE_PREUPDATE_HOOK */
  194040. /************** End of sqlite3session.c **************************************/
  194041. /************** Begin file fts5.c ********************************************/
  194042. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS5)
  194043. #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
  194044. # define NDEBUG 1
  194045. #endif
  194046. #if defined(NDEBUG) && defined(SQLITE_DEBUG)
  194047. # undef NDEBUG
  194048. #endif
  194049. /*
  194050. ** 2014 May 31
  194051. **
  194052. ** The author disclaims copyright to this source code. In place of
  194053. ** a legal notice, here is a blessing:
  194054. **
  194055. ** May you do good and not evil.
  194056. ** May you find forgiveness for yourself and forgive others.
  194057. ** May you share freely, never taking more than you give.
  194058. **
  194059. ******************************************************************************
  194060. **
  194061. ** Interfaces to extend FTS5. Using the interfaces defined in this file,
  194062. ** FTS5 may be extended with:
  194063. **
  194064. ** * custom tokenizers, and
  194065. ** * custom auxiliary functions.
  194066. */
  194067. #ifndef _FTS5_H
  194068. #define _FTS5_H
  194069. /* #include "sqlite3.h" */
  194070. #if 0
  194071. extern "C" {
  194072. #endif
  194073. /*************************************************************************
  194074. ** CUSTOM AUXILIARY FUNCTIONS
  194075. **
  194076. ** Virtual table implementations may overload SQL functions by implementing
  194077. ** the sqlite3_module.xFindFunction() method.
  194078. */
  194079. typedef struct Fts5ExtensionApi Fts5ExtensionApi;
  194080. typedef struct Fts5Context Fts5Context;
  194081. typedef struct Fts5PhraseIter Fts5PhraseIter;
  194082. typedef void (*fts5_extension_function)(
  194083. const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
  194084. Fts5Context *pFts, /* First arg to pass to pApi functions */
  194085. sqlite3_context *pCtx, /* Context for returning result/error */
  194086. int nVal, /* Number of values in apVal[] array */
  194087. sqlite3_value **apVal /* Array of trailing arguments */
  194088. );
  194089. struct Fts5PhraseIter {
  194090. const unsigned char *a;
  194091. const unsigned char *b;
  194092. };
  194093. /*
  194094. ** EXTENSION API FUNCTIONS
  194095. **
  194096. ** xUserData(pFts):
  194097. ** Return a copy of the context pointer the extension function was
  194098. ** registered with.
  194099. **
  194100. ** xColumnTotalSize(pFts, iCol, pnToken):
  194101. ** If parameter iCol is less than zero, set output variable *pnToken
  194102. ** to the total number of tokens in the FTS5 table. Or, if iCol is
  194103. ** non-negative but less than the number of columns in the table, return
  194104. ** the total number of tokens in column iCol, considering all rows in
  194105. ** the FTS5 table.
  194106. **
  194107. ** If parameter iCol is greater than or equal to the number of columns
  194108. ** in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
  194109. ** an OOM condition or IO error), an appropriate SQLite error code is
  194110. ** returned.
  194111. **
  194112. ** xColumnCount(pFts):
  194113. ** Return the number of columns in the table.
  194114. **
  194115. ** xColumnSize(pFts, iCol, pnToken):
  194116. ** If parameter iCol is less than zero, set output variable *pnToken
  194117. ** to the total number of tokens in the current row. Or, if iCol is
  194118. ** non-negative but less than the number of columns in the table, set
  194119. ** *pnToken to the number of tokens in column iCol of the current row.
  194120. **
  194121. ** If parameter iCol is greater than or equal to the number of columns
  194122. ** in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
  194123. ** an OOM condition or IO error), an appropriate SQLite error code is
  194124. ** returned.
  194125. **
  194126. ** This function may be quite inefficient if used with an FTS5 table
  194127. ** created with the "columnsize=0" option.
  194128. **
  194129. ** xColumnText:
  194130. ** This function attempts to retrieve the text of column iCol of the
  194131. ** current document. If successful, (*pz) is set to point to a buffer
  194132. ** containing the text in utf-8 encoding, (*pn) is set to the size in bytes
  194133. ** (not characters) of the buffer and SQLITE_OK is returned. Otherwise,
  194134. ** if an error occurs, an SQLite error code is returned and the final values
  194135. ** of (*pz) and (*pn) are undefined.
  194136. **
  194137. ** xPhraseCount:
  194138. ** Returns the number of phrases in the current query expression.
  194139. **
  194140. ** xPhraseSize:
  194141. ** Returns the number of tokens in phrase iPhrase of the query. Phrases
  194142. ** are numbered starting from zero.
  194143. **
  194144. ** xInstCount:
  194145. ** Set *pnInst to the total number of occurrences of all phrases within
  194146. ** the query within the current row. Return SQLITE_OK if successful, or
  194147. ** an error code (i.e. SQLITE_NOMEM) if an error occurs.
  194148. **
  194149. ** This API can be quite slow if used with an FTS5 table created with the
  194150. ** "detail=none" or "detail=column" option. If the FTS5 table is created
  194151. ** with either "detail=none" or "detail=column" and "content=" option
  194152. ** (i.e. if it is a contentless table), then this API always returns 0.
  194153. **
  194154. ** xInst:
  194155. ** Query for the details of phrase match iIdx within the current row.
  194156. ** Phrase matches are numbered starting from zero, so the iIdx argument
  194157. ** should be greater than or equal to zero and smaller than the value
  194158. ** output by xInstCount().
  194159. **
  194160. ** Usually, output parameter *piPhrase is set to the phrase number, *piCol
  194161. ** to the column in which it occurs and *piOff the token offset of the
  194162. ** first token of the phrase. Returns SQLITE_OK if successful, or an error
  194163. ** code (i.e. SQLITE_NOMEM) if an error occurs.
  194164. **
  194165. ** This API can be quite slow if used with an FTS5 table created with the
  194166. ** "detail=none" or "detail=column" option.
  194167. **
  194168. ** xRowid:
  194169. ** Returns the rowid of the current row.
  194170. **
  194171. ** xTokenize:
  194172. ** Tokenize text using the tokenizer belonging to the FTS5 table.
  194173. **
  194174. ** xQueryPhrase(pFts5, iPhrase, pUserData, xCallback):
  194175. ** This API function is used to query the FTS table for phrase iPhrase
  194176. ** of the current query. Specifically, a query equivalent to:
  194177. **
  194178. ** ... FROM ftstable WHERE ftstable MATCH $p ORDER BY rowid
  194179. **
  194180. ** with $p set to a phrase equivalent to the phrase iPhrase of the
  194181. ** current query is executed. Any column filter that applies to
  194182. ** phrase iPhrase of the current query is included in $p. For each
  194183. ** row visited, the callback function passed as the fourth argument
  194184. ** is invoked. The context and API objects passed to the callback
  194185. ** function may be used to access the properties of each matched row.
  194186. ** Invoking Api.xUserData() returns a copy of the pointer passed as
  194187. ** the third argument to pUserData.
  194188. **
  194189. ** If the callback function returns any value other than SQLITE_OK, the
  194190. ** query is abandoned and the xQueryPhrase function returns immediately.
  194191. ** If the returned value is SQLITE_DONE, xQueryPhrase returns SQLITE_OK.
  194192. ** Otherwise, the error code is propagated upwards.
  194193. **
  194194. ** If the query runs to completion without incident, SQLITE_OK is returned.
  194195. ** Or, if some error occurs before the query completes or is aborted by
  194196. ** the callback, an SQLite error code is returned.
  194197. **
  194198. **
  194199. ** xSetAuxdata(pFts5, pAux, xDelete)
  194200. **
  194201. ** Save the pointer passed as the second argument as the extension function's
  194202. ** "auxiliary data". The pointer may then be retrieved by the current or any
  194203. ** future invocation of the same fts5 extension function made as part of
  194204. ** the same MATCH query using the xGetAuxdata() API.
  194205. **
  194206. ** Each extension function is allocated a single auxiliary data slot for
  194207. ** each FTS query (MATCH expression). If the extension function is invoked
  194208. ** more than once for a single FTS query, then all invocations share a
  194209. ** single auxiliary data context.
  194210. **
  194211. ** If there is already an auxiliary data pointer when this function is
  194212. ** invoked, then it is replaced by the new pointer. If an xDelete callback
  194213. ** was specified along with the original pointer, it is invoked at this
  194214. ** point.
  194215. **
  194216. ** The xDelete callback, if one is specified, is also invoked on the
  194217. ** auxiliary data pointer after the FTS5 query has finished.
  194218. **
  194219. ** If an error (e.g. an OOM condition) occurs within this function,
  194220. ** the auxiliary data is set to NULL and an error code returned. If the
  194221. ** xDelete parameter was not NULL, it is invoked on the auxiliary data
  194222. ** pointer before returning.
  194223. **
  194224. **
  194225. ** xGetAuxdata(pFts5, bClear)
  194226. **
  194227. ** Returns the current auxiliary data pointer for the fts5 extension
  194228. ** function. See the xSetAuxdata() method for details.
  194229. **
  194230. ** If the bClear argument is non-zero, then the auxiliary data is cleared
  194231. ** (set to NULL) before this function returns. In this case the xDelete,
  194232. ** if any, is not invoked.
  194233. **
  194234. **
  194235. ** xRowCount(pFts5, pnRow)
  194236. **
  194237. ** This function is used to retrieve the total number of rows in the table.
  194238. ** In other words, the same value that would be returned by:
  194239. **
  194240. ** SELECT count(*) FROM ftstable;
  194241. **
  194242. ** xPhraseFirst()
  194243. ** This function is used, along with type Fts5PhraseIter and the xPhraseNext
  194244. ** method, to iterate through all instances of a single query phrase within
  194245. ** the current row. This is the same information as is accessible via the
  194246. ** xInstCount/xInst APIs. While the xInstCount/xInst APIs are more convenient
  194247. ** to use, this API may be faster under some circumstances. To iterate
  194248. ** through instances of phrase iPhrase, use the following code:
  194249. **
  194250. ** Fts5PhraseIter iter;
  194251. ** int iCol, iOff;
  194252. ** for(pApi->xPhraseFirst(pFts, iPhrase, &iter, &iCol, &iOff);
  194253. ** iCol>=0;
  194254. ** pApi->xPhraseNext(pFts, &iter, &iCol, &iOff)
  194255. ** ){
  194256. ** // An instance of phrase iPhrase at offset iOff of column iCol
  194257. ** }
  194258. **
  194259. ** The Fts5PhraseIter structure is defined above. Applications should not
  194260. ** modify this structure directly - it should only be used as shown above
  194261. ** with the xPhraseFirst() and xPhraseNext() API methods (and by
  194262. ** xPhraseFirstColumn() and xPhraseNextColumn() as illustrated below).
  194263. **
  194264. ** This API can be quite slow if used with an FTS5 table created with the
  194265. ** "detail=none" or "detail=column" option. If the FTS5 table is created
  194266. ** with either "detail=none" or "detail=column" and "content=" option
  194267. ** (i.e. if it is a contentless table), then this API always iterates
  194268. ** through an empty set (all calls to xPhraseFirst() set iCol to -1).
  194269. **
  194270. ** xPhraseNext()
  194271. ** See xPhraseFirst above.
  194272. **
  194273. ** xPhraseFirstColumn()
  194274. ** This function and xPhraseNextColumn() are similar to the xPhraseFirst()
  194275. ** and xPhraseNext() APIs described above. The difference is that instead
  194276. ** of iterating through all instances of a phrase in the current row, these
  194277. ** APIs are used to iterate through the set of columns in the current row
  194278. ** that contain one or more instances of a specified phrase. For example:
  194279. **
  194280. ** Fts5PhraseIter iter;
  194281. ** int iCol;
  194282. ** for(pApi->xPhraseFirstColumn(pFts, iPhrase, &iter, &iCol);
  194283. ** iCol>=0;
  194284. ** pApi->xPhraseNextColumn(pFts, &iter, &iCol)
  194285. ** ){
  194286. ** // Column iCol contains at least one instance of phrase iPhrase
  194287. ** }
  194288. **
  194289. ** This API can be quite slow if used with an FTS5 table created with the
  194290. ** "detail=none" option. If the FTS5 table is created with either
  194291. ** "detail=none" "content=" option (i.e. if it is a contentless table),
  194292. ** then this API always iterates through an empty set (all calls to
  194293. ** xPhraseFirstColumn() set iCol to -1).
  194294. **
  194295. ** The information accessed using this API and its companion
  194296. ** xPhraseFirstColumn() may also be obtained using xPhraseFirst/xPhraseNext
  194297. ** (or xInst/xInstCount). The chief advantage of this API is that it is
  194298. ** significantly more efficient than those alternatives when used with
  194299. ** "detail=column" tables.
  194300. **
  194301. ** xPhraseNextColumn()
  194302. ** See xPhraseFirstColumn above.
  194303. */
  194304. struct Fts5ExtensionApi {
  194305. int iVersion; /* Currently always set to 3 */
  194306. void *(*xUserData)(Fts5Context*);
  194307. int (*xColumnCount)(Fts5Context*);
  194308. int (*xRowCount)(Fts5Context*, sqlite3_int64 *pnRow);
  194309. int (*xColumnTotalSize)(Fts5Context*, int iCol, sqlite3_int64 *pnToken);
  194310. int (*xTokenize)(Fts5Context*,
  194311. const char *pText, int nText, /* Text to tokenize */
  194312. void *pCtx, /* Context passed to xToken() */
  194313. int (*xToken)(void*, int, const char*, int, int, int) /* Callback */
  194314. );
  194315. int (*xPhraseCount)(Fts5Context*);
  194316. int (*xPhraseSize)(Fts5Context*, int iPhrase);
  194317. int (*xInstCount)(Fts5Context*, int *pnInst);
  194318. int (*xInst)(Fts5Context*, int iIdx, int *piPhrase, int *piCol, int *piOff);
  194319. sqlite3_int64 (*xRowid)(Fts5Context*);
  194320. int (*xColumnText)(Fts5Context*, int iCol, const char **pz, int *pn);
  194321. int (*xColumnSize)(Fts5Context*, int iCol, int *pnToken);
  194322. int (*xQueryPhrase)(Fts5Context*, int iPhrase, void *pUserData,
  194323. int(*)(const Fts5ExtensionApi*,Fts5Context*,void*)
  194324. );
  194325. int (*xSetAuxdata)(Fts5Context*, void *pAux, void(*xDelete)(void*));
  194326. void *(*xGetAuxdata)(Fts5Context*, int bClear);
  194327. int (*xPhraseFirst)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*, int*);
  194328. void (*xPhraseNext)(Fts5Context*, Fts5PhraseIter*, int *piCol, int *piOff);
  194329. int (*xPhraseFirstColumn)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*);
  194330. void (*xPhraseNextColumn)(Fts5Context*, Fts5PhraseIter*, int *piCol);
  194331. };
  194332. /*
  194333. ** CUSTOM AUXILIARY FUNCTIONS
  194334. *************************************************************************/
  194335. /*************************************************************************
  194336. ** CUSTOM TOKENIZERS
  194337. **
  194338. ** Applications may also register custom tokenizer types. A tokenizer
  194339. ** is registered by providing fts5 with a populated instance of the
  194340. ** following structure. All structure methods must be defined, setting
  194341. ** any member of the fts5_tokenizer struct to NULL leads to undefined
  194342. ** behaviour. The structure methods are expected to function as follows:
  194343. **
  194344. ** xCreate:
  194345. ** This function is used to allocate and initialize a tokenizer instance.
  194346. ** A tokenizer instance is required to actually tokenize text.
  194347. **
  194348. ** The first argument passed to this function is a copy of the (void*)
  194349. ** pointer provided by the application when the fts5_tokenizer object
  194350. ** was registered with FTS5 (the third argument to xCreateTokenizer()).
  194351. ** The second and third arguments are an array of nul-terminated strings
  194352. ** containing the tokenizer arguments, if any, specified following the
  194353. ** tokenizer name as part of the CREATE VIRTUAL TABLE statement used
  194354. ** to create the FTS5 table.
  194355. **
  194356. ** The final argument is an output variable. If successful, (*ppOut)
  194357. ** should be set to point to the new tokenizer handle and SQLITE_OK
  194358. ** returned. If an error occurs, some value other than SQLITE_OK should
  194359. ** be returned. In this case, fts5 assumes that the final value of *ppOut
  194360. ** is undefined.
  194361. **
  194362. ** xDelete:
  194363. ** This function is invoked to delete a tokenizer handle previously
  194364. ** allocated using xCreate(). Fts5 guarantees that this function will
  194365. ** be invoked exactly once for each successful call to xCreate().
  194366. **
  194367. ** xTokenize:
  194368. ** This function is expected to tokenize the nText byte string indicated
  194369. ** by argument pText. pText may or may not be nul-terminated. The first
  194370. ** argument passed to this function is a pointer to an Fts5Tokenizer object
  194371. ** returned by an earlier call to xCreate().
  194372. **
  194373. ** The second argument indicates the reason that FTS5 is requesting
  194374. ** tokenization of the supplied text. This is always one of the following
  194375. ** four values:
  194376. **
  194377. ** <ul><li> <b>FTS5_TOKENIZE_DOCUMENT</b> - A document is being inserted into
  194378. ** or removed from the FTS table. The tokenizer is being invoked to
  194379. ** determine the set of tokens to add to (or delete from) the
  194380. ** FTS index.
  194381. **
  194382. ** <li> <b>FTS5_TOKENIZE_QUERY</b> - A MATCH query is being executed
  194383. ** against the FTS index. The tokenizer is being called to tokenize
  194384. ** a bareword or quoted string specified as part of the query.
  194385. **
  194386. ** <li> <b>(FTS5_TOKENIZE_QUERY | FTS5_TOKENIZE_PREFIX)</b> - Same as
  194387. ** FTS5_TOKENIZE_QUERY, except that the bareword or quoted string is
  194388. ** followed by a "*" character, indicating that the last token
  194389. ** returned by the tokenizer will be treated as a token prefix.
  194390. **
  194391. ** <li> <b>FTS5_TOKENIZE_AUX</b> - The tokenizer is being invoked to
  194392. ** satisfy an fts5_api.xTokenize() request made by an auxiliary
  194393. ** function. Or an fts5_api.xColumnSize() request made by the same
  194394. ** on a columnsize=0 database.
  194395. ** </ul>
  194396. **
  194397. ** For each token in the input string, the supplied callback xToken() must
  194398. ** be invoked. The first argument to it should be a copy of the pointer
  194399. ** passed as the second argument to xTokenize(). The third and fourth
  194400. ** arguments are a pointer to a buffer containing the token text, and the
  194401. ** size of the token in bytes. The 4th and 5th arguments are the byte offsets
  194402. ** of the first byte of and first byte immediately following the text from
  194403. ** which the token is derived within the input.
  194404. **
  194405. ** The second argument passed to the xToken() callback ("tflags") should
  194406. ** normally be set to 0. The exception is if the tokenizer supports
  194407. ** synonyms. In this case see the discussion below for details.
  194408. **
  194409. ** FTS5 assumes the xToken() callback is invoked for each token in the
  194410. ** order that they occur within the input text.
  194411. **
  194412. ** If an xToken() callback returns any value other than SQLITE_OK, then
  194413. ** the tokenization should be abandoned and the xTokenize() method should
  194414. ** immediately return a copy of the xToken() return value. Or, if the
  194415. ** input buffer is exhausted, xTokenize() should return SQLITE_OK. Finally,
  194416. ** if an error occurs with the xTokenize() implementation itself, it
  194417. ** may abandon the tokenization and return any error code other than
  194418. ** SQLITE_OK or SQLITE_DONE.
  194419. **
  194420. ** SYNONYM SUPPORT
  194421. **
  194422. ** Custom tokenizers may also support synonyms. Consider a case in which a
  194423. ** user wishes to query for a phrase such as "first place". Using the
  194424. ** built-in tokenizers, the FTS5 query 'first + place' will match instances
  194425. ** of "first place" within the document set, but not alternative forms
  194426. ** such as "1st place". In some applications, it would be better to match
  194427. ** all instances of "first place" or "1st place" regardless of which form
  194428. ** the user specified in the MATCH query text.
  194429. **
  194430. ** There are several ways to approach this in FTS5:
  194431. **
  194432. ** <ol><li> By mapping all synonyms to a single token. In this case, using
  194433. ** the above example, this means that the tokenizer returns the
  194434. ** same token for inputs "first" and "1st". Say that token is in
  194435. ** fact "first", so that when the user inserts the document "I won
  194436. ** 1st place" entries are added to the index for tokens "i", "won",
  194437. ** "first" and "place". If the user then queries for '1st + place',
  194438. ** the tokenizer substitutes "first" for "1st" and the query works
  194439. ** as expected.
  194440. **
  194441. ** <li> By querying the index for all synonyms of each query term
  194442. ** separately. In this case, when tokenizing query text, the
  194443. ** tokenizer may provide multiple synonyms for a single term
  194444. ** within the document. FTS5 then queries the index for each
  194445. ** synonym individually. For example, faced with the query:
  194446. **
  194447. ** <codeblock>
  194448. ** ... MATCH 'first place'</codeblock>
  194449. **
  194450. ** the tokenizer offers both "1st" and "first" as synonyms for the
  194451. ** first token in the MATCH query and FTS5 effectively runs a query
  194452. ** similar to:
  194453. **
  194454. ** <codeblock>
  194455. ** ... MATCH '(first OR 1st) place'</codeblock>
  194456. **
  194457. ** except that, for the purposes of auxiliary functions, the query
  194458. ** still appears to contain just two phrases - "(first OR 1st)"
  194459. ** being treated as a single phrase.
  194460. **
  194461. ** <li> By adding multiple synonyms for a single term to the FTS index.
  194462. ** Using this method, when tokenizing document text, the tokenizer
  194463. ** provides multiple synonyms for each token. So that when a
  194464. ** document such as "I won first place" is tokenized, entries are
  194465. ** added to the FTS index for "i", "won", "first", "1st" and
  194466. ** "place".
  194467. **
  194468. ** This way, even if the tokenizer does not provide synonyms
  194469. ** when tokenizing query text (it should not - to do so would be
  194470. ** inefficient), it doesn't matter if the user queries for
  194471. ** 'first + place' or '1st + place', as there are entries in the
  194472. ** FTS index corresponding to both forms of the first token.
  194473. ** </ol>
  194474. **
  194475. ** Whether it is parsing document or query text, any call to xToken that
  194476. ** specifies a <i>tflags</i> argument with the FTS5_TOKEN_COLOCATED bit
  194477. ** is considered to supply a synonym for the previous token. For example,
  194478. ** when parsing the document "I won first place", a tokenizer that supports
  194479. ** synonyms would call xToken() 5 times, as follows:
  194480. **
  194481. ** <codeblock>
  194482. ** xToken(pCtx, 0, "i", 1, 0, 1);
  194483. ** xToken(pCtx, 0, "won", 3, 2, 5);
  194484. ** xToken(pCtx, 0, "first", 5, 6, 11);
  194485. ** xToken(pCtx, FTS5_TOKEN_COLOCATED, "1st", 3, 6, 11);
  194486. ** xToken(pCtx, 0, "place", 5, 12, 17);
  194487. **</codeblock>
  194488. **
  194489. ** It is an error to specify the FTS5_TOKEN_COLOCATED flag the first time
  194490. ** xToken() is called. Multiple synonyms may be specified for a single token
  194491. ** by making multiple calls to xToken(FTS5_TOKEN_COLOCATED) in sequence.
  194492. ** There is no limit to the number of synonyms that may be provided for a
  194493. ** single token.
  194494. **
  194495. ** In many cases, method (1) above is the best approach. It does not add
  194496. ** extra data to the FTS index or require FTS5 to query for multiple terms,
  194497. ** so it is efficient in terms of disk space and query speed. However, it
  194498. ** does not support prefix queries very well. If, as suggested above, the
  194499. ** token "first" is substituted for "1st" by the tokenizer, then the query:
  194500. **
  194501. ** <codeblock>
  194502. ** ... MATCH '1s*'</codeblock>
  194503. **
  194504. ** will not match documents that contain the token "1st" (as the tokenizer
  194505. ** will probably not map "1s" to any prefix of "first").
  194506. **
  194507. ** For full prefix support, method (3) may be preferred. In this case,
  194508. ** because the index contains entries for both "first" and "1st", prefix
  194509. ** queries such as 'fi*' or '1s*' will match correctly. However, because
  194510. ** extra entries are added to the FTS index, this method uses more space
  194511. ** within the database.
  194512. **
  194513. ** Method (2) offers a midpoint between (1) and (3). Using this method,
  194514. ** a query such as '1s*' will match documents that contain the literal
  194515. ** token "1st", but not "first" (assuming the tokenizer is not able to
  194516. ** provide synonyms for prefixes). However, a non-prefix query like '1st'
  194517. ** will match against "1st" and "first". This method does not require
  194518. ** extra disk space, as no extra entries are added to the FTS index.
  194519. ** On the other hand, it may require more CPU cycles to run MATCH queries,
  194520. ** as separate queries of the FTS index are required for each synonym.
  194521. **
  194522. ** When using methods (2) or (3), it is important that the tokenizer only
  194523. ** provide synonyms when tokenizing document text (method (2)) or query
  194524. ** text (method (3)), not both. Doing so will not cause any errors, but is
  194525. ** inefficient.
  194526. */
  194527. typedef struct Fts5Tokenizer Fts5Tokenizer;
  194528. typedef struct fts5_tokenizer fts5_tokenizer;
  194529. struct fts5_tokenizer {
  194530. int (*xCreate)(void*, const char **azArg, int nArg, Fts5Tokenizer **ppOut);
  194531. void (*xDelete)(Fts5Tokenizer*);
  194532. int (*xTokenize)(Fts5Tokenizer*,
  194533. void *pCtx,
  194534. int flags, /* Mask of FTS5_TOKENIZE_* flags */
  194535. const char *pText, int nText,
  194536. int (*xToken)(
  194537. void *pCtx, /* Copy of 2nd argument to xTokenize() */
  194538. int tflags, /* Mask of FTS5_TOKEN_* flags */
  194539. const char *pToken, /* Pointer to buffer containing token */
  194540. int nToken, /* Size of token in bytes */
  194541. int iStart, /* Byte offset of token within input text */
  194542. int iEnd /* Byte offset of end of token within input text */
  194543. )
  194544. );
  194545. };
  194546. /* Flags that may be passed as the third argument to xTokenize() */
  194547. #define FTS5_TOKENIZE_QUERY 0x0001
  194548. #define FTS5_TOKENIZE_PREFIX 0x0002
  194549. #define FTS5_TOKENIZE_DOCUMENT 0x0004
  194550. #define FTS5_TOKENIZE_AUX 0x0008
  194551. /* Flags that may be passed by the tokenizer implementation back to FTS5
  194552. ** as the third argument to the supplied xToken callback. */
  194553. #define FTS5_TOKEN_COLOCATED 0x0001 /* Same position as prev. token */
  194554. /*
  194555. ** END OF CUSTOM TOKENIZERS
  194556. *************************************************************************/
  194557. /*************************************************************************
  194558. ** FTS5 EXTENSION REGISTRATION API
  194559. */
  194560. typedef struct fts5_api fts5_api;
  194561. struct fts5_api {
  194562. int iVersion; /* Currently always set to 2 */
  194563. /* Create a new tokenizer */
  194564. int (*xCreateTokenizer)(
  194565. fts5_api *pApi,
  194566. const char *zName,
  194567. void *pContext,
  194568. fts5_tokenizer *pTokenizer,
  194569. void (*xDestroy)(void*)
  194570. );
  194571. /* Find an existing tokenizer */
  194572. int (*xFindTokenizer)(
  194573. fts5_api *pApi,
  194574. const char *zName,
  194575. void **ppContext,
  194576. fts5_tokenizer *pTokenizer
  194577. );
  194578. /* Create a new auxiliary function */
  194579. int (*xCreateFunction)(
  194580. fts5_api *pApi,
  194581. const char *zName,
  194582. void *pContext,
  194583. fts5_extension_function xFunction,
  194584. void (*xDestroy)(void*)
  194585. );
  194586. };
  194587. /*
  194588. ** END OF REGISTRATION API
  194589. *************************************************************************/
  194590. #if 0
  194591. } /* end of the 'extern "C"' block */
  194592. #endif
  194593. #endif /* _FTS5_H */
  194594. /*
  194595. ** 2014 May 31
  194596. **
  194597. ** The author disclaims copyright to this source code. In place of
  194598. ** a legal notice, here is a blessing:
  194599. **
  194600. ** May you do good and not evil.
  194601. ** May you find forgiveness for yourself and forgive others.
  194602. ** May you share freely, never taking more than you give.
  194603. **
  194604. ******************************************************************************
  194605. **
  194606. */
  194607. #ifndef _FTS5INT_H
  194608. #define _FTS5INT_H
  194609. /* #include "fts5.h" */
  194610. /* #include "sqlite3ext.h" */
  194611. SQLITE_EXTENSION_INIT1
  194612. /* #include <string.h> */
  194613. /* #include <assert.h> */
  194614. #ifndef SQLITE_AMALGAMATION
  194615. typedef unsigned char u8;
  194616. typedef unsigned int u32;
  194617. typedef unsigned short u16;
  194618. typedef short i16;
  194619. typedef sqlite3_int64 i64;
  194620. typedef sqlite3_uint64 u64;
  194621. #ifndef ArraySize
  194622. # define ArraySize(x) ((int)(sizeof(x) / sizeof(x[0])))
  194623. #endif
  194624. #define testcase(x)
  194625. #define ALWAYS(x) 1
  194626. #define NEVER(x) 0
  194627. #define MIN(x,y) (((x) < (y)) ? (x) : (y))
  194628. #define MAX(x,y) (((x) > (y)) ? (x) : (y))
  194629. /*
  194630. ** Constants for the largest and smallest possible 64-bit signed integers.
  194631. */
  194632. # define LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32))
  194633. # define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
  194634. #endif
  194635. /* Truncate very long tokens to this many bytes. Hard limit is
  194636. ** (65536-1-1-4-9)==65521 bytes. The limiting factor is the 16-bit offset
  194637. ** field that occurs at the start of each leaf page (see fts5_index.c). */
  194638. #define FTS5_MAX_TOKEN_SIZE 32768
  194639. /*
  194640. ** Maximum number of prefix indexes on single FTS5 table. This must be
  194641. ** less than 32. If it is set to anything large than that, an #error
  194642. ** directive in fts5_index.c will cause the build to fail.
  194643. */
  194644. #define FTS5_MAX_PREFIX_INDEXES 31
  194645. /*
  194646. ** Maximum segments permitted in a single index
  194647. */
  194648. #define FTS5_MAX_SEGMENT 2000
  194649. #define FTS5_DEFAULT_NEARDIST 10
  194650. #define FTS5_DEFAULT_RANK "bm25"
  194651. /* Name of rank and rowid columns */
  194652. #define FTS5_RANK_NAME "rank"
  194653. #define FTS5_ROWID_NAME "rowid"
  194654. #ifdef SQLITE_DEBUG
  194655. # define FTS5_CORRUPT sqlite3Fts5Corrupt()
  194656. static int sqlite3Fts5Corrupt(void);
  194657. #else
  194658. # define FTS5_CORRUPT SQLITE_CORRUPT_VTAB
  194659. #endif
  194660. /*
  194661. ** The assert_nc() macro is similar to the assert() macro, except that it
  194662. ** is used for assert() conditions that are true only if it can be
  194663. ** guranteed that the database is not corrupt.
  194664. */
  194665. #ifdef SQLITE_DEBUG
  194666. SQLITE_API extern int sqlite3_fts5_may_be_corrupt;
  194667. # define assert_nc(x) assert(sqlite3_fts5_may_be_corrupt || (x))
  194668. #else
  194669. # define assert_nc(x) assert(x)
  194670. #endif
  194671. /*
  194672. ** A version of memcmp() that does not cause asan errors if one of the pointer
  194673. ** parameters is NULL and the number of bytes to compare is zero.
  194674. */
  194675. #define fts5Memcmp(s1, s2, n) ((n)==0 ? 0 : memcmp((s1), (s2), (n)))
  194676. /* Mark a function parameter as unused, to suppress nuisance compiler
  194677. ** warnings. */
  194678. #ifndef UNUSED_PARAM
  194679. # define UNUSED_PARAM(X) (void)(X)
  194680. #endif
  194681. #ifndef UNUSED_PARAM2
  194682. # define UNUSED_PARAM2(X, Y) (void)(X), (void)(Y)
  194683. #endif
  194684. typedef struct Fts5Global Fts5Global;
  194685. typedef struct Fts5Colset Fts5Colset;
  194686. /* If a NEAR() clump or phrase may only match a specific set of columns,
  194687. ** then an object of the following type is used to record the set of columns.
  194688. ** Each entry in the aiCol[] array is a column that may be matched.
  194689. **
  194690. ** This object is used by fts5_expr.c and fts5_index.c.
  194691. */
  194692. struct Fts5Colset {
  194693. int nCol;
  194694. int aiCol[1];
  194695. };
  194696. /**************************************************************************
  194697. ** Interface to code in fts5_config.c. fts5_config.c contains contains code
  194698. ** to parse the arguments passed to the CREATE VIRTUAL TABLE statement.
  194699. */
  194700. typedef struct Fts5Config Fts5Config;
  194701. /*
  194702. ** An instance of the following structure encodes all information that can
  194703. ** be gleaned from the CREATE VIRTUAL TABLE statement.
  194704. **
  194705. ** And all information loaded from the %_config table.
  194706. **
  194707. ** nAutomerge:
  194708. ** The minimum number of segments that an auto-merge operation should
  194709. ** attempt to merge together. A value of 1 sets the object to use the
  194710. ** compile time default. Zero disables auto-merge altogether.
  194711. **
  194712. ** zContent:
  194713. **
  194714. ** zContentRowid:
  194715. ** The value of the content_rowid= option, if one was specified. Or
  194716. ** the string "rowid" otherwise. This text is not quoted - if it is
  194717. ** used as part of an SQL statement it needs to be quoted appropriately.
  194718. **
  194719. ** zContentExprlist:
  194720. **
  194721. ** pzErrmsg:
  194722. ** This exists in order to allow the fts5_index.c module to return a
  194723. ** decent error message if it encounters a file-format version it does
  194724. ** not understand.
  194725. **
  194726. ** bColumnsize:
  194727. ** True if the %_docsize table is created.
  194728. **
  194729. ** bPrefixIndex:
  194730. ** This is only used for debugging. If set to false, any prefix indexes
  194731. ** are ignored. This value is configured using:
  194732. **
  194733. ** INSERT INTO tbl(tbl, rank) VALUES('prefix-index', $bPrefixIndex);
  194734. **
  194735. */
  194736. struct Fts5Config {
  194737. sqlite3 *db; /* Database handle */
  194738. char *zDb; /* Database holding FTS index (e.g. "main") */
  194739. char *zName; /* Name of FTS index */
  194740. int nCol; /* Number of columns */
  194741. char **azCol; /* Column names */
  194742. u8 *abUnindexed; /* True for unindexed columns */
  194743. int nPrefix; /* Number of prefix indexes */
  194744. int *aPrefix; /* Sizes in bytes of nPrefix prefix indexes */
  194745. int eContent; /* An FTS5_CONTENT value */
  194746. char *zContent; /* content table */
  194747. char *zContentRowid; /* "content_rowid=" option value */
  194748. int bColumnsize; /* "columnsize=" option value (dflt==1) */
  194749. int eDetail; /* FTS5_DETAIL_XXX value */
  194750. char *zContentExprlist;
  194751. Fts5Tokenizer *pTok;
  194752. fts5_tokenizer *pTokApi;
  194753. int bLock; /* True when table is preparing statement */
  194754. /* Values loaded from the %_config table */
  194755. int iCookie; /* Incremented when %_config is modified */
  194756. int pgsz; /* Approximate page size used in %_data */
  194757. int nAutomerge; /* 'automerge' setting */
  194758. int nCrisisMerge; /* Maximum allowed segments per level */
  194759. int nUsermerge; /* 'usermerge' setting */
  194760. int nHashSize; /* Bytes of memory for in-memory hash */
  194761. char *zRank; /* Name of rank function */
  194762. char *zRankArgs; /* Arguments to rank function */
  194763. /* If non-NULL, points to sqlite3_vtab.base.zErrmsg. Often NULL. */
  194764. char **pzErrmsg;
  194765. #ifdef SQLITE_DEBUG
  194766. int bPrefixIndex; /* True to use prefix-indexes */
  194767. #endif
  194768. };
  194769. /* Current expected value of %_config table 'version' field */
  194770. #define FTS5_CURRENT_VERSION 4
  194771. #define FTS5_CONTENT_NORMAL 0
  194772. #define FTS5_CONTENT_NONE 1
  194773. #define FTS5_CONTENT_EXTERNAL 2
  194774. #define FTS5_DETAIL_FULL 0
  194775. #define FTS5_DETAIL_NONE 1
  194776. #define FTS5_DETAIL_COLUMNS 2
  194777. static int sqlite3Fts5ConfigParse(
  194778. Fts5Global*, sqlite3*, int, const char **, Fts5Config**, char**
  194779. );
  194780. static void sqlite3Fts5ConfigFree(Fts5Config*);
  194781. static int sqlite3Fts5ConfigDeclareVtab(Fts5Config *pConfig);
  194782. static int sqlite3Fts5Tokenize(
  194783. Fts5Config *pConfig, /* FTS5 Configuration object */
  194784. int flags, /* FTS5_TOKENIZE_* flags */
  194785. const char *pText, int nText, /* Text to tokenize */
  194786. void *pCtx, /* Context passed to xToken() */
  194787. int (*xToken)(void*, int, const char*, int, int, int) /* Callback */
  194788. );
  194789. static void sqlite3Fts5Dequote(char *z);
  194790. /* Load the contents of the %_config table */
  194791. static int sqlite3Fts5ConfigLoad(Fts5Config*, int);
  194792. /* Set the value of a single config attribute */
  194793. static int sqlite3Fts5ConfigSetValue(Fts5Config*, const char*, sqlite3_value*, int*);
  194794. static int sqlite3Fts5ConfigParseRank(const char*, char**, char**);
  194795. /*
  194796. ** End of interface to code in fts5_config.c.
  194797. **************************************************************************/
  194798. /**************************************************************************
  194799. ** Interface to code in fts5_buffer.c.
  194800. */
  194801. /*
  194802. ** Buffer object for the incremental building of string data.
  194803. */
  194804. typedef struct Fts5Buffer Fts5Buffer;
  194805. struct Fts5Buffer {
  194806. u8 *p;
  194807. int n;
  194808. int nSpace;
  194809. };
  194810. static int sqlite3Fts5BufferSize(int*, Fts5Buffer*, u32);
  194811. static void sqlite3Fts5BufferAppendVarint(int*, Fts5Buffer*, i64);
  194812. static void sqlite3Fts5BufferAppendBlob(int*, Fts5Buffer*, u32, const u8*);
  194813. static void sqlite3Fts5BufferAppendString(int *, Fts5Buffer*, const char*);
  194814. static void sqlite3Fts5BufferFree(Fts5Buffer*);
  194815. static void sqlite3Fts5BufferZero(Fts5Buffer*);
  194816. static void sqlite3Fts5BufferSet(int*, Fts5Buffer*, int, const u8*);
  194817. static void sqlite3Fts5BufferAppendPrintf(int *, Fts5Buffer*, char *zFmt, ...);
  194818. static char *sqlite3Fts5Mprintf(int *pRc, const char *zFmt, ...);
  194819. #define fts5BufferZero(x) sqlite3Fts5BufferZero(x)
  194820. #define fts5BufferAppendVarint(a,b,c) sqlite3Fts5BufferAppendVarint(a,b,c)
  194821. #define fts5BufferFree(a) sqlite3Fts5BufferFree(a)
  194822. #define fts5BufferAppendBlob(a,b,c,d) sqlite3Fts5BufferAppendBlob(a,b,c,d)
  194823. #define fts5BufferSet(a,b,c,d) sqlite3Fts5BufferSet(a,b,c,d)
  194824. #define fts5BufferGrow(pRc,pBuf,nn) ( \
  194825. (u32)((pBuf)->n) + (u32)(nn) <= (u32)((pBuf)->nSpace) ? 0 : \
  194826. sqlite3Fts5BufferSize((pRc),(pBuf),(nn)+(pBuf)->n) \
  194827. )
  194828. /* Write and decode big-endian 32-bit integer values */
  194829. static void sqlite3Fts5Put32(u8*, int);
  194830. static int sqlite3Fts5Get32(const u8*);
  194831. #define FTS5_POS2COLUMN(iPos) (int)(iPos >> 32)
  194832. #define FTS5_POS2OFFSET(iPos) (int)(iPos & 0x7FFFFFFF)
  194833. typedef struct Fts5PoslistReader Fts5PoslistReader;
  194834. struct Fts5PoslistReader {
  194835. /* Variables used only by sqlite3Fts5PoslistIterXXX() functions. */
  194836. const u8 *a; /* Position list to iterate through */
  194837. int n; /* Size of buffer at a[] in bytes */
  194838. int i; /* Current offset in a[] */
  194839. u8 bFlag; /* For client use (any custom purpose) */
  194840. /* Output variables */
  194841. u8 bEof; /* Set to true at EOF */
  194842. i64 iPos; /* (iCol<<32) + iPos */
  194843. };
  194844. static int sqlite3Fts5PoslistReaderInit(
  194845. const u8 *a, int n, /* Poslist buffer to iterate through */
  194846. Fts5PoslistReader *pIter /* Iterator object to initialize */
  194847. );
  194848. static int sqlite3Fts5PoslistReaderNext(Fts5PoslistReader*);
  194849. typedef struct Fts5PoslistWriter Fts5PoslistWriter;
  194850. struct Fts5PoslistWriter {
  194851. i64 iPrev;
  194852. };
  194853. static int sqlite3Fts5PoslistWriterAppend(Fts5Buffer*, Fts5PoslistWriter*, i64);
  194854. static void sqlite3Fts5PoslistSafeAppend(Fts5Buffer*, i64*, i64);
  194855. static int sqlite3Fts5PoslistNext64(
  194856. const u8 *a, int n, /* Buffer containing poslist */
  194857. int *pi, /* IN/OUT: Offset within a[] */
  194858. i64 *piOff /* IN/OUT: Current offset */
  194859. );
  194860. /* Malloc utility */
  194861. static void *sqlite3Fts5MallocZero(int *pRc, sqlite3_int64 nByte);
  194862. static char *sqlite3Fts5Strndup(int *pRc, const char *pIn, int nIn);
  194863. /* Character set tests (like isspace(), isalpha() etc.) */
  194864. static int sqlite3Fts5IsBareword(char t);
  194865. /* Bucket of terms object used by the integrity-check in offsets=0 mode. */
  194866. typedef struct Fts5Termset Fts5Termset;
  194867. static int sqlite3Fts5TermsetNew(Fts5Termset**);
  194868. static int sqlite3Fts5TermsetAdd(Fts5Termset*, int, const char*, int, int *pbPresent);
  194869. static void sqlite3Fts5TermsetFree(Fts5Termset*);
  194870. /*
  194871. ** End of interface to code in fts5_buffer.c.
  194872. **************************************************************************/
  194873. /**************************************************************************
  194874. ** Interface to code in fts5_index.c. fts5_index.c contains contains code
  194875. ** to access the data stored in the %_data table.
  194876. */
  194877. typedef struct Fts5Index Fts5Index;
  194878. typedef struct Fts5IndexIter Fts5IndexIter;
  194879. struct Fts5IndexIter {
  194880. i64 iRowid;
  194881. const u8 *pData;
  194882. int nData;
  194883. u8 bEof;
  194884. };
  194885. #define sqlite3Fts5IterEof(x) ((x)->bEof)
  194886. /*
  194887. ** Values used as part of the flags argument passed to IndexQuery().
  194888. */
  194889. #define FTS5INDEX_QUERY_PREFIX 0x0001 /* Prefix query */
  194890. #define FTS5INDEX_QUERY_DESC 0x0002 /* Docs in descending rowid order */
  194891. #define FTS5INDEX_QUERY_TEST_NOIDX 0x0004 /* Do not use prefix index */
  194892. #define FTS5INDEX_QUERY_SCAN 0x0008 /* Scan query (fts5vocab) */
  194893. /* The following are used internally by the fts5_index.c module. They are
  194894. ** defined here only to make it easier to avoid clashes with the flags
  194895. ** above. */
  194896. #define FTS5INDEX_QUERY_SKIPEMPTY 0x0010
  194897. #define FTS5INDEX_QUERY_NOOUTPUT 0x0020
  194898. /*
  194899. ** Create/destroy an Fts5Index object.
  194900. */
  194901. static int sqlite3Fts5IndexOpen(Fts5Config *pConfig, int bCreate, Fts5Index**, char**);
  194902. static int sqlite3Fts5IndexClose(Fts5Index *p);
  194903. /*
  194904. ** Return a simple checksum value based on the arguments.
  194905. */
  194906. static u64 sqlite3Fts5IndexEntryCksum(
  194907. i64 iRowid,
  194908. int iCol,
  194909. int iPos,
  194910. int iIdx,
  194911. const char *pTerm,
  194912. int nTerm
  194913. );
  194914. /*
  194915. ** Argument p points to a buffer containing utf-8 text that is n bytes in
  194916. ** size. Return the number of bytes in the nChar character prefix of the
  194917. ** buffer, or 0 if there are less than nChar characters in total.
  194918. */
  194919. static int sqlite3Fts5IndexCharlenToBytelen(
  194920. const char *p,
  194921. int nByte,
  194922. int nChar
  194923. );
  194924. /*
  194925. ** Open a new iterator to iterate though all rowids that match the
  194926. ** specified token or token prefix.
  194927. */
  194928. static int sqlite3Fts5IndexQuery(
  194929. Fts5Index *p, /* FTS index to query */
  194930. const char *pToken, int nToken, /* Token (or prefix) to query for */
  194931. int flags, /* Mask of FTS5INDEX_QUERY_X flags */
  194932. Fts5Colset *pColset, /* Match these columns only */
  194933. Fts5IndexIter **ppIter /* OUT: New iterator object */
  194934. );
  194935. /*
  194936. ** The various operations on open token or token prefix iterators opened
  194937. ** using sqlite3Fts5IndexQuery().
  194938. */
  194939. static int sqlite3Fts5IterNext(Fts5IndexIter*);
  194940. static int sqlite3Fts5IterNextFrom(Fts5IndexIter*, i64 iMatch);
  194941. /*
  194942. ** Close an iterator opened by sqlite3Fts5IndexQuery().
  194943. */
  194944. static void sqlite3Fts5IterClose(Fts5IndexIter*);
  194945. /*
  194946. ** Close the reader blob handle, if it is open.
  194947. */
  194948. static void sqlite3Fts5IndexCloseReader(Fts5Index*);
  194949. /*
  194950. ** This interface is used by the fts5vocab module.
  194951. */
  194952. static const char *sqlite3Fts5IterTerm(Fts5IndexIter*, int*);
  194953. static int sqlite3Fts5IterNextScan(Fts5IndexIter*);
  194954. /*
  194955. ** Insert or remove data to or from the index. Each time a document is
  194956. ** added to or removed from the index, this function is called one or more
  194957. ** times.
  194958. **
  194959. ** For an insert, it must be called once for each token in the new document.
  194960. ** If the operation is a delete, it must be called (at least) once for each
  194961. ** unique token in the document with an iCol value less than zero. The iPos
  194962. ** argument is ignored for a delete.
  194963. */
  194964. static int sqlite3Fts5IndexWrite(
  194965. Fts5Index *p, /* Index to write to */
  194966. int iCol, /* Column token appears in (-ve -> delete) */
  194967. int iPos, /* Position of token within column */
  194968. const char *pToken, int nToken /* Token to add or remove to or from index */
  194969. );
  194970. /*
  194971. ** Indicate that subsequent calls to sqlite3Fts5IndexWrite() pertain to
  194972. ** document iDocid.
  194973. */
  194974. static int sqlite3Fts5IndexBeginWrite(
  194975. Fts5Index *p, /* Index to write to */
  194976. int bDelete, /* True if current operation is a delete */
  194977. i64 iDocid /* Docid to add or remove data from */
  194978. );
  194979. /*
  194980. ** Flush any data stored in the in-memory hash tables to the database.
  194981. ** Also close any open blob handles.
  194982. */
  194983. static int sqlite3Fts5IndexSync(Fts5Index *p);
  194984. /*
  194985. ** Discard any data stored in the in-memory hash tables. Do not write it
  194986. ** to the database. Additionally, assume that the contents of the %_data
  194987. ** table may have changed on disk. So any in-memory caches of %_data
  194988. ** records must be invalidated.
  194989. */
  194990. static int sqlite3Fts5IndexRollback(Fts5Index *p);
  194991. /*
  194992. ** Get or set the "averages" values.
  194993. */
  194994. static int sqlite3Fts5IndexGetAverages(Fts5Index *p, i64 *pnRow, i64 *anSize);
  194995. static int sqlite3Fts5IndexSetAverages(Fts5Index *p, const u8*, int);
  194996. /*
  194997. ** Functions called by the storage module as part of integrity-check.
  194998. */
  194999. static int sqlite3Fts5IndexIntegrityCheck(Fts5Index*, u64 cksum);
  195000. /*
  195001. ** Called during virtual module initialization to register UDF
  195002. ** fts5_decode() with SQLite
  195003. */
  195004. static int sqlite3Fts5IndexInit(sqlite3*);
  195005. static int sqlite3Fts5IndexSetCookie(Fts5Index*, int);
  195006. /*
  195007. ** Return the total number of entries read from the %_data table by
  195008. ** this connection since it was created.
  195009. */
  195010. static int sqlite3Fts5IndexReads(Fts5Index *p);
  195011. static int sqlite3Fts5IndexReinit(Fts5Index *p);
  195012. static int sqlite3Fts5IndexOptimize(Fts5Index *p);
  195013. static int sqlite3Fts5IndexMerge(Fts5Index *p, int nMerge);
  195014. static int sqlite3Fts5IndexReset(Fts5Index *p);
  195015. static int sqlite3Fts5IndexLoadConfig(Fts5Index *p);
  195016. /*
  195017. ** End of interface to code in fts5_index.c.
  195018. **************************************************************************/
  195019. /**************************************************************************
  195020. ** Interface to code in fts5_varint.c.
  195021. */
  195022. static int sqlite3Fts5GetVarint32(const unsigned char *p, u32 *v);
  195023. static int sqlite3Fts5GetVarintLen(u32 iVal);
  195024. static u8 sqlite3Fts5GetVarint(const unsigned char*, u64*);
  195025. static int sqlite3Fts5PutVarint(unsigned char *p, u64 v);
  195026. #define fts5GetVarint32(a,b) sqlite3Fts5GetVarint32(a,(u32*)&b)
  195027. #define fts5GetVarint sqlite3Fts5GetVarint
  195028. #define fts5FastGetVarint32(a, iOff, nVal) { \
  195029. nVal = (a)[iOff++]; \
  195030. if( nVal & 0x80 ){ \
  195031. iOff--; \
  195032. iOff += fts5GetVarint32(&(a)[iOff], nVal); \
  195033. } \
  195034. }
  195035. /*
  195036. ** End of interface to code in fts5_varint.c.
  195037. **************************************************************************/
  195038. /**************************************************************************
  195039. ** Interface to code in fts5_main.c.
  195040. */
  195041. /*
  195042. ** Virtual-table object.
  195043. */
  195044. typedef struct Fts5Table Fts5Table;
  195045. struct Fts5Table {
  195046. sqlite3_vtab base; /* Base class used by SQLite core */
  195047. Fts5Config *pConfig; /* Virtual table configuration */
  195048. Fts5Index *pIndex; /* Full-text index */
  195049. };
  195050. static int sqlite3Fts5GetTokenizer(
  195051. Fts5Global*,
  195052. const char **azArg,
  195053. int nArg,
  195054. Fts5Tokenizer**,
  195055. fts5_tokenizer**,
  195056. char **pzErr
  195057. );
  195058. static Fts5Table *sqlite3Fts5TableFromCsrid(Fts5Global*, i64);
  195059. static int sqlite3Fts5FlushToDisk(Fts5Table*);
  195060. /*
  195061. ** End of interface to code in fts5.c.
  195062. **************************************************************************/
  195063. /**************************************************************************
  195064. ** Interface to code in fts5_hash.c.
  195065. */
  195066. typedef struct Fts5Hash Fts5Hash;
  195067. /*
  195068. ** Create a hash table, free a hash table.
  195069. */
  195070. static int sqlite3Fts5HashNew(Fts5Config*, Fts5Hash**, int *pnSize);
  195071. static void sqlite3Fts5HashFree(Fts5Hash*);
  195072. static int sqlite3Fts5HashWrite(
  195073. Fts5Hash*,
  195074. i64 iRowid, /* Rowid for this entry */
  195075. int iCol, /* Column token appears in (-ve -> delete) */
  195076. int iPos, /* Position of token within column */
  195077. char bByte,
  195078. const char *pToken, int nToken /* Token to add or remove to or from index */
  195079. );
  195080. /*
  195081. ** Empty (but do not delete) a hash table.
  195082. */
  195083. static void sqlite3Fts5HashClear(Fts5Hash*);
  195084. static int sqlite3Fts5HashQuery(
  195085. Fts5Hash*, /* Hash table to query */
  195086. int nPre,
  195087. const char *pTerm, int nTerm, /* Query term */
  195088. void **ppObj, /* OUT: Pointer to doclist for pTerm */
  195089. int *pnDoclist /* OUT: Size of doclist in bytes */
  195090. );
  195091. static int sqlite3Fts5HashScanInit(
  195092. Fts5Hash*, /* Hash table to query */
  195093. const char *pTerm, int nTerm /* Query prefix */
  195094. );
  195095. static void sqlite3Fts5HashScanNext(Fts5Hash*);
  195096. static int sqlite3Fts5HashScanEof(Fts5Hash*);
  195097. static void sqlite3Fts5HashScanEntry(Fts5Hash *,
  195098. const char **pzTerm, /* OUT: term (nul-terminated) */
  195099. const u8 **ppDoclist, /* OUT: pointer to doclist */
  195100. int *pnDoclist /* OUT: size of doclist in bytes */
  195101. );
  195102. /*
  195103. ** End of interface to code in fts5_hash.c.
  195104. **************************************************************************/
  195105. /**************************************************************************
  195106. ** Interface to code in fts5_storage.c. fts5_storage.c contains contains
  195107. ** code to access the data stored in the %_content and %_docsize tables.
  195108. */
  195109. #define FTS5_STMT_SCAN_ASC 0 /* SELECT rowid, * FROM ... ORDER BY 1 ASC */
  195110. #define FTS5_STMT_SCAN_DESC 1 /* SELECT rowid, * FROM ... ORDER BY 1 DESC */
  195111. #define FTS5_STMT_LOOKUP 2 /* SELECT rowid, * FROM ... WHERE rowid=? */
  195112. typedef struct Fts5Storage Fts5Storage;
  195113. static int sqlite3Fts5StorageOpen(Fts5Config*, Fts5Index*, int, Fts5Storage**, char**);
  195114. static int sqlite3Fts5StorageClose(Fts5Storage *p);
  195115. static int sqlite3Fts5StorageRename(Fts5Storage*, const char *zName);
  195116. static int sqlite3Fts5DropAll(Fts5Config*);
  195117. static int sqlite3Fts5CreateTable(Fts5Config*, const char*, const char*, int, char **);
  195118. static int sqlite3Fts5StorageDelete(Fts5Storage *p, i64, sqlite3_value**);
  195119. static int sqlite3Fts5StorageContentInsert(Fts5Storage *p, sqlite3_value**, i64*);
  195120. static int sqlite3Fts5StorageIndexInsert(Fts5Storage *p, sqlite3_value**, i64);
  195121. static int sqlite3Fts5StorageIntegrity(Fts5Storage *p);
  195122. static int sqlite3Fts5StorageStmt(Fts5Storage *p, int eStmt, sqlite3_stmt**, char**);
  195123. static void sqlite3Fts5StorageStmtRelease(Fts5Storage *p, int eStmt, sqlite3_stmt*);
  195124. static int sqlite3Fts5StorageDocsize(Fts5Storage *p, i64 iRowid, int *aCol);
  195125. static int sqlite3Fts5StorageSize(Fts5Storage *p, int iCol, i64 *pnAvg);
  195126. static int sqlite3Fts5StorageRowCount(Fts5Storage *p, i64 *pnRow);
  195127. static int sqlite3Fts5StorageSync(Fts5Storage *p);
  195128. static int sqlite3Fts5StorageRollback(Fts5Storage *p);
  195129. static int sqlite3Fts5StorageConfigValue(
  195130. Fts5Storage *p, const char*, sqlite3_value*, int
  195131. );
  195132. static int sqlite3Fts5StorageDeleteAll(Fts5Storage *p);
  195133. static int sqlite3Fts5StorageRebuild(Fts5Storage *p);
  195134. static int sqlite3Fts5StorageOptimize(Fts5Storage *p);
  195135. static int sqlite3Fts5StorageMerge(Fts5Storage *p, int nMerge);
  195136. static int sqlite3Fts5StorageReset(Fts5Storage *p);
  195137. /*
  195138. ** End of interface to code in fts5_storage.c.
  195139. **************************************************************************/
  195140. /**************************************************************************
  195141. ** Interface to code in fts5_expr.c.
  195142. */
  195143. typedef struct Fts5Expr Fts5Expr;
  195144. typedef struct Fts5ExprNode Fts5ExprNode;
  195145. typedef struct Fts5Parse Fts5Parse;
  195146. typedef struct Fts5Token Fts5Token;
  195147. typedef struct Fts5ExprPhrase Fts5ExprPhrase;
  195148. typedef struct Fts5ExprNearset Fts5ExprNearset;
  195149. struct Fts5Token {
  195150. const char *p; /* Token text (not NULL terminated) */
  195151. int n; /* Size of buffer p in bytes */
  195152. };
  195153. /* Parse a MATCH expression. */
  195154. static int sqlite3Fts5ExprNew(
  195155. Fts5Config *pConfig,
  195156. int iCol, /* Column on LHS of MATCH operator */
  195157. const char *zExpr,
  195158. Fts5Expr **ppNew,
  195159. char **pzErr
  195160. );
  195161. /*
  195162. ** for(rc = sqlite3Fts5ExprFirst(pExpr, pIdx, bDesc);
  195163. ** rc==SQLITE_OK && 0==sqlite3Fts5ExprEof(pExpr);
  195164. ** rc = sqlite3Fts5ExprNext(pExpr)
  195165. ** ){
  195166. ** // The document with rowid iRowid matches the expression!
  195167. ** i64 iRowid = sqlite3Fts5ExprRowid(pExpr);
  195168. ** }
  195169. */
  195170. static int sqlite3Fts5ExprFirst(Fts5Expr*, Fts5Index *pIdx, i64 iMin, int bDesc);
  195171. static int sqlite3Fts5ExprNext(Fts5Expr*, i64 iMax);
  195172. static int sqlite3Fts5ExprEof(Fts5Expr*);
  195173. static i64 sqlite3Fts5ExprRowid(Fts5Expr*);
  195174. static void sqlite3Fts5ExprFree(Fts5Expr*);
  195175. static int sqlite3Fts5ExprAnd(Fts5Expr **pp1, Fts5Expr *p2);
  195176. /* Called during startup to register a UDF with SQLite */
  195177. static int sqlite3Fts5ExprInit(Fts5Global*, sqlite3*);
  195178. static int sqlite3Fts5ExprPhraseCount(Fts5Expr*);
  195179. static int sqlite3Fts5ExprPhraseSize(Fts5Expr*, int iPhrase);
  195180. static int sqlite3Fts5ExprPoslist(Fts5Expr*, int, const u8 **);
  195181. typedef struct Fts5PoslistPopulator Fts5PoslistPopulator;
  195182. static Fts5PoslistPopulator *sqlite3Fts5ExprClearPoslists(Fts5Expr*, int);
  195183. static int sqlite3Fts5ExprPopulatePoslists(
  195184. Fts5Config*, Fts5Expr*, Fts5PoslistPopulator*, int, const char*, int
  195185. );
  195186. static void sqlite3Fts5ExprCheckPoslists(Fts5Expr*, i64);
  195187. static int sqlite3Fts5ExprClonePhrase(Fts5Expr*, int, Fts5Expr**);
  195188. static int sqlite3Fts5ExprPhraseCollist(Fts5Expr *, int, const u8 **, int *);
  195189. /*******************************************
  195190. ** The fts5_expr.c API above this point is used by the other hand-written
  195191. ** C code in this module. The interfaces below this point are called by
  195192. ** the parser code in fts5parse.y. */
  195193. static void sqlite3Fts5ParseError(Fts5Parse *pParse, const char *zFmt, ...);
  195194. static Fts5ExprNode *sqlite3Fts5ParseNode(
  195195. Fts5Parse *pParse,
  195196. int eType,
  195197. Fts5ExprNode *pLeft,
  195198. Fts5ExprNode *pRight,
  195199. Fts5ExprNearset *pNear
  195200. );
  195201. static Fts5ExprNode *sqlite3Fts5ParseImplicitAnd(
  195202. Fts5Parse *pParse,
  195203. Fts5ExprNode *pLeft,
  195204. Fts5ExprNode *pRight
  195205. );
  195206. static Fts5ExprPhrase *sqlite3Fts5ParseTerm(
  195207. Fts5Parse *pParse,
  195208. Fts5ExprPhrase *pPhrase,
  195209. Fts5Token *pToken,
  195210. int bPrefix
  195211. );
  195212. static void sqlite3Fts5ParseSetCaret(Fts5ExprPhrase*);
  195213. static Fts5ExprNearset *sqlite3Fts5ParseNearset(
  195214. Fts5Parse*,
  195215. Fts5ExprNearset*,
  195216. Fts5ExprPhrase*
  195217. );
  195218. static Fts5Colset *sqlite3Fts5ParseColset(
  195219. Fts5Parse*,
  195220. Fts5Colset*,
  195221. Fts5Token *
  195222. );
  195223. static void sqlite3Fts5ParsePhraseFree(Fts5ExprPhrase*);
  195224. static void sqlite3Fts5ParseNearsetFree(Fts5ExprNearset*);
  195225. static void sqlite3Fts5ParseNodeFree(Fts5ExprNode*);
  195226. static void sqlite3Fts5ParseSetDistance(Fts5Parse*, Fts5ExprNearset*, Fts5Token*);
  195227. static void sqlite3Fts5ParseSetColset(Fts5Parse*, Fts5ExprNode*, Fts5Colset*);
  195228. static Fts5Colset *sqlite3Fts5ParseColsetInvert(Fts5Parse*, Fts5Colset*);
  195229. static void sqlite3Fts5ParseFinished(Fts5Parse *pParse, Fts5ExprNode *p);
  195230. static void sqlite3Fts5ParseNear(Fts5Parse *pParse, Fts5Token*);
  195231. /*
  195232. ** End of interface to code in fts5_expr.c.
  195233. **************************************************************************/
  195234. /**************************************************************************
  195235. ** Interface to code in fts5_aux.c.
  195236. */
  195237. static int sqlite3Fts5AuxInit(fts5_api*);
  195238. /*
  195239. ** End of interface to code in fts5_aux.c.
  195240. **************************************************************************/
  195241. /**************************************************************************
  195242. ** Interface to code in fts5_tokenizer.c.
  195243. */
  195244. static int sqlite3Fts5TokenizerInit(fts5_api*);
  195245. /*
  195246. ** End of interface to code in fts5_tokenizer.c.
  195247. **************************************************************************/
  195248. /**************************************************************************
  195249. ** Interface to code in fts5_vocab.c.
  195250. */
  195251. static int sqlite3Fts5VocabInit(Fts5Global*, sqlite3*);
  195252. /*
  195253. ** End of interface to code in fts5_vocab.c.
  195254. **************************************************************************/
  195255. /**************************************************************************
  195256. ** Interface to automatically generated code in fts5_unicode2.c.
  195257. */
  195258. static int sqlite3Fts5UnicodeIsdiacritic(int c);
  195259. static int sqlite3Fts5UnicodeFold(int c, int bRemoveDiacritic);
  195260. static int sqlite3Fts5UnicodeCatParse(const char*, u8*);
  195261. static int sqlite3Fts5UnicodeCategory(u32 iCode);
  195262. static void sqlite3Fts5UnicodeAscii(u8*, u8*);
  195263. /*
  195264. ** End of interface to code in fts5_unicode2.c.
  195265. **************************************************************************/
  195266. #endif
  195267. #define FTS5_OR 1
  195268. #define FTS5_AND 2
  195269. #define FTS5_NOT 3
  195270. #define FTS5_TERM 4
  195271. #define FTS5_COLON 5
  195272. #define FTS5_MINUS 6
  195273. #define FTS5_LCP 7
  195274. #define FTS5_RCP 8
  195275. #define FTS5_STRING 9
  195276. #define FTS5_LP 10
  195277. #define FTS5_RP 11
  195278. #define FTS5_CARET 12
  195279. #define FTS5_COMMA 13
  195280. #define FTS5_PLUS 14
  195281. #define FTS5_STAR 15
  195282. /*
  195283. ** 2000-05-29
  195284. **
  195285. ** The author disclaims copyright to this source code. In place of
  195286. ** a legal notice, here is a blessing:
  195287. **
  195288. ** May you do good and not evil.
  195289. ** May you find forgiveness for yourself and forgive others.
  195290. ** May you share freely, never taking more than you give.
  195291. **
  195292. *************************************************************************
  195293. ** Driver template for the LEMON parser generator.
  195294. **
  195295. ** The "lemon" program processes an LALR(1) input grammar file, then uses
  195296. ** this template to construct a parser. The "lemon" program inserts text
  195297. ** at each "%%" line. Also, any "P-a-r-s-e" identifer prefix (without the
  195298. ** interstitial "-" characters) contained in this template is changed into
  195299. ** the value of the %name directive from the grammar. Otherwise, the content
  195300. ** of this template is copied straight through into the generate parser
  195301. ** source file.
  195302. **
  195303. ** The following is the concatenation of all %include directives from the
  195304. ** input grammar file:
  195305. */
  195306. /* #include <stdio.h> */
  195307. /* #include <assert.h> */
  195308. /************ Begin %include sections from the grammar ************************/
  195309. /* #include "fts5Int.h" */
  195310. /* #include "fts5parse.h" */
  195311. /*
  195312. ** Disable all error recovery processing in the parser push-down
  195313. ** automaton.
  195314. */
  195315. #define fts5YYNOERRORRECOVERY 1
  195316. /*
  195317. ** Make fts5yytestcase() the same as testcase()
  195318. */
  195319. #define fts5yytestcase(X) testcase(X)
  195320. /*
  195321. ** Indicate that sqlite3ParserFree() will never be called with a null
  195322. ** pointer.
  195323. */
  195324. #define fts5YYPARSEFREENOTNULL 1
  195325. /*
  195326. ** Alternative datatype for the argument to the malloc() routine passed
  195327. ** into sqlite3ParserAlloc(). The default is size_t.
  195328. */
  195329. #define fts5YYMALLOCARGTYPE u64
  195330. /**************** End of %include directives **********************************/
  195331. /* These constants specify the various numeric values for terminal symbols
  195332. ** in a format understandable to "makeheaders". This section is blank unless
  195333. ** "lemon" is run with the "-m" command-line option.
  195334. ***************** Begin makeheaders token definitions *************************/
  195335. /**************** End makeheaders token definitions ***************************/
  195336. /* The next sections is a series of control #defines.
  195337. ** various aspects of the generated parser.
  195338. ** fts5YYCODETYPE is the data type used to store the integer codes
  195339. ** that represent terminal and non-terminal symbols.
  195340. ** "unsigned char" is used if there are fewer than
  195341. ** 256 symbols. Larger types otherwise.
  195342. ** fts5YYNOCODE is a number of type fts5YYCODETYPE that is not used for
  195343. ** any terminal or nonterminal symbol.
  195344. ** fts5YYFALLBACK If defined, this indicates that one or more tokens
  195345. ** (also known as: "terminal symbols") have fall-back
  195346. ** values which should be used if the original symbol
  195347. ** would not parse. This permits keywords to sometimes
  195348. ** be used as identifiers, for example.
  195349. ** fts5YYACTIONTYPE is the data type used for "action codes" - numbers
  195350. ** that indicate what to do in response to the next
  195351. ** token.
  195352. ** sqlite3Fts5ParserFTS5TOKENTYPE is the data type used for minor type for terminal
  195353. ** symbols. Background: A "minor type" is a semantic
  195354. ** value associated with a terminal or non-terminal
  195355. ** symbols. For example, for an "ID" terminal symbol,
  195356. ** the minor type might be the name of the identifier.
  195357. ** Each non-terminal can have a different minor type.
  195358. ** Terminal symbols all have the same minor type, though.
  195359. ** This macros defines the minor type for terminal
  195360. ** symbols.
  195361. ** fts5YYMINORTYPE is the data type used for all minor types.
  195362. ** This is typically a union of many types, one of
  195363. ** which is sqlite3Fts5ParserFTS5TOKENTYPE. The entry in the union
  195364. ** for terminal symbols is called "fts5yy0".
  195365. ** fts5YYSTACKDEPTH is the maximum depth of the parser's stack. If
  195366. ** zero the stack is dynamically sized using realloc()
  195367. ** sqlite3Fts5ParserARG_SDECL A static variable declaration for the %extra_argument
  195368. ** sqlite3Fts5ParserARG_PDECL A parameter declaration for the %extra_argument
  195369. ** sqlite3Fts5ParserARG_PARAM Code to pass %extra_argument as a subroutine parameter
  195370. ** sqlite3Fts5ParserARG_STORE Code to store %extra_argument into fts5yypParser
  195371. ** sqlite3Fts5ParserARG_FETCH Code to extract %extra_argument from fts5yypParser
  195372. ** sqlite3Fts5ParserCTX_* As sqlite3Fts5ParserARG_ except for %extra_context
  195373. ** fts5YYERRORSYMBOL is the code number of the error symbol. If not
  195374. ** defined, then do no error processing.
  195375. ** fts5YYNSTATE the combined number of states.
  195376. ** fts5YYNRULE the number of rules in the grammar
  195377. ** fts5YYNFTS5TOKEN Number of terminal symbols
  195378. ** fts5YY_MAX_SHIFT Maximum value for shift actions
  195379. ** fts5YY_MIN_SHIFTREDUCE Minimum value for shift-reduce actions
  195380. ** fts5YY_MAX_SHIFTREDUCE Maximum value for shift-reduce actions
  195381. ** fts5YY_ERROR_ACTION The fts5yy_action[] code for syntax error
  195382. ** fts5YY_ACCEPT_ACTION The fts5yy_action[] code for accept
  195383. ** fts5YY_NO_ACTION The fts5yy_action[] code for no-op
  195384. ** fts5YY_MIN_REDUCE Minimum value for reduce actions
  195385. ** fts5YY_MAX_REDUCE Maximum value for reduce actions
  195386. */
  195387. #ifndef INTERFACE
  195388. # define INTERFACE 1
  195389. #endif
  195390. /************* Begin control #defines *****************************************/
  195391. #define fts5YYCODETYPE unsigned char
  195392. #define fts5YYNOCODE 27
  195393. #define fts5YYACTIONTYPE unsigned char
  195394. #define sqlite3Fts5ParserFTS5TOKENTYPE Fts5Token
  195395. typedef union {
  195396. int fts5yyinit;
  195397. sqlite3Fts5ParserFTS5TOKENTYPE fts5yy0;
  195398. int fts5yy4;
  195399. Fts5Colset* fts5yy11;
  195400. Fts5ExprNode* fts5yy24;
  195401. Fts5ExprNearset* fts5yy46;
  195402. Fts5ExprPhrase* fts5yy53;
  195403. } fts5YYMINORTYPE;
  195404. #ifndef fts5YYSTACKDEPTH
  195405. #define fts5YYSTACKDEPTH 100
  195406. #endif
  195407. #define sqlite3Fts5ParserARG_SDECL Fts5Parse *pParse;
  195408. #define sqlite3Fts5ParserARG_PDECL ,Fts5Parse *pParse
  195409. #define sqlite3Fts5ParserARG_PARAM ,pParse
  195410. #define sqlite3Fts5ParserARG_FETCH Fts5Parse *pParse=fts5yypParser->pParse;
  195411. #define sqlite3Fts5ParserARG_STORE fts5yypParser->pParse=pParse;
  195412. #define sqlite3Fts5ParserCTX_SDECL
  195413. #define sqlite3Fts5ParserCTX_PDECL
  195414. #define sqlite3Fts5ParserCTX_PARAM
  195415. #define sqlite3Fts5ParserCTX_FETCH
  195416. #define sqlite3Fts5ParserCTX_STORE
  195417. #define fts5YYNSTATE 35
  195418. #define fts5YYNRULE 28
  195419. #define fts5YYNRULE_WITH_ACTION 28
  195420. #define fts5YYNFTS5TOKEN 16
  195421. #define fts5YY_MAX_SHIFT 34
  195422. #define fts5YY_MIN_SHIFTREDUCE 52
  195423. #define fts5YY_MAX_SHIFTREDUCE 79
  195424. #define fts5YY_ERROR_ACTION 80
  195425. #define fts5YY_ACCEPT_ACTION 81
  195426. #define fts5YY_NO_ACTION 82
  195427. #define fts5YY_MIN_REDUCE 83
  195428. #define fts5YY_MAX_REDUCE 110
  195429. /************* End control #defines *******************************************/
  195430. #define fts5YY_NLOOKAHEAD ((int)(sizeof(fts5yy_lookahead)/sizeof(fts5yy_lookahead[0])))
  195431. /* Define the fts5yytestcase() macro to be a no-op if is not already defined
  195432. ** otherwise.
  195433. **
  195434. ** Applications can choose to define fts5yytestcase() in the %include section
  195435. ** to a macro that can assist in verifying code coverage. For production
  195436. ** code the fts5yytestcase() macro should be turned off. But it is useful
  195437. ** for testing.
  195438. */
  195439. #ifndef fts5yytestcase
  195440. # define fts5yytestcase(X)
  195441. #endif
  195442. /* Next are the tables used to determine what action to take based on the
  195443. ** current state and lookahead token. These tables are used to implement
  195444. ** functions that take a state number and lookahead value and return an
  195445. ** action integer.
  195446. **
  195447. ** Suppose the action integer is N. Then the action is determined as
  195448. ** follows
  195449. **
  195450. ** 0 <= N <= fts5YY_MAX_SHIFT Shift N. That is, push the lookahead
  195451. ** token onto the stack and goto state N.
  195452. **
  195453. ** N between fts5YY_MIN_SHIFTREDUCE Shift to an arbitrary state then
  195454. ** and fts5YY_MAX_SHIFTREDUCE reduce by rule N-fts5YY_MIN_SHIFTREDUCE.
  195455. **
  195456. ** N == fts5YY_ERROR_ACTION A syntax error has occurred.
  195457. **
  195458. ** N == fts5YY_ACCEPT_ACTION The parser accepts its input.
  195459. **
  195460. ** N == fts5YY_NO_ACTION No such action. Denotes unused
  195461. ** slots in the fts5yy_action[] table.
  195462. **
  195463. ** N between fts5YY_MIN_REDUCE Reduce by rule N-fts5YY_MIN_REDUCE
  195464. ** and fts5YY_MAX_REDUCE
  195465. **
  195466. ** The action table is constructed as a single large table named fts5yy_action[].
  195467. ** Given state S and lookahead X, the action is computed as either:
  195468. **
  195469. ** (A) N = fts5yy_action[ fts5yy_shift_ofst[S] + X ]
  195470. ** (B) N = fts5yy_default[S]
  195471. **
  195472. ** The (A) formula is preferred. The B formula is used instead if
  195473. ** fts5yy_lookahead[fts5yy_shift_ofst[S]+X] is not equal to X.
  195474. **
  195475. ** The formulas above are for computing the action when the lookahead is
  195476. ** a terminal symbol. If the lookahead is a non-terminal (as occurs after
  195477. ** a reduce action) then the fts5yy_reduce_ofst[] array is used in place of
  195478. ** the fts5yy_shift_ofst[] array.
  195479. **
  195480. ** The following are the tables generated in this section:
  195481. **
  195482. ** fts5yy_action[] A single table containing all actions.
  195483. ** fts5yy_lookahead[] A table containing the lookahead for each entry in
  195484. ** fts5yy_action. Used to detect hash collisions.
  195485. ** fts5yy_shift_ofst[] For each state, the offset into fts5yy_action for
  195486. ** shifting terminals.
  195487. ** fts5yy_reduce_ofst[] For each state, the offset into fts5yy_action for
  195488. ** shifting non-terminals after a reduce.
  195489. ** fts5yy_default[] Default action for each state.
  195490. **
  195491. *********** Begin parsing tables **********************************************/
  195492. #define fts5YY_ACTTAB_COUNT (105)
  195493. static const fts5YYACTIONTYPE fts5yy_action[] = {
  195494. /* 0 */ 81, 20, 96, 6, 28, 99, 98, 26, 26, 18,
  195495. /* 10 */ 96, 6, 28, 17, 98, 56, 26, 19, 96, 6,
  195496. /* 20 */ 28, 14, 98, 14, 26, 31, 92, 96, 6, 28,
  195497. /* 30 */ 108, 98, 25, 26, 21, 96, 6, 28, 78, 98,
  195498. /* 40 */ 58, 26, 29, 96, 6, 28, 107, 98, 22, 26,
  195499. /* 50 */ 24, 16, 12, 11, 1, 13, 13, 24, 16, 23,
  195500. /* 60 */ 11, 33, 34, 13, 97, 8, 27, 32, 98, 7,
  195501. /* 70 */ 26, 3, 4, 5, 3, 4, 5, 3, 83, 4,
  195502. /* 80 */ 5, 3, 63, 5, 3, 62, 12, 2, 86, 13,
  195503. /* 90 */ 9, 30, 10, 10, 54, 57, 75, 78, 78, 53,
  195504. /* 100 */ 57, 15, 82, 82, 71,
  195505. };
  195506. static const fts5YYCODETYPE fts5yy_lookahead[] = {
  195507. /* 0 */ 16, 17, 18, 19, 20, 22, 22, 24, 24, 17,
  195508. /* 10 */ 18, 19, 20, 7, 22, 9, 24, 17, 18, 19,
  195509. /* 20 */ 20, 9, 22, 9, 24, 13, 17, 18, 19, 20,
  195510. /* 30 */ 26, 22, 24, 24, 17, 18, 19, 20, 15, 22,
  195511. /* 40 */ 9, 24, 17, 18, 19, 20, 26, 22, 21, 24,
  195512. /* 50 */ 6, 7, 9, 9, 10, 12, 12, 6, 7, 21,
  195513. /* 60 */ 9, 24, 25, 12, 18, 5, 20, 14, 22, 5,
  195514. /* 70 */ 24, 3, 1, 2, 3, 1, 2, 3, 0, 1,
  195515. /* 80 */ 2, 3, 11, 2, 3, 11, 9, 10, 5, 12,
  195516. /* 90 */ 23, 24, 10, 10, 8, 9, 9, 15, 15, 8,
  195517. /* 100 */ 9, 9, 27, 27, 11, 27, 27, 27, 27, 27,
  195518. /* 110 */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  195519. /* 120 */ 27,
  195520. };
  195521. #define fts5YY_SHIFT_COUNT (34)
  195522. #define fts5YY_SHIFT_MIN (0)
  195523. #define fts5YY_SHIFT_MAX (93)
  195524. static const unsigned char fts5yy_shift_ofst[] = {
  195525. /* 0 */ 44, 44, 44, 44, 44, 44, 51, 77, 43, 12,
  195526. /* 10 */ 14, 83, 82, 14, 23, 23, 31, 31, 71, 74,
  195527. /* 20 */ 78, 81, 86, 91, 6, 53, 53, 60, 64, 68,
  195528. /* 30 */ 53, 87, 92, 53, 93,
  195529. };
  195530. #define fts5YY_REDUCE_COUNT (17)
  195531. #define fts5YY_REDUCE_MIN (-17)
  195532. #define fts5YY_REDUCE_MAX (67)
  195533. static const signed char fts5yy_reduce_ofst[] = {
  195534. /* 0 */ -16, -8, 0, 9, 17, 25, 46, -17, -17, 37,
  195535. /* 10 */ 67, 4, 4, 8, 4, 20, 27, 38,
  195536. };
  195537. static const fts5YYACTIONTYPE fts5yy_default[] = {
  195538. /* 0 */ 80, 80, 80, 80, 80, 80, 95, 80, 80, 105,
  195539. /* 10 */ 80, 110, 110, 80, 110, 110, 80, 80, 80, 80,
  195540. /* 20 */ 80, 91, 80, 80, 80, 101, 100, 80, 80, 90,
  195541. /* 30 */ 103, 80, 80, 104, 80,
  195542. };
  195543. /********** End of lemon-generated parsing tables *****************************/
  195544. /* The next table maps tokens (terminal symbols) into fallback tokens.
  195545. ** If a construct like the following:
  195546. **
  195547. ** %fallback ID X Y Z.
  195548. **
  195549. ** appears in the grammar, then ID becomes a fallback token for X, Y,
  195550. ** and Z. Whenever one of the tokens X, Y, or Z is input to the parser
  195551. ** but it does not parse, the type of the token is changed to ID and
  195552. ** the parse is retried before an error is thrown.
  195553. **
  195554. ** This feature can be used, for example, to cause some keywords in a language
  195555. ** to revert to identifiers if they keyword does not apply in the context where
  195556. ** it appears.
  195557. */
  195558. #ifdef fts5YYFALLBACK
  195559. static const fts5YYCODETYPE fts5yyFallback[] = {
  195560. };
  195561. #endif /* fts5YYFALLBACK */
  195562. /* The following structure represents a single element of the
  195563. ** parser's stack. Information stored includes:
  195564. **
  195565. ** + The state number for the parser at this level of the stack.
  195566. **
  195567. ** + The value of the token stored at this level of the stack.
  195568. ** (In other words, the "major" token.)
  195569. **
  195570. ** + The semantic value stored at this level of the stack. This is
  195571. ** the information used by the action routines in the grammar.
  195572. ** It is sometimes called the "minor" token.
  195573. **
  195574. ** After the "shift" half of a SHIFTREDUCE action, the stateno field
  195575. ** actually contains the reduce action for the second half of the
  195576. ** SHIFTREDUCE.
  195577. */
  195578. struct fts5yyStackEntry {
  195579. fts5YYACTIONTYPE stateno; /* The state-number, or reduce action in SHIFTREDUCE */
  195580. fts5YYCODETYPE major; /* The major token value. This is the code
  195581. ** number for the token at this stack level */
  195582. fts5YYMINORTYPE minor; /* The user-supplied minor token value. This
  195583. ** is the value of the token */
  195584. };
  195585. typedef struct fts5yyStackEntry fts5yyStackEntry;
  195586. /* The state of the parser is completely contained in an instance of
  195587. ** the following structure */
  195588. struct fts5yyParser {
  195589. fts5yyStackEntry *fts5yytos; /* Pointer to top element of the stack */
  195590. #ifdef fts5YYTRACKMAXSTACKDEPTH
  195591. int fts5yyhwm; /* High-water mark of the stack */
  195592. #endif
  195593. #ifndef fts5YYNOERRORRECOVERY
  195594. int fts5yyerrcnt; /* Shifts left before out of the error */
  195595. #endif
  195596. sqlite3Fts5ParserARG_SDECL /* A place to hold %extra_argument */
  195597. sqlite3Fts5ParserCTX_SDECL /* A place to hold %extra_context */
  195598. #if fts5YYSTACKDEPTH<=0
  195599. int fts5yystksz; /* Current side of the stack */
  195600. fts5yyStackEntry *fts5yystack; /* The parser's stack */
  195601. fts5yyStackEntry fts5yystk0; /* First stack entry */
  195602. #else
  195603. fts5yyStackEntry fts5yystack[fts5YYSTACKDEPTH]; /* The parser's stack */
  195604. fts5yyStackEntry *fts5yystackEnd; /* Last entry in the stack */
  195605. #endif
  195606. };
  195607. typedef struct fts5yyParser fts5yyParser;
  195608. #ifndef NDEBUG
  195609. /* #include <stdio.h> */
  195610. static FILE *fts5yyTraceFILE = 0;
  195611. static char *fts5yyTracePrompt = 0;
  195612. #endif /* NDEBUG */
  195613. #ifndef NDEBUG
  195614. /*
  195615. ** Turn parser tracing on by giving a stream to which to write the trace
  195616. ** and a prompt to preface each trace message. Tracing is turned off
  195617. ** by making either argument NULL
  195618. **
  195619. ** Inputs:
  195620. ** <ul>
  195621. ** <li> A FILE* to which trace output should be written.
  195622. ** If NULL, then tracing is turned off.
  195623. ** <li> A prefix string written at the beginning of every
  195624. ** line of trace output. If NULL, then tracing is
  195625. ** turned off.
  195626. ** </ul>
  195627. **
  195628. ** Outputs:
  195629. ** None.
  195630. */
  195631. static void sqlite3Fts5ParserTrace(FILE *TraceFILE, char *zTracePrompt){
  195632. fts5yyTraceFILE = TraceFILE;
  195633. fts5yyTracePrompt = zTracePrompt;
  195634. if( fts5yyTraceFILE==0 ) fts5yyTracePrompt = 0;
  195635. else if( fts5yyTracePrompt==0 ) fts5yyTraceFILE = 0;
  195636. }
  195637. #endif /* NDEBUG */
  195638. #if defined(fts5YYCOVERAGE) || !defined(NDEBUG)
  195639. /* For tracing shifts, the names of all terminals and nonterminals
  195640. ** are required. The following table supplies these names */
  195641. static const char *const fts5yyTokenName[] = {
  195642. /* 0 */ "$",
  195643. /* 1 */ "OR",
  195644. /* 2 */ "AND",
  195645. /* 3 */ "NOT",
  195646. /* 4 */ "TERM",
  195647. /* 5 */ "COLON",
  195648. /* 6 */ "MINUS",
  195649. /* 7 */ "LCP",
  195650. /* 8 */ "RCP",
  195651. /* 9 */ "STRING",
  195652. /* 10 */ "LP",
  195653. /* 11 */ "RP",
  195654. /* 12 */ "CARET",
  195655. /* 13 */ "COMMA",
  195656. /* 14 */ "PLUS",
  195657. /* 15 */ "STAR",
  195658. /* 16 */ "input",
  195659. /* 17 */ "expr",
  195660. /* 18 */ "cnearset",
  195661. /* 19 */ "exprlist",
  195662. /* 20 */ "colset",
  195663. /* 21 */ "colsetlist",
  195664. /* 22 */ "nearset",
  195665. /* 23 */ "nearphrases",
  195666. /* 24 */ "phrase",
  195667. /* 25 */ "neardist_opt",
  195668. /* 26 */ "star_opt",
  195669. };
  195670. #endif /* defined(fts5YYCOVERAGE) || !defined(NDEBUG) */
  195671. #ifndef NDEBUG
  195672. /* For tracing reduce actions, the names of all rules are required.
  195673. */
  195674. static const char *const fts5yyRuleName[] = {
  195675. /* 0 */ "input ::= expr",
  195676. /* 1 */ "colset ::= MINUS LCP colsetlist RCP",
  195677. /* 2 */ "colset ::= LCP colsetlist RCP",
  195678. /* 3 */ "colset ::= STRING",
  195679. /* 4 */ "colset ::= MINUS STRING",
  195680. /* 5 */ "colsetlist ::= colsetlist STRING",
  195681. /* 6 */ "colsetlist ::= STRING",
  195682. /* 7 */ "expr ::= expr AND expr",
  195683. /* 8 */ "expr ::= expr OR expr",
  195684. /* 9 */ "expr ::= expr NOT expr",
  195685. /* 10 */ "expr ::= colset COLON LP expr RP",
  195686. /* 11 */ "expr ::= LP expr RP",
  195687. /* 12 */ "expr ::= exprlist",
  195688. /* 13 */ "exprlist ::= cnearset",
  195689. /* 14 */ "exprlist ::= exprlist cnearset",
  195690. /* 15 */ "cnearset ::= nearset",
  195691. /* 16 */ "cnearset ::= colset COLON nearset",
  195692. /* 17 */ "nearset ::= phrase",
  195693. /* 18 */ "nearset ::= CARET phrase",
  195694. /* 19 */ "nearset ::= STRING LP nearphrases neardist_opt RP",
  195695. /* 20 */ "nearphrases ::= phrase",
  195696. /* 21 */ "nearphrases ::= nearphrases phrase",
  195697. /* 22 */ "neardist_opt ::=",
  195698. /* 23 */ "neardist_opt ::= COMMA STRING",
  195699. /* 24 */ "phrase ::= phrase PLUS STRING star_opt",
  195700. /* 25 */ "phrase ::= STRING star_opt",
  195701. /* 26 */ "star_opt ::= STAR",
  195702. /* 27 */ "star_opt ::=",
  195703. };
  195704. #endif /* NDEBUG */
  195705. #if fts5YYSTACKDEPTH<=0
  195706. /*
  195707. ** Try to increase the size of the parser stack. Return the number
  195708. ** of errors. Return 0 on success.
  195709. */
  195710. static int fts5yyGrowStack(fts5yyParser *p){
  195711. int newSize;
  195712. int idx;
  195713. fts5yyStackEntry *pNew;
  195714. newSize = p->fts5yystksz*2 + 100;
  195715. idx = p->fts5yytos ? (int)(p->fts5yytos - p->fts5yystack) : 0;
  195716. if( p->fts5yystack==&p->fts5yystk0 ){
  195717. pNew = malloc(newSize*sizeof(pNew[0]));
  195718. if( pNew ) pNew[0] = p->fts5yystk0;
  195719. }else{
  195720. pNew = realloc(p->fts5yystack, newSize*sizeof(pNew[0]));
  195721. }
  195722. if( pNew ){
  195723. p->fts5yystack = pNew;
  195724. p->fts5yytos = &p->fts5yystack[idx];
  195725. #ifndef NDEBUG
  195726. if( fts5yyTraceFILE ){
  195727. fprintf(fts5yyTraceFILE,"%sStack grows from %d to %d entries.\n",
  195728. fts5yyTracePrompt, p->fts5yystksz, newSize);
  195729. }
  195730. #endif
  195731. p->fts5yystksz = newSize;
  195732. }
  195733. return pNew==0;
  195734. }
  195735. #endif
  195736. /* Datatype of the argument to the memory allocated passed as the
  195737. ** second argument to sqlite3Fts5ParserAlloc() below. This can be changed by
  195738. ** putting an appropriate #define in the %include section of the input
  195739. ** grammar.
  195740. */
  195741. #ifndef fts5YYMALLOCARGTYPE
  195742. # define fts5YYMALLOCARGTYPE size_t
  195743. #endif
  195744. /* Initialize a new parser that has already been allocated.
  195745. */
  195746. static void sqlite3Fts5ParserInit(void *fts5yypRawParser sqlite3Fts5ParserCTX_PDECL){
  195747. fts5yyParser *fts5yypParser = (fts5yyParser*)fts5yypRawParser;
  195748. sqlite3Fts5ParserCTX_STORE
  195749. #ifdef fts5YYTRACKMAXSTACKDEPTH
  195750. fts5yypParser->fts5yyhwm = 0;
  195751. #endif
  195752. #if fts5YYSTACKDEPTH<=0
  195753. fts5yypParser->fts5yytos = NULL;
  195754. fts5yypParser->fts5yystack = NULL;
  195755. fts5yypParser->fts5yystksz = 0;
  195756. if( fts5yyGrowStack(fts5yypParser) ){
  195757. fts5yypParser->fts5yystack = &fts5yypParser->fts5yystk0;
  195758. fts5yypParser->fts5yystksz = 1;
  195759. }
  195760. #endif
  195761. #ifndef fts5YYNOERRORRECOVERY
  195762. fts5yypParser->fts5yyerrcnt = -1;
  195763. #endif
  195764. fts5yypParser->fts5yytos = fts5yypParser->fts5yystack;
  195765. fts5yypParser->fts5yystack[0].stateno = 0;
  195766. fts5yypParser->fts5yystack[0].major = 0;
  195767. #if fts5YYSTACKDEPTH>0
  195768. fts5yypParser->fts5yystackEnd = &fts5yypParser->fts5yystack[fts5YYSTACKDEPTH-1];
  195769. #endif
  195770. }
  195771. #ifndef sqlite3Fts5Parser_ENGINEALWAYSONSTACK
  195772. /*
  195773. ** This function allocates a new parser.
  195774. ** The only argument is a pointer to a function which works like
  195775. ** malloc.
  195776. **
  195777. ** Inputs:
  195778. ** A pointer to the function used to allocate memory.
  195779. **
  195780. ** Outputs:
  195781. ** A pointer to a parser. This pointer is used in subsequent calls
  195782. ** to sqlite3Fts5Parser and sqlite3Fts5ParserFree.
  195783. */
  195784. static void *sqlite3Fts5ParserAlloc(void *(*mallocProc)(fts5YYMALLOCARGTYPE) sqlite3Fts5ParserCTX_PDECL){
  195785. fts5yyParser *fts5yypParser;
  195786. fts5yypParser = (fts5yyParser*)(*mallocProc)( (fts5YYMALLOCARGTYPE)sizeof(fts5yyParser) );
  195787. if( fts5yypParser ){
  195788. sqlite3Fts5ParserCTX_STORE
  195789. sqlite3Fts5ParserInit(fts5yypParser sqlite3Fts5ParserCTX_PARAM);
  195790. }
  195791. return (void*)fts5yypParser;
  195792. }
  195793. #endif /* sqlite3Fts5Parser_ENGINEALWAYSONSTACK */
  195794. /* The following function deletes the "minor type" or semantic value
  195795. ** associated with a symbol. The symbol can be either a terminal
  195796. ** or nonterminal. "fts5yymajor" is the symbol code, and "fts5yypminor" is
  195797. ** a pointer to the value to be deleted. The code used to do the
  195798. ** deletions is derived from the %destructor and/or %token_destructor
  195799. ** directives of the input grammar.
  195800. */
  195801. static void fts5yy_destructor(
  195802. fts5yyParser *fts5yypParser, /* The parser */
  195803. fts5YYCODETYPE fts5yymajor, /* Type code for object to destroy */
  195804. fts5YYMINORTYPE *fts5yypminor /* The object to be destroyed */
  195805. ){
  195806. sqlite3Fts5ParserARG_FETCH
  195807. sqlite3Fts5ParserCTX_FETCH
  195808. switch( fts5yymajor ){
  195809. /* Here is inserted the actions which take place when a
  195810. ** terminal or non-terminal is destroyed. This can happen
  195811. ** when the symbol is popped from the stack during a
  195812. ** reduce or during error processing or when a parser is
  195813. ** being destroyed before it is finished parsing.
  195814. **
  195815. ** Note: during a reduce, the only symbols destroyed are those
  195816. ** which appear on the RHS of the rule, but which are *not* used
  195817. ** inside the C code.
  195818. */
  195819. /********* Begin destructor definitions ***************************************/
  195820. case 16: /* input */
  195821. {
  195822. (void)pParse;
  195823. }
  195824. break;
  195825. case 17: /* expr */
  195826. case 18: /* cnearset */
  195827. case 19: /* exprlist */
  195828. {
  195829. sqlite3Fts5ParseNodeFree((fts5yypminor->fts5yy24));
  195830. }
  195831. break;
  195832. case 20: /* colset */
  195833. case 21: /* colsetlist */
  195834. {
  195835. sqlite3_free((fts5yypminor->fts5yy11));
  195836. }
  195837. break;
  195838. case 22: /* nearset */
  195839. case 23: /* nearphrases */
  195840. {
  195841. sqlite3Fts5ParseNearsetFree((fts5yypminor->fts5yy46));
  195842. }
  195843. break;
  195844. case 24: /* phrase */
  195845. {
  195846. sqlite3Fts5ParsePhraseFree((fts5yypminor->fts5yy53));
  195847. }
  195848. break;
  195849. /********* End destructor definitions *****************************************/
  195850. default: break; /* If no destructor action specified: do nothing */
  195851. }
  195852. }
  195853. /*
  195854. ** Pop the parser's stack once.
  195855. **
  195856. ** If there is a destructor routine associated with the token which
  195857. ** is popped from the stack, then call it.
  195858. */
  195859. static void fts5yy_pop_parser_stack(fts5yyParser *pParser){
  195860. fts5yyStackEntry *fts5yytos;
  195861. assert( pParser->fts5yytos!=0 );
  195862. assert( pParser->fts5yytos > pParser->fts5yystack );
  195863. fts5yytos = pParser->fts5yytos--;
  195864. #ifndef NDEBUG
  195865. if( fts5yyTraceFILE ){
  195866. fprintf(fts5yyTraceFILE,"%sPopping %s\n",
  195867. fts5yyTracePrompt,
  195868. fts5yyTokenName[fts5yytos->major]);
  195869. }
  195870. #endif
  195871. fts5yy_destructor(pParser, fts5yytos->major, &fts5yytos->minor);
  195872. }
  195873. /*
  195874. ** Clear all secondary memory allocations from the parser
  195875. */
  195876. static void sqlite3Fts5ParserFinalize(void *p){
  195877. fts5yyParser *pParser = (fts5yyParser*)p;
  195878. while( pParser->fts5yytos>pParser->fts5yystack ) fts5yy_pop_parser_stack(pParser);
  195879. #if fts5YYSTACKDEPTH<=0
  195880. if( pParser->fts5yystack!=&pParser->fts5yystk0 ) free(pParser->fts5yystack);
  195881. #endif
  195882. }
  195883. #ifndef sqlite3Fts5Parser_ENGINEALWAYSONSTACK
  195884. /*
  195885. ** Deallocate and destroy a parser. Destructors are called for
  195886. ** all stack elements before shutting the parser down.
  195887. **
  195888. ** If the fts5YYPARSEFREENEVERNULL macro exists (for example because it
  195889. ** is defined in a %include section of the input grammar) then it is
  195890. ** assumed that the input pointer is never NULL.
  195891. */
  195892. static void sqlite3Fts5ParserFree(
  195893. void *p, /* The parser to be deleted */
  195894. void (*freeProc)(void*) /* Function used to reclaim memory */
  195895. ){
  195896. #ifndef fts5YYPARSEFREENEVERNULL
  195897. if( p==0 ) return;
  195898. #endif
  195899. sqlite3Fts5ParserFinalize(p);
  195900. (*freeProc)(p);
  195901. }
  195902. #endif /* sqlite3Fts5Parser_ENGINEALWAYSONSTACK */
  195903. /*
  195904. ** Return the peak depth of the stack for a parser.
  195905. */
  195906. #ifdef fts5YYTRACKMAXSTACKDEPTH
  195907. static int sqlite3Fts5ParserStackPeak(void *p){
  195908. fts5yyParser *pParser = (fts5yyParser*)p;
  195909. return pParser->fts5yyhwm;
  195910. }
  195911. #endif
  195912. /* This array of booleans keeps track of the parser statement
  195913. ** coverage. The element fts5yycoverage[X][Y] is set when the parser
  195914. ** is in state X and has a lookahead token Y. In a well-tested
  195915. ** systems, every element of this matrix should end up being set.
  195916. */
  195917. #if defined(fts5YYCOVERAGE)
  195918. static unsigned char fts5yycoverage[fts5YYNSTATE][fts5YYNFTS5TOKEN];
  195919. #endif
  195920. /*
  195921. ** Write into out a description of every state/lookahead combination that
  195922. **
  195923. ** (1) has not been used by the parser, and
  195924. ** (2) is not a syntax error.
  195925. **
  195926. ** Return the number of missed state/lookahead combinations.
  195927. */
  195928. #if defined(fts5YYCOVERAGE)
  195929. static int sqlite3Fts5ParserCoverage(FILE *out){
  195930. int stateno, iLookAhead, i;
  195931. int nMissed = 0;
  195932. for(stateno=0; stateno<fts5YYNSTATE; stateno++){
  195933. i = fts5yy_shift_ofst[stateno];
  195934. for(iLookAhead=0; iLookAhead<fts5YYNFTS5TOKEN; iLookAhead++){
  195935. if( fts5yy_lookahead[i+iLookAhead]!=iLookAhead ) continue;
  195936. if( fts5yycoverage[stateno][iLookAhead]==0 ) nMissed++;
  195937. if( out ){
  195938. fprintf(out,"State %d lookahead %s %s\n", stateno,
  195939. fts5yyTokenName[iLookAhead],
  195940. fts5yycoverage[stateno][iLookAhead] ? "ok" : "missed");
  195941. }
  195942. }
  195943. }
  195944. return nMissed;
  195945. }
  195946. #endif
  195947. /*
  195948. ** Find the appropriate action for a parser given the terminal
  195949. ** look-ahead token iLookAhead.
  195950. */
  195951. static fts5YYACTIONTYPE fts5yy_find_shift_action(
  195952. fts5YYCODETYPE iLookAhead, /* The look-ahead token */
  195953. fts5YYACTIONTYPE stateno /* Current state number */
  195954. ){
  195955. int i;
  195956. if( stateno>fts5YY_MAX_SHIFT ) return stateno;
  195957. assert( stateno <= fts5YY_SHIFT_COUNT );
  195958. #if defined(fts5YYCOVERAGE)
  195959. fts5yycoverage[stateno][iLookAhead] = 1;
  195960. #endif
  195961. do{
  195962. i = fts5yy_shift_ofst[stateno];
  195963. assert( i>=0 );
  195964. assert( i<=fts5YY_ACTTAB_COUNT );
  195965. assert( i+fts5YYNFTS5TOKEN<=(int)fts5YY_NLOOKAHEAD );
  195966. assert( iLookAhead!=fts5YYNOCODE );
  195967. assert( iLookAhead < fts5YYNFTS5TOKEN );
  195968. i += iLookAhead;
  195969. assert( i<(int)fts5YY_NLOOKAHEAD );
  195970. if( fts5yy_lookahead[i]!=iLookAhead ){
  195971. #ifdef fts5YYFALLBACK
  195972. fts5YYCODETYPE iFallback; /* Fallback token */
  195973. assert( iLookAhead<sizeof(fts5yyFallback)/sizeof(fts5yyFallback[0]) );
  195974. iFallback = fts5yyFallback[iLookAhead];
  195975. if( iFallback!=0 ){
  195976. #ifndef NDEBUG
  195977. if( fts5yyTraceFILE ){
  195978. fprintf(fts5yyTraceFILE, "%sFALLBACK %s => %s\n",
  195979. fts5yyTracePrompt, fts5yyTokenName[iLookAhead], fts5yyTokenName[iFallback]);
  195980. }
  195981. #endif
  195982. assert( fts5yyFallback[iFallback]==0 ); /* Fallback loop must terminate */
  195983. iLookAhead = iFallback;
  195984. continue;
  195985. }
  195986. #endif
  195987. #ifdef fts5YYWILDCARD
  195988. {
  195989. int j = i - iLookAhead + fts5YYWILDCARD;
  195990. assert( j<(int)(sizeof(fts5yy_lookahead)/sizeof(fts5yy_lookahead[0])) );
  195991. if( fts5yy_lookahead[j]==fts5YYWILDCARD && iLookAhead>0 ){
  195992. #ifndef NDEBUG
  195993. if( fts5yyTraceFILE ){
  195994. fprintf(fts5yyTraceFILE, "%sWILDCARD %s => %s\n",
  195995. fts5yyTracePrompt, fts5yyTokenName[iLookAhead],
  195996. fts5yyTokenName[fts5YYWILDCARD]);
  195997. }
  195998. #endif /* NDEBUG */
  195999. return fts5yy_action[j];
  196000. }
  196001. }
  196002. #endif /* fts5YYWILDCARD */
  196003. return fts5yy_default[stateno];
  196004. }else{
  196005. assert( i>=0 && i<sizeof(fts5yy_action)/sizeof(fts5yy_action[0]) );
  196006. return fts5yy_action[i];
  196007. }
  196008. }while(1);
  196009. }
  196010. /*
  196011. ** Find the appropriate action for a parser given the non-terminal
  196012. ** look-ahead token iLookAhead.
  196013. */
  196014. static fts5YYACTIONTYPE fts5yy_find_reduce_action(
  196015. fts5YYACTIONTYPE stateno, /* Current state number */
  196016. fts5YYCODETYPE iLookAhead /* The look-ahead token */
  196017. ){
  196018. int i;
  196019. #ifdef fts5YYERRORSYMBOL
  196020. if( stateno>fts5YY_REDUCE_COUNT ){
  196021. return fts5yy_default[stateno];
  196022. }
  196023. #else
  196024. assert( stateno<=fts5YY_REDUCE_COUNT );
  196025. #endif
  196026. i = fts5yy_reduce_ofst[stateno];
  196027. assert( iLookAhead!=fts5YYNOCODE );
  196028. i += iLookAhead;
  196029. #ifdef fts5YYERRORSYMBOL
  196030. if( i<0 || i>=fts5YY_ACTTAB_COUNT || fts5yy_lookahead[i]!=iLookAhead ){
  196031. return fts5yy_default[stateno];
  196032. }
  196033. #else
  196034. assert( i>=0 && i<fts5YY_ACTTAB_COUNT );
  196035. assert( fts5yy_lookahead[i]==iLookAhead );
  196036. #endif
  196037. return fts5yy_action[i];
  196038. }
  196039. /*
  196040. ** The following routine is called if the stack overflows.
  196041. */
  196042. static void fts5yyStackOverflow(fts5yyParser *fts5yypParser){
  196043. sqlite3Fts5ParserARG_FETCH
  196044. sqlite3Fts5ParserCTX_FETCH
  196045. #ifndef NDEBUG
  196046. if( fts5yyTraceFILE ){
  196047. fprintf(fts5yyTraceFILE,"%sStack Overflow!\n",fts5yyTracePrompt);
  196048. }
  196049. #endif
  196050. while( fts5yypParser->fts5yytos>fts5yypParser->fts5yystack ) fts5yy_pop_parser_stack(fts5yypParser);
  196051. /* Here code is inserted which will execute if the parser
  196052. ** stack every overflows */
  196053. /******** Begin %stack_overflow code ******************************************/
  196054. sqlite3Fts5ParseError(pParse, "fts5: parser stack overflow");
  196055. /******** End %stack_overflow code ********************************************/
  196056. sqlite3Fts5ParserARG_STORE /* Suppress warning about unused %extra_argument var */
  196057. sqlite3Fts5ParserCTX_STORE
  196058. }
  196059. /*
  196060. ** Print tracing information for a SHIFT action
  196061. */
  196062. #ifndef NDEBUG
  196063. static void fts5yyTraceShift(fts5yyParser *fts5yypParser, int fts5yyNewState, const char *zTag){
  196064. if( fts5yyTraceFILE ){
  196065. if( fts5yyNewState<fts5YYNSTATE ){
  196066. fprintf(fts5yyTraceFILE,"%s%s '%s', go to state %d\n",
  196067. fts5yyTracePrompt, zTag, fts5yyTokenName[fts5yypParser->fts5yytos->major],
  196068. fts5yyNewState);
  196069. }else{
  196070. fprintf(fts5yyTraceFILE,"%s%s '%s', pending reduce %d\n",
  196071. fts5yyTracePrompt, zTag, fts5yyTokenName[fts5yypParser->fts5yytos->major],
  196072. fts5yyNewState - fts5YY_MIN_REDUCE);
  196073. }
  196074. }
  196075. }
  196076. #else
  196077. # define fts5yyTraceShift(X,Y,Z)
  196078. #endif
  196079. /*
  196080. ** Perform a shift action.
  196081. */
  196082. static void fts5yy_shift(
  196083. fts5yyParser *fts5yypParser, /* The parser to be shifted */
  196084. fts5YYACTIONTYPE fts5yyNewState, /* The new state to shift in */
  196085. fts5YYCODETYPE fts5yyMajor, /* The major token to shift in */
  196086. sqlite3Fts5ParserFTS5TOKENTYPE fts5yyMinor /* The minor token to shift in */
  196087. ){
  196088. fts5yyStackEntry *fts5yytos;
  196089. fts5yypParser->fts5yytos++;
  196090. #ifdef fts5YYTRACKMAXSTACKDEPTH
  196091. if( (int)(fts5yypParser->fts5yytos - fts5yypParser->fts5yystack)>fts5yypParser->fts5yyhwm ){
  196092. fts5yypParser->fts5yyhwm++;
  196093. assert( fts5yypParser->fts5yyhwm == (int)(fts5yypParser->fts5yytos - fts5yypParser->fts5yystack) );
  196094. }
  196095. #endif
  196096. #if fts5YYSTACKDEPTH>0
  196097. if( fts5yypParser->fts5yytos>fts5yypParser->fts5yystackEnd ){
  196098. fts5yypParser->fts5yytos--;
  196099. fts5yyStackOverflow(fts5yypParser);
  196100. return;
  196101. }
  196102. #else
  196103. if( fts5yypParser->fts5yytos>=&fts5yypParser->fts5yystack[fts5yypParser->fts5yystksz] ){
  196104. if( fts5yyGrowStack(fts5yypParser) ){
  196105. fts5yypParser->fts5yytos--;
  196106. fts5yyStackOverflow(fts5yypParser);
  196107. return;
  196108. }
  196109. }
  196110. #endif
  196111. if( fts5yyNewState > fts5YY_MAX_SHIFT ){
  196112. fts5yyNewState += fts5YY_MIN_REDUCE - fts5YY_MIN_SHIFTREDUCE;
  196113. }
  196114. fts5yytos = fts5yypParser->fts5yytos;
  196115. fts5yytos->stateno = fts5yyNewState;
  196116. fts5yytos->major = fts5yyMajor;
  196117. fts5yytos->minor.fts5yy0 = fts5yyMinor;
  196118. fts5yyTraceShift(fts5yypParser, fts5yyNewState, "Shift");
  196119. }
  196120. /* For rule J, fts5yyRuleInfoLhs[J] contains the symbol on the left-hand side
  196121. ** of that rule */
  196122. static const fts5YYCODETYPE fts5yyRuleInfoLhs[] = {
  196123. 16, /* (0) input ::= expr */
  196124. 20, /* (1) colset ::= MINUS LCP colsetlist RCP */
  196125. 20, /* (2) colset ::= LCP colsetlist RCP */
  196126. 20, /* (3) colset ::= STRING */
  196127. 20, /* (4) colset ::= MINUS STRING */
  196128. 21, /* (5) colsetlist ::= colsetlist STRING */
  196129. 21, /* (6) colsetlist ::= STRING */
  196130. 17, /* (7) expr ::= expr AND expr */
  196131. 17, /* (8) expr ::= expr OR expr */
  196132. 17, /* (9) expr ::= expr NOT expr */
  196133. 17, /* (10) expr ::= colset COLON LP expr RP */
  196134. 17, /* (11) expr ::= LP expr RP */
  196135. 17, /* (12) expr ::= exprlist */
  196136. 19, /* (13) exprlist ::= cnearset */
  196137. 19, /* (14) exprlist ::= exprlist cnearset */
  196138. 18, /* (15) cnearset ::= nearset */
  196139. 18, /* (16) cnearset ::= colset COLON nearset */
  196140. 22, /* (17) nearset ::= phrase */
  196141. 22, /* (18) nearset ::= CARET phrase */
  196142. 22, /* (19) nearset ::= STRING LP nearphrases neardist_opt RP */
  196143. 23, /* (20) nearphrases ::= phrase */
  196144. 23, /* (21) nearphrases ::= nearphrases phrase */
  196145. 25, /* (22) neardist_opt ::= */
  196146. 25, /* (23) neardist_opt ::= COMMA STRING */
  196147. 24, /* (24) phrase ::= phrase PLUS STRING star_opt */
  196148. 24, /* (25) phrase ::= STRING star_opt */
  196149. 26, /* (26) star_opt ::= STAR */
  196150. 26, /* (27) star_opt ::= */
  196151. };
  196152. /* For rule J, fts5yyRuleInfoNRhs[J] contains the negative of the number
  196153. ** of symbols on the right-hand side of that rule. */
  196154. static const signed char fts5yyRuleInfoNRhs[] = {
  196155. -1, /* (0) input ::= expr */
  196156. -4, /* (1) colset ::= MINUS LCP colsetlist RCP */
  196157. -3, /* (2) colset ::= LCP colsetlist RCP */
  196158. -1, /* (3) colset ::= STRING */
  196159. -2, /* (4) colset ::= MINUS STRING */
  196160. -2, /* (5) colsetlist ::= colsetlist STRING */
  196161. -1, /* (6) colsetlist ::= STRING */
  196162. -3, /* (7) expr ::= expr AND expr */
  196163. -3, /* (8) expr ::= expr OR expr */
  196164. -3, /* (9) expr ::= expr NOT expr */
  196165. -5, /* (10) expr ::= colset COLON LP expr RP */
  196166. -3, /* (11) expr ::= LP expr RP */
  196167. -1, /* (12) expr ::= exprlist */
  196168. -1, /* (13) exprlist ::= cnearset */
  196169. -2, /* (14) exprlist ::= exprlist cnearset */
  196170. -1, /* (15) cnearset ::= nearset */
  196171. -3, /* (16) cnearset ::= colset COLON nearset */
  196172. -1, /* (17) nearset ::= phrase */
  196173. -2, /* (18) nearset ::= CARET phrase */
  196174. -5, /* (19) nearset ::= STRING LP nearphrases neardist_opt RP */
  196175. -1, /* (20) nearphrases ::= phrase */
  196176. -2, /* (21) nearphrases ::= nearphrases phrase */
  196177. 0, /* (22) neardist_opt ::= */
  196178. -2, /* (23) neardist_opt ::= COMMA STRING */
  196179. -4, /* (24) phrase ::= phrase PLUS STRING star_opt */
  196180. -2, /* (25) phrase ::= STRING star_opt */
  196181. -1, /* (26) star_opt ::= STAR */
  196182. 0, /* (27) star_opt ::= */
  196183. };
  196184. static void fts5yy_accept(fts5yyParser*); /* Forward Declaration */
  196185. /*
  196186. ** Perform a reduce action and the shift that must immediately
  196187. ** follow the reduce.
  196188. **
  196189. ** The fts5yyLookahead and fts5yyLookaheadToken parameters provide reduce actions
  196190. ** access to the lookahead token (if any). The fts5yyLookahead will be fts5YYNOCODE
  196191. ** if the lookahead token has already been consumed. As this procedure is
  196192. ** only called from one place, optimizing compilers will in-line it, which
  196193. ** means that the extra parameters have no performance impact.
  196194. */
  196195. static fts5YYACTIONTYPE fts5yy_reduce(
  196196. fts5yyParser *fts5yypParser, /* The parser */
  196197. unsigned int fts5yyruleno, /* Number of the rule by which to reduce */
  196198. int fts5yyLookahead, /* Lookahead token, or fts5YYNOCODE if none */
  196199. sqlite3Fts5ParserFTS5TOKENTYPE fts5yyLookaheadToken /* Value of the lookahead token */
  196200. sqlite3Fts5ParserCTX_PDECL /* %extra_context */
  196201. ){
  196202. int fts5yygoto; /* The next state */
  196203. fts5YYACTIONTYPE fts5yyact; /* The next action */
  196204. fts5yyStackEntry *fts5yymsp; /* The top of the parser's stack */
  196205. int fts5yysize; /* Amount to pop the stack */
  196206. sqlite3Fts5ParserARG_FETCH
  196207. (void)fts5yyLookahead;
  196208. (void)fts5yyLookaheadToken;
  196209. fts5yymsp = fts5yypParser->fts5yytos;
  196210. #ifndef NDEBUG
  196211. if( fts5yyTraceFILE && fts5yyruleno<(int)(sizeof(fts5yyRuleName)/sizeof(fts5yyRuleName[0])) ){
  196212. fts5yysize = fts5yyRuleInfoNRhs[fts5yyruleno];
  196213. if( fts5yysize ){
  196214. fprintf(fts5yyTraceFILE, "%sReduce %d [%s]%s, pop back to state %d.\n",
  196215. fts5yyTracePrompt,
  196216. fts5yyruleno, fts5yyRuleName[fts5yyruleno],
  196217. fts5yyruleno<fts5YYNRULE_WITH_ACTION ? "" : " without external action",
  196218. fts5yymsp[fts5yysize].stateno);
  196219. }else{
  196220. fprintf(fts5yyTraceFILE, "%sReduce %d [%s]%s.\n",
  196221. fts5yyTracePrompt, fts5yyruleno, fts5yyRuleName[fts5yyruleno],
  196222. fts5yyruleno<fts5YYNRULE_WITH_ACTION ? "" : " without external action");
  196223. }
  196224. }
  196225. #endif /* NDEBUG */
  196226. /* Check that the stack is large enough to grow by a single entry
  196227. ** if the RHS of the rule is empty. This ensures that there is room
  196228. ** enough on the stack to push the LHS value */
  196229. if( fts5yyRuleInfoNRhs[fts5yyruleno]==0 ){
  196230. #ifdef fts5YYTRACKMAXSTACKDEPTH
  196231. if( (int)(fts5yypParser->fts5yytos - fts5yypParser->fts5yystack)>fts5yypParser->fts5yyhwm ){
  196232. fts5yypParser->fts5yyhwm++;
  196233. assert( fts5yypParser->fts5yyhwm == (int)(fts5yypParser->fts5yytos - fts5yypParser->fts5yystack));
  196234. }
  196235. #endif
  196236. #if fts5YYSTACKDEPTH>0
  196237. if( fts5yypParser->fts5yytos>=fts5yypParser->fts5yystackEnd ){
  196238. fts5yyStackOverflow(fts5yypParser);
  196239. /* The call to fts5yyStackOverflow() above pops the stack until it is
  196240. ** empty, causing the main parser loop to exit. So the return value
  196241. ** is never used and does not matter. */
  196242. return 0;
  196243. }
  196244. #else
  196245. if( fts5yypParser->fts5yytos>=&fts5yypParser->fts5yystack[fts5yypParser->fts5yystksz-1] ){
  196246. if( fts5yyGrowStack(fts5yypParser) ){
  196247. fts5yyStackOverflow(fts5yypParser);
  196248. /* The call to fts5yyStackOverflow() above pops the stack until it is
  196249. ** empty, causing the main parser loop to exit. So the return value
  196250. ** is never used and does not matter. */
  196251. return 0;
  196252. }
  196253. fts5yymsp = fts5yypParser->fts5yytos;
  196254. }
  196255. #endif
  196256. }
  196257. switch( fts5yyruleno ){
  196258. /* Beginning here are the reduction cases. A typical example
  196259. ** follows:
  196260. ** case 0:
  196261. ** #line <lineno> <grammarfile>
  196262. ** { ... } // User supplied code
  196263. ** #line <lineno> <thisfile>
  196264. ** break;
  196265. */
  196266. /********** Begin reduce actions **********************************************/
  196267. fts5YYMINORTYPE fts5yylhsminor;
  196268. case 0: /* input ::= expr */
  196269. { sqlite3Fts5ParseFinished(pParse, fts5yymsp[0].minor.fts5yy24); }
  196270. break;
  196271. case 1: /* colset ::= MINUS LCP colsetlist RCP */
  196272. {
  196273. fts5yymsp[-3].minor.fts5yy11 = sqlite3Fts5ParseColsetInvert(pParse, fts5yymsp[-1].minor.fts5yy11);
  196274. }
  196275. break;
  196276. case 2: /* colset ::= LCP colsetlist RCP */
  196277. { fts5yymsp[-2].minor.fts5yy11 = fts5yymsp[-1].minor.fts5yy11; }
  196278. break;
  196279. case 3: /* colset ::= STRING */
  196280. {
  196281. fts5yylhsminor.fts5yy11 = sqlite3Fts5ParseColset(pParse, 0, &fts5yymsp[0].minor.fts5yy0);
  196282. }
  196283. fts5yymsp[0].minor.fts5yy11 = fts5yylhsminor.fts5yy11;
  196284. break;
  196285. case 4: /* colset ::= MINUS STRING */
  196286. {
  196287. fts5yymsp[-1].minor.fts5yy11 = sqlite3Fts5ParseColset(pParse, 0, &fts5yymsp[0].minor.fts5yy0);
  196288. fts5yymsp[-1].minor.fts5yy11 = sqlite3Fts5ParseColsetInvert(pParse, fts5yymsp[-1].minor.fts5yy11);
  196289. }
  196290. break;
  196291. case 5: /* colsetlist ::= colsetlist STRING */
  196292. {
  196293. fts5yylhsminor.fts5yy11 = sqlite3Fts5ParseColset(pParse, fts5yymsp[-1].minor.fts5yy11, &fts5yymsp[0].minor.fts5yy0); }
  196294. fts5yymsp[-1].minor.fts5yy11 = fts5yylhsminor.fts5yy11;
  196295. break;
  196296. case 6: /* colsetlist ::= STRING */
  196297. {
  196298. fts5yylhsminor.fts5yy11 = sqlite3Fts5ParseColset(pParse, 0, &fts5yymsp[0].minor.fts5yy0);
  196299. }
  196300. fts5yymsp[0].minor.fts5yy11 = fts5yylhsminor.fts5yy11;
  196301. break;
  196302. case 7: /* expr ::= expr AND expr */
  196303. {
  196304. fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_AND, fts5yymsp[-2].minor.fts5yy24, fts5yymsp[0].minor.fts5yy24, 0);
  196305. }
  196306. fts5yymsp[-2].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
  196307. break;
  196308. case 8: /* expr ::= expr OR expr */
  196309. {
  196310. fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_OR, fts5yymsp[-2].minor.fts5yy24, fts5yymsp[0].minor.fts5yy24, 0);
  196311. }
  196312. fts5yymsp[-2].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
  196313. break;
  196314. case 9: /* expr ::= expr NOT expr */
  196315. {
  196316. fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_NOT, fts5yymsp[-2].minor.fts5yy24, fts5yymsp[0].minor.fts5yy24, 0);
  196317. }
  196318. fts5yymsp[-2].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
  196319. break;
  196320. case 10: /* expr ::= colset COLON LP expr RP */
  196321. {
  196322. sqlite3Fts5ParseSetColset(pParse, fts5yymsp[-1].minor.fts5yy24, fts5yymsp[-4].minor.fts5yy11);
  196323. fts5yylhsminor.fts5yy24 = fts5yymsp[-1].minor.fts5yy24;
  196324. }
  196325. fts5yymsp[-4].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
  196326. break;
  196327. case 11: /* expr ::= LP expr RP */
  196328. {fts5yymsp[-2].minor.fts5yy24 = fts5yymsp[-1].minor.fts5yy24;}
  196329. break;
  196330. case 12: /* expr ::= exprlist */
  196331. case 13: /* exprlist ::= cnearset */ fts5yytestcase(fts5yyruleno==13);
  196332. {fts5yylhsminor.fts5yy24 = fts5yymsp[0].minor.fts5yy24;}
  196333. fts5yymsp[0].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
  196334. break;
  196335. case 14: /* exprlist ::= exprlist cnearset */
  196336. {
  196337. fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseImplicitAnd(pParse, fts5yymsp[-1].minor.fts5yy24, fts5yymsp[0].minor.fts5yy24);
  196338. }
  196339. fts5yymsp[-1].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
  196340. break;
  196341. case 15: /* cnearset ::= nearset */
  196342. {
  196343. fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_STRING, 0, 0, fts5yymsp[0].minor.fts5yy46);
  196344. }
  196345. fts5yymsp[0].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
  196346. break;
  196347. case 16: /* cnearset ::= colset COLON nearset */
  196348. {
  196349. fts5yylhsminor.fts5yy24 = sqlite3Fts5ParseNode(pParse, FTS5_STRING, 0, 0, fts5yymsp[0].minor.fts5yy46);
  196350. sqlite3Fts5ParseSetColset(pParse, fts5yylhsminor.fts5yy24, fts5yymsp[-2].minor.fts5yy11);
  196351. }
  196352. fts5yymsp[-2].minor.fts5yy24 = fts5yylhsminor.fts5yy24;
  196353. break;
  196354. case 17: /* nearset ::= phrase */
  196355. { fts5yylhsminor.fts5yy46 = sqlite3Fts5ParseNearset(pParse, 0, fts5yymsp[0].minor.fts5yy53); }
  196356. fts5yymsp[0].minor.fts5yy46 = fts5yylhsminor.fts5yy46;
  196357. break;
  196358. case 18: /* nearset ::= CARET phrase */
  196359. {
  196360. sqlite3Fts5ParseSetCaret(fts5yymsp[0].minor.fts5yy53);
  196361. fts5yymsp[-1].minor.fts5yy46 = sqlite3Fts5ParseNearset(pParse, 0, fts5yymsp[0].minor.fts5yy53);
  196362. }
  196363. break;
  196364. case 19: /* nearset ::= STRING LP nearphrases neardist_opt RP */
  196365. {
  196366. sqlite3Fts5ParseNear(pParse, &fts5yymsp[-4].minor.fts5yy0);
  196367. sqlite3Fts5ParseSetDistance(pParse, fts5yymsp[-2].minor.fts5yy46, &fts5yymsp[-1].minor.fts5yy0);
  196368. fts5yylhsminor.fts5yy46 = fts5yymsp[-2].minor.fts5yy46;
  196369. }
  196370. fts5yymsp[-4].minor.fts5yy46 = fts5yylhsminor.fts5yy46;
  196371. break;
  196372. case 20: /* nearphrases ::= phrase */
  196373. {
  196374. fts5yylhsminor.fts5yy46 = sqlite3Fts5ParseNearset(pParse, 0, fts5yymsp[0].minor.fts5yy53);
  196375. }
  196376. fts5yymsp[0].minor.fts5yy46 = fts5yylhsminor.fts5yy46;
  196377. break;
  196378. case 21: /* nearphrases ::= nearphrases phrase */
  196379. {
  196380. fts5yylhsminor.fts5yy46 = sqlite3Fts5ParseNearset(pParse, fts5yymsp[-1].minor.fts5yy46, fts5yymsp[0].minor.fts5yy53);
  196381. }
  196382. fts5yymsp[-1].minor.fts5yy46 = fts5yylhsminor.fts5yy46;
  196383. break;
  196384. case 22: /* neardist_opt ::= */
  196385. { fts5yymsp[1].minor.fts5yy0.p = 0; fts5yymsp[1].minor.fts5yy0.n = 0; }
  196386. break;
  196387. case 23: /* neardist_opt ::= COMMA STRING */
  196388. { fts5yymsp[-1].minor.fts5yy0 = fts5yymsp[0].minor.fts5yy0; }
  196389. break;
  196390. case 24: /* phrase ::= phrase PLUS STRING star_opt */
  196391. {
  196392. fts5yylhsminor.fts5yy53 = sqlite3Fts5ParseTerm(pParse, fts5yymsp[-3].minor.fts5yy53, &fts5yymsp[-1].minor.fts5yy0, fts5yymsp[0].minor.fts5yy4);
  196393. }
  196394. fts5yymsp[-3].minor.fts5yy53 = fts5yylhsminor.fts5yy53;
  196395. break;
  196396. case 25: /* phrase ::= STRING star_opt */
  196397. {
  196398. fts5yylhsminor.fts5yy53 = sqlite3Fts5ParseTerm(pParse, 0, &fts5yymsp[-1].minor.fts5yy0, fts5yymsp[0].minor.fts5yy4);
  196399. }
  196400. fts5yymsp[-1].minor.fts5yy53 = fts5yylhsminor.fts5yy53;
  196401. break;
  196402. case 26: /* star_opt ::= STAR */
  196403. { fts5yymsp[0].minor.fts5yy4 = 1; }
  196404. break;
  196405. case 27: /* star_opt ::= */
  196406. { fts5yymsp[1].minor.fts5yy4 = 0; }
  196407. break;
  196408. default:
  196409. break;
  196410. /********** End reduce actions ************************************************/
  196411. };
  196412. assert( fts5yyruleno<sizeof(fts5yyRuleInfoLhs)/sizeof(fts5yyRuleInfoLhs[0]) );
  196413. fts5yygoto = fts5yyRuleInfoLhs[fts5yyruleno];
  196414. fts5yysize = fts5yyRuleInfoNRhs[fts5yyruleno];
  196415. fts5yyact = fts5yy_find_reduce_action(fts5yymsp[fts5yysize].stateno,(fts5YYCODETYPE)fts5yygoto);
  196416. /* There are no SHIFTREDUCE actions on nonterminals because the table
  196417. ** generator has simplified them to pure REDUCE actions. */
  196418. assert( !(fts5yyact>fts5YY_MAX_SHIFT && fts5yyact<=fts5YY_MAX_SHIFTREDUCE) );
  196419. /* It is not possible for a REDUCE to be followed by an error */
  196420. assert( fts5yyact!=fts5YY_ERROR_ACTION );
  196421. fts5yymsp += fts5yysize+1;
  196422. fts5yypParser->fts5yytos = fts5yymsp;
  196423. fts5yymsp->stateno = (fts5YYACTIONTYPE)fts5yyact;
  196424. fts5yymsp->major = (fts5YYCODETYPE)fts5yygoto;
  196425. fts5yyTraceShift(fts5yypParser, fts5yyact, "... then shift");
  196426. return fts5yyact;
  196427. }
  196428. /*
  196429. ** The following code executes when the parse fails
  196430. */
  196431. #ifndef fts5YYNOERRORRECOVERY
  196432. static void fts5yy_parse_failed(
  196433. fts5yyParser *fts5yypParser /* The parser */
  196434. ){
  196435. sqlite3Fts5ParserARG_FETCH
  196436. sqlite3Fts5ParserCTX_FETCH
  196437. #ifndef NDEBUG
  196438. if( fts5yyTraceFILE ){
  196439. fprintf(fts5yyTraceFILE,"%sFail!\n",fts5yyTracePrompt);
  196440. }
  196441. #endif
  196442. while( fts5yypParser->fts5yytos>fts5yypParser->fts5yystack ) fts5yy_pop_parser_stack(fts5yypParser);
  196443. /* Here code is inserted which will be executed whenever the
  196444. ** parser fails */
  196445. /************ Begin %parse_failure code ***************************************/
  196446. /************ End %parse_failure code *****************************************/
  196447. sqlite3Fts5ParserARG_STORE /* Suppress warning about unused %extra_argument variable */
  196448. sqlite3Fts5ParserCTX_STORE
  196449. }
  196450. #endif /* fts5YYNOERRORRECOVERY */
  196451. /*
  196452. ** The following code executes when a syntax error first occurs.
  196453. */
  196454. static void fts5yy_syntax_error(
  196455. fts5yyParser *fts5yypParser, /* The parser */
  196456. int fts5yymajor, /* The major type of the error token */
  196457. sqlite3Fts5ParserFTS5TOKENTYPE fts5yyminor /* The minor type of the error token */
  196458. ){
  196459. sqlite3Fts5ParserARG_FETCH
  196460. sqlite3Fts5ParserCTX_FETCH
  196461. #define FTS5TOKEN fts5yyminor
  196462. /************ Begin %syntax_error code ****************************************/
  196463. UNUSED_PARAM(fts5yymajor); /* Silence a compiler warning */
  196464. sqlite3Fts5ParseError(
  196465. pParse, "fts5: syntax error near \"%.*s\"",FTS5TOKEN.n,FTS5TOKEN.p
  196466. );
  196467. /************ End %syntax_error code ******************************************/
  196468. sqlite3Fts5ParserARG_STORE /* Suppress warning about unused %extra_argument variable */
  196469. sqlite3Fts5ParserCTX_STORE
  196470. }
  196471. /*
  196472. ** The following is executed when the parser accepts
  196473. */
  196474. static void fts5yy_accept(
  196475. fts5yyParser *fts5yypParser /* The parser */
  196476. ){
  196477. sqlite3Fts5ParserARG_FETCH
  196478. sqlite3Fts5ParserCTX_FETCH
  196479. #ifndef NDEBUG
  196480. if( fts5yyTraceFILE ){
  196481. fprintf(fts5yyTraceFILE,"%sAccept!\n",fts5yyTracePrompt);
  196482. }
  196483. #endif
  196484. #ifndef fts5YYNOERRORRECOVERY
  196485. fts5yypParser->fts5yyerrcnt = -1;
  196486. #endif
  196487. assert( fts5yypParser->fts5yytos==fts5yypParser->fts5yystack );
  196488. /* Here code is inserted which will be executed whenever the
  196489. ** parser accepts */
  196490. /*********** Begin %parse_accept code *****************************************/
  196491. /*********** End %parse_accept code *******************************************/
  196492. sqlite3Fts5ParserARG_STORE /* Suppress warning about unused %extra_argument variable */
  196493. sqlite3Fts5ParserCTX_STORE
  196494. }
  196495. /* The main parser program.
  196496. ** The first argument is a pointer to a structure obtained from
  196497. ** "sqlite3Fts5ParserAlloc" which describes the current state of the parser.
  196498. ** The second argument is the major token number. The third is
  196499. ** the minor token. The fourth optional argument is whatever the
  196500. ** user wants (and specified in the grammar) and is available for
  196501. ** use by the action routines.
  196502. **
  196503. ** Inputs:
  196504. ** <ul>
  196505. ** <li> A pointer to the parser (an opaque structure.)
  196506. ** <li> The major token number.
  196507. ** <li> The minor token number.
  196508. ** <li> An option argument of a grammar-specified type.
  196509. ** </ul>
  196510. **
  196511. ** Outputs:
  196512. ** None.
  196513. */
  196514. static void sqlite3Fts5Parser(
  196515. void *fts5yyp, /* The parser */
  196516. int fts5yymajor, /* The major token code number */
  196517. sqlite3Fts5ParserFTS5TOKENTYPE fts5yyminor /* The value for the token */
  196518. sqlite3Fts5ParserARG_PDECL /* Optional %extra_argument parameter */
  196519. ){
  196520. fts5YYMINORTYPE fts5yyminorunion;
  196521. fts5YYACTIONTYPE fts5yyact; /* The parser action. */
  196522. #if !defined(fts5YYERRORSYMBOL) && !defined(fts5YYNOERRORRECOVERY)
  196523. int fts5yyendofinput; /* True if we are at the end of input */
  196524. #endif
  196525. #ifdef fts5YYERRORSYMBOL
  196526. int fts5yyerrorhit = 0; /* True if fts5yymajor has invoked an error */
  196527. #endif
  196528. fts5yyParser *fts5yypParser = (fts5yyParser*)fts5yyp; /* The parser */
  196529. sqlite3Fts5ParserCTX_FETCH
  196530. sqlite3Fts5ParserARG_STORE
  196531. assert( fts5yypParser->fts5yytos!=0 );
  196532. #if !defined(fts5YYERRORSYMBOL) && !defined(fts5YYNOERRORRECOVERY)
  196533. fts5yyendofinput = (fts5yymajor==0);
  196534. #endif
  196535. fts5yyact = fts5yypParser->fts5yytos->stateno;
  196536. #ifndef NDEBUG
  196537. if( fts5yyTraceFILE ){
  196538. if( fts5yyact < fts5YY_MIN_REDUCE ){
  196539. fprintf(fts5yyTraceFILE,"%sInput '%s' in state %d\n",
  196540. fts5yyTracePrompt,fts5yyTokenName[fts5yymajor],fts5yyact);
  196541. }else{
  196542. fprintf(fts5yyTraceFILE,"%sInput '%s' with pending reduce %d\n",
  196543. fts5yyTracePrompt,fts5yyTokenName[fts5yymajor],fts5yyact-fts5YY_MIN_REDUCE);
  196544. }
  196545. }
  196546. #endif
  196547. do{
  196548. assert( fts5yyact==fts5yypParser->fts5yytos->stateno );
  196549. fts5yyact = fts5yy_find_shift_action((fts5YYCODETYPE)fts5yymajor,fts5yyact);
  196550. if( fts5yyact >= fts5YY_MIN_REDUCE ){
  196551. fts5yyact = fts5yy_reduce(fts5yypParser,fts5yyact-fts5YY_MIN_REDUCE,fts5yymajor,
  196552. fts5yyminor sqlite3Fts5ParserCTX_PARAM);
  196553. }else if( fts5yyact <= fts5YY_MAX_SHIFTREDUCE ){
  196554. fts5yy_shift(fts5yypParser,fts5yyact,(fts5YYCODETYPE)fts5yymajor,fts5yyminor);
  196555. #ifndef fts5YYNOERRORRECOVERY
  196556. fts5yypParser->fts5yyerrcnt--;
  196557. #endif
  196558. break;
  196559. }else if( fts5yyact==fts5YY_ACCEPT_ACTION ){
  196560. fts5yypParser->fts5yytos--;
  196561. fts5yy_accept(fts5yypParser);
  196562. return;
  196563. }else{
  196564. assert( fts5yyact == fts5YY_ERROR_ACTION );
  196565. fts5yyminorunion.fts5yy0 = fts5yyminor;
  196566. #ifdef fts5YYERRORSYMBOL
  196567. int fts5yymx;
  196568. #endif
  196569. #ifndef NDEBUG
  196570. if( fts5yyTraceFILE ){
  196571. fprintf(fts5yyTraceFILE,"%sSyntax Error!\n",fts5yyTracePrompt);
  196572. }
  196573. #endif
  196574. #ifdef fts5YYERRORSYMBOL
  196575. /* A syntax error has occurred.
  196576. ** The response to an error depends upon whether or not the
  196577. ** grammar defines an error token "ERROR".
  196578. **
  196579. ** This is what we do if the grammar does define ERROR:
  196580. **
  196581. ** * Call the %syntax_error function.
  196582. **
  196583. ** * Begin popping the stack until we enter a state where
  196584. ** it is legal to shift the error symbol, then shift
  196585. ** the error symbol.
  196586. **
  196587. ** * Set the error count to three.
  196588. **
  196589. ** * Begin accepting and shifting new tokens. No new error
  196590. ** processing will occur until three tokens have been
  196591. ** shifted successfully.
  196592. **
  196593. */
  196594. if( fts5yypParser->fts5yyerrcnt<0 ){
  196595. fts5yy_syntax_error(fts5yypParser,fts5yymajor,fts5yyminor);
  196596. }
  196597. fts5yymx = fts5yypParser->fts5yytos->major;
  196598. if( fts5yymx==fts5YYERRORSYMBOL || fts5yyerrorhit ){
  196599. #ifndef NDEBUG
  196600. if( fts5yyTraceFILE ){
  196601. fprintf(fts5yyTraceFILE,"%sDiscard input token %s\n",
  196602. fts5yyTracePrompt,fts5yyTokenName[fts5yymajor]);
  196603. }
  196604. #endif
  196605. fts5yy_destructor(fts5yypParser, (fts5YYCODETYPE)fts5yymajor, &fts5yyminorunion);
  196606. fts5yymajor = fts5YYNOCODE;
  196607. }else{
  196608. while( fts5yypParser->fts5yytos >= fts5yypParser->fts5yystack
  196609. && (fts5yyact = fts5yy_find_reduce_action(
  196610. fts5yypParser->fts5yytos->stateno,
  196611. fts5YYERRORSYMBOL)) > fts5YY_MAX_SHIFTREDUCE
  196612. ){
  196613. fts5yy_pop_parser_stack(fts5yypParser);
  196614. }
  196615. if( fts5yypParser->fts5yytos < fts5yypParser->fts5yystack || fts5yymajor==0 ){
  196616. fts5yy_destructor(fts5yypParser,(fts5YYCODETYPE)fts5yymajor,&fts5yyminorunion);
  196617. fts5yy_parse_failed(fts5yypParser);
  196618. #ifndef fts5YYNOERRORRECOVERY
  196619. fts5yypParser->fts5yyerrcnt = -1;
  196620. #endif
  196621. fts5yymajor = fts5YYNOCODE;
  196622. }else if( fts5yymx!=fts5YYERRORSYMBOL ){
  196623. fts5yy_shift(fts5yypParser,fts5yyact,fts5YYERRORSYMBOL,fts5yyminor);
  196624. }
  196625. }
  196626. fts5yypParser->fts5yyerrcnt = 3;
  196627. fts5yyerrorhit = 1;
  196628. if( fts5yymajor==fts5YYNOCODE ) break;
  196629. fts5yyact = fts5yypParser->fts5yytos->stateno;
  196630. #elif defined(fts5YYNOERRORRECOVERY)
  196631. /* If the fts5YYNOERRORRECOVERY macro is defined, then do not attempt to
  196632. ** do any kind of error recovery. Instead, simply invoke the syntax
  196633. ** error routine and continue going as if nothing had happened.
  196634. **
  196635. ** Applications can set this macro (for example inside %include) if
  196636. ** they intend to abandon the parse upon the first syntax error seen.
  196637. */
  196638. fts5yy_syntax_error(fts5yypParser,fts5yymajor, fts5yyminor);
  196639. fts5yy_destructor(fts5yypParser,(fts5YYCODETYPE)fts5yymajor,&fts5yyminorunion);
  196640. break;
  196641. #else /* fts5YYERRORSYMBOL is not defined */
  196642. /* This is what we do if the grammar does not define ERROR:
  196643. **
  196644. ** * Report an error message, and throw away the input token.
  196645. **
  196646. ** * If the input token is $, then fail the parse.
  196647. **
  196648. ** As before, subsequent error messages are suppressed until
  196649. ** three input tokens have been successfully shifted.
  196650. */
  196651. if( fts5yypParser->fts5yyerrcnt<=0 ){
  196652. fts5yy_syntax_error(fts5yypParser,fts5yymajor, fts5yyminor);
  196653. }
  196654. fts5yypParser->fts5yyerrcnt = 3;
  196655. fts5yy_destructor(fts5yypParser,(fts5YYCODETYPE)fts5yymajor,&fts5yyminorunion);
  196656. if( fts5yyendofinput ){
  196657. fts5yy_parse_failed(fts5yypParser);
  196658. #ifndef fts5YYNOERRORRECOVERY
  196659. fts5yypParser->fts5yyerrcnt = -1;
  196660. #endif
  196661. }
  196662. break;
  196663. #endif
  196664. }
  196665. }while( fts5yypParser->fts5yytos>fts5yypParser->fts5yystack );
  196666. #ifndef NDEBUG
  196667. if( fts5yyTraceFILE ){
  196668. fts5yyStackEntry *i;
  196669. char cDiv = '[';
  196670. fprintf(fts5yyTraceFILE,"%sReturn. Stack=",fts5yyTracePrompt);
  196671. for(i=&fts5yypParser->fts5yystack[1]; i<=fts5yypParser->fts5yytos; i++){
  196672. fprintf(fts5yyTraceFILE,"%c%s", cDiv, fts5yyTokenName[i->major]);
  196673. cDiv = ' ';
  196674. }
  196675. fprintf(fts5yyTraceFILE,"]\n");
  196676. }
  196677. #endif
  196678. return;
  196679. }
  196680. /*
  196681. ** Return the fallback token corresponding to canonical token iToken, or
  196682. ** 0 if iToken has no fallback.
  196683. */
  196684. static int sqlite3Fts5ParserFallback(int iToken){
  196685. #ifdef fts5YYFALLBACK
  196686. assert( iToken<(int)(sizeof(fts5yyFallback)/sizeof(fts5yyFallback[0])) );
  196687. return fts5yyFallback[iToken];
  196688. #else
  196689. (void)iToken;
  196690. return 0;
  196691. #endif
  196692. }
  196693. /*
  196694. ** 2014 May 31
  196695. **
  196696. ** The author disclaims copyright to this source code. In place of
  196697. ** a legal notice, here is a blessing:
  196698. **
  196699. ** May you do good and not evil.
  196700. ** May you find forgiveness for yourself and forgive others.
  196701. ** May you share freely, never taking more than you give.
  196702. **
  196703. ******************************************************************************
  196704. */
  196705. /* #include "fts5Int.h" */
  196706. #include <math.h> /* amalgamator: keep */
  196707. /*
  196708. ** Object used to iterate through all "coalesced phrase instances" in
  196709. ** a single column of the current row. If the phrase instances in the
  196710. ** column being considered do not overlap, this object simply iterates
  196711. ** through them. Or, if they do overlap (share one or more tokens in
  196712. ** common), each set of overlapping instances is treated as a single
  196713. ** match. See documentation for the highlight() auxiliary function for
  196714. ** details.
  196715. **
  196716. ** Usage is:
  196717. **
  196718. ** for(rc = fts5CInstIterNext(pApi, pFts, iCol, &iter);
  196719. ** (rc==SQLITE_OK && 0==fts5CInstIterEof(&iter);
  196720. ** rc = fts5CInstIterNext(&iter)
  196721. ** ){
  196722. ** printf("instance starts at %d, ends at %d\n", iter.iStart, iter.iEnd);
  196723. ** }
  196724. **
  196725. */
  196726. typedef struct CInstIter CInstIter;
  196727. struct CInstIter {
  196728. const Fts5ExtensionApi *pApi; /* API offered by current FTS version */
  196729. Fts5Context *pFts; /* First arg to pass to pApi functions */
  196730. int iCol; /* Column to search */
  196731. int iInst; /* Next phrase instance index */
  196732. int nInst; /* Total number of phrase instances */
  196733. /* Output variables */
  196734. int iStart; /* First token in coalesced phrase instance */
  196735. int iEnd; /* Last token in coalesced phrase instance */
  196736. };
  196737. /*
  196738. ** Advance the iterator to the next coalesced phrase instance. Return
  196739. ** an SQLite error code if an error occurs, or SQLITE_OK otherwise.
  196740. */
  196741. static int fts5CInstIterNext(CInstIter *pIter){
  196742. int rc = SQLITE_OK;
  196743. pIter->iStart = -1;
  196744. pIter->iEnd = -1;
  196745. while( rc==SQLITE_OK && pIter->iInst<pIter->nInst ){
  196746. int ip; int ic; int io;
  196747. rc = pIter->pApi->xInst(pIter->pFts, pIter->iInst, &ip, &ic, &io);
  196748. if( rc==SQLITE_OK ){
  196749. if( ic==pIter->iCol ){
  196750. int iEnd = io - 1 + pIter->pApi->xPhraseSize(pIter->pFts, ip);
  196751. if( pIter->iStart<0 ){
  196752. pIter->iStart = io;
  196753. pIter->iEnd = iEnd;
  196754. }else if( io<=pIter->iEnd ){
  196755. if( iEnd>pIter->iEnd ) pIter->iEnd = iEnd;
  196756. }else{
  196757. break;
  196758. }
  196759. }
  196760. pIter->iInst++;
  196761. }
  196762. }
  196763. return rc;
  196764. }
  196765. /*
  196766. ** Initialize the iterator object indicated by the final parameter to
  196767. ** iterate through coalesced phrase instances in column iCol.
  196768. */
  196769. static int fts5CInstIterInit(
  196770. const Fts5ExtensionApi *pApi,
  196771. Fts5Context *pFts,
  196772. int iCol,
  196773. CInstIter *pIter
  196774. ){
  196775. int rc;
  196776. memset(pIter, 0, sizeof(CInstIter));
  196777. pIter->pApi = pApi;
  196778. pIter->pFts = pFts;
  196779. pIter->iCol = iCol;
  196780. rc = pApi->xInstCount(pFts, &pIter->nInst);
  196781. if( rc==SQLITE_OK ){
  196782. rc = fts5CInstIterNext(pIter);
  196783. }
  196784. return rc;
  196785. }
  196786. /*************************************************************************
  196787. ** Start of highlight() implementation.
  196788. */
  196789. typedef struct HighlightContext HighlightContext;
  196790. struct HighlightContext {
  196791. CInstIter iter; /* Coalesced Instance Iterator */
  196792. int iPos; /* Current token offset in zIn[] */
  196793. int iRangeStart; /* First token to include */
  196794. int iRangeEnd; /* If non-zero, last token to include */
  196795. const char *zOpen; /* Opening highlight */
  196796. const char *zClose; /* Closing highlight */
  196797. const char *zIn; /* Input text */
  196798. int nIn; /* Size of input text in bytes */
  196799. int iOff; /* Current offset within zIn[] */
  196800. char *zOut; /* Output value */
  196801. };
  196802. /*
  196803. ** Append text to the HighlightContext output string - p->zOut. Argument
  196804. ** z points to a buffer containing n bytes of text to append. If n is
  196805. ** negative, everything up until the first '\0' is appended to the output.
  196806. **
  196807. ** If *pRc is set to any value other than SQLITE_OK when this function is
  196808. ** called, it is a no-op. If an error (i.e. an OOM condition) is encountered,
  196809. ** *pRc is set to an error code before returning.
  196810. */
  196811. static void fts5HighlightAppend(
  196812. int *pRc,
  196813. HighlightContext *p,
  196814. const char *z, int n
  196815. ){
  196816. if( *pRc==SQLITE_OK && z ){
  196817. if( n<0 ) n = (int)strlen(z);
  196818. p->zOut = sqlite3_mprintf("%z%.*s", p->zOut, n, z);
  196819. if( p->zOut==0 ) *pRc = SQLITE_NOMEM;
  196820. }
  196821. }
  196822. /*
  196823. ** Tokenizer callback used by implementation of highlight() function.
  196824. */
  196825. static int fts5HighlightCb(
  196826. void *pContext, /* Pointer to HighlightContext object */
  196827. int tflags, /* Mask of FTS5_TOKEN_* flags */
  196828. const char *pToken, /* Buffer containing token */
  196829. int nToken, /* Size of token in bytes */
  196830. int iStartOff, /* Start offset of token */
  196831. int iEndOff /* End offset of token */
  196832. ){
  196833. HighlightContext *p = (HighlightContext*)pContext;
  196834. int rc = SQLITE_OK;
  196835. int iPos;
  196836. UNUSED_PARAM2(pToken, nToken);
  196837. if( tflags & FTS5_TOKEN_COLOCATED ) return SQLITE_OK;
  196838. iPos = p->iPos++;
  196839. if( p->iRangeEnd>0 ){
  196840. if( iPos<p->iRangeStart || iPos>p->iRangeEnd ) return SQLITE_OK;
  196841. if( p->iRangeStart && iPos==p->iRangeStart ) p->iOff = iStartOff;
  196842. }
  196843. if( iPos==p->iter.iStart ){
  196844. fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iStartOff - p->iOff);
  196845. fts5HighlightAppend(&rc, p, p->zOpen, -1);
  196846. p->iOff = iStartOff;
  196847. }
  196848. if( iPos==p->iter.iEnd ){
  196849. if( p->iRangeEnd && p->iter.iStart<p->iRangeStart ){
  196850. fts5HighlightAppend(&rc, p, p->zOpen, -1);
  196851. }
  196852. fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iEndOff - p->iOff);
  196853. fts5HighlightAppend(&rc, p, p->zClose, -1);
  196854. p->iOff = iEndOff;
  196855. if( rc==SQLITE_OK ){
  196856. rc = fts5CInstIterNext(&p->iter);
  196857. }
  196858. }
  196859. if( p->iRangeEnd>0 && iPos==p->iRangeEnd ){
  196860. fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iEndOff - p->iOff);
  196861. p->iOff = iEndOff;
  196862. if( iPos>=p->iter.iStart && iPos<p->iter.iEnd ){
  196863. fts5HighlightAppend(&rc, p, p->zClose, -1);
  196864. }
  196865. }
  196866. return rc;
  196867. }
  196868. /*
  196869. ** Implementation of highlight() function.
  196870. */
  196871. static void fts5HighlightFunction(
  196872. const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
  196873. Fts5Context *pFts, /* First arg to pass to pApi functions */
  196874. sqlite3_context *pCtx, /* Context for returning result/error */
  196875. int nVal, /* Number of values in apVal[] array */
  196876. sqlite3_value **apVal /* Array of trailing arguments */
  196877. ){
  196878. HighlightContext ctx;
  196879. int rc;
  196880. int iCol;
  196881. if( nVal!=3 ){
  196882. const char *zErr = "wrong number of arguments to function highlight()";
  196883. sqlite3_result_error(pCtx, zErr, -1);
  196884. return;
  196885. }
  196886. iCol = sqlite3_value_int(apVal[0]);
  196887. memset(&ctx, 0, sizeof(HighlightContext));
  196888. ctx.zOpen = (const char*)sqlite3_value_text(apVal[1]);
  196889. ctx.zClose = (const char*)sqlite3_value_text(apVal[2]);
  196890. rc = pApi->xColumnText(pFts, iCol, &ctx.zIn, &ctx.nIn);
  196891. if( ctx.zIn ){
  196892. if( rc==SQLITE_OK ){
  196893. rc = fts5CInstIterInit(pApi, pFts, iCol, &ctx.iter);
  196894. }
  196895. if( rc==SQLITE_OK ){
  196896. rc = pApi->xTokenize(pFts, ctx.zIn, ctx.nIn, (void*)&ctx,fts5HighlightCb);
  196897. }
  196898. fts5HighlightAppend(&rc, &ctx, &ctx.zIn[ctx.iOff], ctx.nIn - ctx.iOff);
  196899. if( rc==SQLITE_OK ){
  196900. sqlite3_result_text(pCtx, (const char*)ctx.zOut, -1, SQLITE_TRANSIENT);
  196901. }
  196902. sqlite3_free(ctx.zOut);
  196903. }
  196904. if( rc!=SQLITE_OK ){
  196905. sqlite3_result_error_code(pCtx, rc);
  196906. }
  196907. }
  196908. /*
  196909. ** End of highlight() implementation.
  196910. **************************************************************************/
  196911. /*
  196912. ** Context object passed to the fts5SentenceFinderCb() function.
  196913. */
  196914. typedef struct Fts5SFinder Fts5SFinder;
  196915. struct Fts5SFinder {
  196916. int iPos; /* Current token position */
  196917. int nFirstAlloc; /* Allocated size of aFirst[] */
  196918. int nFirst; /* Number of entries in aFirst[] */
  196919. int *aFirst; /* Array of first token in each sentence */
  196920. const char *zDoc; /* Document being tokenized */
  196921. };
  196922. /*
  196923. ** Add an entry to the Fts5SFinder.aFirst[] array. Grow the array if
  196924. ** necessary. Return SQLITE_OK if successful, or SQLITE_NOMEM if an
  196925. ** error occurs.
  196926. */
  196927. static int fts5SentenceFinderAdd(Fts5SFinder *p, int iAdd){
  196928. if( p->nFirstAlloc==p->nFirst ){
  196929. int nNew = p->nFirstAlloc ? p->nFirstAlloc*2 : 64;
  196930. int *aNew;
  196931. aNew = (int*)sqlite3_realloc64(p->aFirst, nNew*sizeof(int));
  196932. if( aNew==0 ) return SQLITE_NOMEM;
  196933. p->aFirst = aNew;
  196934. p->nFirstAlloc = nNew;
  196935. }
  196936. p->aFirst[p->nFirst++] = iAdd;
  196937. return SQLITE_OK;
  196938. }
  196939. /*
  196940. ** This function is an xTokenize() callback used by the auxiliary snippet()
  196941. ** function. Its job is to identify tokens that are the first in a sentence.
  196942. ** For each such token, an entry is added to the SFinder.aFirst[] array.
  196943. */
  196944. static int fts5SentenceFinderCb(
  196945. void *pContext, /* Pointer to HighlightContext object */
  196946. int tflags, /* Mask of FTS5_TOKEN_* flags */
  196947. const char *pToken, /* Buffer containing token */
  196948. int nToken, /* Size of token in bytes */
  196949. int iStartOff, /* Start offset of token */
  196950. int iEndOff /* End offset of token */
  196951. ){
  196952. int rc = SQLITE_OK;
  196953. UNUSED_PARAM2(pToken, nToken);
  196954. UNUSED_PARAM(iEndOff);
  196955. if( (tflags & FTS5_TOKEN_COLOCATED)==0 ){
  196956. Fts5SFinder *p = (Fts5SFinder*)pContext;
  196957. if( p->iPos>0 ){
  196958. int i;
  196959. char c = 0;
  196960. for(i=iStartOff-1; i>=0; i--){
  196961. c = p->zDoc[i];
  196962. if( c!=' ' && c!='\t' && c!='\n' && c!='\r' ) break;
  196963. }
  196964. if( i!=iStartOff-1 && (c=='.' || c==':') ){
  196965. rc = fts5SentenceFinderAdd(p, p->iPos);
  196966. }
  196967. }else{
  196968. rc = fts5SentenceFinderAdd(p, 0);
  196969. }
  196970. p->iPos++;
  196971. }
  196972. return rc;
  196973. }
  196974. static int fts5SnippetScore(
  196975. const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
  196976. Fts5Context *pFts, /* First arg to pass to pApi functions */
  196977. int nDocsize, /* Size of column in tokens */
  196978. unsigned char *aSeen, /* Array with one element per query phrase */
  196979. int iCol, /* Column to score */
  196980. int iPos, /* Starting offset to score */
  196981. int nToken, /* Max tokens per snippet */
  196982. int *pnScore, /* OUT: Score */
  196983. int *piPos /* OUT: Adjusted offset */
  196984. ){
  196985. int rc;
  196986. int i;
  196987. int ip = 0;
  196988. int ic = 0;
  196989. int iOff = 0;
  196990. int iFirst = -1;
  196991. int nInst;
  196992. int nScore = 0;
  196993. int iLast = 0;
  196994. sqlite3_int64 iEnd = (sqlite3_int64)iPos + nToken;
  196995. rc = pApi->xInstCount(pFts, &nInst);
  196996. for(i=0; i<nInst && rc==SQLITE_OK; i++){
  196997. rc = pApi->xInst(pFts, i, &ip, &ic, &iOff);
  196998. if( rc==SQLITE_OK && ic==iCol && iOff>=iPos && iOff<iEnd ){
  196999. nScore += (aSeen[ip] ? 1 : 1000);
  197000. aSeen[ip] = 1;
  197001. if( iFirst<0 ) iFirst = iOff;
  197002. iLast = iOff + pApi->xPhraseSize(pFts, ip);
  197003. }
  197004. }
  197005. *pnScore = nScore;
  197006. if( piPos ){
  197007. sqlite3_int64 iAdj = iFirst - (nToken - (iLast-iFirst)) / 2;
  197008. if( (iAdj+nToken)>nDocsize ) iAdj = nDocsize - nToken;
  197009. if( iAdj<0 ) iAdj = 0;
  197010. *piPos = (int)iAdj;
  197011. }
  197012. return rc;
  197013. }
  197014. /*
  197015. ** Return the value in pVal interpreted as utf-8 text. Except, if pVal
  197016. ** contains a NULL value, return a pointer to a static string zero
  197017. ** bytes in length instead of a NULL pointer.
  197018. */
  197019. static const char *fts5ValueToText(sqlite3_value *pVal){
  197020. const char *zRet = (const char*)sqlite3_value_text(pVal);
  197021. return zRet ? zRet : "";
  197022. }
  197023. /*
  197024. ** Implementation of snippet() function.
  197025. */
  197026. static void fts5SnippetFunction(
  197027. const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
  197028. Fts5Context *pFts, /* First arg to pass to pApi functions */
  197029. sqlite3_context *pCtx, /* Context for returning result/error */
  197030. int nVal, /* Number of values in apVal[] array */
  197031. sqlite3_value **apVal /* Array of trailing arguments */
  197032. ){
  197033. HighlightContext ctx;
  197034. int rc = SQLITE_OK; /* Return code */
  197035. int iCol; /* 1st argument to snippet() */
  197036. const char *zEllips; /* 4th argument to snippet() */
  197037. int nToken; /* 5th argument to snippet() */
  197038. int nInst = 0; /* Number of instance matches this row */
  197039. int i; /* Used to iterate through instances */
  197040. int nPhrase; /* Number of phrases in query */
  197041. unsigned char *aSeen; /* Array of "seen instance" flags */
  197042. int iBestCol; /* Column containing best snippet */
  197043. int iBestStart = 0; /* First token of best snippet */
  197044. int nBestScore = 0; /* Score of best snippet */
  197045. int nColSize = 0; /* Total size of iBestCol in tokens */
  197046. Fts5SFinder sFinder; /* Used to find the beginnings of sentences */
  197047. int nCol;
  197048. if( nVal!=5 ){
  197049. const char *zErr = "wrong number of arguments to function snippet()";
  197050. sqlite3_result_error(pCtx, zErr, -1);
  197051. return;
  197052. }
  197053. nCol = pApi->xColumnCount(pFts);
  197054. memset(&ctx, 0, sizeof(HighlightContext));
  197055. iCol = sqlite3_value_int(apVal[0]);
  197056. ctx.zOpen = fts5ValueToText(apVal[1]);
  197057. ctx.zClose = fts5ValueToText(apVal[2]);
  197058. zEllips = fts5ValueToText(apVal[3]);
  197059. nToken = sqlite3_value_int(apVal[4]);
  197060. iBestCol = (iCol>=0 ? iCol : 0);
  197061. nPhrase = pApi->xPhraseCount(pFts);
  197062. aSeen = sqlite3_malloc(nPhrase);
  197063. if( aSeen==0 ){
  197064. rc = SQLITE_NOMEM;
  197065. }
  197066. if( rc==SQLITE_OK ){
  197067. rc = pApi->xInstCount(pFts, &nInst);
  197068. }
  197069. memset(&sFinder, 0, sizeof(Fts5SFinder));
  197070. for(i=0; i<nCol; i++){
  197071. if( iCol<0 || iCol==i ){
  197072. int nDoc;
  197073. int nDocsize;
  197074. int ii;
  197075. sFinder.iPos = 0;
  197076. sFinder.nFirst = 0;
  197077. rc = pApi->xColumnText(pFts, i, &sFinder.zDoc, &nDoc);
  197078. if( rc!=SQLITE_OK ) break;
  197079. rc = pApi->xTokenize(pFts,
  197080. sFinder.zDoc, nDoc, (void*)&sFinder,fts5SentenceFinderCb
  197081. );
  197082. if( rc!=SQLITE_OK ) break;
  197083. rc = pApi->xColumnSize(pFts, i, &nDocsize);
  197084. if( rc!=SQLITE_OK ) break;
  197085. for(ii=0; rc==SQLITE_OK && ii<nInst; ii++){
  197086. int ip, ic, io;
  197087. int iAdj;
  197088. int nScore;
  197089. int jj;
  197090. rc = pApi->xInst(pFts, ii, &ip, &ic, &io);
  197091. if( ic!=i ) continue;
  197092. if( io>nDocsize ) rc = FTS5_CORRUPT;
  197093. if( rc!=SQLITE_OK ) continue;
  197094. memset(aSeen, 0, nPhrase);
  197095. rc = fts5SnippetScore(pApi, pFts, nDocsize, aSeen, i,
  197096. io, nToken, &nScore, &iAdj
  197097. );
  197098. if( rc==SQLITE_OK && nScore>nBestScore ){
  197099. nBestScore = nScore;
  197100. iBestCol = i;
  197101. iBestStart = iAdj;
  197102. nColSize = nDocsize;
  197103. }
  197104. if( rc==SQLITE_OK && sFinder.nFirst && nDocsize>nToken ){
  197105. for(jj=0; jj<(sFinder.nFirst-1); jj++){
  197106. if( sFinder.aFirst[jj+1]>io ) break;
  197107. }
  197108. if( sFinder.aFirst[jj]<io ){
  197109. memset(aSeen, 0, nPhrase);
  197110. rc = fts5SnippetScore(pApi, pFts, nDocsize, aSeen, i,
  197111. sFinder.aFirst[jj], nToken, &nScore, 0
  197112. );
  197113. nScore += (sFinder.aFirst[jj]==0 ? 120 : 100);
  197114. if( rc==SQLITE_OK && nScore>nBestScore ){
  197115. nBestScore = nScore;
  197116. iBestCol = i;
  197117. iBestStart = sFinder.aFirst[jj];
  197118. nColSize = nDocsize;
  197119. }
  197120. }
  197121. }
  197122. }
  197123. }
  197124. }
  197125. if( rc==SQLITE_OK ){
  197126. rc = pApi->xColumnText(pFts, iBestCol, &ctx.zIn, &ctx.nIn);
  197127. }
  197128. if( rc==SQLITE_OK && nColSize==0 ){
  197129. rc = pApi->xColumnSize(pFts, iBestCol, &nColSize);
  197130. }
  197131. if( ctx.zIn ){
  197132. if( rc==SQLITE_OK ){
  197133. rc = fts5CInstIterInit(pApi, pFts, iBestCol, &ctx.iter);
  197134. }
  197135. ctx.iRangeStart = iBestStart;
  197136. ctx.iRangeEnd = iBestStart + nToken - 1;
  197137. if( iBestStart>0 ){
  197138. fts5HighlightAppend(&rc, &ctx, zEllips, -1);
  197139. }
  197140. /* Advance iterator ctx.iter so that it points to the first coalesced
  197141. ** phrase instance at or following position iBestStart. */
  197142. while( ctx.iter.iStart>=0 && ctx.iter.iStart<iBestStart && rc==SQLITE_OK ){
  197143. rc = fts5CInstIterNext(&ctx.iter);
  197144. }
  197145. if( rc==SQLITE_OK ){
  197146. rc = pApi->xTokenize(pFts, ctx.zIn, ctx.nIn, (void*)&ctx,fts5HighlightCb);
  197147. }
  197148. if( ctx.iRangeEnd>=(nColSize-1) ){
  197149. fts5HighlightAppend(&rc, &ctx, &ctx.zIn[ctx.iOff], ctx.nIn - ctx.iOff);
  197150. }else{
  197151. fts5HighlightAppend(&rc, &ctx, zEllips, -1);
  197152. }
  197153. }
  197154. if( rc==SQLITE_OK ){
  197155. sqlite3_result_text(pCtx, (const char*)ctx.zOut, -1, SQLITE_TRANSIENT);
  197156. }else{
  197157. sqlite3_result_error_code(pCtx, rc);
  197158. }
  197159. sqlite3_free(ctx.zOut);
  197160. sqlite3_free(aSeen);
  197161. sqlite3_free(sFinder.aFirst);
  197162. }
  197163. /************************************************************************/
  197164. /*
  197165. ** The first time the bm25() function is called for a query, an instance
  197166. ** of the following structure is allocated and populated.
  197167. */
  197168. typedef struct Fts5Bm25Data Fts5Bm25Data;
  197169. struct Fts5Bm25Data {
  197170. int nPhrase; /* Number of phrases in query */
  197171. double avgdl; /* Average number of tokens in each row */
  197172. double *aIDF; /* IDF for each phrase */
  197173. double *aFreq; /* Array used to calculate phrase freq. */
  197174. };
  197175. /*
  197176. ** Callback used by fts5Bm25GetData() to count the number of rows in the
  197177. ** table matched by each individual phrase within the query.
  197178. */
  197179. static int fts5CountCb(
  197180. const Fts5ExtensionApi *pApi,
  197181. Fts5Context *pFts,
  197182. void *pUserData /* Pointer to sqlite3_int64 variable */
  197183. ){
  197184. sqlite3_int64 *pn = (sqlite3_int64*)pUserData;
  197185. UNUSED_PARAM2(pApi, pFts);
  197186. (*pn)++;
  197187. return SQLITE_OK;
  197188. }
  197189. /*
  197190. ** Set *ppData to point to the Fts5Bm25Data object for the current query.
  197191. ** If the object has not already been allocated, allocate and populate it
  197192. ** now.
  197193. */
  197194. static int fts5Bm25GetData(
  197195. const Fts5ExtensionApi *pApi,
  197196. Fts5Context *pFts,
  197197. Fts5Bm25Data **ppData /* OUT: bm25-data object for this query */
  197198. ){
  197199. int rc = SQLITE_OK; /* Return code */
  197200. Fts5Bm25Data *p; /* Object to return */
  197201. p = pApi->xGetAuxdata(pFts, 0);
  197202. if( p==0 ){
  197203. int nPhrase; /* Number of phrases in query */
  197204. sqlite3_int64 nRow = 0; /* Number of rows in table */
  197205. sqlite3_int64 nToken = 0; /* Number of tokens in table */
  197206. sqlite3_int64 nByte; /* Bytes of space to allocate */
  197207. int i;
  197208. /* Allocate the Fts5Bm25Data object */
  197209. nPhrase = pApi->xPhraseCount(pFts);
  197210. nByte = sizeof(Fts5Bm25Data) + nPhrase*2*sizeof(double);
  197211. p = (Fts5Bm25Data*)sqlite3_malloc64(nByte);
  197212. if( p==0 ){
  197213. rc = SQLITE_NOMEM;
  197214. }else{
  197215. memset(p, 0, (size_t)nByte);
  197216. p->nPhrase = nPhrase;
  197217. p->aIDF = (double*)&p[1];
  197218. p->aFreq = &p->aIDF[nPhrase];
  197219. }
  197220. /* Calculate the average document length for this FTS5 table */
  197221. if( rc==SQLITE_OK ) rc = pApi->xRowCount(pFts, &nRow);
  197222. assert( rc!=SQLITE_OK || nRow>0 );
  197223. if( rc==SQLITE_OK ) rc = pApi->xColumnTotalSize(pFts, -1, &nToken);
  197224. if( rc==SQLITE_OK ) p->avgdl = (double)nToken / (double)nRow;
  197225. /* Calculate an IDF for each phrase in the query */
  197226. for(i=0; rc==SQLITE_OK && i<nPhrase; i++){
  197227. sqlite3_int64 nHit = 0;
  197228. rc = pApi->xQueryPhrase(pFts, i, (void*)&nHit, fts5CountCb);
  197229. if( rc==SQLITE_OK ){
  197230. /* Calculate the IDF (Inverse Document Frequency) for phrase i.
  197231. ** This is done using the standard BM25 formula as found on wikipedia:
  197232. **
  197233. ** IDF = log( (N - nHit + 0.5) / (nHit + 0.5) )
  197234. **
  197235. ** where "N" is the total number of documents in the set and nHit
  197236. ** is the number that contain at least one instance of the phrase
  197237. ** under consideration.
  197238. **
  197239. ** The problem with this is that if (N < 2*nHit), the IDF is
  197240. ** negative. Which is undesirable. So the mimimum allowable IDF is
  197241. ** (1e-6) - roughly the same as a term that appears in just over
  197242. ** half of set of 5,000,000 documents. */
  197243. double idf = log( (nRow - nHit + 0.5) / (nHit + 0.5) );
  197244. if( idf<=0.0 ) idf = 1e-6;
  197245. p->aIDF[i] = idf;
  197246. }
  197247. }
  197248. if( rc!=SQLITE_OK ){
  197249. sqlite3_free(p);
  197250. }else{
  197251. rc = pApi->xSetAuxdata(pFts, p, sqlite3_free);
  197252. }
  197253. if( rc!=SQLITE_OK ) p = 0;
  197254. }
  197255. *ppData = p;
  197256. return rc;
  197257. }
  197258. /*
  197259. ** Implementation of bm25() function.
  197260. */
  197261. static void fts5Bm25Function(
  197262. const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
  197263. Fts5Context *pFts, /* First arg to pass to pApi functions */
  197264. sqlite3_context *pCtx, /* Context for returning result/error */
  197265. int nVal, /* Number of values in apVal[] array */
  197266. sqlite3_value **apVal /* Array of trailing arguments */
  197267. ){
  197268. const double k1 = 1.2; /* Constant "k1" from BM25 formula */
  197269. const double b = 0.75; /* Constant "b" from BM25 formula */
  197270. int rc = SQLITE_OK; /* Error code */
  197271. double score = 0.0; /* SQL function return value */
  197272. Fts5Bm25Data *pData; /* Values allocated/calculated once only */
  197273. int i; /* Iterator variable */
  197274. int nInst = 0; /* Value returned by xInstCount() */
  197275. double D = 0.0; /* Total number of tokens in row */
  197276. double *aFreq = 0; /* Array of phrase freq. for current row */
  197277. /* Calculate the phrase frequency (symbol "f(qi,D)" in the documentation)
  197278. ** for each phrase in the query for the current row. */
  197279. rc = fts5Bm25GetData(pApi, pFts, &pData);
  197280. if( rc==SQLITE_OK ){
  197281. aFreq = pData->aFreq;
  197282. memset(aFreq, 0, sizeof(double) * pData->nPhrase);
  197283. rc = pApi->xInstCount(pFts, &nInst);
  197284. }
  197285. for(i=0; rc==SQLITE_OK && i<nInst; i++){
  197286. int ip; int ic; int io;
  197287. rc = pApi->xInst(pFts, i, &ip, &ic, &io);
  197288. if( rc==SQLITE_OK ){
  197289. double w = (nVal > ic) ? sqlite3_value_double(apVal[ic]) : 1.0;
  197290. aFreq[ip] += w;
  197291. }
  197292. }
  197293. /* Figure out the total size of the current row in tokens. */
  197294. if( rc==SQLITE_OK ){
  197295. int nTok;
  197296. rc = pApi->xColumnSize(pFts, -1, &nTok);
  197297. D = (double)nTok;
  197298. }
  197299. /* Determine the BM25 score for the current row. */
  197300. for(i=0; rc==SQLITE_OK && i<pData->nPhrase; i++){
  197301. score += pData->aIDF[i] * (
  197302. ( aFreq[i] * (k1 + 1.0) ) /
  197303. ( aFreq[i] + k1 * (1 - b + b * D / pData->avgdl) )
  197304. );
  197305. }
  197306. /* If no error has occurred, return the calculated score. Otherwise,
  197307. ** throw an SQL exception. */
  197308. if( rc==SQLITE_OK ){
  197309. sqlite3_result_double(pCtx, -1.0 * score);
  197310. }else{
  197311. sqlite3_result_error_code(pCtx, rc);
  197312. }
  197313. }
  197314. static int sqlite3Fts5AuxInit(fts5_api *pApi){
  197315. struct Builtin {
  197316. const char *zFunc; /* Function name (nul-terminated) */
  197317. void *pUserData; /* User-data pointer */
  197318. fts5_extension_function xFunc;/* Callback function */
  197319. void (*xDestroy)(void*); /* Destructor function */
  197320. } aBuiltin [] = {
  197321. { "snippet", 0, fts5SnippetFunction, 0 },
  197322. { "highlight", 0, fts5HighlightFunction, 0 },
  197323. { "bm25", 0, fts5Bm25Function, 0 },
  197324. };
  197325. int rc = SQLITE_OK; /* Return code */
  197326. int i; /* To iterate through builtin functions */
  197327. for(i=0; rc==SQLITE_OK && i<ArraySize(aBuiltin); i++){
  197328. rc = pApi->xCreateFunction(pApi,
  197329. aBuiltin[i].zFunc,
  197330. aBuiltin[i].pUserData,
  197331. aBuiltin[i].xFunc,
  197332. aBuiltin[i].xDestroy
  197333. );
  197334. }
  197335. return rc;
  197336. }
  197337. /*
  197338. ** 2014 May 31
  197339. **
  197340. ** The author disclaims copyright to this source code. In place of
  197341. ** a legal notice, here is a blessing:
  197342. **
  197343. ** May you do good and not evil.
  197344. ** May you find forgiveness for yourself and forgive others.
  197345. ** May you share freely, never taking more than you give.
  197346. **
  197347. ******************************************************************************
  197348. */
  197349. /* #include "fts5Int.h" */
  197350. static int sqlite3Fts5BufferSize(int *pRc, Fts5Buffer *pBuf, u32 nByte){
  197351. if( (u32)pBuf->nSpace<nByte ){
  197352. u64 nNew = pBuf->nSpace ? pBuf->nSpace : 64;
  197353. u8 *pNew;
  197354. while( nNew<nByte ){
  197355. nNew = nNew * 2;
  197356. }
  197357. pNew = sqlite3_realloc64(pBuf->p, nNew);
  197358. if( pNew==0 ){
  197359. *pRc = SQLITE_NOMEM;
  197360. return 1;
  197361. }else{
  197362. pBuf->nSpace = (int)nNew;
  197363. pBuf->p = pNew;
  197364. }
  197365. }
  197366. return 0;
  197367. }
  197368. /*
  197369. ** Encode value iVal as an SQLite varint and append it to the buffer object
  197370. ** pBuf. If an OOM error occurs, set the error code in p.
  197371. */
  197372. static void sqlite3Fts5BufferAppendVarint(int *pRc, Fts5Buffer *pBuf, i64 iVal){
  197373. if( fts5BufferGrow(pRc, pBuf, 9) ) return;
  197374. pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iVal);
  197375. }
  197376. static void sqlite3Fts5Put32(u8 *aBuf, int iVal){
  197377. aBuf[0] = (iVal>>24) & 0x00FF;
  197378. aBuf[1] = (iVal>>16) & 0x00FF;
  197379. aBuf[2] = (iVal>> 8) & 0x00FF;
  197380. aBuf[3] = (iVal>> 0) & 0x00FF;
  197381. }
  197382. static int sqlite3Fts5Get32(const u8 *aBuf){
  197383. return (int)((((u32)aBuf[0])<<24) + (aBuf[1]<<16) + (aBuf[2]<<8) + aBuf[3]);
  197384. }
  197385. /*
  197386. ** Append buffer nData/pData to buffer pBuf. If an OOM error occurs, set
  197387. ** the error code in p. If an error has already occurred when this function
  197388. ** is called, it is a no-op.
  197389. */
  197390. static void sqlite3Fts5BufferAppendBlob(
  197391. int *pRc,
  197392. Fts5Buffer *pBuf,
  197393. u32 nData,
  197394. const u8 *pData
  197395. ){
  197396. assert_nc( *pRc || nData>=0 );
  197397. if( nData ){
  197398. if( fts5BufferGrow(pRc, pBuf, nData) ) return;
  197399. memcpy(&pBuf->p[pBuf->n], pData, nData);
  197400. pBuf->n += nData;
  197401. }
  197402. }
  197403. /*
  197404. ** Append the nul-terminated string zStr to the buffer pBuf. This function
  197405. ** ensures that the byte following the buffer data is set to 0x00, even
  197406. ** though this byte is not included in the pBuf->n count.
  197407. */
  197408. static void sqlite3Fts5BufferAppendString(
  197409. int *pRc,
  197410. Fts5Buffer *pBuf,
  197411. const char *zStr
  197412. ){
  197413. int nStr = (int)strlen(zStr);
  197414. sqlite3Fts5BufferAppendBlob(pRc, pBuf, nStr+1, (const u8*)zStr);
  197415. pBuf->n--;
  197416. }
  197417. /*
  197418. ** Argument zFmt is a printf() style format string. This function performs
  197419. ** the printf() style processing, then appends the results to buffer pBuf.
  197420. **
  197421. ** Like sqlite3Fts5BufferAppendString(), this function ensures that the byte
  197422. ** following the buffer data is set to 0x00, even though this byte is not
  197423. ** included in the pBuf->n count.
  197424. */
  197425. static void sqlite3Fts5BufferAppendPrintf(
  197426. int *pRc,
  197427. Fts5Buffer *pBuf,
  197428. char *zFmt, ...
  197429. ){
  197430. if( *pRc==SQLITE_OK ){
  197431. char *zTmp;
  197432. va_list ap;
  197433. va_start(ap, zFmt);
  197434. zTmp = sqlite3_vmprintf(zFmt, ap);
  197435. va_end(ap);
  197436. if( zTmp==0 ){
  197437. *pRc = SQLITE_NOMEM;
  197438. }else{
  197439. sqlite3Fts5BufferAppendString(pRc, pBuf, zTmp);
  197440. sqlite3_free(zTmp);
  197441. }
  197442. }
  197443. }
  197444. static char *sqlite3Fts5Mprintf(int *pRc, const char *zFmt, ...){
  197445. char *zRet = 0;
  197446. if( *pRc==SQLITE_OK ){
  197447. va_list ap;
  197448. va_start(ap, zFmt);
  197449. zRet = sqlite3_vmprintf(zFmt, ap);
  197450. va_end(ap);
  197451. if( zRet==0 ){
  197452. *pRc = SQLITE_NOMEM;
  197453. }
  197454. }
  197455. return zRet;
  197456. }
  197457. /*
  197458. ** Free any buffer allocated by pBuf. Zero the structure before returning.
  197459. */
  197460. static void sqlite3Fts5BufferFree(Fts5Buffer *pBuf){
  197461. sqlite3_free(pBuf->p);
  197462. memset(pBuf, 0, sizeof(Fts5Buffer));
  197463. }
  197464. /*
  197465. ** Zero the contents of the buffer object. But do not free the associated
  197466. ** memory allocation.
  197467. */
  197468. static void sqlite3Fts5BufferZero(Fts5Buffer *pBuf){
  197469. pBuf->n = 0;
  197470. }
  197471. /*
  197472. ** Set the buffer to contain nData/pData. If an OOM error occurs, leave an
  197473. ** the error code in p. If an error has already occurred when this function
  197474. ** is called, it is a no-op.
  197475. */
  197476. static void sqlite3Fts5BufferSet(
  197477. int *pRc,
  197478. Fts5Buffer *pBuf,
  197479. int nData,
  197480. const u8 *pData
  197481. ){
  197482. pBuf->n = 0;
  197483. sqlite3Fts5BufferAppendBlob(pRc, pBuf, nData, pData);
  197484. }
  197485. static int sqlite3Fts5PoslistNext64(
  197486. const u8 *a, int n, /* Buffer containing poslist */
  197487. int *pi, /* IN/OUT: Offset within a[] */
  197488. i64 *piOff /* IN/OUT: Current offset */
  197489. ){
  197490. int i = *pi;
  197491. if( i>=n ){
  197492. /* EOF */
  197493. *piOff = -1;
  197494. return 1;
  197495. }else{
  197496. i64 iOff = *piOff;
  197497. int iVal;
  197498. fts5FastGetVarint32(a, i, iVal);
  197499. if( iVal<=1 ){
  197500. if( iVal==0 ){
  197501. *pi = i;
  197502. return 0;
  197503. }
  197504. fts5FastGetVarint32(a, i, iVal);
  197505. iOff = ((i64)iVal) << 32;
  197506. fts5FastGetVarint32(a, i, iVal);
  197507. if( iVal<2 ){
  197508. /* This is a corrupt record. So stop parsing it here. */
  197509. *piOff = -1;
  197510. return 1;
  197511. }
  197512. }
  197513. *piOff = iOff + ((iVal-2) & 0x7FFFFFFF);
  197514. *pi = i;
  197515. return 0;
  197516. }
  197517. }
  197518. /*
  197519. ** Advance the iterator object passed as the only argument. Return true
  197520. ** if the iterator reaches EOF, or false otherwise.
  197521. */
  197522. static int sqlite3Fts5PoslistReaderNext(Fts5PoslistReader *pIter){
  197523. if( sqlite3Fts5PoslistNext64(pIter->a, pIter->n, &pIter->i, &pIter->iPos) ){
  197524. pIter->bEof = 1;
  197525. }
  197526. return pIter->bEof;
  197527. }
  197528. static int sqlite3Fts5PoslistReaderInit(
  197529. const u8 *a, int n, /* Poslist buffer to iterate through */
  197530. Fts5PoslistReader *pIter /* Iterator object to initialize */
  197531. ){
  197532. memset(pIter, 0, sizeof(*pIter));
  197533. pIter->a = a;
  197534. pIter->n = n;
  197535. sqlite3Fts5PoslistReaderNext(pIter);
  197536. return pIter->bEof;
  197537. }
  197538. /*
  197539. ** Append position iPos to the position list being accumulated in buffer
  197540. ** pBuf, which must be already be large enough to hold the new data.
  197541. ** The previous position written to this list is *piPrev. *piPrev is set
  197542. ** to iPos before returning.
  197543. */
  197544. static void sqlite3Fts5PoslistSafeAppend(
  197545. Fts5Buffer *pBuf,
  197546. i64 *piPrev,
  197547. i64 iPos
  197548. ){
  197549. static const i64 colmask = ((i64)(0x7FFFFFFF)) << 32;
  197550. if( (iPos & colmask) != (*piPrev & colmask) ){
  197551. pBuf->p[pBuf->n++] = 1;
  197552. pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], (iPos>>32));
  197553. *piPrev = (iPos & colmask);
  197554. }
  197555. pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], (iPos-*piPrev)+2);
  197556. *piPrev = iPos;
  197557. }
  197558. static int sqlite3Fts5PoslistWriterAppend(
  197559. Fts5Buffer *pBuf,
  197560. Fts5PoslistWriter *pWriter,
  197561. i64 iPos
  197562. ){
  197563. int rc = 0; /* Initialized only to suppress erroneous warning from Clang */
  197564. if( fts5BufferGrow(&rc, pBuf, 5+5+5) ) return rc;
  197565. sqlite3Fts5PoslistSafeAppend(pBuf, &pWriter->iPrev, iPos);
  197566. return SQLITE_OK;
  197567. }
  197568. static void *sqlite3Fts5MallocZero(int *pRc, sqlite3_int64 nByte){
  197569. void *pRet = 0;
  197570. if( *pRc==SQLITE_OK ){
  197571. pRet = sqlite3_malloc64(nByte);
  197572. if( pRet==0 ){
  197573. if( nByte>0 ) *pRc = SQLITE_NOMEM;
  197574. }else{
  197575. memset(pRet, 0, (size_t)nByte);
  197576. }
  197577. }
  197578. return pRet;
  197579. }
  197580. /*
  197581. ** Return a nul-terminated copy of the string indicated by pIn. If nIn
  197582. ** is non-negative, then it is the length of the string in bytes. Otherwise,
  197583. ** the length of the string is determined using strlen().
  197584. **
  197585. ** It is the responsibility of the caller to eventually free the returned
  197586. ** buffer using sqlite3_free(). If an OOM error occurs, NULL is returned.
  197587. */
  197588. static char *sqlite3Fts5Strndup(int *pRc, const char *pIn, int nIn){
  197589. char *zRet = 0;
  197590. if( *pRc==SQLITE_OK ){
  197591. if( nIn<0 ){
  197592. nIn = (int)strlen(pIn);
  197593. }
  197594. zRet = (char*)sqlite3_malloc(nIn+1);
  197595. if( zRet ){
  197596. memcpy(zRet, pIn, nIn);
  197597. zRet[nIn] = '\0';
  197598. }else{
  197599. *pRc = SQLITE_NOMEM;
  197600. }
  197601. }
  197602. return zRet;
  197603. }
  197604. /*
  197605. ** Return true if character 't' may be part of an FTS5 bareword, or false
  197606. ** otherwise. Characters that may be part of barewords:
  197607. **
  197608. ** * All non-ASCII characters,
  197609. ** * The 52 upper and lower case ASCII characters, and
  197610. ** * The 10 integer ASCII characters.
  197611. ** * The underscore character "_" (0x5F).
  197612. ** * The unicode "subsitute" character (0x1A).
  197613. */
  197614. static int sqlite3Fts5IsBareword(char t){
  197615. u8 aBareword[128] = {
  197616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x00 .. 0x0F */
  197617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, /* 0x10 .. 0x1F */
  197618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x20 .. 0x2F */
  197619. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 0x30 .. 0x3F */
  197620. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x40 .. 0x4F */
  197621. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 0x50 .. 0x5F */
  197622. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x60 .. 0x6F */
  197623. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 /* 0x70 .. 0x7F */
  197624. };
  197625. return (t & 0x80) || aBareword[(int)t];
  197626. }
  197627. /*************************************************************************
  197628. */
  197629. typedef struct Fts5TermsetEntry Fts5TermsetEntry;
  197630. struct Fts5TermsetEntry {
  197631. char *pTerm;
  197632. int nTerm;
  197633. int iIdx; /* Index (main or aPrefix[] entry) */
  197634. Fts5TermsetEntry *pNext;
  197635. };
  197636. struct Fts5Termset {
  197637. Fts5TermsetEntry *apHash[512];
  197638. };
  197639. static int sqlite3Fts5TermsetNew(Fts5Termset **pp){
  197640. int rc = SQLITE_OK;
  197641. *pp = sqlite3Fts5MallocZero(&rc, sizeof(Fts5Termset));
  197642. return rc;
  197643. }
  197644. static int sqlite3Fts5TermsetAdd(
  197645. Fts5Termset *p,
  197646. int iIdx,
  197647. const char *pTerm, int nTerm,
  197648. int *pbPresent
  197649. ){
  197650. int rc = SQLITE_OK;
  197651. *pbPresent = 0;
  197652. if( p ){
  197653. int i;
  197654. u32 hash = 13;
  197655. Fts5TermsetEntry *pEntry;
  197656. /* Calculate a hash value for this term. This is the same hash checksum
  197657. ** used by the fts5_hash.c module. This is not important for correct
  197658. ** operation of the module, but is necessary to ensure that some tests
  197659. ** designed to produce hash table collisions really do work. */
  197660. for(i=nTerm-1; i>=0; i--){
  197661. hash = (hash << 3) ^ hash ^ pTerm[i];
  197662. }
  197663. hash = (hash << 3) ^ hash ^ iIdx;
  197664. hash = hash % ArraySize(p->apHash);
  197665. for(pEntry=p->apHash[hash]; pEntry; pEntry=pEntry->pNext){
  197666. if( pEntry->iIdx==iIdx
  197667. && pEntry->nTerm==nTerm
  197668. && memcmp(pEntry->pTerm, pTerm, nTerm)==0
  197669. ){
  197670. *pbPresent = 1;
  197671. break;
  197672. }
  197673. }
  197674. if( pEntry==0 ){
  197675. pEntry = sqlite3Fts5MallocZero(&rc, sizeof(Fts5TermsetEntry) + nTerm);
  197676. if( pEntry ){
  197677. pEntry->pTerm = (char*)&pEntry[1];
  197678. pEntry->nTerm = nTerm;
  197679. pEntry->iIdx = iIdx;
  197680. memcpy(pEntry->pTerm, pTerm, nTerm);
  197681. pEntry->pNext = p->apHash[hash];
  197682. p->apHash[hash] = pEntry;
  197683. }
  197684. }
  197685. }
  197686. return rc;
  197687. }
  197688. static void sqlite3Fts5TermsetFree(Fts5Termset *p){
  197689. if( p ){
  197690. u32 i;
  197691. for(i=0; i<ArraySize(p->apHash); i++){
  197692. Fts5TermsetEntry *pEntry = p->apHash[i];
  197693. while( pEntry ){
  197694. Fts5TermsetEntry *pDel = pEntry;
  197695. pEntry = pEntry->pNext;
  197696. sqlite3_free(pDel);
  197697. }
  197698. }
  197699. sqlite3_free(p);
  197700. }
  197701. }
  197702. /*
  197703. ** 2014 Jun 09
  197704. **
  197705. ** The author disclaims copyright to this source code. In place of
  197706. ** a legal notice, here is a blessing:
  197707. **
  197708. ** May you do good and not evil.
  197709. ** May you find forgiveness for yourself and forgive others.
  197710. ** May you share freely, never taking more than you give.
  197711. **
  197712. ******************************************************************************
  197713. **
  197714. ** This is an SQLite module implementing full-text search.
  197715. */
  197716. /* #include "fts5Int.h" */
  197717. #define FTS5_DEFAULT_PAGE_SIZE 4050
  197718. #define FTS5_DEFAULT_AUTOMERGE 4
  197719. #define FTS5_DEFAULT_USERMERGE 4
  197720. #define FTS5_DEFAULT_CRISISMERGE 16
  197721. #define FTS5_DEFAULT_HASHSIZE (1024*1024)
  197722. /* Maximum allowed page size */
  197723. #define FTS5_MAX_PAGE_SIZE (64*1024)
  197724. static int fts5_iswhitespace(char x){
  197725. return (x==' ');
  197726. }
  197727. static int fts5_isopenquote(char x){
  197728. return (x=='"' || x=='\'' || x=='[' || x=='`');
  197729. }
  197730. /*
  197731. ** Argument pIn points to a character that is part of a nul-terminated
  197732. ** string. Return a pointer to the first character following *pIn in
  197733. ** the string that is not a white-space character.
  197734. */
  197735. static const char *fts5ConfigSkipWhitespace(const char *pIn){
  197736. const char *p = pIn;
  197737. if( p ){
  197738. while( fts5_iswhitespace(*p) ){ p++; }
  197739. }
  197740. return p;
  197741. }
  197742. /*
  197743. ** Argument pIn points to a character that is part of a nul-terminated
  197744. ** string. Return a pointer to the first character following *pIn in
  197745. ** the string that is not a "bareword" character.
  197746. */
  197747. static const char *fts5ConfigSkipBareword(const char *pIn){
  197748. const char *p = pIn;
  197749. while ( sqlite3Fts5IsBareword(*p) ) p++;
  197750. if( p==pIn ) p = 0;
  197751. return p;
  197752. }
  197753. static int fts5_isdigit(char a){
  197754. return (a>='0' && a<='9');
  197755. }
  197756. static const char *fts5ConfigSkipLiteral(const char *pIn){
  197757. const char *p = pIn;
  197758. switch( *p ){
  197759. case 'n': case 'N':
  197760. if( sqlite3_strnicmp("null", p, 4)==0 ){
  197761. p = &p[4];
  197762. }else{
  197763. p = 0;
  197764. }
  197765. break;
  197766. case 'x': case 'X':
  197767. p++;
  197768. if( *p=='\'' ){
  197769. p++;
  197770. while( (*p>='a' && *p<='f')
  197771. || (*p>='A' && *p<='F')
  197772. || (*p>='0' && *p<='9')
  197773. ){
  197774. p++;
  197775. }
  197776. if( *p=='\'' && 0==((p-pIn)%2) ){
  197777. p++;
  197778. }else{
  197779. p = 0;
  197780. }
  197781. }else{
  197782. p = 0;
  197783. }
  197784. break;
  197785. case '\'':
  197786. p++;
  197787. while( p ){
  197788. if( *p=='\'' ){
  197789. p++;
  197790. if( *p!='\'' ) break;
  197791. }
  197792. p++;
  197793. if( *p==0 ) p = 0;
  197794. }
  197795. break;
  197796. default:
  197797. /* maybe a number */
  197798. if( *p=='+' || *p=='-' ) p++;
  197799. while( fts5_isdigit(*p) ) p++;
  197800. /* At this point, if the literal was an integer, the parse is
  197801. ** finished. Or, if it is a floating point value, it may continue
  197802. ** with either a decimal point or an 'E' character. */
  197803. if( *p=='.' && fts5_isdigit(p[1]) ){
  197804. p += 2;
  197805. while( fts5_isdigit(*p) ) p++;
  197806. }
  197807. if( p==pIn ) p = 0;
  197808. break;
  197809. }
  197810. return p;
  197811. }
  197812. /*
  197813. ** The first character of the string pointed to by argument z is guaranteed
  197814. ** to be an open-quote character (see function fts5_isopenquote()).
  197815. **
  197816. ** This function searches for the corresponding close-quote character within
  197817. ** the string and, if found, dequotes the string in place and adds a new
  197818. ** nul-terminator byte.
  197819. **
  197820. ** If the close-quote is found, the value returned is the byte offset of
  197821. ** the character immediately following it. Or, if the close-quote is not
  197822. ** found, -1 is returned. If -1 is returned, the buffer is left in an
  197823. ** undefined state.
  197824. */
  197825. static int fts5Dequote(char *z){
  197826. char q;
  197827. int iIn = 1;
  197828. int iOut = 0;
  197829. q = z[0];
  197830. /* Set stack variable q to the close-quote character */
  197831. assert( q=='[' || q=='\'' || q=='"' || q=='`' );
  197832. if( q=='[' ) q = ']';
  197833. while( z[iIn] ){
  197834. if( z[iIn]==q ){
  197835. if( z[iIn+1]!=q ){
  197836. /* Character iIn was the close quote. */
  197837. iIn++;
  197838. break;
  197839. }else{
  197840. /* Character iIn and iIn+1 form an escaped quote character. Skip
  197841. ** the input cursor past both and copy a single quote character
  197842. ** to the output buffer. */
  197843. iIn += 2;
  197844. z[iOut++] = q;
  197845. }
  197846. }else{
  197847. z[iOut++] = z[iIn++];
  197848. }
  197849. }
  197850. z[iOut] = '\0';
  197851. return iIn;
  197852. }
  197853. /*
  197854. ** Convert an SQL-style quoted string into a normal string by removing
  197855. ** the quote characters. The conversion is done in-place. If the
  197856. ** input does not begin with a quote character, then this routine
  197857. ** is a no-op.
  197858. **
  197859. ** Examples:
  197860. **
  197861. ** "abc" becomes abc
  197862. ** 'xyz' becomes xyz
  197863. ** [pqr] becomes pqr
  197864. ** `mno` becomes mno
  197865. */
  197866. static void sqlite3Fts5Dequote(char *z){
  197867. char quote; /* Quote character (if any ) */
  197868. assert( 0==fts5_iswhitespace(z[0]) );
  197869. quote = z[0];
  197870. if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
  197871. fts5Dequote(z);
  197872. }
  197873. }
  197874. struct Fts5Enum {
  197875. const char *zName;
  197876. int eVal;
  197877. };
  197878. typedef struct Fts5Enum Fts5Enum;
  197879. static int fts5ConfigSetEnum(
  197880. const Fts5Enum *aEnum,
  197881. const char *zEnum,
  197882. int *peVal
  197883. ){
  197884. int nEnum = (int)strlen(zEnum);
  197885. int i;
  197886. int iVal = -1;
  197887. for(i=0; aEnum[i].zName; i++){
  197888. if( sqlite3_strnicmp(aEnum[i].zName, zEnum, nEnum)==0 ){
  197889. if( iVal>=0 ) return SQLITE_ERROR;
  197890. iVal = aEnum[i].eVal;
  197891. }
  197892. }
  197893. *peVal = iVal;
  197894. return iVal<0 ? SQLITE_ERROR : SQLITE_OK;
  197895. }
  197896. /*
  197897. ** Parse a "special" CREATE VIRTUAL TABLE directive and update
  197898. ** configuration object pConfig as appropriate.
  197899. **
  197900. ** If successful, object pConfig is updated and SQLITE_OK returned. If
  197901. ** an error occurs, an SQLite error code is returned and an error message
  197902. ** may be left in *pzErr. It is the responsibility of the caller to
  197903. ** eventually free any such error message using sqlite3_free().
  197904. */
  197905. static int fts5ConfigParseSpecial(
  197906. Fts5Global *pGlobal,
  197907. Fts5Config *pConfig, /* Configuration object to update */
  197908. const char *zCmd, /* Special command to parse */
  197909. const char *zArg, /* Argument to parse */
  197910. char **pzErr /* OUT: Error message */
  197911. ){
  197912. int rc = SQLITE_OK;
  197913. int nCmd = (int)strlen(zCmd);
  197914. if( sqlite3_strnicmp("prefix", zCmd, nCmd)==0 ){
  197915. const int nByte = sizeof(int) * FTS5_MAX_PREFIX_INDEXES;
  197916. const char *p;
  197917. int bFirst = 1;
  197918. if( pConfig->aPrefix==0 ){
  197919. pConfig->aPrefix = sqlite3Fts5MallocZero(&rc, nByte);
  197920. if( rc ) return rc;
  197921. }
  197922. p = zArg;
  197923. while( 1 ){
  197924. int nPre = 0;
  197925. while( p[0]==' ' ) p++;
  197926. if( bFirst==0 && p[0]==',' ){
  197927. p++;
  197928. while( p[0]==' ' ) p++;
  197929. }else if( p[0]=='\0' ){
  197930. break;
  197931. }
  197932. if( p[0]<'0' || p[0]>'9' ){
  197933. *pzErr = sqlite3_mprintf("malformed prefix=... directive");
  197934. rc = SQLITE_ERROR;
  197935. break;
  197936. }
  197937. if( pConfig->nPrefix==FTS5_MAX_PREFIX_INDEXES ){
  197938. *pzErr = sqlite3_mprintf(
  197939. "too many prefix indexes (max %d)", FTS5_MAX_PREFIX_INDEXES
  197940. );
  197941. rc = SQLITE_ERROR;
  197942. break;
  197943. }
  197944. while( p[0]>='0' && p[0]<='9' && nPre<1000 ){
  197945. nPre = nPre*10 + (p[0] - '0');
  197946. p++;
  197947. }
  197948. if( nPre<=0 || nPre>=1000 ){
  197949. *pzErr = sqlite3_mprintf("prefix length out of range (max 999)");
  197950. rc = SQLITE_ERROR;
  197951. break;
  197952. }
  197953. pConfig->aPrefix[pConfig->nPrefix] = nPre;
  197954. pConfig->nPrefix++;
  197955. bFirst = 0;
  197956. }
  197957. assert( pConfig->nPrefix<=FTS5_MAX_PREFIX_INDEXES );
  197958. return rc;
  197959. }
  197960. if( sqlite3_strnicmp("tokenize", zCmd, nCmd)==0 ){
  197961. const char *p = (const char*)zArg;
  197962. sqlite3_int64 nArg = strlen(zArg) + 1;
  197963. char **azArg = sqlite3Fts5MallocZero(&rc, sizeof(char*) * nArg);
  197964. char *pDel = sqlite3Fts5MallocZero(&rc, nArg * 2);
  197965. char *pSpace = pDel;
  197966. if( azArg && pSpace ){
  197967. if( pConfig->pTok ){
  197968. *pzErr = sqlite3_mprintf("multiple tokenize=... directives");
  197969. rc = SQLITE_ERROR;
  197970. }else{
  197971. for(nArg=0; p && *p; nArg++){
  197972. const char *p2 = fts5ConfigSkipWhitespace(p);
  197973. if( *p2=='\'' ){
  197974. p = fts5ConfigSkipLiteral(p2);
  197975. }else{
  197976. p = fts5ConfigSkipBareword(p2);
  197977. }
  197978. if( p ){
  197979. memcpy(pSpace, p2, p-p2);
  197980. azArg[nArg] = pSpace;
  197981. sqlite3Fts5Dequote(pSpace);
  197982. pSpace += (p - p2) + 1;
  197983. p = fts5ConfigSkipWhitespace(p);
  197984. }
  197985. }
  197986. if( p==0 ){
  197987. *pzErr = sqlite3_mprintf("parse error in tokenize directive");
  197988. rc = SQLITE_ERROR;
  197989. }else{
  197990. rc = sqlite3Fts5GetTokenizer(pGlobal,
  197991. (const char**)azArg, (int)nArg, &pConfig->pTok, &pConfig->pTokApi,
  197992. pzErr
  197993. );
  197994. }
  197995. }
  197996. }
  197997. sqlite3_free(azArg);
  197998. sqlite3_free(pDel);
  197999. return rc;
  198000. }
  198001. if( sqlite3_strnicmp("content", zCmd, nCmd)==0 ){
  198002. if( pConfig->eContent!=FTS5_CONTENT_NORMAL ){
  198003. *pzErr = sqlite3_mprintf("multiple content=... directives");
  198004. rc = SQLITE_ERROR;
  198005. }else{
  198006. if( zArg[0] ){
  198007. pConfig->eContent = FTS5_CONTENT_EXTERNAL;
  198008. pConfig->zContent = sqlite3Fts5Mprintf(&rc, "%Q.%Q", pConfig->zDb,zArg);
  198009. }else{
  198010. pConfig->eContent = FTS5_CONTENT_NONE;
  198011. }
  198012. }
  198013. return rc;
  198014. }
  198015. if( sqlite3_strnicmp("content_rowid", zCmd, nCmd)==0 ){
  198016. if( pConfig->zContentRowid ){
  198017. *pzErr = sqlite3_mprintf("multiple content_rowid=... directives");
  198018. rc = SQLITE_ERROR;
  198019. }else{
  198020. pConfig->zContentRowid = sqlite3Fts5Strndup(&rc, zArg, -1);
  198021. }
  198022. return rc;
  198023. }
  198024. if( sqlite3_strnicmp("columnsize", zCmd, nCmd)==0 ){
  198025. if( (zArg[0]!='0' && zArg[0]!='1') || zArg[1]!='\0' ){
  198026. *pzErr = sqlite3_mprintf("malformed columnsize=... directive");
  198027. rc = SQLITE_ERROR;
  198028. }else{
  198029. pConfig->bColumnsize = (zArg[0]=='1');
  198030. }
  198031. return rc;
  198032. }
  198033. if( sqlite3_strnicmp("detail", zCmd, nCmd)==0 ){
  198034. const Fts5Enum aDetail[] = {
  198035. { "none", FTS5_DETAIL_NONE },
  198036. { "full", FTS5_DETAIL_FULL },
  198037. { "columns", FTS5_DETAIL_COLUMNS },
  198038. { 0, 0 }
  198039. };
  198040. if( (rc = fts5ConfigSetEnum(aDetail, zArg, &pConfig->eDetail)) ){
  198041. *pzErr = sqlite3_mprintf("malformed detail=... directive");
  198042. }
  198043. return rc;
  198044. }
  198045. *pzErr = sqlite3_mprintf("unrecognized option: \"%.*s\"", nCmd, zCmd);
  198046. return SQLITE_ERROR;
  198047. }
  198048. /*
  198049. ** Allocate an instance of the default tokenizer ("simple") at
  198050. ** Fts5Config.pTokenizer. Return SQLITE_OK if successful, or an SQLite error
  198051. ** code if an error occurs.
  198052. */
  198053. static int fts5ConfigDefaultTokenizer(Fts5Global *pGlobal, Fts5Config *pConfig){
  198054. assert( pConfig->pTok==0 && pConfig->pTokApi==0 );
  198055. return sqlite3Fts5GetTokenizer(
  198056. pGlobal, 0, 0, &pConfig->pTok, &pConfig->pTokApi, 0
  198057. );
  198058. }
  198059. /*
  198060. ** Gobble up the first bareword or quoted word from the input buffer zIn.
  198061. ** Return a pointer to the character immediately following the last in
  198062. ** the gobbled word if successful, or a NULL pointer otherwise (failed
  198063. ** to find close-quote character).
  198064. **
  198065. ** Before returning, set pzOut to point to a new buffer containing a
  198066. ** nul-terminated, dequoted copy of the gobbled word. If the word was
  198067. ** quoted, *pbQuoted is also set to 1 before returning.
  198068. **
  198069. ** If *pRc is other than SQLITE_OK when this function is called, it is
  198070. ** a no-op (NULL is returned). Otherwise, if an OOM occurs within this
  198071. ** function, *pRc is set to SQLITE_NOMEM before returning. *pRc is *not*
  198072. ** set if a parse error (failed to find close quote) occurs.
  198073. */
  198074. static const char *fts5ConfigGobbleWord(
  198075. int *pRc, /* IN/OUT: Error code */
  198076. const char *zIn, /* Buffer to gobble string/bareword from */
  198077. char **pzOut, /* OUT: malloc'd buffer containing str/bw */
  198078. int *pbQuoted /* OUT: Set to true if dequoting required */
  198079. ){
  198080. const char *zRet = 0;
  198081. sqlite3_int64 nIn = strlen(zIn);
  198082. char *zOut = sqlite3_malloc64(nIn+1);
  198083. assert( *pRc==SQLITE_OK );
  198084. *pbQuoted = 0;
  198085. *pzOut = 0;
  198086. if( zOut==0 ){
  198087. *pRc = SQLITE_NOMEM;
  198088. }else{
  198089. memcpy(zOut, zIn, (size_t)(nIn+1));
  198090. if( fts5_isopenquote(zOut[0]) ){
  198091. int ii = fts5Dequote(zOut);
  198092. zRet = &zIn[ii];
  198093. *pbQuoted = 1;
  198094. }else{
  198095. zRet = fts5ConfigSkipBareword(zIn);
  198096. if( zRet ){
  198097. zOut[zRet-zIn] = '\0';
  198098. }
  198099. }
  198100. }
  198101. if( zRet==0 ){
  198102. sqlite3_free(zOut);
  198103. }else{
  198104. *pzOut = zOut;
  198105. }
  198106. return zRet;
  198107. }
  198108. static int fts5ConfigParseColumn(
  198109. Fts5Config *p,
  198110. char *zCol,
  198111. char *zArg,
  198112. char **pzErr
  198113. ){
  198114. int rc = SQLITE_OK;
  198115. if( 0==sqlite3_stricmp(zCol, FTS5_RANK_NAME)
  198116. || 0==sqlite3_stricmp(zCol, FTS5_ROWID_NAME)
  198117. ){
  198118. *pzErr = sqlite3_mprintf("reserved fts5 column name: %s", zCol);
  198119. rc = SQLITE_ERROR;
  198120. }else if( zArg ){
  198121. if( 0==sqlite3_stricmp(zArg, "unindexed") ){
  198122. p->abUnindexed[p->nCol] = 1;
  198123. }else{
  198124. *pzErr = sqlite3_mprintf("unrecognized column option: %s", zArg);
  198125. rc = SQLITE_ERROR;
  198126. }
  198127. }
  198128. p->azCol[p->nCol++] = zCol;
  198129. return rc;
  198130. }
  198131. /*
  198132. ** Populate the Fts5Config.zContentExprlist string.
  198133. */
  198134. static int fts5ConfigMakeExprlist(Fts5Config *p){
  198135. int i;
  198136. int rc = SQLITE_OK;
  198137. Fts5Buffer buf = {0, 0, 0};
  198138. sqlite3Fts5BufferAppendPrintf(&rc, &buf, "T.%Q", p->zContentRowid);
  198139. if( p->eContent!=FTS5_CONTENT_NONE ){
  198140. for(i=0; i<p->nCol; i++){
  198141. if( p->eContent==FTS5_CONTENT_EXTERNAL ){
  198142. sqlite3Fts5BufferAppendPrintf(&rc, &buf, ", T.%Q", p->azCol[i]);
  198143. }else{
  198144. sqlite3Fts5BufferAppendPrintf(&rc, &buf, ", T.c%d", i);
  198145. }
  198146. }
  198147. }
  198148. assert( p->zContentExprlist==0 );
  198149. p->zContentExprlist = (char*)buf.p;
  198150. return rc;
  198151. }
  198152. /*
  198153. ** Arguments nArg/azArg contain the string arguments passed to the xCreate
  198154. ** or xConnect method of the virtual table. This function attempts to
  198155. ** allocate an instance of Fts5Config containing the results of parsing
  198156. ** those arguments.
  198157. **
  198158. ** If successful, SQLITE_OK is returned and *ppOut is set to point to the
  198159. ** new Fts5Config object. If an error occurs, an SQLite error code is
  198160. ** returned, *ppOut is set to NULL and an error message may be left in
  198161. ** *pzErr. It is the responsibility of the caller to eventually free any
  198162. ** such error message using sqlite3_free().
  198163. */
  198164. static int sqlite3Fts5ConfigParse(
  198165. Fts5Global *pGlobal,
  198166. sqlite3 *db,
  198167. int nArg, /* Number of arguments */
  198168. const char **azArg, /* Array of nArg CREATE VIRTUAL TABLE args */
  198169. Fts5Config **ppOut, /* OUT: Results of parse */
  198170. char **pzErr /* OUT: Error message */
  198171. ){
  198172. int rc = SQLITE_OK; /* Return code */
  198173. Fts5Config *pRet; /* New object to return */
  198174. int i;
  198175. sqlite3_int64 nByte;
  198176. *ppOut = pRet = (Fts5Config*)sqlite3_malloc(sizeof(Fts5Config));
  198177. if( pRet==0 ) return SQLITE_NOMEM;
  198178. memset(pRet, 0, sizeof(Fts5Config));
  198179. pRet->db = db;
  198180. pRet->iCookie = -1;
  198181. nByte = nArg * (sizeof(char*) + sizeof(u8));
  198182. pRet->azCol = (char**)sqlite3Fts5MallocZero(&rc, nByte);
  198183. pRet->abUnindexed = (u8*)&pRet->azCol[nArg];
  198184. pRet->zDb = sqlite3Fts5Strndup(&rc, azArg[1], -1);
  198185. pRet->zName = sqlite3Fts5Strndup(&rc, azArg[2], -1);
  198186. pRet->bColumnsize = 1;
  198187. pRet->eDetail = FTS5_DETAIL_FULL;
  198188. #ifdef SQLITE_DEBUG
  198189. pRet->bPrefixIndex = 1;
  198190. #endif
  198191. if( rc==SQLITE_OK && sqlite3_stricmp(pRet->zName, FTS5_RANK_NAME)==0 ){
  198192. *pzErr = sqlite3_mprintf("reserved fts5 table name: %s", pRet->zName);
  198193. rc = SQLITE_ERROR;
  198194. }
  198195. for(i=3; rc==SQLITE_OK && i<nArg; i++){
  198196. const char *zOrig = azArg[i];
  198197. const char *z;
  198198. char *zOne = 0;
  198199. char *zTwo = 0;
  198200. int bOption = 0;
  198201. int bMustBeCol = 0;
  198202. z = fts5ConfigGobbleWord(&rc, zOrig, &zOne, &bMustBeCol);
  198203. z = fts5ConfigSkipWhitespace(z);
  198204. if( z && *z=='=' ){
  198205. bOption = 1;
  198206. z++;
  198207. if( bMustBeCol ) z = 0;
  198208. }
  198209. z = fts5ConfigSkipWhitespace(z);
  198210. if( z && z[0] ){
  198211. int bDummy;
  198212. z = fts5ConfigGobbleWord(&rc, z, &zTwo, &bDummy);
  198213. if( z && z[0] ) z = 0;
  198214. }
  198215. if( rc==SQLITE_OK ){
  198216. if( z==0 ){
  198217. *pzErr = sqlite3_mprintf("parse error in \"%s\"", zOrig);
  198218. rc = SQLITE_ERROR;
  198219. }else{
  198220. if( bOption ){
  198221. rc = fts5ConfigParseSpecial(pGlobal, pRet, zOne, zTwo?zTwo:"", pzErr);
  198222. }else{
  198223. rc = fts5ConfigParseColumn(pRet, zOne, zTwo, pzErr);
  198224. zOne = 0;
  198225. }
  198226. }
  198227. }
  198228. sqlite3_free(zOne);
  198229. sqlite3_free(zTwo);
  198230. }
  198231. /* If a tokenizer= option was successfully parsed, the tokenizer has
  198232. ** already been allocated. Otherwise, allocate an instance of the default
  198233. ** tokenizer (unicode61) now. */
  198234. if( rc==SQLITE_OK && pRet->pTok==0 ){
  198235. rc = fts5ConfigDefaultTokenizer(pGlobal, pRet);
  198236. }
  198237. /* If no zContent option was specified, fill in the default values. */
  198238. if( rc==SQLITE_OK && pRet->zContent==0 ){
  198239. const char *zTail = 0;
  198240. assert( pRet->eContent==FTS5_CONTENT_NORMAL
  198241. || pRet->eContent==FTS5_CONTENT_NONE
  198242. );
  198243. if( pRet->eContent==FTS5_CONTENT_NORMAL ){
  198244. zTail = "content";
  198245. }else if( pRet->bColumnsize ){
  198246. zTail = "docsize";
  198247. }
  198248. if( zTail ){
  198249. pRet->zContent = sqlite3Fts5Mprintf(
  198250. &rc, "%Q.'%q_%s'", pRet->zDb, pRet->zName, zTail
  198251. );
  198252. }
  198253. }
  198254. if( rc==SQLITE_OK && pRet->zContentRowid==0 ){
  198255. pRet->zContentRowid = sqlite3Fts5Strndup(&rc, "rowid", -1);
  198256. }
  198257. /* Formulate the zContentExprlist text */
  198258. if( rc==SQLITE_OK ){
  198259. rc = fts5ConfigMakeExprlist(pRet);
  198260. }
  198261. if( rc!=SQLITE_OK ){
  198262. sqlite3Fts5ConfigFree(pRet);
  198263. *ppOut = 0;
  198264. }
  198265. return rc;
  198266. }
  198267. /*
  198268. ** Free the configuration object passed as the only argument.
  198269. */
  198270. static void sqlite3Fts5ConfigFree(Fts5Config *pConfig){
  198271. if( pConfig ){
  198272. int i;
  198273. if( pConfig->pTok ){
  198274. pConfig->pTokApi->xDelete(pConfig->pTok);
  198275. }
  198276. sqlite3_free(pConfig->zDb);
  198277. sqlite3_free(pConfig->zName);
  198278. for(i=0; i<pConfig->nCol; i++){
  198279. sqlite3_free(pConfig->azCol[i]);
  198280. }
  198281. sqlite3_free(pConfig->azCol);
  198282. sqlite3_free(pConfig->aPrefix);
  198283. sqlite3_free(pConfig->zRank);
  198284. sqlite3_free(pConfig->zRankArgs);
  198285. sqlite3_free(pConfig->zContent);
  198286. sqlite3_free(pConfig->zContentRowid);
  198287. sqlite3_free(pConfig->zContentExprlist);
  198288. sqlite3_free(pConfig);
  198289. }
  198290. }
  198291. /*
  198292. ** Call sqlite3_declare_vtab() based on the contents of the configuration
  198293. ** object passed as the only argument. Return SQLITE_OK if successful, or
  198294. ** an SQLite error code if an error occurs.
  198295. */
  198296. static int sqlite3Fts5ConfigDeclareVtab(Fts5Config *pConfig){
  198297. int i;
  198298. int rc = SQLITE_OK;
  198299. char *zSql;
  198300. zSql = sqlite3Fts5Mprintf(&rc, "CREATE TABLE x(");
  198301. for(i=0; zSql && i<pConfig->nCol; i++){
  198302. const char *zSep = (i==0?"":", ");
  198303. zSql = sqlite3Fts5Mprintf(&rc, "%z%s%Q", zSql, zSep, pConfig->azCol[i]);
  198304. }
  198305. zSql = sqlite3Fts5Mprintf(&rc, "%z, %Q HIDDEN, %s HIDDEN)",
  198306. zSql, pConfig->zName, FTS5_RANK_NAME
  198307. );
  198308. assert( zSql || rc==SQLITE_NOMEM );
  198309. if( zSql ){
  198310. rc = sqlite3_declare_vtab(pConfig->db, zSql);
  198311. sqlite3_free(zSql);
  198312. }
  198313. return rc;
  198314. }
  198315. /*
  198316. ** Tokenize the text passed via the second and third arguments.
  198317. **
  198318. ** The callback is invoked once for each token in the input text. The
  198319. ** arguments passed to it are, in order:
  198320. **
  198321. ** void *pCtx // Copy of 4th argument to sqlite3Fts5Tokenize()
  198322. ** const char *pToken // Pointer to buffer containing token
  198323. ** int nToken // Size of token in bytes
  198324. ** int iStart // Byte offset of start of token within input text
  198325. ** int iEnd // Byte offset of end of token within input text
  198326. ** int iPos // Position of token in input (first token is 0)
  198327. **
  198328. ** If the callback returns a non-zero value the tokenization is abandoned
  198329. ** and no further callbacks are issued.
  198330. **
  198331. ** This function returns SQLITE_OK if successful or an SQLite error code
  198332. ** if an error occurs. If the tokenization was abandoned early because
  198333. ** the callback returned SQLITE_DONE, this is not an error and this function
  198334. ** still returns SQLITE_OK. Or, if the tokenization was abandoned early
  198335. ** because the callback returned another non-zero value, it is assumed
  198336. ** to be an SQLite error code and returned to the caller.
  198337. */
  198338. static int sqlite3Fts5Tokenize(
  198339. Fts5Config *pConfig, /* FTS5 Configuration object */
  198340. int flags, /* FTS5_TOKENIZE_* flags */
  198341. const char *pText, int nText, /* Text to tokenize */
  198342. void *pCtx, /* Context passed to xToken() */
  198343. int (*xToken)(void*, int, const char*, int, int, int) /* Callback */
  198344. ){
  198345. if( pText==0 ) return SQLITE_OK;
  198346. return pConfig->pTokApi->xTokenize(
  198347. pConfig->pTok, pCtx, flags, pText, nText, xToken
  198348. );
  198349. }
  198350. /*
  198351. ** Argument pIn points to the first character in what is expected to be
  198352. ** a comma-separated list of SQL literals followed by a ')' character.
  198353. ** If it actually is this, return a pointer to the ')'. Otherwise, return
  198354. ** NULL to indicate a parse error.
  198355. */
  198356. static const char *fts5ConfigSkipArgs(const char *pIn){
  198357. const char *p = pIn;
  198358. while( 1 ){
  198359. p = fts5ConfigSkipWhitespace(p);
  198360. p = fts5ConfigSkipLiteral(p);
  198361. p = fts5ConfigSkipWhitespace(p);
  198362. if( p==0 || *p==')' ) break;
  198363. if( *p!=',' ){
  198364. p = 0;
  198365. break;
  198366. }
  198367. p++;
  198368. }
  198369. return p;
  198370. }
  198371. /*
  198372. ** Parameter zIn contains a rank() function specification. The format of
  198373. ** this is:
  198374. **
  198375. ** + Bareword (function name)
  198376. ** + Open parenthesis - "("
  198377. ** + Zero or more SQL literals in a comma separated list
  198378. ** + Close parenthesis - ")"
  198379. */
  198380. static int sqlite3Fts5ConfigParseRank(
  198381. const char *zIn, /* Input string */
  198382. char **pzRank, /* OUT: Rank function name */
  198383. char **pzRankArgs /* OUT: Rank function arguments */
  198384. ){
  198385. const char *p = zIn;
  198386. const char *pRank;
  198387. char *zRank = 0;
  198388. char *zRankArgs = 0;
  198389. int rc = SQLITE_OK;
  198390. *pzRank = 0;
  198391. *pzRankArgs = 0;
  198392. if( p==0 ){
  198393. rc = SQLITE_ERROR;
  198394. }else{
  198395. p = fts5ConfigSkipWhitespace(p);
  198396. pRank = p;
  198397. p = fts5ConfigSkipBareword(p);
  198398. if( p ){
  198399. zRank = sqlite3Fts5MallocZero(&rc, 1 + p - pRank);
  198400. if( zRank ) memcpy(zRank, pRank, p-pRank);
  198401. }else{
  198402. rc = SQLITE_ERROR;
  198403. }
  198404. if( rc==SQLITE_OK ){
  198405. p = fts5ConfigSkipWhitespace(p);
  198406. if( *p!='(' ) rc = SQLITE_ERROR;
  198407. p++;
  198408. }
  198409. if( rc==SQLITE_OK ){
  198410. const char *pArgs;
  198411. p = fts5ConfigSkipWhitespace(p);
  198412. pArgs = p;
  198413. if( *p!=')' ){
  198414. p = fts5ConfigSkipArgs(p);
  198415. if( p==0 ){
  198416. rc = SQLITE_ERROR;
  198417. }else{
  198418. zRankArgs = sqlite3Fts5MallocZero(&rc, 1 + p - pArgs);
  198419. if( zRankArgs ) memcpy(zRankArgs, pArgs, p-pArgs);
  198420. }
  198421. }
  198422. }
  198423. }
  198424. if( rc!=SQLITE_OK ){
  198425. sqlite3_free(zRank);
  198426. assert( zRankArgs==0 );
  198427. }else{
  198428. *pzRank = zRank;
  198429. *pzRankArgs = zRankArgs;
  198430. }
  198431. return rc;
  198432. }
  198433. static int sqlite3Fts5ConfigSetValue(
  198434. Fts5Config *pConfig,
  198435. const char *zKey,
  198436. sqlite3_value *pVal,
  198437. int *pbBadkey
  198438. ){
  198439. int rc = SQLITE_OK;
  198440. if( 0==sqlite3_stricmp(zKey, "pgsz") ){
  198441. int pgsz = 0;
  198442. if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
  198443. pgsz = sqlite3_value_int(pVal);
  198444. }
  198445. if( pgsz<32 || pgsz>FTS5_MAX_PAGE_SIZE ){
  198446. *pbBadkey = 1;
  198447. }else{
  198448. pConfig->pgsz = pgsz;
  198449. }
  198450. }
  198451. else if( 0==sqlite3_stricmp(zKey, "hashsize") ){
  198452. int nHashSize = -1;
  198453. if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
  198454. nHashSize = sqlite3_value_int(pVal);
  198455. }
  198456. if( nHashSize<=0 ){
  198457. *pbBadkey = 1;
  198458. }else{
  198459. pConfig->nHashSize = nHashSize;
  198460. }
  198461. }
  198462. else if( 0==sqlite3_stricmp(zKey, "automerge") ){
  198463. int nAutomerge = -1;
  198464. if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
  198465. nAutomerge = sqlite3_value_int(pVal);
  198466. }
  198467. if( nAutomerge<0 || nAutomerge>64 ){
  198468. *pbBadkey = 1;
  198469. }else{
  198470. if( nAutomerge==1 ) nAutomerge = FTS5_DEFAULT_AUTOMERGE;
  198471. pConfig->nAutomerge = nAutomerge;
  198472. }
  198473. }
  198474. else if( 0==sqlite3_stricmp(zKey, "usermerge") ){
  198475. int nUsermerge = -1;
  198476. if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
  198477. nUsermerge = sqlite3_value_int(pVal);
  198478. }
  198479. if( nUsermerge<2 || nUsermerge>16 ){
  198480. *pbBadkey = 1;
  198481. }else{
  198482. pConfig->nUsermerge = nUsermerge;
  198483. }
  198484. }
  198485. else if( 0==sqlite3_stricmp(zKey, "crisismerge") ){
  198486. int nCrisisMerge = -1;
  198487. if( SQLITE_INTEGER==sqlite3_value_numeric_type(pVal) ){
  198488. nCrisisMerge = sqlite3_value_int(pVal);
  198489. }
  198490. if( nCrisisMerge<0 ){
  198491. *pbBadkey = 1;
  198492. }else{
  198493. if( nCrisisMerge<=1 ) nCrisisMerge = FTS5_DEFAULT_CRISISMERGE;
  198494. if( nCrisisMerge>=FTS5_MAX_SEGMENT ) nCrisisMerge = FTS5_MAX_SEGMENT-1;
  198495. pConfig->nCrisisMerge = nCrisisMerge;
  198496. }
  198497. }
  198498. else if( 0==sqlite3_stricmp(zKey, "rank") ){
  198499. const char *zIn = (const char*)sqlite3_value_text(pVal);
  198500. char *zRank;
  198501. char *zRankArgs;
  198502. rc = sqlite3Fts5ConfigParseRank(zIn, &zRank, &zRankArgs);
  198503. if( rc==SQLITE_OK ){
  198504. sqlite3_free(pConfig->zRank);
  198505. sqlite3_free(pConfig->zRankArgs);
  198506. pConfig->zRank = zRank;
  198507. pConfig->zRankArgs = zRankArgs;
  198508. }else if( rc==SQLITE_ERROR ){
  198509. rc = SQLITE_OK;
  198510. *pbBadkey = 1;
  198511. }
  198512. }else{
  198513. *pbBadkey = 1;
  198514. }
  198515. return rc;
  198516. }
  198517. /*
  198518. ** Load the contents of the %_config table into memory.
  198519. */
  198520. static int sqlite3Fts5ConfigLoad(Fts5Config *pConfig, int iCookie){
  198521. const char *zSelect = "SELECT k, v FROM %Q.'%q_config'";
  198522. char *zSql;
  198523. sqlite3_stmt *p = 0;
  198524. int rc = SQLITE_OK;
  198525. int iVersion = 0;
  198526. /* Set default values */
  198527. pConfig->pgsz = FTS5_DEFAULT_PAGE_SIZE;
  198528. pConfig->nAutomerge = FTS5_DEFAULT_AUTOMERGE;
  198529. pConfig->nUsermerge = FTS5_DEFAULT_USERMERGE;
  198530. pConfig->nCrisisMerge = FTS5_DEFAULT_CRISISMERGE;
  198531. pConfig->nHashSize = FTS5_DEFAULT_HASHSIZE;
  198532. zSql = sqlite3Fts5Mprintf(&rc, zSelect, pConfig->zDb, pConfig->zName);
  198533. if( zSql ){
  198534. rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &p, 0);
  198535. sqlite3_free(zSql);
  198536. }
  198537. assert( rc==SQLITE_OK || p==0 );
  198538. if( rc==SQLITE_OK ){
  198539. while( SQLITE_ROW==sqlite3_step(p) ){
  198540. const char *zK = (const char*)sqlite3_column_text(p, 0);
  198541. sqlite3_value *pVal = sqlite3_column_value(p, 1);
  198542. if( 0==sqlite3_stricmp(zK, "version") ){
  198543. iVersion = sqlite3_value_int(pVal);
  198544. }else{
  198545. int bDummy = 0;
  198546. sqlite3Fts5ConfigSetValue(pConfig, zK, pVal, &bDummy);
  198547. }
  198548. }
  198549. rc = sqlite3_finalize(p);
  198550. }
  198551. if( rc==SQLITE_OK && iVersion!=FTS5_CURRENT_VERSION ){
  198552. rc = SQLITE_ERROR;
  198553. if( pConfig->pzErrmsg ){
  198554. assert( 0==*pConfig->pzErrmsg );
  198555. *pConfig->pzErrmsg = sqlite3_mprintf(
  198556. "invalid fts5 file format (found %d, expected %d) - run 'rebuild'",
  198557. iVersion, FTS5_CURRENT_VERSION
  198558. );
  198559. }
  198560. }
  198561. if( rc==SQLITE_OK ){
  198562. pConfig->iCookie = iCookie;
  198563. }
  198564. return rc;
  198565. }
  198566. /*
  198567. ** 2014 May 31
  198568. **
  198569. ** The author disclaims copyright to this source code. In place of
  198570. ** a legal notice, here is a blessing:
  198571. **
  198572. ** May you do good and not evil.
  198573. ** May you find forgiveness for yourself and forgive others.
  198574. ** May you share freely, never taking more than you give.
  198575. **
  198576. ******************************************************************************
  198577. **
  198578. */
  198579. /* #include "fts5Int.h" */
  198580. /* #include "fts5parse.h" */
  198581. /*
  198582. ** All token types in the generated fts5parse.h file are greater than 0.
  198583. */
  198584. #define FTS5_EOF 0
  198585. #define FTS5_LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32))
  198586. typedef struct Fts5ExprTerm Fts5ExprTerm;
  198587. /*
  198588. ** Functions generated by lemon from fts5parse.y.
  198589. */
  198590. static void *sqlite3Fts5ParserAlloc(void *(*mallocProc)(u64));
  198591. static void sqlite3Fts5ParserFree(void*, void (*freeProc)(void*));
  198592. static void sqlite3Fts5Parser(void*, int, Fts5Token, Fts5Parse*);
  198593. #ifndef NDEBUG
  198594. /* #include <stdio.h> */
  198595. static void sqlite3Fts5ParserTrace(FILE*, char*);
  198596. #endif
  198597. static int sqlite3Fts5ParserFallback(int);
  198598. struct Fts5Expr {
  198599. Fts5Index *pIndex;
  198600. Fts5Config *pConfig;
  198601. Fts5ExprNode *pRoot;
  198602. int bDesc; /* Iterate in descending rowid order */
  198603. int nPhrase; /* Number of phrases in expression */
  198604. Fts5ExprPhrase **apExprPhrase; /* Pointers to phrase objects */
  198605. };
  198606. /*
  198607. ** eType:
  198608. ** Expression node type. Always one of:
  198609. **
  198610. ** FTS5_AND (nChild, apChild valid)
  198611. ** FTS5_OR (nChild, apChild valid)
  198612. ** FTS5_NOT (nChild, apChild valid)
  198613. ** FTS5_STRING (pNear valid)
  198614. ** FTS5_TERM (pNear valid)
  198615. */
  198616. struct Fts5ExprNode {
  198617. int eType; /* Node type */
  198618. int bEof; /* True at EOF */
  198619. int bNomatch; /* True if entry is not a match */
  198620. /* Next method for this node. */
  198621. int (*xNext)(Fts5Expr*, Fts5ExprNode*, int, i64);
  198622. i64 iRowid; /* Current rowid */
  198623. Fts5ExprNearset *pNear; /* For FTS5_STRING - cluster of phrases */
  198624. /* Child nodes. For a NOT node, this array always contains 2 entries. For
  198625. ** AND or OR nodes, it contains 2 or more entries. */
  198626. int nChild; /* Number of child nodes */
  198627. Fts5ExprNode *apChild[1]; /* Array of child nodes */
  198628. };
  198629. #define Fts5NodeIsString(p) ((p)->eType==FTS5_TERM || (p)->eType==FTS5_STRING)
  198630. /*
  198631. ** Invoke the xNext method of an Fts5ExprNode object. This macro should be
  198632. ** used as if it has the same signature as the xNext() methods themselves.
  198633. */
  198634. #define fts5ExprNodeNext(a,b,c,d) (b)->xNext((a), (b), (c), (d))
  198635. /*
  198636. ** An instance of the following structure represents a single search term
  198637. ** or term prefix.
  198638. */
  198639. struct Fts5ExprTerm {
  198640. u8 bPrefix; /* True for a prefix term */
  198641. u8 bFirst; /* True if token must be first in column */
  198642. char *zTerm; /* nul-terminated term */
  198643. Fts5IndexIter *pIter; /* Iterator for this term */
  198644. Fts5ExprTerm *pSynonym; /* Pointer to first in list of synonyms */
  198645. };
  198646. /*
  198647. ** A phrase. One or more terms that must appear in a contiguous sequence
  198648. ** within a document for it to match.
  198649. */
  198650. struct Fts5ExprPhrase {
  198651. Fts5ExprNode *pNode; /* FTS5_STRING node this phrase is part of */
  198652. Fts5Buffer poslist; /* Current position list */
  198653. int nTerm; /* Number of entries in aTerm[] */
  198654. Fts5ExprTerm aTerm[1]; /* Terms that make up this phrase */
  198655. };
  198656. /*
  198657. ** One or more phrases that must appear within a certain token distance of
  198658. ** each other within each matching document.
  198659. */
  198660. struct Fts5ExprNearset {
  198661. int nNear; /* NEAR parameter */
  198662. Fts5Colset *pColset; /* Columns to search (NULL -> all columns) */
  198663. int nPhrase; /* Number of entries in aPhrase[] array */
  198664. Fts5ExprPhrase *apPhrase[1]; /* Array of phrase pointers */
  198665. };
  198666. /*
  198667. ** Parse context.
  198668. */
  198669. struct Fts5Parse {
  198670. Fts5Config *pConfig;
  198671. char *zErr;
  198672. int rc;
  198673. int nPhrase; /* Size of apPhrase array */
  198674. Fts5ExprPhrase **apPhrase; /* Array of all phrases */
  198675. Fts5ExprNode *pExpr; /* Result of a successful parse */
  198676. };
  198677. static void sqlite3Fts5ParseError(Fts5Parse *pParse, const char *zFmt, ...){
  198678. va_list ap;
  198679. va_start(ap, zFmt);
  198680. if( pParse->rc==SQLITE_OK ){
  198681. pParse->zErr = sqlite3_vmprintf(zFmt, ap);
  198682. pParse->rc = SQLITE_ERROR;
  198683. }
  198684. va_end(ap);
  198685. }
  198686. static int fts5ExprIsspace(char t){
  198687. return t==' ' || t=='\t' || t=='\n' || t=='\r';
  198688. }
  198689. /*
  198690. ** Read the first token from the nul-terminated string at *pz.
  198691. */
  198692. static int fts5ExprGetToken(
  198693. Fts5Parse *pParse,
  198694. const char **pz, /* IN/OUT: Pointer into buffer */
  198695. Fts5Token *pToken
  198696. ){
  198697. const char *z = *pz;
  198698. int tok;
  198699. /* Skip past any whitespace */
  198700. while( fts5ExprIsspace(*z) ) z++;
  198701. pToken->p = z;
  198702. pToken->n = 1;
  198703. switch( *z ){
  198704. case '(': tok = FTS5_LP; break;
  198705. case ')': tok = FTS5_RP; break;
  198706. case '{': tok = FTS5_LCP; break;
  198707. case '}': tok = FTS5_RCP; break;
  198708. case ':': tok = FTS5_COLON; break;
  198709. case ',': tok = FTS5_COMMA; break;
  198710. case '+': tok = FTS5_PLUS; break;
  198711. case '*': tok = FTS5_STAR; break;
  198712. case '-': tok = FTS5_MINUS; break;
  198713. case '^': tok = FTS5_CARET; break;
  198714. case '\0': tok = FTS5_EOF; break;
  198715. case '"': {
  198716. const char *z2;
  198717. tok = FTS5_STRING;
  198718. for(z2=&z[1]; 1; z2++){
  198719. if( z2[0]=='"' ){
  198720. z2++;
  198721. if( z2[0]!='"' ) break;
  198722. }
  198723. if( z2[0]=='\0' ){
  198724. sqlite3Fts5ParseError(pParse, "unterminated string");
  198725. return FTS5_EOF;
  198726. }
  198727. }
  198728. pToken->n = (z2 - z);
  198729. break;
  198730. }
  198731. default: {
  198732. const char *z2;
  198733. if( sqlite3Fts5IsBareword(z[0])==0 ){
  198734. sqlite3Fts5ParseError(pParse, "fts5: syntax error near \"%.1s\"", z);
  198735. return FTS5_EOF;
  198736. }
  198737. tok = FTS5_STRING;
  198738. for(z2=&z[1]; sqlite3Fts5IsBareword(*z2); z2++);
  198739. pToken->n = (z2 - z);
  198740. if( pToken->n==2 && memcmp(pToken->p, "OR", 2)==0 ) tok = FTS5_OR;
  198741. if( pToken->n==3 && memcmp(pToken->p, "NOT", 3)==0 ) tok = FTS5_NOT;
  198742. if( pToken->n==3 && memcmp(pToken->p, "AND", 3)==0 ) tok = FTS5_AND;
  198743. break;
  198744. }
  198745. }
  198746. *pz = &pToken->p[pToken->n];
  198747. return tok;
  198748. }
  198749. static void *fts5ParseAlloc(u64 t){ return sqlite3_malloc64((sqlite3_int64)t);}
  198750. static void fts5ParseFree(void *p){ sqlite3_free(p); }
  198751. static int sqlite3Fts5ExprNew(
  198752. Fts5Config *pConfig, /* FTS5 Configuration */
  198753. int iCol,
  198754. const char *zExpr, /* Expression text */
  198755. Fts5Expr **ppNew,
  198756. char **pzErr
  198757. ){
  198758. Fts5Parse sParse;
  198759. Fts5Token token;
  198760. const char *z = zExpr;
  198761. int t; /* Next token type */
  198762. void *pEngine;
  198763. Fts5Expr *pNew;
  198764. *ppNew = 0;
  198765. *pzErr = 0;
  198766. memset(&sParse, 0, sizeof(sParse));
  198767. pEngine = sqlite3Fts5ParserAlloc(fts5ParseAlloc);
  198768. if( pEngine==0 ){ return SQLITE_NOMEM; }
  198769. sParse.pConfig = pConfig;
  198770. do {
  198771. t = fts5ExprGetToken(&sParse, &z, &token);
  198772. sqlite3Fts5Parser(pEngine, t, token, &sParse);
  198773. }while( sParse.rc==SQLITE_OK && t!=FTS5_EOF );
  198774. sqlite3Fts5ParserFree(pEngine, fts5ParseFree);
  198775. /* If the LHS of the MATCH expression was a user column, apply the
  198776. ** implicit column-filter. */
  198777. if( iCol<pConfig->nCol && sParse.pExpr && sParse.rc==SQLITE_OK ){
  198778. int n = sizeof(Fts5Colset);
  198779. Fts5Colset *pColset = (Fts5Colset*)sqlite3Fts5MallocZero(&sParse.rc, n);
  198780. if( pColset ){
  198781. pColset->nCol = 1;
  198782. pColset->aiCol[0] = iCol;
  198783. sqlite3Fts5ParseSetColset(&sParse, sParse.pExpr, pColset);
  198784. }
  198785. }
  198786. assert( sParse.rc!=SQLITE_OK || sParse.zErr==0 );
  198787. if( sParse.rc==SQLITE_OK ){
  198788. *ppNew = pNew = sqlite3_malloc(sizeof(Fts5Expr));
  198789. if( pNew==0 ){
  198790. sParse.rc = SQLITE_NOMEM;
  198791. sqlite3Fts5ParseNodeFree(sParse.pExpr);
  198792. }else{
  198793. if( !sParse.pExpr ){
  198794. const int nByte = sizeof(Fts5ExprNode);
  198795. pNew->pRoot = (Fts5ExprNode*)sqlite3Fts5MallocZero(&sParse.rc, nByte);
  198796. if( pNew->pRoot ){
  198797. pNew->pRoot->bEof = 1;
  198798. }
  198799. }else{
  198800. pNew->pRoot = sParse.pExpr;
  198801. }
  198802. pNew->pIndex = 0;
  198803. pNew->pConfig = pConfig;
  198804. pNew->apExprPhrase = sParse.apPhrase;
  198805. pNew->nPhrase = sParse.nPhrase;
  198806. sParse.apPhrase = 0;
  198807. }
  198808. }else{
  198809. sqlite3Fts5ParseNodeFree(sParse.pExpr);
  198810. }
  198811. sqlite3_free(sParse.apPhrase);
  198812. *pzErr = sParse.zErr;
  198813. return sParse.rc;
  198814. }
  198815. /*
  198816. ** Free the expression node object passed as the only argument.
  198817. */
  198818. static void sqlite3Fts5ParseNodeFree(Fts5ExprNode *p){
  198819. if( p ){
  198820. int i;
  198821. for(i=0; i<p->nChild; i++){
  198822. sqlite3Fts5ParseNodeFree(p->apChild[i]);
  198823. }
  198824. sqlite3Fts5ParseNearsetFree(p->pNear);
  198825. sqlite3_free(p);
  198826. }
  198827. }
  198828. /*
  198829. ** Free the expression object passed as the only argument.
  198830. */
  198831. static void sqlite3Fts5ExprFree(Fts5Expr *p){
  198832. if( p ){
  198833. sqlite3Fts5ParseNodeFree(p->pRoot);
  198834. sqlite3_free(p->apExprPhrase);
  198835. sqlite3_free(p);
  198836. }
  198837. }
  198838. static int sqlite3Fts5ExprAnd(Fts5Expr **pp1, Fts5Expr *p2){
  198839. Fts5Parse sParse;
  198840. memset(&sParse, 0, sizeof(sParse));
  198841. if( *pp1 ){
  198842. Fts5Expr *p1 = *pp1;
  198843. int nPhrase = p1->nPhrase + p2->nPhrase;
  198844. p1->pRoot = sqlite3Fts5ParseNode(&sParse, FTS5_AND, p1->pRoot, p2->pRoot,0);
  198845. p2->pRoot = 0;
  198846. if( sParse.rc==SQLITE_OK ){
  198847. Fts5ExprPhrase **ap = (Fts5ExprPhrase**)sqlite3_realloc(
  198848. p1->apExprPhrase, nPhrase * sizeof(Fts5ExprPhrase*)
  198849. );
  198850. if( ap==0 ){
  198851. sParse.rc = SQLITE_NOMEM;
  198852. }else{
  198853. int i;
  198854. memmove(&ap[p2->nPhrase], ap, p1->nPhrase*sizeof(Fts5ExprPhrase*));
  198855. for(i=0; i<p2->nPhrase; i++){
  198856. ap[i] = p2->apExprPhrase[i];
  198857. }
  198858. p1->nPhrase = nPhrase;
  198859. p1->apExprPhrase = ap;
  198860. }
  198861. }
  198862. sqlite3_free(p2->apExprPhrase);
  198863. sqlite3_free(p2);
  198864. }else{
  198865. *pp1 = p2;
  198866. }
  198867. return sParse.rc;
  198868. }
  198869. /*
  198870. ** Argument pTerm must be a synonym iterator. Return the current rowid
  198871. ** that it points to.
  198872. */
  198873. static i64 fts5ExprSynonymRowid(Fts5ExprTerm *pTerm, int bDesc, int *pbEof){
  198874. i64 iRet = 0;
  198875. int bRetValid = 0;
  198876. Fts5ExprTerm *p;
  198877. assert( pTerm->pSynonym );
  198878. assert( bDesc==0 || bDesc==1 );
  198879. for(p=pTerm; p; p=p->pSynonym){
  198880. if( 0==sqlite3Fts5IterEof(p->pIter) ){
  198881. i64 iRowid = p->pIter->iRowid;
  198882. if( bRetValid==0 || (bDesc!=(iRowid<iRet)) ){
  198883. iRet = iRowid;
  198884. bRetValid = 1;
  198885. }
  198886. }
  198887. }
  198888. if( pbEof && bRetValid==0 ) *pbEof = 1;
  198889. return iRet;
  198890. }
  198891. /*
  198892. ** Argument pTerm must be a synonym iterator.
  198893. */
  198894. static int fts5ExprSynonymList(
  198895. Fts5ExprTerm *pTerm,
  198896. i64 iRowid,
  198897. Fts5Buffer *pBuf, /* Use this buffer for space if required */
  198898. u8 **pa, int *pn
  198899. ){
  198900. Fts5PoslistReader aStatic[4];
  198901. Fts5PoslistReader *aIter = aStatic;
  198902. int nIter = 0;
  198903. int nAlloc = 4;
  198904. int rc = SQLITE_OK;
  198905. Fts5ExprTerm *p;
  198906. assert( pTerm->pSynonym );
  198907. for(p=pTerm; p; p=p->pSynonym){
  198908. Fts5IndexIter *pIter = p->pIter;
  198909. if( sqlite3Fts5IterEof(pIter)==0 && pIter->iRowid==iRowid ){
  198910. if( pIter->nData==0 ) continue;
  198911. if( nIter==nAlloc ){
  198912. sqlite3_int64 nByte = sizeof(Fts5PoslistReader) * nAlloc * 2;
  198913. Fts5PoslistReader *aNew = (Fts5PoslistReader*)sqlite3_malloc64(nByte);
  198914. if( aNew==0 ){
  198915. rc = SQLITE_NOMEM;
  198916. goto synonym_poslist_out;
  198917. }
  198918. memcpy(aNew, aIter, sizeof(Fts5PoslistReader) * nIter);
  198919. nAlloc = nAlloc*2;
  198920. if( aIter!=aStatic ) sqlite3_free(aIter);
  198921. aIter = aNew;
  198922. }
  198923. sqlite3Fts5PoslistReaderInit(pIter->pData, pIter->nData, &aIter[nIter]);
  198924. assert( aIter[nIter].bEof==0 );
  198925. nIter++;
  198926. }
  198927. }
  198928. if( nIter==1 ){
  198929. *pa = (u8*)aIter[0].a;
  198930. *pn = aIter[0].n;
  198931. }else{
  198932. Fts5PoslistWriter writer = {0};
  198933. i64 iPrev = -1;
  198934. fts5BufferZero(pBuf);
  198935. while( 1 ){
  198936. int i;
  198937. i64 iMin = FTS5_LARGEST_INT64;
  198938. for(i=0; i<nIter; i++){
  198939. if( aIter[i].bEof==0 ){
  198940. if( aIter[i].iPos==iPrev ){
  198941. if( sqlite3Fts5PoslistReaderNext(&aIter[i]) ) continue;
  198942. }
  198943. if( aIter[i].iPos<iMin ){
  198944. iMin = aIter[i].iPos;
  198945. }
  198946. }
  198947. }
  198948. if( iMin==FTS5_LARGEST_INT64 || rc!=SQLITE_OK ) break;
  198949. rc = sqlite3Fts5PoslistWriterAppend(pBuf, &writer, iMin);
  198950. iPrev = iMin;
  198951. }
  198952. if( rc==SQLITE_OK ){
  198953. *pa = pBuf->p;
  198954. *pn = pBuf->n;
  198955. }
  198956. }
  198957. synonym_poslist_out:
  198958. if( aIter!=aStatic ) sqlite3_free(aIter);
  198959. return rc;
  198960. }
  198961. /*
  198962. ** All individual term iterators in pPhrase are guaranteed to be valid and
  198963. ** pointing to the same rowid when this function is called. This function
  198964. ** checks if the current rowid really is a match, and if so populates
  198965. ** the pPhrase->poslist buffer accordingly. Output parameter *pbMatch
  198966. ** is set to true if this is really a match, or false otherwise.
  198967. **
  198968. ** SQLITE_OK is returned if an error occurs, or an SQLite error code
  198969. ** otherwise. It is not considered an error code if the current rowid is
  198970. ** not a match.
  198971. */
  198972. static int fts5ExprPhraseIsMatch(
  198973. Fts5ExprNode *pNode, /* Node pPhrase belongs to */
  198974. Fts5ExprPhrase *pPhrase, /* Phrase object to initialize */
  198975. int *pbMatch /* OUT: Set to true if really a match */
  198976. ){
  198977. Fts5PoslistWriter writer = {0};
  198978. Fts5PoslistReader aStatic[4];
  198979. Fts5PoslistReader *aIter = aStatic;
  198980. int i;
  198981. int rc = SQLITE_OK;
  198982. int bFirst = pPhrase->aTerm[0].bFirst;
  198983. fts5BufferZero(&pPhrase->poslist);
  198984. /* If the aStatic[] array is not large enough, allocate a large array
  198985. ** using sqlite3_malloc(). This approach could be improved upon. */
  198986. if( pPhrase->nTerm>ArraySize(aStatic) ){
  198987. sqlite3_int64 nByte = sizeof(Fts5PoslistReader) * pPhrase->nTerm;
  198988. aIter = (Fts5PoslistReader*)sqlite3_malloc64(nByte);
  198989. if( !aIter ) return SQLITE_NOMEM;
  198990. }
  198991. memset(aIter, 0, sizeof(Fts5PoslistReader) * pPhrase->nTerm);
  198992. /* Initialize a term iterator for each term in the phrase */
  198993. for(i=0; i<pPhrase->nTerm; i++){
  198994. Fts5ExprTerm *pTerm = &pPhrase->aTerm[i];
  198995. int n = 0;
  198996. int bFlag = 0;
  198997. u8 *a = 0;
  198998. if( pTerm->pSynonym ){
  198999. Fts5Buffer buf = {0, 0, 0};
  199000. rc = fts5ExprSynonymList(pTerm, pNode->iRowid, &buf, &a, &n);
  199001. if( rc ){
  199002. sqlite3_free(a);
  199003. goto ismatch_out;
  199004. }
  199005. if( a==buf.p ) bFlag = 1;
  199006. }else{
  199007. a = (u8*)pTerm->pIter->pData;
  199008. n = pTerm->pIter->nData;
  199009. }
  199010. sqlite3Fts5PoslistReaderInit(a, n, &aIter[i]);
  199011. aIter[i].bFlag = (u8)bFlag;
  199012. if( aIter[i].bEof ) goto ismatch_out;
  199013. }
  199014. while( 1 ){
  199015. int bMatch;
  199016. i64 iPos = aIter[0].iPos;
  199017. do {
  199018. bMatch = 1;
  199019. for(i=0; i<pPhrase->nTerm; i++){
  199020. Fts5PoslistReader *pPos = &aIter[i];
  199021. i64 iAdj = iPos + i;
  199022. if( pPos->iPos!=iAdj ){
  199023. bMatch = 0;
  199024. while( pPos->iPos<iAdj ){
  199025. if( sqlite3Fts5PoslistReaderNext(pPos) ) goto ismatch_out;
  199026. }
  199027. if( pPos->iPos>iAdj ) iPos = pPos->iPos-i;
  199028. }
  199029. }
  199030. }while( bMatch==0 );
  199031. /* Append position iPos to the output */
  199032. if( bFirst==0 || FTS5_POS2OFFSET(iPos)==0 ){
  199033. rc = sqlite3Fts5PoslistWriterAppend(&pPhrase->poslist, &writer, iPos);
  199034. if( rc!=SQLITE_OK ) goto ismatch_out;
  199035. }
  199036. for(i=0; i<pPhrase->nTerm; i++){
  199037. if( sqlite3Fts5PoslistReaderNext(&aIter[i]) ) goto ismatch_out;
  199038. }
  199039. }
  199040. ismatch_out:
  199041. *pbMatch = (pPhrase->poslist.n>0);
  199042. for(i=0; i<pPhrase->nTerm; i++){
  199043. if( aIter[i].bFlag ) sqlite3_free((u8*)aIter[i].a);
  199044. }
  199045. if( aIter!=aStatic ) sqlite3_free(aIter);
  199046. return rc;
  199047. }
  199048. typedef struct Fts5LookaheadReader Fts5LookaheadReader;
  199049. struct Fts5LookaheadReader {
  199050. const u8 *a; /* Buffer containing position list */
  199051. int n; /* Size of buffer a[] in bytes */
  199052. int i; /* Current offset in position list */
  199053. i64 iPos; /* Current position */
  199054. i64 iLookahead; /* Next position */
  199055. };
  199056. #define FTS5_LOOKAHEAD_EOF (((i64)1) << 62)
  199057. static int fts5LookaheadReaderNext(Fts5LookaheadReader *p){
  199058. p->iPos = p->iLookahead;
  199059. if( sqlite3Fts5PoslistNext64(p->a, p->n, &p->i, &p->iLookahead) ){
  199060. p->iLookahead = FTS5_LOOKAHEAD_EOF;
  199061. }
  199062. return (p->iPos==FTS5_LOOKAHEAD_EOF);
  199063. }
  199064. static int fts5LookaheadReaderInit(
  199065. const u8 *a, int n, /* Buffer to read position list from */
  199066. Fts5LookaheadReader *p /* Iterator object to initialize */
  199067. ){
  199068. memset(p, 0, sizeof(Fts5LookaheadReader));
  199069. p->a = a;
  199070. p->n = n;
  199071. fts5LookaheadReaderNext(p);
  199072. return fts5LookaheadReaderNext(p);
  199073. }
  199074. typedef struct Fts5NearTrimmer Fts5NearTrimmer;
  199075. struct Fts5NearTrimmer {
  199076. Fts5LookaheadReader reader; /* Input iterator */
  199077. Fts5PoslistWriter writer; /* Writer context */
  199078. Fts5Buffer *pOut; /* Output poslist */
  199079. };
  199080. /*
  199081. ** The near-set object passed as the first argument contains more than
  199082. ** one phrase. All phrases currently point to the same row. The
  199083. ** Fts5ExprPhrase.poslist buffers are populated accordingly. This function
  199084. ** tests if the current row contains instances of each phrase sufficiently
  199085. ** close together to meet the NEAR constraint. Non-zero is returned if it
  199086. ** does, or zero otherwise.
  199087. **
  199088. ** If in/out parameter (*pRc) is set to other than SQLITE_OK when this
  199089. ** function is called, it is a no-op. Or, if an error (e.g. SQLITE_NOMEM)
  199090. ** occurs within this function (*pRc) is set accordingly before returning.
  199091. ** The return value is undefined in both these cases.
  199092. **
  199093. ** If no error occurs and non-zero (a match) is returned, the position-list
  199094. ** of each phrase object is edited to contain only those entries that
  199095. ** meet the constraint before returning.
  199096. */
  199097. static int fts5ExprNearIsMatch(int *pRc, Fts5ExprNearset *pNear){
  199098. Fts5NearTrimmer aStatic[4];
  199099. Fts5NearTrimmer *a = aStatic;
  199100. Fts5ExprPhrase **apPhrase = pNear->apPhrase;
  199101. int i;
  199102. int rc = *pRc;
  199103. int bMatch;
  199104. assert( pNear->nPhrase>1 );
  199105. /* If the aStatic[] array is not large enough, allocate a large array
  199106. ** using sqlite3_malloc(). This approach could be improved upon. */
  199107. if( pNear->nPhrase>ArraySize(aStatic) ){
  199108. sqlite3_int64 nByte = sizeof(Fts5NearTrimmer) * pNear->nPhrase;
  199109. a = (Fts5NearTrimmer*)sqlite3Fts5MallocZero(&rc, nByte);
  199110. }else{
  199111. memset(aStatic, 0, sizeof(aStatic));
  199112. }
  199113. if( rc!=SQLITE_OK ){
  199114. *pRc = rc;
  199115. return 0;
  199116. }
  199117. /* Initialize a lookahead iterator for each phrase. After passing the
  199118. ** buffer and buffer size to the lookaside-reader init function, zero
  199119. ** the phrase poslist buffer. The new poslist for the phrase (containing
  199120. ** the same entries as the original with some entries removed on account
  199121. ** of the NEAR constraint) is written over the original even as it is
  199122. ** being read. This is safe as the entries for the new poslist are a
  199123. ** subset of the old, so it is not possible for data yet to be read to
  199124. ** be overwritten. */
  199125. for(i=0; i<pNear->nPhrase; i++){
  199126. Fts5Buffer *pPoslist = &apPhrase[i]->poslist;
  199127. fts5LookaheadReaderInit(pPoslist->p, pPoslist->n, &a[i].reader);
  199128. pPoslist->n = 0;
  199129. a[i].pOut = pPoslist;
  199130. }
  199131. while( 1 ){
  199132. int iAdv;
  199133. i64 iMin;
  199134. i64 iMax;
  199135. /* This block advances the phrase iterators until they point to a set of
  199136. ** entries that together comprise a match. */
  199137. iMax = a[0].reader.iPos;
  199138. do {
  199139. bMatch = 1;
  199140. for(i=0; i<pNear->nPhrase; i++){
  199141. Fts5LookaheadReader *pPos = &a[i].reader;
  199142. iMin = iMax - pNear->apPhrase[i]->nTerm - pNear->nNear;
  199143. if( pPos->iPos<iMin || pPos->iPos>iMax ){
  199144. bMatch = 0;
  199145. while( pPos->iPos<iMin ){
  199146. if( fts5LookaheadReaderNext(pPos) ) goto ismatch_out;
  199147. }
  199148. if( pPos->iPos>iMax ) iMax = pPos->iPos;
  199149. }
  199150. }
  199151. }while( bMatch==0 );
  199152. /* Add an entry to each output position list */
  199153. for(i=0; i<pNear->nPhrase; i++){
  199154. i64 iPos = a[i].reader.iPos;
  199155. Fts5PoslistWriter *pWriter = &a[i].writer;
  199156. if( a[i].pOut->n==0 || iPos!=pWriter->iPrev ){
  199157. sqlite3Fts5PoslistWriterAppend(a[i].pOut, pWriter, iPos);
  199158. }
  199159. }
  199160. iAdv = 0;
  199161. iMin = a[0].reader.iLookahead;
  199162. for(i=0; i<pNear->nPhrase; i++){
  199163. if( a[i].reader.iLookahead < iMin ){
  199164. iMin = a[i].reader.iLookahead;
  199165. iAdv = i;
  199166. }
  199167. }
  199168. if( fts5LookaheadReaderNext(&a[iAdv].reader) ) goto ismatch_out;
  199169. }
  199170. ismatch_out: {
  199171. int bRet = a[0].pOut->n>0;
  199172. *pRc = rc;
  199173. if( a!=aStatic ) sqlite3_free(a);
  199174. return bRet;
  199175. }
  199176. }
  199177. /*
  199178. ** Advance iterator pIter until it points to a value equal to or laster
  199179. ** than the initial value of *piLast. If this means the iterator points
  199180. ** to a value laster than *piLast, update *piLast to the new lastest value.
  199181. **
  199182. ** If the iterator reaches EOF, set *pbEof to true before returning. If
  199183. ** an error occurs, set *pRc to an error code. If either *pbEof or *pRc
  199184. ** are set, return a non-zero value. Otherwise, return zero.
  199185. */
  199186. static int fts5ExprAdvanceto(
  199187. Fts5IndexIter *pIter, /* Iterator to advance */
  199188. int bDesc, /* True if iterator is "rowid DESC" */
  199189. i64 *piLast, /* IN/OUT: Lastest rowid seen so far */
  199190. int *pRc, /* OUT: Error code */
  199191. int *pbEof /* OUT: Set to true if EOF */
  199192. ){
  199193. i64 iLast = *piLast;
  199194. i64 iRowid;
  199195. iRowid = pIter->iRowid;
  199196. if( (bDesc==0 && iLast>iRowid) || (bDesc && iLast<iRowid) ){
  199197. int rc = sqlite3Fts5IterNextFrom(pIter, iLast);
  199198. if( rc || sqlite3Fts5IterEof(pIter) ){
  199199. *pRc = rc;
  199200. *pbEof = 1;
  199201. return 1;
  199202. }
  199203. iRowid = pIter->iRowid;
  199204. assert( (bDesc==0 && iRowid>=iLast) || (bDesc==1 && iRowid<=iLast) );
  199205. }
  199206. *piLast = iRowid;
  199207. return 0;
  199208. }
  199209. static int fts5ExprSynonymAdvanceto(
  199210. Fts5ExprTerm *pTerm, /* Term iterator to advance */
  199211. int bDesc, /* True if iterator is "rowid DESC" */
  199212. i64 *piLast, /* IN/OUT: Lastest rowid seen so far */
  199213. int *pRc /* OUT: Error code */
  199214. ){
  199215. int rc = SQLITE_OK;
  199216. i64 iLast = *piLast;
  199217. Fts5ExprTerm *p;
  199218. int bEof = 0;
  199219. for(p=pTerm; rc==SQLITE_OK && p; p=p->pSynonym){
  199220. if( sqlite3Fts5IterEof(p->pIter)==0 ){
  199221. i64 iRowid = p->pIter->iRowid;
  199222. if( (bDesc==0 && iLast>iRowid) || (bDesc && iLast<iRowid) ){
  199223. rc = sqlite3Fts5IterNextFrom(p->pIter, iLast);
  199224. }
  199225. }
  199226. }
  199227. if( rc!=SQLITE_OK ){
  199228. *pRc = rc;
  199229. bEof = 1;
  199230. }else{
  199231. *piLast = fts5ExprSynonymRowid(pTerm, bDesc, &bEof);
  199232. }
  199233. return bEof;
  199234. }
  199235. static int fts5ExprNearTest(
  199236. int *pRc,
  199237. Fts5Expr *pExpr, /* Expression that pNear is a part of */
  199238. Fts5ExprNode *pNode /* The "NEAR" node (FTS5_STRING) */
  199239. ){
  199240. Fts5ExprNearset *pNear = pNode->pNear;
  199241. int rc = *pRc;
  199242. if( pExpr->pConfig->eDetail!=FTS5_DETAIL_FULL ){
  199243. Fts5ExprTerm *pTerm;
  199244. Fts5ExprPhrase *pPhrase = pNear->apPhrase[0];
  199245. pPhrase->poslist.n = 0;
  199246. for(pTerm=&pPhrase->aTerm[0]; pTerm; pTerm=pTerm->pSynonym){
  199247. Fts5IndexIter *pIter = pTerm->pIter;
  199248. if( sqlite3Fts5IterEof(pIter)==0 ){
  199249. if( pIter->iRowid==pNode->iRowid && pIter->nData>0 ){
  199250. pPhrase->poslist.n = 1;
  199251. }
  199252. }
  199253. }
  199254. return pPhrase->poslist.n;
  199255. }else{
  199256. int i;
  199257. /* Check that each phrase in the nearset matches the current row.
  199258. ** Populate the pPhrase->poslist buffers at the same time. If any
  199259. ** phrase is not a match, break out of the loop early. */
  199260. for(i=0; rc==SQLITE_OK && i<pNear->nPhrase; i++){
  199261. Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
  199262. if( pPhrase->nTerm>1 || pPhrase->aTerm[0].pSynonym
  199263. || pNear->pColset || pPhrase->aTerm[0].bFirst
  199264. ){
  199265. int bMatch = 0;
  199266. rc = fts5ExprPhraseIsMatch(pNode, pPhrase, &bMatch);
  199267. if( bMatch==0 ) break;
  199268. }else{
  199269. Fts5IndexIter *pIter = pPhrase->aTerm[0].pIter;
  199270. fts5BufferSet(&rc, &pPhrase->poslist, pIter->nData, pIter->pData);
  199271. }
  199272. }
  199273. *pRc = rc;
  199274. if( i==pNear->nPhrase && (i==1 || fts5ExprNearIsMatch(pRc, pNear)) ){
  199275. return 1;
  199276. }
  199277. return 0;
  199278. }
  199279. }
  199280. /*
  199281. ** Initialize all term iterators in the pNear object. If any term is found
  199282. ** to match no documents at all, return immediately without initializing any
  199283. ** further iterators.
  199284. **
  199285. ** If an error occurs, return an SQLite error code. Otherwise, return
  199286. ** SQLITE_OK. It is not considered an error if some term matches zero
  199287. ** documents.
  199288. */
  199289. static int fts5ExprNearInitAll(
  199290. Fts5Expr *pExpr,
  199291. Fts5ExprNode *pNode
  199292. ){
  199293. Fts5ExprNearset *pNear = pNode->pNear;
  199294. int i;
  199295. assert( pNode->bNomatch==0 );
  199296. for(i=0; i<pNear->nPhrase; i++){
  199297. Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
  199298. if( pPhrase->nTerm==0 ){
  199299. pNode->bEof = 1;
  199300. return SQLITE_OK;
  199301. }else{
  199302. int j;
  199303. for(j=0; j<pPhrase->nTerm; j++){
  199304. Fts5ExprTerm *pTerm = &pPhrase->aTerm[j];
  199305. Fts5ExprTerm *p;
  199306. int bHit = 0;
  199307. for(p=pTerm; p; p=p->pSynonym){
  199308. int rc;
  199309. if( p->pIter ){
  199310. sqlite3Fts5IterClose(p->pIter);
  199311. p->pIter = 0;
  199312. }
  199313. rc = sqlite3Fts5IndexQuery(
  199314. pExpr->pIndex, p->zTerm, (int)strlen(p->zTerm),
  199315. (pTerm->bPrefix ? FTS5INDEX_QUERY_PREFIX : 0) |
  199316. (pExpr->bDesc ? FTS5INDEX_QUERY_DESC : 0),
  199317. pNear->pColset,
  199318. &p->pIter
  199319. );
  199320. assert( (rc==SQLITE_OK)==(p->pIter!=0) );
  199321. if( rc!=SQLITE_OK ) return rc;
  199322. if( 0==sqlite3Fts5IterEof(p->pIter) ){
  199323. bHit = 1;
  199324. }
  199325. }
  199326. if( bHit==0 ){
  199327. pNode->bEof = 1;
  199328. return SQLITE_OK;
  199329. }
  199330. }
  199331. }
  199332. }
  199333. pNode->bEof = 0;
  199334. return SQLITE_OK;
  199335. }
  199336. /*
  199337. ** If pExpr is an ASC iterator, this function returns a value with the
  199338. ** same sign as:
  199339. **
  199340. ** (iLhs - iRhs)
  199341. **
  199342. ** Otherwise, if this is a DESC iterator, the opposite is returned:
  199343. **
  199344. ** (iRhs - iLhs)
  199345. */
  199346. static int fts5RowidCmp(
  199347. Fts5Expr *pExpr,
  199348. i64 iLhs,
  199349. i64 iRhs
  199350. ){
  199351. assert( pExpr->bDesc==0 || pExpr->bDesc==1 );
  199352. if( pExpr->bDesc==0 ){
  199353. if( iLhs<iRhs ) return -1;
  199354. return (iLhs > iRhs);
  199355. }else{
  199356. if( iLhs>iRhs ) return -1;
  199357. return (iLhs < iRhs);
  199358. }
  199359. }
  199360. static void fts5ExprSetEof(Fts5ExprNode *pNode){
  199361. int i;
  199362. pNode->bEof = 1;
  199363. pNode->bNomatch = 0;
  199364. for(i=0; i<pNode->nChild; i++){
  199365. fts5ExprSetEof(pNode->apChild[i]);
  199366. }
  199367. }
  199368. static void fts5ExprNodeZeroPoslist(Fts5ExprNode *pNode){
  199369. if( pNode->eType==FTS5_STRING || pNode->eType==FTS5_TERM ){
  199370. Fts5ExprNearset *pNear = pNode->pNear;
  199371. int i;
  199372. for(i=0; i<pNear->nPhrase; i++){
  199373. Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
  199374. pPhrase->poslist.n = 0;
  199375. }
  199376. }else{
  199377. int i;
  199378. for(i=0; i<pNode->nChild; i++){
  199379. fts5ExprNodeZeroPoslist(pNode->apChild[i]);
  199380. }
  199381. }
  199382. }
  199383. /*
  199384. ** Compare the values currently indicated by the two nodes as follows:
  199385. **
  199386. ** res = (*p1) - (*p2)
  199387. **
  199388. ** Nodes that point to values that come later in the iteration order are
  199389. ** considered to be larger. Nodes at EOF are the largest of all.
  199390. **
  199391. ** This means that if the iteration order is ASC, then numerically larger
  199392. ** rowids are considered larger. Or if it is the default DESC, numerically
  199393. ** smaller rowids are larger.
  199394. */
  199395. static int fts5NodeCompare(
  199396. Fts5Expr *pExpr,
  199397. Fts5ExprNode *p1,
  199398. Fts5ExprNode *p2
  199399. ){
  199400. if( p2->bEof ) return -1;
  199401. if( p1->bEof ) return +1;
  199402. return fts5RowidCmp(pExpr, p1->iRowid, p2->iRowid);
  199403. }
  199404. /*
  199405. ** All individual term iterators in pNear are guaranteed to be valid when
  199406. ** this function is called. This function checks if all term iterators
  199407. ** point to the same rowid, and if not, advances them until they do.
  199408. ** If an EOF is reached before this happens, *pbEof is set to true before
  199409. ** returning.
  199410. **
  199411. ** SQLITE_OK is returned if an error occurs, or an SQLite error code
  199412. ** otherwise. It is not considered an error code if an iterator reaches
  199413. ** EOF.
  199414. */
  199415. static int fts5ExprNodeTest_STRING(
  199416. Fts5Expr *pExpr, /* Expression pPhrase belongs to */
  199417. Fts5ExprNode *pNode
  199418. ){
  199419. Fts5ExprNearset *pNear = pNode->pNear;
  199420. Fts5ExprPhrase *pLeft = pNear->apPhrase[0];
  199421. int rc = SQLITE_OK;
  199422. i64 iLast; /* Lastest rowid any iterator points to */
  199423. int i, j; /* Phrase and token index, respectively */
  199424. int bMatch; /* True if all terms are at the same rowid */
  199425. const int bDesc = pExpr->bDesc;
  199426. /* Check that this node should not be FTS5_TERM */
  199427. assert( pNear->nPhrase>1
  199428. || pNear->apPhrase[0]->nTerm>1
  199429. || pNear->apPhrase[0]->aTerm[0].pSynonym
  199430. || pNear->apPhrase[0]->aTerm[0].bFirst
  199431. );
  199432. /* Initialize iLast, the "lastest" rowid any iterator points to. If the
  199433. ** iterator skips through rowids in the default ascending order, this means
  199434. ** the maximum rowid. Or, if the iterator is "ORDER BY rowid DESC", then it
  199435. ** means the minimum rowid. */
  199436. if( pLeft->aTerm[0].pSynonym ){
  199437. iLast = fts5ExprSynonymRowid(&pLeft->aTerm[0], bDesc, 0);
  199438. }else{
  199439. iLast = pLeft->aTerm[0].pIter->iRowid;
  199440. }
  199441. do {
  199442. bMatch = 1;
  199443. for(i=0; i<pNear->nPhrase; i++){
  199444. Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
  199445. for(j=0; j<pPhrase->nTerm; j++){
  199446. Fts5ExprTerm *pTerm = &pPhrase->aTerm[j];
  199447. if( pTerm->pSynonym ){
  199448. i64 iRowid = fts5ExprSynonymRowid(pTerm, bDesc, 0);
  199449. if( iRowid==iLast ) continue;
  199450. bMatch = 0;
  199451. if( fts5ExprSynonymAdvanceto(pTerm, bDesc, &iLast, &rc) ){
  199452. pNode->bNomatch = 0;
  199453. pNode->bEof = 1;
  199454. return rc;
  199455. }
  199456. }else{
  199457. Fts5IndexIter *pIter = pPhrase->aTerm[j].pIter;
  199458. if( pIter->iRowid==iLast || pIter->bEof ) continue;
  199459. bMatch = 0;
  199460. if( fts5ExprAdvanceto(pIter, bDesc, &iLast, &rc, &pNode->bEof) ){
  199461. return rc;
  199462. }
  199463. }
  199464. }
  199465. }
  199466. }while( bMatch==0 );
  199467. pNode->iRowid = iLast;
  199468. pNode->bNomatch = ((0==fts5ExprNearTest(&rc, pExpr, pNode)) && rc==SQLITE_OK);
  199469. assert( pNode->bEof==0 || pNode->bNomatch==0 );
  199470. return rc;
  199471. }
  199472. /*
  199473. ** Advance the first term iterator in the first phrase of pNear. Set output
  199474. ** variable *pbEof to true if it reaches EOF or if an error occurs.
  199475. **
  199476. ** Return SQLITE_OK if successful, or an SQLite error code if an error
  199477. ** occurs.
  199478. */
  199479. static int fts5ExprNodeNext_STRING(
  199480. Fts5Expr *pExpr, /* Expression pPhrase belongs to */
  199481. Fts5ExprNode *pNode, /* FTS5_STRING or FTS5_TERM node */
  199482. int bFromValid,
  199483. i64 iFrom
  199484. ){
  199485. Fts5ExprTerm *pTerm = &pNode->pNear->apPhrase[0]->aTerm[0];
  199486. int rc = SQLITE_OK;
  199487. pNode->bNomatch = 0;
  199488. if( pTerm->pSynonym ){
  199489. int bEof = 1;
  199490. Fts5ExprTerm *p;
  199491. /* Find the firstest rowid any synonym points to. */
  199492. i64 iRowid = fts5ExprSynonymRowid(pTerm, pExpr->bDesc, 0);
  199493. /* Advance each iterator that currently points to iRowid. Or, if iFrom
  199494. ** is valid - each iterator that points to a rowid before iFrom. */
  199495. for(p=pTerm; p; p=p->pSynonym){
  199496. if( sqlite3Fts5IterEof(p->pIter)==0 ){
  199497. i64 ii = p->pIter->iRowid;
  199498. if( ii==iRowid
  199499. || (bFromValid && ii!=iFrom && (ii>iFrom)==pExpr->bDesc)
  199500. ){
  199501. if( bFromValid ){
  199502. rc = sqlite3Fts5IterNextFrom(p->pIter, iFrom);
  199503. }else{
  199504. rc = sqlite3Fts5IterNext(p->pIter);
  199505. }
  199506. if( rc!=SQLITE_OK ) break;
  199507. if( sqlite3Fts5IterEof(p->pIter)==0 ){
  199508. bEof = 0;
  199509. }
  199510. }else{
  199511. bEof = 0;
  199512. }
  199513. }
  199514. }
  199515. /* Set the EOF flag if either all synonym iterators are at EOF or an
  199516. ** error has occurred. */
  199517. pNode->bEof = (rc || bEof);
  199518. }else{
  199519. Fts5IndexIter *pIter = pTerm->pIter;
  199520. assert( Fts5NodeIsString(pNode) );
  199521. if( bFromValid ){
  199522. rc = sqlite3Fts5IterNextFrom(pIter, iFrom);
  199523. }else{
  199524. rc = sqlite3Fts5IterNext(pIter);
  199525. }
  199526. pNode->bEof = (rc || sqlite3Fts5IterEof(pIter));
  199527. }
  199528. if( pNode->bEof==0 ){
  199529. assert( rc==SQLITE_OK );
  199530. rc = fts5ExprNodeTest_STRING(pExpr, pNode);
  199531. }
  199532. return rc;
  199533. }
  199534. static int fts5ExprNodeTest_TERM(
  199535. Fts5Expr *pExpr, /* Expression that pNear is a part of */
  199536. Fts5ExprNode *pNode /* The "NEAR" node (FTS5_TERM) */
  199537. ){
  199538. /* As this "NEAR" object is actually a single phrase that consists
  199539. ** of a single term only, grab pointers into the poslist managed by the
  199540. ** fts5_index.c iterator object. This is much faster than synthesizing
  199541. ** a new poslist the way we have to for more complicated phrase or NEAR
  199542. ** expressions. */
  199543. Fts5ExprPhrase *pPhrase = pNode->pNear->apPhrase[0];
  199544. Fts5IndexIter *pIter = pPhrase->aTerm[0].pIter;
  199545. assert( pNode->eType==FTS5_TERM );
  199546. assert( pNode->pNear->nPhrase==1 && pPhrase->nTerm==1 );
  199547. assert( pPhrase->aTerm[0].pSynonym==0 );
  199548. pPhrase->poslist.n = pIter->nData;
  199549. if( pExpr->pConfig->eDetail==FTS5_DETAIL_FULL ){
  199550. pPhrase->poslist.p = (u8*)pIter->pData;
  199551. }
  199552. pNode->iRowid = pIter->iRowid;
  199553. pNode->bNomatch = (pPhrase->poslist.n==0);
  199554. return SQLITE_OK;
  199555. }
  199556. /*
  199557. ** xNext() method for a node of type FTS5_TERM.
  199558. */
  199559. static int fts5ExprNodeNext_TERM(
  199560. Fts5Expr *pExpr,
  199561. Fts5ExprNode *pNode,
  199562. int bFromValid,
  199563. i64 iFrom
  199564. ){
  199565. int rc;
  199566. Fts5IndexIter *pIter = pNode->pNear->apPhrase[0]->aTerm[0].pIter;
  199567. assert( pNode->bEof==0 );
  199568. if( bFromValid ){
  199569. rc = sqlite3Fts5IterNextFrom(pIter, iFrom);
  199570. }else{
  199571. rc = sqlite3Fts5IterNext(pIter);
  199572. }
  199573. if( rc==SQLITE_OK && sqlite3Fts5IterEof(pIter)==0 ){
  199574. rc = fts5ExprNodeTest_TERM(pExpr, pNode);
  199575. }else{
  199576. pNode->bEof = 1;
  199577. pNode->bNomatch = 0;
  199578. }
  199579. return rc;
  199580. }
  199581. static void fts5ExprNodeTest_OR(
  199582. Fts5Expr *pExpr, /* Expression of which pNode is a part */
  199583. Fts5ExprNode *pNode /* Expression node to test */
  199584. ){
  199585. Fts5ExprNode *pNext = pNode->apChild[0];
  199586. int i;
  199587. for(i=1; i<pNode->nChild; i++){
  199588. Fts5ExprNode *pChild = pNode->apChild[i];
  199589. int cmp = fts5NodeCompare(pExpr, pNext, pChild);
  199590. if( cmp>0 || (cmp==0 && pChild->bNomatch==0) ){
  199591. pNext = pChild;
  199592. }
  199593. }
  199594. pNode->iRowid = pNext->iRowid;
  199595. pNode->bEof = pNext->bEof;
  199596. pNode->bNomatch = pNext->bNomatch;
  199597. }
  199598. static int fts5ExprNodeNext_OR(
  199599. Fts5Expr *pExpr,
  199600. Fts5ExprNode *pNode,
  199601. int bFromValid,
  199602. i64 iFrom
  199603. ){
  199604. int i;
  199605. i64 iLast = pNode->iRowid;
  199606. for(i=0; i<pNode->nChild; i++){
  199607. Fts5ExprNode *p1 = pNode->apChild[i];
  199608. assert( p1->bEof || fts5RowidCmp(pExpr, p1->iRowid, iLast)>=0 );
  199609. if( p1->bEof==0 ){
  199610. if( (p1->iRowid==iLast)
  199611. || (bFromValid && fts5RowidCmp(pExpr, p1->iRowid, iFrom)<0)
  199612. ){
  199613. int rc = fts5ExprNodeNext(pExpr, p1, bFromValid, iFrom);
  199614. if( rc!=SQLITE_OK ){
  199615. pNode->bNomatch = 0;
  199616. return rc;
  199617. }
  199618. }
  199619. }
  199620. }
  199621. fts5ExprNodeTest_OR(pExpr, pNode);
  199622. return SQLITE_OK;
  199623. }
  199624. /*
  199625. ** Argument pNode is an FTS5_AND node.
  199626. */
  199627. static int fts5ExprNodeTest_AND(
  199628. Fts5Expr *pExpr, /* Expression pPhrase belongs to */
  199629. Fts5ExprNode *pAnd /* FTS5_AND node to advance */
  199630. ){
  199631. int iChild;
  199632. i64 iLast = pAnd->iRowid;
  199633. int rc = SQLITE_OK;
  199634. int bMatch;
  199635. assert( pAnd->bEof==0 );
  199636. do {
  199637. pAnd->bNomatch = 0;
  199638. bMatch = 1;
  199639. for(iChild=0; iChild<pAnd->nChild; iChild++){
  199640. Fts5ExprNode *pChild = pAnd->apChild[iChild];
  199641. int cmp = fts5RowidCmp(pExpr, iLast, pChild->iRowid);
  199642. if( cmp>0 ){
  199643. /* Advance pChild until it points to iLast or laster */
  199644. rc = fts5ExprNodeNext(pExpr, pChild, 1, iLast);
  199645. if( rc!=SQLITE_OK ){
  199646. pAnd->bNomatch = 0;
  199647. return rc;
  199648. }
  199649. }
  199650. /* If the child node is now at EOF, so is the parent AND node. Otherwise,
  199651. ** the child node is guaranteed to have advanced at least as far as
  199652. ** rowid iLast. So if it is not at exactly iLast, pChild->iRowid is the
  199653. ** new lastest rowid seen so far. */
  199654. assert( pChild->bEof || fts5RowidCmp(pExpr, iLast, pChild->iRowid)<=0 );
  199655. if( pChild->bEof ){
  199656. fts5ExprSetEof(pAnd);
  199657. bMatch = 1;
  199658. break;
  199659. }else if( iLast!=pChild->iRowid ){
  199660. bMatch = 0;
  199661. iLast = pChild->iRowid;
  199662. }
  199663. if( pChild->bNomatch ){
  199664. pAnd->bNomatch = 1;
  199665. }
  199666. }
  199667. }while( bMatch==0 );
  199668. if( pAnd->bNomatch && pAnd!=pExpr->pRoot ){
  199669. fts5ExprNodeZeroPoslist(pAnd);
  199670. }
  199671. pAnd->iRowid = iLast;
  199672. return SQLITE_OK;
  199673. }
  199674. static int fts5ExprNodeNext_AND(
  199675. Fts5Expr *pExpr,
  199676. Fts5ExprNode *pNode,
  199677. int bFromValid,
  199678. i64 iFrom
  199679. ){
  199680. int rc = fts5ExprNodeNext(pExpr, pNode->apChild[0], bFromValid, iFrom);
  199681. if( rc==SQLITE_OK ){
  199682. rc = fts5ExprNodeTest_AND(pExpr, pNode);
  199683. }else{
  199684. pNode->bNomatch = 0;
  199685. }
  199686. return rc;
  199687. }
  199688. static int fts5ExprNodeTest_NOT(
  199689. Fts5Expr *pExpr, /* Expression pPhrase belongs to */
  199690. Fts5ExprNode *pNode /* FTS5_NOT node to advance */
  199691. ){
  199692. int rc = SQLITE_OK;
  199693. Fts5ExprNode *p1 = pNode->apChild[0];
  199694. Fts5ExprNode *p2 = pNode->apChild[1];
  199695. assert( pNode->nChild==2 );
  199696. while( rc==SQLITE_OK && p1->bEof==0 ){
  199697. int cmp = fts5NodeCompare(pExpr, p1, p2);
  199698. if( cmp>0 ){
  199699. rc = fts5ExprNodeNext(pExpr, p2, 1, p1->iRowid);
  199700. cmp = fts5NodeCompare(pExpr, p1, p2);
  199701. }
  199702. assert( rc!=SQLITE_OK || cmp<=0 );
  199703. if( cmp || p2->bNomatch ) break;
  199704. rc = fts5ExprNodeNext(pExpr, p1, 0, 0);
  199705. }
  199706. pNode->bEof = p1->bEof;
  199707. pNode->bNomatch = p1->bNomatch;
  199708. pNode->iRowid = p1->iRowid;
  199709. if( p1->bEof ){
  199710. fts5ExprNodeZeroPoslist(p2);
  199711. }
  199712. return rc;
  199713. }
  199714. static int fts5ExprNodeNext_NOT(
  199715. Fts5Expr *pExpr,
  199716. Fts5ExprNode *pNode,
  199717. int bFromValid,
  199718. i64 iFrom
  199719. ){
  199720. int rc = fts5ExprNodeNext(pExpr, pNode->apChild[0], bFromValid, iFrom);
  199721. if( rc==SQLITE_OK ){
  199722. rc = fts5ExprNodeTest_NOT(pExpr, pNode);
  199723. }
  199724. if( rc!=SQLITE_OK ){
  199725. pNode->bNomatch = 0;
  199726. }
  199727. return rc;
  199728. }
  199729. /*
  199730. ** If pNode currently points to a match, this function returns SQLITE_OK
  199731. ** without modifying it. Otherwise, pNode is advanced until it does point
  199732. ** to a match or EOF is reached.
  199733. */
  199734. static int fts5ExprNodeTest(
  199735. Fts5Expr *pExpr, /* Expression of which pNode is a part */
  199736. Fts5ExprNode *pNode /* Expression node to test */
  199737. ){
  199738. int rc = SQLITE_OK;
  199739. if( pNode->bEof==0 ){
  199740. switch( pNode->eType ){
  199741. case FTS5_STRING: {
  199742. rc = fts5ExprNodeTest_STRING(pExpr, pNode);
  199743. break;
  199744. }
  199745. case FTS5_TERM: {
  199746. rc = fts5ExprNodeTest_TERM(pExpr, pNode);
  199747. break;
  199748. }
  199749. case FTS5_AND: {
  199750. rc = fts5ExprNodeTest_AND(pExpr, pNode);
  199751. break;
  199752. }
  199753. case FTS5_OR: {
  199754. fts5ExprNodeTest_OR(pExpr, pNode);
  199755. break;
  199756. }
  199757. default: assert( pNode->eType==FTS5_NOT ); {
  199758. rc = fts5ExprNodeTest_NOT(pExpr, pNode);
  199759. break;
  199760. }
  199761. }
  199762. }
  199763. return rc;
  199764. }
  199765. /*
  199766. ** Set node pNode, which is part of expression pExpr, to point to the first
  199767. ** match. If there are no matches, set the Node.bEof flag to indicate EOF.
  199768. **
  199769. ** Return an SQLite error code if an error occurs, or SQLITE_OK otherwise.
  199770. ** It is not an error if there are no matches.
  199771. */
  199772. static int fts5ExprNodeFirst(Fts5Expr *pExpr, Fts5ExprNode *pNode){
  199773. int rc = SQLITE_OK;
  199774. pNode->bEof = 0;
  199775. pNode->bNomatch = 0;
  199776. if( Fts5NodeIsString(pNode) ){
  199777. /* Initialize all term iterators in the NEAR object. */
  199778. rc = fts5ExprNearInitAll(pExpr, pNode);
  199779. }else if( pNode->xNext==0 ){
  199780. pNode->bEof = 1;
  199781. }else{
  199782. int i;
  199783. int nEof = 0;
  199784. for(i=0; i<pNode->nChild && rc==SQLITE_OK; i++){
  199785. Fts5ExprNode *pChild = pNode->apChild[i];
  199786. rc = fts5ExprNodeFirst(pExpr, pNode->apChild[i]);
  199787. assert( pChild->bEof==0 || pChild->bEof==1 );
  199788. nEof += pChild->bEof;
  199789. }
  199790. pNode->iRowid = pNode->apChild[0]->iRowid;
  199791. switch( pNode->eType ){
  199792. case FTS5_AND:
  199793. if( nEof>0 ) fts5ExprSetEof(pNode);
  199794. break;
  199795. case FTS5_OR:
  199796. if( pNode->nChild==nEof ) fts5ExprSetEof(pNode);
  199797. break;
  199798. default:
  199799. assert( pNode->eType==FTS5_NOT );
  199800. pNode->bEof = pNode->apChild[0]->bEof;
  199801. break;
  199802. }
  199803. }
  199804. if( rc==SQLITE_OK ){
  199805. rc = fts5ExprNodeTest(pExpr, pNode);
  199806. }
  199807. return rc;
  199808. }
  199809. /*
  199810. ** Begin iterating through the set of documents in index pIdx matched by
  199811. ** the MATCH expression passed as the first argument. If the "bDesc"
  199812. ** parameter is passed a non-zero value, iteration is in descending rowid
  199813. ** order. Or, if it is zero, in ascending order.
  199814. **
  199815. ** If iterating in ascending rowid order (bDesc==0), the first document
  199816. ** visited is that with the smallest rowid that is larger than or equal
  199817. ** to parameter iFirst. Or, if iterating in ascending order (bDesc==1),
  199818. ** then the first document visited must have a rowid smaller than or
  199819. ** equal to iFirst.
  199820. **
  199821. ** Return SQLITE_OK if successful, or an SQLite error code otherwise. It
  199822. ** is not considered an error if the query does not match any documents.
  199823. */
  199824. static int sqlite3Fts5ExprFirst(Fts5Expr *p, Fts5Index *pIdx, i64 iFirst, int bDesc){
  199825. Fts5ExprNode *pRoot = p->pRoot;
  199826. int rc; /* Return code */
  199827. p->pIndex = pIdx;
  199828. p->bDesc = bDesc;
  199829. rc = fts5ExprNodeFirst(p, pRoot);
  199830. /* If not at EOF but the current rowid occurs earlier than iFirst in
  199831. ** the iteration order, move to document iFirst or later. */
  199832. if( rc==SQLITE_OK
  199833. && 0==pRoot->bEof
  199834. && fts5RowidCmp(p, pRoot->iRowid, iFirst)<0
  199835. ){
  199836. rc = fts5ExprNodeNext(p, pRoot, 1, iFirst);
  199837. }
  199838. /* If the iterator is not at a real match, skip forward until it is. */
  199839. while( pRoot->bNomatch ){
  199840. assert( pRoot->bEof==0 && rc==SQLITE_OK );
  199841. rc = fts5ExprNodeNext(p, pRoot, 0, 0);
  199842. }
  199843. return rc;
  199844. }
  199845. /*
  199846. ** Move to the next document
  199847. **
  199848. ** Return SQLITE_OK if successful, or an SQLite error code otherwise. It
  199849. ** is not considered an error if the query does not match any documents.
  199850. */
  199851. static int sqlite3Fts5ExprNext(Fts5Expr *p, i64 iLast){
  199852. int rc;
  199853. Fts5ExprNode *pRoot = p->pRoot;
  199854. assert( pRoot->bEof==0 && pRoot->bNomatch==0 );
  199855. do {
  199856. rc = fts5ExprNodeNext(p, pRoot, 0, 0);
  199857. assert( pRoot->bNomatch==0 || (rc==SQLITE_OK && pRoot->bEof==0) );
  199858. }while( pRoot->bNomatch );
  199859. if( fts5RowidCmp(p, pRoot->iRowid, iLast)>0 ){
  199860. pRoot->bEof = 1;
  199861. }
  199862. return rc;
  199863. }
  199864. static int sqlite3Fts5ExprEof(Fts5Expr *p){
  199865. return p->pRoot->bEof;
  199866. }
  199867. static i64 sqlite3Fts5ExprRowid(Fts5Expr *p){
  199868. return p->pRoot->iRowid;
  199869. }
  199870. static int fts5ParseStringFromToken(Fts5Token *pToken, char **pz){
  199871. int rc = SQLITE_OK;
  199872. *pz = sqlite3Fts5Strndup(&rc, pToken->p, pToken->n);
  199873. return rc;
  199874. }
  199875. /*
  199876. ** Free the phrase object passed as the only argument.
  199877. */
  199878. static void fts5ExprPhraseFree(Fts5ExprPhrase *pPhrase){
  199879. if( pPhrase ){
  199880. int i;
  199881. for(i=0; i<pPhrase->nTerm; i++){
  199882. Fts5ExprTerm *pSyn;
  199883. Fts5ExprTerm *pNext;
  199884. Fts5ExprTerm *pTerm = &pPhrase->aTerm[i];
  199885. sqlite3_free(pTerm->zTerm);
  199886. sqlite3Fts5IterClose(pTerm->pIter);
  199887. for(pSyn=pTerm->pSynonym; pSyn; pSyn=pNext){
  199888. pNext = pSyn->pSynonym;
  199889. sqlite3Fts5IterClose(pSyn->pIter);
  199890. fts5BufferFree((Fts5Buffer*)&pSyn[1]);
  199891. sqlite3_free(pSyn);
  199892. }
  199893. }
  199894. if( pPhrase->poslist.nSpace>0 ) fts5BufferFree(&pPhrase->poslist);
  199895. sqlite3_free(pPhrase);
  199896. }
  199897. }
  199898. /*
  199899. ** Set the "bFirst" flag on the first token of the phrase passed as the
  199900. ** only argument.
  199901. */
  199902. static void sqlite3Fts5ParseSetCaret(Fts5ExprPhrase *pPhrase){
  199903. if( pPhrase && pPhrase->nTerm ){
  199904. pPhrase->aTerm[0].bFirst = 1;
  199905. }
  199906. }
  199907. /*
  199908. ** If argument pNear is NULL, then a new Fts5ExprNearset object is allocated
  199909. ** and populated with pPhrase. Or, if pNear is not NULL, phrase pPhrase is
  199910. ** appended to it and the results returned.
  199911. **
  199912. ** If an OOM error occurs, both the pNear and pPhrase objects are freed and
  199913. ** NULL returned.
  199914. */
  199915. static Fts5ExprNearset *sqlite3Fts5ParseNearset(
  199916. Fts5Parse *pParse, /* Parse context */
  199917. Fts5ExprNearset *pNear, /* Existing nearset, or NULL */
  199918. Fts5ExprPhrase *pPhrase /* Recently parsed phrase */
  199919. ){
  199920. const int SZALLOC = 8;
  199921. Fts5ExprNearset *pRet = 0;
  199922. if( pParse->rc==SQLITE_OK ){
  199923. if( pPhrase==0 ){
  199924. return pNear;
  199925. }
  199926. if( pNear==0 ){
  199927. sqlite3_int64 nByte;
  199928. nByte = sizeof(Fts5ExprNearset) + SZALLOC * sizeof(Fts5ExprPhrase*);
  199929. pRet = sqlite3_malloc64(nByte);
  199930. if( pRet==0 ){
  199931. pParse->rc = SQLITE_NOMEM;
  199932. }else{
  199933. memset(pRet, 0, (size_t)nByte);
  199934. }
  199935. }else if( (pNear->nPhrase % SZALLOC)==0 ){
  199936. int nNew = pNear->nPhrase + SZALLOC;
  199937. sqlite3_int64 nByte;
  199938. nByte = sizeof(Fts5ExprNearset) + nNew * sizeof(Fts5ExprPhrase*);
  199939. pRet = (Fts5ExprNearset*)sqlite3_realloc64(pNear, nByte);
  199940. if( pRet==0 ){
  199941. pParse->rc = SQLITE_NOMEM;
  199942. }
  199943. }else{
  199944. pRet = pNear;
  199945. }
  199946. }
  199947. if( pRet==0 ){
  199948. assert( pParse->rc!=SQLITE_OK );
  199949. sqlite3Fts5ParseNearsetFree(pNear);
  199950. sqlite3Fts5ParsePhraseFree(pPhrase);
  199951. }else{
  199952. if( pRet->nPhrase>0 ){
  199953. Fts5ExprPhrase *pLast = pRet->apPhrase[pRet->nPhrase-1];
  199954. assert( pLast==pParse->apPhrase[pParse->nPhrase-2] );
  199955. if( pPhrase->nTerm==0 ){
  199956. fts5ExprPhraseFree(pPhrase);
  199957. pRet->nPhrase--;
  199958. pParse->nPhrase--;
  199959. pPhrase = pLast;
  199960. }else if( pLast->nTerm==0 ){
  199961. fts5ExprPhraseFree(pLast);
  199962. pParse->apPhrase[pParse->nPhrase-2] = pPhrase;
  199963. pParse->nPhrase--;
  199964. pRet->nPhrase--;
  199965. }
  199966. }
  199967. pRet->apPhrase[pRet->nPhrase++] = pPhrase;
  199968. }
  199969. return pRet;
  199970. }
  199971. typedef struct TokenCtx TokenCtx;
  199972. struct TokenCtx {
  199973. Fts5ExprPhrase *pPhrase;
  199974. int rc;
  199975. };
  199976. /*
  199977. ** Callback for tokenizing terms used by ParseTerm().
  199978. */
  199979. static int fts5ParseTokenize(
  199980. void *pContext, /* Pointer to Fts5InsertCtx object */
  199981. int tflags, /* Mask of FTS5_TOKEN_* flags */
  199982. const char *pToken, /* Buffer containing token */
  199983. int nToken, /* Size of token in bytes */
  199984. int iUnused1, /* Start offset of token */
  199985. int iUnused2 /* End offset of token */
  199986. ){
  199987. int rc = SQLITE_OK;
  199988. const int SZALLOC = 8;
  199989. TokenCtx *pCtx = (TokenCtx*)pContext;
  199990. Fts5ExprPhrase *pPhrase = pCtx->pPhrase;
  199991. UNUSED_PARAM2(iUnused1, iUnused2);
  199992. /* If an error has already occurred, this is a no-op */
  199993. if( pCtx->rc!=SQLITE_OK ) return pCtx->rc;
  199994. if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;
  199995. if( pPhrase && pPhrase->nTerm>0 && (tflags & FTS5_TOKEN_COLOCATED) ){
  199996. Fts5ExprTerm *pSyn;
  199997. sqlite3_int64 nByte = sizeof(Fts5ExprTerm) + sizeof(Fts5Buffer) + nToken+1;
  199998. pSyn = (Fts5ExprTerm*)sqlite3_malloc64(nByte);
  199999. if( pSyn==0 ){
  200000. rc = SQLITE_NOMEM;
  200001. }else{
  200002. memset(pSyn, 0, (size_t)nByte);
  200003. pSyn->zTerm = ((char*)pSyn) + sizeof(Fts5ExprTerm) + sizeof(Fts5Buffer);
  200004. memcpy(pSyn->zTerm, pToken, nToken);
  200005. pSyn->pSynonym = pPhrase->aTerm[pPhrase->nTerm-1].pSynonym;
  200006. pPhrase->aTerm[pPhrase->nTerm-1].pSynonym = pSyn;
  200007. }
  200008. }else{
  200009. Fts5ExprTerm *pTerm;
  200010. if( pPhrase==0 || (pPhrase->nTerm % SZALLOC)==0 ){
  200011. Fts5ExprPhrase *pNew;
  200012. int nNew = SZALLOC + (pPhrase ? pPhrase->nTerm : 0);
  200013. pNew = (Fts5ExprPhrase*)sqlite3_realloc64(pPhrase,
  200014. sizeof(Fts5ExprPhrase) + sizeof(Fts5ExprTerm) * nNew
  200015. );
  200016. if( pNew==0 ){
  200017. rc = SQLITE_NOMEM;
  200018. }else{
  200019. if( pPhrase==0 ) memset(pNew, 0, sizeof(Fts5ExprPhrase));
  200020. pCtx->pPhrase = pPhrase = pNew;
  200021. pNew->nTerm = nNew - SZALLOC;
  200022. }
  200023. }
  200024. if( rc==SQLITE_OK ){
  200025. pTerm = &pPhrase->aTerm[pPhrase->nTerm++];
  200026. memset(pTerm, 0, sizeof(Fts5ExprTerm));
  200027. pTerm->zTerm = sqlite3Fts5Strndup(&rc, pToken, nToken);
  200028. }
  200029. }
  200030. pCtx->rc = rc;
  200031. return rc;
  200032. }
  200033. /*
  200034. ** Free the phrase object passed as the only argument.
  200035. */
  200036. static void sqlite3Fts5ParsePhraseFree(Fts5ExprPhrase *pPhrase){
  200037. fts5ExprPhraseFree(pPhrase);
  200038. }
  200039. /*
  200040. ** Free the phrase object passed as the second argument.
  200041. */
  200042. static void sqlite3Fts5ParseNearsetFree(Fts5ExprNearset *pNear){
  200043. if( pNear ){
  200044. int i;
  200045. for(i=0; i<pNear->nPhrase; i++){
  200046. fts5ExprPhraseFree(pNear->apPhrase[i]);
  200047. }
  200048. sqlite3_free(pNear->pColset);
  200049. sqlite3_free(pNear);
  200050. }
  200051. }
  200052. static void sqlite3Fts5ParseFinished(Fts5Parse *pParse, Fts5ExprNode *p){
  200053. assert( pParse->pExpr==0 );
  200054. pParse->pExpr = p;
  200055. }
  200056. /*
  200057. ** This function is called by the parser to process a string token. The
  200058. ** string may or may not be quoted. In any case it is tokenized and a
  200059. ** phrase object consisting of all tokens returned.
  200060. */
  200061. static Fts5ExprPhrase *sqlite3Fts5ParseTerm(
  200062. Fts5Parse *pParse, /* Parse context */
  200063. Fts5ExprPhrase *pAppend, /* Phrase to append to */
  200064. Fts5Token *pToken, /* String to tokenize */
  200065. int bPrefix /* True if there is a trailing "*" */
  200066. ){
  200067. Fts5Config *pConfig = pParse->pConfig;
  200068. TokenCtx sCtx; /* Context object passed to callback */
  200069. int rc; /* Tokenize return code */
  200070. char *z = 0;
  200071. memset(&sCtx, 0, sizeof(TokenCtx));
  200072. sCtx.pPhrase = pAppend;
  200073. rc = fts5ParseStringFromToken(pToken, &z);
  200074. if( rc==SQLITE_OK ){
  200075. int flags = FTS5_TOKENIZE_QUERY | (bPrefix ? FTS5_TOKENIZE_PREFIX : 0);
  200076. int n;
  200077. sqlite3Fts5Dequote(z);
  200078. n = (int)strlen(z);
  200079. rc = sqlite3Fts5Tokenize(pConfig, flags, z, n, &sCtx, fts5ParseTokenize);
  200080. }
  200081. sqlite3_free(z);
  200082. if( rc || (rc = sCtx.rc) ){
  200083. pParse->rc = rc;
  200084. fts5ExprPhraseFree(sCtx.pPhrase);
  200085. sCtx.pPhrase = 0;
  200086. }else{
  200087. if( pAppend==0 ){
  200088. if( (pParse->nPhrase % 8)==0 ){
  200089. sqlite3_int64 nByte = sizeof(Fts5ExprPhrase*) * (pParse->nPhrase + 8);
  200090. Fts5ExprPhrase **apNew;
  200091. apNew = (Fts5ExprPhrase**)sqlite3_realloc64(pParse->apPhrase, nByte);
  200092. if( apNew==0 ){
  200093. pParse->rc = SQLITE_NOMEM;
  200094. fts5ExprPhraseFree(sCtx.pPhrase);
  200095. return 0;
  200096. }
  200097. pParse->apPhrase = apNew;
  200098. }
  200099. pParse->nPhrase++;
  200100. }
  200101. if( sCtx.pPhrase==0 ){
  200102. /* This happens when parsing a token or quoted phrase that contains
  200103. ** no token characters at all. (e.g ... MATCH '""'). */
  200104. sCtx.pPhrase = sqlite3Fts5MallocZero(&pParse->rc, sizeof(Fts5ExprPhrase));
  200105. }else if( sCtx.pPhrase->nTerm ){
  200106. sCtx.pPhrase->aTerm[sCtx.pPhrase->nTerm-1].bPrefix = (u8)bPrefix;
  200107. }
  200108. pParse->apPhrase[pParse->nPhrase-1] = sCtx.pPhrase;
  200109. }
  200110. return sCtx.pPhrase;
  200111. }
  200112. /*
  200113. ** Create a new FTS5 expression by cloning phrase iPhrase of the
  200114. ** expression passed as the second argument.
  200115. */
  200116. static int sqlite3Fts5ExprClonePhrase(
  200117. Fts5Expr *pExpr,
  200118. int iPhrase,
  200119. Fts5Expr **ppNew
  200120. ){
  200121. int rc = SQLITE_OK; /* Return code */
  200122. Fts5ExprPhrase *pOrig; /* The phrase extracted from pExpr */
  200123. Fts5Expr *pNew = 0; /* Expression to return via *ppNew */
  200124. TokenCtx sCtx = {0,0}; /* Context object for fts5ParseTokenize */
  200125. pOrig = pExpr->apExprPhrase[iPhrase];
  200126. pNew = (Fts5Expr*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Expr));
  200127. if( rc==SQLITE_OK ){
  200128. pNew->apExprPhrase = (Fts5ExprPhrase**)sqlite3Fts5MallocZero(&rc,
  200129. sizeof(Fts5ExprPhrase*));
  200130. }
  200131. if( rc==SQLITE_OK ){
  200132. pNew->pRoot = (Fts5ExprNode*)sqlite3Fts5MallocZero(&rc,
  200133. sizeof(Fts5ExprNode));
  200134. }
  200135. if( rc==SQLITE_OK ){
  200136. pNew->pRoot->pNear = (Fts5ExprNearset*)sqlite3Fts5MallocZero(&rc,
  200137. sizeof(Fts5ExprNearset) + sizeof(Fts5ExprPhrase*));
  200138. }
  200139. if( rc==SQLITE_OK ){
  200140. Fts5Colset *pColsetOrig = pOrig->pNode->pNear->pColset;
  200141. if( pColsetOrig ){
  200142. sqlite3_int64 nByte;
  200143. Fts5Colset *pColset;
  200144. nByte = sizeof(Fts5Colset) + (pColsetOrig->nCol-1) * sizeof(int);
  200145. pColset = (Fts5Colset*)sqlite3Fts5MallocZero(&rc, nByte);
  200146. if( pColset ){
  200147. memcpy(pColset, pColsetOrig, (size_t)nByte);
  200148. }
  200149. pNew->pRoot->pNear->pColset = pColset;
  200150. }
  200151. }
  200152. if( pOrig->nTerm ){
  200153. int i; /* Used to iterate through phrase terms */
  200154. for(i=0; rc==SQLITE_OK && i<pOrig->nTerm; i++){
  200155. int tflags = 0;
  200156. Fts5ExprTerm *p;
  200157. for(p=&pOrig->aTerm[i]; p && rc==SQLITE_OK; p=p->pSynonym){
  200158. const char *zTerm = p->zTerm;
  200159. rc = fts5ParseTokenize((void*)&sCtx, tflags, zTerm, (int)strlen(zTerm),
  200160. 0, 0);
  200161. tflags = FTS5_TOKEN_COLOCATED;
  200162. }
  200163. if( rc==SQLITE_OK ){
  200164. sCtx.pPhrase->aTerm[i].bPrefix = pOrig->aTerm[i].bPrefix;
  200165. sCtx.pPhrase->aTerm[i].bFirst = pOrig->aTerm[i].bFirst;
  200166. }
  200167. }
  200168. }else{
  200169. /* This happens when parsing a token or quoted phrase that contains
  200170. ** no token characters at all. (e.g ... MATCH '""'). */
  200171. sCtx.pPhrase = sqlite3Fts5MallocZero(&rc, sizeof(Fts5ExprPhrase));
  200172. }
  200173. if( rc==SQLITE_OK ){
  200174. /* All the allocations succeeded. Put the expression object together. */
  200175. pNew->pIndex = pExpr->pIndex;
  200176. pNew->pConfig = pExpr->pConfig;
  200177. pNew->nPhrase = 1;
  200178. pNew->apExprPhrase[0] = sCtx.pPhrase;
  200179. pNew->pRoot->pNear->apPhrase[0] = sCtx.pPhrase;
  200180. pNew->pRoot->pNear->nPhrase = 1;
  200181. sCtx.pPhrase->pNode = pNew->pRoot;
  200182. if( pOrig->nTerm==1
  200183. && pOrig->aTerm[0].pSynonym==0
  200184. && pOrig->aTerm[0].bFirst==0
  200185. ){
  200186. pNew->pRoot->eType = FTS5_TERM;
  200187. pNew->pRoot->xNext = fts5ExprNodeNext_TERM;
  200188. }else{
  200189. pNew->pRoot->eType = FTS5_STRING;
  200190. pNew->pRoot->xNext = fts5ExprNodeNext_STRING;
  200191. }
  200192. }else{
  200193. sqlite3Fts5ExprFree(pNew);
  200194. fts5ExprPhraseFree(sCtx.pPhrase);
  200195. pNew = 0;
  200196. }
  200197. *ppNew = pNew;
  200198. return rc;
  200199. }
  200200. /*
  200201. ** Token pTok has appeared in a MATCH expression where the NEAR operator
  200202. ** is expected. If token pTok does not contain "NEAR", store an error
  200203. ** in the pParse object.
  200204. */
  200205. static void sqlite3Fts5ParseNear(Fts5Parse *pParse, Fts5Token *pTok){
  200206. if( pTok->n!=4 || memcmp("NEAR", pTok->p, 4) ){
  200207. sqlite3Fts5ParseError(
  200208. pParse, "fts5: syntax error near \"%.*s\"", pTok->n, pTok->p
  200209. );
  200210. }
  200211. }
  200212. static void sqlite3Fts5ParseSetDistance(
  200213. Fts5Parse *pParse,
  200214. Fts5ExprNearset *pNear,
  200215. Fts5Token *p
  200216. ){
  200217. if( pNear ){
  200218. int nNear = 0;
  200219. int i;
  200220. if( p->n ){
  200221. for(i=0; i<p->n; i++){
  200222. char c = (char)p->p[i];
  200223. if( c<'0' || c>'9' ){
  200224. sqlite3Fts5ParseError(
  200225. pParse, "expected integer, got \"%.*s\"", p->n, p->p
  200226. );
  200227. return;
  200228. }
  200229. nNear = nNear * 10 + (p->p[i] - '0');
  200230. }
  200231. }else{
  200232. nNear = FTS5_DEFAULT_NEARDIST;
  200233. }
  200234. pNear->nNear = nNear;
  200235. }
  200236. }
  200237. /*
  200238. ** The second argument passed to this function may be NULL, or it may be
  200239. ** an existing Fts5Colset object. This function returns a pointer to
  200240. ** a new colset object containing the contents of (p) with new value column
  200241. ** number iCol appended.
  200242. **
  200243. ** If an OOM error occurs, store an error code in pParse and return NULL.
  200244. ** The old colset object (if any) is not freed in this case.
  200245. */
  200246. static Fts5Colset *fts5ParseColset(
  200247. Fts5Parse *pParse, /* Store SQLITE_NOMEM here if required */
  200248. Fts5Colset *p, /* Existing colset object */
  200249. int iCol /* New column to add to colset object */
  200250. ){
  200251. int nCol = p ? p->nCol : 0; /* Num. columns already in colset object */
  200252. Fts5Colset *pNew; /* New colset object to return */
  200253. assert( pParse->rc==SQLITE_OK );
  200254. assert( iCol>=0 && iCol<pParse->pConfig->nCol );
  200255. pNew = sqlite3_realloc64(p, sizeof(Fts5Colset) + sizeof(int)*nCol);
  200256. if( pNew==0 ){
  200257. pParse->rc = SQLITE_NOMEM;
  200258. }else{
  200259. int *aiCol = pNew->aiCol;
  200260. int i, j;
  200261. for(i=0; i<nCol; i++){
  200262. if( aiCol[i]==iCol ) return pNew;
  200263. if( aiCol[i]>iCol ) break;
  200264. }
  200265. for(j=nCol; j>i; j--){
  200266. aiCol[j] = aiCol[j-1];
  200267. }
  200268. aiCol[i] = iCol;
  200269. pNew->nCol = nCol+1;
  200270. #ifndef NDEBUG
  200271. /* Check that the array is in order and contains no duplicate entries. */
  200272. for(i=1; i<pNew->nCol; i++) assert( pNew->aiCol[i]>pNew->aiCol[i-1] );
  200273. #endif
  200274. }
  200275. return pNew;
  200276. }
  200277. /*
  200278. ** Allocate and return an Fts5Colset object specifying the inverse of
  200279. ** the colset passed as the second argument. Free the colset passed
  200280. ** as the second argument before returning.
  200281. */
  200282. static Fts5Colset *sqlite3Fts5ParseColsetInvert(Fts5Parse *pParse, Fts5Colset *p){
  200283. Fts5Colset *pRet;
  200284. int nCol = pParse->pConfig->nCol;
  200285. pRet = (Fts5Colset*)sqlite3Fts5MallocZero(&pParse->rc,
  200286. sizeof(Fts5Colset) + sizeof(int)*nCol
  200287. );
  200288. if( pRet ){
  200289. int i;
  200290. int iOld = 0;
  200291. for(i=0; i<nCol; i++){
  200292. if( iOld>=p->nCol || p->aiCol[iOld]!=i ){
  200293. pRet->aiCol[pRet->nCol++] = i;
  200294. }else{
  200295. iOld++;
  200296. }
  200297. }
  200298. }
  200299. sqlite3_free(p);
  200300. return pRet;
  200301. }
  200302. static Fts5Colset *sqlite3Fts5ParseColset(
  200303. Fts5Parse *pParse, /* Store SQLITE_NOMEM here if required */
  200304. Fts5Colset *pColset, /* Existing colset object */
  200305. Fts5Token *p
  200306. ){
  200307. Fts5Colset *pRet = 0;
  200308. int iCol;
  200309. char *z; /* Dequoted copy of token p */
  200310. z = sqlite3Fts5Strndup(&pParse->rc, p->p, p->n);
  200311. if( pParse->rc==SQLITE_OK ){
  200312. Fts5Config *pConfig = pParse->pConfig;
  200313. sqlite3Fts5Dequote(z);
  200314. for(iCol=0; iCol<pConfig->nCol; iCol++){
  200315. if( 0==sqlite3_stricmp(pConfig->azCol[iCol], z) ) break;
  200316. }
  200317. if( iCol==pConfig->nCol ){
  200318. sqlite3Fts5ParseError(pParse, "no such column: %s", z);
  200319. }else{
  200320. pRet = fts5ParseColset(pParse, pColset, iCol);
  200321. }
  200322. sqlite3_free(z);
  200323. }
  200324. if( pRet==0 ){
  200325. assert( pParse->rc!=SQLITE_OK );
  200326. sqlite3_free(pColset);
  200327. }
  200328. return pRet;
  200329. }
  200330. /*
  200331. ** If argument pOrig is NULL, or if (*pRc) is set to anything other than
  200332. ** SQLITE_OK when this function is called, NULL is returned.
  200333. **
  200334. ** Otherwise, a copy of (*pOrig) is made into memory obtained from
  200335. ** sqlite3Fts5MallocZero() and a pointer to it returned. If the allocation
  200336. ** fails, (*pRc) is set to SQLITE_NOMEM and NULL is returned.
  200337. */
  200338. static Fts5Colset *fts5CloneColset(int *pRc, Fts5Colset *pOrig){
  200339. Fts5Colset *pRet;
  200340. if( pOrig ){
  200341. sqlite3_int64 nByte = sizeof(Fts5Colset) + (pOrig->nCol-1) * sizeof(int);
  200342. pRet = (Fts5Colset*)sqlite3Fts5MallocZero(pRc, nByte);
  200343. if( pRet ){
  200344. memcpy(pRet, pOrig, (size_t)nByte);
  200345. }
  200346. }else{
  200347. pRet = 0;
  200348. }
  200349. return pRet;
  200350. }
  200351. /*
  200352. ** Remove from colset pColset any columns that are not also in colset pMerge.
  200353. */
  200354. static void fts5MergeColset(Fts5Colset *pColset, Fts5Colset *pMerge){
  200355. int iIn = 0; /* Next input in pColset */
  200356. int iMerge = 0; /* Next input in pMerge */
  200357. int iOut = 0; /* Next output slot in pColset */
  200358. while( iIn<pColset->nCol && iMerge<pMerge->nCol ){
  200359. int iDiff = pColset->aiCol[iIn] - pMerge->aiCol[iMerge];
  200360. if( iDiff==0 ){
  200361. pColset->aiCol[iOut++] = pMerge->aiCol[iMerge];
  200362. iMerge++;
  200363. iIn++;
  200364. }else if( iDiff>0 ){
  200365. iMerge++;
  200366. }else{
  200367. iIn++;
  200368. }
  200369. }
  200370. pColset->nCol = iOut;
  200371. }
  200372. /*
  200373. ** Recursively apply colset pColset to expression node pNode and all of
  200374. ** its decendents. If (*ppFree) is not NULL, it contains a spare copy
  200375. ** of pColset. This function may use the spare copy and set (*ppFree) to
  200376. ** zero, or it may create copies of pColset using fts5CloneColset().
  200377. */
  200378. static void fts5ParseSetColset(
  200379. Fts5Parse *pParse,
  200380. Fts5ExprNode *pNode,
  200381. Fts5Colset *pColset,
  200382. Fts5Colset **ppFree
  200383. ){
  200384. if( pParse->rc==SQLITE_OK ){
  200385. assert( pNode->eType==FTS5_TERM || pNode->eType==FTS5_STRING
  200386. || pNode->eType==FTS5_AND || pNode->eType==FTS5_OR
  200387. || pNode->eType==FTS5_NOT || pNode->eType==FTS5_EOF
  200388. );
  200389. if( pNode->eType==FTS5_STRING || pNode->eType==FTS5_TERM ){
  200390. Fts5ExprNearset *pNear = pNode->pNear;
  200391. if( pNear->pColset ){
  200392. fts5MergeColset(pNear->pColset, pColset);
  200393. if( pNear->pColset->nCol==0 ){
  200394. pNode->eType = FTS5_EOF;
  200395. pNode->xNext = 0;
  200396. }
  200397. }else if( *ppFree ){
  200398. pNear->pColset = pColset;
  200399. *ppFree = 0;
  200400. }else{
  200401. pNear->pColset = fts5CloneColset(&pParse->rc, pColset);
  200402. }
  200403. }else{
  200404. int i;
  200405. assert( pNode->eType!=FTS5_EOF || pNode->nChild==0 );
  200406. for(i=0; i<pNode->nChild; i++){
  200407. fts5ParseSetColset(pParse, pNode->apChild[i], pColset, ppFree);
  200408. }
  200409. }
  200410. }
  200411. }
  200412. /*
  200413. ** Apply colset pColset to expression node pExpr and all of its descendents.
  200414. */
  200415. static void sqlite3Fts5ParseSetColset(
  200416. Fts5Parse *pParse,
  200417. Fts5ExprNode *pExpr,
  200418. Fts5Colset *pColset
  200419. ){
  200420. Fts5Colset *pFree = pColset;
  200421. if( pParse->pConfig->eDetail==FTS5_DETAIL_NONE ){
  200422. pParse->rc = SQLITE_ERROR;
  200423. pParse->zErr = sqlite3_mprintf(
  200424. "fts5: column queries are not supported (detail=none)"
  200425. );
  200426. }else{
  200427. fts5ParseSetColset(pParse, pExpr, pColset, &pFree);
  200428. }
  200429. sqlite3_free(pFree);
  200430. }
  200431. static void fts5ExprAssignXNext(Fts5ExprNode *pNode){
  200432. switch( pNode->eType ){
  200433. case FTS5_STRING: {
  200434. Fts5ExprNearset *pNear = pNode->pNear;
  200435. if( pNear->nPhrase==1 && pNear->apPhrase[0]->nTerm==1
  200436. && pNear->apPhrase[0]->aTerm[0].pSynonym==0
  200437. && pNear->apPhrase[0]->aTerm[0].bFirst==0
  200438. ){
  200439. pNode->eType = FTS5_TERM;
  200440. pNode->xNext = fts5ExprNodeNext_TERM;
  200441. }else{
  200442. pNode->xNext = fts5ExprNodeNext_STRING;
  200443. }
  200444. break;
  200445. };
  200446. case FTS5_OR: {
  200447. pNode->xNext = fts5ExprNodeNext_OR;
  200448. break;
  200449. };
  200450. case FTS5_AND: {
  200451. pNode->xNext = fts5ExprNodeNext_AND;
  200452. break;
  200453. };
  200454. default: assert( pNode->eType==FTS5_NOT ); {
  200455. pNode->xNext = fts5ExprNodeNext_NOT;
  200456. break;
  200457. };
  200458. }
  200459. }
  200460. static void fts5ExprAddChildren(Fts5ExprNode *p, Fts5ExprNode *pSub){
  200461. if( p->eType!=FTS5_NOT && pSub->eType==p->eType ){
  200462. int nByte = sizeof(Fts5ExprNode*) * pSub->nChild;
  200463. memcpy(&p->apChild[p->nChild], pSub->apChild, nByte);
  200464. p->nChild += pSub->nChild;
  200465. sqlite3_free(pSub);
  200466. }else{
  200467. p->apChild[p->nChild++] = pSub;
  200468. }
  200469. }
  200470. /*
  200471. ** Allocate and return a new expression object. If anything goes wrong (i.e.
  200472. ** OOM error), leave an error code in pParse and return NULL.
  200473. */
  200474. static Fts5ExprNode *sqlite3Fts5ParseNode(
  200475. Fts5Parse *pParse, /* Parse context */
  200476. int eType, /* FTS5_STRING, AND, OR or NOT */
  200477. Fts5ExprNode *pLeft, /* Left hand child expression */
  200478. Fts5ExprNode *pRight, /* Right hand child expression */
  200479. Fts5ExprNearset *pNear /* For STRING expressions, the near cluster */
  200480. ){
  200481. Fts5ExprNode *pRet = 0;
  200482. if( pParse->rc==SQLITE_OK ){
  200483. int nChild = 0; /* Number of children of returned node */
  200484. sqlite3_int64 nByte; /* Bytes of space to allocate for this node */
  200485. assert( (eType!=FTS5_STRING && !pNear)
  200486. || (eType==FTS5_STRING && !pLeft && !pRight)
  200487. );
  200488. if( eType==FTS5_STRING && pNear==0 ) return 0;
  200489. if( eType!=FTS5_STRING && pLeft==0 ) return pRight;
  200490. if( eType!=FTS5_STRING && pRight==0 ) return pLeft;
  200491. if( eType==FTS5_NOT ){
  200492. nChild = 2;
  200493. }else if( eType==FTS5_AND || eType==FTS5_OR ){
  200494. nChild = 2;
  200495. if( pLeft->eType==eType ) nChild += pLeft->nChild-1;
  200496. if( pRight->eType==eType ) nChild += pRight->nChild-1;
  200497. }
  200498. nByte = sizeof(Fts5ExprNode) + sizeof(Fts5ExprNode*)*(nChild-1);
  200499. pRet = (Fts5ExprNode*)sqlite3Fts5MallocZero(&pParse->rc, nByte);
  200500. if( pRet ){
  200501. pRet->eType = eType;
  200502. pRet->pNear = pNear;
  200503. fts5ExprAssignXNext(pRet);
  200504. if( eType==FTS5_STRING ){
  200505. int iPhrase;
  200506. for(iPhrase=0; iPhrase<pNear->nPhrase; iPhrase++){
  200507. pNear->apPhrase[iPhrase]->pNode = pRet;
  200508. if( pNear->apPhrase[iPhrase]->nTerm==0 ){
  200509. pRet->xNext = 0;
  200510. pRet->eType = FTS5_EOF;
  200511. }
  200512. }
  200513. if( pParse->pConfig->eDetail!=FTS5_DETAIL_FULL ){
  200514. Fts5ExprPhrase *pPhrase = pNear->apPhrase[0];
  200515. if( pNear->nPhrase!=1
  200516. || pPhrase->nTerm>1
  200517. || (pPhrase->nTerm>0 && pPhrase->aTerm[0].bFirst)
  200518. ){
  200519. assert( pParse->rc==SQLITE_OK );
  200520. pParse->rc = SQLITE_ERROR;
  200521. assert( pParse->zErr==0 );
  200522. pParse->zErr = sqlite3_mprintf(
  200523. "fts5: %s queries are not supported (detail!=full)",
  200524. pNear->nPhrase==1 ? "phrase": "NEAR"
  200525. );
  200526. sqlite3_free(pRet);
  200527. pRet = 0;
  200528. }
  200529. }
  200530. }else{
  200531. fts5ExprAddChildren(pRet, pLeft);
  200532. fts5ExprAddChildren(pRet, pRight);
  200533. }
  200534. }
  200535. }
  200536. if( pRet==0 ){
  200537. assert( pParse->rc!=SQLITE_OK );
  200538. sqlite3Fts5ParseNodeFree(pLeft);
  200539. sqlite3Fts5ParseNodeFree(pRight);
  200540. sqlite3Fts5ParseNearsetFree(pNear);
  200541. }
  200542. return pRet;
  200543. }
  200544. static Fts5ExprNode *sqlite3Fts5ParseImplicitAnd(
  200545. Fts5Parse *pParse, /* Parse context */
  200546. Fts5ExprNode *pLeft, /* Left hand child expression */
  200547. Fts5ExprNode *pRight /* Right hand child expression */
  200548. ){
  200549. Fts5ExprNode *pRet = 0;
  200550. Fts5ExprNode *pPrev;
  200551. if( pParse->rc ){
  200552. sqlite3Fts5ParseNodeFree(pLeft);
  200553. sqlite3Fts5ParseNodeFree(pRight);
  200554. }else{
  200555. assert( pLeft->eType==FTS5_STRING
  200556. || pLeft->eType==FTS5_TERM
  200557. || pLeft->eType==FTS5_EOF
  200558. || pLeft->eType==FTS5_AND
  200559. );
  200560. assert( pRight->eType==FTS5_STRING
  200561. || pRight->eType==FTS5_TERM
  200562. || pRight->eType==FTS5_EOF
  200563. );
  200564. if( pLeft->eType==FTS5_AND ){
  200565. pPrev = pLeft->apChild[pLeft->nChild-1];
  200566. }else{
  200567. pPrev = pLeft;
  200568. }
  200569. assert( pPrev->eType==FTS5_STRING
  200570. || pPrev->eType==FTS5_TERM
  200571. || pPrev->eType==FTS5_EOF
  200572. );
  200573. if( pRight->eType==FTS5_EOF ){
  200574. assert( pParse->apPhrase[pParse->nPhrase-1]==pRight->pNear->apPhrase[0] );
  200575. sqlite3Fts5ParseNodeFree(pRight);
  200576. pRet = pLeft;
  200577. pParse->nPhrase--;
  200578. }
  200579. else if( pPrev->eType==FTS5_EOF ){
  200580. Fts5ExprPhrase **ap;
  200581. if( pPrev==pLeft ){
  200582. pRet = pRight;
  200583. }else{
  200584. pLeft->apChild[pLeft->nChild-1] = pRight;
  200585. pRet = pLeft;
  200586. }
  200587. ap = &pParse->apPhrase[pParse->nPhrase-1-pRight->pNear->nPhrase];
  200588. assert( ap[0]==pPrev->pNear->apPhrase[0] );
  200589. memmove(ap, &ap[1], sizeof(Fts5ExprPhrase*)*pRight->pNear->nPhrase);
  200590. pParse->nPhrase--;
  200591. sqlite3Fts5ParseNodeFree(pPrev);
  200592. }
  200593. else{
  200594. pRet = sqlite3Fts5ParseNode(pParse, FTS5_AND, pLeft, pRight, 0);
  200595. }
  200596. }
  200597. return pRet;
  200598. }
  200599. static char *fts5ExprTermPrint(Fts5ExprTerm *pTerm){
  200600. sqlite3_int64 nByte = 0;
  200601. Fts5ExprTerm *p;
  200602. char *zQuoted;
  200603. /* Determine the maximum amount of space required. */
  200604. for(p=pTerm; p; p=p->pSynonym){
  200605. nByte += (int)strlen(pTerm->zTerm) * 2 + 3 + 2;
  200606. }
  200607. zQuoted = sqlite3_malloc64(nByte);
  200608. if( zQuoted ){
  200609. int i = 0;
  200610. for(p=pTerm; p; p=p->pSynonym){
  200611. char *zIn = p->zTerm;
  200612. zQuoted[i++] = '"';
  200613. while( *zIn ){
  200614. if( *zIn=='"' ) zQuoted[i++] = '"';
  200615. zQuoted[i++] = *zIn++;
  200616. }
  200617. zQuoted[i++] = '"';
  200618. if( p->pSynonym ) zQuoted[i++] = '|';
  200619. }
  200620. if( pTerm->bPrefix ){
  200621. zQuoted[i++] = ' ';
  200622. zQuoted[i++] = '*';
  200623. }
  200624. zQuoted[i++] = '\0';
  200625. }
  200626. return zQuoted;
  200627. }
  200628. static char *fts5PrintfAppend(char *zApp, const char *zFmt, ...){
  200629. char *zNew;
  200630. va_list ap;
  200631. va_start(ap, zFmt);
  200632. zNew = sqlite3_vmprintf(zFmt, ap);
  200633. va_end(ap);
  200634. if( zApp && zNew ){
  200635. char *zNew2 = sqlite3_mprintf("%s%s", zApp, zNew);
  200636. sqlite3_free(zNew);
  200637. zNew = zNew2;
  200638. }
  200639. sqlite3_free(zApp);
  200640. return zNew;
  200641. }
  200642. /*
  200643. ** Compose a tcl-readable representation of expression pExpr. Return a
  200644. ** pointer to a buffer containing that representation. It is the
  200645. ** responsibility of the caller to at some point free the buffer using
  200646. ** sqlite3_free().
  200647. */
  200648. static char *fts5ExprPrintTcl(
  200649. Fts5Config *pConfig,
  200650. const char *zNearsetCmd,
  200651. Fts5ExprNode *pExpr
  200652. ){
  200653. char *zRet = 0;
  200654. if( pExpr->eType==FTS5_STRING || pExpr->eType==FTS5_TERM ){
  200655. Fts5ExprNearset *pNear = pExpr->pNear;
  200656. int i;
  200657. int iTerm;
  200658. zRet = fts5PrintfAppend(zRet, "%s ", zNearsetCmd);
  200659. if( zRet==0 ) return 0;
  200660. if( pNear->pColset ){
  200661. int *aiCol = pNear->pColset->aiCol;
  200662. int nCol = pNear->pColset->nCol;
  200663. if( nCol==1 ){
  200664. zRet = fts5PrintfAppend(zRet, "-col %d ", aiCol[0]);
  200665. }else{
  200666. zRet = fts5PrintfAppend(zRet, "-col {%d", aiCol[0]);
  200667. for(i=1; i<pNear->pColset->nCol; i++){
  200668. zRet = fts5PrintfAppend(zRet, " %d", aiCol[i]);
  200669. }
  200670. zRet = fts5PrintfAppend(zRet, "} ");
  200671. }
  200672. if( zRet==0 ) return 0;
  200673. }
  200674. if( pNear->nPhrase>1 ){
  200675. zRet = fts5PrintfAppend(zRet, "-near %d ", pNear->nNear);
  200676. if( zRet==0 ) return 0;
  200677. }
  200678. zRet = fts5PrintfAppend(zRet, "--");
  200679. if( zRet==0 ) return 0;
  200680. for(i=0; i<pNear->nPhrase; i++){
  200681. Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
  200682. zRet = fts5PrintfAppend(zRet, " {");
  200683. for(iTerm=0; zRet && iTerm<pPhrase->nTerm; iTerm++){
  200684. char *zTerm = pPhrase->aTerm[iTerm].zTerm;
  200685. zRet = fts5PrintfAppend(zRet, "%s%s", iTerm==0?"":" ", zTerm);
  200686. if( pPhrase->aTerm[iTerm].bPrefix ){
  200687. zRet = fts5PrintfAppend(zRet, "*");
  200688. }
  200689. }
  200690. if( zRet ) zRet = fts5PrintfAppend(zRet, "}");
  200691. if( zRet==0 ) return 0;
  200692. }
  200693. }else{
  200694. char const *zOp = 0;
  200695. int i;
  200696. switch( pExpr->eType ){
  200697. case FTS5_AND: zOp = "AND"; break;
  200698. case FTS5_NOT: zOp = "NOT"; break;
  200699. default:
  200700. assert( pExpr->eType==FTS5_OR );
  200701. zOp = "OR";
  200702. break;
  200703. }
  200704. zRet = sqlite3_mprintf("%s", zOp);
  200705. for(i=0; zRet && i<pExpr->nChild; i++){
  200706. char *z = fts5ExprPrintTcl(pConfig, zNearsetCmd, pExpr->apChild[i]);
  200707. if( !z ){
  200708. sqlite3_free(zRet);
  200709. zRet = 0;
  200710. }else{
  200711. zRet = fts5PrintfAppend(zRet, " [%z]", z);
  200712. }
  200713. }
  200714. }
  200715. return zRet;
  200716. }
  200717. static char *fts5ExprPrint(Fts5Config *pConfig, Fts5ExprNode *pExpr){
  200718. char *zRet = 0;
  200719. if( pExpr->eType==0 ){
  200720. return sqlite3_mprintf("\"\"");
  200721. }else
  200722. if( pExpr->eType==FTS5_STRING || pExpr->eType==FTS5_TERM ){
  200723. Fts5ExprNearset *pNear = pExpr->pNear;
  200724. int i;
  200725. int iTerm;
  200726. if( pNear->pColset ){
  200727. int iCol = pNear->pColset->aiCol[0];
  200728. zRet = fts5PrintfAppend(zRet, "%s : ", pConfig->azCol[iCol]);
  200729. if( zRet==0 ) return 0;
  200730. }
  200731. if( pNear->nPhrase>1 ){
  200732. zRet = fts5PrintfAppend(zRet, "NEAR(");
  200733. if( zRet==0 ) return 0;
  200734. }
  200735. for(i=0; i<pNear->nPhrase; i++){
  200736. Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
  200737. if( i!=0 ){
  200738. zRet = fts5PrintfAppend(zRet, " ");
  200739. if( zRet==0 ) return 0;
  200740. }
  200741. for(iTerm=0; iTerm<pPhrase->nTerm; iTerm++){
  200742. char *zTerm = fts5ExprTermPrint(&pPhrase->aTerm[iTerm]);
  200743. if( zTerm ){
  200744. zRet = fts5PrintfAppend(zRet, "%s%s", iTerm==0?"":" + ", zTerm);
  200745. sqlite3_free(zTerm);
  200746. }
  200747. if( zTerm==0 || zRet==0 ){
  200748. sqlite3_free(zRet);
  200749. return 0;
  200750. }
  200751. }
  200752. }
  200753. if( pNear->nPhrase>1 ){
  200754. zRet = fts5PrintfAppend(zRet, ", %d)", pNear->nNear);
  200755. if( zRet==0 ) return 0;
  200756. }
  200757. }else{
  200758. char const *zOp = 0;
  200759. int i;
  200760. switch( pExpr->eType ){
  200761. case FTS5_AND: zOp = " AND "; break;
  200762. case FTS5_NOT: zOp = " NOT "; break;
  200763. default:
  200764. assert( pExpr->eType==FTS5_OR );
  200765. zOp = " OR ";
  200766. break;
  200767. }
  200768. for(i=0; i<pExpr->nChild; i++){
  200769. char *z = fts5ExprPrint(pConfig, pExpr->apChild[i]);
  200770. if( z==0 ){
  200771. sqlite3_free(zRet);
  200772. zRet = 0;
  200773. }else{
  200774. int e = pExpr->apChild[i]->eType;
  200775. int b = (e!=FTS5_STRING && e!=FTS5_TERM && e!=FTS5_EOF);
  200776. zRet = fts5PrintfAppend(zRet, "%s%s%z%s",
  200777. (i==0 ? "" : zOp),
  200778. (b?"(":""), z, (b?")":"")
  200779. );
  200780. }
  200781. if( zRet==0 ) break;
  200782. }
  200783. }
  200784. return zRet;
  200785. }
  200786. /*
  200787. ** The implementation of user-defined scalar functions fts5_expr() (bTcl==0)
  200788. ** and fts5_expr_tcl() (bTcl!=0).
  200789. */
  200790. static void fts5ExprFunction(
  200791. sqlite3_context *pCtx, /* Function call context */
  200792. int nArg, /* Number of args */
  200793. sqlite3_value **apVal, /* Function arguments */
  200794. int bTcl
  200795. ){
  200796. Fts5Global *pGlobal = (Fts5Global*)sqlite3_user_data(pCtx);
  200797. sqlite3 *db = sqlite3_context_db_handle(pCtx);
  200798. const char *zExpr = 0;
  200799. char *zErr = 0;
  200800. Fts5Expr *pExpr = 0;
  200801. int rc;
  200802. int i;
  200803. const char **azConfig; /* Array of arguments for Fts5Config */
  200804. const char *zNearsetCmd = "nearset";
  200805. int nConfig; /* Size of azConfig[] */
  200806. Fts5Config *pConfig = 0;
  200807. int iArg = 1;
  200808. if( nArg<1 ){
  200809. zErr = sqlite3_mprintf("wrong number of arguments to function %s",
  200810. bTcl ? "fts5_expr_tcl" : "fts5_expr"
  200811. );
  200812. sqlite3_result_error(pCtx, zErr, -1);
  200813. sqlite3_free(zErr);
  200814. return;
  200815. }
  200816. if( bTcl && nArg>1 ){
  200817. zNearsetCmd = (const char*)sqlite3_value_text(apVal[1]);
  200818. iArg = 2;
  200819. }
  200820. nConfig = 3 + (nArg-iArg);
  200821. azConfig = (const char**)sqlite3_malloc64(sizeof(char*) * nConfig);
  200822. if( azConfig==0 ){
  200823. sqlite3_result_error_nomem(pCtx);
  200824. return;
  200825. }
  200826. azConfig[0] = 0;
  200827. azConfig[1] = "main";
  200828. azConfig[2] = "tbl";
  200829. for(i=3; iArg<nArg; iArg++){
  200830. const char *z = (const char*)sqlite3_value_text(apVal[iArg]);
  200831. azConfig[i++] = (z ? z : "");
  200832. }
  200833. zExpr = (const char*)sqlite3_value_text(apVal[0]);
  200834. if( zExpr==0 ) zExpr = "";
  200835. rc = sqlite3Fts5ConfigParse(pGlobal, db, nConfig, azConfig, &pConfig, &zErr);
  200836. if( rc==SQLITE_OK ){
  200837. rc = sqlite3Fts5ExprNew(pConfig, pConfig->nCol, zExpr, &pExpr, &zErr);
  200838. }
  200839. if( rc==SQLITE_OK ){
  200840. char *zText;
  200841. if( pExpr->pRoot->xNext==0 ){
  200842. zText = sqlite3_mprintf("");
  200843. }else if( bTcl ){
  200844. zText = fts5ExprPrintTcl(pConfig, zNearsetCmd, pExpr->pRoot);
  200845. }else{
  200846. zText = fts5ExprPrint(pConfig, pExpr->pRoot);
  200847. }
  200848. if( zText==0 ){
  200849. rc = SQLITE_NOMEM;
  200850. }else{
  200851. sqlite3_result_text(pCtx, zText, -1, SQLITE_TRANSIENT);
  200852. sqlite3_free(zText);
  200853. }
  200854. }
  200855. if( rc!=SQLITE_OK ){
  200856. if( zErr ){
  200857. sqlite3_result_error(pCtx, zErr, -1);
  200858. sqlite3_free(zErr);
  200859. }else{
  200860. sqlite3_result_error_code(pCtx, rc);
  200861. }
  200862. }
  200863. sqlite3_free((void *)azConfig);
  200864. sqlite3Fts5ConfigFree(pConfig);
  200865. sqlite3Fts5ExprFree(pExpr);
  200866. }
  200867. static void fts5ExprFunctionHr(
  200868. sqlite3_context *pCtx, /* Function call context */
  200869. int nArg, /* Number of args */
  200870. sqlite3_value **apVal /* Function arguments */
  200871. ){
  200872. fts5ExprFunction(pCtx, nArg, apVal, 0);
  200873. }
  200874. static void fts5ExprFunctionTcl(
  200875. sqlite3_context *pCtx, /* Function call context */
  200876. int nArg, /* Number of args */
  200877. sqlite3_value **apVal /* Function arguments */
  200878. ){
  200879. fts5ExprFunction(pCtx, nArg, apVal, 1);
  200880. }
  200881. /*
  200882. ** The implementation of an SQLite user-defined-function that accepts a
  200883. ** single integer as an argument. If the integer is an alpha-numeric
  200884. ** unicode code point, 1 is returned. Otherwise 0.
  200885. */
  200886. static void fts5ExprIsAlnum(
  200887. sqlite3_context *pCtx, /* Function call context */
  200888. int nArg, /* Number of args */
  200889. sqlite3_value **apVal /* Function arguments */
  200890. ){
  200891. int iCode;
  200892. u8 aArr[32];
  200893. if( nArg!=1 ){
  200894. sqlite3_result_error(pCtx,
  200895. "wrong number of arguments to function fts5_isalnum", -1
  200896. );
  200897. return;
  200898. }
  200899. memset(aArr, 0, sizeof(aArr));
  200900. sqlite3Fts5UnicodeCatParse("L*", aArr);
  200901. sqlite3Fts5UnicodeCatParse("N*", aArr);
  200902. sqlite3Fts5UnicodeCatParse("Co", aArr);
  200903. iCode = sqlite3_value_int(apVal[0]);
  200904. sqlite3_result_int(pCtx, aArr[sqlite3Fts5UnicodeCategory((u32)iCode)]);
  200905. }
  200906. static void fts5ExprFold(
  200907. sqlite3_context *pCtx, /* Function call context */
  200908. int nArg, /* Number of args */
  200909. sqlite3_value **apVal /* Function arguments */
  200910. ){
  200911. if( nArg!=1 && nArg!=2 ){
  200912. sqlite3_result_error(pCtx,
  200913. "wrong number of arguments to function fts5_fold", -1
  200914. );
  200915. }else{
  200916. int iCode;
  200917. int bRemoveDiacritics = 0;
  200918. iCode = sqlite3_value_int(apVal[0]);
  200919. if( nArg==2 ) bRemoveDiacritics = sqlite3_value_int(apVal[1]);
  200920. sqlite3_result_int(pCtx, sqlite3Fts5UnicodeFold(iCode, bRemoveDiacritics));
  200921. }
  200922. }
  200923. /*
  200924. ** This is called during initialization to register the fts5_expr() scalar
  200925. ** UDF with the SQLite handle passed as the only argument.
  200926. */
  200927. static int sqlite3Fts5ExprInit(Fts5Global *pGlobal, sqlite3 *db){
  200928. struct Fts5ExprFunc {
  200929. const char *z;
  200930. void (*x)(sqlite3_context*,int,sqlite3_value**);
  200931. } aFunc[] = {
  200932. { "fts5_expr", fts5ExprFunctionHr },
  200933. { "fts5_expr_tcl", fts5ExprFunctionTcl },
  200934. { "fts5_isalnum", fts5ExprIsAlnum },
  200935. { "fts5_fold", fts5ExprFold },
  200936. };
  200937. int i;
  200938. int rc = SQLITE_OK;
  200939. void *pCtx = (void*)pGlobal;
  200940. for(i=0; rc==SQLITE_OK && i<ArraySize(aFunc); i++){
  200941. struct Fts5ExprFunc *p = &aFunc[i];
  200942. rc = sqlite3_create_function(db, p->z, -1, SQLITE_UTF8, pCtx, p->x, 0, 0);
  200943. }
  200944. /* Avoid warnings indicating that sqlite3Fts5ParserTrace() and
  200945. ** sqlite3Fts5ParserFallback() are unused */
  200946. #ifndef NDEBUG
  200947. (void)sqlite3Fts5ParserTrace;
  200948. #endif
  200949. (void)sqlite3Fts5ParserFallback;
  200950. return rc;
  200951. }
  200952. /*
  200953. ** Return the number of phrases in expression pExpr.
  200954. */
  200955. static int sqlite3Fts5ExprPhraseCount(Fts5Expr *pExpr){
  200956. return (pExpr ? pExpr->nPhrase : 0);
  200957. }
  200958. /*
  200959. ** Return the number of terms in the iPhrase'th phrase in pExpr.
  200960. */
  200961. static int sqlite3Fts5ExprPhraseSize(Fts5Expr *pExpr, int iPhrase){
  200962. if( iPhrase<0 || iPhrase>=pExpr->nPhrase ) return 0;
  200963. return pExpr->apExprPhrase[iPhrase]->nTerm;
  200964. }
  200965. /*
  200966. ** This function is used to access the current position list for phrase
  200967. ** iPhrase.
  200968. */
  200969. static int sqlite3Fts5ExprPoslist(Fts5Expr *pExpr, int iPhrase, const u8 **pa){
  200970. int nRet;
  200971. Fts5ExprPhrase *pPhrase = pExpr->apExprPhrase[iPhrase];
  200972. Fts5ExprNode *pNode = pPhrase->pNode;
  200973. if( pNode->bEof==0 && pNode->iRowid==pExpr->pRoot->iRowid ){
  200974. *pa = pPhrase->poslist.p;
  200975. nRet = pPhrase->poslist.n;
  200976. }else{
  200977. *pa = 0;
  200978. nRet = 0;
  200979. }
  200980. return nRet;
  200981. }
  200982. struct Fts5PoslistPopulator {
  200983. Fts5PoslistWriter writer;
  200984. int bOk; /* True if ok to populate */
  200985. int bMiss;
  200986. };
  200987. static Fts5PoslistPopulator *sqlite3Fts5ExprClearPoslists(Fts5Expr *pExpr, int bLive){
  200988. Fts5PoslistPopulator *pRet;
  200989. pRet = sqlite3_malloc64(sizeof(Fts5PoslistPopulator)*pExpr->nPhrase);
  200990. if( pRet ){
  200991. int i;
  200992. memset(pRet, 0, sizeof(Fts5PoslistPopulator)*pExpr->nPhrase);
  200993. for(i=0; i<pExpr->nPhrase; i++){
  200994. Fts5Buffer *pBuf = &pExpr->apExprPhrase[i]->poslist;
  200995. Fts5ExprNode *pNode = pExpr->apExprPhrase[i]->pNode;
  200996. assert( pExpr->apExprPhrase[i]->nTerm==1 );
  200997. if( bLive &&
  200998. (pBuf->n==0 || pNode->iRowid!=pExpr->pRoot->iRowid || pNode->bEof)
  200999. ){
  201000. pRet[i].bMiss = 1;
  201001. }else{
  201002. pBuf->n = 0;
  201003. }
  201004. }
  201005. }
  201006. return pRet;
  201007. }
  201008. struct Fts5ExprCtx {
  201009. Fts5Expr *pExpr;
  201010. Fts5PoslistPopulator *aPopulator;
  201011. i64 iOff;
  201012. };
  201013. typedef struct Fts5ExprCtx Fts5ExprCtx;
  201014. /*
  201015. ** TODO: Make this more efficient!
  201016. */
  201017. static int fts5ExprColsetTest(Fts5Colset *pColset, int iCol){
  201018. int i;
  201019. for(i=0; i<pColset->nCol; i++){
  201020. if( pColset->aiCol[i]==iCol ) return 1;
  201021. }
  201022. return 0;
  201023. }
  201024. static int fts5ExprPopulatePoslistsCb(
  201025. void *pCtx, /* Copy of 2nd argument to xTokenize() */
  201026. int tflags, /* Mask of FTS5_TOKEN_* flags */
  201027. const char *pToken, /* Pointer to buffer containing token */
  201028. int nToken, /* Size of token in bytes */
  201029. int iUnused1, /* Byte offset of token within input text */
  201030. int iUnused2 /* Byte offset of end of token within input text */
  201031. ){
  201032. Fts5ExprCtx *p = (Fts5ExprCtx*)pCtx;
  201033. Fts5Expr *pExpr = p->pExpr;
  201034. int i;
  201035. UNUSED_PARAM2(iUnused1, iUnused2);
  201036. if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;
  201037. if( (tflags & FTS5_TOKEN_COLOCATED)==0 ) p->iOff++;
  201038. for(i=0; i<pExpr->nPhrase; i++){
  201039. Fts5ExprTerm *pTerm;
  201040. if( p->aPopulator[i].bOk==0 ) continue;
  201041. for(pTerm=&pExpr->apExprPhrase[i]->aTerm[0]; pTerm; pTerm=pTerm->pSynonym){
  201042. int nTerm = (int)strlen(pTerm->zTerm);
  201043. if( (nTerm==nToken || (nTerm<nToken && pTerm->bPrefix))
  201044. && memcmp(pTerm->zTerm, pToken, nTerm)==0
  201045. ){
  201046. int rc = sqlite3Fts5PoslistWriterAppend(
  201047. &pExpr->apExprPhrase[i]->poslist, &p->aPopulator[i].writer, p->iOff
  201048. );
  201049. if( rc ) return rc;
  201050. break;
  201051. }
  201052. }
  201053. }
  201054. return SQLITE_OK;
  201055. }
  201056. static int sqlite3Fts5ExprPopulatePoslists(
  201057. Fts5Config *pConfig,
  201058. Fts5Expr *pExpr,
  201059. Fts5PoslistPopulator *aPopulator,
  201060. int iCol,
  201061. const char *z, int n
  201062. ){
  201063. int i;
  201064. Fts5ExprCtx sCtx;
  201065. sCtx.pExpr = pExpr;
  201066. sCtx.aPopulator = aPopulator;
  201067. sCtx.iOff = (((i64)iCol) << 32) - 1;
  201068. for(i=0; i<pExpr->nPhrase; i++){
  201069. Fts5ExprNode *pNode = pExpr->apExprPhrase[i]->pNode;
  201070. Fts5Colset *pColset = pNode->pNear->pColset;
  201071. if( (pColset && 0==fts5ExprColsetTest(pColset, iCol))
  201072. || aPopulator[i].bMiss
  201073. ){
  201074. aPopulator[i].bOk = 0;
  201075. }else{
  201076. aPopulator[i].bOk = 1;
  201077. }
  201078. }
  201079. return sqlite3Fts5Tokenize(pConfig,
  201080. FTS5_TOKENIZE_DOCUMENT, z, n, (void*)&sCtx, fts5ExprPopulatePoslistsCb
  201081. );
  201082. }
  201083. static void fts5ExprClearPoslists(Fts5ExprNode *pNode){
  201084. if( pNode->eType==FTS5_TERM || pNode->eType==FTS5_STRING ){
  201085. pNode->pNear->apPhrase[0]->poslist.n = 0;
  201086. }else{
  201087. int i;
  201088. for(i=0; i<pNode->nChild; i++){
  201089. fts5ExprClearPoslists(pNode->apChild[i]);
  201090. }
  201091. }
  201092. }
  201093. static int fts5ExprCheckPoslists(Fts5ExprNode *pNode, i64 iRowid){
  201094. pNode->iRowid = iRowid;
  201095. pNode->bEof = 0;
  201096. switch( pNode->eType ){
  201097. case FTS5_TERM:
  201098. case FTS5_STRING:
  201099. return (pNode->pNear->apPhrase[0]->poslist.n>0);
  201100. case FTS5_AND: {
  201101. int i;
  201102. for(i=0; i<pNode->nChild; i++){
  201103. if( fts5ExprCheckPoslists(pNode->apChild[i], iRowid)==0 ){
  201104. fts5ExprClearPoslists(pNode);
  201105. return 0;
  201106. }
  201107. }
  201108. break;
  201109. }
  201110. case FTS5_OR: {
  201111. int i;
  201112. int bRet = 0;
  201113. for(i=0; i<pNode->nChild; i++){
  201114. if( fts5ExprCheckPoslists(pNode->apChild[i], iRowid) ){
  201115. bRet = 1;
  201116. }
  201117. }
  201118. return bRet;
  201119. }
  201120. default: {
  201121. assert( pNode->eType==FTS5_NOT );
  201122. if( 0==fts5ExprCheckPoslists(pNode->apChild[0], iRowid)
  201123. || 0!=fts5ExprCheckPoslists(pNode->apChild[1], iRowid)
  201124. ){
  201125. fts5ExprClearPoslists(pNode);
  201126. return 0;
  201127. }
  201128. break;
  201129. }
  201130. }
  201131. return 1;
  201132. }
  201133. static void sqlite3Fts5ExprCheckPoslists(Fts5Expr *pExpr, i64 iRowid){
  201134. fts5ExprCheckPoslists(pExpr->pRoot, iRowid);
  201135. }
  201136. /*
  201137. ** This function is only called for detail=columns tables.
  201138. */
  201139. static int sqlite3Fts5ExprPhraseCollist(
  201140. Fts5Expr *pExpr,
  201141. int iPhrase,
  201142. const u8 **ppCollist,
  201143. int *pnCollist
  201144. ){
  201145. Fts5ExprPhrase *pPhrase = pExpr->apExprPhrase[iPhrase];
  201146. Fts5ExprNode *pNode = pPhrase->pNode;
  201147. int rc = SQLITE_OK;
  201148. assert( iPhrase>=0 && iPhrase<pExpr->nPhrase );
  201149. assert( pExpr->pConfig->eDetail==FTS5_DETAIL_COLUMNS );
  201150. if( pNode->bEof==0
  201151. && pNode->iRowid==pExpr->pRoot->iRowid
  201152. && pPhrase->poslist.n>0
  201153. ){
  201154. Fts5ExprTerm *pTerm = &pPhrase->aTerm[0];
  201155. if( pTerm->pSynonym ){
  201156. Fts5Buffer *pBuf = (Fts5Buffer*)&pTerm->pSynonym[1];
  201157. rc = fts5ExprSynonymList(
  201158. pTerm, pNode->iRowid, pBuf, (u8**)ppCollist, pnCollist
  201159. );
  201160. }else{
  201161. *ppCollist = pPhrase->aTerm[0].pIter->pData;
  201162. *pnCollist = pPhrase->aTerm[0].pIter->nData;
  201163. }
  201164. }else{
  201165. *ppCollist = 0;
  201166. *pnCollist = 0;
  201167. }
  201168. return rc;
  201169. }
  201170. /*
  201171. ** 2014 August 11
  201172. **
  201173. ** The author disclaims copyright to this source code. In place of
  201174. ** a legal notice, here is a blessing:
  201175. **
  201176. ** May you do good and not evil.
  201177. ** May you find forgiveness for yourself and forgive others.
  201178. ** May you share freely, never taking more than you give.
  201179. **
  201180. ******************************************************************************
  201181. **
  201182. */
  201183. /* #include "fts5Int.h" */
  201184. typedef struct Fts5HashEntry Fts5HashEntry;
  201185. /*
  201186. ** This file contains the implementation of an in-memory hash table used
  201187. ** to accumuluate "term -> doclist" content before it is flused to a level-0
  201188. ** segment.
  201189. */
  201190. struct Fts5Hash {
  201191. int eDetail; /* Copy of Fts5Config.eDetail */
  201192. int *pnByte; /* Pointer to bytes counter */
  201193. int nEntry; /* Number of entries currently in hash */
  201194. int nSlot; /* Size of aSlot[] array */
  201195. Fts5HashEntry *pScan; /* Current ordered scan item */
  201196. Fts5HashEntry **aSlot; /* Array of hash slots */
  201197. };
  201198. /*
  201199. ** Each entry in the hash table is represented by an object of the
  201200. ** following type. Each object, its key (a nul-terminated string) and
  201201. ** its current data are stored in a single memory allocation. The
  201202. ** key immediately follows the object in memory. The position list
  201203. ** data immediately follows the key data in memory.
  201204. **
  201205. ** The data that follows the key is in a similar, but not identical format
  201206. ** to the doclist data stored in the database. It is:
  201207. **
  201208. ** * Rowid, as a varint
  201209. ** * Position list, without 0x00 terminator.
  201210. ** * Size of previous position list and rowid, as a 4 byte
  201211. ** big-endian integer.
  201212. **
  201213. ** iRowidOff:
  201214. ** Offset of last rowid written to data area. Relative to first byte of
  201215. ** structure.
  201216. **
  201217. ** nData:
  201218. ** Bytes of data written since iRowidOff.
  201219. */
  201220. struct Fts5HashEntry {
  201221. Fts5HashEntry *pHashNext; /* Next hash entry with same hash-key */
  201222. Fts5HashEntry *pScanNext; /* Next entry in sorted order */
  201223. int nAlloc; /* Total size of allocation */
  201224. int iSzPoslist; /* Offset of space for 4-byte poslist size */
  201225. int nData; /* Total bytes of data (incl. structure) */
  201226. int nKey; /* Length of key in bytes */
  201227. u8 bDel; /* Set delete-flag @ iSzPoslist */
  201228. u8 bContent; /* Set content-flag (detail=none mode) */
  201229. i16 iCol; /* Column of last value written */
  201230. int iPos; /* Position of last value written */
  201231. i64 iRowid; /* Rowid of last value written */
  201232. };
  201233. /*
  201234. ** Eqivalent to:
  201235. **
  201236. ** char *fts5EntryKey(Fts5HashEntry *pEntry){ return zKey; }
  201237. */
  201238. #define fts5EntryKey(p) ( ((char *)(&(p)[1])) )
  201239. /*
  201240. ** Allocate a new hash table.
  201241. */
  201242. static int sqlite3Fts5HashNew(Fts5Config *pConfig, Fts5Hash **ppNew, int *pnByte){
  201243. int rc = SQLITE_OK;
  201244. Fts5Hash *pNew;
  201245. *ppNew = pNew = (Fts5Hash*)sqlite3_malloc(sizeof(Fts5Hash));
  201246. if( pNew==0 ){
  201247. rc = SQLITE_NOMEM;
  201248. }else{
  201249. sqlite3_int64 nByte;
  201250. memset(pNew, 0, sizeof(Fts5Hash));
  201251. pNew->pnByte = pnByte;
  201252. pNew->eDetail = pConfig->eDetail;
  201253. pNew->nSlot = 1024;
  201254. nByte = sizeof(Fts5HashEntry*) * pNew->nSlot;
  201255. pNew->aSlot = (Fts5HashEntry**)sqlite3_malloc64(nByte);
  201256. if( pNew->aSlot==0 ){
  201257. sqlite3_free(pNew);
  201258. *ppNew = 0;
  201259. rc = SQLITE_NOMEM;
  201260. }else{
  201261. memset(pNew->aSlot, 0, (size_t)nByte);
  201262. }
  201263. }
  201264. return rc;
  201265. }
  201266. /*
  201267. ** Free a hash table object.
  201268. */
  201269. static void sqlite3Fts5HashFree(Fts5Hash *pHash){
  201270. if( pHash ){
  201271. sqlite3Fts5HashClear(pHash);
  201272. sqlite3_free(pHash->aSlot);
  201273. sqlite3_free(pHash);
  201274. }
  201275. }
  201276. /*
  201277. ** Empty (but do not delete) a hash table.
  201278. */
  201279. static void sqlite3Fts5HashClear(Fts5Hash *pHash){
  201280. int i;
  201281. for(i=0; i<pHash->nSlot; i++){
  201282. Fts5HashEntry *pNext;
  201283. Fts5HashEntry *pSlot;
  201284. for(pSlot=pHash->aSlot[i]; pSlot; pSlot=pNext){
  201285. pNext = pSlot->pHashNext;
  201286. sqlite3_free(pSlot);
  201287. }
  201288. }
  201289. memset(pHash->aSlot, 0, pHash->nSlot * sizeof(Fts5HashEntry*));
  201290. pHash->nEntry = 0;
  201291. }
  201292. static unsigned int fts5HashKey(int nSlot, const u8 *p, int n){
  201293. int i;
  201294. unsigned int h = 13;
  201295. for(i=n-1; i>=0; i--){
  201296. h = (h << 3) ^ h ^ p[i];
  201297. }
  201298. return (h % nSlot);
  201299. }
  201300. static unsigned int fts5HashKey2(int nSlot, u8 b, const u8 *p, int n){
  201301. int i;
  201302. unsigned int h = 13;
  201303. for(i=n-1; i>=0; i--){
  201304. h = (h << 3) ^ h ^ p[i];
  201305. }
  201306. h = (h << 3) ^ h ^ b;
  201307. return (h % nSlot);
  201308. }
  201309. /*
  201310. ** Resize the hash table by doubling the number of slots.
  201311. */
  201312. static int fts5HashResize(Fts5Hash *pHash){
  201313. int nNew = pHash->nSlot*2;
  201314. int i;
  201315. Fts5HashEntry **apNew;
  201316. Fts5HashEntry **apOld = pHash->aSlot;
  201317. apNew = (Fts5HashEntry**)sqlite3_malloc64(nNew*sizeof(Fts5HashEntry*));
  201318. if( !apNew ) return SQLITE_NOMEM;
  201319. memset(apNew, 0, nNew*sizeof(Fts5HashEntry*));
  201320. for(i=0; i<pHash->nSlot; i++){
  201321. while( apOld[i] ){
  201322. unsigned int iHash;
  201323. Fts5HashEntry *p = apOld[i];
  201324. apOld[i] = p->pHashNext;
  201325. iHash = fts5HashKey(nNew, (u8*)fts5EntryKey(p),
  201326. (int)strlen(fts5EntryKey(p)));
  201327. p->pHashNext = apNew[iHash];
  201328. apNew[iHash] = p;
  201329. }
  201330. }
  201331. sqlite3_free(apOld);
  201332. pHash->nSlot = nNew;
  201333. pHash->aSlot = apNew;
  201334. return SQLITE_OK;
  201335. }
  201336. static int fts5HashAddPoslistSize(
  201337. Fts5Hash *pHash,
  201338. Fts5HashEntry *p,
  201339. Fts5HashEntry *p2
  201340. ){
  201341. int nRet = 0;
  201342. if( p->iSzPoslist ){
  201343. u8 *pPtr = p2 ? (u8*)p2 : (u8*)p;
  201344. int nData = p->nData;
  201345. if( pHash->eDetail==FTS5_DETAIL_NONE ){
  201346. assert( nData==p->iSzPoslist );
  201347. if( p->bDel ){
  201348. pPtr[nData++] = 0x00;
  201349. if( p->bContent ){
  201350. pPtr[nData++] = 0x00;
  201351. }
  201352. }
  201353. }else{
  201354. int nSz = (nData - p->iSzPoslist - 1); /* Size in bytes */
  201355. int nPos = nSz*2 + p->bDel; /* Value of nPos field */
  201356. assert( p->bDel==0 || p->bDel==1 );
  201357. if( nPos<=127 ){
  201358. pPtr[p->iSzPoslist] = (u8)nPos;
  201359. }else{
  201360. int nByte = sqlite3Fts5GetVarintLen((u32)nPos);
  201361. memmove(&pPtr[p->iSzPoslist + nByte], &pPtr[p->iSzPoslist + 1], nSz);
  201362. sqlite3Fts5PutVarint(&pPtr[p->iSzPoslist], nPos);
  201363. nData += (nByte-1);
  201364. }
  201365. }
  201366. nRet = nData - p->nData;
  201367. if( p2==0 ){
  201368. p->iSzPoslist = 0;
  201369. p->bDel = 0;
  201370. p->bContent = 0;
  201371. p->nData = nData;
  201372. }
  201373. }
  201374. return nRet;
  201375. }
  201376. /*
  201377. ** Add an entry to the in-memory hash table. The key is the concatenation
  201378. ** of bByte and (pToken/nToken). The value is (iRowid/iCol/iPos).
  201379. **
  201380. ** (bByte || pToken) -> (iRowid,iCol,iPos)
  201381. **
  201382. ** Or, if iCol is negative, then the value is a delete marker.
  201383. */
  201384. static int sqlite3Fts5HashWrite(
  201385. Fts5Hash *pHash,
  201386. i64 iRowid, /* Rowid for this entry */
  201387. int iCol, /* Column token appears in (-ve -> delete) */
  201388. int iPos, /* Position of token within column */
  201389. char bByte, /* First byte of token */
  201390. const char *pToken, int nToken /* Token to add or remove to or from index */
  201391. ){
  201392. unsigned int iHash;
  201393. Fts5HashEntry *p;
  201394. u8 *pPtr;
  201395. int nIncr = 0; /* Amount to increment (*pHash->pnByte) by */
  201396. int bNew; /* If non-delete entry should be written */
  201397. bNew = (pHash->eDetail==FTS5_DETAIL_FULL);
  201398. /* Attempt to locate an existing hash entry */
  201399. iHash = fts5HashKey2(pHash->nSlot, (u8)bByte, (const u8*)pToken, nToken);
  201400. for(p=pHash->aSlot[iHash]; p; p=p->pHashNext){
  201401. char *zKey = fts5EntryKey(p);
  201402. if( zKey[0]==bByte
  201403. && p->nKey==nToken
  201404. && memcmp(&zKey[1], pToken, nToken)==0
  201405. ){
  201406. break;
  201407. }
  201408. }
  201409. /* If an existing hash entry cannot be found, create a new one. */
  201410. if( p==0 ){
  201411. /* Figure out how much space to allocate */
  201412. char *zKey;
  201413. sqlite3_int64 nByte = sizeof(Fts5HashEntry) + (nToken+1) + 1 + 64;
  201414. if( nByte<128 ) nByte = 128;
  201415. /* Grow the Fts5Hash.aSlot[] array if necessary. */
  201416. if( (pHash->nEntry*2)>=pHash->nSlot ){
  201417. int rc = fts5HashResize(pHash);
  201418. if( rc!=SQLITE_OK ) return rc;
  201419. iHash = fts5HashKey2(pHash->nSlot, (u8)bByte, (const u8*)pToken, nToken);
  201420. }
  201421. /* Allocate new Fts5HashEntry and add it to the hash table. */
  201422. p = (Fts5HashEntry*)sqlite3_malloc64(nByte);
  201423. if( !p ) return SQLITE_NOMEM;
  201424. memset(p, 0, sizeof(Fts5HashEntry));
  201425. p->nAlloc = (int)nByte;
  201426. zKey = fts5EntryKey(p);
  201427. zKey[0] = bByte;
  201428. memcpy(&zKey[1], pToken, nToken);
  201429. assert( iHash==fts5HashKey(pHash->nSlot, (u8*)zKey, nToken+1) );
  201430. p->nKey = nToken;
  201431. zKey[nToken+1] = '\0';
  201432. p->nData = nToken+1 + 1 + sizeof(Fts5HashEntry);
  201433. p->pHashNext = pHash->aSlot[iHash];
  201434. pHash->aSlot[iHash] = p;
  201435. pHash->nEntry++;
  201436. /* Add the first rowid field to the hash-entry */
  201437. p->nData += sqlite3Fts5PutVarint(&((u8*)p)[p->nData], iRowid);
  201438. p->iRowid = iRowid;
  201439. p->iSzPoslist = p->nData;
  201440. if( pHash->eDetail!=FTS5_DETAIL_NONE ){
  201441. p->nData += 1;
  201442. p->iCol = (pHash->eDetail==FTS5_DETAIL_FULL ? 0 : -1);
  201443. }
  201444. nIncr += p->nData;
  201445. }else{
  201446. /* Appending to an existing hash-entry. Check that there is enough
  201447. ** space to append the largest possible new entry. Worst case scenario
  201448. ** is:
  201449. **
  201450. ** + 9 bytes for a new rowid,
  201451. ** + 4 byte reserved for the "poslist size" varint.
  201452. ** + 1 byte for a "new column" byte,
  201453. ** + 3 bytes for a new column number (16-bit max) as a varint,
  201454. ** + 5 bytes for the new position offset (32-bit max).
  201455. */
  201456. if( (p->nAlloc - p->nData) < (9 + 4 + 1 + 3 + 5) ){
  201457. sqlite3_int64 nNew = p->nAlloc * 2;
  201458. Fts5HashEntry *pNew;
  201459. Fts5HashEntry **pp;
  201460. pNew = (Fts5HashEntry*)sqlite3_realloc64(p, nNew);
  201461. if( pNew==0 ) return SQLITE_NOMEM;
  201462. pNew->nAlloc = (int)nNew;
  201463. for(pp=&pHash->aSlot[iHash]; *pp!=p; pp=&(*pp)->pHashNext);
  201464. *pp = pNew;
  201465. p = pNew;
  201466. }
  201467. nIncr -= p->nData;
  201468. }
  201469. assert( (p->nAlloc - p->nData) >= (9 + 4 + 1 + 3 + 5) );
  201470. pPtr = (u8*)p;
  201471. /* If this is a new rowid, append the 4-byte size field for the previous
  201472. ** entry, and the new rowid for this entry. */
  201473. if( iRowid!=p->iRowid ){
  201474. fts5HashAddPoslistSize(pHash, p, 0);
  201475. p->nData += sqlite3Fts5PutVarint(&pPtr[p->nData], iRowid - p->iRowid);
  201476. p->iRowid = iRowid;
  201477. bNew = 1;
  201478. p->iSzPoslist = p->nData;
  201479. if( pHash->eDetail!=FTS5_DETAIL_NONE ){
  201480. p->nData += 1;
  201481. p->iCol = (pHash->eDetail==FTS5_DETAIL_FULL ? 0 : -1);
  201482. p->iPos = 0;
  201483. }
  201484. }
  201485. if( iCol>=0 ){
  201486. if( pHash->eDetail==FTS5_DETAIL_NONE ){
  201487. p->bContent = 1;
  201488. }else{
  201489. /* Append a new column value, if necessary */
  201490. assert( iCol>=p->iCol );
  201491. if( iCol!=p->iCol ){
  201492. if( pHash->eDetail==FTS5_DETAIL_FULL ){
  201493. pPtr[p->nData++] = 0x01;
  201494. p->nData += sqlite3Fts5PutVarint(&pPtr[p->nData], iCol);
  201495. p->iCol = (i16)iCol;
  201496. p->iPos = 0;
  201497. }else{
  201498. bNew = 1;
  201499. p->iCol = (i16)(iPos = iCol);
  201500. }
  201501. }
  201502. /* Append the new position offset, if necessary */
  201503. if( bNew ){
  201504. p->nData += sqlite3Fts5PutVarint(&pPtr[p->nData], iPos - p->iPos + 2);
  201505. p->iPos = iPos;
  201506. }
  201507. }
  201508. }else{
  201509. /* This is a delete. Set the delete flag. */
  201510. p->bDel = 1;
  201511. }
  201512. nIncr += p->nData;
  201513. *pHash->pnByte += nIncr;
  201514. return SQLITE_OK;
  201515. }
  201516. /*
  201517. ** Arguments pLeft and pRight point to linked-lists of hash-entry objects,
  201518. ** each sorted in key order. This function merges the two lists into a
  201519. ** single list and returns a pointer to its first element.
  201520. */
  201521. static Fts5HashEntry *fts5HashEntryMerge(
  201522. Fts5HashEntry *pLeft,
  201523. Fts5HashEntry *pRight
  201524. ){
  201525. Fts5HashEntry *p1 = pLeft;
  201526. Fts5HashEntry *p2 = pRight;
  201527. Fts5HashEntry *pRet = 0;
  201528. Fts5HashEntry **ppOut = &pRet;
  201529. while( p1 || p2 ){
  201530. if( p1==0 ){
  201531. *ppOut = p2;
  201532. p2 = 0;
  201533. }else if( p2==0 ){
  201534. *ppOut = p1;
  201535. p1 = 0;
  201536. }else{
  201537. int i = 0;
  201538. char *zKey1 = fts5EntryKey(p1);
  201539. char *zKey2 = fts5EntryKey(p2);
  201540. while( zKey1[i]==zKey2[i] ) i++;
  201541. if( ((u8)zKey1[i])>((u8)zKey2[i]) ){
  201542. /* p2 is smaller */
  201543. *ppOut = p2;
  201544. ppOut = &p2->pScanNext;
  201545. p2 = p2->pScanNext;
  201546. }else{
  201547. /* p1 is smaller */
  201548. *ppOut = p1;
  201549. ppOut = &p1->pScanNext;
  201550. p1 = p1->pScanNext;
  201551. }
  201552. *ppOut = 0;
  201553. }
  201554. }
  201555. return pRet;
  201556. }
  201557. /*
  201558. ** Extract all tokens from hash table iHash and link them into a list
  201559. ** in sorted order. The hash table is cleared before returning. It is
  201560. ** the responsibility of the caller to free the elements of the returned
  201561. ** list.
  201562. */
  201563. static int fts5HashEntrySort(
  201564. Fts5Hash *pHash,
  201565. const char *pTerm, int nTerm, /* Query prefix, if any */
  201566. Fts5HashEntry **ppSorted
  201567. ){
  201568. const int nMergeSlot = 32;
  201569. Fts5HashEntry **ap;
  201570. Fts5HashEntry *pList;
  201571. int iSlot;
  201572. int i;
  201573. *ppSorted = 0;
  201574. ap = sqlite3_malloc64(sizeof(Fts5HashEntry*) * nMergeSlot);
  201575. if( !ap ) return SQLITE_NOMEM;
  201576. memset(ap, 0, sizeof(Fts5HashEntry*) * nMergeSlot);
  201577. for(iSlot=0; iSlot<pHash->nSlot; iSlot++){
  201578. Fts5HashEntry *pIter;
  201579. for(pIter=pHash->aSlot[iSlot]; pIter; pIter=pIter->pHashNext){
  201580. if( pTerm==0
  201581. || (pIter->nKey+1>=nTerm && 0==memcmp(fts5EntryKey(pIter), pTerm, nTerm))
  201582. ){
  201583. Fts5HashEntry *pEntry = pIter;
  201584. pEntry->pScanNext = 0;
  201585. for(i=0; ap[i]; i++){
  201586. pEntry = fts5HashEntryMerge(pEntry, ap[i]);
  201587. ap[i] = 0;
  201588. }
  201589. ap[i] = pEntry;
  201590. }
  201591. }
  201592. }
  201593. pList = 0;
  201594. for(i=0; i<nMergeSlot; i++){
  201595. pList = fts5HashEntryMerge(pList, ap[i]);
  201596. }
  201597. pHash->nEntry = 0;
  201598. sqlite3_free(ap);
  201599. *ppSorted = pList;
  201600. return SQLITE_OK;
  201601. }
  201602. /*
  201603. ** Query the hash table for a doclist associated with term pTerm/nTerm.
  201604. */
  201605. static int sqlite3Fts5HashQuery(
  201606. Fts5Hash *pHash, /* Hash table to query */
  201607. int nPre,
  201608. const char *pTerm, int nTerm, /* Query term */
  201609. void **ppOut, /* OUT: Pointer to new object */
  201610. int *pnDoclist /* OUT: Size of doclist in bytes */
  201611. ){
  201612. unsigned int iHash = fts5HashKey(pHash->nSlot, (const u8*)pTerm, nTerm);
  201613. char *zKey = 0;
  201614. Fts5HashEntry *p;
  201615. for(p=pHash->aSlot[iHash]; p; p=p->pHashNext){
  201616. zKey = fts5EntryKey(p);
  201617. assert( p->nKey+1==(int)strlen(zKey) );
  201618. if( nTerm==p->nKey+1 && memcmp(zKey, pTerm, nTerm)==0 ) break;
  201619. }
  201620. if( p ){
  201621. int nHashPre = sizeof(Fts5HashEntry) + nTerm + 1;
  201622. int nList = p->nData - nHashPre;
  201623. u8 *pRet = (u8*)(*ppOut = sqlite3_malloc64(nPre + nList + 10));
  201624. if( pRet ){
  201625. Fts5HashEntry *pFaux = (Fts5HashEntry*)&pRet[nPre-nHashPre];
  201626. memcpy(&pRet[nPre], &((u8*)p)[nHashPre], nList);
  201627. nList += fts5HashAddPoslistSize(pHash, p, pFaux);
  201628. *pnDoclist = nList;
  201629. }else{
  201630. *pnDoclist = 0;
  201631. return SQLITE_NOMEM;
  201632. }
  201633. }else{
  201634. *ppOut = 0;
  201635. *pnDoclist = 0;
  201636. }
  201637. return SQLITE_OK;
  201638. }
  201639. static int sqlite3Fts5HashScanInit(
  201640. Fts5Hash *p, /* Hash table to query */
  201641. const char *pTerm, int nTerm /* Query prefix */
  201642. ){
  201643. return fts5HashEntrySort(p, pTerm, nTerm, &p->pScan);
  201644. }
  201645. static void sqlite3Fts5HashScanNext(Fts5Hash *p){
  201646. assert( !sqlite3Fts5HashScanEof(p) );
  201647. p->pScan = p->pScan->pScanNext;
  201648. }
  201649. static int sqlite3Fts5HashScanEof(Fts5Hash *p){
  201650. return (p->pScan==0);
  201651. }
  201652. static void sqlite3Fts5HashScanEntry(
  201653. Fts5Hash *pHash,
  201654. const char **pzTerm, /* OUT: term (nul-terminated) */
  201655. const u8 **ppDoclist, /* OUT: pointer to doclist */
  201656. int *pnDoclist /* OUT: size of doclist in bytes */
  201657. ){
  201658. Fts5HashEntry *p;
  201659. if( (p = pHash->pScan) ){
  201660. char *zKey = fts5EntryKey(p);
  201661. int nTerm = (int)strlen(zKey);
  201662. fts5HashAddPoslistSize(pHash, p, 0);
  201663. *pzTerm = zKey;
  201664. *ppDoclist = (const u8*)&zKey[nTerm+1];
  201665. *pnDoclist = p->nData - (sizeof(Fts5HashEntry) + nTerm + 1);
  201666. }else{
  201667. *pzTerm = 0;
  201668. *ppDoclist = 0;
  201669. *pnDoclist = 0;
  201670. }
  201671. }
  201672. /*
  201673. ** 2014 May 31
  201674. **
  201675. ** The author disclaims copyright to this source code. In place of
  201676. ** a legal notice, here is a blessing:
  201677. **
  201678. ** May you do good and not evil.
  201679. ** May you find forgiveness for yourself and forgive others.
  201680. ** May you share freely, never taking more than you give.
  201681. **
  201682. ******************************************************************************
  201683. **
  201684. ** Low level access to the FTS index stored in the database file. The
  201685. ** routines in this file file implement all read and write access to the
  201686. ** %_data table. Other parts of the system access this functionality via
  201687. ** the interface defined in fts5Int.h.
  201688. */
  201689. /* #include "fts5Int.h" */
  201690. /*
  201691. ** Overview:
  201692. **
  201693. ** The %_data table contains all the FTS indexes for an FTS5 virtual table.
  201694. ** As well as the main term index, there may be up to 31 prefix indexes.
  201695. ** The format is similar to FTS3/4, except that:
  201696. **
  201697. ** * all segment b-tree leaf data is stored in fixed size page records
  201698. ** (e.g. 1000 bytes). A single doclist may span multiple pages. Care is
  201699. ** taken to ensure it is possible to iterate in either direction through
  201700. ** the entries in a doclist, or to seek to a specific entry within a
  201701. ** doclist, without loading it into memory.
  201702. **
  201703. ** * large doclists that span many pages have associated "doclist index"
  201704. ** records that contain a copy of the first rowid on each page spanned by
  201705. ** the doclist. This is used to speed up seek operations, and merges of
  201706. ** large doclists with very small doclists.
  201707. **
  201708. ** * extra fields in the "structure record" record the state of ongoing
  201709. ** incremental merge operations.
  201710. **
  201711. */
  201712. #define FTS5_OPT_WORK_UNIT 1000 /* Number of leaf pages per optimize step */
  201713. #define FTS5_WORK_UNIT 64 /* Number of leaf pages in unit of work */
  201714. #define FTS5_MIN_DLIDX_SIZE 4 /* Add dlidx if this many empty pages */
  201715. #define FTS5_MAIN_PREFIX '0'
  201716. #if FTS5_MAX_PREFIX_INDEXES > 31
  201717. # error "FTS5_MAX_PREFIX_INDEXES is too large"
  201718. #endif
  201719. /*
  201720. ** Details:
  201721. **
  201722. ** The %_data table managed by this module,
  201723. **
  201724. ** CREATE TABLE %_data(id INTEGER PRIMARY KEY, block BLOB);
  201725. **
  201726. ** , contains the following 5 types of records. See the comments surrounding
  201727. ** the FTS5_*_ROWID macros below for a description of how %_data rowids are
  201728. ** assigned to each fo them.
  201729. **
  201730. ** 1. Structure Records:
  201731. **
  201732. ** The set of segments that make up an index - the index structure - are
  201733. ** recorded in a single record within the %_data table. The record consists
  201734. ** of a single 32-bit configuration cookie value followed by a list of
  201735. ** SQLite varints. If the FTS table features more than one index (because
  201736. ** there are one or more prefix indexes), it is guaranteed that all share
  201737. ** the same cookie value.
  201738. **
  201739. ** Immediately following the configuration cookie, the record begins with
  201740. ** three varints:
  201741. **
  201742. ** + number of levels,
  201743. ** + total number of segments on all levels,
  201744. ** + value of write counter.
  201745. **
  201746. ** Then, for each level from 0 to nMax:
  201747. **
  201748. ** + number of input segments in ongoing merge.
  201749. ** + total number of segments in level.
  201750. ** + for each segment from oldest to newest:
  201751. ** + segment id (always > 0)
  201752. ** + first leaf page number (often 1, always greater than 0)
  201753. ** + final leaf page number
  201754. **
  201755. ** 2. The Averages Record:
  201756. **
  201757. ** A single record within the %_data table. The data is a list of varints.
  201758. ** The first value is the number of rows in the index. Then, for each column
  201759. ** from left to right, the total number of tokens in the column for all
  201760. ** rows of the table.
  201761. **
  201762. ** 3. Segment leaves:
  201763. **
  201764. ** TERM/DOCLIST FORMAT:
  201765. **
  201766. ** Most of each segment leaf is taken up by term/doclist data. The
  201767. ** general format of term/doclist, starting with the first term
  201768. ** on the leaf page, is:
  201769. **
  201770. ** varint : size of first term
  201771. ** blob: first term data
  201772. ** doclist: first doclist
  201773. ** zero-or-more {
  201774. ** varint: number of bytes in common with previous term
  201775. ** varint: number of bytes of new term data (nNew)
  201776. ** blob: nNew bytes of new term data
  201777. ** doclist: next doclist
  201778. ** }
  201779. **
  201780. ** doclist format:
  201781. **
  201782. ** varint: first rowid
  201783. ** poslist: first poslist
  201784. ** zero-or-more {
  201785. ** varint: rowid delta (always > 0)
  201786. ** poslist: next poslist
  201787. ** }
  201788. **
  201789. ** poslist format:
  201790. **
  201791. ** varint: size of poslist in bytes multiplied by 2, not including
  201792. ** this field. Plus 1 if this entry carries the "delete" flag.
  201793. ** collist: collist for column 0
  201794. ** zero-or-more {
  201795. ** 0x01 byte
  201796. ** varint: column number (I)
  201797. ** collist: collist for column I
  201798. ** }
  201799. **
  201800. ** collist format:
  201801. **
  201802. ** varint: first offset + 2
  201803. ** zero-or-more {
  201804. ** varint: offset delta + 2
  201805. ** }
  201806. **
  201807. ** PAGE FORMAT
  201808. **
  201809. ** Each leaf page begins with a 4-byte header containing 2 16-bit
  201810. ** unsigned integer fields in big-endian format. They are:
  201811. **
  201812. ** * The byte offset of the first rowid on the page, if it exists
  201813. ** and occurs before the first term (otherwise 0).
  201814. **
  201815. ** * The byte offset of the start of the page footer. If the page
  201816. ** footer is 0 bytes in size, then this field is the same as the
  201817. ** size of the leaf page in bytes.
  201818. **
  201819. ** The page footer consists of a single varint for each term located
  201820. ** on the page. Each varint is the byte offset of the current term
  201821. ** within the page, delta-compressed against the previous value. In
  201822. ** other words, the first varint in the footer is the byte offset of
  201823. ** the first term, the second is the byte offset of the second less that
  201824. ** of the first, and so on.
  201825. **
  201826. ** The term/doclist format described above is accurate if the entire
  201827. ** term/doclist data fits on a single leaf page. If this is not the case,
  201828. ** the format is changed in two ways:
  201829. **
  201830. ** + if the first rowid on a page occurs before the first term, it
  201831. ** is stored as a literal value:
  201832. **
  201833. ** varint: first rowid
  201834. **
  201835. ** + the first term on each page is stored in the same way as the
  201836. ** very first term of the segment:
  201837. **
  201838. ** varint : size of first term
  201839. ** blob: first term data
  201840. **
  201841. ** 5. Segment doclist indexes:
  201842. **
  201843. ** Doclist indexes are themselves b-trees, however they usually consist of
  201844. ** a single leaf record only. The format of each doclist index leaf page
  201845. ** is:
  201846. **
  201847. ** * Flags byte. Bits are:
  201848. ** 0x01: Clear if leaf is also the root page, otherwise set.
  201849. **
  201850. ** * Page number of fts index leaf page. As a varint.
  201851. **
  201852. ** * First rowid on page indicated by previous field. As a varint.
  201853. **
  201854. ** * A list of varints, one for each subsequent termless page. A
  201855. ** positive delta if the termless page contains at least one rowid,
  201856. ** or an 0x00 byte otherwise.
  201857. **
  201858. ** Internal doclist index nodes are:
  201859. **
  201860. ** * Flags byte. Bits are:
  201861. ** 0x01: Clear for root page, otherwise set.
  201862. **
  201863. ** * Page number of first child page. As a varint.
  201864. **
  201865. ** * Copy of first rowid on page indicated by previous field. As a varint.
  201866. **
  201867. ** * A list of delta-encoded varints - the first rowid on each subsequent
  201868. ** child page.
  201869. **
  201870. */
  201871. /*
  201872. ** Rowids for the averages and structure records in the %_data table.
  201873. */
  201874. #define FTS5_AVERAGES_ROWID 1 /* Rowid used for the averages record */
  201875. #define FTS5_STRUCTURE_ROWID 10 /* The structure record */
  201876. /*
  201877. ** Macros determining the rowids used by segment leaves and dlidx leaves
  201878. ** and nodes. All nodes and leaves are stored in the %_data table with large
  201879. ** positive rowids.
  201880. **
  201881. ** Each segment has a unique non-zero 16-bit id.
  201882. **
  201883. ** The rowid for each segment leaf is found by passing the segment id and
  201884. ** the leaf page number to the FTS5_SEGMENT_ROWID macro. Leaves are numbered
  201885. ** sequentially starting from 1.
  201886. */
  201887. #define FTS5_DATA_ID_B 16 /* Max seg id number 65535 */
  201888. #define FTS5_DATA_DLI_B 1 /* Doclist-index flag (1 bit) */
  201889. #define FTS5_DATA_HEIGHT_B 5 /* Max dlidx tree height of 32 */
  201890. #define FTS5_DATA_PAGE_B 31 /* Max page number of 2147483648 */
  201891. #define fts5_dri(segid, dlidx, height, pgno) ( \
  201892. ((i64)(segid) << (FTS5_DATA_PAGE_B+FTS5_DATA_HEIGHT_B+FTS5_DATA_DLI_B)) + \
  201893. ((i64)(dlidx) << (FTS5_DATA_PAGE_B + FTS5_DATA_HEIGHT_B)) + \
  201894. ((i64)(height) << (FTS5_DATA_PAGE_B)) + \
  201895. ((i64)(pgno)) \
  201896. )
  201897. #define FTS5_SEGMENT_ROWID(segid, pgno) fts5_dri(segid, 0, 0, pgno)
  201898. #define FTS5_DLIDX_ROWID(segid, height, pgno) fts5_dri(segid, 1, height, pgno)
  201899. #ifdef SQLITE_DEBUG
  201900. static int sqlite3Fts5Corrupt() { return SQLITE_CORRUPT_VTAB; }
  201901. #endif
  201902. /*
  201903. ** Each time a blob is read from the %_data table, it is padded with this
  201904. ** many zero bytes. This makes it easier to decode the various record formats
  201905. ** without overreading if the records are corrupt.
  201906. */
  201907. #define FTS5_DATA_ZERO_PADDING 8
  201908. #define FTS5_DATA_PADDING 20
  201909. typedef struct Fts5Data Fts5Data;
  201910. typedef struct Fts5DlidxIter Fts5DlidxIter;
  201911. typedef struct Fts5DlidxLvl Fts5DlidxLvl;
  201912. typedef struct Fts5DlidxWriter Fts5DlidxWriter;
  201913. typedef struct Fts5Iter Fts5Iter;
  201914. typedef struct Fts5PageWriter Fts5PageWriter;
  201915. typedef struct Fts5SegIter Fts5SegIter;
  201916. typedef struct Fts5DoclistIter Fts5DoclistIter;
  201917. typedef struct Fts5SegWriter Fts5SegWriter;
  201918. typedef struct Fts5Structure Fts5Structure;
  201919. typedef struct Fts5StructureLevel Fts5StructureLevel;
  201920. typedef struct Fts5StructureSegment Fts5StructureSegment;
  201921. struct Fts5Data {
  201922. u8 *p; /* Pointer to buffer containing record */
  201923. int nn; /* Size of record in bytes */
  201924. int szLeaf; /* Size of leaf without page-index */
  201925. };
  201926. /*
  201927. ** One object per %_data table.
  201928. */
  201929. struct Fts5Index {
  201930. Fts5Config *pConfig; /* Virtual table configuration */
  201931. char *zDataTbl; /* Name of %_data table */
  201932. int nWorkUnit; /* Leaf pages in a "unit" of work */
  201933. /*
  201934. ** Variables related to the accumulation of tokens and doclists within the
  201935. ** in-memory hash tables before they are flushed to disk.
  201936. */
  201937. Fts5Hash *pHash; /* Hash table for in-memory data */
  201938. int nPendingData; /* Current bytes of pending data */
  201939. i64 iWriteRowid; /* Rowid for current doc being written */
  201940. int bDelete; /* Current write is a delete */
  201941. /* Error state. */
  201942. int rc; /* Current error code */
  201943. /* State used by the fts5DataXXX() functions. */
  201944. sqlite3_blob *pReader; /* RO incr-blob open on %_data table */
  201945. sqlite3_stmt *pWriter; /* "INSERT ... %_data VALUES(?,?)" */
  201946. sqlite3_stmt *pDeleter; /* "DELETE FROM %_data ... id>=? AND id<=?" */
  201947. sqlite3_stmt *pIdxWriter; /* "INSERT ... %_idx VALUES(?,?,?,?)" */
  201948. sqlite3_stmt *pIdxDeleter; /* "DELETE FROM %_idx WHERE segid=? */
  201949. sqlite3_stmt *pIdxSelect;
  201950. int nRead; /* Total number of blocks read */
  201951. sqlite3_stmt *pDataVersion;
  201952. i64 iStructVersion; /* data_version when pStruct read */
  201953. Fts5Structure *pStruct; /* Current db structure (or NULL) */
  201954. };
  201955. struct Fts5DoclistIter {
  201956. u8 *aEof; /* Pointer to 1 byte past end of doclist */
  201957. /* Output variables. aPoslist==0 at EOF */
  201958. i64 iRowid;
  201959. u8 *aPoslist;
  201960. int nPoslist;
  201961. int nSize;
  201962. };
  201963. /*
  201964. ** The contents of the "structure" record for each index are represented
  201965. ** using an Fts5Structure record in memory. Which uses instances of the
  201966. ** other Fts5StructureXXX types as components.
  201967. */
  201968. struct Fts5StructureSegment {
  201969. int iSegid; /* Segment id */
  201970. int pgnoFirst; /* First leaf page number in segment */
  201971. int pgnoLast; /* Last leaf page number in segment */
  201972. };
  201973. struct Fts5StructureLevel {
  201974. int nMerge; /* Number of segments in incr-merge */
  201975. int nSeg; /* Total number of segments on level */
  201976. Fts5StructureSegment *aSeg; /* Array of segments. aSeg[0] is oldest. */
  201977. };
  201978. struct Fts5Structure {
  201979. int nRef; /* Object reference count */
  201980. u64 nWriteCounter; /* Total leaves written to level 0 */
  201981. int nSegment; /* Total segments in this structure */
  201982. int nLevel; /* Number of levels in this index */
  201983. Fts5StructureLevel aLevel[1]; /* Array of nLevel level objects */
  201984. };
  201985. /*
  201986. ** An object of type Fts5SegWriter is used to write to segments.
  201987. */
  201988. struct Fts5PageWriter {
  201989. int pgno; /* Page number for this page */
  201990. int iPrevPgidx; /* Previous value written into pgidx */
  201991. Fts5Buffer buf; /* Buffer containing leaf data */
  201992. Fts5Buffer pgidx; /* Buffer containing page-index */
  201993. Fts5Buffer term; /* Buffer containing previous term on page */
  201994. };
  201995. struct Fts5DlidxWriter {
  201996. int pgno; /* Page number for this page */
  201997. int bPrevValid; /* True if iPrev is valid */
  201998. i64 iPrev; /* Previous rowid value written to page */
  201999. Fts5Buffer buf; /* Buffer containing page data */
  202000. };
  202001. struct Fts5SegWriter {
  202002. int iSegid; /* Segid to write to */
  202003. Fts5PageWriter writer; /* PageWriter object */
  202004. i64 iPrevRowid; /* Previous rowid written to current leaf */
  202005. u8 bFirstRowidInDoclist; /* True if next rowid is first in doclist */
  202006. u8 bFirstRowidInPage; /* True if next rowid is first in page */
  202007. /* TODO1: Can use (writer.pgidx.n==0) instead of bFirstTermInPage */
  202008. u8 bFirstTermInPage; /* True if next term will be first in leaf */
  202009. int nLeafWritten; /* Number of leaf pages written */
  202010. int nEmpty; /* Number of contiguous term-less nodes */
  202011. int nDlidx; /* Allocated size of aDlidx[] array */
  202012. Fts5DlidxWriter *aDlidx; /* Array of Fts5DlidxWriter objects */
  202013. /* Values to insert into the %_idx table */
  202014. Fts5Buffer btterm; /* Next term to insert into %_idx table */
  202015. int iBtPage; /* Page number corresponding to btterm */
  202016. };
  202017. typedef struct Fts5CResult Fts5CResult;
  202018. struct Fts5CResult {
  202019. u16 iFirst; /* aSeg[] index of firstest iterator */
  202020. u8 bTermEq; /* True if the terms are equal */
  202021. };
  202022. /*
  202023. ** Object for iterating through a single segment, visiting each term/rowid
  202024. ** pair in the segment.
  202025. **
  202026. ** pSeg:
  202027. ** The segment to iterate through.
  202028. **
  202029. ** iLeafPgno:
  202030. ** Current leaf page number within segment.
  202031. **
  202032. ** iLeafOffset:
  202033. ** Byte offset within the current leaf that is the first byte of the
  202034. ** position list data (one byte passed the position-list size field).
  202035. ** rowid field of the current entry. Usually this is the size field of the
  202036. ** position list data. The exception is if the rowid for the current entry
  202037. ** is the last thing on the leaf page.
  202038. **
  202039. ** pLeaf:
  202040. ** Buffer containing current leaf page data. Set to NULL at EOF.
  202041. **
  202042. ** iTermLeafPgno, iTermLeafOffset:
  202043. ** Leaf page number containing the last term read from the segment. And
  202044. ** the offset immediately following the term data.
  202045. **
  202046. ** flags:
  202047. ** Mask of FTS5_SEGITER_XXX values. Interpreted as follows:
  202048. **
  202049. ** FTS5_SEGITER_ONETERM:
  202050. ** If set, set the iterator to point to EOF after the current doclist
  202051. ** has been exhausted. Do not proceed to the next term in the segment.
  202052. **
  202053. ** FTS5_SEGITER_REVERSE:
  202054. ** This flag is only ever set if FTS5_SEGITER_ONETERM is also set. If
  202055. ** it is set, iterate through rowid in descending order instead of the
  202056. ** default ascending order.
  202057. **
  202058. ** iRowidOffset/nRowidOffset/aRowidOffset:
  202059. ** These are used if the FTS5_SEGITER_REVERSE flag is set.
  202060. **
  202061. ** For each rowid on the page corresponding to the current term, the
  202062. ** corresponding aRowidOffset[] entry is set to the byte offset of the
  202063. ** start of the "position-list-size" field within the page.
  202064. **
  202065. ** iTermIdx:
  202066. ** Index of current term on iTermLeafPgno.
  202067. */
  202068. struct Fts5SegIter {
  202069. Fts5StructureSegment *pSeg; /* Segment to iterate through */
  202070. int flags; /* Mask of configuration flags */
  202071. int iLeafPgno; /* Current leaf page number */
  202072. Fts5Data *pLeaf; /* Current leaf data */
  202073. Fts5Data *pNextLeaf; /* Leaf page (iLeafPgno+1) */
  202074. int iLeafOffset; /* Byte offset within current leaf */
  202075. /* Next method */
  202076. void (*xNext)(Fts5Index*, Fts5SegIter*, int*);
  202077. /* The page and offset from which the current term was read. The offset
  202078. ** is the offset of the first rowid in the current doclist. */
  202079. int iTermLeafPgno;
  202080. int iTermLeafOffset;
  202081. int iPgidxOff; /* Next offset in pgidx */
  202082. int iEndofDoclist;
  202083. /* The following are only used if the FTS5_SEGITER_REVERSE flag is set. */
  202084. int iRowidOffset; /* Current entry in aRowidOffset[] */
  202085. int nRowidOffset; /* Allocated size of aRowidOffset[] array */
  202086. int *aRowidOffset; /* Array of offset to rowid fields */
  202087. Fts5DlidxIter *pDlidx; /* If there is a doclist-index */
  202088. /* Variables populated based on current entry. */
  202089. Fts5Buffer term; /* Current term */
  202090. i64 iRowid; /* Current rowid */
  202091. int nPos; /* Number of bytes in current position list */
  202092. u8 bDel; /* True if the delete flag is set */
  202093. };
  202094. /*
  202095. ** Argument is a pointer to an Fts5Data structure that contains a
  202096. ** leaf page.
  202097. */
  202098. #define ASSERT_SZLEAF_OK(x) assert( \
  202099. (x)->szLeaf==(x)->nn || (x)->szLeaf==fts5GetU16(&(x)->p[2]) \
  202100. )
  202101. #define FTS5_SEGITER_ONETERM 0x01
  202102. #define FTS5_SEGITER_REVERSE 0x02
  202103. /*
  202104. ** Argument is a pointer to an Fts5Data structure that contains a leaf
  202105. ** page. This macro evaluates to true if the leaf contains no terms, or
  202106. ** false if it contains at least one term.
  202107. */
  202108. #define fts5LeafIsTermless(x) ((x)->szLeaf >= (x)->nn)
  202109. #define fts5LeafTermOff(x, i) (fts5GetU16(&(x)->p[(x)->szLeaf + (i)*2]))
  202110. #define fts5LeafFirstRowidOff(x) (fts5GetU16((x)->p))
  202111. /*
  202112. ** Object for iterating through the merged results of one or more segments,
  202113. ** visiting each term/rowid pair in the merged data.
  202114. **
  202115. ** nSeg is always a power of two greater than or equal to the number of
  202116. ** segments that this object is merging data from. Both the aSeg[] and
  202117. ** aFirst[] arrays are sized at nSeg entries. The aSeg[] array is padded
  202118. ** with zeroed objects - these are handled as if they were iterators opened
  202119. ** on empty segments.
  202120. **
  202121. ** The results of comparing segments aSeg[N] and aSeg[N+1], where N is an
  202122. ** even number, is stored in aFirst[(nSeg+N)/2]. The "result" of the
  202123. ** comparison in this context is the index of the iterator that currently
  202124. ** points to the smaller term/rowid combination. Iterators at EOF are
  202125. ** considered to be greater than all other iterators.
  202126. **
  202127. ** aFirst[1] contains the index in aSeg[] of the iterator that points to
  202128. ** the smallest key overall. aFirst[0] is unused.
  202129. **
  202130. ** poslist:
  202131. ** Used by sqlite3Fts5IterPoslist() when the poslist needs to be buffered.
  202132. ** There is no way to tell if this is populated or not.
  202133. */
  202134. struct Fts5Iter {
  202135. Fts5IndexIter base; /* Base class containing output vars */
  202136. Fts5Index *pIndex; /* Index that owns this iterator */
  202137. Fts5Buffer poslist; /* Buffer containing current poslist */
  202138. Fts5Colset *pColset; /* Restrict matches to these columns */
  202139. /* Invoked to set output variables. */
  202140. void (*xSetOutputs)(Fts5Iter*, Fts5SegIter*);
  202141. int nSeg; /* Size of aSeg[] array */
  202142. int bRev; /* True to iterate in reverse order */
  202143. u8 bSkipEmpty; /* True to skip deleted entries */
  202144. i64 iSwitchRowid; /* Firstest rowid of other than aFirst[1] */
  202145. Fts5CResult *aFirst; /* Current merge state (see above) */
  202146. Fts5SegIter aSeg[1]; /* Array of segment iterators */
  202147. };
  202148. /*
  202149. ** An instance of the following type is used to iterate through the contents
  202150. ** of a doclist-index record.
  202151. **
  202152. ** pData:
  202153. ** Record containing the doclist-index data.
  202154. **
  202155. ** bEof:
  202156. ** Set to true once iterator has reached EOF.
  202157. **
  202158. ** iOff:
  202159. ** Set to the current offset within record pData.
  202160. */
  202161. struct Fts5DlidxLvl {
  202162. Fts5Data *pData; /* Data for current page of this level */
  202163. int iOff; /* Current offset into pData */
  202164. int bEof; /* At EOF already */
  202165. int iFirstOff; /* Used by reverse iterators */
  202166. /* Output variables */
  202167. int iLeafPgno; /* Page number of current leaf page */
  202168. i64 iRowid; /* First rowid on leaf iLeafPgno */
  202169. };
  202170. struct Fts5DlidxIter {
  202171. int nLvl;
  202172. int iSegid;
  202173. Fts5DlidxLvl aLvl[1];
  202174. };
  202175. static void fts5PutU16(u8 *aOut, u16 iVal){
  202176. aOut[0] = (iVal>>8);
  202177. aOut[1] = (iVal&0xFF);
  202178. }
  202179. static u16 fts5GetU16(const u8 *aIn){
  202180. return ((u16)aIn[0] << 8) + aIn[1];
  202181. }
  202182. /*
  202183. ** Allocate and return a buffer at least nByte bytes in size.
  202184. **
  202185. ** If an OOM error is encountered, return NULL and set the error code in
  202186. ** the Fts5Index handle passed as the first argument.
  202187. */
  202188. static void *fts5IdxMalloc(Fts5Index *p, sqlite3_int64 nByte){
  202189. return sqlite3Fts5MallocZero(&p->rc, nByte);
  202190. }
  202191. /*
  202192. ** Compare the contents of the pLeft buffer with the pRight/nRight blob.
  202193. **
  202194. ** Return -ve if pLeft is smaller than pRight, 0 if they are equal or
  202195. ** +ve if pRight is smaller than pLeft. In other words:
  202196. **
  202197. ** res = *pLeft - *pRight
  202198. */
  202199. #ifdef SQLITE_DEBUG
  202200. static int fts5BufferCompareBlob(
  202201. Fts5Buffer *pLeft, /* Left hand side of comparison */
  202202. const u8 *pRight, int nRight /* Right hand side of comparison */
  202203. ){
  202204. int nCmp = MIN(pLeft->n, nRight);
  202205. int res = memcmp(pLeft->p, pRight, nCmp);
  202206. return (res==0 ? (pLeft->n - nRight) : res);
  202207. }
  202208. #endif
  202209. /*
  202210. ** Compare the contents of the two buffers using memcmp(). If one buffer
  202211. ** is a prefix of the other, it is considered the lesser.
  202212. **
  202213. ** Return -ve if pLeft is smaller than pRight, 0 if they are equal or
  202214. ** +ve if pRight is smaller than pLeft. In other words:
  202215. **
  202216. ** res = *pLeft - *pRight
  202217. */
  202218. static int fts5BufferCompare(Fts5Buffer *pLeft, Fts5Buffer *pRight){
  202219. int nCmp = MIN(pLeft->n, pRight->n);
  202220. int res = fts5Memcmp(pLeft->p, pRight->p, nCmp);
  202221. return (res==0 ? (pLeft->n - pRight->n) : res);
  202222. }
  202223. static int fts5LeafFirstTermOff(Fts5Data *pLeaf){
  202224. int ret;
  202225. fts5GetVarint32(&pLeaf->p[pLeaf->szLeaf], ret);
  202226. return ret;
  202227. }
  202228. /*
  202229. ** Close the read-only blob handle, if it is open.
  202230. */
  202231. static void sqlite3Fts5IndexCloseReader(Fts5Index *p){
  202232. if( p->pReader ){
  202233. sqlite3_blob *pReader = p->pReader;
  202234. p->pReader = 0;
  202235. sqlite3_blob_close(pReader);
  202236. }
  202237. }
  202238. /*
  202239. ** Retrieve a record from the %_data table.
  202240. **
  202241. ** If an error occurs, NULL is returned and an error left in the
  202242. ** Fts5Index object.
  202243. */
  202244. static Fts5Data *fts5DataRead(Fts5Index *p, i64 iRowid){
  202245. Fts5Data *pRet = 0;
  202246. if( p->rc==SQLITE_OK ){
  202247. int rc = SQLITE_OK;
  202248. if( p->pReader ){
  202249. /* This call may return SQLITE_ABORT if there has been a savepoint
  202250. ** rollback since it was last used. In this case a new blob handle
  202251. ** is required. */
  202252. sqlite3_blob *pBlob = p->pReader;
  202253. p->pReader = 0;
  202254. rc = sqlite3_blob_reopen(pBlob, iRowid);
  202255. assert( p->pReader==0 );
  202256. p->pReader = pBlob;
  202257. if( rc!=SQLITE_OK ){
  202258. sqlite3Fts5IndexCloseReader(p);
  202259. }
  202260. if( rc==SQLITE_ABORT ) rc = SQLITE_OK;
  202261. }
  202262. /* If the blob handle is not open at this point, open it and seek
  202263. ** to the requested entry. */
  202264. if( p->pReader==0 && rc==SQLITE_OK ){
  202265. Fts5Config *pConfig = p->pConfig;
  202266. rc = sqlite3_blob_open(pConfig->db,
  202267. pConfig->zDb, p->zDataTbl, "block", iRowid, 0, &p->pReader
  202268. );
  202269. }
  202270. /* If either of the sqlite3_blob_open() or sqlite3_blob_reopen() calls
  202271. ** above returned SQLITE_ERROR, return SQLITE_CORRUPT_VTAB instead.
  202272. ** All the reasons those functions might return SQLITE_ERROR - missing
  202273. ** table, missing row, non-blob/text in block column - indicate
  202274. ** backing store corruption. */
  202275. if( rc==SQLITE_ERROR ) rc = FTS5_CORRUPT;
  202276. if( rc==SQLITE_OK ){
  202277. u8 *aOut = 0; /* Read blob data into this buffer */
  202278. int nByte = sqlite3_blob_bytes(p->pReader);
  202279. sqlite3_int64 nAlloc = sizeof(Fts5Data) + nByte + FTS5_DATA_PADDING;
  202280. pRet = (Fts5Data*)sqlite3_malloc64(nAlloc);
  202281. if( pRet ){
  202282. pRet->nn = nByte;
  202283. aOut = pRet->p = (u8*)&pRet[1];
  202284. }else{
  202285. rc = SQLITE_NOMEM;
  202286. }
  202287. if( rc==SQLITE_OK ){
  202288. rc = sqlite3_blob_read(p->pReader, aOut, nByte, 0);
  202289. }
  202290. if( rc!=SQLITE_OK ){
  202291. sqlite3_free(pRet);
  202292. pRet = 0;
  202293. }else{
  202294. /* TODO1: Fix this */
  202295. pRet->p[nByte] = 0x00;
  202296. pRet->p[nByte+1] = 0x00;
  202297. pRet->szLeaf = fts5GetU16(&pRet->p[2]);
  202298. }
  202299. }
  202300. p->rc = rc;
  202301. p->nRead++;
  202302. }
  202303. assert( (pRet==0)==(p->rc!=SQLITE_OK) );
  202304. return pRet;
  202305. }
  202306. /*
  202307. ** Release a reference to data record returned by an earlier call to
  202308. ** fts5DataRead().
  202309. */
  202310. static void fts5DataRelease(Fts5Data *pData){
  202311. sqlite3_free(pData);
  202312. }
  202313. static Fts5Data *fts5LeafRead(Fts5Index *p, i64 iRowid){
  202314. Fts5Data *pRet = fts5DataRead(p, iRowid);
  202315. if( pRet ){
  202316. if( pRet->nn<4 || pRet->szLeaf>pRet->nn ){
  202317. p->rc = FTS5_CORRUPT;
  202318. fts5DataRelease(pRet);
  202319. pRet = 0;
  202320. }
  202321. }
  202322. return pRet;
  202323. }
  202324. static int fts5IndexPrepareStmt(
  202325. Fts5Index *p,
  202326. sqlite3_stmt **ppStmt,
  202327. char *zSql
  202328. ){
  202329. if( p->rc==SQLITE_OK ){
  202330. if( zSql ){
  202331. p->rc = sqlite3_prepare_v3(p->pConfig->db, zSql, -1,
  202332. SQLITE_PREPARE_PERSISTENT|SQLITE_PREPARE_NO_VTAB,
  202333. ppStmt, 0);
  202334. }else{
  202335. p->rc = SQLITE_NOMEM;
  202336. }
  202337. }
  202338. sqlite3_free(zSql);
  202339. return p->rc;
  202340. }
  202341. /*
  202342. ** INSERT OR REPLACE a record into the %_data table.
  202343. */
  202344. static void fts5DataWrite(Fts5Index *p, i64 iRowid, const u8 *pData, int nData){
  202345. if( p->rc!=SQLITE_OK ) return;
  202346. if( p->pWriter==0 ){
  202347. Fts5Config *pConfig = p->pConfig;
  202348. fts5IndexPrepareStmt(p, &p->pWriter, sqlite3_mprintf(
  202349. "REPLACE INTO '%q'.'%q_data'(id, block) VALUES(?,?)",
  202350. pConfig->zDb, pConfig->zName
  202351. ));
  202352. if( p->rc ) return;
  202353. }
  202354. sqlite3_bind_int64(p->pWriter, 1, iRowid);
  202355. sqlite3_bind_blob(p->pWriter, 2, pData, nData, SQLITE_STATIC);
  202356. sqlite3_step(p->pWriter);
  202357. p->rc = sqlite3_reset(p->pWriter);
  202358. sqlite3_bind_null(p->pWriter, 2);
  202359. }
  202360. /*
  202361. ** Execute the following SQL:
  202362. **
  202363. ** DELETE FROM %_data WHERE id BETWEEN $iFirst AND $iLast
  202364. */
  202365. static void fts5DataDelete(Fts5Index *p, i64 iFirst, i64 iLast){
  202366. if( p->rc!=SQLITE_OK ) return;
  202367. if( p->pDeleter==0 ){
  202368. Fts5Config *pConfig = p->pConfig;
  202369. char *zSql = sqlite3_mprintf(
  202370. "DELETE FROM '%q'.'%q_data' WHERE id>=? AND id<=?",
  202371. pConfig->zDb, pConfig->zName
  202372. );
  202373. if( fts5IndexPrepareStmt(p, &p->pDeleter, zSql) ) return;
  202374. }
  202375. sqlite3_bind_int64(p->pDeleter, 1, iFirst);
  202376. sqlite3_bind_int64(p->pDeleter, 2, iLast);
  202377. sqlite3_step(p->pDeleter);
  202378. p->rc = sqlite3_reset(p->pDeleter);
  202379. }
  202380. /*
  202381. ** Remove all records associated with segment iSegid.
  202382. */
  202383. static void fts5DataRemoveSegment(Fts5Index *p, int iSegid){
  202384. i64 iFirst = FTS5_SEGMENT_ROWID(iSegid, 0);
  202385. i64 iLast = FTS5_SEGMENT_ROWID(iSegid+1, 0)-1;
  202386. fts5DataDelete(p, iFirst, iLast);
  202387. if( p->pIdxDeleter==0 ){
  202388. Fts5Config *pConfig = p->pConfig;
  202389. fts5IndexPrepareStmt(p, &p->pIdxDeleter, sqlite3_mprintf(
  202390. "DELETE FROM '%q'.'%q_idx' WHERE segid=?",
  202391. pConfig->zDb, pConfig->zName
  202392. ));
  202393. }
  202394. if( p->rc==SQLITE_OK ){
  202395. sqlite3_bind_int(p->pIdxDeleter, 1, iSegid);
  202396. sqlite3_step(p->pIdxDeleter);
  202397. p->rc = sqlite3_reset(p->pIdxDeleter);
  202398. }
  202399. }
  202400. /*
  202401. ** Release a reference to an Fts5Structure object returned by an earlier
  202402. ** call to fts5StructureRead() or fts5StructureDecode().
  202403. */
  202404. static void fts5StructureRelease(Fts5Structure *pStruct){
  202405. if( pStruct && 0>=(--pStruct->nRef) ){
  202406. int i;
  202407. assert( pStruct->nRef==0 );
  202408. for(i=0; i<pStruct->nLevel; i++){
  202409. sqlite3_free(pStruct->aLevel[i].aSeg);
  202410. }
  202411. sqlite3_free(pStruct);
  202412. }
  202413. }
  202414. static void fts5StructureRef(Fts5Structure *pStruct){
  202415. pStruct->nRef++;
  202416. }
  202417. /*
  202418. ** Deserialize and return the structure record currently stored in serialized
  202419. ** form within buffer pData/nData.
  202420. **
  202421. ** The Fts5Structure.aLevel[] and each Fts5StructureLevel.aSeg[] array
  202422. ** are over-allocated by one slot. This allows the structure contents
  202423. ** to be more easily edited.
  202424. **
  202425. ** If an error occurs, *ppOut is set to NULL and an SQLite error code
  202426. ** returned. Otherwise, *ppOut is set to point to the new object and
  202427. ** SQLITE_OK returned.
  202428. */
  202429. static int fts5StructureDecode(
  202430. const u8 *pData, /* Buffer containing serialized structure */
  202431. int nData, /* Size of buffer pData in bytes */
  202432. int *piCookie, /* Configuration cookie value */
  202433. Fts5Structure **ppOut /* OUT: Deserialized object */
  202434. ){
  202435. int rc = SQLITE_OK;
  202436. int i = 0;
  202437. int iLvl;
  202438. int nLevel = 0;
  202439. int nSegment = 0;
  202440. sqlite3_int64 nByte; /* Bytes of space to allocate at pRet */
  202441. Fts5Structure *pRet = 0; /* Structure object to return */
  202442. /* Grab the cookie value */
  202443. if( piCookie ) *piCookie = sqlite3Fts5Get32(pData);
  202444. i = 4;
  202445. /* Read the total number of levels and segments from the start of the
  202446. ** structure record. */
  202447. i += fts5GetVarint32(&pData[i], nLevel);
  202448. i += fts5GetVarint32(&pData[i], nSegment);
  202449. if( nLevel>FTS5_MAX_SEGMENT || nLevel<0
  202450. || nSegment>FTS5_MAX_SEGMENT || nSegment<0
  202451. ){
  202452. return FTS5_CORRUPT;
  202453. }
  202454. nByte = (
  202455. sizeof(Fts5Structure) + /* Main structure */
  202456. sizeof(Fts5StructureLevel) * (nLevel-1) /* aLevel[] array */
  202457. );
  202458. pRet = (Fts5Structure*)sqlite3Fts5MallocZero(&rc, nByte);
  202459. if( pRet ){
  202460. pRet->nRef = 1;
  202461. pRet->nLevel = nLevel;
  202462. pRet->nSegment = nSegment;
  202463. i += sqlite3Fts5GetVarint(&pData[i], &pRet->nWriteCounter);
  202464. for(iLvl=0; rc==SQLITE_OK && iLvl<nLevel; iLvl++){
  202465. Fts5StructureLevel *pLvl = &pRet->aLevel[iLvl];
  202466. int nTotal = 0;
  202467. int iSeg;
  202468. if( i>=nData ){
  202469. rc = FTS5_CORRUPT;
  202470. }else{
  202471. i += fts5GetVarint32(&pData[i], pLvl->nMerge);
  202472. i += fts5GetVarint32(&pData[i], nTotal);
  202473. if( nTotal<pLvl->nMerge ) rc = FTS5_CORRUPT;
  202474. pLvl->aSeg = (Fts5StructureSegment*)sqlite3Fts5MallocZero(&rc,
  202475. nTotal * sizeof(Fts5StructureSegment)
  202476. );
  202477. nSegment -= nTotal;
  202478. }
  202479. if( rc==SQLITE_OK ){
  202480. pLvl->nSeg = nTotal;
  202481. for(iSeg=0; iSeg<nTotal; iSeg++){
  202482. Fts5StructureSegment *pSeg = &pLvl->aSeg[iSeg];
  202483. if( i>=nData ){
  202484. rc = FTS5_CORRUPT;
  202485. break;
  202486. }
  202487. i += fts5GetVarint32(&pData[i], pSeg->iSegid);
  202488. i += fts5GetVarint32(&pData[i], pSeg->pgnoFirst);
  202489. i += fts5GetVarint32(&pData[i], pSeg->pgnoLast);
  202490. if( pSeg->pgnoLast<pSeg->pgnoFirst ){
  202491. rc = FTS5_CORRUPT;
  202492. break;
  202493. }
  202494. }
  202495. if( iLvl>0 && pLvl[-1].nMerge && nTotal==0 ) rc = FTS5_CORRUPT;
  202496. if( iLvl==nLevel-1 && pLvl->nMerge ) rc = FTS5_CORRUPT;
  202497. }
  202498. }
  202499. if( nSegment!=0 && rc==SQLITE_OK ) rc = FTS5_CORRUPT;
  202500. if( rc!=SQLITE_OK ){
  202501. fts5StructureRelease(pRet);
  202502. pRet = 0;
  202503. }
  202504. }
  202505. *ppOut = pRet;
  202506. return rc;
  202507. }
  202508. /*
  202509. **
  202510. */
  202511. static void fts5StructureAddLevel(int *pRc, Fts5Structure **ppStruct){
  202512. if( *pRc==SQLITE_OK ){
  202513. Fts5Structure *pStruct = *ppStruct;
  202514. int nLevel = pStruct->nLevel;
  202515. sqlite3_int64 nByte = (
  202516. sizeof(Fts5Structure) + /* Main structure */
  202517. sizeof(Fts5StructureLevel) * (nLevel+1) /* aLevel[] array */
  202518. );
  202519. pStruct = sqlite3_realloc64(pStruct, nByte);
  202520. if( pStruct ){
  202521. memset(&pStruct->aLevel[nLevel], 0, sizeof(Fts5StructureLevel));
  202522. pStruct->nLevel++;
  202523. *ppStruct = pStruct;
  202524. }else{
  202525. *pRc = SQLITE_NOMEM;
  202526. }
  202527. }
  202528. }
  202529. /*
  202530. ** Extend level iLvl so that there is room for at least nExtra more
  202531. ** segments.
  202532. */
  202533. static void fts5StructureExtendLevel(
  202534. int *pRc,
  202535. Fts5Structure *pStruct,
  202536. int iLvl,
  202537. int nExtra,
  202538. int bInsert
  202539. ){
  202540. if( *pRc==SQLITE_OK ){
  202541. Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
  202542. Fts5StructureSegment *aNew;
  202543. sqlite3_int64 nByte;
  202544. nByte = (pLvl->nSeg + nExtra) * sizeof(Fts5StructureSegment);
  202545. aNew = sqlite3_realloc64(pLvl->aSeg, nByte);
  202546. if( aNew ){
  202547. if( bInsert==0 ){
  202548. memset(&aNew[pLvl->nSeg], 0, sizeof(Fts5StructureSegment) * nExtra);
  202549. }else{
  202550. int nMove = pLvl->nSeg * sizeof(Fts5StructureSegment);
  202551. memmove(&aNew[nExtra], aNew, nMove);
  202552. memset(aNew, 0, sizeof(Fts5StructureSegment) * nExtra);
  202553. }
  202554. pLvl->aSeg = aNew;
  202555. }else{
  202556. *pRc = SQLITE_NOMEM;
  202557. }
  202558. }
  202559. }
  202560. static Fts5Structure *fts5StructureReadUncached(Fts5Index *p){
  202561. Fts5Structure *pRet = 0;
  202562. Fts5Config *pConfig = p->pConfig;
  202563. int iCookie; /* Configuration cookie */
  202564. Fts5Data *pData;
  202565. pData = fts5DataRead(p, FTS5_STRUCTURE_ROWID);
  202566. if( p->rc==SQLITE_OK ){
  202567. /* TODO: Do we need this if the leaf-index is appended? Probably... */
  202568. memset(&pData->p[pData->nn], 0, FTS5_DATA_PADDING);
  202569. p->rc = fts5StructureDecode(pData->p, pData->nn, &iCookie, &pRet);
  202570. if( p->rc==SQLITE_OK && (pConfig->pgsz==0 || pConfig->iCookie!=iCookie) ){
  202571. p->rc = sqlite3Fts5ConfigLoad(pConfig, iCookie);
  202572. }
  202573. fts5DataRelease(pData);
  202574. if( p->rc!=SQLITE_OK ){
  202575. fts5StructureRelease(pRet);
  202576. pRet = 0;
  202577. }
  202578. }
  202579. return pRet;
  202580. }
  202581. static i64 fts5IndexDataVersion(Fts5Index *p){
  202582. i64 iVersion = 0;
  202583. if( p->rc==SQLITE_OK ){
  202584. if( p->pDataVersion==0 ){
  202585. p->rc = fts5IndexPrepareStmt(p, &p->pDataVersion,
  202586. sqlite3_mprintf("PRAGMA %Q.data_version", p->pConfig->zDb)
  202587. );
  202588. if( p->rc ) return 0;
  202589. }
  202590. if( SQLITE_ROW==sqlite3_step(p->pDataVersion) ){
  202591. iVersion = sqlite3_column_int64(p->pDataVersion, 0);
  202592. }
  202593. p->rc = sqlite3_reset(p->pDataVersion);
  202594. }
  202595. return iVersion;
  202596. }
  202597. /*
  202598. ** Read, deserialize and return the structure record.
  202599. **
  202600. ** The Fts5Structure.aLevel[] and each Fts5StructureLevel.aSeg[] array
  202601. ** are over-allocated as described for function fts5StructureDecode()
  202602. ** above.
  202603. **
  202604. ** If an error occurs, NULL is returned and an error code left in the
  202605. ** Fts5Index handle. If an error has already occurred when this function
  202606. ** is called, it is a no-op.
  202607. */
  202608. static Fts5Structure *fts5StructureRead(Fts5Index *p){
  202609. if( p->pStruct==0 ){
  202610. p->iStructVersion = fts5IndexDataVersion(p);
  202611. if( p->rc==SQLITE_OK ){
  202612. p->pStruct = fts5StructureReadUncached(p);
  202613. }
  202614. }
  202615. #if 0
  202616. else{
  202617. Fts5Structure *pTest = fts5StructureReadUncached(p);
  202618. if( pTest ){
  202619. int i, j;
  202620. assert_nc( p->pStruct->nSegment==pTest->nSegment );
  202621. assert_nc( p->pStruct->nLevel==pTest->nLevel );
  202622. for(i=0; i<pTest->nLevel; i++){
  202623. assert_nc( p->pStruct->aLevel[i].nMerge==pTest->aLevel[i].nMerge );
  202624. assert_nc( p->pStruct->aLevel[i].nSeg==pTest->aLevel[i].nSeg );
  202625. for(j=0; j<pTest->aLevel[i].nSeg; j++){
  202626. Fts5StructureSegment *p1 = &pTest->aLevel[i].aSeg[j];
  202627. Fts5StructureSegment *p2 = &p->pStruct->aLevel[i].aSeg[j];
  202628. assert_nc( p1->iSegid==p2->iSegid );
  202629. assert_nc( p1->pgnoFirst==p2->pgnoFirst );
  202630. assert_nc( p1->pgnoLast==p2->pgnoLast );
  202631. }
  202632. }
  202633. fts5StructureRelease(pTest);
  202634. }
  202635. }
  202636. #endif
  202637. if( p->rc!=SQLITE_OK ) return 0;
  202638. assert( p->iStructVersion!=0 );
  202639. assert( p->pStruct!=0 );
  202640. fts5StructureRef(p->pStruct);
  202641. return p->pStruct;
  202642. }
  202643. static void fts5StructureInvalidate(Fts5Index *p){
  202644. if( p->pStruct ){
  202645. fts5StructureRelease(p->pStruct);
  202646. p->pStruct = 0;
  202647. }
  202648. }
  202649. /*
  202650. ** Return the total number of segments in index structure pStruct. This
  202651. ** function is only ever used as part of assert() conditions.
  202652. */
  202653. #ifdef SQLITE_DEBUG
  202654. static int fts5StructureCountSegments(Fts5Structure *pStruct){
  202655. int nSegment = 0; /* Total number of segments */
  202656. if( pStruct ){
  202657. int iLvl; /* Used to iterate through levels */
  202658. for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
  202659. nSegment += pStruct->aLevel[iLvl].nSeg;
  202660. }
  202661. }
  202662. return nSegment;
  202663. }
  202664. #endif
  202665. #define fts5BufferSafeAppendBlob(pBuf, pBlob, nBlob) { \
  202666. assert( (pBuf)->nSpace>=((pBuf)->n+nBlob) ); \
  202667. memcpy(&(pBuf)->p[(pBuf)->n], pBlob, nBlob); \
  202668. (pBuf)->n += nBlob; \
  202669. }
  202670. #define fts5BufferSafeAppendVarint(pBuf, iVal) { \
  202671. (pBuf)->n += sqlite3Fts5PutVarint(&(pBuf)->p[(pBuf)->n], (iVal)); \
  202672. assert( (pBuf)->nSpace>=(pBuf)->n ); \
  202673. }
  202674. /*
  202675. ** Serialize and store the "structure" record.
  202676. **
  202677. ** If an error occurs, leave an error code in the Fts5Index object. If an
  202678. ** error has already occurred, this function is a no-op.
  202679. */
  202680. static void fts5StructureWrite(Fts5Index *p, Fts5Structure *pStruct){
  202681. if( p->rc==SQLITE_OK ){
  202682. Fts5Buffer buf; /* Buffer to serialize record into */
  202683. int iLvl; /* Used to iterate through levels */
  202684. int iCookie; /* Cookie value to store */
  202685. assert( pStruct->nSegment==fts5StructureCountSegments(pStruct) );
  202686. memset(&buf, 0, sizeof(Fts5Buffer));
  202687. /* Append the current configuration cookie */
  202688. iCookie = p->pConfig->iCookie;
  202689. if( iCookie<0 ) iCookie = 0;
  202690. if( 0==sqlite3Fts5BufferSize(&p->rc, &buf, 4+9+9+9) ){
  202691. sqlite3Fts5Put32(buf.p, iCookie);
  202692. buf.n = 4;
  202693. fts5BufferSafeAppendVarint(&buf, pStruct->nLevel);
  202694. fts5BufferSafeAppendVarint(&buf, pStruct->nSegment);
  202695. fts5BufferSafeAppendVarint(&buf, (i64)pStruct->nWriteCounter);
  202696. }
  202697. for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
  202698. int iSeg; /* Used to iterate through segments */
  202699. Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
  202700. fts5BufferAppendVarint(&p->rc, &buf, pLvl->nMerge);
  202701. fts5BufferAppendVarint(&p->rc, &buf, pLvl->nSeg);
  202702. assert( pLvl->nMerge<=pLvl->nSeg );
  202703. for(iSeg=0; iSeg<pLvl->nSeg; iSeg++){
  202704. fts5BufferAppendVarint(&p->rc, &buf, pLvl->aSeg[iSeg].iSegid);
  202705. fts5BufferAppendVarint(&p->rc, &buf, pLvl->aSeg[iSeg].pgnoFirst);
  202706. fts5BufferAppendVarint(&p->rc, &buf, pLvl->aSeg[iSeg].pgnoLast);
  202707. }
  202708. }
  202709. fts5DataWrite(p, FTS5_STRUCTURE_ROWID, buf.p, buf.n);
  202710. fts5BufferFree(&buf);
  202711. }
  202712. }
  202713. #if 0
  202714. static void fts5DebugStructure(int*,Fts5Buffer*,Fts5Structure*);
  202715. static void fts5PrintStructure(const char *zCaption, Fts5Structure *pStruct){
  202716. int rc = SQLITE_OK;
  202717. Fts5Buffer buf;
  202718. memset(&buf, 0, sizeof(buf));
  202719. fts5DebugStructure(&rc, &buf, pStruct);
  202720. fprintf(stdout, "%s: %s\n", zCaption, buf.p);
  202721. fflush(stdout);
  202722. fts5BufferFree(&buf);
  202723. }
  202724. #else
  202725. # define fts5PrintStructure(x,y)
  202726. #endif
  202727. static int fts5SegmentSize(Fts5StructureSegment *pSeg){
  202728. return 1 + pSeg->pgnoLast - pSeg->pgnoFirst;
  202729. }
  202730. /*
  202731. ** Return a copy of index structure pStruct. Except, promote as many
  202732. ** segments as possible to level iPromote. If an OOM occurs, NULL is
  202733. ** returned.
  202734. */
  202735. static void fts5StructurePromoteTo(
  202736. Fts5Index *p,
  202737. int iPromote,
  202738. int szPromote,
  202739. Fts5Structure *pStruct
  202740. ){
  202741. int il, is;
  202742. Fts5StructureLevel *pOut = &pStruct->aLevel[iPromote];
  202743. if( pOut->nMerge==0 ){
  202744. for(il=iPromote+1; il<pStruct->nLevel; il++){
  202745. Fts5StructureLevel *pLvl = &pStruct->aLevel[il];
  202746. if( pLvl->nMerge ) return;
  202747. for(is=pLvl->nSeg-1; is>=0; is--){
  202748. int sz = fts5SegmentSize(&pLvl->aSeg[is]);
  202749. if( sz>szPromote ) return;
  202750. fts5StructureExtendLevel(&p->rc, pStruct, iPromote, 1, 1);
  202751. if( p->rc ) return;
  202752. memcpy(pOut->aSeg, &pLvl->aSeg[is], sizeof(Fts5StructureSegment));
  202753. pOut->nSeg++;
  202754. pLvl->nSeg--;
  202755. }
  202756. }
  202757. }
  202758. }
  202759. /*
  202760. ** A new segment has just been written to level iLvl of index structure
  202761. ** pStruct. This function determines if any segments should be promoted
  202762. ** as a result. Segments are promoted in two scenarios:
  202763. **
  202764. ** a) If the segment just written is smaller than one or more segments
  202765. ** within the previous populated level, it is promoted to the previous
  202766. ** populated level.
  202767. **
  202768. ** b) If the segment just written is larger than the newest segment on
  202769. ** the next populated level, then that segment, and any other adjacent
  202770. ** segments that are also smaller than the one just written, are
  202771. ** promoted.
  202772. **
  202773. ** If one or more segments are promoted, the structure object is updated
  202774. ** to reflect this.
  202775. */
  202776. static void fts5StructurePromote(
  202777. Fts5Index *p, /* FTS5 backend object */
  202778. int iLvl, /* Index level just updated */
  202779. Fts5Structure *pStruct /* Index structure */
  202780. ){
  202781. if( p->rc==SQLITE_OK ){
  202782. int iTst;
  202783. int iPromote = -1;
  202784. int szPromote = 0; /* Promote anything this size or smaller */
  202785. Fts5StructureSegment *pSeg; /* Segment just written */
  202786. int szSeg; /* Size of segment just written */
  202787. int nSeg = pStruct->aLevel[iLvl].nSeg;
  202788. if( nSeg==0 ) return;
  202789. pSeg = &pStruct->aLevel[iLvl].aSeg[pStruct->aLevel[iLvl].nSeg-1];
  202790. szSeg = (1 + pSeg->pgnoLast - pSeg->pgnoFirst);
  202791. /* Check for condition (a) */
  202792. for(iTst=iLvl-1; iTst>=0 && pStruct->aLevel[iTst].nSeg==0; iTst--);
  202793. if( iTst>=0 ){
  202794. int i;
  202795. int szMax = 0;
  202796. Fts5StructureLevel *pTst = &pStruct->aLevel[iTst];
  202797. assert( pTst->nMerge==0 );
  202798. for(i=0; i<pTst->nSeg; i++){
  202799. int sz = pTst->aSeg[i].pgnoLast - pTst->aSeg[i].pgnoFirst + 1;
  202800. if( sz>szMax ) szMax = sz;
  202801. }
  202802. if( szMax>=szSeg ){
  202803. /* Condition (a) is true. Promote the newest segment on level
  202804. ** iLvl to level iTst. */
  202805. iPromote = iTst;
  202806. szPromote = szMax;
  202807. }
  202808. }
  202809. /* If condition (a) is not met, assume (b) is true. StructurePromoteTo()
  202810. ** is a no-op if it is not. */
  202811. if( iPromote<0 ){
  202812. iPromote = iLvl;
  202813. szPromote = szSeg;
  202814. }
  202815. fts5StructurePromoteTo(p, iPromote, szPromote, pStruct);
  202816. }
  202817. }
  202818. /*
  202819. ** Advance the iterator passed as the only argument. If the end of the
  202820. ** doclist-index page is reached, return non-zero.
  202821. */
  202822. static int fts5DlidxLvlNext(Fts5DlidxLvl *pLvl){
  202823. Fts5Data *pData = pLvl->pData;
  202824. if( pLvl->iOff==0 ){
  202825. assert( pLvl->bEof==0 );
  202826. pLvl->iOff = 1;
  202827. pLvl->iOff += fts5GetVarint32(&pData->p[1], pLvl->iLeafPgno);
  202828. pLvl->iOff += fts5GetVarint(&pData->p[pLvl->iOff], (u64*)&pLvl->iRowid);
  202829. pLvl->iFirstOff = pLvl->iOff;
  202830. }else{
  202831. int iOff;
  202832. for(iOff=pLvl->iOff; iOff<pData->nn; iOff++){
  202833. if( pData->p[iOff] ) break;
  202834. }
  202835. if( iOff<pData->nn ){
  202836. i64 iVal;
  202837. pLvl->iLeafPgno += (iOff - pLvl->iOff) + 1;
  202838. iOff += fts5GetVarint(&pData->p[iOff], (u64*)&iVal);
  202839. pLvl->iRowid += iVal;
  202840. pLvl->iOff = iOff;
  202841. }else{
  202842. pLvl->bEof = 1;
  202843. }
  202844. }
  202845. return pLvl->bEof;
  202846. }
  202847. /*
  202848. ** Advance the iterator passed as the only argument.
  202849. */
  202850. static int fts5DlidxIterNextR(Fts5Index *p, Fts5DlidxIter *pIter, int iLvl){
  202851. Fts5DlidxLvl *pLvl = &pIter->aLvl[iLvl];
  202852. assert( iLvl<pIter->nLvl );
  202853. if( fts5DlidxLvlNext(pLvl) ){
  202854. if( (iLvl+1) < pIter->nLvl ){
  202855. fts5DlidxIterNextR(p, pIter, iLvl+1);
  202856. if( pLvl[1].bEof==0 ){
  202857. fts5DataRelease(pLvl->pData);
  202858. memset(pLvl, 0, sizeof(Fts5DlidxLvl));
  202859. pLvl->pData = fts5DataRead(p,
  202860. FTS5_DLIDX_ROWID(pIter->iSegid, iLvl, pLvl[1].iLeafPgno)
  202861. );
  202862. if( pLvl->pData ) fts5DlidxLvlNext(pLvl);
  202863. }
  202864. }
  202865. }
  202866. return pIter->aLvl[0].bEof;
  202867. }
  202868. static int fts5DlidxIterNext(Fts5Index *p, Fts5DlidxIter *pIter){
  202869. return fts5DlidxIterNextR(p, pIter, 0);
  202870. }
  202871. /*
  202872. ** The iterator passed as the first argument has the following fields set
  202873. ** as follows. This function sets up the rest of the iterator so that it
  202874. ** points to the first rowid in the doclist-index.
  202875. **
  202876. ** pData:
  202877. ** pointer to doclist-index record,
  202878. **
  202879. ** When this function is called pIter->iLeafPgno is the page number the
  202880. ** doclist is associated with (the one featuring the term).
  202881. */
  202882. static int fts5DlidxIterFirst(Fts5DlidxIter *pIter){
  202883. int i;
  202884. for(i=0; i<pIter->nLvl; i++){
  202885. fts5DlidxLvlNext(&pIter->aLvl[i]);
  202886. }
  202887. return pIter->aLvl[0].bEof;
  202888. }
  202889. static int fts5DlidxIterEof(Fts5Index *p, Fts5DlidxIter *pIter){
  202890. return p->rc!=SQLITE_OK || pIter->aLvl[0].bEof;
  202891. }
  202892. static void fts5DlidxIterLast(Fts5Index *p, Fts5DlidxIter *pIter){
  202893. int i;
  202894. /* Advance each level to the last entry on the last page */
  202895. for(i=pIter->nLvl-1; p->rc==SQLITE_OK && i>=0; i--){
  202896. Fts5DlidxLvl *pLvl = &pIter->aLvl[i];
  202897. while( fts5DlidxLvlNext(pLvl)==0 );
  202898. pLvl->bEof = 0;
  202899. if( i>0 ){
  202900. Fts5DlidxLvl *pChild = &pLvl[-1];
  202901. fts5DataRelease(pChild->pData);
  202902. memset(pChild, 0, sizeof(Fts5DlidxLvl));
  202903. pChild->pData = fts5DataRead(p,
  202904. FTS5_DLIDX_ROWID(pIter->iSegid, i-1, pLvl->iLeafPgno)
  202905. );
  202906. }
  202907. }
  202908. }
  202909. /*
  202910. ** Move the iterator passed as the only argument to the previous entry.
  202911. */
  202912. static int fts5DlidxLvlPrev(Fts5DlidxLvl *pLvl){
  202913. int iOff = pLvl->iOff;
  202914. assert( pLvl->bEof==0 );
  202915. if( iOff<=pLvl->iFirstOff ){
  202916. pLvl->bEof = 1;
  202917. }else{
  202918. u8 *a = pLvl->pData->p;
  202919. i64 iVal;
  202920. int iLimit;
  202921. int ii;
  202922. int nZero = 0;
  202923. /* Currently iOff points to the first byte of a varint. This block
  202924. ** decrements iOff until it points to the first byte of the previous
  202925. ** varint. Taking care not to read any memory locations that occur
  202926. ** before the buffer in memory. */
  202927. iLimit = (iOff>9 ? iOff-9 : 0);
  202928. for(iOff--; iOff>iLimit; iOff--){
  202929. if( (a[iOff-1] & 0x80)==0 ) break;
  202930. }
  202931. fts5GetVarint(&a[iOff], (u64*)&iVal);
  202932. pLvl->iRowid -= iVal;
  202933. pLvl->iLeafPgno--;
  202934. /* Skip backwards past any 0x00 varints. */
  202935. for(ii=iOff-1; ii>=pLvl->iFirstOff && a[ii]==0x00; ii--){
  202936. nZero++;
  202937. }
  202938. if( ii>=pLvl->iFirstOff && (a[ii] & 0x80) ){
  202939. /* The byte immediately before the last 0x00 byte has the 0x80 bit
  202940. ** set. So the last 0x00 is only a varint 0 if there are 8 more 0x80
  202941. ** bytes before a[ii]. */
  202942. int bZero = 0; /* True if last 0x00 counts */
  202943. if( (ii-8)>=pLvl->iFirstOff ){
  202944. int j;
  202945. for(j=1; j<=8 && (a[ii-j] & 0x80); j++);
  202946. bZero = (j>8);
  202947. }
  202948. if( bZero==0 ) nZero--;
  202949. }
  202950. pLvl->iLeafPgno -= nZero;
  202951. pLvl->iOff = iOff - nZero;
  202952. }
  202953. return pLvl->bEof;
  202954. }
  202955. static int fts5DlidxIterPrevR(Fts5Index *p, Fts5DlidxIter *pIter, int iLvl){
  202956. Fts5DlidxLvl *pLvl = &pIter->aLvl[iLvl];
  202957. assert( iLvl<pIter->nLvl );
  202958. if( fts5DlidxLvlPrev(pLvl) ){
  202959. if( (iLvl+1) < pIter->nLvl ){
  202960. fts5DlidxIterPrevR(p, pIter, iLvl+1);
  202961. if( pLvl[1].bEof==0 ){
  202962. fts5DataRelease(pLvl->pData);
  202963. memset(pLvl, 0, sizeof(Fts5DlidxLvl));
  202964. pLvl->pData = fts5DataRead(p,
  202965. FTS5_DLIDX_ROWID(pIter->iSegid, iLvl, pLvl[1].iLeafPgno)
  202966. );
  202967. if( pLvl->pData ){
  202968. while( fts5DlidxLvlNext(pLvl)==0 );
  202969. pLvl->bEof = 0;
  202970. }
  202971. }
  202972. }
  202973. }
  202974. return pIter->aLvl[0].bEof;
  202975. }
  202976. static int fts5DlidxIterPrev(Fts5Index *p, Fts5DlidxIter *pIter){
  202977. return fts5DlidxIterPrevR(p, pIter, 0);
  202978. }
  202979. /*
  202980. ** Free a doclist-index iterator object allocated by fts5DlidxIterInit().
  202981. */
  202982. static void fts5DlidxIterFree(Fts5DlidxIter *pIter){
  202983. if( pIter ){
  202984. int i;
  202985. for(i=0; i<pIter->nLvl; i++){
  202986. fts5DataRelease(pIter->aLvl[i].pData);
  202987. }
  202988. sqlite3_free(pIter);
  202989. }
  202990. }
  202991. static Fts5DlidxIter *fts5DlidxIterInit(
  202992. Fts5Index *p, /* Fts5 Backend to iterate within */
  202993. int bRev, /* True for ORDER BY ASC */
  202994. int iSegid, /* Segment id */
  202995. int iLeafPg /* Leaf page number to load dlidx for */
  202996. ){
  202997. Fts5DlidxIter *pIter = 0;
  202998. int i;
  202999. int bDone = 0;
  203000. for(i=0; p->rc==SQLITE_OK && bDone==0; i++){
  203001. sqlite3_int64 nByte = sizeof(Fts5DlidxIter) + i * sizeof(Fts5DlidxLvl);
  203002. Fts5DlidxIter *pNew;
  203003. pNew = (Fts5DlidxIter*)sqlite3_realloc64(pIter, nByte);
  203004. if( pNew==0 ){
  203005. p->rc = SQLITE_NOMEM;
  203006. }else{
  203007. i64 iRowid = FTS5_DLIDX_ROWID(iSegid, i, iLeafPg);
  203008. Fts5DlidxLvl *pLvl = &pNew->aLvl[i];
  203009. pIter = pNew;
  203010. memset(pLvl, 0, sizeof(Fts5DlidxLvl));
  203011. pLvl->pData = fts5DataRead(p, iRowid);
  203012. if( pLvl->pData && (pLvl->pData->p[0] & 0x0001)==0 ){
  203013. bDone = 1;
  203014. }
  203015. pIter->nLvl = i+1;
  203016. }
  203017. }
  203018. if( p->rc==SQLITE_OK ){
  203019. pIter->iSegid = iSegid;
  203020. if( bRev==0 ){
  203021. fts5DlidxIterFirst(pIter);
  203022. }else{
  203023. fts5DlidxIterLast(p, pIter);
  203024. }
  203025. }
  203026. if( p->rc!=SQLITE_OK ){
  203027. fts5DlidxIterFree(pIter);
  203028. pIter = 0;
  203029. }
  203030. return pIter;
  203031. }
  203032. static i64 fts5DlidxIterRowid(Fts5DlidxIter *pIter){
  203033. return pIter->aLvl[0].iRowid;
  203034. }
  203035. static int fts5DlidxIterPgno(Fts5DlidxIter *pIter){
  203036. return pIter->aLvl[0].iLeafPgno;
  203037. }
  203038. /*
  203039. ** Load the next leaf page into the segment iterator.
  203040. */
  203041. static void fts5SegIterNextPage(
  203042. Fts5Index *p, /* FTS5 backend object */
  203043. Fts5SegIter *pIter /* Iterator to advance to next page */
  203044. ){
  203045. Fts5Data *pLeaf;
  203046. Fts5StructureSegment *pSeg = pIter->pSeg;
  203047. fts5DataRelease(pIter->pLeaf);
  203048. pIter->iLeafPgno++;
  203049. if( pIter->pNextLeaf ){
  203050. pIter->pLeaf = pIter->pNextLeaf;
  203051. pIter->pNextLeaf = 0;
  203052. }else if( pIter->iLeafPgno<=pSeg->pgnoLast ){
  203053. pIter->pLeaf = fts5LeafRead(p,
  203054. FTS5_SEGMENT_ROWID(pSeg->iSegid, pIter->iLeafPgno)
  203055. );
  203056. }else{
  203057. pIter->pLeaf = 0;
  203058. }
  203059. pLeaf = pIter->pLeaf;
  203060. if( pLeaf ){
  203061. pIter->iPgidxOff = pLeaf->szLeaf;
  203062. if( fts5LeafIsTermless(pLeaf) ){
  203063. pIter->iEndofDoclist = pLeaf->nn+1;
  203064. }else{
  203065. pIter->iPgidxOff += fts5GetVarint32(&pLeaf->p[pIter->iPgidxOff],
  203066. pIter->iEndofDoclist
  203067. );
  203068. }
  203069. }
  203070. }
  203071. /*
  203072. ** Argument p points to a buffer containing a varint to be interpreted as a
  203073. ** position list size field. Read the varint and return the number of bytes
  203074. ** read. Before returning, set *pnSz to the number of bytes in the position
  203075. ** list, and *pbDel to true if the delete flag is set, or false otherwise.
  203076. */
  203077. static int fts5GetPoslistSize(const u8 *p, int *pnSz, int *pbDel){
  203078. int nSz;
  203079. int n = 0;
  203080. fts5FastGetVarint32(p, n, nSz);
  203081. assert_nc( nSz>=0 );
  203082. *pnSz = nSz/2;
  203083. *pbDel = nSz & 0x0001;
  203084. return n;
  203085. }
  203086. /*
  203087. ** Fts5SegIter.iLeafOffset currently points to the first byte of a
  203088. ** position-list size field. Read the value of the field and store it
  203089. ** in the following variables:
  203090. **
  203091. ** Fts5SegIter.nPos
  203092. ** Fts5SegIter.bDel
  203093. **
  203094. ** Leave Fts5SegIter.iLeafOffset pointing to the first byte of the
  203095. ** position list content (if any).
  203096. */
  203097. static void fts5SegIterLoadNPos(Fts5Index *p, Fts5SegIter *pIter){
  203098. if( p->rc==SQLITE_OK ){
  203099. int iOff = pIter->iLeafOffset; /* Offset to read at */
  203100. ASSERT_SZLEAF_OK(pIter->pLeaf);
  203101. if( p->pConfig->eDetail==FTS5_DETAIL_NONE ){
  203102. int iEod = MIN(pIter->iEndofDoclist, pIter->pLeaf->szLeaf);
  203103. pIter->bDel = 0;
  203104. pIter->nPos = 1;
  203105. if( iOff<iEod && pIter->pLeaf->p[iOff]==0 ){
  203106. pIter->bDel = 1;
  203107. iOff++;
  203108. if( iOff<iEod && pIter->pLeaf->p[iOff]==0 ){
  203109. pIter->nPos = 1;
  203110. iOff++;
  203111. }else{
  203112. pIter->nPos = 0;
  203113. }
  203114. }
  203115. }else{
  203116. int nSz;
  203117. fts5FastGetVarint32(pIter->pLeaf->p, iOff, nSz);
  203118. pIter->bDel = (nSz & 0x0001);
  203119. pIter->nPos = nSz>>1;
  203120. assert_nc( pIter->nPos>=0 );
  203121. }
  203122. pIter->iLeafOffset = iOff;
  203123. }
  203124. }
  203125. static void fts5SegIterLoadRowid(Fts5Index *p, Fts5SegIter *pIter){
  203126. u8 *a = pIter->pLeaf->p; /* Buffer to read data from */
  203127. int iOff = pIter->iLeafOffset;
  203128. ASSERT_SZLEAF_OK(pIter->pLeaf);
  203129. if( iOff>=pIter->pLeaf->szLeaf ){
  203130. fts5SegIterNextPage(p, pIter);
  203131. if( pIter->pLeaf==0 ){
  203132. if( p->rc==SQLITE_OK ) p->rc = FTS5_CORRUPT;
  203133. return;
  203134. }
  203135. iOff = 4;
  203136. a = pIter->pLeaf->p;
  203137. }
  203138. iOff += sqlite3Fts5GetVarint(&a[iOff], (u64*)&pIter->iRowid);
  203139. pIter->iLeafOffset = iOff;
  203140. }
  203141. /*
  203142. ** Fts5SegIter.iLeafOffset currently points to the first byte of the
  203143. ** "nSuffix" field of a term. Function parameter nKeep contains the value
  203144. ** of the "nPrefix" field (if there was one - it is passed 0 if this is
  203145. ** the first term in the segment).
  203146. **
  203147. ** This function populates:
  203148. **
  203149. ** Fts5SegIter.term
  203150. ** Fts5SegIter.rowid
  203151. **
  203152. ** accordingly and leaves (Fts5SegIter.iLeafOffset) set to the content of
  203153. ** the first position list. The position list belonging to document
  203154. ** (Fts5SegIter.iRowid).
  203155. */
  203156. static void fts5SegIterLoadTerm(Fts5Index *p, Fts5SegIter *pIter, int nKeep){
  203157. u8 *a = pIter->pLeaf->p; /* Buffer to read data from */
  203158. int iOff = pIter->iLeafOffset; /* Offset to read at */
  203159. int nNew; /* Bytes of new data */
  203160. iOff += fts5GetVarint32(&a[iOff], nNew);
  203161. if( iOff+nNew>pIter->pLeaf->szLeaf || nKeep>pIter->term.n || nNew==0 ){
  203162. p->rc = FTS5_CORRUPT;
  203163. return;
  203164. }
  203165. pIter->term.n = nKeep;
  203166. fts5BufferAppendBlob(&p->rc, &pIter->term, nNew, &a[iOff]);
  203167. assert( pIter->term.n<=pIter->term.nSpace );
  203168. iOff += nNew;
  203169. pIter->iTermLeafOffset = iOff;
  203170. pIter->iTermLeafPgno = pIter->iLeafPgno;
  203171. pIter->iLeafOffset = iOff;
  203172. if( pIter->iPgidxOff>=pIter->pLeaf->nn ){
  203173. pIter->iEndofDoclist = pIter->pLeaf->nn+1;
  203174. }else{
  203175. int nExtra;
  203176. pIter->iPgidxOff += fts5GetVarint32(&a[pIter->iPgidxOff], nExtra);
  203177. pIter->iEndofDoclist += nExtra;
  203178. }
  203179. fts5SegIterLoadRowid(p, pIter);
  203180. }
  203181. static void fts5SegIterNext(Fts5Index*, Fts5SegIter*, int*);
  203182. static void fts5SegIterNext_Reverse(Fts5Index*, Fts5SegIter*, int*);
  203183. static void fts5SegIterNext_None(Fts5Index*, Fts5SegIter*, int*);
  203184. static void fts5SegIterSetNext(Fts5Index *p, Fts5SegIter *pIter){
  203185. if( pIter->flags & FTS5_SEGITER_REVERSE ){
  203186. pIter->xNext = fts5SegIterNext_Reverse;
  203187. }else if( p->pConfig->eDetail==FTS5_DETAIL_NONE ){
  203188. pIter->xNext = fts5SegIterNext_None;
  203189. }else{
  203190. pIter->xNext = fts5SegIterNext;
  203191. }
  203192. }
  203193. /*
  203194. ** Initialize the iterator object pIter to iterate through the entries in
  203195. ** segment pSeg. The iterator is left pointing to the first entry when
  203196. ** this function returns.
  203197. **
  203198. ** If an error occurs, Fts5Index.rc is set to an appropriate error code. If
  203199. ** an error has already occurred when this function is called, it is a no-op.
  203200. */
  203201. static void fts5SegIterInit(
  203202. Fts5Index *p, /* FTS index object */
  203203. Fts5StructureSegment *pSeg, /* Description of segment */
  203204. Fts5SegIter *pIter /* Object to populate */
  203205. ){
  203206. if( pSeg->pgnoFirst==0 ){
  203207. /* This happens if the segment is being used as an input to an incremental
  203208. ** merge and all data has already been "trimmed". See function
  203209. ** fts5TrimSegments() for details. In this case leave the iterator empty.
  203210. ** The caller will see the (pIter->pLeaf==0) and assume the iterator is
  203211. ** at EOF already. */
  203212. assert( pIter->pLeaf==0 );
  203213. return;
  203214. }
  203215. if( p->rc==SQLITE_OK ){
  203216. memset(pIter, 0, sizeof(*pIter));
  203217. fts5SegIterSetNext(p, pIter);
  203218. pIter->pSeg = pSeg;
  203219. pIter->iLeafPgno = pSeg->pgnoFirst-1;
  203220. fts5SegIterNextPage(p, pIter);
  203221. }
  203222. if( p->rc==SQLITE_OK ){
  203223. pIter->iLeafOffset = 4;
  203224. assert_nc( pIter->pLeaf->nn>4 );
  203225. assert_nc( fts5LeafFirstTermOff(pIter->pLeaf)==4 );
  203226. pIter->iPgidxOff = pIter->pLeaf->szLeaf+1;
  203227. fts5SegIterLoadTerm(p, pIter, 0);
  203228. fts5SegIterLoadNPos(p, pIter);
  203229. }
  203230. }
  203231. /*
  203232. ** This function is only ever called on iterators created by calls to
  203233. ** Fts5IndexQuery() with the FTS5INDEX_QUERY_DESC flag set.
  203234. **
  203235. ** The iterator is in an unusual state when this function is called: the
  203236. ** Fts5SegIter.iLeafOffset variable is set to the offset of the start of
  203237. ** the position-list size field for the first relevant rowid on the page.
  203238. ** Fts5SegIter.rowid is set, but nPos and bDel are not.
  203239. **
  203240. ** This function advances the iterator so that it points to the last
  203241. ** relevant rowid on the page and, if necessary, initializes the
  203242. ** aRowidOffset[] and iRowidOffset variables. At this point the iterator
  203243. ** is in its regular state - Fts5SegIter.iLeafOffset points to the first
  203244. ** byte of the position list content associated with said rowid.
  203245. */
  203246. static void fts5SegIterReverseInitPage(Fts5Index *p, Fts5SegIter *pIter){
  203247. int eDetail = p->pConfig->eDetail;
  203248. int n = pIter->pLeaf->szLeaf;
  203249. int i = pIter->iLeafOffset;
  203250. u8 *a = pIter->pLeaf->p;
  203251. int iRowidOffset = 0;
  203252. if( n>pIter->iEndofDoclist ){
  203253. n = pIter->iEndofDoclist;
  203254. }
  203255. ASSERT_SZLEAF_OK(pIter->pLeaf);
  203256. while( 1 ){
  203257. i64 iDelta = 0;
  203258. if( eDetail==FTS5_DETAIL_NONE ){
  203259. /* todo */
  203260. if( i<n && a[i]==0 ){
  203261. i++;
  203262. if( i<n && a[i]==0 ) i++;
  203263. }
  203264. }else{
  203265. int nPos;
  203266. int bDummy;
  203267. i += fts5GetPoslistSize(&a[i], &nPos, &bDummy);
  203268. i += nPos;
  203269. }
  203270. if( i>=n ) break;
  203271. i += fts5GetVarint(&a[i], (u64*)&iDelta);
  203272. pIter->iRowid += iDelta;
  203273. /* If necessary, grow the pIter->aRowidOffset[] array. */
  203274. if( iRowidOffset>=pIter->nRowidOffset ){
  203275. int nNew = pIter->nRowidOffset + 8;
  203276. int *aNew = (int*)sqlite3_realloc64(pIter->aRowidOffset,nNew*sizeof(int));
  203277. if( aNew==0 ){
  203278. p->rc = SQLITE_NOMEM;
  203279. break;
  203280. }
  203281. pIter->aRowidOffset = aNew;
  203282. pIter->nRowidOffset = nNew;
  203283. }
  203284. pIter->aRowidOffset[iRowidOffset++] = pIter->iLeafOffset;
  203285. pIter->iLeafOffset = i;
  203286. }
  203287. pIter->iRowidOffset = iRowidOffset;
  203288. fts5SegIterLoadNPos(p, pIter);
  203289. }
  203290. /*
  203291. **
  203292. */
  203293. static void fts5SegIterReverseNewPage(Fts5Index *p, Fts5SegIter *pIter){
  203294. assert( pIter->flags & FTS5_SEGITER_REVERSE );
  203295. assert( pIter->flags & FTS5_SEGITER_ONETERM );
  203296. fts5DataRelease(pIter->pLeaf);
  203297. pIter->pLeaf = 0;
  203298. while( p->rc==SQLITE_OK && pIter->iLeafPgno>pIter->iTermLeafPgno ){
  203299. Fts5Data *pNew;
  203300. pIter->iLeafPgno--;
  203301. pNew = fts5DataRead(p, FTS5_SEGMENT_ROWID(
  203302. pIter->pSeg->iSegid, pIter->iLeafPgno
  203303. ));
  203304. if( pNew ){
  203305. /* iTermLeafOffset may be equal to szLeaf if the term is the last
  203306. ** thing on the page - i.e. the first rowid is on the following page.
  203307. ** In this case leave pIter->pLeaf==0, this iterator is at EOF. */
  203308. if( pIter->iLeafPgno==pIter->iTermLeafPgno ){
  203309. assert( pIter->pLeaf==0 );
  203310. if( pIter->iTermLeafOffset<pNew->szLeaf ){
  203311. pIter->pLeaf = pNew;
  203312. pIter->iLeafOffset = pIter->iTermLeafOffset;
  203313. }
  203314. }else{
  203315. int iRowidOff;
  203316. iRowidOff = fts5LeafFirstRowidOff(pNew);
  203317. if( iRowidOff ){
  203318. pIter->pLeaf = pNew;
  203319. pIter->iLeafOffset = iRowidOff;
  203320. }
  203321. }
  203322. if( pIter->pLeaf ){
  203323. u8 *a = &pIter->pLeaf->p[pIter->iLeafOffset];
  203324. pIter->iLeafOffset += fts5GetVarint(a, (u64*)&pIter->iRowid);
  203325. break;
  203326. }else{
  203327. fts5DataRelease(pNew);
  203328. }
  203329. }
  203330. }
  203331. if( pIter->pLeaf ){
  203332. pIter->iEndofDoclist = pIter->pLeaf->nn+1;
  203333. fts5SegIterReverseInitPage(p, pIter);
  203334. }
  203335. }
  203336. /*
  203337. ** Return true if the iterator passed as the second argument currently
  203338. ** points to a delete marker. A delete marker is an entry with a 0 byte
  203339. ** position-list.
  203340. */
  203341. static int fts5MultiIterIsEmpty(Fts5Index *p, Fts5Iter *pIter){
  203342. Fts5SegIter *pSeg = &pIter->aSeg[pIter->aFirst[1].iFirst];
  203343. return (p->rc==SQLITE_OK && pSeg->pLeaf && pSeg->nPos==0);
  203344. }
  203345. /*
  203346. ** Advance iterator pIter to the next entry.
  203347. **
  203348. ** This version of fts5SegIterNext() is only used by reverse iterators.
  203349. */
  203350. static void fts5SegIterNext_Reverse(
  203351. Fts5Index *p, /* FTS5 backend object */
  203352. Fts5SegIter *pIter, /* Iterator to advance */
  203353. int *pbUnused /* Unused */
  203354. ){
  203355. assert( pIter->flags & FTS5_SEGITER_REVERSE );
  203356. assert( pIter->pNextLeaf==0 );
  203357. UNUSED_PARAM(pbUnused);
  203358. if( pIter->iRowidOffset>0 ){
  203359. u8 *a = pIter->pLeaf->p;
  203360. int iOff;
  203361. i64 iDelta;
  203362. pIter->iRowidOffset--;
  203363. pIter->iLeafOffset = pIter->aRowidOffset[pIter->iRowidOffset];
  203364. fts5SegIterLoadNPos(p, pIter);
  203365. iOff = pIter->iLeafOffset;
  203366. if( p->pConfig->eDetail!=FTS5_DETAIL_NONE ){
  203367. iOff += pIter->nPos;
  203368. }
  203369. fts5GetVarint(&a[iOff], (u64*)&iDelta);
  203370. pIter->iRowid -= iDelta;
  203371. }else{
  203372. fts5SegIterReverseNewPage(p, pIter);
  203373. }
  203374. }
  203375. /*
  203376. ** Advance iterator pIter to the next entry.
  203377. **
  203378. ** This version of fts5SegIterNext() is only used if detail=none and the
  203379. ** iterator is not a reverse direction iterator.
  203380. */
  203381. static void fts5SegIterNext_None(
  203382. Fts5Index *p, /* FTS5 backend object */
  203383. Fts5SegIter *pIter, /* Iterator to advance */
  203384. int *pbNewTerm /* OUT: Set for new term */
  203385. ){
  203386. int iOff;
  203387. assert( p->rc==SQLITE_OK );
  203388. assert( (pIter->flags & FTS5_SEGITER_REVERSE)==0 );
  203389. assert( p->pConfig->eDetail==FTS5_DETAIL_NONE );
  203390. ASSERT_SZLEAF_OK(pIter->pLeaf);
  203391. iOff = pIter->iLeafOffset;
  203392. /* Next entry is on the next page */
  203393. if( pIter->pSeg && iOff>=pIter->pLeaf->szLeaf ){
  203394. fts5SegIterNextPage(p, pIter);
  203395. if( p->rc || pIter->pLeaf==0 ) return;
  203396. pIter->iRowid = 0;
  203397. iOff = 4;
  203398. }
  203399. if( iOff<pIter->iEndofDoclist ){
  203400. /* Next entry is on the current page */
  203401. i64 iDelta;
  203402. iOff += sqlite3Fts5GetVarint(&pIter->pLeaf->p[iOff], (u64*)&iDelta);
  203403. pIter->iLeafOffset = iOff;
  203404. pIter->iRowid += iDelta;
  203405. }else if( (pIter->flags & FTS5_SEGITER_ONETERM)==0 ){
  203406. if( pIter->pSeg ){
  203407. int nKeep = 0;
  203408. if( iOff!=fts5LeafFirstTermOff(pIter->pLeaf) ){
  203409. iOff += fts5GetVarint32(&pIter->pLeaf->p[iOff], nKeep);
  203410. }
  203411. pIter->iLeafOffset = iOff;
  203412. fts5SegIterLoadTerm(p, pIter, nKeep);
  203413. }else{
  203414. const u8 *pList = 0;
  203415. const char *zTerm = 0;
  203416. int nList;
  203417. sqlite3Fts5HashScanNext(p->pHash);
  203418. sqlite3Fts5HashScanEntry(p->pHash, &zTerm, &pList, &nList);
  203419. if( pList==0 ) goto next_none_eof;
  203420. pIter->pLeaf->p = (u8*)pList;
  203421. pIter->pLeaf->nn = nList;
  203422. pIter->pLeaf->szLeaf = nList;
  203423. pIter->iEndofDoclist = nList;
  203424. sqlite3Fts5BufferSet(&p->rc,&pIter->term, (int)strlen(zTerm), (u8*)zTerm);
  203425. pIter->iLeafOffset = fts5GetVarint(pList, (u64*)&pIter->iRowid);
  203426. }
  203427. if( pbNewTerm ) *pbNewTerm = 1;
  203428. }else{
  203429. goto next_none_eof;
  203430. }
  203431. fts5SegIterLoadNPos(p, pIter);
  203432. return;
  203433. next_none_eof:
  203434. fts5DataRelease(pIter->pLeaf);
  203435. pIter->pLeaf = 0;
  203436. }
  203437. /*
  203438. ** Advance iterator pIter to the next entry.
  203439. **
  203440. ** If an error occurs, Fts5Index.rc is set to an appropriate error code. It
  203441. ** is not considered an error if the iterator reaches EOF. If an error has
  203442. ** already occurred when this function is called, it is a no-op.
  203443. */
  203444. static void fts5SegIterNext(
  203445. Fts5Index *p, /* FTS5 backend object */
  203446. Fts5SegIter *pIter, /* Iterator to advance */
  203447. int *pbNewTerm /* OUT: Set for new term */
  203448. ){
  203449. Fts5Data *pLeaf = pIter->pLeaf;
  203450. int iOff;
  203451. int bNewTerm = 0;
  203452. int nKeep = 0;
  203453. u8 *a;
  203454. int n;
  203455. assert( pbNewTerm==0 || *pbNewTerm==0 );
  203456. assert( p->pConfig->eDetail!=FTS5_DETAIL_NONE );
  203457. /* Search for the end of the position list within the current page. */
  203458. a = pLeaf->p;
  203459. n = pLeaf->szLeaf;
  203460. ASSERT_SZLEAF_OK(pLeaf);
  203461. iOff = pIter->iLeafOffset + pIter->nPos;
  203462. if( iOff<n ){
  203463. /* The next entry is on the current page. */
  203464. assert_nc( iOff<=pIter->iEndofDoclist );
  203465. if( iOff>=pIter->iEndofDoclist ){
  203466. bNewTerm = 1;
  203467. if( iOff!=fts5LeafFirstTermOff(pLeaf) ){
  203468. iOff += fts5GetVarint32(&a[iOff], nKeep);
  203469. }
  203470. }else{
  203471. u64 iDelta;
  203472. iOff += sqlite3Fts5GetVarint(&a[iOff], &iDelta);
  203473. pIter->iRowid += iDelta;
  203474. assert_nc( iDelta>0 );
  203475. }
  203476. pIter->iLeafOffset = iOff;
  203477. }else if( pIter->pSeg==0 ){
  203478. const u8 *pList = 0;
  203479. const char *zTerm = 0;
  203480. int nList = 0;
  203481. assert( (pIter->flags & FTS5_SEGITER_ONETERM) || pbNewTerm );
  203482. if( 0==(pIter->flags & FTS5_SEGITER_ONETERM) ){
  203483. sqlite3Fts5HashScanNext(p->pHash);
  203484. sqlite3Fts5HashScanEntry(p->pHash, &zTerm, &pList, &nList);
  203485. }
  203486. if( pList==0 ){
  203487. fts5DataRelease(pIter->pLeaf);
  203488. pIter->pLeaf = 0;
  203489. }else{
  203490. pIter->pLeaf->p = (u8*)pList;
  203491. pIter->pLeaf->nn = nList;
  203492. pIter->pLeaf->szLeaf = nList;
  203493. pIter->iEndofDoclist = nList+1;
  203494. sqlite3Fts5BufferSet(&p->rc, &pIter->term, (int)strlen(zTerm),
  203495. (u8*)zTerm);
  203496. pIter->iLeafOffset = fts5GetVarint(pList, (u64*)&pIter->iRowid);
  203497. *pbNewTerm = 1;
  203498. }
  203499. }else{
  203500. iOff = 0;
  203501. /* Next entry is not on the current page */
  203502. while( iOff==0 ){
  203503. fts5SegIterNextPage(p, pIter);
  203504. pLeaf = pIter->pLeaf;
  203505. if( pLeaf==0 ) break;
  203506. ASSERT_SZLEAF_OK(pLeaf);
  203507. if( (iOff = fts5LeafFirstRowidOff(pLeaf)) && iOff<pLeaf->szLeaf ){
  203508. iOff += sqlite3Fts5GetVarint(&pLeaf->p[iOff], (u64*)&pIter->iRowid);
  203509. pIter->iLeafOffset = iOff;
  203510. if( pLeaf->nn>pLeaf->szLeaf ){
  203511. pIter->iPgidxOff = pLeaf->szLeaf + fts5GetVarint32(
  203512. &pLeaf->p[pLeaf->szLeaf], pIter->iEndofDoclist
  203513. );
  203514. }
  203515. }
  203516. else if( pLeaf->nn>pLeaf->szLeaf ){
  203517. pIter->iPgidxOff = pLeaf->szLeaf + fts5GetVarint32(
  203518. &pLeaf->p[pLeaf->szLeaf], iOff
  203519. );
  203520. pIter->iLeafOffset = iOff;
  203521. pIter->iEndofDoclist = iOff;
  203522. bNewTerm = 1;
  203523. }
  203524. assert_nc( iOff<pLeaf->szLeaf );
  203525. if( iOff>pLeaf->szLeaf ){
  203526. p->rc = FTS5_CORRUPT;
  203527. return;
  203528. }
  203529. }
  203530. }
  203531. /* Check if the iterator is now at EOF. If so, return early. */
  203532. if( pIter->pLeaf ){
  203533. if( bNewTerm ){
  203534. if( pIter->flags & FTS5_SEGITER_ONETERM ){
  203535. fts5DataRelease(pIter->pLeaf);
  203536. pIter->pLeaf = 0;
  203537. }else{
  203538. fts5SegIterLoadTerm(p, pIter, nKeep);
  203539. fts5SegIterLoadNPos(p, pIter);
  203540. if( pbNewTerm ) *pbNewTerm = 1;
  203541. }
  203542. }else{
  203543. /* The following could be done by calling fts5SegIterLoadNPos(). But
  203544. ** this block is particularly performance critical, so equivalent
  203545. ** code is inlined.
  203546. **
  203547. ** Later: Switched back to fts5SegIterLoadNPos() because it supports
  203548. ** detail=none mode. Not ideal.
  203549. */
  203550. int nSz;
  203551. assert( p->rc==SQLITE_OK );
  203552. assert( pIter->iLeafOffset<=pIter->pLeaf->nn );
  203553. fts5FastGetVarint32(pIter->pLeaf->p, pIter->iLeafOffset, nSz);
  203554. pIter->bDel = (nSz & 0x0001);
  203555. pIter->nPos = nSz>>1;
  203556. assert_nc( pIter->nPos>=0 );
  203557. }
  203558. }
  203559. }
  203560. #define SWAPVAL(T, a, b) { T tmp; tmp=a; a=b; b=tmp; }
  203561. #define fts5IndexSkipVarint(a, iOff) { \
  203562. int iEnd = iOff+9; \
  203563. while( (a[iOff++] & 0x80) && iOff<iEnd ); \
  203564. }
  203565. /*
  203566. ** Iterator pIter currently points to the first rowid in a doclist. This
  203567. ** function sets the iterator up so that iterates in reverse order through
  203568. ** the doclist.
  203569. */
  203570. static void fts5SegIterReverse(Fts5Index *p, Fts5SegIter *pIter){
  203571. Fts5DlidxIter *pDlidx = pIter->pDlidx;
  203572. Fts5Data *pLast = 0;
  203573. int pgnoLast = 0;
  203574. if( pDlidx ){
  203575. int iSegid = pIter->pSeg->iSegid;
  203576. pgnoLast = fts5DlidxIterPgno(pDlidx);
  203577. pLast = fts5DataRead(p, FTS5_SEGMENT_ROWID(iSegid, pgnoLast));
  203578. }else{
  203579. Fts5Data *pLeaf = pIter->pLeaf; /* Current leaf data */
  203580. /* Currently, Fts5SegIter.iLeafOffset points to the first byte of
  203581. ** position-list content for the current rowid. Back it up so that it
  203582. ** points to the start of the position-list size field. */
  203583. int iPoslist;
  203584. if( pIter->iTermLeafPgno==pIter->iLeafPgno ){
  203585. iPoslist = pIter->iTermLeafOffset;
  203586. }else{
  203587. iPoslist = 4;
  203588. }
  203589. fts5IndexSkipVarint(pLeaf->p, iPoslist);
  203590. pIter->iLeafOffset = iPoslist;
  203591. /* If this condition is true then the largest rowid for the current
  203592. ** term may not be stored on the current page. So search forward to
  203593. ** see where said rowid really is. */
  203594. if( pIter->iEndofDoclist>=pLeaf->szLeaf ){
  203595. int pgno;
  203596. Fts5StructureSegment *pSeg = pIter->pSeg;
  203597. /* The last rowid in the doclist may not be on the current page. Search
  203598. ** forward to find the page containing the last rowid. */
  203599. for(pgno=pIter->iLeafPgno+1; !p->rc && pgno<=pSeg->pgnoLast; pgno++){
  203600. i64 iAbs = FTS5_SEGMENT_ROWID(pSeg->iSegid, pgno);
  203601. Fts5Data *pNew = fts5DataRead(p, iAbs);
  203602. if( pNew ){
  203603. int iRowid, bTermless;
  203604. iRowid = fts5LeafFirstRowidOff(pNew);
  203605. bTermless = fts5LeafIsTermless(pNew);
  203606. if( iRowid ){
  203607. SWAPVAL(Fts5Data*, pNew, pLast);
  203608. pgnoLast = pgno;
  203609. }
  203610. fts5DataRelease(pNew);
  203611. if( bTermless==0 ) break;
  203612. }
  203613. }
  203614. }
  203615. }
  203616. /* If pLast is NULL at this point, then the last rowid for this doclist
  203617. ** lies on the page currently indicated by the iterator. In this case
  203618. ** pIter->iLeafOffset is already set to point to the position-list size
  203619. ** field associated with the first relevant rowid on the page.
  203620. **
  203621. ** Or, if pLast is non-NULL, then it is the page that contains the last
  203622. ** rowid. In this case configure the iterator so that it points to the
  203623. ** first rowid on this page.
  203624. */
  203625. if( pLast ){
  203626. int iOff;
  203627. fts5DataRelease(pIter->pLeaf);
  203628. pIter->pLeaf = pLast;
  203629. pIter->iLeafPgno = pgnoLast;
  203630. iOff = fts5LeafFirstRowidOff(pLast);
  203631. iOff += fts5GetVarint(&pLast->p[iOff], (u64*)&pIter->iRowid);
  203632. pIter->iLeafOffset = iOff;
  203633. if( fts5LeafIsTermless(pLast) ){
  203634. pIter->iEndofDoclist = pLast->nn+1;
  203635. }else{
  203636. pIter->iEndofDoclist = fts5LeafFirstTermOff(pLast);
  203637. }
  203638. }
  203639. fts5SegIterReverseInitPage(p, pIter);
  203640. }
  203641. /*
  203642. ** Iterator pIter currently points to the first rowid of a doclist.
  203643. ** There is a doclist-index associated with the final term on the current
  203644. ** page. If the current term is the last term on the page, load the
  203645. ** doclist-index from disk and initialize an iterator at (pIter->pDlidx).
  203646. */
  203647. static void fts5SegIterLoadDlidx(Fts5Index *p, Fts5SegIter *pIter){
  203648. int iSeg = pIter->pSeg->iSegid;
  203649. int bRev = (pIter->flags & FTS5_SEGITER_REVERSE);
  203650. Fts5Data *pLeaf = pIter->pLeaf; /* Current leaf data */
  203651. assert( pIter->flags & FTS5_SEGITER_ONETERM );
  203652. assert( pIter->pDlidx==0 );
  203653. /* Check if the current doclist ends on this page. If it does, return
  203654. ** early without loading the doclist-index (as it belongs to a different
  203655. ** term. */
  203656. if( pIter->iTermLeafPgno==pIter->iLeafPgno
  203657. && pIter->iEndofDoclist<pLeaf->szLeaf
  203658. ){
  203659. return;
  203660. }
  203661. pIter->pDlidx = fts5DlidxIterInit(p, bRev, iSeg, pIter->iTermLeafPgno);
  203662. }
  203663. /*
  203664. ** The iterator object passed as the second argument currently contains
  203665. ** no valid values except for the Fts5SegIter.pLeaf member variable. This
  203666. ** function searches the leaf page for a term matching (pTerm/nTerm).
  203667. **
  203668. ** If the specified term is found on the page, then the iterator is left
  203669. ** pointing to it. If argument bGe is zero and the term is not found,
  203670. ** the iterator is left pointing at EOF.
  203671. **
  203672. ** If bGe is non-zero and the specified term is not found, then the
  203673. ** iterator is left pointing to the smallest term in the segment that
  203674. ** is larger than the specified term, even if this term is not on the
  203675. ** current page.
  203676. */
  203677. static void fts5LeafSeek(
  203678. Fts5Index *p, /* Leave any error code here */
  203679. int bGe, /* True for a >= search */
  203680. Fts5SegIter *pIter, /* Iterator to seek */
  203681. const u8 *pTerm, int nTerm /* Term to search for */
  203682. ){
  203683. int iOff;
  203684. const u8 *a = pIter->pLeaf->p;
  203685. int szLeaf = pIter->pLeaf->szLeaf;
  203686. int n = pIter->pLeaf->nn;
  203687. u32 nMatch = 0;
  203688. u32 nKeep = 0;
  203689. u32 nNew = 0;
  203690. u32 iTermOff;
  203691. int iPgidx; /* Current offset in pgidx */
  203692. int bEndOfPage = 0;
  203693. assert( p->rc==SQLITE_OK );
  203694. iPgidx = szLeaf;
  203695. iPgidx += fts5GetVarint32(&a[iPgidx], iTermOff);
  203696. iOff = iTermOff;
  203697. if( iOff>n ){
  203698. p->rc = FTS5_CORRUPT;
  203699. return;
  203700. }
  203701. while( 1 ){
  203702. /* Figure out how many new bytes are in this term */
  203703. fts5FastGetVarint32(a, iOff, nNew);
  203704. if( nKeep<nMatch ){
  203705. goto search_failed;
  203706. }
  203707. assert( nKeep>=nMatch );
  203708. if( nKeep==nMatch ){
  203709. u32 nCmp;
  203710. u32 i;
  203711. nCmp = (u32)MIN(nNew, nTerm-nMatch);
  203712. for(i=0; i<nCmp; i++){
  203713. if( a[iOff+i]!=pTerm[nMatch+i] ) break;
  203714. }
  203715. nMatch += i;
  203716. if( (u32)nTerm==nMatch ){
  203717. if( i==nNew ){
  203718. goto search_success;
  203719. }else{
  203720. goto search_failed;
  203721. }
  203722. }else if( i<nNew && a[iOff+i]>pTerm[nMatch] ){
  203723. goto search_failed;
  203724. }
  203725. }
  203726. if( iPgidx>=n ){
  203727. bEndOfPage = 1;
  203728. break;
  203729. }
  203730. iPgidx += fts5GetVarint32(&a[iPgidx], nKeep);
  203731. iTermOff += nKeep;
  203732. iOff = iTermOff;
  203733. if( iOff>=n ){
  203734. p->rc = FTS5_CORRUPT;
  203735. return;
  203736. }
  203737. /* Read the nKeep field of the next term. */
  203738. fts5FastGetVarint32(a, iOff, nKeep);
  203739. }
  203740. search_failed:
  203741. if( bGe==0 ){
  203742. fts5DataRelease(pIter->pLeaf);
  203743. pIter->pLeaf = 0;
  203744. return;
  203745. }else if( bEndOfPage ){
  203746. do {
  203747. fts5SegIterNextPage(p, pIter);
  203748. if( pIter->pLeaf==0 ) return;
  203749. a = pIter->pLeaf->p;
  203750. if( fts5LeafIsTermless(pIter->pLeaf)==0 ){
  203751. iPgidx = pIter->pLeaf->szLeaf;
  203752. iPgidx += fts5GetVarint32(&pIter->pLeaf->p[iPgidx], iOff);
  203753. if( iOff<4 || iOff>=pIter->pLeaf->szLeaf ){
  203754. p->rc = FTS5_CORRUPT;
  203755. return;
  203756. }else{
  203757. nKeep = 0;
  203758. iTermOff = iOff;
  203759. n = pIter->pLeaf->nn;
  203760. iOff += fts5GetVarint32(&a[iOff], nNew);
  203761. break;
  203762. }
  203763. }
  203764. }while( 1 );
  203765. }
  203766. search_success:
  203767. pIter->iLeafOffset = iOff + nNew;
  203768. if( pIter->iLeafOffset>n || nNew<1 ){
  203769. p->rc = FTS5_CORRUPT;
  203770. return;
  203771. }
  203772. pIter->iTermLeafOffset = pIter->iLeafOffset;
  203773. pIter->iTermLeafPgno = pIter->iLeafPgno;
  203774. fts5BufferSet(&p->rc, &pIter->term, nKeep, pTerm);
  203775. fts5BufferAppendBlob(&p->rc, &pIter->term, nNew, &a[iOff]);
  203776. if( iPgidx>=n ){
  203777. pIter->iEndofDoclist = pIter->pLeaf->nn+1;
  203778. }else{
  203779. int nExtra;
  203780. iPgidx += fts5GetVarint32(&a[iPgidx], nExtra);
  203781. pIter->iEndofDoclist = iTermOff + nExtra;
  203782. }
  203783. pIter->iPgidxOff = iPgidx;
  203784. fts5SegIterLoadRowid(p, pIter);
  203785. fts5SegIterLoadNPos(p, pIter);
  203786. }
  203787. static sqlite3_stmt *fts5IdxSelectStmt(Fts5Index *p){
  203788. if( p->pIdxSelect==0 ){
  203789. Fts5Config *pConfig = p->pConfig;
  203790. fts5IndexPrepareStmt(p, &p->pIdxSelect, sqlite3_mprintf(
  203791. "SELECT pgno FROM '%q'.'%q_idx' WHERE "
  203792. "segid=? AND term<=? ORDER BY term DESC LIMIT 1",
  203793. pConfig->zDb, pConfig->zName
  203794. ));
  203795. }
  203796. return p->pIdxSelect;
  203797. }
  203798. /*
  203799. ** Initialize the object pIter to point to term pTerm/nTerm within segment
  203800. ** pSeg. If there is no such term in the index, the iterator is set to EOF.
  203801. **
  203802. ** If an error occurs, Fts5Index.rc is set to an appropriate error code. If
  203803. ** an error has already occurred when this function is called, it is a no-op.
  203804. */
  203805. static void fts5SegIterSeekInit(
  203806. Fts5Index *p, /* FTS5 backend */
  203807. const u8 *pTerm, int nTerm, /* Term to seek to */
  203808. int flags, /* Mask of FTS5INDEX_XXX flags */
  203809. Fts5StructureSegment *pSeg, /* Description of segment */
  203810. Fts5SegIter *pIter /* Object to populate */
  203811. ){
  203812. int iPg = 1;
  203813. int bGe = (flags & FTS5INDEX_QUERY_SCAN);
  203814. int bDlidx = 0; /* True if there is a doclist-index */
  203815. sqlite3_stmt *pIdxSelect = 0;
  203816. assert( bGe==0 || (flags & FTS5INDEX_QUERY_DESC)==0 );
  203817. assert( pTerm && nTerm );
  203818. memset(pIter, 0, sizeof(*pIter));
  203819. pIter->pSeg = pSeg;
  203820. /* This block sets stack variable iPg to the leaf page number that may
  203821. ** contain term (pTerm/nTerm), if it is present in the segment. */
  203822. pIdxSelect = fts5IdxSelectStmt(p);
  203823. if( p->rc ) return;
  203824. sqlite3_bind_int(pIdxSelect, 1, pSeg->iSegid);
  203825. sqlite3_bind_blob(pIdxSelect, 2, pTerm, nTerm, SQLITE_STATIC);
  203826. if( SQLITE_ROW==sqlite3_step(pIdxSelect) ){
  203827. i64 val = sqlite3_column_int(pIdxSelect, 0);
  203828. iPg = (int)(val>>1);
  203829. bDlidx = (val & 0x0001);
  203830. }
  203831. p->rc = sqlite3_reset(pIdxSelect);
  203832. sqlite3_bind_null(pIdxSelect, 2);
  203833. if( iPg<pSeg->pgnoFirst ){
  203834. iPg = pSeg->pgnoFirst;
  203835. bDlidx = 0;
  203836. }
  203837. pIter->iLeafPgno = iPg - 1;
  203838. fts5SegIterNextPage(p, pIter);
  203839. if( pIter->pLeaf ){
  203840. fts5LeafSeek(p, bGe, pIter, pTerm, nTerm);
  203841. }
  203842. if( p->rc==SQLITE_OK && bGe==0 ){
  203843. pIter->flags |= FTS5_SEGITER_ONETERM;
  203844. if( pIter->pLeaf ){
  203845. if( flags & FTS5INDEX_QUERY_DESC ){
  203846. pIter->flags |= FTS5_SEGITER_REVERSE;
  203847. }
  203848. if( bDlidx ){
  203849. fts5SegIterLoadDlidx(p, pIter);
  203850. }
  203851. if( flags & FTS5INDEX_QUERY_DESC ){
  203852. fts5SegIterReverse(p, pIter);
  203853. }
  203854. }
  203855. }
  203856. fts5SegIterSetNext(p, pIter);
  203857. /* Either:
  203858. **
  203859. ** 1) an error has occurred, or
  203860. ** 2) the iterator points to EOF, or
  203861. ** 3) the iterator points to an entry with term (pTerm/nTerm), or
  203862. ** 4) the FTS5INDEX_QUERY_SCAN flag was set and the iterator points
  203863. ** to an entry with a term greater than or equal to (pTerm/nTerm).
  203864. */
  203865. assert_nc( p->rc!=SQLITE_OK /* 1 */
  203866. || pIter->pLeaf==0 /* 2 */
  203867. || fts5BufferCompareBlob(&pIter->term, pTerm, nTerm)==0 /* 3 */
  203868. || (bGe && fts5BufferCompareBlob(&pIter->term, pTerm, nTerm)>0) /* 4 */
  203869. );
  203870. }
  203871. /*
  203872. ** Initialize the object pIter to point to term pTerm/nTerm within the
  203873. ** in-memory hash table. If there is no such term in the hash-table, the
  203874. ** iterator is set to EOF.
  203875. **
  203876. ** If an error occurs, Fts5Index.rc is set to an appropriate error code. If
  203877. ** an error has already occurred when this function is called, it is a no-op.
  203878. */
  203879. static void fts5SegIterHashInit(
  203880. Fts5Index *p, /* FTS5 backend */
  203881. const u8 *pTerm, int nTerm, /* Term to seek to */
  203882. int flags, /* Mask of FTS5INDEX_XXX flags */
  203883. Fts5SegIter *pIter /* Object to populate */
  203884. ){
  203885. int nList = 0;
  203886. const u8 *z = 0;
  203887. int n = 0;
  203888. Fts5Data *pLeaf = 0;
  203889. assert( p->pHash );
  203890. assert( p->rc==SQLITE_OK );
  203891. if( pTerm==0 || (flags & FTS5INDEX_QUERY_SCAN) ){
  203892. const u8 *pList = 0;
  203893. p->rc = sqlite3Fts5HashScanInit(p->pHash, (const char*)pTerm, nTerm);
  203894. sqlite3Fts5HashScanEntry(p->pHash, (const char**)&z, &pList, &nList);
  203895. n = (z ? (int)strlen((const char*)z) : 0);
  203896. if( pList ){
  203897. pLeaf = fts5IdxMalloc(p, sizeof(Fts5Data));
  203898. if( pLeaf ){
  203899. pLeaf->p = (u8*)pList;
  203900. }
  203901. }
  203902. }else{
  203903. p->rc = sqlite3Fts5HashQuery(p->pHash, sizeof(Fts5Data),
  203904. (const char*)pTerm, nTerm, (void**)&pLeaf, &nList
  203905. );
  203906. if( pLeaf ){
  203907. pLeaf->p = (u8*)&pLeaf[1];
  203908. }
  203909. z = pTerm;
  203910. n = nTerm;
  203911. pIter->flags |= FTS5_SEGITER_ONETERM;
  203912. }
  203913. if( pLeaf ){
  203914. sqlite3Fts5BufferSet(&p->rc, &pIter->term, n, z);
  203915. pLeaf->nn = pLeaf->szLeaf = nList;
  203916. pIter->pLeaf = pLeaf;
  203917. pIter->iLeafOffset = fts5GetVarint(pLeaf->p, (u64*)&pIter->iRowid);
  203918. pIter->iEndofDoclist = pLeaf->nn;
  203919. if( flags & FTS5INDEX_QUERY_DESC ){
  203920. pIter->flags |= FTS5_SEGITER_REVERSE;
  203921. fts5SegIterReverseInitPage(p, pIter);
  203922. }else{
  203923. fts5SegIterLoadNPos(p, pIter);
  203924. }
  203925. }
  203926. fts5SegIterSetNext(p, pIter);
  203927. }
  203928. /*
  203929. ** Zero the iterator passed as the only argument.
  203930. */
  203931. static void fts5SegIterClear(Fts5SegIter *pIter){
  203932. fts5BufferFree(&pIter->term);
  203933. fts5DataRelease(pIter->pLeaf);
  203934. fts5DataRelease(pIter->pNextLeaf);
  203935. fts5DlidxIterFree(pIter->pDlidx);
  203936. sqlite3_free(pIter->aRowidOffset);
  203937. memset(pIter, 0, sizeof(Fts5SegIter));
  203938. }
  203939. #ifdef SQLITE_DEBUG
  203940. /*
  203941. ** This function is used as part of the big assert() procedure implemented by
  203942. ** fts5AssertMultiIterSetup(). It ensures that the result currently stored
  203943. ** in *pRes is the correct result of comparing the current positions of the
  203944. ** two iterators.
  203945. */
  203946. static void fts5AssertComparisonResult(
  203947. Fts5Iter *pIter,
  203948. Fts5SegIter *p1,
  203949. Fts5SegIter *p2,
  203950. Fts5CResult *pRes
  203951. ){
  203952. int i1 = p1 - pIter->aSeg;
  203953. int i2 = p2 - pIter->aSeg;
  203954. if( p1->pLeaf || p2->pLeaf ){
  203955. if( p1->pLeaf==0 ){
  203956. assert( pRes->iFirst==i2 );
  203957. }else if( p2->pLeaf==0 ){
  203958. assert( pRes->iFirst==i1 );
  203959. }else{
  203960. int nMin = MIN(p1->term.n, p2->term.n);
  203961. int res = fts5Memcmp(p1->term.p, p2->term.p, nMin);
  203962. if( res==0 ) res = p1->term.n - p2->term.n;
  203963. if( res==0 ){
  203964. assert( pRes->bTermEq==1 );
  203965. assert( p1->iRowid!=p2->iRowid );
  203966. res = ((p1->iRowid > p2->iRowid)==pIter->bRev) ? -1 : 1;
  203967. }else{
  203968. assert( pRes->bTermEq==0 );
  203969. }
  203970. if( res<0 ){
  203971. assert( pRes->iFirst==i1 );
  203972. }else{
  203973. assert( pRes->iFirst==i2 );
  203974. }
  203975. }
  203976. }
  203977. }
  203978. /*
  203979. ** This function is a no-op unless SQLITE_DEBUG is defined when this module
  203980. ** is compiled. In that case, this function is essentially an assert()
  203981. ** statement used to verify that the contents of the pIter->aFirst[] array
  203982. ** are correct.
  203983. */
  203984. static void fts5AssertMultiIterSetup(Fts5Index *p, Fts5Iter *pIter){
  203985. if( p->rc==SQLITE_OK ){
  203986. Fts5SegIter *pFirst = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
  203987. int i;
  203988. assert( (pFirst->pLeaf==0)==pIter->base.bEof );
  203989. /* Check that pIter->iSwitchRowid is set correctly. */
  203990. for(i=0; i<pIter->nSeg; i++){
  203991. Fts5SegIter *p1 = &pIter->aSeg[i];
  203992. assert( p1==pFirst
  203993. || p1->pLeaf==0
  203994. || fts5BufferCompare(&pFirst->term, &p1->term)
  203995. || p1->iRowid==pIter->iSwitchRowid
  203996. || (p1->iRowid<pIter->iSwitchRowid)==pIter->bRev
  203997. );
  203998. }
  203999. for(i=0; i<pIter->nSeg; i+=2){
  204000. Fts5SegIter *p1 = &pIter->aSeg[i];
  204001. Fts5SegIter *p2 = &pIter->aSeg[i+1];
  204002. Fts5CResult *pRes = &pIter->aFirst[(pIter->nSeg + i) / 2];
  204003. fts5AssertComparisonResult(pIter, p1, p2, pRes);
  204004. }
  204005. for(i=1; i<(pIter->nSeg / 2); i+=2){
  204006. Fts5SegIter *p1 = &pIter->aSeg[ pIter->aFirst[i*2].iFirst ];
  204007. Fts5SegIter *p2 = &pIter->aSeg[ pIter->aFirst[i*2+1].iFirst ];
  204008. Fts5CResult *pRes = &pIter->aFirst[i];
  204009. fts5AssertComparisonResult(pIter, p1, p2, pRes);
  204010. }
  204011. }
  204012. }
  204013. #else
  204014. # define fts5AssertMultiIterSetup(x,y)
  204015. #endif
  204016. /*
  204017. ** Do the comparison necessary to populate pIter->aFirst[iOut].
  204018. **
  204019. ** If the returned value is non-zero, then it is the index of an entry
  204020. ** in the pIter->aSeg[] array that is (a) not at EOF, and (b) pointing
  204021. ** to a key that is a duplicate of another, higher priority,
  204022. ** segment-iterator in the pSeg->aSeg[] array.
  204023. */
  204024. static int fts5MultiIterDoCompare(Fts5Iter *pIter, int iOut){
  204025. int i1; /* Index of left-hand Fts5SegIter */
  204026. int i2; /* Index of right-hand Fts5SegIter */
  204027. int iRes;
  204028. Fts5SegIter *p1; /* Left-hand Fts5SegIter */
  204029. Fts5SegIter *p2; /* Right-hand Fts5SegIter */
  204030. Fts5CResult *pRes = &pIter->aFirst[iOut];
  204031. assert( iOut<pIter->nSeg && iOut>0 );
  204032. assert( pIter->bRev==0 || pIter->bRev==1 );
  204033. if( iOut>=(pIter->nSeg/2) ){
  204034. i1 = (iOut - pIter->nSeg/2) * 2;
  204035. i2 = i1 + 1;
  204036. }else{
  204037. i1 = pIter->aFirst[iOut*2].iFirst;
  204038. i2 = pIter->aFirst[iOut*2+1].iFirst;
  204039. }
  204040. p1 = &pIter->aSeg[i1];
  204041. p2 = &pIter->aSeg[i2];
  204042. pRes->bTermEq = 0;
  204043. if( p1->pLeaf==0 ){ /* If p1 is at EOF */
  204044. iRes = i2;
  204045. }else if( p2->pLeaf==0 ){ /* If p2 is at EOF */
  204046. iRes = i1;
  204047. }else{
  204048. int res = fts5BufferCompare(&p1->term, &p2->term);
  204049. if( res==0 ){
  204050. assert_nc( i2>i1 );
  204051. assert_nc( i2!=0 );
  204052. pRes->bTermEq = 1;
  204053. if( p1->iRowid==p2->iRowid ){
  204054. p1->bDel = p2->bDel;
  204055. return i2;
  204056. }
  204057. res = ((p1->iRowid > p2->iRowid)==pIter->bRev) ? -1 : +1;
  204058. }
  204059. assert( res!=0 );
  204060. if( res<0 ){
  204061. iRes = i1;
  204062. }else{
  204063. iRes = i2;
  204064. }
  204065. }
  204066. pRes->iFirst = (u16)iRes;
  204067. return 0;
  204068. }
  204069. /*
  204070. ** Move the seg-iter so that it points to the first rowid on page iLeafPgno.
  204071. ** It is an error if leaf iLeafPgno does not exist or contains no rowids.
  204072. */
  204073. static void fts5SegIterGotoPage(
  204074. Fts5Index *p, /* FTS5 backend object */
  204075. Fts5SegIter *pIter, /* Iterator to advance */
  204076. int iLeafPgno
  204077. ){
  204078. assert( iLeafPgno>pIter->iLeafPgno );
  204079. if( iLeafPgno>pIter->pSeg->pgnoLast ){
  204080. p->rc = FTS5_CORRUPT;
  204081. }else{
  204082. fts5DataRelease(pIter->pNextLeaf);
  204083. pIter->pNextLeaf = 0;
  204084. pIter->iLeafPgno = iLeafPgno-1;
  204085. fts5SegIterNextPage(p, pIter);
  204086. assert( p->rc!=SQLITE_OK || pIter->iLeafPgno==iLeafPgno );
  204087. if( p->rc==SQLITE_OK ){
  204088. int iOff;
  204089. u8 *a = pIter->pLeaf->p;
  204090. int n = pIter->pLeaf->szLeaf;
  204091. iOff = fts5LeafFirstRowidOff(pIter->pLeaf);
  204092. if( iOff<4 || iOff>=n ){
  204093. p->rc = FTS5_CORRUPT;
  204094. }else{
  204095. iOff += fts5GetVarint(&a[iOff], (u64*)&pIter->iRowid);
  204096. pIter->iLeafOffset = iOff;
  204097. fts5SegIterLoadNPos(p, pIter);
  204098. }
  204099. }
  204100. }
  204101. }
  204102. /*
  204103. ** Advance the iterator passed as the second argument until it is at or
  204104. ** past rowid iFrom. Regardless of the value of iFrom, the iterator is
  204105. ** always advanced at least once.
  204106. */
  204107. static void fts5SegIterNextFrom(
  204108. Fts5Index *p, /* FTS5 backend object */
  204109. Fts5SegIter *pIter, /* Iterator to advance */
  204110. i64 iMatch /* Advance iterator at least this far */
  204111. ){
  204112. int bRev = (pIter->flags & FTS5_SEGITER_REVERSE);
  204113. Fts5DlidxIter *pDlidx = pIter->pDlidx;
  204114. int iLeafPgno = pIter->iLeafPgno;
  204115. int bMove = 1;
  204116. assert( pIter->flags & FTS5_SEGITER_ONETERM );
  204117. assert( pIter->pDlidx );
  204118. assert( pIter->pLeaf );
  204119. if( bRev==0 ){
  204120. while( !fts5DlidxIterEof(p, pDlidx) && iMatch>fts5DlidxIterRowid(pDlidx) ){
  204121. iLeafPgno = fts5DlidxIterPgno(pDlidx);
  204122. fts5DlidxIterNext(p, pDlidx);
  204123. }
  204124. assert_nc( iLeafPgno>=pIter->iLeafPgno || p->rc );
  204125. if( iLeafPgno>pIter->iLeafPgno ){
  204126. fts5SegIterGotoPage(p, pIter, iLeafPgno);
  204127. bMove = 0;
  204128. }
  204129. }else{
  204130. assert( pIter->pNextLeaf==0 );
  204131. assert( iMatch<pIter->iRowid );
  204132. while( !fts5DlidxIterEof(p, pDlidx) && iMatch<fts5DlidxIterRowid(pDlidx) ){
  204133. fts5DlidxIterPrev(p, pDlidx);
  204134. }
  204135. iLeafPgno = fts5DlidxIterPgno(pDlidx);
  204136. assert( fts5DlidxIterEof(p, pDlidx) || iLeafPgno<=pIter->iLeafPgno );
  204137. if( iLeafPgno<pIter->iLeafPgno ){
  204138. pIter->iLeafPgno = iLeafPgno+1;
  204139. fts5SegIterReverseNewPage(p, pIter);
  204140. bMove = 0;
  204141. }
  204142. }
  204143. do{
  204144. if( bMove && p->rc==SQLITE_OK ) pIter->xNext(p, pIter, 0);
  204145. if( pIter->pLeaf==0 ) break;
  204146. if( bRev==0 && pIter->iRowid>=iMatch ) break;
  204147. if( bRev!=0 && pIter->iRowid<=iMatch ) break;
  204148. bMove = 1;
  204149. }while( p->rc==SQLITE_OK );
  204150. }
  204151. /*
  204152. ** Free the iterator object passed as the second argument.
  204153. */
  204154. static void fts5MultiIterFree(Fts5Iter *pIter){
  204155. if( pIter ){
  204156. int i;
  204157. for(i=0; i<pIter->nSeg; i++){
  204158. fts5SegIterClear(&pIter->aSeg[i]);
  204159. }
  204160. fts5BufferFree(&pIter->poslist);
  204161. sqlite3_free(pIter);
  204162. }
  204163. }
  204164. static void fts5MultiIterAdvanced(
  204165. Fts5Index *p, /* FTS5 backend to iterate within */
  204166. Fts5Iter *pIter, /* Iterator to update aFirst[] array for */
  204167. int iChanged, /* Index of sub-iterator just advanced */
  204168. int iMinset /* Minimum entry in aFirst[] to set */
  204169. ){
  204170. int i;
  204171. for(i=(pIter->nSeg+iChanged)/2; i>=iMinset && p->rc==SQLITE_OK; i=i/2){
  204172. int iEq;
  204173. if( (iEq = fts5MultiIterDoCompare(pIter, i)) ){
  204174. Fts5SegIter *pSeg = &pIter->aSeg[iEq];
  204175. assert( p->rc==SQLITE_OK );
  204176. pSeg->xNext(p, pSeg, 0);
  204177. i = pIter->nSeg + iEq;
  204178. }
  204179. }
  204180. }
  204181. /*
  204182. ** Sub-iterator iChanged of iterator pIter has just been advanced. It still
  204183. ** points to the same term though - just a different rowid. This function
  204184. ** attempts to update the contents of the pIter->aFirst[] accordingly.
  204185. ** If it does so successfully, 0 is returned. Otherwise 1.
  204186. **
  204187. ** If non-zero is returned, the caller should call fts5MultiIterAdvanced()
  204188. ** on the iterator instead. That function does the same as this one, except
  204189. ** that it deals with more complicated cases as well.
  204190. */
  204191. static int fts5MultiIterAdvanceRowid(
  204192. Fts5Iter *pIter, /* Iterator to update aFirst[] array for */
  204193. int iChanged, /* Index of sub-iterator just advanced */
  204194. Fts5SegIter **ppFirst
  204195. ){
  204196. Fts5SegIter *pNew = &pIter->aSeg[iChanged];
  204197. if( pNew->iRowid==pIter->iSwitchRowid
  204198. || (pNew->iRowid<pIter->iSwitchRowid)==pIter->bRev
  204199. ){
  204200. int i;
  204201. Fts5SegIter *pOther = &pIter->aSeg[iChanged ^ 0x0001];
  204202. pIter->iSwitchRowid = pIter->bRev ? SMALLEST_INT64 : LARGEST_INT64;
  204203. for(i=(pIter->nSeg+iChanged)/2; 1; i=i/2){
  204204. Fts5CResult *pRes = &pIter->aFirst[i];
  204205. assert( pNew->pLeaf );
  204206. assert( pRes->bTermEq==0 || pOther->pLeaf );
  204207. if( pRes->bTermEq ){
  204208. if( pNew->iRowid==pOther->iRowid ){
  204209. return 1;
  204210. }else if( (pOther->iRowid>pNew->iRowid)==pIter->bRev ){
  204211. pIter->iSwitchRowid = pOther->iRowid;
  204212. pNew = pOther;
  204213. }else if( (pOther->iRowid>pIter->iSwitchRowid)==pIter->bRev ){
  204214. pIter->iSwitchRowid = pOther->iRowid;
  204215. }
  204216. }
  204217. pRes->iFirst = (u16)(pNew - pIter->aSeg);
  204218. if( i==1 ) break;
  204219. pOther = &pIter->aSeg[ pIter->aFirst[i ^ 0x0001].iFirst ];
  204220. }
  204221. }
  204222. *ppFirst = pNew;
  204223. return 0;
  204224. }
  204225. /*
  204226. ** Set the pIter->bEof variable based on the state of the sub-iterators.
  204227. */
  204228. static void fts5MultiIterSetEof(Fts5Iter *pIter){
  204229. Fts5SegIter *pSeg = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
  204230. pIter->base.bEof = pSeg->pLeaf==0;
  204231. pIter->iSwitchRowid = pSeg->iRowid;
  204232. }
  204233. /*
  204234. ** Move the iterator to the next entry.
  204235. **
  204236. ** If an error occurs, an error code is left in Fts5Index.rc. It is not
  204237. ** considered an error if the iterator reaches EOF, or if it is already at
  204238. ** EOF when this function is called.
  204239. */
  204240. static void fts5MultiIterNext(
  204241. Fts5Index *p,
  204242. Fts5Iter *pIter,
  204243. int bFrom, /* True if argument iFrom is valid */
  204244. i64 iFrom /* Advance at least as far as this */
  204245. ){
  204246. int bUseFrom = bFrom;
  204247. assert( pIter->base.bEof==0 );
  204248. while( p->rc==SQLITE_OK ){
  204249. int iFirst = pIter->aFirst[1].iFirst;
  204250. int bNewTerm = 0;
  204251. Fts5SegIter *pSeg = &pIter->aSeg[iFirst];
  204252. assert( p->rc==SQLITE_OK );
  204253. if( bUseFrom && pSeg->pDlidx ){
  204254. fts5SegIterNextFrom(p, pSeg, iFrom);
  204255. }else{
  204256. pSeg->xNext(p, pSeg, &bNewTerm);
  204257. }
  204258. if( pSeg->pLeaf==0 || bNewTerm
  204259. || fts5MultiIterAdvanceRowid(pIter, iFirst, &pSeg)
  204260. ){
  204261. fts5MultiIterAdvanced(p, pIter, iFirst, 1);
  204262. fts5MultiIterSetEof(pIter);
  204263. pSeg = &pIter->aSeg[pIter->aFirst[1].iFirst];
  204264. if( pSeg->pLeaf==0 ) return;
  204265. }
  204266. fts5AssertMultiIterSetup(p, pIter);
  204267. assert( pSeg==&pIter->aSeg[pIter->aFirst[1].iFirst] && pSeg->pLeaf );
  204268. if( pIter->bSkipEmpty==0 || pSeg->nPos ){
  204269. pIter->xSetOutputs(pIter, pSeg);
  204270. return;
  204271. }
  204272. bUseFrom = 0;
  204273. }
  204274. }
  204275. static void fts5MultiIterNext2(
  204276. Fts5Index *p,
  204277. Fts5Iter *pIter,
  204278. int *pbNewTerm /* OUT: True if *might* be new term */
  204279. ){
  204280. assert( pIter->bSkipEmpty );
  204281. if( p->rc==SQLITE_OK ){
  204282. *pbNewTerm = 0;
  204283. do{
  204284. int iFirst = pIter->aFirst[1].iFirst;
  204285. Fts5SegIter *pSeg = &pIter->aSeg[iFirst];
  204286. int bNewTerm = 0;
  204287. assert( p->rc==SQLITE_OK );
  204288. pSeg->xNext(p, pSeg, &bNewTerm);
  204289. if( pSeg->pLeaf==0 || bNewTerm
  204290. || fts5MultiIterAdvanceRowid(pIter, iFirst, &pSeg)
  204291. ){
  204292. fts5MultiIterAdvanced(p, pIter, iFirst, 1);
  204293. fts5MultiIterSetEof(pIter);
  204294. *pbNewTerm = 1;
  204295. }
  204296. fts5AssertMultiIterSetup(p, pIter);
  204297. }while( fts5MultiIterIsEmpty(p, pIter) );
  204298. }
  204299. }
  204300. static void fts5IterSetOutputs_Noop(Fts5Iter *pUnused1, Fts5SegIter *pUnused2){
  204301. UNUSED_PARAM2(pUnused1, pUnused2);
  204302. }
  204303. static Fts5Iter *fts5MultiIterAlloc(
  204304. Fts5Index *p, /* FTS5 backend to iterate within */
  204305. int nSeg
  204306. ){
  204307. Fts5Iter *pNew;
  204308. int nSlot; /* Power of two >= nSeg */
  204309. for(nSlot=2; nSlot<nSeg; nSlot=nSlot*2);
  204310. pNew = fts5IdxMalloc(p,
  204311. sizeof(Fts5Iter) + /* pNew */
  204312. sizeof(Fts5SegIter) * (nSlot-1) + /* pNew->aSeg[] */
  204313. sizeof(Fts5CResult) * nSlot /* pNew->aFirst[] */
  204314. );
  204315. if( pNew ){
  204316. pNew->nSeg = nSlot;
  204317. pNew->aFirst = (Fts5CResult*)&pNew->aSeg[nSlot];
  204318. pNew->pIndex = p;
  204319. pNew->xSetOutputs = fts5IterSetOutputs_Noop;
  204320. }
  204321. return pNew;
  204322. }
  204323. static void fts5PoslistCallback(
  204324. Fts5Index *pUnused,
  204325. void *pContext,
  204326. const u8 *pChunk, int nChunk
  204327. ){
  204328. UNUSED_PARAM(pUnused);
  204329. assert_nc( nChunk>=0 );
  204330. if( nChunk>0 ){
  204331. fts5BufferSafeAppendBlob((Fts5Buffer*)pContext, pChunk, nChunk);
  204332. }
  204333. }
  204334. typedef struct PoslistCallbackCtx PoslistCallbackCtx;
  204335. struct PoslistCallbackCtx {
  204336. Fts5Buffer *pBuf; /* Append to this buffer */
  204337. Fts5Colset *pColset; /* Restrict matches to this column */
  204338. int eState; /* See above */
  204339. };
  204340. typedef struct PoslistOffsetsCtx PoslistOffsetsCtx;
  204341. struct PoslistOffsetsCtx {
  204342. Fts5Buffer *pBuf; /* Append to this buffer */
  204343. Fts5Colset *pColset; /* Restrict matches to this column */
  204344. int iRead;
  204345. int iWrite;
  204346. };
  204347. /*
  204348. ** TODO: Make this more efficient!
  204349. */
  204350. static int fts5IndexColsetTest(Fts5Colset *pColset, int iCol){
  204351. int i;
  204352. for(i=0; i<pColset->nCol; i++){
  204353. if( pColset->aiCol[i]==iCol ) return 1;
  204354. }
  204355. return 0;
  204356. }
  204357. static void fts5PoslistOffsetsCallback(
  204358. Fts5Index *pUnused,
  204359. void *pContext,
  204360. const u8 *pChunk, int nChunk
  204361. ){
  204362. PoslistOffsetsCtx *pCtx = (PoslistOffsetsCtx*)pContext;
  204363. UNUSED_PARAM(pUnused);
  204364. assert_nc( nChunk>=0 );
  204365. if( nChunk>0 ){
  204366. int i = 0;
  204367. while( i<nChunk ){
  204368. int iVal;
  204369. i += fts5GetVarint32(&pChunk[i], iVal);
  204370. iVal += pCtx->iRead - 2;
  204371. pCtx->iRead = iVal;
  204372. if( fts5IndexColsetTest(pCtx->pColset, iVal) ){
  204373. fts5BufferSafeAppendVarint(pCtx->pBuf, iVal + 2 - pCtx->iWrite);
  204374. pCtx->iWrite = iVal;
  204375. }
  204376. }
  204377. }
  204378. }
  204379. static void fts5PoslistFilterCallback(
  204380. Fts5Index *pUnused,
  204381. void *pContext,
  204382. const u8 *pChunk, int nChunk
  204383. ){
  204384. PoslistCallbackCtx *pCtx = (PoslistCallbackCtx*)pContext;
  204385. UNUSED_PARAM(pUnused);
  204386. assert_nc( nChunk>=0 );
  204387. if( nChunk>0 ){
  204388. /* Search through to find the first varint with value 1. This is the
  204389. ** start of the next columns hits. */
  204390. int i = 0;
  204391. int iStart = 0;
  204392. if( pCtx->eState==2 ){
  204393. int iCol;
  204394. fts5FastGetVarint32(pChunk, i, iCol);
  204395. if( fts5IndexColsetTest(pCtx->pColset, iCol) ){
  204396. pCtx->eState = 1;
  204397. fts5BufferSafeAppendVarint(pCtx->pBuf, 1);
  204398. }else{
  204399. pCtx->eState = 0;
  204400. }
  204401. }
  204402. do {
  204403. while( i<nChunk && pChunk[i]!=0x01 ){
  204404. while( pChunk[i] & 0x80 ) i++;
  204405. i++;
  204406. }
  204407. if( pCtx->eState ){
  204408. fts5BufferSafeAppendBlob(pCtx->pBuf, &pChunk[iStart], i-iStart);
  204409. }
  204410. if( i<nChunk ){
  204411. int iCol;
  204412. iStart = i;
  204413. i++;
  204414. if( i>=nChunk ){
  204415. pCtx->eState = 2;
  204416. }else{
  204417. fts5FastGetVarint32(pChunk, i, iCol);
  204418. pCtx->eState = fts5IndexColsetTest(pCtx->pColset, iCol);
  204419. if( pCtx->eState ){
  204420. fts5BufferSafeAppendBlob(pCtx->pBuf, &pChunk[iStart], i-iStart);
  204421. iStart = i;
  204422. }
  204423. }
  204424. }
  204425. }while( i<nChunk );
  204426. }
  204427. }
  204428. static void fts5ChunkIterate(
  204429. Fts5Index *p, /* Index object */
  204430. Fts5SegIter *pSeg, /* Poslist of this iterator */
  204431. void *pCtx, /* Context pointer for xChunk callback */
  204432. void (*xChunk)(Fts5Index*, void*, const u8*, int)
  204433. ){
  204434. int nRem = pSeg->nPos; /* Number of bytes still to come */
  204435. Fts5Data *pData = 0;
  204436. u8 *pChunk = &pSeg->pLeaf->p[pSeg->iLeafOffset];
  204437. int nChunk = MIN(nRem, pSeg->pLeaf->szLeaf - pSeg->iLeafOffset);
  204438. int pgno = pSeg->iLeafPgno;
  204439. int pgnoSave = 0;
  204440. /* This function does notmwork with detail=none databases. */
  204441. assert( p->pConfig->eDetail!=FTS5_DETAIL_NONE );
  204442. if( (pSeg->flags & FTS5_SEGITER_REVERSE)==0 ){
  204443. pgnoSave = pgno+1;
  204444. }
  204445. while( 1 ){
  204446. xChunk(p, pCtx, pChunk, nChunk);
  204447. nRem -= nChunk;
  204448. fts5DataRelease(pData);
  204449. if( nRem<=0 ){
  204450. break;
  204451. }else{
  204452. pgno++;
  204453. pData = fts5LeafRead(p, FTS5_SEGMENT_ROWID(pSeg->pSeg->iSegid, pgno));
  204454. if( pData==0 ) break;
  204455. pChunk = &pData->p[4];
  204456. nChunk = MIN(nRem, pData->szLeaf - 4);
  204457. if( pgno==pgnoSave ){
  204458. assert( pSeg->pNextLeaf==0 );
  204459. pSeg->pNextLeaf = pData;
  204460. pData = 0;
  204461. }
  204462. }
  204463. }
  204464. }
  204465. /*
  204466. ** Iterator pIter currently points to a valid entry (not EOF). This
  204467. ** function appends the position list data for the current entry to
  204468. ** buffer pBuf. It does not make a copy of the position-list size
  204469. ** field.
  204470. */
  204471. static void fts5SegiterPoslist(
  204472. Fts5Index *p,
  204473. Fts5SegIter *pSeg,
  204474. Fts5Colset *pColset,
  204475. Fts5Buffer *pBuf
  204476. ){
  204477. if( 0==fts5BufferGrow(&p->rc, pBuf, pSeg->nPos+FTS5_DATA_ZERO_PADDING) ){
  204478. memset(&pBuf->p[pBuf->n+pSeg->nPos], 0, FTS5_DATA_ZERO_PADDING);
  204479. if( pColset==0 ){
  204480. fts5ChunkIterate(p, pSeg, (void*)pBuf, fts5PoslistCallback);
  204481. }else{
  204482. if( p->pConfig->eDetail==FTS5_DETAIL_FULL ){
  204483. PoslistCallbackCtx sCtx;
  204484. sCtx.pBuf = pBuf;
  204485. sCtx.pColset = pColset;
  204486. sCtx.eState = fts5IndexColsetTest(pColset, 0);
  204487. assert( sCtx.eState==0 || sCtx.eState==1 );
  204488. fts5ChunkIterate(p, pSeg, (void*)&sCtx, fts5PoslistFilterCallback);
  204489. }else{
  204490. PoslistOffsetsCtx sCtx;
  204491. memset(&sCtx, 0, sizeof(sCtx));
  204492. sCtx.pBuf = pBuf;
  204493. sCtx.pColset = pColset;
  204494. fts5ChunkIterate(p, pSeg, (void*)&sCtx, fts5PoslistOffsetsCallback);
  204495. }
  204496. }
  204497. }
  204498. }
  204499. /*
  204500. ** IN/OUT parameter (*pa) points to a position list n bytes in size. If
  204501. ** the position list contains entries for column iCol, then (*pa) is set
  204502. ** to point to the sub-position-list for that column and the number of
  204503. ** bytes in it returned. Or, if the argument position list does not
  204504. ** contain any entries for column iCol, return 0.
  204505. */
  204506. static int fts5IndexExtractCol(
  204507. const u8 **pa, /* IN/OUT: Pointer to poslist */
  204508. int n, /* IN: Size of poslist in bytes */
  204509. int iCol /* Column to extract from poslist */
  204510. ){
  204511. int iCurrent = 0; /* Anything before the first 0x01 is col 0 */
  204512. const u8 *p = *pa;
  204513. const u8 *pEnd = &p[n]; /* One byte past end of position list */
  204514. while( iCol>iCurrent ){
  204515. /* Advance pointer p until it points to pEnd or an 0x01 byte that is
  204516. ** not part of a varint. Note that it is not possible for a negative
  204517. ** or extremely large varint to occur within an uncorrupted position
  204518. ** list. So the last byte of each varint may be assumed to have a clear
  204519. ** 0x80 bit. */
  204520. while( *p!=0x01 ){
  204521. while( *p++ & 0x80 );
  204522. if( p>=pEnd ) return 0;
  204523. }
  204524. *pa = p++;
  204525. iCurrent = *p++;
  204526. if( iCurrent & 0x80 ){
  204527. p--;
  204528. p += fts5GetVarint32(p, iCurrent);
  204529. }
  204530. }
  204531. if( iCol!=iCurrent ) return 0;
  204532. /* Advance pointer p until it points to pEnd or an 0x01 byte that is
  204533. ** not part of a varint */
  204534. while( p<pEnd && *p!=0x01 ){
  204535. while( *p++ & 0x80 );
  204536. }
  204537. return p - (*pa);
  204538. }
  204539. static void fts5IndexExtractColset(
  204540. int *pRc,
  204541. Fts5Colset *pColset, /* Colset to filter on */
  204542. const u8 *pPos, int nPos, /* Position list */
  204543. Fts5Buffer *pBuf /* Output buffer */
  204544. ){
  204545. if( *pRc==SQLITE_OK ){
  204546. int i;
  204547. fts5BufferZero(pBuf);
  204548. for(i=0; i<pColset->nCol; i++){
  204549. const u8 *pSub = pPos;
  204550. int nSub = fts5IndexExtractCol(&pSub, nPos, pColset->aiCol[i]);
  204551. if( nSub ){
  204552. fts5BufferAppendBlob(pRc, pBuf, nSub, pSub);
  204553. }
  204554. }
  204555. }
  204556. }
  204557. /*
  204558. ** xSetOutputs callback used by detail=none tables.
  204559. */
  204560. static void fts5IterSetOutputs_None(Fts5Iter *pIter, Fts5SegIter *pSeg){
  204561. assert( pIter->pIndex->pConfig->eDetail==FTS5_DETAIL_NONE );
  204562. pIter->base.iRowid = pSeg->iRowid;
  204563. pIter->base.nData = pSeg->nPos;
  204564. }
  204565. /*
  204566. ** xSetOutputs callback used by detail=full and detail=col tables when no
  204567. ** column filters are specified.
  204568. */
  204569. static void fts5IterSetOutputs_Nocolset(Fts5Iter *pIter, Fts5SegIter *pSeg){
  204570. pIter->base.iRowid = pSeg->iRowid;
  204571. pIter->base.nData = pSeg->nPos;
  204572. assert( pIter->pIndex->pConfig->eDetail!=FTS5_DETAIL_NONE );
  204573. assert( pIter->pColset==0 );
  204574. if( pSeg->iLeafOffset+pSeg->nPos<=pSeg->pLeaf->szLeaf ){
  204575. /* All data is stored on the current page. Populate the output
  204576. ** variables to point into the body of the page object. */
  204577. pIter->base.pData = &pSeg->pLeaf->p[pSeg->iLeafOffset];
  204578. }else{
  204579. /* The data is distributed over two or more pages. Copy it into the
  204580. ** Fts5Iter.poslist buffer and then set the output pointer to point
  204581. ** to this buffer. */
  204582. fts5BufferZero(&pIter->poslist);
  204583. fts5SegiterPoslist(pIter->pIndex, pSeg, 0, &pIter->poslist);
  204584. pIter->base.pData = pIter->poslist.p;
  204585. }
  204586. }
  204587. /*
  204588. ** xSetOutputs callback used when the Fts5Colset object has nCol==0 (match
  204589. ** against no columns at all).
  204590. */
  204591. static void fts5IterSetOutputs_ZeroColset(Fts5Iter *pIter, Fts5SegIter *pSeg){
  204592. UNUSED_PARAM(pSeg);
  204593. pIter->base.nData = 0;
  204594. }
  204595. /*
  204596. ** xSetOutputs callback used by detail=col when there is a column filter
  204597. ** and there are 100 or more columns. Also called as a fallback from
  204598. ** fts5IterSetOutputs_Col100 if the column-list spans more than one page.
  204599. */
  204600. static void fts5IterSetOutputs_Col(Fts5Iter *pIter, Fts5SegIter *pSeg){
  204601. fts5BufferZero(&pIter->poslist);
  204602. fts5SegiterPoslist(pIter->pIndex, pSeg, pIter->pColset, &pIter->poslist);
  204603. pIter->base.iRowid = pSeg->iRowid;
  204604. pIter->base.pData = pIter->poslist.p;
  204605. pIter->base.nData = pIter->poslist.n;
  204606. }
  204607. /*
  204608. ** xSetOutputs callback used when:
  204609. **
  204610. ** * detail=col,
  204611. ** * there is a column filter, and
  204612. ** * the table contains 100 or fewer columns.
  204613. **
  204614. ** The last point is to ensure all column numbers are stored as
  204615. ** single-byte varints.
  204616. */
  204617. static void fts5IterSetOutputs_Col100(Fts5Iter *pIter, Fts5SegIter *pSeg){
  204618. assert( pIter->pIndex->pConfig->eDetail==FTS5_DETAIL_COLUMNS );
  204619. assert( pIter->pColset );
  204620. if( pSeg->iLeafOffset+pSeg->nPos>pSeg->pLeaf->szLeaf ){
  204621. fts5IterSetOutputs_Col(pIter, pSeg);
  204622. }else{
  204623. u8 *a = (u8*)&pSeg->pLeaf->p[pSeg->iLeafOffset];
  204624. u8 *pEnd = (u8*)&a[pSeg->nPos];
  204625. int iPrev = 0;
  204626. int *aiCol = pIter->pColset->aiCol;
  204627. int *aiColEnd = &aiCol[pIter->pColset->nCol];
  204628. u8 *aOut = pIter->poslist.p;
  204629. int iPrevOut = 0;
  204630. pIter->base.iRowid = pSeg->iRowid;
  204631. while( a<pEnd ){
  204632. iPrev += (int)a++[0] - 2;
  204633. while( *aiCol<iPrev ){
  204634. aiCol++;
  204635. if( aiCol==aiColEnd ) goto setoutputs_col_out;
  204636. }
  204637. if( *aiCol==iPrev ){
  204638. *aOut++ = (u8)((iPrev - iPrevOut) + 2);
  204639. iPrevOut = iPrev;
  204640. }
  204641. }
  204642. setoutputs_col_out:
  204643. pIter->base.pData = pIter->poslist.p;
  204644. pIter->base.nData = aOut - pIter->poslist.p;
  204645. }
  204646. }
  204647. /*
  204648. ** xSetOutputs callback used by detail=full when there is a column filter.
  204649. */
  204650. static void fts5IterSetOutputs_Full(Fts5Iter *pIter, Fts5SegIter *pSeg){
  204651. Fts5Colset *pColset = pIter->pColset;
  204652. pIter->base.iRowid = pSeg->iRowid;
  204653. assert( pIter->pIndex->pConfig->eDetail==FTS5_DETAIL_FULL );
  204654. assert( pColset );
  204655. if( pSeg->iLeafOffset+pSeg->nPos<=pSeg->pLeaf->szLeaf ){
  204656. /* All data is stored on the current page. Populate the output
  204657. ** variables to point into the body of the page object. */
  204658. const u8 *a = &pSeg->pLeaf->p[pSeg->iLeafOffset];
  204659. if( pColset->nCol==1 ){
  204660. pIter->base.nData = fts5IndexExtractCol(&a, pSeg->nPos,pColset->aiCol[0]);
  204661. pIter->base.pData = a;
  204662. }else{
  204663. int *pRc = &pIter->pIndex->rc;
  204664. fts5BufferZero(&pIter->poslist);
  204665. fts5IndexExtractColset(pRc, pColset, a, pSeg->nPos, &pIter->poslist);
  204666. pIter->base.pData = pIter->poslist.p;
  204667. pIter->base.nData = pIter->poslist.n;
  204668. }
  204669. }else{
  204670. /* The data is distributed over two or more pages. Copy it into the
  204671. ** Fts5Iter.poslist buffer and then set the output pointer to point
  204672. ** to this buffer. */
  204673. fts5BufferZero(&pIter->poslist);
  204674. fts5SegiterPoslist(pIter->pIndex, pSeg, pColset, &pIter->poslist);
  204675. pIter->base.pData = pIter->poslist.p;
  204676. pIter->base.nData = pIter->poslist.n;
  204677. }
  204678. }
  204679. static void fts5IterSetOutputCb(int *pRc, Fts5Iter *pIter){
  204680. if( *pRc==SQLITE_OK ){
  204681. Fts5Config *pConfig = pIter->pIndex->pConfig;
  204682. if( pConfig->eDetail==FTS5_DETAIL_NONE ){
  204683. pIter->xSetOutputs = fts5IterSetOutputs_None;
  204684. }
  204685. else if( pIter->pColset==0 ){
  204686. pIter->xSetOutputs = fts5IterSetOutputs_Nocolset;
  204687. }
  204688. else if( pIter->pColset->nCol==0 ){
  204689. pIter->xSetOutputs = fts5IterSetOutputs_ZeroColset;
  204690. }
  204691. else if( pConfig->eDetail==FTS5_DETAIL_FULL ){
  204692. pIter->xSetOutputs = fts5IterSetOutputs_Full;
  204693. }
  204694. else{
  204695. assert( pConfig->eDetail==FTS5_DETAIL_COLUMNS );
  204696. if( pConfig->nCol<=100 ){
  204697. pIter->xSetOutputs = fts5IterSetOutputs_Col100;
  204698. sqlite3Fts5BufferSize(pRc, &pIter->poslist, pConfig->nCol);
  204699. }else{
  204700. pIter->xSetOutputs = fts5IterSetOutputs_Col;
  204701. }
  204702. }
  204703. }
  204704. }
  204705. /*
  204706. ** Allocate a new Fts5Iter object.
  204707. **
  204708. ** The new object will be used to iterate through data in structure pStruct.
  204709. ** If iLevel is -ve, then all data in all segments is merged. Or, if iLevel
  204710. ** is zero or greater, data from the first nSegment segments on level iLevel
  204711. ** is merged.
  204712. **
  204713. ** The iterator initially points to the first term/rowid entry in the
  204714. ** iterated data.
  204715. */
  204716. static void fts5MultiIterNew(
  204717. Fts5Index *p, /* FTS5 backend to iterate within */
  204718. Fts5Structure *pStruct, /* Structure of specific index */
  204719. int flags, /* FTS5INDEX_QUERY_XXX flags */
  204720. Fts5Colset *pColset, /* Colset to filter on (or NULL) */
  204721. const u8 *pTerm, int nTerm, /* Term to seek to (or NULL/0) */
  204722. int iLevel, /* Level to iterate (-1 for all) */
  204723. int nSegment, /* Number of segments to merge (iLevel>=0) */
  204724. Fts5Iter **ppOut /* New object */
  204725. ){
  204726. int nSeg = 0; /* Number of segment-iters in use */
  204727. int iIter = 0; /* */
  204728. int iSeg; /* Used to iterate through segments */
  204729. Fts5StructureLevel *pLvl;
  204730. Fts5Iter *pNew;
  204731. assert( (pTerm==0 && nTerm==0) || iLevel<0 );
  204732. /* Allocate space for the new multi-seg-iterator. */
  204733. if( p->rc==SQLITE_OK ){
  204734. if( iLevel<0 ){
  204735. assert( pStruct->nSegment==fts5StructureCountSegments(pStruct) );
  204736. nSeg = pStruct->nSegment;
  204737. nSeg += (p->pHash ? 1 : 0);
  204738. }else{
  204739. nSeg = MIN(pStruct->aLevel[iLevel].nSeg, nSegment);
  204740. }
  204741. }
  204742. *ppOut = pNew = fts5MultiIterAlloc(p, nSeg);
  204743. if( pNew==0 ) return;
  204744. pNew->bRev = (0!=(flags & FTS5INDEX_QUERY_DESC));
  204745. pNew->bSkipEmpty = (0!=(flags & FTS5INDEX_QUERY_SKIPEMPTY));
  204746. pNew->pColset = pColset;
  204747. if( (flags & FTS5INDEX_QUERY_NOOUTPUT)==0 ){
  204748. fts5IterSetOutputCb(&p->rc, pNew);
  204749. }
  204750. /* Initialize each of the component segment iterators. */
  204751. if( p->rc==SQLITE_OK ){
  204752. if( iLevel<0 ){
  204753. Fts5StructureLevel *pEnd = &pStruct->aLevel[pStruct->nLevel];
  204754. if( p->pHash ){
  204755. /* Add a segment iterator for the current contents of the hash table. */
  204756. Fts5SegIter *pIter = &pNew->aSeg[iIter++];
  204757. fts5SegIterHashInit(p, pTerm, nTerm, flags, pIter);
  204758. }
  204759. for(pLvl=&pStruct->aLevel[0]; pLvl<pEnd; pLvl++){
  204760. for(iSeg=pLvl->nSeg-1; iSeg>=0; iSeg--){
  204761. Fts5StructureSegment *pSeg = &pLvl->aSeg[iSeg];
  204762. Fts5SegIter *pIter = &pNew->aSeg[iIter++];
  204763. if( pTerm==0 ){
  204764. fts5SegIterInit(p, pSeg, pIter);
  204765. }else{
  204766. fts5SegIterSeekInit(p, pTerm, nTerm, flags, pSeg, pIter);
  204767. }
  204768. }
  204769. }
  204770. }else{
  204771. pLvl = &pStruct->aLevel[iLevel];
  204772. for(iSeg=nSeg-1; iSeg>=0; iSeg--){
  204773. fts5SegIterInit(p, &pLvl->aSeg[iSeg], &pNew->aSeg[iIter++]);
  204774. }
  204775. }
  204776. assert( iIter==nSeg );
  204777. }
  204778. /* If the above was successful, each component iterators now points
  204779. ** to the first entry in its segment. In this case initialize the
  204780. ** aFirst[] array. Or, if an error has occurred, free the iterator
  204781. ** object and set the output variable to NULL. */
  204782. if( p->rc==SQLITE_OK ){
  204783. for(iIter=pNew->nSeg-1; iIter>0; iIter--){
  204784. int iEq;
  204785. if( (iEq = fts5MultiIterDoCompare(pNew, iIter)) ){
  204786. Fts5SegIter *pSeg = &pNew->aSeg[iEq];
  204787. if( p->rc==SQLITE_OK ) pSeg->xNext(p, pSeg, 0);
  204788. fts5MultiIterAdvanced(p, pNew, iEq, iIter);
  204789. }
  204790. }
  204791. fts5MultiIterSetEof(pNew);
  204792. fts5AssertMultiIterSetup(p, pNew);
  204793. if( pNew->bSkipEmpty && fts5MultiIterIsEmpty(p, pNew) ){
  204794. fts5MultiIterNext(p, pNew, 0, 0);
  204795. }else if( pNew->base.bEof==0 ){
  204796. Fts5SegIter *pSeg = &pNew->aSeg[pNew->aFirst[1].iFirst];
  204797. pNew->xSetOutputs(pNew, pSeg);
  204798. }
  204799. }else{
  204800. fts5MultiIterFree(pNew);
  204801. *ppOut = 0;
  204802. }
  204803. }
  204804. /*
  204805. ** Create an Fts5Iter that iterates through the doclist provided
  204806. ** as the second argument.
  204807. */
  204808. static void fts5MultiIterNew2(
  204809. Fts5Index *p, /* FTS5 backend to iterate within */
  204810. Fts5Data *pData, /* Doclist to iterate through */
  204811. int bDesc, /* True for descending rowid order */
  204812. Fts5Iter **ppOut /* New object */
  204813. ){
  204814. Fts5Iter *pNew;
  204815. pNew = fts5MultiIterAlloc(p, 2);
  204816. if( pNew ){
  204817. Fts5SegIter *pIter = &pNew->aSeg[1];
  204818. pIter->flags = FTS5_SEGITER_ONETERM;
  204819. if( pData->szLeaf>0 ){
  204820. pIter->pLeaf = pData;
  204821. pIter->iLeafOffset = fts5GetVarint(pData->p, (u64*)&pIter->iRowid);
  204822. pIter->iEndofDoclist = pData->nn;
  204823. pNew->aFirst[1].iFirst = 1;
  204824. if( bDesc ){
  204825. pNew->bRev = 1;
  204826. pIter->flags |= FTS5_SEGITER_REVERSE;
  204827. fts5SegIterReverseInitPage(p, pIter);
  204828. }else{
  204829. fts5SegIterLoadNPos(p, pIter);
  204830. }
  204831. pData = 0;
  204832. }else{
  204833. pNew->base.bEof = 1;
  204834. }
  204835. fts5SegIterSetNext(p, pIter);
  204836. *ppOut = pNew;
  204837. }
  204838. fts5DataRelease(pData);
  204839. }
  204840. /*
  204841. ** Return true if the iterator is at EOF or if an error has occurred.
  204842. ** False otherwise.
  204843. */
  204844. static int fts5MultiIterEof(Fts5Index *p, Fts5Iter *pIter){
  204845. assert( p->rc
  204846. || (pIter->aSeg[ pIter->aFirst[1].iFirst ].pLeaf==0)==pIter->base.bEof
  204847. );
  204848. return (p->rc || pIter->base.bEof);
  204849. }
  204850. /*
  204851. ** Return the rowid of the entry that the iterator currently points
  204852. ** to. If the iterator points to EOF when this function is called the
  204853. ** results are undefined.
  204854. */
  204855. static i64 fts5MultiIterRowid(Fts5Iter *pIter){
  204856. assert( pIter->aSeg[ pIter->aFirst[1].iFirst ].pLeaf );
  204857. return pIter->aSeg[ pIter->aFirst[1].iFirst ].iRowid;
  204858. }
  204859. /*
  204860. ** Move the iterator to the next entry at or following iMatch.
  204861. */
  204862. static void fts5MultiIterNextFrom(
  204863. Fts5Index *p,
  204864. Fts5Iter *pIter,
  204865. i64 iMatch
  204866. ){
  204867. while( 1 ){
  204868. i64 iRowid;
  204869. fts5MultiIterNext(p, pIter, 1, iMatch);
  204870. if( fts5MultiIterEof(p, pIter) ) break;
  204871. iRowid = fts5MultiIterRowid(pIter);
  204872. if( pIter->bRev==0 && iRowid>=iMatch ) break;
  204873. if( pIter->bRev!=0 && iRowid<=iMatch ) break;
  204874. }
  204875. }
  204876. /*
  204877. ** Return a pointer to a buffer containing the term associated with the
  204878. ** entry that the iterator currently points to.
  204879. */
  204880. static const u8 *fts5MultiIterTerm(Fts5Iter *pIter, int *pn){
  204881. Fts5SegIter *p = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
  204882. *pn = p->term.n;
  204883. return p->term.p;
  204884. }
  204885. /*
  204886. ** Allocate a new segment-id for the structure pStruct. The new segment
  204887. ** id must be between 1 and 65335 inclusive, and must not be used by
  204888. ** any currently existing segment. If a free segment id cannot be found,
  204889. ** SQLITE_FULL is returned.
  204890. **
  204891. ** If an error has already occurred, this function is a no-op. 0 is
  204892. ** returned in this case.
  204893. */
  204894. static int fts5AllocateSegid(Fts5Index *p, Fts5Structure *pStruct){
  204895. int iSegid = 0;
  204896. if( p->rc==SQLITE_OK ){
  204897. if( pStruct->nSegment>=FTS5_MAX_SEGMENT ){
  204898. p->rc = SQLITE_FULL;
  204899. }else{
  204900. /* FTS5_MAX_SEGMENT is currently defined as 2000. So the following
  204901. ** array is 63 elements, or 252 bytes, in size. */
  204902. u32 aUsed[(FTS5_MAX_SEGMENT+31) / 32];
  204903. int iLvl, iSeg;
  204904. int i;
  204905. u32 mask;
  204906. memset(aUsed, 0, sizeof(aUsed));
  204907. for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
  204908. for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
  204909. int iId = pStruct->aLevel[iLvl].aSeg[iSeg].iSegid;
  204910. if( iId<=FTS5_MAX_SEGMENT && iId>0 ){
  204911. aUsed[(iId-1) / 32] |= (u32)1 << ((iId-1) % 32);
  204912. }
  204913. }
  204914. }
  204915. for(i=0; aUsed[i]==0xFFFFFFFF; i++);
  204916. mask = aUsed[i];
  204917. for(iSegid=0; mask & ((u32)1 << iSegid); iSegid++);
  204918. iSegid += 1 + i*32;
  204919. #ifdef SQLITE_DEBUG
  204920. for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
  204921. for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
  204922. assert_nc( iSegid!=pStruct->aLevel[iLvl].aSeg[iSeg].iSegid );
  204923. }
  204924. }
  204925. assert_nc( iSegid>0 && iSegid<=FTS5_MAX_SEGMENT );
  204926. {
  204927. sqlite3_stmt *pIdxSelect = fts5IdxSelectStmt(p);
  204928. if( p->rc==SQLITE_OK ){
  204929. u8 aBlob[2] = {0xff, 0xff};
  204930. sqlite3_bind_int(pIdxSelect, 1, iSegid);
  204931. sqlite3_bind_blob(pIdxSelect, 2, aBlob, 2, SQLITE_STATIC);
  204932. assert_nc( sqlite3_step(pIdxSelect)!=SQLITE_ROW );
  204933. p->rc = sqlite3_reset(pIdxSelect);
  204934. sqlite3_bind_null(pIdxSelect, 2);
  204935. }
  204936. }
  204937. #endif
  204938. }
  204939. }
  204940. return iSegid;
  204941. }
  204942. /*
  204943. ** Discard all data currently cached in the hash-tables.
  204944. */
  204945. static void fts5IndexDiscardData(Fts5Index *p){
  204946. assert( p->pHash || p->nPendingData==0 );
  204947. if( p->pHash ){
  204948. sqlite3Fts5HashClear(p->pHash);
  204949. p->nPendingData = 0;
  204950. }
  204951. }
  204952. /*
  204953. ** Return the size of the prefix, in bytes, that buffer
  204954. ** (pNew/<length-unknown>) shares with buffer (pOld/nOld).
  204955. **
  204956. ** Buffer (pNew/<length-unknown>) is guaranteed to be greater
  204957. ** than buffer (pOld/nOld).
  204958. */
  204959. static int fts5PrefixCompress(int nOld, const u8 *pOld, const u8 *pNew){
  204960. int i;
  204961. for(i=0; i<nOld; i++){
  204962. if( pOld[i]!=pNew[i] ) break;
  204963. }
  204964. return i;
  204965. }
  204966. static void fts5WriteDlidxClear(
  204967. Fts5Index *p,
  204968. Fts5SegWriter *pWriter,
  204969. int bFlush /* If true, write dlidx to disk */
  204970. ){
  204971. int i;
  204972. assert( bFlush==0 || (pWriter->nDlidx>0 && pWriter->aDlidx[0].buf.n>0) );
  204973. for(i=0; i<pWriter->nDlidx; i++){
  204974. Fts5DlidxWriter *pDlidx = &pWriter->aDlidx[i];
  204975. if( pDlidx->buf.n==0 ) break;
  204976. if( bFlush ){
  204977. assert( pDlidx->pgno!=0 );
  204978. fts5DataWrite(p,
  204979. FTS5_DLIDX_ROWID(pWriter->iSegid, i, pDlidx->pgno),
  204980. pDlidx->buf.p, pDlidx->buf.n
  204981. );
  204982. }
  204983. sqlite3Fts5BufferZero(&pDlidx->buf);
  204984. pDlidx->bPrevValid = 0;
  204985. }
  204986. }
  204987. /*
  204988. ** Grow the pWriter->aDlidx[] array to at least nLvl elements in size.
  204989. ** Any new array elements are zeroed before returning.
  204990. */
  204991. static int fts5WriteDlidxGrow(
  204992. Fts5Index *p,
  204993. Fts5SegWriter *pWriter,
  204994. int nLvl
  204995. ){
  204996. if( p->rc==SQLITE_OK && nLvl>=pWriter->nDlidx ){
  204997. Fts5DlidxWriter *aDlidx = (Fts5DlidxWriter*)sqlite3_realloc64(
  204998. pWriter->aDlidx, sizeof(Fts5DlidxWriter) * nLvl
  204999. );
  205000. if( aDlidx==0 ){
  205001. p->rc = SQLITE_NOMEM;
  205002. }else{
  205003. size_t nByte = sizeof(Fts5DlidxWriter) * (nLvl - pWriter->nDlidx);
  205004. memset(&aDlidx[pWriter->nDlidx], 0, nByte);
  205005. pWriter->aDlidx = aDlidx;
  205006. pWriter->nDlidx = nLvl;
  205007. }
  205008. }
  205009. return p->rc;
  205010. }
  205011. /*
  205012. ** If the current doclist-index accumulating in pWriter->aDlidx[] is large
  205013. ** enough, flush it to disk and return 1. Otherwise discard it and return
  205014. ** zero.
  205015. */
  205016. static int fts5WriteFlushDlidx(Fts5Index *p, Fts5SegWriter *pWriter){
  205017. int bFlag = 0;
  205018. /* If there were FTS5_MIN_DLIDX_SIZE or more empty leaf pages written
  205019. ** to the database, also write the doclist-index to disk. */
  205020. if( pWriter->aDlidx[0].buf.n>0 && pWriter->nEmpty>=FTS5_MIN_DLIDX_SIZE ){
  205021. bFlag = 1;
  205022. }
  205023. fts5WriteDlidxClear(p, pWriter, bFlag);
  205024. pWriter->nEmpty = 0;
  205025. return bFlag;
  205026. }
  205027. /*
  205028. ** This function is called whenever processing of the doclist for the
  205029. ** last term on leaf page (pWriter->iBtPage) is completed.
  205030. **
  205031. ** The doclist-index for that term is currently stored in-memory within the
  205032. ** Fts5SegWriter.aDlidx[] array. If it is large enough, this function
  205033. ** writes it out to disk. Or, if it is too small to bother with, discards
  205034. ** it.
  205035. **
  205036. ** Fts5SegWriter.btterm currently contains the first term on page iBtPage.
  205037. */
  205038. static void fts5WriteFlushBtree(Fts5Index *p, Fts5SegWriter *pWriter){
  205039. int bFlag;
  205040. assert( pWriter->iBtPage || pWriter->nEmpty==0 );
  205041. if( pWriter->iBtPage==0 ) return;
  205042. bFlag = fts5WriteFlushDlidx(p, pWriter);
  205043. if( p->rc==SQLITE_OK ){
  205044. const char *z = (pWriter->btterm.n>0?(const char*)pWriter->btterm.p:"");
  205045. /* The following was already done in fts5WriteInit(): */
  205046. /* sqlite3_bind_int(p->pIdxWriter, 1, pWriter->iSegid); */
  205047. sqlite3_bind_blob(p->pIdxWriter, 2, z, pWriter->btterm.n, SQLITE_STATIC);
  205048. sqlite3_bind_int64(p->pIdxWriter, 3, bFlag + ((i64)pWriter->iBtPage<<1));
  205049. sqlite3_step(p->pIdxWriter);
  205050. p->rc = sqlite3_reset(p->pIdxWriter);
  205051. sqlite3_bind_null(p->pIdxWriter, 2);
  205052. }
  205053. pWriter->iBtPage = 0;
  205054. }
  205055. /*
  205056. ** This is called once for each leaf page except the first that contains
  205057. ** at least one term. Argument (nTerm/pTerm) is the split-key - a term that
  205058. ** is larger than all terms written to earlier leaves, and equal to or
  205059. ** smaller than the first term on the new leaf.
  205060. **
  205061. ** If an error occurs, an error code is left in Fts5Index.rc. If an error
  205062. ** has already occurred when this function is called, it is a no-op.
  205063. */
  205064. static void fts5WriteBtreeTerm(
  205065. Fts5Index *p, /* FTS5 backend object */
  205066. Fts5SegWriter *pWriter, /* Writer object */
  205067. int nTerm, const u8 *pTerm /* First term on new page */
  205068. ){
  205069. fts5WriteFlushBtree(p, pWriter);
  205070. if( p->rc==SQLITE_OK ){
  205071. fts5BufferSet(&p->rc, &pWriter->btterm, nTerm, pTerm);
  205072. pWriter->iBtPage = pWriter->writer.pgno;
  205073. }
  205074. }
  205075. /*
  205076. ** This function is called when flushing a leaf page that contains no
  205077. ** terms at all to disk.
  205078. */
  205079. static void fts5WriteBtreeNoTerm(
  205080. Fts5Index *p, /* FTS5 backend object */
  205081. Fts5SegWriter *pWriter /* Writer object */
  205082. ){
  205083. /* If there were no rowids on the leaf page either and the doclist-index
  205084. ** has already been started, append an 0x00 byte to it. */
  205085. if( pWriter->bFirstRowidInPage && pWriter->aDlidx[0].buf.n>0 ){
  205086. Fts5DlidxWriter *pDlidx = &pWriter->aDlidx[0];
  205087. assert( pDlidx->bPrevValid );
  205088. sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, 0);
  205089. }
  205090. /* Increment the "number of sequential leaves without a term" counter. */
  205091. pWriter->nEmpty++;
  205092. }
  205093. static i64 fts5DlidxExtractFirstRowid(Fts5Buffer *pBuf){
  205094. i64 iRowid;
  205095. int iOff;
  205096. iOff = 1 + fts5GetVarint(&pBuf->p[1], (u64*)&iRowid);
  205097. fts5GetVarint(&pBuf->p[iOff], (u64*)&iRowid);
  205098. return iRowid;
  205099. }
  205100. /*
  205101. ** Rowid iRowid has just been appended to the current leaf page. It is the
  205102. ** first on the page. This function appends an appropriate entry to the current
  205103. ** doclist-index.
  205104. */
  205105. static void fts5WriteDlidxAppend(
  205106. Fts5Index *p,
  205107. Fts5SegWriter *pWriter,
  205108. i64 iRowid
  205109. ){
  205110. int i;
  205111. int bDone = 0;
  205112. for(i=0; p->rc==SQLITE_OK && bDone==0; i++){
  205113. i64 iVal;
  205114. Fts5DlidxWriter *pDlidx = &pWriter->aDlidx[i];
  205115. if( pDlidx->buf.n>=p->pConfig->pgsz ){
  205116. /* The current doclist-index page is full. Write it to disk and push
  205117. ** a copy of iRowid (which will become the first rowid on the next
  205118. ** doclist-index leaf page) up into the next level of the b-tree
  205119. ** hierarchy. If the node being flushed is currently the root node,
  205120. ** also push its first rowid upwards. */
  205121. pDlidx->buf.p[0] = 0x01; /* Not the root node */
  205122. fts5DataWrite(p,
  205123. FTS5_DLIDX_ROWID(pWriter->iSegid, i, pDlidx->pgno),
  205124. pDlidx->buf.p, pDlidx->buf.n
  205125. );
  205126. fts5WriteDlidxGrow(p, pWriter, i+2);
  205127. pDlidx = &pWriter->aDlidx[i];
  205128. if( p->rc==SQLITE_OK && pDlidx[1].buf.n==0 ){
  205129. i64 iFirst = fts5DlidxExtractFirstRowid(&pDlidx->buf);
  205130. /* This was the root node. Push its first rowid up to the new root. */
  205131. pDlidx[1].pgno = pDlidx->pgno;
  205132. sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, 0);
  205133. sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, pDlidx->pgno);
  205134. sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, iFirst);
  205135. pDlidx[1].bPrevValid = 1;
  205136. pDlidx[1].iPrev = iFirst;
  205137. }
  205138. sqlite3Fts5BufferZero(&pDlidx->buf);
  205139. pDlidx->bPrevValid = 0;
  205140. pDlidx->pgno++;
  205141. }else{
  205142. bDone = 1;
  205143. }
  205144. if( pDlidx->bPrevValid ){
  205145. iVal = iRowid - pDlidx->iPrev;
  205146. }else{
  205147. i64 iPgno = (i==0 ? pWriter->writer.pgno : pDlidx[-1].pgno);
  205148. assert( pDlidx->buf.n==0 );
  205149. sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, !bDone);
  205150. sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, iPgno);
  205151. iVal = iRowid;
  205152. }
  205153. sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, iVal);
  205154. pDlidx->bPrevValid = 1;
  205155. pDlidx->iPrev = iRowid;
  205156. }
  205157. }
  205158. static void fts5WriteFlushLeaf(Fts5Index *p, Fts5SegWriter *pWriter){
  205159. static const u8 zero[] = { 0x00, 0x00, 0x00, 0x00 };
  205160. Fts5PageWriter *pPage = &pWriter->writer;
  205161. i64 iRowid;
  205162. assert( (pPage->pgidx.n==0)==(pWriter->bFirstTermInPage) );
  205163. /* Set the szLeaf header field. */
  205164. assert( 0==fts5GetU16(&pPage->buf.p[2]) );
  205165. fts5PutU16(&pPage->buf.p[2], (u16)pPage->buf.n);
  205166. if( pWriter->bFirstTermInPage ){
  205167. /* No term was written to this page. */
  205168. assert( pPage->pgidx.n==0 );
  205169. fts5WriteBtreeNoTerm(p, pWriter);
  205170. }else{
  205171. /* Append the pgidx to the page buffer. Set the szLeaf header field. */
  205172. fts5BufferAppendBlob(&p->rc, &pPage->buf, pPage->pgidx.n, pPage->pgidx.p);
  205173. }
  205174. /* Write the page out to disk */
  205175. iRowid = FTS5_SEGMENT_ROWID(pWriter->iSegid, pPage->pgno);
  205176. fts5DataWrite(p, iRowid, pPage->buf.p, pPage->buf.n);
  205177. /* Initialize the next page. */
  205178. fts5BufferZero(&pPage->buf);
  205179. fts5BufferZero(&pPage->pgidx);
  205180. fts5BufferAppendBlob(&p->rc, &pPage->buf, 4, zero);
  205181. pPage->iPrevPgidx = 0;
  205182. pPage->pgno++;
  205183. /* Increase the leaves written counter */
  205184. pWriter->nLeafWritten++;
  205185. /* The new leaf holds no terms or rowids */
  205186. pWriter->bFirstTermInPage = 1;
  205187. pWriter->bFirstRowidInPage = 1;
  205188. }
  205189. /*
  205190. ** Append term pTerm/nTerm to the segment being written by the writer passed
  205191. ** as the second argument.
  205192. **
  205193. ** If an error occurs, set the Fts5Index.rc error code. If an error has
  205194. ** already occurred, this function is a no-op.
  205195. */
  205196. static void fts5WriteAppendTerm(
  205197. Fts5Index *p,
  205198. Fts5SegWriter *pWriter,
  205199. int nTerm, const u8 *pTerm
  205200. ){
  205201. int nPrefix; /* Bytes of prefix compression for term */
  205202. Fts5PageWriter *pPage = &pWriter->writer;
  205203. Fts5Buffer *pPgidx = &pWriter->writer.pgidx;
  205204. int nMin = MIN(pPage->term.n, nTerm);
  205205. assert( p->rc==SQLITE_OK );
  205206. assert( pPage->buf.n>=4 );
  205207. assert( pPage->buf.n>4 || pWriter->bFirstTermInPage );
  205208. /* If the current leaf page is full, flush it to disk. */
  205209. if( (pPage->buf.n + pPgidx->n + nTerm + 2)>=p->pConfig->pgsz ){
  205210. if( pPage->buf.n>4 ){
  205211. fts5WriteFlushLeaf(p, pWriter);
  205212. if( p->rc!=SQLITE_OK ) return;
  205213. }
  205214. fts5BufferGrow(&p->rc, &pPage->buf, nTerm+FTS5_DATA_PADDING);
  205215. }
  205216. /* TODO1: Updating pgidx here. */
  205217. pPgidx->n += sqlite3Fts5PutVarint(
  205218. &pPgidx->p[pPgidx->n], pPage->buf.n - pPage->iPrevPgidx
  205219. );
  205220. pPage->iPrevPgidx = pPage->buf.n;
  205221. #if 0
  205222. fts5PutU16(&pPgidx->p[pPgidx->n], pPage->buf.n);
  205223. pPgidx->n += 2;
  205224. #endif
  205225. if( pWriter->bFirstTermInPage ){
  205226. nPrefix = 0;
  205227. if( pPage->pgno!=1 ){
  205228. /* This is the first term on a leaf that is not the leftmost leaf in
  205229. ** the segment b-tree. In this case it is necessary to add a term to
  205230. ** the b-tree hierarchy that is (a) larger than the largest term
  205231. ** already written to the segment and (b) smaller than or equal to
  205232. ** this term. In other words, a prefix of (pTerm/nTerm) that is one
  205233. ** byte longer than the longest prefix (pTerm/nTerm) shares with the
  205234. ** previous term.
  205235. **
  205236. ** Usually, the previous term is available in pPage->term. The exception
  205237. ** is if this is the first term written in an incremental-merge step.
  205238. ** In this case the previous term is not available, so just write a
  205239. ** copy of (pTerm/nTerm) into the parent node. This is slightly
  205240. ** inefficient, but still correct. */
  205241. int n = nTerm;
  205242. if( pPage->term.n ){
  205243. n = 1 + fts5PrefixCompress(nMin, pPage->term.p, pTerm);
  205244. }
  205245. fts5WriteBtreeTerm(p, pWriter, n, pTerm);
  205246. if( p->rc!=SQLITE_OK ) return;
  205247. pPage = &pWriter->writer;
  205248. }
  205249. }else{
  205250. nPrefix = fts5PrefixCompress(nMin, pPage->term.p, pTerm);
  205251. fts5BufferAppendVarint(&p->rc, &pPage->buf, nPrefix);
  205252. }
  205253. /* Append the number of bytes of new data, then the term data itself
  205254. ** to the page. */
  205255. fts5BufferAppendVarint(&p->rc, &pPage->buf, nTerm - nPrefix);
  205256. fts5BufferAppendBlob(&p->rc, &pPage->buf, nTerm - nPrefix, &pTerm[nPrefix]);
  205257. /* Update the Fts5PageWriter.term field. */
  205258. fts5BufferSet(&p->rc, &pPage->term, nTerm, pTerm);
  205259. pWriter->bFirstTermInPage = 0;
  205260. pWriter->bFirstRowidInPage = 0;
  205261. pWriter->bFirstRowidInDoclist = 1;
  205262. assert( p->rc || (pWriter->nDlidx>0 && pWriter->aDlidx[0].buf.n==0) );
  205263. pWriter->aDlidx[0].pgno = pPage->pgno;
  205264. }
  205265. /*
  205266. ** Append a rowid and position-list size field to the writers output.
  205267. */
  205268. static void fts5WriteAppendRowid(
  205269. Fts5Index *p,
  205270. Fts5SegWriter *pWriter,
  205271. i64 iRowid
  205272. ){
  205273. if( p->rc==SQLITE_OK ){
  205274. Fts5PageWriter *pPage = &pWriter->writer;
  205275. if( (pPage->buf.n + pPage->pgidx.n)>=p->pConfig->pgsz ){
  205276. fts5WriteFlushLeaf(p, pWriter);
  205277. }
  205278. /* If this is to be the first rowid written to the page, set the
  205279. ** rowid-pointer in the page-header. Also append a value to the dlidx
  205280. ** buffer, in case a doclist-index is required. */
  205281. if( pWriter->bFirstRowidInPage ){
  205282. fts5PutU16(pPage->buf.p, (u16)pPage->buf.n);
  205283. fts5WriteDlidxAppend(p, pWriter, iRowid);
  205284. }
  205285. /* Write the rowid. */
  205286. if( pWriter->bFirstRowidInDoclist || pWriter->bFirstRowidInPage ){
  205287. fts5BufferAppendVarint(&p->rc, &pPage->buf, iRowid);
  205288. }else{
  205289. assert_nc( p->rc || iRowid>pWriter->iPrevRowid );
  205290. fts5BufferAppendVarint(&p->rc, &pPage->buf, iRowid - pWriter->iPrevRowid);
  205291. }
  205292. pWriter->iPrevRowid = iRowid;
  205293. pWriter->bFirstRowidInDoclist = 0;
  205294. pWriter->bFirstRowidInPage = 0;
  205295. }
  205296. }
  205297. static void fts5WriteAppendPoslistData(
  205298. Fts5Index *p,
  205299. Fts5SegWriter *pWriter,
  205300. const u8 *aData,
  205301. int nData
  205302. ){
  205303. Fts5PageWriter *pPage = &pWriter->writer;
  205304. const u8 *a = aData;
  205305. int n = nData;
  205306. assert( p->pConfig->pgsz>0 );
  205307. while( p->rc==SQLITE_OK
  205308. && (pPage->buf.n + pPage->pgidx.n + n)>=p->pConfig->pgsz
  205309. ){
  205310. int nReq = p->pConfig->pgsz - pPage->buf.n - pPage->pgidx.n;
  205311. int nCopy = 0;
  205312. while( nCopy<nReq ){
  205313. i64 dummy;
  205314. nCopy += fts5GetVarint(&a[nCopy], (u64*)&dummy);
  205315. }
  205316. fts5BufferAppendBlob(&p->rc, &pPage->buf, nCopy, a);
  205317. a += nCopy;
  205318. n -= nCopy;
  205319. fts5WriteFlushLeaf(p, pWriter);
  205320. }
  205321. if( n>0 ){
  205322. fts5BufferAppendBlob(&p->rc, &pPage->buf, n, a);
  205323. }
  205324. }
  205325. /*
  205326. ** Flush any data cached by the writer object to the database. Free any
  205327. ** allocations associated with the writer.
  205328. */
  205329. static void fts5WriteFinish(
  205330. Fts5Index *p,
  205331. Fts5SegWriter *pWriter, /* Writer object */
  205332. int *pnLeaf /* OUT: Number of leaf pages in b-tree */
  205333. ){
  205334. int i;
  205335. Fts5PageWriter *pLeaf = &pWriter->writer;
  205336. if( p->rc==SQLITE_OK ){
  205337. assert( pLeaf->pgno>=1 );
  205338. if( pLeaf->buf.n>4 ){
  205339. fts5WriteFlushLeaf(p, pWriter);
  205340. }
  205341. *pnLeaf = pLeaf->pgno-1;
  205342. if( pLeaf->pgno>1 ){
  205343. fts5WriteFlushBtree(p, pWriter);
  205344. }
  205345. }
  205346. fts5BufferFree(&pLeaf->term);
  205347. fts5BufferFree(&pLeaf->buf);
  205348. fts5BufferFree(&pLeaf->pgidx);
  205349. fts5BufferFree(&pWriter->btterm);
  205350. for(i=0; i<pWriter->nDlidx; i++){
  205351. sqlite3Fts5BufferFree(&pWriter->aDlidx[i].buf);
  205352. }
  205353. sqlite3_free(pWriter->aDlidx);
  205354. }
  205355. static void fts5WriteInit(
  205356. Fts5Index *p,
  205357. Fts5SegWriter *pWriter,
  205358. int iSegid
  205359. ){
  205360. const int nBuffer = p->pConfig->pgsz + FTS5_DATA_PADDING;
  205361. memset(pWriter, 0, sizeof(Fts5SegWriter));
  205362. pWriter->iSegid = iSegid;
  205363. fts5WriteDlidxGrow(p, pWriter, 1);
  205364. pWriter->writer.pgno = 1;
  205365. pWriter->bFirstTermInPage = 1;
  205366. pWriter->iBtPage = 1;
  205367. assert( pWriter->writer.buf.n==0 );
  205368. assert( pWriter->writer.pgidx.n==0 );
  205369. /* Grow the two buffers to pgsz + padding bytes in size. */
  205370. sqlite3Fts5BufferSize(&p->rc, &pWriter->writer.pgidx, nBuffer);
  205371. sqlite3Fts5BufferSize(&p->rc, &pWriter->writer.buf, nBuffer);
  205372. if( p->pIdxWriter==0 ){
  205373. Fts5Config *pConfig = p->pConfig;
  205374. fts5IndexPrepareStmt(p, &p->pIdxWriter, sqlite3_mprintf(
  205375. "INSERT INTO '%q'.'%q_idx'(segid,term,pgno) VALUES(?,?,?)",
  205376. pConfig->zDb, pConfig->zName
  205377. ));
  205378. }
  205379. if( p->rc==SQLITE_OK ){
  205380. /* Initialize the 4-byte leaf-page header to 0x00. */
  205381. memset(pWriter->writer.buf.p, 0, 4);
  205382. pWriter->writer.buf.n = 4;
  205383. /* Bind the current output segment id to the index-writer. This is an
  205384. ** optimization over binding the same value over and over as rows are
  205385. ** inserted into %_idx by the current writer. */
  205386. sqlite3_bind_int(p->pIdxWriter, 1, pWriter->iSegid);
  205387. }
  205388. }
  205389. /*
  205390. ** Iterator pIter was used to iterate through the input segments of on an
  205391. ** incremental merge operation. This function is called if the incremental
  205392. ** merge step has finished but the input has not been completely exhausted.
  205393. */
  205394. static void fts5TrimSegments(Fts5Index *p, Fts5Iter *pIter){
  205395. int i;
  205396. Fts5Buffer buf;
  205397. memset(&buf, 0, sizeof(Fts5Buffer));
  205398. for(i=0; i<pIter->nSeg && p->rc==SQLITE_OK; i++){
  205399. Fts5SegIter *pSeg = &pIter->aSeg[i];
  205400. if( pSeg->pSeg==0 ){
  205401. /* no-op */
  205402. }else if( pSeg->pLeaf==0 ){
  205403. /* All keys from this input segment have been transfered to the output.
  205404. ** Set both the first and last page-numbers to 0 to indicate that the
  205405. ** segment is now empty. */
  205406. pSeg->pSeg->pgnoLast = 0;
  205407. pSeg->pSeg->pgnoFirst = 0;
  205408. }else{
  205409. int iOff = pSeg->iTermLeafOffset; /* Offset on new first leaf page */
  205410. i64 iLeafRowid;
  205411. Fts5Data *pData;
  205412. int iId = pSeg->pSeg->iSegid;
  205413. u8 aHdr[4] = {0x00, 0x00, 0x00, 0x00};
  205414. iLeafRowid = FTS5_SEGMENT_ROWID(iId, pSeg->iTermLeafPgno);
  205415. pData = fts5LeafRead(p, iLeafRowid);
  205416. if( pData ){
  205417. if( iOff>pData->szLeaf ){
  205418. /* This can occur if the pages that the segments occupy overlap - if
  205419. ** a single page has been assigned to more than one segment. In
  205420. ** this case a prior iteration of this loop may have corrupted the
  205421. ** segment currently being trimmed. */
  205422. p->rc = FTS5_CORRUPT;
  205423. }else{
  205424. fts5BufferZero(&buf);
  205425. fts5BufferGrow(&p->rc, &buf, pData->nn);
  205426. fts5BufferAppendBlob(&p->rc, &buf, sizeof(aHdr), aHdr);
  205427. fts5BufferAppendVarint(&p->rc, &buf, pSeg->term.n);
  205428. fts5BufferAppendBlob(&p->rc, &buf, pSeg->term.n, pSeg->term.p);
  205429. fts5BufferAppendBlob(&p->rc, &buf, pData->szLeaf-iOff,&pData->p[iOff]);
  205430. if( p->rc==SQLITE_OK ){
  205431. /* Set the szLeaf field */
  205432. fts5PutU16(&buf.p[2], (u16)buf.n);
  205433. }
  205434. /* Set up the new page-index array */
  205435. fts5BufferAppendVarint(&p->rc, &buf, 4);
  205436. if( pSeg->iLeafPgno==pSeg->iTermLeafPgno
  205437. && pSeg->iEndofDoclist<pData->szLeaf
  205438. && pSeg->iPgidxOff<=pData->nn
  205439. ){
  205440. int nDiff = pData->szLeaf - pSeg->iEndofDoclist;
  205441. fts5BufferAppendVarint(&p->rc, &buf, buf.n - 1 - nDiff - 4);
  205442. fts5BufferAppendBlob(&p->rc, &buf,
  205443. pData->nn - pSeg->iPgidxOff, &pData->p[pSeg->iPgidxOff]
  205444. );
  205445. }
  205446. pSeg->pSeg->pgnoFirst = pSeg->iTermLeafPgno;
  205447. fts5DataDelete(p, FTS5_SEGMENT_ROWID(iId, 1), iLeafRowid);
  205448. fts5DataWrite(p, iLeafRowid, buf.p, buf.n);
  205449. }
  205450. fts5DataRelease(pData);
  205451. }
  205452. }
  205453. }
  205454. fts5BufferFree(&buf);
  205455. }
  205456. static void fts5MergeChunkCallback(
  205457. Fts5Index *p,
  205458. void *pCtx,
  205459. const u8 *pChunk, int nChunk
  205460. ){
  205461. Fts5SegWriter *pWriter = (Fts5SegWriter*)pCtx;
  205462. fts5WriteAppendPoslistData(p, pWriter, pChunk, nChunk);
  205463. }
  205464. /*
  205465. **
  205466. */
  205467. static void fts5IndexMergeLevel(
  205468. Fts5Index *p, /* FTS5 backend object */
  205469. Fts5Structure **ppStruct, /* IN/OUT: Stucture of index */
  205470. int iLvl, /* Level to read input from */
  205471. int *pnRem /* Write up to this many output leaves */
  205472. ){
  205473. Fts5Structure *pStruct = *ppStruct;
  205474. Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
  205475. Fts5StructureLevel *pLvlOut;
  205476. Fts5Iter *pIter = 0; /* Iterator to read input data */
  205477. int nRem = pnRem ? *pnRem : 0; /* Output leaf pages left to write */
  205478. int nInput; /* Number of input segments */
  205479. Fts5SegWriter writer; /* Writer object */
  205480. Fts5StructureSegment *pSeg; /* Output segment */
  205481. Fts5Buffer term;
  205482. int bOldest; /* True if the output segment is the oldest */
  205483. int eDetail = p->pConfig->eDetail;
  205484. const int flags = FTS5INDEX_QUERY_NOOUTPUT;
  205485. int bTermWritten = 0; /* True if current term already output */
  205486. assert( iLvl<pStruct->nLevel );
  205487. assert( pLvl->nMerge<=pLvl->nSeg );
  205488. memset(&writer, 0, sizeof(Fts5SegWriter));
  205489. memset(&term, 0, sizeof(Fts5Buffer));
  205490. if( pLvl->nMerge ){
  205491. pLvlOut = &pStruct->aLevel[iLvl+1];
  205492. assert( pLvlOut->nSeg>0 );
  205493. nInput = pLvl->nMerge;
  205494. pSeg = &pLvlOut->aSeg[pLvlOut->nSeg-1];
  205495. fts5WriteInit(p, &writer, pSeg->iSegid);
  205496. writer.writer.pgno = pSeg->pgnoLast+1;
  205497. writer.iBtPage = 0;
  205498. }else{
  205499. int iSegid = fts5AllocateSegid(p, pStruct);
  205500. /* Extend the Fts5Structure object as required to ensure the output
  205501. ** segment exists. */
  205502. if( iLvl==pStruct->nLevel-1 ){
  205503. fts5StructureAddLevel(&p->rc, ppStruct);
  205504. pStruct = *ppStruct;
  205505. }
  205506. fts5StructureExtendLevel(&p->rc, pStruct, iLvl+1, 1, 0);
  205507. if( p->rc ) return;
  205508. pLvl = &pStruct->aLevel[iLvl];
  205509. pLvlOut = &pStruct->aLevel[iLvl+1];
  205510. fts5WriteInit(p, &writer, iSegid);
  205511. /* Add the new segment to the output level */
  205512. pSeg = &pLvlOut->aSeg[pLvlOut->nSeg];
  205513. pLvlOut->nSeg++;
  205514. pSeg->pgnoFirst = 1;
  205515. pSeg->iSegid = iSegid;
  205516. pStruct->nSegment++;
  205517. /* Read input from all segments in the input level */
  205518. nInput = pLvl->nSeg;
  205519. }
  205520. bOldest = (pLvlOut->nSeg==1 && pStruct->nLevel==iLvl+2);
  205521. assert( iLvl>=0 );
  205522. for(fts5MultiIterNew(p, pStruct, flags, 0, 0, 0, iLvl, nInput, &pIter);
  205523. fts5MultiIterEof(p, pIter)==0;
  205524. fts5MultiIterNext(p, pIter, 0, 0)
  205525. ){
  205526. Fts5SegIter *pSegIter = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
  205527. int nPos; /* position-list size field value */
  205528. int nTerm;
  205529. const u8 *pTerm;
  205530. pTerm = fts5MultiIterTerm(pIter, &nTerm);
  205531. if( nTerm!=term.n || fts5Memcmp(pTerm, term.p, nTerm) ){
  205532. if( pnRem && writer.nLeafWritten>nRem ){
  205533. break;
  205534. }
  205535. fts5BufferSet(&p->rc, &term, nTerm, pTerm);
  205536. bTermWritten =0;
  205537. }
  205538. /* Check for key annihilation. */
  205539. if( pSegIter->nPos==0 && (bOldest || pSegIter->bDel==0) ) continue;
  205540. if( p->rc==SQLITE_OK && bTermWritten==0 ){
  205541. /* This is a new term. Append a term to the output segment. */
  205542. fts5WriteAppendTerm(p, &writer, nTerm, pTerm);
  205543. bTermWritten = 1;
  205544. }
  205545. /* Append the rowid to the output */
  205546. /* WRITEPOSLISTSIZE */
  205547. fts5WriteAppendRowid(p, &writer, fts5MultiIterRowid(pIter));
  205548. if( eDetail==FTS5_DETAIL_NONE ){
  205549. if( pSegIter->bDel ){
  205550. fts5BufferAppendVarint(&p->rc, &writer.writer.buf, 0);
  205551. if( pSegIter->nPos>0 ){
  205552. fts5BufferAppendVarint(&p->rc, &writer.writer.buf, 0);
  205553. }
  205554. }
  205555. }else{
  205556. /* Append the position-list data to the output */
  205557. nPos = pSegIter->nPos*2 + pSegIter->bDel;
  205558. fts5BufferAppendVarint(&p->rc, &writer.writer.buf, nPos);
  205559. fts5ChunkIterate(p, pSegIter, (void*)&writer, fts5MergeChunkCallback);
  205560. }
  205561. }
  205562. /* Flush the last leaf page to disk. Set the output segment b-tree height
  205563. ** and last leaf page number at the same time. */
  205564. fts5WriteFinish(p, &writer, &pSeg->pgnoLast);
  205565. if( fts5MultiIterEof(p, pIter) ){
  205566. int i;
  205567. /* Remove the redundant segments from the %_data table */
  205568. for(i=0; i<nInput; i++){
  205569. fts5DataRemoveSegment(p, pLvl->aSeg[i].iSegid);
  205570. }
  205571. /* Remove the redundant segments from the input level */
  205572. if( pLvl->nSeg!=nInput ){
  205573. int nMove = (pLvl->nSeg - nInput) * sizeof(Fts5StructureSegment);
  205574. memmove(pLvl->aSeg, &pLvl->aSeg[nInput], nMove);
  205575. }
  205576. pStruct->nSegment -= nInput;
  205577. pLvl->nSeg -= nInput;
  205578. pLvl->nMerge = 0;
  205579. if( pSeg->pgnoLast==0 ){
  205580. pLvlOut->nSeg--;
  205581. pStruct->nSegment--;
  205582. }
  205583. }else{
  205584. assert( pSeg->pgnoLast>0 );
  205585. fts5TrimSegments(p, pIter);
  205586. pLvl->nMerge = nInput;
  205587. }
  205588. fts5MultiIterFree(pIter);
  205589. fts5BufferFree(&term);
  205590. if( pnRem ) *pnRem -= writer.nLeafWritten;
  205591. }
  205592. /*
  205593. ** Do up to nPg pages of automerge work on the index.
  205594. **
  205595. ** Return true if any changes were actually made, or false otherwise.
  205596. */
  205597. static int fts5IndexMerge(
  205598. Fts5Index *p, /* FTS5 backend object */
  205599. Fts5Structure **ppStruct, /* IN/OUT: Current structure of index */
  205600. int nPg, /* Pages of work to do */
  205601. int nMin /* Minimum number of segments to merge */
  205602. ){
  205603. int nRem = nPg;
  205604. int bRet = 0;
  205605. Fts5Structure *pStruct = *ppStruct;
  205606. while( nRem>0 && p->rc==SQLITE_OK ){
  205607. int iLvl; /* To iterate through levels */
  205608. int iBestLvl = 0; /* Level offering the most input segments */
  205609. int nBest = 0; /* Number of input segments on best level */
  205610. /* Set iBestLvl to the level to read input segments from. */
  205611. assert( pStruct->nLevel>0 );
  205612. for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
  205613. Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
  205614. if( pLvl->nMerge ){
  205615. if( pLvl->nMerge>nBest ){
  205616. iBestLvl = iLvl;
  205617. nBest = pLvl->nMerge;
  205618. }
  205619. break;
  205620. }
  205621. if( pLvl->nSeg>nBest ){
  205622. nBest = pLvl->nSeg;
  205623. iBestLvl = iLvl;
  205624. }
  205625. }
  205626. /* If nBest is still 0, then the index must be empty. */
  205627. #ifdef SQLITE_DEBUG
  205628. for(iLvl=0; nBest==0 && iLvl<pStruct->nLevel; iLvl++){
  205629. assert( pStruct->aLevel[iLvl].nSeg==0 );
  205630. }
  205631. #endif
  205632. if( nBest<nMin && pStruct->aLevel[iBestLvl].nMerge==0 ){
  205633. break;
  205634. }
  205635. bRet = 1;
  205636. fts5IndexMergeLevel(p, &pStruct, iBestLvl, &nRem);
  205637. if( p->rc==SQLITE_OK && pStruct->aLevel[iBestLvl].nMerge==0 ){
  205638. fts5StructurePromote(p, iBestLvl+1, pStruct);
  205639. }
  205640. }
  205641. *ppStruct = pStruct;
  205642. return bRet;
  205643. }
  205644. /*
  205645. ** A total of nLeaf leaf pages of data has just been flushed to a level-0
  205646. ** segment. This function updates the write-counter accordingly and, if
  205647. ** necessary, performs incremental merge work.
  205648. **
  205649. ** If an error occurs, set the Fts5Index.rc error code. If an error has
  205650. ** already occurred, this function is a no-op.
  205651. */
  205652. static void fts5IndexAutomerge(
  205653. Fts5Index *p, /* FTS5 backend object */
  205654. Fts5Structure **ppStruct, /* IN/OUT: Current structure of index */
  205655. int nLeaf /* Number of output leaves just written */
  205656. ){
  205657. if( p->rc==SQLITE_OK && p->pConfig->nAutomerge>0 ){
  205658. Fts5Structure *pStruct = *ppStruct;
  205659. u64 nWrite; /* Initial value of write-counter */
  205660. int nWork; /* Number of work-quanta to perform */
  205661. int nRem; /* Number of leaf pages left to write */
  205662. /* Update the write-counter. While doing so, set nWork. */
  205663. nWrite = pStruct->nWriteCounter;
  205664. nWork = (int)(((nWrite + nLeaf) / p->nWorkUnit) - (nWrite / p->nWorkUnit));
  205665. pStruct->nWriteCounter += nLeaf;
  205666. nRem = (int)(p->nWorkUnit * nWork * pStruct->nLevel);
  205667. fts5IndexMerge(p, ppStruct, nRem, p->pConfig->nAutomerge);
  205668. }
  205669. }
  205670. static void fts5IndexCrisismerge(
  205671. Fts5Index *p, /* FTS5 backend object */
  205672. Fts5Structure **ppStruct /* IN/OUT: Current structure of index */
  205673. ){
  205674. const int nCrisis = p->pConfig->nCrisisMerge;
  205675. Fts5Structure *pStruct = *ppStruct;
  205676. int iLvl = 0;
  205677. assert( p->rc!=SQLITE_OK || pStruct->nLevel>0 );
  205678. while( p->rc==SQLITE_OK && pStruct->aLevel[iLvl].nSeg>=nCrisis ){
  205679. fts5IndexMergeLevel(p, &pStruct, iLvl, 0);
  205680. assert( p->rc!=SQLITE_OK || pStruct->nLevel>(iLvl+1) );
  205681. fts5StructurePromote(p, iLvl+1, pStruct);
  205682. iLvl++;
  205683. }
  205684. *ppStruct = pStruct;
  205685. }
  205686. static int fts5IndexReturn(Fts5Index *p){
  205687. int rc = p->rc;
  205688. p->rc = SQLITE_OK;
  205689. return rc;
  205690. }
  205691. typedef struct Fts5FlushCtx Fts5FlushCtx;
  205692. struct Fts5FlushCtx {
  205693. Fts5Index *pIdx;
  205694. Fts5SegWriter writer;
  205695. };
  205696. /*
  205697. ** Buffer aBuf[] contains a list of varints, all small enough to fit
  205698. ** in a 32-bit integer. Return the size of the largest prefix of this
  205699. ** list nMax bytes or less in size.
  205700. */
  205701. static int fts5PoslistPrefix(const u8 *aBuf, int nMax){
  205702. int ret;
  205703. u32 dummy;
  205704. ret = fts5GetVarint32(aBuf, dummy);
  205705. if( ret<nMax ){
  205706. while( 1 ){
  205707. int i = fts5GetVarint32(&aBuf[ret], dummy);
  205708. if( (ret + i) > nMax ) break;
  205709. ret += i;
  205710. }
  205711. }
  205712. return ret;
  205713. }
  205714. /*
  205715. ** Flush the contents of in-memory hash table iHash to a new level-0
  205716. ** segment on disk. Also update the corresponding structure record.
  205717. **
  205718. ** If an error occurs, set the Fts5Index.rc error code. If an error has
  205719. ** already occurred, this function is a no-op.
  205720. */
  205721. static void fts5FlushOneHash(Fts5Index *p){
  205722. Fts5Hash *pHash = p->pHash;
  205723. Fts5Structure *pStruct;
  205724. int iSegid;
  205725. int pgnoLast = 0; /* Last leaf page number in segment */
  205726. /* Obtain a reference to the index structure and allocate a new segment-id
  205727. ** for the new level-0 segment. */
  205728. pStruct = fts5StructureRead(p);
  205729. iSegid = fts5AllocateSegid(p, pStruct);
  205730. fts5StructureInvalidate(p);
  205731. if( iSegid ){
  205732. const int pgsz = p->pConfig->pgsz;
  205733. int eDetail = p->pConfig->eDetail;
  205734. Fts5StructureSegment *pSeg; /* New segment within pStruct */
  205735. Fts5Buffer *pBuf; /* Buffer in which to assemble leaf page */
  205736. Fts5Buffer *pPgidx; /* Buffer in which to assemble pgidx */
  205737. Fts5SegWriter writer;
  205738. fts5WriteInit(p, &writer, iSegid);
  205739. pBuf = &writer.writer.buf;
  205740. pPgidx = &writer.writer.pgidx;
  205741. /* fts5WriteInit() should have initialized the buffers to (most likely)
  205742. ** the maximum space required. */
  205743. assert( p->rc || pBuf->nSpace>=(pgsz + FTS5_DATA_PADDING) );
  205744. assert( p->rc || pPgidx->nSpace>=(pgsz + FTS5_DATA_PADDING) );
  205745. /* Begin scanning through hash table entries. This loop runs once for each
  205746. ** term/doclist currently stored within the hash table. */
  205747. if( p->rc==SQLITE_OK ){
  205748. p->rc = sqlite3Fts5HashScanInit(pHash, 0, 0);
  205749. }
  205750. while( p->rc==SQLITE_OK && 0==sqlite3Fts5HashScanEof(pHash) ){
  205751. const char *zTerm; /* Buffer containing term */
  205752. const u8 *pDoclist; /* Pointer to doclist for this term */
  205753. int nDoclist; /* Size of doclist in bytes */
  205754. /* Write the term for this entry to disk. */
  205755. sqlite3Fts5HashScanEntry(pHash, &zTerm, &pDoclist, &nDoclist);
  205756. fts5WriteAppendTerm(p, &writer, (int)strlen(zTerm), (const u8*)zTerm);
  205757. if( p->rc!=SQLITE_OK ) break;
  205758. assert( writer.bFirstRowidInPage==0 );
  205759. if( pgsz>=(pBuf->n + pPgidx->n + nDoclist + 1) ){
  205760. /* The entire doclist will fit on the current leaf. */
  205761. fts5BufferSafeAppendBlob(pBuf, pDoclist, nDoclist);
  205762. }else{
  205763. i64 iRowid = 0;
  205764. i64 iDelta = 0;
  205765. int iOff = 0;
  205766. /* The entire doclist will not fit on this leaf. The following
  205767. ** loop iterates through the poslists that make up the current
  205768. ** doclist. */
  205769. while( p->rc==SQLITE_OK && iOff<nDoclist ){
  205770. iOff += fts5GetVarint(&pDoclist[iOff], (u64*)&iDelta);
  205771. iRowid += iDelta;
  205772. if( writer.bFirstRowidInPage ){
  205773. fts5PutU16(&pBuf->p[0], (u16)pBuf->n); /* first rowid on page */
  205774. pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iRowid);
  205775. writer.bFirstRowidInPage = 0;
  205776. fts5WriteDlidxAppend(p, &writer, iRowid);
  205777. if( p->rc!=SQLITE_OK ) break;
  205778. }else{
  205779. pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iDelta);
  205780. }
  205781. assert( pBuf->n<=pBuf->nSpace );
  205782. if( eDetail==FTS5_DETAIL_NONE ){
  205783. if( iOff<nDoclist && pDoclist[iOff]==0 ){
  205784. pBuf->p[pBuf->n++] = 0;
  205785. iOff++;
  205786. if( iOff<nDoclist && pDoclist[iOff]==0 ){
  205787. pBuf->p[pBuf->n++] = 0;
  205788. iOff++;
  205789. }
  205790. }
  205791. if( (pBuf->n + pPgidx->n)>=pgsz ){
  205792. fts5WriteFlushLeaf(p, &writer);
  205793. }
  205794. }else{
  205795. int bDummy;
  205796. int nPos;
  205797. int nCopy = fts5GetPoslistSize(&pDoclist[iOff], &nPos, &bDummy);
  205798. nCopy += nPos;
  205799. if( (pBuf->n + pPgidx->n + nCopy) <= pgsz ){
  205800. /* The entire poslist will fit on the current leaf. So copy
  205801. ** it in one go. */
  205802. fts5BufferSafeAppendBlob(pBuf, &pDoclist[iOff], nCopy);
  205803. }else{
  205804. /* The entire poslist will not fit on this leaf. So it needs
  205805. ** to be broken into sections. The only qualification being
  205806. ** that each varint must be stored contiguously. */
  205807. const u8 *pPoslist = &pDoclist[iOff];
  205808. int iPos = 0;
  205809. while( p->rc==SQLITE_OK ){
  205810. int nSpace = pgsz - pBuf->n - pPgidx->n;
  205811. int n = 0;
  205812. if( (nCopy - iPos)<=nSpace ){
  205813. n = nCopy - iPos;
  205814. }else{
  205815. n = fts5PoslistPrefix(&pPoslist[iPos], nSpace);
  205816. }
  205817. assert( n>0 );
  205818. fts5BufferSafeAppendBlob(pBuf, &pPoslist[iPos], n);
  205819. iPos += n;
  205820. if( (pBuf->n + pPgidx->n)>=pgsz ){
  205821. fts5WriteFlushLeaf(p, &writer);
  205822. }
  205823. if( iPos>=nCopy ) break;
  205824. }
  205825. }
  205826. iOff += nCopy;
  205827. }
  205828. }
  205829. }
  205830. /* TODO2: Doclist terminator written here. */
  205831. /* pBuf->p[pBuf->n++] = '\0'; */
  205832. assert( pBuf->n<=pBuf->nSpace );
  205833. if( p->rc==SQLITE_OK ) sqlite3Fts5HashScanNext(pHash);
  205834. }
  205835. sqlite3Fts5HashClear(pHash);
  205836. fts5WriteFinish(p, &writer, &pgnoLast);
  205837. /* Update the Fts5Structure. It is written back to the database by the
  205838. ** fts5StructureRelease() call below. */
  205839. if( pStruct->nLevel==0 ){
  205840. fts5StructureAddLevel(&p->rc, &pStruct);
  205841. }
  205842. fts5StructureExtendLevel(&p->rc, pStruct, 0, 1, 0);
  205843. if( p->rc==SQLITE_OK ){
  205844. pSeg = &pStruct->aLevel[0].aSeg[ pStruct->aLevel[0].nSeg++ ];
  205845. pSeg->iSegid = iSegid;
  205846. pSeg->pgnoFirst = 1;
  205847. pSeg->pgnoLast = pgnoLast;
  205848. pStruct->nSegment++;
  205849. }
  205850. fts5StructurePromote(p, 0, pStruct);
  205851. }
  205852. fts5IndexAutomerge(p, &pStruct, pgnoLast);
  205853. fts5IndexCrisismerge(p, &pStruct);
  205854. fts5StructureWrite(p, pStruct);
  205855. fts5StructureRelease(pStruct);
  205856. }
  205857. /*
  205858. ** Flush any data stored in the in-memory hash tables to the database.
  205859. */
  205860. static void fts5IndexFlush(Fts5Index *p){
  205861. /* Unless it is empty, flush the hash table to disk */
  205862. if( p->nPendingData ){
  205863. assert( p->pHash );
  205864. p->nPendingData = 0;
  205865. fts5FlushOneHash(p);
  205866. }
  205867. }
  205868. static Fts5Structure *fts5IndexOptimizeStruct(
  205869. Fts5Index *p,
  205870. Fts5Structure *pStruct
  205871. ){
  205872. Fts5Structure *pNew = 0;
  205873. sqlite3_int64 nByte = sizeof(Fts5Structure);
  205874. int nSeg = pStruct->nSegment;
  205875. int i;
  205876. /* Figure out if this structure requires optimization. A structure does
  205877. ** not require optimization if either:
  205878. **
  205879. ** + it consists of fewer than two segments, or
  205880. ** + all segments are on the same level, or
  205881. ** + all segments except one are currently inputs to a merge operation.
  205882. **
  205883. ** In the first case, return NULL. In the second, increment the ref-count
  205884. ** on *pStruct and return a copy of the pointer to it.
  205885. */
  205886. if( nSeg<2 ) return 0;
  205887. for(i=0; i<pStruct->nLevel; i++){
  205888. int nThis = pStruct->aLevel[i].nSeg;
  205889. if( nThis==nSeg || (nThis==nSeg-1 && pStruct->aLevel[i].nMerge==nThis) ){
  205890. fts5StructureRef(pStruct);
  205891. return pStruct;
  205892. }
  205893. assert( pStruct->aLevel[i].nMerge<=nThis );
  205894. }
  205895. nByte += (pStruct->nLevel+1) * sizeof(Fts5StructureLevel);
  205896. pNew = (Fts5Structure*)sqlite3Fts5MallocZero(&p->rc, nByte);
  205897. if( pNew ){
  205898. Fts5StructureLevel *pLvl;
  205899. nByte = nSeg * sizeof(Fts5StructureSegment);
  205900. pNew->nLevel = pStruct->nLevel+1;
  205901. pNew->nRef = 1;
  205902. pNew->nWriteCounter = pStruct->nWriteCounter;
  205903. pLvl = &pNew->aLevel[pStruct->nLevel];
  205904. pLvl->aSeg = (Fts5StructureSegment*)sqlite3Fts5MallocZero(&p->rc, nByte);
  205905. if( pLvl->aSeg ){
  205906. int iLvl, iSeg;
  205907. int iSegOut = 0;
  205908. /* Iterate through all segments, from oldest to newest. Add them to
  205909. ** the new Fts5Level object so that pLvl->aSeg[0] is the oldest
  205910. ** segment in the data structure. */
  205911. for(iLvl=pStruct->nLevel-1; iLvl>=0; iLvl--){
  205912. for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
  205913. pLvl->aSeg[iSegOut] = pStruct->aLevel[iLvl].aSeg[iSeg];
  205914. iSegOut++;
  205915. }
  205916. }
  205917. pNew->nSegment = pLvl->nSeg = nSeg;
  205918. }else{
  205919. sqlite3_free(pNew);
  205920. pNew = 0;
  205921. }
  205922. }
  205923. return pNew;
  205924. }
  205925. static int sqlite3Fts5IndexOptimize(Fts5Index *p){
  205926. Fts5Structure *pStruct;
  205927. Fts5Structure *pNew = 0;
  205928. assert( p->rc==SQLITE_OK );
  205929. fts5IndexFlush(p);
  205930. pStruct = fts5StructureRead(p);
  205931. fts5StructureInvalidate(p);
  205932. if( pStruct ){
  205933. pNew = fts5IndexOptimizeStruct(p, pStruct);
  205934. }
  205935. fts5StructureRelease(pStruct);
  205936. assert( pNew==0 || pNew->nSegment>0 );
  205937. if( pNew ){
  205938. int iLvl;
  205939. for(iLvl=0; pNew->aLevel[iLvl].nSeg==0; iLvl++){}
  205940. while( p->rc==SQLITE_OK && pNew->aLevel[iLvl].nSeg>0 ){
  205941. int nRem = FTS5_OPT_WORK_UNIT;
  205942. fts5IndexMergeLevel(p, &pNew, iLvl, &nRem);
  205943. }
  205944. fts5StructureWrite(p, pNew);
  205945. fts5StructureRelease(pNew);
  205946. }
  205947. return fts5IndexReturn(p);
  205948. }
  205949. /*
  205950. ** This is called to implement the special "VALUES('merge', $nMerge)"
  205951. ** INSERT command.
  205952. */
  205953. static int sqlite3Fts5IndexMerge(Fts5Index *p, int nMerge){
  205954. Fts5Structure *pStruct = fts5StructureRead(p);
  205955. if( pStruct ){
  205956. int nMin = p->pConfig->nUsermerge;
  205957. fts5StructureInvalidate(p);
  205958. if( nMerge<0 ){
  205959. Fts5Structure *pNew = fts5IndexOptimizeStruct(p, pStruct);
  205960. fts5StructureRelease(pStruct);
  205961. pStruct = pNew;
  205962. nMin = 2;
  205963. nMerge = nMerge*-1;
  205964. }
  205965. if( pStruct && pStruct->nLevel ){
  205966. if( fts5IndexMerge(p, &pStruct, nMerge, nMin) ){
  205967. fts5StructureWrite(p, pStruct);
  205968. }
  205969. }
  205970. fts5StructureRelease(pStruct);
  205971. }
  205972. return fts5IndexReturn(p);
  205973. }
  205974. static void fts5AppendRowid(
  205975. Fts5Index *p,
  205976. i64 iDelta,
  205977. Fts5Iter *pUnused,
  205978. Fts5Buffer *pBuf
  205979. ){
  205980. UNUSED_PARAM(pUnused);
  205981. fts5BufferAppendVarint(&p->rc, pBuf, iDelta);
  205982. }
  205983. static void fts5AppendPoslist(
  205984. Fts5Index *p,
  205985. i64 iDelta,
  205986. Fts5Iter *pMulti,
  205987. Fts5Buffer *pBuf
  205988. ){
  205989. int nData = pMulti->base.nData;
  205990. int nByte = nData + 9 + 9 + FTS5_DATA_ZERO_PADDING;
  205991. assert( nData>0 );
  205992. if( p->rc==SQLITE_OK && 0==fts5BufferGrow(&p->rc, pBuf, nByte) ){
  205993. fts5BufferSafeAppendVarint(pBuf, iDelta);
  205994. fts5BufferSafeAppendVarint(pBuf, nData*2);
  205995. fts5BufferSafeAppendBlob(pBuf, pMulti->base.pData, nData);
  205996. memset(&pBuf->p[pBuf->n], 0, FTS5_DATA_ZERO_PADDING);
  205997. }
  205998. }
  205999. static void fts5DoclistIterNext(Fts5DoclistIter *pIter){
  206000. u8 *p = pIter->aPoslist + pIter->nSize + pIter->nPoslist;
  206001. assert( pIter->aPoslist );
  206002. if( p>=pIter->aEof ){
  206003. pIter->aPoslist = 0;
  206004. }else{
  206005. i64 iDelta;
  206006. p += fts5GetVarint(p, (u64*)&iDelta);
  206007. pIter->iRowid += iDelta;
  206008. /* Read position list size */
  206009. if( p[0] & 0x80 ){
  206010. int nPos;
  206011. pIter->nSize = fts5GetVarint32(p, nPos);
  206012. pIter->nPoslist = (nPos>>1);
  206013. }else{
  206014. pIter->nPoslist = ((int)(p[0])) >> 1;
  206015. pIter->nSize = 1;
  206016. }
  206017. pIter->aPoslist = p;
  206018. }
  206019. }
  206020. static void fts5DoclistIterInit(
  206021. Fts5Buffer *pBuf,
  206022. Fts5DoclistIter *pIter
  206023. ){
  206024. memset(pIter, 0, sizeof(*pIter));
  206025. pIter->aPoslist = pBuf->p;
  206026. pIter->aEof = &pBuf->p[pBuf->n];
  206027. fts5DoclistIterNext(pIter);
  206028. }
  206029. #if 0
  206030. /*
  206031. ** Append a doclist to buffer pBuf.
  206032. **
  206033. ** This function assumes that space within the buffer has already been
  206034. ** allocated.
  206035. */
  206036. static void fts5MergeAppendDocid(
  206037. Fts5Buffer *pBuf, /* Buffer to write to */
  206038. i64 *piLastRowid, /* IN/OUT: Previous rowid written (if any) */
  206039. i64 iRowid /* Rowid to append */
  206040. ){
  206041. assert( pBuf->n!=0 || (*piLastRowid)==0 );
  206042. fts5BufferSafeAppendVarint(pBuf, iRowid - *piLastRowid);
  206043. *piLastRowid = iRowid;
  206044. }
  206045. #endif
  206046. #define fts5MergeAppendDocid(pBuf, iLastRowid, iRowid) { \
  206047. assert( (pBuf)->n!=0 || (iLastRowid)==0 ); \
  206048. fts5BufferSafeAppendVarint((pBuf), (iRowid) - (iLastRowid)); \
  206049. (iLastRowid) = (iRowid); \
  206050. }
  206051. /*
  206052. ** Swap the contents of buffer *p1 with that of *p2.
  206053. */
  206054. static void fts5BufferSwap(Fts5Buffer *p1, Fts5Buffer *p2){
  206055. Fts5Buffer tmp = *p1;
  206056. *p1 = *p2;
  206057. *p2 = tmp;
  206058. }
  206059. static void fts5NextRowid(Fts5Buffer *pBuf, int *piOff, i64 *piRowid){
  206060. int i = *piOff;
  206061. if( i>=pBuf->n ){
  206062. *piOff = -1;
  206063. }else{
  206064. u64 iVal;
  206065. *piOff = i + sqlite3Fts5GetVarint(&pBuf->p[i], &iVal);
  206066. *piRowid += iVal;
  206067. }
  206068. }
  206069. /*
  206070. ** This is the equivalent of fts5MergePrefixLists() for detail=none mode.
  206071. ** In this case the buffers consist of a delta-encoded list of rowids only.
  206072. */
  206073. static void fts5MergeRowidLists(
  206074. Fts5Index *p, /* FTS5 backend object */
  206075. Fts5Buffer *p1, /* First list to merge */
  206076. Fts5Buffer *p2 /* Second list to merge */
  206077. ){
  206078. int i1 = 0;
  206079. int i2 = 0;
  206080. i64 iRowid1 = 0;
  206081. i64 iRowid2 = 0;
  206082. i64 iOut = 0;
  206083. Fts5Buffer out;
  206084. memset(&out, 0, sizeof(out));
  206085. sqlite3Fts5BufferSize(&p->rc, &out, p1->n + p2->n);
  206086. if( p->rc ) return;
  206087. fts5NextRowid(p1, &i1, &iRowid1);
  206088. fts5NextRowid(p2, &i2, &iRowid2);
  206089. while( i1>=0 || i2>=0 ){
  206090. if( i1>=0 && (i2<0 || iRowid1<iRowid2) ){
  206091. assert( iOut==0 || iRowid1>iOut );
  206092. fts5BufferSafeAppendVarint(&out, iRowid1 - iOut);
  206093. iOut = iRowid1;
  206094. fts5NextRowid(p1, &i1, &iRowid1);
  206095. }else{
  206096. assert( iOut==0 || iRowid2>iOut );
  206097. fts5BufferSafeAppendVarint(&out, iRowid2 - iOut);
  206098. iOut = iRowid2;
  206099. if( i1>=0 && iRowid1==iRowid2 ){
  206100. fts5NextRowid(p1, &i1, &iRowid1);
  206101. }
  206102. fts5NextRowid(p2, &i2, &iRowid2);
  206103. }
  206104. }
  206105. fts5BufferSwap(&out, p1);
  206106. fts5BufferFree(&out);
  206107. }
  206108. /*
  206109. ** Buffers p1 and p2 contain doclists. This function merges the content
  206110. ** of the two doclists together and sets buffer p1 to the result before
  206111. ** returning.
  206112. **
  206113. ** If an error occurs, an error code is left in p->rc. If an error has
  206114. ** already occurred, this function is a no-op.
  206115. */
  206116. static void fts5MergePrefixLists(
  206117. Fts5Index *p, /* FTS5 backend object */
  206118. Fts5Buffer *p1, /* First list to merge */
  206119. Fts5Buffer *p2 /* Second list to merge */
  206120. ){
  206121. if( p2->n ){
  206122. i64 iLastRowid = 0;
  206123. Fts5DoclistIter i1;
  206124. Fts5DoclistIter i2;
  206125. Fts5Buffer out = {0, 0, 0};
  206126. Fts5Buffer tmp = {0, 0, 0};
  206127. /* The maximum size of the output is equal to the sum of the two
  206128. ** input sizes + 1 varint (9 bytes). The extra varint is because if the
  206129. ** first rowid in one input is a large negative number, and the first in
  206130. ** the other a non-negative number, the delta for the non-negative
  206131. ** number will be larger on disk than the literal integer value
  206132. ** was.
  206133. **
  206134. ** Or, if the input position-lists are corrupt, then the output might
  206135. ** include up to 2 extra 10-byte positions created by interpreting -1
  206136. ** (the value PoslistNext64() uses for EOF) as a position and appending
  206137. ** it to the output. This can happen at most once for each input
  206138. ** position-list, hence two 10 byte paddings. */
  206139. if( sqlite3Fts5BufferSize(&p->rc, &out, p1->n + p2->n + 9+10+10) ) return;
  206140. fts5DoclistIterInit(p1, &i1);
  206141. fts5DoclistIterInit(p2, &i2);
  206142. while( 1 ){
  206143. if( i1.iRowid<i2.iRowid ){
  206144. /* Copy entry from i1 */
  206145. fts5MergeAppendDocid(&out, iLastRowid, i1.iRowid);
  206146. fts5BufferSafeAppendBlob(&out, i1.aPoslist, i1.nPoslist+i1.nSize);
  206147. fts5DoclistIterNext(&i1);
  206148. if( i1.aPoslist==0 ) break;
  206149. assert( out.n<=((i1.aPoslist-p1->p) + (i2.aPoslist-p2->p)+9+10+10) );
  206150. }
  206151. else if( i2.iRowid!=i1.iRowid ){
  206152. /* Copy entry from i2 */
  206153. fts5MergeAppendDocid(&out, iLastRowid, i2.iRowid);
  206154. fts5BufferSafeAppendBlob(&out, i2.aPoslist, i2.nPoslist+i2.nSize);
  206155. fts5DoclistIterNext(&i2);
  206156. if( i2.aPoslist==0 ) break;
  206157. assert( out.n<=((i1.aPoslist-p1->p) + (i2.aPoslist-p2->p)+9+10+10) );
  206158. }
  206159. else{
  206160. /* Merge the two position lists. */
  206161. i64 iPos1 = 0;
  206162. i64 iPos2 = 0;
  206163. int iOff1 = 0;
  206164. int iOff2 = 0;
  206165. u8 *a1 = &i1.aPoslist[i1.nSize];
  206166. u8 *a2 = &i2.aPoslist[i2.nSize];
  206167. int nCopy;
  206168. u8 *aCopy;
  206169. i64 iPrev = 0;
  206170. Fts5PoslistWriter writer;
  206171. memset(&writer, 0, sizeof(writer));
  206172. /* See the earlier comment in this function for an explanation of why
  206173. ** corrupt input position lists might cause the output to consume
  206174. ** at most 20 bytes of unexpected space. */
  206175. fts5MergeAppendDocid(&out, iLastRowid, i2.iRowid);
  206176. fts5BufferZero(&tmp);
  206177. sqlite3Fts5BufferSize(&p->rc, &tmp, i1.nPoslist + i2.nPoslist + 10 + 10);
  206178. if( p->rc ) break;
  206179. sqlite3Fts5PoslistNext64(a1, i1.nPoslist, &iOff1, &iPos1);
  206180. sqlite3Fts5PoslistNext64(a2, i2.nPoslist, &iOff2, &iPos2);
  206181. assert_nc( iPos1>=0 && iPos2>=0 );
  206182. if( iPos1<iPos2 ){
  206183. sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos1);
  206184. sqlite3Fts5PoslistNext64(a1, i1.nPoslist, &iOff1, &iPos1);
  206185. }else{
  206186. sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos2);
  206187. sqlite3Fts5PoslistNext64(a2, i2.nPoslist, &iOff2, &iPos2);
  206188. }
  206189. if( iPos1>=0 && iPos2>=0 ){
  206190. while( 1 ){
  206191. if( iPos1<iPos2 ){
  206192. if( iPos1!=iPrev ){
  206193. sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos1);
  206194. }
  206195. sqlite3Fts5PoslistNext64(a1, i1.nPoslist, &iOff1, &iPos1);
  206196. if( iPos1<0 ) break;
  206197. }else{
  206198. assert_nc( iPos2!=iPrev );
  206199. sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos2);
  206200. sqlite3Fts5PoslistNext64(a2, i2.nPoslist, &iOff2, &iPos2);
  206201. if( iPos2<0 ) break;
  206202. }
  206203. }
  206204. }
  206205. if( iPos1>=0 ){
  206206. if( iPos1!=iPrev ){
  206207. sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos1);
  206208. }
  206209. aCopy = &a1[iOff1];
  206210. nCopy = i1.nPoslist - iOff1;
  206211. }else{
  206212. assert_nc( iPos2>=0 && iPos2!=iPrev );
  206213. sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos2);
  206214. aCopy = &a2[iOff2];
  206215. nCopy = i2.nPoslist - iOff2;
  206216. }
  206217. if( nCopy>0 ){
  206218. fts5BufferSafeAppendBlob(&tmp, aCopy, nCopy);
  206219. }
  206220. /* WRITEPOSLISTSIZE */
  206221. assert_nc( tmp.n<=i1.nPoslist+i2.nPoslist );
  206222. assert( tmp.n<=i1.nPoslist+i2.nPoslist+10+10 );
  206223. if( tmp.n>i1.nPoslist+i2.nPoslist ){
  206224. if( p->rc==SQLITE_OK ) p->rc = FTS5_CORRUPT;
  206225. break;
  206226. }
  206227. fts5BufferSafeAppendVarint(&out, tmp.n * 2);
  206228. fts5BufferSafeAppendBlob(&out, tmp.p, tmp.n);
  206229. fts5DoclistIterNext(&i1);
  206230. fts5DoclistIterNext(&i2);
  206231. assert_nc( out.n<=(p1->n+p2->n+9) );
  206232. if( i1.aPoslist==0 || i2.aPoslist==0 ) break;
  206233. assert( out.n<=((i1.aPoslist-p1->p) + (i2.aPoslist-p2->p)+9+10+10) );
  206234. }
  206235. }
  206236. if( i1.aPoslist ){
  206237. fts5MergeAppendDocid(&out, iLastRowid, i1.iRowid);
  206238. fts5BufferSafeAppendBlob(&out, i1.aPoslist, i1.aEof - i1.aPoslist);
  206239. }
  206240. else if( i2.aPoslist ){
  206241. fts5MergeAppendDocid(&out, iLastRowid, i2.iRowid);
  206242. fts5BufferSafeAppendBlob(&out, i2.aPoslist, i2.aEof - i2.aPoslist);
  206243. }
  206244. assert_nc( out.n<=(p1->n+p2->n+9) );
  206245. fts5BufferSet(&p->rc, p1, out.n, out.p);
  206246. fts5BufferFree(&tmp);
  206247. fts5BufferFree(&out);
  206248. }
  206249. }
  206250. static void fts5SetupPrefixIter(
  206251. Fts5Index *p, /* Index to read from */
  206252. int bDesc, /* True for "ORDER BY rowid DESC" */
  206253. const u8 *pToken, /* Buffer containing prefix to match */
  206254. int nToken, /* Size of buffer pToken in bytes */
  206255. Fts5Colset *pColset, /* Restrict matches to these columns */
  206256. Fts5Iter **ppIter /* OUT: New iterator */
  206257. ){
  206258. Fts5Structure *pStruct;
  206259. Fts5Buffer *aBuf;
  206260. const int nBuf = 32;
  206261. void (*xMerge)(Fts5Index*, Fts5Buffer*, Fts5Buffer*);
  206262. void (*xAppend)(Fts5Index*, i64, Fts5Iter*, Fts5Buffer*);
  206263. if( p->pConfig->eDetail==FTS5_DETAIL_NONE ){
  206264. xMerge = fts5MergeRowidLists;
  206265. xAppend = fts5AppendRowid;
  206266. }else{
  206267. xMerge = fts5MergePrefixLists;
  206268. xAppend = fts5AppendPoslist;
  206269. }
  206270. aBuf = (Fts5Buffer*)fts5IdxMalloc(p, sizeof(Fts5Buffer)*nBuf);
  206271. pStruct = fts5StructureRead(p);
  206272. if( aBuf && pStruct ){
  206273. const int flags = FTS5INDEX_QUERY_SCAN
  206274. | FTS5INDEX_QUERY_SKIPEMPTY
  206275. | FTS5INDEX_QUERY_NOOUTPUT;
  206276. int i;
  206277. i64 iLastRowid = 0;
  206278. Fts5Iter *p1 = 0; /* Iterator used to gather data from index */
  206279. Fts5Data *pData;
  206280. Fts5Buffer doclist;
  206281. int bNewTerm = 1;
  206282. memset(&doclist, 0, sizeof(doclist));
  206283. fts5MultiIterNew(p, pStruct, flags, pColset, pToken, nToken, -1, 0, &p1);
  206284. fts5IterSetOutputCb(&p->rc, p1);
  206285. for( /* no-op */ ;
  206286. fts5MultiIterEof(p, p1)==0;
  206287. fts5MultiIterNext2(p, p1, &bNewTerm)
  206288. ){
  206289. Fts5SegIter *pSeg = &p1->aSeg[ p1->aFirst[1].iFirst ];
  206290. int nTerm = pSeg->term.n;
  206291. const u8 *pTerm = pSeg->term.p;
  206292. p1->xSetOutputs(p1, pSeg);
  206293. assert_nc( memcmp(pToken, pTerm, MIN(nToken, nTerm))<=0 );
  206294. if( bNewTerm ){
  206295. if( nTerm<nToken || memcmp(pToken, pTerm, nToken) ) break;
  206296. }
  206297. if( p1->base.nData==0 ) continue;
  206298. if( p1->base.iRowid<=iLastRowid && doclist.n>0 ){
  206299. for(i=0; p->rc==SQLITE_OK && doclist.n; i++){
  206300. assert( i<nBuf );
  206301. if( aBuf[i].n==0 ){
  206302. fts5BufferSwap(&doclist, &aBuf[i]);
  206303. fts5BufferZero(&doclist);
  206304. }else{
  206305. xMerge(p, &doclist, &aBuf[i]);
  206306. fts5BufferZero(&aBuf[i]);
  206307. }
  206308. }
  206309. iLastRowid = 0;
  206310. }
  206311. xAppend(p, p1->base.iRowid-iLastRowid, p1, &doclist);
  206312. iLastRowid = p1->base.iRowid;
  206313. }
  206314. for(i=0; i<nBuf; i++){
  206315. if( p->rc==SQLITE_OK ){
  206316. xMerge(p, &doclist, &aBuf[i]);
  206317. }
  206318. fts5BufferFree(&aBuf[i]);
  206319. }
  206320. fts5MultiIterFree(p1);
  206321. pData = fts5IdxMalloc(p, sizeof(Fts5Data)+doclist.n+FTS5_DATA_ZERO_PADDING);
  206322. if( pData ){
  206323. pData->p = (u8*)&pData[1];
  206324. pData->nn = pData->szLeaf = doclist.n;
  206325. if( doclist.n ) memcpy(pData->p, doclist.p, doclist.n);
  206326. fts5MultiIterNew2(p, pData, bDesc, ppIter);
  206327. }
  206328. fts5BufferFree(&doclist);
  206329. }
  206330. fts5StructureRelease(pStruct);
  206331. sqlite3_free(aBuf);
  206332. }
  206333. /*
  206334. ** Indicate that all subsequent calls to sqlite3Fts5IndexWrite() pertain
  206335. ** to the document with rowid iRowid.
  206336. */
  206337. static int sqlite3Fts5IndexBeginWrite(Fts5Index *p, int bDelete, i64 iRowid){
  206338. assert( p->rc==SQLITE_OK );
  206339. /* Allocate the hash table if it has not already been allocated */
  206340. if( p->pHash==0 ){
  206341. p->rc = sqlite3Fts5HashNew(p->pConfig, &p->pHash, &p->nPendingData);
  206342. }
  206343. /* Flush the hash table to disk if required */
  206344. if( iRowid<p->iWriteRowid
  206345. || (iRowid==p->iWriteRowid && p->bDelete==0)
  206346. || (p->nPendingData > p->pConfig->nHashSize)
  206347. ){
  206348. fts5IndexFlush(p);
  206349. }
  206350. p->iWriteRowid = iRowid;
  206351. p->bDelete = bDelete;
  206352. return fts5IndexReturn(p);
  206353. }
  206354. /*
  206355. ** Commit data to disk.
  206356. */
  206357. static int sqlite3Fts5IndexSync(Fts5Index *p){
  206358. assert( p->rc==SQLITE_OK );
  206359. fts5IndexFlush(p);
  206360. sqlite3Fts5IndexCloseReader(p);
  206361. return fts5IndexReturn(p);
  206362. }
  206363. /*
  206364. ** Discard any data stored in the in-memory hash tables. Do not write it
  206365. ** to the database. Additionally, assume that the contents of the %_data
  206366. ** table may have changed on disk. So any in-memory caches of %_data
  206367. ** records must be invalidated.
  206368. */
  206369. static int sqlite3Fts5IndexRollback(Fts5Index *p){
  206370. sqlite3Fts5IndexCloseReader(p);
  206371. fts5IndexDiscardData(p);
  206372. fts5StructureInvalidate(p);
  206373. /* assert( p->rc==SQLITE_OK ); */
  206374. return SQLITE_OK;
  206375. }
  206376. /*
  206377. ** The %_data table is completely empty when this function is called. This
  206378. ** function populates it with the initial structure objects for each index,
  206379. ** and the initial version of the "averages" record (a zero-byte blob).
  206380. */
  206381. static int sqlite3Fts5IndexReinit(Fts5Index *p){
  206382. Fts5Structure s;
  206383. fts5StructureInvalidate(p);
  206384. fts5IndexDiscardData(p);
  206385. memset(&s, 0, sizeof(Fts5Structure));
  206386. fts5DataWrite(p, FTS5_AVERAGES_ROWID, (const u8*)"", 0);
  206387. fts5StructureWrite(p, &s);
  206388. return fts5IndexReturn(p);
  206389. }
  206390. /*
  206391. ** Open a new Fts5Index handle. If the bCreate argument is true, create
  206392. ** and initialize the underlying %_data table.
  206393. **
  206394. ** If successful, set *pp to point to the new object and return SQLITE_OK.
  206395. ** Otherwise, set *pp to NULL and return an SQLite error code.
  206396. */
  206397. static int sqlite3Fts5IndexOpen(
  206398. Fts5Config *pConfig,
  206399. int bCreate,
  206400. Fts5Index **pp,
  206401. char **pzErr
  206402. ){
  206403. int rc = SQLITE_OK;
  206404. Fts5Index *p; /* New object */
  206405. *pp = p = (Fts5Index*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Index));
  206406. if( rc==SQLITE_OK ){
  206407. p->pConfig = pConfig;
  206408. p->nWorkUnit = FTS5_WORK_UNIT;
  206409. p->zDataTbl = sqlite3Fts5Mprintf(&rc, "%s_data", pConfig->zName);
  206410. if( p->zDataTbl && bCreate ){
  206411. rc = sqlite3Fts5CreateTable(
  206412. pConfig, "data", "id INTEGER PRIMARY KEY, block BLOB", 0, pzErr
  206413. );
  206414. if( rc==SQLITE_OK ){
  206415. rc = sqlite3Fts5CreateTable(pConfig, "idx",
  206416. "segid, term, pgno, PRIMARY KEY(segid, term)",
  206417. 1, pzErr
  206418. );
  206419. }
  206420. if( rc==SQLITE_OK ){
  206421. rc = sqlite3Fts5IndexReinit(p);
  206422. }
  206423. }
  206424. }
  206425. assert( rc!=SQLITE_OK || p->rc==SQLITE_OK );
  206426. if( rc ){
  206427. sqlite3Fts5IndexClose(p);
  206428. *pp = 0;
  206429. }
  206430. return rc;
  206431. }
  206432. /*
  206433. ** Close a handle opened by an earlier call to sqlite3Fts5IndexOpen().
  206434. */
  206435. static int sqlite3Fts5IndexClose(Fts5Index *p){
  206436. int rc = SQLITE_OK;
  206437. if( p ){
  206438. assert( p->pReader==0 );
  206439. fts5StructureInvalidate(p);
  206440. sqlite3_finalize(p->pWriter);
  206441. sqlite3_finalize(p->pDeleter);
  206442. sqlite3_finalize(p->pIdxWriter);
  206443. sqlite3_finalize(p->pIdxDeleter);
  206444. sqlite3_finalize(p->pIdxSelect);
  206445. sqlite3_finalize(p->pDataVersion);
  206446. sqlite3Fts5HashFree(p->pHash);
  206447. sqlite3_free(p->zDataTbl);
  206448. sqlite3_free(p);
  206449. }
  206450. return rc;
  206451. }
  206452. /*
  206453. ** Argument p points to a buffer containing utf-8 text that is n bytes in
  206454. ** size. Return the number of bytes in the nChar character prefix of the
  206455. ** buffer, or 0 if there are less than nChar characters in total.
  206456. */
  206457. static int sqlite3Fts5IndexCharlenToBytelen(
  206458. const char *p,
  206459. int nByte,
  206460. int nChar
  206461. ){
  206462. int n = 0;
  206463. int i;
  206464. for(i=0; i<nChar; i++){
  206465. if( n>=nByte ) return 0; /* Input contains fewer than nChar chars */
  206466. if( (unsigned char)p[n++]>=0xc0 ){
  206467. if( n>=nByte ) return 0;
  206468. while( (p[n] & 0xc0)==0x80 ){
  206469. n++;
  206470. if( n>=nByte ){
  206471. if( i+1==nChar ) break;
  206472. return 0;
  206473. }
  206474. }
  206475. }
  206476. }
  206477. return n;
  206478. }
  206479. /*
  206480. ** pIn is a UTF-8 encoded string, nIn bytes in size. Return the number of
  206481. ** unicode characters in the string.
  206482. */
  206483. static int fts5IndexCharlen(const char *pIn, int nIn){
  206484. int nChar = 0;
  206485. int i = 0;
  206486. while( i<nIn ){
  206487. if( (unsigned char)pIn[i++]>=0xc0 ){
  206488. while( i<nIn && (pIn[i] & 0xc0)==0x80 ) i++;
  206489. }
  206490. nChar++;
  206491. }
  206492. return nChar;
  206493. }
  206494. /*
  206495. ** Insert or remove data to or from the index. Each time a document is
  206496. ** added to or removed from the index, this function is called one or more
  206497. ** times.
  206498. **
  206499. ** For an insert, it must be called once for each token in the new document.
  206500. ** If the operation is a delete, it must be called (at least) once for each
  206501. ** unique token in the document with an iCol value less than zero. The iPos
  206502. ** argument is ignored for a delete.
  206503. */
  206504. static int sqlite3Fts5IndexWrite(
  206505. Fts5Index *p, /* Index to write to */
  206506. int iCol, /* Column token appears in (-ve -> delete) */
  206507. int iPos, /* Position of token within column */
  206508. const char *pToken, int nToken /* Token to add or remove to or from index */
  206509. ){
  206510. int i; /* Used to iterate through indexes */
  206511. int rc = SQLITE_OK; /* Return code */
  206512. Fts5Config *pConfig = p->pConfig;
  206513. assert( p->rc==SQLITE_OK );
  206514. assert( (iCol<0)==p->bDelete );
  206515. /* Add the entry to the main terms index. */
  206516. rc = sqlite3Fts5HashWrite(
  206517. p->pHash, p->iWriteRowid, iCol, iPos, FTS5_MAIN_PREFIX, pToken, nToken
  206518. );
  206519. for(i=0; i<pConfig->nPrefix && rc==SQLITE_OK; i++){
  206520. const int nChar = pConfig->aPrefix[i];
  206521. int nByte = sqlite3Fts5IndexCharlenToBytelen(pToken, nToken, nChar);
  206522. if( nByte ){
  206523. rc = sqlite3Fts5HashWrite(p->pHash,
  206524. p->iWriteRowid, iCol, iPos, (char)(FTS5_MAIN_PREFIX+i+1), pToken,
  206525. nByte
  206526. );
  206527. }
  206528. }
  206529. return rc;
  206530. }
  206531. /*
  206532. ** Open a new iterator to iterate though all rowid that match the
  206533. ** specified token or token prefix.
  206534. */
  206535. static int sqlite3Fts5IndexQuery(
  206536. Fts5Index *p, /* FTS index to query */
  206537. const char *pToken, int nToken, /* Token (or prefix) to query for */
  206538. int flags, /* Mask of FTS5INDEX_QUERY_X flags */
  206539. Fts5Colset *pColset, /* Match these columns only */
  206540. Fts5IndexIter **ppIter /* OUT: New iterator object */
  206541. ){
  206542. Fts5Config *pConfig = p->pConfig;
  206543. Fts5Iter *pRet = 0;
  206544. Fts5Buffer buf = {0, 0, 0};
  206545. /* If the QUERY_SCAN flag is set, all other flags must be clear. */
  206546. assert( (flags & FTS5INDEX_QUERY_SCAN)==0 || flags==FTS5INDEX_QUERY_SCAN );
  206547. if( sqlite3Fts5BufferSize(&p->rc, &buf, nToken+1)==0 ){
  206548. int iIdx = 0; /* Index to search */
  206549. if( nToken ) memcpy(&buf.p[1], pToken, nToken);
  206550. /* Figure out which index to search and set iIdx accordingly. If this
  206551. ** is a prefix query for which there is no prefix index, set iIdx to
  206552. ** greater than pConfig->nPrefix to indicate that the query will be
  206553. ** satisfied by scanning multiple terms in the main index.
  206554. **
  206555. ** If the QUERY_TEST_NOIDX flag was specified, then this must be a
  206556. ** prefix-query. Instead of using a prefix-index (if one exists),
  206557. ** evaluate the prefix query using the main FTS index. This is used
  206558. ** for internal sanity checking by the integrity-check in debug
  206559. ** mode only. */
  206560. #ifdef SQLITE_DEBUG
  206561. if( pConfig->bPrefixIndex==0 || (flags & FTS5INDEX_QUERY_TEST_NOIDX) ){
  206562. assert( flags & FTS5INDEX_QUERY_PREFIX );
  206563. iIdx = 1+pConfig->nPrefix;
  206564. }else
  206565. #endif
  206566. if( flags & FTS5INDEX_QUERY_PREFIX ){
  206567. int nChar = fts5IndexCharlen(pToken, nToken);
  206568. for(iIdx=1; iIdx<=pConfig->nPrefix; iIdx++){
  206569. if( pConfig->aPrefix[iIdx-1]==nChar ) break;
  206570. }
  206571. }
  206572. if( iIdx<=pConfig->nPrefix ){
  206573. /* Straight index lookup */
  206574. Fts5Structure *pStruct = fts5StructureRead(p);
  206575. buf.p[0] = (u8)(FTS5_MAIN_PREFIX + iIdx);
  206576. if( pStruct ){
  206577. fts5MultiIterNew(p, pStruct, flags | FTS5INDEX_QUERY_SKIPEMPTY,
  206578. pColset, buf.p, nToken+1, -1, 0, &pRet
  206579. );
  206580. fts5StructureRelease(pStruct);
  206581. }
  206582. }else{
  206583. /* Scan multiple terms in the main index */
  206584. int bDesc = (flags & FTS5INDEX_QUERY_DESC)!=0;
  206585. buf.p[0] = FTS5_MAIN_PREFIX;
  206586. fts5SetupPrefixIter(p, bDesc, buf.p, nToken+1, pColset, &pRet);
  206587. assert( p->rc!=SQLITE_OK || pRet->pColset==0 );
  206588. fts5IterSetOutputCb(&p->rc, pRet);
  206589. if( p->rc==SQLITE_OK ){
  206590. Fts5SegIter *pSeg = &pRet->aSeg[pRet->aFirst[1].iFirst];
  206591. if( pSeg->pLeaf ) pRet->xSetOutputs(pRet, pSeg);
  206592. }
  206593. }
  206594. if( p->rc ){
  206595. sqlite3Fts5IterClose((Fts5IndexIter*)pRet);
  206596. pRet = 0;
  206597. sqlite3Fts5IndexCloseReader(p);
  206598. }
  206599. *ppIter = (Fts5IndexIter*)pRet;
  206600. sqlite3Fts5BufferFree(&buf);
  206601. }
  206602. return fts5IndexReturn(p);
  206603. }
  206604. /*
  206605. ** Return true if the iterator passed as the only argument is at EOF.
  206606. */
  206607. /*
  206608. ** Move to the next matching rowid.
  206609. */
  206610. static int sqlite3Fts5IterNext(Fts5IndexIter *pIndexIter){
  206611. Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
  206612. assert( pIter->pIndex->rc==SQLITE_OK );
  206613. fts5MultiIterNext(pIter->pIndex, pIter, 0, 0);
  206614. return fts5IndexReturn(pIter->pIndex);
  206615. }
  206616. /*
  206617. ** Move to the next matching term/rowid. Used by the fts5vocab module.
  206618. */
  206619. static int sqlite3Fts5IterNextScan(Fts5IndexIter *pIndexIter){
  206620. Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
  206621. Fts5Index *p = pIter->pIndex;
  206622. assert( pIter->pIndex->rc==SQLITE_OK );
  206623. fts5MultiIterNext(p, pIter, 0, 0);
  206624. if( p->rc==SQLITE_OK ){
  206625. Fts5SegIter *pSeg = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
  206626. if( pSeg->pLeaf && pSeg->term.p[0]!=FTS5_MAIN_PREFIX ){
  206627. fts5DataRelease(pSeg->pLeaf);
  206628. pSeg->pLeaf = 0;
  206629. pIter->base.bEof = 1;
  206630. }
  206631. }
  206632. return fts5IndexReturn(pIter->pIndex);
  206633. }
  206634. /*
  206635. ** Move to the next matching rowid that occurs at or after iMatch. The
  206636. ** definition of "at or after" depends on whether this iterator iterates
  206637. ** in ascending or descending rowid order.
  206638. */
  206639. static int sqlite3Fts5IterNextFrom(Fts5IndexIter *pIndexIter, i64 iMatch){
  206640. Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
  206641. fts5MultiIterNextFrom(pIter->pIndex, pIter, iMatch);
  206642. return fts5IndexReturn(pIter->pIndex);
  206643. }
  206644. /*
  206645. ** Return the current term.
  206646. */
  206647. static const char *sqlite3Fts5IterTerm(Fts5IndexIter *pIndexIter, int *pn){
  206648. int n;
  206649. const char *z = (const char*)fts5MultiIterTerm((Fts5Iter*)pIndexIter, &n);
  206650. *pn = n-1;
  206651. return &z[1];
  206652. }
  206653. /*
  206654. ** Close an iterator opened by an earlier call to sqlite3Fts5IndexQuery().
  206655. */
  206656. static void sqlite3Fts5IterClose(Fts5IndexIter *pIndexIter){
  206657. if( pIndexIter ){
  206658. Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
  206659. Fts5Index *pIndex = pIter->pIndex;
  206660. fts5MultiIterFree(pIter);
  206661. sqlite3Fts5IndexCloseReader(pIndex);
  206662. }
  206663. }
  206664. /*
  206665. ** Read and decode the "averages" record from the database.
  206666. **
  206667. ** Parameter anSize must point to an array of size nCol, where nCol is
  206668. ** the number of user defined columns in the FTS table.
  206669. */
  206670. static int sqlite3Fts5IndexGetAverages(Fts5Index *p, i64 *pnRow, i64 *anSize){
  206671. int nCol = p->pConfig->nCol;
  206672. Fts5Data *pData;
  206673. *pnRow = 0;
  206674. memset(anSize, 0, sizeof(i64) * nCol);
  206675. pData = fts5DataRead(p, FTS5_AVERAGES_ROWID);
  206676. if( p->rc==SQLITE_OK && pData->nn ){
  206677. int i = 0;
  206678. int iCol;
  206679. i += fts5GetVarint(&pData->p[i], (u64*)pnRow);
  206680. for(iCol=0; i<pData->nn && iCol<nCol; iCol++){
  206681. i += fts5GetVarint(&pData->p[i], (u64*)&anSize[iCol]);
  206682. }
  206683. }
  206684. fts5DataRelease(pData);
  206685. return fts5IndexReturn(p);
  206686. }
  206687. /*
  206688. ** Replace the current "averages" record with the contents of the buffer
  206689. ** supplied as the second argument.
  206690. */
  206691. static int sqlite3Fts5IndexSetAverages(Fts5Index *p, const u8 *pData, int nData){
  206692. assert( p->rc==SQLITE_OK );
  206693. fts5DataWrite(p, FTS5_AVERAGES_ROWID, pData, nData);
  206694. return fts5IndexReturn(p);
  206695. }
  206696. /*
  206697. ** Return the total number of blocks this module has read from the %_data
  206698. ** table since it was created.
  206699. */
  206700. static int sqlite3Fts5IndexReads(Fts5Index *p){
  206701. return p->nRead;
  206702. }
  206703. /*
  206704. ** Set the 32-bit cookie value stored at the start of all structure
  206705. ** records to the value passed as the second argument.
  206706. **
  206707. ** Return SQLITE_OK if successful, or an SQLite error code if an error
  206708. ** occurs.
  206709. */
  206710. static int sqlite3Fts5IndexSetCookie(Fts5Index *p, int iNew){
  206711. int rc; /* Return code */
  206712. Fts5Config *pConfig = p->pConfig; /* Configuration object */
  206713. u8 aCookie[4]; /* Binary representation of iNew */
  206714. sqlite3_blob *pBlob = 0;
  206715. assert( p->rc==SQLITE_OK );
  206716. sqlite3Fts5Put32(aCookie, iNew);
  206717. rc = sqlite3_blob_open(pConfig->db, pConfig->zDb, p->zDataTbl,
  206718. "block", FTS5_STRUCTURE_ROWID, 1, &pBlob
  206719. );
  206720. if( rc==SQLITE_OK ){
  206721. sqlite3_blob_write(pBlob, aCookie, 4, 0);
  206722. rc = sqlite3_blob_close(pBlob);
  206723. }
  206724. return rc;
  206725. }
  206726. static int sqlite3Fts5IndexLoadConfig(Fts5Index *p){
  206727. Fts5Structure *pStruct;
  206728. pStruct = fts5StructureRead(p);
  206729. fts5StructureRelease(pStruct);
  206730. return fts5IndexReturn(p);
  206731. }
  206732. /*************************************************************************
  206733. **************************************************************************
  206734. ** Below this point is the implementation of the integrity-check
  206735. ** functionality.
  206736. */
  206737. /*
  206738. ** Return a simple checksum value based on the arguments.
  206739. */
  206740. static u64 sqlite3Fts5IndexEntryCksum(
  206741. i64 iRowid,
  206742. int iCol,
  206743. int iPos,
  206744. int iIdx,
  206745. const char *pTerm,
  206746. int nTerm
  206747. ){
  206748. int i;
  206749. u64 ret = iRowid;
  206750. ret += (ret<<3) + iCol;
  206751. ret += (ret<<3) + iPos;
  206752. if( iIdx>=0 ) ret += (ret<<3) + (FTS5_MAIN_PREFIX + iIdx);
  206753. for(i=0; i<nTerm; i++) ret += (ret<<3) + pTerm[i];
  206754. return ret;
  206755. }
  206756. #ifdef SQLITE_DEBUG
  206757. /*
  206758. ** This function is purely an internal test. It does not contribute to
  206759. ** FTS functionality, or even the integrity-check, in any way.
  206760. **
  206761. ** Instead, it tests that the same set of pgno/rowid combinations are
  206762. ** visited regardless of whether the doclist-index identified by parameters
  206763. ** iSegid/iLeaf is iterated in forwards or reverse order.
  206764. */
  206765. static void fts5TestDlidxReverse(
  206766. Fts5Index *p,
  206767. int iSegid, /* Segment id to load from */
  206768. int iLeaf /* Load doclist-index for this leaf */
  206769. ){
  206770. Fts5DlidxIter *pDlidx = 0;
  206771. u64 cksum1 = 13;
  206772. u64 cksum2 = 13;
  206773. for(pDlidx=fts5DlidxIterInit(p, 0, iSegid, iLeaf);
  206774. fts5DlidxIterEof(p, pDlidx)==0;
  206775. fts5DlidxIterNext(p, pDlidx)
  206776. ){
  206777. i64 iRowid = fts5DlidxIterRowid(pDlidx);
  206778. int pgno = fts5DlidxIterPgno(pDlidx);
  206779. assert( pgno>iLeaf );
  206780. cksum1 += iRowid + ((i64)pgno<<32);
  206781. }
  206782. fts5DlidxIterFree(pDlidx);
  206783. pDlidx = 0;
  206784. for(pDlidx=fts5DlidxIterInit(p, 1, iSegid, iLeaf);
  206785. fts5DlidxIterEof(p, pDlidx)==0;
  206786. fts5DlidxIterPrev(p, pDlidx)
  206787. ){
  206788. i64 iRowid = fts5DlidxIterRowid(pDlidx);
  206789. int pgno = fts5DlidxIterPgno(pDlidx);
  206790. assert( fts5DlidxIterPgno(pDlidx)>iLeaf );
  206791. cksum2 += iRowid + ((i64)pgno<<32);
  206792. }
  206793. fts5DlidxIterFree(pDlidx);
  206794. pDlidx = 0;
  206795. if( p->rc==SQLITE_OK && cksum1!=cksum2 ) p->rc = FTS5_CORRUPT;
  206796. }
  206797. static int fts5QueryCksum(
  206798. Fts5Index *p, /* Fts5 index object */
  206799. int iIdx,
  206800. const char *z, /* Index key to query for */
  206801. int n, /* Size of index key in bytes */
  206802. int flags, /* Flags for Fts5IndexQuery */
  206803. u64 *pCksum /* IN/OUT: Checksum value */
  206804. ){
  206805. int eDetail = p->pConfig->eDetail;
  206806. u64 cksum = *pCksum;
  206807. Fts5IndexIter *pIter = 0;
  206808. int rc = sqlite3Fts5IndexQuery(p, z, n, flags, 0, &pIter);
  206809. while( rc==SQLITE_OK && 0==sqlite3Fts5IterEof(pIter) ){
  206810. i64 rowid = pIter->iRowid;
  206811. if( eDetail==FTS5_DETAIL_NONE ){
  206812. cksum ^= sqlite3Fts5IndexEntryCksum(rowid, 0, 0, iIdx, z, n);
  206813. }else{
  206814. Fts5PoslistReader sReader;
  206815. for(sqlite3Fts5PoslistReaderInit(pIter->pData, pIter->nData, &sReader);
  206816. sReader.bEof==0;
  206817. sqlite3Fts5PoslistReaderNext(&sReader)
  206818. ){
  206819. int iCol = FTS5_POS2COLUMN(sReader.iPos);
  206820. int iOff = FTS5_POS2OFFSET(sReader.iPos);
  206821. cksum ^= sqlite3Fts5IndexEntryCksum(rowid, iCol, iOff, iIdx, z, n);
  206822. }
  206823. }
  206824. if( rc==SQLITE_OK ){
  206825. rc = sqlite3Fts5IterNext(pIter);
  206826. }
  206827. }
  206828. sqlite3Fts5IterClose(pIter);
  206829. *pCksum = cksum;
  206830. return rc;
  206831. }
  206832. /*
  206833. ** Check if buffer z[], size n bytes, contains as series of valid utf-8
  206834. ** encoded codepoints. If so, return 0. Otherwise, if the buffer does not
  206835. ** contain valid utf-8, return non-zero.
  206836. */
  206837. static int fts5TestUtf8(const char *z, int n){
  206838. int i = 0;
  206839. assert_nc( n>0 );
  206840. while( i<n ){
  206841. if( (z[i] & 0x80)==0x00 ){
  206842. i++;
  206843. }else
  206844. if( (z[i] & 0xE0)==0xC0 ){
  206845. if( i+1>=n || (z[i+1] & 0xC0)!=0x80 ) return 1;
  206846. i += 2;
  206847. }else
  206848. if( (z[i] & 0xF0)==0xE0 ){
  206849. if( i+2>=n || (z[i+1] & 0xC0)!=0x80 || (z[i+2] & 0xC0)!=0x80 ) return 1;
  206850. i += 3;
  206851. }else
  206852. if( (z[i] & 0xF8)==0xF0 ){
  206853. if( i+3>=n || (z[i+1] & 0xC0)!=0x80 || (z[i+2] & 0xC0)!=0x80 ) return 1;
  206854. if( (z[i+2] & 0xC0)!=0x80 ) return 1;
  206855. i += 3;
  206856. }else{
  206857. return 1;
  206858. }
  206859. }
  206860. return 0;
  206861. }
  206862. /*
  206863. ** This function is also purely an internal test. It does not contribute to
  206864. ** FTS functionality, or even the integrity-check, in any way.
  206865. */
  206866. static void fts5TestTerm(
  206867. Fts5Index *p,
  206868. Fts5Buffer *pPrev, /* Previous term */
  206869. const char *z, int n, /* Possibly new term to test */
  206870. u64 expected,
  206871. u64 *pCksum
  206872. ){
  206873. int rc = p->rc;
  206874. if( pPrev->n==0 ){
  206875. fts5BufferSet(&rc, pPrev, n, (const u8*)z);
  206876. }else
  206877. if( rc==SQLITE_OK && (pPrev->n!=n || memcmp(pPrev->p, z, n)) ){
  206878. u64 cksum3 = *pCksum;
  206879. const char *zTerm = (const char*)&pPrev->p[1]; /* term sans prefix-byte */
  206880. int nTerm = pPrev->n-1; /* Size of zTerm in bytes */
  206881. int iIdx = (pPrev->p[0] - FTS5_MAIN_PREFIX);
  206882. int flags = (iIdx==0 ? 0 : FTS5INDEX_QUERY_PREFIX);
  206883. u64 ck1 = 0;
  206884. u64 ck2 = 0;
  206885. /* Check that the results returned for ASC and DESC queries are
  206886. ** the same. If not, call this corruption. */
  206887. rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, flags, &ck1);
  206888. if( rc==SQLITE_OK ){
  206889. int f = flags|FTS5INDEX_QUERY_DESC;
  206890. rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, f, &ck2);
  206891. }
  206892. if( rc==SQLITE_OK && ck1!=ck2 ) rc = FTS5_CORRUPT;
  206893. /* If this is a prefix query, check that the results returned if the
  206894. ** the index is disabled are the same. In both ASC and DESC order.
  206895. **
  206896. ** This check may only be performed if the hash table is empty. This
  206897. ** is because the hash table only supports a single scan query at
  206898. ** a time, and the multi-iter loop from which this function is called
  206899. ** is already performing such a scan.
  206900. **
  206901. ** Also only do this if buffer zTerm contains nTerm bytes of valid
  206902. ** utf-8. Otherwise, the last part of the buffer contents might contain
  206903. ** a non-utf-8 sequence that happens to be a prefix of a valid utf-8
  206904. ** character stored in the main fts index, which will cause the
  206905. ** test to fail. */
  206906. if( p->nPendingData==0 && 0==fts5TestUtf8(zTerm, nTerm) ){
  206907. if( iIdx>0 && rc==SQLITE_OK ){
  206908. int f = flags|FTS5INDEX_QUERY_TEST_NOIDX;
  206909. ck2 = 0;
  206910. rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, f, &ck2);
  206911. if( rc==SQLITE_OK && ck1!=ck2 ) rc = FTS5_CORRUPT;
  206912. }
  206913. if( iIdx>0 && rc==SQLITE_OK ){
  206914. int f = flags|FTS5INDEX_QUERY_TEST_NOIDX|FTS5INDEX_QUERY_DESC;
  206915. ck2 = 0;
  206916. rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, f, &ck2);
  206917. if( rc==SQLITE_OK && ck1!=ck2 ) rc = FTS5_CORRUPT;
  206918. }
  206919. }
  206920. cksum3 ^= ck1;
  206921. fts5BufferSet(&rc, pPrev, n, (const u8*)z);
  206922. if( rc==SQLITE_OK && cksum3!=expected ){
  206923. rc = FTS5_CORRUPT;
  206924. }
  206925. *pCksum = cksum3;
  206926. }
  206927. p->rc = rc;
  206928. }
  206929. #else
  206930. # define fts5TestDlidxReverse(x,y,z)
  206931. # define fts5TestTerm(u,v,w,x,y,z)
  206932. #endif
  206933. /*
  206934. ** Check that:
  206935. **
  206936. ** 1) All leaves of pSeg between iFirst and iLast (inclusive) exist and
  206937. ** contain zero terms.
  206938. ** 2) All leaves of pSeg between iNoRowid and iLast (inclusive) exist and
  206939. ** contain zero rowids.
  206940. */
  206941. static void fts5IndexIntegrityCheckEmpty(
  206942. Fts5Index *p,
  206943. Fts5StructureSegment *pSeg, /* Segment to check internal consistency */
  206944. int iFirst,
  206945. int iNoRowid,
  206946. int iLast
  206947. ){
  206948. int i;
  206949. /* Now check that the iter.nEmpty leaves following the current leaf
  206950. ** (a) exist and (b) contain no terms. */
  206951. for(i=iFirst; p->rc==SQLITE_OK && i<=iLast; i++){
  206952. Fts5Data *pLeaf = fts5DataRead(p, FTS5_SEGMENT_ROWID(pSeg->iSegid, i));
  206953. if( pLeaf ){
  206954. if( !fts5LeafIsTermless(pLeaf) ) p->rc = FTS5_CORRUPT;
  206955. if( i>=iNoRowid && 0!=fts5LeafFirstRowidOff(pLeaf) ) p->rc = FTS5_CORRUPT;
  206956. }
  206957. fts5DataRelease(pLeaf);
  206958. }
  206959. }
  206960. static void fts5IntegrityCheckPgidx(Fts5Index *p, Fts5Data *pLeaf){
  206961. int iTermOff = 0;
  206962. int ii;
  206963. Fts5Buffer buf1 = {0,0,0};
  206964. Fts5Buffer buf2 = {0,0,0};
  206965. ii = pLeaf->szLeaf;
  206966. while( ii<pLeaf->nn && p->rc==SQLITE_OK ){
  206967. int res;
  206968. int iOff;
  206969. int nIncr;
  206970. ii += fts5GetVarint32(&pLeaf->p[ii], nIncr);
  206971. iTermOff += nIncr;
  206972. iOff = iTermOff;
  206973. if( iOff>=pLeaf->szLeaf ){
  206974. p->rc = FTS5_CORRUPT;
  206975. }else if( iTermOff==nIncr ){
  206976. int nByte;
  206977. iOff += fts5GetVarint32(&pLeaf->p[iOff], nByte);
  206978. if( (iOff+nByte)>pLeaf->szLeaf ){
  206979. p->rc = FTS5_CORRUPT;
  206980. }else{
  206981. fts5BufferSet(&p->rc, &buf1, nByte, &pLeaf->p[iOff]);
  206982. }
  206983. }else{
  206984. int nKeep, nByte;
  206985. iOff += fts5GetVarint32(&pLeaf->p[iOff], nKeep);
  206986. iOff += fts5GetVarint32(&pLeaf->p[iOff], nByte);
  206987. if( nKeep>buf1.n || (iOff+nByte)>pLeaf->szLeaf ){
  206988. p->rc = FTS5_CORRUPT;
  206989. }else{
  206990. buf1.n = nKeep;
  206991. fts5BufferAppendBlob(&p->rc, &buf1, nByte, &pLeaf->p[iOff]);
  206992. }
  206993. if( p->rc==SQLITE_OK ){
  206994. res = fts5BufferCompare(&buf1, &buf2);
  206995. if( res<=0 ) p->rc = FTS5_CORRUPT;
  206996. }
  206997. }
  206998. fts5BufferSet(&p->rc, &buf2, buf1.n, buf1.p);
  206999. }
  207000. fts5BufferFree(&buf1);
  207001. fts5BufferFree(&buf2);
  207002. }
  207003. static void fts5IndexIntegrityCheckSegment(
  207004. Fts5Index *p, /* FTS5 backend object */
  207005. Fts5StructureSegment *pSeg /* Segment to check internal consistency */
  207006. ){
  207007. Fts5Config *pConfig = p->pConfig;
  207008. sqlite3_stmt *pStmt = 0;
  207009. int rc2;
  207010. int iIdxPrevLeaf = pSeg->pgnoFirst-1;
  207011. int iDlidxPrevLeaf = pSeg->pgnoLast;
  207012. if( pSeg->pgnoFirst==0 ) return;
  207013. fts5IndexPrepareStmt(p, &pStmt, sqlite3_mprintf(
  207014. "SELECT segid, term, (pgno>>1), (pgno&1) FROM %Q.'%q_idx' WHERE segid=%d "
  207015. "ORDER BY 1, 2",
  207016. pConfig->zDb, pConfig->zName, pSeg->iSegid
  207017. ));
  207018. /* Iterate through the b-tree hierarchy. */
  207019. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  207020. i64 iRow; /* Rowid for this leaf */
  207021. Fts5Data *pLeaf; /* Data for this leaf */
  207022. const char *zIdxTerm = (const char*)sqlite3_column_blob(pStmt, 1);
  207023. int nIdxTerm = sqlite3_column_bytes(pStmt, 1);
  207024. int iIdxLeaf = sqlite3_column_int(pStmt, 2);
  207025. int bIdxDlidx = sqlite3_column_int(pStmt, 3);
  207026. /* If the leaf in question has already been trimmed from the segment,
  207027. ** ignore this b-tree entry. Otherwise, load it into memory. */
  207028. if( iIdxLeaf<pSeg->pgnoFirst ) continue;
  207029. iRow = FTS5_SEGMENT_ROWID(pSeg->iSegid, iIdxLeaf);
  207030. pLeaf = fts5LeafRead(p, iRow);
  207031. if( pLeaf==0 ) break;
  207032. /* Check that the leaf contains at least one term, and that it is equal
  207033. ** to or larger than the split-key in zIdxTerm. Also check that if there
  207034. ** is also a rowid pointer within the leaf page header, it points to a
  207035. ** location before the term. */
  207036. if( pLeaf->nn<=pLeaf->szLeaf ){
  207037. p->rc = FTS5_CORRUPT;
  207038. }else{
  207039. int iOff; /* Offset of first term on leaf */
  207040. int iRowidOff; /* Offset of first rowid on leaf */
  207041. int nTerm; /* Size of term on leaf in bytes */
  207042. int res; /* Comparison of term and split-key */
  207043. iOff = fts5LeafFirstTermOff(pLeaf);
  207044. iRowidOff = fts5LeafFirstRowidOff(pLeaf);
  207045. if( iRowidOff>=iOff || iOff>=pLeaf->szLeaf ){
  207046. p->rc = FTS5_CORRUPT;
  207047. }else{
  207048. iOff += fts5GetVarint32(&pLeaf->p[iOff], nTerm);
  207049. res = fts5Memcmp(&pLeaf->p[iOff], zIdxTerm, MIN(nTerm, nIdxTerm));
  207050. if( res==0 ) res = nTerm - nIdxTerm;
  207051. if( res<0 ) p->rc = FTS5_CORRUPT;
  207052. }
  207053. fts5IntegrityCheckPgidx(p, pLeaf);
  207054. }
  207055. fts5DataRelease(pLeaf);
  207056. if( p->rc ) break;
  207057. /* Now check that the iter.nEmpty leaves following the current leaf
  207058. ** (a) exist and (b) contain no terms. */
  207059. fts5IndexIntegrityCheckEmpty(
  207060. p, pSeg, iIdxPrevLeaf+1, iDlidxPrevLeaf+1, iIdxLeaf-1
  207061. );
  207062. if( p->rc ) break;
  207063. /* If there is a doclist-index, check that it looks right. */
  207064. if( bIdxDlidx ){
  207065. Fts5DlidxIter *pDlidx = 0; /* For iterating through doclist index */
  207066. int iPrevLeaf = iIdxLeaf;
  207067. int iSegid = pSeg->iSegid;
  207068. int iPg = 0;
  207069. i64 iKey;
  207070. for(pDlidx=fts5DlidxIterInit(p, 0, iSegid, iIdxLeaf);
  207071. fts5DlidxIterEof(p, pDlidx)==0;
  207072. fts5DlidxIterNext(p, pDlidx)
  207073. ){
  207074. /* Check any rowid-less pages that occur before the current leaf. */
  207075. for(iPg=iPrevLeaf+1; iPg<fts5DlidxIterPgno(pDlidx); iPg++){
  207076. iKey = FTS5_SEGMENT_ROWID(iSegid, iPg);
  207077. pLeaf = fts5DataRead(p, iKey);
  207078. if( pLeaf ){
  207079. if( fts5LeafFirstRowidOff(pLeaf)!=0 ) p->rc = FTS5_CORRUPT;
  207080. fts5DataRelease(pLeaf);
  207081. }
  207082. }
  207083. iPrevLeaf = fts5DlidxIterPgno(pDlidx);
  207084. /* Check that the leaf page indicated by the iterator really does
  207085. ** contain the rowid suggested by the same. */
  207086. iKey = FTS5_SEGMENT_ROWID(iSegid, iPrevLeaf);
  207087. pLeaf = fts5DataRead(p, iKey);
  207088. if( pLeaf ){
  207089. i64 iRowid;
  207090. int iRowidOff = fts5LeafFirstRowidOff(pLeaf);
  207091. ASSERT_SZLEAF_OK(pLeaf);
  207092. if( iRowidOff>=pLeaf->szLeaf ){
  207093. p->rc = FTS5_CORRUPT;
  207094. }else{
  207095. fts5GetVarint(&pLeaf->p[iRowidOff], (u64*)&iRowid);
  207096. if( iRowid!=fts5DlidxIterRowid(pDlidx) ) p->rc = FTS5_CORRUPT;
  207097. }
  207098. fts5DataRelease(pLeaf);
  207099. }
  207100. }
  207101. iDlidxPrevLeaf = iPg;
  207102. fts5DlidxIterFree(pDlidx);
  207103. fts5TestDlidxReverse(p, iSegid, iIdxLeaf);
  207104. }else{
  207105. iDlidxPrevLeaf = pSeg->pgnoLast;
  207106. /* TODO: Check there is no doclist index */
  207107. }
  207108. iIdxPrevLeaf = iIdxLeaf;
  207109. }
  207110. rc2 = sqlite3_finalize(pStmt);
  207111. if( p->rc==SQLITE_OK ) p->rc = rc2;
  207112. /* Page iter.iLeaf must now be the rightmost leaf-page in the segment */
  207113. #if 0
  207114. if( p->rc==SQLITE_OK && iter.iLeaf!=pSeg->pgnoLast ){
  207115. p->rc = FTS5_CORRUPT;
  207116. }
  207117. #endif
  207118. }
  207119. /*
  207120. ** Run internal checks to ensure that the FTS index (a) is internally
  207121. ** consistent and (b) contains entries for which the XOR of the checksums
  207122. ** as calculated by sqlite3Fts5IndexEntryCksum() is cksum.
  207123. **
  207124. ** Return SQLITE_CORRUPT if any of the internal checks fail, or if the
  207125. ** checksum does not match. Return SQLITE_OK if all checks pass without
  207126. ** error, or some other SQLite error code if another error (e.g. OOM)
  207127. ** occurs.
  207128. */
  207129. static int sqlite3Fts5IndexIntegrityCheck(Fts5Index *p, u64 cksum){
  207130. int eDetail = p->pConfig->eDetail;
  207131. u64 cksum2 = 0; /* Checksum based on contents of indexes */
  207132. Fts5Buffer poslist = {0,0,0}; /* Buffer used to hold a poslist */
  207133. Fts5Iter *pIter; /* Used to iterate through entire index */
  207134. Fts5Structure *pStruct; /* Index structure */
  207135. #ifdef SQLITE_DEBUG
  207136. /* Used by extra internal tests only run if NDEBUG is not defined */
  207137. u64 cksum3 = 0; /* Checksum based on contents of indexes */
  207138. Fts5Buffer term = {0,0,0}; /* Buffer used to hold most recent term */
  207139. #endif
  207140. const int flags = FTS5INDEX_QUERY_NOOUTPUT;
  207141. /* Load the FTS index structure */
  207142. pStruct = fts5StructureRead(p);
  207143. /* Check that the internal nodes of each segment match the leaves */
  207144. if( pStruct ){
  207145. int iLvl, iSeg;
  207146. for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
  207147. for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
  207148. Fts5StructureSegment *pSeg = &pStruct->aLevel[iLvl].aSeg[iSeg];
  207149. fts5IndexIntegrityCheckSegment(p, pSeg);
  207150. }
  207151. }
  207152. }
  207153. /* The cksum argument passed to this function is a checksum calculated
  207154. ** based on all expected entries in the FTS index (including prefix index
  207155. ** entries). This block checks that a checksum calculated based on the
  207156. ** actual contents of FTS index is identical.
  207157. **
  207158. ** Two versions of the same checksum are calculated. The first (stack
  207159. ** variable cksum2) based on entries extracted from the full-text index
  207160. ** while doing a linear scan of each individual index in turn.
  207161. **
  207162. ** As each term visited by the linear scans, a separate query for the
  207163. ** same term is performed. cksum3 is calculated based on the entries
  207164. ** extracted by these queries.
  207165. */
  207166. for(fts5MultiIterNew(p, pStruct, flags, 0, 0, 0, -1, 0, &pIter);
  207167. fts5MultiIterEof(p, pIter)==0;
  207168. fts5MultiIterNext(p, pIter, 0, 0)
  207169. ){
  207170. int n; /* Size of term in bytes */
  207171. i64 iPos = 0; /* Position read from poslist */
  207172. int iOff = 0; /* Offset within poslist */
  207173. i64 iRowid = fts5MultiIterRowid(pIter);
  207174. char *z = (char*)fts5MultiIterTerm(pIter, &n);
  207175. /* If this is a new term, query for it. Update cksum3 with the results. */
  207176. fts5TestTerm(p, &term, z, n, cksum2, &cksum3);
  207177. if( eDetail==FTS5_DETAIL_NONE ){
  207178. if( 0==fts5MultiIterIsEmpty(p, pIter) ){
  207179. cksum2 ^= sqlite3Fts5IndexEntryCksum(iRowid, 0, 0, -1, z, n);
  207180. }
  207181. }else{
  207182. poslist.n = 0;
  207183. fts5SegiterPoslist(p, &pIter->aSeg[pIter->aFirst[1].iFirst], 0, &poslist);
  207184. while( 0==sqlite3Fts5PoslistNext64(poslist.p, poslist.n, &iOff, &iPos) ){
  207185. int iCol = FTS5_POS2COLUMN(iPos);
  207186. int iTokOff = FTS5_POS2OFFSET(iPos);
  207187. cksum2 ^= sqlite3Fts5IndexEntryCksum(iRowid, iCol, iTokOff, -1, z, n);
  207188. }
  207189. }
  207190. }
  207191. fts5TestTerm(p, &term, 0, 0, cksum2, &cksum3);
  207192. fts5MultiIterFree(pIter);
  207193. if( p->rc==SQLITE_OK && cksum!=cksum2 ) p->rc = FTS5_CORRUPT;
  207194. fts5StructureRelease(pStruct);
  207195. #ifdef SQLITE_DEBUG
  207196. fts5BufferFree(&term);
  207197. #endif
  207198. fts5BufferFree(&poslist);
  207199. return fts5IndexReturn(p);
  207200. }
  207201. /*************************************************************************
  207202. **************************************************************************
  207203. ** Below this point is the implementation of the fts5_decode() scalar
  207204. ** function only.
  207205. */
  207206. /*
  207207. ** Decode a segment-data rowid from the %_data table. This function is
  207208. ** the opposite of macro FTS5_SEGMENT_ROWID().
  207209. */
  207210. static void fts5DecodeRowid(
  207211. i64 iRowid, /* Rowid from %_data table */
  207212. int *piSegid, /* OUT: Segment id */
  207213. int *pbDlidx, /* OUT: Dlidx flag */
  207214. int *piHeight, /* OUT: Height */
  207215. int *piPgno /* OUT: Page number */
  207216. ){
  207217. *piPgno = (int)(iRowid & (((i64)1 << FTS5_DATA_PAGE_B) - 1));
  207218. iRowid >>= FTS5_DATA_PAGE_B;
  207219. *piHeight = (int)(iRowid & (((i64)1 << FTS5_DATA_HEIGHT_B) - 1));
  207220. iRowid >>= FTS5_DATA_HEIGHT_B;
  207221. *pbDlidx = (int)(iRowid & 0x0001);
  207222. iRowid >>= FTS5_DATA_DLI_B;
  207223. *piSegid = (int)(iRowid & (((i64)1 << FTS5_DATA_ID_B) - 1));
  207224. }
  207225. static void fts5DebugRowid(int *pRc, Fts5Buffer *pBuf, i64 iKey){
  207226. int iSegid, iHeight, iPgno, bDlidx; /* Rowid compenents */
  207227. fts5DecodeRowid(iKey, &iSegid, &bDlidx, &iHeight, &iPgno);
  207228. if( iSegid==0 ){
  207229. if( iKey==FTS5_AVERAGES_ROWID ){
  207230. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "{averages} ");
  207231. }else{
  207232. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "{structure}");
  207233. }
  207234. }
  207235. else{
  207236. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "{%ssegid=%d h=%d pgno=%d}",
  207237. bDlidx ? "dlidx " : "", iSegid, iHeight, iPgno
  207238. );
  207239. }
  207240. }
  207241. static void fts5DebugStructure(
  207242. int *pRc, /* IN/OUT: error code */
  207243. Fts5Buffer *pBuf,
  207244. Fts5Structure *p
  207245. ){
  207246. int iLvl, iSeg; /* Iterate through levels, segments */
  207247. for(iLvl=0; iLvl<p->nLevel; iLvl++){
  207248. Fts5StructureLevel *pLvl = &p->aLevel[iLvl];
  207249. sqlite3Fts5BufferAppendPrintf(pRc, pBuf,
  207250. " {lvl=%d nMerge=%d nSeg=%d", iLvl, pLvl->nMerge, pLvl->nSeg
  207251. );
  207252. for(iSeg=0; iSeg<pLvl->nSeg; iSeg++){
  207253. Fts5StructureSegment *pSeg = &pLvl->aSeg[iSeg];
  207254. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " {id=%d leaves=%d..%d}",
  207255. pSeg->iSegid, pSeg->pgnoFirst, pSeg->pgnoLast
  207256. );
  207257. }
  207258. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "}");
  207259. }
  207260. }
  207261. /*
  207262. ** This is part of the fts5_decode() debugging aid.
  207263. **
  207264. ** Arguments pBlob/nBlob contain a serialized Fts5Structure object. This
  207265. ** function appends a human-readable representation of the same object
  207266. ** to the buffer passed as the second argument.
  207267. */
  207268. static void fts5DecodeStructure(
  207269. int *pRc, /* IN/OUT: error code */
  207270. Fts5Buffer *pBuf,
  207271. const u8 *pBlob, int nBlob
  207272. ){
  207273. int rc; /* Return code */
  207274. Fts5Structure *p = 0; /* Decoded structure object */
  207275. rc = fts5StructureDecode(pBlob, nBlob, 0, &p);
  207276. if( rc!=SQLITE_OK ){
  207277. *pRc = rc;
  207278. return;
  207279. }
  207280. fts5DebugStructure(pRc, pBuf, p);
  207281. fts5StructureRelease(p);
  207282. }
  207283. /*
  207284. ** This is part of the fts5_decode() debugging aid.
  207285. **
  207286. ** Arguments pBlob/nBlob contain an "averages" record. This function
  207287. ** appends a human-readable representation of record to the buffer passed
  207288. ** as the second argument.
  207289. */
  207290. static void fts5DecodeAverages(
  207291. int *pRc, /* IN/OUT: error code */
  207292. Fts5Buffer *pBuf,
  207293. const u8 *pBlob, int nBlob
  207294. ){
  207295. int i = 0;
  207296. const char *zSpace = "";
  207297. while( i<nBlob ){
  207298. u64 iVal;
  207299. i += sqlite3Fts5GetVarint(&pBlob[i], &iVal);
  207300. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "%s%d", zSpace, (int)iVal);
  207301. zSpace = " ";
  207302. }
  207303. }
  207304. /*
  207305. ** Buffer (a/n) is assumed to contain a list of serialized varints. Read
  207306. ** each varint and append its string representation to buffer pBuf. Return
  207307. ** after either the input buffer is exhausted or a 0 value is read.
  207308. **
  207309. ** The return value is the number of bytes read from the input buffer.
  207310. */
  207311. static int fts5DecodePoslist(int *pRc, Fts5Buffer *pBuf, const u8 *a, int n){
  207312. int iOff = 0;
  207313. while( iOff<n ){
  207314. int iVal;
  207315. iOff += fts5GetVarint32(&a[iOff], iVal);
  207316. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " %d", iVal);
  207317. }
  207318. return iOff;
  207319. }
  207320. /*
  207321. ** The start of buffer (a/n) contains the start of a doclist. The doclist
  207322. ** may or may not finish within the buffer. This function appends a text
  207323. ** representation of the part of the doclist that is present to buffer
  207324. ** pBuf.
  207325. **
  207326. ** The return value is the number of bytes read from the input buffer.
  207327. */
  207328. static int fts5DecodeDoclist(int *pRc, Fts5Buffer *pBuf, const u8 *a, int n){
  207329. i64 iDocid = 0;
  207330. int iOff = 0;
  207331. if( n>0 ){
  207332. iOff = sqlite3Fts5GetVarint(a, (u64*)&iDocid);
  207333. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " id=%lld", iDocid);
  207334. }
  207335. while( iOff<n ){
  207336. int nPos;
  207337. int bDel;
  207338. iOff += fts5GetPoslistSize(&a[iOff], &nPos, &bDel);
  207339. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " nPos=%d%s", nPos, bDel?"*":"");
  207340. iOff += fts5DecodePoslist(pRc, pBuf, &a[iOff], MIN(n-iOff, nPos));
  207341. if( iOff<n ){
  207342. i64 iDelta;
  207343. iOff += sqlite3Fts5GetVarint(&a[iOff], (u64*)&iDelta);
  207344. iDocid += iDelta;
  207345. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " id=%lld", iDocid);
  207346. }
  207347. }
  207348. return iOff;
  207349. }
  207350. /*
  207351. ** This function is part of the fts5_decode() debugging function. It is
  207352. ** only ever used with detail=none tables.
  207353. **
  207354. ** Buffer (pData/nData) contains a doclist in the format used by detail=none
  207355. ** tables. This function appends a human-readable version of that list to
  207356. ** buffer pBuf.
  207357. **
  207358. ** If *pRc is other than SQLITE_OK when this function is called, it is a
  207359. ** no-op. If an OOM or other error occurs within this function, *pRc is
  207360. ** set to an SQLite error code before returning. The final state of buffer
  207361. ** pBuf is undefined in this case.
  207362. */
  207363. static void fts5DecodeRowidList(
  207364. int *pRc, /* IN/OUT: Error code */
  207365. Fts5Buffer *pBuf, /* Buffer to append text to */
  207366. const u8 *pData, int nData /* Data to decode list-of-rowids from */
  207367. ){
  207368. int i = 0;
  207369. i64 iRowid = 0;
  207370. while( i<nData ){
  207371. const char *zApp = "";
  207372. u64 iVal;
  207373. i += sqlite3Fts5GetVarint(&pData[i], &iVal);
  207374. iRowid += iVal;
  207375. if( i<nData && pData[i]==0x00 ){
  207376. i++;
  207377. if( i<nData && pData[i]==0x00 ){
  207378. i++;
  207379. zApp = "+";
  207380. }else{
  207381. zApp = "*";
  207382. }
  207383. }
  207384. sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " %lld%s", iRowid, zApp);
  207385. }
  207386. }
  207387. /*
  207388. ** The implementation of user-defined scalar function fts5_decode().
  207389. */
  207390. static void fts5DecodeFunction(
  207391. sqlite3_context *pCtx, /* Function call context */
  207392. int nArg, /* Number of args (always 2) */
  207393. sqlite3_value **apVal /* Function arguments */
  207394. ){
  207395. i64 iRowid; /* Rowid for record being decoded */
  207396. int iSegid,iHeight,iPgno,bDlidx;/* Rowid components */
  207397. const u8 *aBlob; int n; /* Record to decode */
  207398. u8 *a = 0;
  207399. Fts5Buffer s; /* Build up text to return here */
  207400. int rc = SQLITE_OK; /* Return code */
  207401. sqlite3_int64 nSpace = 0;
  207402. int eDetailNone = (sqlite3_user_data(pCtx)!=0);
  207403. assert( nArg==2 );
  207404. UNUSED_PARAM(nArg);
  207405. memset(&s, 0, sizeof(Fts5Buffer));
  207406. iRowid = sqlite3_value_int64(apVal[0]);
  207407. /* Make a copy of the second argument (a blob) in aBlob[]. The aBlob[]
  207408. ** copy is followed by FTS5_DATA_ZERO_PADDING 0x00 bytes, which prevents
  207409. ** buffer overreads even if the record is corrupt. */
  207410. n = sqlite3_value_bytes(apVal[1]);
  207411. aBlob = sqlite3_value_blob(apVal[1]);
  207412. nSpace = n + FTS5_DATA_ZERO_PADDING;
  207413. a = (u8*)sqlite3Fts5MallocZero(&rc, nSpace);
  207414. if( a==0 ) goto decode_out;
  207415. if( n>0 ) memcpy(a, aBlob, n);
  207416. fts5DecodeRowid(iRowid, &iSegid, &bDlidx, &iHeight, &iPgno);
  207417. fts5DebugRowid(&rc, &s, iRowid);
  207418. if( bDlidx ){
  207419. Fts5Data dlidx;
  207420. Fts5DlidxLvl lvl;
  207421. dlidx.p = a;
  207422. dlidx.nn = n;
  207423. memset(&lvl, 0, sizeof(Fts5DlidxLvl));
  207424. lvl.pData = &dlidx;
  207425. lvl.iLeafPgno = iPgno;
  207426. for(fts5DlidxLvlNext(&lvl); lvl.bEof==0; fts5DlidxLvlNext(&lvl)){
  207427. sqlite3Fts5BufferAppendPrintf(&rc, &s,
  207428. " %d(%lld)", lvl.iLeafPgno, lvl.iRowid
  207429. );
  207430. }
  207431. }else if( iSegid==0 ){
  207432. if( iRowid==FTS5_AVERAGES_ROWID ){
  207433. fts5DecodeAverages(&rc, &s, a, n);
  207434. }else{
  207435. fts5DecodeStructure(&rc, &s, a, n);
  207436. }
  207437. }else if( eDetailNone ){
  207438. Fts5Buffer term; /* Current term read from page */
  207439. int szLeaf;
  207440. int iPgidxOff = szLeaf = fts5GetU16(&a[2]);
  207441. int iTermOff;
  207442. int nKeep = 0;
  207443. int iOff;
  207444. memset(&term, 0, sizeof(Fts5Buffer));
  207445. /* Decode any entries that occur before the first term. */
  207446. if( szLeaf<n ){
  207447. iPgidxOff += fts5GetVarint32(&a[iPgidxOff], iTermOff);
  207448. }else{
  207449. iTermOff = szLeaf;
  207450. }
  207451. fts5DecodeRowidList(&rc, &s, &a[4], iTermOff-4);
  207452. iOff = iTermOff;
  207453. while( iOff<szLeaf ){
  207454. int nAppend;
  207455. /* Read the term data for the next term*/
  207456. iOff += fts5GetVarint32(&a[iOff], nAppend);
  207457. term.n = nKeep;
  207458. fts5BufferAppendBlob(&rc, &term, nAppend, &a[iOff]);
  207459. sqlite3Fts5BufferAppendPrintf(
  207460. &rc, &s, " term=%.*s", term.n, (const char*)term.p
  207461. );
  207462. iOff += nAppend;
  207463. /* Figure out where the doclist for this term ends */
  207464. if( iPgidxOff<n ){
  207465. int nIncr;
  207466. iPgidxOff += fts5GetVarint32(&a[iPgidxOff], nIncr);
  207467. iTermOff += nIncr;
  207468. }else{
  207469. iTermOff = szLeaf;
  207470. }
  207471. fts5DecodeRowidList(&rc, &s, &a[iOff], iTermOff-iOff);
  207472. iOff = iTermOff;
  207473. if( iOff<szLeaf ){
  207474. iOff += fts5GetVarint32(&a[iOff], nKeep);
  207475. }
  207476. }
  207477. fts5BufferFree(&term);
  207478. }else{
  207479. Fts5Buffer term; /* Current term read from page */
  207480. int szLeaf; /* Offset of pgidx in a[] */
  207481. int iPgidxOff;
  207482. int iPgidxPrev = 0; /* Previous value read from pgidx */
  207483. int iTermOff = 0;
  207484. int iRowidOff = 0;
  207485. int iOff;
  207486. int nDoclist;
  207487. memset(&term, 0, sizeof(Fts5Buffer));
  207488. if( n<4 ){
  207489. sqlite3Fts5BufferSet(&rc, &s, 7, (const u8*)"corrupt");
  207490. goto decode_out;
  207491. }else{
  207492. iRowidOff = fts5GetU16(&a[0]);
  207493. iPgidxOff = szLeaf = fts5GetU16(&a[2]);
  207494. if( iPgidxOff<n ){
  207495. fts5GetVarint32(&a[iPgidxOff], iTermOff);
  207496. }else if( iPgidxOff>n ){
  207497. rc = FTS5_CORRUPT;
  207498. goto decode_out;
  207499. }
  207500. }
  207501. /* Decode the position list tail at the start of the page */
  207502. if( iRowidOff!=0 ){
  207503. iOff = iRowidOff;
  207504. }else if( iTermOff!=0 ){
  207505. iOff = iTermOff;
  207506. }else{
  207507. iOff = szLeaf;
  207508. }
  207509. if( iOff>n ){
  207510. rc = FTS5_CORRUPT;
  207511. goto decode_out;
  207512. }
  207513. fts5DecodePoslist(&rc, &s, &a[4], iOff-4);
  207514. /* Decode any more doclist data that appears on the page before the
  207515. ** first term. */
  207516. nDoclist = (iTermOff ? iTermOff : szLeaf) - iOff;
  207517. if( nDoclist+iOff>n ){
  207518. rc = FTS5_CORRUPT;
  207519. goto decode_out;
  207520. }
  207521. fts5DecodeDoclist(&rc, &s, &a[iOff], nDoclist);
  207522. while( iPgidxOff<n && rc==SQLITE_OK ){
  207523. int bFirst = (iPgidxOff==szLeaf); /* True for first term on page */
  207524. int nByte; /* Bytes of data */
  207525. int iEnd;
  207526. iPgidxOff += fts5GetVarint32(&a[iPgidxOff], nByte);
  207527. iPgidxPrev += nByte;
  207528. iOff = iPgidxPrev;
  207529. if( iPgidxOff<n ){
  207530. fts5GetVarint32(&a[iPgidxOff], nByte);
  207531. iEnd = iPgidxPrev + nByte;
  207532. }else{
  207533. iEnd = szLeaf;
  207534. }
  207535. if( iEnd>szLeaf ){
  207536. rc = FTS5_CORRUPT;
  207537. break;
  207538. }
  207539. if( bFirst==0 ){
  207540. iOff += fts5GetVarint32(&a[iOff], nByte);
  207541. if( nByte>term.n ){
  207542. rc = FTS5_CORRUPT;
  207543. break;
  207544. }
  207545. term.n = nByte;
  207546. }
  207547. iOff += fts5GetVarint32(&a[iOff], nByte);
  207548. if( iOff+nByte>n ){
  207549. rc = FTS5_CORRUPT;
  207550. break;
  207551. }
  207552. fts5BufferAppendBlob(&rc, &term, nByte, &a[iOff]);
  207553. iOff += nByte;
  207554. sqlite3Fts5BufferAppendPrintf(
  207555. &rc, &s, " term=%.*s", term.n, (const char*)term.p
  207556. );
  207557. iOff += fts5DecodeDoclist(&rc, &s, &a[iOff], iEnd-iOff);
  207558. }
  207559. fts5BufferFree(&term);
  207560. }
  207561. decode_out:
  207562. sqlite3_free(a);
  207563. if( rc==SQLITE_OK ){
  207564. sqlite3_result_text(pCtx, (const char*)s.p, s.n, SQLITE_TRANSIENT);
  207565. }else{
  207566. sqlite3_result_error_code(pCtx, rc);
  207567. }
  207568. fts5BufferFree(&s);
  207569. }
  207570. /*
  207571. ** The implementation of user-defined scalar function fts5_rowid().
  207572. */
  207573. static void fts5RowidFunction(
  207574. sqlite3_context *pCtx, /* Function call context */
  207575. int nArg, /* Number of args (always 2) */
  207576. sqlite3_value **apVal /* Function arguments */
  207577. ){
  207578. const char *zArg;
  207579. if( nArg==0 ){
  207580. sqlite3_result_error(pCtx, "should be: fts5_rowid(subject, ....)", -1);
  207581. }else{
  207582. zArg = (const char*)sqlite3_value_text(apVal[0]);
  207583. if( 0==sqlite3_stricmp(zArg, "segment") ){
  207584. i64 iRowid;
  207585. int segid, pgno;
  207586. if( nArg!=3 ){
  207587. sqlite3_result_error(pCtx,
  207588. "should be: fts5_rowid('segment', segid, pgno))", -1
  207589. );
  207590. }else{
  207591. segid = sqlite3_value_int(apVal[1]);
  207592. pgno = sqlite3_value_int(apVal[2]);
  207593. iRowid = FTS5_SEGMENT_ROWID(segid, pgno);
  207594. sqlite3_result_int64(pCtx, iRowid);
  207595. }
  207596. }else{
  207597. sqlite3_result_error(pCtx,
  207598. "first arg to fts5_rowid() must be 'segment'" , -1
  207599. );
  207600. }
  207601. }
  207602. }
  207603. /*
  207604. ** This is called as part of registering the FTS5 module with database
  207605. ** connection db. It registers several user-defined scalar functions useful
  207606. ** with FTS5.
  207607. **
  207608. ** If successful, SQLITE_OK is returned. If an error occurs, some other
  207609. ** SQLite error code is returned instead.
  207610. */
  207611. static int sqlite3Fts5IndexInit(sqlite3 *db){
  207612. int rc = sqlite3_create_function(
  207613. db, "fts5_decode", 2, SQLITE_UTF8, 0, fts5DecodeFunction, 0, 0
  207614. );
  207615. if( rc==SQLITE_OK ){
  207616. rc = sqlite3_create_function(
  207617. db, "fts5_decode_none", 2,
  207618. SQLITE_UTF8, (void*)db, fts5DecodeFunction, 0, 0
  207619. );
  207620. }
  207621. if( rc==SQLITE_OK ){
  207622. rc = sqlite3_create_function(
  207623. db, "fts5_rowid", -1, SQLITE_UTF8, 0, fts5RowidFunction, 0, 0
  207624. );
  207625. }
  207626. return rc;
  207627. }
  207628. static int sqlite3Fts5IndexReset(Fts5Index *p){
  207629. assert( p->pStruct==0 || p->iStructVersion!=0 );
  207630. if( fts5IndexDataVersion(p)!=p->iStructVersion ){
  207631. fts5StructureInvalidate(p);
  207632. }
  207633. return fts5IndexReturn(p);
  207634. }
  207635. /*
  207636. ** 2014 Jun 09
  207637. **
  207638. ** The author disclaims copyright to this source code. In place of
  207639. ** a legal notice, here is a blessing:
  207640. **
  207641. ** May you do good and not evil.
  207642. ** May you find forgiveness for yourself and forgive others.
  207643. ** May you share freely, never taking more than you give.
  207644. **
  207645. ******************************************************************************
  207646. **
  207647. ** This is an SQLite module implementing full-text search.
  207648. */
  207649. /* #include "fts5Int.h" */
  207650. /*
  207651. ** This variable is set to false when running tests for which the on disk
  207652. ** structures should not be corrupt. Otherwise, true. If it is false, extra
  207653. ** assert() conditions in the fts5 code are activated - conditions that are
  207654. ** only true if it is guaranteed that the fts5 database is not corrupt.
  207655. */
  207656. SQLITE_API int sqlite3_fts5_may_be_corrupt = 1;
  207657. typedef struct Fts5Auxdata Fts5Auxdata;
  207658. typedef struct Fts5Auxiliary Fts5Auxiliary;
  207659. typedef struct Fts5Cursor Fts5Cursor;
  207660. typedef struct Fts5FullTable Fts5FullTable;
  207661. typedef struct Fts5Sorter Fts5Sorter;
  207662. typedef struct Fts5TokenizerModule Fts5TokenizerModule;
  207663. /*
  207664. ** NOTES ON TRANSACTIONS:
  207665. **
  207666. ** SQLite invokes the following virtual table methods as transactions are
  207667. ** opened and closed by the user:
  207668. **
  207669. ** xBegin(): Start of a new transaction.
  207670. ** xSync(): Initial part of two-phase commit.
  207671. ** xCommit(): Final part of two-phase commit.
  207672. ** xRollback(): Rollback the transaction.
  207673. **
  207674. ** Anything that is required as part of a commit that may fail is performed
  207675. ** in the xSync() callback. Current versions of SQLite ignore any errors
  207676. ** returned by xCommit().
  207677. **
  207678. ** And as sub-transactions are opened/closed:
  207679. **
  207680. ** xSavepoint(int S): Open savepoint S.
  207681. ** xRelease(int S): Commit and close savepoint S.
  207682. ** xRollbackTo(int S): Rollback to start of savepoint S.
  207683. **
  207684. ** During a write-transaction the fts5_index.c module may cache some data
  207685. ** in-memory. It is flushed to disk whenever xSync(), xRelease() or
  207686. ** xSavepoint() is called. And discarded whenever xRollback() or xRollbackTo()
  207687. ** is called.
  207688. **
  207689. ** Additionally, if SQLITE_DEBUG is defined, an instance of the following
  207690. ** structure is used to record the current transaction state. This information
  207691. ** is not required, but it is used in the assert() statements executed by
  207692. ** function fts5CheckTransactionState() (see below).
  207693. */
  207694. struct Fts5TransactionState {
  207695. int eState; /* 0==closed, 1==open, 2==synced */
  207696. int iSavepoint; /* Number of open savepoints (0 -> none) */
  207697. };
  207698. /*
  207699. ** A single object of this type is allocated when the FTS5 module is
  207700. ** registered with a database handle. It is used to store pointers to
  207701. ** all registered FTS5 extensions - tokenizers and auxiliary functions.
  207702. */
  207703. struct Fts5Global {
  207704. fts5_api api; /* User visible part of object (see fts5.h) */
  207705. sqlite3 *db; /* Associated database connection */
  207706. i64 iNextId; /* Used to allocate unique cursor ids */
  207707. Fts5Auxiliary *pAux; /* First in list of all aux. functions */
  207708. Fts5TokenizerModule *pTok; /* First in list of all tokenizer modules */
  207709. Fts5TokenizerModule *pDfltTok; /* Default tokenizer module */
  207710. Fts5Cursor *pCsr; /* First in list of all open cursors */
  207711. };
  207712. /*
  207713. ** Each auxiliary function registered with the FTS5 module is represented
  207714. ** by an object of the following type. All such objects are stored as part
  207715. ** of the Fts5Global.pAux list.
  207716. */
  207717. struct Fts5Auxiliary {
  207718. Fts5Global *pGlobal; /* Global context for this function */
  207719. char *zFunc; /* Function name (nul-terminated) */
  207720. void *pUserData; /* User-data pointer */
  207721. fts5_extension_function xFunc; /* Callback function */
  207722. void (*xDestroy)(void*); /* Destructor function */
  207723. Fts5Auxiliary *pNext; /* Next registered auxiliary function */
  207724. };
  207725. /*
  207726. ** Each tokenizer module registered with the FTS5 module is represented
  207727. ** by an object of the following type. All such objects are stored as part
  207728. ** of the Fts5Global.pTok list.
  207729. */
  207730. struct Fts5TokenizerModule {
  207731. char *zName; /* Name of tokenizer */
  207732. void *pUserData; /* User pointer passed to xCreate() */
  207733. fts5_tokenizer x; /* Tokenizer functions */
  207734. void (*xDestroy)(void*); /* Destructor function */
  207735. Fts5TokenizerModule *pNext; /* Next registered tokenizer module */
  207736. };
  207737. struct Fts5FullTable {
  207738. Fts5Table p; /* Public class members from fts5Int.h */
  207739. Fts5Storage *pStorage; /* Document store */
  207740. Fts5Global *pGlobal; /* Global (connection wide) data */
  207741. Fts5Cursor *pSortCsr; /* Sort data from this cursor */
  207742. #ifdef SQLITE_DEBUG
  207743. struct Fts5TransactionState ts;
  207744. #endif
  207745. };
  207746. struct Fts5MatchPhrase {
  207747. Fts5Buffer *pPoslist; /* Pointer to current poslist */
  207748. int nTerm; /* Size of phrase in terms */
  207749. };
  207750. /*
  207751. ** pStmt:
  207752. ** SELECT rowid, <fts> FROM <fts> ORDER BY +rank;
  207753. **
  207754. ** aIdx[]:
  207755. ** There is one entry in the aIdx[] array for each phrase in the query,
  207756. ** the value of which is the offset within aPoslist[] following the last
  207757. ** byte of the position list for the corresponding phrase.
  207758. */
  207759. struct Fts5Sorter {
  207760. sqlite3_stmt *pStmt;
  207761. i64 iRowid; /* Current rowid */
  207762. const u8 *aPoslist; /* Position lists for current row */
  207763. int nIdx; /* Number of entries in aIdx[] */
  207764. int aIdx[1]; /* Offsets into aPoslist for current row */
  207765. };
  207766. /*
  207767. ** Virtual-table cursor object.
  207768. **
  207769. ** iSpecial:
  207770. ** If this is a 'special' query (refer to function fts5SpecialMatch()),
  207771. ** then this variable contains the result of the query.
  207772. **
  207773. ** iFirstRowid, iLastRowid:
  207774. ** These variables are only used for FTS5_PLAN_MATCH cursors. Assuming the
  207775. ** cursor iterates in ascending order of rowids, iFirstRowid is the lower
  207776. ** limit of rowids to return, and iLastRowid the upper. In other words, the
  207777. ** WHERE clause in the user's query might have been:
  207778. **
  207779. ** <tbl> MATCH <expr> AND rowid BETWEEN $iFirstRowid AND $iLastRowid
  207780. **
  207781. ** If the cursor iterates in descending order of rowid, iFirstRowid
  207782. ** is the upper limit (i.e. the "first" rowid visited) and iLastRowid
  207783. ** the lower.
  207784. */
  207785. struct Fts5Cursor {
  207786. sqlite3_vtab_cursor base; /* Base class used by SQLite core */
  207787. Fts5Cursor *pNext; /* Next cursor in Fts5Cursor.pCsr list */
  207788. int *aColumnSize; /* Values for xColumnSize() */
  207789. i64 iCsrId; /* Cursor id */
  207790. /* Zero from this point onwards on cursor reset */
  207791. int ePlan; /* FTS5_PLAN_XXX value */
  207792. int bDesc; /* True for "ORDER BY rowid DESC" queries */
  207793. i64 iFirstRowid; /* Return no rowids earlier than this */
  207794. i64 iLastRowid; /* Return no rowids later than this */
  207795. sqlite3_stmt *pStmt; /* Statement used to read %_content */
  207796. Fts5Expr *pExpr; /* Expression for MATCH queries */
  207797. Fts5Sorter *pSorter; /* Sorter for "ORDER BY rank" queries */
  207798. int csrflags; /* Mask of cursor flags (see below) */
  207799. i64 iSpecial; /* Result of special query */
  207800. /* "rank" function. Populated on demand from vtab.xColumn(). */
  207801. char *zRank; /* Custom rank function */
  207802. char *zRankArgs; /* Custom rank function args */
  207803. Fts5Auxiliary *pRank; /* Rank callback (or NULL) */
  207804. int nRankArg; /* Number of trailing arguments for rank() */
  207805. sqlite3_value **apRankArg; /* Array of trailing arguments */
  207806. sqlite3_stmt *pRankArgStmt; /* Origin of objects in apRankArg[] */
  207807. /* Auxiliary data storage */
  207808. Fts5Auxiliary *pAux; /* Currently executing extension function */
  207809. Fts5Auxdata *pAuxdata; /* First in linked list of saved aux-data */
  207810. /* Cache used by auxiliary functions xInst() and xInstCount() */
  207811. Fts5PoslistReader *aInstIter; /* One for each phrase */
  207812. int nInstAlloc; /* Size of aInst[] array (entries / 3) */
  207813. int nInstCount; /* Number of phrase instances */
  207814. int *aInst; /* 3 integers per phrase instance */
  207815. };
  207816. /*
  207817. ** Bits that make up the "idxNum" parameter passed indirectly by
  207818. ** xBestIndex() to xFilter().
  207819. */
  207820. #define FTS5_BI_MATCH 0x0001 /* <tbl> MATCH ? */
  207821. #define FTS5_BI_RANK 0x0002 /* rank MATCH ? */
  207822. #define FTS5_BI_ROWID_EQ 0x0004 /* rowid == ? */
  207823. #define FTS5_BI_ROWID_LE 0x0008 /* rowid <= ? */
  207824. #define FTS5_BI_ROWID_GE 0x0010 /* rowid >= ? */
  207825. #define FTS5_BI_ORDER_RANK 0x0020
  207826. #define FTS5_BI_ORDER_ROWID 0x0040
  207827. #define FTS5_BI_ORDER_DESC 0x0080
  207828. /*
  207829. ** Values for Fts5Cursor.csrflags
  207830. */
  207831. #define FTS5CSR_EOF 0x01
  207832. #define FTS5CSR_REQUIRE_CONTENT 0x02
  207833. #define FTS5CSR_REQUIRE_DOCSIZE 0x04
  207834. #define FTS5CSR_REQUIRE_INST 0x08
  207835. #define FTS5CSR_FREE_ZRANK 0x10
  207836. #define FTS5CSR_REQUIRE_RESEEK 0x20
  207837. #define FTS5CSR_REQUIRE_POSLIST 0x40
  207838. #define BitFlagAllTest(x,y) (((x) & (y))==(y))
  207839. #define BitFlagTest(x,y) (((x) & (y))!=0)
  207840. /*
  207841. ** Macros to Set(), Clear() and Test() cursor flags.
  207842. */
  207843. #define CsrFlagSet(pCsr, flag) ((pCsr)->csrflags |= (flag))
  207844. #define CsrFlagClear(pCsr, flag) ((pCsr)->csrflags &= ~(flag))
  207845. #define CsrFlagTest(pCsr, flag) ((pCsr)->csrflags & (flag))
  207846. struct Fts5Auxdata {
  207847. Fts5Auxiliary *pAux; /* Extension to which this belongs */
  207848. void *pPtr; /* Pointer value */
  207849. void(*xDelete)(void*); /* Destructor */
  207850. Fts5Auxdata *pNext; /* Next object in linked list */
  207851. };
  207852. #ifdef SQLITE_DEBUG
  207853. #define FTS5_BEGIN 1
  207854. #define FTS5_SYNC 2
  207855. #define FTS5_COMMIT 3
  207856. #define FTS5_ROLLBACK 4
  207857. #define FTS5_SAVEPOINT 5
  207858. #define FTS5_RELEASE 6
  207859. #define FTS5_ROLLBACKTO 7
  207860. static void fts5CheckTransactionState(Fts5FullTable *p, int op, int iSavepoint){
  207861. switch( op ){
  207862. case FTS5_BEGIN:
  207863. assert( p->ts.eState==0 );
  207864. p->ts.eState = 1;
  207865. p->ts.iSavepoint = -1;
  207866. break;
  207867. case FTS5_SYNC:
  207868. assert( p->ts.eState==1 );
  207869. p->ts.eState = 2;
  207870. break;
  207871. case FTS5_COMMIT:
  207872. assert( p->ts.eState==2 );
  207873. p->ts.eState = 0;
  207874. break;
  207875. case FTS5_ROLLBACK:
  207876. assert( p->ts.eState==1 || p->ts.eState==2 || p->ts.eState==0 );
  207877. p->ts.eState = 0;
  207878. break;
  207879. case FTS5_SAVEPOINT:
  207880. assert( p->ts.eState==1 );
  207881. assert( iSavepoint>=0 );
  207882. assert( iSavepoint>=p->ts.iSavepoint );
  207883. p->ts.iSavepoint = iSavepoint;
  207884. break;
  207885. case FTS5_RELEASE:
  207886. assert( p->ts.eState==1 );
  207887. assert( iSavepoint>=0 );
  207888. assert( iSavepoint<=p->ts.iSavepoint );
  207889. p->ts.iSavepoint = iSavepoint-1;
  207890. break;
  207891. case FTS5_ROLLBACKTO:
  207892. assert( p->ts.eState==1 );
  207893. assert( iSavepoint>=-1 );
  207894. /* The following assert() can fail if another vtab strikes an error
  207895. ** within an xSavepoint() call then SQLite calls xRollbackTo() - without
  207896. ** having called xSavepoint() on this vtab. */
  207897. /* assert( iSavepoint<=p->ts.iSavepoint ); */
  207898. p->ts.iSavepoint = iSavepoint;
  207899. break;
  207900. }
  207901. }
  207902. #else
  207903. # define fts5CheckTransactionState(x,y,z)
  207904. #endif
  207905. /*
  207906. ** Return true if pTab is a contentless table.
  207907. */
  207908. static int fts5IsContentless(Fts5FullTable *pTab){
  207909. return pTab->p.pConfig->eContent==FTS5_CONTENT_NONE;
  207910. }
  207911. /*
  207912. ** Delete a virtual table handle allocated by fts5InitVtab().
  207913. */
  207914. static void fts5FreeVtab(Fts5FullTable *pTab){
  207915. if( pTab ){
  207916. sqlite3Fts5IndexClose(pTab->p.pIndex);
  207917. sqlite3Fts5StorageClose(pTab->pStorage);
  207918. sqlite3Fts5ConfigFree(pTab->p.pConfig);
  207919. sqlite3_free(pTab);
  207920. }
  207921. }
  207922. /*
  207923. ** The xDisconnect() virtual table method.
  207924. */
  207925. static int fts5DisconnectMethod(sqlite3_vtab *pVtab){
  207926. fts5FreeVtab((Fts5FullTable*)pVtab);
  207927. return SQLITE_OK;
  207928. }
  207929. /*
  207930. ** The xDestroy() virtual table method.
  207931. */
  207932. static int fts5DestroyMethod(sqlite3_vtab *pVtab){
  207933. Fts5Table *pTab = (Fts5Table*)pVtab;
  207934. int rc = sqlite3Fts5DropAll(pTab->pConfig);
  207935. if( rc==SQLITE_OK ){
  207936. fts5FreeVtab((Fts5FullTable*)pVtab);
  207937. }
  207938. return rc;
  207939. }
  207940. /*
  207941. ** This function is the implementation of both the xConnect and xCreate
  207942. ** methods of the FTS3 virtual table.
  207943. **
  207944. ** The argv[] array contains the following:
  207945. **
  207946. ** argv[0] -> module name ("fts5")
  207947. ** argv[1] -> database name
  207948. ** argv[2] -> table name
  207949. ** argv[...] -> "column name" and other module argument fields.
  207950. */
  207951. static int fts5InitVtab(
  207952. int bCreate, /* True for xCreate, false for xConnect */
  207953. sqlite3 *db, /* The SQLite database connection */
  207954. void *pAux, /* Hash table containing tokenizers */
  207955. int argc, /* Number of elements in argv array */
  207956. const char * const *argv, /* xCreate/xConnect argument array */
  207957. sqlite3_vtab **ppVTab, /* Write the resulting vtab structure here */
  207958. char **pzErr /* Write any error message here */
  207959. ){
  207960. Fts5Global *pGlobal = (Fts5Global*)pAux;
  207961. const char **azConfig = (const char**)argv;
  207962. int rc = SQLITE_OK; /* Return code */
  207963. Fts5Config *pConfig = 0; /* Results of parsing argc/argv */
  207964. Fts5FullTable *pTab = 0; /* New virtual table object */
  207965. /* Allocate the new vtab object and parse the configuration */
  207966. pTab = (Fts5FullTable*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5FullTable));
  207967. if( rc==SQLITE_OK ){
  207968. rc = sqlite3Fts5ConfigParse(pGlobal, db, argc, azConfig, &pConfig, pzErr);
  207969. assert( (rc==SQLITE_OK && *pzErr==0) || pConfig==0 );
  207970. }
  207971. if( rc==SQLITE_OK ){
  207972. pTab->p.pConfig = pConfig;
  207973. pTab->pGlobal = pGlobal;
  207974. }
  207975. /* Open the index sub-system */
  207976. if( rc==SQLITE_OK ){
  207977. rc = sqlite3Fts5IndexOpen(pConfig, bCreate, &pTab->p.pIndex, pzErr);
  207978. }
  207979. /* Open the storage sub-system */
  207980. if( rc==SQLITE_OK ){
  207981. rc = sqlite3Fts5StorageOpen(
  207982. pConfig, pTab->p.pIndex, bCreate, &pTab->pStorage, pzErr
  207983. );
  207984. }
  207985. /* Call sqlite3_declare_vtab() */
  207986. if( rc==SQLITE_OK ){
  207987. rc = sqlite3Fts5ConfigDeclareVtab(pConfig);
  207988. }
  207989. /* Load the initial configuration */
  207990. if( rc==SQLITE_OK ){
  207991. assert( pConfig->pzErrmsg==0 );
  207992. pConfig->pzErrmsg = pzErr;
  207993. rc = sqlite3Fts5IndexLoadConfig(pTab->p.pIndex);
  207994. sqlite3Fts5IndexRollback(pTab->p.pIndex);
  207995. pConfig->pzErrmsg = 0;
  207996. }
  207997. if( rc!=SQLITE_OK ){
  207998. fts5FreeVtab(pTab);
  207999. pTab = 0;
  208000. }else if( bCreate ){
  208001. fts5CheckTransactionState(pTab, FTS5_BEGIN, 0);
  208002. }
  208003. *ppVTab = (sqlite3_vtab*)pTab;
  208004. return rc;
  208005. }
  208006. /*
  208007. ** The xConnect() and xCreate() methods for the virtual table. All the
  208008. ** work is done in function fts5InitVtab().
  208009. */
  208010. static int fts5ConnectMethod(
  208011. sqlite3 *db, /* Database connection */
  208012. void *pAux, /* Pointer to tokenizer hash table */
  208013. int argc, /* Number of elements in argv array */
  208014. const char * const *argv, /* xCreate/xConnect argument array */
  208015. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  208016. char **pzErr /* OUT: sqlite3_malloc'd error message */
  208017. ){
  208018. return fts5InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
  208019. }
  208020. static int fts5CreateMethod(
  208021. sqlite3 *db, /* Database connection */
  208022. void *pAux, /* Pointer to tokenizer hash table */
  208023. int argc, /* Number of elements in argv array */
  208024. const char * const *argv, /* xCreate/xConnect argument array */
  208025. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  208026. char **pzErr /* OUT: sqlite3_malloc'd error message */
  208027. ){
  208028. return fts5InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
  208029. }
  208030. /*
  208031. ** The different query plans.
  208032. */
  208033. #define FTS5_PLAN_MATCH 1 /* (<tbl> MATCH ?) */
  208034. #define FTS5_PLAN_SOURCE 2 /* A source cursor for SORTED_MATCH */
  208035. #define FTS5_PLAN_SPECIAL 3 /* An internal query */
  208036. #define FTS5_PLAN_SORTED_MATCH 4 /* (<tbl> MATCH ? ORDER BY rank) */
  208037. #define FTS5_PLAN_SCAN 5 /* No usable constraint */
  208038. #define FTS5_PLAN_ROWID 6 /* (rowid = ?) */
  208039. /*
  208040. ** Set the SQLITE_INDEX_SCAN_UNIQUE flag in pIdxInfo->flags. Unless this
  208041. ** extension is currently being used by a version of SQLite too old to
  208042. ** support index-info flags. In that case this function is a no-op.
  208043. */
  208044. static void fts5SetUniqueFlag(sqlite3_index_info *pIdxInfo){
  208045. #if SQLITE_VERSION_NUMBER>=3008012
  208046. #ifndef SQLITE_CORE
  208047. if( sqlite3_libversion_number()>=3008012 )
  208048. #endif
  208049. {
  208050. pIdxInfo->idxFlags |= SQLITE_INDEX_SCAN_UNIQUE;
  208051. }
  208052. #endif
  208053. }
  208054. /*
  208055. ** Implementation of the xBestIndex method for FTS5 tables. Within the
  208056. ** WHERE constraint, it searches for the following:
  208057. **
  208058. ** 1. A MATCH constraint against the table column.
  208059. ** 2. A MATCH constraint against the "rank" column.
  208060. ** 3. A MATCH constraint against some other column.
  208061. ** 4. An == constraint against the rowid column.
  208062. ** 5. A < or <= constraint against the rowid column.
  208063. ** 6. A > or >= constraint against the rowid column.
  208064. **
  208065. ** Within the ORDER BY, the following are supported:
  208066. **
  208067. ** 5. ORDER BY rank [ASC|DESC]
  208068. ** 6. ORDER BY rowid [ASC|DESC]
  208069. **
  208070. ** Information for the xFilter call is passed via both the idxNum and
  208071. ** idxStr variables. Specifically, idxNum is a bitmask of the following
  208072. ** flags used to encode the ORDER BY clause:
  208073. **
  208074. ** FTS5_BI_ORDER_RANK
  208075. ** FTS5_BI_ORDER_ROWID
  208076. ** FTS5_BI_ORDER_DESC
  208077. **
  208078. ** idxStr is used to encode data from the WHERE clause. For each argument
  208079. ** passed to the xFilter method, the following is appended to idxStr:
  208080. **
  208081. ** Match against table column: "m"
  208082. ** Match against rank column: "r"
  208083. ** Match against other column: "<column-number>"
  208084. ** Equality constraint against the rowid: "="
  208085. ** A < or <= against the rowid: "<"
  208086. ** A > or >= against the rowid: ">"
  208087. **
  208088. ** This function ensures that there is at most one "r" or "=". And that if
  208089. ** there exists an "=" then there is no "<" or ">".
  208090. **
  208091. ** Costs are assigned as follows:
  208092. **
  208093. ** a) If an unusable MATCH operator is present in the WHERE clause, the
  208094. ** cost is unconditionally set to 1e50 (a really big number).
  208095. **
  208096. ** a) If a MATCH operator is present, the cost depends on the other
  208097. ** constraints also present. As follows:
  208098. **
  208099. ** * No other constraints: cost=1000.0
  208100. ** * One rowid range constraint: cost=750.0
  208101. ** * Both rowid range constraints: cost=500.0
  208102. ** * An == rowid constraint: cost=100.0
  208103. **
  208104. ** b) Otherwise, if there is no MATCH:
  208105. **
  208106. ** * No other constraints: cost=1000000.0
  208107. ** * One rowid range constraint: cost=750000.0
  208108. ** * Both rowid range constraints: cost=250000.0
  208109. ** * An == rowid constraint: cost=10.0
  208110. **
  208111. ** Costs are not modified by the ORDER BY clause.
  208112. */
  208113. static int fts5BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
  208114. Fts5Table *pTab = (Fts5Table*)pVTab;
  208115. Fts5Config *pConfig = pTab->pConfig;
  208116. const int nCol = pConfig->nCol;
  208117. int idxFlags = 0; /* Parameter passed through to xFilter() */
  208118. int i;
  208119. char *idxStr;
  208120. int iIdxStr = 0;
  208121. int iCons = 0;
  208122. int bSeenEq = 0;
  208123. int bSeenGt = 0;
  208124. int bSeenLt = 0;
  208125. int bSeenMatch = 0;
  208126. int bSeenRank = 0;
  208127. assert( SQLITE_INDEX_CONSTRAINT_EQ<SQLITE_INDEX_CONSTRAINT_MATCH );
  208128. assert( SQLITE_INDEX_CONSTRAINT_GT<SQLITE_INDEX_CONSTRAINT_MATCH );
  208129. assert( SQLITE_INDEX_CONSTRAINT_LE<SQLITE_INDEX_CONSTRAINT_MATCH );
  208130. assert( SQLITE_INDEX_CONSTRAINT_GE<SQLITE_INDEX_CONSTRAINT_MATCH );
  208131. assert( SQLITE_INDEX_CONSTRAINT_LE<SQLITE_INDEX_CONSTRAINT_MATCH );
  208132. if( pConfig->bLock ){
  208133. pTab->base.zErrMsg = sqlite3_mprintf(
  208134. "recursively defined fts5 content table"
  208135. );
  208136. return SQLITE_ERROR;
  208137. }
  208138. idxStr = (char*)sqlite3_malloc(pInfo->nConstraint * 6 + 1);
  208139. if( idxStr==0 ) return SQLITE_NOMEM;
  208140. pInfo->idxStr = idxStr;
  208141. pInfo->needToFreeIdxStr = 1;
  208142. for(i=0; i<pInfo->nConstraint; i++){
  208143. struct sqlite3_index_constraint *p = &pInfo->aConstraint[i];
  208144. int iCol = p->iColumn;
  208145. if( p->op==SQLITE_INDEX_CONSTRAINT_MATCH
  208146. || (p->op==SQLITE_INDEX_CONSTRAINT_EQ && iCol>=nCol)
  208147. ){
  208148. /* A MATCH operator or equivalent */
  208149. if( p->usable==0 || iCol<0 ){
  208150. /* As there exists an unusable MATCH constraint this is an
  208151. ** unusable plan. Set a prohibitively high cost. */
  208152. pInfo->estimatedCost = 1e50;
  208153. assert( iIdxStr < pInfo->nConstraint*6 + 1 );
  208154. idxStr[iIdxStr] = 0;
  208155. return SQLITE_OK;
  208156. }else{
  208157. if( iCol==nCol+1 ){
  208158. if( bSeenRank ) continue;
  208159. idxStr[iIdxStr++] = 'r';
  208160. bSeenRank = 1;
  208161. }else{
  208162. bSeenMatch = 1;
  208163. idxStr[iIdxStr++] = 'm';
  208164. if( iCol<nCol ){
  208165. sqlite3_snprintf(6, &idxStr[iIdxStr], "%d", iCol);
  208166. idxStr += strlen(&idxStr[iIdxStr]);
  208167. assert( idxStr[iIdxStr]=='\0' );
  208168. }
  208169. }
  208170. pInfo->aConstraintUsage[i].argvIndex = ++iCons;
  208171. pInfo->aConstraintUsage[i].omit = 1;
  208172. }
  208173. }
  208174. else if( p->usable && bSeenEq==0
  208175. && p->op==SQLITE_INDEX_CONSTRAINT_EQ && iCol<0
  208176. ){
  208177. idxStr[iIdxStr++] = '=';
  208178. bSeenEq = 1;
  208179. pInfo->aConstraintUsage[i].argvIndex = ++iCons;
  208180. }
  208181. }
  208182. if( bSeenEq==0 ){
  208183. for(i=0; i<pInfo->nConstraint; i++){
  208184. struct sqlite3_index_constraint *p = &pInfo->aConstraint[i];
  208185. if( p->iColumn<0 && p->usable ){
  208186. int op = p->op;
  208187. if( op==SQLITE_INDEX_CONSTRAINT_LT || op==SQLITE_INDEX_CONSTRAINT_LE ){
  208188. if( bSeenLt ) continue;
  208189. idxStr[iIdxStr++] = '<';
  208190. pInfo->aConstraintUsage[i].argvIndex = ++iCons;
  208191. bSeenLt = 1;
  208192. }else
  208193. if( op==SQLITE_INDEX_CONSTRAINT_GT || op==SQLITE_INDEX_CONSTRAINT_GE ){
  208194. if( bSeenGt ) continue;
  208195. idxStr[iIdxStr++] = '>';
  208196. pInfo->aConstraintUsage[i].argvIndex = ++iCons;
  208197. bSeenGt = 1;
  208198. }
  208199. }
  208200. }
  208201. }
  208202. idxStr[iIdxStr] = '\0';
  208203. /* Set idxFlags flags for the ORDER BY clause */
  208204. if( pInfo->nOrderBy==1 ){
  208205. int iSort = pInfo->aOrderBy[0].iColumn;
  208206. if( iSort==(pConfig->nCol+1) && bSeenMatch ){
  208207. idxFlags |= FTS5_BI_ORDER_RANK;
  208208. }else if( iSort==-1 ){
  208209. idxFlags |= FTS5_BI_ORDER_ROWID;
  208210. }
  208211. if( BitFlagTest(idxFlags, FTS5_BI_ORDER_RANK|FTS5_BI_ORDER_ROWID) ){
  208212. pInfo->orderByConsumed = 1;
  208213. if( pInfo->aOrderBy[0].desc ){
  208214. idxFlags |= FTS5_BI_ORDER_DESC;
  208215. }
  208216. }
  208217. }
  208218. /* Calculate the estimated cost based on the flags set in idxFlags. */
  208219. if( bSeenEq ){
  208220. pInfo->estimatedCost = bSeenMatch ? 100.0 : 10.0;
  208221. if( bSeenMatch==0 ) fts5SetUniqueFlag(pInfo);
  208222. }else if( bSeenLt && bSeenGt ){
  208223. pInfo->estimatedCost = bSeenMatch ? 500.0 : 250000.0;
  208224. }else if( bSeenLt || bSeenGt ){
  208225. pInfo->estimatedCost = bSeenMatch ? 750.0 : 750000.0;
  208226. }else{
  208227. pInfo->estimatedCost = bSeenMatch ? 1000.0 : 1000000.0;
  208228. }
  208229. pInfo->idxNum = idxFlags;
  208230. return SQLITE_OK;
  208231. }
  208232. static int fts5NewTransaction(Fts5FullTable *pTab){
  208233. Fts5Cursor *pCsr;
  208234. for(pCsr=pTab->pGlobal->pCsr; pCsr; pCsr=pCsr->pNext){
  208235. if( pCsr->base.pVtab==(sqlite3_vtab*)pTab ) return SQLITE_OK;
  208236. }
  208237. return sqlite3Fts5StorageReset(pTab->pStorage);
  208238. }
  208239. /*
  208240. ** Implementation of xOpen method.
  208241. */
  208242. static int fts5OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
  208243. Fts5FullTable *pTab = (Fts5FullTable*)pVTab;
  208244. Fts5Config *pConfig = pTab->p.pConfig;
  208245. Fts5Cursor *pCsr = 0; /* New cursor object */
  208246. sqlite3_int64 nByte; /* Bytes of space to allocate */
  208247. int rc; /* Return code */
  208248. rc = fts5NewTransaction(pTab);
  208249. if( rc==SQLITE_OK ){
  208250. nByte = sizeof(Fts5Cursor) + pConfig->nCol * sizeof(int);
  208251. pCsr = (Fts5Cursor*)sqlite3_malloc64(nByte);
  208252. if( pCsr ){
  208253. Fts5Global *pGlobal = pTab->pGlobal;
  208254. memset(pCsr, 0, (size_t)nByte);
  208255. pCsr->aColumnSize = (int*)&pCsr[1];
  208256. pCsr->pNext = pGlobal->pCsr;
  208257. pGlobal->pCsr = pCsr;
  208258. pCsr->iCsrId = ++pGlobal->iNextId;
  208259. }else{
  208260. rc = SQLITE_NOMEM;
  208261. }
  208262. }
  208263. *ppCsr = (sqlite3_vtab_cursor*)pCsr;
  208264. return rc;
  208265. }
  208266. static int fts5StmtType(Fts5Cursor *pCsr){
  208267. if( pCsr->ePlan==FTS5_PLAN_SCAN ){
  208268. return (pCsr->bDesc) ? FTS5_STMT_SCAN_DESC : FTS5_STMT_SCAN_ASC;
  208269. }
  208270. return FTS5_STMT_LOOKUP;
  208271. }
  208272. /*
  208273. ** This function is called after the cursor passed as the only argument
  208274. ** is moved to point at a different row. It clears all cached data
  208275. ** specific to the previous row stored by the cursor object.
  208276. */
  208277. static void fts5CsrNewrow(Fts5Cursor *pCsr){
  208278. CsrFlagSet(pCsr,
  208279. FTS5CSR_REQUIRE_CONTENT
  208280. | FTS5CSR_REQUIRE_DOCSIZE
  208281. | FTS5CSR_REQUIRE_INST
  208282. | FTS5CSR_REQUIRE_POSLIST
  208283. );
  208284. }
  208285. static void fts5FreeCursorComponents(Fts5Cursor *pCsr){
  208286. Fts5FullTable *pTab = (Fts5FullTable*)(pCsr->base.pVtab);
  208287. Fts5Auxdata *pData;
  208288. Fts5Auxdata *pNext;
  208289. sqlite3_free(pCsr->aInstIter);
  208290. sqlite3_free(pCsr->aInst);
  208291. if( pCsr->pStmt ){
  208292. int eStmt = fts5StmtType(pCsr);
  208293. sqlite3Fts5StorageStmtRelease(pTab->pStorage, eStmt, pCsr->pStmt);
  208294. }
  208295. if( pCsr->pSorter ){
  208296. Fts5Sorter *pSorter = pCsr->pSorter;
  208297. sqlite3_finalize(pSorter->pStmt);
  208298. sqlite3_free(pSorter);
  208299. }
  208300. if( pCsr->ePlan!=FTS5_PLAN_SOURCE ){
  208301. sqlite3Fts5ExprFree(pCsr->pExpr);
  208302. }
  208303. for(pData=pCsr->pAuxdata; pData; pData=pNext){
  208304. pNext = pData->pNext;
  208305. if( pData->xDelete ) pData->xDelete(pData->pPtr);
  208306. sqlite3_free(pData);
  208307. }
  208308. sqlite3_finalize(pCsr->pRankArgStmt);
  208309. sqlite3_free(pCsr->apRankArg);
  208310. if( CsrFlagTest(pCsr, FTS5CSR_FREE_ZRANK) ){
  208311. sqlite3_free(pCsr->zRank);
  208312. sqlite3_free(pCsr->zRankArgs);
  208313. }
  208314. sqlite3Fts5IndexCloseReader(pTab->p.pIndex);
  208315. memset(&pCsr->ePlan, 0, sizeof(Fts5Cursor) - ((u8*)&pCsr->ePlan - (u8*)pCsr));
  208316. }
  208317. /*
  208318. ** Close the cursor. For additional information see the documentation
  208319. ** on the xClose method of the virtual table interface.
  208320. */
  208321. static int fts5CloseMethod(sqlite3_vtab_cursor *pCursor){
  208322. if( pCursor ){
  208323. Fts5FullTable *pTab = (Fts5FullTable*)(pCursor->pVtab);
  208324. Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
  208325. Fts5Cursor **pp;
  208326. fts5FreeCursorComponents(pCsr);
  208327. /* Remove the cursor from the Fts5Global.pCsr list */
  208328. for(pp=&pTab->pGlobal->pCsr; (*pp)!=pCsr; pp=&(*pp)->pNext);
  208329. *pp = pCsr->pNext;
  208330. sqlite3_free(pCsr);
  208331. }
  208332. return SQLITE_OK;
  208333. }
  208334. static int fts5SorterNext(Fts5Cursor *pCsr){
  208335. Fts5Sorter *pSorter = pCsr->pSorter;
  208336. int rc;
  208337. rc = sqlite3_step(pSorter->pStmt);
  208338. if( rc==SQLITE_DONE ){
  208339. rc = SQLITE_OK;
  208340. CsrFlagSet(pCsr, FTS5CSR_EOF);
  208341. }else if( rc==SQLITE_ROW ){
  208342. const u8 *a;
  208343. const u8 *aBlob;
  208344. int nBlob;
  208345. int i;
  208346. int iOff = 0;
  208347. rc = SQLITE_OK;
  208348. pSorter->iRowid = sqlite3_column_int64(pSorter->pStmt, 0);
  208349. nBlob = sqlite3_column_bytes(pSorter->pStmt, 1);
  208350. aBlob = a = sqlite3_column_blob(pSorter->pStmt, 1);
  208351. /* nBlob==0 in detail=none mode. */
  208352. if( nBlob>0 ){
  208353. for(i=0; i<(pSorter->nIdx-1); i++){
  208354. int iVal;
  208355. a += fts5GetVarint32(a, iVal);
  208356. iOff += iVal;
  208357. pSorter->aIdx[i] = iOff;
  208358. }
  208359. pSorter->aIdx[i] = &aBlob[nBlob] - a;
  208360. pSorter->aPoslist = a;
  208361. }
  208362. fts5CsrNewrow(pCsr);
  208363. }
  208364. return rc;
  208365. }
  208366. /*
  208367. ** Set the FTS5CSR_REQUIRE_RESEEK flag on all FTS5_PLAN_MATCH cursors
  208368. ** open on table pTab.
  208369. */
  208370. static void fts5TripCursors(Fts5FullTable *pTab){
  208371. Fts5Cursor *pCsr;
  208372. for(pCsr=pTab->pGlobal->pCsr; pCsr; pCsr=pCsr->pNext){
  208373. if( pCsr->ePlan==FTS5_PLAN_MATCH
  208374. && pCsr->base.pVtab==(sqlite3_vtab*)pTab
  208375. ){
  208376. CsrFlagSet(pCsr, FTS5CSR_REQUIRE_RESEEK);
  208377. }
  208378. }
  208379. }
  208380. /*
  208381. ** If the REQUIRE_RESEEK flag is set on the cursor passed as the first
  208382. ** argument, close and reopen all Fts5IndexIter iterators that the cursor
  208383. ** is using. Then attempt to move the cursor to a rowid equal to or laster
  208384. ** (in the cursors sort order - ASC or DESC) than the current rowid.
  208385. **
  208386. ** If the new rowid is not equal to the old, set output parameter *pbSkip
  208387. ** to 1 before returning. Otherwise, leave it unchanged.
  208388. **
  208389. ** Return SQLITE_OK if successful or if no reseek was required, or an
  208390. ** error code if an error occurred.
  208391. */
  208392. static int fts5CursorReseek(Fts5Cursor *pCsr, int *pbSkip){
  208393. int rc = SQLITE_OK;
  208394. assert( *pbSkip==0 );
  208395. if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_RESEEK) ){
  208396. Fts5FullTable *pTab = (Fts5FullTable*)(pCsr->base.pVtab);
  208397. int bDesc = pCsr->bDesc;
  208398. i64 iRowid = sqlite3Fts5ExprRowid(pCsr->pExpr);
  208399. rc = sqlite3Fts5ExprFirst(pCsr->pExpr, pTab->p.pIndex, iRowid, bDesc);
  208400. if( rc==SQLITE_OK && iRowid!=sqlite3Fts5ExprRowid(pCsr->pExpr) ){
  208401. *pbSkip = 1;
  208402. }
  208403. CsrFlagClear(pCsr, FTS5CSR_REQUIRE_RESEEK);
  208404. fts5CsrNewrow(pCsr);
  208405. if( sqlite3Fts5ExprEof(pCsr->pExpr) ){
  208406. CsrFlagSet(pCsr, FTS5CSR_EOF);
  208407. *pbSkip = 1;
  208408. }
  208409. }
  208410. return rc;
  208411. }
  208412. /*
  208413. ** Advance the cursor to the next row in the table that matches the
  208414. ** search criteria.
  208415. **
  208416. ** Return SQLITE_OK if nothing goes wrong. SQLITE_OK is returned
  208417. ** even if we reach end-of-file. The fts5EofMethod() will be called
  208418. ** subsequently to determine whether or not an EOF was hit.
  208419. */
  208420. static int fts5NextMethod(sqlite3_vtab_cursor *pCursor){
  208421. Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
  208422. int rc;
  208423. assert( (pCsr->ePlan<3)==
  208424. (pCsr->ePlan==FTS5_PLAN_MATCH || pCsr->ePlan==FTS5_PLAN_SOURCE)
  208425. );
  208426. assert( !CsrFlagTest(pCsr, FTS5CSR_EOF) );
  208427. if( pCsr->ePlan<3 ){
  208428. int bSkip = 0;
  208429. if( (rc = fts5CursorReseek(pCsr, &bSkip)) || bSkip ) return rc;
  208430. rc = sqlite3Fts5ExprNext(pCsr->pExpr, pCsr->iLastRowid);
  208431. CsrFlagSet(pCsr, sqlite3Fts5ExprEof(pCsr->pExpr));
  208432. fts5CsrNewrow(pCsr);
  208433. }else{
  208434. switch( pCsr->ePlan ){
  208435. case FTS5_PLAN_SPECIAL: {
  208436. CsrFlagSet(pCsr, FTS5CSR_EOF);
  208437. rc = SQLITE_OK;
  208438. break;
  208439. }
  208440. case FTS5_PLAN_SORTED_MATCH: {
  208441. rc = fts5SorterNext(pCsr);
  208442. break;
  208443. }
  208444. default: {
  208445. Fts5Config *pConfig = ((Fts5Table*)pCursor->pVtab)->pConfig;
  208446. pConfig->bLock++;
  208447. rc = sqlite3_step(pCsr->pStmt);
  208448. pConfig->bLock--;
  208449. if( rc!=SQLITE_ROW ){
  208450. CsrFlagSet(pCsr, FTS5CSR_EOF);
  208451. rc = sqlite3_reset(pCsr->pStmt);
  208452. if( rc!=SQLITE_OK ){
  208453. pCursor->pVtab->zErrMsg = sqlite3_mprintf(
  208454. "%s", sqlite3_errmsg(pConfig->db)
  208455. );
  208456. }
  208457. }else{
  208458. rc = SQLITE_OK;
  208459. }
  208460. break;
  208461. }
  208462. }
  208463. }
  208464. return rc;
  208465. }
  208466. static int fts5PrepareStatement(
  208467. sqlite3_stmt **ppStmt,
  208468. Fts5Config *pConfig,
  208469. const char *zFmt,
  208470. ...
  208471. ){
  208472. sqlite3_stmt *pRet = 0;
  208473. int rc;
  208474. char *zSql;
  208475. va_list ap;
  208476. va_start(ap, zFmt);
  208477. zSql = sqlite3_vmprintf(zFmt, ap);
  208478. if( zSql==0 ){
  208479. rc = SQLITE_NOMEM;
  208480. }else{
  208481. rc = sqlite3_prepare_v3(pConfig->db, zSql, -1,
  208482. SQLITE_PREPARE_PERSISTENT, &pRet, 0);
  208483. if( rc!=SQLITE_OK ){
  208484. *pConfig->pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(pConfig->db));
  208485. }
  208486. sqlite3_free(zSql);
  208487. }
  208488. va_end(ap);
  208489. *ppStmt = pRet;
  208490. return rc;
  208491. }
  208492. static int fts5CursorFirstSorted(
  208493. Fts5FullTable *pTab,
  208494. Fts5Cursor *pCsr,
  208495. int bDesc
  208496. ){
  208497. Fts5Config *pConfig = pTab->p.pConfig;
  208498. Fts5Sorter *pSorter;
  208499. int nPhrase;
  208500. sqlite3_int64 nByte;
  208501. int rc;
  208502. const char *zRank = pCsr->zRank;
  208503. const char *zRankArgs = pCsr->zRankArgs;
  208504. nPhrase = sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
  208505. nByte = sizeof(Fts5Sorter) + sizeof(int) * (nPhrase-1);
  208506. pSorter = (Fts5Sorter*)sqlite3_malloc64(nByte);
  208507. if( pSorter==0 ) return SQLITE_NOMEM;
  208508. memset(pSorter, 0, (size_t)nByte);
  208509. pSorter->nIdx = nPhrase;
  208510. /* TODO: It would be better to have some system for reusing statement
  208511. ** handles here, rather than preparing a new one for each query. But that
  208512. ** is not possible as SQLite reference counts the virtual table objects.
  208513. ** And since the statement required here reads from this very virtual
  208514. ** table, saving it creates a circular reference.
  208515. **
  208516. ** If SQLite a built-in statement cache, this wouldn't be a problem. */
  208517. rc = fts5PrepareStatement(&pSorter->pStmt, pConfig,
  208518. "SELECT rowid, rank FROM %Q.%Q ORDER BY %s(\"%w\"%s%s) %s",
  208519. pConfig->zDb, pConfig->zName, zRank, pConfig->zName,
  208520. (zRankArgs ? ", " : ""),
  208521. (zRankArgs ? zRankArgs : ""),
  208522. bDesc ? "DESC" : "ASC"
  208523. );
  208524. pCsr->pSorter = pSorter;
  208525. if( rc==SQLITE_OK ){
  208526. assert( pTab->pSortCsr==0 );
  208527. pTab->pSortCsr = pCsr;
  208528. rc = fts5SorterNext(pCsr);
  208529. pTab->pSortCsr = 0;
  208530. }
  208531. if( rc!=SQLITE_OK ){
  208532. sqlite3_finalize(pSorter->pStmt);
  208533. sqlite3_free(pSorter);
  208534. pCsr->pSorter = 0;
  208535. }
  208536. return rc;
  208537. }
  208538. static int fts5CursorFirst(Fts5FullTable *pTab, Fts5Cursor *pCsr, int bDesc){
  208539. int rc;
  208540. Fts5Expr *pExpr = pCsr->pExpr;
  208541. rc = sqlite3Fts5ExprFirst(pExpr, pTab->p.pIndex, pCsr->iFirstRowid, bDesc);
  208542. if( sqlite3Fts5ExprEof(pExpr) ){
  208543. CsrFlagSet(pCsr, FTS5CSR_EOF);
  208544. }
  208545. fts5CsrNewrow(pCsr);
  208546. return rc;
  208547. }
  208548. /*
  208549. ** Process a "special" query. A special query is identified as one with a
  208550. ** MATCH expression that begins with a '*' character. The remainder of
  208551. ** the text passed to the MATCH operator are used as the special query
  208552. ** parameters.
  208553. */
  208554. static int fts5SpecialMatch(
  208555. Fts5FullTable *pTab,
  208556. Fts5Cursor *pCsr,
  208557. const char *zQuery
  208558. ){
  208559. int rc = SQLITE_OK; /* Return code */
  208560. const char *z = zQuery; /* Special query text */
  208561. int n; /* Number of bytes in text at z */
  208562. while( z[0]==' ' ) z++;
  208563. for(n=0; z[n] && z[n]!=' '; n++);
  208564. assert( pTab->p.base.zErrMsg==0 );
  208565. pCsr->ePlan = FTS5_PLAN_SPECIAL;
  208566. if( n==5 && 0==sqlite3_strnicmp("reads", z, n) ){
  208567. pCsr->iSpecial = sqlite3Fts5IndexReads(pTab->p.pIndex);
  208568. }
  208569. else if( n==2 && 0==sqlite3_strnicmp("id", z, n) ){
  208570. pCsr->iSpecial = pCsr->iCsrId;
  208571. }
  208572. else{
  208573. /* An unrecognized directive. Return an error message. */
  208574. pTab->p.base.zErrMsg = sqlite3_mprintf("unknown special query: %.*s", n, z);
  208575. rc = SQLITE_ERROR;
  208576. }
  208577. return rc;
  208578. }
  208579. /*
  208580. ** Search for an auxiliary function named zName that can be used with table
  208581. ** pTab. If one is found, return a pointer to the corresponding Fts5Auxiliary
  208582. ** structure. Otherwise, if no such function exists, return NULL.
  208583. */
  208584. static Fts5Auxiliary *fts5FindAuxiliary(Fts5FullTable *pTab, const char *zName){
  208585. Fts5Auxiliary *pAux;
  208586. for(pAux=pTab->pGlobal->pAux; pAux; pAux=pAux->pNext){
  208587. if( sqlite3_stricmp(zName, pAux->zFunc)==0 ) return pAux;
  208588. }
  208589. /* No function of the specified name was found. Return 0. */
  208590. return 0;
  208591. }
  208592. static int fts5FindRankFunction(Fts5Cursor *pCsr){
  208593. Fts5FullTable *pTab = (Fts5FullTable*)(pCsr->base.pVtab);
  208594. Fts5Config *pConfig = pTab->p.pConfig;
  208595. int rc = SQLITE_OK;
  208596. Fts5Auxiliary *pAux = 0;
  208597. const char *zRank = pCsr->zRank;
  208598. const char *zRankArgs = pCsr->zRankArgs;
  208599. if( zRankArgs ){
  208600. char *zSql = sqlite3Fts5Mprintf(&rc, "SELECT %s", zRankArgs);
  208601. if( zSql ){
  208602. sqlite3_stmt *pStmt = 0;
  208603. rc = sqlite3_prepare_v3(pConfig->db, zSql, -1,
  208604. SQLITE_PREPARE_PERSISTENT, &pStmt, 0);
  208605. sqlite3_free(zSql);
  208606. assert( rc==SQLITE_OK || pCsr->pRankArgStmt==0 );
  208607. if( rc==SQLITE_OK ){
  208608. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  208609. sqlite3_int64 nByte;
  208610. pCsr->nRankArg = sqlite3_column_count(pStmt);
  208611. nByte = sizeof(sqlite3_value*)*pCsr->nRankArg;
  208612. pCsr->apRankArg = (sqlite3_value**)sqlite3Fts5MallocZero(&rc, nByte);
  208613. if( rc==SQLITE_OK ){
  208614. int i;
  208615. for(i=0; i<pCsr->nRankArg; i++){
  208616. pCsr->apRankArg[i] = sqlite3_column_value(pStmt, i);
  208617. }
  208618. }
  208619. pCsr->pRankArgStmt = pStmt;
  208620. }else{
  208621. rc = sqlite3_finalize(pStmt);
  208622. assert( rc!=SQLITE_OK );
  208623. }
  208624. }
  208625. }
  208626. }
  208627. if( rc==SQLITE_OK ){
  208628. pAux = fts5FindAuxiliary(pTab, zRank);
  208629. if( pAux==0 ){
  208630. assert( pTab->p.base.zErrMsg==0 );
  208631. pTab->p.base.zErrMsg = sqlite3_mprintf("no such function: %s", zRank);
  208632. rc = SQLITE_ERROR;
  208633. }
  208634. }
  208635. pCsr->pRank = pAux;
  208636. return rc;
  208637. }
  208638. static int fts5CursorParseRank(
  208639. Fts5Config *pConfig,
  208640. Fts5Cursor *pCsr,
  208641. sqlite3_value *pRank
  208642. ){
  208643. int rc = SQLITE_OK;
  208644. if( pRank ){
  208645. const char *z = (const char*)sqlite3_value_text(pRank);
  208646. char *zRank = 0;
  208647. char *zRankArgs = 0;
  208648. if( z==0 ){
  208649. if( sqlite3_value_type(pRank)==SQLITE_NULL ) rc = SQLITE_ERROR;
  208650. }else{
  208651. rc = sqlite3Fts5ConfigParseRank(z, &zRank, &zRankArgs);
  208652. }
  208653. if( rc==SQLITE_OK ){
  208654. pCsr->zRank = zRank;
  208655. pCsr->zRankArgs = zRankArgs;
  208656. CsrFlagSet(pCsr, FTS5CSR_FREE_ZRANK);
  208657. }else if( rc==SQLITE_ERROR ){
  208658. pCsr->base.pVtab->zErrMsg = sqlite3_mprintf(
  208659. "parse error in rank function: %s", z
  208660. );
  208661. }
  208662. }else{
  208663. if( pConfig->zRank ){
  208664. pCsr->zRank = (char*)pConfig->zRank;
  208665. pCsr->zRankArgs = (char*)pConfig->zRankArgs;
  208666. }else{
  208667. pCsr->zRank = (char*)FTS5_DEFAULT_RANK;
  208668. pCsr->zRankArgs = 0;
  208669. }
  208670. }
  208671. return rc;
  208672. }
  208673. static i64 fts5GetRowidLimit(sqlite3_value *pVal, i64 iDefault){
  208674. if( pVal ){
  208675. int eType = sqlite3_value_numeric_type(pVal);
  208676. if( eType==SQLITE_INTEGER ){
  208677. return sqlite3_value_int64(pVal);
  208678. }
  208679. }
  208680. return iDefault;
  208681. }
  208682. /*
  208683. ** This is the xFilter interface for the virtual table. See
  208684. ** the virtual table xFilter method documentation for additional
  208685. ** information.
  208686. **
  208687. ** There are three possible query strategies:
  208688. **
  208689. ** 1. Full-text search using a MATCH operator.
  208690. ** 2. A by-rowid lookup.
  208691. ** 3. A full-table scan.
  208692. */
  208693. static int fts5FilterMethod(
  208694. sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
  208695. int idxNum, /* Strategy index */
  208696. const char *idxStr, /* Unused */
  208697. int nVal, /* Number of elements in apVal */
  208698. sqlite3_value **apVal /* Arguments for the indexing scheme */
  208699. ){
  208700. Fts5FullTable *pTab = (Fts5FullTable*)(pCursor->pVtab);
  208701. Fts5Config *pConfig = pTab->p.pConfig;
  208702. Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
  208703. int rc = SQLITE_OK; /* Error code */
  208704. int bDesc; /* True if ORDER BY [rank|rowid] DESC */
  208705. int bOrderByRank; /* True if ORDER BY rank */
  208706. sqlite3_value *pRank = 0; /* rank MATCH ? expression (or NULL) */
  208707. sqlite3_value *pRowidEq = 0; /* rowid = ? expression (or NULL) */
  208708. sqlite3_value *pRowidLe = 0; /* rowid <= ? expression (or NULL) */
  208709. sqlite3_value *pRowidGe = 0; /* rowid >= ? expression (or NULL) */
  208710. int iCol; /* Column on LHS of MATCH operator */
  208711. char **pzErrmsg = pConfig->pzErrmsg;
  208712. int i;
  208713. int iIdxStr = 0;
  208714. Fts5Expr *pExpr = 0;
  208715. if( pConfig->bLock ){
  208716. pTab->p.base.zErrMsg = sqlite3_mprintf(
  208717. "recursively defined fts5 content table"
  208718. );
  208719. return SQLITE_ERROR;
  208720. }
  208721. if( pCsr->ePlan ){
  208722. fts5FreeCursorComponents(pCsr);
  208723. memset(&pCsr->ePlan, 0, sizeof(Fts5Cursor) - ((u8*)&pCsr->ePlan-(u8*)pCsr));
  208724. }
  208725. assert( pCsr->pStmt==0 );
  208726. assert( pCsr->pExpr==0 );
  208727. assert( pCsr->csrflags==0 );
  208728. assert( pCsr->pRank==0 );
  208729. assert( pCsr->zRank==0 );
  208730. assert( pCsr->zRankArgs==0 );
  208731. assert( pTab->pSortCsr==0 || nVal==0 );
  208732. assert( pzErrmsg==0 || pzErrmsg==&pTab->p.base.zErrMsg );
  208733. pConfig->pzErrmsg = &pTab->p.base.zErrMsg;
  208734. /* Decode the arguments passed through to this function. */
  208735. for(i=0; i<nVal; i++){
  208736. switch( idxStr[iIdxStr++] ){
  208737. case 'r':
  208738. pRank = apVal[i];
  208739. break;
  208740. case 'm': {
  208741. const char *zText = (const char*)sqlite3_value_text(apVal[i]);
  208742. if( zText==0 ) zText = "";
  208743. if( idxStr[iIdxStr]>='0' && idxStr[iIdxStr]<='9' ){
  208744. iCol = 0;
  208745. do{
  208746. iCol = iCol*10 + (idxStr[iIdxStr]-'0');
  208747. iIdxStr++;
  208748. }while( idxStr[iIdxStr]>='0' && idxStr[iIdxStr]<='9' );
  208749. }else{
  208750. iCol = pConfig->nCol;
  208751. }
  208752. if( zText[0]=='*' ){
  208753. /* The user has issued a query of the form "MATCH '*...'". This
  208754. ** indicates that the MATCH expression is not a full text query,
  208755. ** but a request for an internal parameter. */
  208756. rc = fts5SpecialMatch(pTab, pCsr, &zText[1]);
  208757. goto filter_out;
  208758. }else{
  208759. char **pzErr = &pTab->p.base.zErrMsg;
  208760. rc = sqlite3Fts5ExprNew(pConfig, iCol, zText, &pExpr, pzErr);
  208761. if( rc==SQLITE_OK ){
  208762. rc = sqlite3Fts5ExprAnd(&pCsr->pExpr, pExpr);
  208763. pExpr = 0;
  208764. }
  208765. if( rc!=SQLITE_OK ) goto filter_out;
  208766. }
  208767. break;
  208768. }
  208769. case '=':
  208770. pRowidEq = apVal[i];
  208771. break;
  208772. case '<':
  208773. pRowidLe = apVal[i];
  208774. break;
  208775. default: assert( idxStr[iIdxStr-1]=='>' );
  208776. pRowidGe = apVal[i];
  208777. break;
  208778. }
  208779. }
  208780. bOrderByRank = ((idxNum & FTS5_BI_ORDER_RANK) ? 1 : 0);
  208781. pCsr->bDesc = bDesc = ((idxNum & FTS5_BI_ORDER_DESC) ? 1 : 0);
  208782. /* Set the cursor upper and lower rowid limits. Only some strategies
  208783. ** actually use them. This is ok, as the xBestIndex() method leaves the
  208784. ** sqlite3_index_constraint.omit flag clear for range constraints
  208785. ** on the rowid field. */
  208786. if( pRowidEq ){
  208787. pRowidLe = pRowidGe = pRowidEq;
  208788. }
  208789. if( bDesc ){
  208790. pCsr->iFirstRowid = fts5GetRowidLimit(pRowidLe, LARGEST_INT64);
  208791. pCsr->iLastRowid = fts5GetRowidLimit(pRowidGe, SMALLEST_INT64);
  208792. }else{
  208793. pCsr->iLastRowid = fts5GetRowidLimit(pRowidLe, LARGEST_INT64);
  208794. pCsr->iFirstRowid = fts5GetRowidLimit(pRowidGe, SMALLEST_INT64);
  208795. }
  208796. if( pTab->pSortCsr ){
  208797. /* If pSortCsr is non-NULL, then this call is being made as part of
  208798. ** processing for a "... MATCH <expr> ORDER BY rank" query (ePlan is
  208799. ** set to FTS5_PLAN_SORTED_MATCH). pSortCsr is the cursor that will
  208800. ** return results to the user for this query. The current cursor
  208801. ** (pCursor) is used to execute the query issued by function
  208802. ** fts5CursorFirstSorted() above. */
  208803. assert( pRowidEq==0 && pRowidLe==0 && pRowidGe==0 && pRank==0 );
  208804. assert( nVal==0 && bOrderByRank==0 && bDesc==0 );
  208805. assert( pCsr->iLastRowid==LARGEST_INT64 );
  208806. assert( pCsr->iFirstRowid==SMALLEST_INT64 );
  208807. if( pTab->pSortCsr->bDesc ){
  208808. pCsr->iLastRowid = pTab->pSortCsr->iFirstRowid;
  208809. pCsr->iFirstRowid = pTab->pSortCsr->iLastRowid;
  208810. }else{
  208811. pCsr->iLastRowid = pTab->pSortCsr->iLastRowid;
  208812. pCsr->iFirstRowid = pTab->pSortCsr->iFirstRowid;
  208813. }
  208814. pCsr->ePlan = FTS5_PLAN_SOURCE;
  208815. pCsr->pExpr = pTab->pSortCsr->pExpr;
  208816. rc = fts5CursorFirst(pTab, pCsr, bDesc);
  208817. }else if( pCsr->pExpr ){
  208818. rc = fts5CursorParseRank(pConfig, pCsr, pRank);
  208819. if( rc==SQLITE_OK ){
  208820. if( bOrderByRank ){
  208821. pCsr->ePlan = FTS5_PLAN_SORTED_MATCH;
  208822. rc = fts5CursorFirstSorted(pTab, pCsr, bDesc);
  208823. }else{
  208824. pCsr->ePlan = FTS5_PLAN_MATCH;
  208825. rc = fts5CursorFirst(pTab, pCsr, bDesc);
  208826. }
  208827. }
  208828. }else if( pConfig->zContent==0 ){
  208829. *pConfig->pzErrmsg = sqlite3_mprintf(
  208830. "%s: table does not support scanning", pConfig->zName
  208831. );
  208832. rc = SQLITE_ERROR;
  208833. }else{
  208834. /* This is either a full-table scan (ePlan==FTS5_PLAN_SCAN) or a lookup
  208835. ** by rowid (ePlan==FTS5_PLAN_ROWID). */
  208836. pCsr->ePlan = (pRowidEq ? FTS5_PLAN_ROWID : FTS5_PLAN_SCAN);
  208837. rc = sqlite3Fts5StorageStmt(
  208838. pTab->pStorage, fts5StmtType(pCsr), &pCsr->pStmt, &pTab->p.base.zErrMsg
  208839. );
  208840. if( rc==SQLITE_OK ){
  208841. if( pCsr->ePlan==FTS5_PLAN_ROWID ){
  208842. sqlite3_bind_value(pCsr->pStmt, 1, pRowidEq);
  208843. }else{
  208844. sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iFirstRowid);
  208845. sqlite3_bind_int64(pCsr->pStmt, 2, pCsr->iLastRowid);
  208846. }
  208847. rc = fts5NextMethod(pCursor);
  208848. }
  208849. }
  208850. filter_out:
  208851. sqlite3Fts5ExprFree(pExpr);
  208852. pConfig->pzErrmsg = pzErrmsg;
  208853. return rc;
  208854. }
  208855. /*
  208856. ** This is the xEof method of the virtual table. SQLite calls this
  208857. ** routine to find out if it has reached the end of a result set.
  208858. */
  208859. static int fts5EofMethod(sqlite3_vtab_cursor *pCursor){
  208860. Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
  208861. return (CsrFlagTest(pCsr, FTS5CSR_EOF) ? 1 : 0);
  208862. }
  208863. /*
  208864. ** Return the rowid that the cursor currently points to.
  208865. */
  208866. static i64 fts5CursorRowid(Fts5Cursor *pCsr){
  208867. assert( pCsr->ePlan==FTS5_PLAN_MATCH
  208868. || pCsr->ePlan==FTS5_PLAN_SORTED_MATCH
  208869. || pCsr->ePlan==FTS5_PLAN_SOURCE
  208870. );
  208871. if( pCsr->pSorter ){
  208872. return pCsr->pSorter->iRowid;
  208873. }else{
  208874. return sqlite3Fts5ExprRowid(pCsr->pExpr);
  208875. }
  208876. }
  208877. /*
  208878. ** This is the xRowid method. The SQLite core calls this routine to
  208879. ** retrieve the rowid for the current row of the result set. fts5
  208880. ** exposes %_content.rowid as the rowid for the virtual table. The
  208881. ** rowid should be written to *pRowid.
  208882. */
  208883. static int fts5RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
  208884. Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
  208885. int ePlan = pCsr->ePlan;
  208886. assert( CsrFlagTest(pCsr, FTS5CSR_EOF)==0 );
  208887. switch( ePlan ){
  208888. case FTS5_PLAN_SPECIAL:
  208889. *pRowid = 0;
  208890. break;
  208891. case FTS5_PLAN_SOURCE:
  208892. case FTS5_PLAN_MATCH:
  208893. case FTS5_PLAN_SORTED_MATCH:
  208894. *pRowid = fts5CursorRowid(pCsr);
  208895. break;
  208896. default:
  208897. *pRowid = sqlite3_column_int64(pCsr->pStmt, 0);
  208898. break;
  208899. }
  208900. return SQLITE_OK;
  208901. }
  208902. /*
  208903. ** If the cursor requires seeking (bSeekRequired flag is set), seek it.
  208904. ** Return SQLITE_OK if no error occurs, or an SQLite error code otherwise.
  208905. **
  208906. ** If argument bErrormsg is true and an error occurs, an error message may
  208907. ** be left in sqlite3_vtab.zErrMsg.
  208908. */
  208909. static int fts5SeekCursor(Fts5Cursor *pCsr, int bErrormsg){
  208910. int rc = SQLITE_OK;
  208911. /* If the cursor does not yet have a statement handle, obtain one now. */
  208912. if( pCsr->pStmt==0 ){
  208913. Fts5FullTable *pTab = (Fts5FullTable*)(pCsr->base.pVtab);
  208914. int eStmt = fts5StmtType(pCsr);
  208915. rc = sqlite3Fts5StorageStmt(
  208916. pTab->pStorage, eStmt, &pCsr->pStmt, (bErrormsg?&pTab->p.base.zErrMsg:0)
  208917. );
  208918. assert( rc!=SQLITE_OK || pTab->p.base.zErrMsg==0 );
  208919. assert( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_CONTENT) );
  208920. }
  208921. if( rc==SQLITE_OK && CsrFlagTest(pCsr, FTS5CSR_REQUIRE_CONTENT) ){
  208922. Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
  208923. assert( pCsr->pExpr );
  208924. sqlite3_reset(pCsr->pStmt);
  208925. sqlite3_bind_int64(pCsr->pStmt, 1, fts5CursorRowid(pCsr));
  208926. pTab->pConfig->bLock++;
  208927. rc = sqlite3_step(pCsr->pStmt);
  208928. pTab->pConfig->bLock--;
  208929. if( rc==SQLITE_ROW ){
  208930. rc = SQLITE_OK;
  208931. CsrFlagClear(pCsr, FTS5CSR_REQUIRE_CONTENT);
  208932. }else{
  208933. rc = sqlite3_reset(pCsr->pStmt);
  208934. if( rc==SQLITE_OK ){
  208935. rc = FTS5_CORRUPT;
  208936. }else if( pTab->pConfig->pzErrmsg ){
  208937. *pTab->pConfig->pzErrmsg = sqlite3_mprintf(
  208938. "%s", sqlite3_errmsg(pTab->pConfig->db)
  208939. );
  208940. }
  208941. }
  208942. }
  208943. return rc;
  208944. }
  208945. static void fts5SetVtabError(Fts5FullTable *p, const char *zFormat, ...){
  208946. va_list ap; /* ... printf arguments */
  208947. va_start(ap, zFormat);
  208948. assert( p->p.base.zErrMsg==0 );
  208949. p->p.base.zErrMsg = sqlite3_vmprintf(zFormat, ap);
  208950. va_end(ap);
  208951. }
  208952. /*
  208953. ** This function is called to handle an FTS INSERT command. In other words,
  208954. ** an INSERT statement of the form:
  208955. **
  208956. ** INSERT INTO fts(fts) VALUES($pCmd)
  208957. ** INSERT INTO fts(fts, rank) VALUES($pCmd, $pVal)
  208958. **
  208959. ** Argument pVal is the value assigned to column "fts" by the INSERT
  208960. ** statement. This function returns SQLITE_OK if successful, or an SQLite
  208961. ** error code if an error occurs.
  208962. **
  208963. ** The commands implemented by this function are documented in the "Special
  208964. ** INSERT Directives" section of the documentation. It should be updated if
  208965. ** more commands are added to this function.
  208966. */
  208967. static int fts5SpecialInsert(
  208968. Fts5FullTable *pTab, /* Fts5 table object */
  208969. const char *zCmd, /* Text inserted into table-name column */
  208970. sqlite3_value *pVal /* Value inserted into rank column */
  208971. ){
  208972. Fts5Config *pConfig = pTab->p.pConfig;
  208973. int rc = SQLITE_OK;
  208974. int bError = 0;
  208975. if( 0==sqlite3_stricmp("delete-all", zCmd) ){
  208976. if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
  208977. fts5SetVtabError(pTab,
  208978. "'delete-all' may only be used with a "
  208979. "contentless or external content fts5 table"
  208980. );
  208981. rc = SQLITE_ERROR;
  208982. }else{
  208983. rc = sqlite3Fts5StorageDeleteAll(pTab->pStorage);
  208984. }
  208985. }else if( 0==sqlite3_stricmp("rebuild", zCmd) ){
  208986. if( pConfig->eContent==FTS5_CONTENT_NONE ){
  208987. fts5SetVtabError(pTab,
  208988. "'rebuild' may not be used with a contentless fts5 table"
  208989. );
  208990. rc = SQLITE_ERROR;
  208991. }else{
  208992. rc = sqlite3Fts5StorageRebuild(pTab->pStorage);
  208993. }
  208994. }else if( 0==sqlite3_stricmp("optimize", zCmd) ){
  208995. rc = sqlite3Fts5StorageOptimize(pTab->pStorage);
  208996. }else if( 0==sqlite3_stricmp("merge", zCmd) ){
  208997. int nMerge = sqlite3_value_int(pVal);
  208998. rc = sqlite3Fts5StorageMerge(pTab->pStorage, nMerge);
  208999. }else if( 0==sqlite3_stricmp("integrity-check", zCmd) ){
  209000. rc = sqlite3Fts5StorageIntegrity(pTab->pStorage);
  209001. #ifdef SQLITE_DEBUG
  209002. }else if( 0==sqlite3_stricmp("prefix-index", zCmd) ){
  209003. pConfig->bPrefixIndex = sqlite3_value_int(pVal);
  209004. #endif
  209005. }else{
  209006. rc = sqlite3Fts5IndexLoadConfig(pTab->p.pIndex);
  209007. if( rc==SQLITE_OK ){
  209008. rc = sqlite3Fts5ConfigSetValue(pTab->p.pConfig, zCmd, pVal, &bError);
  209009. }
  209010. if( rc==SQLITE_OK ){
  209011. if( bError ){
  209012. rc = SQLITE_ERROR;
  209013. }else{
  209014. rc = sqlite3Fts5StorageConfigValue(pTab->pStorage, zCmd, pVal, 0);
  209015. }
  209016. }
  209017. }
  209018. return rc;
  209019. }
  209020. static int fts5SpecialDelete(
  209021. Fts5FullTable *pTab,
  209022. sqlite3_value **apVal
  209023. ){
  209024. int rc = SQLITE_OK;
  209025. int eType1 = sqlite3_value_type(apVal[1]);
  209026. if( eType1==SQLITE_INTEGER ){
  209027. sqlite3_int64 iDel = sqlite3_value_int64(apVal[1]);
  209028. rc = sqlite3Fts5StorageDelete(pTab->pStorage, iDel, &apVal[2]);
  209029. }
  209030. return rc;
  209031. }
  209032. static void fts5StorageInsert(
  209033. int *pRc,
  209034. Fts5FullTable *pTab,
  209035. sqlite3_value **apVal,
  209036. i64 *piRowid
  209037. ){
  209038. int rc = *pRc;
  209039. if( rc==SQLITE_OK ){
  209040. rc = sqlite3Fts5StorageContentInsert(pTab->pStorage, apVal, piRowid);
  209041. }
  209042. if( rc==SQLITE_OK ){
  209043. rc = sqlite3Fts5StorageIndexInsert(pTab->pStorage, apVal, *piRowid);
  209044. }
  209045. *pRc = rc;
  209046. }
  209047. /*
  209048. ** This function is the implementation of the xUpdate callback used by
  209049. ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
  209050. ** inserted, updated or deleted.
  209051. **
  209052. ** A delete specifies a single argument - the rowid of the row to remove.
  209053. **
  209054. ** Update and insert operations pass:
  209055. **
  209056. ** 1. The "old" rowid, or NULL.
  209057. ** 2. The "new" rowid.
  209058. ** 3. Values for each of the nCol matchable columns.
  209059. ** 4. Values for the two hidden columns (<tablename> and "rank").
  209060. */
  209061. static int fts5UpdateMethod(
  209062. sqlite3_vtab *pVtab, /* Virtual table handle */
  209063. int nArg, /* Size of argument array */
  209064. sqlite3_value **apVal, /* Array of arguments */
  209065. sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */
  209066. ){
  209067. Fts5FullTable *pTab = (Fts5FullTable*)pVtab;
  209068. Fts5Config *pConfig = pTab->p.pConfig;
  209069. int eType0; /* value_type() of apVal[0] */
  209070. int rc = SQLITE_OK; /* Return code */
  209071. /* A transaction must be open when this is called. */
  209072. assert( pTab->ts.eState==1 );
  209073. assert( pVtab->zErrMsg==0 );
  209074. assert( nArg==1 || nArg==(2+pConfig->nCol+2) );
  209075. assert( sqlite3_value_type(apVal[0])==SQLITE_INTEGER
  209076. || sqlite3_value_type(apVal[0])==SQLITE_NULL
  209077. );
  209078. assert( pTab->p.pConfig->pzErrmsg==0 );
  209079. pTab->p.pConfig->pzErrmsg = &pTab->p.base.zErrMsg;
  209080. /* Put any active cursors into REQUIRE_SEEK state. */
  209081. fts5TripCursors(pTab);
  209082. eType0 = sqlite3_value_type(apVal[0]);
  209083. if( eType0==SQLITE_NULL
  209084. && sqlite3_value_type(apVal[2+pConfig->nCol])!=SQLITE_NULL
  209085. ){
  209086. /* A "special" INSERT op. These are handled separately. */
  209087. const char *z = (const char*)sqlite3_value_text(apVal[2+pConfig->nCol]);
  209088. if( pConfig->eContent!=FTS5_CONTENT_NORMAL
  209089. && 0==sqlite3_stricmp("delete", z)
  209090. ){
  209091. rc = fts5SpecialDelete(pTab, apVal);
  209092. }else{
  209093. rc = fts5SpecialInsert(pTab, z, apVal[2 + pConfig->nCol + 1]);
  209094. }
  209095. }else{
  209096. /* A regular INSERT, UPDATE or DELETE statement. The trick here is that
  209097. ** any conflict on the rowid value must be detected before any
  209098. ** modifications are made to the database file. There are 4 cases:
  209099. **
  209100. ** 1) DELETE
  209101. ** 2) UPDATE (rowid not modified)
  209102. ** 3) UPDATE (rowid modified)
  209103. ** 4) INSERT
  209104. **
  209105. ** Cases 3 and 4 may violate the rowid constraint.
  209106. */
  209107. int eConflict = SQLITE_ABORT;
  209108. if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
  209109. eConflict = sqlite3_vtab_on_conflict(pConfig->db);
  209110. }
  209111. assert( eType0==SQLITE_INTEGER || eType0==SQLITE_NULL );
  209112. assert( nArg!=1 || eType0==SQLITE_INTEGER );
  209113. /* Filter out attempts to run UPDATE or DELETE on contentless tables.
  209114. ** This is not suported. */
  209115. if( eType0==SQLITE_INTEGER && fts5IsContentless(pTab) ){
  209116. pTab->p.base.zErrMsg = sqlite3_mprintf(
  209117. "cannot %s contentless fts5 table: %s",
  209118. (nArg>1 ? "UPDATE" : "DELETE from"), pConfig->zName
  209119. );
  209120. rc = SQLITE_ERROR;
  209121. }
  209122. /* DELETE */
  209123. else if( nArg==1 ){
  209124. i64 iDel = sqlite3_value_int64(apVal[0]); /* Rowid to delete */
  209125. rc = sqlite3Fts5StorageDelete(pTab->pStorage, iDel, 0);
  209126. }
  209127. /* INSERT or UPDATE */
  209128. else{
  209129. int eType1 = sqlite3_value_numeric_type(apVal[1]);
  209130. if( eType1!=SQLITE_INTEGER && eType1!=SQLITE_NULL ){
  209131. rc = SQLITE_MISMATCH;
  209132. }
  209133. else if( eType0!=SQLITE_INTEGER ){
  209134. /* If this is a REPLACE, first remove the current entry (if any) */
  209135. if( eConflict==SQLITE_REPLACE && eType1==SQLITE_INTEGER ){
  209136. i64 iNew = sqlite3_value_int64(apVal[1]); /* Rowid to delete */
  209137. rc = sqlite3Fts5StorageDelete(pTab->pStorage, iNew, 0);
  209138. }
  209139. fts5StorageInsert(&rc, pTab, apVal, pRowid);
  209140. }
  209141. /* UPDATE */
  209142. else{
  209143. i64 iOld = sqlite3_value_int64(apVal[0]); /* Old rowid */
  209144. i64 iNew = sqlite3_value_int64(apVal[1]); /* New rowid */
  209145. if( eType1==SQLITE_INTEGER && iOld!=iNew ){
  209146. if( eConflict==SQLITE_REPLACE ){
  209147. rc = sqlite3Fts5StorageDelete(pTab->pStorage, iOld, 0);
  209148. if( rc==SQLITE_OK ){
  209149. rc = sqlite3Fts5StorageDelete(pTab->pStorage, iNew, 0);
  209150. }
  209151. fts5StorageInsert(&rc, pTab, apVal, pRowid);
  209152. }else{
  209153. rc = sqlite3Fts5StorageContentInsert(pTab->pStorage, apVal, pRowid);
  209154. if( rc==SQLITE_OK ){
  209155. rc = sqlite3Fts5StorageDelete(pTab->pStorage, iOld, 0);
  209156. }
  209157. if( rc==SQLITE_OK ){
  209158. rc = sqlite3Fts5StorageIndexInsert(pTab->pStorage, apVal,*pRowid);
  209159. }
  209160. }
  209161. }else{
  209162. rc = sqlite3Fts5StorageDelete(pTab->pStorage, iOld, 0);
  209163. fts5StorageInsert(&rc, pTab, apVal, pRowid);
  209164. }
  209165. }
  209166. }
  209167. }
  209168. pTab->p.pConfig->pzErrmsg = 0;
  209169. return rc;
  209170. }
  209171. /*
  209172. ** Implementation of xSync() method.
  209173. */
  209174. static int fts5SyncMethod(sqlite3_vtab *pVtab){
  209175. int rc;
  209176. Fts5FullTable *pTab = (Fts5FullTable*)pVtab;
  209177. fts5CheckTransactionState(pTab, FTS5_SYNC, 0);
  209178. pTab->p.pConfig->pzErrmsg = &pTab->p.base.zErrMsg;
  209179. fts5TripCursors(pTab);
  209180. rc = sqlite3Fts5StorageSync(pTab->pStorage);
  209181. pTab->p.pConfig->pzErrmsg = 0;
  209182. return rc;
  209183. }
  209184. /*
  209185. ** Implementation of xBegin() method.
  209186. */
  209187. static int fts5BeginMethod(sqlite3_vtab *pVtab){
  209188. fts5CheckTransactionState((Fts5FullTable*)pVtab, FTS5_BEGIN, 0);
  209189. fts5NewTransaction((Fts5FullTable*)pVtab);
  209190. return SQLITE_OK;
  209191. }
  209192. /*
  209193. ** Implementation of xCommit() method. This is a no-op. The contents of
  209194. ** the pending-terms hash-table have already been flushed into the database
  209195. ** by fts5SyncMethod().
  209196. */
  209197. static int fts5CommitMethod(sqlite3_vtab *pVtab){
  209198. UNUSED_PARAM(pVtab); /* Call below is a no-op for NDEBUG builds */
  209199. fts5CheckTransactionState((Fts5FullTable*)pVtab, FTS5_COMMIT, 0);
  209200. return SQLITE_OK;
  209201. }
  209202. /*
  209203. ** Implementation of xRollback(). Discard the contents of the pending-terms
  209204. ** hash-table. Any changes made to the database are reverted by SQLite.
  209205. */
  209206. static int fts5RollbackMethod(sqlite3_vtab *pVtab){
  209207. int rc;
  209208. Fts5FullTable *pTab = (Fts5FullTable*)pVtab;
  209209. fts5CheckTransactionState(pTab, FTS5_ROLLBACK, 0);
  209210. rc = sqlite3Fts5StorageRollback(pTab->pStorage);
  209211. return rc;
  209212. }
  209213. static int fts5CsrPoslist(Fts5Cursor*, int, const u8**, int*);
  209214. static void *fts5ApiUserData(Fts5Context *pCtx){
  209215. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  209216. return pCsr->pAux->pUserData;
  209217. }
  209218. static int fts5ApiColumnCount(Fts5Context *pCtx){
  209219. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  209220. return ((Fts5Table*)(pCsr->base.pVtab))->pConfig->nCol;
  209221. }
  209222. static int fts5ApiColumnTotalSize(
  209223. Fts5Context *pCtx,
  209224. int iCol,
  209225. sqlite3_int64 *pnToken
  209226. ){
  209227. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  209228. Fts5FullTable *pTab = (Fts5FullTable*)(pCsr->base.pVtab);
  209229. return sqlite3Fts5StorageSize(pTab->pStorage, iCol, pnToken);
  209230. }
  209231. static int fts5ApiRowCount(Fts5Context *pCtx, i64 *pnRow){
  209232. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  209233. Fts5FullTable *pTab = (Fts5FullTable*)(pCsr->base.pVtab);
  209234. return sqlite3Fts5StorageRowCount(pTab->pStorage, pnRow);
  209235. }
  209236. static int fts5ApiTokenize(
  209237. Fts5Context *pCtx,
  209238. const char *pText, int nText,
  209239. void *pUserData,
  209240. int (*xToken)(void*, int, const char*, int, int, int)
  209241. ){
  209242. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  209243. Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
  209244. return sqlite3Fts5Tokenize(
  209245. pTab->pConfig, FTS5_TOKENIZE_AUX, pText, nText, pUserData, xToken
  209246. );
  209247. }
  209248. static int fts5ApiPhraseCount(Fts5Context *pCtx){
  209249. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  209250. return sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
  209251. }
  209252. static int fts5ApiPhraseSize(Fts5Context *pCtx, int iPhrase){
  209253. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  209254. return sqlite3Fts5ExprPhraseSize(pCsr->pExpr, iPhrase);
  209255. }
  209256. static int fts5ApiColumnText(
  209257. Fts5Context *pCtx,
  209258. int iCol,
  209259. const char **pz,
  209260. int *pn
  209261. ){
  209262. int rc = SQLITE_OK;
  209263. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  209264. if( fts5IsContentless((Fts5FullTable*)(pCsr->base.pVtab))
  209265. || pCsr->ePlan==FTS5_PLAN_SPECIAL
  209266. ){
  209267. *pz = 0;
  209268. *pn = 0;
  209269. }else{
  209270. rc = fts5SeekCursor(pCsr, 0);
  209271. if( rc==SQLITE_OK ){
  209272. *pz = (const char*)sqlite3_column_text(pCsr->pStmt, iCol+1);
  209273. *pn = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
  209274. }
  209275. }
  209276. return rc;
  209277. }
  209278. static int fts5CsrPoslist(
  209279. Fts5Cursor *pCsr,
  209280. int iPhrase,
  209281. const u8 **pa,
  209282. int *pn
  209283. ){
  209284. Fts5Config *pConfig = ((Fts5Table*)(pCsr->base.pVtab))->pConfig;
  209285. int rc = SQLITE_OK;
  209286. int bLive = (pCsr->pSorter==0);
  209287. if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_POSLIST) ){
  209288. if( pConfig->eDetail!=FTS5_DETAIL_FULL ){
  209289. Fts5PoslistPopulator *aPopulator;
  209290. int i;
  209291. aPopulator = sqlite3Fts5ExprClearPoslists(pCsr->pExpr, bLive);
  209292. if( aPopulator==0 ) rc = SQLITE_NOMEM;
  209293. for(i=0; i<pConfig->nCol && rc==SQLITE_OK; i++){
  209294. int n; const char *z;
  209295. rc = fts5ApiColumnText((Fts5Context*)pCsr, i, &z, &n);
  209296. if( rc==SQLITE_OK ){
  209297. rc = sqlite3Fts5ExprPopulatePoslists(
  209298. pConfig, pCsr->pExpr, aPopulator, i, z, n
  209299. );
  209300. }
  209301. }
  209302. sqlite3_free(aPopulator);
  209303. if( pCsr->pSorter ){
  209304. sqlite3Fts5ExprCheckPoslists(pCsr->pExpr, pCsr->pSorter->iRowid);
  209305. }
  209306. }
  209307. CsrFlagClear(pCsr, FTS5CSR_REQUIRE_POSLIST);
  209308. }
  209309. if( pCsr->pSorter && pConfig->eDetail==FTS5_DETAIL_FULL ){
  209310. Fts5Sorter *pSorter = pCsr->pSorter;
  209311. int i1 = (iPhrase==0 ? 0 : pSorter->aIdx[iPhrase-1]);
  209312. *pn = pSorter->aIdx[iPhrase] - i1;
  209313. *pa = &pSorter->aPoslist[i1];
  209314. }else{
  209315. *pn = sqlite3Fts5ExprPoslist(pCsr->pExpr, iPhrase, pa);
  209316. }
  209317. return rc;
  209318. }
  209319. /*
  209320. ** Ensure that the Fts5Cursor.nInstCount and aInst[] variables are populated
  209321. ** correctly for the current view. Return SQLITE_OK if successful, or an
  209322. ** SQLite error code otherwise.
  209323. */
  209324. static int fts5CacheInstArray(Fts5Cursor *pCsr){
  209325. int rc = SQLITE_OK;
  209326. Fts5PoslistReader *aIter; /* One iterator for each phrase */
  209327. int nIter; /* Number of iterators/phrases */
  209328. int nCol = ((Fts5Table*)pCsr->base.pVtab)->pConfig->nCol;
  209329. nIter = sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
  209330. if( pCsr->aInstIter==0 ){
  209331. sqlite3_int64 nByte = sizeof(Fts5PoslistReader) * nIter;
  209332. pCsr->aInstIter = (Fts5PoslistReader*)sqlite3Fts5MallocZero(&rc, nByte);
  209333. }
  209334. aIter = pCsr->aInstIter;
  209335. if( aIter ){
  209336. int nInst = 0; /* Number instances seen so far */
  209337. int i;
  209338. /* Initialize all iterators */
  209339. for(i=0; i<nIter && rc==SQLITE_OK; i++){
  209340. const u8 *a;
  209341. int n;
  209342. rc = fts5CsrPoslist(pCsr, i, &a, &n);
  209343. if( rc==SQLITE_OK ){
  209344. sqlite3Fts5PoslistReaderInit(a, n, &aIter[i]);
  209345. }
  209346. }
  209347. if( rc==SQLITE_OK ){
  209348. while( 1 ){
  209349. int *aInst;
  209350. int iBest = -1;
  209351. for(i=0; i<nIter; i++){
  209352. if( (aIter[i].bEof==0)
  209353. && (iBest<0 || aIter[i].iPos<aIter[iBest].iPos)
  209354. ){
  209355. iBest = i;
  209356. }
  209357. }
  209358. if( iBest<0 ) break;
  209359. nInst++;
  209360. if( nInst>=pCsr->nInstAlloc ){
  209361. pCsr->nInstAlloc = pCsr->nInstAlloc ? pCsr->nInstAlloc*2 : 32;
  209362. aInst = (int*)sqlite3_realloc64(
  209363. pCsr->aInst, pCsr->nInstAlloc*sizeof(int)*3
  209364. );
  209365. if( aInst ){
  209366. pCsr->aInst = aInst;
  209367. }else{
  209368. rc = SQLITE_NOMEM;
  209369. break;
  209370. }
  209371. }
  209372. aInst = &pCsr->aInst[3 * (nInst-1)];
  209373. aInst[0] = iBest;
  209374. aInst[1] = FTS5_POS2COLUMN(aIter[iBest].iPos);
  209375. aInst[2] = FTS5_POS2OFFSET(aIter[iBest].iPos);
  209376. if( aInst[1]<0 || aInst[1]>=nCol ){
  209377. rc = FTS5_CORRUPT;
  209378. break;
  209379. }
  209380. sqlite3Fts5PoslistReaderNext(&aIter[iBest]);
  209381. }
  209382. }
  209383. pCsr->nInstCount = nInst;
  209384. CsrFlagClear(pCsr, FTS5CSR_REQUIRE_INST);
  209385. }
  209386. return rc;
  209387. }
  209388. static int fts5ApiInstCount(Fts5Context *pCtx, int *pnInst){
  209389. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  209390. int rc = SQLITE_OK;
  209391. if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_INST)==0
  209392. || SQLITE_OK==(rc = fts5CacheInstArray(pCsr)) ){
  209393. *pnInst = pCsr->nInstCount;
  209394. }
  209395. return rc;
  209396. }
  209397. static int fts5ApiInst(
  209398. Fts5Context *pCtx,
  209399. int iIdx,
  209400. int *piPhrase,
  209401. int *piCol,
  209402. int *piOff
  209403. ){
  209404. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  209405. int rc = SQLITE_OK;
  209406. if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_INST)==0
  209407. || SQLITE_OK==(rc = fts5CacheInstArray(pCsr))
  209408. ){
  209409. if( iIdx<0 || iIdx>=pCsr->nInstCount ){
  209410. rc = SQLITE_RANGE;
  209411. #if 0
  209412. }else if( fts5IsOffsetless((Fts5Table*)pCsr->base.pVtab) ){
  209413. *piPhrase = pCsr->aInst[iIdx*3];
  209414. *piCol = pCsr->aInst[iIdx*3 + 2];
  209415. *piOff = -1;
  209416. #endif
  209417. }else{
  209418. *piPhrase = pCsr->aInst[iIdx*3];
  209419. *piCol = pCsr->aInst[iIdx*3 + 1];
  209420. *piOff = pCsr->aInst[iIdx*3 + 2];
  209421. }
  209422. }
  209423. return rc;
  209424. }
  209425. static sqlite3_int64 fts5ApiRowid(Fts5Context *pCtx){
  209426. return fts5CursorRowid((Fts5Cursor*)pCtx);
  209427. }
  209428. static int fts5ColumnSizeCb(
  209429. void *pContext, /* Pointer to int */
  209430. int tflags,
  209431. const char *pUnused, /* Buffer containing token */
  209432. int nUnused, /* Size of token in bytes */
  209433. int iUnused1, /* Start offset of token */
  209434. int iUnused2 /* End offset of token */
  209435. ){
  209436. int *pCnt = (int*)pContext;
  209437. UNUSED_PARAM2(pUnused, nUnused);
  209438. UNUSED_PARAM2(iUnused1, iUnused2);
  209439. if( (tflags & FTS5_TOKEN_COLOCATED)==0 ){
  209440. (*pCnt)++;
  209441. }
  209442. return SQLITE_OK;
  209443. }
  209444. static int fts5ApiColumnSize(Fts5Context *pCtx, int iCol, int *pnToken){
  209445. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  209446. Fts5FullTable *pTab = (Fts5FullTable*)(pCsr->base.pVtab);
  209447. Fts5Config *pConfig = pTab->p.pConfig;
  209448. int rc = SQLITE_OK;
  209449. if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_DOCSIZE) ){
  209450. if( pConfig->bColumnsize ){
  209451. i64 iRowid = fts5CursorRowid(pCsr);
  209452. rc = sqlite3Fts5StorageDocsize(pTab->pStorage, iRowid, pCsr->aColumnSize);
  209453. }else if( pConfig->zContent==0 ){
  209454. int i;
  209455. for(i=0; i<pConfig->nCol; i++){
  209456. if( pConfig->abUnindexed[i]==0 ){
  209457. pCsr->aColumnSize[i] = -1;
  209458. }
  209459. }
  209460. }else{
  209461. int i;
  209462. for(i=0; rc==SQLITE_OK && i<pConfig->nCol; i++){
  209463. if( pConfig->abUnindexed[i]==0 ){
  209464. const char *z; int n;
  209465. void *p = (void*)(&pCsr->aColumnSize[i]);
  209466. pCsr->aColumnSize[i] = 0;
  209467. rc = fts5ApiColumnText(pCtx, i, &z, &n);
  209468. if( rc==SQLITE_OK ){
  209469. rc = sqlite3Fts5Tokenize(
  209470. pConfig, FTS5_TOKENIZE_AUX, z, n, p, fts5ColumnSizeCb
  209471. );
  209472. }
  209473. }
  209474. }
  209475. }
  209476. CsrFlagClear(pCsr, FTS5CSR_REQUIRE_DOCSIZE);
  209477. }
  209478. if( iCol<0 ){
  209479. int i;
  209480. *pnToken = 0;
  209481. for(i=0; i<pConfig->nCol; i++){
  209482. *pnToken += pCsr->aColumnSize[i];
  209483. }
  209484. }else if( iCol<pConfig->nCol ){
  209485. *pnToken = pCsr->aColumnSize[iCol];
  209486. }else{
  209487. *pnToken = 0;
  209488. rc = SQLITE_RANGE;
  209489. }
  209490. return rc;
  209491. }
  209492. /*
  209493. ** Implementation of the xSetAuxdata() method.
  209494. */
  209495. static int fts5ApiSetAuxdata(
  209496. Fts5Context *pCtx, /* Fts5 context */
  209497. void *pPtr, /* Pointer to save as auxdata */
  209498. void(*xDelete)(void*) /* Destructor for pPtr (or NULL) */
  209499. ){
  209500. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  209501. Fts5Auxdata *pData;
  209502. /* Search through the cursors list of Fts5Auxdata objects for one that
  209503. ** corresponds to the currently executing auxiliary function. */
  209504. for(pData=pCsr->pAuxdata; pData; pData=pData->pNext){
  209505. if( pData->pAux==pCsr->pAux ) break;
  209506. }
  209507. if( pData ){
  209508. if( pData->xDelete ){
  209509. pData->xDelete(pData->pPtr);
  209510. }
  209511. }else{
  209512. int rc = SQLITE_OK;
  209513. pData = (Fts5Auxdata*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Auxdata));
  209514. if( pData==0 ){
  209515. if( xDelete ) xDelete(pPtr);
  209516. return rc;
  209517. }
  209518. pData->pAux = pCsr->pAux;
  209519. pData->pNext = pCsr->pAuxdata;
  209520. pCsr->pAuxdata = pData;
  209521. }
  209522. pData->xDelete = xDelete;
  209523. pData->pPtr = pPtr;
  209524. return SQLITE_OK;
  209525. }
  209526. static void *fts5ApiGetAuxdata(Fts5Context *pCtx, int bClear){
  209527. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  209528. Fts5Auxdata *pData;
  209529. void *pRet = 0;
  209530. for(pData=pCsr->pAuxdata; pData; pData=pData->pNext){
  209531. if( pData->pAux==pCsr->pAux ) break;
  209532. }
  209533. if( pData ){
  209534. pRet = pData->pPtr;
  209535. if( bClear ){
  209536. pData->pPtr = 0;
  209537. pData->xDelete = 0;
  209538. }
  209539. }
  209540. return pRet;
  209541. }
  209542. static void fts5ApiPhraseNext(
  209543. Fts5Context *pUnused,
  209544. Fts5PhraseIter *pIter,
  209545. int *piCol, int *piOff
  209546. ){
  209547. UNUSED_PARAM(pUnused);
  209548. if( pIter->a>=pIter->b ){
  209549. *piCol = -1;
  209550. *piOff = -1;
  209551. }else{
  209552. int iVal;
  209553. pIter->a += fts5GetVarint32(pIter->a, iVal);
  209554. if( iVal==1 ){
  209555. pIter->a += fts5GetVarint32(pIter->a, iVal);
  209556. *piCol = iVal;
  209557. *piOff = 0;
  209558. pIter->a += fts5GetVarint32(pIter->a, iVal);
  209559. }
  209560. *piOff += (iVal-2);
  209561. }
  209562. }
  209563. static int fts5ApiPhraseFirst(
  209564. Fts5Context *pCtx,
  209565. int iPhrase,
  209566. Fts5PhraseIter *pIter,
  209567. int *piCol, int *piOff
  209568. ){
  209569. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  209570. int n;
  209571. int rc = fts5CsrPoslist(pCsr, iPhrase, &pIter->a, &n);
  209572. if( rc==SQLITE_OK ){
  209573. pIter->b = &pIter->a[n];
  209574. *piCol = 0;
  209575. *piOff = 0;
  209576. fts5ApiPhraseNext(pCtx, pIter, piCol, piOff);
  209577. }
  209578. return rc;
  209579. }
  209580. static void fts5ApiPhraseNextColumn(
  209581. Fts5Context *pCtx,
  209582. Fts5PhraseIter *pIter,
  209583. int *piCol
  209584. ){
  209585. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  209586. Fts5Config *pConfig = ((Fts5Table*)(pCsr->base.pVtab))->pConfig;
  209587. if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
  209588. if( pIter->a>=pIter->b ){
  209589. *piCol = -1;
  209590. }else{
  209591. int iIncr;
  209592. pIter->a += fts5GetVarint32(&pIter->a[0], iIncr);
  209593. *piCol += (iIncr-2);
  209594. }
  209595. }else{
  209596. while( 1 ){
  209597. int dummy;
  209598. if( pIter->a>=pIter->b ){
  209599. *piCol = -1;
  209600. return;
  209601. }
  209602. if( pIter->a[0]==0x01 ) break;
  209603. pIter->a += fts5GetVarint32(pIter->a, dummy);
  209604. }
  209605. pIter->a += 1 + fts5GetVarint32(&pIter->a[1], *piCol);
  209606. }
  209607. }
  209608. static int fts5ApiPhraseFirstColumn(
  209609. Fts5Context *pCtx,
  209610. int iPhrase,
  209611. Fts5PhraseIter *pIter,
  209612. int *piCol
  209613. ){
  209614. int rc = SQLITE_OK;
  209615. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  209616. Fts5Config *pConfig = ((Fts5Table*)(pCsr->base.pVtab))->pConfig;
  209617. if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
  209618. Fts5Sorter *pSorter = pCsr->pSorter;
  209619. int n;
  209620. if( pSorter ){
  209621. int i1 = (iPhrase==0 ? 0 : pSorter->aIdx[iPhrase-1]);
  209622. n = pSorter->aIdx[iPhrase] - i1;
  209623. pIter->a = &pSorter->aPoslist[i1];
  209624. }else{
  209625. rc = sqlite3Fts5ExprPhraseCollist(pCsr->pExpr, iPhrase, &pIter->a, &n);
  209626. }
  209627. if( rc==SQLITE_OK ){
  209628. pIter->b = &pIter->a[n];
  209629. *piCol = 0;
  209630. fts5ApiPhraseNextColumn(pCtx, pIter, piCol);
  209631. }
  209632. }else{
  209633. int n;
  209634. rc = fts5CsrPoslist(pCsr, iPhrase, &pIter->a, &n);
  209635. if( rc==SQLITE_OK ){
  209636. pIter->b = &pIter->a[n];
  209637. if( n<=0 ){
  209638. *piCol = -1;
  209639. }else if( pIter->a[0]==0x01 ){
  209640. pIter->a += 1 + fts5GetVarint32(&pIter->a[1], *piCol);
  209641. }else{
  209642. *piCol = 0;
  209643. }
  209644. }
  209645. }
  209646. return rc;
  209647. }
  209648. static int fts5ApiQueryPhrase(Fts5Context*, int, void*,
  209649. int(*)(const Fts5ExtensionApi*, Fts5Context*, void*)
  209650. );
  209651. static const Fts5ExtensionApi sFts5Api = {
  209652. 2, /* iVersion */
  209653. fts5ApiUserData,
  209654. fts5ApiColumnCount,
  209655. fts5ApiRowCount,
  209656. fts5ApiColumnTotalSize,
  209657. fts5ApiTokenize,
  209658. fts5ApiPhraseCount,
  209659. fts5ApiPhraseSize,
  209660. fts5ApiInstCount,
  209661. fts5ApiInst,
  209662. fts5ApiRowid,
  209663. fts5ApiColumnText,
  209664. fts5ApiColumnSize,
  209665. fts5ApiQueryPhrase,
  209666. fts5ApiSetAuxdata,
  209667. fts5ApiGetAuxdata,
  209668. fts5ApiPhraseFirst,
  209669. fts5ApiPhraseNext,
  209670. fts5ApiPhraseFirstColumn,
  209671. fts5ApiPhraseNextColumn,
  209672. };
  209673. /*
  209674. ** Implementation of API function xQueryPhrase().
  209675. */
  209676. static int fts5ApiQueryPhrase(
  209677. Fts5Context *pCtx,
  209678. int iPhrase,
  209679. void *pUserData,
  209680. int(*xCallback)(const Fts5ExtensionApi*, Fts5Context*, void*)
  209681. ){
  209682. Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
  209683. Fts5FullTable *pTab = (Fts5FullTable*)(pCsr->base.pVtab);
  209684. int rc;
  209685. Fts5Cursor *pNew = 0;
  209686. rc = fts5OpenMethod(pCsr->base.pVtab, (sqlite3_vtab_cursor**)&pNew);
  209687. if( rc==SQLITE_OK ){
  209688. pNew->ePlan = FTS5_PLAN_MATCH;
  209689. pNew->iFirstRowid = SMALLEST_INT64;
  209690. pNew->iLastRowid = LARGEST_INT64;
  209691. pNew->base.pVtab = (sqlite3_vtab*)pTab;
  209692. rc = sqlite3Fts5ExprClonePhrase(pCsr->pExpr, iPhrase, &pNew->pExpr);
  209693. }
  209694. if( rc==SQLITE_OK ){
  209695. for(rc = fts5CursorFirst(pTab, pNew, 0);
  209696. rc==SQLITE_OK && CsrFlagTest(pNew, FTS5CSR_EOF)==0;
  209697. rc = fts5NextMethod((sqlite3_vtab_cursor*)pNew)
  209698. ){
  209699. rc = xCallback(&sFts5Api, (Fts5Context*)pNew, pUserData);
  209700. if( rc!=SQLITE_OK ){
  209701. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  209702. break;
  209703. }
  209704. }
  209705. }
  209706. fts5CloseMethod((sqlite3_vtab_cursor*)pNew);
  209707. return rc;
  209708. }
  209709. static void fts5ApiInvoke(
  209710. Fts5Auxiliary *pAux,
  209711. Fts5Cursor *pCsr,
  209712. sqlite3_context *context,
  209713. int argc,
  209714. sqlite3_value **argv
  209715. ){
  209716. assert( pCsr->pAux==0 );
  209717. pCsr->pAux = pAux;
  209718. pAux->xFunc(&sFts5Api, (Fts5Context*)pCsr, context, argc, argv);
  209719. pCsr->pAux = 0;
  209720. }
  209721. static Fts5Cursor *fts5CursorFromCsrid(Fts5Global *pGlobal, i64 iCsrId){
  209722. Fts5Cursor *pCsr;
  209723. for(pCsr=pGlobal->pCsr; pCsr; pCsr=pCsr->pNext){
  209724. if( pCsr->iCsrId==iCsrId ) break;
  209725. }
  209726. return pCsr;
  209727. }
  209728. static void fts5ApiCallback(
  209729. sqlite3_context *context,
  209730. int argc,
  209731. sqlite3_value **argv
  209732. ){
  209733. Fts5Auxiliary *pAux;
  209734. Fts5Cursor *pCsr;
  209735. i64 iCsrId;
  209736. assert( argc>=1 );
  209737. pAux = (Fts5Auxiliary*)sqlite3_user_data(context);
  209738. iCsrId = sqlite3_value_int64(argv[0]);
  209739. pCsr = fts5CursorFromCsrid(pAux->pGlobal, iCsrId);
  209740. if( pCsr==0 || pCsr->ePlan==0 ){
  209741. char *zErr = sqlite3_mprintf("no such cursor: %lld", iCsrId);
  209742. sqlite3_result_error(context, zErr, -1);
  209743. sqlite3_free(zErr);
  209744. }else{
  209745. fts5ApiInvoke(pAux, pCsr, context, argc-1, &argv[1]);
  209746. }
  209747. }
  209748. /*
  209749. ** Given cursor id iId, return a pointer to the corresponding Fts5Table
  209750. ** object. Or NULL If the cursor id does not exist.
  209751. */
  209752. static Fts5Table *sqlite3Fts5TableFromCsrid(
  209753. Fts5Global *pGlobal, /* FTS5 global context for db handle */
  209754. i64 iCsrId /* Id of cursor to find */
  209755. ){
  209756. Fts5Cursor *pCsr;
  209757. pCsr = fts5CursorFromCsrid(pGlobal, iCsrId);
  209758. if( pCsr ){
  209759. return (Fts5Table*)pCsr->base.pVtab;
  209760. }
  209761. return 0;
  209762. }
  209763. /*
  209764. ** Return a "position-list blob" corresponding to the current position of
  209765. ** cursor pCsr via sqlite3_result_blob(). A position-list blob contains
  209766. ** the current position-list for each phrase in the query associated with
  209767. ** cursor pCsr.
  209768. **
  209769. ** A position-list blob begins with (nPhrase-1) varints, where nPhrase is
  209770. ** the number of phrases in the query. Following the varints are the
  209771. ** concatenated position lists for each phrase, in order.
  209772. **
  209773. ** The first varint (if it exists) contains the size of the position list
  209774. ** for phrase 0. The second (same disclaimer) contains the size of position
  209775. ** list 1. And so on. There is no size field for the final position list,
  209776. ** as it can be derived from the total size of the blob.
  209777. */
  209778. static int fts5PoslistBlob(sqlite3_context *pCtx, Fts5Cursor *pCsr){
  209779. int i;
  209780. int rc = SQLITE_OK;
  209781. int nPhrase = sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
  209782. Fts5Buffer val;
  209783. memset(&val, 0, sizeof(Fts5Buffer));
  209784. switch( ((Fts5Table*)(pCsr->base.pVtab))->pConfig->eDetail ){
  209785. case FTS5_DETAIL_FULL:
  209786. /* Append the varints */
  209787. for(i=0; i<(nPhrase-1); i++){
  209788. const u8 *dummy;
  209789. int nByte = sqlite3Fts5ExprPoslist(pCsr->pExpr, i, &dummy);
  209790. sqlite3Fts5BufferAppendVarint(&rc, &val, nByte);
  209791. }
  209792. /* Append the position lists */
  209793. for(i=0; i<nPhrase; i++){
  209794. const u8 *pPoslist;
  209795. int nPoslist;
  209796. nPoslist = sqlite3Fts5ExprPoslist(pCsr->pExpr, i, &pPoslist);
  209797. sqlite3Fts5BufferAppendBlob(&rc, &val, nPoslist, pPoslist);
  209798. }
  209799. break;
  209800. case FTS5_DETAIL_COLUMNS:
  209801. /* Append the varints */
  209802. for(i=0; rc==SQLITE_OK && i<(nPhrase-1); i++){
  209803. const u8 *dummy;
  209804. int nByte;
  209805. rc = sqlite3Fts5ExprPhraseCollist(pCsr->pExpr, i, &dummy, &nByte);
  209806. sqlite3Fts5BufferAppendVarint(&rc, &val, nByte);
  209807. }
  209808. /* Append the position lists */
  209809. for(i=0; rc==SQLITE_OK && i<nPhrase; i++){
  209810. const u8 *pPoslist;
  209811. int nPoslist;
  209812. rc = sqlite3Fts5ExprPhraseCollist(pCsr->pExpr, i, &pPoslist, &nPoslist);
  209813. sqlite3Fts5BufferAppendBlob(&rc, &val, nPoslist, pPoslist);
  209814. }
  209815. break;
  209816. default:
  209817. break;
  209818. }
  209819. sqlite3_result_blob(pCtx, val.p, val.n, sqlite3_free);
  209820. return rc;
  209821. }
  209822. /*
  209823. ** This is the xColumn method, called by SQLite to request a value from
  209824. ** the row that the supplied cursor currently points to.
  209825. */
  209826. static int fts5ColumnMethod(
  209827. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  209828. sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
  209829. int iCol /* Index of column to read value from */
  209830. ){
  209831. Fts5FullTable *pTab = (Fts5FullTable*)(pCursor->pVtab);
  209832. Fts5Config *pConfig = pTab->p.pConfig;
  209833. Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
  209834. int rc = SQLITE_OK;
  209835. assert( CsrFlagTest(pCsr, FTS5CSR_EOF)==0 );
  209836. if( pCsr->ePlan==FTS5_PLAN_SPECIAL ){
  209837. if( iCol==pConfig->nCol ){
  209838. sqlite3_result_int64(pCtx, pCsr->iSpecial);
  209839. }
  209840. }else
  209841. if( iCol==pConfig->nCol ){
  209842. /* User is requesting the value of the special column with the same name
  209843. ** as the table. Return the cursor integer id number. This value is only
  209844. ** useful in that it may be passed as the first argument to an FTS5
  209845. ** auxiliary function. */
  209846. sqlite3_result_int64(pCtx, pCsr->iCsrId);
  209847. }else if( iCol==pConfig->nCol+1 ){
  209848. /* The value of the "rank" column. */
  209849. if( pCsr->ePlan==FTS5_PLAN_SOURCE ){
  209850. fts5PoslistBlob(pCtx, pCsr);
  209851. }else if(
  209852. pCsr->ePlan==FTS5_PLAN_MATCH
  209853. || pCsr->ePlan==FTS5_PLAN_SORTED_MATCH
  209854. ){
  209855. if( pCsr->pRank || SQLITE_OK==(rc = fts5FindRankFunction(pCsr)) ){
  209856. fts5ApiInvoke(pCsr->pRank, pCsr, pCtx, pCsr->nRankArg, pCsr->apRankArg);
  209857. }
  209858. }
  209859. }else if( !fts5IsContentless(pTab) ){
  209860. pConfig->pzErrmsg = &pTab->p.base.zErrMsg;
  209861. rc = fts5SeekCursor(pCsr, 1);
  209862. if( rc==SQLITE_OK ){
  209863. sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1));
  209864. }
  209865. pConfig->pzErrmsg = 0;
  209866. }
  209867. return rc;
  209868. }
  209869. /*
  209870. ** This routine implements the xFindFunction method for the FTS3
  209871. ** virtual table.
  209872. */
  209873. static int fts5FindFunctionMethod(
  209874. sqlite3_vtab *pVtab, /* Virtual table handle */
  209875. int nUnused, /* Number of SQL function arguments */
  209876. const char *zName, /* Name of SQL function */
  209877. void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
  209878. void **ppArg /* OUT: User data for *pxFunc */
  209879. ){
  209880. Fts5FullTable *pTab = (Fts5FullTable*)pVtab;
  209881. Fts5Auxiliary *pAux;
  209882. UNUSED_PARAM(nUnused);
  209883. pAux = fts5FindAuxiliary(pTab, zName);
  209884. if( pAux ){
  209885. *pxFunc = fts5ApiCallback;
  209886. *ppArg = (void*)pAux;
  209887. return 1;
  209888. }
  209889. /* No function of the specified name was found. Return 0. */
  209890. return 0;
  209891. }
  209892. /*
  209893. ** Implementation of FTS5 xRename method. Rename an fts5 table.
  209894. */
  209895. static int fts5RenameMethod(
  209896. sqlite3_vtab *pVtab, /* Virtual table handle */
  209897. const char *zName /* New name of table */
  209898. ){
  209899. Fts5FullTable *pTab = (Fts5FullTable*)pVtab;
  209900. return sqlite3Fts5StorageRename(pTab->pStorage, zName);
  209901. }
  209902. static int sqlite3Fts5FlushToDisk(Fts5Table *pTab){
  209903. fts5TripCursors((Fts5FullTable*)pTab);
  209904. return sqlite3Fts5StorageSync(((Fts5FullTable*)pTab)->pStorage);
  209905. }
  209906. /*
  209907. ** The xSavepoint() method.
  209908. **
  209909. ** Flush the contents of the pending-terms table to disk.
  209910. */
  209911. static int fts5SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
  209912. UNUSED_PARAM(iSavepoint); /* Call below is a no-op for NDEBUG builds */
  209913. fts5CheckTransactionState((Fts5FullTable*)pVtab, FTS5_SAVEPOINT, iSavepoint);
  209914. return sqlite3Fts5FlushToDisk((Fts5Table*)pVtab);
  209915. }
  209916. /*
  209917. ** The xRelease() method.
  209918. **
  209919. ** This is a no-op.
  209920. */
  209921. static int fts5ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
  209922. UNUSED_PARAM(iSavepoint); /* Call below is a no-op for NDEBUG builds */
  209923. fts5CheckTransactionState((Fts5FullTable*)pVtab, FTS5_RELEASE, iSavepoint);
  209924. return sqlite3Fts5FlushToDisk((Fts5Table*)pVtab);
  209925. }
  209926. /*
  209927. ** The xRollbackTo() method.
  209928. **
  209929. ** Discard the contents of the pending terms table.
  209930. */
  209931. static int fts5RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
  209932. Fts5FullTable *pTab = (Fts5FullTable*)pVtab;
  209933. UNUSED_PARAM(iSavepoint); /* Call below is a no-op for NDEBUG builds */
  209934. fts5CheckTransactionState(pTab, FTS5_ROLLBACKTO, iSavepoint);
  209935. fts5TripCursors(pTab);
  209936. return sqlite3Fts5StorageRollback(pTab->pStorage);
  209937. }
  209938. /*
  209939. ** Register a new auxiliary function with global context pGlobal.
  209940. */
  209941. static int fts5CreateAux(
  209942. fts5_api *pApi, /* Global context (one per db handle) */
  209943. const char *zName, /* Name of new function */
  209944. void *pUserData, /* User data for aux. function */
  209945. fts5_extension_function xFunc, /* Aux. function implementation */
  209946. void(*xDestroy)(void*) /* Destructor for pUserData */
  209947. ){
  209948. Fts5Global *pGlobal = (Fts5Global*)pApi;
  209949. int rc = sqlite3_overload_function(pGlobal->db, zName, -1);
  209950. if( rc==SQLITE_OK ){
  209951. Fts5Auxiliary *pAux;
  209952. sqlite3_int64 nName; /* Size of zName in bytes, including \0 */
  209953. sqlite3_int64 nByte; /* Bytes of space to allocate */
  209954. nName = strlen(zName) + 1;
  209955. nByte = sizeof(Fts5Auxiliary) + nName;
  209956. pAux = (Fts5Auxiliary*)sqlite3_malloc64(nByte);
  209957. if( pAux ){
  209958. memset(pAux, 0, (size_t)nByte);
  209959. pAux->zFunc = (char*)&pAux[1];
  209960. memcpy(pAux->zFunc, zName, nName);
  209961. pAux->pGlobal = pGlobal;
  209962. pAux->pUserData = pUserData;
  209963. pAux->xFunc = xFunc;
  209964. pAux->xDestroy = xDestroy;
  209965. pAux->pNext = pGlobal->pAux;
  209966. pGlobal->pAux = pAux;
  209967. }else{
  209968. rc = SQLITE_NOMEM;
  209969. }
  209970. }
  209971. return rc;
  209972. }
  209973. /*
  209974. ** Register a new tokenizer. This is the implementation of the
  209975. ** fts5_api.xCreateTokenizer() method.
  209976. */
  209977. static int fts5CreateTokenizer(
  209978. fts5_api *pApi, /* Global context (one per db handle) */
  209979. const char *zName, /* Name of new function */
  209980. void *pUserData, /* User data for aux. function */
  209981. fts5_tokenizer *pTokenizer, /* Tokenizer implementation */
  209982. void(*xDestroy)(void*) /* Destructor for pUserData */
  209983. ){
  209984. Fts5Global *pGlobal = (Fts5Global*)pApi;
  209985. Fts5TokenizerModule *pNew;
  209986. sqlite3_int64 nName; /* Size of zName and its \0 terminator */
  209987. sqlite3_int64 nByte; /* Bytes of space to allocate */
  209988. int rc = SQLITE_OK;
  209989. nName = strlen(zName) + 1;
  209990. nByte = sizeof(Fts5TokenizerModule) + nName;
  209991. pNew = (Fts5TokenizerModule*)sqlite3_malloc64(nByte);
  209992. if( pNew ){
  209993. memset(pNew, 0, (size_t)nByte);
  209994. pNew->zName = (char*)&pNew[1];
  209995. memcpy(pNew->zName, zName, nName);
  209996. pNew->pUserData = pUserData;
  209997. pNew->x = *pTokenizer;
  209998. pNew->xDestroy = xDestroy;
  209999. pNew->pNext = pGlobal->pTok;
  210000. pGlobal->pTok = pNew;
  210001. if( pNew->pNext==0 ){
  210002. pGlobal->pDfltTok = pNew;
  210003. }
  210004. }else{
  210005. rc = SQLITE_NOMEM;
  210006. }
  210007. return rc;
  210008. }
  210009. static Fts5TokenizerModule *fts5LocateTokenizer(
  210010. Fts5Global *pGlobal,
  210011. const char *zName
  210012. ){
  210013. Fts5TokenizerModule *pMod = 0;
  210014. if( zName==0 ){
  210015. pMod = pGlobal->pDfltTok;
  210016. }else{
  210017. for(pMod=pGlobal->pTok; pMod; pMod=pMod->pNext){
  210018. if( sqlite3_stricmp(zName, pMod->zName)==0 ) break;
  210019. }
  210020. }
  210021. return pMod;
  210022. }
  210023. /*
  210024. ** Find a tokenizer. This is the implementation of the
  210025. ** fts5_api.xFindTokenizer() method.
  210026. */
  210027. static int fts5FindTokenizer(
  210028. fts5_api *pApi, /* Global context (one per db handle) */
  210029. const char *zName, /* Name of new function */
  210030. void **ppUserData,
  210031. fts5_tokenizer *pTokenizer /* Populate this object */
  210032. ){
  210033. int rc = SQLITE_OK;
  210034. Fts5TokenizerModule *pMod;
  210035. pMod = fts5LocateTokenizer((Fts5Global*)pApi, zName);
  210036. if( pMod ){
  210037. *pTokenizer = pMod->x;
  210038. *ppUserData = pMod->pUserData;
  210039. }else{
  210040. memset(pTokenizer, 0, sizeof(fts5_tokenizer));
  210041. rc = SQLITE_ERROR;
  210042. }
  210043. return rc;
  210044. }
  210045. static int sqlite3Fts5GetTokenizer(
  210046. Fts5Global *pGlobal,
  210047. const char **azArg,
  210048. int nArg,
  210049. Fts5Tokenizer **ppTok,
  210050. fts5_tokenizer **ppTokApi,
  210051. char **pzErr
  210052. ){
  210053. Fts5TokenizerModule *pMod;
  210054. int rc = SQLITE_OK;
  210055. pMod = fts5LocateTokenizer(pGlobal, nArg==0 ? 0 : azArg[0]);
  210056. if( pMod==0 ){
  210057. assert( nArg>0 );
  210058. rc = SQLITE_ERROR;
  210059. *pzErr = sqlite3_mprintf("no such tokenizer: %s", azArg[0]);
  210060. }else{
  210061. rc = pMod->x.xCreate(pMod->pUserData, &azArg[1], (nArg?nArg-1:0), ppTok);
  210062. *ppTokApi = &pMod->x;
  210063. if( rc!=SQLITE_OK && pzErr ){
  210064. *pzErr = sqlite3_mprintf("error in tokenizer constructor");
  210065. }
  210066. }
  210067. if( rc!=SQLITE_OK ){
  210068. *ppTokApi = 0;
  210069. *ppTok = 0;
  210070. }
  210071. return rc;
  210072. }
  210073. static void fts5ModuleDestroy(void *pCtx){
  210074. Fts5TokenizerModule *pTok, *pNextTok;
  210075. Fts5Auxiliary *pAux, *pNextAux;
  210076. Fts5Global *pGlobal = (Fts5Global*)pCtx;
  210077. for(pAux=pGlobal->pAux; pAux; pAux=pNextAux){
  210078. pNextAux = pAux->pNext;
  210079. if( pAux->xDestroy ) pAux->xDestroy(pAux->pUserData);
  210080. sqlite3_free(pAux);
  210081. }
  210082. for(pTok=pGlobal->pTok; pTok; pTok=pNextTok){
  210083. pNextTok = pTok->pNext;
  210084. if( pTok->xDestroy ) pTok->xDestroy(pTok->pUserData);
  210085. sqlite3_free(pTok);
  210086. }
  210087. sqlite3_free(pGlobal);
  210088. }
  210089. static void fts5Fts5Func(
  210090. sqlite3_context *pCtx, /* Function call context */
  210091. int nArg, /* Number of args */
  210092. sqlite3_value **apArg /* Function arguments */
  210093. ){
  210094. Fts5Global *pGlobal = (Fts5Global*)sqlite3_user_data(pCtx);
  210095. fts5_api **ppApi;
  210096. UNUSED_PARAM(nArg);
  210097. assert( nArg==1 );
  210098. ppApi = (fts5_api**)sqlite3_value_pointer(apArg[0], "fts5_api_ptr");
  210099. if( ppApi ) *ppApi = &pGlobal->api;
  210100. }
  210101. /*
  210102. ** Implementation of fts5_source_id() function.
  210103. */
  210104. static void fts5SourceIdFunc(
  210105. sqlite3_context *pCtx, /* Function call context */
  210106. int nArg, /* Number of args */
  210107. sqlite3_value **apUnused /* Function arguments */
  210108. ){
  210109. assert( nArg==0 );
  210110. UNUSED_PARAM2(nArg, apUnused);
  210111. sqlite3_result_text(pCtx, "fts5: 2020-06-04 12:58:43 ec02243ea6ce33b090870ae55ab8aa2534b54d216d45c4aa2fdbb00e86861e8c", -1, SQLITE_TRANSIENT);
  210112. }
  210113. /*
  210114. ** Return true if zName is the extension on one of the shadow tables used
  210115. ** by this module.
  210116. */
  210117. static int fts5ShadowName(const char *zName){
  210118. static const char *azName[] = {
  210119. "config", "content", "data", "docsize", "idx"
  210120. };
  210121. unsigned int i;
  210122. for(i=0; i<sizeof(azName)/sizeof(azName[0]); i++){
  210123. if( sqlite3_stricmp(zName, azName[i])==0 ) return 1;
  210124. }
  210125. return 0;
  210126. }
  210127. static int fts5Init(sqlite3 *db){
  210128. static const sqlite3_module fts5Mod = {
  210129. /* iVersion */ 3,
  210130. /* xCreate */ fts5CreateMethod,
  210131. /* xConnect */ fts5ConnectMethod,
  210132. /* xBestIndex */ fts5BestIndexMethod,
  210133. /* xDisconnect */ fts5DisconnectMethod,
  210134. /* xDestroy */ fts5DestroyMethod,
  210135. /* xOpen */ fts5OpenMethod,
  210136. /* xClose */ fts5CloseMethod,
  210137. /* xFilter */ fts5FilterMethod,
  210138. /* xNext */ fts5NextMethod,
  210139. /* xEof */ fts5EofMethod,
  210140. /* xColumn */ fts5ColumnMethod,
  210141. /* xRowid */ fts5RowidMethod,
  210142. /* xUpdate */ fts5UpdateMethod,
  210143. /* xBegin */ fts5BeginMethod,
  210144. /* xSync */ fts5SyncMethod,
  210145. /* xCommit */ fts5CommitMethod,
  210146. /* xRollback */ fts5RollbackMethod,
  210147. /* xFindFunction */ fts5FindFunctionMethod,
  210148. /* xRename */ fts5RenameMethod,
  210149. /* xSavepoint */ fts5SavepointMethod,
  210150. /* xRelease */ fts5ReleaseMethod,
  210151. /* xRollbackTo */ fts5RollbackToMethod,
  210152. /* xShadowName */ fts5ShadowName
  210153. };
  210154. int rc;
  210155. Fts5Global *pGlobal = 0;
  210156. pGlobal = (Fts5Global*)sqlite3_malloc(sizeof(Fts5Global));
  210157. if( pGlobal==0 ){
  210158. rc = SQLITE_NOMEM;
  210159. }else{
  210160. void *p = (void*)pGlobal;
  210161. memset(pGlobal, 0, sizeof(Fts5Global));
  210162. pGlobal->db = db;
  210163. pGlobal->api.iVersion = 2;
  210164. pGlobal->api.xCreateFunction = fts5CreateAux;
  210165. pGlobal->api.xCreateTokenizer = fts5CreateTokenizer;
  210166. pGlobal->api.xFindTokenizer = fts5FindTokenizer;
  210167. rc = sqlite3_create_module_v2(db, "fts5", &fts5Mod, p, fts5ModuleDestroy);
  210168. if( rc==SQLITE_OK ) rc = sqlite3Fts5IndexInit(db);
  210169. if( rc==SQLITE_OK ) rc = sqlite3Fts5ExprInit(pGlobal, db);
  210170. if( rc==SQLITE_OK ) rc = sqlite3Fts5AuxInit(&pGlobal->api);
  210171. if( rc==SQLITE_OK ) rc = sqlite3Fts5TokenizerInit(&pGlobal->api);
  210172. if( rc==SQLITE_OK ) rc = sqlite3Fts5VocabInit(pGlobal, db);
  210173. if( rc==SQLITE_OK ){
  210174. rc = sqlite3_create_function(
  210175. db, "fts5", 1, SQLITE_UTF8, p, fts5Fts5Func, 0, 0
  210176. );
  210177. }
  210178. if( rc==SQLITE_OK ){
  210179. rc = sqlite3_create_function(
  210180. db, "fts5_source_id", 0, SQLITE_UTF8, p, fts5SourceIdFunc, 0, 0
  210181. );
  210182. }
  210183. }
  210184. /* If SQLITE_FTS5_ENABLE_TEST_MI is defined, assume that the file
  210185. ** fts5_test_mi.c is compiled and linked into the executable. And call
  210186. ** its entry point to enable the matchinfo() demo. */
  210187. #ifdef SQLITE_FTS5_ENABLE_TEST_MI
  210188. if( rc==SQLITE_OK ){
  210189. extern int sqlite3Fts5TestRegisterMatchinfo(sqlite3*);
  210190. rc = sqlite3Fts5TestRegisterMatchinfo(db);
  210191. }
  210192. #endif
  210193. return rc;
  210194. }
  210195. /*
  210196. ** The following functions are used to register the module with SQLite. If
  210197. ** this module is being built as part of the SQLite core (SQLITE_CORE is
  210198. ** defined), then sqlite3_open() will call sqlite3Fts5Init() directly.
  210199. **
  210200. ** Or, if this module is being built as a loadable extension,
  210201. ** sqlite3Fts5Init() is omitted and the two standard entry points
  210202. ** sqlite3_fts_init() and sqlite3_fts5_init() defined instead.
  210203. */
  210204. #ifndef SQLITE_CORE
  210205. #ifdef _WIN32
  210206. __declspec(dllexport)
  210207. #endif
  210208. SQLITE_API int sqlite3_fts_init(
  210209. sqlite3 *db,
  210210. char **pzErrMsg,
  210211. const sqlite3_api_routines *pApi
  210212. ){
  210213. SQLITE_EXTENSION_INIT2(pApi);
  210214. (void)pzErrMsg; /* Unused parameter */
  210215. return fts5Init(db);
  210216. }
  210217. #ifdef _WIN32
  210218. __declspec(dllexport)
  210219. #endif
  210220. SQLITE_API int sqlite3_fts5_init(
  210221. sqlite3 *db,
  210222. char **pzErrMsg,
  210223. const sqlite3_api_routines *pApi
  210224. ){
  210225. SQLITE_EXTENSION_INIT2(pApi);
  210226. (void)pzErrMsg; /* Unused parameter */
  210227. return fts5Init(db);
  210228. }
  210229. #else
  210230. SQLITE_PRIVATE int sqlite3Fts5Init(sqlite3 *db){
  210231. return fts5Init(db);
  210232. }
  210233. #endif
  210234. /*
  210235. ** 2014 May 31
  210236. **
  210237. ** The author disclaims copyright to this source code. In place of
  210238. ** a legal notice, here is a blessing:
  210239. **
  210240. ** May you do good and not evil.
  210241. ** May you find forgiveness for yourself and forgive others.
  210242. ** May you share freely, never taking more than you give.
  210243. **
  210244. ******************************************************************************
  210245. **
  210246. */
  210247. /* #include "fts5Int.h" */
  210248. struct Fts5Storage {
  210249. Fts5Config *pConfig;
  210250. Fts5Index *pIndex;
  210251. int bTotalsValid; /* True if nTotalRow/aTotalSize[] are valid */
  210252. i64 nTotalRow; /* Total number of rows in FTS table */
  210253. i64 *aTotalSize; /* Total sizes of each column */
  210254. sqlite3_stmt *aStmt[11];
  210255. };
  210256. #if FTS5_STMT_SCAN_ASC!=0
  210257. # error "FTS5_STMT_SCAN_ASC mismatch"
  210258. #endif
  210259. #if FTS5_STMT_SCAN_DESC!=1
  210260. # error "FTS5_STMT_SCAN_DESC mismatch"
  210261. #endif
  210262. #if FTS5_STMT_LOOKUP!=2
  210263. # error "FTS5_STMT_LOOKUP mismatch"
  210264. #endif
  210265. #define FTS5_STMT_INSERT_CONTENT 3
  210266. #define FTS5_STMT_REPLACE_CONTENT 4
  210267. #define FTS5_STMT_DELETE_CONTENT 5
  210268. #define FTS5_STMT_REPLACE_DOCSIZE 6
  210269. #define FTS5_STMT_DELETE_DOCSIZE 7
  210270. #define FTS5_STMT_LOOKUP_DOCSIZE 8
  210271. #define FTS5_STMT_REPLACE_CONFIG 9
  210272. #define FTS5_STMT_SCAN 10
  210273. /*
  210274. ** Prepare the two insert statements - Fts5Storage.pInsertContent and
  210275. ** Fts5Storage.pInsertDocsize - if they have not already been prepared.
  210276. ** Return SQLITE_OK if successful, or an SQLite error code if an error
  210277. ** occurs.
  210278. */
  210279. static int fts5StorageGetStmt(
  210280. Fts5Storage *p, /* Storage handle */
  210281. int eStmt, /* FTS5_STMT_XXX constant */
  210282. sqlite3_stmt **ppStmt, /* OUT: Prepared statement handle */
  210283. char **pzErrMsg /* OUT: Error message (if any) */
  210284. ){
  210285. int rc = SQLITE_OK;
  210286. /* If there is no %_docsize table, there should be no requests for
  210287. ** statements to operate on it. */
  210288. assert( p->pConfig->bColumnsize || (
  210289. eStmt!=FTS5_STMT_REPLACE_DOCSIZE
  210290. && eStmt!=FTS5_STMT_DELETE_DOCSIZE
  210291. && eStmt!=FTS5_STMT_LOOKUP_DOCSIZE
  210292. ));
  210293. assert( eStmt>=0 && eStmt<ArraySize(p->aStmt) );
  210294. if( p->aStmt[eStmt]==0 ){
  210295. const char *azStmt[] = {
  210296. "SELECT %s FROM %s T WHERE T.%Q >= ? AND T.%Q <= ? ORDER BY T.%Q ASC",
  210297. "SELECT %s FROM %s T WHERE T.%Q <= ? AND T.%Q >= ? ORDER BY T.%Q DESC",
  210298. "SELECT %s FROM %s T WHERE T.%Q=?", /* LOOKUP */
  210299. "INSERT INTO %Q.'%q_content' VALUES(%s)", /* INSERT_CONTENT */
  210300. "REPLACE INTO %Q.'%q_content' VALUES(%s)", /* REPLACE_CONTENT */
  210301. "DELETE FROM %Q.'%q_content' WHERE id=?", /* DELETE_CONTENT */
  210302. "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)", /* REPLACE_DOCSIZE */
  210303. "DELETE FROM %Q.'%q_docsize' WHERE id=?", /* DELETE_DOCSIZE */
  210304. "SELECT sz FROM %Q.'%q_docsize' WHERE id=?", /* LOOKUP_DOCSIZE */
  210305. "REPLACE INTO %Q.'%q_config' VALUES(?,?)", /* REPLACE_CONFIG */
  210306. "SELECT %s FROM %s AS T", /* SCAN */
  210307. };
  210308. Fts5Config *pC = p->pConfig;
  210309. char *zSql = 0;
  210310. switch( eStmt ){
  210311. case FTS5_STMT_SCAN:
  210312. zSql = sqlite3_mprintf(azStmt[eStmt],
  210313. pC->zContentExprlist, pC->zContent
  210314. );
  210315. break;
  210316. case FTS5_STMT_SCAN_ASC:
  210317. case FTS5_STMT_SCAN_DESC:
  210318. zSql = sqlite3_mprintf(azStmt[eStmt], pC->zContentExprlist,
  210319. pC->zContent, pC->zContentRowid, pC->zContentRowid,
  210320. pC->zContentRowid
  210321. );
  210322. break;
  210323. case FTS5_STMT_LOOKUP:
  210324. zSql = sqlite3_mprintf(azStmt[eStmt],
  210325. pC->zContentExprlist, pC->zContent, pC->zContentRowid
  210326. );
  210327. break;
  210328. case FTS5_STMT_INSERT_CONTENT:
  210329. case FTS5_STMT_REPLACE_CONTENT: {
  210330. int nCol = pC->nCol + 1;
  210331. char *zBind;
  210332. int i;
  210333. zBind = sqlite3_malloc64(1 + nCol*2);
  210334. if( zBind ){
  210335. for(i=0; i<nCol; i++){
  210336. zBind[i*2] = '?';
  210337. zBind[i*2 + 1] = ',';
  210338. }
  210339. zBind[i*2-1] = '\0';
  210340. zSql = sqlite3_mprintf(azStmt[eStmt], pC->zDb, pC->zName, zBind);
  210341. sqlite3_free(zBind);
  210342. }
  210343. break;
  210344. }
  210345. default:
  210346. zSql = sqlite3_mprintf(azStmt[eStmt], pC->zDb, pC->zName);
  210347. break;
  210348. }
  210349. if( zSql==0 ){
  210350. rc = SQLITE_NOMEM;
  210351. }else{
  210352. int f = SQLITE_PREPARE_PERSISTENT;
  210353. if( eStmt>FTS5_STMT_LOOKUP ) f |= SQLITE_PREPARE_NO_VTAB;
  210354. p->pConfig->bLock++;
  210355. rc = sqlite3_prepare_v3(pC->db, zSql, -1, f, &p->aStmt[eStmt], 0);
  210356. p->pConfig->bLock--;
  210357. sqlite3_free(zSql);
  210358. if( rc!=SQLITE_OK && pzErrMsg ){
  210359. *pzErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(pC->db));
  210360. }
  210361. }
  210362. }
  210363. *ppStmt = p->aStmt[eStmt];
  210364. sqlite3_reset(*ppStmt);
  210365. return rc;
  210366. }
  210367. static int fts5ExecPrintf(
  210368. sqlite3 *db,
  210369. char **pzErr,
  210370. const char *zFormat,
  210371. ...
  210372. ){
  210373. int rc;
  210374. va_list ap; /* ... printf arguments */
  210375. char *zSql;
  210376. va_start(ap, zFormat);
  210377. zSql = sqlite3_vmprintf(zFormat, ap);
  210378. if( zSql==0 ){
  210379. rc = SQLITE_NOMEM;
  210380. }else{
  210381. rc = sqlite3_exec(db, zSql, 0, 0, pzErr);
  210382. sqlite3_free(zSql);
  210383. }
  210384. va_end(ap);
  210385. return rc;
  210386. }
  210387. /*
  210388. ** Drop all shadow tables. Return SQLITE_OK if successful or an SQLite error
  210389. ** code otherwise.
  210390. */
  210391. static int sqlite3Fts5DropAll(Fts5Config *pConfig){
  210392. int rc = fts5ExecPrintf(pConfig->db, 0,
  210393. "DROP TABLE IF EXISTS %Q.'%q_data';"
  210394. "DROP TABLE IF EXISTS %Q.'%q_idx';"
  210395. "DROP TABLE IF EXISTS %Q.'%q_config';",
  210396. pConfig->zDb, pConfig->zName,
  210397. pConfig->zDb, pConfig->zName,
  210398. pConfig->zDb, pConfig->zName
  210399. );
  210400. if( rc==SQLITE_OK && pConfig->bColumnsize ){
  210401. rc = fts5ExecPrintf(pConfig->db, 0,
  210402. "DROP TABLE IF EXISTS %Q.'%q_docsize';",
  210403. pConfig->zDb, pConfig->zName
  210404. );
  210405. }
  210406. if( rc==SQLITE_OK && pConfig->eContent==FTS5_CONTENT_NORMAL ){
  210407. rc = fts5ExecPrintf(pConfig->db, 0,
  210408. "DROP TABLE IF EXISTS %Q.'%q_content';",
  210409. pConfig->zDb, pConfig->zName
  210410. );
  210411. }
  210412. return rc;
  210413. }
  210414. static void fts5StorageRenameOne(
  210415. Fts5Config *pConfig, /* Current FTS5 configuration */
  210416. int *pRc, /* IN/OUT: Error code */
  210417. const char *zTail, /* Tail of table name e.g. "data", "config" */
  210418. const char *zName /* New name of FTS5 table */
  210419. ){
  210420. if( *pRc==SQLITE_OK ){
  210421. *pRc = fts5ExecPrintf(pConfig->db, 0,
  210422. "ALTER TABLE %Q.'%q_%s' RENAME TO '%q_%s';",
  210423. pConfig->zDb, pConfig->zName, zTail, zName, zTail
  210424. );
  210425. }
  210426. }
  210427. static int sqlite3Fts5StorageRename(Fts5Storage *pStorage, const char *zName){
  210428. Fts5Config *pConfig = pStorage->pConfig;
  210429. int rc = sqlite3Fts5StorageSync(pStorage);
  210430. fts5StorageRenameOne(pConfig, &rc, "data", zName);
  210431. fts5StorageRenameOne(pConfig, &rc, "idx", zName);
  210432. fts5StorageRenameOne(pConfig, &rc, "config", zName);
  210433. if( pConfig->bColumnsize ){
  210434. fts5StorageRenameOne(pConfig, &rc, "docsize", zName);
  210435. }
  210436. if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
  210437. fts5StorageRenameOne(pConfig, &rc, "content", zName);
  210438. }
  210439. return rc;
  210440. }
  210441. /*
  210442. ** Create the shadow table named zPost, with definition zDefn. Return
  210443. ** SQLITE_OK if successful, or an SQLite error code otherwise.
  210444. */
  210445. static int sqlite3Fts5CreateTable(
  210446. Fts5Config *pConfig, /* FTS5 configuration */
  210447. const char *zPost, /* Shadow table to create (e.g. "content") */
  210448. const char *zDefn, /* Columns etc. for shadow table */
  210449. int bWithout, /* True for without rowid */
  210450. char **pzErr /* OUT: Error message */
  210451. ){
  210452. int rc;
  210453. char *zErr = 0;
  210454. rc = fts5ExecPrintf(pConfig->db, &zErr, "CREATE TABLE %Q.'%q_%q'(%s)%s",
  210455. pConfig->zDb, pConfig->zName, zPost, zDefn,
  210456. #ifndef SQLITE_FTS5_NO_WITHOUT_ROWID
  210457. bWithout?" WITHOUT ROWID":
  210458. #endif
  210459. ""
  210460. );
  210461. if( zErr ){
  210462. *pzErr = sqlite3_mprintf(
  210463. "fts5: error creating shadow table %q_%s: %s",
  210464. pConfig->zName, zPost, zErr
  210465. );
  210466. sqlite3_free(zErr);
  210467. }
  210468. return rc;
  210469. }
  210470. /*
  210471. ** Open a new Fts5Index handle. If the bCreate argument is true, create
  210472. ** and initialize the underlying tables
  210473. **
  210474. ** If successful, set *pp to point to the new object and return SQLITE_OK.
  210475. ** Otherwise, set *pp to NULL and return an SQLite error code.
  210476. */
  210477. static int sqlite3Fts5StorageOpen(
  210478. Fts5Config *pConfig,
  210479. Fts5Index *pIndex,
  210480. int bCreate,
  210481. Fts5Storage **pp,
  210482. char **pzErr /* OUT: Error message */
  210483. ){
  210484. int rc = SQLITE_OK;
  210485. Fts5Storage *p; /* New object */
  210486. sqlite3_int64 nByte; /* Bytes of space to allocate */
  210487. nByte = sizeof(Fts5Storage) /* Fts5Storage object */
  210488. + pConfig->nCol * sizeof(i64); /* Fts5Storage.aTotalSize[] */
  210489. *pp = p = (Fts5Storage*)sqlite3_malloc64(nByte);
  210490. if( !p ) return SQLITE_NOMEM;
  210491. memset(p, 0, (size_t)nByte);
  210492. p->aTotalSize = (i64*)&p[1];
  210493. p->pConfig = pConfig;
  210494. p->pIndex = pIndex;
  210495. if( bCreate ){
  210496. if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
  210497. int nDefn = 32 + pConfig->nCol*10;
  210498. char *zDefn = sqlite3_malloc64(32 + (sqlite3_int64)pConfig->nCol * 10);
  210499. if( zDefn==0 ){
  210500. rc = SQLITE_NOMEM;
  210501. }else{
  210502. int i;
  210503. int iOff;
  210504. sqlite3_snprintf(nDefn, zDefn, "id INTEGER PRIMARY KEY");
  210505. iOff = (int)strlen(zDefn);
  210506. for(i=0; i<pConfig->nCol; i++){
  210507. sqlite3_snprintf(nDefn-iOff, &zDefn[iOff], ", c%d", i);
  210508. iOff += (int)strlen(&zDefn[iOff]);
  210509. }
  210510. rc = sqlite3Fts5CreateTable(pConfig, "content", zDefn, 0, pzErr);
  210511. }
  210512. sqlite3_free(zDefn);
  210513. }
  210514. if( rc==SQLITE_OK && pConfig->bColumnsize ){
  210515. rc = sqlite3Fts5CreateTable(
  210516. pConfig, "docsize", "id INTEGER PRIMARY KEY, sz BLOB", 0, pzErr
  210517. );
  210518. }
  210519. if( rc==SQLITE_OK ){
  210520. rc = sqlite3Fts5CreateTable(
  210521. pConfig, "config", "k PRIMARY KEY, v", 1, pzErr
  210522. );
  210523. }
  210524. if( rc==SQLITE_OK ){
  210525. rc = sqlite3Fts5StorageConfigValue(p, "version", 0, FTS5_CURRENT_VERSION);
  210526. }
  210527. }
  210528. if( rc ){
  210529. sqlite3Fts5StorageClose(p);
  210530. *pp = 0;
  210531. }
  210532. return rc;
  210533. }
  210534. /*
  210535. ** Close a handle opened by an earlier call to sqlite3Fts5StorageOpen().
  210536. */
  210537. static int sqlite3Fts5StorageClose(Fts5Storage *p){
  210538. int rc = SQLITE_OK;
  210539. if( p ){
  210540. int i;
  210541. /* Finalize all SQL statements */
  210542. for(i=0; i<ArraySize(p->aStmt); i++){
  210543. sqlite3_finalize(p->aStmt[i]);
  210544. }
  210545. sqlite3_free(p);
  210546. }
  210547. return rc;
  210548. }
  210549. typedef struct Fts5InsertCtx Fts5InsertCtx;
  210550. struct Fts5InsertCtx {
  210551. Fts5Storage *pStorage;
  210552. int iCol;
  210553. int szCol; /* Size of column value in tokens */
  210554. };
  210555. /*
  210556. ** Tokenization callback used when inserting tokens into the FTS index.
  210557. */
  210558. static int fts5StorageInsertCallback(
  210559. void *pContext, /* Pointer to Fts5InsertCtx object */
  210560. int tflags,
  210561. const char *pToken, /* Buffer containing token */
  210562. int nToken, /* Size of token in bytes */
  210563. int iUnused1, /* Start offset of token */
  210564. int iUnused2 /* End offset of token */
  210565. ){
  210566. Fts5InsertCtx *pCtx = (Fts5InsertCtx*)pContext;
  210567. Fts5Index *pIdx = pCtx->pStorage->pIndex;
  210568. UNUSED_PARAM2(iUnused1, iUnused2);
  210569. if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;
  210570. if( (tflags & FTS5_TOKEN_COLOCATED)==0 || pCtx->szCol==0 ){
  210571. pCtx->szCol++;
  210572. }
  210573. return sqlite3Fts5IndexWrite(pIdx, pCtx->iCol, pCtx->szCol-1, pToken, nToken);
  210574. }
  210575. /*
  210576. ** If a row with rowid iDel is present in the %_content table, add the
  210577. ** delete-markers to the FTS index necessary to delete it. Do not actually
  210578. ** remove the %_content row at this time though.
  210579. */
  210580. static int fts5StorageDeleteFromIndex(
  210581. Fts5Storage *p,
  210582. i64 iDel,
  210583. sqlite3_value **apVal
  210584. ){
  210585. Fts5Config *pConfig = p->pConfig;
  210586. sqlite3_stmt *pSeek = 0; /* SELECT to read row iDel from %_data */
  210587. int rc; /* Return code */
  210588. int rc2; /* sqlite3_reset() return code */
  210589. int iCol;
  210590. Fts5InsertCtx ctx;
  210591. if( apVal==0 ){
  210592. rc = fts5StorageGetStmt(p, FTS5_STMT_LOOKUP, &pSeek, 0);
  210593. if( rc!=SQLITE_OK ) return rc;
  210594. sqlite3_bind_int64(pSeek, 1, iDel);
  210595. if( sqlite3_step(pSeek)!=SQLITE_ROW ){
  210596. return sqlite3_reset(pSeek);
  210597. }
  210598. }
  210599. ctx.pStorage = p;
  210600. ctx.iCol = -1;
  210601. rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 1, iDel);
  210602. for(iCol=1; rc==SQLITE_OK && iCol<=pConfig->nCol; iCol++){
  210603. if( pConfig->abUnindexed[iCol-1]==0 ){
  210604. const char *zText;
  210605. int nText;
  210606. if( pSeek ){
  210607. zText = (const char*)sqlite3_column_text(pSeek, iCol);
  210608. nText = sqlite3_column_bytes(pSeek, iCol);
  210609. }else{
  210610. zText = (const char*)sqlite3_value_text(apVal[iCol-1]);
  210611. nText = sqlite3_value_bytes(apVal[iCol-1]);
  210612. }
  210613. ctx.szCol = 0;
  210614. rc = sqlite3Fts5Tokenize(pConfig, FTS5_TOKENIZE_DOCUMENT,
  210615. zText, nText, (void*)&ctx, fts5StorageInsertCallback
  210616. );
  210617. p->aTotalSize[iCol-1] -= (i64)ctx.szCol;
  210618. }
  210619. }
  210620. p->nTotalRow--;
  210621. rc2 = sqlite3_reset(pSeek);
  210622. if( rc==SQLITE_OK ) rc = rc2;
  210623. return rc;
  210624. }
  210625. /*
  210626. ** Insert a record into the %_docsize table. Specifically, do:
  210627. **
  210628. ** INSERT OR REPLACE INTO %_docsize(id, sz) VALUES(iRowid, pBuf);
  210629. **
  210630. ** If there is no %_docsize table (as happens if the columnsize=0 option
  210631. ** is specified when the FTS5 table is created), this function is a no-op.
  210632. */
  210633. static int fts5StorageInsertDocsize(
  210634. Fts5Storage *p, /* Storage module to write to */
  210635. i64 iRowid, /* id value */
  210636. Fts5Buffer *pBuf /* sz value */
  210637. ){
  210638. int rc = SQLITE_OK;
  210639. if( p->pConfig->bColumnsize ){
  210640. sqlite3_stmt *pReplace = 0;
  210641. rc = fts5StorageGetStmt(p, FTS5_STMT_REPLACE_DOCSIZE, &pReplace, 0);
  210642. if( rc==SQLITE_OK ){
  210643. sqlite3_bind_int64(pReplace, 1, iRowid);
  210644. sqlite3_bind_blob(pReplace, 2, pBuf->p, pBuf->n, SQLITE_STATIC);
  210645. sqlite3_step(pReplace);
  210646. rc = sqlite3_reset(pReplace);
  210647. sqlite3_bind_null(pReplace, 2);
  210648. }
  210649. }
  210650. return rc;
  210651. }
  210652. /*
  210653. ** Load the contents of the "averages" record from disk into the
  210654. ** p->nTotalRow and p->aTotalSize[] variables. If successful, and if
  210655. ** argument bCache is true, set the p->bTotalsValid flag to indicate
  210656. ** that the contents of aTotalSize[] and nTotalRow are valid until
  210657. ** further notice.
  210658. **
  210659. ** Return SQLITE_OK if successful, or an SQLite error code if an error
  210660. ** occurs.
  210661. */
  210662. static int fts5StorageLoadTotals(Fts5Storage *p, int bCache){
  210663. int rc = SQLITE_OK;
  210664. if( p->bTotalsValid==0 ){
  210665. rc = sqlite3Fts5IndexGetAverages(p->pIndex, &p->nTotalRow, p->aTotalSize);
  210666. p->bTotalsValid = bCache;
  210667. }
  210668. return rc;
  210669. }
  210670. /*
  210671. ** Store the current contents of the p->nTotalRow and p->aTotalSize[]
  210672. ** variables in the "averages" record on disk.
  210673. **
  210674. ** Return SQLITE_OK if successful, or an SQLite error code if an error
  210675. ** occurs.
  210676. */
  210677. static int fts5StorageSaveTotals(Fts5Storage *p){
  210678. int nCol = p->pConfig->nCol;
  210679. int i;
  210680. Fts5Buffer buf;
  210681. int rc = SQLITE_OK;
  210682. memset(&buf, 0, sizeof(buf));
  210683. sqlite3Fts5BufferAppendVarint(&rc, &buf, p->nTotalRow);
  210684. for(i=0; i<nCol; i++){
  210685. sqlite3Fts5BufferAppendVarint(&rc, &buf, p->aTotalSize[i]);
  210686. }
  210687. if( rc==SQLITE_OK ){
  210688. rc = sqlite3Fts5IndexSetAverages(p->pIndex, buf.p, buf.n);
  210689. }
  210690. sqlite3_free(buf.p);
  210691. return rc;
  210692. }
  210693. /*
  210694. ** Remove a row from the FTS table.
  210695. */
  210696. static int sqlite3Fts5StorageDelete(Fts5Storage *p, i64 iDel, sqlite3_value **apVal){
  210697. Fts5Config *pConfig = p->pConfig;
  210698. int rc;
  210699. sqlite3_stmt *pDel = 0;
  210700. assert( pConfig->eContent!=FTS5_CONTENT_NORMAL || apVal==0 );
  210701. rc = fts5StorageLoadTotals(p, 1);
  210702. /* Delete the index records */
  210703. if( rc==SQLITE_OK ){
  210704. rc = fts5StorageDeleteFromIndex(p, iDel, apVal);
  210705. }
  210706. /* Delete the %_docsize record */
  210707. if( rc==SQLITE_OK && pConfig->bColumnsize ){
  210708. rc = fts5StorageGetStmt(p, FTS5_STMT_DELETE_DOCSIZE, &pDel, 0);
  210709. if( rc==SQLITE_OK ){
  210710. sqlite3_bind_int64(pDel, 1, iDel);
  210711. sqlite3_step(pDel);
  210712. rc = sqlite3_reset(pDel);
  210713. }
  210714. }
  210715. /* Delete the %_content record */
  210716. if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
  210717. if( rc==SQLITE_OK ){
  210718. rc = fts5StorageGetStmt(p, FTS5_STMT_DELETE_CONTENT, &pDel, 0);
  210719. }
  210720. if( rc==SQLITE_OK ){
  210721. sqlite3_bind_int64(pDel, 1, iDel);
  210722. sqlite3_step(pDel);
  210723. rc = sqlite3_reset(pDel);
  210724. }
  210725. }
  210726. return rc;
  210727. }
  210728. /*
  210729. ** Delete all entries in the FTS5 index.
  210730. */
  210731. static int sqlite3Fts5StorageDeleteAll(Fts5Storage *p){
  210732. Fts5Config *pConfig = p->pConfig;
  210733. int rc;
  210734. p->bTotalsValid = 0;
  210735. /* Delete the contents of the %_data and %_docsize tables. */
  210736. rc = fts5ExecPrintf(pConfig->db, 0,
  210737. "DELETE FROM %Q.'%q_data';"
  210738. "DELETE FROM %Q.'%q_idx';",
  210739. pConfig->zDb, pConfig->zName,
  210740. pConfig->zDb, pConfig->zName
  210741. );
  210742. if( rc==SQLITE_OK && pConfig->bColumnsize ){
  210743. rc = fts5ExecPrintf(pConfig->db, 0,
  210744. "DELETE FROM %Q.'%q_docsize';",
  210745. pConfig->zDb, pConfig->zName
  210746. );
  210747. }
  210748. /* Reinitialize the %_data table. This call creates the initial structure
  210749. ** and averages records. */
  210750. if( rc==SQLITE_OK ){
  210751. rc = sqlite3Fts5IndexReinit(p->pIndex);
  210752. }
  210753. if( rc==SQLITE_OK ){
  210754. rc = sqlite3Fts5StorageConfigValue(p, "version", 0, FTS5_CURRENT_VERSION);
  210755. }
  210756. return rc;
  210757. }
  210758. static int sqlite3Fts5StorageRebuild(Fts5Storage *p){
  210759. Fts5Buffer buf = {0,0,0};
  210760. Fts5Config *pConfig = p->pConfig;
  210761. sqlite3_stmt *pScan = 0;
  210762. Fts5InsertCtx ctx;
  210763. int rc, rc2;
  210764. memset(&ctx, 0, sizeof(Fts5InsertCtx));
  210765. ctx.pStorage = p;
  210766. rc = sqlite3Fts5StorageDeleteAll(p);
  210767. if( rc==SQLITE_OK ){
  210768. rc = fts5StorageLoadTotals(p, 1);
  210769. }
  210770. if( rc==SQLITE_OK ){
  210771. rc = fts5StorageGetStmt(p, FTS5_STMT_SCAN, &pScan, 0);
  210772. }
  210773. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pScan) ){
  210774. i64 iRowid = sqlite3_column_int64(pScan, 0);
  210775. sqlite3Fts5BufferZero(&buf);
  210776. rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 0, iRowid);
  210777. for(ctx.iCol=0; rc==SQLITE_OK && ctx.iCol<pConfig->nCol; ctx.iCol++){
  210778. ctx.szCol = 0;
  210779. if( pConfig->abUnindexed[ctx.iCol]==0 ){
  210780. const char *zText = (const char*)sqlite3_column_text(pScan, ctx.iCol+1);
  210781. int nText = sqlite3_column_bytes(pScan, ctx.iCol+1);
  210782. rc = sqlite3Fts5Tokenize(pConfig,
  210783. FTS5_TOKENIZE_DOCUMENT,
  210784. zText, nText,
  210785. (void*)&ctx,
  210786. fts5StorageInsertCallback
  210787. );
  210788. }
  210789. sqlite3Fts5BufferAppendVarint(&rc, &buf, ctx.szCol);
  210790. p->aTotalSize[ctx.iCol] += (i64)ctx.szCol;
  210791. }
  210792. p->nTotalRow++;
  210793. if( rc==SQLITE_OK ){
  210794. rc = fts5StorageInsertDocsize(p, iRowid, &buf);
  210795. }
  210796. }
  210797. sqlite3_free(buf.p);
  210798. rc2 = sqlite3_reset(pScan);
  210799. if( rc==SQLITE_OK ) rc = rc2;
  210800. /* Write the averages record */
  210801. if( rc==SQLITE_OK ){
  210802. rc = fts5StorageSaveTotals(p);
  210803. }
  210804. return rc;
  210805. }
  210806. static int sqlite3Fts5StorageOptimize(Fts5Storage *p){
  210807. return sqlite3Fts5IndexOptimize(p->pIndex);
  210808. }
  210809. static int sqlite3Fts5StorageMerge(Fts5Storage *p, int nMerge){
  210810. return sqlite3Fts5IndexMerge(p->pIndex, nMerge);
  210811. }
  210812. static int sqlite3Fts5StorageReset(Fts5Storage *p){
  210813. return sqlite3Fts5IndexReset(p->pIndex);
  210814. }
  210815. /*
  210816. ** Allocate a new rowid. This is used for "external content" tables when
  210817. ** a NULL value is inserted into the rowid column. The new rowid is allocated
  210818. ** by inserting a dummy row into the %_docsize table. The dummy will be
  210819. ** overwritten later.
  210820. **
  210821. ** If the %_docsize table does not exist, SQLITE_MISMATCH is returned. In
  210822. ** this case the user is required to provide a rowid explicitly.
  210823. */
  210824. static int fts5StorageNewRowid(Fts5Storage *p, i64 *piRowid){
  210825. int rc = SQLITE_MISMATCH;
  210826. if( p->pConfig->bColumnsize ){
  210827. sqlite3_stmt *pReplace = 0;
  210828. rc = fts5StorageGetStmt(p, FTS5_STMT_REPLACE_DOCSIZE, &pReplace, 0);
  210829. if( rc==SQLITE_OK ){
  210830. sqlite3_bind_null(pReplace, 1);
  210831. sqlite3_bind_null(pReplace, 2);
  210832. sqlite3_step(pReplace);
  210833. rc = sqlite3_reset(pReplace);
  210834. }
  210835. if( rc==SQLITE_OK ){
  210836. *piRowid = sqlite3_last_insert_rowid(p->pConfig->db);
  210837. }
  210838. }
  210839. return rc;
  210840. }
  210841. /*
  210842. ** Insert a new row into the FTS content table.
  210843. */
  210844. static int sqlite3Fts5StorageContentInsert(
  210845. Fts5Storage *p,
  210846. sqlite3_value **apVal,
  210847. i64 *piRowid
  210848. ){
  210849. Fts5Config *pConfig = p->pConfig;
  210850. int rc = SQLITE_OK;
  210851. /* Insert the new row into the %_content table. */
  210852. if( pConfig->eContent!=FTS5_CONTENT_NORMAL ){
  210853. if( sqlite3_value_type(apVal[1])==SQLITE_INTEGER ){
  210854. *piRowid = sqlite3_value_int64(apVal[1]);
  210855. }else{
  210856. rc = fts5StorageNewRowid(p, piRowid);
  210857. }
  210858. }else{
  210859. sqlite3_stmt *pInsert = 0; /* Statement to write %_content table */
  210860. int i; /* Counter variable */
  210861. rc = fts5StorageGetStmt(p, FTS5_STMT_INSERT_CONTENT, &pInsert, 0);
  210862. for(i=1; rc==SQLITE_OK && i<=pConfig->nCol+1; i++){
  210863. rc = sqlite3_bind_value(pInsert, i, apVal[i]);
  210864. }
  210865. if( rc==SQLITE_OK ){
  210866. sqlite3_step(pInsert);
  210867. rc = sqlite3_reset(pInsert);
  210868. }
  210869. *piRowid = sqlite3_last_insert_rowid(pConfig->db);
  210870. }
  210871. return rc;
  210872. }
  210873. /*
  210874. ** Insert new entries into the FTS index and %_docsize table.
  210875. */
  210876. static int sqlite3Fts5StorageIndexInsert(
  210877. Fts5Storage *p,
  210878. sqlite3_value **apVal,
  210879. i64 iRowid
  210880. ){
  210881. Fts5Config *pConfig = p->pConfig;
  210882. int rc = SQLITE_OK; /* Return code */
  210883. Fts5InsertCtx ctx; /* Tokenization callback context object */
  210884. Fts5Buffer buf; /* Buffer used to build up %_docsize blob */
  210885. memset(&buf, 0, sizeof(Fts5Buffer));
  210886. ctx.pStorage = p;
  210887. rc = fts5StorageLoadTotals(p, 1);
  210888. if( rc==SQLITE_OK ){
  210889. rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 0, iRowid);
  210890. }
  210891. for(ctx.iCol=0; rc==SQLITE_OK && ctx.iCol<pConfig->nCol; ctx.iCol++){
  210892. ctx.szCol = 0;
  210893. if( pConfig->abUnindexed[ctx.iCol]==0 ){
  210894. const char *zText = (const char*)sqlite3_value_text(apVal[ctx.iCol+2]);
  210895. int nText = sqlite3_value_bytes(apVal[ctx.iCol+2]);
  210896. rc = sqlite3Fts5Tokenize(pConfig,
  210897. FTS5_TOKENIZE_DOCUMENT,
  210898. zText, nText,
  210899. (void*)&ctx,
  210900. fts5StorageInsertCallback
  210901. );
  210902. }
  210903. sqlite3Fts5BufferAppendVarint(&rc, &buf, ctx.szCol);
  210904. p->aTotalSize[ctx.iCol] += (i64)ctx.szCol;
  210905. }
  210906. p->nTotalRow++;
  210907. /* Write the %_docsize record */
  210908. if( rc==SQLITE_OK ){
  210909. rc = fts5StorageInsertDocsize(p, iRowid, &buf);
  210910. }
  210911. sqlite3_free(buf.p);
  210912. return rc;
  210913. }
  210914. static int fts5StorageCount(Fts5Storage *p, const char *zSuffix, i64 *pnRow){
  210915. Fts5Config *pConfig = p->pConfig;
  210916. char *zSql;
  210917. int rc;
  210918. zSql = sqlite3_mprintf("SELECT count(*) FROM %Q.'%q_%s'",
  210919. pConfig->zDb, pConfig->zName, zSuffix
  210920. );
  210921. if( zSql==0 ){
  210922. rc = SQLITE_NOMEM;
  210923. }else{
  210924. sqlite3_stmt *pCnt = 0;
  210925. rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &pCnt, 0);
  210926. if( rc==SQLITE_OK ){
  210927. if( SQLITE_ROW==sqlite3_step(pCnt) ){
  210928. *pnRow = sqlite3_column_int64(pCnt, 0);
  210929. }
  210930. rc = sqlite3_finalize(pCnt);
  210931. }
  210932. }
  210933. sqlite3_free(zSql);
  210934. return rc;
  210935. }
  210936. /*
  210937. ** Context object used by sqlite3Fts5StorageIntegrity().
  210938. */
  210939. typedef struct Fts5IntegrityCtx Fts5IntegrityCtx;
  210940. struct Fts5IntegrityCtx {
  210941. i64 iRowid;
  210942. int iCol;
  210943. int szCol;
  210944. u64 cksum;
  210945. Fts5Termset *pTermset;
  210946. Fts5Config *pConfig;
  210947. };
  210948. /*
  210949. ** Tokenization callback used by integrity check.
  210950. */
  210951. static int fts5StorageIntegrityCallback(
  210952. void *pContext, /* Pointer to Fts5IntegrityCtx object */
  210953. int tflags,
  210954. const char *pToken, /* Buffer containing token */
  210955. int nToken, /* Size of token in bytes */
  210956. int iUnused1, /* Start offset of token */
  210957. int iUnused2 /* End offset of token */
  210958. ){
  210959. Fts5IntegrityCtx *pCtx = (Fts5IntegrityCtx*)pContext;
  210960. Fts5Termset *pTermset = pCtx->pTermset;
  210961. int bPresent;
  210962. int ii;
  210963. int rc = SQLITE_OK;
  210964. int iPos;
  210965. int iCol;
  210966. UNUSED_PARAM2(iUnused1, iUnused2);
  210967. if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;
  210968. if( (tflags & FTS5_TOKEN_COLOCATED)==0 || pCtx->szCol==0 ){
  210969. pCtx->szCol++;
  210970. }
  210971. switch( pCtx->pConfig->eDetail ){
  210972. case FTS5_DETAIL_FULL:
  210973. iPos = pCtx->szCol-1;
  210974. iCol = pCtx->iCol;
  210975. break;
  210976. case FTS5_DETAIL_COLUMNS:
  210977. iPos = pCtx->iCol;
  210978. iCol = 0;
  210979. break;
  210980. default:
  210981. assert( pCtx->pConfig->eDetail==FTS5_DETAIL_NONE );
  210982. iPos = 0;
  210983. iCol = 0;
  210984. break;
  210985. }
  210986. rc = sqlite3Fts5TermsetAdd(pTermset, 0, pToken, nToken, &bPresent);
  210987. if( rc==SQLITE_OK && bPresent==0 ){
  210988. pCtx->cksum ^= sqlite3Fts5IndexEntryCksum(
  210989. pCtx->iRowid, iCol, iPos, 0, pToken, nToken
  210990. );
  210991. }
  210992. for(ii=0; rc==SQLITE_OK && ii<pCtx->pConfig->nPrefix; ii++){
  210993. const int nChar = pCtx->pConfig->aPrefix[ii];
  210994. int nByte = sqlite3Fts5IndexCharlenToBytelen(pToken, nToken, nChar);
  210995. if( nByte ){
  210996. rc = sqlite3Fts5TermsetAdd(pTermset, ii+1, pToken, nByte, &bPresent);
  210997. if( bPresent==0 ){
  210998. pCtx->cksum ^= sqlite3Fts5IndexEntryCksum(
  210999. pCtx->iRowid, iCol, iPos, ii+1, pToken, nByte
  211000. );
  211001. }
  211002. }
  211003. }
  211004. return rc;
  211005. }
  211006. /*
  211007. ** Check that the contents of the FTS index match that of the %_content
  211008. ** table. Return SQLITE_OK if they do, or SQLITE_CORRUPT if not. Return
  211009. ** some other SQLite error code if an error occurs while attempting to
  211010. ** determine this.
  211011. */
  211012. static int sqlite3Fts5StorageIntegrity(Fts5Storage *p){
  211013. Fts5Config *pConfig = p->pConfig;
  211014. int rc; /* Return code */
  211015. int *aColSize; /* Array of size pConfig->nCol */
  211016. i64 *aTotalSize; /* Array of size pConfig->nCol */
  211017. Fts5IntegrityCtx ctx;
  211018. sqlite3_stmt *pScan;
  211019. memset(&ctx, 0, sizeof(Fts5IntegrityCtx));
  211020. ctx.pConfig = p->pConfig;
  211021. aTotalSize = (i64*)sqlite3_malloc64(pConfig->nCol*(sizeof(int)+sizeof(i64)));
  211022. if( !aTotalSize ) return SQLITE_NOMEM;
  211023. aColSize = (int*)&aTotalSize[pConfig->nCol];
  211024. memset(aTotalSize, 0, sizeof(i64) * pConfig->nCol);
  211025. /* Generate the expected index checksum based on the contents of the
  211026. ** %_content table. This block stores the checksum in ctx.cksum. */
  211027. rc = fts5StorageGetStmt(p, FTS5_STMT_SCAN, &pScan, 0);
  211028. if( rc==SQLITE_OK ){
  211029. int rc2;
  211030. while( SQLITE_ROW==sqlite3_step(pScan) ){
  211031. int i;
  211032. ctx.iRowid = sqlite3_column_int64(pScan, 0);
  211033. ctx.szCol = 0;
  211034. if( pConfig->bColumnsize ){
  211035. rc = sqlite3Fts5StorageDocsize(p, ctx.iRowid, aColSize);
  211036. }
  211037. if( rc==SQLITE_OK && pConfig->eDetail==FTS5_DETAIL_NONE ){
  211038. rc = sqlite3Fts5TermsetNew(&ctx.pTermset);
  211039. }
  211040. for(i=0; rc==SQLITE_OK && i<pConfig->nCol; i++){
  211041. if( pConfig->abUnindexed[i] ) continue;
  211042. ctx.iCol = i;
  211043. ctx.szCol = 0;
  211044. if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
  211045. rc = sqlite3Fts5TermsetNew(&ctx.pTermset);
  211046. }
  211047. if( rc==SQLITE_OK ){
  211048. const char *zText = (const char*)sqlite3_column_text(pScan, i+1);
  211049. int nText = sqlite3_column_bytes(pScan, i+1);
  211050. rc = sqlite3Fts5Tokenize(pConfig,
  211051. FTS5_TOKENIZE_DOCUMENT,
  211052. zText, nText,
  211053. (void*)&ctx,
  211054. fts5StorageIntegrityCallback
  211055. );
  211056. }
  211057. if( rc==SQLITE_OK && pConfig->bColumnsize && ctx.szCol!=aColSize[i] ){
  211058. rc = FTS5_CORRUPT;
  211059. }
  211060. aTotalSize[i] += ctx.szCol;
  211061. if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
  211062. sqlite3Fts5TermsetFree(ctx.pTermset);
  211063. ctx.pTermset = 0;
  211064. }
  211065. }
  211066. sqlite3Fts5TermsetFree(ctx.pTermset);
  211067. ctx.pTermset = 0;
  211068. if( rc!=SQLITE_OK ) break;
  211069. }
  211070. rc2 = sqlite3_reset(pScan);
  211071. if( rc==SQLITE_OK ) rc = rc2;
  211072. }
  211073. /* Test that the "totals" (sometimes called "averages") record looks Ok */
  211074. if( rc==SQLITE_OK ){
  211075. int i;
  211076. rc = fts5StorageLoadTotals(p, 0);
  211077. for(i=0; rc==SQLITE_OK && i<pConfig->nCol; i++){
  211078. if( p->aTotalSize[i]!=aTotalSize[i] ) rc = FTS5_CORRUPT;
  211079. }
  211080. }
  211081. /* Check that the %_docsize and %_content tables contain the expected
  211082. ** number of rows. */
  211083. if( rc==SQLITE_OK && pConfig->eContent==FTS5_CONTENT_NORMAL ){
  211084. i64 nRow = 0;
  211085. rc = fts5StorageCount(p, "content", &nRow);
  211086. if( rc==SQLITE_OK && nRow!=p->nTotalRow ) rc = FTS5_CORRUPT;
  211087. }
  211088. if( rc==SQLITE_OK && pConfig->bColumnsize ){
  211089. i64 nRow = 0;
  211090. rc = fts5StorageCount(p, "docsize", &nRow);
  211091. if( rc==SQLITE_OK && nRow!=p->nTotalRow ) rc = FTS5_CORRUPT;
  211092. }
  211093. /* Pass the expected checksum down to the FTS index module. It will
  211094. ** verify, amongst other things, that it matches the checksum generated by
  211095. ** inspecting the index itself. */
  211096. if( rc==SQLITE_OK ){
  211097. rc = sqlite3Fts5IndexIntegrityCheck(p->pIndex, ctx.cksum);
  211098. }
  211099. sqlite3_free(aTotalSize);
  211100. return rc;
  211101. }
  211102. /*
  211103. ** Obtain an SQLite statement handle that may be used to read data from the
  211104. ** %_content table.
  211105. */
  211106. static int sqlite3Fts5StorageStmt(
  211107. Fts5Storage *p,
  211108. int eStmt,
  211109. sqlite3_stmt **pp,
  211110. char **pzErrMsg
  211111. ){
  211112. int rc;
  211113. assert( eStmt==FTS5_STMT_SCAN_ASC
  211114. || eStmt==FTS5_STMT_SCAN_DESC
  211115. || eStmt==FTS5_STMT_LOOKUP
  211116. );
  211117. rc = fts5StorageGetStmt(p, eStmt, pp, pzErrMsg);
  211118. if( rc==SQLITE_OK ){
  211119. assert( p->aStmt[eStmt]==*pp );
  211120. p->aStmt[eStmt] = 0;
  211121. }
  211122. return rc;
  211123. }
  211124. /*
  211125. ** Release an SQLite statement handle obtained via an earlier call to
  211126. ** sqlite3Fts5StorageStmt(). The eStmt parameter passed to this function
  211127. ** must match that passed to the sqlite3Fts5StorageStmt() call.
  211128. */
  211129. static void sqlite3Fts5StorageStmtRelease(
  211130. Fts5Storage *p,
  211131. int eStmt,
  211132. sqlite3_stmt *pStmt
  211133. ){
  211134. assert( eStmt==FTS5_STMT_SCAN_ASC
  211135. || eStmt==FTS5_STMT_SCAN_DESC
  211136. || eStmt==FTS5_STMT_LOOKUP
  211137. );
  211138. if( p->aStmt[eStmt]==0 ){
  211139. sqlite3_reset(pStmt);
  211140. p->aStmt[eStmt] = pStmt;
  211141. }else{
  211142. sqlite3_finalize(pStmt);
  211143. }
  211144. }
  211145. static int fts5StorageDecodeSizeArray(
  211146. int *aCol, int nCol, /* Array to populate */
  211147. const u8 *aBlob, int nBlob /* Record to read varints from */
  211148. ){
  211149. int i;
  211150. int iOff = 0;
  211151. for(i=0; i<nCol; i++){
  211152. if( iOff>=nBlob ) return 1;
  211153. iOff += fts5GetVarint32(&aBlob[iOff], aCol[i]);
  211154. }
  211155. return (iOff!=nBlob);
  211156. }
  211157. /*
  211158. ** Argument aCol points to an array of integers containing one entry for
  211159. ** each table column. This function reads the %_docsize record for the
  211160. ** specified rowid and populates aCol[] with the results.
  211161. **
  211162. ** An SQLite error code is returned if an error occurs, or SQLITE_OK
  211163. ** otherwise.
  211164. */
  211165. static int sqlite3Fts5StorageDocsize(Fts5Storage *p, i64 iRowid, int *aCol){
  211166. int nCol = p->pConfig->nCol; /* Number of user columns in table */
  211167. sqlite3_stmt *pLookup = 0; /* Statement to query %_docsize */
  211168. int rc; /* Return Code */
  211169. assert( p->pConfig->bColumnsize );
  211170. rc = fts5StorageGetStmt(p, FTS5_STMT_LOOKUP_DOCSIZE, &pLookup, 0);
  211171. if( rc==SQLITE_OK ){
  211172. int bCorrupt = 1;
  211173. sqlite3_bind_int64(pLookup, 1, iRowid);
  211174. if( SQLITE_ROW==sqlite3_step(pLookup) ){
  211175. const u8 *aBlob = sqlite3_column_blob(pLookup, 0);
  211176. int nBlob = sqlite3_column_bytes(pLookup, 0);
  211177. if( 0==fts5StorageDecodeSizeArray(aCol, nCol, aBlob, nBlob) ){
  211178. bCorrupt = 0;
  211179. }
  211180. }
  211181. rc = sqlite3_reset(pLookup);
  211182. if( bCorrupt && rc==SQLITE_OK ){
  211183. rc = FTS5_CORRUPT;
  211184. }
  211185. }
  211186. return rc;
  211187. }
  211188. static int sqlite3Fts5StorageSize(Fts5Storage *p, int iCol, i64 *pnToken){
  211189. int rc = fts5StorageLoadTotals(p, 0);
  211190. if( rc==SQLITE_OK ){
  211191. *pnToken = 0;
  211192. if( iCol<0 ){
  211193. int i;
  211194. for(i=0; i<p->pConfig->nCol; i++){
  211195. *pnToken += p->aTotalSize[i];
  211196. }
  211197. }else if( iCol<p->pConfig->nCol ){
  211198. *pnToken = p->aTotalSize[iCol];
  211199. }else{
  211200. rc = SQLITE_RANGE;
  211201. }
  211202. }
  211203. return rc;
  211204. }
  211205. static int sqlite3Fts5StorageRowCount(Fts5Storage *p, i64 *pnRow){
  211206. int rc = fts5StorageLoadTotals(p, 0);
  211207. if( rc==SQLITE_OK ){
  211208. /* nTotalRow being zero does not necessarily indicate a corrupt
  211209. ** database - it might be that the FTS5 table really does contain zero
  211210. ** rows. However this function is only called from the xRowCount() API,
  211211. ** and there is no way for that API to be invoked if the table contains
  211212. ** no rows. Hence the FTS5_CORRUPT return. */
  211213. *pnRow = p->nTotalRow;
  211214. if( p->nTotalRow<=0 ) rc = FTS5_CORRUPT;
  211215. }
  211216. return rc;
  211217. }
  211218. /*
  211219. ** Flush any data currently held in-memory to disk.
  211220. */
  211221. static int sqlite3Fts5StorageSync(Fts5Storage *p){
  211222. int rc = SQLITE_OK;
  211223. i64 iLastRowid = sqlite3_last_insert_rowid(p->pConfig->db);
  211224. if( p->bTotalsValid ){
  211225. rc = fts5StorageSaveTotals(p);
  211226. p->bTotalsValid = 0;
  211227. }
  211228. if( rc==SQLITE_OK ){
  211229. rc = sqlite3Fts5IndexSync(p->pIndex);
  211230. }
  211231. sqlite3_set_last_insert_rowid(p->pConfig->db, iLastRowid);
  211232. return rc;
  211233. }
  211234. static int sqlite3Fts5StorageRollback(Fts5Storage *p){
  211235. p->bTotalsValid = 0;
  211236. return sqlite3Fts5IndexRollback(p->pIndex);
  211237. }
  211238. static int sqlite3Fts5StorageConfigValue(
  211239. Fts5Storage *p,
  211240. const char *z,
  211241. sqlite3_value *pVal,
  211242. int iVal
  211243. ){
  211244. sqlite3_stmt *pReplace = 0;
  211245. int rc = fts5StorageGetStmt(p, FTS5_STMT_REPLACE_CONFIG, &pReplace, 0);
  211246. if( rc==SQLITE_OK ){
  211247. sqlite3_bind_text(pReplace, 1, z, -1, SQLITE_STATIC);
  211248. if( pVal ){
  211249. sqlite3_bind_value(pReplace, 2, pVal);
  211250. }else{
  211251. sqlite3_bind_int(pReplace, 2, iVal);
  211252. }
  211253. sqlite3_step(pReplace);
  211254. rc = sqlite3_reset(pReplace);
  211255. sqlite3_bind_null(pReplace, 1);
  211256. }
  211257. if( rc==SQLITE_OK && pVal ){
  211258. int iNew = p->pConfig->iCookie + 1;
  211259. rc = sqlite3Fts5IndexSetCookie(p->pIndex, iNew);
  211260. if( rc==SQLITE_OK ){
  211261. p->pConfig->iCookie = iNew;
  211262. }
  211263. }
  211264. return rc;
  211265. }
  211266. /*
  211267. ** 2014 May 31
  211268. **
  211269. ** The author disclaims copyright to this source code. In place of
  211270. ** a legal notice, here is a blessing:
  211271. **
  211272. ** May you do good and not evil.
  211273. ** May you find forgiveness for yourself and forgive others.
  211274. ** May you share freely, never taking more than you give.
  211275. **
  211276. ******************************************************************************
  211277. */
  211278. /* #include "fts5Int.h" */
  211279. /**************************************************************************
  211280. ** Start of ascii tokenizer implementation.
  211281. */
  211282. /*
  211283. ** For tokenizers with no "unicode" modifier, the set of token characters
  211284. ** is the same as the set of ASCII range alphanumeric characters.
  211285. */
  211286. static unsigned char aAsciiTokenChar[128] = {
  211287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x00..0x0F */
  211288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x10..0x1F */
  211289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x20..0x2F */
  211290. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 0x30..0x3F */
  211291. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x40..0x4F */
  211292. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 0x50..0x5F */
  211293. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x60..0x6F */
  211294. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 0x70..0x7F */
  211295. };
  211296. typedef struct AsciiTokenizer AsciiTokenizer;
  211297. struct AsciiTokenizer {
  211298. unsigned char aTokenChar[128];
  211299. };
  211300. static void fts5AsciiAddExceptions(
  211301. AsciiTokenizer *p,
  211302. const char *zArg,
  211303. int bTokenChars
  211304. ){
  211305. int i;
  211306. for(i=0; zArg[i]; i++){
  211307. if( (zArg[i] & 0x80)==0 ){
  211308. p->aTokenChar[(int)zArg[i]] = (unsigned char)bTokenChars;
  211309. }
  211310. }
  211311. }
  211312. /*
  211313. ** Delete a "ascii" tokenizer.
  211314. */
  211315. static void fts5AsciiDelete(Fts5Tokenizer *p){
  211316. sqlite3_free(p);
  211317. }
  211318. /*
  211319. ** Create an "ascii" tokenizer.
  211320. */
  211321. static int fts5AsciiCreate(
  211322. void *pUnused,
  211323. const char **azArg, int nArg,
  211324. Fts5Tokenizer **ppOut
  211325. ){
  211326. int rc = SQLITE_OK;
  211327. AsciiTokenizer *p = 0;
  211328. UNUSED_PARAM(pUnused);
  211329. if( nArg%2 ){
  211330. rc = SQLITE_ERROR;
  211331. }else{
  211332. p = sqlite3_malloc(sizeof(AsciiTokenizer));
  211333. if( p==0 ){
  211334. rc = SQLITE_NOMEM;
  211335. }else{
  211336. int i;
  211337. memset(p, 0, sizeof(AsciiTokenizer));
  211338. memcpy(p->aTokenChar, aAsciiTokenChar, sizeof(aAsciiTokenChar));
  211339. for(i=0; rc==SQLITE_OK && i<nArg; i+=2){
  211340. const char *zArg = azArg[i+1];
  211341. if( 0==sqlite3_stricmp(azArg[i], "tokenchars") ){
  211342. fts5AsciiAddExceptions(p, zArg, 1);
  211343. }else
  211344. if( 0==sqlite3_stricmp(azArg[i], "separators") ){
  211345. fts5AsciiAddExceptions(p, zArg, 0);
  211346. }else{
  211347. rc = SQLITE_ERROR;
  211348. }
  211349. }
  211350. if( rc!=SQLITE_OK ){
  211351. fts5AsciiDelete((Fts5Tokenizer*)p);
  211352. p = 0;
  211353. }
  211354. }
  211355. }
  211356. *ppOut = (Fts5Tokenizer*)p;
  211357. return rc;
  211358. }
  211359. static void asciiFold(char *aOut, const char *aIn, int nByte){
  211360. int i;
  211361. for(i=0; i<nByte; i++){
  211362. char c = aIn[i];
  211363. if( c>='A' && c<='Z' ) c += 32;
  211364. aOut[i] = c;
  211365. }
  211366. }
  211367. /*
  211368. ** Tokenize some text using the ascii tokenizer.
  211369. */
  211370. static int fts5AsciiTokenize(
  211371. Fts5Tokenizer *pTokenizer,
  211372. void *pCtx,
  211373. int iUnused,
  211374. const char *pText, int nText,
  211375. int (*xToken)(void*, int, const char*, int nToken, int iStart, int iEnd)
  211376. ){
  211377. AsciiTokenizer *p = (AsciiTokenizer*)pTokenizer;
  211378. int rc = SQLITE_OK;
  211379. int ie;
  211380. int is = 0;
  211381. char aFold[64];
  211382. int nFold = sizeof(aFold);
  211383. char *pFold = aFold;
  211384. unsigned char *a = p->aTokenChar;
  211385. UNUSED_PARAM(iUnused);
  211386. while( is<nText && rc==SQLITE_OK ){
  211387. int nByte;
  211388. /* Skip any leading divider characters. */
  211389. while( is<nText && ((pText[is]&0x80)==0 && a[(int)pText[is]]==0) ){
  211390. is++;
  211391. }
  211392. if( is==nText ) break;
  211393. /* Count the token characters */
  211394. ie = is+1;
  211395. while( ie<nText && ((pText[ie]&0x80) || a[(int)pText[ie]] ) ){
  211396. ie++;
  211397. }
  211398. /* Fold to lower case */
  211399. nByte = ie-is;
  211400. if( nByte>nFold ){
  211401. if( pFold!=aFold ) sqlite3_free(pFold);
  211402. pFold = sqlite3_malloc64((sqlite3_int64)nByte*2);
  211403. if( pFold==0 ){
  211404. rc = SQLITE_NOMEM;
  211405. break;
  211406. }
  211407. nFold = nByte*2;
  211408. }
  211409. asciiFold(pFold, &pText[is], nByte);
  211410. /* Invoke the token callback */
  211411. rc = xToken(pCtx, 0, pFold, nByte, is, ie);
  211412. is = ie+1;
  211413. }
  211414. if( pFold!=aFold ) sqlite3_free(pFold);
  211415. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  211416. return rc;
  211417. }
  211418. /**************************************************************************
  211419. ** Start of unicode61 tokenizer implementation.
  211420. */
  211421. /*
  211422. ** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied
  211423. ** from the sqlite3 source file utf.c. If this file is compiled as part
  211424. ** of the amalgamation, they are not required.
  211425. */
  211426. #ifndef SQLITE_AMALGAMATION
  211427. static const unsigned char sqlite3Utf8Trans1[] = {
  211428. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  211429. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  211430. 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
  211431. 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
  211432. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  211433. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  211434. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  211435. 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
  211436. };
  211437. #define READ_UTF8(zIn, zTerm, c) \
  211438. c = *(zIn++); \
  211439. if( c>=0xc0 ){ \
  211440. c = sqlite3Utf8Trans1[c-0xc0]; \
  211441. while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \
  211442. c = (c<<6) + (0x3f & *(zIn++)); \
  211443. } \
  211444. if( c<0x80 \
  211445. || (c&0xFFFFF800)==0xD800 \
  211446. || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \
  211447. }
  211448. #define WRITE_UTF8(zOut, c) { \
  211449. if( c<0x00080 ){ \
  211450. *zOut++ = (unsigned char)(c&0xFF); \
  211451. } \
  211452. else if( c<0x00800 ){ \
  211453. *zOut++ = 0xC0 + (unsigned char)((c>>6)&0x1F); \
  211454. *zOut++ = 0x80 + (unsigned char)(c & 0x3F); \
  211455. } \
  211456. else if( c<0x10000 ){ \
  211457. *zOut++ = 0xE0 + (unsigned char)((c>>12)&0x0F); \
  211458. *zOut++ = 0x80 + (unsigned char)((c>>6) & 0x3F); \
  211459. *zOut++ = 0x80 + (unsigned char)(c & 0x3F); \
  211460. }else{ \
  211461. *zOut++ = 0xF0 + (unsigned char)((c>>18) & 0x07); \
  211462. *zOut++ = 0x80 + (unsigned char)((c>>12) & 0x3F); \
  211463. *zOut++ = 0x80 + (unsigned char)((c>>6) & 0x3F); \
  211464. *zOut++ = 0x80 + (unsigned char)(c & 0x3F); \
  211465. } \
  211466. }
  211467. #endif /* ifndef SQLITE_AMALGAMATION */
  211468. typedef struct Unicode61Tokenizer Unicode61Tokenizer;
  211469. struct Unicode61Tokenizer {
  211470. unsigned char aTokenChar[128]; /* ASCII range token characters */
  211471. char *aFold; /* Buffer to fold text into */
  211472. int nFold; /* Size of aFold[] in bytes */
  211473. int eRemoveDiacritic; /* True if remove_diacritics=1 is set */
  211474. int nException;
  211475. int *aiException;
  211476. unsigned char aCategory[32]; /* True for token char categories */
  211477. };
  211478. /* Values for eRemoveDiacritic (must match internals of fts5_unicode2.c) */
  211479. #define FTS5_REMOVE_DIACRITICS_NONE 0
  211480. #define FTS5_REMOVE_DIACRITICS_SIMPLE 1
  211481. #define FTS5_REMOVE_DIACRITICS_COMPLEX 2
  211482. static int fts5UnicodeAddExceptions(
  211483. Unicode61Tokenizer *p, /* Tokenizer object */
  211484. const char *z, /* Characters to treat as exceptions */
  211485. int bTokenChars /* 1 for 'tokenchars', 0 for 'separators' */
  211486. ){
  211487. int rc = SQLITE_OK;
  211488. int n = (int)strlen(z);
  211489. int *aNew;
  211490. if( n>0 ){
  211491. aNew = (int*)sqlite3_realloc64(p->aiException,
  211492. (n+p->nException)*sizeof(int));
  211493. if( aNew ){
  211494. int nNew = p->nException;
  211495. const unsigned char *zCsr = (const unsigned char*)z;
  211496. const unsigned char *zTerm = (const unsigned char*)&z[n];
  211497. while( zCsr<zTerm ){
  211498. u32 iCode;
  211499. int bToken;
  211500. READ_UTF8(zCsr, zTerm, iCode);
  211501. if( iCode<128 ){
  211502. p->aTokenChar[iCode] = (unsigned char)bTokenChars;
  211503. }else{
  211504. bToken = p->aCategory[sqlite3Fts5UnicodeCategory(iCode)];
  211505. assert( (bToken==0 || bToken==1) );
  211506. assert( (bTokenChars==0 || bTokenChars==1) );
  211507. if( bToken!=bTokenChars && sqlite3Fts5UnicodeIsdiacritic(iCode)==0 ){
  211508. int i;
  211509. for(i=0; i<nNew; i++){
  211510. if( (u32)aNew[i]>iCode ) break;
  211511. }
  211512. memmove(&aNew[i+1], &aNew[i], (nNew-i)*sizeof(int));
  211513. aNew[i] = iCode;
  211514. nNew++;
  211515. }
  211516. }
  211517. }
  211518. p->aiException = aNew;
  211519. p->nException = nNew;
  211520. }else{
  211521. rc = SQLITE_NOMEM;
  211522. }
  211523. }
  211524. return rc;
  211525. }
  211526. /*
  211527. ** Return true if the p->aiException[] array contains the value iCode.
  211528. */
  211529. static int fts5UnicodeIsException(Unicode61Tokenizer *p, int iCode){
  211530. if( p->nException>0 ){
  211531. int *a = p->aiException;
  211532. int iLo = 0;
  211533. int iHi = p->nException-1;
  211534. while( iHi>=iLo ){
  211535. int iTest = (iHi + iLo) / 2;
  211536. if( iCode==a[iTest] ){
  211537. return 1;
  211538. }else if( iCode>a[iTest] ){
  211539. iLo = iTest+1;
  211540. }else{
  211541. iHi = iTest-1;
  211542. }
  211543. }
  211544. }
  211545. return 0;
  211546. }
  211547. /*
  211548. ** Delete a "unicode61" tokenizer.
  211549. */
  211550. static void fts5UnicodeDelete(Fts5Tokenizer *pTok){
  211551. if( pTok ){
  211552. Unicode61Tokenizer *p = (Unicode61Tokenizer*)pTok;
  211553. sqlite3_free(p->aiException);
  211554. sqlite3_free(p->aFold);
  211555. sqlite3_free(p);
  211556. }
  211557. return;
  211558. }
  211559. static int unicodeSetCategories(Unicode61Tokenizer *p, const char *zCat){
  211560. const char *z = zCat;
  211561. while( *z ){
  211562. while( *z==' ' || *z=='\t' ) z++;
  211563. if( *z && sqlite3Fts5UnicodeCatParse(z, p->aCategory) ){
  211564. return SQLITE_ERROR;
  211565. }
  211566. while( *z!=' ' && *z!='\t' && *z!='\0' ) z++;
  211567. }
  211568. sqlite3Fts5UnicodeAscii(p->aCategory, p->aTokenChar);
  211569. return SQLITE_OK;
  211570. }
  211571. /*
  211572. ** Create a "unicode61" tokenizer.
  211573. */
  211574. static int fts5UnicodeCreate(
  211575. void *pUnused,
  211576. const char **azArg, int nArg,
  211577. Fts5Tokenizer **ppOut
  211578. ){
  211579. int rc = SQLITE_OK; /* Return code */
  211580. Unicode61Tokenizer *p = 0; /* New tokenizer object */
  211581. UNUSED_PARAM(pUnused);
  211582. if( nArg%2 ){
  211583. rc = SQLITE_ERROR;
  211584. }else{
  211585. p = (Unicode61Tokenizer*)sqlite3_malloc(sizeof(Unicode61Tokenizer));
  211586. if( p ){
  211587. const char *zCat = "L* N* Co";
  211588. int i;
  211589. memset(p, 0, sizeof(Unicode61Tokenizer));
  211590. p->eRemoveDiacritic = FTS5_REMOVE_DIACRITICS_SIMPLE;
  211591. p->nFold = 64;
  211592. p->aFold = sqlite3_malloc64(p->nFold * sizeof(char));
  211593. if( p->aFold==0 ){
  211594. rc = SQLITE_NOMEM;
  211595. }
  211596. /* Search for a "categories" argument */
  211597. for(i=0; rc==SQLITE_OK && i<nArg; i+=2){
  211598. if( 0==sqlite3_stricmp(azArg[i], "categories") ){
  211599. zCat = azArg[i+1];
  211600. }
  211601. }
  211602. if( rc==SQLITE_OK ){
  211603. rc = unicodeSetCategories(p, zCat);
  211604. }
  211605. for(i=0; rc==SQLITE_OK && i<nArg; i+=2){
  211606. const char *zArg = azArg[i+1];
  211607. if( 0==sqlite3_stricmp(azArg[i], "remove_diacritics") ){
  211608. if( (zArg[0]!='0' && zArg[0]!='1' && zArg[0]!='2') || zArg[1] ){
  211609. rc = SQLITE_ERROR;
  211610. }else{
  211611. p->eRemoveDiacritic = (zArg[0] - '0');
  211612. assert( p->eRemoveDiacritic==FTS5_REMOVE_DIACRITICS_NONE
  211613. || p->eRemoveDiacritic==FTS5_REMOVE_DIACRITICS_SIMPLE
  211614. || p->eRemoveDiacritic==FTS5_REMOVE_DIACRITICS_COMPLEX
  211615. );
  211616. }
  211617. }else
  211618. if( 0==sqlite3_stricmp(azArg[i], "tokenchars") ){
  211619. rc = fts5UnicodeAddExceptions(p, zArg, 1);
  211620. }else
  211621. if( 0==sqlite3_stricmp(azArg[i], "separators") ){
  211622. rc = fts5UnicodeAddExceptions(p, zArg, 0);
  211623. }else
  211624. if( 0==sqlite3_stricmp(azArg[i], "categories") ){
  211625. /* no-op */
  211626. }else{
  211627. rc = SQLITE_ERROR;
  211628. }
  211629. }
  211630. }else{
  211631. rc = SQLITE_NOMEM;
  211632. }
  211633. if( rc!=SQLITE_OK ){
  211634. fts5UnicodeDelete((Fts5Tokenizer*)p);
  211635. p = 0;
  211636. }
  211637. *ppOut = (Fts5Tokenizer*)p;
  211638. }
  211639. return rc;
  211640. }
  211641. /*
  211642. ** Return true if, for the purposes of tokenizing with the tokenizer
  211643. ** passed as the first argument, codepoint iCode is considered a token
  211644. ** character (not a separator).
  211645. */
  211646. static int fts5UnicodeIsAlnum(Unicode61Tokenizer *p, int iCode){
  211647. return (
  211648. p->aCategory[sqlite3Fts5UnicodeCategory((u32)iCode)]
  211649. ^ fts5UnicodeIsException(p, iCode)
  211650. );
  211651. }
  211652. static int fts5UnicodeTokenize(
  211653. Fts5Tokenizer *pTokenizer,
  211654. void *pCtx,
  211655. int iUnused,
  211656. const char *pText, int nText,
  211657. int (*xToken)(void*, int, const char*, int nToken, int iStart, int iEnd)
  211658. ){
  211659. Unicode61Tokenizer *p = (Unicode61Tokenizer*)pTokenizer;
  211660. int rc = SQLITE_OK;
  211661. unsigned char *a = p->aTokenChar;
  211662. unsigned char *zTerm = (unsigned char*)&pText[nText];
  211663. unsigned char *zCsr = (unsigned char *)pText;
  211664. /* Output buffer */
  211665. char *aFold = p->aFold;
  211666. int nFold = p->nFold;
  211667. const char *pEnd = &aFold[nFold-6];
  211668. UNUSED_PARAM(iUnused);
  211669. /* Each iteration of this loop gobbles up a contiguous run of separators,
  211670. ** then the next token. */
  211671. while( rc==SQLITE_OK ){
  211672. u32 iCode; /* non-ASCII codepoint read from input */
  211673. char *zOut = aFold;
  211674. int is;
  211675. int ie;
  211676. /* Skip any separator characters. */
  211677. while( 1 ){
  211678. if( zCsr>=zTerm ) goto tokenize_done;
  211679. if( *zCsr & 0x80 ) {
  211680. /* A character outside of the ascii range. Skip past it if it is
  211681. ** a separator character. Or break out of the loop if it is not. */
  211682. is = zCsr - (unsigned char*)pText;
  211683. READ_UTF8(zCsr, zTerm, iCode);
  211684. if( fts5UnicodeIsAlnum(p, iCode) ){
  211685. goto non_ascii_tokenchar;
  211686. }
  211687. }else{
  211688. if( a[*zCsr] ){
  211689. is = zCsr - (unsigned char*)pText;
  211690. goto ascii_tokenchar;
  211691. }
  211692. zCsr++;
  211693. }
  211694. }
  211695. /* Run through the tokenchars. Fold them into the output buffer along
  211696. ** the way. */
  211697. while( zCsr<zTerm ){
  211698. /* Grow the output buffer so that there is sufficient space to fit the
  211699. ** largest possible utf-8 character. */
  211700. if( zOut>pEnd ){
  211701. aFold = sqlite3_malloc64((sqlite3_int64)nFold*2);
  211702. if( aFold==0 ){
  211703. rc = SQLITE_NOMEM;
  211704. goto tokenize_done;
  211705. }
  211706. zOut = &aFold[zOut - p->aFold];
  211707. memcpy(aFold, p->aFold, nFold);
  211708. sqlite3_free(p->aFold);
  211709. p->aFold = aFold;
  211710. p->nFold = nFold = nFold*2;
  211711. pEnd = &aFold[nFold-6];
  211712. }
  211713. if( *zCsr & 0x80 ){
  211714. /* An non-ascii-range character. Fold it into the output buffer if
  211715. ** it is a token character, or break out of the loop if it is not. */
  211716. READ_UTF8(zCsr, zTerm, iCode);
  211717. if( fts5UnicodeIsAlnum(p,iCode)||sqlite3Fts5UnicodeIsdiacritic(iCode) ){
  211718. non_ascii_tokenchar:
  211719. iCode = sqlite3Fts5UnicodeFold(iCode, p->eRemoveDiacritic);
  211720. if( iCode ) WRITE_UTF8(zOut, iCode);
  211721. }else{
  211722. break;
  211723. }
  211724. }else if( a[*zCsr]==0 ){
  211725. /* An ascii-range separator character. End of token. */
  211726. break;
  211727. }else{
  211728. ascii_tokenchar:
  211729. if( *zCsr>='A' && *zCsr<='Z' ){
  211730. *zOut++ = *zCsr + 32;
  211731. }else{
  211732. *zOut++ = *zCsr;
  211733. }
  211734. zCsr++;
  211735. }
  211736. ie = zCsr - (unsigned char*)pText;
  211737. }
  211738. /* Invoke the token callback */
  211739. rc = xToken(pCtx, 0, aFold, zOut-aFold, is, ie);
  211740. }
  211741. tokenize_done:
  211742. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  211743. return rc;
  211744. }
  211745. /**************************************************************************
  211746. ** Start of porter stemmer implementation.
  211747. */
  211748. /* Any tokens larger than this (in bytes) are passed through without
  211749. ** stemming. */
  211750. #define FTS5_PORTER_MAX_TOKEN 64
  211751. typedef struct PorterTokenizer PorterTokenizer;
  211752. struct PorterTokenizer {
  211753. fts5_tokenizer tokenizer; /* Parent tokenizer module */
  211754. Fts5Tokenizer *pTokenizer; /* Parent tokenizer instance */
  211755. char aBuf[FTS5_PORTER_MAX_TOKEN + 64];
  211756. };
  211757. /*
  211758. ** Delete a "porter" tokenizer.
  211759. */
  211760. static void fts5PorterDelete(Fts5Tokenizer *pTok){
  211761. if( pTok ){
  211762. PorterTokenizer *p = (PorterTokenizer*)pTok;
  211763. if( p->pTokenizer ){
  211764. p->tokenizer.xDelete(p->pTokenizer);
  211765. }
  211766. sqlite3_free(p);
  211767. }
  211768. }
  211769. /*
  211770. ** Create a "porter" tokenizer.
  211771. */
  211772. static int fts5PorterCreate(
  211773. void *pCtx,
  211774. const char **azArg, int nArg,
  211775. Fts5Tokenizer **ppOut
  211776. ){
  211777. fts5_api *pApi = (fts5_api*)pCtx;
  211778. int rc = SQLITE_OK;
  211779. PorterTokenizer *pRet;
  211780. void *pUserdata = 0;
  211781. const char *zBase = "unicode61";
  211782. if( nArg>0 ){
  211783. zBase = azArg[0];
  211784. }
  211785. pRet = (PorterTokenizer*)sqlite3_malloc(sizeof(PorterTokenizer));
  211786. if( pRet ){
  211787. memset(pRet, 0, sizeof(PorterTokenizer));
  211788. rc = pApi->xFindTokenizer(pApi, zBase, &pUserdata, &pRet->tokenizer);
  211789. }else{
  211790. rc = SQLITE_NOMEM;
  211791. }
  211792. if( rc==SQLITE_OK ){
  211793. int nArg2 = (nArg>0 ? nArg-1 : 0);
  211794. const char **azArg2 = (nArg2 ? &azArg[1] : 0);
  211795. rc = pRet->tokenizer.xCreate(pUserdata, azArg2, nArg2, &pRet->pTokenizer);
  211796. }
  211797. if( rc!=SQLITE_OK ){
  211798. fts5PorterDelete((Fts5Tokenizer*)pRet);
  211799. pRet = 0;
  211800. }
  211801. *ppOut = (Fts5Tokenizer*)pRet;
  211802. return rc;
  211803. }
  211804. typedef struct PorterContext PorterContext;
  211805. struct PorterContext {
  211806. void *pCtx;
  211807. int (*xToken)(void*, int, const char*, int, int, int);
  211808. char *aBuf;
  211809. };
  211810. typedef struct PorterRule PorterRule;
  211811. struct PorterRule {
  211812. const char *zSuffix;
  211813. int nSuffix;
  211814. int (*xCond)(char *zStem, int nStem);
  211815. const char *zOutput;
  211816. int nOutput;
  211817. };
  211818. #if 0
  211819. static int fts5PorterApply(char *aBuf, int *pnBuf, PorterRule *aRule){
  211820. int ret = -1;
  211821. int nBuf = *pnBuf;
  211822. PorterRule *p;
  211823. for(p=aRule; p->zSuffix; p++){
  211824. assert( strlen(p->zSuffix)==p->nSuffix );
  211825. assert( strlen(p->zOutput)==p->nOutput );
  211826. if( nBuf<p->nSuffix ) continue;
  211827. if( 0==memcmp(&aBuf[nBuf - p->nSuffix], p->zSuffix, p->nSuffix) ) break;
  211828. }
  211829. if( p->zSuffix ){
  211830. int nStem = nBuf - p->nSuffix;
  211831. if( p->xCond==0 || p->xCond(aBuf, nStem) ){
  211832. memcpy(&aBuf[nStem], p->zOutput, p->nOutput);
  211833. *pnBuf = nStem + p->nOutput;
  211834. ret = p - aRule;
  211835. }
  211836. }
  211837. return ret;
  211838. }
  211839. #endif
  211840. static int fts5PorterIsVowel(char c, int bYIsVowel){
  211841. return (
  211842. c=='a' || c=='e' || c=='i' || c=='o' || c=='u' || (bYIsVowel && c=='y')
  211843. );
  211844. }
  211845. static int fts5PorterGobbleVC(char *zStem, int nStem, int bPrevCons){
  211846. int i;
  211847. int bCons = bPrevCons;
  211848. /* Scan for a vowel */
  211849. for(i=0; i<nStem; i++){
  211850. if( 0==(bCons = !fts5PorterIsVowel(zStem[i], bCons)) ) break;
  211851. }
  211852. /* Scan for a consonent */
  211853. for(i++; i<nStem; i++){
  211854. if( (bCons = !fts5PorterIsVowel(zStem[i], bCons)) ) return i+1;
  211855. }
  211856. return 0;
  211857. }
  211858. /* porter rule condition: (m > 0) */
  211859. static int fts5Porter_MGt0(char *zStem, int nStem){
  211860. return !!fts5PorterGobbleVC(zStem, nStem, 0);
  211861. }
  211862. /* porter rule condition: (m > 1) */
  211863. static int fts5Porter_MGt1(char *zStem, int nStem){
  211864. int n;
  211865. n = fts5PorterGobbleVC(zStem, nStem, 0);
  211866. if( n && fts5PorterGobbleVC(&zStem[n], nStem-n, 1) ){
  211867. return 1;
  211868. }
  211869. return 0;
  211870. }
  211871. /* porter rule condition: (m = 1) */
  211872. static int fts5Porter_MEq1(char *zStem, int nStem){
  211873. int n;
  211874. n = fts5PorterGobbleVC(zStem, nStem, 0);
  211875. if( n && 0==fts5PorterGobbleVC(&zStem[n], nStem-n, 1) ){
  211876. return 1;
  211877. }
  211878. return 0;
  211879. }
  211880. /* porter rule condition: (*o) */
  211881. static int fts5Porter_Ostar(char *zStem, int nStem){
  211882. if( zStem[nStem-1]=='w' || zStem[nStem-1]=='x' || zStem[nStem-1]=='y' ){
  211883. return 0;
  211884. }else{
  211885. int i;
  211886. int mask = 0;
  211887. int bCons = 0;
  211888. for(i=0; i<nStem; i++){
  211889. bCons = !fts5PorterIsVowel(zStem[i], bCons);
  211890. assert( bCons==0 || bCons==1 );
  211891. mask = (mask << 1) + bCons;
  211892. }
  211893. return ((mask & 0x0007)==0x0005);
  211894. }
  211895. }
  211896. /* porter rule condition: (m > 1 and (*S or *T)) */
  211897. static int fts5Porter_MGt1_and_S_or_T(char *zStem, int nStem){
  211898. assert( nStem>0 );
  211899. return (zStem[nStem-1]=='s' || zStem[nStem-1]=='t')
  211900. && fts5Porter_MGt1(zStem, nStem);
  211901. }
  211902. /* porter rule condition: (*v*) */
  211903. static int fts5Porter_Vowel(char *zStem, int nStem){
  211904. int i;
  211905. for(i=0; i<nStem; i++){
  211906. if( fts5PorterIsVowel(zStem[i], i>0) ){
  211907. return 1;
  211908. }
  211909. }
  211910. return 0;
  211911. }
  211912. /**************************************************************************
  211913. ***************************************************************************
  211914. ** GENERATED CODE STARTS HERE (mkportersteps.tcl)
  211915. */
  211916. static int fts5PorterStep4(char *aBuf, int *pnBuf){
  211917. int ret = 0;
  211918. int nBuf = *pnBuf;
  211919. switch( aBuf[nBuf-2] ){
  211920. case 'a':
  211921. if( nBuf>2 && 0==memcmp("al", &aBuf[nBuf-2], 2) ){
  211922. if( fts5Porter_MGt1(aBuf, nBuf-2) ){
  211923. *pnBuf = nBuf - 2;
  211924. }
  211925. }
  211926. break;
  211927. case 'c':
  211928. if( nBuf>4 && 0==memcmp("ance", &aBuf[nBuf-4], 4) ){
  211929. if( fts5Porter_MGt1(aBuf, nBuf-4) ){
  211930. *pnBuf = nBuf - 4;
  211931. }
  211932. }else if( nBuf>4 && 0==memcmp("ence", &aBuf[nBuf-4], 4) ){
  211933. if( fts5Porter_MGt1(aBuf, nBuf-4) ){
  211934. *pnBuf = nBuf - 4;
  211935. }
  211936. }
  211937. break;
  211938. case 'e':
  211939. if( nBuf>2 && 0==memcmp("er", &aBuf[nBuf-2], 2) ){
  211940. if( fts5Porter_MGt1(aBuf, nBuf-2) ){
  211941. *pnBuf = nBuf - 2;
  211942. }
  211943. }
  211944. break;
  211945. case 'i':
  211946. if( nBuf>2 && 0==memcmp("ic", &aBuf[nBuf-2], 2) ){
  211947. if( fts5Porter_MGt1(aBuf, nBuf-2) ){
  211948. *pnBuf = nBuf - 2;
  211949. }
  211950. }
  211951. break;
  211952. case 'l':
  211953. if( nBuf>4 && 0==memcmp("able", &aBuf[nBuf-4], 4) ){
  211954. if( fts5Porter_MGt1(aBuf, nBuf-4) ){
  211955. *pnBuf = nBuf - 4;
  211956. }
  211957. }else if( nBuf>4 && 0==memcmp("ible", &aBuf[nBuf-4], 4) ){
  211958. if( fts5Porter_MGt1(aBuf, nBuf-4) ){
  211959. *pnBuf = nBuf - 4;
  211960. }
  211961. }
  211962. break;
  211963. case 'n':
  211964. if( nBuf>3 && 0==memcmp("ant", &aBuf[nBuf-3], 3) ){
  211965. if( fts5Porter_MGt1(aBuf, nBuf-3) ){
  211966. *pnBuf = nBuf - 3;
  211967. }
  211968. }else if( nBuf>5 && 0==memcmp("ement", &aBuf[nBuf-5], 5) ){
  211969. if( fts5Porter_MGt1(aBuf, nBuf-5) ){
  211970. *pnBuf = nBuf - 5;
  211971. }
  211972. }else if( nBuf>4 && 0==memcmp("ment", &aBuf[nBuf-4], 4) ){
  211973. if( fts5Porter_MGt1(aBuf, nBuf-4) ){
  211974. *pnBuf = nBuf - 4;
  211975. }
  211976. }else if( nBuf>3 && 0==memcmp("ent", &aBuf[nBuf-3], 3) ){
  211977. if( fts5Porter_MGt1(aBuf, nBuf-3) ){
  211978. *pnBuf = nBuf - 3;
  211979. }
  211980. }
  211981. break;
  211982. case 'o':
  211983. if( nBuf>3 && 0==memcmp("ion", &aBuf[nBuf-3], 3) ){
  211984. if( fts5Porter_MGt1_and_S_or_T(aBuf, nBuf-3) ){
  211985. *pnBuf = nBuf - 3;
  211986. }
  211987. }else if( nBuf>2 && 0==memcmp("ou", &aBuf[nBuf-2], 2) ){
  211988. if( fts5Porter_MGt1(aBuf, nBuf-2) ){
  211989. *pnBuf = nBuf - 2;
  211990. }
  211991. }
  211992. break;
  211993. case 's':
  211994. if( nBuf>3 && 0==memcmp("ism", &aBuf[nBuf-3], 3) ){
  211995. if( fts5Porter_MGt1(aBuf, nBuf-3) ){
  211996. *pnBuf = nBuf - 3;
  211997. }
  211998. }
  211999. break;
  212000. case 't':
  212001. if( nBuf>3 && 0==memcmp("ate", &aBuf[nBuf-3], 3) ){
  212002. if( fts5Porter_MGt1(aBuf, nBuf-3) ){
  212003. *pnBuf = nBuf - 3;
  212004. }
  212005. }else if( nBuf>3 && 0==memcmp("iti", &aBuf[nBuf-3], 3) ){
  212006. if( fts5Porter_MGt1(aBuf, nBuf-3) ){
  212007. *pnBuf = nBuf - 3;
  212008. }
  212009. }
  212010. break;
  212011. case 'u':
  212012. if( nBuf>3 && 0==memcmp("ous", &aBuf[nBuf-3], 3) ){
  212013. if( fts5Porter_MGt1(aBuf, nBuf-3) ){
  212014. *pnBuf = nBuf - 3;
  212015. }
  212016. }
  212017. break;
  212018. case 'v':
  212019. if( nBuf>3 && 0==memcmp("ive", &aBuf[nBuf-3], 3) ){
  212020. if( fts5Porter_MGt1(aBuf, nBuf-3) ){
  212021. *pnBuf = nBuf - 3;
  212022. }
  212023. }
  212024. break;
  212025. case 'z':
  212026. if( nBuf>3 && 0==memcmp("ize", &aBuf[nBuf-3], 3) ){
  212027. if( fts5Porter_MGt1(aBuf, nBuf-3) ){
  212028. *pnBuf = nBuf - 3;
  212029. }
  212030. }
  212031. break;
  212032. }
  212033. return ret;
  212034. }
  212035. static int fts5PorterStep1B2(char *aBuf, int *pnBuf){
  212036. int ret = 0;
  212037. int nBuf = *pnBuf;
  212038. switch( aBuf[nBuf-2] ){
  212039. case 'a':
  212040. if( nBuf>2 && 0==memcmp("at", &aBuf[nBuf-2], 2) ){
  212041. memcpy(&aBuf[nBuf-2], "ate", 3);
  212042. *pnBuf = nBuf - 2 + 3;
  212043. ret = 1;
  212044. }
  212045. break;
  212046. case 'b':
  212047. if( nBuf>2 && 0==memcmp("bl", &aBuf[nBuf-2], 2) ){
  212048. memcpy(&aBuf[nBuf-2], "ble", 3);
  212049. *pnBuf = nBuf - 2 + 3;
  212050. ret = 1;
  212051. }
  212052. break;
  212053. case 'i':
  212054. if( nBuf>2 && 0==memcmp("iz", &aBuf[nBuf-2], 2) ){
  212055. memcpy(&aBuf[nBuf-2], "ize", 3);
  212056. *pnBuf = nBuf - 2 + 3;
  212057. ret = 1;
  212058. }
  212059. break;
  212060. }
  212061. return ret;
  212062. }
  212063. static int fts5PorterStep2(char *aBuf, int *pnBuf){
  212064. int ret = 0;
  212065. int nBuf = *pnBuf;
  212066. switch( aBuf[nBuf-2] ){
  212067. case 'a':
  212068. if( nBuf>7 && 0==memcmp("ational", &aBuf[nBuf-7], 7) ){
  212069. if( fts5Porter_MGt0(aBuf, nBuf-7) ){
  212070. memcpy(&aBuf[nBuf-7], "ate", 3);
  212071. *pnBuf = nBuf - 7 + 3;
  212072. }
  212073. }else if( nBuf>6 && 0==memcmp("tional", &aBuf[nBuf-6], 6) ){
  212074. if( fts5Porter_MGt0(aBuf, nBuf-6) ){
  212075. memcpy(&aBuf[nBuf-6], "tion", 4);
  212076. *pnBuf = nBuf - 6 + 4;
  212077. }
  212078. }
  212079. break;
  212080. case 'c':
  212081. if( nBuf>4 && 0==memcmp("enci", &aBuf[nBuf-4], 4) ){
  212082. if( fts5Porter_MGt0(aBuf, nBuf-4) ){
  212083. memcpy(&aBuf[nBuf-4], "ence", 4);
  212084. *pnBuf = nBuf - 4 + 4;
  212085. }
  212086. }else if( nBuf>4 && 0==memcmp("anci", &aBuf[nBuf-4], 4) ){
  212087. if( fts5Porter_MGt0(aBuf, nBuf-4) ){
  212088. memcpy(&aBuf[nBuf-4], "ance", 4);
  212089. *pnBuf = nBuf - 4 + 4;
  212090. }
  212091. }
  212092. break;
  212093. case 'e':
  212094. if( nBuf>4 && 0==memcmp("izer", &aBuf[nBuf-4], 4) ){
  212095. if( fts5Porter_MGt0(aBuf, nBuf-4) ){
  212096. memcpy(&aBuf[nBuf-4], "ize", 3);
  212097. *pnBuf = nBuf - 4 + 3;
  212098. }
  212099. }
  212100. break;
  212101. case 'g':
  212102. if( nBuf>4 && 0==memcmp("logi", &aBuf[nBuf-4], 4) ){
  212103. if( fts5Porter_MGt0(aBuf, nBuf-4) ){
  212104. memcpy(&aBuf[nBuf-4], "log", 3);
  212105. *pnBuf = nBuf - 4 + 3;
  212106. }
  212107. }
  212108. break;
  212109. case 'l':
  212110. if( nBuf>3 && 0==memcmp("bli", &aBuf[nBuf-3], 3) ){
  212111. if( fts5Porter_MGt0(aBuf, nBuf-3) ){
  212112. memcpy(&aBuf[nBuf-3], "ble", 3);
  212113. *pnBuf = nBuf - 3 + 3;
  212114. }
  212115. }else if( nBuf>4 && 0==memcmp("alli", &aBuf[nBuf-4], 4) ){
  212116. if( fts5Porter_MGt0(aBuf, nBuf-4) ){
  212117. memcpy(&aBuf[nBuf-4], "al", 2);
  212118. *pnBuf = nBuf - 4 + 2;
  212119. }
  212120. }else if( nBuf>5 && 0==memcmp("entli", &aBuf[nBuf-5], 5) ){
  212121. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  212122. memcpy(&aBuf[nBuf-5], "ent", 3);
  212123. *pnBuf = nBuf - 5 + 3;
  212124. }
  212125. }else if( nBuf>3 && 0==memcmp("eli", &aBuf[nBuf-3], 3) ){
  212126. if( fts5Porter_MGt0(aBuf, nBuf-3) ){
  212127. memcpy(&aBuf[nBuf-3], "e", 1);
  212128. *pnBuf = nBuf - 3 + 1;
  212129. }
  212130. }else if( nBuf>5 && 0==memcmp("ousli", &aBuf[nBuf-5], 5) ){
  212131. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  212132. memcpy(&aBuf[nBuf-5], "ous", 3);
  212133. *pnBuf = nBuf - 5 + 3;
  212134. }
  212135. }
  212136. break;
  212137. case 'o':
  212138. if( nBuf>7 && 0==memcmp("ization", &aBuf[nBuf-7], 7) ){
  212139. if( fts5Porter_MGt0(aBuf, nBuf-7) ){
  212140. memcpy(&aBuf[nBuf-7], "ize", 3);
  212141. *pnBuf = nBuf - 7 + 3;
  212142. }
  212143. }else if( nBuf>5 && 0==memcmp("ation", &aBuf[nBuf-5], 5) ){
  212144. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  212145. memcpy(&aBuf[nBuf-5], "ate", 3);
  212146. *pnBuf = nBuf - 5 + 3;
  212147. }
  212148. }else if( nBuf>4 && 0==memcmp("ator", &aBuf[nBuf-4], 4) ){
  212149. if( fts5Porter_MGt0(aBuf, nBuf-4) ){
  212150. memcpy(&aBuf[nBuf-4], "ate", 3);
  212151. *pnBuf = nBuf - 4 + 3;
  212152. }
  212153. }
  212154. break;
  212155. case 's':
  212156. if( nBuf>5 && 0==memcmp("alism", &aBuf[nBuf-5], 5) ){
  212157. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  212158. memcpy(&aBuf[nBuf-5], "al", 2);
  212159. *pnBuf = nBuf - 5 + 2;
  212160. }
  212161. }else if( nBuf>7 && 0==memcmp("iveness", &aBuf[nBuf-7], 7) ){
  212162. if( fts5Porter_MGt0(aBuf, nBuf-7) ){
  212163. memcpy(&aBuf[nBuf-7], "ive", 3);
  212164. *pnBuf = nBuf - 7 + 3;
  212165. }
  212166. }else if( nBuf>7 && 0==memcmp("fulness", &aBuf[nBuf-7], 7) ){
  212167. if( fts5Porter_MGt0(aBuf, nBuf-7) ){
  212168. memcpy(&aBuf[nBuf-7], "ful", 3);
  212169. *pnBuf = nBuf - 7 + 3;
  212170. }
  212171. }else if( nBuf>7 && 0==memcmp("ousness", &aBuf[nBuf-7], 7) ){
  212172. if( fts5Porter_MGt0(aBuf, nBuf-7) ){
  212173. memcpy(&aBuf[nBuf-7], "ous", 3);
  212174. *pnBuf = nBuf - 7 + 3;
  212175. }
  212176. }
  212177. break;
  212178. case 't':
  212179. if( nBuf>5 && 0==memcmp("aliti", &aBuf[nBuf-5], 5) ){
  212180. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  212181. memcpy(&aBuf[nBuf-5], "al", 2);
  212182. *pnBuf = nBuf - 5 + 2;
  212183. }
  212184. }else if( nBuf>5 && 0==memcmp("iviti", &aBuf[nBuf-5], 5) ){
  212185. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  212186. memcpy(&aBuf[nBuf-5], "ive", 3);
  212187. *pnBuf = nBuf - 5 + 3;
  212188. }
  212189. }else if( nBuf>6 && 0==memcmp("biliti", &aBuf[nBuf-6], 6) ){
  212190. if( fts5Porter_MGt0(aBuf, nBuf-6) ){
  212191. memcpy(&aBuf[nBuf-6], "ble", 3);
  212192. *pnBuf = nBuf - 6 + 3;
  212193. }
  212194. }
  212195. break;
  212196. }
  212197. return ret;
  212198. }
  212199. static int fts5PorterStep3(char *aBuf, int *pnBuf){
  212200. int ret = 0;
  212201. int nBuf = *pnBuf;
  212202. switch( aBuf[nBuf-2] ){
  212203. case 'a':
  212204. if( nBuf>4 && 0==memcmp("ical", &aBuf[nBuf-4], 4) ){
  212205. if( fts5Porter_MGt0(aBuf, nBuf-4) ){
  212206. memcpy(&aBuf[nBuf-4], "ic", 2);
  212207. *pnBuf = nBuf - 4 + 2;
  212208. }
  212209. }
  212210. break;
  212211. case 's':
  212212. if( nBuf>4 && 0==memcmp("ness", &aBuf[nBuf-4], 4) ){
  212213. if( fts5Porter_MGt0(aBuf, nBuf-4) ){
  212214. *pnBuf = nBuf - 4;
  212215. }
  212216. }
  212217. break;
  212218. case 't':
  212219. if( nBuf>5 && 0==memcmp("icate", &aBuf[nBuf-5], 5) ){
  212220. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  212221. memcpy(&aBuf[nBuf-5], "ic", 2);
  212222. *pnBuf = nBuf - 5 + 2;
  212223. }
  212224. }else if( nBuf>5 && 0==memcmp("iciti", &aBuf[nBuf-5], 5) ){
  212225. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  212226. memcpy(&aBuf[nBuf-5], "ic", 2);
  212227. *pnBuf = nBuf - 5 + 2;
  212228. }
  212229. }
  212230. break;
  212231. case 'u':
  212232. if( nBuf>3 && 0==memcmp("ful", &aBuf[nBuf-3], 3) ){
  212233. if( fts5Porter_MGt0(aBuf, nBuf-3) ){
  212234. *pnBuf = nBuf - 3;
  212235. }
  212236. }
  212237. break;
  212238. case 'v':
  212239. if( nBuf>5 && 0==memcmp("ative", &aBuf[nBuf-5], 5) ){
  212240. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  212241. *pnBuf = nBuf - 5;
  212242. }
  212243. }
  212244. break;
  212245. case 'z':
  212246. if( nBuf>5 && 0==memcmp("alize", &aBuf[nBuf-5], 5) ){
  212247. if( fts5Porter_MGt0(aBuf, nBuf-5) ){
  212248. memcpy(&aBuf[nBuf-5], "al", 2);
  212249. *pnBuf = nBuf - 5 + 2;
  212250. }
  212251. }
  212252. break;
  212253. }
  212254. return ret;
  212255. }
  212256. static int fts5PorterStep1B(char *aBuf, int *pnBuf){
  212257. int ret = 0;
  212258. int nBuf = *pnBuf;
  212259. switch( aBuf[nBuf-2] ){
  212260. case 'e':
  212261. if( nBuf>3 && 0==memcmp("eed", &aBuf[nBuf-3], 3) ){
  212262. if( fts5Porter_MGt0(aBuf, nBuf-3) ){
  212263. memcpy(&aBuf[nBuf-3], "ee", 2);
  212264. *pnBuf = nBuf - 3 + 2;
  212265. }
  212266. }else if( nBuf>2 && 0==memcmp("ed", &aBuf[nBuf-2], 2) ){
  212267. if( fts5Porter_Vowel(aBuf, nBuf-2) ){
  212268. *pnBuf = nBuf - 2;
  212269. ret = 1;
  212270. }
  212271. }
  212272. break;
  212273. case 'n':
  212274. if( nBuf>3 && 0==memcmp("ing", &aBuf[nBuf-3], 3) ){
  212275. if( fts5Porter_Vowel(aBuf, nBuf-3) ){
  212276. *pnBuf = nBuf - 3;
  212277. ret = 1;
  212278. }
  212279. }
  212280. break;
  212281. }
  212282. return ret;
  212283. }
  212284. /*
  212285. ** GENERATED CODE ENDS HERE (mkportersteps.tcl)
  212286. ***************************************************************************
  212287. **************************************************************************/
  212288. static void fts5PorterStep1A(char *aBuf, int *pnBuf){
  212289. int nBuf = *pnBuf;
  212290. if( aBuf[nBuf-1]=='s' ){
  212291. if( aBuf[nBuf-2]=='e' ){
  212292. if( (nBuf>4 && aBuf[nBuf-4]=='s' && aBuf[nBuf-3]=='s')
  212293. || (nBuf>3 && aBuf[nBuf-3]=='i' )
  212294. ){
  212295. *pnBuf = nBuf-2;
  212296. }else{
  212297. *pnBuf = nBuf-1;
  212298. }
  212299. }
  212300. else if( aBuf[nBuf-2]!='s' ){
  212301. *pnBuf = nBuf-1;
  212302. }
  212303. }
  212304. }
  212305. static int fts5PorterCb(
  212306. void *pCtx,
  212307. int tflags,
  212308. const char *pToken,
  212309. int nToken,
  212310. int iStart,
  212311. int iEnd
  212312. ){
  212313. PorterContext *p = (PorterContext*)pCtx;
  212314. char *aBuf;
  212315. int nBuf;
  212316. if( nToken>FTS5_PORTER_MAX_TOKEN || nToken<3 ) goto pass_through;
  212317. aBuf = p->aBuf;
  212318. nBuf = nToken;
  212319. memcpy(aBuf, pToken, nBuf);
  212320. /* Step 1. */
  212321. fts5PorterStep1A(aBuf, &nBuf);
  212322. if( fts5PorterStep1B(aBuf, &nBuf) ){
  212323. if( fts5PorterStep1B2(aBuf, &nBuf)==0 ){
  212324. char c = aBuf[nBuf-1];
  212325. if( fts5PorterIsVowel(c, 0)==0
  212326. && c!='l' && c!='s' && c!='z' && c==aBuf[nBuf-2]
  212327. ){
  212328. nBuf--;
  212329. }else if( fts5Porter_MEq1(aBuf, nBuf) && fts5Porter_Ostar(aBuf, nBuf) ){
  212330. aBuf[nBuf++] = 'e';
  212331. }
  212332. }
  212333. }
  212334. /* Step 1C. */
  212335. if( aBuf[nBuf-1]=='y' && fts5Porter_Vowel(aBuf, nBuf-1) ){
  212336. aBuf[nBuf-1] = 'i';
  212337. }
  212338. /* Steps 2 through 4. */
  212339. fts5PorterStep2(aBuf, &nBuf);
  212340. fts5PorterStep3(aBuf, &nBuf);
  212341. fts5PorterStep4(aBuf, &nBuf);
  212342. /* Step 5a. */
  212343. assert( nBuf>0 );
  212344. if( aBuf[nBuf-1]=='e' ){
  212345. if( fts5Porter_MGt1(aBuf, nBuf-1)
  212346. || (fts5Porter_MEq1(aBuf, nBuf-1) && !fts5Porter_Ostar(aBuf, nBuf-1))
  212347. ){
  212348. nBuf--;
  212349. }
  212350. }
  212351. /* Step 5b. */
  212352. if( nBuf>1 && aBuf[nBuf-1]=='l'
  212353. && aBuf[nBuf-2]=='l' && fts5Porter_MGt1(aBuf, nBuf-1)
  212354. ){
  212355. nBuf--;
  212356. }
  212357. return p->xToken(p->pCtx, tflags, aBuf, nBuf, iStart, iEnd);
  212358. pass_through:
  212359. return p->xToken(p->pCtx, tflags, pToken, nToken, iStart, iEnd);
  212360. }
  212361. /*
  212362. ** Tokenize using the porter tokenizer.
  212363. */
  212364. static int fts5PorterTokenize(
  212365. Fts5Tokenizer *pTokenizer,
  212366. void *pCtx,
  212367. int flags,
  212368. const char *pText, int nText,
  212369. int (*xToken)(void*, int, const char*, int nToken, int iStart, int iEnd)
  212370. ){
  212371. PorterTokenizer *p = (PorterTokenizer*)pTokenizer;
  212372. PorterContext sCtx;
  212373. sCtx.xToken = xToken;
  212374. sCtx.pCtx = pCtx;
  212375. sCtx.aBuf = p->aBuf;
  212376. return p->tokenizer.xTokenize(
  212377. p->pTokenizer, (void*)&sCtx, flags, pText, nText, fts5PorterCb
  212378. );
  212379. }
  212380. /*
  212381. ** Register all built-in tokenizers with FTS5.
  212382. */
  212383. static int sqlite3Fts5TokenizerInit(fts5_api *pApi){
  212384. struct BuiltinTokenizer {
  212385. const char *zName;
  212386. fts5_tokenizer x;
  212387. } aBuiltin[] = {
  212388. { "unicode61", {fts5UnicodeCreate, fts5UnicodeDelete, fts5UnicodeTokenize}},
  212389. { "ascii", {fts5AsciiCreate, fts5AsciiDelete, fts5AsciiTokenize }},
  212390. { "porter", {fts5PorterCreate, fts5PorterDelete, fts5PorterTokenize }},
  212391. };
  212392. int rc = SQLITE_OK; /* Return code */
  212393. int i; /* To iterate through builtin functions */
  212394. for(i=0; rc==SQLITE_OK && i<ArraySize(aBuiltin); i++){
  212395. rc = pApi->xCreateTokenizer(pApi,
  212396. aBuiltin[i].zName,
  212397. (void*)pApi,
  212398. &aBuiltin[i].x,
  212399. 0
  212400. );
  212401. }
  212402. return rc;
  212403. }
  212404. /*
  212405. ** 2012-05-25
  212406. **
  212407. ** The author disclaims copyright to this source code. In place of
  212408. ** a legal notice, here is a blessing:
  212409. **
  212410. ** May you do good and not evil.
  212411. ** May you find forgiveness for yourself and forgive others.
  212412. ** May you share freely, never taking more than you give.
  212413. **
  212414. ******************************************************************************
  212415. */
  212416. /*
  212417. ** DO NOT EDIT THIS MACHINE GENERATED FILE.
  212418. */
  212419. /* #include <assert.h> */
  212420. /*
  212421. ** If the argument is a codepoint corresponding to a lowercase letter
  212422. ** in the ASCII range with a diacritic added, return the codepoint
  212423. ** of the ASCII letter only. For example, if passed 235 - "LATIN
  212424. ** SMALL LETTER E WITH DIAERESIS" - return 65 ("LATIN SMALL LETTER
  212425. ** E"). The resuls of passing a codepoint that corresponds to an
  212426. ** uppercase letter are undefined.
  212427. */
  212428. static int fts5_remove_diacritic(int c, int bComplex){
  212429. unsigned short aDia[] = {
  212430. 0, 1797, 1848, 1859, 1891, 1928, 1940, 1995,
  212431. 2024, 2040, 2060, 2110, 2168, 2206, 2264, 2286,
  212432. 2344, 2383, 2472, 2488, 2516, 2596, 2668, 2732,
  212433. 2782, 2842, 2894, 2954, 2984, 3000, 3028, 3336,
  212434. 3456, 3696, 3712, 3728, 3744, 3766, 3832, 3896,
  212435. 3912, 3928, 3944, 3968, 4008, 4040, 4056, 4106,
  212436. 4138, 4170, 4202, 4234, 4266, 4296, 4312, 4344,
  212437. 4408, 4424, 4442, 4472, 4488, 4504, 6148, 6198,
  212438. 6264, 6280, 6360, 6429, 6505, 6529, 61448, 61468,
  212439. 61512, 61534, 61592, 61610, 61642, 61672, 61688, 61704,
  212440. 61726, 61784, 61800, 61816, 61836, 61880, 61896, 61914,
  212441. 61948, 61998, 62062, 62122, 62154, 62184, 62200, 62218,
  212442. 62252, 62302, 62364, 62410, 62442, 62478, 62536, 62554,
  212443. 62584, 62604, 62640, 62648, 62656, 62664, 62730, 62766,
  212444. 62830, 62890, 62924, 62974, 63032, 63050, 63082, 63118,
  212445. 63182, 63242, 63274, 63310, 63368, 63390,
  212446. };
  212447. #define HIBIT ((unsigned char)0x80)
  212448. unsigned char aChar[] = {
  212449. '\0', 'a', 'c', 'e', 'i', 'n',
  212450. 'o', 'u', 'y', 'y', 'a', 'c',
  212451. 'd', 'e', 'e', 'g', 'h', 'i',
  212452. 'j', 'k', 'l', 'n', 'o', 'r',
  212453. 's', 't', 'u', 'u', 'w', 'y',
  212454. 'z', 'o', 'u', 'a', 'i', 'o',
  212455. 'u', 'u'|HIBIT, 'a'|HIBIT, 'g', 'k', 'o',
  212456. 'o'|HIBIT, 'j', 'g', 'n', 'a'|HIBIT, 'a',
  212457. 'e', 'i', 'o', 'r', 'u', 's',
  212458. 't', 'h', 'a', 'e', 'o'|HIBIT, 'o',
  212459. 'o'|HIBIT, 'y', '\0', '\0', '\0', '\0',
  212460. '\0', '\0', '\0', '\0', 'a', 'b',
  212461. 'c'|HIBIT, 'd', 'd', 'e'|HIBIT, 'e', 'e'|HIBIT,
  212462. 'f', 'g', 'h', 'h', 'i', 'i'|HIBIT,
  212463. 'k', 'l', 'l'|HIBIT, 'l', 'm', 'n',
  212464. 'o'|HIBIT, 'p', 'r', 'r'|HIBIT, 'r', 's',
  212465. 's'|HIBIT, 't', 'u', 'u'|HIBIT, 'v', 'w',
  212466. 'w', 'x', 'y', 'z', 'h', 't',
  212467. 'w', 'y', 'a', 'a'|HIBIT, 'a'|HIBIT, 'a'|HIBIT,
  212468. 'e', 'e'|HIBIT, 'e'|HIBIT, 'i', 'o', 'o'|HIBIT,
  212469. 'o'|HIBIT, 'o'|HIBIT, 'u', 'u'|HIBIT, 'u'|HIBIT, 'y',
  212470. };
  212471. unsigned int key = (((unsigned int)c)<<3) | 0x00000007;
  212472. int iRes = 0;
  212473. int iHi = sizeof(aDia)/sizeof(aDia[0]) - 1;
  212474. int iLo = 0;
  212475. while( iHi>=iLo ){
  212476. int iTest = (iHi + iLo) / 2;
  212477. if( key >= aDia[iTest] ){
  212478. iRes = iTest;
  212479. iLo = iTest+1;
  212480. }else{
  212481. iHi = iTest-1;
  212482. }
  212483. }
  212484. assert( key>=aDia[iRes] );
  212485. if( bComplex==0 && (aChar[iRes] & 0x80) ) return c;
  212486. return (c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : ((int)aChar[iRes] & 0x7F);
  212487. }
  212488. /*
  212489. ** Return true if the argument interpreted as a unicode codepoint
  212490. ** is a diacritical modifier character.
  212491. */
  212492. static int sqlite3Fts5UnicodeIsdiacritic(int c){
  212493. unsigned int mask0 = 0x08029FDF;
  212494. unsigned int mask1 = 0x000361F8;
  212495. if( c<768 || c>817 ) return 0;
  212496. return (c < 768+32) ?
  212497. (mask0 & ((unsigned int)1 << (c-768))) :
  212498. (mask1 & ((unsigned int)1 << (c-768-32)));
  212499. }
  212500. /*
  212501. ** Interpret the argument as a unicode codepoint. If the codepoint
  212502. ** is an upper case character that has a lower case equivalent,
  212503. ** return the codepoint corresponding to the lower case version.
  212504. ** Otherwise, return a copy of the argument.
  212505. **
  212506. ** The results are undefined if the value passed to this function
  212507. ** is less than zero.
  212508. */
  212509. static int sqlite3Fts5UnicodeFold(int c, int eRemoveDiacritic){
  212510. /* Each entry in the following array defines a rule for folding a range
  212511. ** of codepoints to lower case. The rule applies to a range of nRange
  212512. ** codepoints starting at codepoint iCode.
  212513. **
  212514. ** If the least significant bit in flags is clear, then the rule applies
  212515. ** to all nRange codepoints (i.e. all nRange codepoints are upper case and
  212516. ** need to be folded). Or, if it is set, then the rule only applies to
  212517. ** every second codepoint in the range, starting with codepoint C.
  212518. **
  212519. ** The 7 most significant bits in flags are an index into the aiOff[]
  212520. ** array. If a specific codepoint C does require folding, then its lower
  212521. ** case equivalent is ((C + aiOff[flags>>1]) & 0xFFFF).
  212522. **
  212523. ** The contents of this array are generated by parsing the CaseFolding.txt
  212524. ** file distributed as part of the "Unicode Character Database". See
  212525. ** http://www.unicode.org for details.
  212526. */
  212527. static const struct TableEntry {
  212528. unsigned short iCode;
  212529. unsigned char flags;
  212530. unsigned char nRange;
  212531. } aEntry[] = {
  212532. {65, 14, 26}, {181, 64, 1}, {192, 14, 23},
  212533. {216, 14, 7}, {256, 1, 48}, {306, 1, 6},
  212534. {313, 1, 16}, {330, 1, 46}, {376, 116, 1},
  212535. {377, 1, 6}, {383, 104, 1}, {385, 50, 1},
  212536. {386, 1, 4}, {390, 44, 1}, {391, 0, 1},
  212537. {393, 42, 2}, {395, 0, 1}, {398, 32, 1},
  212538. {399, 38, 1}, {400, 40, 1}, {401, 0, 1},
  212539. {403, 42, 1}, {404, 46, 1}, {406, 52, 1},
  212540. {407, 48, 1}, {408, 0, 1}, {412, 52, 1},
  212541. {413, 54, 1}, {415, 56, 1}, {416, 1, 6},
  212542. {422, 60, 1}, {423, 0, 1}, {425, 60, 1},
  212543. {428, 0, 1}, {430, 60, 1}, {431, 0, 1},
  212544. {433, 58, 2}, {435, 1, 4}, {439, 62, 1},
  212545. {440, 0, 1}, {444, 0, 1}, {452, 2, 1},
  212546. {453, 0, 1}, {455, 2, 1}, {456, 0, 1},
  212547. {458, 2, 1}, {459, 1, 18}, {478, 1, 18},
  212548. {497, 2, 1}, {498, 1, 4}, {502, 122, 1},
  212549. {503, 134, 1}, {504, 1, 40}, {544, 110, 1},
  212550. {546, 1, 18}, {570, 70, 1}, {571, 0, 1},
  212551. {573, 108, 1}, {574, 68, 1}, {577, 0, 1},
  212552. {579, 106, 1}, {580, 28, 1}, {581, 30, 1},
  212553. {582, 1, 10}, {837, 36, 1}, {880, 1, 4},
  212554. {886, 0, 1}, {902, 18, 1}, {904, 16, 3},
  212555. {908, 26, 1}, {910, 24, 2}, {913, 14, 17},
  212556. {931, 14, 9}, {962, 0, 1}, {975, 4, 1},
  212557. {976, 140, 1}, {977, 142, 1}, {981, 146, 1},
  212558. {982, 144, 1}, {984, 1, 24}, {1008, 136, 1},
  212559. {1009, 138, 1}, {1012, 130, 1}, {1013, 128, 1},
  212560. {1015, 0, 1}, {1017, 152, 1}, {1018, 0, 1},
  212561. {1021, 110, 3}, {1024, 34, 16}, {1040, 14, 32},
  212562. {1120, 1, 34}, {1162, 1, 54}, {1216, 6, 1},
  212563. {1217, 1, 14}, {1232, 1, 88}, {1329, 22, 38},
  212564. {4256, 66, 38}, {4295, 66, 1}, {4301, 66, 1},
  212565. {7680, 1, 150}, {7835, 132, 1}, {7838, 96, 1},
  212566. {7840, 1, 96}, {7944, 150, 8}, {7960, 150, 6},
  212567. {7976, 150, 8}, {7992, 150, 8}, {8008, 150, 6},
  212568. {8025, 151, 8}, {8040, 150, 8}, {8072, 150, 8},
  212569. {8088, 150, 8}, {8104, 150, 8}, {8120, 150, 2},
  212570. {8122, 126, 2}, {8124, 148, 1}, {8126, 100, 1},
  212571. {8136, 124, 4}, {8140, 148, 1}, {8152, 150, 2},
  212572. {8154, 120, 2}, {8168, 150, 2}, {8170, 118, 2},
  212573. {8172, 152, 1}, {8184, 112, 2}, {8186, 114, 2},
  212574. {8188, 148, 1}, {8486, 98, 1}, {8490, 92, 1},
  212575. {8491, 94, 1}, {8498, 12, 1}, {8544, 8, 16},
  212576. {8579, 0, 1}, {9398, 10, 26}, {11264, 22, 47},
  212577. {11360, 0, 1}, {11362, 88, 1}, {11363, 102, 1},
  212578. {11364, 90, 1}, {11367, 1, 6}, {11373, 84, 1},
  212579. {11374, 86, 1}, {11375, 80, 1}, {11376, 82, 1},
  212580. {11378, 0, 1}, {11381, 0, 1}, {11390, 78, 2},
  212581. {11392, 1, 100}, {11499, 1, 4}, {11506, 0, 1},
  212582. {42560, 1, 46}, {42624, 1, 24}, {42786, 1, 14},
  212583. {42802, 1, 62}, {42873, 1, 4}, {42877, 76, 1},
  212584. {42878, 1, 10}, {42891, 0, 1}, {42893, 74, 1},
  212585. {42896, 1, 4}, {42912, 1, 10}, {42922, 72, 1},
  212586. {65313, 14, 26},
  212587. };
  212588. static const unsigned short aiOff[] = {
  212589. 1, 2, 8, 15, 16, 26, 28, 32,
  212590. 37, 38, 40, 48, 63, 64, 69, 71,
  212591. 79, 80, 116, 202, 203, 205, 206, 207,
  212592. 209, 210, 211, 213, 214, 217, 218, 219,
  212593. 775, 7264, 10792, 10795, 23228, 23256, 30204, 54721,
  212594. 54753, 54754, 54756, 54787, 54793, 54809, 57153, 57274,
  212595. 57921, 58019, 58363, 61722, 65268, 65341, 65373, 65406,
  212596. 65408, 65410, 65415, 65424, 65436, 65439, 65450, 65462,
  212597. 65472, 65476, 65478, 65480, 65482, 65488, 65506, 65511,
  212598. 65514, 65521, 65527, 65528, 65529,
  212599. };
  212600. int ret = c;
  212601. assert( sizeof(unsigned short)==2 && sizeof(unsigned char)==1 );
  212602. if( c<128 ){
  212603. if( c>='A' && c<='Z' ) ret = c + ('a' - 'A');
  212604. }else if( c<65536 ){
  212605. const struct TableEntry *p;
  212606. int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
  212607. int iLo = 0;
  212608. int iRes = -1;
  212609. assert( c>aEntry[0].iCode );
  212610. while( iHi>=iLo ){
  212611. int iTest = (iHi + iLo) / 2;
  212612. int cmp = (c - aEntry[iTest].iCode);
  212613. if( cmp>=0 ){
  212614. iRes = iTest;
  212615. iLo = iTest+1;
  212616. }else{
  212617. iHi = iTest-1;
  212618. }
  212619. }
  212620. assert( iRes>=0 && c>=aEntry[iRes].iCode );
  212621. p = &aEntry[iRes];
  212622. if( c<(p->iCode + p->nRange) && 0==(0x01 & p->flags & (p->iCode ^ c)) ){
  212623. ret = (c + (aiOff[p->flags>>1])) & 0x0000FFFF;
  212624. assert( ret>0 );
  212625. }
  212626. if( eRemoveDiacritic ){
  212627. ret = fts5_remove_diacritic(ret, eRemoveDiacritic==2);
  212628. }
  212629. }
  212630. else if( c>=66560 && c<66600 ){
  212631. ret = c + 40;
  212632. }
  212633. return ret;
  212634. }
  212635. static int sqlite3Fts5UnicodeCatParse(const char *zCat, u8 *aArray){
  212636. aArray[0] = 1;
  212637. switch( zCat[0] ){
  212638. case 'C':
  212639. switch( zCat[1] ){
  212640. case 'c': aArray[1] = 1; break;
  212641. case 'f': aArray[2] = 1; break;
  212642. case 'n': aArray[3] = 1; break;
  212643. case 's': aArray[4] = 1; break;
  212644. case 'o': aArray[31] = 1; break;
  212645. case '*':
  212646. aArray[1] = 1;
  212647. aArray[2] = 1;
  212648. aArray[3] = 1;
  212649. aArray[4] = 1;
  212650. aArray[31] = 1;
  212651. break;
  212652. default: return 1; }
  212653. break;
  212654. case 'L':
  212655. switch( zCat[1] ){
  212656. case 'l': aArray[5] = 1; break;
  212657. case 'm': aArray[6] = 1; break;
  212658. case 'o': aArray[7] = 1; break;
  212659. case 't': aArray[8] = 1; break;
  212660. case 'u': aArray[9] = 1; break;
  212661. case 'C': aArray[30] = 1; break;
  212662. case '*':
  212663. aArray[5] = 1;
  212664. aArray[6] = 1;
  212665. aArray[7] = 1;
  212666. aArray[8] = 1;
  212667. aArray[9] = 1;
  212668. aArray[30] = 1;
  212669. break;
  212670. default: return 1; }
  212671. break;
  212672. case 'M':
  212673. switch( zCat[1] ){
  212674. case 'c': aArray[10] = 1; break;
  212675. case 'e': aArray[11] = 1; break;
  212676. case 'n': aArray[12] = 1; break;
  212677. case '*':
  212678. aArray[10] = 1;
  212679. aArray[11] = 1;
  212680. aArray[12] = 1;
  212681. break;
  212682. default: return 1; }
  212683. break;
  212684. case 'N':
  212685. switch( zCat[1] ){
  212686. case 'd': aArray[13] = 1; break;
  212687. case 'l': aArray[14] = 1; break;
  212688. case 'o': aArray[15] = 1; break;
  212689. case '*':
  212690. aArray[13] = 1;
  212691. aArray[14] = 1;
  212692. aArray[15] = 1;
  212693. break;
  212694. default: return 1; }
  212695. break;
  212696. case 'P':
  212697. switch( zCat[1] ){
  212698. case 'c': aArray[16] = 1; break;
  212699. case 'd': aArray[17] = 1; break;
  212700. case 'e': aArray[18] = 1; break;
  212701. case 'f': aArray[19] = 1; break;
  212702. case 'i': aArray[20] = 1; break;
  212703. case 'o': aArray[21] = 1; break;
  212704. case 's': aArray[22] = 1; break;
  212705. case '*':
  212706. aArray[16] = 1;
  212707. aArray[17] = 1;
  212708. aArray[18] = 1;
  212709. aArray[19] = 1;
  212710. aArray[20] = 1;
  212711. aArray[21] = 1;
  212712. aArray[22] = 1;
  212713. break;
  212714. default: return 1; }
  212715. break;
  212716. case 'S':
  212717. switch( zCat[1] ){
  212718. case 'c': aArray[23] = 1; break;
  212719. case 'k': aArray[24] = 1; break;
  212720. case 'm': aArray[25] = 1; break;
  212721. case 'o': aArray[26] = 1; break;
  212722. case '*':
  212723. aArray[23] = 1;
  212724. aArray[24] = 1;
  212725. aArray[25] = 1;
  212726. aArray[26] = 1;
  212727. break;
  212728. default: return 1; }
  212729. break;
  212730. case 'Z':
  212731. switch( zCat[1] ){
  212732. case 'l': aArray[27] = 1; break;
  212733. case 'p': aArray[28] = 1; break;
  212734. case 's': aArray[29] = 1; break;
  212735. case '*':
  212736. aArray[27] = 1;
  212737. aArray[28] = 1;
  212738. aArray[29] = 1;
  212739. break;
  212740. default: return 1; }
  212741. break;
  212742. }
  212743. return 0;
  212744. }
  212745. static u16 aFts5UnicodeBlock[] = {
  212746. 0, 1471, 1753, 1760, 1760, 1760, 1760, 1760, 1760, 1760,
  212747. 1760, 1760, 1760, 1760, 1760, 1763, 1765,
  212748. };
  212749. static u16 aFts5UnicodeMap[] = {
  212750. 0, 32, 33, 36, 37, 40, 41, 42, 43, 44,
  212751. 45, 46, 48, 58, 60, 63, 65, 91, 92, 93,
  212752. 94, 95, 96, 97, 123, 124, 125, 126, 127, 160,
  212753. 161, 162, 166, 167, 168, 169, 170, 171, 172, 173,
  212754. 174, 175, 176, 177, 178, 180, 181, 182, 184, 185,
  212755. 186, 187, 188, 191, 192, 215, 216, 223, 247, 248,
  212756. 256, 312, 313, 329, 330, 377, 383, 385, 387, 388,
  212757. 391, 394, 396, 398, 402, 403, 405, 406, 409, 412,
  212758. 414, 415, 417, 418, 423, 427, 428, 431, 434, 436,
  212759. 437, 440, 442, 443, 444, 446, 448, 452, 453, 454,
  212760. 455, 456, 457, 458, 459, 460, 461, 477, 478, 496,
  212761. 497, 498, 499, 500, 503, 505, 506, 564, 570, 572,
  212762. 573, 575, 577, 580, 583, 584, 592, 660, 661, 688,
  212763. 706, 710, 722, 736, 741, 748, 749, 750, 751, 768,
  212764. 880, 884, 885, 886, 890, 891, 894, 900, 902, 903,
  212765. 904, 908, 910, 912, 913, 931, 940, 975, 977, 978,
  212766. 981, 984, 1008, 1012, 1014, 1015, 1018, 1020, 1021, 1072,
  212767. 1120, 1154, 1155, 1160, 1162, 1217, 1231, 1232, 1329, 1369,
  212768. 1370, 1377, 1417, 1418, 1423, 1425, 1470, 1471, 1472, 1473,
  212769. 1475, 1476, 1478, 1479, 1488, 1520, 1523, 1536, 1542, 1545,
  212770. 1547, 1548, 1550, 1552, 1563, 1566, 1568, 1600, 1601, 1611,
  212771. 1632, 1642, 1646, 1648, 1649, 1748, 1749, 1750, 1757, 1758,
  212772. 1759, 1765, 1767, 1769, 1770, 1774, 1776, 1786, 1789, 1791,
  212773. 1792, 1807, 1808, 1809, 1810, 1840, 1869, 1958, 1969, 1984,
  212774. 1994, 2027, 2036, 2038, 2039, 2042, 2048, 2070, 2074, 2075,
  212775. 2084, 2085, 2088, 2089, 2096, 2112, 2137, 2142, 2208, 2210,
  212776. 2276, 2304, 2307, 2308, 2362, 2363, 2364, 2365, 2366, 2369,
  212777. 2377, 2381, 2382, 2384, 2385, 2392, 2402, 2404, 2406, 2416,
  212778. 2417, 2418, 2425, 2433, 2434, 2437, 2447, 2451, 2474, 2482,
  212779. 2486, 2492, 2493, 2494, 2497, 2503, 2507, 2509, 2510, 2519,
  212780. 2524, 2527, 2530, 2534, 2544, 2546, 2548, 2554, 2555, 2561,
  212781. 2563, 2565, 2575, 2579, 2602, 2610, 2613, 2616, 2620, 2622,
  212782. 2625, 2631, 2635, 2641, 2649, 2654, 2662, 2672, 2674, 2677,
  212783. 2689, 2691, 2693, 2703, 2707, 2730, 2738, 2741, 2748, 2749,
  212784. 2750, 2753, 2759, 2761, 2763, 2765, 2768, 2784, 2786, 2790,
  212785. 2800, 2801, 2817, 2818, 2821, 2831, 2835, 2858, 2866, 2869,
  212786. 2876, 2877, 2878, 2879, 2880, 2881, 2887, 2891, 2893, 2902,
  212787. 2903, 2908, 2911, 2914, 2918, 2928, 2929, 2930, 2946, 2947,
  212788. 2949, 2958, 2962, 2969, 2972, 2974, 2979, 2984, 2990, 3006,
  212789. 3008, 3009, 3014, 3018, 3021, 3024, 3031, 3046, 3056, 3059,
  212790. 3065, 3066, 3073, 3077, 3086, 3090, 3114, 3125, 3133, 3134,
  212791. 3137, 3142, 3146, 3157, 3160, 3168, 3170, 3174, 3192, 3199,
  212792. 3202, 3205, 3214, 3218, 3242, 3253, 3260, 3261, 3262, 3263,
  212793. 3264, 3270, 3271, 3274, 3276, 3285, 3294, 3296, 3298, 3302,
  212794. 3313, 3330, 3333, 3342, 3346, 3389, 3390, 3393, 3398, 3402,
  212795. 3405, 3406, 3415, 3424, 3426, 3430, 3440, 3449, 3450, 3458,
  212796. 3461, 3482, 3507, 3517, 3520, 3530, 3535, 3538, 3542, 3544,
  212797. 3570, 3572, 3585, 3633, 3634, 3636, 3647, 3648, 3654, 3655,
  212798. 3663, 3664, 3674, 3713, 3716, 3719, 3722, 3725, 3732, 3737,
  212799. 3745, 3749, 3751, 3754, 3757, 3761, 3762, 3764, 3771, 3773,
  212800. 3776, 3782, 3784, 3792, 3804, 3840, 3841, 3844, 3859, 3860,
  212801. 3861, 3864, 3866, 3872, 3882, 3892, 3893, 3894, 3895, 3896,
  212802. 3897, 3898, 3899, 3900, 3901, 3902, 3904, 3913, 3953, 3967,
  212803. 3968, 3973, 3974, 3976, 3981, 3993, 4030, 4038, 4039, 4046,
  212804. 4048, 4053, 4057, 4096, 4139, 4141, 4145, 4146, 4152, 4153,
  212805. 4155, 4157, 4159, 4160, 4170, 4176, 4182, 4184, 4186, 4190,
  212806. 4193, 4194, 4197, 4199, 4206, 4209, 4213, 4226, 4227, 4229,
  212807. 4231, 4237, 4238, 4239, 4240, 4250, 4253, 4254, 4256, 4295,
  212808. 4301, 4304, 4347, 4348, 4349, 4682, 4688, 4696, 4698, 4704,
  212809. 4746, 4752, 4786, 4792, 4800, 4802, 4808, 4824, 4882, 4888,
  212810. 4957, 4960, 4969, 4992, 5008, 5024, 5120, 5121, 5741, 5743,
  212811. 5760, 5761, 5787, 5788, 5792, 5867, 5870, 5888, 5902, 5906,
  212812. 5920, 5938, 5941, 5952, 5970, 5984, 5998, 6002, 6016, 6068,
  212813. 6070, 6071, 6078, 6086, 6087, 6089, 6100, 6103, 6104, 6107,
  212814. 6108, 6109, 6112, 6128, 6144, 6150, 6151, 6155, 6158, 6160,
  212815. 6176, 6211, 6212, 6272, 6313, 6314, 6320, 6400, 6432, 6435,
  212816. 6439, 6441, 6448, 6450, 6451, 6457, 6464, 6468, 6470, 6480,
  212817. 6512, 6528, 6576, 6593, 6600, 6608, 6618, 6622, 6656, 6679,
  212818. 6681, 6686, 6688, 6741, 6742, 6743, 6744, 6752, 6753, 6754,
  212819. 6755, 6757, 6765, 6771, 6783, 6784, 6800, 6816, 6823, 6824,
  212820. 6912, 6916, 6917, 6964, 6965, 6966, 6971, 6972, 6973, 6978,
  212821. 6979, 6981, 6992, 7002, 7009, 7019, 7028, 7040, 7042, 7043,
  212822. 7073, 7074, 7078, 7080, 7082, 7083, 7084, 7086, 7088, 7098,
  212823. 7142, 7143, 7144, 7146, 7149, 7150, 7151, 7154, 7164, 7168,
  212824. 7204, 7212, 7220, 7222, 7227, 7232, 7245, 7248, 7258, 7288,
  212825. 7294, 7360, 7376, 7379, 7380, 7393, 7394, 7401, 7405, 7406,
  212826. 7410, 7412, 7413, 7424, 7468, 7531, 7544, 7545, 7579, 7616,
  212827. 7676, 7680, 7830, 7838, 7936, 7944, 7952, 7960, 7968, 7976,
  212828. 7984, 7992, 8000, 8008, 8016, 8025, 8027, 8029, 8031, 8033,
  212829. 8040, 8048, 8064, 8072, 8080, 8088, 8096, 8104, 8112, 8118,
  212830. 8120, 8124, 8125, 8126, 8127, 8130, 8134, 8136, 8140, 8141,
  212831. 8144, 8150, 8152, 8157, 8160, 8168, 8173, 8178, 8182, 8184,
  212832. 8188, 8189, 8192, 8203, 8208, 8214, 8216, 8217, 8218, 8219,
  212833. 8221, 8222, 8223, 8224, 8232, 8233, 8234, 8239, 8240, 8249,
  212834. 8250, 8251, 8255, 8257, 8260, 8261, 8262, 8263, 8274, 8275,
  212835. 8276, 8277, 8287, 8288, 8298, 8304, 8305, 8308, 8314, 8317,
  212836. 8318, 8319, 8320, 8330, 8333, 8334, 8336, 8352, 8400, 8413,
  212837. 8417, 8418, 8421, 8448, 8450, 8451, 8455, 8456, 8458, 8459,
  212838. 8462, 8464, 8467, 8468, 8469, 8470, 8472, 8473, 8478, 8484,
  212839. 8485, 8486, 8487, 8488, 8489, 8490, 8494, 8495, 8496, 8500,
  212840. 8501, 8505, 8506, 8508, 8510, 8512, 8517, 8519, 8522, 8523,
  212841. 8524, 8526, 8527, 8528, 8544, 8579, 8581, 8585, 8592, 8597,
  212842. 8602, 8604, 8608, 8609, 8611, 8612, 8614, 8615, 8622, 8623,
  212843. 8654, 8656, 8658, 8659, 8660, 8661, 8692, 8960, 8968, 8972,
  212844. 8992, 8994, 9001, 9002, 9003, 9084, 9085, 9115, 9140, 9180,
  212845. 9186, 9216, 9280, 9312, 9372, 9450, 9472, 9655, 9656, 9665,
  212846. 9666, 9720, 9728, 9839, 9840, 9985, 10088, 10089, 10090, 10091,
  212847. 10092, 10093, 10094, 10095, 10096, 10097, 10098, 10099, 10100, 10101,
  212848. 10102, 10132, 10176, 10181, 10182, 10183, 10214, 10215, 10216, 10217,
  212849. 10218, 10219, 10220, 10221, 10222, 10223, 10224, 10240, 10496, 10627,
  212850. 10628, 10629, 10630, 10631, 10632, 10633, 10634, 10635, 10636, 10637,
  212851. 10638, 10639, 10640, 10641, 10642, 10643, 10644, 10645, 10646, 10647,
  212852. 10648, 10649, 10712, 10713, 10714, 10715, 10716, 10748, 10749, 10750,
  212853. 11008, 11056, 11077, 11079, 11088, 11264, 11312, 11360, 11363, 11365,
  212854. 11367, 11374, 11377, 11378, 11380, 11381, 11383, 11388, 11390, 11393,
  212855. 11394, 11492, 11493, 11499, 11503, 11506, 11513, 11517, 11518, 11520,
  212856. 11559, 11565, 11568, 11631, 11632, 11647, 11648, 11680, 11688, 11696,
  212857. 11704, 11712, 11720, 11728, 11736, 11744, 11776, 11778, 11779, 11780,
  212858. 11781, 11782, 11785, 11786, 11787, 11788, 11789, 11790, 11799, 11800,
  212859. 11802, 11803, 11804, 11805, 11806, 11808, 11809, 11810, 11811, 11812,
  212860. 11813, 11814, 11815, 11816, 11817, 11818, 11823, 11824, 11834, 11904,
  212861. 11931, 12032, 12272, 12288, 12289, 12292, 12293, 12294, 12295, 12296,
  212862. 12297, 12298, 12299, 12300, 12301, 12302, 12303, 12304, 12305, 12306,
  212863. 12308, 12309, 12310, 12311, 12312, 12313, 12314, 12315, 12316, 12317,
  212864. 12318, 12320, 12321, 12330, 12334, 12336, 12337, 12342, 12344, 12347,
  212865. 12348, 12349, 12350, 12353, 12441, 12443, 12445, 12447, 12448, 12449,
  212866. 12539, 12540, 12543, 12549, 12593, 12688, 12690, 12694, 12704, 12736,
  212867. 12784, 12800, 12832, 12842, 12872, 12880, 12881, 12896, 12928, 12938,
  212868. 12977, 12992, 13056, 13312, 19893, 19904, 19968, 40908, 40960, 40981,
  212869. 40982, 42128, 42192, 42232, 42238, 42240, 42508, 42509, 42512, 42528,
  212870. 42538, 42560, 42606, 42607, 42608, 42611, 42612, 42622, 42623, 42624,
  212871. 42655, 42656, 42726, 42736, 42738, 42752, 42775, 42784, 42786, 42800,
  212872. 42802, 42864, 42865, 42873, 42878, 42888, 42889, 42891, 42896, 42912,
  212873. 43000, 43002, 43003, 43010, 43011, 43014, 43015, 43019, 43020, 43043,
  212874. 43045, 43047, 43048, 43056, 43062, 43064, 43065, 43072, 43124, 43136,
  212875. 43138, 43188, 43204, 43214, 43216, 43232, 43250, 43256, 43259, 43264,
  212876. 43274, 43302, 43310, 43312, 43335, 43346, 43359, 43360, 43392, 43395,
  212877. 43396, 43443, 43444, 43446, 43450, 43452, 43453, 43457, 43471, 43472,
  212878. 43486, 43520, 43561, 43567, 43569, 43571, 43573, 43584, 43587, 43588,
  212879. 43596, 43597, 43600, 43612, 43616, 43632, 43633, 43639, 43642, 43643,
  212880. 43648, 43696, 43697, 43698, 43701, 43703, 43705, 43710, 43712, 43713,
  212881. 43714, 43739, 43741, 43742, 43744, 43755, 43756, 43758, 43760, 43762,
  212882. 43763, 43765, 43766, 43777, 43785, 43793, 43808, 43816, 43968, 44003,
  212883. 44005, 44006, 44008, 44009, 44011, 44012, 44013, 44016, 44032, 55203,
  212884. 55216, 55243, 55296, 56191, 56319, 57343, 57344, 63743, 63744, 64112,
  212885. 64256, 64275, 64285, 64286, 64287, 64297, 64298, 64312, 64318, 64320,
  212886. 64323, 64326, 64434, 64467, 64830, 64831, 64848, 64914, 65008, 65020,
  212887. 65021, 65024, 65040, 65047, 65048, 65049, 65056, 65072, 65073, 65075,
  212888. 65077, 65078, 65079, 65080, 65081, 65082, 65083, 65084, 65085, 65086,
  212889. 65087, 65088, 65089, 65090, 65091, 65092, 65093, 65095, 65096, 65097,
  212890. 65101, 65104, 65108, 65112, 65113, 65114, 65115, 65116, 65117, 65118,
  212891. 65119, 65122, 65123, 65124, 65128, 65129, 65130, 65136, 65142, 65279,
  212892. 65281, 65284, 65285, 65288, 65289, 65290, 65291, 65292, 65293, 65294,
  212893. 65296, 65306, 65308, 65311, 65313, 65339, 65340, 65341, 65342, 65343,
  212894. 65344, 65345, 65371, 65372, 65373, 65374, 65375, 65376, 65377, 65378,
  212895. 65379, 65380, 65382, 65392, 65393, 65438, 65440, 65474, 65482, 65490,
  212896. 65498, 65504, 65506, 65507, 65508, 65509, 65512, 65513, 65517, 65529,
  212897. 65532, 0, 13, 40, 60, 63, 80, 128, 256, 263,
  212898. 311, 320, 373, 377, 394, 400, 464, 509, 640, 672,
  212899. 768, 800, 816, 833, 834, 842, 896, 927, 928, 968,
  212900. 976, 977, 1024, 1064, 1104, 1184, 2048, 2056, 2058, 2103,
  212901. 2108, 2111, 2135, 2136, 2304, 2326, 2335, 2336, 2367, 2432,
  212902. 2494, 2560, 2561, 2565, 2572, 2576, 2581, 2585, 2616, 2623,
  212903. 2624, 2640, 2656, 2685, 2687, 2816, 2873, 2880, 2904, 2912,
  212904. 2936, 3072, 3680, 4096, 4097, 4098, 4099, 4152, 4167, 4178,
  212905. 4198, 4224, 4226, 4227, 4272, 4275, 4279, 4281, 4283, 4285,
  212906. 4286, 4304, 4336, 4352, 4355, 4391, 4396, 4397, 4406, 4416,
  212907. 4480, 4482, 4483, 4531, 4534, 4543, 4545, 4549, 4560, 5760,
  212908. 5803, 5804, 5805, 5806, 5808, 5814, 5815, 5824, 8192, 9216,
  212909. 9328, 12288, 26624, 28416, 28496, 28497, 28559, 28563, 45056, 53248,
  212910. 53504, 53545, 53605, 53607, 53610, 53613, 53619, 53627, 53635, 53637,
  212911. 53644, 53674, 53678, 53760, 53826, 53829, 54016, 54112, 54272, 54298,
  212912. 54324, 54350, 54358, 54376, 54402, 54428, 54430, 54434, 54437, 54441,
  212913. 54446, 54454, 54459, 54461, 54469, 54480, 54506, 54532, 54535, 54541,
  212914. 54550, 54558, 54584, 54587, 54592, 54598, 54602, 54610, 54636, 54662,
  212915. 54688, 54714, 54740, 54766, 54792, 54818, 54844, 54870, 54896, 54922,
  212916. 54952, 54977, 54978, 55003, 55004, 55010, 55035, 55036, 55061, 55062,
  212917. 55068, 55093, 55094, 55119, 55120, 55126, 55151, 55152, 55177, 55178,
  212918. 55184, 55209, 55210, 55235, 55236, 55242, 55246, 60928, 60933, 60961,
  212919. 60964, 60967, 60969, 60980, 60985, 60987, 60994, 60999, 61001, 61003,
  212920. 61005, 61009, 61012, 61015, 61017, 61019, 61021, 61023, 61025, 61028,
  212921. 61031, 61036, 61044, 61049, 61054, 61056, 61067, 61089, 61093, 61099,
  212922. 61168, 61440, 61488, 61600, 61617, 61633, 61649, 61696, 61712, 61744,
  212923. 61808, 61926, 61968, 62016, 62032, 62208, 62256, 62263, 62336, 62368,
  212924. 62406, 62432, 62464, 62528, 62530, 62713, 62720, 62784, 62800, 62971,
  212925. 63045, 63104, 63232, 0, 42710, 42752, 46900, 46912, 47133, 63488,
  212926. 1, 32, 256, 0, 65533,
  212927. };
  212928. static u16 aFts5UnicodeData[] = {
  212929. 1025, 61, 117, 55, 117, 54, 50, 53, 57, 53,
  212930. 49, 85, 333, 85, 121, 85, 841, 54, 53, 50,
  212931. 56, 48, 56, 837, 54, 57, 50, 57, 1057, 61,
  212932. 53, 151, 58, 53, 56, 58, 39, 52, 57, 34,
  212933. 58, 56, 58, 57, 79, 56, 37, 85, 56, 47,
  212934. 39, 51, 111, 53, 745, 57, 233, 773, 57, 261,
  212935. 1822, 37, 542, 37, 1534, 222, 69, 73, 37, 126,
  212936. 126, 73, 69, 137, 37, 73, 37, 105, 101, 73,
  212937. 37, 73, 37, 190, 158, 37, 126, 126, 73, 37,
  212938. 126, 94, 37, 39, 94, 69, 135, 41, 40, 37,
  212939. 41, 40, 37, 41, 40, 37, 542, 37, 606, 37,
  212940. 41, 40, 37, 126, 73, 37, 1886, 197, 73, 37,
  212941. 73, 69, 126, 105, 37, 286, 2181, 39, 869, 582,
  212942. 152, 390, 472, 166, 248, 38, 56, 38, 568, 3596,
  212943. 158, 38, 56, 94, 38, 101, 53, 88, 41, 53,
  212944. 105, 41, 73, 37, 553, 297, 1125, 94, 37, 105,
  212945. 101, 798, 133, 94, 57, 126, 94, 37, 1641, 1541,
  212946. 1118, 58, 172, 75, 1790, 478, 37, 2846, 1225, 38,
  212947. 213, 1253, 53, 49, 55, 1452, 49, 44, 53, 76,
  212948. 53, 76, 53, 44, 871, 103, 85, 162, 121, 85,
  212949. 55, 85, 90, 364, 53, 85, 1031, 38, 327, 684,
  212950. 333, 149, 71, 44, 3175, 53, 39, 236, 34, 58,
  212951. 204, 70, 76, 58, 140, 71, 333, 103, 90, 39,
  212952. 469, 34, 39, 44, 967, 876, 2855, 364, 39, 333,
  212953. 1063, 300, 70, 58, 117, 38, 711, 140, 38, 300,
  212954. 38, 108, 38, 172, 501, 807, 108, 53, 39, 359,
  212955. 876, 108, 42, 1735, 44, 42, 44, 39, 106, 268,
  212956. 138, 44, 74, 39, 236, 327, 76, 85, 333, 53,
  212957. 38, 199, 231, 44, 74, 263, 71, 711, 231, 39,
  212958. 135, 44, 39, 106, 140, 74, 74, 44, 39, 42,
  212959. 71, 103, 76, 333, 71, 87, 207, 58, 55, 76,
  212960. 42, 199, 71, 711, 231, 71, 71, 71, 44, 106,
  212961. 76, 76, 108, 44, 135, 39, 333, 76, 103, 44,
  212962. 76, 42, 295, 103, 711, 231, 71, 167, 44, 39,
  212963. 106, 172, 76, 42, 74, 44, 39, 71, 76, 333,
  212964. 53, 55, 44, 74, 263, 71, 711, 231, 71, 167,
  212965. 44, 39, 42, 44, 42, 140, 74, 74, 44, 44,
  212966. 42, 71, 103, 76, 333, 58, 39, 207, 44, 39,
  212967. 199, 103, 135, 71, 39, 71, 71, 103, 391, 74,
  212968. 44, 74, 106, 106, 44, 39, 42, 333, 111, 218,
  212969. 55, 58, 106, 263, 103, 743, 327, 167, 39, 108,
  212970. 138, 108, 140, 76, 71, 71, 76, 333, 239, 58,
  212971. 74, 263, 103, 743, 327, 167, 44, 39, 42, 44,
  212972. 170, 44, 74, 74, 76, 74, 39, 71, 76, 333,
  212973. 71, 74, 263, 103, 1319, 39, 106, 140, 106, 106,
  212974. 44, 39, 42, 71, 76, 333, 207, 58, 199, 74,
  212975. 583, 775, 295, 39, 231, 44, 106, 108, 44, 266,
  212976. 74, 53, 1543, 44, 71, 236, 55, 199, 38, 268,
  212977. 53, 333, 85, 71, 39, 71, 39, 39, 135, 231,
  212978. 103, 39, 39, 71, 135, 44, 71, 204, 76, 39,
  212979. 167, 38, 204, 333, 135, 39, 122, 501, 58, 53,
  212980. 122, 76, 218, 333, 335, 58, 44, 58, 44, 58,
  212981. 44, 54, 50, 54, 50, 74, 263, 1159, 460, 42,
  212982. 172, 53, 76, 167, 364, 1164, 282, 44, 218, 90,
  212983. 181, 154, 85, 1383, 74, 140, 42, 204, 42, 76,
  212984. 74, 76, 39, 333, 213, 199, 74, 76, 135, 108,
  212985. 39, 106, 71, 234, 103, 140, 423, 44, 74, 76,
  212986. 202, 44, 39, 42, 333, 106, 44, 90, 1225, 41,
  212987. 41, 1383, 53, 38, 10631, 135, 231, 39, 135, 1319,
  212988. 135, 1063, 135, 231, 39, 135, 487, 1831, 135, 2151,
  212989. 108, 309, 655, 519, 346, 2727, 49, 19847, 85, 551,
  212990. 61, 839, 54, 50, 2407, 117, 110, 423, 135, 108,
  212991. 583, 108, 85, 583, 76, 423, 103, 76, 1671, 76,
  212992. 42, 236, 266, 44, 74, 364, 117, 38, 117, 55,
  212993. 39, 44, 333, 335, 213, 49, 149, 108, 61, 333,
  212994. 1127, 38, 1671, 1319, 44, 39, 2247, 935, 108, 138,
  212995. 76, 106, 74, 44, 202, 108, 58, 85, 333, 967,
  212996. 167, 1415, 554, 231, 74, 333, 47, 1114, 743, 76,
  212997. 106, 85, 1703, 42, 44, 42, 236, 44, 42, 44,
  212998. 74, 268, 202, 332, 44, 333, 333, 245, 38, 213,
  212999. 140, 42, 1511, 44, 42, 172, 42, 44, 170, 44,
  213000. 74, 231, 333, 245, 346, 300, 314, 76, 42, 967,
  213001. 42, 140, 74, 76, 42, 44, 74, 71, 333, 1415,
  213002. 44, 42, 76, 106, 44, 42, 108, 74, 149, 1159,
  213003. 266, 268, 74, 76, 181, 333, 103, 333, 967, 198,
  213004. 85, 277, 108, 53, 428, 42, 236, 135, 44, 135,
  213005. 74, 44, 71, 1413, 2022, 421, 38, 1093, 1190, 1260,
  213006. 140, 4830, 261, 3166, 261, 265, 197, 201, 261, 265,
  213007. 261, 265, 197, 201, 261, 41, 41, 41, 94, 229,
  213008. 265, 453, 261, 264, 261, 264, 261, 264, 165, 69,
  213009. 137, 40, 56, 37, 120, 101, 69, 137, 40, 120,
  213010. 133, 69, 137, 120, 261, 169, 120, 101, 69, 137,
  213011. 40, 88, 381, 162, 209, 85, 52, 51, 54, 84,
  213012. 51, 54, 52, 277, 59, 60, 162, 61, 309, 52,
  213013. 51, 149, 80, 117, 57, 54, 50, 373, 57, 53,
  213014. 48, 341, 61, 162, 194, 47, 38, 207, 121, 54,
  213015. 50, 38, 335, 121, 54, 50, 422, 855, 428, 139,
  213016. 44, 107, 396, 90, 41, 154, 41, 90, 37, 105,
  213017. 69, 105, 37, 58, 41, 90, 57, 169, 218, 41,
  213018. 58, 41, 58, 41, 58, 137, 58, 37, 137, 37,
  213019. 135, 37, 90, 69, 73, 185, 94, 101, 58, 57,
  213020. 90, 37, 58, 527, 1134, 94, 142, 47, 185, 186,
  213021. 89, 154, 57, 90, 57, 90, 57, 250, 57, 1018,
  213022. 89, 90, 57, 58, 57, 1018, 8601, 282, 153, 666,
  213023. 89, 250, 54, 50, 2618, 57, 986, 825, 1306, 217,
  213024. 602, 1274, 378, 1935, 2522, 719, 5882, 57, 314, 57,
  213025. 1754, 281, 3578, 57, 4634, 3322, 54, 50, 54, 50,
  213026. 54, 50, 54, 50, 54, 50, 54, 50, 54, 50,
  213027. 975, 1434, 185, 54, 50, 1017, 54, 50, 54, 50,
  213028. 54, 50, 54, 50, 54, 50, 537, 8218, 4217, 54,
  213029. 50, 54, 50, 54, 50, 54, 50, 54, 50, 54,
  213030. 50, 54, 50, 54, 50, 54, 50, 54, 50, 54,
  213031. 50, 2041, 54, 50, 54, 50, 1049, 54, 50, 8281,
  213032. 1562, 697, 90, 217, 346, 1513, 1509, 126, 73, 69,
  213033. 254, 105, 37, 94, 37, 94, 165, 70, 105, 37,
  213034. 3166, 37, 218, 158, 108, 94, 149, 47, 85, 1221,
  213035. 37, 37, 1799, 38, 53, 44, 743, 231, 231, 231,
  213036. 231, 231, 231, 231, 231, 1036, 85, 52, 51, 52,
  213037. 51, 117, 52, 51, 53, 52, 51, 309, 49, 85,
  213038. 49, 53, 52, 51, 85, 52, 51, 54, 50, 54,
  213039. 50, 54, 50, 54, 50, 181, 38, 341, 81, 858,
  213040. 2874, 6874, 410, 61, 117, 58, 38, 39, 46, 54,
  213041. 50, 54, 50, 54, 50, 54, 50, 54, 50, 90,
  213042. 54, 50, 54, 50, 54, 50, 54, 50, 49, 54,
  213043. 82, 58, 302, 140, 74, 49, 166, 90, 110, 38,
  213044. 39, 53, 90, 2759, 76, 88, 70, 39, 49, 2887,
  213045. 53, 102, 39, 1319, 3015, 90, 143, 346, 871, 1178,
  213046. 519, 1018, 335, 986, 271, 58, 495, 1050, 335, 1274,
  213047. 495, 2042, 8218, 39, 39, 2074, 39, 39, 679, 38,
  213048. 36583, 1786, 1287, 198, 85, 8583, 38, 117, 519, 333,
  213049. 71, 1502, 39, 44, 107, 53, 332, 53, 38, 798,
  213050. 44, 2247, 334, 76, 213, 760, 294, 88, 478, 69,
  213051. 2014, 38, 261, 190, 350, 38, 88, 158, 158, 382,
  213052. 70, 37, 231, 44, 103, 44, 135, 44, 743, 74,
  213053. 76, 42, 154, 207, 90, 55, 58, 1671, 149, 74,
  213054. 1607, 522, 44, 85, 333, 588, 199, 117, 39, 333,
  213055. 903, 268, 85, 743, 364, 74, 53, 935, 108, 42,
  213056. 1511, 44, 74, 140, 74, 44, 138, 437, 38, 333,
  213057. 85, 1319, 204, 74, 76, 74, 76, 103, 44, 263,
  213058. 44, 42, 333, 149, 519, 38, 199, 122, 39, 42,
  213059. 1543, 44, 39, 108, 71, 76, 167, 76, 39, 44,
  213060. 39, 71, 38, 85, 359, 42, 76, 74, 85, 39,
  213061. 70, 42, 44, 199, 199, 199, 231, 231, 1127, 74,
  213062. 44, 74, 44, 74, 53, 42, 44, 333, 39, 39,
  213063. 743, 1575, 36, 68, 68, 36, 63, 63, 11719, 3399,
  213064. 229, 165, 39, 44, 327, 57, 423, 167, 39, 71,
  213065. 71, 3463, 536, 11623, 54, 50, 2055, 1735, 391, 55,
  213066. 58, 524, 245, 54, 50, 53, 236, 53, 81, 80,
  213067. 54, 50, 54, 50, 54, 50, 54, 50, 54, 50,
  213068. 54, 50, 54, 50, 54, 50, 85, 54, 50, 149,
  213069. 112, 117, 149, 49, 54, 50, 54, 50, 54, 50,
  213070. 117, 57, 49, 121, 53, 55, 85, 167, 4327, 34,
  213071. 117, 55, 117, 54, 50, 53, 57, 53, 49, 85,
  213072. 333, 85, 121, 85, 841, 54, 53, 50, 56, 48,
  213073. 56, 837, 54, 57, 50, 57, 54, 50, 53, 54,
  213074. 50, 85, 327, 38, 1447, 70, 999, 199, 199, 199,
  213075. 103, 87, 57, 56, 58, 87, 58, 153, 90, 98,
  213076. 90, 391, 839, 615, 71, 487, 455, 3943, 117, 1455,
  213077. 314, 1710, 143, 570, 47, 410, 1466, 44, 935, 1575,
  213078. 999, 143, 551, 46, 263, 46, 967, 53, 1159, 263,
  213079. 53, 174, 1289, 1285, 2503, 333, 199, 39, 1415, 71,
  213080. 39, 743, 53, 271, 711, 207, 53, 839, 53, 1799,
  213081. 71, 39, 108, 76, 140, 135, 103, 871, 108, 44,
  213082. 271, 309, 935, 79, 53, 1735, 245, 711, 271, 615,
  213083. 271, 2343, 1007, 42, 44, 42, 1703, 492, 245, 655,
  213084. 333, 76, 42, 1447, 106, 140, 74, 76, 85, 34,
  213085. 149, 807, 333, 108, 1159, 172, 42, 268, 333, 149,
  213086. 76, 42, 1543, 106, 300, 74, 135, 149, 333, 1383,
  213087. 44, 42, 44, 74, 204, 42, 44, 333, 28135, 3182,
  213088. 149, 34279, 18215, 2215, 39, 1482, 140, 422, 71, 7898,
  213089. 1274, 1946, 74, 108, 122, 202, 258, 268, 90, 236,
  213090. 986, 140, 1562, 2138, 108, 58, 2810, 591, 841, 837,
  213091. 841, 229, 581, 841, 837, 41, 73, 41, 73, 137,
  213092. 265, 133, 37, 229, 357, 841, 837, 73, 137, 265,
  213093. 233, 837, 73, 137, 169, 41, 233, 837, 841, 837,
  213094. 841, 837, 841, 837, 841, 837, 841, 837, 841, 901,
  213095. 809, 57, 805, 57, 197, 809, 57, 805, 57, 197,
  213096. 809, 57, 805, 57, 197, 809, 57, 805, 57, 197,
  213097. 809, 57, 805, 57, 197, 94, 1613, 135, 871, 71,
  213098. 39, 39, 327, 135, 39, 39, 39, 39, 39, 39,
  213099. 103, 71, 39, 39, 39, 39, 39, 39, 71, 39,
  213100. 135, 231, 135, 135, 39, 327, 551, 103, 167, 551,
  213101. 89, 1434, 3226, 506, 474, 506, 506, 367, 1018, 1946,
  213102. 1402, 954, 1402, 314, 90, 1082, 218, 2266, 666, 1210,
  213103. 186, 570, 2042, 58, 5850, 154, 2010, 154, 794, 2266,
  213104. 378, 2266, 3738, 39, 39, 39, 39, 39, 39, 17351,
  213105. 34, 3074, 7692, 63, 63,
  213106. };
  213107. static int sqlite3Fts5UnicodeCategory(u32 iCode) {
  213108. int iRes = -1;
  213109. int iHi;
  213110. int iLo;
  213111. int ret;
  213112. u16 iKey;
  213113. if( iCode>=(1<<20) ){
  213114. return 0;
  213115. }
  213116. iLo = aFts5UnicodeBlock[(iCode>>16)];
  213117. iHi = aFts5UnicodeBlock[1+(iCode>>16)];
  213118. iKey = (iCode & 0xFFFF);
  213119. while( iHi>iLo ){
  213120. int iTest = (iHi + iLo) / 2;
  213121. assert( iTest>=iLo && iTest<iHi );
  213122. if( iKey>=aFts5UnicodeMap[iTest] ){
  213123. iRes = iTest;
  213124. iLo = iTest+1;
  213125. }else{
  213126. iHi = iTest;
  213127. }
  213128. }
  213129. if( iRes<0 ) return 0;
  213130. if( iKey>=(aFts5UnicodeMap[iRes]+(aFts5UnicodeData[iRes]>>5)) ) return 0;
  213131. ret = aFts5UnicodeData[iRes] & 0x1F;
  213132. if( ret!=30 ) return ret;
  213133. return ((iKey - aFts5UnicodeMap[iRes]) & 0x01) ? 5 : 9;
  213134. }
  213135. static void sqlite3Fts5UnicodeAscii(u8 *aArray, u8 *aAscii){
  213136. int i = 0;
  213137. int iTbl = 0;
  213138. while( i<128 ){
  213139. int bToken = aArray[ aFts5UnicodeData[iTbl] & 0x1F ];
  213140. int n = (aFts5UnicodeData[iTbl] >> 5) + i;
  213141. for(; i<128 && i<n; i++){
  213142. aAscii[i] = (u8)bToken;
  213143. }
  213144. iTbl++;
  213145. }
  213146. }
  213147. /*
  213148. ** 2015 May 30
  213149. **
  213150. ** The author disclaims copyright to this source code. In place of
  213151. ** a legal notice, here is a blessing:
  213152. **
  213153. ** May you do good and not evil.
  213154. ** May you find forgiveness for yourself and forgive others.
  213155. ** May you share freely, never taking more than you give.
  213156. **
  213157. ******************************************************************************
  213158. **
  213159. ** Routines for varint serialization and deserialization.
  213160. */
  213161. /* #include "fts5Int.h" */
  213162. /*
  213163. ** This is a copy of the sqlite3GetVarint32() routine from the SQLite core.
  213164. ** Except, this version does handle the single byte case that the core
  213165. ** version depends on being handled before its function is called.
  213166. */
  213167. static int sqlite3Fts5GetVarint32(const unsigned char *p, u32 *v){
  213168. u32 a,b;
  213169. /* The 1-byte case. Overwhelmingly the most common. */
  213170. a = *p;
  213171. /* a: p0 (unmasked) */
  213172. if (!(a&0x80))
  213173. {
  213174. /* Values between 0 and 127 */
  213175. *v = a;
  213176. return 1;
  213177. }
  213178. /* The 2-byte case */
  213179. p++;
  213180. b = *p;
  213181. /* b: p1 (unmasked) */
  213182. if (!(b&0x80))
  213183. {
  213184. /* Values between 128 and 16383 */
  213185. a &= 0x7f;
  213186. a = a<<7;
  213187. *v = a | b;
  213188. return 2;
  213189. }
  213190. /* The 3-byte case */
  213191. p++;
  213192. a = a<<14;
  213193. a |= *p;
  213194. /* a: p0<<14 | p2 (unmasked) */
  213195. if (!(a&0x80))
  213196. {
  213197. /* Values between 16384 and 2097151 */
  213198. a &= (0x7f<<14)|(0x7f);
  213199. b &= 0x7f;
  213200. b = b<<7;
  213201. *v = a | b;
  213202. return 3;
  213203. }
  213204. /* A 32-bit varint is used to store size information in btrees.
  213205. ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
  213206. ** A 3-byte varint is sufficient, for example, to record the size
  213207. ** of a 1048569-byte BLOB or string.
  213208. **
  213209. ** We only unroll the first 1-, 2-, and 3- byte cases. The very
  213210. ** rare larger cases can be handled by the slower 64-bit varint
  213211. ** routine.
  213212. */
  213213. {
  213214. u64 v64;
  213215. u8 n;
  213216. p -= 2;
  213217. n = sqlite3Fts5GetVarint(p, &v64);
  213218. *v = ((u32)v64) & 0x7FFFFFFF;
  213219. assert( n>3 && n<=9 );
  213220. return n;
  213221. }
  213222. }
  213223. /*
  213224. ** Bitmasks used by sqlite3GetVarint(). These precomputed constants
  213225. ** are defined here rather than simply putting the constant expressions
  213226. ** inline in order to work around bugs in the RVT compiler.
  213227. **
  213228. ** SLOT_2_0 A mask for (0x7f<<14) | 0x7f
  213229. **
  213230. ** SLOT_4_2_0 A mask for (0x7f<<28) | SLOT_2_0
  213231. */
  213232. #define SLOT_2_0 0x001fc07f
  213233. #define SLOT_4_2_0 0xf01fc07f
  213234. /*
  213235. ** Read a 64-bit variable-length integer from memory starting at p[0].
  213236. ** Return the number of bytes read. The value is stored in *v.
  213237. */
  213238. static u8 sqlite3Fts5GetVarint(const unsigned char *p, u64 *v){
  213239. u32 a,b,s;
  213240. a = *p;
  213241. /* a: p0 (unmasked) */
  213242. if (!(a&0x80))
  213243. {
  213244. *v = a;
  213245. return 1;
  213246. }
  213247. p++;
  213248. b = *p;
  213249. /* b: p1 (unmasked) */
  213250. if (!(b&0x80))
  213251. {
  213252. a &= 0x7f;
  213253. a = a<<7;
  213254. a |= b;
  213255. *v = a;
  213256. return 2;
  213257. }
  213258. /* Verify that constants are precomputed correctly */
  213259. assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
  213260. assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
  213261. p++;
  213262. a = a<<14;
  213263. a |= *p;
  213264. /* a: p0<<14 | p2 (unmasked) */
  213265. if (!(a&0x80))
  213266. {
  213267. a &= SLOT_2_0;
  213268. b &= 0x7f;
  213269. b = b<<7;
  213270. a |= b;
  213271. *v = a;
  213272. return 3;
  213273. }
  213274. /* CSE1 from below */
  213275. a &= SLOT_2_0;
  213276. p++;
  213277. b = b<<14;
  213278. b |= *p;
  213279. /* b: p1<<14 | p3 (unmasked) */
  213280. if (!(b&0x80))
  213281. {
  213282. b &= SLOT_2_0;
  213283. /* moved CSE1 up */
  213284. /* a &= (0x7f<<14)|(0x7f); */
  213285. a = a<<7;
  213286. a |= b;
  213287. *v = a;
  213288. return 4;
  213289. }
  213290. /* a: p0<<14 | p2 (masked) */
  213291. /* b: p1<<14 | p3 (unmasked) */
  213292. /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  213293. /* moved CSE1 up */
  213294. /* a &= (0x7f<<14)|(0x7f); */
  213295. b &= SLOT_2_0;
  213296. s = a;
  213297. /* s: p0<<14 | p2 (masked) */
  213298. p++;
  213299. a = a<<14;
  213300. a |= *p;
  213301. /* a: p0<<28 | p2<<14 | p4 (unmasked) */
  213302. if (!(a&0x80))
  213303. {
  213304. /* we can skip these cause they were (effectively) done above in calc'ing s */
  213305. /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
  213306. /* b &= (0x7f<<14)|(0x7f); */
  213307. b = b<<7;
  213308. a |= b;
  213309. s = s>>18;
  213310. *v = ((u64)s)<<32 | a;
  213311. return 5;
  213312. }
  213313. /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  213314. s = s<<7;
  213315. s |= b;
  213316. /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  213317. p++;
  213318. b = b<<14;
  213319. b |= *p;
  213320. /* b: p1<<28 | p3<<14 | p5 (unmasked) */
  213321. if (!(b&0x80))
  213322. {
  213323. /* we can skip this cause it was (effectively) done above in calc'ing s */
  213324. /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
  213325. a &= SLOT_2_0;
  213326. a = a<<7;
  213327. a |= b;
  213328. s = s>>18;
  213329. *v = ((u64)s)<<32 | a;
  213330. return 6;
  213331. }
  213332. p++;
  213333. a = a<<14;
  213334. a |= *p;
  213335. /* a: p2<<28 | p4<<14 | p6 (unmasked) */
  213336. if (!(a&0x80))
  213337. {
  213338. a &= SLOT_4_2_0;
  213339. b &= SLOT_2_0;
  213340. b = b<<7;
  213341. a |= b;
  213342. s = s>>11;
  213343. *v = ((u64)s)<<32 | a;
  213344. return 7;
  213345. }
  213346. /* CSE2 from below */
  213347. a &= SLOT_2_0;
  213348. p++;
  213349. b = b<<14;
  213350. b |= *p;
  213351. /* b: p3<<28 | p5<<14 | p7 (unmasked) */
  213352. if (!(b&0x80))
  213353. {
  213354. b &= SLOT_4_2_0;
  213355. /* moved CSE2 up */
  213356. /* a &= (0x7f<<14)|(0x7f); */
  213357. a = a<<7;
  213358. a |= b;
  213359. s = s>>4;
  213360. *v = ((u64)s)<<32 | a;
  213361. return 8;
  213362. }
  213363. p++;
  213364. a = a<<15;
  213365. a |= *p;
  213366. /* a: p4<<29 | p6<<15 | p8 (unmasked) */
  213367. /* moved CSE2 up */
  213368. /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
  213369. b &= SLOT_2_0;
  213370. b = b<<8;
  213371. a |= b;
  213372. s = s<<4;
  213373. b = p[-4];
  213374. b &= 0x7f;
  213375. b = b>>3;
  213376. s |= b;
  213377. *v = ((u64)s)<<32 | a;
  213378. return 9;
  213379. }
  213380. /*
  213381. ** The variable-length integer encoding is as follows:
  213382. **
  213383. ** KEY:
  213384. ** A = 0xxxxxxx 7 bits of data and one flag bit
  213385. ** B = 1xxxxxxx 7 bits of data and one flag bit
  213386. ** C = xxxxxxxx 8 bits of data
  213387. **
  213388. ** 7 bits - A
  213389. ** 14 bits - BA
  213390. ** 21 bits - BBA
  213391. ** 28 bits - BBBA
  213392. ** 35 bits - BBBBA
  213393. ** 42 bits - BBBBBA
  213394. ** 49 bits - BBBBBBA
  213395. ** 56 bits - BBBBBBBA
  213396. ** 64 bits - BBBBBBBBC
  213397. */
  213398. #ifdef SQLITE_NOINLINE
  213399. # define FTS5_NOINLINE SQLITE_NOINLINE
  213400. #else
  213401. # define FTS5_NOINLINE
  213402. #endif
  213403. /*
  213404. ** Write a 64-bit variable-length integer to memory starting at p[0].
  213405. ** The length of data write will be between 1 and 9 bytes. The number
  213406. ** of bytes written is returned.
  213407. **
  213408. ** A variable-length integer consists of the lower 7 bits of each byte
  213409. ** for all bytes that have the 8th bit set and one byte with the 8th
  213410. ** bit clear. Except, if we get to the 9th byte, it stores the full
  213411. ** 8 bits and is the last byte.
  213412. */
  213413. static int FTS5_NOINLINE fts5PutVarint64(unsigned char *p, u64 v){
  213414. int i, j, n;
  213415. u8 buf[10];
  213416. if( v & (((u64)0xff000000)<<32) ){
  213417. p[8] = (u8)v;
  213418. v >>= 8;
  213419. for(i=7; i>=0; i--){
  213420. p[i] = (u8)((v & 0x7f) | 0x80);
  213421. v >>= 7;
  213422. }
  213423. return 9;
  213424. }
  213425. n = 0;
  213426. do{
  213427. buf[n++] = (u8)((v & 0x7f) | 0x80);
  213428. v >>= 7;
  213429. }while( v!=0 );
  213430. buf[0] &= 0x7f;
  213431. assert( n<=9 );
  213432. for(i=0, j=n-1; j>=0; j--, i++){
  213433. p[i] = buf[j];
  213434. }
  213435. return n;
  213436. }
  213437. static int sqlite3Fts5PutVarint(unsigned char *p, u64 v){
  213438. if( v<=0x7f ){
  213439. p[0] = v&0x7f;
  213440. return 1;
  213441. }
  213442. if( v<=0x3fff ){
  213443. p[0] = ((v>>7)&0x7f)|0x80;
  213444. p[1] = v&0x7f;
  213445. return 2;
  213446. }
  213447. return fts5PutVarint64(p,v);
  213448. }
  213449. static int sqlite3Fts5GetVarintLen(u32 iVal){
  213450. #if 0
  213451. if( iVal<(1 << 7 ) ) return 1;
  213452. #endif
  213453. assert( iVal>=(1 << 7) );
  213454. if( iVal<(1 << 14) ) return 2;
  213455. if( iVal<(1 << 21) ) return 3;
  213456. if( iVal<(1 << 28) ) return 4;
  213457. return 5;
  213458. }
  213459. /*
  213460. ** 2015 May 08
  213461. **
  213462. ** The author disclaims copyright to this source code. In place of
  213463. ** a legal notice, here is a blessing:
  213464. **
  213465. ** May you do good and not evil.
  213466. ** May you find forgiveness for yourself and forgive others.
  213467. ** May you share freely, never taking more than you give.
  213468. **
  213469. ******************************************************************************
  213470. **
  213471. ** This is an SQLite virtual table module implementing direct access to an
  213472. ** existing FTS5 index. The module may create several different types of
  213473. ** tables:
  213474. **
  213475. ** col:
  213476. ** CREATE TABLE vocab(term, col, doc, cnt, PRIMARY KEY(term, col));
  213477. **
  213478. ** One row for each term/column combination. The value of $doc is set to
  213479. ** the number of fts5 rows that contain at least one instance of term
  213480. ** $term within column $col. Field $cnt is set to the total number of
  213481. ** instances of term $term in column $col (in any row of the fts5 table).
  213482. **
  213483. ** row:
  213484. ** CREATE TABLE vocab(term, doc, cnt, PRIMARY KEY(term));
  213485. **
  213486. ** One row for each term in the database. The value of $doc is set to
  213487. ** the number of fts5 rows that contain at least one instance of term
  213488. ** $term. Field $cnt is set to the total number of instances of term
  213489. ** $term in the database.
  213490. **
  213491. ** instance:
  213492. ** CREATE TABLE vocab(term, doc, col, offset, PRIMARY KEY(<all-fields>));
  213493. **
  213494. ** One row for each term instance in the database.
  213495. */
  213496. /* #include "fts5Int.h" */
  213497. typedef struct Fts5VocabTable Fts5VocabTable;
  213498. typedef struct Fts5VocabCursor Fts5VocabCursor;
  213499. struct Fts5VocabTable {
  213500. sqlite3_vtab base;
  213501. char *zFts5Tbl; /* Name of fts5 table */
  213502. char *zFts5Db; /* Db containing fts5 table */
  213503. sqlite3 *db; /* Database handle */
  213504. Fts5Global *pGlobal; /* FTS5 global object for this database */
  213505. int eType; /* FTS5_VOCAB_COL, ROW or INSTANCE */
  213506. unsigned bBusy; /* True if busy */
  213507. };
  213508. struct Fts5VocabCursor {
  213509. sqlite3_vtab_cursor base;
  213510. sqlite3_stmt *pStmt; /* Statement holding lock on pIndex */
  213511. Fts5Table *pFts5; /* Associated FTS5 table */
  213512. int bEof; /* True if this cursor is at EOF */
  213513. Fts5IndexIter *pIter; /* Term/rowid iterator object */
  213514. int nLeTerm; /* Size of zLeTerm in bytes */
  213515. char *zLeTerm; /* (term <= $zLeTerm) paramater, or NULL */
  213516. /* These are used by 'col' tables only */
  213517. int iCol;
  213518. i64 *aCnt;
  213519. i64 *aDoc;
  213520. /* Output values used by all tables. */
  213521. i64 rowid; /* This table's current rowid value */
  213522. Fts5Buffer term; /* Current value of 'term' column */
  213523. /* Output values Used by 'instance' tables only */
  213524. i64 iInstPos;
  213525. int iInstOff;
  213526. };
  213527. #define FTS5_VOCAB_COL 0
  213528. #define FTS5_VOCAB_ROW 1
  213529. #define FTS5_VOCAB_INSTANCE 2
  213530. #define FTS5_VOCAB_COL_SCHEMA "term, col, doc, cnt"
  213531. #define FTS5_VOCAB_ROW_SCHEMA "term, doc, cnt"
  213532. #define FTS5_VOCAB_INST_SCHEMA "term, doc, col, offset"
  213533. /*
  213534. ** Bits for the mask used as the idxNum value by xBestIndex/xFilter.
  213535. */
  213536. #define FTS5_VOCAB_TERM_EQ 0x01
  213537. #define FTS5_VOCAB_TERM_GE 0x02
  213538. #define FTS5_VOCAB_TERM_LE 0x04
  213539. /*
  213540. ** Translate a string containing an fts5vocab table type to an
  213541. ** FTS5_VOCAB_XXX constant. If successful, set *peType to the output
  213542. ** value and return SQLITE_OK. Otherwise, set *pzErr to an error message
  213543. ** and return SQLITE_ERROR.
  213544. */
  213545. static int fts5VocabTableType(const char *zType, char **pzErr, int *peType){
  213546. int rc = SQLITE_OK;
  213547. char *zCopy = sqlite3Fts5Strndup(&rc, zType, -1);
  213548. if( rc==SQLITE_OK ){
  213549. sqlite3Fts5Dequote(zCopy);
  213550. if( sqlite3_stricmp(zCopy, "col")==0 ){
  213551. *peType = FTS5_VOCAB_COL;
  213552. }else
  213553. if( sqlite3_stricmp(zCopy, "row")==0 ){
  213554. *peType = FTS5_VOCAB_ROW;
  213555. }else
  213556. if( sqlite3_stricmp(zCopy, "instance")==0 ){
  213557. *peType = FTS5_VOCAB_INSTANCE;
  213558. }else
  213559. {
  213560. *pzErr = sqlite3_mprintf("fts5vocab: unknown table type: %Q", zCopy);
  213561. rc = SQLITE_ERROR;
  213562. }
  213563. sqlite3_free(zCopy);
  213564. }
  213565. return rc;
  213566. }
  213567. /*
  213568. ** The xDisconnect() virtual table method.
  213569. */
  213570. static int fts5VocabDisconnectMethod(sqlite3_vtab *pVtab){
  213571. Fts5VocabTable *pTab = (Fts5VocabTable*)pVtab;
  213572. sqlite3_free(pTab);
  213573. return SQLITE_OK;
  213574. }
  213575. /*
  213576. ** The xDestroy() virtual table method.
  213577. */
  213578. static int fts5VocabDestroyMethod(sqlite3_vtab *pVtab){
  213579. Fts5VocabTable *pTab = (Fts5VocabTable*)pVtab;
  213580. sqlite3_free(pTab);
  213581. return SQLITE_OK;
  213582. }
  213583. /*
  213584. ** This function is the implementation of both the xConnect and xCreate
  213585. ** methods of the FTS3 virtual table.
  213586. **
  213587. ** The argv[] array contains the following:
  213588. **
  213589. ** argv[0] -> module name ("fts5vocab")
  213590. ** argv[1] -> database name
  213591. ** argv[2] -> table name
  213592. **
  213593. ** then:
  213594. **
  213595. ** argv[3] -> name of fts5 table
  213596. ** argv[4] -> type of fts5vocab table
  213597. **
  213598. ** or, for tables in the TEMP schema only.
  213599. **
  213600. ** argv[3] -> name of fts5 tables database
  213601. ** argv[4] -> name of fts5 table
  213602. ** argv[5] -> type of fts5vocab table
  213603. */
  213604. static int fts5VocabInitVtab(
  213605. sqlite3 *db, /* The SQLite database connection */
  213606. void *pAux, /* Pointer to Fts5Global object */
  213607. int argc, /* Number of elements in argv array */
  213608. const char * const *argv, /* xCreate/xConnect argument array */
  213609. sqlite3_vtab **ppVTab, /* Write the resulting vtab structure here */
  213610. char **pzErr /* Write any error message here */
  213611. ){
  213612. const char *azSchema[] = {
  213613. "CREATE TABlE vocab(" FTS5_VOCAB_COL_SCHEMA ")",
  213614. "CREATE TABlE vocab(" FTS5_VOCAB_ROW_SCHEMA ")",
  213615. "CREATE TABlE vocab(" FTS5_VOCAB_INST_SCHEMA ")"
  213616. };
  213617. Fts5VocabTable *pRet = 0;
  213618. int rc = SQLITE_OK; /* Return code */
  213619. int bDb;
  213620. bDb = (argc==6 && strlen(argv[1])==4 && memcmp("temp", argv[1], 4)==0);
  213621. if( argc!=5 && bDb==0 ){
  213622. *pzErr = sqlite3_mprintf("wrong number of vtable arguments");
  213623. rc = SQLITE_ERROR;
  213624. }else{
  213625. int nByte; /* Bytes of space to allocate */
  213626. const char *zDb = bDb ? argv[3] : argv[1];
  213627. const char *zTab = bDb ? argv[4] : argv[3];
  213628. const char *zType = bDb ? argv[5] : argv[4];
  213629. int nDb = (int)strlen(zDb)+1;
  213630. int nTab = (int)strlen(zTab)+1;
  213631. int eType = 0;
  213632. rc = fts5VocabTableType(zType, pzErr, &eType);
  213633. if( rc==SQLITE_OK ){
  213634. assert( eType>=0 && eType<ArraySize(azSchema) );
  213635. rc = sqlite3_declare_vtab(db, azSchema[eType]);
  213636. }
  213637. nByte = sizeof(Fts5VocabTable) + nDb + nTab;
  213638. pRet = sqlite3Fts5MallocZero(&rc, nByte);
  213639. if( pRet ){
  213640. pRet->pGlobal = (Fts5Global*)pAux;
  213641. pRet->eType = eType;
  213642. pRet->db = db;
  213643. pRet->zFts5Tbl = (char*)&pRet[1];
  213644. pRet->zFts5Db = &pRet->zFts5Tbl[nTab];
  213645. memcpy(pRet->zFts5Tbl, zTab, nTab);
  213646. memcpy(pRet->zFts5Db, zDb, nDb);
  213647. sqlite3Fts5Dequote(pRet->zFts5Tbl);
  213648. sqlite3Fts5Dequote(pRet->zFts5Db);
  213649. }
  213650. }
  213651. *ppVTab = (sqlite3_vtab*)pRet;
  213652. return rc;
  213653. }
  213654. /*
  213655. ** The xConnect() and xCreate() methods for the virtual table. All the
  213656. ** work is done in function fts5VocabInitVtab().
  213657. */
  213658. static int fts5VocabConnectMethod(
  213659. sqlite3 *db, /* Database connection */
  213660. void *pAux, /* Pointer to tokenizer hash table */
  213661. int argc, /* Number of elements in argv array */
  213662. const char * const *argv, /* xCreate/xConnect argument array */
  213663. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  213664. char **pzErr /* OUT: sqlite3_malloc'd error message */
  213665. ){
  213666. return fts5VocabInitVtab(db, pAux, argc, argv, ppVtab, pzErr);
  213667. }
  213668. static int fts5VocabCreateMethod(
  213669. sqlite3 *db, /* Database connection */
  213670. void *pAux, /* Pointer to tokenizer hash table */
  213671. int argc, /* Number of elements in argv array */
  213672. const char * const *argv, /* xCreate/xConnect argument array */
  213673. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  213674. char **pzErr /* OUT: sqlite3_malloc'd error message */
  213675. ){
  213676. return fts5VocabInitVtab(db, pAux, argc, argv, ppVtab, pzErr);
  213677. }
  213678. /*
  213679. ** Implementation of the xBestIndex method.
  213680. **
  213681. ** Only constraints of the form:
  213682. **
  213683. ** term <= ?
  213684. ** term == ?
  213685. ** term >= ?
  213686. **
  213687. ** are interpreted. Less-than and less-than-or-equal are treated
  213688. ** identically, as are greater-than and greater-than-or-equal.
  213689. */
  213690. static int fts5VocabBestIndexMethod(
  213691. sqlite3_vtab *pUnused,
  213692. sqlite3_index_info *pInfo
  213693. ){
  213694. int i;
  213695. int iTermEq = -1;
  213696. int iTermGe = -1;
  213697. int iTermLe = -1;
  213698. int idxNum = 0;
  213699. int nArg = 0;
  213700. UNUSED_PARAM(pUnused);
  213701. for(i=0; i<pInfo->nConstraint; i++){
  213702. struct sqlite3_index_constraint *p = &pInfo->aConstraint[i];
  213703. if( p->usable==0 ) continue;
  213704. if( p->iColumn==0 ){ /* term column */
  213705. if( p->op==SQLITE_INDEX_CONSTRAINT_EQ ) iTermEq = i;
  213706. if( p->op==SQLITE_INDEX_CONSTRAINT_LE ) iTermLe = i;
  213707. if( p->op==SQLITE_INDEX_CONSTRAINT_LT ) iTermLe = i;
  213708. if( p->op==SQLITE_INDEX_CONSTRAINT_GE ) iTermGe = i;
  213709. if( p->op==SQLITE_INDEX_CONSTRAINT_GT ) iTermGe = i;
  213710. }
  213711. }
  213712. if( iTermEq>=0 ){
  213713. idxNum |= FTS5_VOCAB_TERM_EQ;
  213714. pInfo->aConstraintUsage[iTermEq].argvIndex = ++nArg;
  213715. pInfo->estimatedCost = 100;
  213716. }else{
  213717. pInfo->estimatedCost = 1000000;
  213718. if( iTermGe>=0 ){
  213719. idxNum |= FTS5_VOCAB_TERM_GE;
  213720. pInfo->aConstraintUsage[iTermGe].argvIndex = ++nArg;
  213721. pInfo->estimatedCost = pInfo->estimatedCost / 2;
  213722. }
  213723. if( iTermLe>=0 ){
  213724. idxNum |= FTS5_VOCAB_TERM_LE;
  213725. pInfo->aConstraintUsage[iTermLe].argvIndex = ++nArg;
  213726. pInfo->estimatedCost = pInfo->estimatedCost / 2;
  213727. }
  213728. }
  213729. /* This virtual table always delivers results in ascending order of
  213730. ** the "term" column (column 0). So if the user has requested this
  213731. ** specifically - "ORDER BY term" or "ORDER BY term ASC" - set the
  213732. ** sqlite3_index_info.orderByConsumed flag to tell the core the results
  213733. ** are already in sorted order. */
  213734. if( pInfo->nOrderBy==1
  213735. && pInfo->aOrderBy[0].iColumn==0
  213736. && pInfo->aOrderBy[0].desc==0
  213737. ){
  213738. pInfo->orderByConsumed = 1;
  213739. }
  213740. pInfo->idxNum = idxNum;
  213741. return SQLITE_OK;
  213742. }
  213743. /*
  213744. ** Implementation of xOpen method.
  213745. */
  213746. static int fts5VocabOpenMethod(
  213747. sqlite3_vtab *pVTab,
  213748. sqlite3_vtab_cursor **ppCsr
  213749. ){
  213750. Fts5VocabTable *pTab = (Fts5VocabTable*)pVTab;
  213751. Fts5Table *pFts5 = 0;
  213752. Fts5VocabCursor *pCsr = 0;
  213753. int rc = SQLITE_OK;
  213754. sqlite3_stmt *pStmt = 0;
  213755. char *zSql = 0;
  213756. if( pTab->bBusy ){
  213757. pVTab->zErrMsg = sqlite3_mprintf(
  213758. "recursive definition for %s.%s", pTab->zFts5Db, pTab->zFts5Tbl
  213759. );
  213760. return SQLITE_ERROR;
  213761. }
  213762. zSql = sqlite3Fts5Mprintf(&rc,
  213763. "SELECT t.%Q FROM %Q.%Q AS t WHERE t.%Q MATCH '*id'",
  213764. pTab->zFts5Tbl, pTab->zFts5Db, pTab->zFts5Tbl, pTab->zFts5Tbl
  213765. );
  213766. if( zSql ){
  213767. rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pStmt, 0);
  213768. }
  213769. sqlite3_free(zSql);
  213770. assert( rc==SQLITE_OK || pStmt==0 );
  213771. if( rc==SQLITE_ERROR ) rc = SQLITE_OK;
  213772. pTab->bBusy = 1;
  213773. if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
  213774. i64 iId = sqlite3_column_int64(pStmt, 0);
  213775. pFts5 = sqlite3Fts5TableFromCsrid(pTab->pGlobal, iId);
  213776. }
  213777. pTab->bBusy = 0;
  213778. if( rc==SQLITE_OK ){
  213779. if( pFts5==0 ){
  213780. rc = sqlite3_finalize(pStmt);
  213781. pStmt = 0;
  213782. if( rc==SQLITE_OK ){
  213783. pVTab->zErrMsg = sqlite3_mprintf(
  213784. "no such fts5 table: %s.%s", pTab->zFts5Db, pTab->zFts5Tbl
  213785. );
  213786. rc = SQLITE_ERROR;
  213787. }
  213788. }else{
  213789. rc = sqlite3Fts5FlushToDisk(pFts5);
  213790. }
  213791. }
  213792. if( rc==SQLITE_OK ){
  213793. int nByte = pFts5->pConfig->nCol * sizeof(i64)*2 + sizeof(Fts5VocabCursor);
  213794. pCsr = (Fts5VocabCursor*)sqlite3Fts5MallocZero(&rc, nByte);
  213795. }
  213796. if( pCsr ){
  213797. pCsr->pFts5 = pFts5;
  213798. pCsr->pStmt = pStmt;
  213799. pCsr->aCnt = (i64*)&pCsr[1];
  213800. pCsr->aDoc = &pCsr->aCnt[pFts5->pConfig->nCol];
  213801. }else{
  213802. sqlite3_finalize(pStmt);
  213803. }
  213804. *ppCsr = (sqlite3_vtab_cursor*)pCsr;
  213805. return rc;
  213806. }
  213807. static void fts5VocabResetCursor(Fts5VocabCursor *pCsr){
  213808. pCsr->rowid = 0;
  213809. sqlite3Fts5IterClose(pCsr->pIter);
  213810. pCsr->pIter = 0;
  213811. sqlite3_free(pCsr->zLeTerm);
  213812. pCsr->nLeTerm = -1;
  213813. pCsr->zLeTerm = 0;
  213814. pCsr->bEof = 0;
  213815. }
  213816. /*
  213817. ** Close the cursor. For additional information see the documentation
  213818. ** on the xClose method of the virtual table interface.
  213819. */
  213820. static int fts5VocabCloseMethod(sqlite3_vtab_cursor *pCursor){
  213821. Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
  213822. fts5VocabResetCursor(pCsr);
  213823. sqlite3Fts5BufferFree(&pCsr->term);
  213824. sqlite3_finalize(pCsr->pStmt);
  213825. sqlite3_free(pCsr);
  213826. return SQLITE_OK;
  213827. }
  213828. static int fts5VocabInstanceNewTerm(Fts5VocabCursor *pCsr){
  213829. int rc = SQLITE_OK;
  213830. if( sqlite3Fts5IterEof(pCsr->pIter) ){
  213831. pCsr->bEof = 1;
  213832. }else{
  213833. const char *zTerm;
  213834. int nTerm;
  213835. zTerm = sqlite3Fts5IterTerm(pCsr->pIter, &nTerm);
  213836. if( pCsr->nLeTerm>=0 ){
  213837. int nCmp = MIN(nTerm, pCsr->nLeTerm);
  213838. int bCmp = memcmp(pCsr->zLeTerm, zTerm, nCmp);
  213839. if( bCmp<0 || (bCmp==0 && pCsr->nLeTerm<nTerm) ){
  213840. pCsr->bEof = 1;
  213841. }
  213842. }
  213843. sqlite3Fts5BufferSet(&rc, &pCsr->term, nTerm, (const u8*)zTerm);
  213844. }
  213845. return rc;
  213846. }
  213847. static int fts5VocabInstanceNext(Fts5VocabCursor *pCsr){
  213848. int eDetail = pCsr->pFts5->pConfig->eDetail;
  213849. int rc = SQLITE_OK;
  213850. Fts5IndexIter *pIter = pCsr->pIter;
  213851. i64 *pp = &pCsr->iInstPos;
  213852. int *po = &pCsr->iInstOff;
  213853. assert( sqlite3Fts5IterEof(pIter)==0 );
  213854. assert( pCsr->bEof==0 );
  213855. while( eDetail==FTS5_DETAIL_NONE
  213856. || sqlite3Fts5PoslistNext64(pIter->pData, pIter->nData, po, pp)
  213857. ){
  213858. pCsr->iInstPos = 0;
  213859. pCsr->iInstOff = 0;
  213860. rc = sqlite3Fts5IterNextScan(pCsr->pIter);
  213861. if( rc==SQLITE_OK ){
  213862. rc = fts5VocabInstanceNewTerm(pCsr);
  213863. if( pCsr->bEof || eDetail==FTS5_DETAIL_NONE ) break;
  213864. }
  213865. if( rc ){
  213866. pCsr->bEof = 1;
  213867. break;
  213868. }
  213869. }
  213870. return rc;
  213871. }
  213872. /*
  213873. ** Advance the cursor to the next row in the table.
  213874. */
  213875. static int fts5VocabNextMethod(sqlite3_vtab_cursor *pCursor){
  213876. Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
  213877. Fts5VocabTable *pTab = (Fts5VocabTable*)pCursor->pVtab;
  213878. int rc = SQLITE_OK;
  213879. int nCol = pCsr->pFts5->pConfig->nCol;
  213880. pCsr->rowid++;
  213881. if( pTab->eType==FTS5_VOCAB_INSTANCE ){
  213882. return fts5VocabInstanceNext(pCsr);
  213883. }
  213884. if( pTab->eType==FTS5_VOCAB_COL ){
  213885. for(pCsr->iCol++; pCsr->iCol<nCol; pCsr->iCol++){
  213886. if( pCsr->aDoc[pCsr->iCol] ) break;
  213887. }
  213888. }
  213889. if( pTab->eType!=FTS5_VOCAB_COL || pCsr->iCol>=nCol ){
  213890. if( sqlite3Fts5IterEof(pCsr->pIter) ){
  213891. pCsr->bEof = 1;
  213892. }else{
  213893. const char *zTerm;
  213894. int nTerm;
  213895. zTerm = sqlite3Fts5IterTerm(pCsr->pIter, &nTerm);
  213896. assert( nTerm>=0 );
  213897. if( pCsr->nLeTerm>=0 ){
  213898. int nCmp = MIN(nTerm, pCsr->nLeTerm);
  213899. int bCmp = memcmp(pCsr->zLeTerm, zTerm, nCmp);
  213900. if( bCmp<0 || (bCmp==0 && pCsr->nLeTerm<nTerm) ){
  213901. pCsr->bEof = 1;
  213902. return SQLITE_OK;
  213903. }
  213904. }
  213905. sqlite3Fts5BufferSet(&rc, &pCsr->term, nTerm, (const u8*)zTerm);
  213906. memset(pCsr->aCnt, 0, nCol * sizeof(i64));
  213907. memset(pCsr->aDoc, 0, nCol * sizeof(i64));
  213908. pCsr->iCol = 0;
  213909. assert( pTab->eType==FTS5_VOCAB_COL || pTab->eType==FTS5_VOCAB_ROW );
  213910. while( rc==SQLITE_OK ){
  213911. int eDetail = pCsr->pFts5->pConfig->eDetail;
  213912. const u8 *pPos; int nPos; /* Position list */
  213913. i64 iPos = 0; /* 64-bit position read from poslist */
  213914. int iOff = 0; /* Current offset within position list */
  213915. pPos = pCsr->pIter->pData;
  213916. nPos = pCsr->pIter->nData;
  213917. switch( pTab->eType ){
  213918. case FTS5_VOCAB_ROW:
  213919. if( eDetail==FTS5_DETAIL_FULL ){
  213920. while( 0==sqlite3Fts5PoslistNext64(pPos, nPos, &iOff, &iPos) ){
  213921. pCsr->aCnt[0]++;
  213922. }
  213923. }
  213924. pCsr->aDoc[0]++;
  213925. break;
  213926. case FTS5_VOCAB_COL:
  213927. if( eDetail==FTS5_DETAIL_FULL ){
  213928. int iCol = -1;
  213929. while( 0==sqlite3Fts5PoslistNext64(pPos, nPos, &iOff, &iPos) ){
  213930. int ii = FTS5_POS2COLUMN(iPos);
  213931. if( iCol!=ii ){
  213932. if( ii>=nCol ){
  213933. rc = FTS5_CORRUPT;
  213934. break;
  213935. }
  213936. pCsr->aDoc[ii]++;
  213937. iCol = ii;
  213938. }
  213939. pCsr->aCnt[ii]++;
  213940. }
  213941. }else if( eDetail==FTS5_DETAIL_COLUMNS ){
  213942. while( 0==sqlite3Fts5PoslistNext64(pPos, nPos, &iOff,&iPos) ){
  213943. assert_nc( iPos>=0 && iPos<nCol );
  213944. if( iPos>=nCol ){
  213945. rc = FTS5_CORRUPT;
  213946. break;
  213947. }
  213948. pCsr->aDoc[iPos]++;
  213949. }
  213950. }else{
  213951. assert( eDetail==FTS5_DETAIL_NONE );
  213952. pCsr->aDoc[0]++;
  213953. }
  213954. break;
  213955. default:
  213956. assert( pTab->eType==FTS5_VOCAB_INSTANCE );
  213957. break;
  213958. }
  213959. if( rc==SQLITE_OK ){
  213960. rc = sqlite3Fts5IterNextScan(pCsr->pIter);
  213961. }
  213962. if( pTab->eType==FTS5_VOCAB_INSTANCE ) break;
  213963. if( rc==SQLITE_OK ){
  213964. zTerm = sqlite3Fts5IterTerm(pCsr->pIter, &nTerm);
  213965. if( nTerm!=pCsr->term.n
  213966. || (nTerm>0 && memcmp(zTerm, pCsr->term.p, nTerm))
  213967. ){
  213968. break;
  213969. }
  213970. if( sqlite3Fts5IterEof(pCsr->pIter) ) break;
  213971. }
  213972. }
  213973. }
  213974. }
  213975. if( rc==SQLITE_OK && pCsr->bEof==0 && pTab->eType==FTS5_VOCAB_COL ){
  213976. for(/* noop */; pCsr->iCol<nCol && pCsr->aDoc[pCsr->iCol]==0; pCsr->iCol++);
  213977. if( pCsr->iCol==nCol ){
  213978. rc = FTS5_CORRUPT;
  213979. }
  213980. }
  213981. return rc;
  213982. }
  213983. /*
  213984. ** This is the xFilter implementation for the virtual table.
  213985. */
  213986. static int fts5VocabFilterMethod(
  213987. sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
  213988. int idxNum, /* Strategy index */
  213989. const char *zUnused, /* Unused */
  213990. int nUnused, /* Number of elements in apVal */
  213991. sqlite3_value **apVal /* Arguments for the indexing scheme */
  213992. ){
  213993. Fts5VocabTable *pTab = (Fts5VocabTable*)pCursor->pVtab;
  213994. Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
  213995. int eType = pTab->eType;
  213996. int rc = SQLITE_OK;
  213997. int iVal = 0;
  213998. int f = FTS5INDEX_QUERY_SCAN;
  213999. const char *zTerm = 0;
  214000. int nTerm = 0;
  214001. sqlite3_value *pEq = 0;
  214002. sqlite3_value *pGe = 0;
  214003. sqlite3_value *pLe = 0;
  214004. UNUSED_PARAM2(zUnused, nUnused);
  214005. fts5VocabResetCursor(pCsr);
  214006. if( idxNum & FTS5_VOCAB_TERM_EQ ) pEq = apVal[iVal++];
  214007. if( idxNum & FTS5_VOCAB_TERM_GE ) pGe = apVal[iVal++];
  214008. if( idxNum & FTS5_VOCAB_TERM_LE ) pLe = apVal[iVal++];
  214009. if( pEq ){
  214010. zTerm = (const char *)sqlite3_value_text(pEq);
  214011. nTerm = sqlite3_value_bytes(pEq);
  214012. f = 0;
  214013. }else{
  214014. if( pGe ){
  214015. zTerm = (const char *)sqlite3_value_text(pGe);
  214016. nTerm = sqlite3_value_bytes(pGe);
  214017. }
  214018. if( pLe ){
  214019. const char *zCopy = (const char *)sqlite3_value_text(pLe);
  214020. if( zCopy==0 ) zCopy = "";
  214021. pCsr->nLeTerm = sqlite3_value_bytes(pLe);
  214022. pCsr->zLeTerm = sqlite3_malloc(pCsr->nLeTerm+1);
  214023. if( pCsr->zLeTerm==0 ){
  214024. rc = SQLITE_NOMEM;
  214025. }else{
  214026. memcpy(pCsr->zLeTerm, zCopy, pCsr->nLeTerm+1);
  214027. }
  214028. }
  214029. }
  214030. if( rc==SQLITE_OK ){
  214031. Fts5Index *pIndex = pCsr->pFts5->pIndex;
  214032. rc = sqlite3Fts5IndexQuery(pIndex, zTerm, nTerm, f, 0, &pCsr->pIter);
  214033. }
  214034. if( rc==SQLITE_OK && eType==FTS5_VOCAB_INSTANCE ){
  214035. rc = fts5VocabInstanceNewTerm(pCsr);
  214036. }
  214037. if( rc==SQLITE_OK && !pCsr->bEof
  214038. && (eType!=FTS5_VOCAB_INSTANCE
  214039. || pCsr->pFts5->pConfig->eDetail!=FTS5_DETAIL_NONE)
  214040. ){
  214041. rc = fts5VocabNextMethod(pCursor);
  214042. }
  214043. return rc;
  214044. }
  214045. /*
  214046. ** This is the xEof method of the virtual table. SQLite calls this
  214047. ** routine to find out if it has reached the end of a result set.
  214048. */
  214049. static int fts5VocabEofMethod(sqlite3_vtab_cursor *pCursor){
  214050. Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
  214051. return pCsr->bEof;
  214052. }
  214053. static int fts5VocabColumnMethod(
  214054. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  214055. sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
  214056. int iCol /* Index of column to read value from */
  214057. ){
  214058. Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
  214059. int eDetail = pCsr->pFts5->pConfig->eDetail;
  214060. int eType = ((Fts5VocabTable*)(pCursor->pVtab))->eType;
  214061. i64 iVal = 0;
  214062. if( iCol==0 ){
  214063. sqlite3_result_text(
  214064. pCtx, (const char*)pCsr->term.p, pCsr->term.n, SQLITE_TRANSIENT
  214065. );
  214066. }else if( eType==FTS5_VOCAB_COL ){
  214067. assert( iCol==1 || iCol==2 || iCol==3 );
  214068. if( iCol==1 ){
  214069. if( eDetail!=FTS5_DETAIL_NONE ){
  214070. const char *z = pCsr->pFts5->pConfig->azCol[pCsr->iCol];
  214071. sqlite3_result_text(pCtx, z, -1, SQLITE_STATIC);
  214072. }
  214073. }else if( iCol==2 ){
  214074. iVal = pCsr->aDoc[pCsr->iCol];
  214075. }else{
  214076. iVal = pCsr->aCnt[pCsr->iCol];
  214077. }
  214078. }else if( eType==FTS5_VOCAB_ROW ){
  214079. assert( iCol==1 || iCol==2 );
  214080. if( iCol==1 ){
  214081. iVal = pCsr->aDoc[0];
  214082. }else{
  214083. iVal = pCsr->aCnt[0];
  214084. }
  214085. }else{
  214086. assert( eType==FTS5_VOCAB_INSTANCE );
  214087. switch( iCol ){
  214088. case 1:
  214089. sqlite3_result_int64(pCtx, pCsr->pIter->iRowid);
  214090. break;
  214091. case 2: {
  214092. int ii = -1;
  214093. if( eDetail==FTS5_DETAIL_FULL ){
  214094. ii = FTS5_POS2COLUMN(pCsr->iInstPos);
  214095. }else if( eDetail==FTS5_DETAIL_COLUMNS ){
  214096. ii = (int)pCsr->iInstPos;
  214097. }
  214098. if( ii>=0 && ii<pCsr->pFts5->pConfig->nCol ){
  214099. const char *z = pCsr->pFts5->pConfig->azCol[ii];
  214100. sqlite3_result_text(pCtx, z, -1, SQLITE_STATIC);
  214101. }
  214102. break;
  214103. }
  214104. default: {
  214105. assert( iCol==3 );
  214106. if( eDetail==FTS5_DETAIL_FULL ){
  214107. int ii = FTS5_POS2OFFSET(pCsr->iInstPos);
  214108. sqlite3_result_int(pCtx, ii);
  214109. }
  214110. break;
  214111. }
  214112. }
  214113. }
  214114. if( iVal>0 ) sqlite3_result_int64(pCtx, iVal);
  214115. return SQLITE_OK;
  214116. }
  214117. /*
  214118. ** This is the xRowid method. The SQLite core calls this routine to
  214119. ** retrieve the rowid for the current row of the result set. The
  214120. ** rowid should be written to *pRowid.
  214121. */
  214122. static int fts5VocabRowidMethod(
  214123. sqlite3_vtab_cursor *pCursor,
  214124. sqlite_int64 *pRowid
  214125. ){
  214126. Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
  214127. *pRowid = pCsr->rowid;
  214128. return SQLITE_OK;
  214129. }
  214130. static int sqlite3Fts5VocabInit(Fts5Global *pGlobal, sqlite3 *db){
  214131. static const sqlite3_module fts5Vocab = {
  214132. /* iVersion */ 2,
  214133. /* xCreate */ fts5VocabCreateMethod,
  214134. /* xConnect */ fts5VocabConnectMethod,
  214135. /* xBestIndex */ fts5VocabBestIndexMethod,
  214136. /* xDisconnect */ fts5VocabDisconnectMethod,
  214137. /* xDestroy */ fts5VocabDestroyMethod,
  214138. /* xOpen */ fts5VocabOpenMethod,
  214139. /* xClose */ fts5VocabCloseMethod,
  214140. /* xFilter */ fts5VocabFilterMethod,
  214141. /* xNext */ fts5VocabNextMethod,
  214142. /* xEof */ fts5VocabEofMethod,
  214143. /* xColumn */ fts5VocabColumnMethod,
  214144. /* xRowid */ fts5VocabRowidMethod,
  214145. /* xUpdate */ 0,
  214146. /* xBegin */ 0,
  214147. /* xSync */ 0,
  214148. /* xCommit */ 0,
  214149. /* xRollback */ 0,
  214150. /* xFindFunction */ 0,
  214151. /* xRename */ 0,
  214152. /* xSavepoint */ 0,
  214153. /* xRelease */ 0,
  214154. /* xRollbackTo */ 0,
  214155. /* xShadowName */ 0
  214156. };
  214157. void *p = (void*)pGlobal;
  214158. return sqlite3_create_module_v2(db, "fts5vocab", &fts5Vocab, p, 0);
  214159. }
  214160. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS5) */
  214161. /************** End of fts5.c ************************************************/
  214162. /************** Begin file stmt.c ********************************************/
  214163. /*
  214164. ** 2017-05-31
  214165. **
  214166. ** The author disclaims copyright to this source code. In place of
  214167. ** a legal notice, here is a blessing:
  214168. **
  214169. ** May you do good and not evil.
  214170. ** May you find forgiveness for yourself and forgive others.
  214171. ** May you share freely, never taking more than you give.
  214172. **
  214173. *************************************************************************
  214174. **
  214175. ** This file demonstrates an eponymous virtual table that returns information
  214176. ** about all prepared statements for the database connection.
  214177. **
  214178. ** Usage example:
  214179. **
  214180. ** .load ./stmt
  214181. ** .mode line
  214182. ** .header on
  214183. ** SELECT * FROM stmt;
  214184. */
  214185. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_STMTVTAB)
  214186. #if !defined(SQLITEINT_H)
  214187. /* #include "sqlite3ext.h" */
  214188. #endif
  214189. SQLITE_EXTENSION_INIT1
  214190. /* #include <assert.h> */
  214191. /* #include <string.h> */
  214192. #ifndef SQLITE_OMIT_VIRTUALTABLE
  214193. /* stmt_vtab is a subclass of sqlite3_vtab which will
  214194. ** serve as the underlying representation of a stmt virtual table
  214195. */
  214196. typedef struct stmt_vtab stmt_vtab;
  214197. struct stmt_vtab {
  214198. sqlite3_vtab base; /* Base class - must be first */
  214199. sqlite3 *db; /* Database connection for this stmt vtab */
  214200. };
  214201. /* stmt_cursor is a subclass of sqlite3_vtab_cursor which will
  214202. ** serve as the underlying representation of a cursor that scans
  214203. ** over rows of the result
  214204. */
  214205. typedef struct stmt_cursor stmt_cursor;
  214206. struct stmt_cursor {
  214207. sqlite3_vtab_cursor base; /* Base class - must be first */
  214208. sqlite3 *db; /* Database connection for this cursor */
  214209. sqlite3_stmt *pStmt; /* Statement cursor is currently pointing at */
  214210. sqlite3_int64 iRowid; /* The rowid */
  214211. };
  214212. /*
  214213. ** The stmtConnect() method is invoked to create a new
  214214. ** stmt_vtab that describes the stmt virtual table.
  214215. **
  214216. ** Think of this routine as the constructor for stmt_vtab objects.
  214217. **
  214218. ** All this routine needs to do is:
  214219. **
  214220. ** (1) Allocate the stmt_vtab object and initialize all fields.
  214221. **
  214222. ** (2) Tell SQLite (via the sqlite3_declare_vtab() interface) what the
  214223. ** result set of queries against stmt will look like.
  214224. */
  214225. static int stmtConnect(
  214226. sqlite3 *db,
  214227. void *pAux,
  214228. int argc, const char *const*argv,
  214229. sqlite3_vtab **ppVtab,
  214230. char **pzErr
  214231. ){
  214232. stmt_vtab *pNew;
  214233. int rc;
  214234. /* Column numbers */
  214235. #define STMT_COLUMN_SQL 0 /* SQL for the statement */
  214236. #define STMT_COLUMN_NCOL 1 /* Number of result columns */
  214237. #define STMT_COLUMN_RO 2 /* True if read-only */
  214238. #define STMT_COLUMN_BUSY 3 /* True if currently busy */
  214239. #define STMT_COLUMN_NSCAN 4 /* SQLITE_STMTSTATUS_FULLSCAN_STEP */
  214240. #define STMT_COLUMN_NSORT 5 /* SQLITE_STMTSTATUS_SORT */
  214241. #define STMT_COLUMN_NAIDX 6 /* SQLITE_STMTSTATUS_AUTOINDEX */
  214242. #define STMT_COLUMN_NSTEP 7 /* SQLITE_STMTSTATUS_VM_STEP */
  214243. #define STMT_COLUMN_REPREP 8 /* SQLITE_STMTSTATUS_REPREPARE */
  214244. #define STMT_COLUMN_RUN 9 /* SQLITE_STMTSTATUS_RUN */
  214245. #define STMT_COLUMN_MEM 10 /* SQLITE_STMTSTATUS_MEMUSED */
  214246. rc = sqlite3_declare_vtab(db,
  214247. "CREATE TABLE x(sql,ncol,ro,busy,nscan,nsort,naidx,nstep,"
  214248. "reprep,run,mem)");
  214249. if( rc==SQLITE_OK ){
  214250. pNew = sqlite3_malloc( sizeof(*pNew) );
  214251. *ppVtab = (sqlite3_vtab*)pNew;
  214252. if( pNew==0 ) return SQLITE_NOMEM;
  214253. memset(pNew, 0, sizeof(*pNew));
  214254. pNew->db = db;
  214255. }
  214256. return rc;
  214257. }
  214258. /*
  214259. ** This method is the destructor for stmt_cursor objects.
  214260. */
  214261. static int stmtDisconnect(sqlite3_vtab *pVtab){
  214262. sqlite3_free(pVtab);
  214263. return SQLITE_OK;
  214264. }
  214265. /*
  214266. ** Constructor for a new stmt_cursor object.
  214267. */
  214268. static int stmtOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
  214269. stmt_cursor *pCur;
  214270. pCur = sqlite3_malloc( sizeof(*pCur) );
  214271. if( pCur==0 ) return SQLITE_NOMEM;
  214272. memset(pCur, 0, sizeof(*pCur));
  214273. pCur->db = ((stmt_vtab*)p)->db;
  214274. *ppCursor = &pCur->base;
  214275. return SQLITE_OK;
  214276. }
  214277. /*
  214278. ** Destructor for a stmt_cursor.
  214279. */
  214280. static int stmtClose(sqlite3_vtab_cursor *cur){
  214281. sqlite3_free(cur);
  214282. return SQLITE_OK;
  214283. }
  214284. /*
  214285. ** Advance a stmt_cursor to its next row of output.
  214286. */
  214287. static int stmtNext(sqlite3_vtab_cursor *cur){
  214288. stmt_cursor *pCur = (stmt_cursor*)cur;
  214289. pCur->iRowid++;
  214290. pCur->pStmt = sqlite3_next_stmt(pCur->db, pCur->pStmt);
  214291. return SQLITE_OK;
  214292. }
  214293. /*
  214294. ** Return values of columns for the row at which the stmt_cursor
  214295. ** is currently pointing.
  214296. */
  214297. static int stmtColumn(
  214298. sqlite3_vtab_cursor *cur, /* The cursor */
  214299. sqlite3_context *ctx, /* First argument to sqlite3_result_...() */
  214300. int i /* Which column to return */
  214301. ){
  214302. stmt_cursor *pCur = (stmt_cursor*)cur;
  214303. switch( i ){
  214304. case STMT_COLUMN_SQL: {
  214305. sqlite3_result_text(ctx, sqlite3_sql(pCur->pStmt), -1, SQLITE_TRANSIENT);
  214306. break;
  214307. }
  214308. case STMT_COLUMN_NCOL: {
  214309. sqlite3_result_int(ctx, sqlite3_column_count(pCur->pStmt));
  214310. break;
  214311. }
  214312. case STMT_COLUMN_RO: {
  214313. sqlite3_result_int(ctx, sqlite3_stmt_readonly(pCur->pStmt));
  214314. break;
  214315. }
  214316. case STMT_COLUMN_BUSY: {
  214317. sqlite3_result_int(ctx, sqlite3_stmt_busy(pCur->pStmt));
  214318. break;
  214319. }
  214320. default: {
  214321. assert( i==STMT_COLUMN_MEM );
  214322. i = SQLITE_STMTSTATUS_MEMUSED +
  214323. STMT_COLUMN_NSCAN - SQLITE_STMTSTATUS_FULLSCAN_STEP;
  214324. /* Fall thru */
  214325. }
  214326. case STMT_COLUMN_NSCAN:
  214327. case STMT_COLUMN_NSORT:
  214328. case STMT_COLUMN_NAIDX:
  214329. case STMT_COLUMN_NSTEP:
  214330. case STMT_COLUMN_REPREP:
  214331. case STMT_COLUMN_RUN: {
  214332. sqlite3_result_int(ctx, sqlite3_stmt_status(pCur->pStmt,
  214333. i-STMT_COLUMN_NSCAN+SQLITE_STMTSTATUS_FULLSCAN_STEP, 0));
  214334. break;
  214335. }
  214336. }
  214337. return SQLITE_OK;
  214338. }
  214339. /*
  214340. ** Return the rowid for the current row. In this implementation, the
  214341. ** rowid is the same as the output value.
  214342. */
  214343. static int stmtRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
  214344. stmt_cursor *pCur = (stmt_cursor*)cur;
  214345. *pRowid = pCur->iRowid;
  214346. return SQLITE_OK;
  214347. }
  214348. /*
  214349. ** Return TRUE if the cursor has been moved off of the last
  214350. ** row of output.
  214351. */
  214352. static int stmtEof(sqlite3_vtab_cursor *cur){
  214353. stmt_cursor *pCur = (stmt_cursor*)cur;
  214354. return pCur->pStmt==0;
  214355. }
  214356. /*
  214357. ** This method is called to "rewind" the stmt_cursor object back
  214358. ** to the first row of output. This method is always called at least
  214359. ** once prior to any call to stmtColumn() or stmtRowid() or
  214360. ** stmtEof().
  214361. */
  214362. static int stmtFilter(
  214363. sqlite3_vtab_cursor *pVtabCursor,
  214364. int idxNum, const char *idxStr,
  214365. int argc, sqlite3_value **argv
  214366. ){
  214367. stmt_cursor *pCur = (stmt_cursor *)pVtabCursor;
  214368. pCur->pStmt = 0;
  214369. pCur->iRowid = 0;
  214370. return stmtNext(pVtabCursor);
  214371. }
  214372. /*
  214373. ** SQLite will invoke this method one or more times while planning a query
  214374. ** that uses the stmt virtual table. This routine needs to create
  214375. ** a query plan for each invocation and compute an estimated cost for that
  214376. ** plan.
  214377. */
  214378. static int stmtBestIndex(
  214379. sqlite3_vtab *tab,
  214380. sqlite3_index_info *pIdxInfo
  214381. ){
  214382. pIdxInfo->estimatedCost = (double)500;
  214383. pIdxInfo->estimatedRows = 500;
  214384. return SQLITE_OK;
  214385. }
  214386. /*
  214387. ** This following structure defines all the methods for the
  214388. ** stmt virtual table.
  214389. */
  214390. static sqlite3_module stmtModule = {
  214391. 0, /* iVersion */
  214392. 0, /* xCreate */
  214393. stmtConnect, /* xConnect */
  214394. stmtBestIndex, /* xBestIndex */
  214395. stmtDisconnect, /* xDisconnect */
  214396. 0, /* xDestroy */
  214397. stmtOpen, /* xOpen - open a cursor */
  214398. stmtClose, /* xClose - close a cursor */
  214399. stmtFilter, /* xFilter - configure scan constraints */
  214400. stmtNext, /* xNext - advance a cursor */
  214401. stmtEof, /* xEof - check for end of scan */
  214402. stmtColumn, /* xColumn - read data */
  214403. stmtRowid, /* xRowid - read data */
  214404. 0, /* xUpdate */
  214405. 0, /* xBegin */
  214406. 0, /* xSync */
  214407. 0, /* xCommit */
  214408. 0, /* xRollback */
  214409. 0, /* xFindMethod */
  214410. 0, /* xRename */
  214411. 0, /* xSavepoint */
  214412. 0, /* xRelease */
  214413. 0, /* xRollbackTo */
  214414. 0, /* xShadowName */
  214415. };
  214416. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  214417. SQLITE_PRIVATE int sqlite3StmtVtabInit(sqlite3 *db){
  214418. int rc = SQLITE_OK;
  214419. #ifndef SQLITE_OMIT_VIRTUALTABLE
  214420. rc = sqlite3_create_module(db, "sqlite_stmt", &stmtModule, 0);
  214421. #endif
  214422. return rc;
  214423. }
  214424. #ifndef SQLITE_CORE
  214425. #ifdef _WIN32
  214426. __declspec(dllexport)
  214427. #endif
  214428. SQLITE_API int sqlite3_stmt_init(
  214429. sqlite3 *db,
  214430. char **pzErrMsg,
  214431. const sqlite3_api_routines *pApi
  214432. ){
  214433. int rc = SQLITE_OK;
  214434. SQLITE_EXTENSION_INIT2(pApi);
  214435. #ifndef SQLITE_OMIT_VIRTUALTABLE
  214436. rc = sqlite3StmtVtabInit(db);
  214437. #endif
  214438. return rc;
  214439. }
  214440. #endif /* SQLITE_CORE */
  214441. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_STMTVTAB) */
  214442. /************** End of stmt.c ************************************************/
  214443. #if __LINE__!=229610
  214444. #undef SQLITE_SOURCE_ID
  214445. #define SQLITE_SOURCE_ID "2020-06-04 12:58:43 ec02243ea6ce33b090870ae55ab8aa2534b54d216d45c4aa2fdbb00e8686alt2"
  214446. #endif
  214447. /* Return the source-id for this library */
  214448. SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
  214449. /************************** End of sqlite3.c ******************************/